pi-web-ui 0.111.0 → 0.113.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 (88) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/bin/pi-web-ui.mjs +325 -45
  4. package/dist/server/agent-service-daemon.js +29 -4
  5. package/dist/server/agent-service.js +1527 -510
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/canvas/canvas-agent-tool.js +8 -0
  11. package/dist/server/canvas/canvas-orchestrator.js +128 -22
  12. package/dist/server/canvas/pstack-skills-data.js +498 -0
  13. package/dist/server/client-state.js +28 -0
  14. package/dist/server/delegate-mode.js +6 -3
  15. package/dist/server/delegate-task.js +18 -3
  16. package/dist/server/dispatch-domain-handlers.js +39 -11
  17. package/dist/server/dsh/dsh-agent-service.js +294 -15
  18. package/dist/server/dsh/dsh-serialize.js +1 -1
  19. package/dist/server/durable/durable-driver.js +112 -107
  20. package/dist/server/durable/durable-event-projector.js +253 -0
  21. package/dist/server/durable/durable-loader.js +1 -14
  22. package/dist/server/durable/durable-models.js +107 -0
  23. package/dist/server/durable/index.js +0 -4
  24. package/dist/server/engine-probe.js +111 -48
  25. package/dist/server/eval-tool.js +28 -3
  26. package/dist/server/goal-service.js +7 -0
  27. package/dist/server/index.js +371 -57
  28. package/dist/server/json-utils.js +57 -0
  29. package/dist/server/marker-service.js +8 -0
  30. package/dist/server/message-window.js +43 -10
  31. package/dist/server/model-admin.js +247 -163
  32. package/dist/server/model-resolver.js +66 -44
  33. package/dist/server/plan-manager.js +3 -6
  34. package/dist/server/plugin-api-catalog.js +1 -0
  35. package/dist/server/plugin-assets.js +238 -0
  36. package/dist/server/plugin-facilities.js +22 -0
  37. package/dist/server/plugin-ui-slots.js +1 -0
  38. package/dist/server/plugins.js +209 -11
  39. package/dist/server/preset-fields.js +25 -1
  40. package/dist/server/preset-share.js +5 -2
  41. package/dist/server/prompt-assembler.js +2 -1
  42. package/dist/server/prompt-composer.js +18 -8
  43. package/dist/server/protocol-version.js +1 -1
  44. package/dist/server/queue-utils.js +156 -0
  45. package/dist/server/remote-ssh-service.js +110 -12
  46. package/dist/server/sdk-builtin-extensions.js +85 -0
  47. package/dist/server/serialize.js +1 -1
  48. package/dist/server/server-config.js +66 -0
  49. package/dist/server/session-parser.js +49 -13
  50. package/dist/server/session-search.js +4 -3
  51. package/dist/server/settings-service.js +74 -53
  52. package/dist/server/setup-page.js +632 -0
  53. package/dist/server/skill-discovery.js +361 -59
  54. package/dist/server/skill-maintenance.js +231 -0
  55. package/dist/server/skill-tool.js +32 -3
  56. package/dist/server/soft-cap.js +30 -6
  57. package/dist/server/subagent-helpers.js +22 -1
  58. package/dist/server/subagent-notify.js +93 -0
  59. package/dist/server/subagent-security-gate.js +282 -0
  60. package/dist/server/subagent-templates.js +8 -0
  61. package/dist/server/subagents.js +390 -48
  62. package/dist/server/terminals.js +196 -8
  63. package/dist/server/text-quote.js +61 -0
  64. package/dist/server/tool-approval.js +63 -4
  65. package/dist/server/tool-guards.js +208 -0
  66. package/dist/server/tool-host-factories.js +48 -10
  67. package/dist/server/tool-manager.js +106 -28
  68. package/dist/server/tool-overrides.js +21 -11
  69. package/dist/server/universal/driver-base.js +8 -0
  70. package/dist/server/universal/drivers/claude-code.js +116 -7
  71. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  72. package/dist/server/universal/index.js +0 -1
  73. package/dist/server/universal/universal-session.js +106 -10
  74. package/dist/server/worktree-service.js +189 -1
  75. package/docs/dsh-engine.md +1 -5
  76. package/package.json +1 -1
  77. package/plugin-sdk/client-utils.mjs +192 -5
  78. package/plugin-sdk/index.d.ts +63 -1
  79. package/plugin-sdk/index.mjs +94 -0
  80. package/plugin-sdk/package.json +5 -1
  81. package/plugins/catalog.json +21 -0
  82. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
  83. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  84. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  85. package/web/dist/index.html +11 -2
  86. package/web/dist/sw.js +1 -1
  87. package/web/dist/assets/index-B0ajS__T.js +0 -697
  88. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -28,6 +28,8 @@
28
28
  import { defineTool } from "@earendil-works/pi-coding-agent";
29
29
  import { Type } from "typebox";
30
30
  import { pick } from "./i18n.js";
