pi-web-ui 0.110.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  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/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -15,14 +15,16 @@
15
15
  // wholesale (no union merge / no stale built-in leftovers).
16
16
  import "./patch-remote-catalog.js";
17
17
  import "./patch-turn-end-boundary.js";
18
+ import { formatSubagentsCompletionNotice } from "./subagent-notify.js";
18
19
  import { spawn } from "node:child_process";
19
20
  import { createHash, randomUUID } from "node:crypto";
20
21
  import * as fsPromises from "node:fs/promises";
21
22
  import { DEFAULT_PI_CAPABILITIES } from "./engine-capabilities.js";
22
- import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, mkdirSync, watch, writeFileSync, } from "node:fs";
23
+ import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, mkdirSync, statSync, watch, writeFileSync, } from "node:fs";
23
24
  import { homedir } from "node:os";
24
25
  import { basename, delimiter, join, resolve } from "node:path";
25
- import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createCodemodeExtension, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, createToolSearchExtension, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
26
+ import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
27
+ import { getSdkBuiltinExtensionFactories, SDK_DISABLED_BUILTIN_EXTENSIONS } from "./sdk-builtin-extensions.js";
26
28
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
27
29
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
28
30
  import { collectInstalledEngineTargets } from "./engine-probe.js";
@@ -33,7 +35,7 @@ import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundT
33
35
  import { COMPACTION_PENDING_TYPE, looksLikeChainCorruption, makeCompactionMarkerId, repairSessionFile, } from "./compaction-markers.js";
34
36
  import { calibrateSessionLeaf } from "./session-branch.js";
35
37
  import { danglingToolResultText, findDanglingToolCalls, healDanglingToolCallFile, } from "./dangling-tools.js";
36
- import { removeQueuedByIndexOrText } from "./queue-utils.js";
38
+ import { removeQueuedByIndexOrText, removeQueuedEntry, rollbackQueuedEntry, reconcileQueuedEntries, createQueuedEntry, toQueuedPromptItems, } from "./queue-utils.js";
37
39
  import { syncPluginToolsIntoSession } from "./plugins.js";
38
40
  import { modelChangeKey, pickClientConversation } from "./plugin-conversation-view.js";
39
41
  import { SettingsService } from "./settings-service.js";
@@ -44,7 +46,7 @@ import { SlashCommandsService, parseSlash } from "./slash-commands.js";
44
46
  import { ModelAdminService } from "./model-admin.js";
45
47
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
46
48
  import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
47
- import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
49
+ import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, defaultSubagentAutoWakeMaxTurns, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
48
50
  import { isTraditionalLocale, pick, resolveServerLang } from "./i18n.js";
49
51
  import { SubagentTemplatesStore, localizeTemplate, pickTemplatePrompt, } from "./subagent-templates.js";
50
52
  import { ApprovalRulesStore } from "./approval-rules.js";
@@ -59,24 +61,27 @@ import { fillSkillContents } from "./skill-content-filler.js";
59
61
  import { estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
60
62
  import { formatSubagentHandoffMessage, recordSubagentHandoff } from "./subagent-handoff.js";
61
63
  import { executeContextBudgetPruning } from "./context-budget-runner.js";
62
- import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, } from "./tool-approval.js";
64
+ import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, pluginApprovalCategory, } from "./tool-approval.js";
63
65
  import { PlanManager } from "./plan-manager.js";
66
+ import { ApprovalAuditLogger } from "./approval-audit.js";
67
+ export { ApprovalAuditLogger };
64
68
  import { buildPlanModePrompt, planModeDenial, planModeNoticeText, PLAN_MODE_BLOCKED_TOOL_NAMES } from "./plan-mode.js";
65
- import { DELEGATION_SYSTEM_PROMPT, delegateNoticeText } from "./delegate-mode.js";
69
+ import { DELEGATE_MODE_BLOCKED_TOOL_NAMES, DELEGATION_SYSTEM_PROMPT, delegateNoticeText } from "./delegate-mode.js";
66
70
  import { goalReviewDenial, shouldDeferPromptForReview } from "./goal-review-gate.js";
67
71
  import { readPlanModeFromSession, readPlanFromSession } from "./permission-preset.js";
68
72
  import { readDelegateModeFromSession } from "./permission-preset.js";
69
- import { makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE } from "./terminals.js";
73
+ import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
70
74
  import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
71
75
  import { makeLoadToolsTool } from "./load-tools-tool.js";
72
76
  import { formatCompactSignature } from "./tool-signature.js";
73
77
  import { WebUIContext } from "./webui-context.js";
74
- import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, softCapToReserve } from "./soft-cap.js";
78
+ import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, SOFT_CAP_MIN_TOKENS, SOFT_CAP_MIN_HEADROOM, } from "./soft-cap.js";
75
79
  import { makeEditSoftTool } from "./edit-soft-tool.js";
76
80
  // 覆盖 SDK 内置 read:路径是目录时列出目录条目(行为开关 readDirEnabled,默认开)。
77
81
  // 覆盖定义与「与扩展同名工具共存」的注入辅助分在两个文件(后者的依据见 tool-overrides.ts)。
78
82
  import { makeReadDirTool, withReadDirSupport } from "./read-tool.js";
79
83
  import { installToolOverrides, syncSubagentOverride, } from "./tool-overrides.js";
84
+ import { resolveSecurityMode, subagentSecurityDenial, withSubagentSecurityGate, SUBAGENT_WRITE_TOOL_NAMES, } from "./subagent-security-gate.js";
80
85
  // 展示文件给用户(present_files):图片/视频内联、文本开预览弹窗、本地打开按钮。
81
86
  import { makePresentFilesTool } from "./present-files-tool.js";
82
87
  // 主动压缩上下文工具(compact_context):AI 主动根据当前问题精简上下文并自主控制范围。
@@ -101,11 +106,12 @@ import { makeLspTool } from "./lsp-tool.js";
101
106
  import { makeMcpManageTool } from "./mcp-agent-tool.js";
102
107
  import { makeSandboxTool } from "./sandbox-tool.js";
103
108
  import { makeWorktreeTool } from "./worktree-tool.js";
109
+ import { makeCanvasTool } from "./canvas/canvas-agent-tool.js";
104
110
  import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktree-service.js";
105
111
  import { sameSessionFile } from "./scheduler-tasks.js";
106
112
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
107
113
  import { scanAtMentions } from "./universal/universal-attachments.js";
108
- import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
114
+ import { extractStreamingPayload, formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt, } from "./text-quote.js";
109
115
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
110
116
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
111
117
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
@@ -135,6 +141,8 @@ const DELTA_ACTIVE_WINDOW_MS = 1500;
135
141
  */
136
142
  const STATS_CACHE_MS = 250;
137
143
  const WIDGET_REFRESH_MS = 2000;
144
+ /** 创建时未注入派发工具的子代理会话(模块级:过户跨 ClientSession 仍认得),syncSubagentOverride 不得再补回内置 subagent。 */
145
+ const SPAWN_TOOLS_BARRED = new WeakSet();
138
146
  /** Model-stall watchdog: warn (don't abort — deep thinking can be legitimately
139
147
  * quiet for minutes) when a streaming run produced NO SDK events for this long.
140
148
  * Covers the failure class the per-tool watchdog cannot see: half-open API
@@ -195,8 +203,8 @@ import { splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-
195
203
  export { splitAgentStartPrompt };
196
204
  import { makeKillableBashTool, makeAdaptiveBashTool } from "./bash-tool.js";
197
205
  export { makeKillableBashTool, makeAdaptiveBashTool };
198
- import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, } from "./tool-guards.js";
199
- export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, };
206
+ import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, } from "./tool-guards.js";
207
+ export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, };
200
208
  import { normalizeSolPlanToPlanSteps, makePlanUpdateTool } from "./plan-update-tool.js";
201
209
  export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
202
210
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
@@ -210,6 +218,39 @@ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRec
210
218
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
211
219
  export { pickAdoptableOrphan, sameCwd };
212
220
  import { processTreeKillPlan, resolveCwdTarget } from "./process-utils.js";
221
+ /**
222
+ * 清扫异常退出/崩溃后遗留的孤儿临时会话目录(subagent-sessions / ephemeral-sessions)。
223
+ * 默认清理超过 TTL(24h)的临时目录,避免无上限累积。
224
+ */
225
+ export function cleanupOrphanedSessionDirs(agentDir, maxAgeMs = 24 * 3600_000) {
226
+ const cutoff = Date.now() - maxAgeMs;
227
+ for (const sub of ["subagent-sessions", "ephemeral-sessions"]) {
228
+ const root = join(agentDir, sub);
229
+ if (!existsSync(root))
230
+ continue;
231
+ try {
232
+ const entries = readdirSync(root, { withFileTypes: true });
233
+ for (const e of entries) {
234
+ if (!e.isDirectory())
235
+ continue;
236
+ const p = join(root, e.name);
237
+ try {
238
+ const st = statSync(p);
239
+ if (st.mtimeMs < cutoff) {
240
+ rmSync(p, { recursive: true, force: true });
241
+ }
242
+ }
243
+ catch {
244
+ /* skip inaccessible */
245
+ }
246
+ }
247
+ }
248
+ catch {
249
+ /* skip unreadable root */
250
+ }
251
+ }
252
+ }
253
+ let ephemeralCleanupScheduled = false;
213
254
  export { processTreeKillPlan, resolveCwdTarget };
214
255
  export class ClientSession {
215
256
  static mcpBridge = null;
@@ -241,6 +282,8 @@ export class ClientSession {
241
282
  /** 目标模式「委托执行」(Plan A)的「本轮结束」等待者:convId → 回调集合。
242
283
  * agent_end 到达时唤醒(事件驱动,绝不轮询);对话被移出时按 gone 收。 */
243
284
  turnEndWaiters = new Map();
285
+ /** 子代理终态自动通知防抖批处理队列:parentId → { timer, subagents } (issue #713) */
286
+ pendingSubagentNotices = new Map();
244
287
  // -----------------------------------------------------------------------
245
288
  // Goal / review / wizard —— 自包含模块,见 goal-service.ts。每个对话有独立
246
289
  // 的 GoalStatus,审查可并发;宿主回调在构造函数里接入。
@@ -338,6 +381,17 @@ export class ClientSession {
338
381
  throw new Error("no active conversation");
339
382
  return conv;
340
383
  }
384
+ /** 当前激活会话 ID(供服务端按需回水定位用)。 */
385
+ activeConversationId() {
386
+ return this.activeId;
387
+ }
388
+ /** 获取指定会话的全量 UiMessage 列表(供历史窗口按需回水与补齐使用)。 */
389
+ getMessagesOfConversation(convId) {
390
+ const conv = this.convs.get(convId);
391
+ if (!conv)
392
+ return undefined;
393
+ return this.messagesOf(conv);
394
+ }
341
395
  /** Runtime of the active conversation. */
342
396
  get runtime() {
343
397
  return this.conv.runtime;
@@ -420,7 +474,7 @@ export class ClientSession {
420
474
  customType: "terminal-bash-done",
421
475
  content: [{ type: "text", text }],
422
476
  display: true,
423
- })
477
+ }, { deliverAs: "nextTurn" })
424
478
  .catch(() => { });
425
479
  }
426
480
  }
@@ -432,7 +486,7 @@ export class ClientSession {
432
486
  * `model`(可选):"provider/id",显式指定子代理模型。不传时由调用方决定是否
433
487
  * 回退到模板模型 / 设置面板默认模型;null = 跟随主对话当前模型(默认行为,
434
488
  * runtime 重建时会继承共享 ModelRuntime 的当前默认)。 */
435
- async spawnSubagentConversation(prompt, type, cwd, apply, model, parentId, persist, title) {
489
+ async spawnSubagentConversation(prompt, type, cwd, apply, model, parentId, persist, title, thinking, notifyOnDone, isolation, extra) {
436
490
  // 数量上限先行:每个子代理都是完整 runtime + TerminalManager,无上限时一次
437
491
  // 并行派发几十个会把服务进程拖垮。持久化普通对话则受项目会话上限限制。
438
492
  if (persist) {
@@ -467,9 +521,19 @@ export class ClientSession {
467
521
  const baseCwd = spawner?.cwd ?? this.cwd;
468
522
  // 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
469
523
  const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
470
- const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
471
524
  const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
472
- const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
525
+ let effectiveCwd = resolvedCwd;
526
+ let worktreeContext;
527
+ if (isolation === "worktree") {
528
+ if (isRemoteWorkspaceUri(resolvedCwd)) {
529
+ throw new Error(pick(this.getLang(), "远程 SSH 工作区暂不支持工作树物理隔离", "Worktree isolation is not supported in remote SSH workspaces", "agent.subagent.worktree.remote_unsupported"));
530
+ }
531
+ const { createSubagentWorktree } = await import("./worktree-service.js");
532
+ worktreeContext = await createSubagentWorktree(resolvedCwd, conversationId, () => this.getLang());
533
+ effectiveCwd = worktreeContext.subagentCwd;
534
+ }
535
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, effectiveCwd);
536
+ const terminals = this.makeTerminalManager(conversationId, effectiveCwd);
473
537
  const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
474
538
  if (!persist) {
475
539
  // 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
@@ -481,13 +545,30 @@ export class ClientSession {
481
545
  }
482
546
  catch { }
483
547
  }
484
- const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
485
- cwd: sessionBaseDir,
486
- agentDir: this.agentDir,
487
- sessionManager,
488
- });
548
+ const noSpawnTools = !persist && this.subagentAtDepthLimit(parentId ?? this.activeId ?? undefined);
549
+ let runtime;
550
+ try {
551
+ runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId, undefined, undefined, noSpawnTools), {
552
+ cwd: sessionBaseDir,
553
+ agentDir: this.agentDir,
554
+ sessionManager,
555
+ });
556
+ }
557
+ catch (runtimeErr) {
558
+ if (worktreeContext) {
559
+ const { removeWorktree } = await import("./worktree-service.js");
560
+ try {
561
+ await removeWorktree(worktreeContext.mainRepoPath, worktreeContext.worktreePath, true);
562
+ }
563
+ catch { }
564
+ }
565
+ throw runtimeErr;
566
+ }
489
567
  const conv = this.makeConversation(runtime, conversationId, terminals);
490
- conv.cwd = resolvedCwd;
568
+ conv.cwd = effectiveCwd;
569
+ if (worktreeContext) {
570
+ conv.subagentWorktree = worktreeContext;
571
+ }
491
572
  conv.isSubagent = !persist;
