pi-web-ui 0.119.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 (136) hide show
  1. package/CHANGELOG.md +79 -0
  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 +803 -106
  6. package/dist/server/atomic-file.js +130 -5
  7. package/dist/server/bash-timeout.js +15 -0
  8. package/dist/server/bash-tool.js +68 -4
  9. package/dist/server/bg-servers.js +19 -13
  10. package/dist/server/canvas/canvas-dispatch.js +12 -1
  11. package/dist/server/client-state.js +56 -14
  12. package/dist/server/conversation-tool.js +3 -2
  13. package/dist/server/delegate-task.js +8 -8
  14. package/dist/server/device-center/group-router-runtime.js +2 -0
  15. package/dist/server/device-center/hub-upgrade.js +5 -10
  16. package/dist/server/dispatch-domain-handlers.js +96 -22
  17. package/dist/server/dispatch-plugin-handlers.js +10 -0
  18. package/dist/server/dsh/dsh-agent-service.js +9 -9
  19. package/dist/server/durable/durable-agent-service.js +1 -1
  20. package/dist/server/files-service.js +41 -19
  21. package/dist/server/fs-copy.js +93 -0
  22. package/dist/server/goal-review-gate.js +2 -2
  23. package/dist/server/index.js +15 -0
  24. package/dist/server/job-runner.js +345 -0
  25. package/dist/server/marker-service.js +42 -26
  26. package/dist/server/model-session.js +16 -0
  27. package/dist/server/phone-tool.js +167 -0
  28. package/dist/server/plan-mode.js +2 -2
  29. package/dist/server/plugin-api-catalog.js +1 -1
  30. package/dist/server/plugin-bundled.js +35 -28
  31. package/dist/server/plugin-installer.js +15 -0
  32. package/dist/server/plugin-manifest-validate.js +10 -0
  33. package/dist/server/plugin-materialize.js +161 -0
  34. package/dist/server/plugin-paths.js +60 -0
  35. package/dist/server/plugin-removal.js +16 -3
  36. package/dist/server/plugin-schedule.js +8 -7
  37. package/dist/server/plugin-secrets.js +7 -3
  38. package/dist/server/plugin-updater.js +2 -4
  39. package/dist/server/plugins.js +74 -38
  40. package/dist/server/preset-fields.js +9 -9
  41. package/dist/server/process-utils.js +11 -0
  42. package/dist/server/project-scripts.js +38 -0
  43. package/dist/server/prompt-composer.js +40 -21
  44. package/dist/server/protocol-version.js +1 -1
  45. package/dist/server/quick-ask.js +3 -0
  46. package/dist/server/remote-ssh-service.js +39 -0
  47. package/dist/server/scm-commitmsg.js +2 -1
  48. package/dist/server/serialize.js +8 -0
  49. package/dist/server/session-list-index.js +246 -0
  50. package/dist/server/session-list-scan.js +5 -0
  51. package/dist/server/session-parser.js +16 -0
  52. package/dist/server/settings-service.js +39 -6
  53. package/dist/server/subagent-budget.js +68 -0
  54. package/dist/server/subagent-evidence.js +297 -0
  55. package/dist/server/subagent-helpers.js +12 -0
  56. package/dist/server/subagent-ledger.js +401 -0
  57. package/dist/server/subagent-notify.js +6 -2
  58. package/dist/server/subagent-security-gate.js +2 -2
  59. package/dist/server/subagent-settle.js +71 -0
  60. package/dist/server/subagents.js +497 -79
  61. package/dist/server/tabs.js +8 -1
  62. package/dist/server/terminals.js +0 -1
  63. package/dist/server/tool-manager.js +90 -16
  64. package/dist/server/tool-prompts.js +5 -1
  65. package/dist/server/universal/universal-service.js +1 -1
  66. package/dist/server/universal/universal-session.js +45 -7
  67. package/dist/server/vision-bridge.js +2 -0
  68. package/dist/server/workspace-handle.js +119 -17
  69. package/dist/server/workspace-queue.js +37 -0
  70. package/docs/README.md +25 -23
  71. package/docs/architecture-plugins.md +23 -3
  72. package/docs/device-center.md +1 -1
  73. package/package.json +15 -3
  74. package/plugins/catalog.json +13 -2
  75. package/themes/bases/flow-base.css +7 -16
  76. package/web/dist/.build-assets.json +1 -1
  77. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  78. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  79. package/web/dist/assets/{CanvasStudio-2ydYbnpW.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  80. package/web/dist/assets/{CanvasStudio-DizWvRjn.js → CanvasStudio-DU6O3N4u.js} +3 -3
  81. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  82. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  83. package/web/dist/assets/{DeviceExecutionSettings-B7R9ONaq.js → DeviceExecutionSettings-qJzbI0Cf.js} +1 -1
  84. package/web/dist/assets/{DeviceGroups-DFU4cv5b.js → DeviceGroups-DPrQxW6B.js} +1 -1
  85. package/web/dist/assets/{DeviceGroups-DoaQcxKj.js → DeviceGroups-DoucyUjI.js} +1 -1
  86. package/web/dist/assets/{Dropdown-Btjt6Dzh.js → Dropdown-kj_NIj6e.js} +1 -1
  87. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  88. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  89. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  90. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  91. package/web/dist/assets/{GroupConversation-DwZZrMuE.js → GroupConversation-1-lsPO1f.js} +3 -3
  92. package/web/dist/assets/{GroupConversation-KOi8sa5b.js → GroupConversation-HeiyW_O_.js} +3 -3
  93. package/web/dist/assets/{GroupWorkItems-FqAL74bC.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  94. package/web/dist/assets/{HintTip-BOwPzBGR.js → HintTip-DFhoclDw.js} +1 -1
  95. package/web/dist/assets/{ModelConfigModal-DLIfWKdB.js → ModelConfigModal-D2Ro-jUZ.js} +2 -2
  96. package/web/dist/assets/{ModelConfigModal-B140kWrs.js → ModelConfigModal-DPc9R1pq.js} +2 -2
  97. package/web/dist/assets/{NativeCliPanel-BwiLazSq.js → NativeCliPanel-B108d697.js} +3 -3
  98. package/web/dist/assets/{NativeCliPanel-U0F_EfAU.js → NativeCliPanel-DupvGwQM.js} +3 -3
  99. package/web/dist/assets/{PiSetupModal-Dc7EQ4L3.js → PiSetupModal-D0HitBfd.js} +1 -1
  100. package/web/dist/assets/{ProviderOAuthControls-C3opmPhu.js → ProviderOAuthControls-BLKUEDde.js} +1 -1
  101. package/web/dist/assets/{SCMPanel-BBxQfmq9.js → SCMPanel-DDbWrUHR.js} +1 -1
  102. package/web/dist/assets/{SCMPanel-D2t97Vvr.js → SCMPanel-DluNcd2-.js} +1 -1
  103. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  104. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  105. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  106. package/web/dist/assets/{TermXterm-B6nCtO2b.js → TermXterm-SYc-MUk2.js} +1 -1
  107. package/web/dist/assets/{TerminalPanel-BWB3iSeN.js → TerminalPanel-CgA_lhVT.js} +1 -1
  108. package/web/dist/assets/{TerminalPanel-CAV2SosY.js → TerminalPanel-vdSIOPjD.js} +1 -1
  109. package/web/dist/assets/{TuiOverlayModal-B0jBPOMc.js → TuiOverlayModal-Cy1jYYIw.js} +1 -1
  110. package/web/dist/assets/{TuiOverlayModal-DGd6fzU6.js → TuiOverlayModal-kXY_4hV8.js} +1 -1
  111. package/web/dist/assets/{app-globals-CR8Ls9nE.js → app-globals-CBEscsYP.js} +9 -9
  112. package/web/dist/assets/{canvas-client-B0lkqTtF.js → canvas-client-Clsypfs6.js} +1 -1
  113. package/web/dist/assets/{desktop-BME3DkyE.js → desktop-C6D9a8HZ.js} +1 -1
  114. package/web/dist/assets/index-BD29OL9L.js +404 -0
  115. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  116. package/web/dist/assets/index-DB55rbKC.css +1 -0
  117. package/web/dist/assets/{plugin-host-CVgcdBOk.js → plugin-host-VWBcq-LQ.js} +1 -1
  118. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  119. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  120. package/web/dist/index.html +10 -10
  121. package/web/dist/sw.js +1 -1
  122. package/web/dist/assets/BgTasksModal-CVHW1lRA.js +0 -1
  123. package/web/dist/assets/BgTasksModal-t5hxW1H6.js +0 -1
  124. package/web/dist/assets/DeviceCenter-CPaZNBJE.js +0 -3
  125. package/web/dist/assets/DeviceCenter-DsVakAYR.js +0 -3
  126. package/web/dist/assets/FilePreview-QGQfD2lV.js +0 -2
  127. package/web/dist/assets/FilePreview-qez9walH.js +0 -2
  128. package/web/dist/assets/GlobalSearchModal-B-cnTDJ5.js +0 -1
  129. package/web/dist/assets/GlobalSearchModal-BvbafjdU.js +0 -1
  130. package/web/dist/assets/SettingsModal-BqPQNUwF.js +0 -34
  131. package/web/dist/assets/SettingsModal-l7eeV-Rq.js +0 -34
  132. package/web/dist/assets/index-BBAQNi6v.js +0 -404
  133. package/web/dist/assets/index-BYW9d61A.js +0 -404
  134. package/web/dist/assets/index-BYWs88H2.css +0 -1
  135. package/web/dist/assets/remote-ssh-client-DEpvwgqG.js +0 -1
  136. package/web/dist/assets/theme-DVa7Z5Zu.js +0 -1
@@ -14,10 +14,13 @@ import { basename, delimiter, join, resolve } from "node:path";
14
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,6 +70,39 @@ 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
107
  import { answersFromMessage, conversationCommunication, formatCommunicationMessage, } from "./conversation-communication.js";
68
108
  import { requestContextExtension, enableRequestEvidence } from "./request-context.js";
@@ -78,8 +118,8 @@ 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";
@@ -95,7 +135,7 @@ import { makeCompactContextTool, buildCompactionInstructions, DEFAULT_KEEP_RECEN
95
135
  import { disposeAllEvalKernels, disposeEvalSession, makeEvalTool } from "./eval-tool.js";
96
136
  import { normalizeToolInfo } from "./tool-info.js";
97
137
  import { applyToolPromptOverrides, effectiveToolPrompt, toolPromptOverrideOf, } from "./tool-prompt-overrides.js";
98
- import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
138
+ import { collectSubagentDescendantIds, isSubagentTerminal, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
99
139
  import { makeDelegateTaskTool } from "./delegate-task.js";
100
140
  import { mergeConversationTools } from "./conversation-tool.js";
101
141
  import { makeConversationReadTool, toTranscriptInput, } from "./conversation-read-tool.js";
@@ -182,14 +222,16 @@ export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
182
222
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
183
223
  import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
184
224
  import { makeBrowserScriptTool } from "./browser-script-tool.js";
225
+ import { normalizePhoneCallTimeoutMs, collectPhoneArgs, formatPhoneCallResult, formatPhoneError, makePhoneTool, } from "./phone-tool.js";
185
226
  export { makeBrowserScriptTool };
186
227
  export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
187
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";
188
229
  export { workspacePath };
189
230
  import { mapSessionsConcurrent } from "./session-scan.js";
231
+ import { SessionListDiskIndex } from "./session-list-index.js";
190
232
  import { searchSessions as searchSessionTranscripts, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
191
233
  export { piSessionsRoot, isInsideSessionsDir };
192
- import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, } from "./session-parser.js";
234
+ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, parentSessionOfManager, } from "./session-parser.js";
193
235
  import { conversationRowKind } from "./conversation-rows.js";
194
236
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
195
237
  export { pickAdoptableOrphan, sameCwd };
@@ -260,6 +302,118 @@ export class ClientSession {
260
302
  pluginModelKeys = new Map();
261
303
  sharedModelRuntime;
262
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
+ }
263
417
  pendingSubagentNotices = new Map();
264
418
  deliveringSubagentNotices = new Map();
265
419
  pendingCliManagers = new Set();
@@ -280,11 +434,27 @@ export class ClientSession {
280
434
  getLang: () => this.getLang(),
281
435
  getUploadMaxBytes: () => (this.settingsSvc.current.workspaceUploadMaxMb ?? 100) * 1024 * 1024,
282
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
+ });
283
442
  bg = new BgServerTracker({
284
443
  emit: (msg) => this.emit(msg),
285
444
  flushSnapshot: () => this.flushSnapshot(),
286
445
  isDisposed: () => this.disposed,
287
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(),
288
458
  cleanupMinutes: () => this.settingsSvc.current.bgAutoCleanupMin ?? 0,
289
459
  workspaceCwd: () => this.convs.get(this.activeId)?.cwd ?? this.cwd,
290
460
  });
@@ -638,6 +808,55 @@ export class ClientSession {
638
808
  .catch(() => { });
639
809
  }
640
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
+ }
641
860
  spawningSubagents = 0;
642
861
  creatingConversations = new Map();
643
862
  reserveConversationSlot(cwd) {
@@ -698,7 +917,7 @@ export class ClientSession {
698
917
  const maxSubagents = getMaxSubagents();
699
918
  const liveSubagents = countActiveSubagents(this.convs.values(), this.spawningSubagents);
700
919
  if (liveSubagents >= maxSubagents) {
701
- 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 }));
702
921
  }
