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.
@@ -0,0 +1,526 @@
1
+ import type { ManagerConfiguration } from "../../config/types.ts";
2
+ import type { IlinkReplyContext } from "../channel-types.ts";
3
+ import { IlinkApiClient } from "../wechat-ilink/api-client.ts";
4
+ import { readFile, rename, unlink, open } from "node:fs/promises";
5
+ import { mkdir } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import {
8
+ ContextTokenStore,
9
+ ContextTokenStoreError,
10
+ hashNotificationContent,
11
+ isNotificationTextValid,
12
+ type ContextTokenRecord,
13
+ } from "./context-token-store.ts";
14
+
15
+ /**
16
+ * 微信平台 context_token 约 24 小时过期, 发送前保留 4 小时安全余量。
17
+ */
18
+ export const CONTEXT_TOKEN_FRESHNESS_MS = 20 * 60 * 60 * 1000;
19
+
20
+ /**
21
+ * token 完全过期阈值, 与微信平台实测限制一致。
22
+ */
23
+ export const CONTEXT_TOKEN_HARD_EXPIRY_MS = 24 * 60 * 60 * 1000;
24
+
25
+ /**
26
+ * 续命提醒的重复间隔: 一个过期周期内最多提醒一次。
27
+ */
28
+ export const RENEWAL_REMINDER_INTERVAL_MS = 12 * 60 * 60 * 1000;
29
+
30
+ /**
31
+ * 续命提醒的提前量: 距离过期不足 4 小时时开始提醒。
32
+ */
33
+ export const RENEWAL_REMINDER_LEAD_MS = 4 * 60 * 60 * 1000;
34
+
35
+ /**
36
+ * 积压补发时单次最多补发的条数, 防止微信侧风控。
37
+ */
38
+ export const MAX_BACKLOG_REPLAY_COUNT = 10;
39
+
40
+ /**
41
+ * 积压通知的最大保留条数, 超出后丢弃最旧的。
42
+ */
43
+ export const MAX_BACKLOG_ITEMS = 100;
44
+
45
+ /**
46
+ * 积压通知落盘文件名, 位于 manager 数据目录 (ACL 保护)。
47
+ */
48
+ const BACKLOG_FILE_NAME = "notification-backlog.json";
49
+
50
+ /**
51
+ * 续命提醒的固定正文。
52
+ */
53
+ const RENEWAL_REMINDER_TEXT = [
54
+ "🔔 **通知通道快休眠了**",
55
+ "",
56
+ "微信要求 24 小时内有过对话 Bot 才能主动推送。回复 **/renew** 续命, 否则后续通知会按策略积压或丢弃。",
57
+ ].join("\n");
58
+
59
+ /**
60
+ * 通知发送失败原因。
61
+ */
62
+ export type NotificationFailureCode =
63
+ | "notify_no_context"
64
+ | "notify_stale"
65
+ | "notify_deliver_failed"
66
+ | "notify_text_invalid"
67
+ | "notify_store_error";
68
+
69
+ /**
70
+ * 通知发送结果。
71
+ */
72
+ export type NotificationSendResult =
73
+ | { kind: "sent"; clientId: string }
74
+ | { kind: "queued"; position: number }
75
+ | { kind: "dropped"; code: "notify_stale" | "notify_no_context" }
76
+ | { kind: "failed"; code: NotificationFailureCode };
77
+
78
+ /**
79
+ * 一条积压中的通知。
80
+ */
81
+ export interface BackloggedNotification {
82
+ title?: string;
83
+ text: string;
84
+ source?: string;
85
+ enqueuedAt: string;
86
+ }
87
+
88
+ /**
89
+ * ConfigurationStore 的最小结构, 便于测试注入。
90
+ */
91
+ export interface NotificationConfigStore {
92
+ load(): Promise<{ config: ManagerConfiguration }>;
93
+ }
94
+
95
+ /**
96
+ * 把通知直接投递到微信, 不经过会话队列与模型。
97
+ *
98
+ * 复用入站消息捕获的 context_token; token 过期时按配置积压或丢弃,
99
+ * 用户 /renew 续命后自动补发。所有正文末尾都带"勿直接回复"提示。
100
+ */
101
+ export class NotificationService {
102
+ private backlog: BackloggedNotification[] = [];
103
+ private lastRenewalReminderAt?: number;
104
+ private replayTask?: Promise<number>;
105
+
106
+ /**
107
+ * 创建通知服务。
108
+ *
109
+ * @param api iLink API client。
110
+ * @param tokenStore context token 存储。
111
+ * @param configStore 配置存储, 读取 overflowPolicy。
112
+ */
113
+ constructor(
114
+ private readonly api: IlinkApiClient,
115
+ private readonly tokenStore: ContextTokenStore,
116
+ private readonly configStore: NotificationConfigStore,
117
+ private readonly backlogFilePath?: string,
118
+ ) {}
119
+
120
+ /**
121
+ * 返回当前积压的通知条数 (内存缓存, 启动时从磁盘恢复)。
122
+ *
123
+ * @returns 积压条数。
124
+ */
125
+ get backlogCount(): number {
126
+ return this.backlog.length;
127
+ }
128
+
129
+ /**
130
+ * 返回积压通知的只读副本, 供 /status 与测试使用。
131
+ *
132
+ * @returns 积压通知数组。
133
+ */
134
+ getBacklog(): BackloggedNotification[] {
135
+ return [...this.backlog];
136
+ }
137
+
138
+ /**
139
+ * 从磁盘恢复积压通知; daemon 启动时调用一次。
140
+ *
141
+ * @returns 无返回值。
142
+ */
143
+ async restoreBacklog(): Promise<void> {
144
+ if (!this.backlogFilePath) {
145
+ return;
146
+ }
147
+ try {
148
+ const contents = await readFile(this.backlogFilePath, "utf8");
149
+ const parsed: unknown = JSON.parse(contents);
150
+ if (
151
+ typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ||
152
+ !Array.isArray((parsed as { items?: unknown }).items)
153
+ ) {
154
+ return;
155
+ }
156
+ const items = (parsed as { items: unknown[] }).items;
157
+ const restored: BackloggedNotification[] = [];
158
+ for (const item of items) {
159
+ if (typeof item !== "object" || item === null) {
160
+ continue;
161
+ }
162
+ const candidate = item as Record<string, unknown>;
163
+ if (typeof candidate.text !== "string" || typeof candidate.enqueuedAt !== "string") {
164
+ continue;
165
+ }
166
+ restored.push({
167
+ ...(typeof candidate.title === "string" ? { title: candidate.title } : {}),
168
+ text: candidate.text,
169
+ ...(typeof candidate.source === "string" ? { source: candidate.source } : {}),
170
+ enqueuedAt: candidate.enqueuedAt,
171
+ });
172
+ }
173
+ this.backlog = restored.slice(-MAX_BACKLOG_ITEMS);
174
+ } catch {
175
+ // 文件不存在或损坏时视为空积压; 积压丢失不阻断 Hub 服务。
176
+ }
177
+ }
178
+
179
+ /**
180
+ * 将积压通知原子写入磁盘; 写入失败只影响持久性, 不影响本次内存操作。
181
+ *
182
+ * @returns 无返回值。
183
+ */
184
+ private async persistBacklog(): Promise<void> {
185
+ if (!this.backlogFilePath) {
186
+ return;
187
+ }
188
+ const payload = { schemaVersion: 1, items: this.backlog };
189
+ try {
190
+ await mkdir(dirname(this.backlogFilePath), { recursive: true });
191
+ const temporaryPath = `${this.backlogFilePath}.${process.pid}.tmp`;
192
+ const handle = await open(temporaryPath, "wx", 0o600);
193
+ try {
194
+ await handle.writeFile(JSON.stringify(payload, null, 2), "utf8");
195
+ await handle.sync();
196
+ await handle.close();
197
+ await rename(temporaryPath, this.backlogFilePath);
198
+ } catch (error) {
199
+ await handle.close().catch(() => undefined);
200
+ await unlink(temporaryPath).catch(() => undefined);
201
+ throw error;
202
+ }
203
+ } catch {
204
+ // 落盘失败不阻断内存操作; 下次积压变更时重试。
205
+ }
206
+ }
207
+
208
+ /**
209
+ * 发送一条系统通知到授权用户的微信。
210
+ *
211
+ * @param options 标题、正文与调用方标识。
212
+ * @returns 发送结果; 不可送达时按 overflowPolicy 积压或丢弃。
213
+ */
214
+ async notify(options: { title?: string; text: string; source?: string }): Promise<NotificationSendResult> {
215
+ const body = composeNotificationBody(options);
216
+ if (!isNotificationTextValid(body)) {
217
+ return { kind: "failed", code: "notify_text_invalid" };
218
+ }
219
+ const record = await this.loadTokenRecord();
220
+ if (!record) {
221
+ return this.handleUnavailable(options);
222
+ }
223
+ if (!isTokenFresh(record.receivedAt)) {
224
+ return this.handleStale(options);
225
+ }
226
+ try {
227
+ return await this.deliver(record, body);
228
+ } catch {
229
+ return { kind: "failed", code: "notify_deliver_failed" };
230
+ }
231
+ }
232
+
233
+ /**
234
+ * 记录入站消息的 context token; 由 router 在授权通过后调用。
235
+ *
236
+ * @param replyContext 入站消息回复上下文。
237
+ * @returns 无返回值。
238
+ * @throws {ContextTokenStoreError} 存储写入失败时抛出。
239
+ */
240
+ async recordInboundContext(replyContext: IlinkReplyContext): Promise<void> {
241
+ await this.tokenStore.record(replyContext);
242
+ }
243
+
244
+ /**
245
+ * 处理 /renew 命令: 确认续命并补发积压通知。
246
+ *
247
+ * 续命效果由入站路径的 token 捕获自动完成, 这里只负责确认与补发。
248
+ *
249
+ * @param replyContext 当前 /renew 消息的回复上下文。
250
+ * @returns 回给用户的确认文本。
251
+ */
252
+ async renew(replyContext?: IlinkReplyContext): Promise<string> {
253
+ if (replyContext) {
254
+ await this.safeRecordToken(replyContext);
255
+ }
256
+ const record = await this.loadTokenRecord();
257
+ const replayed = await this.replayBacklog();
258
+ const lines = [
259
+ "✅ **通知通道已续命**",
260
+ "",
261
+ `当前窗口约 24 小时 (自 ${formatClock(record?.receivedAt)} 起)。`,
262
+ ];
263
+ if (this.backlogCount > 0) {
264
+ lines.push(`仍有 ${this.backlogCount} 条积压未补发, 下次续命时继续。`);
265
+ } else if (replayed > 0) {
266
+ lines.push(`已补发 ${replayed} 条积压通知。`);
267
+ }
268
+ return lines.join("\n");
269
+ }
270
+
271
+ /**
272
+ * 按需发送续命提醒; 由 Gateway 定时器周期调用。
273
+ *
274
+ * @returns 无返回值。
275
+ */
276
+ async maybeSendRenewalReminder(): Promise<void> {
277
+ const record = await this.loadTokenRecord();
278
+ if (!record) {
279
+ return;
280
+ }
281
+ const ageMs = Date.now() - new Date(record.receivedAt).getTime();
282
+ const remainingMs = CONTEXT_TOKEN_HARD_EXPIRY_MS - ageMs;
283
+ if (remainingMs > RENEWAL_REMINDER_LEAD_MS) {
284
+ return;
285
+ }
286
+ const now = Date.now();
287
+ if (
288
+ this.lastRenewalReminderAt !== undefined &&
289
+ now - this.lastRenewalReminderAt < RENEWAL_REMINDER_INTERVAL_MS
290
+ ) {
291
+ return;
292
+ }
293
+ try {
294
+ await this.deliver(record, RENEWAL_REMINDER_TEXT);
295
+ this.lastRenewalReminderAt = now;
296
+ } catch {
297
+ // 提醒是 best-effort: token 可能刚好失效, 等下个周期重试。
298
+ }
299
+ }
300
+
301
+ /**
302
+ * token 新鲜时补发积压通知; 由入站消息路径触发, 不抛出。
303
+ *
304
+ * @returns 补发条数, 无法补发时为 0。
305
+ */
306
+ async replayBacklogIfFresh(): Promise<number> {
307
+ try {
308
+ const record = await this.loadTokenRecord();
309
+ if (!record || !isTokenFresh(record.receivedAt) || this.backlogCount === 0) {
310
+ return 0;
311
+ }
312
+ return await this.replayBacklog();
313
+ } catch {
314
+ return 0;
315
+ }
316
+ }
317
+
318
+ /**
319
+ * 补发积压通知; 已有补发进行中时等待其完成。
320
+ *
321
+ * @returns 本轮实际补发条数。
322
+ */
323
+ async replayBacklog(): Promise<number> {
324
+ if (this.replayTask) {
325
+ return this.replayTask.then(() => 0);
326
+ }
327
+ this.replayTask = this.replayBacklogInternal().finally(() => {
328
+ this.replayTask = undefined;
329
+ });
330
+ return this.replayTask;
331
+ }
332
+
333
+ /**
334
+ * 补发内部实现: 积压超过阈值时合并为一条摘要, 否则逐条发送。
335
+ *
336
+ * @returns 本轮实际补发条数。
337
+ */
338
+ private async replayBacklogInternal(): Promise<number> {
339
+ let replayed = 0;
340
+ while (this.backlog.length > 0) {
341
+ const record = await this.loadTokenRecord();
342
+ if (!record || !isTokenFresh(record.receivedAt)) {
343
+ break;
344
+ }
345
+ const summaryMode = this.backlog.length > MAX_BACKLOG_REPLAY_COUNT;
346
+ const batch = this.backlog.slice(0, MAX_BACKLOG_REPLAY_COUNT);
347
+ const body = summaryMode
348
+ ? composeBacklogSummary(batch, this.backlog.length)
349
+ : batch.map((item) => composeNotificationBody(item)).join("\n\n---\n\n");
350
+ try {
351
+ await this.deliver(record, body);
352
+ } catch {
353
+ break;
354
+ }
355
+ replayed += batch.length;
356
+ this.backlog = this.backlog.slice(batch.length);
357
+ await this.persistBacklog();
358
+ if (summaryMode) {
359
+ break;
360
+ }
361
+ if (summaryMode) {
362
+ break;
363
+ }
364
+ }
365
+ return replayed;
366
+ }
367
+
368
+ /**
369
+ * 投递正文到微信。
370
+ *
371
+ * @param record 最新 token 记录。
372
+ * @param body 已拼装的正文。
373
+ * @returns 发送成功结果。
374
+ * @throws {IlinkApiError} iLink 发送失败时抛出。
375
+ */
376
+ private async deliver(record: ContextTokenRecord, body: string): Promise<{ kind: "sent"; clientId: string }> {
377
+ const clientId = `piw-notify-${hashNotificationContent(body)}-${Date.now().toString(36)}`;
378
+ await this.api.sendText(record.recipientId, body, record.contextToken, clientId);
379
+ return { kind: "sent", clientId };
380
+ }
381
+
382
+ /**
383
+ * 无任何 context token 时的处理。
384
+ *
385
+ * @param options 原始通知选项。
386
+ * @returns 按策略积压或丢弃的结果。
387
+ */
388
+ private handleUnavailable(options: { title?: string; text: string; source?: string }): Promise<NotificationSendResult> {
389
+ return this.enqueueOrDrop(options, { kind: "dropped", code: "notify_no_context" });
390
+ }
391
+
392
+ /**
393
+ * token 过期时的处理。
394
+ *
395
+ * @param options 原始通知选项。
396
+ * @returns 按策略积压或丢弃的结果。
397
+ */
398
+ private handleStale(options: { title?: string; text: string; source?: string }): Promise<NotificationSendResult> {
399
+ return this.enqueueOrDrop(options, { kind: "dropped", code: "notify_stale" });
400
+ }
401
+
402
+ /**
403
+ * 按 overflowPolicy 处理不可即时送达的通知。
404
+ *
405
+ * @param options 原始通知选项。
406
+ * @param droppedResult drop 模式返回的结果。
407
+ * @returns queue 模式返回积压位置, drop 模式返回丢弃结果。
408
+ */
409
+ private async enqueueOrDrop(
410
+ options: { title?: string; text: string; source?: string },
411
+ droppedResult: NotificationSendResult,
412
+ ): Promise<NotificationSendResult> {
413
+ const { config } = await this.configStore.load();
414
+ if (config.notification.overflowPolicy !== "queue") {
415
+ return droppedResult;
416
+ }
417
+ this.backlog.push({ ...options, enqueuedAt: new Date().toISOString() });
418
+ if (this.backlog.length > MAX_BACKLOG_ITEMS) {
419
+ this.backlog = this.backlog.slice(-MAX_BACKLOG_ITEMS);
420
+ }
421
+ await this.persistBacklog();
422
+ return { kind: "queued", position: this.backlog.length };
423
+ }
424
+
425
+ /**
426
+ * 读取 token 记录, 存储损坏时按无上下文处理。
427
+ *
428
+ * @returns 最新记录或 undefined。
429
+ */
430
+ private async loadTokenRecord(): Promise<ContextTokenRecord | undefined> {
431
+ try {
432
+ return await this.tokenStore.load();
433
+ } catch (error) {
434
+ if (error instanceof ContextTokenStoreError) {
435
+ return undefined;
436
+ }
437
+ throw error;
438
+ }
439
+ }
440
+
441
+ /**
442
+ * best-effort 记录入站 token, 失败不阻断 /renew 确认。
443
+ *
444
+ * @param replyContext 入站回复上下文。
445
+ * @returns 无返回值。
446
+ */
447
+ private async safeRecordToken(replyContext: IlinkReplyContext): Promise<void> {
448
+ try {
449
+ await this.tokenStore.record(replyContext);
450
+ } catch {
451
+ // 续命效果主要由入站路径的 token 捕获完成; 此处失败不阻断确认回复。
452
+ }
453
+ }
454
+ }
455
+
456
+ /**
457
+ * 拼装通知正文: 标题 + 正文 + 固定的"勿直接回复"提示。
458
+ *
459
+ * @param options 通知选项。
460
+ * @returns 多行 markdown 正文。
461
+ */
462
+ function composeNotificationBody(options: { title?: string; text: string; source?: string }): string {
463
+ const header = options.title
464
+ ? `🔔 **${options.title}**${options.source ? ` (${options.source})` : ""}`
465
+ : "🔔 **系统通知**";
466
+ return [
467
+ header,
468
+ "",
469
+ options.text,
470
+ "",
471
+ "〔系统通知, 与会话无关, 请勿直接回复〕",
472
+ ].join("\n");
473
+ }
474
+
475
+ /**
476
+ * 拼装积压摘要, 只保留各条标题行, 避免超长。
477
+ *
478
+ * @param batch 摘要覆盖的积压项。
479
+ * @param total 当前积压总数。
480
+ * @returns 摘要正文。
481
+ */
482
+ function composeBacklogSummary(batch: BackloggedNotification[], total: number): string {
483
+ const lines = batch.map((item) => {
484
+ const titleLine = item.text.split("\n").find((line) => line.startsWith("🔔"))
485
+ ?? item.title
486
+ ?? "(无标题通知)";
487
+ return `- ${titleLine.replace("🔔 **", "").replace("**", "")}`;
488
+ });
489
+ return composeNotificationBody({
490
+ title: `积压通知摘要 (本轮 ${batch.length} 条, 积压共 ${total} 条)`,
491
+ text: [
492
+ "以下为各通知标题, 详情已省略:",
493
+ "",
494
+ ...lines,
495
+ ].join("\n"),
496
+ });
497
+ }
498
+
499
+ /**
500
+ * 判断 token 记录是否仍在安全新鲜度窗口内。
501
+ *
502
+ * @param receivedAt token 对应入站消息时间。
503
+ * @returns 距上次入站消息不足 20 小时时返回 true。
504
+ */
505
+ function isTokenFresh(receivedAt: string): boolean {
506
+ const ageMs = Date.now() - new Date(receivedAt).getTime();
507
+ return ageMs >= 0 && ageMs < CONTEXT_TOKEN_FRESHNESS_MS;
508
+ }
509
+
510
+ /**
511
+ * 将 ISO 时间格式化为 MM-DD HH:mm 本地时间。
512
+ *
513
+ * @param isoTimestamp ISO 时间字符串。
514
+ * @returns 可读时间文本, 无效时返回"未知"。
515
+ */
516
+ function formatClock(isoTimestamp: string | undefined): string {
517
+ if (!isoTimestamp) {
518
+ return "未知";
519
+ }
520
+ const parsed = new Date(isoTimestamp);
521
+ if (Number.isNaN(parsed.getTime())) {
522
+ return "未知";
523
+ }
524
+ const pad = (value: number): string => String(value).padStart(2, "0");
525
+ return `${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
526
+ }