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.
@@ -4,7 +4,14 @@ import type { WorkerInstanceRecord, SessionIndexRecord } from "../registry/types
4
4
  /**
5
5
  * 会话健康状态, 用于 /watch 总览。
6
6
  */
7
- export type HealthState = "starting" | "running" | "stopping" | "error" | "disconnected" | "idle";
7
+ export type HealthState =
8
+ | "starting"
9
+ | "running"
10
+ | "stopping"
11
+ | "error"
12
+ | "disconnected"
13
+ | "interrupted"
14
+ | "idle";
8
15
 
9
16
  /**
10
17
  * 上游失败的归一化分类。
@@ -16,6 +23,7 @@ export type FailureKind =
16
23
  | "rate_limit"
17
24
  | "usage_limit"
18
25
  | "auth"
26
+ | "policy_blocked"
19
27
  | "service_unavailable"
20
28
  | "network"
21
29
  | "aborted"
@@ -32,6 +40,13 @@ export interface TurnFailure {
32
40
  resetAt?: string;
33
41
  /** 归一化前的原始错误前缀, 用于排查。 */
34
42
  raw: string;
43
+ /**
44
+ * 该失败发生的时刻, 取自 transcript 记录的 timestamp。
45
+ *
46
+ * 用于区分“当前故障”与“历史记录”: transcript 不会再变化, 若不看时间,
47
+ * 十几天前的一次失败会永久显示为异常。
48
+ */
49
+ detectedAt?: string;
35
50
  }
36
51
 
37
52
  /**
@@ -53,21 +68,61 @@ const TAIL_READ_MAX_BYTES = 2 * 1024 * 1024;
53
68
  /** 提取到的原始错误在快照中保留的最大字符数。 */
54
69
  const MAX_RAW_ERROR_CHARS = 200;
55
70
 
71
+ /**
72
+ * 失败被视为“当前故障”的最大年龄, 超过后只当作历史记录。
73
+ *
74
+ * 取 24 小时: 足以覆盖一次夜间失败到次日晚间的排查窗口, 又不会让
75
+ * 早已结束的会话永久占据 /watch 的异常列表。
76
+ */
77
+ export const FAILURE_ACTIVE_WINDOW_MS = 24 * 60 * 60 * 1000;
78
+
79
+ /**
80
+ * 判断一条失败记录是否已经超出“当前故障”的时间窗口。
81
+ *
82
+ * 缺少可信时间戳时一律视为未过期, 避免因为解析不到 timestamp 而漏报真实故障。
83
+ *
84
+ * @param failure 失败信息。
85
+ * @param nowMs 当前时间毫秒数。
86
+ * @param windowMs 判定窗口, 默认 {@link FAILURE_ACTIVE_WINDOW_MS}。
87
+ * @returns 已超出窗口返回 true。
88
+ */
89
+ export function isFailureExpired(
90
+ failure: TurnFailure,
91
+ nowMs: number,
92
+ windowMs: number = FAILURE_ACTIVE_WINDOW_MS,
93
+ ): boolean {
94
+ if (!failure.detectedAt) {
95
+ return false;
96
+ }
97
+ const detectedMs = Date.parse(failure.detectedAt);
98
+ if (!Number.isFinite(detectedMs)) {
99
+ return false;
100
+ }
101
+ return nowMs - detectedMs > windowMs;
102
+ }
103
+
56
104
  /**
57
105
  * 计算会话健康状态。
58
106
  *
59
107
  * 只使用 registry 中明确记录的 worker state, 不从静态 heartbeatAt 推断“卡住”:
60
108
  * heartbeatAt 只在状态变化时更新, 并非定时心跳, 用它判卡住会误报长时间运行的 turn。
61
109
  *
110
+ * 失败信息只在“确实需要用户处理”时才算异常:
111
+ *
112
+ * - `aborted` 表示用户主动中断, 不是故障, 归为已中断
113
+ * - 超出 {@link FAILURE_ACTIVE_WINDOW_MS} 的失败属于历史记录, 不再报异常
114
+ *
62
115
  * @param session 会话索引记录。
63
116
  * @param worker 该会话当前的 worker 实例, 可为空。
64
117
  * @param failure 最近一次 turn 的失败信息, 可为空。
118
+ * @param nowMs 当前时间毫秒数, 用于判定失败是否过期。
65
119
  * @returns 当前健康状态。
66
120
  */
