pi-wechat-session-hub 0.1.2 → 0.1.5
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.
- package/CHANGELOG.md +99 -1
- package/README.md +62 -17
- package/docs/decisions/0002-notification-ingress-context-token.md +69 -0
- package/docs/handoff-next-session.md +6 -4
- package/docs/implementation-spec.md +45 -27
- package/extensions/wechat-session-hub.ts +3 -0
- package/package.json +73 -72
- package/scripts/release-preflight.mjs +79 -27
- package/scripts/wx-notify.mjs +266 -0
- package/src/commands/wechat-notify-tool.ts +188 -0
- package/src/config/defaults.ts +13 -1
- package/src/config/types.ts +17 -0
- package/src/config/validation.ts +29 -0
- package/src/gateway/command-parser.ts +5 -0
- package/src/gateway/command-router.ts +181 -54
- package/src/gateway/gateway-runtime.ts +41 -16
- package/src/gateway/notification/context-token-store.ts +186 -0
- package/src/gateway/notification/notification-ingress-server.ts +494 -0
- package/src/gateway/notification/notification-service.ts +526 -0
- package/src/gateway/turn-health.ts +213 -6
- package/src/gateway/ui-worker-extension-bridge.ts +976 -1092
- package/src/gateway/ui-worker-ipc.ts +1406 -1517
- package/src/runtime/background-worker-manager.ts +628 -594
- package/src/runtime/gateway-worker-manager.ts +51 -47
- package/src/runtime/ui-worker-manager.ts +1157 -1216
|
@@ -16,13 +16,16 @@ import {
|
|
|
16
16
|
} from "./durable-message-queue.ts";
|
|
17
17
|
import { ManagerRegistry } from "../registry/manager-registry.ts";
|
|
18
18
|
import { GatewayLease } from "../registry/gateway-lease.ts";
|
|
19
|
-
import type { SessionIndexRecord, WorkerInstanceRecord } from "../registry/types.ts";
|
|
19
|
+
import type { SessionIndexRecord, WorkerInstanceRecord, WorkerMode } from "../registry/types.ts";
|
|
20
20
|
import { BackgroundWorkerManagerError } from "../runtime/background-worker-manager.ts";
|
|
21
21
|
import type { GatewayWorkerService } from "../runtime/gateway-worker-manager.ts";
|
|
22
22
|
import { UiWorkerManagerError } from "../runtime/ui-worker-manager.ts";
|
|
23
|
+
import type { NotificationService } from "./notification/notification-service.ts";
|
|
23
24
|
import {
|
|
24
25
|
evaluateHealth,
|
|
25
26
|
formatHealthState,
|
|
27
|
+
formatRelativeAge,
|
|
28
|
+
readLastUserQuestion,
|
|
26
29
|
readLatestFailure,
|
|
27
30
|
classifyFailure,
|
|
28
31
|
type SessionHealth,
|
|
@@ -98,6 +101,7 @@ export class GatewayCommandRouter {
|
|
|
98
101
|
private readonly lease: GatewayLease;
|
|
99
102
|
private readonly replySink?: GatewayReplySink;
|
|
100
103
|
private readonly processingIndicator?: GatewayProcessingIndicator;
|
|
104
|
+
private readonly notificationService?: NotificationService;
|
|
101
105
|
private readonly uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
|
|
102
106
|
|
|
103
107
|
/**
|
|
@@ -114,6 +118,7 @@ export class GatewayCommandRouter {
|
|
|
114
118
|
lease: GatewayLease;
|
|
115
119
|
replySink?: GatewayReplySink;
|
|
116
120
|
processingIndicator?: GatewayProcessingIndicator;
|
|
121
|
+
notificationService?: NotificationService;
|
|
117
122
|
uiModeCapability?: () => Promise<import("../gateway/windows-terminal-launcher.ts").WindowsTerminalCapability>;
|
|
118
123
|
}) {
|
|
119
124
|
this.configStore = options.configStore;
|
|
@@ -124,6 +129,7 @@ export class GatewayCommandRouter {
|
|
|
124
129
|
this.lease = options.lease;
|
|
125
130
|
this.replySink = options.replySink;
|
|
126
131
|
this.processingIndicator = options.processingIndicator;
|
|
132
|
+
this.notificationService = options.notificationService;
|
|
127
133
|
this.uiModeCapability = options.uiModeCapability;
|
|
128
134
|
this.queue.setSkippedNotifier((routeId, item) =>
|
|
129
135
|
this.notifySkippedItem(routeId, item),
|
|
@@ -231,6 +237,17 @@ export class GatewayCommandRouter {
|
|
|
231
237
|
await this.lease.assertOwned();
|
|
232
238
|
const { config } = await this.configStore.load();
|
|
233
239
|
this.assertAuthorized(message.senderId, config);
|
|
240
|
+
// 授权通过后立即捕获最新 context token, 供通知通道主动发送使用。
|
|
241
|
+
// best-effort: 捕获失败不影响正常消息处理。
|
|
242
|
+
if (message.replyContext) {
|
|
243
|
+
try {
|
|
244
|
+
await this.notificationService?.recordInboundContext(message.replyContext);
|
|
245
|
+
// 本次消息可能已续命: 有积压时异步补发, 不阻塞消息处理。
|
|
246
|
+
void this.notificationService?.replayBacklogIfFresh();
|
|
247
|
+
} catch {
|
|
248
|
+
// token 捕获失败只影响通知通道, 不阻断会话消息。
|
|
249
|
+
}
|
|
250
|
+
}
|
|
234
251
|
if (!message.messageId.trim() || !message.text.trim()) {
|
|
235
252
|
throw new GatewayCommandParseError("微信消息缺少 messageId 或正文, 已拒绝路由。");
|
|
236
253
|
}
|
|
@@ -263,6 +280,9 @@ export class GatewayCommandRouter {
|
|
|
263
280
|
message.replyContext,
|
|
264
281
|
);
|
|
265
282
|
}
|
|
283
|
+
if (command.kind === "renew") {
|
|
284
|
+
return this.renewNotificationChannel(routeId, message, config);
|
|
285
|
+
}
|
|
266
286
|
|
|
267
287
|
const enqueued = await this.queue.enqueue(
|
|
268
288
|
routeId,
|
|
@@ -321,6 +341,42 @@ export class GatewayCommandRouter {
|
|
|
321
341
|
};
|
|
322
342
|
}
|
|
323
343
|
|
|
344
|
+
/**
|
|
345
|
+
* 处理微信端 /renew 命令: 续命通知通道并补发积压, 不进 durable queue。
|
|
346
|
+
*
|
|
347
|
+
* /renew 零副作用, 不触发 Pi turn; 续命效果由入站 token 捕获自动完成。
|
|
348
|
+
*
|
|
349
|
+
* @param routeId 微信 route ID。
|
|
350
|
+
* @param message 原始入站消息。
|
|
351
|
+
* @param config 当前配置快照。
|
|
352
|
+
* @returns receive 结果, 状态固定为 completed。
|
|
353
|
+
*/
|
|
354
|
+
private async renewNotificationChannel(
|
|
355
|
+
routeId: string,
|
|
356
|
+
message: InboundGatewayMessage,
|
|
357
|
+
_config: ManagerConfiguration,
|
|
358
|
+
): Promise<GatewayReceiveResult> {
|
|
359
|
+
let reply: string;
|
|
360
|
+
if (!this.notificationService) {
|
|
361
|
+
reply = "通知通道未启用; 当前 Hub 版本不支持 /renew。";
|
|
362
|
+
} else {
|
|
363
|
+
try {
|
|
364
|
+
reply = await this.notificationService.renew(message.replyContext);
|
|
365
|
+
} catch {
|
|
366
|
+
reply = "续命失败, 请稍后重试。";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (this.replySink) {
|
|
370
|
+
await this.replySink(routeId, message.messageId, reply, message.replyContext);
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
messageId: message.messageId,
|
|
374
|
+
state: "completed",
|
|
375
|
+
duplicate: false,
|
|
376
|
+
...(this.replySink ? {} : { reply }),
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
324
380
|
/**
|
|
325
381
|
* 对失败或中断的入站消息执行显式重试; retry control command 本身不重放。
|
|
326
382
|
*
|
|
@@ -518,9 +574,9 @@ export class GatewayCommandRouter {
|
|
|
518
574
|
const session = await this.workerManager.startNew(alias, name, requestedMode);
|
|
519
575
|
const newSnapshot = await this.registry.readSnapshot();
|
|
520
576
|
const indexedSession = newSnapshot.sessions[session.sessionId];
|
|
521
|
-
const owner =
|
|
522
|
-
|
|
523
|
-
|
|
577
|
+
const owner = this.workerManager.getAvailableOwner
|
|
578
|
+
? await this.workerManager.getAvailableOwner(session.sessionId)
|
|
579
|
+
: selectRouteOwner(newSnapshot, session.sessionId, indexedSession?.mode ?? session.mode);
|
|
524
580
|
if (!owner) {
|
|
525
581
|
await this.workerManager.stop(session.sessionId).catch(() => undefined);
|
|
526
582
|
throw new BackgroundWorkerManagerError(
|
|
@@ -641,10 +697,12 @@ export class GatewayCommandRouter {
|
|
|
641
697
|
/**
|
|
642
698
|
* 展示所有受管会话的运行与错误总览。
|
|
643
699
|
*
|
|
644
|
-
*
|
|
645
|
-
*
|
|
700
|
+
* 默认只显示「打开着」的会话(有 worker 实例)与异常会话; 纯历史会话需要
|
|
701
|
+
* `--all` 才展开。这样总览才对应「当前能操作的会话」, 而不会被上百个
|
|
702
|
+
* 早已关闭的历史会话淹没。
|
|
703
|
+
* 失败原因与最后提问都直接从 transcript 读取, 不触发模型请求。
|
|
646
704
|
*
|
|
647
|
-
* @param all
|
|
705
|
+
* @param all 是否包含全部历史会话。
|
|
648
706
|
* @param config 当前配置快照。
|
|
649
707
|
* @returns markdown 总览表格。
|
|
650
708
|
*/
|
|
@@ -664,68 +722,81 @@ export class GatewayCommandRouter {
|
|
|
664
722
|
return "尚无已登记会话。";
|
|
665
723
|
}
|
|
666
724
|
|
|
667
|
-
const
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
state
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
725
|
+
const nowMs = Date.now();
|
|
726
|
+
const healthRows: Array<SessionHealth & { title: string; projectName: string; question?: string }> =
|
|
727
|
+
await Promise.all(
|
|
728
|
+
sessions.map(async (session) => {
|
|
729
|
+
const worker = workersBySession.get(session.sessionId);
|
|
730
|
+
const failure = await readLatestFailure(session.sessionFile);
|
|
731
|
+
const { state } = evaluateHealth(session, worker, failure, nowMs);
|
|
732
|
+
const title = await resolveSessionTitle(session);
|
|
733
|
+
const projectName = Object.hasOwn(config.projects, session.projectAlias)
|
|
734
|
+
? config.projects[session.projectAlias].displayName
|
|
735
|
+
: session.projectAlias;
|
|
736
|
+
// 只有会被展示的行才读最后提问, 避免为几百个历史会话做无意义 IO。
|
|
737
|
+
const shown = all || worker !== undefined || state === "error" ||
|
|
738
|
+
state === "disconnected" || state === "starting" || state === "stopping";
|
|
739
|
+
const question = shown ? await readLastUserQuestion(session.sessionFile) : undefined;
|
|
740
|
+
return {
|
|
741
|
+
session,
|
|
742
|
+
...(worker ? { worker } : {}),
|
|
743
|
+
state,
|
|
744
|
+
...(failure ? { failure } : {}),
|
|
745
|
+
title,
|
|
746
|
+
projectName,
|
|
747
|
+
...(question ? { question } : {}),
|
|
748
|
+
};
|
|
749
|
+
}),
|
|
750
|
+
);
|
|
686
751
|
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
const
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
const
|
|
752
|
+
// 打开着 = registry 中还有 worker 实例; 这是区分「当前可操作会话」与历史记录的唯一可靠依据。
|
|
753
|
+
const isOpen = (row: SessionHealth): boolean => row.worker !== undefined;
|
|
754
|
+
const isAbnormal = (row: SessionHealth): boolean =>
|
|
755
|
+
row.state === "error" || row.state === "disconnected" || row.state === "stopping";
|
|
756
|
+
|
|
757
|
+
const visibleRows = all ? healthRows : healthRows.filter((row) => isOpen(row) || isAbnormal(row));
|
|
758
|
+
const openRows = visibleRows.filter(isOpen);
|
|
759
|
+
const runningCount = openRows.filter((row) => row.state === "running").length;
|
|
760
|
+
const startingCount = openRows.filter((row) => row.state === "starting").length;
|
|
761
|
+
const stoppingCount = openRows.filter((row) => row.state === "stopping").length;
|
|
762
|
+
const idleCount = openRows.filter((row) => row.state === "idle") .length;
|
|
763
|
+
const errorCount = visibleRows.filter((row) => row.state === "error" || row.state === "disconnected").length;
|
|
764
|
+
|
|
765
|
+
const scope = all
|
|
766
|
+
? `${healthRows.length} 个会话`
|
|
767
|
+
: `打开 ${openRows.length} 个(共 ${healthRows.length})`;
|
|
693
768
|
const summary = [
|
|
694
|
-
`**总览** · ${
|
|
695
|
-
`${runningCount}
|
|
769
|
+
`**总览** · ${scope}`,
|
|
770
|
+
...(runningCount ? [`${runningCount} 运行中`] : []),
|
|
696
771
|
...(startingCount ? [`${startingCount} 启动中`] : []),
|
|
697
|
-
`${
|
|
698
|
-
`${idleCount}
|
|
772
|
+
...(stoppingCount ? [`${stoppingCount} 停止中`] : []),
|
|
773
|
+
...(idleCount ? [`${idleCount} 空闲`] : []),
|
|
774
|
+
...(errorCount ? [`🔴 ${errorCount} 异常`] : []),
|
|
699
775
|
].join(" · ");
|
|
700
776
|
|
|
701
|
-
const visibleRows = all
|
|
702
|
-
? healthRows
|
|
703
|
-
: healthRows.filter((row) => row.state !== "idle");
|
|
704
777
|
if (visibleRows.length === 0) {
|
|
705
778
|
return [
|
|
706
779
|
summary,
|
|
707
|
-
"
|
|
780
|
+
"当前没有打开着或异常的会话。",
|
|
708
781
|
"发送 `/watch --all` 查看全部会话。",
|
|
709
782
|
].join("\n\n");
|
|
710
783
|
}
|
|
711
784
|
|
|
712
785
|
const tableRows = visibleRows.map((row) => {
|
|
713
786
|
const index = String(row.session.publicIndex ?? "?");
|
|
714
|
-
const
|
|
787
|
+
const question = escapeMarkdownTableCell(truncateMiddle(row.question ?? "(暂无提问)", 22));
|
|
715
788
|
const project = escapeMarkdownTableCell(row.projectName);
|
|
716
789
|
const state = formatHealthState(row.state);
|
|
717
|
-
const
|
|
718
|
-
return `| ${index} | ${
|
|
790
|
+
const activity = formatRelativeAge(row.session.lastActivityAt, nowMs);
|
|
791
|
+
return `| ${index} | ${question} | ${project} | ${state} | ${activity} |`;
|
|
719
792
|
});
|
|
720
793
|
const table = [
|
|
721
|
-
"| 索引 |
|
|
794
|
+
"| 索引 | 最后提问 | 项目 | 状态 | 活动 |",
|
|
722
795
|
"| --- | --- | --- | --- | --- |",
|
|
723
796
|
...tableRows,
|
|
724
797
|
].join("\n");
|
|
725
798
|
|
|
726
|
-
const attentionRows = visibleRows.filter(
|
|
727
|
-
row.state === "error" || row.state === "disconnected" || row.state === "stopping",
|
|
728
|
-
);
|
|
799
|
+
const attentionRows = visibleRows.filter(isAbnormal);
|
|
729
800
|
const attention = attentionRows.length === 0
|
|
730
801
|
? []
|
|
731
802
|
: [
|
|
@@ -737,7 +808,10 @@ export class GatewayCommandRouter {
|
|
|
737
808
|
const recovery = !row.worker || row.worker.state === "stale"
|
|
738
809
|
? `; 可发送 \`/resume ${index}\` 重连`
|
|
739
810
|
: "";
|
|
740
|
-
|
|
811
|
+
const when = row.failure.detectedAt
|
|
812
|
+
? `(${formatLocalMinute(row.failure.detectedAt)})`
|
|
813
|
+
: "";
|
|
814
|
+
return `- **${index} ${title}**:${formatFailureSummary(row.failure)}${when}${recovery}`;
|
|
741
815
|
}
|
|
742
816
|
if (row.state === "disconnected") {
|
|
743
817
|
const failureNote = row.failure ? `; ${formatFailureSummary(row.failure)}` : "";
|
|
@@ -747,7 +821,11 @@ export class GatewayCommandRouter {
|
|
|
747
821
|
}),
|
|
748
822
|
];
|
|
749
823
|
|
|
750
|
-
|
|
824
|
+
const footnotes = all
|
|
825
|
+
? []
|
|
826
|
+
: [`共 ${healthRows.length} 个会话,发 \`/watch --all\` 查看全部。`];
|
|
827
|
+
|
|
828
|
+
return [summary, table, ...attention, ...footnotes].join("\n\n");
|
|
751
829
|
}
|
|
752
830
|
|
|
753
831
|
/**
|
|
@@ -765,9 +843,9 @@ export class GatewayCommandRouter {
|
|
|
765
843
|
const previousRoute = (await this.registry.readSnapshot()).routes[routeId];
|
|
766
844
|
await this.workerManager.resume(session.sessionId);
|
|
767
845
|
const snapshot = await this.registry.readSnapshot();
|
|
768
|
-
const owner =
|
|
769
|
-
|
|
770
|
-
|
|
846
|
+
const owner = this.workerManager.getAvailableOwner
|
|
847
|
+
? await this.workerManager.getAvailableOwner(session.sessionId)
|
|
848
|
+
: selectRouteOwner(snapshot, session.sessionId, snapshot.sessions[session.sessionId]?.mode ?? session.mode);
|
|
771
849
|
if (!owner) {
|
|
772
850
|
throw new BackgroundWorkerManagerError(
|
|
773
851
|
"worker_not_found",
|
|
@@ -912,7 +990,10 @@ export class GatewayCommandRouter {
|
|
|
912
990
|
if (!session) {
|
|
913
991
|
return "当前 route 没有活跃 session; 可使用 /sessions 查看列表。";
|
|
914
992
|
}
|
|
915
|
-
|
|
993
|
+
const routeOwner = binding?.sessionId === session.sessionId
|
|
994
|
+
? binding.workerInstanceId
|
|
995
|
+
: selectRouteOwner(snapshot, session.sessionId, session.mode)?.instanceId;
|
|
996
|
+
await this.workerManager.stop(session.sessionId, false, routeOwner);
|
|
916
997
|
if (binding?.sessionId === session.sessionId) {
|
|
917
998
|
await this.registry.setRoute(routeId, null);
|
|
918
999
|
}
|
|
@@ -949,7 +1030,7 @@ export class GatewayCommandRouter {
|
|
|
949
1030
|
if (!worker || worker.state === "stale" || worker.state === "stopping") {
|
|
950
1031
|
return "当前 route 没有可用的 Pi worker; 请使用 /resume <索引> 重连。";
|
|
951
1032
|
}
|
|
952
|
-
return this.workerManager.prompt(binding.sessionId, text);
|
|
1033
|
+
return this.workerManager.prompt(binding.sessionId, text, binding.workerInstanceId);
|
|
953
1034
|
}
|
|
954
1035
|
|
|
955
1036
|
/**
|
|
@@ -1110,6 +1191,10 @@ export class GatewayCommandRouter {
|
|
|
1110
1191
|
return GATEWAY_HELP_TEXT;
|
|
1111
1192
|
case "status":
|
|
1112
1193
|
return await this.formatStatus(routeId, config);
|
|
1194
|
+
case "renew":
|
|
1195
|
+
// /renew 在入站路径已直接处理, 到达这里说明走了 queue 兼容路径。
|
|
1196
|
+
return "通知通道已续命。";
|
|
1197
|
+
case "projects":
|
|
1113
1198
|
case "projects":
|
|
1114
1199
|
return await this.handleProjects(command.arguments);
|
|
1115
1200
|
case "new":
|
|
@@ -1417,6 +1502,24 @@ function truncateTail(text: string, limit: number): { text: string; truncated: b
|
|
|
1417
1502
|
};
|
|
1418
1503
|
}
|
|
1419
1504
|
|
|
1505
|
+
/**
|
|
1506
|
+
* 按 Unicode code point 截断文本并在末尾加省略号。
|
|
1507
|
+
*
|
|
1508
|
+
* 用于总览表格中的「最后提问」列: 手机端表格宽度有限, 过长内容会把表格
|
|
1509
|
+
* 撑到需要横向滚动。用 code point 切割避免拆坏 emoji。
|
|
1510
|
+
*
|
|
1511
|
+
* @param text 原始文本。
|
|
1512
|
+
* @param limit 最大 code point 数, 超出时末尾追加省略号。
|
|
1513
|
+
* @returns 可安全放进表格单元格的短文本。
|
|
1514
|
+
*/
|
|
1515
|
+
function truncateMiddle(text: string, limit: number): string {
|
|
1516
|
+
const characters = Array.from(text);
|
|
1517
|
+
if (characters.length <= limit) {
|
|
1518
|
+
return text;
|
|
1519
|
+
}
|
|
1520
|
+
return `${characters.slice(0, limit).join("")}…`;
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1420
1523
|
/**
|
|
1421
1524
|
* 从 Pi transcript 尾部按需扩展窗口, 读取最近一轮 user 与 assistant 文本。
|
|
1422
1525
|
*
|
|
@@ -1740,6 +1843,27 @@ function truncatePreview(text: string): string {
|
|
|
1740
1843
|
return `${characters.slice(0, 24).join("")}...`;
|
|
1741
1844
|
}
|
|
1742
1845
|
|
|
1846
|
+
/**
|
|
1847
|
+
* 从同一会话的多个 Pi runtime 中选择符合当前 session mode 的 route 目标。
|
|
1848
|
+
*
|
|
1849
|
+
* @param snapshot registry 快照。
|
|
1850
|
+
* @param sessionId Pi session ID。
|
|
1851
|
+
* @param preferredMode 当前 session 记录的首选模式。
|
|
1852
|
+
* @returns 首选模式的最新 runtime, 不存在时回退到最新活跃 runtime。
|
|
1853
|
+
*/
|
|
1854
|
+
function selectRouteOwner(
|
|
1855
|
+
snapshot: Awaited<ReturnType<ManagerRegistry["readSnapshot"]>>,
|
|
1856
|
+
sessionId: string,
|
|
1857
|
+
preferredMode?: WorkerMode,
|
|
1858
|
+
): WorkerInstanceRecord | undefined {
|
|
1859
|
+
const owners = [...Object.values(snapshot.instances)].reverse().filter((instance) =>
|
|
1860
|
+
instance.sessionId === sessionId &&
|
|
1861
|
+
instance.state !== "stale" &&
|
|
1862
|
+
instance.state !== "stopping",
|
|
1863
|
+
);
|
|
1864
|
+
return (preferredMode ? owners.find((instance) => instance.mode === preferredMode) : undefined) ?? owners[0];
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1743
1867
|
/**
|
|
1744
1868
|
* 判断未知值是否为非数组对象。
|
|
1745
1869
|
*
|
|
@@ -1771,6 +1895,9 @@ const GATEWAY_HELP_TEXT = [
|
|
|
1771
1895
|
"- `/watch [--all]` 总览运行中与异常会话, `--all` 查看全部",
|
|
1772
1896
|
"- `/retry <message-id> --confirm` 重新执行失败消息 (可能产生副作用)",
|
|
1773
1897
|
"",
|
|
1898
|
+
"**通知通道**",
|
|
1899
|
+
"- `/renew` 续命通知通道并补发积压通知 (零副作用, 不触发会话)",
|
|
1900
|
+
"",
|
|
1774
1901
|
"发送 `/help` 查看此帮助。",
|
|
1775
1902
|
].join("\n");
|
|
1776
1903
|
|
|
@@ -16,6 +16,9 @@ import { GatewayLease } from "../registry/gateway-lease.ts";
|
|
|
16
16
|
import { ManagerRegistry } from "../registry/manager-registry.ts";
|
|
17
17
|
import type { GatewayStatusRecord, RouteRecord, SessionIndexRecord, WorkerInstanceRecord } from "../registry/types.ts";
|
|
18
18
|
import { isProcessAlive } from "../system/process-liveness.ts";
|
|
19
|
+
import { ContextTokenStore } from "./notification/context-token-store.ts";
|
|
20
|
+
import { NotificationService } from "./notification/notification-service.ts";
|
|
21
|
+
import { NotificationIngressServer } from "./notification/notification-ingress-server.ts";
|
|
19
22
|
import { BackgroundWorkerManager } from "../runtime/background-worker-manager.ts";
|
|
20
23
|
import { GatewayWorkerManager } from "../runtime/gateway-worker-manager.ts";
|
|
21
24
|
import { UiWorkerManager } from "../runtime/ui-worker-manager.ts";
|
|
@@ -29,7 +32,7 @@ import { WindowsTerminalLauncher } from "./windows-terminal-launcher.ts";
|
|
|
29
32
|
export type GatewayRuntimeState = "starting" | "online" | "auth_required" | "stopping" | "stopped" | "lease_lost";
|
|
30
33
|
|
|
31
34
|
/**
|
|
32
|
-
* 表示 Gateway runtime
|
|
35
|
+
* 表示 Gateway runtime 因配置、后台 worker 生命周期、registry 或凭证隔离问题无法安全启动或停止。
|
|
33
36
|
*/
|
|
34
37
|
export class GatewayRuntimeError extends Error {
|
|
35
38
|
/**
|
|
@@ -76,6 +79,8 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
76
79
|
private readonly uiIpcServer: UiWorkerIpcServer,
|
|
77
80
|
private readonly router: GatewayCommandRouter,
|
|
78
81
|
private readonly channel: IlinkChannelAdapter,
|
|
82
|
+
private readonly notificationService?: NotificationService,
|
|
83
|
+
private readonly notificationIngress?: NotificationIngressServer,
|
|
79
84
|
) {
|
|
80
85
|
super();
|
|
81
86
|
this.channel.on("session_expired", () => {
|
|
@@ -183,6 +188,15 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
183
188
|
...(options.fetcher ? { fetcher: options.fetcher } : {}),
|
|
184
189
|
});
|
|
185
190
|
const typingIndicator = new IlinkTypingIndicator(api);
|
|
191
|
+
const contextTokenStore = new ContextTokenStore(dataDirectory);
|
|
192
|
+
const notificationService = new NotificationService(
|
|
193
|
+
api,
|
|
194
|
+
contextTokenStore,
|
|
195
|
+
options.configStore,
|
|
196
|
+
join(dataDirectory, "notification-backlog.json"),
|
|
197
|
+
);
|
|
198
|
+
await notificationService.restoreBacklog().catch(() => undefined);
|
|
199
|
+
const notificationIngress = new NotificationIngressServer(dataDirectory, notificationService);
|
|
186
200
|
channel = new IlinkChannelAdapter(
|
|
187
201
|
api,
|
|
188
202
|
new IlinkCursorStore(join(dataDirectory, "ilink-sync.json"), lease),
|
|
@@ -196,6 +210,7 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
196
210
|
queue,
|
|
197
211
|
lease,
|
|
198
212
|
processingIndicator: typingIndicator,
|
|
213
|
+
notificationService,
|
|
199
214
|
uiModeCapability: () => uiWorkerManager!.describeUiModeCapability(),
|
|
200
215
|
replySink: (routeId, messageId, reply, replyContext) =>
|
|
201
216
|
channel!.sendReply(routeId, messageId, reply, replyContext),
|
|
@@ -210,6 +225,8 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
210
225
|
uiIpcServer,
|
|
211
226
|
router,
|
|
212
227
|
channel,
|
|
228
|
+
notificationService,
|
|
229
|
+
notificationIngress,
|
|
213
230
|
);
|
|
214
231
|
await runtime.initialize(options.onControlReady);
|
|
215
232
|
return runtime;
|
|
@@ -248,7 +265,7 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
248
265
|
}
|
|
249
266
|
throw new GatewayRuntimeError(
|
|
250
267
|
"worker_shutdown_failed",
|
|
251
|
-
"Gateway 初始化失败且后台资源未能全部停止;
|
|
268
|
+
"Gateway 初始化失败且后台资源未能全部停止; 为避免第二个 Gateway 同时接管 route/poller, manager.lock 已保留。",
|
|
252
269
|
);
|
|
253
270
|
}
|
|
254
271
|
await registry?.setGateway(null).catch(() => undefined);
|
|
@@ -309,6 +326,10 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
309
326
|
): Promise<void> {
|
|
310
327
|
await this.registry.setGateway(this.toGatewayRecord("starting"));
|
|
311
328
|
await this.uiWorkerManager.listen();
|
|
329
|
+
// 通知入口随 Gateway 生命周期启停; 失败不阻断 Hub 主体服务。
|
|
330
|
+
if (this.notificationIngress) {
|
|
331
|
+
await this.notificationIngress.listen().catch(() => undefined);
|
|
332
|
+
}
|
|
312
333
|
await onControlReady?.(this.lease, this.registry);
|
|
313
334
|
await this.recoverRoutes();
|
|
314
335
|
await this.channel.start((message) => this.router.acceptInbound(message));
|
|
@@ -317,6 +338,8 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
317
338
|
}
|
|
318
339
|
this.heartbeatTimer = setInterval(() => {
|
|
319
340
|
void this.refreshHeartbeat();
|
|
341
|
+
// 续命提醒: 距 token 过期不足 4 小时时 best-effort 提醒一次。
|
|
342
|
+
void this.notificationService?.maybeSendRenewalReminder().catch(() => undefined);
|
|
320
343
|
}, this.config.runtime.heartbeatIntervalMs);
|
|
321
344
|
this.heartbeatTimer.unref();
|
|
322
345
|
}
|
|
@@ -359,7 +382,7 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
359
382
|
} else {
|
|
360
383
|
throw new GatewayRuntimeError(
|
|
361
384
|
"live_worker_detected",
|
|
362
|
-
|
|
385
|
+
`检测到仍存活的 Pi RPC worker PID ${instance.pid} (session ${instance.sessionId}); 无法确认旧后台 worker 已退出, Gateway 未启动以避免重复后台 worker。`,
|
|
363
386
|
);
|
|
364
387
|
}
|
|
365
388
|
}
|
|
@@ -420,17 +443,19 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
420
443
|
`route ${routeId} 与 session registry 不一致; 保留绑定并拒绝启动。`,
|
|
421
444
|
);
|
|
422
445
|
}
|
|
423
|
-
const
|
|
424
|
-
const ownerIsActive =
|
|
425
|
-
owner &&
|
|
426
|
-
owner.sessionId === route.sessionId &&
|
|
427
|
-
owner.state !== "stale" &&
|
|
428
|
-
owner.state !== "stopping" &&
|
|
429
|
-
this.gatewayWorkerManager.hasAvailableOwner(owner),
|
|
430
|
-
);
|
|
446
|
+
const routeOwner = await this.gatewayWorkerManager.getAvailableOwner(route.sessionId, route.workerInstanceId);
|
|
447
|
+
const ownerIsActive = routeOwner !== undefined;
|
|
431
448
|
const sessionFileExists = await isPersistedSessionFile(session.sessionFile);
|
|
432
|
-
return { routeId, route, session, ownerIsActive, sessionFileExists };
|
|
449
|
+
return { routeId, route, session, ownerIsActive, routeOwner, sessionFileExists };
|
|
433
450
|
}));
|
|
451
|
+
await Promise.all(routeAnalyses.filter(({ route, routeOwner }) =>
|
|
452
|
+
routeOwner !== undefined && route.workerInstanceId !== routeOwner.instanceId,
|
|
453
|
+
).map(({ routeId, route, routeOwner }) => this.registry.setRoute(routeId, {
|
|
454
|
+
...route,
|
|
455
|
+
workerInstanceId: routeOwner!.instanceId,
|
|
456
|
+
generation: route.generation + 1,
|
|
457
|
+
updatedAt: new Date().toISOString(),
|
|
458
|
+
})));
|
|
434
459
|
|
|
435
460
|
const restorableRoutes = routeAnalyses.filter(({ session, ownerIsActive, sessionFileExists }) =>
|
|
436
461
|
!ownerIsActive &&
|
|
@@ -501,10 +526,7 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
501
526
|
await this.registry.upsertSession({ ...session, state: "saved" });
|
|
502
527
|
}
|
|
503
528
|
const resumed = await this.gatewayWorkerManager.resume(session.sessionId, session.mode);
|
|
504
|
-
const
|
|
505
|
-
const owner = Object.values(afterResume.instances).find((instance) =>
|
|
506
|
-
instance.sessionId === resumed.sessionId,
|
|
507
|
-
);
|
|
529
|
+
const owner = await this.gatewayWorkerManager.getAvailableOwner(resumed.sessionId);
|
|
508
530
|
if (!owner) {
|
|
509
531
|
throw new GatewayRuntimeError(
|
|
510
532
|
"registry_inconsistent",
|
|
@@ -540,6 +562,9 @@ export class GatewayRuntime extends EventEmitter {
|
|
|
540
562
|
statusWriteFailed = true;
|
|
541
563
|
}
|
|
542
564
|
await this.channel.stop();
|
|
565
|
+
if (this.notificationIngress) {
|
|
566
|
+
await this.notificationIngress.close().catch(() => undefined);
|
|
567
|
+
}
|
|
543
568
|
await this.queue.waitForIdle();
|
|
544
569
|
await this.uiWorkerManager.detachGateway();
|
|
545
570
|
try {
|