pi-web-ui 0.118.0 → 0.120.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 (195) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -3,8 +3,16 @@ import { Type } from "typebox";
3
3
  import { pick } from "./i18n.js";
4
4
  import { resolveSecurityMode } from "./subagent-security-gate.js";
5
5
  import { THINKING_LEVELS } from "./subagent-templates.js";
6
- import { CONVERSATION_TOOL_NAME, SUBAGENT_TOOL_NAME } from "./tool-manager.js";
7
- export { CONVERSATION_TOOL_NAME, SUBAGENT_TOOL_NAME } from "./tool-manager.js";
6
+ import { evidenceVerdictLabel, formatEvidenceSummary, normalizeEvidenceInput, } from "./subagent-evidence.js";
7
+ import { CONVERSATION_TOOL_NAME } from "./tool-manager.js";
8
+ import { richQuestionsSchema } from "./question-params.js";
9
+ import { questionsFromMessage } from "./conversation-communication.js";
10
+ import { Value } from "typebox/value";
11
+ export { CONVERSATION_TOOL_NAME } from "./tool-manager.js";
12
+ /** 单次派发的扇出上限:超过就分多次调用,避免一次调用把并发预算挤爆。 */
13
+ export const SUBAGENT_FANOUT_MAX = 16;
14
+ /** 运行键长度与形状:模型给的短名,映射到真实运行身份。 */
15
+ export const SUBAGENT_KEY_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,39}$/;
8
16
  export function computeWaitCapMs(watchdogMs) {
9
17
  const customSecs = Number(process.env.PI_WEB_SUBAGENT_WAIT_CAP_SECONDS);
10
18
  if (Number.isFinite(customSecs) && customSecs > 0) {
@@ -69,7 +77,13 @@ export const SUBAGENT_ACTIONS = [
69
77
  "consult",
70
78
  "answer",
71
79
  "escalate",
80
+ "resume",
72
81
  ];
82
+ /** Compact action signature: the single place documenting parameters, so field schemas stay prose-free. */
83
+ export const MANAGEMENT_ACTION_SIGNATURE = "spawn(prompt,type?,key? | tasks[{key,prompt,type?,template?,model?,thinking?,isolation?,persist?,notifyOnDone?}]) | " +
84
+ "steer/answer(runId,message,requestId?) | complete(summary,evidence{files[],commands[],none?,blocked?}) | consult(message) | " +
85
+ "escalate(runId,requestId) | get_result/stop/resume(runId,message?) | wait_all/dismiss(runIds? keys accepted) | " +
86
+ "handoff(toRunId,payload) | list(kind?) | templates";
73
87
  export function makeSubagentTool(host, lang, selfConvId) {
74
88
  const selfIdOf = () => (typeof selfConvId === "function" ? selfConvId() : selfConvId);
75
89
  const executionOf = (snapshot) => snapshot.executionId ?? snapshot.convId;
@@ -82,6 +96,133 @@ export function makeSubagentTool(host, lang, selfConvId) {
82
96
  });
83
97
  const deliveredConsults = new Set();
84
98
  const consultKey = (parentId, runId, requestId) => JSON.stringify([parentId, runId, requestId]);
99
+ // 扇出键表:模型给短 key,工具映射成稳定运行身份(有界,旧的先丢)。
100
+ const RUN_KEY_CAP = 256;
101
+ const runKeys = new Map();
102
+ const rememberRunKey = (key, convId) => {
103
+ if (!key)
104
+ return;
105
+ runKeys.delete(key);
106
+ runKeys.set(key, convId);
107
+ while (runKeys.size > RUN_KEY_CAP) {
108
+ const oldest = runKeys.keys().next().value;
109
+ if (oldest === undefined)
110
+ break;
111
+ runKeys.delete(oldest);
112
+ }
113
+ };
114
+ /** `key` 与真实 id 都接受:命中键表就换成运行身份,否则原样返回。 */
115
+ const resolveRunRef = (ref) => runKeys.get(ref.trim()) ?? ref;
116
+ const normalizeSpawnRequest = (request, ordinal) => {
117
+ const lang = getLang();
118
+ const zh = lang === "zh";
119
+ const rawKey = typeof request.key === "string" ? request.key.trim() : "";
120
+ const label = rawKey ? `[${rawKey}]` : zh ? `[第 ${ordinal} 项]` : `[task ${ordinal}]`;
121
+ const prompt = typeof request.prompt === "string" ? request.prompt : "";
122
+ if (!prompt.trim()) {
123
+ return {
124
+ error: pick(lang, `${label} 缺少 prompt。`, `${label} is missing a prompt.`, "subagents.spawn.task.missing.prompt", { label }),
125
+ };
126
+ }
127
+ if (rawKey && !SUBAGENT_KEY_PATTERN.test(rawKey)) {
128
+ return {
129
+ error: pick(lang, `${label} 的 key 不合法:只用字母/数字/下划线/点/横线,最长 40 字符。`, `${label} has an invalid key: use letters/digits/\`_.-\`, max 40 chars.`, "subagents.spawn.task.bad.key", { label }),
130
+ };
131
+ }
132
+ const type = typeof request.type === "string" && request.type.trim() ? request.type.trim() : "general";
133
+ const requestedTemplate = typeof request.template === "string" && request.template.trim() ? request.template.trim() : undefined;
134
+ let templateName;
135
+ if (requestedTemplate) {
136
+ if (!host.isTemplateUsable(requestedTemplate)) {
137
+ return {
138
+ error: pick(lang, `${label} 的子代理模板不可用:${requestedTemplate}(不存在或已停用)。用 conversation(action="templates") 看清单。`, `${label} requests an unavailable template: ${requestedTemplate} (missing or disabled). Use conversation(action="templates") to list them.`, "subagents.spawn.template.unavailable", { label, "p.template": requestedTemplate }),
139
+ };
140
+ }
141
+ templateName = requestedTemplate;
142
+ }
143
+ else if (host.isTemplateUsable(type)) {
144
+ templateName = type;
145
+ }
146
+ const thinking = typeof request.thinking === "string" && request.thinking.trim() ? request.thinking.trim() : undefined;
147
+ if (thinking && !THINKING_LEVELS.includes(thinking)) {
148
+ return {
149
+ error: pick(lang, `${label} 非法思考强度:${thinking}。可选档位:${THINKING_LEVELS.join(", ")}。`, `${label} has an invalid thinking level: ${thinking}. Allowed levels: ${THINKING_LEVELS.join(", ")}.`, "subagents.spawn.thinking.invalid", { label, thinking, levels: THINKING_LEVELS.join(", ") }),
150
+ };
151
+ }
152
+ const rawIsolation = typeof request.isolation === "string" ? request.isolation.trim().toLowerCase() : "";
153
+ if (rawIsolation && rawIsolation !== "worktree" && rawIsolation !== "none") {
154
+ return {
155
+ error: pick(lang, `${label} 不支持的隔离模式:${rawIsolation}(可选 worktree / none)。`, `${label} uses an unsupported isolation mode: ${rawIsolation} (worktree / none).`, "subagents.spawn.isolation.invalid", { label, isolation: rawIsolation }),
156
+ };
157
+ }
158
+ const model = typeof request.model === "string" && request.model.trim() ? request.model.trim() : undefined;
159
+ // schema 里不再给 notifyOnDone 写 enum(联合类型 + enum 会被 Moonshot 等供应商判成非法 schema,
160
+ // 整轮请求 400),约束落到这里:只有 false / "manual" 有意义,其余一律按默认(通知)处理。
161
+ const rawNotify = request.notifyOnDone;
162
+ const notifyOnDone = typeof rawNotify === "boolean" ? rawNotify : rawNotify === "manual" ? "manual" : undefined;
163
+ return {
164
+ spec: {
165
+ key: rawKey || undefined,
166
+ prompt,
167
+ type,
168
+ templateName,
169
+ model,
170
+ thinking,
171
+ isolationMode: rawIsolation === "worktree" || rawIsolation === "none" ? rawIsolation : undefined,
172
+ persist: request.persist,
173
+ notifyOnDone,
174
+ },
175
+ };
176
+ };
177
+ /** 单次启动:校验完的 spec → 真实子代理。错误以结果返回,不抛(扇出时其它项照常跑)。 */
178
+ const spawnSpec = async (spec, cwd, signal) => {
179
+ const matchedTemplate = spec.templateName
180
+ ? host.listTemplates().find((t) => t.name === spec.templateName)
181
+ : undefined;
182
+ const securityMode = resolveSecurityMode(spec.type, matchedTemplate);
183
+ const extra = securityMode !== "normal" ? { securityMode } : undefined;
184
+ const spawnArgs = [
185
+ spec.prompt,
186
+ spec.type,
187
+ cwd,
188
+ spec.templateName,
189
+ spec.model,
190
+ undefined,
191
+ spec.persist,
192
+ spec.thinking,
193
+ spec.notifyOnDone,
194
+ ];
195
+ if (spec.isolationMode === "worktree" || extra !== undefined || signal !== undefined) {
196
+ spawnArgs.push(spec.isolationMode === "worktree" ? "worktree" : undefined);
197
+ }
198
+ if (extra !== undefined || signal !== undefined)
199
+ spawnArgs.push(extra);
200
+ if (signal !== undefined)
201
+ spawnArgs.push(signal);
202
+ try {
203
+ signal?.throwIfAborted();
204
+ const convId = await host.spawnSubagent(...spawnArgs);
205
+ rememberRunKey(spec.key, convId);
206
+ return { ok: true, convId, executionId: host.getSubagent(convId)?.executionId };
207
+ }
208
+ catch (err) {
209
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
210
+ }
211
+ };
212
+ /** 扇出时的有限并发:避免与并发上限抢名额,又不至于串行等每个子代理初始化完。 */
213
+ const SPAWN_FANOUT_CONCURRENCY = 4;
214
+ const mapLimited = async (items, limit, fn) => {
215
+ const out = new Array(items.length);
216
+ let cursor = 0;
217
+ const worker = async () => {
218
+ while (cursor < items.length) {
219
+ const index = cursor++;
220
+ out[index] = await fn(items[index]);
221
+ }
222
+ };
223
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
224
+ return out;
225
+ };
85
226
  const expandDescendants = (roots) => {
86
227
  if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
87
228
  return [];
@@ -143,123 +284,63 @@ export function makeSubagentTool(host, lang, selfConvId) {
143
284
  const currentWaitCapMs = typeof host.getWatchdogTimeoutMs === "function"
144
285
  ? computeWaitCapMs(host.getWatchdogTimeoutMs())
145
286
  : computeWaitCapMs();
146
- const capSeconds = Math.floor(currentWaitCapMs / 1000);
147
287
  return defineTool({
148
288
  name: CONVERSATION_TOOL_NAME,
149
289
  label: "Conversation collaboration",
150
- description: "Create and manage collaborative conversations, including temporary subagents and persistent sessions, for delegation, research, and execution. " +
151
- "Each action's arguments are documented on the parameters below.",
290
+ description: "Create and manage collaborative conversations, including temporary subagents and persistent sessions, for delegation, research, and execution.",
152
291
  promptSnippet: "Delegate tasks, inspect results, or request task completion.",
153
- promptGuidelines: [
154
- "Prefer communicate for messages and questions; consult/answer/escalate/handoff remain compatible.",
155
- ],
292
+ promptGuidelines: ["Prefer communicate; consult/answer/escalate/handoff stay supported as legacy routes."],
156
293
  parameters: Type.Object({
157
294
  action: Type.Unsafe({
158
295
  type: "string",
159
296
  enum: [...SUBAGENT_ACTIONS],
160
- description: "The subagent action to perform.",
297
+ description: MANAGEMENT_ACTION_SIGNATURE,
161
298
  }),
162
- questions: Type.Optional(Type.Array(Type.Object({
163
- id: Type.String({ minLength: 1 }),
164
- question: Type.String({ minLength: 1 }),
165
- detail: Type.Optional(Type.String()),
166
- header: Type.Optional(Type.String()),
167
- options: Type.Optional(Type.Array(Type.Object({
168
- label: Type.String(),
169
- description: Type.Optional(Type.String()),
170
- preview: Type.Optional(Type.String()),
171
- recommended: Type.Optional(Type.Boolean()),
172
- }))),
173
- multiSelect: Type.Optional(Type.Boolean()),
174
- dependsOn: Type.Optional(Type.Object({
175
- questionId: Type.String(),
176
- value: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
177
- })),
178
- optionsMap: Type.Optional(Type.Record(Type.String(), Type.Array(Type.Object({
179
- label: Type.String(),
180
- description: Type.Optional(Type.String()),
181
- preview: Type.Optional(Type.String()),
182
- recommended: Type.Optional(Type.Boolean()),
183
- })))),
184
- }), { description: "consult: ask the parent for a decision.", minItems: 1, maxItems: 3 })),
185
- requestId: Type.Optional(Type.String({ description: "answer/escalate: pending consult request ID." })),
186
- answers: Type.Optional(Type.Array(Type.Object({
187
- id: Type.String(),
188
- selected: Type.Array(Type.String()),
189
- custom: Type.Optional(Type.String()),
190
- }), { description: "answer: responses to the child's consult.", minItems: 1 })),
191
- prompt: Type.Optional(Type.String({
192
- description: "spawn: instructions (goal, constraints, expected output).",
193
- })),
194
- runId: Type.Optional(Type.String({
195
- description: "get_result/steer/stop/dismiss/answer/escalate: target conversation ID.",
196
- })),
197
- runIds: Type.Optional(Type.Array(Type.String(), {
198
- description: "wait_all/dismiss: conversation IDs to wait for or dismiss.",
199
- })),
200
- message: Type.Optional(Type.String({
201
- description: "steer: follow-up instruction; complete: completion summary alias.",
202
- })),
203
- summary: Type.Optional(Type.String({ description: "complete: final task summary." })),
204
- payload: Type.Optional(Type.String({
205
- description: "handoff: what to transfer to the peer.",
206
- })),
207
- toRunId: Type.Optional(Type.String({
208
- description: "handoff: target peer ID.",
209
- })),
210
- fromRunId: Type.Optional(Type.String({
211
- description: "handoff: optional source ID; must match the calling conversation.",
212
- })),
213
- type: Type.Optional(Type.String({
214
- description: "spawn: role/type (e.g. explore/implement/review, default: general). When matching a template name, the template and its security profile (e.g. readonly for explore, verify for review) are automatically applied.",
215
- })),
216
- template: Type.Optional(Type.String({
217
- description: "spawn: template name (see action=templates).",
218
- })),
219
- model: Type.Optional(Type.String({
220
- description: 'spawn: model override "provider/id".',
221
- })),
222
- thinking: Type.Optional(Type.String({
223
- enum: [...THINKING_LEVELS],
224
- description: 'spawn: thinking budget level ("off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max").',
225
- })),
226
- notifyOnDone: Type.Optional(Type.Union([Type.Boolean(), Type.Literal("manual")], {
227
- description: "spawn: true wakes parent per turn, false disables wakes, manual waits for task completion (default: true).",
228
- })),
229
- cwd: Type.Optional(Type.String({
230
- description: "spawn: working directory (default = current).",
231
- })),
232
- persist: Type.Optional(Type.Boolean({
233
- description: "spawn: persist as a regular session (default = ephemeral).",
234
- })),
235
- isolation: Type.Optional(Type.String({
236
- enum: ["worktree", "none"],
237
- description: 'spawn: workspace isolation mode ("worktree" creates a dedicated git worktree & branch; "none" = shared cwd).',
238
- })),
239
- kind: Type.Optional(Type.String({
240
- enum: ["all", "subagent", "persistent"],
241
- description: "list: filter subagents by kind (default: all).",
242
- })),
243
- timeoutSeconds: Type.Optional(Type.Integer({
244
- description: `wait_all: max wait in seconds (default: ${capSeconds}s); returns early for new parent consults.`,
245
- minimum: 1,
246
- maximum: capSeconds,
247
- })),
248
- scope: Type.Optional(Type.String({
249
- enum: ["finished_all"],
250
- description: 'dismiss: batch dismissal scope ("finished_all" to dismiss all finished descendant subagents).',
251
- })),
252
- force: Type.Optional(Type.Boolean({
253
- description: "dismiss: force abort running subagents before dismissing (default: false).",
254
- })),
255
- includePersisted: Type.Optional(Type.Boolean({
256
- description: "dismiss: allow dismissing persisted subagents (default: false).",
299
+ prompt: Type.Optional(Type.String()),
300
+ key: Type.Optional(Type.String()),
301
+ tasks: Type.Optional(Type.Array(Type.Object({
302
+ key: Type.Optional(Type.String()),
303
+ prompt: Type.Optional(Type.String()),
304
+ type: Type.Optional(Type.String()),
305
+ template: Type.Optional(Type.String()),
306
+ model: Type.Optional(Type.String()),
307
+ thinking: Type.Optional(Type.String({ enum: [...THINKING_LEVELS] })),
308
+ isolation: Type.Optional(Type.String({ enum: ["worktree", "none"] })),
309
+ persist: Type.Optional(Type.Boolean()),
310
+ notifyOnDone: Type.Optional(Type.Unsafe({ type: ["boolean", "string"] })),
311
+ }))),
312
+ message: Type.Optional(Type.String({ description: "Steer instruction, consult question, or answer text." })),
313
+ summary: Type.Optional(Type.String()),
314
+ evidence: Type.Optional(Type.Object({
315
+ files: Type.Optional(Type.Array(Type.String())),
316
+ commands: Type.Optional(Type.Array(Type.String())),
317
+ none: Type.Optional(Type.Boolean()),
318
+ blocked: Type.Optional(Type.String()),
257
319
  })),
320
+ payload: Type.Optional(Type.String()),
321
+ runId: Type.Optional(Type.String()),
322
+ runIds: Type.Optional(Type.Array(Type.String())),
323
+ toRunId: Type.Optional(Type.String()),
324
+ requestId: Type.Optional(Type.String()),
325
+ type: Type.Optional(Type.String({ description: "Role/template (explore, implement, review, general)." })),
326
+ model: Type.Optional(Type.String()),
327
+ thinking: Type.Optional(Type.String({ enum: [...THINKING_LEVELS] })),
328
+ notifyOnDone: Type.Optional(Type.Unsafe({ type: ["boolean", "string"] })),
329
+ cwd: Type.Optional(Type.String()),
330
+ persist: Type.Optional(Type.Boolean()),
331
+ isolation: Type.Optional(Type.String({ enum: ["worktree", "none"] })),
332
+ kind: Type.Optional(Type.String({ enum: ["all", "subagent", "persistent"] })),
333
+ scope: Type.Optional(Type.String({ enum: ["finished_all"] })),
334
+ force: Type.Optional(Type.Boolean()),
335
+ includePersisted: Type.Optional(Type.Boolean()),
336
+ timeoutSeconds: Type.Optional(Type.Integer()),
258
337
  }),
259
338
  execute: async (_id, p, signal, _onUpdate, ctx) => {
260
339
  const action = (p.action ?? "").trim().toLowerCase();
340
+ // Text-first compatibility: the schema exposes `message` only; legacy/undocumented fields pass through.
341
+ const legacy = p;
261
342
  if (!action) {
262
- return text(pick(getLang(), `subagent 工具缺少 action 参数(可选:${SUBAGENT_ACTIONS.join(", ")})。`, `subagent tool requires an action parameter (one of: ${SUBAGENT_ACTIONS.join(", ")}).`, "subagents.action.missing"));
343
+ return text(pick(getLang(), `conversation 工具缺少 action 参数(可选:${SUBAGENT_ACTIONS.join(", ")})。`, `conversation tool requires an action parameter (one of: ${SUBAGENT_ACTIONS.join(", ")}).`, "subagents.action.missing"));
263
344
  }
264
345
  switch (action) {
265
346
  case "complete": {
@@ -270,13 +351,24 @@ export function makeSubagentTool(host, lang, selfConvId) {
270
351
  const summary = (p.summary ?? p.message ?? "").trim();
271
352
  if (!summary)
272
353
  throw new Error("complete requires a nonempty summary or message.");
273
- const result = await host.completeSubagent(selfId, summary);
274
- if (result && typeof result === "object" && "ok" in result && result.ok === false) {
275
- throw new Error(String("error" in result ? result.error : "Completion request rejected."));
354
+ const normalized = normalizeEvidenceInput(p.evidence);
355
+ if (!normalized.ok) {
356
+ return text(pick(getLang(), 'evidence 形状不对:要么给 {files:[], commands:[]},要么 {none:true}(只读任务),要么 {blocked:"原因"};空对象不算证据。', 'Malformed evidence: pass {files:[], commands:[]}, {none:true} for read-only work, or {blocked:"reason"}. An empty object is not evidence.', "subagents.complete.evidence.invalid"), { status: "evidence_invalid" });
357
+ }
358
+ const result = await host.completeSubagent(selfId, summary, normalized.value);
359
+ if (result.ok === false) {
360
+ const issues = result.issues && result.issues.length > 0 ? result.issues : [result.error ?? "unspecified"];
361
+ throw new Error(pick(getLang(), `完成被驳回:证据与本会话转录不符。\n- ${issues.join("\n- ")}\n先修正再 complete:声称跑过的命令必须真的在本会话里跑过且成功;没改文件就写 {none:true};做不完就写 {blocked:"原因"}。不要把口供改成能过的样子。`, `Completion rejected: the evidence does not match this session's transcript.\n- ${issues.join("\n- ")}\nFix the work, then complete again: commands must actually have run and succeeded; use {none:true} if you changed no files; use {blocked:"reason"} if you could not finish. Do not restate claims just to pass.`, "subagents.complete.rejected"));
276
362
  }
277
- return text("Completion intent recorded; settlement waits for idle state and pending dependencies.", {
363
+ const evidence = result.evidence;
364
+ const evidenceLine = evidence ? formatEvidenceSummary(evidence, getLang()) : "";
365
+ return text(evidence
366
+ ? pick(getLang(), `完成意图已登记。证据:${evidenceLine}\n结算会等空闲与依赖收口。`, `Completion intent recorded. Evidence: ${evidenceLine}\nSettlement waits for idle state and pending dependencies.`, "subagents.complete.recorded", { evidence: evidenceLine })
367
+ : "Completion intent recorded; settlement waits for idle state and pending dependencies.", {
278
368
  status: "completion_requested",
279
369
  runId: selfId,
370
+ verdict: evidence?.verdict,
371
+ evidence,
280
372
  });
281
373
  }
282
374
  case "consult": {
@@ -284,14 +376,22 @@ export function makeSubagentTool(host, lang, selfConvId) {
284
376
  const selfId = selfIdOf();
285
377
  if (!selfId || !host.consultParent)
286
378
  throw new Error("Parent consultation is unavailable.");
287
- if (!Array.isArray(p.questions) ||
288
- p.questions.length < 1 ||
289
- p.questions.length > 3 ||
290
- p.questions.some((q) => !q || typeof q.id !== "string" || !q.id.trim() || typeof q.question !== "string" || !q.question.trim()) ||
291
- new Set(p.questions.map((q) => q.id)).size !== p.questions.length) {
292
- throw new Error("consult requires 1-3 questions with unique IDs and nonempty text.");
293
- }
294
- const result = await host.consultParent(selfId, p.questions, signal);
379
+ const questions = legacy.questions ?? questionsFromMessage(p.message);
380
+ if (!Array.isArray(questions) ||
381
+ questions.length < 1 ||
382
+ questions.length > 3 ||
383
+ questions.some((q) => !q || typeof q.id !== "string" || !q.id.trim() || typeof q.question !== "string" || !q.question.trim()) ||
384
+ new Set(questions.map((q) => q.id)).size !== questions.length) {
385
+ throw new Error("consult requires a nonempty message (or 1-3 legacy questions with unique IDs).");
386
+ }
387
+ // schema 只下发展开档,富字段(options/optionsMap/dependsOn)的校验在这里补上,否则会把残缺选项透给 UI。
388
+ const questionErrors = Value.Errors(richQuestionsSchema(), questions);
389
+ if (questionErrors.length) {
390
+ throw new Error(`Invalid consult questions: ${questionErrors
391
+ .map((error) => `${error.instancePath || "/"}: ${error.message}`)
392
+ .join("; ")}`);
393
+ }
394
+ const result = await host.consultParent(selfId, questions, signal);
295
395
  signal?.throwIfAborted();
296
396
  return text(`${JSON.stringify(result) ?? "Consult resolved."}\nIf timed_out, do not choose on the parent's behalf. Ask again with only the context needed for the decision.`, result);
297
397
  }
@@ -306,17 +406,27 @@ export function makeSubagentTool(host, lang, selfConvId) {
306
406
  if (action === "answer") {
307
407
  if (!host.answerConsult)
308
408
  throw new Error("Consult answers are unavailable.");
309
- if (!Array.isArray(p.answers) ||
310
- p.answers.length === 0 ||
311
- p.answers.some((a) => !a ||
312
- typeof a.id !== "string" ||
313
- !a.id.trim() ||
314
- !Array.isArray(a.selected) ||
315
- a.selected.some((s) => typeof s !== "string") ||
316
- (a.custom !== undefined && typeof a.custom !== "string"))) {
317
- throw new Error("answer requires structured answers.");
318
- }
319
- result = await host.answerConsult(selfId, p.runId, p.requestId, p.answers);
409
+ const answers = legacy.answers;
410
+ const answerText = typeof p.message === "string" ? p.message.trim() : "";
411
+ if (answers !== undefined) {
412
+ if (!Array.isArray(answers) ||
413
+ answers.length === 0 ||
414
+ answers.some((a) => !a ||
415
+ typeof a.id !== "string" ||
416
+ !a.id.trim() ||
417
+ !Array.isArray(a.selected) ||
418
+ a.selected.some((s) => typeof s !== "string") ||
419
+ (a.custom !== undefined && typeof a.custom !== "string"))) {
420
+ throw new Error("answer requires structured answers with unique IDs.");
421
+ }
422
+ result = await host.answerConsult(selfId, p.runId, p.requestId, answers);
423
+ }
424
+ else if (answerText) {
425
+ result = await host.answerConsult(selfId, p.runId, p.requestId, undefined, answerText);
426
+ }
427
+ else {
428
+ throw new Error("answer requires a nonempty message (or legacy structured answers).");
429
+ }
320
430
  }
321
431
  else {
322
432
  if (!host.escalateConsult)
@@ -329,42 +439,103 @@ export function makeSubagentTool(host, lang, selfConvId) {
329
439
  return text(JSON.stringify(result) ?? `Consult ${action} submitted.`, result);
330
440
  }
331
441
  case "spawn": {
332
- if (!p.prompt || typeof p.prompt !== "string" || !p.prompt.trim()) {
333
- return text(pick(getLang(), 'subagent(action="spawn") 缺少 prompt 参数。', 'subagent(action="spawn") requires prompt parameter.', "subagents.spawn.missing.prompt"));
442
+ const batchTasks = Array.isArray(p.tasks) && p.tasks.length > 0 ? p.tasks : undefined;
443
+ if (!batchTasks && (!p.prompt || typeof p.prompt !== "string" || !p.prompt.trim())) {
444
+ return text(pick(getLang(), 'conversation(action="spawn") 缺少 prompt 参数(也可用 tasks[] 一次派多个)。', 'conversation(action="spawn") requires prompt (or tasks[] for a fan-out).', "subagents.spawn.missing.prompt"));
334
445
  }
335
- let templateName;
336
- if (p.template) {
337
- if (!host.isTemplateUsable(p.template)) {
338
- return text(pick(getLang(), `子代理模板不可用:${p.template}(不存在或已停用)。用 subagent(action="templates") 查看当前可用模板清单;不传 template 则按默认配置运行。`, `Subagent template unavailable: ${p.template} (missing or disabled). Use subagent(action="templates") to list available templates; omit template to run with defaults.`, "subagents.spawn.template.unavailable", { "p.template": p.template }));
339
- }
340
- templateName = p.template.trim();
341
- }
342
- else if (p.type && typeof p.type === "string" && host.isTemplateUsable(p.type.trim())) {
343
- templateName = p.type.trim();
446
+ const requests = batchTasks
447
+ ? batchTasks.map((task) => ({ ...task }))
448
+ : [
449
+ {
450
+ key: p.key,
451
+ prompt: p.prompt,
452
+ type: p.type,
453
+ template: legacy.template,
454
+ model: p.model,
455
+ thinking: p.thinking,
456
+ isolation: p.isolation,
457
+ persist: p.persist,
458
+ notifyOnDone: p.notifyOnDone,
459
+ },
460
+ ];
461
+ if (requests.length > SUBAGENT_FANOUT_MAX) {
462
+ return text(pick(getLang(), `一次最多派发 ${SUBAGENT_FANOUT_MAX} 个(收到 ${requests.length} 个)。分批调用或先等一批收口。`, `At most ${SUBAGENT_FANOUT_MAX} tasks per call (got ${requests.length}). Split the batch or wait for a round to settle first.`, "subagents.spawn.batch.too.many", { limit: SUBAGENT_FANOUT_MAX, count: requests.length }), { status: "rejected", reason: "fanout_limit", limit: SUBAGENT_FANOUT_MAX });
344
463
  }
345
- if (p.thinking && !THINKING_LEVELS.includes(p.thinking)) {
346
- return text(pick(getLang(), `非法思考强度:${p.thinking}。可选档位:${THINKING_LEVELS.join(", ")}。`, `Invalid thinking level: ${p.thinking}. Allowed levels: ${THINKING_LEVELS.join(", ")}.`, "subagents.spawn.thinking.invalid", { thinking: p.thinking, levels: THINKING_LEVELS.join(", ") }));
464
+ // 整批先校验再启动:一个不合法就一个都不启动,避免半批运行后预算/工作树无法回收。
465
+ const prepared = [];
466
+ const problems = [];
467
+ const usedKeys = new Set();
468
+ requests.forEach((request, index) => {
469
+ const normalized = normalizeSpawnRequest(request, index + 1);
470
+ if ("error" in normalized) {
471
+ problems.push(normalized.error);
472
+ return;
473
+ }
474
+ const key = normalized.spec.key;
475
+ if (key && usedKeys.has(key)) {
476
+ problems.push(pick(getLang(), `key 重复:${key}(同一批里必须唯一)。`, `Duplicate key: ${key} (keys must be unique within a batch).`, "subagents.spawn.batch.duplicate.key", { key }));
477
+ return;
478
+ }
479
+ if (key)
480
+ usedKeys.add(key);
481
+ prepared.push(normalized.spec);
482
+ });
483
+ if (problems.length > 0) {
484
+ const head = pick(getLang(), "派发被驳回(整批都未启动):\n", "Fan-out rejected (nothing launched):\n", "subagents.spawn.batch.rejected");
485
+ return text(`${head}${problems.map((problem) => `- ${problem}`).join("\n")}`, {
486
+ status: "rejected",
487
+ problems,
488
+ });
347
489
  }
348
- const isolationMode = p.isolation?.trim().toLowerCase();
349
- if (isolationMode && isolationMode !== "worktree" && isolationMode !== "none") {
350
- return text(pick(getLang(), `不支持的隔离模式:${p.isolation}。可选模式:"worktree"(基于 Git 工作树物理隔离)或 "none"(默认共享工作区)。`, `Unsupported isolation mode: ${p.isolation}. Supported modes: "worktree" (git worktree isolation) or "none" (shared workspace).`, "subagents.spawn.isolation.invalid", { isolation: p.isolation }));
490
+ if (batchTasks) {
491
+ const results = await mapLimited(prepared, SPAWN_FANOUT_CONCURRENCY, (spec) => spawnSpec(spec, p.cwd ?? ctx.cwd, signal));
492
+ const lines = results.map((result, index) => {
493
+ const spec = prepared[index];
494
+ const label = spec.key ?? `#${index + 1}`;
495
+ if (!result.ok)
496
+ return `- ${label} ✗ ${result.error}`;
497
+ const address = result.executionId ? ` · runId: ${result.executionId}` : "";
498
+ const tpl = spec.templateName ? ` · ${spec.templateName}` : "";
499
+ return `- ${label} → ${result.convId}${address} · ${spec.type}${tpl}`;
500
+ });
501
+ const startedKeys = prepared
502
+ .filter((spec, index) => spec.key && results[index]?.ok)
503
+ .map((spec) => spec.key);
504
+ const okCount = results.filter((result) => result.ok).length;
505
+ const head = pick(getLang(), `已派发 ${okCount}/${results.length} 个(key → 运行):\n`, `Started ${okCount}/${results.length} task(s) (key → run):\n`, "subagents.spawn.batch.started", { okCount, "results.length": results.length });
506
+ const keyHint = startedKeys.length > 0
507
+ ? pick(getLang(), `\n用 conversation(action="wait_all", runIds=${JSON.stringify(startedKeys)}) 一次等这批收口(key 与 runId 都接受)。`, `\nUse conversation(action="wait_all", runIds=${JSON.stringify(startedKeys)}) to collect this batch (keys and runIds both work).`, "subagents.spawn.batch.wait.hint", { keys: JSON.stringify(startedKeys) })
508
+ : "";
509
+ return text(`${head}${lines.join("\n")}${keyHint}`, {
510
+ status: "spawned",
511
+ tasks: results.map((result, index) => ({
512
+ key: prepared[index].key,
513
+ ok: result.ok,
514
+ convId: result.ok ? result.convId : undefined,
515
+ executionId: result.ok ? result.executionId : undefined,
516
+ error: result.ok ? undefined : result.error,
517
+ })),
518
+ });
351
519
  }
520
+ const single = prepared[0];
521
+ const templateName = single.templateName;
522
+ const isolationMode = single.isolationMode;
352
523
  let convId;
353
- const subagentType = p.type ?? "general";
524
+ const subagentType = single.type;
354
525
  const matchedTemplate = templateName ? host.listTemplates().find((t) => t.name === templateName) : undefined;
355
526
  const securityMode = resolveSecurityMode(subagentType, matchedTemplate);
356
527
  const extra = securityMode !== "normal" ? { securityMode } : undefined;
357
528
  try {
358
529
  const spawnArgs = [
359
- p.prompt,
530
+ single.prompt,
360
531
  subagentType,
361
532
  p.cwd ?? ctx.cwd,
362
533
  templateName,
363
- p.model,
534
+ single.model,
364
535
  undefined,
365
- p.persist,
366
- p.thinking,
367
- p.notifyOnDone,
536
+ single.persist,
537
+ single.thinking,
538
+ single.notifyOnDone,
368
539
  ];
369
540
  if (isolationMode === "worktree" || extra !== undefined || signal !== undefined) {
370
541
  spawnArgs.push(isolationMode === "worktree" ? "worktree" : undefined);
@@ -383,9 +554,12 @@ export function makeSubagentTool(host, lang, selfConvId) {
383
554
  error: msg,
384
555
  }));
385
556
  }
557
+ rememberRunKey(single.key, convId);
386
558
  const executionId = host.getSubagent(convId)?.executionId;
559
+ const keyLineZh = single.key ? `\nkey:${single.key}` : "";
560
+ const keyLineEn = single.key ? `\nkey: ${single.key}` : "";
387
561
  const addressLine = executionId ? `\nrunId: ${executionId}` : "";
388
- const subagentTitleText = subagentTitle(p.prompt);
562
+ const subagentTitleText = subagentTitle(single.prompt);
389
563
  const templateLineZh = templateName ? `\n模板:${templateName}` : "";
390
564
  const templateLineEn = templateName ? `\nTemplate: ${templateName}` : "";
391
565
  const modelLineZh = p.model ? `\n模型:${p.model}` : "";
@@ -398,13 +572,13 @@ export function makeSubagentTool(host, lang, selfConvId) {
398
572
  const isolationLineEn = isolationMode === "worktree" ? "\nWorktree isolation: enabled (dedicated Git worktree & branch)" : "";
399
573
  const kindLabelZh = p.persist ? "普通持久化对话" : "子代理";
400
574
  const kindLabelEn = p.persist ? "Persistent conversation" : "Subagent";
401
- return text(pick(getLang(), `${kindLabelZh}已启动(运行列表可见):${convId}\n类型:${subagentType} · 标题:${subagentTitleText}${templateLineZh}${modelLineZh}${thinkingLineZh}${notifyLineZh}${isolationLineZh}${addressLine}` +
402
- `\n用 subagent(action="wait_all") 一次等全部完成(不用轮询),subagent(action="get_result") 取单个结果,subagent(action="list") 看运行态,subagent(action="steer") 改向,subagent(action="stop") 停止。`, `${kindLabelEn} started (visible in the running list): ${convId}\nType: ${subagentType} · Title: ${subagentTitleText}${templateLineEn}${modelLineEn}${thinkingLineEn}${notifyLineEn}${isolationLineEn}${addressLine}` +
403
- `\nUse subagent(action="wait_all") to wait for all at once (no polling), subagent(action="get_result") for a single result, subagent(action="list") for live status, subagent(action="steer") to redirect, subagent(action="stop") to stop.`, "subagents.spawn.started", {
575
+ return text(pick(getLang(), `${kindLabelZh}已启动(运行列表可见):${convId}\n类型:${subagentType} · 标题:${subagentTitleText}${keyLineZh}${templateLineZh}${modelLineZh}${thinkingLineZh}${notifyLineZh}${isolationLineZh}${addressLine}` +
576
+ `\n用 conversation(action="wait_all") 一次等全部完成(事件驱动,不再轮询),conversation(action="get_result") 取单个结果,conversation(action="list") 看运行态,conversation(action="steer") 改向,conversation(action="stop") 停止。`, `${kindLabelEn} started (visible in the running list): ${convId}\nType: ${subagentType} · Title: ${subagentTitleText}${keyLineEn}${templateLineEn}${modelLineEn}${thinkingLineEn}${notifyLineEn}${isolationLineEn}${addressLine}` +
577
+ `\nUse conversation(action="wait_all") to wait for all at once (event-driven, no polling), conversation(action="get_result") for a single result, conversation(action="list") for live status, conversation(action="steer") to redirect, conversation(action="stop") to stop.`, "subagents.spawn.started", {
404
578
  convId,
405
579
  subagentType,
406
580
  subagentTitleText,
407
- "p.template": p.template,
581
+ "p.template": legacy.template,
408
582
  "p.model": p.model,
409
583
  "p.thinking": p.thinking,
410
584
  templateLineZh,
@@ -424,7 +598,8 @@ export function makeSubagentTool(host, lang, selfConvId) {
424
598
  }), {
425
599
  convId,
426
600
  executionId,
427
- template: p.template,
601
+ key: single.key,
602
+ template: templateName,
428
603
  model: p.model,
429
604
  thinking: p.thinking,
430
605
  persisted: !!p.persist,
@@ -434,10 +609,20 @@ export function makeSubagentTool(host, lang, selfConvId) {
434
609
  }
435
610
  case "get_result": {
436
611
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
437
- return text(pick(getLang(), 'subagent(action="get_result") 缺少 runId 参数。', 'subagent(action="get_result") requires runId parameter.', "subagents.get.missing.runId"));
612
+ return text(pick(getLang(), 'conversation(action="get_result") 缺少 runId 参数。', 'conversation(action="get_result") requires runId parameter.', "subagents.get.missing.runId"));
438
613
  }
439
- let r = host.getSubagent(p.runId);
614
+ const requestedRun = resolveRunRef(p.runId);
615
+ let r = host.getSubagent(requestedRun);
440
616
  const missingId = shortId(p.runId);
617
+ if (!r && host.getLedgerRun) {
618
+ // 进程里没有 → 回落运行账本:重启/移出后仍能拿回结论、证据与工作树。
619
+ const recorded = await host.getLedgerRun(requestedRun).catch(() => undefined);
620
+ if (recorded) {
621
+ const timeline = (await host.getLedgerEvents?.(requestedRun, 8).catch(() => [])) ?? [];
622
+ const formatted = formatLedgerRunResult(recorded, getLang(), timeline);
623
+ return text(formatted, { ...recorded, timeline });
624
+ }
625
+ }
441
626
  if (!r)
442
627
  return text(pick(getLang(), `未找到子代理 ${missingId}(可能已移出)。`, `Subagent ${missingId} not found (may have been dismissed).`, "subagents.get.not.found", { missingId }), undefined);
443
628
  const verdict = subagentVerdict(r, getLang());
@@ -445,6 +630,10 @@ export function makeSubagentTool(host, lang, selfConvId) {
445
630
  const doneDetail = verdictText(r, getLang());
446
631
  const doneOutput = r.output || (getLang() === "zh" ? "(无结果)" : "(no result)");
447
632
  const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
633
+ const usageTag = formatUsageTag(r.usage, getLang());
634
+ const evidenceLine = r.evidence
635
+ ? pick(getLang(), `\n证据:${formatEvidenceSummary(r.evidence, getLang())}`, `\nEvidence: ${formatEvidenceSummary(r.evidence, getLang())}`, "subagents.get.evidence", { evidence: formatEvidenceSummary(r.evidence, getLang()) })
636
+ : "";
448
637
  if (!isSubagentTerminal(r)) {
449
638
  const runningId = shortId(r.convId);
450
639
  const runningOutput = r.output || (getLang() === "zh" ? "(暂无输出)" : "(no output yet)");
@@ -466,28 +655,112 @@ export function makeSubagentTool(host, lang, selfConvId) {
466
655
  worktreeDetail = pick(getLang(), `\n\n[工作树隔离] 代码改动已保留供审阅:\n- 路径:${wt.path}\n- 分支:${wt.branch}\n- 改动:${wt.uncommittedCount ?? 0} 个未提交文件修改,领先 ${wt.aheadCount ?? 0} 个提交\n(提示:可执行 git merge ${wt.branch} 合并,或调用 worktree(action="remove", path="${wt.path}", force=true) 放弃)`, `\n\n[Worktree isolation] Changes preserved for review:\n- Path: ${wt.path}\n- Branch: ${wt.branch}\n- Changes: ${wt.uncommittedCount ?? 0} uncommitted file(s), ${wt.aheadCount ?? 0} commit(s) ahead\n(Note: run git merge ${wt.branch} to merge, or worktree(action="remove", path="${wt.path}", force=true) to discard)`, "subagents.get.worktree.preserved", { path: wt.path, branch: wt.branch, uncommitted: wt.uncommittedCount ?? 0, ahead: wt.aheadCount ?? 0 });
467
656
  }
468
657
  }
469
- return text(pick(getLang(), `子代理 ${doneId}(${r.type}${modelTag})状态:${verdict}\n${doneDetail}\n${doneOutput}${worktreeDetail}`, `Subagent ${doneId} (${r.type}${modelTag}) status: ${verdict}\n${doneDetail}\n${doneOutput}${worktreeDetail}`, "subagents.get.done", { doneId, "r.type": r.type, modelTag, verdict, doneDetail, doneOutput: `${doneOutput}${worktreeDetail}` }), r);
658
+ return text(pick(getLang(), `子代理 ${doneId}(${r.type}${modelTag}${usageTag})状态:${verdict}\n${doneDetail}${evidenceLine}\n${doneOutput}${worktreeDetail}`, `Subagent ${doneId} (${r.type}${modelTag}${usageTag}) status: ${verdict}\n${doneDetail}${evidenceLine}\n${doneOutput}${worktreeDetail}`, "subagents.get.done", {
659
+ doneId,
660
+ "r.type": r.type,
661
+ modelTag,
662
+ verdict,
663
+ doneDetail,
664
+ evidenceLine,
665
+ doneOutput: `${doneOutput}${worktreeDetail}`,
666
+ }), r);
667
+ }
668
+ case "resume": {
669
+ if (!host.resumeLedgerRun)
670
+ throw new Error("Run resume is unavailable on this engine.");
671
+ if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
672
+ return text(pick(getLang(), 'conversation(action="resume") 缺少 runId 参数。', 'conversation(action="resume") requires runId parameter.', "subagents.resume.missing.runId"));
673
+ }
674
+ const resumeSelf = selfIdOf();
675
+ if (!resumeSelf)
676
+ throw new Error("Resume requires a verified conversation identity.");
677
+ const resumeTarget = resolveRunRef(p.runId);
678
+ const resumeExtra = typeof p.message === "string" && p.message.trim() ? p.message.trim() : undefined;
679
+ const result = await host.resumeLedgerRun(resumeSelf, resumeTarget, resumeExtra);
680
+ if (!result.ok) {
681
+ const resumedId = result.runId ? shortId(result.runId) : "";
682
+ const reasons = {
683
+ not_found: [
684
+ '账本里没有这个运行(可能已被清理)。用 conversation(action="list") 看现有记录。',
685
+ 'Not in the run ledger (it may have been pruned). Use conversation(action="list") to inspect records.',
686
+ ],
687
+ running: [
688
+ "这个运行还在进程里跑着:先 wait_all / get_result,别重复派发。",
689
+ "This run is still live: use wait_all / get_result instead of relaunching it.",
690
+ ],
691
+ already_resumed: [
692
+ `已经续跑过了${resumedId ? `(新运行 ${resumedId})` : ""},别重复续跑。`,
693
+ `It was already resumed${resumedId ? ` (new run ${resumedId})` : ""}; do not resume twice.`,
694
+ ],
695
+ parent_missing: [
696
+ "原父对话已不可用,续跑挂不回去。请直接在当前对话里 spawn 一次。",
697
+ "The original parent is gone, so the relaunch cannot attach to it. Spawn from this conversation instead.",
698
+ ],
699
+ };
700
+ const [zhReason, enReason] = reasons[result.error] ?? [
701
+ `续跑失败:${result.error}`,
702
+ `Resume failed: ${result.error}`,
703
+ ];
704
+ return text(pick(getLang(), zhReason, enReason, "subagents.resume.failed", { reason: result.error }), result);
705
+ }
706
+ const newRunId = result.executionId ?? result.convId;
707
+ const transcript = result.sessionFile
708
+ ? pick(getLang(), `旧会话记录 ${result.sessionFile} 可在历史对话里回看。`, `The old transcript ${result.sessionFile} stays readable from History.`, "subagents.resume.transcript", { file: result.sessionFile })
709
+ : pick(getLang(), "旧会话没有落盘,接不上原转录:这次是带上原任务与已知进度的重派。", "The old in-memory session was never persisted, so this is a relaunch carrying the original task and known progress.", "subagents.resume.no.transcript");
710
+ return text(pick(getLang(), `已续跑:旧运行 ${shortId(result.runId)}(${result.previousState})→ 新运行 ${newRunId}。${transcript}`, `Resumed: ${shortId(result.runId)} (${result.previousState}) → new run ${newRunId}. ${transcript}`, "subagents.resume.ok", { oldId: shortId(result.runId), state: result.previousState, newId: newRunId, transcript }), result);
470
711
  }
471
712
  case "steer": {
472
713
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
473
- return text(pick(getLang(), 'subagent(action="steer") 缺少 runId 参数。', 'subagent(action="steer") requires runId parameter.', "subagents.steer.missing.runId"));
714
+ return text(pick(getLang(), 'conversation(action="steer") 缺少 runId 参数。', 'conversation(action="steer") requires runId parameter.', "subagents.steer.missing.runId"));
474
715
  }
475
716
  if (typeof p.message !== "string" || !p.message.trim()) {
476
- return text(pick(getLang(), 'subagent(action="steer") 缺少 message 参数。', 'subagent(action="steer") requires message parameter.', "subagents.steer.missing.message"));
717
+ return text(pick(getLang(), 'conversation(action="steer") 缺少 message 参数。', 'conversation(action="steer") requires message parameter.', "subagents.steer.missing.message"));
477
718
  }
478
- if (!host.getSubagent(p.runId)) {
719
+ const steerTarget = resolveRunRef(p.runId);
720
+ if (!host.getSubagent(steerTarget)) {
479
721
  const missingSteerId = shortId(p.runId);
480
- return text(pick(getLang(), `未找到子代理 ${missingSteerId}(可能已移出),消息未注入。请用 subagent(action="list") 确认仍在运行的子代理。`, `Subagent ${missingSteerId} not found (may have been dismissed); message not injected. Use subagent(action="list") to confirm running subagents.`, "subagents.steer.not.found", { missingSteerId }));
722
+ return text(pick(getLang(), `未找到子代理 ${missingSteerId}(可能已移出),消息未注入。请用 conversation(action="list") 确认仍在运行的子代理。`, `Subagent ${missingSteerId} not found (may have been dismissed); message not injected. Use conversation(action="list") to confirm running subagents.`, "subagents.steer.not.found", { missingSteerId }));
481
723
  }
482
- await host.steerSubagent(executionOfId(p.runId), p.message);
724
+ const receipt = await host.steerSubagent(executionOfId(steerTarget), p.message);
725
+ const steerState = receipt && "state" in receipt ? receipt.state : "delivered";
483
726
  const steerId = shortId(p.runId);
484
- return text(pick(getLang(), `已向子代理 ${steerId} 注入消息。`, `Message injected into subagent ${steerId}.`, "subagents.steer.injected", { steerId }));
727
+ const stateText = steerState === "queued"
728
+ ? pick(getLang(), "已排队,等当前回合结束再送。", "Queued; delivered when the current turn ends.", "subagents.steer.queued")
729
+ : steerState === "restarted"
730
+ ? pick(getLang(), "它当时已空闲,已在同一会话里开新一轮。", "It was idle; a new round started in the same session.", "subagents.steer.restarted")
731
+ : steerState === "missed"
732
+ ? pick(getLang(), "没能送达(运行已结束无可投递通道)。", "Not delivered (the run ended with no live route).", "subagents.steer.missed")
733
+ : pick(getLang(), "已送进当前回话上下文。", "Delivered into the live turn.", "subagents.steer.delivered");
734
+ return text(pick(getLang(), `已向子代理 ${steerId} 注入消息(${steerState}):${stateText}`, `Message injected into subagent ${steerId} (${steerState}): ${stateText}`, "subagents.steer.injected", { steerId, steerState, stateText }), { steerId, state: steerState });
485
735
  }
486
736
  case "list": {
487
737
  const list = host.listSubagents(p.kind, selfIdOf());
488
- if (list.length === 0)
489
- return text(pick(getLang(), "当前没有运行中的对话/子代理。", "No managed conversations or subagents running.", "subagents.list.empty"));
490
738
  const tLang = getLang();
739
+ // 账本追加:活运行永远以内存快照为准,账本只补「已经不在进程里」的那些。
740
+ const ledgerLines = [];
741
+ if (host.listLedgerRuns) {
742
+ try {
743
+ const recorded = await host.listLedgerRuns({ limit: 32 });
744
+ for (const rec of recorded) {
745
+ if (rec.state === "dismissed")
746
+ continue;
747
+ if (host.getSubagent(rec.runId))
748
+ continue;
749
+ const tag = rec.evidence ? ` · ${formatLedgerEvidence(rec, tLang)}` : "";
750
+ const resumed = rec.resumedBy
751
+ ? pick(tLang, `,已续跑→${shortId(rec.resumedBy)}`, `, resumed→${shortId(rec.resumedBy)}`, "subagents.list.ledger.resumed", { id: shortId(rec.resumedBy) })
752
+ : "";
753
+ ledgerLines.push(pick(tLang, `- 账本 ${shortId(rec.runId)} · ${rec.type} · ${rec.state} · ${rec.title}${tag}${resumed}`, `- ledger ${shortId(rec.runId)} · ${rec.type} · ${rec.state} · ${rec.title}${tag}${resumed}`, "subagents.list.ledger.item", { id: shortId(rec.runId), type: rec.type, state: rec.state, title: rec.title, tag, resumed }));
754
+ if (ledgerLines.length >= 10)
755
+ break;
756
+ }
757
+ }
758
+ catch {
759
+ // 账本读失败不影响活运行列表。
760
+ }
761
+ }
762
+ if (list.length === 0 && ledgerLines.length === 0)
763
+ return text(pick(getLang(), "当前没有运行中的对话/子代理(运行账本里也没有记录)。", "No managed conversations or subagents running (the run ledger is empty too).", "subagents.list.empty"));
491
764
  const lines = list.map((r) => {
492
765
  const tag = r.persisted
493
766
  ? tLang === "zh"
@@ -497,20 +770,26 @@ export function makeSubagentTool(host, lang, selfConvId) {
497
770
  ? "子代理"
498
771
  : "subagent";
499
772
  const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
773
+ const evidenceTag = r.evidence ? ` · ${formatEvidenceSummary(r.evidence, tLang)}` : "";
500
774
  return (`- ${r.convId}${r.executionId ? ` (runId: ${r.executionId})` : ""} · ${r.type}${modelTag} · ${subagentVerdict(r, tLang)} · ${r.title}` +
501
- (tLang === "zh" ? `(${tag} · msg: ${r.messageCount})` : ` (${tag} · msg: ${r.messageCount})`));
775
+ (tLang === "zh" ? `(${tag} · msg: ${r.messageCount})` : ` (${tag} · msg: ${r.messageCount})`) +
776
+ evidenceTag);
502
777
  });
503
- return text(lines.join("\n"));
778
+ const ledgerHead = ledgerLines.length > 0
779
+ ? pick(tLang, "\n\n运行账本(不在进程里:get_result 取已产出的结论/证据,resume 续跑):\n", "\n\nRun ledger (no longer in-process; get_result for the recorded result, resume to relaunch):\n", "subagents.list.ledger.head")
780
+ : "";
781
+ return text(`${lines.join("\n")}${ledgerHead}${ledgerLines.join("\n")}`);
504
782
  }
505
783
  case "stop": {
506
784
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
507
- return text(pick(getLang(), 'subagent(action="stop") 缺少 runId 参数。', 'subagent(action="stop") requires runId parameter.', "subagents.stop.missing.runId"));
785
+ return text(pick(getLang(), 'conversation(action="stop") 缺少 runId 参数。', 'conversation(action="stop") requires runId parameter.', "subagents.stop.missing.runId"));
508
786
  }
509
- if (!host.getSubagent(p.runId)) {
787
+ const stopTarget = resolveRunRef(p.runId);
788
+ if (!host.getSubagent(stopTarget)) {
510
789
  const missingStopId = shortId(p.runId);
511
- return text(pick(getLang(), `未找到子代理 ${missingStopId}(可能已移出或已结束),无需停止。请用 subagent(action="list") 确认仍在运行的子代理。`, `Subagent ${missingStopId} not found (may have been dismissed or already finished); nothing to stop. Use subagent(action="list") to confirm running subagents.`, "subagents.stop.not.found", { missingStopId }));
790
+ return text(pick(getLang(), `未找到子代理 ${missingStopId}(可能已移出或已结束),无需停止。请用 conversation(action="list") 确认仍在运行的子代理。`, `Subagent ${missingStopId} not found (may have been dismissed or already finished); nothing to stop. Use conversation(action="list") to confirm running subagents.`, "subagents.stop.not.found", { missingStopId }));
512
791
  }
513
- await host.stopSubagent(p.runId);
792
+ await host.stopSubagent(stopTarget);
514
793
  const stopId = shortId(p.runId);
515
794
  return text(pick(getLang(), `已请求停止子代理 ${stopId}。`, `Stop requested for subagent ${stopId}.`, "subagents.stop.requested", { stopId }));
516
795
  }
@@ -536,7 +815,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
536
815
  if (explicit) {
537
816
  const seedRoots = [];
538
817
  for (const requestedId of p.runIds) {
539
- const id = executionOfId(requestedId);
818
+ const id = executionOfId(resolveRunRef(requestedId));
540
819
  if (selfId && id === selfId)
541
820
  continue;
542
821
  if (selfAncestorIds.has(id))
@@ -600,13 +879,24 @@ export function makeSubagentTool(host, lang, selfConvId) {
600
879
  : currentWaitCapMs;
601
880
  const liveCapSeconds = Math.floor(liveWaitCapMs / 1000);
602
881
  const timeoutMs = Math.min(Math.max(p.timeoutSeconds ?? liveCapSeconds, 1), liveCapSeconds) * 1000;
882
+ // 已收口单源:`getSubagent` 拿不到(已移出/已结束并回收)与显式终态都算收口,
883
+ // 等待与「还剩谁」必须用同一判据,否则会出现「全都完成了却报还有人在跑」。
884
+ const isSettled = (id) => {
885
+ const r = host.getSubagent(id);
886
+ return r === undefined || isSubagentTerminal(r);
887
+ };
603
888
  const startedAt = Date.now();
604
- const POLL_INTERVAL_MS = 250;
889
+ // 单次等待切片:上游在真实事件上唤醒;到点只是重新算一遍(新派生的后代、问卷),
890
+ // 不再用固定轮询去抢快照。
891
+ const SETTLE_SLICE_MS = 30_000;
605
892
  try {
606
893
  const waitingParentId = selfIdOf();
607
894
  if (waitingParentId)
608
895
  host.setConsultWaiting?.(waitingParentId, true);
609
- while (!signal?.aborted && Date.now() - startedAt < timeoutMs) {
896
+ while (!signal?.aborted) {
897
+ const remainingMs = timeoutMs - (Date.now() - startedAt);
898
+ if (remainingMs <= 0)
899
+ break;
610
900
  for (const descId of expandDescendants(wanted)) {
611
901
  if (selfId && descId === selfId)
612
902
  continue;
@@ -617,13 +907,15 @@ export function makeSubagentTool(host, lang, selfConvId) {
617
907
  const consults = collectConsults();
618
908
  if (consults)
619
909
  return consults;
620
- const allDone = Array.from(wanted).every((id) => {
621
- const r = host.getSubagent(id);
622
- return r === undefined || isSubagentTerminal(r);
623
- });
910
+ const allDone = Array.from(wanted).every(isSettled);
624
911
  if (allDone)
625
912
  break;
626
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
913
+ const wake = await host.waitForSubagentSettle(Array.from(wanted), {
914
+ timeoutMs: Math.min(remainingMs, SETTLE_SLICE_MS),
915
+ signal,
916
+ });
917
+ if (wake === "aborted")
918
+ break;
627
919
  }
628
920
  }
629
921
  finally {
@@ -634,10 +926,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
634
926
  const tLang = getLang();
635
927
  const waitedSecs = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
636
928
  const timeoutSecs = Math.round(timeoutMs / 1000);
637
- const finishedIds = Array.from(wanted).filter((id) => {
638
- const r = host.getSubagent(id);
639
- return r === undefined || isSubagentTerminal(r);
640
- });
929
+ const finishedIds = Array.from(wanted).filter(isSettled);
641
930
  if (finishedIds.length > 0) {
642
931
  host.markSubagentsConsumed?.(finishedIds);
643
932
  if (host.finalizeSubagentWorktree) {
@@ -653,6 +942,8 @@ export function makeSubagentTool(host, lang, selfConvId) {
653
942
  }
654
943
  const verdict = subagentVerdict(r, tLang);
655
944
  const detail = verdictText(r, tLang);
945
+ const usageTag = formatUsageTag(r.usage, tLang);
946
+ const evidenceTag = r.evidence ? ` · ${formatEvidenceSummary(r.evidence, tLang)}` : "";
656
947
  const out = clipSubagentOutput(r.output || (tLang === "zh" ? "(无输出)" : "(no output)"), tLang);
657
948
  let wtTag = "";
658
949
  let wtPathInfo = "";
@@ -669,13 +960,10 @@ export function makeSubagentTool(host, lang, selfConvId) {
669
960
  tLang === "zh" ? `\n - 工作树路径:${r.worktree.path}` : `\n - Worktree path: ${r.worktree.path}`;
670
961
  }
671
962
  }
672
- return `- ${sId}(${r.type} · ${verdict} · ${r.title}${wtTag})${detail ? ` · ${detail}` : ""}:\n${out}${wtPathInfo}`;
963
+ return `- ${sId}(${r.type} · ${verdict} · ${r.title}${wtTag}${usageTag})${detail ? ` · ${detail}` : ""}${evidenceTag}:\n${out}${wtPathInfo}`;
673
964
  })
674
965
  .join("\n\n");
675
- const remaining = Array.from(wanted).filter((id) => {
676
- const r = host.getSubagent(id);
677
- return !isSubagentTerminal(r);
678
- });
966
+ const remaining = Array.from(wanted).filter((id) => !isSettled(id));
679
967
  const head = remaining.length === 0
680
968
  ? pick(tLang, `全部 ${wanted.size} 个子代理已收口:`, `All ${wanted.size} subagent(s) collected:`, "subagents.wait.collected", { "wanted.size": wanted.size })
681
969
  : signal?.aborted
@@ -710,21 +998,21 @@ export function makeSubagentTool(host, lang, selfConvId) {
710
998
  });
711
999
  const firstTemplateName = list[0]?.name;
712
1000
  const templateLines = lines.join("\n");
713
- return text(pick(getLang(), `可用的子代理模板(subagent 的 template 参数传名字,如 subagent(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, `Available subagent templates (pass the name as subagent's template param, e.g. subagent(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, "subagents.templates.list", { firstTemplateName, templateLines }));
1001
+ return text(pick(getLang(), `可用的子代理模板(subagent 的 template 参数传名字,如 conversation(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, `Available subagent templates (pass the name as subagent's template param, e.g. conversation(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, "subagents.templates.list", { firstTemplateName, templateLines }));
714
1002
  }
715
1003
  case "handoff": {
716
1004
  signal?.throwIfAborted();
717
1005
  const fromId = selfIdOf();
718
1006
  if (!fromId)
719
1007
  throw new Error("Handoff requires a verified conversation identity.");
720
- if (p.fromRunId && p.fromRunId !== fromId) {
1008
+ if (legacy.fromRunId && legacy.fromRunId !== fromId) {
721
1009
  throw new Error("Handoff source must match the calling conversation.");
722
1010
  }
723
1011
  if (!p.toRunId || typeof p.toRunId !== "string" || !p.toRunId.trim()) {
724
- return text(pick(getLang(), 'subagent(action="handoff") 缺少 toRunId 参数。', 'subagent(action="handoff") requires toRunId parameter.', "subagents.handoff.missing.toRunId"));
1012
+ return text(pick(getLang(), 'conversation(action="handoff") 缺少 toRunId 参数。', 'conversation(action="handoff") requires toRunId parameter.', "subagents.handoff.missing.toRunId"));
725
1013
  }
726
1014
  if (typeof p.payload !== "string" || !p.payload.trim()) {
727
- return text(pick(getLang(), 'subagent(action="handoff") 缺少 payload 参数。', 'subagent(action="handoff") requires payload parameter.', "subagents.handoff.missing.payload"));
1015
+ return text(pick(getLang(), 'conversation(action="handoff") 缺少 payload 参数。', 'conversation(action="handoff") requires payload parameter.', "subagents.handoff.missing.payload"));
728
1016
  }
729
1017
  if (fromId === p.toRunId) {
730
1018
  return text(pick(getLang(), `交接失败:不能交接给自身(${shortId(fromId)})。请指定其他同行子代理。`, `Handoff failed: cannot hand off to oneself (${shortId(fromId)}). Please specify a different peer subagent.`, "subagents.handoff.self", { id: shortId(fromId) }));
@@ -732,7 +1020,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
732
1020
  const target = host.getSubagent(p.toRunId);
733
1021
  if (!target) {
734
1022
  const missingId = shortId(p.toRunId);
735
- return text(pick(getLang(), `未找到目标子代理 ${missingId}(可能已移出或不存在)。请用 subagent(action="list") 确认可用的子代理。`, `Target subagent ${missingId} not found (may have been dismissed or non-existent). Use subagent(action="list") to check available subagents.`, "subagents.handoff.not.found", { missingId }));
1023
+ return text(pick(getLang(), `未找到目标子代理 ${missingId}(可能已移出或不存在)。请用 conversation(action="list") 确认可用的子代理。`, `Target subagent ${missingId} not found (may have been dismissed or non-existent). Use conversation(action="list") to check available subagents.`, "subagents.handoff.not.found", { missingId }));
736
1024
  }
737
1025
  try {
738
1026
  await host.handoffSubagent(fromId, executionOf(target), p.payload);
@@ -762,7 +1050,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
762
1050
  }
763
1051
  const isFinishedAll = p.scope === "finished_all";
764
1052
  if (explicitIds.length === 0 && !isFinishedAll) {
765
- return text(pick(getLang(), 'subagent(action="dismiss") 缺少目标参数:请指定 runId、runIds 或 scope="finished_all"。', 'subagent(action="dismiss") requires target parameter: specify runId, runIds, or scope="finished_all".', "subagents.dismiss.missing.target"));
1053
+ return text(pick(getLang(), 'conversation(action="dismiss") 缺少目标参数:请指定 runId、runIds 或 scope="finished_all"。', 'conversation(action="dismiss") requires target parameter: specify runId, runIds, or scope="finished_all".', "subagents.dismiss.missing.target"));
766
1054
  }
767
1055
  const selfId = selfIdOf();
768
1056
  const activeConvId = host.getActiveConversationId?.();
@@ -820,7 +1108,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
820
1108
  const isRunning = snapshot.streaming || snapshot.state === "running";
821
1109
  if (isRunning && !p.force) {
822
1110
  const runningId = shortId(targetId);
823
- return text(pick(getLang(), `子代理 ${runningId} 仍在运行中(状态:${snapshot.state})。请等待其完成、调用 subagent(action="stop"),或指定 force=true 强行中止并移出。`, `Subagent ${runningId} is still running (state: ${snapshot.state}). Wait for it to finish, call subagent(action="stop"), or specify force=true to force abort and dismiss.`, "subagents.dismiss.running", { runningId, state: snapshot.state }));
1111
+ return text(pick(getLang(), `子代理 ${runningId} 仍在运行中(状态:${snapshot.state})。请等待其完成、调用 conversation(action="stop"),或指定 force=true 强行中止并移出。`, `Subagent ${runningId} is still running (state: ${snapshot.state}). Wait for it to finish, call conversation(action="stop"), or specify force=true to force abort and dismiss.`, "subagents.dismiss.running", { runningId, state: snapshot.state }));
824
1112
  }
825
1113
  if (host.finalizeSubagentWorktree) {
826
1114
  await host.finalizeSubagentWorktree(targetId);
@@ -849,7 +1137,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
849
1137
  return text(pick(getLang(), `移出子代理 ${failedId} 失败:${res.reason ?? "未知原因"}。`, `Failed to dismiss subagent ${failedId}: ${res.reason ?? "unknown reason"}.`, "subagents.dismiss.failed", { failedId, reason: res.reason ?? "unknown" }));
850
1138
  }
851
1139
  const doneId = shortId(targetId);
852
- return text(pick(getLang(), `已移出子代理 ${doneId}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 subagent(action="get_result")。`, `Dismissed subagent ${doneId}. Dismissal is irreversible (session removed from panel, runtime and temporary data released). Note: call subagent(action="get_result") before dismissal if you need its output.`, "subagents.dismiss.success.single", { doneId }), { dismissed: [targetId], skipped: [] });
1140
+ return text(pick(getLang(), `已移出子代理 ${doneId}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 conversation(action="get_result")。`, `Dismissed subagent ${doneId}. Dismissal is irreversible (session removed from panel, runtime and temporary data released). Note: call conversation(action="get_result") before dismissal if you need its output.`, "subagents.dismiss.success.single", { doneId }), { dismissed: [targetId], skipped: [] });
853
1141
  }
854
1142
  candidateIds.sort((a, b) => depthOf(b) - depthOf(a));
855
1143
  const dismissed = [];
@@ -913,7 +1201,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
913
1201
  const skippedCount = skipped.length;
914
1202
  const skippedZh = skippedCount > 0 ? `(${skippedCount} 个已跳过)` : "";
915
1203
  const skippedEn = skippedCount > 0 ? ` (${skippedCount} skipped)` : "";
916
- return text(pick(getLang(), `已成功移出 ${dismissed.length} 个子代理${skippedZh}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 subagent(action="get_result")。`, `Successfully dismissed ${dismissed.length} subagent(s)${skippedEn}. Dismissal is irreversible (sessions removed from panel, runtimes and temporary data released). Note: call subagent(action="get_result") before dismissal if you need their outputs.`, "subagents.dismiss.success.batch", { count: dismissed.length, skippedZh, skippedEn }), { dismissed, skipped });
1204
+ return text(pick(getLang(), `已成功移出 ${dismissed.length} 个子代理${skippedZh}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 conversation(action="get_result")。`, `Successfully dismissed ${dismissed.length} subagent(s)${skippedEn}. Dismissal is irreversible (sessions removed from panel, runtimes and temporary data released). Note: call conversation(action="get_result") before dismissal if you need their outputs.`, "subagents.dismiss.success.batch", { count: dismissed.length, skippedZh, skippedEn }), { dismissed, skipped });
917
1205
  }
918
1206
  default:
919
1207
  return text(pick(getLang(), `未知 action:${action}。支持的 action:${SUBAGENT_ACTIONS.join(", ")}。`, `Unknown action: ${action}. Supported actions: ${SUBAGENT_ACTIONS.join(", ")}.`, "subagents.action.unknown", { action }));
@@ -922,17 +1210,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
922
1210
  });
923
1211
  }
924
1212
  export function makeSubagentTools(host, lang, selfConvId) {
925
- const primary = makeSubagentTool(host, lang, selfConvId);
926
- return [
927
- primary,
928
- {
929
- ...primary,
930
- name: SUBAGENT_TOOL_NAME,
931
- label: "Conversation collaboration (legacy alias)",
932
- description: "Compatibility alias for conversation. Prefer conversation for new calls; parameters and behavior are identical.",
933
- promptSnippet: "support existing subagent calls; prefer conversation",
934
- },
935
- ];
1213
+ return [makeSubagentTool(host, lang, selfConvId)];
936
1214
  }
937
1215
  function shortId(id) {
938
1216
  return id.slice(0, 8);
@@ -986,9 +1264,86 @@ function verdictText(r, lang = "en") {
986
1264
  return pick(lang, "(被中止,未产出结论)", "(Aborted, no conclusion produced.)", "subagents.verdict.aborted");
987
1265
  return "";
988
1266
  }
1267
+ /** 账本证据摘要(记录里只有计数与裁决,没有原始 claims)。 */
1268
+ function formatLedgerEvidence(record, lang) {
1269
+ const ev = record.evidence;
1270
+ if (!ev)
1271
+ return "";
1272
+ const zh = lang === "zh";
1273
+ const label = evidenceVerdictLabel(ev.verdict, lang);
1274
+ const parts = [];
1275
+ if (ev.files > 0)
1276
+ parts.push(zh ? `${ev.matchedFiles}/${ev.files} 文件` : `${ev.matchedFiles}/${ev.files} files`);
1277
+ if (ev.commands > 0) {
1278
+ parts.push(zh ? `${ev.matchedCommands}/${ev.commands} 命令` : `${ev.matchedCommands}/${ev.commands} commands`);
1279
+ }
1280
+ if (ev.none)
1281
+ parts.push(zh ? "声明无改动" : "declared no changes");
1282
+ if (ev.blocked)
1283
+ parts.push(zh ? `受阻:${ev.blocked}` : `blocked: ${ev.blocked}`);
1284
+ if (parts.length === 0)
1285
+ return label;
1286
+ return `${label}${zh ? "(" : " ("}${parts.join(zh ? "、" : ", ")}${zh ? ")" : ")"}`;
1287
+ }
1288
+ /** `get_result` 的账本回落:进程里已经没有这个运行了,只能给出落盘的结论与证据。 */
1289
+ function formatLedgerRunResult(record, lang, timeline = []) {
1290
+ const zh = lang === "zh";
1291
+ const id = shortId(record.runId);
1292
+ const lines = [
1293
+ zh
1294
+ ? `运行 ${id}(${record.type})已不在进程里;账本状态:${record.state}`
1295
+ : `Run ${id} (${record.type}) is no longer in process; ledger state: ${record.state}`,
1296
+ ];
1297
+ if (record.title)
1298
+ lines.push(zh ? `目标:${record.title}` : `Goal: ${record.title}`);
1299
+ if (record.evidence)
1300
+ lines.push(zh ? `证据:${formatLedgerEvidence(record, lang)}` : `Evidence: ${formatLedgerEvidence(record, lang)}`);
1301
+ if (record.error)
1302
+ lines.push(zh ? `错误:${record.error}` : `Error: ${record.error}`);
1303
+ if (record.worktree) {
1304
+ const wt = record.worktree;
1305
+ lines.push(zh
1306
+ ? `工作树:${wt.path}(分支 ${wt.branch}${wt.cleanedUp ? " · 已清理" : ""})`
1307
+ : `Worktree: ${wt.path} (branch ${wt.branch}${wt.cleanedUp ? " · cleaned" : ""})`);
1308
+ }
1309
+ if (record.sessionFile) {
1310
+ lines.push(zh
1311
+ ? `会话记录:${record.sessionFile}(可在历史对话里打开回看)`
1312
+ : `Session file: ${record.sessionFile} (openable from History)`);
1313
+ }
1314
+ if (record.outputTail) {
1315
+ lines.push(zh ? `最后输出(尾部):\n${record.outputTail}` : `Last output (tail):\n${record.outputTail}`);
1316
+ }
1317
+ if (timeline.length > 0) {
1318
+ lines.push(zh ? `生命周期(最近 ${timeline.length} 条):` : `Lifecycle (last ${timeline.length}):`);
1319
+ for (const event of timeline) {
1320
+ const at = new Date(event.ts);
1321
+ const when = Number.isFinite(at.getTime()) ? at.toISOString().slice(11, 19) : "--:--:--";
1322
+ lines.push(`- ${when} ${event.event}`);
1323
+ }
1324
+ }
1325
+ if (record.resumedBy) {
1326
+ lines.push(zh ? `已续跑为:${record.resumedBy}` : `Resumed as: ${record.resumedBy}`);
1327
+ }
1328
+ else if (record.state === "running" || record.state === "interrupted") {
1329
+ lines.push(zh
1330
+ ? `继续:conversation(action="resume", runId="${record.runId}")(带已知进度重派;旧会话不落盘,接不上原转录)`
1331
+ : `Continue: conversation(action="resume", runId="${record.runId}") (relaunch with known progress; the old in-memory session cannot be reattached)`);
1332
+ }
1333
+ return lines.join("\n");
1334
+ }
1335
+ function formatUsageTag(usage, lang) {
1336
+ if (!usage)
1337
+ return "";
1338
+ const zh = lang === "zh";
1339
+ const short = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
1340
+ return zh
1341
+ ? ` · ${short(usage.input)}↓${short(usage.output)}↑`
1342
+ : ` · ${short(usage.input)}in/${short(usage.output)}out`;
1343
+ }
989
1344
  function promptRemaining(remaining, lang = "en") {
990
1345
  if (remaining.length === 0)
991
1346
  return "";
992
1347
  const pendingIds = remaining.map(shortId).join(", ");
993
- return pick(lang, `\n未完成:${pendingIds}。可再次调用 subagent(action="wait_all")继续等待耗时任务,或使用 steer 补充指令 / stop 中止。`, `\nPending: ${pendingIds}. You may call subagent (action="wait_all") again to continue waiting for long tasks, or use steer to add instructions / stop to abort.`, "subagents.wait.pending", { pendingIds: pendingIds });
1348
+ return pick(lang, `\n未完成:${pendingIds}。可再次调用 subagent(action="wait_all")继续等待耗时任务,或使用 steer 补充指令 / stop 中止。`, `\nPending: ${pendingIds}. You may call conversation(action="wait_all") again to continue waiting for long tasks, or use steer to add instructions / stop to abort.`, "subagents.wait.pending", { pendingIds: pendingIds });
994
1349
  }