pi-web-ui 0.118.0 → 0.120.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -11,13 +11,16 @@ import { DEFAULT_PI_CAPABILITIES } from "./engine-capabilities.js";
11
11
  import { existsSync, readFileSync, readdirSync, rmSync, mkdirSync, statSync, watch, writeFileSync } from "node:fs";
12
12
  import { homedir } from "node:os";
13
13
  import { basename, delimiter, join, resolve } from "node:path";
14
- import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
14
+ import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, createPowerShellToolDefinition, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
15
15
  import { getSdkBuiltinExtensionFactories, SDK_DISABLED_BUILTIN_EXTENSIONS } from "./sdk-builtin-extensions.js";
16
16
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
17
+ import { JobRegistry, JOB_TASK_PREFIX } from "./job-runner.js";
18
+ import { resolveProjectScripts } from "./project-scripts.js";
17
19
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
18
20
  import { collectInstalledEngineTargets } from "./engine-probe.js";
19
21
  import { captureQuickAskConversation } from "./quick-ask-context.js";
20
22
  import { checkPluginUpdates } from "./plugin-updater.js";
23
+ import { enablePluginAfterInstall } from "./plugin-installer.js";
21
24
  import { getAppVersion, getPkgRoot } from "./pkg-info.js";
22
25
  import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
23
26
  import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundTask, shouldRetainActive, } from "./wait-subscription-scan.js";
@@ -56,6 +59,10 @@ import { extractGroupContextMetrics, groupContextMessage, recordGroupContextMetr
56
59
  import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, readWorkspaceSnapshotsFromSession, appendWorkspaceSnapshotToSession, withWorkspaceSnapshotGate, } from "./workspace-snapshot.js";
57
60
  import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
58
61
  import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
62
+ import { SubagentSettleRegistry } from "./subagent-settle.js";
63
+ import { SubagentSpawnBudget } from "./subagent-budget.js";
64
+ import { collectTranscriptFacts, verifyEvidence } from "./subagent-evidence.js";
65
+ import { buildResumePrompt, disabledSubagentLedger, getSubagentLedger, ledgerBootId, toLedgerEvidence, } from "./subagent-ledger.js";
59
66
  import { createSubagentTask, restartSubagentTask, requestSubagentCompletion, isSubagentTaskPending, } from "./subagent-task.js";
60
67
  import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
61
68
  import { messageDeletionTargets, undeletedContextEntries } from "./message-deletion.js";
@@ -63,13 +70,46 @@ import { fillSkillContents } from "./skill-content-filler.js";
63
70
  import { estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
64
71
  import { makeCommunicateTool } from "./communicate-tool.js";
65
72
  import { conversationIdentity, bindConversationParent, hasConversationParentBinding, conversationParent, parentConversationIdentity, } from "./conversation-identity.js";
73
+ /**
74
+ * 会话文件 header 里的真实 cwd(跨机器 workspace URI 会先还原成本地路径)。
75
+ * 读不到时回落到 fallback —— 不能让一句读盘失败把置顶弄丢。
76
+ */
77
+ export async function sessionOwnerCwd(sessionFile, fallback) {
78
+ try {
79
+ const headerCwd = restoreWorkspaceUriFromSessionDir((await readCwdFromSessionHeader(resolve(sessionFile))) ?? "");
80
+ return headerCwd || fallback;
81
+ }
82
+ catch {
83
+ return fallback;
84
+ }
85
+ }
86
+ /**
87
+ * 过滤掉不属于当前 cwd 的置顶路径。
88
+ * 历史脏数据(在 A 视图下钉了 B 的会话)就靠这一层拦住,不必要求用户手工清理
89
+ * `client-state.json`。归属读不出来的路径保留原行为,宁多勿丢。
90
+ */
91
+ export async function pinnedPathsOwnedBy(paths, cwd) {
92
+ const owner = normalizePathKey(cwd);
93
+ const kept = [];
94
+ for (const path of paths) {
95
+ try {
96
+ const headerCwd = restoreWorkspaceUriFromSessionDir((await readCwdFromSessionHeader(resolve(path))) ?? "");
97
+ if (!headerCwd || normalizePathKey(headerCwd) === owner)
98
+ kept.push(path);
99
+ }
100
+ catch {
101
+ kept.push(path);
102
+ }
103
+ }
104
+ return kept;
105
+ }
66
106
  const communicationAddress = conversationIdentity;
67
- import { conversationCommunication, formatCommunicationMessage, } from "./conversation-communication.js";
107
+ import { answersFromMessage, conversationCommunication, formatCommunicationMessage, } from "./conversation-communication.js";
68
108
  import { requestContextExtension, enableRequestEvidence } from "./request-context.js";
69
109
  import { removeContextEvidence, withContextEvidenceRead, copyContextEvidence, buildContextEvidenceIndex, } from "./context-evidence.js";
70
110
  import { installCompactionInstructions } from "./compaction-instructions.js";
71
111
  import { installEvidenceToolHooks } from "./evidence-tool-hooks.js";
72
- import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, pluginApprovalCategory, } from "./tool-approval.js";
112
+ import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, pluginApprovalCategory, unattendedApprovalTimeoutMs, } from "./tool-approval.js";
73
113
  import { PlanManager } from "./plan-manager.js";
74
114
  import { ApprovalAuditLogger } from "./approval-audit.js";
75
115
  export { ApprovalAuditLogger };
@@ -78,22 +118,24 @@ import { DELEGATE_MODE_BLOCKED_TOOL_NAMES, DELEGATION_SYSTEM_PROMPT, delegateNot
78
118
  import { goalReviewDenial, shouldDeferPromptForReview } from "./goal-review-gate.js";
79
119
  import { readPlanModeFromSession, readPlanFromSession } from "./permission-preset.js";
80
120
  import { readDelegateModeFromSession } from "./permission-preset.js";
81
- import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
82
- import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, CANVAS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
121
+ import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi } from "./terminals.js";
122
+ import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isNeverLazyTool, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, normalizeLazyOnDemandList, partitionLazyTools, CANVAS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
83
123
  import { makeLoadToolsTool } from "./load-tools-tool.js";
84
124
  import { formatCompactSignature } from "./tool-signature.js";
85
125
  import { WebUIContext } from "./webui-context.js";
86
126
  import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, SOFT_CAP_MIN_TOKENS, SOFT_CAP_MIN_HEADROOM, softCapReserveFor, } from "./soft-cap.js";
87
- import { makeEditSoftTool } from "./edit-soft-tool.js";
127
+ import { makeEditToolDefinition } from "./edit-tool.js";
128
+ import { FIND_DESCRIPTION, FIND_PARAMETERS, GREP_DESCRIPTION, GREP_PARAMETERS, LS_DESCRIPTION, LS_PARAMETERS, POWERSHELL_DESCRIPTION, POWERSHELL_PARAMETERS, WRITE_DESCRIPTION, WRITE_PARAMETERS, } from "./tool-prompts.js";
129
+ import { withDefaultBashTimeout } from "./bash-timeout.js";
88
130
  import { makeReadDirTool, withReadDirSupport } from "./read-tool.js";
89
- import { installToolOverrides, syncSubagentOverride, } from "./tool-overrides.js";
131
+ import { installToolOverrides, syncSubagentOverride, withSlimPrompt, } from "./tool-overrides.js";
90
132
  import { resolveSecurityMode, subagentSecurityDenial, subagentAllowedToolVisible, withSubagentSecurityGate, SUBAGENT_WRITE_TOOL_NAMES, } from "./subagent-security-gate.js";
91
133
  import { makePresentFilesTool } from "./present-files-tool.js";
92
134
  import { makeCompactContextTool, buildCompactionInstructions, DEFAULT_KEEP_RECENT_TOKENS, } from "./compact-context-tool.js";
93
135
  import { disposeAllEvalKernels, disposeEvalSession, makeEvalTool } from "./eval-tool.js";
94
136
  import { normalizeToolInfo } from "./tool-info.js";
95
137
  import { applyToolPromptOverrides, effectiveToolPrompt, toolPromptOverrideOf, } from "./tool-prompt-overrides.js";
96
- import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
138
+ import { collectSubagentDescendantIds, isSubagentTerminal, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
97
139
  import { makeDelegateTaskTool } from "./delegate-task.js";
98
140
  import { mergeConversationTools } from "./conversation-tool.js";
99
141
  import { makeConversationReadTool, toTranscriptInput, } from "./conversation-read-tool.js";
@@ -145,6 +187,12 @@ const STALL_NOTIFY_MS = (() => {
145
187
  const v = Number(process.env.PI_WEB_STALL_NOTIFY_MS);
146
188
  return Number.isFinite(v) && v >= 0 ? v : 180_000;
147
189
  })();
190
+ /**
191
+ * 无人值守会话(伪客户端:plugin:/scheduler:/canvas:)的审批等待上限与工具审批判定。
192
+ * 超时按「拒绝」处理 —— 无人可点时绝不自作主张放行,但也绝不无限期挂住整个 run。
193
+ *
194
+ * 判定与取值见 `unattendedApprovalTimeoutMs`(server/tool-approval.ts)。
195
+ */
148
196
  export const OFFLINE_ROW_TTL_MS = (() => {
149
197
  const raw = String(process.env.PI_WEB_OFFLINE_ROWS_TTL_MS ?? "")
150
198
  .trim()
@@ -167,19 +215,24 @@ import { splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-
167
215
  export { splitAgentStartPrompt };
168
216
  import { makeKillableBashTool, makeAdaptiveBashTool } from "./bash-tool.js";
169
217
  export { makeKillableBashTool, makeAdaptiveBashTool };
170
- import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, } from "./tool-guards.js";
171
- export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, };
218
+ import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, wrapEditToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, } from "./tool-guards.js";
219
+ export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, wrapEditToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, };
172
220
  import { normalizeSolPlanToPlanSteps, makePlanUpdateTool } from "./plan-update-tool.js";
173
221
  export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
174
222
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
175
223
  import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
224
+ import { makeBrowserScriptTool } from "./browser-script-tool.js";
225
+ import { normalizePhoneCallTimeoutMs, collectPhoneArgs, formatPhoneCallResult, formatPhoneError, makePhoneTool, } from "./phone-tool.js";
226
+ export { makeBrowserScriptTool };
176
227
  export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
177
228
  import { RUN_TASK_CAP, RUN_ARGS_CAP, getMaxOpenConversations, getMaxSubagents, DEFAULT_CONV_TITLE, truncRun, previewToolResult, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
178
229
  export { workspacePath };
179
230
  import { mapSessionsConcurrent } from "./session-scan.js";
231
+ import { SessionListDiskIndex } from "./session-list-index.js";
180
232
  import { searchSessions as searchSessionTranscripts, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
181
233
  export { piSessionsRoot, isInsideSessionsDir };
182
- import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, } from "./session-parser.js";
234
+ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, parentSessionOfManager, } from "./session-parser.js";
235
+ import { conversationRowKind } from "./conversation-rows.js";
183
236
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
184
237
  export { pickAdoptableOrphan, sameCwd };
185
238
  const consultWaitingParents = new WeakSet();
