@ai-zen/agents-sdk 1.0.0-alpha.24 → 1.0.0-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/README.md +5 -5
  3. package/README.zh.md +5 -5
  4. package/dist/agent-plugins/AutoMigratePlugin.js +1 -3
  5. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
  6. package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -1
  7. package/dist/agent-plugins/ContextGuardPlugin.js +11 -1
  8. package/dist/config/ConfigManager.js +1 -1
  9. package/dist/config/constants.js +5 -8
  10. package/dist/config/migrate.d.ts +31 -0
  11. package/dist/config/migrate.js +52 -4
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +3 -3
  14. package/dist/runtime/HandoffService.d.ts +5 -4
  15. package/dist/runtime/HandoffService.js +17 -14
  16. package/dist/runtime/createAgent.js +1 -3
  17. package/dist/scope/Scope.d.ts +3 -1
  18. package/dist/scope/Scope.js +3 -1
  19. package/dist/scope/plugins/builtin/BatchEditTool.js +15 -8
  20. package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
  21. package/dist/scope/plugins/builtin/DownloadFileTool.js +54 -30
  22. package/dist/scope/plugins/builtin/EditTool.js +13 -18
  23. package/dist/scope/plugins/builtin/ExecTool.js +127 -18
  24. package/dist/scope/plugins/builtin/FindTextTool.js +6 -1
  25. package/dist/scope/plugins/builtin/GenerateImageTool.js +80 -14
  26. package/dist/scope/plugins/builtin/GlobTool.js +6 -1
  27. package/dist/scope/plugins/builtin/SpawnTool.js +28 -45
  28. package/dist/scope/plugins/builtin/ViewImageTool.js +6 -2
  29. package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
  30. package/dist/scope/plugins/builtin/searchBase.js +17 -0
  31. package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
  32. package/dist/scope/plugins/builtin/test-helpers.js +3 -3
  33. package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
  34. package/dist/scope/plugins/builtin/textEdit.js +37 -0
  35. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
  36. package/dist/scope/plugins/mcp/McpConnectionManager.js +88 -9
  37. package/dist/scope/plugins/mcp/McpScopePlugin.js +7 -6
  38. package/dist/scope/plugins/mcp/mcpTools.d.ts +2 -2
  39. package/dist/scope/plugins/mcp/mcpTools.js +42 -10
  40. package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
  41. package/dist/scope/plugins/skills/discover.js +25 -5
  42. package/dist/scope/plugins/skills/skillTools.js +13 -1
  43. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
  44. package/dist/scope/plugins/usertools/discover.js +8 -2
  45. package/dist/shared/EntityRepository.d.ts +10 -1
  46. package/dist/shared/EntityRepository.js +18 -6
  47. package/dist/shared/content-blocks.d.ts +5 -12
  48. package/dist/shared/content-blocks.js +1 -1
  49. package/dist/types/index.d.ts +48 -0
  50. package/package.json +5 -6
