pi-web-ui 0.111.0 → 0.113.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 +92 -2
- package/bin/frp-manager.mjs +9 -2
- package/bin/pi-web-ui.mjs +325 -45
- package/dist/server/agent-service-daemon.js +29 -4
- package/dist/server/agent-service.js +1527 -510
- package/dist/server/approval-audit.js +119 -0
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/approval-rules.js +42 -17
- package/dist/server/attachment-store.js +8 -8
- package/dist/server/canvas/canvas-agent-tool.js +8 -0
- package/dist/server/canvas/canvas-orchestrator.js +128 -22
- package/dist/server/canvas/pstack-skills-data.js +498 -0
- package/dist/server/client-state.js +28 -0
- package/dist/server/delegate-mode.js +6 -3
- package/dist/server/delegate-task.js +18 -3
- package/dist/server/dispatch-domain-handlers.js +39 -11
- package/dist/server/dsh/dsh-agent-service.js +294 -15
- package/dist/server/dsh/dsh-serialize.js +1 -1
- package/dist/server/durable/durable-driver.js +112 -107
- package/dist/server/durable/durable-event-projector.js +253 -0
- package/dist/server/durable/durable-loader.js +1 -14
- package/dist/server/durable/durable-models.js +107 -0
- package/dist/server/durable/index.js +0 -4
- package/dist/server/engine-probe.js +111 -48
- package/dist/server/eval-tool.js +28 -3
- package/dist/server/goal-service.js +7 -0
- package/dist/server/index.js +371 -57
- package/dist/server/json-utils.js +57 -0
- package/dist/server/marker-service.js +8 -0
- package/dist/server/message-window.js +43 -10
- package/dist/server/model-admin.js +247 -163
- package/dist/server/model-resolver.js +66 -44
- package/dist/server/plan-manager.js +3 -6
- package/dist/server/plugin-api-catalog.js +1 -0
- package/dist/server/plugin-assets.js +238 -0
- package/dist/server/plugin-facilities.js +22 -0
- package/dist/server/plugin-ui-slots.js +1 -0
- package/dist/server/plugins.js +209 -11
- package/dist/server/preset-fields.js +25 -1
- package/dist/server/preset-share.js +5 -2
- package/dist/server/prompt-assembler.js +2 -1
- package/dist/server/prompt-composer.js +18 -8
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-utils.js +156 -0
- package/dist/server/remote-ssh-service.js +110 -12
- package/dist/server/sdk-builtin-extensions.js +85 -0
- package/dist/server/serialize.js +1 -1
- package/dist/server/server-config.js +66 -0
- package/dist/server/session-parser.js +49 -13
- package/dist/server/session-search.js +4 -3
- package/dist/server/settings-service.js +74 -53
- package/dist/server/setup-page.js +632 -0
- package/dist/server/skill-discovery.js +361 -59
- package/dist/server/skill-maintenance.js +231 -0
- package/dist/server/skill-tool.js +32 -3
- package/dist/server/soft-cap.js +30 -6
- package/dist/server/subagent-helpers.js +22 -1
- package/dist/server/subagent-notify.js +93 -0
- package/dist/server/subagent-security-gate.js +282 -0
- package/dist/server/subagent-templates.js +8 -0
- package/dist/server/subagents.js +390 -48
- package/dist/server/terminals.js +196 -8
- package/dist/server/text-quote.js +61 -0
- package/dist/server/tool-approval.js +63 -4
- package/dist/server/tool-guards.js +208 -0
- package/dist/server/tool-host-factories.js +48 -10
- package/dist/server/tool-manager.js +106 -28
- package/dist/server/tool-overrides.js +21 -11
- package/dist/server/universal/driver-base.js +8 -0
- package/dist/server/universal/drivers/claude-code.js +116 -7
- package/dist/server/universal/drivers/dsh-driver.js +3 -0
- package/dist/server/universal/index.js +0 -1
- package/dist/server/universal/universal-session.js +106 -10
- package/dist/server/worktree-service.js +189 -1
- package/docs/dsh-engine.md +1 -5
- package/package.json +1 -1
- package/plugin-sdk/client-utils.mjs +192 -5
- package/plugin-sdk/index.d.ts +63 -1
- package/plugin-sdk/index.mjs +94 -0
- package/plugin-sdk/package.json +5 -1
- package/plugins/catalog.json +21 -0
- package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
- package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
- package/web/dist/assets/index-BwL7qBh6.css +1 -0
- package/web/dist/index.html +11 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B0ajS__T.js +0 -697
- package/web/dist/assets/index-BHik5WGG.css +0 -1
|
@@ -15,14 +15,16 @@
|
|
|
15
15
|
// wholesale (no union merge / no stale built-in leftovers).
|
|
16
16
|
import "./patch-remote-catalog.js";
|
|
17
17
|
import "./patch-turn-end-boundary.js";
|
|
18
|
+
import { formatSubagentsCompletionNotice } from "./subagent-notify.js";
|
|
18
19
|
import { spawn } from "node:child_process";
|
|
19
20
|
import { createHash, randomUUID } from "node:crypto";
|
|
20
21
|
import * as fsPromises from "node:fs/promises";
|
|
21
22
|
import { DEFAULT_PI_CAPABILITIES } from "./engine-capabilities.js";
|
|
22
|
-
import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, mkdirSync, watch, writeFileSync, } from "node:fs";
|
|
23
|
+
import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, mkdirSync, statSync, watch, writeFileSync, } from "node:fs";
|
|
23
24
|
import { homedir } from "node:os";
|
|
24
25
|
import { basename, delimiter, join, resolve } from "node:path";
|
|
25
|
-
import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices,
|
|
26
|
+
import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
|
|
27
|
+
import { getSdkBuiltinExtensionFactories, SDK_DISABLED_BUILTIN_EXTENSIONS } from "./sdk-builtin-extensions.js";
|
|
26
28
|
import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
|
|
27
29
|
import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
|
|
28
30
|
import { collectInstalledEngineTargets } from "./engine-probe.js";
|
|
@@ -33,18 +35,19 @@ import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundT
|
|
|
33
35
|
import { COMPACTION_PENDING_TYPE, looksLikeChainCorruption, makeCompactionMarkerId, repairSessionFile, } from "./compaction-markers.js";
|
|
34
36
|
import { calibrateSessionLeaf } from "./session-branch.js";
|
|
35
37
|
import { danglingToolResultText, findDanglingToolCalls, healDanglingToolCallFile, } from "./dangling-tools.js";
|
|
36
|
-
import { removeQueuedByIndexOrText } from "./queue-utils.js";
|
|
38
|
+
import { removeQueuedByIndexOrText, removeQueuedEntry, rollbackQueuedEntry, reconcileQueuedEntries, createQueuedEntry, toQueuedPromptItems, } from "./queue-utils.js";
|
|
37
39
|
import { syncPluginToolsIntoSession } from "./plugins.js";
|
|
38
40
|
import { modelChangeKey, pickClientConversation } from "./plugin-conversation-view.js";
|
|
39
41
|
import { SettingsService } from "./settings-service.js";
|
|
40
42
|
import { GoalService, buildDiffFingerprint, extractErrorSnippetFromSession, lastToolNameOfSession, } from "./goal-service.js";
|
|
41
43
|
import { buildEvidenceDigest, sessionMessagesOf } from "./goal-evidence.js";
|
|
42
44
|
import { MarkerService } from "./marker-service.js";
|
|
45
|
+
import { discoverDiskSkills, mergeSkillCollections, readSkillInstruction } from "./skill-discovery.js";
|
|
43
46
|
import { SlashCommandsService, parseSlash } from "./slash-commands.js";
|
|
44
47
|
import { ModelAdminService } from "./model-admin.js";
|
|
45
48
|
import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
|
|
46
49
|
import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
|
|
47
|
-
import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
|
|
50
|
+
import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, defaultSubagentAutoWakeMaxTurns, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
|
|
48
51
|
import { isTraditionalLocale, pick, resolveServerLang } from "./i18n.js";
|
|
49
52
|
import { SubagentTemplatesStore, localizeTemplate, pickTemplatePrompt, } from "./subagent-templates.js";
|
|
50
53
|
import { ApprovalRulesStore } from "./approval-rules.js";
|
|
@@ -59,24 +62,27 @@ import { fillSkillContents } from "./skill-content-filler.js";
|
|
|
59
62
|
import { estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
|
|
60
63
|
import { formatSubagentHandoffMessage, recordSubagentHandoff } from "./subagent-handoff.js";
|
|
61
64
|
import { executeContextBudgetPruning } from "./context-budget-runner.js";
|
|
62
|
-
import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, } from "./tool-approval.js";
|
|
65
|
+
import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, pluginApprovalCategory, } from "./tool-approval.js";
|
|
63
66
|
import { PlanManager } from "./plan-manager.js";
|
|
67
|
+
import { ApprovalAuditLogger } from "./approval-audit.js";
|
|
68
|
+
export { ApprovalAuditLogger };
|
|
64
69
|
import { buildPlanModePrompt, planModeDenial, planModeNoticeText, PLAN_MODE_BLOCKED_TOOL_NAMES } from "./plan-mode.js";
|
|
65
|
-
import { DELEGATION_SYSTEM_PROMPT, delegateNoticeText } from "./delegate-mode.js";
|
|
70
|
+
import { DELEGATE_MODE_BLOCKED_TOOL_NAMES, DELEGATION_SYSTEM_PROMPT, delegateNoticeText } from "./delegate-mode.js";
|
|
66
71
|
import { goalReviewDenial, shouldDeferPromptForReview } from "./goal-review-gate.js";
|
|
67
72
|
import { readPlanModeFromSession, readPlanFromSession } from "./permission-preset.js";
|
|
68
73
|
import { readDelegateModeFromSession } from "./permission-preset.js";
|
|
69
|
-
import { makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE } from "./terminals.js";
|
|
74
|
+
import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
|
|
70
75
|
import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
|
|
71
76
|
import { makeLoadToolsTool } from "./load-tools-tool.js";
|
|
72
77
|
import { formatCompactSignature } from "./tool-signature.js";
|
|
73
78
|
import { WebUIContext } from "./webui-context.js";
|
|
74
|
-
import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap,
|
|
79
|
+
import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, SOFT_CAP_MIN_TOKENS, SOFT_CAP_MIN_HEADROOM, softCapReserveFor, } from "./soft-cap.js";
|
|
75
80
|
import { makeEditSoftTool } from "./edit-soft-tool.js";
|
|
76
81
|
// 覆盖 SDK 内置 read:路径是目录时列出目录条目(行为开关 readDirEnabled,默认开)。
|
|
77
82
|
// 覆盖定义与「与扩展同名工具共存」的注入辅助分在两个文件(后者的依据见 tool-overrides.ts)。
|
|
78
83
|
import { makeReadDirTool, withReadDirSupport } from "./read-tool.js";
|
|
79
84
|
import { installToolOverrides, syncSubagentOverride, } from "./tool-overrides.js";
|
|
85
|
+
import { resolveSecurityMode, subagentSecurityDenial, withSubagentSecurityGate, SUBAGENT_WRITE_TOOL_NAMES, } from "./subagent-security-gate.js";
|
|
80
86
|
// 展示文件给用户(present_files):图片/视频内联、文本开预览弹窗、本地打开按钮。
|
|
81
87
|
import { makePresentFilesTool } from "./present-files-tool.js";
|
|
82
88
|
// 主动压缩上下文工具(compact_context):AI 主动根据当前问题精简上下文并自主控制范围。
|
|
@@ -106,7 +112,7 @@ import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktre
|
|
|
106
112
|
import { sameSessionFile } from "./scheduler-tasks.js";
|
|
107
113
|
import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
|
|
108
114
|
import { scanAtMentions } from "./universal/universal-attachments.js";
|
|
109
|
-
import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
|
|
115
|
+
import { extractStreamingPayload, formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt, } from "./text-quote.js";
|
|
110
116
|
import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
|
|
111
117
|
import { generateScmCommitMessage } from "./scm-commitmsg.js";
|
|
112
118
|
import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
|
|
@@ -136,6 +142,8 @@ const DELTA_ACTIVE_WINDOW_MS = 1500;
|
|
|
136
142
|
*/
|
|
137
143
|
const STATS_CACHE_MS = 250;
|
|
138
144
|
const WIDGET_REFRESH_MS = 2000;
|
|
145
|
+
/** 创建时未注入派发工具的子代理会话(模块级:过户跨 ClientSession 仍认得),syncSubagentOverride 不得再补回内置 subagent。 */
|
|
146
|
+
const SPAWN_TOOLS_BARRED = new WeakSet();
|
|
139
147
|
/** Model-stall watchdog: warn (don't abort — deep thinking can be legitimately
|
|
140
148
|
* quiet for minutes) when a streaming run produced NO SDK events for this long.
|
|
141
149
|
* Covers the failure class the per-tool watchdog cannot see: half-open API
|
|
@@ -196,8 +204,8 @@ import { splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-
|
|
|
196
204
|
export { splitAgentStartPrompt };
|
|
197
205
|
import { makeKillableBashTool, makeAdaptiveBashTool } from "./bash-tool.js";
|
|
198
206
|
export { makeKillableBashTool, makeAdaptiveBashTool };
|
|
199
|
-
import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, } from "./tool-guards.js";
|
|
200
|
-
export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, };
|
|
207
|
+
import { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, } from "./tool-guards.js";
|
|
208
|
+
export { withPlanModeGate, withGoalReviewGate, withDelegationGate, makeLateToolGuard, withToolGuard, withApprovalGate, isInsideWorkspaceRoots, wrapWriteToolWithPermission, EDIT_DESCRIPTION, EDIT_GUIDELINES, wrapEditToolWithPermission, wrapEditSoftToolWithPermission, wrapBashToolWithPermission, wrapPatchToolWithPermission, };
|
|
201
209
|
import { normalizeSolPlanToPlanSteps, makePlanUpdateTool } from "./plan-update-tool.js";
|
|
202
210
|
export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
|
|
203
211
|
import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
|
|
@@ -211,6 +219,39 @@ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRec
|
|
|
211
219
|
import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
|
|
212
220
|
export { pickAdoptableOrphan, sameCwd };
|
|
213
221
|
import { processTreeKillPlan, resolveCwdTarget } from "./process-utils.js";
|
|
222
|
+
/**
|
|
223
|
+
* 清扫异常退出/崩溃后遗留的孤儿临时会话目录(subagent-sessions / ephemeral-sessions)。
|
|
224
|
+
* 默认清理超过 TTL(24h)的临时目录,避免无上限累积。
|
|
225
|
+
*/
|
|
226
|
+
export function cleanupOrphanedSessionDirs(agentDir, maxAgeMs = 24 * 3600_000) {
|
|
227
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
228
|
+
for (const sub of ["subagent-sessions", "ephemeral-sessions"]) {
|
|
229
|
+
const root = join(agentDir, sub);
|
|
230
|
+
if (!existsSync(root))
|
|
231
|
+
continue;
|
|
232
|
+
try {
|
|
233
|
+
const entries = readdirSync(root, { withFileTypes: true });
|
|
234
|
+
for (const e of entries) {
|
|
235
|
+
if (!e.isDirectory())
|
|
236
|
+
continue;
|
|
237
|
+
const p = join(root, e.name);
|
|
238
|
+
try {
|
|
239
|
+
const st = statSync(p);
|
|
240
|
+
if (st.mtimeMs < cutoff) {
|
|
241
|
+
rmSync(p, { recursive: true, force: true });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
/* skip inaccessible */
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
/* skip unreadable root */
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
let ephemeralCleanupScheduled = false;
|
|
214
255
|
export { processTreeKillPlan, resolveCwdTarget };
|
|
215
256
|
export class ClientSession {
|
|
216
257
|
static mcpBridge = null;
|
|
@@ -242,6 +283,8 @@ export class ClientSession {
|
|
|
242
283
|
/** 目标模式「委托执行」(Plan A)的「本轮结束」等待者:convId → 回调集合。
|
|
243
284
|
* agent_end 到达时唤醒(事件驱动,绝不轮询);对话被移出时按 gone 收。 */
|
|
244
285
|
turnEndWaiters = new Map();
|
|
286
|
+
/** 子代理终态自动通知防抖批处理队列:parentId → { timer, subagents } (issue #713) */
|
|
287
|
+
pendingSubagentNotices = new Map();
|
|
245
288
|
// -----------------------------------------------------------------------
|
|
246
289
|
// Goal / review / wizard —— 自包含模块,见 goal-service.ts。每个对话有独立
|
|
247
290
|
// 的 GoalStatus,审查可并发;宿主回调在构造函数里接入。
|
|
@@ -264,6 +307,8 @@ export class ClientSession {
|
|
|
264
307
|
bashKills = new Set();
|
|
265
308
|
/** Background-server tracking (port snapshots + 后台任务 panel state) —
|
|
266
309
|
* 自包含模块,见 bg-servers.ts。列表按 CLIENT 存活,不随对话切换/结束消失。 */
|
|
310
|
+
/** 用户直接创建的交互式终端(按 CLIENT/工作区 存活,始终显示,不受单个对话切换、生命周期与过滤影响) */
|
|
311
|
+
userTerminals;
|
|
267
312
|
/** 文件树 / 预览读写 / SCM 查询 / watcher —— 自包含模块,见 files-service.ts。 */
|
|
268
313
|
files = new FilesService({
|
|
269
314
|
emit: (msg) => this.emit(msg),
|
|
@@ -339,6 +384,17 @@ export class ClientSession {
|
|
|
339
384
|
throw new Error("no active conversation");
|
|
340
385
|
return conv;
|
|
341
386
|
}
|
|
387
|
+
/** 当前激活会话 ID(供服务端按需回水定位用)。 */
|
|
388
|
+
activeConversationId() {
|
|
389
|
+
return this.activeId;
|
|
390
|
+
}
|
|
391
|
+
/** 获取指定会话的全量 UiMessage 列表(供历史窗口按需回水与补齐使用)。 */
|
|
392
|
+
getMessagesOfConversation(convId) {
|
|
393
|
+
const conv = this.convs.get(convId);
|
|
394
|
+
if (!conv)
|
|
395
|
+
return undefined;
|
|
396
|
+
return this.messagesOf(conv);
|
|
397
|
+
}
|
|
342
398
|
/** Runtime of the active conversation. */
|
|
343
399
|
get runtime() {
|
|
344
400
|
return this.conv.runtime;
|
|
@@ -352,12 +408,44 @@ export class ClientSession {
|
|
|
352
408
|
get terminals() {
|
|
353
409
|
return this.conv.terminals;
|
|
354
410
|
}
|
|
411
|
+
getUserTerminalManager() {
|
|
412
|
+
return this.userTerminals;
|
|
413
|
+
}
|
|
414
|
+
findTerminalManager(terminalId, conversationId) {
|
|
415
|
+
if (this.userTerminals?.has(terminalId)) {
|
|
416
|
+
return this.userTerminals;
|
|
417
|
+
}
|
|
418
|
+
if (conversationId) {
|
|
419
|
+
const convTm = this.convs.get(conversationId)?.terminals;
|
|
420
|
+
if (convTm?.has(terminalId))
|
|
421
|
+
return convTm;
|
|
422
|
+
}
|
|
423
|
+
if (this.conv?.terminals?.has(terminalId)) {
|
|
424
|
+
return this.conv.terminals;
|
|
425
|
+
}
|
|
426
|
+
for (const conv of this.convs.values()) {
|
|
427
|
+
if (conv.terminals?.has(terminalId))
|
|
428
|
+
return conv.terminals;
|
|
429
|
+
}
|
|
430
|
+
return this.getTerminalManager(conversationId);
|
|
431
|
+
}
|
|
355
432
|
getTerminalManager(conversationId) {
|
|
356
433
|
return (conversationId ? this.convs.get(conversationId) : this.convs.get(this.activeId))?.terminals;
|
|
357
434
|
}
|
|
358
435
|
getTerminalCwd(conversationId) {
|
|
359
436
|
return (conversationId ? this.convs.get(conversationId) : this.convs.get(this.activeId))?.cwd ?? this.cwd;
|
|
360
437
|
}
|
|
438
|
+
makeUserTerminalManager() {
|
|
439
|
+
const mgr = new TerminalManager((msg) => {
|
|
440
|
+
if (msg.type === "terminal_list") {
|
|
441
|
+
this.pushTerminals();
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
// 用户终端的输出、退出无条件向前端广播,绝不受 activeId 限制
|
|
445
|
+
this.emit(msg);
|
|
446
|
+
}, this.cwd, () => this.getLang());
|
|
447
|
+
return mgr;
|
|
448
|
+
}
|
|
361
449
|
makeTerminalManager(conversationId, cwd) {
|
|
362
450
|
const mgr = new TerminalManager((msg) => this.emitTerminal(conversationId, msg), cwd,
|
|
363
451
|
// issue #91:终端输入错误按客户端 UI 语言出中英(英文默认)。
|
|
@@ -433,7 +521,7 @@ export class ClientSession {
|
|
|
433
521
|
* `model`(可选):"provider/id",显式指定子代理模型。不传时由调用方决定是否
|
|
434
522
|
* 回退到模板模型 / 设置面板默认模型;null = 跟随主对话当前模型(默认行为,
|
|
435
523
|
* runtime 重建时会继承共享 ModelRuntime 的当前默认)。 */
|
|
436
|
-
async spawnSubagentConversation(prompt, type, cwd, apply, model, parentId, persist, title) {
|
|
524
|
+
async spawnSubagentConversation(prompt, type, cwd, apply, model, parentId, persist, title, thinking, notifyOnDone, isolation, extra) {
|
|
437
525
|
// 数量上限先行:每个子代理都是完整 runtime + TerminalManager,无上限时一次
|
|
438
526
|
// 并行派发几十个会把服务进程拖垮。持久化普通对话则受项目会话上限限制。
|
|
439
527
|
if (persist) {
|
|
@@ -468,9 +556,19 @@ export class ClientSession {
|
|
|
468
556
|
const baseCwd = spawner?.cwd ?? this.cwd;
|
|
469
557
|
// 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
|
|
470
558
|
const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
|
|
471
|
-
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
|
|
472
559
|
const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
|
|
473
|
-
|
|
560
|
+
let effectiveCwd = resolvedCwd;
|
|
561
|
+
let worktreeContext;
|
|
562
|
+
if (isolation === "worktree") {
|
|
563
|
+
if (isRemoteWorkspaceUri(resolvedCwd)) {
|
|
564
|
+
throw new Error(pick(this.getLang(), "远程 SSH 工作区暂不支持工作树物理隔离", "Worktree isolation is not supported in remote SSH workspaces", "agent.subagent.worktree.remote_unsupported"));
|
|
565
|
+
}
|
|
566
|
+
const { createSubagentWorktree } = await import("./worktree-service.js");
|
|
567
|
+
worktreeContext = await createSubagentWorktree(resolvedCwd, conversationId, () => this.getLang());
|
|
568
|
+
effectiveCwd = worktreeContext.subagentCwd;
|
|
569
|
+
}
|
|
570
|
+
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, effectiveCwd);
|
|
571
|
+
const terminals = this.makeTerminalManager(conversationId, effectiveCwd);
|
|
474
572
|
const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
|
|
475
573
|
if (!persist) {
|
|
476
574
|
// 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
|
|
@@ -482,13 +580,30 @@ export class ClientSession {
|
|
|
482
580
|
}
|
|
483
581
|
catch { }
|
|
484
582
|
}
|
|
485
|
-
const
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
583
|
+
const noSpawnTools = !persist && this.subagentAtDepthLimit(parentId ?? this.activeId ?? undefined);
|
|
584
|
+
let runtime;
|
|
585
|
+
try {
|
|
586
|
+
runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId, undefined, undefined, noSpawnTools), {
|
|
587
|
+
cwd: sessionBaseDir,
|
|
588
|
+
agentDir: this.agentDir,
|
|
589
|
+
sessionManager,
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
catch (runtimeErr) {
|
|
593
|
+
if (worktreeContext) {
|
|
594
|
+
const { removeWorktree } = await import("./worktree-service.js");
|
|
595
|
+
try {
|
|
596
|
+
await removeWorktree(worktreeContext.mainRepoPath, worktreeContext.worktreePath, true);
|
|
597
|
+
}
|
|
598
|
+
catch { }
|
|
599
|
+
}
|
|
600
|
+
throw runtimeErr;
|
|
601
|
+
}
|
|
490
602
|
const conv = this.makeConversation(runtime, conversationId, terminals);
|
|
491
|
-
conv.cwd =
|
|
603
|
+
conv.cwd = effectiveCwd;
|
|
604
|
+
if (worktreeContext) {
|
|
605
|
+
conv.subagentWorktree = worktreeContext;
|
|
606
|
+
}
|
|
492
607
|
conv.isSubagent = !persist;
|
|
493
608
|
if (conv.isSubagent) {
|
|
494
609
|
// 首轮 sendUserMessage 进入流式前的预检/模型切换窗口标记为投递中,
|
|
@@ -501,6 +616,17 @@ export class ClientSession {
|
|
|
501
616
|
conv.parentId = parentId ?? this.activeId ?? undefined;
|
|
502
617
|
conv.subagentType = type;
|
|
503
618
|
conv.subagentPrompt = prompt;
|
|
619
|
+
conv.subagentThinking = thinking;
|
|
620
|
+
conv.notifyOnDone = notifyOnDone !== false;
|
|
621
|
+
// 安全模式与工具白名单(issue #727):优先从 extra 取,缺省按 type 与模板自动推导
|
|
622
|
+
const securityMode = extra?.securityMode ?? resolveSecurityMode(type, apply);
|
|
623
|
+
conv.subagentSecurityMode = securityMode;
|
|
624
|
+
if (extra?.allowedTools && extra.allowedTools.length > 0) {
|
|
625
|
+
conv.subagentAllowedTools = new Set(extra.allowedTools);
|
|
626
|
+
}
|
|
627
|
+
if (securityMode === "readonly" && !conv.permissionPreset) {
|
|
628
|
+
conv.permissionPreset = "read-only";
|
|
629
|
+
}
|
|
504
630
|
// 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
|
|
505
631
|
// (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
|
|
506
632
|
conv.subagentTemplate = apply;
|
|
@@ -519,11 +645,6 @@ export class ClientSession {
|
|
|
519
645
|
// message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
|
|
520
646
|
// 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
|
|
521
647
|
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
522
|
-
// 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
|
|
523
|
-
this.applyRetryOverrides();
|
|
524
|
-
// 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
|
|
525
|
-
this.applyCompactionOverrides();
|
|
526
|
-
this.applyCodemodeOverrides();
|
|
527
648
|
// 扩展绑定(rpc 模式);用 headless 的 Web UI context:
|
|
528
649
|
// 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
|
|
529
650
|
try {
|
|
@@ -545,7 +666,8 @@ export class ClientSession {
|
|
|
545
666
|
// 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
|
|
546
667
|
// 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
|
|
547
668
|
// 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
|
|
548
|
-
const
|
|
669
|
+
const explicitModel = model?.trim() || apply?.model?.trim() || null;
|
|
670
|
+
const resolvedModel = explicitModel ?? (this.settingsSvc.current.subagentDefaultModel || null);
|
|
549
671
|
const followModel = resolvedModel
|
|
550
672
|
? resolvedModel
|
|
551
673
|
: spawnerSession.model
|
|
@@ -561,9 +683,12 @@ export class ClientSession {
|
|
|
561
683
|
// 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
|
|
562
684
|
// 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
|
|
563
685
|
await this.restoreKeyForModel(followModel, resolvedCwd);
|
|
564
|
-
await conv.session
|
|
686
|
+
await this.applySessionModel(conv.session, m);
|
|
565
687
|
}
|
|
566
688
|
catch (err) {
|
|
689
|
+
if (explicitModel) {
|
|
690
|
+
throw new Error(pick(this.getLang(), `子代理模型切换失败:${followModel}(${err.message})`, `Failed to set subagent model: ${followModel} (${err.message})`, "agent.subagent.model.failed", { model: followModel, error: err.message }));
|
|
691
|
+
}
|
|
567
692
|
// 换模型失败不阻断运行——沿用默认模型继续。
|
|
568
693
|
this.emit({
|
|
569
694
|
type: "notice",
|
|
@@ -574,6 +699,9 @@ export class ClientSession {
|
|
|
574
699
|
}
|
|
575
700
|
}
|
|
576
701
|
else {
|
|
702
|
+
if (explicitModel) {
|
|
703
|
+
throw new Error(pick(this.getLang(), `子代理指定的模型不存在:${followModel},请检查 provider/id 格式或通过 /models 确认可用模型`, `Subagent model not found: ${followModel}. Please check provider/id format or use /models to confirm available models`, "agent.subagent.model.not.found", { model: followModel }));
|
|
704
|
+
}
|
|
577
705
|
this.emit({
|
|
578
706
|
type: "notice",
|
|
579
707
|
level: "warning",
|
|
@@ -582,16 +710,8 @@ export class ClientSession {
|
|
|
582
710
|
});
|
|
583
711
|
}
|
|
584
712
|
}
|
|
585
|
-
//
|
|
586
|
-
|
|
587
|
-
// 触发点变成负数,上下文到几万 token 就压)。
|
|
588
|
-
this.refreshCompactionOverride(conv);
|
|
589
|
-
// 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
|
|
590
|
-
// 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
|
|
591
|
-
// SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
|
|
592
|
-
// 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
|
|
593
|
-
// 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
|
|
594
|
-
const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
|
|
713
|
+
// 思考强度:显式 thinking 参数 > 模板指定 > 派发者当前强度
|
|
714
|
+
const thinkingLevel = thinking?.trim() || apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
|
|
595
715
|
if (thinkingLevel) {
|
|
596
716
|
try {
|
|
597
717
|
conv.session.setThinkingLevel(thinkingLevel);
|
|
@@ -606,6 +726,10 @@ export class ClientSession {
|
|
|
606
726
|
});
|
|
607
727
|
}
|
|
608
728
|
}
|
|
729
|
+
// 子代理不走 bindSession——统一收口注入配置覆盖与工具门控。
|
|
730
|
+
// 必须在上面换模型(followModel 块)之后调:压缩 reserveTokens 按会话当前
|
|
731
|
+
// 模型的窗口算,提前调就会把子代理的判定线钉在派发者模型上(issue #773)。
|
|
732
|
+
this.applySessionOverrides(conv);
|
|
609
733
|
// 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
|
|
610
734
|
// 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
|
|
611
735
|
conv.kickoff = conv.session
|
|
@@ -646,6 +770,21 @@ export class ClientSession {
|
|
|
646
770
|
const found = this.findSubagentOwner?.(convId);
|
|
647
771
|
return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
|
|
648
772
|
}
|
|
773
|
+
/** 由该父对话派出的子代理处在主对话下第几层:沿 parentId 链数祖先(主对话派的 = 1)。 */
|
|
774
|
+
subagentDepthUnder(parentId) {
|
|
775
|
+
let depth = 0;
|
|
776
|
+
const seen = new Set();
|
|
777
|
+
for (let id = parentId; id && !seen.has(id); id = this.subagentSnapshotAnywhere(id)?.parentId) {
|
|
778
|
+
seen.add(id);
|
|
779
|
+
depth++;
|
|
780
|
+
}
|
|
781
|
+
return depth;
|
|
782
|
+
}
|
|
783
|
+
/** 设了嵌套上限(subagentMaxDepth > 0)且已到上限那一层的内存子代理,创建时不注入派发工具。 */
|
|
784
|
+
subagentAtDepthLimit(parentId) {
|
|
785
|
+
const max = this.settingsSvc.current.subagentMaxDepth ?? 0;
|
|
786
|
+
return max > 0 && this.subagentDepthUnder(parentId) >= max;
|
|
787
|
+
}
|
|
649
788
|
/** B20:convId 当前由哪个 ClientSession 持有(本会话优先;查不到兜底本会话)。 */
|
|
650
789
|
subagentOwnerOf(convId) {
|
|
651
790
|
if (!convId)
|
|
@@ -710,7 +849,7 @@ export class ClientSession {
|
|
|
710
849
|
/** B20:subagentHost.spawnSubagent 的委托入口(在**当前**会话上执行模板校验与真正
|
|
711
850
|
* spawn)—— 过户后由 host 按 parentId 的持有方调用,保证新子代理注册进持有方
|
|
712
851
|
* 的 convs(左栏「不见/错位」、cwd 跟错项目才不再发生)。 */
|
|
713
|
-
async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist) {
|
|
852
|
+
async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) {
|
|
714
853
|
// 模板:存在且启用时应用;传了名字但不可用 → 抛错让工具转给 AI。
|
|
715
854
|
const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
|
|
716
855
|
if (templateName && (!tpl || !tpl.enabled)) {
|
|
@@ -719,11 +858,220 @@ export class ClientSession {
|
|
|
719
858
|
// B20:parentId 是建时旧 id 时先解析成当前 id(过户撞 id 改名后,新子代理
|
|
720
859
|
// 的 parentId 必须指向改名后的主对话,否则族展开/lists 都认不出它)。
|
|
721
860
|
const canonParent = parentId ? (this.findSubagentOwner?.(parentId)?.convId ?? parentId) : parentId;
|
|
722
|
-
return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist);
|
|
861
|
+
return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist, undefined, thinking, notifyOnDone, isolation, extra);
|
|
723
862
|
}
|
|
724
863
|
subagentRunOutcome(conv) {
|
|
725
864
|
return subagentRunOutcome(conv);
|
|
726
865
|
}
|
|
866
|
+
/**
|
|
867
|
+
* 终态结算与清理子代理的工作树(issue #728)。
|
|
868
|
+
* 判定是否有未提交或提交修改:无修改自动清理,有修改保留供审阅。
|
|
869
|
+
*/
|
|
870
|
+
async finalizeSubagentWorktree(conv) {
|
|
871
|
+
const wt = conv.subagentWorktree;
|
|
872
|
+
if (!wt)
|
|
873
|
+
return undefined;
|
|
874
|
+
if (wt.finalized)
|
|
875
|
+
return wt;
|
|
876
|
+
if (conv.subagentWorktreePromise)
|
|
877
|
+
return conv.subagentWorktreePromise;
|
|
878
|
+
conv.subagentWorktreePromise = (async () => {
|
|
879
|
+
try {
|
|
880
|
+
try {
|
|
881
|
+
conv.terminals.killAll();
|
|
882
|
+
}
|
|
883
|
+
catch { }
|
|
884
|
+
const { finalizeSubagentWorktree } = await import("./worktree-service.js");
|
|
885
|
+
return await finalizeSubagentWorktree(wt, () => this.getLang());
|
|
886
|
+
}
|
|
887
|
+
finally {
|
|
888
|
+
conv.subagentWorktreePromise = undefined;
|
|
889
|
+
}
|
|
890
|
+
})();
|
|
891
|
+
return conv.subagentWorktreePromise;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* issue #713:安排向父对话投递子代理执行完成的聚合通知。
|
|
895
|
+
* 采用 400ms 脉冲防抖(Pulse Debounce):多个子代理近乎同时收口时,
|
|
896
|
+
* 合并为一条聚合消息唤醒父对话,避免碎片化多次打断父对话。
|
|
897
|
+
*/
|
|
898
|
+
scheduleSubagentCompletionNotice(conv) {
|
|
899
|
+
const parentId = conv.parentId;
|
|
900
|
+
if (!parentId || conv.notifyOnDone === false)
|
|
901
|
+
return;
|
|
902
|
+
if (conv.subagentDoneNotified || conv.subagentConsumedByParent)
|
|
903
|
+
return;
|
|
904
|
+
let entry = this.pendingSubagentNotices.get(parentId);
|
|
905
|
+
if (!entry) {
|
|
906
|
+
entry = {
|
|
907
|
+
timer: null,
|
|
908
|
+
subagents: new Set(),
|
|
909
|
+
};
|
|
910
|
+
this.pendingSubagentNotices.set(parentId, entry);
|
|
911
|
+
}
|
|
912
|
+
entry.subagents.add(conv);
|
|
913
|
+
if (entry.timer)
|
|
914
|
+
clearTimeout(entry.timer);
|
|
915
|
+
entry.timer = setTimeout(() => {
|
|
916
|
+
void this.flushSubagentCompletionNotice(parentId);
|
|
917
|
+
}, 400);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* issue #726:提取并清空当前对话挂起的子代理通知。
|
|
921
|
+
* 过滤掉已被消费(subagentConsumedByParent)或已通知(subagentDoneNotified)的子代理,
|
|
922
|
+
* 将留存的挂起子代理标为已通知,返回待交付的列表。
|
|
923
|
+
*/
|
|
924
|
+
drainSuspendedSubagents(conv) {
|
|
925
|
+
if (!conv.suspendedSubagents || conv.suspendedSubagents.size === 0)
|
|
926
|
+
return [];
|
|
927
|
+
const buffered = Array.from(conv.suspendedSubagents).filter((c) => !c.subagentConsumedByParent && !c.subagentDoneNotified);
|
|
928
|
+
conv.suspendedSubagents.clear();
|
|
929
|
+
for (const c of buffered) {
|
|
930
|
+
c.subagentDoneNotified = true;
|
|
931
|
+
}
|
|
932
|
+
return buffered;
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* issue #726:检查子代理自动唤醒熔断条件。
|
|
936
|
+
* 区分真正的循环(空转/单代理反复震荡/超出配置的轮数上限)与有效流程推进。
|
|
937
|
+
*/
|
|
938
|
+
checkSubagentWakeCircuitBreaker(targetConv, parentOwner, _toNotify) {
|
|
939
|
+
// 1. 空转熔断:父对话由子代理唤醒后,连续 2 轮未执行任何工具操作(纯回复或停止),又有子代理唤醒
|
|
940
|
+
const idleTurns = targetConv.consecutiveIdleWakeTurns ?? 0;
|
|
941
|
+
if (idleTurns >= 2) {
|
|
942
|
+
return {
|
|
943
|
+
suspend: true,
|
|
944
|
+
reason: "idle_loop",
|
|
945
|
+
messageZh: (count) => `子代理协作检测到父对话已连续 ${idleTurns} 轮未执行任何操作(处于空转/等待状态),已挂起后续自动唤醒(${count} 个完成通知已暂存)。请查看结果并输入新指令。`,
|
|
946
|
+
messageEn: (count) => `Subagent orchestration detected ${idleTurns} consecutive idle wake turns (no tool actions performed); auto-wake suspended (${count} notice(s) buffered). Please inspect and reply.`,
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
// 2. 单代理反复震荡死锁检测:如果最近连续 4 次唤醒完全来自于同一个子代理(无其他子代理且无人类干预)
|
|
950
|
+
const recentIds = targetConv.recentWakeSubagentIds ?? [];
|
|
951
|
+
if (recentIds.length >= 4) {
|
|
952
|
+
const tail = recentIds.slice(-4);
|
|
953
|
+
const first = tail[0];
|
|
954
|
+
if (tail.every((id) => id === first)) {
|
|
955
|
+
const short = first.slice(0, 8);
|
|
956
|
+
return {
|
|
957
|
+
suspend: true,
|
|
958
|
+
reason: "single_agent_oscillation",
|
|
959
|
+
messageZh: (count) => `检测到同一个子代理 ${short} 连续反复唤醒父对话达到 4 次,可能陷入修改死循环,已挂起自动唤醒(${count} 个完成通知已暂存)。请查看结果并介入。`,
|
|
960
|
+
messageEn: (count) => `Subagent ${short} consecutively woke parent conversation 4 times (potential oscillation loop); auto-wake suspended (${count} notice(s) buffered). Please inspect.`,
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
// 3. 自主连续轮次上限检测:可配置(0 = 不限制,默认 5 轮)
|
|
965
|
+
const autoTurns = targetConv.autonomousTurnsWithoutUser ?? 0;
|
|
966
|
+
const maxTurns = parentOwner?.settingsSvc?.current?.subagentAutoWakeMaxTurns ?? defaultSubagentAutoWakeMaxTurns();
|
|
967
|
+
if (maxTurns > 0 && autoTurns >= maxTurns) {
|
|
968
|
+
return {
|
|
969
|
+
suspend: true,
|
|
970
|
+
reason: "max_turns",
|
|
971
|
+
messageZh: (count) => `子代理协作已自动推进 ${autoTurns} 轮,已触发防死循环熔断(上限 ${maxTurns} 轮),已暂停自动唤醒(${count} 个完成通知已暂存)。请查看结果或输入新指令继续。`,
|
|
972
|
+
messageEn: (count) => `Subagent orchestration advanced ${autoTurns} autonomous rounds (limit ${maxTurns}); auto-wake suspended to prevent loops (${count} notice(s) buffered). Please inspect or reply to continue.`,
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
return null;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* 执行向父对话投递已完成子代理的结构化通知。
|
|
979
|
+
*/
|
|
980
|
+
async flushSubagentCompletionNotice(parentId, retryCount = 0) {
|
|
981
|
+
const entry = this.pendingSubagentNotices.get(parentId);
|
|
982
|
+
if (!entry)
|
|
983
|
+
return;
|
|
984
|
+
this.pendingSubagentNotices.delete(parentId);
|
|
985
|
+
if (entry.timer)
|
|
986
|
+
clearTimeout(entry.timer);
|
|
987
|
+
// 过滤出未被消费、未被通知过的子代理
|
|
988
|
+
const toNotify = Array.from(entry.subagents).filter((c) => !c.subagentConsumedByParent && !c.subagentDoneNotified);
|
|
989
|
+
if (toNotify.length === 0)
|
|
990
|
+
return;
|
|
991
|
+
// issue #728:提前结算隔离工作树,确保通知文本包含最新工作树状态
|
|
992
|
+
if (typeof this.finalizeSubagentWorktree === "function") {
|
|
993
|
+
await Promise.all(toNotify.map((c) => this.finalizeSubagentWorktree(c)));
|
|
994
|
+
}
|
|
995
|
+
// 寻找父对话(支持跨 ClientSession 查找)
|
|
996
|
+
const parentOwner = this.subagentOwnerOf(parentId);
|
|
997
|
+
let targetConv = parentOwner.convs.get(parentId);
|
|
998
|
+
let isFallback = false;
|
|
999
|
+
// 活跃视口兜底:若原父对话已不在,寻找同 cwd 的活跃非子代理对话
|
|
1000
|
+
if (!targetConv || !targetConv.session) {
|
|
1001
|
+
const projectCwd = toNotify[0]?.cwd ?? this.cwd;
|
|
1002
|
+
for (const c of parentOwner.convs.values()) {
|
|
1003
|
+
if (!c.isSubagent && c.cwd === projectCwd) {
|
|
1004
|
+
targetConv = c;
|
|
1005
|
+
isFallback = true;
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
// 无存活主对话时优雅降级为系统 Notice,不报错不中断
|
|
1011
|
+
if (!targetConv || !targetConv.session) {
|
|
1012
|
+
for (const c of toNotify)
|
|
1013
|
+
c.subagentDoneNotified = true;
|
|
1014
|
+
const ids = toNotify.map((c) => c.id.slice(0, 8)).join(", ");
|
|
1015
|
+
this.emit({
|
|
1016
|
+
type: "notice",
|
|
1017
|
+
level: "info",
|
|
1018
|
+
text: `子代理 ${ids} 已执行完毕(原父对话已关闭)。`,
|
|
1019
|
+
textEn: `Subagents ${ids} completed (originating conversation is closed).`,
|
|
1020
|
+
});
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
// issue #726:自适应防死循环熔断(检查空转、单代理震荡、配置的轮次上限)
|
|
1024
|
+
const checker = this.checkSubagentWakeCircuitBreaker ?? ClientSession.prototype.checkSubagentWakeCircuitBreaker;
|
|
1025
|
+
const circuit = checker.call(this, targetConv, parentOwner, toNotify);
|
|
1026
|
+
if (circuit) {
|
|
1027
|
+
targetConv.suspendedSubagents = targetConv.suspendedSubagents ?? new Set();
|
|
1028
|
+
for (const c of toNotify) {
|
|
1029
|
+
targetConv.suspendedSubagents.add(c);
|
|
1030
|
+
}
|
|
1031
|
+
const count = targetConv.suspendedSubagents.size;
|
|
1032
|
+
parentOwner.emit({
|
|
1033
|
+
type: "notice",
|
|
1034
|
+
level: "warning",
|
|
1035
|
+
text: circuit.messageZh(count),
|
|
1036
|
+
textEn: circuit.messageEn(count),
|
|
1037
|
+
});
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
// 若目标对话正在进行上下文压缩(isCompacting),延迟 800ms 避让重试
|
|
1041
|
+
if (targetConv.session.isCompacting === true) {
|
|
1042
|
+
if (retryCount < 10) {
|
|
1043
|
+
const retryTimer = setTimeout(() => {
|
|
1044
|
+
this.pendingSubagentNotices.set(parentId, { timer: retryTimer, subagents: new Set(toNotify) });
|
|
1045
|
+
void this.flushSubagentCompletionNotice(parentId, retryCount + 1);
|
|
1046
|
+
}, 800);
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
for (const c of toNotify) {
|
|
1051
|
+
c.subagentDoneNotified = true;
|
|
1052
|
+
}
|
|
1053
|
+
const noticeText = formatSubagentsCompletionNotice(toNotify, this.getLang(), isFallback ? parentId : undefined);
|
|
1054
|
+
const autoTurns = targetConv.autonomousTurnsWithoutUser ?? 0;
|
|
1055
|
+
targetConv.autonomousTurnsWithoutUser = autoTurns + 1;
|
|
1056
|
+
targetConv.wakeReason = "subagent_completion";
|
|
1057
|
+
targetConv.wakeTurnHadAction = false;
|
|
1058
|
+
targetConv.recentWakeSubagentIds = [
|
|
1059
|
+
...(targetConv.recentWakeSubagentIds ?? []),
|
|
1060
|
+
...toNotify.map((c) => c.id),
|
|
1061
|
+
].slice(-10);
|
|
1062
|
+
try {
|
|
1063
|
+
await targetConv.session.sendUserMessage(noticeText, targetConv.session.isStreaming ? { deliverAs: "steer" } : undefined);
|
|
1064
|
+
parentOwner.flushSnapshot();
|
|
1065
|
+
}
|
|
1066
|
+
catch (err) {
|
|
1067
|
+
parentOwner.emit({
|
|
1068
|
+
type: "notice",
|
|
1069
|
+
level: "warning",
|
|
1070
|
+
text: `向父对话投递子代理完成通知失败:${err.message}`,
|
|
1071
|
+
textEn: `Failed to deliver subagent completion notice to parent conversation: ${err.message}`,
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
727
1075
|
/**
|
|
728
1076
|
* 事件驱动地等某对话「当前回合结束」(目标模式委托执行用)。
|
|
729
1077
|
* 若当前并未在跑则立即返回既有结局;超时返回 "timeout";对话已消失返回 "gone"。
|
|
@@ -820,18 +1168,32 @@ export class ClientSession {
|
|
|
820
1168
|
this.emit(msg);
|
|
821
1169
|
}
|
|
822
1170
|
pushTerminals(conversation = this.conv) {
|
|
1171
|
+
const userList = this.userTerminals ? this.userTerminals.list() : [];
|
|
1172
|
+
const convList = conversation ? conversation.terminals.list() : [];
|
|
823
1173
|
this.emit({
|
|
824
1174
|
type: "terminal_list",
|
|
825
|
-
conversationId: conversation
|
|
826
|
-
terminals:
|
|
1175
|
+
conversationId: conversation?.id,
|
|
1176
|
+
terminals: [...userList, ...convList],
|
|
827
1177
|
});
|
|
828
|
-
|
|
829
|
-
this.
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
1178
|
+
if (this.userTerminals) {
|
|
1179
|
+
for (const output of this.userTerminals.replay()) {
|
|
1180
|
+
this.emit({
|
|
1181
|
+
type: "terminal_output",
|
|
1182
|
+
conversationId: conversation?.id,
|
|
1183
|
+
terminalId: output.terminalId,
|
|
1184
|
+
data: output.data,
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
if (conversation) {
|
|
1189
|
+
for (const output of conversation.terminals.replay()) {
|
|
1190
|
+
this.emit({
|
|
1191
|
+
type: "terminal_output",
|
|
1192
|
+
conversationId: conversation.id,
|
|
1193
|
+
terminalId: output.terminalId,
|
|
1194
|
+
data: output.data,
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
835
1197
|
}
|
|
836
1198
|
}
|
|
837
1199
|
/**
|
|
@@ -974,6 +1336,17 @@ export class ClientSession {
|
|
|
974
1336
|
if (conv?.planMode === true)
|
|
975
1337
|
for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
|
|
976
1338
|
disabled.add(n);
|
|
1339
|
+
if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
|
|
1340
|
+
for (const t of all) {
|
|
1341
|
+
if (!conv.subagentAllowedTools.has(t))
|
|
1342
|
+
disabled.add(t);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
|
|
1346
|
+
for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
|
|
1347
|
+
disabled.add(toolName);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
977
1350
|
return all.filter((n) => allowed.has(n) && !disabled.has(n));
|
|
978
1351
|
}
|
|
979
1352
|
/** 工具在系统提示词里的一行摘要:用户覆盖 → 出厂 snippet → 描述首句。 */
|
|
@@ -1064,6 +1437,17 @@ export class ClientSession {
|
|
|
1064
1437
|
if (conv?.planMode === true)
|
|
1065
1438
|
for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
|
|
1066
1439
|
disabled.add(n);
|
|
1440
|
+
if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
|
|
1441
|
+
for (const t of all) {
|
|
1442
|
+
if (!conv.subagentAllowedTools.has(t))
|
|
1443
|
+
disabled.add(t);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
|
|
1447
|
+
for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
|
|
1448
|
+
disabled.add(toolName);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1067
1451
|
const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
|
|
1068
1452
|
// 「已加载集合」里有名字 ≠ 活跃集里有它:JIT 自动激活(见 autoActivateToolIfLoadable)
|
|
1069
1453
|
// 与任何只标记不重放门控的路径都会造出这种半吊子状态。按活跃集判定,
|
|
@@ -1214,6 +1598,7 @@ export class ClientSession {
|
|
|
1214
1598
|
return renderMainCompose(this.composeInputs(src), {
|
|
1215
1599
|
promptTemplate: this.settingsSvc.current.promptTemplate,
|
|
1216
1600
|
promptOverrides: this.settingsSvc.current.promptOverrides,
|
|
1601
|
+
promptDisabled: this.settingsSvc.current.promptDisabled ?? [],
|
|
1217
1602
|
preset,
|
|
1218
1603
|
disabledToolCount: effectiveDisabledAgentTools(this.settingsSvc.current).length,
|
|
1219
1604
|
isLazy: src.lazy,
|
|
@@ -1267,9 +1652,12 @@ export class ClientSession {
|
|
|
1267
1652
|
const def = sess.getToolDefinition(name);
|
|
1268
1653
|
if (!def)
|
|
1269
1654
|
continue;
|
|
1270
|
-
const
|
|
1271
|
-
|
|
1655
|
+
const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
|
|
1656
|
+
const eff = effectiveToolPrompt(def, ov);
|
|
1657
|
+
// 与活体 run 钩子同规则:非延迟模式只列被覆盖过的 snippet(省 token 且与实发一致)。
|
|
1658
|
+
if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
|
|
1272
1659
|
snippets[name] = eff.promptSnippet.trim();
|
|
1660
|
+
}
|
|
1273
1661
|
if (baseSet.has(name) && eff.promptGuidelines)
|
|
1274
1662
|
guidelines.push(...eff.promptGuidelines);
|
|
1275
1663
|
}
|
|
@@ -1292,7 +1680,7 @@ export class ClientSession {
|
|
|
1292
1680
|
const tpl = (this.settingsSvc.current.promptTemplate ?? "").trim();
|
|
1293
1681
|
const ovs = this.settingsSvc.current.promptOverrides ?? {};
|
|
1294
1682
|
const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
|
|
1295
|
-
const rendered = renderPromptTemplate(tpl || DEFAULT_PROMPT_TEMPLATE, texts, hasOverride ? ovs : undefined);
|
|
1683
|
+
const rendered = renderPromptTemplate(tpl || DEFAULT_PROMPT_TEMPLATE, texts, hasOverride ? ovs : undefined, new Set(this.settingsSvc.current.promptDisabled ?? []));
|
|
1296
1684
|
return { texts, full: rendered, toolsSchema: buildToolsSchemaText(schemaEntries) };
|
|
1297
1685
|
}
|
|
1298
1686
|
catch {
|
|
@@ -1442,12 +1830,20 @@ export class ClientSession {
|
|
|
1442
1830
|
}
|
|
1443
1831
|
}
|
|
1444
1832
|
subagentHost = {
|
|
1445
|
-
spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist) => {
|
|
1833
|
+
spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra) => {
|
|
1446
1834
|
// B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
|
|
1447
1835
|
// 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
|
|
1448
1836
|
// 否则新子代理注册进旧会话、目标页左栏「不见/错位」。
|
|
1449
1837
|
const owner = parentId ? this.subagentOwnerOf(parentId) : this;
|
|
1450
|
-
return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist);
|
|
1838
|
+
return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra);
|
|
1839
|
+
},
|
|
1840
|
+
finalizeSubagentWorktree: async (convId) => {
|
|
1841
|
+
const owner = this.subagentOwnerOf(convId);
|
|
1842
|
+
const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
|
|
1843
|
+
const conv = owner.convs.get(curId);
|
|
1844
|
+
if (conv) {
|
|
1845
|
+
await owner.finalizeSubagentWorktree(conv);
|
|
1846
|
+
}
|
|
1451
1847
|
},
|
|
1452
1848
|
getSubagent: (convId) => {
|
|
1453
1849
|
// B20:本会话查不到就去「当前持有方」查 —— 过户把子代理整体搬走后,
|
|
@@ -1459,6 +1855,19 @@ export class ClientSession {
|
|
|
1459
1855
|
return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
|
|
1460
1856
|
},
|
|
1461
1857
|
listSubagents: (scope, forSelfId) => this.listSubagentSnapshots(scope, forSelfId),
|
|
1858
|
+
markSubagentsConsumed: (runIds) => {
|
|
1859
|
+
for (const id of runIds) {
|
|
1860
|
+
const owner = this.subagentOwnerOf(id);
|
|
1861
|
+
const curId = owner.convs.has(id) ? id : this.subagentCurrentId(id);
|
|
1862
|
+
const conv = owner.convs.get(curId);
|
|
1863
|
+
if (conv) {
|
|
1864
|
+
conv.subagentConsumedByParent = true;
|
|
1865
|
+
for (const parent of owner.convs.values()) {
|
|
1866
|
+
parent.suspendedSubagents?.delete(conv);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
},
|
|
1462
1871
|
handoffSubagent: async (fromRunId, toRunId, payload) => {
|
|
1463
1872
|
await this.handoffSubagent(fromRunId, toRunId, payload);
|
|
1464
1873
|
},
|
|
@@ -1479,8 +1888,29 @@ export class ClientSession {
|
|
|
1479
1888
|
if (conv.session.isStreaming || !conv.session.isIdle) {
|
|
1480
1889
|
await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
|
|
1481
1890
|
}
|
|
1891
|
+
if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
|
|
1892
|
+
void owner.finalizeSubagentWorktree(conv).catch(() => { });
|
|
1893
|
+
}
|
|
1482
1894
|
}
|
|
1483
1895
|
},
|
|
1896
|
+
getActiveConversationId: () => this.activeId,
|
|
1897
|
+
dismissSubagent: async (convId, opts) => {
|
|
1898
|
+
const owner = this.subagentOwnerOf(convId);
|
|
1899
|
+
const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
|
|
1900
|
+
const conv = owner.convs.get(curId);
|
|
1901
|
+
if (!conv) {
|
|
1902
|
+
return { ok: false, reason: "not_found" };
|
|
1903
|
+
}
|
|
1904
|
+
if (curId === owner.activeId) {
|
|
1905
|
+
return { ok: false, reason: "active" };
|
|
1906
|
+
}
|
|
1907
|
+
if (!conv.isSubagent && !conv.parentId && !conv.subagentPrompt) {
|
|
1908
|
+
return { ok: false, reason: "not_subagent" };
|
|
1909
|
+
}
|
|
1910
|
+
await owner.dismissConversation(curId, true, opts?.force);
|
|
1911
|
+
const stillThere = owner.convs.has(curId);
|
|
1912
|
+
return stillThere ? { ok: false, reason: "retained" } : { ok: true };
|
|
1913
|
+
},
|
|
1484
1914
|
getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
|
|
1485
1915
|
// issue #91:子代理工具返回按客户端 UI 语言出中英(英文默认)。
|
|
1486
1916
|
lang: () => this.getLang(),
|
|
@@ -1672,6 +2102,8 @@ export class ClientSession {
|
|
|
1672
2102
|
subagentTemplates;
|
|
1673
2103
|
/** 审批规则库(全局共享,<dataDir>/approval-rules.json)。 */
|
|
1674
2104
|
approvalRules;
|
|
2105
|
+
/** 审批审计日志追加器(<dataDir>/audit/approvals.jsonl,Issue #722)。 */
|
|
2106
|
+
auditLogger;
|
|
1675
2107
|
/** 未发送输入框草稿(全局共享,<dataDir>/composer-drafts.json,按 sessionId 键入,见 server/composer-drafts.ts)。 */
|
|
1676
2108
|
drafts;
|
|
1677
2109
|
/** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
|
|
@@ -1693,8 +2125,21 @@ export class ClientSession {
|
|
|
1693
2125
|
/** 任务计划管理器(Plan Mode / Step State Machine)。 */
|
|
1694
2126
|
planManager;
|
|
1695
2127
|
approvalSeq = 0;
|
|
1696
|
-
/**
|
|
1697
|
-
|
|
2128
|
+
/** 确保对话拥有待审批项 Map */
|
|
2129
|
+
ensurePendingApprovals(conv) {
|
|
2130
|
+
if (!conv.pendingApprovals)
|
|
2131
|
+
conv.pendingApprovals = new Map();
|
|
2132
|
+
return conv.pendingApprovals;
|
|
2133
|
+
}
|
|
2134
|
+
/** 跨对话查找挂起的审批条目及其所属对话 */
|
|
2135
|
+
findPendingApproval(id) {
|
|
2136
|
+
for (const conv of this.convs.values()) {
|
|
2137
|
+
if (conv.pendingApprovals?.has(id)) {
|
|
2138
|
+
return { conv, entry: conv.pendingApprovals.get(id) };
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
return undefined;
|
|
2142
|
+
}
|
|
1698
2143
|
// -----------------------------------------------------------------------
|
|
1699
2144
|
// 浏览器页面桥(标准 pi 引擎的 browser_page customTool):模型调工具 → 发
|
|
1700
2145
|
// page_request 给浏览器 → 前端转 page-picker 扩展 → page_response 回到这里
|
|
@@ -1717,6 +2162,7 @@ export class ClientSession {
|
|
|
1717
2162
|
this.roots = stateStore.getWorkspaceRoots(clientId, cwd);
|
|
1718
2163
|
this.subagentTemplates = new SubagentTemplatesStore(join(stateStore.dataDir, "subagent-templates.json"));
|
|
1719
2164
|
this.approvalRules = new ApprovalRulesStore(join(stateStore.dataDir, "approval-rules.json"));
|
|
2165
|
+
this.auditLogger = new ApprovalAuditLogger(stateStore.dataDir);
|
|
1720
2166
|
this.drafts = new ComposerDraftsStore(join(stateStore.dataDir, "composer-drafts.json"));
|
|
1721
2167
|
this.sandboxes = new SandboxManager(stateStore.dataDir);
|
|
1722
2168
|
this.planManager = new PlanManager(join(stateStore.dataDir, "plans.json"));
|
|
@@ -1758,21 +2204,21 @@ export class ClientSession {
|
|
|
1758
2204
|
getSession: () => this.session,
|
|
1759
2205
|
cwd: () => this.cwd,
|
|
1760
2206
|
agentDir: () => this.agentDir,
|
|
1761
|
-
isStreaming: () => this.session.isStreaming,
|
|
2207
|
+
isStreaming: () => this.session.isStreaming || Boolean(this.conv?.promptInFlight),
|
|
1762
2208
|
reloadSession: async () => {
|
|
2209
|
+
if (this.session.isStreaming || Boolean(this.conv?.promptInFlight)) {
|
|
2210
|
+
this.settingsSvc.setPendingReload(true);
|
|
2211
|
+
return;
|
|
2212
|
+
}
|
|
1763
2213
|
await this.session.reload();
|
|
1764
|
-
// reload() 重读磁盘 settings.json
|
|
1765
|
-
|
|
1766
|
-
this.applyRetryOverrides();
|
|
1767
|
-
this.applyCompactionOverrides();
|
|
1768
|
-
this.applyCodemodeOverrides();
|
|
1769
|
-
// reload() 会把 custom 工具重新加回活跃集——重放当前会话归属预设门控。
|
|
1770
|
-
this.applyToolGating(this.session, this.conv?.agentPreset);
|
|
2214
|
+
// reload() 重读磁盘 settings.json,统一收口重放配置覆盖与工具门控
|
|
2215
|
+
this.applySessionOverrides(this.conv);
|
|
1771
2216
|
await this.pushSlashCommands();
|
|
1772
2217
|
},
|
|
1773
2218
|
applyRetryOverrides: () => this.applyRetryOverrides(),
|
|
1774
2219
|
applyCompactionOverrides: () => this.applyCompactionOverrides(),
|
|
1775
2220
|
applyCodemodeOverrides: () => this.applyCodemodeOverrides(),
|
|
2221
|
+
applySessionOverrides: () => this.applySessionOverrides(),
|
|
1776
2222
|
applyToolGating: () => {
|
|
1777
2223
|
for (const conv of this.convs.values()) {
|
|
1778
2224
|
this.applyToolGating(conv.session, conv.agentPreset);
|
|
@@ -1970,6 +2416,14 @@ export class ClientSession {
|
|
|
1970
2416
|
// Prune dead background tasks every 30s (only spawns netstat/lsof while
|
|
1971
2417
|
// the list is non-empty). unref: must not keep the process alive.
|
|
1972
2418
|
this.bg.start();
|
|
2419
|
+
this.userTerminals = this.makeUserTerminalManager();
|
|
2420
|
+
if (!ephemeralCleanupScheduled) {
|
|
2421
|
+
ephemeralCleanupScheduled = true;
|
|
2422
|
+
const timer = setTimeout(() => {
|
|
2423
|
+
cleanupOrphanedSessionDirs(this.agentDir);
|
|
2424
|
+
}, 5000);
|
|
2425
|
+
timer.unref?.();
|
|
2426
|
+
}
|
|
1973
2427
|
}
|
|
1974
2428
|
static async create(clientId, cwd, stateStore, opts) {
|
|
1975
2429
|
const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
|
|
@@ -2114,8 +2568,9 @@ export class ClientSession {
|
|
|
2114
2568
|
* 应用(prompt replace/append + 白名单),其余(终端接管、Windows persona
|
|
2115
2569
|
* 等)仍跟随主会话设置。undefined = 按主会话设置(普通对话/不选模板的子代理)。
|
|
2116
2570
|
*/
|
|
2117
|
-
makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset) {
|
|
2571
|
+
makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset, noSpawnTools) {
|
|
2118
2572
|
return async ({ cwd: effectiveCwd, sessionManager }) => {
|
|
2573
|
+
const sdkBuiltins = await getSdkBuiltinExtensionFactories();
|
|
2119
2574
|
const services = await createAgentSessionServices({
|
|
2120
2575
|
cwd: effectiveCwd,
|
|
2121
2576
|
modelRuntime: this.sharedModelRuntime,
|
|
@@ -2205,16 +2660,22 @@ export class ClientSession {
|
|
|
2205
2660
|
// 否则按主会话禁用集过滤。预设拿掉 skill 加载器时(minimal/code/ask)
|
|
2206
2661
|
// 名录同步隐藏——列出来但调不动只是噪音(见 tool-manager.ts 语义总表)。
|
|
2207
2662
|
skillsOverride: (res) => {
|
|
2663
|
+
const discovered = discoverDiskSkills({
|
|
2664
|
+
cwd: effectiveCwd,
|
|
2665
|
+
agentDir: this.agentDir,
|
|
2666
|
+
workspaceRoots: this.roots,
|
|
2667
|
+
});
|
|
2668
|
+
const allSkills = mergeSkillCollections(res.skills, discovered);
|
|
2208
2669
|
if (apply && apply.enabledSkills.length > 0) {
|
|
2209
2670
|
const set = new Set(apply.enabledSkills);
|
|
2210
|
-
return { ...res, skills:
|
|
2671
|
+
return { ...res, skills: allSkills.filter((s) => set.has(s.name)) };
|
|
2211
2672
|
}
|
|
2212
2673
|
const preset = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2213
2674
|
if (!presetShowsSkillCatalog(preset))
|
|
2214
2675
|
return { ...res, skills: [] };
|
|
2215
2676
|
return {
|
|
2216
2677
|
...res,
|
|
2217
|
-
skills:
|
|
2678
|
+
skills: allSkills.filter((s) => !this.settingsSvc.current.disabledSkills.includes(s.name)),
|
|
2218
2679
|
};
|
|
2219
2680
|
},
|
|
2220
2681
|
// 插件:模板非空扩展白名单时只加载白名单里的;否则按主会话禁用集过滤。
|
|
@@ -2239,19 +2700,9 @@ export class ClientSession {
|
|
|
2239
2700
|
// agent run 前触发,SDK 此时已用最新工具/资源拼好基础提示词;若配置了模板或
|
|
2240
2701
|
// 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
|
|
2241
2702
|
// 等都取自本次 run 的 systemPromptOptions,永远最新)。
|
|
2703
|
+
disabledBuiltinExtensions: SDK_DISABLED_BUILTIN_EXTENSIONS,
|
|
2242
2704
|
extensionFactories: [
|
|
2243
|
-
|
|
2244
|
-
name: "codemode",
|
|
2245
|
-
hidden: true,
|
|
2246
|
-
replaceable: true,
|
|
2247
|
-
factory: createCodemodeExtension(),
|
|
2248
|
-
},
|
|
2249
|
-
{
|
|
2250
|
-
name: "tool-search",
|
|
2251
|
-
hidden: true,
|
|
2252
|
-
replaceable: true,
|
|
2253
|
-
factory: createToolSearchExtension(),
|
|
2254
|
-
},
|
|
2705
|
+
...sdkBuiltins,
|
|
2255
2706
|
{
|
|
2256
2707
|
name: "pi-webui-persona",
|
|
2257
2708
|
hidden: true,
|
|
@@ -2301,8 +2752,11 @@ export class ClientSession {
|
|
|
2301
2752
|
const def = sess.getToolDefinition(name);
|
|
2302
2753
|
if (!def)
|
|
2303
2754
|
continue;
|
|
2304
|
-
const
|
|
2305
|
-
|
|
2755
|
+
const ov = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
|
|
2756
|
+
const eff = effectiveToolPrompt(def, ov);
|
|
2757
|
+
// 非延迟模式不展开完整目录(省 token):只列出被用户覆盖过的
|
|
2758
|
+
// snippet,保证覆盖文案能到达模型(活体链路恒走自渲染)。
|
|
2759
|
+
if (eff.promptSnippet && eff.promptSnippet.trim() && (lazyOn || ov?.promptSnippet)) {
|
|
2306
2760
|
activeSnippets[name] = eff.promptSnippet.trim();
|
|
2307
2761
|
}
|
|
2308
2762
|
if (baseSet.has(name) && eff.promptGuidelines) {
|
|
@@ -2385,61 +2839,37 @@ export class ClientSession {
|
|
|
2385
2839
|
services,
|
|
2386
2840
|
sessionManager,
|
|
2387
2841
|
model: sessionModel,
|
|
2388
|
-
//
|
|
2389
|
-
//
|
|
2390
|
-
//
|
|
2391
|
-
// 整列工具统一过计划模式闸门(只规划不实施,写类/旁路工具执行前拒),
|
|
2392
|
-
// read/write/edit 三处覆盖在会话建好后另注入(见 installToolOverrides)。
|
|
2842
|
+
// bash / read / write / edit 四处覆盖统一在会话建好后另注入(见 installToolOverrides)。
|
|
2843
|
+
// 原因是创建时的 customTools 恒顶掉第三方扩展注册的同名工具(SDK 的合并链是
|
|
2844
|
+
// [...扩展注册的工具, ...customTools] 后写赢,issue #750)。
|
|
2393
2845
|
customTools: [
|
|
2394
|
-
// P1-5:bash/read 包插件拦截(pre 拒/问即拦、post 脱敏补上下文;
|
|
2395
|
-
// 未注入 toolGuard 时 withToolGuard 原样返回,零开销)。
|
|
2396
|
-
// 权限沙箱拦截(只读模式拦截终端执行)。
|
|
2397
|
-
wrapBashToolWithPermission(withToolGuard(withWorkspaceSnapshotGate(makeAdaptiveBashTool(
|
|
2398
|
-
// issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
|
|
2399
|
-
makeKillableBashTool(effectiveCwd, this.bashKills, () => this.getLang()), makeTerminalBashTool(terminals, {
|
|
2400
|
-
cwd: effectiveCwd,
|
|
2401
|
-
// 设置开 = 用终端;此分支里 persist 未显式给时默认一次性(false)。
|
|
2402
|
-
defaultPersist: () => false,
|
|
2403
|
-
idleMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashIdleMs) || 0),
|
|
2404
|
-
maxForegroundMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashMaxForegroundMs) || 0),
|
|
2405
|
-
kills: this.bashKills,
|
|
2406
|
-
notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
|
|
2407
|
-
// issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
|
|
2408
|
-
lang: () => this.getLang(),
|
|
2409
|
-
}),
|
|
2410
|
-
// 设置关 → 原生 bash;开 → 终端 bash。
|
|
2411
|
-
() => this.settingsSvc.current.terminalBash), () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
|
|
2412
|
-
toolName: "bash",
|
|
2413
|
-
guard: this.lateToolGuard,
|
|
2414
|
-
conversationId: () => ownerId,
|
|
2415
|
-
getLang: () => this.getLang(),
|
|
2416
|
-
cwd: effectiveCwd,
|
|
2417
|
-
getRoots: () => this.roots,
|
|
2418
|
-
askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
|
|
2419
|
-
getRules: () => this.approvalRules.list(),
|
|
2420
|
-
}), () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
2421
|
-
this.settingsSvc.current.defaultPermissionPreset ??
|
|
2422
|
-
"workspace-write-never", () => this.getLang()),
|
|
2423
2846
|
...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang(), {
|
|
2424
|
-
checkSafety: (cmd) => {
|
|
2847
|
+
checkSafety: async (cmd, ctx) => {
|
|
2425
2848
|
// 沙盒硬围栏:禁止引用源项目路径或跳出沙盒根。
|
|
2426
2849
|
const activeSbx = this.sandboxes.getByCwd(effectiveCwd);
|
|
2427
2850
|
if (activeSbx) {
|
|
2428
2851
|
const sbxDenied = evaluateSandboxJail(activeSbx, "bash", { command: cmd }, effectiveCwd);
|
|
2429
2852
|
if (sbxDenied)
|
|
2430
|
-
return { blocked: true, reason: sbxDenied.reason };
|
|
2853
|
+
return { blocked: true, reason: sbxDenied.reason, reasonEn: sbxDenied.reasonEn };
|
|
2431
2854
|
}
|
|
2432
2855
|
// 计划模式:终端只放行只读命令(常驻终端也走这条,与 bash 覆盖同口径)。
|
|
2433
2856
|
if (this.planModeOf(ownerId)) {
|
|
2434
2857
|
const denied = planModeDenial("bash", { command: cmd });
|
|
2435
2858
|
if (denied)
|
|
2436
|
-
return { blocked: true, reason: denied.reason };
|
|
2859
|
+
return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
|
|
2437
2860
|
}
|
|
2438
2861
|
// 目标审查回合:常驻终端同样只放只读命令(审查者跑测试可以,改文件不行)。
|
|
2439
2862
|
if (this.goalReviewTurnOf(ownerId)) {
|
|
2440
2863
|
const denied = goalReviewDenial("bash", { command: cmd });
|
|
2441
2864
|
if (denied)
|
|
2442
|
-
return { blocked: true, reason: denied.reason };
|
|
2865
|
+
return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
|
|
2866
|
+
}
|
|
2867
|
+
// 子代理安全规格硬闸门(issue #727):受限子代理(readonly/verify)或工具白名单
|
|
2868
|
+
const subagentMode = this.subagentSecurityModeOf(ownerId);
|
|
2869
|
+
if (subagentMode !== "normal" || this.subagentAllowedToolsOf(ownerId)) {
|
|
2870
|
+
const denied = subagentSecurityDenial(subagentMode, "bash", { command: cmd }, this.subagentAllowedToolsOf(ownerId));
|
|
2871
|
+
if (denied)
|
|
2872
|
+
return { blocked: true, reason: denied.reason, reasonEn: denied.reasonEn };
|
|
2443
2873
|
}
|
|
2444
2874
|
const perm = (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
2445
2875
|
this.settingsSvc.current.defaultPermissionPreset ??
|
|
@@ -2447,17 +2877,77 @@ export class ClientSession {
|
|
|
2447
2877
|
if (perm === "read-only") {
|
|
2448
2878
|
const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
|
|
2449
2879
|
if (danger.denied || danger.dangerous) {
|
|
2450
|
-
return {
|
|
2880
|
+
return {
|
|
2881
|
+
blocked: true,
|
|
2882
|
+
reason: danger.reason || "只读模式禁止执行高危/破坏性命令",
|
|
2883
|
+
reasonEn: danger.reasonEn || "Read-only mode forbids dangerous or destructive commands",
|
|
2884
|
+
};
|
|
2451
2885
|
}
|
|
2452
2886
|
}
|
|
2887
|
+
// 1. 系统核心安全:内置高危操作检测与自定义审批规则先行(优先级最高,防绕过)
|
|
2453
2888
|
const danger = checkDangerousToolCall("bash", { command: cmd }, effectiveCwd, this.roots, this.approvalRules.list());
|
|
2454
2889
|
if (danger.denied) {
|
|
2455
|
-
return {
|
|
2890
|
+
return {
|
|
2891
|
+
blocked: true,
|
|
2892
|
+
reason: danger.reason || "命中系统阻断规则",
|
|
2893
|
+
reasonEn: danger.reasonEn || "Blocked by system approval rule",
|
|
2894
|
+
};
|
|
2895
|
+
}
|
|
2896
|
+
// 2. 插件前置守卫 deny 拦截
|
|
2897
|
+
let pre;
|
|
2898
|
+
if (this.lateToolGuard) {
|
|
2899
|
+
try {
|
|
2900
|
+
pre = await this.lateToolGuard.pre({ toolName: "bash", params: { command: cmd }, conversationId: ownerId }, this.getLang());
|
|
2901
|
+
}
|
|
2902
|
+
catch {
|
|
2903
|
+
pre = { verdict: { decision: "allow" } };
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
if (pre?.verdict.decision === "deny") {
|
|
2907
|
+
return {
|
|
2908
|
+
blocked: true,
|
|
2909
|
+
reason: pre.verdict.reason ?? "插件拒绝执行此命令",
|
|
2910
|
+
reasonEn: pre.verdict.reasonEn ?? "Plugin denied execution of this command",
|
|
2911
|
+
};
|
|
2912
|
+
}
|
|
2913
|
+
// 3. 决定是否需要弹窗审批(系统高危 ask 优先于插件通用 ask,issue #721)
|
|
2914
|
+
let needApproval = false;
|
|
2915
|
+
let approvalReason;
|
|
2916
|
+
let approvalReasonEn;
|
|
2917
|
+
let approvalCategory;
|
|
2918
|
+
let approvalHits;
|
|
2919
|
+
if (danger.dangerous) {
|
|
2920
|
+
needApproval = true;
|
|
2921
|
+
approvalReason = danger.reason;
|
|
2922
|
+
approvalReasonEn = danger.reasonEn;
|
|
2923
|
+
approvalCategory = danger.category;
|
|
2924
|
+
approvalHits = danger.hits;
|
|
2925
|
+
}
|
|
2926
|
+
else if (pre?.verdict.decision === "ask") {
|
|
2927
|
+
needApproval = true;
|
|
2928
|
+
approvalReason = pre.verdict.reason ?? "插件要求确认本次操作";
|
|
2929
|
+
approvalReasonEn = pre.verdict.reasonEn ?? "Plugin requested confirmation for this operation";
|
|
2930
|
+
approvalCategory = pluginApprovalCategory(pre.pluginId ?? "plugin");
|
|
2931
|
+
}
|
|
2932
|
+
if (needApproval) {
|
|
2933
|
+
const res = await this.askApproval(ctx.toolCallId, "bash", { command: cmd, terminalId: ctx.terminalId }, approvalReason, approvalReasonEn, ownerId, approvalCategory, approvalHits);
|
|
2934
|
+
if (res.decision === "deny") {
|
|
2935
|
+
return {
|
|
2936
|
+
blocked: true,
|
|
2937
|
+
userDenied: true,
|
|
2938
|
+
reason: res.reason || "操作被用户拒绝",
|
|
2939
|
+
reasonEn: res.reason || "Operation denied by user",
|
|
2940
|
+
};
|
|
2941
|
+
}
|
|
2942
|
+
if (res.decision === "edit") {
|
|
2943
|
+
const editedCmd = typeof res.editedParams?.command === "string" ? res.editedParams.command : cmd;
|
|
2944
|
+
return { editedCommand: editedCmd };
|
|
2945
|
+
}
|
|
2456
2946
|
}
|
|
2457
2947
|
return {};
|
|
2458
2948
|
},
|
|
2459
2949
|
}).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
|
|
2460
|
-
// read / write / edit
|
|
2950
|
+
// bash / read / write / edit 四处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
|
|
2461
2951
|
// 扩展加载顺序无关,直接塞进来会静默顶掉第三方扩展注册的同名工具(见
|
|
2462
2952
|
// tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
|
|
2463
2953
|
// 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置;带权限沙箱拦截与人机协同)。
|
|
@@ -2472,26 +2962,31 @@ export class ClientSession {
|
|
|
2472
2962
|
// 空白名单 = 跟随主会话(插件工具照常进入子代理)。
|
|
2473
2963
|
...(apply && apply.enabledExtensions.length > 0 ? [] : this.enabledPluginToolDefs()),
|
|
2474
2964
|
// 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
|
|
2475
|
-
//
|
|
2965
|
+
// 默认也注册了它们,因此可自然嵌套派发;设置了 subagentMaxDepth 且子代理
|
|
2966
|
+
// 已到上限层时 noSpawnTools=true,连同下面的 delegate_task 一起不注入。host 按 ownerId 包装:子代理的
|
|
2476
2967
|
// 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
|
|
2477
2968
|
// 派发瞬间的 active——后台对话继续产出时用户可能已切到别的项目,用
|
|
2478
2969
|
// activeId 会把孩子记到无关会话名下、沉到别的组/底部(issue #95)。
|
|
2479
2970
|
// ownerId 即本 runtime 所属会话(创建时就已知,见各调用点),一身二任:
|
|
2480
2971
|
// spawn 的 parentId(子代理记到真正的派发会话名下)+ wait_all 的
|
|
2481
2972
|
// selfConvId(调用者自身永不计入等待,防 self-wait deadlock)。
|
|
2482
|
-
...(
|
|
2483
|
-
?
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2973
|
+
...(noSpawnTools
|
|
2974
|
+
? []
|
|
2975
|
+
: ownerId
|
|
2976
|
+
? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined,
|
|
2977
|
+
// B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
|
|
2978
|
+
// 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
|
|
2979
|
+
() => bridgeAnchor.session
|
|
2980
|
+
? (this.findConversationHome?.(bridgeAnchor.session)?.convId ?? ownerId)
|
|
2981
|
+
: ownerId)
|
|
2982
|
+
: makeSubagentTools(this.subagentHost)),
|
|
2490
2983
|
// 结构化派单(六段式 + 服务端校验;执行体复用子代理 spawn 通道)。
|
|
2491
2984
|
// owner 包装与上面同理:子代理记到真正的派发会话名下。
|
|
2492
|
-
...(
|
|
2493
|
-
? [
|
|
2494
|
-
:
|
|
2985
|
+
...(noSpawnTools
|
|
2986
|
+
? []
|
|
2987
|
+
: ownerId
|
|
2988
|
+
? [makeDelegateTaskTool(withSubagentOwner(this.subagentHost, ownerId))]
|
|
2989
|
+
: [makeDelegateTaskTool(this.subagentHost)]),
|
|
2495
2990
|
// 结构化任务计划更新(Plan Mode / Step State Machine)。
|
|
2496
2991
|
makePlanUpdateTool(this.planManager, () => {
|
|
2497
2992
|
const id = ownerId ?? this.activeId;
|
|
@@ -2561,8 +3056,13 @@ export class ClientSession {
|
|
|
2561
3056
|
ownerId,
|
|
2562
3057
|
lang: () => this.getLang(),
|
|
2563
3058
|
}),
|
|
2564
|
-
// 高可靠行补丁工具(patch
|
|
2565
|
-
|
|
3059
|
+
// 高可靠行补丁工具(patch,基于内容哈希与语法块级替换)。写目标
|
|
3060
|
+
// (含 REM/MV)内嵌在补丁文本里,权限预设与敏感文件审批规则要靠
|
|
3061
|
+
// 包装器解析段头后求值——否则 read-only/workspace 沙箱与 .env 等
|
|
3062
|
+
// 规则会被 patch 整体旁路(write/edit 会拦的操作改走 patch 即落地)。
|
|
3063
|
+
wrapPatchToolWithPermission(makePatchTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
3064
|
+
this.settingsSvc.current.defaultPermissionPreset ??
|
|
3065
|
+
"workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category, hits) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category, hits), () => ownerId, () => this.approvalRules.list()),
|
|
2566
3066
|
// 原生语言服务器工具(lsp,定义跳转/引用/悬停/诊断)。
|
|
2567
3067
|
makeLspTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
|
|
2568
3068
|
// MCP 服务器检测与安装管理工具(mcp_manage:list/check/install/remove/reload)。
|
|
@@ -2594,19 +3094,28 @@ export class ClientSession {
|
|
|
2594
3094
|
lang: () => this.getLang(),
|
|
2595
3095
|
getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
|
|
2596
3096
|
}),
|
|
2597
|
-
].map((t) =>
|
|
2598
|
-
// 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
|
|
2599
|
-
// 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
|
|
2600
|
-
// 计划/审查者闸门同口径不在覆盖面,见 goal-review-gate.ts 头注)。
|
|
2601
|
-
withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(t, () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
|
|
3097
|
+
].map((t) => this.wrapGenericTool(t, ownerId, effectiveCwd)),
|
|
2602
3098
|
});
|
|
2603
3099
|
// 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
|
|
2604
3100
|
// 不改它(见 ClientSession.findConversationHome)。
|
|
2605
3101
|
bridgeAnchor.session = created.session;
|
|
2606
|
-
|
|
3102
|
+
if (noSpawnTools)
|
|
3103
|
+
SPAWN_TOOLS_BARRED.add(created.session);
|
|
3104
|
+
// bash / read / write / edit 四处覆盖在会话建好后注入(见 tool-overrides.ts):SDK 的合并链是
|
|
2607
3105
|
// [...扩展工具, ...customTools] 后写赢 ⇒ 创建时塞进 customTools 会**恒定顶掉**第三方
|
|
2608
|
-
// 扩展注册的同名工具(官方 docs/extensions.md 明写扩展可覆盖 read/write/edit)。
|
|
2609
|
-
installToolOverrides(created.session, this.toolOverrideSpecs(ownerId, effectiveCwd)
|
|
3106
|
+
// 扩展注册的同名工具(官方 docs/extensions.md 明写扩展可覆盖 bash/read/write/edit,issue #750)。
|
|
3107
|
+
installToolOverrides(created.session, this.toolOverrideSpecs(ownerId, effectiveCwd, terminals), {
|
|
3108
|
+
onComposed: (name) => {
|
|
3109
|
+
if (name === "bash") {
|
|
3110
|
+
this.emit({
|
|
3111
|
+
type: "notice",
|
|
3112
|
+
level: "info",
|
|
3113
|
+
text: "已接入第三方扩展注册的 bash 工具(扩展审查/沙箱已生效,内置终端接管已让位)。",
|
|
3114
|
+
textEn: "Third-party extension bash tool is active (extension review/sandbox enabled; built-in terminal takeover yielded).",
|
|
3115
|
+
});
|
|
3116
|
+
}
|
|
3117
|
+
},
|
|
3118
|
+
});
|
|
2610
3119
|
// 终端工具开关与预设门控从创建起就生效(工具始终注册进注册表,只调活跃集)。
|
|
2611
3120
|
this.applyToolGating(created.session, targetPreset);
|
|
2612
3121
|
return {
|
|
@@ -2666,7 +3175,8 @@ export class ClientSession {
|
|
|
2666
3175
|
lastMessagesArray: [],
|
|
2667
3176
|
queueSteering: [],
|
|
2668
3177
|
queueFollowUp: [],
|
|
2669
|
-
|
|
3178
|
+
queuedSteeringEntries: [],
|
|
3179
|
+
queuedFollowUpEntries: [],
|
|
2670
3180
|
toolStartTimes: new Map(),
|
|
2671
3181
|
toolPendingArgs: new Map(),
|
|
2672
3182
|
activeToolCalls: new Map(),
|
|
@@ -2947,13 +3457,8 @@ export class ClientSession {
|
|
|
2947
3457
|
onError: this.makeExtensionErrorReporter(conv.isEphemeral ? { text: `临时对话 ${conv.id}:`, textEn: `Ephemeral chat ${conv.id}: ` } : undefined),
|
|
2948
3458
|
});
|
|
2949
3459
|
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
2950
|
-
// 新会话 / 切换会话 /
|
|
2951
|
-
|
|
2952
|
-
// 次还是按 3 次重试”。已存在会话重复注入是幂等的(同值覆盖)。
|
|
2953
|
-
this.applyRetryOverrides();
|
|
2954
|
-
// 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
|
|
2955
|
-
this.applyCompactionOverrides();
|
|
2956
|
-
this.applyCodemodeOverrides();
|
|
3460
|
+
// 新会话 / 切换会话 / 强杀重建的必经之路:统一收口注入配置覆盖与工具门控
|
|
3461
|
+
this.applySessionOverrides(conv);
|
|
2957
3462
|
this.scheduleSnapshot();
|
|
2958
3463
|
this.webUi.refresh();
|
|
2959
3464
|
this.startWidgetsTimer();
|
|
@@ -3065,18 +3570,52 @@ export class ClientSession {
|
|
|
3065
3570
|
clearTimeout(t);
|
|
3066
3571
|
conv.toolWatchdogs.clear();
|
|
3067
3572
|
}
|
|
3573
|
+
/** 清理会话所有执行中的工具运行时状态(看门狗、计时器、进行中集合与参数缓存)。 */
|
|
3574
|
+
clearConversationToolStates(conv) {
|
|
3575
|
+
this.clearAllToolWatchdogs(conv);
|
|
3576
|
+
conv.toolStartTimes.clear();
|
|
3577
|
+
conv.activeToolCalls.clear();
|
|
3578
|
+
conv.toolPendingArgs.clear();
|
|
3579
|
+
}
|
|
3068
3580
|
/** 发一条运行轨迹事件给插件(host.onRunEvent 订阅者,如轨迹视图插件)。
|
|
3069
3581
|
* 异常隔离——序列化/插件坏了只记日志,绝不影响主流程。 */
|
|
3070
3582
|
emitRun(conv, ev) {
|
|
3071
3583
|
if (!this.onRunEvent)
|
|
3072
3584
|
return;
|
|
3073
3585
|
try {
|
|
3074
|
-
this.onRunEvent({
|
|
3586
|
+
this.onRunEvent({
|
|
3587
|
+
...ev,
|
|
3588
|
+
conversationId: conv.id,
|
|
3589
|
+
clientId: this.clientId,
|
|
3590
|
+
// 通道插件按它认领「自己那一轮」——过户换持有客户端、对话被改 id 都不影响。
|
|
3591
|
+
...(conv.pluginRunId ? { runId: conv.pluginRunId } : {}),
|
|
3592
|
+
at: Date.now(),
|
|
3593
|
+
});
|
|
3075
3594
|
}
|
|
3076
3595
|
catch (err) {
|
|
3077
3596
|
console.error("[agent-service] onRunEvent failed:", err);
|
|
3078
3597
|
}
|
|
3079
3598
|
}
|
|
3599
|
+
/** 插件无头调用(host.chat)标记「本轮由该插件驱动」,返回被打标的对话 id。
|
|
3600
|
+
* 已在流式中(steer 并入在途运行)立即生效;否则等 agent_start 认领。
|
|
3601
|
+
* token 在 run_end 清掉,用户随后自己接着聊的那一轮不会被误认成插件的。 */
|
|
3602
|
+
markPluginRun(runId, conv) {
|
|
3603
|
+
const target = conv ?? this.conv;
|
|
3604
|
+
const id = String(runId ?? "").trim();
|
|
3605
|
+
if (!target || !id)
|
|
3606
|
+
return target?.id ?? "";
|
|
3607
|
+
try {
|
|
3608
|
+
if (target.session.isStreaming)
|
|
3609
|
+
target.pluginRunId = id;
|
|
3610
|
+
else
|
|
3611
|
+
target.pendingPluginRunId = id;
|
|
3612
|
+
}
|
|
3613
|
+
catch {
|
|
3614
|
+
/* isStreaming 读不到就按未启动处理 */
|
|
3615
|
+
target.pendingPluginRunId = id;
|
|
3616
|
+
}
|
|
3617
|
+
return target.id;
|
|
3618
|
+
}
|
|
3080
3619
|
/** 当前打开对话变了 → 通知插件重拉(切历史会话/切 running 对话/新对话)。
|
|
3081
3620
|
* 异常隔离——插件坏了只记日志,绝不影响切换流程。 */
|
|
3082
3621
|
notifyConversationChanged() {
|
|
@@ -3275,6 +3814,12 @@ export class ClientSession {
|
|
|
3275
3814
|
await conv.session.sendUserMessage(text, conv.session.isStreaming ? { deliverAs: "steer" } : undefined);
|
|
3276
3815
|
return { ok: true };
|
|
3277
3816
|
}
|
|
3817
|
+
/** 按 id 取本会话持有的对话(不存在返回 undefined)。
|
|
3818
|
+
* host.chat 命中已有会话时,用它在**对方**会话里校验/定位被唤醒的那条对话。 */
|
|
3819
|
+
getConversation(id) {
|
|
3820
|
+
const key = String(id ?? "").trim();
|
|
3821
|
+
return key ? this.convs.get(key) : undefined;
|
|
3822
|
+
}
|
|
3278
3823
|
/** issue #231:本客户端内按稳定键定位调度唤醒目标。
|
|
3279
3824
|
* sessionFile 优先(压缩/重启后内存对话 id 已变,落盘会话文件才是同一会话);
|
|
3280
3825
|
* 只有没给 sessionFile 时才按内存 id 找,且 id 必须附带 cwd 一致才认 ——
|
|
@@ -3438,11 +3983,6 @@ export class ClientSession {
|
|
|
3438
3983
|
// Any SDK event proves the run is alive — feeds the stall watchdog below.
|
|
3439
3984
|
conv.lastSdkEventAt = Date.now();
|
|
3440
3985
|
conv.stallNoticed = false;
|
|
3441
|
-
// 模型可能在 pi-web-ui 之外被换(SDK 从会话历史恢复、/model 命令等),
|
|
3442
|
-
// 而软上限 reserve 是按注入那一刻的窗口换算的固定值——模型一变必须重算,
|
|
3443
|
-
// 否则大窗口算出的 reserve 泄漏到小窗口模型上,触发点被压成负数,
|
|
3444
|
-
// 上下文刚过几万 token 就反复触发压缩。热路径只做一次字符串比对。
|
|
3445
|
-
this.reapplySoftCapIfModelChanged(conv);
|
|
3446
3986
|
switch (event.type) {
|
|
3447
3987
|
case "bash_execution_update": {
|
|
3448
3988
|
if (event.id) {
|
|
@@ -3458,6 +3998,8 @@ export class ClientSession {
|
|
|
3458
3998
|
break;
|
|
3459
3999
|
}
|
|
3460
4000
|
case "tool_execution_start": {
|
|
4001
|
+
// issue #726:记录本轮触发了实质性工具操作,证明非空转推进
|
|
4002
|
+
conv.wakeTurnHadAction = true;
|
|
3461
4003
|
// JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
|
|
3462
4004
|
// automatically mark it as loaded so subsequent turns track it as fully active.
|
|
3463
4005
|
if (conv.session && event.toolName) {
|
|
@@ -3588,14 +4130,8 @@ export class ClientSession {
|
|
|
3588
4130
|
case "queue_update":
|
|
3589
4131
|
conv.queueSteering = [...event.steering];
|
|
3590
4132
|
conv.queueFollowUp = [...event.followUp];
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
for (const key of conv.queuedImages.keys()) {
|
|
3594
|
-
if (!allQueued.has(key)) {
|
|
3595
|
-
conv.queuedImages.delete(key);
|
|
3596
|
-
}
|
|
3597
|
-
}
|
|
3598
|
-
}
|
|
4133
|
+
conv.queuedSteeringEntries = reconcileQueuedEntries(conv.queuedSteeringEntries ?? [], event.steering);
|
|
4134
|
+
conv.queuedFollowUpEntries = reconcileQueuedEntries(conv.queuedFollowUpEntries ?? [], event.followUp);
|
|
3599
4135
|
break;
|
|
3600
4136
|
// 手动 /compact 或阈值/溢出自动压缩开始——常驻进度条(快照 compaction
|
|
3601
4137
|
// 字段),而不是一次性 toast(toast 几秒就消失,而摘要生成可能持续
|
|
@@ -3705,6 +4241,10 @@ export class ClientSession {
|
|
|
3705
4241
|
return a.role === "assistant" && typeof a.stopReason === "string";
|
|
3706
4242
|
});
|
|
3707
4243
|
this.emitRun(conv, lastAssistant?.stopReason ? { type: "run_end", stopReason: lastAssistant.stopReason } : { type: "run_end" });
|
|
4244
|
+
// 本轮已收尾:插件运行 token 到刺杀 —— 用户随后在同一对话里自己接着聊的
|
|
4245
|
+
// 那一轮不得再被当成插件驱动的(否则微信会回传网页端用户的轮次)。
|
|
4246
|
+
conv.pluginRunId = undefined;
|
|
4247
|
+
conv.pendingPluginRunId = undefined;
|
|
3708
4248
|
}
|
|
3709
4249
|
catch {
|
|
3710
4250
|
/* 轨迹尽力而为 */
|
|
@@ -3729,6 +4269,19 @@ export class ClientSession {
|
|
|
3729
4269
|
if (stopNotice) {
|
|
3730
4270
|
this.emit({ type: "notice", level: "warning", text: stopNotice.text, textEn: stopNotice.textEn });
|
|
3731
4271
|
}
|
|
4272
|
+
// 用户手动中止,重置自主轮次与空转计数(issue #726)
|
|
4273
|
+
conv.autonomousTurnsWithoutUser = 0;
|
|
4274
|
+
conv.consecutiveIdleWakeTurns = 0;
|
|
4275
|
+
conv.recentWakeSubagentIds = [];
|
|
4276
|
+
conv.wakeReason = undefined;
|
|
4277
|
+
conv.wakeTurnHadAction = undefined;
|
|
4278
|
+
if (conv.isSubagent &&
|
|
4279
|
+
conv.notifyOnDone !== false &&
|
|
4280
|
+
!conv.subagentDoneNotified &&
|
|
4281
|
+
!conv.subagentConsumedByParent &&
|
|
4282
|
+
conv.parentId) {
|
|
4283
|
+
this.scheduleSubagentCompletionNotice(conv);
|
|
4284
|
+
}
|
|
3732
4285
|
this.emitConversations();
|
|
3733
4286
|
break;
|
|
3734
4287
|
}
|
|
@@ -3757,6 +4310,26 @@ export class ClientSession {
|
|
|
3757
4310
|
// 或「等对话空闲」上,而 onAgentEnd 随后会把它需要的 verdict 交回。
|
|
3758
4311
|
this.notifyTurnEnd(conv);
|
|
3759
4312
|
this.goalSvc.onAgentEnd(conv, false);
|
|
4313
|
+
// issue #726:若本轮是由子代理唤醒触发,核算是否为空转
|
|
4314
|
+
if (conv.wakeReason === "subagent_completion") {
|
|
4315
|
+
if (conv.wakeTurnHadAction) {
|
|
4316
|
+
conv.consecutiveIdleWakeTurns = 0;
|
|
4317
|
+
}
|
|
4318
|
+
else {
|
|
4319
|
+
conv.consecutiveIdleWakeTurns = (conv.consecutiveIdleWakeTurns ?? 0) + 1;
|
|
4320
|
+
}
|
|
4321
|
+
conv.wakeReason = undefined;
|
|
4322
|
+
conv.wakeTurnHadAction = undefined;
|
|
4323
|
+
}
|
|
4324
|
+
// issue #713:子代理终态(非可重试瞬时错)时,安排向父对话自动发送完成通知
|
|
4325
|
+
if (conv.isSubagent &&
|
|
4326
|
+
!event.willRetry &&
|
|
4327
|
+
conv.notifyOnDone !== false &&
|
|
4328
|
+
!conv.subagentDoneNotified &&
|
|
4329
|
+
!conv.subagentConsumedByParent &&
|
|
4330
|
+
conv.parentId) {
|
|
4331
|
+
this.scheduleSubagentCompletionNotice(conv);
|
|
4332
|
+
}
|
|
3760
4333
|
// Deferred settings reload: settings (system prompt / skills /
|
|
3761
4334
|
// extensions) changed while the run was streaming — applying now
|
|
3762
4335
|
// would have torn down the in-flight run.
|
|
@@ -3799,10 +4372,19 @@ export class ClientSession {
|
|
|
3799
4372
|
}
|
|
3800
4373
|
}, 50);
|
|
3801
4374
|
}
|
|
4375
|
+
else if (!event.willRetry && !aborted && !this.disposed) {
|
|
4376
|
+
// 软上限主动压缩:回合结算后若上下文已达阈值,异步触发压缩(issue #716)
|
|
4377
|
+
setTimeout(() => {
|
|
4378
|
+
if (!this.disposed) {
|
|
4379
|
+
void this.triggerSoftCapCompactionIfExceeded(conv);
|
|
4380
|
+
}
|
|
4381
|
+
}, 50);
|
|
4382
|
+
}
|
|
3802
4383
|
// 本轮真正结束且不再重试:立即向客户端广播最新会话状态(流式状态及时复位)
|
|
3803
4384
|
if (!event.willRetry) {
|
|
3804
4385
|
if (conv.queueSteering.length === 0 && conv.queueFollowUp.length === 0) {
|
|
3805
|
-
conv.
|
|
4386
|
+
conv.queuedSteeringEntries = [];
|
|
4387
|
+
conv.queuedFollowUpEntries = [];
|
|
3806
4388
|
if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
|
|
3807
4389
|
conv.session._pendingNextTurnMessages = [];
|
|
3808
4390
|
}
|
|
@@ -3879,6 +4461,11 @@ export class ClientSession {
|
|
|
3879
4461
|
case "agent_start": {
|
|
3880
4462
|
// 本轮已正式进入流式(session.isStreaming=true),清除首轮启动期投递标记(#589)。
|
|
3881
4463
|
conv.promptInFlight = false;
|
|
4464
|
+
// 插件投递的待认领 token 在本轮真的开跑时转正(未开跑的不认领,避免污染下一轮)。
|
|
4465
|
+
if (conv.pendingPluginRunId) {
|
|
4466
|
+
conv.pluginRunId = conv.pendingPluginRunId;
|
|
4467
|
+
conv.pendingPluginRunId = undefined;
|
|
4468
|
+
}
|
|
3882
4469
|
// 轨迹事件:新一轮开始(任务文本由 prompt() 暂存;steer/内部续跑
|
|
3883
4470
|
// 无暂存时省略,插件回退为「继续执行」)。
|
|
3884
4471
|
const task = conv.pendingTask;
|
|
@@ -4161,53 +4748,17 @@ export class ClientSession {
|
|
|
4161
4748
|
cost: s.cost,
|
|
4162
4749
|
contextUsage: (() => {
|
|
4163
4750
|
const cu = s.contextUsage;
|
|
4164
|
-
if (!cu)
|
|
4751
|
+
if (!cu || cu.contextWindow <= 0)
|
|
4165
4752
|
return stats.contextUsage;
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
|
|
4170
|
-
contextWindow: cu.contextWindow,
|
|
4171
|
-
percent: (conv.lastCompactionTokens / cu.contextWindow) * 100,
|
|
4172
|
-
estimated: false,
|
|
4173
|
-
softCap: this.activeSoftCap(cu.contextWindow),
|
|
4174
|
-
};
|
|
4175
|
-
}
|
|
4176
|
-
// 展示用兜底 0(会话未就绪时旧行为也是 0);落账 lastTurnBaseTokens 的路径
|
|
4177
|
-
// 在 agent_settled 处对 null 跳过,不受此兜底影响。
|
|
4178
|
-
const baseTokens = this.currentBaseTokens(conv) ?? 0;
|
|
4179
|
-
// 空白会话(尚未发言,SDK 报 0 或 null):真实反映当前模式/工具配置下的 Base 开销。
|
|
4180
|
-
if (cu.contextWindow > 0 && (this.isBlankConversation(conv) || cu.tokens == null || cu.tokens === 0)) {
|
|
4181
|
-
return {
|
|
4182
|
-
tokens: baseTokens,
|
|
4183
|
-
contextWindow: cu.contextWindow,
|
|
4184
|
-
percent: (baseTokens / cu.contextWindow) * 100,
|
|
4185
|
-
estimated: false,
|
|
4186
|
-
softCap: this.activeSoftCap(cu.contextWindow),
|
|
4187
|
-
};
|
|
4188
|
-
}
|
|
4189
|
-
// 首轮对话中(或尚未获得带有效 usage 的定稿助手消息):
|
|
4190
|
-
// 叠加精准的 Base 开销与当前非系统消息(用户输入、流式生成等)估算,
|
|
4191
|
-
// 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致突增翻倍(如 10k 变成 17k)。
|
|
4192
|
-
if ((conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) && cu.contextWindow > 0) {
|
|
4193
|
-
const nonSystemTokens = this.estimateNonSystemTokens(conv);
|
|
4194
|
-
const total = baseTokens + nonSystemTokens;
|
|
4195
|
-
return {
|
|
4196
|
-
tokens: total,
|
|
4197
|
-
contextWindow: cu.contextWindow,
|
|
4198
|
-
percent: (total / cu.contextWindow) * 100,
|
|
4199
|
-
estimated: true,
|
|
4200
|
-
softCap: this.activeSoftCap(cu.contextWindow),
|
|
4201
|
-
};
|
|
4202
|
-
}
|
|
4203
|
-
// 已有多轮对话历史:若在对话间歇切预设或开关工具,叠加当前 Base 开销相比上一轮定稿时的差额
|
|
4204
|
-
const baseDelta = baseTokens - (conv.lastTurnBaseTokens ?? baseTokens);
|
|
4205
|
-
const effectiveTokens = Math.max(0, (cu.tokens ?? 0) + baseDelta);
|
|
4753
|
+
const effectiveTokens = this.getEffectiveContextTokens(conv);
|
|
4754
|
+
const isEstimated = cu.tokens != null &&
|
|
4755
|
+
(conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) &&
|
|
4756
|
+
!this.isBlankConversation(conv);
|
|
4206
4757
|
return {
|
|
4207
4758
|
tokens: effectiveTokens,
|
|
4208
4759
|
contextWindow: cu.contextWindow,
|
|
4209
|
-
percent:
|
|
4210
|
-
estimated:
|
|
4760
|
+
percent: (effectiveTokens / cu.contextWindow) * 100,
|
|
4761
|
+
estimated: isEstimated,
|
|
4211
4762
|
softCap: this.activeSoftCap(cu.contextWindow),
|
|
4212
4763
|
};
|
|
4213
4764
|
})(),
|
|
@@ -4257,7 +4808,14 @@ export class ClientSession {
|
|
|
4257
4808
|
// Only the levels the current model actually supports — the SDK clamps
|
|
4258
4809
|
// anything else, so the UI must not offer (or must disable) the rest.
|
|
4259
4810
|
availableThinkingLevels: this.session.getAvailableThinkingLevels(),
|
|
4260
|
-
queue: {
|
|
4811
|
+
queue: {
|
|
4812
|
+
steering: conv.queueSteering,
|
|
4813
|
+
followUp: conv.queueFollowUp,
|
|
4814
|
+
entries: {
|
|
4815
|
+
steering: toQueuedPromptItems(conv.queuedSteeringEntries ?? []),
|
|
4816
|
+
followUp: toQueuedPromptItems(conv.queuedFollowUpEntries ?? []),
|
|
4817
|
+
},
|
|
4818
|
+
},
|
|
4261
4819
|
errorMessage: state.errorMessage,
|
|
4262
4820
|
retry: conv.retryState ?? null,
|
|
4263
4821
|
compaction: conv.compactionState ?? null,
|
|
@@ -4487,10 +5045,9 @@ export class ClientSession {
|
|
|
4487
5045
|
if (p.conversationId === undefined || p.conversationId === conversationId)
|
|
4488
5046
|
return true;
|
|
4489
5047
|
}
|
|
4490
|
-
|
|
4491
|
-
|
|
4492
|
-
|
|
4493
|
-
}
|
|
5048
|
+
const conv = this.convs.get(conversationId);
|
|
5049
|
+
if (conv?.pendingApprovals && conv.pendingApprovals.size > 0)
|
|
5050
|
+
return true;
|
|
4494
5051
|
return false;
|
|
4495
5052
|
}
|
|
4496
5053
|
/** 标准引擎的 question_answer 路由入口(index.ts 经 cs.answerQuestion?. 转发)。
|
|
@@ -4549,9 +5106,25 @@ export class ClientSession {
|
|
|
4549
5106
|
return;
|
|
4550
5107
|
}
|
|
4551
5108
|
const id = `appr-${++this.approvalSeq}`;
|
|
4552
|
-
const
|
|
4553
|
-
const
|
|
5109
|
+
const targetConv = conversationId ? this.convs.get(conversationId) : this.conv;
|
|
5110
|
+
const resolvedConvId = conversationId ?? targetConv?.id ?? this.activeId;
|
|
5111
|
+
const conv = (resolvedConvId ? this.convs.get(resolvedConvId) : undefined) ?? targetConv;
|
|
5112
|
+
const suppression = approvalSuppressionReason(conv?.approvalPolicy, this.settingsSvc.current.toolApprovalEnabled !== false, category?.id, toolName, params);
|
|
4554
5113
|
if (suppression) {
|
|
5114
|
+
// 记录静默放行审计日志(Issue #722)
|
|
5115
|
+
this.auditLogger.record({
|
|
5116
|
+
conversationId: resolvedConvId,
|
|
5117
|
+
toolName,
|
|
5118
|
+
params,
|
|
5119
|
+
decision: "approved",
|
|
5120
|
+
decisionSource: suppression === "disabled"
|
|
5121
|
+
? "suppressed_disabled"
|
|
5122
|
+
: suppression === "allow-all"
|
|
5123
|
+
? "suppressed_all"
|
|
5124
|
+
: "suppressed_category",
|
|
5125
|
+
categoryId: category?.id,
|
|
5126
|
+
reason,
|
|
5127
|
+
});
|
|
4555
5128
|
// 放行但不弹窗:不记 pending,不发消息,模型继续跑。
|
|
4556
5129
|
resolve({ decision: "approve" });
|
|
4557
5130
|
return;
|
|
@@ -4566,6 +5139,10 @@ export class ClientSession {
|
|
|
4566
5139
|
}
|
|
4567
5140
|
}
|
|
4568
5141
|
}
|
|
5142
|
+
if (!conv) {
|
|
5143
|
+
resolve({ decision: "deny", reason: "目标对话不存在" });
|
|
5144
|
+
return;
|
|
5145
|
+
}
|
|
4569
5146
|
const entry = {
|
|
4570
5147
|
id,
|
|
4571
5148
|
toolCallId,
|
|
@@ -4576,12 +5153,12 @@ export class ClientSession {
|
|
|
4576
5153
|
...(category ? { category } : {}),
|
|
4577
5154
|
...(hits && hits.length > 0 ? { hits } : {}),
|
|
4578
5155
|
...(parentTool ? { parentTool } : {}),
|
|
4579
|
-
conversationId,
|
|
5156
|
+
conversationId: conv.id,
|
|
4580
5157
|
conversationTitle,
|
|
4581
5158
|
resolve,
|
|
4582
5159
|
createdAt: Date.now(),
|
|
4583
5160
|
};
|
|
4584
|
-
this.
|
|
5161
|
+
this.ensurePendingApprovals(conv).set(id, entry);
|
|
4585
5162
|
this.emit({
|
|
4586
5163
|
type: "tool_approval_pending",
|
|
4587
5164
|
id,
|
|
@@ -4593,7 +5170,7 @@ export class ClientSession {
|
|
|
4593
5170
|
...(category ? { category } : {}),
|
|
4594
5171
|
...(hits && hits.length > 0 ? { hits } : {}),
|
|
4595
5172
|
...(parentTool ? { parentTool } : {}),
|
|
4596
|
-
|
|
5173
|
+
conversationId: conv.id,
|
|
4597
5174
|
...(conversationTitle ? { conversationTitle } : {}),
|
|
4598
5175
|
});
|
|
4599
5176
|
this.flushSnapshot();
|
|
@@ -4607,21 +5184,48 @@ export class ClientSession {
|
|
|
4607
5184
|
* 「全部允许」却还有几张弹窗挂着等点),并推一次设置面板(撤销区)。
|
|
4608
5185
|
*/
|
|
4609
5186
|
resolveToolApproval(id, decision, editedParams, reason, scope) {
|
|
4610
|
-
|
|
4611
|
-
if (!
|
|
5187
|
+
let found = typeof this.findPendingApproval === "function" ? this.findPendingApproval(id) : undefined;
|
|
5188
|
+
if (!found) {
|
|
5189
|
+
// 兼容单测 mock 或旧结构中直接挂在 cs.pendingApprovals 上的对象
|
|
5190
|
+
const legacyPending = this.pendingApprovals?.get?.(id);
|
|
5191
|
+
if (legacyPending) {
|
|
5192
|
+
const convId = legacyPending.conversationId ?? this.activeId;
|
|
5193
|
+
const conv = convId ? this.convs.get(convId) : undefined;
|
|
5194
|
+
if (conv)
|
|
5195
|
+
found = { conv, entry: legacyPending };
|
|
5196
|
+
}
|
|
5197
|
+
}
|
|
5198
|
+
if (!found)
|
|
4612
5199
|
return false;
|
|
4613
|
-
const
|
|
4614
|
-
const
|
|
4615
|
-
|
|
5200
|
+
const { conv, entry: pending } = found;
|
|
5201
|
+
const convId = conv.id;
|
|
5202
|
+
conv.pendingApprovals?.delete(id);
|
|
5203
|
+
this.pendingApprovals?.delete?.(id);
|
|
5204
|
+
// 记录用户主动决策审计日志(Issue #722)
|
|
5205
|
+
this.auditLogger.record({
|
|
5206
|
+
conversationId: convId,
|
|
5207
|
+
toolName: pending.toolName,
|
|
5208
|
+
params: decision === "edit" ? editedParams : pending.params,
|
|
5209
|
+
decision: decision === "approve" ? "approved" : decision === "edit" ? "edited" : "denied",
|
|
5210
|
+
decisionSource: "user_dialog",
|
|
5211
|
+
scope: decision === "approve" ? scope : undefined,
|
|
5212
|
+
userEdited: decision === "edit",
|
|
5213
|
+
categoryId: pending.category?.id,
|
|
5214
|
+
reason: decision === "deny" ? reason : pending.reason,
|
|
5215
|
+
});
|
|
5216
|
+
// 用户主动审批(批准/编辑/拒绝)代表人类介入,重置自主轮次与空转计数(issue #726)
|
|
5217
|
+
conv.autonomousTurnsWithoutUser = 0;
|
|
5218
|
+
conv.consecutiveIdleWakeTurns = 0;
|
|
5219
|
+
conv.recentWakeSubagentIds = [];
|
|
4616
5220
|
pending.resolve({ decision, editedParams, reason });
|
|
4617
5221
|
this.emit({ type: "tool_approval_resolved", id });
|
|
4618
|
-
if (decision === "approve" && scope && scope !== "once"
|
|
5222
|
+
if (decision === "approve" && scope && scope !== "once") {
|
|
4619
5223
|
const policy = this.ensureApprovalPolicy(conv);
|
|
4620
5224
|
if (scope === "all")
|
|
4621
5225
|
policy.allowAll = true;
|
|
4622
5226
|
else if (pending.category)
|
|
4623
5227
|
policy.categories.set(pending.category.id, pending.category);
|
|
4624
|
-
this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(
|
|
5228
|
+
this.emitApprovalPolicyNotice(scope, pending.category, this.approveCoveredPending(conv, policy));
|
|
4625
5229
|
this.settingsSvc.push();
|
|
4626
5230
|
}
|
|
4627
5231
|
this.flushSnapshot();
|
|
@@ -4634,15 +5238,24 @@ export class ClientSession {
|
|
|
4634
5238
|
return conv.approvalPolicy;
|
|
4635
5239
|
}
|
|
4636
5240
|
/** 把某对话里已被策略覆盖的其它待审批项一并放行,返回放行条数。 */
|
|
4637
|
-
approveCoveredPending(
|
|
5241
|
+
approveCoveredPending(conv, policy) {
|
|
4638
5242
|
let n = 0;
|
|
5243
|
+
if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
|
|
5244
|
+
return 0;
|
|
4639
5245
|
// eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
|
|
4640
|
-
for (const [oid, o] of [...
|
|
4641
|
-
if ((o.
|
|
4642
|
-
continue;
|
|
4643
|
-
if (!approvalSuppressionReason(policy, true, o.category?.id))
|
|
5246
|
+
for (const [oid, o] of [...conv.pendingApprovals]) {
|
|
5247
|
+
if (!approvalSuppressionReason(policy, true, o.category?.id, o.toolName, o.params))
|
|
4644
5248
|
continue;
|
|
4645
|
-
|
|
5249
|
+
conv.pendingApprovals.delete(oid);
|
|
5250
|
+
this.auditLogger.record({
|
|
5251
|
+
conversationId: conv.id,
|
|
5252
|
+
toolName: o.toolName,
|
|
5253
|
+
params: o.params,
|
|
5254
|
+
decision: "approved",
|
|
5255
|
+
decisionSource: "batch_approved_policy",
|
|
5256
|
+
categoryId: o.category?.id,
|
|
5257
|
+
reason: o.reason,
|
|
5258
|
+
});
|
|
4646
5259
|
o.resolve({ decision: "approve" });
|
|
4647
5260
|
this.emit({ type: "tool_approval_resolved", id: oid });
|
|
4648
5261
|
n++;
|
|
@@ -4673,23 +5286,36 @@ export class ClientSession {
|
|
|
4673
5286
|
}
|
|
4674
5287
|
/** 全局审批开关被关掉时:挂着的待审批全部按批准放行(否则弹窗还在等人点)。 */
|
|
4675
5288
|
autoApprovePendingApprovals(reasonZh, reasonEn) {
|
|
4676
|
-
if (this.pendingApprovals.size === 0)
|
|
4677
|
-
return;
|
|
4678
5289
|
let n = 0;
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
5290
|
+
for (const conv of this.convs.values()) {
|
|
5291
|
+
if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
|
|
5292
|
+
continue;
|
|
5293
|
+
// eslint-disable-next-line unicorn/no-useless-spread -- 快照:循环里会从 map 删项(迭代中改集合)
|
|
5294
|
+
for (const [oid, o] of [...conv.pendingApprovals]) {
|
|
5295
|
+
conv.pendingApprovals.delete(oid);
|
|
5296
|
+
this.auditLogger.record({
|
|
5297
|
+
conversationId: o.conversationId,
|
|
5298
|
+
toolName: o.toolName,
|
|
5299
|
+
params: o.params,
|
|
5300
|
+
decision: "approved",
|
|
5301
|
+
decisionSource: "batch_approved_disabled",
|
|
5302
|
+
categoryId: o.category?.id,
|
|
5303
|
+
reason: o.reason,
|
|
5304
|
+
});
|
|
5305
|
+
o.resolve({ decision: "approve" });
|
|
5306
|
+
this.emit({ type: "tool_approval_resolved", id: oid });
|
|
5307
|
+
n++;
|
|
5308
|
+
}
|
|
5309
|
+
}
|
|
5310
|
+
if (n > 0) {
|
|
5311
|
+
this.emit({
|
|
5312
|
+
type: "notice",
|
|
5313
|
+
level: "info",
|
|
5314
|
+
text: `${reasonZh},已自动放行 ${n} 项待审批。`,
|
|
5315
|
+
textEn: `${reasonEn} — auto-approved ${n} pending request(s).`,
|
|
5316
|
+
});
|
|
5317
|
+
this.flushSnapshot();
|
|
4685
5318
|
}
|
|
4686
|
-
this.emit({
|
|
4687
|
-
type: "notice",
|
|
4688
|
-
level: "info",
|
|
4689
|
-
text: `${reasonZh},已自动放行 ${n} 项待审批。`,
|
|
4690
|
-
textEn: `${reasonEn} — auto-approved ${n} pending request(s).`,
|
|
4691
|
-
});
|
|
4692
|
-
this.flushSnapshot();
|
|
4693
5319
|
}
|
|
4694
5320
|
/**
|
|
4695
5321
|
* 设置面板撤销区用:当前对话的审批策略(allowAll + 已记住的同类档位)。
|
|
@@ -4705,14 +5331,20 @@ export class ClientSession {
|
|
|
4705
5331
|
categories: policy ? [...policy.categories.values()] : [],
|
|
4706
5332
|
};
|
|
4707
5333
|
}
|
|
5334
|
+
/** 获取审批决策审计日志记录器(Issue #722)。 */
|
|
5335
|
+
getAuditLogger() {
|
|
5336
|
+
return this.auditLogger;
|
|
5337
|
+
}
|
|
4708
5338
|
/**
|
|
4709
5339
|
* 设置某对话的审批策略(设置面板撤销用)。只应用给出的字段:allowAll 直接赋值;
|
|
4710
5340
|
* categories 给出时作为保留名单整体替换(空数组 = 清掉全部同类记忆)。
|
|
4711
5341
|
*/
|
|
4712
5342
|
setApprovalPolicy(partial) {
|
|
4713
5343
|
const convId = partial.conversationId ?? this.activeId;
|
|
5344
|
+
if (!convId)
|
|
5345
|
+
return;
|
|
4714
5346
|
const conv = this.convs.get(convId);
|
|
4715
|
-
if (!conv)
|
|
5347
|
+
if (!conv || conv.isSubagent)
|
|
4716
5348
|
return;
|
|
4717
5349
|
const cur = conv.approvalPolicy;
|
|
4718
5350
|
const next = {
|
|
@@ -4731,9 +5363,10 @@ export class ClientSession {
|
|
|
4731
5363
|
this.flushSnapshot();
|
|
4732
5364
|
}
|
|
4733
5365
|
pendingApprovalForSnapshot() {
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
5366
|
+
const conv = this.conv;
|
|
5367
|
+
if (!conv?.pendingApprovals || conv.pendingApprovals.size === 0)
|
|
5368
|
+
return null;
|
|
5369
|
+
for (const [id, p] of conv.pendingApprovals) {
|
|
4737
5370
|
return {
|
|
4738
5371
|
id,
|
|
4739
5372
|
toolCallId: p.toolCallId,
|
|
@@ -4874,31 +5507,48 @@ export class ClientSession {
|
|
|
4874
5507
|
// 单个结算异常不影响其余清理
|
|
4875
5508
|
}
|
|
4876
5509
|
}
|
|
4877
|
-
|
|
4878
|
-
|
|
5510
|
+
const conv = this.convs.get(convId);
|
|
5511
|
+
if (conv?.pendingApprovals && conv.pendingApprovals.size > 0) {
|
|
5512
|
+
for (const [id, a] of conv.pendingApprovals) {
|
|
5513
|
+
try {
|
|
5514
|
+
a.resolve({ decision: "deny", reason: "运行已停止" });
|
|
5515
|
+
}
|
|
5516
|
+
catch {
|
|
5517
|
+
// 单个结算异常不影响其余清理
|
|
5518
|
+
}
|
|
5519
|
+
this.emit({ type: "tool_approval_resolved", id });
|
|
5520
|
+
}
|
|
5521
|
+
conv.pendingApprovals.clear();
|
|
5522
|
+
}
|
|
5523
|
+
for (const [id, p] of this.pendingPageCalls) {
|
|
5524
|
+
if (p.conversationId !== convId)
|
|
4879
5525
|
continue;
|
|
4880
|
-
this.
|
|
5526
|
+
this.pendingPageCalls.delete(id);
|
|
5527
|
+
clearTimeout(p.timer);
|
|
4881
5528
|
try {
|
|
4882
|
-
|
|
5529
|
+
p.resolve({ ok: false, error: "会话已重置或停止,挂起中的页面调用已取消。" });
|
|
4883
5530
|
}
|
|
4884
5531
|
catch {
|
|
4885
5532
|
// 单个结算异常不影响其余清理
|
|
4886
5533
|
}
|
|
4887
|
-
this.emit({ type: "tool_approval_resolved", id });
|
|
4888
5534
|
}
|
|
4889
5535
|
}
|
|
4890
5536
|
/** 关闭所有挂起审批(dispose 时清理):以「拒绝」解析,避免等答复的
|
|
4891
5537
|
* Promise 与对应 runtime 泄漏(会话没了,审批弹窗永远不会有人点)。 */
|
|
4892
5538
|
cancelPendingApprovals() {
|
|
4893
|
-
for (const
|
|
4894
|
-
|
|
4895
|
-
|
|
4896
|
-
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
|
|
5539
|
+
for (const conv of this.convs.values()) {
|
|
5540
|
+
if (!conv.pendingApprovals || conv.pendingApprovals.size === 0)
|
|
5541
|
+
continue;
|
|
5542
|
+
for (const [id, a] of conv.pendingApprovals) {
|
|
5543
|
+
try {
|
|
5544
|
+
a.resolve({ decision: "deny", reason: "会话已关闭" });
|
|
5545
|
+
}
|
|
5546
|
+
catch {
|
|
5547
|
+
// 单个 resolve 异常不影响其余清理
|
|
5548
|
+
}
|
|
5549
|
+
this.emit({ type: "tool_approval_resolved", id });
|
|
4900
5550
|
}
|
|
4901
|
-
|
|
5551
|
+
conv.pendingApprovals.clear();
|
|
4902
5552
|
}
|
|
4903
5553
|
}
|
|
4904
5554
|
// -----------------------------------------------------------------------
|
|
@@ -5588,11 +6238,8 @@ export class ClientSession {
|
|
|
5588
6238
|
setPlanMode: (enabled) => this.setPlanMode(enabled),
|
|
5589
6239
|
getPlanMode: () => this.conv?.planMode === true,
|
|
5590
6240
|
afterReload: () => {
|
|
5591
|
-
// /reload 同样重读磁盘 settings.json
|
|
5592
|
-
this.
|
|
5593
|
-
this.applyCompactionOverrides();
|
|
5594
|
-
this.applyCodemodeOverrides();
|
|
5595
|
-
this.applyToolGating(this.session, this.conv?.agentPreset);
|
|
6241
|
+
// /reload 同样重读磁盘 settings.json——统一收口重放配置覆盖与工具门控。
|
|
6242
|
+
this.applySessionOverrides(this.conv);
|
|
5596
6243
|
},
|
|
5597
6244
|
pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
|
|
5598
6245
|
execPluginCommand: async (name, args) => {
|
|
@@ -5920,7 +6567,7 @@ export class ClientSession {
|
|
|
5920
6567
|
}
|
|
5921
6568
|
return;
|
|
5922
6569
|
}
|
|
5923
|
-
await this.session
|
|
6570
|
+
await this.applySessionModel(this.session, model);
|
|
5924
6571
|
}
|
|
5925
6572
|
catch {
|
|
5926
6573
|
// model no longer resolvable / key gone — keep the conversation default
|
|
@@ -5935,6 +6582,26 @@ export class ClientSession {
|
|
|
5935
6582
|
pushSettings() {
|
|
5936
6583
|
this.settingsSvc.push();
|
|
5937
6584
|
}
|
|
6585
|
+
/**
|
|
6586
|
+
* 统一会话配置与门控收口方法(单一事实源)。
|
|
6587
|
+
* 无论是新建、切换、回滚、编辑重问、看门狗重置还是设置变更:
|
|
6588
|
+
* 统一应用重试次数、压缩保留值(按会话自己的模型与软上限重算)、codemode 预算以及工具门控(含 planMode/delegateMode/禁用名单/权限预设)。
|
|
6589
|
+
* 彻底杜绝各业务入口散落调用与遗漏。
|
|
6590
|
+
*/
|
|
6591
|
+
applySessionOverrides(target) {
|
|
6592
|
+
const conv = target ?? this.conv;
|
|
6593
|
+
if (!conv?.session)
|
|
6594
|
+
return;
|
|
6595
|
+
try {
|
|
6596
|
+
this.applyRetryOverrides();
|
|
6597
|
+
this.applyCompactionOverrides();
|
|
6598
|
+
this.applyCodemodeOverrides();
|
|
6599
|
+
this.applyToolGating(conv.session, conv.agentPreset);
|
|
6600
|
+
}
|
|
6601
|
+
catch {
|
|
6602
|
+
// 会话未就绪或已释放
|
|
6603
|
+
}
|
|
6604
|
+
}
|
|
5938
6605
|
/** 把设置面板的出错重试次数注入全部存活会话的 SDK SettingsManager。
|
|
5939
6606
|
* applyOverrides 只改内存合并视图(不碰 ~/.pi/agent/settings.json),
|
|
5940
6607
|
* 且 SDK 每次退避前都重读 getRetrySettings()——即时生效、无需 reload。
|
|
@@ -5951,35 +6618,58 @@ export class ClientSession {
|
|
|
5951
6618
|
}
|
|
5952
6619
|
}
|
|
5953
6620
|
}
|
|
5954
|
-
/**
|
|
5955
|
-
*
|
|
5956
|
-
*
|
|
5957
|
-
*
|
|
5958
|
-
*
|
|
5959
|
-
*
|
|
5960
|
-
*
|
|
5961
|
-
*
|
|
6621
|
+
/** 逐会话重算 SDK compaction reserveTokens(issue #229 → #716 → #773)。
|
|
6622
|
+
* 软上限双层管控:
|
|
6623
|
+
* - 回合内层:reserve = max(默认 16384, cw - cap)。SDK 在每次工具调用间隙的
|
|
6624
|
+
* _compactBeforeNextAssistantResponse 就会在 cap 处压缩——自治长跑(子代理、
|
|
6625
|
+
* 单回合几十次工具调用)全程没有空闲态,只有这一层拦得住(issue #773)。
|
|
6626
|
+
* - 空闲态层:triggerSoftCapCompactionIfExceeded,负责 reserve 管不到的场景
|
|
6627
|
+
* (cap 中途下调 / 附件注入超阈 / 从磁盘恢复的已超阈会话)。
|
|
6628
|
+
*
|
|
6629
|
+
* #716 当初把 reserve 锁死在默认值,怕的是「换模型残留上一模型的 W - C」。
|
|
6630
|
+
* 所以这里必须用**每个会话自己的活模型**算,且每次都完整重算、不累加——
|
|
6631
|
+
* 残留状态不存在,泄漏也就无从发生(换模型一律走 applySessionModel,其他重算点:
|
|
6632
|
+
* 新建/切换、设置变更、reload、AI 主动压缩后,见 applySessionOverrides 等)。
|
|
6633
|
+
* cap 关闭/非法/压不下来时回落默认 16384 = 原样的物理兜底线。 */
|
|
5962
6634
|
applyCompactionOverrides() {
|
|
5963
6635
|
const s = this.settingsSvc.current;
|
|
5964
6636
|
for (const c of this.convs.values()) {
|
|
6637
|
+
let reserve = DEFAULT_COMPACTION_RESERVE_TOKENS;
|
|
6638
|
+
try {
|
|
6639
|
+
const cw = contextWindowOf(c.session);
|
|
6640
|
+
if (cw > 0) {
|
|
6641
|
+
const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(c.session));
|
|
6642
|
+
// keepRecentTokens 读活值:用户可在 settings.json 覆盖,压缩尾部就按它留。
|
|
6643
|
+
let keepRecent = 0;
|
|
6644
|
+
try {
|
|
6645
|
+
keepRecent = c.session.settingsManager.getCompactionKeepRecentTokens(c.session.model) ?? 0;
|
|
6646
|
+
}
|
|
6647
|
+
catch {
|
|
6648
|
+
keepRecent = 0;
|
|
6649
|
+
}
|
|
6650
|
+
reserve = softCapReserveFor(cw, cap, keepRecent) ?? DEFAULT_COMPACTION_RESERVE_TOKENS;
|
|
6651
|
+
}
|
|
6652
|
+
}
|
|
6653
|
+
catch {
|
|
6654
|
+
// 会话未就绪/已释放 → 只回默认值,不连累其他会话。
|
|
6655
|
+
}
|
|
5965
6656
|
try {
|
|
5966
|
-
|
|
6657
|
+
c.session.settingsManager.applyOverrides({ compaction: { reserveTokens: reserve } });
|
|
5967
6658
|
}
|
|
5968
6659
|
catch {
|
|
5969
6660
|
// 会话未就绪或已释放 → 其 runtime 创建时统一注入。
|
|
5970
6661
|
}
|
|
5971
6662
|
}
|
|
5972
6663
|
}
|
|
5973
|
-
/**
|
|
5974
|
-
*
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
});
|
|
6664
|
+
/** 会话换模型的唯一入口(issue #716/#773):先把模型换上,立即按新模型的窗口
|
|
6665
|
+
* 重算该会话的 compaction reserveTokens。
|
|
6666
|
+
*
|
|
6667
|
+
* reserve 依赖会话**当前**模型(cw - cap),任何绕过此处的裸 session.setModel()
|
|
6668
|
+
* 都会让判定线卡在上一模型的 W - C 上(子代理因此在长回合里不压缩,issue #773)。
|
|
6669
|
+
* 新增换模型路径必须走这里,不要直接 setModel。 */
|
|
6670
|
+
async applySessionModel(session, model) {
|
|
6671
|
+
await session.setModel(model);
|
|
6672
|
+
this.applyCompactionOverrides();
|
|
5983
6673
|
}
|
|
5984
6674
|
/** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
|
|
5985
6675
|
applyCodemodeOverrides() {
|
|
@@ -5996,45 +6686,79 @@ export class ClientSession {
|
|
|
5996
6686
|
}
|
|
5997
6687
|
}
|
|
5998
6688
|
}
|
|
5999
|
-
/**
|
|
6000
|
-
|
|
6001
|
-
* 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
|
|
6002
|
-
* 模型(1M 窗口)算出 748576,泄漏到 500K 窗口的会话后压缩触发点
|
|
6003
|
-
* 变成负数,上下文几万 token 就被反复压缩。onEvent 比对模型 key 与窗口,
|
|
6004
|
-
* 有变化才重放。setModel 本身不发 session 事件,子代理创建路径另有同步重算。 */
|
|
6005
|
-
reapplySoftCapIfModelChanged(conv) {
|
|
6689
|
+
/** 计算指定会话当前的有效上下文 token 估算值(对齐底栏展示逻辑)。 */
|
|
6690
|
+
getEffectiveContextTokens(conv) {
|
|
6006
6691
|
try {
|
|
6007
|
-
const
|
|
6008
|
-
|
|
6009
|
-
|
|
6010
|
-
|
|
6011
|
-
conv.
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6692
|
+
const cu = conv.session?.getSessionStats()?.contextUsage;
|
|
6693
|
+
if (!cu || cu.contextWindow <= 0)
|
|
6694
|
+
return 0;
|
|
6695
|
+
// 压缩刚结束、下轮响应未到:SDK 报 null,用压缩结果回填约数。
|
|
6696
|
+
if (cu.tokens == null && conv.lastCompactionTokens != null) {
|
|
6697
|
+
return conv.lastCompactionTokens;
|
|
6698
|
+
}
|
|
6699
|
+
const baseTokens = this.currentBaseTokens(conv) ?? 0;
|
|
6700
|
+
if (this.isBlankConversation(conv) || cu.tokens == null || cu.tokens === 0) {
|
|
6701
|
+
return baseTokens;
|
|
6702
|
+
}
|
|
6703
|
+
if (conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) {
|
|
6704
|
+
const nonSystemTokens = this.estimateNonSystemTokens(conv);
|
|
6705
|
+
return baseTokens + nonSystemTokens;
|
|
6706
|
+
}
|
|
6707
|
+
const baseDelta = baseTokens - (conv.lastTurnBaseTokens ?? baseTokens);
|
|
6708
|
+
return Math.max(0, (cu.tokens ?? 0) + baseDelta);
|
|
6015
6709
|
}
|
|
6016
6710
|
catch {
|
|
6017
|
-
|
|
6711
|
+
return 0;
|
|
6018
6712
|
}
|
|
6019
6713
|
}
|
|
6020
|
-
/**
|
|
6021
|
-
*
|
|
6022
|
-
|
|
6714
|
+
/**
|
|
6715
|
+
* 若当前会话的有效 token 超过软上限,主动触发 SDK 上下文压缩(issue #716)。
|
|
6716
|
+
* 仅在空闲状态下触发(不会掐断进行中的任务)。
|
|
6717
|
+
* 返回是否触发了压缩。
|
|
6718
|
+
*/
|
|
6719
|
+
async triggerSoftCapCompactionIfExceeded(conv) {
|
|
6023
6720
|
try {
|
|
6024
|
-
|
|
6025
|
-
|
|
6026
|
-
|
|
6721
|
+
const session = conv.session;
|
|
6722
|
+
if (!session || session.isStreaming)
|
|
6723
|
+
return false;
|
|
6724
|
+
const contextWindow = contextWindowOf(session);
|
|
6725
|
+
// 用**本会话**的模型算按模型覆盖:子代理/后台对话的模型未必等于当前活动对话,
|
|
6726
|
+
// 串用会拿错 cap(issue #773)。
|
|
6727
|
+
const cap = this.activeSoftCap(contextWindow, session);
|
|
6728
|
+
if (!cap || cap <= 0)
|
|
6729
|
+
return false;
|
|
6730
|
+
const currentTokens = this.getEffectiveContextTokens(conv);
|
|
6731
|
+
if (currentTokens < cap)
|
|
6732
|
+
return false;
|
|
6733
|
+
await session.compact();
|
|
6734
|
+
return true;
|
|
6027
6735
|
}
|
|
6028
|
-
catch {
|
|
6029
|
-
|
|
6736
|
+
catch (err) {
|
|
6737
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
6738
|
+
// SDK 的边界报错:Already compacted 或 Nothing to compact 属于正常跳过
|
|
6739
|
+
if (msg.includes("Already compacted") || msg.includes("Nothing to compact")) {
|
|
6740
|
+
return false;
|
|
6741
|
+
}
|
|
6742
|
+
this.emit({
|
|
6743
|
+
type: "notice",
|
|
6744
|
+
level: "warning",
|
|
6745
|
+
text: `软上限上下文自动压缩未完成:${msg}`,
|
|
6746
|
+
textEn: `Soft cap context compaction did not complete: ${msg}`,
|
|
6747
|
+
});
|
|
6748
|
+
return false;
|
|
6030
6749
|
}
|
|
6031
6750
|
}
|
|
6032
|
-
/**
|
|
6033
|
-
|
|
6751
|
+
/** 生效软上限(快照底栏标记线用;null = 关闭/未知)。
|
|
6752
|
+
* session 缺省 = 当前活动会话;压缩触发方必须传自己那个会话来算按模型覆盖。 */
|
|
6753
|
+
activeSoftCap(contextWindow, session = this.session) {
|
|
6034
6754
|
try {
|
|
6035
6755
|
const s = this.settingsSvc.current;
|
|
6036
|
-
const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(
|
|
6037
|
-
|
|
6756
|
+
const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(session));
|
|
6757
|
+
if (!cap || cap < SOFT_CAP_MIN_TOKENS)
|
|
6758
|
+
return null;
|
|
6759
|
+
if (contextWindow > 0 && cap >= contextWindow - SOFT_CAP_MIN_HEADROOM)
|
|
6760
|
+
return null;
|
|
6761
|
+
return cap;
|
|
6038
6762
|
}
|
|
6039
6763
|
catch {
|
|
6040
6764
|
return null;
|
|
@@ -6078,9 +6802,7 @@ export class ClientSession {
|
|
|
6078
6802
|
if (!this.session.isStreaming) {
|
|
6079
6803
|
try {
|
|
6080
6804
|
await this.session.reload();
|
|
6081
|
-
this.
|
|
6082
|
-
this.applyCompactionOverrides();
|
|
6083
|
-
this.applyToolGating(this.session, this.conv?.agentPreset);
|
|
6805
|
+
this.applySessionOverrides(this.conv);
|
|
6084
6806
|
await this.pushSlashCommands();
|
|
6085
6807
|
this.pushSettings();
|
|
6086
6808
|
}
|
|
@@ -6446,8 +7168,25 @@ export class ClientSession {
|
|
|
6446
7168
|
error: res.error,
|
|
6447
7169
|
});
|
|
6448
7170
|
}
|
|
6449
|
-
/**
|
|
7171
|
+
/** 拉取单个技能的完整 SKILL.md 内容(支持本地已安装与远程仓库) */
|
|
6450
7172
|
async fetchSkillContent(repo, skillId) {
|
|
7173
|
+
if (repo === "local" || !repo) {
|
|
7174
|
+
const diskSkills = discoverDiskSkills({
|
|
7175
|
+
cwd: this.cwd,
|
|
7176
|
+
agentDir: this.agentDir,
|
|
7177
|
+
});
|
|
7178
|
+
const matched = diskSkills.find((s) => s.name.toLowerCase() === skillId.toLowerCase());
|
|
7179
|
+
if (matched) {
|
|
7180
|
+
const content = readSkillInstruction(matched.filePath);
|
|
7181
|
+
this.emit({
|
|
7182
|
+
type: "skill_content_result",
|
|
7183
|
+
ok: true,
|
|
7184
|
+
skillId,
|
|
7185
|
+
content,
|
|
7186
|
+
});
|
|
7187
|
+
return;
|
|
7188
|
+
}
|
|
7189
|
+
}
|
|
6451
7190
|
const res = await fetchRemoteSkillContent({
|
|
6452
7191
|
repo,
|
|
6453
7192
|
skillId,
|
|
@@ -6466,9 +7205,7 @@ export class ClientSession {
|
|
|
6466
7205
|
if (this.session && !this.session.isStreaming) {
|
|
6467
7206
|
try {
|
|
6468
7207
|
await this.session.reload();
|
|
6469
|
-
this.
|
|
6470
|
-
this.applyCompactionOverrides();
|
|
6471
|
-
this.applyToolGating(this.session, this.conv?.agentPreset);
|
|
7208
|
+
this.applySessionOverrides(this.conv);
|
|
6472
7209
|
await this.pushSlashCommands();
|
|
6473
7210
|
}
|
|
6474
7211
|
catch {
|
|
@@ -6495,11 +7232,11 @@ export class ClientSession {
|
|
|
6495
7232
|
return undefined;
|
|
6496
7233
|
}
|
|
6497
7234
|
/**
|
|
6498
|
-
* read / write / edit
|
|
6499
|
-
* (见 tool-overrides.ts ——
|
|
6500
|
-
* 同名工具,而官方 docs/extensions.md 明写扩展可覆盖 read/write/edit)。
|
|
7235
|
+
* bash / read / write / edit 四处覆盖的注入规格:基底 = 扩展注册的同名工具优先,否则 SDK 内置实现
|
|
7236
|
+
* (见 tool-overrides.ts —— 这四处覆盖不能塞进创建时的 `customTools`,那会静默顶掉扩展的
|
|
7237
|
+
* 同名工具,而官方 docs/extensions.md 明写扩展可覆盖 bash/read/write/edit,issue #750)。
|
|
6501
7238
|
*/
|
|
6502
|
-
toolOverrideSpecs(ownerId, cwd) {
|
|
7239
|
+
toolOverrideSpecs(ownerId, cwd, terminals) {
|
|
6503
7240
|
const currentPermission = () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
6504
7241
|
this.settingsSvc.current.defaultPermissionPreset ??
|
|
6505
7242
|
"workspace-write-never";
|
|
@@ -6518,15 +7255,78 @@ export class ClientSession {
|
|
|
6518
7255
|
getRoots: () => this.roots,
|
|
6519
7256
|
askApproval: approve,
|
|
6520
7257
|
getRules: () => this.approvalRules.list(),
|
|
7258
|
+
onAudit: (entry) => this.auditLogger.record(entry),
|
|
6521
7259
|
};
|
|
6522
|
-
//
|
|
7260
|
+
// 写/编/终端的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
|
|
6523
7261
|
// 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
|
|
6524
7262
|
// 快照并发门禁包裹在工具执行最前沿,确保写操作前快照必定已就绪。
|
|
6525
|
-
const planGate = (def) => withWorkspaceSnapshotGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () =>
|
|
7263
|
+
const planGate = (def) => withWorkspaceSnapshotGate(withSubagentSecurityGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => ({
|
|
7264
|
+
mode: this.subagentSecurityModeOf(ownerId),
|
|
7265
|
+
allowedTools: this.subagentAllowedToolsOf(ownerId),
|
|
7266
|
+
}), () => this.getLang()), () => this.awaitPendingWorkspaceSnapshot(ownerId));
|
|
6526
7267
|
const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
|
|
6527
7268
|
const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
|
|
7269
|
+
const composeBash = (base) => {
|
|
7270
|
+
let core;
|
|
7271
|
+
if (base) {
|
|
7272
|
+
// 扩展提供了同名 bash:以扩展定义为基底,保留其 schema/描述/guidelines,
|
|
7273
|
+
// 同时挂载 abort_bash 信号中断支持与 head/tail 输出后处理。
|
|
7274
|
+
core = {
|
|
7275
|
+
...base,
|
|
7276
|
+
execute: async (toolCallId, params, signal, onUpdate, ctx) => {
|
|
7277
|
+
const ac = new AbortController();
|
|
7278
|
+
this.bashKills.add(ac);
|
|
7279
|
+
try {
|
|
7280
|
+
const signals = [signal, ac.signal].filter((s) => s !== undefined);
|
|
7281
|
+
const combinedSignal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
|
7282
|
+
const result = (await base.execute(toolCallId, params, combinedSignal, onUpdate, ctx));
|
|
7283
|
+
const p = params;
|
|
7284
|
+
if ((p?.head || p?.tail) && result?.content?.[0]?.text != null) {
|
|
7285
|
+
result.content[0].text = applyHeadTail(result.content[0].text, p.head, p.tail, this.getLang());
|
|
7286
|
+
}
|
|
7287
|
+
return result;
|
|
7288
|
+
}
|
|
7289
|
+
finally {
|
|
7290
|
+
this.bashKills.delete(ac);
|
|
7291
|
+
}
|
|
7292
|
+
},
|
|
7293
|
+
};
|
|
7294
|
+
}
|
|
7295
|
+
else {
|
|
7296
|
+
// 没有扩展 bash:完整的原生与终端自适应分流 bash(行为与改动前逐字一致)。
|
|
7297
|
+
core = makeAdaptiveBashTool(makeKillableBashTool(cwd, this.bashKills, () => this.getLang()), terminals
|
|
7298
|
+
? makeTerminalBashTool(terminals, {
|
|
7299
|
+
cwd,
|
|
7300
|
+
defaultPersist: () => false,
|
|
7301
|
+
idleMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashIdleMs) || 0),
|
|
7302
|
+
maxForegroundMs: () => Math.max(0, Math.floor(this.settingsSvc.current.terminalBashMaxForegroundMs) || 0),
|
|
7303
|
+
kills: this.bashKills,
|
|
7304
|
+
notifyBackgroundDone: (info) => this.notifyTerminalBashDone(terminals, info),
|
|
7305
|
+
lang: () => this.getLang(),
|
|
7306
|
+
})
|
|
7307
|
+
: makeKillableBashTool(cwd, this.bashKills, () => this.getLang()), () => Boolean(terminals && this.settingsSvc.current.terminalBash));
|
|
7308
|
+
}
|
|
7309
|
+
const guarded = withToolGuard(withWorkspaceSnapshotGate(core, () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
|
|
7310
|
+
toolName: "bash",
|
|
7311
|
+
guard: this.lateToolGuard,
|
|
7312
|
+
conversationId: () => ownerId,
|
|
7313
|
+
getLang: () => this.getLang(),
|
|
7314
|
+
cwd,
|
|
7315
|
+
getRoots: () => this.roots,
|
|
7316
|
+
askApproval: approve,
|
|
7317
|
+
getRules: () => this.approvalRules.list(),
|
|
7318
|
+
onAudit: (entry) => this.auditLogger.record(entry),
|
|
7319
|
+
});
|
|
7320
|
+
const permissionWrapped = wrapBashToolWithPermission(guarded, currentPermission, () => this.getLang());
|
|
7321
|
+
return this.wrapGenericTool(permissionWrapped, ownerId, cwd);
|
|
7322
|
+
};
|
|
6528
7323
|
const remoteOps = createRemoteSdkOperations(cwd);
|
|
6529
7324
|
const specs = [
|
|
7325
|
+
{
|
|
7326
|
+
name: "bash",
|
|
7327
|
+
fallback: () => composeBash(),
|
|
7328
|
+
composeWith: (base) => composeBash(base),
|
|
7329
|
+
},
|
|
6530
7330
|
{
|
|
6531
7331
|
name: "read",
|
|
6532
7332
|
// 没有扩展 read:完整覆盖(内置基底 + 英文描述 + file_path 别名)。
|
|
@@ -6584,12 +7384,33 @@ export class ClientSession {
|
|
|
6584
7384
|
this.settingsSvc.current.defaultAgentPreset ??
|
|
6585
7385
|
"standard";
|
|
6586
7386
|
const isPlanMode = conv?.planMode === true;
|
|
7387
|
+
const isDelegateMode = conv?.delegateMode === true;
|
|
6587
7388
|
const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
|
|
6588
7389
|
if (isPlanMode) {
|
|
6589
7390
|
for (const toolName of PLAN_MODE_BLOCKED_TOOL_NAMES) {
|
|
6590
7391
|
disabled.add(toolName);
|
|
6591
7392
|
}
|
|
6592
7393
|
}
|
|
7394
|
+
else if (isDelegateMode) {
|
|
7395
|
+
for (const toolName of DELEGATE_MODE_BLOCKED_TOOL_NAMES) {
|
|
7396
|
+
disabled.add(toolName);
|
|
7397
|
+
}
|
|
7398
|
+
}
|
|
7399
|
+
if (conv?.subagentAllowedTools && conv.subagentAllowedTools.size > 0) {
|
|
7400
|
+
try {
|
|
7401
|
+
for (const t of session.getAllTools()) {
|
|
7402
|
+
if (!conv.subagentAllowedTools.has(t.name)) {
|
|
7403
|
+
disabled.add(t.name);
|
|
7404
|
+
}
|
|
7405
|
+
}
|
|
7406
|
+
}
|
|
7407
|
+
catch { }
|
|
7408
|
+
}
|
|
7409
|
+
if (conv?.subagentSecurityMode === "readonly" || conv?.subagentSecurityMode === "verify") {
|
|
7410
|
+
for (const toolName of SUBAGENT_WRITE_TOOL_NAMES) {
|
|
7411
|
+
disabled.add(toolName);
|
|
7412
|
+
}
|
|
7413
|
+
}
|
|
6593
7414
|
// 延迟加载(默认开):未加载的已登记工具一律当「临时禁用」——与用户禁用名单 /
|
|
6594
7415
|
// 计划模式闸门走同一条门控链,不做第二套机制。加载只是把名字从这份名单里拿出来。
|
|
6595
7416
|
let loadedNames = [];
|
|
@@ -6617,7 +7438,8 @@ export class ClientSession {
|
|
|
6617
7438
|
forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME, ...loadedNames] : [],
|
|
6618
7439
|
});
|
|
6619
7440
|
const ownerId = conv?.id;
|
|
6620
|
-
|
|
7441
|
+
const subagentOff = disabled.has("subagent") || SPAWN_TOOLS_BARRED.has(session);
|
|
7442
|
+
syncSubagentOverride(session, subagentOff, () => ownerId
|
|
6621
7443
|
? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined, ownerId)[0]
|
|
6622
7444
|
: makeSubagentTools(this.subagentHost)[0]);
|
|
6623
7445
|
this.syncPluginTools(session, targetPreset);
|
|
@@ -6775,6 +7597,16 @@ export class ClientSession {
|
|
|
6775
7597
|
const id = ownerId ?? this.activeId;
|
|
6776
7598
|
return this.convs.get(id)?.awaitingVerdict != null;
|
|
6777
7599
|
}
|
|
7600
|
+
/** 子代理安全规格模式("normal" | "readonly" | "verify",issue #727)。 */
|
|
7601
|
+
subagentSecurityModeOf(ownerId) {
|
|
7602
|
+
const id = ownerId ?? this.activeId;
|
|
7603
|
+
return this.convs.get(id)?.subagentSecurityMode ?? "normal";
|
|
7604
|
+
}
|
|
7605
|
+
/** 子代理显式允许的工具白名单集合(issue #727)。 */
|
|
7606
|
+
subagentAllowedToolsOf(ownerId) {
|
|
7607
|
+
const id = ownerId ?? this.activeId;
|
|
7608
|
+
return this.convs.get(id)?.subagentAllowedTools;
|
|
7609
|
+
}
|
|
6778
7610
|
/** 等待该会话正在并发生成的影子快照完成,确保写操作发生在快照完成之后。 */
|
|
6779
7611
|
async awaitPendingWorkspaceSnapshot(ownerId) {
|
|
6780
7612
|
const id = ownerId ?? this.activeId;
|
|
@@ -7113,6 +7945,32 @@ export class ClientSession {
|
|
|
7113
7945
|
this.refreshPermission();
|
|
7114
7946
|
this.flushSnapshot();
|
|
7115
7947
|
}
|
|
7948
|
+
/**
|
|
7949
|
+
* 统一工具安全流水线(Issue #722):
|
|
7950
|
+
* 将通用工具(包括插件 AI 工具、MCP 桥接工具、第一方辅助工具等)统一包裹:
|
|
7951
|
+
* 1. withApprovalGate:检查审批规则(checkDangerousToolCall)与人机协同审批;
|
|
7952
|
+
* 2. withSandboxJailGate:工作区沙箱越界拦截;
|
|
7953
|
+
* 3. withPlanModeGate:计划模式只读拦截;
|
|
7954
|
+
* 4. withDelegationGate:审查者委派拦截;
|
|
7955
|
+
* 5. withGoalReviewGate:目标审查回合拦截;
|
|
7956
|
+
* 6. withSubagentSecurityGate:子代理安全规格拦截(只读/审查/工具白名单,issue #727)。
|
|
7957
|
+
* 无论是会话创建时的静态 customTools 还是 syncPluginTools 动态注入的工具,均无差别经由此管道。
|
|
7958
|
+
*/
|
|
7959
|
+
wrapGenericTool(def, ownerId, cwdOverride) {
|
|
7960
|
+
const getEffectiveCwd = () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? cwdOverride ?? this.cwd;
|
|
7961
|
+
return withSubagentSecurityGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(withApprovalGate(def, {
|
|
7962
|
+
cwd: getEffectiveCwd,
|
|
7963
|
+
getRoots: () => this.roots,
|
|
7964
|
+
getRules: () => this.approvalRules.list(),
|
|
7965
|
+
getLang: () => this.getLang(),
|
|
7966
|
+
conversationId: () => ownerId,
|
|
7967
|
+
askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category, hits) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category, hits),
|
|
7968
|
+
onAudit: (entry) => this.auditLogger.record(entry),
|
|
7969
|
+
}), () => this.sandboxes.getByCwd(getEffectiveCwd()), getEffectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => ({
|
|
7970
|
+
mode: this.subagentSecurityModeOf(ownerId),
|
|
7971
|
+
allowedTools: this.subagentAllowedToolsOf(ownerId),
|
|
7972
|
+
}), () => this.getLang());
|
|
7973
|
+
}
|
|
7116
7974
|
/** 当前启用的插件 AI 工具定义(provider 快照按 disabledPlugins 与 disabledPluginTools 过滤;
|
|
7117
7975
|
* 未知/已卸载插件的禁用条目保留但不影响现有工具)。
|
|
7118
7976
|
* 预设是第二层门控(见 tool-manager.ts 语义总表):非 standard 预设下插件工具
|
|
@@ -7133,18 +7991,21 @@ export class ClientSession {
|
|
|
7133
7991
|
/** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
|
|
7134
7992
|
* 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。
|
|
7135
7993
|
* 模板白名单的子代理(subagentBarsPluginTools)跳过:工厂期就没注册,这里
|
|
7136
|
-
* 不回补,否则白名单等于没关门。
|
|
7994
|
+
* 不回补,否则白名单等于没关门。
|
|
7995
|
+
* 动态补入的工具统一经 wrapGenericTool 包裹,具备模式硬闸门与审批规则防护(Issue #722)。 */
|
|
7137
7996
|
syncPluginTools(session, preset) {
|
|
7138
7997
|
let targetPreset = preset;
|
|
7139
|
-
|
|
7998
|
+
let ownerId;
|
|
7999
|
+
for (const [id, conv] of this.convs.entries()) {
|
|
7140
8000
|
if (conv.session !== session)
|
|
7141
8001
|
continue;
|
|
8002
|
+
ownerId = id;
|
|
7142
8003
|
if (conv.subagentBarsPluginTools)
|
|
7143
8004
|
return;
|
|
7144
8005
|
targetPreset ??= conv.agentPreset;
|
|
7145
8006
|
}
|
|
7146
8007
|
try {
|
|
7147
|
-
const defs = this.enabledPluginToolDefs(targetPreset);
|
|
8008
|
+
const defs = this.enabledPluginToolDefs(targetPreset).map((t) => this.wrapGenericTool(t, ownerId));
|
|
7148
8009
|
// 移除口径 = 已同步过的 ∪ 全量插件宇宙:创建时工厂直接注册进
|
|
7149
8010
|
// _customTools 的工具不在 applied 表里,首轮同步(defs 为空时)否则删不掉。
|
|
7150
8011
|
const universe = new Set([
|
|
@@ -7438,8 +8299,35 @@ export class ClientSession {
|
|
|
7438
8299
|
* after the current turn settles, skipping remaining planned tool calls.
|
|
7439
8300
|
*/
|
|
7440
8301
|
queue = false) {
|
|
7441
|
-
|
|
8302
|
+
// Captured at the START (before any await): the conversation being
|
|
8303
|
+
// addressed by this prompt. See the naming block below — a concurrent
|
|
8304
|
+
// switch/new_chat while prompt() is in flight must never target a
|
|
8305
|
+
// different conversation.
|
|
8306
|
+
const conv = this.conv;
|
|
8307
|
+
// 人类用户发送新消息,重置自主轮次与空转计数器(issue #726)
|
|
8308
|
+
conv.autonomousTurnsWithoutUser = 0;
|
|
8309
|
+
conv.consecutiveIdleWakeTurns = 0;
|
|
8310
|
+
conv.recentWakeSubagentIds = [];
|
|
8311
|
+
conv.wakeReason = "user";
|
|
8312
|
+
conv.wakeTurnHadAction = undefined;
|
|
8313
|
+
// issue #726:若当前对话存在自动唤醒挂起期间暂存的子代理完成通知,
|
|
8314
|
+
// 自动提取合并并注入,确保挂起期间的通知 100% 零丢失
|
|
8315
|
+
const drainer = this.drainSuspendedSubagents ?? ClientSession.prototype.drainSuspendedSubagents;
|
|
8316
|
+
const bufferedSubagents = drainer ? drainer.call(this, conv) : [];
|
|
8317
|
+
const rawTrimmed = (text ?? "").trim();
|
|
7442
8318
|
const hasAttachments = Boolean(attachments && attachments.length > 0);
|
|
8319
|
+
if (bufferedSubagents.length > 0) {
|
|
8320
|
+
const bufferedNotice = formatSubagentsCompletionNotice(bufferedSubagents, this.getLang());
|
|
8321
|
+
if (!rawTrimmed && !hasAttachments) {
|
|
8322
|
+
text = bufferedNotice;
|
|
8323
|
+
}
|
|
8324
|
+
else {
|
|
8325
|
+
const prefixZh = `[在自动唤醒挂起期间已完成的子代理通知]:\n\n${bufferedNotice}\n\n---\n[用户最新指令]:\n`;
|
|
8326
|
+
const prefixEn = `[Buffered subagent completion notice(s) during suspended auto-wake]:\n\n${bufferedNotice}\n\n---\n[User instruction]:\n`;
|
|
8327
|
+
text = `${this.getLang() === "zh" ? prefixZh : prefixEn}${text}`;
|
|
8328
|
+
}
|
|
8329
|
+
}
|
|
8330
|
+
const trimmedText = (text ?? "").trim();
|
|
7443
8331
|
if (!trimmedText && !hasAttachments) {
|
|
7444
8332
|
this.emit({
|
|
7445
8333
|
type: "notice",
|
|
@@ -7450,11 +8338,6 @@ export class ClientSession {
|
|
|
7450
8338
|
this.flushSnapshot();
|
|
7451
8339
|
return;
|
|
7452
8340
|
}
|
|
7453
|
-
// Captured at the START (before any await): the conversation being
|
|
7454
|
-
// addressed by this prompt. See the naming block below — a concurrent
|
|
7455
|
-
// switch/new_chat while prompt() is in flight must never target a
|
|
7456
|
-
// different conversation.
|
|
7457
|
-
const conv = this.conv;
|
|
7458
8341
|
const promptAc = new AbortController();
|
|
7459
8342
|
conv.activePromptAc = promptAc;
|
|
7460
8343
|
this.markerSvc.clearActions(conv.id);
|
|
@@ -7586,9 +8469,7 @@ export class ClientSession {
|
|
|
7586
8469
|
conv.transcriptBlocked = false;
|
|
7587
8470
|
try {
|
|
7588
8471
|
await s.reload();
|
|
7589
|
-
this.
|
|
7590
|
-
this.applyCompactionOverrides();
|
|
7591
|
-
this.applyToolGating(s, conv.agentPreset);
|
|
8472
|
+
this.applySessionOverrides(conv);
|
|
7592
8473
|
}
|
|
7593
8474
|
catch {
|
|
7594
8475
|
// reload 失败兜底
|
|
@@ -7856,61 +8737,10 @@ export class ClientSession {
|
|
|
7856
8737
|
});
|
|
7857
8738
|
return;
|
|
7858
8739
|
}
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
if (s.isStreaming) {
|
|
7864
|
-
for (const aside of asides) {
|
|
7865
|
-
const details = aside.message.details;
|
|
7866
|
-
for (const b of aside.message.content) {
|
|
7867
|
-
if (typeof b === "string") {
|
|
7868
|
-
if (b.trim())
|
|
7869
|
-
textAsides.push(b.trim());
|
|
7870
|
-
continue;
|
|
7871
|
-
}
|
|
7872
|
-
if (!b || typeof b !== "object")
|
|
7873
|
-
continue;
|
|
7874
|
-
if (b.type === "image" && typeof b.data === "string") {
|
|
7875
|
-
if (mainSupportsVision) {
|
|
7876
|
-
promptImages.push({
|
|
7877
|
-
type: "image",
|
|
7878
|
-
data: b.data,
|
|
7879
|
-
mimeType: b.mimeType || "image/png",
|
|
7880
|
-
});
|
|
7881
|
-
if (details?.name) {
|
|
7882
|
-
imageNames.push(details.name);
|
|
7883
|
-
}
|
|
7884
|
-
}
|
|
7885
|
-
}
|
|
7886
|
-
else if (b.type === "text" &&
|
|
7887
|
-
typeof b.text === "string" &&
|
|
7888
|
-
b.text.trim()) {
|
|
7889
|
-
textAsides.push(b.text.trim());
|
|
7890
|
-
if (details?.mode === "bridged" && details?.name) {
|
|
7891
|
-
imageNames.push(details.name);
|
|
7892
|
-
}
|
|
7893
|
-
}
|
|
7894
|
-
}
|
|
7895
|
-
}
|
|
7896
|
-
// 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
|
|
7897
|
-
// Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
|
|
7898
|
-
// 排队消息无法获取附件,且附件残留泄露到下一次提问。
|
|
7899
|
-
// 保证 SDK 内部暂存队列清空,防止历史残留污染。
|
|
7900
|
-
if (Array.isArray(s._pendingNextTurnMessages)) {
|
|
7901
|
-
s._pendingNextTurnMessages = [];
|
|
7902
|
-
}
|
|
7903
|
-
}
|
|
7904
|
-
else {
|
|
7905
|
-
// 空闲提问:必须携带 deliverAs: "nextTurn",将附件(图片、文件引用、视觉证据等)
|
|
7906
|
-
// 注入 SDK 的 _pendingNextTurnMessages,并在随后的 s.prompt() 中由 SDK 作为上下文消息
|
|
7907
|
-
// 传递给 LLM 并落盘(fixes #667)。严禁在此清空 _pendingNextTurnMessages。
|
|
7908
|
-
for (const aside of asides) {
|
|
7909
|
-
await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
|
|
7910
|
-
}
|
|
7911
|
-
if (asides.length > 0) {
|
|
7912
|
-
this.flushSnapshot();
|
|
7913
|
-
}
|
|
8740
|
+
// 空闲前置:若当前未处于流式运行且上下文超标,提早在注入附件前执行软上限主动压缩(issue #716)。
|
|
8741
|
+
// 必须在任何 nextTurn 注入之前完成,避免耗时压缩期间发生状态变化导致附件残留泄漏(fixes #717)。
|
|
8742
|
+
if (!s.isStreaming) {
|
|
8743
|
+
await this.triggerSoftCapCompactionIfExceeded(conv);
|
|
7914
8744
|
}
|
|
7915
8745
|
if (promptAc.signal.aborted) {
|
|
7916
8746
|
conv.activePromptAc = undefined;
|
|
@@ -7937,38 +8767,70 @@ export class ClientSession {
|
|
|
7937
8767
|
textEn: `Message delivered to "${conv.title}" — you switched conversations before it landed`,
|
|
7938
8768
|
});
|
|
7939
8769
|
}
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
//
|
|
7946
|
-
//
|
|
7947
|
-
//
|
|
7948
|
-
//
|
|
7949
|
-
|
|
7950
|
-
|
|
7951
|
-
|
|
7952
|
-
|
|
7953
|
-
// 严禁在此处启动或 await 工作区 Git 影子快照(否则在大型仓库或工具占锁时会把
|
|
7954
|
-
// 入队回执与 flushSnapshot 阻塞数秒至 15 秒,造成「按完 Enter 消息消失」)。
|
|
7955
|
-
// 排队/插队消息的工作区快照在其真正出队定稿(message_end, role="user")时异步生成。
|
|
8770
|
+
const mainSupportsVision = s.model?.input?.includes("image") ?? false;
|
|
8771
|
+
const modelLabel = s.model?.name ?? s.model?.id ?? "unknown";
|
|
8772
|
+
// 单源流式投递执行器:无论进入时已处于流式还是中途跃迁为流式,均通过单源解构提取
|
|
8773
|
+
// 完整的图片、文本与非视觉模型占位,确保排队消息绝不丢图且清空 SDK 暂存杜绝跨轮泄漏(fixes #717)。
|
|
8774
|
+
const deliverStreamingPrompt = async () => {
|
|
8775
|
+
// 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
|
|
8776
|
+
// Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
|
|
8777
|
+
// 排队消息无法获取附件,且附件残留泄露到下一次提问。
|
|
8778
|
+
// 保证 SDK 内部暂存队列排空,防止历史残留污染。
|
|
8779
|
+
if (Array.isArray(s._pendingNextTurnMessages)) {
|
|
8780
|
+
s._pendingNextTurnMessages = [];
|
|
8781
|
+
}
|
|
8782
|
+
const { promptImages, textAsides, imageNames, quotes } = extractStreamingPayload(asides, streamingQuotes, mainSupportsVision, modelLabel);
|
|
7956
8783
|
const kind = queue ? "followUp" : "steer";
|
|
7957
|
-
const fullPromptText = formatStreamingPrompt(text, textAsides,
|
|
8784
|
+
const fullPromptText = formatStreamingPrompt(text, textAsides, quotes, imageNames);
|
|
7958
8785
|
if (this.consumeCancelledInFlightQueue(conv, kind, text, fullPromptText)) {
|
|
7959
8786
|
this.flushSnapshot();
|
|
7960
8787
|
return;
|
|
7961
8788
|
}
|
|
7962
|
-
|
|
7963
|
-
conv.queuedImages.set(fullPromptText, promptImages);
|
|
7964
|
-
}
|
|
7965
|
-
await s.prompt(fullPromptText, {
|
|
7966
|
-
streamingBehavior: kind,
|
|
8789
|
+
const entry = createQueuedEntry(fullPromptText, {
|
|
7967
8790
|
images: promptImages.length > 0 ? promptImages : undefined,
|
|
8791
|
+
attachments: effectiveAttachments,
|
|
7968
8792
|
});
|
|
8793
|
+
if (kind === "steer") {
|
|
8794
|
+
(conv.queuedSteeringEntries ??= []).push(entry);
|
|
8795
|
+
}
|
|
8796
|
+
else {
|
|
8797
|
+
(conv.queuedFollowUpEntries ??= []).push(entry);
|
|
8798
|
+
}
|
|
8799
|
+
try {
|
|
8800
|
+
await s.prompt(fullPromptText, {
|
|
8801
|
+
streamingBehavior: kind,
|
|
8802
|
+
images: promptImages.length > 0 ? promptImages : undefined,
|
|
8803
|
+
});
|
|
8804
|
+
}
|
|
8805
|
+
catch (err) {
|
|
8806
|
+
if (kind === "steer") {
|
|
8807
|
+
conv.queuedSteeringEntries = rollbackQueuedEntry(conv.queuedSteeringEntries ?? [], fullPromptText);
|
|
8808
|
+
}
|
|
8809
|
+
else {
|
|
8810
|
+
conv.queuedFollowUpEntries = rollbackQueuedEntry(conv.queuedFollowUpEntries ?? [], fullPromptText);
|
|
8811
|
+
}
|
|
8812
|
+
throw err;
|
|
8813
|
+
}
|
|
8814
|
+
};
|
|
8815
|
+
if (s.isStreaming) {
|
|
8816
|
+
await deliverStreamingPrompt();
|
|
7969
8817
|
}
|
|
7970
8818
|
else {
|
|
7971
|
-
//
|
|
8819
|
+
// 空闲提问:必须携带 deliverAs: "nextTurn",将附件(图片、文件引用、视觉证据等)
|
|
8820
|
+
// 注入 SDK 的 _pendingNextTurnMessages,并在随后的 s.prompt() 中由 SDK 作为上下文消息
|
|
8821
|
+
// 传递给 LLM 并落盘(fixes #667)。严禁在此清空 _pendingNextTurnMessages。
|
|
8822
|
+
for (const aside of asides) {
|
|
8823
|
+
await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
|
|
8824
|
+
}
|
|
8825
|
+
// 临界区并发保护:若在注入期间或注入后瞬间会话转入流式状态,立即回退转入流式投递并排空暂存(fixes #717)
|
|
8826
|
+
if (s.isStreaming) {
|
|
8827
|
+
await deliverStreamingPrompt();
|
|
8828
|
+
return;
|
|
8829
|
+
}
|
|
8830
|
+
if (asides.length > 0) {
|
|
8831
|
+
this.flushSnapshot();
|
|
8832
|
+
}
|
|
8833
|
+
// 启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
|
|
7972
8834
|
// 绑定由 message_end 异步完成,绝不阻塞 prompt 收尾与气泡上屏)。
|
|
7973
8835
|
const snapshotPromise = this.startWorkspaceSnapshot(conv);
|
|
7974
8836
|
try {
|
|
@@ -8138,7 +9000,7 @@ export class ClientSession {
|
|
|
8138
9000
|
* item still at that position; on any mismatch we fall back to first-occurrence
|
|
8139
9001
|
* text match (old clients, or the queue shifted between click and handling).
|
|
8140
9002
|
*/
|
|
8141
|
-
async removeQueued(kind, text, index) {
|
|
9003
|
+
async removeQueued(kind, text, index, id) {
|
|
8142
9004
|
const conv = this.conv;
|
|
8143
9005
|
// Always-defined display mirrors; also the provenance of bubble rendering.
|
|
8144
9006
|
const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
|
|
@@ -8170,6 +9032,20 @@ export class ClientSession {
|
|
|
8170
9032
|
if (next.length !== local.length) {
|
|
8171
9033
|
local.splice(0, local.length, ...next);
|
|
8172
9034
|
}
|
|
9035
|
+
if (kind === "steer") {
|
|
9036
|
+
conv.queuedSteeringEntries = removeQueuedEntry(conv.queuedSteeringEntries ?? [], {
|
|
9037
|
+
id,
|
|
9038
|
+
text: targetText,
|
|
9039
|
+
index,
|
|
9040
|
+
});
|
|
9041
|
+
}
|
|
9042
|
+
else {
|
|
9043
|
+
conv.queuedFollowUpEntries = removeQueuedEntry(conv.queuedFollowUpEntries ?? [], {
|
|
9044
|
+
id,
|
|
9045
|
+
text: targetText,
|
|
9046
|
+
index,
|
|
9047
|
+
});
|
|
9048
|
+
}
|
|
8173
9049
|
this.flushSnapshot();
|
|
8174
9050
|
return;
|
|
8175
9051
|
}
|
|
@@ -8187,22 +9063,44 @@ export class ClientSession {
|
|
|
8187
9063
|
if (next.length !== local.length) {
|
|
8188
9064
|
local.splice(0, local.length, ...next);
|
|
8189
9065
|
}
|
|
9066
|
+
if (kind === "steer") {
|
|
9067
|
+
conv.queuedSteeringEntries = removeQueuedEntry(conv.queuedSteeringEntries ?? [], {
|
|
9068
|
+
id,
|
|
9069
|
+
text: targetText,
|
|
9070
|
+
index,
|
|
9071
|
+
});
|
|
9072
|
+
}
|
|
9073
|
+
else {
|
|
9074
|
+
conv.queuedFollowUpEntries = removeQueuedEntry(conv.queuedFollowUpEntries ?? [], {
|
|
9075
|
+
id,
|
|
9076
|
+
text: targetText,
|
|
9077
|
+
index,
|
|
9078
|
+
});
|
|
9079
|
+
}
|
|
8190
9080
|
this.flushSnapshot();
|
|
8191
9081
|
return;
|
|
8192
9082
|
}
|
|
8193
|
-
//
|
|
8194
|
-
|
|
8195
|
-
|
|
8196
|
-
|
|
8197
|
-
const
|
|
9083
|
+
// 用 clearQueue 返回的最新队列对账,确保与清空前状态严格对齐(issue #718)
|
|
9084
|
+
const currentSteeringEntries = reconcileQueuedEntries(conv.queuedSteeringEntries ?? [], steering);
|
|
9085
|
+
const currentFollowUpEntries = reconcileQueuedEntries(conv.queuedFollowUpEntries ?? [], followUp);
|
|
9086
|
+
// 气泡 ✕ 对应条目:优先按唯一 id 精准剔除,兜底按 index/text 剔除
|
|
9087
|
+
const keptSteeringEntries = kind === "steer"
|
|
9088
|
+
? removeQueuedEntry(currentSteeringEntries, { id, text: targetText, index })
|
|
9089
|
+
: currentSteeringEntries;
|
|
9090
|
+
const keptFollowUpEntries = kind === "followUp"
|
|
9091
|
+
? removeQueuedEntry(currentFollowUpEntries, { id, text: targetText, index })
|
|
9092
|
+
: currentFollowUpEntries;
|
|
9093
|
+
conv.queuedSteeringEntries = [];
|
|
9094
|
+
conv.queuedFollowUpEntries = [];
|
|
8198
9095
|
// Re-queue the survivors in original order. Guard each call so a single
|
|
8199
9096
|
// failure can't leave the queue half-drained silently.
|
|
8200
|
-
for (const
|
|
9097
|
+
for (const entry of keptSteeringEntries) {
|
|
8201
9098
|
try {
|
|
8202
|
-
|
|
8203
|
-
await s.steer(
|
|
9099
|
+
conv.queuedSteeringEntries.push(entry);
|
|
9100
|
+
await s.steer(entry.text, entry.images);
|
|
8204
9101
|
}
|
|
8205
9102
|
catch (err) {
|
|
9103
|
+
conv.queuedSteeringEntries.pop();
|
|
8206
9104
|
this.emit({
|
|
8207
9105
|
type: "notice",
|
|
8208
9106
|
level: "error",
|
|
@@ -8211,12 +9109,13 @@ export class ClientSession {
|
|
|
8211
9109
|
});
|
|
8212
9110
|
}
|
|
8213
9111
|
}
|
|
8214
|
-
for (const
|
|
9112
|
+
for (const entry of keptFollowUpEntries) {
|
|
8215
9113
|
try {
|
|
8216
|
-
|
|
8217
|
-
await s.followUp(
|
|
9114
|
+
conv.queuedFollowUpEntries.push(entry);
|
|
9115
|
+
await s.followUp(entry.text, entry.images);
|
|
8218
9116
|
}
|
|
8219
9117
|
catch (err) {
|
|
9118
|
+
conv.queuedFollowUpEntries.pop();
|
|
8220
9119
|
this.emit({
|
|
8221
9120
|
type: "notice",
|
|
8222
9121
|
level: "error",
|
|
@@ -8225,7 +9124,6 @@ export class ClientSession {
|
|
|
8225
9124
|
});
|
|
8226
9125
|
}
|
|
8227
9126
|
}
|
|
8228
|
-
conv.queuedImages?.delete(targetText);
|
|
8229
9127
|
if (Array.isArray(s._pendingNextTurnMessages)) {
|
|
8230
9128
|
s._pendingNextTurnMessages = [];
|
|
8231
9129
|
}
|
|
@@ -8345,7 +9243,14 @@ export class ClientSession {
|
|
|
8345
9243
|
}
|
|
8346
9244
|
/** Interrupt a run: abort, with a force-reset fallback on timeout. */
|
|
8347
9245
|
async interruptRun(conv, reason) {
|
|
8348
|
-
//
|
|
9246
|
+
// 正在投递的消息前置阶段(附件构建 / 影子快照)立即打断
|
|
9247
|
+
if (conv.activePromptAc) {
|
|
9248
|
+
conv.activePromptAc.abort();
|
|
9249
|
+
conv.activePromptAc = undefined;
|
|
9250
|
+
}
|
|
9251
|
+
// 统一清理在飞的工具看门狗、计时器与进行中参数状态,防止中止后残留或跳出超时鬼影警告
|
|
9252
|
+
this.clearConversationToolStates(conv);
|
|
9253
|
+
// #487:停下就结算该会话的挂起提问/审批/页面调用——残留条目让 isWaitingOnUser 恒真
|
|
8349
9254
|
// (stall 失联检测被永久豁免),弹窗也会跨轮残留;dispose 语义已范本化。
|
|
8350
9255
|
this.settlePendingsForConv(conv.id);
|
|
8351
9256
|
if (!this.conversationStreaming(conv) && conv.session.isIdle) {
|
|
@@ -8417,8 +9322,11 @@ export class ClientSession {
|
|
|
8417
9322
|
try {
|
|
8418
9323
|
conv.unsubscribe?.();
|
|
8419
9324
|
conv.unsubscribe = undefined;
|
|
8420
|
-
this.
|
|
8421
|
-
|
|
9325
|
+
this.clearConversationToolStates(conv);
|
|
9326
|
+
// 强杀重建:上一轮的运行已经没了(agent_end 不会再发,run_end 不会到达带 runId),
|
|
9327
|
+
// 残留的插件运行 token 必须清掉——否则用户随后自己聊的那一轮会被当插件驱动。
|
|
9328
|
+
conv.pluginRunId = undefined;
|
|
9329
|
+
conv.pendingPluginRunId = undefined;
|
|
8422
9330
|
disposeEvalSession(conv.id);
|
|
8423
9331
|
await conv.runtime.dispose();
|
|
8424
9332
|
// #485:dispose 挂起期间会话可能已被强行关闭移出(forceDismiss 走
|
|
@@ -8452,7 +9360,7 @@ export class ClientSession {
|
|
|
8452
9360
|
}, (m) =>
|
|
8453
9361
|
// 子代理带模板时按原模板重建(conv.subagentTemplate 是派发时工厂
|
|
8454
9362
|
// 用的同一快照);普通对话 undefined,行为不变。
|
|
8455
|
-
createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id), {
|
|
9363
|
+
createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id, undefined, undefined, conv.isSubagent && this.subagentAtDepthLimit(conv.parentId)), {
|
|
8456
9364
|
cwd: sessionBaseDir,
|
|
8457
9365
|
agentDir: this.agentDir,
|
|
8458
9366
|
sessionManager: m,
|
|
@@ -8666,7 +9574,7 @@ export class ClientSession {
|
|
|
8666
9574
|
const mid = `${p}/${prevModel.id}`;
|
|
8667
9575
|
// 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
|
|
8668
9576
|
await this.restoreKeyForModel(mid, this.cwd);
|
|
8669
|
-
await this.session
|
|
9577
|
+
await this.applySessionModel(this.session, prevModel);
|
|
8670
9578
|
modelRestored = true;
|
|
8671
9579
|
}
|
|
8672
9580
|
catch {
|
|
@@ -9111,9 +10019,27 @@ export class ClientSession {
|
|
|
9111
10019
|
// ignore
|
|
9112
10020
|
}
|
|
9113
10021
|
this.convs.delete(id);
|
|
10022
|
+
conv.suspendedSubagents?.clear();
|
|
10023
|
+
for (const c of this.convs.values()) {
|
|
10024
|
+
c.suspendedSubagents?.delete(conv);
|
|
10025
|
+
}
|
|
10026
|
+
const pendingNotice = this.pendingSubagentNotices.get(id);
|
|
10027
|
+
if (pendingNotice) {
|
|
10028
|
+
clearTimeout(pendingNotice.timer);
|
|
10029
|
+
this.pendingSubagentNotices.delete(id);
|
|
10030
|
+
}
|
|
10031
|
+
for (const [pId, entry] of this.pendingSubagentNotices) {
|
|
10032
|
+
entry.subagents.delete(conv);
|
|
10033
|
+
if (entry.subagents.size === 0) {
|
|
10034
|
+
clearTimeout(entry.timer);
|
|
10035
|
+
this.pendingSubagentNotices.delete(pId);
|
|
10036
|
+
}
|
|
10037
|
+
}
|
|
9114
10038
|
this.pluginModelKeys?.delete(id);
|
|
9115
10039
|
this.planManager.unbindConversation(id);
|
|
9116
|
-
this.
|
|
10040
|
+
this.markerSvc.clearConversation(id);
|
|
10041
|
+
this.clearConversationToolStates(conv);
|
|
10042
|
+
this.goalSvc.notifyConversationRemoved(conv);
|
|
9117
10043
|
// 关对话 → 连它的 eval 内核(Python/Node 子进程 + 临时沙箱目录)一起回收:
|
|
9118
10044
|
// 这些进程是 detached 进程组,父进程退出不会自动带走它们。
|
|
9119
10045
|
disposeEvalSession(id);
|
|
@@ -9126,6 +10052,9 @@ export class ClientSession {
|
|
|
9126
10052
|
rmSync(ephemeralDir, { recursive: true, force: true });
|
|
9127
10053
|
}
|
|
9128
10054
|
catch { }
|
|
10055
|
+
if (conv.subagentWorktree && !conv.subagentWorktree.finalized) {
|
|
10056
|
+
void this.finalizeSubagentWorktree(conv).catch(() => { });
|
|
10057
|
+
}
|
|
9129
10058
|
}
|
|
9130
10059
|
if (conv.isEphemeral) {
|
|
9131
10060
|
const ephemeralDir = join(this.agentDir, "ephemeral-sessions", conv.id);
|
|
@@ -9247,22 +10176,24 @@ export class ClientSession {
|
|
|
9247
10176
|
// 永远等不到答复)。只搬归属明确的(conversationId 对得上,与问卷/页调用
|
|
9248
10177
|
// 同一规则);目标侧按新 id 重发弹窗,等待中的 Promise 原样过户不 resolve。
|
|
9249
10178
|
const approvals = [];
|
|
9250
|
-
for (const
|
|
9251
|
-
if (
|
|
9252
|
-
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
9257
|
-
|
|
9258
|
-
|
|
9259
|
-
|
|
9260
|
-
|
|
9261
|
-
|
|
9262
|
-
|
|
9263
|
-
|
|
9264
|
-
|
|
9265
|
-
|
|
10179
|
+
for (const conv of convs) {
|
|
10180
|
+
if (conv.pendingApprovals && conv.pendingApprovals.size > 0) {
|
|
10181
|
+
for (const [, a] of conv.pendingApprovals) {
|
|
10182
|
+
approvals.push({
|
|
10183
|
+
resolve: a.resolve,
|
|
10184
|
+
toolCallId: a.toolCallId,
|
|
10185
|
+
toolName: a.toolName,
|
|
10186
|
+
params: a.params,
|
|
10187
|
+
reason: a.reason,
|
|
10188
|
+
reasonEn: a.reasonEn,
|
|
10189
|
+
...(a.category ? { category: a.category } : {}),
|
|
10190
|
+
...(a.hits ? { hits: a.hits } : {}),
|
|
10191
|
+
conversationId: a.conversationId ?? conv.id,
|
|
10192
|
+
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
10193
|
+
createdAt: a.createdAt,
|
|
10194
|
+
});
|
|
10195
|
+
}
|
|
10196
|
+
conv.pendingApprovals.clear();
|
|
9266
10197
|
}
|
|
9267
10198
|
}
|
|
9268
10199
|
this.emitConversations();
|
|
@@ -9385,23 +10316,9 @@ export class ClientSession {
|
|
|
9385
10316
|
for (const a of payload.approvals) {
|
|
9386
10317
|
const nid = `appr-${++this.approvalSeq}`;
|
|
9387
10318
|
const aConvId = fix(a.conversationId);
|
|
9388
|
-
this.
|
|
9389
|
-
|
|
9390
|
-
|
|
9391
|
-
toolName: a.toolName,
|
|
9392
|
-
params: a.params,
|
|
9393
|
-
reason: a.reason,
|
|
9394
|
-
reasonEn: a.reasonEn,
|
|
9395
|
-
...(a.category ? { category: a.category } : {}),
|
|
9396
|
-
...(a.hits ? { hits: a.hits } : {}),
|
|
9397
|
-
conversationId: aConvId,
|
|
9398
|
-
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
9399
|
-
resolve: a.resolve,
|
|
9400
|
-
createdAt: a.createdAt,
|
|
9401
|
-
});
|
|
9402
|
-
if (aConvId === mainId) {
|
|
9403
|
-
this.emit({
|
|
9404
|
-
type: "tool_approval_pending",
|
|
10319
|
+
const targetConv = this.convs.get(aConvId);
|
|
10320
|
+
if (targetConv) {
|
|
10321
|
+
this.ensurePendingApprovals(targetConv).set(nid, {
|
|
9405
10322
|
id: nid,
|
|
9406
10323
|
toolCallId: a.toolCallId,
|
|
9407
10324
|
toolName: a.toolName,
|
|
@@ -9412,7 +10329,24 @@ export class ClientSession {
|
|
|
9412
10329
|
...(a.hits ? { hits: a.hits } : {}),
|
|
9413
10330
|
conversationId: aConvId,
|
|
9414
10331
|
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
10332
|
+
resolve: a.resolve,
|
|
10333
|
+
createdAt: a.createdAt,
|
|
9415
10334
|
});
|
|
10335
|
+
if (aConvId === mainId) {
|
|
10336
|
+
this.emit({
|
|
10337
|
+
type: "tool_approval_pending",
|
|
10338
|
+
id: nid,
|
|
10339
|
+
toolCallId: a.toolCallId,
|
|
10340
|
+
toolName: a.toolName,
|
|
10341
|
+
params: a.params,
|
|
10342
|
+
reason: a.reason,
|
|
10343
|
+
reasonEn: a.reasonEn,
|
|
10344
|
+
...(a.category ? { category: a.category } : {}),
|
|
10345
|
+
...(a.hits ? { hits: a.hits } : {}),
|
|
10346
|
+
conversationId: aConvId,
|
|
10347
|
+
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
10348
|
+
});
|
|
10349
|
+
}
|
|
9416
10350
|
}
|
|
9417
10351
|
}
|
|
9418
10352
|
return mainId;
|
|
@@ -9624,7 +10558,12 @@ export class ClientSession {
|
|
|
9624
10558
|
return pq ? { hasQuestion: true, questionId: pq.id, questionTitle: pq.title } : {};
|
|
9625
10559
|
})(),
|
|
9626
10560
|
parentId: conv.parentId,
|
|
10561
|
+
model: conv.session.model
|
|
10562
|
+
? `${conv.session.model.provider}/${conv.session.model.id}`
|
|
10563
|
+
: (conv.subagentTemplate?.model ?? undefined),
|
|
10564
|
+
thinkingLevel: conv.session.thinkingLevel ?? conv.subagentThinking ?? undefined,
|
|
9627
10565
|
...(conv.pinned ? { pinned: true } : {}),
|
|
10566
|
+
...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
|
|
9628
10567
|
...(conv.forkFrom ? { forkFrom: conv.forkFrom } : {}),
|
|
9629
10568
|
});
|
|
9630
10569
|
}
|
|
@@ -9804,18 +10743,44 @@ export class ClientSession {
|
|
|
9804
10743
|
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
|
|
9805
10744
|
const run = (async () => {
|
|
9806
10745
|
try {
|
|
9807
|
-
const
|
|
9808
|
-
|
|
9809
|
-
|
|
9810
|
-
if (
|
|
9811
|
-
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
10746
|
+
const projectDir = SessionManager.create(sessionBaseDir).getSessionDir();
|
|
10747
|
+
const extraRoot = piSessionsRoot() ? resolve(piSessionsRoot()) : undefined;
|
|
10748
|
+
const candidateFiles = new Map();
|
|
10749
|
+
if (existsSync(projectDir)) {
|
|
10750
|
+
const dirEntries = await fsPromises.readdir(projectDir);
|
|
10751
|
+
for (const f of dirEntries) {
|
|
10752
|
+
if (f.endsWith(".jsonl")) {
|
|
10753
|
+
const fp = join(projectDir, f);
|
|
10754
|
+
candidateFiles.set(normalizePathKey(fp), fp);
|
|
10755
|
+
}
|
|
10756
|
+
}
|
|
10757
|
+
}
|
|
10758
|
+
if (extraRoot && existsSync(extraRoot)) {
|
|
10759
|
+
const dirEntries = await fsPromises.readdir(extraRoot);
|
|
10760
|
+
for (const f of dirEntries) {
|
|
10761
|
+
if (f.endsWith(".jsonl")) {
|
|
10762
|
+
const fp = join(extraRoot, f);
|
|
10763
|
+
candidateFiles.set(normalizePathKey(fp), fp);
|
|
10764
|
+
}
|
|
10765
|
+
}
|
|
10766
|
+
const extraSubdir = join(extraRoot, basename(projectDir));
|
|
10767
|
+
if (normalizePathKey(extraSubdir) !== normalizePathKey(projectDir) && existsSync(extraSubdir)) {
|
|
10768
|
+
try {
|
|
10769
|
+
const subEntries = await fsPromises.readdir(extraSubdir);
|
|
10770
|
+
for (const f of subEntries) {
|
|
10771
|
+
if (f.endsWith(".jsonl")) {
|
|
10772
|
+
const fp = join(extraSubdir, f);
|
|
10773
|
+
candidateFiles.set(normalizePathKey(fp), fp);
|
|
10774
|
+
}
|
|
10775
|
+
}
|
|
10776
|
+
}
|
|
10777
|
+
catch { }
|
|
10778
|
+
}
|
|
10779
|
+
}
|
|
10780
|
+
if (candidateFiles.size === 0)
|
|
9815
10781
|
return [];
|
|
9816
10782
|
// Stat files to detect modified/new files (takes only ~8ms for 600+ files)
|
|
9817
|
-
const stats = await Promise.all(
|
|
9818
|
-
const fp = join(sessionDir, f);
|
|
10783
|
+
const stats = await Promise.all(Array.from(candidateFiles.values()).map(async (fp) => {
|
|
9819
10784
|
try {
|
|
9820
10785
|
const st = await fsPromises.stat(fp);
|
|
9821
10786
|
return { path: fp, mtime: st.mtimeMs, size: st.size };
|
|
@@ -9845,18 +10810,46 @@ export class ClientSession {
|
|
|
9845
10810
|
const validInfos = results.filter((info) => info !== null);
|
|
9846
10811
|
const baseDirKey = normalizePathKey(sessionBaseDir);
|
|
9847
10812
|
const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
|
|
9848
|
-
const
|
|
10813
|
+
const seenIds = new Set();
|
|
10814
|
+
const dedupedOwnInfos = [];
|
|
10815
|
+
for (const info of ownInfos) {
|
|
10816
|
+
if (info.id) {
|
|
10817
|
+
if (seenIds.has(info.id))
|
|
10818
|
+
continue;
|
|
10819
|
+
seenIds.add(info.id);
|
|
10820
|
+
}
|
|
10821
|
+
dedupedOwnInfos.push(info);
|
|
10822
|
+
}
|
|
10823
|
+
const candidates = dedupedOwnInfos.slice(0, 200);
|
|
9849
10824
|
candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
9850
10825
|
ClientSession.sessionInfosCache.set(cwdKey, { infos: candidates, at: Date.now() });
|
|
9851
10826
|
return candidates;
|
|
9852
10827
|
}
|
|
9853
10828
|
catch {
|
|
9854
10829
|
try {
|
|
9855
|
-
const
|
|
9856
|
-
|
|
9857
|
-
|
|
9858
|
-
|
|
9859
|
-
|
|
10830
|
+
const projectInfos = await SessionManager.list(sessionBaseDir).catch(() => []);
|
|
10831
|
+
const extraInfos = piSessionsRoot()
|
|
10832
|
+
? await SessionManager.list(sessionBaseDir, piSessionsRoot()).catch(() => [])
|
|
10833
|
+
: [];
|
|
10834
|
+
const seenPath = new Set();
|
|
10835
|
+
const seenId = new Set();
|
|
10836
|
+
const combined = [];
|
|
10837
|
+
for (const s of [...projectInfos, ...extraInfos]) {
|
|
10838
|
+
const key = normalizePathKey(s.path);
|
|
10839
|
+
if (seenPath.has(key))
|
|
10840
|
+
continue;
|
|
10841
|
+
seenPath.add(key);
|
|
10842
|
+
if (s.id) {
|
|
10843
|
+
if (seenId.has(s.id))
|
|
10844
|
+
continue;
|
|
10845
|
+
seenId.add(s.id);
|
|
10846
|
+
}
|
|
10847
|
+
// 统一口径:列表缓存一律不带转录全文(issue #440),搜索按需另行加载
|
|
10848
|
+
combined.push({ ...s, allMessagesText: "" });
|
|
10849
|
+
}
|
|
10850
|
+
combined.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
10851
|
+
ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now() });
|
|
10852
|
+
return combined;
|
|
9860
10853
|
}
|
|
9861
10854
|
catch {
|
|
9862
10855
|
return [];
|
|
@@ -10415,8 +11408,8 @@ export class ClientSession {
|
|
|
10415
11408
|
this.emit({
|
|
10416
11409
|
type: "notice",
|
|
10417
11410
|
level: "warning",
|
|
10418
|
-
text: `对话「${conv.title}
|
|
10419
|
-
textEn: `Conversation "${conv.title}" still has open terminals — close them
|
|
11411
|
+
text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端或右键选择「强行关闭」后再移出`,
|
|
11412
|
+
textEn: `Conversation "${conv.title}" still has open terminals — close them or right-click to force-dismiss`,
|
|
10420
11413
|
});
|
|
10421
11414
|
return;
|
|
10422
11415
|
}
|
|
@@ -10984,10 +11977,6 @@ export class ClientSession {
|
|
|
10984
11977
|
if (displaced)
|
|
10985
11978
|
this.removeConversation(displaced.id);
|
|
10986
11979
|
await this.bindSession();
|
|
10987
|
-
// #436:转录回放恢复的 planMode 在 runtime 工厂的 applyToolGating 时还读不到
|
|
10988
|
-
//(conv 尚未进 this.convs,planModeOf 落空)——注册后统一补一次门控,让
|
|
10989
|
-
// 计划模式的写类/旁路工具剥离对重开的会话同样生效。下同(forkSession/setCwd)。
|
|
10990
|
-
this.applyToolGating(conv.session, conv.agentPreset);
|
|
10991
11980
|
this.cwd = targetCwd;
|
|
10992
11981
|
this.files.unwatchGit();
|
|
10993
11982
|
// 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
|
|
@@ -11194,14 +12183,11 @@ export class ClientSession {
|
|
|
11194
12183
|
await this.bindSession();
|
|
11195
12184
|
this.invalidateSessionInfos();
|
|
11196
12185
|
this.scheduleSessionsRefresh();
|
|
11197
|
-
// #436:同 switchSession —— 派生出的会话若从转录回放恢复了 planMode,
|
|
11198
|
-
// 工厂里的门控当时读不到它,注册后补一次。
|
|
11199
|
-
this.applyToolGating(newConv.session, newConv.agentPreset);
|
|
11200
12186
|
if (prevModel && this.sharedModelRuntime) {
|
|
11201
12187
|
try {
|
|
11202
12188
|
const pm = prevModel;
|
|
11203
12189
|
await this.restoreKeyForModel(`${pm.provider}/${pm.id}`, targetConv.cwd);
|
|
11204
|
-
await this.session
|
|
12190
|
+
await this.applySessionModel(this.session, prevModel);
|
|
11205
12191
|
}
|
|
11206
12192
|
catch {
|
|
11207
12193
|
// keep default
|
|
@@ -11276,10 +12262,8 @@ export class ClientSession {
|
|
|
11276
12262
|
}
|
|
11277
12263
|
}
|
|
11278
12264
|
await targetConv.session.reload();
|
|
11279
|
-
//
|
|
11280
|
-
this.
|
|
11281
|
-
this.applyCompactionOverrides();
|
|
11282
|
-
this.applyToolGating(targetConv.session, targetConv.agentPreset);
|
|
12265
|
+
// 重新应用设置和门控(统一收口)
|
|
12266
|
+
this.applySessionOverrides(targetConv);
|
|
11283
12267
|
// 清理该会话的 UI 消息缓存和序列化映射
|
|
11284
12268
|
targetConv.uiMessageCache.clear();
|
|
11285
12269
|
targetConv.msgIds.clear();
|
|
@@ -11289,7 +12273,8 @@ export class ClientSession {
|
|
|
11289
12273
|
targetConv.lastMessagesArray = [];
|
|
11290
12274
|
targetConv.queueSteering = [];
|
|
11291
12275
|
targetConv.queueFollowUp = [];
|
|
11292
|
-
targetConv.
|
|
12276
|
+
targetConv.queuedSteeringEntries = [];
|
|
12277
|
+
targetConv.queuedFollowUpEntries = [];
|
|
11293
12278
|
try {
|
|
11294
12279
|
targetConv.session.clearQueue?.();
|
|
11295
12280
|
}
|
|
@@ -11443,14 +12428,15 @@ export class ClientSession {
|
|
|
11443
12428
|
this.conv.lastMessagesArray = [];
|
|
11444
12429
|
this.conv.queueSteering = [];
|
|
11445
12430
|
this.conv.queueFollowUp = [];
|
|
11446
|
-
this.conv.
|
|
12431
|
+
this.conv.queuedSteeringEntries = [];
|
|
12432
|
+
this.conv.queuedFollowUpEntries = [];
|
|
11447
12433
|
// Restore the previously-selected model on the forked branch.
|
|
11448
12434
|
if (prevModel && this.sharedModelRuntime) {
|
|
11449
12435
|
try {
|
|
11450
12436
|
const pm = prevModel;
|
|
11451
12437
|
// 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
|
|
11452
12438
|
await this.restoreKeyForModel(`${pm.provider}/${pm.id}`, this.cwd);
|
|
11453
|
-
await this.session
|
|
12439
|
+
await this.applySessionModel(this.session, prevModel);
|
|
11454
12440
|
}
|
|
11455
12441
|
catch {
|
|
11456
12442
|
// model no longer resolvable — keep the default
|
|
@@ -12311,6 +13297,8 @@ export class ClientSession {
|
|
|
12311
13297
|
};
|
|
12312
13298
|
});
|
|
12313
13299
|
this.emit({ type: "models", models });
|
|
13300
|
+
// 联网刷新拉回动态本地模型(如 llama.cpp)后,若当前对话尚处于未发消息阶段,尝试自愈恢复记忆模型
|
|
13301
|
+
void this.restoreProjectModelForCwd(this.cwd);
|
|
12314
13302
|
}
|
|
12315
13303
|
catch (err) {
|
|
12316
13304
|
this.emit({
|
|
@@ -12383,13 +13371,12 @@ export class ClientSession {
|
|
|
12383
13371
|
throw new Error(`模型不存在:${modelId}`);
|
|
12384
13372
|
// 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
|
|
12385
13373
|
await this.restoreKeyForModel(modelId, this.cwd);
|
|
12386
|
-
await this.session
|
|
13374
|
+
await this.applySessionModel(this.session, model);
|
|
12387
13375
|
// Immediately remember the model + the key it uses for the current
|
|
12388
13376
|
// project (not only after a turn). This is what makes project switching
|
|
12389
13377
|
// restore both the model and the provider key.
|
|
12390
13378
|
this.rememberProjectModel(modelId);
|
|
12391
|
-
//
|
|
12392
|
-
this.applyCompactionOverrides();
|
|
13379
|
+
// 换模型后按新模型的窗口重算软上限覆盖已由 applySessionModel 完成(issue #229/#773)。
|
|
12393
13380
|
// 切换成功 → 立即通知插件(#542:不发消息也能收到);失败路径落在 catch 里,不发。
|
|
12394
13381
|
this.notifyPluginModelChange();
|
|
12395
13382
|
}
|
|
@@ -12534,6 +13521,7 @@ export class ClientSession {
|
|
|
12534
13521
|
// TerminateProcess + 状态清理,句柄由 OS 在进程退出时回收。
|
|
12535
13522
|
for (const conv of this.convs.values())
|
|
12536
13523
|
conv.terminals.killAll({ shutdown: true });
|
|
13524
|
+
this.userTerminals?.killAll({ shutdown: true });
|
|
12537
13525
|
if (this.snapshotTimer) {
|
|
12538
13526
|
clearTimeout(this.snapshotTimer);
|
|
12539
13527
|
this.snapshotTimer = null;
|
|
@@ -12553,15 +13541,44 @@ export class ClientSession {
|
|
|
12553
13541
|
this.files.unwatchDir();
|
|
12554
13542
|
this.files.unwatchGit();
|
|
12555
13543
|
this.webUi.dispose();
|
|
13544
|
+
for (const entry of this.pendingSubagentNotices.values()) {
|
|
13545
|
+
clearTimeout(entry.timer);
|
|
13546
|
+
}
|
|
13547
|
+
this.pendingSubagentNotices.clear();
|
|
13548
|
+
for (const c of this.convs.values()) {
|
|
13549
|
+
c.suspendedSubagents?.clear();
|
|
13550
|
+
}
|
|
12556
13551
|
// 关闭所有挂起的用户提问(dispose 时以「取消」解析,避免模型挂死)。
|
|
12557
13552
|
this.cancelPendingQuestions();
|
|
12558
13553
|
// 同理关闭挂起的页面调用(以失败解析:对面是扩展,没有答可等)。
|
|
12559
13554
|
this.cancelPendingPageCalls();
|
|
12560
13555
|
// 挂起的工具审批一并清掉(以「拒绝」解析,防 Promise/runtime 泄漏)。
|
|
12561
13556
|
this.cancelPendingApprovals();
|
|
13557
|
+
// 角色轮等待者:客户端销毁 → 唤醒所有等待者收到 gone(避免悬挂超时)
|
|
13558
|
+
for (const [, waiters] of this.turnEndWaiters) {
|
|
13559
|
+
for (const fn of waiters) {
|
|
13560
|
+
try {
|
|
13561
|
+
fn("gone");
|
|
13562
|
+
}
|
|
13563
|
+
catch {
|
|
13564
|
+
// ignore
|
|
13565
|
+
}
|
|
13566
|
+
}
|
|
13567
|
+
waiters.clear();
|
|
13568
|
+
}
|
|
13569
|
+
this.turnEndWaiters.clear();
|
|
13570
|
+
// 释放客户端所有对话名下的文件认领
|
|
13571
|
+
try {
|
|
13572
|
+
for (const id of this.convs.keys()) {
|
|
13573
|
+
this.getClaimStore?.().releaseByOwner(id);
|
|
13574
|
+
}
|
|
13575
|
+
}
|
|
13576
|
+
catch {
|
|
13577
|
+
// ignore
|
|
13578
|
+
}
|
|
12562
13579
|
this.bg.stop();
|
|
12563
13580
|
for (const conv of this.convs.values()) {
|
|
12564
|
-
this.
|
|
13581
|
+
this.clearConversationToolStates(conv);
|
|
12565
13582
|
// 逐个对话回收 eval 内核;下面的兜底再清一次表(含已 delete 的残留)。
|
|
12566
13583
|
disposeEvalSession(conv.id);
|
|
12567
13584
|
conv.unsubscribe?.();
|