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,309 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { randomUUID } from "node:crypto";
3
+ import type { PiCliInvocation } from "./pi-cli.ts";
4
+ import { PiRpcClient, PiRpcError } from "./pi-rpc-client.ts";
5
+ import type { WorkerState } from "../registry/types.ts";
6
+
7
+ export interface BackgroundPiWorkerOptions {
8
+ invocation: PiCliInvocation;
9
+ cwd: string;
10
+ name?: string;
11
+ sessionFile?: string;
12
+ sessionDirectory?: string;
13
+ env?: NodeJS.ProcessEnv;
14
+ disableDiscoveredResources?: boolean;
15
+ startupTimeoutMs?: number;
16
+ turnTimeoutMs?: number;
17
+ shutdownTimeoutMs?: number;
18
+ }
19
+
20
+ export interface BackgroundPiSessionInfo {
21
+ instanceId: string;
22
+ pid: number;
23
+ processBirthId: string;
24
+ sessionId: string;
25
+ sessionFile: string;
26
+ cwd: string;
27
+ name?: string;
28
+ }
29
+
30
+ /**
31
+ * 表示后台 Pi worker 当前不可接受消息。
32
+ */
33
+ export class BackgroundWorkerBusyError extends Error {
34
+ /**
35
+ * 创建 worker busy 错误。
36
+ *
37
+ * @param message 面向用户的中文错误信息。
38
+ */
39
+ constructor(message: string) {
40
+ super(message);
41
+ this.name = "BackgroundWorkerBusyError";
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 通过 Pi RPC 管理一个原生持久化 session 的后台 runtime。
47
+ */
48
+ export class BackgroundPiWorker extends EventEmitter {
49
+ readonly info: BackgroundPiSessionInfo;
50
+ readonly client: PiRpcClient;
51
+ private currentState: WorkerState = "idle";
52
+ private readonly turnTimeoutMs: number;
53
+ private readonly shutdownTimeoutMs: number;
54
+
55
+ /**
56
+ * 创建已完成 Pi RPC 握手的后台 worker。
57
+ *
58
+ * @param client Pi RPC 客户端。
59
+ * @param info Pi 返回的 session 和进程信息。
60
+ * @param turnTimeoutMs 单轮模型执行超时。
61
+ * @param shutdownTimeoutMs 优雅退出等待时长。
62
+ */
63
+ private constructor(
64
+ client: PiRpcClient,
65
+ info: BackgroundPiSessionInfo,
66
+ turnTimeoutMs: number,
67
+ shutdownTimeoutMs: number,
68
+ ) {
69
+ super();
70
+ this.client = client;
71
+ this.info = info;
72
+ this.turnTimeoutMs = turnTimeoutMs;
73
+ this.shutdownTimeoutMs = shutdownTimeoutMs;
74
+ this.currentState = client.isClosed ? "stale" : "idle";
75
+ client.on("process_exit", () => this.setState("stale"));
76
+ }
77
+
78
+ /**
79
+ * 创建或恢复 Pi session, 并等待 Pi 报告 sessionId/sessionFile。
80
+ *
81
+ * @param options worker 启动参数。
82
+ * @returns 已注册 session 信息的后台 worker。
83
+ * @throws {PiRpcError} Pi 启动失败或未返回 session 元数据时抛出。
84
+ */
85
+ static async start(options: BackgroundPiWorkerOptions): Promise<BackgroundPiWorker> {
86
+ const args: string[] = [];
87
+ if (options.sessionDirectory) {
88
+ args.push("--session-dir", options.sessionDirectory);
89
+ }
90
+ if (options.sessionFile) {
91
+ args.push("--session", options.sessionFile);
92
+ }
93
+ if (options.name) {
94
+ args.push("--name", options.name);
95
+ }
96
+ if (options.disableDiscoveredResources) {
97
+ args.push(
98
+ "--no-extensions",
99
+ "--no-skills",
100
+ "--no-prompt-templates",
101
+ "--no-context-files",
102
+ );
103
+ }
104
+
105
+ const client = await PiRpcClient.start({
106
+ invocation: options.invocation,
107
+ args,
108
+ cwd: options.cwd,
109
+ env: options.env,
110
+ requestTimeoutMs: options.startupTimeoutMs ?? 15000,
111
+ });
112
+
113
+ try {
114
+ const stateResponse = await client.request(
115
+ { type: "get_state" },
116
+ options.startupTimeoutMs ?? 15000,
117
+ );
118
+ if (options.name) {
119
+ await client.request(
120
+ { type: "set_session_name", name: options.name },
121
+ options.startupTimeoutMs ?? 15000,
122
+ );
123
+ }
124
+ const state = asRecord(stateResponse.data);
125
+ const sessionId = state?.sessionId;
126
+ const sessionFile = state?.sessionFile;
127
+ if (typeof sessionId !== "string" || !sessionId || typeof sessionFile !== "string" || !sessionFile) {
128
+ throw new PiRpcError("Pi RPC 未返回持久化 sessionId/sessionFile。");
129
+ }
130
+ const pid = client.pid;
131
+ if (typeof pid !== "number") {
132
+ throw new PiRpcError("Pi RPC 子进程缺少 PID。");
133
+ }
134
+ if (client.isClosed) {
135
+ throw new PiRpcError("Pi RPC 在完成启动握手后立即退出。");
136
+ }
137
+ const info: BackgroundPiSessionInfo = {
138
+ instanceId: randomUUID(),
139
+ pid,
140
+ processBirthId: `${pid}:${Date.now()}`,
141
+ sessionId,
142
+ sessionFile,
143
+ cwd: options.cwd,
144
+ ...(options.name
145
+ ? { name: options.name }
146
+ : typeof state.sessionName === "string"
147
+ ? { name: state.sessionName }
148
+ : {}),
149
+ };
150
+ return new BackgroundPiWorker(
151
+ client,
152
+ info,
153
+ options.turnTimeoutMs ?? 15 * 60 * 1000,
154
+ options.shutdownTimeoutMs ?? 5000,
155
+ );
156
+ } catch (error) {
157
+ await client.shutdown(2000).catch(() => undefined);
158
+ throw error;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 获取 worker 当前运行状态。
164
+ *
165
+ * @returns worker 状态。
166
+ */
167
+ get state(): WorkerState {
168
+ return this.currentState;
169
+ }
170
+
171
+ /**
172
+ * 向后台 Pi session 发送一条用户消息并等待本轮最终文本。
173
+ *
174
+ * @param message 用户消息正文。
175
+ * @returns Pi 最终 assistant 文本。
176
+ * @throws {BackgroundWorkerBusyError} worker 正在执行其他 turn 时抛出。
177
+ * @throws {PiRpcError} prompt 被拒绝、超时或没有最终文本时抛出。
178
+ */
179
+ async prompt(message: string): Promise<string> {
180
+ if (this.currentState !== "idle") {
181
+ throw new BackgroundWorkerBusyError("后台 Pi session 当前不可接受新消息。");
182
+ }
183
+ if (!message.trim()) {
184
+ throw new PiRpcError("不能发送空消息。");
185
+ }
186
+
187
+ this.setState("running");
188
+ let accepted = false;
189
+ let settled = false;
190
+ const abortController = new AbortController();
191
+ const assistantMessages: string[] = [];
192
+ const onMessageEnd = (event: Record<string, unknown>): void => {
193
+ const agentMessage = asRecord(event.message);
194
+ if (agentMessage?.role !== "assistant") {
195
+ return;
196
+ }
197
+ const text = extractAssistantText(agentMessage.content);
198
+ if (text) {
199
+ assistantMessages.push(text);
200
+ }
201
+ };
202
+ this.client.on("message_end", onMessageEnd);
203
+ const settledPromise = this.client.waitForEvent(
204
+ "agent_settled",
205
+ this.turnTimeoutMs,
206
+ abortController.signal,
207
+ );
208
+
209
+ try {
210
+ const response = await this.client.request({
211
+ type: "prompt",
212
+ message,
213
+ });
214
+ const responseData = asRecord(response.data);
215
+ if (responseData?.disposition === "handled") {
216
+ throw new PiRpcError("Pi extension 已处理该消息, 没有启动模型 turn。", "prompt");
217
+ }
218
+ accepted = true;
219
+ await settledPromise;
220
+ settled = true;
221
+ const finalText = assistantMessages.at(-1);
222
+ if (!finalText) {
223
+ throw new PiRpcError("Pi session 已结束本轮, 但没有可返回的 assistant 文本。");
224
+ }
225
+ return finalText;
226
+ } catch (error) {
227
+ abortController.abort();
228
+ await settledPromise.catch(() => undefined);
229
+ throw error;
230
+ } finally {
231
+ this.client.off("message_end", onMessageEnd);
232
+ if ((settled || !accepted) && this.state !== "stale") {
233
+ this.setState("idle");
234
+ }
235
+ }
236
+ }
237
+
238
+ /**
239
+ * 优雅关闭 worker; 正在运行时需显式指定允许 abort。
240
+ *
241
+ * @param options 关闭策略。
242
+ * @returns 无返回值。
243
+ * @throws {BackgroundWorkerBusyError} 正在运行且未授权 abort 时抛出。
244
+ * @throws {PiRpcError} Pi 未能在超时内退出时抛出, 不会自动强杀。
245
+ */
246
+ async shutdown(options: { abortRunning?: boolean } = {}): Promise<void> {
247
+ if (this.currentState === "stale") {
248
+ return;
249
+ }
250
+ if (this.currentState === "running") {
251
+ if (!options.abortRunning) {
252
+ throw new BackgroundWorkerBusyError(
253
+ "后台 Pi session 正在执行; 请等待结束或显式确认 abort 后再关闭。",
254
+ );
255
+ }
256
+ await this.client.request({ type: "abort" }, this.turnTimeoutMs);
257
+ }
258
+ this.setState("stopping");
259
+ await this.client.shutdown(this.shutdownTimeoutMs);
260
+ this.setState("stale");
261
+ }
262
+
263
+ /**
264
+ * 更新 worker 状态并通知监听者。
265
+ *
266
+ * @param state 新状态。
267
+ * @returns 无返回值。
268
+ */
269
+ private setState(state: WorkerState): void {
270
+ if (this.currentState === state) {
271
+ return;
272
+ }
273
+ this.currentState = state;
274
+ this.emit("state_change", state);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * 将未知 RPC payload 转换为对象。
280
+ *
281
+ * @param value 待检查值。
282
+ * @returns 普通对象或 undefined。
283
+ */
284
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
285
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
286
+ return undefined;
287
+ }
288
+ return value as Record<string, unknown>;
289
+ }
290
+
291
+ /**
292
+ * 提取 assistant 消息中的普通文本, 不暴露 thinking 或工具参数。
293
+ *
294
+ * @param content Pi message content。
295
+ * @returns 拼接后的普通文本。
296
+ */
297
+ function extractAssistantText(content: unknown): string {
298
+ if (typeof content === "string") {
299
+ return content;
300
+ }
301
+ if (!Array.isArray(content)) {
302
+ return "";
303
+ }
304
+ return content
305
+ .map((block) => asRecord(block))
306
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
307
+ .map((block) => block?.text as string)
308
+ .join("");
309
+ }