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,339 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import type { PiCliInvocation } from "./pi-cli.ts";
|
|
4
|
+
import { GatewayControlClient, GatewayControlError } from "../gateway/gateway-control-ipc.ts";
|
|
5
|
+
import {
|
|
6
|
+
watchGatewayLifecycleOperation,
|
|
7
|
+
writeGatewayLifecycleOperationReceipt,
|
|
8
|
+
} from "./gateway-lifecycle-operation.ts";
|
|
9
|
+
|
|
10
|
+
const LIFECYCLE_RESPONSE_TIMEOUT_MS = 300000;
|
|
11
|
+
|
|
12
|
+
export type GatewayServiceState = "offline" | "starting" | "online" | "auth_required" | "stopping";
|
|
13
|
+
|
|
14
|
+
export interface GatewayServiceStatus {
|
|
15
|
+
state: GatewayServiceState;
|
|
16
|
+
pid?: number;
|
|
17
|
+
startedAt?: string;
|
|
18
|
+
foregroundSessionCount?: number;
|
|
19
|
+
backgroundSessionCount?: number;
|
|
20
|
+
routeCount?: number;
|
|
21
|
+
error?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface GatewayDaemonLaunchSpec {
|
|
25
|
+
managerDirectory: string;
|
|
26
|
+
extensionPath: string;
|
|
27
|
+
daemonEntry: string;
|
|
28
|
+
piInvocation: PiCliInvocation;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 控制一个独立于当前 Pi TUI 生命周期的 Gateway daemon。
|
|
33
|
+
*/
|
|
34
|
+
export class GatewayServiceController {
|
|
35
|
+
private readonly controlClient: GatewayControlClient;
|
|
36
|
+
private readonly launchDaemon: (spec: GatewayDaemonLaunchSpec) => Promise<void>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 创建后台 Gateway 控制器。
|
|
40
|
+
*
|
|
41
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
42
|
+
* @param launchSpec daemon 启动时需要的固定运行参数。
|
|
43
|
+
* @param options 可注入控制客户端和进程启动边界。
|
|
44
|
+
*/
|
|
45
|
+
constructor(
|
|
46
|
+
private readonly managerDirectory: string,
|
|
47
|
+
private readonly launchSpec: GatewayDaemonLaunchSpec,
|
|
48
|
+
options: {
|
|
49
|
+
controlClient?: GatewayControlClient;
|
|
50
|
+
launchDaemon?: (spec: GatewayDaemonLaunchSpec) => Promise<void>;
|
|
51
|
+
} = {},
|
|
52
|
+
) {
|
|
53
|
+
this.controlClient = options.controlClient ?? new GatewayControlClient(managerDirectory);
|
|
54
|
+
this.launchDaemon = options.launchDaemon ?? launchDetachedGatewayDaemon;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 查询真实后台进程和 Gateway 状态。
|
|
59
|
+
*
|
|
60
|
+
* @returns IPC 服务提供的活动状态; 控制通道离线时返回 offline。
|
|
61
|
+
* @throws {GatewayControlError} 身份校验或状态协议不可信时抛出。
|
|
62
|
+
*/
|
|
63
|
+
async status(): Promise<GatewayServiceStatus> {
|
|
64
|
+
try {
|
|
65
|
+
const response = await this.controlClient.request("status");
|
|
66
|
+
return parseServiceStatus(response);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error instanceof GatewayControlError && error.code === "not_running") {
|
|
69
|
+
return { state: "offline" };
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 幂等启动后台 Gateway daemon。
|
|
77
|
+
*
|
|
78
|
+
* @returns 已存在或新启动服务的状态。
|
|
79
|
+
* @throws {Error} daemon 启动失败且没有可用的现有服务时抛出。
|
|
80
|
+
*/
|
|
81
|
+
async start(): Promise<GatewayServiceStatus> {
|
|
82
|
+
const current = await this.status();
|
|
83
|
+
if (current.state !== "offline") {
|
|
84
|
+
return current;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
await this.launchDaemon(this.launchSpec);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
const concurrentlyStarted = await this.status().catch(() => ({ state: "offline" as const }));
|
|
90
|
+
if (concurrentlyStarted.state !== "offline") {
|
|
91
|
+
return concurrentlyStarted;
|
|
92
|
+
}
|
|
93
|
+
throw error instanceof GatewayControlError
|
|
94
|
+
? error
|
|
95
|
+
: new GatewayControlError(
|
|
96
|
+
"request_failed",
|
|
97
|
+
error instanceof Error ? error.message : "后台 Gateway 启动失败, 请检查配置和微信授权。",
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return this.status();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 请求后台 Gateway 在安全停止窗口内优雅退出。
|
|
105
|
+
*
|
|
106
|
+
* @returns Gateway 停止并释放控制租约后的最终状态。
|
|
107
|
+
* @throws {GatewayControlError} Gateway 离线或无法认证时抛出。
|
|
108
|
+
*/
|
|
109
|
+
async stop(): Promise<GatewayServiceStatus> {
|
|
110
|
+
const current = await this.status();
|
|
111
|
+
if (current.state === "offline") {
|
|
112
|
+
return current;
|
|
113
|
+
}
|
|
114
|
+
return parseServiceStatus(await this.controlClient.request("stop", {
|
|
115
|
+
responseTimeoutMs: LIFECYCLE_RESPONSE_TIMEOUT_MS,
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 请求后台 Gateway 安全停止当前 daemon 并启动新 daemon, 等待新服务就绪。
|
|
121
|
+
*
|
|
122
|
+
* @returns 新 Gateway 启动就绪后的最终状态。
|
|
123
|
+
* @throws {GatewayControlError} Gateway 离线或无法认证时抛出。
|
|
124
|
+
*/
|
|
125
|
+
async restart(): Promise<GatewayServiceStatus> {
|
|
126
|
+
const current = await this.status();
|
|
127
|
+
if (current.state === "offline") {
|
|
128
|
+
return this.start();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const operationId = randomUUID();
|
|
132
|
+
const watcher = await watchGatewayLifecycleOperation(this.managerDirectory, operationId);
|
|
133
|
+
let operationAccepted = false;
|
|
134
|
+
let receiptRead = false;
|
|
135
|
+
try {
|
|
136
|
+
await writeGatewayLifecycleOperationReceipt(this.managerDirectory, {
|
|
137
|
+
action: "restart",
|
|
138
|
+
operationId,
|
|
139
|
+
state: "pending",
|
|
140
|
+
});
|
|
141
|
+
const accepted = await this.controlClient.request("restart", { operationId });
|
|
142
|
+
if (
|
|
143
|
+
!isRecord(accepted) ||
|
|
144
|
+
accepted.state !== "stopping" ||
|
|
145
|
+
(accepted.operationId !== undefined && accepted.operationId !== operationId)
|
|
146
|
+
) {
|
|
147
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 未确认重启操作。 ");
|
|
148
|
+
}
|
|
149
|
+
operationAccepted = true;
|
|
150
|
+
const receipt = await watcher.wait(LIFECYCLE_RESPONSE_TIMEOUT_MS).catch((error: unknown) => {
|
|
151
|
+
throw new GatewayControlError(
|
|
152
|
+
"timeout",
|
|
153
|
+
error instanceof Error ? error.message : "等待后台 Gateway 重启结果超时。",
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
receiptRead = true;
|
|
157
|
+
if (receipt.state === "failed") {
|
|
158
|
+
throw new GatewayControlError(
|
|
159
|
+
"request_failed",
|
|
160
|
+
receipt.message ?? "后台 Gateway 重启失败; 请执行 /wx status 查看当前状态。",
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
if (!receipt.serviceStatus) {
|
|
164
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 重启结果缺少最终状态。 ");
|
|
165
|
+
}
|
|
166
|
+
return parseServiceStatus(receipt.serviceStatus);
|
|
167
|
+
} finally {
|
|
168
|
+
watcher.close();
|
|
169
|
+
if (receiptRead || !operationAccepted) {
|
|
170
|
+
await watcher.removeReceipt().catch(() => undefined);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 将已验证的 daemon 启动参数编码为 Node CLI payload。
|
|
178
|
+
*
|
|
179
|
+
* @param spec daemon 启动参数。
|
|
180
|
+
* @returns 不含 shell 解释的 base64url JSON。
|
|
181
|
+
*/
|
|
182
|
+
export function encodeGatewayDaemonLaunchSpec(spec: GatewayDaemonLaunchSpec): string {
|
|
183
|
+
return Buffer.from(JSON.stringify(spec), "utf8").toString("base64url");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 解码并验证 daemon 启动 payload。
|
|
188
|
+
*
|
|
189
|
+
* @param encoded base64url JSON 字符串。
|
|
190
|
+
* @returns 已验证启动参数。
|
|
191
|
+
* @throws {Error} payload 格式或路径字段无效时抛出。
|
|
192
|
+
*/
|
|
193
|
+
export function decodeGatewayDaemonLaunchSpec(encoded: string): GatewayDaemonLaunchSpec {
|
|
194
|
+
let parsed: unknown;
|
|
195
|
+
try {
|
|
196
|
+
parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as unknown;
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error("后台 Gateway 启动参数编码无效。");
|
|
199
|
+
}
|
|
200
|
+
if (!isRecord(parsed) || !isAbsolutePath(parsed.managerDirectory) ||
|
|
201
|
+
!isAbsolutePath(parsed.extensionPath) || !isAbsolutePath(parsed.daemonEntry) ||
|
|
202
|
+
!isRecord(parsed.piInvocation) || !isAbsolutePath(parsed.piInvocation.command) ||
|
|
203
|
+
!Array.isArray(parsed.piInvocation.args) ||
|
|
204
|
+
!parsed.piInvocation.args.every((argument) => typeof argument === "string")) {
|
|
205
|
+
throw new Error("后台 Gateway 启动参数字段无效。");
|
|
206
|
+
}
|
|
207
|
+
return parsed as unknown as GatewayDaemonLaunchSpec;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 通过独立进程启动 Gateway daemon, 并等待本机控制 endpoint ready。
|
|
212
|
+
*
|
|
213
|
+
* @param spec daemon 启动参数。
|
|
214
|
+
* @returns daemon 已开始持有服务进程时正常结束。
|
|
215
|
+
* @throws {Error} 子进程无法创建、提前退出或未能及时 ready 时抛出。
|
|
216
|
+
*/
|
|
217
|
+
export async function launchDetachedGatewayDaemon(spec: GatewayDaemonLaunchSpec): Promise<void> {
|
|
218
|
+
const encoded = encodeGatewayDaemonLaunchSpec(spec);
|
|
219
|
+
const args = [
|
|
220
|
+
"--experimental-transform-types",
|
|
221
|
+
spec.daemonEntry,
|
|
222
|
+
"--launch-payload",
|
|
223
|
+
encoded,
|
|
224
|
+
];
|
|
225
|
+
const child = spawn(spec.piInvocation.command, args, {
|
|
226
|
+
detached: true,
|
|
227
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
228
|
+
windowsHide: true,
|
|
229
|
+
env: {
|
|
230
|
+
...process.env,
|
|
231
|
+
PI_WECHAT_HUB_DAEMON: "1",
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
child.unref();
|
|
235
|
+
|
|
236
|
+
await new Promise<void>((resolveLaunch, rejectLaunch) => {
|
|
237
|
+
let settled = false;
|
|
238
|
+
const timeout = setTimeout(() => finish(new Error("后台 Gateway 启动超时, 请使用 /wx status 检查。")), 30000);
|
|
239
|
+
timeout.unref();
|
|
240
|
+
const cleanup = (): void => {
|
|
241
|
+
clearTimeout(timeout);
|
|
242
|
+
child.off("message", onMessage);
|
|
243
|
+
child.off("error", onError);
|
|
244
|
+
child.off("exit", onExit);
|
|
245
|
+
};
|
|
246
|
+
const finish = (error?: Error): void => {
|
|
247
|
+
if (settled) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
settled = true;
|
|
251
|
+
cleanup();
|
|
252
|
+
if (child.connected) {
|
|
253
|
+
child.disconnect();
|
|
254
|
+
}
|
|
255
|
+
if (error) {
|
|
256
|
+
rejectLaunch(error);
|
|
257
|
+
} else {
|
|
258
|
+
resolveLaunch();
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
const onMessage = (message: unknown): void => {
|
|
262
|
+
if (!isRecord(message)) {
|
|
263
|
+
finish(new Error("后台 Gateway 启动握手响应无效。"));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (message.kind === "ready") {
|
|
267
|
+
finish();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (message.kind === "failed") {
|
|
271
|
+
finish(new Error(typeof message.message === "string" ? message.message : "后台 Gateway 启动失败。"));
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
const onError = (): void => finish(new Error("无法创建后台 Gateway 进程。"));
|
|
275
|
+
const onExit = (code: number | null): void => {
|
|
276
|
+
finish(new Error(`后台 Gateway 在 ready 前退出 (code ${code ?? "unknown"})。`));
|
|
277
|
+
};
|
|
278
|
+
child.on("message", onMessage);
|
|
279
|
+
child.once("error", onError);
|
|
280
|
+
child.once("exit", onExit);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* 解析并校验 daemon 返回的状态对象。
|
|
286
|
+
*
|
|
287
|
+
* @param value 未知 IPC response payload。
|
|
288
|
+
* @returns Gateway service 状态。
|
|
289
|
+
* @throws {GatewayControlError} 状态字段不受支持时抛出。
|
|
290
|
+
*/
|
|
291
|
+
function parseServiceStatus(value: unknown): GatewayServiceStatus {
|
|
292
|
+
if (!isRecord(value) || !isGatewayServiceState(value.state)) {
|
|
293
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 状态响应字段无效。");
|
|
294
|
+
}
|
|
295
|
+
const numericFields = ["pid", "foregroundSessionCount", "backgroundSessionCount", "routeCount"] as const;
|
|
296
|
+
for (const field of numericFields) {
|
|
297
|
+
if (value[field] !== undefined && (!Number.isSafeInteger(value[field]) || (value[field] as number) < 0)) {
|
|
298
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 状态计数字段无效。");
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (value.startedAt !== undefined && typeof value.startedAt !== "string") {
|
|
302
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 启动时间字段无效。");
|
|
303
|
+
}
|
|
304
|
+
if (value.error !== undefined && typeof value.error !== "string") {
|
|
305
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway 状态错误字段无效。");
|
|
306
|
+
}
|
|
307
|
+
return value as unknown as GatewayServiceStatus;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* 判断状态值是否为受支持的 Gateway lifecycle state。
|
|
312
|
+
*
|
|
313
|
+
* @param value 未知状态字段。
|
|
314
|
+
* @returns 状态受支持时返回 true。
|
|
315
|
+
*/
|
|
316
|
+
function isGatewayServiceState(value: unknown): value is GatewayServiceState {
|
|
317
|
+
return value === "offline" || value === "starting" || value === "online" ||
|
|
318
|
+
value === "auth_required" || value === "stopping";
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* 判断值是否为普通对象。
|
|
323
|
+
*
|
|
324
|
+
* @param value 待校验值。
|
|
325
|
+
* @returns 普通对象时返回 true。
|
|
326
|
+
*/
|
|
327
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
328
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 判断路径是否为绝对路径。
|
|
333
|
+
*
|
|
334
|
+
* @param value 待校验字段。
|
|
335
|
+
* @returns 绝对路径字符串时返回 true。
|
|
336
|
+
*/
|
|
337
|
+
function isAbsolutePath(value: unknown): value is string {
|
|
338
|
+
return typeof value === "string" && (value.startsWith("/") || /^[a-z]:[\\/]/i.test(value));
|
|
339
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import type { RuntimeMode } from "../config/types.ts";
|
|
2
|
+
import { ManagerRegistry } from "../registry/manager-registry.ts";
|
|
3
|
+
import type { SessionIndexRecord, WorkerInstanceRecord } from "../registry/types.ts";
|
|
4
|
+
import { BackgroundWorkerManager, BackgroundWorkerManagerError } from "./background-worker-manager.ts";
|
|
5
|
+
import { UiWorkerManager } from "./ui-worker-manager.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Gateway router 所需的统一 Pi worker 生命周期接口。
|
|
9
|
+
*/
|
|
10
|
+
export interface GatewayWorkerService {
|
|
11
|
+
startNew(projectAlias: string, name?: string, mode?: RuntimeMode): Promise<SessionIndexRecord>;
|
|
12
|
+
resume(sessionId: string, mode?: RuntimeMode): Promise<SessionIndexRecord>;
|
|
13
|
+
prompt(sessionId: string, message: string): Promise<string>;
|
|
14
|
+
stop(sessionId: string, abortRunning?: boolean): Promise<void>;
|
|
15
|
+
stopAll(): Promise<void>;
|
|
16
|
+
listSessions(): Promise<SessionIndexRecord[]>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 根据 registry owner mode 将 route 操作分发给 background 或 UI worker manager。
|
|
21
|
+
*/
|
|
22
|
+
export class GatewayWorkerManager implements GatewayWorkerService {
|
|
23
|
+
/**
|
|
24
|
+
* 创建跨模式的 worker manager facade。
|
|
25
|
+
*
|
|
26
|
+
* @param background 后台 Pi RPC worker manager。
|
|
27
|
+
* @param ui 可见 Pi TUI worker manager。
|
|
28
|
+
* @param registry session owner registry。
|
|
29
|
+
*/
|
|
30
|
+
constructor(
|
|
31
|
+
private readonly background: BackgroundWorkerManager,
|
|
32
|
+
private readonly ui: UiWorkerManager,
|
|
33
|
+
private readonly registry: ManagerRegistry,
|
|
34
|
+
) {}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 按请求模式创建一个 Pi session。
|
|
38
|
+
*
|
|
39
|
+
* @param projectAlias 已登记项目 alias。
|
|
40
|
+
* @param name 可选显示名称。
|
|
41
|
+
* @param mode background 或 ui, 缺省按配置选择。
|
|
42
|
+
* @returns 新创建 session 索引。
|
|
43
|
+
*/
|
|
44
|
+
async startNew(
|
|
45
|
+
projectAlias: string,
|
|
46
|
+
name?: string,
|
|
47
|
+
mode: RuntimeMode = "background",
|
|
48
|
+
): Promise<SessionIndexRecord> {
|
|
49
|
+
if (mode === "ui") {
|
|
50
|
+
return this.ui.startNew(projectAlias, name);
|
|
51
|
+
}
|
|
52
|
+
return this.background.startNew(projectAlias, name);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 按显式 mode 或当前活跃 owner 模式恢复 Pi session; 没有 UI owner 时恢复到后台。
|
|
57
|
+
*
|
|
58
|
+
* @param sessionId Pi session ID。
|
|
59
|
+
* @param mode 可选强制恢复模式。
|
|
60
|
+
* @returns 已恢复或已绑定的 session。
|
|
61
|
+
*/
|
|
62
|
+
async resume(sessionId: string, mode?: RuntimeMode): Promise<SessionIndexRecord> {
|
|
63
|
+
const snapshot = await this.registry.readSnapshot();
|
|
64
|
+
const session = snapshot.sessions[sessionId];
|
|
65
|
+
if (!session) {
|
|
66
|
+
return this.background.resume(sessionId);
|
|
67
|
+
}
|
|
68
|
+
const owner = findOwner(snapshot, sessionId);
|
|
69
|
+
const requestedMode = mode ?? (owner?.mode ?? "background");
|
|
70
|
+
if (owner) {
|
|
71
|
+
if (owner.mode === requestedMode && this.hasAvailableOwner(owner)) {
|
|
72
|
+
return session;
|
|
73
|
+
}
|
|
74
|
+
throw new BackgroundWorkerManagerError(
|
|
75
|
+
"session_owned_by_other_process",
|
|
76
|
+
`session ${sessionId} 当前由 ${owner.mode} runtime 持有; 先停止 owner 后再切换模式。`,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
if (requestedMode === "ui") {
|
|
80
|
+
return this.ui.resume(sessionId);
|
|
81
|
+
}
|
|
82
|
+
return this.background.resume(sessionId);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 根据 registry owner 模式向 Pi session 投递消息。
|
|
87
|
+
*
|
|
88
|
+
* @param sessionId Pi session ID。
|
|
89
|
+
* @param message 用户消息正文。
|
|
90
|
+
* @returns 最终 assistant 回复文本。
|
|
91
|
+
*/
|
|
92
|
+
async prompt(sessionId: string, message: string): Promise<string> {
|
|
93
|
+
const snapshot = await this.registry.readSnapshot();
|
|
94
|
+
const owner = findOwner(snapshot, sessionId);
|
|
95
|
+
if (!owner) {
|
|
96
|
+
throw new BackgroundWorkerManagerError(
|
|
97
|
+
"worker_not_found",
|
|
98
|
+
`session ${sessionId} 当前没有活跃 Pi worker owner。`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (owner.mode === "ui") {
|
|
102
|
+
return this.ui.prompt(sessionId, message);
|
|
103
|
+
}
|
|
104
|
+
return this.background.prompt(sessionId, message);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 停止一个 session 当前的 runtime owner。
|
|
109
|
+
*
|
|
110
|
+
* @param sessionId Pi session ID。
|
|
111
|
+
* @param abortRunning 是否明确允许 abort 正在运行的 turn。
|
|
112
|
+
* @returns 无返回值。
|
|
113
|
+
*/
|
|
114
|
+
async stop(sessionId: string, abortRunning = false): Promise<void> {
|
|
115
|
+
const snapshot = await this.registry.readSnapshot();
|
|
116
|
+
const owner = findOwner(snapshot, sessionId);
|
|
117
|
+
if (!owner) {
|
|
118
|
+
throw new BackgroundWorkerManagerError(
|
|
119
|
+
"worker_not_found",
|
|
120
|
+
`session ${sessionId} 当前没有活跃 Pi worker owner。`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
if (owner.mode === "ui") {
|
|
124
|
+
await this.ui.stop(sessionId, abortRunning);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
await this.background.stop(sessionId, abortRunning);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 只停止由 Gateway 管理的 background 子进程, UI tab 在 Gateway 停止时可断线后重连。
|
|
132
|
+
*
|
|
133
|
+
* @returns background worker 全部停止时正常结束。
|
|
134
|
+
*/
|
|
135
|
+
async stopAll(): Promise<void> {
|
|
136
|
+
await this.background.stopAll();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 列出 registry 中的全部 Pi session。
|
|
141
|
+
*
|
|
142
|
+
* @returns 按最近活动时间倒序排列的 session。
|
|
143
|
+
*/
|
|
144
|
+
async listSessions(): Promise<SessionIndexRecord[]> {
|
|
145
|
+
const snapshot = await this.registry.readSnapshot();
|
|
146
|
+
return Object.values(snapshot.sessions).sort((left, right) =>
|
|
147
|
+
right.lastActivityAt.localeCompare(left.lastActivityAt),
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 判断 registry owner 是否由当前 Gateway manager 持有可用连接。
|
|
153
|
+
*
|
|
154
|
+
* @param instance worker owner 记录。
|
|
155
|
+
* @returns 运行态且当前 manager 可向其投递时返回 true。
|
|
156
|
+
*/
|
|
157
|
+
hasAvailableOwner(instance: WorkerInstanceRecord): boolean {
|
|
158
|
+
if (instance.state === "stale" || instance.state === "stopping") {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
return instance.mode === "background"
|
|
162
|
+
? this.background.hasWorker(instance.sessionId)
|
|
163
|
+
: this.ui.hasConnection(instance.instanceId);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 查找 session 当前唯一的活跃 registry owner。
|
|
169
|
+
*
|
|
170
|
+
* @param snapshot registry 快照。
|
|
171
|
+
* @param sessionId Pi session ID。
|
|
172
|
+
* @returns 非 stale/stopping owner 或 undefined。
|
|
173
|
+
*/
|
|
174
|
+
function findOwner(
|
|
175
|
+
snapshot: Awaited<ReturnType<ManagerRegistry["readSnapshot"]>>,
|
|
176
|
+
sessionId: string,
|
|
177
|
+
): WorkerInstanceRecord | undefined {
|
|
178
|
+
return Object.values(snapshot.instances).find((instance) =>
|
|
179
|
+
instance.sessionId === sessionId && instance.state !== "stale" && instance.state !== "stopping",
|
|
180
|
+
);
|
|
181
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
export interface PiCliInvocation {
|
|
5
|
+
command: string;
|
|
6
|
+
args: string[];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 表示当前 Pi CLI 入口无法被安全解析。
|
|
11
|
+
*/
|
|
12
|
+
export class PiCliUnavailableError extends Error {
|
|
13
|
+
/**
|
|
14
|
+
* 创建 Pi CLI 入口错误。
|
|
15
|
+
*
|
|
16
|
+
* @param message 面向用户的中文错误信息。
|
|
17
|
+
*/
|
|
18
|
+
constructor(message: string) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "PiCliUnavailableError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 解析当前运行中 Pi 进程的 CLI JavaScript 入口, 避免从 PATH 启动另一个版本。
|
|
26
|
+
*
|
|
27
|
+
* @param argv Pi 进程的 argv。
|
|
28
|
+
* @param runtimeExecutable Node.js 可执行文件路径。
|
|
29
|
+
* @returns 不经过 shell 的 Node 命令及固定入口参数。
|
|
30
|
+
* @throws {PiCliUnavailableError} CLI 入口不存在或不是文件时抛出。
|
|
31
|
+
*/
|
|
32
|
+
export function resolveCurrentPiCli(
|
|
33
|
+
argv = process.argv,
|
|
34
|
+
runtimeExecutable = process.execPath,
|
|
35
|
+
): PiCliInvocation {
|
|
36
|
+
const entry = argv[1];
|
|
37
|
+
if (!entry) {
|
|
38
|
+
throw new PiCliUnavailableError(
|
|
39
|
+
"无法确定当前 Pi CLI 入口; 请通过 Node.js 安装版 Pi 启动会话。",
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const cliEntry = isAbsolute(entry) ? entry : resolve(entry);
|
|
43
|
+
try {
|
|
44
|
+
if (!existsSync(cliEntry) || !statSync(cliEntry).isFile()) {
|
|
45
|
+
throw new Error("not_file");
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
throw new PiCliUnavailableError(
|
|
49
|
+
"当前 Pi CLI 入口不可用; 为避免误用 PATH 中的其他版本, 已拒绝启动后台 worker。",
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
command: runtimeExecutable,
|
|
54
|
+
args: [cliEntry],
|
|
55
|
+
};
|
|
56
|
+
}
|