From a36e91d0dc323a858cdcf919b34b079d4368bf3d Mon Sep 17 00:00:00 2001 From: huanghaosheng <386998068@qq.com> Date: Mon, 2 Nov 2026 12:08:18 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E9=98=B6=E6=AE=B5=E8=AE=A1=E5=88=92?= =?UTF-8?q?=E4=B9=A6=E6=8B=86=E5=88=86=E5=88=B0=20docs/upgrade-plan=20?= =?UTF-8?q?=E5=B9=B6=E5=90=88=E5=B9=B6=E7=BC=BA=E9=99=B7=E5=8F=B0=E8=B4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 方案第 4 章 P0-P8 拆为 9 份独立阶段计划书,原文件只保留索引与横切章节 - 《项目完善报告》《评审与收编清单》内容拆入各阶段计划书后删除 - 统一缺陷台账 F-01…F-76(历史 71 条 + 方案补充 5 条),保留历史编号对照 - 新增 README 作为路线图索引:阶段清单、执行顺序、第 0 天清扫、台账、迭代约定 --- docs/agent-platform-upgrade-plan.md | 2988 +------------------------- docs/upgrade-plan/P0-运行时内核.md | 572 +++++ docs/upgrade-plan/P1-工具网关.md | 682 ++++++ docs/upgrade-plan/P2-会话持久化.md | 446 ++++ docs/upgrade-plan/P3-记忆与知识.md | 407 ++++ docs/upgrade-plan/P4-上下文工程.md | 271 +++ docs/upgrade-plan/P5-工作流编排.md | 407 ++++ docs/upgrade-plan/P6-工具治理.md | 365 ++++ docs/upgrade-plan/P7-可观测与评测.md | 357 +++ docs/upgrade-plan/P8-生产化.md | 655 ++++++ docs/upgrade-plan/README.md | 169 ++ docs/完善报告-评审与收编清单.md | 265 --- docs/项目完善报告.md | 1262 ----------- 13 files changed, 4373 insertions(+), 4473 deletions(-) create mode 100644 docs/upgrade-plan/P0-运行时内核.md create mode 100644 docs/upgrade-plan/P1-工具网关.md create mode 100644 docs/upgrade-plan/P2-会话持久化.md create mode 100644 docs/upgrade-plan/P3-记忆与知识.md create mode 100644 docs/upgrade-plan/P4-上下文工程.md create mode 100644 docs/upgrade-plan/P5-工作流编排.md create mode 100644 docs/upgrade-plan/P6-工具治理.md create mode 100644 docs/upgrade-plan/P7-可观测与评测.md create mode 100644 docs/upgrade-plan/P8-生产化.md create mode 100644 docs/upgrade-plan/README.md delete mode 100644 docs/完善报告-评审与收编清单.md delete mode 100644 docs/项目完善报告.md diff --git a/docs/agent-platform-upgrade-plan.md b/docs/agent-platform-upgrade-plan.md index c362478..32ab9dc 100644 --- a/docs/agent-platform-upgrade-plan.md +++ b/docs/agent-platform-upgrade-plan.md @@ -89,32 +89,31 @@ P0 运行时内核 ──► P1 工具网关 ──► P2 会话持久化 ── ### 1.3 关键缺陷证据(按阶段归属) -编号 `D-xx` 在后续阶段中直接引用,避免重复描述。 +编号 `F-xx` 是全局缺陷台账(见 [`upgrade-plan/README.md`](upgrade-plan/README.md)),在后续阶段中直接引用,避免重复描述。 -| ID | 现象 | 证据(file:line) | 影响 | 归属 | +| ID | 现象 | 证据(标识符 · 文件) | 影响 | 归属 | |---|---|---|---|---| -| D-01 | 每轮对话只构造 `system + user` 两条消息,无历史 | `initialMessages` in `internal/infrastructure/adk/adapter.go` | 多轮对话第二十轮丢失首轮信息 | P4 | -| D-02 | `Runner.Run/Stream` 用 `context.Background()` | `(*Runner).Run`、`(*Runner).Stream`、`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | HTTP 取消/超时传不到 Agent;客户端断开仍烧 token | P0 | -| D-03 | 任一工具失败即整轮失败 | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 一个下游 5xx 让整个 run 失败 | P1 | -| D-04 | 所有工具参数硬编码为单个 `query: string` | `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 模型无法正确填参;无法做参数校验 | P1 | -| D-05 | `ListTools` 只取 `name`,丢弃 description/inputSchema | `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | 与 D-04 叠加,工具描述与 schema 双双缺失 | P1 | -| D-06 | `callRPC` 在 `postURL==""` 时直接 return,未删 `pending[id]` | `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | 内存泄漏 | P1 | -| D-07 | `MCPToolRouter` 无锁,多 goroutine 并发注册/调用 | `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | data race | P1 | -| D-08 | `maxToolCallIterations = 4` 常量 | `maxToolCallIterations` in `internal/infrastructure/adk/adapter.go` | 无法按 Agent 配置;复杂任务早退 | P0 | -| D-09 | `max-iterations` 配置被解析但从未使用 | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 配置项形同虚设 | P5 | -| D-10 | parallel 与 loop 都退化为串行 fan-out | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 并行分支耗时 = 串行之和 | P5 | -| D-11 | `CreateSession` 先 `Get` 再 `Set`,无锁无唯一约束 | `(*Service).CreateSession` in `internal/domain/agent/service/chat/service.go` | 并发创建出多个会话 | P2 | -| D-12 | `resolveRunnerSession` 直接用请求里的 `sessionID` | `(*Service).resolveRunnerSession` in `internal/domain/agent/service/chat/service.go` | 任意用户可读写他人会话(越权) | P2 | -| D-13 | `SessionStore` 只存 ID,`ChatMessage` 从不落库 | `SessionStore` in `internal/domain/agent/ports/ports.go` | 重启即失忆;无法回溯 | P2/P3 | -| D-14 | `Runner.CreateSession` 用全局原子计数拼 ID | `(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go` | 跨 Agent 可能撞 ID;无租户维度 | P2 | -| D-15 | Armory 遍历 map 装配 | `armory/service.go` | 启动顺序不确定,问题难复现 | P0 | -| D-16 | 工具无超时,仅靠 HTTP 客户端整体超时 | `ai/mcp_sse_client.go` `RequestTimeout` 默认 300s | 单工具挂起拖死整个 run | P1 | -| D-17 | 无 run_id / trace_id,日志无法关联一次执行 | `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 线上问题无法定位 | P7 | -| D-18 | `writeError(c, nil)` | `writeError` in `internal/trigger/http/agent_handler.go` | nil 解引用 panic | P8 | -| D-19 | CORS 反射任意 Origin 且允许凭证 | `corsMiddleware` in `internal/app/bootstrap/bootstrap.go` | 跨站请求伪造面 | P8 | -| D-20 | 无优雅停机,`engine.Run()` 直接 `Router.Run(addr)` | `(*Engine).Run` in `internal/app/bootstrap/bootstrap.go` | 发布丢请求、MCP 连接不复位 | P8 | +| F-24 | 每轮对话只构造 `system + user` 两条消息,无历史;`SessionStore` 只存 ID,`ChatMessage` 从不落库 | `initialMessages` in `internal/infrastructure/adk/adapter.go`;`SessionStore` in `internal/domain/agent/ports/ports.go` | 多轮对话第二十轮丢失首轮信息;重启即失忆;无法回溯 | P4;P2/P3 | +| F-02 | `Runner.Run/Stream` 用 `context.Background()` | `(*Runner).Run`、`(*Runner).Stream`、`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | HTTP 取消/超时传不到 Agent;客户端断开仍烧 token | P0 | +| F-21 | 任一工具失败即整轮失败 | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 一个下游 5xx 让整个 run 失败 | P1 | +| F-15 | 所有工具参数硬编码为单个 `query: string` | `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 模型无法正确填参;无法做参数校验 | P1 | +| F-10 | `ListTools` 只取 `name`,丢弃 description/inputSchema | `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | 与 F-15 叠加,工具描述与 schema 双双缺失 | P1 | +| F-11 | `callRPC` 在 `postURL==""` 时直接 return,未删 `pending[id]` | `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | 内存泄漏 | P1 | +| F-16 | `MCPToolRouter` 无锁,多 goroutine 并发注册/调用 | `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | data race | P1 | +| F-09 | `maxToolCallIterations = 4` 常量 | `maxToolCallIterations` in `internal/infrastructure/adk/adapter.go` | 无法按 Agent 配置;复杂任务早退 | P0 | +| F-34 | `max-iterations` 配置被解析但从未使用 | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 配置项形同虚设 | P5 | +| F-35 | parallel 与 loop 都退化为串行 fan-out | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 并行分支耗时 = 串行之和 | P5 | +| F-25 | `CreateSession` 先 `Get` 再 `Set`,无锁无唯一约束 | `(*Service).CreateSession` in `internal/domain/agent/service/chat/service.go` | 并发创建出多个会话 | P2 | +| F-23 | `resolveRunnerSession` 直接用请求里的 `sessionID` | `(*Service).resolveRunnerSession` in `internal/domain/agent/service/chat/service.go` | 任意用户可读写他人会话(越权) | P2 | +| F-31 | `Runner.CreateSession` 用全局原子计数拼 ID | `(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go` | 跨 Agent 可能撞 ID;无租户维度 | P2 | +| F-04 | Armory 遍历 map 装配 | `armory/service.go` | 启动顺序不确定,问题难复现 | P0 | +| F-22 | 工具无超时,仅靠 HTTP 客户端整体超时 | `ai/mcp_sse_client.go` `RequestTimeout` 默认 300s | 单工具挂起拖死整个 run | P1 | +| F-41 | 无 run_id / trace_id,日志无法关联一次执行 | `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 线上问题无法定位 | P7 | +| F-44 | `writeError(c, nil)` | `writeError` in `internal/trigger/http/agent_handler.go` | nil 解引用 panic | P8 | +| F-42 | CORS 反射任意 Origin 且允许凭证 | `corsMiddleware` in `internal/app/bootstrap/bootstrap.go` | 跨站请求伪造面 | P8 | +| F-45 | 无优雅停机,`engine.Run()` 直接 `Router.Run(addr)` | `(*Engine).Run` in `internal/app/bootstrap/bootstrap.go` | 发布丢请求、MCP 连接不复位 | P8 | -> 完整审计见 `docs/项目完善报告.md`(P0-1..P3-23,带 file:line),本表只保留与升级路线强相关的 20 条。 +> 本表只保留与升级路线强相关、有明确代码证据的条目;完整台账(76 条,含历史审计 71 条与本方案新增 5 条)见 [`upgrade-plan/README.md`](upgrade-plan/README.md)。 ### 1.4 可复用资产(不要重复造) @@ -253,2871 +252,25 @@ cmd/migrate/ # ★新增:迁移执行 --- -# 4. 阶段详设 - -## 4.1 P0 · 运行时内核:让每一次执行都成为一等公民 - -### 目标 - -把"一次函数调用"升级为"一个有状态、有预算、可观测、可中断、可重放的 Run"。这是后面所有能力的地基:没有 Step 就没有节点级重试(P5),没有事件就没有回放(P7),没有 ctx 就没有流式取消。 - -### 当前问题 - -| 证据 | 问题 | -|---|---| -| `(*Runner).Run`、`(*Runner).Stream`、`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 三处 `context.Background()`,请求取消传不进去(D-02) | -| `maxToolCallIterations` in `internal/infrastructure/adk/adapter.go` | `maxToolCallIterations = 4` 硬编码(D-08) | -| `adk/adapter.go` 全文 572 行 | 定义/执行/流程/插件混在一个文件,无法单测 | -| `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 插件输出走 `fmt.Printf`,无 run 上下文(D-17) | -| `armory/service.go` | map 遍历装配,顺序随机(D-15) | -| `SessionStore` in `internal/domain/agent/ports/ports.go` | `SessionStore` 无 ctx,存储层无法超时/取消 | - -### 设计 - -#### 4.1.1 新增领域包 `internal/domain/runtime` - -```go -package runtime - -type RunID string -type StepID string - -type RunStatus string - -const ( - RunPending RunStatus = "pending" - RunRunning RunStatus = "running" - RunWaitingApproval RunStatus = "waiting_approval" - RunWaitingHuman RunStatus = "waiting_human" - RunSucceeded RunStatus = "succeeded" - RunFailed RunStatus = "failed" - RunCanceled RunStatus = "canceled" - RunExhausted RunStatus = "exhausted" // 预算耗尽,非错误 -) - -// Run 是一次执行的聚合根。 -type Run struct { - ID RunID - TenantID string - UserID string - AgentID string - SessionID string - TurnID string - Status RunStatus - Budget Budget - Usage Usage - Labels map[string]string // 业务透传,如 trace_id、实验分组 - StartedAt time.Time - EndedAt *time.Time - Failure *Failure -} - -// Budget 只减不增;任何 Executor 不得自行放大。 -type Budget struct { - MaxSteps int // 默认 24 - MaxToolCalls int // 默认 16 - MaxTokens int // prompt+completion 合计,默认 200_000 - MaxWallClock time.Duration // 默认 3m -} - -type Usage struct { - Steps, ToolCalls int - PromptTokens, CompletionTokens int -} - -func (u *Usage) Total() int { return u.PromptTokens + u.CompletionTokens } -``` - -```go -type StepKind string - -const ( - StepLLM StepKind = "llm" - StepTool StepKind = "tool" - StepAgent StepKind = "agent" - StepWorkflow StepKind = "workflow" - StepApproval StepKind = "approval" - StepCompaction StepKind = "compaction" -) - -type Step struct { - ID StepID - RunID RunID - Index int - Kind StepKind - Name string // 工具名 / Agent 名 / 节点 ID - Status StepStatus - Input json.RawMessage // 脱敏后 - Output json.RawMessage - Usage Usage - Attempt int - Failure *Failure - StartedAt time.Time - EndedAt *time.Time -} -``` - -```go -// Event 追加写、不可变。P0 落 JSONL,P2 落库,P7 接 OTel。 -type Event struct { - RunID RunID - Seq int64 - At time.Time - Type EventType - StepID StepID - Payload json.RawMessage -} - -type EventType string - -const ( - EvRunStarted EventType = "run.started" - EvRunFinished EventType = "run.finished" - EvRunCanceled EventType = "run.canceled" - EvRunExhausted EventType = "run.exhausted" - EvStepStarted EventType = "step.started" - EvStepFinished EventType = "step.finished" - EvLLMDelta EventType = "llm.delta" - EvLLMUsage EventType = "llm.usage" - EvToolRequested EventType = "tool.requested" - EvToolResult EventType = "tool.result" - EvToolRetry EventType = "tool.retry" - EvToolDegraded EventType = "tool.degraded" - EvApprovalRequired EventType = "approval.required" - EvMemoryAssembled EventType = "memory.assembled" - EvMemoryCompacted EventType = "memory.compacted" -) -``` - -#### 4.1.2 执行器插件化(替换 `runWithVars` 的 switch) - -现在的分派逻辑: - -```go -// 现状:(*Agent).runWithVars in internal/infrastructure/adk/adapter.go -func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { - switch a.kind { - case "llm": return a.runLLM(ctx, content, vars) - case "sequential": return a.runSequential(ctx, content, vars) - case "loop", "parallel": return a.runFanOut(ctx, content, vars) - default: return "", fmt.Errorf("agent %q has unknown kind %q", a.name, a.kind) - } -} -``` - -改为: - -```go -// internal/domain/runtime/executor.go -type Kind string - -type Input struct { - UserMessage string - Vars map[string]string - Attachments []Attachment -} - -type Output struct { - Text string - Vars map[string]string - Payload json.RawMessage // 结构化输出(P5 图执行用) -} - -type Executor interface { - Kind() Kind - Execute(rc *Context, in Input) (Output, error) -} - -type Registry struct { - mu sync.RWMutex - m map[Kind]Executor -} - -func (r *Registry) Register(e Executor) error // 重复注册返回错误 -func (r *Registry) Get(k Kind) (Executor, bool) -``` - -`Context` 是把 Run/Step/预算/事件/工具/记忆一次性注入的**唯一入口**(类似 `*gin.Context`): - -```go -// internal/domain/runtime/context.go -type Context struct { - ctx context.Context // 私有,禁止外部取出 Background - - Run *Run - Budget *Budget - Scope *Scope // {key} 变量作用域,goroutine 安全 - Events EventSink - Tools tool.Gateway - Memory memory.Retriever // P3 的检索端口:事实/摘要/知识库统一召回 - Clock clock.Clock // 测试注入 -} - -// Step 开启一个 Step,返回结束回调;正常/panic 都会关闭 Step。 -// 这是全项目唯一允许创建 Step 的入口,保证 index 单调与成对。 -func (c *Context) Step(kind StepKind, name string) (*StepHandle, error) - -func (h *StepHandle) Finish(out Output, err error) error - -// Scope 是 {key} 变量作用域;并行分支各持一份副本,join 时显式合并。 -type Scope struct { - mu sync.RWMutex - vars map[string]string -} - -func (s *Scope) Get(k string) (string, bool) -func (s *Scope) Set(k, v string) -func (s *Scope) Snapshot() map[string]string -func (s *Scope) Merge(branch *Scope) // 并行分支回填,冲突以显式规则处理 - -``` - -用法(`executor_llm.go`): - -```go -step, err := rc.Step(runtime.StepLLM, agentName) -if err != nil { return Output{}, err } -defer step.Finish(...) - -reply, err := model.Generate(rc.Context(), msgs, tools) -``` - -**收益**:Step 序号、耗时、token 记账、事件发射、错误归类五件事全部收敛到一处,Executor 只需实现业务逻辑。 - -#### 4.1.3 终止保证(回答"死循环会不会烧 token") - -四道闸门,任一触发即终止,且**终止不是异常**: - -| 闸门 | 触发条件 | 终止动作 | 状态 | -|---|---|---|---| -| 墙钟 | `ctx.Deadline` 到期(`runtime.budget.max-wall-clock`) | 取消 ctx | `run.canceled` | -| 步数 | `Usage.Steps >= MaxSteps` | 拒绝下一个 `Step()` | `run.exhausted` | -| 工具次数 | `Usage.ToolCalls >= MaxToolCalls` | 后续工具调用直接返回"预算耗尽" | `run.exhausted` | -| Token | `Usage.Total() >= MaxTokens` | 在 LLM 调用前检查,拒绝新调用 | `run.exhausted` | - -关键实现细节(面试可讲): - -- **检查点放在 LLM 调用之前而不是之后**:token 是"调用后才知道"的,所以用「上一轮实际用量 + 本轮 prompt 估算」做预测,超限则先压缩上下文(P4)而不是直接失败。 -- **预算检查必须是原子的**:`Budget` 用 `atomic.Int64` 或 `Context` 内锁,避免并发分支各自判断都通过。 -- **`run.exhausted` 仍要落最终 assistant 消息**,内容为"已达执行上限,以下是已完成部分:……",让用户拿到部分结果而不是空白。 - -#### 4.1.4 事件日志与重放 - -P0 落 **JSONL**(每行一个事件,按 `run_id` 分文件),零依赖、可 `tail -f`、可直接喂给 P7: - -``` -data/events/2026-10-30/01J9...jsonl -{"run_id":"01J9...","seq":1,"type":"run.started","payload":{"agent":"testAgent03","session":"..."}} -{"run_id":"01J9...","seq":2,"type":"step.started","payload":{"kind":"llm","name":"onlyAgent"}} -``` - -`cmd/replay/main.go` 的 P0 能力(P7 增强): - -```bash -go run ./cmd/replay -run 01J9... -format timeline -# 输出: -# 000ms run.started agent=testAgent03 -# 012ms step.started llm:onlyAgent -# 480ms step.finished llm:onlyAgent tokens=1204/86 -# 481ms step.started tool:baidu_search -# 1203ms tool.retry attempt=2 backoff=400ms reason=timeout -# 1650ms step.finished tool:baidu_search ok -... -``` - -#### 4.1.5 拆分 572 行巨石(机械搬迁,不改语义) - -| 原 `adk/adapter.go` 的组成 | 新文件 | 说明 | -|---|---|---| -| Agent 定义与构造(`Agent`、`Factory`) | `adk/agent.go`、`adk/factory.go` | 只留数据结构与构建 | -| `runWithVars` / `runLLM` | `adk/executor_llm.go` | 改为实现 `runtime.Executor` | -| `streamLLM` | `adk/executor_llm_stream.go` | 同上,流式变体 | -| `executeToolCalls` | `adk/tool_loop.go` | P1 在此挂网关 | -| `runSequential` / `runFanOut` | `adk/executor_workflow.go` | P5 整体替换为图执行 | -| `applyVars` / `initialMessages` | `adk/prompt.go` | P4 用装配器替换 `initialMessages` | -| `Runner` 与插件(`myTestPlugin`、`myLogPlugin`) | `adk/runner.go`、`adk/plugin.go` | 插件改用 zap + run 上下文 | - -目标:`adapter.go` 保留为**兼容壳 < 80 行**(构造 Executor 注册表、把旧 `Runner` 接口适配到新 Runtime),P2 后再删除。 - -#### 4.1.6 接口演进(破坏性,阶段内闭环) - -```go -// 旧:internal/domain/agent/model/command.go -type Runner interface { - CreateSession(userID string) (string, error) - Run(userID, sessionID string, content ChatContent) ([]string, error) - Stream(userID, sessionID string, content ChatContent) (<-chan string, <-chan error) -} - -// 新:internal/domain/runtime/ports.go -type Session struct { ID, TenantID, UserID, AgentID string } - -type SubmitRequest struct { - TenantID string - UserID string - AgentID string - SessionID string // 空则自动创建(幂等,P2 保证) - Content model.ChatContent - IdempotencyKey string -} - -type SubmitResult struct { - RunID string - SessionID string - Output string -} - -type Runner interface { - Submit(ctx context.Context, req SubmitRequest) (SubmitResult, error) - Stream(ctx context.Context, req SubmitRequest) (<-chan runtime.Event, error) - GetRun(ctx context.Context, runID string) (*runtime.Run, error) - Cancel(ctx context.Context, runID string) error -} -``` - -`chat.Service` 与 `trigger/http` 在**同一阶段**改为调用新接口,旧 `Run/Stream` 方法保留为 `// Deprecated` 适配层一个版本。 - -#### 4.1.7 确定性装配 - -`armory/service.go` 的 `AcceptArmoryAgents` 改为: - -```go -func (s *Service) AcceptArmoryAgents(ctx context.Context, tables map[string]model.AiAgentConfigTable) error { - names := make([]string, 0, len(tables)) - for name := range tables { names = append(names, name) } // 入参是 map[string]table - sort.Strings(names) // 确定性:map 遍历顺序随机 - for _, name := range names { - _, err := s.handler.Apply(ctx, model.ArmoryCommand{Table: tables[name]}, NewDynamicContext()) - if err != nil { return fmt.Errorf("apply agent table %q: %w", name, err) } - } - return nil -} -``` - -并对工作流按 `(type, name)` 排序,保证同一份配置每次装配出的链完全一致。 - -### 涉及的代码模块 - -| 类型 | 文件 | 改动要点 | -|---|---|---| -| 新增 | `internal/domain/runtime/run.go` | Run/Step/Status/Usage | -| 新增 | `internal/domain/runtime/budget.go` | 预算与原子扣减 | -| 新增 | `internal/domain/runtime/event.go` | Event/EventType/EventSink | -| 新增 | `internal/domain/runtime/executor.go` | Executor/Registry/Input/Output | -| 新增 | `internal/domain/runtime/context.go` | Context/Scope/StepHandle | -| 新增 | `internal/domain/runtime/errors.go` | Failure/ErrorClass(P1 复用) | -| 新增 | `internal/domain/runtime/ids.go` | ULID 生成 | -| 新增 | `internal/domain/runtime/ports.go` | 新 Runner 接口 | -| 新增 | `internal/infrastructure/obs/eventstore_jsonl.go` | JSONL 追加写 + 按日分片 | -| 新增 | `cmd/replay/main.go` | timeline 重放 | -| 修改 | `internal/infrastructure/adk/adapter.go` | 拆分为 7 个文件(见 4.1.5) | -| 修改 | `internal/domain/agent/model/command.go` | Runner 接口替换 + Deprecated 适配 | -| 修改 | `internal/domain/agent/service/chat/service.go` | 适配新 Runner,透传 ctx | -| 修改 | `internal/trigger/http/agent_handler.go` | 改用新 Runner,修复 `writeError(c,nil)` | -| 修改 | `internal/domain/agent/service/armory/service.go` | 确定性排序 | -| 修改 | `internal/app/bootstrap/bootstrap.go` | 注册 Executor、构造 Runtime、注入 EventStore | -| 修改 | `internal/domain/agent/model/config.go` | 新增 `RuntimeConfig`(budget/events) | -| 修改 | `internal/app/config/application.go` | 解析 `runtime:` 段 | -| 修改 | `cmd/server/main.go` | 传入可取消的 root ctx | - -### 配置变更(全部可选,有默认值) - -```yaml -runtime: - enabled: true - budget: - max-steps: 24 - max-tool-calls: 16 - max-tokens: 200000 - max-wall-clock: 3m - events: - enabled: true - dir: ./data/events - retention-days: 14 - include-llm-deltas: false # 生产默认关闭,避免日志膨胀 -``` - -### 验收标准 - -1. `go build ./...` 通过;`adk/adapter.go` ≤ 80 行且仅含兼容代码。 -2. 新增 `internal/domain/runtime/*_test.go` ≥ 12 用例,覆盖:预算耗尽、ctx 取消、Step 嵌套、事件顺序、并发分支预算正确。 -3. 同一输入运行两次,事件序列(剔除时间戳/ID)**完全一致**(确定性)。 -4. 客户端断开 SSE 后 **≤ 300ms** 服务端取消,事件中出现 `run.canceled`,且不再发起新的工具调用。 -5. `/api/v1/chat` 对两个样例 Agent 的输出与改造前**逐字节一致**(golden test)。 -6. 启动日志显示 Agent 装配顺序与配置书写顺序无关(按名称排序)。 -7. `go run ./cmd/replay -run ` 能还原出完整 Step 时间线。 - -### 测试策略 - -- **表驱动单测**:fake `ChatModel`(返回预设 reply/tool_calls)+ fake `ToolRouter`,断言 Step 与 Usage。 -- **并发测试**:`go test -race` 跑 100 个并发 Run,验证预算原子性。 -- **契约测试**:录制改造前的 `/chat` 响应为 golden JSON,改造后 diff。 -- **取消测试**:`context.WithTimeout(50ms)` 触发,断言错误链为 `context.DeadlineExceeded` 且 Run 状态正确。 - -### 风险与回滚 - -| 风险 | 缓解 | -|---|---| -| 接口破坏导致前端 500 | 兼容壳保留旧 `Runner` 实现一个版本;`runtime.enabled=false` 回退 | -| 预算过紧导致正常任务被截断 | 默认值按现有 draw-io 流程实测得出(~7 步),留 3 倍余量;支持 per-agent 覆盖 | -| 事件日志写盘拖慢主链路 | 异步 channel + 批量 flush(100 条/50ms),队列满则丢弃 `llm.delta` 类低价值事件并计数 | - ---- - -## 4.2 P1 · 工具网关:把"能调通"变成"调不坏" - -### 目标 - -工具调用从"一次 try-call,失败即整轮失败"升级为**带 schema 校验、超时、指数退避、熔断、分级降级**的网关。这是面试官 A 第一个追问点("模型调工具报错、参数不符合 schema、下游超时,代码怎么做异常处理")的直接答案。 - -### 当前问题 - -| 证据 | 问题 | -|---|---| -| `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 所有工具只暴露一个 `query` 字符串参数,模型无法填结构化参数,也没有可校验的 schema(D-04) | -| `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | `tools/list` 只取 name,丢弃 `description`/`inputSchema`(D-05) | -| `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 任一工具失败 `return nil, err`,整轮终止(D-03) | -| `tools.go` `normalizeTimeout` | 默认 300s,无单工具超时控制(D-16) | -| `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | `pending` map 泄漏(D-06) | -| `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | Router 无锁(D-07) | -| `ai/tools.go` 的 `SkillTool` | Skill 注册成工具但没有 `Invoke`,调用即空转;本阶段改为只注入 instruction(见 4.2.8) | -| 全局 | 无重试、无熔断、无幂等、无结果大小限制 | - -### 设计 - -#### 4.2.1 `ToolSpec`:工具的完整契约 - -```go -// internal/domain/tool/spec.go -package tool - -type SideEffect string - -const ( - EffectRead SideEffect = "read" // 可随意重试 - EffectWrite SideEffect = "write" // 重试需幂等键 - EffectDestructive SideEffect = "destructive" // 默认需人工确认 - EffectExternal SideEffect = "external" // 外发(邮件/Webhook) -) - -type Spec struct { - Name string // 全局唯一,`server.tool` 命名空间 - Title string - Description string // 必填,模型靠它选工具 - InputSchema json.RawMessage // JSON Schema 2020-12,来自 MCP tools/list - OutputSchema json.RawMessage // 可选,有则校验 - SideEffect SideEffect - Timeout time.Duration // 默认 30s - Retry RetryPolicy - Idempotency IdempotencyMode // none | key | natural - Result ResultPolicy // 截断/摘要 - Approval ApprovalPolicy // P6 使用,P1 仅占位 - Visibility Visibility // model | human_only(P6 使用) - Version string // 工具契约版本,用于缓存与审计 -} - -type RetryPolicy struct { - MaxAttempts int // 默认 3(含首次) - BaseDelay time.Duration // 200ms - MaxDelay time.Duration // 5s - Multiplier float64 // 2.0 - Jitter float64 // 0.2,full jitter - RetryOn []ErrorClass // 默认 transient/rate_limited/timeout -} - -type ResultPolicy struct { - MaxBytes int // 默认 32768 - MaxLines int // 默认 2000 - Strategy string // truncate | head_tail | summarize(P7) -} -``` - -#### 4.2.2 错误分类(重试与降级的前提) - -统一 `Failure` 结构,贯穿 P0 运行时、P1 工具、P5 工作流: - -```go -// internal/domain/runtime/errors.go -type ErrorClass string - -const ( - ErrTransient ErrorClass = "transient" // 网络抖动、连接重置 - ErrRateLimited ErrorClass = "rate_limited" // 429 / 限流 - ErrTimeout ErrorClass = "timeout" // 单工具超时 - ErrInvalidInput ErrorClass = "invalid_input" // 参数不符合 schema - ErrNotFound ErrorClass = "not_found" // 资源不存在 - ErrPermission ErrorClass = "permission" // 鉴权/策略拒绝 - ErrUpstream ErrorClass = "upstream" // 下游 4xx(非 429) - ErrSchema ErrorClass = "schema" // 返回结果不符合 OutputSchema - ErrInternal ErrorClass = "internal" // 本地 bug -) - -type Failure struct { - Class ErrorClass - Code string // TOOL_TIMEOUT / TOOL_SCHEMA_INVALID / ... - Message string - ToolName string - Attempt int - Retryable bool - Cause error -} -``` - -| 错误类 | 典型来源 | 可重试 | 默认降级动作 | -|---|---|---|---| -| `transient` | 连接重置、EOF | ✅ | 指数退避重试 | -| `rate_limited` | 429 | ✅(尊重 `Retry-After`) | 退避 + 限流排队 | -| `timeout` | 单工具 deadline | ✅ | 重试 1 次后换备用工具 | -| `invalid_input` | schema 校验失败 | ❌(但可让模型修参) | 回灌错误给模型修复重试 1 次 | -| `not_found` | 404 / 空结果 | ❌ | 走备用工具 | -| `permission` | 策略拒绝/401/403 | ❌ | 直接终止该工具,转人工或拒绝 | -| `upstream` | 下游 400/500 非临时 | ⚠️ 仅 5xx | 熔断计数 | -| `schema` | 返回体不符 OutputSchema | ❌ | 保留原始结果 + 标记 `_validation_warning` | -| `internal` | 本地 panic/序列化 | ❌ | 终止该工具并告警 | - -#### 4.2.3 网关流水线(12 步,顺序即设计) - -``` -调用请求 - │ - 1. Resolve 查注册表,取 Spec;未注册 → not_found(不再"静默失败") - 2. Visibility 模型可见性检查(P6 生效,P1 恒 true) - 3. ValidateArgs 按 InputSchema 校验 + 轻量类型纠正("5"→5) - 4. SizeGuard 参数体积上限(默认 64KB) - 5. Approval 需人工确认 → 挂起 Run(P6) - 6. Breaker 熔断器状态检查(open → 直接走降级 L4) - 7. RateLimit 每工具/每租户令牌桶 - 8. Invoke 带 per-call timeout 执行(ctx 派生) - 9. ValidateResult 有 OutputSchema 则校验 - 10. Normalize 截断/head-tail/合并多段文本 - 11. Classify 错误归类为 Failure - 12. Retry/Degrade 退避重试 → 降级阶梯 - │ -调用结果(永不 panic,永不静默丢错) -``` - -```go -// internal/domain/tool/gateway.go -type Invocation struct { - RunID string - SessionID string - TenantID string - UserID string - ToolName string - Args json.RawMessage - IdempotencyKey string // sha256(run_id + tool + args) -} - -type Result struct { - Content string // 归一化后的文本,喂给模型的就是它 - Raw json.RawMessage // 原始返回,落审计 - Degraded bool // 是否走过降级阶梯(L4/L5) - Attempts int -} - -type Gateway interface { - // Invoke 是模型工具调用的唯一出口:失败已归类为 Failure 并走完降级阶梯。 - Invoke(ctx context.Context, inv Invocation) (Result, error) - // Specs 返回当前可见的工具集(P1 返回全部,P6 按 Subject 过滤)。 - Specs(ctx context.Context) []Spec -} -``` - -`adk/tool_loop.go` 改造后不再直接调 `router.CallTool`,而是 `gw.Invoke(...)`——这是"所有工具来源收敛到一个出口"的落地形态。 - -```go -// internal/domain/tool/registry.go -type Registration struct { - Spec Spec - Invoker func(ctx context.Context, args json.RawMessage) (string, error) -} - -type Registry interface { - Register(reg Registration) error // 同名返回 ErrDuplicateTool,不再静默成功 - Get(name string) (Registration, bool) - List() []Spec -} -``` - -三种工具来源(MCP / Skill / 内置 Go 函数)都只需产出 `Registration`,`Gateway` 不关心它从哪来。 - - -#### 4.2.4 重试算法(面试可讲的细节) - -```go -func backoff(p RetryPolicy, attempt int, retryAfter time.Duration) time.Duration { - if retryAfter > 0 { return min(retryAfter, p.MaxDelay) } // 尊重服务端 - d := float64(p.BaseDelay) * math.Pow(p.Multiplier, float64(attempt-1)) - if d > float64(p.MaxDelay) { d = float64(p.MaxDelay) } - // full jitter:避免重试风暴同步 - return time.Duration(rand.Float64() * d * (1 + p.Jitter)) -} -``` - -三条容易漏的工程细节: - -1. **只对幂等操作重试**:`EffectRead` 直接重试;`EffectWrite` 必须带幂等键(`run_id + tool + sha256(args)`,Redis 存 24h),重放时返回缓存结果而不是再执行一次。 -2. **重试要计入 Step 的 `Attempt` 与事件**(`tool.retry`),否则线上无法判断"慢"是网络还是下游。 -3. **总耗时要受 Run 预算约束**:`attempt` 循环内每轮检查 `rc.Deadline()`,避免重试把 3 分钟预算吃光。 - -#### 4.2.5 降级阶梯(L0–L6) - -| 级别 | 动作 | 触发 | 用户感知 | -|---|---|---|---| -| L0 | **参数自愈**:把校验错误作为 tool 结果回灌,让模型改参重试(限 1 次) | `invalid_input` | 无感,多 1 次 LLM 调用 | -| L1 | **退避重试** | `transient`/`rate_limited`/`timeout` | 无感,延迟增加 | -| L2 | **熔断短路** | 滑动窗口 10 次失败 ≥5 | 立即失败,不再排队 | -| L3 | **备用工具**(`fallback: [search_backup]`) | L1 耗尽 / `not_found` | 结果来源变化,需在结果里标注 | -| L4 | **陈旧/缓存结果**(read-only,`stale-while-error`) | 熔断开 + 有缓存 | 结果标注 `stale: true` | -| L5 | **结构化降级**:返回 `{"status":"unavailable","reason":"..."}` 给模型 | 以上皆失败 | 模型自行改计划(例如换关键词/跳过) | -| L6 | **人工兜底**:写类/外发类不可降级 → 转审批队列,Run 挂起 | `permission` 或 `destructive` 失败 | 提示"已转人工处理" | - -**关键决策**:L5 之后 **run 不失败**,只有预算耗尽或显式致命错误才失败。这是"异常收敛"的核心——把工具故障转化为模型的输入,而不是系统的异常。 - -#### 4.2.6 MCP schema 透传(修复 D-05) - -```go -// ai/mcp_sse_client.go 改造 -type ServerTool struct { - Name string `json:"name"` - Description string `json:"description"` - InputSchema json.RawMessage `json:"inputSchema"` - Annotations struct { - SideEffect string `json:"sideEffectHint"` // 非标准字段,可选 - } `json:"annotations"` -} - -func (c *MCPSSEClient) ListTools(ctx context.Context) ([]ServerTool, error) -``` - -`RegisterAndExpand` 改用 `[]ServerTool`,注册为 `tool.Registration{Spec, Invoker}`;同名冲突返回错误而非 `nil`(修复 P0-9);`pending` map 在 defer 中删除(修复 D-06);`MCPToolRouter` 加 `sync.RWMutex`(修复 D-07)。 - -同时修复 `encodeTools`: - -```go -// 现状:encodeTools in internal/infrastructure/ai/openai_client.go 让所有工具共用 {query: string} -// 改为: -func encodeTools(specs []tool.Spec) []map[string]any { - out := make([]map[string]any, 0, len(specs)) - for _, s := range specs { - schema := s.InputSchema - if len(schema) == 0 { - schema = json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`) - } - out = append(out, map[string]any{ - "type": "function", - "function": map[string]any{ - "name": s.Name, - "description": s.Description, - "parameters": schema, - "strict": true, // OpenAI 结构化输出约束 - }, - }) - } - return out -} -``` - -#### 4.2.7 结果校验与规整 - -- 有 `OutputSchema` 且校验失败:**不丢弃结果**,保留原文并在 tool 消息上加 `{"_validation_warning": "..."}`,同时发 `tool.result` 事件带 `valid=false`。理由:线上工具常返回"多一个字段/少一个字段",直接判失败比容错更伤可用性。 -- 截断策略:`head_tail`(保留前 24KB + 后 8KB,中间标注省略字节数),对日志/HTML 类结果体验最好。 -- 大结果**标记为"可摘要"**:P7 接 LLM 摘要,P1 先只截断。 - -#### 4.2.8 Skill 的定位:本阶段只做 instruction 注入(已决策) - -**决策**:P1 阶段 `SKILL.md` 只作为**提示词侧的能力包**注入 system instruction,不注册为 function tool。"Skill 可被调用"这件事延后到 P6 沙箱就绪之后。 - -三条理由: - -1. **Skill 的产物是方法论,不是函数**。`SKILL.md` 给的是步骤、判据与参考文档,没有稳定的输入/输出契约。当前 `SkillTool` 只暴露一个自由文本 `query`,模型"调用"它等于请求一段说明,却要付一次模型往返和一次工具调用预算——收益低于直接把正文放进上下文。 -2. **现在根本没有执行面**。`SkillTool` 没有 `Invoke`,脚本与附件无人执行。把"看起来能调、实际调不出东西"的工具注册给模型,正是《项目完善报告》P1-1 批评的功能谎言;先删暴露面,才是诚实的降级。 -3. **可调用 Skill 必须先有沙箱**。真正的 Skill 要跑脚本(生成 drawio、转 PDF、执行分析),只能落在 P6 的 `sandbox.Runner` 里。在沙箱之前实现,只能是宿主机 `exec.Command`——正好是 P6 要消除的风险面。 - -**P1 的落地方式**: - -| 动作 | 位置 | 说明 | -|---|---|---| -| 新增端口 | `internal/domain/skill/loader.go` | `Loader{Load(name string) (Skill, error)}`;`Skill{Name, Description, Instruction, Resources, Scripts}` | -| 新增适配器 | `internal/infrastructure/skill/fs_loader.go` | 读 `SKILL.md`(YAML front matter + 正文),解析 `scripts/`、`resources/` | -| 修改装配 | `armory/agent_node.go` | 构造 instruction 时把选中 Skill 的正文追加到 system prompt,带 `## 技能:` 分隔标题 | -| 修改语义 | `ChatModelConfig.ToolSkillsList` | 字段名不变,含义从"注册成工具"改为"注入为技能";行为变更需 release note + 开关 `skills.mode: inject|expose`,默认 `inject` | -| 保留不暴露 | `ai/tools.go` 的 `SkillTool` | 保留类型但**不注册**到模型可见工具集,`Visibility: human_only` 占位,`Invoke` 留给 P6 | - -注入的正文计入 P4 的 token 预算(单个 Skill 正文建议 ≤ 4k token,超出截断并告警);同一 Skill 在一次 Run 内只注入一次,避免重复占用预算。 - -**P6 的升级路径(本阶段只预留接口)**: - -```go -// internal/domain/skill/exec.go(P6 引入) -type Runner interface { - Run(ctx context.Context, skill Skill, script string, args []string) (Result, error) -} -``` - -`SKILL.md` 增加可选 front matter `scripts: [{name, entry, timeout}]`;P6 把每个 script 包装成 `tool.Spec{Name: "skill..