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,1449 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { createInterface } from "node:readline";
4
+ import { ConfigurationStore } from "../config/store.ts";
5
+ import type { ManagerConfiguration, RuntimeMode } from "../config/types.ts";
6
+ import type { GatewayInboundMessage, IlinkReplyContext } from "./channel-types.ts";
7
+ import { ProjectService, ProjectServiceError } from "../projects/project-service.ts";
8
+ import { parseProjectCommand, ProjectCommandParseError } from "../commands/project-command-parser.ts";
9
+ import { parseGatewayCommand, GatewayCommandParseError } from "./command-parser.ts";
10
+ import {
11
+ DurableMessageQueue,
12
+ DurableQueueError,
13
+ type DurableQueueItem,
14
+ type QueueDispatchResult,
15
+ type QueueProcessor,
16
+ } from "./durable-message-queue.ts";
17
+ import { ManagerRegistry } from "../registry/manager-registry.ts";
18
+ import { GatewayLease } from "../registry/gateway-lease.ts";
19
+ import type { SessionIndexRecord } from "../registry/types.ts";
20
+ import { BackgroundWorkerManagerError } from "../runtime/background-worker-manager.ts";
21
+ import type { GatewayWorkerService } from "../runtime/gateway-worker-manager.ts";
22
+ import { UiWorkerManagerError } from "../runtime/ui-worker-manager.ts";
23
+
24
+ export type InboundGatewayMessage = GatewayInboundMessage;
25
+
26
+ export interface GatewayReceiveResult {
27
+ messageId: string;
28
+ state: string;
29
+ duplicate: boolean;
30
+ reply?: string;
31
+ }
32
+
33
+ export type GatewayReplySink = (
34
+ routeId: string,
35
+ messageId: string,
36
+ reply: string,
37
+ replyContext?: IlinkReplyContext,
38
+ ) => Promise<void>;
39
+
40
+ /**
41
+ * 管理消息进入 worker 到最终回复之间的可见处理状态。
42
+ */
43
+ export interface GatewayProcessingIndicator {
44
+ /**
45
+ * 开始该 queue 消息的用户可见处理状态。
46
+ *
47
+ * @param messageId durable queue 消息 ID。
48
+ * @param replyContext 对应入站消息的回复上下文。
49
+ * @returns 无返回值。
50
+ */
51
+ start(messageId: string, replyContext?: IlinkReplyContext): void;
52
+
53
+ /**
54
+ * 结束该 queue 消息的用户可见处理状态。
55
+ *
56
+ * @param messageId durable queue 消息 ID。
57
+ * @returns 无返回值。
58
+ */
59
+ stop(messageId: string): void;
60
+ }
61
+
62
+ /**
63
+ * 表示消息发送者未通过个人微信 allowlist。
64
+ */
65
+ export class GatewayAuthorizationError extends Error {
66
+ /**
67
+ * 创建微信授权错误。
68
+ *
69
+ * @param code 稳定错误代码。
70
+ * @param message 不暴露本地配置的中文错误说明。
71
+ */
72
+ constructor(
73
+ readonly code: "wechat_auth_unavailable" | "unauthorized_wechat_user",
74
+ message: string,
75
+ ) {
76
+ super(message);
77
+ this.name = "GatewayAuthorizationError";
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 将授权消息路由到管理命令或当前 Pi session, 并经 durable queue 按 route FIFO 处理。
83
+ */
84
+ export class GatewayCommandRouter {
85
+ private readonly configStore: ConfigurationStore;
86
+ private readonly projectService: ProjectService;
87
+ private readonly workerManager: GatewayWorkerService;
88
+ private readonly registry: ManagerRegistry;
89
+ private readonly queue: DurableMessageQueue;
90
+ private readonly lease: GatewayLease;
91
+ private readonly replySink?: GatewayReplySink;
92
+ private readonly processingIndicator?: GatewayProcessingIndicator;
93
+ private readonly uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
94
+
95
+ /**
96
+ * 创建 Gateway 命令路由器。
97
+ *
98
+ * @param options 路由依赖和可选回复发送器。
99
+ */
100
+ constructor(options: {
101
+ configStore: ConfigurationStore;
102
+ projectService: ProjectService;
103
+ workerManager: GatewayWorkerService;
104
+ registry: ManagerRegistry;
105
+ queue: DurableMessageQueue;
106
+ lease: GatewayLease;
107
+ replySink?: GatewayReplySink;
108
+ processingIndicator?: GatewayProcessingIndicator;
109
+ uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
110
+ }) {
111
+ this.configStore = options.configStore;
112
+ this.projectService = options.projectService;
113
+ this.workerManager = options.workerManager;
114
+ this.registry = options.registry;
115
+ this.queue = options.queue;
116
+ this.lease = options.lease;
117
+ this.replySink = options.replySink;
118
+ this.processingIndicator = options.processingIndicator;
119
+ this.uiModeCapability = options.uiModeCapability;
120
+ }
121
+
122
+ /**
123
+ * 验证 sender allowlist, 持久化去重消息并等待 FIFO 处理结果。
124
+ *
125
+ * @param message 正规化后的微信消息。
126
+ * @returns 去重、处理状态及可选回复。
127
+ * @throws {GatewayAuthorizationError} 未配置 allowlist 或 sender 不匹配时抛出。
128
+ */
129
+ async receive(message: InboundGatewayMessage): Promise<GatewayReceiveResult> {
130
+ await this.lease.assertOwned();
131
+ const { config } = await this.configStore.load();
132
+ this.assertAuthorized(message.senderId, config);
133
+ if (!message.messageId.trim() || !message.text.trim()) {
134
+ throw new GatewayCommandParseError("微信消息缺少 messageId 或正文, 已拒绝路由。");
135
+ }
136
+
137
+ let command;
138
+ try {
139
+ command = parseGatewayCommand(message.text);
140
+ } catch (error) {
141
+ if (!(error instanceof GatewayCommandParseError)) {
142
+ throw error;
143
+ }
144
+ if (this.replySink) {
145
+ await this.replySink(message.senderId, message.messageId, error.message, message.replyContext);
146
+ }
147
+ return {
148
+ messageId: message.messageId,
149
+ state: "rejected",
150
+ duplicate: false,
151
+ ...(this.replySink ? {} : { reply: error.message }),
152
+ };
153
+ }
154
+ const routeId = message.senderId;
155
+ if (command.kind === "retry") {
156
+ return this.retryMessage(
157
+ routeId,
158
+ command.messageId,
159
+ message.messageId,
160
+ command.confirmed,
161
+ config,
162
+ message.replyContext,
163
+ );
164
+ }
165
+
166
+ const result = await this.queue.dispatch(
167
+ routeId,
168
+ message.messageId,
169
+ message.text,
170
+ config.runtime.maxQueuePerSession,
171
+ this.createProcessor(routeId, config),
172
+ message.replyContext,
173
+ );
174
+ const normalized = toReceiveResult(result);
175
+ if (this.replySink) {
176
+ delete normalized.reply;
177
+ }
178
+ return normalized;
179
+ }
180
+
181
+ /**
182
+ * 快速接收入站消息: 先完成授权与 durable enqueue, 再异步触发 route drain。
183
+ *
184
+ * Channel poller 应在收到此方法成功返回后提交 get_updates_buf, 不必等待 Pi 模型完成。
185
+ *
186
+ * @param message 正规化后的微信消息。
187
+ * @returns 入队结果, 不包含模型回复。
188
+ * @throws {GatewayAuthorizationError} sender 未授权时抛出。
189
+ */
190
+ async acceptInbound(message: InboundGatewayMessage): Promise<GatewayReceiveResult> {
191
+ await this.lease.assertOwned();
192
+ const { config } = await this.configStore.load();
193
+ this.assertAuthorized(message.senderId, config);
194
+ if (!message.messageId.trim() || !message.text.trim()) {
195
+ throw new GatewayCommandParseError("微信消息缺少 messageId 或正文, 已拒绝路由。");
196
+ }
197
+ if (!this.replySink) {
198
+ throw new Error("异步 Gateway 入站处理必须配置 replySink。");
199
+ }
200
+
201
+ let command;
202
+ try {
203
+ command = parseGatewayCommand(message.text);
204
+ } catch (error) {
205
+ if (!(error instanceof GatewayCommandParseError)) {
206
+ throw error;
207
+ }
208
+ await this.replySink(message.senderId, message.messageId, error.message, message.replyContext);
209
+ return {
210
+ messageId: message.messageId,
211
+ state: "rejected",
212
+ duplicate: false,
213
+ };
214
+ }
215
+ const routeId = message.senderId;
216
+ if (command.kind === "retry") {
217
+ return this.retryMessage(
218
+ routeId,
219
+ command.messageId,
220
+ message.messageId,
221
+ command.confirmed,
222
+ config,
223
+ message.replyContext,
224
+ );
225
+ }
226
+
227
+ const enqueued = await this.queue.enqueue(
228
+ routeId,
229
+ message.messageId,
230
+ message.text,
231
+ config.runtime.maxQueuePerSession,
232
+ message.replyContext,
233
+ );
234
+ this.queue.drainPending(routeId, this.createProcessor(routeId, config));
235
+ return {
236
+ messageId: message.messageId,
237
+ state: enqueued.item.state,
238
+ duplicate: enqueued.duplicate,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * 在 Gateway 启动时恢复指定 route 的 queued 消息。
244
+ *
245
+ * @param routeId route 稳定 ID。
246
+ * @returns 无返回值。
247
+ */
248
+ async drainPending(routeId: string): Promise<void> {
249
+ if (!this.replySink) {
250
+ throw new Error("Gateway 启动恢复队列需要配置 replySink。");
251
+ }
252
+ await this.lease.assertOwned();
253
+ const { config } = await this.configStore.load();
254
+ this.queue.drainPending(routeId, this.createProcessor(routeId, config));
255
+ }
256
+
257
+ /**
258
+ * 生成单条 queue 消息处理器。
259
+ *
260
+ * @param routeId route 稳定 ID。
261
+ * @param config 当前配置快照。
262
+ * @returns 处理队列消息的异步函数。
263
+ */
264
+ private createProcessor(routeId: string, config: ManagerConfiguration): QueueProcessor {
265
+ return async (item) => {
266
+ this.processingIndicator?.start(item.messageId, item.replyContext);
267
+ try {
268
+ const reply = await this.processQueueItem(routeId, item, config);
269
+ if (this.replySink) {
270
+ await this.replySink(routeId, item.messageId, reply, item.replyContext);
271
+ }
272
+ return reply;
273
+ } finally {
274
+ this.processingIndicator?.stop(item.messageId);
275
+ }
276
+ };
277
+ }
278
+
279
+ /**
280
+ * 对失败或中断的入站消息执行显式重试; retry control command 本身不重放。
281
+ *
282
+ * @param routeId 微信 route ID。
283
+ * @param targetMessageId 需要重试的原始消息 ID。
284
+ * @param controlMessageId 当前 /retry 命令 ID。
285
+ * @param confirmed 是否带有显式确认标志。
286
+ * @param config 当前配置快照。
287
+ * @returns retry 结果。
288
+ */
289
+ private async retryMessage(
290
+ routeId: string,
291
+ targetMessageId: string,
292
+ controlMessageId: string,
293
+ confirmed: boolean,
294
+ config: ManagerConfiguration,
295
+ controlReplyContext?: IlinkReplyContext,
296
+ ): Promise<GatewayReceiveResult> {
297
+ if (!confirmed) {
298
+ const warning = "重试会重新执行原 prompt, 可能重复产生副作用。确认后使用 /retry <message-id> --confirm。";
299
+ if (this.replySink) {
300
+ await this.replySink(routeId, controlMessageId, warning, controlReplyContext);
301
+ }
302
+ return {
303
+ messageId: controlMessageId,
304
+ state: "confirmation_required",
305
+ duplicate: false,
306
+ ...(this.replySink ? {} : { reply: warning }),
307
+ };
308
+ }
309
+
310
+ let items: DurableQueueItem[];
311
+ try {
312
+ items = await this.queue.recoverInterrupted(routeId);
313
+ } catch (error) {
314
+ const message = error instanceof DurableQueueError
315
+ ? error.message
316
+ : "无法安全恢复当前 route queue。";
317
+ if (this.replySink) {
318
+ await this.replySink(routeId, controlMessageId, message, controlReplyContext);
319
+ }
320
+ return {
321
+ messageId: controlMessageId,
322
+ state: "retry_blocked",
323
+ duplicate: false,
324
+ ...(this.replySink ? {} : { reply: message }),
325
+ };
326
+ }
327
+ const target = items.find((item) => item.messageId === targetMessageId);
328
+ if (!target) {
329
+ const notFound = `未找到 queue 消息: ${targetMessageId}。`;
330
+ if (this.replySink) {
331
+ await this.replySink(routeId, controlMessageId, notFound, controlReplyContext);
332
+ }
333
+ return {
334
+ messageId: controlMessageId,
335
+ state: "not_found",
336
+ duplicate: false,
337
+ ...(this.replySink ? {} : { reply: notFound }),
338
+ };
339
+ }
340
+ let originalCommand;
341
+ try {
342
+ originalCommand = parseGatewayCommand(target.text);
343
+ } catch {
344
+ originalCommand = undefined;
345
+ }
346
+ if (!originalCommand || originalCommand.kind === "retry") {
347
+ const notRetryable = "无法识别原 queue 命令; 不会自动重放 control command。";
348
+ if (this.replySink) {
349
+ await this.replySink(routeId, controlMessageId, notRetryable, controlReplyContext);
350
+ }
351
+ return {
352
+ messageId: controlMessageId,
353
+ state: "not_retryable",
354
+ duplicate: false,
355
+ ...(this.replySink ? {} : { reply: notRetryable }),
356
+ };
357
+ }
358
+
359
+ try {
360
+ await this.queue.retry(routeId, targetMessageId);
361
+ } catch (error) {
362
+ const message = error instanceof DurableQueueError ? error.message : "queue retry 失败。";
363
+ if (this.replySink) {
364
+ await this.replySink(routeId, controlMessageId, message, controlReplyContext);
365
+ }
366
+ return {
367
+ messageId: controlMessageId,
368
+ state: "retry_rejected",
369
+ duplicate: false,
370
+ ...(this.replySink ? {} : { reply: message }),
371
+ };
372
+ }
373
+
374
+ const retryNotice = `已确认重试 ${targetMessageId}; 原 prompt 会再次执行, 请留意可能的重复副作用。`;
375
+ if (this.replySink) {
376
+ await this.replySink(routeId, controlMessageId, retryNotice, controlReplyContext);
377
+ }
378
+ const result = await this.queue.dispatch(
379
+ routeId,
380
+ targetMessageId,
381
+ target.text,
382
+ config.runtime.maxQueuePerSession,
383
+ this.createProcessor(routeId, config),
384
+ target.replyContext,
385
+ );
386
+ return {
387
+ messageId: controlMessageId,
388
+ state: result.item.state,
389
+ duplicate: false,
390
+ ...(this.replySink ? {} : { reply: result.reply ?? retryNotice }),
391
+ };
392
+ }
393
+
394
+ /**
395
+ * 登记或更改一个项目 alias。
396
+ *
397
+ * @param arguments_ /projects 后的原始参数。
398
+ * @returns 命令回复。
399
+ */
400
+ private async handleProjects(arguments_: string): Promise<string> {
401
+ let command;
402
+ try {
403
+ command = parseProjectCommand(arguments_);
404
+ } catch (error) {
405
+ if (error instanceof ProjectCommandParseError) {
406
+ return error.message;
407
+ }
408
+ throw error;
409
+ }
410
+
411
+ if (command.action === "list") {
412
+ const { config, projects } = await this.projectService.list();
413
+ if (projects.length === 0) {
414
+ return config.allowedProjectRoots.length === 0
415
+ ? "尚无项目 alias。请先在配置文件设置 allowedProjectRoots。"
416
+ : "尚无项目 alias, 可用 /projects add 登记项目。";
417
+ }
418
+ return [
419
+ "已登记项目:",
420
+ ...projects.map(([alias, project]) => {
421
+ const defaultMark = config.defaultProject === alias ? " (默认)" : "";
422
+ return `${alias}${defaultMark}: ${project.displayName}`;
423
+ }),
424
+ ].join("\n");
425
+ }
426
+ if (command.action === "add") {
427
+ const project = await this.projectService.add(
428
+ command.alias,
429
+ command.displayName,
430
+ command.path,
431
+ );
432
+ return `项目已登记: ${command.alias} - ${project.displayName}`;
433
+ }
434
+ if (command.action === "remove") {
435
+ await this.projectService.remove(command.alias);
436
+ return `已移除项目登记: ${command.alias}; 项目目录未删除。`;
437
+ }
438
+ await this.projectService.setDefault(command.alias);
439
+ return `默认项目已设置为: ${command.alias}`;
440
+ }
441
+
442
+ /**
443
+ * 创建后台或可见 UI Pi session 并原子切换当前 route 绑定。
444
+ *
445
+ * @param routeId 微信 route ID。
446
+ * @param mode 新会话运行模式, 缺省为后台。
447
+ * @param projectAlias 用户指定项目 alias。
448
+ * @param name 可选 session 名称。
449
+ * @param config 当前配置快照。
450
+ * @returns 创建结果。
451
+ */
452
+ private async handleNew(
453
+ routeId: string,
454
+ mode: RuntimeMode | undefined,
455
+ projectAlias: string | undefined,
456
+ name: string | undefined,
457
+ config: ManagerConfiguration,
458
+ ): Promise<string> {
459
+ const requestedMode = mode ?? "background";
460
+ const alias = projectAlias ?? config.defaultProject;
461
+ if (!alias) {
462
+ return "尚未设置 defaultProject。请先通过 /projects default <alias> 选择项目。";
463
+ }
464
+
465
+ const oldSnapshot = await this.registry.readSnapshot();
466
+ const oldRoute = Object.hasOwn(oldSnapshot.routes, routeId)
467
+ ? oldSnapshot.routes[routeId]
468
+ : undefined;
469
+ const session = await this.workerManager.startNew(alias, name, requestedMode);
470
+ const newSnapshot = await this.registry.readSnapshot();
471
+ const indexedSession = newSnapshot.sessions[session.sessionId];
472
+ const owner = Object.values(newSnapshot.instances).find((instance) =>
473
+ instance.sessionId === session.sessionId,
474
+ );
475
+ if (!owner) {
476
+ await this.workerManager.stop(session.sessionId).catch(() => undefined);
477
+ throw new BackgroundWorkerManagerError(
478
+ "worker_not_found",
479
+ "Pi worker 已启动, 但 registry 未登记 owner; 已尝试优雅停止。",
480
+ );
481
+ }
482
+
483
+ try {
484
+ await this.registry.setRoute(routeId, {
485
+ sessionId: session.sessionId,
486
+ workerInstanceId: owner.instanceId,
487
+ generation: (oldRoute?.generation ?? 0) + 1,
488
+ updatedAt: new Date().toISOString(),
489
+ });
490
+ } catch (error) {
491
+ await this.workerManager.stop(session.sessionId).catch(() => undefined);
492
+ throw error;
493
+ }
494
+ const stateText = indexedSession?.state === "pending" ? "等待首条 transcript 写入" : "活跃";
495
+ const modeText = requestedMode === "ui" ? "可见 UI" : "后台";
496
+ return `${modeText} Pi session 已创建: ${indexedSession?.name ?? `#${indexedSession?.publicIndex ?? "?"}`} (${alias}, ${stateText})。`;
497
+ }
498
+
499
+ /**
500
+ * 列出 sessions, 不更改当前 route。
501
+ *
502
+ * @param routeId 当前微信 route ID。
503
+ * @param projectAlias 可选项目筛选。
504
+ * @param state 状态筛选。
505
+ * @param page 页码。
506
+ * @param config 当前配置快照。
507
+ * @returns 分页清单文本。
508
+ */
509
+ private async formatSessions(
510
+ routeId: string,
511
+ projectAlias: string | undefined,
512
+ state: "default" | "active" | "saved" | "pending" | "all",
513
+ page: number,
514
+ config: ManagerConfiguration,
515
+ ): Promise<string> {
516
+ const snapshot = await this.registry.readSnapshot();
517
+ const currentRouteSessionId = snapshot.routes[routeId]?.sessionId;
518
+ const activeSessionIds = new Set(
519
+ Object.values(snapshot.instances)
520
+ .filter((instance) => instance.state !== "stale" && instance.state !== "stopping")
521
+ .map((instance) => instance.sessionId),
522
+ );
523
+ const sessions = Object.values(snapshot.sessions)
524
+ .filter((session) => !projectAlias || session.projectAlias === projectAlias)
525
+ .filter((session) => {
526
+ if (state === "all") {
527
+ return true;
528
+ }
529
+ if (state === "active") {
530
+ return activeSessionIds.has(session.sessionId);
531
+ }
532
+ if (state === "default") {
533
+ return activeSessionIds.has(session.sessionId) || session.state === "saved";
534
+ }
535
+ return session.state === state;
536
+ })
537
+ .sort((left, right) => right.lastActivityAt.localeCompare(left.lastActivityAt));
538
+ const pageSize = 5;
539
+ const pageCount = Math.max(1, Math.ceil(sessions.length / pageSize));
540
+ if (page > pageCount) {
541
+ return `没有第 ${page} 页; 共 ${pageCount} 页。`;
542
+ }
543
+ const pageSessions = sessions.slice((page - 1) * pageSize, page * pageSize);
544
+ if (pageSessions.length === 0) {
545
+ return "没有匹配的会话。";
546
+ }
547
+ const displaySessions = await Promise.all(pageSessions.map(async (session) => ({
548
+ session,
549
+ title: await resolveSessionTitle(session),
550
+ })));
551
+ const currentRouteSession = currentRouteSessionId
552
+ ? snapshot.sessions[currentRouteSessionId]
553
+ : undefined;
554
+ const currentRouteLabel = currentRouteSession
555
+ ? `当前微信路由:#${currentRouteSession.publicIndex ?? "?"}`
556
+ : undefined;
557
+ const cards = displaySessions.map(({ session, title }) => {
558
+ const projectName = Object.hasOwn(config.projects, session.projectAlias)
559
+ ? config.projects[session.projectAlias].displayName
560
+ : session.projectAlias;
561
+ const status = activeSessionIds.has(session.sessionId)
562
+ ? session.state === "pending" ? "等待首条记录" : "活跃"
563
+ : session.state === "pending" ? "等待首条记录" : "已保存";
564
+ const mode = activeSessionIds.has(session.sessionId) && session.mode === "ui" ? "前台" : "后台";
565
+ const currentMark = currentRouteSessionId === session.sessionId ? "【当前】" : "";
566
+ return `${currentMark}#${session.publicIndex ?? "?"} ${title}\n项目:${projectName} · ${mode} · ${status}`;
567
+ });
568
+ const pageHint = pageCount > 1
569
+ ? page < pageCount
570
+ ? `下一页:${buildSessionsPageCommand(page + 1, projectAlias, state)}`
571
+ : `上一页:${buildSessionsPageCommand(page - 1, projectAlias, state)}`
572
+ : undefined;
573
+ return [
574
+ `会话列表 · 第 ${page}/${pageCount} 页 · 共 ${sessions.length} 个`,
575
+ ...(currentRouteLabel ? [currentRouteLabel] : []),
576
+ ...cards,
577
+ "切换会话:/resume <索引或名称>",
578
+ ...(pageHint ? [pageHint] : []),
579
+ ].join("\n\n");
580
+ }
581
+
582
+ /**
583
+ * 恢复唯一匹配的 session 并切换当前 route。
584
+ *
585
+ * @param routeId 微信 route ID。
586
+ * @param selector session ID 前缀或名称。
587
+ * @param mode 用户指定恢复模式。
588
+ * @returns 恢复结果。
589
+ */
590
+ private async handleResume(
591
+ routeId: string,
592
+ selector: string,
593
+ ): Promise<string> {
594
+ const session = await this.resolveSessionSelector(selector);
595
+ const previousRoute = (await this.registry.readSnapshot()).routes[routeId];
596
+ await this.workerManager.resume(session.sessionId);
597
+ const snapshot = await this.registry.readSnapshot();
598
+ const owner = Object.values(snapshot.instances).find((instance) =>
599
+ instance.sessionId === session.sessionId,
600
+ );
601
+ if (!owner) {
602
+ throw new BackgroundWorkerManagerError(
603
+ "worker_not_found",
604
+ "Pi session 已启动, 但 registry 未找到 owner。",
605
+ );
606
+ }
607
+ await this.registry.setRoute(routeId, {
608
+ sessionId: session.sessionId,
609
+ workerInstanceId: owner.instanceId,
610
+ generation: (Object.hasOwn(snapshot.routes, routeId) ? snapshot.routes[routeId].generation : 0) + 1,
611
+ updatedAt: new Date().toISOString(),
612
+ });
613
+ const confirmation = `已恢复会话 #${session.publicIndex ?? "?"} ${session.name ?? "未命名"} (${session.projectAlias})。`;
614
+ if (previousRoute?.sessionId === session.sessionId || owner.state !== "idle") {
615
+ return confirmation;
616
+ }
617
+ const latestAssistantText = await readLatestAssistantText(session.sessionFile);
618
+ if (!latestAssistantText) {
619
+ return confirmation;
620
+ }
621
+ const preview = truncateResumeAssistantText(latestAssistantText);
622
+ return `${confirmation}\n\n最近一次回复${preview.truncated ? "(节选)" : ""}:\n${preview.text}${
623
+ preview.truncated ? "\n\n[内容较长, 完整回复仍保留在会话记录中。]" : ""
624
+ }`;
625
+ }
626
+
627
+ /**
628
+ * 只读展示指定或当前 route 会话的最近一轮对话, 不更改 route 绑定, 也不投递 prompt。
629
+ *
630
+ * @param routeId 微信 route ID。
631
+ * @param selector 可选会话索引或名称。
632
+ * @param config 当前配置快照。
633
+ * @returns 最近一轮对话的只读摘要。
634
+ */
635
+ private async handleLast(
636
+ routeId: string,
637
+ selector: string | undefined,
638
+ config: ManagerConfiguration,
639
+ ): Promise<string> {
640
+ const snapshot = await this.registry.readSnapshot();
641
+ const boundSessionId = Object.hasOwn(snapshot.routes, routeId)
642
+ ? snapshot.routes[routeId].sessionId
643
+ : undefined;
644
+ const session = selector
645
+ ? await this.resolveSessionSelector(selector)
646
+ : boundSessionId && Object.hasOwn(snapshot.sessions, boundSessionId)
647
+ ? snapshot.sessions[boundSessionId]
648
+ : undefined;
649
+ if (!session) {
650
+ return "当前微信路由没有绑定会话。使用 /sessions 查看列表, 或 /last <索引> 查看指定会话。";
651
+ }
652
+ const running = Object.values(snapshot.instances).some((instance) =>
653
+ instance.sessionId === session.sessionId && instance.state === "running"
654
+ );
655
+ const projectName = Object.hasOwn(config.projects, session.projectAlias)
656
+ ? config.projects[session.projectAlias].displayName
657
+ : session.projectAlias;
658
+ const title = await resolveSessionTitle(session);
659
+ const header = [
660
+ `会话 #${session.publicIndex ?? "?"} ${title} · ${projectName}`,
661
+ `最后活动:${formatLocalMinute(session.lastActivityAt)} · ${session.mode === "ui" ? "前台" : "后台"}`,
662
+ ];
663
+ const turn = await readLatestTurn(session.sessionFile);
664
+ if (!turn) {
665
+ return [
666
+ ...header,
667
+ "",
668
+ session.state === "pending"
669
+ ? "该会话尚未写入任何对话记录。"
670
+ : "未能读取该会话的对话记录。",
671
+ ].join("\n");
672
+ }
673
+
674
+ const body: string[] = [];
675
+ if (turn.userText) {
676
+ const userPreview = truncateTurnText(turn.userText);
677
+ body.push(`你:\n${userPreview.text}`, ...(userPreview.truncated ? ["[提问较长, 已截断。]"] : []));
678
+ }
679
+ if (turn.assistantText) {
680
+ const assistantPreview = truncateTurnText(turn.assistantText);
681
+ body.push(
682
+ `AI${assistantPreview.truncated ? "(节选)" : ""}:\n${assistantPreview.text}`,
683
+ ...(assistantPreview.truncated ? ["[回复较长, 完整内容仍在会话记录中。]"] : []),
684
+ );
685
+ } else {
686
+ body.push("AI:尚未产生回复。");
687
+ }
688
+ return [
689
+ ...header,
690
+ ...(running ? ["⚠️ 该会话正在运行, 以下为目前已落盘的内容。"] : []),
691
+ "",
692
+ "最近一轮对话",
693
+ ...body,
694
+ "",
695
+ selector ? "发送 /resume " + (session.publicIndex ?? selector) + " 可切换到此会话。" : "发送任意内容可继续对话。",
696
+ ].join("\n");
697
+ }
698
+
699
+ /**
700
+ * 停止当前 route 或指定的活跃 Pi session。
701
+ *
702
+ * @param routeId 微信 route ID。
703
+ * @param selector 可选 session ID 前缀或名称。
704
+ * @returns 停止结果。
705
+ */
706
+ private async handleStop(routeId: string, selector: string | undefined): Promise<string> {
707
+ const snapshot = await this.registry.readSnapshot();
708
+ const binding = Object.hasOwn(snapshot.routes, routeId)
709
+ ? snapshot.routes[routeId]
710
+ : undefined;
711
+ const session = selector
712
+ ? await this.resolveSessionSelector(selector)
713
+ : binding && Object.hasOwn(snapshot.sessions, binding.sessionId)
714
+ ? snapshot.sessions[binding.sessionId]
715
+ : undefined;
716
+ if (!session) {
717
+ return "当前 route 没有活跃 session; 可使用 /sessions 查看列表。";
718
+ }
719
+ await this.workerManager.stop(session.sessionId);
720
+ if (binding?.sessionId === session.sessionId) {
721
+ await this.registry.setRoute(routeId, null);
722
+ }
723
+ const stoppedSession = (await this.registry.readSnapshot()).sessions[session.sessionId];
724
+ return stoppedSession?.state === "pending"
725
+ ? `会话 #${session.publicIndex ?? "?"} 已停止, 但尚无 transcript 文件, 因此不能恢复。`
726
+ : `会话 #${session.publicIndex ?? "?"} 已停止并保存。`;
727
+ }
728
+
729
+ /**
730
+ * 将普通文本投递到 route 当前绑定的 background 或 UI Pi worker。
731
+ *
732
+ * @param routeId 微信 route ID。
733
+ * @param text prompt 正文。
734
+ * @returns Pi assistant 回复。
735
+ */
736
+ private async handlePrompt(routeId: string, text: string): Promise<string> {
737
+ const snapshot = await this.registry.readSnapshot();
738
+ const binding = Object.hasOwn(snapshot.routes, routeId)
739
+ ? snapshot.routes[routeId]
740
+ : undefined;
741
+ if (!binding) {
742
+ return "当前没有活动会话。请先使用 /new --project <alias> 创建后台会话, 再用 /resume <索引> 切换。";
743
+ }
744
+ const session = Object.hasOwn(snapshot.sessions, binding.sessionId)
745
+ ? snapshot.sessions[binding.sessionId]
746
+ : undefined;
747
+ if (!session) {
748
+ return "当前 route 指向的 session 不在 registry 中, 已停止投递以避免错路由。";
749
+ }
750
+ const worker = Object.hasOwn(snapshot.instances, binding.workerInstanceId)
751
+ ? snapshot.instances[binding.workerInstanceId]
752
+ : undefined;
753
+ if (!worker || worker.state === "stale" || worker.state === "stopping") {
754
+ return "当前 route 没有可用的 Pi worker; 请使用 /resume <索引> 重连。";
755
+ }
756
+ return this.workerManager.prompt(binding.sessionId, text);
757
+ }
758
+
759
+ /**
760
+ * 格式化当前 Gateway、route、worker 和队列状态。
761
+ *
762
+ * @param routeId 微信 route ID。
763
+ * @param config 当前配置快照。
764
+ * @returns 不包含凭证和完整路径的状态文本。
765
+ */
766
+ private async formatStatus(routeId: string, config: ManagerConfiguration): Promise<string> {
767
+ const snapshot = await this.registry.readSnapshot();
768
+ const binding = Object.hasOwn(snapshot.routes, routeId)
769
+ ? snapshot.routes[routeId]
770
+ : undefined;
771
+ const session = binding && Object.hasOwn(snapshot.sessions, binding.sessionId)
772
+ ? snapshot.sessions[binding.sessionId]
773
+ : undefined;
774
+ const instance = binding && Object.hasOwn(snapshot.instances, binding.workerInstanceId)
775
+ ? snapshot.instances[binding.workerInstanceId]
776
+ : undefined;
777
+ const queueItems = await this.queue.list(routeId);
778
+ const pendingQueueCount = queueItems.filter((item) =>
779
+ item.state === "queued" || item.state === "failed" || item.state === "interrupted",
780
+ ).length;
781
+ const projectCount = Object.keys(config.projects).length;
782
+ const projectName = session
783
+ ? Object.hasOwn(config.projects, session.projectAlias)
784
+ ? config.projects[session.projectAlias].displayName
785
+ : session.projectAlias
786
+ : undefined;
787
+ const sessionTitle = session
788
+ ? `#${session.publicIndex ?? "?"} ${await resolveSessionTitle(session)}`
789
+ : "未绑定";
790
+ const workerLabel = instance
791
+ ? `${instance.mode === "ui" ? "前台" : "后台"} · ${formatWorkerState(instance.state)}`
792
+ : "未运行";
793
+ const uiModeLine = this.uiModeCapability
794
+ ? [`可见 UI 模式:${await this.formatUiModeCapability()}`]
795
+ : [];
796
+ return [
797
+ `Hub 状态:${formatGatewayState(snapshot.gateway?.state)}`,
798
+ `当前微信会话:${sessionTitle}`,
799
+ ...(projectName ? [`项目:${projectName}`] : []),
800
+ `Pi:${workerLabel}`,
801
+ ...uiModeLine,
802
+ `未完成消息:${pendingQueueCount} 条`,
803
+ `已登记项目:${projectCount} 个`,
804
+ ].join("\n");
805
+ }
806
+
807
+ /**
808
+ * 格式化当前环境是否可创建或恢复可见 UI 会话。
809
+ *
810
+ * @returns 面向微信用户的中文能力说明。
811
+ */
812
+ private async formatUiModeCapability(): Promise<string> {
813
+ try {
814
+ const capability = await this.uiModeCapability!();
815
+ return capability.supported ? "可用" : `不可用(${capability.reason})`;
816
+ } catch {
817
+ return "不可用(无法确认 Windows Terminal 可用性)";
818
+ }
819
+ }
820
+
821
+ /**
822
+ * 按稳定数字索引或名称查找唯一 session。
823
+ *
824
+ * @param selector 用户输入选择器。
825
+ * @returns 唯一匹配 session。
826
+ */
827
+ private async resolveSessionSelector(selector: string): Promise<SessionIndexRecord> {
828
+ const snapshot = await this.registry.readSnapshot();
829
+ const normalized = selector.toLowerCase();
830
+ if (/^[1-9]\d*$/.test(normalized)) {
831
+ const publicIndex = Number(normalized);
832
+ const indexedSession = Object.values(snapshot.sessions).find((session) =>
833
+ session.publicIndex === publicIndex,
834
+ );
835
+ if (indexedSession) {
836
+ return indexedSession;
837
+ }
838
+ }
839
+ const matches = Object.values(snapshot.sessions).filter((session) =>
840
+ session.name?.toLowerCase() === normalized,
841
+ );
842
+ if (matches.length === 0) {
843
+ throw new BackgroundWorkerManagerError("session_not_found", `未找到会话索引或名称: ${selector}。`);
844
+ }
845
+ if (matches.length > 1) {
846
+ throw new GatewayCommandParseError(`会话名称匹配到多个结果: ${selector}; 请使用数字索引。`);
847
+ }
848
+ return matches[0];
849
+ }
850
+
851
+ /**
852
+ * 对授权用户的 queue 文本执行路由命令。
853
+ *
854
+ * @param routeId 微信 route ID。
855
+ * @param item durable queue 项。
856
+ * @param config 当前配置快照。
857
+ * @returns 命令或 agent 回复。
858
+ */
859
+ private async processQueueItem(
860
+ routeId: string,
861
+ item: DurableQueueItem,
862
+ config: ManagerConfiguration,
863
+ ): Promise<string> {
864
+ let command;
865
+ try {
866
+ command = parseGatewayCommand(item.text);
867
+ } catch (error) {
868
+ if (error instanceof GatewayCommandParseError) {
869
+ return error.message;
870
+ }
871
+ throw error;
872
+ }
873
+ return this.processCommand(routeId, command, config);
874
+ }
875
+
876
+ /**
877
+ * 执行已解析的 Gateway command 或投递普通 prompt。
878
+ *
879
+ * @param routeId 微信 route ID。
880
+ * @param command 已规范化命令。
881
+ * @param config 当前配置快照。
882
+ * @returns 回复文本。
883
+ */
884
+ private async processCommand(
885
+ routeId: string,
886
+ command: ReturnType<typeof parseGatewayCommand>,
887
+ config: ManagerConfiguration,
888
+ ): Promise<string> {
889
+ try {
890
+ switch (command.kind) {
891
+ case "help":
892
+ return GATEWAY_HELP_TEXT;
893
+ case "status":
894
+ return await this.formatStatus(routeId, config);
895
+ case "projects":
896
+ return await this.handleProjects(command.arguments);
897
+ case "new":
898
+ return await this.handleNew(routeId, command.mode, command.projectAlias, command.name, config);
899
+ case "sessions":
900
+ return await this.formatSessions(routeId, command.projectAlias, command.state, command.page, config);
901
+ case "resume":
902
+ return await this.handleResume(routeId, command.selector);
903
+ case "last":
904
+ return await this.handleLast(routeId, command.selector, config);
905
+ case "stop":
906
+ return await this.handleStop(routeId, command.selector);
907
+ case "retry":
908
+ return "`/retry` 需要由 queue 控制面直接处理, 不能作为普通 FIFO 消息执行。";
909
+ case "prompt":
910
+ return await this.handlePrompt(routeId, command.text);
911
+ }
912
+ } catch (error) {
913
+ if (
914
+ error instanceof ProjectServiceError ||
915
+ error instanceof BackgroundWorkerManagerError ||
916
+ error instanceof UiWorkerManagerError ||
917
+ error instanceof DurableQueueError
918
+ ) {
919
+ return error.message;
920
+ }
921
+ throw error;
922
+ }
923
+ }
924
+
925
+ /**
926
+ * 仅允许配置中的个人微信用户进入消息队列。
927
+ *
928
+ * @param senderId 消息发送者 ID。
929
+ * @param config 当前配置。
930
+ * @returns 无返回值。
931
+ * @throws {GatewayAuthorizationError} allowlist 未配置或 sender 不匹配时抛出。
932
+ */
933
+ private assertAuthorized(senderId: string, config: ManagerConfiguration): void {
934
+ const authorizedUserId = config.wechat.authorizedUserId;
935
+ if (!authorizedUserId.trim()) {
936
+ throw new GatewayAuthorizationError(
937
+ "wechat_auth_unavailable",
938
+ "微信 allowlist 尚未配置, 消息未写入队列。",
939
+ );
940
+ }
941
+ if (senderId !== authorizedUserId) {
942
+ throw new GatewayAuthorizationError(
943
+ "unauthorized_wechat_user",
944
+ "消息来源未授权, 已在队列和路由前拒绝。",
945
+ );
946
+ }
947
+ }
948
+ }
949
+
950
+ const SESSION_TITLE_LIMIT = 32;
951
+ const RESUME_ASSISTANT_TEXT_LIMIT = 800;
952
+ const LAST_TURN_TEXT_LIMIT = 600;
953
+ const TAIL_READ_BYTES = 256 * 1024;
954
+ const TAIL_READ_MAX_BYTES = 8 * 1024 * 1024;
955
+
956
+ /**
957
+ * 生成保留当前筛选条件的会话翻页命令.
958
+ *
959
+ * @param page 目标页码.
960
+ * @param projectAlias 可选项目 alias.
961
+ * @param state 当前会话状态筛选.
962
+ * @returns 可直接发送到微信的下一页或上一页命令.
963
+ */
964
+ function buildSessionsPageCommand(
965
+ page: number,
966
+ projectAlias: string | undefined,
967
+ state: "default" | "active" | "saved" | "pending" | "all",
968
+ ): string {
969
+ const arguments_: string[] = [];
970
+ if (projectAlias) {
971
+ arguments_.push(`--project ${projectAlias}`);
972
+ }
973
+ if (state !== "default") {
974
+ arguments_.push(`--state ${state}`);
975
+ }
976
+ arguments_.push(`--page ${page}`);
977
+ return `/sessions ${arguments_.join(" ")}`;
978
+ }
979
+
980
+ /**
981
+ * 将 Gateway 生命周期状态转换为面向微信用户的中文说明.
982
+ *
983
+ * @param state Gateway 当前状态.
984
+ * @returns 简短的中文状态说明.
985
+ */
986
+ function formatGatewayState(state: string | undefined): string {
987
+ switch (state) {
988
+ case undefined:
989
+ return "未启动";
990
+ case "starting":
991
+ return "启动中";
992
+ case "online":
993
+ return "在线";
994
+ case "auth_required":
995
+ return "需要重新登录";
996
+ case "stopping":
997
+ return "停止中";
998
+ case "stopped":
999
+ return "已停止";
1000
+ case "lease_lost":
1001
+ return "连接异常";
1002
+ default:
1003
+ return "状态未知";
1004
+ }
1005
+ }
1006
+
1007
+ /**
1008
+ * 将 Pi worker 生命周期状态转换为面向微信用户的中文说明.
1009
+ *
1010
+ * @param state worker 当前状态.
1011
+ * @returns 简短的中文状态说明.
1012
+ */
1013
+ function formatWorkerState(state: string): string {
1014
+ switch (state) {
1015
+ case "starting":
1016
+ return "启动中";
1017
+ case "idle":
1018
+ return "空闲";
1019
+ case "running":
1020
+ return "运行中";
1021
+ case "stopping":
1022
+ return "停止中";
1023
+ case "stale":
1024
+ return "断连待恢复";
1025
+ default:
1026
+ return "状态未知";
1027
+ }
1028
+ }
1029
+
1030
+ /**
1031
+ * 解析 session 显示标题: 优先使用名称, 否则使用 Pi resume 列表采用的首条用户文本。
1032
+ *
1033
+ * @param session Hub session 索引。
1034
+ * @returns 已清理并截断的会话标题。
1035
+ */
1036
+ async function resolveSessionTitle(session: SessionIndexRecord): Promise<string> {
1037
+ const name = session.name ? normalizeSessionTitle(session.name) : "";
1038
+ const firstMessage = name ? undefined : await readFirstUserMessage(session.sessionFile);
1039
+ return truncateSessionTitle(name || firstMessage || "(尚无用户消息)");
1040
+ }
1041
+
1042
+ /**
1043
+ * 从 Pi JSONL session 文件中读取首条非空 user 文本。
1044
+ *
1045
+ * @param sessionFile Pi session 文件路径。
1046
+ * @returns 首条用户文本, 不存在或无法读取时返回 undefined。
1047
+ */
1048
+ async function readFirstUserMessage(sessionFile: string): Promise<string | undefined> {
1049
+ let input: ReturnType<typeof createReadStream> | undefined;
1050
+ let lines: ReturnType<typeof createInterface> | undefined;
1051
+ try {
1052
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1053
+ lines = createInterface({ input, crlfDelay: Infinity });
1054
+ for await (const line of lines) {
1055
+ let entry: unknown;
1056
+ try {
1057
+ entry = JSON.parse(line) as unknown;
1058
+ } catch {
1059
+ continue;
1060
+ }
1061
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1062
+ continue;
1063
+ }
1064
+ const message = entry.message;
1065
+ if (message.role !== "user") {
1066
+ continue;
1067
+ }
1068
+ const content = message.content;
1069
+ const text = typeof content === "string"
1070
+ ? content
1071
+ : Array.isArray(content)
1072
+ ? content
1073
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1074
+ .map((block) => (block as { text: string }).text)
1075
+ .join(" ")
1076
+ : "";
1077
+ const normalized = normalizeSessionTitle(text);
1078
+ if (normalized) {
1079
+ return normalized;
1080
+ }
1081
+ }
1082
+ } catch {
1083
+ return undefined;
1084
+ } finally {
1085
+ lines?.close();
1086
+ input?.destroy();
1087
+ }
1088
+ return undefined;
1089
+ }
1090
+
1091
+ /**
1092
+ * 从 Pi JSONL session 文件读取最近一条 assistant 对外文本.
1093
+ *
1094
+ * @param sessionFile Pi transcript 文件路径.
1095
+ * @returns 最近一条非空 assistant 文本, 无法读取或不存在时返回 undefined.
1096
+ */
1097
+ async function readLatestAssistantText(sessionFile: string): Promise<string | undefined> {
1098
+ let input: ReturnType<typeof createReadStream> | undefined;
1099
+ let lines: ReturnType<typeof createInterface> | undefined;
1100
+ let latestText: string | undefined;
1101
+ try {
1102
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1103
+ lines = createInterface({ input, crlfDelay: Infinity });
1104
+ for await (const line of lines) {
1105
+ let entry: unknown;
1106
+ try {
1107
+ entry = JSON.parse(line) as unknown;
1108
+ } catch {
1109
+ continue;
1110
+ }
1111
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1112
+ continue;
1113
+ }
1114
+ const message = entry.message;
1115
+ if (message.role !== "assistant") {
1116
+ continue;
1117
+ }
1118
+ const content = message.content;
1119
+ const text = typeof content === "string"
1120
+ ? content
1121
+ : Array.isArray(content)
1122
+ ? content
1123
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1124
+ .map((block) => (block as { type: "text"; text: string }).text)
1125
+ .join("")
1126
+ : "";
1127
+ const normalized = normalizeAssistantText(text);
1128
+ if (normalized) {
1129
+ latestText = normalized;
1130
+ }
1131
+ }
1132
+ } catch {
1133
+ return undefined;
1134
+ } finally {
1135
+ lines?.close();
1136
+ input?.destroy();
1137
+ }
1138
+ return latestText;
1139
+ }
1140
+
1141
+ /**
1142
+ * 将 ISO 时间转换为本地时区的分钟精度文本。
1143
+ *
1144
+ * @param isoTimestamp registry 中记录的 ISO 时间。
1145
+ * @returns 形如 `2026-08-05 14:32` 的本地时间, 无法解析时返回原始文本。
1146
+ */
1147
+ function formatLocalMinute(isoTimestamp: string): string {
1148
+ const parsed = new Date(isoTimestamp);
1149
+ if (Number.isNaN(parsed.getTime())) {
1150
+ return isoTimestamp;
1151
+ }
1152
+ const pad = (value: number): string => String(value).padStart(2, "0");
1153
+ return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
1154
+ }
1155
+
1156
+ /**
1157
+ * 将发往微信的最近一轮文本限制在固定长度内, 按 Unicode code point 截断。
1158
+ *
1159
+ * @param text 原始消息文本。
1160
+ * @returns 可安全发送的完整或截断文本。
1161
+ */
1162
+ function truncateTurnText(text: string): { text: string; truncated: boolean } {
1163
+ const characters = Array.from(text);
1164
+ if (characters.length <= LAST_TURN_TEXT_LIMIT) {
1165
+ return { text, truncated: false };
1166
+ }
1167
+ return {
1168
+ text: characters.slice(0, LAST_TURN_TEXT_LIMIT).join(""),
1169
+ truncated: true,
1170
+ };
1171
+ }
1172
+
1173
+ /**
1174
+ * 从 Pi transcript 尾部按需扩展窗口, 读取最近一轮 user 与 assistant 文本。
1175
+ *
1176
+ * 先读文件末尾固定字节区间, 按 LF 切分后从后向前定位最新的 user 与 assistant
1177
+ * 消息; 尾部首行可能是被截断的半行, 因此总是丢弃。如果窗口内找不到完整一轮
1178
+ * (常见于单条消息本身就超过初始窗口), 按倍数扩大窗口重试; 超过上限仍未命中时
1179
+ * 回退为流式全文件扫描, 保证结果正确。
1180
+ *
1181
+ * @param sessionFile Pi transcript 文件路径。
1182
+ * @returns 最近一轮 user 与 assistant 文本, 无可用记录时返回 undefined。
1183
+ */
1184
+ async function readLatestTurn(sessionFile: string): Promise<LatestTurn | undefined> {
1185
+ const handle = await open(sessionFile, "r").catch(() => undefined);
1186
+ if (!handle) {
1187
+ return undefined;
1188
+ }
1189
+ try {
1190
+ const { size } = await handle.stat();
1191
+ if (size === 0) {
1192
+ return undefined;
1193
+ }
1194
+ let windowBytes = Math.min(size, TAIL_READ_BYTES);
1195
+ for (;;) {
1196
+ const start = size - windowBytes;
1197
+ const chunk = Buffer.alloc(windowBytes);
1198
+ await handle.read(chunk, 0, windowBytes, start);
1199
+ const text = chunk.toString("utf8");
1200
+ let buffer = text;
1201
+ if (start > 0) {
1202
+ const firstNewline = text.indexOf("\n");
1203
+ buffer = firstNewline < 0 ? "" : text.slice(firstNewline + 1);
1204
+ }
1205
+ const turn = scanTurnLines(buffer);
1206
+ if (turn.assistantText !== undefined && turn.userText !== undefined) {
1207
+ return turn;
1208
+ }
1209
+ if (start === 0) {
1210
+ return turn.assistantText === undefined && turn.userText === undefined ? undefined : turn;
1211
+ }
1212
+ if (windowBytes >= TAIL_READ_MAX_BYTES) {
1213
+ const fallback = await fullScanLatestTurn(sessionFile);
1214
+ return fallback.assistantText === undefined && fallback.userText === undefined
1215
+ ? undefined
1216
+ : fallback;
1217
+ }
1218
+ windowBytes = Math.min(size, windowBytes * 2);
1219
+ }
1220
+ } finally {
1221
+ await handle.close();
1222
+ }
1223
+ }
1224
+
1225
+ /**
1226
+ * 在一段 transcript 文本中从后向前定位最新的 user 与 assistant 文本。
1227
+ *
1228
+ * @param buffer 已剔除尾部半行的 transcript 文本片段。
1229
+ * @returns 已找到的 user 与 assistant 文本, 任意字段都可能缺失。
1230
+ */
1231
+ function scanTurnLines(buffer: string): LatestTurn {
1232
+ const lines = buffer.split("\n");
1233
+ let assistantText: string | undefined;
1234
+ let userText: string | undefined;
1235
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1236
+ const line = lines[index];
1237
+ if (!line.trim()) {
1238
+ continue;
1239
+ }
1240
+ let entry: unknown;
1241
+ try {
1242
+ entry = JSON.parse(line) as unknown;
1243
+ } catch {
1244
+ continue;
1245
+ }
1246
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1247
+ continue;
1248
+ }
1249
+ const role = entry.message.role;
1250
+ if (role !== "user" && role !== "assistant") {
1251
+ continue;
1252
+ }
1253
+ const text = extractMessageText(entry.message.content);
1254
+ if (!text) {
1255
+ continue;
1256
+ }
1257
+ if (role === "assistant") {
1258
+ assistantText ??= text;
1259
+ } else if (userText === undefined) {
1260
+ userText = text;
1261
+ }
1262
+ if (assistantText !== undefined && userText !== undefined) {
1263
+ break;
1264
+ }
1265
+ }
1266
+ return { userText, assistantText };
1267
+ }
1268
+
1269
+ /**
1270
+ * 流式扫描整个 transcript, 作为超大单条记录窗口读取失败后的兼容路径。
1271
+ *
1272
+ * @param sessionFile Pi transcript 文件路径。
1273
+ * @returns 整个文件中最后一组 user 与 assistant 文本。
1274
+ */
1275
+ async function fullScanLatestTurn(sessionFile: string): Promise<LatestTurn> {
1276
+ let input: ReturnType<typeof createReadStream> | undefined;
1277
+ let lines: ReturnType<typeof createInterface> | undefined;
1278
+ let assistantText: string | undefined;
1279
+ let userText: string | undefined;
1280
+ try {
1281
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1282
+ lines = createInterface({ input, crlfDelay: Infinity });
1283
+ for await (const line of lines) {
1284
+ let entry: unknown;
1285
+ try {
1286
+ entry = JSON.parse(line) as unknown;
1287
+ } catch {
1288
+ continue;
1289
+ }
1290
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1291
+ continue;
1292
+ }
1293
+ const role = entry.message.role;
1294
+ if (role !== "user" && role !== "assistant") {
1295
+ continue;
1296
+ }
1297
+ const text = extractMessageText(entry.message.content);
1298
+ if (!text) {
1299
+ continue;
1300
+ }
1301
+ if (role === "assistant") {
1302
+ assistantText = text;
1303
+ } else {
1304
+ userText = text;
1305
+ }
1306
+ }
1307
+ } catch {
1308
+ return { userText, assistantText };
1309
+ } finally {
1310
+ lines?.close();
1311
+ input?.destroy();
1312
+ }
1313
+ return { userText, assistantText };
1314
+ }
1315
+
1316
+ /**
1317
+ * 从 Pi message content 中提取纯文本片段, 忽略 thinking 等非对外内容。
1318
+ *
1319
+ * @param content message.content 原始值。
1320
+ * @returns 已清理的文本, 无文本时返回 undefined。
1321
+ */
1322
+ function extractMessageText(content: unknown): string | undefined {
1323
+ const raw = typeof content === "string"
1324
+ ? content
1325
+ : Array.isArray(content)
1326
+ ? content
1327
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1328
+ .map((block) => (block as { text: string }).text)
1329
+ .join("\n")
1330
+ : "";
1331
+ const normalized = normalizeAssistantText(raw);
1332
+ return normalized || undefined;
1333
+ }
1334
+
1335
+ /**
1336
+ * 表示从 transcript 尾部提取出的最近一轮对话。
1337
+ */
1338
+ interface LatestTurn {
1339
+ userText?: string;
1340
+ assistantText?: string;
1341
+ }
1342
+
1343
+ /**
1344
+ * 清理 assistant 文本中的终端控制字符, 保留换行和制表符格式.
1345
+ *
1346
+ * @param text transcript 中的 assistant 文本.
1347
+ * @returns 清理并去除首尾空白后的文本.
1348
+ */
1349
+ function normalizeAssistantText(text: string): string {
1350
+ return text
1351
+ .replace(/\r\n?/g, "\n")
1352
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
1353
+ .trim();
1354
+ }
1355
+
1356
+ /**
1357
+ * 限制发往微信的恢复预览长度, 超长时保留开头内容.
1358
+ *
1359
+ * @param text 最近一次 assistant 文本.
1360
+ * @returns 可安全发送的完整或截断文本.
1361
+ */
1362
+ function truncateResumeAssistantText(text: string): { text: string; truncated: boolean } {
1363
+ const characters = Array.from(text);
1364
+ if (characters.length <= RESUME_ASSISTANT_TEXT_LIMIT) {
1365
+ return { text, truncated: false };
1366
+ }
1367
+ return {
1368
+ text: characters.slice(0, RESUME_ASSISTANT_TEXT_LIMIT).join(""),
1369
+ truncated: true,
1370
+ };
1371
+ }
1372
+
1373
+ /**
1374
+ * 清理标题中的控制字符并折叠空白, 保证每个会话只占一行。
1375
+ *
1376
+ * @param title 原始标题或用户文本。
1377
+ * @returns 去除控制字符并折叠空白后的文本。
1378
+ */
1379
+ function normalizeSessionTitle(title: string): string {
1380
+ return title.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
1381
+ }
1382
+
1383
+ /**
1384
+ * 将会话标题限制为 32 个 Unicode code point, 超出部分以三个点省略。
1385
+ *
1386
+ * @param title 已清理标题。
1387
+ * @returns 长度限制内的标题。
1388
+ */
1389
+ function truncateSessionTitle(title: string): string {
1390
+ const characters = Array.from(title);
1391
+ if (characters.length <= SESSION_TITLE_LIMIT) {
1392
+ return title;
1393
+ }
1394
+ return `${characters.slice(0, SESSION_TITLE_LIMIT - 3).join("")}...`;
1395
+ }
1396
+
1397
+ /**
1398
+ * 判断未知值是否为非数组对象。
1399
+ *
1400
+ * @param value 待检查的值。
1401
+ * @returns 值可安全读取字段时返回 true。
1402
+ */
1403
+ function isRecord(value: unknown): value is Record<string, unknown> {
1404
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1405
+ }
1406
+
1407
+ const GATEWAY_HELP_TEXT = [
1408
+ "微信命令帮助",
1409
+ "",
1410
+ "会话命令",
1411
+ "/new [--mode background|ui]",
1412
+ " [--project <别名>] [--name <名称>]",
1413
+ "/sessions [筛选条件]",
1414
+ " --project <别名> --state <状态> --page <页码>",
1415
+ " 状态:default / active / saved / pending / all",
1416
+ "/resume <索引或名称>",
1417
+ "/last [索引或名称]",
1418
+ " 只读查看最近一轮对话",
1419
+ "/stop [索引或名称]",
1420
+ "",
1421
+ "项目命令",
1422
+ "/projects",
1423
+ "/projects add <别名>",
1424
+ " --name <名称> --path <绝对路径>",
1425
+ "/projects remove <别名>",
1426
+ "/projects default <别名>",
1427
+ "",
1428
+ "Hub 状态与队列",
1429
+ "/status",
1430
+ "/retry <message-id> --confirm",
1431
+ " 会重新执行原消息, 可能产生副作用。",
1432
+ "",
1433
+ "发送 /help 查看此帮助。",
1434
+ ].join("\n");
1435
+
1436
+ /**
1437
+ * 将 durable queue dispatch 结果规范化为 Gateway receive 结果。
1438
+ *
1439
+ * @param result queue dispatch 结果。
1440
+ * @returns Gateway 层结果。
1441
+ */
1442
+ function toReceiveResult(result: QueueDispatchResult): GatewayReceiveResult {
1443
+ return {
1444
+ messageId: result.item.messageId,
1445
+ state: result.item.state,
1446
+ duplicate: result.duplicate,
1447
+ ...(result.reply === undefined ? {} : { reply: result.reply }),
1448
+ };
1449
+ }