pi-web-ui 0.111.0 → 0.112.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 (77) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/dist/server/agent-service.js +1325 -488
  4. package/dist/server/approval-audit.js +119 -0
  5. package/dist/server/approval-default-rules.js +4 -4
  6. package/dist/server/approval-rules.js +42 -17
  7. package/dist/server/attachment-store.js +8 -8
  8. package/dist/server/canvas/canvas-agent-tool.js +6 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +88 -21
  10. package/dist/server/client-state.js +28 -0
  11. package/dist/server/delegate-mode.js +6 -3
  12. package/dist/server/delegate-task.js +18 -3
  13. package/dist/server/dispatch-domain-handlers.js +3 -0
  14. package/dist/server/dsh/dsh-agent-service.js +242 -11
  15. package/dist/server/dsh/dsh-serialize.js +1 -1
  16. package/dist/server/durable/durable-driver.js +75 -9
  17. package/dist/server/durable/durable-loader.js +1 -14
  18. package/dist/server/durable/durable-models.js +107 -0
  19. package/dist/server/durable/index.js +0 -4
  20. package/dist/server/engine-probe.js +76 -37
  21. package/dist/server/eval-tool.js +28 -3
  22. package/dist/server/goal-service.js +7 -0
  23. package/dist/server/index.js +344 -56
  24. package/dist/server/json-utils.js +57 -0
  25. package/dist/server/marker-service.js +8 -0
  26. package/dist/server/message-window.js +43 -10
  27. package/dist/server/model-admin.js +68 -106
  28. package/dist/server/model-resolver.js +66 -44
  29. package/dist/server/plan-manager.js +3 -6
  30. package/dist/server/plugin-api-catalog.js +1 -0
  31. package/dist/server/plugin-assets.js +238 -0
  32. package/dist/server/plugin-facilities.js +22 -0
  33. package/dist/server/plugin-ui-slots.js +1 -0
  34. package/dist/server/plugins.js +199 -5
  35. package/dist/server/preset-fields.js +25 -1
  36. package/dist/server/preset-share.js +5 -2
  37. package/dist/server/prompt-assembler.js +2 -1
  38. package/dist/server/prompt-composer.js +18 -8
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/queue-utils.js +156 -0
  41. package/dist/server/sdk-builtin-extensions.js +85 -0
  42. package/dist/server/server-config.js +66 -0
  43. package/dist/server/session-parser.js +49 -13
  44. package/dist/server/session-search.js +4 -3
  45. package/dist/server/settings-service.js +38 -5
  46. package/dist/server/soft-cap.js +8 -6
  47. package/dist/server/subagent-helpers.js +22 -1
  48. package/dist/server/subagent-notify.js +93 -0
  49. package/dist/server/subagent-security-gate.js +282 -0
  50. package/dist/server/subagent-templates.js +8 -0
  51. package/dist/server/subagents.js +144 -17
  52. package/dist/server/terminals.js +196 -8
  53. package/dist/server/text-quote.js +61 -0
  54. package/dist/server/tool-approval.js +63 -4
  55. package/dist/server/tool-guards.js +208 -0
  56. package/dist/server/tool-host-factories.js +46 -10
  57. package/dist/server/tool-overrides.js +21 -11
  58. package/dist/server/universal/driver-base.js +8 -0
  59. package/dist/server/universal/drivers/claude-code.js +20 -3
  60. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  61. package/dist/server/universal/index.js +0 -1
  62. package/dist/server/universal/universal-session.js +87 -10
  63. package/dist/server/worktree-service.js +189 -1
  64. package/docs/dsh-engine.md +1 -5
  65. package/package.json +1 -1
  66. package/plugin-sdk/client-utils.mjs +192 -5
  67. package/plugin-sdk/index.d.ts +63 -1
  68. package/plugin-sdk/index.mjs +94 -0
  69. package/plugin-sdk/package.json +5 -1
  70. package/plugins/catalog.json +11 -0
  71. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-Dqr1dK28.js} +1 -1
  72. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  73. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  74. package/web/dist/index.html +11 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B0ajS__T.js +0 -697
  77. 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,19 @@ 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(),
74
87
  };
75
88
  }
76
89
  export const SUBAGENT_TOOL_NAME = "subagent";
@@ -142,7 +155,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
142
155
  description: "handoff: source ID (default = this subagent).",
143
156
  })),
