pi-wechat-session-hub 0.1.0 → 0.1.2

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.
@@ -1,1449 +1,1790 @@
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
- }
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, WorkerInstanceRecord } 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
+ import {
24
+ evaluateHealth,
25
+ formatHealthState,
26
+ readLatestFailure,
27
+ classifyFailure,
28
+ type SessionHealth,
29
+ type TurnFailure,
30
+ } from "./turn-health.ts";
31
+
32
+ export type InboundGatewayMessage = GatewayInboundMessage;
33
+
34
+ export interface GatewayReceiveResult {
35
+ messageId: string;
36
+ state: string;
37
+ duplicate: boolean;
38
+ reply?: string;
39
+ }
40
+
41
+ export type GatewayReplySink = (
42
+ routeId: string,
43
+ messageId: string,
44
+ reply: string,
45
+ replyContext?: IlinkReplyContext,
46
+ ) => Promise<void>;
47
+
48
+ /**
49
+ * 管理消息进入 worker 到最终回复之间的可见处理状态。
50
+ */
51
+ export interface GatewayProcessingIndicator {
52
+ /**
53
+ * 开始该 queue 消息的用户可见处理状态。
54
+ *
55
+ * @param messageId durable queue 消息 ID。
56
+ * @param replyContext 对应入站消息的回复上下文。
57
+ * @returns 无返回值。
58
+ */
59
+ start(messageId: string, replyContext?: IlinkReplyContext): void;
60
+
61
+ /**
62
+ * 结束该 queue 消息的用户可见处理状态。
63
+ *
64
+ * @param messageId durable queue 消息 ID。
65
+ * @returns 无返回值。
66
+ */
67
+ stop(messageId: string): void;
68
+ }
69
+
70
+ /**
71
+ * 表示消息发送者未通过个人微信 allowlist。
72
+ */
73
+ export class GatewayAuthorizationError extends Error {
74
+ /**
75
+ * 创建微信授权错误。
76
+ *
77
+ * @param code 稳定错误代码。
78
+ * @param message 不暴露本地配置的中文错误说明。
79
+ */
80
+ constructor(
81
+ readonly code: "wechat_auth_unavailable" | "unauthorized_wechat_user",
82
+ message: string,
83
+ ) {
84
+ super(message);
85
+ this.name = "GatewayAuthorizationError";
86
+ }
87
+ }
88
+
89
+ /**
90
+ * 将授权消息路由到管理命令或当前 Pi session, 并经 durable queue 按 route FIFO 处理。
91
+ */
92
+ export class GatewayCommandRouter {
93
+ private readonly configStore: ConfigurationStore;
94
+ private readonly projectService: ProjectService;
95
+ private readonly workerManager: GatewayWorkerService;
96
+ private readonly registry: ManagerRegistry;
97
+ private readonly queue: DurableMessageQueue;
98
+ private readonly lease: GatewayLease;
99
+ private readonly replySink?: GatewayReplySink;
100
+ private readonly processingIndicator?: GatewayProcessingIndicator;
101
+ private readonly uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
102
+
103
+ /**
104
+ * 创建 Gateway 命令路由器。
105
+ *
106
+ * @param options 路由依赖和可选回复发送器。
107
+ */
108
+ constructor(options: {
109
+ configStore: ConfigurationStore;
110
+ projectService: ProjectService;
111
+ workerManager: GatewayWorkerService;
112
+ registry: ManagerRegistry;
113
+ queue: DurableMessageQueue;
114
+ lease: GatewayLease;
115
+ replySink?: GatewayReplySink;
116
+ processingIndicator?: GatewayProcessingIndicator;
117
+ uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
118
+ }) {
119
+ this.configStore = options.configStore;
120
+ this.projectService = options.projectService;
121
+ this.workerManager = options.workerManager;
122
+ this.registry = options.registry;
123
+ this.queue = options.queue;
124
+ this.lease = options.lease;
125
+ this.replySink = options.replySink;
126
+ this.processingIndicator = options.processingIndicator;
127
+ this.uiModeCapability = options.uiModeCapability;
128
+ this.queue.setSkippedNotifier((routeId, item) =>
129
+ this.notifySkippedItem(routeId, item),
130
+ );
131
+ }
132
+
133
+ /**
134
+ * 向上游告知某条消息已被自动跳过, 避免用户以为消息没发出去。
135
+ *
136
+ * 提示使用该消息自己的 replyContext 投递; 若该项本来就没有上下文,
137
+ * 或投递失败, 只放弃提示, 不影响队列继续处理后续消息。
138
+ *
139
+ * @param routeId route 稳定 ID。
140
+ * @param item 被跳过的 queue 项。
141
+ * @returns 无返回值。
142
+ */
143
+ private async notifySkippedItem(routeId: string, item: DurableQueueItem): Promise<void> {
144
+ if (!this.replySink) {
145
+ return;
146
+ }
147
+ const notice = [
148
+ "⚠️ **有一条消息没有处理成功, 已自动跳过**",
149
+ [
150
+ "| 项 | 值 |",
151
+ "| --- | --- |",
152
+ `| 消息 ID | ${item.messageId} |`,
153
+ `| 原文 | ${truncatePreview(item.text)} |`,
154
+ ...(item.errorCode ? [`| 原因 | ${item.errorCode} |`] : []),
155
+ ].join("\n"),
156
+ "后续消息不受影响。",
157
+ `重新执行:\`/retry ${item.messageId} --confirm\` (可能重复产生副作用)`,
158
+ ].join("\n\n");
159
+ await this.replySink(routeId, `${item.messageId}:skipped`, notice, item.replyContext);
160
+ }
161
+
162
+ /**
163
+ * 验证 sender allowlist, 持久化去重消息并等待 FIFO 处理结果。
164
+ *
165
+ * @param message 正规化后的微信消息。
166
+ * @returns 去重、处理状态及可选回复。
167
+ * @throws {GatewayAuthorizationError} 未配置 allowlist 或 sender 不匹配时抛出。
168
+ */
169
+ async receive(message: InboundGatewayMessage): Promise<GatewayReceiveResult> {
170
+ await this.lease.assertOwned();
171
+ const { config } = await this.configStore.load();
172
+ this.assertAuthorized(message.senderId, config);
173
+ if (!message.messageId.trim() || !message.text.trim()) {
174
+ throw new GatewayCommandParseError("微信消息缺少 messageId 或正文, 已拒绝路由。");
175
+ }
176
+
177
+ let command;
178
+ try {
179
+ command = parseGatewayCommand(message.text);
180
+ } catch (error) {
181
+ if (!(error instanceof GatewayCommandParseError)) {
182
+ throw error;
183
+ }
184
+ if (this.replySink) {
185
+ await this.replySink(message.senderId, message.messageId, error.message, message.replyContext);
186
+ }
187
+ return {
188
+ messageId: message.messageId,
189
+ state: "rejected",
190
+ duplicate: false,
191
+ ...(this.replySink ? {} : { reply: error.message }),
192
+ };
193
+ }
194
+ const routeId = message.senderId;
195
+ if (command.kind === "retry") {
196
+ return this.retryMessage(
197
+ routeId,
198
+ command.messageId,
199
+ message.messageId,
200
+ command.confirmed,
201
+ config,
202
+ message.replyContext,
203
+ );
204
+ }
205
+
206
+ const result = await this.queue.dispatch(
207
+ routeId,
208
+ message.messageId,
209
+ message.text,
210
+ config.runtime.maxQueuePerSession,
211
+ this.createProcessor(routeId, config),
212
+ message.replyContext,
213
+ );
214
+ const normalized = toReceiveResult(result);
215
+ if (this.replySink) {
216
+ delete normalized.reply;
217
+ }
218
+ return normalized;
219
+ }
220
+
221
+ /**
222
+ * 快速接收入站消息: 先完成授权与 durable enqueue, 再异步触发 route drain。
223
+ *
224
+ * Channel poller 应在收到此方法成功返回后提交 get_updates_buf, 不必等待 Pi 模型完成。
225
+ *
226
+ * @param message 正规化后的微信消息。
227
+ * @returns 入队结果, 不包含模型回复。
228
+ * @throws {GatewayAuthorizationError} sender 未授权时抛出。
229
+ */
230
+ async acceptInbound(message: InboundGatewayMessage): Promise<GatewayReceiveResult> {
231
+ await this.lease.assertOwned();
232
+ const { config } = await this.configStore.load();
233
+ this.assertAuthorized(message.senderId, config);
234
+ if (!message.messageId.trim() || !message.text.trim()) {
235
+ throw new GatewayCommandParseError("微信消息缺少 messageId 或正文, 已拒绝路由。");
236
+ }
237
+ if (!this.replySink) {
238
+ throw new Error("异步 Gateway 入站处理必须配置 replySink。");
239
+ }
240
+
241
+ let command;
242
+ try {
243
+ command = parseGatewayCommand(message.text);
244
+ } catch (error) {
245
+ if (!(error instanceof GatewayCommandParseError)) {
246
+ throw error;
247
+ }
248
+ await this.replySink(message.senderId, message.messageId, error.message, message.replyContext);
249
+ return {
250
+ messageId: message.messageId,
251
+ state: "rejected",
252
+ duplicate: false,
253
+ };
254
+ }
255
+ const routeId = message.senderId;
256
+ if (command.kind === "retry") {
257
+ return this.retryMessage(
258
+ routeId,
259
+ command.messageId,
260
+ message.messageId,
261
+ command.confirmed,
262
+ config,
263
+ message.replyContext,
264
+ );
265
+ }
266
+
267
+ const enqueued = await this.queue.enqueue(
268
+ routeId,
269
+ message.messageId,
270
+ message.text,
271
+ config.runtime.maxQueuePerSession,
272
+ message.replyContext,
273
+ );
274
+ this.queue.drainPending(routeId, this.createProcessor(routeId, config));
275
+ return {
276
+ messageId: message.messageId,
277
+ state: enqueued.item.state,
278
+ duplicate: enqueued.duplicate,
279
+ };
280
+ }
281
+
282
+ /**
283
+ * 在 Gateway 启动时恢复指定 route 的 queued 消息。
284
+ *
285
+ * @param routeId route 稳定 ID。
286
+ * @returns 无返回值。
287
+ */
288
+ async drainPending(routeId: string): Promise<void> {
289
+ if (!this.replySink) {
290
+ throw new Error("Gateway 启动恢复队列需要配置 replySink。");
291
+ }
292
+ await this.lease.assertOwned();
293
+ const { config } = await this.configStore.load();
294
+ this.queue.drainPending(routeId, this.createProcessor(routeId, config));
295
+ }
296
+
297
+ /**
298
+ * 生成单条 queue 消息处理器。
299
+ *
300
+ * @param routeId route 稳定 ID。
301
+ * @param config 当前配置快照。
302
+ * @returns 处理队列消息的异步函数。
303
+ */
304
+ private createProcessor(routeId: string, config: ManagerConfiguration): QueueProcessor {
305
+ return async (item) => {
306
+ this.processingIndicator?.start(item.messageId, item.replyContext);
307
+ try {
308
+ const reply = await this.processQueueItem(routeId, item, config);
309
+ if (this.replySink) {
310
+ await this.replySink(
311
+ routeId,
312
+ item.messageId,
313
+ truncateToSingleMessage(reply),
314
+ item.replyContext,
315
+ );
316
+ }
317
+ return reply;
318
+ } finally {
319
+ this.processingIndicator?.stop(item.messageId);
320
+ }
321
+ };
322
+ }
323
+
324
+ /**
325
+ * 对失败或中断的入站消息执行显式重试; retry control command 本身不重放。
326
+ *
327
+ * @param routeId 微信 route ID。
328
+ * @param targetMessageId 需要重试的原始消息 ID。
329
+ * @param controlMessageId 当前 /retry 命令 ID。
330
+ * @param confirmed 是否带有显式确认标志。
331
+ * @param config 当前配置快照。
332
+ * @returns retry 结果。
333
+ */
334
+ private async retryMessage(
335
+ routeId: string,
336
+ targetMessageId: string,
337
+ controlMessageId: string,
338
+ confirmed: boolean,
339
+ config: ManagerConfiguration,
340
+ controlReplyContext?: IlinkReplyContext,
341
+ ): Promise<GatewayReceiveResult> {
342
+ if (!confirmed) {
343
+ const warning = "重试会重新执行原 prompt, 可能重复产生副作用。确认后使用 /retry <message-id> --confirm。";
344
+ if (this.replySink) {
345
+ await this.replySink(routeId, controlMessageId, warning, controlReplyContext);
346
+ }
347
+ return {
348
+ messageId: controlMessageId,
349
+ state: "confirmation_required",
350
+ duplicate: false,
351
+ ...(this.replySink ? {} : { reply: warning }),
352
+ };
353
+ }
354
+
355
+ let items: DurableQueueItem[];
356
+ try {
357
+ items = await this.queue.recoverInterrupted(routeId);
358
+ } catch (error) {
359
+ const message = error instanceof DurableQueueError
360
+ ? error.message
361
+ : "无法安全恢复当前 route queue。";
362
+ if (this.replySink) {
363
+ await this.replySink(routeId, controlMessageId, message, controlReplyContext);
364
+ }
365
+ return {
366
+ messageId: controlMessageId,
367
+ state: "retry_blocked",
368
+ duplicate: false,
369
+ ...(this.replySink ? {} : { reply: message }),
370
+ };
371
+ }
372
+ const target = items.find((item) => item.messageId === targetMessageId);
373
+ if (!target) {
374
+ const notFound = `未找到 queue 消息: ${targetMessageId}。`;
375
+ if (this.replySink) {
376
+ await this.replySink(routeId, controlMessageId, notFound, controlReplyContext);
377
+ }
378
+ return {
379
+ messageId: controlMessageId,
380
+ state: "not_found",
381
+ duplicate: false,
382
+ ...(this.replySink ? {} : { reply: notFound }),
383
+ };
384
+ }
385
+ let originalCommand;
386
+ try {
387
+ originalCommand = parseGatewayCommand(target.text);
388
+ } catch {
389
+ originalCommand = undefined;
390
+ }
391
+ if (!originalCommand || originalCommand.kind === "retry") {
392
+ const notRetryable = "无法识别原 queue 命令; 不会自动重放 control command。";
393
+ if (this.replySink) {
394
+ await this.replySink(routeId, controlMessageId, notRetryable, controlReplyContext);
395
+ }
396
+ return {
397
+ messageId: controlMessageId,
398
+ state: "not_retryable",
399
+ duplicate: false,
400
+ ...(this.replySink ? {} : { reply: notRetryable }),
401
+ };
402
+ }
403
+
404
+ try {
405
+ await this.queue.retry(routeId, targetMessageId);
406
+ } catch (error) {
407
+ const message = error instanceof DurableQueueError ? error.message : "queue retry 失败。";
408
+ if (this.replySink) {
409
+ await this.replySink(routeId, controlMessageId, message, controlReplyContext);
410
+ }
411
+ return {
412
+ messageId: controlMessageId,
413
+ state: "retry_rejected",
414
+ duplicate: false,
415
+ ...(this.replySink ? {} : { reply: message }),
416
+ };
417
+ }
418
+
419
+ const retryNotice = `已确认重试 ${targetMessageId}; 原 prompt 会再次执行, 请留意可能的重复副作用。`;
420
+ if (this.replySink) {
421
+ await this.replySink(routeId, controlMessageId, retryNotice, controlReplyContext);
422
+ }
423
+ const result = await this.queue.dispatch(
424
+ routeId,
425
+ targetMessageId,
426
+ target.text,
427
+ config.runtime.maxQueuePerSession,
428
+ this.createProcessor(routeId, config),
429
+ target.replyContext,
430
+ );
431
+ return {
432
+ messageId: controlMessageId,
433
+ state: result.item.state,
434
+ duplicate: false,
435
+ ...(this.replySink ? {} : { reply: result.reply ?? retryNotice }),
436
+ };
437
+ }
438
+
439
+ /**
440
+ * 登记或更改一个项目 alias。
441
+ *
442
+ * @param arguments_ /projects 后的原始参数。
443
+ * @returns 命令回复。
444
+ */
445
+ private async handleProjects(arguments_: string): Promise<string> {
446
+ let command;
447
+ try {
448
+ command = parseProjectCommand(arguments_);
449
+ } catch (error) {
450
+ if (error instanceof ProjectCommandParseError) {
451
+ return error.message;
452
+ }
453
+ throw error;
454
+ }
455
+
456
+ if (command.action === "list") {
457
+ const { config, projects } = await this.projectService.list();
458
+ if (projects.length === 0) {
459
+ return config.allowedProjectRoots.length === 0
460
+ ? "尚无项目 alias。请先在配置文件设置 allowedProjectRoots。"
461
+ : "尚无项目 alias, 可用 /projects add 登记项目。";
462
+ }
463
+ const defaultAlias = config.defaultProject;
464
+ const rows = projects.map(([alias, project]) => {
465
+ const mark = defaultAlias === alias ? "**是**" : "";
466
+ return `| ${alias} | ${project.displayName} | ${mark} |`;
467
+ });
468
+ return [
469
+ `**已登记项目** · 共 ${projects.length} 个`,
470
+ ["| 别名 | 名称 | 默认 |", "| --- | --- | --- |", ...rows].join("\n"),
471
+ `默认项目:${defaultAlias ? `\`${defaultAlias}\`` : "未设置"}`,
472
+ "登记新项目:`/projects add <别名> --name <名称> --path <绝对路径>`",
473
+ ].join("\n\n");
474
+ }
475
+ if (command.action === "add") {
476
+ const project = await this.projectService.add(
477
+ command.alias,
478
+ command.displayName,
479
+ command.path,
480
+ );
481
+ return `项目已登记: ${command.alias} - ${project.displayName}`;
482
+ }
483
+ if (command.action === "remove") {
484
+ await this.projectService.remove(command.alias);
485
+ return `已移除项目登记: ${command.alias}; 项目目录未删除。`;
486
+ }
487
+ await this.projectService.setDefault(command.alias);
488
+ return `默认项目已设置为: ${command.alias}`;
489
+ }
490
+
491
+ /**
492
+ * 创建后台或可见 UI Pi session 并原子切换当前 route 绑定。
493
+ *
494
+ * @param routeId 微信 route ID。
495
+ * @param mode 新会话运行模式, 缺省为后台。
496
+ * @param projectAlias 用户指定项目 alias。
497
+ * @param name 可选 session 名称。
498
+ * @param config 当前配置快照。
499
+ * @returns 创建结果。
500
+ */
501
+ private async handleNew(
502
+ routeId: string,
503
+ mode: RuntimeMode | undefined,
504
+ projectAlias: string | undefined,
505
+ name: string | undefined,
506
+ config: ManagerConfiguration,
507
+ ): Promise<string> {
508
+ const requestedMode = mode ?? "background";
509
+ const alias = projectAlias ?? config.defaultProject;
510
+ if (!alias) {
511
+ return "尚未设置 defaultProject。请先通过 /projects default <alias> 选择项目。";
512
+ }
513
+
514
+ const oldSnapshot = await this.registry.readSnapshot();
515
+ const oldRoute = Object.hasOwn(oldSnapshot.routes, routeId)
516
+ ? oldSnapshot.routes[routeId]
517
+ : undefined;
518
+ const session = await this.workerManager.startNew(alias, name, requestedMode);
519
+ const newSnapshot = await this.registry.readSnapshot();
520
+ const indexedSession = newSnapshot.sessions[session.sessionId];
521
+ const owner = Object.values(newSnapshot.instances).find((instance) =>
522
+ instance.sessionId === session.sessionId,
523
+ );
524
+ if (!owner) {
525
+ await this.workerManager.stop(session.sessionId).catch(() => undefined);
526
+ throw new BackgroundWorkerManagerError(
527
+ "worker_not_found",
528
+ "Pi worker 已启动, 但 registry 未登记 owner; 已尝试优雅停止。",
529
+ );
530
+ }
531
+
532
+ try {
533
+ await this.registry.setRoute(routeId, {
534
+ sessionId: session.sessionId,
535
+ workerInstanceId: owner.instanceId,
536
+ generation: (oldRoute?.generation ?? 0) + 1,
537
+ updatedAt: new Date().toISOString(),
538
+ });
539
+ } catch (error) {
540
+ await this.workerManager.stop(session.sessionId).catch(() => undefined);
541
+ throw error;
542
+ }
543
+ const stateText = indexedSession?.state === "pending" ? "待首次对话后落盘" : "活跃";
544
+ const modeText = requestedMode === "ui" ? "可见 UI" : "后台";
545
+ const sessionLabel = indexedSession?.name ?? `#${indexedSession?.publicIndex ?? "?"}`;
546
+ return [
547
+ `**已创建会话** ${sessionLabel}`,
548
+ `项目:${alias}`,
549
+ `模式:${modeText}`,
550
+ `状态:${stateText}`,
551
+ "直接发送内容即可开始对话。",
552
+ ].join("\n\n");
553
+ }
554
+
555
+ /**
556
+ * 一页列出符合筛选条件的所有 sessions, 不更改当前 route。
557
+ *
558
+ * @param routeId 当前微信 route ID。
559
+ * @param projectAlias 可选项目筛选。
560
+ * @param state 状态筛选。
561
+ * @param config 当前配置快照。
562
+ * @returns 完整会话清单文本。
563
+ */
564
+ private async formatSessions(
565
+ routeId: string,
566
+ projectAlias: string | undefined,
567
+ state: "default" | "active" | "saved" | "pending" | "all",
568
+ config: ManagerConfiguration,
569
+ ): Promise<string> {
570
+ const snapshot = await this.registry.readSnapshot();
571
+ const currentRouteSessionId = snapshot.routes[routeId]?.sessionId;
572
+ const activeSessionIds = new Set(
573
+ Object.values(snapshot.instances)
574
+ .filter((instance) => instance.state !== "stale" && instance.state !== "stopping")
575
+ .map((instance) => instance.sessionId),
576
+ );
577
+ const sessions = Object.values(snapshot.sessions)
578
+ .filter((session) => !projectAlias || session.projectAlias === projectAlias)
579
+ .filter((session) => {
580
+ if (state === "all") {
581
+ return true;
582
+ }
583
+ if (state === "active") {
584
+ return activeSessionIds.has(session.sessionId);
585
+ }
586
+ if (state === "default") {
587
+ return activeSessionIds.has(session.sessionId) || session.state === "saved";
588
+ }
589
+ return session.state === state;
590
+ })
591
+ .sort((left, right) => right.lastActivityAt.localeCompare(left.lastActivityAt));
592
+ if (sessions.length === 0) {
593
+ return "没有匹配的会话。";
594
+ }
595
+ const displaySessions = await Promise.all(sessions.map(async (session) => ({
596
+ session,
597
+ title: await resolveSessionTitle(session),
598
+ })));
599
+ const currentRouteSession = currentRouteSessionId
600
+ ? snapshot.sessions[currentRouteSessionId]
601
+ : undefined;
602
+ const currentRouteLabel = currentRouteSession
603
+ ? `当前微信路由:#${currentRouteSession.publicIndex ?? "?"}`
604
+ : undefined;
605
+ const rows = displaySessions.map(({ session, title }) => {
606
+ const status = activeSessionIds.has(session.sessionId)
607
+ ? session.state === "pending" ? "等待首条记录" : "活跃"
608
+ : session.state === "pending" ? "等待首条记录" : "已保存";
609
+ const mode = activeSessionIds.has(session.sessionId) && session.mode === "ui" ? "前台" : "后台";
610
+ // 表头已明确写有“索引”, 单元格内不必再加 # 前缀; 该值可直接用于 /resume。
611
+ const index = String(session.publicIndex ?? "?");
612
+ const markedTitle = currentRouteSessionId === session.sessionId
613
+ ? `${title}(当前)`
614
+ : title;
615
+ return `| ${index} | ${markedTitle} | ${mode} | ${status} |`;
616
+ });
617
+ // 项目名逐行重复会显著撑宽表格, 改为按项目分组在表格下方一次性说明。
618
+ const projectSummary = [...new Set(displaySessions.map(({ session }) =>
619
+ Object.hasOwn(config.projects, session.projectAlias)
620
+ ? config.projects[session.projectAlias].displayName
621
+ : session.projectAlias,
622
+ ))];
623
+ // 微信 markdown 渲染支持表格, 且手机端无需横向滚动 (2026-11-11 实测)。
624
+ // 列表项与表格行都是块级元素, 不受“单换行被吞”影响, 因此不用空行分隔。
625
+ const intro = [
626
+ `**会话列表** · 共 ${sessions.length} 个`,
627
+ ...(currentRouteLabel ? [currentRouteLabel] : []),
628
+ ].join("\n\n");
629
+ const table = [
630
+ "| 索引 | 标题 | 模式 | 状态 |",
631
+ "| --- | --- | --- | --- |",
632
+ ...rows,
633
+ ].join("\n");
634
+ const outro = [
635
+ ...(projectSummary.length > 0 ? [`项目:${projectSummary.join("、")}`] : []),
636
+ `切换会话:\`/resume <索引或名称>\``,
637
+ ].join("\n\n");
638
+ return [intro, table, outro].join("\n\n");
639
+ }
640
+
641
+ /**
642
+ * 展示所有受管会话的运行与错误总览。
643
+ *
644
+ * 默认只展示运行中、启动中、异常或断连的会话; `--all` 会包含空闲会话。
645
+ * 失败原因直接从 Pi transcript 最后一条 assistant 记录读取, 不触发模型请求。
646
+ *
647
+ * @param all 是否包含空闲会话。
648
+ * @param config 当前配置快照。
649
+ * @returns markdown 总览表格。
650
+ */
651
+ private async formatWatch(all: boolean, config: ManagerConfiguration): Promise<string> {
652
+ const snapshot = await this.registry.readSnapshot();
653
+ const workersBySession = new Map<string, WorkerInstanceRecord>();
654
+ for (const worker of Object.values(snapshot.instances)) {
655
+ const previous = workersBySession.get(worker.sessionId);
656
+ if (!previous || (previous.state === "stale" && worker.state !== "stale")) {
657
+ workersBySession.set(worker.sessionId, worker);
658
+ }
659
+ }
660
+
661
+ const sessions = Object.values(snapshot.sessions)
662
+ .sort((left, right) => right.lastActivityAt.localeCompare(left.lastActivityAt));
663
+ if (sessions.length === 0) {
664
+ return "尚无已登记会话。";
665
+ }
666
+
667
+ const healthRows: Array<SessionHealth & { title: string; projectName: string }> = await Promise.all(
668
+ sessions.map(async (session) => {
669
+ const worker = workersBySession.get(session.sessionId);
670
+ const failure = await readLatestFailure(session.sessionFile);
671
+ const { state } = evaluateHealth(session, worker, failure);
672
+ const title = await resolveSessionTitle(session);
673
+ const projectName = Object.hasOwn(config.projects, session.projectAlias)
674
+ ? config.projects[session.projectAlias].displayName
675
+ : session.projectAlias;
676
+ return {
677
+ session,
678
+ ...(worker ? { worker } : {}),
679
+ state,
680
+ ...(failure ? { failure } : {}),
681
+ title,
682
+ projectName,
683
+ };
684
+ }),
685
+ );
686
+
687
+ const runningCount = healthRows.filter((row) => row.state === "running").length;
688
+ const startingCount = healthRows.filter((row) => row.state === "starting").length;
689
+ const errorCount = healthRows.filter((row) => row.state === "error").length;
690
+ const stoppingCount = healthRows.filter((row) => row.state === "stopping").length;
691
+ const disconnectedCount = healthRows.filter((row) => row.state === "disconnected").length;
692
+ const idleCount = healthRows.filter((row) => row.state === "idle").length;
693
+ const summary = [
694
+ `**总览** · ${healthRows.length} 个会话`,
695
+ `${runningCount} 运行中`,
696
+ ...(startingCount ? [`${startingCount} 启动中`] : []),
697
+ `${errorCount + disconnectedCount + stoppingCount} 异常`,
698
+ `${idleCount} 空闲`,
699
+ ].join(" · ");
700
+
701
+ const visibleRows = all
702
+ ? healthRows
703
+ : healthRows.filter((row) => row.state !== "idle");
704
+ if (visibleRows.length === 0) {
705
+ return [
706
+ summary,
707
+ "当前没有运行中或异常会话。",
708
+ "发送 `/watch --all` 查看全部会话。",
709
+ ].join("\n\n");
710
+ }
711
+
712
+ const tableRows = visibleRows.map((row) => {
713
+ const index = String(row.session.publicIndex ?? "?");
714
+ const title = escapeMarkdownTableCell(row.title);
715
+ const project = escapeMarkdownTableCell(row.projectName);
716
+ const state = formatHealthState(row.state);
717
+ const lastActivity = formatLocalMinute(row.session.lastActivityAt);
718
+ return `| ${index} | ${title} | ${project} | ${state} | ${lastActivity} |`;
719
+ });
720
+ const table = [
721
+ "| 索引 | 会话 | 项目 | 状态 | 最后活动 |",
722
+ "| --- | --- | --- | --- | --- |",
723
+ ...tableRows,
724
+ ].join("\n");
725
+
726
+ const attentionRows = visibleRows.filter((row) =>
727
+ row.state === "error" || row.state === "disconnected" || row.state === "stopping",
728
+ );
729
+ const attention = attentionRows.length === 0
730
+ ? []
731
+ : [
732
+ "**需要处理**",
733
+ ...attentionRows.map((row) => {
734
+ const index = row.session.publicIndex ?? "?";
735
+ const title = row.title;
736
+ if (row.state === "error" && row.failure) {
737
+ const recovery = !row.worker || row.worker.state === "stale"
738
+ ? `; 可发送 \`/resume ${index}\` 重连`
739
+ : "";
740
+ return `- **${index} ${title}**:${formatFailureSummary(row.failure)}${recovery}`;
741
+ }
742
+ if (row.state === "disconnected") {
743
+ const failureNote = row.failure ? `; ${formatFailureSummary(row.failure)}` : "";
744
+ return `- **${index} ${title}**:会话断连${failureNote}, 可发送 \`/resume ${index}\` 重连`;
745
+ }
746
+ return `- **${index} ${title}**:正在停止`;
747
+ }),
748
+ ];
749
+
750
+ return [summary, table, ...attention].join("\n\n");
751
+ }
752
+
753
+ /**
754
+ * 恢复唯一匹配的 session 并切换当前 route。
755
+ *
756
+ * @param routeId 微信 route ID。
757
+ * @param selector session ID 前缀或名称。
758
+ * @returns 恢复结果。
759
+ */
760
+ private async handleResume(
761
+ routeId: string,
762
+ selector: string,
763
+ ): Promise<string> {
764
+ const session = await this.resolveSessionSelector(selector);
765
+ const previousRoute = (await this.registry.readSnapshot()).routes[routeId];
766
+ await this.workerManager.resume(session.sessionId);
767
+ const snapshot = await this.registry.readSnapshot();
768
+ const owner = Object.values(snapshot.instances).find((instance) =>
769
+ instance.sessionId === session.sessionId,
770
+ );
771
+ if (!owner) {
772
+ throw new BackgroundWorkerManagerError(
773
+ "worker_not_found",
774
+ "Pi session 已启动, 但 registry 未找到 owner。",
775
+ );
776
+ }
777
+ await this.registry.setRoute(routeId, {
778
+ sessionId: session.sessionId,
779
+ workerInstanceId: owner.instanceId,
780
+ generation: (Object.hasOwn(snapshot.routes, routeId) ? snapshot.routes[routeId].generation : 0) + 1,
781
+ updatedAt: new Date().toISOString(),
782
+ });
783
+ const confirmation = `已恢复会话 #${session.publicIndex ?? "?"} ${session.name ?? "未命名"} (${session.projectAlias})。`;
784
+ if (previousRoute?.sessionId === session.sessionId || owner.state !== "idle") {
785
+ return confirmation;
786
+ }
787
+ const latestFailure = await readLatestFailure(session.sessionFile);
788
+ if (latestFailure) {
789
+ return [
790
+ confirmation,
791
+ `**最近一次回复失败**\n\n${formatFailureSummary(latestFailure)}`,
792
+ ].join("\n\n");
793
+ }
794
+ const latestAssistantText = await readLatestAssistantText(session.sessionFile);
795
+ if (!latestAssistantText) {
796
+ return confirmation;
797
+ }
798
+ const preview = truncateTail(latestAssistantText, RESUME_ASSISTANT_TEXT_LIMIT);
799
+ // 单个换行会被微信的 markdown 渲染吞成空格, 因此标签与正文之间用空行分隔。
800
+ return [
801
+ `${confirmation}`,
802
+ preview.truncated
803
+ ? `**最近一次回复(末段节选)**\n\n${preview.text}\n\n[回复较长, 以上为结尾 ${RESUME_ASSISTANT_TEXT_LIMIT} 字; 完整回复仍保留在会话记录中。]`
804
+ : `**最近一次回复**\n\n${preview.text}`,
805
+ ].join("\n\n");
806
+ }
807
+
808
+ /**
809
+ * 只读展示指定或当前 route 会话的最近一轮对话, 不更改 route 绑定, 也不投递 prompt。
810
+ *
811
+ * @param routeId 微信 route ID。
812
+ * @param selector 可选会话索引或名称。
813
+ * @param config 当前配置快照。
814
+ * @returns 最近一轮对话的只读摘要。
815
+ */
816
+ private async handleLast(
817
+ routeId: string,
818
+ selector: string | undefined,
819
+ config: ManagerConfiguration,
820
+ ): Promise<string> {
821
+ const snapshot = await this.registry.readSnapshot();
822
+ const boundSessionId = Object.hasOwn(snapshot.routes, routeId)
823
+ ? snapshot.routes[routeId].sessionId
824
+ : undefined;
825
+ const session = selector
826
+ ? await this.resolveSessionSelector(selector)
827
+ : boundSessionId && Object.hasOwn(snapshot.sessions, boundSessionId)
828
+ ? snapshot.sessions[boundSessionId]
829
+ : undefined;
830
+ if (!session) {
831
+ return "当前微信路由没有绑定会话。使用 /sessions 查看列表, 或 /last <索引> 查看指定会话。";
832
+ }
833
+ const running = Object.values(snapshot.instances).some((instance) =>
834
+ instance.sessionId === session.sessionId && instance.state === "running"
835
+ );
836
+ const projectName = Object.hasOwn(config.projects, session.projectAlias)
837
+ ? config.projects[session.projectAlias].displayName
838
+ : session.projectAlias;
839
+ const title = await resolveSessionTitle(session);
840
+ const header = [
841
+ `**会话 #${session.publicIndex ?? "?"}** ${title}`,
842
+ `项目:${projectName}`,
843
+ `最后活动:${formatLocalMinute(session.lastActivityAt)} · ${session.mode === "ui" ? "前台" : "后台"}`,
844
+ ].join("\n\n");
845
+ const turn = await readLatestTurn(session.sessionFile);
846
+ if (!turn) {
847
+ return [
848
+ header,
849
+ session.state === "pending"
850
+ ? "该会话尚未写入任何对话记录。"
851
+ : "未能读取该会话的对话记录。",
852
+ ].join("\n\n");
853
+ }
854
+
855
+ const body: string[] = [];
856
+ if (turn.userText) {
857
+ const userPreview = truncateHead(turn.userText, LAST_USER_TEXT_LIMIT);
858
+ body.push(
859
+ [
860
+ "**你**",
861
+ userPreview.text,
862
+ ...(userPreview.truncated ? ["[提问较长, 已截断。]"] : []),
863
+ ].join("\n\n"),
864
+ );
865
+ }
866
+ if (turn.assistantFailure) {
867
+ body.push([
868
+ "**AI(错误)**",
869
+ formatFailureSummary(turn.assistantFailure),
870
+ ].join("\n\n"));
871
+ } else if (turn.assistantText) {
872
+ const assistantPreview = truncateTail(turn.assistantText, LAST_ASSISTANT_TEXT_LIMIT);
873
+ body.push(
874
+ [
875
+ assistantPreview.truncated ? "**AI(末段节选)**" : "**AI**",
876
+ assistantPreview.text,
877
+ ...(assistantPreview.truncated
878
+ ? [`[回复较长, 以上为结尾 ${LAST_ASSISTANT_TEXT_LIMIT} 字; 完整内容仍保留在会话记录中。]`]
879
+ : []),
880
+ ].join("\n\n"),
881
+ );
882
+ } else {
883
+ body.push(["**AI**", "尚未产生回复。"].join("\n\n"));
884
+ }
885
+ return [
886
+ header,
887
+ ...(running ? ["⚠️ 该会话正在运行, 以下为目前已落盘的内容。"] : []),
888
+ body.join("\n\n"),
889
+ selector
890
+ ? `发送 \`/resume ${session.publicIndex ?? selector}\` 可切换到此会话。`
891
+ : "发送任意内容可继续对话。",
892
+ ].join("\n\n");
893
+ }
894
+
895
+ /**
896
+ * 停止当前 route 或指定的活跃 Pi session。
897
+ *
898
+ * @param routeId 微信 route ID。
899
+ * @param selector 可选 session ID 前缀或名称。
900
+ * @returns 停止结果。
901
+ */
902
+ private async handleStop(routeId: string, selector: string | undefined): Promise<string> {
903
+ const snapshot = await this.registry.readSnapshot();
904
+ const binding = Object.hasOwn(snapshot.routes, routeId)
905
+ ? snapshot.routes[routeId]
906
+ : undefined;
907
+ const session = selector
908
+ ? await this.resolveSessionSelector(selector)
909
+ : binding && Object.hasOwn(snapshot.sessions, binding.sessionId)
910
+ ? snapshot.sessions[binding.sessionId]
911
+ : undefined;
912
+ if (!session) {
913
+ return "当前 route 没有活跃 session; 可使用 /sessions 查看列表。";
914
+ }
915
+ await this.workerManager.stop(session.sessionId);
916
+ if (binding?.sessionId === session.sessionId) {
917
+ await this.registry.setRoute(routeId, null);
918
+ }
919
+ const stoppedSession = (await this.registry.readSnapshot()).sessions[session.sessionId];
920
+ return stoppedSession?.state === "pending"
921
+ ? `会话 #${session.publicIndex ?? "?"} 已停止, 但尚无 transcript 文件, 因此不能恢复。`
922
+ : `会话 #${session.publicIndex ?? "?"} 已停止并保存。`;
923
+ }
924
+
925
+ /**
926
+ * 将普通文本投递到 route 当前绑定的 background 或 UI Pi worker。
927
+ *
928
+ * @param routeId 微信 route ID。
929
+ * @param text prompt 正文。
930
+ * @returns Pi assistant 回复。
931
+ */
932
+ private async handlePrompt(routeId: string, text: string): Promise<string> {
933
+ const snapshot = await this.registry.readSnapshot();
934
+ const binding = Object.hasOwn(snapshot.routes, routeId)
935
+ ? snapshot.routes[routeId]
936
+ : undefined;
937
+ if (!binding) {
938
+ return "当前没有活动会话。请先使用 /new --project <alias> 创建后台会话, 再用 /resume <索引> 切换。";
939
+ }
940
+ const session = Object.hasOwn(snapshot.sessions, binding.sessionId)
941
+ ? snapshot.sessions[binding.sessionId]
942
+ : undefined;
943
+ if (!session) {
944
+ return "当前 route 指向的 session 不在 registry 中, 已停止投递以避免错路由。";
945
+ }
946
+ const worker = Object.hasOwn(snapshot.instances, binding.workerInstanceId)
947
+ ? snapshot.instances[binding.workerInstanceId]
948
+ : undefined;
949
+ if (!worker || worker.state === "stale" || worker.state === "stopping") {
950
+ return "当前 route 没有可用的 Pi worker; 请使用 /resume <索引> 重连。";
951
+ }
952
+ return this.workerManager.prompt(binding.sessionId, text);
953
+ }
954
+
955
+ /**
956
+ * 格式化当前 Gateway、route、worker 和队列状态。
957
+ *
958
+ * @param routeId 微信 route ID。
959
+ * @param config 当前配置快照。
960
+ * @returns 不包含凭证和完整路径的状态文本。
961
+ */
962
+ private async formatStatus(routeId: string, config: ManagerConfiguration): Promise<string> {
963
+ const snapshot = await this.registry.readSnapshot();
964
+ const binding = Object.hasOwn(snapshot.routes, routeId)
965
+ ? snapshot.routes[routeId]
966
+ : undefined;
967
+ const session = binding && Object.hasOwn(snapshot.sessions, binding.sessionId)
968
+ ? snapshot.sessions[binding.sessionId]
969
+ : undefined;
970
+ const instance = binding && Object.hasOwn(snapshot.instances, binding.workerInstanceId)
971
+ ? snapshot.instances[binding.workerInstanceId]
972
+ : undefined;
973
+ const queueItems = await this.queue.list(routeId);
974
+ const pendingQueueCount = queueItems.filter((item) =>
975
+ item.state === "queued" || item.state === "failed" || item.state === "interrupted",
976
+ ).length;
977
+ const skippedItems = await this.queue.listSkipped(routeId);
978
+ const skippedLines = skippedItems.length === 0
979
+ ? []
980
+ : [
981
+ [
982
+ `**已跳过** · ${skippedItems.length} 条`,
983
+ [
984
+ "| 消息 ID | 原因 | 原文 |",
985
+ "| --- | --- | --- |",
986
+ ...skippedItems.slice(-3).map((item) =>
987
+ `| ${item.messageId} | ${item.errorCode ?? "未知"} | ${truncatePreview(item.text)} |`,
988
+ ),
989
+ ].join("\n"),
990
+ "重新执行:`/retry <消息ID> --confirm`",
991
+ ].join("\n\n"),
992
+ ];
993
+ const projectCount = Object.keys(config.projects).length;
994
+ const projectName = session
995
+ ? Object.hasOwn(config.projects, session.projectAlias)
996
+ ? config.projects[session.projectAlias].displayName
997
+ : session.projectAlias
998
+ : undefined;
999
+ const sessionTitle = session
1000
+ ? `#${session.publicIndex ?? "?"} ${await resolveSessionTitle(session)}`
1001
+ : "未绑定";
1002
+ const workerLabel = instance
1003
+ ? `${instance.mode === "ui" ? "前台" : "后台"} · ${formatWorkerState(instance.state)}`
1004
+ : "未运行";
1005
+ const uiModeLine = this.uiModeCapability
1006
+ ? [`| 可见 UI 模式 | ${await this.formatUiModeCapability()} |`]
1007
+ : [];
1008
+ return [
1009
+ "**Hub 状态**",
1010
+ [
1011
+ "| 项 | 值 |",
1012
+ "| --- | --- |",
1013
+ `| 连接 | ${formatGatewayState(snapshot.gateway?.state)} |`,
1014
+ `| 当前会话 | ${sessionTitle} |`,
1015
+ ...(projectName ? [`| 项目 | ${projectName} |`] : []),
1016
+ `| Pi | ${workerLabel} |`,
1017
+ ...uiModeLine,
1018
+ `| 未完成消息 | ${pendingQueueCount} 条 |`,
1019
+ `| 已登记项目 | ${projectCount} 个 |`,
1020
+ ].join("\n"),
1021
+ ...skippedLines,
1022
+ ].join("\n\n");
1023
+ }
1024
+
1025
+ /**
1026
+ * 格式化当前环境是否可创建或恢复可见 UI 会话。
1027
+ *
1028
+ * @returns 面向微信用户的中文能力说明。
1029
+ */
1030
+ private async formatUiModeCapability(): Promise<string> {
1031
+ try {
1032
+ const capability = await this.uiModeCapability!();
1033
+ return capability.supported ? "可用" : `不可用(${capability.reason})`;
1034
+ } catch {
1035
+ return "不可用(无法确认 Windows Terminal 可用性)";
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * 按稳定数字索引或名称查找唯一 session。
1041
+ *
1042
+ * @param selector 用户输入选择器。
1043
+ * @returns 唯一匹配 session。
1044
+ */
1045
+ private async resolveSessionSelector(selector: string): Promise<SessionIndexRecord> {
1046
+ const snapshot = await this.registry.readSnapshot();
1047
+ const normalized = selector.toLowerCase();
1048
+ if (/^[1-9]\d*$/.test(normalized)) {
1049
+ const publicIndex = Number(normalized);
1050
+ const indexedSession = Object.values(snapshot.sessions).find((session) =>
1051
+ session.publicIndex === publicIndex,
1052
+ );
1053
+ if (indexedSession) {
1054
+ return indexedSession;
1055
+ }
1056
+ }
1057
+ const matches = Object.values(snapshot.sessions).filter((session) =>
1058
+ session.name?.toLowerCase() === normalized,
1059
+ );
1060
+ if (matches.length === 0) {
1061
+ throw new BackgroundWorkerManagerError("session_not_found", `未找到会话索引或名称: ${selector}。`);
1062
+ }
1063
+ if (matches.length > 1) {
1064
+ throw new GatewayCommandParseError(`会话名称匹配到多个结果: ${selector}; 请使用数字索引。`);
1065
+ }
1066
+ return matches[0];
1067
+ }
1068
+
1069
+ /**
1070
+ * 对授权用户的 queue 文本执行路由命令。
1071
+ *
1072
+ * @param routeId 微信 route ID。
1073
+ * @param item durable queue 项。
1074
+ * @param config 当前配置快照。
1075
+ * @returns 命令或 agent 回复。
1076
+ */
1077
+ private async processQueueItem(
1078
+ routeId: string,
1079
+ item: DurableQueueItem,
1080
+ config: ManagerConfiguration,
1081
+ ): Promise<string> {
1082
+ let command;
1083
+ try {
1084
+ command = parseGatewayCommand(item.text);
1085
+ } catch (error) {
1086
+ if (error instanceof GatewayCommandParseError) {
1087
+ return error.message;
1088
+ }
1089
+ throw error;
1090
+ }
1091
+ return this.processCommand(routeId, command, config);
1092
+ }
1093
+
1094
+ /**
1095
+ * 执行已解析的 Gateway command 或投递普通 prompt。
1096
+ *
1097
+ * @param routeId 微信 route ID。
1098
+ * @param command 已规范化命令。
1099
+ * @param config 当前配置快照。
1100
+ * @returns 回复文本。
1101
+ */
1102
+ private async processCommand(
1103
+ routeId: string,
1104
+ command: ReturnType<typeof parseGatewayCommand>,
1105
+ config: ManagerConfiguration,
1106
+ ): Promise<string> {
1107
+ try {
1108
+ switch (command.kind) {
1109
+ case "help":
1110
+ return GATEWAY_HELP_TEXT;
1111
+ case "status":
1112
+ return await this.formatStatus(routeId, config);
1113
+ case "projects":
1114
+ return await this.handleProjects(command.arguments);
1115
+ case "new":
1116
+ return await this.handleNew(routeId, command.mode, command.projectAlias, command.name, config);
1117
+ case "sessions":
1118
+ return await this.formatSessions(routeId, command.projectAlias, command.state, config);
1119
+ case "watch":
1120
+ return await this.formatWatch(command.all, config);
1121
+ case "resume":
1122
+ return await this.handleResume(routeId, command.selector);
1123
+ case "last":
1124
+ return await this.handleLast(routeId, command.selector, config);
1125
+ case "stop":
1126
+ return await this.handleStop(routeId, command.selector);
1127
+ case "retry":
1128
+ return "`/retry` 需要由 queue 控制面直接处理, 不能作为普通 FIFO 消息执行。";
1129
+ case "prompt":
1130
+ return await this.handlePrompt(routeId, command.text);
1131
+ }
1132
+ } catch (error) {
1133
+ if (
1134
+ error instanceof ProjectServiceError ||
1135
+ error instanceof BackgroundWorkerManagerError ||
1136
+ error instanceof UiWorkerManagerError ||
1137
+ error instanceof DurableQueueError
1138
+ ) {
1139
+ return error.message;
1140
+ }
1141
+ throw error;
1142
+ }
1143
+ }
1144
+
1145
+ /**
1146
+ * 仅允许配置中的个人微信用户进入消息队列。
1147
+ *
1148
+ * @param senderId 消息发送者 ID。
1149
+ * @param config 当前配置。
1150
+ * @returns 无返回值。
1151
+ * @throws {GatewayAuthorizationError} allowlist 未配置或 sender 不匹配时抛出。
1152
+ */
1153
+ private assertAuthorized(senderId: string, config: ManagerConfiguration): void {
1154
+ const authorizedUserId = config.wechat.authorizedUserId;
1155
+ if (!authorizedUserId.trim()) {
1156
+ throw new GatewayAuthorizationError(
1157
+ "wechat_auth_unavailable",
1158
+ "微信 allowlist 尚未配置, 消息未写入队列。",
1159
+ );
1160
+ }
1161
+ if (senderId !== authorizedUserId) {
1162
+ throw new GatewayAuthorizationError(
1163
+ "unauthorized_wechat_user",
1164
+ "消息来源未授权, 已在队列和路由前拒绝。",
1165
+ );
1166
+ }
1167
+ }
1168
+ }
1169
+
1170
+ const SESSION_TITLE_LIMIT = 32;
1171
+
1172
+ /**
1173
+ * 单条 iLink 消息的 JSON 请求体安全上限 (字节)。
1174
+ *
1175
+ * 2026-11-11 用真实 iLink 服务端二分实测: `sendmessage` 的 body 在
1176
+ * 16791 字节时成功, 16926 字节时返回 `ret=-2`. 这里取 15000 字节并保留
1177
+ * 约 1800 字节余量, 容忍 base_info 字段或服务端额外校验的变化。
1178
+ *
1179
+ * 注意限制的是 **UTF-8 字节数** 而非字符数: 一个汉字占 3 字节, ASCII 占
1180
+ * 1 字节, 所以同一个字节预算下中文比英文能装的字数少得多。
1181
+ */
1182
+ const MAX_SINGLE_MESSAGE_BYTES = 15000;
1183
+
1184
+ /**
1185
+ * iLink 单条消息里 `item_list` 只能是 1 个元素。
1186
+ *
1187
+ * 实测 2 个 item 时即使总长只有 30 字也会返回 `ret=-2 prepare failed`,
1188
+ * 因此任何回复都必须压到单 item 可容纳的字节预算内。
1189
+ */
1190
+ const MAX_SINGLE_MESSAGE_ITEMS = 1;
1191
+
1192
+ /**
1193
+ * 截断提示占用的字节预算, 从总预算中预先扣除。
1194
+ */
1195
+ const TRUNCATION_NOTICE = "\n\n[回复过长, 已截断。]";
1196
+
1197
+ const RESUME_ASSISTANT_TEXT_LIMIT = 3800;
1198
+ const LAST_USER_TEXT_LIMIT = 1200;
1199
+ const LAST_ASSISTANT_TEXT_LIMIT = 3800;
1200
+ const TAIL_READ_BYTES = 256 * 1024;
1201
+ const TAIL_READ_MAX_BYTES = 8 * 1024 * 1024;
1202
+
1203
+ /**
1204
+ * 将 Gateway 生命周期状态转换为面向微信用户的中文说明.
1205
+ *
1206
+ * @param state Gateway 当前状态.
1207
+ * @returns 简短的中文状态说明.
1208
+ */
1209
+ function formatGatewayState(state: string | undefined): string {
1210
+ switch (state) {
1211
+ case undefined:
1212
+ return "未启动";
1213
+ case "starting":
1214
+ return "启动中";
1215
+ case "online":
1216
+ return "在线";
1217
+ case "auth_required":
1218
+ return "需要重新登录";
1219
+ case "stopping":
1220
+ return "停止中";
1221
+ case "stopped":
1222
+ return "已停止";
1223
+ case "lease_lost":
1224
+ return "连接异常";
1225
+ default:
1226
+ return "状态未知";
1227
+ }
1228
+ }
1229
+
1230
+ /**
1231
+ * 将 Pi worker 生命周期状态转换为面向微信用户的中文说明.
1232
+ *
1233
+ * @param state worker 当前状态.
1234
+ * @returns 简短的中文状态说明.
1235
+ */
1236
+ function formatWorkerState(state: string): string {
1237
+ switch (state) {
1238
+ case "starting":
1239
+ return "启动中";
1240
+ case "idle":
1241
+ return "空闲";
1242
+ case "running":
1243
+ return "运行中";
1244
+ case "stopping":
1245
+ return "停止中";
1246
+ case "stale":
1247
+ return "断连待恢复";
1248
+ default:
1249
+ return "状态未知";
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * 解析 session 显示标题: 优先使用名称, 否则使用 Pi resume 列表采用的首条用户文本。
1255
+ *
1256
+ * @param session Hub session 索引。
1257
+ * @returns 已清理并截断的会话标题。
1258
+ */
1259
+ async function resolveSessionTitle(session: SessionIndexRecord): Promise<string> {
1260
+ const name = session.name ? normalizeSessionTitle(session.name) : "";
1261
+ const firstMessage = name ? undefined : await readFirstUserMessage(session.sessionFile);
1262
+ return truncateSessionTitle(name || firstMessage || "(尚无用户消息)");
1263
+ }
1264
+
1265
+ /**
1266
+ * 从 Pi JSONL session 文件中读取首条非空 user 文本。
1267
+ *
1268
+ * @param sessionFile Pi session 文件路径。
1269
+ * @returns 首条用户文本, 不存在或无法读取时返回 undefined。
1270
+ */
1271
+ async function readFirstUserMessage(sessionFile: string): Promise<string | undefined> {
1272
+ let input: ReturnType<typeof createReadStream> | undefined;
1273
+ let lines: ReturnType<typeof createInterface> | undefined;
1274
+ try {
1275
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1276
+ lines = createInterface({ input, crlfDelay: Infinity });
1277
+ for await (const line of lines) {
1278
+ let entry: unknown;
1279
+ try {
1280
+ entry = JSON.parse(line) as unknown;
1281
+ } catch {
1282
+ continue;
1283
+ }
1284
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1285
+ continue;
1286
+ }
1287
+ const message = entry.message;
1288
+ if (message.role !== "user") {
1289
+ continue;
1290
+ }
1291
+ const content = message.content;
1292
+ const text = typeof content === "string"
1293
+ ? content
1294
+ : Array.isArray(content)
1295
+ ? content
1296
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1297
+ .map((block) => (block as { text: string }).text)
1298
+ .join(" ")
1299
+ : "";
1300
+ const normalized = normalizeSessionTitle(text);
1301
+ if (normalized) {
1302
+ return normalized;
1303
+ }
1304
+ }
1305
+ } catch {
1306
+ return undefined;
1307
+ } finally {
1308
+ lines?.close();
1309
+ input?.destroy();
1310
+ }
1311
+ return undefined;
1312
+ }
1313
+
1314
+ /**
1315
+ * 从 Pi JSONL session 文件读取最近一条 assistant 对外文本.
1316
+ *
1317
+ * @param sessionFile Pi transcript 文件路径.
1318
+ * @returns 最近一条非空 assistant 文本, 无法读取或不存在时返回 undefined.
1319
+ */
1320
+ async function readLatestAssistantText(sessionFile: string): Promise<string | undefined> {
1321
+ let input: ReturnType<typeof createReadStream> | undefined;
1322
+ let lines: ReturnType<typeof createInterface> | undefined;
1323
+ let latestText: string | undefined;
1324
+ try {
1325
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1326
+ lines = createInterface({ input, crlfDelay: Infinity });
1327
+ for await (const line of lines) {
1328
+ let entry: unknown;
1329
+ try {
1330
+ entry = JSON.parse(line) as unknown;
1331
+ } catch {
1332
+ continue;
1333
+ }
1334
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1335
+ continue;
1336
+ }
1337
+ const message = entry.message;
1338
+ if (message.role !== "assistant") {
1339
+ continue;
1340
+ }
1341
+ const content = message.content;
1342
+ const text = typeof content === "string"
1343
+ ? content
1344
+ : Array.isArray(content)
1345
+ ? content
1346
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1347
+ .map((block) => (block as { type: "text"; text: string }).text)
1348
+ .join("")
1349
+ : "";
1350
+ const normalized = normalizeAssistantText(text);
1351
+ if (normalized) {
1352
+ latestText = normalized;
1353
+ }
1354
+ }
1355
+ } catch {
1356
+ return undefined;
1357
+ } finally {
1358
+ lines?.close();
1359
+ input?.destroy();
1360
+ }
1361
+ return latestText;
1362
+ }
1363
+
1364
+ /**
1365
+ * 将 ISO 时间转换为本地时区的分钟精度文本。
1366
+ *
1367
+ * @param isoTimestamp registry 中记录的 ISO 时间。
1368
+ * @returns 形如 `2026-08-05 14:32` 的本地时间, 无法解析时返回原始文本。
1369
+ */
1370
+ function formatLocalMinute(isoTimestamp: string): string {
1371
+ const parsed = new Date(isoTimestamp);
1372
+ if (Number.isNaN(parsed.getTime())) {
1373
+ return isoTimestamp;
1374
+ }
1375
+ const pad = (value: number): string => String(value).padStart(2, "0");
1376
+ return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
1377
+ }
1378
+
1379
+ /**
1380
+ * 将用户提问限制在固定长度内, 保留开头。
1381
+ *
1382
+ * 提问通常开头就说明主题, 因此保留前段更利于判断“我在问什么”。
1383
+ *
1384
+ * @param text 原始提问文本。
1385
+ * @param limit 最大 Unicode code point 数。
1386
+ * @returns 可安全发送的完整或截断文本。
1387
+ */
1388
+ function truncateHead(text: string, limit: number): { text: string; truncated: boolean } {
1389
+ const characters = Array.from(text);
1390
+ if (characters.length <= limit) {
1391
+ return { text, truncated: false };
1392
+ }
1393
+ return {
1394
+ text: characters.slice(0, limit).join(""),
1395
+ truncated: true,
1396
+ };
1397
+ }
1398
+
1399
+ /**
1400
+ * 将助手回复限制在固定长度内, 保留结尾。
1401
+ *
1402
+ * “最近聊到哪”的结论与下一步通常落在回复末尾, 因此保留后段更贴近
1403
+ * 用户在手机上回顾上下文时的真实需求。
1404
+ *
1405
+ * @param text 原始回复文本。
1406
+ * @param limit 最大 Unicode code point 数。
1407
+ * @returns 可安全发送的完整或截断文本。
1408
+ */
1409
+ function truncateTail(text: string, limit: number): { text: string; truncated: boolean } {
1410
+ const characters = Array.from(text);
1411
+ if (characters.length <= limit) {
1412
+ return { text, truncated: false };
1413
+ }
1414
+ return {
1415
+ text: characters.slice(-limit).join(""),
1416
+ truncated: true,
1417
+ };
1418
+ }
1419
+
1420
+ /**
1421
+ * 从 Pi transcript 尾部按需扩展窗口, 读取最近一轮 user 与 assistant 文本。
1422
+ *
1423
+ * 先读文件末尾固定字节区间, 按 LF 切分后从后向前定位最新的 user 与 assistant
1424
+ * 消息; 尾部首行可能是被截断的半行, 因此总是丢弃。如果窗口内找不到完整一轮
1425
+ * (常见于单条消息本身就超过初始窗口), 按倍数扩大窗口重试; 超过上限仍未命中时
1426
+ * 回退为流式全文件扫描, 保证结果正确。
1427
+ *
1428
+ * @param sessionFile Pi transcript 文件路径。
1429
+ * @returns 最近一轮 user 与 assistant 文本, 无可用记录时返回 undefined。
1430
+ */
1431
+ async function readLatestTurn(sessionFile: string): Promise<LatestTurn | undefined> {
1432
+ const handle = await open(sessionFile, "r").catch(() => undefined);
1433
+ if (!handle) {
1434
+ return undefined;
1435
+ }
1436
+ try {
1437
+ const { size } = await handle.stat();
1438
+ if (size === 0) {
1439
+ return undefined;
1440
+ }
1441
+ let windowBytes = Math.min(size, TAIL_READ_BYTES);
1442
+ for (;;) {
1443
+ const start = size - windowBytes;
1444
+ const chunk = Buffer.alloc(windowBytes);
1445
+ await handle.read(chunk, 0, windowBytes, start);
1446
+ const text = chunk.toString("utf8");
1447
+ let buffer = text;
1448
+ if (start > 0) {
1449
+ const firstNewline = text.indexOf("\n");
1450
+ buffer = firstNewline < 0 ? "" : text.slice(firstNewline + 1);
1451
+ }
1452
+ const turn = scanTurnLines(buffer);
1453
+ const hasAssistantResult = turn.assistantText !== undefined || turn.assistantFailure !== undefined;
1454
+ if (hasAssistantResult && turn.userText !== undefined) {
1455
+ return turn;
1456
+ }
1457
+ if (start === 0) {
1458
+ return !hasAssistantResult && turn.userText === undefined ? undefined : turn;
1459
+ }
1460
+ if (windowBytes >= TAIL_READ_MAX_BYTES) {
1461
+ const fallback = await fullScanLatestTurn(sessionFile);
1462
+ return fallback.assistantText === undefined &&
1463
+ fallback.assistantFailure === undefined &&
1464
+ fallback.userText === undefined
1465
+ ? undefined
1466
+ : fallback;
1467
+ }
1468
+ windowBytes = Math.min(size, windowBytes * 2);
1469
+ }
1470
+ } finally {
1471
+ await handle.close();
1472
+ }
1473
+ }
1474
+
1475
+ /**
1476
+ * 在一段 transcript 文本中从后向前定位最新的 user 与 assistant 文本。
1477
+ *
1478
+ * @param buffer 已剔除尾部半行的 transcript 文本片段。
1479
+ * @returns 已找到的 user 与 assistant 文本, 任意字段都可能缺失。
1480
+ */
1481
+ function scanTurnLines(buffer: string): LatestTurn {
1482
+ const lines = buffer.split("\n");
1483
+ let assistantText: string | undefined;
1484
+ let assistantFailure: TurnFailure | undefined;
1485
+ let assistantResolved = false;
1486
+ let userText: string | undefined;
1487
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1488
+ const line = lines[index];
1489
+ if (!line.trim()) {
1490
+ continue;
1491
+ }
1492
+ let entry: unknown;
1493
+ try {
1494
+ entry = JSON.parse(line) as unknown;
1495
+ } catch {
1496
+ continue;
1497
+ }
1498
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1499
+ continue;
1500
+ }
1501
+ const message = entry.message;
1502
+ const role = message.role;
1503
+ if (role !== "user" && role !== "assistant") {
1504
+ continue;
1505
+ }
1506
+ if (role === "assistant" && !assistantResolved) {
1507
+ const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage : "";
1508
+ const stopReason = typeof message.stopReason === "string" ? message.stopReason : "";
1509
+ if (errorMessage || stopReason === "error") {
1510
+ assistantFailure = errorMessage
1511
+ ? classifyFailure(errorMessage)
1512
+ : { kind: "unknown", summary: "上游返回错误但未提供详情", raw: "stopReason=error" };
1513
+ assistantResolved = true;
1514
+ } else {
1515
+ const text = extractMessageText(message.content);
1516
+ if (text) {
1517
+ assistantText = text;
1518
+ assistantResolved = true;
1519
+ }
1520
+ }
1521
+ } else if (role === "user" && userText === undefined) {
1522
+ userText = extractMessageText(message.content);
1523
+ }
1524
+ if (assistantResolved && userText !== undefined) {
1525
+ break;
1526
+ }
1527
+ }
1528
+ return { userText, assistantText, assistantFailure };
1529
+ }
1530
+
1531
+ /**
1532
+ * 流式扫描整个 transcript, 作为超大单条记录窗口读取失败后的兼容路径。
1533
+ *
1534
+ * @param sessionFile Pi transcript 文件路径。
1535
+ * @returns 整个文件中最后一组 user 与 assistant 文本。
1536
+ */
1537
+ async function fullScanLatestTurn(sessionFile: string): Promise<LatestTurn> {
1538
+ let input: ReturnType<typeof createReadStream> | undefined;
1539
+ let lines: ReturnType<typeof createInterface> | undefined;
1540
+ let assistantText: string | undefined;
1541
+ let assistantFailure: TurnFailure | undefined;
1542
+ let userText: string | undefined;
1543
+ try {
1544
+ input = createReadStream(sessionFile, { encoding: "utf8" });
1545
+ lines = createInterface({ input, crlfDelay: Infinity });
1546
+ for await (const line of lines) {
1547
+ let entry: unknown;
1548
+ try {
1549
+ entry = JSON.parse(line) as unknown;
1550
+ } catch {
1551
+ continue;
1552
+ }
1553
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
1554
+ continue;
1555
+ }
1556
+ const message = entry.message;
1557
+ if (message.role === "user") {
1558
+ const text = extractMessageText(message.content);
1559
+ if (text) {
1560
+ userText = text;
1561
+ assistantText = undefined;
1562
+ assistantFailure = undefined;
1563
+ }
1564
+ continue;
1565
+ }
1566
+ if (message.role !== "assistant") {
1567
+ continue;
1568
+ }
1569
+ const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage : "";
1570
+ const stopReason = typeof message.stopReason === "string" ? message.stopReason : "";
1571
+ if (errorMessage || stopReason === "error") {
1572
+ assistantText = undefined;
1573
+ assistantFailure = errorMessage
1574
+ ? classifyFailure(errorMessage)
1575
+ : { kind: "unknown", summary: "上游返回错误但未提供详情", raw: "stopReason=error" };
1576
+ continue;
1577
+ }
1578
+ const text = extractMessageText(message.content);
1579
+ if (text) {
1580
+ assistantText = text;
1581
+ assistantFailure = undefined;
1582
+ }
1583
+ }
1584
+ } catch {
1585
+ return { userText, assistantText, assistantFailure };
1586
+ } finally {
1587
+ lines?.close();
1588
+ input?.destroy();
1589
+ }
1590
+ return { userText, assistantText, assistantFailure };
1591
+ }
1592
+
1593
+ /**
1594
+ * 从 Pi message content 中提取纯文本片段, 忽略 thinking 等非对外内容。
1595
+ *
1596
+ * @param content message.content 原始值。
1597
+ * @returns 已清理的文本, 无文本时返回 undefined。
1598
+ */
1599
+ function extractMessageText(content: unknown): string | undefined {
1600
+ const raw = typeof content === "string"
1601
+ ? content
1602
+ : Array.isArray(content)
1603
+ ? content
1604
+ .filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string")
1605
+ .map((block) => (block as { text: string }).text)
1606
+ .join("\n")
1607
+ : "";
1608
+ const normalized = normalizeAssistantText(raw);
1609
+ return normalized || undefined;
1610
+ }
1611
+
1612
+ /**
1613
+ * 表示从 transcript 尾部提取出的最近一轮对话。
1614
+ */
1615
+ interface LatestTurn {
1616
+ userText?: string;
1617
+ assistantText?: string;
1618
+ assistantFailure?: TurnFailure;
1619
+ }
1620
+
1621
+ /**
1622
+ * 清理 assistant 文本中的终端控制字符, 保留换行和制表符格式.
1623
+ *
1624
+ * @param text transcript 中的 assistant 文本.
1625
+ * @returns 清理并去除首尾空白后的文本.
1626
+ */
1627
+ function normalizeAssistantText(text: string): string {
1628
+ return text
1629
+ .replace(/\r\n?/g, "\n")
1630
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
1631
+ .trim();
1632
+ }
1633
+
1634
+ /**
1635
+ * 将任意回复压到单条 iLink 消息能安全发送的字节预算内。
1636
+ *
1637
+ * 这是发往微信前的最后一道保险. iLink 只接受单 `text_item` 消息且 body
1638
+ * 总字节数有上限, 两者任一越界都会得到 `ret=-2` 并导致投递失败, 所以这
1639
+ * 里按 UTF-8 字节数精确截断, 而不是按字符数估算。
1640
+ *
1641
+ * @param reply 即将发送的回复正文。
1642
+ * @returns UTF-8 字节数在 {@link MAX_SINGLE_MESSAGE_BYTES} 以内的回复。
1643
+ */
1644
+ function truncateToSingleMessage(reply: string): string {
1645
+ if (Buffer.byteLength(reply, "utf8") <= MAX_SINGLE_MESSAGE_BYTES) {
1646
+ return reply;
1647
+ }
1648
+ const noticeBytes = Buffer.byteLength(TRUNCATION_NOTICE, "utf8");
1649
+ const budget = Math.max(0, MAX_SINGLE_MESSAGE_BYTES - noticeBytes - REQUEST_ENVELOPE_BYTES);
1650
+ return `${takeUtf8Prefix(reply, budget)}${TRUNCATION_NOTICE}`;
1651
+ }
1652
+
1653
+ /**
1654
+ * 按 UTF-8 字节预算截取字符串前缀, 不切断代理对与多字节字符。
1655
+ *
1656
+ * @param text 原始文本。
1657
+ * @param maxBytes 最大 UTF-8 字节数。
1658
+ * @returns 字节数不超过 maxBytes 的最长前缀。
1659
+ */
1660
+ function takeUtf8Prefix(text: string, maxBytes: number): string {
1661
+ let total = 0;
1662
+ let result = "";
1663
+ for (const character of text) {
1664
+ const bytes = Buffer.byteLength(character, "utf8");
1665
+ if (total + bytes > maxBytes) {
1666
+ break;
1667
+ }
1668
+ total += bytes;
1669
+ result += character;
1670
+ }
1671
+ return result;
1672
+ }
1673
+
1674
+ /**
1675
+ * 估算 `sendmessage` 请求中除正文外固定字段占用的字节数。
1676
+ *
1677
+ * 包括 JSON 结构、`context_token`、`recipientId` 与 `base_info` 等字段,
1678
+ * 实测空消息体约 430 字节, 这里取略大的值以保安全。
1679
+ */
1680
+ const REQUEST_ENVELOPE_BYTES = 600;
1681
+
1682
+ /**
1683
+ * 清理标题中的控制字符并折叠空白, 保证每个会话只占一行。
1684
+ *
1685
+ * @param title 原始标题或用户文本。
1686
+ * @returns 去除控制字符并折叠空白后的文本。
1687
+ */
1688
+ function normalizeSessionTitle(title: string): string {
1689
+ return title.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
1690
+ }
1691
+
1692
+ /**
1693
+ * 将会话标题限制为 32 个 Unicode code point, 超出部分以三个点省略。
1694
+ *
1695
+ * @param title 已清理标题。
1696
+ * @returns 长度限制内的标题。
1697
+ */
1698
+ function truncateSessionTitle(title: string): string {
1699
+ const characters = Array.from(title);
1700
+ if (characters.length <= SESSION_TITLE_LIMIT) {
1701
+ return title;
1702
+ }
1703
+ return `${characters.slice(0, SESSION_TITLE_LIMIT - 3).join("")}...`;
1704
+ }
1705
+
1706
+ /**
1707
+ * 将 markdown 表格单元格中的特殊字符转义, 避免内容破坏列结构。
1708
+ *
1709
+ * @param value 单元格原始内容。
1710
+ * @returns 单行且竖线已转义的内容。
1711
+ */
1712
+ function escapeMarkdownTableCell(value: string): string {
1713
+ return value.replace(/[|\r\n]+/g, " ").trim();
1714
+ }
1715
+
1716
+ /**
1717
+ * 将归一化失败信息格式化为简洁的人类可读说明。
1718
+ *
1719
+ * @param failure 已分类的 turn 失败。
1720
+ * @returns 含重置时间 (若有) 的说明。
1721
+ */
1722
+ function formatFailureSummary(failure: TurnFailure): string {
1723
+ return failure.resetAt
1724
+ ? `${failure.summary}, 重置时间 ${failure.resetAt}`
1725
+ : failure.summary;
1726
+ }
1727
+
1728
+ /**
1729
+ * 将失败消息正文压缩为单行预览, 避免提示占用过多屏幕。
1730
+ *
1731
+ * @param text 消息原文。
1732
+ * @returns 最多 24 个 Unicode code point 的单行预览。
1733
+ */
1734
+ function truncatePreview(text: string): string {
1735
+ const normalized = text.replace(/\s+/g, " ").trim();
1736
+ const characters = Array.from(normalized);
1737
+ if (characters.length <= 24) {
1738
+ return normalized;
1739
+ }
1740
+ return `${characters.slice(0, 24).join("")}...`;
1741
+ }
1742
+
1743
+ /**
1744
+ * 判断未知值是否为非数组对象。
1745
+ *
1746
+ * @param value 待检查的值。
1747
+ * @returns 值可安全读取字段时返回 true。
1748
+ */
1749
+ function isRecord(value: unknown): value is Record<string, unknown> {
1750
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1751
+ }
1752
+
1753
+ const GATEWAY_HELP_TEXT = [
1754
+ "**微信命令帮助**",
1755
+ "",
1756
+ "**会话命令**",
1757
+ "- `/new [--mode background|ui] [--project <别名>] [--name <名称>]`",
1758
+ "- `/sessions [--project <别名>] [--state active|saved|pending|all]`",
1759
+ "- `/resume <索引或名称>` 切换会话",
1760
+ "- `/last [索引或名称]` 只读查看最近一轮对话",
1761
+ "- `/stop [索引或名称]` 停止会话",
1762
+ "",
1763
+ "**项目命令**",
1764
+ "- `/projects` 列出已登记项目",
1765
+ "- `/projects add <别名> --name <名称> --path <绝对路径>`",
1766
+ "- `/projects remove <别名>`",
1767
+ "- `/projects default <别名>`",
1768
+ "",
1769
+ "**Hub 状态与队列**",
1770
+ "- `/status` 查看连接与当前会话状态",
1771
+ "- `/watch [--all]` 总览运行中与异常会话, `--all` 查看全部",
1772
+ "- `/retry <message-id> --confirm` 重新执行失败消息 (可能产生副作用)",
1773
+ "",
1774
+ "发送 `/help` 查看此帮助。",
1775
+ ].join("\n");
1776
+
1777
+ /**
1778
+ * 将 durable queue dispatch 结果规范化为 Gateway receive 结果。
1779
+ *
1780
+ * @param result queue dispatch 结果。
1781
+ * @returns Gateway 层结果。
1782
+ */
1783
+ function toReceiveResult(result: QueueDispatchResult): GatewayReceiveResult {
1784
+ return {
1785
+ messageId: result.item.messageId,
1786
+ state: result.item.state,
1787
+ duplicate: result.duplicate,
1788
+ ...(result.reply === undefined ? {} : { reply: result.reply }),
1789
+ };
1790
+ }