@ai-zen/agents-sdk 1.0.0-alpha.25 → 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 (48) hide show
  1. package/CHANGELOG.md +134 -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.js +1 -3
  11. package/dist/index.d.ts +5 -5
  12. package/dist/index.js +3 -3
  13. package/dist/runtime/HandoffService.d.ts +5 -4
  14. package/dist/runtime/HandoffService.js +17 -14
  15. package/dist/runtime/createAgent.js +1 -3
  16. package/dist/scope/Scope.d.ts +3 -1
  17. package/dist/scope/Scope.js +3 -1
  18. package/dist/scope/plugins/builtin/BatchEditTool.js +15 -8
  19. package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
  20. package/dist/scope/plugins/builtin/DownloadFileTool.js +54 -30
  21. package/dist/scope/plugins/builtin/EditTool.js +13 -18
  22. package/dist/scope/plugins/builtin/ExecTool.js +127 -18
  23. package/dist/scope/plugins/builtin/FindTextTool.js +6 -1
  24. package/dist/scope/plugins/builtin/GenerateImageTool.js +80 -14
  25. package/dist/scope/plugins/builtin/GlobTool.js +6 -1
  26. package/dist/scope/plugins/builtin/SpawnTool.js +28 -45
  27. package/dist/scope/plugins/builtin/ViewImageTool.js +6 -2
  28. package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
  29. package/dist/scope/plugins/builtin/searchBase.js +17 -0
  30. package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
  31. package/dist/scope/plugins/builtin/test-helpers.js +3 -3
  32. package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
  33. package/dist/scope/plugins/builtin/textEdit.js +37 -0
  34. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
  35. package/dist/scope/plugins/mcp/McpConnectionManager.js +88 -9
  36. package/dist/scope/plugins/mcp/McpScopePlugin.js +7 -6
  37. package/dist/scope/plugins/mcp/mcpTools.d.ts +2 -2
  38. package/dist/scope/plugins/mcp/mcpTools.js +42 -10
  39. package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
  40. package/dist/scope/plugins/skills/discover.js +25 -5
  41. package/dist/scope/plugins/skills/skillTools.js +13 -1
  42. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
  43. package/dist/scope/plugins/usertools/discover.js +8 -2
  44. package/dist/shared/EntityRepository.js +1 -3
  45. package/dist/shared/content-blocks.d.ts +5 -12
  46. package/dist/shared/content-blocks.js +1 -1
  47. package/dist/types/index.d.ts +48 -0
  48. package/package.json +4 -5
package/CHANGELOG.md CHANGED
@@ -1,3 +1,137 @@
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
+
1
135
  ## [1.0.0-alpha.25] - 2026-11-02
2
136
 