144
157
  type: Type.Optional(Type.String({
145
- description: "spawn: role/type (e.g. explore/implement/review, default: general).",
158
+ 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
159
  })),
147
160
  template: Type.Optional(Type.String({
148
161
  description: "spawn: template name (see action=templates).",
@@ -150,12 +163,23 @@ export function makeSubagentTool(host, lang, selfConvId) {
150
163
  model: Type.Optional(Type.String({
151
164
  description: 'spawn: model override "provider/id".',
152
165
  })),
166
+ thinking: Type.Optional(Type.String({
167
+ enum: [...THINKING_LEVELS],
168
+ description: 'spawn: thinking budget level ("off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max").',
169
+ })),
170
+ notifyOnDone: Type.Optional(Type.Boolean({
171
+ description: "spawn: notify and wake parent conversation when finished (default: true).",
172
+ })),
153
173
  cwd: Type.Optional(Type.String({
154
174
  description: "spawn: working directory (default = current).",
155
175
  })),
156
176
  persist: Type.Optional(Type.Boolean({
157
177
  description: "spawn: persist as a regular session (default = ephemeral).",
158
178
  })),
179
+ isolation: Type.Optional(Type.String({
180
+ enum: ["worktree", "none"],
181
+ description: 'spawn: workspace isolation mode ("worktree" creates a dedicated git worktree & branch; "none" = shared cwd).',
182
+ })),
159
183
  kind: Type.Optional(Type.String({
160
184
  enum: ["all", "subagent", "persistent"],
161
185
  description: "list: filter subagents by kind (default: all).",
@@ -176,12 +200,47 @@ export function makeSubagentTool(host, lang, selfConvId) {
176
200
  if (!p.prompt || typeof p.prompt !== "string" || !p.prompt.trim()) {
177
201
  return text(pick(getLang(), 'subagent(action="spawn") 缺少 prompt 参数。', 'subagent(action="spawn") requires prompt parameter.', "subagents.spawn.missing.prompt"));
178
202
  }
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 }));
203
+ let templateName;
204
+ if (p.template) {
205
+ if (!host.isTemplateUsable(p.template)) {
206
+ 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 }));
207
+ }
208
+ templateName = p.template.trim();
209
+ }
210
+ else if (p.type && typeof p.type === "string" && host.isTemplateUsable(p.type.trim())) {
211
+ templateName = p.type.trim();
212
+ }
213
+ if (p.thinking && !THINKING_LEVELS.includes(p.thinking)) {
214
+ 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(", ") }));
215
+ }
216
+ const isolationMode = p.isolation?.trim().toLowerCase();
217
+ if (isolationMode && isolationMode !== "worktree" && isolationMode !== "none") {
218
+ 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
219
  }
182
220
  let convId;
221
+ const subagentType = p.type ?? "general";
222
+ const matchedTemplate = templateName ? host.listTemplates().find((t) => t.name === templateName) : undefined;
223
+ const securityMode = resolveSecurityMode(subagentType, matchedTemplate);
224
+ const extra = securityMode !== "normal" ? { securityMode } : undefined;
183
225
  try {
184
- convId = await host.spawnSubagent(p.prompt, p.type ?? "general", p.cwd ?? ctx.cwd, p.template, p.model, undefined, p.persist);
226
+ const spawnArgs = [
227
+ p.prompt,
228
+ subagentType,
229
+ p.cwd ?? ctx.cwd,
230
+ templateName,
231
+ p.model,
232
+ undefined,
233
+ p.persist,
234
+ p.thinking,
235
+ p.notifyOnDone,
236
+ ];
237
+ if (isolationMode === "worktree" || extra !== undefined) {
238
+ spawnArgs.push(isolationMode === "worktree" ? "worktree" : undefined);
239
+ }
240
+ if (extra !== undefined) {
241
+ spawnArgs.push(extra);
242
+ }
243
+ convId = await host.spawnSubagent(...spawnArgs);
185
244
  }
186
245
  catch (err) {
187
246
  const msg = err instanceof Error ? err.message : String(err);
@@ -189,36 +248,56 @@ export function makeSubagentTool(host, lang, selfConvId) {
189
248
  error: msg,
190
249
  }));
191
250
  }
192
- const subagentType = p.type ?? "general";
193
251
  const subagentTitleText = subagentTitle(p.prompt);