package/CHANGELOG.md CHANGED
@@ -1,3 +1,212 @@
1
+ ## [1.0.0-alpha.26] - 2026-11-03
2
+
3
+ > A full review of this package (ledger committed as `docs/code-review-ledger.md`)
4
+ > turned up 24 defects that bite in ordinary use. 14 candidate findings were
5
+ > dropped on purpose: the model is not an attacker, the tool layer is not a
6
+ > security boundary, and an error string returned by a tool is a legitimate
7
+ > result. What stayed is everything a normal session trips over: a tool call that
8
+ > freezes the process, a silent file corruption, a silent data loss, a "success"
9
+ > that never happened, permission rules that were declared but not enforced.
10
+ >
11
+ > Two of the fixes live elsewhere: `@ai-zen/agents-core@4.5.4` (`send()` return
12
+ > timing, `lastUsage` as a derived value) and a following `ai-zen/cli` release
13
+ > (guard hand-off and dependency bump).
14
+
15
+ ### 🛡️ Fixed — a tool call that froze the whole process
16
+
17
+ - **`edit` with an empty `oldText`** spun forever in `countOccurrences()`
18
+ (`indexOf("", pos)` returns `pos`, `pos += 0` never advances). It blocked the
19
+ event loop, so `abort()` could not help — one agent froze every session in the
20
+ process. Empty `oldText` is now rejected before anything else; `batch_edit`
21
+ treats it as a failed replacement instead of stalling the batch.
22
+
23
+ ### 🛡️ Fixed — `edit` / `batch_edit` silently rewrote the replacement text
24
+
25
+ - `content.replace(oldText, newText)` treats `$&`, `` $` ``, `$'` and `$$` inside
26
+ `newText` as replacement patterns. Writing `cost: $& ($$)` produced `cost: PRICE
27
+ ($)` — a corrupted file reported as `success`. Both tools now use the callback
28
+ form of the replacer, where the return value is always taken literally. The
29
+ shared logic moved to `builtin/textEdit.ts`.
30
+ - `batch_edit` keeps its cascading semantics (each replacement applies to the
31
+ result of the previous one) but now says so in its description; the "no match"
32
+ reason explains that matching happens against the post-previous-replacements
33
+ content, and `replacedCount` is the actual number of replacements (it used to
34
+ report `1` for `isReplaceAll`).
35
+
36
+ ### 🛡️ Fixed — `download_file` could delete an existing file, and had no limits
37
+
38
+ - On abort it ran `rm(savePath, { force: true })`. With the old
39
+ buffer-then-write design the abort could only happen before the single
40
+ `writeFile`, so the only file that branch could ever delete was one that
41
+ already existed at that path. The branch is gone; an interrupted download now
42
+ reports what happened and never touches the file.
43
+ - The body is written as a stream instead of `arrayBuffer()` (a 200 MB file used
44
+ to cost ~650 MB of heap).
45
+ - **New required `timeout` parameter** (milliseconds, same convention as `exec`):
46
+ `fetch` only bounds the response headers, the body could stream forever.
47
+
48
+ ### 🛡️ Fixed — `exec` lied about exit codes, leaked orphans, and truncated silently
49
+
50
+ - Successful commands reported `exitCode: null`, which reads as "did not finish
51
+ normally". Now `0`.
52
+ - `child_process.exec()` **ignores `detached`** (verified on Node 26), so the
53
+ timeout only killed the shell and grandchildren survived as orphans. `exec` now
54
+ uses `spawn(shell, detached)` with its own stream collection and kills the whole
55
+ process group (`kill(-pid)`); on Windows it falls back to killing the child.
56
+ When the child exited but a descendant still holds the stdio pipes, the tool
57
+ drains what arrived and returns instead of hanging until the timeout.
58
+ - `maxBuffer` is set explicitly (16 MB) and truncation is reported as
59
+ `truncated` + a truthful note, instead of returning
60
+ `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` as the "exit code" while claiming the full
61
+ content had been written to disk.
62
+
63
+ ### 🛡️ Fixed — `spawn` reported failures as success
64
+
65
+ - Its `exit` listener was removed by `removeAllListeners()`, so a command that
66
+ failed immediately (`exit 3`, missing binary, syntax error) came back as
67
+ `success: true`. The field is now `started`, with an explicit note that this
68
+ tool does not track the exit status — use `exec` for that.
69
+
70
+ ### 🛡️ Fixed — `glob` / `find_text` answered "no files" for a bad base directory
71
+
72
+ - A non-existent or non-directory `path` silently returned `[]` (`ls` raises
73
+ `ENOENT` in the same situation). Both tools now validate the base directory and
74
+ say so; the implicit `**/node_modules/**` default for `exclude` is documented in
75
+ the parameter description.
76
+
77
+ ### 🛡️ Fixed — `generate_image` returned `success: true` with no images
78
+
79
+ - Only `url` entries were collected, so an endpoint that returns `b64_json`
80
+ produced `{ success: true, images: [] }`. Base64 payloads are now decoded,
81
+ written to `<tmp>/ai-zen/generated-images/` (extension sniffed from the magic
82
+ bytes) and returned as a local path; a response with neither field is a
83
+ failure.
84
+
85
+ ### 🛡️ Fixed — `permissions` were declared but not enforced
86
+
87
+ - `load_skill` / `call_skill_sub_agent` only used `filteredSkills` to build the
88
+ `enum`; the callback read from the full skill directory, so a denied skill
89
+ could be loaded by naming it (and `../..` escaped the directory entirely). Both
90
+ now validate `skill_id` against the filtered set.
91
+ - `call_mcp_tool` / `read_mcp_resource` only checked "is this server connected".
92
+ The connection manager is shared across the Scope, so any server connected by
93
+ one agent was callable by every agent. Both tools receive the filtered server
94
+ list and validate against it.
95
+
96
+ ### 🛡️ Fixed — runtime edges around handoff and MCP
97
+
98
+ - Handoff file names dropped the `conversationId` suffix (and the parameter with
99
+ it): session names are hand-edited and would only make the file name noisier.
100
+ - `migrate()` reads `definition.messages ?? []` — a hand-written definition
101
+ without `messages` used to throw a raw `TypeError` after the handoff turn had
102
+ already run.
103
+ - MCP: a `disconnect()` during connect no longer resurrects the connection (and
104
+ closes the resources it built); a transport that closes at runtime marks the
105
+ server `disconnected` instead of leaving a stale manifest behind; connecting
106
+ has a 60 s timeout (`connectTimeoutMs`) instead of hanging `load_mcp` forever
107
+ on a misconfigured endpoint.
108
+ - `ContextGuardPlugin` gained `isSuspended?: () => boolean`. Handoff/migration
109
+ turns are started precisely when the context is fullest; the guard now steps
110
+ aside for them itself, and `HandoffService` no longer clears usage data to make
111
+ that happen ("whoever imposes the limit lifts it").
112
+
113
+ ### 🧪 Engineering
114
+
115
+ - Tests are now type-checked: new `tsconfig.test.json`, `pretest` runs it. 234
116
+ type errors had accumulated (including real drift: `defaultModel` removed,
117
+ `maxTokens` → `handoffTokens`, `McpServerConfig.name` removed,
118
+ `AgentDefinition.messages` must be `Message` instances). All cleared.
119
+ - `npm test` no longer pulls in `test/e2e-*.test.ts`: those need an API key, real
120
+ network, or a local MCP server, and `prepublishOnly` hangs off that command.
121
+ Scripts now mirror the CLI: `test` / `test:e2e` / `test:all`.
122
+ - Default suite: **628 passed** (53 files). E2E: **36 passed, 6 skipped**.
123
+
124
+ ### 📖 Docs
125
+
126
+ - Aligned 8 drifts: `ContextGuardPlugin({ guardTokens, isSuspended })` (no
127
+ `maxTokens`, no `ratio`, no `suspendedRatio` — the threshold is absolute),
128
+ `AutoMigratePlugin({ handoffTokens })`, `AutoMigrateModeResolver`'s
129
+ `info.handoffTokens`, `Model.tokenThresholds` instead of `maxContextTokens`,
130
+ `Endpoint.capabilities`, the `content-blocks` module in the directory tree and
131
+ the module layering, plus a new "file → content block" section describing the
132
+ transport decision table, upload cache, degradation rules and the `deps.upload`
133
+ injection point.
134
+
135
+ ## [1.0.0-alpha.25] - 2026-11-02
136
+
137
+ > Endpoint capability bits are now backfilled on migration. Since alpha.12 the
138
+ > `capabilities.filesApi` bit decides whether local media is uploaded (Files API) or
139
+ > inlined as base64 — but endpoints are never factory-managed, and migration did not
140
+ > touch them either, so any config written before alpha.12 kept `deepseek` without the
141
+ > bit. For those users the promised "deepseek goes through the Files API" never took
142
+ > effect: images, `view_image` and MCP media silently degraded to base64 inline, and
143
+ > the request body grew with every turn of history.
144
+ >
145
+ > Alongside it, entity ids are now confined to their repository directory: a hostile id
146
+ > could previously make `AgentRepository` read / write / delete JSON files outside of
147
+ > `agents/`.
148
+
149
+ ### 🛡️ Fixed — `Endpoint.capabilities` is backfilled when missing
150
+
151
+ - **`normalizeEndpointCapabilities()`** (in `config/migrate.ts`, wired into
152
+ `migrateConfig()`) fills in `capabilities` **only when the whole field is absent**,
153
+ taking the values from the factory endpoint with the same id. Nothing else is touched:
154
+ - an endpoint that already has `capabilities` — even `{}` or `{"filesApi": false}` — is
155
+ left byte-for-byte alone; an explicit `false` is a decision, not a gap;
156
+ - endpoints whose id is not in the factory list (user-built) are left alone, because
157
+ guessing would send uploads to a `/files` endpoint that may not exist.
158
+ - The migration lands on disk through the usual `ensureDefaultConfig()` path, so it runs
159
+ exactly once per config: a second start finds nothing to change.
160
+ - Verified end to end against a legacy-shaped config: `deepseek` gains
161
+ `{ filesApi: true }` in memory **and** on disk, a user-written `filesApi: false` on
162
+ `openai` survives, a self-built endpoint stays untouched, and the second start does not
163
+ rewrite the file.
164
+
165
+ ### 🔒 Fixed — entity ids can no longer escape their repository directory
166
+
167
+ - **`EntityRepository.path()`** now validates the resolved target:
168
+ `resolve()` + a `root + sep` prefix check, instead of `join(dir, `${id}.json`)`.
169
+ - A bare `startsWith(root)` would not have been enough: `../agents-evil/x` normalizes to
170
+ `<root>-evil/x.json`, which still *starts with* `<root>`.
171
+ - `join` cannot normalize absolute paths, so `/etc/passwd` used to land in
172
+ `<dir>/etc/passwd.json`; `resolve` catches it.
173
+ - The check lives in `path()` rather than in `write()` / `delete()`: `read`, `write` and
174
+ `delete` all go through it, and `list()` only ever passes single-segment names coming
175
+ from `readdir`, so it cannot break listing — one gate, read/write/delete consistent.
176
+ - Affected callers that pass a user-supplied id straight through: `AgentRepository`
177
+ (agent / sub-agent definitions) and the CLI's conversation repository (`/save`, `/load`).
178
+ A hostile id now fails loudly (`Invalid entity id: …`) instead of writing outside the
179
+ directory.
180
+ - Known and accepted: `a/../b` normalizes back inside `<root>/b.json` and is therefore
181
+ still allowed — the only remaining effect is overwriting another definition, and
182
+ `config.json` is out of reach.
183
+
184
+ ### ✅ Tests
185
+
186
+ - `AgentRepository.test.ts` +5: `../escaped` rejected *and* no file written outside,
187
+ `../agents-evil/x` rejected, `read` / `delete` share the same gate, absolute path
188
+ rejected, normal id unaffected. Uses a two-level temp directory so an escape would land
189
+ inside the test's own tmpdir instead of `/tmp`.
190
+ - `migrate.test.ts` +7: backfill on a legacy config, explicit `false` respected,
191
+ existing-but-empty `capabilities` untouched, user-built endpoint untouched, factory
192
+ endpoint without the bit untouched, idempotency, and "no side effects on the caller's
193
+ object".
194
+ - Full suite: **57 files / 629 tests passing** (6 skipped), `tsc --noEmit` clean.
195
+
196
+ ### 🔧 Toolchain — TypeScript 5.9.3 → 7.0.2
197
+
198
+ - **`packages/sdk/tsconfig.json`**: added `"types": ["node"]`. TypeScript 7 no longer
199
+ picks global types up from `node_modules/@types` automatically (at least under this
200
+ repo's pnpm symlink layout), so `"node:fs"` / `process` / `Buffer` all turn into
201
+ `TS2591`. Naming the types explicitly is also what `@ai-zen/cli` already does.
202
+ - **`packages/core/tsconfig.json`**: `moduleResolution: "Node"` → `"Bundler"`. The
203
+ `node10` resolution mode was **removed** in TypeScript 7 (`TS5108`); `Bundler` is the
204
+ closest equivalent for a package compiled with `module: ESNext`.
205
+ - Verified after the upgrade: `tsc --noEmit` clean for both packages, both `build`
206
+ scripts succeed, core **150 passed / 17 skipped**, sdk **624 passed / 6 skipped**
207
+ at that point (629 after the entity-id hardening above), and `dist/index.js` still
208
+ loads at runtime (84 exports).
209
+
1
210
  # Changelog
2
211
 
3
212
  ## [1.0.0-alpha.24] - 2026-10-29
package/README.md CHANGED
@@ -24,7 +24,7 @@ crud ← capability-entity CRUD (Agent definitions; conversations/draft
24
24
  runtime ← model factory + Agent assembly + task handoff/migration (cancellable via `AbortSignal`; createModel / createAgent / SdkAgent / HandoffService / HandoffGuardPlugin)
25
25
  scope ← Scope orchestration container + ScopePlugin contract + PermissionEvaluator / disclosure + plugins/ (5 self-contained capability sources: discovery + tools + plugin)
26
26
  agent-plugins ← Agent plugins (autoMigrate, autoRefreshTools, contextGuard, unknownToolHint)
27
- shared ← logging, errors
27
+ shared ← content blocks (file → content block transport), entity repository, logging, errors
28
28
  ```
29
29
 
30
30
  Dependency direction: `agent-plugins → runtime → scope`; `runtime → scope / crud / shared / types`, `scope → types / shared`. Upper layers depend on lower layers.
@@ -69,8 +69,8 @@ await scope.init();
69
69
 
70
70
  const agent = await createAgent(scope, "my-agent");
71
71
  const handoffService = new HandoffService({ handoffDir: "/work/.ai-zen/handoffs", skillDirs });
72
- agent.use(new ContextGuardPlugin({ maxTokens, isSuspended: () => handoffService.busy }));
73
- agent.use(new AutoMigratePlugin({ service: handoffService, maxTokens }));
72
+ agent.use(new ContextGuardPlugin({ guardTokens, isSuspended: () => handoffService.busy }));
73
+ agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens }));
74
74
  agent.use(new AutoRefreshToolsPlugin());
75
75
  agent.use(new UnknownToolHintPlugin({ scope }));
76
76
  await agent.init();
@@ -131,9 +131,9 @@ Interrupt strategies live in the config: `AppConfig.abortedMessageStrategy` (`ke
131
131
 
132
132
  | Plugin | Description |
133
133
  |--------|-------------|
134
- | `AutoMigratePlugin` | Automatically triggers task migration when the context overflows; delegates the actual migration to the injected `HandoffService` (history handled per `strategy`: default `omit` keeps it auditable, optional `prune` drops it). `resolveMode` lets the caller pick the handoff executor or skip the round. Steps aside while `service.busy` to avoid the handoff→migrate→handoff recursion |
134
+ | `AutoMigratePlugin` | Automatically triggers task migration when `usage.prompt_tokens` exceeds `handoffTokens`; delegates the actual migration to the injected `HandoffService` (history handled per `strategy`: default `omit` keeps it auditable, optional `prune` drops it). `resolveMode` lets the caller pick the handoff executor or skip the round. Steps aside while `service.busy` to avoid the handoff→migrate→handoff recursion |
135
135
  | `AutoRefreshToolsPlugin` | Re-scans the file system before each `send()` to refresh the tool list |
136
- | `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `maxTokens × ratio` (default 1.5), preventing context runaway from reading oversized files |
136
+ | `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `guardTokens` (an absolute value: no multiplier, no looser tier), preventing context runaway from reading oversized files. `isSuspended()` lets the guard itself step aside for handoff/migration turns |
137
137
  | `UnknownToolHintPlugin` | Smarter unknown-tool hints — when the LLM calls a nonexistent tool, guides it to `call_mcp_tool` / points out permission issues based on MCP config (opt-in via `agent.use`) |
138
138
 
139
139
  ## Language
package/README.zh.md CHANGED
@@ -23,7 +23,7 @@ crud ← 能力实体 CRUD(Agent 定义等;会话/草稿已下放
23
23
  runtime ← 模型工厂 + Agent 组装 + 任务交接/迁移(可 `AbortSignal` 取消;createModel / createAgent / SdkAgent / HandoffService / HandoffGuardPlugin)
24
24
  scope ← Scope 编排容器 + ScopePlugin 契约 + PermissionEvaluator / disclosure + plugins/(5 个自包含能力来源:发现 + 工具 + 插件)
25
25
  agent-plugins ← Agent 插件(autoMigrate、autoRefreshTools、contextGuard、unknownToolHint)
26
- shared ← 日志、错误
26
+ shared ← 内容块(文件 → 内容块的传输决策)、实体仓储、日志、错误
27
27
  ```
28
28
 
29
29
  依赖方向:`agent-plugins → runtime → scope`;`runtime → scope / crud / shared / types`,`scope → types / shared`。上层依赖下层,反之不行。
@@ -68,8 +68,8 @@ await scope.init();
68
68
 
69
69
  const agent = await createAgent(scope, "my-agent");
70
70
  const handoffService = new HandoffService({ handoffDir: "/work/.ai-zen/handoffs", skillDirs });
71
- agent.use(new ContextGuardPlugin({ maxTokens, isSuspended: () => handoffService.busy }));
72
- agent.use(new AutoMigratePlugin({ service: handoffService, maxTokens }));
71
+ agent.use(new ContextGuardPlugin({ guardTokens, isSuspended: () => handoffService.busy }));
72
+ agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens }));
73
73
  agent.use(new AutoRefreshToolsPlugin());
74
74
  agent.use(new UnknownToolHintPlugin({ scope }));
75
75
  await agent.init();
@@ -88,7 +88,7 @@ await scope.dispose(); // 断开 MCP、释放插件资源
88
88
  | `scope` | ✅ 已实现 — Scope + ScopePlugin + 5 个标准插件(builtin / user-tools / skills / mcp / subagents)+ allInOne |
89
89
  | `runtime` | ✅ 已实现 — createAgent、MCP 连接管理、任务迁移 |
90
90
  | `agent-plugins` | ✅ 已实现 — AutoMigratePlugin / AutoRefreshToolsPlugin / ContextGuardPlugin / UnknownToolHintPlugin |
91
- | `shared` | ✅ 已实现 — SdkError + 可注入 Logger |
91
+ | `shared` | ✅ 已实现 — 内容块传输决策(`content-blocks`)+ 实体仓储 + SdkError + 可注入 Logger |
92
92
 
93
93
  ## 内置工具
94
94
 
@@ -132,7 +132,7 @@ await scope.dispose(); // 断开 MCP、释放插件资源
132
132
  |------|------|
133
133
  | `AutoMigratePlugin` | 上下文超限时自动触发任务迁移(历史按 `strategy` 处理:默认 `omit` 标记保留可审计,可选 `prune` 物理剔除),委托注入的 `HandoffService`;`resolveMode` 让调用方决定交接执行者或跳过本轮;`service.busy` 期间让行,避免「交接→迁移→交接」递归 |
134
134
  | `AutoRefreshToolsPlugin` | 每次 `send()` 前重新扫描文件系统,刷新工具列表 |
135
- | `ContextGuardPlugin` | 上下文安全护栏 — 每轮发请求前检测上一轮 `usage.prompt_tokens`,超过 `maxTokens × ratio`(默认 1.5,即 +50%)时抛 `ContextOverflowError` 中断对话,防止读入超大文件导致上下文失控 |
135
+ | `ContextGuardPlugin` | 上下文安全护栏 — 每轮发请求前检测上一轮 `usage.prompt_tokens`,超过 `guardTokens`(绝对值:没有倍数、没有放宽档)时抛 `ContextOverflowError` 中断对话,防止读入超大文件导致上下文失控。`isSuspended()` 让护栏自己在交接/迁移回合让行 |
136
136
  | `UnknownToolHintPlugin` | 未知工具智能提示 — LLM 调用不存在的工具时,根据 MCP 配置引导使用 `call_mcp_tool` / 提示权限问题(调用方显式 `agent.use` 注册) |
137
137
 
138
138
  ## 语言
@@ -35,9 +35,7 @@ export class AutoMigratePlugin {
35
35
  if (promptTokens <= handoffTokens)
36
36
  return;
37
37
  try {
38
- const mode = resolveMode
39
- ? await resolveMode({ promptTokens, handoffTokens })
40
- : undefined;
38
+ const mode = resolveMode ? await resolveMode({ promptTokens, handoffTokens }) : undefined;
41
39
  if (mode === null)
42
40
  return; // 用户选择跳过本次迁移
43
41
  await service.migrate({ agent, promptTokens, handoffTokens, mode: mode ?? undefined });
@@ -12,9 +12,7 @@ export class AutoRefreshToolsPlugin {
12
12
  await agent.scope.refresh({ silent: true });
13
13
  agent.tools = agent.scope.buildTools(agent.definition, {
14
14
  exclude: {
15
- subagents: agent.definition.function?.name
16
- ? [agent.definition.function.name]
17
- : undefined,
15
+ subagents: agent.definition.function?.name ? [agent.definition.function.name] : undefined,
18
16
  },
19
17
  });
20
18
  }
@@ -7,6 +7,14 @@ export interface ContextGuardOptions {
7
7
  * 想调松就把它调大,「安全边界写多少就是多少」比「隐式乘以某个系数」可预测得多。
8
8
  */
9
9
  guardTokens: number;
10
+ /**
11
+ * 临时让行:返回 `true` 时本轮不做超限判定(默认 `false`)。
12
+ *
13
+ * 用于交接/迁移回合 —— 那些回合本身就是「上下文已满」时才发起的,若不放宽必定被打回。
14
+ * 语义是「谁做限制谁放宽」:限制在护栏自己身上,放宽也必须由护栏自己表达,
15
+ * 而不是由调用方去改写用量数据。典型接线:`isSuspended: () => handoffService.busy`。
16
+ */
17
+ isSuspended?: () => boolean;
10
18
  }
11
19
  /**
12
20
  * 上下文安全护栏插件。
@@ -21,12 +29,18 @@ export interface ContextGuardOptions {
21
29
  *
22
30
  * ```ts
23
31
  * const { handoff, guard } = config.models[i].tokenThresholds;
24
- * agent.use(new ContextGuardPlugin({ guardTokens: guard }));
32
+ * agent.use(
33
+ * new ContextGuardPlugin({
34
+ * guardTokens: guard,
35
+ * isSuspended: () => handoffService.busy, // 交接回合让行
36
+ * }),
37
+ * );
25
38
  * agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
26
39
  * ```
27
40
  */
28
41
  export declare class ContextGuardPlugin implements AgentPlugin {
29
42
  private readonly guardTokens;
43
+ private readonly isSuspended?;
30
44
  constructor(options: ContextGuardOptions);
31
45
  onInnerLoopStart(ctx: SendContext): Promise<void>;
32
46
  }
@@ -12,16 +12,26 @@ import { ContextOverflowError } from "../shared/errors.js";
12
12
  *
13
13
  * ```ts
14
14
  * const { handoff, guard } = config.models[i].tokenThresholds;
15
- * agent.use(new ContextGuardPlugin({ guardTokens: guard }));
15
+ * agent.use(
16
+ * new ContextGuardPlugin({
17
+ * guardTokens: guard,
18
+ * isSuspended: () => handoffService.busy, // 交接回合让行
19
+ * }),
20
+ * );
16
21
  * agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
17
22
  * ```
18
23
  */
19
24
  export class ContextGuardPlugin {
20
25
  guardTokens;
26
+ isSuspended;
21
27
  constructor(options) {
22
28
  this.guardTokens = options.guardTokens;
29
+ this.isSuspended = options.isSuspended;
23
30
  }
24
31
  async onInnerLoopStart(ctx) {
32
+ // 交接/迁移回合让行(见 `isSuspended`)
33
+ if (this.isSuspended?.())
34
+ return;
25
35
  const promptTokens = ctx.agent.lastUsage?.prompt_tokens;
26
36
  // 首轮请求前尚无用量数据,跳过(只能在发出首轮请求、拿到 usage 后才有据可查)
27
37
  if (promptTokens == null)
@@ -409,7 +409,7 @@ export function syncManagedModels(config) {
409
409
  const imageModels = pick(config.imageModels, DEFAULT_APP_CONFIG.imageModels ?? []);
410
410
  const modelIds = new Set(models.map((m) => m.id));
411
411
  const imageIds = new Set(imageModels.map((m) => m.id));
412
- const resolve = (id, ids, fallback) => id && ids.has(id) ? id : fallback;
412
+ const resolve = (id, ids, fallback) => (id && ids.has(id) ? id : fallback);
413
413
  return {
414
414
  ...config,
415
415
  models,
@@ -59,7 +59,10 @@ export const DEFAULT_SUBAGENT_DEFINITION = {
59
59
  parameters: {
60
60
  type: "object",
61
61
  properties: {
62
- task: { type: "string", description: "Complete task description; must include all necessary background, goals, constraints and context. Any unclear information will cause the sub-agent to refuse execution." },
62
+ task: {
63
+ type: "string",
64
+ description: "Complete task description; must include all necessary background, goals, constraints and context. Any unclear information will cause the sub-agent to refuse execution.",
65
+ },
63
66
  },
64
67
  required: ["task"],
65
68
  additionalProperties: false,
@@ -281,10 +284,4 @@ export const DEFAULT_MCP_CONFIG = {
281
284
  * ~/.ai-zen/cli/ ← CLI 运行时
282
285
  * ~/.ai-zen/desktop/ ← Desktop 运行时(未来)
283
286
  */
284
- export const CONFIG_SUB_DIRS = [
285
- "agents",
286
- "sub-agents",
287
- "skills",
288
- "tools",
289
- "mcp-oauth",
290
- ];
287
+ export const CONFIG_SUB_DIRS = ["agents", "sub-agents", "skills", "tools", "mcp-oauth"];
@@ -15,6 +15,8 @@
15
15
  * `reasoningPreset` 而默默失去调档能力。这里删掉旧字段,并按**同 id 的出厂模型**
16
16
  * 补上正确的策略名(同一 id 即同一厂商型号,协议能力不会因用户改过参数而变)。
17
17
  *
18
+ * 另有一类「缺省值缺位」的迁移:`Endpoint.capabilities`(见 `normalizeEndpointCapabilities`)。
19
+ *
18
20
  * 迁移时机:`ConfigManager.read()` 读出即迁(内存里永远是当前形状);
19
21
  * 落盘由 `ensureDefaultConfig()` 负责 —— 它比较迁移结果与磁盘原文,不同才写回,
20
22
  * 因此迁移只发生一次,且不会在每次启动时无谓地改写文件。
@@ -73,3 +75,32 @@ export declare const ABORTED_MESSAGE_STRATEGIES: readonly ["keep", "drop"];
73
75
  export declare const ABORTED_TOOL_ROUND_STRATEGIES: readonly ["fill", "drop"];
74
76
  /** 缺失 / 非法 → 出厂默认;返回是否有改动(直接改写传入对象) */
75
77
  export declare function normalizeAbortStrategies(config: AppConfig): boolean;
78
+ /**
79
+ * 补齐端点**缺失**的能力位声明(`Endpoint.capabilities`)。
80
+ *
81
+ * ## 这个问题是怎么来的
82
+ *
83
+ * `capabilities.filesApi` 是 alpha.12 才引入的能力位 —— 同一版把 `view_image` 的判定
84
+ * 从「端点 id 是不是 `deepseek`」改成「看这一位」,并只给**出厂 deepseek** 打了 `true`。
85
+ * 但端点**不参与出厂托管**(`ConfigManager.syncManagedModels` 明写「保持用户配置」),
86
+ * 迁移此前也完全不碰 `endpoints` —— 于是 alpha.12 之前就已写下的配置,其 deepseek
87
+ * 端点永远缺 `capabilities`,`supportsFilesApi()` 恒为 `false`:
88
+ *
89
+ * · 出厂承诺的「deepseek 走 Files API」对这些用户从未生效;
90
+ * · 而且**全程静默** —— 「未声明能力位」和「缺 apiKey」两个分支都不发 warning,
91
+ * 图片 / `view_image` / MCP 媒体就悄悄退化成 base64 内联,请求体随历史膨胀。
92
+ *
93
+ * 这是「默认值缺位」,不是「用户选择」,所以由迁移补 —— 与模型清单不同,端点本身仍然
94
+ * 归用户所有,我们只往**空位**里放出厂默认。
95
+ *
96
+ * ## 边界:只补整体缺失,绝不覆盖
97
+ *
98
+ * - `capabilities` **整体缺失** → 按**同 id 的出厂端点**补上整块;
99
+ * - `capabilities` 已存在(哪怕是 `{}`、哪怕写着 `filesApi: false`)→ 一个字段都不动:
100
+ * 用户已经表过态,`false` 就是「我不走 Files API」;
101
+ * - 端点 id 不在出厂清单(用户自建)→ 不动:我们不知道它是否真有 `/files`,
102
+ * 猜错会把上传请求打到不存在的接口上。
103
+ *
104
+ * @returns 是否有改动(直接改写传入对象)
105
+ */
106
+ export declare function normalizeEndpointCapabilities(config: AppConfig): boolean;
@@ -15,6 +15,8 @@
15
15
  * `reasoningPreset` 而默默失去调档能力。这里删掉旧字段,并按**同 id 的出厂模型**
16
16
  * 补上正确的策略名(同一 id 即同一厂商型号,协议能力不会因用户改过参数而变)。
17
17
  *
18
+ * 另有一类「缺省值缺位」的迁移:`Endpoint.capabilities`(见 `normalizeEndpointCapabilities`)。
19
+ *
18
20
  * 迁移时机:`ConfigManager.read()` 读出即迁(内存里永远是当前形状);
19
21
  * 落盘由 `ensureDefaultConfig()` 负责 —— 它比较迁移结果与磁盘原文,不同才写回,
20
22
  * 因此迁移只发生一次,且不会在每次启动时无谓地改写文件。
@@ -60,9 +62,7 @@ export function migrateModelThresholds(model) {
60
62
  const legacyTokens = toPositiveInt(source[LEGACY_TOKEN_FIELD]);
61
63
  const legacyChars = toPositiveInt(source[LEGACY_CHARS_FIELD]);
62
64
  const legacySingle = toPositiveInt(source.tokenThreshold);
63
- const hasLegacy = LEGACY_TOKEN_FIELD in source ||
64
- LEGACY_CHARS_FIELD in source ||
65
- "tokenThreshold" in source;
65
+ const hasLegacy = LEGACY_TOKEN_FIELD in source || LEGACY_CHARS_FIELD in source || "tokenThreshold" in source;
66
66
  const complete = current.handoff !== undefined && current.guard !== undefined;
67
67
  if (!hasLegacy && complete)
68
68
  return { model, changed: false };
@@ -118,7 +118,12 @@ export function migrateConfig(config) {
118
118
  changed = true;
119
119
  return reasoning.model;
120
120
  });
121
- const next = { ...config, models };
121
+ const next = {
122
+ ...config,
123
+ models,
124
+ // 端点数组浅拷贝:能力位补齐会改元素,不把副作用浇到调用方手里的旧对象上
125
+ endpoints: (config.endpoints ?? []).map((endpoint) => ({ ...endpoint })),
126
+ };
122
127
  // 已废弃字段:不参与运行,也不允许再写回磁盘
123
128
  if ("defaultModel" in next) {
124
129
  delete next.defaultModel;
@@ -126,6 +131,8 @@ export function migrateConfig(config) {
126
131
  }
127
132
  if (normalizeAbortStrategies(next))
128
133
  changed = true;
134
+ if (normalizeEndpointCapabilities(next))
135
+ changed = true;
129
136
  if (!changed)
130
137
  return { config, changed };
131
138
  return { config: next, changed };
@@ -146,3 +153,44 @@ export function normalizeAbortStrategies(config) {
146
153
  }
147
154
  return changed;
148
155
  }
156
+ /**
157
+ * 补齐端点**缺失**的能力位声明(`Endpoint.capabilities`)。
158
+ *
159
+ * ## 这个问题是怎么来的
160
+ *
161
+ * `capabilities.filesApi` 是 alpha.12 才引入的能力位 —— 同一版把 `view_image` 的判定
162
+ * 从「端点 id 是不是 `deepseek`」改成「看这一位」,并只给**出厂 deepseek** 打了 `true`。
163
+ * 但端点**不参与出厂托管**(`ConfigManager.syncManagedModels` 明写「保持用户配置」),
164
+ * 迁移此前也完全不碰 `endpoints` —— 于是 alpha.12 之前就已写下的配置,其 deepseek
165
+ * 端点永远缺 `capabilities`,`supportsFilesApi()` 恒为 `false`:
166
+ *
167
+ * · 出厂承诺的「deepseek 走 Files API」对这些用户从未生效;
168
+ * · 而且**全程静默** —— 「未声明能力位」和「缺 apiKey」两个分支都不发 warning,
169
+ * 图片 / `view_image` / MCP 媒体就悄悄退化成 base64 内联,请求体随历史膨胀。
170
+ *
171
+ * 这是「默认值缺位」,不是「用户选择」,所以由迁移补 —— 与模型清单不同,端点本身仍然
172
+ * 归用户所有,我们只往**空位**里放出厂默认。
173
+ *
174
+ * ## 边界:只补整体缺失,绝不覆盖
175
+ *
176
+ * - `capabilities` **整体缺失** → 按**同 id 的出厂端点**补上整块;
177
+ * - `capabilities` 已存在(哪怕是 `{}`、哪怕写着 `filesApi: false`)→ 一个字段都不动:
178
+ * 用户已经表过态,`false` 就是「我不走 Files API」;
179
+ * - 端点 id 不在出厂清单(用户自建)→ 不动:我们不知道它是否真有 `/files`,
180
+ * 猜错会把上传请求打到不存在的接口上。
181
+ *
182
+ * @returns 是否有改动(直接改写传入对象)
183
+ */
184
+ export function normalizeEndpointCapabilities(config) {
185
+ let changed = false;
186
+ for (const endpoint of config.endpoints ?? []) {
187
+ if (endpoint.capabilities != null)
188
+ continue;
189
+ const factory = (DEFAULT_APP_CONFIG.endpoints ?? []).find((item) => item.id === endpoint.id);
190
+ if (!factory?.capabilities)
191
+ continue;
192
+ endpoint.capabilities = { ...factory.capabilities };
193
+ changed = true;
194
+ }
195
+ return changed;
196
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { PermissionPolicy, AgentPermissions, Endpoint, EndpointCapabilities, Model, TokenThresholds, ModelParams, ReasoningPatch, ReasoningPreset, ReasoningPresets, ImageModel, AgentDefinition, AppConfig, ToolEnv, McpIcon, McpAnnotations, McpToolDef, McpResourceDef, McpPromptDef, McpServerManifest, McpServerConfig, McpConnectionState, } from "./types/index.js";
1
+ export type { PermissionPolicy, AgentPermissions, Endpoint, EndpointCapabilities, Model, TokenThresholds, ModelParams, ReasoningPatch, ReasoningPreset, ReasoningPresets, ImageModel, AgentDefinition, AppConfig, ToolEnv, ToolEnvDeps, GenerateImageFn, McpIcon, McpAnnotations, McpToolDef, McpResourceDef, McpPromptDef, McpServerManifest, McpServerConfig, McpConnectionState, } from "./types/index.js";
2
2
  export { PermissionEvaluator } from "./scope/PermissionEvaluator.js";
3
3
  export type { CandidateSets } from "./scope/PermissionEvaluator.js";
4
4
  export { createDisclosureParam } from "./scope/disclosure.js";
@@ -10,7 +10,7 @@ export type { SkillInfo, Frontmatter } from "./scope/plugins/skills/discover.js"
10
10
  export { discoverMcpServers } from "./scope/plugins/mcp/discover.js";
11
11
  export { discoverUserTools } from "./scope/plugins/usertools/discover.js";
12
12
  export { Scope } from "./scope/Scope.js";
13
- export type { FilterOutput, ExcludeOptions, FilterOptions, } from "./scope/Scope.js";
13
+ export type { FilterOutput, ExcludeOptions, FilterOptions } from "./scope/Scope.js";
14
14
  export type { ScopePlugin, ScopeCandidates } from "./scope/ScopePlugin.js";
15
15
  export { BuiltinToolsScopePlugin } from "./scope/plugins/builtin/BuiltinToolsScopePlugin.js";
16
16
  export { UserToolsScopePlugin } from "./scope/plugins/usertools/UserToolsScopePlugin.js";
@@ -21,7 +21,7 @@ export { allInOne } from "./scope/plugins/allInOne.js";
21
21
  export type { AllInOneOptions } from "./scope/plugins/allInOne.js";
22
22
  export { ConfigManager, DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_SUBAGENT_ID, DEFAULT_SUBAGENT_DEFINITION, DEFAULT_APP_CONFIG, DEFAULT_MCP_CONFIG, CONFIG_SUB_DIRS, } from "./config/ConfigManager.js";
23
23
  export { FACTORY_SKILLS, HANDOFF_SKILL_ID, FALLBACK_HANDOFF_TEMPLATE, isCustomSkill, } from "./config/factory-skills.js";
24
- export { FACTORY_REASONING_PRESETS, REASONING_PRESETS_FILE, } from "./config/reasoning-presets.js";
24
+ export { FACTORY_REASONING_PRESETS, REASONING_PRESETS_FILE } from "./config/reasoning-presets.js";
25
25
  export { EntityRepository } from "./shared/EntityRepository.js";
26
26
  export { AgentRepository } from "./crud/AgentRepository.js";
27
27
  export { fileToContentSection, resolveModelAndEndpoint, supportsFilesApi, mimeOf, toDataUrl, base64ByteLength, contentHash, clearUploadCache, MIME_BY_EXT, DEFAULT_MAX_INLINE_BYTES, } from "./shared/content-blocks.js";
@@ -48,8 +48,8 @@ export { BUILTIN_TOOL_CLASSES } from "./scope/plugins/builtin/index.js";
48
48
  export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, } from "./scope/plugins/builtin/index.js";
49
49
  export { GenerateImageTool } from "./scope/plugins/builtin/GenerateImageTool.js";
50
50
  export { ViewImageTool } from "./scope/plugins/builtin/ViewImageTool.js";
51
- export { createLoadSkillTool, createCallSkillSubAgentTool } from "./scope/plugins/skills/skillTools.js";
52
- export { createLoadMcpTool, createCallMcpTool, createReadMcpResourceTool } from "./scope/plugins/mcp/mcpTools.js";
51
+ export { createLoadSkillTool, createCallSkillSubAgentTool, } from "./scope/plugins/skills/skillTools.js";
52
+ export { createLoadMcpTool, createCallMcpTool, createReadMcpResourceTool, } from "./scope/plugins/mcp/mcpTools.js";
53
53
  export { createSubAgentTool } from "./scope/plugins/subagents/subAgentTools.js";
54
54
  export { getLogger, setLogger } from "./shared/logger.js";
55
55
  export type { Logger, LogFunctions } from "./shared/logger.js";
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ export { ConfigManager, DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_SUBA
21
21
  export { FACTORY_SKILLS, HANDOFF_SKILL_ID, FALLBACK_HANDOFF_TEMPLATE, isCustomSkill, } from "./config/factory-skills.js";
22
22
  // 出厂资产 — 思考策略表(随版本释放到 <basePath>/reasoning-presets.json)
23
23
  // 表是跨客户端共享的「定义 + 出厂默认」,SDK 不拿它生成请求参数
24
- export { FACTORY_REASONING_PRESETS, REASONING_PRESETS_FILE, } from "./config/reasoning-presets.js";
24
+ export { FACTORY_REASONING_PRESETS, REASONING_PRESETS_FILE } from "./config/reasoning-presets.js";
25
25
  // CRUD — 实体仓储(仅 Agent 定义等能力实体)
26
26
  export { EntityRepository } from "./shared/EntityRepository.js";
27
27
  export { AgentRepository } from "./crud/AgentRepository.js";
@@ -45,8 +45,8 @@ export { BUILTIN_TOOL_CLASSES } from "./scope/plugins/builtin/index.js";
45
45
  export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, } from "./scope/plugins/builtin/index.js";
46
46
  export { GenerateImageTool } from "./scope/plugins/builtin/GenerateImageTool.js";
47
47
  export { ViewImageTool } from "./scope/plugins/builtin/ViewImageTool.js";
48
- export { createLoadSkillTool, createCallSkillSubAgentTool } from "./scope/plugins/skills/skillTools.js";
49
- export { createLoadMcpTool, createCallMcpTool, createReadMcpResourceTool } from "./scope/plugins/mcp/mcpTools.js";
48
+ export { createLoadSkillTool, createCallSkillSubAgentTool, } from "./scope/plugins/skills/skillTools.js";
49
+ export { createLoadMcpTool, createCallMcpTool, createReadMcpResourceTool, } from "./scope/plugins/mcp/mcpTools.js";
50
50
  export { createSubAgentTool } from "./scope/plugins/subagents/subAgentTools.js";
51
51
  // 共享
52
52
  export { getLogger, setLogger } from "./shared/logger.js";
@@ -96,8 +96,6 @@ export interface HandoffParams {
96
96
  promptTokens?: number;
97
97
  /** 上下文阈值(可选,仅透传给钩子) */
98
98
  handoffTokens?: number;
99
- /** 会话 id(可选,用于交接文件名,便于回溯) */
100
- conversationId?: string;
101
99
  /**
102
100
  * 取消信号(可选)。触发后交接**立即停止且不降级**,抛 {@link HandoffAbortedError}。
103
101
  *
@@ -154,9 +152,12 @@ export declare class HandoffService {
154
152
  /** 交接文档目录 */
155
153
  get handoffDir(): string;
156
154
  /**
157
- * 交接文件名:`<YYYYMMDD-HHmmss>-<会话id前8位>.md`(本地时间,便于人眼归档)。
155
+ * 交接文件名:`<YYYYMMDD-HHmmss>.md`(本地时间,便于人眼归档)。
156
+ *
157
+ * 只有到秒的时间戳。同一秒内两次交接会撞名 —— 不做去重兜底:同一时刻并发交接
158
+ * 本来就是调用方该避免的事,加随机后缀只会让文件名更难认。
158
159
  */
159
- static createHandoffFileName(date?: Date, conversationId?: string): string;
160
+ static createHandoffFileName(date?: Date): string;
160
161
  /**
161
162
  * 拼装「本轮交接」指令:`[Skill 正文] + [本次交接参数]`。
162
163
  *