@@ -249,6 +302,118 @@ export class ClientSession {
249
302
  pluginModelKeys = new Map();
250
303
  sharedModelRuntime;
251
304
  turnEndWaiters = new Map();
305
+ subagentSettleStore;
306
+ subagentSpawnBudgetStore;
307
+ /**
308
+ * 子代理结算边沿:回合结束 / 停止 / 移出 / 问卷变化 都从这里唤醒等待方。
309
+ * 做成原型访问器 + 懒建,测试里的 fake ClientSession(Object.create(prototype))也能拿到自己的注册表。
310
+ */
311
+ get subagentSettle() {
312
+ return (this.subagentSettleStore ??= new SubagentSettleRegistry());
313
+ }
314
+ /** 每棵运行树的累计派发预算(并发与深度之外的第三道闸)。 */
315
+ get subagentSpawnBudget() {
316
+ return (this.subagentSpawnBudgetStore ??= new SubagentSpawnBudget());
317
+ }
318
+ subagentLedgerStore;
319
+ /** 运行账本:dataDir 级单例,同一进程的多个 ClientSession 共用。 */
320
+ get subagentLedger() {
321
+ if (!this.subagentLedgerStore) {
322
+ const dataDir = this.stateStore?.dataDir;
323
+ this.subagentLedgerStore = dataDir ? getSubagentLedger(dataDir) : disabledSubagentLedger();
324
+ }
325
+ return this.subagentLedgerStore;
326
+ }
327
+ /** 派发时登记一条 running;进程死在这里,重启后它就是「被中断的运行」。 */
328
+ recordSubagentRunStart(conv, info) {
329
+ const ledger = this.subagentLedger;
330
+ if (!ledger.enabled)
331
+ return;
332
+ const runId = conversationIdentity(conv);
333
+ const parent = this.parentExecution(conv)?.conv;
334
+ let sessionFile;
335
+ try {
336
+ sessionFile = conv.session.sessionFile ?? undefined;
337
+ }
338
+ catch {
339
+ sessionFile = undefined;
340
+ }
341
+ let model;
342
+ try {
343
+ const m = conv.session.model;
344
+ model = m ? `${m.provider}/${m.id}` : undefined;
345
+ }
346
+ catch {
347
+ model = undefined;
348
+ }
349
+ const worktree = conv.subagentWorktree;
350
+ ledger.upsert({
351
+ runId,
352
+ parentRunId: parent ? conversationIdentity(parent) : undefined,
353
+ parentSessionFile: parent ? this.sessionFileOfConversation(parent) : undefined,
354
+ cwd: conv.cwd,
355
+ type: conv.subagentType ?? "general",
356
+ title: conv.title,
357
+ template: info.template,
358
+ model,
359
+ thinking: conv.subagentThinking,
360
+ prompt: info.prompt,
361
+ state: "running",
362
+ bootId: ledgerBootId(),
363
+ createdAt: Date.now(),
364
+ updatedAt: Date.now(),
365
+ sessionFile,
366
+ persisted: info.persist,
367
+ worktree: worktree ? { path: worktree.worktreePath, branch: worktree.branch } : undefined,
368
+ });
369
+ ledger.event(runId, "spawned", { type: conv.subagentType ?? "general", persist: info.persist });
370
+ }
371
+ sessionFileOfConversation(conv) {
372
+ try {
373
+ return conv.session.sessionFile ?? undefined;
374
+ }
375
+ catch {
376
+ return undefined;
377
+ }
378
+ }
379
+ /** 把当前运行态同步进账本;没登记过的对话(普通对话)直接跳过。 */
380
+ syncSubagentLedger(conv, opts = {}) {
381
+ const ledger = this.subagentLedger;
382
+ if (!ledger.enabled)
383
+ return;
384
+ const runId = conversationIdentity(conv);
385
+ const previous = ledger.read(runId);
386
+ if (!previous)
387
+ return;
388
+ const outcome = subagentRunOutcome(conv);
389
+ const state = opts.state ?? (outcome.error ? "failed" : outcome.canceled ? "canceled" : "running");
390
+ let outputTail;
391
+ try {
392
+ outputTail = conv.session.getLastAssistantText() ?? undefined;
393
+ }
394
+ catch {
395
+ outputTail = undefined;
396
+ }
397
+ const worktree = conv.subagentWorktree;
398
+ ledger.upsert({
399
+ ...previous,
400
+ runId,
401
+ cwd: conv.cwd,
402
+ type: conv.subagentType ?? previous.type,
403
+ title: conv.title || previous.title,
404
+ state,
405
+ updatedAt: Date.now(),
406
+ finishedAt: state === "running" ? previous.finishedAt : Date.now(),
407
+ error: outcome.error ?? previous.error,
408
+ outputTail: outputTail ?? previous.outputTail,
409
+ evidence: toLedgerEvidence(conv.subagentEvidence) ?? previous.evidence,
410
+ worktree: worktree
411
+ ? { path: worktree.worktreePath, branch: worktree.branch, cleanedUp: Boolean(worktree.cleanedUp) }
412
+ : previous.worktree,
413
+ });
414
+ if (opts.event)
415
+ ledger.event(runId, opts.event);
416
+ }
252
417
  pendingSubagentNotices = new Map();
253
418
  deliveringSubagentNotices = new Map();
254
419
  pendingCliManagers = new Set();
@@ -269,11 +434,27 @@ export class ClientSession {
269
434
  getLang: () => this.getLang(),
270
435
  getUploadMaxBytes: () => (this.settingsSvc.current.workspaceUploadMaxMb ?? 100) * 1024 * 1024,
271
436
  });
437
+ jobs = new JobRegistry({
438
+ logDir: () => join(this.stateStore?.dataDir ?? resolve(process.env.PI_WEB_DATA_DIR ?? join(homedir(), ".pi-web")), "jobs"),
439
+ onChange: () => this.bg.push(),
440
+ onExit: (job) => this.notifyBackgroundJobDone(job),
441
+ });
272
442
  bg = new BgServerTracker({
273
443
  emit: (msg) => this.emit(msg),
274
444
  flushSnapshot: () => this.flushSnapshot(),
275
445
  isDisposed: () => this.disposed,
276
446
  pluginTasks: () => this.pluginBgTasksProvider?.() ?? [],
447
+ jobs: () => this.jobs.list().map((job) => ({
448
+ taskId: `${JOB_TASK_PREFIX}${job.id}`,
449
+ pid: job.pid,
450
+ since: job.since,
451
+ name: job.label,
452
+ command: job.command,
453
+ status: "running",
454
+ ...(job.origin ? { origin: job.origin } : {}),
455
+ logPath: job.logPath,
456
+ })),
457
+ killAllJobs: () => this.jobs.killAll(),
277
458
  cleanupMinutes: () => this.settingsSvc.current.bgAutoCleanupMin ?? 0,
278
459
  workspaceCwd: () => this.convs.get(this.activeId)?.cwd ?? this.cwd,
279
460
  });
@@ -627,6 +808,55 @@ export class ClientSession {
627
808
  .catch(() => { });
628
809
  }
629
810
  }
811
+ notifyBackgroundJobDone(job) {
812
+ if (this.disposed)
813
+ return;
814
+ const conv = job.origin ? this.convs.get(job.origin) : undefined;
815
+ const reasonText = job.reason === "timeout"
816
+ ? "超时被强杀"
817
+ : job.reason === "idle"
818
+ ? "静默卡死被强杀"
819
+ : job.reason === "killed"
820
+ ? "被手动停止"
821
+ : job.reason === "spawn-error"
822
+ ? "启动失败"
823
+ : "正常退出";
824
+ const reasonEn = job.reason === "timeout"
825
+ ? "killed on hard timeout"
826
+ : job.reason === "idle"
827
+ ? "killed as idle"
828
+ : job.reason === "killed"
829
+ ? "stopped manually"
830
+ : job.reason === "spawn-error"
831
+ ? "failed to start"
832
+ : "exited";
833
+ const cmdShort = job.command.length > 120 ? `${job.command.slice(0, 120)}…` : job.command;
834
+ const tail = (job.tail ?? "").trim() || "(无输出)";
835
+ // 先发一条可见 notice(面板/提示区),再在有归属对话时补一条系统消息。
836
+ this.emit({
837
+ type: "notice",
838
+ level: job.exitCode === 0 || job.reason === "killed" ? "info" : "warning",
839
+ text: `后台任务 ${job.id} 已结束(${reasonText},退出码 ${job.exitCode ?? "null"}):${cmdShort}`,
840
+ textEn: `Background job ${job.id} ended (${reasonEn}, exit ${job.exitCode ?? "null"}): ${cmdShort}`,
841
+ });
842
+ if (!conv)
843
+ return;
844
+ const text = `(系统:你之前用 background=true 起的后台任务 ${job.id} 已结束(${reasonText},退出码 ${job.exitCode ?? "null"}):${cmdShort}\n` +
845
+ `日志:${job.logPath}\n最后输出:\n${tail})`;
846
+ const session = conv.runtime.session;
847
+ if (session.isStreaming) {
848
+ void session.sendUserMessage(text).catch(() => { });
849
+ }
850
+ else {
851
+ void session
852
+ .sendCustomMessage({
853
+ customType: "background-job-done",
854
+ content: [{ type: "text", text }],
855
+ display: true,
856
+ }, { deliverAs: "nextTurn" })
857
+ .catch(() => { });
858
+ }
859
+ }
630
860
  spawningSubagents = 0;
631
861
  creatingConversations = new Map();