194
- const templateLineZh = p.template ? `\n模板:${p.template}` : "";
195
- const templateLineEn = p.template ? `\nTemplate: ${p.template}` : "";
252
+ const templateLineZh = templateName ? `\n模板:${templateName}` : "";
253
+ const templateLineEn = templateName ? `\nTemplate: ${templateName}` : "";
196
254
  const modelLineZh = p.model ? `\n模型:${p.model}` : "";
197
255
  const modelLineEn = p.model ? `\nModel: ${p.model}` : "";
256
+ const thinkingLineZh = p.thinking ? `\n思考强度:${p.thinking}` : "";
257
+ const thinkingLineEn = p.thinking ? `\nThinking: ${p.thinking}` : "";
258
+ const notifyLineZh = p.notifyOnDone === false ? "\n自动通知:已关闭" : "";
259
+ const notifyLineEn = p.notifyOnDone === false ? "\nAuto-notify: disabled" : "";
260
+ const isolationLineZh = isolationMode === "worktree" ? "\n工作树隔离:已启用(独立 Git 工作树与分支)" : "";
261
+ const isolationLineEn = isolationMode === "worktree" ? "\nWorktree isolation: enabled (dedicated Git worktree & branch)" : "";
198
262
  const kindLabelZh = p.persist ? "普通持久化对话" : "子代理";
