pi-web-ui 0.100.0 → 0.102.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 +53 -1
- package/README.md +46 -44
- package/README.zh-CN.md +41 -39
- package/bin/pi-web-ui.mjs +17 -19
- package/dist/server/agent-formatters.js +191 -0
- package/dist/server/agent-service-daemon.js +1266 -0
- package/dist/server/agent-service.js +9884 -12815
- package/dist/server/approval-default-rules.js +158 -0
- package/dist/server/approval-rules.js +41 -167
- package/dist/server/ask-user-question-tool.js +104 -0
- package/dist/server/attachment-store.js +38 -1
- package/dist/server/bash-tool.js +83 -0
- package/dist/server/browser-page-tool.js +207 -0
- package/dist/server/client-id-utils.js +51 -0
- package/dist/server/client-state.js +38 -2
- package/dist/server/compaction-markers.js +34 -1
- package/dist/server/context-budget-runner.js +43 -0
- package/dist/server/dangling-tools.js +18 -5
- package/dist/server/delegate-mode.js +1 -0
- package/dist/server/dispatch-domain-handlers.js +631 -0
- package/dist/server/dispatch-plugin-handlers.js +300 -0
- package/dist/server/dsh/dsh-agent-service.js +30 -5
- package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
- package/dist/server/goal-evidence.js +9 -2
- package/dist/server/goal-service.js +1 -1
- package/dist/server/hashline-engine.js +1 -1
- package/dist/server/index.js +191 -969
- package/dist/server/left-panel-running.js +115 -0
- package/dist/server/lsp-tool.js +40 -12
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/market-service.js +277 -0
- package/dist/server/mcp-bridge.js +137 -30
- package/dist/server/mcp-hot-reload.js +84 -27
- package/dist/server/mcp-manager.js +215 -0
- package/dist/server/message-entry-resolver.js +32 -0
- package/dist/server/orphan-manager.js +44 -0
- package/dist/server/persona-chain.js +63 -0
- package/dist/server/plan-mode.js +2 -0
- package/dist/server/plan-update-tool.js +96 -0
- package/dist/server/plugin-api-catalog.js +20 -0
- package/dist/server/plugin-facilities.js +13 -3
- package/dist/server/plugin-installer.js +6 -1
- package/dist/server/plugin-ui-slots.js +39 -0
- package/dist/server/plugins.js +72 -38
- package/dist/server/preset-fields.js +35 -0
- package/dist/server/preset-share.js +9 -0
- package/dist/server/process-utils.js +30 -0
- package/dist/server/prompt-assembler.js +80 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/scm-commitmsg.js +74 -0
- package/dist/server/serialize.js +97 -7
- package/dist/server/session-branch.js +367 -0
- package/dist/server/session-parser.js +235 -0
- package/dist/server/session-search.js +158 -0
- package/dist/server/settings-service.js +28 -1
- package/dist/server/skill-content-filler.js +33 -0
- package/dist/server/subagent-handoff.js +18 -0
- package/dist/server/subagent-helpers.js +88 -0
- package/dist/server/terminals.js +155 -58
- package/dist/server/tool-guards.js +527 -0
- package/dist/server/tool-host-factories.js +217 -0
- package/dist/server/tool-manager.js +30 -5
- package/dist/server/wait-subscription-scan.js +46 -1
- package/dist/server/workspace-snapshot.js +18 -0
- package/extensions/webui.ts +90 -24
- package/package.json +1 -1
- package/plugin-sdk/README.md +17 -0
- package/plugin-sdk/index.d.ts +17 -0
- package/plugin-sdk/index.mjs +5 -0
- package/plugins/catalog.json +20 -0
- package/themes/aetheris.css +3 -1
- package/themes/translucent.css +8 -1
- package/themes/transparent.css +9 -1
- package/themes/zhupi-dark.css +3 -14
- package/themes/zhupi.css +2 -16
- package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
- package/web/dist/assets/index-CP71PHb6.js +680 -0
- package/web/dist/assets/index-ytRwL6j0.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B-E2EM_0.css +0 -1
- package/web/dist/assets/index-BYumAaGi.js +0 -379
|
@@ -0,0 +1,1266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-service-daemon — pi-web-ui 多客户端顶层连接服务与过户事务编排引擎。
|
|
3
|
+
*
|
|
4
|
+
* 负责:
|
|
5
|
+
* - 多客户端会话池管理(ClientSession registry & attach/detach 连接池)
|
|
6
|
+
* - 服务排空门禁与状态机(Quiesce / Draining state machine)
|
|
7
|
+
* - 跨标签页会话查重与同项目并行感知(SessionOwnerInfo & ElsewhereRunning)
|
|
8
|
+
* - 跨端手动过户事务与夭折回滚(Takeover Transactions & Rollback)
|
|
9
|
+
* - 跨端问卷预告与答复路由(Peek & Answer Elsewhere Questions)
|
|
10
|
+
* - 插件/调度器无头客户端隔离执行(completeForPlugins & scheduler dispatch)
|
|
11
|
+
* - 服务端运行状态快照(serviceStatus)
|
|
12
|
+
*
|
|
13
|
+
* 从 agent-service.ts 抽出为独立模块。
|
|
14
|
+
*/
|
|
15
|
+
import { join, resolve, sep } from "node:path";
|
|
16
|
+
import { statSync } from "node:fs";
|
|
17
|
+
import { VERSION, SessionManager, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import { ClientStateStore } from "./client-state.js";
|
|
19
|
+
import { ClaimStore } from "./claim-store.js";
|
|
20
|
+
import { toServiceInfo, launchOrigin } from "./launch-origin.js";
|
|
21
|
+
import { isPseudoClientId, checkPluginCwd } from "./client-id-utils.js";
|
|
22
|
+
import { pickAdoptableOrphan } from "./orphan-manager.js";
|
|
23
|
+
import { piSessionsRoot } from "./session-search.js";
|
|
24
|
+
import { MAX_OPEN_CONVERSATIONS } from "./agent-formatters.js";
|
|
25
|
+
import { collectSubagentDescendantIds } from "./subagents.js";
|
|
26
|
+
import { pickLatestClientSnapshot } from "./plugin-conversation-view.js";
|
|
27
|
+
import { ClientSession, QuiesceRejectedError, OFFLINE_ROW_TTL_MS, } from "./agent-service.js";
|
|
28
|
+
export class AgentService {
|
|
29
|
+
cwd;
|
|
30
|
+
static isPseudoClientId = isPseudoClientId;
|
|
31
|
+
/** 客户端 -> 最后一个浏览器断开的时刻(离线行宽限期起点;重连/认领即删)。 */
|
|
32
|
+
offlineSince = new Map();
|
|
33
|
+
/** 客户端 -> 离线行宽限期到期定时器(到期后让其他客户端重推,行消失)。 */
|
|
34
|
+
offlineTimers = new Map();
|
|
35
|
+
/** index.ts 注入:SDK 工具执行事件的插件转发钩子,attach 时拷贝到每个新会话。 */
|
|
36
|
+
onToolEvent = undefined;
|
|
37
|
+
/** index.ts 注入:bash/read 插件拦截钩子,attach 时拷贝到每个新会话。 */
|
|
38
|
+
toolGuard = undefined;
|
|
39
|
+
/** index.ts 注入:运行轨迹事件的插件转发钩子,attach 时拷贝到每个新会话。 */
|
|
40
|
+
onRunEvent = undefined;
|
|
41
|
+
/** index.ts 注入:对话切换通知钩子,attach 时拷贝到每个新会话。 */
|
|
42
|
+
onConversationChanged = undefined;
|
|
43
|
+
/** index.ts 注入:模型切换成功通知钩子(#542),attach 时拷贝到每个新会话。 */
|
|
44
|
+
onClientModelChanged = undefined;
|
|
45
|
+
/** index.ts 注入:读取插件当前注册的 AI 工具(attach 时拷贝到每个新会话)。 */
|
|
46
|
+
pluginToolsProvider = undefined;
|
|
47
|
+
/** index.ts 注入:读取插件当前注册的斜杠命令(attach 时拷贝到每个新会话)。 */
|
|
48
|
+
pluginCommandsProvider = undefined;
|
|
49
|
+
/** index.ts 注入:读取插件注册的常驻后台任务(并入 bg_servers 面板)。 */
|
|
50
|
+
pluginBgTasksProvider = undefined;
|
|
51
|
+
/** index.ts 注入:停止插件任务(kill_background_server with taskId)。 */
|
|
52
|
+
pluginStopBgTask = undefined;
|
|
53
|
+
/** index.ts 注入:内置调度存储(attach 时拷贝到每个新会话,供 schedule_* 工具)。 */
|
|
54
|
+
schedulerStore = undefined;
|
|
55
|
+
clients = new Map();
|
|
56
|
+
/** 全局认领表(跨浏览器标签页共享;<dataDir>/claims.json,best-effort 持久化)。 */
|
|
57
|
+
claimStore;
|
|
58
|
+
/** Quiesce (draining) state — the service refuses NEW work (prompts, forks,
|
|
59
|
+
* session resumes, new clients) so a deploy/upgrade/backup can stop cleanly
|
|
60
|
+
* once existing runs finish. Controlled via the local control socket:
|
|
61
|
+
* `pi-web-ui server quiesce|unquiesce`. */
|
|
62
|
+
quiesced = false;
|
|
63
|
+
quiescedAt = 0;
|
|
64
|
+
/** Attached browser sockets (reported by index.ts on open/close) — the
|
|
65
|
+
* control socket reports real sockets, not cached client-session objects. */
|
|
66
|
+
socketCount = 0;
|
|
67
|
+
pending = new Map();
|
|
68
|
+
pendingDetaches = new Map();
|
|
69
|
+
stateStore;
|
|
70
|
+
/** Set by index.ts: called when /pi-web-ui:quit is invoked. */
|
|
71
|
+
onQuit = undefined;
|
|
72
|
+
/** 任意客户端成功切换工作区后触发(新绝对路径 + 该项目的额外工作区根)。
|
|
73
|
+
* index.ts 接到 PluginManager.notifyCwd / notifyWorkspaceRoots,让插件宿主的
|
|
74
|
+
* host.cwd 实时跟随当前项目、受支持路径范围跟着多根变。 */
|
|
75
|
+
onClientCwdChanged = undefined;
|
|
76
|
+
constructor(cwd, stateFile) {
|
|
77
|
+
this.cwd = cwd;
|
|
78
|
+
this.stateStore = new ClientStateStore(stateFile);
|
|
79
|
+
this.claimStore = new ClaimStore(join(this.stateStore.dataDir, "claims.json"));
|
|
80
|
+
}
|
|
81
|
+
/** Get or create the session for a client, racing attach calls safely. */
|
|
82
|
+
/** True while the service is draining — new work is refused. */
|
|
83
|
+
isQuiesced() {
|
|
84
|
+
return this.quiesced;
|
|
85
|
+
}
|
|
86
|
+
/** Enter quiesce: stop admitting new work. Existing runs keep going. */
|
|
87
|
+
quiesce() {
|
|
88
|
+
this.quiesced = true;
|
|
89
|
+
this.quiescedAt = Date.now();
|
|
90
|
+
}
|
|
91
|
+
/** Leave quiesce: admit new work again. */
|
|
92
|
+
unquiesce() {
|
|
93
|
+
this.quiesced = false;
|
|
94
|
+
this.quiescedAt = 0;
|
|
95
|
+
}
|
|
96
|
+
/** Snapshot for the control socket / status command. */
|
|
97
|
+
quiesceInfo() {
|
|
98
|
+
return this.quiesced ? { quiesced: true, quiescedSince: this.quiescedAt } : { quiesced: false };
|
|
99
|
+
}
|
|
100
|
+
/** issue #145:除请求方外是否有客户端正在跑(扫目录查重前置的无 I/O 判断)。 */
|
|
101
|
+
hasStreamingElsewhere(excludeClientId) {
|
|
102
|
+
for (const [clientId, cs] of this.clients) {
|
|
103
|
+
if (clientId === excludeClientId)
|
|
104
|
+
continue;
|
|
105
|
+
try {
|
|
106
|
+
if (cs.activeConversations() > 0)
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// 单客户端坏了不影响判断
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
/** issue #145:跨客户端同会话查重 —— 找持有某 session 文件的别处对话。
|
|
116
|
+
* 调用方在 SessionManager.open() 之前问这一句,就造不出第二个 writer。 */
|
|
117
|
+
findSessionOwner(targetPath, excludeClientId) {
|
|
118
|
+
for (const [clientId, cs] of this.clients) {
|
|
119
|
+
if (clientId === excludeClientId)
|
|
120
|
+
continue;
|
|
121
|
+
const conv = cs.findConversationBySessionFile(targetPath);
|
|
122
|
+
if (conv) {
|
|
123
|
+
return {
|
|
124
|
+
clientId,
|
|
125
|
+
convId: conv.id,
|
|
126
|
+
title: conv.title,
|
|
127
|
+
cwd: conv.cwd,
|
|
128
|
+
isStreaming: cs.conversationStreaming(conv),
|
|
129
|
+
connected: cs.sinkCount() > 0,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
/** 插件 steer 跨客户端兜底:除请求方外逐个问其他客户端的 conversations,
|
|
136
|
+
* 找到持有方由其执行 steer(只调 steerOwnConversation,不碰钩子,无递归);
|
|
137
|
+
* 都找不到回 undefined,调用方回未知对话。单客户端异常跳过,不影响其他。 */
|
|
138
|
+
async steerElsewhere(excludeClientId, id, text) {
|
|
139
|
+
for (const [clientId, cs] of this.clients) {
|
|
140
|
+
if (clientId === excludeClientId)
|
|
141
|
+
continue;
|
|
142
|
+
try {
|
|
143
|
+
const r = await cs.steerOwnConversation(id, text);
|
|
144
|
+
if (r)
|
|
145
|
+
return r;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// 单客户端坏了继续找下一个
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
/** issue #193:定时任务唤醒发起对话。逐个客户端找持有方,用 steer 语义投递
|
|
154
|
+
* (运行时插队、未跑时普通投递,不切用户当前对话);都找不到回 ok:false,
|
|
155
|
+
* 调用方(index.ts executor)回落视口/无头执行。quiesced 时直接拒绝。
|
|
156
|
+
* issue #226:成功时带回持有方 clientId(插件绑定网页会话时原样回执)。
|
|
157
|
+
* issue #231:opts.sessionFile 是跨压缩/重启的稳定键 —— 优先按它认同一会话
|
|
158
|
+
* (内存对话 id 重启即失效,压缩后同文件对话可能已换新 id,成功时带回**实际**
|
|
159
|
+
* 投递的 conversationId + sessionFile,调用方据此重绑定任务);id 相位带 cwd
|
|
160
|
+
* 护栏(各客户端计数器都从 c1 开始,不校验会把报告投进无关项目)。压缩进行中
|
|
161
|
+
* 的持有方回 busy:true(调用方另寻视口兄弟,而不是当成“不在”静默转无头)。 */
|
|
162
|
+
async wakeConversation(id, text, opts) {
|
|
163
|
+
const wantFile = String(opts?.sessionFile ?? "").trim();
|
|
164
|
+
const wantCwd = String(opts?.cwd ?? "").trim();
|
|
165
|
+
if ((!id && !wantFile) || !text.trim())
|
|
166
|
+
return { ok: false, error: "唤醒目标或文本为空" };
|
|
167
|
+
if (this.quiesced)
|
|
168
|
+
return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
|
|
169
|
+
const liveFile = (c) => {
|
|
170
|
+
try {
|
|
171
|
+
return String(c.session.sessionFile ?? "");
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return "";
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const flush = (cs) => {
|
|
178
|
+
try {
|
|
179
|
+
cs.flushSnapshot();
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// 推送失败不影响已投递的唤醒
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
// 相位一:落盘会话文件(稳定键)。同文件可能在多处打开,取最近活跃者;
|
|
186
|
+
// 全部忙(压缩中)则报 busy,调用方去找视口兄弟。
|
|
187
|
+
if (wantFile) {
|
|
188
|
+
const hits = [];
|
|
189
|
+
for (const [clientId, cs] of this.clients) {
|
|
190
|
+
try {
|
|
191
|
+
const conv = cs.resolveSchedulerTarget({ sessionFile: wantFile });
|
|
192
|
+
if (conv)
|
|
193
|
+
hits.push({ cs, clientId, conv });
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
// 单客户端坏了继续找下一个
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
200
|
+
let busyError;
|
|
201
|
+
for (const h of hits) {
|
|
202
|
+
try {
|
|
203
|
+
const r = await h.cs.trySteerScheduler(h.conv, text);
|
|
204
|
+
if (r.ok) {
|
|
205
|
+
flush(h.cs);
|
|
206
|
+
return { ok: true, conversationId: h.conv.id, sessionFile: liveFile(h.conv), clientId: h.clientId };
|
|
207
|
+
}
|
|
208
|
+
if (r.busy)
|
|
209
|
+
busyError = r.error;
|
|
210
|
+
// 非忙失败(投递异常)试下一个同文件持有方
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
// 单客户端坏了继续找下一个
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (hits.length > 0) {
|
|
217
|
+
if (busyError)
|
|
218
|
+
return { ok: false, busy: true, error: busyError };
|
|
219
|
+
// 同文件持有方都在但都投递失败 —— id 相位大概率指向同一批,无需再试
|
|
220
|
+
return { ok: false, error: "目标对话投递失败(持有方异常)" };
|
|
221
|
+
}
|
|
222
|
+
// 无同文件持有方 —— 老任务只有 id,继续相位二
|
|
223
|
+
}
|
|
224
|
+
// 相位二:内存对话 id(易失键,必须配 cwd 护栏防跨项目串台)。
|
|
225
|
+
if (id) {
|
|
226
|
+
const hits = [];
|
|
227
|
+
for (const [clientId, cs] of this.clients) {
|
|
228
|
+
try {
|
|
229
|
+
const conv = cs.resolveSchedulerTarget({
|
|
230
|
+
conversationId: id,
|
|
231
|
+
...(wantCwd ? { cwd: wantCwd } : {}),
|
|
232
|
+
});
|
|
233
|
+
if (conv)
|
|
234
|
+
hits.push({ cs, clientId, conv });
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
// 单客户端坏了继续找下一个
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
hits.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
241
|
+
let busyError;
|
|
242
|
+
for (const h of hits) {
|
|
243
|
+
try {
|
|
244
|
+
const r = await h.cs.trySteerScheduler(h.conv, text);
|
|
245
|
+
if (r.ok) {
|
|
246
|
+
flush(h.cs);
|
|
247
|
+
return { ok: true, conversationId: h.conv.id, sessionFile: liveFile(h.conv), clientId: h.clientId };
|
|
248
|
+
}
|
|
249
|
+
if (r.busy)
|
|
250
|
+
busyError = r.error;
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
// 单客户端坏了继续找下一个
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (busyError)
|
|
257
|
+
return { ok: false, busy: true, error: busyError };
|
|
258
|
+
}
|
|
259
|
+
return { ok: false, error: "目标对话不在运行中(已关闭或服务重启过)" };
|
|
260
|
+
}
|
|
261
|
+
/** issue #231:同项目视口回退 —— 原绑定对话不在时,把唤醒投给该项目最近活跃
|
|
262
|
+
* 的对话(用户当前正看着的面),而不是静默转无头。excludeIds 跳过已知忙对话;
|
|
263
|
+
* 候选全部忙回 busy:true;无候选回 ok:false。成功带回实际投递方(调用方重绑定)。 */
|
|
264
|
+
async wakeViewportInCwd(cwd, text, excludeIds) {
|
|
265
|
+
const want = String(cwd ?? "").trim();
|
|
266
|
+
if (!want || !text.trim())
|
|
267
|
+
return { ok: false, error: "回退目标或文本为空" };
|
|
268
|
+
if (this.quiesced)
|
|
269
|
+
return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
|
|
270
|
+
const cands = [];
|
|
271
|
+
for (const [clientId, cs] of this.clients) {
|
|
272
|
+
try {
|
|
273
|
+
const conv = cs.findViewportInCwd(want, excludeIds);
|
|
274
|
+
if (conv)
|
|
275
|
+
cands.push({ cs, clientId, conv });
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
// 单客户端坏了继续找下一个
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
cands.sort((a, b) => b.conv.lastActiveAt - a.conv.lastActiveAt);
|
|
282
|
+
if (cands.length === 0)
|
|
283
|
+
return { ok: false, error: "同项目无存活对话" };
|
|
284
|
+
let busyError;
|
|
285
|
+
for (const c of cands) {
|
|
286
|
+
try {
|
|
287
|
+
const r = await c.cs.trySteerScheduler(c.conv, text);
|
|
288
|
+
if (r.ok) {
|
|
289
|
+
try {
|
|
290
|
+
c.cs.flushSnapshot();
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// 推送失败不影响已投递的唤醒
|
|
294
|
+
}
|
|
295
|
+
let f = "";
|
|
296
|
+
try {
|
|
297
|
+
f = String(c.conv.session.sessionFile ?? "");
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
f = "";
|
|
301
|
+
}
|
|
302
|
+
return { ok: true, conversationId: c.conv.id, sessionFile: f, clientId: c.clientId };
|
|
303
|
+
}
|
|
304
|
+
if (r.busy)
|
|
305
|
+
busyError = r.error;
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
// 单客户端坏了继续找下一个
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (busyError)
|
|
312
|
+
return { ok: false, busy: true, error: busyError };
|
|
313
|
+
return { ok: false, error: "同项目对话投递失败" };
|
|
314
|
+
}
|
|
315
|
+
/** issue #145:别处在某 cwd 下正在跑的对话(同项目并行感知用,不含请求方)。 */
|
|
316
|
+
listProjectRunners(cwd, excludeClientId) {
|
|
317
|
+
const out = [];
|
|
318
|
+
for (const [clientId, cs] of this.clients) {
|
|
319
|
+
if (clientId === excludeClientId)
|
|
320
|
+
continue;
|
|
321
|
+
for (const r of cs.streamingInCwd(cwd))
|
|
322
|
+
out.push({ clientId, title: r.title, sessionFile: r.sessionFile });
|
|
323
|
+
}
|
|
324
|
+
return out;
|
|
325
|
+
}
|
|
326
|
+
/** 按 SDK 会话(runtime 身份)找它当前归属的客户端会话与对话 id(过户后归属会变):
|
|
327
|
+
* 桥接工具(问卷 / 页面)在调用瞬间用它投递,见 ClientSession.bridgeTarget。
|
|
328
|
+
* 一条对话任一时刻只属于一个会话(过户先摘后插),扫一遍即可 —— 问卷/截图都是
|
|
329
|
+
* 低频调用,不值得为此再维护一张全局索引。 */
|
|
330
|
+
findConversationHome(sdkSession) {
|
|
331
|
+
for (const cs of this.clients.values()) {
|
|
332
|
+
try {
|
|
333
|
+
const convId = cs.conversationIdOfSession(sdkSession);
|
|
334
|
+
if (convId)
|
|
335
|
+
return { session: cs, convId };
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
// 单客户端坏了不影响解析
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return undefined;
|
|
342
|
+
}
|
|
343
|
+
/** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
|
|
344
|
+
* owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
|
|
345
|
+
listExternalRunning(excludeClientId) {
|
|
346
|
+
// 1) 收集当前请求客户端自己持有的对话(按 sessionFile 与 cwd+title 双维度),
|
|
347
|
+
// 本机已经持有的对话绝不作为 elsewhere 行推给本机(避免左栏同一对话既是“当前”又是“另一处”)。
|
|
348
|
+
const currentCs = this.clients.get(excludeClientId);
|
|
349
|
+
const localFiles = new Set();
|
|
350
|
+
const localCwdTitles = new Set();
|
|
351
|
+
if (currentCs) {
|
|
352
|
+
for (const b of currentCs.takeoverBriefs()) {
|
|
353
|
+
if (b.sessionFile)
|
|
354
|
+
localFiles.add(resolve(b.sessionFile));
|
|
355
|
+
localCwdTitles.add(`${b.cwd}\0${b.title}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// 2) 遍历其他客户端,收集条目并按 sessionFile / cwd+title 去重。
|
|
359
|
+
// 若多个客户端持有同会话(如断连竞争、多标签残留),保留正在运行(streaming)或有问卷的更活跃者,
|
|
360
|
+
// 杜绝“一堆同一个对话的另一处”在左栏堆积。
|
|
361
|
+
const dedupMap = new Map();
|
|
362
|
+
const now = Date.now();
|
|
363
|
+
for (const [clientId, cs] of this.clients) {
|
|
364
|
+
if (clientId === excludeClientId)
|
|
365
|
+
continue;
|
|
366
|
+
// 伪客户端(scheduler:/plugin:)不走浏览器,sinkCount 永远为 0,保留。
|
|
367
|
+
const isPseudo = AgentService.isPseudoClientId(clientId);
|
|
368
|
+
// 无浏览器连接的残骸(sinkCount=0 = 断连留存):宽限期内仍下发(标
|
|
369
|
+
// ownerOffline,可接管),过期或 TTL=0 时按 issue #291 不入列表。
|
|
370
|
+
const offline = !isPseudo && cs.sinkCount() === 0;
|
|
371
|
+
if (offline && OFFLINE_ROW_TTL_MS <= 0)
|
|
372
|
+
continue;
|
|
373
|
+
const offlineSince = offline ? (this.offlineSince.get(clientId) ?? 0) : 0;
|
|
374
|
+
for (const r of cs.streamingSummariesAll()) {
|
|
375
|
+
// activity 只服务宽限期判定,不进 wire(ElsewhereRunning 无此字段)。
|
|
376
|
+
const { activity, ...rest } = r;
|
|
377
|
+
if (offline && !rest.isStreaming) {
|
|
378
|
+
// 宽限期从「断开时刻」与「最后一次活动」里取较晚者:跑动的后台任务
|
|
379
|
+
// 每有事件就续期,不会跑到一半从别人列表里消失。
|
|
380
|
+
const latest = Math.max(offlineSince, activity || 0);
|
|
381
|
+
if (latest > 0 && now - latest > OFFLINE_ROW_TTL_MS)
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const normFile = rest.sessionFile ? resolve(rest.sessionFile) : undefined;
|
|
385
|
+
// 本机已持有该会话文件,或本机在同项目下已有同名可见对话:排除
|
|
386
|
+
if (normFile && localFiles.has(normFile))
|
|
387
|
+
continue;
|
|
388
|
+
if (localCwdTitles.has(`${rest.cwd}\0${rest.title}`))
|
|
389
|
+
continue;
|
|
390
|
+
const entry = {
|
|
391
|
+
...rest,
|
|
392
|
+
owner: clientId,
|
|
393
|
+
...(isPseudo ? { pseudo: true } : {}),
|
|
394
|
+
...(offline ? { ownerOffline: true } : {}),
|
|
395
|
+
};
|
|
396
|
+
// 跨客户端去重键:有文件按规范路径去重,无文件按 cwd + title 去重
|
|
397
|
+
const dedupKey = normFile ? `file:${normFile}` : `title:${rest.cwd}\0${rest.title}`;
|
|
398
|
+
const existing = dedupMap.get(dedupKey);
|
|
399
|
+
if (existing) {
|
|
400
|
+
// 优先保留 streaming,其次保留 hasQuestion,最后才轮到离线行让位在线行
|
|
401
|
+
const preferNew = (!existing.isStreaming && entry.isStreaming) ||
|
|
402
|
+
(!existing.hasQuestion && entry.hasQuestion) ||
|
|
403
|
+
(Boolean(existing.ownerOffline) && !entry.ownerOffline);
|
|
404
|
+
if (preferNew) {
|
|
405
|
+
dedupMap.set(dedupKey, entry);
|
|
406
|
+
}
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
dedupMap.set(dedupKey, entry);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return [...dedupMap.values()];
|
|
413
|
+
}
|
|
414
|
+
/** 离线行宽限期到期 → 让其他客户端重推一次(行随之从列表消失,回到 #291 口径)。
|
|
415
|
+
*
|
|
416
|
+
* 到期时刻取「断开时刻」与「最后一次活动」的较晚者:断开后 run 还在跑的后台任务
|
|
417
|
+
* 每有流式变化都会重排(见 pokeExternalRunning),跑完那一刻的推送把宽限期从新起算。
|
|
418
|
+
* 到期回调只推送、**不再重排**,否则「行已过期」会被无限排成 1s 轮询。 */
|
|
419
|
+
armOfflineRowExpiry(clientId, cs) {
|
|
420
|
+
if (OFFLINE_ROW_TTL_MS <= 0)
|
|
421
|
+
return;
|
|
422
|
+
const prev = this.offlineTimers.get(clientId);
|
|
423
|
+
if (prev)
|
|
424
|
+
clearTimeout(prev);
|
|
425
|
+
let activity = 0;
|
|
426
|
+
try {
|
|
427
|
+
activity = cs.latestActivity();
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
activity = 0;
|
|
431
|
+
}
|
|
432
|
+
const since = Math.max(this.offlineSince.get(clientId) ?? 0, activity || 0);
|
|
433
|
+
const delay = Math.max(1_000, since + OFFLINE_ROW_TTL_MS - Date.now() + 1_000);
|
|
434
|
+
const timer = setTimeout(() => {
|
|
435
|
+
this.offlineTimers.delete(clientId);
|
|
436
|
+
// 期间重连/被认领/被回收都算作废:只推真实还存在的离线残骸。
|
|
437
|
+
if (this.clients.get(clientId) === cs && !AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
|
|
438
|
+
this.notifyExternalRunning(clientId);
|
|
439
|
+
}
|
|
440
|
+
}, delay);
|
|
441
|
+
timer.unref?.();
|
|
442
|
+
this.offlineTimers.set(clientId, timer);
|
|
443
|
+
}
|
|
444
|
+
/** 又有浏览器连上(或残骸被认领/回收):离线行状态作废,别的页面按在线行重推。 */
|
|
445
|
+
clearOfflineRows(clientId) {
|
|
446
|
+
const had = this.offlineSince.delete(clientId);
|
|
447
|
+
const timer = this.offlineTimers.get(clientId);
|
|
448
|
+
if (timer) {
|
|
449
|
+
clearTimeout(timer);
|
|
450
|
+
this.offlineTimers.delete(clientId);
|
|
451
|
+
}
|
|
452
|
+
if (had)
|
|
453
|
+
this.pokeExternalRunning(clientId);
|
|
454
|
+
}
|
|
455
|
+
/** issue #291:删除定时任务后回收对应伪客户端,避免残留在 elsewhere 列表。 */
|
|
456
|
+
releaseSchedulerClient(taskId) {
|
|
457
|
+
const safe = String(taskId ?? "").replace(/[^A-Za-z0-9_-]/g, "") || "task";
|
|
458
|
+
const clientId = `scheduler:${safe}`;
|
|
459
|
+
const cs = this.clients.get(clientId);
|
|
460
|
+
if (!cs)
|
|
461
|
+
return;
|
|
462
|
+
// 伪客户端常驻一个 noop sink(chatFromScheduler 的 attach),所以不能按
|
|
463
|
+
// sinkCount 判断「有没有浏览器」—— 它永远为 1。这里就是它的回收点。
|
|
464
|
+
this.clients.delete(clientId);
|
|
465
|
+
// 先摘出 map 再异步 dispose:只删 map 的话,对话的 runtime/终端/看门狗
|
|
466
|
+
// 计时器全都留在内存里(泄漏),转录还挂着活 writer(同文件双写者风险)。
|
|
467
|
+
void cs.dispose().catch(() => {
|
|
468
|
+
// 回收失败不拦主流程:尽力而为,进程退出时 OS 兜底
|
|
469
|
+
});
|
|
470
|
+
// 通知其他客户端刷新 elsewhere 列表。
|
|
471
|
+
this.pokeExternalRunning(clientId);
|
|
472
|
+
}
|
|
473
|
+
/** issue #145: 某客户端流式集合变化 → 其他客户端重推 conversations。 */
|
|
474
|
+
pokeExternalRunning(excludeClientId) {
|
|
475
|
+
// 离线残骸刚有状态变化(run 跑完 / 又有事件):离线行宽限期重新起算,
|
|
476
|
+
// 定时器顺延到「最后一次活动 + TTL」——否则任务跑完后再没人推它。
|
|
477
|
+
const offlineCs = this.clients.get(excludeClientId);
|
|
478
|
+
if (offlineCs && !AgentService.isPseudoClientId(excludeClientId) && offlineCs.sinkCount() === 0) {
|
|
479
|
+
this.armOfflineRowExpiry(excludeClientId, offlineCs);
|
|
480
|
+
}
|
|
481
|
+
this.notifyExternalRunning(excludeClientId);
|
|
482
|
+
}
|
|
483
|
+
/** 只让其他客户端重推一次(不碰离线宽限期定时器)。 */
|
|
484
|
+
notifyExternalRunning(excludeClientId) {
|
|
485
|
+
for (const [clientId, cs] of this.clients) {
|
|
486
|
+
if (clientId === excludeClientId)
|
|
487
|
+
continue;
|
|
488
|
+
try {
|
|
489
|
+
cs.refreshExternalRunning();
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
// 单客户端坏了不影响其他
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
/** issue #145:向除请求方外的所有客户端发一条 notice(并行通告用)。 */
|
|
497
|
+
notifyClientsExcept(excludeClientId, msg) {
|
|
498
|
+
for (const [clientId, cs] of this.clients) {
|
|
499
|
+
if (clientId === excludeClientId)
|
|
500
|
+
continue;
|
|
501
|
+
try {
|
|
502
|
+
// 经 ClientSession.emit 才能进该客户端的 sink 组播;用公开发送面。
|
|
503
|
+
cs.sendNotice(msg);
|
|
504
|
+
}
|
|
505
|
+
catch {
|
|
506
|
+
// 单客户端坏了不影响其他
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/** Aggregate across every client session: conversations with in-flight runs. */
|
|
511
|
+
activeConversations() {
|
|
512
|
+
let n = 0;
|
|
513
|
+
for (const cs of this.clients.values())
|
|
514
|
+
n += cs.activeConversations();
|
|
515
|
+
return n;
|
|
516
|
+
}
|
|
517
|
+
/** Aggregate across every client session: messages queued in the SDK. */
|
|
518
|
+
pendingMessages() {
|
|
519
|
+
let n = 0;
|
|
520
|
+
for (const cs of this.clients.values())
|
|
521
|
+
n += cs.pendingMessages();
|
|
522
|
+
return n;
|
|
523
|
+
}
|
|
524
|
+
/** 插件用:全客户端最近活跃对话的快照(#542:按 clientId 取某个标签页正在看的
|
|
525
|
+
* 对话;缺省回落「最近活跃的**非子代理**会话」——子代理跑得再勤也不会把用户
|
|
526
|
+
* 正在看的对话挤出快照)。clientId 不认识/该客户端暂无对话时同样走回落。 */
|
|
527
|
+
readConversationForPlugins(opts) {
|
|
528
|
+
const want = (opts?.clientId ?? "").trim();
|
|
529
|
+
if (want) {
|
|
530
|
+
const cs = this.clients.get(want);
|
|
531
|
+
if (cs) {
|
|
532
|
+
try {
|
|
533
|
+
// 显式客户端:返回它**真正在看**的对话(含子代理对话——那是事实,
|
|
534
|
+
// 快照带 isSubagent 由插件自己判)。
|
|
535
|
+
const s = cs.readConversationForPlugins({ preferActive: true, includeSubagents: true });
|
|
536
|
+
if (s)
|
|
537
|
+
return s;
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
/* 单客户端坏了不影响回落 */
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
const snaps = [];
|
|
545
|
+
for (const cs of this.clients.values()) {
|
|
546
|
+
try {
|
|
547
|
+
snaps.push(cs.readConversationForPlugins());
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
/* 单客户端坏了不影响其他 */
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return pickLatestClientSnapshot(snaps);
|
|
554
|
+
}
|
|
555
|
+
/** 插件无头调用(host.chat 的落地):外部通道(微信等)把文本投给 agent。
|
|
556
|
+
* 每个 (pluginId, accountId) 独立伪客户端——复用 attach 完整链路
|
|
557
|
+
* (会话恢复/持久化/工具注入/快照),无浏览器也能跑;sink 是空函数,
|
|
558
|
+
* 快照/notice 发了即丢,不攒内存。fire-and-forget:prompt 投递即返回,
|
|
559
|
+
* 运行结果经 onRunEvent(run_end) 按 conversationId 关联。
|
|
560
|
+
* v1 语义:与该服务 cwd 下最近会话共享(单用户视角连续);peer 名由插件
|
|
561
|
+
* 拼进文本前缀,per-peer 会话隔离以后再加。
|
|
562
|
+
* issue #226:对齐定时任务的四件套——conversationId 命中时走 steer 语义
|
|
563
|
+
* 投递(网页端实时可见,miss 则回落无头);cwd 显式 pin 住(不存在/系统
|
|
564
|
+
* 目录即拒绝,不默默跑错目录);model/thinkingLevel 投递前应用(失败即
|
|
565
|
+
* 拒绝,不回落,避免账单/效果与预期不符)。 */
|
|
566
|
+
async chatFromPlugin(pluginId, req) {
|
|
567
|
+
const safe = String(pluginId ?? "plugin").replace(/[^A-Za-z0-9_-]/g, "") || "plugin";
|
|
568
|
+
const acct = String(req?.accountId ?? "default").replace(/[^A-Za-z0-9_-]/g, "") || "default";
|
|
569
|
+
const clientId = `plugin:${safe}:${acct}`;
|
|
570
|
+
const text = String(req?.text ?? "");
|
|
571
|
+
if (!text.trim())
|
|
572
|
+
throw new Error("chatFromPlugin: text 为空");
|
|
573
|
+
if (this.quiesced)
|
|
574
|
+
throw new QuiesceRejectedError("插件无头调用被拒绝,请等服务器恢复后重试");
|
|
575
|
+
// 1. 绑定已有会话:steer 语义投递,网页端实时可见(微信当远程遥控器用)。
|
|
576
|
+
// miss/已回收时不抛错,回落无头伪客户端(浏览器关着时微信照常可用)。
|
|
577
|
+
const target = String(req?.conversationId ?? "").trim();
|
|
578
|
+
if (target) {
|
|
579
|
+
const w = await this.wakeConversation(target, text);
|
|
580
|
+
if (w.ok)
|
|
581
|
+
return { conversationId: target, clientId: w.clientId ?? clientId };
|
|
582
|
+
}
|
|
583
|
+
// 2. 工作空间:不传回落伪客户端当前目录;传了必须存在且非系统目录。
|
|
584
|
+
const cwdReq = String(req?.cwd ?? "").trim();
|
|
585
|
+
let cwdAbs = "";
|
|
586
|
+
if (cwdReq) {
|
|
587
|
+
const chk = checkPluginCwd(cwdReq);
|
|
588
|
+
if (!chk.ok)
|
|
589
|
+
throw new Error(`chatFromPlugin: ${chk.error}`);
|
|
590
|
+
cwdAbs = chk.abs ?? "";
|
|
591
|
+
}
|
|
592
|
+
const cs = await this.attach(clientId, () => { });
|
|
593
|
+
try {
|
|
594
|
+
if (cwdAbs && cs.cwd !== cwdAbs)
|
|
595
|
+
await cs.setCwd(cwdAbs);
|
|
596
|
+
}
|
|
597
|
+
catch (err) {
|
|
598
|
+
throw new Error(`chatFromPlugin: 切换工作目录失败(${cwdAbs}):${err.message}`);
|
|
599
|
+
}
|
|
600
|
+
const model = String(req?.model ?? "").trim();
|
|
601
|
+
if (model) {
|
|
602
|
+
try {
|
|
603
|
+
await cs.switchModelOrThrow(model);
|
|
604
|
+
}
|
|
605
|
+
catch (err) {
|
|
606
|
+
throw new Error(`chatFromPlugin: 切换模型失败(${model}):${err.message}`);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const thinking = String(req?.thinkingLevel ?? "").trim();
|
|
610
|
+
if (thinking) {
|
|
611
|
+
try {
|
|
612
|
+
cs.setThinking(thinking);
|
|
613
|
+
}
|
|
614
|
+
catch (err) {
|
|
615
|
+
throw new Error(`chatFromPlugin: 切换思考强度失败(${thinking}):${err.message}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
|
|
619
|
+
void cs.prompt(text);
|
|
620
|
+
return { conversationId, clientId };
|
|
621
|
+
}
|
|
622
|
+
/** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
|
|
623
|
+
* 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
|
|
624
|
+
* cwd 按任务配置 pin 住(不存在即失败,不默默跑错目录);可选模型/思考强度
|
|
625
|
+
* 在投递前应用(失败即返回错误,不回落,避免账单/效果与预期不符)。
|
|
626
|
+
* fire-and-forget 投递后等待运行结束(最长 10 分钟轮询),回填真实 outcome
|
|
627
|
+
* (成功/失败/耗时/会话 id)供历史记录与通知使用;超时按失败记录(运行本身
|
|
628
|
+
* 不中止,继续在后台跑完)。 */
|
|
629
|
+
async chatFromScheduler(task) {
|
|
630
|
+
const safe = String(task.id ?? "task").replace(/[^A-Za-z0-9_-]/g, "") || "task";
|
|
631
|
+
const clientId = `scheduler:${safe}`;
|
|
632
|
+
const text = String(task.prompt ?? "");
|
|
633
|
+
if (!text.trim())
|
|
634
|
+
return { ok: false, error: "触发指令为空" };
|
|
635
|
+
if (this.quiesced)
|
|
636
|
+
return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
|
|
637
|
+
const cwd = String(task.cwd ?? "").trim();
|
|
638
|
+
try {
|
|
639
|
+
if (!cwd || !statSync(cwd).isDirectory())
|
|
640
|
+
throw new Error("not-a-dir");
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
return { ok: false, error: `目标项目不存在或不是目录:${cwd || "(空)"}` };
|
|
644
|
+
}
|
|
645
|
+
try {
|
|
646
|
+
const cs = await this.attach(clientId, () => { });
|
|
647
|
+
if (cs.cwd !== cwd)
|
|
648
|
+
await cs.setCwd(cwd);
|
|
649
|
+
const model = String(task.model ?? "").trim();
|
|
650
|
+
if (model) {
|
|
651
|
+
try {
|
|
652
|
+
await cs.switchModelOrThrow(model);
|
|
653
|
+
}
|
|
654
|
+
catch (err) {
|
|
655
|
+
return { ok: false, error: `切换模型失败(${model}):${err.message}` };
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const thinking = String(task.thinkingLevel ?? "").trim();
|
|
659
|
+
if (thinking) {
|
|
660
|
+
try {
|
|
661
|
+
cs.setThinking(thinking);
|
|
662
|
+
}
|
|
663
|
+
catch (err) {
|
|
664
|
+
return { ok: false, error: `切换思考强度失败(${thinking}):${err.message}` };
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
|
|
668
|
+
void cs.prompt(`[定时任务] ${text}`);
|
|
669
|
+
// 等待运行结束:每 2s 轮询,最长 10 分钟。超时按失败记录(运行继续)。
|
|
670
|
+
const deadline = Date.now() + 10 * 60 * 1000;
|
|
671
|
+
for (;;) {
|
|
672
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
673
|
+
let streaming = false;
|
|
674
|
+
let lastError;
|
|
675
|
+
try {
|
|
676
|
+
const snap = cs.readConversationForPlugins();
|
|
677
|
+
streaming = snap?.isStreaming === true;
|
|
678
|
+
const msgs = snap?.messages ?? [];
|
|
679
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
680
|
+
const m = msgs[i];
|
|
681
|
+
if (m.role === "assistant" && m.errorMessage) {
|
|
682
|
+
lastError = m.errorMessage;
|
|
683
|
+
break;
|
|
684
|
+
}
|
|
685
|
+
if (m.role === "assistant")
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
catch {
|
|
690
|
+
streaming = false;
|
|
691
|
+
}
|
|
692
|
+
if (!streaming) {
|
|
693
|
+
if (lastError)
|
|
694
|
+
return { ok: false, conversationId: conversationId || undefined, error: lastError };
|
|
695
|
+
return { ok: true, conversationId: conversationId || undefined };
|
|
696
|
+
}
|
|
697
|
+
if (Date.now() >= deadline)
|
|
698
|
+
return { ok: false, conversationId: conversationId || undefined, error: "运行超时(10 分钟),仍在后台继续" };
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
catch (err) {
|
|
702
|
+
return { ok: false, error: err.message };
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
|
|
706
|
+
* 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
|
|
707
|
+
* quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
|
|
708
|
+
async completeForPlugins(pluginId, req) {
|
|
709
|
+
try {
|
|
710
|
+
if (this.quiesced)
|
|
711
|
+
return { ok: false, error: "插件 LLM 调用被拒绝,请等服务器恢复后重试" };
|
|
712
|
+
let env;
|
|
713
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
|
|
714
|
+
try {
|
|
715
|
+
const cs = this.pluginClient();
|
|
716
|
+
env = cs?.llmEnvForPlugins() ?? { cwd: this.cwd, agentDir };
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
env = { cwd: this.cwd, agentDir };
|
|
720
|
+
}
|
|
721
|
+
const mod = await import("./plugin-llm.js");
|
|
722
|
+
const r = await mod.completeWithIsolatedSession(env, { ...req, prompt: String(req?.prompt ?? "") });
|
|
723
|
+
if (!r.ok)
|
|
724
|
+
return r;
|
|
725
|
+
console.log(`[plugin:${pluginId}] llm.complete ok(模型 ${r.model},输出 ${r.text.length} 字)`);
|
|
726
|
+
return r;
|
|
727
|
+
}
|
|
728
|
+
catch (err) {
|
|
729
|
+
return { ok: false, error: err.message };
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
/** index.ts calls this when a browser socket opens/closes. */
|
|
733
|
+
noteSocketOpen() {
|
|
734
|
+
this.socketCount += 1;
|
|
735
|
+
}
|
|
736
|
+
noteSocketClose() {
|
|
737
|
+
this.socketCount = Math.max(0, this.socketCount - 1);
|
|
738
|
+
}
|
|
739
|
+
/** Full status for the control socket / `server status` command. */
|
|
740
|
+
serviceStatus() {
|
|
741
|
+
return {
|
|
742
|
+
pid: process.pid,
|
|
743
|
+
version: VERSION,
|
|
744
|
+
cwd: this.cwd,
|
|
745
|
+
...this.quiesceInfo(),
|
|
746
|
+
connectedClients: this.socketCount,
|
|
747
|
+
activeConversations: this.activeConversations(),
|
|
748
|
+
pendingMessages: this.pendingMessages(),
|
|
749
|
+
service: toServiceInfo(launchOrigin()),
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
// (原 private static isPseudoClientId 已抽到模块级导出并挂为 static 属性)
|
|
753
|
+
/**
|
|
754
|
+
* 浏览器重启认领:给 fresh clientId 找一个可接管的断开残留会话(返回旧 id)。
|
|
755
|
+
* 有别的在线浏览器时返回 null(issue #10 隔离优先)。
|
|
756
|
+
* 全同步:attach 里的认领段不含 await,并发的新标签后到者看到 sinkCount>0,
|
|
757
|
+
* 不会抢走同一个残留。
|
|
758
|
+
*/
|
|
759
|
+
findAdoptableOrphan(excludeClientId) {
|
|
760
|
+
const cands = [];
|
|
761
|
+
for (const [id, cs] of this.clients) {
|
|
762
|
+
if (id === excludeClientId)
|
|
763
|
+
continue;
|
|
764
|
+
const pseudo = AgentService.isPseudoClientId(id);
|
|
765
|
+
let live = false;
|
|
766
|
+
let streaming = 0;
|
|
767
|
+
let adoptable = false;
|
|
768
|
+
let activity = 0;
|
|
769
|
+
try {
|
|
770
|
+
live = cs.sinkCount() > 0;
|
|
771
|
+
}
|
|
772
|
+
catch {
|
|
773
|
+
live = false;
|
|
774
|
+
}
|
|
775
|
+
if (!pseudo && !live) {
|
|
776
|
+
try {
|
|
777
|
+
streaming = cs.activeConversations();
|
|
778
|
+
}
|
|
779
|
+
catch {
|
|
780
|
+
streaming = 0;
|
|
781
|
+
}
|
|
782
|
+
try {
|
|
783
|
+
adoptable = cs.hasAdoptableContent();
|
|
784
|
+
}
|
|
785
|
+
catch {
|
|
786
|
+
adoptable = false;
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
activity = cs.latestActivity();
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
activity = 0;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
cands.push({ id, live, pseudo, streaming, adoptable, activity });
|
|
796
|
+
}
|
|
797
|
+
const picked = pickAdoptableOrphan(cands);
|
|
798
|
+
if (!picked)
|
|
799
|
+
return null;
|
|
800
|
+
const cs = this.clients.get(picked);
|
|
801
|
+
return cs ? { oldId: picked, cs } : null;
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表 / 跨端 steer)。
|
|
805
|
+
* attach 尾部与认领分支共用 —— 认领换了 map 键,必须在首帧推送(attachSink)
|
|
806
|
+
* 前就按新 id 重接,否则 self-exclusion 失效:把自己当成“另一处”(elsewhere
|
|
807
|
+
* 误报 + prompt/switch 自拦)。尾部会再调一次,幂等。
|
|
808
|
+
*/
|
|
809
|
+
wireClient(cs, clientId) {
|
|
810
|
+
cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
|
|
811
|
+
cs.takeOverConversationElsewhere = (ownerId, convId) => this.takeOverConversation(clientId, ownerId, convId);
|
|
812
|
+
cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
|
|
813
|
+
cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
|
|
814
|
+
cs.getClaimStore = () => this.claimStore;
|
|
815
|
+
cs.findConversationHome = (sdkSession) => this.findConversationHome(sdkSession);
|
|
816
|
+
cs.listExternalRunning = () => this.listExternalRunning(clientId);
|
|
817
|
+
cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
|
|
818
|
+
cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
|
|
819
|
+
cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
|
|
820
|
+
cs.schedulerStore = this.schedulerStore;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* 手动过户(take_over_conversation):把 owner 会话的某主对话(含子代理后代、
|
|
824
|
+
* 等答复问卷/页调用)整体搬到 target 会话并切过去。搬的是 runtime 本体不是
|
|
825
|
+
* 副本,单 writer 不变 —— 从在线标签页手里接管也是安全的;源会话修好 active
|
|
826
|
+
* 并推全量刷新,双方都收到去向通知。quiesce 排空期也放行(重连既有工作)。
|
|
827
|
+
*/
|
|
828
|
+
async takeOverConversation(targetId, ownerId, convId) {
|
|
829
|
+
const target = this.clients.get(targetId);
|
|
830
|
+
if (!target)
|
|
831
|
+
return;
|
|
832
|
+
const fail = (text, textEn) => {
|
|
833
|
+
target.sendNotice({ type: "notice", level: "warning", text, textEn });
|
|
834
|
+
};
|
|
835
|
+
if (!ownerId || !convId) {
|
|
836
|
+
fail("过户目标不明确(缺 owner/id),请重试", "Takeover target unclear (missing owner/id), please retry.");
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
if (ownerId === targetId) {
|
|
840
|
+
// 自己的对话 → 退化为普通切换。
|
|
841
|
+
try {
|
|
842
|
+
await target.switchConversation(convId);
|
|
843
|
+
}
|
|
844
|
+
catch {
|
|
845
|
+
/* switch 内部已用 notice 报错 */
|
|
846
|
+
}
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
if (AgentService.isPseudoClientId(ownerId)) {
|
|
850
|
+
fail("定时任务/插件会话不支持过户 —— 报告会自动落回绑定的对话,可在后台任务面板查看进度", "Scheduler/plugin sessions cannot be taken over — reports are saved to the bound conversation automatically; check progress in the Background Tasks panel.");
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
const source = this.clients.get(ownerId);
|
|
854
|
+
if (!source) {
|
|
855
|
+
fail("对方会话已不存在,可从历史对话里直接打开", "The source session is gone; reopen it from History instead.");
|
|
856
|
+
target.refreshExternalRunning();
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
const briefs = source.takeoverBriefs();
|
|
860
|
+
const main = briefs.find((b) => b.id === convId);
|
|
861
|
+
if (!main) {
|
|
862
|
+
fail("对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", "That conversation is gone on the other side; the list refreshes shortly.");
|
|
863
|
+
target.refreshExternalRunning();
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (main.isSubagent) {
|
|
867
|
+
fail("只能过户主对话(子代理随主对话一起搬)", "Only main conversations can be taken over (subagents move with their parent).");
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
const moveIds = [convId, ...collectSubagentDescendantIds(briefs, convId)];
|
|
871
|
+
const moveSet = new Set(moveIds);
|
|
872
|
+
// 容量:与 switchSession 同口径(目标项目非子代理且非临时会话 8 个)。
|
|
873
|
+
const movedMains = briefs.filter((b) => moveSet.has(b.id) && !b.isSubagent && !b.isEphemeral).length;
|
|
874
|
+
const openInProject = target.takeoverBriefs().filter((b) => b.cwd === main.cwd && !b.isSubagent && !b.isEphemeral).length + movedMains;
|
|
875
|
+
if (openInProject > MAX_OPEN_CONVERSATIONS) {
|
|
876
|
+
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; pinned chats must be unpinned first.`);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
try {
|
|
880
|
+
const detached = await source.detachTakeoverConversations(moveIds);
|
|
881
|
+
if (!detached.ok) {
|
|
882
|
+
fail(detached.reason === "empty"
|
|
883
|
+
? "对方会话只剩这一条对话且服务排空中,稍后再试"
|
|
884
|
+
: "对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", detached.reason === "empty"
|
|
885
|
+
? "The source session only has this conversation and the server is draining; try later."
|
|
886
|
+
: "That conversation is gone on the other side; the list refreshes shortly.");
|
|
887
|
+
if (detached.reason === "missing")
|
|
888
|
+
target.refreshExternalRunning();
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
// 测试专用故障注入(默认情况下一行不生效):让「接进目标」这一步必错,用来回归
|
|
892
|
+
// 「过户夭折不得变成幽灵」(tests/takeover-rollback-test.mjs)。
|
|
893
|
+
let newMainId;
|
|
894
|
+
try {
|
|
895
|
+
if (process.env.PI_WEB_TEST_TAKEOVER_FAIL_INSERT === "1")
|
|
896
|
+
throw new Error("injected takeover insert failure");
|
|
897
|
+
newMainId = target.insertTakeoverConvs(detached.payload);
|
|
898
|
+
await target.switchConversation(newMainId);
|
|
899
|
+
await target.bindSession();
|
|
900
|
+
}
|
|
901
|
+
catch (err) {
|
|
902
|
+
// 夭折回滚:对话已经从源会话摘下来了(源侧 map 已删、订阅已断),接进目标或切换失败就是
|
|
903
|
+
// 「还在跑但谁的列表里都没有」的幽灵 —— 只有重启服务才能靠落盘恢复(issue #556)。
|
|
904
|
+
// 原样搬回源会话,两边都拿到诚实的回执。
|
|
905
|
+
const where = await this.returnTakeoverPayload(source, target, detached.payload);
|
|
906
|
+
console.error("[takeover] insert/activate failed, payload returned to", where, err);
|
|
907
|
+
if (where === "source") {
|
|
908
|
+
// 源页面也得知道发生了什么:它的对话刚才静默地从列表里消失过一瞬间。
|
|
909
|
+
source.sendNotice({
|
|
910
|
+
type: "notice",
|
|
911
|
+
level: "info",
|
|
912
|
+
text: `对方的过户未完成,「${main.title}」已退回本页,可直接继续。`,
|
|
913
|
+
textEn: `The takeover did not complete on the other side — "${main.title}" is back on this page.`,
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
fail(where === "source"
|
|
917
|
+
? `过户失败(${err.message})——对话已退回原页面,可直接重试`
|
|
918
|
+
: `过户失败(${err.message})——对话留在本页运行列表里,刷新即可继续`, where === "source"
|
|
919
|
+
? `Takeover failed (${err.message}) — the conversation is back on the source page; retry there.`
|
|
920
|
+
: `Takeover failed (${err.message}) — the conversation is kept in this page's running list; refresh to pick it up.`);
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
// 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
|
|
924
|
+
// 无 sink 时 emit 即丢,无需判断。
|
|
925
|
+
source.sendNotice({
|
|
926
|
+
type: "notice",
|
|
927
|
+
level: "info",
|
|
928
|
+
text: `「${main.title}」已过户到另一处接管,本页不再持有它。`,
|
|
929
|
+
textEn: `"${main.title}" was taken over by another page and is no longer held here.`,
|
|
930
|
+
});
|
|
931
|
+
target.sendNotice({
|
|
932
|
+
type: "notice",
|
|
933
|
+
level: "info",
|
|
934
|
+
text: `已将「${main.title}」过户到当前页面,可直接继续查看与操作。`,
|
|
935
|
+
textEn: `"${main.title}" was moved to this page — pick up right where it left off.`,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
catch (err) {
|
|
939
|
+
fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* 过户夭折回滚:把已经摘下来的对话搬回源会话(及其运行列表)。
|
|
944
|
+
*
|
|
945
|
+
* 为什么要它:detach 与 insert 之间是唯一的空档期 —— 源侧已经删了 map、断了订阅,
|
|
946
|
+
* 一旦 insert 报错,对话就两头不挂,但 runtime 还在跑(“幽灵会话”,只有重启服务
|
|
947
|
+
* 才能靠落盘会话恢复,issue #556)。这里用同一套 insert 接线原样搬回去。
|
|
948
|
+
*
|
|
949
|
+
* 搬不回去(二次失败,理论上不该发生)时把它们**留在目标会话**:宁可留在新页面
|
|
950
|
+
* 的运行列表里(insert 已给主对话置 listed),也绝不落到“没人持有”的空档。
|
|
951
|
+
* 返回最终归属方,调用方据此给用户出对应文案。
|
|
952
|
+
*/
|
|
953
|
+
async returnTakeoverPayload(source, target, payload) {
|
|
954
|
+
// 先摘掉已部分插进目标的残留(不 dispose:runtime 要原样搬)。
|
|
955
|
+
target.reclaimTakeoverConvs(payload);
|
|
956
|
+
try {
|
|
957
|
+
const mainId = source.insertTakeoverConvs(payload);
|
|
958
|
+
await source.switchConversation(mainId);
|
|
959
|
+
await source.bindSession();
|
|
960
|
+
return "source";
|
|
961
|
+
}
|
|
962
|
+
catch (err) {
|
|
963
|
+
console.error("[takeover] rollback to source failed:", err);
|
|
964
|
+
try {
|
|
965
|
+
target.insertTakeoverConvs(payload);
|
|
966
|
+
}
|
|
967
|
+
catch {
|
|
968
|
+
/* 双失败:对象还在 payload 里,不要再次搬运 —— 不抛,不让 handler 崩 */
|
|
969
|
+
}
|
|
970
|
+
return "target";
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
|
|
975
|
+
* 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
|
|
976
|
+
*/
|
|
977
|
+
async peekElsewhereQuestion(targetId, ownerId, convId) {
|
|
978
|
+
const target = this.clients.get(targetId);
|
|
979
|
+
if (!target)
|
|
980
|
+
return;
|
|
981
|
+
const fail = (text, textEn) => {
|
|
982
|
+
target.sendNotice({ type: "notice", level: "warning", text, textEn });
|
|
983
|
+
};
|
|
984
|
+
if (!ownerId || !convId) {
|
|
985
|
+
fail("问卷目标不明确(缺 owner/id),请重试", "Question target unclear (missing owner/id), please retry.");
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
if (ownerId === targetId)
|
|
989
|
+
return; // 自己的问卷走本地通道,不需要预告
|
|
990
|
+
if (AgentService.isPseudoClientId(ownerId)) {
|
|
991
|
+
fail("定时任务/插件会话的问卷不支持跨页作答 —— 报告会自动落回绑定的对话,可在后台任务面板查看进度", "Scheduler/plugin session questions cannot be answered cross-page — reports are saved to the bound conversation automatically; check progress in the Background Tasks panel.");
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
const source = this.clients.get(ownerId);
|
|
995
|
+
const q = source?.peekPendingQuestion(convId);
|
|
996
|
+
if (!q) {
|
|
997
|
+
fail("那张问卷已不在(对方刚回答/取消或对话已结束)", "That question is gone (just answered/cancelled there, or the run ended).");
|
|
998
|
+
target.refreshExternalRunning();
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
target.pushElsewhereQuestion(ownerId, convId, q);
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
|
|
1005
|
+
* 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
|
|
1006
|
+
*/
|
|
1007
|
+
async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
|
|
1008
|
+
const target = this.clients.get(targetId);
|
|
1009
|
+
if (!target)
|
|
1010
|
+
return;
|
|
1011
|
+
const source = this.clients.get(ownerId);
|
|
1012
|
+
const ok = source ? source.resolveQuestion(id, answers, cancelled, cancelReason) : false;
|
|
1013
|
+
if (!ok) {
|
|
1014
|
+
target.sendNotice({
|
|
1015
|
+
type: "notice",
|
|
1016
|
+
level: "warning",
|
|
1017
|
+
text: "那张问卷已不在(对方刚回答/取消或对话已结束),你的回答没有送出",
|
|
1018
|
+
textEn: "That question is gone (just answered/cancelled there, or the run ended) — your answer was not delivered.",
|
|
1019
|
+
});
|
|
1020
|
+
target.refreshExternalRunning();
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
/** Get or create the session for a client, racing attach calls safely. */
|
|
1024
|
+
async attach(clientId, send) {
|
|
1025
|
+
let cs = this.clients.get(clientId);
|
|
1026
|
+
if (!cs) {
|
|
1027
|
+
const inflight = this.pending.get(clientId);
|
|
1028
|
+
if (inflight) {
|
|
1029
|
+
cs = await inflight;
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
// 浏览器重启认领(clientId 存 sessionStorage,关浏览器即失;服务端残留
|
|
1033
|
+
// ClientSession 的运行中对话否则永远卡在“另一处”只读,连看都看不了):
|
|
1034
|
+
// 无其他在线浏览器时,把最近断开的残留会话整体过户给这个新 id
|
|
1035
|
+
// (只换 map 键,不搬 runtime:对话/终端/订阅/cwd 原样保留,
|
|
1036
|
+
// 流式增量经尾部 attachSink 直接推给新 socket)。
|
|
1037
|
+
// 有其他在线标签时不认领(issue #10 隔离优先);quiesce 排空期也放行
|
|
1038
|
+
// (这是重连既有工作,不是新工作)。本段无 await,并发 attach 原子。
|
|
1039
|
+
// 伪客户端(scheduler:/plugin:,定时任务/插件的无头调用)绝不认领:
|
|
1040
|
+
// 否则无头会话会改键劫持用户关浏览器留下的残会话。
|
|
1041
|
+
const orphan = AgentService.isPseudoClientId(clientId) ? null : this.findAdoptableOrphan(clientId);
|
|
1042
|
+
if (orphan) {
|
|
1043
|
+
this.clients.delete(orphan.oldId);
|
|
1044
|
+
// 残骸被本页认领:它的离线行状态随 id 作废(行归到新 id 名下)。
|
|
1045
|
+
this.clearOfflineRows(orphan.oldId);
|
|
1046
|
+
this.clients.set(clientId, orphan.cs);
|
|
1047
|
+
cs = orphan.cs;
|
|
1048
|
+
// 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
|
|
1049
|
+
this.wireClient(cs, clientId);
|
|
1050
|
+
cs.noteAdopted();
|
|
1051
|
+
// 服务重启前记在旧 id 名下的中断记录搬到新 id 名下,尾部
|
|
1052
|
+
// resumeInterrupted 按新 id 消费(只认领一次,不重复恢复)。
|
|
1053
|
+
const inter = this.stateStore.takeInterrupted(orphan.oldId);
|
|
1054
|
+
if (inter?.length)
|
|
1055
|
+
this.stateStore.saveInterrupted(clientId, inter);
|
|
1056
|
+
}
|
|
1057
|
+
else {
|
|
1058
|
+
// Restore this client's last-used workspace when it still exists;
|
|
1059
|
+
// Admission gate: while quiesced, only clients with an EXISTING
|
|
1060
|
+
// session may attach (they can watch their runs drain); brand-new
|
|
1061
|
+
// clients are refused — index.ts closes their socket (4403) and the
|
|
1062
|
+
// browser reconnect loop retries after admission reopens.
|
|
1063
|
+
if (this.quiesced) {
|
|
1064
|
+
throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
|
|
1065
|
+
}
|
|
1066
|
+
// otherwise fall back to the server's configured default cwd.
|
|
1067
|
+
let cwd = this.cwd;
|
|
1068
|
+
const saved = this.stateStore.get(clientId);
|
|
1069
|
+
if (saved.lastCwd && saved.lastCwd !== this.cwd) {
|
|
1070
|
+
try {
|
|
1071
|
+
// issue #295:异步 stat —— 同步 stat 落在坏挂载(已卸载的外部卷/
|
|
1072
|
+
// autofs 触发点)上会在内核里挂起,冻住整个事件循环(含控制
|
|
1073
|
+
// socket 与其他客户端的心跳);异步版本只挡本连接,超时提示照发。
|
|
1074
|
+
const { stat } = await import("node:fs/promises");
|
|
1075
|
+
if ((await stat(saved.lastCwd)).isDirectory())
|
|
1076
|
+
cwd = saved.lastCwd;
|
|
1077
|
+
}
|
|
1078
|
+
catch {
|
|
1079
|
+
// gone (unmounted drive / deleted / hanging mount) — fall back to the default
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// Sessions use the SDK default per-project dir — no per-client dir.
|
|
1083
|
+
// issue #145:新标签页默认恢复项目最近的会话 —— 若那条仍被别处持有
|
|
1084
|
+
// (跑着或空闲),建之前就决定空白(第二个 writer 根本不会被打开,
|
|
1085
|
+
// 也无需事后拆 runtime)。之前只拦 running:空闲持有照样恢复出双
|
|
1086
|
+
// writer,两边轮流发送分叉历史。其他客户端不存在时不扫目录。
|
|
1087
|
+
let createOpts;
|
|
1088
|
+
if (this.clients.size > 0) {
|
|
1089
|
+
try {
|
|
1090
|
+
const infos = await SessionManager.list(cwd, piSessionsRoot());
|
|
1091
|
+
const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
|
|
1092
|
+
const owner = recent ? this.findSessionOwner(recent, clientId) : null;
|
|
1093
|
+
if (owner) {
|
|
1094
|
+
createOpts = { blank: true, blankTitle: owner.title, ...(owner.isStreaming ? {} : { idleHeld: true }) };
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
catch {
|
|
1098
|
+
// 列表失败不挡正常恢复
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
const creating = ClientSession.create(clientId, cwd, this.stateStore, createOpts).finally(() => {
|
|
1102
|
+
this.pending.delete(clientId);
|
|
1103
|
+
});
|
|
1104
|
+
this.pending.set(clientId, creating);
|
|
1105
|
+
cs = await creating;
|
|
1106
|
+
this.clients.set(clientId, cs);
|
|
1107
|
+
// issue #145 接线提前:首帧 elsewhere 依赖它。
|
|
1108
|
+
this.wireClient(cs, clientId);
|
|
1109
|
+
// Make sure the restored/default workspace appears in the project list.
|
|
1110
|
+
this.stateStore.remember(clientId, cwd);
|
|
1111
|
+
if (cwd !== this.cwd) {
|
|
1112
|
+
send({
|
|
1113
|
+
type: "notice",
|
|
1114
|
+
level: "info",
|
|
1115
|
+
text: `已恢复上次的工作目录:${cwd}`,
|
|
1116
|
+
textEn: `Restored the last working directory: ${cwd}`,
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
// First attach after a restart: reopen sessions that were streaming
|
|
1123
|
+
// when the previous process shut down and continue them (consumed
|
|
1124
|
+
// once, then cleared). Fire-and-forget AFTER attachSink + hooks:
|
|
1125
|
+
// resume emits directly to sinks and needs the owner guards.
|
|
1126
|
+
// Progress arrives over the socket as usual.
|
|
1127
|
+
const detachedSinks = this.pendingDetaches.get(clientId);
|
|
1128
|
+
if (detachedSinks?.has(send)) {
|
|
1129
|
+
detachedSinks.delete(send);
|
|
1130
|
+
if (detachedSinks.size === 0)
|
|
1131
|
+
this.pendingDetaches.delete(clientId);
|
|
1132
|
+
}
|
|
1133
|
+
else {
|
|
1134
|
+
cs.attachSink(send);
|
|
1135
|
+
// 又有浏览器连上:离线行状态作废(别的页面按在线行重推,去掉离线标记)。
|
|
1136
|
+
this.clearOfflineRows(clientId);
|
|
1137
|
+
}
|
|
1138
|
+
// Forward hooks (set once by index.ts) to every session.
|
|
1139
|
+
cs.onQuit = this.onQuit;
|
|
1140
|
+
cs.onToolEvent = this.onToolEvent;
|
|
1141
|
+
cs.toolGuard = this.toolGuard;
|
|
1142
|
+
cs.onRunEvent = this.onRunEvent;
|
|
1143
|
+
cs.onConversationChanged = () => this.onConversationChanged?.();
|
|
1144
|
+
cs.onClientModelChanged = (snap) => this.onClientModelChanged?.(snap);
|
|
1145
|
+
cs.pluginToolsProvider = this.pluginToolsProvider;
|
|
1146
|
+
cs.pluginCommandsProvider = this.pluginCommandsProvider;
|
|
1147
|
+
cs.pluginBgTasksProvider = this.pluginBgTasksProvider;
|
|
1148
|
+
cs.pluginStopBgTask = this.pluginStopBgTask;
|
|
1149
|
+
cs.isQuiesced = () => this.quiesced;
|
|
1150
|
+
// issue #145 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表)。
|
|
1151
|
+
this.wireClient(cs, clientId);
|
|
1152
|
+
// 插件宿主工作区跟随:初次接入也同步一次(恢复的 lastCwd 可能≠服务启动目录),
|
|
1153
|
+
// notifyCwd 幂等去重;此后 set_cwd 成功时由 cs.onCwdChanged 继续驱动。
|
|
1154
|
+
cs.onCwdChanged = (abs, roots) => this.onClientCwdChanged?.(abs, roots);
|
|
1155
|
+
this.onClientCwdChanged?.(cs.cwd, cs.workspaceRoots);
|
|
1156
|
+
void cs.resumeInterrupted(this.stateStore.takeInterrupted(clientId));
|
|
1157
|
+
return cs;
|
|
1158
|
+
}
|
|
1159
|
+
/** 插件 AI 工具集合变化(注册/注销)时由 index.ts 触发:推送到所有客户端的全部会话。 */
|
|
1160
|
+
applyPluginAgentTools() {
|
|
1161
|
+
for (const cs of this.clients.values())
|
|
1162
|
+
cs.refreshPluginTools();
|
|
1163
|
+
}
|
|
1164
|
+
/** Browser UI locale report (hello.locale / set_locale): persist per client
|
|
1165
|
+
* and refresh lang-aware prompts (streaming-safe via ClientSession). */
|
|
1166
|
+
async setLocale(clientId, locale) {
|
|
1167
|
+
const cs = this.clients.get(clientId);
|
|
1168
|
+
if (cs) {
|
|
1169
|
+
await cs.setLocale(locale);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
// hello race: session still being created — wait for it, then apply.
|
|
1173
|
+
const inflight = this.pending.get(clientId);
|
|
1174
|
+
if (inflight) {
|
|
1175
|
+
try {
|
|
1176
|
+
await (await inflight).setLocale(locale);
|
|
1177
|
+
}
|
|
1178
|
+
catch {
|
|
1179
|
+
/* attach failed — nothing to apply to */
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
/** 插件斜杠命令集合变化时由 index.ts 触发:重推各客户端的命令目录。 */
|
|
1184
|
+
applyPluginCommandCatalog() {
|
|
1185
|
+
for (const cs of this.clients.values())
|
|
1186
|
+
void cs.pushSlashCommands();
|
|
1187
|
+
}
|
|
1188
|
+
/** 插件常驻后台任务变化时由 index.ts 触发:重推各客户端的 bg_servers。 */
|
|
1189
|
+
refreshBackgroundServers() {
|
|
1190
|
+
for (const cs of this.clients.values())
|
|
1191
|
+
cs.refreshBgTasks();
|
|
1192
|
+
}
|
|
1193
|
+
/** Remove a socket from a client's broadcast set (called on socket close). */
|
|
1194
|
+
detach(clientId, send) {
|
|
1195
|
+
const cs = this.clients.get(clientId);
|
|
1196
|
+
if (cs) {
|
|
1197
|
+
cs.detachSink(send);
|
|
1198
|
+
// 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
|
|
1199
|
+
// (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
|
|
1200
|
+
// (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
|
|
1201
|
+
// 「残骸不永久占位」仍然成立)。
|
|
1202
|
+
if (!AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
|
|
1203
|
+
this.offlineSince.set(clientId, Date.now());
|
|
1204
|
+
this.pokeExternalRunning(clientId);
|
|
1205
|
+
this.armOfflineRowExpiry(clientId, cs);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
else if (this.pending.has(clientId)) {
|
|
1209
|
+
// 连接在 attach 异步创建期间断开:记录待 detach 的 sink,attach 完成后清理,避免死连接泄漏
|
|
1210
|
+
let set = this.pendingDetaches.get(clientId);
|
|
1211
|
+
if (!set) {
|
|
1212
|
+
set = new Set();
|
|
1213
|
+
this.pendingDetaches.set(clientId, set);
|
|
1214
|
+
}
|
|
1215
|
+
set.add(send);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
get(clientId) {
|
|
1219
|
+
return this.clients.get(clientId);
|
|
1220
|
+
}
|
|
1221
|
+
/** 插件扩展点 v2:挑一个最合适的客户端会话供无浏览器调用的插件 API 用
|
|
1222
|
+
* (conversationLister/Searcher/Writer、modelLister、runAborter)。
|
|
1223
|
+
* 有运行中对话的优先,否则任意残留客户端;一个没有时返回 undefined,
|
|
1224
|
+
* 调用方(index.ts 注入)回退空列表 / {ok:false},绝不抛错。 */
|
|
1225
|
+
pluginClient() {
|
|
1226
|
+
let fallback;
|
|
1227
|
+
for (const cs of this.clients.values()) {
|
|
1228
|
+
if (!fallback)
|
|
1229
|
+
fallback = cs;
|
|
1230
|
+
try {
|
|
1231
|
+
if (cs.activeConversations() > 0)
|
|
1232
|
+
return cs;
|
|
1233
|
+
}
|
|
1234
|
+
catch {
|
|
1235
|
+
// 单客户端坏了不影响挑选
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
return fallback;
|
|
1239
|
+
}
|
|
1240
|
+
/** Snapshot still-streaming conversations for post-restart resume.
|
|
1241
|
+
* Called during graceful shutdown AND from the restart_service handler
|
|
1242
|
+
* (which exits without shutdown under systemd — without this, the
|
|
1243
|
+
* interrupted-run record would silently never be written there). */
|
|
1244
|
+
recordInterruptedRuns() {
|
|
1245
|
+
// Record still-streaming conversations BEFORE tearing anything down, so
|
|
1246
|
+
// the next attach can tell the user what was lost (SIGTERM / update).
|
|
1247
|
+
// eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
|
|
1248
|
+
for (const [clientId, cs] of [...this.clients]) {
|
|
1249
|
+
try {
|
|
1250
|
+
const running = cs.streamingSummaries();
|
|
1251
|
+
if (running.length > 0) {
|
|
1252
|
+
this.stateStore.saveInterrupted(clientId, running.map((r) => ({ ...r, at: Date.now() })));
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
catch {
|
|
1256
|
+
// best effort — never block shutdown on bookkeeping
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
async disposeAll() {
|
|
1261
|
+
this.recordInterruptedRuns();
|
|
1262
|
+
const all = [...this.clients.values()];
|
|
1263
|
+
this.clients.clear();
|
|
1264
|
+
await Promise.all(all.map((cs) => cs.dispose()));
|
|
1265
|
+
}
|
|
1266
|
+
}
|