31
+ import { resolveSecurityMode } from "./subagent-security-gate.js";
32
+ import { THINKING_LEVELS } from "./subagent-templates.js";
31
33
  /**
32
34
  * subagent_wait_all 的最长阻塞时间:必须短暂低于工具看门狗(默认 20 分钟,
33
35
  * PI_WEB_TOOL_TIMEOUT_MS 可调),否则看门狗会先中止整个会话而不是让 wait
@@ -69,8 +71,21 @@ export function subagentTitle(prompt) {
69
71
  export function withSubagentOwner(host, ownerId) {
70
72
  return {
71
73
  ...host,
72
- spawnSubagent: (prompt, type, cwd, templateName, model, _parentId, persist) => host.spawnSubagent(prompt, type, cwd, templateName, model, ownerId, persist),
74
+ spawnSubagent: (prompt, type, cwd, templateName, model, _parentId, persist, thinking, notifyOnDone, isolation, extra) => {
75
+ const args = [prompt, type, cwd, templateName, model, ownerId, persist, thinking, notifyOnDone];
76
+ if (isolation !== undefined || extra !== undefined) {
77
+ args.push(isolation);
78
+ }
79
+ if (extra !== undefined) {
80
+ args.push(extra);
81
+ }
82
+ return host.spawnSubagent(...args);
83
+ },
73
84
  handoffSubagent: (fromRunId, toRunId, payload) => host.handoffSubagent(fromRunId || ownerId, toRunId, payload),
85
+ markSubagentsConsumed: (runIds) => host.markSubagentsConsumed?.(runIds),
86
+ finalizeSubagentWorktree: (convId) => host.finalizeSubagentWorktree?.(convId) ?? Promise.resolve(),
87
+ getActiveConversationId: () => host.getActiveConversationId?.(),
88
+ dismissSubagent: (convId, opts) => host.dismissSubagent?.(convId, opts) ?? Promise.resolve({ ok: false, reason: "unsupported" }),
74
89
  };
75
90
  }
76
91
  export const SUBAGENT_TOOL_NAME = "subagent";
@@ -83,6 +98,7 @@ export const SUBAGENT_ACTIONS = [
83
98
  "wait_all",
84
99
  "templates",
85
100
  "handoff",
101
+ "dismiss",
86
102
  ];
87
103
  /**
88
104
  * 单 action 子代理总工具(注册进每个会话的 customTools,供主 agent 驱动子代理)。
@@ -104,6 +120,63 @@ export function makeSubagentTool(host, lang, selfConvId) {
104
120
  content: [{ type: "text", text: t }],
105
121
  details,
106
122
  });
123
+ const expandDescendants = (roots) => {
124
+ if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
125
+ return [];
126
+ const rootSet = roots instanceof Set ? roots : new Set(roots);
127
+ // B20:带 forSelfId(本会话的族)展开 —— 过户把整族搬到别的会话后,
128
+ // 只列本会话自己的列表会展不开后代,wait_all 会误报「没有需要等待的子代理」。
129
+ const all = host.listSubagents(undefined, selfIdOf());
130
+ const out = [];
131
+ for (const s of all) {
132
+ if (rootSet.has(s.convId))
133
+ continue;
134
+ let curParent = s.parentId;
135
+ const seen = new Set();
136
+ while (curParent) {
137
+ if (rootSet.has(curParent)) {
138
+ out.push(s.convId);
139
+ break;
140
+ }
141
+ if (seen.has(curParent))
142
+ break;
143
+ seen.add(curParent);
144
+ curParent = host.getSubagent(curParent)?.parentId;
145
+ }
146
+ }
147
+ return out;
148
+ };
149
+ const isDescendantOf = (targetId, rootId) => {
150
+ const target = host.getSubagent(targetId);
151
+ if (!target)
152
+ return false;
153
+ let curParent = target.parentId;
154
+ const seen = new Set([targetId]);
155
+ while (curParent) {
156
+ if (curParent === rootId)
157
+ return true;
158
+ if (seen.has(curParent))
159
+ break;
160
+ seen.add(curParent);
161
+ curParent = host.getSubagent(curParent)?.parentId;
162
+ }
163
+ return false;
164
+ };
165
+ const depthOf = (targetId) => {
166
+ let d = 0;
167
+ let cur = host.getSubagent(targetId);
168
+ const seen = new Set([targetId]);
169
+ while (cur?.parentId) {
170
+ if (seen.has(cur.parentId))
171
+ break;
172
+ seen.add(cur.parentId);
173
+ d++;
174
+ cur = host.getSubagent(cur.parentId);
175
+ if (!cur)
176
+ break;
177
+ }
178
+ return d;
179
+ };
107
180
  const currentWaitCapMs = typeof host.getWatchdogTimeoutMs === "function"
108
181
  ? computeWaitCapMs(host.getWatchdogTimeoutMs())
109
182
  : computeWaitCapMs();
@@ -113,7 +186,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
113
186
  label: "Subagent manager",
114
187
  description: "Manage background subagent conversations for parallel delegation, research, and execution. " +
115
188
  "Each action's arguments are documented on the parameters below.",
116
- promptSnippet: "manage background subagents (spawn/steer/wait/templates)",
189
+ promptSnippet: "manage background subagents (spawn/steer/wait/dismiss)",
117
190
  parameters: Type.Object({
118
191
  action: Type.Unsafe({
119
192
  type: "string",
@@ -124,10 +197,10 @@ export function makeSubagentTool(host, lang, selfConvId) {
124
197
  description: "spawn: instructions (goal, constraints, expected output).",
125
198
  })),
126
199
  runId: Type.Optional(Type.String({
127
- description: "get_result/steer/stop: target conversation ID.",
200
+ description: "get_result/steer/stop/dismiss: target conversation ID.",
128
201
  })),
129
202
  runIds: Type.Optional(Type.Array(Type.String(), {
130
- description: "wait_all: conversation IDs to wait for (omit = all active).",
203
+ description: "wait_all/dismiss: conversation IDs to wait for or dismiss.",
131
204
  })),
132
205
  message: Type.Optional(Type.String({
133
206
  description: "steer: follow-up instruction.",
@@ -142,7 +215,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
142
215
  description: "handoff: source ID (default = this subagent).",
143
216
  })),
144
217
  type: Type.Optional(Type.String({
145
- description: "spawn: role/type (e.g. explore/implement/review, default: general).",
218
+ 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.",
146
219
  })),
147
220
  template: Type.Optional(Type.String({
148
221
  description: "spawn: template name (see action=templates).",
@@ -150,12 +223,23 @@ export function makeSubagentTool(host, lang, selfConvId) {
150
223
  model: Type.Optional(Type.String({
151
224
  description: 'spawn: model override "provider/id".',
152
225
  })),
226
+ thinking: Type.Optional(Type.String({
227
+ enum: [...THINKING_LEVELS],
228
+ description: 'spawn: thinking budget level ("off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max").',
229
+ })),
230
+ notifyOnDone: Type.Optional(Type.Boolean({
231
+ description: "spawn: notify and wake parent conversation when finished (default: true).",
232
+ })),
153
233
  cwd: Type.Optional(Type.String({
154
234
  description: "spawn: working directory (default = current).",
155
235
  })),
156
236
  persist: Type.Optional(Type.Boolean({
157
237
  description: "spawn: persist as a regular session (default = ephemeral).",
158
238
  })),
239
+ isolation: Type.Optional(Type.String({
240
+ enum: ["worktree", "none"],
241
+ description: 'spawn: workspace isolation mode ("worktree" creates a dedicated git worktree & branch; "none" = shared cwd).',
242
+ })),
159
243
  kind: Type.Optional(Type.String({
160
244
  enum: ["all", "subagent", "persistent"],
161
245
  description: "list: filter subagents by kind (default: all).",
@@ -165,23 +249,68 @@ export function makeSubagentTool(host, lang, selfConvId) {
165
249
  minimum: 1,
166
250
  maximum: capSeconds,
167
251
  })),
252
+ scope: Type.Optional(Type.String({
253
+ enum: ["finished_all"],
254
+ description: 'dismiss: batch dismissal scope ("finished_all" to dismiss all finished descendant subagents).',
255
+ })),
256
+ force: Type.Optional(Type.Boolean({
257
+ description: "dismiss: force abort running subagents before dismissing (default: false).",
258
+ })),
259
+ includePersisted: Type.Optional(Type.Boolean({
260
+ description: "dismiss: allow dismissing persisted subagents (default: false).",
261
+ })),
168
262
  }),
169
263
  execute: async (_id, p, signal, _onUpdate, ctx) => {
170
264
  const action = (p.action ?? "").trim().toLowerCase();
171
265
  if (!action) {
172
- return text(pick(getLang(), "subagent 工具缺少 action 参数(可选:spawn, get_result, steer, list, stop, wait_all, templates, handoff)。", "subagent tool requires an action parameter (one of: spawn, get_result, steer, list, stop, wait_all, templates, handoff).", "subagents.action.missing"));
266
+ return text(pick(getLang(), "subagent 工具缺少 action 参数(可选:spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss)。", "subagent tool requires an action parameter (one of: spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss).", "subagents.action.missing"));
173
267
  }
174
268
  switch (action) {
175
269
  case "spawn": {
176
270
  if (!p.prompt || typeof p.prompt !== "string" || !p.prompt.trim()) {
177
271
  return text(pick(getLang(), 'subagent(action="spawn") 缺少 prompt 参数。', 'subagent(action="spawn") requires prompt parameter.', "subagents.spawn.missing.prompt"));
178
272
  }
179
- if (p.template && !host.isTemplateUsable(p.template)) {
180
- 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 }));
273
+ let templateName;
274
+ if (p.template) {
275
+ if (!host.isTemplateUsable(p.template)) {
276
+ 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 }));
277
+ }
278
+ templateName = p.template.trim();
279
+ }
280
+ else if (p.type && typeof p.type === "string" && host.isTemplateUsable(p.type.trim())) {
281
+ templateName = p.type.trim();
282
+ }
283
+ if (p.thinking && !THINKING_LEVELS.includes(p.thinking)) {
284
+ 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(", ") }));
285
+ }
286
+ const isolationMode = p.isolation?.trim().toLowerCase();
287
+ if (isolationMode && isolationMode !== "worktree" && isolationMode !== "none") {
288
+ 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 }));
181
289
  }
182
290
  let convId;
291
+ const subagentType = p.type ?? "general";
292
+ const matchedTemplate = templateName ? host.listTemplates().find((t) => t.name === templateName) : undefined;
293
+ const securityMode = resolveSecurityMode(subagentType, matchedTemplate);
294
+ const extra = securityMode !== "normal" ? { securityMode } : undefined;
183
295
  try {
184
- convId = await host.spawnSubagent(p.prompt, p.type ?? "general", p.cwd ?? ctx.cwd, p.template, p.model, undefined, p.persist);
296
+ const spawnArgs = [
297
+ p.prompt,
298
+ subagentType,
299
+ p.cwd ?? ctx.cwd,
300
+ templateName,
301
+ p.model,
302
+ undefined,
303
+ p.persist,
304
+ p.thinking,
305
+ p.notifyOnDone,
306
+ ];
307
+ if (isolationMode === "worktree" || extra !== undefined) {
308
+ spawnArgs.push(isolationMode === "worktree" ? "worktree" : undefined);
309
+ }
310
+ if (extra !== undefined) {
311
+ spawnArgs.push(extra);
312
+ }
313
+ convId = await host.spawnSubagent(...spawnArgs);
185
314
  }
186
315
  catch (err) {
187
316
  const msg = err instanceof Error ? err.message : String(err);
@@ -189,36 +318,56 @@ export function makeSubagentTool(host, lang, selfConvId) {
189
318
  error: msg,
190
319
  }));
191
320
  }
192
- const subagentType = p.type ?? "general";
193
321
  const subagentTitleText = subagentTitle(p.prompt);
194
- const templateLineZh = p.template ? `\n模板:${p.template}` : "";
195
- const templateLineEn = p.template ? `\nTemplate: ${p.template}` : "";
322
+ const templateLineZh = templateName ? `\n模板:${templateName}` : "";
323
+ const templateLineEn = templateName ? `\nTemplate: ${templateName}` : "";
196
324
  const modelLineZh = p.model ? `\n模型:${p.model}` : "";
197
325
  const modelLineEn = p.model ? `\nModel: ${p.model}` : "";
326
+ const thinkingLineZh = p.thinking ? `\n思考强度:${p.thinking}` : "";
327
+ const thinkingLineEn = p.thinking ? `\nThinking: ${p.thinking}` : "";
328
+ const notifyLineZh = p.notifyOnDone === false ? "\n自动通知:已关闭" : "";
329
+ const notifyLineEn = p.notifyOnDone === false ? "\nAuto-notify: disabled" : "";
330
+ const isolationLineZh = isolationMode === "worktree" ? "\n工作树隔离:已启用(独立 Git 工作树与分支)" : "";
331
+ const isolationLineEn = isolationMode === "worktree" ? "\nWorktree isolation: enabled (dedicated Git worktree & branch)" : "";
198
332
  const kindLabelZh = p.persist ? "普通持久化对话" : "子代理";
199
333
  const kindLabelEn = p.persist ? "Persistent conversation" : "Subagent";
200
- return text(pick(getLang(), `${kindLabelZh}已启动(运行列表可见):${convId}\n类型:${subagentType} · 标题:${subagentTitleText}${templateLineZh}${modelLineZh}` +
201
- `\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}` +
334
+ return text(pick(getLang(), `${kindLabelZh}已启动(运行列表可见):${convId}\n类型:${subagentType} · 标题:${subagentTitleText}${templateLineZh}${modelLineZh}${thinkingLineZh}${notifyLineZh}${isolationLineZh}` +
335
+ `\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}` +
202
336
  `\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", {
203
337
  convId,
204
338
  subagentType,
205
339
  subagentTitleText,
206
340
  "p.template": p.template,
207
341
  "p.model": p.model,
342
+ "p.thinking": p.thinking,
208
343
  templateLineZh,
209
344
  templateLineEn,
210
345
  modelLineZh,
211
346
  modelLineEn,
347
+ thinkingLineZh,
348
+ thinkingLineEn,
349
+ notifyLineZh,
350
+ notifyLineEn,
351
+ isolationLineZh,
352
+ isolationLineEn,
212
353
  kindLabel: kindLabelEn,
213
354
  kindLabelEn,
214
355
  kindLabelZh,
215
- }), { convId, template: p.template, model: p.model, persisted: !!p.persist });
356
+ }), {
357
+ convId,
358
+ template: p.template,
359
+ model: p.model,
360
+ thinking: p.thinking,
361
+ persisted: !!p.persist,
362
+ notifyOnDone: p.notifyOnDone !== false,
363
+ isolation: isolationMode === "worktree" ? "worktree" : undefined,
364
+ });
216
365
  }
217
366
  case "get_result": {
218
367
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
219
368
  return text(pick(getLang(), 'subagent(action="get_result") 缺少 runId 参数。', 'subagent(action="get_result") requires runId parameter.', "subagents.get.missing.runId"));
220
369
  }
221
- const r = host.getSubagent(p.runId);
370
+ let r = host.getSubagent(p.runId);
222
371
  const missingId = shortId(p.runId);
223
372
  if (!r)
224
373
  return text(pick(getLang(), `未找到子代理 ${missingId}(可能已移出)。`, `Subagent ${missingId} not found (may have been dismissed).`, "subagents.get.not.found", { missingId }), undefined);
@@ -226,12 +375,29 @@ export function makeSubagentTool(host, lang, selfConvId) {
226
375
  const doneId = shortId(r.convId);
227
376
  const doneDetail = verdictText(r, getLang());
228
377
  const doneOutput = r.output || (getLang() === "zh" ? "(无结果)" : "(no result)");
378
+ const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
229
379
  if (r.streaming || r.state === "running") {
230
380
  const runningId = shortId(r.convId);
231
381
  const runningOutput = r.output || (getLang() === "zh" ? "(暂无输出)" : "(no output yet)");
232
- return text(pick(getLang(), `子代理 ${runningId}(${r.type})仍在运行(状态 ${r.state})。\n当前输出:\n${runningOutput}`, `Subagent ${runningId} (${r.type}) is still running (state ${r.state}).\nCurrent output:\n${runningOutput}`, "subagents.get.running", { runningId, "r.type": r.type, "r.state": r.state, runningOutput }), r);
382
+ return text(pick(getLang(), `子代理 ${runningId}(${r.type}${modelTag})仍在运行(状态 ${r.state})。\n当前输出:\n${runningOutput}`, `Subagent ${runningId} (${r.type}${modelTag}) is still running (state ${r.state}).\nCurrent output:\n${runningOutput}`, "subagents.get.running", { runningId, "r.type": r.type, modelTag, "r.state": r.state, runningOutput }), r);
383
+ }
384
+ // 终态结果被父对话取走,标记已消费,避免后续重复触发自动通知
385
+ host.markSubagentsConsumed?.([p.runId]);
386
+ if (host.finalizeSubagentWorktree) {
387
+ await host.finalizeSubagentWorktree(p.runId);
388
+ r = host.getSubagent(p.runId) ?? r;
233
389
  }
234
- return text(pick(getLang(), `子代理 ${doneId}(${r.type})状态:${verdict}\n${doneDetail}\n${doneOutput}`, `Subagent ${doneId} (${r.type}) status: ${verdict}\n${doneDetail}\n${doneOutput}`, "subagents.get.done", { doneId, "r.type": r.type, verdict, doneDetail, doneOutput }), r);
390
+ let worktreeDetail = "";
391
+ if (r.worktree) {
392
+ const wt = r.worktree;
393
+ if (wt.cleanedUp) {
394
+ worktreeDetail = pick(getLang(), "\n\n[工作树隔离] 无文件修改,临时工作树与分支已自动清理。", "\n\n[Worktree isolation] No changes made; temporary worktree and branch have been cleaned up automatically.", "subagents.get.worktree.cleaned");
395
+ }
396
+ else {
397
+ 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 });
398
+ }
399
+ }
400
+ 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);
235
401
  }
236
402
  case "steer": {
237
403
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
@@ -261,7 +427,8 @@ export function makeSubagentTool(host, lang, selfConvId) {
261
427
  : tLang === "zh"
262
428
  ? "子代理"
263
429
  : "subagent";
264
- return (`- ${r.convId} · ${r.type} · ${subagentVerdict(r, tLang)} · ${r.title}` +
430
+ const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
431
+ return (`- ${r.convId} · ${r.type}${modelTag} · ${subagentVerdict(r, tLang)} · ${r.title}` +
265
432
  (tLang === "zh" ? `(${tag} · msg: ${r.messageCount})` : ` (${tag} · msg: ${r.messageCount})`));
266
433
  });
267
434
  return text(lines.join("\n"));
@@ -291,32 +458,6 @@ export function makeSubagentTool(host, lang, selfConvId) {
291
458
  }
292
459
  return out;
293
460
  };
294
- const expandDescendants = (roots) => {
295
- if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
296
- return [];
297
- const rootSet = roots instanceof Set ? roots : new Set(roots);
298
- // B20:带 forSelfId(本会话的族)展开 —— 过户把整族搬到别的会话后,
299
- // 只列本会话自己的列表会展不开后代,wait_all 会误报「没有需要等待的子代理」。
300
- const all = host.listSubagents(undefined, selfId);
301
- const out = [];
302
- for (const s of all) {
303
- if (rootSet.has(s.convId))
304
- continue;
305
- let curParent = s.parentId;
306
- const seen = new Set();
307
- while (curParent) {
308
- if (rootSet.has(curParent)) {
309
- out.push(s.convId);
310
- break;
311
- }
312
- if (seen.has(curParent))
313
- break;
314
- seen.add(curParent);
315
- curParent = host.getSubagent(curParent)?.parentId;
316
- }
317
- }
318
- return out;
319
- };
320
461
  const explicit = p.runIds && p.runIds.length > 0;
321
462
  const wanted = new Set();
322
463
  const selfAncestorIds = selfId ? ancestorIdsOf(selfId) : new Set();
@@ -359,7 +500,11 @@ export function makeSubagentTool(host, lang, selfConvId) {
359
500
  if (wanted.size === 0) {
360
501
  return text(pick(getLang(), "没有需要等待的子代理(调用者自身与其祖先永不计入等待;子代理无参数调用时只等待属于它自己的后代)。", "No subagents to wait for (the calling session itself and its ancestors are never waited on; a subagent without runIds only waits for its own descendants).", "subagents.wait.empty"));
361
502
  }
362
- const timeoutMs = Math.min(Math.max(p.timeoutSeconds ?? capSeconds, 1), capSeconds) * 1000;
503
+ const liveWaitCapMs = typeof host.getWatchdogTimeoutMs === "function"
504
+ ? computeWaitCapMs(host.getWatchdogTimeoutMs())
505
+ : currentWaitCapMs;
506
+ const liveCapSeconds = Math.floor(liveWaitCapMs / 1000);
507
+ const timeoutMs = Math.min(Math.max(p.timeoutSeconds ?? liveCapSeconds, 1), liveCapSeconds) * 1000;
363
508
  const startedAt = Date.now();
364
509
  const POLL_INTERVAL_MS = 250;
365
510
  while (!signal?.aborted && Date.now() - startedAt < timeoutMs) {
@@ -384,6 +529,17 @@ export function makeSubagentTool(host, lang, selfConvId) {
384
529
  const tLang = getLang();
385
530
  const waitedSecs = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
386
531
  const timeoutSecs = Math.round(timeoutMs / 1000);
532
+ // 收口的子代理标记已消费,避免后续重复自动通知打扰父对话;同时结算隔离工作树
533
+ const finishedIds = Array.from(wanted).filter((id) => {
534
+ const r = host.getSubagent(id);
535
+ return r === undefined || isSubagentTerminal(r);
536
+ });
537
+ if (finishedIds.length > 0) {
538
+ host.markSubagentsConsumed?.(finishedIds);
539
+ if (host.finalizeSubagentWorktree) {
540
+ await Promise.all(finishedIds.map((id) => host.finalizeSubagentWorktree(id)));
541
+ }
542
+ }
387
543
  const lines = Array.from(wanted)
388
544
  .map((id) => {
389
545
  const r = host.getSubagent(id);
@@ -394,7 +550,22 @@ export function makeSubagentTool(host, lang, selfConvId) {
394
550
  const verdict = subagentVerdict(r, tLang);
395
551
  const detail = verdictText(r, tLang);
396
552
  const out = clipSubagentOutput(r.output || (tLang === "zh" ? "(无输出)" : "(no output)"), tLang);
397
- return `- ${sId}(${r.type} · ${verdict} · ${r.title})${detail ? ` · ${detail}` : ""}:\n${out}`;
553
+ let wtTag = "";
554
+ let wtPathInfo = "";
555
+ if (r.worktree) {
556
+ if (r.worktree.cleanedUp) {
557
+ wtTag = tLang === "zh" ? " · 工作树已清理" : " · worktree cleaned";
558
+ }
559
+ else {
560
+ wtTag =
561
+ tLang === "zh"
562
+ ? ` · 工作树保留: ${r.worktree.branch} (${r.worktree.uncommittedCount ?? 0} 改动, +${r.worktree.aheadCount ?? 0} 提交)`
563
+ : ` · worktree kept: ${r.worktree.branch} (${r.worktree.uncommittedCount ?? 0} dirty, +${r.worktree.aheadCount ?? 0} commits)`;
564
+ wtPathInfo =
565
+ tLang === "zh" ? `\n - 工作树路径:${r.worktree.path}` : `\n - Worktree path: ${r.worktree.path}`;
566
+ }
567
+ }
568
+ return `- ${sId}(${r.type} · ${verdict} · ${r.title}${wtTag})${detail ? ` · ${detail}` : ""}:\n${out}${wtPathInfo}`;
398
569
  })
399
570
  .join("\n\n");
400
571
  const remaining = Array.from(wanted).filter((id) => {
@@ -464,8 +635,179 @@ export function makeSubagentTool(host, lang, selfConvId) {
464
635
  return text(pick(getLang(), `交接失败:${msg}`, `Handoff failed: ${msg}`, "subagents.handoff.failed", { error: msg }));
465
636
  }
466
637
  }
638
+ case "dismiss": {
639
+ if (!host.dismissSubagent) {
640
+ return text(pick(getLang(), "当前引擎不支持子代理移出能力。", "Subagent dismissal is not supported by the current engine.", "subagents.dismiss.unsupported"));
641
+ }
642
+ const explicitIds = [];
643
+ if (Array.isArray(p.runIds) && p.runIds.length > 0) {
644
+ for (const id of p.runIds) {
645
+ if (typeof id === "string" && id.trim()) {
646
+ explicitIds.push(id.trim());
647
+ }
648
+ }
649
+ }
650
+ else if (p.runId && typeof p.runId === "string" && p.runId.trim()) {
651
+ explicitIds.push(p.runId.trim());
652
+ }
653
+ const isFinishedAll = p.scope === "finished_all";
654
+ if (explicitIds.length === 0 && !isFinishedAll) {
655
+ 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"));
656
+ }
657
+ const selfId = selfIdOf();
658
+ const activeConvId = host.getActiveConversationId?.();
659
+ let candidateIds = [];
660
+ if (isFinishedAll) {
661
+ const all = host.listSubagents(undefined, selfId);
662
+ let inScopeList = all;
663
+ if (selfId) {
664
+ const descIds = new Set(expandDescendants(new Set([selfId])));
665
+ inScopeList = all.filter((s) => descIds.has(s.convId));
666
+ }
667
+ // 口径与 finishedSubagentCount 一致:isSubagent、非 streaming、非当前 active
668
+ candidateIds = inScopeList
669
+ .filter((s) => {
670
+ if (s.streaming || s.state === "running")
671
+ return false;
672
+ if (s.convId === selfId)
673
+ return false;
674
+ if (activeConvId && s.convId === activeConvId)
675
+ return false;
676
+ if (s.persisted && !p.includePersisted)
677
+ return false;
678
+ return true;
679
+ })
680
+ .map((s) => s.convId);
681
+ if (candidateIds.length === 0) {
682
+ return text(pick(getLang(), "没有可移出的已结束子代理。", "No finished subagents to dismiss.", "subagents.dismiss.finished_all.empty"), { dismissed: [], skipped: [] });
683
+ }
684
+ }
685
+ else {
686
+ candidateIds = [...new Set(explicitIds)];
687
+ }
688
+ const isSingleExplicit = !isFinishedAll && explicitIds.length === 1;
689
+ if (isSingleExplicit) {
690
+ const targetId = candidateIds[0];
691
+ const snapshot = host.getSubagent(targetId);
692
+ if (!snapshot) {
693
+ const missingId = shortId(targetId);
694
+ return text(pick(getLang(), `未找到子代理 ${missingId}(可能已移出或不存在)。`, `Subagent ${missingId} not found (may have been dismissed or non-existent).`, "subagents.dismiss.not_found", { missingId }));
695
+ }
696
+ if (selfId && targetId === selfId) {
697
+ return text(pick(getLang(), "拒绝移出:不能移出当前会话自身。", "Refused: cannot dismiss the current conversation itself.", "subagents.dismiss.self"));
698
+ }
699
+ if (activeConvId && targetId === activeConvId) {
700
+ const activeId = shortId(targetId);
701
+ return text(pick(getLang(), `子代理 ${activeId} 正在前端处于活动打开状态,无法直接移出。`, `Subagent ${activeId} is currently active in the UI and cannot be dismissed.`, "subagents.dismiss.active", { activeId }));
702
+ }
703
+ if (selfId && !isDescendantOf(targetId, selfId)) {
704
+ const notDescId = shortId(targetId);
705
+ return text(pick(getLang(), `拒绝移出:子代理 ${notDescId} 不属于当前会话的派发族谱(仅允许移出由当前会话派发的子代理)。`, `Refused: subagent ${notDescId} does not belong to the descendant hierarchy of this conversation (can only dismiss subagents spawned by this conversation).`, "subagents.dismiss.not_descendant", { notDescId }));
706
+ }
707
+ if (snapshot.persisted && !p.includePersisted) {
708
+ const persistedId = shortId(targetId);
709
+ return text(pick(getLang(), `子代理 ${persistedId} 为持久化会话(已落盘历史)。如确认需要移出,请传入 includePersisted=true。`, `Subagent ${persistedId} is a persistent session. If you are sure you want to dismiss it, pass includePersisted=true.`, "subagents.dismiss.persisted", { persistedId }));
710
+ }
711
+ const isRunning = snapshot.streaming || snapshot.state === "running";
712
+ if (isRunning && !p.force) {
713
+ const runningId = shortId(targetId);
714
+ 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 }));
715
+ }
716
+ if (host.finalizeSubagentWorktree) {
717
+ await host.finalizeSubagentWorktree(targetId);
718
+ }
719
+ const updated = host.getSubagent(targetId) ?? snapshot;
720
+ if (updated.worktree && !updated.worktree.cleanedUp) {
721
+ const wt = updated.worktree;
722
+ const isDirty = Boolean(wt.isDirty || (wt.uncommittedCount ?? 0) > 0 || (wt.aheadCount ?? 0) > 0);
723
+ if (isDirty) {
724
+ const dirtyId = shortId(targetId);
725
+ return text(pick(getLang(), `子代理 ${dirtyId} 的工作树存在未合并改动,无法移出(静默移出会丢失代码):\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) 清理。`, `Subagent ${dirtyId} has unmerged worktree changes and cannot be dismissed (silent dismissal would lose code):\n- Path: ${wt.path}\n- Branch: ${wt.branch}\n- Changes: ${wt.uncommittedCount ?? 0} uncommitted file(s), ${wt.aheadCount ?? 0} commit(s) ahead\nPlease merge the branch (git merge ${wt.branch}) or discard changes via worktree(action="remove", path="${wt.path}", force=true).`, "subagents.dismiss.worktree.dirty", {
726
+ dirtyId,
727
+ path: wt.path,
728
+ branch: wt.branch,
729
+ uncommitted: wt.uncommittedCount ?? 0,
730
+ ahead: wt.aheadCount ?? 0,
731
+ }));
732
+ }
733
+ }
734
+ const res = await host.dismissSubagent(targetId, {
735
+ force: p.force,
736
+ includePersisted: p.includePersisted,
737
+ });
738
+ if (!res.ok) {
739
+ const failedId = shortId(targetId);
740
+ return text(pick(getLang(), `移出子代理 ${failedId} 失败:${res.reason ?? "未知原因"}。`, `Failed to dismiss subagent ${failedId}: ${res.reason ?? "unknown reason"}.`, "subagents.dismiss.failed", { failedId, reason: res.reason ?? "unknown" }));
741
+ }
742
+ const doneId = shortId(targetId);
743
+ 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: [] });
744
+ }
745
+ candidateIds.sort((a, b) => depthOf(b) - depthOf(a));
746
+ const dismissed = [];
747
+ const skipped = [];
748
+ for (const targetId of candidateIds) {
749
+ const snapshot = host.getSubagent(targetId);
750
+ if (!snapshot) {
751
+ skipped.push({ runId: targetId, reason: "not_found" });
752
+ continue;
753
+ }
754
+ if (selfId && targetId === selfId) {
755
+ skipped.push({ runId: targetId, reason: "self" });
756
+ continue;
757
+ }
758
+ if (activeConvId && targetId === activeConvId) {
759
+ skipped.push({ runId: targetId, reason: "active" });
760
+ continue;
761
+ }
762
+ if (selfId && !isDescendantOf(targetId, selfId)) {
763
+ skipped.push({ runId: targetId, reason: "not_descendant" });
764
+ continue;
765
+ }
766
+ if (snapshot.persisted && !p.includePersisted) {
767
+ skipped.push({ runId: targetId, reason: "persisted" });
768
+ continue;
769
+ }
770
+ const isRunning = snapshot.streaming || snapshot.state === "running";
771
+ if (isRunning && !p.force) {
772
+ skipped.push({ runId: targetId, reason: "running" });
773
+ continue;
774
+ }
775
+ if (host.finalizeSubagentWorktree) {
776
+ await host.finalizeSubagentWorktree(targetId);
777
+ }
778
+ const updated = host.getSubagent(targetId) ?? snapshot;
779
+ if (updated.worktree && !updated.worktree.cleanedUp) {
780
+ const wt = updated.worktree;
781
+ const isDirty = Boolean(wt.isDirty || (wt.uncommittedCount ?? 0) > 0 || (wt.aheadCount ?? 0) > 0);
782
+ if (isDirty) {
783
+ skipped.push({ runId: targetId, reason: "dirty_worktree" });
784
+ continue;
785
+ }
786
+ }
787
+ const res = await host.dismissSubagent(targetId, {
788
+ force: p.force,
789
+ includePersisted: p.includePersisted,
790
+ });
791
+ if (res.ok) {
792
+ dismissed.push(targetId);
793
+ }
794
+ else {
795
+ skipped.push({ runId: targetId, reason: res.reason ?? "failed" });
796
+ }
797
+ }
798
+ if (dismissed.length === 0) {
799
+ if (isFinishedAll) {
800
+ return text(pick(getLang(), "没有可移出的已结束子代理。", "No finished subagents to dismiss.", "subagents.dismiss.finished_all.empty"), { dismissed: [], skipped });
801
+ }
802
+ return text(pick(getLang(), "没有成功移出任何子代理。", "No subagents were dismissed.", "subagents.dismiss.none"), { dismissed: [], skipped });
803
+ }
804
+ const skippedCount = skipped.length;
805
+ const skippedZh = skippedCount > 0 ? `(${skippedCount} 个已跳过)` : "";
806
+ const skippedEn = skippedCount > 0 ? ` (${skippedCount} skipped)` : "";
807
+ 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 });
808
+ }
467
809
  default:
468
- return text(pick(getLang(), `未知 action:${action}。支持的 action:spawn, get_result, steer, list, stop, wait_all, templates, handoff。`, `Unknown action: ${action}. Supported actions: spawn, get_result, steer, list, stop, wait_all, templates, handoff.`, "subagents.action.unknown", { action }));
810
+ return text(pick(getLang(), `未知 action:${action}。支持的 action:spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss。`, `Unknown action: ${action}. Supported actions: spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss.`, "subagents.action.unknown", { action }));
469
811
  }
470
812
  },
471
813
  });