3
137
  > Endpoint capability bits are now backfilled on migration. Since alpha.12 the
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"];
@@ -62,9 +62,7 @@ export function migrateModelThresholds(model) {
62
62
  const legacyTokens = toPositiveInt(source[LEGACY_TOKEN_FIELD]);
63
63
  const legacyChars = toPositiveInt(source[LEGACY_CHARS_FIELD]);
64
64
  const legacySingle = toPositiveInt(source.tokenThreshold);
65
- const hasLegacy = LEGACY_TOKEN_FIELD in source ||
66
- LEGACY_CHARS_FIELD in source ||
67
- "tokenThreshold" in source;
65
+ const hasLegacy = LEGACY_TOKEN_FIELD in source || LEGACY_CHARS_FIELD in source || "tokenThreshold" in source;
68
66
  const complete = current.handoff !== undefined && current.guard !== undefined;
69
67
  if (!hasLegacy && complete)
70
68
  return { model, changed: false };
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
  *
@@ -96,14 +96,16 @@ export class HandoffService {
96
96
  // 静态纯工具(供上层复用 / 单测)
97
97
  // ==================================================================
98
98
  /**
99
- * 交接文件名:`<YYYYMMDD-HHmmss>-<会话id前8位>.md`(本地时间,便于人眼归档)。
99
+ * 交接文件名:`<YYYYMMDD-HHmmss>.md`(本地时间,便于人眼归档)。
100
+ *
101
+ * 只有到秒的时间戳。同一秒内两次交接会撞名 —— 不做去重兜底:同一时刻并发交接
102
+ * 本来就是调用方该避免的事,加随机后缀只会让文件名更难认。
100
103
  */
101
- static createHandoffFileName(date = new Date(), conversationId) {
104
+ static createHandoffFileName(date = new Date()) {
102
105
  const p = (n) => String(n).padStart(2, "0");
103
106
  const stamp = `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}` +
104
107
  `-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`;
105
- const suffix = conversationId ? `-${conversationId.slice(0, 8)}` : "";
106
- return `${stamp}${suffix}.md`;
108
+ return `${stamp}.md`;
107
109
  }
108
110
  /**
109
111
  * 拼装「本轮交接」指令:`[Skill 正文] + [本次交接参数]`。
@@ -189,12 +191,15 @@ export class HandoffService {
189
191
  const { agent } = ctx;
190
192
  const strategy = params.strategy ?? this.defaultStrategy;
191
193
  const breakpointMessages = HandoffService.createPostMessages(ctx.handoffPath);
194
+ // 交接回合可能已经把 messages 换成新会话,definition 也可能是手写的(没有 messages):
195
+ // 这里按空模板处理,好让报错落在"模型该补的配置"上,而不是原生 TypeError
196
+ const templateMessages = agent.definition.messages ?? [];
192
197
  if (strategy === "prune") {
193
198
  // 浅拷贝模板消息,避免污染 definition.messages 引用的对象
194
- agent.messages = [...agent.definition.messages, ...breakpointMessages];
199
+ agent.messages = [...templateMessages, ...breakpointMessages];
195
200
  }
196
201
  else {
197
- const preserveCount = Math.min(agent.definition.messages.length, agent.messages.length);
202
+ const preserveCount = Math.min(templateMessages.length, agent.messages.length);
198
203
  agent.messages = [
199
204
  ...agent.messages.map((m, i) => ({
200
205
  ...m,
@@ -273,9 +278,9 @@ export class HandoffService {
273
278
  }
274
279
  }
275
280
  async runHandoff(params, migrating) {
276
- const { agent, promptTokens, handoffTokens, conversationId, signal } = params;
281
+ const { agent, promptTokens, handoffTokens, signal } = params;
277
282
  const requestedMode = params.mode ?? this.defaultMode;
278
- const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date(), conversationId));
283
+ const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()));
279
284
  const model = this.model ?? agent.model;
280
285
  const messageCountBefore = agent.messages.length;
281
286
  // 迁移前上下文(不含文档,语义固定)
@@ -357,13 +362,11 @@ export class HandoffService {
357
362
  // 取消时只删本次新建的文件,不碰本已存在的同名文件
358
363
  const existedBefore = await this.fileExists(handoffPath);
359
364
  /*
360
- * 清空 lastUsage 再开跑:
361
- * - 护栏(ContextGuardPlugin)在每轮请求前用 lastUsage 判定严重超限,
362
- * 而交接恰好发生在上下文最满的时刻;
363
- * - AutoMigratePlugin 也会读它。busy 已能让两者让行,这里再清一次是纵深防御。
364
- * 交接回合结束后 lastUsage 由本轮真实响应用量回填,无需恢复旧值。
365
+ * 交接回合的护栏让行由 `ContextGuardPlugin.isSuspended` 负责(接线为
366
+ * `() => handoffService.busy`),这里不再去改写用量数据:
367
+ * - `lastUsage` 是从 `messages` 派生的只读值,本就不可写;
368
+ * - 「谁做限制谁放宽」—— 限制在护栏自己身上,放宽也必须写在护栏的选项里。
365
369
  */
366
- agent.lastUsage = undefined;
367
370
  guard.arm(handoffPath, cwd);
368
371
  try {
369
372
  await agent.send(HandoffService.createHandoffInstruction({
@@ -22,9 +22,7 @@ export async function createAgent(scope, agentId, options = {}) {
22
22
  const { client, model, modelConfig } = createModel(scope, modelId, definition.modelParams);
23
23
  const tools = scope.buildTools(definition, {
24
24
  exclude: {
25
- subagents: definition.function?.name
26
- ? [definition.function.name]
27
- : undefined,
25
+ subagents: definition.function?.name ? [definition.function.name] : undefined,
28
26
  },
29
27
  });
30
28
  const agent = new SdkAgent({
@@ -1,5 +1,5 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
- import type { AppConfig, AgentDefinition, ToolEnv } from "../types/index.js";
2
+ import type { AppConfig, AgentDefinition, ToolEnv, ToolEnvDeps } from "../types/index.js";
3
3
  import type { ScopePlugin } from "./ScopePlugin.js";
4
4
  /**
5
5
  * 能力过滤系统的公共类型。
@@ -64,6 +64,8 @@ export declare class Scope {
64
64
  config: AppConfig;
65
65
  agentsDir: string;
66
66
  cwd?: string;
67
+ /** 出网/外部依赖的注入点(缺省全部走真实 OpenAI SDK),会透传到 ToolEnv.deps */
68
+ deps?: ToolEnvDeps;
67
69
  });
68
70
  /** 已注册插件(只读视图) */
69
71
  get plugins(): readonly ScopePlugin[];
@@ -36,7 +36,9 @@ export class Scope {
36
36
  constructor(options) {
37
37
  this.config = options.config;
38
38
  this.cwd = options.cwd ?? process.cwd();
39
- this.env = { cwd: this.cwd, config: this.config };
39
+ this.env = options.deps
40
+ ? { cwd: this.cwd, config: this.config, deps: options.deps }
41
+ : { cwd: this.cwd, config: this.config };
40
42
  this.agentsDir = options.agentsDir;
41
43
  }
42
44
  // ==================================================================
@@ -1,11 +1,13 @@
1
1
  import * as fsp from "fs/promises";
2
2
  import { SdkCallbackTool } from "./SdkCallbackTool.js";
3
+ import { replaceText } from "./textEdit.js";
3
4
  export class BatchEditTool extends SdkCallbackTool {
4
5
  function = {
5
6
  name: "batch_edit",
6
7
  description: [
7
8
  "Edit text in a file in batches. Prefer this tool when making edits to a file.",
8
9
  "Submit all changes to the same file in a single call (the replacements array) instead of calling edit in parallel multiple times — parallel edits to the same file overwrite each other.",
10
+ "Replacements are applied in order, each on the result of the previous one: a later oldText is matched against the content already produced by the earlier replacements.",
9
11
  ].join("\n"),
10
12
  parameters: {
11
13
  type: "object",
@@ -56,21 +58,26 @@ export class BatchEditTool extends SdkCallbackTool {
56
58
  // 成功项不回显原文与新文,仅计入成功数,避免大段文本回显撑大输出
57
59
  const failed = [];
58
60
  for (const replacement of input.replacements) {
59
- if (!newContent.includes(replacement.oldText)) {
61
+ // 空串会匹配每一个位置,不是有意义的编辑,单独拒绝
62
+ if (replacement.oldText === "") {
60
63
  failed.push({
61
64
  oldText: replacement.oldText,
62
65
  newText: replacement.newText,
63
- reason: "No exact match found for the text to replace",
66
+ reason: "oldText must not be empty",
64
67
  });
65
68
  continue;
66
69
  }
67
- if (replacement.isReplaceAll) {
68
- newContent = newContent.replaceAll(replacement.oldText, replacement.newText);
69
- }
70
- else {
71
- newContent = newContent.replace(replacement.oldText, replacement.newText);
70
+ const { content: nextContent, replacedCount: count } = replaceText(newContent, replacement.oldText, replacement.newText, replacement.isReplaceAll ?? false);
71
+ if (count === 0) {
72
+ failed.push({
73
+ oldText: replacement.oldText,
74
+ newText: replacement.newText,
75
+ reason: "No exact match found for this oldText (matched against the content after the previous replacements in this batch)",
76
+ });
77
+ continue;
72
78
  }
73
- replacedCount++;
79
+ newContent = nextContent;
80
+ replacedCount += count;
74
81
  }
75
82
  await fsp.writeFile(filePath, newContent);
76
83
  if (failed.length === 0) {
@@ -7,5 +7,6 @@ export declare class DownloadFileTool extends SdkCallbackTool {
7
7
  call(input: {
8
8
  url: string;
9
9
  outputPath?: string;
10
+ timeout: number;
10
11
  }, ctx?: ToolCallContext): Promise<string>;
11
12
  }