pi-web-ui 0.111.0 → 0.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/dist/server/agent-service.js +1325 -488
  4. package/dist/server/approval-audit.js +119 -0
  5. package/dist/server/approval-default-rules.js +4 -4
  6. package/dist/server/approval-rules.js +42 -17
  7. package/dist/server/attachment-store.js +8 -8
  8. package/dist/server/canvas/canvas-agent-tool.js +6 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +88 -21
  10. package/dist/server/client-state.js +28 -0
  11. package/dist/server/delegate-mode.js +6 -3
  12. package/dist/server/delegate-task.js +18 -3
  13. package/dist/server/dispatch-domain-handlers.js +3 -0
  14. package/dist/server/dsh/dsh-agent-service.js +242 -11
  15. package/dist/server/dsh/dsh-serialize.js +1 -1
  16. package/dist/server/durable/durable-driver.js +75 -9
  17. package/dist/server/durable/durable-loader.js +1 -14
  18. package/dist/server/durable/durable-models.js +107 -0
  19. package/dist/server/durable/index.js +0 -4
  20. package/dist/server/engine-probe.js +76 -37
  21. package/dist/server/eval-tool.js +28 -3
  22. package/dist/server/goal-service.js +7 -0
  23. package/dist/server/index.js +344 -56
  24. package/dist/server/json-utils.js +57 -0
  25. package/dist/server/marker-service.js +8 -0
  26. package/dist/server/message-window.js +43 -10
  27. package/dist/server/model-admin.js +68 -106
  28. package/dist/server/model-resolver.js +66 -44
  29. package/dist/server/plan-manager.js +3 -6
  30. package/dist/server/plugin-api-catalog.js +1 -0
  31. package/dist/server/plugin-assets.js +238 -0
  32. package/dist/server/plugin-facilities.js +22 -0
  33. package/dist/server/plugin-ui-slots.js +1 -0
  34. package/dist/server/plugins.js +199 -5
  35. package/dist/server/preset-fields.js +25 -1
  36. package/dist/server/preset-share.js +5 -2
  37. package/dist/server/prompt-assembler.js +2 -1
  38. package/dist/server/prompt-composer.js +18 -8
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/queue-utils.js +156 -0
  41. package/dist/server/sdk-builtin-extensions.js +85 -0
  42. package/dist/server/server-config.js +66 -0
  43. package/dist/server/session-parser.js +49 -13
  44. package/dist/server/session-search.js +4 -3
  45. package/dist/server/settings-service.js +38 -5
  46. package/dist/server/soft-cap.js +8 -6
  47. package/dist/server/subagent-helpers.js +22 -1
  48. package/dist/server/subagent-notify.js +93 -0
  49. package/dist/server/subagent-security-gate.js +282 -0
  50. package/dist/server/subagent-templates.js +8 -0
  51. package/dist/server/subagents.js +144 -17
  52. package/dist/server/terminals.js +196 -8
  53. package/dist/server/text-quote.js +61 -0
  54. package/dist/server/tool-approval.js +63 -4
  55. package/dist/server/tool-guards.js +208 -0
  56. package/dist/server/tool-host-factories.js +46 -10
  57. package/dist/server/tool-overrides.js +21 -11
  58. package/dist/server/universal/driver-base.js +8 -0
  59. package/dist/server/universal/drivers/claude-code.js +20 -3
  60. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  61. package/dist/server/universal/index.js +0 -1
  62. package/dist/server/universal/universal-session.js +87 -10
  63. package/dist/server/worktree-service.js +189 -1
  64. package/docs/dsh-engine.md +1 -5
  65. package/package.json +1 -1
  66. package/plugin-sdk/client-utils.mjs +192 -5
  67. package/plugin-sdk/index.d.ts +63 -1
  68. package/plugin-sdk/index.mjs +94 -0
  69. package/plugin-sdk/package.json +5 -1
  70. package/plugins/catalog.json +11 -0
  71. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-Dqr1dK28.js} +1 -1
  72. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  73. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  74. package/web/dist/index.html +11 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B0ajS__T.js +0 -697
  77. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -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 主动根据当前问题精简上下文并自主控制范围。
@@ -106,7 +111,7 @@ import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktre
106
111
  import { sameSessionFile } from "./scheduler-tasks.js";
107
112
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
108
113
  import { scanAtMentions } from "./universal/universal-attachments.js";
109
- import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
114
+ import { extractStreamingPayload, formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt, } from "./text-quote.js";
110
115
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
111
116
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
112
117
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
@@ -136,6 +141,8 @@ const DELTA_ACTIVE_WINDOW_MS = 1500;
136
141
  */
137
142
  const STATS_CACHE_MS = 250;
138
143
  const WIDGET_REFRESH_MS = 2000;
144
+ /** 创建时未注入派发工具的子代理会话(模块级:过户跨 ClientSession 仍认得),syncSubagentOverride 不得再补回内置 subagent。 */
145
+ const SPAWN_TOOLS_BARRED = new WeakSet();
139
146
  /** Model-stall watchdog: warn (don't abort — deep thinking can be legitimately
140
147
  * quiet for minutes) when a streaming run produced NO SDK events for this long.
141
148
  * Covers the failure class the per-tool watchdog cannot see: half-open API
@@ -196,8 +203,8 @@ import { splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-
196
203
  export { splitAgentStartPrompt };
197
204
  import { makeKillableBashTool, makeAdaptiveBashTool } from "./bash-tool.js";
198
205
  export { makeKillableBashTool, makeAdaptiveBashTool };
199
- import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, } from "./tool-guards.js";
200
- 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, };
201
208
  import { normalizeSolPlanToPlanSteps, makePlanUpdateTool } from "./plan-update-tool.js";
202
209
  export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
203
210
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
@@ -211,6 +218,39 @@ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRec
211
218
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
212
219
  export { pickAdoptableOrphan, sameCwd };
213
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;
214
254
  export { processTreeKillPlan, resolveCwdTarget };
215
255
  export class ClientSession {
216
256
  static mcpBridge = null;
@@ -242,6 +282,8 @@ export class ClientSession {
242
282
  /** 目标模式「委托执行」(Plan A)的「本轮结束」等待者:convId → 回调集合。
243
283
  * agent_end 到达时唤醒(事件驱动,绝不轮询);对话被移出时按 gone 收。 */
244
284
  turnEndWaiters = new Map();
285
+ /** 子代理终态自动通知防抖批处理队列:parentId → { timer, subagents } (issue #713) */
286
+ pendingSubagentNotices = new Map();
245
287
  // -----------------------------------------------------------------------
246
288
  // Goal / review / wizard —— 自包含模块,见 goal-service.ts。每个对话有独立
247
289
  // 的 GoalStatus,审查可并发;宿主回调在构造函数里接入。
@@ -339,6 +381,17 @@ export class ClientSession {
339
381
  throw new Error("no active conversation");
340
382
  return conv;
341
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
+ }
342
395
  /** Runtime of the active conversation. */
343
396
  get runtime() {
344
397
  return this.conv.runtime;
@@ -433,7 +486,7 @@ export class ClientSession {
433
486
  * `model`(可选):"provider/id",显式指定子代理模型。不传时由调用方决定是否
434
487
  * 回退到模板模型 / 设置面板默认模型;null = 跟随主对话当前模型(默认行为,
435
488
  * runtime 重建时会继承共享 ModelRuntime 的当前默认)。 */
436
- 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) {
437
490
  // 数量上限先行:每个子代理都是完整 runtime + TerminalManager,无上限时一次
438
491
  // 并行派发几十个会把服务进程拖垮。持久化普通对话则受项目会话上限限制。
439
492
  if (persist) {
@@ -468,9 +521,19 @@ export class ClientSession {
468
521
  const baseCwd = spawner?.cwd ?? this.cwd;
469
522
  // 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
470
523
  const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
471
- const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
472
524
  const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
473
- 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);
474
537
  const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
475
538
  if (!persist) {
476
539
  // 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
@@ -482,13 +545,30 @@ export class ClientSession {
482
545
  }
483
546
  catch { }
484
547
  }
485
- const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
486
- cwd: sessionBaseDir,
487
- agentDir: this.agentDir,
488
- sessionManager,
489
- });
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
+ }
490
567
  const conv = this.makeConversation(runtime, conversationId, terminals);
491
- conv.cwd = resolvedCwd;
568
+ conv.cwd = effectiveCwd;
569
+ if (worktreeContext) {
570
+ conv.subagentWorktree = worktreeContext;
571
+ }
492
572
  conv.isSubagent = !persist;