703
922
  }
704
923
  const quotaBase = parentId ? (this.convs.get(parentId)?.cwd ?? this.cwd) : this.cwd;
@@ -708,6 +927,15 @@ export class ClientSession {
708
927
  if (isEphemeralSubagent) {
709
928
  this.spawningSubagents++;
710
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
+ }
711
939
  let handedOffToConv = false;
712
940
  let pendingRuntime;
713
941
  let pendingTerminals;
@@ -899,6 +1127,7 @@ export class ClientSession {
899
1127
  };
900
1128
  signal?.addEventListener("abort", onSpawnAbort, { once: true });
901
1129
  holder.assertSubagentWorktreeAdmission(conv);
1130
+ this.recordSubagentRunStart(conv, { prompt, template: apply?.name, persist: Boolean(persist) });
902
1131
  conv.kickoff = runtime.session
903
1132
  .sendUserMessage(prompt)
904
1133
  .catch((err) => {
@@ -927,6 +1156,9 @@ export class ClientSession {
927
1156
  return conv.id;
928
1157
  }
929
1158
  catch (error) {
1159
+ this.subagentSpawnBudget.refund(budgetRoot);
1160
+ if (registered)
1161
+ this.syncSubagentLedger(registered, { state: "failed", event: "spawn_failed" });
930
1162
  if (registered) {
931
1163
  const home = pendingRuntime && this.findConversationHome?.(pendingRuntime.session);
932
1164
  const holder = home?.session ?? this;
@@ -1050,6 +1282,25 @@ export class ClientSession {
1050
1282
  const max = this.settingsSvc.current.subagentMaxDepth ?? 0;
1051
1283
  return max > 0 && this.subagentDepthUnder(parentId) >= max;
1052
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
+ }
1053
1304
  subagentOwnerOf(convId) {
1054
1305
  return convId ? (this.resolveExecution(convId)?.session ?? this) : this;
1055
1306
  }
@@ -1092,6 +1343,75 @@ export class ClientSession {
1092
1343
  }
1093
1344
  return false;
1094
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
+ }
1095
1415
  async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal) {
1096
1416
  const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
1097
1417
  if (templateName && (!tpl || !tpl.enabled)) {
@@ -1145,6 +1465,7 @@ export class ClientSession {
1145
1465
  conv.subagentWorktreePromise = undefined;
1146
1466
  }
1147
1467
  })();
1468
+ void conv.subagentWorktreePromise.finally(() => this.syncSubagentLedger(conv, { event: "worktree_finalized" }));
1148
1469
  return conv.subagentWorktreePromise;
1149
1470
  }
1150
1471
  async stopSubagentTask(convId) {
@@ -1159,6 +1480,8 @@ export class ClientSession {
1159
1480
  await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1160
1481
  }
1161
1482
  const currentOwner = this.resolveExecution(conversationIdentity(conv))?.session;
1483
+ this.syncSubagentLedger(conv, { state: "canceled", event: "stopped" });
1484
+ this.subagentSettle.notify(conv.id);
1162
1485
  if (!currentOwner)
1163
1486
  return;
1164
1487
  currentOwner.scheduleSubagentCompletionNotice(conv);
@@ -1207,11 +1530,11 @@ export class ClientSession {
1207
1530
  const session = conv.session;
1208
1531
  if (session.isStreaming) {
1209
1532
  await session.sendUserMessage(message, { deliverAs: "steer" });
1210
- return;
1533
+ return { state: "delivered" };
1211
1534
  }
1212
1535
  if (conv.promptInFlight || !session.isIdle) {
1213
1536
  await session.steer(message);
1214
- return;
1537
+ return { state: "queued" };
1215
1538
  }
1216
1539
  const generation = (conv.subagentRunGeneration ?? 0) + 1;
1217
1540
  conv.subagentRunGeneration = generation;
@@ -1222,6 +1545,7 @@ export class ClientSession {
1222
1545
  conv.subagentConsumedByParent = false;
1223
1546
  conv.subagentError = undefined;
1224
1547
  conv.subagentErrorNotified = undefined;
1548
+ this.syncSubagentLedger(conv, { state: "running", event: "steer_restart" });
1225
1549
  const parentKey = this.parentExecutionKey(conv);
1226
1550
  if (parentKey) {
1227
1551
  const pending = this.pendingSubagentNotices.get(parentKey);
@@ -1268,6 +1592,7 @@ export class ClientSession {
1268
1592
  }
1269
1593
  })();
1270
1594
  this.emitConversations();
1595
+ return { state: "restarted" };
1271
1596
  }
1272
1597
  scheduleSubagentCompletionNotice(conv) {
1273
1598
  const parentId = this.parentExecutionKey ? this.parentExecutionKey(conv) : conv.parentId;
@@ -1296,6 +1621,7 @@ export class ClientSession {
1296
1621
  owner.emitConversations();
1297
1622
  if (owner.activeId === (this.subagentCurrentId?.(parentId) ?? parentId))
1298
1623
  owner.flushSnapshot();
1624
+ owner.subagentSettle.notifyAll();
1299
1625
  }
1300
1626
  drainSuspendedSubagents(conv) {
1301
1627
  if (!conv.suspendedSubagents || conv.suspendedSubagents.size === 0)
@@ -1568,6 +1894,8 @@ export class ClientSession {
1568
1894
  catch { }
1569
1895
  }
1570
1896
  notifyTurnEnd(conv) {
1897
+ this.subagentSettle.notify(conv.id);
1898
+ this.syncSubagentLedger(conv, { event: "turn_end" });
1571
1899
  if (conv.session.isIdle && !conv.retryState)
1572
1900
  this.releaseConversationClaims(conv);
1573
1901
  const set = this.turnEndWaiters.get(conv.id);
@@ -1636,6 +1964,10 @@ export class ClientSession {
1636
1964
  lazyLoadingOn() {
1637
1965
  return this.settingsSvc?.current.toolLazyLoading === true;
1638
1966
  }
1967
+ /** 按需加载实际生效?开关开 + 名单非空。名单为空 = 无工具可加载,等同关闭(不挂 load_tools、不出目录段)。 */
1968
+ lazyEffectiveOn() {
1969
+ return this.lazyLoadingOn() && this.lazyOnDemandSet().size > 0;
1970
+ }
1639
1971
  sessionHasTranscript(session) {
1640
1972
  try {
1641
1973
  return (session.state?.messages?.length ?? 0) > 0;
@@ -1644,17 +1976,30 @@ export class ClientSession {
1644
1976
  return false;
1645
1977
  }
1646
1978
  }
1979
+ lazyOnDemandSet() {
1980
+ try {
1981
+ return new Set(normalizeLazyOnDemandList(this.settingsSvc.current.toolOnDemandTools));
1982
+ }
1983
+ catch {
1984
+ return new Set();
1985
+ }
1986
+ }
1647
1987
  lazyLoadedFor(session, seedFromActive) {
1648
1988
  const existing = this.lazyLoadedBySession.get(session);
1649
1989
  if (existing)
1650
1990
  return existing;
1651
1991
  const seed = [];
1652
1992
  if (seedFromActive) {
1653
- const core = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
1993
+ const onDemand = this.lazyOnDemandSet();
1654
1994
  try {
1655
- for (const n of session.getActiveToolNames())
1656
- if (!core.has(n))
1657
- 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
+ }
1658
2003
  }
1659
2004
  catch { }
1660
2005
  }
@@ -1667,13 +2012,15 @@ export class ClientSession {
1667
2012
  if (!session || !this.lazyLoadingOn())
1668
2013
  return empty;
1669
2014
  try {
1670
- const all = this.allowedToolNames(session, conv);
2015
+ const { pending } = this.lazyPartition(session, conv);
2016
+ if (pending.length === 0)
2017
+ return empty;
1671
2018
  const active = new Set(session.getActiveToolNames());
1672
2019
  const names = [];
1673
2020
  const snippets = {};
1674
2021
  const infos = [];
1675
- for (const name of all) {
1676
- if (active.has(name) || name === LOAD_TOOLS_TOOL_NAME)
2022
+ for (const name of pending) {
2023
+ if (active.has(name) || isNeverLazyTool(name))
1677
2024
  continue;
1678
2025
  const def = session.getToolDefinition(name);
1679
2026
  const snippet = this.toolSnippetOf(def);
@@ -1702,7 +2049,14 @@ export class ClientSession {
1702
2049
  t.namespace.name.startsWith("mcp__") &&
1703
2050
  (t.exposure ?? "codemode") === "deferred")
1704
2051
  .map((t) => t.name));
1705
- 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));
1706
2060
  const snippets = {};
1707
2061
  const signatures = {};
1708
2062
  for (const name of names) {
@@ -1722,10 +2076,8 @@ export class ClientSession {
1722
2076
  return empty;
1723
2077
  }
1724
2078
  }
1725
- allowedToolNames(session, conv) {
1726
- const all = session.getAllTools().map((t) => t.name);
1727
- const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1728
- const allowed = new Set(filterToolsByPreset(all, preset));
2079
+ /** 禁用集单源:内置禁用 + 计划/委派/子代理闸门。插件硬禁用在注册层过滤,不在此处。 */
2080
+ disabledToolSet(session, conv, all) {
1729
2081
  const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
1730
2082
  if (conv?.planMode === true)
1731
2083
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
@@ -1741,8 +2093,24 @@ export class ClientSession {
1741
2093
  disabled.add(toolName);
1742
2094
  }
1743
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);
1744
2103
  return all.filter((n) => allowed.has(n) && !disabled.has(n));
1745
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
+ }
1746
2114
  toolSnippetOf(def) {
1747
2115
  if (!def)
1748
2116
  return "";
@@ -1760,6 +2128,15 @@ export class ClientSession {
1760
2128
  const base = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
1761
2129
  return all.filter((n) => base.has(n));
1762
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
+ }
1763
2140
  loadToolsHost(ownerId) {
1764
2141
  return {
1765
2142
  listLoadable: () => this.lazyToolCatalog(this.sessionOfOwner(ownerId), this.convOfOwner(ownerId)).infos,
@@ -1820,23 +2197,12 @@ export class ClientSession {
1820
2197
  };
1821
2198
  }
1822
2199
  const known = new Set(all);
2200
+ // 与 allowedToolNames 同一口径:预设 + 禁用集单源,避免两处手写分歧。
2201
+ // 插件硬禁用在注册层已过滤(不在 known 里),此处按未知处理,提示模型看目录。
1823
2202
  const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1824
- const allowed = new Set(filterToolsByPreset(all, preset));
1825
- const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
1826
- if (conv?.planMode === true)
1827
- for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
1828
- disabled.add(n);
1829
- if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
1830
- for (const t of all) {
1831
- if (!conv.subagentAllowedTools.has(t))
1832
- disabled.add(t);
1833
- }
1834
- }
1835
- if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
1836
- for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
1837
- disabled.add(toolName);
1838
- }
1839
- }
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)));
1840
2206
  const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1841
2207
  let activeNow = new Set();
1842
2208
  try {
@@ -1852,7 +2218,7 @@ export class ClientSession {
1852
2218
  });
1853
2219
  continue;
1854
2220
  }
1855
- if (name === LOAD_TOOLS_TOOL_NAME || LAZY_CORE_TOOL_NAMES.includes(name)) {
2221
+ if (isNeverLazyTool(name)) {
1856
2222
  rejected.push({
1857
2223
  name,
1858
2224
  reason: pick(lang, "常驻核心工具,无需加载", "always available without loading", "loadtools.always"),
@@ -1863,6 +2229,14 @@ export class ClientSession {
1863
2229
  rejected.push({ name, reason: pick(lang, "已经加载过了", "already loaded", "loadtools.already") });
1864
2230
  continue;
1865
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
+ }
1866
2240
  if (disabled.has(name)) {
1867
2241
  rejected.push({
1868
2242
  name,
@@ -1908,12 +2282,12 @@ export class ClientSession {
1908
2282
  }
1909
2283
  }
1910
2284
  autoActivateToolIfLoadable(session, conv, name) {
1911
- if (!this.lazyLoadingOn() ||
1912
- !name ||
1913
- name === LOAD_TOOLS_TOOL_NAME ||
1914
- LAZY_CORE_TOOL_NAMES.includes(name)) {
2285
+ if (!this.lazyLoadingOn() || !name || isNeverLazyTool(name)) {
1915
2286
  return;
1916
2287
  }
2288
+ // 名单制:只有名单里的才会被 JIT 激活,名单外常驻本就可用。
2289
+ if (!this.lazyOnDemandSet().has(name))
2290
+ return;
1917
2291
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1918
2292
  if (loaded.has(name))
1919
2293
  return;
@@ -1933,7 +2307,6 @@ export class ClientSession {
1933
2307
  const showSkills = presetShowsSkillCatalog(preset);
1934
2308
  const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
1935
2309
  const realCwd = restoreWorkspaceUriFromSessionDir(src.cwd);
1936
- const isRemote = isRemoteWorkspaceUri(realCwd);
1937
2310
  return {
1938
2311
  cwd: formatCwdForPrompt(realCwd),
1939
2312
  systemPromptFile: promptBase.system || undefined,
@@ -1951,14 +2324,6 @@ export class ClientSession {
1951
2324
  pluginSdk: join(getPkgRoot(), "plugin-sdk"),
1952
2325
  pluginsDir: join(this.stateStore.dataDir, "plugins"),
1953
2326
  appendFiles: [...promptBase.append],
1954
- windowsPersona: isRemote
1955
- ? buildRemoteWorkspacePersona(realCwd)
1956
- : process.platform === "win32"
1957
- ? WINDOWS_PERSONA
1958
- : "",
1959
- terminalGuidance: isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), preset)
1960
- ? TERMINAL_TOOLS_GUIDANCE
1961
- : "",
1962
2327
  markersGuidance: this.markerSvc.buildGuidance(),
1963
2328
  lang: this.getLang(),
1964
2329
  contextFiles: src.contextFiles,
@@ -2012,7 +2377,7 @@ export class ClientSession {
2012
2377
  }
2013
2378
  const loader = sess.resourceLoader;
2014
2379
  const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2015
- const lazyOn = this.lazyLoadingOn();
2380
+ const lazyOn = this.lazyEffectiveOn();
2016
2381
  const catalog = lazyOn
2017
2382
  ? this.promptToolCatalog(sess, conv)
2018
2383
  : {
@@ -2020,8 +2385,8 @@ export class ClientSession {
2020
2385
  snippets: {},
2021
2386
  signatures: {},
2022
2387
  };
2023
- const baseNames = lazyOn ? this.lazyBaselineNames(sess) : active;
2024
- const baseSet = new Set(baseNames);
2388
+ // 名单制:基线 = 常驻(允许集 - 名单,含核心 + load_tools),目录 = 名单(不重复列常驻)。
2389
+ const baseNames = lazyOn ? this.lazyResidentNames(sess, conv) : active;
2025
2390
  const snippets = {};
2026
2391
  const signatures = catalog.signatures ?? {};
2027
2392
  const guidelines = [];
@@ -2034,7 +2399,14 @@ export class ClientSession {
2034
2399
  if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
2035
2400
  snippets[name] = eff.promptSnippet.trim();
2036
2401
  }
2037
- 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)
2038
2410
  guidelines.push(...eff.promptGuidelines);
2039
2411
  }
2040
2412
  const texts = resolveSectionTexts(this.composeInputs({
@@ -2154,13 +2526,22 @@ export class ClientSession {
2154
2526
  const owner = parentId ? this.subagentOwnerOf(parentId) : this;
2155
2527
  return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal);
2156
2528
  },
2157
- completeSubagent: (selfId, summary) => {
2529
+ completeSubagent: (selfId, summary, evidenceInput) => {
2158
2530
  const owner = this.subagentOwnerOf(selfId);
2159
2531
  const conv = owner.convs.get(this.subagentCurrentId(selfId));
2160
2532
  if (!conv?.parentId)
2161
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" });
2162
2542
  conv.subagentTask = requestSubagentCompletion(conv.subagentTask ?? createSubagentTask(conv.notifyOnDone), summary);
2163
- return { accepted: true, taskPending: owner.subagentTaskPending(conv) };
2543
+ this.subagentSettle.notify(conv.id);
2544
+ return { ok: true, taskPending: owner.subagentTaskPending(conv), evidence };
2164
2545
  },
2165
2546
  finalizeSubagentWorktree: async (convId) => {
2166
2547
  const owner = this.subagentOwnerOf(convId);
@@ -2193,9 +2574,23 @@ export class ClientSession {
2193
2574
  const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
2194
2575
  const conv = owner.convs.get(curId);
2195
2576
  if (!conv?.session)
2196
- return;
2197
- 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);
2198
2591
  },
2592
+ getLedgerEvents: (runId, limit) => this.subagentLedger.events(runId, limit),
2593
+ resumeLedgerRun: (selfId, runId, message) => this.resumeSubagentRun(selfId, runId, message),
2199
2594
  stopSubagent: (convId) => this.stopSubagentTask(convId),
2200
2595
  getActiveConversationId: () => this.activeId,
2201
2596
  dismissSubagent: async (convId, opts) => {
@@ -2433,6 +2828,8 @@ export class ClientSession {
2433
2828
  }
2434
2829
  return undefined;
2435
2830
  }
2831
+ phoneSeq = 0;
2832
+ pendingPhoneCalls = new Map();
2436
2833
  pageSeq = 0;
2437
2834
  pendingPageCalls = new Map();
2438
2835
  constructor(clientId, cwd, agentDir, stateStore) {
@@ -2508,7 +2905,6 @@ export class ClientSession {
2508
2905
  },
2509
2906
  promptSnapshot: () => this.promptSnapshot(),
2510
2907
  getMarkerState: () => ({
2511
- markersEnabled: this.markerSvc.current.markersEnabled,
2512
2908
  disabledMarkers: [...this.markerSvc.current.disabledMarkers],
2513
2909
  markers: this.markerSvc.listForUi(),
2514
2910
  }),
@@ -2778,6 +3174,7 @@ export class ClientSession {
2778
3174
  });
2779
3175
  }
2780
3176
  await cs.bindSession();
3177
+ void cs.recoverSubagentRuns().catch(() => { });
2781
3178
  const globalDefault = stateStore.getDefaultModel();
2782
3179
  if (globalDefault) {
2783
3180
  const slash = globalDefault.indexOf("/");
@@ -2799,7 +3196,7 @@ export class ClientSession {
2799
3196
  conv.pinned = true;
2800
3197
  conv.listed = true;
2801
3198
  }
2802
- const pinnedPaths = botExecution ? [] : (cs.stateStore?.getPinnedSessions(cwd) ?? []);
3199
+ const pinnedPaths = botExecution ? [] : await pinnedPathsOwnedBy(cs.stateStore?.getPinnedSessions(cwd) ?? [], cwd);
2803
3200
  const maxOpenConversations = getMaxOpenConversations();
2804
3201
  for (const p of pinnedPaths) {
2805
3202
  if (cs.convs.size >= maxOpenConversations)
@@ -2918,10 +3315,6 @@ export class ClientSession {
2918
3315
  else if (process.platform === "win32") {
2919
3316
  out.push(WINDOWS_PERSONA);
2920
3317
  }
2921
- const presetForGuidance = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2922
- if (isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), presetForGuidance)) {
2923
- out.push(TERMINAL_TOOLS_GUIDANCE);
2924
- }
2925
3318
  const markerGuidance = this.markerSvc.buildGuidance();
2926
3319
  if (markerGuidance)
2927
3320
  out.push(markerGuidance);
@@ -3038,7 +3431,7 @@ export class ClientSession {
3038
3431
  const conv = this.convs.get(ownerId ?? this.activeId) ?? this.conv;
3039
3432
  const sess = conv?.session;
3040
3433
  const activeToolNames = sess ? sess.getActiveToolNames() : [];
3041
- const lazyOn = this.lazyLoadingOn();
3434
+ const lazyOn = this.lazyEffectiveOn();
3042
3435
  const catalog = lazyOn && sess
3043
3436
  ? this.promptToolCatalog(sess, conv)
3044
3437
  : {
@@ -3046,8 +3439,7 @@ export class ClientSession {
3046
3439
  snippets: {},
3047
3440
  signatures: {},
3048
3441
  };
3049
- const baseNames = lazyOn && sess ? this.lazyBaselineNames(sess) : activeToolNames;
3050
- const baseSet = new Set(baseNames);
3442
+ const baseNames = lazyOn && sess ? this.lazyResidentNames(sess, conv) : activeToolNames;
3051
3443
  const activeSnippets = {};
3052
3444
  const activeSignatures = catalog.signatures ?? {};
3053
3445
  const activeGuidelines = [];
@@ -3061,9 +3453,15 @@ export class ClientSession {
3061
3453
  if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
3062
3454
  activeSnippets[name] = eff.promptSnippet.trim();
3063
3455
  }
3064
- 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)
3065
3464
  activeGuidelines.push(...eff.promptGuidelines);
3066
- }
3067
3465
  }
3068
3466
  }
3069
3467
  const currentPreset = conv?.agentPreset ?? targetPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
@@ -3275,6 +3673,7 @@ export class ClientSession {
3275
3673
  }, (msg) => this.emit(msg), () => this.flushSnapshot()),
3276
3674
  makeAskUserQuestionTool(bridge, ownerId),
3277
3675
  makeBrowserPageTool(bridge, ownerId),
3676
+ makePhoneTool(bridge, ownerId),
3278
3677
  makeBrowserScriptTool(bridge, ownerId),
3279
3678
  makeConversationReadTool(this.conversationReadHost(), () => this.getLang(), {
3280
3679
  listClaims: (cwd) => (this.getClaimStore?.().list(cwd) ?? []).map((c) => ({
@@ -3569,6 +3968,9 @@ export class ClientSession {
3569
3968
  toolWatchdogs: new Map(),
3570
3969
  workspaceSnapshots: readWorkspaceSnapshotsFromSession(runtime.session.sessionManager),
3571
3970
  };
3971
+ const forkedFromSessionPath = parentSessionOfManager(runtime.session.sessionManager);
3972
+ if (forkedFromSessionPath)
3973
+ conv.forkedFromSessionPath = forkedFromSessionPath;
3572
3974
  if (conv.nativeCli)
3573
3975
  this.ensureNativeCliBinding(conv);
3574
3976
  conversationIdentity(conv);
@@ -3617,6 +4019,9 @@ export class ClientSession {
3617
4019
  for (const conv of this.convs.values()) {
3618
4020
  if (!conv.session.isStreaming)
3619
4021
  continue;
4022
+ // 子代理/持久化子会话由运行账本负责重启对账与续跑,不能当成普通标签页重新打开。
4023
+ if (conv.isSubagent || conv.parentId || conv.subagentPrompt)
4024
+ continue;
3620
4025
  let sessionFile;
3621
4026
  try {
3622
4027
  sessionFile = conv.session.sessionFile ?? undefined;
@@ -4756,6 +5161,8 @@ export class ClientSession {
4756
5161
  }
4757
5162
  case "turn_end": {
4758
5163
  this.emitRun(conv, { type: "turn_end" });
5164
+ // 这一轮写进会话文件后,所属项目的会话列表要跟着刷新(可能属于别的项目)。
5165
+ this.scheduleSessionsPush(conv.cwd);
4759
5166
  break;
4760
5167
  }
4761
5168
  case "message_update": {
@@ -5111,6 +5518,10 @@ export class ClientSession {
5111
5518
  const h = home();
5112
5519
  return h.session.pageCall(req, sig, h.convId);
5113
5520
  },
5521
+ phoneCall: (req, sig) => {
5522
+ const h = home();
5523
+ return h.session.phoneCall(req, sig, h.convId);
5524
+ },
5114
5525
  canSeeImages: () => home().session.canSeeImages(),
5115
5526
  transcribeToolImage: (image, signal) => home().session.transcribeToolImage(image, signal),
5116
5527
  };
@@ -5308,9 +5719,20 @@ export class ClientSession {
5308
5719
  const home = current();
5309
5720
  return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId);
5310
5721
  },
5311
- 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) => {
5312
5731
  const home = current();
5313
- 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);
5314
5736
  },
5315
5737
  getPendingConsults: () => {
5316
5738
  const home = current();
@@ -5568,6 +5990,7 @@ export class ClientSession {
5568
5990
  }
5569
5991
  }
5570
5992
  questionsChanged() {
5993
+ this.subagentSettle.notifyAll();
5571
5994
  for (const owner of new Set([this, ...(this.allSubagentSessions?.() ?? [])])) {
5572
5995
  for (const request of owner.pendingQuestions.values())
5573
5996
  owner.notifyUserQuestion(request);
@@ -6103,6 +6526,16 @@ export class ClientSession {
6103
6526
  }
6104
6527
  conv.pendingApprovals.clear();
6105
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
+ }
6106
6539
  for (const [id, p] of this.pendingPageCalls) {
6107
6540
  if (p.conversationId !== convId)
6108
6541
  continue;
@@ -6199,6 +6632,44 @@ export class ClientSession {
6199
6632
  this.emit({ type: "page_request", id, op: req.op, args: req.args, target: req.target, timeoutMs });
6200
6633
  });
6201
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
+ }
6202
6673
  resolvePageCall(id, ok, result, error, conversationId) {
6203
6674
  const pending = this.pendingPageCalls.get(id);
6204
6675
  if (conversationId && pending?.conversationId !== conversationId)
@@ -7096,15 +7567,12 @@ export class ClientSession {
7096
7567
  async setSettings(partial) {
7097
7568
  if (this.botExecution)
7098
7569
  throw new Error("Bot settings are fixed");
7099
- const { markersEnabled, disabledMarkers, quickPhrasesSeeded, ...rest } = partial;
7570
+ const { disabledMarkers, quickPhrasesSeeded, ...rest } = partial;
7100
7571
  if (quickPhrasesSeeded)
7101
7572
  this.stateStore.markQuickPhrasesSeeded();
7102
7573
  let markerChanged = false;
7103
- if (markersEnabled !== undefined || disabledMarkers !== undefined) {
7104
- this.markerSvc.setAll({
7105
- ...(markersEnabled !== undefined ? { markersEnabled } : {}),
7106
- ...(disabledMarkers !== undefined ? { disabledMarkers } : {}),
7107
- });
7574
+ if (disabledMarkers !== undefined) {
7575
+ this.markerSvc.setDisabledMarkers(disabledMarkers);
7108
7576
  markerChanged = true;
7109
7577
  }
7110
7578
  await this.settingsSvc.set(rest);
@@ -7137,6 +7605,19 @@ export class ClientSession {
7137
7605
  }
7138
7606
  }
7139
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
+ }
7140
7621
  async savePreset(name) {
7141
7622
  return this.settingsSvc.savePreset(name);
7142
7623
  }
@@ -7620,7 +8101,7 @@ export class ClientSession {
7620
8101
  };
7621
8102
  }
7622
8103
  else {
7623
- core = makeAdaptiveBashTool(makeKillableBashTool(cwd, convKills, () => this.getLang()), terminals
8104
+ core = makeAdaptiveBashTool(makeKillableBashTool(cwd, convKills, () => this.getLang(), this.jobs, () => ownerId), terminals
7624
8105
  ? makeTerminalBashTool(terminals, {
7625
8106
  cwd,
7626
8107
  defaultPersist: () => false,
@@ -7630,7 +8111,7 @@ export class ClientSession {
7630
8111
  notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
7631
8112
  lang: () => this.getLang(),
7632
8113
  })
7633
- : 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));
7634
8115
  }
7635
8116
  return core;
7636
8117
  };
@@ -7789,12 +8270,14 @@ export class ClientSession {
7789
8270
  }
7790
8271
  }
7791
8272
  let loadedNames = [];
7792
- const lazy = this.lazyLoadingOn();
8273
+ const lazy = this.lazyEffectiveOn();
7793
8274
  if (lazy) {
7794
8275
  try {
7795
8276
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
7796
8277
  loadedNames = [...loaded];
7797
- 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)) {
7798
8281
  disabled.add(name);
7799
8282
  }
7800
8283
  }
@@ -8544,6 +9027,7 @@ export class ClientSession {
8544
9027
  isStreaming: streaming,
8545
9028
  convId: conv.id,
8546
9029
  independent: conv.independent !== false,
9030
+ forked: Boolean(conv.forkFrom || conv.forkedFromSessionPath),
8547
9031
  hasQuestion: !!pq,
8548
9032
  ...(pq?.title ? { questionTitle: pq.title } : {}),
8549
9033
  ...(sessionFile ? { sessionFile } : {}),
@@ -8650,6 +9134,7 @@ export class ClientSession {
8650
9134
  this.flushSnapshot();
8651
9135
  return;
8652
9136
  }
9137
+ this.markProjectConversationActivity(conv.cwd);
8653
9138
  const promptAc = new AbortController();
8654
9139
  conv.activePromptAc = promptAc;
8655
9140
  this.markerSvc.clearActions(conv.id);
@@ -9377,6 +9862,61 @@ export class ClientSession {
9377
9862
  async listBgServers() {
9378
9863
  await this.bg.listAndPush();
9379
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
+ }
9380
9920
  refreshBgTasks() {
9381
9921
  this.bg.push();
9382
9922
  }
@@ -9384,6 +9924,35 @@ export class ClientSession {
9384
9924
  this.emit({ type: "notice", level, text, textEn });
9385
9925
  }
9386
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
+ }
9387
9956
  if (taskId) {
9388
9957
  const ok = this.pluginStopBgTask?.(taskId) ?? false;
9389
9958
  if (!ok) {
@@ -10397,6 +10966,9 @@ export class ClientSession {
10397
10966
  for (const fn of waiters)
10398
10967
  fn("gone");
10399
10968
  }
10969
+ this.syncSubagentLedger(conv, { state: "dismissed", event: "dismissed" });
10970
+ this.subagentSettle.notify(id);
10971
+ this.subagentSpawnBudget.forget(this.subagentRootId(id));
10400
10972
  try {
10401
10973
  this.getClaimStore?.().releaseByOwner(id);
10402
10974
  }
@@ -10457,6 +11029,10 @@ export class ClientSession {
10457
11029
  hasConversation(convId) {
10458
11030
  return this.convs.has(convId);
10459
11031
  }
11032
+ /** 这个 conv 对象当前是不是本页持有的那一个(过户回退时用来判断要不要重新 insert)。 */
11033
+ ownsConversation(conv) {
11034
+ return this.convs.get(conv.id) === conv;
11035
+ }
10460
11036
  takeoverBriefs() {
10461
11037
  return [...this.convs.values()].map((c) => {
10462
11038
  let sessionFile;
@@ -10475,7 +11051,16 @@ export class ClientSession {
10475
11051
  };
10476
11052
  });
10477
11053
  }
10478
- 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) {
10479
11064
  if (this.botExecution)
10480
11065
  return { ok: false, reason: "missing" };
10481
11066
  const set = new Set(ids);
@@ -10503,7 +11088,6 @@ export class ClientSession {
10503
11088
  delete conv.transferring;
10504
11089
  }
10505
11090
  for (const conv of convs) {
10506
- this.convs.delete(conv.id);
10507
11091
  this.pluginModelKeys?.delete(conv.id);
10508
11092
  this.clearAllToolWatchdogs(conv);
10509
11093
  conv.unsubscribe?.();
@@ -10516,15 +11100,6 @@ export class ClientSession {
10516
11100
  }
10517
11101
  this.goalSvc.notifyTakeover(conv);
10518
11102
  }
10519
- if (!this.convs.has(this.activeId)) {
10520
- const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
10521
- if (fallback) {
10522
- this.activeId = fallback.id;
10523
- }
10524
- else {
10525
- await this.newChat();
10526
- }
10527
- }
10528
11103
  const questions = [];
10529
11104
  for (const [qid, p] of this.pendingQuestions) {
10530
11105
  if (p.conversationId !== undefined && set.has(p.conversationId)) {
@@ -10554,6 +11129,29 @@ export class ClientSession {
10554
11129
  this.questionsChanged();
10555
11130
  return { ok: true, payload: { convs, questions, pageCalls, approvals } };
10556
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
+ }
10557
11155
  insertTakeoverConvs(payload) {
10558
11156
  if (this.botExecution)
10559
11157
  throw new Error("Bot sessions cannot receive transferred conversations");
@@ -10702,13 +11300,27 @@ export class ClientSession {
10702
11300
  this.activeId = fallback.id;
10703
11301
  }
10704
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
+ }
10705
11317
  applyCwdSideEffects(abs) {
10706
11318
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
10707
11319
  try {
10708
11320
  this.onCwdChanged?.(abs, this.roots);
10709
11321
  }
10710
11322
  catch { }
10711
- this.stateStore.remember(this.clientId, abs);
11323
+ this.stateStore.remember(this.clientId, abs, { promote: false });
10712
11324
  this.invalidateProjectsCache();
10713
11325
  void this.pushProjects();
10714
11326
  this.refreshSessionsOnSwitch();
@@ -10888,6 +11500,7 @@ export class ClientSession {
10888
11500
  ...(sessionFile ? { sessionFile } : {}),
10889
11501
  ...(modified ? { modified } : {}),
10890
11502
  ...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
11503
+ ...(conv.subagentEvidence ? { subagentVerdict: conv.subagentEvidence.verdict } : {}),
10891
11504
  ...(pendingQuestion
10892
11505
  ? { hasQuestion: true, questionId: pendingQuestion.id, questionTitle: pendingQuestion.title }
10893
11506
  : {}),
@@ -10899,6 +11512,7 @@ export class ClientSession {
10899
11512
  ...(conv.pinned ? { pinned: true } : {}),
10900
11513
  ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
10901
11514
  ...(conv.forkFrom ? { forkFrom: conv.forkFrom } : {}),
11515
+ ...(conv.forkFrom || conv.forkedFromSessionPath ? { forked: true } : {}),
10902
11516
  });
10903
11517
  }
10904
11518
  try {
@@ -10923,6 +11537,12 @@ export class ClientSession {
10923
11537
  }
10924
11538
  lastRunningSig = "";
10925
11539
  sessionsRequested = false;
11540
+ /**
11541
+ * 会话跑完一轮后按它自己的 cwd 补推列表的节流句柄(cwd key → timer)。
11542
+ * 服务端在内容变化时只做缓存失效、不推送:前端「运行中」分组把会话移走之后,
11543
+ * 所属项目的会话列表里也没有它,得手点项目发一次 list_sessions 重新扫盘才出现。
11544
+ */
11545
+ sessionsPushTimers = new Map();
10926
11546
  static projectsCache = null;
10927
11547
  static PROJECTS_CACHE_TTL = 60_000;
10928
11548
  static projectsInFlight = null;
@@ -10951,13 +11571,15 @@ export class ClientSession {
10951
11571
  static sessionInfosGeneration = 0;
10952
11572
  static SESSION_INFO_CACHE_TTL = 30_000;
10953
11573
  static SESSION_LIST_PARSE_EXTRA = 60;
11574
+ /** 一页至少要这么多条(客户端首屏要的就是这个数)。 */
11575
+ static SESSION_LIST_MIN = 20;
10954
11576
  static SESSION_LIST_DEFAULT = 200;
10955
11577
  static SESSION_LIST_MAX = 5000;
10956
11578
  static SESSION_LIST_PARSE_LIMIT = ClientSession.SESSION_LIST_DEFAULT + ClientSession.SESSION_LIST_PARSE_EXTRA;
10957
11579
  async loadSessionInfos(forCwd, opts) {
10958
11580
  const targetCwd = forCwd ?? this.cwd;
10959
11581
  const listOnly = opts?.listOnly === true;
10960
- 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);
10961
11583
  const parseNeed = listOnly
10962
11584
  ? ClientSession.SESSION_LIST_PARSE_LIMIT + (listLimit - ClientSession.SESSION_LIST_DEFAULT)
10963
11585
  : Number.POSITIVE_INFINITY;
@@ -10981,6 +11603,10 @@ export class ClientSession {
10981
11603
  try {
10982
11604
  const projectDir = SessionManager.create(sessionBaseDir).getSessionDir();
10983
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;
10984
11610
  const candidateFiles = new Map();
10985
11611
  if (existsSync(projectDir)) {
10986
11612
  const dirEntries = await fsPromises.readdir(projectDir);
@@ -11010,7 +11636,10 @@ export class ClientSession {
11010
11636
  }
11011
11637
  }
11012
11638
  }
11013
- catch { }
11639
+ catch {
11640
+ // 枚举不全时不要根据 present 修剪索引,否则会把没枚举到的条目全删掉
11641
+ enumerationComplete = false;
11642
+ }
11014
11643
  }
11015
11644
  }
11016
11645
  if (candidateFiles.size === 0)
@@ -11038,11 +11667,26 @@ export class ClientSession {
11038
11667
  ownCount++;
11039
11668
  return cached.info;
11040
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
+ }
11041
11685
  if (ownCount >= parseLimit) {
11042
11686
  truncated = true;
11043
11687
  return null;
11044
11688
  }
11045
- 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));
11046
11690
  const info = scanned?.info ?? null;
11047
11691
  if (info && scanned) {
11048
11692
  if (generation === ClientSession.sessionInfosGeneration) {
@@ -11053,11 +11697,13 @@ export class ClientSession {
11053
11697
  scan: scanned.state,
11054
11698
  });
11055
11699
  }
11700
+ diskIndex?.remember(file, scanned.state);
11056
11701
  if (isOwn(info))
11057
11702
  ownCount++;
11058
11703
  }
11059
11704
  return info;
11060
11705
  });
11706
+ diskIndex?.reconcile(new Set(validStats.map((f) => normalizePathKey(f.path))), { prune: enumerationComplete });
11061
11707
  const validInfos = results.filter((info) => info !== null);
11062
11708
  const ownInfos = validInfos.filter(isOwn);
11063
11709
  const seenIds = new Set();
@@ -11148,11 +11794,40 @@ export class ClientSession {
11148
11794
  if (this.sessionsRequested)
11149
11795
  void this.refreshSessions();
11150
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
+ }
11151
11826
  sessionListLimits = new Map();
11152
11827
  setSessionListLimit(cwd, limit) {
11153
11828
  const key = normalizePathKey(cwd);
11154
11829
  if (typeof limit === "number" && Number.isFinite(limit)) {
11155
- 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)));
11156
11831
  this.sessionListLimits.set(key, clamped);
11157
11832
  return clamped;
11158
11833
  }
@@ -11161,10 +11836,11 @@ export class ClientSession {
11161
11836
  async sessionListPayload(targetCwd) {
11162
11837
  const limit = this.setSessionListLimit(targetCwd);
11163
11838
  const infos = await this.loadSessionInfos(targetCwd, { listOnly: true, listLimit: limit });
11164
- const all = this.buildSessionSummaries(targetCwd, infos, Number.POSITIVE_INFINITY);
11839
+ // 多取一条只是为了判 hasMore:索引命中后 infos 可能是项目全量(上千条),没必要全建摘要。
11840
+ const page = this.buildSessionSummaries(targetCwd, infos, limit + 1);
11165
11841
  const cached = ClientSession.sessionInfosCache.get(normalizePathKey(targetCwd));
11166
- const hasMore = all.length > limit || (cached ? !cached.complete : false);
11167
- 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 };
11168
11844
  }
11169
11845
  buildSessionSummaries(targetCwd, infos, limit = ClientSession.SESSION_LIST_DEFAULT) {
11170
11846
  const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
@@ -11420,6 +12096,10 @@ export class ClientSession {
11420
12096
  }
11421
12097
  this.emitConversations();
11422
12098
  this.flushSnapshot();
12099
+ // 历史行上的 📌 来自 sessions 摘要(`isSessionPinned`),emitConversations 不会动它:
12100
+ // 不推的话,取消钉住后图标要等点一下项目重新拉列表才消失。按会话自己的 cwd 推,
12101
+ // 在项目 A 里取消属于 B 的钉住时刷的也是 B 的列表。
12102
+ void this.pushSessionsForCwd(conv.cwd).catch(() => { });
11423
12103
  this.emit({
11424
12104
  type: "notice",
11425
12105
  level: "info",
@@ -11433,7 +12113,10 @@ export class ClientSession {
11433
12113
  }
11434
12114
  async pinSession(path, pinned) {
11435
12115
  const targetPath = resolve(path);
11436
- 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);
11437
12120
  for (const conv of this.convs.values()) {
11438
12121
  if (conv.session.sessionFile && resolve(conv.session.sessionFile) === targetPath) {
11439
12122
  if (pinned) {
@@ -11448,7 +12131,12 @@ export class ClientSession {
11448
12131
  }
11449
12132
  this.emitConversations();
11450
12133
  this.flushSnapshot();
11451
- 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);
11452
12140
  }
11453
12141
  async renameConversation(id, name) {
11454
12142
  try {
@@ -12822,7 +13510,7 @@ export class ClientSession {
12822
13510
  ClientSession.projectsInFlight = run;
12823
13511
  await run;
12824
13512
  }
12825
- withCurrentCwd(projects, now) {
13513
+ withCurrentCwd(projects, _now) {
12826
13514
  const currentKey = normalizePathKey(this.cwd);
12827
13515
  const removedKeys = new Set(this.stateStore.getRemovedProjects(this.clientId).map(normalizePathKey));
12828
13516
  const validProjects = projects.filter((p) => {
@@ -12836,10 +13524,11 @@ export class ClientSession {
12836
13524
  list = validProjects;
12837
13525
  }
12838
13526
  else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
12839
- list = validProjects.map((p) => normalizePathKey(p.path) === currentKey ? { ...p, lastUsed: Math.max(p.lastUsed, now) } : p);
13527
+ // 当前项目不刷时间:项目顺序只认真实对话,切过去看看不该把它顶到最新
13528
+ list = validProjects;
12840
13529
  }
12841
13530
  else {
12842
- 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);
12843
13532
  }
12844
13533
  const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
12845
13534
  for (const sbx of this.sandboxes.list()) {
@@ -12862,8 +13551,8 @@ export class ClientSession {
12862
13551
  async listFiles(relPath) {
12863
13552
  return this.files.listFiles(relPath);
12864
13553
  }
12865
- async searchFiles(query, reqId) {
12866
- return this.files.searchFiles(query, reqId);
13554
+ async searchFiles(query, reqId, scope) {
13555
+ return this.files.searchFiles(query, reqId, scope);
12867
13556
  }
12868
13557
  sessionSearchController;
12869
13558
  async searchSessions(query, reqId) {
@@ -13736,6 +14425,9 @@ export class ClientSession {
13736
14425
  clearTimeout(this.sessionsTimer);
13737
14426
  this.sessionsTimer = null;
13738
14427
  }
14428
+ for (const timer of this.sessionsPushTimers.values())
14429
+ clearTimeout(timer);
14430
+ this.sessionsPushTimers.clear();
13739
14431
  if (this.widgetsTimer) {
13740
14432
  clearInterval(this.widgetsTimer);
13741
14433
  this.widgetsTimer = null;
@@ -13767,6 +14459,8 @@ export class ClientSession {
13767
14459
  waiters.clear();
13768
14460
  }
13769
14461
  this.turnEndWaiters.clear();
14462
+ this.subagentSettle.shutdown();
14463
+ void this.subagentLedger.flush().catch(() => { });
13770
14464
  try {
13771
14465
  for (const id of this.convs.keys()) {
13772
14466
  this.getClaimStore?.().releaseByOwner(id);
@@ -13774,6 +14468,9 @@ export class ClientSession {
13774
14468
  }
13775
14469
  catch { }
13776
14470
  this.bg.stop();
14471
+ // jobs 是后台任务 WIP 特性新增的字段:测试替身(fakeClientSession)可能没初始化它,
14472
+ // 释放路径必须容忍缺失,别让 dispose 本身炸掉。
14473
+ this.jobs?.dispose?.();
13777
14474
  for (const conv of this.convs.values()) {
13778
14475
  this.clearConversationToolStates(conv);
13779
14476
  disposeEvalSession(conv.id);