feat(loop,gateway): 事件批 — tool_execution 三事件 + streamId + turn.start/end(裁决 01.4.1/01.4.2/01.4.3/01.4.5/03.4.4/1.12)
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

执行方案阶段 2 · P2-3(`DevDocs/audit/_plan.md`)。契约 `Docs/api-client.md` → **v0.50**。

- **01.4.1 `tool_execution` 拆三事件**:`model/stream.go` 删旧 `StreamKindToolExecution`,新增
  `tool_execution.start/update/end` + `ToolPhaseRunning/Done/Error`(与 design/19 status 同值);
  `StreamEvent` 增 `Tool`/`Phase`;`loop/tools.go` 的 `emitToolExecution` 重写为结构化字段、
  **Delta 恒空**(断言锁死),`ID` 复用 provider tool call id(可与 `tool_call.*` 关联)。
  ⚠️ **诚实边界**:start/end 有真实生产者;`update` 的 wire 映射已实现并单测锁定,但**工具分发器
  无中途进度上报源 ⇒ loop 暂不产出 update 帧**(已在 api-client §3.1 如实登记)。
- **03.4.4 phase 驱动图节点状态**:`invokeOne` 用**单一 phase 决策**同时决定 end 帧 phase、
  span 的 `phase` prop 与终态;`trace/graph.go` 新增 `FlowStatusForPhase`,`graph_build.go` 的
  `AddSpan` 对 tool 节点**优先消费 phase prop**(缺省回落 span 终态 ⇒ 两路不可能矛盾)。
- **01.4.2 `streamId`**:`StreamEvent` 增 `StreamID`;`loop/stream.go` 每次 ChatStream 生成
  `stream-<hex>`(crypto/rand,降级时间戳),该流所有帧共享、多步工具轮取新 id;`ws_bridge`
  把它并进**模型流帧** `data`(`tool_execution.*`/`turn.*` 不带)。语义区分:`turnId` = 哪轮回答,
  `streamId` = 这条流式消息。
- **01.4.3 `turn.start`/`turn.end`**:`loop/run.go` 入口发 start、defer 发 end,**覆盖全部出口**
  (最终答案/安全网终止/预算耗尽/步骤错误);帧**无 data 载荷**;静音的内部 run(backthink/子代理)
  不发。顺带把 91 行的 `Run` 拆成 `driveTurn` + `settleAndReturn`(清掉一处既有 >80 行违规)。
- **01.4.5**:仅 `Docs/api-client.md` §3.5 补 `graph_update` 三范围(`web`/`web:<uuid>`/`sess-backthink`),
  与 `wire_runtime.go` 的 allow 谓词一致,**零代码变更**。

验证:`go build ./...` 绿;本批四包(loop/model/trace/gateway)vet + 测试绿(含 `-count=1`);
linux/amd64 + darwin/arm64 交叉编译绿;本批 16 文件 ≤500 行、函数 ≤80 行。
**真 WS 帧断言 8 条**:帧序 `turn.start → message.delta → tool_execution.start →
tool_execution.end → message.delta → turn.end`(+`stream_end`)、turn 边界无载荷且整轮 turnId 一致、
两条模型流 `streamId` 互异、tool 帧 `{tool,phase,id}` 且无 `delta`/`streamId` 键、
`turn.end` 在步骤出错时也发出、内部静音 run 不发边界帧。
**变异验证**:把 `ev.StreamID = streamID` 改为赋空 → 两条断言 FAIL(`streamId` 为空/两流同空),
还原后复绿(直接删行会先被编译期 `declared and not used` 拦截)。

未验证:前端未消费这些帧(本轮未动 `frontend/**`,「前端能渲染」待前端批);无真实模型端到端。
This commit is contained in:
AskaEth committed 2026-10-04 11:26:35 +08:00
1 parent afef75f640
commit 6e7ec56f9a
16 files changed
+982 -126

No files matched your search

