pi-web-ui 0.114.3 → 0.116.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.
- package/CHANGELOG.md +62 -1
- package/bin/pi-web-ui.mjs +90 -8
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +522 -32
- package/dist/server/agent-service.js +954 -402
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +42 -2
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +100 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +362 -13
- package/dist/server/device-center/collab-tool.js +824 -13
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +20 -0
- package/dist/server/device-center/execution-settings.js +213 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +392 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +186 -96
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +210 -0
- package/dist/server/device-center/group-context.js +179 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +233 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub-locks.js +320 -0
- package/dist/server/device-center/hub-page.js +13 -33
- package/dist/server/device-center/hub-webhooks.js +165 -0
- package/dist/server/device-center/hub.js +2379 -107
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +20 -1
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +430 -41
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/partition-log.js +293 -0
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +598 -41
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +203 -41
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +445 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +841 -8
- package/dist/server/dispatch-domain-handlers.js +35 -6
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/durable/durable-capabilities.js +11 -0
- package/dist/server/engine-probe.js +112 -1
- package/dist/server/global-loader.js +119 -19
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +222 -29
- package/dist/server/managed.js +2 -0
- package/dist/server/markers/builtins/services.js +123 -0
- package/dist/server/markers/builtins/todo.js +189 -0
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/model-admin.js +48 -6
- package/dist/server/model-enrich.js +10 -1
- package/dist/server/orchestrator.js +109 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +65 -7
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +44 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/reasoning-registry.js +207 -0
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/startup-banner.js +35 -0
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +52 -37
- package/dist/server/system-prompt-soul.js +41 -0
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/tool-manager.js +17 -9
- package/dist/server/unauthorized-page.js +319 -0
- package/dist/server/univer-service.js +448 -0
- package/dist/server/universal/drivers/dsh-driver.js +379 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/README.md +94 -0
- package/docs/architecture-plugins.md +946 -0
- package/docs/device-center.md +106 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +2 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
- package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
- package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
- package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
- package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
- package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
- package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
- package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
- package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
- package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
- package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
- package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
- package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
- package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
- package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
- package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
- package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
- package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
- package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-C6DwztqE.css +1 -0
- package/web/dist/assets/index-CuN802Sj.js +93 -0
- package/web/dist/assets/index-EH5Fw9fa.js +93 -0
- package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
- package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
- package/web/dist/assets/theme-D2l_mLNo.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
- package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
- package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
- package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
- package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
- package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
- package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
- package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
- package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
- package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
- package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
- package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
- package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
- package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
- package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
- package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
- package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
- package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
- package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
- package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
- package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
- package/web/dist/assets/index-DK3F5ZJo.js +0 -85
- package/web/dist/assets/index-DQMii2he.js +0 -85
- package/web/dist/assets/index-vwBnwzkr.css +0 -1
- package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
- package/web/dist/assets/theme-D2DMH6tH.js +0 -1
|
@@ -32,7 +32,7 @@ import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
|
|
|
32
32
|
import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
|
|
33
33
|
import { collectInstalledEngineTargets } from "./engine-probe.js";
|
|
34
34
|
import { checkPluginUpdates } from "./plugin-updater.js";
|
|
35
|
-
import { getAppVersion } from "./pkg-info.js";
|
|
35
|
+
import { getAppVersion, getPkgRoot } from "./pkg-info.js";
|
|
36
36
|
import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
|
|
37
37
|
import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundTask, shouldRetainActive, } from "./wait-subscription-scan.js";
|
|
38
38
|
import { looksLikeChainCorruption, repairSessionFile } from "./compaction-markers.js";
|
|
@@ -61,26 +61,21 @@ import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGa
|
|
|
61
61
|
import { readPermissionFromSession } from "./permission-preset.js";
|
|
62
62
|
import { McpBridge, getMcpToolServer } from "./mcp-bridge.js";
|
|
63
63
|
import { getBotExecution } from "./device-center/bot-execution.js";
|
|
64
|
+
import { checkGroupTaskPlanGuard } from "./device-center/group-plan-guard.js";
|
|
65
|
+
import { prepareBotExecutionSystemPrompt } from "./device-center/execution-system-prompt.js";
|
|
66
|
+
import { extractGroupContextMetrics, groupContextMessage, recordGroupContextMetrics, repairGroupContextRequest, } from "./device-center/group-context-message.js";
|
|
64
67
|
import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, readWorkspaceSnapshotsFromSession, appendWorkspaceSnapshotToSession, withWorkspaceSnapshotGate, } from "./workspace-snapshot.js";
|
|
65
68
|
import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
|
|
66
69
|
import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
|
|
67
70
|
import { createSubagentTask, restartSubagentTask, requestSubagentCompletion, isSubagentTaskPending, } from "./subagent-task.js";
|
|
68
71
|
import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
|
|
72
|
+
import { messageDeletionTargets, undeletedContextEntries } from "./message-deletion.js";
|
|
69
73
|
import { fillSkillContents } from "./skill-content-filler.js";
|
|
70
74
|
import { estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
|
|
71
75
|
import { makeCommunicateTool } from "./communicate-tool.js";
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
let address = communicationAddresses.get(endpoint);
|
|
76
|
-
if (!address) {
|
|
77
|
-
address = `comm-${++communicationAddressSequence}`;
|
|
78
|
-
communicationAddresses.set(endpoint, address);
|
|
79
|
-
}
|
|
80
|
-
return address;
|
|
81
|
-
}
|
|
82
|
-
import { conversationCommunication, } from "./conversation-communication.js";
|
|
83
|
-
import { executeContextBudgetPruning } from "./context-budget-runner.js";
|
|
76
|
+
import { conversationIdentity, bindConversationParent, hasConversationParentBinding, conversationParent, parentConversationIdentity, } from "./conversation-identity.js";
|
|
77
|
+
const communicationAddress = conversationIdentity;
|
|
78
|
+
import { conversationCommunication, formatCommunicationMessage, } from "./conversation-communication.js";
|
|
84
79
|
import { requestContextExtension, enableRequestEvidence } from "./request-context.js";
|
|
85
80
|
import { removeContextEvidence, withContextEvidenceRead, copyContextEvidence, buildContextEvidenceIndex, } from "./context-evidence.js";
|
|
86
81
|
import { installCompactionInstructions } from "./compaction-instructions.js";
|
|
@@ -143,6 +138,7 @@ import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./v
|
|
|
143
138
|
import { generateScmCommitMessage } from "./scm-commitmsg.js";
|
|
144
139
|
import { estimateBaseContext, estimateContextWeights, reconcileContextCategories, } from "./context-usage.js";
|
|
145
140
|
import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
|
|
141
|
+
import { createPromptBaseObservers, readPromptBase } from "./prompt-base-store.js";
|
|
146
142
|
import { listAllMcpServers, checkMcpServer, installMcpServer, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
|
|
147
143
|
import { fetchRemoteMcpMarket, fetchRemoteSkillMarket, fetchRemoteSkillContent } from "./market-service.js";
|
|
148
144
|
import { McpOAuthUi } from "./mcp-oauth-ui.js";
|
|
@@ -715,13 +711,14 @@ export class ClientSession {
|
|
|
715
711
|
// 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
|
|
716
712
|
// 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
|
|
717
713
|
// 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
|
|
718
|
-
conv.parentId = parent?.id ?? parentId
|
|
714
|
+
conv.parentId = parent?.id ?? parentId;
|
|
715
|
+
bindConversationParent(conv, parent);
|
|
719
716
|
conv.subagentType = type;
|
|
720
717
|
conv.subagentPrompt = prompt;
|
|
721
718
|
conv.subagentThinking = thinking;
|
|
722
719
|
conv.notifyOnDone = notifyOnDone ?? true;
|
|
723
720
|
conv.subagentTask = createSubagentTask(conv.notifyOnDone);
|
|
724
|
-
conv.subagentTaskPending = () => this.
|
|
721
|
+
conv.subagentTaskPending = () => this.resolveExecution(conversationIdentity(conv))?.session.subagentTaskPending(conv) ?? false;
|
|
725
722
|
// 安全模式与工具白名单(issue #727):优先从 extra 取,缺省按 type 与模板自动推导
|
|
726
723
|
const securityMode = extra?.securityMode ?? resolveSecurityMode(type, apply);
|
|
727
724
|
conv.subagentSecurityMode = securityMode;
|
|
@@ -753,7 +750,12 @@ export class ClientSession {
|
|
|
753
750
|
// 子代理会话同样订阅 SDK 事件:否则 onEvent 永不触发,点开查看时没有
|
|
754
751
|
// message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
|
|
755
752
|
// 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
|
|
756
|
-
conv.unsubscribe =
|
|
753
|
+
conv.unsubscribe = runtime.session.subscribe((event) => {
|
|
754
|
+
const owner = this.findConversationHome?.(runtime.session)?.session ?? spawnOwner;
|
|
755
|
+
if (owner.convs.get(conv.id) === conv && conv.runtime === runtime && conv.session === runtime.session) {
|
|
756
|
+
owner.onEvent(conv, event);
|
|
757
|
+
}
|
|
758
|
+
});
|
|
757
759
|
// 扩展绑定(rpc 模式);用 headless 的 Web UI context:
|
|
758
760
|
// 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
|
|
759
761
|
try {
|
|
@@ -846,16 +848,27 @@ export class ClientSession {
|
|
|
846
848
|
assertChildCurrent();
|
|
847
849
|
// 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
|
|
848
850
|
// 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
|
|
851
|
+
const generation = conv.subagentRunGeneration ?? 0;
|
|
852
|
+
const currentHolder = () => {
|
|
853
|
+
const owner = this.findConversationHome?.(runtime.session)?.session ?? this;
|
|
854
|
+
return owner.convs.get(conv.id) === conv &&
|
|
855
|
+
conv.runtime === runtime &&
|
|
856
|
+
conv.session === runtime.session &&
|
|
857
|
+
(conv.subagentRunGeneration ?? 0) === generation
|
|
858
|
+
? owner
|
|
859
|
+
: undefined;
|
|
860
|
+
};
|
|
849
861
|
const onSpawnAbort = () => {
|
|
850
862
|
// SDK sendUserMessage has no signal option; abort only the captured child session.
|
|
851
|
-
|
|
863
|
+
if (currentHolder())
|
|
864
|
+
void runtime.session.abort().catch(() => { });
|
|
852
865
|
};
|
|
853
866
|
signal?.addEventListener("abort", onSpawnAbort, { once: true });
|
|
854
867
|
holder.assertSubagentWorktreeAdmission(conv);
|
|
855
868
|
conv.kickoff = runtime.session
|
|
856
869
|
.sendUserMessage(prompt)
|
|
857
870
|
.catch((err) => {
|
|
858
|
-
|
|
871
|
+
currentHolder()?.emit({
|
|
859
872
|
type: "notice",
|
|
860
873
|
level: "error",
|
|
861
874
|
text: `子代理 ${conversationId} 启动失败: ${err instanceof Error ? err.message : String(err)}`,
|
|
@@ -864,8 +877,16 @@ export class ClientSession {
|
|
|
864
877
|
})
|
|
865
878
|
.finally(() => {
|
|
866
879
|
signal?.removeEventListener("abort", onSpawnAbort);
|
|
880
|
+
const owner = currentHolder();
|
|
881
|
+
if (!owner)
|
|
882
|
+
return;
|
|
867
883
|
conv.promptInFlight = false;
|
|
884
|
+
if (conv.isSubagent)
|
|
885
|
+
owner.scheduleSubagentCompletionNotice(conv);
|
|
886
|
+
owner.emitConversations();
|
|
868
887
|
});
|
|
888
|
+
// spawn 成功派发后解除与父工具信号的绑定;后续父对话停止不连带中止已派出的子代理(issue #833)
|
|
889
|
+
signal?.removeEventListener("abort", onSpawnAbort);
|
|
869
890
|
if (persist) {
|
|
870
891
|
holder.pushProjects().catch(() => { });
|
|
871
892
|
}
|
|
@@ -930,22 +951,70 @@ export class ClientSession {
|
|
|
930
951
|
}
|
|
931
952
|
getSubagentSnapshot(convId) {
|
|
932
953
|
const conv = this.convs.get(convId);
|
|
933
|
-
|
|
954
|
+
if (!conv?.session)
|
|
955
|
+
return undefined;
|
|
956
|
+
this.parentExecution(conv);
|
|
957
|
+
return toSubagentSnapshot(conv);
|
|
934
958
|
}
|
|
935
|
-
/**
|
|
936
|
-
* 旧 host 闭包仍指向源会话,按 id 全局查才能看到还在跑的子代理,而不是误判
|
|
937
|
-
* 「已移出/不存在」)。findSubagentOwner 按别名表把旧 id 解析成改名后的当前 id。 */
|
|
959
|
+
/** Resolve a stable execution address through its current holder. */
|
|
938
960
|
subagentSnapshotAnywhere(convId) {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
961
|
+
const found = this.resolveExecution(convId);
|
|
962
|
+
return found?.session.getSubagentSnapshot(found.convId);
|
|
963
|
+
}
|
|
964
|
+
/** One resolver for runtime identities. Bare ids are local, or globally unique. */
|
|
965
|
+
resolveExecutionAddress(id) {
|
|
966
|
+
if (id.startsWith("exec-")) {
|
|
967
|
+
for (const conv of this.convs.values())
|
|
968
|
+
if (conversationIdentity(conv) === id)
|
|
969
|
+
return conv.id;
|
|
970
|
+
return undefined;
|
|
971
|
+
}
|
|
972
|
+
return this.convs.has(id) ? id : undefined;
|
|
973
|
+
}
|
|
974
|
+
resolveExecution(id) {
|
|
975
|
+
const owners = new Set([this, ...(this.allSubagentSessions?.() ?? [])]);
|
|
976
|
+
if (id.startsWith("exec-")) {
|
|
977
|
+
for (const session of owners) {
|
|
978
|
+
for (const conv of session.convs.values()) {
|
|
979
|
+
if (conversationIdentity(conv) === id)
|
|
980
|
+
return { session, convId: conv.id, conv };
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
return undefined;
|
|
984
|
+
}
|
|
985
|
+
const local = this.convs.get(id);
|
|
986
|
+
if (local)
|
|
987
|
+
return { session: this, convId: local.id, conv: local };
|
|
988
|
+
const matches = [...owners].flatMap((session) => {
|
|
989
|
+
const conv = session.convs.get(id);
|
|
990
|
+
return conv ? [{ session, convId: conv.id, conv }] : [];
|
|
991
|
+
});
|
|
992
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
993
|
+
}
|
|
994
|
+
/** Bind legacy relations once; an absent parent remains absent even after id reuse. */
|
|
995
|
+
parentExecution(child) {
|
|
996
|
+
if (!hasConversationParentBinding(child)) {
|
|
997
|
+
const home = [...new Set([this, ...(this.allSubagentSessions?.() ?? [])])].find((owner) => owner.convs.get(child.id) === child);
|
|
998
|
+
const parent = child.parentId ? (home ?? this).resolveExecution(child.parentId)?.conv : undefined;
|
|
999
|
+
bindConversationParent(child, parent);
|
|
1000
|
+
}
|
|
1001
|
+
const parent = conversationParent(child);
|
|
1002
|
+
return parent ? this.resolveExecution(conversationIdentity(parent)) : undefined;
|
|
1003
|
+
}
|
|
1004
|
+
parentExecutionKey(child) {
|
|
1005
|
+
this.parentExecution(child);
|
|
1006
|
+
return parentConversationIdentity(child);
|
|
1007
|
+
}
|
|
1008
|
+
/** UI parent ids are meaningful only inside this holder's namespace. */
|
|
1009
|
+
localParentId(child) {
|
|
1010
|
+
const parent = this.parentExecution(child);
|
|
1011
|
+
return parent?.session === this ? parent.convId : undefined;
|
|
943
1012
|
}
|
|
944
1013
|
/** 由该父对话派出的子代理处在主对话下第几层:沿 parentId 链数祖先(主对话派的 = 1)。 */
|
|
945
1014
|
subagentDepthUnder(parentId) {
|
|
946
1015
|
let depth = 0;
|
|
947
1016
|
const seen = new Set();
|
|
948
|
-
for (let id = parentId; id && !seen.has(id); id = this.subagentSnapshotAnywhere(id)?.
|
|
1017
|
+
for (let id = parentId; id && !seen.has(id); id = this.subagentSnapshotAnywhere(id)?.parentExecutionId) {
|
|
949
1018
|
seen.add(id);
|
|
950
1019
|
depth++;
|
|
951
1020
|
}
|
|
@@ -958,62 +1027,48 @@ export class ClientSession {
|
|
|
958
1027
|
}
|
|
959
1028
|
/** B20:convId 当前由哪个 ClientSession 持有(本会话优先;查不到兜底本会话)。 */
|
|
960
1029
|
subagentOwnerOf(convId) {
|
|
961
|
-
|
|
962
|
-
return this;
|
|
963
|
-
if (this.convs.has(convId))
|
|
964
|
-
return this;
|
|
965
|
-
return this.findSubagentOwner?.(convId)?.session ?? this;
|
|
1030
|
+
return convId ? (this.resolveExecution(convId)?.session ?? this) : this;
|
|
966
1031
|
}
|
|
967
1032
|
/** B20:解析到当前(可能被过户改名)的对话 id;查不到原样返回。 */
|
|
968
1033
|
subagentCurrentId(convId) {
|
|
969
|
-
|
|
970
|
-
return convId;
|
|
971
|
-
return this.findSubagentOwner?.(convId)?.convId ?? convId;
|
|
1034
|
+
return this.resolveExecution(convId)?.convId ?? convId;
|
|
972
1035
|
}
|
|
973
1036
|
listSubagentSnapshots(scope, forSelfId) {
|
|
1037
|
+
for (const conv of this.convs.values())
|
|
1038
|
+
this.parentExecution(conv);
|
|
974
1039
|
const own = listSubagentSnapshots(this.convs.values(), scope);
|
|
975
1040
|
// B20:带 forSelfId 才并入会话外本族(祖先链能走到 forSelfId 的子代理,
|
|
976
1041
|
// 过户搬走后 wait_all 的「无参展开」与 list 仍能看到它们);不传 = 只列本会话。
|
|
977
1042
|
if (!forSelfId || !this.allSubagentSessions)
|
|
978
1043
|
return own;
|
|
979
|
-
const seen = new Set(own.map((s) => s.convId));
|
|
1044
|
+
const seen = new Set(own.map((s) => s.executionId ?? s.convId));
|
|
980
1045
|
const out = [...own];
|
|
981
1046
|
for (const other of this.allSubagentSessions()) {
|
|
982
1047
|
if (other === this)
|
|
983
1048
|
continue;
|
|
984
1049
|
for (const s of other.listSubagentSnapshots(scope)) {
|
|
985
|
-
if (seen.has(s.convId))
|
|
1050
|
+
if (seen.has(s.executionId ?? s.convId))
|
|
986
1051
|
continue;
|
|
987
1052
|
if (!this.subagentInFamilyOf(s, forSelfId))
|
|
988
1053
|
continue;
|
|
989
|
-
seen.add(s.convId);
|
|
1054
|
+
seen.add(s.executionId ?? s.convId);
|
|
990
1055
|
out.push(s);
|
|
991
1056
|
}
|
|
992
1057
|
}
|
|
993
1058
|
return out;
|
|
994
1059
|
}
|
|
995
|
-
/**
|
|
996
|
-
* 当前持有方 + 别名解析:过户撞 id 改名后,自省 id 与孩子们记录的 parentId
|
|
997
|
-
* 都可能还是建时旧 id(c1→c2),不比显式相等,比的是「解析后的当前 id」。 */
|
|
1060
|
+
/** Family membership follows bound object identities, never matching display ids. */
|
|
998
1061
|
subagentInFamilyOf(s, selfId) {
|
|
999
|
-
|
|
1062
|
+
const self = this.resolveExecution(selfId)?.conv;
|
|
1063
|
+
if (!self)
|
|
1064
|
+
return false;
|
|
1065
|
+
let cur = this.resolveExecution(s.executionId ?? s.convId)?.conv;
|
|
1000
1066
|
const seen = new Set();
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
if (
|
|
1005
|
-
return true;
|
|
1006
|
-
const found = this.findSubagentOwner?.(curId);
|
|
1007
|
-
if (!found)
|
|
1008
|
-
return false;
|
|
1009
|
-
if (found.convId === selfId)
|
|
1067
|
+
while (cur && !seen.has(cur)) {
|
|
1068
|
+
seen.add(cur);
|
|
1069
|
+
cur = this.parentExecution(cur)?.conv;
|
|
1070
|
+
if (cur === self)
|
|
1010
1071
|
return true;
|
|
1011
|
-
const snap = found.session === this
|
|
1012
|
-
? this.getSubagentSnapshot(found.convId)
|
|
1013
|
-
: found.session.getSubagentSnapshot(found.convId);
|
|
1014
|
-
if (!snap)
|
|
1015
|
-
return false;
|
|
1016
|
-
curId = snap.parentId;
|
|
1017
1072
|
}
|
|
1018
1073
|
return false;
|
|
1019
1074
|
}
|
|
@@ -1028,7 +1083,11 @@ export class ClientSession {
|
|
|
1028
1083
|
}
|
|
1029
1084
|
// B20:parentId 是建时旧 id 时先解析成当前 id(过户撞 id 改名后,新子代理
|
|
1030
1085
|
// 的 parentId 必须指向改名后的主对话,否则族展开/lists 都认不出它)。
|
|
1031
|
-
|
|
1086
|
+
// Runtime-bound callers already supply an id in this holder. A global alias
|
|
1087
|
+
// for another client's cN must never replace an existing local parent.
|
|
1088
|
+
const canonParent = parentId ? this.resolveExecution(parentId)?.convId : undefined;
|
|
1089
|
+
if (parentId && !canonParent)
|
|
1090
|
+
throw new Error("Subagent parent is unavailable or ambiguous");
|
|
1032
1091
|
return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist, undefined, thinking, notifyOnDone, isolation, extra, signal);
|
|
1033
1092
|
}
|
|
1034
1093
|
requireSubagentOwner(anchor, ownerId) {
|
|
@@ -1037,7 +1096,7 @@ export class ClientSession {
|
|
|
1037
1096
|
const conv = holder.convs.get(home?.convId ?? ownerId);
|
|
1038
1097
|
if (!conv || conv.session !== anchor.session)
|
|
1039
1098
|
throw new Error("Subagent parent runtime is no longer current");
|
|
1040
|
-
return conv
|
|
1099
|
+
return conversationIdentity(conv);
|
|
1041
1100
|
}
|
|
1042
1101
|
subagentRunOutcome(conv) {
|
|
1043
1102
|
return subagentRunOutcome(conv);
|
|
@@ -1081,7 +1140,7 @@ export class ClientSession {
|
|
|
1081
1140
|
}
|
|
1082
1141
|
async stopSubagentTask(convId) {
|
|
1083
1142
|
const owner = this.subagentOwnerOf(convId);
|
|
1084
|
-
const conv = owner.convs.get(
|
|
1143
|
+
const conv = owner.convs.get(this.subagentCurrentId(convId));
|
|
1085
1144
|
if (!conv)
|
|
1086
1145
|
return;
|
|
1087
1146
|
conv.subagentTaskStopped = true;
|
|
@@ -1090,10 +1149,13 @@ export class ClientSession {
|
|
|
1090
1149
|
if (conv.session.isStreaming || !conv.session.isIdle) {
|
|
1091
1150
|
await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
|
|
1092
1151
|
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1152
|
+
const currentOwner = this.resolveExecution(conversationIdentity(conv))?.session;
|
|
1153
|
+
if (!currentOwner)
|
|
1154
|
+
return;
|
|
1155
|
+
currentOwner.scheduleSubagentCompletionNotice(conv);
|
|
1156
|
+
currentOwner.emitConversations();
|
|
1095
1157
|
if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
|
|
1096
|
-
void
|
|
1158
|
+
void currentOwner.finalizeSubagentWorktree(conv).catch(() => { });
|
|
1097
1159
|
}
|
|
1098
1160
|
}
|
|
1099
1161
|
/** Admission lock shared with communication and inherited-cwd spawns. */
|
|
@@ -1154,16 +1216,17 @@ export class ClientSession {
|
|
|
1154
1216
|
conv.subagentError = undefined;
|
|
1155
1217
|
conv.subagentErrorNotified = undefined;
|
|
1156
1218
|
// Remove the previous round from debounce and circuit-breaker buffers.
|
|
1157
|
-
|
|
1158
|
-
|
|
1219
|
+
const parentKey = this.parentExecutionKey(conv);
|
|
1220
|
+
if (parentKey) {
|
|
1221
|
+
const pending = this.pendingSubagentNotices.get(parentKey);
|
|
1159
1222
|
if (pending) {
|
|
1160
1223
|
pending.subagents.delete(conv);
|
|
1161
1224
|
if (pending.subagents.size === 0) {
|
|
1162
1225
|
clearTimeout(pending.timer);
|
|
1163
|
-
this.pendingSubagentNotices.delete(
|
|
1226
|
+
this.pendingSubagentNotices.delete(parentKey);
|
|
1164
1227
|
}
|
|
1165
1228
|
}
|
|
1166
|
-
this.
|
|
1229
|
+
this.parentExecution(conv)?.conv.suspendedSubagents?.delete(conv);
|
|
1167
1230
|
}
|
|
1168
1231
|
conv.promptInFlight = true;
|
|
1169
1232
|
const isCurrent = () => conv.session === session && conv.subagentRunGeneration === generation;
|
|
@@ -1177,7 +1240,9 @@ export class ClientSession {
|
|
|
1177
1240
|
const error = err instanceof Error ? err.message : String(err);
|
|
1178
1241
|
conv.subagentError = error;
|
|
1179
1242
|
conv.subagentErrorNotified = error;
|
|
1180
|
-
const holder = this.
|
|
1243
|
+
const holder = this.resolveExecution(conversationIdentity(conv))?.session;
|
|
1244
|
+
if (!holder)
|
|
1245
|
+
return;
|
|
1181
1246
|
holder.emit({
|
|
1182
1247
|
type: "notice",
|
|
1183
1248
|
level: "error",
|
|
@@ -1188,8 +1253,8 @@ export class ClientSession {
|
|
|
1188
1253
|
finally {
|
|
1189
1254
|
if (isCurrent()) {
|
|
1190
1255
|
conv.promptInFlight = false;
|
|
1191
|
-
const holder = this.
|
|
1192
|
-
if (holder
|
|
1256
|
+
const holder = this.resolveExecution(conversationIdentity(conv))?.session;
|
|
1257
|
+
if (holder?.convs.get(conv.id) === conv) {
|
|
1193
1258
|
holder.scheduleSubagentCompletionNotice(conv);
|
|
1194
1259
|
holder.emitConversations();
|
|
1195
1260
|
}
|
|
@@ -1204,7 +1269,7 @@ export class ClientSession {
|
|
|
1204
1269
|
* 合并为一条聚合消息唤醒父对话,避免碎片化多次打断父对话。
|
|
1205
1270
|
*/
|
|
1206
1271
|
scheduleSubagentCompletionNotice(conv) {
|
|
1207
|
-
const parentId = conv.parentId;
|
|
1272
|
+
const parentId = this.parentExecutionKey ? this.parentExecutionKey(conv) : conv.parentId;
|
|
1208
1273
|
if (!parentId || conv.notifyOnDone === false || this.subagentTaskPending?.(conv))
|
|
1209
1274
|
return;
|
|
1210
1275
|
if (conv.subagentDoneNotified || conv.subagentConsumedByParent)
|
|
@@ -1229,7 +1294,7 @@ export class ClientSession {
|
|
|
1229
1294
|
refreshCompletionState(parentId) {
|
|
1230
1295
|
const owner = this.subagentOwnerOf(parentId);
|
|
1231
1296
|
owner.emitConversations();
|
|
1232
|
-
if (owner.activeId === parentId)
|
|
1297
|
+
if (owner.activeId === (this.subagentCurrentId?.(parentId) ?? parentId))
|
|
1233
1298
|
owner.flushSnapshot();
|
|
1234
1299
|
}
|
|
1235
1300
|
/**
|
|
@@ -1309,7 +1374,7 @@ export class ClientSession {
|
|
|
1309
1374
|
this.deliveringSubagentNotices.delete(parentId);
|
|
1310
1375
|
this.refreshCompletionState(parentId);
|
|
1311
1376
|
const owner = this.subagentOwnerOf(parentId);
|
|
1312
|
-
const parent = owner.convs.get(
|
|
1377
|
+
const parent = owner.convs.get(this.subagentCurrentId?.(parentId) ?? parentId);
|
|
1313
1378
|
if (parent?.notifyOnDone === "manual" && !parent.subagentDoneNotified && !parent.subagentConsumedByParent) {
|
|
1314
1379
|
owner.scheduleSubagentCompletionNotice(parent);
|
|
1315
1380
|
}
|
|
@@ -1347,19 +1412,10 @@ export class ClientSession {
|
|
|
1347
1412
|
return;
|
|
1348
1413
|
// 寻找父对话(支持跨 ClientSession 查找)
|
|
1349
1414
|
const parentOwner = this.subagentOwnerOf(parentId);
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
//
|
|
1353
|
-
|
|
1354
|
-
const projectCwd = toNotify[0]?.cwd ?? this.cwd;
|
|
1355
|
-
for (const c of parentOwner.convs.values()) {
|
|
1356
|
-
if (!c.isSubagent && c.cwd === projectCwd) {
|
|
1357
|
-
targetConv = c;
|
|
1358
|
-
isFallback = true;
|
|
1359
|
-
break;
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1415
|
+
const currentParentId = this.subagentCurrentId?.(parentId) ?? parentId;
|
|
1416
|
+
const targetConv = parentOwner.convs.get(currentParentId);
|
|
1417
|
+
// Completion belongs only to its originating parent. Sharing a project
|
|
1418
|
+
// directory does not authorize injecting it into another conversation.
|
|
1363
1419
|
// 无存活主对话时优雅降级为系统 Notice,不报错不中断
|
|
1364
1420
|
if (!targetConv || !targetConv.session) {
|
|
1365
1421
|
for (const c of toNotify)
|
|
@@ -1420,10 +1476,30 @@ export class ClientSession {
|
|
|
1420
1476
|
return;
|
|
1421
1477
|
}
|
|
1422
1478
|
}
|
|
1479
|
+
// 若父对话正在 wait_all 等待中,完成通知暂不投递进 steering 队列,避免与 wait_all 返回重复(issue #828)
|
|
1480
|
+
if (consultWaitingParents.has(targetConv)) {
|
|
1481
|
+
if (retryCount < 60) {
|
|
1482
|
+
const retryTimer = setTimeout(() => {
|
|
1483
|
+
const current = toNotify.filter(isCurrent);
|
|
1484
|
+
if (current.length === 0)
|
|
1485
|
+
return;
|
|
1486
|
+
const pending = this.pendingSubagentNotices.get(parentId);
|
|
1487
|
+
if (pending?.timer)
|
|
1488
|
+
clearTimeout(pending.timer);
|
|
1489
|
+
this.pendingSubagentNotices.set(parentId, {
|
|
1490
|
+
timer: retryTimer,
|
|
1491
|
+
subagents: new Set([...(pending?.subagents ?? []), ...current]),
|
|
1492
|
+
});
|
|
1493
|
+
void this.flushSubagentCompletionNotice(parentId, retryCount + 1);
|
|
1494
|
+
}, 400);
|
|
1495
|
+
this.pendingSubagentNotices.set(parentId, { timer: retryTimer, subagents: new Set(toNotify) });
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1423
1499
|
for (const c of toNotify) {
|
|
1424
1500
|
c.subagentDoneNotified = true;
|
|
1425
1501
|
}
|
|
1426
|
-
const noticeText = formatSubagentsCompletionNotice(toNotify, this.getLang()
|
|
1502
|
+
const noticeText = formatSubagentsCompletionNotice(toNotify, this.getLang());
|
|
1427
1503
|
if (targetConv.notifyOnDone === "manual") {
|
|
1428
1504
|
targetConv.subagentDoneNotified = false;
|
|
1429
1505
|
targetConv.subagentConsumedByParent = false;
|
|
@@ -1535,8 +1611,13 @@ export class ClientSession {
|
|
|
1535
1611
|
emitTerminal(conversationId, msg) {
|
|
1536
1612
|
// Background conversations keep collecting output in their own PTY buffer.
|
|
1537
1613
|
// Do not stream it into the active xterm; push the retained window on switch.
|
|
1538
|
-
if (msg.type === "terminal_output" && conversationId !== this.activeId)
|
|
1614
|
+
if (msg.type === "terminal_output" && conversationId !== this.activeId) {
|
|
1615
|
+
const conv = this.convs.get(conversationId);
|
|
1616
|
+
if (conv)
|
|
1617
|
+
for (const send of this.sharedTerminalSinks?.get(conv) ?? [])
|
|
1618
|
+
send({ ...msg, conversationId });
|
|
1539
1619
|
return;
|
|
1620
|
+
}
|
|
1540
1621
|
if (msg.type === "terminal_exit") {
|
|
1541
1622
|
this.updatesAllCache = null;
|
|
1542
1623
|
}
|
|
@@ -1584,12 +1665,15 @@ export class ClientSession {
|
|
|
1584
1665
|
* prompt with the same images skips the vision API call entirely — editing
|
|
1585
1666
|
* a question doesn't re-burn tokens on re-transcribing identical screenshots.
|
|
1586
1667
|
*/
|
|
1587
|
-
/**
|
|
1588
|
-
*
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
*
|
|
1592
|
-
|
|
1668
|
+
/**
|
|
1669
|
+
* SYSTEM.md / APPEND_SYSTEM.md 的 base **不存这里**——见 prompt-base-store.ts。
|
|
1670
|
+
*
|
|
1671
|
+
* 归属必须是「哪个 loader / 哪个 session」,不是「哪个浏览器客户端」:曾经是
|
|
1672
|
+
* `lastBaseSystemPrompt` 字段(本类 = 一个浏览器客户端),切项目时新会话没有
|
|
1673
|
+
* SYSTEM.md → base 为 undefined → 旧值没人清 → 上一个项目的提示词泄漏到本项目
|
|
1674
|
+
* 的预览与新建对话(issue #812)。任何「最近一次看到的值」形态的客户端级字段都
|
|
1675
|
+
* 会复发这个 bug,读取一律走 readPromptBase(conv.session.resourceLoader)。
|
|
1676
|
+
*/
|
|
1593
1677
|
/**
|
|
1594
1678
|
* 延迟加载(工具按需加载)模式下,按 session 对象存「已加载」工具集。
|
|
1595
1679
|
*
|
|
@@ -1939,7 +2023,8 @@ export class ClientSession {
|
|
|
1939
2023
|
}
|
|
1940
2024
|
/** 当前活动会话的工具/资源快照 → composer 输入。cwd 取活动对话的。 */
|
|
1941
2025
|
composeInputs(src) {
|
|
1942
|
-
const preset = src.preset ?? this.
|
|
2026
|
+
const preset = src.preset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2027
|
+
const promptBase = readPromptBase(src.session?.resourceLoader);
|
|
1943
2028
|
// 技能名录指纹观测(只打日志,不干预组装;预览与 run 共用此入口,
|
|
1944
2029
|
// 变化才记一行,首轮静默)。用未注文的目录(fill 前),全文注入不影响指纹。
|
|
1945
2030
|
this.noteSkillCatalogDigest(src.skills);
|
|
@@ -1949,7 +2034,8 @@ export class ClientSession {
|
|
|
1949
2034
|
const isRemote = isRemoteWorkspaceUri(realCwd);
|
|
1950
2035
|
return {
|
|
1951
2036
|
cwd: formatCwdForPrompt(realCwd),
|
|
1952
|
-
|
|
2037
|
+
// 空串 = 没有 SYSTEM.md(loader 记录的 base 原文,绝不沿用别的会话)。
|
|
2038
|
+
systemPromptFile: promptBase.system || undefined,
|
|
1953
2039
|
builtinSoul: BUILTIN_SOUL,
|
|
1954
2040
|
selectedTools: src.selectedTools,
|
|
1955
2041
|
toolSnippets: src.toolSnippets,
|
|
@@ -1960,7 +2046,10 @@ export class ClientSession {
|
|
|
1960
2046
|
piReadme: PI_DOC_PATHS.readme,
|
|
1961
2047
|
piDocs: PI_DOC_PATHS.docs,
|
|
1962
2048
|
piExamples: PI_DOC_PATHS.examples,
|
|
1963
|
-
|
|
2049
|
+
pluginDocs: join(getPkgRoot(), "docs", "architecture-plugins.md"),
|
|
2050
|
+
pluginSdk: join(getPkgRoot(), "plugin-sdk"),
|
|
2051
|
+
pluginsDir: join(this.stateStore.dataDir, "plugins"),
|
|
2052
|
+
appendFiles: [...promptBase.append],
|
|
1964
2053
|
windowsPersona: isRemote
|
|
1965
2054
|
? buildRemoteWorkspacePersona(realCwd)
|
|
1966
2055
|
: process.platform === "win32"
|
|
@@ -1982,13 +2071,16 @@ export class ClientSession {
|
|
|
1982
2071
|
}
|
|
1983
2072
|
/** skill 全文注入({{skills}} 全文模式):最好努力读名单里技能的文件正文。 */
|
|
1984
2073
|
fillSkillContents(skills) {
|
|
1985
|
-
return fillSkillContents(skills, this.settingsSvc.current.skillsFullText
|
|
2074
|
+
return fillSkillContents(skills, this.settingsSvc.current.skillsFullText, {
|
|
2075
|
+
maxFileBytes: this.settingsSvc.current.skillsMaxFileBytes,
|
|
2076
|
+
maxTotalBytes: this.settingsSvc.current.skillsFullTextMaxBytes,
|
|
2077
|
+
});
|
|
1986
2078
|
}
|
|
1987
2079
|
/** 渲染当前组合模板。当存在自定义模板/覆盖,或者当前会话预设非 standard(如 code/minimal/ask/reader),
|
|
1988
2080
|
* 或者存在被禁用的工具时,必须渲染完整系统提示词,保证工具门控、技能隐藏与 Guidelines 严格对齐当前预设;
|
|
1989
2081
|
* 仅在完全默认且全功能 standard 状态下返回 undefined 让 SDK 拼装。 */
|
|
1990
2082
|
renderMainCompose(src) {
|
|
1991
|
-
const preset = src.preset ?? this.
|
|
2083
|
+
const preset = src.preset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
1992
2084
|
const showSkills = presetShowsSkillCatalog(preset);
|
|
1993
2085
|
const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
|
|
1994
2086
|
return renderMainCompose(this.composeInputs(src), {
|
|
@@ -2071,6 +2163,8 @@ export class ClientSession {
|
|
|
2071
2163
|
filePath: s.filePath ?? "",
|
|
2072
2164
|
})),
|
|
2073
2165
|
preset,
|
|
2166
|
+
// base(SYSTEM.md / APPEND_SYSTEM.md)跟着 loader 走:算哪个会话就读哪个会话。
|
|
2167
|
+
session: sess,
|
|
2074
2168
|
}));
|
|
2075
2169
|
// 模板/覆盖渲染(无自定义模板时用默认模板渲染完整提示词,确保与真实 run 规则一致且包含预设过滤)。
|
|
2076
2170
|
const tpl = (this.settingsSvc.current.promptTemplate ?? "").trim();
|
|
@@ -2178,13 +2272,14 @@ export class ClientSession {
|
|
|
2178
2272
|
await this.communicate(fromRunId, "send", { to: toRunId, message: payload });
|
|
2179
2273
|
}
|
|
2180
2274
|
subagentHost = {
|
|
2275
|
+
resolveConversationId: (id) => this.resolveExecution(id)?.convId,
|
|
2181
2276
|
consultParent: (selfId, questions, signal) => this.consultParent(selfId, questions, signal),
|
|
2182
2277
|
answerConsult: (selfId, runId, requestId, answers) => this.answerConsult(selfId, runId, requestId, answers),
|
|
2183
2278
|
escalateConsult: (selfId, runId, requestId) => this.answerConsult(selfId, runId, requestId),
|
|
2184
2279
|
getPendingConsults: (parentId) => this.getPendingConsults(parentId),
|
|
2185
2280
|
setConsultWaiting: (parentId, waiting) => {
|
|
2186
2281
|
const owner = this.subagentOwnerOf(parentId);
|
|
2187
|
-
const parent = owner.convs.get(
|
|
2282
|
+
const parent = owner.convs.get(this.subagentCurrentId(parentId));
|
|
2188
2283
|
if (parent) {
|
|
2189
2284
|
if (waiting)
|
|
2190
2285
|
consultWaitingParents.add(parent);
|
|
@@ -2192,6 +2287,11 @@ export class ClientSession {
|
|
|
2192
2287
|
consultWaitingParents.delete(parent);
|
|
2193
2288
|
}
|
|
2194
2289
|
},
|
|
2290
|
+
isRequestSteering: (parentId, requestId) => {
|
|
2291
|
+
const owner = this.subagentOwnerOf(parentId);
|
|
2292
|
+
const parent = owner.convs.get(this.subagentCurrentId(parentId));
|
|
2293
|
+
return !!parent?.queuedSteeringRequestIds?.has(requestId);
|
|
2294
|
+
},
|
|
2195
2295
|
spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal) => {
|
|
2196
2296
|
// B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
|
|
2197
2297
|
// 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
|
|
@@ -2201,7 +2301,7 @@ export class ClientSession {
|
|
|
2201
2301
|
},
|
|
2202
2302
|
completeSubagent: (selfId, summary) => {
|
|
2203
2303
|
const owner = this.subagentOwnerOf(selfId);
|
|
2204
|
-
const conv = owner.convs.get(
|
|
2304
|
+
const conv = owner.convs.get(this.subagentCurrentId(selfId));
|
|
2205
2305
|
if (!conv?.parentId)
|
|
2206
2306
|
throw new Error("Only a child task can complete itself.");
|
|
2207
2307
|
conv.subagentTask = requestSubagentCompletion(conv.subagentTask ?? createSubagentTask(conv.notifyOnDone), summary);
|
|
@@ -2215,15 +2315,7 @@ export class ClientSession {
|
|
|
2215
2315
|
await owner.finalizeSubagentWorktree(conv);
|
|
2216
2316
|
}
|
|
2217
2317
|
},
|
|
2218
|
-
getSubagent: (convId) =>
|
|
2219
|
-
// B20:本会话查不到就去「当前持有方」查 —— 过户把子代理整体搬走后,
|
|
2220
|
-
// 旧 host 仍指向源会话(搬不动闭包),不跨会话解析 wait_all/get_result
|
|
2221
|
-
// 会以为子代理「已移出/不存在」而其实还在跑。
|
|
2222
|
-
if (this.convs.has(convId))
|
|
2223
|
-
return this.getSubagentSnapshot(convId);
|
|
2224
|
-
const found = this.findSubagentOwner?.(convId);
|
|
2225
|
-
return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
|
|
2226
|
-
},
|
|
2318
|
+
getSubagent: (convId) => this.subagentSnapshotAnywhere(convId),
|
|
2227
2319
|
listSubagents: (scope, forSelfId) => this.listSubagentSnapshots(scope, forSelfId),
|
|
2228
2320
|
markSubagentsConsumed: (runIds) => {
|
|
2229
2321
|
for (const id of runIds) {
|
|
@@ -2401,6 +2493,8 @@ export class ClientSession {
|
|
|
2401
2493
|
return createSkillToolHost({
|
|
2402
2494
|
resolveTarget: (oid) => ((oid ?? "").trim() !== "" ? this.convs.get(oid.trim()) : this.convs.get(this.activeId)),
|
|
2403
2495
|
getDisabledSkills: () => this.settingsSvc.current.disabledSkills,
|
|
2496
|
+
// 单文件上限跟随设置(与全文注入同口径);每次调用实时读,改设置不必重建工具。
|
|
2497
|
+
getMaxFileBytes: () => this.settingsSvc.current.skillsMaxFileBytes,
|
|
2404
2498
|
ownerId,
|
|
2405
2499
|
});
|
|
2406
2500
|
}
|
|
@@ -2492,7 +2586,6 @@ export class ClientSession {
|
|
|
2492
2586
|
pendingQuestions = new Map();
|
|
2493
2587
|
/** 任务计划管理器(Plan Mode / Step State Machine)。 */
|
|
2494
2588
|
planManager;
|
|
2495
|
-
approvalSeq = 0;
|
|
2496
2589
|
/** 确保对话拥有待审批项 Map */
|
|
2497
2590
|
ensurePendingApprovals(conv) {
|
|
2498
2591
|
if (!conv.pendingApprovals)
|
|
@@ -2807,18 +2900,29 @@ export class ClientSession {
|
|
|
2807
2900
|
executionMcpBridge(cwd) {
|
|
2808
2901
|
return this.botExecution ? this.botMcpBridge : ClientSession.mcpProjects?.getBridge(cwd);
|
|
2809
2902
|
}
|
|
2810
|
-
|
|
2903
|
+
botToolAuthorization(name, cwd = this.cwd, params, phase = "execute") {
|
|
2811
2904
|
const bot = this.botExecution;
|
|
2812
2905
|
if (!bot)
|
|
2813
|
-
return true;
|
|
2906
|
+
return { allowed: true };
|
|
2814
2907
|
bot.assertActive();
|
|
2908
|
+
if (bot.planOnly && phase === "execute") {
|
|
2909
|
+
const denial = checkGroupTaskPlanGuard(name, params ?? {}, true);
|
|
2910
|
+
if (denial)
|
|
2911
|
+
return { allowed: false, reason: denial.reason };
|
|
2912
|
+
}
|
|
2815
2913
|
const mcp = this.executionMcpBridge(cwd)?.getTools() ?? [];
|
|
2816
2914
|
const matches = mcp.filter((tool) => tool.name === name);
|
|
2817
|
-
if (!bot.allowsTool(name))
|
|
2818
|
-
return false;
|
|
2819
|
-
if (matches.length)
|
|
2820
|
-
return
|
|
2821
|
-
return true;
|
|
2915
|
+
if (!(phase === "register" ? bot.allowsToolRegistration(name) : bot.allowsTool(name, params ?? {})))
|
|
2916
|
+
return { allowed: false, reason: "Tool is not authorized for this Bot" };
|
|
2917
|
+
if (matches.length && !(matches.length === 1 && bot.bot.mcpServers.includes(getMcpToolServer(matches[0]) ?? "")))
|
|
2918
|
+
return { allowed: false, reason: "Bot MCP tool authorization mismatch" };
|
|
2919
|
+
return { allowed: true };
|
|
2920
|
+
}
|
|
2921
|
+
botToolAllowed(name, cwd = this.cwd, params) {
|
|
2922
|
+
return this.botToolAuthorization(name, cwd, params).allowed;
|
|
2923
|
+
}
|
|
2924
|
+
botToolRegistrationAllowed(name, cwd = this.cwd) {
|
|
2925
|
+
return this.botToolAuthorization(name, cwd, undefined, "register").allowed;
|
|
2822
2926
|
}
|
|
2823
2927
|
static async create(clientId, cwd, stateStore, opts) {
|
|
2824
2928
|
const botExecution = getBotExecution(clientId);
|
|
@@ -3016,96 +3120,97 @@ export class ClientSession {
|
|
|
3016
3120
|
await ClientSession.mcpProjects?.prepare(effectiveCwd);
|
|
3017
3121
|
const sdkBuiltins = sandboxIdentity || this.botExecution ? [] : await getSdkBuiltinExtensionFactories();
|
|
3018
3122
|
const sandboxRuntimeGate = createSandboxRuntimeGate(() => this.sandboxes.getExecutionIdentity(effectiveCwd, sandboxIdentity), effectiveCwd);
|
|
3123
|
+
// 本次 runtime 的提示词 base(SYSTEM.md / APPEND_SYSTEM.md 原文)—— 由
|
|
3124
|
+
// prompt-base-store 登记到**本 loader**(session 本体)名下,而不是本客户端:
|
|
3125
|
+
// base 缺失就写空、每次 reload 覆盖,所以切项目不可能沿用上一个项目的内容,
|
|
3126
|
+
// 过户搬 session 时记录也跟着走(issue #812)。
|
|
3127
|
+
const promptBase = createPromptBaseObservers({
|
|
3128
|
+
// 返回给 SDK 的值:主会话原样返回 base —— 默认分支据此保留 .pi/SYSTEM.md
|
|
3129
|
+
// (TUI 同语义);以前恒返回 undefined,组合模板未激活时 SYSTEM.md 被静默
|
|
3130
|
+
// 丢弃。组合模板激活时 before_agent_start 整体换掉提示词,二者不叠加。
|
|
3131
|
+
// 子代理模板 replace:有 base 时整体替换(无 base 时留给下方 persona
|
|
3132
|
+
// 扩展做灵魂段替换,保留工具/文档自动段)。
|
|
3133
|
+
system: (base) => base && apply && apply.promptMode === "replace" && this.templatePrompt(apply).trim()
|
|
3134
|
+
? this.templatePrompt(apply)
|
|
3135
|
+
: base,
|
|
3136
|
+
// APPEND_SYSTEM.md 之上再叠运行时段(模板 append / 计划模式 / 审查者 / 沙箱 /
|
|
3137
|
+
// 平台 persona / 终端引导 / 标记工具引导)。base 已由工厂登记给 loader,
|
|
3138
|
+
// {{append}} 用的就是那份原文 —— 这里 push 的额外段不会回灌到 composer。
|
|
3139
|
+
append: (base) => {
|
|
3140
|
+
const out = [...base];
|
|
3141
|
+
if (apply && apply.promptMode === "append" && this.templatePrompt(apply).trim()) {
|
|
3142
|
+
out.push(this.templatePrompt(apply));
|
|
3143
|
+
}
|
|
3144
|
+
// 主会话自定义「追加」已并入组合模板的 {{append}} 覆盖,不再在此注入。
|
|
3145
|
+
// 计划模式:只规划不实施 —— 硬闸门(server/plan-mode.ts 拒写类/旁路
|
|
3146
|
+
// 工具与非常规 bash)之外再补一段软约束,每轮重建提示词时读当前
|
|
3147
|
+
// 会话状态,切换后下一次 reload 生效。提示词正文可在设置面板改
|
|
3148
|
+
// (追加/替换内置默认,见 buildPlanModePrompt)。
|
|
3149
|
+
// ⚠️ 这一段与平台无关(曾在 win32 分支里被误嵌套,导致非 Windows
|
|
3150
|
+
// 上计划模式的软约束从来没进过提示词,只有硬闸门在挡)。
|
|
3151
|
+
if (this.planModeOf(ownerId)) {
|
|
3152
|
+
const planPrefs = this.settingsSvc.current;
|
|
3153
|
+
out.push(buildPlanModePrompt(planPrefs.planModePromptMode, planPrefs.planModePrompt));
|
|
3154
|
+
}
|
|
3155
|
+
// 审查者模式(自动委派):本对话只审阅,活由服务端派给常驻执行对话。
|
|
3156
|
+
// 与计划模式**互斥优先级**:计划模式开着时以计划模式为准,不派活。
|
|
3157
|
+
if (this.delegateModeOf(ownerId) && !this.planModeOf(ownerId)) {
|
|
3158
|
+
out.push(DELEGATION_SYSTEM_PROMPT);
|
|
3159
|
+
}
|
|
3160
|
+
const activeSandbox = this.sandboxes.getExecutionIdentity(effectiveCwd, sandboxIdentity);
|
|
3161
|
+
if (activeSandbox) {
|
|
3162
|
+
out.push(`[Sandbox Isolation Mode] You are operating inside an isolated sandbox workspace "${activeSandbox.name}" at "${activeSandbox.path}".` +
|
|
3163
|
+
(activeSandbox.sourcePath
|
|
3164
|
+
? ` This sandbox is an isolated copy of "${activeSandbox.sourcePath}". NEVER read from or modify "${activeSandbox.sourcePath}" directly; make all changes exclusively within the current sandbox directory "${activeSandbox.path}".`
|
|
3165
|
+
: ` Keep all file operations strictly inside "${activeSandbox.path}".`) +
|
|
3166
|
+
" Only restricted local file editing is supported. Shell commands, scripts, terminals, evaluation, and unknown tools are unavailable without an OS isolation backend.");
|
|
3167
|
+
}
|
|
3168
|
+
const realCwd = restoreWorkspaceUriFromSessionDir(effectiveCwd);
|
|
3169
|
+
if (isRemoteWorkspaceUri(realCwd)) {
|
|
3170
|
+
// 远程 SSH 工作区:明确告知 AI 当前处于远程主机以及所有工具已透明桥接至远端,
|
|
3171
|
+
// 绝不注入本地 WINDOWS_PERSONA 以免误导模型以为在本地 Windows 环境。
|
|
3172
|
+
out.push(buildRemoteWorkspacePersona(realCwd));
|
|
3173
|
+
}
|
|
3174
|
+
else if (process.platform === "win32") {
|
|
3175
|
+
// Windows 专属 persona:bash 工具跑 Git Bash 且无默认超时、终端
|
|
3176
|
+
// 是交互式 TTY——注入约束避免 heredoc/交互/长驻命令挂死整个会话;
|
|
3177
|
+
// GBK 老中文文件让模型改用终端按正确编码读(iconv/chcp/Get-Content)。
|
|
3178
|
+
out.push(WINDOWS_PERSONA);
|
|
3179
|
+
}
|
|
3180
|
+
// 终端引导只教「开关开着且预设下仍可用」的工具(见 tool-manager.ts 语义总表)。
|
|
3181
|
+
const presetForGuidance = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
3182
|
+
if (isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), presetForGuidance)) {
|
|
3183
|
+
// 终端工具使用引导(全平台):告诉模型什么场景该用持久终端
|
|
3184
|
+
// 而不是一次性 bash——没有这段模型几乎从不主动选终端工具。
|
|
3185
|
+
// 组内工具全关时不注入(不教 AI 用不存在的工具)。
|
|
3186
|
+
out.push(TERMINAL_TOOLS_GUIDANCE);
|
|
3187
|
+
}
|
|
3188
|
+
// bash 管道限制已并入 bash 工具自身的 description,不再作为独立提示段注入。
|
|
3189
|
+
// 内置标记工具引导(按总开关/分组开关过滤)
|
|
3190
|
+
const markerGuidance = this.markerSvc.buildGuidance();
|
|
3191
|
+
if (markerGuidance)
|
|
3192
|
+
out.push(markerGuidance);
|
|
3193
|
+
return out;
|
|
3194
|
+
},
|
|
3195
|
+
});
|
|
3019
3196
|
const services = await createAgentSessionServices({
|
|
3020
3197
|
cwd: effectiveCwd,
|
|
3021
3198
|
modelRuntime: this.sharedModelRuntime,
|
|
3022
|
-
// 设置面板钩子(官方 SDK 的 resourceLoader overrides
|
|
3023
|
-
//
|
|
3024
|
-
//
|
|
3025
|
-
//
|
|
3026
|
-
// 子代理带模板(apply)时:prompt/skills/extensions 改读模板视图——
|
|
3027
|
-
//
|
|
3028
|
-
//
|
|
3029
|
-
// 整体替换 base。append 模式把模板提示词追加到
|
|
3030
|
-
// 末尾(此时主会话的自定义 prompt 不再叠加,角色由模板定义);非空
|
|
3199
|
+
// 设置面板钩子(官方 SDK 的 resourceLoader overrides):override 在每次
|
|
3200
|
+
// resourceLoader.reload() 时重放,且读取 this.settings 的当前值——因此
|
|
3201
|
+
// session.reload() 即可让系统提示词 / 技能 / 插件开关生效,新对话(新 runtime)
|
|
3202
|
+
// 也会自动带上当前设置。
|
|
3203
|
+
// 子代理带模板(apply)时:prompt/skills/extensions 改读模板视图——replace 模式
|
|
3204
|
+
// 把基座换成模板提示词(无 SYSTEM.md 时由下方 pi-webui-persona 内联扩展换掉
|
|
3205
|
+
// 灵魂段),append 模式把模板提示词追加到末尾(此时角色由模板定义);非空
|
|
3031
3206
|
// 白名单取代主会话开关(只启用这些),空白名单 = 跟随主会话。
|
|
3032
3207
|
resourceLoaderOptions: {
|
|
3033
3208
|
// Filter before import: extensionsOverride runs after arbitrary module initialization.
|
|
3034
3209
|
...sandboxExtensionOptions(Boolean(sandboxIdentity) || Boolean(this.botExecution)),
|
|
3035
|
-
//
|
|
3036
|
-
//
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
systemPromptOverride: (base) => {
|
|
3040
|
-
if (typeof base === "string" && base) {
|
|
3041
|
-
this.lastBaseSystemPrompt = base;
|
|
3042
|
-
if (apply && apply.promptMode === "replace" && this.templatePrompt(apply).trim()) {
|
|
3043
|
-
return this.templatePrompt(apply);
|
|
3044
|
-
}
|
|
3045
|
-
}
|
|
3046
|
-
return undefined;
|
|
3047
|
-
},
|
|
3048
|
-
appendSystemPromptOverride: (base) => {
|
|
3049
|
-
// 记录 SDK APPEND_SYSTEM.md base(composer {{append}} 自动内容)。
|
|
3050
|
-
if (!apply)
|
|
3051
|
-
this.lastSdkAppendFiles = base.slice();
|
|
3052
|
-
const out = [...base];
|
|
3053
|
-
if (this.botExecution?.bot.systemPrompt)
|
|
3054
|
-
out.push(this.botExecution.bot.systemPrompt);
|
|
3055
|
-
if (apply && apply.promptMode === "append" && this.templatePrompt(apply).trim()) {
|
|
3056
|
-
out.push(this.templatePrompt(apply));
|
|
3057
|
-
}
|
|
3058
|
-
// 主会话自定义「追加」已并入组合模板的 {{append}} 覆盖,不再在此注入。
|
|
3059
|
-
// 计划模式:只规划不实施 —— 硬闸门(server/plan-mode.ts 拒写类/旁路
|
|
3060
|
-
// 工具与非常规 bash)之外再补一段软约束,每轮重建提示词时读当前
|
|
3061
|
-
// 会话状态,切换后下一次 reload 生效。提示词正文可在设置面板改
|
|
3062
|
-
// (追加/替换内置默认,见 buildPlanModePrompt)。
|
|
3063
|
-
// ⚠️ 这一段与平台无关(曾在 win32 分支里被误嵌套,导致非 Windows
|
|
3064
|
-
// 上计划模式的软约束从来没进过提示词,只有硬闸门在挡)。
|
|
3065
|
-
if (this.planModeOf(ownerId)) {
|
|
3066
|
-
const planPrefs = this.settingsSvc.current;
|
|
3067
|
-
out.push(buildPlanModePrompt(planPrefs.planModePromptMode, planPrefs.planModePrompt));
|
|
3068
|
-
}
|
|
3069
|
-
// 审查者模式(自动委派):本对话只审阅,活由服务端派给常驻执行对话。
|
|
3070
|
-
// 与计划模式**互斥优先级**:计划模式开着时以计划模式为准,不派活。
|
|
3071
|
-
if (this.delegateModeOf(ownerId) && !this.planModeOf(ownerId)) {
|
|
3072
|
-
out.push(DELEGATION_SYSTEM_PROMPT);
|
|
3073
|
-
}
|
|
3074
|
-
const activeSandbox = this.sandboxes.getExecutionIdentity(effectiveCwd, sandboxIdentity);
|
|
3075
|
-
if (activeSandbox) {
|
|
3076
|
-
out.push(`[Sandbox Isolation Mode] You are operating inside an isolated sandbox workspace "${activeSandbox.name}" at "${activeSandbox.path}".` +
|
|
3077
|
-
(activeSandbox.sourcePath
|
|
3078
|
-
? ` This sandbox is an isolated copy of "${activeSandbox.sourcePath}". NEVER read from or modify "${activeSandbox.sourcePath}" directly; make all changes exclusively within the current sandbox directory "${activeSandbox.path}".`
|
|
3079
|
-
: ` Keep all file operations strictly inside "${activeSandbox.path}".`) +
|
|
3080
|
-
" Only restricted local file editing is supported. Shell commands, scripts, terminals, evaluation, and unknown tools are unavailable without an OS isolation backend.");
|
|
3081
|
-
}
|
|
3082
|
-
const realCwd = restoreWorkspaceUriFromSessionDir(effectiveCwd);
|
|
3083
|
-
if (isRemoteWorkspaceUri(realCwd)) {
|
|
3084
|
-
// 远程 SSH 工作区:明确告知 AI 当前处于远程主机以及所有工具已透明桥接至远端,
|
|
3085
|
-
// 绝不注入本地 WINDOWS_PERSONA 以免误导模型以为在本地 Windows 环境。
|
|
3086
|
-
out.push(buildRemoteWorkspacePersona(realCwd));
|
|
3087
|
-
}
|
|
3088
|
-
else if (process.platform === "win32") {
|
|
3089
|
-
// Windows 专属 persona:bash 工具跑 Git Bash 且无默认超时、终端
|
|
3090
|
-
// 是交互式 TTY——注入约束避免 heredoc/交互/长驻命令挂死整个会话;
|
|
3091
|
-
// GBK 老中文文件让模型改用终端按正确编码读(iconv/chcp/Get-Content)。
|
|
3092
|
-
out.push(WINDOWS_PERSONA);
|
|
3093
|
-
}
|
|
3094
|
-
// 终端引导只教「开关开着且预设下仍可用」的工具(见 tool-manager.ts 语义总表)。
|
|
3095
|
-
const presetForGuidance = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
3096
|
-
if (isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), presetForGuidance)) {
|
|
3097
|
-
// 终端工具使用引导(全平台):告诉模型什么场景该用持久终端
|
|
3098
|
-
// 而不是一次性 bash——没有这段模型几乎从不主动选终端工具。
|
|
3099
|
-
// 组内工具全关时不注入(不教 AI 用不存在的工具)。
|
|
3100
|
-
out.push(TERMINAL_TOOLS_GUIDANCE);
|
|
3101
|
-
}
|
|
3102
|
-
// bash 管道限制已并入 bash 工具自身的 description,不再作为独立提示段注入。
|
|
3103
|
-
// 内置标记工具引导(按总开关/分组开关过滤)
|
|
3104
|
-
const markerGuidance = this.markerSvc.buildGuidance();
|
|
3105
|
-
if (markerGuidance)
|
|
3106
|
-
out.push(markerGuidance);
|
|
3107
|
-
return out;
|
|
3108
|
-
},
|
|
3210
|
+
// 提示词基座(SYSTEM.md / APPEND_SYSTEM.md):登记归属 + 决定返回给 SDK 的值,
|
|
3211
|
+
// 见 prompt-base-store.ts(issue #812)。
|
|
3212
|
+
systemPromptOverride: promptBase.systemPromptOverride,
|
|
3213
|
+
appendSystemPromptOverride: promptBase.appendSystemPromptOverride,
|
|
3109
3214
|
// 技能:模板非空白名单时只启用白名单里的(显式配置优先于预设);
|
|
3110
3215
|
// 否则按主会话禁用集过滤。预设拿掉 skill 加载器时(minimal/code/ask)
|
|
3111
3216
|
// 名录同步隐藏——列出来但调不动只是噪音(见 tool-manager.ts 语义总表)。
|
|
@@ -3163,8 +3268,9 @@ export class ClientSession {
|
|
|
3163
3268
|
pi.on("tool_call", (event) => {
|
|
3164
3269
|
if (this.botExecution) {
|
|
3165
3270
|
try {
|
|
3166
|
-
|
|
3167
|
-
|
|
3271
|
+
const auth = this.botToolAuthorization(event.toolName, effectiveCwd, event.input);
|
|
3272
|
+
if (!auth.allowed)
|
|
3273
|
+
return { block: true, reason: auth.reason ?? "Tool is not authorized for this Bot" };
|
|
3168
3274
|
}
|
|
3169
3275
|
catch {
|
|
3170
3276
|
return { block: true, reason: "Bot execution authorization expired" };
|
|
@@ -3174,6 +3280,35 @@ export class ClientSession {
|
|
|
3174
3280
|
});
|
|
3175
3281
|
},
|
|
3176
3282
|
},
|
|
3283
|
+
{
|
|
3284
|
+
name: "pi-webui-device-group-context",
|
|
3285
|
+
hidden: true,
|
|
3286
|
+
factory: (pi) => {
|
|
3287
|
+
// SDK context runs after per-turn and virtual-model compaction,
|
|
3288
|
+
// immediately before conversion to provider messages (also on tool continuation).
|
|
3289
|
+
pi.on("context", (event, ctx) => {
|
|
3290
|
+
const bot = this.botExecution;
|
|
3291
|
+
if (!bot?.groupContext)
|
|
3292
|
+
return;
|
|
3293
|
+
const messages = repairGroupContextRequest(bot.groupContext, event.messages, bot.bot.id);
|
|
3294
|
+
const metrics = messages !== event.messages
|
|
3295
|
+
? messages.at(-1).details.metrics
|
|
3296
|
+
: extractGroupContextMetrics(bot.groupContext, [], "", "none", true);
|
|
3297
|
+
recordGroupContextMetrics(ctx.sessionManager.getSessionId(), metrics);
|
|
3298
|
+
if (messages !== event.messages)
|
|
3299
|
+
return { messages };
|
|
3300
|
+
});
|
|
3301
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
3302
|
+
const bot = this.botExecution;
|
|
3303
|
+
const current = bot?.groupContext;
|
|
3304
|
+
if (!current)
|
|
3305
|
+
return;
|
|
3306
|
+
const message = groupContextMessage(current, ctx.sessionManager.buildSessionProjection().messages, bot.bot.id);
|
|
3307
|
+
recordGroupContextMetrics(ctx.sessionManager.getSessionId(), message.details.metrics);
|
|
3308
|
+
return { message };
|
|
3309
|
+
});
|
|
3310
|
+
},
|
|
3311
|
+
},
|
|
3177
3312
|
{
|
|
3178
3313
|
name: "pi-webui-persona",
|
|
3179
3314
|
hidden: true,
|
|
@@ -3182,8 +3317,7 @@ export class ClientSession {
|
|
|
3182
3317
|
// 我们是链上最后一个 handler:先把早前扩展的首尾增补摘出来(pre/post),
|
|
3183
3318
|
// 只在 SDK 原始提示词 core 上做事,最后原样套回去——否则返回 systemPrompt
|
|
3184
3319
|
// 会整体替换,把别的扩展注入的内容(如 <invoked_skill>)一起丢掉。
|
|
3185
|
-
const {
|
|
3186
|
-
const rewrap = (next) => pre + next + post;
|
|
3320
|
+
const { core, rewrap } = prepareBotExecutionSystemPrompt(event, this.botExecution);
|
|
3187
3321
|
// 子代理模板 replace(无 SYSTEM.md 时):默认分支拼好的提示词里
|
|
3188
3322
|
// 把灵魂段换成模板提示词,自动段保留;SYSTEM.md 情形已在
|
|
3189
3323
|
// systemPromptOverride 整体替换,此处边界不存在会自然跳过。
|
|
@@ -3253,6 +3387,9 @@ export class ClientSession {
|
|
|
3253
3387
|
filePath: s.filePath ?? "",
|
|
3254
3388
|
})),
|
|
3255
3389
|
preset: currentPreset,
|
|
3390
|
+
// SYSTEM.md / APPEND_SYSTEM.md 的 base 取自**本会话**的 loader,不是
|
|
3391
|
+
// 「最近一次 reload 观察到」的客户端级字段(issue #812)。
|
|
3392
|
+
session: sess ?? undefined,
|
|
3256
3393
|
});
|
|
3257
3394
|
if (rendered) {
|
|
3258
3395
|
return { systemPrompt: rewrap(rendered) };
|
|
@@ -3271,6 +3408,9 @@ export class ClientSession {
|
|
|
3271
3408
|
],
|
|
3272
3409
|
},
|
|
3273
3410
|
});
|
|
3411
|
+
// override 的首次重放发生在 createAgentSessionServices 内部(那时还没有加载器
|
|
3412
|
+
// 句柄):拿到 loader 后补登记一次,后续 session.reload() 直接按 loader 写。
|
|
3413
|
+
promptBase.bind(services.resourceLoader);
|
|
3274
3414
|
// 桥接工具目标(问卷 / 页面):每次调用都解析「现在谁持有这条对话」,
|
|
3275
3415
|
// 而不是认这个 runtime 是在哪个 ClientSession 里建出来的(过户会换主)。
|
|
3276
3416
|
// anchor 在拿到 created.session 后回填(SDK 的 runtime.session 就是它)。
|
|
@@ -3457,9 +3597,11 @@ export class ClientSession {
|
|
|
3457
3597
|
? makeSubagentTools(withSubagentOwner(this.communicationBoundSubagentHost(bridgeAnchor), ownerId, () => this.requireSubagentOwner(bridgeAnchor, ownerId)), undefined,
|
|
3458
3598
|
// B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
|
|
3459
3599
|
// 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
|
|
3460
|
-
() =>
|
|
3461
|
-
|
|
3462
|
-
|
|
3600
|
+
() => {
|
|
3601
|
+
const home = bridgeAnchor.session && this.findConversationHome?.(bridgeAnchor.session);
|
|
3602
|
+
const conv = home?.session.convs.get(home.convId);
|
|
3603
|
+
return conv ? conversationIdentity(conv) : undefined;
|
|
3604
|
+
})
|
|
3463
3605
|
: makeSubagentTools(this.subagentHost)),
|
|
3464
3606
|
makeCommunicateTool({
|
|
3465
3607
|
communicate: (action, args, signal) => this.communicateFromSession(bridgeAnchor, action, args, signal),
|
|
@@ -3470,7 +3612,7 @@ export class ClientSession {
|
|
|
3470
3612
|
? []
|
|
3471
3613
|
: ownerId
|
|
3472
3614
|
? [
|
|
3473
|
-
makeDelegateTaskTool(withSubagentOwner(this.
|
|
3615
|
+
makeDelegateTaskTool(withSubagentOwner(this.communicationBoundSubagentHost(bridgeAnchor), ownerId, () => this.requireSubagentOwner(bridgeAnchor, ownerId))),
|
|
3474
3616
|
]
|
|
3475
3617
|
: [makeDelegateTaskTool(this.subagentHost)]),
|
|
3476
3618
|
// 结构化任务计划更新(Plan Mode / Step State Machine)。
|
|
@@ -3484,7 +3626,7 @@ export class ClientSession {
|
|
|
3484
3626
|
};
|
|
3485
3627
|
}, (msg) => this.emit(msg), () => this.flushSnapshot()),
|
|
3486
3628
|
// 标准引擎的 ask_user_question:模型调用 → 浏览器富渲染问卷(复用 DSH
|
|
3487
|
-
// 的 question_pending/question_answer 协议,前端
|
|
3629
|
+
// 的 question_pending/question_answer 协议,前端 QuestionDialog)。
|
|
3488
3630
|
// DSH 引擎不经此(它走 goal-rpc 的 userQuestions provider)。
|
|
3489
3631
|
makeAskUserQuestionTool(bridge, ownerId),
|
|
3490
3632
|
// 浏览器页面工具:模型调用 → page_request 给浏览器 → page-picker 扩展
|
|
@@ -3569,7 +3711,8 @@ export class ClientSession {
|
|
|
3569
3711
|
askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
|
|
3570
3712
|
getConversationId: () => ownerId,
|
|
3571
3713
|
}, () => this.getLang()),
|
|
3572
|
-
|
|
3714
|
+
// 设备中心群任务协作工具(仅在群任务 Bot 执行上下文注入;普通单聊完全不挂载)。
|
|
3715
|
+
...(this.botExecution ? [makeDeviceCollabTool()] : []),
|
|
3573
3716
|
// Git 工作树管理工具(worktree:list/create/switch/remove)。
|
|
3574
3717
|
makeWorktreeTool({
|
|
3575
3718
|
getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
|
|
@@ -3639,16 +3782,154 @@ export class ClientSession {
|
|
|
3639
3782
|
makeGoalStatus() {
|
|
3640
3783
|
return this.goalSvc.makeGoalStatus();
|
|
3641
3784
|
}
|
|
3785
|
+
readConversationIndependent(session) {
|
|
3786
|
+
let independent = !isPseudoClientId(this.clientId ?? "") && !this.clientId?.startsWith("device-task-");
|
|
3787
|
+
for (const entry of session.sessionManager.getEntries()) {
|
|
3788
|
+
if (entry.type === "custom" && entry.customType === "webui/independent")
|
|
3789
|
+
independent = entry.data?.independent !== false;
|
|
3790
|
+
}
|
|
3791
|
+
return independent;
|
|
3792
|
+
}
|
|
3793
|
+
setConversationIndependent(id, independent) {
|
|
3794
|
+
const conv = this.convs.get(id);
|
|
3795
|
+
if (!conv)
|
|
3796
|
+
return;
|
|
3797
|
+
conv.session.sessionManager.appendCustomEntry("webui/independent", { independent });
|
|
3798
|
+
conv.independent = independent;
|
|
3799
|
+
this.emitConversations();
|
|
3800
|
+
}
|
|
3642
3801
|
/** Allocate a stable conversation id before constructing its runtime/tools. */
|
|
3643
3802
|
nextConversationId() {
|
|
3644
3803
|
return `c${++this.convSeq}`;
|
|
3645
3804
|
}
|
|
3646
3805
|
/** Wrap a fresh runtime as a new conversation record. */
|
|
3806
|
+
conversationViewers = new Map();
|
|
3807
|
+
sharedTerminalSinks = new Map();
|
|
3808
|
+
emitSharedInteraction(msg) {
|
|
3809
|
+
this.emit(msg);
|
|
3810
|
+
}
|
|
3811
|
+
sharedPendingMessages() {
|
|
3812
|
+
const messages = [];
|
|
3813
|
+
for (const request of this.pendingQuestions.values()) {
|
|
3814
|
+
if (request.settled || request.audience !== "user")
|
|
3815
|
+
continue;
|
|
3816
|
+
messages.push({
|
|
3817
|
+
type: "question_pending",
|
|
3818
|
+
id: request.id,
|
|
3819
|
+
questions: request.questions,
|
|
3820
|
+
deadline: request.deadline,
|
|
3821
|
+
conversationId: request.conversationId,
|
|
3822
|
+
conversationTitle: this.convs.get(request.conversationId)?.title,
|
|
3823
|
+
});
|
|
3824
|
+
}
|
|
3825
|
+
for (const approval of this.pendingApprovalsForSnapshot())
|
|
3826
|
+
messages.push({ type: "tool_approval_pending", ...approval });
|
|
3827
|
+
return messages;
|
|
3828
|
+
}
|
|
3829
|
+
subscribeConversation(conv, send) {
|
|
3830
|
+
if (this.convs.get(conv.id) !== conv)
|
|
3831
|
+
throw new Error("Conversation is no longer available");
|
|
3832
|
+
let viewers = this.conversationViewers.get(conv);
|
|
3833
|
+
if (!viewers)
|
|
3834
|
+
this.conversationViewers.set(conv, (viewers = new Set()));
|
|
3835
|
+
let timer;
|
|
3836
|
+
let closed = false;
|
|
3837
|
+
let previous;
|
|
3838
|
+
const pushNow = () => {
|
|
3839
|
+
timer = undefined;
|
|
3840
|
+
if (closed || this.convs.get(conv.id) !== conv)
|
|
3841
|
+
return;
|
|
3842
|
+
const state = this.snapshotForConversation(conv);
|
|
3843
|
+
const prior = previous;
|
|
3844
|
+
previous = state;
|
|
3845
|
+
const appendOnly = prior &&
|
|
3846
|
+
state.sessionId === prior.sessionId &&
|
|
3847
|
+
state.messages.length >= prior.messages.length &&
|
|
3848
|
+
prior.messages.every((message, index) => state.messages[index] === message);
|
|
3849
|
+
if (appendOnly) {
|
|
3850
|
+
const { messages, ...light } = state;
|
|
3851
|
+
send({
|
|
3852
|
+
type: "snapshot_delta",
|
|
3853
|
+
conversationId: conv.id,
|
|
3854
|
+
rev: state.rev,
|
|
3855
|
+
baseRev: prior.rev,
|
|
3856
|
+
appended: messages.slice(prior.messages.length),
|
|
3857
|
+
state: light,
|
|
3858
|
+
});
|
|
3859
|
+
}
|
|
3860
|
+
else
|
|
3861
|
+
send({ type: "snapshot", state });
|
|
3862
|
+
};
|
|
3863
|
+
const push = () => {
|
|
3864
|
+
if (!timer && !closed)
|
|
3865
|
+
timer = setTimeout(pushNow, 60);
|
|
3866
|
+
};
|
|
3867
|
+
const deltaSink = (message) => {
|
|
3868
|
+
if (!closed &&
|
|
3869
|
+
this.convs.get(conv.id) === conv &&
|
|
3870
|
+
(message.type === "message_delta" || message.type === "tool_delta" || message.type === "terminal_list"
|
|
3871
|
+
? message.conversationId === conv.id
|
|
3872
|
+
: (message.type === "terminal_output" || message.type === "terminal_exit") &&
|
|
3873
|
+
message.conversationId === conv.id &&
|
|
3874
|
+
message.ownerKind === "conversation"))
|
|
3875
|
+
send(message);
|
|
3876
|
+
};
|
|
3877
|
+
let terminalSinks = this.sharedTerminalSinks.get(conv);
|
|
3878
|
+
if (!terminalSinks)
|
|
3879
|
+
this.sharedTerminalSinks.set(conv, (terminalSinks = new Set()));
|
|
3880
|
+
terminalSinks.add(deltaSink);
|
|
3881
|
+
this.attachSink(deltaSink);
|
|
3882
|
+
viewers.add(push);
|
|
3883
|
+
pushNow();
|
|
3884
|
+
return () => {
|
|
3885
|
+
closed = true;
|
|
3886
|
+
if (timer)
|
|
3887
|
+
clearTimeout(timer);
|
|
3888
|
+
this.detachSink(deltaSink);
|
|
3889
|
+
terminalSinks.delete(deltaSink);
|
|
3890
|
+
if (!terminalSinks.size)
|
|
3891
|
+
this.sharedTerminalSinks.delete(conv);
|
|
3892
|
+
viewers.delete(push);
|
|
3893
|
+
if (!viewers.size)
|
|
3894
|
+
this.conversationViewers.delete(conv);
|
|
3895
|
+
};
|
|
3896
|
+
}
|
|
3897
|
+
snapshotForConversation(conv) {
|
|
3898
|
+
if (this.convs.get(conv.id) !== conv)
|
|
3899
|
+
throw new Error("Conversation is no longer available");
|
|
3900
|
+
const state = this.buildLightState(++this.snapRev, true, conv);
|
|
3901
|
+
return {
|
|
3902
|
+
...state,
|
|
3903
|
+
pendingApprovals: state.pendingApprovals?.filter((entry) => entry.conversationId === conv.id),
|
|
3904
|
+
cwd: conv.cwd,
|
|
3905
|
+
messages: this.messagesOf(conv),
|
|
3906
|
+
};
|
|
3907
|
+
}
|
|
3908
|
+
async abortConversation(conv) {
|
|
3909
|
+
if (this.convs.get(conv.id) !== conv)
|
|
3910
|
+
return;
|
|
3911
|
+
conv.goalGeneration++;
|
|
3912
|
+
try {
|
|
3913
|
+
conv.session.clearQueue?.();
|
|
3914
|
+
}
|
|
3915
|
+
catch (err) {
|
|
3916
|
+
console.error("[agent-service] clearQueue failed during abortConversation:", err);
|
|
3917
|
+
}
|
|
3918
|
+
conv.queueSteering = [];
|
|
3919
|
+
conv.queueFollowUp = [];
|
|
3920
|
+
conv.queuedSteeringEntries = [];
|
|
3921
|
+
conv.queuedFollowUpEntries = [];
|
|
3922
|
+
conv.queuedSteeringRequestIds?.clear();
|
|
3923
|
+
await this.interruptRun(conv, "已停止");
|
|
3924
|
+
for (const push of this.conversationViewers?.get(conv) ?? [])
|
|
3925
|
+
push();
|
|
3926
|
+
}
|
|
3647
3927
|
makeConversation(runtime, id, terminals) {
|
|
3648
3928
|
const conv = {
|
|
3649
3929
|
id,
|
|
3650
3930
|
title: conversationTitle(runtime.session),
|
|
3651
3931
|
isSubagent: false,
|
|
3932
|
+
independent: this.readConversationIndependent(runtime.session),
|
|
3652
3933
|
runtime,
|
|
3653
3934
|
session: runtime.session,
|
|
3654
3935
|
cwd: restoreWorkspaceUriFromSessionDir(runtime.cwd),
|
|
@@ -3692,6 +3973,7 @@ export class ClientSession {
|
|
|
3692
3973
|
toolWatchdogs: new Map(),
|
|
3693
3974
|
workspaceSnapshots: readWorkspaceSnapshotsFromSession(runtime.session.sessionManager),
|
|
3694
3975
|
};
|
|
3976
|
+
conversationIdentity(conv);
|
|
3695
3977
|
this.restorePlan(conv);
|
|
3696
3978
|
return conv;
|
|
3697
3979
|
}
|
|
@@ -4095,6 +4377,7 @@ export class ClientSession {
|
|
|
4095
4377
|
this.onRunEvent({
|
|
4096
4378
|
...ev,
|
|
4097
4379
|
conversationId: conv.id,
|
|
4380
|
+
sessionId: conv.session.sessionId,
|
|
4098
4381
|
clientId: this.clientId,
|
|
4099
4382
|
// 通道插件按它认领「自己那一轮」——过户换持有客户端、对话被改 id 都不影响。
|
|
4100
4383
|
...(conv.pluginRunId ? { runId: conv.pluginRunId } : {}),
|
|
@@ -4890,6 +5173,10 @@ export class ClientSession {
|
|
|
4890
5173
|
// Deferred settings reload: settings (system prompt / skills /
|
|
4891
5174
|
// extensions) changed while the run was streaming — applying now
|
|
4892
5175
|
// would have torn down the in-flight run.
|
|
5176
|
+
const settingsTarget = this.conversationSettingsTargets.get(conv);
|
|
5177
|
+
if (settingsTarget && this.settingsSvc.consumePendingReload(settingsTarget) && !this.disposed) {
|
|
5178
|
+
void this.settingsSvc.applyRuntime(false, settingsTarget).catch(() => { });
|
|
5179
|
+
}
|
|
4893
5180
|
if (this.settingsSvc.hasPendingReload() && !this.disposed) {
|
|
4894
5181
|
this.settingsSvc.consumePendingReload();
|
|
4895
5182
|
void this.applySettingsReload();
|
|
@@ -4951,6 +5238,12 @@ export class ClientSession {
|
|
|
4951
5238
|
break;
|
|
4952
5239
|
}
|
|
4953
5240
|
case "agent_settled": {
|
|
5241
|
+
// agent_end can precede both SDK idle and kickoff's finally. Retry at
|
|
5242
|
+
// each settlement boundary; the scheduler rechecks manual dependencies.
|
|
5243
|
+
const owner = this.findConversationHome?.(conv.session)?.session ?? this;
|
|
5244
|
+
if (owner.convs.get(conv.id) === conv && conv.isSubagent && !conv.promptInFlight && !conv.session.isStreaming) {
|
|
5245
|
+
owner.scheduleSubagentCompletionNotice(conv);
|
|
5246
|
+
}
|
|
4954
5247
|
// 记录本会话自己的 Base 基线:currentBaseTokens 必须传 conv(否则串成
|
|
4955
5248
|
// 活跃会话的基线);快照未就绪时保持 undefined,宁可少补偿也不把 0 钉死。
|
|
4956
5249
|
// 只有在真正获得了有效的大模型回复 usage 时才落账(被 abort 或网络失败全 0 不落账,
|
|
@@ -5060,7 +5353,7 @@ export class ClientSession {
|
|
|
5060
5353
|
// stale state. Only the ACTIVE conversation streams to the browser —
|
|
5061
5354
|
// background conversations would clobber the streaming view; their
|
|
5062
5355
|
// state arrives via snapshot when switched to.
|
|
5063
|
-
if (conv.id !== this.conv.id)
|
|
5356
|
+
if (conv.id !== this.conv.id && !this.conversationViewers?.has(conv))
|
|
5064
5357
|
break;
|
|
5065
5358
|
const ame = event.assistantMessageEvent;
|
|
5066
5359
|
const m = event.message;
|
|
@@ -5106,6 +5399,8 @@ export class ClientSession {
|
|
|
5106
5399
|
// #259 实测 8 子代理 × 5 次 bash → 8 条全量快照共 39.5MB,而激活对话一个
|
|
5107
5400
|
// 字节都没变。后台对话的内容在切过去时取(switch_session / get_state 强制
|
|
5108
5401
|
// 全量),它在左栏的运行态由 emitConversations 走另一条通道。
|
|
5402
|
+
for (const push of this.conversationViewers?.get(conv) ?? [])
|
|
5403
|
+
push();
|
|
5109
5404
|
if (conv.id !== this.conv.id)
|
|
5110
5405
|
return;
|
|
5111
5406
|
const eventMsgRole = event.type === "message_start" || event.type === "message_end"
|
|
@@ -5288,8 +5583,7 @@ export class ClientSession {
|
|
|
5288
5583
|
cache.delete(key);
|
|
5289
5584
|
}
|
|
5290
5585
|
/** Build every UiState field EXCEPT messages (the expensive part). */
|
|
5291
|
-
buildLightState(rev, withDraft = false) {
|
|
5292
|
-
const conv = this.conv;
|
|
5586
|
+
buildLightState(rev, withDraft = false, conv = this.conv) {
|
|
5293
5587
|
const state = conv.session.agent.state;
|
|
5294
5588
|
const model = state.model;
|
|
5295
5589
|
let stats = {
|
|
@@ -5299,7 +5593,7 @@ export class ClientSession {
|
|
|
5299
5593
|
contextUsage: { tokens: null, contextWindow: 0, percent: null },
|
|
5300
5594
|
};
|
|
5301
5595
|
try {
|
|
5302
|
-
const s = this.sessionStats();
|
|
5596
|
+
const s = this.sessionStats(conv.session);
|
|
5303
5597
|
stats = {
|
|
5304
5598
|
totalMessages: s.totalMessages,
|
|
5305
5599
|
tokens: s.tokens,
|
|
@@ -5343,20 +5637,21 @@ export class ClientSession {
|
|
|
5343
5637
|
// 用户主目录(右栏 🏠):进程内不变,模块级求值一次,不在热路径调 homedir()。
|
|
5344
5638
|
homeDir: HOME_WIRE,
|
|
5345
5639
|
desktopDir: DESKTOP_WIRE,
|
|
5346
|
-
sessionId:
|
|
5347
|
-
sessionFile:
|
|
5348
|
-
conversationId:
|
|
5640
|
+
sessionId: conv.session.sessionId,
|
|
5641
|
+
sessionFile: conv.session.sessionFile,
|
|
5642
|
+
conversationId: conv.id,
|
|
5643
|
+
sharedConversation: null,
|
|
5349
5644
|
// 临时对话标记(issue #285):提示条/转正按钮跟当前对话走。
|
|
5350
5645
|
// 不能只靠 conversations 列表 —— 空白的临时对话不在运行列表里(shownInRunningList
|
|
5351
5646
|
// 只列有内容的),刚新建时列表里查不到它,提示条就永远不出现。
|
|
5352
5647
|
// 必须**恒存在**(不能只在 true 时展开):转正后它由 true→false,而增量快照是
|
|
5353
5648
|
// `{...ui, ...d.state}` 浅合并,缺字段会把 true 残留下来。
|
|
5354
|
-
isEphemeral: !!
|
|
5355
|
-
sandbox: this.sandboxes?.getByCwd(
|
|
5356
|
-
worktree: this.worktreeInfo ?? null,
|
|
5649
|
+
isEphemeral: !!conv.isEphemeral,
|
|
5650
|
+
sandbox: this.sandboxes?.getByCwd(conv.cwd) ?? null,
|
|
5651
|
+
worktree: conv.cwd === this.cwd ? (this.worktreeInfo ?? null) : null,
|
|
5357
5652
|
rev,
|
|
5358
5653
|
streamingMessage,
|
|
5359
|
-
isStreaming:
|
|
5654
|
+
isStreaming: conv.session.isStreaming,
|
|
5360
5655
|
completionPending: this.completionPending(conv),
|
|
5361
5656
|
turnTiming: conv.turnTiming ?? null,
|
|
5362
5657
|
model: model
|
|
@@ -5370,7 +5665,7 @@ export class ClientSession {
|
|
|
5370
5665
|
thinkingLevel: state.thinkingLevel,
|
|
5371
5666
|
// Only the levels the current model actually supports — the SDK clamps
|
|
5372
5667
|
// anything else, so the UI must not offer (or must disable) the rest.
|
|
5373
|
-
availableThinkingLevels:
|
|
5668
|
+
availableThinkingLevels: conv.session.getAvailableThinkingLevels(),
|
|
5374
5669
|
queue: {
|
|
5375
5670
|
steering: conv.queueSteering,
|
|
5376
5671
|
followUp: conv.queueFollowUp,
|
|
@@ -5382,13 +5677,13 @@ export class ClientSession {
|
|
|
5382
5677
|
errorMessage: state.errorMessage,
|
|
5383
5678
|
retry: conv.retryState ?? null,
|
|
5384
5679
|
compaction: conv.compactionState ?? null,
|
|
5385
|
-
pendingQuestion: this.pendingQuestionForSnapshot(),
|
|
5386
|
-
actionSuggestions: this.markerSvc.getActionSuggestions(
|
|
5387
|
-
pendingApproval: this.pendingApprovalForSnapshot(),
|
|
5680
|
+
pendingQuestion: this.pendingQuestionForSnapshot(conv),
|
|
5681
|
+
actionSuggestions: this.markerSvc.getActionSuggestions(conv.id) ?? null,
|
|
5682
|
+
pendingApproval: this.pendingApprovalForSnapshot(conv),
|
|
5388
5683
|
pendingApprovals: this.pendingApprovalsForSnapshot(),
|
|
5389
5684
|
// 任务计划看板状态同样是会话级:快照恒给 PlanState 或 null(不用 undefined),
|
|
5390
5685
|
// 否则 snapshot_delta 里 key 缺席 → 前端 spread 浅合并会残留上一对话的 plan。
|
|
5391
|
-
plan: this.planManager.getPlan(
|
|
5686
|
+
plan: this.planManager.getPlan(conv.id) ?? null,
|
|
5392
5687
|
// 计划模式是**会话级**开关:快照恒给布尔(不用 undefined),否则
|
|
5393
5688
|
// snapshot_delta 里 key 缺席 → 前端 spread 合并会残留上一对话的 true。
|
|
5394
5689
|
planMode: conv?.planMode === true,
|
|
@@ -5409,7 +5704,7 @@ export class ClientSession {
|
|
|
5409
5704
|
// 未发送草稿只跟全量快照走(切会话/new_chat/get_state):增量 delta 里
|
|
5410
5705
|
// 这个 key 必须整个缺席(不能是显式的 undefined——前端 delta 合并是
|
|
5411
5706
|
// {...ui, ...d.state} 整批覆盖,显式 undefined 会把上次全量带回的草稿洗掉)。
|
|
5412
|
-
...(withDraft ? { draft: this.draftForSnapshot() } : {}),
|
|
5707
|
+
...(withDraft ? { draft: this.draftForSnapshot(conv) } : {}),
|
|
5413
5708
|
engineCapabilities: DEFAULT_PI_CAPABILITIES,
|
|
5414
5709
|
tools: state.tools.map((t) => t.name),
|
|
5415
5710
|
version: ++this.version,
|
|
@@ -5434,6 +5729,9 @@ export class ClientSession {
|
|
|
5434
5729
|
emitSnapshotNow(forceFull = false) {
|
|
5435
5730
|
if (this.disposed)
|
|
5436
5731
|
return;
|
|
5732
|
+
for (const viewers of this.conversationViewers?.values() ?? [])
|
|
5733
|
+
for (const push of viewers)
|
|
5734
|
+
push();
|
|
5437
5735
|
if (this.convs.size === 0) {
|
|
5438
5736
|
// 自愈兜底:没有任何活跃对话,异步触发 newChat 恢复状态,避免抛错挂死
|
|
5439
5737
|
void this.newChat()
|
|
@@ -5567,8 +5865,7 @@ export class ClientSession {
|
|
|
5567
5865
|
const seen = new Set();
|
|
5568
5866
|
while (root.parentId && !seen.has(root)) {
|
|
5569
5867
|
seen.add(root);
|
|
5570
|
-
const
|
|
5571
|
-
const parent = owner.convs.get(owner.subagentCurrentId(root.parentId));
|
|
5868
|
+
const parent = this.parentExecution(root)?.conv;
|
|
5572
5869
|
if (!parent || !sameCwd(parent.cwd, conv.cwd))
|
|
5573
5870
|
break;
|
|
5574
5871
|
root = parent;
|
|
@@ -5586,8 +5883,7 @@ export class ClientSession {
|
|
|
5586
5883
|
const seen = new Set();
|
|
5587
5884
|
while (root.parentId && !seen.has(root)) {
|
|
5588
5885
|
seen.add(root);
|
|
5589
|
-
const
|
|
5590
|
-
const parent = holder.convs.get(holder.subagentCurrentId(root.parentId));
|
|
5886
|
+
const parent = owner.parentExecution(root)?.conv;
|
|
5591
5887
|
if (!parent || !sameCwd(parent.cwd, conv.cwd))
|
|
5592
5888
|
break;
|
|
5593
5889
|
root = parent;
|
|
@@ -5610,11 +5906,16 @@ export class ClientSession {
|
|
|
5610
5906
|
}
|
|
5611
5907
|
getPendingConsults(parentId) {
|
|
5612
5908
|
const parentOwner = this.subagentOwnerOf(parentId);
|
|
5613
|
-
const currentParentId =
|
|
5909
|
+
const currentParentId = this.subagentCurrentId(parentId);
|
|
5614
5910
|
const parent = parentOwner.convs.get(currentParentId);
|
|
5615
5911
|
if (!parent)
|
|
5616
5912
|
return [];
|
|
5617
|
-
const result = conversationCommunication
|
|
5913
|
+
const result = conversationCommunication
|
|
5914
|
+
.incomingRequests(parent)
|
|
5915
|
+
.map((request) => {
|
|
5916
|
+
const source = conversationCommunication.requestSource(request.requestId);
|
|
5917
|
+
return { ...request, runId: source ? conversationIdentity(source) : request.runId };
|
|
5918
|
+
});
|
|
5618
5919
|
for (const owner of new Set([this, ...(this.allSubagentSessions?.() ?? [])])) {
|
|
5619
5920
|
for (const request of owner.pendingQuestions.values()) {
|
|
5620
5921
|
const child = owner.convs.get(request.conversationId);
|
|
@@ -5622,9 +5923,10 @@ export class ClientSession {
|
|
|
5622
5923
|
continue;
|
|
5623
5924
|
if (!request.settled &&
|
|
5624
5925
|
request.audience === "parent" &&
|
|
5625
|
-
child
|
|
5926
|
+
child &&
|
|
5927
|
+
owner.parentExecution(child)?.conv === parent &&
|
|
5626
5928
|
sameCwd(child.cwd, parent.cwd)) {
|
|
5627
|
-
result.push({ runId: child
|
|
5929
|
+
result.push({ runId: conversationIdentity(child), requestId: request.id, questions: request.questions });
|
|
5628
5930
|
}
|
|
5629
5931
|
}
|
|
5630
5932
|
}
|
|
@@ -5639,29 +5941,25 @@ export class ClientSession {
|
|
|
5639
5941
|
}
|
|
5640
5942
|
resolveCommunicationTarget(senderId, to) {
|
|
5641
5943
|
const owner = this.subagentOwnerOf(senderId);
|
|
5642
|
-
const sender = owner.convs.get(
|
|
5944
|
+
const sender = owner.convs.get(this.subagentCurrentId(senderId));
|
|
5643
5945
|
if (!sender)
|
|
5644
5946
|
return undefined;
|
|
5645
5947
|
if (to === "parent") {
|
|
5646
|
-
|
|
5647
|
-
return undefined;
|
|
5648
|
-
const parentOwner = owner.subagentOwnerOf(sender.parentId);
|
|
5649
|
-
return parentOwner.convs.get(parentOwner.subagentCurrentId(sender.parentId));
|
|
5948
|
+
return owner.parentExecution(sender)?.conv;
|
|
5650
5949
|
}
|
|
5651
5950
|
if (to === "root") {
|
|
5652
5951
|
let root = sender;
|
|
5653
5952
|
const seen = new Set();
|
|
5654
5953
|
while (root.parentId && !seen.has(root)) {
|
|
5655
5954
|
seen.add(root);
|
|
5656
|
-
const
|
|
5657
|
-
const parent = parentOwner.convs.get(parentOwner.subagentCurrentId(root.parentId));
|
|
5955
|
+
const parent = owner.parentExecution(root)?.conv;
|
|
5658
5956
|
if (!parent)
|
|
5659
5957
|
break;
|
|
5660
5958
|
root = parent;
|
|
5661
5959
|
}
|
|
5662
5960
|
return root;
|
|
5663
5961
|
}
|
|
5664
|
-
if (to.startsWith("
|
|
5962
|
+
if (to.startsWith("exec-")) {
|
|
5665
5963
|
for (const candidate of new Set([this, ...(this.allSubagentSessions?.() ?? [])])) {
|
|
5666
5964
|
for (const conv of candidate.convs.values())
|
|
5667
5965
|
if (communicationAddress(conv) === to)
|
|
@@ -5689,6 +5987,16 @@ export class ClientSession {
|
|
|
5689
5987
|
};
|
|
5690
5988
|
return {
|
|
5691
5989
|
...this.subagentHost,
|
|
5990
|
+
resolveConversationId: (id) => current().session.resolveExecution(id)?.convId,
|
|
5991
|
+
getSubagent: (id) => current().session.subagentHost.getSubagent(id),
|
|
5992
|
+
listSubagents: (scope, self) => current().session.subagentHost.listSubagents(scope, self),
|
|
5993
|
+
steerSubagent: (id, message) => current().session.subagentHost.steerSubagent(id, message),
|
|
5994
|
+
stopSubagent: (id) => current().session.subagentHost.stopSubagent(id),
|
|
5995
|
+
markSubagentsConsumed: (ids) => current().session.subagentHost.markSubagentsConsumed?.(ids),
|
|
5996
|
+
finalizeSubagentWorktree: (id) => current().session.subagentHost.finalizeSubagentWorktree?.(id) ?? Promise.resolve(),
|
|
5997
|
+
dismissSubagent: (id, options) => current().session.subagentHost.dismissSubagent?.(id, options) ??
|
|
5998
|
+
Promise.resolve({ ok: false, reason: "unsupported" }),
|
|
5999
|
+
getActiveConversationId: () => current().session.activeId,
|
|
5692
6000
|
spawnSubagent: (prompt, type, cwd, templateName, model, _parentId, persist, thinking, notifyOnDone, isolation, extra, signal) => {
|
|
5693
6001
|
// Resolve by runtime identity: a moved parent's new id can also name
|
|
5694
6002
|
// the replacement conversation in the original client.
|
|
@@ -5701,15 +6009,15 @@ export class ClientSession {
|
|
|
5701
6009
|
},
|
|
5702
6010
|
consultParent: (_self, questions, signal) => {
|
|
5703
6011
|
const home = current();
|
|
5704
|
-
return home.session.consultParent(home.convId, questions, signal);
|
|
6012
|
+
return home.session.consultParent(conversationIdentity(home.session.convs.get(home.convId)), questions, signal);
|
|
5705
6013
|
},
|
|
5706
6014
|
answerConsult: (_self, runId, requestId, answers) => {
|
|
5707
6015
|
const home = current();
|
|
5708
|
-
return home.session.answerConsult(home.convId, runId, requestId, answers);
|
|
6016
|
+
return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId, answers);
|
|
5709
6017
|
},
|
|
5710
6018
|
escalateConsult: (_self, runId, requestId) => {
|
|
5711
6019
|
const home = current();
|
|
5712
|
-
return home.session.answerConsult(home.convId, runId, requestId);
|
|
6020
|
+
return home.session.answerConsult(conversationIdentity(home.session.convs.get(home.convId)), runId, requestId);
|
|
5713
6021
|
},
|
|
5714
6022
|
completeSubagent: (_self, summary) => {
|
|
5715
6023
|
const home = current();
|
|
@@ -5717,7 +6025,7 @@ export class ClientSession {
|
|
|
5717
6025
|
},
|
|
5718
6026
|
getPendingConsults: () => {
|
|
5719
6027
|
const home = current();
|
|
5720
|
-
return home.session.getPendingConsults(home.convId);
|
|
6028
|
+
return home.session.getPendingConsults(conversationIdentity(home.session.convs.get(home.convId)));
|
|
5721
6029
|
},
|
|
5722
6030
|
setConsultWaiting: (_self, waiting) => {
|
|
5723
6031
|
const home = current();
|
|
@@ -5739,17 +6047,18 @@ export class ClientSession {
|
|
|
5739
6047
|
const seen = new Set();
|
|
5740
6048
|
while (!seen.has(conv)) {
|
|
5741
6049
|
seen.add(conv);
|
|
5742
|
-
if (conv.subagentWorktree && isSameOrSubpath(endpoint.cwd, conv.subagentWorktree.worktreePath))
|
|
5743
|
-
return conv.subagentWorktree.mainRepoPath;
|
|
5744
6050
|
if (!conv.parentId)
|
|
5745
6051
|
break;
|
|
5746
|
-
const
|
|
5747
|
-
const parent = parentOwner.convs.get(parentOwner.subagentCurrentId(conv.parentId));
|
|
6052
|
+
const parent = this.parentExecution(conv)?.conv;
|
|
5748
6053
|
if (!parent)
|
|
5749
6054
|
break;
|
|
5750
6055
|
conv = parent;
|
|
5751
6056
|
}
|
|
5752
|
-
|
|
6057
|
+
if (conv.subagentWorktree && isSameOrSubpath(conv.cwd, conv.subagentWorktree.worktreePath))
|
|
6058
|
+
return normalizePathKey(conv.subagentWorktree.mainRepoPath);
|
|
6059
|
+
// A child may execute in an independent checkout. Its registered ancestry,
|
|
6060
|
+
// rather than that checkout's path, determines the collaboration project.
|
|
6061
|
+
return normalizePathKey(conv.cwd);
|
|
5753
6062
|
}
|
|
5754
6063
|
communicationPending(conv) {
|
|
5755
6064
|
return conversationCommunication.pending(conv) || conversationCommunication.inbox(conv).length > 0;
|
|
@@ -5862,7 +6171,7 @@ export class ClientSession {
|
|
|
5862
6171
|
if (conv.subagentTaskStopped)
|
|
5863
6172
|
throw new Error("Communication target task was stopped");
|
|
5864
6173
|
const busy = conv.session.isStreaming || conv.promptInFlight;
|
|
5865
|
-
const text =
|
|
6174
|
+
const text = formatCommunicationMessage(envelope, source);
|
|
5866
6175
|
if (!busy) {
|
|
5867
6176
|
if (conv.isSubagent && (conv.subagentDoneNotified || conv.subagentConsumedByParent)) {
|
|
5868
6177
|
conv.subagentDoneNotified = false;
|
|
@@ -5875,8 +6184,16 @@ export class ClientSession {
|
|
|
5875
6184
|
conv.wakeReason = "other";
|
|
5876
6185
|
conv.wakeTurnHadAction = false;
|
|
5877
6186
|
}
|
|
6187
|
+
if (busy && envelope.requestId) {
|
|
6188
|
+
conv.queuedSteeringRequestIds = conv.queuedSteeringRequestIds ?? new Set();
|
|
6189
|
+
conv.queuedSteeringRequestIds.add(envelope.requestId);
|
|
6190
|
+
}
|
|
5878
6191
|
// SDK queue acceptance is delivery to this conversation, not proof that the model read it.
|
|
5879
6192
|
const delivery = conv.session.sendUserMessage(text, busy ? { deliverAs: "steer" } : undefined);
|
|
6193
|
+
void delivery.finally(() => {
|
|
6194
|
+
if (envelope.requestId)
|
|
6195
|
+
conv.queuedSteeringRequestIds?.delete(envelope.requestId);
|
|
6196
|
+
});
|
|
5880
6197
|
void delivery.catch((error) => {
|
|
5881
6198
|
owner.sendNotice({
|
|
5882
6199
|
type: "notice",
|
|
@@ -5903,11 +6220,11 @@ export class ClientSession {
|
|
|
5903
6220
|
}
|
|
5904
6221
|
answerConsult(selfId, runId, requestId, answers) {
|
|
5905
6222
|
const parentOwner = this.subagentOwnerOf(selfId);
|
|
5906
|
-
const parent = parentOwner.convs.get(
|
|
6223
|
+
const parent = parentOwner.convs.get(this.subagentCurrentId(selfId));
|
|
5907
6224
|
const owner = this.subagentOwnerOf(runId);
|
|
5908
|
-
const child = owner.convs.get(
|
|
6225
|
+
const child = owner.convs.get(this.subagentCurrentId(runId));
|
|
5909
6226
|
if (parent && child && conversationCommunication.requestSource(requestId) === child) {
|
|
5910
|
-
if (child
|
|
6227
|
+
if (owner.parentExecution(child)?.conv !== parent)
|
|
5911
6228
|
return { ok: false, error: "Only the direct parent may use the compatibility answer action." };
|
|
5912
6229
|
return this.communicate(parent.id, answers ? "reply" : "escalate", {
|
|
5913
6230
|
requestId,
|
|
@@ -5917,7 +6234,7 @@ export class ClientSession {
|
|
|
5917
6234
|
const request = owner.pendingQuestions.get(requestId);
|
|
5918
6235
|
if (!parent ||
|
|
5919
6236
|
!child ||
|
|
5920
|
-
child
|
|
6237
|
+
owner.parentExecution(child)?.conv !== parent ||
|
|
5921
6238
|
!sameCwd(parent.cwd, child.cwd) ||
|
|
5922
6239
|
!request ||
|
|
5923
6240
|
request.settled ||
|
|
@@ -5935,7 +6252,7 @@ export class ClientSession {
|
|
|
5935
6252
|
}
|
|
5936
6253
|
async consultParent(selfId, questions, signal) {
|
|
5937
6254
|
const owner = this.subagentOwnerOf(selfId);
|
|
5938
|
-
const child = owner.convs.get(
|
|
6255
|
+
const child = owner.convs.get(this.subagentCurrentId(selfId));
|
|
5939
6256
|
if (!child?.isSubagent || owner.disposed || signal?.aborted)
|
|
5940
6257
|
return Promise.resolve(null);
|
|
5941
6258
|
const parent = child.parentId ? owner.resolveCommunicationTarget(child.id, "parent") : undefined;
|
|
@@ -5954,7 +6271,8 @@ export class ClientSession {
|
|
|
5954
6271
|
const child = owner.convs.get(request.conversationId);
|
|
5955
6272
|
if (!request.settled &&
|
|
5956
6273
|
request.audience === "parent" &&
|
|
5957
|
-
child
|
|
6274
|
+
child &&
|
|
6275
|
+
owner.parentExecution(child)?.conv === parent &&
|
|
5958
6276
|
sameCwd(parent.cwd, child.cwd)) {
|
|
5959
6277
|
request.audience = "user";
|
|
5960
6278
|
changed = true;
|
|
@@ -5990,11 +6308,11 @@ export class ClientSession {
|
|
|
5990
6308
|
}
|
|
5991
6309
|
/** 快照侧的待答提问(UiState.pendingQuestion):只带当前对话的问卷——切回
|
|
5992
6310
|
* 原对话会重推快照,对话框随之回来(重连/刷新/第二标签页的恢复通道)。 */
|
|
5993
|
-
pendingQuestionForSnapshot() {
|
|
6311
|
+
pendingQuestionForSnapshot(conversation = this.conv) {
|
|
5994
6312
|
for (const [id, p] of this.pendingQuestions) {
|
|
5995
6313
|
if (p.audience !== "user" || p.settled)
|
|
5996
6314
|
continue;
|
|
5997
|
-
if (p.conversationId !== undefined && p.conversationId !==
|
|
6315
|
+
if (p.conversationId !== undefined && p.conversationId !== conversation.id)
|
|
5998
6316
|
continue;
|
|
5999
6317
|
const conv = p.conversationId !== undefined ? this.convs.get(p.conversationId) : this.conv;
|
|
6000
6318
|
const conversationTitle = conv?.title;
|
|
@@ -6074,7 +6392,7 @@ export class ClientSession {
|
|
|
6074
6392
|
resolve({ decision: "deny", reason: "会话已关闭" });
|
|
6075
6393
|
return;
|
|
6076
6394
|
}
|
|
6077
|
-
const id = `appr-${
|
|
6395
|
+
const id = `appr-${randomUUID()}`;
|
|
6078
6396
|
const targetConv = conversationId ? this.convs.get(conversationId) : this.conv;
|
|
6079
6397
|
const resolvedConvId = conversationId ?? targetConv?.id ?? this.activeId;
|
|
6080
6398
|
const conv = (resolvedConvId ? this.convs.get(resolvedConvId) : undefined) ?? targetConv;
|
|
@@ -6374,8 +6692,7 @@ export class ClientSession {
|
|
|
6374
6692
|
})))
|
|
6375
6693
|
.sort((a, b) => a.createdAt - b.createdAt);
|
|
6376
6694
|
}
|
|
6377
|
-
pendingApprovalForSnapshot() {
|
|
6378
|
-
const conv = this.conv;
|
|
6695
|
+
pendingApprovalForSnapshot(conv = this.conv) {
|
|
6379
6696
|
if (!conv?.pendingApprovals || conv.pendingApprovals.size === 0)
|
|
6380
6697
|
return null;
|
|
6381
6698
|
for (const [id, p] of conv.pendingApprovals) {
|
|
@@ -6673,8 +6990,10 @@ export class ClientSession {
|
|
|
6673
6990
|
/** 前端回页面调用结果(index.ts 的 page_response → cs.resolvePageCall)。
|
|
6674
6991
|
* 找不到 id 就静默忽略:那是正常竞态(超时后才迟到、页面刷新后重发、旧链接
|
|
6675
6992
|
* 残留),不是错误,也没人能处理。 */
|
|
6676
|
-
resolvePageCall(id, ok, result, error) {
|
|
6993
|
+
resolvePageCall(id, ok, result, error, conversationId) {
|
|
6677
6994
|
const pending = this.pendingPageCalls.get(id);
|
|
6995
|
+
if (conversationId && pending?.conversationId !== conversationId)
|
|
6996
|
+
throw new Error("Page request does not belong to the shared conversation");
|
|
6678
6997
|
if (!pending)
|
|
6679
6998
|
return;
|
|
6680
6999
|
this.pendingPageCalls.delete(id);
|
|
@@ -6883,10 +7202,8 @@ export class ClientSession {
|
|
|
6883
7202
|
* 投错。(注意不能用 runtime 对象比:SDK 会把工厂返回值包成新的 AgentSessionRuntime
|
|
6884
7203
|
* 实例,而 `runtime.session` 与本工厂的 `created.session` 是同一个对象。) */
|
|
6885
7204
|
findConversationHome = undefined;
|
|
6886
|
-
/**
|
|
6887
|
-
*
|
|
6888
|
-
* 后代)整体搬去另一会话后,旧 host 闭包仍指向源会话,subagent 工具族靠它现查持有方;
|
|
6889
|
-
* - allSubagentSessions:全部客户端会话(wait_all/list 的「本族跨会话展开」用)。 */
|
|
7205
|
+
/** Legacy lookup rejects globally ambiguous ids. Runtime routing uses resolveExecution
|
|
7206
|
+
* over live holders; allSubagentSessions also supplies cross-holder family traversal. */
|
|
6890
7207
|
findSubagentOwner = undefined;
|
|
6891
7208
|
allSubagentSessions = undefined;
|
|
6892
7209
|
/** issue #145 跨客户端同会话感知 —— attach 时由 AgentService 接线:
|
|
@@ -6901,6 +7218,7 @@ export class ClientSession {
|
|
|
6901
7218
|
* 当别处已持有该 session 文件时,直接把该会话本体从持有方迁移过来,避免创建第二个
|
|
6902
7219
|
* runtime 导致 pi-background-tasks 等扩展激活冲突与分支分叉。 */
|
|
6903
7220
|
takeOverConversationElsewhere = undefined;
|
|
7221
|
+
prepareBotSessionResume = undefined;
|
|
6904
7222
|
/** 插件 steer 跨客户端兜底钩子:attach 时由 AgentService 接线(见 steerElsewhere),
|
|
6905
7223
|
* 在其他客户端的 conversations 里找对话并由持有方执行 steer,未持有回 undefined。 */
|
|
6906
7224
|
steerConversationElsewhere = undefined;
|
|
@@ -7209,13 +7527,13 @@ export class ClientSession {
|
|
|
7209
7527
|
* Callers that need the authoritative value can still call the session
|
|
7210
7528
|
* directly; every cache hit here is at most STATS_CACHE_MS stale.
|
|
7211
7529
|
*/
|
|
7212
|
-
sessionStats() {
|
|
7530
|
+
sessionStats(session = this.session) {
|
|
7213
7531
|
const now = Date.now();
|
|
7214
7532
|
const hit = this.sessionStatsCache;
|
|
7215
|
-
if (hit && hit.session ===
|
|
7533
|
+
if (hit && hit.session === session && now - hit.at < STATS_CACHE_MS)
|
|
7216
7534
|
return hit.value;
|
|
7217
|
-
const value =
|
|
7218
|
-
this.sessionStatsCache = { at: now, session
|
|
7535
|
+
const value = session.getSessionStats();
|
|
7536
|
+
this.sessionStatsCache = { at: now, session, value };
|
|
7219
7537
|
return value;
|
|
7220
7538
|
}
|
|
7221
7539
|
scheduleSnapshot() {
|
|
@@ -7604,6 +7922,10 @@ export class ClientSession {
|
|
|
7604
7922
|
pushSettings() {
|
|
7605
7923
|
this.settingsSvc.push();
|
|
7606
7924
|
}
|
|
7925
|
+
/** Explicit resource discovery for the settings panel; never reloads the runtime. */
|
|
7926
|
+
refreshSettings() {
|
|
7927
|
+
this.settingsSvc.refreshResources();
|
|
7928
|
+
}
|
|
7607
7929
|
/**
|
|
7608
7930
|
* 统一会话配置与门控收口方法(单一事实源)。
|
|
7609
7931
|
* 无论是新建、切换、回滚、编辑重问、看门狗重置还是设置变更:
|
|
@@ -7863,8 +8185,28 @@ export class ClientSession {
|
|
|
7863
8185
|
return this.settingsSvc.savePreset(name);
|
|
7864
8186
|
}
|
|
7865
8187
|
/** Replace the current settings with the named preset and apply it. */
|
|
7866
|
-
|
|
7867
|
-
|
|
8188
|
+
conversationSettingsTargets = new WeakMap();
|
|
8189
|
+
conversationSettingsTarget(conv) {
|
|
8190
|
+
let target = this.conversationSettingsTargets.get(conv);
|
|
8191
|
+
if (!target) {
|
|
8192
|
+
const runtime = conv.runtime;
|
|
8193
|
+
target = {
|
|
8194
|
+
isStreaming: () => runtime.session.isStreaming || Boolean(conv.promptInFlight),
|
|
8195
|
+
reloadSession: async () => {
|
|
8196
|
+
if (this.disposed || this.convs.get(conv.id) !== conv || conv.runtime !== runtime)
|
|
8197
|
+
throw new Error("Conversation runtime no longer available");
|
|
8198
|
+
await runtime.session.reload();
|
|
8199
|
+
if (this.disposed || this.convs.get(conv.id) !== conv || conv.runtime !== runtime)
|
|
8200
|
+
return;
|
|
8201
|
+
this.applySessionOverrides(conv);
|
|
8202
|
+
},
|
|
8203
|
+
};
|
|
8204
|
+
this.conversationSettingsTargets.set(conv, target);
|
|
8205
|
+
}
|
|
8206
|
+
return target;
|
|
8207
|
+
}
|
|
8208
|
+
async applyPreset(name, conv) {
|
|
8209
|
+
return this.settingsSvc.applyPreset(name, conv ? this.conversationSettingsTarget(conv) : undefined);
|
|
7868
8210
|
}
|
|
7869
8211
|
/** Remove a named preset. */
|
|
7870
8212
|
async deletePreset(name) {
|
|
@@ -8501,7 +8843,7 @@ export class ClientSession {
|
|
|
8501
8843
|
if (this.botExecution) {
|
|
8502
8844
|
session.setActiveToolsByName(session
|
|
8503
8845
|
.getAllTools()
|
|
8504
|
-
.filter((tool) => this.
|
|
8846
|
+
.filter((tool) => this.botToolRegistrationAllowed(tool.name))
|
|
8505
8847
|
.map((tool) => tool.name));
|
|
8506
8848
|
return;
|
|
8507
8849
|
}
|
|
@@ -8563,7 +8905,11 @@ export class ClientSession {
|
|
|
8563
8905
|
const subagentOff = disabled.has("conversation") || disabled.has("subagent") || SPAWN_TOOLS_BARRED.has(session);
|
|
8564
8906
|
syncSubagentOverride(session, subagentOff, (name) => mergeConversationTools([
|
|
8565
8907
|
...(ownerId
|
|
8566
|
-
? makeSubagentTools(withSubagentOwner(this.communicationBoundSubagentHost({ session }), ownerId, () => this.requireSubagentOwner({ session }, ownerId)), undefined, () =>
|
|
8908
|
+
? makeSubagentTools(withSubagentOwner(this.communicationBoundSubagentHost({ session }), ownerId, () => this.requireSubagentOwner({ session }, ownerId)), undefined, () => {
|
|
8909
|
+
const home = this.findConversationHome?.(session);
|
|
8910
|
+
const conv = home?.session.convs.get(home.convId);
|
|
8911
|
+
return conv ? conversationIdentity(conv) : undefined;
|
|
8912
|
+
})
|
|
8567
8913
|
: makeSubagentTools(this.subagentHost)),
|
|
8568
8914
|
makeConversationReadTool(this.conversationReadHost(), () => this.getLang()),
|
|
8569
8915
|
]).find((tool) => tool.name === name));
|
|
@@ -9090,7 +9436,7 @@ export class ClientSession {
|
|
|
9090
9436
|
def = {
|
|
9091
9437
|
...def,
|
|
9092
9438
|
execute: async (...args) => {
|
|
9093
|
-
if (!this.botToolAllowed(def.name, cwdOverride))
|
|
9439
|
+
if (!this.botToolAllowed(def.name, cwdOverride, args[1]))
|
|
9094
9440
|
throw new Error("Tool is not authorized for this Bot");
|
|
9095
9441
|
return execute(...args);
|
|
9096
9442
|
},
|
|
@@ -9140,7 +9486,7 @@ export class ClientSession {
|
|
|
9140
9486
|
if (this.botExecution) {
|
|
9141
9487
|
const mcp = this.executionMcpBridge(cwd ?? this.cwd)?.getTools() ?? [];
|
|
9142
9488
|
return (mcp.includes(t) &&
|
|
9143
|
-
this.
|
|
9489
|
+
this.botToolRegistrationAllowed(t.name, cwd) &&
|
|
9144
9490
|
!["bash", "read", "write", "edit", "powershell", "ls", "grep", "find"].includes(t.name));
|
|
9145
9491
|
}
|
|
9146
9492
|
if (t.pluginId && disabledPlugins.has(t.pluginId))
|
|
@@ -9156,7 +9502,7 @@ export class ClientSession {
|
|
|
9156
9502
|
...def,
|
|
9157
9503
|
execute: async (...args) => {
|
|
9158
9504
|
const current = this.executionMcpBridge(cwd ?? this.cwd)?.getTools() ?? [];
|
|
9159
|
-
if (!current.includes(tool) || !this.botToolAllowed(tool.name, cwd))
|
|
9505
|
+
if (!current.includes(tool) || !this.botToolAllowed(tool.name, cwd, args[1]))
|
|
9160
9506
|
throw new Error("Bot MCP tool authorization expired");
|
|
9161
9507
|
return execute(...args);
|
|
9162
9508
|
},
|
|
@@ -9332,14 +9678,14 @@ export class ClientSession {
|
|
|
9332
9678
|
let pendingQuestions = false;
|
|
9333
9679
|
for (const owner of owners) {
|
|
9334
9680
|
for (const child of owner.convs.values()) {
|
|
9335
|
-
if (child
|
|
9681
|
+
if (owner.parentExecution(child)?.conv !== conv)
|
|
9336
9682
|
continue;
|
|
9337
9683
|
if (owner.subagentTaskPending(child, new Set(seen)) ||
|
|
9338
9684
|
(child.notifyOnDone !== false && !child.subagentDoneNotified && !child.subagentConsumedByParent))
|
|
9339
9685
|
activeChildren = true;
|
|
9340
9686
|
}
|
|
9341
9687
|
for (const request of owner.pendingQuestions?.values() ?? []) {
|
|
9342
|
-
if (!request.settled && request.conversationId === conv
|
|
9688
|
+
if (!request.settled && owner.convs.get(request.conversationId) === conv)
|
|
9343
9689
|
pendingQuestions = true;
|
|
9344
9690
|
}
|
|
9345
9691
|
}
|
|
@@ -9357,7 +9703,11 @@ export class ClientSession {
|
|
|
9357
9703
|
return true;
|
|
9358
9704
|
const owners = new Set([this, ...(this.allSubagentSessions?.() ?? [])]);
|
|
9359
9705
|
for (const owner of owners) {
|
|
9360
|
-
|
|
9706
|
+
const key = conversationIdentity(conv);
|
|
9707
|
+
if (owner.pendingSubagentNotices.has(key) || owner.deliveringSubagentNotices.has(key))
|
|
9708
|
+
return true;
|
|
9709
|
+
if (owner.convs.get(conv.id) === conv &&
|
|
9710
|
+
(owner.pendingSubagentNotices.has(conv.id) || owner.deliveringSubagentNotices.has(conv.id)))
|
|
9361
9711
|
return true;
|
|
9362
9712
|
}
|
|
9363
9713
|
return false;
|
|
@@ -9457,6 +9807,7 @@ export class ClientSession {
|
|
|
9457
9807
|
cwd: conv.cwd,
|
|
9458
9808
|
isStreaming: streaming,
|
|
9459
9809
|
convId: conv.id,
|
|
9810
|
+
independent: conv.independent !== false,
|
|
9460
9811
|
hasQuestion: !!pq,
|
|
9461
9812
|
...(pq?.title ? { questionTitle: pq.title } : {}),
|
|
9462
9813
|
...(sessionFile ? { sessionFile } : {}),
|
|
@@ -9787,7 +10138,7 @@ export class ClientSession {
|
|
|
9787
10138
|
.map((c) => {
|
|
9788
10139
|
let label;
|
|
9789
10140
|
if (c.isSubagent) {
|
|
9790
|
-
const parent =
|
|
10141
|
+
const parent = this.parentExecution(c)?.conv;
|
|
9791
10142
|
label = parent ? `本窗口「${parent.title}」的子代理「${c.title}」` : `本窗口子代理「${c.title}」`;
|
|
9792
10143
|
}
|
|
9793
10144
|
else {
|
|
@@ -10154,6 +10505,18 @@ export class ClientSession {
|
|
|
10154
10505
|
if (Array.isArray(this.conv.session?._pendingNextTurnMessages)) {
|
|
10155
10506
|
this.conv.session._pendingNextTurnMessages = [];
|
|
10156
10507
|
}
|
|
10508
|
+
// 停止时先清空 SDK 队列与本地排队镜像,防止 agent-loop 工具结束后消费排队消息导致写入对话却被中止丢消息(issue #834)
|
|
10509
|
+
try {
|
|
10510
|
+
this.conv.session.clearQueue?.();
|
|
10511
|
+
}
|
|
10512
|
+
catch (err) {
|
|
10513
|
+
console.error("[agent-service] clearQueue failed during abort:", err);
|
|
10514
|
+
}
|
|
10515
|
+
this.conv.queueSteering = [];
|
|
10516
|
+
this.conv.queueFollowUp = [];
|
|
10517
|
+
this.conv.queuedSteeringEntries = [];
|
|
10518
|
+
this.conv.queuedFollowUpEntries = [];
|
|
10519
|
+
this.conv.queuedSteeringRequestIds?.clear();
|
|
10157
10520
|
const isRunning = this.conversationStreaming(this.conv) || !this.conv.session.isIdle;
|
|
10158
10521
|
if (!isRunning) {
|
|
10159
10522
|
this.flushSnapshot();
|
|
@@ -10168,12 +10531,16 @@ export class ClientSession {
|
|
|
10168
10531
|
* 本轮已停止并标红,用户点「重试」再触发一轮 LLM 调用。不新增用户气泡——
|
|
10169
10532
|
* 用 display:false 的 custom 消息 triggerTurn 续跑,模型基于完整上下文
|
|
10170
10533
|
* (含上次报错)继续生成。流式中 / 无可重试失败时只发 notice 拒绝。 */
|
|
10171
|
-
async retryLast() {
|
|
10172
|
-
const conv = this.conv;
|
|
10534
|
+
async retryLast(targetConversation) {
|
|
10535
|
+
const conv = targetConversation ?? this.conv;
|
|
10536
|
+
if (targetConversation && this.convs.get(conv.id) !== conv)
|
|
10537
|
+
throw new Error("Retry conversation is no longer available");
|
|
10538
|
+
const runtime = conv.runtime;
|
|
10539
|
+
const s = conv.session;
|
|
10540
|
+
const current = () => this.convs.get(conv.id) === conv && conv.runtime === runtime && conv.session === s;
|
|
10173
10541
|
try {
|
|
10174
10542
|
if (this.quiesceBlocked())
|
|
10175
10543
|
return;
|
|
10176
|
-
const s = this.session;
|
|
10177
10544
|
if (s.isStreaming) {
|
|
10178
10545
|
this.emit({
|
|
10179
10546
|
type: "notice",
|
|
@@ -10230,6 +10597,8 @@ export class ClientSession {
|
|
|
10230
10597
|
],
|
|
10231
10598
|
display: false,
|
|
10232
10599
|
}, { triggerTurn: true });
|
|
10600
|
+
if (!current())
|
|
10601
|
+
return;
|
|
10233
10602
|
conv.promptedSinceActive = true;
|
|
10234
10603
|
conv.lastActiveAt = Date.now();
|
|
10235
10604
|
conv.lastSdkEventAt = Date.now();
|
|
@@ -10257,8 +10626,13 @@ export class ClientSession {
|
|
|
10257
10626
|
* item still at that position; on any mismatch we fall back to first-occurrence
|
|
10258
10627
|
* text match (old clients, or the queue shifted between click and handling).
|
|
10259
10628
|
*/
|
|
10260
|
-
async removeQueued(kind, text, index, id) {
|
|
10261
|
-
const conv = this.conv;
|
|
10629
|
+
async removeQueued(kind, text, index, id, targetConversation) {
|
|
10630
|
+
const conv = targetConversation ?? this.conv;
|
|
10631
|
+
if (targetConversation && this.convs.get(conv.id) !== conv)
|
|
10632
|
+
throw new Error("Queue conversation is no longer available");
|
|
10633
|
+
const runtime = conv.runtime;
|
|
10634
|
+
const s = conv.session;
|
|
10635
|
+
const current = () => this.convs.get(conv.id) === conv && conv.runtime === runtime && conv.session === s;
|
|
10262
10636
|
// Always-defined display mirrors; also the provenance of bubble rendering.
|
|
10263
10637
|
const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
|
|
10264
10638
|
let targetText = text;
|
|
@@ -10281,7 +10655,6 @@ export class ClientSession {
|
|
|
10281
10655
|
return;
|
|
10282
10656
|
}
|
|
10283
10657
|
}
|
|
10284
|
-
const s = this.conv.session;
|
|
10285
10658
|
if (!s) {
|
|
10286
10659
|
// Runtime not bound yet (fresh conversation) — drop the display mirror;
|
|
10287
10660
|
// a later queue_update reconciles any SDK-side state.
|
|
@@ -10352,11 +10725,17 @@ export class ClientSession {
|
|
|
10352
10725
|
// Re-queue the survivors in original order. Guard each call so a single
|
|
10353
10726
|
// failure can't leave the queue half-drained silently.
|
|
10354
10727
|
for (const entry of keptSteeringEntries) {
|
|
10728
|
+
if (!current())
|
|
10729
|
+
return;
|
|
10355
10730
|
try {
|
|
10356
10731
|
conv.queuedSteeringEntries.push(entry);
|
|
10357
10732
|
await s.steer(entry.text, entry.images);
|
|
10733
|
+
if (!current())
|
|
10734
|
+
return;
|
|
10358
10735
|
}
|
|
10359
10736
|
catch (err) {
|
|
10737
|
+
if (!current())
|
|
10738
|
+
return;
|
|
10360
10739
|
conv.queuedSteeringEntries.pop();
|
|
10361
10740
|
this.emit({
|
|
10362
10741
|
type: "notice",
|
|
@@ -10367,11 +10746,17 @@ export class ClientSession {
|
|
|
10367
10746
|
}
|
|
10368
10747
|
}
|
|
10369
10748
|
for (const entry of keptFollowUpEntries) {
|
|
10749
|
+
if (!current())
|
|
10750
|
+
return;
|
|
10370
10751
|
try {
|
|
10371
10752
|
conv.queuedFollowUpEntries.push(entry);
|
|
10372
10753
|
await s.followUp(entry.text, entry.images);
|
|
10754
|
+
if (!current())
|
|
10755
|
+
return;
|
|
10373
10756
|
}
|
|
10374
10757
|
catch (err) {
|
|
10758
|
+
if (!current())
|
|
10759
|
+
return;
|
|
10375
10760
|
conv.queuedFollowUpEntries.pop();
|
|
10376
10761
|
this.emit({
|
|
10377
10762
|
type: "notice",
|
|
@@ -10394,10 +10779,14 @@ export class ClientSession {
|
|
|
10394
10779
|
* 晚于服务端的切换到达)。空白新会话的转录还没落盘,但 id 内存里已有。
|
|
10395
10780
|
* 存完不推快照:同页的草稿本来就是自己打的;恢复走全量快照的 draft 字段。
|
|
10396
10781
|
* 陈旧写由 ComposerDraftsStore 的 clear 水位丢弃(ts <= clearTs 不复活)。 */
|
|
10397
|
-
saveDraft(sessionId, text, ts) {
|
|
10782
|
+
saveDraft(sessionId, text, ts, targetConversation) {
|
|
10398
10783
|
try {
|
|
10399
10784
|
if (!sessionId)
|
|
10400
10785
|
return;
|
|
10786
|
+
if (targetConversation &&
|
|
10787
|
+
(this.convs.get(targetConversation.id) !== targetConversation ||
|
|
10788
|
+
targetConversation.session.sessionId !== sessionId))
|
|
10789
|
+
throw new Error("Draft conversation is no longer available or does not match the session");
|
|
10401
10790
|
this.drafts.save(sessionId, text, ts);
|
|
10402
10791
|
}
|
|
10403
10792
|
catch {
|
|
@@ -10405,9 +10794,9 @@ export class ClientSession {
|
|
|
10405
10794
|
}
|
|
10406
10795
|
}
|
|
10407
10796
|
/** 当前活跃对话的草稿(全量快照用;增量 snapshot_delta 传 withDraft=false 不带)。 */
|
|
10408
|
-
draftForSnapshot() {
|
|
10797
|
+
draftForSnapshot(conv = this.conv) {
|
|
10409
10798
|
try {
|
|
10410
|
-
return this.drafts.get(
|
|
10799
|
+
return this.drafts.get(conv.session.sessionId) ?? null;
|
|
10411
10800
|
}
|
|
10412
10801
|
catch {
|
|
10413
10802
|
return null;
|
|
@@ -10669,7 +11058,7 @@ export class ClientSession {
|
|
|
10669
11058
|
}, (m) =>
|
|
10670
11059
|
// 子代理带模板时按原模板重建(conv.subagentTemplate 是派发时工厂
|
|
10671
11060
|
// 用的同一快照);普通对话 undefined,行为不变。
|
|
10672
|
-
createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id, undefined, undefined, conv.isSubagent && this.subagentAtDepthLimit(conv
|
|
11061
|
+
createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id, undefined, undefined, conv.isSubagent && this.subagentAtDepthLimit(this.parentExecutionKey(conv))), {
|
|
10673
11062
|
cwd: sessionBaseDir,
|
|
10674
11063
|
agentDir: this.agentDir,
|
|
10675
11064
|
sessionManager: m,
|
|
@@ -10739,7 +11128,7 @@ export class ClientSession {
|
|
|
10739
11128
|
* 空白新对话」——/new <prompt> 只在 true 时投递首条提示;false 表示没能进入
|
|
10740
11129
|
* 新对话(准入关闭 / 同项目对话数达上限 / runtime 创建失败),此时照发会把
|
|
10741
11130
|
* 首条提示投进用户原本正在用的那个对话里。 */
|
|
10742
|
-
async newChat(_preset, ephemeral, onReady) {
|
|
11131
|
+
async newChat(_preset, ephemeral, onReady, independent = true) {
|
|
10743
11132
|
if (this.quiesceBlocked())
|
|
10744
11133
|
return false;
|
|
10745
11134
|
// Reuse an already-open blank conversation instead of piling up new ones
|
|
@@ -10767,6 +11156,7 @@ export class ClientSession {
|
|
|
10767
11156
|
this.pushSettings();
|
|
10768
11157
|
this.flushSnapshot();
|
|
10769
11158
|
}
|
|
11159
|
+
this.setConversationIndependent(active.id, independent);
|
|
10770
11160
|
onReady?.(active.id);
|
|
10771
11161
|
return true;
|
|
10772
11162
|
}
|
|
@@ -10780,6 +11170,7 @@ export class ClientSession {
|
|
|
10780
11170
|
await this.selectAgentPreset(_preset);
|
|
10781
11171
|
else
|
|
10782
11172
|
this.flushSnapshot();
|
|
11173
|
+
this.setConversationIndependent(conv.id, independent);
|
|
10783
11174
|
onReady?.(conv.id);
|
|
10784
11175
|
return true;
|
|
10785
11176
|
}
|
|
@@ -10848,6 +11239,8 @@ export class ClientSession {
|
|
|
10848
11239
|
});
|
|
10849
11240
|
const conv = this.makeConversation(runtime, conversationId, terminals);
|
|
10850
11241
|
conv.cwd = this.cwd;
|
|
11242
|
+
conv.independent = independent;
|
|
11243
|
+
conv.session.sessionManager.appendCustomEntry("webui/independent", { independent });
|
|
10851
11244
|
if (ephemeral)
|
|
10852
11245
|
conv.isEphemeral = true;
|
|
10853
11246
|
if (_preset) {
|
|
@@ -11216,7 +11609,7 @@ export class ClientSession {
|
|
|
11216
11609
|
// Also retain a parent while any live first-party subagent conversation
|
|
11217
11610
|
// points at it: dropping an idle in-memory parent orphans the child row
|
|
11218
11611
|
// (the child vanishes from Running Chats with no result available).
|
|
11219
|
-
const hasLiveChild = [...this.convs.values()].some((child) => child
|
|
11612
|
+
const hasLiveChild = [...new Set([this, ...(this.allSubagentSessions?.() ?? [])])].some((owner) => [...owner.convs.values()].some((child) => owner.parentExecution(child)?.conv === conv));
|
|
11220
11613
|
// Ephemeral transcripts have no history fallback: once started, only an
|
|
11221
11614
|
// explicit close may discard them, even after revisiting without a prompt.
|
|
11222
11615
|
const retainFinished = (Boolean(conv.isEphemeral) || Boolean(this.settingsSvc?.current.retainFinishedConversations)) &&
|
|
@@ -11359,7 +11752,7 @@ export class ClientSession {
|
|
|
11359
11752
|
id: c.id,
|
|
11360
11753
|
title: c.title,
|
|
11361
11754
|
cwd: c.cwd,
|
|
11362
|
-
...(c
|
|
11755
|
+
...(this.localParentId(c) ? { parentId: this.localParentId(c) } : {}),
|
|
11363
11756
|
isSubagent: c.isSubagent,
|
|
11364
11757
|
isEphemeral: !!c.isEphemeral,
|
|
11365
11758
|
...(sessionFile ? { sessionFile } : {}),
|
|
@@ -11380,6 +11773,8 @@ export class ClientSession {
|
|
|
11380
11773
|
const convs = [...this.convs.values()].filter((c) => set.has(c.id));
|
|
11381
11774
|
if (convs.length === 0)
|
|
11382
11775
|
return { ok: false, reason: "missing" };
|
|
11776
|
+
for (const conv of this.convs.values())
|
|
11777
|
+
this.parentExecution(conv);
|
|
11383
11778
|
for (const conv of convs)
|
|
11384
11779
|
conv.transferring = true;
|
|
11385
11780
|
try {
|
|
@@ -11471,17 +11866,33 @@ export class ClientSession {
|
|
|
11471
11866
|
if (this.botExecution)
|
|
11472
11867
|
throw new Error("Bot sessions cannot receive transferred conversations");
|
|
11473
11868
|
const remap = new Map();
|
|
11869
|
+
const incomingIds = new Set(payload.convs.map((conv) => conv.id));
|
|
11870
|
+
const reserved = new Set([...this.convs.keys(), ...incomingIds]);
|
|
11871
|
+
// Resolve legacy parent links before any ids mutate or destination ids collide.
|
|
11872
|
+
for (const conv of payload.convs) {
|
|
11873
|
+
if (!hasConversationParentBinding(conv)) {
|
|
11874
|
+
bindConversationParent(conv, payload.convs.find((candidate) => candidate.id === conv.parentId));
|
|
11875
|
+
}
|
|
11876
|
+
}
|
|
11474
11877
|
for (const conv of payload.convs) {
|
|
11475
11878
|
if (this.convs.has(conv.id)) {
|
|
11476
|
-
|
|
11879
|
+
let next;
|
|
11880
|
+
do
|
|
11881
|
+
next = this.nextConversationId();
|
|
11882
|
+
while (reserved.has(next));
|
|
11883
|
+
reserved.add(next);
|
|
11884
|
+
remap.set(conv.id, next);
|
|
11477
11885
|
}
|
|
11478
11886
|
}
|
|
11479
11887
|
const fix = (id) => remap.get(id) ?? id;
|
|
11888
|
+
const parentDisplayIds = new Map(payload.convs.map((conv) => {
|
|
11889
|
+
const parent = conversationParent(conv);
|
|
11890
|
+
return [conv, parent ? (payload.convs.includes(parent) ? fix(parent.id) : parent.id) : undefined];
|
|
11891
|
+
}));
|
|
11480
11892
|
let mainId = "";
|
|
11481
11893
|
for (const conv of payload.convs) {
|
|
11482
11894
|
conv.id = fix(conv.id);
|
|
11483
|
-
|
|
11484
|
-
conv.parentId = fix(conv.parentId);
|
|
11895
|
+
conv.parentId = parentDisplayIds.get(conv);
|
|
11485
11896
|
if (!conv.isSubagent && !mainId) {
|
|
11486
11897
|
mainId = conv.id;
|
|
11487
11898
|
// 过户是用户显式动作:这条对话必须在某一页看得见。`listed` 一旦置位就进本页的
|
|
@@ -11561,7 +11972,7 @@ export class ClientSession {
|
|
|
11561
11972
|
for (const a of payload.approvals) {
|
|
11562
11973
|
if (settledApprovalRequests.has(a))
|
|
11563
11974
|
continue;
|
|
11564
|
-
const nid = `appr-${
|
|
11975
|
+
const nid = `appr-${randomUUID()}`;
|
|
11565
11976
|
const aConvId = fix(a.conversationId);
|
|
11566
11977
|
const targetConv = this.convs.get(aConvId);
|
|
11567
11978
|
if (targetConv) {
|
|
@@ -11639,8 +12050,22 @@ export class ClientSession {
|
|
|
11639
12050
|
}
|
|
11640
12051
|
/** Switch the ACTIVE conversation without interrupting any other chat. */
|
|
11641
12052
|
async switchConversation(id) {
|
|
11642
|
-
if (id === this.activeId)
|
|
12053
|
+
if (id === this.activeId) {
|
|
12054
|
+
// A shared view may hide the still-active local conversation. Returning
|
|
12055
|
+
// to it needs a full snapshot (the browser may hold the remote rev)
|
|
12056
|
+
// and an acknowledgement to finish the browser's navigation transition.
|
|
12057
|
+
this.flushSnapshot(true);
|
|
12058
|
+
this.emit({
|
|
12059
|
+
type: "transition_progress",
|
|
12060
|
+
kind: "conversation",
|
|
12061
|
+
target: id,
|
|
12062
|
+
phase: "done",
|
|
12063
|
+
progress: 100,
|
|
12064
|
+
text: "对话切换完成",
|
|
12065
|
+
textEn: "Conversation switched",
|
|
12066
|
+
});
|
|
11643
12067
|
return;
|
|
12068
|
+
}
|
|
11644
12069
|
if (!this.convs.has(id)) {
|
|
11645
12070
|
this.emit({
|
|
11646
12071
|
type: "transition_progress",
|
|
@@ -11757,7 +12182,7 @@ export class ClientSession {
|
|
|
11757
12182
|
// listed subagents hang under them, so both rows remain clickable.
|
|
11758
12183
|
const visibleParents = new Set([...this.convs.values()]
|
|
11759
12184
|
.filter((conv) => conv.listed)
|
|
11760
|
-
.map((conv) => conv
|
|
12185
|
+
.map((conv) => this.localParentId(conv))
|
|
11761
12186
|
.filter(Boolean));
|
|
11762
12187
|
for (const conv of this.convs.values()) {
|
|
11763
12188
|
if (!this.shownInRunningList(conv) && !visibleParents.has(conv.id))
|
|
@@ -11773,6 +12198,7 @@ export class ClientSession {
|
|
|
11773
12198
|
}
|
|
11774
12199
|
conversations.push({
|
|
11775
12200
|
id: conv.id,
|
|
12201
|
+
independent: conv.independent !== false,
|
|
11776
12202
|
title: conv.title,
|
|
11777
12203
|
cwd: conv.cwd,
|
|
11778
12204
|
messageCount,
|
|
@@ -11801,7 +12227,7 @@ export class ClientSession {
|
|
|
11801
12227
|
const pq = this.getPendingQuestionForConv(conv.id);
|
|
11802
12228
|
return pq ? { hasQuestion: true, questionId: pq.id, questionTitle: pq.title } : {};
|
|
11803
12229
|
})(),
|
|
11804
|
-
parentId: conv
|
|
12230
|
+
parentId: this.localParentId(conv),
|
|
11805
12231
|
model: conv.session.model
|
|
11806
12232
|
? `${conv.session.model.provider}/${conv.session.model.id}`
|
|
11807
12233
|
: (conv.subagentTemplate?.model ?? undefined),
|
|
@@ -12058,6 +12484,28 @@ export class ClientSession {
|
|
|
12058
12484
|
if (this.sessionsRequested)
|
|
12059
12485
|
void this.refreshSessions();
|
|
12060
12486
|
}
|
|
12487
|
+
buildSessionSummaries(targetCwd, infos) {
|
|
12488
|
+
const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
|
|
12489
|
+
const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
|
|
12490
|
+
const sessions = new Map();
|
|
12491
|
+
for (const s of visibleInfos) {
|
|
12492
|
+
const isPinned = this.stateStore?.isSessionPinned(targetCwd, s.path);
|
|
12493
|
+
const displayName = s.name?.trim() || (s.firstMessage ? s.firstMessage.trim().replace(/\s+/g, " ") : undefined);
|
|
12494
|
+
sessions.set(s.path, {
|
|
12495
|
+
path: s.path,
|
|
12496
|
+
...(s.id ? { sessionId: s.id } : {}),
|
|
12497
|
+
name: s.name,
|
|
12498
|
+
displayName,
|
|
12499
|
+
firstMessage: s.firstMessage,
|
|
12500
|
+
messageCount: s.messageCount,
|
|
12501
|
+
modified: s.modified.getTime(),
|
|
12502
|
+
source: "web",
|
|
12503
|
+
...(isPinned ? { pinned: true } : {}),
|
|
12504
|
+
...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
|
|
12505
|
+
});
|
|
12506
|
+
}
|
|
12507
|
+
return [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200);
|
|
12508
|
+
}
|
|
12061
12509
|
async pushSessions() {
|
|
12062
12510
|
if (!this.sessionsRequested)
|
|
12063
12511
|
return;
|
|
@@ -12066,34 +12514,24 @@ export class ClientSession {
|
|
|
12066
12514
|
// (<agentDir>/sessions/--<cwd>--/), the same files the pi CLI/TUI
|
|
12067
12515
|
// use — one listing covers every conversation of the current folder.
|
|
12068
12516
|
const infos = await this.loadSessionInfos();
|
|
12069
|
-
|
|
12070
|
-
// 开启 showForkedParentSessions 时保留全部会话(全文搜索 searchSessions 始终保留全部)。
|
|
12071
|
-
const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
|
|
12072
|
-
const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
|
|
12073
|
-
const sessions = new Map();
|
|
12074
|
-
for (const s of visibleInfos) {
|
|
12075
|
-
const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
|
|
12076
|
-
const displayName = s.name?.trim() || (s.firstMessage ? s.firstMessage.trim().replace(/\s+/g, " ") : undefined);
|
|
12077
|
-
sessions.set(s.path, {
|
|
12078
|
-
path: s.path,
|
|
12079
|
-
...(s.id ? { sessionId: s.id } : {}),
|
|
12080
|
-
name: s.name,
|
|
12081
|
-
displayName,
|
|
12082
|
-
firstMessage: s.firstMessage,
|
|
12083
|
-
messageCount: s.messageCount,
|
|
12084
|
-
modified: s.modified.getTime(),
|
|
12085
|
-
source: "web",
|
|
12086
|
-
...(isPinned ? { pinned: true } : {}),
|
|
12087
|
-
...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
|
|
12088
|
-
});
|
|
12089
|
-
}
|
|
12090
|
-
const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200); // newest first — the panel shows recent history
|
|
12517
|
+
const sorted = this.buildSessionSummaries(this.cwd, infos);
|
|
12091
12518
|
this.emit({ type: "sessions", sessions: sorted });
|
|
12092
12519
|
}
|
|
12093
12520
|
catch {
|
|
12094
12521
|
this.emit({ type: "sessions", sessions: [] });
|
|
12095
12522
|
}
|
|
12096
12523
|
}
|
|
12524
|
+
/** Push the persisted session list for a specific project directory (on demand, e.g. expanding an unopened project). */
|
|
12525
|
+
async pushSessionsForCwd(targetCwd) {
|
|
12526
|
+
try {
|
|
12527
|
+
const infos = await this.loadSessionInfos(targetCwd);
|
|
12528
|
+
const sorted = this.buildSessionSummaries(targetCwd, infos);
|
|
12529
|
+
this.emit({ type: "sessions", sessions: sorted, cwd: targetCwd });
|
|
12530
|
+
}
|
|
12531
|
+
catch {
|
|
12532
|
+
this.emit({ type: "sessions", sessions: [], cwd: targetCwd });
|
|
12533
|
+
}
|
|
12534
|
+
}
|
|
12097
12535
|
/** Remove an entry from the client's recent-project list (UI state only, or destroy if sandbox). */
|
|
12098
12536
|
async removeProject(path) {
|
|
12099
12537
|
const sbx = this.sandboxes.get(path) ?? this.sandboxes.getByCwd(path);
|
|
@@ -12157,33 +12595,46 @@ export class ClientSession {
|
|
|
12157
12595
|
else
|
|
12158
12596
|
await this.newChat();
|
|
12159
12597
|
// displaceActive() may have RETAINED the old conversation as a
|
|
12160
|
-
// background run
|
|
12161
|
-
//
|
|
12162
|
-
//
|
|
12163
|
-
//
|
|
12164
|
-
//
|
|
12165
|
-
//
|
|
12166
|
-
//
|
|
12598
|
+
// background run — the file is still held, so we cannot yank it from a
|
|
12599
|
+
// live runtime. What counts as "live" here is **runtime activity**
|
|
12600
|
+
// (streaming / compacting), not `listed`: `listed` is the left-panel
|
|
12601
|
+
// listing rule, and once displacement started retaining idle chats in
|
|
12602
|
+
// the running list, treating it as "still running" made deleting the
|
|
12603
|
+
// ONLY session fail forever with a bogus "still running in the
|
|
12604
|
+
// background" notice (smoke left-panel-delete has been red since
|
|
12605
|
+
// 2026-10-31 — hidden because a unit failure skipped the smoke step).
|
|
12606
|
+
// A retained-but-idle holder is released instead: deleting an explicit
|
|
12607
|
+
// transcript is user intent, and an idle runtime holding it has no
|
|
12608
|
+
// more work to do.
|
|
12167
12609
|
const stillHeld = [...this.convs.values()].find(holdsTarget);
|
|
12168
12610
|
if (stillHeld) {
|
|
12169
|
-
let stillRunning
|
|
12611
|
+
let stillRunning;
|
|
12170
12612
|
try {
|
|
12171
|
-
stillRunning = stillHeld.session.isStreaming ||
|
|
12613
|
+
stillRunning = stillHeld.session.isStreaming || stillHeld.session.isCompacting;
|
|
12172
12614
|
}
|
|
12173
12615
|
catch {
|
|
12174
|
-
|
|
12616
|
+
stillRunning = true; // 会话正在替换 —— 保守地等它
|
|
12617
|
+
}
|
|
12618
|
+
if (stillRunning) {
|
|
12619
|
+
this.emit({
|
|
12620
|
+
type: "notice",
|
|
12621
|
+
level: "warning",
|
|
12622
|
+
text: "对话仍在后台运行,已停止删除;请等待其结束后再删除",
|
|
12623
|
+
textEn: "Conversation is still running in the background; delete aborted — wait for it to finish and retry",
|
|
12624
|
+
});
|
|
12625
|
+
return;
|
|
12626
|
+
}
|
|
12627
|
+
// 空闲但被持有(后台保留 / 置换未释放)→ 放掉它占用的运行时再删文件。
|
|
12628
|
+
this.removeConversation(stillHeld.id);
|
|
12629
|
+
if ([...this.convs.values()].some(holdsTarget)) {
|
|
12630
|
+
this.emit({
|
|
12631
|
+
type: "notice",
|
|
12632
|
+
level: "warning",
|
|
12633
|
+
text: "该对话仍被占用,无法删除;请先关闭它再重试",
|
|
12634
|
+
textEn: "The conversation is still held; close it and retry the delete",
|
|
12635
|
+
});
|
|
12636
|
+
return;
|
|
12175
12637
|
}
|
|
12176
|
-
this.emit({
|
|
12177
|
-
type: "notice",
|
|
12178
|
-
level: "warning",
|
|
12179
|
-
text: stillRunning
|
|
12180
|
-
? "对话仍在后台运行,已停止删除;请等待其结束后再删除"
|
|
12181
|
-
: "未能切换到其他对话,已取消删除本次操作",
|
|
12182
|
-
textEn: stillRunning
|
|
12183
|
-
? "Conversation is still running in the background; delete aborted — wait for it to finish and retry"
|
|
12184
|
-
: "Could not switch to another conversation; delete cancelled",
|
|
12185
|
-
});
|
|
12186
|
-
return;
|
|
12187
12638
|
}
|
|
12188
12639
|
}
|
|
12189
12640
|
// #145 同款守卫:删之前查一遍其他客户端是否持有这份转录 ——
|
|
@@ -12548,8 +12999,12 @@ export class ClientSession {
|
|
|
12548
12999
|
return true;
|
|
12549
13000
|
}
|
|
12550
13001
|
};
|
|
12551
|
-
const descendants = collectSubagentDescendantIds([...this.convs.values()].map((c) => ({
|
|
12552
|
-
|
|
13002
|
+
const descendants = collectSubagentDescendantIds([...this.convs.values()].map((c) => ({
|
|
13003
|
+
id: conversationIdentity(c),
|
|
13004
|
+
parentId: this.parentExecutionKey(c),
|
|
13005
|
+
isSubagent: c.isSubagent,
|
|
13006
|
+
})), conversationIdentity(conv))
|
|
13007
|
+
.map((did) => this.resolveExecution(did)?.conv)
|
|
12553
13008
|
.filter((c) => !!c);
|
|
12554
13009
|
if (force) {
|
|
12555
13010
|
await this.forceDismissConversation(conv, descendants, isStreaming);
|
|
@@ -12673,7 +13128,8 @@ export class ClientSession {
|
|
|
12673
13128
|
return;
|
|
12674
13129
|
}
|
|
12675
13130
|
}
|
|
12676
|
-
this.
|
|
13131
|
+
if (this.convs.get(conv.id) === conv && conv.id !== this.activeId)
|
|
13132
|
+
this.removeConversation(conv.id);
|
|
12677
13133
|
this.emitConversations();
|
|
12678
13134
|
this.flushSnapshot();
|
|
12679
13135
|
}
|
|
@@ -12705,7 +13161,7 @@ export class ClientSession {
|
|
|
12705
13161
|
continue;
|
|
12706
13162
|
if (isStreaming(d)) {
|
|
12707
13163
|
try {
|
|
12708
|
-
await this.subagentHost.stopSubagent(d
|
|
13164
|
+
await this.subagentHost.stopSubagent(conversationIdentity(d));
|
|
12709
13165
|
stopped++;
|
|
12710
13166
|
}
|
|
12711
13167
|
catch {
|
|
@@ -12722,7 +13178,7 @@ export class ClientSession {
|
|
|
12722
13178
|
const deferred = [];
|
|
12723
13179
|
for (const d of descendants) {
|
|
12724
13180
|
const cur = this.convs.get(d.id);
|
|
12725
|
-
if (
|
|
13181
|
+
if (cur !== d || cur === conv)
|
|
12726
13182
|
continue;
|
|
12727
13183
|
if (cur.id === this.activeId) {
|
|
12728
13184
|
deferred.push(cur);
|
|
@@ -12793,14 +13249,13 @@ export class ClientSession {
|
|
|
12793
13249
|
let d = 0;
|
|
12794
13250
|
let cur = this.convs.get(id);
|
|
12795
13251
|
const seen = new Set([id]);
|
|
12796
|
-
while (cur
|
|
12797
|
-
|
|
13252
|
+
while (cur) {
|
|
13253
|
+
const parent = this.parentExecution(cur);
|
|
13254
|
+
if (!parent || seen.has(conversationIdentity(parent.conv)))
|
|
12798
13255
|
break;
|
|
12799
|
-
seen.add(
|
|
13256
|
+
seen.add(conversationIdentity(parent.conv));
|
|
12800
13257
|
d++;
|
|
12801
|
-
cur =
|
|
12802
|
-
if (!cur)
|
|
12803
|
-
break;
|
|
13258
|
+
cur = parent.conv;
|
|
12804
13259
|
}
|
|
12805
13260
|
return d;
|
|
12806
13261
|
};
|
|
@@ -12817,15 +13272,14 @@ export class ClientSession {
|
|
|
12817
13272
|
return true;
|
|
12818
13273
|
let cur = conv;
|
|
12819
13274
|
const seen = new Set();
|
|
12820
|
-
while (cur
|
|
12821
|
-
|
|
12822
|
-
|
|
12823
|
-
if (seen.has(cur.parentId))
|
|
12824
|
-
return false;
|
|
12825
|
-
seen.add(cur.parentId);
|
|
12826
|
-
cur = this.convs.get(cur.parentId);
|
|
12827
|
-
if (!cur)
|
|
13275
|
+
while (cur) {
|
|
13276
|
+
const parent = this.parentExecution(cur);
|
|
13277
|
+
if (!parent || seen.has(conversationIdentity(parent.conv)))
|
|
12828
13278
|
return false;
|
|
13279
|
+
if (parent.conv === this.convs.get(root))
|
|
13280
|
+
return true;
|
|
13281
|
+
seen.add(conversationIdentity(parent.conv));
|
|
13282
|
+
cur = parent.conv;
|
|
12829
13283
|
}
|
|
12830
13284
|
return false;
|
|
12831
13285
|
};
|
|
@@ -12876,7 +13330,7 @@ export class ClientSession {
|
|
|
12876
13330
|
}
|
|
12877
13331
|
// Re-check live children: earlier removals in this same batch may
|
|
12878
13332
|
// have cleared the guard; still-running children block the parent.
|
|
12879
|
-
const liveChild = [...this.convs.values()].some((child) => child
|
|
13333
|
+
const liveChild = [...this.convs.values()].some((child) => this.parentExecution(child)?.conv === cur && isStreaming(child));
|
|
12880
13334
|
if (liveChild) {
|
|
12881
13335
|
skippedRunning++;
|
|
12882
13336
|
continue;
|
|
@@ -12959,7 +13413,7 @@ export class ClientSession {
|
|
|
12959
13413
|
* current runtime, which would otherwise stop a response merely because the
|
|
12960
13414
|
* user opened history while it was streaming.
|
|
12961
13415
|
*/
|
|
12962
|
-
async switchSession(path, sessionId) {
|
|
13416
|
+
async switchSession(path, sessionId, independent) {
|
|
12963
13417
|
if (this.quiesceBlocked())
|
|
12964
13418
|
return;
|
|
12965
13419
|
const timing = startLoadTiming();
|
|
@@ -12978,8 +13432,19 @@ export class ClientSession {
|
|
|
12978
13432
|
/* ignore */
|
|
12979
13433
|
}
|
|
12980
13434
|
if (sid === wantSid || conv.id === wantSid) {
|
|
13435
|
+
if (independent !== undefined)
|
|
13436
|
+
this.setConversationIndependent(conv.id, independent);
|
|
12981
13437
|
await this.switchConversation(conv.id);
|
|
12982
13438
|
outcome = "reused";
|
|
13439
|
+
this.emit({
|
|
13440
|
+
type: "transition_progress",
|
|
13441
|
+
kind: "session",
|
|
13442
|
+
target: wantSid,
|
|
13443
|
+
phase: "done",
|
|
13444
|
+
progress: 100,
|
|
13445
|
+
text: "会话加载完成",
|
|
13446
|
+
textEn: "Session loaded",
|
|
13447
|
+
});
|
|
12983
13448
|
return;
|
|
12984
13449
|
}
|
|
12985
13450
|
}
|
|
@@ -13012,6 +13477,8 @@ export class ClientSession {
|
|
|
13012
13477
|
for (const conv of this.convs.values()) {
|
|
13013
13478
|
const sessionFile = conv.session.sessionFile;
|
|
13014
13479
|
if (sessionFile && resolve(sessionFile) === targetPath) {
|
|
13480
|
+
if (independent !== undefined)
|
|
13481
|
+
this.setConversationIndependent(conv.id, independent);
|
|
13015
13482
|
await this.switchConversation(conv.id);
|
|
13016
13483
|
outcome = "reused";
|
|
13017
13484
|
this.emit({
|
|
@@ -13032,7 +13499,16 @@ export class ClientSession {
|
|
|
13032
13499
|
// 伪客户端(定时任务等):不允许过户抢占,直接拦截;
|
|
13033
13500
|
// 空闲或离线宽限期残骸:直接执行跨客户端自动过户(Auto-Takeover),
|
|
13034
13501
|
// 搬移 runtime 本体,保持单 writer,避免双 runtime 导致激活冲突与分支分叉。
|
|
13502
|
+
if (this.botExecution) {
|
|
13503
|
+
this.botExecution.assertActive();
|
|
13504
|
+
if (targetPath !== resolve(this.botExecution.authorizedResumePath ?? ""))
|
|
13505
|
+
throw new Error("Bot transcript resume is not authorized");
|
|
13506
|
+
await this.prepareBotSessionResume?.(targetPath);
|
|
13507
|
+
this.botExecution.assertActive();
|
|
13508
|
+
}
|
|
13035
13509
|
const owner = this.findSessionOwner?.(targetPath);
|
|
13510
|
+
if (owner && this.botExecution)
|
|
13511
|
+
throw new Error("Bot transcript still has an active owner");
|
|
13036
13512
|
if (owner && owner.isStreaming) {
|
|
13037
13513
|
this.emit({
|
|
13038
13514
|
type: "notice",
|
|
@@ -13147,6 +13623,10 @@ export class ClientSession {
|
|
|
13147
13623
|
return;
|
|
13148
13624
|
}
|
|
13149
13625
|
const conv = this.makeConversation(openedRuntime, conversationId, openedTerminals);
|
|
13626
|
+
if (independent !== undefined) {
|
|
13627
|
+
conv.session.sessionManager.appendCustomEntry("webui/independent", { independent });
|
|
13628
|
+
conv.independent = independent;
|
|
13629
|
+
}
|
|
13150
13630
|
// Deliberately resumed — must not be dismissed when the user later
|
|
13151
13631
|
// switches away without sending a new message.
|
|
13152
13632
|
conv.listed = true;
|
|
@@ -13177,7 +13657,8 @@ export class ClientSession {
|
|
|
13177
13657
|
await this.restoreProjectProviderKeysForCwd(targetCwd);
|
|
13178
13658
|
if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
|
|
13179
13659
|
return;
|
|
13180
|
-
|
|
13660
|
+
if (!this.botExecution)
|
|
13661
|
+
await this.restoreProjectModelForCwd(targetCwd);
|
|
13181
13662
|
if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
|
|
13182
13663
|
return;
|
|
13183
13664
|
this.flushSnapshot();
|
|
@@ -13242,24 +13723,26 @@ export class ClientSession {
|
|
|
13242
13723
|
* Map a rendered user-message id (`u-<timestamp>-<seq>`, assigned in
|
|
13243
13724
|
* serialize.ts) back to its append-only session entry id.
|
|
13244
13725
|
*/
|
|
13245
|
-
resolveUserMessageEntryId(messageId) {
|
|
13246
|
-
return resolveUserMessageEntryId(this.session.sessionManager.buildContextEntries(), messageId);
|
|
13726
|
+
resolveUserMessageEntryId(messageId, targetConversation) {
|
|
13727
|
+
return resolveUserMessageEntryId(undeletedContextEntries((targetConversation ?? this.conv).session.sessionManager.buildContextEntries()), messageId);
|
|
13247
13728
|
}
|
|
13248
13729
|
/**
|
|
13249
13730
|
* Map any rendered message id (u-*, a-*, t-*, b-*, c-*, or raw entry id)
|
|
13250
13731
|
* back to its append-only session entry in the given conversation.
|
|
13251
13732
|
*/
|
|
13252
13733
|
resolveMessageEntry(conv, messageId) {
|
|
13253
|
-
return resolveConversationMessageEntry(conv.session.sessionManager.buildContextEntries(), messageId, (m) => this.uiMessageKey(conv, m).n, (id) => conv.session.sessionManager.getEntry(id));
|
|
13734
|
+
return resolveConversationMessageEntry(undeletedContextEntries(conv.session.sessionManager.buildContextEntries()), messageId, (m) => this.uiMessageKey(conv, m).n, (id) => conv.session.sessionManager.getEntry(id));
|
|
13254
13735
|
}
|
|
13255
13736
|
/**
|
|
13256
13737
|
* 获取被某个压缩卡片折叠的历史消息(issue #398,按需惰性加载)。
|
|
13257
13738
|
*/
|
|
13258
|
-
getCompactedMessages(compactionMessageId, targetConvId) {
|
|
13259
|
-
const targetConv =
|
|
13739
|
+
getCompactedMessages(compactionMessageId, targetConvId, send = this.emit.bind(this)) {
|
|
13740
|
+
const targetConv = targetConvId ? this.convs.get(targetConvId) : this.conv;
|
|
13741
|
+
if (!targetConv)
|
|
13742
|
+
throw new Error("Conversation no longer available");
|
|
13260
13743
|
const sm = targetConv.session.sessionManager;
|
|
13261
13744
|
const result = getCompactedMessages(sm, compactionMessageId, (m) => this.uiMessageKey(targetConv, m).n);
|
|
13262
|
-
|
|
13745
|
+
send({
|
|
13263
13746
|
type: "compacted_messages_result",
|
|
13264
13747
|
compactionMessageId,
|
|
13265
13748
|
conversationId: targetConv.id,
|
|
@@ -13582,7 +14065,54 @@ export class ClientSession {
|
|
|
13582
14065
|
* Replace a past question and its later history in the same SDK session/file.
|
|
13583
14066
|
* Attachments are re-sent through prompt() after removing the original turn.
|
|
13584
14067
|
*/
|
|
13585
|
-
async
|
|
14068
|
+
async deleteMessage(messageId, conversationId) {
|
|
14069
|
+
if (this.quiesceBlocked())
|
|
14070
|
+
return;
|
|
14071
|
+
const target = conversationId ? this.convs.get(conversationId) : this.conv;
|
|
14072
|
+
try {
|
|
14073
|
+
if (!target)
|
|
14074
|
+
throw new Error("Conversation is no longer available");
|
|
14075
|
+
const session = target.session;
|
|
14076
|
+
if (session.isStreaming)
|
|
14077
|
+
throw new Error("Stop generation before deleting a message");
|
|
14078
|
+
const manager = session.sessionManager;
|
|
14079
|
+
if (typeof manager.appendContextEdit !== "function")
|
|
14080
|
+
throw new Error("This engine does not support message deletion");
|
|
14081
|
+
const entry = this.resolveMessageEntry(target, messageId);
|
|
14082
|
+
if (!entry)
|
|
14083
|
+
throw new Error("Message not found");
|
|
14084
|
+
const ids = messageDeletionTargets(manager.buildContextEntries(), entry.id);
|
|
14085
|
+
try {
|
|
14086
|
+
for (const id of ids)
|
|
14087
|
+
manager.appendContextEdit(id, null);
|
|
14088
|
+
}
|
|
14089
|
+
catch (error) {
|
|
14090
|
+
// SDK mutates indexes before writing; restore the committed transcript on failure.
|
|
14091
|
+
if (session.sessionFile)
|
|
14092
|
+
manager.setSessionFile(session.sessionFile);
|
|
14093
|
+
throw error;
|
|
14094
|
+
}
|
|
14095
|
+
finally {
|
|
14096
|
+
session.agent.state.messages = manager.buildSessionContext().messages;
|
|
14097
|
+
target.uiMessageCache.clear();
|
|
14098
|
+
target.userSeqByTs.clear();
|
|
14099
|
+
target.lastMessagesSig = "";
|
|
14100
|
+
target.lastMessagesArray = [];
|
|
14101
|
+
}
|
|
14102
|
+
this.invalidateSessionInfos();
|
|
14103
|
+
this.scheduleSessionsRefresh();
|
|
14104
|
+
}
|
|
14105
|
+
catch (error) {
|
|
14106
|
+
this.emit({
|
|
14107
|
+
type: "notice",
|
|
14108
|
+
level: "error",
|
|
14109
|
+
text: `删除消息失败:${error.message}`,
|
|
14110
|
+
textEn: `Failed to delete message: ${error.message}`,
|
|
14111
|
+
});
|
|
14112
|
+
}
|
|
14113
|
+
this.flushSnapshot();
|
|
14114
|
+
}
|
|
14115
|
+
async editMessage(messageId, text, attachments, targetConversation) {
|
|
13586
14116
|
if (this.quiesceBlocked())
|
|
13587
14117
|
return;
|
|
13588
14118
|
const trimmed = text.trim();
|
|
@@ -13597,7 +14127,11 @@ export class ClientSession {
|
|
|
13597
14127
|
this.flushSnapshot();
|
|
13598
14128
|
return;
|
|
13599
14129
|
}
|
|
13600
|
-
|
|
14130
|
+
if (targetConversation && this.convs.get(targetConversation.id) !== targetConversation)
|
|
14131
|
+
throw new Error("Edit conversation is no longer available");
|
|
14132
|
+
const entryId = targetConversation
|
|
14133
|
+
? this.resolveUserMessageEntryId(messageId, targetConversation)
|
|
14134
|
+
: this.resolveUserMessageEntryId(messageId);
|
|
13601
14135
|
if (!entryId) {
|
|
13602
14136
|
this.emit({
|
|
13603
14137
|
type: "notice",
|
|
@@ -13608,7 +14142,7 @@ export class ClientSession {
|
|
|
13608
14142
|
this.flushSnapshot();
|
|
13609
14143
|
return;
|
|
13610
14144
|
}
|
|
13611
|
-
const target = this.conv;
|
|
14145
|
+
const target = targetConversation ?? this.conv;
|
|
13612
14146
|
const runtime = target.runtime;
|
|
13613
14147
|
const session = target.session;
|
|
13614
14148
|
const sessionFile = session.sessionFile;
|
|
@@ -13924,18 +14458,18 @@ export class ClientSession {
|
|
|
13924
14458
|
* 恰好应答一次:任何失败都以 ok:false 的 scm_data(kind "commitmsg")收尾,
|
|
13925
14459
|
* 前端按钮不会卡在转圈。
|
|
13926
14460
|
*/
|
|
13927
|
-
async scmGenCommitMessage(reqId) {
|
|
14461
|
+
async scmGenCommitMessage(reqId, conv = this.conv, send = this.emit.bind(this)) {
|
|
13928
14462
|
const lang = this.getLang();
|
|
13929
|
-
const cwd =
|
|
14463
|
+
const cwd = conv.cwd;
|
|
13930
14464
|
const reply = (ok, extra) => {
|
|
13931
|
-
|
|
14465
|
+
send({ type: "scm_data", reqId, kind: "commitmsg", ok, ...extra });
|
|
13932
14466
|
};
|
|
13933
14467
|
const fail = (err) => {
|
|
13934
14468
|
reply(false, { error: err instanceof Error ? err.message : String(err) });
|
|
13935
14469
|
};
|
|
13936
14470
|
try {
|
|
13937
|
-
const runtime =
|
|
13938
|
-
const model =
|
|
14471
|
+
const runtime = conv.runtime.services.modelRuntime;
|
|
14472
|
+
const model = conv.session?.model;
|
|
13939
14473
|
if (!model) {
|
|
13940
14474
|
throw new Error(pick(lang, "当前没有可用模型——先在顶栏选择一个模型再生成", "No model available — pick one in the top bar first", "scm.commitmsg.no.model"));
|
|
13941
14475
|
}
|
|
@@ -13959,6 +14493,17 @@ export class ClientSession {
|
|
|
13959
14493
|
fail(err);
|
|
13960
14494
|
}
|
|
13961
14495
|
}
|
|
14496
|
+
/** Shared viewers use a captured workspace instead of active getters. */
|
|
14497
|
+
createConversationFiles(conv, send) {
|
|
14498
|
+
const cwd = conv.cwd;
|
|
14499
|
+
return new FilesService({
|
|
14500
|
+
emit: send,
|
|
14501
|
+
isDisposed: () => this.disposed || this.convs.get(conv.id) !== conv,
|
|
14502
|
+
getCwd: () => cwd,
|
|
14503
|
+
getActiveCwd: () => cwd,
|
|
14504
|
+
getLang: () => this.getLang(),
|
|
14505
|
+
});
|
|
14506
|
+
}
|
|
13962
14507
|
/** Read a workspace file for the preview panel (size-capped, binary-safe). */
|
|
13963
14508
|
async readFile(relPath) {
|
|
13964
14509
|
return this.files.readFile(relPath);
|
|
@@ -14623,17 +15168,17 @@ export class ClientSession {
|
|
|
14623
15168
|
// Goal / review
|
|
14624
15169
|
// ---------------------------------------------------------------------------
|
|
14625
15170
|
/** Goal family delegates to GoalService (see goal-service.ts). */
|
|
14626
|
-
async setGoal(goalText, opts) {
|
|
14627
|
-
return this.goalSvc.setGoal(goalText, opts);
|
|
15171
|
+
async setGoal(goalText, opts, conv) {
|
|
15172
|
+
return this.goalSvc.setGoal(goalText, { ...opts, ...(conv ? { targetConvId: conv.id } : {}) });
|
|
14628
15173
|
}
|
|
14629
|
-
async startGoalWizard(text, opts) {
|
|
14630
|
-
return this.goalSvc.startGoalWizard(text, opts);
|
|
15174
|
+
async startGoalWizard(text, opts, conv) {
|
|
15175
|
+
return this.goalSvc.startGoalWizard(text, opts, conv);
|
|
14631
15176
|
}
|
|
14632
|
-
async setGoalPrefs(opts) {
|
|
14633
|
-
return this.goalSvc.setGoalPrefs(opts);
|
|
15177
|
+
async setGoalPrefs(opts, conv) {
|
|
15178
|
+
return this.goalSvc.setGoalPrefs(opts, conv);
|
|
14634
15179
|
}
|
|
14635
|
-
async clearGoal() {
|
|
14636
|
-
return this.goalSvc.clearGoal();
|
|
15180
|
+
async clearGoal(conv) {
|
|
15181
|
+
return this.goalSvc.clearGoal(conv);
|
|
14637
15182
|
}
|
|
14638
15183
|
/**
|
|
14639
15184
|
* Run a git diff (unstaged + staged) in a conversation's workspace, or
|
|
@@ -14667,11 +15212,11 @@ export class ClientSession {
|
|
|
14667
15212
|
/** Switch to a specific model by "provider/id" (e.g. "anthropic/claude-sonnet-5").
|
|
14668
15213
|
* 失败时只发 notice 不抛错(UI 路径靠 notice 提示,见 cycleModel 等调用方)。
|
|
14669
15214
|
* 需要「失败即拒绝」的无头路径(插件/定时任务)用 switchModelOrThrow。 */
|
|
14670
|
-
async setModel(modelId) {
|
|
15215
|
+
async setModel(modelId, conv = this.conv) {
|
|
14671
15216
|
if (this.botExecution)
|
|
14672
15217
|
throw new Error("Bot model is fixed");
|
|
14673
15218
|
try {
|
|
14674
|
-
const mr =
|
|
15219
|
+
const mr = conv.runtime.services.modelRuntime;
|
|
14675
15220
|
const slash = modelId.indexOf("/");
|
|
14676
15221
|
if (slash <= 0 || slash === modelId.length - 1) {
|
|
14677
15222
|
throw new Error(`无效的模型 ID:${modelId}`);
|
|
@@ -14682,15 +15227,19 @@ export class ClientSession {
|
|
|
14682
15227
|
if (!model)
|
|
14683
15228
|
throw new Error(`模型不存在:${modelId}`);
|
|
14684
15229
|
// 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
|
|
14685
|
-
await this.restoreKeyForModel(modelId,
|
|
14686
|
-
|
|
15230
|
+
await this.restoreKeyForModel(modelId, conv.cwd);
|
|
15231
|
+
if (this.convs.get(conv.id) !== conv)
|
|
15232
|
+
return;
|
|
15233
|
+
await this.applySessionModel(conv.session, model);
|
|
14687
15234
|
// Immediately remember the model + the key it uses for the current
|
|
14688
15235
|
// project (not only after a turn). This is what makes project switching
|
|
14689
15236
|
// restore both the model and the provider key.
|
|
14690
|
-
this.
|
|
15237
|
+
if (conv === this.conv)
|
|
15238
|
+
this.rememberProjectModel(modelId);
|
|
14691
15239
|
// 换模型后按新模型的窗口重算软上限覆盖已由 applySessionModel 完成(issue #229/#773)。
|
|
14692
15240
|
// 切换成功 → 立即通知插件(#542:不发消息也能收到);失败路径落在 catch 里,不发。
|
|
14693
|
-
this.
|
|
15241
|
+
if (conv === this.conv)
|
|
15242
|
+
this.notifyPluginModelChange();
|
|
14694
15243
|
}
|
|
14695
15244
|
catch (err) {
|
|
14696
15245
|
this.emit({
|
|
@@ -14788,13 +15337,13 @@ export class ClientSession {
|
|
|
14788
15337
|
throw new Error(`切换模型失败(${modelId}),当前仍是 ${curId} —— 请检查模型 ID 与供应商密钥`);
|
|
14789
15338
|
}
|
|
14790
15339
|
/** Set the thinking level for future turns. */
|
|
14791
|
-
setThinking(level) {
|
|
15340
|
+
setThinking(level, conv = this.conv) {
|
|
14792
15341
|
try {
|
|
14793
15342
|
const thinkingLevel = level;
|
|
14794
|
-
|
|
14795
|
-
const cur =
|
|
15343
|
+
conv.session.setThinkingLevel(thinkingLevel, { persist: true });
|
|
15344
|
+
const cur = conv.session.model;
|
|
14796
15345
|
if (cur) {
|
|
14797
|
-
|
|
15346
|
+
conv.session.settingsManager.setModelThinkingLevel(cur.provider, cur.id, thinkingLevel);
|
|
14798
15347
|
}
|
|
14799
15348
|
}
|
|
14800
15349
|
catch (err) {
|
|
@@ -14825,7 +15374,10 @@ export class ClientSession {
|
|
|
14825
15374
|
this.emit({ type: "commands", commands, path });
|
|
14826
15375
|
this.emit({ type: "notice", level: "info", text: `命令已保存:${path}`, textEn: `Command saved: ${path}` });
|
|
14827
15376
|
}
|
|
15377
|
+
onDisposed;
|
|
14828
15378
|
async dispose() {
|
|
15379
|
+
this.onDisposed?.();
|
|
15380
|
+
this.onDisposed = undefined;
|
|
14829
15381
|
// Escalate incoming decisions while this holder is still live, then close execution identities.
|
|
14830
15382
|
for (const conv of this.convs.values()) {
|
|
14831
15383
|
for (const request of conversationCommunication.incomingRequests(conv)) {
|