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,320 @@
1
+ import { createHash } from "node:crypto";
2
+ import { EventEmitter } from "node:events";
3
+ import type { GatewayInboundMessage, IlinkGetUpdatesResponse, IlinkTextMessage } from "../channel-types.ts";
4
+ import { GatewayAuthorizationError } from "../command-router.ts";
5
+ import { IlinkApiClient, IlinkApiError } from "./api-client.ts";
6
+ import { IlinkCursorStore } from "./cursor-store.ts";
7
+
8
+ /**
9
+ * Gateway 入站消息处理函数。
10
+ *
11
+ * @param message 规范化后的入站消息。
12
+ * @returns 处理结果。
13
+ */
14
+ export type IlinkInboundHandler = (message: GatewayInboundMessage) => Promise<unknown>;
15
+
16
+ /**
17
+ * iLink adapter 向调用方返回的无敏感信息 poll 统计。
18
+ */
19
+ export interface IlinkPollSummary {
20
+ receivedCount: number;
21
+ acceptedCount: number;
22
+ ignoredCount: number;
23
+ nextLongPollTimeoutMs: number;
24
+ }
25
+
26
+ /**
27
+ * iLink 长轮询配置, 必须绑定唯一授权微信 userId。
28
+ */
29
+ export interface IlinkChannelAdapterOptions {
30
+ authorizedUserId: string;
31
+ initialLongPollTimeoutMs?: number;
32
+ maxBackoffMs?: number;
33
+ }
34
+
35
+ /**
36
+ * 将 iLink getupdates 批次适配到 Gateway normalized message, 并处理 poll 生命周期。
37
+ *
38
+ * 本适配器不会执行 QR 登录或自动修改账号凭证。
39
+ */
40
+ export class IlinkChannelAdapter extends EventEmitter {
41
+ private running = false;
42
+ private handler?: IlinkInboundHandler;
43
+ private abortController?: AbortController;
44
+ private pollTask?: Promise<void>;
45
+ private timer?: NodeJS.Timeout;
46
+ private backoffMs = 1000;
47
+ private longPollTimeoutMs: number;
48
+ private readonly maxBackoffMs: number;
49
+ private readonly authorizedUserId: string;
50
+
51
+ /**
52
+ * 创建 iLink channel adapter。
53
+ *
54
+ * @param api iLink API client, 凭证由调用方显式注入。
55
+ * @param cursorStore 持久化 get_updates_buf 的存储。
56
+ * @param options 长轮询和退避参数。
57
+ */
58
+ constructor(
59
+ private readonly api: IlinkApiClient,
60
+ private readonly cursorStore: IlinkCursorStore,
61
+ options: IlinkChannelAdapterOptions,
62
+ ) {
63
+ super();
64
+ if (!options.authorizedUserId.trim()) {
65
+ throw new IlinkApiError("invalid_credentials", "iLink poller 必须配置单一授权 userId。");
66
+ }
67
+ this.authorizedUserId = options.authorizedUserId;
68
+ this.longPollTimeoutMs = options.initialLongPollTimeoutMs ?? 35000;
69
+ this.maxBackoffMs = options.maxBackoffMs ?? 30000;
70
+ }
71
+
72
+ /**
73
+ * 开始持续长轮询; 方法在首轮 poll 启动后返回。
74
+ *
75
+ * @param handler 已授权 Gateway 入站处理函数。
76
+ * @returns 无返回值。
77
+ * @throws {Error} adapter 已经运行时抛出。
78
+ */
79
+ async start(handler: IlinkInboundHandler): Promise<void> {
80
+ if (this.running) {
81
+ throw new Error("iLink channel adapter 已经运行。");
82
+ }
83
+ this.running = true;
84
+ this.handler = handler;
85
+ this.abortController = new AbortController();
86
+ this.pollTask = this.pollCycle();
87
+ await Promise.resolve();
88
+ }
89
+
90
+ /**
91
+ * 请求停止轮询并等待当前长轮询退出。
92
+ *
93
+ * @returns 无返回值。
94
+ */
95
+ async stop(): Promise<void> {
96
+ this.running = false;
97
+ if (this.timer) {
98
+ clearTimeout(this.timer);
99
+ this.timer = undefined;
100
+ }
101
+ this.abortController?.abort();
102
+ await this.pollTask?.catch(() => undefined);
103
+ this.pollTask = undefined;
104
+ this.handler = undefined;
105
+ }
106
+
107
+ /**
108
+ * 将一批 iLink 消息持久入队并在处理完毕后提交同步游标。
109
+ *
110
+ * @param handler Gateway normalized message handler。
111
+ * @param signal 可选取消信号。
112
+ * @returns poll 摘要, 不包含 message body 或 context token。
113
+ * @throws {IlinkApiError} getupdates 或游标持久化失败时抛出。
114
+ */
115
+ async pollOnce(
116
+ handler: IlinkInboundHandler,
117
+ signal?: AbortSignal,
118
+ ): Promise<IlinkPollSummary> {
119
+ const cursor = await this.cursorStore.load();
120
+ const updates = await this.api.getUpdates(cursor, signal, this.longPollTimeoutMs);
121
+ this.updateLongPollTimeout(updates);
122
+ const messages = updates.msgs ?? [];
123
+ const unsupported: Array<{ message: IlinkTextMessage; context: { recipientId: string; contextToken: string } }> = [];
124
+ let acceptedCount = 0;
125
+ let ignoredCount = 0;
126
+
127
+ for (const message of messages) {
128
+ if (message.message_type !== 1) {
129
+ ignoredCount += 1;
130
+ continue;
131
+ }
132
+ const recipientId = message.from_user_id;
133
+ if (recipientId !== this.authorizedUserId) {
134
+ ignoredCount += 1;
135
+ continue;
136
+ }
137
+ const contextToken = message.context_token;
138
+ const messageId = message.message_id === undefined
139
+ ? message.client_id
140
+ : String(message.message_id);
141
+ if (!recipientId || !contextToken || !messageId) {
142
+ ignoredCount += 1;
143
+ continue;
144
+ }
145
+
146
+ const text = extractText(message);
147
+ const hasUnsupportedMedia = (message.item_list ?? []).some((item) =>
148
+ item.type !== undefined && item.type !== 1,
149
+ );
150
+ if (!text.trim()) {
151
+ if (hasUnsupportedMedia) {
152
+ unsupported.push({
153
+ message,
154
+ context: { recipientId, contextToken },
155
+ });
156
+ ignoredCount += 1;
157
+ } else {
158
+ ignoredCount += 1;
159
+ }
160
+ continue;
161
+ }
162
+ const normalized: GatewayInboundMessage = {
163
+ messageId,
164
+ senderId: recipientId,
165
+ text: hasUnsupportedMedia
166
+ ? `${text}\n[此消息包含附件, 当前版本尚未读取附件内容。]`
167
+ : text,
168
+ replyContext: { recipientId, contextToken },
169
+ };
170
+ try {
171
+ await handler(normalized);
172
+ acceptedCount += 1;
173
+ } catch (error) {
174
+ if (error instanceof GatewayAuthorizationError) {
175
+ ignoredCount += 1;
176
+ continue;
177
+ }
178
+ throw error;
179
+ }
180
+ }
181
+
182
+ await Promise.all(unsupported.map(({ message, context }) =>
183
+ this.api.sendText(
184
+ context.recipientId,
185
+ "当前版本只处理文本消息, 暂不读取该附件。",
186
+ context.contextToken,
187
+ stableUnsupportedReplyId(message),
188
+ ),
189
+ ));
190
+
191
+ if (typeof updates.get_updates_buf === "string") {
192
+ await this.cursorStore.save(updates.get_updates_buf);
193
+ }
194
+ return {
195
+ receivedCount: messages.length,
196
+ acceptedCount,
197
+ ignoredCount,
198
+ nextLongPollTimeoutMs: this.longPollTimeoutMs,
199
+ };
200
+ }
201
+
202
+ /**
203
+ * 通过入站消息上下文发送文本回复。
204
+ *
205
+ * @param routeId route ID, 用于生成稳定发送幂等键。
206
+ * @param messageId channel 入站消息 ID。
207
+ * @param text 回复正文。
208
+ * @param replyContext 需要原样回传的 iLink context。
209
+ * @returns 无返回值。
210
+ * @throws {IlinkApiError} 缺少 context 时抛出。
211
+ */
212
+ async sendReply(
213
+ routeId: string,
214
+ messageId: string,
215
+ text: string,
216
+ replyContext?: { recipientId: string; contextToken: string },
217
+ ): Promise<void> {
218
+ if (!replyContext) {
219
+ throw new IlinkApiError(
220
+ "context_token_missing",
221
+ "iLink replySink 缺少入站 replyContext; 为避免错发, 已拒绝发送。",
222
+ );
223
+ }
224
+ const clientId = stableReplyId(routeId, messageId, text);
225
+ await this.api.sendText(
226
+ replyContext.recipientId,
227
+ text,
228
+ replyContext.contextToken,
229
+ clientId,
230
+ );
231
+ }
232
+
233
+ /**
234
+ * 执行一次 poll 并安排下一轮; session 过期时停止, 绝不自动重登。
235
+ *
236
+ * @returns 无返回值。
237
+ */
238
+ private async pollCycle(): Promise<void> {
239
+ if (!this.running || !this.handler || !this.abortController) {
240
+ return;
241
+ }
242
+ let delayMs = 0;
243
+ try {
244
+ await this.pollOnce(this.handler, this.abortController.signal);
245
+ this.backoffMs = 1000;
246
+ } catch (error) {
247
+ if (!this.running || this.abortController.signal.aborted) {
248
+ return;
249
+ }
250
+ if (error instanceof IlinkApiError && error.code === "session_expired") {
251
+ this.running = false;
252
+ this.emit("session_expired");
253
+ return;
254
+ }
255
+ const errorCode = error instanceof IlinkApiError ? error.code : "unexpected_error";
256
+ this.emit("poll_error", { code: errorCode });
257
+ delayMs = this.backoffMs;
258
+ this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs);
259
+ }
260
+
261
+ if (!this.running) {
262
+ return;
263
+ }
264
+ this.timer = setTimeout(() => {
265
+ this.timer = undefined;
266
+ this.pollTask = this.pollCycle();
267
+ }, delayMs);
268
+ }
269
+
270
+ /**
271
+ * 更新服务端建议的下一轮长轮询超时。
272
+ *
273
+ * @param updates iLink getupdates 响应。
274
+ * @returns 无返回值。
275
+ */
276
+ private updateLongPollTimeout(updates: IlinkGetUpdatesResponse): void {
277
+ const timeout = updates.longpolling_timeout_ms;
278
+ if (typeof timeout === "number" && Number.isInteger(timeout) && timeout >= 1000 && timeout <= 120000) {
279
+ this.longPollTimeoutMs = timeout;
280
+ }
281
+ }
282
+ }
283
+
284
+ /**
285
+ * 从 iLink 入站消息提取所有文本片段。
286
+ *
287
+ * @param message iLink 消息。
288
+ * @returns 以换行分隔的文本内容。
289
+ */
290
+ function extractText(message: IlinkTextMessage): string {
291
+ return (message.item_list ?? [])
292
+ .filter((item) => item.type === 1 && typeof item.text_item?.text === "string")
293
+ .map((item) => item.text_item?.text ?? "")
294
+ .filter((text) => text.length > 0)
295
+ .join("\n");
296
+ }
297
+
298
+ /**
299
+ * 为不支持的媒体提示生成重试稳定的 iLink client_id。
300
+ *
301
+ * @param message iLink 消息。
302
+ * @returns 确定性发送 ID。
303
+ */
304
+ function stableUnsupportedReplyId(message: IlinkTextMessage): string {
305
+ const messageId = String(message.message_id ?? message.client_id ?? "unknown");
306
+ return `piw-unsupported-${createHash("sha256").update(messageId).digest("hex").slice(0, 32)}`;
307
+ }
308
+
309
+ /**
310
+ * 为普通回复生成确定性 iLink client_id, 以便发送端重试时被服务端去重。
311
+ *
312
+ * @param routeId route ID。
313
+ * @param messageId 入站消息 ID。
314
+ * @param text 回复文本。
315
+ * @returns 确定性发送 ID。
316
+ */
317
+ function stableReplyId(routeId: string, messageId: string, text: string): string {
318
+ const contentHash = createHash("sha256").update(`${routeId}\n${messageId}\n${text}`).digest("hex");
319
+ return `piw-reply-${contentHash.slice(0, 32)}`;
320
+ }
@@ -0,0 +1,134 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { GatewayLease } from "../../registry/gateway-lease.ts";
5
+
6
+ /**
7
+ * 持久化格式, 仅保存不透明的同步游标。
8
+ */
9
+ interface CursorRecord {
10
+ schemaVersion: 1;
11
+ getUpdatesBuf: string;
12
+ }
13
+
14
+ /**
15
+ * 表示 iLink 同步游标文件无效。
16
+ */
17
+ export class IlinkCursorError extends Error {
18
+ /**
19
+ * 创建游标文件错误。
20
+ *
21
+ * @param message 不包含游标内容的中文说明。
22
+ */
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "IlinkCursorError";
26
+ }
27
+ }
28
+
29
+ /**
30
+ * 在 manager 私有目录中原子保存 iLink get_updates_buf。
31
+ */
32
+ export class IlinkCursorStore {
33
+ /**
34
+ * 创建 iLink 游标存储。
35
+ *
36
+ * @param filePath 独立游标文件路径。
37
+ * @param lease 当前 Gateway owner 租约。
38
+ */
39
+ constructor(
40
+ readonly filePath: string,
41
+ private readonly lease: GatewayLease,
42
+ ) {}
43
+
44
+ /**
45
+ * 读取已持久化的 get_updates_buf; 首次运行返回空字符串。
46
+ *
47
+ * @returns 不透明同步游标。
48
+ * @throws {IlinkCursorError} 文件损坏或版本不兼容时抛出。
49
+ */
50
+ async load(): Promise<string> {
51
+ try {
52
+ const content = await readFile(this.filePath, "utf8");
53
+ let parsed: unknown;
54
+ try {
55
+ parsed = JSON.parse(content) as unknown;
56
+ } catch {
57
+ throw new IlinkCursorError("iLink cursor 文件不是有效 JSON, 已停止轮询。");
58
+ }
59
+ if (
60
+ typeof parsed !== "object" ||
61
+ parsed === null ||
62
+ Array.isArray(parsed) ||
63
+ !("schemaVersion" in parsed) ||
64
+ parsed.schemaVersion !== 1 ||
65
+ !("getUpdatesBuf" in parsed) ||
66
+ typeof parsed.getUpdatesBuf !== "string"
67
+ ) {
68
+ throw new IlinkCursorError("iLink cursor 文件格式不兼容, 已停止轮询。");
69
+ }
70
+ return parsed.getUpdatesBuf;
71
+ } catch (error) {
72
+ if (isNodeError(error) && error.code === "ENOENT") {
73
+ return "";
74
+ }
75
+ throw error;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 在 Gateway lease 下原子保存同步游标。
81
+ *
82
+ * @param getUpdatesBuf iLink 返回的不透明游标。
83
+ * @returns 无返回值。
84
+ * @throws {IlinkCursorError} 游标无效时抛出。
85
+ */
86
+ async save(getUpdatesBuf: string): Promise<void> {
87
+ if (typeof getUpdatesBuf !== "string" || getUpdatesBuf.length > 1024 * 1024) {
88
+ throw new IlinkCursorError("iLink get_updates_buf 无效或超过大小限制。");
89
+ }
90
+ await this.lease.assertOwned();
91
+ await mkdir(dirname(this.filePath), { recursive: true });
92
+ const record: CursorRecord = {
93
+ schemaVersion: 1,
94
+ getUpdatesBuf,
95
+ };
96
+ const temporaryPath = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
97
+ const handle = await open(temporaryPath, "wx", 0o600);
98
+ try {
99
+ await handle.writeFile(`${JSON.stringify(record)}\n`, "utf8");
100
+ await handle.sync();
101
+ } catch (error) {
102
+ await handle.close();
103
+ try {
104
+ await unlink(temporaryPath);
105
+ } catch {
106
+ throw new IlinkCursorError("iLink cursor 写入失败且临时文件无法清理。");
107
+ }
108
+ throw error;
109
+ }
110
+ await handle.close();
111
+ try {
112
+ await rename(temporaryPath, this.filePath);
113
+ } catch (error) {
114
+ try {
115
+ await unlink(temporaryPath);
116
+ } catch (cleanupError) {
117
+ if (!isNodeError(cleanupError) || cleanupError.code !== "ENOENT") {
118
+ throw cleanupError;
119
+ }
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 判断值是否为 Node.js 文件系统错误。
128
+ *
129
+ * @param error 待检查值。
130
+ * @returns 值带有 Node.js 错误代码时返回 true。
131
+ */
132
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
133
+ return error instanceof Error && "code" in error;
134
+ }