Compare commits
12 Commits
bc087ad54b
...
a36e91d0dc
| Author | SHA1 | Date | |
|---|---|---|---|
| a36e91d0dc | |||
| cbc55a2543 | |||
| c20dd20f0f | |||
| 46fa071a59 | |||
| 39afae6024 | |||
| 407e19124f | |||
| 7ef38ed7a6 | |||
| 5ea2daae4a | |||
| 52e93879c9 | |||
| adf5fdb6f4 | |||
| 4811a2d48a | |||
| 71198f3ca9 |
@@ -10,9 +10,11 @@ REDIS_ADDR=127.0.0.1:16379
|
||||
# base-url 末尾可带或不带斜杠,代码会自动处理
|
||||
# OPENAI_BASE_URL=https://api.openai.com/
|
||||
# OPENAI_API_KEY=replace-me
|
||||
# OPENAI_MODEL=your-model-name
|
||||
# 中转站推荐:https://codez.zwenooo.link/register?aff=c3yW
|
||||
OPENAI_BASE_URL=https://api-s.abcd.link/
|
||||
OPENAI_API_KEY=sk-A7B5Wv41qabcdefg**********7yoCxlcU
|
||||
OPENAI_MODEL=gpt-5.5
|
||||
|
||||
# 百度搜索 MCP(SSE 模式)
|
||||
# base-uri:保留到 /mcp/ 这一层,sse-endpoint 是相对路径
|
||||
|
||||
120
AGENTS.md
Normal file
120
AGENTS.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file holds the working standards for this repository. Project overview, commands, architecture, and configuration live in [README.md](README.md) — read that first, and do not duplicate it here.
|
||||
|
||||
## Documentation Standards
|
||||
|
||||
Docs fall into three categories with different standards. Pick the category before writing and state it at the top of the file (for example, `> Doc type: implementation`). The categories are engineering docs (plan, implementation, bug fix), introductory docs, and reference docs (APIs, configuration, error codes).
|
||||
|
||||
### Common rules (all docs)
|
||||
|
||||
- **Never locate code by line number.** Use `path` plus an identifier (function, type, constant, config key), for example `Adapter.Execute` in `internal/infrastructure/adk/adapter.go`. Line numbers drift when code changes; identifiers do not.
|
||||
- **One concept, one term.** Use the same word for the same thing throughout a doc, with no synonyms. Define each term at its first use, for example: **Armory** — the chain of responsibility that turns YAML configuration into runnable agents.
|
||||
- **Do not document what you cannot verify.** Mark unverified behavior `TBD` and say how to confirm it (whom to ask, which command to run). Never present a guess as fact.
|
||||
- **Generate reference docs from code or schema.** Build API lists, config keys, and error-code tables from `go doc`, route registration code, the YAML schema, or the constants in `pkg/types`, then proofread the result. Hand-written parts must be checked against the source entry by entry.
|
||||
- **Examples must run.** Commands, configuration, and snippets should be copy-paste runnable. Mark anything that does not run as `illustrative, untested`.
|
||||
- Do not repeat onboarding content that already exists in the README; link to it. Keep each fact in one place.
|
||||
|
||||
### Engineering docs (plan / implementation / bug fix)
|
||||
|
||||
Goal: someone else can execute, verify, and debug from the doc alone. Be as detailed and specific as possible.
|
||||
|
||||
**Each entry is self-contained** and states at least:
|
||||
|
||||
1. Preconditions: required configuration, services, permissions, existing changes, version assumptions.
|
||||
2. Parameters and defaults: name, type, unit, value range, and behavior when omitted.
|
||||
3. Returns and side effects: what it returns, what it writes, what events it emits, whether it is idempotent and reentrant.
|
||||
4. Failure modes and error codes: when it fails, the error or HTTP code, the message text, retry semantics.
|
||||
5. Observability: log fields, metrics, traces, how to confirm success or failure, where to start debugging.
|
||||
|
||||
**Organize by the question the reader asks** (for example "add an agent", "switch to Redis storage", "debug error 0002"), not by source-file order. Each section is readable on its own; no reading order is required.
|
||||
|
||||
**Walk all nine boundary dimensions.** Write "undefined" explicitly where behavior is undefined; never leave a gap.
|
||||
|
||||
| Dimension | Questions to answer |
|
||||
| --- | --- |
|
||||
| Input | empty values, oversized input, invalid characters, encoding, duplicate keys, unknown fields |
|
||||
| Numeric | zero, negative, upper bounds, precision, overflow, unit mismatch |
|
||||
| Resource | concurrency limits, memory and file handles, connection-pool exhaustion, large objects |
|
||||
| Time | timeouts, clock skew, retry backoff, TTL, time zones |
|
||||
| State | repeated execution, concurrent modification, recovery after restart, partial success |
|
||||
| Permission | who may call, privilege escalation, missing or expired credentials, tenant isolation |
|
||||
| Failure | downstream outage, partial failure, degradation, rollback |
|
||||
| Version | protocol and configuration compatibility, upgrade and rollback paths |
|
||||
| Environment | dev versus prod differences, platform differences, missing env vars, origin of default values |
|
||||
|
||||
Per-category additions:
|
||||
|
||||
- Plan: phases, deliverables and acceptance criteria per phase, dependency order, rollback points, deferred or out-of-scope items with reasons.
|
||||
- Implementation: change list at file and identifier level (not line numbers), migration and compatibility strategy, verification steps (command plus expected output), rollout and rollback steps.
|
||||
- Bug fix: close the loop — phenomenon → reproduction (minimal steps plus environment) → root cause → blast radius → fix → verification → regression risk. Reproduction steps must run standalone; the root cause names the exact code path and trigger, not "some logic is wrong".
|
||||
|
||||
### Introductory docs
|
||||
|
||||
Goal: the reader gains a complete, clear picture and can run the thing.
|
||||
|
||||
Include one **runnable main path**, in four steps, with no gaps:
|
||||
|
||||
1. What it is: one sentence of positioning plus 3–5 key characteristics.
|
||||
2. What problem it solves: the pain without it, grounded in a concrete scenario.
|
||||
3. How it solves it: the overall approach and key trade-offs, saying why this way and not another.
|
||||
4. How it is implemented: the implementation path — entry point, key modules, data flow, output.
|
||||
|
||||
Also provide a **directory map** (one line of responsibility per module or directory, using identifiers rather than line numbers) and the **implementation path** (the components and functions a request passes from entry to persistence or response). Mention detail without going to engineering-doc depth; link to engineering docs for the rest.
|
||||
|
||||
Use precise, plain words in the spirit of ASD-STE100: one idea per sentence, active voice, few nested clauses, one verb per action, sparing pronouns, no adjective stacking, no marketing language. Prefer short sentences and short paragraphs. Stop once the main path is covered; do not chase full coverage.
|
||||
|
||||
## Commit Standards
|
||||
|
||||
- **Language**: write commit messages in Chinese; keep `type` and `scope` in English.
|
||||
- **Format**: Conventional Commits, `type(scope): subject`.
|
||||
- type is `feat` / `fix` / `docs` / `refactor` / `test` / `chore`; use `perf` / `build` / `ci` / `style` / `revert` when warranted.
|
||||
- scope is the affected module — a first-level directory or subsystem under `internal/` or `frontend/`, such as `agent`, `armory`, `chat`, `adk`, `config`, `http`, `frontend`. Omit it, or use `repo`, for changes that span modules.
|
||||
- subject is imperative, states what changed and why it matters, takes no trailing period, and stays around 50 characters.
|
||||
- Add a body when needed for motivation and impact, wrapped at 72 characters. Flag breaking changes with `!` after the type or a `BREAKING CHANGE:` footer.
|
||||
- Examples (subjects in Chinese, matching the language rule):
|
||||
- `feat(armory): 支持用环境变量覆盖模型温度`
|
||||
- `fix(chat): 会话不存在时返回 0002 而不是 0001`
|
||||
- `docs(agents): 补充文档、提交与注释规范`
|
||||
- **No single-shot commits.** Do not stuff a batch of changes into one commit, and do not hoard work until the end of a task.
|
||||
- **Granularity**: one logical change per commit, independently buildable (`go build ./...`, `cd frontend && npm run build`) and independently revertable (`git revert` leaves the repository usable). Split the commit if either fails.
|
||||
- **Titles carry information.** Ban `update`, `fix bug`, `修改`, `优化`, `提交` and similar zero-information titles; the title alone must tell what changed without opening the diff.
|
||||
- **Do not mix categories.** Formatting, renames, and import sorting go in their own `style` or `refactor` commit, separate from behavior changes. Pure file moves use `refactor` with "no behavior change" in the body.
|
||||
- Unrelated problems noticed along the way get their own commit or a tracked note; do not smuggle them into the current commit.
|
||||
|
||||
## Comment Standards
|
||||
|
||||
Comments come in two kinds with different jobs. Do not let them bleed into each other.
|
||||
|
||||
### Doc comments (for callers)
|
||||
|
||||
State what it is and how to use it: what the exported identifier does, what its parameters mean and constrain, what it returns, when it fails, and the side effects a caller must know about (concurrency safety, lock holding, blocking, idempotency).
|
||||
|
||||
Describe the contract and usage only — not internal choices such as "implemented with a skip list". Implementations change; contracts do not. Go doc comments start with the identifier name. Exported frontend functions and components carry JSDoc/TSDoc for parameters and return values. Package comments state the package boundary and its invariants.
|
||||
|
||||
### Implementation comments (for maintainers)
|
||||
|
||||
Write only what the code cannot express:
|
||||
|
||||
- Why this way: the reason for this approach over another.
|
||||
- Non-obvious ordering and locking: what must precede what, which lock guards which state, why a lock cannot be taken at that point.
|
||||
- Magic numbers: where 4 tool-call iterations, timeouts, and retry counts come from (protocol limit, measurement, upstream docs).
|
||||
- Workarounds: the concrete bug being bypassed and the condition under which the code can be deleted.
|
||||
|
||||
Never write:
|
||||
|
||||
- Restatements of the code (`i++ // increment i`).
|
||||
- Commented-out code: version control keeps it, so delete it.
|
||||
- Author, date, or change history: git already has that.
|
||||
- Language truisms: what an error is, what a goroutine is.
|
||||
- Internal detail in doc comments: which data structure or private function is used.
|
||||
- Line numbers or copies of variable names that go stale on rename.
|
||||
- What a rename or a smaller function should say instead: a comment explaining "this variable holds pending items" is a request to rename the variable.
|
||||
- ASCII banners and separator lines.
|
||||
- Ownerless TODOs (`// TODO: optimize`). If one is needed, write `// TODO(module): condition and action`, with an issue number when possible.
|
||||
|
||||
### Length and where knowledge lands
|
||||
|
||||
- One point per comment; if one line carries it, do not write three.
|
||||
- Design notes that belong in introductory or engineering docs stay short in code: link to the doc or leave a pointer. Code comments keep only what the reader needs on the spot.
|
||||
- Change comments together with the code. Any behavior change requires re-reading the affected comments; a stale comment is worse than none.
|
||||
7
CLAUDE.md
Normal file
7
CLAUDE.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# CLAUDE.md
|
||||
|
||||
The working standards for this repository — documentation, commit, and comment rules — are defined once in [AGENTS.md](AGENTS.md) and loaded below. Project overview, commands, architecture, and configuration live in [README.md](README.md).
|
||||
|
||||
Do not keep a copy of either here. Edit the source file when a rule changes.
|
||||
|
||||
@AGENTS.md
|
||||
@@ -15,7 +15,7 @@ ai:
|
||||
completions-path: v1/chat/completions
|
||||
embeddings-path: v1/embeddings
|
||||
chat-model:
|
||||
model: "gpt-5.5"
|
||||
model: ${OPENAI_MODEL}
|
||||
tool-mcp-list:
|
||||
- sse:
|
||||
name: baidu-search
|
||||
|
||||
@@ -15,7 +15,7 @@ ai:
|
||||
completions-path: "v1/chat/completions"
|
||||
embeddings-path: "v1/embeddings"
|
||||
chat-model:
|
||||
model: "gpt-5.5"
|
||||
model: ${OPENAI_MODEL}
|
||||
tool-mcp-list:
|
||||
- sse:
|
||||
name: baidu-search
|
||||
|
||||
901
docs/agent-platform-upgrade-plan.md
Normal file
901
docs/agent-platform-upgrade-plan.md
Normal file
@@ -0,0 +1,901 @@
|
||||
# Agent 平台升级方案
|
||||
|
||||
> 从「YAML 驱动的多 Agent 执行器」到「Agent 搭建脚手架 + Agent 运行时」
|
||||
>
|
||||
> 适用仓库:`ai-agent-scaffold-go`(Go 1.25.6 / Gin / eino / adk)
|
||||
> 文档版本:v1.0 编写日期:2026-10-30
|
||||
> 文档性质:架构演进方案 + 分阶段实施计划(本文不含代码改动)
|
||||
> Doc type: plan(工程文档:阶段、交付物、验收标准、依赖顺序、回滚点)
|
||||
|
||||
---
|
||||
|
||||
# 0. 结论摘要(先看这一页)
|
||||
|
||||
**一句话诊断**:当前项目是一个"能把 YAML 配置翻译成一次 LLM 调用链"的**执行器**,还不是"平台"。它有能力跑通 demo,但缺少让 Agent 在生产里**活着**的四类基础设施:**状态与预算**(Run/Step 生命周期、上下文透传、步数上限)、**持久化与记忆**(会话、消息、跨轮上下文)、**工具治理**(schema、重试、降级、权限、审批)、**可观测与评测**(trace、回放、断言、Bad Case 闭环)。
|
||||
|
||||
**升级目标**:把它拆成三层可独立演进的能力面。
|
||||
|
||||
| 层 | 回答的问题 | 本文对应阶段 |
|
||||
|---|---|---|
|
||||
| **搭建脚手架(Authoring)** | 怎么用 YAML/Skill/Tool 快速定义一个新 Agent | P1、P5、P6 |
|
||||
| **运行时(Runtime)** | 一个请求进来,怎么被调度、记忆、约束、恢复 | P0、P2、P3、P4 |
|
||||
| **治理面(Governance)** | 怎么保证它安全、可观测、可度量、可回滚 | P6、P7、P8 |
|
||||
|
||||
**路线图一览**(9 个阶段,估算 85–110 人日,单人约 4–5 个月 / 双人约 10 周):
|
||||
|
||||
```
|
||||
P0 运行时内核 ──► P1 工具网关 ──► P2 会话持久化 ──► P3 记忆与知识 ──► P4 上下文工程
|
||||
│ │
|
||||
└──────────► P5 工作流编排 ◄───────┘
|
||||
│
|
||||
P6 权限/审批/沙箱/Vault ──► P7 可观测与评测 ──► P8 生产化
|
||||
```
|
||||
|
||||
**四个设计红线**(贯穿全部阶段,后文不再重复):
|
||||
|
||||
1. **前端零改动**:`/api/v1/query_ai_agent_config_list`、`/api/v1/create_session`、`/api/v1/chat` 三个端点的**请求与响应结构必须保持不变**(`agentApi` in `frontend/src/api/agent.ts` 直接依赖)。
|
||||
2. **配置向后兼容**:`configs/agent/*.yaml` 只做**增量字段**,旧字段语义不变;行为变更(如 parallel 真并发)必须通过开关切换,默认保持旧行为一个版本。
|
||||
3. **六边形架构不破**:新增能力一律「先在 `internal/domain/` 定端口,再到 `internal/infrastructure/` 落适配器,最后在 `bootstrap.Build()` 显式装配」。禁止在 handler 或 adapter 里直接 `new` 基础设施。
|
||||
4. **每阶段必须可独立上线 + 可回滚**:用 4 个配置开关控制(`runtime.enabled` / `memory.enabled` / `tools.governance.enabled` / `workflow.execution-mode`),任何阶段出问题能退回上一阶段的行为。
|
||||
|
||||
---
|
||||
|
||||
# 1. 现状评估
|
||||
|
||||
### 1.1 代码地图
|
||||
|
||||
全部 Go 代码 **3939 行,零测试**。模块与职责如下(行数为实际统计):
|
||||
|
||||
| 层 | 文件 | 行数 | 职责 | 关键问题 |
|
||||
|---|---|---:|---|---|
|
||||
| 入口 | `cmd/server/main.go` | 87 | 加载 env/config → bootstrap → `engine.Run()` | 无优雅停机;无 signal 处理 |
|
||||
| 装配 | `internal/app/bootstrap/bootstrap.go` | 157 | 手工装配全部依赖 | MySQL/Redis 适配器**从未接线**;CORS 反射任意 Origin |
|
||||
| 配置 | `internal/app/config/application.go` | 88 | `application.yaml` 加载 | 不做 `${VAR}` 展开 |
|
||||
| 配置 | `internal/app/config/loader.go` | 186 | Agent YAML 加载/校验 | 不校验子 Agent 存在性、重名、runner 引用 |
|
||||
| 领域模型 | `internal/domain/agent/model/config.go` | 96 | 配置结构体 | `EmbeddingsPath` 定义但**全项目未使用** |
|
||||
| 领域模型 | `internal/domain/agent/model/command.go` | 47 | 命令/内容对象 | `Runner` 接口**无 ctx**;`Files`/`InlineDatas` 被静默忽略 |
|
||||
| 端口 | `internal/domain/agent/ports/ports.go` | 167 | 全部接口 + 内存实现 | `SessionStore` 只存 ID 不存消息;无 ctx;无租户 |
|
||||
| 服务 | `internal/domain/agent/service/chat/service.go` | 117 | 会话管理 + 消息分发 | `CreateSession` get-then-set 竞态;**不校验 session 归属** |
|
||||
| 装配链 | `internal/domain/agent/service/armory/*.go` + `workflow/*.go` | ~600 | Root→AiAPI→ChatModel→Agent→Workflow→Runner | `AcceptArmoryAgents` 遍历 map,**装配顺序随机** |
|
||||
| 执行器 | `internal/infrastructure/adk/adapter.go` | **572** | LLM/sequential/loop/parallel 四种执行 | 单文件巨石;`maxToolCallIterations = 4` 硬编码;工具失败即整轮失败 |
|
||||
| 模型 | `internal/infrastructure/ai/openai_client.go` | 368 | OpenAI 兼容 HTTP 客户端 | 工具参数**硬编码为单个 `query` 字符串**;无重试/退避 |
|
||||
| 模型 | `internal/infrastructure/ai/eino_adapter.go` | 117 | Provider 适配 | 依赖 `ToolDescriptor`,但**无类型实现该接口** → 描述恒空 |
|
||||
| 工具 | `internal/infrastructure/ai/tools.go` | 584 | MCP/Skill/本地工具工厂 | stdio/local 工具运行期不可执行 |
|
||||
| 工具 | `internal/infrastructure/ai/mcp_sse_client.go` | 580 | MCP SSE + JSON-RPC | `ListTools` 丢弃 description/inputSchema;`pending` map 泄漏;Router 无锁 |
|
||||
| 存储 | `internal/infrastructure/persistence/mysql.go` | 35 | `OpenMySQL` | **未被调用** |
|
||||
| 存储 | `internal/infrastructure/cache/redis.go` | 35 | `OpenRedis` | **未被调用** |
|
||||
| 日志 | `internal/infrastructure/logging/logger.go` | 10 | 按 env 二选一 | 不可配置级别/输出;未注入全链路 |
|
||||
| HTTP | `internal/trigger/http/agent_handler.go` | 109 | 5 个端点 | `writeError(c, nil)` 会 panic |
|
||||
| 契约 | `internal/api/dto/agent.go` / `response/response.go` | ~80 | DTO + `{code,info,data}` | DTO 无 binding tag |
|
||||
|
||||
### 1.2 能力矩阵
|
||||
|
||||
以"一个可用于生产的 Agent 平台"应具备的 12 项能力为标尺:
|
||||
|
||||
| # | 能力 | 现状 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 1 | Agent 定义与装配 | 🟡 40% | YAML 驱动、Armory 链装配已成型;但校验弱、顺序随机、无法热加载 |
|
||||
| 2 | 执行与调度 | 🟡 35% | 四种执行模式可跑;无显式 Run/Step 状态、无预算、ctx 丢失 |
|
||||
| 3 | 会话与多轮对话 | 🔴 10% | 只存 `userID:agentID → sessionID` 映射;**每轮都是全新上下文** |
|
||||
| 4 | 记忆系统 | 🔴 0% | 无分层、无摘要、无长期记忆、无检索 |
|
||||
| 5 | 工具调用可靠性 | 🔴 15% | 无 schema、无重试、无降级、无超时;一次失败整轮失败 |
|
||||
| 6 | 工具治理(权限/审批) | 🔴 0% | 无可见范围控制、无人工确认、无审计 |
|
||||
| 7 | 沙箱与密钥 | 🔴 0% | 无隔离执行;密钥明文在 YAML/.env |
|
||||
| 8 | 工作流编排 | 🟡 30% | sequential 可用;parallel 是**串行**,loop 无迭代语义,无回滚/断点 |
|
||||
| 9 | 持久化 | 🔴 5% | 适配器存在但未接线,重启即失忆 |
|
||||
| 10 | 可观测性 | 🔴 10% | 只有 zap 基础日志与 `fmt.Printf` 插件;无 trace、无 run_id |
|
||||
| 11 | 安全与内容合规 | 🔴 0% | 无内容审核、无 PII 处理、CORS 全开 |
|
||||
| 12 | 测试与评测 | 🔴 0% | 零测试、无评测集、无回归门禁 |
|
||||
|
||||
### 1.3 关键缺陷证据(按阶段归属)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账(见 [`upgrade-plan/README.md`](upgrade-plan/README.md)),在后续阶段中直接引用,避免重复描述。
|
||||
|
||||
| ID | 现象 | 证据(标识符 · 文件) | 影响 | 归属 |
|
||||
|---|---|---|---|---|
|
||||
| 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 |
|
||||
|
||||
> 本表只保留与升级路线强相关、有明确代码证据的条目;完整台账(76 条,含历史审计 71 条与本方案新增 5 条)见 [`upgrade-plan/README.md`](upgrade-plan/README.md)。
|
||||
|
||||
### 1.4 可复用资产(不要重复造)
|
||||
|
||||
升级不是重写。以下资产已验证可用,应保留并在其上扩展:
|
||||
|
||||
- **配置驱动范式**:`configs/agent/*.yaml` + `internal/app/config/loader.go` 的 `${VAR:-default}` 展开机制,是正确的"脚手架"形态,直接沿用。
|
||||
- **armory 责任链**:`internal/domain/shared/tree/router.go` + `armory/root_node.go` 这条链的**分层装配思想**是对的(配置 → API → 模型 → 工具 → Agent → 工作流 → Runner),只需换成**确定性顺序**并支持插件节点。
|
||||
- **MCP SSE 客户端**:`ai/mcp_sse_client.go` 的 JSON-RPC + SSE 实现可用,缺的是 schema 透传与并发安全,属于修补而非重写。
|
||||
- **OpenAI 兼容层**:`ai/openai_client.go` 的流式解析(按 index 累积 tool_calls)可用,只需把 `encodeTools` 换成真实 schema。
|
||||
- **Skill 机制**:`SKILL.md` front matter 扫描(`ai/tools.go`)是很好的"领域能力包"入口,可扩展为 Skill 注册中心。
|
||||
- **MySQL/Redis 适配器**:`persistence/mysql.go`、`cache/redis.go` 已有连接封装,接线即可用。
|
||||
- **前端**:`frontend/` 的 Next.js 对话界面无需改动,新能力通过新增端点与 SSE 事件扩展。
|
||||
|
||||
---
|
||||
|
||||
# 2. 目标蓝图
|
||||
|
||||
### 2.1 分层架构
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────────┐
|
||||
│ 接入层 internal/trigger/http │
|
||||
│ /api/v1/chat(兼容) /api/v1/runs:stream(事件流) /approvals /admin │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ 应用层 internal/domain/{runtime, session, workflow} │
|
||||
│ Run 状态机 · 预算仲裁 · 会话聚合 · 图执行 · 检查点 · 断点续跑 │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ 领域能力 internal/domain/{memory, context, tool, security, guard, evals}│
|
||||
│ 记忆分层 · 上下文装配/压缩 · 工具网关 · 策略/审批 · 内容安全 · 断言 │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ 执行器 internal/infrastructure/adk │
|
||||
│ Executor 插件:llm / sequential / parallel / loop / human / subgraph │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ 适配器 internal/infrastructure/{ai, persistence, cache, sandbox, vault, obs}│
|
||||
│ OpenAI 兼容 · MySQL · Redis · Docker/Wasm · 密钥 · OTel │
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**关键变化**:现在的 `adk.Agent` 同时承担"定义 + 调度 + 执行 + 插件通知"四件事;升级后**定义**留在 `domain/agent`,**调度**上移到 `domain/runtime`,**执行**下沉为 `Executor` 插件,**观测**统一走 `obs`。
|
||||
|
||||
### 2.2 目标目录结构(增量标注)
|
||||
|
||||
```
|
||||
internal/
|
||||
domain/
|
||||
agent/ # 保留:YAML 模型、armory 装配链
|
||||
runtime/ # ★新增:Run/Step/Event/Budget/Executor/错误模型
|
||||
session/ # ★新增:会话聚合、仓储端口、生命周期
|
||||
memory/ # ★新增:事实/摘要/检索/抽取/评分
|
||||
context/ # ★新增:Token 预算装配、压缩、pinning
|
||||
tool/ # ★新增:ToolSpec、网关、重试、熔断、降级
|
||||
workflow/ # ★新增:图/节点/条件/Saga/检查点/续跑
|
||||
security/ # ★新增:策略引擎、审批、密钥端口、脱敏
|
||||
guard/ # ★新增:输入输出安全
|
||||
evals/ # ★新增:断言、评测用例、评分器
|
||||
shared/tree/ # 保留
|
||||
infrastructure/
|
||||
adk/ # ◆改造:拆成 agent.go / executor_*.go / runner.go / plugin.go
|
||||
ai/ # ◆改造:provider 分层、embedding、tool adapter
|
||||
persistence/mysql/# ★新增:session/message/run/event/fact/summary/approval 仓储
|
||||
cache/redis/ # ◆改造:会话缓存、分布式锁、幂等、限流
|
||||
sandbox/ # ★新增:docker / wasm / local
|
||||
vault/ # ★新增:env / file / kms
|
||||
obs/ # ★新增:otel、结构化日志、metrics、事件存储
|
||||
memory/ # ★新增:异步记忆抽取 worker + outbox
|
||||
app/
|
||||
config/ # ◆改造:严格校验、环境变量展开、版本化
|
||||
bootstrap/ # ◆改造:分层装配、特性开关、优雅停机
|
||||
trigger/http/ # ◆改造:v2 端点、鉴权/限流/追踪中间件
|
||||
api/ # ◆改造:DTO 拆分与绑定校验
|
||||
pkg/types/ # ◆改造:分层错误码
|
||||
migrations/ # ★新增:SQL 迁移(golang-migrate)
|
||||
cmd/replay/ # ★新增:事件日志重放
|
||||
cmd/migrate/ # ★新增:迁移执行
|
||||
```
|
||||
|
||||
### 2.3 核心领域对象与不变量
|
||||
|
||||
| 对象 | 语义 | 必须成立的不变量 |
|
||||
|---|---|---|
|
||||
| `Agent` | 由 YAML 定义的可执行体(LLM/组合) | 名称在 app 内唯一;引用的子 Agent 必须存在 |
|
||||
| `Session` | 用户与某 Agent 的**长期对话容器** | 属于唯一 `(tenant, user, agent)`;同一三元组同时只有一个 `active` |
|
||||
| `Turn` | 一次用户输入的逻辑单元(user msg → 若干 assistant/tool msg) | 归属于 Session;`seq` 单调递增 |
|
||||
| `Run` | 一次**执行实例**(一个 Turn 触发的完整调度) | 必属一个 Session;状态机单向;预算只减不增 |
|
||||
| `Step` | Run 内最小可观测单元(llm/tool/agent/workflow/approval) | `index` 单调;`start/end` 成对;失败必须携带 `Failure` |
|
||||
| `Event` | 追加写的事实(append-only) | `seq` 单调不可变;重放可完整重建 Run |
|
||||
| `Message` | 持久化消息(含 tool_calls/tool 结果) | `seq` 在 Session 内唯一;tool 调用与结果成对 |
|
||||
| `MemoryFact` | 长期事实(偏好/实体/决策/约束) | 物理不删,只 `valid_to` 失效;必有来源 `message_id` |
|
||||
| `Approval` | 人工确认单 | 有 TTL;决策不可改;与 Step 一一对应 |
|
||||
|
||||
### 2.4 兼容性契约
|
||||
|
||||
| 维度 | 现状 | 本方案的承诺 | 验证方式 |
|
||||
|---|---|---|---|
|
||||
| HTTP 老端点 | 5 个端点 | 路径、请求体、响应体**零变化** | 前端 e2e + golden JSON |
|
||||
| SSE 老端点 | `/chat_stream` 只推 delta 文本 | 保持只推 delta,新事件走新端点 `/runs:stream` | 契约测试 |
|
||||
| Agent YAML | 现有 2 个文件 | 只增字段;旧字段语义不变 | 加载两个样例配置启动成功 |
|
||||
| 装配链 | 责任链可扩展 | 保留链路,改为确定性顺序 | 启动日志断言顺序 |
|
||||
| 数据库 | 无表 | 只加表,不改既有结构;启动自动迁移可选 | 迁移 dry-run 输出 |
|
||||
| Go 内部接口 | 无 ctx | 每阶段集中改一次,阶段内闭环,不跨阶段遗留 | `go build ./...` + lint 禁止 `context.Background()`(除 main/serve) |
|
||||
|
||||
### 2.5 特性开关(回滚抓手)
|
||||
|
||||
| 开关 | 默认 | 作用 | 引入阶段 |
|
||||
|---|---|---|---|
|
||||
| `runtime.enabled` | `true` | 启用新 Run 状态机;false 走旧 runner | P0 |
|
||||
| `runtime.budget.*` | 24 步 / 16 次工具 / 200k token / 3m | 终止保证 | P0 |
|
||||
| `tools.governance.enabled` | `false` | 工具网关(schema/重试/降级);false 走原直连 | P1 |
|
||||
| `tools.approval.enabled` | `false` | 写类工具人工确认 | P6 |
|
||||
| `skills.mode` | `inject` | `inject` 注入 instruction / `expose` 注册为工具(旧行为) | P1 |
|
||||
| `memory.enabled` | `false` | 记忆写入与召回 | P3 |
|
||||
| `context.assembler.enabled` | `false` | 上下文装配器;false 用原 `initialMessages` | P4 |
|
||||
| `workflow.execution-mode` | `legacy` | `legacy` / `graph` | P5 |
|
||||
| `persistence.mode` | `memory` | `memory` / `mysql` / `mysql+redis` | P2 |
|
||||
| `obs.otel.enabled` | `false` | 分布式追踪 | P7 |
|
||||
|
||||
> 原则:**新代码默认关闭,灰度打开**。任一阶段上线后出问题,改一个配置即可回到上一阶段行为,不需要回滚代码。
|
||||
|
||||
---
|
||||
|
||||
# 3. 路线图总览
|
||||
|
||||
| 阶段 | 主题 | 一句话交付 | 新增模块 | 主要改动文件 | 人日 | 依赖 | 演示效果 |
|
||||
|---|---|---|---|---|---:|---|---|
|
||||
| **P0** | 运行时内核 | 每次执行都有 Run/Step 状态与预算,可中断、可重放 | `domain/runtime`、`adk/executor_*` | `adk/adapter.go`(拆分)、`ports.go`、`bootstrap.go` | 8–10 | — | 断开浏览器,服务端 300ms 内停止并记录 `run.canceled` |
|
||||
| **P1** | 工具网关 | 工具调用带 schema 校验、指数退避、熔断、分级降级 | `domain/tool`、`infra/tool` | `openai_client.go`、`mcp_sse_client.go`、`tools.go` | 10–12 | P0 | 注入 30% 失败率,run 仍成功且事件里能看到 3 次重试 |
|
||||
| **P2** | 会话持久化 | 会话与消息落 MySQL,Redis 做缓存/锁/幂等,重启不失忆 | `domain/session`、`persistence/mysql` | `chat/service.go`、`ports.go`、`bootstrap.go`、`migrations/` | 8–10 | P0 | `kill -9` 重启后继续对话,上下文完整 |
|
||||
| **P3** | 记忆与知识 | working/episodic/semantic 三层记忆 + 文档知识库检索 | `domain/memory`、`ai/embedding` | 新增 6 个仓储/schema、`config.go` | 12–15 | P2 | 第 25 轮准确复述第 2 轮的偏好;知识库问答带引用 |
|
||||
| **P4** | 上下文工程 | Token 预算装配 + 滚动摘要压缩 + 关键信息优先召回 | `domain/contextasm` | `adk/executor_llm.go`、`chat/service.go`、`openai_client.go` | 10–12 | P3 | 20+ 轮对话 Token 稳定在 6k,关键事实召回率 > 95% |
|
||||
| **P5** | 工作流编排 | 图/状态机执行、节点重试、Saga 补偿、断点续跑、真并发 | `domain/workflow` | `adk/adapter.go`(删旧 fan-out)、`armory/workflow/*` | 12–15 | P0、P2 | 5 节点流程第 3 节点失败 → 自动补偿并可从检查点续跑 |
|
||||
| **P6** | 工具治理 | 可见范围、策略引擎、HITL 审批、沙箱、Vault | `domain/security`、`infra/sandbox`、`infra/vault` | `domain/tool/gateway.go`、`trigger/http`、`bootstrap.go` | 10–12 | P1、P5 | 写类工具弹出审批,批准后从断点继续;stdio 工具跑在容器里 |
|
||||
| **P7** | 可观测与评测 | Trace/事件回放/关键节点断言/Bad Case 闭环/评测集 | `infra/obs`、`domain/evals`、`domain/guard` | 全链路埋点、`cmd/replay`、CI | 10–12 | P0、P4 | 用 run_id 串起一次执行的 37 个 span;评测集回归 |
|
||||
| **P8** | 生产化 | 鉴权、限流、迁移、优雅停机、安全加固 | `trigger/http/middleware` | `main.go`、`bootstrap.go`、`config` | 6–8 | P2、P7 | 压测 200 QPS;滚动发布零失败请求 |
|
||||
|
||||
**排序理由**:P0 是其余所有阶段的"底座"(没有 Run/Step 就没有地方挂预算、事件、审批、检查点);P1/P2 可并行(工具可靠性与持久化互不阻塞);P3→P4 必须串行(先有存储才有装配);P5 依赖 P0 的 Step 模型与 P2 的检查点存储;P6 依赖 P1 的网关插槽与 P5 的断点能力;P7/P8 收尾。
|
||||
|
||||
---
|
||||
|
||||
# 4. 阶段清单(阶段详设已拆分)
|
||||
|
||||
九个阶段各自是一份独立计划书,放在 [`upgrade-plan/`](upgrade-plan/README.md) 下;本节只保留索引。
|
||||
正文(目标 / 当前问题 / 设计 / 涉及模块 / 配置 / 验收 / 测试 / 风险)与「本阶段收编的缺陷」都在对应文件里,
|
||||
跨文件引用仍用原来的 `4.x.y` 小节号,按号在文件内查找即可。
|
||||
|
||||
| 阶段 | 计划书 | 主题 | 预估 | 前置 |
|
||||
|---|---|---|---|---|
|
||||
| P0 | [`P0-运行时内核.md`](upgrade-plan/P0-运行时内核.md) | 运行时内核:让每一次执行都成为一等公民 | 8–10 人日 | — |
|
||||
| P1 | [`P1-工具网关.md`](upgrade-plan/P1-工具网关.md) | 工具网关:把「能调通」变成「调不坏」 | 10–12 人日 | P0 |
|
||||
| P2 | [`P2-会话持久化.md`](upgrade-plan/P2-会话持久化.md) | 会话生命周期与持久化:让 Agent 记得住、找得回 | 8–10 人日 | P0 |
|
||||
| P3 | [`P3-记忆与知识.md`](upgrade-plan/P3-记忆与知识.md) | 记忆与知识:三层记忆 + 可检索知识库 | 12–15 人日 | P2 |
|
||||
| P4 | [`P4-上下文工程.md`](upgrade-plan/P4-上下文工程.md) | 上下文工程:20 轮之后还记得第一句话 | 10–12 人日 | P2、P3 |
|
||||
| P5 | [`P5-工作流编排.md`](upgrade-plan/P5-工作流编排.md) | 工作流编排:从「线性 Chain」到「可补偿的状态机」 | 12–15 人日 | P2 |
|
||||
| P6 | [`P6-工具治理.md`](upgrade-plan/P6-工具治理.md) | 工具治理:可见范围、人工确认、沙箱与密钥 | 10–12 人日 | P1、P2 |
|
||||
| P7 | [`P7-可观测与评测.md`](upgrade-plan/P7-可观测与评测.md) | 可观测、断言与评测:让「跑偏」可被发现 | 10–12 人日 | P0 |
|
||||
| P8 | [`P8-生产化.md`](upgrade-plan/P8-生产化.md) | 生产化:从「能跑」到「敢上线」 | 6–8 人日 | P0–P7 |
|
||||
|
||||
> 缺陷台账(F-01…F-76)、执行顺序、第 0 天清扫与迭代约定见 [`upgrade-plan/README.md`](upgrade-plan/README.md)。
|
||||
|
||||
# 5. 横向专题
|
||||
|
||||
前面 9 个阶段是"纵向切分"。这一章处理**横切所有阶段**的六件事:错误语义、观测协议、安全清单、成本模型、数据演进、测试策略。这些内容如果散落在各阶段里会互相打架,必须收敛成统一规范。
|
||||
|
||||
## 5.1 错误模型与错误码演进
|
||||
|
||||
### 5.1.1 现状
|
||||
|
||||
`internal/api/response/response.go` 与 `pkg/types/codes.go` 目前只有 4 个码:
|
||||
|
||||
| 码 | 含义 |
|
||||
|---|---|
|
||||
| `0000` | 成功 |
|
||||
| `0001` | 未知错误 |
|
||||
| `0002` | 参数非法 |
|
||||
| `0003` | Agent 不存在 |
|
||||
|
||||
前端(`frontend/src/api/agent.ts`)**按 `code === "0000"` 判断成功**,其余一律当失败展示 `info`。这意味着两件事:
|
||||
|
||||
1. `0000` 绝对不能再赋予其他含义;
|
||||
2. 新增的细分码只要非 `0000`,前端行为不会变坏(只是提示信息更粗)。
|
||||
|
||||
### 5.1.2 演进策略
|
||||
|
||||
**保留旧码字面值,在 4 位数字空间内扩展**,同一次响应同时给"粗码"与"细码":
|
||||
|
||||
```go
|
||||
type Error struct {
|
||||
Code string // 兼容码:0000/0001/0002/0003,前端与旧调用方只看这个
|
||||
SubCode string // 细分码:1001、2003、3003……新调用方可选使用
|
||||
Message string // 用户可读
|
||||
TraceID string // 排障用
|
||||
Details map[string]any // 仅 debug 模式返回
|
||||
}
|
||||
|
||||
func (e *Error) HTTPStatus() int
|
||||
```
|
||||
|
||||
响应体保持 `{code, info, data, sub_code?, trace_id?}` —— **新增字段全部可选**,旧前端解析不受影响。
|
||||
|
||||
### 5.1.3 错误码全集
|
||||
|
||||
| SubCode | 兼容码 | HTTP | 含义 | 典型来源 |
|
||||
|---|---|---|---|---|
|
||||
| `0000` | — | 200 | 成功 | — |
|
||||
| `1001` | 0002 | 400 | 参数非法 | 校验中间件 |
|
||||
| `1002` | 0001 | 404 | 资源不存在 | 通用 |
|
||||
| `1003` | 0001 | 403 | 无权限 | P6 策略 |
|
||||
| `1004` | 0001 | 401 | 未认证 | P8 鉴权 |
|
||||
| `1005` | 0001 | 429 | 限流 | P8 限流 |
|
||||
| `1006` | 0001 | 409 | 状态冲突 | P2 幂等 |
|
||||
| `1007` | 0001 | 504 | 上游超时 | P1 网关 |
|
||||
| `2001` | 0003 | 404 | Agent 不存在 | registry |
|
||||
| `2002` | 0001 | 404 | 会话不存在 | P2 |
|
||||
| `2003` | 0001 | 403 | 会话不属于当前用户 | P2 `Authorize` |
|
||||
| `2004` | 0001 | 410 | 会话已过期/归档 | P2 |
|
||||
| `3001` | 0001 | 404 | Run 不存在 | P0 |
|
||||
| `3002` | 0001 | 409 | Run 已取消 | P0 |
|
||||
| `3003` | 0001 | 422 | 预算耗尽 | P0 四闸门 |
|
||||
| `3004` | 0001 | 500 | Run 执行失败 | P0 |
|
||||
| `3005` | 0001 | 409 | 工作流图版本不匹配 | P5 |
|
||||
| `3006` | 0001 | 409 | Run 正在等待审批 | P6 |
|
||||
| `4001` | 0001 | 400 | 工具未注册 | P1 |
|
||||
| `4002` | 0002 | 400 | 工具参数不符合 schema | P1 |
|
||||
| `4003` | 0001 | 504 | 工具调用超时(重试耗尽) | P1 |
|
||||
| `4004` | 0001 | 403 | 工具调用被策略拒绝 | P6 |
|
||||
| `4005` | 0001 | 202 | 已挂起,等待人工审批 | P6 |
|
||||
| `4006` | 0001 | 403 | 审批被拒绝 | P6 |
|
||||
| `4007` | 0001 | 422 | 工具返回结果校验失败 | P1 |
|
||||
| `5001` | 0001 | 503 | 记忆检索不可用(已降级) | P3/P4 |
|
||||
| `6001` | 0001 | 503 | 存储不可用 | P2 |
|
||||
| `6002` | 0001 | 502 | 模型服务异常 | P1 |
|
||||
| `6003` | 0001 | 503 | 沙箱不可用 | P6 |
|
||||
|
||||
**规则**:
|
||||
|
||||
- 业务错误用 4 位 `sub_code`;基础设施错误统一落 `6xxx`,便于告警分流。
|
||||
- 每个 `sub_code` 必须有唯一归属的"产生点"(一个函数),禁止多处随性拼接。
|
||||
- 内部错误(panic、SQLError)**对外一律 `0001` + 通用文案**,细节只进日志。
|
||||
|
||||
### 5.1.4 映射与改造点
|
||||
|
||||
| 现状 | 改造后 |
|
||||
|---|---|
|
||||
| `writeError` in `internal/trigger/http/agent_handler.go` 未判 `err==nil`,会 panic | `response.Error(c, err)`,内部 `nil` 保护 + `AppError` 类型断言 + 未知错误归一 |
|
||||
| handler 里散落 `response.Fail(c, "0002", ...)` | 统一 `apperr.Invalid(...)` / `apperr.Forbidden(...)` 构造器 |
|
||||
| 引擎返回裸 `fmt.Errorf("tool %q: %w")` | `Failure` 结构(P1)→ 映射到 sub_code |
|
||||
|
||||
新增文件:`internal/pkg/apperr/errors.go`(错误构造器与分类)、`internal/api/response/error.go`(序列化与 HTTP 状态映射)。
|
||||
|
||||
---
|
||||
|
||||
## 5.2 事件与日志命名规范
|
||||
|
||||
### 5.2.1 事件类型命名
|
||||
|
||||
统一 `<domain>.<object>.<verb>`,全小写、点分隔、过去式动词:
|
||||
|
||||
```
|
||||
run.started run.finished run.canceled run.exhausted
|
||||
step.started step.finished
|
||||
llm.delta llm.usage
|
||||
tool.requested tool.result tool.retry tool.degraded
|
||||
approval.required approval.decided
|
||||
memory.assembled memory.compacted memory.written
|
||||
```
|
||||
|
||||
约束:
|
||||
|
||||
- 事件名是**契约**,进 CI 检查(`internal/domain/runtime/event.go` 里是唯一真相源,禁止字符串裸写)。
|
||||
- 每个事件的 `Payload` 用具体 struct,不用 `map[string]any`(否则重放器无法反序列化)。
|
||||
- 事件一旦发布不可改语义,只能新增版本(`tool.result.v2`)或新增字段。
|
||||
|
||||
### 5.2.2 日志字段契约
|
||||
|
||||
见 `P7-可观测与评测.md` 的 4.8.2 节。补充三条硬规则:
|
||||
|
||||
1. **`run_id` 必填**:任何与 Run 相关的日志缺 `run_id` 视为缺陷(用 lint 规则或 code review checklist 兜)。
|
||||
2. **禁止 PII 与密钥**:`Guard` 的 `Redact` 与日志 hook 共用一套正则。
|
||||
3. **错误日志必须带 `error_class`**,否则无法聚合统计("多少失败是上游超时"这类问题无法回答)。
|
||||
|
||||
### 5.2.3 指标命名
|
||||
|
||||
Prometheus 规范 `<namespace>_<subsystem>_<name>_<unit>`:
|
||||
|
||||
```
|
||||
agent_run_total{status,agent_id}
|
||||
agent_run_duration_seconds_bucket
|
||||
agent_step_total{kind}
|
||||
tool_call_total{tool,status,degraded_level}
|
||||
llm_tokens_total{model,type}
|
||||
llm_request_duration_seconds_bucket{model}
|
||||
memory_retrieve_total{hit}
|
||||
approval_pending_gauge
|
||||
budget_exhausted_total{reason}
|
||||
```
|
||||
|
||||
**标签基数控制**:`session_id`/`run_id`/`user_id` 绝不进标签(会导致基数爆炸),它们属于日志与 trace。
|
||||
|
||||
---
|
||||
|
||||
## 5.3 安全与合规清单(跨阶段汇总)
|
||||
|
||||
| # | 项 | 阶段 | 验收方式 |
|
||||
|---|---|---|---|
|
||||
| S1 | 未认证请求被拒(401) | P8 | 集成测试 |
|
||||
| S2 | 跨租户读写被拒(403) | P2/P8 | 双租户越权用例 |
|
||||
| S3 | 会话归属校验 | P2 | `Authorize` 单测 |
|
||||
| S4 | 工具调用必经策略引擎(无旁路) | P6 | 架构测试:`ToolRouter` 之外无人直接调 MCP client |
|
||||
| S5 | 高危工具默认需审批 | P6 | 策略示例用例 |
|
||||
| S6 | 沙箱隔离(无网/非 root/只读根/资源限额) | P6 | 逃逸用例(尝试写 `/etc`、访问外网) |
|
||||
| S7 | 密钥不落库、不落日志、不进 prompt | P6 | 日志扫描 + 代码评审 |
|
||||
| S8 | 工具结果注入防护 | P7 | 10 条注入样本 |
|
||||
| S9 | 输出内容安全(违规/PII/泄露系统提示) | P7 | Guard 用例 |
|
||||
| S10 | CORS 白名单、无凭证通配 | P8 | 预检请求测试 |
|
||||
| S11 | 请求体大小限制 | P8 | 超大 body 用例 |
|
||||
| S12 | 错误不回显内部细节 | P8 | 断言响应不含堆栈/SQL |
|
||||
| S13 | `.env.example` 无真实密钥,仓库有 secret 扫描 | P8 | gitleaks |
|
||||
| S14 | 依赖漏洞扫描(govulncheck/gosec) | P8 | CI |
|
||||
| S15 | 审计日志(谁在何时调了哪个高危工具) | P6/P7 | approval 表 + 事件 |
|
||||
|
||||
**合规提示**:若涉及个人信息,`agent_message` 与 `agent_memory_fact` 的 `content` 需支持加密列(MySQL `AES_ENCRYPT` 或应用层 KMS),并提供"按用户删除"接口(GDPR 式被遗忘权)——这一步在 P2 的 schema 设计中预留 `content_enc BLOB` 字段即可,不必首期实现。
|
||||
|
||||
---
|
||||
|
||||
## 5.4 成本模型
|
||||
|
||||
### 5.4.1 单次 Run 成本
|
||||
|
||||
```
|
||||
cost(run) = Σ_steps [ prompt_tokens × price_in(model)
|
||||
+ (1 - cache_hit_ratio) × ...
|
||||
+ completion_tokens × price_out(model) ]
|
||||
+ Σ_memory [ embed_tokens × price_embed(model) ]
|
||||
```
|
||||
|
||||
关键杠杆(按收益排序):
|
||||
|
||||
1. **前缀缓存**(收益最大):系统提示 + 工具定义 + pinned 记忆稳定不变 → 命中率可达 60–80%,输入成本降一个数量级。要求 P4 的装配顺序对缓存友好(稳定前缀在前)。
|
||||
2. **上下文压缩**:长会话不压缩,第 20 轮输入是第 1 轮的 5–8 倍;压缩后稳定在 1.2–1.5 倍。
|
||||
3. **模型分级**:抽取、摘要、评分用便宜模型;只有主对话与复杂推理用强模型。
|
||||
4. **结果截断**:工具返回 32KB → 8KB,直接省掉大量输入 token(同时降低噪声)。
|
||||
5. **预算硬顶**:`MaxTokens` 兜底,防止死循环烧钱。
|
||||
|
||||
### 5.4.2 模型分级表(配置化)
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
profiles:
|
||||
chat: {model: "gpt-4o-mini", price_in: 0.15, price_out: 0.60} # 主对话
|
||||
reason: {model: "gpt-4o", price_in: 2.50, price_out: 10.00} # 复杂推理,按需
|
||||
extract: {model: "gpt-4o-mini", price_in: 0.15, price_out: 0.60} # 记忆抽取
|
||||
summarize: {model: "gpt-4o-mini", price_in: 0.15, price_out: 0.60} # 压缩
|
||||
embed: {model: "text-embedding-3-small", price_in: 0.02, price_out: 0}
|
||||
judge: {model: "gpt-4o-mini", price_in: 0.15, price_out: 0.60} # 评测
|
||||
```
|
||||
|
||||
Agent 级可覆盖:`agent.llm_profile: chat`。
|
||||
|
||||
### 5.4.3 成本预算与告警
|
||||
|
||||
| 层级 | 阈值 | 动作 |
|
||||
|---|---|---|
|
||||
| Run | `MaxTokens` | 硬中止(`run.exhausted`) |
|
||||
| 会话 | 单会话累计 > X | 告警 + 提示用户开新会话 |
|
||||
| 租户/日 | 配置 | 告警 → 限流(降档模型)→ 熔断 |
|
||||
| 单 Run 异常 | > P99 × 3 | 记 Bad Case(可能是死循环前兆) |
|
||||
|
||||
### 5.4.4 成本可见性
|
||||
|
||||
`token_ledger` 按 `purpose` 拆分后,可以直接回答三个问题:
|
||||
|
||||
- 钱花在哪:主对话 vs 记忆抽取 vs 压缩 vs 评测(通常记忆抽取占 10–15%,若超过 30% 说明抽取过于频繁)。
|
||||
- 缓存省了多少:`cached_in / tokens_in`。
|
||||
- 哪个 Agent 最贵:按 `agent_id` 聚合,通常是"工具调用次数多 + 上下文长"的那个。
|
||||
|
||||
---
|
||||
|
||||
## 5.5 数据迁移与版本演进
|
||||
|
||||
### 5.5.1 迁移纪律
|
||||
|
||||
1. **只前滚**:不写 `down` 迁移(生产回滚靠备份 + 修数据,不靠 DDL 回退)。
|
||||
2. **命名**:`migrations/000N_<domain>_<desc>.up.sql`,N 三位递增,与阶段对应(0001=P0/0002=P1/0003=P2/0004=P3/0005=P5/0006=P6/0007=P7)。
|
||||
3. **可空跑**:每个迁移在空库与"已有数据"的库上都要能执行(用 `IF NOT EXISTS`、`DEFAULT`)。
|
||||
4. **大表加列**:MySQL 8 的 `ADD COLUMN ... DEFAULT` 是 instant/近 instant 的,但 `ALTER ... MODIFY` 可能重建表 → 超过 100 万行的表走 gh-ost/pt-osc,不在迁移文件里裸写。
|
||||
5. **索引**:新索引必须有明确的查询支撑(哪个 API、哪个条件),否则不加。
|
||||
6. **字符集**:统一 `utf8mb4` + `utf8mb4_0900_ai_ci`(中文与 emoji 安全)。
|
||||
|
||||
### 5.5.2 schema_version 与启动校验
|
||||
|
||||
```go
|
||||
// internal/app/bootstrap/migrate.go
|
||||
const expectedSchemaVersion = 7
|
||||
|
||||
func VerifySchema(ctx context.Context, db *gorm.DB) error {
|
||||
var v int
|
||||
db.Raw("SELECT MAX(version) FROM schema_migrations").Scan(&v)
|
||||
if v != expectedSchemaVersion {
|
||||
return fmt.Errorf("schema version mismatch: db=%d code=%d, run `cmd/migrate up`", v, expectedSchemaVersion)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
**启动时只校验,不自动迁移**——多实例同时启动时自动迁移会互相踩,且迁移失败会让服务起不来(宁可起不来也不要半迁移状态)。
|
||||
|
||||
### 5.5.3 backfill 任务
|
||||
|
||||
| 任务 | 阶段 | 说明 |
|
||||
|---|---|---|
|
||||
| 历史消息的 `pinned` 标记 | P4 上线后 | 按 pinning 5 规则回扫 `agent_message`,分批 1000 条,限速 |
|
||||
| `agent_memory_fact` 的 embedding | P3 上线后 | 对无 embedding 的 fact 补算,失败重试 3 次后置 `embedding_model='' ` 跳过 |
|
||||
| `prompt_tokens` 精确回填 | P4 上线后 | 用真实 tokenizer 重算历史值,与原估算值对比校准系数 |
|
||||
| 旧 `chat_sessions`(内存迁移) | P2 上线前 | 内存会话天然无持久化,无需迁移;但需在切换时**主动让旧会话失效**并提示重新开始 |
|
||||
|
||||
backfill 必须**幂等 + 可中断 + 可观测进度**(打日志 + 计数),否则跑一半失败无法续。
|
||||
|
||||
### 5.5.4 配置版本演进
|
||||
|
||||
YAML 加字段用"可选 + 默认值",语义变更用开关:
|
||||
|
||||
```yaml
|
||||
config_version: 2 # 新增;缺省视为 1
|
||||
```
|
||||
|
||||
`config_version` 的作用:当某个字段语义变化(例如 `max-iterations` 从"不生效"变成"生效"),可根据版本号决定新旧行为,逐版本收敛,避免"一升级所有 Agent 行为都变"。
|
||||
|
||||
---
|
||||
|
||||
## 5.6 测试金字塔
|
||||
|
||||
### 5.6.1 分层与目标
|
||||
|
||||
| 层 | 占比 | 数量级 | 运行时间 | 依赖 |
|
||||
|---|---|---|---|---|
|
||||
| 单元测试 | 70% | 300+ | < 10s | 无(mock 端口) |
|
||||
| 集成测试 | 20% | 60+ | < 2min | MySQL/Redis(testcontainers 或本地 compose) |
|
||||
| 评测(离线) | 10% | 30–50 用例 | < 5min | fake model(确定性) |
|
||||
| 评测(在线) | 少量 | 20 用例 | 5–10min | 真实模型,每日/发版 |
|
||||
|
||||
**当前状态是 0 测试**,所以第一阶段的"测试基建"比测试数量更重要:
|
||||
|
||||
- `go test ./... -race` 进 CI 的第一天起就阻断。
|
||||
- 表驱动测试成为默认写法(`cases := []struct{...}`)。
|
||||
- `internal/infrastructure/ai/fake_client.go`:可编程的假模型(按脚本返回 tool_calls / 文本),是 P0 之后所有测试的基础设施。
|
||||
|
||||
### 5.6.2 各阶段测试资产
|
||||
|
||||
| 阶段 | 必测项 | 测试类型 |
|
||||
|---|---|---|
|
||||
| P0 | 预算闸门 4 种终止、事件序列、ctx 取消、拆包后行为等价(golden) | 单测 + golden |
|
||||
| P1 | schema 校验、退避时序(fake clock)、9 类错误分类、降级阶梯、幂等 | 单测 |
|
||||
| P2 | 唯一活跃会话、seq 并发、越权、重启恢复、缓存失效 | 集成(真 MySQL) |
|
||||
| P3 | 切分质量、打分排序、去重消解、outbox 重投 | 单测 + 集成 |
|
||||
| P4 | 预算配额不超、装配顺序、压缩保真(pinned 不丢)、token 校准 | 单测 + 快照 |
|
||||
| P5 | 分支/join、节点重试、补偿逆序、续跑、真并发、循环终止 | 单测 + 集成 |
|
||||
| P6 | 策略求值顺序、审批三分支、沙箱逃逸、密钥不泄露 | 单测 + 集成 |
|
||||
| P7 | 断言拦截、重放确定性、注入拦截、成本核算 | 单测 + 评测 |
|
||||
| P8 | 鉴权、限流、优雅停机、健康检查、CORS | 集成 + 压测 |
|
||||
|
||||
### 5.6.3 契约测试(防前端回归)
|
||||
|
||||
三条不可破的契约用 golden JSON 锁定:
|
||||
|
||||
```go
|
||||
func TestContract(t *testing.T) {
|
||||
cases := []struct{ name, req, resp string }{
|
||||
{"config_list", "testdata/http/config_list.req.json", "testdata/http/config_list.resp.golden.json"},
|
||||
{"create_session", "testdata/http/create_session.req.json", "testdata/http/create_session.resp.golden.json"},
|
||||
{"chat", "testdata/http/chat.req.json", "testdata/http/chat.resp.golden.json"},
|
||||
}
|
||||
// 比对时忽略 data 里的时间戳与 sessionId 等易变字段
|
||||
}
|
||||
```
|
||||
|
||||
任何让这三个 golden 变化的改动,必须显式更新 golden 并在 PR 里说明——**这是"前端零改动"红线的机械保障**。
|
||||
|
||||
---
|
||||
|
||||
# 6. 与面试考点的映射
|
||||
|
||||
方案不是照抄面试题,但每个阶段都对应面试官真正会追问的能力。下面两张表是"能力 → 本项目落点 → 可展示证据"的对应关系,答辩时可直接按此组织话术。
|
||||
|
||||
## 6.1 对应面试官 A 的四个维度
|
||||
|
||||
| 维度 | 面试官的原话要求 | 本项目落点 | 可展示证据 |
|
||||
|---|---|---|---|
|
||||
| **数据层** | 知识库怎么清洗、按什么策略切分 | P3:7 步清洗流水线、5 种切分策略(含 parent-child 与 semantic)、混合检索 + MMR | `internal/domain/memory/chunk.go`、评测集里的检索命中率对比 |
|
||||
| **工具层** | 失败重试策略、超时怎么降级 | P1:9 类错误分类、指数退避 + full jitter、单工具超时、熔断、6 级降级阶梯、幂等键 | `internal/domain/tool/gateway.go` 的 12 步流水线;演示"工具 500 时 Agent 仍能给出可用回答" |
|
||||
| **记忆层** | 多轮上下文怎么管理、关键信息怎么召回 | P3 分层存储 + P4 预算装配、滚动摘要、pinned 规则、混合打分 | 20 轮对话 demo:第 1 轮的关键约束在第 20 轮仍然生效;`context_preview` 可视化每段 token 占比 |
|
||||
| **工程层** | Token 成本怎么控制、异常怎么收敛 | P0 预算四闸门 + P4 压缩 + P7 成本账本;P1 失败不扩散 + P0 终止策略 | 成本看板;`budget_exhausted` 指标;死循环用例被 `no_tool_loop` 拦截 |
|
||||
|
||||
**针对"六个人都撑不过三轮追问"的高频问题,本项目给出的具体答案**:
|
||||
|
||||
| 追问 | 常见弱答案 | 本项目的答案 |
|
||||
|---|---|---|
|
||||
| 工具报错怎么处理? | try-except | 错误先分类再决策:`invalid_input` 回灌模型自愈(1 次),`transient` 退避重试,`permission` 不重试直接拒绝,全部失败走 L5 结构化降级,**Run 不失败** |
|
||||
| 参数不符合 schema 怎么办? | 重试 | 三重防线:生成侧用真实 JSON Schema + `strict:true`;调用侧校验并回灌错误;结果侧校验 `OutputSchema` |
|
||||
| 下游超时怎么降级? | 抛异常 | 单工具超时 → 重试 → 熔断 → 备用工具 → 陈旧缓存 → 结构化降级,六层阶梯 |
|
||||
| 第二十轮丢信息? | 换大模型 | 三层机制:pinned 永久保留 + 滚动摘要 + 关键节点断言;压缩时 pinned 逐条比对,缺失则抽取式回填 |
|
||||
| 死循环怎么办? | 加 if 判断 | 四道闸门:步数、工具次数、token、墙钟;外加 `no_tool_loop` 断言做同参重复检测 |
|
||||
| 为什么用状态机不用 Chain? | 因为灵活 | 节点级状态机提供**可恢复性**(checkpoint + 幂等重放)与**可观测性**(每节点一个 Step),线性 Chain 两者都没有 |
|
||||
| 分支失败怎么回滚? | 重新跑整个流程 | Saga 逆序补偿,补偿动作幂等,失败不阻断后续补偿 |
|
||||
| Token 成本怎么控制? | 换便宜模型 | 四杠杆:前缀缓存友好排序、上下文压缩、模型分级、结果截断;外加预算硬顶与账本可观测 |
|
||||
| Bad Case 怎么复盘? | 看一下日志 | 三段闭环:事件流重放(发生了什么)→ LLM 记录确定性重放(为什么这么答)→ 回归用例(确保不再犯) |
|
||||
|
||||
## 6.2 对应面试官 B 的三个阶段
|
||||
|
||||
| 阶段 | 面试官定义的能力 | 本项目覆盖 | 对应章节 |
|
||||
|---|---|---|---|
|
||||
| **一阶段:跑通最小 Agent** | 系统边界、开发顺序 | 已有基础(YAML 装配 + LLM 循环);本期补齐"可组合的执行内核":Run/Step/Event、预算、ctx 透传 | P0(4.1)、P2(4.3) |
|
||||
| **二阶段:加入执行能力** | 领域 Skill、内置/自定义 Tool、工具权限、Sandbox、人工确认 | 工具网关(schema/重试/降级)+ 三层治理(可见范围/策略/审批)+ 沙箱 + 热更新 | P1(4.2)、P6(4.7) |
|
||||
| **三阶段:完整系统设计** | MCP、Worker、执行环境安全、Vault、文件、持久化记忆、Session 生命周期,统一工具可见范围与鉴权 | MCP 生命周期管理、outbox Worker、沙箱、Vault、记忆分层、Session 生命周期、统一策略与租户鉴权 | P6(4.7)、P2(4.3)、P3(4.4)、P7(4.8)、P8(4.9) |
|
||||
|
||||
**"统一处理"这一条特别说明**:面试官 B 强调"skill、MCP Server、大模型都使用统一处理工具可见范围、调用权限、人工确认和业务鉴权"。本项目的做法是——**所有工具最终都收敛成 `tool.Spec`**,无论来源是 MCP、Skill 还是内置 Go 函数,都经过同一个 `Gateway`,因此可见范围、策略、审批、审计只有一份实现。这是"架构收敛"而非"逐个特性叠加"的关键设计,也是最能体现设计能力的点。
|
||||
|
||||
## 6.3 一句话总结项目演进
|
||||
|
||||
> 原有的项目是"**把 YAML 翻译成 LLM 调用**";改造后是"**把一次用户请求变成一段可观测、可预算、可恢复、可审批、可评测的执行过程**"。前者是脚本,后者是运行时。
|
||||
|
||||
---
|
||||
|
||||
# 7. 里程碑与交付节奏
|
||||
|
||||
## 7.1 建议排期
|
||||
|
||||
假设 2 名后端(A 偏运行时/平台,B 偏数据/记忆),约 12 周(含 20% buffer):
|
||||
|
||||
| 周 | A(运行时 / 平台) | B(数据 / 记忆) | 里程碑 |
|
||||
|---|---|---|---|
|
||||
| W1–W2 | P0 运行时内核 + 拆包 | P2 表结构设计与迁移工具 | M1:新执行内核可跑通 draw-io Agent,事件可重放 |
|
||||
| W3–W4 | P1 工具网关 | P2 仓储实现 + Redis 缓存 | M2:工具故障注入下 Run 不失败 |
|
||||
| W5 | P1 收尾(熔断/幂等)+ 契约测试 | P2 API + 越权校验 | M3:会话重启不丢 |
|
||||
| W6–W7 | P3 知识库接入(kb_*)+ 检索端口 | P3 记忆抽取 outbox + 打分 | M4:跨会话记住用户偏好 |
|
||||
| W8 | P4 装配器 + 预算 | P4 压缩 + pinning | M5:20 轮对话不丢关键信息 |
|
||||
| W9 | P5 图执行(分支/join/真并发) | P5 检查点 + 续跑 | M6:分支失败可回滚、中断可续跑 |
|
||||
| W10–W11 | P6 策略引擎 + 审批 API | P6 沙箱 + Vault | M7:高危工具需人工确认 |
|
||||
| W11–W12 | P7 trace + 重放 + 断言 | P7 评测集 + Bad Case + CI | M8:评测通过率可量化,回归可发现 |
|
||||
| W12 | P8 鉴权 + 限流 + 优雅停机 | P8 迁移收尾 + 压测 | M9:可上线 |
|
||||
|
||||
单人执行则约 20–24 周,建议顺序不变但把 P6 与 P7 的顺序互换(先可观测再治理),因为观测能力能显著降低后续阶段的调试成本。
|
||||
|
||||
## 7.2 每阶段的 Demo(能演示才算完成)
|
||||
|
||||
| 阶段 | Demo 脚本 |
|
||||
|---|---|
|
||||
| P0 | 发起一个 Run,`curl` stream 看到 `run.started → step.started(llm) → llm.delta → tool.requested → step.finished → run.finished`;`cmd/replay` 打印时间线 |
|
||||
| P1 | 把工具 API 改成 500,Agent 自动重试 2 次后走降级,最终仍返回可读答案;日志里有 4 条 `tool.retry` |
|
||||
| P2 | 起两个进程,同一 user 并发 `create_session` 只产生 1 个会话;`kill -9` 后重启,历史消息仍在;用他人 sessionId 请求返回 403 |
|
||||
| P3 | 说"以后都用中文回答",换会话后仍生效;问知识库问题返回带引用的答案 |
|
||||
| P4 | 20 轮对话后 `context_preview` 显示摘要 + pinned 的 token 占比;第 1 轮的约束仍在 messages 里 |
|
||||
| P5 | 分支流程图:一个分支失败触发补偿,实例可续跑;并行节点耗时明显低于串行 |
|
||||
| P6 | 调用"导出用户数据"工具弹出审批(其实是 Run 挂起 + 事件),批准后继续;拒绝后 Agent 收到"被拒绝"并换方案 |
|
||||
| P7 | 关闭网络重放一次历史 Run,输出与原来一致;注入样本被拦截并生成 Bad Case |
|
||||
| P8 | 无 token 请求 401;`kill -TERM` 时在途请求正常完成;`/readyz` 在 DB 挂掉时 503 |
|
||||
|
||||
## 7.3 阶段"可讲的故事"
|
||||
|
||||
每个阶段都能支撑一段 2 分钟的面试叙事,避免"我做了个 Agent 项目"这种空话:
|
||||
|
||||
- **P0**:"我做的第一件事是把执行从'函数调用'变成'可恢复的运行时'——每个 Step 有状态、有预算、有事件,所以后面所有能力(重试、审批、续跑、回放)都有了挂载点。"
|
||||
- **P1**:"工具调用的可靠性不是 try-catch,而是先定义失败分类,再按分类决定重试/降级/拒绝;最关键的一点是工具故障不应该让整个 Run 失败。"
|
||||
- **P2**:"会话的并发正确性我一开始想用 Redis 锁,后来发现唯一索引才是真相,锁只是降低冲突;这个认知来自一次并发压测。"
|
||||
- **P3**:"记忆不是把历史全塞进 prompt,而是分层——事实、摘要、消息各司其职,检索分数要混入重要性和时间衰减。"
|
||||
- **P4**:"上下文工程的核心是预算分配,我做了一个装配器把窗口切成 7 段,并且顺序对前缀缓存友好,实测缓存命中率从 0 到 70%。"
|
||||
- **P5**:"从 Chain 换到状态机不是因为时髦,是因为要支持断点续跑——恢复的时候必须知道'哪个节点成功了、哪个正在跑'。"
|
||||
- **P6**:"权限不是 if-else,是三层:能不能看见、能不能调、在哪执行;deny 优先是安全默认。"
|
||||
- **P7**:"可观测不是打日志,是能确定性重放——重放让'线上问题'变成'本地 30 秒复现'。"
|
||||
- **P8**:"生产化的细节最能体现工程成熟度:优雅停机的关闭顺序、schema 版本校验、限流的四个维度。"
|
||||
|
||||
---
|
||||
|
||||
# 8. 风险登记册
|
||||
|
||||
| # | 风险 | 影响 | 触发信号 | 应对 |
|
||||
|---|---|---|---|---|
|
||||
| R1 | 执行内核重构引入回归 | 高 | golden 契约测试失败、行为差异 | 新旧内核双跑一个版本;`runtime.enabled=false` 一键回退;先做"行为等价"重构再改动语义 |
|
||||
| R2 | 记忆抽取质量差,写入噪声 | 中 | 用户反馈"记错事"、检索命中率低 | 抽取 prompt 加 few-shot + evidence_seq;低 importance 不写;提供"删除这条记忆"接口 |
|
||||
| R3 | 上下文压缩丢关键信息 | 高 | 断言 `must_include` 失败、用户重复说同一件事 | pinned 优先级 + 压缩后校验 + 保留原文可按需回捞;压缩比可配 |
|
||||
| R4 | 工作流改造破坏既有 draw-io 流程 | 高 | demo 结果与旧版不一致 | 旧 YAML 映射表 + `execution-mode=legacy` 默认 + 输出顺序固定;先并排跑再切换 |
|
||||
| R5 | 审批挂起导致 Run 长期占用资源 | 中 | 挂起 Run 数增长 | 挂起不占 goroutine(检查点 + 恢复);审批 TTL 自动拒绝;每日清理 |
|
||||
| R6 | 沙箱性能不达预期(容器启动慢) | 中 | 工具调用 P95 上升 | 容器池预热;只在 stdio/代码执行时用容器,只读工具用进程内 |
|
||||
| R7 | 迁移失败导致服务不可用 | 高 | 启动报 schema mismatch | 迁移与部署分离;先备份;灰度一个实例 |
|
||||
| R8 | 打开鉴权后前端 401 | 高 | 前端报错 | 前后端同发版;先 `report-only` 模式观测不阻断;灰度 |
|
||||
| R9 | 观测埋点拖慢主链路 | 低 | p95 上升 > 3% | 采样 + 异步 + 基准测试门禁 |
|
||||
| R10 | 存储增长失控(消息 + 事件 + LLM 记录) | 中 | 磁盘告警 | 分区表/按日分片、TTL 清理、冷数据归档 |
|
||||
| R11 | 过度工程化,交付周期失控 | 高 | 单个阶段超期 50% | 每阶段有最小可交付子集(下表);开关控制,可只交付核心 |
|
||||
|
||||
### 8.1 每阶段的最小可交付子集(防止过度工程)
|
||||
|
||||
| 阶段 | 必须做 | 可以后延 |
|
||||
|---|---|---|
|
||||
| P0 | Run/Step/Event + 预算 + ctx | JSONL 事件归档、replay CLI 的 timeline 格式美化 |
|
||||
| P1 | Spec + 校验 + 重试 + 失败不扩散 | 熔断、幂等、备用工具链、参数自愈 |
|
||||
| P2 | 消息持久化 + 归属校验 + 幂等创建 | Redis 缓存、归档/TTL、5 个只读 API 的完整分页 |
|
||||
| P3 | 分层表 + 写入 + 检索 | 知识库(kb_*)、parent-child 切分、MMR |
|
||||
| P4 | 预算装配 + 摘要压缩 | pinning 全部 5 规则、token 系数校准、context_preview |
|
||||
| P5 | 分支 + join + 节点重试 + 真循环 | Saga 补偿、断点续跑、子图 |
|
||||
| P6 | 策略引擎 + 审批 | 沙箱(先用 local)、Vault(先读环境变量)、MCP 热更新 |
|
||||
| P7 | 结构化日志 + 断言 + 评测骨架 | trace、确定性重放、Bad Case 表、成本账本 |
|
||||
| P8 | 鉴权 + 优雅停机 + healthz | 限流、迁移工具、压测、strict-config |
|
||||
|
||||
---
|
||||
|
||||
# 附录
|
||||
|
||||
## 附录 A:新增配置项总览
|
||||
|
||||
```yaml
|
||||
# configs/application.yaml 增量部分
|
||||
server:
|
||||
shutdown-timeout: 30s
|
||||
|
||||
runtime:
|
||||
enabled: true
|
||||
budget:
|
||||
max-steps: 24
|
||||
max-tool-calls: 16
|
||||
max-tokens: 200000
|
||||
max-wall-clock: 3m
|
||||
|
||||
tools:
|
||||
governance:
|
||||
enabled: false
|
||||
policy-file: configs/policies.yaml
|
||||
approval:
|
||||
enabled: false
|
||||
default-timeout: 30s
|
||||
retry: {max-attempts: 3, base-delay: 200ms, max-delay: 5s, jitter: 0.2}
|
||||
|
||||
skills:
|
||||
mode: inject # inject(默认,P1:注入 instruction)| expose(旧行为,P6 后移除)
|
||||
max-tokens: 4000 # 单个 Skill 注入正文的 token 上限
|
||||
|
||||
memory:
|
||||
enabled: false
|
||||
retrieval:
|
||||
top-k: 8
|
||||
scoring: {relevance: 0.55, importance: 0.25, recency: 0.20, half-life-days: 30}
|
||||
extraction:
|
||||
enabled: true
|
||||
model-profile: extract
|
||||
batch-size: 16
|
||||
worker-concurrency: 4
|
||||
|
||||
context:
|
||||
assembler:
|
||||
enabled: false
|
||||
window: 128000
|
||||
max-output: 4096
|
||||
safety-ratio: 0.05
|
||||
quotas: {pinned: 0.15, summary: 0.20, anchors: 0.15, recent: 0.40}
|
||||
compact:
|
||||
trigger-ratio: 0.60
|
||||
every-turns: 8
|
||||
max-tool-result-tokens: 8000
|
||||
|
||||
persistence:
|
||||
mode: memory # memory | mysql | mysql+redis
|
||||
message-ttl-days: 180
|
||||
|
||||
workflow:
|
||||
execution-mode: legacy # legacy | graph
|
||||
max-parallel: 4
|
||||
|
||||
obs:
|
||||
otel: {enabled: false, endpoint: ""}
|
||||
log: {level: info, format: json}
|
||||
llm-record: {enabled: false, sample-ratio: 0.05, ttl-days: 30}
|
||||
|
||||
auth:
|
||||
mode: none # none | api_key | jwt
|
||||
jwt: {issuer: "", secret-env: JWT_SECRET}
|
||||
|
||||
ratelimit:
|
||||
enabled: false
|
||||
tenant-qps: 50
|
||||
user-run-concurrency: 4
|
||||
agent-qps: 20
|
||||
```
|
||||
|
||||
## 附录 B:SSE 事件协议
|
||||
|
||||
新端点 `GET /api/v1/runs:stream?id=<run_id>&after=<seq>`:
|
||||
|
||||
```
|
||||
id: 1
|
||||
event: run.started
|
||||
data: {"run_id":"01J...","agent_id":"drawIoAgent","budget":{"max_steps":24}}
|
||||
|
||||
id: 2
|
||||
event: step.started
|
||||
data: {"step_id":"01J...","kind":"llm","name":"agent_analyst","index":1}
|
||||
|
||||
id: 3
|
||||
event: llm.delta
|
||||
data: {"text":"我来"}
|
||||
|
||||
id: 4
|
||||
event: tool.requested
|
||||
data: {"step_id":"01J...","tool":"mcp_baidu_search","args_digest":"ab12..."}
|
||||
|
||||
id: 5
|
||||
event: tool.result
|
||||
data: {"step_id":"01J...","status":"ok","bytes":842,"truncated":false}
|
||||
|
||||
id: 6
|
||||
event: run.finished
|
||||
data: {"status":"succeeded","usage":{"steps":5,"tool_calls":2,"prompt_tokens":8120,"completion_tokens":940}}
|
||||
|
||||
: heartbeat
|
||||
```
|
||||
|
||||
约定:
|
||||
|
||||
- `id` 是 `seq`,客户端断线重连带 `Last-Event-ID`(或 `after`),服务端从该 seq 之后重发 → **事件必须持久化才能续传**(P0 的 JSONL / P2 的 `agent_message` 之外的 `run_event` 表)。
|
||||
- `event` 名即 5.2.1 的规范名,客户端按 `event` 分派。
|
||||
- 心跳每 15s 一行注释帧(`: heartbeat`),防止代理空闲断连。
|
||||
- 结束帧之后服务端主动关闭流;`waiting_approval` 是**终态之一**(本段流结束),审批通过后客户端再连一次。
|
||||
- 旧的 `/api/v1/chat_stream` 保留,内部改为转接新流并映射为旧的裸文本帧(前端零改动)。
|
||||
|
||||
## 附录 C:新增数据表清单
|
||||
|
||||
| 表 | 阶段 | 用途 | 关键约束 |
|
||||
|---|---|---|---|
|
||||
| `agent_session` | P2 | 会话主体 | 唯一活跃会话 `uk_active_user_agent` |
|
||||
| `agent_message` | P2 | 消息与附件 | `uk_session_seq` |
|
||||
| `agent_run` | P2 | Run 记录 | `idx_session_created` |
|
||||
| `agent_memory_fact` | P3 | 语义事实 | `uk_content_hash`、软失效 |
|
||||
| `agent_memory_summary` | P3 | 情节摘要 | `uk_session_range` |
|
||||
| `agent_memory_job` | P3 | 抽取 outbox | `idx_status_next` |
|
||||
| `kb_document` | P3 | 知识库文档 | `uk_source_hash` |
|
||||
| `kb_chunk` | P3 | 分块与向量 | `idx_document` |
|
||||
| `wf_instance` | P5 | 工作流实例 | `idx_status` |
|
||||
| `wf_node_exec` | P5 | 节点执行记录 | `uk_node_attempt` |
|
||||
| `agent_approval` | P6 | 审批单 | `idx_status`、`expires_at` |
|
||||
| `agent_llm_record` | P7 | LLM 往返录制 | `uk_run_call` |
|
||||
| `agent_badcase` | P7 | Bad Case | `idx_status_severity` |
|
||||
| `token_ledger` | P7 | 成本账本 | `idx_tenant_day` |
|
||||
|
||||
## 附录 D:每阶段 DoD(完成定义)
|
||||
|
||||
**通用 DoD**(每阶段都必须满足):
|
||||
|
||||
- [ ] `go build ./...` 与 `go test ./... -race` 全绿
|
||||
- [ ] 三条 HTTP 契约 golden 未变(或变更有 PR 说明)
|
||||
- [ ] 新配置项有默认值,旧 YAML 不改也能跑
|
||||
- [ ] 有对应 demo 脚本与录制证据(截图/日志)
|
||||
- [ ] 涉及表的阶段有迁移文件 + 回滚说明(数据层)
|
||||
- [ ] `README.md` 与配置注释同步更新
|
||||
|
||||
**阶段专项 DoD**:
|
||||
|
||||
| 阶段 | 专项验收 |
|
||||
|---|---|
|
||||
| P0 | 预算四闸门各有一个用例;事件序列有 golden;ctx 取消能中断 LLM 流 |
|
||||
| P1 | 9 类错误各有用例;工具 500 时 Run 成功;schema 校验拦截非法参数 |
|
||||
| P2 | 并发建会话仅 1 个;越权 403;重启后消息完整 |
|
||||
| P3 | 记忆跨会话生效;检索有分数解释;抽取失败可重投 |
|
||||
| P4 | 装配不超预算;20 轮不丢 pinned;压缩有兜底 |
|
||||
| P5 | 分支/join/补偿/续跑各有 demo;并行确实更快 |
|
||||
| P6 | 策略 deny 优先;审批三分支;沙箱逃逸失败 |
|
||||
| P7 | 失败 Run 可确定性重放;断言能阻断;注入被拦 |
|
||||
| P8 | 401/403/429 正确;优雅停机无损;readyz 反映依赖 |
|
||||
|
||||
## 附录 E:术语表
|
||||
|
||||
| 术语 | 含义 |
|
||||
|---|---|
|
||||
| **Run** | 一次完整的 Agent 执行(一次用户请求 → 最终答复),有独立预算与状态 |
|
||||
| **Step** | Run 内的最小执行单元(一次 LLM 调用、一次工具调用、一个子 Agent) |
|
||||
| **Turn** | 对话轮次,一个 Turn 通常对应一个 Run |
|
||||
| **Budget** | 预算四元组:步数 / 工具次数 / token / 墙钟 |
|
||||
| **Checkpoint** | 可恢复的执行快照(当前节点、变量、已完成节点集合) |
|
||||
| **Degrade** | 降级,指上游能力不可用时仍给出可用结果的策略阶梯 |
|
||||
| **Pinned** | 永不压缩、始终置顶的关键信息(用户硬约束、身份偏好) |
|
||||
| **Compaction** | 上下文压缩,把长历史折叠为结构化摘要 |
|
||||
| **Facts** | 从对话中抽取出的结构化记忆(偏好、实体、决策、约束) |
|
||||
| **Policy** | 工具调用策略(allow / deny / require_approval) |
|
||||
| **HITL** | Human-in-the-loop,人工确认环节 |
|
||||
| **Saga** | 分布式事务补偿模式,用于工作流节点失败回滚 |
|
||||
| **Replay** | 重放,用事件流或录制响应重现一次执行 |
|
||||
| **Prefix Cache** | 前缀缓存,稳定的 prompt 前缀可被模型侧缓存以降本 |
|
||||
| **MMR** | Maximal Marginal Relevance,兼顾相关性与多样性的重排 |
|
||||
|
||||
---
|
||||
59
docs/mermaid/Agent执行引擎位置与启动装配.md
Normal file
59
docs/mermaid/Agent执行引擎位置与启动装配.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Agent 执行引擎位置与启动装配
|
||||
|
||||
> 源码:
|
||||
`internal/app/bootstrap/bootstrap.go`
|
||||
`internal/infrastructure/adk/adapter.go`
|
||||
|
||||
|
||||
Agent 执行引擎是“HTTP 请求进来后,真正驱动大模型和工具执行”的核心模块。它向上承接 ChatService,向下连接 OpenAI 客户端与 MCP 工具系统;项目启动时通过 Armory 装配链把它创建并注册到内存 Registry。
|
||||
|
||||
## 整体调用链图
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
HTTP["trigger/http/agent_handler.go"] --> Chat["domain/agent/service/chat/service.go"]
|
||||
Chat --> Runner["model.Runner"]
|
||||
Runner --> ADK["adk.Runner"]
|
||||
ADK --> Agent["adk.Agent"]
|
||||
Agent --> ChatModel["ports.ChatModel"]
|
||||
ChatModel --> Eino["ai/EinoChatModel"]
|
||||
Eino --> OpenAI["ai/OpenAIClient"]
|
||||
Agent --> ToolRouter["ports.ToolRouter"]
|
||||
ToolRouter --> MCP["ai/MCPToolRouter/MCPSSEClient"]
|
||||
```
|
||||
|
||||
- `HTTP`:Gin HTTP Handler,接收 `/chat` 与 `/chat_stream` 请求。
|
||||
- `Chat`:ChatService,负责会话管理和消息路由。
|
||||
- `Runner`:领域层定义的 Runner 接口。
|
||||
- `ADK`:`adk.Runner`,负责生命周期管理。
|
||||
- `Agent`:`adk.Agent`,负责 LLM 调用、工具调用和工作流编排。
|
||||
- `ChatModel`:实际由 `EinoChatModel` 实现,内部使用 `OpenAIClient`。
|
||||
- `ToolRouter`:实际由 `MCPToolRouter` 实现,内部使用 `MCPSSEClient`。
|
||||
|
||||
因此,这个文件是整条链路中的“调度核心”,而不是单纯的 HTTP 客户端或模型客户端。
|
||||
|
||||
---
|
||||
|
||||
## 启动装配时序图
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant B as bootstrap.Build
|
||||
participant F as adk.Factory
|
||||
participant Armory as Armory 装配链
|
||||
participant R as RunnerRegistry
|
||||
|
||||
B->>F: NewFactory()
|
||||
B->>F: UseToolRouter(MCPToolRouter)
|
||||
B->>Armory: AcceptArmoryAgents()
|
||||
Armory->>F: NewLLMAgent(config, chatModel)
|
||||
Armory->>F: NewSequentialAgent(config, subAgents)
|
||||
Armory->>F: NewRunner(appName, entryAgent, plugins)
|
||||
Armory->>R: Register(RegisteredAgent{Runner: runner})
|
||||
```
|
||||
|
||||
- `bootstrap.Build` 是启动装配入口。
|
||||
- `adk.Factory` 负责创建 Agent 与 Runner。
|
||||
- Armory 装配链负责把 YAML 配置解析并调用 Factory 创建对象。
|
||||
- `RunnerRegistry` 是 `ports.InMemoryAgentRegistry`,保存注册后的 Agent 与 Runner。
|
||||
- 整个装配发生在启动阶段,运行时只从 Registry 中取 Runner 执行。
|
||||
129
docs/mermaid/Agent执行引擎流式执行.md
Normal file
129
docs/mermaid/Agent执行引擎流式执行.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# Agent 执行引擎流式执行
|
||||
|
||||
> 源码:
|
||||
> `internal/trigger/http/agent_handler.go`
|
||||
> `internal/infrastructure/adk/adapter.go`
|
||||
> `internal/infrastructure/ai/openai_client.go`
|
||||
> `internal/infrastructure/ai/eino_adapter.go`
|
||||
|
||||
流式聊天请求会经过 HTTP → ChatService → Runner → Agent → ChatModel → OpenAIClient 多层。每层的“流式”语义不同:
|
||||
|
||||
- `Runner.Stream`:应用层流式入口,负责用户会话、插件通知和 channel 生命周期。
|
||||
- `Agent.streamLLM`:Agent 编排层流式执行,负责 Tool-Calling Loop、消息历史和工具结果回灌。
|
||||
- `OpenAIClient.Stream`:协议层流式实现,负责 HTTP SSE 解析、`[DONE]` 处理和工具调用分片累积。
|
||||
|
||||
---
|
||||
|
||||
## 流式执行分层
|
||||
|
||||
`Agent.stream` 中只有 `kind == "llm"` 走真正的逐 token 流式;workflow Agent 先完整执行再一次性推送结果。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
HTTP["trigger/http chatStream"] --> Chat["chat.Service.HandleCommandStream"]
|
||||
Chat --> RunnerStream["adk.Runner.Stream"]
|
||||
RunnerStream --> AgentStream["Agent.stream"]
|
||||
AgentStream -->|"kind == llm"| StreamLLM["Agent.streamLLM"]
|
||||
AgentStream -->|"kind != llm"| RunFallback["Agent.run(workflow 整体输出)"]
|
||||
StreamLLM --> ChatModelStream["ports.ChatModel.Stream"]
|
||||
ChatModelStream --> Eino["EinoChatModel.Stream"]
|
||||
Eino --> OpenAIClientStream["OpenAIClient.Stream"]
|
||||
OpenAIClientStream --> Upstream["OpenAI-compatible HTTP API"]
|
||||
```
|
||||
|
||||
| 层 | 方法 | 关注点 | 输出单位 |
|
||||
|---|---|---|---|
|
||||
| 协议 / 网络层 | `OpenAIClient.Stream` | HTTP SSE、OpenAI 协议、工具调用分片累积 | `ChatStreamEvent` |
|
||||
| Agent 编排层 | `Agent.streamLLM` | Tool-Calling Loop、消息历史、工具执行 | `string` 增量 |
|
||||
| 应用 / 会话层 | `Runner.Stream` | 用户、会话、插件、channel 生命周期 | `string` |
|
||||
|
||||
---
|
||||
|
||||
## streamLLM 流程图
|
||||
|
||||
`streamLLM` 在最多 4 轮循环中流式调用模型;边收文本边转发给前端;同时累积工具调用;如果有工具调用,就执行工具并把结果回灌,再进入下一轮。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start["streamLLM 开始"] --> Init["messages = system + user"]
|
||||
Init --> Loop{"iter < 4?"}
|
||||
Loop -->|是| Stream["chatModel.Stream(messages)"]
|
||||
Stream --> Read["循环读取 events / errs"]
|
||||
Read --> Delta{"ev.Delta 非空?"}
|
||||
Delta -->|是| Out["finalText += Delta<br/>out <- Delta"]
|
||||
Delta -->|否| ToolCheck
|
||||
Out --> ToolCheck{"ev.ToolCalls 非空?"}
|
||||
ToolCheck -->|是| Collect["toolCalls 累加"]
|
||||
ToolCheck -->|否| Read
|
||||
Collect --> Read
|
||||
Read --> End{"events 关闭 / errs / ctx.Done"}
|
||||
End --> StreamErr{"streamErr?"}
|
||||
StreamErr -->|有| Err["返回错误"]
|
||||
StreamErr -->|无| HasTool{"len(toolCalls) == 0?"}
|
||||
HasTool -->|是| DoneCheck{"done?"}
|
||||
DoneCheck -->|是| Nil["返回 nil"]
|
||||
DoneCheck -->|否| Err2["stream closed without completion"]
|
||||
HasTool -->|否| Append["追加 assistant + tool 结果"]
|
||||
Append --> Loop
|
||||
Loop -->|否| MaxErr["超过最大迭代次数"]
|
||||
```
|
||||
|
||||
> 注意:`Runner.Stream` 当前使用 `context.Background()`,所以图中的 `ctx.Done()` 分支实际上很难触发。
|
||||
|
||||
---
|
||||
|
||||
## 流式调用时序图
|
||||
|
||||
从 HTTP 到 OpenAIClient 的完整流式链路如下,包含一轮工具调用后的二次模型请求。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP Handler
|
||||
participant C as ChatService
|
||||
participant R as Runner.Stream
|
||||
participant A as Agent.streamLLM
|
||||
participant CM as ChatModel.Stream
|
||||
participant O as OpenAIClient.Stream
|
||||
|
||||
H->>C: POST /chat_stream
|
||||
C->>R: Runner.Stream(userID, sessionID, content)
|
||||
R->>R: notifyPlugins()
|
||||
R->>A: Agent.stream(ctx, content, outputs)
|
||||
A->>CM: Stream(ctx, messages)
|
||||
CM->>O: Stream(ctx, messages, tools)
|
||||
O-->>CM: ChatStreamEvent{Delta}
|
||||
CM-->>A: ChatStreamEvent{Delta}
|
||||
A-->>R: out <- Delta
|
||||
R-->>H: outputs <- Delta
|
||||
H-->>H: c.SSEvent("message", Delta)
|
||||
O-->>CM: ChatStreamEvent{ToolCalls}
|
||||
CM-->>A: ChatStreamEvent{ToolCalls}
|
||||
A->>A: executeToolCalls()
|
||||
A->>CM: Stream(ctx, messages + tool result)
|
||||
O-->>CM: ChatStreamEvent{Done}
|
||||
CM-->>A: ChatStreamEvent{Done}
|
||||
A-->>R: return nil
|
||||
R-->>H: close(outputs)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Channel 生命周期
|
||||
|
||||
三层各自创建和关闭自己的 channel,遵循“谁创建、谁关闭”的原则。
|
||||
|
||||
| 层 | 创建的 channel | 关闭者 | 消费方 |
|
||||
|---|---|---|---|
|
||||
| `OpenAIClient.Stream` | `events`、`errs` | 它自己的 goroutine defer | `EinoChatModel` / `streamLLM` |
|
||||
| `EinoChatModel.Stream` | 不创建,直接透传 | 不负责 | `streamLLM` |
|
||||
| `streamLLM` | 不创建,使用传入的 `out` | 不负责 | `Runner.Stream` |
|
||||
| `Runner.Stream` | `outputs`、`errs` | 它自己的 goroutine defer | HTTP Handler |
|
||||
|
||||
数据单位会逐层“降噪”:
|
||||
|
||||
```text
|
||||
HTTP SSE 原始 chunk
|
||||
→ ChatStreamEvent(Delta / ToolCalls / Done)
|
||||
→ 纯文本字符串
|
||||
→ SSE message 事件
|
||||
```
|
||||
141
docs/mermaid/Agent执行引擎结构与策略分发.md
Normal file
141
docs/mermaid/Agent执行引擎结构与策略分发.md
Normal file
@@ -0,0 +1,141 @@
|
||||
# Agent 执行引擎结构与策略分发
|
||||
|
||||
> 源码:
|
||||
`internal/infrastructure/adk/adapter.go`
|
||||
|
||||
|
||||
`adk` 包内部由 `Factory`、`Agent`、`Runner` 三层组成:Factory 负责创建对象,Agent 负责按 kind 执行,Runner 负责生命周期管理。
|
||||
|
||||
## 三层结构图
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Factory["adk.Factory(创建层)"]
|
||||
F["sessionCounter / plugins / router"]
|
||||
F -->|NewLLMAgent| LA["Agent{kind:llm}"]
|
||||
F -->|NewSequentialAgent| SA["Agent{kind:sequential}"]
|
||||
F -->|NewParallelAgent| PA["Agent{kind:parallel}"]
|
||||
F -->|NewLoopAgent| LO["Agent{kind:loop}"]
|
||||
F -->|NewRunner| R["Runner"]
|
||||
end
|
||||
|
||||
subgraph Agent["adk.Agent(执行层)"]
|
||||
LA -->|runWithVars| LLM["runLLM"]
|
||||
SA -->|runWithVars| SEQ["runSequential"]
|
||||
PA -->|runWithVars| FAN["runFanOut"]
|
||||
LO -->|runWithVars| FAN
|
||||
end
|
||||
|
||||
subgraph Runner["adk.Runner(生命周期层)"]
|
||||
R -->|Run| RUN["agent.run"]
|
||||
R -->|Stream| STREAM["agent.stream"]
|
||||
R -->|notifyPlugins| PLUGIN["RunnerPlugin"]
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
| 层 | 核心类型 | 职责 |
|
||||
|---|---|---|
|
||||
| 创建层 | `Factory` | 创建 Agent / Runner,注入 ToolRouter |
|
||||
| 执行层 | `Agent` | 根据 `kind` 选择 `runLLM` / `runSequential` / `runFanOut` |
|
||||
| 生命周期层 | `Runner` | 插件通知、会话 ID 生成、普通/流式执行入口 |
|
||||
|
||||
设计意图:创建与执行分离,执行与生命周期分离,依赖通过外部注入。
|
||||
|
||||
---
|
||||
|
||||
## 执行策略分发图
|
||||
|
||||
`runWithVars` 是 Agent 执行的分发中心。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Run["Agent.run"] --> RW["Agent.runWithVars"]
|
||||
RW --> Switch{"kind?"}
|
||||
Switch -->|"llm"| RunLLM["runLLM"]
|
||||
Switch -->|"sequential"| RunSeq["runSequential"]
|
||||
Switch -->|"loop / parallel"| RunFan["runFanOut"]
|
||||
```
|
||||
|
||||
### 代码对应
|
||||
|
||||
```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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| kind | 执行方法 | 说明 |
|
||||
|---|---|---|
|
||||
| `llm` | `runLLM` | 普通大模型对话 + Tool-Calling Loop |
|
||||
| `sequential` | `runSequential` | 按顺序执行子 Agent,并通过 outputKey 传值 |
|
||||
| `loop` | `runFanOut` | 当前实现按 fan-out 聚合子 Agent 输出 |
|
||||
| `parallel` | `runFanOut` | 当前实现按 fan-out 聚合子 Agent 输出 |
|
||||
|
||||
> 注意:当前 `loop` 与 `parallel` 都走 `runFanOut`,并不是真正的并发执行。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 为什么 AgentFactory 和 RunnerFactory 是同一个 Factory
|
||||
|
||||
`bootstrap.Build()` 中只创建了一个 `*adk.Factory`,同时把它作为 `ports.AgentFactory` 和 `ports.RunnerFactory` 传入 Armory:
|
||||
|
||||
```go
|
||||
agentFactory := adk.NewFactory()
|
||||
agentFactory.UseToolRouter(toolRouter)
|
||||
runnerFactory := agentFactory
|
||||
```
|
||||
|
||||
调用方通过窄接口依赖 Factory,但底层共享同一个会话计数器、工具路由器和插件注册表。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B["bootstrap.Build"] -->|"agentFactory"| F["*adk.Factory"]
|
||||
B -->|"runnerFactory"| F
|
||||
F -->|"实现"| AF["ports.AgentFactory"]
|
||||
F -->|"实现"| RF["ports.RunnerFactory"]
|
||||
AN["Armory.AgentNode / WorkflowNode"] --> AF
|
||||
RN["Armory.RunnerNode"] --> RF
|
||||
```
|
||||
|
||||
好处:
|
||||
|
||||
1. `sessionCounter` 全局唯一,多个 Runner 不会生成重复会话 ID。
|
||||
2. `router` 只注入一次,所有 Agent 共享同一个工具路由器。
|
||||
3. Runner 可以对同一个 Factory 产出的 `*Agent` 做类型断言和编排。
|
||||
4. 外部按需依赖 `ports.AgentFactory` 或 `ports.RunnerFactory`,不依赖具体类型。
|
||||
|
||||
---
|
||||
|
||||
## Sequential 变量作用域链
|
||||
|
||||
Sequential 工作流通过 `output-key` 把上一步的完整输出写入 `scope`,后续 Agent 的 instruction 在 `applyVars` 时替换 `{key}`。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
R["Agent.run<br/>vars = {}"] --> RW["runWithVars"]
|
||||
RW --> S["runSequential<br/>scope := cloneVars(vars)"]
|
||||
S --> S1["sub1.runWithVars(scope)"]
|
||||
S1 -->|"outputKey: analysis_result"| Scope["scope"]
|
||||
Scope -->|"applyVars(instruction, scope)"| S2["sub2.runWithVars(scope)"]
|
||||
S2 -->|"outputKey: draft_diagram"| Scope
|
||||
Scope -->|"applyVars(instruction, scope)"| S3["sub3.runWithVars(scope)"]
|
||||
S3 -->|"最终输出"| Out["返回 last"]
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- `run` 是无变量入口,内部传入 `map[string]string{}` 作为初始作用域。
|
||||
- `runWithVars` 才是带变量作用域的递归入口。
|
||||
- Sequential 每次使用 `cloneVars` 复制作用域,避免影响外部调用方。
|
||||
- `loop` / `parallel` 走 `runFanOut`,所有子 Agent 共用同一份变量,不会逐级累加 `output-key`。
|
||||
143
docs/mermaid/Agent执行引擎运行时流程.md
Normal file
143
docs/mermaid/Agent执行引擎运行时流程.md
Normal file
@@ -0,0 +1,143 @@
|
||||
# Agent 执行引擎运行时流程
|
||||
|
||||
> 源码:
|
||||
`internal/trigger/http/agent_handler.go`
|
||||
`internal/domain/agent/service/chat/service.go`
|
||||
`internal/infrastructure/adk/adapter.go`
|
||||
|
||||
运行时流程包含两部分:一是单个 LLM Agent 内部的 Tool-Calling Loop,二是一次聊天请求从 HTTP 到 Runner、Agent、模型、工具的整体时序。
|
||||
|
||||
## Tool-Calling Loop 流程图
|
||||
|
||||
`runLLM` 实现了大模型“思考 → 调用工具 → 看到结果 → 再思考”的循环,最多迭代 4 轮。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start["初始 messages: system + user"] --> Gen["ChatModel.Generate"]
|
||||
Gen --> Check{"有 ToolCalls?"}
|
||||
Check -->|"无"| Return["返回 reply.Content"]
|
||||
Check -->|"有"| AppendAssistant["追加 assistant tool_calls"]
|
||||
AppendAssistant --> Exec["executeToolCalls"]
|
||||
Exec --> AppendTool["追加 tool 结果"]
|
||||
AppendTool --> Loop{"iter < 4?"}
|
||||
Loop -->|"是"| Gen
|
||||
Loop -->|"否"| Error["超过最大迭代次数"]
|
||||
```
|
||||
|
||||
### 代码对应
|
||||
|
||||
```go
|
||||
func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
|
||||
for iter := 0; iter < maxToolCallIterations; iter++ {
|
||||
reply, err := a.chatModel.Generate(ctx, messages)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(reply.ToolCalls) == 0 {
|
||||
return reply.Content, nil
|
||||
}
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls})
|
||||
toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
messages = append(messages, toolMessages...)
|
||||
}
|
||||
return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
|
||||
}
|
||||
```
|
||||
|
||||
### 关键步骤
|
||||
|
||||
1. 构建初始消息:`system` + `user`。
|
||||
2. 调用 `ChatModel.Generate`。
|
||||
3. 如果没有工具调用,直接返回文本结果。
|
||||
4. 如果有工具调用,把 assistant 消息加入历史。
|
||||
5. 执行工具调用并追加 `tool` 角色消息。
|
||||
6. 回到第 2 步,最多 4 轮。
|
||||
|
||||
---
|
||||
|
||||
## 请求执行时序图
|
||||
|
||||
一次普通聊天请求从 HTTP 进入,经过 ChatService 找到 Runner,再由 Agent 调用大模型和工具,最终返回结果。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP Handler
|
||||
participant C as ChatService
|
||||
participant R as adk.Runner
|
||||
participant A as adk.Agent
|
||||
participant CM as EinoChatModel/OpenAIClient
|
||||
participant TR as MCPToolRouter/MCPSSEClient
|
||||
|
||||
H->>C: HandleMessage()
|
||||
C->>R: Runner.Run()
|
||||
R->>R: notifyPlugins()
|
||||
R->>A: agent.run()
|
||||
A->>A: runWithVars()
|
||||
A->>CM: ChatModel.Generate()
|
||||
CM-->>A: ChatReply{ToolCalls}
|
||||
A->>TR: ToolRouter.CallTool()
|
||||
TR-->>A: tool result
|
||||
A->>CM: Generate(messages + tool result)
|
||||
CM-->>A: final content
|
||||
A-->>R: output
|
||||
R-->>C: []string{output}
|
||||
C-->>H: JSON response
|
||||
```
|
||||
|
||||
| 参与者 | 实际类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `HTTP Handler` | `internal/trigger/http/agent_handler.go` | 接收 `/chat` 请求 |
|
||||
| `ChatService` | `internal/domain/agent/service/chat/service.go` | 会话路由 |
|
||||
| `adk.Runner` | `internal/infrastructure/adk/adapter.go` | 生命周期管理、插件通知 |
|
||||
| `adk.Agent` | `internal/infrastructure/adk/adapter.go` | 执行核心 |
|
||||
| `EinoChatModel/OpenAIClient` | `internal/infrastructure/ai/*` | 大模型调用 |
|
||||
| `MCPToolRouter/MCPSSEClient` | `internal/infrastructure/ai/*` | 工具调用 |
|
||||
|
||||
> 图中展示的是包含一轮工具调用的场景。实际运行时可能根据 Tool-Calling Loop 进行多轮工具调用,直到模型返回最终文本。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Runner 视角的完整链路(含 Registry)
|
||||
|
||||
前面的时序图侧重“Agent 内部如何调模型和工具”。下面这张图把 `AgentRegistry` 的查找过程显式画出来,更侧重 Runner 在会话链路中的位置。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant Handler as HTTP Handler
|
||||
participant Chat as ChatService
|
||||
participant Registry as AgentRegistry
|
||||
participant Runner as adk.Runner
|
||||
participant Agent as adk.Agent
|
||||
participant Model as ChatModel
|
||||
participant Tool as ToolRouter
|
||||
|
||||
Client->>Handler: POST /api/v1/chat
|
||||
Handler->>Chat: HandleMessage(agentID, userID, sessionID, message)
|
||||
Chat->>Registry: Get(agentID)
|
||||
Registry-->>Chat: RegisteredAgent{Runner}
|
||||
Chat->>Runner: Run(userID, sessionID, content)
|
||||
Runner->>Runner: notifyPlugins()
|
||||
Runner->>Agent: run(content)
|
||||
Agent->>Model: Generate(messages)
|
||||
Model-->>Agent: ToolCalls
|
||||
Agent->>Tool: CallTool(...)
|
||||
Tool-->>Agent: result
|
||||
Agent->>Model: Generate(messages + tool result)
|
||||
Model-->>Agent: final content
|
||||
Agent-->>Runner: output
|
||||
Runner-->>Chat: []string{output}
|
||||
Chat-->>Handler: outputs
|
||||
Handler-->>Client: JSON response
|
||||
```
|
||||
|
||||
关键点:
|
||||
|
||||
- `ChatService` 不直接依赖 `adk.Runner`,只依赖 `model.Runner` 接口。
|
||||
- `Runner` 不关心模型和工具的协议细节,只负责会话与生命周期。
|
||||
- 入口 Agent 通常是一个 workflow Agent,内部再编排多个子 Agent。
|
||||
23
docs/mermaid/README.md
Normal file
23
docs/mermaid/README.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# Mermaid 图表阅读索引
|
||||
|
||||
本目录下的文档用于配合阅读 Agent 执行引擎源码:
|
||||
|
||||
- 源码文件:`../../internal/infrastructure/adk/adapter.go`
|
||||
- 相关端口:`../../internal/domain/agent/ports/ports.go`
|
||||
- 相关入口:`../../internal/app/bootstrap/bootstrap.go`
|
||||
- 流式协议:`../../internal/infrastructure/ai/openai_client.go`
|
||||
- HTTP / 会话入口:`../../internal/trigger/http/agent_handler.go`、`../../internal/domain/agent/service/chat/service.go`
|
||||
|
||||
| 文件 | 主要内容 |
|
||||
|---|---|
|
||||
| [Agent执行引擎位置与启动装配.md](Agent执行引擎位置与启动装配.md) | 执行引擎在项目中的位置、启动装配时序 |
|
||||
| [Agent执行引擎结构与策略分发.md](Agent执行引擎结构与策略分发.md) | Factory / Agent / Runner 三层结构、策略分发、Factory 双接口、Sequential 变量作用域 |
|
||||
| [Agent执行引擎运行时流程.md](Agent执行引擎运行时流程.md) | Tool-Calling Loop、一次请求的完整执行时序、Runner 视角的 Registry 链路 |
|
||||
| [Agent执行引擎流式执行.md](Agent执行引擎流式执行.md) | Runner.Stream / streamLLM / OpenAIClient.Stream 的分层关系、流程图与时序图 |
|
||||
|
||||
建议阅读顺序:
|
||||
|
||||
1. 先看 `Agent执行引擎位置与启动装配.md`
|
||||
2. 再看 `Agent执行引擎结构与策略分发.md`
|
||||
3. 接着看 `Agent执行引擎运行时流程.md`
|
||||
4. 最后看 `Agent执行引擎流式执行.md`
|
||||
572
docs/upgrade-plan/P0-运行时内核.md
Normal file
572
docs/upgrade-plan/P0-运行时内核.md
Normal file
@@ -0,0 +1,572 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P0 · 运行时内核:让每一次执行都成为一等公民 | **预估**:8–10 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.1 节
|
||||
> **本阶段收编缺陷**:F-01、F-02、F-03、F-04、F-05、F-06、F-07、F-08、F-09(共 9 条,明细见文末附录)
|
||||
> 下一阶段:[`P1`](P1-工具网关.md)
|
||||
|
||||
|
||||
# 4.1 P0 · 运行时内核:让每一次执行都成为一等公民
|
||||
|
||||
## 目标
|
||||
|
||||
把"一次函数调用"升级为"一个有状态、有预算、可观测、可中断、可重放的 Run"。这是后面所有能力的地基:没有 Step 就没有节点级重试(P5),没有事件就没有回放(P7),没有 ctx 就没有流式取消。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 证据 | 问题 |
|
||||
|---|---|
|
||||
| `(*Runner).Run`、`(*Runner).Stream`、`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 三处 `context.Background()`,请求取消传不进去(F-02) |
|
||||
| `maxToolCallIterations` in `internal/infrastructure/adk/adapter.go` | `maxToolCallIterations = 4` 硬编码(F-09) |
|
||||
| `adk/adapter.go` 全文 572 行 | 定义/执行/流程/插件混在一个文件,无法单测 |
|
||||
| `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` | 插件输出走 `fmt.Printf`,无 run 上下文(F-41) |
|
||||
| `armory/service.go` | map 遍历装配,顺序随机(F-04) |
|
||||
| `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 <id>` 能还原出完整 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` 类低价值事件并计数 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(9 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-01 流式取消时 `OpenAIClient.Stream` goroutine 泄漏
|
||||
|
||||
**位置**:`Stream` in `internal/infrastructure/ai/openai_client.go`,尤其:
|
||||
|
||||
```go
|
||||
if delta.Content != "" {
|
||||
select {
|
||||
case events <- ports.ChatStreamEvent{Delta: delta.Content}:
|
||||
case <-ctx.Done():
|
||||
errs <- ctx.Err()
|
||||
return
|
||||
}
|
||||
}
|
||||
...
|
||||
emitToolCalls(events, toolCallBuf) // <- 无 ctx 保护,直接阻塞写入
|
||||
events <- ports.ChatStreamEvent{Done: true} // <- 无 ctx 保护
|
||||
```
|
||||
|
||||
**问题概述**:`emitToolCalls` 和最后的 `Done` 事件都是无保护的阻塞发送。当消费方(`streamLLM`)因 `ctx.Done()` 提前退出、不再读取 `events` 时,若 `events` 缓冲(8)已满,生产 goroutine 会永久阻塞在 `events <- ...`,导致 goroutine 泄漏。
|
||||
|
||||
**影响**:客户端频繁断开/取消时,泄漏的 goroutine 与底层 HTTP 连接会持续累积。
|
||||
|
||||
**修复方案**:给 `emitToolCalls` 传入 ctx 并用 `select`;对 `[DONE]` 分支的发送也加 `select`:
|
||||
|
||||
```go
|
||||
func emitToolCalls(ctx context.Context, events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) {
|
||||
...
|
||||
select {
|
||||
case events <- ports.ChatStreamEvent{ToolCalls: calls}:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **归属**:P0 | **状态**:🟡 | **历史编号**:P0-6
|
||||
>
|
||||
> P0 的 ctx 透传能收口;`emitToolCalls` 与 `Done` 的裸发送要补 `select ctx.Done()`,验收项为「取消后 goroutine 数回落」
|
||||
|
||||
### F-02 HTTP 请求 context 未传递到 Agent
|
||||
|
||||
**位置**:`Run` in `internal/infrastructure/adk/adapter.go` `Runner.Run`、`:429-453` `Runner.Stream`、`:460-470` `notifyPlugins`(全部用 `context.Background()`)
|
||||
|
||||
**问题概述**:`Runner.Run/Stream/notifyPlugins` 都丢弃了调用方 context,改用 `context.Background()`。
|
||||
|
||||
**影响**:客户端断开、请求超时都无法中断正在进行的 LLM/工具调用,资源被无效占用;`application.yaml` 的 `llm.request-timeout` 只能覆盖单次 HTTP,不能覆盖整个请求生命周期。
|
||||
|
||||
**修复方案**:`Runner` 接口签名增加 `ctx context.Context`(`model.Runner`),`chat.Service` 各方法也加 ctx,HTTP handler 传 `c.Request.Context()`,一路透传到 `runLLM` / `executeToolCalls` / `notifyPlugins`。
|
||||
|
||||
> **归属**:P0 | **状态**:✅ | **历史编号**:P1-4
|
||||
|
||||
### F-03 `DynamicContext.agentGroup` 名称覆盖与静默跳过
|
||||
|
||||
**位置**:`AddAgent` in `internal/domain/agent/service/armory/context.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `agentGroup[agent.Name()]` 同名覆盖,后注册的赢;
|
||||
- `QueryAgentList` 对不存在的名字静默跳过,可能构造出缺子 Agent 甚至空 workflow。
|
||||
|
||||
**影响**:配置错误被掩盖,运行时行为与预期不符。
|
||||
|
||||
**修复方案**:`AddAgent` 检测重名并报错(或在 loader 校验 Agent 唯一性);`QueryAgentList` 返回缺失的名称列表,由调用方决定是否报错。
|
||||
|
||||
> **归属**:P0 | **状态**:✅ | **历史编号**:P2-2
|
||||
>
|
||||
> P0 确定性装配 + P8 `--strict-config` 重名即报错
|
||||
|
||||
### F-04 装配与加载顺序不确定
|
||||
|
||||
**位置**:`AcceptArmoryAgents` in `internal/domain/agent/service/armory/service.go`、`LoadAgentTables` in `internal/app/config/loader.go`、`loadAgentTables` in `internal/app/bootstrap/bootstrap.go`
|
||||
|
||||
**问题概述**:多处 `for name, table := range tables`,Go map 遍历顺序随机。
|
||||
|
||||
**影响**:多表装配顺序、注册顺序不稳定;对依赖注册顺序的扩展(如后注册覆盖前注册)会不确定。
|
||||
|
||||
**修复方案**:把 `tables` 改为按 name 排序后的切片再遍历,保证确定性。
|
||||
|
||||
> **归属**:P0 | **状态**:✅ | **历史编号**:P2-3
|
||||
|
||||
### F-05 Service 层方法无 context
|
||||
|
||||
**位置**:`internal/domain/agent/service/chat/service.go` 全部方法
|
||||
|
||||
**问题概述**:`CreateSession`、`HandleMessage`、`HandleCommand`、`HandleMessageStream`、`HandleCommandStream` 都不接收 context。
|
||||
|
||||
**影响**:无法实现超时/取消,与 F-02 同源。
|
||||
|
||||
**修复方案**:统一加 `ctx context.Context` 作为首参,并透传。
|
||||
|
||||
> **归属**:P0 | **状态**:✅ | **历史编号**:P2-17
|
||||
|
||||
### F-06 `AgentFactory` 为三种 workflow 各定义一个方法
|
||||
|
||||
**为什么优化**:新增 workflow 类型要同时改端口、实现、Armory 节点,扩展成本高。
|
||||
|
||||
**方案**:统一为 `NewWorkflowAgent(ctx, workflowType, config, subAgents)`,由实现内部按 type 分派;或让 `AgentFactory` 只保留 `NewLLMAgent` + `NewWorkflowAgent`。
|
||||
|
||||
**改动量**:小-中(端口 + factory + 三个 node 文件)。
|
||||
|
||||
**影响**:扩展新 workflow 只需改一处;接口更内聚。
|
||||
|
||||
> **归属**:P0 | **状态**:✅ | **历史编号**:P3-4
|
||||
|
||||
### F-07 `InMemoryAgentRegistry.Register` 无校验且恒返回 nil
|
||||
|
||||
**为什么优化**:`Register` 声明返回 error 但永远 nil;空 `AgentID` 会互相覆盖到 `""`。
|
||||
|
||||
**方案**:校验 `AgentID` 非空、重复注册报错(或显式允许覆盖)。
|
||||
|
||||
**改动量**:很小。
|
||||
|
||||
**影响**:装配期即可发现 Agent 配置问题。
|
||||
|
||||
> **归属**:P0 | **状态**:🟡 | **历史编号**:P3-12
|
||||
>
|
||||
> 新 Runner 不再用旧 registry;旧 `InMemoryAgentRegistry` 保留一版并补校验
|
||||
|
||||
### F-08 `adkRunnerPlugin` 是空壳,`myLogPlugin` 实际没有任何 ADK 日志能力
|
||||
|
||||
**位置**:`Name` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
```go
|
||||
func (p adkRunnerPlugin) OnUserMessage(...) error {
|
||||
if p.plugin.OnUserMessageCallback() != nil {
|
||||
fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:代码只判断「ADK 回调是否非 nil」,然后打印自己的硬编码文案,**从未真正调用 `p.plugin.OnUserMessageCallback()`**;`BeforeAgent` 同样。也就是说 `loggingplugin.New("myLogPlugin")` 创建出来的 ADK 插件除了被拿来做非 nil 判断外,没有任何实际作用。
|
||||
|
||||
**影响**:README/CLAUDE.md 宣称的插件生命周期(`OnUserMessage` / `BeforeAgent`)在 `myLogPlugin` 路径下是假的;用户配置了 `myLogPlugin` 却得不到 ADK 的日志输出,而且是 `fmt.Printf` 而非结构化日志。
|
||||
|
||||
**修复方案**:真正调用 ADK 回调(按其签名构造参数),或移除该包装;同时把输出改为注入的 `*zap.Logger`(与 F-40 合并处理)。
|
||||
|
||||
> **归属**:P0 | **状态**:🟡 | **历史编号**:P1-13
|
||||
>
|
||||
> P0 只做 `plugin.go` 的拆分搬迁,未重写插件语义;插件语义由 P7 的 run/step 事件取代
|
||||
|
||||
### F-09 tool-calling 循环上限硬编码为 4 次
|
||||
|
||||
**位置**:`maxToolCallIterations` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:`runLLM` 的 tool-calling 循环上限是包级常量 4,既不进配置,也不进 Run 的预算,无法按 Agent 的复杂度调整;复杂任务在第 4 轮被强行截断且没有任何提示。
|
||||
|
||||
**影响**:需要多轮工具编排的 Agent(检索→读文件→计算→再检索)必然早退;且截断时模型不知道「为什么停」,会给出半截答案。
|
||||
|
||||
**修复方案**:并入 P0 的 `runtime.Budget{MaxSteps,MaxToolCalls,...}`,由预算而非常量控制;耗尽时以 `RunStatus=exhausted` + `run.exhausted` 事件明确结束,并在最后一条系统提示里告知模型「已达到步数上限,请基于现有信息作答」。
|
||||
|
||||
> **归属**:P0 | **状态**:✅
|
||||
682
docs/upgrade-plan/P1-工具网关.md
Normal file
682
docs/upgrade-plan/P1-工具网关.md
Normal file
@@ -0,0 +1,682 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P1 · 工具网关:把「能调通」变成「调不坏」 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.2 节
|
||||
> **本阶段收编缺陷**:F-10、F-11、F-12、F-13、F-14、F-15、F-16、F-17、F-18、F-19、F-20、F-21、F-22(共 13 条,明细见文末附录)
|
||||
> 上一阶段:[`P0`](P0-运行时内核.md) | 下一阶段:[`P2`](P2-会话持久化.md)
|
||||
|
||||
|
||||
# 4.2 P1 · 工具网关:把"能调通"变成"调不坏"
|
||||
|
||||
## 目标
|
||||
|
||||
工具调用从"一次 try-call,失败即整轮失败"升级为**带 schema 校验、超时、指数退避、熔断、分级降级**的网关。这是面试官 A 第一个追问点("模型调工具报错、参数不符合 schema、下游超时,代码怎么做异常处理")的直接答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 证据 | 问题 |
|
||||
|---|---|
|
||||
| `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 所有工具只暴露一个 `query` 字符串参数,模型无法填结构化参数,也没有可校验的 schema(F-15) |
|
||||
| `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | `tools/list` 只取 name,丢弃 `description`/`inputSchema`(F-10) |
|
||||
| `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 任一工具失败 `return nil, err`,整轮终止(F-21) |
|
||||
| `tools.go` `normalizeTimeout` | 默认 300s,无单工具超时控制(F-22) |
|
||||
| `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | `pending` map 泄漏(F-11) |
|
||||
| `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | Router 无锁(F-16) |
|
||||
| `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 透传(修复 F-10)
|
||||
|
||||
```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`(修复 F-13);`pending` map 在 defer 中删除(修复 F-11);`MCPToolRouter` 加 `sync.RWMutex`(修复 F-16)。
|
||||
|
||||
同时修复 `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`,脚本与附件无人执行。把"看起来能调、实际调不出东西"的工具注册给模型,正是缺陷 F-14 指出的功能谎言;先删暴露面,才是诚实的降级。
|
||||
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,带 `## 技能:<name>` 分隔标题 |
|
||||
| 修改语义 | `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.<skill>.<script>"}` 走同一个 Gateway,执行体是 `sandbox.Runner`。这样"所有工具来源统一收敛到 `tool.Spec`"的架构目标在 P6 闭环,而不需要 P1 先造半成品。
|
||||
|
||||
**回滚**:`skills.mode=expose` 时恢复旧行为(把 Skill 注册为工具),用于对比与紧急回退;P6 完成后移除该开关。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/tool/spec.go` | Spec/RetryPolicy/ResultPolicy |
|
||||
| 新增 | `internal/domain/tool/gateway.go` | Gateway 接口 + 12 步流水线编排 |
|
||||
| 新增 | `internal/domain/tool/registry.go` | 注册表、命名空间、版本 |
|
||||
| 新增 | `internal/domain/tool/errors.go` | 错误归类(`Classify`) |
|
||||
| 新增 | `internal/domain/tool/ports.go` | Invoker/Result/SchemaValidator |
|
||||
| 新增 | `internal/infrastructure/tool/schema.go` | JSON Schema 校验(`santhosh-tekuri/jsonschema/v6`) |
|
||||
| 新增 | `internal/infrastructure/tool/retry.go` | backoff + 幂等键 |
|
||||
| 新增 | `internal/infrastructure/tool/breaker.go` | 滑动窗口熔断 |
|
||||
| 新增 | `internal/infrastructure/tool/ratelimit.go` | 令牌桶(本地 + Redis) |
|
||||
| 新增 | `internal/infrastructure/tool/degrade.go` | 降级阶梯 L3–L5 |
|
||||
| 新增 | `internal/infrastructure/tool/truncate.go` | head_tail 截断 |
|
||||
| 新增 | `internal/infrastructure/tool/mcp_adapter.go` | MCP ServerTool → Spec |
|
||||
| 修改 | `internal/infrastructure/ai/mcp_sse_client.go` | schema 透传、pending 泄漏、加锁、错误而非 nil |
|
||||
| 修改 | `internal/infrastructure/ai/tools.go` | `SkillTool` 不注册为 function tool(见 4.2.8);新增 `SkillSpec` 描述;stdio/local 注册 Spec |
|
||||
| 新增 | `internal/domain/skill/loader.go`、`internal/infrastructure/skill/fs_loader.go` | Skill 加载与 instruction 注入 |
|
||||
| 修改 | `internal/infrastructure/ai/openai_client.go` | `encodeTools` 用真实 schema |
|
||||
| 修改 | `internal/infrastructure/ai/eino_adapter.go` | `toolDefs` 改为从 Registry 取 Spec |
|
||||
| 修改 | `internal/infrastructure/adk/tool_loop.go` | 失败不再中断 run,改为 tool 消息 `is_error` |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | Tool 配置扩展(timeout/retry/fallback/effect) |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Registry + Gateway |
|
||||
| 修改 | `configs/agent/*.yaml` | 显式声明工具策略(示例见下) |
|
||||
|
||||
## 配置示例
|
||||
|
||||
```yaml
|
||||
# configs/application.yaml 新增
|
||||
tool-defaults:
|
||||
timeout: 30s
|
||||
retry:
|
||||
max-attempts: 3
|
||||
base-delay: 200ms
|
||||
max-delay: 5s
|
||||
multiplier: 2
|
||||
jitter: 0.2
|
||||
result:
|
||||
max-bytes: 32768
|
||||
strategy: head_tail
|
||||
circuit-breaker:
|
||||
window: 10
|
||||
failure-threshold: 5
|
||||
open-for: 30s
|
||||
|
||||
# configs/agent/xxx.yaml 单个工具覆盖
|
||||
tools:
|
||||
- name: baidu-search.search
|
||||
timeout: 8s
|
||||
effect: read
|
||||
fallback: [echoLocalTool]
|
||||
retry: {max-attempts: 2}
|
||||
- name: crm.updateOrder
|
||||
effect: write
|
||||
idempotency: key
|
||||
approval: required # P6 生效
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **故障注入测试集 ≥ 15 个场景**(超时、429、5xx、连接重置、坏 JSON、schema 不符、空结果、超大结果、重复注册、并发注册),全部断言:run **不失败**、错误被归类、降级动作符合预期。
|
||||
2. 失败注入 30% 时,任务成功率从当前 ~70% 提升到 **≥ 95%**(同一评测集)。
|
||||
3. 重试间隔符合退避公式(测试用 mock clock,断言 200/400/800ms ± jitter)。
|
||||
4. 写类工具重放同一幂等键,实际执行次数 = 1。
|
||||
5. 熔断:连续 5 次失败后 30s 内直接快速失败(P99 延迟从 30s 降到 < 5ms)。
|
||||
6. 工具描述与 schema 100% 透传到模型(抓包断言 `parameters.properties` 非空)。
|
||||
7. `go test -race` 通过,Router 无 data race。
|
||||
8. **Skill 只注入不暴露**:抓包断言 `tools` 数组不含 `skill_*`;system prompt 含 `SKILL.md` 正文与 `## 技能:` 标题;`skills.mode=expose` 时回到旧行为(回滚开关可用)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- `internal/infrastructure/tool/testdata/` 下用 `httptest` 起**可编程 SSE MCP Server**(按脚本返回失败/延迟/坏 schema)。
|
||||
- 单测覆盖:`backoff` 表驱动、`Classify` 表驱动、截断边界(0B/32KB/1MB)、幂等键碰撞。
|
||||
- 集成测试:真实 MCP(baidu-search)跑 10 次,记录成功率与 p95。
|
||||
- 混沌:在 CI 中把注入概率设为 0.3 跑评测集,失败则阻断合并。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 真实 MCP 返回的 schema 不规范(draft-04/缺 type) | 校验前做 schema 归一化;校验失败按 `schema` 类处理并降级,不阻断 |
|
||||
| 重试放大下游压力 | 默认仅 3 次 + 全抖动;熔断 + 令牌桶双限流 |
|
||||
| 参数"自愈"让模型陷入改参循环 | 硬限 1 次,且计入 Run 的 tool 预算 |
|
||||
| 引入 JSON Schema 库增大体积 | `santhosh-tekuri/jsonschema/v6` 无第三方依赖,约 400KB |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(13 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-10 工具描述全部丢失,模型只能看到兜底描述
|
||||
|
||||
**位置**:
|
||||
|
||||
- 接口定义:`ToolDescriptor` in `internal/domain/agent/ports/ports.go`
|
||||
- 消费方:`toolDefs` in `internal/infrastructure/ai/eino_adapter.go` `toolDefs()`
|
||||
- 工具实现:`internal/infrastructure/ai/tools.go`(`MCPTool`、`SkillTool`)、`eino_adapter.go`(`EinoTool`)
|
||||
|
||||
**问题概述**:`toolDefs()` 里用 `tool.(ports.ToolDescriptor)` 取描述,但**项目中没有任何类型实现了 `Description() string`**:
|
||||
|
||||
```go
|
||||
desc := ""
|
||||
if d, ok := tool.(ports.ToolDescriptor); ok {
|
||||
desc = d.Description() // 永远走不到
|
||||
}
|
||||
defs = append(defs, OpenAIToolDef{Name: tool.Name(), Description: desc})
|
||||
```
|
||||
|
||||
`SkillTool` 虽然有 `Description` 字段,但没有 `Description()` 方法;`MCPTool` 和 `EinoTool` 连字段都没有。结果所有工具描述都是空,`fallbackDescription` 统一返回「外部工具 X,参数 query 为自由文本」。
|
||||
|
||||
**影响**:模型无法区分各工具用途(比如百度搜索、drawio 绘图工具都被描述成同样的自由文本),工具选择准确率显著下降,而这是当前 demo 场景(多工具 + 多 Agent)的核心体验问题。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 给 `SkillTool` 加 `func (t SkillTool) Description() string { return t.Description }`。
|
||||
- 给 `EinoTool` 增加 `Description` 字段并实现方法;在 `MCPToolRouter.RegisterAndExpand` 从 `tools/list` 的 `description` 填充。
|
||||
- 给 `MCPTool` 实现 `Description()` 并保存 SSE 配置里的描述。
|
||||
- 保留 `eino_adapter.go` 的类型断言,同时提供统一的描述访问方式,避免以后再漏。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-3
|
||||
|
||||
### F-11 MCP `pending` map 在超时/提前返回路径泄漏
|
||||
|
||||
**位置**:`callRPC` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
postURL := c.postURL
|
||||
c.pending[id] = ch
|
||||
c.mu.Unlock()
|
||||
if postURL == "" {
|
||||
return nil, fmt.Errorf("mcp post url is not set") // <- 未删除 pending[id]
|
||||
}
|
||||
...
|
||||
select {
|
||||
case msg, ok := <-ch:
|
||||
...
|
||||
case <-waitCtx.Done():
|
||||
return nil, fmt.Errorf("mcp call %s timeout: %w", method, waitCtx.Err()) // <- 未删除 pending[id]
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`pending[id]` 在注册后,只有在 `handleMessage` 收到响应或 `signalStreamErr` 广播时才会被删除。超时、`postURL` 为空等提前返回路径都不会清理。
|
||||
|
||||
**影响**:MCP Server 慢/挂掉时,每次超时都会在 `pending` 里留下一个带缓冲 channel,长跑进程持续占用内存,属于慢性内存泄漏。残留条目还会让 `signalStreamErr` 在断线时向已无人等待的 channel 写入。
|
||||
|
||||
**修复方案**:在 `callRPC` 内用 `defer` 清理:
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
c.pending[id] = ch
|
||||
c.mu.Unlock()
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, id)
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
```
|
||||
|
||||
注意避免重复关闭 channel;推荐让「所有权持有者」关闭,或用 `sync.Once`。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-4
|
||||
|
||||
### F-12 `ensureStarted` 并发首次调用会失败
|
||||
|
||||
**位置**:`ensureStarted` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
if c.started { // goroutine B 看到 true
|
||||
c.mu.Unlock()
|
||||
return nil // <- B 直接返回成功
|
||||
}
|
||||
...
|
||||
c.started = true // A 先标记,再在锁外做耗时连接
|
||||
c.mu.Unlock() // <- B 此刻可能已经进入 callRPC
|
||||
```
|
||||
|
||||
**问题概述**:第一个调用者(A)在锁内置 `started = true` 后释放锁,然后在锁外做 `openSSE`、等待 `endpoint`、`initialize`(可能数百毫秒到数秒)。此时第二个并发调用者(B)会看到 `started == true` 而直接返回 nil,随后 B 进入 `callRPC` 时 `postURL` 仍为空,报 `mcp post url is not set`。
|
||||
|
||||
**影响**:并发首次调用工具(如 parallel workflow 同时触发工具,或第一个请求尚未完成时的第二个请求)会随机失败。当前 demo 不易触发,但一旦上线就是间歇性报错。
|
||||
|
||||
**修复方案**:把「标记」与「完成」分开,使用 `sync.Once` + 初始化结果,或引入 `started`/`ready` 两个状态 + `sync.Cond`,让并发调用者等待初始化完成或拿到同一个初始化错误。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P0-5
|
||||
>
|
||||
> P1 先修并发正确性(`sync.Once` 或双状态),P6 的 MCP 生命周期重构会重写这段
|
||||
|
||||
### F-13 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具
|
||||
|
||||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go` 与 `BuildTools` in `internal/infrastructure/ai/tools.go`
|
||||
|
||||
```go
|
||||
if _, exists := r.clients[mcp.ToolName]; exists {
|
||||
return nil // <- 第二次注册直接返回 nil
|
||||
}
|
||||
```
|
||||
|
||||
`BuildTools` 里:
|
||||
|
||||
```go
|
||||
ts := f.router.RegisterAndExpand(t)
|
||||
if len(ts) == 0 { continue } // 展开为空 -> 被跳过
|
||||
...
|
||||
if len(expanded) > 0 { return expanded, nil }
|
||||
return tools, nil // <- 回退成原始 MCPTool 占位符
|
||||
```
|
||||
|
||||
**问题概述**:`MCPToolRouter` 在 `bootstrap.Build` 中是全局单例。当前两个示例表都配置了同名 `baidu-search` SSE 工具。第二张表注册时命中 `exists` 分支返回 nil,`BuildTools` 的 `expanded` 为空,于是回退返回原始 `MCPTool{ToolName:"baidu-search"}`(不是 `tools/list` 发现的真实工具)。
|
||||
|
||||
**影响**:第二张表拿到的是配置名 `baidu-search` 这个占位工具,而不是 `tools/list` 发现的真实工具名。由于 `CallTool` 会先查 `r.clients[name]`(第 565 行),而 `baidu-search` 恰好在第一张表注册时已写入 `clients`,所以调用不会走 `case MCPTool:` 分支,而是被转发成 `tools/call {name:"baidu-search"}`——但 `baidu-search` 只是「服务端标签」,不是 MCP Server 上真实存在的工具名,服务端会返回「工具不存在」,最终表现为「Agent 一调工具就报错」。注意:这与 F-37 的 stdio/local「transport not supported」是两条不同的错误路径。
|
||||
|
||||
**修复方案**(任一):
|
||||
|
||||
1. `RegisterAndExpand` 命中已存在时,返回该 client 已展开的真实工具列表(需要缓存 `expandedByServer`)。
|
||||
2. `BuildTools` 在 `len(ts) == 0` 时不要静默跳过,而是报错提示「工具已被注册」。
|
||||
3. 更彻底:把 MCP client 的复用键改为 `baseURI+endpoint`,工具名到 client 的映射独立维护。
|
||||
|
||||
推荐方案 1 或 3,并为「多表共享同名 MCP」补测试。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-9
|
||||
>
|
||||
> 同名注册命中即返回错误;P6 用 `server.tool` 命名空间彻底隔离
|
||||
|
||||
### F-14 Skill 工具只暴露、不可执行
|
||||
|
||||
**位置**:`internal/infrastructure/ai/tools.go`(`SkillFactory`)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:Skill 被解析为 `SkillTool`(实现了 `ports.Tool`),会作为 function 暴露给模型;但它没有注册到 `MCPToolRouter` 的 `clients` map 中,运行时 `CallTool` 找不到客户端,返回 `tool %q is not callable in current runtime`。
|
||||
|
||||
**影响**:模型一旦选择 skill 工具就必然失败,用户侧看到「工具调用报错」。当前两个示例 skill(battle-plan、pdf)实际都不可用。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 明确 Skill 的执行语义:要么实现本地执行器(按 `SKILL.md` 指令执行脚本/读取文档),要么在装配阶段就不要把 Skill 暴露为 function。
|
||||
- 短期最稳:把 Skill 从 tool 列表移除,改为注入 instruction 上下文;长期:新增 `SkillToolExecutor` 注册到 `ToolRouter`。
|
||||
- 无论选哪种,都应消除「暴露但不可执行」的不一致状态。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-1
|
||||
>
|
||||
> 2026-11-02 决策:P1 只注入 instruction(4.2.8),P6 沙箱就绪后再做成可调用工具
|
||||
|
||||
### F-15 工具参数 schema 硬编码为 `query`
|
||||
|
||||
**位置**:`encodeTools` in `internal/infrastructure/ai/openai_client.go`
|
||||
|
||||
**问题概述**:所有工具的参数 schema 都被写成单一 `query: string`:
|
||||
|
||||
```go
|
||||
"parameters": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"query": map[string]any{"type": "string", ...},
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
但真实 MCP 工具的 `inputSchema` 各异(百度搜索可能要求 `query`,其他工具可能是别的字段)。
|
||||
|
||||
**影响**:模型按 schema 生成的参数可能与 MCP Server 期望不符,工具调用失败;同时丢失了 MCP `tools/list` 返回的真实 schema。
|
||||
|
||||
**修复方案**:`MCPToolRouter.RegisterAndExpand` 在 `tools/list` 时同时保留 `inputSchema`;`EinoChatModel.toolDefs` 传递完整 schema;`encodeTools` 直接使用它。若暂时拿不到 schema,至少保留参数名与描述。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-9
|
||||
|
||||
### F-16 `MCPToolRouter` 无锁
|
||||
|
||||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:`clients` / `tools` / `registered` / `listFailures` 都是普通 map,没有任何互斥保护。当前写入只发生在启动阶段(单 goroutine),运行时只读,勉强安全;但一旦支持热更新、延迟注册或并发 `BuildTools`,就是数据竞争。
|
||||
|
||||
**影响**:潜在 `fatal error: concurrent map read and map write`,进程直接崩溃。
|
||||
|
||||
**修复方案**:给 `MCPToolRouter` 加 `sync.RWMutex`,所有读写走锁;`CallTool` 读路径用 RLock。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P2-10
|
||||
|
||||
### F-17 MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警
|
||||
|
||||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go`、`BuildTools` in `internal/infrastructure/ai/tools.go`
|
||||
|
||||
```go
|
||||
names, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
r.listFailures[mcp.ToolName] = err // 只记录,从不读取、从不告警
|
||||
r.tools = append(r.tools, mcp) // 把配置名当工具塞回去
|
||||
return []ports.Tool{mcp}
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:MCP Server 启动时不可达/超时(或如 F-13 的重复注册)时,`BuildTools` 会把 `MCPTool{ToolName:"baidu-search"}` 作为「工具」返回给 ChatModel。模型看到一个名为 `baidu-search` 的 function,但该名字不是服务端真实工具,运行时 `tools/call` 必然失败;`listFailures` 只写不读,启动既不失败也不打日志。
|
||||
|
||||
**影响**:把不可用工具暴露给模型导致运行期报错;「降级保留占位工具」的初衷(启动不中断 + 错误清晰)没有达成,属于静默劣化。
|
||||
|
||||
**修复方案**:启动期区分「连接失败」与「无工具」,失败时记 `listFailures` 并打警告日志,或按 `required` 语义 fail fast;不要把配置名当可调用工具暴露;若保留占位,运行时应给出「MCP Server 未就绪」的明确错误。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-14
|
||||
>
|
||||
> `listFailures` 参与告警与 fail fast;探活逻辑在 P6 重写
|
||||
|
||||
### F-18 `io.ReadAll` 无上限读取上游响应体
|
||||
|
||||
**位置**:`Generate` in `internal/infrastructure/ai/openai_client.go`、`openSSE` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:三处都用 `io.ReadAll` 把响应体一次性读入内存,没有任何大小限制。`truncate(...,400)` 只截断错误文案,读入本身仍是全量。
|
||||
|
||||
**影响**:异常/恶意上游返回超大响应(或错误页)时可导致内存快速膨胀,属于 DoS 面;对非流式 `Generate` 尤其明显。
|
||||
|
||||
**修复方案**:用 `io.LimitReader`(如 4~8 MiB)限制读取并在超限时返回明确错误;错误体只需读几百字节。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-22
|
||||
>
|
||||
> 入站有 `MaxBytesReader`;出站 `io.LimitReader` 上限写进 P1 的模型客户端加固
|
||||
|
||||
### F-19 流式请求没有发送 `Accept: text/event-stream`
|
||||
|
||||
**位置**:`do` in `internal/infrastructure/ai/openai_client.go` `do()`
|
||||
|
||||
```go
|
||||
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
|
||||
...
|
||||
req.Header.Set("Accept", "application/json") // 流式/非流式共用
|
||||
```
|
||||
|
||||
**问题概述**:`do()` 被 `Generate` 与 `Stream` 共用,`Accept` 恒为 `application/json`,流式调用没有声明 `text/event-stream`。
|
||||
|
||||
**影响**:OpenAI 官方端点通常宽容,但部分兼容实现/网关会依据 `Accept` 决定是否返回 SSE,可能表现为流式请求拿不到事件流或直接被拒。
|
||||
|
||||
**修复方案**:`do()` 增加 `accept string` 参数,流式传 `text/event-stream`、非流式传 `application/json`;或校验返回的 `Content-Type` 并给出明确错误。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-23
|
||||
>
|
||||
> `Accept: text/event-stream` 写进 P1 的模型客户端加固
|
||||
|
||||
### F-20 `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码
|
||||
|
||||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`、`notify` 在 `:458-485`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `registered map[string]struct{}` 只写不读(第 548 行写、无任何读取);
|
||||
- `listFailures map[string]error` 只写不读(第 540 行写、无任何读取);
|
||||
- `notify()` 丢弃响应体后不检查 `StatusCode`。
|
||||
|
||||
**影响**:死字段误导读者;`notifications/initialized` 若被服务端拒绝(4xx/5xx),客户端仍认为握手成功,后续调用才报莫名的错。
|
||||
|
||||
**修复方案**:删除死字段(或让 `listFailures` 真正参与启动告警);`notify` 增加状态码校验。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P3-15
|
||||
>
|
||||
> `listFailures` 改为告警后自然解决;`notify` 的状态码校验在 P1 补
|
||||
|
||||
### F-21 任一工具失败即整轮失败(`executeToolCalls`)
|
||||
|
||||
**位置**:`(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:工具调用循环里任何一个工具返回错误,`executeToolCalls` 直接 `return nil, fmt.Errorf("tool %q: %w", call.Name, err)`,整个 run 终止,没有重试、没有降级、没有把失败结果作为 observation 回灌给模型。
|
||||
|
||||
**影响**:一个下游 5xx、一次限流、一次超时就能让整轮对话失败;而模型其实完全有能力基于「工具不可用」这个observation 给出替代答案。
|
||||
|
||||
**修复方案**:P1 的 `tool.Gateway` 把失败分类后走六层降级(P1 设计中的 L0–L6)。L5 结构化降级之后必须把结果作为工具输出回灌给模型,而不是让 run 失败——「工具故障是模型要处理的信息,不是 run 的终态」。
|
||||
|
||||
> **归属**:P1 | **状态**:✅
|
||||
|
||||
### F-22 工具调用无单次超时,只靠 HTTP 客户端整体超时
|
||||
|
||||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go` 的 `RequestTimeout`(默认 300s)
|
||||
|
||||
**问题概述**:工具级超时只有一个默认 300 秒的 `RequestTimeout`,实际调用路径上没有被单独施加 deadline 的地方;一次工具挂起会一直占用一个 step,直到外层 HTTP 客户端超时。
|
||||
|
||||
**影响**:单个慢工具能把整个 run 拖到分钟级;并发场景下直接耗尽连接与 goroutine。
|
||||
|
||||
**修复方案**:P1 的 `tool.Spec.Timeout` 成为唯一事实源(默认 30s,可按工具覆盖),Gateway 在 `Invoke` 前用 `context.WithTimeout` 施加 deadline;超时归类为 `timeout`(可重试),并计入 `Budget.MaxWallClock`。
|
||||
|
||||
> **归属**:P1 | **状态**:✅
|
||||
446
docs/upgrade-plan/P2-会话持久化.md
Normal file
446
docs/upgrade-plan/P2-会话持久化.md
Normal file
@@ -0,0 +1,446 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P2 · 会话生命周期与持久化:让 Agent 记得住、找得回 | **预估**:8–10 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.3 节
|
||||
> **本阶段收编缺陷**:F-23、F-24、F-25、F-26、F-27、F-28、F-29、F-30、F-31(共 9 条,明细见文末附录)
|
||||
> 上一阶段:[`P1`](P1-工具网关.md) | 下一阶段:[`P3`](P3-记忆与知识.md)
|
||||
|
||||
|
||||
# 4.3 P2 · 会话生命周期与持久化:让 Agent 记得住、找得回
|
||||
|
||||
## 目标
|
||||
|
||||
把"会话"从一张 `map[userID:agentID]sessionID` 升级为**有生命周期、有归属、有消息历史、可恢复**的领域聚合,并真正接上已经写好但从未被调用的 MySQL / Redis 适配器。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 证据 | 问题 |
|
||||
|---|---|
|
||||
| `InMemoryAgentRegistry`/`InMemorySessionStore` in `internal/domain/agent/ports/ports.go` | `InMemorySessionStore` 只有 `Get/Set`,重启即丢(F-24) |
|
||||
| `(*Service).CreateSession` in `internal/domain/agent/service/chat/service.go` | `CreateSession` 先 Get 再 Set,无锁无唯一约束(F-25) |
|
||||
| `(*Service).resolveRunnerSession` in `internal/domain/agent/service/chat/service.go` | `resolveRunnerSession` 直接用请求里的 `sessionID`,不校验归属(F-23) |
|
||||
| `(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go` | `appName:userID:counter` 拼 ID,无租户、可能撞号(F-31) |
|
||||
| `Build` in `internal/app/bootstrap/bootstrap.go` | 写死 `NewInMemorySessionStore()`,MySQL/Redis 适配器未接线 |
|
||||
| 全局 | 无消息表、无历史查询、无 TTL、无归档 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.3.1 会话聚合与状态机
|
||||
|
||||
```go
|
||||
// internal/domain/session/session.go
|
||||
type Status int8
|
||||
|
||||
const (
|
||||
StatusActive Status = 1
|
||||
StatusArchived Status = 2
|
||||
StatusExpired Status = 3
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID string // ULID,26 字符
|
||||
TenantID string
|
||||
UserID string
|
||||
AgentID string
|
||||
Title string
|
||||
Status Status
|
||||
LastSeq int // 消息序号水位(乐观并发)
|
||||
MessageCount int
|
||||
PromptTokens, CompletionTokens int
|
||||
Meta map[string]any
|
||||
CreatedAt, UpdatedAt, LastActiveAt time.Time
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
// 状态迁移:active --idle-timeout--> archived --retention--> expired
|
||||
// 反向:archived --new message--> active(复用会话,不新建)
|
||||
```
|
||||
|
||||
### 4.3.2 端口定义
|
||||
|
||||
```go
|
||||
// internal/domain/session/ports.go
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, s *Session) error // 唯一键冲突返回 ErrSessionExists
|
||||
Get(ctx context.Context, id string) (*Session, error) // 不存在返回 ErrSessionNotFound
|
||||
GetActive(ctx context.Context, tenant, user, agent string) (*Session, error)
|
||||
Touch(ctx context.Context, id string, at time.Time, tokens Usage) error
|
||||
UpdateStatus(ctx context.Context, id string, from, to Status) error
|
||||
ListByUser(ctx context.Context, tenant, user string, cursor string, limit int) ([]*Session, string, error)
|
||||
Sweep(ctx context.Context, now time.Time, idleAfter, retention time.Duration) (archived, expired int, err error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
// Append 在一个事务内分配连续 seq,保证 (session_id, seq) 唯一。
|
||||
Append(ctx context.Context, sessionID string, msgs []Message) ([]Message, error)
|
||||
ListRange(ctx context.Context, sessionID string, fromSeq, toSeq int) ([]Message, error)
|
||||
ListRecent(ctx context.Context, sessionID string, limit int) ([]Message, error) // 内部 DESC 后反转
|
||||
CountTokens(ctx context.Context, sessionID string, fromSeq int) (int, error)
|
||||
}
|
||||
|
||||
type RunRepository interface {
|
||||
Create(ctx context.Context, r *runtime.Run) error
|
||||
Finish(ctx context.Context, r *runtime.Run) error
|
||||
Get(ctx context.Context, id string) (*runtime.Run, error)
|
||||
ListBySession(ctx context.Context, sessionID string, limit int) ([]*runtime.Run, error)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3.3 表结构(MySQL 8.0)
|
||||
|
||||
```sql
|
||||
-- migrations/0001_session.up.sql
|
||||
CREATE TABLE `agent_session` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '1=active 2=archived 3=expired',
|
||||
-- 生成列:只在 active 时为 1,archived/expired 为 NULL,
|
||||
-- 从而"同一用户同一 Agent 仅一个活跃会话"可用唯一索引表达(MySQL 唯一索引允许多个 NULL)
|
||||
`active_flag` TINYINT GENERATED ALWAYS AS (IF(`status` = 1, 1, NULL)) STORED,
|
||||
`last_seq` INT NOT NULL DEFAULT 0,
|
||||
`message_count` INT NOT NULL DEFAULT 0,
|
||||
`prompt_tokens` INT NOT NULL DEFAULT 0,
|
||||
`completion_tokens` INT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
`last_active_at` DATETIME(3) NOT NULL,
|
||||
`expires_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_active_user_agent` (`tenant_id`,`user_id`,`agent_id`,`active_flag`),
|
||||
KEY `idx_user_recent` (`tenant_id`,`user_id`,`status`,`last_active_at`),
|
||||
KEY `idx_sweep` (`status`,`last_active_at`),
|
||||
KEY `idx_expires` (`expires_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
CREATE TABLE `agent_message` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`seq` INT NOT NULL,
|
||||
`role` VARCHAR(16) NOT NULL COMMENT 'system|user|assistant|tool',
|
||||
`name` VARCHAR(128) NOT NULL DEFAULT '',
|
||||
`content` MEDIUMTEXT NULL,
|
||||
`tool_calls` JSON NULL,
|
||||
`tool_call_id` VARCHAR(128) NOT NULL DEFAULT '',
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`finish_reason` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`pinned` TINYINT NOT NULL DEFAULT 0 COMMENT '关键信息,压缩时永不丢弃',
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_seq` (`session_id`,`seq`),
|
||||
KEY `idx_session_id` (`session_id`,`id`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `agent_run` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`turn_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`status` VARCHAR(24) NOT NULL,
|
||||
`steps` INT NOT NULL DEFAULT 0,
|
||||
`tool_calls` INT NOT NULL DEFAULT 0,
|
||||
`prompt_tokens` INT NOT NULL DEFAULT 0,
|
||||
`completion_tokens` INT NOT NULL DEFAULT 0,
|
||||
`failure_class` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`failure_code` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_session_started` (`session_id`,`started_at`),
|
||||
KEY `idx_status_started` (`status`,`started_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.3.4 序号分配:唯一索引 + 事务内自增
|
||||
|
||||
不引入发号器,直接利用会话行的 `last_seq`:
|
||||
|
||||
```sql
|
||||
-- 事务内
|
||||
SELECT last_seq FROM agent_session WHERE id = ? FOR UPDATE;
|
||||
-- 应用层 seq = last_seq+1 ... +N
|
||||
INSERT INTO agent_message (...) VALUES (...);
|
||||
UPDATE agent_session SET last_seq = ?, message_count = message_count + ?, updated_at = ? WHERE id = ?;
|
||||
```
|
||||
|
||||
`FOR UPDATE` 把同一会话的并发写串行化(单会话写入本就是串行语义),跨会话完全并行。`uk_session_seq` 是最后一道防线:任何越界写入都会失败而不是产生重复。
|
||||
|
||||
### 4.3.5 幂等创建(修复 F-25)
|
||||
|
||||
```go
|
||||
func (s *Service) EnsureSession(ctx context.Context, req EnsureRequest) (*Session, error) {
|
||||
if s := s.repo.FindActive(ctx, req.Tenant, req.User, req.Agent); s != nil {
|
||||
return s, nil
|
||||
}
|
||||
sess := NewSession(req)
|
||||
err := s.repo.Create(ctx, sess)
|
||||
if errors.Is(err, ErrSessionExists) { // 并发下唯一键冲突 → 回到读路径
|
||||
return s.repo.GetActive(ctx, req.Tenant, req.User, req.Agent)
|
||||
}
|
||||
return sess, err
|
||||
}
|
||||
```
|
||||
|
||||
不依赖 Redis 锁即可保证正确性;Redis 锁(`lock:session:create:{tenant}:{user}:{agent}`,3s)只用于**降低冲突率**,不是正确性来源。这是面试里"为什么不用分布式锁保证唯一"的标准答案:唯一约束才是真相,锁只是优化。
|
||||
|
||||
### 4.3.6 归属校验(修复 F-23 越权)
|
||||
|
||||
```go
|
||||
var ErrSessionForbidden = errors.New("session does not belong to caller")
|
||||
|
||||
func (s *Service) Authorize(ctx context.Context, tenant, user, agent, sessionID string) (*Session, error) {
|
||||
sess, err := s.repo.Get(ctx, sessionID)
|
||||
if err != nil { return nil, err }
|
||||
if sess.TenantID != tenant || sess.UserID != user || sess.AgentID != agent {
|
||||
return nil, ErrSessionForbidden // → HTTP 403 / code 4003
|
||||
}
|
||||
return sess, nil
|
||||
}
|
||||
```
|
||||
|
||||
**配套**:`ChatCommand` 增加 `TenantID`;HTTP 层在 P8 从 token 取,P2 阶段从 `X-Tenant-ID` 取(默认 `default`)。
|
||||
|
||||
### 4.3.7 Redis 的四个职责(不是"缓存一下"这么简单)
|
||||
|
||||
| 用途 | Key | TTL | 说明 |
|
||||
|---|---|---|---|
|
||||
| 会话读缓存 | `sess:{id}` | 10m | Cache-aside,写后失效;命中率目标 > 80% |
|
||||
| 最近消息缓存 | `sess:recent:{id}` | 10m | List,只存最近 40 条,供 P4 装配器热路径使用 |
|
||||
| 创建锁 | `lock:sess:create:{t}:{u}:{a}` | 3s | 仅降冲突,不是正确性来源 |
|
||||
| 幂等键 | `idem:run:{t}:{key}` | 24h | 重复提交返回同一 run_id |
|
||||
|
||||
**降级策略**:Redis 不可用时**必须**回落到"直连 MySQL + 进程内 LRU",不允许因此拒绝请求。用 `golang.org/x/sync/singleflight` 合并同一会话的并发回源。
|
||||
|
||||
### 4.3.8 持久化模式与优雅降级
|
||||
|
||||
```yaml
|
||||
persistence:
|
||||
mode: mysql+redis # memory | mysql | mysql+redis
|
||||
mysql:
|
||||
required: true # false 且连接失败 → 降级 memory 并打 WARN + 指标
|
||||
redis:
|
||||
required: false
|
||||
```
|
||||
|
||||
`bootstrap.Build()` 中的装配逻辑:
|
||||
|
||||
```go
|
||||
switch cfg.Persistence.Mode {
|
||||
case "mysql+redis":
|
||||
db := mysql.Open(ctx, cfg.Database) // 失败且 required=false → 降级
|
||||
rdb := redis.Open(ctx, cfg.Redis) // 失败 → 继续,日志告警
|
||||
sessionRepo = mysqlrepo.NewSessionRepo(db)
|
||||
...
|
||||
default:
|
||||
sessionRepo = ports.NewInMemorySessionStore() // 保持现有能力,供单测/本地
|
||||
}
|
||||
```
|
||||
|
||||
注意:`configs/application.yaml` 现有 `database.required: false`,语义正好可用于"本地无 MySQL 也能起"。
|
||||
|
||||
### 4.3.9 新增只读 API(不影响老端点)
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/sessions` | 当前用户会话列表(游标分页) |
|
||||
| GET | `/api/v1/sessions/{id}` | 会话详情 + 统计 |
|
||||
| GET | `/api/v1/sessions/{id}/messages?after_seq=&limit=` | 历史消息(前端"加载更多") |
|
||||
| DELETE | `/api/v1/sessions/{id}` | 软归档 |
|
||||
| GET | `/api/v1/runs/{id}` | Run 状态与用量 |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/session/session.go` | 聚合、状态迁移、不变量 |
|
||||
| 新增 | `internal/domain/session/ports.go` | 三个 Repository 接口 |
|
||||
| 新增 | `internal/domain/session/service.go` | Ensure/Authorize/Touch/Sweep |
|
||||
| 新增 | `internal/domain/session/message.go` | Message 领域模型 + 角色校验 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/db.go` | 连接池、健康检查、指标 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/session_repo.go` | 会话 CRUD + Sweep |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/message_repo.go` | seq 分配、区间查询 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/run_repo.go` | Run 落库 |
|
||||
| 新增 | `migrations/0001_session.up.sql` / `.down.sql` | 上述 DDL |
|
||||
| 新增 | `cmd/migrate/main.go` | 迁移执行(启动参数 `-migrate`) |
|
||||
| 修改 | `internal/infrastructure/cache/redis.go` | 增加通用客户端、缓存、锁、幂等封装 |
|
||||
| 修改 | `internal/infrastructure/persistence/mysql.go` | 改为薄封装或删除(逻辑移入 `mysql/` 包) |
|
||||
| 修改 | `internal/domain/agent/model/command.go` | `ChatCommand` 加 `TenantID` |
|
||||
| 修改 | `internal/domain/agent/service/chat/service.go` | 改用 session.Service,鉴权后再建会话 |
|
||||
| 修改 | `internal/infrastructure/adk/runner.go` | Run 落库、消息落库时机 |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 新增 5 个只读端点、错误映射 4003 |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 按 `persistence.mode` 装配 + 健康检查 |
|
||||
| 修改 | `cmd/server/main.go` | 启动时执行迁移(可选)、关闭时释放连接池 |
|
||||
| 修改 | `pkg/types/codes.go` | 新增 4003(越权)/4004(会话不存在)/5001(存储不可用) |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **重启不丢**:`kill -9` 后重启,同一 `session_id` 的历史消息完整返回(seq 连续)。
|
||||
2. **并发唯一**:100 goroutine 同时 `EnsureSession(tenant,user,agent)`,数据库最终只有 1 条 active。
|
||||
3. **越权拒绝**:用户 B 带用户 A 的 session_id 请求,返回 403/4003,且**不产生任何用户 A 的消息写入**。
|
||||
4. **seq 无重复**:并发 append 1000 条消息,`(session_id, seq)` 唯一,无空洞以外的异常。
|
||||
5. **降级可用**:MySQL 关闭且 `required: false` 时服务正常启动,日志 WARN,指标 `persistence_degraded=1`。
|
||||
6. Redis 关闭时,功能全部可用,仅延迟上升(p95 < 50ms)。
|
||||
7. 会话清理任务:手动把 `last_active_at` 改为 31 天前,跑 Sweep 后状态变 `archived`。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **仓储集成测试**:testcontainers-go 起 MySQL 8.0 + Redis 6.2,跑真实 SQL;CI 用 docker-compose 复用 `deployments/docker-compose.yml`(顺手修掉其中 redis `networks: voice-input-net` 的引用错误)。
|
||||
- **并发测试**:`-race` + 100 并发 Ensure/Append。
|
||||
- **迁移测试**:up → down → up 幂等;对空库与有数据分别验证。
|
||||
- **降级测试**:用 `sqlmock` 注入连接失败,断言回落内存实现。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 消息表膨胀(单会话万级消息) | 按 `session_id` 分区/归档;P4 压缩后老消息移到冷表 |
|
||||
| `FOR UPDATE` 热点 | 单会话串行是语义要求;跨会话无竞争;若仍不足,改 `INSERT ... SELECT MAX(seq)+1` 乐观重试 |
|
||||
| 迁移失败阻塞启动 | 迁移与启动解耦:`-migrate` 单独执行;启动只做 `schema_version` 校验 |
|
||||
| gorm 与 sqlx 混用 | 新仓储统一 `sqlx`;`mysql.go` 的 gorm 代码冻结不再扩展,下一个版本删除依赖 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(9 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-23 `sessionId` 不校验归属
|
||||
|
||||
**位置**:`resolveRunnerSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:只要 `command.SessionID != ""` 就直接使用,不校验它是否属于该 `userId` / `agentId`,也不校验是否存在。
|
||||
|
||||
**影响**:任意调用方可传入他人 sessionId;虽然当前 session 无状态、危害有限,但一旦引入对话历史(F-24)或计费,就是越权访问。
|
||||
|
||||
**修复方案**:`SessionStore` 增加 `Validate(userID, agentID, sessionID) bool` 或让 `Get` 返回后比对;`resolveRunnerSession` 中先校验再使用,不匹配返回 `CodeIllegalParameter`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-5
|
||||
|
||||
### F-24 Session 无对话历史(Agent 实际无状态)
|
||||
|
||||
**位置**:`InMemorySessionStore` in `internal/domain/agent/ports/ports.go`、`applyVars` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:`SessionStore` 只保存 `userID:agentID -> sessionID` 字符串,不保存消息历史;`runLLM` 每次都从 `[system, user]` 重建消息。
|
||||
|
||||
**影响**:看似支持多轮对话,实则每轮独立;前端「上下文」只能靠把上一轮 XML 拼进 message 来绕过。这是产品能力的核心缺口。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 新增 `ConversationStore` 端口,保存 `sessionID -> []ChatMessage`。
|
||||
- `Runner.Run` 前加载历史并追加到 `initialMessages` 之后;执行完成后把 user + assistant 消息写回。
|
||||
- 内存实现先用带锁 map,后续可替换 Redis/MySQL。
|
||||
- 注意消息裁剪(token 预算)与并发写同一 session 的顺序问题。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-6
|
||||
>
|
||||
> P2 落消息持久化,P4 落预算装配,两者合起来才是完整的多轮
|
||||
|
||||
### F-25 `CreateSession` 并发竞态
|
||||
|
||||
**位置**:`CreateSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:`Get` 未命中后创建再 `Set`,两个并发请求可能都未命中,各自创建 session,后写覆盖先写。
|
||||
|
||||
**影响**:同一用户同一 Agent 出现 session 抖动,前一个 session 的 ID 被覆盖后客户端可能拿到「已经不存在」的 ID。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- `SessionStore` 增加 `GetOrCreate(userID, agentID, creator func() (string,error))`,内部加锁(或 Redis `SetNX`)。
|
||||
- 或在 `chat.Service` 内为 `userID:agentID` 加 per-key `singleflight`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-7
|
||||
|
||||
### F-26 MySQL / Redis 适配器未接入
|
||||
|
||||
**位置**:`Build` in `internal/app/bootstrap/bootstrap.go`
|
||||
|
||||
**问题概述**:始终使用 `NewInMemoryAgentRegistry()` / `NewInMemorySessionStore()`,`persistence.OpenMySQL` 与 `cache.OpenRedis` 无人调用。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 重启丢会话;
|
||||
- 多实例无法共享;
|
||||
- 适配器代码长期未被验证,可能已腐化。
|
||||
|
||||
**修复方案**:在 `bootstrap.Build` 中根据 `appCfg.Database.Required/DSN`、`appCfg.Redis.Required/Addr` 决定是否打开,并让 `SessionStore` 走 Redis 实现(需先解决 F-29 的 context 问题)。`Required=false` 时保持内存实现并打日志说明。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P2-8
|
||||
|
||||
### F-27 空内容错误码不准确 + 先建 Session 后校验内容
|
||||
|
||||
**位置**:`resolveRunnerSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
```go
|
||||
if sessionID == "" {
|
||||
sessionID, err = s.CreateSession(...) // 先建会话
|
||||
}
|
||||
...
|
||||
if ... 内容为空 {
|
||||
return ..., fmt.Errorf("chat content is required") // 非法参数却报 0001
|
||||
}
|
||||
```
|
||||
|
||||
**影响**:空消息请求会创建一个无用 Session;错误码是 `0001 unknown` 而非 `0002 illegal parameter`。
|
||||
|
||||
**修复方案**:把内容校验提到 `CreateSession` 之前;错误改为 `types.NewAppError(types.CodeIllegalParameter, "chat content is required")`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P2-11
|
||||
>
|
||||
> 参数校验前置 + 错误码 `1001`(§5.1)
|
||||
|
||||
### F-28 `CreateSession` 不校验 Agent 是否仍存在
|
||||
|
||||
**位置**:`CreateSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:命中缓存直接返回旧 session,不检查 `registry` 中 Agent 是否还在。
|
||||
|
||||
**影响**:当前 registry 只增不删,问题不显现;支持热更新/下线后会出现「Agent 已下线仍可用」的不一致。
|
||||
|
||||
**修复方案**:命中缓存后仍做一次 `registry.Get(agentID)` 校验。
|
||||
|
||||
> **归属**:P2 | **状态**:🟡 | **历史编号**:P2-16
|
||||
>
|
||||
> 方案未点名;`CreateSession` 顺手加 `registry.Get` 校验
|
||||
|
||||
### F-29 `ports.SessionStore` 无 context
|
||||
|
||||
**为什么优化**:接口无 context,Redis/MySQL 实现只能内部用 `context.Background()`,无法随请求取消/超时。
|
||||
|
||||
**方案**:`Get(ctx, ...)` / `Set(ctx, ...)`,同步改内存实现与调用方。
|
||||
|
||||
**改动量**:小-中。
|
||||
|
||||
**影响**:为 F-26 的 Redis 接入铺路。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P3-7
|
||||
|
||||
### F-30 Session key 用 `:` 拼接存在歧义
|
||||
|
||||
**为什么优化**:`userID + ":" + agentID`,当 ID 自身含 `:` 时可能碰撞(如 `a:b` + `c` 与 `a` + `b:c`)。
|
||||
|
||||
**方案**:改用长度前缀编码、`\x00` 分隔或 `struct{userID, agentID string}` 作为 map key。
|
||||
|
||||
**改动量**:很小。
|
||||
|
||||
**影响**:消除边界情况。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P3-13
|
||||
|
||||
### F-31 Session ID 用全局原子计数拼接,无租户维度且跨 Agent 撞号
|
||||
|
||||
**位置**:`(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:会话 ID 由 `fmt.Sprintf("%s:%s:%d", appName, userID, counter.Add(1))` 生成。计数器是进程内全局的,重启即归零;ID 里没有租户维度,也不能用于分布式部署(多实例各自从 1 开始)。
|
||||
|
||||
**影响**:重启后可能与历史会话 ID 重复;多实例部署必然撞号;ID 本身携带用户信息,属于不必要的泄露面。
|
||||
|
||||
**修复方案**:P2 起会话 ID 改为应用层生成的 ULID(`CHAR(26)`),租户与用户信息入库而不进主键;旧格式 ID 在迁移期由 `session.Repository.Get` 兼容读取(前缀解析),迁移完成后删除兼容分支。
|
||||
|
||||
> **归属**:P2 | **状态**:✅
|
||||
407
docs/upgrade-plan/P3-记忆与知识.md
Normal file
407
docs/upgrade-plan/P3-记忆与知识.md
Normal file
@@ -0,0 +1,407 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P3 · 记忆与知识:三层记忆 + 可检索知识库 | **预估**:12–15 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.4 节
|
||||
> **本阶段收编缺陷**:F-32(共 1 条,明细见文末附录)
|
||||
> 上一阶段:[`P2`](P2-会话持久化.md) | 下一阶段:[`P4`](P4-上下文工程.md)
|
||||
|
||||
|
||||
# 4.4 P3 · 记忆与知识:三层记忆 + 可检索知识库
|
||||
|
||||
## 目标
|
||||
|
||||
让 Agent 具备**跨轮、跨会话的记忆能力**,以及**基于文档的知识检索能力**(覆盖面试官 A 的"数据层:知识库怎么清洗、按什么切分"与"记忆层:多轮上下文怎么管理")。
|
||||
|
||||
## 当前问题
|
||||
|
||||
- 无任何记忆抽象:`ChatMessage` 只在单次 Run 的内存里存在(F-24)。
|
||||
- `AiAPIConfig.EmbeddingsPath` 定义了却从未使用(`model/config.go`)——说明作者预留了位置但没实现。
|
||||
- 无文档入库、切片、索引、召回的任何代码。
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.4.1 记忆分层模型
|
||||
|
||||
| 层 | 内容 | 存储 | 生命周期 | 何时读 | 何时写 |
|
||||
|---|---|---|---|---|---|
|
||||
| **L0 工作记忆** | 当前 Run 的 scope 变量、工具中间结果、计划 | 内存(`runtime.Scope`) | Run 级 | 每个 Step | 每个 Step |
|
||||
| **L1 短期记忆** | 原始消息流(user/assistant/tool) | `agent_message` | 会话级 | 每轮装配最近窗口 | 每轮(P2 已做) |
|
||||
| **L2 情节记忆** | 分段摘要(带时间、主题、决策) | `agent_memory_summary` | 会话级,长留存 | 装配时按需 | 触发压缩时(P4) |
|
||||
| **L3 语义记忆** | 事实:偏好/实体/决策/约束/未完成任务 | `agent_memory_fact` | 用户级,长期 | 每轮按相关性召回 | Run 结束后异步抽取 |
|
||||
| **L4 知识库** | 外部文档切片 + 向量 | `kb_document` / `kb_chunk` | 租户级 | 每轮检索 | 离线 ingest |
|
||||
|
||||
**为什么分三层而不是两层**:L1 解决"最近说了什么",L2 解决"这段聊了什么",L3 解决"这个用户是谁、他定过什么规矩"。三者检索代价与更新频率完全不同,混在一张表里会导致"要么全量塞上下文,要么全丢"。
|
||||
|
||||
### 4.4.2 语义记忆表(支持改写而非删除)
|
||||
|
||||
```sql
|
||||
-- migrations/0002_memory.up.sql
|
||||
CREATE TABLE `agent_memory_fact` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`scope` VARCHAR(16) NOT NULL COMMENT 'user|session|agent|tenant',
|
||||
`scope_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`kind` VARCHAR(32) NOT NULL COMMENT 'preference|entity|decision|constraint|open_task|correction',
|
||||
`subject` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`predicate` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`object` TEXT NULL,
|
||||
`content` TEXT NOT NULL COMMENT '自然语言陈述,供模型直接读',
|
||||
`importance` TINYINT NOT NULL DEFAULT 3 COMMENT '1..5',
|
||||
`confidence` DECIMAL(3,2) NOT NULL DEFAULT 1.00,
|
||||
`source_message_id` BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
`source_run_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`valid_from` DATETIME(3) NOT NULL,
|
||||
`valid_to` DATETIME(3) NULL COMMENT '非空表示已失效,但保留以便回溯',
|
||||
`superseded_by` CHAR(26) NULL,
|
||||
`access_count` INT NOT NULL DEFAULT 0,
|
||||
`last_accessed_at` DATETIME(3) NULL,
|
||||
`embedding` MEDIUMBLOB NULL COMMENT 'float32 小端拼接,维度见 embedding_dim',
|
||||
`embedding_dim` SMALLINT NOT NULL DEFAULT 0,
|
||||
`embedding_model` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`content_hash` CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256(content),去重用',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_content_hash` (`tenant_id`,`user_id`,`scope`,`scope_id`,`content_hash`),
|
||||
KEY `idx_semantic` (`tenant_id`,`user_id`,`kind`,`valid_to`,`importance`),
|
||||
KEY `idx_recall` (`tenant_id`,`user_id`,`importance`,`last_accessed_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `agent_memory_summary` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`level` TINYINT NOT NULL COMMENT '1=分段 2=会话级 3=用户画像',
|
||||
`from_seq` INT NOT NULL,
|
||||
`to_seq` INT NOT NULL,
|
||||
`message_count` INT NOT NULL DEFAULT 0,
|
||||
`content` TEXT NOT NULL,
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`model` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`parent_id` CHAR(26) NULL COMMENT '递归压缩的上游摘要',
|
||||
`pinned_facts` JSON NULL COMMENT '压缩时被固化的事实快照',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_range` (`session_id`,`level`,`from_seq`,`to_seq`),
|
||||
KEY `idx_session_level` (`session_id`,`level`,`to_seq`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- 记忆异步处理任务(outbox,保证不丢)
|
||||
CREATE TABLE `agent_memory_job` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`kind` VARCHAR(24) NOT NULL COMMENT 'extract_facts|summarize|embed',
|
||||
`payload` JSON NULL,
|
||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0=pending 1=running 2=done 3=failed',
|
||||
`attempts` TINYINT NOT NULL DEFAULT 0,
|
||||
`last_error` VARCHAR(512) NOT NULL DEFAULT '',
|
||||
`next_run_at` DATETIME(3) NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_pending` (`status`,`next_run_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.4.3 知识库表(覆盖"数据层")
|
||||
|
||||
```sql
|
||||
CREATE TABLE `kb_document` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`title` VARCHAR(512) NOT NULL,
|
||||
`source` VARCHAR(1024) NOT NULL COMMENT '文件路径/URL/上传 ID',
|
||||
`mime` VARCHAR(64) NOT NULL,
|
||||
`content_hash` CHAR(64) NOT NULL,
|
||||
`size_bytes` BIGINT NOT NULL DEFAULT 0,
|
||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0=ingesting 1=ready 2=failed',
|
||||
`chunk_count` INT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_hash` (`tenant_id`,`content_hash`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `kb_chunk` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`doc_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`seq` INT NOT NULL,
|
||||
`content` MEDIUMTEXT NOT NULL,
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`heading_path` VARCHAR(512) NOT NULL DEFAULT '' COMMENT '标题层级,如 "3.2 退换货/时限"',
|
||||
`chunk_strategy` VARCHAR(32) NOT NULL DEFAULT 'recursive',
|
||||
`embedding` MEDIUMBLOB NULL,
|
||||
`embedding_dim` SMALLINT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_doc_seq` (`doc_id`,`seq`),
|
||||
KEY `idx_tenant_doc` (`tenant_id`,`doc_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.4.4 文档入库流水线(清洗 → 切分 → 向量化)
|
||||
|
||||
```
|
||||
上传/挂载 ──► Parse ──► Normalize ──► Chunk ──► Embed ──► Index ──► Ready
|
||||
│ │ │ │
|
||||
PDF/DOCX 去页眉页脚 策略可选 批量 64 条
|
||||
MD/HTML 合并断行 带 heading 失败重试 3 次
|
||||
纯文本 去重复空行 路径元数据
|
||||
```
|
||||
|
||||
**切分策略**(面试常问,必须能说出取舍):
|
||||
|
||||
| 策略 | 适用 | 参数 | 缺点 |
|
||||
|---|---|---|---|
|
||||
| `fixed` 定长 | 日志、无结构文本 | 512 token / overlap 64 | 切断语义 |
|
||||
| `recursive` 递归分隔(默认) | 通用文档 | `\n\n` → `\n` → `。` → 空格 | 可能超长块 |
|
||||
| `heading` 标题感知 | 手册、规范 | 按 `#/##/###` 分层,保留 `heading_path` | 依赖文档结构 |
|
||||
| `parent-child` 父子块 | 问答精度要求高 | 子块 256(检索),父块 1024(喂模型) | 存储翻倍 |
|
||||
| `semantic` 语义切分 | 长文、主题跳跃 | 相邻句 embedding 距离阈值 | 成本高、慢 |
|
||||
|
||||
默认 `recursive` + `heading` 混合:先按标题切,再对超长段递归切,overlap 10%。
|
||||
|
||||
**清洗规则**(可配置,顺序执行):去页眉页脚(按重复行检测)→ 合并硬换行(中文行尾无标点则拼接)→ 去连续空行 → 去零宽字符 → 表格转 Markdown → 图片 OCR(可选)→ 去重(SimHash,阈值 0.9)。
|
||||
|
||||
### 4.4.5 端口定义
|
||||
|
||||
```go
|
||||
// internal/domain/memory/ports.go
|
||||
type Fact struct {
|
||||
ID, TenantID, UserID, AgentID string
|
||||
Scope, ScopeID string
|
||||
Kind Kind
|
||||
Subject, Predicate, Object string
|
||||
Content string
|
||||
Importance int
|
||||
Confidence float64
|
||||
SourceMessageID int64
|
||||
SourceRunID string
|
||||
ValidFrom time.Time
|
||||
ValidTo *time.Time
|
||||
}
|
||||
|
||||
type FactStore interface {
|
||||
Upsert(ctx context.Context, facts []Fact) (inserted, superseded int, err error)
|
||||
Search(ctx context.Context, q FactQuery) ([]Fact, error)
|
||||
Touch(ctx context.Context, ids []string, at time.Time) error
|
||||
Forget(ctx context.Context, q ForgetQuery) (int, error) // 软失效
|
||||
}
|
||||
|
||||
type SummaryStore interface {
|
||||
Put(ctx context.Context, s Summary) error
|
||||
Latest(ctx context.Context, sessionID string, level int) (*Summary, error)
|
||||
ListRange(ctx context.Context, sessionID string, fromSeq, toSeq int) ([]Summary, error)
|
||||
}
|
||||
|
||||
type Retriever interface {
|
||||
Retrieve(ctx context.Context, q Query) ([]Hit, error)
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
TenantID, UserID, AgentID, SessionID string
|
||||
Text string
|
||||
Kinds []Kind
|
||||
TopK int
|
||||
MinScore float64
|
||||
IncludeKB bool
|
||||
KBFilter map[string]string // doc_id/heading 前缀过滤
|
||||
}
|
||||
|
||||
type Hit struct {
|
||||
Ref Ref // fact / summary / chunk
|
||||
Content string
|
||||
Score float64
|
||||
Breakdown ScoreBreakdown
|
||||
}
|
||||
|
||||
type Extractor interface {
|
||||
// Extract 从一段对话中抽取事实,必须返回结构化 JSON(受 schema 约束)
|
||||
Extract(ctx context.Context, in ExtractInput) ([]Fact, error)
|
||||
}
|
||||
|
||||
type Embedder interface {
|
||||
Embed(ctx context.Context, texts []string) ([][]float32, error)
|
||||
Dim() int
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4.6 混合检索打分(不依赖向量库也能跑)
|
||||
|
||||
```go
|
||||
// 综合分 = 相关性 0.55 + 重要性 0.25 + 时效性 0.20,再做 MMR 去冗余
|
||||
score = 0.55*relevance + 0.25*float64(importance)/5 + 0.20*recencyDecay
|
||||
|
||||
recencyDecay = math.Exp(-ageDays / halfLifeDays) // 默认 halfLife = 30 天
|
||||
relevance = max(cosine(queryEmb, factEmb), bm25(query, content)/normBM25)
|
||||
```
|
||||
|
||||
- **有 embedding**:余弦相似度;无 embedding(或未配置 `embeddings-path`):回落 BM25(Go 侧内存倒排,按租户分片,万级文档足够)。
|
||||
- **MMR 去冗余**:`λ*score - (1-λ)*max_sim(已选)`,λ=0.7,避免召回 5 条几乎相同的事实。
|
||||
- **向量规模**:单用户事实 < 2 万条时,Go 内暴力余弦(2 万 × 1536 维 ≈ 120MB 内存/全量扫描 30ms),足够;超过则通过 `VectorIndex` 端口切 Qdrant/pgvector,不改上层。
|
||||
|
||||
### 4.4.7 写入路径:异步、可重试、不阻塞响应
|
||||
|
||||
```
|
||||
Run 结束
|
||||
└─► 事务内写 agent_memory_job(kind=extract_facts) ← 与 assistant 消息同事务,保证不丢
|
||||
└─► worker(每 5s 拉 pending,最多 4 并发)
|
||||
├─► Extractor:用**便宜模型**(可配)按 JSON schema 抽事实
|
||||
├─► 去重/消解:content_hash 唯一;subject+predicate 相同 → 旧的置 valid_to
|
||||
├─► Embed(批量 64,失败重试 3 次,指数退避)
|
||||
└─► 更新 job=done
|
||||
```
|
||||
|
||||
**为什么异步**:抽取要多一次 LLM 调用(几百 ms 到数秒),放主链路会显著抬高 p95。用户感知的是"下一轮才想起来",这是可接受的取舍——但要在产品上明确("记忆在下一轮生效")。
|
||||
|
||||
**为什么用 outbox 表而不是直接 goroutine**:进程崩溃会丢任务;表 + 轮询是零依赖的可靠队列,配 `FOR UPDATE SKIP LOCKED` 支持多实例。
|
||||
|
||||
```sql
|
||||
SELECT * FROM agent_memory_job
|
||||
WHERE status = 0 AND next_run_at <= NOW()
|
||||
ORDER BY next_run_at LIMIT 20
|
||||
FOR UPDATE SKIP LOCKED;
|
||||
```
|
||||
|
||||
### 4.4.8 抽取的 prompt 契约(结构化,防幻觉)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"facts": {
|
||||
"type": "array",
|
||||
"maxItems": 8,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["kind", "content", "importance", "evidence_seq"],
|
||||
"properties": {
|
||||
"kind": {"enum": ["preference","entity","decision","constraint","open_task","correction"]},
|
||||
"subject": {"type": "string"},
|
||||
"predicate": {"type": "string"},
|
||||
"object": {"type": "string"},
|
||||
"content": {"type": "string", "maxLength": 300},
|
||||
"importance": {"type": "integer", "minimum": 1, "maximum": 5},
|
||||
"evidence_seq": {"type": "integer", "description": "该事实来自第几条消息,必须真实存在"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
三条硬规则:**只抽用户明确表达的内容**(不抽模型自己的推测)、**每条必须带 evidence_seq**(可回溯、可审计)、**importance 有明确定义**(见下表),避免模型全打 5 分。
|
||||
|
||||
| 分值 | 含义 | 例子 |
|
||||
|---|---|---|
|
||||
| 5 | 硬约束/禁令 | "以后不要用 emoji"、"金额必须保留两位小数" |
|
||||
| 4 | 稳定偏好/身份 | "我是后端工程师"、"偏好 Go" |
|
||||
| 3 | 项目事实 | "这个项目用 MySQL 8" |
|
||||
| 2 | 一次性上下文 | "这次先看 3 个文件" |
|
||||
| 1 | 闲聊 | "今天天气不错" |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/memory/fact.go` | Fact/Kind/校验 |
|
||||
| 新增 | `internal/domain/memory/summary.go` | Summary/层级 |
|
||||
| 新增 | `internal/domain/memory/ports.go` | FactStore/SummaryStore/Retriever/Extractor/Embedder |
|
||||
| 新增 | `internal/domain/memory/service.go` | Consume(run) 编排、去重消解 |
|
||||
| 新增 | `internal/domain/memory/extractor.go` | 结构化抽取 + evidence 校验 |
|
||||
| 新增 | `internal/domain/memory/retriever.go` | 混合检索 + MMR |
|
||||
| 新增 | `internal/domain/memory/scoring.go` | BM25、余弦、时效衰减 |
|
||||
| 新增 | `internal/domain/knowledge/{document.go,chunk.go,parser.go,chunker.go,service.go}` | 文档入库 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/fact_repo.go` | 事实 CRUD + 唯一键消解 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/summary_repo.go` | 摘要读写 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/job_repo.go` | outbox(SKIP LOCKED) |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/kb_repo.go` | 文档/切片 |
|
||||
| 新增 | `internal/infrastructure/ai/embedding_client.go` | 复用 `EmbeddingsPath`、批量、缓存、重试 |
|
||||
| 新增 | `internal/infrastructure/memory/worker.go` | 轮询 worker + 优雅退出 |
|
||||
| 新增 | `migrations/0002_memory.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | 新增 `MemoryConfig`、`KnowledgeConfig` |
|
||||
| 修改 | `internal/app/config/application.go` | 解析 `memory:` / `knowledge:` |
|
||||
| 修改 | `internal/infrastructure/adk/runner.go` | Run 成功后投递 job(同事务) |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Retriever/Store/Worker(`memory.enabled` 开关) |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 新增 `POST /api/v1/knowledge/documents`、`GET /api/v1/memory/facts` |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
extract:
|
||||
model: gpt-4o-mini # 便宜模型
|
||||
max-facts-per-run: 8
|
||||
worker-concurrency: 4
|
||||
poll-interval: 5s
|
||||
retrieve:
|
||||
top-k: 6
|
||||
min-score: 0.35
|
||||
half-life-days: 30
|
||||
mmr-lambda: 0.7
|
||||
embedding:
|
||||
path: v1/embeddings # 复用 AiAPIConfig.EmbeddingsPath
|
||||
model: text-embedding-3-small
|
||||
dim: 1536
|
||||
batch-size: 64
|
||||
|
||||
knowledge:
|
||||
enabled: false
|
||||
chunk:
|
||||
strategy: recursive # fixed|recursive|heading|parent_child|semantic
|
||||
max-tokens: 512
|
||||
overlap-tokens: 64
|
||||
ingest:
|
||||
max-file-size: 20MB
|
||||
allowed-mime: [text/plain, text/markdown, application/pdf]
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **跨轮记忆**:脚本第 2 轮说"我叫小林,以后叫我小林",第 25 轮问"我叫什么",回答必须包含"小林"(连续 10 次运行 10 次通过)。
|
||||
2. **约束遵守**:第 3 轮说"不要用表格",第 20 轮输出不含 markdown 表格。
|
||||
3. **事实去重**:同一事实重复 5 次,`agent_memory_fact` 只有 1 条有效记录,其余 `valid_to` 非空。
|
||||
4. **改写而非删除**:"预算 100 万" → 后续改口"预算改成 200 万",检索只返回 200 万,且旧记录可查。
|
||||
5. **知识库**:上传 50 页 PDF,切分出 300± 块,问 10 个跨页问题,命中率 ≥ 8/10,答案带 `doc_id + heading_path` 引用。
|
||||
6. **异步不阻塞**:开启记忆后 `/chat` p95 延迟增幅 < 5%。
|
||||
7. **可删除**:`Forget(user)` 后检索不到该用户任何事实(软失效 + 检索过滤)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **评测驱动**:`testdata/memory/scenarios/*.yaml` 定义多轮脚本与断言,`go test ./internal/domain/memory -tags=eval`。
|
||||
- **抽取质量**:构造 50 段对话,人工标注期望事实,测 precision/recall(目标 P ≥ 0.85,R ≥ 0.7);抽取结果必须 100% 带合法 `evidence_seq`。
|
||||
- **检索**:20 条 query 的 recall@6、MRR;BM25 与向量两路分别跑,再跑融合。
|
||||
- **切分**:对同一文档跑 5 种策略,输出块数/平均长度/边界截断率对比表。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 抽取幻觉(编造用户没说的事) | 强制 `evidence_seq` 且回查原文包含关键实体;不匹配则丢弃并计数 |
|
||||
| 记忆污染(错误事实长期生效) | 提供"忘记这条"指令;`agent_memory_fact` 管理接口;importance×confidence 双阈值召回 |
|
||||
| 向量维度/模型变更 | 表内记录 `embedding_model/dim`;变更时后台重算,双写过渡 |
|
||||
| MySQL 存向量性能 | 单用户 < 2 万条内存暴力扫;超限切 `VectorIndex` 端口 |
|
||||
| 隐私合规 | 租户级隔离 + `Forget` + 留存期配置;PII 字段入库前脱敏(P7 guard 复用) |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(1 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-32 `EmbeddingsPath` 定义但未使用
|
||||
|
||||
**为什么优化**:配置项存在但不生效会让使用者误以为支持 embedding。
|
||||
|
||||
**方案**:实现 embedding 客户端并在 Armory 中新增节点,或暂时从配置与文档中移除。
|
||||
|
||||
**改动量**:移除很小;实现则中等(新客户端 + 新节点 + 端口)。
|
||||
|
||||
**影响**:配置语义变清晰,或新增 RAG 能力。
|
||||
|
||||
> **归属**:P3 | **状态**:✅ | **历史编号**:P3-3
|
||||
271
docs/upgrade-plan/P4-上下文工程.md
Normal file
271
docs/upgrade-plan/P4-上下文工程.md
Normal file
@@ -0,0 +1,271 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P4 · 上下文工程:20 轮之后还记得第一句话 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.5 节
|
||||
> **本阶段收编缺陷**:F-33(共 1 条,明细见文末附录)
|
||||
> 上一阶段:[`P3`](P3-记忆与知识.md) | 下一阶段:[`P5`](P5-工作流编排.md)
|
||||
|
||||
|
||||
# 4.5 P4 · 上下文工程:20 轮之后还记得第一句话
|
||||
|
||||
## 目标
|
||||
|
||||
用**确定性预算装配 + 滚动摘要压缩 + 关键信息优先召回**,替换现在"每轮只有 system+user"的做法(F-24),让上下文长度稳定、关键信息不丢、Token 成本可控。这是"记忆分层、上下文压缩、关键信息优先召回"三连问的完整答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
```go
|
||||
// 现状:initialMessages in internal/infrastructure/adk/adapter.go
|
||||
func initialMessages(instruction, userText string) []ports.ChatMessage {
|
||||
messages := make([]ports.ChatMessage, 0, 2)
|
||||
if strings.TrimSpace(instruction) != "" {
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleSystem, Content: instruction})
|
||||
}
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleUser, Content: userText})
|
||||
return messages
|
||||
}
|
||||
```
|
||||
|
||||
后果:
|
||||
- 第 2 轮起,模型完全不知道上一轮说了什么(连自己刚生成的答案都不知道)。
|
||||
- `ChatCommand.SessionID` 传了个寂寞——`resolveRunnerSession` 拿到 ID 后没查任何历史。
|
||||
- 工具调用结果也不落历史,多轮追问"刚才那个链接"必然失败。
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.5.1 装配器输入输出
|
||||
|
||||
```go
|
||||
// internal/domain/contextasm/assembler.go
|
||||
type Request struct {
|
||||
TenantID, UserID, AgentID, SessionID string
|
||||
Query string // 本轮用户输入
|
||||
SystemPrompt string
|
||||
Tools []tool.Spec
|
||||
Window int // 模型上下文窗口,默认 32768
|
||||
MaxOutput int // 预留输出,默认 2048
|
||||
Policy Policy
|
||||
}
|
||||
|
||||
type Bundle struct {
|
||||
Messages []ports.ChatMessage
|
||||
Tokens int
|
||||
Breakdown Breakdown // 每层用了多少 token,供观测与调优
|
||||
Refs []memory.Ref // 引用来源,用于前端"依据"展示与审计
|
||||
}
|
||||
|
||||
type Breakdown struct {
|
||||
System, Tools, Pinned, Summary, Anchors, Recent, Retrieved int
|
||||
Compacted bool
|
||||
Dropped int // 被裁剪的候选消息数
|
||||
}
|
||||
|
||||
type Assembler interface {
|
||||
Assemble(ctx context.Context, req Request) (Bundle, error)
|
||||
}
|
||||
```
|
||||
|
||||
> 包名取 `contextasm` 而非 `context`:若目录名即包名,`Assemble(ctx context.Context, ...)` 这类函数只能靠别名 import 标准库,读起来别扭且容易与 `runtime.Context` 混淆。
|
||||
|
||||
### 4.5.2 预算分配(先算再取,绝不"塞到爆")
|
||||
|
||||
```
|
||||
available = Window - MaxOutput - Safety(5%)
|
||||
```
|
||||
|
||||
| 层 | 内容 | 配额 | 超限策略 |
|
||||
|---|---|---:|---|
|
||||
| S | system prompt + 工具 schema | 固定,先扣 | 工具过多时按使用频次裁剪(P1 的 `Visibility`) |
|
||||
| P | **Pinned 事实**(importance ≥ 4 或本轮实体命中) | ≤ 15% | 按 importance 降序,超出则只留 5 条 |
|
||||
| M | 最新会话摘要 | ≤ 20% | 摘要本身超限 → 触发递归压缩(level 2) |
|
||||
| A | **锚点消息**(用户原话/纠正/带数字与 ID 的消息) | ≤ 15% | 按 `pinned` 标记优先,其余丢弃 |
|
||||
| R | 最近对话窗口 | ≤ 40% | 从最新往回取整轮(user+assistant+tool 成组) |
|
||||
| T | 检索到的情节/知识 | 剩余 | 按综合分取 top-k,低于 `min-score` 不取 |
|
||||
|
||||
**"成组"很重要**:assistant 的 `tool_calls` 与对应 `tool` 结果必须一起进或一起出,否则 OpenAI 协议直接 400(`tool_call_id` 无对应结果)。
|
||||
|
||||
### 4.5.3 装配顺序(为 prefix cache 优化)
|
||||
|
||||
```
|
||||
[system] ← 稳定
|
||||
[pinned facts](按 fact_id 排序) ← 半稳定,只增不改
|
||||
[summary](最新一条) ← 每次压缩才变
|
||||
[retrieved docs/facts] ← 每轮变化
|
||||
[anchors](按 seq 升序) ← 半稳定
|
||||
[recent window](时序) ← 每轮变化
|
||||
[user query] ← 最后
|
||||
```
|
||||
|
||||
设计理由(面试可讲):
|
||||
|
||||
1. **稳定前缀在前**:OpenAI/DeepSeek 的 prefix caching 按前缀匹配,`system + pinned` 不变即可命中缓存,输入成本可降 30%–50%。
|
||||
2. **pinned 按 ID 稳定排序**:绝不按"相关度"重排,否则每次都 miss。
|
||||
3. **U 型注意力**:关键约束放开头(system 之后紧跟 pinned),最新问题放结尾,符合长上下文"中间信息易丢"的经验规律。
|
||||
4. **不要把摘要放在最前面**:摘要会随压缩变化,放前面会让整段前缀失效。
|
||||
|
||||
### 4.5.4 压缩流水线(trigger → segment → summarize → verify → store)
|
||||
|
||||
```go
|
||||
type Compactor interface {
|
||||
ShouldCompact(ctx context.Context, s SessionStats) bool
|
||||
Compact(ctx context.Context, req CompactRequest) (Summary, error)
|
||||
}
|
||||
```
|
||||
|
||||
**触发条件**(满足任一):
|
||||
|
||||
- `session_tokens > 0.6 * Window`
|
||||
- 距上次摘要新增轮次 ≥ `compact.every-n-turns`(默认 8)
|
||||
- 单轮工具结果总量 > 8k token
|
||||
|
||||
**分段**:优先按"话题边界"切(连续两条用户消息 embedding 距离 > 阈值,或用户显式切换任务);退化方案按固定 8 轮。
|
||||
|
||||
**摘要模板**(结构化,避免自由发挥):
|
||||
|
||||
```markdown
|
||||
## 任务目标
|
||||
## 已确认的决策(含理由)
|
||||
## 硬约束与偏好(逐条,保留原话关键短语)
|
||||
## 关键实体(人名/项目/ID/数字,逐个列出)
|
||||
## 已完成 / 未完成
|
||||
## 产出物(文件/链接/代码片段摘要)
|
||||
```
|
||||
|
||||
**校验(关键一步,多数实现会漏)**:
|
||||
|
||||
1. 把该段的 **pinned 事实清单** 逐条检查是否出现在摘要里,缺失则**抽取式回填原句**(不重新生成,避免二次幻觉)。
|
||||
2. 用规则检查数字/ID/URL 是否保留(正则比对原文)。
|
||||
3. 摘要 token 必须 ≤ 原文的 `compact.ratio`(默认 0.25),否则重试一次更激进的模板。
|
||||
4. 校验不通过 → 降级为"抽取式摘要"(取每轮用户消息 + assistant 结论句),保证**信息不丢但可能啰嗦**。
|
||||
|
||||
**存储**:写 `agent_memory_summary(level=1, from_seq, to_seq)`,幂等(唯一键);递归压缩时 `level=2` 引用 `parent_id`。
|
||||
|
||||
### 4.5.5 关键信息优先召回(pinning 规则)
|
||||
|
||||
哪些消息在写入时就打 `pinned=1`(P2 表已有字段):
|
||||
|
||||
| 触发 | 判定 | 例子 |
|
||||
|---|---|---|
|
||||
| 用户显式指令 | 含"以后/始终/永远/不要/必须/记住" | "以后回答都用中文" |
|
||||
| 纠正 | 含"不对/不是/改成/应该是" | "不是 100 万,是 200 万" |
|
||||
| 数字与标识 | 正则命中金额/日期/订单号/URL | "订单 A12345" |
|
||||
| 自报身份/偏好 | 抽取器判定 `preference/entity` | "我是后端工程师" |
|
||||
| 任务目标 | 每轮第一条 user 消息 | "帮我把这个需求拆成任务" |
|
||||
|
||||
**召回增强**:把本轮 query 与"当前任务目标 + pinned 事实里的实体名"拼接后再检索(query rewriting),避免"它怎么样了"这类指代无法检索。
|
||||
|
||||
### 4.5.6 Token 计量与校准
|
||||
|
||||
- **估算**:装配阶段用轻量分词器估算(中文约 1 token/字,英文 1 token/4 字符,或用 `tiktoken-go` 精确算)。
|
||||
- **实际**:从 API 响应的 `usage` 读真值,回写 `Step.Usage` 与 `agent_message.token_count`。
|
||||
- **校准**:维护 `estimate/actual` 比值滑动平均,偏差 > 15% 时自动调整估算系数(不同模型分词器不同)。
|
||||
- **成本可控**:每轮装配产出 `Breakdown`,可直接回答"这个 6k token 里,2.1k 是工具 schema、1.8k 是最近窗口"。
|
||||
|
||||
### 4.5.7 可观测:上下文预览接口
|
||||
|
||||
```
|
||||
GET /api/v1/sessions/{id}/context_preview?query=...&window=32768
|
||||
```
|
||||
|
||||
返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"tokens": 6120,
|
||||
"breakdown": {"system":820,"tools":1650,"pinned":430,"summary":960,"anchors":0,"recent":1980,"retrieved":280},
|
||||
"compacted": true,
|
||||
"messages": [{"role":"system","tokens":820,"preview":"你是..."}],
|
||||
"refs": [{"type":"fact","id":"01J...","content":"用户偏好中文回答","score":0.82}]
|
||||
}
|
||||
```
|
||||
|
||||
这个接口在演示与排障时价值极高:能直接看到"为什么模型忘了"。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/contextasm/assembler.go` | 装配主流程 + 成组裁剪 |
|
||||
| 新增 | `internal/domain/contextasm/budget.go` | 配额计算与扣减 |
|
||||
| 新增 | `internal/domain/contextasm/pinning.go` | pin 判定规则 |
|
||||
| 新增 | `internal/domain/contextasm/compactor.go` | 触发/分段/摘要/校验 |
|
||||
| 新增 | `internal/domain/contextasm/token.go` | 估算、校准 |
|
||||
| 新增 | `internal/domain/contextasm/rewrite.go` | query 重写 |
|
||||
| 修改 | `internal/infrastructure/adk/executor_llm.go` | `initialMessages` → `assembler.Assemble` |
|
||||
| 修改 | `internal/infrastructure/adk/prompt.go` | 保留旧实现作为 fallback |
|
||||
| 修改 | `internal/domain/agent/service/chat/service.go` | 传入 session 与 query,触发压缩 |
|
||||
| 修改 | `internal/infrastructure/ai/openai_client.go` | 解析 `usage` 回填;支持 `max_tokens`/`temperature` 透传 |
|
||||
| 修改 | `internal/domain/agent/ports/ports.go` | `ChatModel` 增加 `Window() int`、`CountTokens()` |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Assembler/Compactor |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | `context_preview` 端点 |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | `ContextConfig` |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
context:
|
||||
assembler:
|
||||
enabled: true
|
||||
window: 32768
|
||||
max-output: 2048
|
||||
quotas: # 百分比,合计 ≤ 100
|
||||
pinned: 15
|
||||
summary: 20
|
||||
anchors: 15
|
||||
recent: 40
|
||||
compact:
|
||||
trigger-ratio: 0.6
|
||||
every-n-turns: 8
|
||||
ratio: 0.25 # 摘要/原文 token 比
|
||||
model: gpt-4o-mini
|
||||
verify: true
|
||||
fallback: extractive # extractive | none
|
||||
cache:
|
||||
stable-prefix: true
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **20 轮回归**:固定脚本 25 轮,第 1 轮注入 5 条关键信息(称呼、预算、日期、禁令、订单号),第 25 轮逐一追问,**全部答对**(10 次运行全通过)。
|
||||
2. **Token 稳定**:25 轮对话总输入 token 曲线在 5.5k–7k 之间波动,**不超过 8k**(当前实现第 25 轮虽然小,但会直接丢信息;对照实验见下)。
|
||||
3. **压缩保真**:对 50 段对话做压缩,pinned 事实召回率 100%(校验器保证),数字/ID 保留率 100%。
|
||||
4. **缓存命中**:连续 5 轮对话,第 2 轮起 prefix cache 命中率 ≥ 60%(以 provider 返回的 `cached_tokens` 为准,没有则用成本对比估算)。
|
||||
5. **协议合法**:装配结果中每个 `tool_calls` 都有配对的 `tool_call_id` 结果,回放 100 轮不出现 400。
|
||||
6. **延迟**:装配本身 p95 < 15ms(不含检索);开检索后 p95 < 80ms。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **黄金用例**:`testdata/context/turns_25.jsonl` + 断言文件,`-tags=eval` 跑真实模型,CI 每日跑一次。
|
||||
- **离线断言**:用 fake Retriever 返回固定事实,单测装配顺序、配额、成组裁剪、pinning 规则(表驱动 30 例)。
|
||||
- **压缩测试**:构造含 12 条关键信息的 50 轮对话,压缩后检查校验器 12/12 通过;故意删掉一条验证校验器能发现。
|
||||
- **Token 对齐**:对比估算与实际 usage,偏差 < 15%。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 摘要丢关键信息 | 三层校验 + 抽取式回填;`pinned` 永不进摘要只做保留 |
|
||||
| 压缩本身很贵 | 用便宜模型 + 只在阈值触发 + 结果缓存(同一 from/to 不重算) |
|
||||
| 装配顺序影响模型表现 | A/B:`stable-prefix` 开关对比任务成功率与成本 |
|
||||
| 工具 schema 占满预算 | 工具 > 20 个时按使用频次动态裁剪;`human_only` 工具不进 schema |
|
||||
| 老数据无 pinned 标记 | 一次性 backfill 任务:对历史 user 消息跑 pinning 规则 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(1 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-33 无法配置任何生成参数
|
||||
|
||||
**位置**:`ChatModelConfig` in `internal/domain/agent/model/config.go`、`buildRequestBody` in `internal/infrastructure/ai/openai_client.go`
|
||||
|
||||
**问题概述**:`buildRequestBody` 只发送 `model` / `messages` / `stream` / `tools`,没有 `temperature`、`max_tokens`、`top_p`、`stop`、`response_format`、`seed` 等参数,YAML 也无处可配(`grep "temperature|max_tokens|top_p" internal/ configs/` 无命中)。
|
||||
|
||||
**影响**:无法控制确定性与成本上限;drawio 这类「要求严格只输出 XML」的场景无法用 `response_format` 或低 `temperature` 提升稳定性,也无法用 `max_tokens` 控制成本。
|
||||
|
||||
**修复方案**:`ChatModelConfig` 增加 `params`/`generation` 子结构(用指针字段区分「未设置」与「零值」),透传到 `buildRequestBody`。改动集中在 model + provider + client 三处,向后兼容。
|
||||
|
||||
> **归属**:P4 | **状态**:🟡 | **历史编号**:P2-24
|
||||
>
|
||||
> 只覆盖了 `max_output`;`temperature`/`max_tokens`/`response_format` 透传写进 P4
|
||||
407
docs/upgrade-plan/P5-工作流编排.md
Normal file
407
docs/upgrade-plan/P5-工作流编排.md
Normal file
@@ -0,0 +1,407 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P5 · 工作流编排:从「线性 Chain」到「可补偿的状态机」 | **预估**:12–15 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.6 节
|
||||
> **本阶段收编缺陷**:F-34、F-35、F-36(共 3 条,明细见文末附录)
|
||||
> 上一阶段:[`P4`](P4-上下文工程.md) | 下一阶段:[`P6`](P6-工具治理.md)
|
||||
|
||||
|
||||
# 4.6 P5 · 工作流编排:从"线性 Chain"到"可补偿的状态机"
|
||||
|
||||
## 目标
|
||||
|
||||
把现在"sequential 能跑、parallel 假并发、loop 无迭代"的编排(F-34、F-35)升级为**显式图执行 + 节点级重试 + Saga 补偿 + 检查点续跑**。这是面试官 A "为什么选状态机而不是线性 Chain / 分支失败怎么回滚"的唯一可信答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
```go
|
||||
// 现状:(*Agent).runFanOut in internal/infrastructure/adk/adapter.go,parallel 与 loop 走同一个串行 fan-out
|
||||
func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
parts := make([]string, 0, len(a.subAgents))
|
||||
for _, sub := range a.subAgents { // ← 串行
|
||||
impl, ok := sub.(*Agent) // ← 只能接同包具体类型
|
||||
if !ok { return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name()) }
|
||||
text, err := impl.runWithVars(ctx, content, vars)
|
||||
if err != nil { return "", err } // ← 一个失败全失败
|
||||
parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text))
|
||||
}
|
||||
return strings.Join(parts, "\n"), nil
|
||||
}
|
||||
```
|
||||
|
||||
| 问题 | 证据 | 影响 |
|
||||
|---|---|---|
|
||||
| parallel 串行执行 | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 3 分支各 10s,实际 30s |
|
||||
| `max-iterations` 从未使用 | 同上 + `model/config.go` | loop 配置形同虚设 |
|
||||
| 无节点级重试 | 同上 | 一个分支抖动毁掉整条链 |
|
||||
| 无补偿/回滚 | 全局无 | 第 3 步失败,前 2 步的副作用留在系统里 |
|
||||
| 无检查点 | 全局无 | 进程重启后只能从头跑,重复产生副作用 |
|
||||
| 无分支/条件 | 只有顺序执行 | 无法表达"评审不通过则回到绘制" |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.6.1 图模型
|
||||
|
||||
```go
|
||||
// internal/domain/workflow/graph.go
|
||||
type NodeID string
|
||||
|
||||
type NodeKind string
|
||||
|
||||
const (
|
||||
NodeAgent NodeKind = "agent" // 调用一个 Agent
|
||||
NodeTool NodeKind = "tool" // 直接调工具(不经模型)
|
||||
NodeBranch NodeKind = "branch" // 条件分支
|
||||
NodeJoin NodeKind = "join" // 汇聚
|
||||
NodeLoop NodeKind = "loop" // 循环子图
|
||||
NodeHuman NodeKind = "human" // 人工确认(P6)
|
||||
NodeSubgraph NodeKind = "subgraph" // 复用子图
|
||||
)
|
||||
|
||||
type Graph struct {
|
||||
ID string
|
||||
Version string // 配置版本,检查点据此判断兼容性
|
||||
Nodes map[NodeID]Node
|
||||
Edges []Edge
|
||||
Entry NodeID
|
||||
Vars map[string]VarSpec
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
ID NodeID
|
||||
Kind NodeKind
|
||||
Agent string // Kind=agent
|
||||
Tool string // Kind=tool
|
||||
Inputs map[string]Binding // 形参 → 表达式("{analysis_result}" / "$.nodes.draw.output")
|
||||
OutputKey string
|
||||
Retry RetryPolicy
|
||||
Timeout time.Duration
|
||||
OnError ErrorPolicy // fail | skip | fallback | compensate | escalate
|
||||
Compensate NodeID // Saga 补偿节点
|
||||
Loop *LoopSpec
|
||||
When *Condition
|
||||
}
|
||||
|
||||
type LoopSpec struct {
|
||||
MaxIterations int
|
||||
Until *Condition // 为空则跑满次数(保持旧 loop 语义)
|
||||
StateKey string // 每轮写入的变量,用于无进展检测
|
||||
}
|
||||
|
||||
type Edge struct {
|
||||
From NodeID
|
||||
To NodeID
|
||||
When *Condition // 为空表示无条件
|
||||
Default bool // 所有条件不满足时走这条
|
||||
}
|
||||
```
|
||||
|
||||
### 4.6.2 条件表达式
|
||||
|
||||
用 `github.com/expr-lang/expr`(纯 Go、无反射逃逸、编译期检查变量),而不是 `text/template` 或自研 DSL:
|
||||
|
||||
```yaml
|
||||
when: "nodes.review.output.ok == false && attempt < 3"
|
||||
when: "vars.budget_remaining > 1000"
|
||||
when: "run.usage.steps < 12"
|
||||
```
|
||||
|
||||
环境变量只暴露白名单(`nodes` / `vars` / `run` / `attempt`),**不允许**访问 OS、文件、环境变量。表达式编译结果缓存,避免每次求值重新解析。
|
||||
|
||||
### 4.6.3 执行状态机
|
||||
|
||||
```
|
||||
┌──────────┐
|
||||
│ pending │
|
||||
└────┬─────┘
|
||||
前置满足 │
|
||||
┌────▼─────┐ retry ┌──────────┐
|
||||
│ running ├──────────►│ retrying │
|
||||
└────┬─────┘ └────┬─────┘
|
||||
成功 │ │ 失败 │
|
||||
┌────▼──┐ ▼ │
|
||||
│ done │ ┌──────────┐ │
|
||||
└───┬───┘ │ failed │◄────────────┘
|
||||
│ └────┬─────┘
|
||||
│ │ on_error=compensate
|
||||
│ ┌────▼────────┐
|
||||
│ │ compensating│──► compensated
|
||||
│ └─────────────┘
|
||||
└──────────► 下一个节点
|
||||
```
|
||||
|
||||
**关键决策:节点状态机而不是整图状态机**。整图状态机(如 Temporal 的 workflow)语义更严格,但改造成本高;节点级状态机 + 检查点表已经能满足"失败可定位、可重试、可续跑",且与现有 YAML 结构最贴近。
|
||||
|
||||
### 4.6.4 与旧配置的兼容映射
|
||||
|
||||
| 旧配置 | 新图 | 行为变化 | 兼容处理 |
|
||||
|---|---|---|---|
|
||||
| `type: sequential` + `sub-agents` | 线性链 `n1→n2→n3` | 无 | 直接映射 |
|
||||
| `type: parallel` + `sub-agents` | `fanout → n1..nk → join` | **真并发**(默认并发度 4) | 输出仍按 `sub-agents` 声明顺序拼接,保证 golden 一致;`workflow.execution-mode=legacy` 时走旧实现 |
|
||||
| `type: loop` + `max-iterations` | `loop` 节点 | `max-iterations` **真正生效** | 旧语义是"跑一次 fan-out",属 bug;修复需在 release note 标注,默认 `execution-mode=legacy` 保持一版 |
|
||||
| `output-key` | `OutputKey` + 变量写入 `scope` | 无 | 直接映射;同时支持 `$.nodes.x.output` 引用 |
|
||||
| `{key}` 模板 | `Binding` 表达式 | 无 | `"{key}"` 等价 `vars.key`,旧写法继续可用 |
|
||||
|
||||
### 4.6.5 检查点与续跑
|
||||
|
||||
```sql
|
||||
-- migrations/0003_workflow.up.sql
|
||||
CREATE TABLE `wf_instance` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`graph_id` VARCHAR(128) NOT NULL,
|
||||
`graph_version` VARCHAR(32) NOT NULL,
|
||||
`status` VARCHAR(24) NOT NULL COMMENT 'running|waiting|succeeded|failed|compensated',
|
||||
`current_node` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`vars` JSON NULL,
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_run` (`run_id`),
|
||||
KEY `idx_status` (`status`,`started_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `wf_node_exec` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`instance_id` CHAR(26) NOT NULL,
|
||||
`node_id` VARCHAR(64) NOT NULL,
|
||||
`attempt` SMALLINT NOT NULL DEFAULT 1,
|
||||
`status` VARCHAR(16) NOT NULL,
|
||||
`input` JSON NULL,
|
||||
`output` JSON NULL,
|
||||
`failure_class` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`failure_msg` VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_node_attempt` (`instance_id`,`node_id`,`attempt`),
|
||||
KEY `idx_instance` (`instance_id`,`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**续跑算法**:
|
||||
|
||||
```
|
||||
resume(instanceID):
|
||||
1. 读 wf_instance.vars(已完成的输出变量)
|
||||
2. 读所有 status='succeeded' 的 node 集合 S
|
||||
3. 从 Entry 做拓扑遍历,跳过 S 中节点,从第一个非 S 且前置全部 ∈ S 的节点开始
|
||||
4. 若该节点 status='running'(上次崩在半路)→ 按幂等键判断:副作用是否已发生?
|
||||
- 有幂等键 → 重放安全,attempt+1 重跑
|
||||
- 无幂等键 → 标记 needs_review,转人工(宁可漏跑不可重跑)
|
||||
5. 图版本不一致 → 拒绝续跑,返回 GRAPH_VERSION_MISMATCH
|
||||
```
|
||||
|
||||
**副作用安全**是这里最容易被忽略的点:续跑只对**幂等节点**自动重放;写类节点必须有幂等键(P1 的 `Idempotency`),否则转人工。这与 P1 的设计是同一个机制,复用即可。
|
||||
|
||||
### 4.6.6 真并发(errgroup + 部分失败策略)
|
||||
|
||||
```go
|
||||
g, gctx := errgroup.WithContext(rc.Context())
|
||||
g.SetLimit(policy.Concurrency) // 默认 4,来自配置
|
||||
for _, n := range branches {
|
||||
n := n
|
||||
g.Go(func() error {
|
||||
_, err := e.execNode(gctx, n)
|
||||
switch policy.PartialFailure {
|
||||
case "all": return err // 任一失败即取消其余
|
||||
case "any": return nil // 任一成功即算分支成功(记录其余失败)
|
||||
case "best_effort": return nil // 全部跑完,失败项降级为 remark
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
return g.Wait()
|
||||
```
|
||||
|
||||
三条约束:
|
||||
|
||||
1. **每个分支独立 `Step`,但共享 `Run.Budget`**(原子扣减),否则 k 个分支各自花光预算。
|
||||
2. **取消传播**:`all` 模式下任一失败要 `cancel()` 其余分支,并等待它们退出(`errgroup` 自带),避免 goroutine 泄漏。
|
||||
3. **输出顺序稳定**:结果按 `branches` 声明顺序收集,不按完成顺序,保证同样输入得到同样输出(可重放、可对比)。
|
||||
|
||||
### 4.6.7 循环的终止保证(回答"死循环")
|
||||
|
||||
三层终止:
|
||||
|
||||
| 层 | 机制 |
|
||||
|---|---|
|
||||
| 硬上限 | `MaxIterations`(配置,默认 3,硬顶 20),到点退出并标记 `loop_exhausted` |
|
||||
| 预算 | 每轮消耗 Run 预算,预算耗尽即退出(P0 已保证) |
|
||||
| **无进展检测** | 每轮结束计算 `state_hash = sha256(StateKey 的值)`;连续 2 轮相同 → 判定"原地打转",退出并记录 `no_progress`,把控制权交回(默认让模型总结当前进展) |
|
||||
|
||||
第三层是实践中最有用的:模型经常在两三个状态间来回,硬上限只会浪费 token,无进展检测能在第 3 轮就止损。
|
||||
|
||||
### 4.6.8 Saga 补偿
|
||||
|
||||
```yaml
|
||||
nodes:
|
||||
- id: reserve
|
||||
kind: tool
|
||||
tool: inventory.reserve
|
||||
compensate: release
|
||||
- id: charge
|
||||
kind: tool
|
||||
tool: payment.charge
|
||||
compensate: refund
|
||||
- id: notify
|
||||
kind: tool
|
||||
tool: notify.send
|
||||
```
|
||||
|
||||
失败从后往前执行补偿节点(逆序),每个补偿:
|
||||
|
||||
- 必须幂等(补偿本身可能重试)。
|
||||
- 失败不阻断后续补偿(记录 `compensation_failed`,最终统一告警)。
|
||||
- 补偿结果写 `wf_node_exec`,形成完整审计链。
|
||||
|
||||
对 Agent 场景,很多"步骤"没有真正的副作用(纯 LLM 调用),补偿节点可省略;真正需要补偿的是**工具写操作**与**外部通知**。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/workflow/graph.go` | Graph/Node/Edge/Condition |
|
||||
| 新增 | `internal/domain/workflow/builder.go` | 配置 → 图(兼容旧 type) |
|
||||
| 新增 | `internal/domain/workflow/executor.go` | 调度主循环、状态机 |
|
||||
| 新增 | `internal/domain/workflow/node_exec.go` | 单节点执行、重试、超时 |
|
||||
| 新增 | `internal/domain/workflow/state.go` | 实例状态、变量作用域、无进展检测 |
|
||||
| 新增 | `internal/domain/workflow/saga.go` | 逆序补偿 |
|
||||
| 新增 | `internal/domain/workflow/checkpoint.go` | 检查点存取与续跑 |
|
||||
| 新增 | `internal/domain/workflow/condition.go` | expr 编译缓存与白名单 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/workflow_repo.go` | wf_instance/wf_node_exec |
|
||||
| 新增 | `migrations/0003_workflow.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/infrastructure/adk/adapter.go` | 删除 `runSequential`/`runFanOut`(迁入 workflow) |
|
||||
| 修改 | `internal/domain/agent/service/armory/workflow/*.go` | 从"建 Agent"改为"建 Graph" |
|
||||
| 修改 | `internal/domain/agent/service/armory/agent_node.go` | 支持 graph 类型 |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | `AgentWorkflowConfig` 增加 `Nodes/Edges/Version/PartialFailure/Concurrency` |
|
||||
| 修改 | `internal/app/config/loader.go` | graph 校验(节点唯一、边引用存在、入口可达、无环除 loop) |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | `GET /api/v1/runs/{id}/workflow`、`POST /runs/{id}/resume` |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Graph builder + Executor |
|
||||
| 修改 | `configs/agent/agent-draw-io.yaml` | 增加 graph 版本示例(保留旧配置作为 legacy 对照) |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
workflow:
|
||||
execution-mode: legacy # legacy | graph
|
||||
concurrency: 4
|
||||
partial-failure: all # all | any | best_effort
|
||||
loop:
|
||||
hard-max-iterations: 20
|
||||
no-progress-threshold: 2
|
||||
checkpoint:
|
||||
enabled: true
|
||||
store: mysql
|
||||
```
|
||||
|
||||
### 等价改写示例(draw-io 流程)
|
||||
|
||||
```yaml
|
||||
# 旧(现状)
|
||||
agent-workflows:
|
||||
- type: loop
|
||||
name: loop_refinement
|
||||
max-iterations: 3
|
||||
description: 循环优化绘图结果
|
||||
sub-agents: [agent_drawer, agent_reviewer]
|
||||
|
||||
# 新(graph)——循环体带退出条件与无进展检测
|
||||
agent-workflows:
|
||||
- type: graph
|
||||
version: "2"
|
||||
name: loop_refinement_v2
|
||||
entry: analyze
|
||||
nodes:
|
||||
- {id: analyze, kind: agent, agent: agent_analyst, output-key: analysis_result}
|
||||
- {id: draw, kind: agent, agent: agent_drawer, inputs: {analysis: "{analysis_result}"}, output-key: draft_diagram,
|
||||
retry: {max-attempts: 3, retry-on: [transient, timeout]}, timeout: 120s}
|
||||
- {id: review, kind: agent, agent: agent_reviewer, inputs: {draft: "{draft_diagram}"}, output-key: review_result}
|
||||
- {id: decide, kind: branch, when: "nodes.review.output.passed == true"}
|
||||
edges:
|
||||
- {from: analyze, to: draw}
|
||||
- {from: draw, to: review}
|
||||
- {from: review, to: decide}
|
||||
- {from: decide, to: END, when: "nodes.review.output.passed == true"}
|
||||
- {from: decide, to: draw, default: true}
|
||||
loop: {max-iterations: 3, state-key: draft_diagram}
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **真并发**:3 个各耗时 2s 的分支,`concurrency=3` 时总耗时 < 2.5s;`legacy` 模式下 ≈ 6s(对照)。
|
||||
2. **循环生效**:`max-iterations: 3` 的 loop 实际执行 3 轮(事件中 3 组 `step.started/finished`)。
|
||||
3. **无进展退出**:构造"每轮输出相同"的假 Agent,第 3 轮检测到 `no_progress` 并退出,不跑满 20 轮。
|
||||
4. **节点重试**:第 2 个节点注入 2 次超时后成功,整图成功,`attempt=3` 出现在事件里。
|
||||
5. **补偿逆序**:5 节点图在第 4 节点失败,补偿按 3→2→1 执行(顺序断言),`wf_node_exec` 有 3 条 compensating 记录。
|
||||
6. **断点续跑**:在第 3 节点执行中 `kill -9`,重启 `POST /resume`,从第 3 节点继续,前 2 节点**不重复执行**(用计数器断言)。
|
||||
7. **版本不匹配拒绝续跑**:改 `graph_version` 后 resume 返回 `GRAPH_VERSION_MISMATCH`。
|
||||
8. `go test -race` 通过;100 次并发图执行无 goroutine 泄漏(`goleak`)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **图构造单测**:配置 → 图的映射(旧 type 三种、非法边、环检测、入口不可达)。
|
||||
- **确定性执行测试**:fake Executor 按脚本返回,断言节点调用顺序、变量传递、事件序列。
|
||||
- **故障注入**:第 N 节点失败/超时/panic,验证重试、降级、补偿、整图状态。
|
||||
- **续跑测试**:用真实 MySQL 存检查点,在中间状态重启进程(`exec.Command` 起子进程)验证恢复。
|
||||
- **并发**:`goleak` + 1000 次图执行,断言无泄漏、预算不超。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 旧配置行为变化(loop 从 1 次变 N 次) | `execution-mode=legacy` 默认;release note 明确;灰度按 agent 切 |
|
||||
| 真并发导致下游限流 | 并发度默认 4 + 每工具令牌桶(P1);`partial-failure=all` 时快速取消 |
|
||||
| 补偿逻辑误删数据 | 补偿节点默认"只允许幂等、只允许反向操作"白名单;高危补偿需审批(P6) |
|
||||
| 检查点表写入放大 | 只在节点开始时写、结束更新,不逐 token 落;按 `run_id` 归档 |
|
||||
| expr 表达式注入 | 白名单环境 + 只读 AST 求值,禁止函数调用副作用 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(3 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-34 `max-iterations` 配置无效
|
||||
|
||||
**位置**:`normalizeDefaults` in `internal/app/config/loader.go`(补默认值)、`NewLoopAgent` in `internal/infrastructure/adk/adapter.go`(构建与分发)
|
||||
|
||||
**问题概述**:YAML 支持 `max-iterations`,loader 也会补默认值 3,但 `adk.Agent` 没有该字段,`NewLoopAgent` 不读取它,`runWithVars` 把 `loop` 和 `parallel` 一起丢给 `runFanOut`,导致 `max-iterations` 完全无效。
|
||||
|
||||
**影响**:用户以为配置了循环优化(如 drawio 的 `loop_refinement`),实际上只执行一次 fan-out,配置产生误导。
|
||||
|
||||
**修复方案**:按参考文档实现真正的 `runLoop`:
|
||||
|
||||
1. `adk.Agent` 增加 `maxIterations int`;
|
||||
2. `newWorkflowAgent` 按 kind 保存该值(或拆分构建方法);
|
||||
3. `runWithVars` 增加 `case "loop": return a.runLoop(...)`;
|
||||
4. `runLoop` 内按迭代次数执行并把上一轮结果写入 scope。
|
||||
|
||||
> **归属**:P5 | **状态**:✅ | **历史编号**:P1-2
|
||||
|
||||
### F-35 `parallel` 并非真正并发
|
||||
|
||||
**位置**:`runFanOut` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:`runFanOut` 是普通 for 循环,子 Agent 串行执行;`parallel` 命名与实际行为不符。
|
||||
|
||||
**影响**:并行工作流没有加速效果,多子 Agent 场景延迟线性叠加。
|
||||
|
||||
**修复方案**:`runFanOut` 改为 `goroutine + sync.WaitGroup + 有序结果切片`,并考虑子 Agent 的失败策略(快速失败 or 全部收集)。注意 `router`/`chatModel` 的并发安全性——当前 `OpenAIClient` 并发安全(只读字段),`MCPToolRouter` 需加锁(见 F-16)。
|
||||
|
||||
> **归属**:P5 | **状态**:✅ | **历史编号**:P1-3
|
||||
|
||||
### F-36 `AgentWorkflowNode.Apply` 递归实现
|
||||
|
||||
**位置**:`Apply` in `internal/domain/agent/service/armory/workflow/agent_workflow_node.go`
|
||||
|
||||
**问题概述**:用尾递归遍历 workflows,逻辑隐晦;虽然当前 `NewDynamicContext()` 每次全新、递归深度可控,但可读性差。
|
||||
|
||||
**影响**:维护成本,且未来若支持复用 context 会引入「从中间继续」的隐式语义。
|
||||
|
||||
**修复方案**:按参考文档改为 for 循环版本,并同步清理 `currentStepIndex`(若采用「循环版本一」)。改动量很小(单文件),行为等价。
|
||||
|
||||
> **归属**:P5 | **状态**:🟡 | **历史编号**:P2-1
|
||||
>
|
||||
> P5 图模型替换递归装配,需显式删除 `AgentWorkflowNode.Apply` 的递归实现
|
||||
365
docs/upgrade-plan/P6-工具治理.md
Normal file
365
docs/upgrade-plan/P6-工具治理.md
Normal file
@@ -0,0 +1,365 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P6 · 工具治理:可见范围、人工确认、沙箱与密钥 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.7 节
|
||||
> **本阶段收编缺陷**:F-37、F-38(共 2 条,明细见文末附录)
|
||||
> 上一阶段:[`P5`](P5-工作流编排.md) | 下一阶段:[`P7`](P7-可观测与评测.md)
|
||||
|
||||
|
||||
# 4.7 P6 · 工具治理:可见范围、人工确认、沙箱与密钥
|
||||
|
||||
## 目标
|
||||
|
||||
把"所有注册的工具对所有 Agent 全开放、密钥明文躺在 YAML 里、stdio 工具直接跑在宿主机"的现状,升级为**统一治理面**:谁能看见哪些工具、调用要不要人批、在什么环境里执行、密钥从哪来。对应面试官 B 的第三阶段(MCP / Worker / 执行环境安全 / Vault / 持久化记忆 / Session 生命周期)。
|
||||
|
||||
本阶段同时兑现 P1 留下的决策:Skill 从"仅注入 instruction"升级为"沙箱内可调用"(见 `P1-工具网关.md` 的 4.2.8 节),并移除 `skills.mode` 开关。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 无工具可见范围:`ChatModelNode` 把 `tool-mcp-list` 里的工具全部注册给模型 | `armory/chat_model_node.go` |
|
||||
| 无权限/审批:任何工具只要注册即可被调用 | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`、`ToolRouter` in `internal/domain/agent/ports/ports.go` |
|
||||
| 无沙箱:`stdio` MCP 通过 `exec.Command` 直接在宿主进程组里跑 | `ai/tools.go` |
|
||||
| 无密钥托管:API Key 来自 YAML + `.env` | `configs/agent/*.yaml`、`.env.example` 含疑似真实密钥 |
|
||||
| 无审计:谁在什么时候调了什么工具,无记录 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.7.1 三层治理模型
|
||||
|
||||
```
|
||||
① 可见范围(Visibility):模型能不能"看到"这个工具
|
||||
↓
|
||||
② 调用策略(Policy):看到之后,这次调用 allow / deny / require_approval
|
||||
↓
|
||||
③ 执行隔离(Sandbox):批准之后,在哪个环境里、以什么权限执行
|
||||
```
|
||||
|
||||
三层职责分离的好处:可见范围是**静态配置**(启动时定),策略是**运行时判定**(按主体/参数/上下文),沙箱是**执行细节**(与策略解耦)。面试里能讲清这个分层,比笼统说"做了权限控制"高一个档次。
|
||||
|
||||
### 4.7.2 策略模型与求值
|
||||
|
||||
```go
|
||||
// internal/domain/security/policy.go
|
||||
type Effect string
|
||||
|
||||
const (
|
||||
EffectAllow Effect = "allow"
|
||||
EffectDeny Effect = "deny"
|
||||
EffectRequireApproval Effect = "require_approval"
|
||||
)
|
||||
|
||||
type Subject struct {
|
||||
TenantID string
|
||||
UserID string
|
||||
Roles []string
|
||||
AgentID string
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
Subject Subject
|
||||
Tool string
|
||||
Effect tool.SideEffect
|
||||
Args json.RawMessage
|
||||
RunID string
|
||||
SessionID string
|
||||
Context map[string]any // 时间、渠道、风险分等
|
||||
}
|
||||
|
||||
type Decision struct {
|
||||
Effect Effect
|
||||
RuleID string
|
||||
Reason string
|
||||
Approvers []string
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type Engine interface {
|
||||
Evaluate(ctx context.Context, req Request) (Decision, error)
|
||||
}
|
||||
```
|
||||
|
||||
**求值顺序(必须确定)**:
|
||||
|
||||
```
|
||||
1. 显式 deny 规则(任一命中 → deny,短路)
|
||||
2. 显式 require_approval 规则(任一命中 → 需审批)
|
||||
3. 显式 allow 规则(任一命中 → allow)
|
||||
4. 默认策略:EffectRead → allow;Write/Destructive/External → require_approval(可配 deny)
|
||||
```
|
||||
|
||||
**"deny 优先"是安全默认**:规则有冲突时永远取最严格的。规则本身用 YAML 声明 + expr 条件:
|
||||
|
||||
```yaml
|
||||
# configs/policies.yaml
|
||||
version: 1
|
||||
defaults:
|
||||
read: allow
|
||||
write: require_approval
|
||||
destructive: deny
|
||||
external: require_approval
|
||||
|
||||
rules:
|
||||
- id: deny-pii-export
|
||||
match:
|
||||
tool: ["crm.export*", "user.dump*"]
|
||||
effect: deny
|
||||
reason: "禁止导出用户明细"
|
||||
|
||||
- id: auto-allow-internal-search
|
||||
match:
|
||||
tool: ["search.*", "kb.search"]
|
||||
effect: [read]
|
||||
effect: allow
|
||||
|
||||
- id: big-refund-needs-manager
|
||||
match:
|
||||
tool: ["payment.refund"]
|
||||
when: "args.amount > 1000"
|
||||
effect: require_approval
|
||||
approvers: [manager]
|
||||
ttl: 30m
|
||||
|
||||
- id: deny-off-hours-writes
|
||||
match:
|
||||
effect: [write, destructive]
|
||||
when: "now().Hour() < 9 || now().Hour() > 19"
|
||||
effect: deny
|
||||
reason: "非工作时段禁止写操作"
|
||||
```
|
||||
|
||||
`match.tool` 支持通配,`when` 是 expr(环境变量 `args` / `subject` / `now` / `context`)。规则编译期校验、求值 p99 < 1ms,结果可按 `(tool, effect, 参数哈希)` 缓存。
|
||||
|
||||
### 4.7.3 人工确认(HITL)流程
|
||||
|
||||
```
|
||||
工具调用 → Policy 判定 require_approval
|
||||
│
|
||||
├─ 写 agent_approval(status=pending, expires_at=now+ttl)
|
||||
├─ Run 状态 → waiting_approval
|
||||
├─ 发事件 approval.required(含工具名、参数摘要、风险说明)
|
||||
└─ 挂起(保存检查点,释放 goroutine)
|
||||
│
|
||||
├─ 用户批准 → 写 decision=approved → 唤醒 Run(从检查点续跑)→ 执行工具
|
||||
├─ 用户拒绝 → decision=rejected → 工具返回 "denied by user" → 模型改计划(L5 降级)
|
||||
└─ 超时 → decision=expired → 同拒绝,且记录指标
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_approval` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`step_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tool_name` VARCHAR(128) NOT NULL,
|
||||
`args_digest` CHAR(64) NOT NULL COMMENT '参数 sha256,避免存敏感原文',
|
||||
`args_preview` TEXT NULL COMMENT '脱敏后的参数预览',
|
||||
`risk` VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
`status` VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending|approved|rejected|expired',
|
||||
`decided_by` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`decided_at` DATETIME(3) NULL,
|
||||
`reason` VARCHAR(512) NOT NULL DEFAULT '',
|
||||
`expires_at` DATETIME(3) NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_pending` (`tenant_id`,`status`,`expires_at`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
API:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/approvals?status=pending` | 待办列表 |
|
||||
| POST | `/api/v1/approvals/{id}/approve` | `{reason, remember_for: session\|never}` |
|
||||
| POST | `/api/v1/approvals/{id}/reject` | `{reason}` |
|
||||
|
||||
**`remember_for: session`** 是体验关键:同一个会话内同类工具不再重复弹窗(存 `session` 级豁免表),否则用户会被审批疲劳拖死。
|
||||
|
||||
**挂起不能占资源**:Run 挂起时**不持有 goroutine**,靠检查点 + 事件驱动恢复。这是"waiting_approval 状态"存在的意义——如果用 `time.Sleep` 轮询,1000 个待审批请求就是 1000 个阻塞的 goroutine。
|
||||
|
||||
### 4.7.4 沙箱执行
|
||||
|
||||
```go
|
||||
// internal/domain/sandbox/ports.go
|
||||
type Spec struct {
|
||||
Image string
|
||||
Cmd []string
|
||||
Env map[string]string // 只允许白名单注入
|
||||
WorkDir string
|
||||
Timeout time.Duration
|
||||
MemoryMB int
|
||||
CPUShares int
|
||||
NetworkMode string // none | egress-proxy | host(仅 dev)
|
||||
ReadOnlyFS bool
|
||||
Mounts []Mount // 只读挂载输入,可写挂载输出
|
||||
}
|
||||
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, spec Spec, stdin []byte) (Result, error)
|
||||
Kill(ctx context.Context, id string) error
|
||||
}
|
||||
```
|
||||
|
||||
三种实现,按风险分级选择:
|
||||
|
||||
| 实现 | 隔离级别 | 适用 | 依赖 |
|
||||
|---|---|---|---|
|
||||
| `local` | 无(仅超时+资源限制) | 本地开发 | — |
|
||||
| `docker` | 容器(只读根、无网、内存/CPU 限额、非 root) | stdio MCP、代码执行 | Docker |
|
||||
| `wasm`(wazero) | 进程内沙箱 | 纯计算型插件 | 无 |
|
||||
|
||||
默认:`stdio` MCP 与"执行代码"类工具走 `docker`;`local` 仅在 `env=local` 且显式开启时可用。
|
||||
|
||||
**出口网络**:`egress-proxy` 模式通过一个白名单代理(只允许配置的域名)出网,防止工具被诱导外发数据(prompt injection 的常见利用链)。
|
||||
|
||||
### 4.7.5 密钥托管(Vault)
|
||||
|
||||
```go
|
||||
// internal/domain/security/secret.go
|
||||
type Ref struct {
|
||||
Provider string // env | file | kms
|
||||
Path string // e.g. "agent/testAgent03/api-key"
|
||||
Key string
|
||||
}
|
||||
|
||||
type Resolver interface {
|
||||
Resolve(ctx context.Context, ref Ref) (string, error)
|
||||
}
|
||||
```
|
||||
|
||||
配置里不再写明文:
|
||||
|
||||
```yaml
|
||||
ai-api:
|
||||
base-url: ${BAIDU_BASE_URL}
|
||||
api-key: ${vault:agents/testAgent03#api_key}
|
||||
```
|
||||
|
||||
四条规则:
|
||||
|
||||
1. **懒解析**:只在真正调用时解析,不启动时全量解密(减少密钥驻留时间)。
|
||||
2. **绝不落日志**:日志/事件/trace 统一过 `Redact` 中间件,按正则与已知密钥值做掩码(`sk-****abcd`)。
|
||||
3. **可轮换**:`file` provider 监听文件变更热重载;KMS 按 TTL 缓存。
|
||||
4. **最小暴露**:只有需要工具的 Executor 能拿到解引用能力,模型永远看不到密钥。
|
||||
|
||||
### 4.7.6 MCP 生命周期治理
|
||||
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| Server 注册表 | 每个 MCP Server 一条记录:名称、传输、健康状态、工具清单、最后发现时间 |
|
||||
| 健康检查 | 每 30s `tools/list` 探活;连续 3 次失败标记 `unhealthy`,其工具从模型可见列表移除 |
|
||||
| 工具热刷新 | 定时(5min)或手动 `POST /admin/mcp/{name}/refresh` 重新发现 |
|
||||
| 熔断开关 | `POST /admin/mcp/{name}/disable` 立即摘除该 Server 的所有工具 |
|
||||
| 命名空间 | 工具名统一 `server.tool`,避免不同 Server 同名覆盖(修复 F-13) |
|
||||
| 速率限制 | 每 Server 独立令牌桶,防止一个 Server 拖垮全局 |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/security/policy.go` | Subject/Request/Decision/Engine |
|
||||
| 新增 | `internal/domain/security/approval.go` | Approval 聚合、状态机、TTL |
|
||||
| 新增 | `internal/domain/security/secret.go` | Ref/Resolver 端口 |
|
||||
| 新增 | `internal/domain/security/redact.go` | 脱敏规则 |
|
||||
| 新增 | `internal/domain/sandbox/ports.go` | Spec/Runner |
|
||||
| 新增 | `internal/domain/skill/exec.go` | Skill Runner(脚本执行契约,见 `P1-工具网关.md` 的 4.2.8 节) |
|
||||
| 新增 | `internal/infrastructure/skill/executor.go` | 把 Skill script 包装为 `tool.Spec`,执行体走 `sandbox.Runner` |
|
||||
| 新增 | `internal/infrastructure/security/policy_yaml.go` | 规则加载、expr 求值、缓存 |
|
||||
| 新增 | `internal/infrastructure/security/approval_repo.go` | approval 表读写 |
|
||||
| 新增 | `internal/infrastructure/security/vault_env.go` / `vault_file.go` | 两种 Resolver |
|
||||
| 新增 | `internal/infrastructure/sandbox/local.go` / `docker.go` / `wasm.go` | 三种 Runner |
|
||||
| 新增 | `internal/infrastructure/sandbox/egress.go` | 出口白名单代理 |
|
||||
| 新增 | `internal/domain/tool/approval_gate.go` | 网关第 5 步的实现 |
|
||||
| 新增 | `migrations/0004_security.up.sql` | agent_approval / agent_audit |
|
||||
| 修改 | `internal/domain/tool/gateway.go` | 接入 Policy 与 Approval |
|
||||
| 修改 | `internal/domain/agent/service/armory/chat_model_node.go` | 只注册 `Visibility=model` 的工具 |
|
||||
| 修改 | `internal/infrastructure/ai/tools.go` | stdio 执行改走 sandbox.Runner |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Policy/Vault/Sandbox |
|
||||
| 修改 | `internal/trigger/http/*` | approvals/admin 端点 + 鉴权中间件 |
|
||||
| 修改 | `configs/agent/*.yaml` | 密钥改 `${vault:...}`;工具加 `visibility` |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **可见范围**:给 Agent 配 `visibility: human_only` 的工具,模型请求中**不出现**该工具(抓包断言),但人工可以直接调用。
|
||||
2. **策略生效**:`deny` 规则命中时工具不执行(下游 mock 零调用),返回 `permission` 错误且 Run 继续(模型改计划)。
|
||||
3. **审批闭环**:写类工具触发 `waiting_approval`,批准后 3s 内继续执行;拒绝则模型收到 denied 并改口;超时自动拒绝。
|
||||
4. **挂起不占资源**:10 个并发待审批 Run,进程 goroutine 数不增长(对比基线 < +5)。
|
||||
5. **沙箱隔离**:stdio 工具尝试 `curl` 外网被拒;尝试写 `/etc` 失败;内存超 256MB 被杀;超时被杀。
|
||||
6. **密钥不泄露**:全量日志 grep 不到任何真实 key;`args_preview` 中敏感字段已掩码。
|
||||
7. **MCP 摘除**:disable 某 Server 后 1s 内其工具从模型可见列表消失,调用返回 `not_found` 而非挂起。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- 策略引擎:50 条规则冲突矩阵表驱动测试,断言"deny 优先"。
|
||||
- 审批:状态机单测 + 集成(真 DB + HTTP)。
|
||||
- 沙箱:用 alpine 镜像跑 `sh -c` 测试网络/写盘/资源三类限制;CI 标记 `-tags=sandbox`,无 Docker 时跳过。
|
||||
- 安全:`gosec` + 自写测试断言日志脱敏(构造假密钥写入日志,断言输出为掩码)。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 审批导致体验断崖 | `remember_for: session`;只对 write/destructive 默认审批;read 全自动 |
|
||||
| 沙箱性能开销(容器启动 ~300ms) | 预热容器池;纯计算走 wasm;非高风险工具走 local+超时 |
|
||||
| 策略规则写错导致全拒 | 启动时 dry-run 校验 + `policy.mode=shadow`(只记录不拦截)灰度 |
|
||||
| Vault 不可用导致全站不可用 | 本地缓存 + 启动时预热 + 降级为 env(告警) |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(2 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-37 `stdio` / `local` 传输运行时不可执行
|
||||
|
||||
**位置**:`validateMCPConfig` in `internal/infrastructure/ai/tools.go`(构建)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:配置层支持 stdio/local,`buildStdioMCPTools` 会构建 `MCPTool`,但运行时 `CallTool` 只处理 `clients` 里的 SSE 客户端,stdio/local 一律报「transport not supported in runtime」/「not callable」。此外 local 传输是更彻底的桩:`buildLocalMCPTools`(`validateMCPConfig` in `internal/infrastructure/ai/tools.go`)只认识硬编码的 `echoLocalTool`,其他名字直接报 `local mcp tool %q is not registered in go`,而即便是 `echoLocalTool` 也没注册到 `clients`,调用时同样落到「transport not supported」。
|
||||
|
||||
**影响**:`stdio` 与 `local` 是「能配置不能跑」的假功能;文档(CLAUDE.md/README)却宣称支持三种传输,存在误导。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 要么实现 stdio(启动子进程 + JSON-RPC over stdin/stdout)与 local(内置 Go 工具注册表)执行器;
|
||||
- 要么在配置校验阶段直接拒绝 stdio/local,并同步修正文档,避免用户踩坑。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P6 | **状态**:✅ | **历史编号**:P1-10
|
||||
>
|
||||
> stdio MCP 走 docker 沙箱;local 内置工具注册表在 P6 一并补齐
|
||||
|
||||
### F-38 MCP 客户端连接状态没有「代际」隔离,旧连接的错误会污染新连接
|
||||
|
||||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go`(`pending` / `streamErr` 为共享字段,`signalStreamErr` 广播)
|
||||
|
||||
```go
|
||||
func (c *MCPSSEClient) signalStreamErr(err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
select {
|
||||
case c.streamErr <- err:
|
||||
default:
|
||||
}
|
||||
for id, ch := range c.pending { // <- 可能已经是「新一代」的 pending
|
||||
ch <- mustJSON(...)
|
||||
close(ch)
|
||||
delete(c.pending, id)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`pending`、`streamErr`、`postURL` 都是客户端上的可变字段,没有按连接代际隔离。场景:连接 A 断开并触发重连(`shutdown` + 新 `ensureStarted` 生成新 `pending`/`streamErr`),但旧 `readLoop(A)` 退出前仍会执行 `signalStreamErr`,此时它遍历/写入的已经是新一代的 `pending`/`streamErr`,从而把「A 已断开」的错误广播给正在等 B 的请求。
|
||||
|
||||
**影响**:偶发的「刚连上却收到 stream closed / 请求失败」,难以复现和排查;并发重连时概率上升。
|
||||
|
||||
**修复方案**:为每次启动引入 `generation uint64`,把 `pending`/`streamErr`/`cancelFn` 收进 `connState` 结构体,`readLoop` 闭包捕获自己那一代,`signalStreamErr` 只操作自己那一代;或用 `context` 取消 + 带代际的 channel。
|
||||
|
||||
> **归属**:P6 | **状态**:🟡 | **历史编号**:P2-21
|
||||
>
|
||||
> P6 的 `connState` 代际隔离重构会覆盖,需点名
|
||||
357
docs/upgrade-plan/P7-可观测与评测.md
Normal file
357
docs/upgrade-plan/P7-可观测与评测.md
Normal file
@@ -0,0 +1,357 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P7 · 可观测、断言与评测:让「跑偏」可被发现 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.8 节
|
||||
> **本阶段收编缺陷**:F-39、F-40、F-41(共 3 条,明细见文末附录)
|
||||
> 上一阶段:[`P6`](P6-工具治理.md) | 下一阶段:[`P8`](P8-生产化.md)
|
||||
|
||||
|
||||
# 4.8 P7 · 可观测、断言与评测:让"跑偏"可被发现
|
||||
|
||||
## 目标
|
||||
|
||||
建立"**看得见 → 查得到 → 测得准 → 改得掉**"的闭环:全链路 trace、事件日志重放、关键节点断言、Bad Case 归集、评测集回归、内容安全。这是面试官 A "日志重放机制、关键节点断言、Bad Case 闭环复盘"三件套的完整落地。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 日志是 `fmt.Printf`,无 run_id/step_id | `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go`(`myTestPlugin`) |
|
||||
| 无 trace,跨 LLM/工具调用无法串联 | 全局 |
|
||||
| 无断言,模型答非所问无人发现 | 全局 |
|
||||
| 无评测,改动靠"感觉" | 零测试 |
|
||||
| 无内容安全,违规输出直接返回 | 全局 |
|
||||
| 无成本度量 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.8.1 Trace 模型(OpenTelemetry)
|
||||
|
||||
| Span | 关键属性 |
|
||||
|---|---|
|
||||
| `agent.run` | `run.id`, `session.id`, `agent.id`, `tenant.id`, `run.status`, `run.steps`, `tokens.total` |
|
||||
| `agent.step` | `step.kind`, `step.name`, `step.attempt`, `step.duration_ms` |
|
||||
| `llm.call` | `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `output_tokens`, `cache.read_tokens` |
|
||||
| `tool.call` | `tool.name`, `tool.effect`, `tool.attempt`, `tool.result_bytes`, `tool.degraded_level` |
|
||||
| `memory.assemble` | `memory.tokens`, `memory.breakdown.*`, `memory.compacted` |
|
||||
| `memory.retrieve` | `memory.hits`, `memory.top_score`, `memory.latency_ms` |
|
||||
| `policy.evaluate` | `policy.rule_id`, `policy.effect` |
|
||||
|
||||
采样策略:默认 `parentbased_traceidratio=0.1`;**出错与超预算的 Run 强制 100% 采样**(尾部采样需 collector,简化为"错误路径升级采样率")。
|
||||
|
||||
### 4.8.2 结构化日志规范
|
||||
|
||||
```go
|
||||
logger.Info("tool call failed",
|
||||
zap.String("event", "tool.call.failed"),
|
||||
zap.String("run_id", rc.Run.ID),
|
||||
zap.String("step_id", step.ID),
|
||||
zap.String("session_id", rc.Run.SessionID),
|
||||
zap.String("tenant_id", rc.Run.TenantID),
|
||||
zap.String("tool", call.Name),
|
||||
zap.Int("attempt", attempt),
|
||||
zap.String("error_class", failure.Class),
|
||||
zap.Duration("duration", elapsed),
|
||||
)
|
||||
```
|
||||
|
||||
**统一字段**(漏一个就没法关联):`event`、`run_id`、`step_id`、`session_id`、`tenant_id`、`agent_id`。用 `zap` 的 `With()` 在 Run 入口一次性挂上,后续全继承。
|
||||
|
||||
**禁止**:日志里出现 prompt 全文、工具原始返回、任何密钥。需要时用 `_debug=true` 开关 + 脱敏。
|
||||
|
||||
### 4.8.3 关键节点断言(Assertion)
|
||||
|
||||
```go
|
||||
// internal/domain/evals/assertion.go
|
||||
type Phase string // pre_llm | post_tool | post_step | post_run
|
||||
|
||||
type Assertion interface {
|
||||
Name() string
|
||||
Phase() Phase
|
||||
Check(ctx context.Context, env *Env) error
|
||||
}
|
||||
|
||||
type Env struct {
|
||||
Run *runtime.Run
|
||||
Step *runtime.Step
|
||||
Input string
|
||||
Output string
|
||||
Tools []ToolObservation
|
||||
Context contextasm.Bundle
|
||||
}
|
||||
```
|
||||
|
||||
内置断言(配置开关,默认只告警不阻断):
|
||||
|
||||
| 断言 | 阶段 | 规则 | 失败后果 |
|
||||
|---|---|---|---|
|
||||
| `non_empty_output` | post_run | 最终答案非空且 ≥ 10 字符 | 阻断,返回兜底话术 |
|
||||
| `budget_respected` | post_run | steps ≤ max,tokens ≤ max | 告警(说明预算配小了) |
|
||||
| `tool_result_valid` | post_tool | 符合 OutputSchema | 告警 + 标记 |
|
||||
| `no_policy_violation` | post_tool | 未调用被拒工具 | 阻断 |
|
||||
| `must_include` | post_run | 必须包含配置的关键词/事实 | 阻断(可配) |
|
||||
| `must_exclude` | post_run | 不得包含违禁内容 | 阻断 |
|
||||
| `citation_present` | post_run | 知识库问答必须带引用 | 告警 |
|
||||
| `no_tool_loop` | post_step | 同一工具同参数连续 3 次 | 阻断(防死循环,P0 预算的第二道保险) |
|
||||
| `latency_budget` | post_run | p95 超过阈值 | 告警 |
|
||||
|
||||
```yaml
|
||||
# configs/agents/testAgent03.assertions.yaml
|
||||
assertions:
|
||||
- {name: non_empty_output, action: block}
|
||||
- {name: no_tool_loop, action: block}
|
||||
- {name: must_exclude, patterns: ["<script>", "SELECT * FROM"], action: block}
|
||||
- {name: must_include, keywords: ["小林"], action: warn}
|
||||
```
|
||||
|
||||
**"关键节点断言"的本质**:把"事后人工发现"变成"运行时机器拦截"。断言失败不是崩溃,而是产生一条 `assertion.failed` 事件 +(可选)一条 Bad Case 记录。
|
||||
|
||||
### 4.8.4 确定性重放(record & replay)
|
||||
|
||||
只靠事件日志能还原"发生了什么",但还原不了"模型当时为什么这么答"。所以要记录 LLM 往返:
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_llm_record` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`step_id` CHAR(26) NOT NULL,
|
||||
`call_index` INT NOT NULL,
|
||||
`prompt_hash` CHAR(64) NOT NULL COMMENT 'messages+tools 的 sha256',
|
||||
`request` MEDIUMBLOB NULL COMMENT '压缩后的请求(可脱敏)',
|
||||
`response` MEDIUMBLOB NULL,
|
||||
`model` VARCHAR(64) NOT NULL,
|
||||
`tokens_in` INT NOT NULL DEFAULT 0,
|
||||
`tokens_out` INT NOT NULL DEFAULT 0,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_run_call` (`run_id`,`call_index`),
|
||||
KEY `idx_prompt_hash` (`prompt_hash`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**重放器**:`cmd/replay -run <id> -mode deterministic` 时,`ChatModel` 被替换为 `recordedModel`:按 `call_index` 顺序返回录制响应,**不发起真实请求**。
|
||||
|
||||
用途(三个都很实用):
|
||||
|
||||
1. **回归**:改了 prompt/装配逻辑,重放同一 run,输出应一致(或差异可解释)。
|
||||
2. **调试**:线上出问题,本地重放 30 秒复现,不需要重新烧 token。
|
||||
3. **评测**:录一批真实轨迹作为评测基线,避免"评测结果随机"。
|
||||
|
||||
**成本控制**:只录 `run.status != succeeded` 或采样 5% 的成功 run;请求体压缩(zstd)+ 30 天 TTL。
|
||||
|
||||
### 4.8.5 Bad Case 闭环
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_badcase` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`symptom` VARCHAR(64) NOT NULL COMMENT 'wrong_answer|tool_error|timeout|loop|policy|format|hallucination',
|
||||
`severity` TINYINT NOT NULL DEFAULT 3,
|
||||
`root_cause` VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'prompt|context|tool|model|config|code',
|
||||
`detail` TEXT NULL,
|
||||
`fix_commit` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`regression_case` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '关联的评测用例 ID',
|
||||
`status` VARCHAR(16) NOT NULL DEFAULT 'open' COMMENT 'open|analyzing|fixed|wontfix',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`closed_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_status` (`status`,`severity`),
|
||||
KEY `idx_agent` (`agent_id`,`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**闭环规则(写进团队流程,不只是建表)**:
|
||||
|
||||
1. 每个断言失败 / 用户点踩 / 线上 5xx 自动生成或手工登记 Bad Case。
|
||||
2. 定位 `root_cause`(五选一),**不允许填"模型不稳定"**。
|
||||
3. 修复必须附一条评测用例(`regression_case` 必填),否则不许关单。
|
||||
4. 每周看板:新增/关闭数、按 `root_cause` 分布、Top3 高频问题。
|
||||
|
||||
### 4.8.6 评测集与 CI 门禁
|
||||
|
||||
```yaml
|
||||
# testdata/evals/drawio/basic.yaml
|
||||
id: drawio-basic-001
|
||||
agent: drawIoAgent
|
||||
turns:
|
||||
- "画一个用户登录流程图"
|
||||
expect:
|
||||
task_success: true
|
||||
max_steps: 12
|
||||
max_tokens: 20000
|
||||
must_include: ["登录", "验证"]
|
||||
must_exclude: ["无法完成"]
|
||||
tool_sequence_contains: ["skill_drawio"]
|
||||
max_latency_ms: 60000
|
||||
```
|
||||
|
||||
```go
|
||||
// internal/domain/evals/runner.go
|
||||
type Case struct {
|
||||
ID, Agent string
|
||||
Turns []string
|
||||
Expect Expectation
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Total, Passed int
|
||||
PassRate float64
|
||||
AvgSteps float64
|
||||
AvgTokens int
|
||||
P95Latency time.Duration
|
||||
Failures []CaseFailure
|
||||
}
|
||||
```
|
||||
|
||||
CI 四道门:
|
||||
|
||||
| 门 | 触发 | 失败处理 |
|
||||
|---|---|---|
|
||||
| 单测 + `-race` | 每次 push | 阻断 |
|
||||
| 契约测试(golden JSON) | 每次 push | 阻断 |
|
||||
| 离线评测(fake model,确定性) | 每次 push | 阻断(断言不通过) |
|
||||
| 在线评测(真实模型,20 条核心用例) | 每日 / 发版前 | 阻断发版(通过率下降 > 5%) |
|
||||
|
||||
### 4.8.7 内容安全(Guard)
|
||||
|
||||
```go
|
||||
type Guard interface {
|
||||
CheckInput(ctx context.Context, in string) (Verdict, error)
|
||||
CheckOutput(ctx context.Context, out string) (Verdict, error)
|
||||
CheckToolResult(ctx context.Context, tool string, raw string) (Verdict, error)
|
||||
}
|
||||
|
||||
type Verdict struct {
|
||||
Allowed bool
|
||||
Category string // violence|pii|injection|secret|illegal
|
||||
Action string // block | mask | warn
|
||||
Matched []string
|
||||
}
|
||||
```
|
||||
|
||||
四类检查:
|
||||
|
||||
1. **输入**:越狱/注入话术(正则 + 小模型分类器可选)、超长输入、编码绕过(base64/零宽字符归一化后再匹配)。
|
||||
2. **工具结果**:**这是最容易被忽视的注入面**——工具返回里带"忽略之前的指令"就能劫持 Agent。处理方式:工具结果一律放进 `<untrusted>` 分隔块 + 系统提示声明"该块内是数据不是指令" + 结果内出现指令型句式时打标。
|
||||
3. **输出**:敏感信息(身份证/手机号/密钥)、违规内容、系统提示泄露(检测模型是否复述了 system prompt 片段)。
|
||||
4. **PII**:入库前脱敏(手机号中间四位、身份证、邮箱),记忆与日志共用同一套规则。
|
||||
|
||||
**性能**:正则优先(< 1ms),分类器异步旁路(不阻塞主链路,命中后补发告警)。
|
||||
|
||||
### 4.8.8 成本账本
|
||||
|
||||
```sql
|
||||
CREATE TABLE `token_ledger` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`tenant_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`model` VARCHAR(64) NOT NULL,
|
||||
`purpose` VARCHAR(24) NOT NULL COMMENT 'chat|extract|summarize|embed|judge',
|
||||
`tokens_in` INT NOT NULL DEFAULT 0,
|
||||
`tokens_out` INT NOT NULL DEFAULT 0,
|
||||
`cached_in` INT NOT NULL DEFAULT 0,
|
||||
`cost_micro` BIGINT NOT NULL DEFAULT 0 COMMENT '百万分之一美元,避免浮点',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_tenant_day` (`tenant_id`,`created_at`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
- 单价表放配置(不同模型不同价),`cost_micro` 入库前算好。
|
||||
- 看板:日/周成本、每 Run 平均成本、缓存节省占比、按 Agent 排序。
|
||||
- 告警:单租户日成本超阈值、单 Run 成本 > P99 的 3 倍。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/infrastructure/obs/otel.go` | TracerProvider、OTLP/stdout exporter |
|
||||
| 新增 | `internal/infrastructure/obs/log.go` | zap 封装 + 统一字段 + 脱敏 hook |
|
||||
| 新增 | `internal/infrastructure/obs/metrics.go` | Prometheus 指标(run/step/tool/token) |
|
||||
| 新增 | `internal/infrastructure/obs/llm_record.go` | record & replay 存储 |
|
||||
| 新增 | `internal/domain/evals/assertion.go` + `builtin.go` | 断言框架与内置断言 |
|
||||
| 新增 | `internal/domain/evals/runner.go` | 评测执行与报告 |
|
||||
| 新增 | `internal/domain/evals/report.go` | Markdown/JSON 报告 |
|
||||
| 新增 | `internal/domain/guard/guard.go` + `rules.go` + `pii.go` | 内容安全 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/badcase_repo.go` / `ledger_repo.go` / `llm_record_repo.go` | 三张表 |
|
||||
| 新增 | `migrations/0005_observability.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/domain/runtime/context.go` | Step 内自动开 span、挂日志字段 |
|
||||
| 修改 | `internal/infrastructure/adk/*.go` | 所有 LLM/工具调用埋点 |
|
||||
| 修改 | `internal/trigger/http/*` | 追踪中间件、错误 metric |
|
||||
| 修改 | `cmd/replay/main.go` | deterministic 模式 |
|
||||
| 修改 | `.github/workflows/ci.yml` | 四道门 |
|
||||
| 修改 | `internal/infrastructure/logging/logger.go` | 可配置级别/采样/输出 |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 给定 `run_id`,能在 trace 中看到完整 span 树(≥ 8 个 span),跨 LLM/工具/记忆调用。
|
||||
2. 任意一次失败 Run,`cmd/replay -mode deterministic` 能在本地复现同样输出,**零真实 API 调用**。
|
||||
3. 断言:构造"空输出"与"死循环"两个用例,运行时被拦截并产生 Bad Case。
|
||||
4. 评测:20 条核心用例,本地跑 3 次通过率方差 < 5%(确定性由 fake model 保证)。
|
||||
5. 安全:10 个注入样本(含工具结果注入),拦截率 ≥ 9/10;PII 输出被掩码。
|
||||
6. 成本:任意 Run 可查到 `cost_micro`,日汇总误差 < 2%(对比账单)。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 埋点影响性能 | span 默认采样 10%;日志异步;基准测试保证 p95 增幅 < 3% |
|
||||
| 记录 LLM 往返带来存储与隐私风险 | 压缩 + 30 天 TTL + 脱敏 + 按租户隔离;可只记 hash |
|
||||
| 断言误杀 | 默认 `warn`,灰度 `block`;每条断言可单独开关 |
|
||||
| 评测集过拟合 | 保留 30% 未公开 holdout;定期补充真实 Bad Case |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(3 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-39 SSE 无心跳、未处理客户端断连
|
||||
|
||||
**位置**:`chatStream` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:`chatStream` 只是 range outputs 并 flush,未发送心跳注释行,也未监听 `c.Request.Context().Done()`。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 反向代理(Nginx/网关)可能因长时间无数据断开连接;
|
||||
- 客户端断开后后端仍继续生成,浪费模型调用。
|
||||
|
||||
**修复方案**:启动 `time.Ticker` 定期写 `: ping\n\n`;监听 `c.Request.Context().Done()` 并取消下游(依赖 F-02)。
|
||||
|
||||
> **归属**:P7 | **状态**:✅ | **历史编号**:P2-13
|
||||
>
|
||||
> 附录 B 的 15s heartbeat
|
||||
|
||||
### F-40 日志体系不完善
|
||||
|
||||
**位置**:`internal/infrastructure/logging/logger.go`、`bootstrap.newRouter`、`newMyTestPlugin` in `internal/infrastructure/adk/adapter.go`、`main` in `cmd/server/main.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 日志级别/格式/输出目标不可配;
|
||||
- Gin 访问日志用 `gin.Logger()`,未接 zap;
|
||||
- `myTestPlugin`、`adkRunnerPlugin` 用 `fmt.Printf`,绕过日志系统;
|
||||
- `logger.Fatal` 内部 `os.Exit(1)` 会跳过 `defer logger.Sync()`。
|
||||
|
||||
**影响**:生产环境日志无法集中采集/检索;关键上下文缺失;`Sync` 未执行可能丢最后几条日志。
|
||||
|
||||
**修复方案**:按参考文档把 `logging.New(env, cfg)` 扩展为可配置(level/encoding/outputPaths);新增 `ZapLogger(logger)` 中间件替换 `gin.Logger()`;插件注入 `*zap.Logger`;`main` 中用 `logger.Error + return` 或显式 `Sync` 后再 `os.Exit`。
|
||||
|
||||
> **归属**:P7 | **状态**:✅ | **历史编号**:P2-15
|
||||
|
||||
### F-41 无 run_id / trace_id,日志无法关联一次执行
|
||||
|
||||
**位置**:`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:插件与运行时的日志只有 `fmt.Printf` 的零散输出,没有 run_id、step_id、session_id,也没有 trace 上下文;一次失败执行在日志里无法还原成一条链路。
|
||||
|
||||
**影响**:线上问题只能靠时间戳猜;多用户并发时日志互相穿插,无法归因。
|
||||
|
||||
**修复方案**:P7 统一 6 个必填日志字段(event/run_id/step_id/session_id/tenant_id/agent_id)+ 7 类 span;P0 的 `runtime.Event` 已经带 run_id/step_id,P7 只需把它接到 zap 与 OTel。
|
||||
|
||||
> **归属**:P7 | **状态**:✅
|
||||
655
docs/upgrade-plan/P8-生产化.md
Normal file
655
docs/upgrade-plan/P8-生产化.md
Normal file
@@ -0,0 +1,655 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P8 · 生产化:从「能跑」到「敢上线」 | **预估**:6–8 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.9 节
|
||||
> **本阶段收编缺陷**:F-42、F-43、F-44、F-45、F-46、F-47、F-48、F-49、F-50、F-51、F-52、F-53、F-54、F-55、F-56、F-57、F-58、F-59、F-60、F-61、F-62、F-63、F-64、F-65、F-66(共 25 条,明细见文末附录)
|
||||
> 上一阶段:[`P7`](P7-可观测与评测.md)
|
||||
|
||||
|
||||
# 4.9 P8 · 生产化:从"能跑"到"敢上线"
|
||||
|
||||
## 目标
|
||||
|
||||
补齐上线必需但"不出彩"的能力:鉴权、限流、优雅停机、健康检查、迁移、配置强校验、安全加固、部署形态。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 无鉴权:任何人可调 `/chat` | `trigger/http/agent_handler.go` |
|
||||
| CORS 反射任意 Origin + `Allow-Credentials: true` | `corsMiddleware` in `internal/app/bootstrap/bootstrap.go`(F-42) |
|
||||
| 无优雅停机:`kill` 即丢请求、MCP 连接不复位 | `(*Engine).Run` in `internal/app/bootstrap/bootstrap.go`(F-45) |
|
||||
| `writeError(c, nil)` 会 panic | `writeError` in `internal/trigger/http/agent_handler.go`(F-44) |
|
||||
| `.env.example` 含疑似真实密钥与推广链接 | `.env.example` |
|
||||
| 配置校验弱:`application.yaml` 不做 `${VAR}` 展开 | `app/config/application.go` |
|
||||
| 无健康检查、无指标端点 | 全局 |
|
||||
| 无迁移工具 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.9.1 鉴权与租户
|
||||
|
||||
```go
|
||||
// internal/trigger/http/middleware/auth.go
|
||||
type Principal struct {
|
||||
TenantID string
|
||||
UserID string
|
||||
Roles []string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
func Authenticate(cfg AuthConfig) gin.HandlerFunc
|
||||
```
|
||||
|
||||
| 模式 | 用途 | 说明 |
|
||||
|---|---|---|
|
||||
| `api_key` | 服务间调用 | `Authorization: Bearer <key>`,key 存 DB(hash),带租户与 scope |
|
||||
| `jwt` | 终端用户 | HS256/RS256,claim 含 `tenant_id`/`sub`/`roles` |
|
||||
| `none` | 本地开发 | 仅 `env=local` 允许,启动打 WARN |
|
||||
|
||||
租户来源**只从凭证取**,绝不信任请求头(当前若加 `X-Tenant-ID` 必须仅在 `env=local` 生效)。
|
||||
|
||||
### 4.9.2 限流
|
||||
|
||||
| 维度 | Key | 默认 |
|
||||
|---|---|---|
|
||||
| 租户级 QPS | `rl:t:{tenant}` | 50 |
|
||||
| 用户级并发 Run | `rl:u:{tenant}:{user}` | 4 |
|
||||
| Agent 级 QPS | `rl:a:{tenant}:{agent}` | 20 |
|
||||
| 模型 token/分钟 | `rl:tok:{tenant}` | 按套餐 |
|
||||
|
||||
算法:Redis 令牌桶(Lua 脚本保证原子),Redis 不可用时退化为进程内 `golang.org/x/time/rate` 并降额。
|
||||
|
||||
超额返回 `429 + Retry-After`,并计入 `token_ledger` 的"被限流"指标。
|
||||
|
||||
### 4.9.3 优雅停机
|
||||
|
||||
```go
|
||||
func (e *Engine) Run(ctx context.Context) error {
|
||||
srv := &http.Server{
|
||||
Addr: e.cfg.Server.Addr,
|
||||
Handler: e.Router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- srv.ListenAndServe() }()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
// 1. 停止接收新请求
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), e.cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil { ... }
|
||||
|
||||
// 2. 取消所有在途 Run(触发 P0 的 run.canceled + 检查点)
|
||||
e.runtime.CancelAll(shutdownCtx)
|
||||
|
||||
// 3. 关闭顺序:worker → MCP 客户端 → Redis → MySQL
|
||||
return e.closeAll(shutdownCtx)
|
||||
}
|
||||
```
|
||||
|
||||
关闭顺序很重要:**先停入口,再停工作,最后停存储**。反了会出现"消息已落库但 run 状态没更新"。
|
||||
|
||||
`main.go` 接 `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)`。
|
||||
|
||||
### 4.9.4 健康检查与指标
|
||||
|
||||
| 端点 | 语义 |
|
||||
|---|---|
|
||||
| `GET /healthz` | 进程存活(永远 200) |
|
||||
| `GET /readyz` | 依赖就绪(DB/Redis/至少一个 MCP 可用),未就绪 503 |
|
||||
| `GET /metrics` | Prometheus 指标(内网/鉴权) |
|
||||
|
||||
关键指标:`agent_run_total{status}`、`agent_run_duration_seconds`、`tool_call_total{tool,status}`、`llm_tokens_total{model,type}`、`memory_hit_ratio`、`approval_pending`、`budget_exhausted_total`。
|
||||
|
||||
### 4.9.5 配置强校验与迁移
|
||||
|
||||
- `application.yaml` 支持 `${VAR}` / `${VAR:-default}`(复用 loader 已有实现,抽成公共包)。
|
||||
- 启动时 `--strict-config`:未知字段、缺失必填、引用不存在(子 Agent/工具/策略/模型)一律启动失败,并打印可定位的错误路径(`agents.agent_drawer.inputs.analysis -> 未定义的 output_key`)。
|
||||
- 迁移:`cmd/migrate` + `golang-migrate`,启动时只校验 `schema_version` 是否与代码期望一致,**不在启动时自动改表**(避免多实例并发迁移)。
|
||||
|
||||
### 4.9.6 安全加固清单
|
||||
|
||||
| 项 | 处理 |
|
||||
|---|---|
|
||||
| CORS | 白名单 Origin 配置;`Allow-Credentials` 仅对白名单生效;默认关闭通配 |
|
||||
| 请求体大小 | `http.MaxBytesReader` 默认 1MB(附件另走上传端点) |
|
||||
| 超时 | ReadHeader 5s、Write 由 Run 预算控制、Idle 120s |
|
||||
| 错误回显 | 生产只返回 code + 通用信息,详细错误进日志(含 `trace_id` 供用户报障) |
|
||||
| 依赖扫描 | `govulncheck` + `gosec` 进 CI |
|
||||
| 密钥 | `.env.example` 只留占位;仓库加 `gitleaks` pre-commit |
|
||||
| 越权 | P2 的 `Authorize` 全覆盖;新增端点默认要求鉴权 |
|
||||
| 日志 | 脱敏中间件(P6 的 `Redact`) |
|
||||
|
||||
### 4.9.7 部署形态
|
||||
|
||||
```yaml
|
||||
# docker-compose 增加 app 服务(生产用 K8s)
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
environment:
|
||||
APP_CONFIG: /etc/agent/application.yaml
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8091/readyz"]
|
||||
interval: 10s
|
||||
deploy:
|
||||
replicas: 2
|
||||
resources: { limits: { cpus: "2", memory: 2G } }
|
||||
```
|
||||
|
||||
多实例注意:会话缓存(Redis 共享)、`FOR UPDATE SKIP LOCKED` 的 worker(天然多实例安全)、审批与挂起状态在 DB(无粘性会话需求)、限流在 Redis(全局生效)。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/trigger/http/middleware/auth.go` | API Key / JWT / none |
|
||||
| 新增 | `internal/trigger/http/middleware/ratelimit.go` | 令牌桶 + Redis Lua |
|
||||
| 新增 | `internal/trigger/http/middleware/recover.go` | panic 恢复 + 统一错误 |
|
||||
| 新增 | `internal/trigger/http/middleware/trace.go` | trace_id 注入与回传 |
|
||||
| 新增 | `internal/trigger/http/health.go` | healthz/readyz/metrics |
|
||||
| 新增 | `internal/app/config/expand.go` | `${VAR}` 展开(从 loader 抽出复用) |
|
||||
| 新增 | `internal/app/config/strict.go` | 严格校验与错误路径 |
|
||||
| 新增 | `internal/domain/security/auth.go` | Principal / Token 校验端口 |
|
||||
| 新增 | `cmd/migrate/main.go` | 迁移 CLI |
|
||||
| 修改 | `cmd/server/main.go` | signal.NotifyContext + 优雅停机 |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | http.Server、中间件链、关闭顺序、CORS 白名单 |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 鉴权、参数校验、错误码映射、修 `writeError(nil)` |
|
||||
| 修改 | `internal/api/response/response.go` | 统一错误结构(code/message/trace_id) |
|
||||
| 修改 | `.env.example` | 去真实密钥 |
|
||||
| 修改 | `deployments/docker-compose.yml` | 修 redis networks 引用、加 app 服务 |
|
||||
| 修改 | `Dockerfile`(新增) | 多阶段构建、非 root、只读根 |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 无凭证请求返回 401;跨租户访问返回 403;`env=local` 下 `auth.mode=none` 可用。
|
||||
2. 限流:单租户 100 QPS 打 10s,通过率≈配置值,超额 429 且带 `Retry-After`。
|
||||
3. 优雅停机:`kill -TERM` 时在途 20 个请求全部正常返回(无 502),进程 30s 内退出。
|
||||
4. `writeError(c, nil)` 构造用例不再 panic(有单测)。
|
||||
5. CORS:非白名单 Origin 预检被拒;白名单通过。
|
||||
6. `--strict-config` 下故意写错一个字段,启动失败并打印精确路径。
|
||||
7. `readyz` 在 MySQL 断开时返回 503,恢复后 10s 内转 200。
|
||||
8. 压测:2 副本各 2C2G,200 QPS 持续 5min,p95 < 2s(不含 LLM 耗时),错误率 < 0.1%。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 开启鉴权导致现有前端 401 | 前端与后端同步发版;`auth.mode=api_key` 只对 `/api/v1/**` 生效,静态资源豁免 |
|
||||
| 严格配置校验阻断老配置 | 提供 `--migrate-config` 自动补默认值;`strict` 默认关闭一个版本 |
|
||||
| 限流误伤内部批处理 | 内部调用走独立 API Key + 更高配额 |
|
||||
| 优雅停机时间不够 | `shutdown-timeout` 默认 30s,可配;超过则强制取消并落检查点 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(25 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-42 CORS 允许任意 Origin 携带凭证
|
||||
|
||||
**位置**:`corsMiddleware` in `internal/app/bootstrap/bootstrap.go` `corsMiddleware()`
|
||||
|
||||
```go
|
||||
origin := c.GetHeader("Origin")
|
||||
if origin != "" {
|
||||
c.Header("Access-Control-Allow-Origin", origin) // 反射任意 Origin
|
||||
c.Header("Vary", "Origin")
|
||||
} else {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
...
|
||||
c.Header("Access-Control-Allow-Credentials", "true") // 且允许凭证
|
||||
```
|
||||
|
||||
**问题概述**:把请求方 `Origin` 原样回显到 `Access-Control-Allow-Origin`,同时打开 `Allow-Credentials: true`,等价于允许互联网上任意站点带着用户凭证(Cookie/Authorization)跨源读取本服务响应。
|
||||
|
||||
**影响**:任何恶意网页都能以受害者身份调用 `/api/v1/*`,属于典型的跨源凭证泄露,必须修。当前项目虽无登录态 Cookie,但前端登录信息存在 Cookie、且 Authorization 头被允许,风险真实存在。
|
||||
|
||||
**修复方案**:引入 Origin 白名单配置(如 `server.allowed-origins`),仅当 `origin` 命中白名单时才回显,并同时设置 `Vary: Origin`;未命中直接不回 `Allow-Origin`。默认只允许 `http://localhost:3000`。示例:
|
||||
|
||||
```go
|
||||
allowed := map[string]bool{"http://localhost:3000": true}
|
||||
if origin != "" && allowed[origin] {
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
c.Header("Vary", "Origin")
|
||||
```
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-1
|
||||
|
||||
### F-43 `.env.example` 被 git 跟踪且含疑似密钥与推广链接
|
||||
|
||||
**位置**:`.env.example:16,25`(已被 git 跟踪)
|
||||
|
||||
```text
|
||||
OPENAI_API_KEY=sk-A7B5Wv41qabcdefg**********7yoCxlcU
|
||||
BAIDU_SEARCH_MCP_SSE_ENDPOINT=sse?api_key=bce-v3/ALTAK-wSdZlzasdfghjkl**********
|
||||
...
|
||||
# 中转站推荐:https://codez.zwenooo.link/register?aff=c3yW
|
||||
```
|
||||
|
||||
**问题概述**:`.env` 已在 `.gitignore` 中,但 `.env.example` 反而把疑似真实 Key(虽被 `*` 部分打码)和推广/返利链接提交进了仓库历史。即使 `*` 是打码,前缀 `sk-A7B5Wv41q...` 与 `ALTAK-wSdZl...` 仍可能泄露账号线索。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 仓库公开/共享时等于泄露密钥线索;若曾用过真实 Key,存在被滥用的可能。
|
||||
- `.env.example` 本应是「可复制的模板」,现在却会让 `cp .env.example .env` 的用户直接拿到错误/失效配置。
|
||||
- 推广链接进入代码仓库不符合工程规范。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
1. 把 `.env.example` 中真实值全部改为 `replace-me` / `your-model-name`。
|
||||
2. 移除推广链接。
|
||||
3. 若这些 Key 曾真实可用,立即在供应商侧吊销并轮换。
|
||||
4. 加 pre-commit / CI 检查,扫描 `sk-`、`ALTAK`、`api_key=` 等模式。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-2
|
||||
|
||||
### F-44 `writeError(c, nil)` 会 panic
|
||||
|
||||
**位置**:`writeError` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
```go
|
||||
func writeError(c *gin.Context, err error) {
|
||||
var appErr *types.AppError
|
||||
if errors.As(err, &appErr) { ... }
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, err.Error())) // err 为 nil 时 panic
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`errors.As(nil, ...)` 返回 false,随后调用 `err.Error()` 触发 nil 指针 panic。虽然当前调用方都传非 nil,但这是库函数级别的隐患。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
```go
|
||||
if err == nil {
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, types.InfoUnknownError))
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-7
|
||||
>
|
||||
> 统一 `response.Error(c, err)`,内部做 nil 保护
|
||||
|
||||
### F-45 没有优雅停机
|
||||
|
||||
**位置**:`main` in `cmd/server/main.go`、`Run` in `internal/app/bootstrap/bootstrap.go` `Engine.Run`
|
||||
|
||||
```go
|
||||
if err := engine.Run(); err != nil { logger.Fatal(...) }
|
||||
// Engine.Run -> e.Router.Run(addr) // 阻塞,没有 Shutdown
|
||||
```
|
||||
|
||||
**问题概述**:没有监听 `SIGINT` / `SIGTERM`,没有 `http.Server.Shutdown(ctx)`,没有等待在途请求。进程被 `Ctrl+C` 或容器编排 `SIGTERM` 时会直接中断。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 正在执行的 Agent 请求(可能已经调用 LLM / 写库)被硬中断,产生半成品状态。
|
||||
- SSE 连接被立即切断。
|
||||
- 容器滚动发布期间出现请求失败。
|
||||
|
||||
**修复方案**:在 `Engine.Run` 中改用显式 `http.Server`:
|
||||
|
||||
```go
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: e.Router,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
go srv.ListenAndServe()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
return srv.Shutdown(shutdownCtx)
|
||||
```
|
||||
|
||||
这同时解决 F-54(`http.Server` 无超时)。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-8
|
||||
|
||||
### F-46 配置校验缺失
|
||||
|
||||
**位置**:`validateTable` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:只校验了必填字段、workflow type、MCP 传输类型,未校验:
|
||||
|
||||
- `agent-workflows[].sub-agents` 是否为空;
|
||||
- 子 Agent 名称是否存在;
|
||||
- Agent name 是否重复;
|
||||
- `runner.agent-name` 是否存在于 agents 或 workflows;
|
||||
- `tool-skills-list[].path` 是否存在、`type` 是否合法;
|
||||
- workflow 名称是否重复。
|
||||
|
||||
**影响**:错误配置延迟到 Armory 装配甚至运行时才暴露;`sub-agents` 写错会「少一个子 Agent 甚至空 workflow」但启动不报错。
|
||||
|
||||
**修复方案**:在 `validateTable` 中构建 agent/workflow 名称集合,做存在性与重复性校验;把 `runner.agent-name`、`sub-agents` 校验前置到配置加载阶段,让报错信息精确定位到 YAML 字段。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-8
|
||||
>
|
||||
> `--strict-config` 收口;建议前移到 P2 之前执行,见 `README.md` 的执行顺序
|
||||
|
||||
### F-47 跨文件同名 table 静默覆盖
|
||||
|
||||
**位置**:`loadAgentTables` in `internal/app/bootstrap/bootstrap.go`
|
||||
|
||||
```go
|
||||
for name, table := range tables {
|
||||
merged[name] = table // 后加载文件覆盖先加载
|
||||
}
|
||||
```
|
||||
|
||||
**影响**:两个 YAML 文件里写了同名 table 时,前者被静默丢弃,排查困难。
|
||||
|
||||
**修复方案**:合并时检测重复并报错,或明确「后者覆盖前者」并打警告日志。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-4
|
||||
>
|
||||
> `--strict-config` 可覆盖,需显式加「跨文件同名 table 即报错」
|
||||
|
||||
### F-48 环境变量在 YAML 解析前展开
|
||||
|
||||
**位置**:`LoadAgentTables` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:`expandEnvPlaceholders(string(data))` 先做字符串替换,再 `yaml.Unmarshal`。
|
||||
|
||||
**影响**:环境变量值包含 YAML 特殊字符(`:`、`#`、换行、引号)时会破坏 YAML 结构,报错信息指向解析失败而非环境变量。
|
||||
|
||||
**修复方案**:给 `.env` 值加引号的约定(文档化);或改为「先解析,再对字符串字段做展开」,从根上避免注入破坏结构。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-5
|
||||
|
||||
### F-49 YAML 非严格解析
|
||||
|
||||
**位置**:`LoadAgentTables` in `internal/app/config/loader.go`、`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:`yaml.Unmarshal` 忽略未知字段,字段名拼错不会报错。
|
||||
|
||||
**影响**:如 `base-url` 写成 `base_url` 会静默取零值,最终表现为「必填校验失败」或运行异常,定位成本高。
|
||||
|
||||
**修复方案**:使用 `yaml.NewDecoder(bytes.NewReader(...))` + `dec.KnownFields(true)` 开启严格模式。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-6
|
||||
|
||||
### F-50 `application.yaml` 不做环境变量替换
|
||||
|
||||
**位置**:`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:直接 `yaml.Unmarshal`,`configs/application.yaml` 里的值写死;`.env` 中 `MYSQL_DSN`、`REDIS_ADDR` 实际未被 bootstrap 使用。
|
||||
|
||||
**影响**:不同环境(local/test/prod)需要改文件,无法用 env 覆盖;也导致 `.env.example` 里的 `MYSQL_DSN`/`REDIS_ADDR` 形同虚设。
|
||||
|
||||
**修复方案**:复用 `loader.go` 的 `expandEnvPlaceholders`,在 `LoadApplication` 解析前对内容做展开,把 DSN/Redis 地址改成 `${MYSQL_DSN}` 等占位符。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-7
|
||||
|
||||
### F-51 应用配置校验偏弱
|
||||
|
||||
**位置**:`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:只校验 `llm.request-timeout`,未校验 `app.name`、`server.addr` 合法性、`agent.config-paths` 非空、`required=true` 时 DSN/Addr 非空。
|
||||
|
||||
**影响**:错误配置延迟到 bootstrap 或运行时,报错不明确。
|
||||
|
||||
**修复方案**:在 `LoadApplication` 末尾统一做一次语义校验,返回聚合错误(含字段名),让启动即失败、失败信息可操作。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-9
|
||||
|
||||
### F-52 DTO 缺少 binding 校验 / GET 接口无校验
|
||||
|
||||
**位置**:`internal/api/dto/agent.go`、`createSession` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `CreateSessionRequest`、`ChatRequest` 都没有 `binding:"required"`;
|
||||
- `GET /create_session` 直接取 query 参数,为空要到下游才报错;
|
||||
- `message` 无长度限制。
|
||||
|
||||
**影响**:无效请求返回 `0001` 而不是 `0002`;超长 message 直接送入模型,浪费 token 并可能触发上游 400。
|
||||
|
||||
**修复方案**:给必填字段加 `binding:"required"`;给 `Message` 加 `binding:"max=..."`;GET 接口显式校验或改为 POST 单一入口。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-12
|
||||
>
|
||||
> 方案提了 `MaxBytesReader`;DTO 的 `binding` tag 与字段长度上限需点名
|
||||
|
||||
### F-53 未知错误直接回显内部信息
|
||||
|
||||
**位置**:`writeError` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
```go
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, err.Error()))
|
||||
```
|
||||
|
||||
**问题概述**:把内部错误原文返回给客户端,可能包含上游 URL、响应片段(`openai upstream 500: {...}`)、文件路径等。
|
||||
|
||||
**影响**:信息泄露,攻击者可据此探测上游服务。
|
||||
|
||||
**修复方案**:对外返回 `types.InfoUnknownError` 之类的通用文案,详细错误只写日志(配合 request id)。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-14
|
||||
|
||||
### F-54 `http.Server` 缺少超时、`Engine` 无 Close
|
||||
|
||||
**位置**:`Run` in `internal/app/bootstrap/bootstrap.go` `Engine.Run`
|
||||
|
||||
**问题概述**:`gin.Engine.Run` 内部创建默认 `http.Server`,无 `ReadHeaderTimeout`/`ReadTimeout`/`WriteTimeout`/`IdleTimeout`,存在慢速攻击与连接堆积风险;同时没有 `Close`/`Shutdown` 句柄。
|
||||
|
||||
**修复方案**:与 F-45 一并改为显式 `http.Server` 并设置合理超时;为 `Engine` 增加 `Close(ctx)`。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-18
|
||||
|
||||
### F-55 CORS 缺少 `Expose-Headers` / `Max-Age`
|
||||
|
||||
**为什么优化**:预检结果无法缓存,增加 OPTIONS 请求;若未来返回自定义头前端读不到。
|
||||
|
||||
**方案**:与 F-42 一起补 `Access-Control-Max-Age` 和必要的 `Access-Control-Expose-Headers`。
|
||||
|
||||
**改动量**:很小。
|
||||
|
||||
**影响**:减少预检开销,前端可用性更完整。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-10
|
||||
|
||||
### F-56 `docker-compose.yml` 中 redis 引用了未声明的网络,compose 无法启动
|
||||
|
||||
**位置**:`deployments/docker-compose.yml`
|
||||
|
||||
```yaml
|
||||
redis:
|
||||
networks:
|
||||
- voice-input-net # <- 未在顶层 networks 中声明
|
||||
...
|
||||
networks:
|
||||
ai-agent-scaffold: # <- 只声明了这个
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
**问题概述**:redis 服务引用的 `voice-input-net` 在顶层 `networks:` 中不存在(明显是从别的项目复制过来的)。`docker compose -f deployments/docker-compose.yml up -d` 会因为 “service redis refers to undefined network” 而校验失败,MySQL 能起、Redis 起不来(或需手工创建该网络)。
|
||||
|
||||
**影响**:CLAUDE.md 与 README 推荐的本地基础设施启动命令直接不可用;即使手工绕过,Redis 与 MySQL 也不在同一网络,无法互访。
|
||||
|
||||
**修复方案**:把 redis 的 `networks` 改为 `ai-agent-scaffold`(与 mysql 一致),删除遗留的 `voice-input-net`。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-11
|
||||
|
||||
### F-57 全项目没有鉴权,`userId` 完全由客户端控制
|
||||
|
||||
**位置**:`internal/trigger/http/agent_handler.go`(无认证中间件)、`CreateSessionRequest` in `internal/api/dto/agent.go`
|
||||
|
||||
**问题概述**:所有 `/api/v1/*` 接口完全开放;`userId` 直接取自请求体/query,服务端不校验其真实性,也不与任何凭证绑定。前端登录页只是把 `user` 写进 Cookie,后端完全不感知(`grep "Auth|middleware" internal/trigger internal/app` 只命中 CORS 里的 `Authorization` 头名)。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 任何调用方可伪造任意 `userId`,以他人身份创建会话、发消息、读同一 Session 上下文(F-23 的 sessionId 不校验会进一步放大);
|
||||
- 一旦引入对话历史/计费/审计,就是越权与数据泄露;
|
||||
- `createSessionQuery` 允许 GET 传 `userId`,更易被日志/Referer 泄露。
|
||||
|
||||
**修复方案**:接入认证中间件(JWT / API Key / 网关透传身份),从凭证解析 `userId` 而非信任入参;至少在 `chat.Service` 层校验 `userId` 与凭证一致。CORS 已允许 `Authorization` 头,具备接入条件。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-12
|
||||
|
||||
### F-58 MySQL 库名与端口在三个文件里互不一致
|
||||
|
||||
**位置**:`deployments/docker-compose.yml`、`configs/application.yaml`、`.env.example:6` / `.env:6`
|
||||
|
||||
**问题概述**:同一套本地环境出现三种库名与两种端口:
|
||||
|
||||
| 来源 | 库名 | 端口 |
|
||||
|---|---|---|
|
||||
| `deployments/docker-compose.yml` | `ai-agent-scaffold` | 13306:3306 |
|
||||
| `configs/application.yaml` | `ai-agent-scaffold-go` | 13306 |
|
||||
| `.env` / `.env.example` | `ai_agent_scaffold_go` | `.env` 用 3306 |
|
||||
|
||||
由于 MySQL 目前未接入,问题被掩盖;一旦按 F-26 启用 MySQL,连接会直接失败(库不存在)。
|
||||
|
||||
**影响**:启用持久化时立刻踩坑;三处配置让排查成本变高。
|
||||
|
||||
**修复方案**:统一为一个库名(建议 `ai_agent_scaffold_go`)与一个端口(compose `13306`),并让 `application.yaml` 用 `${MYSQL_DSN}` 占位符(依赖 F-50),使 `.env` 成为唯一事实来源。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-19
|
||||
>
|
||||
> 统一库名 + Redis 端口(6379/16379),写进 P8 部署清单
|
||||
|
||||
### F-59 `.env` 里的 `APP_ENV` 与 `SERVER_ADDR` 根本不生效
|
||||
|
||||
**位置**:`main` in `cmd/server/main.go`、`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:`logging.New(appCfg.App.Env)` 的 `appCfg.App.Env` 来自 `configs/application.yaml` 的 `app.env`;监听地址来自 `server.addr`。`.env` 里的 `APP_ENV` / `SERVER_ADDR` 在 Go 代码中**从未被读取**(`grep "APP_ENV|SERVER_ADDR" *.go` 无命中)。
|
||||
|
||||
**影响**:把 `.env` 的 `APP_ENV` 改成 `prod` 不会切换日志级别、也不会关闭 Gin debug 日志;改 `SERVER_ADDR` 不会改端口。属于典型的「看似可配实际无效」,与 F-50 同源但影响面更直接。
|
||||
|
||||
**修复方案**:让 `LoadApplication` 展开 `${APP_ENV}` / `${SERVER_ADDR}` 占位符(F-50 的统一解法),或在文档中明确这两个变量无需配置并从 `.env.example` 删除以免误导。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-20
|
||||
|
||||
### F-60 本地路径解析依赖进程 CWD,从其他目录启动会失败
|
||||
|
||||
**位置**:`resolveSkillRoot` in `internal/infrastructure/ai/tools.go`(`os.Getwd()`)、`loadAgentTables` in `internal/app/bootstrap/bootstrap.go`(`os.ExpandEnv(path)` 后直接 `os.ReadFile`)
|
||||
|
||||
**问题概述**:技能路径通过「从当前工作目录逐级向上找候选」解析;`agent.config-paths` 与 `.env` 路径也相对 CWD。代码没有以可执行文件位置或配置目录为基准。
|
||||
|
||||
**影响**:用 systemd / 容器 / IDE 以不同 `WORKDIR` 启动时可能找不到技能或 Agent 配置;`skillPathCandidates` 里硬编码的 `ai-agent-scaffold-go` 目录名让解析逻辑对仓库名敏感。
|
||||
|
||||
**修复方案**:以「配置文件所在目录」或显式 `APP_BASE_DIR` 环境变量为基准解析相对路径;技能路径优先支持绝对路径并给出清晰错误;去掉硬编码的仓库目录名候选。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-25
|
||||
>
|
||||
> 容器化 + 配置路径绝对化,写进 P8 部署清单
|
||||
|
||||
### F-61 `prod` 环境判断在多处重复
|
||||
|
||||
**位置**:`newRouter` in `internal/app/bootstrap/bootstrap.go`、`New` in `internal/infrastructure/logging/logger.go`
|
||||
|
||||
**问题概述**:`env == "prod" || env == "production"` 出现了三次,且 `bootstrap` 还要正反各判断一遍。
|
||||
|
||||
**影响**:新增环境名(如 `staging`/`release`)需要改多处,易漏。
|
||||
|
||||
**修复方案**:抽 `func isProduction(env string) bool`(放在 `app/config` 或 `pkg`),三处复用。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-17
|
||||
>
|
||||
> `isProduction` 收敛到单一实现
|
||||
|
||||
### F-62 工作区 `.env` 含真实密钥,且缺少 CI / 后端 Dockerfile / Makefile
|
||||
|
||||
**位置**:`.env`(未跟踪但存在于工作区)、仓库根目录
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `.env` 里有 2 处真实感密钥(`grep -c "sk-\|ALTAK" .env` = 2)。虽然 `.env` 已被 gitignore,但工作区若被打包/分享就会泄露;
|
||||
- 仓库没有 `.github/workflows`、没有后端 `Dockerfile`、没有 `Makefile`(只有 frontend 有 Dockerfile/build.sh)。
|
||||
|
||||
**影响**:密钥有泄露面;构建、测试、镜像化、CI 校验都没有标准化入口,新人上手和发布一致性靠人肉。
|
||||
|
||||
**修复方案**:轮换 `.env` 中的密钥并仅保留在本地/密钥管理;补最小 CI(`go build` + `go vet` + `gofmt -l` 校验)和后端多阶段 `Dockerfile`;可选加 `Makefile` 统一 `build/test/run/lint`。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-19
|
||||
|
||||
### F-63 `validateTable` 错误顺序随机,timeout 校验文案与行为不符
|
||||
|
||||
**位置**:`validateTable` in `internal/app/config/loader.go`、`validateMCPEntry` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 必填字段放在 `map[string]string` 里遍历,Go map 顺序随机,同一份错误配置每次报错字段可能不同;
|
||||
- `request-timeout < 0` 才报错,文案却是 "must be positive",即 `0` 被允许(随后被 `normalizeTimeout` 改成 300000)。
|
||||
|
||||
**影响**:错误信息不稳定,测试/排障时对不上;文案误导用户以为 0 非法。
|
||||
|
||||
**修复方案**:必填校验改为有序 `[]struct{name, value string}`;明确 `0` 的语义(「使用默认值」)并把文案改为 `must not be negative`。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-20
|
||||
>
|
||||
> 严格校验重写时一并统一报错顺序与文案
|
||||
|
||||
### F-64 缺少就绪探针/指标,SSE 响应头不完整
|
||||
|
||||
**位置**:`newRouter` in `internal/app/bootstrap/bootstrap.go`(`/healthz`)、`chatStream` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 只有 `/healthz` 恒返回 `{"status":"ok"}`,不检查任何依赖(MCP/LLM 连通性),也没有 `/readyz` 与 `/metrics`;
|
||||
- `chatStream` 只设置 `Content-Type: text/event-stream`,缺少 `Cache-Control: no-cache`、`Connection: keep-alive`、`X-Accel-Buffering: no` 等常见 SSE 头。
|
||||
|
||||
**影响**:编排系统无法区分「进程活着」与「可以接流量」;经过 Nginx 等反代时 SSE 可能被缓冲,破坏「逐字输出」体验。
|
||||
|
||||
**修复方案**:补 `/readyz`(可选地探测关键依赖)与基础指标;`chatStream` 补齐 SSE 标准响应头。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-21
|
||||
|
||||
### F-65 本地基础设施配置存在遗留项与弱口令
|
||||
|
||||
**位置**:`deployments/mysql/my.cnf:16-18,22-24`、`deployments/redis/redis.conf`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `my.cnf` 里留着 `binlog-do-db = big_market_01` / `big_market_02`(明显从其他项目复制),与本项目无关;
|
||||
- 自定义 `slow-query-log-file` / `log-error` 指向 `/var/log/mysql/`,在官方镜像中该目录可能不存在或不可写,可能导致容器启动异常;
|
||||
- `redis.conf` 只有 `bind 0.0.0.0` 与 `port 6379`,没有 `requirepass`,而 compose 把 6379 映射到宿主机;
|
||||
- `MYSQL_ROOT_PASSWORD: 123456` 为弱口令,且与 `application.yaml` 中的 DSN 明文一致。
|
||||
|
||||
**影响**:本地环境可能起不来(日志路径/库名)或存在弱口令暴露面;这些配置会被当作「模板」复制到真实环境。
|
||||
|
||||
**修复方案**:清理 `my.cnf` 中与本项目无关的 binlog/slow-log 配置;Redis 增加 `requirepass` 并在配置中用 `${REDIS_PASSWORD}`;弱口令改为 `.env` 注入,并在 README 标注「仅本地示例」。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-22
|
||||
>
|
||||
> 弱口令与遗留配置写进 P8 安全清单
|
||||
|
||||
### F-66 其他值得顺手处理的小问题
|
||||
|
||||
**位置**:多处
|
||||
|
||||
| 问题 | 位置 | 说明 / 建议 |
|
||||
|---|---|---|
|
||||
| 入站请求体无大小限制 | `internal/trigger/http/agent_handler.go` 的 `ShouldBindJSON` | 未使用 `http.MaxBytesReader` 或 Gin body limit,超大 JSON 可导致内存膨胀;与 F-18 对称,建议加统一上限 |
|
||||
| 没有编译期接口断言 | `ports/ports.go` 及各 adapter | 建议加 `var _ ports.ChatModel = (*EinoChatModel)(nil)` 之类的断言,避免接口漂移在运行期才暴露 |
|
||||
| `Eino*` 命名与实际实现不符 | `internal/infrastructure/ai/eino_adapter.go` | 类型叫 `EinoProvider`/`EinoChatModel`/`EinoTool`,但实现完全基于自研 `OpenAIClient`,Eino 未被使用(见 F-67);建议改名为 `OpenAIProvider` 等,减少误导 |
|
||||
| `AgentWorkflowNode.build` 的 `buildOrder` 冗余 | `build` in `internal/domain/agent/service/armory/workflow/agent_workflow_node.go` | 已有 `builders map[WorkflowType]workflowBuilder`,可直接 `n.builders[workflow.Type]` 查表,无需再维护 `buildOrder` 列表并循环匹配 |
|
||||
| `DynamicContext` 封装风格不一致 | `DynamicContext` in `internal/domain/agent/service/armory/context.go` | `ModelAPI`/`ChatModel` 是导出的可变字段,其余状态都走带锁方法;建议统一(要么都走方法,要么明确这两者只在装配期单线程写入) |
|
||||
| MySQL healthcheck 未带密码、MySQL 8 参数已弃用 | `deployments/docker-compose.yml`、`deployments/mysql/my.cnf` | healthcheck 用 `mysqladmin ping -h localhost` 无 `-p`(部分版本会产生告警);`--default-authentication-plugin` 在 MySQL 8.4 将被移除,8.0 下也会告警,建议按需清理 |
|
||||
| `ToolFactory.BuildTools` 存在不可达分支 | `BuildTools` in `internal/infrastructure/ai/tools.go` | `validateMCPConfig` 已保证 `kind` 是 local/sse/stdio 之一,后面 `case config.SSE != nil` / `case config.Stdio != nil` 是永远走不到的历史兼容分支,建议删除 |
|
||||
| `LoadApplication` 忽略 `app/llm` 以外的语义校验 | `LoadApplication` in `internal/app/config/application.go` | 与 F-51 同源,建议一次性补齐并集中 |
|
||||
|
||||
**影响**:均为小问题,不阻塞运行,但会累积成维护噪音。
|
||||
|
||||
**修复方案**:按上表逐项小改;建议与 F-67、F-61 一起作为一个「代码整洁」批次处理。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-23
|
||||
>
|
||||
> `MaxBytesReader` 已覆盖;编译期断言、`Eino*` 改名、不可达分支进第 0 天清单
|
||||
169
docs/upgrade-plan/README.md
Normal file
169
docs/upgrade-plan/README.md
Normal file
@@ -0,0 +1,169 @@
|
||||
> **文档类型**:plan(路线图与缺陷台账索引)| **总方案**:[`../agent-platform-upgrade-plan.md`](../agent-platform-upgrade-plan.md)
|
||||
|
||||
# Agent 平台升级 · 阶段规划清单
|
||||
|
||||
这套文档是「按顺序迭代」的入口:九个阶段各一份计划书(`P0-…md` 到 `P8-…md`),每份都自包含「为什么改、改成什么、改哪些文件、怎么验收」,并把历史审计里的缺陷按编号收编进来(`F-xx`)。
|
||||
|
||||
## 怎么用
|
||||
|
||||
1. 想了解全局(现状、蓝图、路线图、横切专题、面试映射):读 [`../agent-platform-upgrade-plan.md`](../agent-platform-upgrade-plan.md)。
|
||||
2. 想开工某一阶段:读该阶段计划书;「当前问题」告诉你为什么,「设计」告诉你怎么做,「涉及的代码模块」告诉你在哪改,「验收标准」告诉你什么时候算完。
|
||||
3. 想知道某条历史缺陷落到哪了:查本文第 4 节的台账,或直接搜 `F-xx`。
|
||||
4. 每完成一个阶段:把台账里对应条目的状态从 🟡 改为 ✅,并在阶段计划书的「验收标准」下方勾选。
|
||||
|
||||
## 1. 阶段清单
|
||||
|
||||
| 阶段 | 计划书 | 主题 | 预估 | 前置 | 收编缺陷 |
|
||||
|---|---|---|---|---|---|
|
||||
| P0 | [`P0-运行时内核.md`](P0-运行时内核.md) | 运行时内核:让每一次执行都成为一等公民 | 8–10 人日 | — | 9 条 |
|
||||
| P1 | [`P1-工具网关.md`](P1-工具网关.md) | 工具网关:把「能调通」变成「调不坏」 | 10–12 人日 | P0 | 13 条 |
|
||||
| P2 | [`P2-会话持久化.md`](P2-会话持久化.md) | 会话生命周期与持久化:让 Agent 记得住、找得回 | 8–10 人日 | P0 | 9 条 |
|
||||
| P3 | [`P3-记忆与知识.md`](P3-记忆与知识.md) | 记忆与知识:三层记忆 + 可检索知识库 | 12–15 人日 | P2 | 1 条 |
|
||||
| P4 | [`P4-上下文工程.md`](P4-上下文工程.md) | 上下文工程:20 轮之后还记得第一句话 | 10–12 人日 | P2、P3 | 1 条 |
|
||||
| P5 | [`P5-工作流编排.md`](P5-工作流编排.md) | 工作流编排:从「线性 Chain」到「可补偿的状态机」 | 12–15 人日 | P2 | 3 条 |
|
||||
| P6 | [`P6-工具治理.md`](P6-工具治理.md) | 工具治理:可见范围、人工确认、沙箱与密钥 | 10–12 人日 | P1、P2 | 2 条 |
|
||||
| P7 | [`P7-可观测与评测.md`](P7-可观测与评测.md) | 可观测、断言与评测:让「跑偏」可被发现 | 10–12 人日 | P0 | 3 条 |
|
||||
| P8 | [`P8-生产化.md`](P8-生产化.md) | 生产化:从「能跑」到「敢上线」 | 6–8 人日 | P0–P7 | 25 条 |
|
||||
|
||||
合计 85–110 人日(单人 4–5 个月,双人约 10 周,排期见总方案第 7 章)。
|
||||
|
||||
## 2. 执行顺序
|
||||
|
||||
- **必须先做**:第 0 天技术债清扫(0.5–1 人日)→ P0 运行时内核。P0 是后八个阶段的挂载点,它定义的 `Run/Step/Event/Budget` 是全系统的公共语言。
|
||||
- **建议前移**:P8 里的「配置严格校验」提前到 P2 之前做。P3 的 embedding、P5 的图引用、P6 的策略规则都以「配置引用正确」为前提,晚做会让后三个阶段建立在一堆可能指向不存在节点的配置上。
|
||||
- **可以并行**:P3(记忆)与 P5(工作流)之间没有强依赖,P4 依赖 P3 的检索端口但不依赖其实现,可先按端口开发。
|
||||
- **串行依赖链**:P0 → P1 → P2 → P4(P4 需要 P2 的消息持久化与 P3 的检索),P5 / P6 / P7 在 P2 之后可任意顺序。
|
||||
|
||||
## 3. 第 0 天:技术债清扫(P0 之前,0.5–1 人日)
|
||||
|
||||
这些改动零行为变更,但能让后续每个 PR 的 diff 干净(否则 CRLF 会把改动变成全文件 diff)。
|
||||
|
||||
| 缺陷 | 动作 | 状态 |
|
||||
|---|---|---|
|
||||
| F-67 | 第 0 天删除 `internal/infrastructure/dependencies` 并 `go mod tidy` | ⬜ 待做 |
|
||||
| F-68 | 第 0 天清理死代码清单(13 项) | ⬜ 待做 |
|
||||
| F-69 | `.gitattributes` + CI `gofmt -l` 门 | ⬜ 待做 |
|
||||
| F-70 | P2 的 DTO 层显式拒绝 + 「明确不支持」清单 | ⬜ 待做 |
|
||||
| F-71 | P0 拆包会顺带删除一部分,其余进第 0 天清理清单 | ⬜ 待做 |
|
||||
| F-72 | 已由 `52e9387` 修复,仅需在清单中标注完成 | ✅ 已在 `52e9387` 完成 |
|
||||
|
||||
## 4. 缺陷台账索引(76 条)
|
||||
|
||||
来源:历史审计 71 条(原编号 `P0-1…P3-23`,见「历史编号」列)+ 本方案补充 5 条(无历史编号)。状态:✅ 已被某阶段完整收编 50 条;🟡 部分收编、需在执行时点名 21 条;❌ 未收编、需单独立项 5 条。
|
||||
|
||||
| 编号 | 历史编号 | 症状 | 归属 | 状态 |
|
||||
|---|---|---|---|---|
|
||||
| F-01 | P0-6 | 流式取消时 `OpenAIClient.Stream` goroutine 泄漏 | P0 | 🟡 |
|
||||
| F-02 | P1-4 | HTTP 请求 context 未传递到 Agent | P0 | ✅ |
|
||||
| F-03 | P2-2 | `DynamicContext.agentGroup` 名称覆盖与静默跳过 | P0 | ✅ |
|
||||
| F-04 | P2-3 | 装配与加载顺序不确定 | P0 | ✅ |
|
||||
| F-05 | P2-17 | Service 层方法无 context | P0 | ✅ |
|
||||
| F-06 | P3-4 | `AgentFactory` 为三种 workflow 各定义一个方法 | P0 | ✅ |
|
||||
| F-07 | P3-12 | `InMemoryAgentRegistry.Register` 无校验且恒返回 nil | P0 | 🟡 |
|
||||
| F-08 | P1-13 | `adkRunnerPlugin` 是空壳,`myLogPlugin` 实际没有任何 ADK 日志能力 | P0 | 🟡 |
|
||||
| F-09 | (新增) | tool-calling 循环上限硬编码为 4 次 | P0 | ✅ |
|
||||
| F-10 | P0-3 | 工具描述全部丢失,模型只能看到兜底描述 | P1 | ✅ |
|
||||
| F-11 | P0-4 | MCP `pending` map 在超时/提前返回路径泄漏 | P1 | ✅ |
|
||||
| F-12 | P0-5 | `ensureStarted` 并发首次调用会失败 | P1 | 🟡 |
|
||||
| F-13 | P0-9 | 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具 | P1 | ✅ |
|
||||
| F-14 | P1-1 | Skill 工具只暴露、不可执行 | P1 | ✅ |
|
||||
| F-15 | P1-9 | 工具参数 schema 硬编码为 `query` | P1 | ✅ |
|
||||
| F-16 | P2-10 | `MCPToolRouter` 无锁 | P1 | ✅ |
|
||||
| F-17 | P1-14 | MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警 | P1 | ✅ |
|
||||
| F-18 | P2-22 | `io.ReadAll` 无上限读取上游响应体 | P1 | 🟡 |
|
||||
| F-19 | P2-23 | 流式请求没有发送 `Accept: text/event-stream` | P1 | 🟡 |
|
||||
| F-20 | P3-15 | `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码 | P1 | 🟡 |
|
||||
| F-21 | (新增) | 任一工具失败即整轮失败(`executeToolCalls`) | P1 | ✅ |
|
||||
| F-22 | (新增) | 工具调用无单次超时,只靠 HTTP 客户端整体超时 | P1 | ✅ |
|
||||
| F-23 | P1-5 | `sessionId` 不校验归属 | P2 | ✅ |
|
||||
| F-24 | P1-6 | Session 无对话历史(Agent 实际无状态) | P2 | ✅ |
|
||||
| F-25 | P1-7 | `CreateSession` 并发竞态 | P2 | ✅ |
|
||||
| F-26 | P2-8 | MySQL / Redis 适配器未接入 | P2 | ✅ |
|
||||
| F-27 | P2-11 | 空内容错误码不准确 + 先建 Session 后校验内容 | P2 | ✅ |
|
||||
| F-28 | P2-16 | `CreateSession` 不校验 Agent 是否仍存在 | P2 | 🟡 |
|
||||
| F-29 | P3-7 | `ports.SessionStore` 无 context | P2 | ✅ |
|
||||
| F-30 | P3-13 | Session key 用 `:` 拼接存在歧义 | P2 | ✅ |
|
||||
| F-31 | (新增) | Session ID 用全局原子计数拼接,无租户维度且跨 Agent 撞号 | P2 | ✅ |
|
||||
| F-32 | P3-3 | `EmbeddingsPath` 定义但未使用 | P3 | ✅ |
|
||||
| F-33 | P2-24 | 无法配置任何生成参数 | P4 | 🟡 |
|
||||
| F-34 | P1-2 | `max-iterations` 配置无效 | P5 | ✅ |
|
||||
| F-35 | P1-3 | `parallel` 并非真正并发 | P5 | ✅ |
|
||||
| F-36 | P2-1 | `AgentWorkflowNode.Apply` 递归实现 | P5 | 🟡 |
|
||||
| F-37 | P1-10 | `stdio` / `local` 传输运行时不可执行 | P6 | ✅ |
|
||||
| F-38 | P2-21 | MCP 客户端连接状态没有「代际」隔离,旧连接的错误会污染新连接 | P6 | 🟡 |
|
||||
| F-39 | P2-13 | SSE 无心跳、未处理客户端断连 | P7 | ✅ |
|
||||
| F-40 | P2-15 | 日志体系不完善 | P7 | ✅ |
|
||||
| F-41 | (新增) | 无 run_id / trace_id,日志无法关联一次执行 | P7 | ✅ |
|
||||
| F-42 | P0-1 | CORS 允许任意 Origin 携带凭证 | P8 | ✅ |
|
||||
| F-43 | P0-2 | `.env.example` 被 git 跟踪且含疑似密钥与推广链接 | P8 | ✅ |
|
||||
| F-44 | P0-7 | `writeError(c, nil)` 会 panic | P8 | ✅ |
|
||||
| F-45 | P0-8 | 没有优雅停机 | P8 | ✅ |
|
||||
| F-46 | P1-8 | 配置校验缺失 | P8 | ✅ |
|
||||
| F-47 | P2-4 | 跨文件同名 table 静默覆盖 | P8 | 🟡 |
|
||||
| F-48 | P2-5 | 环境变量在 YAML 解析前展开 | P8 | ✅ |
|
||||
| F-49 | P2-6 | YAML 非严格解析 | P8 | ✅ |
|
||||
| F-50 | P2-7 | `application.yaml` 不做环境变量替换 | P8 | ✅ |
|
||||
| F-51 | P2-9 | 应用配置校验偏弱 | P8 | ✅ |
|
||||
| F-52 | P2-12 | DTO 缺少 binding 校验 / GET 接口无校验 | P8 | 🟡 |
|
||||
| F-53 | P2-14 | 未知错误直接回显内部信息 | P8 | ✅ |
|
||||
| F-54 | P2-18 | `http.Server` 缺少超时、`Engine` 无 Close | P8 | ✅ |
|
||||
| F-55 | P3-10 | CORS 缺少 `Expose-Headers` / `Max-Age` | P8 | ✅ |
|
||||
| F-56 | P1-11 | `docker-compose.yml` 中 redis 引用了未声明的网络,compose 无法启动 | P8 | ✅ |
|
||||
| F-57 | P1-12 | 全项目没有鉴权,`userId` 完全由客户端控制 | P8 | ✅ |
|
||||
| F-58 | P2-19 | MySQL 库名与端口在三个文件里互不一致 | P8 | 🟡 |
|
||||
| F-59 | P2-20 | `.env` 里的 `APP_ENV` 与 `SERVER_ADDR` 根本不生效 | P8 | ✅ |
|
||||
| F-60 | P2-25 | 本地路径解析依赖进程 CWD,从其他目录启动会失败 | P8 | 🟡 |
|
||||
| F-61 | P3-17 | `prod` 环境判断在多处重复 | P8 | 🟡 |
|
||||
| F-62 | P3-19 | 工作区 `.env` 含真实密钥,且缺少 CI / 后端 Dockerfile / Makefile | P8 | ✅ |
|
||||
| F-63 | P3-20 | `validateTable` 错误顺序随机,timeout 校验文案与行为不符 | P8 | 🟡 |
|
||||
| F-64 | P3-21 | 缺少就绪探针/指标,SSE 响应头不完整 | P8 | ✅ |
|
||||
| F-65 | P3-22 | 本地基础设施配置存在遗留项与弱口令 | P8 | 🟡 |
|
||||
| F-66 | P3-23 | 其他值得顺手处理的小问题 | P8 | 🟡 |
|
||||
| F-67 | P3-1 | `internal/infrastructure/dependencies` 从未被 import | DAY0 | ❌ |
|
||||
| F-68 | P3-2 | 全局死代码与未使用接口 | DAY0 | ❌ |
|
||||
| F-69 | P3-9 | `gofmt -l .` 报告所有文件(CRLF) | DAY0 | ❌ |
|
||||
| F-70 | P3-11 | `ChatContent` 的 Files / InlineDatas 被静默忽略 | DAY0 | ❌ |
|
||||
| F-71 | P3-14 | 未使用的接口方法 | DAY0 | 🟡 |
|
||||
| F-72 | P3-18 | `.gitignore` 忽略了 `docs/`,`CLAUDE.md` 也被忽略 | DAY0 | ❌ |
|
||||
| F-73 | P3-5 | 错误码体系过少、`Code` 为裸 string | GLOBAL | ✅ |
|
||||
| F-74 | P3-6 | `AppError` 不含上下文与错误链 | GLOBAL | ✅ |
|
||||
| F-75 | P3-8 | 项目零测试 | GLOBAL | ✅ |
|
||||
| F-76 | P3-16 | 空列表响应会缺少 `data` 字段,与前端约定的响应契约不一致 | GLOBAL | 🟡 |
|
||||
|
||||
跨阶段条目(`GLOBAL`)不归属任何单一阶段,落点是总方案的横切章节:
|
||||
|
||||
| 编号 | 落点 |
|
||||
|---|---|
|
||||
| F-73 | §5.1 错误码扩展 |
|
||||
| F-74 | §5.1 `Error{TraceID,Details,Cause}` |
|
||||
| F-75 | §5.6 测试金字塔 |
|
||||
| F-76 | §5.1 的响应契约需明确 `data` 空值策略 |
|
||||
|
||||
## 5. 历史评审记录(已归档)
|
||||
|
||||
两份历史文档(`项目完善报告.md`、`完善报告-评审与收编清单.md`)的内容已于 2026-11-02 全部拆入本目录并删除,结论保留如下:
|
||||
|
||||
- 历史审计共 71 条,逐条抽查 15 条**全部属实**,无虚报;综合质量 8.2/10(事实准确性 9、证据强度 9、可执行性 7、完整性 8、结构与自洽 8)。
|
||||
- 原始判断「45 条会被阶段天然消化 / 21 条需点名 / 5 条未收编」已落实为本文台账的 ✅ / 🟡 / ❌ 三档。
|
||||
- 审计本身有 5 个可改进点(同根因重复计 3 组、混用「会崩/会越权/功能谎言」三种性质、缺验收标准、约 5 条属代码整洁、配置单一事实源未升格),本次合并时已按「一条一编号、带状态、带归属」的格式消解。
|
||||
|
||||
## 6. 迭代约定
|
||||
|
||||
- **一阶段一 PR(或一组 PR)**:阶段计划书里的「验收标准」是合并条件,不是建议。
|
||||
- **开关先行**:每阶段新行为都必须有开关且默认保旧一个版本(开关表见总方案 2.5)。
|
||||
- **缺陷回填**:阶段完成后更新本文第 4 节状态列与阶段文件里的 `> **状态**` 行,这是唯一的进度事实源。
|
||||
- **不新增行号引用**:仓库约定用「反引号标识符 + 文件路径」定位代码,不用 `文件:行号`(行号必然漂移)。
|
||||
|
||||
## 7. 状态看板
|
||||
|
||||
| 阶段 | 状态 | 开始 | 完成 | 备注 |
|
||||
|---|---|---|---|---|
|
||||
| P0 | ⬜ 未开始 | — | — | |
|
||||
| P1 | ⬜ 未开始 | — | — | |
|
||||
| P2 | ⬜ 未开始 | — | — | |
|
||||
| P3 | ⬜ 未开始 | — | — | |
|
||||
| P4 | ⬜ 未开始 | — | — | |
|
||||
| P5 | ⬜ 未开始 | — | — | |
|
||||
| P6 | ⬜ 未开始 | — | — | |
|
||||
| P7 | ⬜ 未开始 | — | — | |
|
||||
| P8 | ⬜ 未开始 | — | — | |
|
||||
2
go.mod
2
go.mod
@@ -5,6 +5,7 @@ go 1.25.6
|
||||
require (
|
||||
github.com/cloudwego/eino v0.9.2
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/redis/go-redis/v9 v9.20.0
|
||||
go.uber.org/zap v1.28.0
|
||||
google.golang.org/adk v1.4.0
|
||||
@@ -49,7 +50,6 @@ require (
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
|
||||
@@ -57,7 +57,14 @@ func Build(ctx context.Context, appCfg config.Application, logger *zap.Logger) (
|
||||
agentFactory.UseToolRouter(toolRouter)
|
||||
runnerFactory := agentFactory
|
||||
|
||||
armoryFactory := factory.NewDefaultFactory(modelProvider, mcpFactory, skillFactory, agentFactory, runnerFactory, registry)
|
||||
armoryFactory := factory.NewDefaultFactory(
|
||||
modelProvider,
|
||||
mcpFactory,
|
||||
skillFactory,
|
||||
agentFactory,
|
||||
runnerFactory,
|
||||
registry,
|
||||
)
|
||||
armoryService := armory.NewService(armoryFactory.ArmoryStrategyHandler())
|
||||
|
||||
if err := armoryService.AcceptArmoryAgents(ctx, tables); err != nil {
|
||||
|
||||
@@ -42,6 +42,9 @@ func NewFactory() *Factory {
|
||||
return &Factory{plugins: defaultPlugins()}
|
||||
}
|
||||
|
||||
// UseToolRouter 注入工具路由器.
|
||||
//
|
||||
// 该路由器会被后续创建的所有 Agent 共享, Agent 在模型请求工具调用时通过它执行工具.
|
||||
func (f *Factory) UseToolRouter(router ports.ToolRouter) {
|
||||
f.router = router
|
||||
}
|
||||
@@ -103,19 +106,28 @@ func newWorkflowAgent(kind string, config model.AgentWorkflowConfig, subAgents [
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name 返回 Agent 名称, 实现 ports.Agent 接口.
|
||||
func (a *Agent) Name() string {
|
||||
return a.name
|
||||
}
|
||||
|
||||
// Description 返回 Agent 描述信息, 主要用于日志和外部展示.
|
||||
func (a *Agent) Description() string {
|
||||
return a.description
|
||||
}
|
||||
|
||||
// run 以空变量作用域执行 Agent.
|
||||
//
|
||||
// 包内普通执行入口, 调用 runWithVars 并传入空的模板变量表.
|
||||
func (a *Agent) run(ctx context.Context, content model.ChatContent) (string, error) {
|
||||
return a.runWithVars(ctx, content, map[string]string{})
|
||||
}
|
||||
|
||||
// runWithVars 根据 Agent 类型分派到具体执行逻辑.
|
||||
//
|
||||
// vars 保存 Sequential 工作流传入的模板变量, 供 instruction 中的 {output-key} 占位符替换使用.
|
||||
func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
// 按 kind 分派到 LLM / 串行 / 并行 / 循环执行策略
|
||||
switch a.kind {
|
||||
case "llm":
|
||||
return a.runLLM(ctx, content, vars)
|
||||
@@ -128,6 +140,10 @@ func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars
|
||||
}
|
||||
}
|
||||
|
||||
// stream 以流式方式执行 Agent.
|
||||
//
|
||||
// 仅 llm 类型支持真正的逐 token 流式输出;
|
||||
// workflow 类型没有独立的模型流, 因此先完整执行, 再把最终结果一次性写入 out.
|
||||
func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<- string) error {
|
||||
switch a.kind {
|
||||
case "llm":
|
||||
@@ -148,36 +164,54 @@ func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<
|
||||
}
|
||||
}
|
||||
|
||||
// runLLM 执行非流式 Tool-Calling Loop.
|
||||
//
|
||||
// 每次循环调用一次模型:
|
||||
// 1. 模型未返回工具调用时, 直接返回最终文本;
|
||||
// 2. 模型返回工具调用时, 先追加 assistant 消息, 再执行工具并把 tool 结果追加到消息列表;
|
||||
// 3. 重复上述过程, 最多迭代 maxToolCallIterations 次.
|
||||
func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
|
||||
// 最多执行 maxToolCallIterations 轮 模型调用 -> 工具执行 -> 结果回灌
|
||||
for iter := 0; iter < maxToolCallIterations; iter++ {
|
||||
reply, err := a.chatModel.Generate(ctx, messages)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 没有工具调用, 模型已给出最终答案
|
||||
if len(reply.ToolCalls) == 0 {
|
||||
return reply.Content, nil
|
||||
}
|
||||
// 追加 assistant 消息, 保留模型请求的 tool_calls
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls})
|
||||
toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 把工具结果回灌到消息列表, 供下一轮模型使用
|
||||
messages = append(messages, toolMessages...)
|
||||
}
|
||||
return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
|
||||
}
|
||||
|
||||
// streamLLM 执行流式 Tool-Calling Loop.
|
||||
//
|
||||
// 与 runLLM 的区别是: 模型返回的文本增量会实时写入 out;
|
||||
// 同时使用 finalText 暂存本轮完整文本, 用于在模型请求工具调用时构造 assistant 消息.
|
||||
// 工具调用执行完成后结果会被追加到消息列表, 并进入下一轮模型调用, 最多迭代 maxToolCallIterations 次.
|
||||
func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out chan<- string, vars map[string]string) error {
|
||||
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
|
||||
// 最多执行 maxToolCallIterations 轮流式 Tool-Calling
|
||||
for iter := 0; iter < maxToolCallIterations; iter++ {
|
||||
events, errs := a.chatModel.Stream(ctx, messages)
|
||||
// finalText 暂存本轮完整文本; toolCalls 收集工具调用; done 标记流是否正常结束
|
||||
var (
|
||||
finalText strings.Builder
|
||||
toolCalls []ports.ChatToolCall
|
||||
done bool
|
||||
)
|
||||
streamErr := error(nil)
|
||||
// 标签用于从嵌套 select 中直接跳出读取循环
|
||||
streamLoop:
|
||||
for {
|
||||
select {
|
||||
@@ -191,6 +225,7 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
if ev.Done {
|
||||
done = true
|
||||
}
|
||||
// 文本增量: 写入完整文本并转发给下游
|
||||
if ev.Delta != "" {
|
||||
finalText.WriteString(ev.Delta)
|
||||
select {
|
||||
@@ -213,12 +248,15 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
if streamErr != nil {
|
||||
return streamErr
|
||||
}
|
||||
// 没有工具调用, 本轮文本就是最终答案
|
||||
if len(toolCalls) == 0 {
|
||||
// 缺少 Done 标记, 视为流异常关闭
|
||||
if !done {
|
||||
return fmt.Errorf("agent %q stream closed without completion", a.name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// 追加 assistant 消息, 保留文本和工具调用
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: finalText.String(), ToolCalls: toolCalls})
|
||||
toolMessages, err := a.executeToolCalls(ctx, toolCalls)
|
||||
if err != nil {
|
||||
@@ -229,7 +267,12 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
return fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
|
||||
}
|
||||
|
||||
// executeToolCalls 依次执行模型请求的工具调用.
|
||||
//
|
||||
// 每个工具通过 ToolRouter 执行, 返回结果会被转换为 role=tool 的 ChatMessage,
|
||||
// 并通过 ToolCallID 与 assistant 消息中的工具调用一一对应.
|
||||
func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall) ([]ports.ChatMessage, error) {
|
||||
// 模型请求了工具但未注入路由器, 属于非法状态
|
||||
if a.router == nil {
|
||||
return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name)
|
||||
}
|
||||
@@ -239,6 +282,7 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool %q: %w", call.Name, err)
|
||||
}
|
||||
// 包装为 role=tool 的消息, 通过 ToolCallID 与 assistant 消息对应
|
||||
out = append(out, ports.ChatMessage{
|
||||
Role: ports.ChatRoleTool,
|
||||
Content: result,
|
||||
@@ -249,19 +293,29 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// runSequential 执行串行工作流.
|
||||
//
|
||||
// 子 Agent 按配置顺序依次执行, 每个子 Agent 的输出在存在 output-key 时写入 scope;
|
||||
// 后续子 Agent 的 instruction 可以通过 {output-key} 引用前面步骤的结果.
|
||||
// 返回值是最后一个子 Agent 的输出.
|
||||
func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
// 复制变量表, 避免污染外层作用域
|
||||
scope := cloneVars(vars)
|
||||
// 记录最后一个子 Agent 的输出作为工作流返回值
|
||||
var last string
|
||||
for _, sub := range a.subAgents {
|
||||
// 当前实现要求子 Agent 必须是 adk.Agent
|
||||
impl, ok := sub.(*Agent)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
|
||||
}
|
||||
// 使用当前 scope 执行, 使 instruction 能读取已产生的变量
|
||||
text, err := impl.runWithVars(ctx, content, scope)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
last = text
|
||||
// 配置了 output-key 时把输出写入变量表
|
||||
if key := strings.TrimSpace(impl.outputKey); key != "" {
|
||||
scope[key] = text
|
||||
}
|
||||
@@ -269,22 +323,33 @@ func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, va
|
||||
return last, nil
|
||||
}
|
||||
|
||||
// runFanOut 执行并行/循环工作流的聚合逻辑.
|
||||
//
|
||||
// 当前实现会依次执行所有子 Agent, 并把每个子 Agent 的输出以 [AgentName] 前缀拼接返回.
|
||||
// 注意: 当前 loop 和 parallel 都复用该逻辑, 并未真正实现并发或循环迭代.
|
||||
func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
parts := make([]string, 0, len(a.subAgents))
|
||||
// 依次执行所有子 Agent (当前实现并未真正并发)
|
||||
for _, sub := range a.subAgents {
|
||||
// 同样要求子 Agent 必须是 adk.Agent
|
||||
impl, ok := sub.(*Agent)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
|
||||
}
|
||||
// 所有子 Agent 共享同一份输入变量
|
||||
text, err := impl.runWithVars(ctx, content, vars)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 输出带 Agent 名前缀, 方便上层区分来源
|
||||
parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text))
|
||||
}
|
||||
return strings.Join(parts, "\n"), nil
|
||||
}
|
||||
|
||||
// cloneVars 复制变量表.
|
||||
//
|
||||
// Sequential 工作流使用副本保存本步骤的输出, 避免修改调用方传入的原始变量.
|
||||
func cloneVars(vars map[string]string) map[string]string {
|
||||
out := make(map[string]string, len(vars)+4)
|
||||
for k, v := range vars {
|
||||
@@ -293,6 +358,9 @@ func cloneVars(vars map[string]string) map[string]string {
|
||||
return out
|
||||
}
|
||||
|
||||
// applyVars 将模板中的 {key} 占位符替换为 vars 中对应的值.
|
||||
//
|
||||
// 模板为空或变量表为空时直接返回模板; 替换使用简单的字符串匹配, 不做转义处理.
|
||||
func applyVars(template string, vars map[string]string) string {
|
||||
if template == "" || len(vars) == 0 {
|
||||
return template
|
||||
@@ -304,6 +372,10 @@ func applyVars(template string, vars map[string]string) string {
|
||||
return out
|
||||
}
|
||||
|
||||
// initialMessages 构造一次模型调用的初始消息列表.
|
||||
//
|
||||
// instruction 非空时作为 system 消息; 用户输入始终作为 user 消息.
|
||||
// 当前实现不保存跨轮对话历史, 每次执行都从 system + user 重新开始.
|
||||
func initialMessages(instruction, userText string) []ports.ChatMessage {
|
||||
messages := make([]ports.ChatMessage, 0, 2)
|
||||
if strings.TrimSpace(instruction) != "" {
|
||||
@@ -313,14 +385,21 @@ func initialMessages(instruction, userText string) []ports.ChatMessage {
|
||||
return messages
|
||||
}
|
||||
|
||||
// CreateSession 根据用户 ID 和应用名生成会话 ID.
|
||||
//
|
||||
// 会话 ID 格式为 appName:userID:序号, 序号来自 Factory 的全局原子计数器.
|
||||
func (r *Runner) CreateSession(userID string) (string, error) {
|
||||
if strings.TrimSpace(userID) == "" {
|
||||
return "", fmt.Errorf("user id is required")
|
||||
}
|
||||
// 全局原子自增, 保证所有 Runner 的会话序号不冲突
|
||||
next := r.counter.Add(1)
|
||||
return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil
|
||||
}
|
||||
|
||||
// Run 以非流式方式执行 Runner 持有的入口 Agent.
|
||||
//
|
||||
// 执行前先通知插件, 然后把内容委托给 Agent.run, 并把最终文本包装为 []string 返回.
|
||||
func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]string, error) {
|
||||
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
|
||||
return nil, fmt.Errorf("user id and session id are required")
|
||||
@@ -328,6 +407,7 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
|
||||
if err := r.notifyPlugins(userID, sessionID, content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Runner 只能运行 adk.Agent, 这里做类型断言
|
||||
impl, ok := r.agent.(*Agent)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
|
||||
@@ -342,6 +422,10 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
|
||||
return []string{output}, nil
|
||||
}
|
||||
|
||||
// Stream 以流式方式执行 Runner 持有的入口 Agent.
|
||||
//
|
||||
// 方法在 goroutine 中执行, 返回文本输出 channel 和错误 channel;
|
||||
// 调用方通过这两个 channel 消费执行过程中的增量结果.
|
||||
func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-chan string, <-chan error) {
|
||||
outputs := make(chan string, 8)
|
||||
errs := make(chan error, 1)
|
||||
@@ -356,6 +440,7 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
// Runner 只能运行 adk.Agent, 这里做类型断言
|
||||
impl, ok := r.agent.(*Agent)
|
||||
if !ok {
|
||||
errs <- fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
|
||||
@@ -368,6 +453,10 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
|
||||
return outputs, errs
|
||||
}
|
||||
|
||||
// notifyPlugins 按配置顺序通知所有 RunnerPlugin.
|
||||
//
|
||||
// 对每个插件依次触发 OnUserMessage 和 BeforeAgent 两个生命周期回调,
|
||||
// 任一回调返回错误都会中止后续执行.
|
||||
func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatContent) error {
|
||||
for _, item := range r.plugins {
|
||||
if err := item.OnUserMessage(context.Background(), r.appName, userID, sessionID, r.agent, content); err != nil {
|
||||
@@ -380,6 +469,9 @@ func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatConte
|
||||
return nil
|
||||
}
|
||||
|
||||
// firstText 返回 ChatContent 中的第一段文本.
|
||||
//
|
||||
// 当前模型调用主要使用文本输入, 文件与内联数据暂未参与消息构造.
|
||||
func firstText(content model.ChatContent) string {
|
||||
if len(content.Texts) == 0 {
|
||||
return ""
|
||||
@@ -387,6 +479,9 @@ func firstText(content model.ChatContent) string {
|
||||
return content.Texts[0].Message
|
||||
}
|
||||
|
||||
// defaultPlugins 返回内置的 RunnerPlugin 工厂表.
|
||||
//
|
||||
// key 是 YAML 中配置的插件名, value 用于按需创建插件实例.
|
||||
func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
|
||||
return map[string]func() (ports.RunnerPlugin, error){
|
||||
"myTestPlugin": newMyTestPlugin,
|
||||
@@ -400,6 +495,9 @@ func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// resolvePlugins 根据插件名列表解析并创建 RunnerPlugin 实例.
|
||||
//
|
||||
// 列表中不存在的插件名会直接返回错误, 保证装配阶段就能发现配置问题.
|
||||
func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
|
||||
if len(names) == 0 {
|
||||
return nil, nil
|
||||
@@ -411,6 +509,7 @@ func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
|
||||
continue
|
||||
}
|
||||
builder, ok := f.plugins[pluginName]
|
||||
// 未注册的插件名在装配阶段直接报错
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("runner plugin %q is not registered", pluginName)
|
||||
}
|
||||
@@ -429,15 +528,18 @@ func newMyTestPlugin() (ports.RunnerPlugin, error) {
|
||||
|
||||
type myTestPlugin struct{}
|
||||
|
||||
// Name 返回插件名, 用于错误信息和日志展示.
|
||||
func (myTestPlugin) Name() string {
|
||||
return "myTestPlugin"
|
||||
}
|
||||
|
||||
// OnUserMessage 在用户消息到达时打印调试信息.
|
||||
func (myTestPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
|
||||
fmt.Printf("[myTestPlugin] 用户输入信息:%s\n", firstText(content))
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeforeAgent 在 Agent 开始执行前打印 Agent 名称.
|
||||
func (myTestPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
|
||||
fmt.Printf("[myTestPlugin] 智能体名称:%s\n", agent.Name())
|
||||
return nil
|
||||
@@ -448,10 +550,12 @@ type adkRunnerPlugin struct {
|
||||
plugin *plugin.Plugin
|
||||
}
|
||||
|
||||
// Name 返回 ADK 插件包装器的名称.
|
||||
func (p adkRunnerPlugin) Name() string {
|
||||
return p.name
|
||||
}
|
||||
|
||||
// OnUserMessage 在 ADK 插件注册了用户消息回调时打印调试信息.
|
||||
func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
|
||||
if p.plugin.OnUserMessageCallback() != nil {
|
||||
fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
|
||||
@@ -459,6 +563,7 @@ func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ port
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeforeAgent 在 ADK 插件注册了 Agent 开始回调时打印调试信息.
|
||||
func (p adkRunnerPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
|
||||
if p.plugin.BeforeAgentCallback() != nil {
|
||||
fmt.Printf("[%s] AGENT STARTING %s\n", p.name, agent.Name())
|
||||
|
||||
@@ -33,12 +33,16 @@ type MCPSSEClient struct {
|
||||
started bool
|
||||
postURL string
|
||||
cancelFn context.CancelFunc
|
||||
pending map[uint64]chan json.RawMessage
|
||||
pending map[uint64]chan json.RawMessage // 请求 ID: 响应 channel 的映射, 这是并发请求-响应匹配的核心
|
||||
nextID atomic.Uint64
|
||||
streamErr chan error
|
||||
endpointSig chan struct{}
|
||||
}
|
||||
|
||||
// NewMCPSSEClient 创建一个 MCP SSE 客户端实例.
|
||||
//
|
||||
// baseURI 为服务端基础地址, endpoint 为 SSE 端点路径, requestTimeoutMillis 为单次 RPC 调用的超时毫秒数.
|
||||
// 该函数只初始化配置, 不会建立连接, 连接会在首次调用工具或列出工具时按需建立.
|
||||
func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSEClient {
|
||||
timeout := time.Duration(requestTimeoutMillis) * time.Millisecond
|
||||
if timeout <= 0 {
|
||||
@@ -47,11 +51,15 @@ func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSE
|
||||
return &MCPSSEClient{
|
||||
baseURI: strings.TrimRight(baseURI, "/"),
|
||||
endpoint: endpoint,
|
||||
httpClient: &http.Client{Timeout: 0},
|
||||
httpClient: &http.Client{Timeout: 0}, // SSE 不设置超时
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// ensureStarted 确保 SSE 连接已经建立.
|
||||
//
|
||||
// 若尚未启动, 则依次完成: 发起 SSE 长连接、等待服务端下发 endpoint 事件、完成 JSON-RPC 初始化握手;
|
||||
// 失败时调用 shutdown 重置状态.
|
||||
func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
if c.started {
|
||||
@@ -61,16 +69,18 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
|
||||
c.pending = make(map[uint64]chan json.RawMessage)
|
||||
c.endpointSig = make(chan struct{})
|
||||
c.streamErr = make(chan error, 1)
|
||||
streamCtx, cancel := context.WithCancel(context.Background())
|
||||
streamCtx, cancel := context.WithCancel(context.Background()) // streamCtx 用来控制后台 SSE 读取 goroutine 的生命周期
|
||||
c.cancelFn = cancel
|
||||
c.started = true
|
||||
c.mu.Unlock()
|
||||
|
||||
// 发起 GET /sse, 建立 SSE 长连接
|
||||
if err := c.openSSE(streamCtx); err != nil {
|
||||
c.shutdown()
|
||||
return err
|
||||
}
|
||||
|
||||
// 等待服务器通过 SSE 推送 endpoint 事件
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer waitCancel()
|
||||
select {
|
||||
@@ -83,6 +93,7 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
|
||||
return fmt.Errorf("mcp sse endpoint event timeout: %w", waitCtx.Err())
|
||||
}
|
||||
|
||||
// 执行 JSON-RPC 初始化握手
|
||||
if err := c.initialize(ctx); err != nil {
|
||||
c.shutdown()
|
||||
return err
|
||||
@@ -90,6 +101,9 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// openSSE 向服务端发起 GET 请求建立 SSE 长连接
|
||||
//
|
||||
// 成功后会启动后台 readLoop goroutine 持续读取事件流.
|
||||
func (c *MCPSSEClient) openSSE(ctx context.Context) error {
|
||||
target := c.baseURI + c.endpoint
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
@@ -106,13 +120,17 @@ func (c *MCPSSEClient) openSSE(ctx context.Context) error {
|
||||
_ = resp.Body.Close()
|
||||
return fmt.Errorf("mcp sse status %d: %s", resp.StatusCode, truncate(string(raw), 200))
|
||||
}
|
||||
go c.readLoop(resp)
|
||||
go c.readLoop(resp) // 启动 readLoop goroutine 持续读取 SSE 事件
|
||||
return nil
|
||||
}
|
||||
|
||||
// readLoop 在后台 goroutine 中持续读取 SSE 事件流
|
||||
//
|
||||
// 按 event/data 行解析事件, 并在事件结束时根据事件类型分发处理;
|
||||
// 读取失败时会通知所有等待中的 RPC 调用.
|
||||
func (c *MCPSSEClient) readLoop(resp *http.Response) {
|
||||
defer resp.Body.Close()
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
reader := bufio.NewReader(resp.Body) // 获取带缓冲逐行读的字节流
|
||||
var event string
|
||||
var dataBuf strings.Builder
|
||||
dispatch := func() {
|
||||
@@ -133,7 +151,7 @@ func (c *MCPSSEClient) readLoop(resp *http.Response) {
|
||||
}
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if err != nil { // 读取失败, 通知所有等待中的 RPC 调用, 并退出循环
|
||||
if err != io.EOF {
|
||||
c.signalStreamErr(fmt.Errorf("mcp sse read: %w", err))
|
||||
} else {
|
||||
@@ -158,6 +176,10 @@ func (c *MCPSSEClient) readLoop(resp *http.Response) {
|
||||
}
|
||||
}
|
||||
|
||||
// handleEndpoint 处理 SSE 的 endpoint 事件
|
||||
//
|
||||
// 解析并记录服务端下发的 POST 消息地址;
|
||||
// 若已记录过地址, 则尝试将数据按普通 message 事件处理.
|
||||
func (c *MCPSSEClient) handleEndpoint(data, eventName string) {
|
||||
if c.postURLAlreadySet() {
|
||||
if eventName == "" {
|
||||
@@ -174,12 +196,16 @@ func (c *MCPSSEClient) handleEndpoint(data, eventName string) {
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// postURLAlreadySet 返回当前是否已经记录 POST 消息地址.
|
||||
func (c *MCPSSEClient) postURLAlreadySet() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.postURL != ""
|
||||
}
|
||||
|
||||
// resolvePostURL 将服务端返回的 endpoint 数据解析为完整可用的 POST 地址;
|
||||
//
|
||||
// 若数据为相对路径, 则基于 baseURI 进行解析.
|
||||
func (c *MCPSSEClient) resolvePostURL(raw string) string {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || !parsed.IsAbs() {
|
||||
@@ -194,6 +220,9 @@ func (c *MCPSSEClient) resolvePostURL(raw string) string {
|
||||
return raw
|
||||
}
|
||||
|
||||
// handleMessage 处理 SSE 的 message 事件
|
||||
//
|
||||
// 解析 JSON-RPC 2.0 响应, 根据响应 ID 找到对应的等待 channel 并投递结果或错误.
|
||||
func (c *MCPSSEClient) handleMessage(data string) {
|
||||
var resp struct {
|
||||
ID json.Number `json:"id"`
|
||||
@@ -231,11 +260,17 @@ func (c *MCPSSEClient) handleMessage(data string) {
|
||||
close(ch)
|
||||
}
|
||||
|
||||
// mustJSON 将任意值序列化为 JSON 字节
|
||||
//
|
||||
// 这里仅用于构造错误包装对象, 因此忽略序列化错误.
|
||||
func mustJSON(v any) json.RawMessage {
|
||||
raw, _ := json.Marshal(v)
|
||||
return raw
|
||||
}
|
||||
|
||||
// signalStreamErr 错误广播
|
||||
//
|
||||
// 在 SSE 流读取失败时向所有等待中的 RPC 调用广播错误, 并清理 pending 映射, 避免 goroutine 泄漏.
|
||||
func (c *MCPSSEClient) signalStreamErr(err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
@@ -250,6 +285,9 @@ func (c *MCPSSEClient) signalStreamErr(err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// shutdown 取消后台读取 goroutine 并重置客户端状态
|
||||
//
|
||||
// 状态重置后客户端可以再次尝试启动.
|
||||
func (c *MCPSSEClient) shutdown() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
@@ -261,6 +299,9 @@ func (c *MCPSSEClient) shutdown() {
|
||||
c.pending = nil
|
||||
}
|
||||
|
||||
// initialize 执行 MCP 协议初始化握手
|
||||
//
|
||||
// 发送 initialize 请求, 随后发送 notifications/initialized 通知.
|
||||
func (c *MCPSSEClient) initialize(ctx context.Context) error {
|
||||
_, err := c.callRPC(ctx, "initialize", map[string]any{
|
||||
"protocolVersion": mcpProtocolVersion,
|
||||
@@ -279,6 +320,9 @@ func (c *MCPSSEClient) initialize(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CallTool 调用指定的 MCP 工具
|
||||
//
|
||||
// 确保连接已建立后, 将工具名与 JSON 参数通过 tools/call 发送给服务端, 并返回提取后的文本结果.
|
||||
func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (string, error) {
|
||||
if err := c.ensureStarted(ctx); err != nil {
|
||||
return "", err
|
||||
@@ -300,6 +344,7 @@ func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (st
|
||||
return extractToolText(result), nil
|
||||
}
|
||||
|
||||
// ListTools 调用 tools/list 获取服务端暴露的工具列表, 并返回所有工具名.
|
||||
func (c *MCPSSEClient) ListTools(ctx context.Context) ([]string, error) {
|
||||
if err := c.ensureStarted(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -331,6 +376,9 @@ type toolCallResult struct {
|
||||
IsError bool `json:"isError"`
|
||||
}
|
||||
|
||||
// extractToolText 从 MCP 工具调用的原始响应中提取文本内容
|
||||
//
|
||||
// 若响应不符合标准结构, 则返回原始 JSON 字符串.
|
||||
func extractToolText(raw json.RawMessage) string {
|
||||
var parsed toolCallResult
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
@@ -348,6 +396,9 @@ func extractToolText(raw json.RawMessage) string {
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
|
||||
// callRPC 发送 JSON-RPC 2.0 请求, 并通过 SSE 通道异步等待对应 ID 的响应,
|
||||
//
|
||||
// 支持 context 超时控制.
|
||||
func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (json.RawMessage, error) {
|
||||
id := c.nextID.Add(1)
|
||||
ch := make(chan json.RawMessage, 1)
|
||||
@@ -401,6 +452,9 @@ func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (
|
||||
}
|
||||
}
|
||||
|
||||
// notify 发送一个不带 ID 的 JSON-RPC 通知
|
||||
//
|
||||
// 通知无需等待服务端响应.
|
||||
func (c *MCPSSEClient) notify(ctx context.Context, method string, params any) error {
|
||||
c.mu.Lock()
|
||||
postURL := c.postURL
|
||||
@@ -438,6 +492,9 @@ type MCPToolRouter struct {
|
||||
listFailures map[string]error
|
||||
}
|
||||
|
||||
// NewMCPToolRouter 创建一个 MCP 工具路由器
|
||||
//
|
||||
// 用于注册、自动发现并分发 MCP 工具调用.
|
||||
func NewMCPToolRouter() *MCPToolRouter {
|
||||
return &MCPToolRouter{
|
||||
clients: make(map[string]*MCPSSEClient),
|
||||
@@ -447,16 +504,25 @@ func NewMCPToolRouter() *MCPToolRouter {
|
||||
}
|
||||
}
|
||||
|
||||
// Register 注册一个工具
|
||||
//
|
||||
// 内部直接委托给 RegisterAndExpand 处理.
|
||||
func (r *MCPToolRouter) Register(tool ports.Tool) {
|
||||
r.RegisterAndExpand(tool)
|
||||
}
|
||||
|
||||
// RegisterAndExpand 注册工具并对 SSE 类型的 MCP 工具进行自动展开
|
||||
//
|
||||
// 创建共享客户端、调用 tools/list 发现所有工具并逐一注册;
|
||||
// 发现失败时降级保留原始工具.
|
||||
func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool {
|
||||
mcp, ok := tool.(MCPTool)
|
||||
// 非 MCP 工具不展开,直接注册,返回原始工具
|
||||
if !ok {
|
||||
r.tools = append(r.tools, tool)
|
||||
return []ports.Tool{tool}
|
||||
}
|
||||
// 不是 SSE 传输类型的 MCP 工具也是原样注册
|
||||
if mcp.TransportType != "sse" {
|
||||
r.tools = append(r.tools, mcp)
|
||||
return []ports.Tool{mcp}
|
||||
@@ -475,6 +541,7 @@ func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool {
|
||||
r.tools = append(r.tools, mcp)
|
||||
return []ports.Tool{mcp}
|
||||
}
|
||||
// 将发现的工具名注册为 EinoTool, 并共享同一个 SSE 客户端
|
||||
expanded := make([]ports.Tool, 0, len(names))
|
||||
for _, n := range names {
|
||||
r.clients[n] = client
|
||||
@@ -486,10 +553,14 @@ func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool {
|
||||
return expanded
|
||||
}
|
||||
|
||||
// Tools 返回当前已注册的所有工具.
|
||||
func (r *MCPToolRouter) Tools() []ports.Tool {
|
||||
return r.tools
|
||||
}
|
||||
|
||||
// CallTool 根据工具名将调用分发给已注册的 MCP SSE 客户端;
|
||||
//
|
||||
// 找不到可调用客户端时返回明确错误.
|
||||
func (r *MCPToolRouter) CallTool(ctx context.Context, name, arguments string) (string, error) {
|
||||
if client, ok := r.clients[name]; ok {
|
||||
return client.CallTool(ctx, name, arguments)
|
||||
|
||||
@@ -38,7 +38,12 @@ func NewOpenAIClient(completionsURL, apiKey, model string, requestTimeout time.D
|
||||
}
|
||||
}
|
||||
|
||||
// Generate 发送非流式 Chat Completions 请求,等待完整响应后返回文本内容与工具调用列表。
|
||||
//
|
||||
// 该请求使用 stream=false,服务端会一次性返回完整 JSON 响应。
|
||||
// 返回的 ChatReply 包含模型最终文本内容;若模型决定调用工具,则同时包含工具调用列表。
|
||||
func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (ports.ChatReply, error) {
|
||||
// stream=false,构造一次性返回完整响应的普通请求
|
||||
body, err := buildRequestBody(c.model, messages, tools, false)
|
||||
if err != nil {
|
||||
return ports.ChatReply{}, err
|
||||
@@ -76,6 +81,11 @@ func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessag
|
||||
return reply, nil
|
||||
}
|
||||
|
||||
// Stream 发送流式 Chat Completions 请求,并通过 channel 持续返回增量文本、工具调用和错误。
|
||||
//
|
||||
// 调用方通过 events 接收流式事件,通过 errs 接收错误;
|
||||
// 当收到 Done=true 事件或 events channel 被关闭时,表示本次流式请求结束。
|
||||
// 流式响应中 tool_calls 是分片到达的,因此内部使用 map[int]*ChatToolCall 按 index 累积完整工具调用。
|
||||
func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (<-chan ports.ChatStreamEvent, <-chan error) {
|
||||
events := make(chan ports.ChatStreamEvent, 8)
|
||||
errs := make(chan error, 1)
|
||||
@@ -100,8 +110,9 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
|
||||
return
|
||||
}
|
||||
|
||||
// 按 index 暂存流式 tool_call,用于跨多个 SSE chunk 累积完整参数
|
||||
toolCallBuf := map[int]*ports.ChatToolCall{}
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
reader := bufio.NewReader(resp.Body) // 带缓冲逐行读取 SSE 数据
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
@@ -113,11 +124,11 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
|
||||
errs <- fmt.Errorf("openai stream read: %w", err)
|
||||
return
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
line = strings.TrimRight(line, "\r\n") // 去掉行尾换行符,兼容 \n 与 \r\n
|
||||
if line == "" || !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
continue // 忽略空行和非 data: 的 SSE 行
|
||||
}
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) // 提取 data 内容
|
||||
if payload == "[DONE]" {
|
||||
emitToolCalls(events, toolCallBuf)
|
||||
events <- ports.ChatStreamEvent{Done: true}
|
||||
@@ -153,6 +164,7 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
|
||||
current.Name = tc.Function.Name
|
||||
}
|
||||
if tc.Function.Arguments != "" {
|
||||
// arguments 是 JSON 增量片段,需要持续拼接成完整参数
|
||||
current.Arguments += tc.Function.Arguments
|
||||
}
|
||||
}
|
||||
@@ -161,6 +173,10 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
|
||||
return events, errs
|
||||
}
|
||||
|
||||
// emitToolCalls 将流式读取过程中累积的工具调用按 index 顺序发送到事件管道。
|
||||
//
|
||||
// OpenAI 流式协议中多个工具调用可能交错返回,因此内部先用 map 暂存;
|
||||
// 发送时按 index 从 0 开始遍历,保证上层拿到的工具调用顺序稳定。
|
||||
func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) {
|
||||
if len(buf) == 0 {
|
||||
return
|
||||
@@ -176,6 +192,10 @@ func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatT
|
||||
}
|
||||
}
|
||||
|
||||
// do 构造并发送 HTTP POST 请求,统一处理 Content-Type、Accept 和 Bearer 认证。
|
||||
//
|
||||
// 该方法只负责发送请求,不读取响应体;响应体由调用方负责关闭。
|
||||
// 网络层错误会包装为带上下文的错误返回。
|
||||
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.completionsURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
@@ -193,6 +213,10 @@ func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, err
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// buildRequestBody 构造 OpenAI Chat Completions 请求体,并序列化为 JSON 字节。
|
||||
//
|
||||
// stream 为 true 时生成流式请求,为 false 时生成普通请求;
|
||||
// 仅当 tools 非空时才写入 tools 字段,避免无工具时发送空数组。
|
||||
func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []OpenAIToolDef, stream bool) ([]byte, error) {
|
||||
payload := map[string]any{
|
||||
"model": modelName,
|
||||
@@ -209,6 +233,10 @@ func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []Op
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
// encodeMessages 将领域层消息转换为 OpenAI Chat Completions 协议所需的消息格式。
|
||||
//
|
||||
// 支持普通 system/user 消息、assistant 工具调用消息、tool 执行结果消息;
|
||||
// 当 assistant 消息带有 tool_calls 且 content 为空时,按 OpenAI 协议省略 content 字段。
|
||||
func encodeMessages(messages []ports.ChatMessage) []map[string]any {
|
||||
encoded := make([]map[string]any, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
@@ -243,6 +271,10 @@ func encodeMessages(messages []ports.ChatMessage) []map[string]any {
|
||||
return encoded
|
||||
}
|
||||
|
||||
// encodeTools 将工具定义转换为 OpenAI 函数调用(Function Calling)协议格式。
|
||||
//
|
||||
// 当前实现把工具参数统一建模为 query 字符串,适合将 MCP/Skill 工具包装为自由文本输入;
|
||||
// 若工具描述为空,会通过 fallbackDescription 生成默认描述。
|
||||
func encodeTools(tools []OpenAIToolDef) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(tools))
|
||||
for _, t := range tools {
|
||||
@@ -266,6 +298,10 @@ func encodeTools(tools []OpenAIToolDef) []map[string]any {
|
||||
return out
|
||||
}
|
||||
|
||||
// fallbackDescription 返回工具描述
|
||||
//
|
||||
// 当描述为空时,生成一个通用默认描述。
|
||||
// 默认描述会包含工具名,提示模型该工具接收自由文本 query 参数。
|
||||
func fallbackDescription(t OpenAIToolDef) string {
|
||||
if strings.TrimSpace(t.Description) != "" {
|
||||
return t.Description
|
||||
@@ -273,6 +309,9 @@ func fallbackDescription(t OpenAIToolDef) string {
|
||||
return "外部工具 " + t.Name + ",参数 query 为自由文本"
|
||||
}
|
||||
|
||||
// truncate 将过长的字符串截断到指定长度,用于控制错误信息中的响应体长度。
|
||||
//
|
||||
// 如果原始字符串长度不超过 max,则原样返回;否则截取前 max 个字符并追加省略号。
|
||||
func truncate(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
@@ -280,6 +319,9 @@ func truncate(s string, max int) string {
|
||||
return s[:max] + "..."
|
||||
}
|
||||
|
||||
// openaiCompletion 对应 OpenAI 非流式 Chat Completions 响应。
|
||||
//
|
||||
// 其中 choices[0].message 保存最终文本内容与模型请求的工具调用列表。
|
||||
type openaiCompletion struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
@@ -289,6 +331,9 @@ type openaiCompletion struct {
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
// openaiStreamChunk 对应 OpenAI 流式响应中的单个 SSE data chunk。
|
||||
//
|
||||
// delta 中可能包含 content 文本增量,或 tool_calls 工具的增量片段。
|
||||
type openaiStreamChunk struct {
|
||||
Choices []struct {
|
||||
Delta struct {
|
||||
@@ -299,6 +344,7 @@ type openaiStreamChunk struct {
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
// openaiToolCallV1 对应 OpenAI 非流式响应中的完整工具调用。
|
||||
type openaiToolCallV1 struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
@@ -308,6 +354,9 @@ type openaiToolCallV1 struct {
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
// openaiStreamToolCall 对应 OpenAI 流式响应中的工具调用增量片段。
|
||||
//
|
||||
// Index 用于区分同一响应中的多个工具调用,Arguments 是需要跨 chunk 拼接的 JSON 增量。
|
||||
type openaiStreamToolCall struct {
|
||||
Index int `json:"index"`
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"ai-agent-scaffold-go/internal/domain/agent/model"
|
||||
"ai-agent-scaffold-go/internal/domain/agent/ports"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -41,15 +42,26 @@ type SkillTool struct {
|
||||
ManifestPath string
|
||||
}
|
||||
|
||||
// NewToolFactory 创建 ToolFactory.
|
||||
//
|
||||
// router 用于将构建出的 MCP 工具注册并展开为 LLM 可调用的工具列表, 可为 nil.
|
||||
func NewToolFactory(router *MCPToolRouter) *ToolFactory {
|
||||
return &ToolFactory{router: router}
|
||||
}
|
||||
|
||||
// NewSkillFactory 创建 SkillFactory.
|
||||
//
|
||||
// SkillFactory 是无状态的, 所有技能信息均从磁盘上的 SKILL.md 扫描获得.
|
||||
func NewSkillFactory() *SkillFactory {
|
||||
return &SkillFactory{}
|
||||
}
|
||||
|
||||
// BuildTools 根据 model.ToolMCPConfig 构建工具列表, 实现 ports.MCPToolFactory 接口.
|
||||
//
|
||||
// 支持 local、sse、stdio 三种传输方式;
|
||||
// SSE 工具会交由 router 动态展开为服务端真实工具列表.
|
||||
func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig) ([]ports.Tool, error) {
|
||||
// 校验配置必须且只能指定一种传输方式, 并返回其类型
|
||||
kind, err := validateMCPConfig(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -58,6 +70,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
|
||||
var (
|
||||
tools []ports.Tool
|
||||
)
|
||||
// 按传输类型构建工具, 兼容 type 为空时直接依据非空字段判断的历史配置
|
||||
switch {
|
||||
case kind == "local":
|
||||
tools, err = buildLocalMCPTools(config.Local)
|
||||
@@ -75,6 +88,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 有 router 时注册并展开工具, 例如把 SSE 配置展开为服务端真实工具列表
|
||||
if f.router != nil {
|
||||
expanded := make([]ports.Tool, 0, len(tools))
|
||||
for _, t := range tools {
|
||||
@@ -84,6 +98,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
|
||||
}
|
||||
expanded = append(expanded, ts...)
|
||||
}
|
||||
// 展开结果为空说明注册失败, 回退到原始工具列表以保证启动不中断
|
||||
if len(expanded) > 0 {
|
||||
return expanded, nil
|
||||
}
|
||||
@@ -91,11 +106,16 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// Name 返回工具名, 实现 ports.Tool 接口.
|
||||
func (t MCPTool) Name() string {
|
||||
return t.ToolName
|
||||
}
|
||||
|
||||
// BuildTools 根据 model.ToolSkillsConfig 扫描目录下的 SKILL.md 并构建技能工具列表, 实现 ports.SkillFactory 接口.
|
||||
//
|
||||
// 每个 SKILL.md 会被解析为一个独立的 SkillTool, 工具名统一添加 skill_ 前缀以避免与 MCP 工具重名.
|
||||
func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConfig) ([]ports.Tool, error) {
|
||||
// type 为空时默认为 directory, 目前仅支持 directory 与 resource 两种取值
|
||||
skillType := strings.TrimSpace(config.Type)
|
||||
if skillType == "" {
|
||||
skillType = "directory"
|
||||
@@ -109,10 +129,12 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
|
||||
return nil, fmt.Errorf("skill path is required")
|
||||
}
|
||||
|
||||
// 把配置中的相对路径解析为实际存在的技能根路径
|
||||
root, err := resolveSkillRoot(skillType, rawPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 递归查找技能根路径下的所有 SKILL.md
|
||||
manifests, err := findSkillManifests(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -121,9 +143,10 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
|
||||
return nil, fmt.Errorf("skill path %q has no SKILL.md files", root)
|
||||
}
|
||||
|
||||
// 每个 SKILL.md 解析为一个独立工具
|
||||
tools := make([]ports.Tool, 0, len(manifests))
|
||||
for _, manifest := range manifests {
|
||||
tool, err := loadSkillTool(root, manifest)
|
||||
tool, err := loadSkillTool(manifest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -132,11 +155,16 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// Name 返回工具名, 实现 ports.Tool 接口.
|
||||
func (t SkillTool) Name() string {
|
||||
return t.ToolName
|
||||
}
|
||||
|
||||
// resolveSkillRoot 将配置中的技能路径解析为实际存在的根路径.
|
||||
//
|
||||
// 支持绝对路径, 也支持从当前工作目录逐级向上查找多个相对路径候选.
|
||||
func resolveSkillRoot(skillType, rawPath string) (string, error) {
|
||||
// 绝对路径直接校验
|
||||
if filepath.IsAbs(rawPath) {
|
||||
return existingPath(rawPath, rawPath)
|
||||
}
|
||||
@@ -146,6 +174,7 @@ func resolveSkillRoot(skillType, rawPath string) (string, error) {
|
||||
return "", fmt.Errorf("resolve skill path %q: %w", rawPath, err)
|
||||
}
|
||||
|
||||
// 依次尝试候选路径, 返回第一个真实存在的路径
|
||||
candidates := skillPathCandidates(cwd, skillType, rawPath)
|
||||
for _, candidate := range candidates {
|
||||
if path, err := existingPath(candidate, rawPath); err == nil {
|
||||
@@ -155,8 +184,12 @@ func resolveSkillRoot(skillType, rawPath string) (string, error) {
|
||||
return "", fmt.Errorf("skill path %q cannot be resolved", rawPath)
|
||||
}
|
||||
|
||||
// skillPathCandidates 从当前工作目录逐级向上生成技能路径候选, 并做去重.
|
||||
//
|
||||
// 同时兼容直接使用原始相对路径、configs 前缀以及仓库目录名三种常见布局.
|
||||
func skillPathCandidates(cwd, skillType, rawPath string) []string {
|
||||
var candidates []string
|
||||
// 去重后加入候选列表, 避免重复路径被多次校验
|
||||
add := func(path string) {
|
||||
clean := filepath.Clean(path)
|
||||
for _, candidate := range candidates {
|
||||
@@ -167,6 +200,7 @@ func skillPathCandidates(cwd, skillType, rawPath string) []string {
|
||||
candidates = append(candidates, clean)
|
||||
}
|
||||
|
||||
// 从当前目录逐级向上尝试, 直到文件系统根目录
|
||||
for dir := cwd; ; dir = filepath.Dir(dir) {
|
||||
add(filepath.Join(dir, rawPath))
|
||||
add(filepath.Join(dir, "configs", rawPath))
|
||||
@@ -184,6 +218,7 @@ func skillPathCandidates(cwd, skillType, rawPath string) []string {
|
||||
return candidates
|
||||
}
|
||||
|
||||
// existingPath 校验候选路径是否存在, 且必须是目录或 SKILL.md 文件.
|
||||
func existingPath(candidate, original string) (string, error) {
|
||||
info, err := os.Stat(candidate)
|
||||
if err != nil {
|
||||
@@ -195,15 +230,18 @@ func existingPath(candidate, original string) (string, error) {
|
||||
return candidate, nil
|
||||
}
|
||||
|
||||
// findSkillManifests 在技能根路径下递归查找所有 SKILL.md, 并按路径排序保证结果稳定.
|
||||
func findSkillManifests(root string) ([]string, error) {
|
||||
info, err := os.Stat(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 路径本身就是单个 SKILL.md 文件时直接返回
|
||||
if !info.IsDir() {
|
||||
return []string{root}, nil
|
||||
}
|
||||
|
||||
// 递归遍历目录, 只收集文件名严格等于 SKILL.md 的文件
|
||||
var manifests []string
|
||||
err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
@@ -224,7 +262,10 @@ func findSkillManifests(root string) ([]string, error) {
|
||||
return manifests, nil
|
||||
}
|
||||
|
||||
func loadSkillTool(root, manifest string) (SkillTool, error) {
|
||||
// loadSkillTool 读取并解析单个 SKILL.md, 构建 SkillTool.
|
||||
//
|
||||
// 元数据缺少 name 时使用技能目录名, 最终工具名会经过清洗并添加 skill_ 前缀.
|
||||
func loadSkillTool(manifest string) (SkillTool, error) {
|
||||
data, err := os.ReadFile(manifest)
|
||||
if err != nil {
|
||||
return SkillTool{}, fmt.Errorf("read skill manifest %q: %w", manifest, err)
|
||||
@@ -235,6 +276,7 @@ func loadSkillTool(root, manifest string) (SkillTool, error) {
|
||||
}
|
||||
|
||||
skillDir := filepath.Dir(manifest)
|
||||
// name 缺失时回退为目录名
|
||||
name := strings.TrimSpace(meta["name"])
|
||||
if name == "" {
|
||||
name = filepath.Base(skillDir)
|
||||
@@ -250,7 +292,9 @@ func loadSkillTool(root, manifest string) (SkillTool, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// sanitizeToolName 清洗工具名, 仅保留字母、数字、下划线和连字符, 并限制长度不超过 64 个字符.
|
||||
func sanitizeToolName(name string) string {
|
||||
// 非法字符统一替换为下划线
|
||||
var b strings.Builder
|
||||
for _, r := range name {
|
||||
switch {
|
||||
@@ -270,8 +314,12 @@ func sanitizeToolName(name string) string {
|
||||
return out
|
||||
}
|
||||
|
||||
// parseSkillFrontMatter 解析 SKILL.md 头部的 YAML front matter, 返回元数据键值对.
|
||||
//
|
||||
// 文件不以 --- 开头时返回空元数据, 由调用方回退到默认命名.
|
||||
func parseSkillFrontMatter(content string) (map[string]string, error) {
|
||||
result := make(map[string]string)
|
||||
// 没有 front matter 时直接返回空结果
|
||||
if !strings.HasPrefix(content, "---") {
|
||||
return result, nil
|
||||
}
|
||||
@@ -289,7 +337,9 @@ func parseSkillFrontMatter(content string) (map[string]string, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// validateMCPConfig 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种, 并返回其类型.
|
||||
func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
|
||||
// 统计非空传输字段, 数量必须恰好为 1
|
||||
count := 0
|
||||
kind := ""
|
||||
if config.Local != nil {
|
||||
@@ -315,6 +365,7 @@ func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// buildLocalMCPTools 根据本地工具配置构建 MCPTool, 目前仅支持内置的 echoLocalTool.
|
||||
func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error) {
|
||||
name := strings.TrimSpace(config.Name)
|
||||
if name == "" {
|
||||
@@ -329,6 +380,9 @@ func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error)
|
||||
}
|
||||
}
|
||||
|
||||
// buildSSEMCPTools 根据 SSE 配置构建 MCPTool, 并规范化 base-uri 与 sse-endpoint.
|
||||
//
|
||||
// 返回的工具只保存连接信息, 真正的工具列表由 MCPToolRouter 在注册时从服务端自动发现.
|
||||
func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
|
||||
name := strings.TrimSpace(config.Name)
|
||||
if name == "" {
|
||||
@@ -339,10 +393,12 @@ func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
|
||||
return nil, fmt.Errorf("sse mcp tool %q base-uri is required", name)
|
||||
}
|
||||
|
||||
// 把 base-uri 与 sse-endpoint 合并规范化为可复用的连接目标
|
||||
normalizedBaseURI, endpoint, err := normalizeSSETarget(baseURI, strings.TrimSpace(config.SSEEndpoint))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sse mcp tool %q: %w", name, err)
|
||||
}
|
||||
// 超时未配置时使用默认值
|
||||
timeout := normalizeTimeout(config.RequestTimeout)
|
||||
|
||||
return []ports.Tool{MCPTool{
|
||||
@@ -354,6 +410,7 @@ func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// buildStdioMCPTools 根据 stdio 配置构建 MCPTool, 并拷贝命令参数与环境变量.
|
||||
func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, error) {
|
||||
name := strings.TrimSpace(config.Name)
|
||||
if name == "" {
|
||||
@@ -365,6 +422,7 @@ func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, erro
|
||||
}
|
||||
timeout := normalizeTimeout(config.RequestTimeout)
|
||||
|
||||
// Args 与 Env 都做拷贝, 避免运行时对象与配置共享底层数据
|
||||
return []ports.Tool{MCPTool{
|
||||
ToolName: name,
|
||||
TransportType: "stdio",
|
||||
@@ -375,15 +433,20 @@ func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, erro
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// normalizeSSETarget 规范化 SSE 目标地址, 将 base-uri 与 endpoint 合并为 (scheme://host, path) 两部分.
|
||||
//
|
||||
// endpoint 为空时根据 base-uri 的 path 推断, 默认回退到 /sse.
|
||||
func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
|
||||
parsed, err := url.Parse(baseURI)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("invalid base-uri: %w", err)
|
||||
}
|
||||
// base-uri 必须是带 scheme 和 host 的绝对地址
|
||||
if parsed.Scheme == "" || parsed.Host == "" {
|
||||
return "", "", fmt.Errorf("base-uri must include scheme and host")
|
||||
}
|
||||
|
||||
// 只保留 scheme://host, path 与 query 单独处理
|
||||
host := strings.TrimRight(parsed.Scheme+"://"+parsed.Host, "/")
|
||||
basePath := parsed.RawPath
|
||||
if basePath == "" {
|
||||
@@ -391,6 +454,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
|
||||
}
|
||||
baseQuery := parsed.RawQuery
|
||||
|
||||
// endpoint 为空时从 base-uri 的 path 推断
|
||||
if endpoint == "" {
|
||||
if basePath == "" || basePath == "/" {
|
||||
return host, "/sse", nil
|
||||
@@ -402,6 +466,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
|
||||
return host, normalizeEndpoint(merged), nil
|
||||
}
|
||||
|
||||
// 合并 path 与 query, query 部分直接拼接
|
||||
endpointPath, endpointQuery := splitPathQuery(endpoint)
|
||||
mergedPath := joinPaths(basePath, endpointPath)
|
||||
mergedQuery := mergeQueries(baseQuery, endpointQuery)
|
||||
@@ -411,6 +476,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
|
||||
return host, normalizeEndpoint(mergedPath), nil
|
||||
}
|
||||
|
||||
// splitPathQuery 将 URL 路径与查询串按第一个 '?' 拆开.
|
||||
func splitPathQuery(raw string) (string, string) {
|
||||
if idx := strings.Index(raw, "?"); idx >= 0 {
|
||||
return raw[:idx], raw[idx+1:]
|
||||
@@ -418,6 +484,7 @@ func splitPathQuery(raw string) (string, string) {
|
||||
return raw, ""
|
||||
}
|
||||
|
||||
// joinPaths 拼接 URL 路径, 处理空路径、绝对路径和重复斜杠.
|
||||
func joinPaths(base, extra string) string {
|
||||
if extra == "" {
|
||||
if base == "" {
|
||||
@@ -437,6 +504,7 @@ func joinPaths(base, extra string) string {
|
||||
return base + "/" + extra
|
||||
}
|
||||
|
||||
// mergeQueries 合并两段查询串.
|
||||
func mergeQueries(base, extra string) string {
|
||||
switch {
|
||||
case base == "" && extra == "":
|
||||
@@ -450,6 +518,7 @@ func mergeQueries(base, extra string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeEndpoint 确保端点以 '/' 开头, 空值回退为 /sse.
|
||||
func normalizeEndpoint(endpoint string) string {
|
||||
trimmed := strings.TrimSpace(endpoint)
|
||||
if trimmed == "" {
|
||||
@@ -461,6 +530,7 @@ func normalizeEndpoint(endpoint string) string {
|
||||
return "/" + trimmed
|
||||
}
|
||||
|
||||
// normalizeTimeout 规范化超时毫秒数, 非正数时返回默认值 300000(5 分钟).
|
||||
func normalizeTimeout(timeout int) int {
|
||||
if timeout > 0 {
|
||||
return timeout
|
||||
@@ -468,6 +538,7 @@ func normalizeTimeout(timeout int) int {
|
||||
return 300000
|
||||
}
|
||||
|
||||
// cloneEnv 拷贝环境变量 map, 避免运行时对象与配置共享底层数据.
|
||||
func cloneEnv(values map[string]string) map[string]string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
@@ -479,6 +550,9 @@ func cloneEnv(values map[string]string) map[string]string {
|
||||
return cloned
|
||||
}
|
||||
|
||||
// maskSecretPath 对 URL 查询参数中疑似密钥的值进行脱敏, 用于日志输出.
|
||||
//
|
||||
// 参数名包含 KEY、TOKEN 或 SECRET 时, 其值会被替换为 ${VAR} 形式的占位符.
|
||||
func maskSecretPath(raw string) string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return raw
|
||||
@@ -496,6 +570,7 @@ func maskSecretPath(raw string) string {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
// 没有敏感参数时原样返回
|
||||
if !changed {
|
||||
return raw
|
||||
}
|
||||
@@ -503,6 +578,7 @@ func maskSecretPath(raw string) string {
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
// mcpTimeoutString 将超时毫秒数规范化为字符串.
|
||||
func mcpTimeoutString(timeout int) string {
|
||||
return strconv.Itoa(normalizeTimeout(timeout))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user