67
121
  export function evaluateHealth(
68
122
  session: SessionIndexRecord,
69
123
  worker: WorkerInstanceRecord | undefined,
70
124
  failure: TurnFailure | undefined,
125
+ nowMs: number = Date.now(),
71
126
  ): { state: HealthState } {
72
127
  if (worker?.state === "stale") {
73
128
  return { state: "disconnected" };
@@ -81,7 +136,10 @@ export function evaluateHealth(
81
136
  if (worker?.state === "running") {
82
137
  return { state: "running" };
83
138
  }
84
- if (failure) {
139
+ if (failure?.kind === "aborted") {
140
+ return { state: "interrupted" };
141
+ }
142
+ if (failure && !isFailureExpired(failure, nowMs)) {
85
143
  return { state: "error" };
86
144
  }
87
145
  if (!worker && session.state === "active") {
@@ -129,6 +187,16 @@ export function classifyFailure(errorMessage: string): TurnFailure {
129
187
  if (lowered.includes("not supported for this image model") || lowered.includes("complexity")) {
130
188
  return { kind: "unknown", summary: "模型不支持该请求参数", raw };
131
189
  }
190
+ // 上游把第三方客户端或账号合规拦截归在这里, 与网络/额度无关, 换模型或换账号才能解决。
191
+ if (
192
+ lowered.includes("request blocked") ||
193
+ lowered.includes("not allowed") ||
194
+ lowered.includes("violates") ||
195
+ lowered.includes("unsupported_country") ||
196
+ lowered.includes("account suspension")
197
+ ) {
198
+ return { kind: "policy_blocked", summary: "请求被上游合规策略拦截", raw };
199
+ }
132
200
  if (lowered.includes("auth_unavailable") || lowered.includes("unauthorized") || lowered.includes("401")) {
133
201
  return { kind: "auth", summary: "上游鉴权不可用", raw };
134
202
  }
@@ -175,8 +243,7 @@ export function extractResetTime(errorMessage: string): string | undefined {
175
243
  *
176
244
  * @param sessionFile Pi session 文件路径。
177
245
  * @returns 失败信息; 最后一条 assistant 正常结束或无法读取时返回 undefined。
178
- */
179
- export async function readLatestFailure(sessionFile: string): Promise<TurnFailure | undefined> {
246
+ */export async function readLatestFailure(sessionFile: string): Promise<TurnFailure | undefined> {
180
247
  const handle = await open(sessionFile, "r").catch(() => undefined);
181
248
  if (!handle) {
182
249
  return undefined;
@@ -235,17 +302,155 @@ function scanFailureLines(buffer: string): TurnFailure | undefined {
235
302
  }
236
303
  const stopReason = typeof message.stopReason === "string" ? message.stopReason : undefined;
237
304
  const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : "";
305
+ const timestamp = typeof entry.timestamp === "string" ? entry.timestamp : undefined;
238
306
  if (errorMessage) {
239
- return classifyFailure(errorMessage);
307
+ return withTimestamp(classifyFailure(errorMessage), timestamp);
240
308
  }
241
309
  if (stopReason === "error") {
242
- return { kind: "unknown", summary: "上游返回错误但未提供详情", raw: "stopReason=error" };
310
+ return withTimestamp(
311
+ { kind: "unknown", summary: "上游返回错误但未提供详情", raw: "stopReason=error" },
312
+ timestamp,
313
+ );
243
314
  }
244
315
  return undefined;
245
316
  }
246
317
  return undefined;
247
318
  }
248
319
 
320
+ /**
321
+ * 把 transcript 记录的 timestamp 附到失败信息上。
322
+ *
323
+ * @param failure 已分类的失败信息。
324
+ * @param timestamp transcript 条目上的时间戳。
325
+ * @returns 带 detectedAt 的新对象; 无可用时间戳时原样返回。
326
+ */
327
+ function withTimestamp(failure: TurnFailure, timestamp: string | undefined): TurnFailure {
328
+ return timestamp ? { ...failure, detectedAt: timestamp } : failure;
329
+ }
330
+
331
+ /**
332
+ * 从 session transcript 尾部读取最后一条 user 消息的文本。
333
+ *
334
+ * 用于 `/watch` 总览的「最后提问」列: 相比会话标题, 用户自己最后一句话
335
+ * 更能帮助回忆起这个会话在干什么。只读文件尾部有限窗口, 不扫全文。
336
+ *
337
+ * @param sessionFile Pi session 文件路径。
338
+ * @returns 清理过空白的提问文本; 无提问或无法读取时返回 undefined。
339
+ */
340
+ export async function readLastUserQuestion(sessionFile: string): Promise<string | undefined> {
341
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
342
+ try {
343
+ handle = await open(sessionFile, "r");
344
+ const { size } = await handle.stat();
345
+ if (size === 0) {
346
+ return undefined;
347
+ }
348
+ // 一条 turn 可能包含大量 assistant 工具输出, 把最后一条 user 消息挤到
349
+ // 初始窗口之外, 因此和 readLatestFailure 一样逐次扩大窗口直到找到为止。
350
+ let windowBytes = Math.min(size, TAIL_READ_BYTES);
351
+ for (;;) {
352
+ const start = size - windowBytes;
353
+ const chunk = Buffer.alloc(windowBytes);
354
+ await handle.read(chunk, 0, windowBytes, start);
355
+ const text = chunk.toString("utf8");
356
+ const buffer = start > 0 ? text.slice(text.indexOf("\n") + 1) : text;
357
+ const question = scanLastUserQuestion(buffer);
358
+ if (question !== undefined) {
359
+ return question;
360
+ }
361
+ if (start === 0 || windowBytes >= TAIL_READ_MAX_BYTES) {
362
+ return undefined;
363
+ }
364
+ windowBytes = Math.min(size, windowBytes * 2);
365
+ }
366
+ } catch {
367
+ return undefined;
368
+ } finally {
369
+ await handle?.close();
370
+ }
371
+ }
372
+
373
+ /**
374
+ * 在一段 transcript 文本中从后向前定位最后一条 user 消息的文本。
375
+ *
376
+ * @param buffer 已剔除尾部半行的 transcript 文本片段。
377
+ * @returns 提问文本; 未找到时返回 undefined。
378
+ */
379
+ function scanLastUserQuestion(buffer: string): string | undefined {
380
+ const lines = buffer.split("\n");
381
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
382
+ const line = lines[index];
383
+ if (!line.trim()) {
384
+ continue;
385
+ }
386
+ let entry: unknown;
387
+ try {
388
+ entry = JSON.parse(line) as unknown;
389
+ } catch {
390
+ continue;
391
+ }
392
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
393
+ continue;
394
+ }
395
+ if (entry.message.role !== "user") {
396
+ continue;
397
+ }
398
+ const question = extractMessageText(entry.message.content);
399
+ if (question) {
400
+ return question;
401
+ }
402
+ }
403
+ return undefined;
404
+ }
405
+
406
+ /**
407
+ * 从 message.content 中提取纯文本。
408
+ *
409
+ * content 两种形态都要兼容: 纯字符串, 或带 type 的内容块数组。
410
+ *
411
+ * @param content transcript 中记录的 message.content。
412
+ * @returns 合并空白后的文本; 无文本时返回 undefined。
413
+ */
414
+ function extractMessageText(content: unknown): string | undefined {
415
+ let text = "";
416
+ if (typeof content === "string") {
417
+ text = content;
418
+ } else if (Array.isArray(content)) {
419
+ text = content
420
+ .filter((block): block is Record<string, unknown> => isRecord(block) && block.type === "text")
421
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
422
+ .join(" ");
423
+ }
424
+ const normalized = text.replace(/\s+/g, " ").trim();
425
+ return normalized.length > 0 ? normalized : undefined;
426
+ }
427
+
428
+ /**
429
+ * 将时间格式化为相对描述, 用于总览表格。
430
+ *
431
+ * @param isoTimestamp ISO 时间戳。
432
+ * @param nowMs 当前毫秒数。
433
+ * @returns 形如 `刚刚` / `5m` / `3h` / `2d` 的短文本。
434
+ */
435
+ export function formatRelativeAge(isoTimestamp: string, nowMs: number = Date.now()): string {
436
+ const parsed = Date.parse(isoTimestamp);
437
+ if (!Number.isFinite(parsed)) {
438
+ return isoTimestamp;
439
+ }
440
+ const minutes = Math.floor((nowMs - parsed) / 60000);
441
+ if (minutes < 1) {
442
+ return "刚刚";
443
+ }
444
+ if (minutes < 60) {
445
+ return `${minutes}m`;
446
+ }
447
+ const hours = Math.floor(minutes / 60);
448
+ if (hours < 24) {
449
+ return `${hours}h`;
450
+ }
451
+ return `${Math.floor(hours / 24)}d`;
452
+ }
453
+
249
454
  /**
250
455
  * 将心跳年龄格式化为简短的中文描述。
251
456
  *
@@ -289,6 +494,8 @@ export function formatHealthState(state: HealthState): string {
289
494
  return "🔴 错误";
290
495
  case "disconnected":
291
496
  return "⚫ 断连";
497
+ case "interrupted":
498
+ return "⚪ 已中断";
292
499
  case "idle":
293
500
  return "⚪ 空闲";
294
501
  }