493
573
  if (conv.isSubagent) {
494
574
  // 首轮 sendUserMessage 进入流式前的预检/模型切换窗口标记为投递中,
@@ -501,6 +581,17 @@ export class ClientSession {
501
581
  conv.parentId = parentId ?? this.activeId ?? undefined;
502
582
  conv.subagentType = type;
503
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
+ }
504
595
  // 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
505
596
  // (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
506
597
  conv.subagentTemplate = apply;
@@ -519,11 +610,8 @@ export class ClientSession {
519
610
  // message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
520
611
  // 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
521
612
  conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
522
- // 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
523
- this.applyRetryOverrides();
524
- // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
525
- this.applyCompactionOverrides();
526
- this.applyCodemodeOverrides();
613
+ // 子代理不走 bindSession——统一收口注入配置覆盖与工具门控
614
+ this.applySessionOverrides(conv);
527
615
  // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
528
616
  // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
529
617
  try {
@@ -545,7 +633,8 @@ export class ClientSession {
545
633
  // 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
546
634
  // 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
547
635
  // 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
548
- 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);
549
638
  const followModel = resolvedModel
550
639
  ? resolvedModel
551
640
  : spawnerSession.model
@@ -564,6 +653,9 @@ export class ClientSession {
564
653
  await conv.session.setModel(m);
565
654
  }
566
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
+ }
567
659
  // 换模型失败不阻断运行——沿用默认模型继续。
568
660
  this.emit({
569
661
  type: "notice",
@@ -574,6 +666,9 @@ export class ClientSession {
574
666
  }
575
667
  }
576
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
+ }
577
672
  this.emit({
578
673
  type: "notice",
579
674
  level: "warning",
@@ -582,16 +677,8 @@ export class ClientSession {
582
677
  });
583
678
  }
584
679
  }
585
- // 换模型之后同步重算软上限。setModel 的 model_select 不进 session.subscribe,
586
- // 首轮压缩检查会用到换模型前的 reserve(1M 窗口算出的 74 万泄漏到小窗口上,
587
- // 触发点变成负数,上下文到几万 token 就压)。
588
- this.refreshCompactionOverride(conv);
589
- // 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
590
- // 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
591
- // SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
592
- // 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
593
- // 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
594
- const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
680
+ // 思考强度:显式 thinking 参数 > 模板指定 > 派发者当前强度
681
+ const thinkingLevel = thinking?.trim() || apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
595
682
  if (thinkingLevel) {
596
683
  try {
597
684
  conv.session.setThinkingLevel(thinkingLevel);
@@ -646,6 +733,21 @@ export class ClientSession {
646
733
  const found = this.findSubagentOwner?.(convId);
647
734
  return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
648
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
+ }
649
751
  /** B20:convId 当前由哪个 ClientSession 持有(本会话优先;查不到兜底本会话)。 */
650
752
  subagentOwnerOf(convId) {
651
753
  if (!convId)
@@ -710,7 +812,7 @@ export class ClientSession {
710
812
  /** B20:subagentHost.spawnSubagent 的委托入口(在**当前**会话上执行模板校验与真正
711
813
  * spawn)—— 过户后由 host 按 parentId 的持有方调用,保证新子代理注册进持有方
712
814
  * 的 convs(左栏「不见/错位」、cwd 跟错项目才不再发生)。 */
713
- async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist) {
815
+ async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) {
714
816
  // 模板:存在且启用时应用;传了名字但不可用 → 抛错让工具转给 AI。
715
817
  const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
716
818
  if (templateName && (!tpl || !tpl.enabled)) {
@@ -719,11 +821,220 @@ export class ClientSession {
719
821
  // B20:parentId 是建时旧 id 时先解析成当前 id(过户撞 id 改名后,新子代理
720
822
  // 的 parentId 必须指向改名后的主对话,否则族展开/lists 都认不出它)。
721
823
  const canonParent = parentId ? (this.findSubagentOwner?.(parentId)?.convId ?? parentId) : parentId;
722
- 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);
723
825
  }
724
826
  subagentRunOutcome(conv) {
725
827
  return subagentRunOutcome(conv);
726
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
+ }
727
1038
  /**
728
1039
  * 事件驱动地等某对话「当前回合结束」(目标模式委托执行用)。
729
1040
  * 若当前并未在跑则立即返回既有结局;超时返回 "timeout";对话已消失返回 "gone"。
@@ -974,6 +1285,17 @@ export class ClientSession {
974
1285
  if (conv?.planMode === true)
975
1286
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
976
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
+ }
977
1299
  return all.filter((n) => allowed.has(n) && !disabled.has(n));
978
1300
  }
979
1301
  /** 工具在系统提示词里的一行摘要:用户覆盖 → 出厂 snippet → 描述首句。 */
@@ -1064,6 +1386,17 @@ export class ClientSession {
1064
1386
  if (conv?.planMode === true)
1065
1387
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
1066
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
+ }
1067
1400
  const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1068
1401
  // 「已加载集合」里有名字 ≠ 活跃集里有它:JIT 自动激活(见 autoActivateToolIfLoadable)
1069
1402
  // 与任何只标记不重放门控的路径都会造出这种半吊子状态。按活跃集判定,
@@ -1214,6 +1547,7 @@ export class ClientSession {
1214
1547
  return renderMainCompose(this.composeInputs(src), {
1215
1548
  promptTemplate: this.settingsSvc.current.promptTemplate,
1216
1549
  promptOverrides: this.settingsSvc.current.promptOverrides,
1550
+ promptDisabled: this.settingsSvc.current.promptDisabled ?? [],
1217
1551
  preset,
1218
1552
  disabledToolCount: effectiveDisabledAgentTools(this.settingsSvc.current).length,
1219
1553
  isLazy: src.lazy,
@@ -1267,9 +1601,12 @@ export class ClientSession {
1267
1601
  const def = sess.getToolDefinition(name);
1268
1602
  if (!def)
1269
1603
  continue;
1270
- const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
1271
- 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)) {
1272
1608
  snippets[name] = eff.promptSnippet.trim();
1609
+ }
1273
1610
  if (baseSet.has(name) && eff.promptGuidelines)
1274
1611
  guidelines.push(...eff.promptGuidelines);
1275
1612
  }
@@ -1292,7 +1629,7 @@ export class ClientSession {
1292
1629
  const tpl = (this.settingsSvc.current.promptTemplate ?? "").trim();
1293
1630
  const ovs = this.settingsSvc.current.promptOverrides ?? {};
1294
1631
  const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
1295
- 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 ?? []));
1296
1633
  return { texts, full: rendered, toolsSchema: buildToolsSchemaText(schemaEntries) };
1297
1634
  }
1298
1635
  catch {
@@ -1442,12 +1779,20 @@ export class ClientSession {
1442
1779
  }
1443
1780
  }
1444
1781
  subagentHost = {
1445
- spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist) => {
1782
+ spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) => {
1446
1783
  // B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
1447
1784
  // 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
1448
1785
  // 否则新子代理注册进旧会话、目标页左栏「不见/错位」。
1449
1786
  const owner = parentId ? this.subagentOwnerOf(parentId) : this;
1450
- 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
+ }
1451
1796
  },
1452
1797
  getSubagent: (convId) => {
1453
1798
  // B20:本会话查不到就去「当前持有方」查 —— 过户把子代理整体搬走后,
@@ -1459,6 +1804,19 @@ export class ClientSession {
1459
1804
  return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
1460
1805
  },
1461
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
+ },
1462
1820
  handoffSubagent: async (fromRunId, toRunId, payload) => {
1463
1821
  await this.handoffSubagent(fromRunId, toRunId, payload);
1464
1822
  },
@@ -1479,6 +1837,9 @@ export class ClientSession {
1479
1837
  if (conv.session.isStreaming || !conv.session.isIdle) {
1480
1838
  await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1481
1839
  }
1840
+ if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
1841
+ void owner.finalizeSubagentWorktree(conv).catch(() => { });
1842
+ }
1482
1843
  }
1483
1844
  },
1484
1845
  getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
@@ -1672,6 +2033,8 @@ export class ClientSession {
1672
2033
  subagentTemplates;
1673
2034
  /** 审批规则库(全局共享,<dataDir>/approval-rules.json)。 */
1674
2035
  approvalRules;
2036
+ /** 审批审计日志追加器(<dataDir>/audit/approvals.jsonl,Issue #722)。 */
2037
+ auditLogger;
1675
2038
  /** 未发送输入框草稿(全局共享,<dataDir>/composer-drafts.json,按 sessionId 键入,见 server/composer-drafts.ts)。 */
1676
2039
  drafts;
1677
2040
  /** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
@@ -1693,8 +2056,21 @@ export class ClientSession {
1693
2056
  /** 任务计划管理器(Plan Mode / Step State Machine)。 */
1694
2057
  planManager;
1695
2058
  approvalSeq = 0;
1696
- /** 待审批高危工具调用(Human-in-the-Loop: Edit & Run)。 */
1697
- 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
+ }
1698
2074
  // -----------------------------------------------------------------------
1699
2075
  // 浏览器页面桥(标准 pi 引擎的 browser_page customTool):模型调工具 → 发
1700
2076
  // page_request 给浏览器 → 前端转 page-picker 扩展 → page_response 回到这里
@@ -1717,6 +2093,7 @@ export class ClientSession {
1717
2093
  this.roots = stateStore.getWorkspaceRoots(clientId, cwd);
1718
2094
  this.subagentTemplates = new SubagentTemplatesStore(join(stateStore.dataDir, "subagent-templates.json"));
1719
2095
  this.approvalRules = new ApprovalRulesStore(join(stateStore.dataDir, "approval-rules.json"));
2096
+ this.auditLogger = new ApprovalAuditLogger(stateStore.dataDir);
1720
2097
  this.drafts = new ComposerDraftsStore(join(stateStore.dataDir, "composer-drafts.json"));
1721
2098
  this.sandboxes = new SandboxManager(stateStore.dataDir);
1722
2099
  this.planManager = new PlanManager(join(stateStore.dataDir, "plans.json"));
@@ -1758,21 +2135,21 @@ export class ClientSession {
1758
2135
  getSession: () => this.session,
1759
2136
  cwd: () => this.cwd,
1760
2137
  agentDir: () => this.agentDir,
1761
- isStreaming: () => this.session.isStreaming,
2138
+ isStreaming: () => this.session.isStreaming || Boolean(this.conv?.promptInFlight),
1762
2139
  reloadSession: async () => {
2140
+ if (this.session.isStreaming || Boolean(this.conv?.promptInFlight)) {
2141
+ this.settingsSvc.setPendingReload(true);
2142
+ return;
2143
+ }
1763
2144
  await this.session.reload();
1764
- // reload() 重读磁盘 settings.json,会丢掉内存 applyOverrides
1765
- // (含重试次数覆盖)——依次重放:重试覆盖 → 软上限覆盖 → 终端门控。
1766
- this.applyRetryOverrides();
1767
- this.applyCompactionOverrides();
1768
- this.applyCodemodeOverrides();
1769
- // reload() 会把 custom 工具重新加回活跃集——重放当前会话归属预设门控。
1770
- this.applyToolGating(this.session, this.conv?.agentPreset);
2145
+ // reload() 重读磁盘 settings.json,统一收口重放配置覆盖与工具门控
2146
+ this.applySessionOverrides(this.conv);
1771
2147
  await this.pushSlashCommands();
1772
2148
  },
1773
2149
  applyRetryOverrides: () => this.applyRetryOverrides(),
1774
2150
  applyCompactionOverrides: () => this.applyCompactionOverrides(),
1775
2151
  applyCodemodeOverrides: () => this.applyCodemodeOverrides(),
2152
+ applySessionOverrides: () => this.applySessionOverrides(),
1776
2153
  applyToolGating: () => {
1777
2154
  for (const conv of this.convs.values()) {
1778
2155
  this.applyToolGating(conv.session, conv.agentPreset);
@@ -1970,6 +2347,13 @@ export class ClientSession {
1970
2347
  // Prune dead background tasks every 30s (only spawns netstat/lsof while
1971
2348
  // the list is non-empty). unref: must not keep the process alive.
1972
2349
  this.bg.start();
2350
+ if (!ephemeralCleanupScheduled) {
2351
+ ephemeralCleanupScheduled = true;
2352
+ const timer = setTimeout(() => {
2353
+ cleanupOrphanedSessionDirs(this.agentDir);
2354
+ }, 5000);
2355
+ timer.unref?.();
2356
+ }
1973
2357
  }
1974
2358
  static async create(clientId, cwd, stateStore, opts) {
1975
2359
  const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
@@ -2114,8 +2498,9 @@ export class ClientSession {
2114
2498
  * 应用(prompt replace/append + 白名单),其余(终端接管、Windows persona
2115
2499
  * 等)仍跟随主会话设置。undefined = 按主会话设置(普通对话/不选模板的子代理)。
2116
2500
  */
2117
- makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset) {
2501
+ makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset, noSpawnTools) {
2118
2502
  return async ({ cwd: effectiveCwd, sessionManager }) => {
2503
+ const sdkBuiltins = await getSdkBuiltinExtensionFactories();
2119
2504
  const services = await createAgentSessionServices({
2120
2505
  cwd: effectiveCwd,
2121
2506
  modelRuntime: this.sharedModelRuntime,
@@ -2239,19 +2624,9 @@ export class ClientSession {
2239
2624
  // agent run 前触发,SDK 此时已用最新工具/资源拼好基础提示词;若配置了模板或
2240
2625
  // 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
2241
2626
  // 等都取自本次 run 的 systemPromptOptions,永远最新)。
2627
+ disabledBuiltinExtensions: SDK_DISABLED_BUILTIN_EXTENSIONS,
2242
2628
  extensionFactories: [
2243
- {
2244
- name: "codemode",
2245
- hidden: true,
2246
- replaceable: true,
2247
- factory: createCodemodeExtension(),
2248
- },
2249
- {
2250
- name: "tool-search",
2251
- hidden: true,
2252
- replaceable: true,
2253
- factory: createToolSearchExtension(),
2254
- },
2629
+ ...sdkBuiltins,
2255
2630
  {
2256
2631
  name: "pi-webui-persona",
2257
2632
  hidden: true,
@@ -2301,8 +2676,11 @@ export class ClientSession {
2301
2676
  const def = sess.getToolDefinition(name);
2302
2677
  if (!def)
2303
2678
  continue;
2304
- const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
2305
- 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)) {
2306
2684
  activeSnippets[name] = eff.promptSnippet.trim();
2307
2685
  }
2308
2686
  if (baseSet.has(name) && eff.promptGuidelines) {
@@ -2385,61 +2763,37 @@ export class ClientSession {
2385
2763
  services,
2386
2764
  sessionManager,
2387
2765
  model: sessionModel,
2388
- // 覆盖 SDK 内置 bash(customTools 按 name 覆盖)。双实现分流:
2389
- // 「默认 bash 覆盖」开关(terminalBash)关 → 原生 SDK bash(纯进程、不开终端);
2390
- // 开 → 终端接管 bash(persist 决定一次性/持久,可静默自动转后台)。
2391
- // 整列工具统一过计划模式闸门(只规划不实施,写类/旁路工具执行前拒),
2392
- // read/write/edit 三处覆盖在会话建好后另注入(见 installToolOverrides)。
2766
+ // bash / read / write / edit 四处覆盖统一在会话建好后另注入(见 installToolOverrides)。
2767
+ // 原因是创建时的 customTools 恒顶掉第三方扩展注册的同名工具(SDK 的合并链是
2768
+ // [...扩展注册的工具, ...customTools] 后写赢,issue #750)。
2393
2769
  customTools: [
2394
- // P1-5:bash/read 包插件拦截(pre 拒/问即拦、post 脱敏补上下文;
2395
- // 未注入 toolGuard 时 withToolGuard 原样返回,零开销)。
2396
- // 权限沙箱拦截(只读模式拦截终端执行)。
2397
- wrapBashToolWithPermission(withToolGuard(withWorkspaceSnapshotGate(makeAdaptiveBashTool(
2398
- // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2399
- makeKillableBashTool(effectiveCwd, this.bashKills, () => this.getLang()), makeTerminalBashTool(terminals, {
2400
- cwd: effectiveCwd,
2401
- // 设置开 = 用终端;此分支里 persist 未显式给时默认一次性(false)。
2402
- defaultPersist: () => false,
2403
- idleMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashIdleMs) || 0),
2404
- maxForegroundMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashMaxForegroundMs) || 0),
2405
- kills: this.bashKills,
2406
- notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
2407
- // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2408
- lang: () => this.getLang(),
2409
- }),
2410
- // 设置关 → 原生 bash;开 → 终端 bash。
2411
- () => this.settingsSvc.current.terminalBash), () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
2412
- toolName: "bash",
2413
- guard: this.lateToolGuard,
2414
- conversationId: () => ownerId,
2415
- getLang: () => this.getLang(),
2416
- cwd: effectiveCwd,
2417
- getRoots: () => this.roots,
2418
- askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
2419
- getRules: () => this.approvalRules.list(),
2420
- }), () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2421
- this.settingsSvc.current.defaultPermissionPreset ??
2422
- "workspace-write-never", () => this.getLang()),
2423
2770
  ...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang(), {
2424
- checkSafety: (cmd) => {
2771
+ checkSafety: async (cmd, ctx) => {
2425
2772
  // 沙盒硬围栏:禁止引用源项目路径或跳出沙盒根。
2426
2773
  const activeSbx = this.sandboxes.getByCwd(effectiveCwd);
2427
2774
  if (activeSbx) {
2428
2775
  const sbxDenied = evaluateSandboxJail(activeSbx, "bash", { command: cmd }, effectiveCwd);
2429
2776
  if (sbxDenied)
2430
- return { blocked: true, reason: sbxDenied.reason };
2777
+ return { blocked: true, reason: sbxDenied.reason, reasonEn: sbxDenied.reasonEn };
2431
2778
  }
2432
2779
  // 计划模式:终端只放行只读命令(常驻终端也走这条,与 bash 覆盖同口径)。
2433
2780
  if (this.planModeOf(ownerId)) {
2434
2781
  const denied = planModeDenial("bash", { command: cmd });
2435
2782
  if (denied)
2436
- return { blocked: true, reason: denied.reason };
2783
+ return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
2437
2784
  }
2438
2785
  // 目标审查回合:常驻终端同样只放只读命令(审查者跑测试可以,改文件不行)。
2439
2786
  if (this.goalReviewTurnOf(ownerId)) {
2440
2787
  const denied = goalReviewDenial("bash", { command: cmd });
2441
2788
  if (denied)
2442
- 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 };
2443
2797
  }
2444
2798
  const perm = (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2445
2799
  this.settingsSvc.current.defaultPermissionPreset ??
@@ -2447,17 +2801,77 @@ export class ClientSession {
2447
2801
  if (perm === "read-only") {
2448
2802
  const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
2449
2803
  if (danger.denied || danger.dangerous) {
2450
- 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
+ };
2451
2809
  }
2452
2810
  }
2811
+ // 1. 系统核心安全:内置高危操作检测与自定义审批规则先行(优先级最高,防绕过)
2453
2812
  const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
2454
2813
  if (danger.denied) {
2455
- 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
+ }
2456
2870
  }
2457
2871
  return {};
2458
2872
  },
2459
2873
  }).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
2460
- // read / write / edit 三处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2874
+ // bash / read / write / edit 四处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2461
2875
  // 扩展加载顺序无关,直接塞进来会静默顶掉第三方扩展注册的同名工具(见
2462
2876
  // tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
2463
2877
  // 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置;带权限沙箱拦截与人机协同)。
@@ -2472,26 +2886,31 @@ export class ClientSession {
2472
2886
  // 空白名单 = 跟随主会话(插件工具照常进入子代理)。
2473
2887
  ...(apply && apply.enabledExtensions.length > 0 ? [] : this.enabledPluginToolDefs()),
2474
2888
  // 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
2475
- // 也注册了它们,因此可自然嵌套派发。host 按 ownerId 包装:子代理的
2889
+ // 默认也注册了它们,因此可自然嵌套派发;设置了 subagentMaxDepth 且子代理
2890
+ // 已到上限层时 noSpawnTools=true,连同下面的 delegate_task 一起不注入。host 按 ownerId 包装:子代理的
2476
2891
  // 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
2477
2892
  // 派发瞬间的 active——后台对话继续产出时用户可能已切到别的项目,用
2478
2893
  // activeId 会把孩子记到无关会话名下、沉到别的组/底部(issue #95)。
2479
2894
  // ownerId 即本 runtime 所属会话(创建时就已知,见各调用点),一身二任:
2480
2895
  // spawn 的 parentId(子代理记到真正的派发会话名下)+ wait_all 的
2481
2896
  // selfConvId(调用者自身永不计入等待,防 self-wait deadlock)。
2482
- ...(ownerId
2483
- ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined,
2484
- // B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
2485
- // 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
2486
- () => bridgeAnchor.session
2487
- ? (this.findConversationHome?.(bridgeAnchor.session)?.convId ?? ownerId)
2488
- : ownerId)
2489
- : 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)),
2490
2907
  // 结构化派单(六段式 + 服务端校验;执行体复用子代理 spawn 通道)。
2491
2908
  // owner 包装与上面同理:子代理记到真正的派发会话名下。
2492
- ...(ownerId
2493
- ? [makeDelegateTaskTool(withSubagentOwner(this.subagentHost, ownerId))]
2494
- : [makeDelegateTaskTool(this.subagentHost)]),
2909
+ ...(noSpawnTools
2910
+ ? []
2911
+ : ownerId
2912
+ ? [makeDelegateTaskTool(withSubagentOwner(this.subagentHost, ownerId))]
2913
+ : [makeDelegateTaskTool(this.subagentHost)]),
2495
2914
  // 结构化任务计划更新(Plan Mode / Step State Machine)。
2496
2915
  makePlanUpdateTool(this.planManager, () => {
2497
2916
  const id = ownerId ?? this.activeId;
@@ -2561,8 +2980,13 @@ export class ClientSession {
2561
2980
  ownerId,
2562
2981
  lang: () => this.getLang(),
2563
2982
  }),
2564
- // 高可靠行补丁工具(patch,基于内容哈希与语法块级替换)。
2565
- 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()),
2566
2990
  // 原生语言服务器工具(lsp,定义跳转/引用/悬停/诊断)。
2567
2991
  makeLspTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
2568
2992
  // MCP 服务器检测与安装管理工具(mcp_manage:list/check/install/remove/reload)。
@@ -2594,19 +3018,28 @@ export class ClientSession {
2594
3018
  lang: () => this.getLang(),
2595
3019
  getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
2596
3020
  }),
2597
- ].map((t) =>
2598
- // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2599
- // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
2600
- // 计划/审查者闸门同口径不在覆盖面,见 goal-review-gate.ts 头注)。
2601
- 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())),
3021
+ ].map((t) => this.wrapGenericTool(t, ownerId, effectiveCwd)),
2602
3022
  });
2603
3023
  // 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
2604
3024
  // 不改它(见 ClientSession.findConversationHome)。
2605
3025
  bridgeAnchor.session = created.session;
2606
- // 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 的合并链是
2607
3029
  // [...扩展工具, ...customTools] 后写赢 ⇒ 创建时塞进 customTools 会**恒定顶掉**第三方
2608
- // 扩展注册的同名工具(官方 docs/extensions.md 明写扩展可覆盖 read/write/edit)。
2609
- 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
+ });
2610
3043
  // 终端工具开关与预设门控从创建起就生效(工具始终注册进注册表,只调活跃集)。
2611
3044
  this.applyToolGating(created.session, targetPreset);
2612
3045
  return {
@@ -2666,7 +3099,8 @@ export class ClientSession {
2666
3099
  lastMessagesArray: [],
2667
3100
  queueSteering: [],
2668
3101
  queueFollowUp: [],
2669
- queuedImages: new Map(),
3102
+ queuedSteeringEntries: [],
3103
+ queuedFollowUpEntries: [],
2670
3104
  toolStartTimes: new Map(),
2671
3105
  toolPendingArgs: new Map(),
2672
3106
  activeToolCalls: new Map(),
@@ -2947,13 +3381,8 @@ export class ClientSession {
2947
3381
  onError: this.makeExtensionErrorReporter(conv.isEphemeral ? { text: `临时对话 ${conv.id}:`, textEn: `Ephemeral chat ${conv.id}: ` } : undefined),
2948
3382
  });
2949
3383
  conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
2950
- // 新会话 / 切换会话 / 强杀重建的必经之路:刚创建的 runtime 用的是 SDK
2951
- // 默认重试 3 次——这里把面板的 retryMaxAttempts 覆盖注入,否则“设了 6
2952
- // 次还是按 3 次重试”。已存在会话重复注入是幂等的(同值覆盖)。
2953
- this.applyRetryOverrides();
2954
- // 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
2955
- this.applyCompactionOverrides();
2956
- this.applyCodemodeOverrides();
3384
+ // 新会话 / 切换会话 / 强杀重建的必经之路:统一收口注入配置覆盖与工具门控
3385
+ this.applySessionOverrides(conv);
2957
3386
  this.scheduleSnapshot();
2958
3387
  this.webUi.refresh();
2959
3388
  this.startWidgetsTimer();
@@ -3065,6 +3494,13 @@ export class ClientSession {
3065
3494
  clearTimeout(t);
3066
3495
  conv.toolWatchdogs.clear();
3067
3496
  }
3497
+ /** 清理会话所有执行中的工具运行时状态(看门狗、计时器、进行中集合与参数缓存)。 */
3498
+ clearConversationToolStates(conv) {
3499
+ this.clearAllToolWatchdogs(conv);
3500
+ conv.toolStartTimes.clear();
3501
+ conv.activeToolCalls.clear();
3502
+ conv.toolPendingArgs.clear();
3503
+ }
3068
3504
  /** 发一条运行轨迹事件给插件(host.onRunEvent 订阅者,如轨迹视图插件)。
3069
3505
  * 异常隔离——序列化/插件坏了只记日志,绝不影响主流程。 */
3070
3506
  emitRun(conv, ev) {
@@ -3438,11 +3874,6 @@ export class ClientSession {
3438
3874
  // Any SDK event proves the run is alive — feeds the stall watchdog below.
3439
3875
  conv.lastSdkEventAt = Date.now();
3440
3876
  conv.stallNoticed = false;
3441
- // 模型可能在 pi-web-ui 之外被换(SDK 从会话历史恢复、/model 命令等),
3442
- // 而软上限 reserve 是按注入那一刻的窗口换算的固定值——模型一变必须重算,
3443
- // 否则大窗口算出的 reserve 泄漏到小窗口模型上,触发点被压成负数,
3444
- // 上下文刚过几万 token 就反复触发压缩。热路径只做一次字符串比对。
3445
- this.reapplySoftCapIfModelChanged(conv);
3446
3877
  switch (event.type) {
3447
3878
  case "bash_execution_update": {
3448
3879
  if (event.id) {
@@ -3458,6 +3889,8 @@ export class ClientSession {
3458
3889
  break;
3459
3890
  }
3460
3891
  case "tool_execution_start": {
3892
+ // issue #726:记录本轮触发了实质性工具操作,证明非空转推进
3893
+ conv.wakeTurnHadAction = true;
3461
3894
  // JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
3462
3895
  // automatically mark it as loaded so subsequent turns track it as fully active.
3463
3896
  if (conv.session && event.toolName) {
@@ -3588,14 +4021,8 @@ export class ClientSession {
3588
4021
  case "queue_update":
3589
4022
  conv.queueSteering = [...event.steering];
3590
4023
  conv.queueFollowUp = [...event.followUp];
3591
- if (conv.queuedImages && conv.queuedImages.size > 0) {
3592
- const allQueued = new Set([...event.steering, ...event.followUp]);
3593
- for (const key of conv.queuedImages.keys()) {
3594
- if (!allQueued.has(key)) {
3595
- conv.queuedImages.delete(key);
3596
- }
3597
- }
3598
- }
4024
+ conv.queuedSteeringEntries = reconcileQueuedEntries(conv.queuedSteeringEntries ?? [], event.steering);
4025
+ conv.queuedFollowUpEntries = reconcileQueuedEntries(conv.queuedFollowUpEntries ?? [], event.followUp);
3599
4026
  break;
3600
4027
  // 手动 /compact 或阈值/溢出自动压缩开始——常驻进度条(快照 compaction
3601
4028
  // 字段),而不是一次性 toast(toast 几秒就消失,而摘要生成可能持续
@@ -3729,6 +4156,19 @@ export class ClientSession {
3729
4156
  if (stopNotice) {
3730
4157
  this.emit({ type: "notice", level: "warning", text: stopNotice.text, textEn: stopNotice.textEn });
3731
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
+ }
3732
4172
  this.emitConversations();
3733
4173
  break;
3734
4174
  }
@@ -3757,6 +4197,26 @@ export class ClientSession {
3757
4197
  // 或「等对话空闲」上,而 onAgentEnd 随后会把它需要的 verdict 交回。
3758
4198
  this.notifyTurnEnd(conv);
3759
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
+ }
3760
4220
  // Deferred settings reload: settings (system prompt / skills /
3761
4221
  // extensions) changed while the run was streaming — applying now
3762
4222
  // would have torn down the in-flight run.
@@ -3799,10 +4259,19 @@ export class ClientSession {
3799
4259
  }
3800
4260
  }, 50);
3801
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
+ }
3802
4270
  // 本轮真正结束且不再重试:立即向客户端广播最新会话状态(流式状态及时复位)
3803
4271
  if (!event.willRetry) {
3804
4272
  if (conv.queueSteering.length === 0 && conv.queueFollowUp.length === 0) {
3805
- conv.queuedImages?.clear();
4273
+ conv.queuedSteeringEntries = [];
4274
+ conv.queuedFollowUpEntries = [];
3806
4275
  if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
3807
4276
  conv.session._pendingNextTurnMessages = [];
3808
4277
  }
@@ -4161,53 +4630,17 @@ export class ClientSession {
4161
4630
  cost: s.cost,
4162
4631
  contextUsage: (() => {
4163
4632
  const cu = s.contextUsage;
4164
- if (!cu)
4633
+ if (!cu || cu.contextWindow <= 0)
4165
4634
  return stats.contextUsage;
4166
- // 压缩刚结束、下轮响应未到:SDK 报 null,用压缩结果回填约数。
4167
- if (cu.tokens == null && conv.lastCompactionTokens != null && cu.contextWindow > 0) {
4168
- return {
4169
- tokens: conv.lastCompactionTokens,
4170
- contextWindow: cu.contextWindow,
4171
- percent: (conv.lastCompactionTokens / cu.contextWindow) * 100,
4172
- estimated: false,
4173
- softCap: this.activeSoftCap(cu.contextWindow),
4174
- };
4175
- }
4176
- // 展示用兜底 0(会话未就绪时旧行为也是 0);落账 lastTurnBaseTokens 的路径
4177
- // 在 agent_settled 处对 null 跳过,不受此兜底影响。
4178
- const baseTokens = this.currentBaseTokens(conv) ?? 0;
4179
- // 空白会话(尚未发言,SDK 报 0 或 null):真实反映当前模式/工具配置下的 Base 开销。
4180
- if (cu.contextWindow > 0 && (this.isBlankConversation(conv) || cu.tokens == null || cu.tokens === 0)) {
4181
- return {
4182
- tokens: baseTokens,
4183
- contextWindow: cu.contextWindow,
4184
- percent: (baseTokens / cu.contextWindow) * 100,
4185
- estimated: false,
4186
- softCap: this.activeSoftCap(cu.contextWindow),
4187
- };
4188
- }
4189
- // 首轮对话中(或尚未获得带有效 usage 的定稿助手消息):
4190
- // 叠加精准的 Base 开销与当前非系统消息(用户输入、流式生成等)估算,
4191
- // 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致突增翻倍(如 10k 变成 17k)。
4192
- if ((conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) && cu.contextWindow > 0) {
4193
- const nonSystemTokens = this.estimateNonSystemTokens(conv);
4194
- const total = baseTokens + nonSystemTokens;
4195
- return {
4196
- tokens: total,
4197
- contextWindow: cu.contextWindow,
4198
- percent: (total / cu.contextWindow) * 100,
4199
- estimated: true,
4200
- softCap: this.activeSoftCap(cu.contextWindow),
4201
- };
4202
- }
4203
- // 已有多轮对话历史:若在对话间歇切预设或开关工具,叠加当前 Base 开销相比上一轮定稿时的差额
4204
- const baseDelta = baseTokens - (conv.lastTurnBaseTokens ?? baseTokens);
4205
- 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);
4206
4639
  return {
4207
4640
  tokens: effectiveTokens,
4208
4641
  contextWindow: cu.contextWindow,
4209
- percent: cu.contextWindow > 0 ? (effectiveTokens / cu.contextWindow) * 100 : cu.percent,
4210
- estimated: false,
4642
+ percent: (effectiveTokens / cu.contextWindow) * 100,
4643
+ estimated: isEstimated,
4211
4644
  softCap: this.activeSoftCap(cu.contextWindow),
4212
4645
  };
4213
4646
  })(),
@@ -4257,7 +4690,14 @@ export class ClientSession {
4257
4690
  // Only the levels the current model actually supports — the SDK clamps
4258
4691
  // anything else, so the UI must not offer (or must disable) the rest.
4259
4692
  availableThinkingLevels: this.session.getAvailableThinkingLevels(),
4260
- 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
+ },
4261
4701
  errorMessage: state.errorMessage,
4262
4702
  retry: conv.retryState ?? null,
4263
4703
  compaction: conv.compactionState ?? null,
@@ -4487,10 +4927,9 @@ export class ClientSession {
4487
4927
  if (p.conversationId === undefined || p.conversationId === conversationId)
4488
4928
  return true;
4489
4929
  }
4490
- for (const a of this.pendingApprovals.values()) {
4491
- if (a.conversationId === undefined || a.conversationId === conversationId)
4492
- return true;
4493
- }
4930
+ const conv = this.convs.get(conversationId);
4931
+ if (conv?.pendingApprovals && conv.pendingApprovals.size > 0)
4932
+ return true;
4494
4933
  return false;
4495
4934
  }
4496
4935
  /** 标准引擎的 question_answer 路由入口(index.ts 经 cs.answerQuestion?. 转发)。
@@ -4549,9 +4988,25 @@ export class ClientSession {
4549
4988
  return;
4550
4989
  }
4551
4990
  const id = `appr-${++this.approvalSeq}`;
4552
- const conv = conversationId ? this.convs.get(conversationId) : this.conv;
4553
- 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);
4554
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
+ });
4555
5010
  // 放行但不弹窗:不记 pending,不发消息,模型继续跑。
4556
5011
  resolve({ decision: "approve" });
4557
5012
  return;
@@ -4566,6 +5021,10 @@ export class ClientSession {
4566
5021
  }
4567
5022
  }
4568
5023
  }
5024
+ if (!conv) {
5025
+ resolve({ decision: "deny", reason: "目标对话不存在" });
5026
+ return;
5027
+ }
4569
5028
  const entry = {
4570
5029
  id,
4571
5030
  toolCallId,
@@ -4576,12 +5035,12 @@ export class ClientSession {
4576
5035
  ...(category ? { category } : {}),
4577
5036
  ...(hits && hits.length > 0 ? { hits } : {}),
4578
5037
  ...(parentTool ? { parentTool } : {}),
4579
- conversationId,
5038
+ conversationId: conv.id,
4580
5039
  conversationTitle,
4581
5040
  resolve,
4582
5041
  createdAt: Date.now(),
4583
5042
  };
4584
- this.pendingApprovals.set(id, entry);
5043
+ this.ensurePendingApprovals(conv).set(id, entry);
4585
5044
  this.emit({
4586
5045
  type: "tool_approval_pending",
4587
5046
  id,
@@ -4593,7 +5052,7 @@ export class ClientSession {
4593
5052
  ...(category ? { category } : {}),
4594
5053
  ...(hits && hits.length > 0 ? { hits } : {}),
4595
5054
  ...(parentTool ? { parentTool } : {}),
4596
- ...(conversationId !== undefined ? { conversationId } : {}),
5055
+ conversationId: conv.id,
4597
5056
  ...(conversationTitle ? { conversationTitle } : {}),
4598
5057
  });
4599
5058
  this.flushSnapshot();
@@ -4607,21 +5066,48 @@ export class ClientSession {
4607
5066
  * 「全部允许」却还有几张弹窗挂着等点),并推一次设置面板(撤销区)。
4608
5067
  */
4609
5068
  resolveToolApproval(id, decision, editedParams, reason, scope) {
4610
- const pending = this.pendingApprovals.get(id);
4611
- 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)
4612
5081
  return false;
4613
- const convId = pending.conversationId ?? this.activeId;
4614
- const conv = this.convs.get(convId);
4615
- 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 = [];
4616
5102
  pending.resolve({ decision, editedParams, reason });
4617
5103
  this.emit({ type: "tool_approval_resolved", id });
4618
- if (decision === "approve" && scope && scope !== "once" && conv) {
5104
+ if (decision === "approve" && scope && scope !== "once") {
4619
5105
  const policy = this.ensureApprovalPolicy(conv);
4620
5106
  if (scope === "all")
4621
5107
  policy.allowAll = true;
4622
5108
  else if (pending.category)
4623
5109
  policy.categories.set(pending.category.id, pending.category);
4624
- this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(convId, policy));
5110
+ this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(conv, policy));
4625
5111
  this.settingsSvc.push();
4626
5112
  }
4627
5113
  this.flushSnapshot();
@@ -4634,15 +5120,24 @@ export class ClientSession {
4634
5120
  return conv.approvalPolicy;
4635
5121
  }
4636
5122
  /** 把某对话里已被策略覆盖的其它待审批项一并放行,返回放行条数。 */
4637
- approveCoveredPending(convId, policy) {
5123
+ approveCoveredPending(conv, policy) {
4638
5124
  let n = 0;
5125
+ if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
5126
+ return 0;
4639
5127
  // eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
4640
- for (const [oid, o] of [...this.pendingApprovals]) {
4641
- if ((o.conversationId ?? this.activeId) !== convId)
4642
- continue;
4643
- if (!approvalSuppressionReason(policy, true, o.category?.id))
5128
+ for (const [oid, o] of [...conv.pendingApprovals]) {
5129
+ if (!approvalSuppressionReason(policy, true, o.category?.id, o.toolName, o.params))
4644
5130
  continue;
4645
- 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
+ });
4646
5141
  o.resolve({ decision: "approve" });
4647
5142
  this.emit({ type: "tool_approval_resolved", id: oid });
4648
5143
  n++;
@@ -4673,23 +5168,36 @@ export class ClientSession {
4673
5168
  }
4674
5169
  /** 全局审批开关被关掉时:挂着的待审批全部按批准放行(否则弹窗还在等人点)。 */
4675
5170
  autoApprovePendingApprovals(reasonZh, reasonEn) {
4676
- if (this.pendingApprovals.size === 0)
4677
- return;
4678
5171
  let n = 0;
4679
- // eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
4680
- for (const [oid, o] of [...this.pendingApprovals]) {
4681
- this.pendingApprovals.delete(oid);
4682
- o.resolve({ decision: "approve" });
4683
- this.emit({ type: "tool_approval_resolved", id: oid });
4684
- 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();
4685
5200
  }
4686
- this.emit({
4687
- type: "notice",
4688
- level: "info",
4689
- text: `${reasonZh},已自动放行 ${n} 项待审批。`,
4690
- textEn: `${reasonEn} — auto-approved ${n} pending request(s).`,
4691
- });
4692
- this.flushSnapshot();
4693
5201
  }
4694
5202
  /**
4695
5203
  * 设置面板撤销区用:当前对话的审批策略(allowAll + 已记住的同类档位)。
@@ -4705,14 +5213,20 @@ export class ClientSession {
4705
5213
  categories: policy ? [...policy.categories.values()] : [],
4706
5214
  };
4707
5215
  }
5216
+ /** 获取审批决策审计日志记录器(Issue #722)。 */
5217
+ getAuditLogger() {
5218
+ return this.auditLogger;
5219
+ }
4708
5220
  /**
4709
5221
  * 设置某对话的审批策略(设置面板撤销用)。只应用给出的字段:allowAll 直接赋值;
4710
5222
  * categories 给出时作为保留名单整体替换(空数组 = 清掉全部同类记忆)。
4711
5223
  */
4712
5224
  setApprovalPolicy(partial) {
4713
5225
  const convId = partial.conversationId ?? this.activeId;
5226
+ if (!convId)
5227
+ return;
4714
5228
  const conv = this.convs.get(convId);
4715
- if (!conv)
5229
+ if (!conv || conv.isSubagent)
4716
5230
  return;
4717
5231
  const cur = conv.approvalPolicy;
4718
5232
  const next = {
@@ -4731,9 +5245,10 @@ export class ClientSession {
4731
5245
  this.flushSnapshot();
4732
5246
  }
4733
5247
  pendingApprovalForSnapshot() {
4734
- for (const [id, p] of this.pendingApprovals) {
4735
- if (p.conversationId !== undefined && p.conversationId !== this.activeId)
4736
- 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) {
4737
5252
  return {
4738
5253
  id,
4739
5254
  toolCallId: p.toolCallId,
@@ -4874,31 +5389,48 @@ export class ClientSession {
4874
5389
  // 单个结算异常不影响其余清理
4875
5390
  }
4876
5391
  }
4877
- for (const [id, a] of this.pendingApprovals) {
4878
- 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)
4879
5407
  continue;
4880
- this.pendingApprovals.delete(id);
5408
+ this.pendingPageCalls.delete(id);
5409
+ clearTimeout(p.timer);
4881
5410
  try {
4882
- a.resolve({ decision: "deny", reason: "运行已停止" });
5411
+ p.resolve({ ok: false, error: "会话已重置或停止,挂起中的页面调用已取消。" });
4883
5412
  }
4884
5413
  catch {
4885
5414
  // 单个结算异常不影响其余清理
4886
5415
  }
4887
- this.emit({ type: "tool_approval_resolved", id });
4888
5416
  }
4889
5417
  }
4890
5418
  /** 关闭所有挂起审批(dispose 时清理):以「拒绝」解析,避免等答复的
4891
5419
  * Promise 与对应 runtime 泄漏(会话没了,审批弹窗永远不会有人点)。 */
4892
5420
  cancelPendingApprovals() {
4893
- for (const [id, a] of this.pendingApprovals) {
4894
- this.pendingApprovals.delete(id);
4895
- try {
4896
- a.resolve({ decision: "deny", reason: "会话已关闭" });
4897
- }
4898
- catch {
4899
- // 单个 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 });
4900
5432
  }
4901
- this.emit({ type: "tool_approval_resolved", id });
5433
+ conv.pendingApprovals.clear();
4902
5434
  }
4903
5435
  }
4904
5436
  // -----------------------------------------------------------------------
@@ -5588,11 +6120,8 @@ export class ClientSession {
5588
6120
  setPlanMode: (enabled) => this.setPlanMode(enabled),
5589
6121
  getPlanMode: () => this.conv?.planMode === true,
5590
6122
  afterReload: () => {
5591
- // /reload 同样重读磁盘 settings.json——重放重试覆盖 + 软上限覆盖 + 终端门控。
5592
- this.applyRetryOverrides();
5593
- this.applyCompactionOverrides();
5594
- this.applyCodemodeOverrides();
5595
- this.applyToolGating(this.session, this.conv?.agentPreset);
6123
+ // /reload 同样重读磁盘 settings.json——统一收口重放配置覆盖与工具门控。
6124
+ this.applySessionOverrides(this.conv);
5596
6125
  },
5597
6126
  pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
5598
6127
  execPluginCommand: async (name, args) => {
@@ -5935,6 +6464,26 @@ export class ClientSession {
5935
6464
  pushSettings() {
5936
6465
  this.settingsSvc.push();
5937
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
+ }
5938
6487
  /** 把设置面板的出错重试次数注入全部存活会话的 SDK SettingsManager。
5939
6488
  * applyOverrides 只改内存合并视图(不碰 ~/.pi/agent/settings.json),
5940
6489
  * 且 SDK 每次退避前都重读 getRetrySettings()——即时生效、无需 reload。
@@ -5951,36 +6500,21 @@ export class ClientSession {
5951
6500
  }
5952
6501
  }
5953
6502
  }
5954
- /** 把压缩软上限换算成各存活会话的 compaction reserveTokens 覆盖
5955
- * (issue #229)。与重试覆盖同一 live 机制:applyOverrides 只改内存
5956
- * 合并视图,SDK 每次自动压缩检查前都重读 getCompactionSettings(),
5957
- * 无需 reload;软上限关闭时回填 SDK 默认 reserve(不让旧覆盖泄漏)。
5958
- * 窗口未知(会话未就绪/无模型)的会话跳过——创建/就绪/换模型路径
5959
- * 会重放(见各 applyRetryOverrides 调用点);此外 onEvent 按模型
5960
- * key 变化兜底重放(reapplySoftCapIfModelChanged),保证会话模型
5961
- * 在 pi-web-ui 之外被换(如 SDK 从会话历史恢复)后覆盖不泄漏。 */
6503
+ /** 确保各存活会话的 SDK compaction reserveTokens 保持默认值(issue #716)。
6504
+ * 软上限由 pi-web-ui 主动管控(triggerSoftCapCompactionIfExceeded),
6505
+ * 不再将 W - C 注入 SDK reserveTokens,从数学上杜绝换模型重算泄漏。 */
5962
6506
  applyCompactionOverrides() {
5963
- const s = this.settingsSvc.current;
5964
6507
  for (const c of this.convs.values()) {
5965
6508
  try {
5966
- this.applyCompactionOverrideForConv(c, s);
6509
+ c.session.settingsManager.applyOverrides({
6510
+ compaction: { reserveTokens: DEFAULT_COMPACTION_RESERVE_TOKENS },
6511
+ });
5967
6512
  }
5968
6513
  catch {
5969
6514
  // 会话未就绪或已释放 → 其 runtime 创建时统一注入。
5970
6515
  }
5971
6516
  }
5972
6517
  }
5973
- /** 单会话换算并注入软上限 reserve(applyCompactionOverrides 的循环体;
5974
- * reapplySoftCapIfModelChanged 单会话重放也复用)。抛错交调用方处置。 */
5975
- applyCompactionOverrideForConv(c, s) {
5976
- const modelId = modelKeyOf(c.session);
5977
- const contextWindow = contextWindowOf(c.session);
5978
- const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelId);
5979
- const reserve = softCapToReserve(contextWindow, cap);
5980
- c.session.settingsManager.applyOverrides({
5981
- compaction: { reserveTokens: reserve ?? DEFAULT_COMPACTION_RESERVE_TOKENS },
5982
- });
5983
- }
5984
6518
  /** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
5985
6519
  applyCodemodeOverrides() {
5986
6520
  const mode = this.settingsSvc.current.codemodeMode ?? "on";
@@ -5996,37 +6530,64 @@ export class ClientSession {
5996
6530
  }
5997
6531
  }
5998
6532
  }
5999
- /** 会话模型或窗口变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
6000
- * (findInitialModel)与 /model 命令都不经过 pi-web-ui 的 setModel
6001
- * 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
6002
- * 模型(1M 窗口)算出 748576,泄漏到 500K 窗口的会话后压缩触发点
6003
- * 变成负数,上下文几万 token 就被反复压缩。onEvent 比对模型 key 与窗口,
6004
- * 有变化才重放。setModel 本身不发 session 事件,子代理创建路径另有同步重算。 */
6005
- reapplySoftCapIfModelChanged(conv) {
6533
+ /** 计算指定会话当前的有效上下文 token 估算值(对齐底栏展示逻辑)。 */
6534
+ getEffectiveContextTokens(conv) {
6006
6535
  try {
6007
- const key = modelKeyOf(conv.session);
6008
- const contextWindow = contextWindowOf(conv.session);
6009
- if (conv.lastModelKey === key && conv.lastContextWindow === contextWindow)
6010
- return;
6011
- conv.lastModelKey = key;
6012
- conv.lastContextWindow = contextWindow;
6013
- if (key)
6014
- 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);
6015
6553
  }
6016
6554
  catch {
6017
- // 会话未就绪或已释放 → 留给创建/换模型路径与后续事件重试。
6555
+ return 0;
6018
6556
  }
6019
6557
  }
6020
- /** setModel 只向扩展发 model_select,不走 session.subscribe,
6021
- * onEvent 里的重放赶不上首轮压缩检查。换完模型后必须同步重算。 */
6022
- refreshCompactionOverride(conv) {
6558
+ /**
6559
+ * 若当前会话的有效 token 超过软上限,主动触发 SDK 上下文压缩(issue #716)。
6560
+ * 仅在空闲状态下触发(不会掐断进行中的任务)。
6561
+ * 返回是否触发了压缩。
6562
+ */
6563
+ async triggerSoftCapCompactionIfExceeded(conv) {
6023
6564
  try {
6024
- this.applyCompactionOverrideForConv(conv, this.settingsSvc.current);
6025
- conv.lastModelKey = modelKeyOf(conv.session);
6026
- conv.lastContextWindow = contextWindowOf(conv.session);
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;
6027
6577
  }
6028
- catch {
6029
- // 会话未就绪 → 首个 SDK 事件仍会走 reapplySoftCapIfModelChanged。
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;
6030
6591
  }
6031
6592
  }
6032
6593
  /** 当前活动对话的生效软上限(快照底栏标记线用;null = 关闭/未知)。 */
@@ -6034,7 +6595,11 @@ export class ClientSession {
6034
6595
  try {
6035
6596
  const s = this.settingsSvc.current;
6036
6597
  const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(this.session));
6037
- 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;
6038
6603
  }
6039
6604
  catch {
6040
6605
  return null;
@@ -6078,9 +6643,7 @@ export class ClientSession {
6078
6643
  if (!this.session.isStreaming) {
6079
6644
  try {
6080
6645
  await this.session.reload();
6081
- this.applyRetryOverrides();
6082
- this.applyCompactionOverrides();
6083
- this.applyToolGating(this.session, this.conv?.agentPreset);
6646
+ this.applySessionOverrides(this.conv);
6084
6647
  await this.pushSlashCommands();
6085
6648
  this.pushSettings();
6086
6649
  }
@@ -6466,9 +7029,7 @@ export class ClientSession {
6466
7029
  if (this.session && !this.session.isStreaming) {
6467
7030
  try {
6468
7031
  await this.session.reload();
6469
- this.applyRetryOverrides();
6470
- this.applyCompactionOverrides();
6471
- this.applyToolGating(this.session, this.conv?.agentPreset);
7032
+ this.applySessionOverrides(this.conv);
6472
7033
  await this.pushSlashCommands();
6473
7034
  }
6474
7035
  catch {
@@ -6495,11 +7056,11 @@ export class ClientSession {
6495
7056
  return undefined;
6496
7057
  }
6497
7058
  /**
6498
- * read / write / edit 三处覆盖的注入规格:基底 = 扩展注册的同名工具优先,否则 SDK 内置实现
6499
- * (见 tool-overrides.ts —— 这三处覆盖不能塞进创建时的 `customTools`,那会静默顶掉扩展的
6500
- * 同名工具,而官方 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)。
6501
7062
  */
6502
- toolOverrideSpecs(ownerId, cwd) {
7063
+ toolOverrideSpecs(ownerId, cwd, terminals) {
6503
7064
  const currentPermission = () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
6504
7065
  this.settingsSvc.current.defaultPermissionPreset ??
6505
7066
  "workspace-write-never";
@@ -6518,15 +7079,78 @@ export class ClientSession {
6518
7079
  getRoots: () => this.roots,
6519
7080
  askApproval: approve,
6520
7081
  getRules: () => this.approvalRules.list(),
7082
+ onAudit: (entry) => this.auditLogger.record(entry),
6521
7083
  };
6522
- // 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
7084
+ // 写/编/终端的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
6523
7085
  // 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
6524
7086
  // 快照并发门禁包裹在工具执行最前沿,确保写操作前快照必定已就绪。
6525
- 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));
6526
7091
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6527
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
+ };
6528
7147
  const remoteOps = createRemoteSdkOperations(cwd);
6529
7148
  const specs = [
7149
+ {
7150
+ name: "bash",
7151
+ fallback: () => composeBash(),
7152
+ composeWith: (base) => composeBash(base),
7153
+ },
6530
7154
  {
6531
7155
  name: "read",
6532
7156
  // 没有扩展 read:完整覆盖(内置基底 + 英文描述 + file_path 别名)。
@@ -6584,12 +7208,33 @@ export class ClientSession {
6584
7208
  this.settingsSvc.current.defaultAgentPreset ??
6585
7209
  "standard";
6586
7210
  const isPlanMode = conv?.planMode === true;
7211
+ const isDelegateMode = conv?.delegateMode === true;
6587
7212
  const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
6588
7213
  if (isPlanMode) {
6589
7214
  for (const toolName of PLAN_MODE_BLOCKED_TOOL_NAMES) {
6590
7215
  disabled.add(toolName);
6591
7216
  }
6592
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
+ }
6593
7238
  // 延迟加载(默认开):未加载的已登记工具一律当「临时禁用」——与用户禁用名单 /
6594
7239
  // 计划模式闸门走同一条门控链,不做第二套机制。加载只是把名字从这份名单里拿出来。
6595
7240
  let loadedNames = [];
@@ -6617,7 +7262,8 @@ export class ClientSession {
6617
7262
  forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME, ...loadedNames] : [],
6618
7263
  });
6619
7264
  const ownerId = conv?.id;
6620
- syncSubagentOverride(session, disabled.has("subagent"), () => ownerId
7265
+ const subagentOff = disabled.has("subagent") || SPAWN_TOOLS_BARRED.has(session);
7266
+ syncSubagentOverride(session, subagentOff, () => ownerId
6621
7267
  ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined, ownerId)[0]
6622
7268
  : makeSubagentTools(this.subagentHost)[0]);
6623
7269
  this.syncPluginTools(session, targetPreset);
@@ -6775,6 +7421,16 @@ export class ClientSession {
6775
7421
  const id = ownerId ?? this.activeId;
6776
7422
  return this.convs.get(id)?.awaitingVerdict != null;
6777
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
+ }
6778
7434
  /** 等待该会话正在并发生成的影子快照完成,确保写操作发生在快照完成之后。 */
6779
7435
  async awaitPendingWorkspaceSnapshot(ownerId) {
6780
7436
  const id = ownerId ?? this.activeId;
@@ -7113,6 +7769,32 @@ export class ClientSession {
7113
7769
  this.refreshPermission();
7114
7770
  this.flushSnapshot();
7115
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
+ }
7116
7798
  /** 当前启用的插件 AI 工具定义(provider 快照按 disabledPlugins 与 disabledPluginTools 过滤;
7117
7799
  * 未知/已卸载插件的禁用条目保留但不影响现有工具)。
7118
7800
  * 预设是第二层门控(见 tool-manager.ts 语义总表):非 standard 预设下插件工具
@@ -7133,18 +7815,21 @@ export class ClientSession {
7133
7815
  /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
7134
7816
  * 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。
7135
7817
  * 模板白名单的子代理(subagentBarsPluginTools)跳过:工厂期就没注册,这里
7136
- * 不回补,否则白名单等于没关门。 */
7818
+ * 不回补,否则白名单等于没关门。
7819
+ * 动态补入的工具统一经 wrapGenericTool 包裹,具备模式硬闸门与审批规则防护(Issue #722)。 */
7137
7820
  syncPluginTools(session, preset) {
7138
7821
  let targetPreset = preset;
7139
- for (const conv of this.convs.values()) {
7822
+ let ownerId;
7823
+ for (const [id, conv] of this.convs.entries()) {
7140
7824
  if (conv.session !== session)
7141
7825
  continue;
7826
+ ownerId = id;
7142
7827
  if (conv.subagentBarsPluginTools)
7143
7828
  return;
7144
7829
  targetPreset ??= conv.agentPreset;
7145
7830
  }
7146
7831
  try {
7147
- const defs = this.enabledPluginToolDefs(targetPreset);
7832
+ const defs = this.enabledPluginToolDefs(targetPreset).map((t) => this.wrapGenericTool(t, ownerId));
7148
7833
  // 移除口径 = 已同步过的 ∪ 全量插件宇宙:创建时工厂直接注册进
7149
7834
  // _customTools 的工具不在 applied 表里,首轮同步(defs 为空时)否则删不掉。
7150
7835
  const universe = new Set([
@@ -7438,8 +8123,35 @@ export class ClientSession {
7438
8123
  * after the current turn settles, skipping remaining planned tool calls.
7439
8124
  */
7440
8125
  queue = false) {
7441
- 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();
7442
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();
7443
8155
  if (!trimmedText && !hasAttachments) {
7444
8156
  this.emit({
7445
8157
  type: "notice",
@@ -7450,11 +8162,6 @@ export class ClientSession {
7450
8162
  this.flushSnapshot();
7451
8163
  return;
7452
8164
  }
7453
- // Captured at the START (before any await): the conversation being
7454
- // addressed by this prompt. See the naming block below — a concurrent
7455
- // switch/new_chat while prompt() is in flight must never target a
7456
- // different conversation.
7457
- const conv = this.conv;
7458
8165
  const promptAc = new AbortController();
7459
8166
  conv.activePromptAc = promptAc;
7460
8167
  this.markerSvc.clearActions(conv.id);
@@ -7586,9 +8293,7 @@ export class ClientSession {
7586
8293
  conv.transcriptBlocked = false;
7587
8294
  try {
7588
8295
  await s.reload();
7589
- this.applyRetryOverrides();
7590
- this.applyCompactionOverrides();
7591
- this.applyToolGating(s, conv.agentPreset);
8296
+ this.applySessionOverrides(conv);
7592
8297
  }
7593
8298
  catch {
7594
8299
  // reload 失败兜底
@@ -7856,61 +8561,10 @@ export class ClientSession {
7856
8561
  });
7857
8562
  return;
7858
8563
  }
7859
- const mainSupportsVision = s.model?.input?.includes("image") ?? false;
7860
- const promptImages = [];
7861
- const textAsides = [];
7862
- const imageNames = [];
7863
- if (s.isStreaming) {
7864
- for (const aside of asides) {
7865
- const details = aside.message.details;
7866
- for (const b of aside.message.content) {
7867
- if (typeof b === "string") {
7868
- if (b.trim())
7869
- textAsides.push(b.trim());
7870
- continue;
7871
- }
7872
- if (!b || typeof b !== "object")
7873
- continue;
7874
- if (b.type === "image" && typeof b.data === "string") {
7875
- if (mainSupportsVision) {
7876
- promptImages.push({
7877
- type: "image",
7878
- data: b.data,
7879
- mimeType: b.mimeType || "image/png",
7880
- });
7881
- if (details?.name) {
7882
- imageNames.push(details.name);
7883
- }
7884
- }
7885
- }
7886
- else if (b.type === "text" &&
7887
- typeof b.text === "string" &&
7888
- b.text.trim()) {
7889
- textAsides.push(b.text.trim());
7890
- if (details?.mode === "bridged" && details?.name) {
7891
- imageNames.push(details.name);
7892
- }
7893
- }
7894
- }
7895
- }
7896
- // 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
7897
- // Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
7898
- // 排队消息无法获取附件,且附件残留泄露到下一次提问。
7899
- // 保证 SDK 内部暂存队列清空,防止历史残留污染。
7900
- if (Array.isArray(s._pendingNextTurnMessages)) {
7901
- s._pendingNextTurnMessages = [];
7902
- }
7903
- }
7904
- else {
7905
- // 空闲提问:必须携带 deliverAs: "nextTurn",将附件(图片、文件引用、视觉证据等)
7906
- // 注入 SDK 的 _pendingNextTurnMessages,并在随后的 s.prompt() 中由 SDK 作为上下文消息
7907
- // 传递给 LLM 并落盘(fixes #667)。严禁在此清空 _pendingNextTurnMessages。
7908
- for (const aside of asides) {
7909
- await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
7910
- }
7911
- if (asides.length > 0) {
7912
- this.flushSnapshot();
7913
- }
8564
+ // 空闲前置:若当前未处于流式运行且上下文超标,提早在注入附件前执行软上限主动压缩(issue #716)。
8565
+ // 必须在任何 nextTurn 注入之前完成,避免耗时压缩期间发生状态变化导致附件残留泄漏(fixes #717)。
8566
+ if (!s.isStreaming) {
8567
+ await this.triggerSoftCapCompactionIfExceeded(conv);
7914
8568
  }
7915
8569
  if (promptAc.signal.aborted) {
7916
8570
  conv.activePromptAc = undefined;
@@ -7937,38 +8591,70 @@ export class ClientSession {
7937
8591
  textEn: `Message delivered to "${conv.title}" — you switched conversations before it landed`,
7938
8592
  });
7939
8593
  }
7940
- if (s.isStreaming) {
7941
- // queue=true (补充 button) → followUp: the message is delivered only
7942
- // after the whole run finishes — the agent finishes what it started,
7943
- // then responds to the queued message. queue=false/undefined
7944
- // (plain Enter) → steer: interrupts the current run — the message
7945
- // is delivered right after the current assistant turn settles
7946
- // (remaining planned tool calls are skipped) and the agent
7947
- // immediately responds to it. This is the pi CLI
7948
- // Enter-during-streaming semantic (docs/usage: Enter queues a
7949
- // steering message); followUp would wait for the whole run
7950
- // to finish, which users perceive as ordinary queueing.
7951
- //
7952
- // 注意:流式期间入队仅进入 SDK 内存队列(尚未落盘为 sessionManager entry),
7953
- // 严禁在此处启动或 await 工作区 Git 影子快照(否则在大型仓库或工具占锁时会把
7954
- // 入队回执与 flushSnapshot 阻塞数秒至 15 秒,造成「按完 Enter 消息消失」)。
7955
- // 排队/插队消息的工作区快照在其真正出队定稿(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);
7956
8607
  const kind = queue ? "followUp" : "steer";
7957
- const fullPromptText = formatStreamingPrompt(text, textAsides, streamingQuotes, imageNames);
8608
+ const fullPromptText = formatStreamingPrompt(text, textAsides, quotes, imageNames);
7958
8609
  if (this.consumeCancelledInFlightQueue(conv, kind, text, fullPromptText)) {
7959
8610
  this.flushSnapshot();
7960
8611
  return;
7961
8612
  }
7962
- if (promptImages.length > 0) {
7963
- conv.queuedImages.set(fullPromptText, promptImages);
7964
- }
7965
- await s.prompt(fullPromptText, {
7966
- streamingBehavior: kind,
8613
+ const entry = createQueuedEntry(fullPromptText, {
7967
8614
  images: promptImages.length > 0 ? promptImages : undefined,
8615
+ attachments: effectiveAttachments,
7968
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();
7969
8641
  }
7970
8642
  else {
7971
- // 空闲提问:启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
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
+ // 启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
7972
8658
  // 绑定由 message_end 异步完成,绝不阻塞 prompt 收尾与气泡上屏)。
7973
8659
  const snapshotPromise = this.startWorkspaceSnapshot(conv);
7974
8660
  try {
@@ -8138,7 +8824,7 @@ export class ClientSession {
8138
8824
  * item still at that position; on any mismatch we fall back to first-occurrence
8139
8825
  * text match (old clients, or the queue shifted between click and handling).
8140
8826
  */
8141
- async removeQueued(kind, text, index) {
8827
+ async removeQueued(kind, text, index, id) {
8142
8828
  const conv = this.conv;
8143
8829
  // Always-defined display mirrors; also the provenance of bubble rendering.
8144
8830
  const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
@@ -8170,6 +8856,20 @@ export class ClientSession {
8170
8856
  if (next.length !== local.length) {
8171
8857
  local.splice(0, local.length, ...next);
8172
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
+ }
8173
8873
  this.flushSnapshot();
8174
8874
  return;
8175
8875
  }
@@ -8187,22 +8887,44 @@ export class ClientSession {
8187
8887
  if (next.length !== local.length) {
8188
8888
  local.splice(0, local.length, ...next);
8189
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
+ }
8190
8904
  this.flushSnapshot();
8191
8905
  return;
8192
8906
  }
8193
- // 气泡 ✕ 对应的是「第几个气泡」(index),不是「哪段文本」:同一文本排队两次时
8194
- // 按文本只会删掉第一条,点第二个气泡却删掉第一个。用 index 定位,位置对不上
8195
- // (队列在点击与执行之间变化)或旧客户端没发 index 时回落到第一处文本匹配。
8196
- const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, targetText, index) : steering;
8197
- 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 = [];
8198
8919
  // Re-queue the survivors in original order. Guard each call so a single
8199
8920
  // failure can't leave the queue half-drained silently.
8200
- for (const t of keptSteering) {
8921
+ for (const entry of keptSteeringEntries) {
8201
8922
  try {
8202
- const imgs = conv.queuedImages?.get(t);
8203
- await s.steer(t, imgs);
8923
+ conv.queuedSteeringEntries.push(entry);
8924
+ await s.steer(entry.text, entry.images);
8204
8925
  }
8205
8926
  catch (err) {
8927
+ conv.queuedSteeringEntries.pop();
8206
8928
  this.emit({
8207
8929
  type: "notice",
8208
8930
  level: "error",
@@ -8211,12 +8933,13 @@ export class ClientSession {
8211
8933
  });
8212
8934
  }
8213
8935
  }
8214
- for (const t of keptFollowUp) {
8936
+ for (const entry of keptFollowUpEntries) {
8215
8937
  try {
8216
- const imgs = conv.queuedImages?.get(t);
8217
- await s.followUp(t, imgs);
8938
+ conv.queuedFollowUpEntries.push(entry);
8939
+ await s.followUp(entry.text, entry.images);
8218
8940
  }
8219
8941
  catch (err) {
8942
+ conv.queuedFollowUpEntries.pop();
8220
8943
  this.emit({
8221
8944
  type: "notice",
8222
8945
  level: "error",
@@ -8225,7 +8948,6 @@ export class ClientSession {
8225
8948
  });
8226
8949
  }
8227
8950
  }
8228
- conv.queuedImages?.delete(targetText);
8229
8951
  if (Array.isArray(s._pendingNextTurnMessages)) {
8230
8952
  s._pendingNextTurnMessages = [];
8231
8953
  }
@@ -8345,7 +9067,14 @@ export class ClientSession {
8345
9067
  }
8346
9068
  /** Interrupt a run: abort, with a force-reset fallback on timeout. */
8347
9069
  async interruptRun(conv, reason) {
8348
- // #487:停下就结算该会话的挂起提问/审批——残留条目让 isWaitingOnUser 恒真
9070
+ // 正在投递的消息前置阶段(附件构建 / 影子快照)立即打断
9071
+ if (conv.activePromptAc) {
9072
+ conv.activePromptAc.abort();
9073
+ conv.activePromptAc = undefined;
9074
+ }
9075
+ // 统一清理在飞的工具看门狗、计时器与进行中参数状态,防止中止后残留或跳出超时鬼影警告
9076
+ this.clearConversationToolStates(conv);
9077
+ // #487:停下就结算该会话的挂起提问/审批/页面调用——残留条目让 isWaitingOnUser 恒真
8349
9078
  // (stall 失联检测被永久豁免),弹窗也会跨轮残留;dispose 语义已范本化。
8350
9079
  this.settlePendingsForConv(conv.id);
8351
9080
  if (!this.conversationStreaming(conv) && conv.session.isIdle) {
@@ -8417,8 +9146,7 @@ export class ClientSession {
8417
9146
  try {
8418
9147
  conv.unsubscribe?.();
8419
9148
  conv.unsubscribe = undefined;
8420
- this.clearAllToolWatchdogs(conv);
8421
- conv.toolStartTimes.clear();
9149
+ this.clearConversationToolStates(conv);
8422
9150
  disposeEvalSession(conv.id);
8423
9151
  await conv.runtime.dispose();
8424
9152
  // #485:dispose 挂起期间会话可能已被强行关闭移出(forceDismiss 走
@@ -8452,7 +9180,7 @@ export class ClientSession {
8452
9180
  }, (m) =>
8453
9181
  // 子代理带模板时按原模板重建(conv.subagentTemplate 是派发时工厂
8454
9182
  // 用的同一快照);普通对话 undefined,行为不变。
8455
- 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)), {
8456
9184
  cwd: sessionBaseDir,
8457
9185
  agentDir: this.agentDir,
8458
9186
  sessionManager: m,
@@ -9111,9 +9839,27 @@ export class ClientSession {
9111
9839
  // ignore
9112
9840
  }
9113
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
+ }
9114
9858
  this.pluginModelKeys?.delete(id);
9115
9859
  this.planManager.unbindConversation(id);
9116
- this.clearAllToolWatchdogs(conv);
9860
+ this.markerSvc.clearConversation(id);
9861
+ this.clearConversationToolStates(conv);
9862
+ this.goalSvc.notifyConversationRemoved(conv);
9117
9863
  // 关对话 → 连它的 eval 内核(Python/Node 子进程 + 临时沙箱目录)一起回收:
9118
9864
  // 这些进程是 detached 进程组,父进程退出不会自动带走它们。
9119
9865
  disposeEvalSession(id);
@@ -9126,6 +9872,9 @@ export class ClientSession {
9126
9872
  rmSync(ephemeralDir, { recursive: true, force: true });
9127
9873
  }
9128
9874
  catch { }
9875
+ if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
9876
+ void this.finalizeSubagentWorktree(conv).catch(() => { });
9877
+ }
9129
9878
  }
9130
9879
  if (conv.isEphemeral) {
9131
9880
  const ephemeralDir = join(this.agentDir, "ephemeral-sessions", conv.id);
@@ -9247,22 +9996,24 @@ export class ClientSession {
9247
9996
  // 永远等不到答复)。只搬归属明确的(conversationId 对得上,与问卷/页调用
9248
9997
  // 同一规则);目标侧按新 id 重发弹窗,等待中的 Promise 原样过户不 resolve。
9249
9998
  const approvals = [];
9250
- for (const [aid, a] of this.pendingApprovals) {
9251
- if (a.conversationId !== undefined && set.has(a.conversationId)) {
9252
- this.pendingApprovals.delete(aid);
9253
- approvals.push({
9254
- resolve: a.resolve,
9255
- toolCallId: a.toolCallId,
9256
- toolName: a.toolName,
9257
- params: a.params,
9258
- reason: a.reason,
9259
- reasonEn: a.reasonEn,
9260
- ...(a.category ? { category: a.category } : {}),
9261
- ...(a.hits ? { hits: a.hits } : {}),
9262
- conversationId: a.conversationId,
9263
- ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
9264
- createdAt: a.createdAt,
9265
- });
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();
9266
10017
  }
9267
10018
  }
9268
10019
  this.emitConversations();
@@ -9385,23 +10136,9 @@ export class ClientSession {
9385
10136
  for (const a of payload.approvals) {
9386
10137
  const nid = `appr-${++this.approvalSeq}`;
9387
10138
  const aConvId = fix(a.conversationId);
9388
- this.pendingApprovals.set(nid, {
9389
- id: nid,
9390
- toolCallId: a.toolCallId,
9391
- toolName: a.toolName,
9392
- params: a.params,
9393
- reason: a.reason,
9394
- reasonEn: a.reasonEn,
9395
- ...(a.category ? { category: a.category } : {}),
9396
- ...(a.hits ? { hits: a.hits } : {}),
9397
- conversationId: aConvId,
9398
- ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
9399
- resolve: a.resolve,
9400
- createdAt: a.createdAt,
9401
- });
9402
- if (aConvId === mainId) {
9403
- this.emit({
9404
- type: "tool_approval_pending",
10139
+ const targetConv = this.convs.get(aConvId);
10140
+ if (targetConv) {
10141
+ this.ensurePendingApprovals(targetConv).set(nid, {
9405
10142
  id: nid,
9406
10143
  toolCallId: a.toolCallId,
9407
10144
  toolName: a.toolName,
@@ -9412,7 +10149,24 @@ export class ClientSession {
9412
10149
  ...(a.hits ? { hits: a.hits } : {}),
9413
10150
  conversationId: aConvId,
9414
10151
  ...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
10152
+ resolve: a.resolve,
10153
+ createdAt: a.createdAt,
9415
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
+ }
9416
10170
  }
9417
10171
  }
9418
10172
  return mainId;
@@ -9624,7 +10378,12 @@ export class ClientSession {
9624
10378
  return pq ? { hasQuestion: true, questionId: pq.id, questionTitle: pq.title } : {};
9625
10379
  })(),
9626
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,
9627
10385
  ...(conv.pinned ? { pinned: true } : {}),
10386
+ ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
9628
10387
  ...(conv.forkFrom ? { forkFrom: conv.forkFrom } : {}),
9629
10388
  });
9630
10389
  }
@@ -9804,18 +10563,44 @@ export class ClientSession {
9804
10563
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
9805
10564
  const run = (async () => {
9806
10565
  try {
9807
- const sessionDir = piSessionsRoot()
9808
- ? resolve(piSessionsRoot())
9809
- : SessionManager.create(sessionBaseDir).getSessionDir();
9810
- if (!existsSync(sessionDir))
9811
- return [];
9812
- const dirEntries = await fsPromises.readdir(sessionDir);
9813
- const files = dirEntries.filter((f) => f.endsWith(".jsonl"));
9814
- 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)
9815
10601
  return [];
9816
10602
  // Stat files to detect modified/new files (takes only ~8ms for 600+ files)
9817
- const stats = await Promise.all(files.map(async (f) => {
9818
- const fp = join(sessionDir, f);
10603
+ const stats = await Promise.all(Array.from(candidateFiles.values()).map(async (fp) => {
9819
10604
  try {
9820
10605
  const st = await fsPromises.stat(fp);
9821
10606
  return { path: fp, mtime: st.mtimeMs, size: st.size };
@@ -9845,18 +10630,46 @@ export class ClientSession {
9845
10630
  const validInfos = results.filter((info) => info !== null);
9846
10631
  const baseDirKey = normalizePathKey(sessionBaseDir);
9847
10632
  const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
9848
- 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);
9849
10644
  candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
9850
10645
  ClientSession.sessionInfosCache.set(cwdKey, { infos: candidates, at: Date.now() });
9851
10646
  return candidates;
9852
10647
  }
9853
10648
  catch {
9854
10649
  try {
9855
- const fallback = await SessionManager.list(sessionBaseDir, piSessionsRoot());
9856
- // 统一口径:列表缓存一律不带转录全文(issue #440),搜索按需另行加载
9857
- const stripped = fallback.map((s) => ({ ...s, allMessagesText: "" }));
9858
- ClientSession.sessionInfosCache.set(cwdKey, { infos: stripped, at: Date.now() });
9859
- 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;
9860
10673
  }
9861
10674
  catch {
9862
10675
  return [];
@@ -10415,8 +11228,8 @@ export class ClientSession {
10415
11228
  this.emit({
10416
11229
  type: "notice",
10417
11230
  level: "warning",
10418
- text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端后再移出`,
10419
- 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`,
10420
11233
  });
10421
11234
  return;
10422
11235
  }
@@ -10984,10 +11797,6 @@ export class ClientSession {
10984
11797
  if (displaced)
10985
11798
  this.removeConversation(displaced.id);
10986
11799
  await this.bindSession();
10987
- // #436:转录回放恢复的 planMode 在 runtime 工厂的 applyToolGating 时还读不到
10988
- //(conv 尚未进 this.convs,planModeOf 落空)——注册后统一补一次门控,让
10989
- // 计划模式的写类/旁路工具剥离对重开的会话同样生效。下同(forkSession/setCwd)。
10990
- this.applyToolGating(conv.session, conv.agentPreset);
10991
11800
  this.cwd = targetCwd;
10992
11801
  this.files.unwatchGit();
10993
11802
  // 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
@@ -11194,9 +12003,6 @@ export class ClientSession {
11194
12003
  await this.bindSession();
11195
12004
  this.invalidateSessionInfos();
11196
12005
  this.scheduleSessionsRefresh();
11197
- // #436:同 switchSession —— 派生出的会话若从转录回放恢复了 planMode,
11198
- // 工厂里的门控当时读不到它,注册后补一次。
11199
- this.applyToolGating(newConv.session, newConv.agentPreset);
11200
12006
  if (prevModel && this.sharedModelRuntime) {
11201
12007
  try {
11202
12008
  const pm = prevModel;
@@ -11276,10 +12082,8 @@ export class ClientSession {
11276
12082
  }
11277
12083
  }
11278
12084
  await targetConv.session.reload();
11279
- // 重新应用设置和门控
11280
- this.applyRetryOverrides();
11281
- this.applyCompactionOverrides();
11282
- this.applyToolGating(targetConv.session, targetConv.agentPreset);
12085
+ // 重新应用设置和门控(统一收口)
12086
+ this.applySessionOverrides(targetConv);
11283
12087
  // 清理该会话的 UI 消息缓存和序列化映射
11284
12088
  targetConv.uiMessageCache.clear();
11285
12089
  targetConv.msgIds.clear();
@@ -11289,7 +12093,8 @@ export class ClientSession {
11289
12093
  targetConv.lastMessagesArray = [];
11290
12094
  targetConv.queueSteering = [];
11291
12095
  targetConv.queueFollowUp = [];
11292
- targetConv.queuedImages = new Map();
12096
+ targetConv.queuedSteeringEntries = [];
12097
+ targetConv.queuedFollowUpEntries = [];
11293
12098
  try {
11294
12099
  targetConv.session.clearQueue?.();
11295
12100
  }
@@ -11443,7 +12248,8 @@ export class ClientSession {
11443
12248
  this.conv.lastMessagesArray = [];
11444
12249
  this.conv.queueSteering = [];
11445
12250
  this.conv.queueFollowUp = [];
11446
- this.conv.queuedImages = new Map();
12251
+ this.conv.queuedSteeringEntries = [];
12252
+ this.conv.queuedFollowUpEntries = [];
11447
12253
  // Restore the previously-selected model on the forked branch.
11448
12254
  if (prevModel && this.sharedModelRuntime) {
11449
12255
  try {
@@ -12311,6 +13117,8 @@ export class ClientSession {
12311
13117
  };
12312
13118
  });
12313
13119
  this.emit({ type: "models", models });
13120
+ // 联网刷新拉回动态本地模型(如 llama.cpp)后,若当前对话尚处于未发消息阶段,尝试自愈恢复记忆模型
13121
+ void this.restoreProjectModelForCwd(this.cwd);
12314
13122
  }
12315
13123
  catch (err) {
12316
13124
  this.emit({
@@ -12553,15 +13361,44 @@ export class ClientSession {
12553
13361
  this.files.unwatchDir();
12554
13362
  this.files.unwatchGit();
12555
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
+ }
12556
13371
  // 关闭所有挂起的用户提问(dispose 时以「取消」解析,避免模型挂死)。
12557
13372
  this.cancelPendingQuestions();
12558
13373
  // 同理关闭挂起的页面调用(以失败解析:对面是扩展,没有答可等)。
12559
13374
  this.cancelPendingPageCalls();
12560
13375
  // 挂起的工具审批一并清掉(以「拒绝」解析,防 Promise/runtime 泄漏)。
12561
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
+ }
12562
13399
  this.bg.stop();
12563
13400
  for (const conv of this.convs.values()) {
12564
- this.clearAllToolWatchdogs(conv);
13401
+ this.clearConversationToolStates(conv);
12565
13402
  // 逐个对话回收 eval 内核;下面的兜底再清一次表(含已 delete 的残留)。
12566
13403
  disposeEvalSession(conv.id);
12567
13404
  conv.unsubscribe?.();