@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.0

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 (38) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/dist/agent-plugins/AutoMigratePlugin.d.ts +34 -5
  5. package/dist/agent-plugins/AutoMigratePlugin.js +56 -7
  6. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +8 -5
  7. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +5 -6
  8. package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -3
  9. package/dist/agent-plugins/ContextGuardPlugin.js +16 -2
  10. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +18 -16
  11. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +16 -14
  12. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +12 -3
  13. package/dist/agent-plugins/UnknownToolHintPlugin.js +16 -4
  14. package/dist/index.d.ts +5 -2
  15. package/dist/index.js +3 -0
  16. package/dist/runtime/HandoffGuardPlugin.d.ts +7 -5
  17. package/dist/runtime/HandoffGuardPlugin.js +8 -6
  18. package/dist/runtime/HandoffService.d.ts +51 -12
  19. package/dist/runtime/HandoffService.js +112 -19
  20. package/dist/runtime/SdkAgent.d.ts +2 -3
  21. package/dist/runtime/SdkAgent.js +1 -2
  22. package/dist/scope/Scope.d.ts +35 -8
  23. package/dist/scope/Scope.js +50 -11
  24. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +7 -0
  25. package/dist/scope/plugins/mcp/McpConnectionManager.js +7 -0
  26. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +23 -0
  27. package/dist/scope/plugins/mcp/McpScopePlugin.js +68 -1
  28. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +28 -0
  29. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +35 -0
  30. package/dist/scope/plugins/peers/peerSessionTools.d.ts +122 -0
  31. package/dist/scope/plugins/peers/peerSessionTools.js +266 -0
  32. package/dist/scope/plugins/skills/skillTools.d.ts +1 -1
  33. package/dist/scope/plugins/skills/skillTools.js +6 -2
  34. package/dist/scope/plugins/subagents/subAgentTools.js +3 -0
  35. package/dist/shared/errors.d.ts +10 -3
  36. package/dist/shared/errors.js +10 -3
  37. package/dist/types/index.d.ts +6 -4
  38. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import type { AgentPlugin, ToolCallContext } from "@ai-zen/agents-core";
1
+ import type { AgentPlugin, ToolHookContext } from "@ai-zen/agents-core";
2
2
  /**
3
3
  * 交接回合的工具守卫 —— 保证「原 agent 停下手头一切工作」不只是提示词约定。
4
4
  *
@@ -8,13 +8,15 @@ import type { AgentPlugin, ToolCallContext } from "@ai-zen/agents-core";
8
8
  * - `edit` / `batch_edit` / `rm` / `rename` / `mkdir` / `copy`:一律拒绝;
9
9
  * - 读取类工具与其他工具:放行。
10
10
  *
11
- * 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolCall` 语义会把该字符串作为
12
- * 工具结果回给模型并继续下一轮,因此模型能读到引导(「只允许写交接文档」)并转回正题。
13
- * 反例:抛错会让该工具结果标记为 Error 且 `isPreventDefault`,整轮交接直接中断。
11
+ * 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolStart` 语义会把该字符串作为那条
12
+ * tool 消息的正文回给模型并继续下一圈,因此模型能读到引导(「只允许写交接文档」)并转回正题。
13
+ * 反例:抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),整轮交接直接停摆。
14
14
  *
15
15
  * 边界(必须如实记录,不要误以为是安全边界):
16
16
  * - **挡不住 `exec`**:`echo > file`、`cat > file <<EOF` 永远能绕过。本插件降低的是
17
17
  * 「顺手改代码」的误操作概率,不是沙箱。
18
+ * - **料不到的参数不算放行**:参数解析失败时 `parsedArgs` 为 `undefined`,`write` 会被
19
+ * 当成「没给路径」而拒绝(宁可让模型重试一次,也不放一个看不清的写操作)。
18
20
  * - 一次性:`arm()` 后生效,`disarm()` 后完全让行。`Agent.use()` 没有移除 API,
19
21
  * 故用「同一实例 + 开关」而非反复注册,避免插件数组无限增长。
20
22
  */
@@ -31,5 +33,5 @@ export declare class HandoffGuardPlugin implements AgentPlugin {
31
33
  disarm(): void;
32
34
  /** 是否处于交接回合(供上层/测试观察) */
33
35
  get armed(): boolean;
34
- onToolCall(ctx: ToolCallContext): string | undefined;
36
+ onToolStart({ toolCall }: ToolHookContext): string | undefined;
35
37
  }
@@ -8,13 +8,15 @@ import { resolve as resolvePath } from "node:path";
8
8
  * - `edit` / `batch_edit` / `rm` / `rename` / `mkdir` / `copy`:一律拒绝;
9
9
  * - 读取类工具与其他工具:放行。
10
10
  *
