pi-wechat-session-hub 0.1.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/LICENSE +661 -0
- package/README.md +365 -0
- package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
- package/docs/handoff-next-session.md +134 -0
- package/docs/implementation-spec.md +147 -0
- package/extensions/wechat-session-hub.ts +589 -0
- package/package.json +67 -0
- package/scripts/pi-rpc-smoke.mjs +150 -0
- package/scripts/probe-wt-capability.mjs +27 -0
- package/scripts/start-ui-worker.ps1 +37 -0
- package/src/commands/ilink-qr-login-component.ts +148 -0
- package/src/commands/project-command-parser.ts +108 -0
- package/src/commands/tokenizer.ts +71 -0
- package/src/commands/wechat-manager-command-parser.ts +143 -0
- package/src/config/defaults.ts +30 -0
- package/src/config/paths.ts +56 -0
- package/src/config/store.ts +311 -0
- package/src/config/types.ts +33 -0
- package/src/config/validation.ts +221 -0
- package/src/gateway/channel-types.ts +47 -0
- package/src/gateway/command-parser.ts +291 -0
- package/src/gateway/command-router.ts +1449 -0
- package/src/gateway/credential-store.ts +611 -0
- package/src/gateway/durable-message-queue.ts +1043 -0
- package/src/gateway/gateway-control-ipc.ts +687 -0
- package/src/gateway/gateway-runtime.ts +726 -0
- package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
- package/src/gateway/ui-worker-ipc.ts +1483 -0
- package/src/gateway/ui-worker-types.ts +50 -0
- package/src/gateway/wechat-ilink/api-client.ts +390 -0
- package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
- package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
- package/src/gateway/wechat-ilink/qr-login.ts +612 -0
- package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
- package/src/gateway/windows-terminal-launcher.ts +247 -0
- package/src/projects/project-service.ts +483 -0
- package/src/registry/gateway-lease.ts +348 -0
- package/src/registry/manager-registry.ts +466 -0
- package/src/registry/types.ts +61 -0
- package/src/runtime/background-pi-worker.ts +309 -0
- package/src/runtime/background-worker-manager.ts +594 -0
- package/src/runtime/gateway-daemon.ts +281 -0
- package/src/runtime/gateway-lifecycle-operation.ts +308 -0
- package/src/runtime/gateway-service-controller.ts +339 -0
- package/src/runtime/gateway-worker-manager.ts +181 -0
- package/src/runtime/pi-cli.ts +56 -0
- package/src/runtime/pi-rpc-client.ts +427 -0
- package/src/runtime/ui-worker-manager.ts +1186 -0
- package/src/runtime/windows-logon-task-manager.ts +212 -0
- package/src/system/process-liveness.ts +88 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,1186 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { ProjectService, ProjectServiceError } from "../projects/project-service.ts";
|
|
5
|
+
import type { ProjectDefinition } from "../config/types.ts";
|
|
6
|
+
import { ManagerRegistry } from "../registry/manager-registry.ts";
|
|
7
|
+
import type { SessionIndexRecord, WorkerInstanceRecord, WorkerState } from "../registry/types.ts";
|
|
8
|
+
import {
|
|
9
|
+
parseUiWorkerRegistration,
|
|
10
|
+
UiWorkerIpcError,
|
|
11
|
+
UiWorkerIpcServer,
|
|
12
|
+
type UiWorkerIpcConnection,
|
|
13
|
+
} from "../gateway/ui-worker-ipc.ts";
|
|
14
|
+
import { isProcessAlive } from "../system/process-liveness.ts";
|
|
15
|
+
import type { UiWorkerLaunchRecord, UiWorkerRegistration } from "../gateway/ui-worker-types.ts";
|
|
16
|
+
import type { PiCliInvocation } from "./pi-cli.ts";
|
|
17
|
+
import type { BackgroundWorkerManager } from "./background-worker-manager.ts";
|
|
18
|
+
import { WindowsTerminalLaunchError, WindowsTerminalLauncher, probeWindowsTerminalCapability, type WindowsTerminalCapability } from "../gateway/windows-terminal-launcher.ts";
|
|
19
|
+
|
|
20
|
+
export type UiWorkerManagerErrorCode =
|
|
21
|
+
| "unsupported_platform"
|
|
22
|
+
| "wt_not_found"
|
|
23
|
+
| "session_not_found"
|
|
24
|
+
| "session_owned_by_other_process"
|
|
25
|
+
| "worker_not_found"
|
|
26
|
+
| "worker_busy"
|
|
27
|
+
| "worker_launch_failed"
|
|
28
|
+
| "worker_registration_timeout"
|
|
29
|
+
| "worker_shutdown_timeout"
|
|
30
|
+
| "registry_inconsistent";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 表示可见 Pi UI worker 无法安全启动、路由或关闭。
|
|
34
|
+
*/
|
|
35
|
+
export class UiWorkerManagerError extends Error {
|
|
36
|
+
/**
|
|
37
|
+
* 创建可安全向 Gateway 用户显示的 UI worker 错误。
|
|
38
|
+
*
|
|
39
|
+
* @param code 稳定错误代码。
|
|
40
|
+
* @param message 不包含凭证、正文或完整 launch ticket 的中文说明。
|
|
41
|
+
*/
|
|
42
|
+
constructor(
|
|
43
|
+
readonly code: UiWorkerManagerErrorCode,
|
|
44
|
+
message: string,
|
|
45
|
+
) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "UiWorkerManagerError";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 管理通过 Windows Terminal 启动的真实 Pi TUI worker。
|
|
53
|
+
*/
|
|
54
|
+
export class UiWorkerManager {
|
|
55
|
+
private readonly connections = new Map<string, UiWorkerIpcConnection>();
|
|
56
|
+
private readonly disconnectWaiters = new Map<string, Set<() => void>>();
|
|
57
|
+
private readonly staleTimers = new Map<string, NodeJS.Timeout>();
|
|
58
|
+
private readonly explicitStops = new Set<string>();
|
|
59
|
+
private readonly maxStaleMs: number;
|
|
60
|
+
private capabilityTask?: Promise<WindowsTerminalCapability>;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 创建 UI worker manager 并安装 IPC lifecycle handlers。
|
|
64
|
+
*
|
|
65
|
+
* @param options Windows Terminal、Pi CLI、项目服务和 registry 依赖。
|
|
66
|
+
*/
|
|
67
|
+
constructor(private readonly options: {
|
|
68
|
+
managerDirectory: string;
|
|
69
|
+
projectService: ProjectService;
|
|
70
|
+
registry: ManagerRegistry;
|
|
71
|
+
ipcServer: UiWorkerIpcServer;
|
|
72
|
+
launcher?: Pick<WindowsTerminalLauncher, "launch">;
|
|
73
|
+
probeCapability?: () => Promise<WindowsTerminalCapability>;
|
|
74
|
+
invocation: PiCliInvocation;
|
|
75
|
+
extensionPath: string;
|
|
76
|
+
backgroundWorkerManager?: BackgroundWorkerManager;
|
|
77
|
+
staleAfterMs?: number;
|
|
78
|
+
registrationTimeoutMs?: number;
|
|
79
|
+
shutdownTimeoutMs?: number;
|
|
80
|
+
platform?: NodeJS.Platform;
|
|
81
|
+
}) {
|
|
82
|
+
this.maxStaleMs = options.staleAfterMs ?? 20000;
|
|
83
|
+
options.ipcServer.setHandlers({
|
|
84
|
+
onRegister: (registration, authHash, launchRecord, connection) =>
|
|
85
|
+
this.registerWorker(registration, authHash, launchRecord, connection),
|
|
86
|
+
onWorkerEvent: (connection, name, data) => this.handleWorkerEvent(connection, name, data),
|
|
87
|
+
onRequest: (connection, method, params) => this.handleWorkerRequest(connection, method, params),
|
|
88
|
+
onDisconnect: (connection, serverStopping) => this.handleDisconnect(connection, serverStopping),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 判断当前部署是否支持创建或恢复可见 Pi TUI。
|
|
94
|
+
*
|
|
95
|
+
* @returns Windows 或测试注入平台为 win32 时返回 true。
|
|
96
|
+
*/
|
|
97
|
+
get isSupported(): boolean {
|
|
98
|
+
return (this.options.platform ?? process.platform) === "win32";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 为本机 Windows TUI workers 打开稳定 IPC endpoint。
|
|
103
|
+
*
|
|
104
|
+
* @returns pipe server 开始监听后正常结束。
|
|
105
|
+
*/
|
|
106
|
+
async listen(): Promise<void> {
|
|
107
|
+
if (this.isSupported) {
|
|
108
|
+
await this.options.ipcServer.listen();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 在已登记项目中启动一个新的 Pi 原生 UI session。
|
|
114
|
+
*
|
|
115
|
+
* @param projectAlias 配置中的项目 alias。
|
|
116
|
+
* @param name 可选 session display name。
|
|
117
|
+
* @returns Pi extension 完成 launch handshake 后的 session 记录。
|
|
118
|
+
* @throws {UiWorkerManagerError} Windows Terminal 不可用或 Pi worker 未注册时抛出。
|
|
119
|
+
*/
|
|
120
|
+
async startNew(projectAlias: string, name?: string): Promise<SessionIndexRecord> {
|
|
121
|
+
await this.assertUiModeAvailable();
|
|
122
|
+
const project = await this.resolveProject(projectAlias);
|
|
123
|
+
const launch = this.createLaunchRecord({
|
|
124
|
+
mode: "new",
|
|
125
|
+
projectAlias,
|
|
126
|
+
projectPath: project.path,
|
|
127
|
+
...(name ? { sessionName: name } : {}),
|
|
128
|
+
});
|
|
129
|
+
return this.launchAndWait(launch);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 在新 Windows Terminal tab 中恢复已保存的 UI session。
|
|
134
|
+
*
|
|
135
|
+
* @param sessionId Pi session ID。
|
|
136
|
+
* @returns 已重新注册的 session 记录。
|
|
137
|
+
* @throws {UiWorkerManagerError} session 无法安全恢复或 owner 仍活跃时抛出。
|
|
138
|
+
*/
|
|
139
|
+
async resume(sessionId: string): Promise<SessionIndexRecord> {
|
|
140
|
+
await this.assertUiModeAvailable();
|
|
141
|
+
let snapshot = await this.options.registry.readSnapshot();
|
|
142
|
+
let session = snapshot.sessions[sessionId];
|
|
143
|
+
if (!session) {
|
|
144
|
+
throw new UiWorkerManagerError("session_not_found", `未找到 session: ${sessionId}。`);
|
|
145
|
+
}
|
|
146
|
+
const priorOwner = Object.values(snapshot.instances).find((instance) => instance.sessionId === sessionId);
|
|
147
|
+
if (priorOwner && priorOwner.state !== "stale" && priorOwner.state !== "stopping") {
|
|
148
|
+
if (priorOwner.mode === "ui" && this.connections.has(priorOwner.instanceId)) {
|
|
149
|
+
return session;
|
|
150
|
+
}
|
|
151
|
+
throw new UiWorkerManagerError(
|
|
152
|
+
"session_owned_by_other_process",
|
|
153
|
+
`session ${sessionId} 仍由 ${priorOwner.mode} owner PID ${priorOwner.pid} 持有; 拒绝双 writer。`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (priorOwner) {
|
|
157
|
+
if (isProcessAlive(priorOwner.pid)) {
|
|
158
|
+
throw new UiWorkerManagerError(
|
|
159
|
+
"session_owned_by_other_process",
|
|
160
|
+
`session ${sessionId} 的旧 UI owner PID ${priorOwner.pid} 仍存活但 IPC 不可用; 拒绝双开。`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
await this.markStopped(priorOwner.instanceId);
|
|
164
|
+
snapshot = await this.options.registry.readSnapshot();
|
|
165
|
+
session = snapshot.sessions[sessionId];
|
|
166
|
+
if (!session) {
|
|
167
|
+
throw new UiWorkerManagerError("session_not_found", `未找到 session: ${sessionId}。`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (session.state === "active") {
|
|
171
|
+
session = {
|
|
172
|
+
...session,
|
|
173
|
+
state: await isPersistedSessionFile(session.sessionFile) ? "saved" : "pending",
|
|
174
|
+
};
|
|
175
|
+
await this.options.registry.upsertSession(session);
|
|
176
|
+
}
|
|
177
|
+
if (!(await isPersistedSessionFile(session.sessionFile))) {
|
|
178
|
+
throw new UiWorkerManagerError(
|
|
179
|
+
"session_not_found",
|
|
180
|
+
`session ${sessionId} 尚无可恢复的 Pi transcript 文件。`,
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
if (session.state !== "saved") {
|
|
184
|
+
session = { ...session, state: "saved" };
|
|
185
|
+
await this.options.registry.upsertSession(session);
|
|
186
|
+
}
|
|
187
|
+
let project;
|
|
188
|
+
try {
|
|
189
|
+
project = await this.options.projectService.resolveSession(session.projectAlias, session.cwd);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error instanceof ProjectServiceError) {
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
throw new UiWorkerManagerError("session_not_found", "恢复 session 的项目路径验证失败。 ");
|
|
195
|
+
}
|
|
196
|
+
const launch = this.createLaunchRecord({
|
|
197
|
+
mode: "resume",
|
|
198
|
+
projectAlias: session.projectAlias,
|
|
199
|
+
projectPath: project.path,
|
|
200
|
+
sessionId,
|
|
201
|
+
sessionFile: session.sessionFile,
|
|
202
|
+
...(session.name ? { sessionName: session.name } : {}),
|
|
203
|
+
});
|
|
204
|
+
await this.launchAndWait(launch);
|
|
205
|
+
const resumed = (await this.options.registry.readSnapshot()).sessions[sessionId];
|
|
206
|
+
if (!resumed) {
|
|
207
|
+
throw new UiWorkerManagerError("registry_inconsistent", "Pi UI worker 已启动, 但 session registry 未更新。 ");
|
|
208
|
+
}
|
|
209
|
+
return resumed;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 向当前已认证的 UI worker 注入真实用户消息并等待 Pi agent_settled。
|
|
214
|
+
*
|
|
215
|
+
* @param sessionId Pi session ID。
|
|
216
|
+
* @param message 用户消息正文。
|
|
217
|
+
* @returns UI Pi agent 最终 assistant 文本。
|
|
218
|
+
* @throws {UiWorkerManagerError} worker 断连、忙碌或回复结构无效时抛出。
|
|
219
|
+
*/
|
|
220
|
+
async prompt(sessionId: string, message: string): Promise<string> {
|
|
221
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
222
|
+
const instance = Object.values(snapshot.instances).find((candidate) =>
|
|
223
|
+
candidate.sessionId === sessionId && candidate.mode === "ui" &&
|
|
224
|
+
candidate.state !== "stale" && candidate.state !== "stopping",
|
|
225
|
+
);
|
|
226
|
+
if (!instance) {
|
|
227
|
+
throw new UiWorkerManagerError("worker_not_found", `session ${sessionId} 没有活跃 UI worker。`);
|
|
228
|
+
}
|
|
229
|
+
const connection = this.connections.get(instance.instanceId);
|
|
230
|
+
if (!connection) {
|
|
231
|
+
throw new UiWorkerManagerError("worker_not_found", "UI worker 尚未连接到 Gateway; 不会改用 background writer。 ");
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const response = await connection.request("prompt", { message });
|
|
235
|
+
if (!isRecord(response) || typeof response.reply !== "string") {
|
|
236
|
+
throw new UiWorkerManagerError("registry_inconsistent", "UI worker 没有返回有效的最终 assistant 文本。 ");
|
|
237
|
+
}
|
|
238
|
+
return response.reply;
|
|
239
|
+
} catch (error) {
|
|
240
|
+
if (error instanceof UiWorkerIpcError) {
|
|
241
|
+
if (error.code === "request_timeout") {
|
|
242
|
+
throw new UiWorkerManagerError("worker_busy", "UI Pi turn 尚未结束; 消息保留在队列, 请检查该 tab 状态。 ");
|
|
243
|
+
}
|
|
244
|
+
throw new UiWorkerManagerError("worker_not_found", "UI worker IPC 已断开; route 消息会保留供显式恢复。 ");
|
|
245
|
+
}
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* 优雅关闭指定 UI tab, 让 Pi 自己保存 session 并发出 shutdown lifecycle event。
|
|
252
|
+
*
|
|
253
|
+
* @param sessionId Pi session ID。
|
|
254
|
+
* @param abortRunning 是否允许中止正在运行的 turn。
|
|
255
|
+
* @returns worker 注销并持久化 session 状态后正常结束。
|
|
256
|
+
* @throws {UiWorkerManagerError} 当前 turn 正忙或 worker 无法关闭时抛出。
|
|
257
|
+
*/
|
|
258
|
+
async stop(sessionId: string, abortRunning = false): Promise<void> {
|
|
259
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
260
|
+
const instance = Object.values(snapshot.instances).find((candidate) =>
|
|
261
|
+
candidate.sessionId === sessionId && candidate.mode === "ui" &&
|
|
262
|
+
candidate.state !== "stale" && candidate.state !== "stopping",
|
|
263
|
+
);
|
|
264
|
+
if (!instance) {
|
|
265
|
+
throw new UiWorkerManagerError("worker_not_found", `session ${sessionId} 没有活跃 UI worker。`);
|
|
266
|
+
}
|
|
267
|
+
const connection = this.connections.get(instance.instanceId);
|
|
268
|
+
if (!connection) {
|
|
269
|
+
throw new UiWorkerManagerError("worker_not_found", "UI worker IPC 已断开; 拒绝假设 session 已停止。 ");
|
|
270
|
+
}
|
|
271
|
+
if (instance.state === "running") {
|
|
272
|
+
if (!abortRunning) {
|
|
273
|
+
throw new UiWorkerManagerError(
|
|
274
|
+
"worker_busy",
|
|
275
|
+
"UI Pi turn 正在运行; 等待结束后再 /stop。为避免意外中断, 当前不会隐式 abort。",
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
await connection.request("abort", {}, this.options.shutdownTimeoutMs ?? 10000);
|
|
280
|
+
} catch {
|
|
281
|
+
throw new UiWorkerManagerError("worker_shutdown_timeout", "UI worker 未确认 abort; session owner 仍保留。 ");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
this.explicitStops.add(sessionId);
|
|
285
|
+
const stopped = new Promise<void>((resolveStopped, rejectStopped) => {
|
|
286
|
+
const waiters = this.disconnectWaiters.get(instance.instanceId) ?? new Set<() => void>();
|
|
287
|
+
const resolveOnce = (): void => {
|
|
288
|
+
clearTimeout(timer);
|
|
289
|
+
this.disconnectWaiters.get(instance.instanceId)?.delete(resolveOnce);
|
|
290
|
+
resolveStopped();
|
|
291
|
+
};
|
|
292
|
+
waiters.add(resolveOnce);
|
|
293
|
+
this.disconnectWaiters.set(instance.instanceId, waiters);
|
|
294
|
+
const timer = setTimeout(() => {
|
|
295
|
+
waiters.delete(resolveOnce);
|
|
296
|
+
rejectStopped(new UiWorkerManagerError(
|
|
297
|
+
"worker_shutdown_timeout",
|
|
298
|
+
"UI worker 未在期限内完成 session shutdown; registry owner 保留以避免双 writer。",
|
|
299
|
+
));
|
|
300
|
+
}, this.options.shutdownTimeoutMs ?? 10000);
|
|
301
|
+
timer.unref();
|
|
302
|
+
});
|
|
303
|
+
void stopped.catch(() => undefined);
|
|
304
|
+
try {
|
|
305
|
+
await connection.request("shutdown", { abortRunning }, this.options.shutdownTimeoutMs ?? 10000);
|
|
306
|
+
await stopped;
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (error instanceof UiWorkerManagerError) {
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
if (error instanceof UiWorkerIpcError && error.message.includes("UI Pi turn 正在运行")) {
|
|
312
|
+
throw new UiWorkerManagerError(
|
|
313
|
+
"worker_busy",
|
|
314
|
+
"UI Pi turn 正在运行; 等待结束后再 /stop。",
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
throw new UiWorkerManagerError("worker_shutdown_timeout", "UI worker shutdown request 未完成。 ");
|
|
318
|
+
} finally {
|
|
319
|
+
this.explicitStops.delete(sessionId);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* 检查 registry owner 是否已拥有可用 IPC connection。
|
|
325
|
+
*
|
|
326
|
+
* @param instanceId UI worker instance ID。
|
|
327
|
+
* @returns connection 存活时返回 true。
|
|
328
|
+
*/
|
|
329
|
+
hasConnection(instanceId: string): boolean {
|
|
330
|
+
return this.connections.has(instanceId);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* 列出 manager registry 中的 session 索引。
|
|
335
|
+
*
|
|
336
|
+
* @returns 按最近活动时间倒序排列的 session 记录。
|
|
337
|
+
*/
|
|
338
|
+
async listSessions(): Promise<SessionIndexRecord[]> {
|
|
339
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
340
|
+
return Object.values(snapshot.sessions).sort((left, right) =>
|
|
341
|
+
right.lastActivityAt.localeCompare(left.lastActivityAt),
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Gateway shutdown 时断开 pipe, 保留仍运行的 Pi TUI owner 供下一 Gateway 重连。
|
|
347
|
+
*
|
|
348
|
+
* @returns IPC server 关闭后正常结束。
|
|
349
|
+
*/
|
|
350
|
+
async detachGateway(): Promise<void> {
|
|
351
|
+
await this.options.ipcServer.close();
|
|
352
|
+
this.connections.clear();
|
|
353
|
+
for (const timer of this.staleTimers.values()) {
|
|
354
|
+
clearTimeout(timer);
|
|
355
|
+
}
|
|
356
|
+
this.staleTimers.clear();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* 按启动 ticket 或现有 process 身份验证并更新 session/instance registry。
|
|
361
|
+
*
|
|
362
|
+
* @param registration UI extension 声明。
|
|
363
|
+
* @param authHash ticket SHA-256。
|
|
364
|
+
* @param launchRecord 新启动时使用的一次性记录。
|
|
365
|
+
* @param connection 已完成 HMAC 的 IPC 连接。
|
|
366
|
+
* @returns registry 落盘后正常结束。
|
|
367
|
+
*/
|
|
368
|
+
private async registerWorker(
|
|
369
|
+
registration: UiWorkerRegistration,
|
|
370
|
+
authHash: string,
|
|
371
|
+
launchRecord: UiWorkerLaunchRecord | undefined,
|
|
372
|
+
connection: UiWorkerIpcConnection,
|
|
373
|
+
clearName = false,
|
|
374
|
+
): Promise<void> {
|
|
375
|
+
let resolvedProject: ProjectDefinition;
|
|
376
|
+
try {
|
|
377
|
+
resolvedProject = await this.options.projectService.resolveSession(
|
|
378
|
+
registration.projectAlias,
|
|
379
|
+
registration.cwd,
|
|
380
|
+
);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (error instanceof ProjectServiceError) {
|
|
383
|
+
throw error;
|
|
384
|
+
}
|
|
385
|
+
throw new UiWorkerManagerError("worker_launch_failed", "UI worker cwd 未通过 allowedProjectRoots 检查。 ");
|
|
386
|
+
}
|
|
387
|
+
if (launchRecord && !samePath(resolvedProject.path, launchRecord.projectPath)) {
|
|
388
|
+
throw new UiWorkerManagerError("worker_launch_failed", "UI worker cwd 与受控 launch project 不匹配。 ");
|
|
389
|
+
}
|
|
390
|
+
const canonicalCwd = resolvedProject.path;
|
|
391
|
+
let snapshot = await this.options.registry.readSnapshot();
|
|
392
|
+
let otherOwner = Object.values(snapshot.instances).find((instance) =>
|
|
393
|
+
instance.sessionId === registration.sessionId &&
|
|
394
|
+
instance.instanceId !== registration.instanceId &&
|
|
395
|
+
isProcessAlive(instance.pid),
|
|
396
|
+
);
|
|
397
|
+
if (
|
|
398
|
+
otherOwner?.mode === "background" &&
|
|
399
|
+
this.options.backgroundWorkerManager &&
|
|
400
|
+
otherOwner.state !== "stale" &&
|
|
401
|
+
otherOwner.state !== "stopping"
|
|
402
|
+
) {
|
|
403
|
+
await this.options.backgroundWorkerManager.stop(registration.sessionId);
|
|
404
|
+
snapshot = await this.options.registry.readSnapshot();
|
|
405
|
+
otherOwner = Object.values(snapshot.instances).find((instance) =>
|
|
406
|
+
instance.sessionId === registration.sessionId &&
|
|
407
|
+
instance.instanceId !== registration.instanceId &&
|
|
408
|
+
isProcessAlive(instance.pid),
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
if (otherOwner) {
|
|
412
|
+
throw new UiWorkerManagerError(
|
|
413
|
+
"session_owned_by_other_process",
|
|
414
|
+
`session ${registration.sessionId} 已由 ${otherOwner.mode} owner 持有; 拒绝双 writer。`,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
let previousInstance: WorkerInstanceRecord | undefined;
|
|
418
|
+
let session: SessionIndexRecord;
|
|
419
|
+
|
|
420
|
+
if (launchRecord) {
|
|
421
|
+
const existing = snapshot.sessions[registration.sessionId];
|
|
422
|
+
if (launchRecord.mode === "resume") {
|
|
423
|
+
if (
|
|
424
|
+
!existing ||
|
|
425
|
+
existing.state === "active" ||
|
|
426
|
+
!samePath(existing.sessionFile, registration.sessionFile) ||
|
|
427
|
+
existing.sessionId !== registration.sessionId
|
|
428
|
+
) {
|
|
429
|
+
throw new UiWorkerManagerError("session_owned_by_other_process", "保存的 UI session 状态已变化, 拒绝恢复。 ");
|
|
430
|
+
}
|
|
431
|
+
session = {
|
|
432
|
+
...existing,
|
|
433
|
+
cwd: canonicalCwd,
|
|
434
|
+
name: registration.name ?? launchRecord.sessionName ?? existing.name,
|
|
435
|
+
mode: "ui",
|
|
436
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
437
|
+
lastActivityAt: new Date().toISOString(),
|
|
438
|
+
};
|
|
439
|
+
} else {
|
|
440
|
+
if (existing) {
|
|
441
|
+
throw new UiWorkerManagerError("registry_inconsistent", "Pi 为新 UI launch 返回了已登记 sessionId。 ");
|
|
442
|
+
}
|
|
443
|
+
session = {
|
|
444
|
+
sessionId: registration.sessionId,
|
|
445
|
+
sessionFile: registration.sessionFile,
|
|
446
|
+
cwd: canonicalCwd,
|
|
447
|
+
projectAlias: registration.projectAlias,
|
|
448
|
+
...(registration.name ?? launchRecord.sessionName
|
|
449
|
+
? { name: registration.name ?? launchRecord.sessionName }
|
|
450
|
+
: {}),
|
|
451
|
+
mode: "ui",
|
|
452
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
453
|
+
lastActivityAt: new Date().toISOString(),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
} else {
|
|
457
|
+
previousInstance = snapshot.instances[registration.instanceId];
|
|
458
|
+
if (!previousInstance) {
|
|
459
|
+
const existing = snapshot.sessions[registration.sessionId];
|
|
460
|
+
if (existing && !samePath(existing.sessionFile, registration.sessionFile)) {
|
|
461
|
+
throw new UiWorkerManagerError("session_owned_by_other_process", "Pi UI session transcript 与已有 session 索引不匹配。 ");
|
|
462
|
+
}
|
|
463
|
+
const baseSession: SessionIndexRecord = existing
|
|
464
|
+
? {
|
|
465
|
+
...existing,
|
|
466
|
+
sessionFile: registration.sessionFile,
|
|
467
|
+
cwd: canonicalCwd,
|
|
468
|
+
projectAlias: registration.projectAlias,
|
|
469
|
+
mode: "ui",
|
|
470
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
471
|
+
lastActivityAt: new Date().toISOString(),
|
|
472
|
+
}
|
|
473
|
+
: {
|
|
474
|
+
sessionId: registration.sessionId,
|
|
475
|
+
sessionFile: registration.sessionFile,
|
|
476
|
+
cwd: canonicalCwd,
|
|
477
|
+
projectAlias: registration.projectAlias,
|
|
478
|
+
mode: "ui",
|
|
479
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
480
|
+
lastActivityAt: new Date().toISOString(),
|
|
481
|
+
};
|
|
482
|
+
session = applySessionName(baseSession, registration.name, clearName);
|
|
483
|
+
} else {
|
|
484
|
+
if (
|
|
485
|
+
previousInstance.mode !== "ui" ||
|
|
486
|
+
previousInstance.launchId !== registration.launchId ||
|
|
487
|
+
previousInstance.pid !== registration.pid ||
|
|
488
|
+
previousInstance.processBirthId !== registration.processBirthId ||
|
|
489
|
+
previousInstance.ipcAuthHash !== authHash
|
|
490
|
+
) {
|
|
491
|
+
throw new UiWorkerManagerError("session_owned_by_other_process", "UI worker 重连身份不匹配。 ");
|
|
492
|
+
}
|
|
493
|
+
const previousSession = snapshot.sessions[previousInstance.sessionId];
|
|
494
|
+
if (!previousSession) {
|
|
495
|
+
throw new UiWorkerManagerError("registry_inconsistent", "UI worker owner 缺少 session registry。 ");
|
|
496
|
+
}
|
|
497
|
+
if (previousSession.sessionId !== registration.sessionId) {
|
|
498
|
+
await this.options.registry.upsertSession({
|
|
499
|
+
...previousSession,
|
|
500
|
+
state: await isPersistedSessionFile(previousSession.sessionFile) ? "saved" : "pending",
|
|
501
|
+
lastActivityAt: new Date().toISOString(),
|
|
502
|
+
});
|
|
503
|
+
const nextExisting = snapshot.sessions[registration.sessionId];
|
|
504
|
+
if (nextExisting) {
|
|
505
|
+
session = applySessionName({
|
|
506
|
+
...nextExisting,
|
|
507
|
+
sessionFile: registration.sessionFile,
|
|
508
|
+
cwd: canonicalCwd,
|
|
509
|
+
projectAlias: registration.projectAlias,
|
|
510
|
+
mode: "ui",
|
|
511
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
512
|
+
lastActivityAt: new Date().toISOString(),
|
|
513
|
+
}, registration.name, clearName);
|
|
514
|
+
} else {
|
|
515
|
+
session = {
|
|
516
|
+
sessionId: registration.sessionId,
|
|
517
|
+
sessionFile: registration.sessionFile,
|
|
518
|
+
cwd: canonicalCwd,
|
|
519
|
+
projectAlias: registration.projectAlias,
|
|
520
|
+
...(registration.name ? { name: registration.name } : {}),
|
|
521
|
+
mode: "ui",
|
|
522
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
523
|
+
lastActivityAt: new Date().toISOString(),
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
await this.rebindRoutes(previousInstance.instanceId, previousSession.sessionId, session.sessionId);
|
|
527
|
+
} else {
|
|
528
|
+
session = applySessionName({
|
|
529
|
+
...previousSession,
|
|
530
|
+
sessionFile: registration.sessionFile,
|
|
531
|
+
cwd: canonicalCwd,
|
|
532
|
+
projectAlias: registration.projectAlias,
|
|
533
|
+
mode: "ui",
|
|
534
|
+
state: await isPersistedSessionFile(registration.sessionFile) ? "active" : "pending",
|
|
535
|
+
lastActivityAt: new Date().toISOString(),
|
|
536
|
+
}, registration.name, clearName);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const instance: WorkerInstanceRecord = {
|
|
542
|
+
instanceId: registration.instanceId,
|
|
543
|
+
pid: registration.pid,
|
|
544
|
+
processBirthId: registration.processBirthId,
|
|
545
|
+
sessionId: registration.sessionId,
|
|
546
|
+
sessionFile: registration.sessionFile,
|
|
547
|
+
cwd: canonicalCwd,
|
|
548
|
+
projectAlias: registration.projectAlias,
|
|
549
|
+
mode: "ui",
|
|
550
|
+
state: registration.state,
|
|
551
|
+
heartbeatAt: new Date().toISOString(),
|
|
552
|
+
launchId: registration.launchId,
|
|
553
|
+
ipcAuthHash: authHash,
|
|
554
|
+
};
|
|
555
|
+
await this.options.registry.upsertSession(session);
|
|
556
|
+
await this.options.registry.upsertInstance(instance);
|
|
557
|
+
const routeSnapshot = await this.options.registry.readSnapshot();
|
|
558
|
+
const reboundRoutes = Object.entries(routeSnapshot.routes).filter(([, route]) =>
|
|
559
|
+
route.sessionId === session.sessionId && route.workerInstanceId !== instance.instanceId,
|
|
560
|
+
);
|
|
561
|
+
await Promise.all(reboundRoutes.map(([routeId, route]) =>
|
|
562
|
+
this.options.registry.setRoute(routeId, {
|
|
563
|
+
...route,
|
|
564
|
+
workerInstanceId: instance.instanceId,
|
|
565
|
+
generation: route.generation + 1,
|
|
566
|
+
updatedAt: new Date().toISOString(),
|
|
567
|
+
}),
|
|
568
|
+
));
|
|
569
|
+
if (!previousInstance) {
|
|
570
|
+
await this.options.registry.appendEvent("worker.ui_registered", {
|
|
571
|
+
sessionId: session.sessionId,
|
|
572
|
+
instanceId: instance.instanceId,
|
|
573
|
+
projectAlias: session.projectAlias,
|
|
574
|
+
pid: instance.pid,
|
|
575
|
+
});
|
|
576
|
+
} else if (previousInstance.sessionId !== session.sessionId) {
|
|
577
|
+
await this.options.registry.appendEvent("worker.ui_session_changed", {
|
|
578
|
+
previousSessionId: previousInstance.sessionId,
|
|
579
|
+
sessionId: session.sessionId,
|
|
580
|
+
instanceId: instance.instanceId,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
this.connections.set(instance.instanceId, connection);
|
|
584
|
+
this.cancelStaleTimer(instance.instanceId);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* 更新 UI session 切换后的微信 route binding。
|
|
589
|
+
*
|
|
590
|
+
* @param instanceId 当前 TUI process owner。
|
|
591
|
+
* @param oldSessionId 之前的 Pi session。
|
|
592
|
+
* @param newSessionId 新的 Pi session。
|
|
593
|
+
* @returns 无返回值。
|
|
594
|
+
*/
|
|
595
|
+
private async rebindRoutes(instanceId: string, oldSessionId: string, newSessionId: string): Promise<void> {
|
|
596
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
597
|
+
const routes = Object.entries(snapshot.routes).filter(([, route]) =>
|
|
598
|
+
route.workerInstanceId === instanceId && route.sessionId === oldSessionId,
|
|
599
|
+
);
|
|
600
|
+
await Promise.all(routes.map(([routeId, route]) => this.options.registry.setRoute(routeId, {
|
|
601
|
+
...route,
|
|
602
|
+
sessionId: newSessionId,
|
|
603
|
+
generation: route.generation + 1,
|
|
604
|
+
updatedAt: new Date().toISOString(),
|
|
605
|
+
})));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* 验证 TUI 是否可以切换到目标 Pi session 而不违反单 writer。
|
|
610
|
+
*
|
|
611
|
+
* @param connection 已认证 UI worker connection。
|
|
612
|
+
* @param method 控制 request 方法名。
|
|
613
|
+
* @param params 目标 sessionFile 等参数。
|
|
614
|
+
* @returns 包含 allowed 与稳定理由代码的结果。
|
|
615
|
+
*/
|
|
616
|
+
private async handleWorkerRequest(
|
|
617
|
+
connection: UiWorkerIpcConnection,
|
|
618
|
+
method: string,
|
|
619
|
+
params: Record<string, unknown>,
|
|
620
|
+
): Promise<unknown> {
|
|
621
|
+
if (method !== "can_switch_session") {
|
|
622
|
+
throw new UiWorkerManagerError("registry_inconsistent", "Gateway 收到未知 UI worker request。 ");
|
|
623
|
+
}
|
|
624
|
+
if (typeof params.sessionFile !== "string" || !isAbsolute(params.sessionFile)) {
|
|
625
|
+
return { allowed: false, reason: "invalid_session_file" };
|
|
626
|
+
}
|
|
627
|
+
let snapshot = await this.options.registry.readSnapshot();
|
|
628
|
+
const target = Object.values(snapshot.sessions).find((session) =>
|
|
629
|
+
samePath(session.sessionFile, params.sessionFile as string),
|
|
630
|
+
);
|
|
631
|
+
if (!target) {
|
|
632
|
+
const unindexedOwner = Object.values(snapshot.instances).find((instance) =>
|
|
633
|
+
samePath(instance.sessionFile, params.sessionFile as string) &&
|
|
634
|
+
instance.instanceId !== connection.registration.instanceId &&
|
|
635
|
+
isProcessAlive(instance.pid),
|
|
636
|
+
);
|
|
637
|
+
return unindexedOwner
|
|
638
|
+
? { allowed: false, reason: "session_owned_by_other_process" }
|
|
639
|
+
: { allowed: true, reason: "session_not_registered" };
|
|
640
|
+
}
|
|
641
|
+
try {
|
|
642
|
+
await this.options.projectService.resolveSession(target.projectAlias, target.cwd);
|
|
643
|
+
} catch {
|
|
644
|
+
return { allowed: false, reason: "project_path_denied" };
|
|
645
|
+
}
|
|
646
|
+
let competingOwner = Object.values(snapshot.instances).find((instance) =>
|
|
647
|
+
instance.sessionId === target.sessionId &&
|
|
648
|
+
instance.instanceId !== connection.registration.instanceId &&
|
|
649
|
+
isProcessAlive(instance.pid),
|
|
650
|
+
);
|
|
651
|
+
if (
|
|
652
|
+
competingOwner?.mode === "background" &&
|
|
653
|
+
competingOwner.state !== "stale" &&
|
|
654
|
+
competingOwner.state !== "stopping" &&
|
|
655
|
+
this.options.backgroundWorkerManager
|
|
656
|
+
) {
|
|
657
|
+
try {
|
|
658
|
+
await this.options.backgroundWorkerManager.stop(target.sessionId);
|
|
659
|
+
} catch {
|
|
660
|
+
return { allowed: false, reason: "background_handoff_failed" };
|
|
661
|
+
}
|
|
662
|
+
snapshot = await this.options.registry.readSnapshot();
|
|
663
|
+
competingOwner = Object.values(snapshot.instances).find((instance) =>
|
|
664
|
+
instance.sessionId === target.sessionId &&
|
|
665
|
+
instance.instanceId !== connection.registration.instanceId &&
|
|
666
|
+
isProcessAlive(instance.pid),
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
if (competingOwner) {
|
|
670
|
+
return { allowed: false, reason: "session_owned_by_other_process" };
|
|
671
|
+
}
|
|
672
|
+
return { allowed: true };
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* 接收 UI worker heartbeat、session change 或 shutdown event。
|
|
677
|
+
*
|
|
678
|
+
* @param connection 已认证的 worker connection。
|
|
679
|
+
* @param name IPC event name。
|
|
680
|
+
* @param data event payload。
|
|
681
|
+
* @returns 无返回值。
|
|
682
|
+
*/
|
|
683
|
+
private async handleWorkerEvent(
|
|
684
|
+
connection: UiWorkerIpcConnection,
|
|
685
|
+
name: string,
|
|
686
|
+
data: Record<string, unknown>,
|
|
687
|
+
): Promise<void> {
|
|
688
|
+
const instanceId = connection.registration.instanceId;
|
|
689
|
+
if (name === "heartbeat") {
|
|
690
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
691
|
+
const instance = snapshot.instances[instanceId];
|
|
692
|
+
if (!instance) {
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
const state = isWorkerState(data.state) ? data.state : instance.state;
|
|
696
|
+
await this.options.registry.upsertInstance({
|
|
697
|
+
...instance,
|
|
698
|
+
state,
|
|
699
|
+
heartbeatAt: new Date().toISOString(),
|
|
700
|
+
});
|
|
701
|
+
const session = snapshot.sessions[instance.sessionId];
|
|
702
|
+
if (session) {
|
|
703
|
+
const persistedState = await isPersistedSessionFile(session.sessionFile) ? "active" : "pending";
|
|
704
|
+
if (session.state !== persistedState) {
|
|
705
|
+
await this.options.registry.upsertSession({ ...session, state: persistedState });
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
if (name === "turn_settled") {
|
|
711
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
712
|
+
const instance = snapshot.instances[instanceId];
|
|
713
|
+
const session = instance ? snapshot.sessions[instance.sessionId] : undefined;
|
|
714
|
+
if (session) {
|
|
715
|
+
await this.options.registry.upsertSession({
|
|
716
|
+
...session,
|
|
717
|
+
state: await isPersistedSessionFile(session.sessionFile) ? "active" : "pending",
|
|
718
|
+
lastActivityAt: new Date().toISOString(),
|
|
719
|
+
});
|
|
720
|
+
await this.options.registry.appendEvent("worker.ui_turn_settled", {
|
|
721
|
+
sessionId: session.sessionId,
|
|
722
|
+
instanceId,
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
if (name === "session_changed" || name === "session_info_changed") {
|
|
728
|
+
const registration = parseUiWorkerRegistration(data.registration);
|
|
729
|
+
const original = connection.registration;
|
|
730
|
+
if (
|
|
731
|
+
registration.instanceId !== original.instanceId ||
|
|
732
|
+
registration.launchId !== original.launchId ||
|
|
733
|
+
registration.pid !== original.pid ||
|
|
734
|
+
registration.processBirthId !== original.processBirthId
|
|
735
|
+
) {
|
|
736
|
+
throw new UiWorkerManagerError(
|
|
737
|
+
"registry_inconsistent",
|
|
738
|
+
"已认证的 UI worker 不得替换其他 instance 的身份信息。",
|
|
739
|
+
);
|
|
740
|
+
}
|
|
741
|
+
const clearName = name === "session_info_changed" && data.clearName === true;
|
|
742
|
+
await this.registerWorker(
|
|
743
|
+
registration,
|
|
744
|
+
await this.findInstanceAuthHash(instanceId),
|
|
745
|
+
undefined,
|
|
746
|
+
connection,
|
|
747
|
+
clearName,
|
|
748
|
+
);
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (name === "worker_shutdown") {
|
|
752
|
+
await this.markStopped(instanceId);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* 在非 Gateway shutdown 造成的断连时短暂标记 stale 并等待 bridge reconnect。
|
|
758
|
+
*
|
|
759
|
+
* @param connection 已关闭的 connection。
|
|
760
|
+
* @param serverStopping 当前 Gateway 是否正在优雅退出。
|
|
761
|
+
* @returns 无返回值。
|
|
762
|
+
*/
|
|
763
|
+
private async handleDisconnect(connection: UiWorkerIpcConnection, serverStopping: boolean): Promise<void> {
|
|
764
|
+
const instanceId = connection.registration.instanceId;
|
|
765
|
+
if (this.connections.get(instanceId) === connection) {
|
|
766
|
+
this.connections.delete(instanceId);
|
|
767
|
+
}
|
|
768
|
+
if (serverStopping) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
772
|
+
const instance = snapshot.instances[instanceId];
|
|
773
|
+
if (!instance || instance.mode !== "ui") {
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (!isProcessAlive(instance.pid)) {
|
|
777
|
+
await this.markStopped(instanceId);
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
await this.options.registry.upsertInstance({
|
|
781
|
+
...instance,
|
|
782
|
+
state: "stale",
|
|
783
|
+
heartbeatAt: new Date().toISOString(),
|
|
784
|
+
});
|
|
785
|
+
this.scheduleStaleCleanup(instanceId);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* 将已退出 UI owner 的 session 保存, 并把关联 route 安全交给后台 RPC worker。
|
|
790
|
+
*
|
|
791
|
+
* @param instanceId UI worker instance ID。
|
|
792
|
+
* @returns route 已交接或无须交接后正常结束。
|
|
793
|
+
*/
|
|
794
|
+
private async markStopped(instanceId: string): Promise<void> {
|
|
795
|
+
this.cancelStaleTimer(instanceId);
|
|
796
|
+
this.connections.delete(instanceId);
|
|
797
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
798
|
+
const instance = snapshot.instances[instanceId];
|
|
799
|
+
if (!instance) {
|
|
800
|
+
this.resolveDisconnectWaiters(instanceId);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
const session = snapshot.sessions[instance.sessionId];
|
|
804
|
+
const routes = Object.entries(snapshot.routes).filter(([, route]) =>
|
|
805
|
+
route.sessionId === instance.sessionId && route.workerInstanceId === instanceId,
|
|
806
|
+
);
|
|
807
|
+
const explicitStop = this.explicitStops.has(instance.sessionId);
|
|
808
|
+
const transcriptExists = session ? await isPersistedSessionFile(session.sessionFile) : false;
|
|
809
|
+
if (session) {
|
|
810
|
+
await this.options.registry.upsertSession({
|
|
811
|
+
...session,
|
|
812
|
+
mode: explicitStop ? session.mode : "background",
|
|
813
|
+
state: transcriptExists ? "saved" : "pending",
|
|
814
|
+
lastActivityAt: new Date().toISOString(),
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
await this.options.registry.removeInstance(instanceId);
|
|
818
|
+
|
|
819
|
+
if (explicitStop || routes.length === 0 || !session || !this.options.backgroundWorkerManager) {
|
|
820
|
+
await Promise.all(routes.map(([routeId]) => this.options.registry.setRoute(routeId, null)));
|
|
821
|
+
} else {
|
|
822
|
+
try {
|
|
823
|
+
const backgroundSession = transcriptExists
|
|
824
|
+
? await this.options.backgroundWorkerManager.resume(session.sessionId, "background")
|
|
825
|
+
: await this.options.backgroundWorkerManager.startNew(session.projectAlias, session.name);
|
|
826
|
+
const afterHandoff = await this.options.registry.readSnapshot();
|
|
827
|
+
const backgroundOwner = Object.values(afterHandoff.instances).find((candidate) =>
|
|
828
|
+
candidate.sessionId === backgroundSession.sessionId &&
|
|
829
|
+
candidate.mode === "background" &&
|
|
830
|
+
candidate.state !== "stale" &&
|
|
831
|
+
candidate.state !== "stopping",
|
|
832
|
+
);
|
|
833
|
+
if (!backgroundOwner) {
|
|
834
|
+
throw new UiWorkerManagerError("registry_inconsistent", "后台 owner 注册后未出现在 session registry。 ");
|
|
835
|
+
}
|
|
836
|
+
await Promise.all(routes.map(([routeId, route]) => this.options.registry.setRoute(routeId, {
|
|
837
|
+
...route,
|
|
838
|
+
sessionId: backgroundSession.sessionId,
|
|
839
|
+
workerInstanceId: backgroundOwner.instanceId,
|
|
840
|
+
generation: route.generation + 1,
|
|
841
|
+
updatedAt: new Date().toISOString(),
|
|
842
|
+
})));
|
|
843
|
+
} catch {
|
|
844
|
+
await Promise.all(routes.map(([routeId]) => this.options.registry.setRoute(routeId, null)));
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
await this.options.registry.appendEvent("worker.ui_stopped", {
|
|
849
|
+
sessionId: instance.sessionId,
|
|
850
|
+
instanceId,
|
|
851
|
+
routeHandoff: !explicitStop && routes.length > 0,
|
|
852
|
+
});
|
|
853
|
+
this.resolveDisconnectWaiters(instanceId);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/**
|
|
857
|
+
* 在 UI TUI 长期断连时保留 owner 记录并释放 stale timeout。
|
|
858
|
+
*
|
|
859
|
+
* @param instanceId worker instance ID。
|
|
860
|
+
* @returns 无返回值。
|
|
861
|
+
*/
|
|
862
|
+
private scheduleStaleCleanup(instanceId: string): void {
|
|
863
|
+
this.cancelStaleTimer(instanceId);
|
|
864
|
+
const timer = setTimeout(() => {
|
|
865
|
+
this.staleTimers.delete(instanceId);
|
|
866
|
+
void this.confirmStaleWorker(instanceId);
|
|
867
|
+
}, this.maxStaleMs);
|
|
868
|
+
timer.unref();
|
|
869
|
+
this.staleTimers.set(instanceId, timer);
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* stale 超时后只回收已退出的 Pi TUI; 存活或状态不明时保留 owner。
|
|
874
|
+
*
|
|
875
|
+
* @param instanceId worker instance ID。
|
|
876
|
+
* @returns 无返回值。
|
|
877
|
+
*/
|
|
878
|
+
private async confirmStaleWorker(instanceId: string): Promise<void> {
|
|
879
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
880
|
+
const instance = snapshot.instances[instanceId];
|
|
881
|
+
if (!instance || instance.state !== "stale" || isProcessAlive(instance.pid)) {
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
await this.markStopped(instanceId);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* 清理指定 worker 的 stale timer。
|
|
889
|
+
*
|
|
890
|
+
* @param instanceId worker instance ID。
|
|
891
|
+
* @returns 无返回值。
|
|
892
|
+
*/
|
|
893
|
+
private cancelStaleTimer(instanceId: string): void {
|
|
894
|
+
const timer = this.staleTimers.get(instanceId);
|
|
895
|
+
if (timer) {
|
|
896
|
+
clearTimeout(timer);
|
|
897
|
+
this.staleTimers.delete(instanceId);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* 获取现存 UI worker 的 registry 认证摘要。
|
|
903
|
+
*
|
|
904
|
+
* @param instanceId worker instance ID。
|
|
905
|
+
* @returns ticket SHA-256 摘要。
|
|
906
|
+
*/
|
|
907
|
+
private async findInstanceAuthHash(instanceId: string): Promise<string> {
|
|
908
|
+
const snapshot = await this.options.registry.readSnapshot();
|
|
909
|
+
const instance = snapshot.instances[instanceId];
|
|
910
|
+
if (!instance?.ipcAuthHash) {
|
|
911
|
+
throw new UiWorkerManagerError("registry_inconsistent", "UI worker registry 缺少 IPC auth hash。 ");
|
|
912
|
+
}
|
|
913
|
+
return instance.ipcAuthHash;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* 等待 UI worker shutdown lifecycle 完成。
|
|
918
|
+
*
|
|
919
|
+
* @param instanceId worker instance ID。
|
|
920
|
+
* @returns 所有 stop waiter 正常结束。
|
|
921
|
+
*/
|
|
922
|
+
private resolveDisconnectWaiters(instanceId: string): void {
|
|
923
|
+
const waiters = this.disconnectWaiters.get(instanceId);
|
|
924
|
+
if (!waiters) {
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
this.disconnectWaiters.delete(instanceId);
|
|
928
|
+
for (const resolveWaiter of waiters) {
|
|
929
|
+
resolveWaiter();
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* 在当前平台启动可见 Pi UI worker。
|
|
935
|
+
*
|
|
936
|
+
* @returns Windows 平台正常结束。
|
|
937
|
+
* @throws {UiWorkerManagerError} 非 Windows 平台时抛出。
|
|
938
|
+
*/
|
|
939
|
+
private assertSupportedPlatform(): void {
|
|
940
|
+
if ((this.options.platform ?? process.platform) !== "win32") {
|
|
941
|
+
throw new UiWorkerManagerError(
|
|
942
|
+
"unsupported_platform",
|
|
943
|
+
"可见 UI 模式依赖 Windows Terminal, 当前平台不支持, 已阻塞该操作; 请改用 background 模式。",
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* 探测可见 UI 模式是否可用, 不可用时在启动前阻塞操作。
|
|
950
|
+
*
|
|
951
|
+
* 仅缓存成功结果; 失败结果不缓存, 以便用户安装 Windows Terminal 后无需重启 daemon 即可重试。
|
|
952
|
+
*
|
|
953
|
+
* @returns 可用时正常结束。
|
|
954
|
+
* @throws {UiWorkerManagerError} 平台不受支持或 Windows Terminal 缺失时抛出。
|
|
955
|
+
*/
|
|
956
|
+
private async assertUiModeAvailable(): Promise<void> {
|
|
957
|
+
this.assertSupportedPlatform();
|
|
958
|
+
const capability = await this.describeUiModeCapability();
|
|
959
|
+
if (capability.supported) {
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
throw new UiWorkerManagerError(
|
|
963
|
+
"wt_not_found",
|
|
964
|
+
`${capability.reason}; 已阻塞可见 UI 会话创建与恢复, 请安装 Windows Terminal 或改用 background 模式。`,
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* 读取可见 UI 模式的能力探测结果, 供状态展示复用。
|
|
970
|
+
*
|
|
971
|
+
* 仅缓存成功结果; 平台不受支持或缺少 wt.exe 时每次重新探测。
|
|
972
|
+
*
|
|
973
|
+
* @returns 当前环境的 UI 模式能力。
|
|
974
|
+
*/
|
|
975
|
+
async describeUiModeCapability(): Promise<WindowsTerminalCapability> {
|
|
976
|
+
if ((this.options.platform ?? process.platform) !== "win32") {
|
|
977
|
+
return {
|
|
978
|
+
supported: false,
|
|
979
|
+
reason: `当前系统为 ${this.options.platform ?? process.platform}, 可见 UI 模式依赖 Windows Terminal, 仅支持 Windows`,
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
if (this.capabilityTask) {
|
|
983
|
+
return this.capabilityTask;
|
|
984
|
+
}
|
|
985
|
+
const probe = this.options.probeCapability
|
|
986
|
+
? this.options.probeCapability
|
|
987
|
+
: async (): Promise<WindowsTerminalCapability> =>
|
|
988
|
+
probeWindowsTerminalCapability({ platform: this.options.platform ?? process.platform });
|
|
989
|
+
const capability = await probe();
|
|
990
|
+
if (capability.supported) {
|
|
991
|
+
this.capabilityTask = Promise.resolve(capability);
|
|
992
|
+
}
|
|
993
|
+
return capability;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* 解析已登记项目并在启动前重新验证允许根目录。
|
|
998
|
+
*
|
|
999
|
+
* @param projectAlias 项目 alias。
|
|
1000
|
+
* @returns 已验证项目路径。
|
|
1001
|
+
*/
|
|
1002
|
+
private async resolveProject(projectAlias: string): Promise<{ displayName: string; path: string }> {
|
|
1003
|
+
try {
|
|
1004
|
+
return await this.options.projectService.resolve(projectAlias);
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
if (error instanceof ProjectServiceError) {
|
|
1007
|
+
throw error;
|
|
1008
|
+
}
|
|
1009
|
+
throw new UiWorkerManagerError("worker_launch_failed", "UI worker 项目路径验证失败。 ");
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* 创建一次性 launch record。
|
|
1015
|
+
*
|
|
1016
|
+
* @param options 新建或恢复 session 参数。
|
|
1017
|
+
* @returns 带有随机 instanceId/ticket 的 record。
|
|
1018
|
+
*/
|
|
1019
|
+
private createLaunchRecord(options: {
|
|
1020
|
+
mode: "new" | "resume";
|
|
1021
|
+
projectAlias: string;
|
|
1022
|
+
projectPath: string;
|
|
1023
|
+
sessionName?: string;
|
|
1024
|
+
sessionId?: string;
|
|
1025
|
+
sessionFile?: string;
|
|
1026
|
+
}): UiWorkerLaunchRecord {
|
|
1027
|
+
const piCliEntry = this.options.invocation.args[0];
|
|
1028
|
+
if (!piCliEntry || !isAbsolute(this.options.invocation.command) || !isAbsolute(piCliEntry)) {
|
|
1029
|
+
throw new UiWorkerManagerError("worker_launch_failed", "当前 Pi CLI argv 不适用于安全 UI worker 启动。 ");
|
|
1030
|
+
}
|
|
1031
|
+
const now = Date.now();
|
|
1032
|
+
return {
|
|
1033
|
+
schemaVersion: 1,
|
|
1034
|
+
launchId: randomUUID(),
|
|
1035
|
+
instanceId: randomUUID(),
|
|
1036
|
+
ticket: randomBytes(32).toString("hex"),
|
|
1037
|
+
mode: options.mode,
|
|
1038
|
+
projectAlias: options.projectAlias,
|
|
1039
|
+
projectPath: options.projectPath,
|
|
1040
|
+
...(options.sessionName ? { sessionName: options.sessionName } : {}),
|
|
1041
|
+
...(options.sessionId ? { sessionId: options.sessionId } : {}),
|
|
1042
|
+
...(options.sessionFile ? { sessionFile: options.sessionFile } : {}),
|
|
1043
|
+
managerDirectory: resolve(this.options.managerDirectory),
|
|
1044
|
+
agentDirectory: dirname(resolve(this.options.managerDirectory)),
|
|
1045
|
+
pipeEndpoint: this.options.ipcServer.endpoint,
|
|
1046
|
+
nodeExecutable: this.options.invocation.command,
|
|
1047
|
+
piCliEntry: resolve(piCliEntry),
|
|
1048
|
+
extensionPath: resolve(this.options.extensionPath),
|
|
1049
|
+
createdAt: new Date(now).toISOString(),
|
|
1050
|
+
expiresAt: new Date(now + (this.options.registrationTimeoutMs ?? 30000)).toISOString(),
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* 调用 WT launcher 并等待 extension 完成注册。
|
|
1056
|
+
*
|
|
1057
|
+
* @param launch 已校验 launch record。
|
|
1058
|
+
* @returns 注册 session。
|
|
1059
|
+
*/
|
|
1060
|
+
private async launchAndWait(launch: UiWorkerLaunchRecord): Promise<SessionIndexRecord> {
|
|
1061
|
+
const launcher = this.options.launcher ?? new WindowsTerminalLauncher();
|
|
1062
|
+
const registration = this.options.ipcServer.waitForLaunch(
|
|
1063
|
+
launch.launchId,
|
|
1064
|
+
this.options.registrationTimeoutMs ?? 30000,
|
|
1065
|
+
);
|
|
1066
|
+
void registration.catch(() => undefined);
|
|
1067
|
+
try {
|
|
1068
|
+
await this.options.ipcServer.registerLaunch(launch);
|
|
1069
|
+
await launcher.launch(this.options.managerDirectory, launch.projectPath, launch.launchId);
|
|
1070
|
+
await registration;
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
await this.options.ipcServer.removeLaunch(launch.launchId).catch(() => undefined);
|
|
1073
|
+
if (error instanceof WindowsTerminalLaunchError) {
|
|
1074
|
+
const code = error.code === "wt_not_found" ? "wt_not_found" :
|
|
1075
|
+
error.code === "unsupported_platform" ? "unsupported_platform" : "worker_launch_failed";
|
|
1076
|
+
throw new UiWorkerManagerError(code, error.message);
|
|
1077
|
+
}
|
|
1078
|
+
if (error instanceof UiWorkerIpcError && error.code === "request_timeout") {
|
|
1079
|
+
throw new UiWorkerManagerError("worker_registration_timeout", error.message);
|
|
1080
|
+
}
|
|
1081
|
+
if (error instanceof UiWorkerManagerError) {
|
|
1082
|
+
throw error;
|
|
1083
|
+
}
|
|
1084
|
+
throw new UiWorkerManagerError("worker_launch_failed", "UI worker 启动失败; 未绑定微信 route。 ");
|
|
1085
|
+
}
|
|
1086
|
+
const registeredSessionId = launch.mode === "resume"
|
|
1087
|
+
? launch.sessionId
|
|
1088
|
+
: [...this.connections.values()].find((connection) => connection.registration.instanceId === launch.instanceId)
|
|
1089
|
+
?.registration.sessionId;
|
|
1090
|
+
const session = registeredSessionId
|
|
1091
|
+
? (await this.options.registry.readSnapshot()).sessions[registeredSessionId]
|
|
1092
|
+
: undefined;
|
|
1093
|
+
if (!session) {
|
|
1094
|
+
throw new UiWorkerManagerError("registry_inconsistent", "UI worker 注册成功, 但 session 索引未写入。 ");
|
|
1095
|
+
}
|
|
1096
|
+
return session;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/**
|
|
1101
|
+
* 按 session_info_changed 事件更新或清除 session display name。
|
|
1102
|
+
*
|
|
1103
|
+
* @param session 现有 session 索引。
|
|
1104
|
+
* @param name 新名称。
|
|
1105
|
+
* @param clearName 是否明确清除名称。
|
|
1106
|
+
* @returns 更新后的 session record。
|
|
1107
|
+
*/
|
|
1108
|
+
function applySessionName(
|
|
1109
|
+
session: SessionIndexRecord,
|
|
1110
|
+
name: string | undefined,
|
|
1111
|
+
clearName: boolean,
|
|
1112
|
+
): SessionIndexRecord {
|
|
1113
|
+
const updated = { ...session };
|
|
1114
|
+
if (clearName) {
|
|
1115
|
+
delete updated.name;
|
|
1116
|
+
} else if (name !== undefined) {
|
|
1117
|
+
updated.name = name;
|
|
1118
|
+
}
|
|
1119
|
+
return updated;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/**
|
|
1123
|
+
* 比较两个已解析项目路径, Windows 上忽略大小写。
|
|
1124
|
+
*
|
|
1125
|
+
* @param left 路径一。
|
|
1126
|
+
* @param right 路径二。
|
|
1127
|
+
* @returns 规范路径一致时返回 true。
|
|
1128
|
+
*/
|
|
1129
|
+
function samePath(left: string, right: string): boolean {
|
|
1130
|
+
const resolvedLeft = resolve(left);
|
|
1131
|
+
const resolvedRight = resolve(right);
|
|
1132
|
+
return process.platform === "win32"
|
|
1133
|
+
? resolvedLeft.toLowerCase() === resolvedRight.toLowerCase()
|
|
1134
|
+
: resolvedLeft === resolvedRight;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/**
|
|
1138
|
+
* 校验 UI bridge 发来的 worker state。
|
|
1139
|
+
*
|
|
1140
|
+
* @param value 任意事件字段。
|
|
1141
|
+
* @returns WorkerState union 成员时返回 true。
|
|
1142
|
+
*/
|
|
1143
|
+
function isWorkerState(value: unknown): value is WorkerState {
|
|
1144
|
+
return value === "starting" ||
|
|
1145
|
+
value === "idle" ||
|
|
1146
|
+
value === "running" ||
|
|
1147
|
+
value === "stopping" ||
|
|
1148
|
+
value === "stale";
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/**
|
|
1152
|
+
* 验证一个值是否是普通 JSON object。
|
|
1153
|
+
*
|
|
1154
|
+
* @param value 任意值。
|
|
1155
|
+
* @returns 非数组对象时返回 true。
|
|
1156
|
+
*/
|
|
1157
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1158
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* 检查 UI session transcript 是否已由 Pi 写入磁盘。
|
|
1163
|
+
*
|
|
1164
|
+
* @param sessionFile Pi session 文件路径。
|
|
1165
|
+
* @returns 普通文件存在时返回 true。
|
|
1166
|
+
*/
|
|
1167
|
+
async function isPersistedSessionFile(sessionFile: string): Promise<boolean> {
|
|
1168
|
+
try {
|
|
1169
|
+
return (await stat(sessionFile)).isFile();
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1172
|
+
return false;
|
|
1173
|
+
}
|
|
1174
|
+
throw error;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/**
|
|
1179
|
+
* 判断值是否为 Node.js 文件系统错误。
|
|
1180
|
+
*
|
|
1181
|
+
* @param error 任意错误。
|
|
1182
|
+
* @returns 包含 Node.js 错误代码时返回 true。
|
|
1183
|
+
*/
|
|
1184
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
1185
|
+
return error instanceof Error && "code" in error;
|
|
1186
|
+
}
|