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

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 (131) hide show
  1. package/CHANGELOG.md +73 -16
  2. package/README.md +397 -113
  3. package/README.zh.md +314 -112
  4. package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
  5. package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
  6. package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -14
  7. package/dist/agent-plugins/AutoMigratePlugin.js +36 -36
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +6 -6
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +2 -2
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +20 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +25 -24
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +25 -35
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +26 -41
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +14 -9
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -13
  16. package/dist/config/ConfigManager.d.ts +13 -5
  17. package/dist/config/ConfigManager.js +58 -39
  18. package/dist/config/constants.d.ts +1 -1
  19. package/dist/config/constants.js +2 -2
  20. package/dist/config/factory-skills.js +2 -2
  21. package/dist/config/normalize.d.ts +93 -0
  22. package/dist/config/normalize.js +158 -0
  23. package/dist/crud/AgentRepository.d.ts +3 -1
  24. package/dist/crud/AgentRepository.js +4 -2
  25. package/dist/index.d.ts +19 -9
  26. package/dist/index.js +14 -7
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +82 -15
  30. package/dist/runtime/HandoffGuardPlugin.js +136 -17
  31. package/dist/runtime/HandoffService.d.ts +244 -119
  32. package/dist/runtime/HandoffService.js +373 -251
  33. package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
  34. package/dist/runtime/RuntimePeerSessions.js +50 -0
  35. package/dist/runtime/Scopes.d.ts +123 -0
  36. package/dist/runtime/Scopes.js +169 -0
  37. package/dist/runtime/SdkAgent.d.ts +19 -8
  38. package/dist/runtime/SdkAgent.js +23 -6
  39. package/dist/runtime/completeOnce.d.ts +3 -3
  40. package/dist/runtime/completeOnce.js +3 -3
  41. package/dist/runtime/createAgent.d.ts +29 -7
  42. package/dist/runtime/createAgent.js +57 -12
  43. package/dist/runtime/createModel.d.ts +4 -4
  44. package/dist/runtime/createModel.js +6 -6
  45. package/dist/runtime/lastPromptTokens.d.ts +18 -0
  46. package/dist/runtime/lastPromptTokens.js +26 -0
  47. package/dist/runtime/resolveModel.d.ts +9 -9
  48. package/dist/runtime/resolveModel.js +8 -8
  49. package/dist/scope/Scope.d.ts +10 -9
  50. package/dist/scope/Scope.js +6 -6
  51. package/dist/scope/ScopePlugin.d.ts +2 -8
  52. package/dist/scope/disclosure.d.ts +1 -1
  53. package/dist/scope/disclosure.js +1 -1
  54. package/dist/scope/plugins/allInOne.d.ts +13 -1
  55. package/dist/scope/plugins/allInOne.js +9 -5
  56. package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
  57. package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
  58. package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
  59. package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
  60. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
  61. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
  62. package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
  63. package/dist/scope/plugins/builtin/ExecTool.js +10 -199
  64. package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
  65. package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
  66. package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
  67. package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
  68. package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
  69. package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
  70. package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
  71. package/dist/scope/plugins/builtin/SleepTool.js +2 -3
  72. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
  73. package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
  74. package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
  75. package/dist/scope/plugins/builtin/WriteTool.js +8 -1
  76. package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
  77. package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
  78. package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
  79. package/dist/scope/plugins/builtin/commandOutput.js +55 -0
  80. package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
  81. package/dist/scope/plugins/builtin/commandRun.js +169 -0
  82. package/dist/scope/plugins/builtin/discover.d.ts +1 -3
  83. package/dist/scope/plugins/builtin/discover.js +1 -3
  84. package/dist/scope/plugins/builtin/index.d.ts +5 -7
  85. package/dist/scope/plugins/builtin/index.js +7 -7
  86. package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
  87. package/dist/scope/plugins/builtin/outputGuard.js +1 -5
  88. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +56 -11
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +169 -74
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +17 -7
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +36 -12
  92. package/dist/scope/plugins/mcp/discover.d.ts +9 -2
  93. package/dist/scope/plugins/mcp/discover.js +12 -14
  94. package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
  95. package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
  96. package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
  97. package/dist/scope/plugins/mcp/mcpTools.js +220 -39
  98. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +4 -7
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +4 -7
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +97 -46
  101. package/dist/scope/plugins/peers/peerSessionTools.js +147 -121
  102. package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
  103. package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
  104. package/dist/scope/plugins/skills/discover.d.ts +15 -8
  105. package/dist/scope/plugins/skills/discover.js +15 -26
  106. package/dist/scope/plugins/skills/skillTools.d.ts +8 -7
  107. package/dist/scope/plugins/skills/skillTools.js +18 -14
  108. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
  109. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
  110. package/dist/scope/plugins/subagents/discover.d.ts +7 -1
  111. package/dist/scope/plugins/subagents/discover.js +7 -3
  112. package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
  113. package/dist/scope/plugins/subagents/subAgentTools.js +11 -1
  114. package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
  115. package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
  116. package/dist/scope/plugins/usertools/discover.d.ts +7 -8
  117. package/dist/scope/plugins/usertools/discover.js +17 -27
  118. package/dist/shared/EntityRepository.d.ts +22 -5
  119. package/dist/shared/EntityRepository.js +45 -29
  120. package/dist/shared/content-blocks.d.ts +9 -3
  121. package/dist/shared/content-blocks.js +12 -19
  122. package/dist/shared/errors.d.ts +5 -7
  123. package/dist/shared/errors.js +6 -8
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +36 -13
  127. package/package.json +2 -2
  128. package/dist/config/migrate.d.ts +0 -115
  129. package/dist/config/migrate.js +0 -200
  130. package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
  131. package/dist/scope/plugins/builtin/test-helpers.js +0 -4
@@ -1,19 +1,20 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { dirname, join, resolve as resolvePath } from "node:path";
3
- import { AgentError, Message } from "@ai-zen/agents-core";
4
- import { getLogger } from "../shared/logger.js";
3
+ import { AgentError, AgentNS, Message } from "@ai-zen/agents-core";
4
+ import { SILENT_LOG } 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";
7
7
  import { completeOnce } from "./completeOnce.js";
8
- import { HandoffGuardPlugin } from "./HandoffGuardPlugin.js";
8
+ import { HandoffGuardPlugin, HANDOFF_SOURCE_LABEL } from "./HandoffGuardPlugin.js";
9
+ import { WRITE_TOOL_NAME } from "../scope/plugins/builtin/WriteTool.js";
9
10
  /**
10
11
  * 交接被调用方取消(`AbortSignal` 触发)。
11
12
  *
12
13
  * 单独成类型而不是复用 `Error`,原因有两个:
13
- * - 调用方(如 TUI)要把「用户按了 Ctrl+C」与「交接真的失败了」区分开 ——
14
- * 前者应静默收尾并提示「已取消」,后者才该报错;
15
- * - 它**不可降级**:`self` 被取消后绝不能退到 `summary` 再跑一遍。
16
- * 把「用户中止」当成「模型没写出文档」,会白白多烧一轮全量输入。
14
+ * - 调用方要把「用户按了 Ctrl+C」与「交接真的失败了」区分开 ——
15
+ * 前者静默收尾并提示「已取消」,后者才该报错;
16
+ * - 它不降级:`self` 被取消后不重试 `summary`。把「用户中止」当成「模型没写出文档」,
17
+ * 会白白多烧一次全量输入。
17
18
  */
