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.
Files changed (51) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +365 -0
  3. package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
  4. package/docs/handoff-next-session.md +134 -0
  5. package/docs/implementation-spec.md +147 -0
  6. package/extensions/wechat-session-hub.ts +589 -0
  7. package/package.json +67 -0
  8. package/scripts/pi-rpc-smoke.mjs +150 -0
  9. package/scripts/probe-wt-capability.mjs +27 -0
  10. package/scripts/start-ui-worker.ps1 +37 -0
  11. package/src/commands/ilink-qr-login-component.ts +148 -0
  12. package/src/commands/project-command-parser.ts +108 -0
  13. package/src/commands/tokenizer.ts +71 -0
  14. package/src/commands/wechat-manager-command-parser.ts +143 -0
  15. package/src/config/defaults.ts +30 -0
  16. package/src/config/paths.ts +56 -0
  17. package/src/config/store.ts +311 -0
  18. package/src/config/types.ts +33 -0
  19. package/src/config/validation.ts +221 -0
  20. package/src/gateway/channel-types.ts +47 -0
  21. package/src/gateway/command-parser.ts +291 -0
  22. package/src/gateway/command-router.ts +1449 -0
  23. package/src/gateway/credential-store.ts +611 -0
  24. package/src/gateway/durable-message-queue.ts +1043 -0
  25. package/src/gateway/gateway-control-ipc.ts +687 -0
  26. package/src/gateway/gateway-runtime.ts +726 -0
  27. package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
  28. package/src/gateway/ui-worker-ipc.ts +1483 -0
  29. package/src/gateway/ui-worker-types.ts +50 -0
  30. package/src/gateway/wechat-ilink/api-client.ts +390 -0
  31. package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
  32. package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
  33. package/src/gateway/wechat-ilink/qr-login.ts +612 -0
  34. package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
  35. package/src/gateway/windows-terminal-launcher.ts +247 -0
  36. package/src/projects/project-service.ts +483 -0
  37. package/src/registry/gateway-lease.ts +348 -0
  38. package/src/registry/manager-registry.ts +466 -0
  39. package/src/registry/types.ts +61 -0
  40. package/src/runtime/background-pi-worker.ts +309 -0
  41. package/src/runtime/background-worker-manager.ts +594 -0
  42. package/src/runtime/gateway-daemon.ts +281 -0
  43. package/src/runtime/gateway-lifecycle-operation.ts +308 -0
  44. package/src/runtime/gateway-service-controller.ts +339 -0
  45. package/src/runtime/gateway-worker-manager.ts +181 -0
  46. package/src/runtime/pi-cli.ts +56 -0
  47. package/src/runtime/pi-rpc-client.ts +427 -0
  48. package/src/runtime/ui-worker-manager.ts +1186 -0
  49. package/src/runtime/windows-logon-task-manager.ts +212 -0
  50. package/src/system/process-liveness.ts +88 -0
  51. package/tsconfig.json +19 -0