632
862
  reserveConversationSlot(cwd) {
@@ -687,7 +917,7 @@ export class ClientSession {
687
917
  const maxSubagents = getMaxSubagents();
688
918
  const liveSubagents = countActiveSubagents(this.convs.values(), this.spawningSubagents);
689
919
  if (liveSubagents >= maxSubagents) {
690
- throw new Error(pick(this.getLang(), `同时运行的子代理数量已达上限(${maxSubagents} 个),请先用 subagent(action="wait_all") 等一部分完成、或用 subagent(action="stop") 停掉不需要的再派发`, `Active subagent limit reached (${maxSubagents} live). Wait for some with subagent(action="wait_all") or stop unneeded ones with subagent(action="stop") before spawning more`, "agent.subagent.limit.reached", { limit: maxSubagents }));
920
+ throw new Error(pick(this.getLang(), `同时运行的子代理数量已达上限(${maxSubagents} 个),请先用 conversation(action="wait_all") 等一部分完成、或用 conversation(action="stop") 停掉不需要的再派发`, `Active subagent limit reached (${maxSubagents} live). Wait for some with conversation(action="wait_all") or stop unneeded ones with conversation(action="stop") before spawning more`, "agent.subagent.limit.reached", { limit: maxSubagents }));
691
921
  }
692
922
  }
693
923
  const quotaBase = parentId ? (this.convs.get(parentId)?.cwd ?? this.cwd) : this.cwd;
@@ -697,6 +927,15 @@ export class ClientSession {
697
927
  if (isEphemeralSubagent) {
698
928
  this.spawningSubagents++;
699
929
  }
930
+ // 运行树累计预算:并发与深度之外再压一道,扇出→收口→再扇出也不会无限烧钱。
931
+ const budgetRoot = this.subagentRootId(parentId);
932
+ const budgetReservation = this.subagentSpawnBudget.reserve(budgetRoot);
933
+ if (!budgetReservation.ok) {
934
+ releaseSlot?.();
935
+ if (isEphemeralSubagent)
936
+ this.spawningSubagents = Math.max(0, this.spawningSubagents - 1);
937
+ throw new Error(pick(this.getLang(), `本次运行树累计已派发 ${budgetReservation.count} 个子代理(上限 ${budgetReservation.limit}),已拒绝继续派发。先收口已有结果;确实需要更多就把 PI_WEB_SUBAGENT_MAX_SPAWNS_PER_RUN 调大,或在新的顶层对话里开一批。`, `This run tree already spawned ${budgetReservation.count} subagents (limit ${budgetReservation.limit}); further spawns are refused. Collect the results you have; raise PI_WEB_SUBAGENT_MAX_SPAWNS_PER_RUN or start a new top-level conversation for another batch.`, "agent.subagent.budget.reached", { count: budgetReservation.count, limit: budgetReservation.limit }));
938
+ }
700
939
  let handedOffToConv = false;
701
940
  let pendingRuntime;
702
941
  let pendingTerminals;
@@ -888,6 +1127,7 @@ export class ClientSession {
888
1127
  };
889
1128
  signal?.addEventListener("abort", onSpawnAbort, { once: true });
890
1129
  holder.assertSubagentWorktreeAdmission(conv);
1130
+ this.recordSubagentRunStart(conv, { prompt, template: apply?.name, persist: Boolean(persist) });
891
1131
  conv.kickoff = runtime.session
892
1132
  .sendUserMessage(prompt)
893
1133
  .catch((err) => {
@@ -916,6 +1156,9 @@ export class ClientSession {
916
1156
  return conv.id;
917
1157
  }
918
1158
  catch (error) {
1159
+ this.subagentSpawnBudget.refund(budgetRoot);
1160
+ if (registered)
1161
+ this.syncSubagentLedger(registered, { state: "failed", event: "spawn_failed" });
919
1162
  if (registered) {
920
1163
  const home = pendingRuntime && this.findConversationHome?.(pendingRuntime.session);
921
1164
  const holder = home?.session ?? this;
@@ -1039,6 +1282,25 @@ export class ClientSession {
1039
1282
  const max = this.settingsSvc.current.subagentMaxDepth ?? 0;
1040
1283
  return max > 0 && this.subagentDepthUnder(parentId) >= max;
1041
1284
  }
1285
+ /**
1286
+ * 运行树根:沿对话对象上的父子绑定走到最顶层会话;用作累计派发预算的记账键。
1287
+ * 刻意不投影快照(CLI / 临时对话没有 session,投影会抛)。
1288
+ */
1289
+ subagentRootId(parentId) {
1290
+ if (!parentId)
1291
+ return this.activeId || "session";
1292
+ let conv = this.convs.get(parentId);
1293
+ const seen = new Set();
1294
+ while (conv && !seen.has(conv.id)) {
1295
+ seen.add(conv.id);
1296
+ const parent = conversationParent(conv) ??
1297
+ (conv.parentId ? this.convs.get(conv.parentId) : undefined);
1298
+ if (!parent)
1299
+ return conversationIdentity(conv);
1300
+ conv = parent;
1301
+ }
1302
+ return parentId;
1303
+ }
1042
1304
  subagentOwnerOf(convId) {
1043
1305
  return convId ? (this.resolveExecution(convId)?.session ?? this) : this;
1044
1306
  }
@@ -1081,6 +1343,75 @@ export class ClientSession {
1081
1343
  }
1082
1344
  return false;
1083
1345
  }
1346
+ /**
1347
+ * 续跑一条账本运行:进程内子代理会话不落盘,接不上原转录,所以这是「带已知进度重派」。
1348
+ * 工作树若仍保留,就直接在旧工作树里跑(不新建),未提交的改动不丢。
1349
+ */
1350
+ async resumeSubagentRun(selfId, runId, message) {
1351
+ const ledger = this.subagentLedger;
1352
+ await ledger.ready();
1353
+ const record = ledger.read(runId);
1354
+ if (!record)
1355
+ return { ok: false, error: "not_found" };
1356
+ const live = this.subagentSnapshotAnywhere(runId);
1357
+ if (live && !isSubagentTerminal(live))
1358
+ return { ok: false, error: "running", runId };
1359
+ if (record.resumedBy)
1360
+ return { ok: false, error: "already_resumed", runId: record.resumedBy };
1361
+ const parentId = this.subagentCurrentId(selfId);
1362
+ if (!this.convs.get(parentId))
1363
+ return { ok: false, error: "parent_missing" };
1364
+ const recordedTemplate = record.template ? this.subagentTemplates.get(record.template) : undefined;
1365
+ // 模板可能被删/停用:续跑不假装还带着原角色,明确降级并告知子代理。
1366
+ const template = recordedTemplate && recordedTemplate.enabled !== false ? recordedTemplate : undefined;
1367
+ const templateNote = record.template && !template
1368
+ ? `\n\nNote: the original role template "${record.template}" is gone or disabled; you run with the default role.`
1369
+ : "";
1370
+ const cwd = record.worktree && !record.worktree.cleanedUp ? record.worktree.path : record.cwd;
1371
+ const title = pick(this.getLang(), `续跑:${record.title}`, `Resumed: ${record.title}`, "agent.subagent.resume.title", { title: record.title });
1372
+ const convId = await this.spawnSubagentConversation(`${buildResumePrompt(record, message)}${templateNote}`, record.type, cwd, template, record.model ?? undefined, parentId, record.persisted, title, record.thinking, true, "none");
1373
+ const conv = this.convs.get(convId);
1374
+ const executionId = conv ? conversationIdentity(conv) : undefined;
1375
+ const newRunId = executionId ?? convId;
1376
+ const fresh = ledger.read(newRunId);
1377
+ if (fresh)
1378
+ ledger.upsert({ ...fresh, resumedFrom: runId, updatedAt: Date.now() });
1379
+ ledger.markResumed(runId, newRunId);
1380
+ return {
1381
+ ok: true,
1382
+ runId,
1383
+ convId,
1384
+ executionId,
1385
+ mode: "relaunch",
1386
+ previousState: record.state,
1387
+ sessionFile: record.sessionFile,
1388
+ };
1389
+ }
1390
+ /** 启动对账:把上一次进程留下的 running 标成 interrupted,并提示可以续跑。 */
1391
+ async recoverSubagentRuns() {
1392
+ const ledger = this.subagentLedger;
1393
+ if (!ledger.enabled)
1394
+ return;
1395
+ const recovered = await ledger.recover();
1396
+ if (recovered.length === 0)
1397
+ return;
1398
+ const shown = recovered
1399
+ .slice(0, 5)
1400
+ .map((record) => `${record.title || record.type}(${record.runId.slice(0, 8)})`)
1401
+ .join("、");
1402
+ const more = recovered.length > 5 ? ` 等 ${recovered.length} 个` : "";
1403
+ const notice = {
1404
+ type: "notice",
1405
+ level: "warning",
1406
+ text: `上次服务重启中断了 ${recovered.length} 个子代理运行:${shown}${more}。用 conversation(action="resume", runId="…") 带已知进度续跑,或 get_result 取已产出的证据。`,
1407
+ textEn: `${recovered.length} subagent run(s) were interrupted by the last restart: ${shown}${more}. Use conversation(action="resume", runId="…") to relaunch with the recorded progress, or get_result for the evidence already produced.`,
1408
+ };
1409
+ // 对账是异步的:已有客户端就直发,否则排队到下次 attach(别只塞 pendingNotices 等下一次连接)。
1410
+ if (this.sinks?.size === 0)
1411
+ this.pendingNotices.push(notice);
1412
+ else
1413
+ this.emit(notice);
1414
+ }
1084
1415
  async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal) {
1085
1416
  const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
1086
1417
  if (templateName && (!tpl || !tpl.enabled)) {
@@ -1134,6 +1465,7 @@ export class ClientSession {
1134
1465
  conv.subagentWorktreePromise = undefined;
1135
1466
  }
1136
1467
  })();
1468
+ void conv.subagentWorktreePromise.finally(() => this.syncSubagentLedger(conv, { event: "worktree_finalized" }));
1137
1469
  return conv.subagentWorktreePromise;
1138
1470
  }
1139
1471
  async stopSubagentTask(convId) {
@@ -1148,6 +1480,8 @@ export class ClientSession {
1148
1480
  await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1149
1481
  }
1150
1482
  const currentOwner = this.resolveExecution(conversationIdentity(conv))?.session;
1483
+ this.syncSubagentLedger(conv, { state: "canceled", event: "stopped" });
1484
+ this.subagentSettle.notify(conv.id);
1151
1485
  if (!currentOwner)
1152
1486
  return;
1153
1487
  currentOwner.scheduleSubagentCompletionNotice(conv);
@@ -1196,11 +1530,11 @@ export class ClientSession {
1196
1530
  const session = conv.session;
1197
1531
  if (session.isStreaming) {
1198
1532
  await session.sendUserMessage(message, { deliverAs: "steer" });
1199
- return;
1533
+ return { state: "delivered" };
1200
1534
  }
1201
1535
  if (conv.promptInFlight || !session.isIdle) {
1202
1536
  await session.steer(message);
1203
- return;
1537
+ return { state: "queued" };
1204
1538
  }
1205
1539
  const generation = (conv.subagentRunGeneration ?? 0) + 1;
1206
1540
  conv.subagentRunGeneration = generation;
@@ -1211,6 +1545,7 @@ export class ClientSession {
1211
1545
  conv.subagentConsumedByParent = false;
1212
1546
  conv.subagentError = undefined;
1213
1547
  conv.subagentErrorNotified = undefined;
1548
+ this.syncSubagentLedger(conv, { state: "running", event: "steer_restart" });
1214
1549
  const parentKey = this.parentExecutionKey(conv);
1215
1550
  if (parentKey) {
1216
1551
  const pending = this.pendingSubagentNotices.get(parentKey);
@@ -1257,6 +1592,7 @@ export class ClientSession {
1257
1592
  }
1258
1593
  })();
1259
1594
  this.emitConversations();
1595
+ return { state: "restarted" };
1260
1596
  }
1261
1597
  scheduleSubagentCompletionNotice(conv) {
1262
1598
  const parentId = this.parentExecutionKey ? this.parentExecutionKey(conv) : conv.parentId;
@@ -1285,6 +1621,7 @@ export class ClientSession {
1285
1621
  owner.emitConversations();
1286
1622
  if (owner.activeId === (this.subagentCurrentId?.(parentId) ?? parentId))
1287
1623
  owner.flushSnapshot();
1624
+ owner.subagentSettle.notifyAll();
1288
1625
  }
1289
1626
  drainSuspendedSubagents(conv) {
1290
1627
  if (!conv.suspendedSubagents || conv.suspendedSubagents.size === 0)
@@ -1557,6 +1894,8 @@ export class ClientSession {
1557
1894
  catch { }
1558
1895
  }
1559
1896
  notifyTurnEnd(conv) {
1897
+ this.subagentSettle.notify(conv.id);
1898
+ this.syncSubagentLedger(conv, { event: "turn_end" });
1560
1899
  if (conv.session.isIdle && !conv.retryState)
1561
1900
  this.releaseConversationClaims(conv);
1562
1901
  const set = this.turnEndWaiters.get(conv.id);
@@ -1625,6 +1964,10 @@ export class ClientSession {
1625
1964
  lazyLoadingOn() {
1626
1965
  return this.settingsSvc?.current.toolLazyLoading === true;
1627
1966
  }
1967
+ /** 按需加载实际生效?开关开 + 名单非空。名单为空 = 无工具可加载,等同关闭(不挂 load_tools、不出目录段)。 */
1968
+ lazyEffectiveOn() {
1969
+ return this.lazyLoadingOn() && this.lazyOnDemandSet().size > 0;
1970
+ }
1628
1971
  sessionHasTranscript(session) {
1629
1972
  try {
1630
1973
  return (session.state?.messages?.length ?? 0) > 0;
@@ -1633,17 +1976,30 @@ export class ClientSession {
1633
1976
  return false;
1634
1977
  }
1635
1978
  }
1979
+ lazyOnDemandSet() {
1980
+ try {
1981
+ return new Set(normalizeLazyOnDemandList(this.settingsSvc.current.toolOnDemandTools));
1982
+ }
1983
+ catch {
1984
+ return new Set();
1985
+ }
1986
+ }
1636
1987
  lazyLoadedFor(session, seedFromActive) {
1637
1988
  const existing = this.lazyLoadedBySession.get(session);
1638
1989
  if (existing)
1639
1990
  return existing;
1640
1991
  const seed = [];
1641
1992
  if (seedFromActive) {
1642
- const core = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
1993
+ const onDemand = this.lazyOnDemandSet();
1643
1994
  try {
1644
- for (const n of session.getActiveToolNames())
1645
- if (!core.has(n))
1646
- seed.push(n);
1995
+ for (const n of session.getActiveToolNames()) {
1996
+ if (isNeverLazyTool(n))
1997
+ continue;
1998
+ // 名单制:只记住名单里的已加载,名单外常驻无需记忆。
1999
+ if (onDemand.size > 0 && !onDemand.has(n))
2000
+ continue;
2001
+ seed.push(n);
2002
+ }
1647
2003
  }
1648
2004
  catch { }
1649
2005
  }
@@ -1656,13 +2012,15 @@ export class ClientSession {
1656
2012
  if (!session || !this.lazyLoadingOn())
1657
2013
  return empty;
1658
2014
  try {
1659
- const all = this.allowedToolNames(session, conv);
2015
+ const { pending } = this.lazyPartition(session, conv);
2016
+ if (pending.length === 0)
2017
+ return empty;
1660
2018
  const active = new Set(session.getActiveToolNames());
1661
2019
  const names = [];
1662
2020
  const snippets = {};
1663
2021
  const infos = [];
1664
- for (const name of all) {
1665
- if (active.has(name) || name === LOAD_TOOLS_TOOL_NAME)
2022
+ for (const name of pending) {
2023
+ if (active.has(name) || isNeverLazyTool(name))
1666
2024
  continue;
1667
2025
  const def = session.getToolDefinition(name);
1668
2026
  const snippet = this.toolSnippetOf(def);
@@ -1691,7 +2049,14 @@ export class ClientSession {
1691
2049
  t.namespace.name.startsWith("mcp__") &&
1692
2050
  (t.exposure ?? "codemode") === "deferred")
1693
2051
  .map((t) => t.name));
1694
- const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME && !mcpDeferred.has(n));
2052
+ const { pending, loadedLazy } = this.lazyPartition(session, conv);
2053
+ if (pending.length === 0 && loadedLazy.length === 0) {
2054
+ // 名单为空:没有可加载的工具,目录段整段不输出(常驻工具的 schema 已全量下发)。
2055
+ return empty;
2056
+ }
2057
+ // 目录 = 按需名单(不过滤已加载,保证加载前后 system 逐字节相同);核心/常驻不重复列。
2058
+ const stableSet = new Set([...pending, ...loadedLazy]);
2059
+ const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME && !mcpDeferred.has(n) && stableSet.has(n));
1695
2060
  const snippets = {};
1696
2061
  const signatures = {};
1697
2062
  for (const name of names) {
@@ -1711,10 +2076,8 @@ export class ClientSession {
1711
2076
  return empty;
1712
2077
  }
1713
2078
  }
1714
- allowedToolNames(session, conv) {
1715
- const all = session.getAllTools().map((t) => t.name);
1716
- const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1717
- const allowed = new Set(filterToolsByPreset(all, preset));
2079
+ /** 禁用集单源:内置禁用 + 计划/委派/子代理闸门。插件硬禁用在注册层过滤,不在此处。 */
2080
+ disabledToolSet(session, conv, all) {
1718
2081
  const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
1719
2082
  if (conv?.planMode === true)
1720
2083
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
@@ -1730,8 +2093,24 @@ export class ClientSession {
1730
2093
  disabled.add(toolName);
1731
2094
  }
1732
2095
  }
2096
+ return disabled;
2097
+ }
2098
+ allowedToolNames(session, conv) {
2099
+ const all = session.getAllTools().map((t) => t.name);
2100
+ const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2101
+ const allowed = new Set(filterToolsByPreset(all, preset));
2102
+ const disabled = this.disabledToolSet(session, conv, all);
1733
2103
  return all.filter((n) => allowed.has(n) && !disabled.has(n));
1734
2104
  }
2105
+ /** 延迟上下文单源:allowed + onDemand + loaded 一次算出 resident/pending,供目录/门控/加载共用。 */
2106
+ lazyPartition(session, conv) {
2107
+ const all = session.getAllTools().map((t) => t.name);
2108
+ const allowed = this.allowedToolNames(session, conv);
2109
+ const onDemand = this.lazyOnDemandSet();
2110
+ const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
2111
+ const part = partitionLazyTools({ all, allowed, onDemand, loaded });
2112
+ return { all, allowed, onDemand, loaded, ...part };
2113
+ }
1735
2114
  toolSnippetOf(def) {
1736
2115
  if (!def)
1737
2116
  return "";
@@ -1749,6 +2128,15 @@ export class ClientSession {
1749
2128
  const base = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
1750
2129
  return all.filter((n) => base.has(n));
1751
2130
  }
2131
+ lazyResidentNames(session, conv) {
2132
+ try {
2133
+ // 单源划分:常驻 = 允许 - 可延迟名单(含插件),与门控/目录同一口径。
2134
+ return this.lazyPartition(session, conv).resident;
2135
+ }
2136
+ catch {
2137
+ return this.lazyBaselineNames(session);
2138
+ }
2139
+ }
1752
2140
  loadToolsHost(ownerId) {
1753
2141
  return {
1754
2142
  listLoadable: () => this.lazyToolCatalog(this.sessionOfOwner(ownerId), this.convOfOwner(ownerId)).infos,
@@ -1809,23 +2197,12 @@ export class ClientSession {
1809
2197
  };
1810
2198
  }
1811
2199
  const known = new Set(all);
2200
+ // 与 allowedToolNames 同一口径:预设 + 禁用集单源,避免两处手写分歧。
2201
+ // 插件硬禁用在注册层已过滤(不在 known 里),此处按未知处理,提示模型看目录。
1812
2202
  const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1813
- const allowed = new Set(filterToolsByPreset(all, preset));
1814
- const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
1815
- if (conv?.planMode === true)
1816
- for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
1817
- disabled.add(n);
1818
- if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
1819
- for (const t of all) {
1820
- if (!conv.subagentAllowedTools.has(t))
1821
- disabled.add(t);
1822
- }
1823
- }
1824
- if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
1825
- for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
1826
- disabled.add(toolName);
1827
- }
1828
- }
2203
+ const presetAllowed = new Set(filterToolsByPreset(all, preset));
2204
+ const disabled = this.disabledToolSet(session, conv, all);
2205
+ const allowed = new Set(all.filter((n) => presetAllowed.has(n) && !disabled.has(n)));
1829
2206
  const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1830
2207
  let activeNow = new Set();
1831
2208
  try {
@@ -1841,7 +2218,7 @@ export class ClientSession {
1841
2218
  });
1842
2219
  continue;
1843
2220
  }
1844
- if (name === LOAD_TOOLS_TOOL_NAME || LAZY_CORE_TOOL_NAMES.includes(name)) {
2221
+ if (isNeverLazyTool(name)) {
1845
2222
  rejected.push({
1846
2223
  name,
1847
2224
  reason: pick(lang, "常驻核心工具,无需加载", "always available without loading", "loadtools.always"),
@@ -1852,6 +2229,14 @@ export class ClientSession {
1852
2229
  rejected.push({ name, reason: pick(lang, "已经加载过了", "already loaded", "loadtools.already") });
1853
2230
  continue;
1854
2231
  }
2232
+ // 名单制:不在名单里的常驻可用,无需加载。
2233
+ if (!this.lazyOnDemandSet().has(name)) {
2234
+ rejected.push({
2235
+ name,
2236
+ reason: pick(lang, "常驻工具,无需加载(不在按需名单里,直接调用即可)", "always available without loading (not in the on-demand list, call it directly)", "loadtools.always"),
2237
+ });
2238
+ continue;
2239
+ }
1855
2240
  if (disabled.has(name)) {
1856
2241
  rejected.push({
1857
2242
  name,
@@ -1897,12 +2282,12 @@ export class ClientSession {
1897
2282
  }
1898
2283
  }
1899
2284
  autoActivateToolIfLoadable(session, conv, name) {
1900
- if (!this.lazyLoadingOn() ||
1901
- !name ||
1902
- name === LOAD_TOOLS_TOOL_NAME ||
1903
- LAZY_CORE_TOOL_NAMES.includes(name)) {
2285
+ if (!this.lazyLoadingOn() || !name || isNeverLazyTool(name)) {
1904
2286
  return;
1905
2287
  }
2288
+ // 名单制:只有名单里的才会被 JIT 激活,名单外常驻本就可用。
2289
+ if (!this.lazyOnDemandSet().has(name))
2290
+ return;
1906
2291
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1907
2292
  if (loaded.has(name))
1908
2293
  return;
@@ -1922,7 +2307,6 @@ export class ClientSession {
1922
2307
  const showSkills = presetShowsSkillCatalog(preset);
1923
2308
  const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
1924
2309
  const realCwd = restoreWorkspaceUriFromSessionDir(src.cwd);
1925
- const isRemote = isRemoteWorkspaceUri(realCwd);
1926
2310
  return {
1927
2311
  cwd: formatCwdForPrompt(realCwd),
1928
2312
  systemPromptFile: promptBase.system || undefined,
@@ -1940,14 +2324,6 @@ export class ClientSession {
1940
2324
  pluginSdk: join(getPkgRoot(), "plugin-sdk"),
1941
2325
  pluginsDir: join(this.stateStore.dataDir, "plugins"),
1942
2326
  appendFiles: [...promptBase.append],
1943
- windowsPersona: isRemote
1944
- ? buildRemoteWorkspacePersona(realCwd)
1945
- : process.platform === "win32"
1946
- ? WINDOWS_PERSONA
1947
- : "",
1948
- terminalGuidance: isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), preset)
1949
- ? TERMINAL_TOOLS_GUIDANCE
1950
- : "",
1951
2327
  markersGuidance: this.markerSvc.buildGuidance(),
1952
2328
  lang: this.getLang(),
1953
2329
  contextFiles: src.contextFiles,
@@ -2001,7 +2377,7 @@ export class ClientSession {
2001
2377
  }
2002
2378
  const loader = sess.resourceLoader;
2003
2379
  const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2004
- const lazyOn = this.lazyLoadingOn();
2380
+ const lazyOn = this.lazyEffectiveOn();
2005
2381
  const catalog = lazyOn
2006
2382
  ? this.promptToolCatalog(sess, conv)
2007
2383
  : {
@@ -2009,8 +2385,8 @@ export class ClientSession {
2009
2385
  snippets: {},
2010
2386
  signatures: {},
2011
2387
  };
2012
- const baseNames = lazyOn ? this.lazyBaselineNames(sess) : active;
2013
- const baseSet = new Set(baseNames);
2388
+ // 名单制:基线 = 常驻(允许集 - 名单,含核心 + load_tools),目录 = 名单(不重复列常驻)。
2389
+ const baseNames = lazyOn ? this.lazyResidentNames(sess, conv) : active;
2014
2390
  const snippets = {};
2015
2391
  const signatures = catalog.signatures ?? {};
2016
2392
  const guidelines = [];
@@ -2023,7 +2399,14 @@ export class ClientSession {
2023
2399
  if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
2024
2400
  snippets[name] = eff.promptSnippet.trim();
2025
2401
  }
2026
- if (baseSet.has(name) && eff.promptGuidelines)
2402
+ }
2403
+ for (const name of baseNames) {
2404
+ const def = sess.getToolDefinition(name);
2405
+ if (!def)
2406
+ continue;
2407
+ const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
2408
+ const eff = effectiveToolPrompt(def, ov);
2409
+ if (eff.promptGuidelines)
2027
2410
  guidelines.push(...eff.promptGuidelines);
2028
2411
  }
2029
2412
  const texts = resolveSectionTexts(this.composeInputs({
@@ -2121,7 +2504,7 @@ export class ClientSession {
2121
2504
  subagentHost = {
2122
2505
  resolveConversationId: (id) => this.resolveExecution(id)?.convId,
2123
2506
  consultParent: (selfId, questions, signal) => this.consultParent(selfId, questions, signal),
2124
- answerConsult: (selfId, runId, requestId, answers) => this.answerConsult(selfId, runId, requestId, answers),
2507
+ answerConsult: (selfId, runId, requestId, answers, message) => this.answerConsult(selfId, runId, requestId, answers, message),
2125
2508
  escalateConsult: (selfId, runId, requestId) => this.answerConsult(selfId, runId, requestId),
2126
2509
  getPendingConsults: (parentId) => this.getPendingConsults(parentId),
2127
2510
  setConsultWaiting: (parentId, waiting) => {
@@ -2143,13 +2526,22 @@ export class ClientSession {
2143
2526
  const owner = parentId ? this.subagentOwnerOf(parentId) : this;
2144
2527
  return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal);
2145
2528
  },
2146
- completeSubagent: (selfId, summary) => {
2529
+ completeSubagent: (selfId, summary, evidenceInput) => {
2147
2530
  const owner = this.subagentOwnerOf(selfId);
2148
2531
  const conv = owner.convs.get(this.subagentCurrentId(selfId));
2149
2532
  if (!conv?.parentId)
2150
2533
  throw new Error("Only a child task can complete itself.");
2534
+ // 证据不采信自述:拿它自己的转录核对声称的文件与命令。
2535
+ const facts = collectTranscriptFacts(sessionMessagesOf(conv.session));
2536
+ const evidence = verifyEvidence(evidenceInput ?? {}, facts);
2537
+ if (evidence.issues.length > 0) {
2538
+ return { ok: false, error: evidence.issues[0], issues: evidence.issues, evidence };
2539
+ }
2540
+ conv.subagentEvidence = evidence;
2541
+ owner.syncSubagentLedger(conv, { state: "running", event: "completion_requested" });
2151
2542
  conv.subagentTask = requestSubagentCompletion(conv.subagentTask ?? createSubagentTask(conv.notifyOnDone), summary);
2152
- return { accepted: true, taskPending: owner.subagentTaskPending(conv) };
2543
+ this.subagentSettle.notify(conv.id);
2544
+ return { ok: true, taskPending: owner.subagentTaskPending(conv), evidence };
2153
2545
  },
2154
2546
  finalizeSubagentWorktree: async (convId) => {
2155
2547
  const owner = this.subagentOwnerOf(convId);
@@ -2182,9 +2574,23 @@ export class ClientSession {
2182
2574
  const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
2183
2575
  const conv = owner.convs.get(curId);
2184
2576
  if (!conv?.session)
2185
- return;
2186
- await owner.steerSubagentRound(conv, message);
2577
+ return { state: "missed" };
2578
+ return await owner.steerSubagentRound(conv, message);
2579
+ },
2580
+ waitForSubagentSettle: (ids, opts) => this.subagentSettle.waitFor(ids, opts),
2581
+ listLedgerRuns: async (opts) => {
2582
+ const ledger = this.subagentLedger;
2583
+ await ledger.ready();
2584
+ const limit = Math.max(1, Math.min(opts?.limit ?? 32, 100));
2585
+ return ledger.list().slice(0, limit);
2586
+ },
2587
+ getLedgerRun: async (runId) => {
2588
+ const ledger = this.subagentLedger;
2589
+ await ledger.ready();
2590
+ return ledger.read(runId);
2187
2591
  },
2592
+ getLedgerEvents: (runId, limit) => this.subagentLedger.events(runId, limit),
2593
+ resumeLedgerRun: (selfId, runId, message) => this.resumeSubagentRun(selfId, runId, message),
2188
2594
  stopSubagent: (convId) => this.stopSubagentTask(convId),
2189
2595
  getActiveConversationId: () => this.activeId,
2190
2596
  dismissSubagent: async (convId, opts) => {
@@ -2422,6 +2828,8 @@ export class ClientSession {
2422
2828
  }
2423
2829
  return undefined;
2424
2830
  }
2831
+ phoneSeq = 0;
2832
+ pendingPhoneCalls = new Map();
2425
2833
  pageSeq = 0;
2426
2834
  pendingPageCalls = new Map();
2427
2835
  constructor(clientId, cwd, agentDir, stateStore) {
@@ -2497,7 +2905,6 @@ export class ClientSession {
2497
2905
  },
2498
2906
  promptSnapshot: () => this.promptSnapshot(),
2499
2907
  getMarkerState: () => ({
2500
- markersEnabled: this.markerSvc.current.markersEnabled,
2501
2908
  disabledMarkers: [...this.markerSvc.current.disabledMarkers],
2502
2909
  markers: this.markerSvc.listForUi(),
2503
2910
  }),
@@ -2767,6 +3174,7 @@ export class ClientSession {
2767
3174
  });
2768
3175
  }
2769
3176
  await cs.bindSession();
3177
+ void cs.recoverSubagentRuns().catch(() => { });
2770
3178
  const globalDefault = stateStore.getDefaultModel();
2771
3179
  if (globalDefault) {
2772
3180
  const slash = globalDefault.indexOf("/");
@@ -2788,7 +3196,7 @@ export class ClientSession {
2788
3196
  conv.pinned = true;
2789
3197
  conv.listed = true;
2790
3198
  }
2791
- const pinnedPaths = botExecution ? [] : (cs.stateStore?.getPinnedSessions(cwd) ?? []);
3199
+ const pinnedPaths = botExecution ? [] : await pinnedPathsOwnedBy(cs.stateStore?.getPinnedSessions(cwd) ?? [], cwd);
2792
3200
  const maxOpenConversations = getMaxOpenConversations();
2793
3201
  for (const p of pinnedPaths) {
2794
3202
  if (cs.convs.size >= maxOpenConversations)
@@ -2907,10 +3315,6 @@ export class ClientSession {
2907
3315
  else if (process.platform === "win32") {
2908
3316
  out.push(WINDOWS_PERSONA);
2909
3317
  }
2910
- const presetForGuidance = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2911
- if (isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), presetForGuidance)) {
2912
- out.push(TERMINAL_TOOLS_GUIDANCE);
2913
- }
2914
3318
  const markerGuidance = this.markerSvc.buildGuidance();
2915
3319
  if (markerGuidance)
2916
3320
  out.push(markerGuidance);
@@ -3027,7 +3431,7 @@ export class ClientSession {
3027
3431
  const conv = this.convs.get(ownerId ?? this.activeId) ?? this.conv;
3028
3432
  const sess = conv?.session;
3029
3433
  const activeToolNames = sess ? sess.getActiveToolNames() : [];
3030
- const lazyOn = this.lazyLoadingOn();
3434
+ const lazyOn = this.lazyEffectiveOn();
3031
3435
  const catalog = lazyOn && sess
3032
3436
  ? this.promptToolCatalog(sess, conv)
3033
3437
  : {
@@ -3035,8 +3439,7 @@ export class ClientSession {
3035
3439
  snippets: {},
3036
3440
  signatures: {},
3037
3441
  };
3038
- const baseNames = lazyOn && sess ? this.lazyBaselineNames(sess) : activeToolNames;
3039
- const baseSet = new Set(baseNames);
3442
+ const baseNames = lazyOn && sess ? this.lazyResidentNames(sess, conv) : activeToolNames;
3040
3443
  const activeSnippets = {};
3041
3444
  const activeSignatures = catalog.signatures ?? {};
3042
3445
  const activeGuidelines = [];
@@ -3050,9 +3453,15 @@ export class ClientSession {
3050
3453
  if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
3051
3454
  activeSnippets[name] = eff.promptSnippet.trim();
3052
3455
  }
3053
- if (baseSet.has(name) && eff.promptGuidelines) {
3456
+ }
3457
+ for (const name of baseNames) {
3458
+ const def = sess.getToolDefinition(name);
3459
+ if (!def)
3460
+ continue;
3461
+ const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
3462
+ const eff = effectiveToolPrompt(def, ov);
3463
+ if (eff.promptGuidelines)
3054
3464
  activeGuidelines.push(...eff.promptGuidelines);
3055
- }
3056
3465
  }
3057
3466
  }
3058
3467
  const currentPreset = conv?.agentPreset ?? targetPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
@@ -3231,9 +3640,6 @@ export class ClientSession {
3231
3640
  return {};
3232
3641
  },
3233
3642
  }).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
3234
- withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(wrapEditSoftToolWithPermission(makeEditSoftTool(effectiveCwd, () => this.getLang()), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
3235
- this.settingsSvc.current.defaultPermissionPreset ??
3236
- "workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category), () => ownerId, () => this.approvalRules.list()), () => this.sandboxes.getExecutionIdentity(effectiveCwd, sandboxIdentity), () => effectiveCwd, () => this.getLang(), { trustedTool: true }, () => this.sandboxes.acquireExecution(effectiveCwd, sandboxIdentity)), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()),
3237
3643
  ...(sandboxIdentity || (apply && apply.enabledExtensions.length > 0)
3238
3644
  ? []
3239
3645
  : this.enabledPluginToolDefs(undefined, effectiveCwd)),
@@ -3267,6 +3673,8 @@ export class ClientSession {
3267
3673
  }, (msg) => this.emit(msg), () => this.flushSnapshot()),
3268
3674
  makeAskUserQuestionTool(bridge, ownerId),
3269
3675
  makeBrowserPageTool(bridge, ownerId),
3676
+ makePhoneTool(bridge, ownerId),
3677
+ makeBrowserScriptTool(bridge, ownerId),
3270
3678
  makeConversationReadTool(this.conversationReadHost(), () => this.getLang(), {
3271
3679
  listClaims: (cwd) => (this.getClaimStore?.().list(cwd) ?? []).map((c) => ({
3272
3680
  path: c.path,
@@ -3560,6 +3968,9 @@ export class ClientSession {
3560
3968
  toolWatchdogs: new Map(),
3561
3969
  workspaceSnapshots: readWorkspaceSnapshotsFromSession(runtime.session.sessionManager),
3562
3970
  };
3971
+ const forkedFromSessionPath = parentSessionOfManager(runtime.session.sessionManager);
3972
+ if (forkedFromSessionPath)
3973
+ conv.forkedFromSessionPath = forkedFromSessionPath;
3563
3974
  if (conv.nativeCli)
3564
3975
  this.ensureNativeCliBinding(conv);
3565
3976
  conversationIdentity(conv);
@@ -3608,6 +4019,9 @@ export class ClientSession {
3608
4019
  for (const conv of this.convs.values()) {
3609
4020
  if (!conv.session.isStreaming)
3610
4021
  continue;
4022
+ // 子代理/持久化子会话由运行账本负责重启对账与续跑,不能当成普通标签页重新打开。
4023
+ if (conv.isSubagent || conv.parentId || conv.subagentPrompt)
4024
+ continue;
3611
4025
  let sessionFile;
3612
4026
  try {
3613
4027
  sessionFile = conv.session.sessionFile ?? undefined;
@@ -4747,6 +5161,8 @@ export class ClientSession {
4747
5161
  }
4748
5162
  case "turn_end": {
4749
5163
  this.emitRun(conv, { type: "turn_end" });
5164
+ // 这一轮写进会话文件后,所属项目的会话列表要跟着刷新(可能属于别的项目)。
5165
+ this.scheduleSessionsPush(conv.cwd);
4750
5166
  break;
4751
5167
  }
4752
5168
  case "message_update": {
@@ -5102,6 +5518,10 @@ export class ClientSession {
5102
5518
  const h = home();
5103
5519
  return h.session.pageCall(req, sig, h.convId);
5104
5520
  },
5521
+ phoneCall: (req, sig) => {
5522
+ const h = home();
5523
+ return h.session.phoneCall(req, sig, h.convId);
5524
+ },
5105
5525
  canSeeImages: () => home().session.canSeeImages(),
5106
5526
  transcribeToolImage: (image, signal) => home().session.transcribeToolImage(image, signal),
5107
5527
  };
@@ -5114,7 +5534,9 @@ export class ClientSession {
5114
5534
  return Promise.reject(new Error("Questionnaire is disabled"));
5115
5535
  }
5116
5536
  const conv = this.convs.get(conversationId);
5117
- const request = new PendingQuestion(questions, conversationId, "user", conv?.isSubagent ? (this.settingsSvc.current.questionTimeoutSeconds ?? 240) : 0, sig);
5537
+ // 无人值守(伪客户端)与子代理一样按 questionTimeoutSeconds 超时;有人盯着的普通会话保持永不超时。
5538
+ const unattended = conv?.isSubagent || isPseudoClientId(this.clientId ?? "");
5539
+ const request = new PendingQuestion(questions, conversationId, "user", unattended ? (this.settingsSvc.current.questionTimeoutSeconds ?? 240) : 0, sig);
5118
5540
  this.registerQuestion(request);
5119
5541
  this.questionsChanged();
5120
5542
  return request.promise;
@@ -5289,17 +5711,28 @@ export class ClientSession {
5289
5711
  const home = current();
5290
5712
  return home.session.consultParent(conversationIdentity(home.session.convs.get(home.convId)), questions, signal);
5291
5713
  },
5292
- answerConsult: (_self, runId, requestId, answers) => {
5714
+ answerConsult: (_self, runId, requestId, answers, message) => {
5293
5715
  const home = current();
5294
- return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId, answers);
5716
+ return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId, answers, message);
5295
5717
  },
5296
5718
  escalateConsult: (_self, runId, requestId) => {
5297
5719
  const home = current();
5298
5720
  return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId);
5299
5721
  },
5300
- completeSubagent: (_self, summary) => {
5722
+ completeSubagent: (_self, summary, evidence) => {
5723
+ const home = current();
5724
+ return home.session.subagentHost.completeSubagent(home.convId, summary, evidence);
5725
+ },
5726
+ waitForSubagentSettle: (ids, opts) => current().session.subagentSettle.waitFor(ids, opts),
5727
+ listLedgerRuns: (opts) => current().session.subagentHost.listLedgerRuns?.(opts) ?? Promise.resolve([]),
5728
+ getLedgerRun: (runId) => current().session.subagentHost.getLedgerRun?.(runId) ?? Promise.resolve(undefined),
5729
+ getLedgerEvents: (runId, limit) => current().session.subagentHost.getLedgerEvents?.(runId, limit) ?? Promise.resolve([]),
5730
+ resumeLedgerRun: (_self, runId, message) => {
5301
5731
  const home = current();
5302
- return home.session.subagentHost.completeSubagent(home.convId, summary);
5732
+ const resume = home.session.subagentHost.resumeLedgerRun;
5733
+ if (!resume)
5734
+ return Promise.resolve({ ok: false, error: "unsupported" });
5735
+ return resume(home.convId, runId, message);
5303
5736
  },
5304
5737
  getPendingConsults: () => {
5305
5738
  const home = current();
@@ -5487,17 +5920,20 @@ export class ClientSession {
5487
5920
  owner.emitConversations();
5488
5921
  return "queued";
5489
5922
  }
5490
- answerConsult(selfId, runId, requestId, answers) {
5923
+ answerConsult(selfId, runId, requestId, answers, message) {
5491
5924
  const parentOwner = this.subagentOwnerOf(selfId);
5492
5925
  const parent = parentOwner.convs.get(this.subagentCurrentId(selfId));
5493
5926
  const owner = this.subagentOwnerOf(runId);
5494
5927
  const child = owner.convs.get(this.subagentCurrentId(runId));
5928
+ const text = typeof message === "string" && message.trim() ? message : undefined;
5495
5929
  if (parent && child && conversationCommunication.requestSource(requestId) === child) {
5496
5930
  if (owner.parentExecution(child)?.conv !== parent)
5497
5931
  return { ok: false, error: "Only the direct parent may use the compatibility answer action." };
5498
- return this.communicate(parent.id, answers ? "reply" : "escalate", {
5932
+ if (answers === undefined && !text)
5933
+ return this.communicate(parent.id, "escalate", { requestId });
5934
+ return this.communicate(parent.id, "reply", {
5499
5935
  requestId,
5500
- ...(answers ? { answers } : {}),
5936
+ ...(answers === undefined ? { message: text } : { answers }),
5501
5937
  });
5502
5938
  }
5503
5939
  const request = owner.pendingQuestions.get(requestId);
@@ -5511,8 +5947,10 @@ export class ClientSession {
5511
5947
  request.audience !== "parent") {
5512
5948
  return { ok: false, error: "Only the direct parent may answer or escalate its pending consult." };
5513
5949
  }
5514
- if (answers)
5950
+ if (answers !== undefined)
5515
5951
  request.resolve(answers);
5952
+ else if (text)
5953
+ request.resolve(answersFromMessage(text, request.questions) ?? null);
5516
5954
  else {
5517
5955
  request.audience = "user";
5518
5956
  owner.questionsChanged();
@@ -5552,6 +5990,7 @@ export class ClientSession {
5552
5990
  }
5553
5991
  }
5554
5992
  questionsChanged() {
5993
+ this.subagentSettle.notifyAll();
5555
5994
  for (const owner of new Set([this, ...(this.allSubagentSessions?.() ?? [])])) {
5556
5995
  for (const request of owner.pendingQuestions.values())
5557
5996
  owner.notifyUserQuestion(request);
@@ -5677,6 +6116,7 @@ export class ClientSession {
5677
6116
  }
5678
6117
  const approvalSession = conv.session;
5679
6118
  let settled = false;
6119
+ let unattendedTimer = null;
5680
6120
  const onAbort = () => {
5681
6121
  if (settled)
5682
6122
  return;
@@ -5689,6 +6129,10 @@ export class ClientSession {
5689
6129
  if (settled)
5690
6130
  return;
5691
6131
  settled = true;
6132
+ if (unattendedTimer) {
6133
+ clearTimeout(unattendedTimer);
6134
+ unattendedTimer = null;
6135
+ }
5692
6136
  settledApprovalRequests.add(entry);
5693
6137
  signal?.removeEventListener("abort", onAbort);
5694
6138
  if (conv.pendingApprovals?.get(entry.id) === entry)
@@ -5716,6 +6160,28 @@ export class ClientSession {
5716
6160
  onAbort();
5717
6161
  return;
5718
6162
  }
6163
+ // 无人值守(plugin:/scheduler:/canvas: —— 没人能点 UI):超时后安全拒绝,
6164
+ // 并在会话里留一条可解释的 notice(渠道侧会把它当成 run 事件回给用户)。
6165
+ const unattendedApprovalMs = unattendedApprovalTimeoutMs(this.clientId ?? "");
6166
+ if (unattendedApprovalMs !== null) {
6167
+ unattendedTimer = setTimeout(() => {
6168
+ if (settled)
6169
+ return;
6170
+ const seconds = Math.round(unattendedApprovalMs / 1000);
6171
+ this.emitNotice("warning", `无人值守审批超时(${seconds}s):已拒绝工具 ${toolName}。如需自动放行请调整审批策略或该会话的白名单。`, `Unattended approval timed out after ${seconds}s: tool ${toolName} was denied. Adjust the approval policy to allow it.`);
6172
+ this.auditLogger.record({
6173
+ conversationId: conv.id,
6174
+ toolName,
6175
+ params,
6176
+ decision: "denied",
6177
+ decisionSource: "unattended_timeout",
6178
+ ...(category ? { categoryId: category.id } : {}),
6179
+ reason: "unattended approval timeout",
6180
+ });
6181
+ finish({ decision: "deny", reason: "Unattended approval timeout" });
6182
+ }, unattendedApprovalMs);
6183
+ unattendedTimer.unref?.();
6184
+ }
5719
6185
  this.notifyMobile(conv, "approval", id, conv.session?.sessionId, entry.createdAt);
5720
6186
  this.emit({
5721
6187
  type: "tool_approval_pending",
@@ -6060,6 +6526,16 @@ export class ClientSession {
6060
6526
  }
6061
6527
  conv.pendingApprovals.clear();
6062
6528
  }
6529
+ for (const [id, p] of this.pendingPhoneCalls) {
6530
+ if (p.conversationId !== convId)
6531
+ continue;
6532
+ this.pendingPhoneCalls.delete(id);
6533
+ clearTimeout(p.timer);
6534
+ try {
6535
+ p.resolve({ ok: false, error: "会话已重置或停止,挂起中的手机操控已取消。" });
6536
+ }
6537
+ catch { }
6538
+ }
6063
6539
  for (const [id, p] of this.pendingPageCalls) {
6064
6540
  if (p.conversationId !== convId)
6065
6541
  continue;
@@ -6156,6 +6632,44 @@ export class ClientSession {
6156
6632
  this.emit({ type: "page_request", id, op: req.op, args: req.args, target: req.target, timeoutMs });
6157
6633
  });
6158
6634
  }
6635
+ /** 手机操控调用:与 pageCall 同一套「服务端发起 → 客户端执行 → 回来兑现 Promise」的桥。 */
6636
+ phoneCall(req, sig, conversationId) {
6637
+ return new Promise((resolve) => {
6638
+ if (sig?.aborted || this.disposed) {
6639
+ resolve({ ok: false, error: "手机操控已中止(phone aborted)。" });
6640
+ return;
6641
+ }
6642
+ if (this.sinks.size === 0) {
6643
+ resolve({
6644
+ ok: false,
6645
+ error: "没有已连接的手机客户端(no phone connected)。请在手机上打开 pi,并确认无障碍服务已开启。",
6646
+ });
6647
+ return;
6648
+ }
6649
+ const id = `ph-${++this.phoneSeq}`;
6650
+ const timeoutMs = normalizePhoneCallTimeoutMs(req.timeoutMs);
6651
+ const timer = setTimeout(() => {
6652
+ if (this.pendingPhoneCalls.delete(id)) {
6653
+ resolve({
6654
+ ok: false,
6655
+ error: `${Math.round(timeoutMs / 1000)} 秒内没有收到手机响应(timeout ${timeoutMs}ms)。请确认 pi 手机端在前台且无障碍服务已开启。`,
6656
+ });
6657
+ }
6658
+ }, timeoutMs);
6659
+ this.pendingPhoneCalls.set(id, { resolve, timer, conversationId, timeoutMs });
6660
+ this.emit({ type: "phone_request", id, op: req.op, args: req.args, timeoutMs });
6661
+ });
6662
+ }
6663
+ resolvePhoneCall(id, ok, result, error, conversationId) {
6664
+ const pending = this.pendingPhoneCalls.get(id);
6665
+ if (conversationId && pending?.conversationId !== conversationId)
6666
+ throw new Error("Phone request does not belong to the shared conversation");
6667
+ if (!pending)
6668
+ return;
6669
+ this.pendingPhoneCalls.delete(id);
6670
+ clearTimeout(pending.timer);
6671
+ pending.resolve(ok ? { ok: true, result } : { ok: false, error: error?.trim() || "手机操作失败(no error message)" });
6672
+ }
6159
6673
  resolvePageCall(id, ok, result, error, conversationId) {
6160
6674
  const pending = this.pendingPageCalls.get(id);
6161
6675
  if (conversationId && pending?.conversationId !== conversationId)
@@ -7053,15 +7567,12 @@ export class ClientSession {
7053
7567
  async setSettings(partial) {
7054
7568
  if (this.botExecution)
7055
7569
  throw new Error("Bot settings are fixed");
7056
- const { markersEnabled, disabledMarkers, quickPhrasesSeeded, ...rest } = partial;
7570
+ const { disabledMarkers, quickPhrasesSeeded, ...rest } = partial;
7057
7571
  if (quickPhrasesSeeded)
7058
7572
  this.stateStore.markQuickPhrasesSeeded();
7059
7573
  let markerChanged = false;
7060
- if (markersEnabled !== undefined || disabledMarkers !== undefined) {
7061
- this.markerSvc.setAll({
7062
- ...(markersEnabled !== undefined ? { markersEnabled } : {}),
7063
- ...(disabledMarkers !== undefined ? { disabledMarkers } : {}),
7064
- });
7574
+ if (disabledMarkers !== undefined) {
7575
+ this.markerSvc.setDisabledMarkers(disabledMarkers);
7065
7576
  markerChanged = true;
7066
7577
  }
7067
7578
  await this.settingsSvc.set(rest);
@@ -7094,6 +7605,19 @@ export class ClientSession {
7094
7605
  }
7095
7606
  }
7096
7607
  }
7608
+ /**
7609
+ * 安装成功即启用:把插件从 `disabledPlugins` 里摘掉。设置是全局的,写一次所有客户端下次收到 settings 即生效。
7610
+ * 「更新」不走这里——用户主动禁用过的插件升级后应保持禁用。
7611
+ */
7612
+ async enableInstalledPlugin(pluginId) {
7613
+ if (this.botExecution)
7614
+ return false;
7615
+ const next = enablePluginAfterInstall(this.settingsSvc.current.disabledPlugins, pluginId);
7616
+ if (!next)
7617
+ return false;
7618
+ await this.settingsSvc.set({ disabledPlugins: next });
7619
+ return true;
7620
+ }
7097
7621
  async savePreset(name) {
7098
7622
  return this.settingsSvc.savePreset(name);
7099
7623
  }
@@ -7549,7 +8073,7 @@ export class ClientSession {
7549
8073
  mode: this.subagentSecurityModeOf(ownerId),
7550
8074
  allowedTools: this.subagentAllowedToolsOf(ownerId),
7551
8075
  }), () => this.getLang()), () => this.awaitPendingWorkspaceSnapshot(ownerId));
7552
- const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
8076
+ const composeWrite = (base) => withSlimPrompt(planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base)), WRITE_DESCRIPTION, WRITE_PARAMETERS);
7553
8077
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
7554
8078
  const composeBash = (base) => {
7555
8079
  const makeCore = (convKills) => {
@@ -7577,7 +8101,7 @@ export class ClientSession {
7577
8101
  };
7578
8102
  }
7579
8103
  else {
7580
- core = makeAdaptiveBashTool(makeKillableBashTool(cwd, convKills, () => this.getLang()), terminals
8104
+ core = makeAdaptiveBashTool(makeKillableBashTool(cwd, convKills, () => this.getLang(), this.jobs, () => ownerId), terminals
7581
8105
  ? makeTerminalBashTool(terminals, {
7582
8106
  cwd,
7583
8107
  defaultPersist: () => false,
@@ -7587,7 +8111,7 @@ export class ClientSession {
7587
8111
  notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
7588
8112
  lang: () => this.getLang(),
7589
8113
  })
7590
- : makeKillableBashTool(cwd, convKills, () => this.getLang()), () => Boolean(terminals && this.settingsSvc.current.terminalBash));
8114
+ : makeKillableBashTool(cwd, convKills, () => this.getLang(), this.jobs, () => ownerId), () => Boolean(terminals && this.settingsSvc.current.terminalBash));
7591
8115
  }
7592
8116
  return core;
7593
8117
  };
@@ -7633,31 +8157,43 @@ export class ClientSession {
7633
8157
  { name: "write", fallback: () => composeWrite(), composeWith: (base) => composeWrite(base) },
7634
8158
  {
7635
8159
  name: "edit",
7636
- fallback: () => composeEdit({
7637
- ...createEditToolDefinition(cwd, remoteOps ? { operations: remoteOps.edit } : undefined),
7638
- description: EDIT_DESCRIPTION,
7639
- promptGuidelines: EDIT_GUIDELINES,
7640
- }),
8160
+ fallback: () => composeEdit(makeEditToolDefinition(cwd, () => this.getLang())),
7641
8161
  composeWith: (base) => composeEdit(base),
7642
8162
  },
7643
- ];
7644
- if (remoteOps) {
7645
- specs.push({
7646
- name: "ls",
7647
- fallback: () => createLsToolDefinition(cwd, { operations: remoteOps.ls }),
7648
- }, {
8163
+ {
7649
8164
  name: "find",
7650
- fallback: () => createFindToolDefinition(cwd, { operations: remoteOps.find }),
7651
- }, {
8165
+ fallback: () => withSlimPrompt(createFindToolDefinition(cwd, remoteOps ? { operations: remoteOps.find } : undefined), FIND_DESCRIPTION, FIND_PARAMETERS),
8166
+ },
8167
+ {
7652
8168
  name: "grep",
7653
8169
  fallback: () => {
7654
- const baseGrep = createGrepToolDefinition(cwd);
8170
+ const base = createGrepToolDefinition(cwd);
8171
+ const slimmed = remoteOps
8172
+ ? {
8173
+ ...base,
8174
+ execute: async (_id, params) => ({
8175
+ content: [{ type: "text", text: await remoteOps.grepExecute(params ?? {}) }],
8176
+ details: undefined,
8177
+ }),
8178
+ }
8179
+ : base;
8180
+ return withSlimPrompt(slimmed, GREP_DESCRIPTION, GREP_PARAMETERS);
8181
+ },
8182
+ },
8183
+ {
8184
+ name: "ls",
8185
+ fallback: () => withSlimPrompt(createLsToolDefinition(cwd, remoteOps ? { operations: remoteOps.ls } : undefined), LS_DESCRIPTION, LS_PARAMETERS),
8186
+ },
8187
+ ];
8188
+ if (process.platform === "win32") {
8189
+ specs.push({
8190
+ name: "powershell",
8191
+ fallback: () => {
8192
+ const slim = withSlimPrompt(createPowerShellToolDefinition(cwd), POWERSHELL_DESCRIPTION, POWERSHELL_PARAMETERS);
8193
+ // 与 bash 同一处归一(server/bash-timeout.ts):漏传 timeout 不等于无时限。
7655
8194
  return {
7656
- ...baseGrep,
7657
- execute: async (_id, params) => {
7658
- const text = await remoteOps.grepExecute(params ?? {});
7659
- return { content: [{ type: "text", text }], details: undefined };
7660
- },
8195
+ ...slim,
8196
+ execute: (id, params, signal, onUpdate, ctx) => slim.execute(id, withDefaultBashTimeout(params), signal, onUpdate, ctx),
7661
8197
  };
7662
8198
  },
7663
8199
  });
@@ -7734,12 +8270,14 @@ export class ClientSession {
7734
8270
  }
7735
8271
  }
7736
8272
  let loadedNames = [];
7737
- const lazy = this.lazyLoadingOn();
8273
+ const lazy = this.lazyEffectiveOn();
7738
8274
  if (lazy) {
7739
8275
  try {
7740
8276
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
7741
8277
  loadedNames = [...loaded];
7742
- for (const name of lazyLoadingDisabledTools(session.getAllTools().map((t) => t.name), loaded)) {
8278
+ // 名单制:只延迟名单里的工具;名单为空等于都不延迟(仅常驻 + load_tools)。
8279
+ const only = this.lazyOnDemandSet();
8280
+ for (const name of lazyLoadingDisabledTools(session.getAllTools().map((t) => t.name), loaded, undefined, only)) {
7743
8281
  disabled.add(name);
7744
8282
  }
7745
8283
  }
@@ -7752,7 +8290,7 @@ export class ClientSession {
7752
8290
  forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME, ...loadedNames] : [],
7753
8291
  });
7754
8292
  const ownerId = conv?.id;
7755
- const subagentOff = disabled.has("conversation") || disabled.has("subagent") || SPAWN_TOOLS_BARRED.has(session);
8293
+ const subagentOff = disabled.has("conversation") || SPAWN_TOOLS_BARRED.has(session);
7756
8294
  syncSubagentOverride(session, subagentOff, (name) => mergeConversationTools([
7757
8295
  ...(ownerId
7758
8296
  ? makeSubagentTools(withSubagentOwner(this.communicationBoundSubagentHost({ session }), ownerId, () => this.requireSubagentOwner({ session }, ownerId)), undefined, () => {
@@ -8489,6 +9027,7 @@ export class ClientSession {
8489
9027
  isStreaming: streaming,
8490
9028
  convId: conv.id,
8491
9029
  independent: conv.independent !== false,
9030
+ forked: Boolean(conv.forkFrom || conv.forkedFromSessionPath),
8492
9031
  hasQuestion: !!pq,
8493
9032
  ...(pq?.title ? { questionTitle: pq.title } : {}),
8494
9033
  ...(sessionFile ? { sessionFile } : {}),
@@ -8595,6 +9134,7 @@ export class ClientSession {
8595
9134
  this.flushSnapshot();
8596
9135
  return;
8597
9136
  }
9137
+ this.markProjectConversationActivity(conv.cwd);
8598
9138
  const promptAc = new AbortController();
8599
9139
  conv.activePromptAc = promptAc;
8600
9140
  this.markerSvc.clearActions(conv.id);
@@ -9322,6 +9862,61 @@ export class ClientSession {
9322
9862
  async listBgServers() {
9323
9863
  await this.bg.listAndPush();
9324
9864
  }
9865
+ listProjectScripts(cwd) {
9866
+ const base = (typeof cwd === "string" && cwd.trim()) || this.convs.get(this.activeId)?.cwd || this.cwd;
9867
+ try {
9868
+ const found = resolveProjectScripts(base);
9869
+ this.emit({ type: "project_scripts", cwd: found.cwd, scripts: found.scripts });
9870
+ }
9871
+ catch (err) {
9872
+ this.emit({
9873
+ type: "project_scripts",
9874
+ cwd: base,
9875
+ scripts: {},
9876
+ error: err instanceof Error ? err.message : String(err),
9877
+ });
9878
+ }
9879
+ }
9880
+ startBgScript(script, cwd) {
9881
+ const name = String(script ?? "").trim();
9882
+ if (!/^[A-Za-z0-9 _.:-]+$/.test(name) || name.length > 80) {
9883
+ this.emitNotice("warning", `启动脚本名不合法:「${name}」`);
9884
+ return;
9885
+ }
9886
+ const dir = (typeof cwd === "string" && cwd.trim()) || this.convs.get(this.activeId)?.cwd || this.cwd;
9887
+ const found = resolveProjectScripts(dir);
9888
+ if (!found.scripts[name]) {
9889
+ this.emitNotice("warning", `package.json 里没有脚本「${name}」`);
9890
+ return;
9891
+ }
9892
+ try {
9893
+ this.jobs.start({ command: `npm run ${name}`, cwd: found.cwd, label: name, origin: this.activeId });
9894
+ }
9895
+ catch (err) {
9896
+ this.emitNotice("warning", `启动失败:${err instanceof Error ? err.message : String(err)}`);
9897
+ }
9898
+ this.bg.push();
9899
+ this.flushSnapshot();
9900
+ }
9901
+ restartBgJob(taskId) {
9902
+ const id = String(taskId ?? "");
9903
+ if (!id.startsWith(JOB_TASK_PREFIX))
9904
+ return;
9905
+ const snap = this.jobs.get(id.slice(JOB_TASK_PREFIX.length));
9906
+ if (!snap) {
9907
+ this.emitNotice("info", `后台任务「${id}」不存在或已结束`);
9908
+ return;
9909
+ }
9910
+ this.jobs.kill(snap.id);
9911
+ try {
9912
+ this.jobs.start({ command: snap.command, cwd: snap.cwd, label: snap.label, origin: this.activeId });
9913
+ }
9914
+ catch (err) {
9915
+ this.emitNotice("warning", `重启失败:${err instanceof Error ? err.message : String(err)}`);
9916
+ }
9917
+ this.bg.push();
9918
+ this.flushSnapshot();
9919
+ }
9325
9920
  refreshBgTasks() {
9326
9921
  this.bg.push();
9327
9922
  }
@@ -9329,6 +9924,35 @@ export class ClientSession {
9329
9924
  this.emit({ type: "notice", level, text, textEn });
9330
9925
  }
9331
9926
  async killBackgroundServer(port, taskId) {
9927
+ if (taskId?.startsWith(JOB_TASK_PREFIX)) {
9928
+ const raw = taskId.slice(JOB_TASK_PREFIX.length);
9929
+ const res = await this.jobs.killAndWait(raw);
9930
+ if (!res.ok) {
9931
+ this.emit({
9932
+ type: "notice",
9933
+ level: "info",
9934
+ text: `后台任务「${taskId}」不存在或已结束`,
9935
+ textEn: `Background job "${taskId}" does not exist or has ended`,
9936
+ });
9937
+ }
9938
+ if (res.timedOut) {
9939
+ this.emit({
9940
+ type: "notice",
9941
+ level: "warning",
9942
+ text: `后台任务「${taskId}」停止超时,已强制从列表移除;若进程仍在请手动 kill`,
9943
+ textEn: `Background job "${taskId}" stop timed out, force-removed; kill manually if still alive`,
9944
+ });
9945
+ }
9946
+ this.bg.push();
9947
+ this.flushSnapshot();
9948
+ setTimeout(() => {
9949
+ if (!this.disposed) {
9950
+ this.bg.push();
9951
+ this.flushSnapshot();
9952
+ }
9953
+ }, 2000)?.unref?.();
9954
+ return res.ok;
9955
+ }
9332
9956
  if (taskId) {
9333
9957
  const ok = this.pluginStopBgTask?.(taskId) ?? false;
9334
9958
  if (!ok) {
@@ -10342,6 +10966,9 @@ export class ClientSession {
10342
10966
  for (const fn of waiters)
10343
10967
  fn("gone");
10344
10968
  }
10969
+ this.syncSubagentLedger(conv, { state: "dismissed", event: "dismissed" });
10970
+ this.subagentSettle.notify(id);
10971
+ this.subagentSpawnBudget.forget(this.subagentRootId(id));
10345
10972
  try {
10346
10973
  this.getClaimStore?.().releaseByOwner(id);
10347
10974
  }
@@ -10402,6 +11029,10 @@ export class ClientSession {
10402
11029
  hasConversation(convId) {
10403
11030
  return this.convs.has(convId);
10404
11031
  }
11032
+ /** 这个 conv 对象当前是不是本页持有的那一个(过户回退时用来判断要不要重新 insert)。 */
11033
+ ownsConversation(conv) {
11034
+ return this.convs.get(conv.id) === conv;
11035
+ }
10405
11036
  takeoverBriefs() {
10406
11037
  return [...this.convs.values()].map((c) => {
10407
11038
  let sessionFile;
@@ -10420,7 +11051,16 @@ export class ClientSession {
10420
11051
  };
10421
11052
  });
10422
11053
  }
10423
- async detachTakeoverConversations(ids) {
11054
+ /**
11055
+ * 过户交接第一步:把要搬的对话从当前页的排队/订阅/看门狗里摘出来,组装 payload。
11056
+ *
11057
+ * 关键:**本步不动 `this.convs`**。持有权要等目标页 `insertTakeoverConvs` 完成之后,
11058
+ * 再由 `commitTakeoverRemoval` 摘掉——中间任何一帧都不能出现「两边都不持有」的真空:
11059
+ * 在飞的工具调用(wait_all 展开后代、subagent 查询)靠 session→conversation 身份反查
11060
+ * 归属,真空里会直接抛「Calling conversation is no longer available」把整个工具调用判死
11061
+ * (回归:tests/subagent-takeover-test.mjs)。
11062
+ */
11063
+ async prepareTakeoverConversations(ids) {
10424
11064
  if (this.botExecution)
10425
11065
  return { ok: false, reason: "missing" };
10426
11066
  const set = new Set(ids);
@@ -10448,7 +11088,6 @@ export class ClientSession {
10448
11088
  delete conv.transferring;
10449
11089
  }
10450
11090
  for (const conv of convs) {
10451
- this.convs.delete(conv.id);
10452
11091
  this.pluginModelKeys?.delete(conv.id);
10453
11092
  this.clearAllToolWatchdogs(conv);
10454
11093
  conv.unsubscribe?.();
@@ -10461,15 +11100,6 @@ export class ClientSession {
10461
11100
  }
10462
11101
  this.goalSvc.notifyTakeover(conv);
10463
11102
  }
10464
- if (!this.convs.has(this.activeId)) {
10465
- const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
10466
- if (fallback) {
10467
- this.activeId = fallback.id;
10468
- }
10469
- else {
10470
- await this.newChat();
10471
- }
10472
- }
10473
11103
  const questions = [];
10474
11104
  for (const [qid, p] of this.pendingQuestions) {
10475
11105
  if (p.conversationId !== undefined && set.has(p.conversationId)) {
@@ -10499,6 +11129,29 @@ export class ClientSession {
10499
11129
  this.questionsChanged();
10500
11130
  return { ok: true, payload: { convs, questions, pageCalls, approvals } };
10501
11131
  }
11132
+ /**
11133
+ * 过户交接第二步:目标页接管后摘掉来源页的持有权。同步且必须紧跟在 `insertTakeoverConvs`
11134
+ * 之后调用(中间不许有 await)——先插入后移除,交接期间对话始终至少有且只有一个持有方。
11135
+ */
11136
+ commitTakeoverRemoval(payload) {
11137
+ // 按对象身份摘,不按 id:`insertTakeoverConvs` 在目标页撞号时会把 conv.id 重编,
11138
+ // 那时来源页 map 的 key 还是旧 id,按 id 删会漏(留下一条「已搬走却还在」的幽灵行)。
11139
+ const moved = new Set(payload.convs);
11140
+ for (const [id, conv] of this.convs)
11141
+ if (moved.has(conv))
11142
+ this.convs.delete(id);
11143
+ if (!this.convs.has(this.activeId)) {
11144
+ const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
11145
+ if (fallback)
11146
+ this.activeId = fallback.id;
11147
+ }
11148
+ }
11149
+ async detachTakeoverConversations(ids) {
11150
+ const prepared = await this.prepareTakeoverConversations(ids);
11151
+ if (prepared.ok)
11152
+ this.commitTakeoverRemoval(prepared.payload);
11153
+ return prepared;
11154
+ }
10502
11155
  insertTakeoverConvs(payload) {
10503
11156
  if (this.botExecution)
10504
11157
  throw new Error("Bot sessions cannot receive transferred conversations");
@@ -10647,13 +11300,27 @@ export class ClientSession {
10647
11300
  this.activeId = fallback.id;
10648
11301
  }
10649
11302
  }
11303
+ /**
11304
+ * 只有在真的往项目里发了消息时才算「最近对话」:刷新项目 `lastUsed` 并推给客户端,
11305
+ * 这样左栏项目顺序只会因为对话而变,浏览/切换不会。
11306
+ */
11307
+ markProjectConversationActivity(cwd) {
11308
+ if (!this.stateStore || !cwd)
11309
+ return;
11310
+ try {
11311
+ this.stateStore.remember(this.clientId, cwd);
11312
+ // 推送失败不影响发消息本身(假体会话、断连、无工作区都会在这里抛)
11313
+ void this.pushProjects().catch(() => { });
11314
+ }
11315
+ catch { }
11316
+ }
10650
11317
  applyCwdSideEffects(abs) {
10651
11318
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
10652
11319
  try {
10653
11320
  this.onCwdChanged?.(abs, this.roots);
10654
11321
  }
10655
11322
  catch { }
10656
- this.stateStore.remember(this.clientId, abs);
11323
+ this.stateStore.remember(this.clientId, abs, { promote: false });
10657
11324
  this.invalidateProjectsCache();
10658
11325
  void this.pushProjects();
10659
11326
  this.refreshSessionsOnSwitch();
@@ -10788,43 +11455,56 @@ export class ClientSession {
10788
11455
  continue;
10789
11456
  let messageCount = 0;
10790
11457
  let isStreaming = false;
11458
+ let sessionId;
11459
+ let sessionFile;
10791
11460
  try {
10792
11461
  messageCount = conv.session.getSessionStats().totalMessages;
10793
11462
  isStreaming = conv.session.isStreaming;
11463
+ sessionId = conv.session.sessionId;
11464
+ sessionFile = conv.session.sessionFile;
10794
11465
  }
10795
11466
  catch { }
11467
+ const completionPending = this.completionPending(conv);
11468
+ const parentId = this.localParentId(conv);
11469
+ const pendingQuestion = this.getPendingQuestionForConv(conv.id);
11470
+ let modified = sessionFile ? ClientSession.conversationFileMtime(sessionFile) : undefined;
11471
+ if (conv.nativeCli) {
11472
+ const cliTime = Math.max(conv.nativeCli.status?.lastActivityAt ?? 0, conv.nativeCli.status?.updatedAt ?? 0);
11473
+ if (cliTime > 0)
11474
+ modified = Math.max(modified ?? 0, cliTime);
11475
+ }
10796
11476
  conversations.push({
10797
11477
  id: conv.id,
11478
+ rowKind: conversationRowKind({
11479
+ isStreaming,
11480
+ completionPending,
11481
+ hasQuestion: Boolean(pendingQuestion),
11482
+ isSubagent: !!conv.isSubagent,
11483
+ parentId,
11484
+ pinned: conv.pinned,
11485
+ isEphemeral: conv.isEphemeral,
11486
+ nativeCli: conv.nativeCli,
11487
+ hasHistoryRow: Boolean(sessionFile),
11488
+ forceOpen: visibleParents.has(conv.id),
11489
+ }),
10798
11490
  ...(conv.nativeCli ? { nativeCli: conv.nativeCli } : {}),
10799
11491
  independent: conv.independent !== false,
10800
11492
  title: conv.title,
10801
11493
  cwd: conv.cwd,
10802
11494
  messageCount,
10803
11495
  isStreaming,
10804
- completionPending: this.completionPending(conv),
11496
+ completionPending,
10805
11497
  isSubagent: !!conv.isSubagent,
10806
11498
  ...(conv.isEphemeral ? { isEphemeral: true } : {}),
10807
- ...(() => {
10808
- try {
10809
- const sid = conv.session.sessionId;
10810
- const f = conv.session.sessionFile;
10811
- const modified = f ? ClientSession.conversationFileMtime(f) : undefined;
10812
- return {
10813
- ...(sid ? { sessionId: sid } : {}),
10814
- ...(f ? { sessionFile: f } : {}),
10815
- ...(modified ? { modified } : {}),
10816
- };
10817
- }
10818
- catch {
10819
- return {};
10820
- }
10821
- })(),
11499
+ ...(sessionId ? { sessionId } : {}),
11500
+ ...(sessionFile ? { sessionFile } : {}),
11501
+ ...(modified ? { modified } : {}),
10822
11502
  ...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
10823
- ...(() => {
10824
- const pq = this.getPendingQuestionForConv(conv.id);
10825
- return pq ? { hasQuestion: true, questionId: pq.id, questionTitle: pq.title } : {};
10826
- })(),
10827
- parentId: this.localParentId(conv),
11503
+ ...(conv.subagentEvidence ? { subagentVerdict: conv.subagentEvidence.verdict } : {}),
11504
+ ...(pendingQuestion
11505
+ ? { hasQuestion: true, questionId: pendingQuestion.id, questionTitle: pendingQuestion.title }
11506
+ : {}),
11507
+ parentId,
10828
11508
  model: conv.session.model
10829
11509
  ? `${conv.session.model.provider}/${conv.session.model.id}`
10830
11510
  : (conv.subagentTemplate?.model ?? undefined),
@@ -10832,6 +11512,7 @@ export class ClientSession {
10832
11512
  ...(conv.pinned ? { pinned: true } : {}),
10833
11513
  ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
10834
11514
  ...(conv.forkFrom ? { forkFrom: conv.forkFrom } : {}),
11515
+ ...(conv.forkFrom || conv.forkedFromSessionPath ? { forked: true } : {}),
10835
11516
  });
10836
11517
  }
10837
11518
  try {
@@ -10856,6 +11537,12 @@ export class ClientSession {
10856
11537
  }
10857
11538
  lastRunningSig = "";
10858
11539
  sessionsRequested = false;
11540
+ /**
11541
+ * 会话跑完一轮后按它自己的 cwd 补推列表的节流句柄(cwd key → timer)。
11542
+ * 服务端在内容变化时只做缓存失效、不推送:前端「运行中」分组把会话移走之后,
11543
+ * 所属项目的会话列表里也没有它,得手点项目发一次 list_sessions 重新扫盘才出现。
11544
+ */
11545
+ sessionsPushTimers = new Map();
10859
11546
  static projectsCache = null;
10860
11547
  static PROJECTS_CACHE_TTL = 60_000;
10861
11548
  static projectsInFlight = null;
@@ -10884,13 +11571,15 @@ export class ClientSession {
10884
11571
  static sessionInfosGeneration = 0;
10885
11572
  static SESSION_INFO_CACHE_TTL = 30_000;
10886
11573
  static SESSION_LIST_PARSE_EXTRA = 60;
11574
+ /** 一页至少要这么多条(客户端首屏要的就是这个数)。 */
11575
+ static SESSION_LIST_MIN = 20;
10887
11576
  static SESSION_LIST_DEFAULT = 200;
10888
11577
  static SESSION_LIST_MAX = 5000;
10889
11578
  static SESSION_LIST_PARSE_LIMIT = ClientSession.SESSION_LIST_DEFAULT + ClientSession.SESSION_LIST_PARSE_EXTRA;
10890
11579
  async loadSessionInfos(forCwd, opts) {
10891
11580
  const targetCwd = forCwd ?? this.cwd;
10892
11581
  const listOnly = opts?.listOnly === true;
10893
- const listLimit = Math.max(ClientSession.SESSION_LIST_DEFAULT, opts?.listLimit ?? ClientSession.SESSION_LIST_DEFAULT);
11582
+ const listLimit = Math.max(ClientSession.SESSION_LIST_MIN, opts?.listLimit ?? ClientSession.SESSION_LIST_DEFAULT);
10894
11583
  const parseNeed = listOnly
10895
11584
  ? ClientSession.SESSION_LIST_PARSE_LIMIT + (listLimit - ClientSession.SESSION_LIST_DEFAULT)
10896
11585
  : Number.POSITIVE_INFINITY;
@@ -10914,6 +11603,10 @@ export class ClientSession {
10914
11603
  try {
10915
11604
  const projectDir = SessionManager.create(sessionBaseDir).getSessionDir();
10916
11605
  const extraRoot = piSessionsRoot() ? resolve(piSessionsRoot()) : undefined;
11606
+ // 磁盘索引(纯缓存):命中就不必再读文件内容,只用 readdir + stat 校对文件没变。
11607
+ const diskIndex = SessionListDiskIndex.open(this.stateStore?.dataDir, projectDir);
11608
+ await diskIndex?.ensureLoaded();
11609
+ let enumerationComplete = true;
10917
11610
  const candidateFiles = new Map();
10918
11611
  if (existsSync(projectDir)) {
10919
11612
  const dirEntries = await fsPromises.readdir(projectDir);
@@ -10943,7 +11636,10 @@ export class ClientSession {
10943
11636
  }
10944
11637
  }
10945
11638
  }
10946
- catch { }
11639
+ catch {
11640
+ // 枚举不全时不要根据 present 修剪索引,否则会把没枚举到的条目全删掉
11641
+ enumerationComplete = false;
11642
+ }
10947
11643
  }
10948
11644
  }
10949
11645
  if (candidateFiles.size === 0)
@@ -10971,11 +11667,26 @@ export class ClientSession {
10971
11667
  ownCount++;
10972
11668
  return cached.info;
10973
11669
  }
11670
+ // 磁盘索引命中:文件 mtime + size 没变,元信息直接用,省掉整份文件扫描。
11671
+ const indexed = diskIndex?.lookup(file);
11672
+ if (indexed) {
11673
+ if (generation === ClientSession.sessionInfosGeneration) {
11674
+ ClientSession.sessionFileCacheStore(file.path, {
11675
+ mtime: file.mtime,
11676
+ size: file.size,
11677
+ info: indexed.info,
11678
+ scan: indexed.scan,
11679
+ });
11680
+ }
11681
+ if (isOwn(indexed.info))
11682
+ ownCount++;
11683
+ return indexed.info;
11684
+ }
10974
11685
  if (ownCount >= parseLimit) {
10975
11686
  truncated = true;
10976
11687
  return null;
10977
11688
  }
10978
- const scanned = await scanSessionListInfo(file.path, file.mtime, cached?.scan);
11689
+ const scanned = await scanSessionListInfo(file.path, file.mtime, cached?.scan ?? diskIndex?.previousScan(file.path));
10979
11690
  const info = scanned?.info ?? null;
10980
11691
  if (info && scanned) {
10981
11692
  if (generation === ClientSession.sessionInfosGeneration) {
@@ -10986,11 +11697,13 @@ export class ClientSession {
10986
11697
  scan: scanned.state,
10987
11698
  });
10988
11699
  }
11700
+ diskIndex?.remember(file, scanned.state);
10989
11701
  if (isOwn(info))
10990
11702
  ownCount++;
10991
11703
  }
10992
11704
  return info;
10993
11705
  });
11706
+ diskIndex?.reconcile(new Set(validStats.map((f) => normalizePathKey(f.path))), { prune: enumerationComplete });
10994
11707
  const validInfos = results.filter((info) => info !== null);
10995
11708
  const ownInfos = validInfos.filter(isOwn);
10996
11709
  const seenIds = new Set();
@@ -11081,11 +11794,40 @@ export class ClientSession {
11081
11794
  if (this.sessionsRequested)
11082
11795
  void this.refreshSessions();
11083
11796
  }
11797
+ /**
11798
+ * 会话跑完一轮后,按会话自己的 cwd 补推列表:第一轮立刻推,600ms 内的后续轮次
11799
+ * 合并成一次尾部推送。
11800
+ * 不推的话前端「运行中」分组随手把会话移走、左栏里又没有它;推迟 600ms 再推的话
11801
+ * 中间那段空窗就是「跑完闪一下不见了,过一会儿又冒出来」,所以首轮必须立刻推。
11802
+ */
11803
+ scheduleSessionsPush(cwd) {
11804
+ if (!cwd || this.disposed || !this.sessionsRequested)
11805
+ return;
11806
+ const key = normalizePathKey(cwd);
11807
+ // 这一轮刚写进会话文件:先让该项目的列表缓存失效,否则推出去还是旧列表。
11808
+ ClientSession.sessionInfosCache.delete(key);
11809
+ const pending = this.sessionsPushTimers.get(key);
11810
+ if (pending) {
11811
+ clearTimeout(pending);
11812
+ }
11813
+ else {
11814
+ void this.pushSessionsForCwd(cwd).catch(() => { });
11815
+ }
11816
+ const timer = setTimeout(() => {
11817
+ this.sessionsPushTimers.delete(key);
11818
+ if (this.disposed)
11819
+ return;
11820
+ ClientSession.sessionInfosCache.delete(key);
11821
+ void this.pushSessionsForCwd(cwd).catch(() => { });
11822
+ }, 600);
11823
+ timer.unref?.();
11824
+ this.sessionsPushTimers.set(key, timer);
11825
+ }
11084
11826
  sessionListLimits = new Map();
11085
11827
  setSessionListLimit(cwd, limit) {
11086
11828
  const key = normalizePathKey(cwd);
11087
11829
  if (typeof limit === "number" && Number.isFinite(limit)) {
11088
- const clamped = Math.min(ClientSession.SESSION_LIST_MAX, Math.max(ClientSession.SESSION_LIST_DEFAULT, Math.floor(limit)));
11830
+ const clamped = Math.min(ClientSession.SESSION_LIST_MAX, Math.max(ClientSession.SESSION_LIST_MIN, Math.floor(limit)));
11089
11831
  this.sessionListLimits.set(key, clamped);
11090
11832
  return clamped;
11091
11833
  }
@@ -11094,10 +11836,11 @@ export class ClientSession {
11094
11836
  async sessionListPayload(targetCwd) {
11095
11837
  const limit = this.setSessionListLimit(targetCwd);
11096
11838
  const infos = await this.loadSessionInfos(targetCwd, { listOnly: true, listLimit: limit });
11097
- const all = this.buildSessionSummaries(targetCwd, infos, Number.POSITIVE_INFINITY);
11839
+ // 多取一条只是为了判 hasMore:索引命中后 infos 可能是项目全量(上千条),没必要全建摘要。
11840
+ const page = this.buildSessionSummaries(targetCwd, infos, limit + 1);
11098
11841
  const cached = ClientSession.sessionInfosCache.get(normalizePathKey(targetCwd));
11099
- const hasMore = all.length > limit || (cached ? !cached.complete : false);
11100
- return { sessions: all.slice(0, limit), hasMore };
11842
+ const hasMore = page.length > limit || (cached ? !cached.complete : false);
11843
+ return { sessions: page.slice(0, limit), hasMore };
11101
11844
  }
11102
11845
  buildSessionSummaries(targetCwd, infos, limit = ClientSession.SESSION_LIST_DEFAULT) {
11103
11846
  const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
@@ -11353,6 +12096,10 @@ export class ClientSession {
11353
12096
  }
11354
12097
  this.emitConversations();
11355
12098
  this.flushSnapshot();
12099
+ // 历史行上的 📌 来自 sessions 摘要(`isSessionPinned`),emitConversations 不会动它:
12100
+ // 不推的话,取消钉住后图标要等点一下项目重新拉列表才消失。按会话自己的 cwd 推,
12101
+ // 在项目 A 里取消属于 B 的钉住时刷的也是 B 的列表。
12102
+ void this.pushSessionsForCwd(conv.cwd).catch(() => { });
11356
12103
  this.emit({
11357
12104
  type: "notice",
11358
12105
  level: "info",
@@ -11366,7 +12113,10 @@ export class ClientSession {
11366
12113
  }
11367
12114
  async pinSession(path, pinned) {
11368
12115
  const targetPath = resolve(path);
11369
- this.stateStore?.setSessionPinned(this.cwd, targetPath, pinned);
12116
+ // 置顶归属按会话自身 header 的 cwd 记账:在 A 项目里给 B 项目的会话点钉住,
12117
+ // 记录必须落在 B 名下,否则刷新后它会被当成 A 的置顶会话预打开(跨项目串台)。
12118
+ const pinCwd = await sessionOwnerCwd(targetPath, this.cwd);
12119
+ this.stateStore?.setSessionPinned(pinCwd, targetPath, pinned);
11370
12120
  for (const conv of this.convs.values()) {
11371
12121
  if (conv.session.sessionFile && resolve(conv.session.sessionFile) === targetPath) {
11372
12122
  if (pinned) {
@@ -11381,7 +12131,12 @@ export class ClientSession {
11381
12131
  }
11382
12132
  this.emitConversations();
11383
12133
  this.flushSnapshot();
11384
- await this.refreshSessions();
12134
+ // 摘要里的 pinned 按归属项目的 cwd 记账:与当前项目不同就推那一边的列表,
12135
+ // 否则在这边怎么刷都不会让另一边的图标变化。
12136
+ if (normalizePathKey(pinCwd) === normalizePathKey(this.cwd))
12137
+ await this.refreshSessions();
12138
+ else
12139
+ await this.pushSessionsForCwd(pinCwd);
11385
12140
  }
11386
12141
  async renameConversation(id, name) {
11387
12142
  try {
@@ -12755,7 +13510,7 @@ export class ClientSession {
12755
13510
  ClientSession.projectsInFlight = run;
12756
13511
  await run;
12757
13512
  }
12758
- withCurrentCwd(projects, now) {
13513
+ withCurrentCwd(projects, _now) {
12759
13514
  const currentKey = normalizePathKey(this.cwd);
12760
13515
  const removedKeys = new Set(this.stateStore.getRemovedProjects(this.clientId).map(normalizePathKey));
12761
13516
  const validProjects = projects.filter((p) => {
@@ -12769,10 +13524,11 @@ export class ClientSession {
12769
13524
  list = validProjects;
12770
13525
  }
12771
13526
  else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
12772
- list = validProjects.map((p) => normalizePathKey(p.path) === currentKey ? { ...p, lastUsed: Math.max(p.lastUsed, now) } : p);
13527
+ // 当前项目不刷时间:项目顺序只认真实对话,切过去看看不该把它顶到最新
13528
+ list = validProjects;
12773
13529
  }
12774
13530
  else {
12775
- list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, RECENT_PROJECTS_MAX);
13531
+ list = [{ path: this.cwd, lastUsed: 0 }, ...validProjects].slice(0, RECENT_PROJECTS_MAX);
12776
13532
  }
12777
13533
  const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
12778
13534
  for (const sbx of this.sandboxes.list()) {
@@ -12795,8 +13551,8 @@ export class ClientSession {
12795
13551
  async listFiles(relPath) {
12796
13552
  return this.files.listFiles(relPath);
12797
13553
  }
12798
- async searchFiles(query, reqId) {
12799
- return this.files.searchFiles(query, reqId);
13554
+ async searchFiles(query, reqId, scope) {
13555
+ return this.files.searchFiles(query, reqId, scope);
12800
13556
  }
12801
13557
  sessionSearchController;
12802
13558
  async searchSessions(query, reqId) {
@@ -13669,6 +14425,9 @@ export class ClientSession {
13669
14425
  clearTimeout(this.sessionsTimer);
13670
14426
  this.sessionsTimer = null;
13671
14427
  }
14428
+ for (const timer of this.sessionsPushTimers.values())
14429
+ clearTimeout(timer);
14430
+ this.sessionsPushTimers.clear();
13672
14431
  if (this.widgetsTimer) {
13673
14432
  clearInterval(this.widgetsTimer);
13674
14433
  this.widgetsTimer = null;
@@ -13700,6 +14459,8 @@ export class ClientSession {
13700
14459
  waiters.clear();
13701
14460
  }
13702
14461
  this.turnEndWaiters.clear();
14462
+ this.subagentSettle.shutdown();
14463
+ void this.subagentLedger.flush().catch(() => { });
13703
14464
  try {
13704
14465
  for (const id of this.convs.keys()) {
13705
14466
  this.getClaimStore?.().releaseByOwner(id);
@@ -13707,6 +14468,9 @@ export class ClientSession {
13707
14468
  }
13708
14469
  catch { }
13709
14470
  this.bg.stop();
14471
+ // jobs 是后台任务 WIP 特性新增的字段:测试替身(fakeClientSession)可能没初始化它,
14472
+ // 释放路径必须容忍缺失,别让 dispose 本身炸掉。
14473
+ this.jobs?.dispose?.();
13710
14474
  for (const conv of this.convs.values()) {
13711
14475
  this.clearConversationToolStates(conv);
13712
14476
  disposeEvalSession(conv.id);