+94 -69
View File
@@ -114,42 +114,8 @@ func (l *Loop) runToolCalls(ctx context.Context, messages []model.Message, calls
res.terminate = true
}
// 安全门(design/11 §3):群聊/陌生人会话只能调用
// 其可编辑标记允许该环境的工具(默认关闭)。不被允许的
// 调用绝不执行;它以 not_allowed 软结果回灌
// 并记录到审计 sink。它是该批的最终权威 ——
// 后续的审计钩子可以收紧,但绝不重新放行被拒的工具。
if d != nil {
l.applyToolSecurityGate(ctx, d, calls, actions)
}
// BatchAdmit 钩子(审计 / 政治审查):拦截整批。
if l.hooks.BatchAdmit != nil {
if ok, reason := l.hooks.BatchAdmit(ctx, calls); !ok {
if reason == "" {
reason = "tool batch blocked by policy"
}
for i := range calls {
actions[i] = toolCallAction{run: false, reason: reason}
}
}
}
// CallAdmit 钩子:对我们打算运行的调用逐个否决。
if l.hooks.CallAdmit != nil {
for i := range calls {
if !actions[i].run {
continue
}
if veto := l.hooks.CallAdmit(ctx, calls[i]); veto != nil && veto.Block {
reason := veto.Reason
if reason == "" {
reason = "tool call blocked by policy"
}
actions[i] = toolCallAction{run: false, reason: reason}
}
}
}
// 执行前的三道门(安全门 + 批次/逐调用钩子)见 applyToolAdmissions。
l.applyToolAdmissions(ctx, d, calls, actions)
// 决定串行还是并行:显式串行模式,或任一调用的工具
// 被声明为串行(单个串行标记即让整组
@@ -187,26 +153,8 @@ func (l *Loop) runToolCalls(ctx context.Context, messages []model.Message, calls
res.executed += len(idxs)
}
// AfterCall 钩子(仅对实际执行过的调用)。
if l.hooks.AfterCall != nil {
for i := range calls {
if outcomes[i].Skipped {
continue
}
if after := l.hooks.AfterCall(ctx, calls[i], outcomes[i]); after != nil {
outcomes[i] = *after
}
}
}
// AfterOutcome 钩子(对每个最终结果运行,无论是否跳过)。
if l.hooks.AfterOutcome != nil {
for i := range calls {
if after := l.hooks.AfterOutcome(ctx, calls[i], outcomes[i]); after != nil {
outcomes[i] = *after
}
}
}
// 结果落定后的两类观察/改写钩子见 applyToolOutcomeHooks。
l.applyToolOutcomeHooks(ctx, calls, outcomes)
// 钩子可以把每个调用都标记为 terminate 来要求终止本轮
// (OpenClaw 的 shouldTerminateToolBatch)。
@@ -277,48 +225,125 @@ func classifyToolBatch(st *toolLoopState, calls []agent.ToolCall) ([]toolCallAct
return actions, terminate
}
// applyToolAdmissions 对一批调用应用执行前的三道门,把不放行的
// 调用改写为携带原因的跳过决策:① 安全门(design/11 §3)——
// 群聊/陌生人会话只能调用其标记允许该环境的工具(默认关闭),
// 不被允许的调用绝不执行,以 not_allowed 软结果回灌并记录审计;
// 它是该批的最终权威,后续钩子可以收紧但绝不重新放行。②
// BatchAdmit 批次钩子(审计 / 政治审查)拦截整批。③ CallAdmit
// 逐调用否决。dispatcher 缺席时安全门跳过(runToolCalls 已保证
// 此时整批以错误回灌)。
func (l *Loop) applyToolAdmissions(ctx context.Context, d *tool.Dispatcher, calls []agent.ToolCall, actions []toolCallAction) {
if d != nil {
l.applyToolSecurityGate(ctx, d, calls, actions)
}
if l.hooks.BatchAdmit != nil {
if ok, reason := l.hooks.BatchAdmit(ctx, calls); !ok {
if reason == "" {
reason = "tool batch blocked by policy"
}
for i := range calls {
actions[i] = toolCallAction{run: false, reason: reason}
}
}
}
if l.hooks.CallAdmit != nil {
for i := range calls {
if !actions[i].run {
continue
}
if veto := l.hooks.CallAdmit(ctx, calls[i]); veto != nil && veto.Block {
reason := veto.Reason
if reason == "" {
reason = "tool call blocked by policy"
}
actions[i] = toolCallAction{run: false, reason: reason}
}
}
}
}
// applyToolOutcomeHooks 运行结果落定后的两类观察/改写钩子,
// 就地改写 outcomes:AfterCall 仅对实际执行过的调用(在
// AfterOutcome 之前),AfterOutcome 对每个最终结果(无论是否
// 跳过),都在结果回灌给模型之前运行。
func (l *Loop) applyToolOutcomeHooks(ctx context.Context, calls []agent.ToolCall, outcomes []ToolOutcome) {
if l.hooks.AfterCall != nil {
for i := range calls {
if outcomes[i].Skipped {
continue
}
if after := l.hooks.AfterCall(ctx, calls[i], outcomes[i]); after != nil {
outcomes[i] = *after
}
}
}
if l.hooks.AfterOutcome != nil {
for i := range calls {
if after := l.hooks.AfterOutcome(ctx, calls[i], outcomes[i]); after != nil {
outcomes[i] = *after
}
}
}
}
// invokeOne 在其每工具截止时间下执行单个工具调用,发出一个
// tool span、流式输出 tool_execution_update 进度并归一化
// 结果。
// tool span、以 tool_execution.start/end 事件流式输出执行进度
// 并归一化结果。执行全程由单一 phase 决策驱动:start 帧带
// running,Invoke 返回后按成败取 done/error,同一取值既决定
// end 帧的 phase,也决定 span 终态(design/19 的 tool 节点
// running/done/error 状态即由此驱动)。
func (l *Loop) invokeOne(ctx context.Context, d *tool.Dispatcher, tc agent.ToolCall) ToolOutcome {
if d == nil {
return ToolOutcome{Err: fmt.Errorf("no tool dispatcher configured for %q", tc.Name), ErrKind: tool.KindExecution}
}
l.emitToolExecution(ctx, tc.Name, "start")
_, toolSpan := l.span(ctx, "tool."+tc.Name, trace.SpanKindTool)
l.emitToolExecution(ctx, tc, model.StreamKindToolExecutionStart, model.ToolPhaseRunning)
result, err := d.Invoke(ctx, tc.Name, tc.Args)
phase := "end"
phase := model.ToolPhaseDone
if err != nil {
phase = "end:error"
phase = model.ToolPhaseError
}
l.emitToolExecution(ctx, tc.Name, phase)
l.emitToolExecution(ctx, tc, model.StreamKindToolExecutionEnd, phase)
out := ToolOutcome{Result: result, Err: err, ErrKind: errorKind(err)}
l.spanProp(toolSpan, "phase", phase)
l.recordToolDone(toolSpan, tc, out)
if err != nil {
l.spanProp(toolSpan, "error", err.Error())
l.spanProp(toolSpan, "error_kind", out.ErrKind)
l.finishSpan(toolSpan, trace.SpanStatusError)
} else {
l.spanProp(toolSpan, "result", result)
l.finishSpan(toolSpan, trace.SpanStatusOK)
}
l.finishSpan(toolSpan, spanStatusForToolPhase(phase))
return out
}
// emitToolExecution 在循环处于流式路径(配置了 OnStream)时把
// tool_execution_update 进度事件转发给前端;否则为空操作
// (被静音的内部流程也会跳过它)。phase 是一个短标签,
// 如 "start" 或 "end:error"。
func (l *Loop) emitToolExecution(ctx context.Context, name, phase string) {
// tool_execution 三事件(start / update / end)转发给前端;否则为
// 空操作(被静音的内部流程也会跳过它)。phase 是结构化字段
// (running/done/error),绝不塞进 Delta;工具名走 Tool 字段,
// ID 复用 provider 的 tool call id,使执行帧能与其 tool_call.* 帧
// 关联。
func (l *Loop) emitToolExecution(ctx context.Context, tc agent.ToolCall, kind model.StreamKind, phase string) {
if l.onStream == nil || isMutedBroadcast(ctx) {
return
}
ev := model.StreamEvent{Kind: model.StreamKindToolExecution, Delta: phase + ":" + name}
ev := model.StreamEvent{Kind: kind, Phase: phase, Tool: tc.Name, ID: tc.ID}
ev.SessionID = loopSession(ctx)
ev.TurnID = loopTurn(ctx)
l.onStream(ev)
}
// spanStatusForToolPhase 把工具执行的终态 phase 映射为 span 终态,
// 使 trace/流程图与 WS 帧从同一个 phase 取值得出一致结论。
// 非终态 phase(running)不会走到这里 —— span 只在执行结束时收尾。
func spanStatusForToolPhase(phase string) trace.SpanStatus {
if phase == model.ToolPhaseError {
return trace.SpanStatusError
}
return trace.SpanStatusOK
}
// invokeParallel 并发运行 idxs 处的调用,上限为循环的
// 并行度,并把每个结果写回 out 的对应调用索引处,使调用方
// 能按原始顺序渲染结果。信号量限制并发,在途