492
573
  if (conv.isSubagent) {
493
574
  // 首轮 sendUserMessage 进入流式前的预检/模型切换窗口标记为投递中,
@@ -500,6 +581,17 @@ export class ClientSession {
500
581
  conv.parentId = parentId ?? this.activeId ?? undefined;
501
582
  conv.subagentType = type;
502
583
  conv.subagentPrompt = prompt;
584
+ conv.subagentThinking = thinking;
585
+ conv.notifyOnDone = notifyOnDone !== false;
586
+ // 安全模式与工具白名单(issue #727):优先从 extra 取,缺省按 type 与模板自动推导
587
+ const securityMode = extra?.securityMode ?? resolveSecurityMode(type, apply);
588
+ conv.subagentSecurityMode = securityMode;
589
+ if (extra?.allowedTools && extra.allowedTools.length > 0) {
590
+ conv.subagentAllowedTools = new Set(extra.allowedTools);
591
+ }
592
+ if (securityMode === "readonly" && !conv.permissionPreset) {
593
+ conv.permissionPreset = "read-only";
594
+ }
503
595
  // 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
504
596
  // (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
505
597
  conv.subagentTemplate = apply;
@@ -518,11 +610,8 @@ export class ClientSession {
518
610
  // message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
519
611
  // 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
520
612
  conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
521
- // 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
522
- this.applyRetryOverrides();
523
- // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
524
- this.applyCompactionOverrides();
525
- this.applyCodemodeOverrides();
613
+ // 子代理不走 bindSession——统一收口注入配置覆盖与工具门控
614
+ this.applySessionOverrides(conv);
526
615
  // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
527
616
  // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
528
617
  try {
@@ -544,7 +633,8 @@ export class ClientSession {
544
633
  // 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
545
634
  // 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
546
635
  // 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
547
- const resolvedModel = model ?? (apply?.model?.trim() || null) ?? (this.settingsSvc.current.subagentDefaultModel || null);
636
+ const explicitModel = model?.trim() || apply?.model?.trim() || null;
637
+ const resolvedModel = explicitModel ?? (this.settingsSvc.current.subagentDefaultModel || null);
548
638
  const followModel = resolvedModel
549
639
  ? resolvedModel
550
640
  : spawnerSession.model
@@ -563,6 +653,9 @@ export class ClientSession {
563
653
  await conv.session.setModel(m);
564
654
  }
565
655
  catch (err) {
656
+ if (explicitModel) {
657
+ throw new Error(pick(this.getLang(), `子代理模型切换失败:${followModel}(${err.message})`, `Failed to set subagent model: ${followModel} (${err.message})`, "agent.subagent.model.failed", { model: followModel, error: err.message }));
658
+ }
566
659
  // 换模型失败不阻断运行——沿用默认模型继续。
567
660
  this.emit({
568
661
  type: "notice",
@@ -573,6 +666,9 @@ export class ClientSession {
573
666
  }
574
667
  }
575
668
  else {
669
+ if (explicitModel) {
670
+ throw new Error(pick(this.getLang(), `子代理指定的模型不存在:${followModel},请检查 provider/id 格式或通过 /models 确认可用模型`, `Subagent model not found: ${followModel}. Please check provider/id format or use /models to confirm available models`, "agent.subagent.model.not.found", { model: followModel }));
671
+ }
576
672
  this.emit({
577
673
  type: "notice",
578
674
  level: "warning",
@@ -581,12 +677,8 @@ export class ClientSession {
581
677
  });
582
678
  }
583
679
  }
584
- // 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
585
- // 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
586
- // SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
587
- // 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
588
- // 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
589
- const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
680
+ // 思考强度:显式 thinking 参数 > 模板指定 > 派发者当前强度
681
+ const thinkingLevel = thinking?.trim() || apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
590
682
  if (thinkingLevel) {
591
683
  try {
592
684
  conv.session.setThinkingLevel(thinkingLevel);
@@ -641,6 +733,21 @@ export class ClientSession {
641
733
  const found = this.findSubagentOwner?.(convId);
642
734
  return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
643
735
  }
736
+ /** 由该父对话派出的子代理处在主对话下第几层:沿 parentId 链数祖先(主对话派的 = 1)。 */
737
+ subagentDepthUnder(parentId) {
738
+ let depth = 0;
739
+ const seen = new Set();
740
+ for (let id = parentId; id && !seen.has(id); id = this.subagentSnapshotAnywhere(id)?.parentId) {
741
+ seen.add(id);
742
+ depth++;
743
+ }
744
+ return depth;
745
+ }
746
+ /** 设了嵌套上限(subagentMaxDepth > 0)且已到上限那一层的内存子代理,创建时不注入派发工具。 */
747
+ subagentAtDepthLimit(parentId) {
748
+ const max = this.settingsSvc.current.subagentMaxDepth ?? 0;
749
+ return max > 0 && this.subagentDepthUnder(parentId) >= max;
750
+ }
644
751
  /** B20:convId 当前由哪个 ClientSession 持有(本会话优先;查不到兜底本会话)。 */
645
752
  subagentOwnerOf(convId) {
646
753
  if (!convId)
@@ -705,7 +812,7 @@ export class ClientSession {
705
812
  /** B20:subagentHost.spawnSubagent 的委托入口(在**当前**会话上执行模板校验与真正
706
813
  * spawn)—— 过户后由 host 按 parentId 的持有方调用,保证新子代理注册进持有方
707
814
  * 的 convs(左栏「不见/错位」、cwd 跟错项目才不再发生)。 */
708
- async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist) {
815
+ async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) {
709
816
  // 模板:存在且启用时应用;传了名字但不可用 → 抛错让工具转给 AI。
710
817
  const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
711
818
  if (templateName && (!tpl || !tpl.enabled)) {
@@ -714,11 +821,220 @@ export class ClientSession {
714
821
  // B20:parentId 是建时旧 id 时先解析成当前 id(过户撞 id 改名后,新子代理
715
822
  // 的 parentId 必须指向改名后的主对话,否则族展开/lists 都认不出它)。
716
823
  const canonParent = parentId ? (this.findSubagentOwner?.(parentId)?.convId ?? parentId) : parentId;
717
- return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist);
824
+ return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist, undefined, thinking, notifyOnDone, isolation, extra);
718
825
  }
719
826
  subagentRunOutcome(conv) {
720
827
  return subagentRunOutcome(conv);
721
828
  }
829
+ /**
830
+ * 终态结算与清理子代理的工作树(issue #728)。
831
+ * 判定是否有未提交或提交修改:无修改自动清理,有修改保留供审阅。
832
+ */
833
+ async finalizeSubagentWorktree(conv) {
834
+ const wt = conv.subagentWorktree;
835
+ if (!wt)
836
+ return undefined;
837
+ if (wt.finalized)
838
+ return wt;
839
+ if (conv.subagentWorktreePromise)
840
+ return conv.subagentWorktreePromise;
841
+ conv.subagentWorktreePromise = (async () => {
842
+ try {
843
+ try {
844
+ conv.terminals.killAll();
845
+ }
846
+ catch { }
847
+ const { finalizeSubagentWorktree } = await import("./worktree-service.js");
848
+ return await finalizeSubagentWorktree(wt, () => this.getLang());
849
+ }
850
+ finally {
851
+ conv.subagentWorktreePromise = undefined;
852
+ }
853
+ })();
854
+ return conv.subagentWorktreePromise;
855
+ }
856
+ /**
857
+ * issue #713:安排向父对话投递子代理执行完成的聚合通知。
858
+ * 采用 400ms 脉冲防抖(Pulse Debounce):多个子代理近乎同时收口时,
859
+ * 合并为一条聚合消息唤醒父对话,避免碎片化多次打断父对话。
860
+ */
861
+ scheduleSubagentCompletionNotice(conv) {
862
+ const parentId = conv.parentId;
863
+ if (!parentId || conv.notifyOnDone === false)
864
+ return;
865
+ if (conv.subagentDoneNotified || conv.subagentConsumedByParent)
866
+ return;
867
+ let entry = this.pendingSubagentNotices.get(parentId);
868
+ if (!entry) {
869
+ entry = {
870
+ timer: null,
871
+ subagents: new Set(),
872
+ };
873
+ this.pendingSubagentNotices.set(parentId, entry);
874
+ }
875
+ entry.subagents.add(conv);
876
+ if (entry.timer)
877
+ clearTimeout(entry.timer);
878
+ entry.timer = setTimeout(() => {
879
+ void this.flushSubagentCompletionNotice(parentId);
880
+ }, 400);
881
+ }
882
+ /**
883
+ * issue #726:提取并清空当前对话挂起的子代理通知。
884
+ * 过滤掉已被消费(subagentConsumedByParent)或已通知(subagentDoneNotified)的子代理,
885
+ * 将留存的挂起子代理标为已通知,返回待交付的列表。
886
+ */
887
+ drainSuspendedSubagents(conv) {
888
+ if (!conv.suspendedSubagents || conv.suspendedSubagents.size === 0)
889
+ return [];
890
+ const buffered = Array.from(conv.suspendedSubagents).filter((c) => !c.subagentConsumedByParent && !c.subagentDoneNotified);
891
+ conv.suspendedSubagents.clear();
892
+ for (const c of buffered) {
893
+ c.subagentDoneNotified = true;
894
+ }
895
+ return buffered;
896
+ }
897
+ /**
898
+ * issue #726:检查子代理自动唤醒熔断条件。
899
+ * 区分真正的循环(空转/单代理反复震荡/超出配置的轮数上限)与有效流程推进。
900
+ */
901
+ checkSubagentWakeCircuitBreaker(targetConv, parentOwner, _toNotify) {
902
+ // 1. 空转熔断:父对话由子代理唤醒后,连续 2 轮未执行任何工具操作(纯回复或停止),又有子代理唤醒
903
+ const idleTurns = targetConv.consecutiveIdleWakeTurns ?? 0;
904
+ if (idleTurns >= 2) {
905
+ return {
906
+ suspend: true,
907
+ reason: "idle_loop",
908
+ messageZh: (count) => `子代理协作检测到父对话已连续 ${idleTurns} 轮未执行任何操作(处于空转/等待状态),已挂起后续自动唤醒(${count} 个完成通知已暂存)。请查看结果并输入新指令。`,
909
+ messageEn: (count) => `Subagent orchestration detected ${idleTurns} consecutive idle wake turns (no tool actions performed); auto-wake suspended (${count} notice(s) buffered). Please inspect and reply.`,
910
+ };
911
+ }
912
+ // 2. 单代理反复震荡死锁检测:如果最近连续 4 次唤醒完全来自于同一个子代理(无其他子代理且无人类干预)
913
+ const recentIds = targetConv.recentWakeSubagentIds ?? [];
914
+ if (recentIds.length >= 4) {
915
+ const tail = recentIds.slice(-4);
916
+ const first = tail[0];
917
+ if (tail.every((id) => id === first)) {
918
+ const short = first.slice(0, 8);
919
+ return {
920
+ suspend: true,
921
+ reason: "single_agent_oscillation",
922
+ messageZh: (count) => `检测到同一个子代理 ${short} 连续反复唤醒父对话达到 4 次,可能陷入修改死循环,已挂起自动唤醒(${count} 个完成通知已暂存)。请查看结果并介入。`,
923
+ messageEn: (count) => `Subagent ${short} consecutively woke parent conversation 4 times (potential oscillation loop); auto-wake suspended (${count} notice(s) buffered). Please inspect.`,
924
+ };
925
+ }
926
+ }
927
+ // 3. 自主连续轮次上限检测:可配置(0 = 不限制,默认 5 轮)
928
+ const autoTurns = targetConv.autonomousTurnsWithoutUser ?? 0;
929
+ const maxTurns = parentOwner?.settingsSvc?.current?.subagentAutoWakeMaxTurns ?? defaultSubagentAutoWakeMaxTurns();
930
+ if (maxTurns > 0 && autoTurns >= maxTurns) {
931
+ return {
932
+ suspend: true,
933
+ reason: "max_turns",
934
+ messageZh: (count) => `子代理协作已自动推进 ${autoTurns} 轮,已触发防死循环熔断(上限 ${maxTurns} 轮),已暂停自动唤醒(${count} 个完成通知已暂存)。请查看结果或输入新指令继续。`,
935
+ messageEn: (count) => `Subagent orchestration advanced ${autoTurns} autonomous rounds (limit ${maxTurns}); auto-wake suspended to prevent loops (${count} notice(s) buffered). Please inspect or reply to continue.`,
936
+ };
937
+ }
938
+ return null;
939
+ }
940
+ /**
941
+ * 执行向父对话投递已完成子代理的结构化通知。
942
+ */
943
+ async flushSubagentCompletionNotice(parentId, retryCount = 0) {
944
+ const entry = this.pendingSubagentNotices.get(parentId);
945
+ if (!entry)
946
+ return;
947
+ this.pendingSubagentNotices.delete(parentId);
948
+ if (entry.timer)
949
+ clearTimeout(entry.timer);
950
+ // 过滤出未被消费、未被通知过的子代理
951
+ const toNotify = Array.from(entry.subagents).filter((c) => !c.subagentConsumedByParent && !c.subagentDoneNotified);
952
+ if (toNotify.length === 0)
953
+ return;
954
+ // issue #728:提前结算隔离工作树,确保通知文本包含最新工作树状态
955
+ if (typeof this.finalizeSubagentWorktree === "function") {
956
+ await Promise.all(toNotify.map((c) => this.finalizeSubagentWorktree(c)));
957
+ }
958
+ // 寻找父对话(支持跨 ClientSession 查找)
959
+ const parentOwner = this.subagentOwnerOf(parentId);
960
+ let targetConv = parentOwner.convs.get(parentId);
961
+ let isFallback = false;
962
+ // 活跃视口兜底:若原父对话已不在,寻找同 cwd 的活跃非子代理对话
963
+ if (!targetConv || !targetConv.session) {
964
+ const projectCwd = toNotify[0]?.cwd ?? this.cwd;
965
+ for (const c of parentOwner.convs.values()) {
966
+ if (!c.isSubagent && c.cwd === projectCwd) {
967
+ targetConv = c;
968
+ isFallback = true;
969
+ break;
970
+ }
971
+ }
972
+ }
973
+ // 无存活主对话时优雅降级为系统 Notice,不报错不中断
974
+ if (!targetConv || !targetConv.session) {
975
+ for (const c of toNotify)
976
+ c.subagentDoneNotified = true;
977
+ const ids = toNotify.map((c) => c.id.slice(0, 8)).join(", ");
978
+ this.emit({
979
+ type: "notice",
980
+ level: "info",
981
+ text: `子代理 ${ids} 已执行完毕(原父对话已关闭)。`,
982
+ textEn: `Subagents ${ids} completed (originating conversation is closed).`,
983
+ });
984
+ return;
985
+ }
986
+ // issue #726:自适应防死循环熔断(检查空转、单代理震荡、配置的轮次上限)
987
+ const checker = this.checkSubagentWakeCircuitBreaker ?? ClientSession.prototype.checkSubagentWakeCircuitBreaker;
988
+ const circuit = checker.call(this, targetConv, parentOwner, toNotify);
989
+ if (circuit) {
990
+ targetConv.suspendedSubagents = targetConv.suspendedSubagents ?? new Set();
991
+ for (const c of toNotify) {
992
+ targetConv.suspendedSubagents.add(c);
993
+ }
994
+ const count = targetConv.suspendedSubagents.size;
995
+ parentOwner.emit({
996
+ type: "notice",
997
+ level: "warning",
998
+ text: circuit.messageZh(count),
999
+ textEn: circuit.messageEn(count),
1000
+ });
1001
+ return;
1002
+ }
1003
+ // 若目标对话正在进行上下文压缩(isCompacting),延迟 800ms 避让重试
1004
+ if (targetConv.session.isCompacting === true) {
1005
+ if (retryCount < 10) {
1006
+ const retryTimer = setTimeout(() => {
1007
+ this.pendingSubagentNotices.set(parentId, { timer: retryTimer, subagents: new Set(toNotify) });
1008
+ void this.flushSubagentCompletionNotice(parentId, retryCount + 1);
1009
+ }, 800);
1010
+ return;
1011
+ }
1012
+ }
1013
+ for (const c of toNotify) {
1014
+ c.subagentDoneNotified = true;
1015
+ }
1016
+ const noticeText = formatSubagentsCompletionNotice(toNotify, this.getLang(), isFallback ? parentId : undefined);
1017
+ const autoTurns = targetConv.autonomousTurnsWithoutUser ?? 0;
1018
+ targetConv.autonomousTurnsWithoutUser = autoTurns + 1;
1019
+ targetConv.wakeReason = "subagent_completion";
1020
+ targetConv.wakeTurnHadAction = false;
1021
+ targetConv.recentWakeSubagentIds = [
1022
+ ...(targetConv.recentWakeSubagentIds ?? []),
1023
+ ...toNotify.map((c) => c.id),
1024
+ ].slice(-10);
1025
+ try {
1026
+ await targetConv.session.sendUserMessage(noticeText, targetConv.session.isStreaming ? { deliverAs: "steer" } : undefined);
1027
+ parentOwner.flushSnapshot();
1028
+ }
1029
+ catch (err) {
1030
+ parentOwner.emit({
1031
+ type: "notice",
1032
+ level: "warning",
1033
+ text: `向父对话投递子代理完成通知失败:${err.message}`,
1034
+ textEn: `Failed to deliver subagent completion notice to parent conversation: ${err.message}`,
1035
+ });
1036
+ }
1037
+ }
722
1038
  /**
723
1039
  * 事件驱动地等某对话「当前回合结束」(目标模式委托执行用)。
724
1040
  * 若当前并未在跑则立即返回既有结局;超时返回 "timeout";对话已消失返回 "gone"。
@@ -930,7 +1246,17 @@ export class ClientSession {
930
1246
  if (!session || !this.lazyLoadingOn())
931
1247
  return empty;
932
1248
  try {
933
- const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME);
1249
+ // PATCH-F1: 目录排除 MCP deferred 工具——「恒定全集」在 MCP deferred 后会把
1250
+ // 数百个工具摘要常驻 tools 节(实测 318 工具时 2042→20854 chars,+75K tok/轮)。
1251
+ // deferred 工具按设计不声明给模型,其发现走 mcp 网关(searchTools)与
1252
+ // tool_search 的 BM25 元数据(零 schema 注入);目录里列出它们违背 deferred
1253
+ // 语义且每轮全价。目录其余部分仍恒定(MCP deferred 集合会话内固定),不影响前缀缓存。
1254
+ const mcpDeferred = new Set((session.getAllTools?.() ?? [])
1255
+ .filter((t) => typeof t?.namespace?.name === "string" &&
1256
+ t.namespace.name.startsWith("mcp__") &&
1257
+ (t.exposure ?? "codemode") === "deferred")
1258
+ .map((t) => t.name));
1259
+ const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME && !mcpDeferred.has(n));
934
1260
  const snippets = {};
935
1261
  const signatures = {};
936
1262
  for (const name of names) {
@@ -959,6 +1285,17 @@ export class ClientSession {
959
1285
  if (conv?.planMode === true)
960
1286
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
961
1287
  disabled.add(n);
1288
+ if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
1289
+ for (const t of all) {
1290
+ if (!conv.subagentAllowedTools.has(t))
1291
+ disabled.add(t);
1292
+ }
1293
+ }
1294
+ if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
1295
+ for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
1296
+ disabled.add(toolName);
1297
+ }
1298
+ }
962
1299
  return all.filter((n) => allowed.has(n) && !disabled.has(n));
963
1300
  }
964
1301
  /** 工具在系统提示词里的一行摘要:用户覆盖 → 出厂 snippet → 描述首句。 */
@@ -1049,6 +1386,17 @@ export class ClientSession {
1049
1386
  if (conv?.planMode === true)
1050
1387
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
1051
1388
  disabled.add(n);
1389
+ if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
1390
+ for (const t of all) {
1391
+ if (!conv.subagentAllowedTools.has(t))
1392
+ disabled.add(t);
1393
+ }
1394
+ }
1395
+ if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
1396
+ for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
1397
+ disabled.add(toolName);
1398
+ }
1399
+ }
1052
1400
  const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1053
1401
  // 「已加载集合」里有名字 ≠ 活跃集里有它:JIT 自动激活(见 autoActivateToolIfLoadable)
1054
1402
  // 与任何只标记不重放门控的路径都会造出这种半吊子状态。按活跃集判定,
@@ -1180,6 +1528,9 @@ export class ClientSession {
1180
1528
  contextFiles: src.contextFiles,
1181
1529
  skills: effectiveSkills,
1182
1530
  skillsFullText: showSkills ? normalizeSkillList(this.settingsSvc.current.skillsFullText) : [],
1531
+ skillsCatalogMaxDesc: this.settingsSvc.current.skillsCatalogMaxDesc,
1532
+ skillsCatalogShowLocation: this.settingsSvc.current.skillsCatalogShowLocation,
1533
+ skillsCatalogBudget: this.settingsSvc.current.skillsCatalogBudget,
1183
1534
  };
1184
1535
  }
1185
1536
  /** skill 全文注入({{skills}} 全文模式):最好努力读名单里技能的文件正文。 */
@@ -1191,12 +1542,17 @@ export class ClientSession {
1191
1542
  * 仅在完全默认且全功能 standard 状态下返回 undefined 让 SDK 拼装。 */
1192
1543
  renderMainCompose(src) {
1193
1544
  const preset = src.preset ?? this.conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1545
+ const showSkills = presetShowsSkillCatalog(preset);
1546
+ const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
1194
1547
  return renderMainCompose(this.composeInputs(src), {
1195
1548
  promptTemplate: this.settingsSvc.current.promptTemplate,
1196
1549
  promptOverrides: this.settingsSvc.current.promptOverrides,
1550
+ promptDisabled: this.settingsSvc.current.promptDisabled ?? [],
1197
1551
  preset,
1198
1552
  disabledToolCount: effectiveDisabledAgentTools(this.settingsSvc.current).length,
1199
1553
  isLazy: src.lazy,
1554
+ hasSkills: effectiveSkills.length > 0,
1555
+ hasSkillsFullText: (this.settingsSvc.current.skillsFullText?.length ?? 0) > 0,
1200
1556
  });
1201
1557
  }
1202
1558
  /** 从指定会话(缺省 = 活跃会话)收集工具/资源快照 → 一次算出 ①各来源默认(自动)
@@ -1245,9 +1601,12 @@ export class ClientSession {
1245
1601
  const def = sess.getToolDefinition(name);
1246
1602
  if (!def)
1247
1603
  continue;
1248
- const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
1249
- if (eff.promptSnippet && eff.promptSnippet.trim())
1604
+ const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
1605
+ const eff = effectiveToolPrompt(def, ov);
1606
+ // 与活体 run 钩子同规则:非延迟模式只列被覆盖过的 snippet(省 token 且与实发一致)。
1607
+ if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
1250
1608
  snippets[name] = eff.promptSnippet.trim();
1609
+ }
1251
1610
  if (baseSet.has(name) && eff.promptGuidelines)
1252
1611
  guidelines.push(...eff.promptGuidelines);
1253
1612
  }
@@ -1270,7 +1629,7 @@ export class ClientSession {
1270
1629
  const tpl = (this.settingsSvc.current.promptTemplate ?? "").trim();
1271
1630
  const ovs = this.settingsSvc.current.promptOverrides ?? {};
1272
1631
  const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
1273
- const rendered = renderPromptTemplate(tpl || DEFAULT_PROMPT_TEMPLATE, texts, hasOverride ? ovs : undefined);
1632
+ const rendered = renderPromptTemplate(tpl || DEFAULT_PROMPT_TEMPLATE, texts, hasOverride ? ovs : undefined, new Set(this.settingsSvc.current.promptDisabled ?? []));
1274
1633
  return { texts, full: rendered, toolsSchema: buildToolsSchemaText(schemaEntries) };
1275
1634
  }
1276
1635
  catch {
@@ -1420,12 +1779,20 @@ export class ClientSession {
1420
1779
  }
1421
1780
  }
1422
1781
  subagentHost = {
1423
- spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist) => {
1782
+ spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) => {
1424
1783
  // B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
1425
1784
  // 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
1426
1785
  // 否则新子代理注册进旧会话、目标页左栏「不见/错位」。
1427
1786
  const owner = parentId ? this.subagentOwnerOf(parentId) : this;
1428
- return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist);
1787
+ return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra);
1788
+ },
1789
+ finalizeSubagentWorktree: async (convId) => {
1790
+ const owner = this.subagentOwnerOf(convId);
1791
+ const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
1792
+ const conv = owner.convs.get(curId);
1793
+ if (conv) {
1794
+ await owner.finalizeSubagentWorktree(conv);
1795
+ }
1429
1796
  },
1430
1797
  getSubagent: (convId) => {
1431
1798
  // B20:本会话查不到就去「当前持有方」查 —— 过户把子代理整体搬走后,
@@ -1437,6 +1804,19 @@ export class ClientSession {
1437
1804
  return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
1438
1805
  },
1439
1806
  listSubagents: (scope, forSelfId) => this.listSubagentSnapshots(scope, forSelfId),
1807
+ markSubagentsConsumed: (runIds) => {
1808
+ for (const id of runIds) {
1809
+ const owner = this.subagentOwnerOf(id);
1810
+ const curId = owner.convs.has(id) ? id : this.subagentCurrentId(id);
1811
+ const conv = owner.convs.get(curId);
1812
+ if (conv) {
1813
+ conv.subagentConsumedByParent = true;
1814
+ for (const parent of owner.convs.values()) {
1815
+ parent.suspendedSubagents?.delete(conv);
1816
+ }
1817
+ }
1818
+ }
1819
+ },
1440
1820
  handoffSubagent: async (fromRunId, toRunId, payload) => {
1441
1821
  await this.handoffSubagent(fromRunId, toRunId, payload);
1442
1822
  },
@@ -1457,6 +1837,9 @@ export class ClientSession {
1457
1837
  if (conv.session.isStreaming || !conv.session.isIdle) {
1458
1838
  await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1459
1839
  }
1840
+ if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
1841
+ void owner.finalizeSubagentWorktree(conv).catch(() => { });
1842
+ }
1460
1843
  }
1461
1844
  },
1462
1845
  getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
@@ -1650,6 +2033,8 @@ export class ClientSession {
1650
2033
  subagentTemplates;
1651
2034
  /** 审批规则库(全局共享,<dataDir>/approval-rules.json)。 */
1652
2035
  approvalRules;
2036
+ /** 审批审计日志追加器(<dataDir>/audit/approvals.jsonl,Issue #722)。 */
2037
+ auditLogger;
1653
2038
  /** 未发送输入框草稿(全局共享,<dataDir>/composer-drafts.json,按 sessionId 键入,见 server/composer-drafts.ts)。 */
1654
2039
  drafts;
1655
2040
  /** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
@@ -1671,8 +2056,21 @@ export class ClientSession {
1671
2056
  /** 任务计划管理器(Plan Mode / Step State Machine)。 */
1672
2057
  planManager;
1673
2058
  approvalSeq = 0;
1674
- /** 待审批高危工具调用(Human-in-the-Loop: Edit & Run)。 */
1675
- pendingApprovals = new Map();
2059
+ /** 确保对话拥有待审批项 Map */
2060
+ ensurePendingApprovals(conv) {
2061
+ if (!conv.pendingApprovals)
2062
+ conv.pendingApprovals = new Map();
2063
+ return conv.pendingApprovals;
2064
+ }
2065
+ /** 跨对话查找挂起的审批条目及其所属对话 */
2066
+ findPendingApproval(id) {
2067
+ for (const conv of this.convs.values()) {
2068
+ if (conv.pendingApprovals?.has(id)) {
2069
+ return { conv, entry: conv.pendingApprovals.get(id) };
2070
+ }
2071
+ }
2072
+ return undefined;
2073
+ }
1676
2074
  // -----------------------------------------------------------------------
1677
2075
  // 浏览器页面桥(标准 pi 引擎的 browser_page customTool):模型调工具 → 发
1678
2076
  // page_request 给浏览器 → 前端转 page-picker 扩展 → page_response 回到这里
@@ -1695,6 +2093,7 @@ export class ClientSession {
1695
2093
  this.roots = stateStore.getWorkspaceRoots(clientId, cwd);
1696
2094
  this.subagentTemplates = new SubagentTemplatesStore(join(stateStore.dataDir, "subagent-templates.json"));
1697
2095
  this.approvalRules = new ApprovalRulesStore(join(stateStore.dataDir, "approval-rules.json"));
2096
+ this.auditLogger = new ApprovalAuditLogger(stateStore.dataDir);
1698
2097
  this.drafts = new ComposerDraftsStore(join(stateStore.dataDir, "composer-drafts.json"));
1699
2098
  this.sandboxes = new SandboxManager(stateStore.dataDir);
1700
2099
  this.planManager = new PlanManager(join(stateStore.dataDir, "plans.json"));
@@ -1736,21 +2135,21 @@ export class ClientSession {
1736
2135
  getSession: () => this.session,
1737
2136
  cwd: () => this.cwd,
1738
2137
  agentDir: () => this.agentDir,
1739
- isStreaming: () => this.session.isStreaming,
2138
+ isStreaming: () => this.session.isStreaming || Boolean(this.conv?.promptInFlight),
1740
2139
  reloadSession: async () => {
2140
+ if (this.session.isStreaming || Boolean(this.conv?.promptInFlight)) {
2141
+ this.settingsSvc.setPendingReload(true);
2142
+ return;
2143
+ }
1741
2144
  await this.session.reload();
1742
- // reload() 重读磁盘 settings.json,会丢掉内存 applyOverrides
1743
- // (含重试次数覆盖)——依次重放:重试覆盖 → 软上限覆盖 → 终端门控。
1744
- this.applyRetryOverrides();
1745
- this.applyCompactionOverrides();
1746
- this.applyCodemodeOverrides();
1747
- // reload() 会把 custom 工具重新加回活跃集——重放当前会话归属预设门控。
1748
- this.applyToolGating(this.session, this.conv?.agentPreset);
2145
+ // reload() 重读磁盘 settings.json,统一收口重放配置覆盖与工具门控
2146
+ this.applySessionOverrides(this.conv);
1749
2147
  await this.pushSlashCommands();
1750
2148
  },
1751
2149
  applyRetryOverrides: () => this.applyRetryOverrides(),
1752
2150
  applyCompactionOverrides: () => this.applyCompactionOverrides(),
1753
2151
  applyCodemodeOverrides: () => this.applyCodemodeOverrides(),
2152
+ applySessionOverrides: () => this.applySessionOverrides(),
1754
2153
  applyToolGating: () => {
1755
2154
  for (const conv of this.convs.values()) {
1756
2155
  this.applyToolGating(conv.session, conv.agentPreset);
@@ -1948,6 +2347,13 @@ export class ClientSession {
1948
2347
  // Prune dead background tasks every 30s (only spawns netstat/lsof while
1949
2348
  // the list is non-empty). unref: must not keep the process alive.
1950
2349
  this.bg.start();
2350
+ if (!ephemeralCleanupScheduled) {
2351
+ ephemeralCleanupScheduled = true;
2352
+ const timer = setTimeout(() => {
2353
+ cleanupOrphanedSessionDirs(this.agentDir);
2354
+ }, 5000);
2355
+ timer.unref?.();
2356
+ }
1951
2357
  }
1952
2358
  static async create(clientId, cwd, stateStore, opts) {
1953
2359
  const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
@@ -2092,8 +2498,9 @@ export class ClientSession {
2092
2498
  * 应用(prompt replace/append + 白名单),其余(终端接管、Windows persona
2093
2499
  * 等)仍跟随主会话设置。undefined = 按主会话设置(普通对话/不选模板的子代理)。
2094
2500
  */
2095
- makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset) {
2501
+ makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset, noSpawnTools) {
2096
2502
  return async ({ cwd: effectiveCwd, sessionManager }) => {
2503
+ const sdkBuiltins = await getSdkBuiltinExtensionFactories();
2097
2504
  const services = await createAgentSessionServices({
2098
2505
  cwd: effectiveCwd,
2099
2506
  modelRuntime: this.sharedModelRuntime,
@@ -2217,19 +2624,9 @@ export class ClientSession {
2217
2624
  // agent run 前触发,SDK 此时已用最新工具/资源拼好基础提示词;若配置了模板或
2218
2625
  // 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
2219
2626
  // 等都取自本次 run 的 systemPromptOptions,永远最新)。
2627
+ disabledBuiltinExtensions: SDK_DISABLED_BUILTIN_EXTENSIONS,
2220
2628
  extensionFactories: [
2221
- {
2222
- name: "codemode",
2223
- hidden: true,
2224
- replaceable: true,
2225
- factory: createCodemodeExtension(),
2226
- },
2227
- {
2228
- name: "tool-search",
2229
- hidden: true,
2230
- replaceable: true,
2231
- factory: createToolSearchExtension(),
2232
- },
2629
+ ...sdkBuiltins,
2233
2630
  {
2234
2631
  name: "pi-webui-persona",
2235
2632
  hidden: true,
@@ -2279,8 +2676,11 @@ export class ClientSession {
2279
2676
  const def = sess.getToolDefinition(name);
2280
2677
  if (!def)
2281
2678
  continue;
2282
- const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
2283
- if (eff.promptSnippet && eff.promptSnippet.trim()) {
2679
+ const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
2680
+ const eff = effectiveToolPrompt(def, ov);
2681
+ // 非延迟模式不展开完整目录(省 token):只列出被用户覆盖过的
2682
+ // snippet,保证覆盖文案能到达模型(活体链路恒走自渲染)。
2683
+ if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
2284
2684
  activeSnippets[name] = eff.promptSnippet.trim();
2285
2685
  }
2286
2686
  if (baseSet.has(name) && eff.promptGuidelines) {
@@ -2363,61 +2763,37 @@ export class ClientSession {
2363
2763
  services,
2364
2764
  sessionManager,
2365
2765
  model: sessionModel,
2366
- // 覆盖 SDK 内置 bash(customTools 按 name 覆盖)。双实现分流:
2367
- // 「默认 bash 覆盖」开关(terminalBash)关 → 原生 SDK bash(纯进程、不开终端);
2368
- // 开 → 终端接管 bash(persist 决定一次性/持久,可静默自动转后台)。
2369
- // 整列工具统一过计划模式闸门(只规划不实施,写类/旁路工具执行前拒),
2370
- // read/write/edit 三处覆盖在会话建好后另注入(见 installToolOverrides)。
2766
+ // bash / read / write / edit 四处覆盖统一在会话建好后另注入(见 installToolOverrides)。
2767
+ // 原因是创建时的 customTools 恒顶掉第三方扩展注册的同名工具(SDK 的合并链是
2768
+ // [...扩展注册的工具, ...customTools] 后写赢,issue #750)。
2371
2769
  customTools: [
2372
- // P1-5:bash/read 包插件拦截(pre 拒/问即拦、post 脱敏补上下文;
2373
- // 未注入 toolGuard 时 withToolGuard 原样返回,零开销)。
2374
- // 权限沙箱拦截(只读模式拦截终端执行)。
2375
- wrapBashToolWithPermission(withToolGuard(withWorkspaceSnapshotGate(makeAdaptiveBashTool(
2376
- // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2377
- makeKillableBashTool(effectiveCwd, this.bashKills, () => this.getLang()), makeTerminalBashTool(terminals, {
2378
- cwd: effectiveCwd,
2379
- // 设置开 = 用终端;此分支里 persist 未显式给时默认一次性(false)。
2380
- defaultPersist: () => false,
2381
- idleMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashIdleMs) || 0),
2382
- maxForegroundMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashMaxForegroundMs) || 0),
2383
- kills: this.bashKills,
2384
- notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
2385
- // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2386
- lang: () => this.getLang(),
2387
- }),
2388
- // 设置关 → 原生 bash;开 → 终端 bash。
2389
- () => this.settingsSvc.current.terminalBash), () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
2390
- toolName: "bash",
2391
- guard: this.lateToolGuard,
2392
- conversationId: () => ownerId,
2393
- getLang: () => this.getLang(),
2394
- cwd: effectiveCwd,
2395
- getRoots: () => this.roots,
2396
- askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
2397
- getRules: () => this.approvalRules.list(),
2398
- }), () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2399
- this.settingsSvc.current.defaultPermissionPreset ??
2400
- "workspace-write-never", () => this.getLang()),
2401
2770
  ...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang(), {
2402
- checkSafety: (cmd) => {
2771
+ checkSafety: async (cmd, ctx) => {
2403
2772
  // 沙盒硬围栏:禁止引用源项目路径或跳出沙盒根。
2404
2773
  const activeSbx = this.sandboxes.getByCwd(effectiveCwd);
2405
2774
  if (activeSbx) {
2406
2775
  const sbxDenied = evaluateSandboxJail(activeSbx, "bash", { command: cmd }, effectiveCwd);
2407
2776
  if (sbxDenied)
2408
- return { blocked: true, reason: sbxDenied.reason };
2777
+ return { blocked: true, reason: sbxDenied.reason, reasonEn: sbxDenied.reasonEn };
2409
2778
  }
2410
2779
  // 计划模式:终端只放行只读命令(常驻终端也走这条,与 bash 覆盖同口径)。
2411
2780
  if (this.planModeOf(ownerId)) {
2412
2781
  const denied = planModeDenial("bash", { command: cmd });
2413
2782
  if (denied)
2414
- return { blocked: true, reason: denied.reason };
2783
+ return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
2415
2784
  }
2416
2785
  // 目标审查回合:常驻终端同样只放只读命令(审查者跑测试可以,改文件不行)。
2417
2786
  if (this.goalReviewTurnOf(ownerId)) {
2418
2787
  const denied = goalReviewDenial("bash", { command: cmd });
2419
2788
  if (denied)
2420
- return { blocked: true, reason: denied.reason };
2789
+ return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
2790
+ }
2791
+ // 子代理安全规格硬闸门(issue #727):受限子代理(readonly/verify)或工具白名单
2792
+ const subagentMode = this.subagentSecurityModeOf(ownerId);
2793
+ if (subagentMode !== "normal" || this.subagentAllowedToolsOf(ownerId)) {
2794
+ const denied = subagentSecurityDenial(subagentMode, "bash", { command: cmd }, this.subagentAllowedToolsOf(ownerId));
2795
+ if (denied)
2796
+ return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
2421
2797
  }
2422
2798
  const perm = (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2423
2799
  this.settingsSvc.current.defaultPermissionPreset ??
@@ -2425,17 +2801,77 @@ export class ClientSession {
2425
2801
  if (perm === "read-only") {
2426
2802
  const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
2427
2803
  if (danger.denied || danger.dangerous) {
2428
- return { blocked: true, reason: danger.reason || "只读模式禁止执行高危/破坏性命令" };
2804
+ return {
2805
+ blocked: true,
2806
+ reason: danger.reason || "只读模式禁止执行高危/破坏性命令",
2807
+ reasonEn: danger.reasonEn || "Read-only mode forbids dangerous or destructive commands",
2808
+ };
2429
2809
  }
2430
2810
  }
2811
+ // 1. 系统核心安全:内置高危操作检测与自定义审批规则先行(优先级最高,防绕过)
2431
2812
  const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
2432
2813
  if (danger.denied) {
2433
- return { blocked: true, reason: danger.reason || "命中系统阻断规则" };
2814
+ return {
2815
+ blocked: true,
2816
+ reason: danger.reason || "命中系统阻断规则",
2817
+ reasonEn: danger.reasonEn || "Blocked by system approval rule",
2818
+ };
2819
+ }
2820
+ // 2. 插件前置守卫 deny 拦截
2821
+ let pre;
2822
+ if (this.lateToolGuard) {
2823
+ try {
2824
+ pre = await this.lateToolGuard.pre({ toolName: "bash", params: { command: cmd }, conversationId: ownerId }, this.getLang());
2825
+ }
2826
+ catch {
2827
+ pre = { verdict: { decision: "allow" } };
2828
+ }
2829
+ }
2830
+ if (pre?.verdict.decision === "deny") {
2831
+ return {
2832
+ blocked: true,
2833
+ reason: pre.verdict.reason ?? "插件拒绝执行此命令",
2834
+ reasonEn: pre.verdict.reasonEn ?? "Plugin denied execution of this command",
2835
+ };
2836
+ }
2837
+ // 3. 决定是否需要弹窗审批(系统高危 ask 优先于插件通用 ask,issue #721)
2838
+ let needApproval = false;
2839
+ let approvalReason;
2840
+ let approvalReasonEn;
2841
+ let approvalCategory;
2842
+ let approvalHits;
2843
+ if (danger.dangerous) {
2844
+ needApproval = true;
2845
+ approvalReason = danger.reason;
2846
+ approvalReasonEn = danger.reasonEn;
2847
+ approvalCategory = danger.category;
2848
+ approvalHits = danger.hits;
2849
+ }
2850
+ else if (pre?.verdict.decision === "ask") {
2851
+ needApproval = true;
2852
+ approvalReason = pre.verdict.reason ?? "插件要求确认本次操作";
2853
+ approvalReasonEn = pre.verdict.reasonEn ?? "Plugin requested confirmation for this operation";
2854
+ approvalCategory = pluginApprovalCategory(pre.pluginId ?? "plugin");
2855
+ }
2856
+ if (needApproval) {
2857
+ const res = await this.askApproval(ctx.toolCallId, "bash", { command: cmd, terminalId: ctx.terminalId }, approvalReason, approvalReasonEn, ownerId, approvalCategory, approvalHits);
2858
+ if (res.decision === "deny") {
2859
+ return {
2860
+ blocked: true,
2861
+ userDenied: true,
2862
+ reason: res.reason || "操作被用户拒绝",
2863
+ reasonEn: res.reason || "Operation denied by user",
2864
+ };
2865
+ }
2866
+ if (res.decision === "edit") {
2867
+ const editedCmd = typeof res.editedParams?.command === "string" ? res.editedParams.command : cmd;
2868
+ return { editedCommand: editedCmd };
2869
+ }
2434
2870
  }
2435
2871
  return {};
2436
2872
  },
2437
2873
  }).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
2438
- // read / write / edit 三处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2874
+ // bash / read / write / edit 四处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2439
2875
  // 扩展加载顺序无关,直接塞进来会静默顶掉第三方扩展注册的同名工具(见
2440
2876
  // tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
2441
2877
  // 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置;带权限沙箱拦截与人机协同)。
@@ -2450,26 +2886,31 @@ export class ClientSession {
2450
2886
  // 空白名单 = 跟随主会话(插件工具照常进入子代理)。
2451
2887
  ...(apply && apply.enabledExtensions.length > 0 ? [] : this.enabledPluginToolDefs()),
2452
2888
  // 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
2453
- // 也注册了它们,因此可自然嵌套派发。host 按 ownerId 包装:子代理的
2889
+ // 默认也注册了它们,因此可自然嵌套派发;设置了 subagentMaxDepth 且子代理
2890
+ // 已到上限层时 noSpawnTools=true,连同下面的 delegate_task 一起不注入。host 按 ownerId 包装:子代理的
2454
2891
  // 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
2455
2892
  // 派发瞬间的 active——后台对话继续产出时用户可能已切到别的项目,用
2456
2893
  // activeId 会把孩子记到无关会话名下、沉到别的组/底部(issue #95)。
2457
2894
  // ownerId 即本 runtime 所属会话(创建时就已知,见各调用点),一身二任:
2458
2895
  // spawn 的 parentId(子代理记到真正的派发会话名下)+ wait_all 的
2459
2896
  // selfConvId(调用者自身永不计入等待,防 self-wait deadlock)。
2460
- ...(ownerId
2461
- ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined,
2462
- // B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
2463
- // 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
2464
- () => bridgeAnchor.session
2465
- ? (this.findConversationHome?.(bridgeAnchor.session)?.convId ?? ownerId)
2466
- : ownerId)
2467
- : makeSubagentTools(this.subagentHost)),
2897
+ ...(noSpawnTools
2898
+ ? []
2899
+ : ownerId
2900
+ ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined,
2901
+ // B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
2902
+ // 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
2903
+ () => bridgeAnchor.session
2904
+ ? (this.findConversationHome?.(bridgeAnchor.session)?.convId ?? ownerId)
2905
+ : ownerId)
2906
+ : makeSubagentTools(this.subagentHost)),
2468
2907
  // 结构化派单(六段式 + 服务端校验;执行体复用子代理 spawn 通道)。
2469
2908
  // owner 包装与上面同理:子代理记到真正的派发会话名下。
2470
- ...(ownerId
2471
- ? [makeDelegateTaskTool(withSubagentOwner(this.subagentHost, ownerId))]
2472
- : [makeDelegateTaskTool(this.subagentHost)]),
2909
+ ...(noSpawnTools
2910
+ ? []
2911
+ : ownerId
2912
+ ? [makeDelegateTaskTool(withSubagentOwner(this.subagentHost, ownerId))]
2913
+ : [makeDelegateTaskTool(this.subagentHost)]),
2473
2914
  // 结构化任务计划更新(Plan Mode / Step State Machine)。
2474
2915
  makePlanUpdateTool(this.planManager, () => {
2475
2916
  const id = ownerId ?? this.activeId;
@@ -2539,8 +2980,13 @@ export class ClientSession {
2539
2980
  ownerId,
2540
2981
  lang: () => this.getLang(),
2541
2982
  }),
2542
- // 高可靠行补丁工具(patch,基于内容哈希与语法块级替换)。
2543
- makePatchTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
2983
+ // 高可靠行补丁工具(patch,基于内容哈希与语法块级替换)。写目标
2984
+ // (含 REM/MV)内嵌在补丁文本里,权限预设与敏感文件审批规则要靠
2985
+ // 包装器解析段头后求值——否则 read-only/workspace 沙箱与 .env 等
2986
+ // 规则会被 patch 整体旁路(write/edit 会拦的操作改走 patch 即落地)。
2987
+ wrapPatchToolWithPermission(makePatchTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2988
+ this.settingsSvc.current.defaultPermissionPreset ??
2989
+ "workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category, hits) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category, hits), () => ownerId, () => this.approvalRules.list()),
2544
2990
  // 原生语言服务器工具(lsp,定义跳转/引用/悬停/诊断)。
2545
2991
  makeLspTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
2546
2992
  // MCP 服务器检测与安装管理工具(mcp_manage:list/check/install/remove/reload)。
@@ -2566,19 +3012,34 @@ export class ClientSession {
2566
3012
  await this.refreshWorktreeInfo();
2567
3013
  },
2568
3014
  }, () => this.getLang()),
2569
- ].map((t) =>
2570
- // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2571
- // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
2572
- // 计划/审查者闸门同口径不在覆盖面,见 goal-review-gate.ts 头注)。
2573
- withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(t, () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
3015
+ // 画布流水线编辑工具(canvas:增删改查/重排/运行/调试;新节点 cwd 跟随当前项目)。
3016
+ makeCanvasTool({
3017
+ dataDir: this.stateStore.dataDir,
3018
+ lang: () => this.getLang(),
3019
+ getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
3020
+ }),
3021
+ ].map((t) => this.wrapGenericTool(t, ownerId, effectiveCwd)),
2574
3022
  });
2575
3023
  // 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
2576
3024
  // 不改它(见 ClientSession.findConversationHome)。
2577
3025
  bridgeAnchor.session = created.session;
2578
- // read / write / edit 三处覆盖在会话建好后注入(见 tool-overrides.ts):SDK 的合并链是
3026
+ if (noSpawnTools)
3027
+ SPAWN_TOOLS_BARRED.add(created.session);
3028
+ // bash / read / write / edit 四处覆盖在会话建好后注入(见 tool-overrides.ts):SDK 的合并链是
2579
3029
  // [...扩展工具, ...customTools] 后写赢 ⇒ 创建时塞进 customTools 会**恒定顶掉**第三方
2580
- // 扩展注册的同名工具(官方 docs/extensions.md 明写扩展可覆盖 read/write/edit)。
2581
- installToolOverrides(created.session, this.toolOverrideSpecs(ownerId, effectiveCwd));
3030
+ // 扩展注册的同名工具(官方 docs/extensions.md 明写扩展可覆盖 bash/read/write/edit,issue #750)。
3031
+ installToolOverrides(created.session, this.toolOverrideSpecs(ownerId, effectiveCwd, terminals), {
3032
+ onComposed: (name) => {
3033
+ if (name === "bash") {
3034
+ this.emit({
3035
+ type: "notice",
3036
+ level: "info",
3037
+ text: "已接入第三方扩展注册的 bash 工具(扩展审查/沙箱已生效,内置终端接管已让位)。",
3038
+ textEn: "Third-party extension bash tool is active (extension review/sandbox enabled; built-in terminal takeover yielded).",
3039
+ });
3040
+ }
3041
+ },
3042
+ });
2582
3043
  // 终端工具开关与预设门控从创建起就生效(工具始终注册进注册表,只调活跃集)。
2583
3044
  this.applyToolGating(created.session, targetPreset);
2584
3045
  return {
@@ -2638,7 +3099,8 @@ export class ClientSession {
2638
3099
  lastMessagesArray: [],
2639
3100
  queueSteering: [],
2640
3101
  queueFollowUp: [],
2641
- queuedImages: new Map(),
3102
+ queuedSteeringEntries: [],
3103
+ queuedFollowUpEntries: [],
2642
3104
  toolStartTimes: new Map(),
2643
3105
  toolPendingArgs: new Map(),
2644
3106
  activeToolCalls: new Map(),
@@ -2919,13 +3381,8 @@ export class ClientSession {
2919
3381
  onError: this.makeExtensionErrorReporter(conv.isEphemeral ? { text: `临时对话 ${conv.id}:`, textEn: `Ephemeral chat ${conv.id}: ` } : undefined),
2920
3382
  });
2921
3383
  conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
2922
- // 新会话 / 切换会话 / 强杀重建的必经之路:刚创建的 runtime 用的是 SDK
2923
- // 默认重试 3 次——这里把面板的 retryMaxAttempts 覆盖注入,否则“设了 6
2924
- // 次还是按 3 次重试”。已存在会话重复注入是幂等的(同值覆盖)。
2925
- this.applyRetryOverrides();
2926
- // 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
2927
- this.applyCompactionOverrides();
2928
- this.applyCodemodeOverrides();
3384
+ // 新会话 / 切换会话 / 强杀重建的必经之路:统一收口注入配置覆盖与工具门控
3385
+ this.applySessionOverrides(conv);
2929
3386
  this.scheduleSnapshot();
2930
3387
  this.webUi.refresh();
2931
3388
  this.startWidgetsTimer();
@@ -3037,6 +3494,13 @@ export class ClientSession {
3037
3494
  clearTimeout(t);
3038
3495
  conv.toolWatchdogs.clear();
3039
3496
  }
3497
+ /** 清理会话所有执行中的工具运行时状态(看门狗、计时器、进行中集合与参数缓存)。 */
3498
+ clearConversationToolStates(conv) {
3499
+ this.clearAllToolWatchdogs(conv);
3500
+ conv.toolStartTimes.clear();
3501
+ conv.activeToolCalls.clear();
3502
+ conv.toolPendingArgs.clear();
3503
+ }
3040
3504
  /** 发一条运行轨迹事件给插件(host.onRunEvent 订阅者,如轨迹视图插件)。
3041
3505
  * 异常隔离——序列化/插件坏了只记日志,绝不影响主流程。 */
3042
3506
  emitRun(conv, ev) {
@@ -3410,11 +3874,6 @@ export class ClientSession {
3410
3874
  // Any SDK event proves the run is alive — feeds the stall watchdog below.
3411
3875
  conv.lastSdkEventAt = Date.now();
3412
3876
  conv.stallNoticed = false;
3413
- // 模型可能在 pi-web-ui 之外被换(SDK 从会话历史恢复、/model 命令等),
3414
- // 而软上限 reserve 是按注入那一刻的窗口换算的固定值——模型一变必须重算,
3415
- // 否则大窗口算出的 reserve 泄漏到小窗口模型上,触发点被压成负数,
3416
- // 上下文刚过几万 token 就反复触发压缩。热路径只做一次字符串比对。
3417
- this.reapplySoftCapIfModelChanged(conv);
3418
3877
  switch (event.type) {
3419
3878
  case "bash_execution_update": {
3420
3879
  if (event.id) {
@@ -3430,6 +3889,8 @@ export class ClientSession {
3430
3889
  break;
3431
3890
  }
3432
3891
  case "tool_execution_start": {
3892
+ // issue #726:记录本轮触发了实质性工具操作,证明非空转推进
3893
+ conv.wakeTurnHadAction = true;
3433
3894
  // JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
3434
3895
  // automatically mark it as loaded so subsequent turns track it as fully active.
3435
3896
  if (conv.session && event.toolName) {
@@ -3560,14 +4021,8 @@ export class ClientSession {
3560
4021
  case "queue_update":
3561
4022
  conv.queueSteering = [...event.steering];
3562
4023
  conv.queueFollowUp = [...event.followUp];
3563
- if (conv.queuedImages && conv.queuedImages.size > 0) {
3564
- const allQueued = new Set([...event.steering, ...event.followUp]);
3565
- for (const key of conv.queuedImages.keys()) {
3566
- if (!allQueued.has(key)) {
3567
- conv.queuedImages.delete(key);
3568
- }
3569
- }
3570
- }
4024
+ conv.queuedSteeringEntries = reconcileQueuedEntries(conv.queuedSteeringEntries ?? [], event.steering);
4025
+ conv.queuedFollowUpEntries = reconcileQueuedEntries(conv.queuedFollowUpEntries ?? [], event.followUp);
3571
4026
  break;
3572
4027
  // 手动 /compact 或阈值/溢出自动压缩开始——常驻进度条(快照 compaction
3573
4028
  // 字段),而不是一次性 toast(toast 几秒就消失,而摘要生成可能持续
@@ -3701,6 +4156,19 @@ export class ClientSession {
3701
4156
  if (stopNotice) {
3702
4157
  this.emit({ type: "notice", level: "warning", text: stopNotice.text, textEn: stopNotice.textEn });
3703
4158
  }
4159
+ // 用户手动中止,重置自主轮次与空转计数(issue #726)
4160
+ conv.autonomousTurnsWithoutUser = 0;
4161
+ conv.consecutiveIdleWakeTurns = 0;
4162
+ conv.recentWakeSubagentIds = [];
4163
+ conv.wakeReason = undefined;
4164
+ conv.wakeTurnHadAction = undefined;
4165
+ if (conv.isSubagent &&
4166
+ conv.notifyOnDone !== false &&
4167
+ !conv.subagentDoneNotified &&
4168
+ !conv.subagentConsumedByParent &&
4169
+ conv.parentId) {
4170
+ this.scheduleSubagentCompletionNotice(conv);
4171
+ }
3704
4172
  this.emitConversations();
3705
4173
  break;
3706
4174
  }
@@ -3729,6 +4197,26 @@ export class ClientSession {
3729
4197
  // 或「等对话空闲」上,而 onAgentEnd 随后会把它需要的 verdict 交回。
3730
4198
  this.notifyTurnEnd(conv);
3731
4199
  this.goalSvc.onAgentEnd(conv, false);
4200
+ // issue #726:若本轮是由子代理唤醒触发,核算是否为空转
4201
+ if (conv.wakeReason === "subagent_completion") {
4202
+ if (conv.wakeTurnHadAction) {
4203
+ conv.consecutiveIdleWakeTurns = 0;
4204
+ }
4205
+ else {
4206
+ conv.consecutiveIdleWakeTurns = (conv.consecutiveIdleWakeTurns ?? 0) + 1;
4207
+ }
4208
+ conv.wakeReason = undefined;
4209
+ conv.wakeTurnHadAction = undefined;
4210
+ }
4211
+ // issue #713:子代理终态(非可重试瞬时错)时,安排向父对话自动发送完成通知
4212
+ if (conv.isSubagent &&
4213
+ !event.willRetry &&
4214
+ conv.notifyOnDone !== false &&
4215
+ !conv.subagentDoneNotified &&
4216
+ !conv.subagentConsumedByParent &&
4217
+ conv.parentId) {
4218
+ this.scheduleSubagentCompletionNotice(conv);
4219
+ }
3732
4220
  // Deferred settings reload: settings (system prompt / skills /
3733
4221
  // extensions) changed while the run was streaming — applying now
3734
4222
  // would have torn down the in-flight run.
@@ -3771,10 +4259,19 @@ export class ClientSession {
3771
4259
  }
3772
4260
  }, 50);
3773
4261
  }
4262
+ else if (!event.willRetry && !aborted && !this.disposed) {
4263
+ // 软上限主动压缩:回合结算后若上下文已达阈值,异步触发压缩(issue #716)
4264
+ setTimeout(() => {
4265
+ if (!this.disposed) {
4266
+ void this.triggerSoftCapCompactionIfExceeded(conv);
4267
+ }
4268
+ }, 50);
4269
+ }
3774
4270
  // 本轮真正结束且不再重试:立即向客户端广播最新会话状态(流式状态及时复位)
3775
4271
  if (!event.willRetry) {
3776
4272
  if (conv.queueSteering.length === 0 && conv.queueFollowUp.length === 0) {
3777
- conv.queuedImages?.clear();
4273
+ conv.queuedSteeringEntries = [];
4274
+ conv.queuedFollowUpEntries = [];
3778
4275
  if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
3779
4276
  conv.session._pendingNextTurnMessages = [];
3780
4277
  }
@@ -4133,53 +4630,17 @@ export class ClientSession {
4133
4630
  cost: s.cost,
4134
4631
  contextUsage: (() => {
4135
4632
  const cu = s.contextUsage;
4136
- if (!cu)
4633
+ if (!cu || cu.contextWindow <= 0)
4137
4634
  return stats.contextUsage;
4138
- // 压缩刚结束、下轮响应未到:SDK 报 null,用压缩结果回填约数。
4139
- if (cu.tokens == null && conv.lastCompactionTokens != null && cu.contextWindow > 0) {
4140
- return {
4141
- tokens: conv.lastCompactionTokens,
4142
- contextWindow: cu.contextWindow,
4143
- percent: (conv.lastCompactionTokens / cu.contextWindow) * 100,
4144
- estimated: false,
4145
- softCap: this.activeSoftCap(cu.contextWindow),
4146
- };
4147
- }
4148
- // 展示用兜底 0(会话未就绪时旧行为也是 0);落账 lastTurnBaseTokens 的路径
4149
- // 在 agent_settled 处对 null 跳过,不受此兜底影响。
4150
- const baseTokens = this.currentBaseTokens(conv) ?? 0;
4151
- // 空白会话(尚未发言,SDK 报 0 或 null):真实反映当前模式/工具配置下的 Base 开销。
4152
- if (cu.contextWindow > 0 && (this.isBlankConversation(conv) || cu.tokens == null || cu.tokens === 0)) {
4153
- return {
4154
- tokens: baseTokens,
4155
- contextWindow: cu.contextWindow,
4156
- percent: (baseTokens / cu.contextWindow) * 100,
4157
- estimated: false,
4158
- softCap: this.activeSoftCap(cu.contextWindow),
4159
- };
4160
- }
4161
- // 首轮对话中(或尚未获得带有效 usage 的定稿助手消息):
4162
- // 叠加精准的 Base 开销与当前非系统消息(用户输入、流式生成等)估算,
4163
- // 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致突增翻倍(如 10k 变成 17k)。
4164
- if ((conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) && cu.contextWindow > 0) {
4165
- const nonSystemTokens = this.estimateNonSystemTokens(conv);
4166
- const total = baseTokens + nonSystemTokens;
4167
- return {
4168
- tokens: total,
4169
- contextWindow: cu.contextWindow,
4170
- percent: (total / cu.contextWindow) * 100,
4171
- estimated: true,
4172
- softCap: this.activeSoftCap(cu.contextWindow),
4173
- };
4174
- }
4175
- // 已有多轮对话历史:若在对话间歇切预设或开关工具,叠加当前 Base 开销相比上一轮定稿时的差额
4176
- const baseDelta = baseTokens - (conv.lastTurnBaseTokens ?? baseTokens);
4177
- const effectiveTokens = Math.max(0, (cu.tokens ?? 0) + baseDelta);
4635
+ const effectiveTokens = this.getEffectiveContextTokens(conv);
4636
+ const isEstimated = cu.tokens != null &&
4637
+ (conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) &&
4638
+ !this.isBlankConversation(conv);
4178
4639
  return {
4179
4640
  tokens: effectiveTokens,
4180
4641
  contextWindow: cu.contextWindow,
4181
- percent: cu.contextWindow > 0 ? (effectiveTokens / cu.contextWindow) * 100 : cu.percent,
4182
- estimated: false,
4642
+ percent: (effectiveTokens / cu.contextWindow) * 100,
4643
+ estimated: isEstimated,
4183
4644
  softCap: this.activeSoftCap(cu.contextWindow),
4184
4645
  };
4185
4646
  })(),
@@ -4229,7 +4690,14 @@ export class ClientSession {
4229
4690
  // Only the levels the current model actually supports — the SDK clamps
4230
4691
  // anything else, so the UI must not offer (or must disable) the rest.
4231
4692
  availableThinkingLevels: this.session.getAvailableThinkingLevels(),
4232
- queue: { steering: conv.queueSteering, followUp: conv.queueFollowUp },
4693
+ queue: {
4694
+ steering: conv.queueSteering,
4695
+ followUp: conv.queueFollowUp,
4696
+ entries: {
4697
+ steering: toQueuedPromptItems(conv.queuedSteeringEntries ?? []),
4698
+ followUp: toQueuedPromptItems(conv.queuedFollowUpEntries ?? []),
4699
+ },
4700
+ },
4233
4701
  errorMessage: state.errorMessage,
4234
4702
  retry: conv.retryState ?? null,
4235
4703
  compaction: conv.compactionState ?? null,
@@ -4459,10 +4927,9 @@ export class ClientSession {
4459
4927
  if (p.conversationId === undefined || p.conversationId === conversationId)
4460
4928
  return true;
4461
4929
  }
4462
- for (const a of this.pendingApprovals.values()) {
4463
- if (a.conversationId === undefined || a.conversationId === conversationId)
4464
- return true;
4465
- }
4930
+ const conv = this.convs.get(conversationId);
4931
+ if (conv?.pendingApprovals && conv.pendingApprovals.size > 0)
4932
+ return true;
4466
4933
  return false;
4467
4934
  }
4468
4935
  /** 标准引擎的 question_answer 路由入口(index.ts 经 cs.answerQuestion?. 转发)。
@@ -4521,9 +4988,25 @@ export class ClientSession {
4521
4988
  return;
4522
4989
  }
4523
4990
  const id = `appr-${++this.approvalSeq}`;
4524
- const conv = conversationId ? this.convs.get(conversationId) : this.conv;
4525
- const suppression = approvalSuppressionReason(conv?.approvalPolicy, this.settingsSvc.current.toolApprovalEnabled !== false, category?.id);
4991
+ const targetConv = conversationId ? this.convs.get(conversationId) : this.conv;
4992
+ const resolvedConvId = conversationId ?? targetConv?.id ?? this.activeId;
4993
+ const conv = (resolvedConvId ? this.convs.get(resolvedConvId) : undefined) ?? targetConv;
4994
+ const suppression = approvalSuppressionReason(conv?.approvalPolicy, this.settingsSvc.current.toolApprovalEnabled !== false, category?.id, toolName, params);
4526
4995
  if (suppression) {
4996
+ // 记录静默放行审计日志(Issue #722)
4997
+ this.auditLogger.record({
4998
+ conversationId: resolvedConvId,
4999
+ toolName,
5000
+ params,
5001
+ decision: "approved",
5002
+ decisionSource: suppression === "disabled"
5003
+ ? "suppressed_disabled"
5004
+ : suppression === "allow-all"
5005
+ ? "suppressed_all"
5006
+ : "suppressed_category",
5007
+ categoryId: category?.id,
5008
+ reason,
5009
+ });
4527
5010
  // 放行但不弹窗:不记 pending,不发消息,模型继续跑。
4528
5011
  resolve({ decision: "approve" });
4529
5012
  return;
@@ -4538,6 +5021,10 @@ export class ClientSession {
4538
5021
  }
4539
5022
  }
4540
5023
  }
5024
+ if (!conv) {
5025
+ resolve({ decision: "deny", reason: "目标对话不存在" });
5026
+ return;
5027
+ }
4541
5028
  const entry = {
4542
5029
  id,
4543
5030
  toolCallId,
@@ -4548,12 +5035,12 @@ export class ClientSession {
4548
5035
  ...(category ? { category } : {}),
4549
5036
  ...(hits && hits.length > 0 ? { hits } : {}),
4550
5037
  ...(parentTool ? { parentTool } : {}),
4551
- conversationId,
5038
+ conversationId: conv.id,
4552
5039
  conversationTitle,
4553
5040
  resolve,
4554
5041
  createdAt: Date.now(),
4555
5042
  };
4556
- this.pendingApprovals.set(id, entry);
5043
+ this.ensurePendingApprovals(conv).set(id, entry);
4557
5044
  this.emit({
4558
5045
  type: "tool_approval_pending",
4559
5046
  id,
@@ -4565,7 +5052,7 @@ export class ClientSession {
4565
5052
  ...(category ? { category } : {}),
4566
5053
  ...(hits && hits.length > 0 ? { hits } : {}),
4567
5054
  ...(parentTool ? { parentTool } : {}),
4568
- ...(conversationId !== undefined ? { conversationId } : {}),
5055
+ conversationId: conv.id,
4569
5056
  ...(conversationTitle ? { conversationTitle } : {}),
4570
5057
  });
4571
5058
  this.flushSnapshot();
@@ -4579,21 +5066,48 @@ export class ClientSession {
4579
5066
  * 「全部允许」却还有几张弹窗挂着等点),并推一次设置面板(撤销区)。
4580
5067
  */
4581
5068
  resolveToolApproval(id, decision, editedParams, reason, scope) {
4582
- const pending = this.pendingApprovals.get(id);
4583
- if (!pending)
5069
+ let found = typeof this.findPendingApproval === "function" ? this.findPendingApproval(id) : undefined;
5070
+ if (!found) {
5071
+ // 兼容单测 mock 或旧结构中直接挂在 cs.pendingApprovals 上的对象
5072
+ const legacyPending = this.pendingApprovals?.get?.(id);
5073
+ if (legacyPending) {
5074
+ const convId = legacyPending.conversationId ?? this.activeId;
5075
+ const conv = convId ? this.convs.get(convId) : undefined;
5076
+ if (conv)
5077
+ found = { conv, entry: legacyPending };
5078
+ }
5079
+ }
5080
+ if (!found)
4584
5081
  return false;
4585
- const convId = pending.conversationId ?? this.activeId;
4586
- const conv = this.convs.get(convId);
4587
- this.pendingApprovals.delete(id);
5082
+ const { conv, entry: pending } = found;
5083
+ const convId = conv.id;
5084
+ conv.pendingApprovals?.delete(id);
5085
+ this.pendingApprovals?.delete?.(id);
5086
+ // 记录用户主动决策审计日志(Issue #722)
5087
+ this.auditLogger.record({
5088
+ conversationId: convId,
5089
+ toolName: pending.toolName,
5090
+ params: decision === "edit" ? editedParams : pending.params,
5091
+ decision: decision === "approve" ? "approved" : decision === "edit" ? "edited" : "denied",
5092
+ decisionSource: "user_dialog",
5093
+ scope: decision === "approve" ? scope : undefined,
5094
+ userEdited: decision === "edit",
5095
+ categoryId: pending.category?.id,
5096
+ reason: decision === "deny" ? reason : pending.reason,
5097
+ });
5098
+ // 用户主动审批(批准/编辑/拒绝)代表人类介入,重置自主轮次与空转计数(issue #726)
5099
+ conv.autonomousTurnsWithoutUser = 0;
5100
+ conv.consecutiveIdleWakeTurns = 0;
5101
+ conv.recentWakeSubagentIds = [];
4588
5102
  pending.resolve({ decision, editedParams, reason });
4589
5103
  this.emit({ type: "tool_approval_resolved", id });
4590
- if (decision === "approve" && scope && scope !== "once" && conv) {
5104
+ if (decision === "approve" && scope && scope !== "once") {
4591
5105
  const policy = this.ensureApprovalPolicy(conv);
4592
5106
  if (scope === "all")
4593
5107
  policy.allowAll = true;
4594
5108
  else if (pending.category)
4595
5109
  policy.categories.set(pending.category.id, pending.category);
4596
- this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(convId, policy));
5110
+ this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(conv, policy));
4597
5111
  this.settingsSvc.push();
4598
5112
  }
4599
5113
  this.flushSnapshot();
@@ -4606,15 +5120,24 @@ export class ClientSession {
4606
5120
  return conv.approvalPolicy;
4607
5121
  }
4608
5122
  /** 把某对话里已被策略覆盖的其它待审批项一并放行,返回放行条数。 */
4609
- approveCoveredPending(convId, policy) {
5123
+ approveCoveredPending(conv, policy) {
4610
5124
  let n = 0;
5125
+ if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
5126
+ return 0;
4611
5127
  // eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
4612
- for (const [oid, o] of [...this.pendingApprovals]) {
4613
- if ((o.conversationId ?? this.activeId) !== convId)
5128
+ for (const [oid, o] of [...conv.pendingApprovals]) {
5129
+ if (!approvalSuppressionReason(policy, true, o.category?.id, o.toolName, o.params))
4614
5130
  continue;
4615
- if (!approvalSuppressionReason(policy, true, o.category?.id))
4616
- continue;
4617
- this.pendingApprovals.delete(oid);
5131
+ conv.pendingApprovals.delete(oid);
5132
+ this.auditLogger.record({
5133
+ conversationId: conv.id,
5134
+ toolName: o.toolName,
5135
+ params: o.params,
5136
+ decision: "approved",
5137
+ decisionSource: "batch_approved_policy",
5138
+ categoryId: o.category?.id,
5139
+ reason: o.reason,
5140
+ });
4618
5141
  o.resolve({ decision: "approve" });
4619
5142
  this.emit({ type: "tool_approval_resolved", id: oid });
4620
5143
  n++;
@@ -4645,23 +5168,36 @@ export class ClientSession {
4645
5168
  }
4646
5169
  /** 全局审批开关被关掉时:挂着的待审批全部按批准放行(否则弹窗还在等人点)。 */
4647
5170
  autoApprovePendingApprovals(reasonZh, reasonEn) {
4648
- if (this.pendingApprovals.size === 0)
4649
- return;
4650
5171
  let n = 0;
4651
- // eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
4652
- for (const [oid, o] of [...this.pendingApprovals]) {
4653
- this.pendingApprovals.delete(oid);
4654
- o.resolve({ decision: "approve" });
4655
- this.emit({ type: "tool_approval_resolved", id: oid });
4656
- n++;
5172
+ for (const conv of this.convs.values()) {
5173
+ if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
5174
+ continue;
5175
+ // eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
5176
+ for (const [oid, o] of [...conv.pendingApprovals]) {
5177
+ conv.pendingApprovals.delete(oid);
5178
+ this.auditLogger.record({
5179
+ conversationId: o.conversationId,
5180
+ toolName: o.toolName,
5181
+ params: o.params,
5182
+ decision: "approved",
5183
+ decisionSource: "batch_approved_disabled",
5184
+ categoryId: o.category?.id,
5185
+ reason: o.reason,
5186
+ });
5187
+ o.resolve({ decision: "approve" });
5188
+ this.emit({ type: "tool_approval_resolved", id: oid });
5189
+ n++;
5190
+ }
5191
+ }
5192
+ if (n > 0) {
5193
+ this.emit({
5194
+ type: "notice",
5195
+ level: "info",
5196
+ text: `${reasonZh},已自动放行 ${n} 项待审批。`,
5197
+ textEn: `${reasonEn} — auto-approved ${n} pending request(s).`,
5198
+ });
5199
+ this.flushSnapshot();
4657
5200
  }
4658
- this.emit({
4659
- type: "notice",
4660
- level: "info",
4661
- text: `${reasonZh},已自动放行 ${n} 项待审批。`,
4662
- textEn: `${reasonEn} — auto-approved ${n} pending request(s).`,
4663
- });
4664
- this.flushSnapshot();
4665
5201
  }
4666
5202
  /**
4667
5203
  * 设置面板撤销区用:当前对话的审批策略(allowAll + 已记住的同类档位)。
@@ -4677,14 +5213,20 @@ export class ClientSession {
4677
5213
  categories: policy ? [...policy.categories.values()] : [],
4678
5214
  };
4679
5215
  }
5216
+ /** 获取审批决策审计日志记录器(Issue #722)。 */
5217
+ getAuditLogger() {
5218
+ return this.auditLogger;
5219
+ }
4680
5220
  /**
4681
5221
  * 设置某对话的审批策略(设置面板撤销用)。只应用给出的字段:allowAll 直接赋值;
4682
5222
  * categories 给出时作为保留名单整体替换(空数组 = 清掉全部同类记忆)。
4683
5223
  */
4684
5224
  setApprovalPolicy(partial) {
4685
5225
  const convId = partial.conversationId ?? this.activeId;
5226
+ if (!convId)
5227
+ return;
4686
5228
  const conv = this.convs.get(convId);
4687
- if (!conv)
5229
+ if (!conv || conv.isSubagent)
4688
5230
  return;
4689
5231
  const cur = conv.approvalPolicy;
4690
5232
  const next = {
@@ -4703,9 +5245,10 @@ export class ClientSession {
4703
5245
  this.flushSnapshot();
4704
5246
  }
4705
5247
  pendingApprovalForSnapshot() {
4706
- for (const [id, p] of this.pendingApprovals) {
4707
- if (p.conversationId !== undefined && p.conversationId !== this.activeId)
4708
- continue;
5248
+ const conv = this.conv;
5249
+ if (!conv?.pendingApprovals || conv.pendingApprovals.size === 0)
5250
+ return null;
5251
+ for (const [id, p] of conv.pendingApprovals) {
4709
5252
  return {
4710
5253
  id,
4711
5254
  toolCallId: p.toolCallId,
@@ -4846,31 +5389,48 @@ export class ClientSession {
4846
5389
  // 单个结算异常不影响其余清理
4847
5390
  }
4848
5391
  }
4849
- for (const [id, a] of this.pendingApprovals) {
4850
- if (a.conversationId !== convId)
5392
+ const conv = this.convs.get(convId);
5393
+ if (conv?.pendingApprovals && conv.pendingApprovals.size > 0) {
5394
+ for (const [id, a] of conv.pendingApprovals) {
5395
+ try {
5396
+ a.resolve({ decision: "deny", reason: "运行已停止" });
5397
+ }
5398
+ catch {
5399
+ // 单个结算异常不影响其余清理
5400
+ }
5401
+ this.emit({ type: "tool_approval_resolved", id });
5402
+ }
5403
+ conv.pendingApprovals.clear();
5404
+ }
5405
+ for (const [id, p] of this.pendingPageCalls) {
5406
+ if (p.conversationId !== convId)
4851
5407
  continue;
4852
- this.pendingApprovals.delete(id);
5408
+ this.pendingPageCalls.delete(id);
5409
+ clearTimeout(p.timer);
4853
5410
  try {
4854
- a.resolve({ decision: "deny", reason: "运行已停止" });
5411
+ p.resolve({ ok: false, error: "会话已重置或停止,挂起中的页面调用已取消。" });
4855
5412
  }
4856
5413
  catch {
4857
5414
  // 单个结算异常不影响其余清理
4858
5415
  }
4859
- this.emit({ type: "tool_approval_resolved", id });
4860
5416
  }
4861
5417
  }
4862
5418
  /** 关闭所有挂起审批(dispose 时清理):以「拒绝」解析,避免等答复的
4863
5419
  * Promise 与对应 runtime 泄漏(会话没了,审批弹窗永远不会有人点)。 */
4864
5420
  cancelPendingApprovals() {
4865
- for (const [id, a] of this.pendingApprovals) {
4866
- this.pendingApprovals.delete(id);
4867
- try {
4868
- a.resolve({ decision: "deny", reason: "会话已关闭" });
4869
- }
4870
- catch {
4871
- // 单个 resolve 异常不影响其余清理
5421
+ for (const conv of this.convs.values()) {
5422
+ if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
5423
+ continue;
5424
+ for (const [id, a] of conv.pendingApprovals) {
5425
+ try {
5426
+ a.resolve({ decision: "deny", reason: "会话已关闭" });
5427
+ }
5428
+ catch {
5429
+ // 单个 resolve 异常不影响其余清理
5430
+ }
5431
+ this.emit({ type: "tool_approval_resolved", id });
4872
5432
  }
4873
- this.emit({ type: "tool_approval_resolved", id });
5433
+ conv.pendingApprovals.clear();
4874
5434
  }
4875
5435
  }
4876
5436
  // -----------------------------------------------------------------------
@@ -5560,11 +6120,8 @@ export class ClientSession {
5560
6120
  setPlanMode: (enabled) => this.setPlanMode(enabled),
5561
6121
  getPlanMode: () => this.conv?.planMode === true,
5562
6122
  afterReload: () => {
5563
- // /reload 同样重读磁盘 settings.json——重放重试覆盖 + 软上限覆盖 + 终端门控。
5564
- this.applyRetryOverrides();
5565
- this.applyCompactionOverrides();
5566
- this.applyCodemodeOverrides();
5567
- this.applyToolGating(this.session, this.conv?.agentPreset);
6123
+ // /reload 同样重读磁盘 settings.json——统一收口重放配置覆盖与工具门控。
6124
+ this.applySessionOverrides(this.conv);
5568
6125
  },
5569
6126
  pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
5570
6127
  execPluginCommand: async (name, args) => {
@@ -5907,6 +6464,26 @@ export class ClientSession {
5907
6464
  pushSettings() {
5908
6465
  this.settingsSvc.push();
5909
6466
  }
6467
+ /**
6468
+ * 统一会话配置与门控收口方法(单一事实源)。
6469
+ * 无论是新建、切换、回滚、编辑重问、看门狗重置还是设置变更:
6470
+ * 统一应用重试次数、压缩防爆保留值、codemode 预算以及工具门控(含 planMode/delegateMode/禁用名单/权限预设)。
6471
+ * 彻底杜绝各业务入口散落调用与遗漏。
6472
+ */
6473
+ applySessionOverrides(target) {
6474
+ const conv = target ?? this.conv;
6475
+ if (!conv?.session)
6476
+ return;
6477
+ try {
6478
+ this.applyRetryOverrides();
6479
+ this.applyCompactionOverrides();
6480
+ this.applyCodemodeOverrides();
6481
+ this.applyToolGating(conv.session, conv.agentPreset);
6482
+ }
6483
+ catch {
6484
+ // 会话未就绪或已释放
6485
+ }
6486
+ }
5910
6487
  /** 把设置面板的出错重试次数注入全部存活会话的 SDK SettingsManager。
5911
6488
  * applyOverrides 只改内存合并视图(不碰 ~/.pi/agent/settings.json),
5912
6489
  * 且 SDK 每次退避前都重读 getRetrySettings()——即时生效、无需 reload。
@@ -5923,36 +6500,21 @@ export class ClientSession {
5923
6500
  }
5924
6501
  }
5925
6502
  }
5926
- /** 把压缩软上限换算成各存活会话的 compaction reserveTokens 覆盖
5927
- * (issue #229)。与重试覆盖同一 live 机制:applyOverrides 只改内存
5928
- * 合并视图,SDK 每次自动压缩检查前都重读 getCompactionSettings(),
5929
- * 无需 reload;软上限关闭时回填 SDK 默认 reserve(不让旧覆盖泄漏)。
5930
- * 窗口未知(会话未就绪/无模型)的会话跳过——创建/就绪/换模型路径
5931
- * 会重放(见各 applyRetryOverrides 调用点);此外 onEvent 按模型
5932
- * key 变化兜底重放(reapplySoftCapIfModelChanged),保证会话模型
5933
- * 在 pi-web-ui 之外被换(如 SDK 从会话历史恢复)后覆盖不泄漏。 */
6503
+ /** 确保各存活会话的 SDK compaction reserveTokens 保持默认值(issue #716)。
6504
+ * 软上限由 pi-web-ui 主动管控(triggerSoftCapCompactionIfExceeded),
6505
+ * 不再将 W - C 注入 SDK reserveTokens,从数学上杜绝换模型重算泄漏。 */
5934
6506
  applyCompactionOverrides() {
5935
- const s = this.settingsSvc.current;
5936
6507
  for (const c of this.convs.values()) {
5937
6508
  try {
5938
- this.applyCompactionOverrideForConv(c, s);
6509
+ c.session.settingsManager.applyOverrides({
6510
+ compaction: { reserveTokens: DEFAULT_COMPACTION_RESERVE_TOKENS },
6511
+ });
5939
6512
  }
5940
6513
  catch {
5941
6514
  // 会话未就绪或已释放 → 其 runtime 创建时统一注入。
5942
6515
  }
5943
6516
  }
5944
6517
  }
5945
- /** 单会话换算并注入软上限 reserve(applyCompactionOverrides 的循环体;
5946
- * reapplySoftCapIfModelChanged 单会话重放也复用)。抛错交调用方处置。 */
5947
- applyCompactionOverrideForConv(c, s) {
5948
- const modelId = modelKeyOf(c.session);
5949
- const contextWindow = contextWindowOf(c.session);
5950
- const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelId);
5951
- const reserve = softCapToReserve(contextWindow, cap);
5952
- c.session.settingsManager.applyOverrides({
5953
- compaction: { reserveTokens: reserve ?? DEFAULT_COMPACTION_RESERVE_TOKENS },
5954
- });
5955
- }
5956
6518
  /** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
5957
6519
  applyCodemodeOverrides() {
5958
6520
  const mode = this.settingsSvc.current.codemodeMode ?? "on";
@@ -5968,23 +6530,64 @@ export class ClientSession {
5968
6530
  }
5969
6531
  }
5970
6532
  }
5971
- /** 会话模型变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
5972
- * (findInitialModel)与 /model 命令都不经过 pi-web-ui 的 setModel
5973
- * 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
5974
- * 模型(1M 窗口)算出 748576,泄漏到 500K 窗口的会话后压缩触发点
5975
- * 变成负数,上下文几万 token 就被反复压缩。onEvent 每个事件比对
5976
- * 一次 model key(O(1) 字符串比较),变化才重放。 */
5977
- reapplySoftCapIfModelChanged(conv) {
6533
+ /** 计算指定会话当前的有效上下文 token 估算值(对齐底栏展示逻辑)。 */
6534
+ getEffectiveContextTokens(conv) {
5978
6535
  try {
5979
- const key = modelKeyOf(conv.session);
5980
- if (conv.lastModelKey === key)
5981
- return;
5982
- conv.lastModelKey = key;
5983
- if (key)
5984
- this.applyCompactionOverrideForConv(conv, this.settingsSvc.current);
6536
+ const cu = conv.session?.getSessionStats()?.contextUsage;
6537
+ if (!cu || cu.contextWindow <= 0)
6538
+ return 0;
6539
+ // 压缩刚结束、下轮响应未到:SDK 报 null,用压缩结果回填约数。
6540
+ if (cu.tokens == null && conv.lastCompactionTokens != null) {
6541
+ return conv.lastCompactionTokens;
6542
+ }
6543
+ const baseTokens = this.currentBaseTokens(conv) ?? 0;
6544
+ if (this.isBlankConversation(conv) || cu.tokens == null || cu.tokens === 0) {
6545
+ return baseTokens;
6546
+ }
6547
+ if (conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) {
6548
+ const nonSystemTokens = this.estimateNonSystemTokens(conv);
6549
+ return baseTokens + nonSystemTokens;
6550
+ }
6551
+ const baseDelta = baseTokens - (conv.lastTurnBaseTokens ?? baseTokens);
6552
+ return Math.max(0, (cu.tokens ?? 0) + baseDelta);
5985
6553
  }
5986
6554
  catch {
5987
- // 会话未就绪或已释放 → 留给创建/换模型路径与后续事件重试。
6555
+ return 0;
6556
+ }
6557
+ }
6558
+ /**
6559
+ * 若当前会话的有效 token 超过软上限,主动触发 SDK 上下文压缩(issue #716)。
6560
+ * 仅在空闲状态下触发(不会掐断进行中的任务)。
6561
+ * 返回是否触发了压缩。
6562
+ */
6563
+ async triggerSoftCapCompactionIfExceeded(conv) {
6564
+ try {
6565
+ const session = conv.session;
6566
+ if (!session || session.isStreaming)
6567
+ return false;
6568
+ const contextWindow = contextWindowOf(session);
6569
+ const cap = this.activeSoftCap(contextWindow);
6570
+ if (!cap || cap <= 0)
6571
+ return false;
6572
+ const currentTokens = this.getEffectiveContextTokens(conv);
6573
+ if (currentTokens < cap)
6574
+ return false;
6575
+ await session.compact();
6576
+ return true;
6577
+ }
6578
+ catch (err) {
6579
+ const msg = err instanceof Error ? err.message : String(err);
6580
+ // SDK 的边界报错:Already compacted 或 Nothing to compact 属于正常跳过
6581
+ if (msg.includes("Already compacted") || msg.includes("Nothing to compact")) {
6582
+ return false;
6583
+ }
6584
+ this.emit({
6585
+ type: "notice",
6586
+ level: "warning",
6587
+ text: `软上限上下文自动压缩未完成:${msg}`,
6588
+ textEn: `Soft cap context compaction did not complete: ${msg}`,
6589
+ });
6590
+ return false;
5988
6591
  }
5989
6592
  }
5990
6593
  /** 当前活动对话的生效软上限(快照底栏标记线用;null = 关闭/未知)。 */
@@ -5992,7 +6595,11 @@ export class ClientSession {
5992
6595
  try {
5993
6596
  const s = this.settingsSvc.current;
5994
6597
  const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(this.session));
5995
- return softCapToReserve(contextWindow, cap) === null ? null : cap;
6598
+ if (!cap || cap < SOFT_CAP_MIN_TOKENS)
6599
+ return null;
6600
+ if (contextWindow > 0 && cap >= contextWindow - SOFT_CAP_MIN_HEADROOM)
6601
+ return null;
6602
+ return cap;
5996
6603
  }
5997
6604
  catch {
5998
6605
  return null;
@@ -6036,9 +6643,7 @@ export class ClientSession {
6036
6643
  if (!this.session.isStreaming) {
6037
6644
  try {
6038
6645
  await this.session.reload();
6039
- this.applyRetryOverrides();
6040
- this.applyCompactionOverrides();
6041
- this.applyToolGating(this.session, this.conv?.agentPreset);
6646
+ this.applySessionOverrides(this.conv);
6042
6647
  await this.pushSlashCommands();
6043
6648
  this.pushSettings();
6044
6649
  }
@@ -6424,9 +7029,7 @@ export class ClientSession {
6424
7029
  if (this.session && !this.session.isStreaming) {
6425
7030
  try {
6426
7031
  await this.session.reload();
6427
- this.applyRetryOverrides();
6428
- this.applyCompactionOverrides();
6429
- this.applyToolGating(this.session, this.conv?.agentPreset);
7032
+ this.applySessionOverrides(this.conv);
6430
7033
  await this.pushSlashCommands();
6431
7034
  }
6432
7035
  catch {
@@ -6453,11 +7056,11 @@ export class ClientSession {
6453
7056
  return undefined;
6454
7057
  }
6455
7058
  /**
6456
- * read / write / edit 三处覆盖的注入规格:基底 = 扩展注册的同名工具优先,否则 SDK 内置实现
6457
- * (见 tool-overrides.ts —— 这三处覆盖不能塞进创建时的 `customTools`,那会静默顶掉扩展的
6458
- * 同名工具,而官方 docs/extensions.md 明写扩展可覆盖 read/write/edit)。
7059
+ * bash / read / write / edit 四处覆盖的注入规格:基底 = 扩展注册的同名工具优先,否则 SDK 内置实现
7060
+ * (见 tool-overrides.ts —— 这四处覆盖不能塞进创建时的 `customTools`,那会静默顶掉扩展的
7061
+ * 同名工具,而官方 docs/extensions.md 明写扩展可覆盖 bash/read/write/edit,issue #750)。
6459
7062
  */
6460
- toolOverrideSpecs(ownerId, cwd) {
7063
+ toolOverrideSpecs(ownerId, cwd, terminals) {
6461
7064
  const currentPermission = () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
6462
7065
  this.settingsSvc.current.defaultPermissionPreset ??
6463
7066
  "workspace-write-never";
@@ -6476,15 +7079,78 @@ export class ClientSession {
6476
7079
  getRoots: () => this.roots,
6477
7080
  askApproval: approve,
6478
7081
  getRules: () => this.approvalRules.list(),
7082
+ onAudit: (entry) => this.auditLogger.record(entry),
6479
7083
  };
6480
- // 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
7084
+ // 写/编/终端的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
6481
7085
  // 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
6482
7086
  // 快照并发门禁包裹在工具执行最前沿,确保写操作前快照必定已就绪。
6483
- const planGate = (def) => withWorkspaceSnapshotGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => this.awaitPendingWorkspaceSnapshot(ownerId));
7087
+ const planGate = (def) => withWorkspaceSnapshotGate(withSubagentSecurityGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => ({
7088
+ mode: this.subagentSecurityModeOf(ownerId),
7089
+ allowedTools: this.subagentAllowedToolsOf(ownerId),
7090
+ }), () => this.getLang()), () => this.awaitPendingWorkspaceSnapshot(ownerId));
6484
7091
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6485
7092
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
7093
+ const composeBash = (base) => {
7094
+ let core;
7095
+ if (base) {
7096
+ // 扩展提供了同名 bash:以扩展定义为基底,保留其 schema/描述/guidelines,
7097
+ // 同时挂载 abort_bash 信号中断支持与 head/tail 输出后处理。
7098
+ core = {
7099
+ ...base,
7100
+ execute: async (toolCallId, params, signal, onUpdate, ctx) => {
7101
+ const ac = new AbortController();
7102
+ this.bashKills.add(ac);
7103
+ try {
7104
+ const signals = [signal, ac.signal].filter((s) => s !== undefined);
7105
+ const combinedSignal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
7106
+ const result = (await base.execute(toolCallId, params, combinedSignal, onUpdate, ctx));
7107
+ const p = params;
7108
+ if ((p?.head || p?.tail) && result?.content?.[0]?.text != null) {
7109
+ result.content[0].text = applyHeadTail(result.content[0].text, p.head, p.tail, this.getLang());
7110
+ }
7111
+ return result;
7112
+ }
7113
+ finally {
7114
+ this.bashKills.delete(ac);
7115
+ }
7116
+ },
7117
+ };
7118
+ }
7119
+ else {
7120
+ // 没有扩展 bash:完整的原生与终端自适应分流 bash(行为与改动前逐字一致)。
7121
+ core = makeAdaptiveBashTool(makeKillableBashTool(cwd, this.bashKills, () => this.getLang()), terminals
7122
+ ? makeTerminalBashTool(terminals, {
7123
+ cwd,
7124
+ defaultPersist: () => false,
7125
+ idleMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashIdleMs) || 0),
7126
+ maxForegroundMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashMaxForegroundMs) || 0),
7127
+ kills: this.bashKills,
7128
+ notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
7129
+ lang: () => this.getLang(),
7130
+ })
7131
+ : makeKillableBashTool(cwd, this.bashKills, () => this.getLang()), () => Boolean(terminals && this.settingsSvc.current.terminalBash));
7132
+ }
7133
+ const guarded = withToolGuard(withWorkspaceSnapshotGate(core, () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
7134
+ toolName: "bash",
7135
+ guard: this.lateToolGuard,
7136
+ conversationId: () => ownerId,
7137
+ getLang: () => this.getLang(),
7138
+ cwd,
7139
+ getRoots: () => this.roots,
7140
+ askApproval: approve,
7141
+ getRules: () => this.approvalRules.list(),
7142
+ onAudit: (entry) => this.auditLogger.record(entry),
7143
+ });
7144
+ const permissionWrapped = wrapBashToolWithPermission(guarded, currentPermission, () => this.getLang());
7145
+ return this.wrapGenericTool(permissionWrapped, ownerId, cwd);
7146
+ };
6486
7147
  const remoteOps = createRemoteSdkOperations(cwd);
6487
7148
  const specs = [
7149
+ {
7150
+ name: "bash",
7151
+ fallback: () => composeBash(),
7152
+ composeWith: (base) => composeBash(base),
7153
+ },
6488
7154
  {
6489
7155
  name: "read",
6490
7156
  // 没有扩展 read:完整覆盖(内置基底 + 英文描述 + file_path 别名)。
@@ -6542,18 +7208,41 @@ export class ClientSession {
6542
7208
  this.settingsSvc.current.defaultAgentPreset ??
6543
7209
  "standard";
6544
7210
  const isPlanMode = conv?.planMode === true;
7211
+ const isDelegateMode = conv?.delegateMode === true;
6545
7212
  const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
6546
7213
  if (isPlanMode) {
6547
7214
  for (const toolName of PLAN_MODE_BLOCKED_TOOL_NAMES) {
6548
7215
  disabled.add(toolName);
6549
7216
  }
6550
7217
  }
7218
+ else if (isDelegateMode) {
7219
+ for (const toolName of DELEGATE_MODE_BLOCKED_TOOL_NAMES) {
7220
+ disabled.add(toolName);
7221
+ }
7222
+ }
7223
+ if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
7224
+ try {
7225
+ for (const t of session.getAllTools()) {
7226
+ if (!conv.subagentAllowedTools.has(t.name)) {
7227
+ disabled.add(t.name);
7228
+ }
7229
+ }
7230
+ }
7231
+ catch { }
7232
+ }
7233
+ if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
7234
+ for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
7235
+ disabled.add(toolName);
7236
+ }
7237
+ }
6551
7238
  // 延迟加载(默认开):未加载的已登记工具一律当「临时禁用」——与用户禁用名单 /
6552
7239
  // 计划模式闸门走同一条门控链,不做第二套机制。加载只是把名字从这份名单里拿出来。
7240
+ let loadedNames = [];
6553
7241
  const lazy = this.lazyLoadingOn();
6554
7242
  if (lazy) {
6555
7243
  try {
6556
7244
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
7245
+ loadedNames = [...loaded];
6557
7246
  for (const name of lazyLoadingDisabledTools(session.getAllTools().map((t) => t.name), loaded)) {
6558
7247
  disabled.add(name);
6559
7248
  }
@@ -6567,10 +7256,14 @@ export class ClientSession {
6567
7256
  }
6568
7257
  applyAgentToolsGating(session, [...disabled], targetPreset, {
6569
7258
  // load_tools 不在任何预设白名单里,又必须在延迟加载开启时永远可用(ask 预设本来就无工具,不强加;非延迟加载模式不激活)。
6570
- forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME] : [],
7259
+ // 显式 load_tools 加载过的名字一并强制激活:PATCH-B1 门控会无条件剔除
7260
+ // exposure≠direct 的 MCP 工具(连 deferred 的也在内),若这里不把它们
7261
+ // 加回活跃集,会复现 #652 的死路变体——「已加载且目录可见,但永不活跃」。
7262
+ forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME, ...loadedNames] : [],
6571
7263
  });
6572
7264
  const ownerId = conv?.id;
6573
- syncSubagentOverride(session, disabled.has("subagent"), () => ownerId
7265
+ const subagentOff = disabled.has("subagent") || SPAWN_TOOLS_BARRED.has(session);
7266
+ syncSubagentOverride(session, subagentOff, () => ownerId
6574
7267
  ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined, ownerId)[0]
6575
7268
  : makeSubagentTools(this.subagentHost)[0]);
6576
7269
  this.syncPluginTools(session, targetPreset);
@@ -6728,6 +7421,16 @@ export class ClientSession {
6728
7421
  const id = ownerId ?? this.activeId;
6729
7422
  return this.convs.get(id)?.awaitingVerdict != null;
6730
7423
  }
7424
+ /** 子代理安全规格模式("normal" | "readonly" | "verify",issue #727)。 */
7425
+ subagentSecurityModeOf(ownerId) {
7426
+ const id = ownerId ?? this.activeId;
7427
+ return this.convs.get(id)?.subagentSecurityMode ?? "normal";
7428
+ }
7429
+ /** 子代理显式允许的工具白名单集合(issue #727)。 */
7430
+ subagentAllowedToolsOf(ownerId) {
7431
+ const id = ownerId ?? this.activeId;
7432
+ return this.convs.get(id)?.subagentAllowedTools;
7433
+ }
6731
7434
  /** 等待该会话正在并发生成的影子快照完成,确保写操作发生在快照完成之后。 */
6732
7435
  async awaitPendingWorkspaceSnapshot(ownerId) {
6733
7436
  const id = ownerId ?? this.activeId;
@@ -7066,6 +7769,32 @@ export class ClientSession {
7066
7769
  this.refreshPermission();
7067
7770
  this.flushSnapshot();
7068
7771
  }
7772
+ /**
7773
+ * 统一工具安全流水线(Issue #722):
7774
+ * 将通用工具(包括插件 AI 工具、MCP 桥接工具、第一方辅助工具等)统一包裹:
7775
+ * 1. withApprovalGate:检查审批规则(checkDangerousToolCall)与人机协同审批;
7776
+ * 2. withSandboxJailGate:工作区沙箱越界拦截;
7777
+ * 3. withPlanModeGate:计划模式只读拦截;
7778
+ * 4. withDelegationGate:审查者委派拦截;
7779
+ * 5. withGoalReviewGate:目标审查回合拦截;
7780
+ * 6. withSubagentSecurityGate:子代理安全规格拦截(只读/审查/工具白名单,issue #727)。
7781
+ * 无论是会话创建时的静态 customTools 还是 syncPluginTools 动态注入的工具,均无差别经由此管道。
7782
+ */
7783
+ wrapGenericTool(def, ownerId, cwdOverride) {
7784
+ const getEffectiveCwd = () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? cwdOverride ?? this.cwd;
7785
+ return withSubagentSecurityGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(withApprovalGate(def, {
7786
+ cwd: getEffectiveCwd,
7787
+ getRoots: () => this.roots,
7788
+ getRules: () => this.approvalRules.list(),
7789
+ getLang: () => this.getLang(),
7790
+ conversationId: () => ownerId,
7791
+ askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category, hits) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category, hits),
7792
+ onAudit: (entry) => this.auditLogger.record(entry),
7793
+ }), () => this.sandboxes.getByCwd(getEffectiveCwd()), getEffectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => ({
7794
+ mode: this.subagentSecurityModeOf(ownerId),
7795
+ allowedTools: this.subagentAllowedToolsOf(ownerId),
7796
+ }), () => this.getLang());
7797
+ }
7069
7798
  /** 当前启用的插件 AI 工具定义(provider 快照按 disabledPlugins 与 disabledPluginTools 过滤;
7070
7799
  * 未知/已卸载插件的禁用条目保留但不影响现有工具)。
7071
7800
  * 预设是第二层门控(见 tool-manager.ts 语义总表):非 standard 预设下插件工具
@@ -7086,18 +7815,21 @@ export class ClientSession {
7086
7815
  /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
7087
7816
  * 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。
7088
7817
  * 模板白名单的子代理(subagentBarsPluginTools)跳过:工厂期就没注册,这里
7089
- * 不回补,否则白名单等于没关门。 */
7818
+ * 不回补,否则白名单等于没关门。
7819
+ * 动态补入的工具统一经 wrapGenericTool 包裹,具备模式硬闸门与审批规则防护(Issue #722)。 */
7090
7820
  syncPluginTools(session, preset) {
7091
7821
  let targetPreset = preset;
7092
- for (const conv of this.convs.values()) {
7822
+ let ownerId;
7823
+ for (const [id, conv] of this.convs.entries()) {
7093
7824
  if (conv.session !== session)
7094
7825
  continue;
7826
+ ownerId = id;
7095
7827
  if (conv.subagentBarsPluginTools)
7096
7828
  return;
7097
7829
  targetPreset ??= conv.agentPreset;
7098
7830
  }
7099
7831
  try {
7100
- const defs = this.enabledPluginToolDefs(targetPreset);
7832
+ const defs = this.enabledPluginToolDefs(targetPreset).map((t) => this.wrapGenericTool(t, ownerId));
7101
7833
  // 移除口径 = 已同步过的 ∪ 全量插件宇宙:创建时工厂直接注册进
7102
7834
  // _customTools 的工具不在 applied 表里,首轮同步(defs 为空时)否则删不掉。
7103
7835
  const universe = new Set([
@@ -7117,6 +7849,11 @@ export class ClientSession {
7117
7849
  for (const conv of this.convs.values())
7118
7850
  this.syncPluginTools(conv.session);
7119
7851
  }
7852
+ /** index.ts 经 pluginMgr.onMarkersChanged 触发:刷新客户端 markers 设置与小部件。 */
7853
+ refreshPluginMarkers() {
7854
+ this.settingsSvc.push();
7855
+ this.markerSvc.pushOverlay(this.activeId);
7856
+ }
7120
7857
  async applySettingsReload() {
7121
7858
  // 兼容旧入口:reload + 刷目录在宿主回调里完成
7122
7859
  return this.settingsSvc.applyRuntime();
@@ -7283,6 +8020,10 @@ export class ClientSession {
7283
8020
  * (随主对话一起搬)。activity = 该对话最近一次活跃时间(离线行的宽限期判定用,
7284
8021
  * 见 OFFLINE_ROW_TTL_MS)。 */
7285
8022
  streamingSummariesAll() {
8023
+ // 画布专用客户端(CanvasStudio)绝不参与聊天会话列表感知,杜绝向 elsewhere 暴露任何条目
8024
+ if (this.clientId?.startsWith("canvas:") || this.clientId?.startsWith("canvas-")) {
8025
+ return [];
8026
+ }
7286
8027
  const out = [];
7287
8028
  const seenFiles = new Set();
7288
8029
  for (const conv of this.convs.values()) {
@@ -7382,8 +8123,35 @@ export class ClientSession {
7382
8123
  * after the current turn settles, skipping remaining planned tool calls.
7383
8124
  */
7384
8125
  queue = false) {
7385
- const trimmedText = (text ?? "").trim();
8126
+ // Captured at the START (before any await): the conversation being
8127
+ // addressed by this prompt. See the naming block below — a concurrent
8128
+ // switch/new_chat while prompt() is in flight must never target a
8129
+ // different conversation.
8130
+ const conv = this.conv;
8131
+ // 人类用户发送新消息,重置自主轮次与空转计数器(issue #726)
8132
+ conv.autonomousTurnsWithoutUser = 0;
8133
+ conv.consecutiveIdleWakeTurns = 0;
8134
+ conv.recentWakeSubagentIds = [];
8135
+ conv.wakeReason = "user";
8136
+ conv.wakeTurnHadAction = undefined;
8137
+ // issue #726:若当前对话存在自动唤醒挂起期间暂存的子代理完成通知,
8138
+ // 自动提取合并并注入,确保挂起期间的通知 100% 零丢失
8139
+ const drainer = this.drainSuspendedSubagents ?? ClientSession.prototype.drainSuspendedSubagents;
8140
+ const bufferedSubagents = drainer ? drainer.call(this, conv) : [];
8141
+ const rawTrimmed = (text ?? "").trim();
7386
8142
  const hasAttachments = Boolean(attachments && attachments.length > 0);
8143
+ if (bufferedSubagents.length > 0) {
8144
+ const bufferedNotice = formatSubagentsCompletionNotice(bufferedSubagents, this.getLang());
8145
+ if (!rawTrimmed && !hasAttachments) {
8146
+ text = bufferedNotice;
8147
+ }
8148
+ else {
8149
+ const prefixZh = `[在自动唤醒挂起期间已完成的子代理通知]:\n\n${bufferedNotice}\n\n---\n[用户最新指令]:\n`;
8150
+ const prefixEn = `[Buffered subagent completion notice(s) during suspended auto-wake]:\n\n${bufferedNotice}\n\n---\n[User instruction]:\n`;
8151
+ text = `${this.getLang() === "zh" ? prefixZh : prefixEn}${text}`;
8152
+ }
8153
+ }
8154
+ const trimmedText = (text ?? "").trim();
7387
8155
  if (!trimmedText && !hasAttachments) {
7388
8156
  this.emit({
7389
8157
  type: "notice",
@@ -7394,11 +8162,6 @@ export class ClientSession {
7394
8162
  this.flushSnapshot();
7395
8163
  return;
7396
8164
  }
7397
- // Captured at the START (before any await): the conversation being
7398
- // addressed by this prompt. See the naming block below — a concurrent
7399
- // switch/new_chat while prompt() is in flight must never target a
7400
- // different conversation.
7401
- const conv = this.conv;
7402
8165
  const promptAc = new AbortController();
7403
8166
  conv.activePromptAc = promptAc;
7404
8167
  this.markerSvc.clearActions(conv.id);
@@ -7466,8 +8229,8 @@ export class ClientSession {
7466
8229
  catch {
7467
8230
  // ignore
7468
8231
  }
8232
+ const s = this.session;
7469
8233
  try {
7470
- const s = this.session;
7471
8234
  // Native slash commands (see NATIVE_COMMANDS) are executed here and
7472
8235
  // never reach the SDK. Extension / skill / template commands fall
7473
8236
  // through — AgentSession.prompt() handles those itself.
@@ -7530,9 +8293,7 @@ export class ClientSession {
7530
8293
  conv.transcriptBlocked = false;
7531
8294
  try {
7532
8295
  await s.reload();
7533
- this.applyRetryOverrides();
7534
- this.applyCompactionOverrides();
7535
- this.applyToolGating(s, conv.agentPreset);
8296
+ this.applySessionOverrides(conv);
7536
8297
  }
7537
8298
  catch {
7538
8299
  // reload 失败兜底
@@ -7800,64 +8561,16 @@ export class ClientSession {
7800
8561
  });
7801
8562
  return;
7802
8563
  }
7803
- const mainSupportsVision = s.model?.input?.includes("image") ?? false;
7804
- const promptImages = [];
7805
- const textAsides = [];
7806
- const imageNames = [];
7807
- if (s.isStreaming) {
7808
- for (const aside of asides) {
7809
- const details = aside.message.details;
7810
- for (const b of aside.message.content) {
7811
- if (typeof b === "string") {
7812
- if (b.trim())
7813
- textAsides.push(b.trim());
7814
- continue;
7815
- }
7816
- if (!b || typeof b !== "object")
7817
- continue;
7818
- if (b.type === "image" && typeof b.data === "string") {
7819
- if (mainSupportsVision) {
7820
- promptImages.push({
7821
- type: "image",
7822
- data: b.data,
7823
- mimeType: b.mimeType || "image/png",
7824
- });
7825
- if (details?.name) {
7826
- imageNames.push(details.name);
7827
- }
7828
- }
7829
- }
7830
- else if (b.type === "text" &&
7831
- typeof b.text === "string" &&
7832
- b.text.trim()) {
7833
- textAsides.push(b.text.trim());
7834
- if (details?.mode === "bridged" && details?.name) {
7835
- imageNames.push(details.name);
7836
- }
7837
- }
7838
- }
7839
- }
7840
- // 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
7841
- // Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
7842
- // 排队消息无法获取附件,且附件残留泄露到下一次提问。
7843
- // 保证 SDK 内部暂存队列清空,防止历史残留污染。
7844
- if (Array.isArray(s._pendingNextTurnMessages)) {
7845
- s._pendingNextTurnMessages = [];
7846
- }
8564
+ // 空闲前置:若当前未处于流式运行且上下文超标,提早在注入附件前执行软上限主动压缩(issue #716)。
8565
+ // 必须在任何 nextTurn 注入之前完成,避免耗时压缩期间发生状态变化导致附件残留泄漏(fixes #717)。
8566
+ if (!s.isStreaming) {
8567
+ await this.triggerSoftCapCompactionIfExceeded(conv);
7847
8568
  }
7848
- else {
7849
- for (const aside of asides) {
7850
- await s.sendCustomMessage(aside.message);
7851
- }
7852
- if (asides.length > 0) {
7853
- this.flushSnapshot();
7854
- }
8569
+ if (promptAc.signal.aborted) {
8570
+ conv.activePromptAc = undefined;
7855
8571
  if (Array.isArray(s._pendingNextTurnMessages)) {
7856
8572
  s._pendingNextTurnMessages = [];
7857
8573
  }
7858
- }
7859
- if (promptAc.signal.aborted) {
7860
- conv.activePromptAc = undefined;
7861
8574
  // #492:同上——前置阶段的 abort 也必须给回执,不能静默黑洞。
7862
8575
  this.emit({
7863
8576
  type: "notice",
@@ -7878,38 +8591,70 @@ export class ClientSession {
7878
8591
  textEn: `Message delivered to "${conv.title}" — you switched conversations before it landed`,
7879
8592
  });
7880
8593
  }
7881
- if (s.isStreaming) {
7882
- // queue=true (补充 button) → followUp: the message is delivered only
7883
- // after the whole run finishes — the agent finishes what it started,
7884
- // then responds to the queued message. queue=false/undefined
7885
- // (plain Enter) → steer: interrupts the current run — the message
7886
- // is delivered right after the current assistant turn settles
7887
- // (remaining planned tool calls are skipped) and the agent
7888
- // immediately responds to it. This is the pi CLI
7889
- // Enter-during-streaming semantic (docs/usage: Enter queues a
7890
- // steering message); followUp would wait for the whole run
7891
- // to finish, which users perceive as ordinary queueing.
7892
- //
7893
- // 注意:流式期间入队仅进入 SDK 内存队列(尚未落盘为 sessionManager entry),
7894
- // 严禁在此处启动或 await 工作区 Git 影子快照(否则在大型仓库或工具占锁时会把
7895
- // 入队回执与 flushSnapshot 阻塞数秒至 15 秒,造成「按完 Enter 消息消失」)。
7896
- // 排队/插队消息的工作区快照在其真正出队定稿(message_end, role="user")时异步生成。
8594
+ const mainSupportsVision = s.model?.input?.includes("image") ?? false;
8595
+ const modelLabel = s.model?.name ?? s.model?.id ?? "unknown";
8596
+ // 单源流式投递执行器:无论进入时已处于流式还是中途跃迁为流式,均通过单源解构提取
8597
+ // 完整的图片、文本与非视觉模型占位,确保排队消息绝不丢图且清空 SDK 暂存杜绝跨轮泄漏(fixes #717)。
8598
+ const deliverStreamingPrompt = async () => {
8599
+ // 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
8600
+ // Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
8601
+ // 排队消息无法获取附件,且附件残留泄露到下一次提问。
8602
+ // 保证 SDK 内部暂存队列排空,防止历史残留污染。
8603
+ if (Array.isArray(s._pendingNextTurnMessages)) {
8604
+ s._pendingNextTurnMessages = [];
8605
+ }
8606
+ const { promptImages, textAsides, imageNames, quotes } = extractStreamingPayload(asides, streamingQuotes, mainSupportsVision, modelLabel);
7897
8607
  const kind = queue ? "followUp" : "steer";
7898
- const fullPromptText = formatStreamingPrompt(text, textAsides, streamingQuotes, imageNames);
8608
+ const fullPromptText = formatStreamingPrompt(text, textAsides, quotes, imageNames);
7899
8609
  if (this.consumeCancelledInFlightQueue(conv, kind, text, fullPromptText)) {
7900
8610
  this.flushSnapshot();
7901
8611
  return;
7902
8612
  }
7903
- if (promptImages.length > 0) {
7904
- conv.queuedImages.set(fullPromptText, promptImages);
7905
- }
7906
- await s.prompt(fullPromptText, {
7907
- streamingBehavior: kind,
8613
+ const entry = createQueuedEntry(fullPromptText, {
7908
8614
  images: promptImages.length > 0 ? promptImages : undefined,
8615
+ attachments: effectiveAttachments,
7909
8616
  });
8617
+ if (kind === "steer") {
8618
+ (conv.queuedSteeringEntries ??= []).push(entry);
8619
+ }
8620
+ else {
8621
+ (conv.queuedFollowUpEntries ??= []).push(entry);
8622
+ }
8623
+ try {
8624
+ await s.prompt(fullPromptText, {
8625
+ streamingBehavior: kind,
8626
+ images: promptImages.length > 0 ? promptImages : undefined,
8627
+ });
8628
+ }
8629
+ catch (err) {
8630
+ if (kind === "steer") {
8631
+ conv.queuedSteeringEntries = rollbackQueuedEntry(conv.queuedSteeringEntries ?? [], fullPromptText);
8632
+ }
8633
+ else {
8634
+ conv.queuedFollowUpEntries = rollbackQueuedEntry(conv.queuedFollowUpEntries ?? [], fullPromptText);
8635
+ }
8636
+ throw err;
8637
+ }
8638
+ };
8639
+ if (s.isStreaming) {
8640
+ await deliverStreamingPrompt();
7910
8641
  }
7911
8642
  else {
7912
- // 空闲提问:启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
8643
+ // 空闲提问:必须携带 deliverAs: "nextTurn",将附件(图片、文件引用、视觉证据等)
8644
+ // 注入 SDK 的 _pendingNextTurnMessages,并在随后的 s.prompt() 中由 SDK 作为上下文消息
8645
+ // 传递给 LLM 并落盘(fixes #667)。严禁在此清空 _pendingNextTurnMessages。
8646
+ for (const aside of asides) {
8647
+ await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
8648
+ }
8649
+ // 临界区并发保护:若在注入期间或注入后瞬间会话转入流式状态,立即回退转入流式投递并排空暂存(fixes #717)
8650
+ if (s.isStreaming) {
8651
+ await deliverStreamingPrompt();
8652
+ return;
8653
+ }
8654
+ if (asides.length > 0) {
8655
+ this.flushSnapshot();
8656
+ }
8657
+ // 启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
7913
8658
  // 绑定由 message_end 异步完成,绝不阻塞 prompt 收尾与气泡上屏)。
7914
8659
  const snapshotPromise = this.startWorkspaceSnapshot(conv);
7915
8660
  try {
@@ -7924,6 +8669,9 @@ export class ClientSession {
7924
8669
  }
7925
8670
  catch (err) {
7926
8671
  conv.activePromptAc = undefined;
8672
+ if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
8673
+ conv.session._pendingNextTurnMessages = [];
8674
+ }
7927
8675
  this.emit({
7928
8676
  type: "notice",
7929
8677
  level: "error",
@@ -8076,7 +8824,7 @@ export class ClientSession {
8076
8824
  * item still at that position; on any mismatch we fall back to first-occurrence
8077
8825
  * text match (old clients, or the queue shifted between click and handling).
8078
8826
  */
8079
- async removeQueued(kind, text, index) {
8827
+ async removeQueued(kind, text, index, id) {
8080
8828
  const conv = this.conv;
8081
8829
  // Always-defined display mirrors; also the provenance of bubble rendering.
8082
8830
  const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
@@ -8108,6 +8856,20 @@ export class ClientSession {
8108
8856
  if (next.length !== local.length) {
8109
8857
  local.splice(0, local.length, ...next);
8110
8858
  }
8859
+ if (kind === "steer") {
8860
+ conv.queuedSteeringEntries = removeQueuedEntry(conv.queuedSteeringEntries ?? [], {
8861
+ id,
8862
+ text: targetText,
8863
+ index,
8864
+ });
8865
+ }
8866
+ else {
8867
+ conv.queuedFollowUpEntries = removeQueuedEntry(conv.queuedFollowUpEntries ?? [], {
8868
+ id,
8869
+ text: targetText,
8870
+ index,
8871
+ });
8872
+ }
8111
8873
  this.flushSnapshot();
8112
8874
  return;
8113
8875
  }
@@ -8125,22 +8887,44 @@ export class ClientSession {
8125
8887
  if (next.length !== local.length) {
8126
8888
  local.splice(0, local.length, ...next);
8127
8889
  }
8890
+ if (kind === "steer") {
8891
+ conv.queuedSteeringEntries = removeQueuedEntry(conv.queuedSteeringEntries ?? [], {
8892
+ id,
8893
+ text: targetText,
8894
+ index,
8895
+ });
8896
+ }
8897
+ else {
8898
+ conv.queuedFollowUpEntries = removeQueuedEntry(conv.queuedFollowUpEntries ?? [], {
8899
+ id,
8900
+ text: targetText,
8901
+ index,
8902
+ });
8903
+ }
8128
8904
  this.flushSnapshot();
8129
8905
  return;
8130
8906
  }
8131
- // 气泡 ✕ 对应的是「第几个气泡」(index),不是「哪段文本」:同一文本排队两次时
8132
- // 按文本只会删掉第一条,点第二个气泡却删掉第一个。用 index 定位,位置对不上
8133
- // (队列在点击与执行之间变化)或旧客户端没发 index 时回落到第一处文本匹配。
8134
- const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, targetText, index) : steering;
8135
- const keptFollowUp = kind === "followUp" ? removeQueuedByIndexOrText(followUp, targetText, index) : followUp;
8907
+ // 用 clearQueue 返回的最新队列对账,确保与清空前状态严格对齐(issue #718)
8908
+ const currentSteeringEntries = reconcileQueuedEntries(conv.queuedSteeringEntries ?? [], steering);
8909
+ const currentFollowUpEntries = reconcileQueuedEntries(conv.queuedFollowUpEntries ?? [], followUp);
8910
+ // 气泡 ✕ 对应条目:优先按唯一 id 精准剔除,兜底按 index/text 剔除
8911
+ const keptSteeringEntries = kind === "steer"
8912
+ ? removeQueuedEntry(currentSteeringEntries, { id, text: targetText, index })
8913
+ : currentSteeringEntries;
8914
+ const keptFollowUpEntries = kind === "followUp"
8915
+ ? removeQueuedEntry(currentFollowUpEntries, { id, text: targetText, index })
8916
+ : currentFollowUpEntries;
8917
+ conv.queuedSteeringEntries = [];
8918
+ conv.queuedFollowUpEntries = [];
8136
8919
  // Re-queue the survivors in original order. Guard each call so a single
8137
8920
  // failure can't leave the queue half-drained silently.
8138
- for (const t of keptSteering) {
8921
+ for (const entry of keptSteeringEntries) {
8139
8922
  try {
8140
- const imgs = conv.queuedImages?.get(t);
8141
- await s.steer(t, imgs);
8923
+ conv.queuedSteeringEntries.push(entry);
8924
+ await s.steer(entry.text, entry.images);
8142
8925
  }
8143
8926
  catch (err) {
8927
+ conv.queuedSteeringEntries.pop();
8144
8928
  this.emit({
8145
8929
  type: "notice",
8146
8930
  level: "error",
@@ -8149,12 +8933,13 @@ export class ClientSession {
8149
8933
  });
8150
8934
  }
8151
8935
  }
8152
- for (const t of keptFollowUp) {
8936
+ for (const entry of keptFollowUpEntries) {
8153
8937
  try {
8154
- const imgs = conv.queuedImages?.get(t);
8155
- await s.followUp(t, imgs);
8938
+ conv.queuedFollowUpEntries.push(entry);
8939
+ await s.followUp(entry.text, entry.images);
8156
8940
  }
8157
8941
  catch (err) {
8942
+ conv.queuedFollowUpEntries.pop();
8158
8943
  this.emit({
8159
8944
  type: "notice",
8160
8945
  level: "error",
@@ -8163,7 +8948,6 @@ export class ClientSession {
8163
8948
  });
8164
8949
  }
8165
8950
  }
8166
- conv.queuedImages?.delete(targetText);
8167
8951
  if (Array.isArray(s._pendingNextTurnMessages)) {
8168
8952
  s._pendingNextTurnMessages = [];
8169
8953
  }
@@ -8283,7 +9067,14 @@ export class ClientSession {
8283
9067
  }
8284
9068
  /** Interrupt a run: abort, with a force-reset fallback on timeout. */
8285
9069
  async interruptRun(conv, reason) {
8286
- // #487:停下就结算该会话的挂起提问/审批——残留条目让 isWaitingOnUser 恒真
9070
+ // 正在投递的消息前置阶段(附件构建 / 影子快照)立即打断
9071
+ if (conv.activePromptAc) {
9072
+ conv.activePromptAc.abort();
9073
+ conv.activePromptAc = undefined;
9074
+ }
9075
+ // 统一清理在飞的工具看门狗、计时器与进行中参数状态,防止中止后残留或跳出超时鬼影警告
9076
+ this.clearConversationToolStates(conv);
9077
+ // #487:停下就结算该会话的挂起提问/审批/页面调用——残留条目让 isWaitingOnUser 恒真
8287
9078
  // (stall 失联检测被永久豁免),弹窗也会跨轮残留;dispose 语义已范本化。
8288
9079
  this.settlePendingsForConv(conv.id);
8289
9080
  if (!this.conversationStreaming(conv) && conv.session.isIdle) {
@@ -8355,8 +9146,7 @@ export class ClientSession {
8355
9146
  try {
8356
9147
  conv.unsubscribe?.();
8357
9148
  conv.unsubscribe = undefined;
8358
- this.clearAllToolWatchdogs(conv);
8359
- conv.toolStartTimes.clear();
9149
+ this.clearConversationToolStates(conv);
8360
9150
  disposeEvalSession(conv.id);
8361
9151
  await conv.runtime.dispose();
8362
9152
  // #485:dispose 挂起期间会话可能已被强行关闭移出(forceDismiss 走
@@ -8390,7 +9180,7 @@ export class ClientSession {
8390
9180
  }, (m) =>
8391
9181
  // 子代理带模板时按原模板重建(conv.subagentTemplate 是派发时工厂
8392
9182
  // 用的同一快照);普通对话 undefined,行为不变。
8393
- createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id), {
9183
+ createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id, undefined, undefined, conv.isSubagent && this.subagentAtDepthLimit(conv.parentId)), {
8394
9184
  cwd: sessionBaseDir,
8395
9185
  agentDir: this.agentDir,
8396
9186
  sessionManager: m,
@@ -9049,9 +9839,27 @@ export class ClientSession {
9049
9839
  // ignore
9050
9840
  }
9051
9841
  this.convs.delete(id);
9842
+ conv.suspendedSubagents?.clear();
9843
+ for (const c of this.convs.values()) {
9844
+ c.suspendedSubagents?.delete(conv);
9845
+ }
9846
+ const pendingNotice = this.pendingSubagentNotices.get(id);
9847
+ if (pendingNotice) {
9848
+ clearTimeout(pendingNotice.timer);
9849
+ this.pendingSubagentNotices.delete(id);
9850
+ }
9851
+ for (const [pId, entry] of this.pendingSubagentNotices) {
9852
+ entry.subagents.delete(conv);
9853
+ if (entry.subagents.size === 0) {
9854
+ clearTimeout(entry.timer);
9855
+ this.pendingSubagentNotices.delete(pId);
9856
+ }
9857
+ }
9052
9858
  this.pluginModelKeys?.delete(id);
9053
9859
  this.planManager.unbindConversation(id);
9054
- this.clearAllToolWatchdogs(conv);
9860
+ this.markerSvc.clearConversation(id);
9861
+ this.clearConversationToolStates(conv);
9862
+ this.goalSvc.notifyConversationRemoved(conv);
9055
9863
  // 关对话 → 连它的 eval 内核(Python/Node 子进程 + 临时沙箱目录)一起回收:
9056
9864
  // 这些进程是 detached 进程组,父进程退出不会自动带走它们。
9057
9865
  disposeEvalSession(id);
@@ -9064,6 +9872,9 @@ export class ClientSession {
9064
9872
  rmSync(ephemeralDir, { recursive: true, force: true });
9065
9873
  }
9066
9874
  catch { }
9875
+ if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
9876
+ void this.finalizeSubagentWorktree(conv).catch(() => { });
9877
+ }
9067
9878
  }
9068
9879
  if (conv.isEphemeral) {
9069
9880
  const ephemeralDir = join(this.agentDir, "ephemeral-sessions", conv.id);
@@ -9185,22 +9996,24 @@ export class ClientSession {
9185
9996
  // 永远等不到答复)。只搬归属明确的(conversationId 对得上,与问卷/页调用
9186
9997
  // 同一规则);目标侧按新 id 重发弹窗,等待中的 Promise 原样过户不 resolve。
9187
9998
  const approvals = [];
9188
- for (const [aid, a] of this.pendingApprovals) {
9189
- if (a.conversationId !== undefined && set.has(a.conversationId)) {
9190
- this.pendingApprovals.delete(aid);
9191
- approvals.push({
9192
- resolve: a.resolve,
9193
- toolCallId: a.toolCallId,
9194
- toolName: a.toolName,
9195
- params: a.params,
9196
- reason: a.reason,
9197
- reasonEn: a.reasonEn,
9198
- ...(a.category ? { category: a.category } : {}),
9199
- ...(a.hits ? { hits: a.hits } : {}),
9200
- conversationId: a.conversationId,
9201
- ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
9202
- createdAt: a.createdAt,
9203
- });
9999
+ for (const conv of convs) {
10000
+ if (conv.pendingApprovals && conv.pendingApprovals.size > 0) {
10001
+ for (const [, a] of conv.pendingApprovals) {
10002
+ approvals.push({
10003
+ resolve: a.resolve,
10004
+ toolCallId: a.toolCallId,
10005
+ toolName: a.toolName,
10006
+ params: a.params,
10007
+ reason: a.reason,
10008
+ reasonEn: a.reasonEn,
10009
+ ...(a.category ? { category: a.category } : {}),
10010
+ ...(a.hits ? { hits: a.hits } : {}),
10011
+ conversationId: a.conversationId ?? conv.id,
10012
+ ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
10013
+ createdAt: a.createdAt,
10014
+ });
10015
+ }
10016
+ conv.pendingApprovals.clear();
9204
10017
  }
9205
10018
  }
9206
10019
  this.emitConversations();
@@ -9323,23 +10136,9 @@ export class ClientSession {
9323
10136
  for (const a of payload.approvals) {
9324
10137
  const nid = `appr-${++this.approvalSeq}`;
9325
10138
  const aConvId = fix(a.conversationId);
9326
- this.pendingApprovals.set(nid, {
9327
- id: nid,
9328
- toolCallId: a.toolCallId,
9329
- toolName: a.toolName,
9330
- params: a.params,
9331
- reason: a.reason,
9332
- reasonEn: a.reasonEn,
9333
- ...(a.category ? { category: a.category } : {}),
9334
- ...(a.hits ? { hits: a.hits } : {}),
9335
- conversationId: aConvId,
9336
- ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
9337
- resolve: a.resolve,
9338
- createdAt: a.createdAt,
9339
- });
9340
- if (aConvId === mainId) {
9341
- this.emit({
9342
- type: "tool_approval_pending",
10139
+ const targetConv = this.convs.get(aConvId);
10140
+ if (targetConv) {
10141
+ this.ensurePendingApprovals(targetConv).set(nid, {
9343
10142
  id: nid,
9344
10143
  toolCallId: a.toolCallId,
9345
10144
  toolName: a.toolName,
@@ -9350,7 +10149,24 @@ export class ClientSession {
9350
10149
  ...(a.hits ? { hits: a.hits } : {}),
9351
10150
  conversationId: aConvId,
9352
10151
  ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
10152
+ resolve: a.resolve,
10153
+ createdAt: a.createdAt,
9353
10154
  });
10155
+ if (aConvId === mainId) {
10156
+ this.emit({
10157
+ type: "tool_approval_pending",
10158
+ id: nid,
10159
+ toolCallId: a.toolCallId,
10160
+ toolName: a.toolName,
10161
+ params: a.params,
10162
+ reason: a.reason,
10163
+ reasonEn: a.reasonEn,
10164
+ ...(a.category ? { category: a.category } : {}),
10165
+ ...(a.hits ? { hits: a.hits } : {}),
10166
+ conversationId: aConvId,
10167
+ ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
10168
+ });
10169
+ }
9354
10170
  }
9355
10171
  }
9356
10172
  return mainId;
@@ -9400,8 +10216,21 @@ export class ClientSession {
9400
10216
  }
9401
10217
  /** Switch the ACTIVE conversation without interrupting any other chat. */
9402
10218
  async switchConversation(id) {
9403
- if (!this.convs.has(id) || id === this.activeId)
10219
+ if (id === this.activeId)
10220
+ return;
10221
+ if (!this.convs.has(id)) {
10222
+ this.emit({
10223
+ type: "transition_progress",
10224
+ kind: "conversation",
10225
+ target: id,
10226
+ phase: "error",
10227
+ progress: 100,
10228
+ text: "对话已不存在或已结束",
10229
+ textEn: "Conversation no longer exists or has finished",
10230
+ });
10231
+ this.flushSnapshot();
9404
10232
  return;
10233
+ }
9405
10234
  const displaced = this.displaceActive();
9406
10235
  this.activeId = id;
9407
10236
  const newCwd = this.conv.cwd;
@@ -9418,10 +10247,26 @@ export class ClientSession {
9418
10247
  this.emitConversations();
9419
10248
  this.goalSvc.emitGoalStatus();
9420
10249
  this.pushTerminals();
9421
- // The switched-to conversation has its own runtime (own resource cache).
9422
- void this.pushSlashCommands();
9423
10250
  if (cwdChanged) {
9424
10251
  this.cwd = newCwd;
10252
+ this.files.unwatchGit();
10253
+ this.roots = this.stateStore.getWorkspaceRoots(this.clientId, newCwd);
10254
+ }
10255
+ // 核心:快照与完成信号优先!在繁重的工作区扫描/设置推送之前第一时间发往
10256
+ // 浏览器,0ms 呈现对话内容与状态,绝不让前端在空转中等待文件树与设置大包。
10257
+ this.flushSnapshot();
10258
+ this.emit({
10259
+ type: "transition_progress",
10260
+ kind: "conversation",
10261
+ target: id,
10262
+ phase: "done",
10263
+ progress: 100,
10264
+ text: "对话切换完成",
10265
+ textEn: "Conversation switched",
10266
+ });
10267
+ // 工作区跟随副作用(命令/项目/会话/文件树/插件通知/设置)异步推进,不阻塞会话呈现
10268
+ void this.pushSlashCommands();
10269
+ if (cwdChanged) {
9425
10270
  // 模型/key 恢复不挡快照:后台做,带代际 guard(用户又切走就跳过),
9426
10271
  // 做完补一次 flush 刷新模型栏。
9427
10272
  {
@@ -9448,7 +10293,6 @@ export class ClientSession {
9448
10293
  // 当前打开对话变了 → 插件重拉(轨迹视图切会话后即刷新,不等轮询)。
9449
10294
  this.notifyConversationChanged();
9450
10295
  this.pushSettings();
9451
- this.flushSnapshot();
9452
10296
  }
9453
10297
  /** 左栏「运行的对话」的展示口径(issue #140)。
9454
10298
  *
@@ -9534,7 +10378,12 @@ export class ClientSession {
9534
10378
  return pq ? { hasQuestion: true, questionId: pq.id, questionTitle: pq.title } : {};
9535
10379
  })(),
9536
10380
  parentId: conv.parentId,
10381
+ model: conv.session.model
10382
+ ? `${conv.session.model.provider}/${conv.session.model.id}`
10383
+ : (conv.subagentTemplate?.model ?? undefined),
10384
+ thinkingLevel: conv.session.thinkingLevel ?? conv.subagentThinking ?? undefined,
9537
10385
  ...(conv.pinned ? { pinned: true } : {}),
10386
+ ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
9538
10387
  ...(conv.forkFrom ? { forkFrom: conv.forkFrom } : {}),
9539
10388
  });
9540
10389
  }
@@ -9714,18 +10563,44 @@ export class ClientSession {
9714
10563
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
9715
10564
  const run = (async () => {
9716
10565
  try {
9717
- const sessionDir = piSessionsRoot()
9718
- ? resolve(piSessionsRoot())
9719
- : SessionManager.create(sessionBaseDir).getSessionDir();
9720
- if (!existsSync(sessionDir))
9721
- return [];
9722
- const dirEntries = await fsPromises.readdir(sessionDir);
9723
- const files = dirEntries.filter((f) => f.endsWith(".jsonl"));
9724
- if (files.length === 0)
10566
+ const projectDir = SessionManager.create(sessionBaseDir).getSessionDir();
10567
+ const extraRoot = piSessionsRoot() ? resolve(piSessionsRoot()) : undefined;
10568
+ const candidateFiles = new Map();
10569
+ if (existsSync(projectDir)) {
10570
+ const dirEntries = await fsPromises.readdir(projectDir);
10571
+ for (const f of dirEntries) {
10572
+ if (f.endsWith(".jsonl")) {
10573
+ const fp = join(projectDir, f);
10574
+ candidateFiles.set(normalizePathKey(fp), fp);
10575
+ }
10576
+ }
10577
+ }
10578
+ if (extraRoot && existsSync(extraRoot)) {
10579
+ const dirEntries = await fsPromises.readdir(extraRoot);
10580
+ for (const f of dirEntries) {
10581
+ if (f.endsWith(".jsonl")) {
10582
+ const fp = join(extraRoot, f);
10583
+ candidateFiles.set(normalizePathKey(fp), fp);
10584
+ }
10585
+ }
10586
+ const extraSubdir = join(extraRoot, basename(projectDir));
10587
+ if (normalizePathKey(extraSubdir) !== normalizePathKey(projectDir) && existsSync(extraSubdir)) {
10588
+ try {
10589
+ const subEntries = await fsPromises.readdir(extraSubdir);
10590
+ for (const f of subEntries) {
10591
+ if (f.endsWith(".jsonl")) {
10592
+ const fp = join(extraSubdir, f);
10593
+ candidateFiles.set(normalizePathKey(fp), fp);
10594
+ }
10595
+ }
10596
+ }
10597
+ catch { }
10598
+ }
10599
+ }
10600
+ if (candidateFiles.size === 0)
9725
10601
  return [];
9726
10602
  // Stat files to detect modified/new files (takes only ~8ms for 600+ files)
9727
- const stats = await Promise.all(files.map(async (f) => {
9728
- const fp = join(sessionDir, f);
10603
+ const stats = await Promise.all(Array.from(candidateFiles.values()).map(async (fp) => {
9729
10604
  try {
9730
10605
  const st = await fsPromises.stat(fp);
9731
10606
  return { path: fp, mtime: st.mtimeMs, size: st.size };
@@ -9755,18 +10630,46 @@ export class ClientSession {
9755
10630
  const validInfos = results.filter((info) => info !== null);
9756
10631
  const baseDirKey = normalizePathKey(sessionBaseDir);
9757
10632
  const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
9758
- const candidates = ownInfos.slice(0, 200);
10633
+ const seenIds = new Set();
10634
+ const dedupedOwnInfos = [];
10635
+ for (const info of ownInfos) {
10636
+ if (info.id) {
10637
+ if (seenIds.has(info.id))
10638
+ continue;
10639
+ seenIds.add(info.id);
10640
+ }
10641
+ dedupedOwnInfos.push(info);
10642
+ }
10643
+ const candidates = dedupedOwnInfos.slice(0, 200);
9759
10644
  candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
9760
10645
  ClientSession.sessionInfosCache.set(cwdKey, { infos: candidates, at: Date.now() });
9761
10646
  return candidates;
9762
10647
  }
9763
10648
  catch {
9764
10649
  try {
9765
- const fallback = await SessionManager.list(sessionBaseDir, piSessionsRoot());
9766
- // 统一口径:列表缓存一律不带转录全文(issue #440),搜索按需另行加载
9767
- const stripped = fallback.map((s) => ({ ...s, allMessagesText: "" }));
9768
- ClientSession.sessionInfosCache.set(cwdKey, { infos: stripped, at: Date.now() });
9769
- return stripped;
10650
+ const projectInfos = await SessionManager.list(sessionBaseDir).catch(() => []);
10651
+ const extraInfos = piSessionsRoot()
10652
+ ? await SessionManager.list(sessionBaseDir, piSessionsRoot()).catch(() => [])
10653
+ : [];
10654
+ const seenPath = new Set();
10655
+ const seenId = new Set();
10656
+ const combined = [];
10657
+ for (const s of [...projectInfos, ...extraInfos]) {
10658
+ const key = normalizePathKey(s.path);
10659
+ if (seenPath.has(key))
10660
+ continue;
10661
+ seenPath.add(key);
10662
+ if (s.id) {
10663
+ if (seenId.has(s.id))
10664
+ continue;
10665
+ seenId.add(s.id);
10666
+ }
10667
+ // 统一口径:列表缓存一律不带转录全文(issue #440),搜索按需另行加载
10668
+ combined.push({ ...s, allMessagesText: "" });
10669
+ }
10670
+ combined.sort((a, b) => b.modified.getTime() - a.modified.getTime());
10671
+ ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now() });
10672
+ return combined;
9770
10673
  }
9771
10674
  catch {
9772
10675
  return [];
@@ -9798,11 +10701,11 @@ export class ClientSession {
9798
10701
  await this.pushSessions();
9799
10702
  }
9800
10703
  /** 切项目时的会话列表刷新:sessionInfosCache 已按 cwdKey 隔离(30s TTL),
9801
- * 若刚刚在 setCwd 并行预热过(<2s 内)则直接复用预热结果推送,不再清空重扫。 */
10704
+ * 若在 TTL 内则直接复用缓存推送,不再全盘清空重扫。 */
9802
10705
  refreshSessionsOnSwitch() {
9803
10706
  const cwdKey = normalizePathKey(this.cwd);
9804
10707
  const cached = ClientSession.sessionInfosCache.get(cwdKey);
9805
- if (!cached || Date.now() - cached.at > 2_000) {
10708
+ if (!cached || Date.now() - cached.at > ClientSession.SESSION_INFO_CACHE_TTL) {
9806
10709
  ClientSession.sessionInfosCache.delete(cwdKey);
9807
10710
  }
9808
10711
  if (this.sessionsRequested)
@@ -10325,8 +11228,8 @@ export class ClientSession {
10325
11228
  this.emit({
10326
11229
  type: "notice",
10327
11230
  level: "warning",
10328
- text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端后再移出`,
10329
- textEn: `Conversation "${conv.title}" still has open terminals — close them before removing`,
11231
+ text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端或右键选择「强行关闭」后再移出`,
11232
+ textEn: `Conversation "${conv.title}" still has open terminals — close them or right-click to force-dismiss`,
10330
11233
  });
10331
11234
  return;
10332
11235
  }
@@ -10894,11 +11797,8 @@ export class ClientSession {
10894
11797
  if (displaced)
10895
11798
  this.removeConversation(displaced.id);
10896
11799
  await this.bindSession();
10897
- // #436:转录回放恢复的 planMode 在 runtime 工厂的 applyToolGating 时还读不到
10898
- //(conv 尚未进 this.convs,planModeOf 落空)——注册后统一补一次门控,让
10899
- // 计划模式的写类/旁路工具剥离对重开的会话同样生效。下同(forkSession/setCwd)。
10900
- this.applyToolGating(conv.session, conv.agentPreset);
10901
11800
  this.cwd = targetCwd;
11801
+ this.files.unwatchGit();
10902
11802
  // 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
10903
11803
  // 历史列表/命令目录/最近项目)必须跟着切,否则 UI 停在旧项目。
10904
11804
  this.applyCwdSideEffects(targetCwd);
@@ -11103,9 +12003,6 @@ export class ClientSession {
11103
12003
  await this.bindSession();
11104
12004
  this.invalidateSessionInfos();
11105
12005
  this.scheduleSessionsRefresh();
11106
- // #436:同 switchSession —— 派生出的会话若从转录回放恢复了 planMode,
11107
- // 工厂里的门控当时读不到它,注册后补一次。
11108
- this.applyToolGating(newConv.session, newConv.agentPreset);
11109
12006
  if (prevModel && this.sharedModelRuntime) {
11110
12007
  try {
11111
12008
  const pm = prevModel;
@@ -11164,6 +12061,14 @@ export class ClientSession {
11164
12061
  if (targetConv.session.isStreaming) {
11165
12062
  await targetConv.session.abort();
11166
12063
  }
12064
+ // 回滚开始时的会话长度:物理还原前复核,若期间已有新回合写入则跳过还原保新改动(#697)
12065
+ let sessionLenAtRollback = -1;
12066
+ try {
12067
+ sessionLenAtRollback = targetConv.session.agent.state.messages.length;
12068
+ }
12069
+ catch {
12070
+ // best effort
12071
+ }
11167
12072
  // 重置分支 leaf 到目标 entry.id
11168
12073
  targetConv.session.sessionManager.branch(entry.id);
11169
12074
  const branchedContext = targetConv.session.sessionManager.buildSessionContext();
@@ -11177,10 +12082,8 @@ export class ClientSession {
11177
12082
  }
11178
12083
  }
11179
12084
  await targetConv.session.reload();
11180
- // 重新应用设置和门控
11181
- this.applyRetryOverrides();
11182
- this.applyCompactionOverrides();
11183
- this.applyToolGating(targetConv.session, targetConv.agentPreset);
12085
+ // 重新应用设置和门控(统一收口)
12086
+ this.applySessionOverrides(targetConv);
11184
12087
  // 清理该会话的 UI 消息缓存和序列化映射
11185
12088
  targetConv.uiMessageCache.clear();
11186
12089
  targetConv.msgIds.clear();
@@ -11190,7 +12093,8 @@ export class ClientSession {
11190
12093
  targetConv.lastMessagesArray = [];
11191
12094
  targetConv.queueSteering = [];
11192
12095
  targetConv.queueFollowUp = [];
11193
- targetConv.queuedImages = new Map();
12096
+ targetConv.queuedSteeringEntries = [];
12097
+ targetConv.queuedFollowUpEntries = [];
11194
12098
  try {
11195
12099
  targetConv.session.clearQueue?.();
11196
12100
  }
@@ -11214,18 +12118,35 @@ export class ClientSession {
11214
12118
  // 查找最贴近该 entry 的快照(按 entryId 或 <= entryTs 的最后一份快照)
11215
12119
  const matched = findMatchingWorkspaceSnapshot(targetConv.workspaceSnapshots ?? [], entry.id, entryTs);
11216
12120
  if (matched) {
11217
- const res = await restoreWorkspaceSnapshot(targetConv.cwd, matched.snapshotRef);
11218
- if (res.success) {
11219
- workspaceRestored = true;
12121
+ let sessionLenNow = -1;
12122
+ try {
12123
+ sessionLenNow = targetConv.session.agent.state.messages.length;
11220
12124
  }
11221
- else {
12125
+ catch {
12126
+ // best effort
12127
+ }
12128
+ if (sessionLenAtRollback >= 0 && sessionLenNow > sessionLenAtRollback) {
11222
12129
  this.emit({
11223
12130
  type: "notice",
11224
12131
  level: "warning",
11225
- text: `会话已回滚,但工作区物理文件还原失败:${res.error}`,
11226
- textEn: `Session rolled back, but workspace file restore failed: ${res.error}`,
12132
+ text: "检测到回滚期间已有新对话写入,为保护新改动已跳过工作区物理文件还原(会话历史仍已回滚)。",
12133
+ textEn: "New messages arrived during rollback; skipped workspace file restore to protect new changes (history still rolled back).",
11227
12134
  });
11228
12135
  }
12136
+ else {
12137
+ const res = await restoreWorkspaceSnapshot(targetConv.cwd, matched.snapshotRef);
12138
+ if (res.success) {
12139
+ workspaceRestored = true;
12140
+ }
12141
+ else {
12142
+ this.emit({
12143
+ type: "notice",
12144
+ level: "warning",
12145
+ text: `会话已回滚,但工作区物理文件还原失败:${res.error}`,
12146
+ textEn: `Session rolled back, but workspace file restore failed: ${res.error}`,
12147
+ });
12148
+ }
12149
+ }
11229
12150
  }
11230
12151
  else {
11231
12152
  this.emit({
@@ -11327,7 +12248,8 @@ export class ClientSession {
11327
12248
  this.conv.lastMessagesArray = [];
11328
12249
  this.conv.queueSteering = [];
11329
12250
  this.conv.queueFollowUp = [];
11330
- this.conv.queuedImages = new Map();
12251
+ this.conv.queuedSteeringEntries = [];
12252
+ this.conv.queuedFollowUpEntries = [];
11331
12253
  // Restore the previously-selected model on the forked branch.
11332
12254
  if (prevModel && this.sharedModelRuntime) {
11333
12255
  try {
@@ -12195,6 +13117,8 @@ export class ClientSession {
12195
13117
  };
12196
13118
  });
12197
13119
  this.emit({ type: "models", models });
13120
+ // 联网刷新拉回动态本地模型(如 llama.cpp)后,若当前对话尚处于未发消息阶段,尝试自愈恢复记忆模型
13121
+ void this.restoreProjectModelForCwd(this.cwd);
12198
13122
  }
12199
13123
  catch (err) {
12200
13124
  this.emit({
@@ -12437,15 +13361,44 @@ export class ClientSession {
12437
13361
  this.files.unwatchDir();
12438
13362
  this.files.unwatchGit();
12439
13363
  this.webUi.dispose();
13364
+ for (const entry of this.pendingSubagentNotices.values()) {
13365
+ clearTimeout(entry.timer);
13366
+ }
13367
+ this.pendingSubagentNotices.clear();
13368
+ for (const c of this.convs.values()) {
13369
+ c.suspendedSubagents?.clear();
13370
+ }
12440
13371
  // 关闭所有挂起的用户提问(dispose 时以「取消」解析,避免模型挂死)。
12441
13372
  this.cancelPendingQuestions();
12442
13373
  // 同理关闭挂起的页面调用(以失败解析:对面是扩展,没有答可等)。
12443
13374
  this.cancelPendingPageCalls();
12444
13375
  // 挂起的工具审批一并清掉(以「拒绝」解析,防 Promise/runtime 泄漏)。
12445
13376
  this.cancelPendingApprovals();
13377
+ // 角色轮等待者:客户端销毁 → 唤醒所有等待者收到 gone(避免悬挂超时)
13378
+ for (const [, waiters] of this.turnEndWaiters) {
13379
+ for (const fn of waiters) {
13380
+ try {
13381
+ fn("gone");
13382
+ }
13383
+ catch {
13384
+ // ignore
13385
+ }
13386
+ }
13387
+ waiters.clear();
13388
+ }
13389
+ this.turnEndWaiters.clear();
13390
+ // 释放客户端所有对话名下的文件认领
13391
+ try {
13392
+ for (const id of this.convs.keys()) {
13393
+ this.getClaimStore?.().releaseByOwner(id);
13394
+ }
13395
+ }
13396
+ catch {
13397
+ // ignore
13398
+ }
12446
13399
  this.bg.stop();
12447
13400
  for (const conv of this.convs.values()) {
12448
- this.clearAllToolWatchdogs(conv);
13401
+ this.clearConversationToolStates(conv);
12449
13402
  // 逐个对话回收 eval 内核;下面的兜底再清一次表(含已 delete 的残留)。
12450
13403
  disposeEvalSession(conv.id);
12451
13404
  conv.unsubscribe?.();