18
19
  export class HandoffAbortedError extends Error {
19
20
  constructor() {
@@ -36,34 +37,46 @@ function isAbortError(err, signal) {
36
37
  return name === "AbortError" || name === "APIUserAbortError";
37
38
  }
38
39
  /**
39
- * 合并两条取消信号:任一触发即视为取消。
40
+ * 让一件承诺与取消信号赛跑:信号响了就用给定的那个值作答。
40
41
  *
41
- * 服务自身的 `abort()`(见 {@link HandoffService.abort})与调用方传入的 `signal`
42
- * 都要认:前者是自动迁移唯一的取消入口(那条链路调用方递不进 signal),后者留给
43
- * 「外层还有自己的超时 / 取消」的调用方。
42
+ * 返回的 `stop()` 要把监听摧掉 —— 调用方的 signal 可能活得比这一趟长得多。没有信号时那条
43
+ * 承诺不会落定,赛跑就等于等另一头。
44
44
  */
45
- function mergeSignals(own, external) {
46
- return external ? AbortSignal.any([own, external]) : own;
45
+ function abortRace(signal, whenAborted) {
46
+ let stop = () => undefined;
47
+ const raced = new Promise((resolve) => {
48
+ if (!signal)
49
+ return;
50
+ const onAbort = () => resolve(whenAborted);
51
+ signal.addEventListener("abort", onAbort, { once: true });
52
+ stop = () => signal.removeEventListener("abort", onAbort);
53
+ });
54
+ return { raced, stop };
47
55
  }
48
56
  /**
49
57
  * 任务交接服务。
50
58
  *
51
- * 职责分层(这是本模块唯一的设计主线):
52
- * - `handoff()`:**只产出交接文档**(停工 → 写文档 → 校验 → 失败降级),不动会话;
53
- * - `migrate()`:`handoff()` 之后清历史并开新会话。
59
+ * 职责两半:`handoff()` 只产出交接文档(停工 → 写文档,做不成就报失败),不动会话;`migrate()`
60
+ * 再算出「换完之后记忆长什么样」并交给接缝。落库(旧历史挂成存档会话、写回会话行)在宿主
61
+ * 那一侧:那是一个库事务,SDK 不认识库。
54
62
  *
55
63
  * 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
56
- * 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
64
+ * 「读正文 → 注入 → 读不到时用兜底模板」,不持有第二份章节清单。
65
+ *
66
+ * ## `handingOff` 只说「这一趟自己在跑」,不是「这段会话在交接」
57
67
  *
58
- * 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身就是「往同一个 agent
59
- * 里再投一轮」(`push` 一条指令),它跑完后 agent 会再变闲一次 —— 若不在 busy 期间让
60
- * `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、迁移再触发交接」
61
- * 无限递归,或在最满的时刻被护栏直接拒掉。
68
+ * 「这段会话正在交接」那份事实由宿主持有(`ChatRunner.beginHandoff` / `endHandoff`:它决定
69
+ * 这段的消息落不落库、对外报哪一格),SDK 这一层根本不认识会话,也就不该有自己的那本账。
70
+ * 这里的 `handingOff` 只回答一件事:**本服务这一趟是不是已经在跑**(防重入 + 给自动交接插件
71
+ * 一个让行的依据)。自重入是真会发生的:自交接就是「往同一个 agent 里再投一条指令」(`push`),
72
+ * 它跑完那一段照样落回闲 —— 不在 `handingOff` 期间让 `AutoMigratePlugin` 让行,就会「交接触发
73
+ * 自动交接、自动交接再触发交接」无限递归。硬线(`ContextGuardPlugin`)不在这条线上:它在交接
74
+ * 回合也照拦、不让路(见 `dev-docs/prd/05-control.md`「两条线的口径」)。
62
75
  *
63
- * 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
64
- * `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
65
- * 只认外部 signal 的后果是「自动迁移期间按 Ctrl+C 会被当成『文档没写出来』,于是重试一轮、
66
- * 再降级 summary 一轮,最后照样迁移」。取消后一律回到交接前的状态(见 {@link HandoffService.restoreBeforeHandoff})。
76
+ * ## 取消只认调用方递进来的 `signal`
77
+ *
78
+ * 服务自己不持有取消句柄:谁启动这一趟,谁手里的 `signal` 就是它的取消口;这一趟被取消后
79
+ * 回到交接前的状态(见 {@link HandoffService.restoreBeforeHandoff})。
67
80
  */
68
81
  export class HandoffService {
69
82
  /** 交接文档兜底模板(仅在读不到 Skill 时使用) */
@@ -71,51 +84,79 @@ export class HandoffService {
71
84
  handoffDirPath;
72
85
  defaultMode;
73
86
  defaultStrategy;
87
+ minHandoffBytes;
74
88
  skillDirs;
75
89
  client;
76
90
  model;
77
91
  modelConfig;
78
- minHandoffBytes;
79
92
  onBeforeHandoff;
80
93
  onHandoff;
81
94
  onMigrated;
95
+ commitMemory;
82
96
  logger;
83
- /** 交接/迁移进行中标志(插件据此让行) */
84
- _busy = false;
85
97
  /**
86
- * 当前这次交接/迁移的取消句柄(`null` = 没有进行中的交接)。
98
+ * 这一趟交接是不是本服务自己在跑(防重入 + 自动交接插件据此让行)。
87
99
  *
88
- * 三条链路(`/handoff`、`/migrate`、自动迁移)共用同一个开关:前两条还有调用方能
89
- * 传 `signal`,自动迁移没有 —— 句柄放在服务里,三者的取消语义才不会各不相同。
100
+ * 不是「这段会话在交接」:那份事实由宿主持有(见类注释)。
90
101
  */
91
- abortController = null;
102
+ _handingOff = false;
92
103
  /** 交接回合的工具守卫(同一实例复用 + arm/disarm,避免插件数组无限增长) */
93
104
  guard;
94
105
  /** 已注册过守卫的 agent(每个 agent 只 use 一次) */
95
106
  guardedAgents = new WeakSet();
107
+ /**
108
+ * 订了交接事实的那些人。**旁路**:只收,不参与任何判断(交接的流程一个字都不从这里读),
109
+ * 与运行时的 `listeners` 同一个位置、同一个用法。
110
+ */
111
+ listeners = new Set();
96
112
  constructor(options = {}) {
97
- const { handoffDir, mode, strategy, skillDirs, client, model, modelConfig, minHandoffBytes, onBeforeHandoff, onHandoff, onMigrated, logger, } = options;
113
+ const { handoffDir, mode, strategy, minHandoffBytes, skillDirs, client, model, modelConfig, onBeforeHandoff, onHandoff, onMigrated, commitMemory, logger, } = options;
98
114
  this.handoffDirPath = resolvePath(handoffDir ?? join(process.cwd(), ".ai-zen", "handoffs"));
99
115
  this.defaultMode = mode ?? "self";
100
116
  this.defaultStrategy = strategy ?? "omit";
117
+ // 400 字节是文档里的数(`PRD.md` 3.6 / 4.5),不在这里再发明一个
118
+ this.minHandoffBytes = minHandoffBytes ?? 400;
101
119
  this.skillDirs = skillDirs ?? [];
102
120
  this.client = client;
103
121
  this.model = model;
104
122
  this.modelConfig = modelConfig;
105
- this.minHandoffBytes = minHandoffBytes ?? 400;
106
123
  this.onBeforeHandoff = onBeforeHandoff;
107
124
  this.onHandoff = onHandoff;
108
125
  this.onMigrated = onMigrated;
109
- this.logger = logger ?? getLogger();
126
+ this.commitMemory = commitMemory;
127
+ this.logger = logger ?? SILENT_LOG;
110
128
  }
111
- /** 是否正在交接/迁移(`AutoMigratePlugin` / `ContextGuardPlugin` 据此让行) */
112
- get busy() {
113
- return this._busy;
129
+ /** 这一趟交接是不是本服务自己在跑(`AutoMigratePlugin` 据此让行,防递归) */
130
+ get handingOff() {
131
+ return this._handingOff;
114
132
  }
115
133
  /** 交接文档目录 */
116
134
  get handoffDir() {
117
135
  return this.handoffDirPath;
118
136
  }
137
+ /**
138
+ * 订阅交接的事实;返回幂等的退订函数。
139
+ *
140
+ * 三格({@link HandoffFact}):开始了、成了、没成(失败那一格带错误)。发出点只有一处 ——
141
+ * {@link HandoffService.withHandingOff},`handoff()` 与 `migrate()` 共用的那道包装:它本来就
142
+ * 是「正在交接」被立起来的地方;两边各发一遍就是把同一趟报两次。
143
+ *
144
+ * **这三格为什么挂在 `HandoffService` 上而不是内核的事件表上**:交接是这一层的概念,内核不认识
145
+ * 它。把它塞进内核的事件表,等于让内核认识一个它永远不参与的东西。
146
+ *
147
+ * **订阅者抛错不影响这一趟交接**:事实是旁路,谁都可能在那里抛(写库、推送);隔离兜在
148
+ * {@link HandoffService.emit} 那一个循环里 —— 一个订阅者炸了只记一句日志,这一趟该跑完照常
149
+ * 跑完、该报的 `finished` / `failed` 照常报。
150
+ *
151
+ * **晚到的订阅者**拿不到过去的事实:事实只报变化,「此刻在不在交接」那一格由 `handingOff`
152
+ * 快照对齐,两者合起来才说得清「此刻」与「怎么走到这一刻」。
153
+ */
154
+ observe(listener) {
155
+ this.listeners.add(listener);
156
+ return () => {
157
+ this.listeners.delete(listener);
158
+ };
159
+ }
119
160
  // ==================================================================
120
161
  // 静态纯工具(供上层复用 / 单测)
121
162
  // ==================================================================
@@ -132,9 +173,9 @@ export class HandoffService {
132
173
  return `${stamp}.md`;
133
174
  }
134
175
  /**
135
- * 拼装「本轮交接」指令:`[Skill 正文] + [本次交接参数]`。
176
+ * 拼装「这次交接」的指令:`[Skill 正文] + [本次交接参数]`。
136
177
  *
137
- * 不在 Skill 正文里发明占位符(本体系没有模板变量引擎),参数一律由代码拼在后面,
178
+ * 不在 Skill 正文里发明占位符(本体系没有模板变量引擎),参数都由代码拼在后面,
138
179
  * 这样 Skill 只讲「怎么写」、代码只讲「写到哪、有什么能力」。
139
180
  */
140
181
  static createHandoffInstruction(params) {
@@ -148,7 +189,7 @@ export class HandoffService {
148
189
  "Output the complete document body directly: no explanations, do not wrap it in a code block, the caller will persist it to disk itself.",
149
190
  ];
150
191
  return [
151
- "You are now to write a task handoff document for this conversation. The following handoff rules are mandatory.",
192
+ "You are now to write a task handoff document for this session. The following handoff rules are mandatory.",
152
193
  "",
153
194
  "---",
154
195
  "",
@@ -166,22 +207,23 @@ export class HandoffService {
166
207
  ].join("\n");
167
208
  }
168
209
  /**
169
- * 生成迁移后追加的「交接断点」消息(role=user):只给路径,让接手方自己 read。
210
+ * 交接断点消息:换完记忆之后,接手的那一代看到的那一条。
170
211
  *
171
- * 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
172
- * 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
212
+ * 形状是死的(`PRD.md` 3.6 / 4.5、`PLAN.md` §5.3):`role: system` + `hidden`(不给人看,
213
+ * 但照常进上下文)+ **正文只带文档路径**。不带全文:读的钱由需要细节的一方付,内联只会让
214
+ * 之后每一条请求都携着全文。
173
215
  *
174
- * `source` 必须带(`CORE.md` §3「所有 `role: user` 的消息都必须有 source」):这条不是
175
- * 用户说的话,是宿主注入的,所以是 `system` + label。
216
+ * **只有这一处造它**:外部使用者用 SDK 时也是这一条,宿主落库时落的也是这一条。
176
217
  */
177
218
  static createPostMessages(handoffPath) {
178
- const content = [
179
- "The previous conversation has been handed off, the handoff document is saved at:",
180
- handoffPath,
181
- "",
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.",
183
- ].join("\n");
184
- return [Message.User(content, { kind: "system", label: "handoff" })];
219
+ return [
220
+ new Message({
221
+ role: AgentNS.Role.System,
222
+ content: handoffPath,
223
+ status: AgentNS.MessageStatus.Completed,
224
+ hidden: true,
225
+ }),
226
+ ];
185
227
  }
186
228
  /** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
187
229
  static serializeMessages(messages) {
@@ -196,18 +238,6 @@ export class HandoffService {
196
238
  // ==================================================================
197
239
  // 公开流程
198
240
  // ==================================================================
199
- /**
200
- * 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
201
- *
202
- * 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
203
- * 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的那一轮是往常驻 agent 里
204
- * `push()` 的一条指令,调用方通常要同时 `agent.abort()`(TUI 就是这么做的 ——
205
- * 那一按会让 agent 停在 `paused`,本服务随之把这一轮判成「没跑完」);`summary`
206
- * 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
207
- */
208
- abort() {
209
- this.abortController?.abort();
210
- }
211
241
  /**
212
242
  * 只产出交接文档,**不改动会话**(`/handoff`)。
213
243
  *
@@ -216,67 +246,130 @@ export class HandoffService {
216
246
  * 回合从 `agent.messages` 里截掉,本次新建的文档也不留。
217
247
  */
218
248
  async handoff(params) {
219
- return this.withBusy((own) => this.runHandoff({ ...params, signal: mergeSignals(own, params.signal) }, false));
249
+ return this.withHandingOff(this.modeOf(params), () => this.runHandoff(params));
220
250
  }
221
251
  /**
222
- * 交接 + 开新会话(`/migrate`、自动迁移)。
252
+ * 交接 **+ 换记忆**(宿主的交接收口、自动交接、`/migrate`)。
253
+ *
254
+ * 两半,第二半是这方法存在的理由:
255
+ * 1. 先跟 {@link handoff} 一样把文档写出来(写不出来就抛:不换执行者);
256
+ * 2. 然后**算出换完之后那段记忆长什么样**({@link planMemory})并把它交给接缝。
257
+ *
258
+ * 「长什么样」只有这一处算:哪些旧消息留(`omit` / `prune`)、断点消息的形状
259
+ * (`role: system` + `hidden` + 只带路径)、文档够不够长(不到 `minHandoffBytes` 算没写出来,在
260
+ * `runSelfHandoff` 里判)—— 外部使用者用 SDK 时也是这一份,宿主不另写一遍(`PRD.md` 4.5)。
223
261
  *
224
- * 策略(`strategy`):
225
- * - `omit`(默认):历史标记 `omit: true`(保留可审计),末尾追加交接断点;
226
- * - `prune`:物理剔除历史,只留 `definition.messages` + 交接断点。
262
+ * 换完的记忆就是「模板(系统提示)+ 断点消息」这两截:**没有** cwd 消息 —— 目录随时问 `cwd`
263
+ * 工具就行,不必往新记忆里塞一条(那一条只在创建会话时写一次)。
264
+ *
265
+ * 落点在哪儿就看有没有注入 {@link HandoffServiceOptions.commitMemory}:
266
+ * - **没注入**:SDK 自己把 `agent.messages` **原地**换成新记忆(外部使用者的路)。用 `splice`
267
+ * 不换引用:同一个数组已经交出去了,换引用等于把别人的眼睛一起换掉(`CORE.md` §12);
268
+ * - **注入了**:`agent.messages` 一个字节都不动,整份交给回调,由调用方落库、落内存。
269
+ * 接缝不改变记忆长什么样,它只决定这份记忆落在哪儿。
270
+ *
271
+ * 换完才叫 `onMigrated`(恢复后的钩子就在这一拍:此刻记忆已经是新的那一份了)。
227
272
  */
228
273
  async migrate(params) {
229
- return this.withBusy(async (own) => {
230
- // 拿到 ctx 即「已提交」:文档已通过校验,取消不再生效(见 runHandoff 末尾的取消点)。
231
- // 在 prune 之前再拦一次取消会留下第三种状态 ——「用户点了取消,旧会话却已存档、
232
- // 历史却已剔除」,比让迁移做完更糟
233
- const ctx = await this.runHandoff({ ...params, signal: mergeSignals(own, params.signal) }, true);
234
- const { agent } = ctx;
235
- const strategy = params.strategy ?? this.defaultStrategy;
236
- const breakpointMessages = HandoffService.createPostMessages(ctx.handoffPath);
237
- // 交接回合可能已经把 messages 换成新会话,definition 也可能是手写的(没有 messages):
238
- // 这里按空模板处理,好让报错落在"模型该补的配置"上,而不是原生 TypeError
239
- const templateMessages = agent.definition.messages ?? [];
240
- if (strategy === "prune") {
241
- // 浅拷贝模板消息,避免污染 definition.messages 引用的对象
242
- agent.messages = [...templateMessages, ...breakpointMessages];
274
+ return this.withHandingOff(this.modeOf(params), async () => {
275
+ // 拿到 ctx 就是「已提交」:文档已经写好并通过校验,取消不再生效(见 `runHandoff`)
276
+ const ctx = await this.runHandoff(params);
277
+ const memory = this.planMemory(ctx.agent, ctx.handoffPath, params.strategy ?? this.defaultStrategy);
278
+ if (this.commitMemory) {
279
+ // 宿主那一路:SDK 不动 `agent.messages`,落库与落内存都是调用方的事
280
+ await this.commitMemory({ memory, handoffPath: ctx.handoffPath, mode: ctx.mode });
243
281
  }
244
282
  else {
245
- const preserveCount = Math.min(templateMessages.length, agent.messages.length);
246
- agent.messages = [
247
- ...agent.messages.map((m, i) => ({
248
- ...m,
249
- omit: i >= preserveCount ? true : m.omit,
250
- })),
251
- ...breakpointMessages,
252
- ];
283
+ // 外部使用者那一路:原地换(`CORE.md` §12:已经交出去的数组不许换引用)
284
+ ctx.agent.messages.splice(0, ctx.agent.messages.length, ...memory);
253
285
  }
254
- await this.safeHook(this.onMigrated, ctx);
286
+ // 换记忆就是这一拍落下:叫完之后记忆已经是新的那一份
287
+ await this.onMigrated?.(ctx);
255
288
  return ctx;
256
289
  });
257
290
  }
291
+ /**
292
+ * 换完之后那段记忆**就是**这一份 —— 全仓唯一一处算它。
293
+ *
294
+ * 开头是模板(`definition.messages`:系统提示那几条,它们不是旧记忆的一部分,换完还得在),
295
+ * 末尾是交接断点({@link createPostMessages})—— 一条,只有它。中间那段看策略:
296
+ * - `prune`:一条不留(旧记忆整段腾空);
297
+ * - `omit`:原样留着但标 `omit: true`(不再发给模型,仍可回看)—— 模板那几条不标。
298
+ *
299
+ * 两个地方都不改原对象:`omit` 那一路造的是拷贝(同一个消息对象被两处引用等于两份事实)。
300
+ *
301
+ * `definition` 可能根本没有 `messages`(手写的定义 / 替身):按空模板处理,好让差错落在
302
+ * 「模型该补的配置」上,而不是一个原生 `TypeError`。
303
+ */
304
+ planMemory(agent, handoffPath, strategy) {
305
+ const templateMessages = agent.definition?.messages ?? [];
306
+ // 尾巴只有一条:断点(「旧记忆到这里为止」)
307
+ const tail = HandoffService.createPostMessages(handoffPath);
308
+ if (strategy === "prune")
309
+ return [...templateMessages, ...tail];
310
+ // `omit`:模板那几条(与正文长度取小,防模板比历史还长)原样留,其余标 omit
311
+ const preserveCount = Math.min(templateMessages.length, agent.messages.length);
312
+ return [
313
+ ...agent.messages.map((message, index) => index >= preserveCount ? { ...message, omit: true } : message),
314
+ ...tail,
315
+ ];
316
+ }
258
317
  // ==================================================================
259
318
  // 内部
260
319
  // ==================================================================
261
320
  /**
262
- * 串行化 + 防重入:交接与迁移共用同一把锁,也共用同一个取消句柄。
321
+ * 串行化 + 防重入:本服务同一时刻只跑一趟交接。
263
322
  *
264
- * 句柄与 `busy` 同寿命:`finally` 里清掉,否则下一次 `abort()` 会往一个已结束的
265
- * controller 上发出无意义的 abort(看起来「取消成功」,实际什么都没发生)。
323
+ * 只管「这一趟自己在跑」(不是「这段会话在交接」——那份事实在宿主那里),所以不需要
324
+ * 跨实例的锁,也不持有取消句柄:取消只认调用方递进来的 `signal`。
325
+ *
326
+ * 这一趟的三格事实也在这里发({@link HandoffFact}):`handoff()` 与 `migrate()` 共用它,
327
+ * 而「正在交接」正是在这一处被立起来的 —— 两边各发一遍就是把同一趟报两次。
266
328
  */
267
- async withBusy(fn) {
268
- if (this._busy)
329
+ async withHandingOff(mode, fn) {
330
+ if (this._handingOff)
269
331
  throw new Error("A handoff is already in progress, wait for it to finish");
270
- this._busy = true;
271
- const controller = new AbortController();
272
- this.abortController = controller;
332
+ this._handingOff = true;
273
333
  try {
274
- return await fn(controller.signal);
334
+ this.emit({ type: "started", mode });
335
+ let result;
336
+ try {
337
+ result = await fn();
338
+ }
339
+ catch (thrown) {
340
+ // 没成:错误收成 `Error`(与内核 `observerFailed` 那一处同一个口径),拿到事实的人不必
341
+ // 再分「这次是 Error 还是一个字符串」
342
+ this.emit({
343
+ type: "failed",
344
+ mode,
345
+ error: thrown instanceof Error ? thrown : new Error(String(thrown)),
346
+ });
347
+ throw thrown;
348
+ }
349
+ // 成了:这一格只由「闭包正常返回」发 —— 订阅者在报事实那一下抛错,不会被当成这一趟失败
350
+ this.emit({ type: "finished", mode });
351
+ return result;
275
352
  }
276
353
  finally {
277
- this._busy = false;
278
- if (this.abortController === controller)
279
- this.abortController = null;
354
+ this._handingOff = false;
355
+ }
356
+ }
357
+ /** 这一趟用哪个执行者:申请的那个,没申请就是构造时的默认(`runHandoff` 与事实那一侧同一份) */
358
+ modeOf(params) {
359
+ return params.mode ?? this.defaultMode;
360
+ }
361
+ /**
362
+ * 把一格事实交给每一个订阅者(这里唯一的循环):逐个接住,一个订阅者抛错只记一句日志,接着
363
+ * 交给下一个 —— 旁路炸了不打断这一趟交接。
364
+ */
365
+ emit(fact) {
366
+ for (const listener of this.listeners) {
367
+ try {
368
+ listener(fact);
369
+ }
370
+ catch (error) {
371
+ this.logger.warn(`[handoff] a listener of "${fact.type}" threw; ignored`, error);
372
+ }
280
373
  }
281
374
  }
282
375
  /** 取消点检查:每跨过一个阶段就确认一次,避免取消后继续往下一步冲 */
@@ -297,8 +390,8 @@ export class HandoffService {
297
390
  * 取消后清掉半成品文档。
298
391
  *
299
392
  * 只删「本次新建」的文件:交接文件名含时间戳,正常不会撞已有文件,但调用方也
300
- * 可以把 `handoffDir` 指向人工目录;不管怎样都不该删掉别人的文件。
301
- * 留着半成品更糟 —— 下一轮接手方会把不完整的内容当成真实交接读进去。
393
+ * 可以把 `handoffDir` 指向人工目录,那就不能删别人的文件。
394
+ * 留着半成品更糟 —— 下一回接手方会把不完整的内容当成真实交接读进去。
302
395
  */
303
396
  async discardPartialFile(path, existedBefore) {
304
397
  if (existedBefore)
@@ -311,27 +404,29 @@ export class HandoffService {
311
404
  }
312
405
  }
313
406
  /**
314
- * 跑完一次交接("/handoff" 与 "/migrate" 共用),取消时**由本方法统一回退**。
407
+ * 跑完一次交接,取消时**由本方法统一回退**。
315
408
  *
316
409
  * 为什么回退只写在这一处:取消可能从任何一个阶段冒出来(`self` 回合后的主动检查、
317
410
  * `summary` 请求被 abort、前置的 `readSkillContent`),分散到各自的 catch 里就会
318
- * 漏掉「文档已落盘但还没校验通过」这种半成品状态。这里一次拿全三件事:
411
+ * 漏掉「文档已落盘但还没提交」这种半成品状态。这里一次拿全三件事:
319
412
  * 交接前的消息条数、文档路径、以及「文档本就不存在」这个事实。
320
413
  *
321
414
  * 取消形态有两类,都要认:{@link HandoffAbortedError}(主动检查)与底层 abort 错误
322
415
  * (OpenAI 的 `APIUserAbortError`)。调用方只需要认前者。
416
+ *
417
+ * **本方法不开输出闸**:开闸的时刻是「记忆换定了」,而换记忆在宿主那一侧(这一趟只产出
418
+ * 一份文档);SDK 拿到写文档结果时换记忆还没发生,这时候开闸会让这期间落进来的话
419
+ * 落进即将被换掉的旧记忆。开闸由宿主在交接收口做。
323
420
  */
324
- async runHandoff(params, migrating) {
421
+ async runHandoff(params) {
325
422
  const { agent, promptTokens, handoffTokens, signal } = params;
326
- const requestedMode = params.mode ?? this.defaultMode;
423
+ const requestedMode = this.modeOf(params);
327
424
  const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()));
328
425
  const model = this.model ?? agent.model;
329
426
  const messageCountBefore = agent.messages.length;
330
- // 只删「本次新建」的文档:交接文件名含时间戳,正常不会撞已有文件,但调用方也可以
331
- // 把 `handoffDir` 指向人工目录,不管怎样都不该删掉别人的文件
332
427
  const existedBefore = await this.fileExists(handoffPath);
333
428
  try {
334
- // 迁移前上下文(不含文档,语义固定)
429
+ // 交接前上下文(不含文档,语义固定)
335
430
  const beforeCtx = {
336
431
  agent,
337
432
  mode: requestedMode,
@@ -340,34 +435,31 @@ export class HandoffService {
340
435
  model,
341
436
  promptTokens,
342
437
  handoffTokens,
343
- migrating,
344
438
  messageCountBefore,
345
439
  historyText: "",
346
440
  };
347
- await this.safeHook(this.onBeforeHandoff, beforeCtx);
441
+ await this.onBeforeHandoff?.(beforeCtx);
348
442
  this.throwIfAborted(signal);
349
- // ---- 执行者:self 优先,失败/不可用则单向降级 summary ----
350
- let mode = requestedMode;
443
+ // ---- 执行者:申请哪个就跑哪个,做不成 = 失败 ----
444
+ // 这里**不换执行者**:换一个接着做,会让一次失败的交接看起来像成功,而用户以为手里那份
445
+ // 文档是原会话自己写的。做不成就抛,由调用方开闸、退出交接状态、报失败。
446
+ const mode = requestedMode;
351
447
  let handoffDoc;
352
448
  let historyText = "";
353
- if (mode === "self" && !this.supportsSelfHandoff(agent)) {
354
- this.logger.warn("[handoff] agent has no write tool or is not a resident session, falling back to standalone summary mode");
355
- mode = "summary";
356
- }
357
449
  if (mode === "self") {
358
- const ok = await this.runSelfHandoff(agent, handoffPath, signal);
359
- if (!ok) {
360
- this.logger.warn("[handoff] self handoff failed, falling back to standalone summary mode");
361
- mode = "summary";
362
- }
450
+ this.assertSelfHandoffAvailable(agent);
451
+ await this.runSelfHandoff(agent, handoffPath, signal);
363
452
  }
364
453
  if (mode === "summary") {
454
+ // 这一档没有「那一批」(不投指令、不进队列),所以没人替它关闸 —— 生成摘要之前自己关
455
+ if (!agent.isOutputPaused)
456
+ agent.pauseOutput();
365
457
  historyText = HandoffService.serializeMessages(agent.messages.filter((m) => !m.omit));
366
458
  handoffDoc = await this.generateSummary(agent, historyText, handoffPath, signal);
367
459
  await this.writeHandoffFile(handoffPath, handoffDoc);
368
460
  }
369
461
  // 最后一道取消点:即使两步都跑完,只要期间被取消就不能算成功。跨过这一步就是
370
- // 「已提交」——之后的 `onHandoff` 钩子(存旧会话等)与迁移收尾不再响应取消
462
+ // 「已提交」——之后的 `onHandoff` 钩子(宿主在那一拍换记忆)不再响应取消
371
463
  this.throwIfAborted(signal);
372
464
  const ctx = {
373
465
  agent,
@@ -378,16 +470,17 @@ export class HandoffService {
378
470
  model,
379
471
  promptTokens,
380
472
  handoffTokens,
381
- migrating,
382
473
  messageCountBefore,
383
474
  historyText,
384
475
  };
385
- await this.safeHook(this.onHandoff, ctx);
476
+ await this.onHandoff?.(ctx);
386
477
  return ctx;
387
478
  }
388
479
  catch (err) {
389
- if (!(err instanceof HandoffAbortedError) && !isAbortError(err, signal))
480
+ if (!(err instanceof HandoffAbortedError) && !isAbortError(err, signal)) {
390
481
  throw err;
482
+ }
483
+ // 取消:交接回合截掉、半成品文档删掉(闸不在这里开,见方法注释)
391
484
  await this.restoreBeforeHandoff({ agent, messageCountBefore, handoffPath, existedBefore });
392
485
  throw new HandoffAbortedError();
393
486
  }
@@ -396,7 +489,7 @@ export class HandoffService {
396
489
  * 取消后回到交接前的状态:把交接回合追加的消息全部截掉,并删掉本次新建的文档。
397
490
  *
398
491
  * 为什么必须截消息:`self` 模式的交接回合是「一条几 KB 的 Skill 指令 user 消息 +
399
- * 工具结果 + 回执」,留在 `agent.messages` 里既让用户看到半段无关对话,也让下一次
492
+ * 工具结果 + 回执」,留在 `agent.messages` 里既让用户看到半段无关会话,也让下一次
400
493
  * 请求把它当历史再发一遍(`↑` 翻历史还会把它翻出来)。`agent.messages` 是唯一真相源,
401
494
  * 截回原长度之后,转录、历史、用量全都自动复位,不需要第二处补偿。
402
495
  */
@@ -407,153 +500,188 @@ export class HandoffService {
407
500
  await this.discardPartialFile(handoffPath, existedBefore);
408
501
  }
409
502
  /**
410
- * 自交接是否可用:需要 `write` 工具,且 agent 是**常驻**的。
503
+ * 申请的 `self` 这一趟**能不能做**:需要 `write` 工具(名字只由 {@link WRITE_TOOL_NAME}
504
+ * 命名一次),且 agent 是**常驻**的。做不到就抛,**不换成摘要** ——
505
+ * 两种原因分开报,因为人能做的事不同(给这段会话配一个写工具 / 换一段常驻会话),
506
+ * 而失败通知里只有这一句话可读。
411
507
  *
412
- * 为什么要看 `lifetime`:自交接靠「往同一个会话里投一轮指令」实现,而一次性 agent
508
+ * 为什么要看 `lifetime`:自交接靠「往同一个会话里投一条指令」实现,而一次性 agent
413
509
  * 开跑即关收(第二次 `push` 抛 `closed`),且跑完就死透(`CORE.md` §1)—— 它根本没
414
- * 有「再问一轮」这种能力。
510
+ * 有「再问一次」这种能力。
415
511
  */
416
- supportsSelfHandoff(agent) {
417
- if (agent.lifetime === "one-shot")
418
- return false;
419
- return Boolean(agent.tools?.some((tool) => tool.function?.name === "write"));
512
+ assertSelfHandoffAvailable(agent) {
513
+ if (!agent.tools?.some((tool) => tool.function?.name === WRITE_TOOL_NAME)) {
514
+ throw new Error("Cannot write the handoff document with this session: the agent has no write tool, so it has no way to put the document on disk. No other writer was swapped in — request the standalone summary explicitly if that is what you want.");
515
+ }
516
+ if (agent.lifetime === "one-shot") {
517
+ throw new Error("Cannot write the handoff document with this session: it is a one-shot session, and a one-shot session closes as soon as it starts, so it cannot be asked to write again after it stops. No other writer was swapped in — request the standalone summary explicitly if that is what you want.");
518
+ }
420
519
  }
421
520
  /**
422
- * 自交接回合:让原 agent 停工、核实、写文档,并校验文件确实落盘。
521
+ * 自交接:让原 agent 停下手里的活,把文档写到那个路径上。
522
+ *
523
+ * ## 判据是那次写文档的工具调用
524
+ *
525
+ * 指令投进去之后只等两个事实,两个都来自 core 的钩子({@link HandoffGuardPlugin}):
526
+ * - 「工具名 `write` + 路径等于交接路径」的那次调用回来了 → 写完了(`onToolEnd`);
527
+ * - 那一批收口了还没见到它 → 没写出来(`onOuterLoopEnd`)。
528
+ *
529
+ * 不看状态、不等 `idle`、不设计时器:模型可以只回一句「写好了」而一个字没写,那种情形下它
530
+ * 连工具都没调,「这一批收口」这一拍就是结论,不必等谁到点。
531
+ *
532
+ * ## 门与判据挂在同一处
533
+ *
534
+ * `arm()` 之后守卫既当门、又把上面那两个事实报回来(细节见 {@link HandoffGuardPlugin}):
535
+ * 「只许写这份文档」与「写完了没有」看的是同一份输入 —— 工具参数里的路径。
536
+ *
537
+ * **只投一次**:没写出来就是没写出来,不「再问一次」。第二次投递要能跑就得先把闸开开,
538
+ * 一开闸,这期间用户压着的件就跟着那一批一起被取走,而那一趟仍然要换记忆 —— 同一个误伤。
423
539
  *
424
- * 失败判定(任一成立即视为失败,交由上层单向降级 summary):
425
- * - 文件不存在 / 小于阈值;
426
- * - 模型/工具链抛错(例如没有权限、被护栏拒绝);
427
- * - 这一轮压根没跑完(agent 被 `abort()` 暂停、或已经被关门/硬杀)。
540
+ * ## 判据只有一条:文档写出来了没有
428
541
  *
429
- * **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
430
- * 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:`agent.abort()` 不抛错
431
- * (core 把在途请求掉、消息标记成 Aborted 然后正常返回),否则「用户按了 Ctrl+C」会被
432
- * 下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级一轮 —— 用户以为取消了,
433
- * 实际多烧了两轮全量输入。
542
+ * 这一次交接成不成,只看那一批里有没有出现那次写:出现了就是成了(文档在盘上),没出现就是
543
+ * 没成。这一回合里报过的错(端点 4xx、超时、core 内部错、插件抛错)**只是「为什么没写出来」
544
+ * 的解释**,不是判据本身 —— 模型先撞一次错、缓过来照样把文档写成的,是一次**成功的**交接,
545
+ * 不该被那个错反过来判死。
434
546
  *
435
- * 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
436
- * 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
547
+ * 于是四种情形,各自的报法:
548
+ *
549
+ * - **写出来了**:`failures` 不再看。文档已经落盘,之后再冒的错与这一次交接无关;
550
+ * - **这个会话已经没了**(`gone`):抛「会话已不存在」—— 先于「写没写过」,没有可写的东西,
551
+ * 也别为一个死掉的会话白烧一次全量输入;
552
+ * - **没写出来,且这一回合报过错**:那个错就是真因,**原样抛给调用方**;
553
+ * - **没写出来,且一个错都没报**(齐根没调写工具 / 只说了句「写好了」):抛「没写出可用的
554
+ * 文档」,这一趟到此为止。
555
+ *
556
+ * 这一趟答 `void` 或抛 —— **没有「成了没有」这个布尔值**:`false` 从前只有一个意思(交上层去
557
+ * 降级),而看不懂原因的失败等于没说;换个执行者接着做则是另一件更坏的事(见 {@link runHandoff})。
558
+ *
559
+ * 「这一回合报过错」这个事实 core 不从 `start()` 往外招(`Agent.start()` 的注释:一次请求挂了
560
+ * 就是一次挂了,循环接着等下一个事件),它报成 `failed` 事件 —— 所以这一回合期间订阅它一次,
561
+ * 只为了在「没写出来」时答得出为什么。
562
+ *
563
+ * **取消不算失败**:用户按了中断就抛 {@link HandoffAbortedError},既不重试也不降级。取消的
564
+ * 善后(删文档、截消息)不在这里做 —— 交给 {@link runHandoff} 的 catch 一处处理。
437
565
  */
438
566
  async runSelfHandoff(agent, handoffPath, signal) {
567
+ // 已经不收件了(用户让它停):此刻投进去只会排在队里,等放行之后突然自己跑起来 —— 这一趟没
568
+ // 跑成。报的是「会话不收件」而不是笼统的一句失败:那一种处置是「让用户放开闸再试」,而
569
+ // 「会话已不存在」那一种是「这段会话得重开」
570
+ if (agent.isOutputPaused) {
571
+ throw new Error("Cannot write the handoff document with this session: it is not taking new work right now (its output is paused), so an instruction pushed into it would only queue up and start by itself after the resume. No other writer was swapped in.");
572
+ }
439
573
  const guard = this.ensureGuard(agent);
440
574
  const skillContent = await this.readSkillContent();
441
575
  const cwd = agent.scope?.cwd ?? process.cwd();
442
576
  /*
443
- * 交接回合的护栏让行由 `ContextGuardPlugin.isSuspended` 负责(接线为
444
- * `() => handoffService.busy`),这里不再去改写用量数据:
445
- * - `lastUsage` 是从 `messages` 派生的只读值,本就不可写;
446
- * - 「谁做限制谁放宽」—— 限制在护栏自己身上,放宽也必须写在护栏的选项里。
577
+ * 这一回合里 core 报过的错(端点 4xx / 超时 / core 内部错 / 插件抛错)。
578
+ * 只在这个窗口里听:订阅与 `guard.arm()` 同一拍开,`finally` 里一定撕。
579
+ */
580
+ const failures = [];
581
+ const stopWatchingFailures = agent.on("failed", ({ error }) => {
582
+ failures.push(error instanceof Error ? error : new Error(String(error)));
583
+ });
584
+ /*
585
+ * 硬线(`ContextGuardPlugin`)在交接回合**也照拦**,不放宽:交接那一次请求不让路
586
+ * (`dev-docs/prd/05-control.md`「两条线的口径」),要避免撞线就把阈值配得够宽。
587
+ * 这里因此不去改写用量数据,也没有任何「让行」要接。
447
588
  */
448
- guard.arm(handoffPath, cwd);
449
589
  try {
450
- const first = await this.pushInstructionRound(agent, HandoffService.createHandoffInstruction({
590
+ const instruction = HandoffService.createHandoffInstruction({
451
591
  skillContent,
452
592
  handoffPath,
453
593
  toolsAvailable: true,
454
- }), signal);
455
- // `agent.abort()` 不抛错,必须主动检查(见方法注释)
594
+ });
595
+ const watch = guard.arm(handoffPath, cwd);
596
+ const outcome = await this.pushAndWatch(agent, watch, instruction, signal);
597
+ // `agent.abort()` 不抛错,取消要主动看一眼(见方法注释)
456
598
  this.throwIfAborted(signal);
457
- // 这一轮没跑完(暂停 / 关门 / 硬杀):产物没意义,也别再往里投 ——
458
- // 暂停中不取件,再投只会把一条陈旧指令留在队列里,等 resume 之后突然自己跑起来
459
- if (first !== "idle")
460
- return false;
461
- if (await this.isHandoffFileReady(handoffPath))
462
- return true;
463
- this.logger.warn(`[handoff] handoff document missing or too small, retrying once: ${handoffPath}`);
464
- const second = await this.pushInstructionRound(agent, [
465
- `The handoff document does not exist or is too small to deliver: ${handoffPath}`,
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.",
467
- ].join("\n"), signal);
468
- this.throwIfAborted(signal);
469
- if (second !== "idle")
470
- return false;
471
- return await this.isHandoffFileReady(handoffPath);
599
+ // 那一下被掐(用户把它叫停了):回到交接前,不重试
600
+ if (outcome === "interrupted")
601
+ throw new HandoffAbortedError();
602
+ // 这个会话已经不在了:没有可写的东西,也别为一个死掉的会话白烧一次全量输入。
603
+ // 与「没写出文档」分开报:那一种是模型没写成(还能再试)、这一段会话照旧能用;
604
+ // 这一种是会话本身没了,得像开一段新会话那样处置
605
+ if (outcome === "gone") {
606
+ throw new Error("Cannot write the handoff document with this session: the session no longer exists (it was stopped or killed during the round), so there is nothing left to write with. No other writer was swapped in.");
607
+ }
608
+ // 写出来了:这一次交接已经成,`failures` 从此不再看(文档在盘上,之后冒的错与它无关)
609
+ if (outcome === "written") {
610
+ // 等这一批收口:此后这个会话的消息不再增长,要换掉的就是定了的这一份
611
+ await this.waitRoundOver(watch, signal);
612
+ // 写出来了没有:文件在不在、够不够长(默认 400 字节,`PRD.md` 3.6)。
613
+ // 这一格与断点消息的形状同在 SDK 一处算 —— 宿主不再自己量一遍(`PRD.md` 4.5)。
614
+ if (await this.isHandoffFileReady(handoffPath))
615
+ return;
616
+ }
617
+ // 没写出可用的文档(齐根没调写工具 / 只说了句「写好了」/ 写出来不到阈值):这一趟里报过的
618
+ // 那个错就是真因,原样交上去
619
+ if (failures.length > 0)
620
+ throw failures[0];
621
+ // 一个错都没报:交接没写出可用的文档。不换成摘要 —— 那会让一次失败的交接看起来像成功
622
+ throw new Error(`Cannot write the handoff document with this session: the round produced no usable handoff document (the write tool was never called on the handoff path, or the file is missing or smaller than ${this.minHandoffBytes} bytes). No other writer was swapped in.`);
472
623
  }
473
624
  catch (err) {
474
- // agent 已经关门:不是「文档没写出来」,是「这个会话已经不在了」。降级 summary 会
475
- // 为一个死掉的会话白烧一轮全量输入,所以直接把 `closed` 往上交(调用方该知道这件事)
625
+ // 取消不是失败:它要一路走到 {@link runHandoff} 的收尾那里(删半成品、截消息)
626
+ if (err instanceof HandoffAbortedError)
627
+ throw err;
628
+ // agent 已经关门:不是「文档没写出来」,是「这个会话已经不在了」。换一个执行者接着做只会
629
+ // 为一个死掉的会话白烧一次全量输入,所以直接把 `closed` 往上交(调用方该知道这件事)
476
630
  if (err instanceof AgentError && err.code === "closed")
477
631
  throw err;
478
632
  if (isAbortError(err, signal))
479
633
  throw new HandoffAbortedError();
480
- this.logger.error(`[handoff] self handoff round failed: ${err?.message ?? err}`);
481
- return false;
634
+ // 其余一切都不是「模型没写出来」:原样抛给调用方,由它报失败(宿主 `onFailed`)
635
+ // 并把输出闸开回来。
636
+ throw err;
482
637
  }
483
638
  finally {
639
+ stopWatchingFailures();
484
640
  guard.disarm();
485
641
  }
486
642
  }
487
643
  /**
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
- * ## 返回「这一轮怎么结束的」而不是「成没成」
644
+ * 把一条指令投进它的队列,然后等这一趟的结论。
504
645
  *
505
- * 三种结束方式对调用方意义不同(`idle` 才能去校验产物),所以分开报:
506
- * - `idle`:跑完了;
507
- * - `paused`:被 `abort()` 暂停/掉;
508
- * - `dead`:关门/硬杀,循环已经结束。
509
- *
510
- * 第四种情况不在这里表达:`push` 在关门之后会直接抛 `AgentError("closed")` —— 那是
511
- * 「调用方违约」(往一个已经没有的会话里塞东西),就该往上抛,不该被归成一种“结束方式”。
646
+ * core 只有投递(`CORE.md` §1:常驻会话只 `push`,不看返回值),所以这里投完就等钩子报回来的
647
+ * 事实,不去问状态。关门之后 `push` 抛 `AgentError("closed")` —— 那是调用方违约,不接,
648
+ * 让它一路走到 {@link runSelfHandoff} 的 catch(那里原样再往上交)。
512
649
  */
513
- async pushInstructionRound(agent, content, signal) {
514
- // 暂停中不取件:此刻投进去只会排在队列里,等 resume 后突然自己跑起来
515
- if (agent.state === "paused")
516
- return "paused";
650
+ async pushAndWatch(agent, watch, content, signal) {
517
651
  // 叫起来(幂等;不 await —— 那句 promise 到死才 resolve)
518
652
  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
653
  agent.push({
548
654
  content,
549
655
  priority: "low",
550
656
  // 这条指令是**宿主侧**(`/handoff` 命令、自动迁移)注入的,不是用户说的话 ——
551
657
  // 按「谁注入谁填」给它一个 system 来源(`CORE.md` §3)
552
- source: { kind: "system", label: "handoff" },
658
+ source: { kind: "system", label: HANDOFF_SOURCE_LABEL },
553
659
  });
554
- // 关门之后投递会抛 `AgentError("closed")`(`CORE.md` §1):不接、不归类,
555
- // 让它往上走到 {@link runSelfHandoff} 的 catch(那里把 closed 原样再往上交)
556
- return await ended;
660
+ return await this.waitOutcome(watch, signal);
661
+ }
662
+ /** 等这一趟的结论;取消信号响了就按「被掐」处置(结论不会比这个更早) */
663
+ async waitOutcome(watch, signal) {
664
+ if (signal?.aborted)
665
+ return "interrupted";
666
+ const { raced, stop } = abortRace(signal, "interrupted");
667
+ try {
668
+ return await Promise.race([watch.outcome, raced]);
669
+ }
670
+ finally {
671
+ stop();
672
+ }
673
+ }
674
+ /** 等这一批收口;取消信号响了也放行(收尾统一在 {@link runHandoff} 那一处做) */
675
+ async waitRoundOver(watch, signal) {
676
+ if (signal?.aborted)
677
+ return;
678
+ const { raced, stop } = abortRace(signal, undefined);
679
+ try {
680
+ await Promise.race([watch.over, raced]);
681
+ }
682
+ finally {
683
+ stop();
684
+ }
557
685
  }
558
686
  /** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
559
687
  async generateSummary(agent, historyText, handoffPath, signal) {
@@ -563,8 +691,7 @@ export class HandoffService {
563
691
  const skillContent = await this.readSkillContent();
564
692
  this.throwIfAborted(signal);
565
693
  // 请求体形状(system + user、modelConfig 展开、signal 走 RequestOptions)的唯一实现在
566
- // `completeOnce`:会话自动标题那一类「辅助小请求」走同一条路,两边不会一份带 stream、
567
- // 另一份不带
694
+ // `completeOnce`(会话自动标题那一类小请求也走它)
568
695
  const handoffDoc = await completeOnce({
569
696
  client,
570
697
  model,
@@ -587,7 +714,13 @@ export class HandoffService {
587
714
  await fs.mkdir(dirname(handoffPath), { recursive: true });
588
715
  await fs.writeFile(handoffPath, content, "utf-8");
589
716
  }
590
- /** 交接文档是否可用:文件存在且不小于阈值(不读内容,避免二次读取) */ async isHandoffFileReady(handoffPath) {
717
+ /**
718
+ * 交接文档写出来了没有:文件在、且不小于 {@link HandoffServiceOptions.minHandoffBytes}。
719
+ *
720
+ * 只看 `stat`,不读内容 —— 「够不够长」不需要读懂它写了什么。写了一半、模型只回了一句
721
+ * 「写好了」而一个字没写,都在这一格里落定。
722
+ */
723
+ async isHandoffFileReady(handoffPath) {
591
724
  try {
592
725
  const stat = await fs.stat(handoffPath);
593
726
  return stat.isFile() && stat.size >= this.minHandoffBytes;
@@ -615,15 +748,4 @@ export class HandoffService {
615
748
  }
616
749
  return guard;
617
750
  }
618
- /** 钩子容错:抛错只记录,不中断交接(与既有迁移钩子语义一致) */
619
- async safeHook(hook, ctx) {
620
- if (!hook)
621
- return;
622
- try {
623
- await hook(ctx);
624
- }
625
- catch (err) {
626
- this.logger.error(`[handoff] hook execution failed: ${err?.message ?? err}`);
627
- }
628
- }
629
751
  }