pi-web-ui 0.90.0 → 0.91.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 +74 -1
- package/README.md +7 -4
- package/README.zh-CN.md +6 -3
- package/bin/pi-web-ui.mjs +37 -10
- package/deploy/pi-web-ui.service +36 -31
- package/dist/server/agent-service.js +1309 -151
- package/dist/server/client-state.js +70 -5
- package/dist/server/compaction-markers.js +287 -0
- package/dist/server/delegate-task.js +12 -1
- package/dist/server/dsh/dsh-agent-service.js +21 -1
- package/dist/server/file-transfer-routes.js +4 -1
- package/dist/server/icon-svg.js +35 -0
- package/dist/server/index.js +175 -38
- package/dist/server/plugin-catalog.js +5 -0
- package/dist/server/plugin-facilities.js +42 -11
- package/dist/server/plugins.js +47 -8
- package/dist/server/prompt-composer.js +1 -1
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/schedule-agent-tool.js +23 -5
- package/dist/server/scheduler-tasks.js +60 -1
- package/dist/server/scm-commitmsg.js +140 -0
- package/dist/server/scm.js +42 -0
- package/dist/server/settings-service.js +40 -0
- package/dist/server/skill-tool.js +120 -0
- package/dist/server/soft-cap.js +68 -0
- package/dist/server/subagent-templates.js +6 -0
- package/dist/server/subagents.js +157 -16
- package/dist/server/terminals.js +50 -20
- package/dist/server/tool-manager.js +7 -1
- package/package.json +33 -32
- package/plugins/catalog.json +10 -0
- package/web/dist/assets/TerminalPanel-GtDQ1h85.js +3 -0
- package/web/dist/assets/es-DIDZppIF.js +2 -0
- package/web/dist/assets/index-CdsKltOS.css +1 -0
- package/web/dist/assets/index-OoULNF70.js +363 -0
- package/web/dist/assets/markdown-CCeVCbci.css +1 -0
- package/web/dist/assets/markdown-eUQn_o9D.js +296 -0
- package/web/dist/assets/react-CR5VJ85Q.js +9 -0
- package/web/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/web/dist/assets/xterm-B1njb2Cr.css +1 -0
- package/web/dist/assets/xterm-Cf5xxe4g.js +16 -0
- package/web/dist/index.html +6 -4
- package/web/dist/assets/TerminalPanel-BDbdLhpT.js +0 -6
- package/web/dist/assets/TerminalPanel-DOrYoP_4.css +0 -32
- package/web/dist/assets/index-1f_DP8S3.js +0 -380
- package/web/dist/assets/index-DeUwDA-C.css +0 -10
- package/web/dist/assets/markdown-D3PKeHAZ.js +0 -311
- package/web/dist/assets/react-w24rH0km.js +0 -24
- package/web/dist/assets/xterm-B96xOxS9.js +0 -38
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// wholesale (no union merge / no stale built-in leftovers).
|
|
16
16
|
import "./patch-remote-catalog.js";
|
|
17
17
|
import { spawn } from "node:child_process";
|
|
18
|
-
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
19
19
|
import { createRequire } from "node:module";
|
|
20
20
|
import { appendFileSync, existsSync, readFileSync, rmSync, statSync, mkdirSync, watch, writeFileSync } from "node:fs";
|
|
21
21
|
import { homedir } from "node:os";
|
|
@@ -26,6 +26,7 @@ import { Type } from "typebox";
|
|
|
26
26
|
import { BgServerTracker } from "./bg-servers.js";
|
|
27
27
|
import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
|
|
28
28
|
import { hasActiveSubagentRun, hasPendingWaitSubscription, shouldRetainActive } from "./wait-subscription-scan.js";
|
|
29
|
+
import { COMPACTION_PENDING_TYPE, looksLikeChainCorruption, makeCompactionMarkerId, repairSessionFile, } from "./compaction-markers.js";
|
|
29
30
|
import { removeQueuedByIndexOrText } from "./queue-utils.js";
|
|
30
31
|
import { syncPluginToolsIntoSession } from "./plugins.js";
|
|
31
32
|
import { SettingsService } from "./settings-service.js";
|
|
@@ -41,14 +42,19 @@ import { ComposerDraftsStore } from "./composer-drafts.js";
|
|
|
41
42
|
import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
|
|
42
43
|
import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, BROWSER_PAGE_TOOL_NAME, effectiveDisabledAgentTools, isTerminalGuidanceOn, MARKERS_LIST_TOOL_NAME, } from "./tool-manager.js";
|
|
43
44
|
import { WebUIContext } from "./webui-context.js";
|
|
45
|
+
import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, softCapToReserve } from "./soft-cap.js";
|
|
44
46
|
import { decodeText } from "./text-sniff.js";
|
|
45
47
|
import { makeEditSoftTool } from "./edit-soft-tool.js";
|
|
46
48
|
import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
|
|
47
49
|
import { makeDelegateTaskTool } from "./delegate-task.js";
|
|
48
50
|
import { makeConversationReadTool, parseTranscriptLines, toTranscriptInput, } from "./conversation-read-tool.js";
|
|
51
|
+
import { makeSkillTool } from "./skill-tool.js";
|
|
49
52
|
import { makeScheduleTools } from "./schedule-agent-tool.js";
|
|
53
|
+
import { sameSessionFile } from "./scheduler-tasks.js";
|
|
50
54
|
import { buildAttachmentMessages, parseModelSpec } from "./attachments.js";
|
|
51
55
|
import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
|
|
56
|
+
import { isNotRepoError, scmCommitContext } from "./scm.js";
|
|
57
|
+
import { buildCommitMsgInput, buildCommitMsgPrompt, sanitizeCommitMessage } from "./scm-commitmsg.js";
|
|
52
58
|
import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
|
|
53
59
|
import { launchOrigin, toServiceInfo } from "./launch-origin.js";
|
|
54
60
|
import { serializeMessage, serializeStreamingMessage, stripTransientRetryErrors, } from "./serialize.js";
|
|
@@ -68,6 +74,8 @@ const STREAMING_SNAPSHOT_INTERVAL_MS = 2000;
|
|
|
68
74
|
/** Deltas newer than this keep the streaming (low-frequency) snapshot cadence. */
|
|
69
75
|
const DELTA_ACTIVE_WINDOW_MS = 1500;
|
|
70
76
|
const WIDGET_REFRESH_MS = 2000;
|
|
77
|
+
/** SCM「AI 生成提交信息」的单次补全超时——慢供应商不该让按钮转圈到天荒地老。 */
|
|
78
|
+
const SCM_COMMITMSG_TIMEOUT_MS = 60_000;
|
|
71
79
|
/** Model-stall watchdog: warn (don't abort — deep thinking can be legitimately
|
|
72
80
|
* quiet for minutes) when a streaming run produced NO SDK events for this long.
|
|
73
81
|
* Covers the failure class the per-tool watchdog cannot see: half-open API
|
|
@@ -648,6 +656,13 @@ const TOOL_WATCHDOG_TIMEOUT_MS = (() => {
|
|
|
648
656
|
* runtime alive; conversations of other projects keep their own lists).
|
|
649
657
|
* 子代理不计入:子代理是 inMemory 后台任务,不参与此上限,既不占位也不被此上限拦截。 */
|
|
650
658
|
const MAX_OPEN_CONVERSATIONS = 8;
|
|
659
|
+
/** 同时存活的子代理上限(按客户端计,含嵌套派生的孙子辈)。每个子代理都是一个完整
|
|
660
|
+
* runtime + TerminalManager,无上限时 AI 一次并行派发几十个会把服务进程拖垮。
|
|
661
|
+
* 主对话的 8 个上限是按项目计的,子代理按客户端全局计(wait_all 本来就是全局口径)。 */
|
|
662
|
+
const MAX_SUBAGENTS = 16;
|
|
663
|
+
/** SubagentSnapshot.prompt 下发上限:存的是全量 prompt,快照里只带前 N 字符,
|
|
664
|
+
* 避免 subagent_list 一次把几个长 prompt 全推给模型烧 token。 */
|
|
665
|
+
const SUBAGENT_PROMPT_SNAPSHOT_CAP = 2000;
|
|
651
666
|
const DEFAULT_CONV_TITLE = "新对话";
|
|
652
667
|
/** First user text in a session, truncated for the conversation list. */
|
|
653
668
|
function conversationTitle(session) {
|
|
@@ -784,6 +799,63 @@ export function isInsideSessionsDir(agentDir, targetPath) {
|
|
|
784
799
|
const sessionsRoot = resolve(agentDir, "sessions");
|
|
785
800
|
return abs.startsWith(sessionsRoot + sep);
|
|
786
801
|
}
|
|
802
|
+
/** 会话当前模型的 "provider/id"(无模型时 null;软上限按模型覆盖用,issue #229)。 */
|
|
803
|
+
function modelKeyOf(session) {
|
|
804
|
+
const m = session?.model;
|
|
805
|
+
if (!m || typeof m.provider !== "string" || typeof m.id !== "string")
|
|
806
|
+
return null;
|
|
807
|
+
return `${m.provider}/${m.id}`;
|
|
808
|
+
}
|
|
809
|
+
/** 会话当前模型的上下文窗口(未知时 0):live 统计优先,模型定义回落。 */
|
|
810
|
+
function contextWindowOf(session) {
|
|
811
|
+
try {
|
|
812
|
+
const live = session?.getSessionStats?.()?.contextUsage?.contextWindow;
|
|
813
|
+
if (typeof live === "number" && live > 0)
|
|
814
|
+
return Math.floor(live);
|
|
815
|
+
}
|
|
816
|
+
catch {
|
|
817
|
+
// 会话未就绪 → 回落模型定义。
|
|
818
|
+
}
|
|
819
|
+
const def = session?.model?.contextWindow;
|
|
820
|
+
return typeof def === "number" && def > 0 ? Math.floor(def) : 0;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* 选一个断开的残留会话给新标签认领(纯函数):
|
|
824
|
+
* - 还有别的在线浏览器(非伪客户端且 live)→ 不认领(新标签是第二块屏,
|
|
825
|
+
* issue #10 的隔离必须保留,跑着的对话继续走 elsewhere 只读感知)。
|
|
826
|
+
* - 否则在断开 + 非伪 + 有内容的候选中按(streaming 多 → 最近活跃)取最优;
|
|
827
|
+
* 没有返回 null(调用方走正常新建流程)。
|
|
828
|
+
*/
|
|
829
|
+
export function pickAdoptableOrphan(cands) {
|
|
830
|
+
if (cands.some((c) => !c.pseudo && c.live))
|
|
831
|
+
return null;
|
|
832
|
+
let best = null;
|
|
833
|
+
for (const c of cands) {
|
|
834
|
+
if (c.pseudo || c.live || !c.adoptable)
|
|
835
|
+
continue;
|
|
836
|
+
if (!best || c.streaming > best.streaming || (c.streaming === best.streaming && c.activity > best.activity)) {
|
|
837
|
+
best = c;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return best?.id ?? null;
|
|
841
|
+
}
|
|
842
|
+
/** 同项目判定(纯函数):调度视口回退与 id 唤醒的 cwd 护栏用。
|
|
843
|
+
* Windows 大小写/分隔符差异归一,空串永不相等。 */
|
|
844
|
+
export function sameCwd(a, b) {
|
|
845
|
+
const x = String(a ?? "").trim();
|
|
846
|
+
const y = String(b ?? "").trim();
|
|
847
|
+
if (!x || !y)
|
|
848
|
+
return false;
|
|
849
|
+
const norm = (s) => s.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
850
|
+
if (norm(x) === norm(y))
|
|
851
|
+
return true;
|
|
852
|
+
try {
|
|
853
|
+
return norm(resolve(x)) === norm(resolve(y));
|
|
854
|
+
}
|
|
855
|
+
catch {
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
787
859
|
export class ClientSession {
|
|
788
860
|
clientId;
|
|
789
861
|
/** Set by AgentService.attach: reflects the SERVICE-wide quiesce flag
|
|
@@ -966,12 +1038,27 @@ export class ClientSession {
|
|
|
966
1038
|
* 回退到模板模型 / 设置面板默认模型;null = 跟随主对话当前模型(默认行为,
|
|
967
1039
|
* runtime 重建时会继承共享 ModelRuntime 的当前默认)。 */
|
|
968
1040
|
async spawnSubagentConversation(prompt, type, cwd, apply, model, parentId) {
|
|
1041
|
+
// 数量上限先行:每个子代理都是完整 runtime + TerminalManager,无上限时一次
|
|
1042
|
+
// 并行派发几十个会把服务进程拖垮。抛错由 subagent_spawn / delegate_task 转成
|
|
1043
|
+
// 返回文本,AI 读到后可改串行 / 等待收口后重试,而不是看到工具异常。
|
|
1044
|
+
const liveSubagents = [...this.convs.values()].filter((c) => c.isSubagent).length;
|
|
1045
|
+
if (liveSubagents >= MAX_SUBAGENTS) {
|
|
1046
|
+
throw new Error(pick(this.getLang(), `子代理数量已达上限(${MAX_SUBAGENTS} 个),请先用 subagent_wait_all 等一部分完成、或用 subagent_stop 停掉不需要的再派发`, `Subagent limit reached (${MAX_SUBAGENTS} live). Wait for some with subagent_wait_all or stop unneeded ones with subagent_stop before spawning more`, "agent.subagent.limit.reached", { limit: MAX_SUBAGENTS }));
|
|
1047
|
+
}
|
|
1048
|
+
// 真正的派发者(withSubagentOwner 按 runtime 归属填入):cwd 基准 / 跟随模型 /
|
|
1049
|
+
// 跟随思考强度一律读它,而不是派发瞬间的 active——后台对话产出时用户可能正
|
|
1050
|
+
// 看着别的项目,读 active 会跟错模型、把相对 cwd 解析到错误的项目下。
|
|
1051
|
+
const spawner = parentId ? this.convs.get(parentId) : undefined;
|
|
1052
|
+
const spawnerSession = spawner?.session ?? this.session;
|
|
1053
|
+
const baseCwd = spawner?.cwd ?? this.cwd;
|
|
1054
|
+
// 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
|
|
1055
|
+
const resolvedCwd = cwd ? resolve(baseCwd, cwd) : baseCwd;
|
|
969
1056
|
const conversationId = `sa-${randomUUID().slice(0, 8)}`;
|
|
970
|
-
const terminals = this.makeTerminalManager(conversationId,
|
|
1057
|
+
const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
|
|
971
1058
|
const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
|
|
972
|
-
cwd,
|
|
1059
|
+
cwd: resolvedCwd,
|
|
973
1060
|
agentDir: this.agentDir,
|
|
974
|
-
sessionManager: SessionManager.inMemory(
|
|
1061
|
+
sessionManager: SessionManager.inMemory(resolvedCwd),
|
|
975
1062
|
});
|
|
976
1063
|
const conv = this.makeConversation(runtime, conversationId, terminals);
|
|
977
1064
|
conv.isSubagent = true;
|
|
@@ -980,6 +1067,11 @@ export class ClientSession {
|
|
|
980
1067
|
// 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
|
|
981
1068
|
conv.parentId = parentId ?? this.activeId ?? undefined;
|
|
982
1069
|
conv.subagentType = type;
|
|
1070
|
+
conv.subagentPrompt = prompt;
|
|
1071
|
+
// 插件工具门与模板扩展白名单对齐:白名单非空时插件/MCP 工具(无 SDK
|
|
1072
|
+
// extensionKey 身份)不进该会话。工厂期 customTools 不注册 + 下面的
|
|
1073
|
+
// syncPluginTools 不回补,模板热改不影响已运行的子代理(与 prompt/技能一致)。
|
|
1074
|
+
conv.subagentBarsPluginTools = !!apply && apply.enabledExtensions.length > 0;
|
|
983
1075
|
conv.listed = true;
|
|
984
1076
|
conv.title = subagentTitle(prompt);
|
|
985
1077
|
this.convs.set(conv.id, conv);
|
|
@@ -989,6 +1081,8 @@ export class ClientSession {
|
|
|
989
1081
|
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
990
1082
|
// 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
|
|
991
1083
|
this.applyRetryOverrides();
|
|
1084
|
+
// 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
|
|
1085
|
+
this.applyCompactionOverrides();
|
|
992
1086
|
// 扩展绑定(rpc 模式);用 headless 的 Web UI context:
|
|
993
1087
|
// 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
|
|
994
1088
|
try {
|
|
@@ -1010,8 +1104,8 @@ export class ClientSession {
|
|
|
1010
1104
|
const resolvedModel = model ?? (apply?.model?.trim() || null) ?? (this.settingsSvc.current.subagentDefaultModel || null);
|
|
1011
1105
|
const followModel = resolvedModel
|
|
1012
1106
|
? resolvedModel
|
|
1013
|
-
:
|
|
1014
|
-
? `${
|
|
1107
|
+
: spawnerSession.model
|
|
1108
|
+
? `${spawnerSession.model.provider}/${spawnerSession.model.id}`
|
|
1015
1109
|
: null;
|
|
1016
1110
|
if (followModel) {
|
|
1017
1111
|
const slash = followModel.indexOf("/");
|
|
@@ -1021,7 +1115,8 @@ export class ClientSession {
|
|
|
1021
1115
|
if (m) {
|
|
1022
1116
|
try {
|
|
1023
1117
|
// 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
|
|
1024
|
-
|
|
1118
|
+
// 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
|
|
1119
|
+
await this.restoreKeyForModel(followModel, resolvedCwd);
|
|
1025
1120
|
await conv.session.setModel(m);
|
|
1026
1121
|
}
|
|
1027
1122
|
catch (err) {
|
|
@@ -1043,12 +1138,12 @@ export class ClientSession {
|
|
|
1043
1138
|
});
|
|
1044
1139
|
}
|
|
1045
1140
|
}
|
|
1046
|
-
//
|
|
1047
|
-
// 同一取数源:
|
|
1048
|
-
//
|
|
1049
|
-
//
|
|
1050
|
-
//
|
|
1051
|
-
const thinkingLevel = apply?.thinkingLevel?.trim() ||
|
|
1141
|
+
// 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
|
|
1142
|
+
// 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
|
|
1143
|
+
// SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
|
|
1144
|
+
// 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
|
|
1145
|
+
// 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
|
|
1146
|
+
const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
|
|
1052
1147
|
if (thinkingLevel) {
|
|
1053
1148
|
try {
|
|
1054
1149
|
conv.session.setThinkingLevel(thinkingLevel);
|
|
@@ -1089,7 +1184,10 @@ export class ClientSession {
|
|
|
1089
1184
|
}
|
|
1090
1185
|
toSubagentSnapshot(conv) {
|
|
1091
1186
|
const streaming = conv.session.isStreaming;
|
|
1092
|
-
const
|
|
1187
|
+
const { error, canceled } = this.subagentRunOutcome(conv);
|
|
1188
|
+
// state 如实反映终态:之前 canceled 的子代理报的也是 done,只能靠独立 flag
|
|
1189
|
+
// 分辨。"queued" 保留给未来(排队调度),当前 spawn 即运行,无排队态。
|
|
1190
|
+
const state = streaming ? "running" : canceled ? "canceled" : "done";
|
|
1093
1191
|
let messageCount = 0;
|
|
1094
1192
|
try {
|
|
1095
1193
|
messageCount = conv.session.getSessionStats().totalMessages;
|
|
@@ -1097,12 +1195,14 @@ export class ClientSession {
|
|
|
1097
1195
|
catch {
|
|
1098
1196
|
// session being replaced — report defaults
|
|
1099
1197
|
}
|
|
1100
|
-
const
|
|
1198
|
+
const fullPrompt = conv.subagentPrompt ?? "";
|
|
1101
1199
|
return {
|
|
1102
1200
|
convId: conv.id,
|
|
1103
1201
|
type: conv.subagentType ?? "general",
|
|
1104
1202
|
title: conv.title,
|
|
1105
|
-
prompt:
|
|
1203
|
+
prompt: fullPrompt.length > SUBAGENT_PROMPT_SNAPSHOT_CAP
|
|
1204
|
+
? `${fullPrompt.slice(0, SUBAGENT_PROMPT_SNAPSHOT_CAP)}\n… [truncated]`
|
|
1205
|
+
: fullPrompt,
|
|
1106
1206
|
state,
|
|
1107
1207
|
streaming,
|
|
1108
1208
|
error,
|
|
@@ -1110,6 +1210,7 @@ export class ClientSession {
|
|
|
1110
1210
|
messageCount,
|
|
1111
1211
|
model: conv.session.model?.id,
|
|
1112
1212
|
output: conv.session.getLastAssistantText() ?? "",
|
|
1213
|
+
parentId: conv.parentId,
|
|
1113
1214
|
};
|
|
1114
1215
|
}
|
|
1115
1216
|
/** 子代理最近一次运行的结局:最后一条 assistant 消息的 errorMessage / stopReason。
|
|
@@ -1180,6 +1281,9 @@ export class ClientSession {
|
|
|
1180
1281
|
lastSdkAppendFiles = [];
|
|
1181
1282
|
/** 当前活动会话的工具/资源快照 → composer 输入。cwd 取活动对话的。 */
|
|
1182
1283
|
composeInputs(src) {
|
|
1284
|
+
// 技能名录指纹观测(只打日志,不干预组装;预览与 run 共用此入口,
|
|
1285
|
+
// 变化才记一行,首轮静默)。用未注文的目录(fill 前),全文注入不影响指纹。
|
|
1286
|
+
this.noteSkillCatalogDigest(src.skills);
|
|
1183
1287
|
return {
|
|
1184
1288
|
cwd: src.cwd,
|
|
1185
1289
|
systemPromptFile: this.lastBaseSystemPrompt || undefined,
|
|
@@ -1344,12 +1448,32 @@ export class ClientSession {
|
|
|
1344
1448
|
return !!t && t.enabled;
|
|
1345
1449
|
},
|
|
1346
1450
|
};
|
|
1347
|
-
/** schedule_* 工具的数据宿主:全局调度存储+创建时刻 live 的 cwd/活动对话。
|
|
1451
|
+
/** schedule_* 工具的数据宿主:全局调度存储+创建时刻 live 的 cwd/活动对话。
|
|
1452
|
+
* issue #231:同时快照 owner 对话的落盘会话文件(压缩/重启后稳定),触发时
|
|
1453
|
+
* 先按 sessionFile 认同一会话(内存对话 id 重启即失效,不可单独做持久键)。 */
|
|
1348
1454
|
scheduleToolHost() {
|
|
1349
1455
|
return {
|
|
1350
1456
|
store: () => this.schedulerStore,
|
|
1351
1457
|
cwd: () => this.cwd,
|
|
1352
1458
|
activeConversationId: () => this.activeId,
|
|
1459
|
+
conversationInfo: (id) => {
|
|
1460
|
+
try {
|
|
1461
|
+
const target = (id ?? "").trim() ? this.convs.get((id ?? "").trim()) : this.convs.get(this.activeId);
|
|
1462
|
+
if (!target)
|
|
1463
|
+
return undefined;
|
|
1464
|
+
let sessionFile = "";
|
|
1465
|
+
try {
|
|
1466
|
+
sessionFile = String(target.session.sessionFile ?? "");
|
|
1467
|
+
}
|
|
1468
|
+
catch {
|
|
1469
|
+
sessionFile = "";
|
|
1470
|
+
}
|
|
1471
|
+
return { cwd: target.cwd ?? this.cwd, sessionFile };
|
|
1472
|
+
}
|
|
1473
|
+
catch {
|
|
1474
|
+
return undefined;
|
|
1475
|
+
}
|
|
1476
|
+
},
|
|
1353
1477
|
};
|
|
1354
1478
|
}
|
|
1355
1479
|
/** conversation_read 工具的数据宿主:读本客户端的 conversation 体系 +
|
|
@@ -1432,6 +1556,45 @@ export class ClientSession {
|
|
|
1432
1556
|
},
|
|
1433
1557
|
};
|
|
1434
1558
|
}
|
|
1559
|
+
/** skill 工具的数据宿主:读所属会话 loader 的实时技能表 + 主会话禁用集过滤
|
|
1560
|
+
* (与 skillsOverride 主会话语义一致)。ownerId 语义同 browser_page(本
|
|
1561
|
+
* runtime 所属会话,不是派发瞬间的 active)。失败回空目录,不抛错。 */
|
|
1562
|
+
skillToolHost(ownerId) {
|
|
1563
|
+
return {
|
|
1564
|
+
listSkills: () => {
|
|
1565
|
+
try {
|
|
1566
|
+
const target = (ownerId ?? "").trim() !== "" ? this.convs.get(ownerId.trim()) : this.convs.get(this.activeId);
|
|
1567
|
+
const all = target?.session.resourceLoader.getSkills().skills ?? [];
|
|
1568
|
+
const disabled = new Set(this.settingsSvc.current.disabledSkills);
|
|
1569
|
+
return all
|
|
1570
|
+
.filter((s) => !disabled.has(s.name))
|
|
1571
|
+
.map((s) => ({
|
|
1572
|
+
name: s.name,
|
|
1573
|
+
description: s.description ?? "",
|
|
1574
|
+
filePath: s.filePath ?? "",
|
|
1575
|
+
}));
|
|
1576
|
+
}
|
|
1577
|
+
catch {
|
|
1578
|
+
return [];
|
|
1579
|
+
}
|
|
1580
|
+
},
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
/** 技能名录指纹(sha256 over name+description,非正文):变化才打一行日志,
|
|
1584
|
+
* 首轮静默。只观测不干预组装(digest 第一步:日志;复用以后再说)。 */
|
|
1585
|
+
lastSkillCatalogDigest = "";
|
|
1586
|
+
noteSkillCatalogDigest(skills) {
|
|
1587
|
+
const d = createHash("sha256")
|
|
1588
|
+
.update(skills.map((s) => `${s.name}\n${s.description}`).join("\n"))
|
|
1589
|
+
.digest("hex")
|
|
1590
|
+
.slice(0, 16);
|
|
1591
|
+
if (d === this.lastSkillCatalogDigest)
|
|
1592
|
+
return;
|
|
1593
|
+
const prev = this.lastSkillCatalogDigest;
|
|
1594
|
+
this.lastSkillCatalogDigest = d;
|
|
1595
|
+
if (prev)
|
|
1596
|
+
console.log(`[skills] catalog digest ${prev}→${d} (${skills.length} skills)`);
|
|
1597
|
+
}
|
|
1435
1598
|
widgetsTimer = null;
|
|
1436
1599
|
/** Model-stall watchdog interval (see startStallTimer). */
|
|
1437
1600
|
stallTimer = null;
|
|
@@ -1555,13 +1718,15 @@ export class ClientSession {
|
|
|
1555
1718
|
reloadSession: async () => {
|
|
1556
1719
|
await this.session.reload();
|
|
1557
1720
|
// reload() 重读磁盘 settings.json,会丢掉内存 applyOverrides
|
|
1558
|
-
// (含重试次数覆盖)——依次重放:重试覆盖 → 终端门控。
|
|
1721
|
+
// (含重试次数覆盖)——依次重放:重试覆盖 → 软上限覆盖 → 终端门控。
|
|
1559
1722
|
this.applyRetryOverrides();
|
|
1723
|
+
this.applyCompactionOverrides();
|
|
1560
1724
|
// reload() 会把 custom 工具重新加回活跃集——重放终端开关。
|
|
1561
1725
|
this.applyToolGating(this.session);
|
|
1562
1726
|
await this.pushSlashCommands();
|
|
1563
1727
|
},
|
|
1564
1728
|
applyRetryOverrides: () => this.applyRetryOverrides(),
|
|
1729
|
+
applyCompactionOverrides: () => this.applyCompactionOverrides(),
|
|
1565
1730
|
applyToolGating: () => this.applyToolGating(this.session),
|
|
1566
1731
|
promptSnapshot: () => this.promptSnapshot(),
|
|
1567
1732
|
getMarkerState: () => ({
|
|
@@ -1611,15 +1776,22 @@ export class ClientSession {
|
|
|
1611
1776
|
const cs = new ClientSession(clientId, cwd, agentDir, stateStore);
|
|
1612
1777
|
const conversationId = cs.nextConversationId();
|
|
1613
1778
|
const terminals = cs.makeTerminalManager(conversationId, cwd);
|
|
1614
|
-
|
|
1779
|
+
// Resume the most recent session for this project — the SDK default
|
|
1780
|
+
// per-project dir (<agentDir>/sessions/--<cwd>--/, shared with the
|
|
1781
|
+
// pi CLI/TUI) — or start a fresh one on first visit.
|
|
1782
|
+
// issue #145: opts.blank = 跳过恢复(最近那条在别处跑着),直接空白新对话。
|
|
1783
|
+
// issue #235:坏转录(重复压缩标记成环)修一次再试,否则整项目首屏
|
|
1784
|
+
// "Failed to initialize session"。
|
|
1785
|
+
const opened = await cs.openManagerAndRuntime(() => (opts?.blank ? SessionManager.create(cwd) : SessionManager.continueRecent(cwd)), (m) => createAgentSessionRuntime(cs.makeRuntimeFactory(terminals, undefined, conversationId), {
|
|
1615
1786
|
cwd,
|
|
1616
1787
|
agentDir,
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1788
|
+
sessionManager: m,
|
|
1789
|
+
}), async () => (await SessionManager.list(cwd))[0]?.path);
|
|
1790
|
+
const runtime = opened.runtime;
|
|
1791
|
+
if (opened.repair) {
|
|
1792
|
+
for (const n of cs.transcriptRepairNotices(opened.repair))
|
|
1793
|
+
cs.pendingNotices.push(n);
|
|
1794
|
+
}
|
|
1623
1795
|
// First conversation = the resumed session; it also seeds the shared
|
|
1624
1796
|
// ModelRuntime that every later conversation reuses.
|
|
1625
1797
|
cs.sharedModelRuntime = runtime.services.modelRuntime;
|
|
@@ -1759,12 +1931,18 @@ export class ClientSession {
|
|
|
1759
1931
|
// 把灵魂段换成模板提示词,自动段保留;SYSTEM.md 情形已在
|
|
1760
1932
|
// systemPromptOverride 整体替换,此处边界不存在会自然跳过。
|
|
1761
1933
|
if (apply) {
|
|
1762
|
-
|
|
1934
|
+
const tplPrompt = pickTemplatePrompt(apply, this.getLang()).trim();
|
|
1935
|
+
if (apply.promptMode !== "replace" || !tplPrompt)
|
|
1763
1936
|
return undefined;
|
|
1764
1937
|
const boundary = event.systemPrompt.indexOf("\n\nAvailable tools:");
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1938
|
+
// 边界串是 SDK 提示词的内部格式:版本一变就可能对不上。
|
|
1939
|
+
// 对不上时不再静默回退默认 persona(模板等于没生效),而是把模板
|
|
1940
|
+
// 提示词前置拼接——角色约束仍在,只是灵魂段没被精确替换。
|
|
1941
|
+
if (boundary === -1) {
|
|
1942
|
+
const fallback = `${tplPrompt}\n\n${event.systemPrompt}`;
|
|
1943
|
+
return fallback === event.systemPrompt ? undefined : { systemPrompt: fallback };
|
|
1944
|
+
}
|
|
1945
|
+
const swapped = tplPrompt + event.systemPrompt.slice(boundary);
|
|
1768
1946
|
return swapped === event.systemPrompt ? undefined : { systemPrompt: swapped };
|
|
1769
1947
|
}
|
|
1770
1948
|
// 主会话:组合模板渲染(模板为空且无覆盖时返回 undefined = 用 SDK 默认)。
|
|
@@ -1814,7 +1992,10 @@ export class ClientSession {
|
|
|
1814
1992
|
makeEditSoftTool(effectiveCwd, () => this.getLang()),
|
|
1815
1993
|
// 插件注册的 AI 工具(创建时刻的实时快照,已按 disabledPluginTools 过滤;
|
|
1816
1994
|
// 后续注册经 refreshPluginTools 动态补入已有会话)。
|
|
1817
|
-
|
|
1995
|
+
// 子代理模板带非空扩展白名单时不注入:插件/MCP 工具没有 SDK extensionKey
|
|
1996
|
+
// 身份、无法参与白名单匹配,全放行等于白名单没关门,全收编才符合「只加载这些」。
|
|
1997
|
+
// 空白名单 = 跟随主会话(插件工具照常进入子代理)。
|
|
1998
|
+
...(apply && apply.enabledExtensions.length > 0 ? [] : this.enabledPluginToolDefs()),
|
|
1818
1999
|
// 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
|
|
1819
2000
|
// 也注册了它们,因此可自然嵌套派发。host 按 ownerId 包装:子代理的
|
|
1820
2001
|
// 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
|
|
@@ -1846,6 +2027,10 @@ export class ClientSession {
|
|
|
1846
2027
|
// 会话同样注册了它,可自然嵌套读取。不需要 ownerId——读的是本
|
|
1847
2028
|
// 客户端的 conversation 体系与落盘历史,与派发者无关。
|
|
1848
2029
|
makeConversationReadTool(this.conversationReadHost(), () => this.getLang()),
|
|
2030
|
+
// 技能全文按名加载(名录在 {{skills}} 段):模型不再拼路径调 read。
|
|
2031
|
+
// 子代理会话同样注册(owner 即真正派发的父对话,读该会话 loader)。
|
|
2032
|
+
// DSH 引擎无 customTool 注册面,不接。开关走统一工具 tab。
|
|
2033
|
+
makeSkillTool(this.skillToolHost(ownerId), () => this.getLang()),
|
|
1849
2034
|
// 定时唤醒三件套(schedule_task/list/cancel,issue #193):默认绑定
|
|
1850
2035
|
// 发起对话(ownerId,无则活动对话),到期 steer 语义唤醒它;子代理
|
|
1851
2036
|
// 会话同样注册(owner 即真正派发的父对话)。开关走统一工具 tab。
|
|
@@ -2055,6 +2240,8 @@ export class ClientSession {
|
|
|
2055
2240
|
// 默认重试 3 次——这里把面板的 retryMaxAttempts 覆盖注入,否则“设了 6
|
|
2056
2241
|
// 次还是按 3 次重试”。已存在会话重复注入是幂等的(同值覆盖)。
|
|
2057
2242
|
this.applyRetryOverrides();
|
|
2243
|
+
// 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
|
|
2244
|
+
this.applyCompactionOverrides();
|
|
2058
2245
|
this.scheduleSnapshot();
|
|
2059
2246
|
this.webUi.refresh();
|
|
2060
2247
|
this.startWidgetsTimer();
|
|
@@ -2103,6 +2290,11 @@ export class ClientSession {
|
|
|
2103
2290
|
* TOOL_WATCHDOG_TIMEOUT_MS, abort the session instead of letting the
|
|
2104
2291
|
* conversation hang forever (the SDK bash tool has no default timeout). */
|
|
2105
2292
|
armToolWatchdog(conv, toolCallId) {
|
|
2293
|
+
this.rearmToolWatchdog(conv, toolCallId, TOOL_WATCHDOG_TIMEOUT_MS);
|
|
2294
|
+
}
|
|
2295
|
+
/** (重)布工具挂死看门狗:delayMs 后仍在跑则 abort 整轮。过户时用剩余时间重布
|
|
2296
|
+
* (已逾期的立即触发,语义不变). */
|
|
2297
|
+
rearmToolWatchdog(conv, toolCallId, delayMs) {
|
|
2106
2298
|
const t = setTimeout(() => {
|
|
2107
2299
|
conv.toolWatchdogs.delete(toolCallId);
|
|
2108
2300
|
// The tool finished before the deadline — nothing to do.
|
|
@@ -2120,7 +2312,7 @@ export class ClientSession {
|
|
|
2120
2312
|
// clears any goal / review loop. interruptRun adds a force-reset
|
|
2121
2313
|
// fallback in case the model stream ignores the abort signal.
|
|
2122
2314
|
void this.interruptRun(conv, "工具执行超时");
|
|
2123
|
-
},
|
|
2315
|
+
}, Math.max(0, delayMs));
|
|
2124
2316
|
t.unref?.();
|
|
2125
2317
|
conv.toolWatchdogs.set(toolCallId, t);
|
|
2126
2318
|
}
|
|
@@ -2318,6 +2510,94 @@ export class ClientSession {
|
|
|
2318
2510
|
await conv.session.sendUserMessage(text, conv.session.isStreaming ? { deliverAs: "steer" } : undefined);
|
|
2319
2511
|
return { ok: true };
|
|
2320
2512
|
}
|
|
2513
|
+
/** issue #231:本客户端内按稳定键定位调度唤醒目标。
|
|
2514
|
+
* sessionFile 优先(压缩/重启后内存对话 id 已变,落盘会话文件才是同一会话);
|
|
2515
|
+
* 只有没给 sessionFile 时才按内存 id 找,且 id 必须附带 cwd 一致才认 ——
|
|
2516
|
+
* 各客户端计数器都从 c1 开始,跨项目同 id 必然撞车,不校验 cwd 会把巡检
|
|
2517
|
+
* 报告投进完全无关的项目对话。
|
|
2518
|
+
* excludeIds 用于视口回退时跳过已知的忙对话。 */
|
|
2519
|
+
resolveSchedulerTarget(opts) {
|
|
2520
|
+
const wantFile = String(opts.sessionFile ?? "").trim();
|
|
2521
|
+
const wantId = String(opts.conversationId ?? "").trim();
|
|
2522
|
+
const wantCwd = String(opts.cwd ?? "").trim();
|
|
2523
|
+
const excluded = opts.excludeIds;
|
|
2524
|
+
if (wantFile) {
|
|
2525
|
+
let best = null;
|
|
2526
|
+
for (const c of this.convs.values()) {
|
|
2527
|
+
if (!c?.session || (excluded && excluded.has(c.id)))
|
|
2528
|
+
continue;
|
|
2529
|
+
let f = "";
|
|
2530
|
+
try {
|
|
2531
|
+
f = String(c.session.sessionFile ?? "");
|
|
2532
|
+
}
|
|
2533
|
+
catch {
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
if (!sameSessionFile(f, wantFile))
|
|
2537
|
+
continue;
|
|
2538
|
+
if (!best || c.lastActiveAt > best.lastActiveAt)
|
|
2539
|
+
best = c;
|
|
2540
|
+
}
|
|
2541
|
+
if (best)
|
|
2542
|
+
return best;
|
|
2543
|
+
}
|
|
2544
|
+
if (wantId) {
|
|
2545
|
+
const c = this.convs.get(wantId);
|
|
2546
|
+
if (!c?.session || (excluded && excluded.has(c.id)))
|
|
2547
|
+
return null;
|
|
2548
|
+
if (wantCwd && !sameCwd(c.cwd, wantCwd))
|
|
2549
|
+
return null;
|
|
2550
|
+
return c;
|
|
2551
|
+
}
|
|
2552
|
+
return null;
|
|
2553
|
+
}
|
|
2554
|
+
/** issue #231:本客户端内同项目的最近活跃对话(视口回退目标)。
|
|
2555
|
+
* 主对话优先(用户正看着的面),没有主对话时才考虑子代理行;
|
|
2556
|
+
* 最近活跃者即用户当前的视口。 */
|
|
2557
|
+
findViewportInCwd(cwd, excludeIds) {
|
|
2558
|
+
const want = String(cwd ?? "").trim();
|
|
2559
|
+
if (!want)
|
|
2560
|
+
return null;
|
|
2561
|
+
let best = null;
|
|
2562
|
+
let bestSub = null;
|
|
2563
|
+
for (const c of this.convs.values()) {
|
|
2564
|
+
if (!c?.session || (excludeIds && excludeIds.has(c.id)))
|
|
2565
|
+
continue;
|
|
2566
|
+
if (!sameCwd(c.cwd, want))
|
|
2567
|
+
continue;
|
|
2568
|
+
if (c.isSubagent) {
|
|
2569
|
+
if (!bestSub || c.lastActiveAt > bestSub.lastActiveAt)
|
|
2570
|
+
bestSub = c;
|
|
2571
|
+
}
|
|
2572
|
+
else if (!best || c.lastActiveAt > best.lastActiveAt) {
|
|
2573
|
+
best = c;
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return best ?? bestSub;
|
|
2577
|
+
}
|
|
2578
|
+
/** issue #231:带压缩忙检测的调度 steer。压缩进行中时 SDK 直接抛错
|
|
2579
|
+
* (Cannot submit a prompt while compaction is in progress),调用方据 busy
|
|
2580
|
+
* 另寻视口兄弟或稍后重试,而不是当成“对话不在”静默转无头。 */
|
|
2581
|
+
async trySteerScheduler(conv, text) {
|
|
2582
|
+
try {
|
|
2583
|
+
try {
|
|
2584
|
+
if (conv.session.isCompacting === true) {
|
|
2585
|
+
return { ok: false, busy: true, error: "上下文压缩进行中,稍后重试" };
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
catch {
|
|
2589
|
+
/* 读不到压缩态就直接投递,失败按异常走 */
|
|
2590
|
+
}
|
|
2591
|
+
await conv.session.sendUserMessage(text, conv.session.isStreaming ? { deliverAs: "steer" } : undefined);
|
|
2592
|
+
return { ok: true };
|
|
2593
|
+
}
|
|
2594
|
+
catch (err) {
|
|
2595
|
+
const msg = String(err?.message ?? err);
|
|
2596
|
+
if (/compaction is in progress/i.test(msg))
|
|
2597
|
+
return { ok: false, busy: true, error: msg };
|
|
2598
|
+
return { ok: false, busy: false, error: msg };
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2321
2601
|
/** 插件扩展点(供 runSteerer):向指定对话插队一条用户消息,复用子代理 steer 的
|
|
2322
2602
|
* sendUserMessage + deliverAs:'steer' 路径(运行时插队;未跑时按普通消息投递)。
|
|
2323
2603
|
* 先找本客户端 conversations,找不到再经 steerConversationElsewhere 问其他客户端;
|
|
@@ -2924,12 +3204,14 @@ export class ClientSession {
|
|
|
2924
3204
|
contextWindow: cu.contextWindow,
|
|
2925
3205
|
percent: (conv.lastCompactionTokens / cu.contextWindow) * 100,
|
|
2926
3206
|
estimated: true,
|
|
3207
|
+
softCap: this.activeSoftCap(cu.contextWindow),
|
|
2927
3208
|
};
|
|
2928
3209
|
}
|
|
2929
3210
|
return {
|
|
2930
3211
|
tokens: cu.tokens,
|
|
2931
3212
|
contextWindow: cu.contextWindow,
|
|
2932
3213
|
percent: cu.percent,
|
|
3214
|
+
softCap: this.activeSoftCap(cu.contextWindow),
|
|
2933
3215
|
};
|
|
2934
3216
|
})(),
|
|
2935
3217
|
};
|
|
@@ -3065,6 +3347,8 @@ export class ClientSession {
|
|
|
3065
3347
|
}
|
|
3066
3348
|
const id = `q-${++this.questionSeq}`;
|
|
3067
3349
|
this.pendingQuestions.set(id, { resolve, questions, conversationId });
|
|
3350
|
+
// 运行列表的「?」角标靠 conversations 推送(问卷登记/解决不经过快照通道)。
|
|
3351
|
+
this.emitConversations();
|
|
3068
3352
|
this.emit({
|
|
3069
3353
|
type: "question_pending",
|
|
3070
3354
|
id,
|
|
@@ -3073,14 +3357,20 @@ export class ClientSession {
|
|
|
3073
3357
|
});
|
|
3074
3358
|
}
|
|
3075
3359
|
/** 前端回答模型提问(question_answer → 恢复 askUser 的 Promise)。id 需匹配
|
|
3076
|
-
* pendingQuestions
|
|
3077
|
-
*
|
|
3360
|
+
* pendingQuestions 中键;未匹配(对方刚回答/取消、页面刷新重发)静默忽略。
|
|
3361
|
+
* 成功 resolve 后同步推 question_retracted + conversations:本页 live 对话框
|
|
3362
|
+
* 靠前者收起(跨页作答时源页就靠它),别处的「?」角标靠后者即时消失。
|
|
3363
|
+
* 返回是否真的恢复了一个挂起提问(跨页作答的送达回执用)。 */
|
|
3078
3364
|
resolveQuestion(id, answers, cancelled) {
|
|
3079
3365
|
const pending = this.pendingQuestions.get(id);
|
|
3080
|
-
if (pending)
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3366
|
+
if (!pending)
|
|
3367
|
+
return false;
|
|
3368
|
+
this.pendingQuestions.delete(id);
|
|
3369
|
+
pending.resolve(cancelled ? null : answers);
|
|
3370
|
+
this.emit({ type: "question_retracted", id });
|
|
3371
|
+
// 同上:角标消失也要即时推送(否则要等到 run 结束别处才知道问完了)。
|
|
3372
|
+
this.emitConversations();
|
|
3373
|
+
return true;
|
|
3084
3374
|
}
|
|
3085
3375
|
/** 快照侧的待答提问(UiState.pendingQuestion):只带当前对话的问卷——切回
|
|
3086
3376
|
* 原对话会重推快照,对话框随之回来(重连/刷新/第二标签页的恢复通道)。 */
|
|
@@ -3106,6 +3396,18 @@ export class ClientSession {
|
|
|
3106
3396
|
this.resolveQuestion(id, answers, cancelled);
|
|
3107
3397
|
return Promise.resolve();
|
|
3108
3398
|
}
|
|
3399
|
+
/** 取某对话的等答复问卷原文(跨页作答的 peek 用;只读,不改变状态)。 */
|
|
3400
|
+
peekPendingQuestion(convId) {
|
|
3401
|
+
for (const [id, p] of this.pendingQuestions) {
|
|
3402
|
+
if (p.conversationId === convId)
|
|
3403
|
+
return { id, questions: p.questions };
|
|
3404
|
+
}
|
|
3405
|
+
return undefined;
|
|
3406
|
+
}
|
|
3407
|
+
/** 跨页作答:把别处问卷的原文推给本页弹框(回答经 answerElsewhereQuestion 回去)。 */
|
|
3408
|
+
pushElsewhereQuestion(owner, convId, q) {
|
|
3409
|
+
this.emit({ type: "elsewhere_question", owner, convId, id: q.id, questions: q.questions });
|
|
3410
|
+
}
|
|
3109
3411
|
/** 关闭所有挂起提问(dispose 时清理):以「取消」解析,避免模型挂死。 */
|
|
3110
3412
|
cancelPendingQuestions() {
|
|
3111
3413
|
for (const [, p] of this.pendingQuestions) {
|
|
@@ -3174,6 +3476,20 @@ export class ClientSession {
|
|
|
3174
3476
|
return { reason: `视觉桥转写失败:${err instanceof Error ? err.message : String(err)}` };
|
|
3175
3477
|
}
|
|
3176
3478
|
}
|
|
3479
|
+
/** 页调用超时计时器:到点按失败 resolve(晚到的 page_response 在
|
|
3480
|
+
* resolvePageCall 里找不到 id 会静默忽略)。过户重建时复用(计时重走). */
|
|
3481
|
+
armPageCallTimeout(id, resolve, timeoutMs) {
|
|
3482
|
+
return setTimeout(() => {
|
|
3483
|
+
// 到点:先删再 resolve——晚到的 page_response 在 resolvePageCall 里找
|
|
3484
|
+
// 找不到 id,会静默忽略(见那里的注释)。
|
|
3485
|
+
if (this.pendingPageCalls.delete(id)) {
|
|
3486
|
+
resolve({
|
|
3487
|
+
ok: false,
|
|
3488
|
+
error: `${Math.round(timeoutMs / 1000)} 秒内没有收到浏览器响应(timeout ${timeoutMs}ms)。请确认 pi-web-ui 页面已打开且 page-picker 扩展已启用。`,
|
|
3489
|
+
});
|
|
3490
|
+
}
|
|
3491
|
+
}, timeoutMs);
|
|
3492
|
+
}
|
|
3177
3493
|
pageCall(req, sig, conversationId) {
|
|
3178
3494
|
return new Promise((resolve) => {
|
|
3179
3495
|
if (sig?.aborted || this.disposed) {
|
|
@@ -3190,18 +3506,9 @@ export class ClientSession {
|
|
|
3190
3506
|
const id = `p-${++this.pageSeq}`;
|
|
3191
3507
|
// 夹取与工具入口同一套规则(防手写脏值/其它调用方绕过 schema)。
|
|
3192
3508
|
const timeoutMs = normalizePageCallTimeoutMs(req.timeoutMs);
|
|
3193
|
-
const timer =
|
|
3194
|
-
// 到点:先删再 resolve——晚到的 page_response 在 resolvePageCall 里找
|
|
3195
|
-
// 找不到 id,会静默忽略(见那里的注释)。
|
|
3196
|
-
if (this.pendingPageCalls.delete(id)) {
|
|
3197
|
-
resolve({
|
|
3198
|
-
ok: false,
|
|
3199
|
-
error: `${Math.round(timeoutMs / 1000)} 秒内没有收到浏览器响应(timeout ${timeoutMs}ms)。请确认 pi-web-ui 页面已打开且 page-picker 扩展已启用。`,
|
|
3200
|
-
});
|
|
3201
|
-
}
|
|
3202
|
-
}, timeoutMs);
|
|
3509
|
+
const timer = this.armPageCallTimeout(id, resolve, timeoutMs);
|
|
3203
3510
|
// 先登记再发:同步回包(同进程假客户端)也不能漏掉。
|
|
3204
|
-
this.pendingPageCalls.set(id, { resolve, timer, conversationId });
|
|
3511
|
+
this.pendingPageCalls.set(id, { resolve, timer, conversationId, req, timeoutMs });
|
|
3205
3512
|
this.emit({ type: "page_request", id, op: req.op, args: req.args, target: req.target, timeoutMs });
|
|
3206
3513
|
});
|
|
3207
3514
|
}
|
|
@@ -3538,8 +3845,9 @@ export class ClientSession {
|
|
|
3538
3845
|
},
|
|
3539
3846
|
refreshSessions: () => this.refreshSessions(),
|
|
3540
3847
|
afterReload: () => {
|
|
3541
|
-
// /reload 同样重读磁盘 settings.json——重放重试覆盖 + 终端门控。
|
|
3848
|
+
// /reload 同样重读磁盘 settings.json——重放重试覆盖 + 软上限覆盖 + 终端门控。
|
|
3542
3849
|
this.applyRetryOverrides();
|
|
3850
|
+
this.applyCompactionOverrides();
|
|
3543
3851
|
this.applyToolGating(this.session);
|
|
3544
3852
|
},
|
|
3545
3853
|
pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
|
|
@@ -3783,6 +4091,40 @@ export class ClientSession {
|
|
|
3783
4091
|
}
|
|
3784
4092
|
}
|
|
3785
4093
|
}
|
|
4094
|
+
/** 把压缩软上限换算成各存活会话的 compaction reserveTokens 覆盖
|
|
4095
|
+
* (issue #229)。与重试覆盖同一 live 机制:applyOverrides 只改内存
|
|
4096
|
+
* 合并视图,SDK 每次自动压缩检查前都重读 getCompactionSettings(),
|
|
4097
|
+
* 无需 reload;软上限关闭时回填 SDK 默认 reserve(不让旧覆盖泄漏)。
|
|
4098
|
+
* 窗口未知(会话未就绪/无模型)的会话跳过——创建/就绪/换模型路径
|
|
4099
|
+
* 会重放(见各 applyRetryOverrides 调用点)。 */
|
|
4100
|
+
applyCompactionOverrides() {
|
|
4101
|
+
const s = this.settingsSvc.current;
|
|
4102
|
+
for (const c of this.convs.values()) {
|
|
4103
|
+
try {
|
|
4104
|
+
const modelId = modelKeyOf(c.session);
|
|
4105
|
+
const contextWindow = contextWindowOf(c.session);
|
|
4106
|
+
const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelId);
|
|
4107
|
+
const reserve = softCapToReserve(contextWindow, cap);
|
|
4108
|
+
c.session.settingsManager.applyOverrides({
|
|
4109
|
+
compaction: { reserveTokens: reserve ?? DEFAULT_COMPACTION_RESERVE_TOKENS },
|
|
4110
|
+
});
|
|
4111
|
+
}
|
|
4112
|
+
catch {
|
|
4113
|
+
// 会话未就绪或已释放 → 其 runtime 创建时统一注入。
|
|
4114
|
+
}
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
/** 当前活动对话的生效软上限(快照底栏标记线用;null = 关闭/未知)。 */
|
|
4118
|
+
activeSoftCap(contextWindow) {
|
|
4119
|
+
try {
|
|
4120
|
+
const s = this.settingsSvc.current;
|
|
4121
|
+
const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(this.session));
|
|
4122
|
+
return softCapToReserve(contextWindow, cap) === null ? null : cap;
|
|
4123
|
+
}
|
|
4124
|
+
catch {
|
|
4125
|
+
return null;
|
|
4126
|
+
}
|
|
4127
|
+
}
|
|
3786
4128
|
/** Extensions/skills changed externally (e.g. `pi remove` finished in the
|
|
3787
4129
|
* terminal): re-run session.reload() and re-push state. Streaming-safe —
|
|
3788
4130
|
* deferred to agent_end, same as settings reloads. */
|
|
@@ -3817,6 +4159,7 @@ export class ClientSession {
|
|
|
3817
4159
|
try {
|
|
3818
4160
|
await this.session.reload();
|
|
3819
4161
|
this.applyRetryOverrides();
|
|
4162
|
+
this.applyCompactionOverrides();
|
|
3820
4163
|
this.applyToolGating(this.session);
|
|
3821
4164
|
await this.pushSlashCommands();
|
|
3822
4165
|
this.pushSettings();
|
|
@@ -3879,8 +4222,14 @@ export class ClientSession {
|
|
|
3879
4222
|
return (this.pluginToolsProvider?.() ?? []).filter((t) => !off.has(t.name)).map(pluginToolToDefinition);
|
|
3880
4223
|
}
|
|
3881
4224
|
/** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
|
|
3882
|
-
* 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。
|
|
4225
|
+
* 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。
|
|
4226
|
+
* 模板白名单的子代理(subagentBarsPluginTools)跳过:工厂期就没注册,这里
|
|
4227
|
+
* 不回补,否则白名单等于没关门。 */
|
|
3883
4228
|
syncPluginTools(session) {
|
|
4229
|
+
for (const conv of this.convs.values()) {
|
|
4230
|
+
if (conv.session === session && conv.subagentBarsPluginTools)
|
|
4231
|
+
return;
|
|
4232
|
+
}
|
|
3884
4233
|
try {
|
|
3885
4234
|
const defs = this.enabledPluginToolDefs();
|
|
3886
4235
|
const next = syncPluginToolsIntoSession(session, defs, this.appliedPluginToolNames);
|
|
@@ -4019,7 +4368,8 @@ export class ClientSession {
|
|
|
4019
4368
|
}
|
|
4020
4369
|
return out;
|
|
4021
4370
|
}
|
|
4022
|
-
/** issue #145:本实例所有正在跑的对话摘要(elsewhere
|
|
4371
|
+
/** issue #145:本实例所有正在跑的对话摘要(elsewhere 列表的本机一半 +
|
|
4372
|
+
* 手动过户的目标定位:convId + 是否有等答复问卷)。 */
|
|
4023
4373
|
streamingSummariesAll() {
|
|
4024
4374
|
const out = [];
|
|
4025
4375
|
for (const conv of this.convs.values()) {
|
|
@@ -4027,10 +4377,62 @@ export class ClientSession {
|
|
|
4027
4377
|
continue;
|
|
4028
4378
|
if (!this.conversationStreaming(conv))
|
|
4029
4379
|
continue;
|
|
4030
|
-
out.push({
|
|
4380
|
+
out.push({
|
|
4381
|
+
title: conv.title,
|
|
4382
|
+
cwd: conv.cwd,
|
|
4383
|
+
isStreaming: true,
|
|
4384
|
+
convId: conv.id,
|
|
4385
|
+
hasQuestion: this.isWaitingOnUser(conv.id),
|
|
4386
|
+
});
|
|
4031
4387
|
}
|
|
4032
4388
|
return out;
|
|
4033
4389
|
}
|
|
4390
|
+
/**
|
|
4391
|
+
* 浏览器重启认领用:本会话是否有值得新标签接管的内容。
|
|
4392
|
+
* 跑着的(主对话/子代理都算)、后台挂着的(listed)、有消息历史的都算;
|
|
4393
|
+
* 纯空白会话(刚建就关了标签)不算 —— 认领它与新建无异,不如走新建流程。
|
|
4394
|
+
* 零 token 冒烟测试的残留会话永远是空白的,因此认领逻辑不会改变它们的行为。
|
|
4395
|
+
*/
|
|
4396
|
+
hasAdoptableContent() {
|
|
4397
|
+
for (const c of this.convs.values()) {
|
|
4398
|
+
try {
|
|
4399
|
+
if (c.session.isStreaming)
|
|
4400
|
+
return true;
|
|
4401
|
+
}
|
|
4402
|
+
catch {
|
|
4403
|
+
// 会话替换中 —— 按未跑处理
|
|
4404
|
+
}
|
|
4405
|
+
if (c.isSubagent)
|
|
4406
|
+
continue;
|
|
4407
|
+
if (c.listed)
|
|
4408
|
+
return true;
|
|
4409
|
+
try {
|
|
4410
|
+
if (c.session.getSessionStats().totalMessages > 0)
|
|
4411
|
+
return true;
|
|
4412
|
+
}
|
|
4413
|
+
catch {
|
|
4414
|
+
// 会话替换中 —— 按无消息处理
|
|
4415
|
+
}
|
|
4416
|
+
}
|
|
4417
|
+
return false;
|
|
4418
|
+
}
|
|
4419
|
+
/** 各对话最近活跃时间的最大值(认领时多个残留按此排序,新的优先)。 */
|
|
4420
|
+
latestActivity() {
|
|
4421
|
+
let at = 0;
|
|
4422
|
+
for (const c of this.convs.values()) {
|
|
4423
|
+
at = Math.max(at, c.lastActiveAt || 0, c.lastSdkEventAt || 0);
|
|
4424
|
+
}
|
|
4425
|
+
return at;
|
|
4426
|
+
}
|
|
4427
|
+
/** 被新标签认领后首帧即被告之(pendingNotices 随 attachSink 下发)。 */
|
|
4428
|
+
noteAdopted() {
|
|
4429
|
+
this.pendingNotices.push({
|
|
4430
|
+
type: "notice",
|
|
4431
|
+
level: "info",
|
|
4432
|
+
text: "已恢复你关闭浏览器前的工作会话(含运行中的对话),可直接继续查看与操作。",
|
|
4433
|
+
textEn: "Restored the workspace session from before the browser was closed, including its running conversations — pick up right where you left off.",
|
|
4434
|
+
});
|
|
4435
|
+
}
|
|
4034
4436
|
/** issue #145:让其他客户端重推 conversations(elsewhere 刷新用;
|
|
4035
4437
|
* 流式集合签名驱动,外层循环安全)。 */
|
|
4036
4438
|
refreshExternalRunning() {
|
|
@@ -4099,7 +4501,8 @@ export class ClientSession {
|
|
|
4099
4501
|
// issue #145:同项目并行感知 —— 同一 cwd 下别处(或其他对话)正在跑时,
|
|
4100
4502
|
// 允许并行(可以同时改不同部分),但用户与 AI 都必须知道。只在新一轮启动时
|
|
4101
4503
|
// 通告一次(steer/排队等流式中发送不重复打扰)。
|
|
4102
|
-
|
|
4504
|
+
// parallelReminderEnabled=false 时整段跳过(不发 notice、不注 AI、不通知对端)。
|
|
4505
|
+
if (!conv.isSubagent && !s.isStreaming && this.settingsSvc.current.parallelReminderEnabled !== false) {
|
|
4103
4506
|
const localRunners = [...this.convs.values()]
|
|
4104
4507
|
.filter((c) => c.id !== conv.id && !c.isSubagent && c.cwd === conv.cwd && this.conversationStreaming(c))
|
|
4105
4508
|
.map((c) => ({ title: c.title }));
|
|
@@ -4552,11 +4955,17 @@ export class ClientSession {
|
|
|
4552
4955
|
this.clearAllToolWatchdogs(conv);
|
|
4553
4956
|
conv.toolStartTimes.clear();
|
|
4554
4957
|
await conv.runtime.dispose();
|
|
4555
|
-
|
|
4958
|
+
// #235:转录链损坏时修一次再试(见 openManagerAndRuntime)。
|
|
4959
|
+
const opened = await this.openManagerAndRuntime(() => SessionManager.continueRecent(conv.cwd), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, undefined, conv.id), {
|
|
4556
4960
|
cwd: conv.cwd,
|
|
4557
4961
|
agentDir: this.agentDir,
|
|
4558
|
-
sessionManager:
|
|
4559
|
-
});
|
|
4962
|
+
sessionManager: m,
|
|
4963
|
+
}), async () => (await SessionManager.list(conv.cwd))[0]?.path);
|
|
4964
|
+
const runtime = opened.runtime;
|
|
4965
|
+
if (opened.repair) {
|
|
4966
|
+
for (const n of this.transcriptRepairNotices(opened.repair))
|
|
4967
|
+
this.emit(n);
|
|
4968
|
+
}
|
|
4560
4969
|
conv.runtime = runtime;
|
|
4561
4970
|
conv.session = runtime.session;
|
|
4562
4971
|
this.emit({
|
|
@@ -4711,9 +5120,11 @@ export class ClientSession {
|
|
|
4711
5120
|
return;
|
|
4712
5121
|
// parentId joins the live chain: a null-parent marker would become a
|
|
4713
5122
|
// second root and hijack the leaf, corrupting the transcript.
|
|
5123
|
+
// #235: id 必须唯一——硬编码共享 id + SDK byId last-wins + 标记恰为末行
|
|
5124
|
+
// 时新消息 parent 记成共享 id = 下次 open 回溯成环,整个会话打不开。
|
|
4714
5125
|
const marker = {
|
|
4715
5126
|
type: "custom",
|
|
4716
|
-
id: "
|
|
5127
|
+
id: makeCompactionMarkerId("pending"),
|
|
4717
5128
|
parentId: conv.session.sessionManager.getLeafId(),
|
|
4718
5129
|
timestamp: new Date().toISOString(),
|
|
4719
5130
|
customType: "pi-web-ui/compaction-pending",
|
|
@@ -4740,10 +5151,18 @@ export class ClientSession {
|
|
|
4740
5151
|
const file = conv.session.sessionFile;
|
|
4741
5152
|
if (!file || !existsSync(file))
|
|
4742
5153
|
return;
|
|
4743
|
-
const id = "pi-web-ui-compaction-pending";
|
|
4744
5154
|
const raw = readFileSync(file, "utf8");
|
|
4745
5155
|
const lines = raw.split("\n");
|
|
4746
|
-
|
|
5156
|
+
// #235:按 customType 定位(id 自本 fix 起唯一,老文件仍是硬编码 id,
|
|
5157
|
+
// 按 id 找已不可靠)。取最后一个:重叠压缩时它属于本次,旧残留留给
|
|
5158
|
+
// 下次 open 的 repair/notice 处理。
|
|
5159
|
+
let idx = -1;
|
|
5160
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
5161
|
+
if (lines[i].includes(`"${COMPACTION_PENDING_TYPE}"`)) {
|
|
5162
|
+
idx = i;
|
|
5163
|
+
break;
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
4747
5166
|
if (idx < 0)
|
|
4748
5167
|
return;
|
|
4749
5168
|
// ponytail: full-file rewrite on compaction end — compactions are rare
|
|
@@ -4761,7 +5180,7 @@ export class ClientSession {
|
|
|
4761
5180
|
}
|
|
4762
5181
|
const done = {
|
|
4763
5182
|
type: "custom",
|
|
4764
|
-
id: "
|
|
5183
|
+
id: makeCompactionMarkerId("done"),
|
|
4765
5184
|
parentId,
|
|
4766
5185
|
timestamp: new Date().toISOString(),
|
|
4767
5186
|
customType: "pi-web-ui/compaction-done",
|
|
@@ -4791,15 +5210,80 @@ export class ClientSession {
|
|
|
4791
5210
|
return;
|
|
4792
5211
|
const kept = raw.split("\n").filter((line) => !line.includes("pi-web-ui/compaction-pending"));
|
|
4793
5212
|
writeFileSync(file, kept.join("\n"));
|
|
4794
|
-
this.
|
|
5213
|
+
this.emitCompactionInterruptedNotice();
|
|
5214
|
+
}
|
|
5215
|
+
catch {
|
|
5216
|
+
// Best-effort, same as the write path.
|
|
5217
|
+
}
|
|
5218
|
+
}
|
|
5219
|
+
emitCompactionInterruptedNotice() {
|
|
5220
|
+
this.emit({
|
|
5221
|
+
type: "notice",
|
|
5222
|
+
level: "warning",
|
|
5223
|
+
text: "上次压缩上下文被服务端重启打断,未完成。可发送 /compact 重试。",
|
|
5224
|
+
textEn: "The last context compaction was interrupted by a server restart and did not finish. Send /compact to retry.",
|
|
5225
|
+
});
|
|
5226
|
+
}
|
|
5227
|
+
/** #235 修复产生的提示(调用方决定 emit 还是进 pendingNotices)。 */
|
|
5228
|
+
transcriptRepairNotices(repair) {
|
|
5229
|
+
const out = [];
|
|
5230
|
+
if (repair.interrupted) {
|
|
5231
|
+
out.push({
|
|
4795
5232
|
type: "notice",
|
|
4796
5233
|
level: "warning",
|
|
4797
5234
|
text: "上次压缩上下文被服务端重启打断,未完成。可发送 /compact 重试。",
|
|
4798
5235
|
textEn: "The last context compaction was interrupted by a server restart and did not finish. Send /compact to retry.",
|
|
4799
5236
|
});
|
|
4800
5237
|
}
|
|
5238
|
+
if (repair.renamedIds > 0 || repair.rewiredParents > 0 || repair.cyclesBroken > 0) {
|
|
5239
|
+
out.push({
|
|
5240
|
+
type: "notice",
|
|
5241
|
+
level: "warning",
|
|
5242
|
+
text: `对话记录链损坏已自动修复(重复的压缩标记),原文件备份在 ${repair.backup ?? "同目录 .bak 文件"}。如内容异常可手动恢复。`,
|
|
5243
|
+
textEn: `The conversation transcript had a corrupted parent chain (duplicate compaction markers) and was auto-repaired. The original file is backed up at ${repair.backup ?? "a .bak file next to it"}; restore it manually if anything looks off.`,
|
|
5244
|
+
});
|
|
5245
|
+
}
|
|
5246
|
+
return out;
|
|
5247
|
+
}
|
|
5248
|
+
/**
|
|
5249
|
+
* #235:已知路径先修后开(openConversation 走这条——单文件预扫描零负担)。
|
|
5250
|
+
* 返回 null = 文件健康或无需处理;返回 repair = 修过,调用方弹提示。
|
|
5251
|
+
*/
|
|
5252
|
+
repairTranscriptFileBeforeOpen(filePath) {
|
|
5253
|
+
let repair = null;
|
|
5254
|
+
try {
|
|
5255
|
+
repair = repairSessionFile(filePath);
|
|
5256
|
+
}
|
|
4801
5257
|
catch {
|
|
4802
|
-
|
|
5258
|
+
return null;
|
|
5259
|
+
}
|
|
5260
|
+
if (!repair?.changed)
|
|
5261
|
+
return null;
|
|
5262
|
+
for (const n of this.transcriptRepairNotices(repair))
|
|
5263
|
+
this.emit(n);
|
|
5264
|
+
return repair;
|
|
5265
|
+
}
|
|
5266
|
+
/**
|
|
5267
|
+
* #235:manager+runtime 一起建,链损坏报错则修最近文件后重试一次。
|
|
5268
|
+
* SessionManager.open 本身不走 parent 链(真正死循环的是 runtime 初始化里的
|
|
5269
|
+
* getBranch),所以重试必须把两步都包进来;修完用全新 manager 重读。
|
|
5270
|
+
*/
|
|
5271
|
+
async openManagerAndRuntime(makeManager, makeRuntime, locateFile) {
|
|
5272
|
+
try {
|
|
5273
|
+
const manager = makeManager();
|
|
5274
|
+
const runtime = await makeRuntime(manager);
|
|
5275
|
+
return { manager, runtime, repair: null };
|
|
5276
|
+
}
|
|
5277
|
+
catch (err) {
|
|
5278
|
+
if (!looksLikeChainCorruption(err))
|
|
5279
|
+
throw err;
|
|
5280
|
+
const file = await locateFile().catch(() => undefined);
|
|
5281
|
+
const repair = file ? repairSessionFile(file) : null;
|
|
5282
|
+
if (!repair?.changed)
|
|
5283
|
+
throw err;
|
|
5284
|
+
const manager = makeManager();
|
|
5285
|
+
const runtime = await makeRuntime(manager);
|
|
5286
|
+
return { manager, runtime, repair };
|
|
4803
5287
|
}
|
|
4804
5288
|
}
|
|
4805
5289
|
displaceActive() {
|
|
@@ -4863,6 +5347,133 @@ export class ClientSession {
|
|
|
4863
5347
|
conv.unsubscribe = undefined;
|
|
4864
5348
|
void conv.runtime.dispose().catch(() => { });
|
|
4865
5349
|
}
|
|
5350
|
+
/** 过户用的对话摘要(AgentService 拼移动集合 + 容量检查用)。 */
|
|
5351
|
+
takeoverBriefs() {
|
|
5352
|
+
return [...this.convs.values()].map((c) => ({
|
|
5353
|
+
id: c.id,
|
|
5354
|
+
title: c.title,
|
|
5355
|
+
cwd: c.cwd,
|
|
5356
|
+
...(c.parentId ? { parentId: c.parentId } : {}),
|
|
5357
|
+
isSubagent: c.isSubagent,
|
|
5358
|
+
}));
|
|
5359
|
+
}
|
|
5360
|
+
/**
|
|
5361
|
+
* 过户转出:把指定对话(含事件订阅/看门狗计时器/等答复问卷/页调用)从本会话摘除。
|
|
5362
|
+
* - 先修 active:active 被搬且还有剩余 → 切过去(优先主对话);active 被搬且掏空 →
|
|
5363
|
+
* 建空白兜底,建不出来(quiesce)则拒绝搬出(ok:false),绝不留悬空 active。
|
|
5364
|
+
* - 看门狗计时器清掉(toolStartTimes 保留,目标按剩余时间重布)。
|
|
5365
|
+
* - 只搬归属被搬对话的问卷/页调用(conversationId 对得上的;未记归属的留在源会话)。
|
|
5366
|
+
*/
|
|
5367
|
+
async detachTakeoverConversations(ids) {
|
|
5368
|
+
const set = new Set(ids);
|
|
5369
|
+
const convs = [...this.convs.values()].filter((c) => set.has(c.id));
|
|
5370
|
+
if (convs.length === 0)
|
|
5371
|
+
return { ok: false, reason: "missing" };
|
|
5372
|
+
if (set.has(this.activeId)) {
|
|
5373
|
+
const remaining = [...this.convs.values()].find((c) => !set.has(c.id) && !c.isSubagent) ??
|
|
5374
|
+
[...this.convs.values()].find((c) => !set.has(c.id));
|
|
5375
|
+
if (remaining) {
|
|
5376
|
+
await this.switchConversation(remaining.id);
|
|
5377
|
+
}
|
|
5378
|
+
else if (!(await this.newChat())) {
|
|
5379
|
+
return { ok: false, reason: "empty" };
|
|
5380
|
+
}
|
|
5381
|
+
}
|
|
5382
|
+
for (const conv of convs) {
|
|
5383
|
+
this.convs.delete(conv.id);
|
|
5384
|
+
this.clearAllToolWatchdogs(conv);
|
|
5385
|
+
conv.unsubscribe?.();
|
|
5386
|
+
conv.unsubscribe = undefined;
|
|
5387
|
+
}
|
|
5388
|
+
const questions = [];
|
|
5389
|
+
for (const [qid, p] of this.pendingQuestions) {
|
|
5390
|
+
if (p.conversationId !== undefined && set.has(p.conversationId)) {
|
|
5391
|
+
this.pendingQuestions.delete(qid);
|
|
5392
|
+
questions.push({ resolve: p.resolve, questions: p.questions, conversationId: p.conversationId });
|
|
5393
|
+
// 源页面的对话框可能是即时通道弹出的(live),快照为 null 收不掉它 ——
|
|
5394
|
+
// 明确撤回,让源页面立即收起(目标页由转入方重推 question_pending)。
|
|
5395
|
+
this.emit({ type: "question_retracted", id: qid });
|
|
5396
|
+
}
|
|
5397
|
+
}
|
|
5398
|
+
const pageCalls = [];
|
|
5399
|
+
for (const [pid, p] of this.pendingPageCalls) {
|
|
5400
|
+
if (p.conversationId !== undefined && set.has(p.conversationId)) {
|
|
5401
|
+
this.pendingPageCalls.delete(pid);
|
|
5402
|
+
clearTimeout(p.timer);
|
|
5403
|
+
pageCalls.push({ resolve: p.resolve, req: p.req, timeoutMs: p.timeoutMs, conversationId: p.conversationId });
|
|
5404
|
+
}
|
|
5405
|
+
}
|
|
5406
|
+
this.emitConversations();
|
|
5407
|
+
this.flushSnapshot();
|
|
5408
|
+
return { ok: true, payload: { convs, questions, pageCalls } };
|
|
5409
|
+
}
|
|
5410
|
+
/**
|
|
5411
|
+
* 过户转入:把另一会话摘除的对话整体接过来,返回主对话的新 id。
|
|
5412
|
+
* - id 冲突(两边计数器都从 c1 开始,大概率撞上)→ 给搬入方分配新 id,move
|
|
5413
|
+
* 集合内的 parentId/问卷归属同步改写。模型手里旧 runId 的后续子代理工具调用
|
|
5414
|
+
* 会报 unknown(可经列表查新 id);定时唤醒的旧 id 同理回落无头执行。
|
|
5415
|
+
* - 事件订阅/终端投递/问卷/页调用全部重接到本会话并立即重推(问卷对话框在新
|
|
5416
|
+
* 页面直接弹出来)。看门狗按剩余时间重布(已逾期的立即触发)。
|
|
5417
|
+
*/
|
|
5418
|
+
insertTakeoverConvs(payload) {
|
|
5419
|
+
const remap = new Map();
|
|
5420
|
+
for (const conv of payload.convs) {
|
|
5421
|
+
if (this.convs.has(conv.id)) {
|
|
5422
|
+
remap.set(conv.id, this.nextConversationId());
|
|
5423
|
+
}
|
|
5424
|
+
}
|
|
5425
|
+
const fix = (id) => remap.get(id) ?? id;
|
|
5426
|
+
let mainId = "";
|
|
5427
|
+
for (const conv of payload.convs) {
|
|
5428
|
+
conv.id = fix(conv.id);
|
|
5429
|
+
if (conv.parentId)
|
|
5430
|
+
conv.parentId = fix(conv.parentId);
|
|
5431
|
+
if (!conv.isSubagent && !mainId)
|
|
5432
|
+
mainId = conv.id;
|
|
5433
|
+
conv.lastActiveAt = Date.now();
|
|
5434
|
+
conv.terminals.rebindEmit((msg) => this.emitTerminal(conv.id, msg));
|
|
5435
|
+
conv.terminals.onAgentIdle = (terminalId, idleMs, title, lastLines) => this.notifyTerminalIdle(conv.id, terminalId, idleMs, title, lastLines);
|
|
5436
|
+
conv.unsubscribe?.();
|
|
5437
|
+
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
5438
|
+
for (const [toolCallId, start] of conv.toolStartTimes) {
|
|
5439
|
+
if (!conv.toolWatchdogs.has(toolCallId)) {
|
|
5440
|
+
this.rearmToolWatchdog(conv, toolCallId, TOOL_WATCHDOG_TIMEOUT_MS - (Date.now() - start));
|
|
5441
|
+
}
|
|
5442
|
+
}
|
|
5443
|
+
this.convs.set(conv.id, conv);
|
|
5444
|
+
}
|
|
5445
|
+
if (!mainId)
|
|
5446
|
+
mainId = payload.convs[0]?.id ?? "";
|
|
5447
|
+
for (const q of payload.questions) {
|
|
5448
|
+
const nid = `q-${++this.questionSeq}`;
|
|
5449
|
+
this.pendingQuestions.set(nid, {
|
|
5450
|
+
resolve: q.resolve,
|
|
5451
|
+
questions: q.questions,
|
|
5452
|
+
conversationId: fix(q.conversationId),
|
|
5453
|
+
});
|
|
5454
|
+
this.emit({ type: "question_pending", id: nid, questions: q.questions });
|
|
5455
|
+
}
|
|
5456
|
+
for (const p of payload.pageCalls) {
|
|
5457
|
+
const nid = `p-${++this.pageSeq}`;
|
|
5458
|
+
const timer = this.armPageCallTimeout(nid, p.resolve, p.timeoutMs);
|
|
5459
|
+
this.pendingPageCalls.set(nid, {
|
|
5460
|
+
resolve: p.resolve,
|
|
5461
|
+
timer,
|
|
5462
|
+
conversationId: fix(p.conversationId),
|
|
5463
|
+
req: p.req,
|
|
5464
|
+
timeoutMs: p.timeoutMs,
|
|
5465
|
+
});
|
|
5466
|
+
this.emit({
|
|
5467
|
+
type: "page_request",
|
|
5468
|
+
id: nid,
|
|
5469
|
+
op: p.req.op,
|
|
5470
|
+
args: p.req.args,
|
|
5471
|
+
target: p.req.target,
|
|
5472
|
+
timeoutMs: p.timeoutMs,
|
|
5473
|
+
});
|
|
5474
|
+
}
|
|
5475
|
+
return mainId;
|
|
5476
|
+
}
|
|
4866
5477
|
/** Switch the ACTIVE conversation without interrupting any other chat. */
|
|
4867
5478
|
async switchConversation(id) {
|
|
4868
5479
|
if (!this.convs.has(id) || id === this.activeId)
|
|
@@ -4998,14 +5609,17 @@ export class ClientSession {
|
|
|
4998
5609
|
})(),
|
|
4999
5610
|
// 子代理带 error 标记:左栏红点提示(普通对话不参与)。
|
|
5000
5611
|
...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
|
|
5612
|
+
// 等答复的问卷:左栏「?」角标(主对话/子代理各自挂名下,切过去即可回答)。
|
|
5613
|
+
...(this.isWaitingOnUser(conv.id) ? { hasQuestion: true } : {}),
|
|
5001
5614
|
parentId: conv.parentId,
|
|
5002
5615
|
});
|
|
5003
5616
|
}
|
|
5004
|
-
// issue #145:流式集合签名变化 →
|
|
5617
|
+
// issue #145:流式集合签名变化 → 通知其他客户端重推(左栏「另一处正在运行」近实时)。
|
|
5618
|
+
// 签名含等问卷态(问卷挂起/解决不改变流式集合,不带它已打开的别处页面永远看不到 `?`)。
|
|
5005
5619
|
try {
|
|
5006
5620
|
const sig = JSON.stringify([...this.convs.values()]
|
|
5007
5621
|
.filter((c) => this.conversationStreaming(c))
|
|
5008
|
-
.map((c) => c.id)
|
|
5622
|
+
.map((c) => `${c.id}:${this.isWaitingOnUser(c.id) ? 1 : 0}`)
|
|
5009
5623
|
.sort());
|
|
5010
5624
|
if (sig !== this.lastRunningSig) {
|
|
5011
5625
|
this.lastRunningSig = sig;
|
|
@@ -5025,8 +5639,8 @@ export class ClientSession {
|
|
|
5025
5639
|
});
|
|
5026
5640
|
}
|
|
5027
5641
|
/** List persisted sessions for this client, newest first. */
|
|
5028
|
-
/** issue #145:上次 emit 时本实例流式对话 id
|
|
5029
|
-
* onRunningChanged 让其他客户端重推 conversations(elsewhere 近实时);
|
|
5642
|
+
/** issue #145:上次 emit 时本实例流式对话 id 集合签名(含等问卷态,见 emitConversations)。
|
|
5643
|
+
* 变化时经 onRunningChanged 让其他客户端重推 conversations(elsewhere 近实时);
|
|
5030
5644
|
* 签名相等即停,天然防 ping-pong 循环。 */
|
|
5031
5645
|
lastRunningSig = "";
|
|
5032
5646
|
/** The client asked for the session list at least once (lazy loading) —
|
|
@@ -5764,6 +6378,9 @@ export class ClientSession {
|
|
|
5764
6378
|
});
|
|
5765
6379
|
}
|
|
5766
6380
|
}
|
|
6381
|
+
// #235:先修后开——坏转录到 open 后的 getBranch 会死循环,修完再读。
|
|
6382
|
+
// 单文件预扫描,健康文件只多一次小读;修过即弹提示(含压缩被打断)。
|
|
6383
|
+
this.repairTranscriptFileBeforeOpen(targetPath);
|
|
5767
6384
|
const sessionManager = SessionManager.open(targetPath);
|
|
5768
6385
|
const targetCwd = sessionManager.getCwd();
|
|
5769
6386
|
const conversationId = this.nextConversationId();
|
|
@@ -6068,6 +6685,79 @@ export class ClientSession {
|
|
|
6068
6685
|
async scmQuery(kind, reqId, arg) {
|
|
6069
6686
|
return this.files.scmQuery(kind, reqId, arg);
|
|
6070
6687
|
}
|
|
6688
|
+
/**
|
|
6689
|
+
* SCM「AI 生成提交信息」:用当前对话模型做一次 completeSimple 一次性补全
|
|
6690
|
+
* (与视觉桥同一条通路)——不进对话上下文、不打断正在流式的回复。
|
|
6691
|
+
* 恰好应答一次:任何失败都以 ok:false 的 scm_data(kind "commitmsg")收尾,
|
|
6692
|
+
* 前端按钮不会卡在转圈。
|
|
6693
|
+
*/
|
|
6694
|
+
async scmGenCommitMessage(reqId) {
|
|
6695
|
+
const lang = this.getLang();
|
|
6696
|
+
const cwd = this.conv?.cwd ?? this.cwd;
|
|
6697
|
+
const reply = (ok, extra) => {
|
|
6698
|
+
this.emit({ type: "scm_data", reqId, kind: "commitmsg", ok, ...extra });
|
|
6699
|
+
};
|
|
6700
|
+
const fail = (err) => {
|
|
6701
|
+
reply(false, { error: err instanceof Error ? err.message : String(err) });
|
|
6702
|
+
};
|
|
6703
|
+
try {
|
|
6704
|
+
const runtime = this.runtime.services.modelRuntime;
|
|
6705
|
+
const model = this.session?.model;
|
|
6706
|
+
if (!model) {
|
|
6707
|
+
throw new Error(pick(lang, "当前没有可用模型——先在顶栏选择一个模型再生成", "No model available — pick one in the top bar first", "scm.commitmsg.no.model"));
|
|
6708
|
+
}
|
|
6709
|
+
const ctx = await scmCommitContext(cwd, () => lang);
|
|
6710
|
+
const input = buildCommitMsgInput(ctx, lang === "zh" ? "zh" : "en");
|
|
6711
|
+
if (!input) {
|
|
6712
|
+
throw new Error(pick(lang, "没有可描述的更改(工作区干净)", "Nothing to describe (working tree clean)", "scm.commitmsg.no.changes"));
|
|
6713
|
+
}
|
|
6714
|
+
const ac = new AbortController();
|
|
6715
|
+
const timer = setTimeout(() => ac.abort(), SCM_COMMITMSG_TIMEOUT_MS);
|
|
6716
|
+
// 提示词可配置(设置 → 提示词 → AI 提交信息):追加/替换内置默认。
|
|
6717
|
+
const commitSettings = this.settingsSvc.current;
|
|
6718
|
+
const systemPrompt = buildCommitMsgPrompt(commitSettings.scmCommitMsgPromptMode === "replace" ? "replace" : "append", commitSettings.scmCommitMsgPrompt ?? "");
|
|
6719
|
+
let msg;
|
|
6720
|
+
try {
|
|
6721
|
+
msg = await runtime.completeSimple(model, {
|
|
6722
|
+
systemPrompt,
|
|
6723
|
+
messages: [
|
|
6724
|
+
{
|
|
6725
|
+
role: "user",
|
|
6726
|
+
timestamp: Date.now(),
|
|
6727
|
+
content: [{ type: "text", text: input }],
|
|
6728
|
+
},
|
|
6729
|
+
],
|
|
6730
|
+
}, { signal: ac.signal, maxTokens: 400 });
|
|
6731
|
+
}
|
|
6732
|
+
finally {
|
|
6733
|
+
clearTimeout(timer);
|
|
6734
|
+
}
|
|
6735
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") {
|
|
6736
|
+
throw new Error(msg.errorMessage ||
|
|
6737
|
+
pick(lang, `模型异常终止(${msg.stopReason})`, `Model terminated abnormally (${msg.stopReason})`, "scm.commitmsg.model.terminated"));
|
|
6738
|
+
}
|
|
6739
|
+
const raw = msg.content
|
|
6740
|
+
.filter((b) => b.type === "text")
|
|
6741
|
+
.map((b) => b.text ?? "")
|
|
6742
|
+
.join("\n");
|
|
6743
|
+
const text = sanitizeCommitMessage(raw);
|
|
6744
|
+
if (!text) {
|
|
6745
|
+
throw new Error(pick(lang, "模型返回了空的提交信息", "The model returned an empty commit message", "scm.commitmsg.empty"));
|
|
6746
|
+
}
|
|
6747
|
+
reply(true, { text });
|
|
6748
|
+
}
|
|
6749
|
+
catch (err) {
|
|
6750
|
+
if (isNotRepoError(err)) {
|
|
6751
|
+
fail(new Error(pick(lang, "当前目录不是 Git 仓库", "Current directory is not a Git repository", "scm.commitmsg.not.repo")));
|
|
6752
|
+
return;
|
|
6753
|
+
}
|
|
6754
|
+
if (err instanceof Error && /abort/i.test(`${err.name} ${err.message}`)) {
|
|
6755
|
+
fail(new Error(pick(lang, `生成提交信息超时(${Math.round(SCM_COMMITMSG_TIMEOUT_MS / 1000)} 秒)`, `Commit-message generation timed out (${Math.round(SCM_COMMITMSG_TIMEOUT_MS / 1000)}s)`, "scm.commitmsg.timeout")));
|
|
6756
|
+
return;
|
|
6757
|
+
}
|
|
6758
|
+
fail(err);
|
|
6759
|
+
}
|
|
6760
|
+
}
|
|
6071
6761
|
/** Read a workspace file for the preview panel (size-capped, binary-safe). */
|
|
6072
6762
|
async readFile(relPath) {
|
|
6073
6763
|
return this.files.readFile(relPath);
|
|
@@ -6236,7 +6926,6 @@ export class ClientSession {
|
|
|
6236
6926
|
// default-opening it would strand the tab on a conversation it
|
|
6237
6927
|
// cannot use (the prompt guard refuses) with a stale leaf that
|
|
6238
6928
|
// forks history once the owner finishes. Land blank instead.
|
|
6239
|
-
let sessionManager = SessionManager.continueRecent(abs);
|
|
6240
6929
|
let resumeSkipped = null;
|
|
6241
6930
|
// 无人在跑时不扫目录(首访切项目的常见情形零开销)。
|
|
6242
6931
|
if (this.hasStreamingElsewhere?.() ?? false) {
|
|
@@ -6245,7 +6934,6 @@ export class ClientSession {
|
|
|
6245
6934
|
const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
|
|
6246
6935
|
const owner = recent ? this.findSessionOwner?.(recent) : null;
|
|
6247
6936
|
if (owner?.isStreaming) {
|
|
6248
|
-
sessionManager = SessionManager.create(abs);
|
|
6249
6937
|
resumeSkipped = owner;
|
|
6250
6938
|
}
|
|
6251
6939
|
}
|
|
@@ -6255,11 +6943,18 @@ export class ClientSession {
|
|
|
6255
6943
|
}
|
|
6256
6944
|
const conversationId = this.nextConversationId();
|
|
6257
6945
|
const terminals = this.makeTerminalManager(conversationId, abs);
|
|
6258
|
-
|
|
6946
|
+
// #235:manager+runtime 一起建,转录链损坏时修最近文件后重试一次
|
|
6947
|
+
// (见 openManagerAndRuntime)。blank(别处在跑)是全新空会话,不会坏。
|
|
6948
|
+
const opened = await this.openManagerAndRuntime(() => (resumeSkipped ? SessionManager.create(abs) : SessionManager.continueRecent(abs)), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId), {
|
|
6259
6949
|
cwd: abs,
|
|
6260
6950
|
agentDir: this.agentDir,
|
|
6261
|
-
sessionManager,
|
|
6262
|
-
});
|
|
6951
|
+
sessionManager: m,
|
|
6952
|
+
}), async () => (await SessionManager.list(abs))[0]?.path);
|
|
6953
|
+
const newRuntime = opened.runtime;
|
|
6954
|
+
if (opened.repair) {
|
|
6955
|
+
for (const n of this.transcriptRepairNotices(opened.repair))
|
|
6956
|
+
this.emit(n);
|
|
6957
|
+
}
|
|
6263
6958
|
const conv = this.makeConversation(newRuntime, conversationId, terminals);
|
|
6264
6959
|
this.convs.set(conv.id, conv);
|
|
6265
6960
|
this.activeId = conv.id;
|
|
@@ -6409,7 +7104,9 @@ export class ClientSession {
|
|
|
6409
7104
|
return "";
|
|
6410
7105
|
}
|
|
6411
7106
|
}
|
|
6412
|
-
/** Switch to a specific model by "provider/id" (e.g. "anthropic/claude-sonnet-5").
|
|
7107
|
+
/** Switch to a specific model by "provider/id" (e.g. "anthropic/claude-sonnet-5").
|
|
7108
|
+
* 失败时只发 notice 不抛错(UI 路径靠 notice 提示,见 cycleModel 等调用方)。
|
|
7109
|
+
* 需要「失败即拒绝」的无头路径(插件/定时任务)用 switchModelOrThrow。 */
|
|
6413
7110
|
async setModel(modelId) {
|
|
6414
7111
|
try {
|
|
6415
7112
|
const mr = this.runtime.services.modelRuntime;
|
|
@@ -6428,6 +7125,8 @@ export class ClientSession {
|
|
|
6428
7125
|
// project (not only after a turn). This is what makes project switching
|
|
6429
7126
|
// restore both the model and the provider key.
|
|
6430
7127
|
this.rememberProjectModel(modelId);
|
|
7128
|
+
// 换模型后按新模型的窗口重算软上限覆盖(按模型覆盖可能不同,issue #229)。
|
|
7129
|
+
this.applyCompactionOverrides();
|
|
6431
7130
|
}
|
|
6432
7131
|
catch (err) {
|
|
6433
7132
|
this.emit({
|
|
@@ -6439,6 +7138,25 @@ export class ClientSession {
|
|
|
6439
7138
|
}
|
|
6440
7139
|
this.flushSnapshot();
|
|
6441
7140
|
}
|
|
7141
|
+
/** 切换模型,失败时抛出(无头路径专用:插件 host.chat / 定时任务)。
|
|
7142
|
+
* setModel 为兼容 UI 把异常吞成 notice(面板要能看到原因、调用方是 fire-and-forget),
|
|
7143
|
+
* 无头路径拿不到那个 notice,于是「模型 ID 打错/没配密钥」会变成静默按旧模型跑 ——
|
|
7144
|
+
* 账单与效果都和用户预期不符。这里统一改成响亮失败。 */
|
|
7145
|
+
async switchModelOrThrow(modelId) {
|
|
7146
|
+
await this.setModel(modelId);
|
|
7147
|
+
// 复核结果:读不到(无活跃对话)不阻断,读得到且不符才拒绝。
|
|
7148
|
+
// 注意 session 是 getter,无活跃对话时会抛,不能用 `?.` 兜底。
|
|
7149
|
+
let curId = "";
|
|
7150
|
+
try {
|
|
7151
|
+
const cur = this.session?.model;
|
|
7152
|
+
curId = cur ? `${cur.provider}/${cur.id}` : "";
|
|
7153
|
+
}
|
|
7154
|
+
catch {
|
|
7155
|
+
curId = "";
|
|
7156
|
+
}
|
|
7157
|
+
if (curId && curId !== modelId)
|
|
7158
|
+
throw new Error(`切换模型失败(${modelId}),当前仍是 ${curId} —— 请检查模型 ID 与供应商密钥`);
|
|
7159
|
+
}
|
|
6442
7160
|
/** Set the thinking level for future turns. */
|
|
6443
7161
|
setThinking(level) {
|
|
6444
7162
|
try {
|
|
@@ -6489,8 +7207,10 @@ export class ClientSession {
|
|
|
6489
7207
|
async dispose() {
|
|
6490
7208
|
this.disposed = true;
|
|
6491
7209
|
this.modelAdmin.dispose();
|
|
7210
|
+
// 关机路径:Windows 下跳过 pty.kill()(issue #215 ConPTY 死锁),只做
|
|
7211
|
+
// TerminateProcess + 状态清理,句柄由 OS 在进程退出时回收。
|
|
6492
7212
|
for (const conv of this.convs.values())
|
|
6493
|
-
conv.terminals.killAll();
|
|
7213
|
+
conv.terminals.killAll({ shutdown: true });
|
|
6494
7214
|
if (this.snapshotTimer) {
|
|
6495
7215
|
clearTimeout(this.snapshotTimer);
|
|
6496
7216
|
this.snapshotTimer = null;
|
|
@@ -6527,6 +7247,42 @@ export class ClientSession {
|
|
|
6527
7247
|
}
|
|
6528
7248
|
}
|
|
6529
7249
|
}
|
|
7250
|
+
/** issue #226:插件无头调用的工作目录校验(纯函数,可单测)。
|
|
7251
|
+
* 存在性语义与定时任务一致(须存在且为目录,不默默跑错目录);另在
|
|
7252
|
+
* Windows 下拒绝 SystemRoot 及其子树(如 C:\Windows\System32)——后台服务/
|
|
7253
|
+
* 快捷方式启动时宿主 cwd 常飘到 system32,直接跑就是高危误操作。 */
|
|
7254
|
+
export function checkPluginCwd(cwd) {
|
|
7255
|
+
const trimmed = String(cwd ?? "").trim();
|
|
7256
|
+
if (!trimmed)
|
|
7257
|
+
return { ok: false, error: "工作目录为空" };
|
|
7258
|
+
let abs;
|
|
7259
|
+
try {
|
|
7260
|
+
abs =
|
|
7261
|
+
process.platform === "win32" && /^[A-Za-z]:$/.test(trimmed) ? `${trimmed.toUpperCase()}${sep}` : resolve(trimmed);
|
|
7262
|
+
}
|
|
7263
|
+
catch {
|
|
7264
|
+
return { ok: false, error: `工作目录非法:${trimmed}` };
|
|
7265
|
+
}
|
|
7266
|
+
try {
|
|
7267
|
+
if (!statSync(abs).isDirectory())
|
|
7268
|
+
throw new Error("not-a-dir");
|
|
7269
|
+
}
|
|
7270
|
+
catch {
|
|
7271
|
+
return { ok: false, error: `目标项目不存在或不是目录:${trimmed}` };
|
|
7272
|
+
}
|
|
7273
|
+
if (process.platform === "win32") {
|
|
7274
|
+
const sysRoot = (process.env.SystemRoot || process.env.windir || "C:\\Windows")
|
|
7275
|
+
.replace(/\//g, "\\")
|
|
7276
|
+
.replace(/\\+$/, "");
|
|
7277
|
+
const norm = abs.replace(/\//g, "\\").replace(/\\+$/, "");
|
|
7278
|
+
const low = norm.toLowerCase();
|
|
7279
|
+
const rootLow = sysRoot.toLowerCase();
|
|
7280
|
+
if (low === rootLow || low.startsWith(`${rootLow}\\`)) {
|
|
7281
|
+
return { ok: false, error: `拒绝在系统目录执行:${abs}(请在插件设置里指定项目工作目录)` };
|
|
7282
|
+
}
|
|
7283
|
+
}
|
|
7284
|
+
return { ok: true, abs };
|
|
7285
|
+
}
|
|
6530
7286
|
export class AgentService {
|
|
6531
7287
|
cwd;
|
|
6532
7288
|
/** index.ts 注入:SDK 工具执行事件的插件转发钩子,attach 时拷贝到每个新会话。 */
|
|
@@ -6640,30 +7396,165 @@ export class AgentService {
|
|
|
6640
7396
|
}
|
|
6641
7397
|
/** issue #193:定时任务唤醒发起对话。逐个客户端找持有方,用 steer 语义投递
|
|
6642
7398
|
* (运行时插队、未跑时普通投递,不切用户当前对话);都找不到回 ok:false,
|
|
6643
|
-
* 调用方(index.ts executor
|
|
6644
|
-
|
|
6645
|
-
|
|
7399
|
+
* 调用方(index.ts executor)回落视口/无头执行。quiesced 时直接拒绝。
|
|
7400
|
+
* issue #226:成功时带回持有方 clientId(插件绑定网页会话时原样回执)。
|
|
7401
|
+
* issue #231:opts.sessionFile 是跨压缩/重启的稳定键 —— 优先按它认同一会话
|
|
7402
|
+
* (内存对话 id 重启即失效,压缩后同文件对话可能已换新 id,成功时带回**实际**
|
|
7403
|
+
* 投递的 conversationId + sessionFile,调用方据此重绑定任务);id 相位带 cwd
|
|
7404
|
+
* 护栏(各客户端计数器都从 c1 开始,不校验会把报告投进无关项目)。压缩进行中
|
|
7405
|
+
* 的持有方回 busy:true(调用方另寻视口兄弟,而不是当成“不在”静默转无头)。 */
|
|
7406
|
+
async wakeConversation(id, text, opts) {
|
|
7407
|
+
const wantFile = String(opts?.sessionFile ?? "").trim();
|
|
7408
|
+
const wantCwd = String(opts?.cwd ?? "").trim();
|
|
7409
|
+
if ((!id && !wantFile) || !text.trim())
|
|
6646
7410
|
return { ok: false, error: "唤醒目标或文本为空" };
|
|
6647
7411
|
if (this.quiesced)
|
|
6648
7412
|
return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
|
|
6649
|
-
|
|
7413
|
+
const liveFile = (c) => {
|
|
6650
7414
|
try {
|
|
6651
|
-
|
|
6652
|
-
|
|
7415
|
+
return String(c.session.sessionFile ?? "");
|
|
7416
|
+
}
|
|
7417
|
+
catch {
|
|
7418
|
+
return "";
|
|
7419
|
+
}
|
|
7420
|
+
};
|
|
7421
|
+
const flush = (cs) => {
|
|
7422
|
+
try {
|
|
7423
|
+
cs.flushSnapshot();
|
|
7424
|
+
}
|
|
7425
|
+
catch {
|
|
7426
|
+
// 推送失败不影响已投递的唤醒
|
|
7427
|
+
}
|
|
7428
|
+
};
|
|
7429
|
+
// 相位一:落盘会话文件(稳定键)。同文件可能在多处打开,取最近活跃者;
|
|
7430
|
+
// 全部忙(压缩中)则报 busy,调用方去找视口兄弟。
|
|
7431
|
+
if (wantFile) {
|
|
7432
|
+
const hits = [];
|
|
7433
|
+
for (const [clientId, cs] of this.clients) {
|
|
7434
|
+
try {
|
|
7435
|
+
const conv = cs.resolveSchedulerTarget({ sessionFile: wantFile });
|
|
7436
|
+
if (conv)
|
|
7437
|
+
hits.push({ cs, clientId, conv });
|
|
7438
|
+
}
|
|
7439
|
+
catch {
|
|
7440
|
+
// 单客户端坏了继续找下一个
|
|
7441
|
+
}
|
|
7442
|
+
}
|
|
7443
|
+
hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
7444
|
+
let busyError;
|
|
7445
|
+
for (const h of hits) {
|
|
7446
|
+
try {
|
|
7447
|
+
const r = await h.cs.trySteerScheduler(h.conv, text);
|
|
7448
|
+
if (r.ok) {
|
|
7449
|
+
flush(h.cs);
|
|
7450
|
+
return { ok: true, conversationId: h.conv.id, sessionFile: liveFile(h.conv), clientId: h.clientId };
|
|
7451
|
+
}
|
|
7452
|
+
if (r.busy)
|
|
7453
|
+
busyError = r.error;
|
|
7454
|
+
// 非忙失败(投递异常)试下一个同文件持有方
|
|
7455
|
+
}
|
|
7456
|
+
catch {
|
|
7457
|
+
// 单客户端坏了继续找下一个
|
|
7458
|
+
}
|
|
7459
|
+
}
|
|
7460
|
+
if (hits.length > 0) {
|
|
7461
|
+
if (busyError)
|
|
7462
|
+
return { ok: false, busy: true, error: busyError };
|
|
7463
|
+
// 同文件持有方都在但都投递失败 —— id 相位大概率指向同一批,无需再试
|
|
7464
|
+
return { ok: false, error: "目标对话投递失败(持有方异常)" };
|
|
7465
|
+
}
|
|
7466
|
+
// 无同文件持有方 —— 老任务只有 id,继续相位二
|
|
7467
|
+
}
|
|
7468
|
+
// 相位二:内存对话 id(易失键,必须配 cwd 护栏防跨项目串台)。
|
|
7469
|
+
if (id) {
|
|
7470
|
+
const hits = [];
|
|
7471
|
+
for (const [clientId, cs] of this.clients) {
|
|
7472
|
+
try {
|
|
7473
|
+
const conv = cs.resolveSchedulerTarget({
|
|
7474
|
+
conversationId: id,
|
|
7475
|
+
...(wantCwd ? { cwd: wantCwd } : {}),
|
|
7476
|
+
});
|
|
7477
|
+
if (conv)
|
|
7478
|
+
hits.push({ cs, clientId, conv });
|
|
7479
|
+
}
|
|
7480
|
+
catch {
|
|
7481
|
+
// 单客户端坏了继续找下一个
|
|
7482
|
+
}
|
|
7483
|
+
}
|
|
7484
|
+
hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
7485
|
+
let busyError;
|
|
7486
|
+
for (const h of hits) {
|
|
7487
|
+
try {
|
|
7488
|
+
const r = await h.cs.trySteerScheduler(h.conv, text);
|
|
7489
|
+
if (r.ok) {
|
|
7490
|
+
flush(h.cs);
|
|
7491
|
+
return { ok: true, conversationId: h.conv.id, sessionFile: liveFile(h.conv), clientId: h.clientId };
|
|
7492
|
+
}
|
|
7493
|
+
if (r.busy)
|
|
7494
|
+
busyError = r.error;
|
|
7495
|
+
}
|
|
7496
|
+
catch {
|
|
7497
|
+
// 单客户端坏了继续找下一个
|
|
7498
|
+
}
|
|
7499
|
+
}
|
|
7500
|
+
if (busyError)
|
|
7501
|
+
return { ok: false, busy: true, error: busyError };
|
|
7502
|
+
}
|
|
7503
|
+
return { ok: false, error: "目标对话不在运行中(已关闭或服务重启过)" };
|
|
7504
|
+
}
|
|
7505
|
+
/** issue #231:同项目视口回退 —— 原绑定对话不在时,把唤醒投给该项目最近活跃
|
|
7506
|
+
* 的对话(用户当前正看着的面),而不是静默转无头。excludeIds 跳过已知忙对话;
|
|
7507
|
+
* 候选全部忙回 busy:true;无候选回 ok:false。成功带回实际投递方(调用方重绑定)。 */
|
|
7508
|
+
async wakeViewportInCwd(cwd, text, excludeIds) {
|
|
7509
|
+
const want = String(cwd ?? "").trim();
|
|
7510
|
+
if (!want || !text.trim())
|
|
7511
|
+
return { ok: false, error: "回退目标或文本为空" };
|
|
7512
|
+
if (this.quiesced)
|
|
7513
|
+
return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
|
|
7514
|
+
const cands = [];
|
|
7515
|
+
for (const [clientId, cs] of this.clients) {
|
|
7516
|
+
try {
|
|
7517
|
+
const conv = cs.findViewportInCwd(want, excludeIds);
|
|
7518
|
+
if (conv)
|
|
7519
|
+
cands.push({ cs, clientId, conv });
|
|
7520
|
+
}
|
|
7521
|
+
catch {
|
|
7522
|
+
// 单客户端坏了继续找下一个
|
|
7523
|
+
}
|
|
7524
|
+
}
|
|
7525
|
+
cands.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
7526
|
+
if (cands.length === 0)
|
|
7527
|
+
return { ok: false, error: "同项目无存活对话" };
|
|
7528
|
+
let busyError;
|
|
7529
|
+
for (const c of cands) {
|
|
7530
|
+
try {
|
|
7531
|
+
const r = await c.cs.trySteerScheduler(c.conv, text);
|
|
7532
|
+
if (r.ok) {
|
|
6653
7533
|
try {
|
|
6654
|
-
cs.flushSnapshot();
|
|
7534
|
+
c.cs.flushSnapshot();
|
|
6655
7535
|
}
|
|
6656
7536
|
catch {
|
|
6657
7537
|
// 推送失败不影响已投递的唤醒
|
|
6658
7538
|
}
|
|
6659
|
-
|
|
7539
|
+
let f = "";
|
|
7540
|
+
try {
|
|
7541
|
+
f = String(c.conv.session.sessionFile ?? "");
|
|
7542
|
+
}
|
|
7543
|
+
catch {
|
|
7544
|
+
f = "";
|
|
7545
|
+
}
|
|
7546
|
+
return { ok: true, conversationId: c.conv.id, sessionFile: f, clientId: c.clientId };
|
|
6660
7547
|
}
|
|
7548
|
+
if (r.busy)
|
|
7549
|
+
busyError = r.error;
|
|
6661
7550
|
}
|
|
6662
7551
|
catch {
|
|
6663
7552
|
// 单客户端坏了继续找下一个
|
|
6664
7553
|
}
|
|
6665
7554
|
}
|
|
6666
|
-
|
|
7555
|
+
if (busyError)
|
|
7556
|
+
return { ok: false, busy: true, error: busyError };
|
|
7557
|
+
return { ok: false, error: "同项目对话投递失败" };
|
|
6667
7558
|
}
|
|
6668
7559
|
/** issue #145:别处在某 cwd 下正在跑的对话(同项目并行感知用,不含请求方)。 */
|
|
6669
7560
|
listProjectRunners(cwd, excludeClientId) {
|
|
@@ -6676,14 +7567,15 @@ export class AgentService {
|
|
|
6676
7567
|
}
|
|
6677
7568
|
return out;
|
|
6678
7569
|
}
|
|
6679
|
-
/** issue #145:别处所有正在跑的对话(左栏 elsewhere
|
|
7570
|
+
/** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
|
|
7571
|
+
* owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
|
|
6680
7572
|
listExternalRunning(excludeClientId) {
|
|
6681
7573
|
const out = [];
|
|
6682
7574
|
for (const [clientId, cs] of this.clients) {
|
|
6683
7575
|
if (clientId === excludeClientId)
|
|
6684
7576
|
continue;
|
|
6685
7577
|
for (const r of cs.streamingSummariesAll())
|
|
6686
|
-
out.push(r);
|
|
7578
|
+
out.push({ ...r, owner: clientId });
|
|
6687
7579
|
}
|
|
6688
7580
|
return out;
|
|
6689
7581
|
}
|
|
@@ -6749,7 +7641,11 @@ export class AgentService {
|
|
|
6749
7641
|
* 快照/notice 发了即丢,不攒内存。fire-and-forget:prompt 投递即返回,
|
|
6750
7642
|
* 运行结果经 onRunEvent(run_end) 按 conversationId 关联。
|
|
6751
7643
|
* v1 语义:与该服务 cwd 下最近会话共享(单用户视角连续);peer 名由插件
|
|
6752
|
-
* 拼进文本前缀,per-peer 会话隔离以后再加。
|
|
7644
|
+
* 拼进文本前缀,per-peer 会话隔离以后再加。
|
|
7645
|
+
* issue #226:对齐定时任务的四件套——conversationId 命中时走 steer 语义
|
|
7646
|
+
* 投递(网页端实时可见,miss 则回落无头);cwd 显式 pin 住(不存在/系统
|
|
7647
|
+
* 目录即拒绝,不默默跑错目录);model/thinkingLevel 投递前应用(失败即
|
|
7648
|
+
* 拒绝,不回落,避免账单/效果与预期不符)。 */
|
|
6753
7649
|
async chatFromPlugin(pluginId, req) {
|
|
6754
7650
|
const safe = String(pluginId ?? "plugin").replace(/[^A-Za-z0-9_-]/g, "") || "plugin";
|
|
6755
7651
|
const acct = String(req?.accountId ?? "default").replace(/[^A-Za-z0-9_-]/g, "") || "default";
|
|
@@ -6759,10 +7655,52 @@ export class AgentService {
|
|
|
6759
7655
|
throw new Error("chatFromPlugin: text 为空");
|
|
6760
7656
|
if (this.quiesced)
|
|
6761
7657
|
throw new QuiesceRejectedError("插件无头调用被拒绝,请等服务器恢复后重试");
|
|
7658
|
+
// 1. 绑定已有会话:steer 语义投递,网页端实时可见(微信当远程遥控器用)。
|
|
7659
|
+
// miss/已回收时不抛错,回落无头伪客户端(浏览器关着时微信照常可用)。
|
|
7660
|
+
const target = String(req?.conversationId ?? "").trim();
|
|
7661
|
+
if (target) {
|
|
7662
|
+
const w = await this.wakeConversation(target, text);
|
|
7663
|
+
if (w.ok)
|
|
7664
|
+
return { conversationId: target, clientId: w.clientId ?? clientId };
|
|
7665
|
+
}
|
|
7666
|
+
// 2. 工作空间:不传回落伪客户端当前目录;传了必须存在且非系统目录。
|
|
7667
|
+
const cwdReq = String(req?.cwd ?? "").trim();
|
|
7668
|
+
let cwdAbs = "";
|
|
7669
|
+
if (cwdReq) {
|
|
7670
|
+
const chk = checkPluginCwd(cwdReq);
|
|
7671
|
+
if (!chk.ok)
|
|
7672
|
+
throw new Error(`chatFromPlugin: ${chk.error}`);
|
|
7673
|
+
cwdAbs = chk.abs ?? "";
|
|
7674
|
+
}
|
|
6762
7675
|
const cs = await this.attach(clientId, () => { });
|
|
6763
|
-
|
|
7676
|
+
try {
|
|
7677
|
+
if (cwdAbs && cs.cwd !== cwdAbs)
|
|
7678
|
+
await cs.setCwd(cwdAbs);
|
|
7679
|
+
}
|
|
7680
|
+
catch (err) {
|
|
7681
|
+
throw new Error(`chatFromPlugin: 切换工作目录失败(${cwdAbs}):${err.message}`);
|
|
7682
|
+
}
|
|
7683
|
+
const model = String(req?.model ?? "").trim();
|
|
7684
|
+
if (model) {
|
|
7685
|
+
try {
|
|
7686
|
+
await cs.switchModelOrThrow(model);
|
|
7687
|
+
}
|
|
7688
|
+
catch (err) {
|
|
7689
|
+
throw new Error(`chatFromPlugin: 切换模型失败(${model}):${err.message}`);
|
|
7690
|
+
}
|
|
7691
|
+
}
|
|
7692
|
+
const thinking = String(req?.thinkingLevel ?? "").trim();
|
|
7693
|
+
if (thinking) {
|
|
7694
|
+
try {
|
|
7695
|
+
cs.setThinking(thinking);
|
|
7696
|
+
}
|
|
7697
|
+
catch (err) {
|
|
7698
|
+
throw new Error(`chatFromPlugin: 切换思考强度失败(${thinking}):${err.message}`);
|
|
7699
|
+
}
|
|
7700
|
+
}
|
|
7701
|
+
const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
|
|
6764
7702
|
void cs.prompt(text);
|
|
6765
|
-
return { conversationId
|
|
7703
|
+
return { conversationId, clientId };
|
|
6766
7704
|
}
|
|
6767
7705
|
/** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
|
|
6768
7706
|
* 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
|
|
@@ -6794,7 +7732,7 @@ export class AgentService {
|
|
|
6794
7732
|
const model = String(task.model ?? "").trim();
|
|
6795
7733
|
if (model) {
|
|
6796
7734
|
try {
|
|
6797
|
-
await cs.
|
|
7735
|
+
await cs.switchModelOrThrow(model);
|
|
6798
7736
|
}
|
|
6799
7737
|
catch (err) {
|
|
6800
7738
|
return { ok: false, error: `切换模型失败(${model}):${err.message}` };
|
|
@@ -6894,6 +7832,216 @@ export class AgentService {
|
|
|
6894
7832
|
service: toServiceInfo(launchOrigin()),
|
|
6895
7833
|
};
|
|
6896
7834
|
}
|
|
7835
|
+
/** 插件/调度伪客户端:sink 常驻(fire-and-forget 的空函数),不能按浏览器存活判断。 */
|
|
7836
|
+
static isPseudoClientId(id) {
|
|
7837
|
+
return id.startsWith("plugin:") || id.startsWith("scheduler:");
|
|
7838
|
+
}
|
|
7839
|
+
/**
|
|
7840
|
+
* 浏览器重启认领:给 fresh clientId 找一个可接管的断开残留会话(返回旧 id)。
|
|
7841
|
+
* 有别的在线浏览器时返回 null(issue #10 隔离优先)。
|
|
7842
|
+
* 全同步:attach 里的认领段不含 await,并发的新标签后到者看到 sinkCount>0,
|
|
7843
|
+
* 不会抢走同一个残留。
|
|
7844
|
+
*/
|
|
7845
|
+
findAdoptableOrphan(excludeClientId) {
|
|
7846
|
+
const cands = [];
|
|
7847
|
+
for (const [id, cs] of this.clients) {
|
|
7848
|
+
if (id === excludeClientId)
|
|
7849
|
+
continue;
|
|
7850
|
+
const pseudo = AgentService.isPseudoClientId(id);
|
|
7851
|
+
let live = false;
|
|
7852
|
+
let streaming = 0;
|
|
7853
|
+
let adoptable = false;
|
|
7854
|
+
let activity = 0;
|
|
7855
|
+
try {
|
|
7856
|
+
live = cs.sinkCount() > 0;
|
|
7857
|
+
}
|
|
7858
|
+
catch {
|
|
7859
|
+
live = false;
|
|
7860
|
+
}
|
|
7861
|
+
if (!pseudo && !live) {
|
|
7862
|
+
try {
|
|
7863
|
+
streaming = cs.activeConversations();
|
|
7864
|
+
}
|
|
7865
|
+
catch {
|
|
7866
|
+
streaming = 0;
|
|
7867
|
+
}
|
|
7868
|
+
try {
|
|
7869
|
+
adoptable = cs.hasAdoptableContent();
|
|
7870
|
+
}
|
|
7871
|
+
catch {
|
|
7872
|
+
adoptable = false;
|
|
7873
|
+
}
|
|
7874
|
+
try {
|
|
7875
|
+
activity = cs.latestActivity();
|
|
7876
|
+
}
|
|
7877
|
+
catch {
|
|
7878
|
+
activity = 0;
|
|
7879
|
+
}
|
|
7880
|
+
}
|
|
7881
|
+
cands.push({ id, live, pseudo, streaming, adoptable, activity });
|
|
7882
|
+
}
|
|
7883
|
+
const picked = pickAdoptableOrphan(cands);
|
|
7884
|
+
if (!picked)
|
|
7885
|
+
return null;
|
|
7886
|
+
const cs = this.clients.get(picked);
|
|
7887
|
+
return cs ? { oldId: picked, cs } : null;
|
|
7888
|
+
}
|
|
7889
|
+
/**
|
|
7890
|
+
* 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表 / 跨端 steer)。
|
|
7891
|
+
* attach 尾部与认领分支共用 —— 认领换了 map 键,必须在首帧推送(attachSink)
|
|
7892
|
+
* 前就按新 id 重接,否则 self-exclusion 失效:把自己当成“另一处”(elsewhere
|
|
7893
|
+
* 误报 + prompt/switch 自拦)。尾部会再调一次,幂等。
|
|
7894
|
+
*/
|
|
7895
|
+
wireClient(cs, clientId) {
|
|
7896
|
+
cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
|
|
7897
|
+
cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
|
|
7898
|
+
cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
|
|
7899
|
+
cs.listExternalRunning = () => this.listExternalRunning(clientId);
|
|
7900
|
+
cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
|
|
7901
|
+
cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
|
|
7902
|
+
cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
|
|
7903
|
+
cs.schedulerStore = this.schedulerStore;
|
|
7904
|
+
}
|
|
7905
|
+
/**
|
|
7906
|
+
* 手动过户(take_over_conversation):把 owner 会话的某主对话(含子代理后代、
|
|
7907
|
+
* 等答复问卷/页调用)整体搬到 target 会话并切过去。搬的是 runtime 本体不是
|
|
7908
|
+
* 副本,单 writer 不变 —— 从在线标签页手里接管也是安全的;源会话修好 active
|
|
7909
|
+
* 并推全量刷新,双方都收到去向通知。quiesce 排空期也放行(重连既有工作)。
|
|
7910
|
+
*/
|
|
7911
|
+
async takeOverConversation(targetId, ownerId, convId) {
|
|
7912
|
+
const target = this.clients.get(targetId);
|
|
7913
|
+
if (!target)
|
|
7914
|
+
return;
|
|
7915
|
+
const fail = (text, textEn) => {
|
|
7916
|
+
target.sendNotice({ type: "notice", level: "warning", text, textEn });
|
|
7917
|
+
};
|
|
7918
|
+
if (!ownerId || !convId) {
|
|
7919
|
+
fail("过户目标不明确(缺 owner/id),请重试", "Takeover target unclear (missing owner/id), please retry.");
|
|
7920
|
+
return;
|
|
7921
|
+
}
|
|
7922
|
+
if (ownerId === targetId) {
|
|
7923
|
+
// 自己的对话 → 退化为普通切换。
|
|
7924
|
+
try {
|
|
7925
|
+
await target.switchConversation(convId);
|
|
7926
|
+
}
|
|
7927
|
+
catch {
|
|
7928
|
+
/* switch 内部已用 notice 报错 */
|
|
7929
|
+
}
|
|
7930
|
+
return;
|
|
7931
|
+
}
|
|
7932
|
+
if (AgentService.isPseudoClientId(ownerId)) {
|
|
7933
|
+
fail("定时任务/插件会话不支持过户", "Scheduler/plugin sessions cannot be taken over.");
|
|
7934
|
+
return;
|
|
7935
|
+
}
|
|
7936
|
+
const source = this.clients.get(ownerId);
|
|
7937
|
+
if (!source) {
|
|
7938
|
+
fail("对方会话已不存在,可从历史对话里直接打开", "The source session is gone; reopen it from History instead.");
|
|
7939
|
+
target.refreshExternalRunning();
|
|
7940
|
+
return;
|
|
7941
|
+
}
|
|
7942
|
+
const briefs = source.takeoverBriefs();
|
|
7943
|
+
const main = briefs.find((b) => b.id === convId);
|
|
7944
|
+
if (!main) {
|
|
7945
|
+
fail("对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", "That conversation is gone on the other side; the list refreshes shortly.");
|
|
7946
|
+
target.refreshExternalRunning();
|
|
7947
|
+
return;
|
|
7948
|
+
}
|
|
7949
|
+
if (main.isSubagent) {
|
|
7950
|
+
fail("只能过户主对话(子代理随主对话一起搬)", "Only main conversations can be taken over (subagents move with their parent).");
|
|
7951
|
+
return;
|
|
7952
|
+
}
|
|
7953
|
+
const moveIds = [convId, ...collectSubagentDescendantIds(briefs, convId)];
|
|
7954
|
+
const moveSet = new Set(moveIds);
|
|
7955
|
+
// 容量:与 switchSession 同口径(目标项目非子代理 8 个)。
|
|
7956
|
+
const movedMains = briefs.filter((b) => moveSet.has(b.id) && !b.isSubagent).length;
|
|
7957
|
+
const openInProject = target.takeoverBriefs().filter((b) => b.cwd === main.cwd && !b.isSubagent).length + movedMains;
|
|
7958
|
+
if (openInProject > MAX_OPEN_CONVERSATIONS) {
|
|
7959
|
+
fail(`目标项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),请先打开某个对话并离开(不继续对话)以移出列表`, `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}). Open one and leave it (without continuing) to remove it from the list.`);
|
|
7960
|
+
return;
|
|
7961
|
+
}
|
|
7962
|
+
try {
|
|
7963
|
+
const detached = await source.detachTakeoverConversations(moveIds);
|
|
7964
|
+
if (!detached.ok) {
|
|
7965
|
+
fail(detached.reason === "empty"
|
|
7966
|
+
? "对方会话只剩这一条对话且服务排空中,稍后再试"
|
|
7967
|
+
: "对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", detached.reason === "empty"
|
|
7968
|
+
? "The source session only has this conversation and the server is draining; try later."
|
|
7969
|
+
: "That conversation is gone on the other side; the list refreshes shortly.");
|
|
7970
|
+
if (detached.reason === "missing")
|
|
7971
|
+
target.refreshExternalRunning();
|
|
7972
|
+
return;
|
|
7973
|
+
}
|
|
7974
|
+
const newMainId = target.insertTakeoverConvs(detached.payload);
|
|
7975
|
+
// 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
|
|
7976
|
+
// 无 sink 时 emit 即丢,无需判断。
|
|
7977
|
+
source.sendNotice({
|
|
7978
|
+
type: "notice",
|
|
7979
|
+
level: "info",
|
|
7980
|
+
text: `「${main.title}」已过户到另一处接管,本页不再持有它。`,
|
|
7981
|
+
textEn: `"${main.title}" was taken over by another page and is no longer held here.`,
|
|
7982
|
+
});
|
|
7983
|
+
target.sendNotice({
|
|
7984
|
+
type: "notice",
|
|
7985
|
+
level: "info",
|
|
7986
|
+
text: `已将「${main.title}」过户到当前页面,可直接继续查看与操作。`,
|
|
7987
|
+
textEn: `"${main.title}" was moved to this page — pick up right where it left off.`,
|
|
7988
|
+
});
|
|
7989
|
+
await target.switchConversation(newMainId);
|
|
7990
|
+
}
|
|
7991
|
+
catch (err) {
|
|
7992
|
+
fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
|
|
7993
|
+
}
|
|
7994
|
+
}
|
|
7995
|
+
/**
|
|
7996
|
+
* 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
|
|
7997
|
+
* 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
|
|
7998
|
+
*/
|
|
7999
|
+
async peekElsewhereQuestion(targetId, ownerId, convId) {
|
|
8000
|
+
const target = this.clients.get(targetId);
|
|
8001
|
+
if (!target)
|
|
8002
|
+
return;
|
|
8003
|
+
const fail = (text, textEn) => {
|
|
8004
|
+
target.sendNotice({ type: "notice", level: "warning", text, textEn });
|
|
8005
|
+
};
|
|
8006
|
+
if (!ownerId || !convId) {
|
|
8007
|
+
fail("问卷目标不明确(缺 owner/id),请重试", "Question target unclear (missing owner/id), please retry.");
|
|
8008
|
+
return;
|
|
8009
|
+
}
|
|
8010
|
+
if (ownerId === targetId)
|
|
8011
|
+
return; // 自己的问卷走本地通道,不需要预告
|
|
8012
|
+
if (AgentService.isPseudoClientId(ownerId)) {
|
|
8013
|
+
fail("定时任务/插件会话的问卷不支持跨页作答", "Scheduler/plugin session questions cannot be answered cross-page.");
|
|
8014
|
+
return;
|
|
8015
|
+
}
|
|
8016
|
+
const source = this.clients.get(ownerId);
|
|
8017
|
+
const q = source?.peekPendingQuestion(convId);
|
|
8018
|
+
if (!q) {
|
|
8019
|
+
fail("那张问卷已不在(对方刚回答/取消或对话已结束)", "That question is gone (just answered/cancelled there, or the run ended).");
|
|
8020
|
+
target.refreshExternalRunning();
|
|
8021
|
+
return;
|
|
8022
|
+
}
|
|
8023
|
+
target.pushElsewhereQuestion(ownerId, convId, q);
|
|
8024
|
+
}
|
|
8025
|
+
/**
|
|
8026
|
+
* 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
|
|
8027
|
+
* 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
|
|
8028
|
+
*/
|
|
8029
|
+
async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled) {
|
|
8030
|
+
const target = this.clients.get(targetId);
|
|
8031
|
+
if (!target)
|
|
8032
|
+
return;
|
|
8033
|
+
const source = this.clients.get(ownerId);
|
|
8034
|
+
const ok = source ? source.resolveQuestion(id, answers, cancelled) : false;
|
|
8035
|
+
if (!ok) {
|
|
8036
|
+
target.sendNotice({
|
|
8037
|
+
type: "notice",
|
|
8038
|
+
level: "warning",
|
|
8039
|
+
text: "那张问卷已不在(对方刚回答/取消或对话已结束),你的回答没有送出",
|
|
8040
|
+
textEn: "That question is gone (just answered/cancelled there, or the run ended) — your answer was not delivered.",
|
|
8041
|
+
});
|
|
8042
|
+
target.refreshExternalRunning();
|
|
8043
|
+
}
|
|
8044
|
+
}
|
|
6897
8045
|
/** Get or create the session for a client, racing attach calls safely. */
|
|
6898
8046
|
async attach(clientId, send) {
|
|
6899
8047
|
let cs = this.clients.get(clientId);
|
|
@@ -6903,67 +8051,83 @@ export class AgentService {
|
|
|
6903
8051
|
cs = await inflight;
|
|
6904
8052
|
}
|
|
6905
8053
|
else {
|
|
6906
|
-
//
|
|
6907
|
-
//
|
|
6908
|
-
//
|
|
6909
|
-
//
|
|
6910
|
-
//
|
|
6911
|
-
|
|
6912
|
-
|
|
8054
|
+
// 浏览器重启认领(clientId 存 sessionStorage,关浏览器即失;服务端残留
|
|
8055
|
+
// ClientSession 的运行中对话否则永远卡在“另一处”只读,连看都看不了):
|
|
8056
|
+
// 无其他在线浏览器时,把最近断开的残留会话整体过户给这个新 id
|
|
8057
|
+
// (只换 map 键,不搬 runtime:对话/终端/订阅/cwd 原样保留,
|
|
8058
|
+
// 流式增量经尾部 attachSink 直接推给新 socket)。
|
|
8059
|
+
// 有其他在线标签时不认领(issue #10 隔离优先);quiesce 排空期也放行
|
|
8060
|
+
// (这是重连既有工作,不是新工作)。本段无 await,并发 attach 原子。
|
|
8061
|
+
const orphan = this.findAdoptableOrphan(clientId);
|
|
8062
|
+
if (orphan) {
|
|
8063
|
+
this.clients.delete(orphan.oldId);
|
|
8064
|
+
this.clients.set(clientId, orphan.cs);
|
|
8065
|
+
cs = orphan.cs;
|
|
8066
|
+
// 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
|
|
8067
|
+
this.wireClient(cs, clientId);
|
|
8068
|
+
cs.noteAdopted();
|
|
8069
|
+
// 服务重启前记在旧 id 名下的中断记录搬到新 id 名下,尾部
|
|
8070
|
+
// resumeInterrupted 按新 id 消费(只认领一次,不重复恢复)。
|
|
8071
|
+
const inter = this.stateStore.takeInterrupted(orphan.oldId);
|
|
8072
|
+
if (inter?.length)
|
|
8073
|
+
this.stateStore.saveInterrupted(clientId, inter);
|
|
6913
8074
|
}
|
|
6914
|
-
|
|
6915
|
-
|
|
6916
|
-
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
|
|
6920
|
-
|
|
6921
|
-
|
|
6922
|
-
catch {
|
|
6923
|
-
// gone (unmounted drive / deleted) — fall back to the default
|
|
8075
|
+
else {
|
|
8076
|
+
// Restore this client's last-used workspace when it still exists;
|
|
8077
|
+
// Admission gate: while quiesced, only clients with an EXISTING
|
|
8078
|
+
// session may attach (they can watch their runs drain); brand-new
|
|
8079
|
+
// clients are refused — index.ts closes their socket (4403) and the
|
|
8080
|
+
// browser reconnect loop retries after admission reopens.
|
|
8081
|
+
if (this.quiesced) {
|
|
8082
|
+
throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
|
|
6924
8083
|
}
|
|
6925
|
-
|
|
6926
|
-
|
|
6927
|
-
|
|
6928
|
-
|
|
6929
|
-
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
|
|
6934
|
-
|
|
6935
|
-
|
|
6936
|
-
if (owner?.isStreaming)
|
|
6937
|
-
createOpts = { blank: true, blankTitle: owner.title };
|
|
8084
|
+
// otherwise fall back to the server's configured default cwd.
|
|
8085
|
+
let cwd = this.cwd;
|
|
8086
|
+
const saved = this.stateStore.get(clientId);
|
|
8087
|
+
if (saved.lastCwd && saved.lastCwd !== this.cwd) {
|
|
8088
|
+
try {
|
|
8089
|
+
if (statSync(saved.lastCwd).isDirectory())
|
|
8090
|
+
cwd = saved.lastCwd;
|
|
8091
|
+
}
|
|
8092
|
+
catch {
|
|
8093
|
+
// gone (unmounted drive / deleted) — fall back to the default
|
|
8094
|
+
}
|
|
6938
8095
|
}
|
|
6939
|
-
|
|
6940
|
-
|
|
8096
|
+
// Sessions use the SDK default per-project dir — no per-client dir.
|
|
8097
|
+
// issue #145:新标签页默认恢复项目最近的会话 —— 若那条在别处跑着,
|
|
8098
|
+
// 建之前就决定空白(第二个 writer 根本不会被打开,也无需事后拆 runtime)。
|
|
8099
|
+
// 先做无 I/O 的便宜判断,无人在跑时不扫目录。
|
|
8100
|
+
let createOpts;
|
|
8101
|
+
if (this.hasStreamingElsewhere(clientId)) {
|
|
8102
|
+
try {
|
|
8103
|
+
const infos = await SessionManager.list(cwd, piSessionsRoot());
|
|
8104
|
+
const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
|
|
8105
|
+
const owner = recent ? this.findSessionOwner(recent, clientId) : null;
|
|
8106
|
+
if (owner?.isStreaming)
|
|
8107
|
+
createOpts = { blank: true, blankTitle: owner.title };
|
|
8108
|
+
}
|
|
8109
|
+
catch {
|
|
8110
|
+
// 列表失败不挡正常恢复
|
|
8111
|
+
}
|
|
6941
8112
|
}
|
|
6942
|
-
|
|
6943
|
-
|
|
6944
|
-
this.pending.delete(clientId);
|
|
6945
|
-
});
|
|
6946
|
-
this.pending.set(clientId, creating);
|
|
6947
|
-
cs = await creating;
|
|
6948
|
-
this.clients.set(clientId, cs);
|
|
6949
|
-
// issue #145 接线提前:首帧 elsewhere 依赖它。
|
|
6950
|
-
cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
|
|
6951
|
-
cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
|
|
6952
|
-
cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
|
|
6953
|
-
cs.listExternalRunning = () => this.listExternalRunning(clientId);
|
|
6954
|
-
cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
|
|
6955
|
-
cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
|
|
6956
|
-
cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
|
|
6957
|
-
cs.schedulerStore = this.schedulerStore;
|
|
6958
|
-
// Make sure the restored/default workspace appears in the project list.
|
|
6959
|
-
this.stateStore.remember(clientId, cwd);
|
|
6960
|
-
if (cwd !== this.cwd) {
|
|
6961
|
-
send({
|
|
6962
|
-
type: "notice",
|
|
6963
|
-
level: "info",
|
|
6964
|
-
text: `已恢复上次的工作目录:${cwd}`,
|
|
6965
|
-
textEn: `Restored the last working directory: ${cwd}`,
|
|
8113
|
+
const creating = ClientSession.create(clientId, cwd, this.stateStore, createOpts).finally(() => {
|
|
8114
|
+
this.pending.delete(clientId);
|
|
6966
8115
|
});
|
|
8116
|
+
this.pending.set(clientId, creating);
|
|
8117
|
+
cs = await creating;
|
|
8118
|
+
this.clients.set(clientId, cs);
|
|
8119
|
+
// issue #145 接线提前:首帧 elsewhere 依赖它。
|
|
8120
|
+
this.wireClient(cs, clientId);
|
|
8121
|
+
// Make sure the restored/default workspace appears in the project list.
|
|
8122
|
+
this.stateStore.remember(clientId, cwd);
|
|
8123
|
+
if (cwd !== this.cwd) {
|
|
8124
|
+
send({
|
|
8125
|
+
type: "notice",
|
|
8126
|
+
level: "info",
|
|
8127
|
+
text: `已恢复上次的工作目录:${cwd}`,
|
|
8128
|
+
textEn: `Restored the last working directory: ${cwd}`,
|
|
8129
|
+
});
|
|
8130
|
+
}
|
|
6967
8131
|
}
|
|
6968
8132
|
}
|
|
6969
8133
|
}
|
|
@@ -6984,13 +8148,7 @@ export class AgentService {
|
|
|
6984
8148
|
cs.pluginStopBgTask = this.pluginStopBgTask;
|
|
6985
8149
|
cs.isQuiesced = () => this.quiesced;
|
|
6986
8150
|
// issue #145 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表)。
|
|
6987
|
-
|
|
6988
|
-
cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
|
|
6989
|
-
cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
|
|
6990
|
-
cs.listExternalRunning = () => this.listExternalRunning(clientId);
|
|
6991
|
-
cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
|
|
6992
|
-
cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
|
|
6993
|
-
cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
|
|
8151
|
+
this.wireClient(cs, clientId);
|
|
6994
8152
|
// 插件宿主工作区跟随:初次接入也同步一次(恢复的 lastCwd 可能≠服务启动目录),
|
|
6995
8153
|
// notifyCwd 幂等去重;此后 set_cwd 成功时由 cs.onCwdChanged 继续驱动。
|
|
6996
8154
|
cs.onCwdChanged = (abs, roots) => this.onClientCwdChanged?.(abs, roots);
|