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,212 @@
1
+ import { execFile } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import type { GatewayDaemonLaunchSpec } from "./gateway-service-controller.ts";
4
+ import { encodeGatewayDaemonLaunchSpec } from "./gateway-service-controller.ts";
5
+
6
+ export interface TaskSchedulerResult {
7
+ code: number;
8
+ stdout: string;
9
+ stderr: string;
10
+ }
11
+
12
+ export type TaskSchedulerExecutor = (
13
+ executable: string,
14
+ args: string[],
15
+ ) => Promise<TaskSchedulerResult>;
16
+
17
+ export class WindowsLogonTaskManagerError extends Error {
18
+ /**
19
+ * 创建 Windows 登录任务错误。
20
+ *
21
+ * @param message 可安全显示的中文说明。
22
+ */
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "WindowsLogonTaskManagerError";
26
+ }
27
+ }
28
+
29
+ const TASK_NAME = "PiWeChatSessionHub";
30
+
31
+ /**
32
+ * 管理当前 Windows 用户登录后启动 Hub daemon 的计划任务。
33
+ */
34
+ export class WindowsLogonTaskManager {
35
+ private readonly platform: NodeJS.Platform;
36
+ private readonly execute: TaskSchedulerExecutor;
37
+
38
+ /**
39
+ * 创建 Windows 登录计划任务管理器。
40
+ *
41
+ * @param launchSpec Hub daemon 的固定启动参数。
42
+ * @param options 平台和 schtasks 边界注入。
43
+ */
44
+ constructor(
45
+ private readonly launchSpec: GatewayDaemonLaunchSpec,
46
+ options: { platform?: NodeJS.Platform; execute?: TaskSchedulerExecutor } = {},
47
+ ) {
48
+ this.platform = options.platform ?? process.platform;
49
+ this.execute = options.execute ?? executeTaskScheduler;
50
+ }
51
+
52
+ /**
53
+ * 创建或更新当前用户登录后运行的 Hub daemon 任务。
54
+ *
55
+ * @returns Task Scheduler 确认创建后正常结束。
56
+ * @throws {WindowsLogonTaskManagerError} 当前平台不受支持或任务创建失败时抛出。
57
+ */
58
+ async enable(): Promise<void> {
59
+ this.assertWindows();
60
+ const result = await this.execute(getTaskSchedulerExecutable(), [
61
+ "/Create",
62
+ "/F",
63
+ "/SC",
64
+ "ONLOGON",
65
+ "/TN",
66
+ TASK_NAME,
67
+ "/TR",
68
+ buildWindowsScheduledTaskCommand(this.launchSpec),
69
+ "/RL",
70
+ "LIMITED",
71
+ ]);
72
+ if (result.code !== 0) {
73
+ throw new WindowsLogonTaskManagerError("无法创建 Windows 登录自动启动任务; 配置未启用。");
74
+ }
75
+ }
76
+
77
+ /**
78
+ * 删除自动启动任务; 任务不存在时按已关闭处理。
79
+ *
80
+ * @returns 删除成功或确认任务不存在后正常结束。
81
+ * @throws {WindowsLogonTaskManagerError} 任务仍存在但无法删除时抛出。
82
+ */
83
+ async disable(): Promise<void> {
84
+ this.assertWindows();
85
+ const deletion = await this.execute(getTaskSchedulerExecutable(), ["/Delete", "/TN", TASK_NAME, "/F"]);
86
+ if (deletion.code === 0) {
87
+ return;
88
+ }
89
+ const query = await this.execute(getTaskSchedulerExecutable(), ["/Query", "/TN", TASK_NAME]);
90
+ if (query.code === 0) {
91
+ throw new WindowsLogonTaskManagerError("Windows 登录自动启动任务仍存在, 未能安全关闭。");
92
+ }
93
+ }
94
+
95
+ /**
96
+ * 查询当前用户的自动启动任务是否存在。
97
+ *
98
+ * @returns 任务存在时返回 true。
99
+ * @throws {WindowsLogonTaskManagerError} 当前平台不受支持时抛出。
100
+ */
101
+ async isEnabled(): Promise<boolean> {
102
+ this.assertWindows();
103
+ const result = await this.execute(getTaskSchedulerExecutable(), ["/Query", "/TN", TASK_NAME]);
104
+ return result.code === 0;
105
+ }
106
+
107
+ /**
108
+ * 校验当前平台支持 Windows Task Scheduler。
109
+ *
110
+ * @returns Windows 平台时正常结束。
111
+ * @throws {WindowsLogonTaskManagerError} 非 Windows 平台时抛出。
112
+ */
113
+ private assertWindows(): void {
114
+ if (this.platform !== "win32") {
115
+ throw new WindowsLogonTaskManagerError("Windows 登录自动启动任务仅支持 Windows。");
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * 将固定 daemon 参数编码为 Task Scheduler 可执行的 Windows command line。
122
+ *
123
+ * @param spec daemon 启动参数。
124
+ * @returns 经过 Windows argv 规则引用的 command line。
125
+ */
126
+ export function buildWindowsScheduledTaskCommand(spec: GatewayDaemonLaunchSpec): string {
127
+ const args = [
128
+ "--experimental-transform-types",
129
+ spec.daemonEntry,
130
+ "--launch-payload",
131
+ encodeGatewayDaemonLaunchSpec(spec),
132
+ ];
133
+ return [spec.piInvocation.command, ...args].map(quoteWindowsArgument).join(" ");
134
+ }
135
+
136
+ /**
137
+ * 按 Windows argv 规则引用一个 command line 参数。
138
+ *
139
+ * @param value 原始参数。
140
+ * @returns 可作为单个 argv 参数解析的引用字符串。
141
+ */
142
+ export function quoteWindowsArgument(value: string): string {
143
+ if (value.length > 0 && !/[\s"]/.test(value)) {
144
+ return value;
145
+ }
146
+ let quoted = '"';
147
+ let backslashes = 0;
148
+ for (const character of value) {
149
+ if (character === "\\") {
150
+ backslashes += 1;
151
+ continue;
152
+ }
153
+ if (character === '"') {
154
+ quoted += "\\".repeat(backslashes * 2 + 1);
155
+ quoted += '"';
156
+ backslashes = 0;
157
+ continue;
158
+ }
159
+ quoted += "\\".repeat(backslashes);
160
+ quoted += character;
161
+ backslashes = 0;
162
+ }
163
+ quoted += "\\".repeat(backslashes * 2);
164
+ quoted += '"';
165
+ return quoted;
166
+ }
167
+
168
+ /**
169
+ * 获取系统自带 Task Scheduler CLI 的绝对路径。
170
+ *
171
+ * @returns System32 下的 schtasks.exe 路径。
172
+ */
173
+ function getTaskSchedulerExecutable(): string {
174
+ const systemRoot = process.env.SystemRoot ?? "C:\\Windows";
175
+ return join(systemRoot, "System32", "schtasks.exe");
176
+ }
177
+
178
+ /**
179
+ * 使用 execFile 直接调用 schtasks.exe, 不经过 shell。
180
+ *
181
+ * @param executable 固定 Windows Task Scheduler CLI。
182
+ * @param args 结构化 argv 参数。
183
+ * @returns exit code、stdout 与 stderr。
184
+ */
185
+ function executeTaskScheduler(
186
+ executable: string,
187
+ args: string[],
188
+ ): Promise<TaskSchedulerResult> {
189
+ return new Promise<TaskSchedulerResult>((resolveResult, rejectResult) => {
190
+ execFile(executable, args, {
191
+ windowsHide: true,
192
+ timeout: 15000,
193
+ maxBuffer: 64 * 1024,
194
+ }, (error, stdout, stderr) => {
195
+ if (!error) {
196
+ resolveResult({ code: 0, stdout, stderr });
197
+ return;
198
+ }
199
+ const rawExitCode = error.code;
200
+ const exitCode = typeof rawExitCode === "number"
201
+ ? rawExitCode
202
+ : typeof rawExitCode === "string" && /^\d+$/.test(rawExitCode)
203
+ ? Number(rawExitCode)
204
+ : undefined;
205
+ if (exitCode !== undefined) {
206
+ resolveResult({ code: exitCode, stdout, stderr });
207
+ return;
208
+ }
209
+ rejectResult(new WindowsLogonTaskManagerError("无法访问 Windows Task Scheduler。"));
210
+ });
211
+ });
212
+ }
@@ -0,0 +1,88 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { join } from "node:path";
3
+
4
+ const TASKLIST_TIMEOUT_MS = 3000;
5
+ const TASKLIST_MAX_BUFFER_BYTES = 4 * 1024 * 1024;
6
+
7
+ /**
8
+ * 判断指定进程是否仍可能运行, 只有明确确认进程不存在时才返回 false.
9
+ *
10
+ * Windows 上 process.kill(pid, 0) 的 EPERM 可能对应已退出的 PID, 因此会用 tasklist 快照复核.
11
+ *
12
+ * @param pid 操作系统进程 ID.
13
+ * @returns 进程存在或状态不明确时返回 true.
14
+ */
15
+ export function isProcessAlive(pid: number): boolean {
16
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
17
+ return true;
18
+ }
19
+
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ } catch (error) {
24
+ if (isNodeError(error) && error.code === "ESRCH") {
25
+ return false;
26
+ }
27
+ if (
28
+ process.platform === "win32" &&
29
+ isNodeError(error) &&
30
+ (error.code === "EPERM" || error.code === "EACCES")
31
+ ) {
32
+ return isWindowsProcessAlive(pid);
33
+ }
34
+ return true;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 使用 Windows 进程快照复核 PID 是否存在.
40
+ *
41
+ * @param pid 操作系统进程 ID.
42
+ * @returns tasklist 确认 PID 存在时返回 true; 查询失败或结果不完整时保守返回 true.
43
+ */
44
+ function isWindowsProcessAlive(pid: number): boolean {
45
+ const tasklistPath = process.env.SystemRoot
46
+ ? join(process.env.SystemRoot, "System32", "tasklist.exe")
47
+ : "tasklist.exe";
48
+ const result = spawnSync(tasklistPath, ["/FO", "CSV", "/NH"], {
49
+ encoding: "buffer",
50
+ maxBuffer: TASKLIST_MAX_BUFFER_BYTES,
51
+ timeout: TASKLIST_TIMEOUT_MS,
52
+ windowsHide: true,
53
+ });
54
+
55
+ if (result.error || result.status !== 0 || !Buffer.isBuffer(result.stdout)) {
56
+ return true;
57
+ }
58
+
59
+ const processIds = parseTasklistProcessIds(result.stdout);
60
+ return processIds.size === 0 || processIds.has(pid);
61
+ }
62
+
63
+ /**
64
+ * 从 tasklist CSV 快照中提取进程 ID 列.
65
+ *
66
+ * @param output tasklist 标准输出字节.
67
+ * @returns 成功解析出的进程 ID 集合.
68
+ */
69
+ function parseTasklistProcessIds(output: Buffer): Set<number> {
70
+ const processIds = new Set<number>();
71
+ for (const line of output.toString("latin1").split(/\r?\n/)) {
72
+ const match = /^"[^"]*","(\d+)"/.exec(line);
73
+ if (match) {
74
+ processIds.add(Number(match[1]));
75
+ }
76
+ }
77
+ return processIds;
78
+ }
79
+
80
+ /**
81
+ * 判断未知值是否为携带 Node 错误码的异常.
82
+ *
83
+ * @param error 待判断值.
84
+ * @returns 值为带错误码的 Error 时返回 true.
85
+ */
86
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
87
+ return error instanceof Error && "code" in error;
88
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "allowImportingTsExtensions": true,
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "skipLibCheck": true,
10
+ "types": [
11
+ "node"
12
+ ]
13
+ },
14
+ "include": [
15
+ "extensions/**/*.ts",
16
+ "src/**/*.ts",
17
+ "tests/**/*.ts"
18
+ ]
19
+ }