pi-web-ui 0.98.0 → 0.100.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 +85 -5
- package/README.md +2 -1
- package/README.zh-CN.md +2 -1
- package/bin/pi-web-ui.mjs +174 -36
- package/dist/server/agent-service.js +1169 -152
- package/dist/server/approval-rules.js +95 -23
- package/dist/server/attachments.js +55 -0
- package/dist/server/bg-servers.js +82 -2
- package/dist/server/claim-files-tool.js +4 -4
- package/dist/server/client-state.js +41 -0
- package/dist/server/compact-context-tool.js +10 -9
- package/dist/server/conversation-read-tool.js +7 -8
- package/dist/server/conversation-touches.js +19 -0
- package/dist/server/delegate-task.js +10 -14
- package/dist/server/dsh/dsh-agent-service.js +116 -12
- package/dist/server/edit-soft-tool.js +10 -12
- package/dist/server/eval-tool.js +26 -6
- package/dist/server/goal-evidence.js +173 -0
- package/dist/server/goal-service.js +78 -15
- package/dist/server/hashline-engine.js +198 -31
- package/dist/server/index.js +55 -9
- package/dist/server/load-tools-tool.js +100 -0
- package/dist/server/lsp-tool.js +10 -16
- package/dist/server/marker-service.js +53 -12
- package/dist/server/markers/builtins/action.js +108 -0
- package/dist/server/markers/index.js +4 -1
- package/dist/server/model-enrich.js +2 -0
- package/dist/server/patch-remote-catalog.js +28 -10
- package/dist/server/patch-tool.js +74 -38
- package/dist/server/plan-manager.js +71 -30
- package/dist/server/plan-mode.js +7 -6
- package/dist/server/plugin-api-catalog.js +10 -3
- package/dist/server/plugin-conversation-view.js +47 -0
- package/dist/server/plugins.js +113 -26
- package/dist/server/present-files-tool.js +10 -11
- package/dist/server/preset-fields.js +693 -0
- package/dist/server/preset-share.js +1178 -0
- package/dist/server/prompt-composer.js +23 -9
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/read-tool.js +8 -10
- package/dist/server/resolve-global-sdk.js +80 -18
- package/dist/server/schedule-agent-tool.js +147 -146
- package/dist/server/sdk-origin.js +125 -37
- package/dist/server/settings-service.js +103 -84
- package/dist/server/skill-tool.js +3 -4
- package/dist/server/subagents.js +15 -22
- package/dist/server/terminals.js +29 -39
- package/dist/server/tool-approval.js +3 -1
- package/dist/server/tool-manager.js +63 -27
- package/dist/server/tool-prompt-overrides.js +158 -0
- package/dist/server/tool-prompts.js +42 -0
- package/dist/server/tool-signature.js +104 -0
- package/dist/server/update-check.js +0 -15
- package/dist/server/workspace-snapshot.js +42 -11
- package/package.json +5 -3
- package/plugin-sdk/README.md +8 -4
- package/plugin-sdk/import-check.mjs +210 -0
- package/plugin-sdk/index.d.ts +4 -1
- package/plugin-sdk/index.mjs +1 -0
- package/plugins/catalog.json +33 -2
- package/themes/zhupi-dark.css +1 -1
- package/themes/zhupi.css +1 -1
- package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
- package/web/dist/assets/index-B-E2EM_0.css +1 -0
- package/web/dist/assets/index-BYumAaGi.js +379 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-2jDtjHvW.css +0 -1
- package/web/dist/assets/index-BjdK7s1M.js +0 -368
|
@@ -24,9 +24,9 @@ import { homedir } from "node:os";
|
|
|
24
24
|
import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
|
|
25
25
|
import { fileURLToPath } from "node:url";
|
|
26
26
|
import { writeAtomicSync } from "./atomic-file.js";
|
|
27
|
-
import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashToolDefinition, createEditToolDefinition, createLocalBashOperations, createWriteToolDefinition, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
|
|
27
|
+
import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashToolDefinition, createEditToolDefinition, createLocalBashOperations, createWriteToolDefinition, getAgentDir, SessionManager, VERSION, estimateTokens, } from "@earendil-works/pi-coding-agent";
|
|
28
28
|
import { Type } from "typebox";
|
|
29
|
-
import { BgServerTracker } from "./bg-servers.js";
|
|
29
|
+
import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
|
|
30
30
|
import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
|
|
31
31
|
import { checkPluginUpdates } from "./plugin-updater.js";
|
|
32
32
|
import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
|
|
@@ -35,9 +35,12 @@ import { COMPACTION_PENDING_TYPE, looksLikeChainCorruption, makeCompactionMarker
|
|
|
35
35
|
import { DANGLING_TOOL_RESULT_TEXT, DANGLING_TOOL_RESULT_TEXT_EN, findDanglingToolCalls, healDanglingToolCallFile, } from "./dangling-tools.js";
|
|
36
36
|
import { removeQueuedByIndexOrText } from "./queue-utils.js";
|
|
37
37
|
import { syncPluginToolsIntoSession } from "./plugins.js";
|
|
38
|
+
import { modelChangeKey, pickClientConversation, pickLatestClientSnapshot } from "./plugin-conversation-view.js";
|
|
38
39
|
import { denialText, } from "./plugin-tool-guard.js";
|
|
40
|
+
import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
|
|
39
41
|
import { SettingsService } from "./settings-service.js";
|
|
40
42
|
import { GoalService, buildDiffFingerprint, extractErrorSnippetFromSession, lastToolNameOfSession, } from "./goal-service.js";
|
|
43
|
+
import { buildEvidenceDigest, sessionMessagesOf } from "./goal-evidence.js";
|
|
41
44
|
import { MarkerService } from "./marker-service.js";
|
|
42
45
|
import { SlashCommandsService, parseSlash } from "./slash-commands.js";
|
|
43
46
|
import { ModelAdminService } from "./model-admin.js";
|
|
@@ -58,7 +61,9 @@ import { goalReviewDenial, shouldDeferPromptForReview } from "./goal-review-gate
|
|
|
58
61
|
import { readPlanModeFromSession, readPlanFromSession } from "./permission-preset.js";
|
|
59
62
|
import { readDelegateModeFromSession } from "./permission-preset.js";
|
|
60
63
|
import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
|
|
61
|
-
import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, BROWSER_PAGE_TOOL_NAME, effectiveDisabledAgentTools, isAgentToolEnabled, isTerminalGuidanceOn, localizedName, MARKERS_LIST_TOOL_NAME, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PLAN_UPDATE_TOOL_NAME, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
|
|
64
|
+
import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, BROWSER_PAGE_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, localizedName, MARKERS_LIST_TOOL_NAME, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PLAN_UPDATE_TOOL_NAME, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
|
|
65
|
+
import { makeLoadToolsTool } from "./load-tools-tool.js";
|
|
66
|
+
import { formatCompactSignature } from "./tool-signature.js";
|
|
62
67
|
import { WebUIContext } from "./webui-context.js";
|
|
63
68
|
import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, softCapToReserve } from "./soft-cap.js";
|
|
64
69
|
import { pruneContextHierarchically } from "./context-budget.js";
|
|
@@ -76,6 +81,8 @@ import { makeCompactContextTool, buildCompactionInstructions, DEFAULT_KEEP_RECEN
|
|
|
76
81
|
import { disposeAllEvalKernels, disposeEvalSession, makeEvalTool } from "./eval-tool.js";
|
|
77
82
|
// 工具定义说明的归一化(工具卡右键 → 「显示工具详细信息」,见 getToolInfo)。
|
|
78
83
|
import { normalizeToolInfo } from "./tool-info.js";
|
|
84
|
+
// 逐工具文案覆盖(设置页「工具」区可编辑 description/snippet/guidelines)。
|
|
85
|
+
import { applyToolPromptOverrides, effectiveToolPrompt, toolPromptOverrideOf, } from "./tool-prompt-overrides.js";
|
|
79
86
|
import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
|
|
80
87
|
import { makeDelegateTaskTool } from "./delegate-task.js";
|
|
81
88
|
import { makeConversationReadTool, parseTranscriptLines, toTranscriptInput, } from "./conversation-read-tool.js";
|
|
@@ -84,11 +91,11 @@ import { ClaimStore, matchClaims, mergeTouchSidecar, readTouchSidecar, removeTou
|
|
|
84
91
|
import { makeClaimFilesTool } from "./claim-files-tool.js";
|
|
85
92
|
import { makeSkillTool } from "./skill-tool.js";
|
|
86
93
|
import { getCompactedMessages } from "./compacted-history.js";
|
|
87
|
-
import {
|
|
94
|
+
import { makeScheduleTool } from "./schedule-agent-tool.js";
|
|
88
95
|
import { makePatchTool } from "./patch-tool.js";
|
|
89
96
|
import { makeLspTool } from "./lsp-tool.js";
|
|
90
97
|
import { sameSessionFile } from "./scheduler-tasks.js";
|
|
91
|
-
import { buildAttachmentMessages, parseModelSpec } from "./attachments.js";
|
|
98
|
+
import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
|
|
92
99
|
import { formatQuotedPrompt, readTextQuote } from "./text-quote.js";
|
|
93
100
|
import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
|
|
94
101
|
import { isNotRepoError, scmCommitContext } from "./scm.js";
|
|
@@ -130,6 +137,25 @@ const STALL_NOTIFY_MS = (() => {
|
|
|
130
137
|
const v = Number(process.env.PI_WEB_STALL_NOTIFY_MS);
|
|
131
138
|
return Number.isFinite(v) && v >= 0 ? v : 180_000;
|
|
132
139
|
})();
|
|
140
|
+
/** 断连残骸(浏览器全断开、只剩服务端残留会话)的 elsewhere 行宽限期:宽限期内仍
|
|
141
|
+
* 下发给其他页面(标 ownerOffline、照样可接管),过后按 issue #291 消失。
|
|
142
|
+
*
|
|
143
|
+
* 为什么必须有这段宽限:手机端「run 途中关页面 → run 在服务端继续跑完」之后,
|
|
144
|
+
* 换一台设备打开网页,既看不到「另一处」行(残骸 sinkCount=0 被 #291 跳过),
|
|
145
|
+
* 也没法过户;只能去历史对话里开 —— 而残留 runtime 仍持有那份转录,历史里开
|
|
146
|
+
* 等于给同一份 JSONL 造第二个 writer(历史分叉的温床)。宽限期够换设备接管。
|
|
147
|
+
* Override: PI_WEB_OFFLINE_ROWS_TTL_MS(毫秒;0/off/false/no = 不下发离线行 = 旧
|
|
148
|
+
* 口径;上限 6 小时,防 env 写出超长定时器)。 */
|
|
149
|
+
const OFFLINE_ROW_TTL_MS = (() => {
|
|
150
|
+
const raw = String(process.env.PI_WEB_OFFLINE_ROWS_TTL_MS ?? "")
|
|
151
|
+
.trim()
|
|
152
|
+
.toLowerCase();
|
|
153
|
+
if (raw === "0" || raw === "off" || raw === "false" || raw === "no")
|
|
154
|
+
return 0;
|
|
155
|
+
const v = Number(raw);
|
|
156
|
+
const ms = Number.isFinite(v) && v > 0 ? v : 30 * 60_000;
|
|
157
|
+
return Math.min(ms, 6 * 60 * 60_000);
|
|
158
|
+
})();
|
|
133
159
|
/** Serialization-cache soft cap per conversation (see serializeCachedFor /
|
|
134
160
|
* pruneMessageCache). Cached UiMessage objects are pure-function results, so a
|
|
135
161
|
* miss only costs a recompute — but a miss on a message that is STILL in the
|
|
@@ -241,24 +267,10 @@ lang = () => "en") {
|
|
|
241
267
|
return {
|
|
242
268
|
name: tool.name,
|
|
243
269
|
label: tool.label,
|
|
244
|
-
description:
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
persist: Type.Optional(Type.Boolean({
|
|
249
|
-
description: "Ignored in native mode (no terminal). Only meaningful when the terminal-backed bash is active.",
|
|
250
|
-
})),
|
|
251
|
-
head: Type.Optional(Type.Integer({
|
|
252
|
-
minimum: 1,
|
|
253
|
-
maximum: 5000,
|
|
254
|
-
description: "Only return the FIRST N lines of output (like `| head -N`).",
|
|
255
|
-
})),
|
|
256
|
-
tail: Type.Optional(Type.Integer({
|
|
257
|
-
minimum: 1,
|
|
258
|
-
maximum: 5000,
|
|
259
|
-
description: "Only return the LAST N lines of output (like `| tail -N`).",
|
|
260
|
-
})),
|
|
261
|
-
}),
|
|
270
|
+
description: BASH_DESCRIPTION,
|
|
271
|
+
promptSnippet: BASH_PROMPT_SNIPPET,
|
|
272
|
+
promptGuidelines: BASH_PROMPT_GUIDELINES,
|
|
273
|
+
parameters: BASH_PARAMETERS,
|
|
262
274
|
prepareArguments: tool.prepareArguments,
|
|
263
275
|
executionMode: tool.executionMode,
|
|
264
276
|
execute: async (toolCallId, params, signal, onUpdate, ctx) => {
|
|
@@ -276,15 +288,13 @@ lang = () => "en") {
|
|
|
276
288
|
* 动态分流 bash:按「默认 bash 覆盖」设置(terminalBash)在调用时决定走哪套——
|
|
277
289
|
* 关 = 原生 SDK bash(纯进程、不开终端);开 = 终端接管 bash(persist 决定一次性/
|
|
278
290
|
* 持久)。开关因此即时生效(customTools 固定于 runtime 创建,不能在创建时二选一)。
|
|
291
|
+
*
|
|
292
|
+
* 提示词不在此覆盖:两条路径共用 server/tool-prompts.ts 的那一份(单源),
|
|
293
|
+
* 覆盖 description 正是当年终端版文案被写死却不生效的成因。
|
|
279
294
|
*/
|
|
280
295
|
export function makeAdaptiveBashTool(killable, terminalBacked, useTerminal) {
|
|
281
296
|
return {
|
|
282
297
|
...killable,
|
|
283
|
-
description: "Run a shell command and return its full output plus exit code. Behavior depends on the「default bash override」setting (terminalBash):\n" +
|
|
284
|
-
"OFF → runs natively (process spawn, no terminal); persist has no effect.\n" +
|
|
285
|
-
"ON → runs in a visible terminal. persist=true keeps the 'ai-bash' terminal alive (shell state cd/venv/ssh retained across calls); persist=false (default) is a one-shot terminal whose output stays viewable.\n" +
|
|
286
|
-
"Run the bare command — never pipe through head/tail/more/less (use the head/tail params; pipes hide live progress). For interactive commands (REPLs, y/n prompts) set persist=true and drive them with terminal_input / terminal_key.",
|
|
287
|
-
promptSnippet: "run shell commands",
|
|
288
298
|
execute: (id, params, signal, onUpdate, ctx) => {
|
|
289
299
|
const p = params;
|
|
290
300
|
// Windows 下 ConPTY 架构限制(MSYS2 全局控制台上限 128,且高频创建销毁容易句柄耗尽/卡顿):
|
|
@@ -384,6 +394,22 @@ export function withDelegationGate(def, delegateMode, getLang) {
|
|
|
384
394
|
* - 用户选择 deny: 阻断并告知模型
|
|
385
395
|
* 3. post guard 合并(脱敏/补上下文)。
|
|
386
396
|
*/
|
|
397
|
+
/**
|
|
398
|
+
* 把「可能晚一点才注入」的插件守卫包成**调用时解析**的代理。
|
|
399
|
+
*
|
|
400
|
+
* 为什么需要它(P1-5 的真实缺口):`withToolGuard` 在建工具定义时就把 `opts.guard`
|
|
401
|
+
* 捕进了闭包,而 runtime 是在 `ClientSession.create()` 里建的、`cs.toolGuard` 却是在
|
|
402
|
+
* `AgentService.attach()` 末尾才赋值 —— 直接传 `this.toolGuard` 会把 `undefined`
|
|
403
|
+
* 永久固化进那条对话的工具里,于是「attach 时恢复出来的那条对话」永远不受
|
|
404
|
+
* 插件 `onToolPre/onToolPost` 约束(只有新建/切换对话才带上)。代理每次调用才解析,
|
|
405
|
+
* 与赋值时序无关;未注入时逐字等价于直通(allow / undefined)。
|
|
406
|
+
*/
|
|
407
|
+
export function makeLateToolGuard(get) {
|
|
408
|
+
return {
|
|
409
|
+
pre: (req, lang) => get()?.pre(req, lang) ?? Promise.resolve({ verdict: { decision: "allow" } }),
|
|
410
|
+
post: (req, lang) => get()?.post(req, lang) ?? Promise.resolve(undefined),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
387
413
|
export function withToolGuard(def, opts) {
|
|
388
414
|
const guard = opts.guard;
|
|
389
415
|
const toolName = opts.toolName;
|
|
@@ -433,11 +459,13 @@ export function withToolGuard(def, opts) {
|
|
|
433
459
|
};
|
|
434
460
|
}
|
|
435
461
|
// 3. 决定是否需要弹窗审批(系统高危 ask 优先于插件通用 ask,防止恶意或低危插件掩盖高危告警)
|
|
462
|
+
let approvalHits;
|
|
436
463
|
if (danger?.dangerous) {
|
|
437
464
|
needApproval = true;
|
|
438
465
|
approvalReason = danger.reason;
|
|
439
466
|
approvalReasonEn = danger.reasonEn;
|
|
440
467
|
approvalCategory = danger.category;
|
|
468
|
+
approvalHits = danger.hits;
|
|
441
469
|
}
|
|
442
470
|
else if (pre?.verdict.decision === "ask") {
|
|
443
471
|
needApproval = true;
|
|
@@ -449,7 +477,7 @@ export function withToolGuard(def, opts) {
|
|
|
449
477
|
let effectiveParams = params;
|
|
450
478
|
let userEdited = false;
|
|
451
479
|
if (needApproval && opts.askApproval) {
|
|
452
|
-
const res = await opts.askApproval(toolCallId, toolName, params, approvalReason, approvalReasonEn, conversationId, approvalCategory);
|
|
480
|
+
const res = await opts.askApproval(toolCallId, toolName, params, approvalReason, approvalReasonEn, conversationId, approvalCategory, approvalHits);
|
|
453
481
|
if (res.decision === "deny") {
|
|
454
482
|
const reasonText = res.reason ? ` 原因:${res.reason}` : "";
|
|
455
483
|
const reasonTextEn = res.reason ? ` Reason: ${res.reason}` : "";
|
|
@@ -560,7 +588,7 @@ function wrapWriteToolWithPermission(cwd, getPermission, getRoots, getLang, askA
|
|
|
560
588
|
};
|
|
561
589
|
}
|
|
562
590
|
if (danger.dangerous) {
|
|
563
|
-
const res = await askApproval(toolCallId, "write", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category);
|
|
591
|
+
const res = await askApproval(toolCallId, "write", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category, danger.hits);
|
|
564
592
|
if (res.decision === "deny") {
|
|
565
593
|
return {
|
|
566
594
|
content: [
|
|
@@ -592,6 +620,21 @@ function wrapWriteToolWithPermission(cwd, getPermission, getRoots, getLang, askA
|
|
|
592
620
|
},
|
|
593
621
|
};
|
|
594
622
|
}
|
|
623
|
+
/**
|
|
624
|
+
* `edit` 的模型可见主描述(仅无扩展覆盖时的基底用;有扩展 edit 时保留它自己的文案)。
|
|
625
|
+
*
|
|
626
|
+
* SDK 自带的描述与其自带 guidelines 几乎逐条复述(oldText 要唯一匹配 / 多处改动合成一次调用 /
|
|
627
|
+
* 不要垫大段未改区域都说两遍),单条信息重复进上下文。这里只留一句「做什么」,细节交给
|
|
628
|
+
* guidelines(它们是 SDK 的,本模块不碰)。
|
|
629
|
+
*/
|
|
630
|
+
const EDIT_DESCRIPTION = "Edit a single file by exact text replacement: every edits[].oldText must uniquely match the original file.";
|
|
631
|
+
/** `edit` 的精简 guidelines(同上:只用于无扩展覆盖的基底;与 SDK 四条规则一一对应,只去冗余措辞)。 */
|
|
632
|
+
const EDIT_GUIDELINES = [
|
|
633
|
+
"Use edit for precise changes; oldText must match exactly",
|
|
634
|
+
"When changing several separate locations in one file, put them in ONE call's edits[] instead of multiple calls",
|
|
635
|
+
"Each oldText matches the original file, not earlier edits in the same call — never overlapping or nested",
|
|
636
|
+
"Keep oldText small but unique; never pad with large unchanged regions",
|
|
637
|
+
];
|
|
595
638
|
/**
|
|
596
639
|
* 为 edit 工具包装会话级权限沙箱与人机协同审批(基底语义同 write)。
|
|
597
640
|
*/
|
|
@@ -643,7 +686,7 @@ function wrapEditToolWithPermission(cwd, getPermission, getRoots, getLang, askAp
|
|
|
643
686
|
};
|
|
644
687
|
}
|
|
645
688
|
if (danger.dangerous) {
|
|
646
|
-
const res = await askApproval(toolCallId, "edit", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category);
|
|
689
|
+
const res = await askApproval(toolCallId, "edit", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category, danger.hits);
|
|
647
690
|
if (res.decision === "deny") {
|
|
648
691
|
return {
|
|
649
692
|
content: [
|
|
@@ -724,7 +767,7 @@ function wrapEditSoftToolWithPermission(tool, cwd, getPermission, getRoots, getL
|
|
|
724
767
|
};
|
|
725
768
|
}
|
|
726
769
|
if (danger.dangerous) {
|
|
727
|
-
const res = await askApproval(toolCallId, "edit_soft", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category);
|
|
770
|
+
const res = await askApproval(toolCallId, "edit_soft", params, danger.reason, danger.reasonEn, getConversationId?.(), danger.category, danger.hits);
|
|
728
771
|
if (res.decision === "deny") {
|
|
729
772
|
return {
|
|
730
773
|
content: [
|
|
@@ -756,6 +799,35 @@ function wrapEditSoftToolWithPermission(tool, cwd, getPermission, getRoots, getL
|
|
|
756
799
|
},
|
|
757
800
|
};
|
|
758
801
|
}
|
|
802
|
+
/**
|
|
803
|
+
* 将 SoL-Pi 的 update_plan 步骤结构({ id, goal, status })标准化为 pi-web-ui 的 PlanStep[] 结构。
|
|
804
|
+
*/
|
|
805
|
+
export function normalizeSolPlanToPlanSteps(steps) {
|
|
806
|
+
if (!Array.isArray(steps))
|
|
807
|
+
return { steps: [] };
|
|
808
|
+
let activeStepId = null;
|
|
809
|
+
const normalizedSteps = steps.map((s, idx) => {
|
|
810
|
+
const step = (s && typeof s === "object" ? s : {});
|
|
811
|
+
const id = typeof step.id === "string" && step.id ? step.id : String(idx + 1);
|
|
812
|
+
const rawTitle = typeof step.goal === "string" ? step.goal : typeof step.title === "string" ? step.title : `Step ${id}`;
|
|
813
|
+
const rawStatus = typeof step.status === "string" ? step.status : "pending";
|
|
814
|
+
let status = "pending";
|
|
815
|
+
if (rawStatus === "completed" || rawStatus === "done") {
|
|
816
|
+
status = "done";
|
|
817
|
+
}
|
|
818
|
+
else if (rawStatus === "in_progress") {
|
|
819
|
+
status = "in_progress";
|
|
820
|
+
if (!activeStepId)
|
|
821
|
+
activeStepId = id;
|
|
822
|
+
}
|
|
823
|
+
else if (rawStatus === "failed") {
|
|
824
|
+
status = "failed";
|
|
825
|
+
}
|
|
826
|
+
const description = typeof step.description === "string" ? step.description : undefined;
|
|
827
|
+
return { id, title: rawTitle, status, ...(description ? { description } : {}) };
|
|
828
|
+
});
|
|
829
|
+
return { steps: normalizedSteps, activeStepId };
|
|
830
|
+
}
|
|
759
831
|
/**
|
|
760
832
|
* 结构化任务执行计划更新工具(plan_update)— Plan Mode / Step State Machine。
|
|
761
833
|
*/
|
|
@@ -763,12 +835,12 @@ export function makePlanUpdateTool(planManager, getActiveConvTarget, emit, flush
|
|
|
763
835
|
return {
|
|
764
836
|
name: PLAN_UPDATE_TOOL_NAME,
|
|
765
837
|
label: "plan_update",
|
|
766
|
-
description: "Update the structured task plan / step state machine (Plan Mode)
|
|
767
|
-
promptSnippet: "
|
|
838
|
+
description: "Update the structured task plan / step state machine (Plan Mode) and track progress (pending -> in_progress -> done/failed).",
|
|
839
|
+
promptSnippet: "track decision-ready steps, file touch list, and live status",
|
|
768
840
|
promptGuidelines: [
|
|
769
|
-
"
|
|
770
|
-
|
|
771
|
-
"
|
|
841
|
+
"Use plan_update early on non-trivial tasks to outline decision-ready steps before coding",
|
|
842
|
+
"Per step: discovery conclusions, files to be touched (File Touch List), rollback strategy",
|
|
843
|
+
"Update step status as work progresses for real-time visibility",
|
|
772
844
|
],
|
|
773
845
|
parameters: Type.Object({
|
|
774
846
|
steps: Type.Array(Type.Object({
|
|
@@ -780,7 +852,7 @@ export function makePlanUpdateTool(planManager, getActiveConvTarget, emit, flush
|
|
|
780
852
|
description: "Step status: pending | in_progress | done | failed (default: pending)",
|
|
781
853
|
})),
|
|
782
854
|
description: Type.Optional(Type.String({
|
|
783
|
-
description: "Optional
|
|
855
|
+
description: "Optional step detail: acceptance criteria, files touched, rollback note.",
|
|
784
856
|
})),
|
|
785
857
|
}), { description: "List of plan steps" }),
|
|
786
858
|
activeStepId: Type.Optional(Type.String({ description: "ID of the step currently being executed" })),
|
|
@@ -842,7 +914,7 @@ function wrapBashToolWithPermission(tool, getPermission, getLang) {
|
|
|
842
914
|
function makeMarkersListTool(getActiveId, markerSvc) {
|
|
843
915
|
return {
|
|
844
916
|
name: MARKERS_LIST_TOOL_NAME,
|
|
845
|
-
promptSnippet: "list
|
|
917
|
+
promptSnippet: "list inline-marker tasks (read-only; writes use [[todo:...]])",
|
|
846
918
|
label: "List marker state",
|
|
847
919
|
description: "Read-only query of inline marker state. All WRITE operations must use inline markers ([[todo:new:...]] etc.) in the reply body — never this tool.",
|
|
848
920
|
parameters: Type.Object({
|
|
@@ -915,17 +987,15 @@ ownerId) {
|
|
|
915
987
|
name: "ask_user_question",
|
|
916
988
|
label: "Ask the user",
|
|
917
989
|
description: "Ask the user 1-3 focused questions to clarify requirements, confirm decisions, or choose options. " +
|
|
918
|
-
"Provide 2-4 choices (recommended first) with concise tradeoffs. " +
|
|
919
990
|
"Renders a rich browser dialog; resumes on submit or cancel.",
|
|
920
|
-
promptSnippet: "
|
|
991
|
+
promptSnippet: "clarify ambiguous requirements or confirm a decision with the user",
|
|
921
992
|
promptGuidelines: [
|
|
922
|
-
"When requirements are ambiguous,
|
|
923
|
-
"strictly 1 to 3 focused questions (prefer 1), 2-4 choices with recommended option first, and explain impact/tradeoff concisely",
|
|
993
|
+
"When requirements are ambiguous, clarify with ask_user_question: 1 to 3 focused questions (prefer 1), 2-4 choices with the recommended option first, each with a concise impact/tradeoff",
|
|
924
994
|
"A cancelled question comes back as a tool error — respect it without immediately re-asking",
|
|
925
995
|
],
|
|
926
996
|
parameters: Type.Object({
|
|
927
997
|
questions: Type.Array(QuestionSchema, {
|
|
928
|
-
description: "
|
|
998
|
+
description: "Questions to ask (prefer 1).",
|
|
929
999
|
minItems: 1,
|
|
930
1000
|
maxItems: 3,
|
|
931
1001
|
}),
|
|
@@ -1040,28 +1110,20 @@ ownerId) {
|
|
|
1040
1110
|
name: BROWSER_PAGE_TOOL_NAME,
|
|
1041
1111
|
label: "Browser page",
|
|
1042
1112
|
description: [
|
|
1043
|
-
|
|
1044
|
-
"
|
|
1045
|
-
"
|
|
1046
|
-
' read — { what?: "text" | "html" | "title" | "url" | "query", selector?, all? }',
|
|
1047
|
-
" click — { selector, index? }",
|
|
1048
|
-
" type — { selector, text, clear?, submit? } (submit: true presses Enter)",
|
|
1049
|
-
" scroll — { selector?, to?: { x, y }, by?: { x, y } }",
|
|
1050
|
-
" goto — { url }",
|
|
1051
|
-
" wait — { selector?, text?, timeoutMs? } waits for the element/text to appear; that timeoutMs is the op's own",
|
|
1052
|
-
" eval — { code } runs JS inside the page (extension-side switch, off by default)",
|
|
1053
|
-
"Op options that are not fields of this tool (e.g. read's `limit`) fall back to the extension's defaults. `target` selects the page by origin when more than one is allowed; `timeoutMs` is how long the SERVER waits for the browser (1000-120000, default 30000) before failing the call.",
|
|
1113
|
+
"Read or act on a page in the USER'S OWN browser via the pi-web-ui page-picker extension (the server only forwards).",
|
|
1114
|
+
"Only the parameters below exist — an op option that is not a field here (e.g. type's submit) is unavailable.",
|
|
1115
|
+
"ops: pages | read (what? selector? all?) | click (selector? index?) | type (selector text) | scroll (selector?) | goto (url) | wait (selector? text? timeoutMs?) | eval (code) | shot (maxEdge?)",
|
|
1054
1116
|
].join("\n"),
|
|
1055
|
-
promptSnippet: "
|
|
1117
|
+
promptSnippet: "operate a page in the user's browser (page-picker extension)",
|
|
1056
1118
|
promptGuidelines: [
|
|
1057
1119
|
"Only use browser_page when the user asked you to read or act on a page in their browser; " +
|
|
1058
1120
|
"never click or type on their pages on your own initiative",
|
|
1059
|
-
'Start with op:"pages"
|
|
1060
|
-
"
|
|
1121
|
+
'Start with op:"pages"; the target page must already be allowed in the page-picker extension — ' +
|
|
1122
|
+
"if it fails, tell the user what to enable instead of retrying.",
|
|
1061
1123
|
],
|
|
1062
1124
|
parameters: Type.Object({
|
|
1063
1125
|
op: Type.String({
|
|
1064
|
-
description: "Action
|
|
1126
|
+
description: "Action to perform (extension-side).",
|
|
1065
1127
|
}),
|
|
1066
1128
|
target: Type.Optional(Type.String({
|
|
1067
1129
|
description: "Target page origin (e.g. https://example.com). Only needed when several pages are allowed.",
|
|
@@ -1071,15 +1133,15 @@ ownerId) {
|
|
|
1071
1133
|
text: Type.Optional(Type.String({ description: "For op:type — the text to enter; for op:wait — the text to wait for." })),
|
|
1072
1134
|
url: Type.Optional(Type.String({ description: "For op:goto — the absolute URL to navigate to." })),
|
|
1073
1135
|
code: Type.Optional(Type.String({
|
|
1074
|
-
description: "For op:eval —
|
|
1136
|
+
description: "For op:eval — JS to run in the page (extension-side switch, disabled by default).",
|
|
1075
1137
|
})),
|
|
1076
1138
|
all: Type.Optional(Type.Boolean({ description: "For op:read — return every match instead of only the first one." })),
|
|
1077
1139
|
index: Type.Optional(Type.Number({ description: "For op:click — which match to click (default: 0)." })),
|
|
1078
1140
|
maxEdge: Type.Optional(Type.Number({
|
|
1079
|
-
description: "For op:shot — max
|
|
1141
|
+
description: "For op:shot — max px of the longer side (320-1568, default 1280).",
|
|
1080
1142
|
})),
|
|
1081
1143
|
timeoutMs: Type.Optional(Type.Number({
|
|
1082
|
-
description: "How long the server waits for the browser
|
|
1144
|
+
description: "How long the server waits for the browser (1000-120000 ms, default 30000).",
|
|
1083
1145
|
})),
|
|
1084
1146
|
}),
|
|
1085
1147
|
execute: async (_id, params, signal) => {
|
|
@@ -1268,6 +1330,25 @@ function extractAssistantTextFromContent(content) {
|
|
|
1268
1330
|
.join("\n");
|
|
1269
1331
|
}
|
|
1270
1332
|
export { workspacePath };
|
|
1333
|
+
// ---------------------------------------------------------------------------
|
|
1334
|
+
// Per-client persisted UI state (<dataDir>/client-state.json)
|
|
1335
|
+
// ---------------------------------------------------------------------------
|
|
1336
|
+
/**
|
|
1337
|
+
* One open conversation (chat thread) of a client. Each conversation owns its
|
|
1338
|
+
* OWN AgentSessionRuntime, so starting a new chat or switching between chats
|
|
1339
|
+
* never interrupts another conversation's in-flight run.
|
|
1340
|
+
*
|
|
1341
|
+
* 导出给过户载荷类型(TakeoverPayload)用:对话对象本身在会话之间整体搬迁。
|
|
1342
|
+
*/
|
|
1343
|
+
/** 描述首句(延迟加载目录里没 promptSnippet 时的回落摘要)。 */
|
|
1344
|
+
function firstSentence(description) {
|
|
1345
|
+
const text = (description ?? "").trim();
|
|
1346
|
+
if (!text)
|
|
1347
|
+
return "";
|
|
1348
|
+
const cut = text.split(/\n|[.。](?=\s|$)/)[0]?.trim() ?? "";
|
|
1349
|
+
const head = cut || text;
|
|
1350
|
+
return head.length > 160 ? `${head.slice(0, 160)}…` : head;
|
|
1351
|
+
}
|
|
1271
1352
|
/** 轨迹事件 payload 封顶(可直接广播/持久化,不撑爆 storage.json)。 */
|
|
1272
1353
|
const RUN_TASK_CAP = 500;
|
|
1273
1354
|
const RUN_ARGS_CAP = 4000;
|
|
@@ -1825,6 +1906,9 @@ export class ClientSession {
|
|
|
1825
1906
|
convs = new Map();
|
|
1826
1907
|
activeId = "";
|
|
1827
1908
|
convSeq = 0;
|
|
1909
|
+
/** 模型变更事件(#542)已发过的去重键:convId → `modelChangeKey(snap)`。重连重放
|
|
1910
|
+
* 同一个 set_model、或重复点同一个模型,不会重复触发插件订阅者。 */
|
|
1911
|
+
pluginModelKeys = new Map();
|
|
1828
1912
|
/** One ModelRuntime shared by all conversations — the model chosen in the
|
|
1829
1913
|
* top bar applies to every chat, not just the one that set it. Seeded by
|
|
1830
1914
|
* the first conversation and reused by later ones. */
|
|
@@ -1869,6 +1953,8 @@ export class ClientSession {
|
|
|
1869
1953
|
isDisposed: () => this.disposed,
|
|
1870
1954
|
// 插件注册的常驻任务(host.registerBackgroundTask)并入同一「后台任务」面板。
|
|
1871
1955
|
pluginTasks: () => this.pluginBgTasksProvider?.() ?? [],
|
|
1956
|
+
// 「自动清理遗留实例」阈值(分钟;0 = 关):每轮定时器实时读设置。
|
|
1957
|
+
cleanupMinutes: () => this.settingsSvc.current.bgAutoCleanupMin ?? 0,
|
|
1872
1958
|
});
|
|
1873
1959
|
/** index.ts 注入(经 AgentService 拷贝到每个新会话):把 SDK 工具执行事件转发给
|
|
1874
1960
|
* 插件(PluginManager.emitToolEvent)。未设置时不做任何事。 */
|
|
@@ -1876,12 +1962,29 @@ export class ClientSession {
|
|
|
1876
1962
|
/** index.ts 注入(P1-5,经 AgentService 拷贝到每个新会话):bash/read 执行前后的
|
|
1877
1963
|
* 插件拦截(PluginManager.evaluateToolPre/evaluateToolPost)。未设置时直通。 */
|
|
1878
1964
|
toolGuard = undefined;
|
|
1965
|
+
/**
|
|
1966
|
+
* 工具定义用的**延迟绑定**守卫(`guard:` 参数一律传这个,不要直接传 this.toolGuard)。
|
|
1967
|
+
*
|
|
1968
|
+
* 原因:`withToolGuard` 在**建工具定义时**就把 `opts.guard` 捕进闭包了,而 runtime
|
|
1969
|
+
* 是在 `ClientSession.create()` 里建的,`cs.toolGuard` 却是在 attach 末尾才赋值
|
|
1970
|
+
* (见 AgentService.attach 的“Forward hooks”段)—— 直接传 this.toolGuard 会把
|
|
1971
|
+
* `undefined` 永久固化进那条对话的工具里,导致「attach 时恢复出来的那条对话」
|
|
1972
|
+
* **永远不受插件 onToolPre/onToolPost 约束**(新建/切换对话才带上)。
|
|
1973
|
+
* 这个代理每次调用才解析真正的守卫,与赋值时序无关。
|
|
1974
|
+
*/
|
|
1975
|
+
get lateToolGuard() {
|
|
1976
|
+
return this.#lateGuard;
|
|
1977
|
+
}
|
|
1978
|
+
#lateGuard = makeLateToolGuard(() => this.toolGuard);
|
|
1879
1979
|
/** index.ts 注入:把运行轨迹事件转发给插件(PluginManager.emitRunEvent,
|
|
1880
1980
|
* 轨迹视图插件靠它聚合时间线)。未设置时不做任何事。 */
|
|
1881
1981
|
onRunEvent = undefined;
|
|
1882
1982
|
/** index.ts 注入:当前打开对话变了(切历史会话/切 running 对话/新对话)时
|
|
1883
1983
|
* 通知插件(PluginManager.emitConversationChanged)——轨迹视图靠它重拉。 */
|
|
1884
1984
|
onConversationChanged = undefined;
|
|
1985
|
+
/** index.ts 注入:某客户端的对话模型切换成功(#542)——直接转发给
|
|
1986
|
+
* PluginManager.emitClientModelChanged(插件用 host.onClientModelChanged 订阅)。 */
|
|
1987
|
+
onClientModelChanged = undefined;
|
|
1885
1988
|
/** index.ts 注入:读取插件当前注册的 AI 工具(attach 时拷贝到每个新会话)。 */
|
|
1886
1989
|
pluginToolsProvider = undefined;
|
|
1887
1990
|
/** index.ts 经 AgentService 注入:内置调度存储(定时任务 Agent 工具用;未注入时工具直接报错)。 */
|
|
@@ -1896,7 +1999,15 @@ export class ClientSession {
|
|
|
1896
1999
|
appliedPluginToolNames = new Set();
|
|
1897
2000
|
/** The active conversation (all session operations target it). */
|
|
1898
2001
|
get conv() {
|
|
1899
|
-
|
|
2002
|
+
let conv = this.convs.get(this.activeId);
|
|
2003
|
+
if (!conv) {
|
|
2004
|
+
// 自愈:若 activeId 悬空,优先回退到现存的非子代理会话,其次任意现存会话
|
|
2005
|
+
const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
|
|
2006
|
+
if (fallback) {
|
|
2007
|
+
this.activeId = fallback.id;
|
|
2008
|
+
conv = fallback;
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
1900
2011
|
if (!conv)
|
|
1901
2012
|
throw new Error("no active conversation");
|
|
1902
2013
|
return conv;
|
|
@@ -2363,6 +2474,280 @@ export class ClientSession {
|
|
|
2363
2474
|
/** SDK APPEND_SYSTEM.md 内容(appendSystemPromptOverride 收到的 base)——
|
|
2364
2475
|
* composer 的 {{append}} 自动内容。仅主会话(无模板)记录。 */
|
|
2365
2476
|
lastSdkAppendFiles = [];
|
|
2477
|
+
/**
|
|
2478
|
+
* 延迟加载(工具按需加载)模式下,按 session 对象存「已加载」工具集。
|
|
2479
|
+
*
|
|
2480
|
+
* 为什么手 session 而不是对话 id:过户搬的就是 session 本体(见 take_over_conversation),
|
|
2481
|
+
* 集合跟它一起走;会话销毁后 WeakMap 自动回收,不需要清理钩子。
|
|
2482
|
+
*/
|
|
2483
|
+
lazyLoadedBySession = new WeakMap();
|
|
2484
|
+
/** 延迟加载总开关(设置项,默认开;DSH 无 pi 工具注册面,走自己的服务)。 */
|
|
2485
|
+
lazyLoadingOn() {
|
|
2486
|
+
return this.settingsSvc?.current.toolLazyLoading !== false;
|
|
2487
|
+
}
|
|
2488
|
+
/** 会话是否已有转录内容 —— 区分「刚建的新会话」(种子为空)与「从转录恢复的会话」
|
|
2489
|
+
* (种子 = 当时活跃的非核心工具,保证上次加载过什么就还是什么)。 */
|
|
2490
|
+
sessionHasTranscript(session) {
|
|
2491
|
+
try {
|
|
2492
|
+
return (session.state?.messages?.length ?? 0) > 0;
|
|
2493
|
+
}
|
|
2494
|
+
catch {
|
|
2495
|
+
return false;
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
/** 取(必要时建立)某 session 的已加载集合。 */
|
|
2499
|
+
lazyLoadedFor(session, seedFromActive) {
|
|
2500
|
+
const existing = this.lazyLoadedBySession.get(session);
|
|
2501
|
+
if (existing)
|
|
2502
|
+
return existing;
|
|
2503
|
+
const seed = [];
|
|
2504
|
+
if (seedFromActive) {
|
|
2505
|
+
const core = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
|
|
2506
|
+
try {
|
|
2507
|
+
for (const n of session.getActiveToolNames())
|
|
2508
|
+
if (!core.has(n))
|
|
2509
|
+
seed.push(n);
|
|
2510
|
+
}
|
|
2511
|
+
catch {
|
|
2512
|
+
/* session 未就绪:空集 = 只用核心工具 */
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
const set = new Set(seed);
|
|
2516
|
+
this.lazyLoadedBySession.set(session, set);
|
|
2517
|
+
return set;
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* 当前**未加载但可加载**的工具名录(名字 + 一行摘要)—— 供系统提示词的目录段
|
|
2521
|
+
* 与 `load_tools` 的数据源。
|
|
2522
|
+
*
|
|
2523
|
+
* 已按用户禁用名单 / 预设白名单 / 计划模式闸门过滤:目录里绝不能出现模型实际
|
|
2524
|
+
* 拿不到的工具,否则它会反复尝试加载。
|
|
2525
|
+
*/
|
|
2526
|
+
lazyToolCatalog(session, conv) {
|
|
2527
|
+
const empty = { names: [], snippets: {}, infos: [] };
|
|
2528
|
+
if (!session || !this.lazyLoadingOn())
|
|
2529
|
+
return empty;
|
|
2530
|
+
try {
|
|
2531
|
+
const all = this.allowedToolNames(session, conv);
|
|
2532
|
+
const active = new Set(session.getActiveToolNames());
|
|
2533
|
+
const names = [];
|
|
2534
|
+
const snippets = {};
|
|
2535
|
+
const infos = [];
|
|
2536
|
+
for (const name of all) {
|
|
2537
|
+
if (active.has(name) || name === LOAD_TOOLS_TOOL_NAME)
|
|
2538
|
+
continue;
|
|
2539
|
+
const def = session.getToolDefinition(name);
|
|
2540
|
+
const snippet = this.toolSnippetOf(def);
|
|
2541
|
+
if (snippet)
|
|
2542
|
+
snippets[name] = snippet;
|
|
2543
|
+
names.push(name);
|
|
2544
|
+
infos.push({ name, summary: snippet, description: def?.description, guidelines: def?.promptGuidelines });
|
|
2545
|
+
}
|
|
2546
|
+
return { names, snippets, infos };
|
|
2547
|
+
}
|
|
2548
|
+
catch {
|
|
2549
|
+
return empty;
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* 延迟加载下系统提示词里的工具目录:**全部可用工具**(含已加载),顺序 = 注册表顺序。
|
|
2554
|
+
*
|
|
2555
|
+
* 刻意不过滤已加载集合 —— 列表随加载变化会让系统提示词变,供应商的前缀缓存整段失效。
|
|
2556
|
+
* 「哪些已附 schema」由 function list(tools 数组)表达,那是追加式变化,缓存前缀不变。
|
|
2557
|
+
*/
|
|
2558
|
+
promptToolCatalog(session, conv) {
|
|
2559
|
+
const empty = {
|
|
2560
|
+
names: [],
|
|
2561
|
+
snippets: {},
|
|
2562
|
+
signatures: {},
|
|
2563
|
+
};
|
|
2564
|
+
if (!session || !this.lazyLoadingOn())
|
|
2565
|
+
return empty;
|
|
2566
|
+
try {
|
|
2567
|
+
const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME);
|
|
2568
|
+
const snippets = {};
|
|
2569
|
+
const signatures = {};
|
|
2570
|
+
for (const name of names) {
|
|
2571
|
+
const def = session.getToolDefinition(name);
|
|
2572
|
+
const snippet = this.toolSnippetOf(def);
|
|
2573
|
+
if (snippet)
|
|
2574
|
+
snippets[name] = snippet;
|
|
2575
|
+
if (def?.parameters) {
|
|
2576
|
+
const sig = formatCompactSignature(def.parameters);
|
|
2577
|
+
if (sig)
|
|
2578
|
+
signatures[name] = sig;
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
return { names, snippets, signatures };
|
|
2582
|
+
}
|
|
2583
|
+
catch {
|
|
2584
|
+
return empty;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
/** 当前可用(未被用户禁用 / 未被预设屏蔽 / 未被当前模式闸门拦截)的工具名,注册表顺序。 */
|
|
2588
|
+
allowedToolNames(session, conv) {
|
|
2589
|
+
const all = session.getAllTools().map((t) => t.name);
|
|
2590
|
+
const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2591
|
+
const allowed = new Set(filterToolsByPreset(all, preset));
|
|
2592
|
+
const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
|
|
2593
|
+
if (conv?.planMode === true)
|
|
2594
|
+
for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
|
|
2595
|
+
disabled.add(n);
|
|
2596
|
+
return all.filter((n) => allowed.has(n) && !disabled.has(n));
|
|
2597
|
+
}
|
|
2598
|
+
/** 工具在系统提示词里的一行摘要:用户覆盖 → 出厂 snippet → 描述首句。 */
|
|
2599
|
+
toolSnippetOf(def) {
|
|
2600
|
+
if (!def)
|
|
2601
|
+
return "";
|
|
2602
|
+
const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, def.name));
|
|
2603
|
+
return (eff.promptSnippet ?? "").trim() || firstSentence(eff.description);
|
|
2604
|
+
}
|
|
2605
|
+
/** 延迟加载下**永远活跃**的基线工具名(核心 + load_tools,按注册表顺序)。 */
|
|
2606
|
+
lazyBaselineNames(session) {
|
|
2607
|
+
let all = [];
|
|
2608
|
+
try {
|
|
2609
|
+
all = session.getAllTools().map((t) => t.name);
|
|
2610
|
+
}
|
|
2611
|
+
catch {
|
|
2612
|
+
return [];
|
|
2613
|
+
}
|
|
2614
|
+
const base = new Set([...LAZY_CORE_TOOL_NAMES, LOAD_TOOLS_TOOL_NAME]);
|
|
2615
|
+
return all.filter((n) => base.has(n));
|
|
2616
|
+
}
|
|
2617
|
+
/** `load_tools` 宿主(延迟加载):只管「现在能加载什么」与「加载」。 */
|
|
2618
|
+
loadToolsHost(ownerId) {
|
|
2619
|
+
return {
|
|
2620
|
+
listLoadable: () => this.lazyToolCatalog(this.sessionOfOwner(ownerId), this.convOfOwner(ownerId)).infos,
|
|
2621
|
+
listLoaded: () => {
|
|
2622
|
+
const session = this.sessionOfOwner(ownerId);
|
|
2623
|
+
if (!session)
|
|
2624
|
+
return [];
|
|
2625
|
+
try {
|
|
2626
|
+
return session.getActiveToolNames();
|
|
2627
|
+
}
|
|
2628
|
+
catch {
|
|
2629
|
+
return [];
|
|
2630
|
+
}
|
|
2631
|
+
},
|
|
2632
|
+
load: (names) => this.loadLazyTools(this.sessionOfOwner(ownerId), this.convOfOwner(ownerId), names),
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
/** 按 ownerId 解析会话/对话(调用瞬间解析,与问卷/页桥同口径)。 */
|
|
2636
|
+
sessionOfOwner(ownerId) {
|
|
2637
|
+
try {
|
|
2638
|
+
return (ownerId ? this.convs.get(ownerId)?.session : undefined) ?? this.conv?.session ?? this.session;
|
|
2639
|
+
}
|
|
2640
|
+
catch {
|
|
2641
|
+
return undefined;
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
convOfOwner(ownerId) {
|
|
2645
|
+
try {
|
|
2646
|
+
return (ownerId ? this.convs.get(ownerId) : undefined) ?? this.conv ?? undefined;
|
|
2647
|
+
}
|
|
2648
|
+
catch {
|
|
2649
|
+
return undefined;
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
/** `load_tools` 的执行体:校验 → 加入已加载集 → 重放门控(工具就此活跃)。 */
|
|
2653
|
+
loadLazyTools(session, conv, names) {
|
|
2654
|
+
const lang = this.getLang();
|
|
2655
|
+
const loaded = [];
|
|
2656
|
+
const rejected = [];
|
|
2657
|
+
if (!session) {
|
|
2658
|
+
return {
|
|
2659
|
+
loaded,
|
|
2660
|
+
rejected: names.map((name) => ({
|
|
2661
|
+
name,
|
|
2662
|
+
reason: pick(lang, "会话未就绪", "session not ready", "loadtools.notready"),
|
|
2663
|
+
})),
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
let all = [];
|
|
2667
|
+
try {
|
|
2668
|
+
all = session.getAllTools().map((t) => t.name);
|
|
2669
|
+
}
|
|
2670
|
+
catch {
|
|
2671
|
+
return {
|
|
2672
|
+
loaded,
|
|
2673
|
+
rejected: names.map((name) => ({
|
|
2674
|
+
name,
|
|
2675
|
+
reason: pick(lang, "会话未就绪", "session not ready", "loadtools.notready"),
|
|
2676
|
+
})),
|
|
2677
|
+
};
|
|
2678
|
+
}
|
|
2679
|
+
const known = new Set(all);
|
|
2680
|
+
const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2681
|
+
const allowed = new Set(filterToolsByPreset(all, preset));
|
|
2682
|
+
const disabled = new Set(effectiveDisabledAgentTools(this.settingsSvc.current));
|
|
2683
|
+
if (conv?.planMode === true)
|
|
2684
|
+
for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
|
|
2685
|
+
disabled.add(n);
|
|
2686
|
+
const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
|
|
2687
|
+
let changed = false;
|
|
2688
|
+
for (const name of names) {
|
|
2689
|
+
if (!known.has(name)) {
|
|
2690
|
+
rejected.push({
|
|
2691
|
+
name,
|
|
2692
|
+
reason: pick(lang, "未知工具名(看目录里的名字)", "unknown tool name (use a catalog name)", "loadtools.unknown"),
|
|
2693
|
+
});
|
|
2694
|
+
continue;
|
|
2695
|
+
}
|
|
2696
|
+
if (name === LOAD_TOOLS_TOOL_NAME) {
|
|
2697
|
+
rejected.push({ name, reason: pick(lang, "常驻工具,无需加载", "always available", "loadtools.always") });
|
|
2698
|
+
continue;
|
|
2699
|
+
}
|
|
2700
|
+
if (set.has(name)) {
|
|
2701
|
+
rejected.push({ name, reason: pick(lang, "已经加载过了", "already loaded", "loadtools.already") });
|
|
2702
|
+
continue;
|
|
2703
|
+
}
|
|
2704
|
+
if (disabled.has(name)) {
|
|
2705
|
+
rejected.push({
|
|
2706
|
+
name,
|
|
2707
|
+
reason: pick(lang, "已被关闭,或在当前模式下被拦截", "disabled, or blocked in the current mode", "loadtools.disabled"),
|
|
2708
|
+
});
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
if (!allowed.has(name)) {
|
|
2712
|
+
rejected.push({
|
|
2713
|
+
name,
|
|
2714
|
+
reason: pick(lang, "当前预设不允许使用它", "not allowed by the current preset", "loadtools.preset"),
|
|
2715
|
+
});
|
|
2716
|
+
continue;
|
|
2717
|
+
}
|
|
2718
|
+
set.add(name);
|
|
2719
|
+
changed = true;
|
|
2720
|
+
const def = session.getToolDefinition(name);
|
|
2721
|
+
loaded.push({
|
|
2722
|
+
name,
|
|
2723
|
+
summary: def?.promptSnippet,
|
|
2724
|
+
description: def?.description,
|
|
2725
|
+
guidelines: Array.isArray(def?.promptGuidelines) ? def.promptGuidelines : undefined,
|
|
2726
|
+
});
|
|
2727
|
+
}
|
|
2728
|
+
if (changed) {
|
|
2729
|
+
this.applyToolGating(session, conv?.agentPreset);
|
|
2730
|
+
this.sessionStatsCache = null;
|
|
2731
|
+
this.cachedBaseTokens = null;
|
|
2732
|
+
this.flushSnapshot();
|
|
2733
|
+
}
|
|
2734
|
+
return { loaded, rejected };
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
|
|
2738
|
+
* automatically mark it as loaded so subsequent turns track it as fully active.
|
|
2739
|
+
*/
|
|
2740
|
+
autoActivateToolIfLoadable(session, conv, name) {
|
|
2741
|
+
if (!this.lazyLoadingOn() || !name || name === LOAD_TOOLS_TOOL_NAME)
|
|
2742
|
+
return;
|
|
2743
|
+
const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
|
|
2744
|
+
if (loaded.has(name))
|
|
2745
|
+
return;
|
|
2746
|
+
const allowed = new Set(this.allowedToolNames(session, conv));
|
|
2747
|
+
if (allowed.has(name)) {
|
|
2748
|
+
loaded.add(name);
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2366
2751
|
/** 当前活动会话的工具/资源快照 → composer 输入。cwd 取活动对话的。 */
|
|
2367
2752
|
composeInputs(src) {
|
|
2368
2753
|
const preset = src.preset ?? this.conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
@@ -2377,7 +2762,10 @@ export class ClientSession {
|
|
|
2377
2762
|
builtinSoul: BUILTIN_SOUL,
|
|
2378
2763
|
selectedTools: src.selectedTools,
|
|
2379
2764
|
toolSnippets: src.toolSnippets,
|
|
2765
|
+
toolSignatures: src.toolSignatures,
|
|
2380
2766
|
toolGuidelines: src.toolGuidelines,
|
|
2767
|
+
...(src.lazy ? { lazy: true } : {}),
|
|
2768
|
+
...(src.lazy && src.catalogTools ? { catalogTools: src.catalogTools } : {}),
|
|
2381
2769
|
piReadme: PI_DOC_PATHS.readme,
|
|
2382
2770
|
piDocs: PI_DOC_PATHS.docs,
|
|
2383
2771
|
piExamples: PI_DOC_PATHS.examples,
|
|
@@ -2426,7 +2814,12 @@ export class ClientSession {
|
|
|
2426
2814
|
const ovs = this.settingsSvc.current.promptOverrides ?? {};
|
|
2427
2815
|
const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
|
|
2428
2816
|
const preset = src.preset ?? this.conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2429
|
-
const isCustomized = !!tpl ||
|
|
2817
|
+
const isCustomized = !!tpl ||
|
|
2818
|
+
hasOverride ||
|
|
2819
|
+
preset !== "standard" ||
|
|
2820
|
+
effectiveDisabledAgentTools(this.settingsSvc.current).length > 0 ||
|
|
2821
|
+
// 延迟加载:提示词多了恒定目录段与 load_tools 引导,不渲染就根本不会出现。
|
|
2822
|
+
src.lazy === true;
|
|
2430
2823
|
if (!isCustomized)
|
|
2431
2824
|
return undefined;
|
|
2432
2825
|
const texts = resolveSectionTexts(this.composeInputs(src));
|
|
@@ -2444,30 +2837,53 @@ export class ClientSession {
|
|
|
2444
2837
|
const sess = conv.session;
|
|
2445
2838
|
const cwd = conv.cwd;
|
|
2446
2839
|
const active = sess.getActiveToolNames();
|
|
2447
|
-
const snippets = {};
|
|
2448
|
-
const guidelines = [];
|
|
2449
2840
|
const schemaEntries = [];
|
|
2450
2841
|
for (const name of active) {
|
|
2451
2842
|
const def = sess.getToolDefinition(name);
|
|
2452
2843
|
if (!def)
|
|
2453
2844
|
continue;
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
if (def.promptGuidelines)
|
|
2457
|
-
guidelines.push(...def.promptGuidelines);
|
|
2845
|
+
// 用户覆盖优先(description 同时反映在 schema 预览里)。
|
|
2846
|
+
const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
|
|
2458
2847
|
schemaEntries.push({
|
|
2459
2848
|
name,
|
|
2460
|
-
description:
|
|
2849
|
+
description: eff.description,
|
|
2461
2850
|
parameters: def.parameters,
|
|
2462
2851
|
});
|
|
2463
2852
|
}
|
|
2464
2853
|
const loader = sess.resourceLoader;
|
|
2465
2854
|
const preset = conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
|
|
2855
|
+
// 提示词侧的输入必须**与已加载集合无关**:延迟加载下列完整目录(恒定),
|
|
2856
|
+
// guidelines 只取基线(核心 + load_tools)——它们的要点随 load_tools 回执交付。
|
|
2857
|
+
const lazyOn = this.lazyLoadingOn();
|
|
2858
|
+
const catalog = lazyOn
|
|
2859
|
+
? this.promptToolCatalog(sess, conv)
|
|
2860
|
+
: {
|
|
2861
|
+
names: active,
|
|
2862
|
+
snippets: {},
|
|
2863
|
+
signatures: {},
|
|
2864
|
+
};
|
|
2865
|
+
const baseNames = lazyOn ? this.lazyBaselineNames(sess) : active;
|
|
2866
|
+
const baseSet = new Set(baseNames);
|
|
2867
|
+
const snippets = {};
|
|
2868
|
+
const signatures = catalog.signatures ?? {};
|
|
2869
|
+
const guidelines = [];
|
|
2870
|
+
for (const name of catalog.names) {
|
|
2871
|
+
const def = sess.getToolDefinition(name);
|
|
2872
|
+
if (!def)
|
|
2873
|
+
continue;
|
|
2874
|
+
const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
|
|
2875
|
+
if (eff.promptSnippet && eff.promptSnippet.trim())
|
|
2876
|
+
snippets[name] = eff.promptSnippet.trim();
|
|
2877
|
+
if (baseSet.has(name) && eff.promptGuidelines)
|
|
2878
|
+
guidelines.push(...eff.promptGuidelines);
|
|
2879
|
+
}
|
|
2466
2880
|
const texts = resolveSectionTexts(this.composeInputs({
|
|
2467
2881
|
cwd,
|
|
2468
|
-
selectedTools:
|
|
2882
|
+
selectedTools: baseNames,
|
|
2469
2883
|
toolSnippets: snippets,
|
|
2884
|
+
toolSignatures: signatures,
|
|
2470
2885
|
toolGuidelines: guidelines,
|
|
2886
|
+
...(lazyOn ? { lazy: true, catalogTools: catalog.names } : {}),
|
|
2471
2887
|
contextFiles: loader.getAgentsFiles().agentsFiles,
|
|
2472
2888
|
skills: loader.getSkills().skills.map((s) => ({
|
|
2473
2889
|
name: s.name,
|
|
@@ -2517,6 +2933,49 @@ export class ClientSession {
|
|
|
2517
2933
|
this.cachedBaseTokens = { at: now, convId: conv.id, tokens };
|
|
2518
2934
|
return tokens;
|
|
2519
2935
|
}
|
|
2936
|
+
/** 判断会话中是否已有大模型返回过有效 usage(input/output/totalTokens > 0)的定稿助手消息。 */
|
|
2937
|
+
hasSettledAssistantUsage(conv) {
|
|
2938
|
+
try {
|
|
2939
|
+
const msgs = conv.session.agent.state.messages;
|
|
2940
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
2941
|
+
const m = msgs[i];
|
|
2942
|
+
if (m.role === "assistant" && m.usage) {
|
|
2943
|
+
const u = m.usage;
|
|
2944
|
+
if ((u.input ?? 0) > 0 || (u.totalTokens ?? 0) > 0 || (u.output ?? 0) > 0) {
|
|
2945
|
+
return true;
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
catch {
|
|
2951
|
+
// fallback
|
|
2952
|
+
}
|
|
2953
|
+
return false;
|
|
2954
|
+
}
|
|
2955
|
+
/**
|
|
2956
|
+
* 估算会话中所有非系统消息(用户消息、工具调用/结果、自定义消息以及正在流式的助手内容)的 Token 开销。
|
|
2957
|
+
* 用于在尚未获得定稿 LLM usage 时,配合精准的 baseTokens 给出平滑、真实的上下文预估,
|
|
2958
|
+
* 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致首轮突增翻倍。
|
|
2959
|
+
*/
|
|
2960
|
+
estimateNonSystemTokens(conv) {
|
|
2961
|
+
let total = 0;
|
|
2962
|
+
try {
|
|
2963
|
+
const msgs = conv.session.agent.state.messages;
|
|
2964
|
+
for (const m of msgs) {
|
|
2965
|
+
if (m.role !== "system") {
|
|
2966
|
+
total += estimateTokens(m);
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
const streaming = conv.session.agent.state.streamingMessage;
|
|
2970
|
+
if (streaming) {
|
|
2971
|
+
total += estimateTokens(streaming);
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
catch {
|
|
2975
|
+
// best-effort
|
|
2976
|
+
}
|
|
2977
|
+
return total;
|
|
2978
|
+
}
|
|
2520
2979
|
/** Web-facing extension UI context (widgets, notifications). */
|
|
2521
2980
|
webUi = new WebUIContext((msg) => this.emit(msg));
|
|
2522
2981
|
/**
|
|
@@ -3085,6 +3544,10 @@ export class ClientSession {
|
|
|
3085
3544
|
},
|
|
3086
3545
|
// 标记 widget 合并进扩展 widget 里,跟随当前活动会话渲染(切换会话即刷新)。
|
|
3087
3546
|
refreshMarkers: () => this.webUi.refresh(),
|
|
3547
|
+
onActionsChange: (convId) => {
|
|
3548
|
+
if (convId === this.activeId)
|
|
3549
|
+
this.flushSnapshot();
|
|
3550
|
+
},
|
|
3088
3551
|
// issue #91:标记引导/错误按客户端 UI 语言出中英(英文默认)。
|
|
3089
3552
|
lang: () => this.getLang(),
|
|
3090
3553
|
});
|
|
@@ -3235,6 +3698,19 @@ export class ClientSession {
|
|
|
3235
3698
|
usage,
|
|
3236
3699
|
};
|
|
3237
3700
|
},
|
|
3701
|
+
// #543:执行者会话最近的工具/命令证据 —— 审查者的输入原本只有「执行者自述」,
|
|
3702
|
+
// 远程部署类目标于是只能靠猜。只在审查前读一次(轮次边界),与 vitals 分开。
|
|
3703
|
+
readRoleEvidence: (convId) => {
|
|
3704
|
+
const conv = this.convs.get(convId);
|
|
3705
|
+
if (!conv?.session)
|
|
3706
|
+
return undefined;
|
|
3707
|
+
try {
|
|
3708
|
+
return buildEvidenceDigest(sessionMessagesOf(conv.session)) || undefined;
|
|
3709
|
+
}
|
|
3710
|
+
catch {
|
|
3711
|
+
return undefined;
|
|
3712
|
+
}
|
|
3713
|
+
},
|
|
3238
3714
|
stopRoleAgent: async (convId) => {
|
|
3239
3715
|
const conv = this.convs.get(convId);
|
|
3240
3716
|
if (!conv)
|
|
@@ -3554,23 +4030,37 @@ export class ClientSession {
|
|
|
3554
4030
|
const swapped = rewrap(boundary === -1 ? `${tplPrompt}\n\n${core}` : tplPrompt + core.slice(boundary));
|
|
3555
4031
|
return swapped === event.systemPrompt ? undefined : { systemPrompt: swapped };
|
|
3556
4032
|
}
|
|
3557
|
-
//
|
|
4033
|
+
// 主会话:按当前会话归属预设与工具组装系统提示词。
|
|
4034
|
+
// 延迟加载打开时,提示词内容刻意**不依赖已加载集合**(否则每次 load_tools
|
|
4035
|
+
// 都会改系统提示词,供应商前缀缓存整段失效):工具列表 = 完整目录,
|
|
4036
|
+
// guidelines 只取基线;加载后的 schema 追加在 tools 数组里(前缀不变)。
|
|
3558
4037
|
const conv = this.convs.get(ownerId ?? this.activeId) ?? this.conv;
|
|
3559
4038
|
const sess = conv?.session;
|
|
3560
4039
|
const activeToolNames = sess ? sess.getActiveToolNames() : [];
|
|
3561
|
-
const
|
|
4040
|
+
const lazyOn = this.lazyLoadingOn();
|
|
4041
|
+
const catalog = lazyOn && sess
|
|
4042
|
+
? this.promptToolCatalog(sess, conv)
|
|
4043
|
+
: {
|
|
4044
|
+
names: activeToolNames,
|
|
4045
|
+
snippets: {},
|
|
4046
|
+
signatures: {},
|
|
4047
|
+
};
|
|
4048
|
+
const baseNames = lazyOn && sess ? this.lazyBaselineNames(sess) : activeToolNames;
|
|
4049
|
+
const baseSet = new Set(baseNames);
|
|
3562
4050
|
const activeSnippets = {};
|
|
4051
|
+
const activeSignatures = catalog.signatures ?? {};
|
|
3563
4052
|
const activeGuidelines = [];
|
|
3564
4053
|
if (sess) {
|
|
3565
|
-
for (const name of
|
|
4054
|
+
for (const name of catalog.names) {
|
|
3566
4055
|
const def = sess.getToolDefinition(name);
|
|
3567
4056
|
if (!def)
|
|
3568
4057
|
continue;
|
|
3569
|
-
|
|
3570
|
-
|
|
4058
|
+
const eff = effectiveToolPrompt(def, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
|
|
4059
|
+
if (eff.promptSnippet && eff.promptSnippet.trim()) {
|
|
4060
|
+
activeSnippets[name] = eff.promptSnippet.trim();
|
|
3571
4061
|
}
|
|
3572
|
-
if (
|
|
3573
|
-
activeGuidelines.push(...
|
|
4062
|
+
if (baseSet.has(name) && eff.promptGuidelines) {
|
|
4063
|
+
activeGuidelines.push(...eff.promptGuidelines);
|
|
3574
4064
|
}
|
|
3575
4065
|
}
|
|
3576
4066
|
}
|
|
@@ -3578,9 +4068,11 @@ export class ClientSession {
|
|
|
3578
4068
|
const opts = event.systemPromptOptions;
|
|
3579
4069
|
const rendered = this.renderMainCompose({
|
|
3580
4070
|
cwd: typeof opts?.cwd === "string" ? opts.cwd : (conv?.cwd ?? effectiveCwd ?? this.cwd),
|
|
3581
|
-
selectedTools:
|
|
4071
|
+
selectedTools: baseNames.length > 0 ? baseNames : (opts?.selectedTools ?? []),
|
|
3582
4072
|
toolSnippets: activeSnippets,
|
|
4073
|
+
toolSignatures: activeSignatures,
|
|
3583
4074
|
toolGuidelines: activeGuidelines,
|
|
4075
|
+
...(lazyOn ? { lazy: true, catalogTools: catalog.names } : {}),
|
|
3584
4076
|
contextFiles: opts?.contextFiles ?? [],
|
|
3585
4077
|
skills: (opts?.skills ?? []).map((s) => ({
|
|
3586
4078
|
name: s.name,
|
|
@@ -3659,7 +4151,7 @@ export class ClientSession {
|
|
|
3659
4151
|
// 设置关 → 原生 bash;开 → 终端 bash。
|
|
3660
4152
|
() => this.settingsSvc.current.terminalBash), {
|
|
3661
4153
|
toolName: "bash",
|
|
3662
|
-
guard: this.
|
|
4154
|
+
guard: this.lateToolGuard,
|
|
3663
4155
|
conversationId: () => ownerId,
|
|
3664
4156
|
getLang: () => this.getLang(),
|
|
3665
4157
|
cwd: effectiveCwd,
|
|
@@ -3776,6 +4268,11 @@ export class ClientSession {
|
|
|
3776
4268
|
enabled: () => isAgentToolEnabled(PRESENT_FILES_TOOL_NAME, effectiveDisabledAgentTools(this.settingsSvc.current)),
|
|
3777
4269
|
getLang: () => this.getLang(),
|
|
3778
4270
|
}),
|
|
4271
|
+
// 延迟加载入口(延迟加载模式默认开):系统提示词只给未加载工具的
|
|
4272
|
+
// 名字 + 一行摘要,模型用本工具把要用的工具拉进本对话(schema 才随之下发)。
|
|
4273
|
+
// 本事常在活跃集(见 applyToolGating 的 forceActive),关掉延迟加载后
|
|
4274
|
+
// 它也无害(目录为空,调用会告诉模型没东西可加载)。
|
|
4275
|
+
makeLoadToolsTool(this.loadToolsHost(ownerId), () => this.getLang()),
|
|
3779
4276
|
// 技能全文按名加载(名录在 {{skills}} 段):模型不再拼路径调 read。
|
|
3780
4277
|
// 子代理会话同样注册(owner 即真正派发的父对话,读该会话 loader)。
|
|
3781
4278
|
// DSH 引擎无 customTool 注册面,不接。开关走统一工具 tab。
|
|
@@ -3783,11 +4280,11 @@ export class ClientSession {
|
|
|
3783
4280
|
// 主动压缩上下文工具(compact_context):AI 主动根据当前问题精简上下文。
|
|
3784
4281
|
// 开关走统一工具 tab(ActiveSet 门控)。DSH 引擎无 customTool 注册面,不接。
|
|
3785
4282
|
makeCompactContextTool(this.compactContextHost(ownerId), () => this.getLang()),
|
|
3786
|
-
//
|
|
4283
|
+
// 定时唤醒(单 action:create/list/cancel,issue #193):默认绑定
|
|
3787
4284
|
// 发起对话(ownerId,无则活动对话),到期 steer 语义唤醒它;子代理
|
|
3788
4285
|
// 会话同样注册(owner 即真正派发的父对话)。开关走统一工具 tab。
|
|
3789
4286
|
// DSH 引擎无 customTool 注册面,不接。
|
|
3790
|
-
|
|
4287
|
+
makeScheduleTool(this.scheduleToolHost(), ownerId, () => this.getLang()),
|
|
3791
4288
|
// 持久代码求值沙箱(eval):开关走统一工具 tab(ActiveSet 门控,默认关)。
|
|
3792
4289
|
// ownerId 绑定当前会话;DSH 引擎无 customTool 注册面,不接。
|
|
3793
4290
|
makeEvalTool({
|
|
@@ -3872,6 +4369,7 @@ export class ClientSession {
|
|
|
3872
4369
|
queueSteering: [],
|
|
3873
4370
|
queueFollowUp: [],
|
|
3874
4371
|
toolStartTimes: new Map(),
|
|
4372
|
+
toolPendingArgs: new Map(),
|
|
3875
4373
|
toolWatchdogs: new Map(),
|
|
3876
4374
|
workspaceSnapshots: [],
|
|
3877
4375
|
};
|
|
@@ -3892,7 +4390,7 @@ export class ClientSession {
|
|
|
3892
4390
|
this.planManager.setPlan(conv.id, smPlan.steps, smPlan.activeStepId, sessionId);
|
|
3893
4391
|
return;
|
|
3894
4392
|
}
|
|
3895
|
-
// 3. 从已有历史消息中回放最后一次成功的 plan_update 工具调用
|
|
4393
|
+
// 3. 从已有历史消息中回放最后一次成功的 plan_update 或 update_plan 工具调用
|
|
3896
4394
|
const msgs = conv.session.agent?.state?.messages;
|
|
3897
4395
|
if (Array.isArray(msgs)) {
|
|
3898
4396
|
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
@@ -3900,12 +4398,18 @@ export class ClientSession {
|
|
|
3900
4398
|
if (msg?.role === "assistant" && Array.isArray(msg.content)) {
|
|
3901
4399
|
for (const part of msg.content) {
|
|
3902
4400
|
const p = part;
|
|
3903
|
-
if (p?.type === "tool_use" &&
|
|
3904
|
-
p.name === "plan_update"
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
4401
|
+
if (p?.type === "tool_use" && Array.isArray(p.input?.steps) && p.input.steps.length > 0) {
|
|
4402
|
+
if (p.name === "plan_update") {
|
|
4403
|
+
this.planManager.setPlan(conv.id, p.input.steps, p.input.activeStepId ?? null, sessionId);
|
|
4404
|
+
return;
|
|
4405
|
+
}
|
|
4406
|
+
if (p.name === "update_plan") {
|
|
4407
|
+
const normalized = normalizeSolPlanToPlanSteps(p.input.steps);
|
|
4408
|
+
if (normalized.steps.length > 0) {
|
|
4409
|
+
this.planManager.setPlan(conv.id, normalized.steps, normalized.activeStepId ?? null, sessionId);
|
|
4410
|
+
return;
|
|
4411
|
+
}
|
|
4412
|
+
}
|
|
3909
4413
|
}
|
|
3910
4414
|
}
|
|
3911
4415
|
}
|
|
@@ -4274,15 +4778,38 @@ export class ClientSession {
|
|
|
4274
4778
|
console.error("[agent-service] onConversationChanged failed:", err);
|
|
4275
4779
|
}
|
|
4276
4780
|
}
|
|
4781
|
+
/** 模型切换成功后通知插件(#542):只在(客户端, 对话, 模型)三元组真的变了时发
|
|
4782
|
+
* 一次——重连重放同一个 set_model / 重复点同一个模型不重复触发订阅者。异常隔离:
|
|
4783
|
+
* 插件侧报错不得影响切换流程。 */
|
|
4784
|
+
notifyPluginModelChange() {
|
|
4785
|
+
if (!this.onClientModelChanged)
|
|
4786
|
+
return;
|
|
4787
|
+
try {
|
|
4788
|
+
// 取「本客户端正在看的那条对话」的快照(模型属于它,不能回落成别的会话)。
|
|
4789
|
+
const snap = this.readConversationForPlugins({ preferActive: true, includeSubagents: true });
|
|
4790
|
+
if (!snap)
|
|
4791
|
+
return;
|
|
4792
|
+
const key = modelChangeKey(snap);
|
|
4793
|
+
if (this.pluginModelKeys.get(snap.conversationId) === key)
|
|
4794
|
+
return;
|
|
4795
|
+
this.pluginModelKeys.set(snap.conversationId, key);
|
|
4796
|
+
this.onClientModelChanged(snap);
|
|
4797
|
+
}
|
|
4798
|
+
catch (err) {
|
|
4799
|
+
console.error("[agent-service] onClientModelChanged failed:", err);
|
|
4800
|
+
}
|
|
4801
|
+
}
|
|
4277
4802
|
/** 插件用:本客户端最近活跃对话的快照(轨迹视图直接显示打开对话的时间线)。
|
|
4278
|
-
* messages/streamingMessage 为引用稳定的只读缓存对象——调用方只读、不得修改。
|
|
4279
|
-
|
|
4803
|
+
* messages/streamingMessage 为引用稳定的只读缓存对象——调用方只读、不得修改。
|
|
4804
|
+
*
|
|
4805
|
+
* #542:`opts.preferActive` = 先认「本客户端正在看的对话」(按 clientId 取快照时用),
|
|
4806
|
+
* 否则按 lastActiveAt 选;`opts.includeSubagents` = 连子代理对话一起算(缺省跳过)。 */
|
|
4807
|
+
readConversationForPlugins(opts) {
|
|
4280
4808
|
try {
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
}
|
|
4809
|
+
const target = pickClientConversation(this.convs.values(), {
|
|
4810
|
+
active: opts?.preferActive ? this.convs.get(this.activeId) : undefined,
|
|
4811
|
+
includeSubagents: opts?.includeSubagents,
|
|
4812
|
+
});
|
|
4286
4813
|
if (!target)
|
|
4287
4814
|
return null;
|
|
4288
4815
|
const state = target.session.agent.state;
|
|
@@ -4308,7 +4835,9 @@ export class ClientSession {
|
|
|
4308
4835
|
const curModel = target.session.model;
|
|
4309
4836
|
const modelId = curModel ? `${curModel.provider}/${curModel.id}` : undefined;
|
|
4310
4837
|
return {
|
|
4838
|
+
clientId: this.clientId,
|
|
4311
4839
|
conversationId: target.id,
|
|
4840
|
+
isSubagent: target.isSubagent,
|
|
4312
4841
|
sessionId: target.session.sessionId,
|
|
4313
4842
|
sessionFile: target.session.sessionFile,
|
|
4314
4843
|
sessionDir: target.session.sessionManager?.getSessionDir?.(),
|
|
@@ -4618,6 +5147,11 @@ export class ClientSession {
|
|
|
4618
5147
|
break;
|
|
4619
5148
|
}
|
|
4620
5149
|
case "tool_execution_start": {
|
|
5150
|
+
// JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
|
|
5151
|
+
// automatically mark it as loaded so subsequent turns track it as fully active.
|
|
5152
|
+
if (conv.session && event.toolName) {
|
|
5153
|
+
this.autoActivateToolIfLoadable(conv.session, conv, event.toolName);
|
|
5154
|
+
}
|
|
4621
5155
|
// Record the moment the tool actually starts so tool_status can
|
|
4622
5156
|
// report real execution time (vs. time spent waiting on the model).
|
|
4623
5157
|
conv.toolStartTimes.set(event.toolCallId, Date.now());
|
|
@@ -4626,6 +5160,9 @@ export class ClientSession {
|
|
|
4626
5160
|
if (event.toolName === "bash") {
|
|
4627
5161
|
this.bg.snapshotBefore();
|
|
4628
5162
|
}
|
|
5163
|
+
if (event.toolName === "update_plan") {
|
|
5164
|
+
conv.toolPendingArgs.set(event.toolCallId, event.args);
|
|
5165
|
+
}
|
|
4629
5166
|
// 看门狗豁免:ask_user_question 阻塞等的是「人类回答」,不是挂死的工具
|
|
4630
5167
|
// (默认 20 分钟会把还在思考的用户连对话一起剁掉)。它的收场自有路子:
|
|
4631
5168
|
// 用户回答/取消、会话 dispose(cancelPendingQuestions),不限时。
|
|
@@ -4659,6 +5196,11 @@ export class ClientSession {
|
|
|
4659
5196
|
const startedAt = conv.toolStartTimes.get(event.toolCallId);
|
|
4660
5197
|
conv.toolStartTimes.delete(event.toolCallId);
|
|
4661
5198
|
this.clearToolWatchdog(conv, event.toolCallId);
|
|
5199
|
+
const pendingArgs = conv.toolPendingArgs.get(event.toolCallId);
|
|
5200
|
+
conv.toolPendingArgs.delete(event.toolCallId);
|
|
5201
|
+
if (!event.isError && event.toolName === "update_plan" && pendingArgs) {
|
|
5202
|
+
this.syncSolUpdatePlan(conv, pendingArgs);
|
|
5203
|
+
}
|
|
4662
5204
|
// Bash finished — wait briefly for background servers to bind their
|
|
4663
5205
|
// ports, then diff against the pre-run snapshot and record them.
|
|
4664
5206
|
if (event.toolName === "bash")
|
|
@@ -4944,9 +5486,12 @@ export class ClientSession {
|
|
|
4944
5486
|
case "agent_settled": {
|
|
4945
5487
|
// 记录本会话自己的 Base 基线:currentBaseTokens 必须传 conv(否则串成
|
|
4946
5488
|
// 活跃会话的基线);快照未就绪时保持 undefined,宁可少补偿也不把 0 钉死。
|
|
5489
|
+
// 只有在真正获得了有效的大模型回复 usage 时才落账(被 abort 或网络失败全 0 不落账,
|
|
5490
|
+
// 防止未获得有效 usage 时提早进入 delta 模式导致显示掉落到 SDK 粗估值)。
|
|
4947
5491
|
const settledBaseTokens = this.currentBaseTokens(conv);
|
|
4948
|
-
if (settledBaseTokens != null)
|
|
5492
|
+
if (settledBaseTokens != null && this.hasSettledAssistantUsage(conv)) {
|
|
4949
5493
|
conv.lastTurnBaseTokens = settledBaseTokens;
|
|
5494
|
+
}
|
|
4950
5495
|
if (conv.pendingCompaction && !this.disposed) {
|
|
4951
5496
|
const pending = conv.pendingCompaction;
|
|
4952
5497
|
conv.pendingCompaction = null;
|
|
@@ -5280,14 +5825,17 @@ export class ClientSession {
|
|
|
5280
5825
|
softCap: this.activeSoftCap(cu.contextWindow),
|
|
5281
5826
|
};
|
|
5282
5827
|
}
|
|
5283
|
-
//
|
|
5284
|
-
|
|
5285
|
-
|
|
5828
|
+
// 首轮对话中(或尚未获得带有效 usage 的定稿助手消息):
|
|
5829
|
+
// 叠加精准的 Base 开销与当前非系统消息(用户输入、流式生成等)估算,
|
|
5830
|
+
// 杜绝 SDK 内部全量遍历粗估系统提示词与 baseTokens 双重叠加导致突增翻倍(如 10k 变成 17k)。
|
|
5831
|
+
if ((conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) && cu.contextWindow > 0) {
|
|
5832
|
+
const nonSystemTokens = this.estimateNonSystemTokens(conv);
|
|
5833
|
+
const total = baseTokens + nonSystemTokens;
|
|
5286
5834
|
return {
|
|
5287
5835
|
tokens: total,
|
|
5288
5836
|
contextWindow: cu.contextWindow,
|
|
5289
5837
|
percent: (total / cu.contextWindow) * 100,
|
|
5290
|
-
estimated:
|
|
5838
|
+
estimated: true,
|
|
5291
5839
|
softCap: this.activeSoftCap(cu.contextWindow),
|
|
5292
5840
|
};
|
|
5293
5841
|
}
|
|
@@ -5351,8 +5899,11 @@ export class ClientSession {
|
|
|
5351
5899
|
retry: conv.retryState ?? null,
|
|
5352
5900
|
compaction: conv.compactionState ?? null,
|
|
5353
5901
|
pendingQuestion: this.pendingQuestionForSnapshot(),
|
|
5902
|
+
actionSuggestions: this.markerSvc.getActionSuggestions(this.activeId) ?? null,
|
|
5354
5903
|
pendingApproval: this.pendingApprovalForSnapshot(),
|
|
5355
|
-
|
|
5904
|
+
// 任务计划看板状态同样是会话级:快照恒给 PlanState 或 null(不用 undefined),
|
|
5905
|
+
// 否则 snapshot_delta 里 key 缺席 → 前端 spread 浅合并会残留上一对话的 plan。
|
|
5906
|
+
plan: this.planManager.getPlan(this.activeId) ?? null,
|
|
5356
5907
|
// 计划模式是**会话级**开关:快照恒给布尔(不用 undefined),否则
|
|
5357
5908
|
// snapshot_delta 里 key 缺席 → 前端 spread 合并会残留上一对话的 true。
|
|
5358
5909
|
planMode: conv?.planMode === true,
|
|
@@ -5394,6 +5945,13 @@ export class ClientSession {
|
|
|
5394
5945
|
emitSnapshotNow(forceFull = false) {
|
|
5395
5946
|
if (this.disposed)
|
|
5396
5947
|
return;
|
|
5948
|
+
if (this.convs.size === 0) {
|
|
5949
|
+
// 自愈兜底:没有任何活跃对话,异步触发 newChat 恢复状态,避免抛错挂死
|
|
5950
|
+
void this.newChat()
|
|
5951
|
+
.then(() => this.flushSnapshot(true))
|
|
5952
|
+
.catch(() => { });
|
|
5953
|
+
return;
|
|
5954
|
+
}
|
|
5397
5955
|
const cur = this.currentMessages();
|
|
5398
5956
|
const prev = this.emittedMessages;
|
|
5399
5957
|
let incremental = !forceFull && prev !== null && this.emittedConvId === this.activeId && prev.length <= cur.length;
|
|
@@ -5601,7 +6159,7 @@ export class ClientSession {
|
|
|
5601
6159
|
* 门禁都返回已 resolve 的 Promise,调用方(withToolGuard / 三个权限包装)
|
|
5602
6160
|
* 无需关心是否真的弹过窗。
|
|
5603
6161
|
*/
|
|
5604
|
-
askApproval(toolCallId, toolName, params, reason, reasonEn, conversationId, category) {
|
|
6162
|
+
askApproval(toolCallId, toolName, params, reason, reasonEn, conversationId, category, hits) {
|
|
5605
6163
|
return new Promise((resolve) => {
|
|
5606
6164
|
if (this.disposed) {
|
|
5607
6165
|
resolve({ decision: "deny", reason: "会话已关闭" });
|
|
@@ -5624,6 +6182,7 @@ export class ClientSession {
|
|
|
5624
6182
|
reason,
|
|
5625
6183
|
reasonEn,
|
|
5626
6184
|
...(category ? { category } : {}),
|
|
6185
|
+
...(hits && hits.length > 0 ? { hits } : {}),
|
|
5627
6186
|
conversationId,
|
|
5628
6187
|
conversationTitle,
|
|
5629
6188
|
resolve,
|
|
@@ -5639,6 +6198,7 @@ export class ClientSession {
|
|
|
5639
6198
|
reason,
|
|
5640
6199
|
reasonEn,
|
|
5641
6200
|
...(category ? { category } : {}),
|
|
6201
|
+
...(hits && hits.length > 0 ? { hits } : {}),
|
|
5642
6202
|
...(conversationId !== undefined ? { conversationId } : {}),
|
|
5643
6203
|
...(conversationTitle ? { conversationTitle } : {}),
|
|
5644
6204
|
});
|
|
@@ -5788,6 +6348,7 @@ export class ClientSession {
|
|
|
5788
6348
|
reason: p.reason,
|
|
5789
6349
|
reasonEn: p.reasonEn,
|
|
5790
6350
|
...(p.category ? { category: p.category } : {}),
|
|
6351
|
+
...(p.hits ? { hits: p.hits } : {}),
|
|
5791
6352
|
conversationId: p.conversationId,
|
|
5792
6353
|
conversationTitle: p.conversationTitle,
|
|
5793
6354
|
};
|
|
@@ -5843,6 +6404,37 @@ export class ClientSession {
|
|
|
5843
6404
|
});
|
|
5844
6405
|
this.flushSnapshot();
|
|
5845
6406
|
}
|
|
6407
|
+
/**
|
|
6408
|
+
* 自动桥接 SoL-Pi 的 update_plan 工具调用结果至 pi-web-ui 的 PlanManager,
|
|
6409
|
+
* 使模型调用 update_plan 时,Web 前端计划看板与顶栏状态能够实时同步。
|
|
6410
|
+
*/
|
|
6411
|
+
syncSolUpdatePlan(conv, params) {
|
|
6412
|
+
if (!params || typeof params !== "object")
|
|
6413
|
+
return;
|
|
6414
|
+
const p = params;
|
|
6415
|
+
if (!Array.isArray(p.steps) || p.steps.length === 0)
|
|
6416
|
+
return;
|
|
6417
|
+
const normalized = normalizeSolPlanToPlanSteps(p.steps);
|
|
6418
|
+
if (normalized.steps.length === 0)
|
|
6419
|
+
return;
|
|
6420
|
+
const sessionId = conv.session.sessionId;
|
|
6421
|
+
const plan = this.planManager.setPlan(conv.id, normalized.steps, normalized.activeStepId ?? null, sessionId);
|
|
6422
|
+
if (conv.session.sessionManager) {
|
|
6423
|
+
try {
|
|
6424
|
+
const sm = conv.session.sessionManager;
|
|
6425
|
+
sm?.appendCustomEntry?.("plan/update", { plan });
|
|
6426
|
+
}
|
|
6427
|
+
catch {
|
|
6428
|
+
// 转录追加失败不影响主流程
|
|
6429
|
+
}
|
|
6430
|
+
}
|
|
6431
|
+
this.emit({
|
|
6432
|
+
type: "plan_updated",
|
|
6433
|
+
conversationId: conv.id,
|
|
6434
|
+
plan,
|
|
6435
|
+
});
|
|
6436
|
+
this.flushSnapshot();
|
|
6437
|
+
}
|
|
5846
6438
|
/** 「✨ 净室执行(Clean-session Handoff)」:
|
|
5847
6439
|
* 关闭源会话的计划闸门,新建隔离会话,在新会话中原子设置计划步骤、可选迁移目标,并触发实施轮 prompt。 */
|
|
5848
6440
|
async planCleanHandoff(steps, promptText) {
|
|
@@ -5853,7 +6445,7 @@ export class ClientSession {
|
|
|
5853
6445
|
const sourceGoal = sourceConv?.goal?.goal;
|
|
5854
6446
|
await this.newChat();
|
|
5855
6447
|
const targetConv = this.conv;
|
|
5856
|
-
this.planManager.setPlan(targetConv.id, steps);
|
|
6448
|
+
this.planManager.setPlan(targetConv.id, steps, undefined, targetConv?.session?.sessionId);
|
|
5857
6449
|
if (sourceGoal) {
|
|
5858
6450
|
try {
|
|
5859
6451
|
await this.goalSvc.setGoal(sourceGoal, { targetConvId: targetConv.id, autoStart: false });
|
|
@@ -6061,6 +6653,8 @@ export class ClientSession {
|
|
|
6061
6653
|
* the forked child deadlocks between fork and exec. This applies to
|
|
6062
6654
|
* asynchronous spawns too — the previous async probe reproduced the hang.
|
|
6063
6655
|
*/
|
|
6656
|
+
// 手写 TTL 缓存而非通用 memoize:安装 pi 后 invalidatePiCliProbe() 要立即
|
|
6657
|
+
// 失效重探,通用 TTL memoize 不带失效通道(issue #470 处置说明)。
|
|
6064
6658
|
static piCliProbe = null;
|
|
6065
6659
|
static PI_CLI_PROBE_TTL_MS = 10_000;
|
|
6066
6660
|
isPiCliInstalled() {
|
|
@@ -6605,14 +7199,63 @@ export class ClientSession {
|
|
|
6605
7199
|
try {
|
|
6606
7200
|
const defs = this.session.getAllTools();
|
|
6607
7201
|
const found = defs.find((d) => d.name === name);
|
|
6608
|
-
if (found)
|
|
6609
|
-
|
|
7202
|
+
if (found) {
|
|
7203
|
+
// `getAllTools()` 不带 promptSnippet(SDK 的 ToolInfo 里就没这个字段),
|
|
7204
|
+
// 从 getToolDefinition 补齐默认值(该表是出厂定义,本服务不改它)。
|
|
7205
|
+
const def = this.session.getToolDefinition(name);
|
|
7206
|
+
const base = {
|
|
7207
|
+
...found,
|
|
7208
|
+
...(def?.promptSnippet ? { promptSnippet: def.promptSnippet } : {}),
|
|
7209
|
+
};
|
|
7210
|
+
// 展示的是**生效文案**(用户在设置页覆盖后的)——与模型看到的 tool schema 一致。
|
|
7211
|
+
const eff = effectiveToolPrompt(base, toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name));
|
|
7212
|
+
raw = {
|
|
7213
|
+
...base,
|
|
7214
|
+
description: eff.description,
|
|
7215
|
+
promptSnippet: eff.promptSnippet,
|
|
7216
|
+
promptGuidelines: eff.promptGuidelines,
|
|
7217
|
+
active: this.session.getActiveToolNames().includes(name),
|
|
7218
|
+
};
|
|
7219
|
+
}
|
|
6610
7220
|
}
|
|
6611
7221
|
catch {
|
|
6612
7222
|
// Session not ready (or the engine threw) — fall through to found:false.
|
|
6613
7223
|
}
|
|
6614
7224
|
this.emit({ type: "tool_info", ...normalizeToolInfo(name, raw) });
|
|
6615
7225
|
}
|
|
7226
|
+
/**
|
|
7227
|
+
* 设置页逐工具编辑文案时取「出厂默认 + 当前覆盖」→ `tool_prompt`。
|
|
7228
|
+
*
|
|
7229
|
+
* 与 getToolInfo 分开:那条应答会弹「工具详细信息」弹窗,在设置页里弹它不合适。
|
|
7230
|
+
* 出厂默认从 `getToolDefinition()`(SDK 原始定义,本服务从不改它)取 —— 它带
|
|
7231
|
+
* promptSnippet(`getAllTools()` 不带);所以无论用户覆盖过几次,编辑器都能展示真正的默认文本。
|
|
7232
|
+
*/
|
|
7233
|
+
getToolPrompt(name) {
|
|
7234
|
+
let found;
|
|
7235
|
+
try {
|
|
7236
|
+
const def = this.session.getToolDefinition(name);
|
|
7237
|
+
if (def) {
|
|
7238
|
+
found = {
|
|
7239
|
+
...(typeof def.description === "string" ? { description: def.description } : {}),
|
|
7240
|
+
...(typeof def.promptSnippet === "string" ? { promptSnippet: def.promptSnippet } : {}),
|
|
7241
|
+
...(Array.isArray(def.promptGuidelines) ? { promptGuidelines: def.promptGuidelines } : {}),
|
|
7242
|
+
};
|
|
7243
|
+
}
|
|
7244
|
+
}
|
|
7245
|
+
catch {
|
|
7246
|
+
// 会话未就绪:回 found:false,前端显示「取不到定义」。
|
|
7247
|
+
}
|
|
7248
|
+
const override = toolPromptOverrideOf(this.settingsSvc.current.toolPromptOverrides, name);
|
|
7249
|
+
this.emit({
|
|
7250
|
+
type: "tool_prompt",
|
|
7251
|
+
name,
|
|
7252
|
+
found: Boolean(found),
|
|
7253
|
+
...(found?.description ? { defaultDescription: found.description } : {}),
|
|
7254
|
+
...(found?.promptSnippet ? { defaultPromptSnippet: found.promptSnippet } : {}),
|
|
7255
|
+
...(found?.promptGuidelines ? { defaultPromptGuidelines: found.promptGuidelines } : {}),
|
|
7256
|
+
...(override ? { override } : {}),
|
|
7257
|
+
});
|
|
7258
|
+
}
|
|
6616
7259
|
/** 模型/服务商配置管理 —— 自包含模块,见 model-admin.ts。 */
|
|
6617
7260
|
modelAdmin;
|
|
6618
7261
|
/** Persist an api-key credential for a provider (auth.json). */
|
|
@@ -6998,6 +7641,26 @@ export class ClientSession {
|
|
|
6998
7641
|
async deletePreset(name) {
|
|
6999
7642
|
return this.settingsSvc.deletePreset(name);
|
|
7000
7643
|
}
|
|
7644
|
+
/** 导出预设/当前设置为可分享的 JSON(server/preset-share.ts)。 */
|
|
7645
|
+
async exportPreset(msg) {
|
|
7646
|
+
return this.settingsSvc.exportPreset(msg);
|
|
7647
|
+
}
|
|
7648
|
+
/** 解析导入的预设 JSON(dryRun = 只预览)。 */
|
|
7649
|
+
async importPreset(msg) {
|
|
7650
|
+
return this.settingsSvc.importPreset(msg);
|
|
7651
|
+
}
|
|
7652
|
+
/** 按网址导入预设(服务端抓取)。 */
|
|
7653
|
+
async importPresetFromUrl(msg) {
|
|
7654
|
+
return this.settingsSvc.importPresetFromUrl(msg);
|
|
7655
|
+
}
|
|
7656
|
+
/** 拉社区共享预设目录。 */
|
|
7657
|
+
async pushPresetCatalog(msg) {
|
|
7658
|
+
return this.settingsSvc.pushPresetCatalog(msg);
|
|
7659
|
+
}
|
|
7660
|
+
/** 一键分享预设到社区共享仓库。 */
|
|
7661
|
+
async sharePreset(msg) {
|
|
7662
|
+
return this.settingsSvc.sharePreset(msg);
|
|
7663
|
+
}
|
|
7001
7664
|
/** Upsert 一个子代理模板(全局共享)。 */
|
|
7002
7665
|
async saveSubagentTemplate(template) {
|
|
7003
7666
|
return this.settingsSvc.saveTemplate(template);
|
|
@@ -7049,7 +7712,7 @@ export class ClientSession {
|
|
|
7049
7712
|
const currentPermission = () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
7050
7713
|
this.settingsSvc.current.defaultPermissionPreset ??
|
|
7051
7714
|
"workspace-write-never";
|
|
7052
|
-
const approve = (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category);
|
|
7715
|
+
const approve = (toolCallId, toolName, params, reason, reasonEn, convId, category, hits) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category, hits);
|
|
7053
7716
|
// 行为开关(read 本体不可关):每次调用实时读设置 —— 不进 tool-manager 的 ActiveSet 目录。
|
|
7054
7717
|
const readDirOptions = {
|
|
7055
7718
|
dirEnabled: () => this.settingsSvc.current.readDirEnabled !== false,
|
|
@@ -7057,7 +7720,7 @@ export class ClientSession {
|
|
|
7057
7720
|
};
|
|
7058
7721
|
const readGuardOptions = {
|
|
7059
7722
|
toolName: "read",
|
|
7060
|
-
guard: this.
|
|
7723
|
+
guard: this.lateToolGuard,
|
|
7061
7724
|
conversationId: () => ownerId,
|
|
7062
7725
|
getLang: () => this.getLang(),
|
|
7063
7726
|
cwd,
|
|
@@ -7079,7 +7742,18 @@ export class ClientSession {
|
|
|
7079
7742
|
composeWith: (base) => withToolGuard(withReadDirSupport(base, cwd, readDirOptions), readGuardOptions),
|
|
7080
7743
|
},
|
|
7081
7744
|
{ name: "write", fallback: () => composeWrite(), composeWith: (base) => composeWrite(base) },
|
|
7082
|
-
{
|
|
7745
|
+
{
|
|
7746
|
+
name: "edit",
|
|
7747
|
+
// 无扩展 edit:基底用 SDK 定义,但把**模型可见描述**换成精简版——SDK 的原描述与其自带的
|
|
7748
|
+
// guidelines 逐条复述(唯一/合并/不要垫大段未改区域都说两遍)。只改描述,保留 SDK 的
|
|
7749
|
+
// 参数 schema / guidelines / 执行体;有扩展 edit 时(composeWith)一律不动它的文案。
|
|
7750
|
+
fallback: () => composeEdit({
|
|
7751
|
+
...createEditToolDefinition(cwd),
|
|
7752
|
+
description: EDIT_DESCRIPTION,
|
|
7753
|
+
promptGuidelines: EDIT_GUIDELINES,
|
|
7754
|
+
}),
|
|
7755
|
+
composeWith: (base) => composeEdit(base),
|
|
7756
|
+
},
|
|
7083
7757
|
];
|
|
7084
7758
|
}
|
|
7085
7759
|
/** 统一工具门控(tool_manage 唯一落点):按 disabledAgentTools 把目录内工具
|
|
@@ -7101,12 +7775,33 @@ export class ClientSession {
|
|
|
7101
7775
|
disabled.add(toolName);
|
|
7102
7776
|
}
|
|
7103
7777
|
}
|
|
7104
|
-
|
|
7778
|
+
// 延迟加载(默认开):未加载的已登记工具一律当「临时禁用」——与用户禁用名单 /
|
|
7779
|
+
// 计划模式闸门走同一条门控链,不做第二套机制。加载只是把名字从这份名单里拿出来。
|
|
7780
|
+
const lazy = this.lazyLoadingOn();
|
|
7781
|
+
if (lazy) {
|
|
7782
|
+
try {
|
|
7783
|
+
const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
|
|
7784
|
+
for (const name of lazyLoadingDisabledTools(session.getAllTools().map((t) => t.name), loaded)) {
|
|
7785
|
+
disabled.add(name);
|
|
7786
|
+
}
|
|
7787
|
+
}
|
|
7788
|
+
catch {
|
|
7789
|
+
/* session 未就绪:下次创建/reload 会再应用 */
|
|
7790
|
+
}
|
|
7791
|
+
}
|
|
7792
|
+
applyAgentToolsGating(session, [...disabled], targetPreset, {
|
|
7793
|
+
// load_tools 不在任何预设白名单里,又必须永远可用(ask 预设本来就无工具,不强加)。
|
|
7794
|
+
forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME] : [],
|
|
7795
|
+
});
|
|
7105
7796
|
const ownerId = conv?.id;
|
|
7106
7797
|
syncSubagentOverride(session, disabled.has("subagent"), () => ownerId
|
|
7107
7798
|
? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined, ownerId)[0]
|
|
7108
7799
|
: makeSubagentTools(this.subagentHost)[0]);
|
|
7109
7800
|
this.syncPluginTools(session, targetPreset);
|
|
7801
|
+
// 逐工具文案覆盖(设置页「工具」区):在插件 sync / 工具刷新之后重放——
|
|
7802
|
+
// `_refreshToolRegistry()` 会用出厂定义重建注册表,覆盖必须重新打上去。
|
|
7803
|
+
// 只改模型可见的 description / snippet / guidelines,不碰执行体。
|
|
7804
|
+
applyToolPromptOverrides(session, this.settingsSvc.current.toolPromptOverrides);
|
|
7110
7805
|
this.sessionStatsCache = null;
|
|
7111
7806
|
this.cachedBaseTokens = null;
|
|
7112
7807
|
// SDK 的 setActiveToolsByName 只改 agent.state.tools,不派发任何事件——门控后
|
|
@@ -7651,9 +8346,11 @@ export class ClientSession {
|
|
|
7651
8346
|
* 一结束 elsewhere 行就消失,另一处想过户查看只能趁运行中动手 —— 跑完
|
|
7652
8347
|
* 即失联。空闲行带 isStreaming:false + sessionFile,照样可过户(搬 runtime
|
|
7653
8348
|
* 本体,单 writer 不变;takeoverBriefs 本来就含空闲对话)。子代理不单列
|
|
7654
|
-
* (随主对话一起搬)。
|
|
8349
|
+
* (随主对话一起搬)。activity = 该对话最近一次活跃时间(离线行的宽限期判定用,
|
|
8350
|
+
* 见 OFFLINE_ROW_TTL_MS)。 */
|
|
7655
8351
|
streamingSummariesAll() {
|
|
7656
8352
|
const out = [];
|
|
8353
|
+
const seenFiles = new Set();
|
|
7657
8354
|
for (const conv of this.convs.values()) {
|
|
7658
8355
|
if (conv.isSubagent)
|
|
7659
8356
|
continue;
|
|
@@ -7663,11 +8360,16 @@ export class ClientSession {
|
|
|
7663
8360
|
const pq = this.getPendingQuestionForConv(conv.id);
|
|
7664
8361
|
let sessionFile;
|
|
7665
8362
|
try {
|
|
7666
|
-
sessionFile = conv.session.sessionFile
|
|
8363
|
+
sessionFile = conv.session.sessionFile ? resolve(conv.session.sessionFile) : undefined;
|
|
7667
8364
|
}
|
|
7668
8365
|
catch {
|
|
7669
8366
|
sessionFile = undefined;
|
|
7670
8367
|
}
|
|
8368
|
+
if (sessionFile) {
|
|
8369
|
+
if (seenFiles.has(sessionFile))
|
|
8370
|
+
continue;
|
|
8371
|
+
seenFiles.add(sessionFile);
|
|
8372
|
+
}
|
|
7671
8373
|
out.push({
|
|
7672
8374
|
title: conv.title,
|
|
7673
8375
|
cwd: conv.cwd,
|
|
@@ -7676,6 +8378,7 @@ export class ClientSession {
|
|
|
7676
8378
|
hasQuestion: !!pq,
|
|
7677
8379
|
...(pq?.title ? { questionTitle: pq.title } : {}),
|
|
7678
8380
|
...(sessionFile ? { sessionFile } : {}),
|
|
8381
|
+
activity: Math.max(conv.lastActiveAt || 0, conv.lastSdkEventAt || 0),
|
|
7679
8382
|
});
|
|
7680
8383
|
}
|
|
7681
8384
|
return out;
|
|
@@ -7764,6 +8467,7 @@ export class ClientSession {
|
|
|
7764
8467
|
const conv = this.conv;
|
|
7765
8468
|
const promptAc = new AbortController();
|
|
7766
8469
|
conv.activePromptAc = promptAc;
|
|
8470
|
+
this.markerSvc.clearActions(conv.id);
|
|
7767
8471
|
if (conv.planMode === true) {
|
|
7768
8472
|
this.applyToolGating(conv.session);
|
|
7769
8473
|
}
|
|
@@ -8518,6 +9222,18 @@ export class ClientSession {
|
|
|
8518
9222
|
async killAllBackgroundServers() {
|
|
8519
9223
|
return this.bg.killAll();
|
|
8520
9224
|
}
|
|
9225
|
+
/** 钉住 / 取消钉住一个后台实例(自动清理跳过钉住的)。 */
|
|
9226
|
+
setBackgroundKeep(port, keep) {
|
|
9227
|
+
return this.bg.setKeep(port, keep);
|
|
9228
|
+
}
|
|
9229
|
+
/** 手动「立即清理」:按当前策略阈值(策略为关时用兑底 30 分钟)清一次遗留实例。 */
|
|
9230
|
+
async cleanBackgroundLeftovers(minutesOverride) {
|
|
9231
|
+
const override = Number(minutesOverride);
|
|
9232
|
+
const policy = Number(this.settingsSvc.current.bgAutoCleanupMin ?? 0);
|
|
9233
|
+
const minutes = Number.isFinite(override) && override > 0 ? override : policy;
|
|
9234
|
+
const thresholdMs = (minutes > 0 ? minutes : BG_CLEANUP_FALLBACK_MIN) * 60_000;
|
|
9235
|
+
return this.bg.cleanStale(thresholdMs, { manual: true });
|
|
9236
|
+
}
|
|
8521
9237
|
/** Kill only the running bash command(s) — the agent run itself continues
|
|
8522
9238
|
* (the bash tool returns an aborted error and the model moves on). Uses
|
|
8523
9239
|
* the per-client AbortController set registered by the bash tool paths
|
|
@@ -8740,16 +9456,19 @@ export class ClientSession {
|
|
|
8740
9456
|
// the per-project running-list model displaced blanks are disposed, so
|
|
8741
9457
|
// this branch normally can't exist — kept as a safety net).
|
|
8742
9458
|
const isBlank = (c) => {
|
|
9459
|
+
if (c.transferring)
|
|
9460
|
+
return false;
|
|
8743
9461
|
try {
|
|
8744
|
-
|
|
9462
|
+
const hasPlan = (this.planManager.getPlan(c.id)?.steps.length ?? 0) > 0;
|
|
9463
|
+
return c.session.getSessionStats().totalMessages === 0 && c.terminals.list().length === 0 && !hasPlan;
|
|
8745
9464
|
}
|
|
8746
9465
|
catch {
|
|
8747
9466
|
// session being replaced — treat as used so we don't switch onto it
|
|
8748
9467
|
return false;
|
|
8749
9468
|
}
|
|
8750
9469
|
};
|
|
8751
|
-
const active = this.
|
|
8752
|
-
if (!ephemeral && active && isBlank(active)) {
|
|
9470
|
+
const active = this.convs.get(this.activeId);
|
|
9471
|
+
if (!ephemeral && active && !active.transferring && isBlank(active)) {
|
|
8753
9472
|
if (_preset)
|
|
8754
9473
|
await this.selectAgentPreset(_preset);
|
|
8755
9474
|
else {
|
|
@@ -8760,7 +9479,7 @@ export class ClientSession {
|
|
|
8760
9479
|
}
|
|
8761
9480
|
if (!ephemeral) {
|
|
8762
9481
|
for (const conv of this.convs.values()) {
|
|
8763
|
-
if (conv.id === this.activeId)
|
|
9482
|
+
if (conv.id === this.activeId || conv.transferring)
|
|
8764
9483
|
continue;
|
|
8765
9484
|
if (isBlank(conv)) {
|
|
8766
9485
|
await this.switchConversation(conv.id);
|
|
@@ -9208,6 +9927,7 @@ export class ClientSession {
|
|
|
9208
9927
|
// ignore
|
|
9209
9928
|
}
|
|
9210
9929
|
this.convs.delete(id);
|
|
9930
|
+
this.planManager.unbindConversation(id);
|
|
9211
9931
|
this.clearAllToolWatchdogs(conv);
|
|
9212
9932
|
// 关对话 → 连它的 eval 内核(Python/Node 子进程 + 临时沙箱目录)一起回收:
|
|
9213
9933
|
// 这些进程是 detached 进程组,父进程退出不会自动带走它们。
|
|
@@ -9242,14 +9962,22 @@ export class ClientSession {
|
|
|
9242
9962
|
}
|
|
9243
9963
|
/** 过户用的对话摘要(AgentService 拼移动集合 + 容量检查用)。 */
|
|
9244
9964
|
takeoverBriefs() {
|
|
9245
|
-
return [...this.convs.values()].map((c) =>
|
|
9246
|
-
|
|
9247
|
-
|
|
9248
|
-
|
|
9249
|
-
|
|
9250
|
-
|
|
9251
|
-
|
|
9252
|
-
|
|
9965
|
+
return [...this.convs.values()].map((c) => {
|
|
9966
|
+
let sessionFile;
|
|
9967
|
+
try {
|
|
9968
|
+
sessionFile = c.session.sessionFile ? resolve(c.session.sessionFile) : undefined;
|
|
9969
|
+
}
|
|
9970
|
+
catch { }
|
|
9971
|
+
return {
|
|
9972
|
+
id: c.id,
|
|
9973
|
+
title: c.title,
|
|
9974
|
+
cwd: c.cwd,
|
|
9975
|
+
...(c.parentId ? { parentId: c.parentId } : {}),
|
|
9976
|
+
isSubagent: c.isSubagent,
|
|
9977
|
+
isEphemeral: !!c.isEphemeral,
|
|
9978
|
+
...(sessionFile ? { sessionFile } : {}),
|
|
9979
|
+
};
|
|
9980
|
+
});
|
|
9253
9981
|
}
|
|
9254
9982
|
/**
|
|
9255
9983
|
* 过户转出:把指定对话(含事件订阅/看门狗计时器/等答复问卷/页调用)从本会话摘除。
|
|
@@ -9295,6 +10023,18 @@ export class ClientSession {
|
|
|
9295
10023
|
}
|
|
9296
10024
|
this.goalSvc.notifyTakeover(conv);
|
|
9297
10025
|
}
|
|
10026
|
+
// 严密防御:搬迁删除后,源客户端的 activeId 必须指向当前仍存在的合法会话;
|
|
10027
|
+
// 若因竞态或原对话删除后悬空,自动切到现存主会话,没有任何会话时自动补建空白新会话,
|
|
10028
|
+
// 绝不让源客户端陷入无活跃会话的死锁。
|
|
10029
|
+
if (!this.convs.has(this.activeId)) {
|
|
10030
|
+
const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
|
|
10031
|
+
if (fallback) {
|
|
10032
|
+
this.activeId = fallback.id;
|
|
10033
|
+
}
|
|
10034
|
+
else {
|
|
10035
|
+
await this.newChat();
|
|
10036
|
+
}
|
|
10037
|
+
}
|
|
9298
10038
|
const questions = [];
|
|
9299
10039
|
for (const [qid, p] of this.pendingQuestions) {
|
|
9300
10040
|
if (p.conversationId !== undefined && set.has(p.conversationId)) {
|
|
@@ -9328,6 +10068,7 @@ export class ClientSession {
|
|
|
9328
10068
|
reason: a.reason,
|
|
9329
10069
|
reasonEn: a.reasonEn,
|
|
9330
10070
|
...(a.category ? { category: a.category } : {}),
|
|
10071
|
+
...(a.hits ? { hits: a.hits } : {}),
|
|
9331
10072
|
conversationId: a.conversationId,
|
|
9332
10073
|
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
9333
10074
|
createdAt: a.createdAt,
|
|
@@ -9359,8 +10100,14 @@ export class ClientSession {
|
|
|
9359
10100
|
conv.id = fix(conv.id);
|
|
9360
10101
|
if (conv.parentId)
|
|
9361
10102
|
conv.parentId = fix(conv.parentId);
|
|
9362
|
-
if (!conv.isSubagent && !mainId)
|
|
10103
|
+
if (!conv.isSubagent && !mainId) {
|
|
9363
10104
|
mainId = conv.id;
|
|
10105
|
+
// 过户是用户显式动作:这条对话必须在某一页看得见。`listed` 一旦置位就进本页的
|
|
10106
|
+
// 运行列表(不靠「是当前对话 + 有内容」那条展示口径兜底)—— 否则一旦后面的
|
|
10107
|
+
// switchConversation 没切过去(抛错/竞态),它就成了「还在跑但谁的列表里都没
|
|
10108
|
+
// 有」的幽灵(issue #556)。代价只是切走时按「被保留」处理,用户可正常关掉。
|
|
10109
|
+
conv.listed = true;
|
|
10110
|
+
}
|
|
9364
10111
|
conv.lastActiveAt = Date.now();
|
|
9365
10112
|
conv.terminals.rebindEmit((msg) => this.emitTerminal(conv.id, msg));
|
|
9366
10113
|
conv.terminals.onAgentIdle = (terminalId, idleMs, title, lastLines) => this.notifyTerminalIdle(conv.id, terminalId, idleMs, title, lastLines);
|
|
@@ -9374,6 +10121,32 @@ export class ClientSession {
|
|
|
9374
10121
|
}
|
|
9375
10122
|
}
|
|
9376
10123
|
}
|
|
10124
|
+
// 防重:若本机在过户前已残留有相同会话文件的旧对话实例,先行清理
|
|
10125
|
+
let incomingFile;
|
|
10126
|
+
try {
|
|
10127
|
+
incomingFile = conv.session.sessionFile ? resolve(conv.session.sessionFile) : undefined;
|
|
10128
|
+
}
|
|
10129
|
+
catch { }
|
|
10130
|
+
if (incomingFile) {
|
|
10131
|
+
for (const [existingId, existingConv] of this.convs) {
|
|
10132
|
+
if (existingId === conv.id)
|
|
10133
|
+
continue;
|
|
10134
|
+
let existingFile;
|
|
10135
|
+
try {
|
|
10136
|
+
existingFile = existingConv.session.sessionFile ? resolve(existingConv.session.sessionFile) : undefined;
|
|
10137
|
+
}
|
|
10138
|
+
catch { }
|
|
10139
|
+
if (existingFile && existingFile === incomingFile) {
|
|
10140
|
+
if (existingId === this.activeId) {
|
|
10141
|
+
existingConv.listed = false;
|
|
10142
|
+
existingConv.pinned = false;
|
|
10143
|
+
}
|
|
10144
|
+
else {
|
|
10145
|
+
this.removeConversation(existingId);
|
|
10146
|
+
}
|
|
10147
|
+
}
|
|
10148
|
+
}
|
|
10149
|
+
}
|
|
9377
10150
|
this.convs.set(conv.id, conv);
|
|
9378
10151
|
}
|
|
9379
10152
|
if (!mainId)
|
|
@@ -9430,6 +10203,7 @@ export class ClientSession {
|
|
|
9430
10203
|
reason: a.reason,
|
|
9431
10204
|
reasonEn: a.reasonEn,
|
|
9432
10205
|
...(a.category ? { category: a.category } : {}),
|
|
10206
|
+
...(a.hits ? { hits: a.hits } : {}),
|
|
9433
10207
|
conversationId: aConvId,
|
|
9434
10208
|
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
9435
10209
|
resolve: a.resolve,
|
|
@@ -9445,6 +10219,7 @@ export class ClientSession {
|
|
|
9445
10219
|
reason: a.reason,
|
|
9446
10220
|
reasonEn: a.reasonEn,
|
|
9447
10221
|
...(a.category ? { category: a.category } : {}),
|
|
10222
|
+
...(a.hits ? { hits: a.hits } : {}),
|
|
9448
10223
|
conversationId: aConvId,
|
|
9449
10224
|
...(a.conversationTitle ? { conversationTitle: a.conversationTitle } : {}),
|
|
9450
10225
|
});
|
|
@@ -9452,6 +10227,25 @@ export class ClientSession {
|
|
|
9452
10227
|
}
|
|
9453
10228
|
return mainId;
|
|
9454
10229
|
}
|
|
10230
|
+
/**
|
|
10231
|
+
* 过户夭折回滚用:把 payload 里的对话对象从本会话 map 上摘掉,交还给源会话。
|
|
10232
|
+
* 按**对象身份**认,不按 id —— 转入时可能已因 id 冲突改写过 id。
|
|
10233
|
+
* 绝不 dispose:runtime/终端/订阅要原样接着用(订阅由转入方的 insert 重挂)。
|
|
10234
|
+
*/
|
|
10235
|
+
reclaimTakeoverConvs(payload) {
|
|
10236
|
+
const moved = new Set(payload.convs);
|
|
10237
|
+
// 遍历中只删当前项:Map 迭代器允许(已删除的条目不会再被访问)。
|
|
10238
|
+
for (const [id, conv] of this.convs) {
|
|
10239
|
+
if (moved.has(conv))
|
|
10240
|
+
this.convs.delete(id);
|
|
10241
|
+
}
|
|
10242
|
+
// 防御:万一 active 被抽走(不应该发生),别留一个悬空 active。
|
|
10243
|
+
if (!this.convs.has(this.activeId)) {
|
|
10244
|
+
const fallback = [...this.convs.values()].find((c) => !c.isSubagent) ?? [...this.convs.values()][0];
|
|
10245
|
+
if (fallback)
|
|
10246
|
+
this.activeId = fallback.id;
|
|
10247
|
+
}
|
|
10248
|
+
}
|
|
9455
10249
|
/**
|
|
9456
10250
|
* 切到新工作目录后的“跟随面”刷新(roots / 插件钩子 / 最近项目 / 历史列表 /
|
|
9457
10251
|
* 文件树 / 命令目录)。调用方先把 this.cwd 改好再调本函数。
|
|
@@ -10943,7 +11737,7 @@ export class ClientSession {
|
|
|
10943
11737
|
this.flushSnapshot();
|
|
10944
11738
|
return;
|
|
10945
11739
|
}
|
|
10946
|
-
const targetLeafId = position === "at" ? entry.id : entry.
|
|
11740
|
+
const targetLeafId = position === "at" ? entry.id : (findTurnBaseEntryId(targetConv.session.sessionManager, entry.id) ?? undefined);
|
|
10947
11741
|
try {
|
|
10948
11742
|
const currentSessionFile = targetConv.session.sessionFile;
|
|
10949
11743
|
const isPersisted = targetConv.session.sessionManager.isPersisted() && currentSessionFile && existsSync(currentSessionFile);
|
|
@@ -11226,7 +12020,10 @@ export class ClientSession {
|
|
|
11226
12020
|
// branch with the ModelRuntime default model otherwise.
|
|
11227
12021
|
const prevModel = this.session.agent.state.model ?? null;
|
|
11228
12022
|
const prevThinking = this.session.thinkingLevel ?? null;
|
|
11229
|
-
const
|
|
12023
|
+
const baseEntryId = findTurnBaseEntryId(this.session.sessionManager, entryId);
|
|
12024
|
+
const result = baseEntryId
|
|
12025
|
+
? await this.runtime.fork(baseEntryId, { position: "at" })
|
|
12026
|
+
: await this.runtime.newSession({ parentSession: this.session.sessionFile ?? undefined });
|
|
11230
12027
|
if (result.cancelled) {
|
|
11231
12028
|
this.emit({
|
|
11232
12029
|
type: "notice",
|
|
@@ -11238,6 +12035,14 @@ export class ClientSession {
|
|
|
11238
12035
|
return;
|
|
11239
12036
|
}
|
|
11240
12037
|
await this.bindSession();
|
|
12038
|
+
this.conv.uiMessageCache.clear();
|
|
12039
|
+
this.conv.msgIds.clear();
|
|
12040
|
+
this.conv.userSeqByTs.clear();
|
|
12041
|
+
this.conv.nextMsgId = 1;
|
|
12042
|
+
this.conv.lastMessagesSig = "";
|
|
12043
|
+
this.conv.lastMessagesArray = [];
|
|
12044
|
+
this.conv.queueSteering = [];
|
|
12045
|
+
this.conv.queueFollowUp = [];
|
|
11241
12046
|
// Restore the previously-selected model on the forked branch.
|
|
11242
12047
|
if (prevModel && this.sharedModelRuntime) {
|
|
11243
12048
|
try {
|
|
@@ -11625,7 +12430,7 @@ export class ClientSession {
|
|
|
11625
12430
|
const infos = await SessionManager.list(abs, piSessionsRoot());
|
|
11626
12431
|
const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
|
|
11627
12432
|
const owner = recent ? this.findSessionOwner?.(recent) : null;
|
|
11628
|
-
if (owner
|
|
12433
|
+
if (owner) {
|
|
11629
12434
|
resumeSkipped = owner;
|
|
11630
12435
|
}
|
|
11631
12436
|
}
|
|
@@ -11833,6 +12638,8 @@ export class ClientSession {
|
|
|
11833
12638
|
this.rememberProjectModel(modelId);
|
|
11834
12639
|
// 换模型后按新模型的窗口重算软上限覆盖(按模型覆盖可能不同,issue #229)。
|
|
11835
12640
|
this.applyCompactionOverrides();
|
|
12641
|
+
// 切换成功 → 立即通知插件(#542:不发消息也能收到);失败路径落在 catch 里,不发。
|
|
12642
|
+
this.notifyPluginModelChange();
|
|
11836
12643
|
}
|
|
11837
12644
|
catch (err) {
|
|
11838
12645
|
this.emit({
|
|
@@ -12058,6 +12865,10 @@ export function isPseudoClientId(id) {
|
|
|
12058
12865
|
export class AgentService {
|
|
12059
12866
|
cwd;
|
|
12060
12867
|
static isPseudoClientId = isPseudoClientId;
|
|
12868
|
+
/** 客户端 -> 最后一个浏览器断开的时刻(离线行宽限期起点;重连/认领即删)。 */
|
|
12869
|
+
offlineSince = new Map();
|
|
12870
|
+
/** 客户端 -> 离线行宽限期到期定时器(到期后让其他客户端重推,行消失)。 */
|
|
12871
|
+
offlineTimers = new Map();
|
|
12061
12872
|
/** index.ts 注入:SDK 工具执行事件的插件转发钩子,attach 时拷贝到每个新会话。 */
|
|
12062
12873
|
onToolEvent = undefined;
|
|
12063
12874
|
/** index.ts 注入:bash/read 插件拦截钩子,attach 时拷贝到每个新会话。 */
|
|
@@ -12066,6 +12877,8 @@ export class AgentService {
|
|
|
12066
12877
|
onRunEvent = undefined;
|
|
12067
12878
|
/** index.ts 注入:对话切换通知钩子,attach 时拷贝到每个新会话。 */
|
|
12068
12879
|
onConversationChanged = undefined;
|
|
12880
|
+
/** index.ts 注入:模型切换成功通知钩子(#542),attach 时拷贝到每个新会话。 */
|
|
12881
|
+
onClientModelChanged = undefined;
|
|
12069
12882
|
/** index.ts 注入:读取插件当前注册的 AI 工具(attach 时拷贝到每个新会话)。 */
|
|
12070
12883
|
pluginToolsProvider = undefined;
|
|
12071
12884
|
/** index.ts 注入:读取插件当前注册的斜杠命令(attach 时拷贝到每个新会话)。 */
|
|
@@ -12089,6 +12902,7 @@ export class AgentService {
|
|
|
12089
12902
|
* control socket reports real sockets, not cached client-session objects. */
|
|
12090
12903
|
socketCount = 0;
|
|
12091
12904
|
pending = new Map();
|
|
12905
|
+
pendingDetaches = new Map();
|
|
12092
12906
|
stateStore;
|
|
12093
12907
|
/** Set by index.ts: called when /pi-web-ui:quit is invoked. */
|
|
12094
12908
|
onQuit = undefined;
|
|
@@ -12365,24 +13179,114 @@ export class AgentService {
|
|
|
12365
13179
|
/** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
|
|
12366
13180
|
* owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
|
|
12367
13181
|
listExternalRunning(excludeClientId) {
|
|
12368
|
-
|
|
13182
|
+
// 1) 收集当前请求客户端自己持有的对话(按 sessionFile 与 cwd+title 双维度),
|
|
13183
|
+
// 本机已经持有的对话绝不作为 elsewhere 行推给本机(避免左栏同一对话既是“当前”又是“另一处”)。
|
|
13184
|
+
const currentCs = this.clients.get(excludeClientId);
|
|
13185
|
+
const localFiles = new Set();
|
|
13186
|
+
const localCwdTitles = new Set();
|
|
13187
|
+
if (currentCs) {
|
|
13188
|
+
for (const b of currentCs.takeoverBriefs()) {
|
|
13189
|
+
if (b.sessionFile)
|
|
13190
|
+
localFiles.add(resolve(b.sessionFile));
|
|
13191
|
+
localCwdTitles.add(`${b.cwd}\0${b.title}`);
|
|
13192
|
+
}
|
|
13193
|
+
}
|
|
13194
|
+
// 2) 遍历其他客户端,收集条目并按 sessionFile / cwd+title 去重。
|
|
13195
|
+
// 若多个客户端持有同会话(如断连竞争、多标签残留),保留正在运行(streaming)或有问卷的更活跃者,
|
|
13196
|
+
// 杜绝“一堆同一个对话的另一处”在左栏堆积。
|
|
13197
|
+
const dedupMap = new Map();
|
|
13198
|
+
const now = Date.now();
|
|
12369
13199
|
for (const [clientId, cs] of this.clients) {
|
|
12370
13200
|
if (clientId === excludeClientId)
|
|
12371
13201
|
continue;
|
|
12372
|
-
// issue #291:跳过无浏览器连接的残骸(非伪客户端 sinkCount=0 = 断连留存)。
|
|
12373
13202
|
// 伪客户端(scheduler:/plugin:)不走浏览器,sinkCount 永远为 0,保留。
|
|
12374
13203
|
const isPseudo = AgentService.isPseudoClientId(clientId);
|
|
12375
|
-
|
|
13204
|
+
// 无浏览器连接的残骸(sinkCount=0 = 断连留存):宽限期内仍下发(标
|
|
13205
|
+
// ownerOffline,可接管),过期或 TTL=0 时按 issue #291 不入列表。
|
|
13206
|
+
const offline = !isPseudo && cs.sinkCount() === 0;
|
|
13207
|
+
if (offline && OFFLINE_ROW_TTL_MS <= 0)
|
|
12376
13208
|
continue;
|
|
13209
|
+
const offlineSince = offline ? (this.offlineSince.get(clientId) ?? 0) : 0;
|
|
12377
13210
|
for (const r of cs.streamingSummariesAll()) {
|
|
12378
|
-
|
|
12379
|
-
|
|
13211
|
+
// activity 只服务宽限期判定,不进 wire(ElsewhereRunning 无此字段)。
|
|
13212
|
+
const { activity, ...rest } = r;
|
|
13213
|
+
if (offline && !rest.isStreaming) {
|
|
13214
|
+
// 宽限期从「断开时刻」与「最后一次活动」里取较晚者:跑动的后台任务
|
|
13215
|
+
// 每有事件就续期,不会跑到一半从别人列表里消失。
|
|
13216
|
+
const latest = Math.max(offlineSince, activity || 0);
|
|
13217
|
+
if (latest > 0 && now - latest > OFFLINE_ROW_TTL_MS)
|
|
13218
|
+
continue;
|
|
13219
|
+
}
|
|
13220
|
+
const normFile = rest.sessionFile ? resolve(rest.sessionFile) : undefined;
|
|
13221
|
+
// 本机已持有该会话文件,或本机在同项目下已有同名可见对话:排除
|
|
13222
|
+
if (normFile && localFiles.has(normFile))
|
|
13223
|
+
continue;
|
|
13224
|
+
if (localCwdTitles.has(`${rest.cwd}\0${rest.title}`))
|
|
13225
|
+
continue;
|
|
13226
|
+
const entry = {
|
|
13227
|
+
...rest,
|
|
12380
13228
|
owner: clientId,
|
|
12381
13229
|
...(isPseudo ? { pseudo: true } : {}),
|
|
12382
|
-
|
|
13230
|
+
...(offline ? { ownerOffline: true } : {}),
|
|
13231
|
+
};
|
|
13232
|
+
// 跨客户端去重键:有文件按规范路径去重,无文件按 cwd + title 去重
|
|
13233
|
+
const dedupKey = normFile ? `file:${normFile}` : `title:${rest.cwd}\0${rest.title}`;
|
|
13234
|
+
const existing = dedupMap.get(dedupKey);
|
|
13235
|
+
if (existing) {
|
|
13236
|
+
// 优先保留 streaming,其次保留 hasQuestion,最后才轮到离线行让位在线行
|
|
13237
|
+
const preferNew = (!existing.isStreaming && entry.isStreaming) ||
|
|
13238
|
+
(!existing.hasQuestion && entry.hasQuestion) ||
|
|
13239
|
+
(Boolean(existing.ownerOffline) && !entry.ownerOffline);
|
|
13240
|
+
if (preferNew) {
|
|
13241
|
+
dedupMap.set(dedupKey, entry);
|
|
13242
|
+
}
|
|
13243
|
+
continue;
|
|
13244
|
+
}
|
|
13245
|
+
dedupMap.set(dedupKey, entry);
|
|
12383
13246
|
}
|
|
12384
13247
|
}
|
|
12385
|
-
return
|
|
13248
|
+
return [...dedupMap.values()];
|
|
13249
|
+
}
|
|
13250
|
+
/** 离线行宽限期到期 → 让其他客户端重推一次(行随之从列表消失,回到 #291 口径)。
|
|
13251
|
+
*
|
|
13252
|
+
* 到期时刻取「断开时刻」与「最后一次活动」的较晚者:断开后 run 还在跑的后台任务
|
|
13253
|
+
* 每有流式变化都会重排(见 pokeExternalRunning),跑完那一刻的推送把宽限期从新起算。
|
|
13254
|
+
* 到期回调只推送、**不再重排**,否则「行已过期」会被无限排成 1s 轮询。 */
|
|
13255
|
+
armOfflineRowExpiry(clientId, cs) {
|
|
13256
|
+
if (OFFLINE_ROW_TTL_MS <= 0)
|
|
13257
|
+
return;
|
|
13258
|
+
const prev = this.offlineTimers.get(clientId);
|
|
13259
|
+
if (prev)
|
|
13260
|
+
clearTimeout(prev);
|
|
13261
|
+
let activity = 0;
|
|
13262
|
+
try {
|
|
13263
|
+
activity = cs.latestActivity();
|
|
13264
|
+
}
|
|
13265
|
+
catch {
|
|
13266
|
+
activity = 0;
|
|
13267
|
+
}
|
|
13268
|
+
const since = Math.max(this.offlineSince.get(clientId) ?? 0, activity || 0);
|
|
13269
|
+
const delay = Math.max(1_000, since + OFFLINE_ROW_TTL_MS - Date.now() + 1_000);
|
|
13270
|
+
const timer = setTimeout(() => {
|
|
13271
|
+
this.offlineTimers.delete(clientId);
|
|
13272
|
+
// 期间重连/被认领/被回收都算作废:只推真实还存在的离线残骸。
|
|
13273
|
+
if (this.clients.get(clientId) === cs && !AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
|
|
13274
|
+
this.notifyExternalRunning(clientId);
|
|
13275
|
+
}
|
|
13276
|
+
}, delay);
|
|
13277
|
+
timer.unref?.();
|
|
13278
|
+
this.offlineTimers.set(clientId, timer);
|
|
13279
|
+
}
|
|
13280
|
+
/** 又有浏览器连上(或残骸被认领/回收):离线行状态作废,别的页面按在线行重推。 */
|
|
13281
|
+
clearOfflineRows(clientId) {
|
|
13282
|
+
const had = this.offlineSince.delete(clientId);
|
|
13283
|
+
const timer = this.offlineTimers.get(clientId);
|
|
13284
|
+
if (timer) {
|
|
13285
|
+
clearTimeout(timer);
|
|
13286
|
+
this.offlineTimers.delete(clientId);
|
|
13287
|
+
}
|
|
13288
|
+
if (had)
|
|
13289
|
+
this.pokeExternalRunning(clientId);
|
|
12386
13290
|
}
|
|
12387
13291
|
/** issue #291:删除定时任务后回收对应伪客户端,避免残留在 elsewhere 列表。 */
|
|
12388
13292
|
releaseSchedulerClient(taskId) {
|
|
@@ -12404,6 +13308,16 @@ export class AgentService {
|
|
|
12404
13308
|
}
|
|
12405
13309
|
/** issue #145: 某客户端流式集合变化 → 其他客户端重推 conversations。 */
|
|
12406
13310
|
pokeExternalRunning(excludeClientId) {
|
|
13311
|
+
// 离线残骸刚有状态变化(run 跑完 / 又有事件):离线行宽限期重新起算,
|
|
13312
|
+
// 定时器顺延到「最后一次活动 + TTL」——否则任务跑完后再没人推它。
|
|
13313
|
+
const offlineCs = this.clients.get(excludeClientId);
|
|
13314
|
+
if (offlineCs && !AgentService.isPseudoClientId(excludeClientId) && offlineCs.sinkCount() === 0) {
|
|
13315
|
+
this.armOfflineRowExpiry(excludeClientId, offlineCs);
|
|
13316
|
+
}
|
|
13317
|
+
this.notifyExternalRunning(excludeClientId);
|
|
13318
|
+
}
|
|
13319
|
+
/** 只让其他客户端重推一次(不碰离线宽限期定时器)。 */
|
|
13320
|
+
notifyExternalRunning(excludeClientId) {
|
|
12407
13321
|
for (const [clientId, cs] of this.clients) {
|
|
12408
13322
|
if (clientId === excludeClientId)
|
|
12409
13323
|
continue;
|
|
@@ -12443,20 +13357,36 @@ export class AgentService {
|
|
|
12443
13357
|
n += cs.pendingMessages();
|
|
12444
13358
|
return n;
|
|
12445
13359
|
}
|
|
12446
|
-
/**
|
|
12447
|
-
|
|
12448
|
-
|
|
13360
|
+
/** 插件用:全客户端最近活跃对话的快照(#542:按 clientId 取某个标签页正在看的
|
|
13361
|
+
* 对话;缺省回落「最近活跃的**非子代理**会话」——子代理跑得再勤也不会把用户
|
|
13362
|
+
* 正在看的对话挤出快照)。clientId 不认识/该客户端暂无对话时同样走回落。 */
|
|
13363
|
+
readConversationForPlugins(opts) {
|
|
13364
|
+
const want = (opts?.clientId ?? "").trim();
|
|
13365
|
+
if (want) {
|
|
13366
|
+
const cs = this.clients.get(want);
|
|
13367
|
+
if (cs) {
|
|
13368
|
+
try {
|
|
13369
|
+
// 显式客户端:返回它**真正在看**的对话(含子代理对话——那是事实,
|
|
13370
|
+
// 快照带 isSubagent 由插件自己判)。
|
|
13371
|
+
const s = cs.readConversationForPlugins({ preferActive: true, includeSubagents: true });
|
|
13372
|
+
if (s)
|
|
13373
|
+
return s;
|
|
13374
|
+
}
|
|
13375
|
+
catch {
|
|
13376
|
+
/* 单客户端坏了不影响回落 */
|
|
13377
|
+
}
|
|
13378
|
+
}
|
|
13379
|
+
}
|
|
13380
|
+
const snaps = [];
|
|
12449
13381
|
for (const cs of this.clients.values()) {
|
|
12450
13382
|
try {
|
|
12451
|
-
|
|
12452
|
-
if (s && (!best || s.at > best.at))
|
|
12453
|
-
best = s;
|
|
13383
|
+
snaps.push(cs.readConversationForPlugins());
|
|
12454
13384
|
}
|
|
12455
13385
|
catch {
|
|
12456
13386
|
/* 单客户端坏了不影响其他 */
|
|
12457
13387
|
}
|
|
12458
13388
|
}
|
|
12459
|
-
return
|
|
13389
|
+
return pickLatestClientSnapshot(snaps);
|
|
12460
13390
|
}
|
|
12461
13391
|
/** 插件无头调用(host.chat 的落地):外部通道(微信等)把文本投给 agent。
|
|
12462
13392
|
* 每个 (pluginId, accountId) 独立伪客户端——复用 attach 完整链路
|
|
@@ -12793,7 +13723,36 @@ export class AgentService {
|
|
|
12793
13723
|
target.refreshExternalRunning();
|
|
12794
13724
|
return;
|
|
12795
13725
|
}
|
|
12796
|
-
|
|
13726
|
+
// 测试专用故障注入(默认情况下一行不生效):让「接进目标」这一步必错,用来回归
|
|
13727
|
+
// 「过户夭折不得变成幽灵」(tests/takeover-rollback-test.mjs)。
|
|
13728
|
+
let newMainId;
|
|
13729
|
+
try {
|
|
13730
|
+
if (process.env.PI_WEB_TEST_TAKEOVER_FAIL_INSERT === "1")
|
|
13731
|
+
throw new Error("injected takeover insert failure");
|
|
13732
|
+
newMainId = target.insertTakeoverConvs(detached.payload);
|
|
13733
|
+
}
|
|
13734
|
+
catch (err) {
|
|
13735
|
+
// 夭折回滚:对话已经从源会话摘下来了(源侧 map 已删、订阅已断),接进目标失败就是
|
|
13736
|
+
// 「还在跑但谁的列表里都没有」的幽灵 —— 只有重启服务才能靠落盘恢复(issue #556)。
|
|
13737
|
+
// 原样搬回源会话,两边都拿到诚实的回执。
|
|
13738
|
+
const where = await this.returnTakeoverPayload(source, target, detached.payload);
|
|
13739
|
+
console.error("[takeover] insert failed, payload returned to", where, err);
|
|
13740
|
+
if (where === "source") {
|
|
13741
|
+
// 源页面也得知道发生了什么:它的对话刚才静默地从列表里消失过一瞬间。
|
|
13742
|
+
source.sendNotice({
|
|
13743
|
+
type: "notice",
|
|
13744
|
+
level: "info",
|
|
13745
|
+
text: `对方的过户未完成,「${main.title}」已退回本页,可直接继续。`,
|
|
13746
|
+
textEn: `The takeover did not complete on the other side — "${main.title}" is back on this page.`,
|
|
13747
|
+
});
|
|
13748
|
+
}
|
|
13749
|
+
fail(where === "source"
|
|
13750
|
+
? `过户失败(${err.message})——对话已退回原页面,可直接重试`
|
|
13751
|
+
: `过户失败(${err.message})——对话留在本页运行列表里,刷新即可继续`, where === "source"
|
|
13752
|
+
? `Takeover failed (${err.message}) — the conversation is back on the source page; retry there.`
|
|
13753
|
+
: `Takeover failed (${err.message}) — the conversation is kept in this page's running list; refresh to pick it up.`);
|
|
13754
|
+
return;
|
|
13755
|
+
}
|
|
12797
13756
|
// 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
|
|
12798
13757
|
// 无 sink 时 emit 即丢,无需判断。
|
|
12799
13758
|
source.sendNotice({
|
|
@@ -12815,6 +13774,37 @@ export class AgentService {
|
|
|
12815
13774
|
fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
|
|
12816
13775
|
}
|
|
12817
13776
|
}
|
|
13777
|
+
/**
|
|
13778
|
+
* 过户夭折回滚:把已经摘下来的对话搬回源会话(及其运行列表)。
|
|
13779
|
+
*
|
|
13780
|
+
* 为什么要它:detach 与 insert 之间是唯一的空档期 —— 源侧已经删了 map、断了订阅,
|
|
13781
|
+
* 一旦 insert 报错,对话就两头不挂,但 runtime 还在跑(“幽灵会话”,只有重启服务
|
|
13782
|
+
* 才能靠落盘会话恢复,issue #556)。这里用同一套 insert 接线原样搬回去。
|
|
13783
|
+
*
|
|
13784
|
+
* 搬不回去(二次失败,理论上不该发生)时把它们**留在目标会话**:宁可留在新页面
|
|
13785
|
+
* 的运行列表里(insert 已给主对话置 listed),也绝不落到“没人持有”的空档。
|
|
13786
|
+
* 返回最终归属方,调用方据此给用户出对应文案。
|
|
13787
|
+
*/
|
|
13788
|
+
async returnTakeoverPayload(source, target, payload) {
|
|
13789
|
+
// 先摘掉已部分插进目标的残留(不 dispose:runtime 要原样搬)。
|
|
13790
|
+
target.reclaimTakeoverConvs(payload);
|
|
13791
|
+
try {
|
|
13792
|
+
const mainId = source.insertTakeoverConvs(payload);
|
|
13793
|
+
await source.switchConversation(mainId);
|
|
13794
|
+
await source.bindSession();
|
|
13795
|
+
return "source";
|
|
13796
|
+
}
|
|
13797
|
+
catch (err) {
|
|
13798
|
+
console.error("[takeover] rollback to source failed:", err);
|
|
13799
|
+
try {
|
|
13800
|
+
target.insertTakeoverConvs(payload);
|
|
13801
|
+
}
|
|
13802
|
+
catch {
|
|
13803
|
+
/* 双失败:对象还在 payload 里,不要再次搬运 —— 不抛,不让 handler 崩 */
|
|
13804
|
+
}
|
|
13805
|
+
return "target";
|
|
13806
|
+
}
|
|
13807
|
+
}
|
|
12818
13808
|
/**
|
|
12819
13809
|
* 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
|
|
12820
13810
|
* 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
|
|
@@ -12886,6 +13876,8 @@ export class AgentService {
|
|
|
12886
13876
|
const orphan = AgentService.isPseudoClientId(clientId) ? null : this.findAdoptableOrphan(clientId);
|
|
12887
13877
|
if (orphan) {
|
|
12888
13878
|
this.clients.delete(orphan.oldId);
|
|
13879
|
+
// 残骸被本页认领:它的离线行状态随 id 作废(行归到新 id 名下)。
|
|
13880
|
+
this.clearOfflineRows(orphan.oldId);
|
|
12889
13881
|
this.clients.set(clientId, orphan.cs);
|
|
12890
13882
|
cs = orphan.cs;
|
|
12891
13883
|
// 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
|
|
@@ -12933,7 +13925,7 @@ export class AgentService {
|
|
|
12933
13925
|
const infos = await SessionManager.list(cwd, piSessionsRoot());
|
|
12934
13926
|
const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
|
|
12935
13927
|
const owner = recent ? this.findSessionOwner(recent, clientId) : null;
|
|
12936
|
-
if (owner
|
|
13928
|
+
if (owner) {
|
|
12937
13929
|
createOpts = { blank: true, blankTitle: owner.title, ...(owner.isStreaming ? {} : { idleHeld: true }) };
|
|
12938
13930
|
}
|
|
12939
13931
|
}
|
|
@@ -12967,13 +13959,24 @@ export class AgentService {
|
|
|
12967
13959
|
// once, then cleared). Fire-and-forget AFTER attachSink + hooks:
|
|
12968
13960
|
// resume emits directly to sinks and needs the owner guards.
|
|
12969
13961
|
// Progress arrives over the socket as usual.
|
|
12970
|
-
|
|
13962
|
+
const detachedSinks = this.pendingDetaches.get(clientId);
|
|
13963
|
+
if (detachedSinks?.has(send)) {
|
|
13964
|
+
detachedSinks.delete(send);
|
|
13965
|
+
if (detachedSinks.size === 0)
|
|
13966
|
+
this.pendingDetaches.delete(clientId);
|
|
13967
|
+
}
|
|
13968
|
+
else {
|
|
13969
|
+
cs.attachSink(send);
|
|
13970
|
+
// 又有浏览器连上:离线行状态作废(别的页面按在线行重推,去掉离线标记)。
|
|
13971
|
+
this.clearOfflineRows(clientId);
|
|
13972
|
+
}
|
|
12971
13973
|
// Forward hooks (set once by index.ts) to every session.
|
|
12972
13974
|
cs.onQuit = this.onQuit;
|
|
12973
13975
|
cs.onToolEvent = this.onToolEvent;
|
|
12974
13976
|
cs.toolGuard = this.toolGuard;
|
|
12975
13977
|
cs.onRunEvent = this.onRunEvent;
|
|
12976
13978
|
cs.onConversationChanged = () => this.onConversationChanged?.();
|
|
13979
|
+
cs.onClientModelChanged = (snap) => this.onClientModelChanged?.(snap);
|
|
12977
13980
|
cs.pluginToolsProvider = this.pluginToolsProvider;
|
|
12978
13981
|
cs.pluginCommandsProvider = this.pluginCommandsProvider;
|
|
12979
13982
|
cs.pluginBgTasksProvider = this.pluginBgTasksProvider;
|
|
@@ -13025,12 +14028,26 @@ export class AgentService {
|
|
|
13025
14028
|
/** Remove a socket from a client's broadcast set (called on socket close). */
|
|
13026
14029
|
detach(clientId, send) {
|
|
13027
14030
|
const cs = this.clients.get(clientId);
|
|
13028
|
-
cs
|
|
13029
|
-
|
|
13030
|
-
|
|
13031
|
-
|
|
13032
|
-
|
|
13033
|
-
|
|
14031
|
+
if (cs) {
|
|
14032
|
+
cs.detachSink(send);
|
|
14033
|
+
// 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
|
|
14034
|
+
// (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
|
|
14035
|
+
// (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
|
|
14036
|
+
// 「残骸不永久占位」仍然成立)。
|
|
14037
|
+
if (!AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
|
|
14038
|
+
this.offlineSince.set(clientId, Date.now());
|
|
14039
|
+
this.pokeExternalRunning(clientId);
|
|
14040
|
+
this.armOfflineRowExpiry(clientId, cs);
|
|
14041
|
+
}
|
|
14042
|
+
}
|
|
14043
|
+
else if (this.pending.has(clientId)) {
|
|
14044
|
+
// 连接在 attach 异步创建期间断开:记录待 detach 的 sink,attach 完成后清理,避免死连接泄漏
|
|
14045
|
+
let set = this.pendingDetaches.get(clientId);
|
|
14046
|
+
if (!set) {
|
|
14047
|
+
set = new Set();
|
|
14048
|
+
this.pendingDetaches.set(clientId, set);
|
|
14049
|
+
}
|
|
14050
|
+
set.add(send);
|
|
13034
14051
|
}
|
|
13035
14052
|
}
|
|
13036
14053
|
get(clientId) {
|