199
263
  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}` +
264
+ return text(pick(getLang(), `${kindLabelZh}已启动(运行列表可见):${convId}\n类型:${subagentType} · 标题:${subagentTitleText}${templateLineZh}${modelLineZh}${thinkingLineZh}${notifyLineZh}${isolationLineZh}` +
265
+ `\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
266
  `\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
267
  convId,
204
268
  subagentType,
205
269
  subagentTitleText,
206
270
  "p.template": p.template,
207
271
  "p.model": p.model,
272
+ "p.thinking": p.thinking,
208
273
  templateLineZh,
209
274
  templateLineEn,
210
275
  modelLineZh,
211
276
  modelLineEn,
277
+ thinkingLineZh,
278
+ thinkingLineEn,
279
+ notifyLineZh,
280
+ notifyLineEn,
281
+ isolationLineZh,
282
+ isolationLineEn,
212
283
  kindLabel: kindLabelEn,
213
284
  kindLabelEn,
214
285
  kindLabelZh,
215
- }), { convId, template: p.template, model: p.model, persisted: !!p.persist });
286
+ }), {
287
+ convId,
288
+ template: p.template,
289
+ model: p.model,
290
+ thinking: p.thinking,
291
+ persisted: !!p.persist,
292
+ notifyOnDone: p.notifyOnDone !== false,
293
+ isolation: isolationMode === "worktree" ? "worktree" : undefined,
294
+ });
216
295
  }
217
296
  case "get_result": {
218
297
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
219
298
  return text(pick(getLang(), 'subagent(action="get_result") 缺少 runId 参数。', 'subagent(action="get_result") requires runId parameter.', "subagents.get.missing.runId"));
220
299
  }
221
- const r = host.getSubagent(p.runId);
300
+ let r = host.getSubagent(p.runId);
222
301
  const missingId = shortId(p.runId);
223
302
  if (!r)
224
303
  return text(pick(getLang(), `未找到子代理 ${missingId}(可能已移出)。`, `Subagent ${missingId} not found (may have been dismissed).`, "subagents.get.not.found", { missingId }), undefined);
@@ -226,12 +305,29 @@ export function makeSubagentTool(host, lang, selfConvId) {
226
305
  const doneId = shortId(r.convId);
227
306
  const doneDetail = verdictText(r, getLang());
228
307
  const doneOutput = r.output || (getLang() === "zh" ? "(无结果)" : "(no result)");
308
+ const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
229
309
  if (r.streaming || r.state === "running") {
230
310
  const runningId = shortId(r.convId);
231
311
  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);
312
+ 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);
233
313
  }
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);
314
+ // 终态结果被父对话取走,标记已消费,避免后续重复触发自动通知
315
+ host.markSubagentsConsumed?.([p.runId]);
316
+ if (host.finalizeSubagentWorktree) {
317
+ await host.finalizeSubagentWorktree(p.runId);
318
+ r = host.getSubagent(p.runId) ?? r;
319
+ }
320
+ let worktreeDetail = "";
321
+ if (r.worktree) {
322
+ const wt = r.worktree;
323
+ if (wt.cleanedUp) {
324
+ 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");
325
+ }
326
+ else {
327
+ 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 });
328
+ }
329
+ }
330
+ 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
331
  }
236
332
  case "steer": {
237
333
  if (!p.runId || typeof p.runId !== "string" || !p.runId.trim()) {
@@ -261,7 +357,8 @@ export function makeSubagentTool(host, lang, selfConvId) {
261
357
  : tLang === "zh"
262
358
  ? "子代理"
263
359
  : "subagent";
264
- return (`- ${r.convId} · ${r.type} · ${subagentVerdict(r, tLang)} · ${r.title}` +
360
+ const modelTag = r.model ? ` · ${r.model}${r.thinkingLevel ? `:${r.thinkingLevel}` : ""}` : "";
361
+ return (`- ${r.convId} · ${r.type}${modelTag} · ${subagentVerdict(r, tLang)} · ${r.title}` +
265
362
  (tLang === "zh" ? `(${tag} · msg: ${r.messageCount})` : ` (${tag} · msg: ${r.messageCount})`));
266
363
  });
267
364
  return text(lines.join("\n"));
@@ -359,7 +456,11 @@ export function makeSubagentTool(host, lang, selfConvId) {
359
456
  if (wanted.size === 0) {
360
457
  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
458
  }
362
- const timeoutMs = Math.min(Math.max(p.timeoutSeconds ?? capSeconds, 1), capSeconds) * 1000;
459
+ const liveWaitCapMs = typeof host.getWatchdogTimeoutMs === "function"
460
+ ? computeWaitCapMs(host.getWatchdogTimeoutMs())
461
+ : currentWaitCapMs;
462
+ const liveCapSeconds = Math.floor(liveWaitCapMs / 1000);
463
+ const timeoutMs = Math.min(Math.max(p.timeoutSeconds ?? liveCapSeconds, 1), liveCapSeconds) * 1000;
363
464
  const startedAt = Date.now();
364
465
  const POLL_INTERVAL_MS = 250;
365
466
  while (!signal?.aborted && Date.now() - startedAt < timeoutMs) {
@@ -384,6 +485,17 @@ export function makeSubagentTool(host, lang, selfConvId) {
384
485
  const tLang = getLang();
385
486
  const waitedSecs = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
386
487
  const timeoutSecs = Math.round(timeoutMs / 1000);
488
+ // 收口的子代理标记已消费,避免后续重复自动通知打扰父对话;同时结算隔离工作树
489
+ const finishedIds = Array.from(wanted).filter((id) => {
490
+ const r = host.getSubagent(id);
491
+ return r === undefined || isSubagentTerminal(r);
492
+ });
493
+ if (finishedIds.length > 0) {
494
+ host.markSubagentsConsumed?.(finishedIds);
495
+ if (host.finalizeSubagentWorktree) {
496
+ await Promise.all(finishedIds.map((id) => host.finalizeSubagentWorktree(id)));
497
+ }
498
+ }
387
499
  const lines = Array.from(wanted)
388
500
  .map((id) => {
389
501
  const r = host.getSubagent(id);
@@ -394,7 +506,22 @@ export function makeSubagentTool(host, lang, selfConvId) {
394
506
  const verdict = subagentVerdict(r, tLang);
395
507
  const detail = verdictText(r, tLang);
396
508
  const out = clipSubagentOutput(r.output || (tLang === "zh" ? "(无输出)" : "(no output)"), tLang);
397
- return `- ${sId}(${r.type} · ${verdict} · ${r.title})${detail ? ` · ${detail}` : ""}:\n${out}`;
509
+ let wtTag = "";
510
+ let wtPathInfo = "";
511
+ if (r.worktree) {
512
+ if (r.worktree.cleanedUp) {
513
+ wtTag = tLang === "zh" ? " · 工作树已清理" : " · worktree cleaned";
514
+ }
515
+ else {
516
+ wtTag =
517
+ tLang === "zh"
518
+ ? ` · 工作树保留: ${r.worktree.branch} (${r.worktree.uncommittedCount ?? 0} 改动, +${r.worktree.aheadCount ?? 0} 提交)`
519
+ : ` · worktree kept: ${r.worktree.branch} (${r.worktree.uncommittedCount ?? 0} dirty, +${r.worktree.aheadCount ?? 0} commits)`;
520
+ wtPathInfo =
521
+ tLang === "zh" ? `\n - 工作树路径:${r.worktree.path}` : `\n - Worktree path: ${r.worktree.path}`;
522
+ }
523
+ }
524
+ return `- ${sId}(${r.type} · ${verdict} · ${r.title}${wtTag})${detail ? ` · ${detail}` : ""}:\n${out}${wtPathInfo}`;
398
525
  })
399
526
  .join("\n\n");
400
527
  const remaining = Array.from(wanted).filter((id) => {
@@ -900,12 +900,62 @@ export function encodeTerminalKey(key, modifiers = {}) {
900
900
  }
901
901
  return { data };
902
902
  }
903
+ /**
904
+ * 终端行输入流状态机解析(纯函数,issue #721)。
905
+ *
906
+ * 结合前次未完成的行缓冲与本次输入字符,按换行符(CR / LF / CRLF)切分出
907
+ * 全部已闭合的完整命令行,并正确处理退格(Backspace)与中断清除(Ctrl+C / Ctrl+U)。
908
+ */
909
+ export function parseTerminalLineStream(previousPending, inputChunk) {
910
+ const completedLines = [];
911
+ let current = previousPending;
912
+ let i = 0;
913
+ while (i < inputChunk.length) {
914
+ const ch = inputChunk[i];
915
+ if (ch === "\r" || ch === "\n") {
916
+ completedLines.push(current);
917
+ current = "";
918
+ // 处理 CRLF 双字符换行:若为 \r 且后一个字符是 \n,跳过后续 \n
919
+ if (ch === "\r" && i + 1 < inputChunk.length && inputChunk[i + 1] === "\n") {
920
+ i++;
921
+ }
922
+ }
923
+ else if (ch === "\x03" || ch === "\x15") {
924
+ // Ctrl+C (ETX) 或 Ctrl+U (NAK) 清除当前行
925
+ current = "";
926
+ }
927
+ else if (ch === "\x7f" || ch === "\x08") {
928
+ // 退格键 Backspace
929
+ if (current.length > 0) {
930
+ current = current.slice(0, -1);
931
+ }
932
+ }
933
+ else {
934
+ current += ch;
935
+ }
936
+ i++;
937
+ }
938
+ return {
939
+ completedLines,
940
+ remainingPending: current,
941
+ };
942
+ }
903
943
  /**
904
944
  * Owns one or more PTYs for a conversation. All output is forwarded as
905
945
  * `terminal_output` messages through the provided emit (broadcast to every
906
946
  * socket attached to the client session). Failed spawns emit an error notice and
907
947
  * terminal_exit instead of throwing into the WebSocket dispatcher.
908
948
  */
949
+ /**
950
+ * 识别是否属于终端仿真器自动回传的握手/探测序列(如光标位置报告 CPR、设备属性 DA1/DA2、焦点通知等)。
951
+ * 这些序列由 xterm.js 接收到 Shell/ConPTY 发出的探针后自动回复,绝非用户真实键盘输入。
952
+ * 收到此类自动响应时不应把 pristine 裸 shell 标记为 used,否则点开终端自动建的空 shell 会被永久误判为
953
+ * “用户动过的终端”并阻断会话移出。
954
+ */
955
+ export const TERMINAL_QUERY_RESPONSE_RE = /^(?:\x1b\[(?:\??|>|<)?\d*(?:;\d+)*(?:\$?y|[cRnIOt])|\x1b\]\d+;[^\x07\x1b]*(?:\x07|\x1b\\))+$/;
956
+ export function isTerminalQueryResponse(data) {
957
+ return TERMINAL_QUERY_RESPONSE_RE.test(data);
958
+ }
909
959
  export class TerminalManager {
910
960
  emit;
911
961
  workspaceRoot;
@@ -919,6 +969,22 @@ export class TerminalManager {
919
969
  /** 宿主回调:AI 触碰过的终端静默 ≥ 阈值时触发(一次性/纪元语义见
920
970
  * noteAgentActivity)。宿主自行判断会话是否在运行并决定是否注入。 */
921
971
  onAgentIdle = null;
972
+ /** 获取该终端当前被 AI 累积但尚未提交的命令行(issue #721) */
973
+ getAgentPendingLine(id) {
974
+ return this.terms.get(id)?.agentPendingLine ?? "";
975
+ }
976
+ /** 设置该终端 AI 累积的待提交行(issue #721) */
977
+ setAgentPendingLine(id, line) {
978
+ const entry = this.terms.get(id);
979
+ if (entry)
980
+ entry.agentPendingLine = line;
981
+ }
982
+ /** 清空该终端 AI 累积的待提交行(issue #721) */
983
+ clearAgentPendingLine(id) {
984
+ const entry = this.terms.get(id);
985
+ if (entry)
986
+ entry.agentPendingLine = "";
987
+ }
922
988
  constructor(emit, workspaceRoot,
923
989
  // issue #91:按键/输入校验错误按客户端 UI 语言出中英(英文默认)。
924
990
  lang) {
@@ -1171,6 +1237,7 @@ export class TerminalManager {
1171
1237
  // noteAgentActivity)。
1172
1238
  used: agentBash || command !== undefined,
1173
1239
  locale,
1240
+ agentPendingLine: "",
1174
1241
  };
1175
1242
  this.terms.set(id, entry);
1176
1243
  // The closures capture `entry`: after a restart the map points at the
@@ -1480,12 +1547,14 @@ export class TerminalManager {
1480
1547
  return pick(this.lang?.() ?? "en", "终端不存在或进程已退出", "Terminal not found or its process has exited", "terminals.not.found.exited");
1481
1548
  // 已武装的纪元里任何人(含用户手动敲键盘)写了输入都算新活动,重置倒计时。
1482
1549
  // 成功的输入同时把终端标为“用过”(见 used):动过的 shell 才参与对话保留/
1483
- // 关闭拦截,没动过的空 shell 不算。
1550
+ // 关闭拦截,没动过的空 shell 不算。仿真器自动应答探针(CPR/DA 等)不计入用过。
1484
1551
  entry.lastActivityAt = Date.now();
1485
1552
  if (entry.idleTimer)
1486
1553
  this.armIdleWatch(entry);
1487
1554
  entry.pty.write(data);
1488
- entry.used = true;
1555
+ if (data.length > 0 && !isTerminalQueryResponse(data)) {
1556
+ entry.used = true;
1557
+ }
1489
1558
  return null;
1490
1559
  }
1491
1560
  key(id, key, modifiers = {}) {
@@ -1642,6 +1711,9 @@ export class TerminalManager {
1642
1711
  this.emitList();
1643
1712
  }
1644
1713
  input(id, data) {
1714
+ if (data.includes("\r") || data.includes("\n") || data.includes("\x03")) {
1715
+ this.clearAgentPendingLine(id);
1716
+ }
1645
1717
  void this.inputChecked(id, data);
1646
1718
  }
1647
1719
  resize(id, cols, rows) {
@@ -2207,6 +2279,30 @@ lang, options) {
2207
2279
  if (error)
2208
2280
  throw new Error(error);
2209
2281
  };
2282
+ // 针对单测或外部 mock 的行缓冲兜底支持
2283
+ const fallbackPending = new Map();
2284
+ const getPending = (id) => {
2285
+ if (typeof terminals.getAgentPendingLine === "function") {
2286
+ return terminals.getAgentPendingLine(id);
2287
+ }
2288
+ return fallbackPending.get(id) ?? "";
2289
+ };
2290
+ const setPending = (id, line) => {
2291
+ if (typeof terminals.setAgentPendingLine === "function") {
2292
+ terminals.setAgentPendingLine(id, line);
2293
+ }
2294
+ else {
2295
+ fallbackPending.set(id, line);
2296
+ }
2297
+ };
2298
+ const clearPending = (id) => {
2299
+ if (typeof terminals.clearAgentPendingLine === "function") {
2300
+ terminals.clearAgentPendingLine(id);
2301
+ }
2302
+ else {
2303
+ fallbackPending.delete(id);
2304
+ }
2305
+ };
2210
2306
  return [
2211
2307
  defineTool({
2212
2308
  name: "terminal_create",
@@ -2265,13 +2361,54 @@ lang, options) {
2265
2361
  parameters: Type.Object({ terminalId: Type.String(), data: Type.String() }),
2266
2362
  execute: async (_id, p) => {
2267
2363
  const lang = getLang();
2268
- if (options?.checkSafety && (p.data.includes("\n") || p.data.includes("\r"))) {
2269
- const safety = options.checkSafety(p.data.trim());
2270
- if (safety.blocked) {
2271
- throw new Error(pick(lang, `【终端输入命令被安全规则阻断】${safety.reason ? ` 原因:${safety.reason}` : ""}`, `[Terminal command blocked by safety rule]${safety.reason ? ` Reason: ${safety.reason}` : ""}`, "terminals.command.blocked", { reason: safety.reason ?? "" }));
2364
+ const prevPending = getPending(p.terminalId);
2365
+ const parsed = parseTerminalLineStream(prevPending, p.data);
2366
+ if (options?.checkSafety && parsed.completedLines.length > 0) {
2367
+ for (const line of parsed.completedLines) {
2368
+ const cleanCmd = stripAnsi(line).trim();
2369
+ if (!cleanCmd)
2370
+ continue;
2371
+ const safety = await options.checkSafety(cleanCmd, {
2372
+ terminalId: p.terminalId,
2373
+ toolCallId: _id,
2374
+ toolName: "terminal_input",
2375
+ });
2376
+ if (safety.blocked) {
2377
+ // 发现阻断:若终端此前已留有未提交字符,发送 \x03 取消当前行
2378
+ if (prevPending) {
2379
+ try {
2380
+ terminals.inputChecked(p.terminalId, "\x03");
2381
+ }
2382
+ catch {
2383
+ // ignore
2384
+ }
2385
+ }
2386
+ clearPending(p.terminalId);
2387
+ const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
2388
+ const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
2389
+ throw new Error(safety.userDenied
2390
+ ? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
2391
+ : pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
2392
+ }
2393
+ if (safety.editedCommand !== undefined) {
2394
+ // 用户通过审批改写了命令
2395
+ if (prevPending) {
2396
+ try {
2397
+ terminals.inputChecked(p.terminalId, "\x03");
2398
+ }
2399
+ catch {
2400
+ // ignore
2401
+ }
2402
+ }
2403
+ clearPending(p.terminalId);
2404
+ failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
2405
+ terminals.noteAgentActivity(p.terminalId);
2406
+ return result(pick(lang, `已发送改写后的命令到 ${p.terminalId}:${safety.editedCommand}`, `Sent edited command to ${p.terminalId}: ${safety.editedCommand}`, "terminals.input.edited_sent", { command: safety.editedCommand, "p.terminalId": p.terminalId }));
2407
+ }
2272
2408
  }
2273
2409
  }
2274
2410
  failIf(terminals.inputChecked(p.terminalId, p.data));
2411
+ setPending(p.terminalId, parsed.remainingPending);
2275
2412
  // AI 发了输入 = 在等结果,重开一个静默纪元。
2276
2413
  terminals.noteAgentActivity(p.terminalId);
2277
2414
  return result(pick(lang, `已发送 ${p.data.length} 个字符到 ${p.terminalId}`, `Sent ${p.data.length} chars to ${p.terminalId}`, "terminals.input.sent", { "p.data.length": p.data.length, "p.terminalId": p.terminalId }));
@@ -2294,8 +2431,59 @@ lang, options) {
2294
2431
  }),
2295
2432
  execute: async (_id, p) => {
2296
2433
  const lang = getLang();
2297
- failIf(terminals.key(p.terminalId, p.key, p.modifiers));
2298
- // 同 terminal_input:AI 主动交互后重新计时。
2434
+ const encoded = encodeTerminalKey(p.key, p.modifiers);
2435
+ if ("error" in encoded)
2436
+ throw new Error(encoded.error);
2437
+ const isEnter = encoded.data.includes("\r") || encoded.data.includes("\n");
2438
+ if (isEnter) {
2439
+ const pending = getPending(p.terminalId);
2440
+ const cleanCmd = stripAnsi(pending).trim();
2441
+ if (options?.checkSafety && cleanCmd) {
2442
+ const safety = await options.checkSafety(cleanCmd, {
2443
+ terminalId: p.terminalId,
2444
+ toolCallId: _id,
2445
+ toolName: "terminal_key",
2446
+ });
2447
+ if (safety.blocked) {
2448
+ // 阻断 Enter 提交:发送 \x03 冲刷取消终端屏幕残留的脏命令
2449
+ try {
2450
+ terminals.inputChecked(p.terminalId, "\x03");
2451
+ }
2452
+ catch {
2453
+ // ignore
2454
+ }
2455
+ clearPending(p.terminalId);
2456
+ const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
2457
+ const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
2458
+ throw new Error(safety.userDenied
2459
+ ? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
2460
+ : pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
2461
+ }
2462
+ if (safety.editedCommand !== undefined) {
2463
+ // 用户在审批弹窗中改写了命令:先取消原行,再提交改写后的命令
2464
+ try {
2465
+ terminals.inputChecked(p.terminalId, "\x03");
2466
+ }
2467
+ catch {
2468
+ // ignore
2469
+ }
2470
+ clearPending(p.terminalId);
2471
+ failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
2472
+ terminals.noteAgentActivity(p.terminalId);
2473
+ return result(pick(lang, `已发送改写后的命令到 ${p.terminalId}:${safety.editedCommand}`, `Sent edited command to ${p.terminalId}: ${safety.editedCommand}`, "terminals.key.edited_sent", { command: safety.editedCommand, "p.terminalId": p.terminalId }));
2474
+ }
2475
+ }
2476
+ // 提交回车成功
2477
+ failIf(terminals.inputChecked(p.terminalId, encoded.data));
2478
+ clearPending(p.terminalId);
2479
+ terminals.noteAgentActivity(p.terminalId);
2480
+ return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
2481
+ }
2482
+ // 非回车按键:若为退格或清除键,更新 pending 缓冲
2483
+ const prev = getPending(p.terminalId);
2484
+ const parsed = parseTerminalLineStream(prev, encoded.data);
2485
+ failIf(terminals.inputChecked(p.terminalId, encoded.data));
2486
+ setPending(p.terminalId, parsed.remainingPending);
2299
2487
  terminals.noteAgentActivity(p.terminalId);
2300
2488
  return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
2301
2489
  },
@@ -62,6 +62,67 @@ export function formatStreamingPrompt(text, textAsides = [], quotes = [], imageN
62
62
  }
63
63
  return parts.join("\n\n");
64
64
  }
65
+ /**
66
+ * 将附件消息(asides)解构为流式排队/插队可消费的载荷。
67
+ * 统一作为单源解析,杜绝空闲/流式分支错位造成的丢图、漏附件与非视觉模型静默丢弃。
68
+ */
69
+ export function extractStreamingPayload(asides, initialQuotes = [], mainSupportsVision = false, modelLabel = "unknown") {
70
+ const promptImages = [];
71
+ const textAsides = [];
72
+ const imageNames = [];
73
+ const quotes = [...initialQuotes];
74
+ for (const aside of asides) {
75
+ const details = aside.message?.details;
76
+ const isBridged = details?.mode === "bridged";
77
+ const isQuote = details?.mode === "quote";
78
+ if (isQuote && details?.quote) {
79
+ const q = readTextQuote(details.quote);
80
+ if (q) {
81
+ quotes.push(q);
82
+ continue;
83
+ }
84
+ }
85
+ const rawContent = aside.message?.content;
86
+ if (typeof rawContent === "string") {
87
+ if (rawContent.trim())
88
+ textAsides.push(rawContent.trim());
89
+ continue;
90
+ }
91
+ const content = Array.isArray(rawContent) ? rawContent : [];
92
+ for (const b of content) {
93
+ if (typeof b === "string") {
94
+ if (b.trim())
95
+ textAsides.push(b.trim());
96
+ continue;
97
+ }
98
+ if (!b || typeof b !== "object")
99
+ continue;
100
+ const block = b;
101
+ if (block.type === "image" && typeof block.data === "string") {
102
+ const imgName = details?.name ?? "image.png";
103
+ if (mainSupportsVision) {
104
+ promptImages.push({
105
+ type: "image",
106
+ data: block.data,
107
+ mimeType: typeof block.mimeType === "string" && block.mimeType ? block.mimeType : "image/png",
108
+ });
109
+ imageNames.push(imgName);
110
+ }
111
+ else if (!isBridged) {
112
+ imageNames.push(imgName);
113
+ textAsides.push(`[Attached image "${imgName}" omitted: model (${modelLabel}) does not support vision]`);
114
+ }
115
+ }
116
+ else if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
117
+ textAsides.push(block.text.trim());
118
+ if (isBridged && details?.name) {
119
+ imageNames.push(details.name);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ return { promptImages, textAsides, imageNames, quotes };
125
+ }
65
126
  /** 排队项把引用与附件随提问一起保存;展示时拆分末尾的引用块与附件标记。 */
66
127
  export function splitQuotedPrompt(value) {
67
128
  let text = value;