11
- * 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolCall` 语义会把该字符串作为
12
- * 工具结果回给模型并继续下一轮,因此模型能读到引导(「只允许写交接文档」)并转回正题。
13
- * 反例:抛错会让该工具结果标记为 Error 且 `isPreventDefault`,整轮交接直接中断。
11
+ * 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolStart` 语义会把该字符串作为那条
12
+ * tool 消息的正文回给模型并继续下一圈,因此模型能读到引导(「只允许写交接文档」)并转回正题。
13
+ * 反例:抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),整轮交接直接停摆。
14
14
  *
15
15
  * 边界(必须如实记录,不要误以为是安全边界):
16
16
  * - **挡不住 `exec`**:`echo > file`、`cat > file <<EOF` 永远能绕过。本插件降低的是
17
17
  * 「顺手改代码」的误操作概率,不是沙箱。
18
+ * - **料不到的参数不算放行**:参数解析失败时 `parsedArgs` 为 `undefined`,`write` 会被
19
+ * 当成「没给路径」而拒绝(宁可让模型重试一次,也不放一个看不清的写操作)。
18
20
  * - 一次性:`arm()` 后生效,`disarm()` 后完全让行。`Agent.use()` 没有移除 API,
19
21
  * 故用「同一实例 + 开关」而非反复注册,避免插件数组无限增长。
20
22
  */
