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,133 @@
1
+ import type { IlinkReplyContext } from "../channel-types.ts";
2
+
3
+ export interface IlinkTypingApi {
4
+ /**
5
+ * 获取当前微信回复上下文的 typing_ticket。
6
+ *
7
+ * @param recipientId 微信 userId。
8
+ * @param contextToken 当前入站消息的 context_token。
9
+ * @returns 可用于 sendTyping 的 ticket。
10
+ */
11
+ getTypingConfig(recipientId: string, contextToken: string): Promise<{ typingTicket?: string }>;
12
+
13
+ /**
14
+ * 发出或取消微信端“正在输入”状态。
15
+ *
16
+ * @param recipientId 微信 userId。
17
+ * @param typingTicket getTypingConfig 返回的 ticket。
18
+ * @param status 1 开始, 2 取消。
19
+ * @returns API 成功时完成。
20
+ */
21
+ sendTyping(recipientId: string, typingTicket: string, status: 1 | 2): Promise<void>;
22
+ }
23
+
24
+ interface ActiveTypingEntry {
25
+ active: boolean;
26
+ recipientId: string;
27
+ contextToken: string;
28
+ typingTicket?: string;
29
+ typingStarted: boolean;
30
+ keepalive?: NodeJS.Timeout;
31
+ }
32
+
33
+ /**
34
+ * 在 route queue 处理期间维护微信原生“正在输入”状态。
35
+ *
36
+ * typing API 失败仅跳过状态提示, 不影响 Pi 生成和最终回复。
37
+ */
38
+ export class IlinkTypingIndicator {
39
+ private readonly activeEntries = new Map<string, ActiveTypingEntry>();
40
+ private readonly keepaliveIntervalMs: number;
41
+
42
+ /**
43
+ * 创建 typing indicator manager。
44
+ *
45
+ * @param api iLink getconfig/sendtyping API 实现。
46
+ * @param options typing 状态续期配置。
47
+ */
48
+ constructor(
49
+ private readonly api: IlinkTypingApi,
50
+ options: { keepaliveIntervalMs?: number } = {},
51
+ ) {
52
+ this.keepaliveIntervalMs = options.keepaliveIntervalMs ?? 5000;
53
+ }
54
+
55
+ /**
56
+ * 异步启动某条 queue 消息的微信 typing 状态, 不阻塞 worker。
57
+ *
58
+ * @param messageId durable queue 消息 ID。
59
+ * @param replyContext 消息对应的微信回复上下文。
60
+ * @returns 无返回值。
61
+ */
62
+ start(messageId: string, replyContext: IlinkReplyContext | undefined): void {
63
+ if (!replyContext || this.activeEntries.has(messageId)) {
64
+ return;
65
+ }
66
+ const entry: ActiveTypingEntry = {
67
+ active: true,
68
+ recipientId: replyContext.recipientId,
69
+ contextToken: replyContext.contextToken,
70
+ typingStarted: false,
71
+ };
72
+ this.activeEntries.set(messageId, entry);
73
+ void this.startEntry(messageId, entry);
74
+ }
75
+
76
+ /**
77
+ * 停止某条 queue 消息的 typing 状态并释放续期 timer。
78
+ *
79
+ * @param messageId durable queue 消息 ID。
80
+ * @returns 无返回值。
81
+ */
82
+ stop(messageId: string): void {
83
+ const entry = this.activeEntries.get(messageId);
84
+ if (!entry) {
85
+ return;
86
+ }
87
+ entry.active = false;
88
+ if (entry.keepalive) {
89
+ clearInterval(entry.keepalive);
90
+ entry.keepalive = undefined;
91
+ }
92
+ this.activeEntries.delete(messageId);
93
+ if (entry.typingStarted && entry.typingTicket) {
94
+ void this.api.sendTyping(entry.recipientId, entry.typingTicket, 2).catch(() => undefined);
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 获取 typing_ticket 后发送开始状态, 并定时续期。
100
+ *
101
+ * @param messageId durable queue 消息 ID。
102
+ * @param entry 本次消息的临时状态。
103
+ * @returns 无返回值。
104
+ */
105
+ private async startEntry(messageId: string, entry: ActiveTypingEntry): Promise<void> {
106
+ try {
107
+ const config = await this.api.getTypingConfig(entry.recipientId, entry.contextToken);
108
+ if (!entry.active || !this.activeEntries.has(messageId) || !config.typingTicket) {
109
+ this.activeEntries.delete(messageId);
110
+ return;
111
+ }
112
+ entry.typingTicket = config.typingTicket;
113
+ await this.api.sendTyping(entry.recipientId, entry.typingTicket, 1);
114
+ entry.typingStarted = true;
115
+ if (!entry.active || !this.activeEntries.has(messageId)) {
116
+ await this.api.sendTyping(entry.recipientId, entry.typingTicket, 2).catch(() => undefined);
117
+ return;
118
+ }
119
+ entry.keepalive = setInterval(() => {
120
+ if (entry.active && entry.typingTicket) {
121
+ void this.api.sendTyping(entry.recipientId, entry.typingTicket, 1).catch(() => undefined);
122
+ }
123
+ }, this.keepaliveIntervalMs);
124
+ entry.keepalive.unref();
125
+ } catch {
126
+ entry.active = false;
127
+ if (entry.keepalive) {
128
+ clearInterval(entry.keepalive);
129
+ }
130
+ this.activeEntries.delete(messageId);
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,247 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join, win32 } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+
7
+ export type WindowsTerminalLaunchErrorCode =
8
+ | "unsupported_platform"
9
+ | "wt_not_found"
10
+ | "launch_failed";
11
+
12
+ /**
13
+ * 描述当前环境能否启动可见 Windows Terminal UI worker。
14
+ */
15
+ export type WindowsTerminalCapability =
16
+ | { supported: true; executable: string }
17
+ | { supported: false; reason: string };
18
+
19
+ /**
20
+ * 表示 Windows Terminal UI worker 无法安全启动。
21
+ */
22
+ export class WindowsTerminalLaunchError extends Error {
23
+ /**
24
+ * 创建不包含用户命令或凭证的启动错误。
25
+ *
26
+ * @param code 稳定错误代码。
27
+ * @param message 可安全显示的中文说明。
28
+ */
29
+ constructor(
30
+ readonly code: WindowsTerminalLaunchErrorCode,
31
+ message: string,
32
+ ) {
33
+ super(message);
34
+ this.name = "WindowsTerminalLaunchError";
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 通过固定 PowerShell launcher 在 Windows Terminal 中启动独立 Pi TUI tab。
40
+ */
41
+ export class WindowsTerminalLauncher {
42
+ private readonly scriptPath: string;
43
+ private readonly platform: NodeJS.Platform;
44
+ private readonly spawnProcess: typeof spawn;
45
+
46
+ /**
47
+ * 创建 Windows Terminal launcher。
48
+ *
49
+ * @param options 可注入 Windows Terminal CLI 和受控启动脚本路径。
50
+ */
51
+ constructor(options: {
52
+ wtExecutable?: string;
53
+ scriptPath?: string;
54
+ platform?: NodeJS.Platform;
55
+ spawnProcess?: typeof spawn;
56
+ } = {}) {
57
+ this.wtExecutable = options.wtExecutable;
58
+ this.scriptPath = options.scriptPath ?? fileURLToPath(
59
+ new URL("../../scripts/start-ui-worker.ps1", import.meta.url),
60
+ );
61
+ this.platform = options.platform ?? process.platform;
62
+ this.spawnProcess = options.spawnProcess ?? spawn;
63
+ }
64
+
65
+ private readonly wtExecutable?: string;
66
+
67
+ /**
68
+ * 在指定项目目录启动 UI worker tab。
69
+ *
70
+ * @param managerDirectory manager 数据目录。
71
+ * @param projectPath 经 ProjectService 验证的项目目录。
72
+ * @param launchId UUID 启动记录 ID。
73
+ * @returns Windows Terminal 接受启动请求后正常结束。
74
+ * @throws {WindowsTerminalLaunchError} 平台、CLI 或参数不安全时抛出。
75
+ */
76
+ async launch(managerDirectory: string, projectPath: string, launchId: string): Promise<void> {
77
+ if (this.platform !== "win32") {
78
+ throw new WindowsTerminalLaunchError(
79
+ "unsupported_platform",
80
+ "当前系统不支持 Windows Terminal UI worker; 可使用 background 模式。",
81
+ );
82
+ }
83
+ if (!/^[a-f0-9-]{36}$/i.test(launchId)) {
84
+ throw new WindowsTerminalLaunchError("launch_failed", "UI worker launchId 无效, 已拒绝启动。");
85
+ }
86
+ const wtExecutable = this.wtExecutable ?? await resolveWindowsTerminalExecutable();
87
+ const pwshExecutable = resolvePowerShellExecutable();
88
+ if (!existsSync(this.scriptPath)) {
89
+ throw new WindowsTerminalLaunchError("launch_failed", "受控 UI worker 启动脚本不存在, 已拒绝启动。");
90
+ }
91
+
92
+ const args = [
93
+ "-w",
94
+ "0",
95
+ "new-tab",
96
+ "-d",
97
+ projectPath,
98
+ "--title",
99
+ "Pi UI session",
100
+ pwshExecutable,
101
+ "-NoLogo",
102
+ "-NoProfile",
103
+ "-NonInteractive",
104
+ "-File",
105
+ this.scriptPath,
106
+ managerDirectory,
107
+ launchId,
108
+ ];
109
+ await new Promise<void>((resolveLaunch, rejectLaunch) => {
110
+ const child = this.spawnProcess(wtExecutable, args, {
111
+ cwd: projectPath,
112
+ detached: true,
113
+ stdio: "ignore",
114
+ windowsHide: false,
115
+ });
116
+ child.once("spawn", () => {
117
+ child.unref();
118
+ resolveLaunch();
119
+ });
120
+ child.once("error", () => {
121
+ rejectLaunch(new WindowsTerminalLaunchError(
122
+ "launch_failed",
123
+ "Windows Terminal 未能接受 UI worker 启动请求。",
124
+ ));
125
+ });
126
+ });
127
+ }
128
+ }
129
+
130
+ /**
131
+ * 探测当前环境是否具备启动可见 Windows Terminal UI worker 的能力。
132
+ *
133
+ * 该探测不启动任何进程, 只判断平台与 wt.exe 是否可用, 供命令在执行前阻塞不受支持的操作。
134
+ *
135
+ * @param options 可注入平台、WindowsApps 路径、文件存在检查器和 where.exe 查询器。
136
+ * @returns 支持时返回已解析的 wt.exe 路径, 否则返回面向用户的中文原因。
137
+ */
138
+ export async function probeWindowsTerminalCapability(options: {
139
+ platform?: NodeJS.Platform;
140
+ localAppData?: string;
141
+ systemRoot?: string;
142
+ fileExists?: (path: string) => boolean;
143
+ findOnPath?: (wherePath: string) => Promise<string>;
144
+ } = {}): Promise<WindowsTerminalCapability> {
145
+ const platform = options.platform ?? process.platform;
146
+ if (platform !== "win32") {
147
+ return {
148
+ supported: false,
149
+ reason: `当前系统为 ${platform}, 可见 UI 模式依赖 Windows Terminal, 仅支持 Windows`,
150
+ };
151
+ }
152
+ try {
153
+ const executable = await resolveWindowsTerminalExecutable(options);
154
+ return { supported: true, executable };
155
+ } catch (error) {
156
+ return {
157
+ supported: false,
158
+ reason: error instanceof WindowsTerminalLaunchError && error.code === "wt_not_found"
159
+ ? "未找到 Windows Terminal (wt.exe), 请先安装 Windows Terminal 或将其加入应用执行别名"
160
+ : "无法确认 Windows Terminal 可用性",
161
+ };
162
+ }
163
+ }
164
+
165
+ /**
166
+ * 解析当前 Windows Terminal app execution alias 或安装路径。
167
+ *
168
+ * @param options 可注入的 WindowsApps 路径、文件存在检查器和 where.exe 查询器。
169
+ * @returns wt.exe 绝对路径。
170
+ * @throws {WindowsTerminalLaunchError} 系统找不到受信任的 wt.exe 时抛出。
171
+ */
172
+ export async function resolveWindowsTerminalExecutable(options: {
173
+ localAppData?: string;
174
+ systemRoot?: string;
175
+ fileExists?: (path: string) => boolean;
176
+ findOnPath?: (wherePath: string) => Promise<string>;
177
+ } = {}): Promise<string> {
178
+ const localAppData = options.localAppData ?? process.env.LOCALAPPDATA;
179
+ const windowsAppsPath = localAppData
180
+ ? join(localAppData, "Microsoft", "WindowsApps", "wt.exe")
181
+ : undefined;
182
+ const fileExists = options.fileExists ?? existsSync;
183
+ if (windowsAppsPath && fileExists(windowsAppsPath)) {
184
+ return windowsAppsPath;
185
+ }
186
+
187
+ const systemRoot = options.systemRoot ?? process.env.SystemRoot ?? "C:\\Windows";
188
+ const wherePath = join(systemRoot, "System32", "where.exe");
189
+ try {
190
+ const output = options.findOnPath
191
+ ? await options.findOnPath(wherePath)
192
+ : (await promisify(execFile)(wherePath, ["wt.exe"], {
193
+ windowsHide: true,
194
+ timeout: 5000,
195
+ maxBuffer: 64 * 1024,
196
+ })).stdout;
197
+ const candidate = output.split(/\r?\n/).find((line) => line.trim())?.trim();
198
+ if (candidate && fileExists(candidate)) {
199
+ return candidate;
200
+ }
201
+ if (candidate && windowsAppsPath && sameWindowsPath(candidate, windowsAppsPath)) {
202
+ return candidate;
203
+ }
204
+ } catch {
205
+ throw new WindowsTerminalLaunchError(
206
+ "wt_not_found",
207
+ "未找到 Windows Terminal wt.exe; 已拒绝启动 UI worker。",
208
+ );
209
+ }
210
+ throw new WindowsTerminalLaunchError(
211
+ "wt_not_found",
212
+ "未找到 Windows Terminal wt.exe; 已拒绝启动 UI worker。",
213
+ );
214
+ }
215
+
216
+ /**
217
+ * 比较 Windows 文件路径并忽略大小写。
218
+ *
219
+ * @param left 路径一。
220
+ * @param right 路径二。
221
+ * @returns 规范化后的路径相同时返回 true。
222
+ */
223
+ function sameWindowsPath(left: string, right: string): boolean {
224
+ return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();
225
+ }
226
+
227
+ /**
228
+ * 解析 PowerShell 7 可执行文件, 不回退到 profile 脚本或系统命令解释器。
229
+ *
230
+ * @returns pwsh.exe 路径或可信 app execution alias。
231
+ */
232
+ function resolvePowerShellExecutable(): string {
233
+ const programFiles = process.env.ProgramFiles;
234
+ const installationPath = programFiles
235
+ ? join(programFiles, "PowerShell", "7", "pwsh.exe")
236
+ : undefined;
237
+ if (installationPath && existsSync(installationPath)) {
238
+ return installationPath;
239
+ }
240
+ const localAppData = process.env.LOCALAPPDATA;
241
+ const appExecutionAlias = localAppData
242
+ ? join(localAppData, "Microsoft", "WindowsApps", "pwsh.exe")
243
+ : undefined;
244
+ return appExecutionAlias && existsSync(appExecutionAlias)
245
+ ? appExecutionAlias
246
+ : "pwsh.exe";
247
+ }