@@ -0,0 +1,281 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { ConfigurationStore } from "../config/store.ts";
4
+ import { ManagerRegistry } from "../registry/manager-registry.ts";
5
+ import { ProjectService } from "../projects/project-service.ts";
6
+ import { GatewayRuntime } from "../gateway/gateway-runtime.ts";
7
+ import {
8
+ GatewayControlClient,
9
+ GatewayControlError,
10
+ GatewayControlServer,
11
+ type GatewayControlAction,
12
+ } from "../gateway/gateway-control-ipc.ts";
13
+ import {
14
+ decodeGatewayDaemonLaunchSpec,
15
+ launchDetachedGatewayDaemon,
16
+ type GatewayDaemonLaunchSpec,
17
+ type GatewayServiceState,
18
+ type GatewayServiceStatus,
19
+ } from "./gateway-service-controller.ts";
20
+ import {
21
+ completePendingGatewayLifecycleOperations,
22
+ writeGatewayLifecycleOperationReceipt,
23
+ } from "./gateway-lifecycle-operation.ts";
24
+
25
+ interface GatewayDaemonProcessChannel {
26
+ send?: (message: unknown, callback?: (error: Error | null) => void) => boolean;
27
+ disconnect?: () => void;
28
+ }
29
+
30
+ /**
31
+ * 启动独立的 Hub daemon, 由它持有 Gateway lease 和微信 poller。
32
+ *
33
+ * @returns Gateway 正常停止或启动失败后结束。
34
+ */
35
+ export async function runGatewayDaemon(): Promise<void> {
36
+ const launchSpec = readLaunchSpec(process.argv.slice(2));
37
+ const managerDirectory = resolve(launchSpec.managerDirectory);
38
+ const agentDirectory = dirname(managerDirectory);
39
+ const configStore = new ConfigurationStore(
40
+ join(agentDirectory, "wechat-session-manager.json"),
41
+ join(managerDirectory, "credentials.json"),
42
+ );
43
+ const projectService = new ProjectService(configStore);
44
+ const workerEnvironment = {
45
+ ...process.env,
46
+ PI_CODING_AGENT_DIR: agentDirectory,
47
+ PI_WECHAT_HUB_DAEMON: "1",
48
+ };
49
+ let serviceState: GatewayServiceState = "starting";
50
+ let runtimeStart: Promise<GatewayRuntime> | undefined;
51
+ let runtime: GatewayRuntime | undefined;
52
+ let controlServer: GatewayControlServer | undefined;
53
+ let registry: ManagerRegistry | undefined;
54
+ let restartOperationId: string | undefined;
55
+ let restartTask: Promise<void> | undefined;
56
+ let readySent = false;
57
+
58
+ runtimeStart = GatewayRuntime.start({
59
+ dataDirectory: managerDirectory,
60
+ configStore,
61
+ projectService,
62
+ invocation: launchSpec.piInvocation,
63
+ extensionPath: launchSpec.extensionPath,
64
+ env: workerEnvironment,
65
+ onControlReady: async (lease, gatewayRegistry) => {
66
+ registry = gatewayRegistry;
67
+ controlServer = new GatewayControlServer(managerDirectory, lease, {
68
+ handleAction: async (action, operationId) => handleControlAction(action, operationId),
69
+ afterActionResponse: async (action, operationId) => {
70
+ if (action === "stop" && serviceState === "offline") {
71
+ const currentControlServer = controlServer;
72
+ controlServer = undefined;
73
+ await currentControlServer?.close();
74
+ } else if (action === "restart") {
75
+ const currentOperationId = operationId ?? restartOperationId;
76
+ if (currentOperationId) {
77
+ await beginRestart(currentOperationId);
78
+ }
79
+ }
80
+ },
81
+ });
82
+ await controlServer.listen();
83
+ },
84
+ });
85
+
86
+ try {
87
+ runtime = await runtimeStart;
88
+ serviceState = toGatewayServiceState(runtime.status);
89
+ runtime.on("status_change", (state: string) => {
90
+ serviceState = toGatewayServiceState(state);
91
+ });
92
+ await completePendingGatewayLifecycleOperations(managerDirectory, {
93
+ state: serviceState,
94
+ pid: process.pid,
95
+ }).catch(() => undefined);
96
+ readySent = true;
97
+ notifyParent({ kind: "ready" });
98
+ } catch (error) {
99
+ await completePendingGatewayLifecycleOperations(
100
+ managerDirectory,
101
+ { state: "offline" },
102
+ toSafeStartupMessage(error),
103
+ ).catch(() => undefined);
104
+ if (!readySent) {
105
+ notifyParent({ kind: "failed", message: toSafeStartupMessage(error) });
106
+ }
107
+ await controlServer?.close().catch(() => undefined);
108
+ controlServer = undefined;
109
+ process.exitCode = 1;
110
+ }
111
+
112
+ async function handleControlAction(
113
+ action: GatewayControlAction,
114
+ operationId?: string,
115
+ ): Promise<unknown> {
116
+ if (action === "stop") {
117
+ if (restartOperationId || serviceState === "stopping") {
118
+ throw new GatewayControlError("request_failed", "后台 Gateway 正在执行其他生命周期操作, 请稍后重试。");
119
+ }
120
+ serviceState = "stopping";
121
+ const currentRuntime = runtime ?? await runtimeStart;
122
+ try {
123
+ await currentRuntime?.stop();
124
+ } catch {
125
+ serviceState = currentRuntime ? toGatewayServiceState(currentRuntime.status) : "offline";
126
+ throw new GatewayControlError(
127
+ "request_failed",
128
+ "后台 Gateway 未能安全停止; 请执行 /wx status 查看当前状态。",
129
+ );
130
+ }
131
+ runtime = undefined;
132
+ serviceState = "offline";
133
+ return { state: "offline" };
134
+ }
135
+ if (action === "restart") {
136
+ if (restartOperationId || serviceState === "stopping") {
137
+ throw new GatewayControlError("request_failed", "后台 Gateway 正在执行其他生命周期操作, 请稍后重试。");
138
+ }
139
+ const currentOperationId = operationId ?? randomUUID();
140
+ if (!operationId) {
141
+ await writeGatewayLifecycleOperationReceipt(managerDirectory, {
142
+ action: "restart",
143
+ operationId: currentOperationId,
144
+ state: "pending",
145
+ });
146
+ }
147
+ restartOperationId = currentOperationId;
148
+ serviceState = "stopping";
149
+ return { state: "stopping", operationId: currentOperationId };
150
+ }
151
+ if (serviceState === "stopping" || serviceState === "offline") {
152
+ return { state: serviceState, pid: process.pid };
153
+ }
154
+ return buildStatus(serviceState);
155
+ }
156
+
157
+ async function beginRestart(operationId: string): Promise<void> {
158
+ if (restartTask) {
159
+ return restartTask;
160
+ }
161
+ restartTask = (async () => {
162
+ let oldControlServerClosed = false;
163
+ try {
164
+ const currentRuntime = runtime ?? await runtimeStart;
165
+ await currentRuntime?.stop();
166
+ runtime = undefined;
167
+ serviceState = "offline";
168
+ const currentControlServer = controlServer;
169
+ controlServer = undefined;
170
+ await currentControlServer?.close();
171
+ oldControlServerClosed = true;
172
+ await launchDetachedGatewayDaemon(launchSpec);
173
+ const serviceStatus = await new GatewayControlClient(managerDirectory).request("status") as GatewayServiceStatus;
174
+ serviceState = serviceStatus.state;
175
+ await completePendingGatewayLifecycleOperations(
176
+ managerDirectory,
177
+ serviceStatus,
178
+ undefined,
179
+ operationId,
180
+ );
181
+ } catch (error) {
182
+ const message = error instanceof GatewayControlError
183
+ ? error.message
184
+ : "后台 Gateway 重启失败; 请执行 /wx status 查看当前状态。";
185
+ const serviceStatus: GatewayServiceStatus = oldControlServerClosed
186
+ ? { state: "offline" }
187
+ : { state: serviceState };
188
+ await completePendingGatewayLifecycleOperations(
189
+ managerDirectory,
190
+ serviceStatus,
191
+ message,
192
+ operationId,
193
+ ).catch(() => undefined);
194
+ if (oldControlServerClosed) {
195
+ process.exitCode = 1;
196
+ }
197
+ } finally {
198
+ restartOperationId = undefined;
199
+ restartTask = undefined;
200
+ }
201
+ })();
202
+ return restartTask;
203
+ }
204
+
205
+ async function buildStatus(state: GatewayServiceState): Promise<Record<string, unknown>> {
206
+ const snapshot = await registry?.readSnapshot();
207
+ const liveInstances = Object.values(snapshot?.instances ?? {}).filter((instance) =>
208
+ instance.state !== "stale" && instance.state !== "stopping",
209
+ );
210
+ return {
211
+ state,
212
+ pid: process.pid,
213
+ startedAt: snapshot?.gateway?.startedAt,
214
+ foregroundSessionCount: liveInstances.filter((instance) => instance.mode === "ui").length,
215
+ backgroundSessionCount: liveInstances.filter((instance) => instance.mode === "background").length,
216
+ routeCount: Object.keys(snapshot?.routes ?? {}).length,
217
+ };
218
+ }
219
+ }
220
+
221
+ /**
222
+ * 从固定 CLI 参数读取并校验 daemon launch payload。
223
+ *
224
+ * @param args daemon 启动参数。
225
+ * @returns 已校验 launch spec。
226
+ * @throws {Error} CLI 参数不是固定 payload 格式时抛出。
227
+ */
228
+ function readLaunchSpec(args: string[]): GatewayDaemonLaunchSpec {
229
+ if (args.length !== 2 || args[0] !== "--launch-payload") {
230
+ throw new Error("后台 Gateway 只接受受控 launch payload。");
231
+ }
232
+ return decodeGatewayDaemonLaunchSpec(args[1]);
233
+ }
234
+
235
+ /**
236
+ * 向通过 Node IPC 启动的父进程报告 ready 或安全启动错误。
237
+ *
238
+ * @param message 不含凭证或消息正文的握手消息。
239
+ * @returns 当前进程不受父 IPC 管道管理时正常结束。
240
+ */
241
+ function notifyParent(message: Record<string, unknown>): void {
242
+ const childProcess = process as unknown as GatewayDaemonProcessChannel;
243
+ if (typeof childProcess.send !== "function") {
244
+ return;
245
+ }
246
+ childProcess.send(message, () => childProcess.disconnect?.());
247
+ }
248
+
249
+ /**
250
+ * 将 Gateway runtime 状态缩窄为对外状态枚举。
251
+ *
252
+ * @param value runtime 状态字符串。
253
+ * @returns 可公开状态时返回 true。
254
+ */
255
+ function toGatewayServiceState(value: string): GatewayServiceState {
256
+ if (value === "offline" || value === "starting" || value === "online" ||
257
+ value === "auth_required" || value === "stopping") {
258
+ return value;
259
+ }
260
+ return value === "stopped" ? "offline" : "stopping";
261
+ }
262
+
263
+ /**
264
+ * 将启动错误转换为不泄露配置、路径或凭证的简短说明。
265
+ *
266
+ * @param error runtime 初始化异常。
267
+ * @returns 安全的中文错误文本。
268
+ */
269
+ function toSafeStartupMessage(error: unknown): string {
270
+ if (error instanceof Error && /configuration_incomplete|credential|授权|凭证/.test(error.message)) {
271
+ return "后台 Gateway 尚未具备有效微信授权, 请先在 Pi TUI 执行 /wx login。";
272
+ }
273
+ return "后台 Gateway 启动失败, 请检查配置、授权和会话 owner 状态。";
274
+ }
275
+
276
+ if (process.env.PI_WECHAT_HUB_DAEMON === "1" || process.argv.includes("--launch-payload")) {
277
+ void runGatewayDaemon().catch(() => {
278
+ notifyParent({ kind: "failed", message: "后台 Gateway 启动失败, 请检查配置和授权。" });
279
+ process.exitCode = 1;
280
+ });
281
+ }
@@ -0,0 +1,308 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { watch } from "node:fs";
3
+ import { lstat, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import type { GatewayServiceStatus } from "./gateway-service-controller.ts";
6
+
7
+ export interface GatewayLifecycleOperationReceipt {
8
+ action: "restart";
9
+ operationId: string;
10
+ state: "pending" | "completed" | "failed";
11
+ serviceStatus?: GatewayServiceStatus;
12
+ message?: string;
13
+ }
14
+
15
+ export interface GatewayLifecycleOperationWatcher {
16
+ wait(timeoutMs: number): Promise<GatewayLifecycleOperationReceipt>;
17
+ close(): void;
18
+ removeReceipt(): Promise<void>;
19
+ }
20
+
21
+ /**
22
+ * 在 manager 私有目录监听一次 Gateway 重启操作的最终结果.
23
+ *
24
+ * @param managerDirectory Gateway manager 数据目录.
25
+ * @param operationId 本次操作 UUID.
26
+ * @returns 已安装文件系统监听器的一次性等待句柄.
27
+ */
28
+ export async function watchGatewayLifecycleOperation(
29
+ managerDirectory: string,
30
+ operationId: string,
31
+ ): Promise<GatewayLifecycleOperationWatcher> {
32
+ if (!isOperationId(operationId)) {
33
+ throw new Error("Gateway 生命周期操作 ID 无效。");
34
+ }
35
+ const operationDirectory = await ensureOperationDirectory(managerDirectory);
36
+ const receiptPath = join(operationDirectory, `${operationId}.json`);
37
+ const watcher = watch(operationDirectory, { persistent: false });
38
+ let cachedReceipt: GatewayLifecycleOperationReceipt | undefined;
39
+ let readError: Error | undefined;
40
+ let resolveWait: ((receipt: GatewayLifecycleOperationReceipt) => void) | undefined;
41
+ let rejectWait: ((error: Error) => void) | undefined;
42
+ let timer: NodeJS.Timeout | undefined;
43
+ let closed = false;
44
+
45
+ const clearWait = (): void => {
46
+ if (timer) {
47
+ clearTimeout(timer);
48
+ timer = undefined;
49
+ }
50
+ resolveWait = undefined;
51
+ rejectWait = undefined;
52
+ };
53
+ const readReceipt = async (): Promise<void> => {
54
+ if (closed || cachedReceipt || readError) {
55
+ return;
56
+ }
57
+ try {
58
+ const parsed = parseReceipt(JSON.parse(await readFile(receiptPath, "utf8")) as unknown, operationId);
59
+ if (parsed.state === "pending") {
60
+ return;
61
+ }
62
+ cachedReceipt = parsed;
63
+ if (timer) {
64
+ clearTimeout(timer);
65
+ timer = undefined;
66
+ }
67
+ resolveWait?.(parsed);
68
+ resolveWait = undefined;
69
+ rejectWait = undefined;
70
+ } catch (error) {
71
+ if (isNodeError(error) && error.code === "ENOENT") {
72
+ return;
73
+ }
74
+ readError = error instanceof Error ? error : new Error("Gateway 生命周期结果无效。");
75
+ if (timer) {
76
+ clearTimeout(timer);
77
+ timer = undefined;
78
+ }
79
+ rejectWait?.(readError);
80
+ resolveWait = undefined;
81
+ rejectWait = undefined;
82
+ }
83
+ };
84
+
85
+ watcher.on("change", () => {
86
+ void readReceipt();
87
+ });
88
+ watcher.on("error", (error) => {
89
+ readError = error;
90
+ if (timer) {
91
+ clearTimeout(timer);
92
+ timer = undefined;
93
+ }
94
+ rejectWait?.(error);
95
+ resolveWait = undefined;
96
+ rejectWait = undefined;
97
+ });
98
+
99
+ return {
100
+ wait(timeoutMs: number): Promise<GatewayLifecycleOperationReceipt> {
101
+ if (cachedReceipt) {
102
+ return Promise.resolve(cachedReceipt);
103
+ }
104
+ if (readError) {
105
+ return Promise.reject(readError);
106
+ }
107
+ return new Promise<GatewayLifecycleOperationReceipt>((resolveReceipt, rejectReceipt) => {
108
+ resolveWait = resolveReceipt;
109
+ rejectWait = rejectReceipt;
110
+ timer = setTimeout(() => {
111
+ timer = undefined;
112
+ const reject = rejectWait;
113
+ clearWait();
114
+ reject?.(new Error("等待 Gateway 重启完成超时。"));
115
+ }, timeoutMs);
116
+ timer.unref();
117
+ void readReceipt();
118
+ });
119
+ },
120
+ close(): void {
121
+ closed = true;
122
+ const reject = rejectWait;
123
+ clearWait();
124
+ watcher.close();
125
+ reject?.(new Error("Gateway 重启结果监听已关闭。"));
126
+ },
127
+ async removeReceipt(): Promise<void> {
128
+ try {
129
+ await unlink(receiptPath);
130
+ } catch (error) {
131
+ if (!isNodeError(error) || error.code !== "ENOENT") {
132
+ throw error;
133
+ }
134
+ }
135
+ },
136
+ };
137
+ }
138
+
139
+ /**
140
+ * 原子写入一次 Gateway 生命周期操作结果.
141
+ *
142
+ * @param managerDirectory Gateway manager 数据目录.
143
+ * @param receipt 操作 ID、阶段、最终状态和可选错误提示.
144
+ * @returns 操作结果写入并替换完成后正常结束.
145
+ */
146
+ export async function writeGatewayLifecycleOperationReceipt(
147
+ managerDirectory: string,
148
+ receipt: GatewayLifecycleOperationReceipt,
149
+ ): Promise<void> {
150
+ if (!isOperationId(receipt.operationId)) {
151
+ throw new Error("Gateway 生命周期操作 ID 无效。");
152
+ }
153
+ const operationDirectory = await ensureOperationDirectory(managerDirectory);
154
+ const receiptPath = join(operationDirectory, `${receipt.operationId}.json`);
155
+ const temporaryPath = `${receiptPath}.${process.pid}.${randomUUID()}.tmp`;
156
+ await writeFile(temporaryPath, `${JSON.stringify(receipt)}\n`, {
157
+ encoding: "utf8",
158
+ flag: "wx",
159
+ mode: 0o600,
160
+ });
161
+ try {
162
+ await rename(temporaryPath, receiptPath);
163
+ } catch (error) {
164
+ await unlink(temporaryPath).catch(() => undefined);
165
+ throw error;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Gateway 启动就绪后完成上次 daemon 重启遗留的 pending 操作.
171
+ *
172
+ * @param managerDirectory Gateway manager 数据目录.
173
+ * @param serviceStatus 新 Gateway 的最终状态.
174
+ * @param failureMessage 存在时将 pending 操作标记为失败并记录安全提示.
175
+ * @param operationId 可选的特定重启操作 ID.
176
+ * @returns 所有匹配的 pending 重启操作完成后正常结束.
177
+ */
178
+ export async function completePendingGatewayLifecycleOperations(
179
+ managerDirectory: string,
180
+ serviceStatus: GatewayServiceStatus,
181
+ failureMessage?: string,
182
+ operationId?: string,
183
+ ): Promise<void> {
184
+ if (operationId && !isOperationId(operationId)) {
185
+ throw new Error("Gateway 生命周期操作 ID 无效。");
186
+ }
187
+ let operationDirectory: string;
188
+ try {
189
+ operationDirectory = await ensureOperationDirectory(managerDirectory);
190
+ } catch (error) {
191
+ if (isNodeError(error) && error.code === "ENOENT") {
192
+ return;
193
+ }
194
+ throw error;
195
+ }
196
+
197
+ const entries = await readdir(operationDirectory);
198
+ const operationIds = entries
199
+ .filter((entry) => entry.endsWith(".json"))
200
+ .map((entry) => entry.slice(0, -5))
201
+ .filter(isOperationId);
202
+ const receipts = await Promise.all(operationIds.map(async (operationId) => {
203
+ try {
204
+ return await readOperationReceipt(operationDirectory, operationId);
205
+ } catch (error) {
206
+ if (isNodeError(error) && error.code === "ENOENT") {
207
+ return undefined;
208
+ }
209
+ return undefined;
210
+ }
211
+ }));
212
+ const pendingOperationIds = receipts
213
+ .filter((receipt): receipt is GatewayLifecycleOperationReceipt =>
214
+ receipt?.state === "pending" && (!operationId || receipt.operationId === operationId),
215
+ )
216
+ .map((receipt) => receipt.operationId);
217
+ await Promise.all(pendingOperationIds.map((operationId) => writeGatewayLifecycleOperationReceipt(
218
+ managerDirectory,
219
+ {
220
+ action: "restart",
221
+ operationId,
222
+ state: failureMessage ? "failed" : "completed",
223
+ serviceStatus,
224
+ ...(failureMessage ? { message: failureMessage } : {}),
225
+ },
226
+ )));
227
+ }
228
+
229
+ /**
230
+ * 确保生命周期操作目录是 manager 私有目录下的普通目录.
231
+ *
232
+ * @param managerDirectory Gateway manager 数据目录.
233
+ * @returns 生命周期操作目录绝对路径.
234
+ */
235
+ async function ensureOperationDirectory(managerDirectory: string): Promise<string> {
236
+ const operationDirectory = join(resolve(managerDirectory), "lifecycle-operations");
237
+ await mkdir(operationDirectory, { recursive: true, mode: 0o700 });
238
+ const directoryInfo = await lstat(operationDirectory);
239
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) {
240
+ throw new Error("Gateway 生命周期操作目录不安全。");
241
+ }
242
+ return operationDirectory;
243
+ }
244
+
245
+ /**
246
+ * 读取并验证指定生命周期操作的结果文件.
247
+ *
248
+ * @param operationDirectory 操作记录目录.
249
+ * @param operationId 本次操作 UUID.
250
+ * @returns 已验证的操作记录.
251
+ */
252
+ async function readOperationReceipt(
253
+ operationDirectory: string,
254
+ operationId: string,
255
+ ): Promise<GatewayLifecycleOperationReceipt> {
256
+ const receiptPath = join(operationDirectory, `${operationId}.json`);
257
+ const receiptInfo = await lstat(receiptPath);
258
+ if (!receiptInfo.isFile() || receiptInfo.isSymbolicLink()) {
259
+ throw new Error("Gateway 生命周期结果文件类型无效。");
260
+ }
261
+ const contents = await readFile(receiptPath, "utf8");
262
+ return parseReceipt(JSON.parse(contents) as unknown, operationId);
263
+ }
264
+
265
+ /**
266
+ * 验证操作 ID 为 UUID, 避免从操作记录路径逸出.
267
+ *
268
+ * @param operationId 操作 ID.
269
+ * @returns ID 有效时返回 true.
270
+ */
271
+ function isOperationId(operationId: string): boolean {
272
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(operationId);
273
+ }
274
+
275
+ /**
276
+ * 验证生命周期结果与当前操作 ID 匹配.
277
+ *
278
+ * @param value JSON 文件内容.
279
+ * @param expectedOperationId 当前等待的操作 ID.
280
+ * @returns 已验证的生命周期操作结果.
281
+ */
282
+ function parseReceipt(value: unknown, expectedOperationId: string): GatewayLifecycleOperationReceipt {
283
+ if (
284
+ typeof value !== "object" || value === null || Array.isArray(value) ||
285
+ !("action" in value) || value.action !== "restart" ||
286
+ !("operationId" in value) || value.operationId !== expectedOperationId ||
287
+ !("state" in value) || (value.state !== "pending" && value.state !== "completed" && value.state !== "failed") ||
288
+ (value.state !== "pending" && (
289
+ !("serviceStatus" in value) || typeof value.serviceStatus !== "object" ||
290
+ value.serviceStatus === null || Array.isArray(value.serviceStatus) ||
291
+ !("state" in value.serviceStatus) || typeof value.serviceStatus.state !== "string"
292
+ )) ||
293
+ ("message" in value && typeof value.message !== "string")
294
+ ) {
295
+ throw new Error("Gateway 生命周期结果格式无效。");
296
+ }
297
+ return value as unknown as GatewayLifecycleOperationReceipt;
298
+ }
299
+
300
+ /**
301
+ * 判断未知异常是否携带 Node.js 错误代码.
302
+ *
303
+ * @param error 待检查的异常.
304
+ * @returns 错误带 code 字段时返回 true.
305
+ */
306
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
307
+ return error instanceof Error && "code" in error;
308
+ }