@@ -45,13 +47,13 @@ export class HandoffGuardPlugin {
45
47
  get armed() {
46
48
  return this.handoffPath !== undefined;
47
49
  }
48
- onToolCall(ctx) {
50
+ onToolStart({ toolCall }) {
49
51
  const handoffPath = this.handoffPath;
50
52
  if (handoffPath == null)
51
53
  return;
52
- const name = ctx.tool_call?.function?.name ?? "";
54
+ const name = toolCall.tool_call?.function?.name ?? "";
53
55
  if (name === "write") {
54
- const raw = ctx.parsedArgs?.path;
56
+ const raw = toolCall.parsedArgs?.path;
55
57
  if (typeof raw === "string" && resolvePath(this.cwd, raw) === handoffPath) {
56
58
  return;
57
59
  }
@@ -102,7 +102,7 @@ export interface HandoffParams {
102
102
  * 两种执行者都要认它:
103
103
  * - `summary`:直接作为 `chat.completions.create` 的 RequestOptions 传下去,
104
104
  * 请求会真的被中断(否则该请求根本无从取消);
105
- * - `self`:`agent.abort()` 不抛错,所以每个 `send()` 之后要主动检查 `aborted`。
105
+ * - `self`:agent 被 `abort()` 了(`paused`),所以每一轮之后要主动检查取不取消。
106
106
  */
107
107
  signal?: AbortSignal;
108
108
  }
@@ -121,9 +121,10 @@ export interface MigrateParams extends HandoffParams {
121
121
  * 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
122
122
  * 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
123
123
  *
124
- * 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身也是一次 `send()`,
125
- * 若不在 busy 期间让 `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、
126
- * 迁移再触发交接」无限递归,或在最满的时刻被护栏直接击杀。
124
+ * 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身就是「往同一个 agent
125
+ * 里再投一轮」(`push` 一条指令),它跑完后 agent 会再变闲一次 —— 若不在 busy 期间让
126
+ * `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、迁移再触发交接」
127
+ * 无限递归,或在最满的时刻被护栏直接拒掉。
127
128
  *
128
129
  * 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
129
130
  * `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
@@ -187,6 +188,9 @@ export declare class HandoffService {
187
188
  *
188
189
  * 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
189
190
  * 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
191
+ *
192
+ * `source` 必须带(`CORE.md` §3「所有 `role: user` 的消息都必须有 source」):这条不是
193
+ * 用户说的话,是宿主注入的,所以是 `system` + label。
190
194
  */
191
195
  static createPostMessages(handoffPath: string): AgentNS.Message[];
192
196
  /** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
@@ -195,8 +199,9 @@ export declare class HandoffService {
195
199
  * 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
196
200
  *
197
201
  * 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
198
- * 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的回合是
199
- * `agent.send()`,调用方通常要同时 `agent.abort()`(TUI 就是这么做的);`summary`
202
+ * 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的那一轮是往常驻 agent 里
203
+ * `push()` 的一条指令,调用方通常要同时 `agent.abort()`(TUI 就是这么做的 ——
204
+ * 那一按会让 agent 停在 `paused`,本服务随之把这一轮判成「没跑完」);`summary`
200
205
  * 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
201
206
  */
202
207
  abort(): void;
@@ -255,25 +260,59 @@ export declare class HandoffService {
255
260
  * 截回原长度之后,转录、历史、用量全都自动复位,不需要第二处补偿。
256
261
  */
257
262
  private restoreBeforeHandoff;
258
- /** 自交接是否可用:需要 `write` 工具 + `send` 能力 */
263
+ /**
264
+ * 自交接是否可用:需要 `write` 工具,且 agent 是**常驻**的。
265
+ *
266
+ * 为什么要看 `lifetime`:自交接靠「往同一个会话里投一轮指令」实现,而一次性 agent
267
+ * 开跑即关收(第二次 `push` 抛 `closed`),且跑完就死透(`CORE.md` §1)—— 它根本没
268
+ * 有「再问一轮」这种能力。
269
+ */
259
270
  private supportsSelfHandoff;
260
271
  /**
261
272
  * 自交接回合:让原 agent 停工、核实、写文档,并校验文件确实落盘。
262
273
  *
263
274
  * 失败判定(任一成立即视为失败,交由上层单向降级 summary):
264
275
  * - 文件不存在 / 小于阈值;
265
- * - 模型/工具链抛错(例如没有权限、被护栏中断)。
276
+ * - 模型/工具链抛错(例如没有权限、被护栏拒绝);
277
+ * - 这一轮压根没跑完(agent 被 `abort()` 暂停、或已经被关门/硬杀)。
266
278
  *
267
279
  * **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
268
- * 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:
269
- * `agent.abort()` 不抛错(core 把消息标记为 Aborted 后正常返回),否则「用户
270
- * 按了 Ctrl+C」会被下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级
271
- * 一轮 —— 用户以为取消了,实际多烧了两轮全量输入。
280
+ * 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:`agent.abort()` 不抛错
281
+ * (core 把在途请求掉、消息标记成 Aborted 然后正常返回),否则「用户按了 Ctrl+C」会被
282
+ * 下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级一轮 —— 用户以为取消了,
283
+ * 实际多烧了两轮全量输入。
272
284
  *
273
285
  * 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
274
286
  * 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
275
287
  */
276
288
  private runSelfHandoff;
289
+ /**
290
+ * 往**常驻** agent 里投一条指令,等这一轮真的收完。
291
+ *
292
+ * ## 为什么是「push + 订阅 state」
293
+ *
294
+ * core 重写后没有 `send()` 了(`CORE.md` §1:「常驻会话只 `push`,不看返回值」):
295
+ * 「等」这种动作看不见不由我引起的变化,唯一可靠的替代是**订阅**。于是这里先订阅
296
+ * `state`、再 `push` —— 顺序不能反:push 之后状态已经变了,晚一步就错过「这一轮开始了」
297
+ * 那一拍,随后第一次报闲会被误当成「我这一轮跑完了」。
298
+ *
299
+ * ## `start()`:老 `send()` 隐含的那件事
300
+ *
301
+ * 老的 `send()` 是对「这个 agent」发起的,没起来也能顺手跑一段。新 core 的循环只听
302
+ * `start()`,所以这里先把它叫起来:`start()` 幂等(已起来就返回同一句 promise),
303
+ * **不能 await** —— 它到死才 resolve。宿主正常会话里这一句是空动作。
304
+ *
305
+ * ## 返回「这一轮怎么结束的」而不是「成没成」
306
+ *
307
+ * 三种结束方式对调用方意义不同(`idle` 才能去校验产物),所以分开报:
308
+ * - `idle`:跑完了;
309
+ * - `paused`:被 `abort()` 暂停/掉;
310
+ * - `dead`:关门/硬杀,循环已经结束。
311
+ *
312
+ * 第四种情况不在这里表达:`push` 在关门之后会直接抛 `AgentError("closed")` —— 那是
313
+ * 「调用方违约」(往一个已经没有的会话里塞东西),就该往上抛,不该被归成一种“结束方式”。
314
+ */
315
+ private pushInstructionRound;
277
316
  /** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
278
317
  private generateSummary;
279
318
  /** 落盘(仅 `summary` 模式需要;`self` 模式由 agent 的 write 工具完成) */
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { dirname, join, resolve as resolvePath } from "node:path";
3
- import { Message } from "@ai-zen/agents-core";
3
+ import { AgentError, Message } from "@ai-zen/agents-core";
4
4
  import { getLogger } from "../shared/logger.js";
5
5
  import { readSkill } from "../scope/plugins/skills/discover.js";
6
6
  import { FALLBACK_HANDOFF_TEMPLATE, HANDOFF_SKILL_ID } from "../config/factory-skills.js";
@@ -55,9 +55,10 @@ function mergeSignals(own, external) {
55
55
  * 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
56
56
  * 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
57
57
  *
58
- * 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身也是一次 `send()`,
59
- * 若不在 busy 期间让 `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、
60
- * 迁移再触发交接」无限递归,或在最满的时刻被护栏直接击杀。
58
+ * 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身就是「往同一个 agent
59
+ * 里再投一轮」(`push` 一条指令),它跑完后 agent 会再变闲一次 —— 若不在 busy 期间让
60
+ * `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、迁移再触发交接」
61
+ * 无限递归,或在最满的时刻被护栏直接拒掉。
61
62
  *
62
63
  * 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
63
64
  * `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
@@ -169,6 +170,9 @@ export class HandoffService {
169
170
  *
170
171
  * 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
171
172
  * 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
173
+ *
174
+ * `source` 必须带(`CORE.md` §3「所有 `role: user` 的消息都必须有 source」):这条不是
175
+ * 用户说的话,是宿主注入的,所以是 `system` + label。
172
176
  */
173
177
  static createPostMessages(handoffPath) {
174
178
  const content = [
@@ -177,7 +181,7 @@ export class HandoffService {
177
181
  "",
178
182
  "Read that file first with the read tool, and once you understand the context and the unfinished work, continue helping the user with the task.",
179
183
  ].join("\n");
180
- return [Message.User(content)];
184
+ return [Message.User(content, { kind: "system", label: "handoff" })];
181
185
  }
182
186
  /** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
183
187
  static serializeMessages(messages) {
@@ -196,8 +200,9 @@ export class HandoffService {
196
200
  * 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
197
201
  *
198
202
  * 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
199
- * 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的回合是
200
- * `agent.send()`,调用方通常要同时 `agent.abort()`(TUI 就是这么做的);`summary`
203
+ * 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的那一轮是往常驻 agent 里
204
+ * `push()` 的一条指令,调用方通常要同时 `agent.abort()`(TUI 就是这么做的 ——
205
+ * 那一按会让 agent 停在 `paused`,本服务随之把这一轮判成「没跑完」);`summary`
201
206
  * 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
202
207
  */
203
208
  abort() {
@@ -346,7 +351,7 @@ export class HandoffService {
346
351
  let handoffDoc;
347
352
  let historyText = "";
348
353
  if (mode === "self" && !this.supportsSelfHandoff(agent)) {
349
- this.logger.warn("[handoff] agent has no write tool or send capability, falling back to standalone summary mode");
354
+ this.logger.warn("[handoff] agent has no write tool or is not a resident session, falling back to standalone summary mode");
350
355
  mode = "summary";
351
356
  }
352
357
  if (mode === "self") {
@@ -401,9 +406,15 @@ export class HandoffService {
401
406
  agent.messages.splice(messageCountBefore);
402
407
  await this.discardPartialFile(handoffPath, existedBefore);
403
408
  }
404
- /** 自交接是否可用:需要 `write` 工具 + `send` 能力 */
409
+ /**
410
+ * 自交接是否可用:需要 `write` 工具,且 agent 是**常驻**的。
411
+ *
412
+ * 为什么要看 `lifetime`:自交接靠「往同一个会话里投一轮指令」实现,而一次性 agent
413
+ * 开跑即关收(第二次 `push` 抛 `closed`),且跑完就死透(`CORE.md` §1)—— 它根本没
414
+ * 有「再问一轮」这种能力。
415
+ */
405
416
  supportsSelfHandoff(agent) {
406
- if (typeof agent.send !== "function")
417
+ if (agent.lifetime === "one-shot")
407
418
  return false;
408
419
  return Boolean(agent.tools?.some((tool) => tool.function?.name === "write"));
409
420
  }
@@ -412,13 +423,14 @@ export class HandoffService {
412
423
  *
413
424
  * 失败判定(任一成立即视为失败,交由上层单向降级 summary):
414
425
  * - 文件不存在 / 小于阈值;
415
- * - 模型/工具链抛错(例如没有权限、被护栏中断)。
426
+ * - 模型/工具链抛错(例如没有权限、被护栏拒绝);
427
+ * - 这一轮压根没跑完(agent 被 `abort()` 暂停、或已经被关门/硬杀)。
416
428
  *
417
429
  * **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
418
- * 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:
419
- * `agent.abort()` 不抛错(core 把消息标记为 Aborted 后正常返回),否则「用户
420
- * 按了 Ctrl+C」会被下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级
421
- * 一轮 —— 用户以为取消了,实际多烧了两轮全量输入。
430
+ * 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:`agent.abort()` 不抛错
431
+ * (core 把在途请求掉、消息标记成 Aborted 然后正常返回),否则「用户按了 Ctrl+C」会被
432
+ * 下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级一轮 —— 用户以为取消了,
433
+ * 实际多烧了两轮全量输入。
422
434
  *
423
435
  * 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
424
436
  * 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
@@ -435,24 +447,34 @@ export class HandoffService {
435
447
  */
436
448
  guard.arm(handoffPath, cwd);
437
449
  try {
438
- await agent.send(HandoffService.createHandoffInstruction({
450
+ const first = await this.pushInstructionRound(agent, HandoffService.createHandoffInstruction({
439
451
  skillContent,
440
452
  handoffPath,
441
453
  toolsAvailable: true,
442
- }));
454
+ }), signal);
443
455
  // `agent.abort()` 不抛错,必须主动检查(见方法注释)
444
456
  this.throwIfAborted(signal);
457
+ // 这一轮没跑完(暂停 / 关门 / 硬杀):产物没意义,也别再往里投 ——
458
+ // 暂停中不取件,再投只会把一条陈旧指令留在队列里,等 resume 之后突然自己跑起来
459
+ if (first !== "idle")
460
+ return false;
445
461
  if (await this.isHandoffFileReady(handoffPath))
446
462
  return true;
447
463
  this.logger.warn(`[handoff] handoff document missing or too small, retrying once: ${handoffPath}`);
448
- await agent.send([
464
+ const second = await this.pushInstructionRound(agent, [
449
465
  `The handoff document does not exist or is too small to deliver: ${handoffPath}`,
450
466
  "Use the write tool right now to write the **complete** handoff document to that path (use the path exactly as given) and do nothing else.",
451
- ].join("\n"));
467
+ ].join("\n"), signal);
452
468
  this.throwIfAborted(signal);
469
+ if (second !== "idle")
470
+ return false;
453
471
  return await this.isHandoffFileReady(handoffPath);
454
472
  }
455
473
  catch (err) {
474
+ // agent 已经关门:不是「文档没写出来」,是「这个会话已经不在了」。降级 summary 会
475
+ // 为一个死掉的会话白烧一轮全量输入,所以直接把 `closed` 往上交(调用方该知道这件事)
476
+ if (err instanceof AgentError && err.code === "closed")
477
+ throw err;
456
478
  if (isAbortError(err, signal))
457
479
  throw new HandoffAbortedError();
458
480
  this.logger.error(`[handoff] self handoff round failed: ${err?.message ?? err}`);
@@ -462,6 +484,77 @@ export class HandoffService {
462
484
  guard.disarm();
463
485
  }
464
486
  }
487
+ /**
488
+ * 往**常驻** agent 里投一条指令,等这一轮真的收完。
489
+ *
490
+ * ## 为什么是「push + 订阅 state」
491
+ *
492
+ * core 重写后没有 `send()` 了(`CORE.md` §1:「常驻会话只 `push`,不看返回值」):
493
+ * 「等」这种动作看不见不由我引起的变化,唯一可靠的替代是**订阅**。于是这里先订阅
494
+ * `state`、再 `push` —— 顺序不能反:push 之后状态已经变了,晚一步就错过「这一轮开始了」
495
+ * 那一拍,随后第一次报闲会被误当成「我这一轮跑完了」。
496
+ *
497
+ * ## `start()`:老 `send()` 隐含的那件事
498
+ *
499
+ * 老的 `send()` 是对「这个 agent」发起的,没起来也能顺手跑一段。新 core 的循环只听
500
+ * `start()`,所以这里先把它叫起来:`start()` 幂等(已起来就返回同一句 promise),
501
+ * **不能 await** —— 它到死才 resolve。宿主正常会话里这一句是空动作。
502
+ *
503
+ * ## 返回「这一轮怎么结束的」而不是「成没成」
504
+ *
505
+ * 三种结束方式对调用方意义不同(`idle` 才能去校验产物),所以分开报:
506
+ * - `idle`:跑完了;
507
+ * - `paused`:被 `abort()` 暂停/掉;
508
+ * - `dead`:关门/硬杀,循环已经结束。
509
+ *
510
+ * 第四种情况不在这里表达:`push` 在关门之后会直接抛 `AgentError("closed")` —— 那是
511
+ * 「调用方违约」(往一个已经没有的会话里塞东西),就该往上抛,不该被归成一种“结束方式”。
512
+ */
513
+ async pushInstructionRound(agent, content, signal) {
514
+ // 暂停中不取件:此刻投进去只会排在队列里,等 resume 后突然自己跑起来
515
+ if (agent.state === "paused")
516
+ return "paused";
517
+ // 叫起来(幂等;不 await —— 那句 promise 到死才 resolve)
518
+ void agent.start();
519
+ const ended = new Promise((resolve) => {
520
+ let sawBusy = false;
521
+ const offs = [];
522
+ const finish = (end) => {
523
+ for (const off of offs.splice(0))
524
+ off();
525
+ resolve(end);
526
+ };
527
+ offs.push(agent.on("state", (event) => {
528
+ if (event.to === "busy") {
529
+ sawBusy = true;
530
+ }
531
+ else if (event.to === "idle" && sawBusy) {
532
+ // 只认「忙过之后的闲」:投递之前那一段(队列里还压着别人的货)的闲不是我的
533
+ finish("idle");
534
+ }
535
+ else if (event.to === "paused") {
536
+ finish("paused");
537
+ }
538
+ }));
539
+ offs.push(agent.on("stopped", () => finish("dead")));
540
+ offs.push(agent.on("killed", () => finish("dead")));
541
+ // 取消也要能打断「等闲」(`CORE.md` §5 那个死角:等子 agent 闲同样得能被掐断)
542
+ const onAbort = () => finish("paused");
543
+ signal?.addEventListener("abort", onAbort, { once: true });
544
+ // 正常收尾时把 signal 上的监听一起摘掉:调用方的 signal 可能活得比这一轮长得多
545
+ offs.push(() => signal?.removeEventListener("abort", onAbort));
546
+ });
547
+ agent.push({
548
+ content,
549
+ priority: "low",
550
+ // 这条指令是**宿主侧**(`/handoff` 命令、自动迁移)注入的,不是用户说的话 ——
551
+ // 按「谁注入谁填」给它一个 system 来源(`CORE.md` §3)
552
+ source: { kind: "system", label: "handoff" },
553
+ });
554
+ // 关门之后投递会抛 `AgentError("closed")`(`CORE.md` §1):不接、不归类,
555
+ // 让它往上走到 {@link runSelfHandoff} 的 catch(那里把 closed 原样再往上交)
556
+ return await ended;
557
+ }
465
558
  /** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
466
559
  async generateSummary(agent, historyText, handoffPath, signal) {
467
560
  const client = this.client ?? agent.client;
@@ -4,7 +4,7 @@ import type { AbortedMessageStrategy, AbortedToolRoundStrategy, AgentNS, Tool }
4
4
  import type { AgentDefinition } from "../types/index.js";
5
5
  import type { Scope } from "../scope/Scope.js";
6
6
  import type { ModelLevel } from "./resolveModel.js";
7
- export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
7
+ export type { AgentPlugin, InnerLoopContext, OuterLoopContext, SubAgentHookContext, ToolHookContext, } from "@ai-zen/agents-core";
8
8
  /**
9
9
  * SDK Agent — 继承 Core Agent,携带 SDK 层额外信息。
10
10
  *
@@ -16,7 +16,7 @@ export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
16
16
  * - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
17
17
  * 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
18
18
  *
19
- * 插件能力(use / init / send 钩子分发)继承自 Core Agent,此处不重复实现。
19
+ * 插件能力(use / init / 钩子分发)继承自 Core Agent,此处不重复实现。
20
20
  * 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
21
21
  * 权限统一从 `definition.permissions` 读取。
22
22
  */
@@ -36,7 +36,6 @@ export declare class SdkAgent extends Agent {
36
36
  modelConfig?: Record<string, unknown>;
37
37
  messages?: AgentNS.Message[];
38
38
  tools?: Tool[];
39
- allowJsonParseError?: boolean;
40
39
  /** 工具轮次被中断时的归一策略(core 默认 `fill`) */
41
40
  abortedToolRoundStrategy?: AbortedToolRoundStrategy;
42
41
  /** `fill` 策略下未完成工具结果的填充原因 */
@@ -10,7 +10,7 @@ import { Agent } from "@ai-zen/agents-core";
10
10
  * - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
11
11
  * 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
12
12
  *
13
- * 插件能力(use / init / send 钩子分发)继承自 Core Agent,此处不重复实现。
13
+ * 插件能力(use / init / 钩子分发)继承自 Core Agent,此处不重复实现。
14
14
  * 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
15
15
  * 权限统一从 `definition.permissions` 读取。
16
16
  */
@@ -28,7 +28,6 @@ export class SdkAgent extends Agent {
28
28
  modelConfig: params.modelConfig,
29
29
  messages: params.messages,
30
30
  tools: params.tools,
31
- allowJsonParseError: params.allowJsonParseError,
32
31
  abortedToolRoundStrategy: params.abortedToolRoundStrategy,
33
32
  abortedToolRoundReason: params.abortedToolRoundReason,
34
33
  abortedMessageStrategy: params.abortedMessageStrategy,
@@ -25,6 +25,15 @@ export interface ExcludeOptions {
25
25
  export interface FilterOptions {
26
26
  exclude?: ExcludeOptions;
27
27
  }
28
+ /**
29
+ * 取配置的端口 —— `Scope` 不再收一份配置快照,而是收「怎么拿到当下这一份」。
30
+ *
31
+ * 配置的本质是磁盘上那几个 json:改完之后该由下一次 `refresh()` 现读读到,
32
+ * 而不是把整个 Scope 拆掉重建(拆掉会连带别的能力一起重来,且正在跑的那一轮
33
+ * 会被抽掉能力)。端口可以是同步的(测试里给一份常量),也可以是异步的
34
+ * (宿主给 `ConfigManager.read()`)。
35
+ */
36
+ export type ScopeConfigSource = () => AppConfig | Promise<AppConfig>;
28
37
  /**
29
38
  * Scope — 全局上下文 + 能力装配编排容器。
30
39
  *
@@ -36,7 +45,7 @@ export interface FilterOptions {
36
45
  *
37
46
  * 装配方式(插件必须显式注入,Scope 不装任何默认插件):
38
47
  * ```ts
39
- * const scope = new Scope({ config, cwd, agentsDir })
48
+ * const scope = new Scope({ getConfig, cwd, agentsDir })
40
49
  * .use(...allInOne({ skillsPaths, toolsPaths, subAgentsPaths, mcpPaths }));
41
50
  * await scope.init();
42
51
  * ```
@@ -44,14 +53,21 @@ export interface FilterOptions {
44
53
  * 设计原则:
45
54
  * - Scope 只做编排:三阶段管线骨架(发现 → 过滤 → 实例化)+ 生命周期
46
55
  * - 能力来源(内置/用户工具、Skill、MCP、SubAgent)全部疏散到 ScopePlugin,各自自持
47
- * - Scope 实例一旦创建,config/cwd/agentsDir/env 不变;refresh() 只让插件重新发现
56
+ * - config 随 `refresh()` 更新(每轮现读端口),cwd / agentsDir 创建之后不变
48
57
  */
49
58
  export declare class Scope {
50
- /** 应用配置(端点、模型等) */
51
- readonly config: AppConfig;
59
+ /** 取配置的端口:每次 `refresh()` 都问它要一份 */
60
+ private readonly getConfig;
61
+ /**
62
+ * 当下这一份配置。
63
+ *
64
+ * 只有一个字段、一个来源:`scope.config` 与 `scope.env.config` 读的都是它,
65
+ * 于是「按新配置算出来的东西」与「工具 exec 时看到的配置」不会分叉。
66
+ */
67
+ private current?;
52
68
  /** 当前工作目录 — 相对路径解析基准,也是 ToolEnv.cwd 的来源 */
53
69
  readonly cwd: string;
54
- /** 工具环境 — 插件实例化内置工具时注入 */
70
+ /** 工具环境 — 插件实例化内置工具时注入(`config` 是活的,见构造函数的注释) */
55
71
  readonly env: ToolEnv;
56
72
  /** Agent 定义目录(createAgent 用) */
57
73
  readonly agentsDir: string;
@@ -60,12 +76,20 @@ export declare class Scope {
60
76
  /** 是否已 init(init 之后禁止再 use) */
61
77
  private _initialized;
62
78
  constructor(options: {
63
- config: AppConfig;
79
+ /** 取配置的端口:配置改了不必重建 Scope,下一次 `refresh()` 就会读到新的那一份 */
80
+ getConfig: ScopeConfigSource;
64
81
  agentsDir: string;
65
82
  cwd?: string;
66
83
  /** 出网/外部依赖的注入点(缺省全部走真实 OpenAI SDK),会透传到 ToolEnv.deps */
67
84
  deps?: ToolEnvDeps;
68
85
  });
86
+ /**
87
+ * 应用配置(端点、模型等)。
88
+ *
89
+ * 同步读,读到的是**当下**那一份:`refresh()` 之后就是磁盘上的新配置。
90
+ * 配置端口是异步的且还没 `init()` 过时抛错(那时确实还没有「当下这一份」)。
91
+ */
92
+ get config(): AppConfig;
69
93
  /** 已注册插件(只读视图) */
70
94
  get plugins(): readonly ScopePlugin[];
71
95
  /**
@@ -81,11 +105,14 @@ export declare class Scope {
81
105
  /** 按 id 查找插件(供外部代码/其它插件查询插件状态) */
82
106
  getPluginById<T extends ScopePlugin>(id: string): T | undefined;
83
107
  /**
84
- * 初始化:执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
108
+ * 初始化:取一次配置 + 执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
85
109
  */
86
110
  init(): Promise<void>;
87
111
  /**
88
- * 重新执行全局发现(遍历插件 discover())。
112
+ * 重新取配置 + 重新执行全局发现(遍历插件 discover())。
113
+ *
114
+ * 顺序不能反:插件发现可能要用新配置算路径 / 开关(如内置工具的可用性、
115
+ * MCP 的连接对账),所以先把 `current` 换掉,再让插件看世界。
89
116
  */
90
117
  refresh(options?: {
91
118
  silent?: boolean;
@@ -10,7 +10,7 @@ import { PermissionEvaluator } from "./PermissionEvaluator.js";
10
10
  *
11
11
  * 装配方式(插件必须显式注入,Scope 不装任何默认插件):
12
12
  * ```ts
13
- * const scope = new Scope({ config, cwd, agentsDir })
13
+ * const scope = new Scope({ getConfig, cwd, agentsDir })
14
14
  * .use(...allInOne({ skillsPaths, toolsPaths, subAgentsPaths, mcpPaths }));
15
15
  * await scope.init();
16
16
  * ```
@@ -18,14 +18,21 @@ import { PermissionEvaluator } from "./PermissionEvaluator.js";
18
18
  * 设计原则:
19
19
  * - Scope 只做编排:三阶段管线骨架(发现 → 过滤 → 实例化)+ 生命周期
20
20
  * - 能力来源(内置/用户工具、Skill、MCP、SubAgent)全部疏散到 ScopePlugin,各自自持
21
- * - Scope 实例一旦创建,config/cwd/agentsDir/env 不变;refresh() 只让插件重新发现
21
+ * - config 随 `refresh()` 更新(每轮现读端口),cwd / agentsDir 创建之后不变
22
22
  */
23
23
  export class Scope {
24
- /** 应用配置(端点、模型等) */
25
- config;
24
+ /** 取配置的端口:每次 `refresh()` 都问它要一份 */
25
+ getConfig;
26
+ /**
27
+ * 当下这一份配置。
28
+ *
29
+ * 只有一个字段、一个来源:`scope.config` 与 `scope.env.config` 读的都是它,
30
+ * 于是「按新配置算出来的东西」与「工具 exec 时看到的配置」不会分叉。
31
+ */
32
+ current;
26
33
  /** 当前工作目录 — 相对路径解析基准,也是 ToolEnv.cwd 的来源 */
27
34
  cwd;
28
- /** 工具环境 — 插件实例化内置工具时注入 */
35
+ /** 工具环境 — 插件实例化内置工具时注入(`config` 是活的,见构造函数的注释) */
29
36
  env;
30
37
  /** Agent 定义目录(createAgent 用) */
31
38
  agentsDir;
@@ -34,12 +41,36 @@ export class Scope {
34
41
  /** 是否已 init(init 之后禁止再 use) */
35
42
  _initialized = false;
36
43
  constructor(options) {
37
- this.config = options.config;
44
+ this.getConfig = options.getConfig;
38
45
  this.cwd = options.cwd ?? process.cwd();
39
- this.env = options.deps
40
- ? { cwd: this.cwd, config: this.config, deps: options.deps }
41
- : { cwd: this.cwd, config: this.config };
42
46
  this.agentsDir = options.agentsDir;
47
+ // 端口给的是现成的一份(同步)时,构造完就能读 config;给的是 Promise 时
48
+ // 留到 init() / refresh() 填 —— 那时候读之前先等一次即可。
49
+ const seeded = options.getConfig();
50
+ if (!isPromiseLike(seeded))
51
+ this.current = seeded;
52
+ const scope = this;
53
+ this.env = {
54
+ cwd: this.cwd,
55
+ // 活的 config:工具在 exec 时读到的永远是「当下这一份」,refresh 之后就是新的。
56
+ // 不在这里另存一份,否则 env.config 与 scope.config 会分叉。
57
+ get config() {
58
+ return scope.config;
59
+ },
60
+ ...(options.deps ? { deps: options.deps } : {}),
61
+ };
62
+ }
63
+ /**
64
+ * 应用配置(端点、模型等)。
65
+ *
66
+ * 同步读,读到的是**当下**那一份:`refresh()` 之后就是磁盘上的新配置。
67
+ * 配置端口是异步的且还没 `init()` 过时抛错(那时确实还没有「当下这一份」)。
68
+ */
69
+ get config() {
70
+ if (this.current === undefined) {
71
+ throw new Error("Scope.config is not loaded yet: the config port is async, await init() / refresh() first");
72
+ }
73
+ return this.current;
43
74
  }
44
75
  // ==================================================================
45
76
  // 插件注册与生命周期
@@ -71,17 +102,21 @@ export class Scope {
71
102
  return this._plugins.find((p) => p.id === id);
72
103
  }
73
104
  /**
74
- * 初始化:执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
105
+ * 初始化:取一次配置 + 执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
75
106
  */
76
107
  async init() {
77
108
  await this.refresh();
78
109
  this._initialized = true;
79
110
  }
80
111
  /**
81
- * 重新执行全局发现(遍历插件 discover())。
112
+ * 重新取配置 + 重新执行全局发现(遍历插件 discover())。
113
+ *
114
+ * 顺序不能反:插件发现可能要用新配置算路径 / 开关(如内置工具的可用性、
115
+ * MCP 的连接对账),所以先把 `current` 换掉,再让插件看世界。
82
116
  */
83
117
  async refresh(options) {
84
118
  const opts = { silent: options?.silent ?? false };
119
+ this.current = await this.getConfig();
85
120
  for (const plugin of this._plugins) {
86
121
  await plugin.discover?.(this, opts);
87
122
  }
@@ -153,6 +188,10 @@ export class Scope {
153
188
  return dedupTools(result);
154
189
  }
155
190
  }
191
+ /** 端口返回值是不是 Promise(同步端口因此可以省掉一次 await 的语义差别) */
192
+ function isPromiseLike(value) {
193
+ return typeof value?.then === "function";
194
+ }
156
195
  function dedupTools(tools) {
157
196
  const seen = new Set();
158
197
  const result = [];