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.
@@ -0,0 +1,305 @@
1
+ import { open } from "node:fs/promises";
2
+ import type { WorkerInstanceRecord, SessionIndexRecord } from "../registry/types.ts";
3
+
4
+ /**
5
+ * 会话健康状态, 用于 /watch 总览。
6
+ */
7
+ export type HealthState = "starting" | "running" | "stopping" | "error" | "disconnected" | "idle";
8
+
9
+ /**
10
+ * 上游失败的归一化分类。
11
+ */
12
+ export type FailureKind =
13
+ | "daily_quota"
14
+ | "weekly_quota"
15
+ | "monthly_quota"
16
+ | "rate_limit"
17
+ | "usage_limit"
18
+ | "auth"
19
+ | "service_unavailable"
20
+ | "network"
21
+ | "aborted"
22
+ | "unknown";
23
+
24
+ /**
25
+ * 从 transcript 最后一条 assistant 记录中提取的失败信息。
26
+ */
27
+ export interface TurnFailure {
28
+ kind: FailureKind;
29
+ /** 面向用户的一句话说明。 */
30
+ summary: string;
31
+ /** 服务端给出的重置时间原文, 仅额度类错误会出现。 */
32
+ resetAt?: string;
33
+ /** 归一化前的原始错误前缀, 用于排查。 */
34
+ raw: string;
35
+ }
36
+
37
+ /**
38
+ * 单个会话的健康快照。
39
+ */
40
+ export interface SessionHealth {
41
+ session: SessionIndexRecord;
42
+ worker?: WorkerInstanceRecord;
43
+ state: HealthState;
44
+ failure?: TurnFailure;
45
+ }
46
+
47
+ /** 读取 transcript 尾部时使用的初始窗口大小。 */
48
+ const TAIL_READ_BYTES = 64 * 1024;
49
+
50
+ /** transcript 尾部窗口的最大扩展上限。 */
51
+ const TAIL_READ_MAX_BYTES = 2 * 1024 * 1024;
52
+
53
+ /** 提取到的原始错误在快照中保留的最大字符数。 */
54
+ const MAX_RAW_ERROR_CHARS = 200;
55
+
56
+ /**
57
+ * 计算会话健康状态。
58
+ *
59
+ * 只使用 registry 中明确记录的 worker state, 不从静态 heartbeatAt 推断“卡住”:
60
+ * heartbeatAt 只在状态变化时更新, 并非定时心跳, 用它判卡住会误报长时间运行的 turn。
61
+ *
62
+ * @param session 会话索引记录。
63
+ * @param worker 该会话当前的 worker 实例, 可为空。
64
+ * @param failure 最近一次 turn 的失败信息, 可为空。
65
+ * @returns 当前健康状态。
66
+ */
67
+ export function evaluateHealth(
68
+ session: SessionIndexRecord,
69
+ worker: WorkerInstanceRecord | undefined,
70
+ failure: TurnFailure | undefined,
71
+ ): { state: HealthState } {
72
+ if (worker?.state === "stale") {
73
+ return { state: "disconnected" };
74
+ }
75
+ if (worker?.state === "stopping") {
76
+ return { state: "stopping" };
77
+ }
78
+ if (worker?.state === "starting") {
79
+ return { state: "starting" };
80
+ }
81
+ if (worker?.state === "running") {
82
+ return { state: "running" };
83
+ }
84
+ if (failure) {
85
+ return { state: "error" };
86
+ }
87
+ if (!worker && session.state === "active") {
88
+ return { state: "disconnected" };
89
+ }
90
+ return { state: "idle" };
91
+ }
92
+
93
+ /**
94
+ * 将 upstream 的 errorMessage 归一化为可读的失败分类。
95
+ *
96
+ * 真实样本来自 Pi transcript 的 `message.errorMessage`, 形如:
97
+ *
98
+ * ```text
99
+ * 429: {"message":"You have exceeded the weekly usage quota. It will reset at
100
+ * 2026-11-16 00:00:00 +0800 CST...","type":"TooManyRequests","code":"AccountQuotaExceeded"}
101
+ * ```
102
+ *
103
+ * @param errorMessage transcript 中记录的原始错误文本。
104
+ * @returns 归一化失败信息, 无法识别时归类为 unknown。
105
+ */
106
+ export function classifyFailure(errorMessage: string): TurnFailure {
107
+ const raw = errorMessage.trim().slice(0, MAX_RAW_ERROR_CHARS);
108
+ const lowered = errorMessage.toLowerCase();
109
+ const resetAt = extractResetTime(errorMessage);
110
+
111
+ if (lowered.includes("weekly usage quota")) {
112
+ return { kind: "weekly_quota", summary: "周额度已耗尽", ...(resetAt ? { resetAt } : {}), raw };
113
+ }
114
+ if (lowered.includes("5-hour usage quota") || lowered.includes("5 hour usage quota")) {
115
+ return { kind: "daily_quota", summary: "5 小时额度已耗尽", ...(resetAt ? { resetAt } : {}), raw };
116
+ }
117
+ if (lowered.includes("monthly usage quota")) {
118
+ return { kind: "monthly_quota", summary: "月额度已耗尽", ...(resetAt ? { resetAt } : {}), raw };
119
+ }
120
+ if (lowered.includes("tokens per minute") || lowered.includes("tpm")) {
121
+ return { kind: "rate_limit", summary: "触发 TPM 限流", raw };
122
+ }
123
+ if (lowered.includes("usage limit has been reached") || lowered.includes("usage limit")) {
124
+ return { kind: "usage_limit", summary: "触发用量上限", ...(resetAt ? { resetAt } : {}), raw };
125
+ }
126
+ if (lowered.includes("429") && lowered.includes("too many requests")) {
127
+ return { kind: "rate_limit", summary: "被限流 (429)", ...(resetAt ? { resetAt } : {}), raw };
128
+ }
129
+ if (lowered.includes("not supported for this image model") || lowered.includes("complexity")) {
130
+ return { kind: "unknown", summary: "模型不支持该请求参数", raw };
131
+ }
132
+ if (lowered.includes("auth_unavailable") || lowered.includes("unauthorized") || lowered.includes("401")) {
133
+ return { kind: "auth", summary: "上游鉴权不可用", raw };
134
+ }
135
+ if (lowered.includes("503") || lowered.includes("service unavailable") || lowered.includes("overloaded")) {
136
+ return { kind: "service_unavailable", summary: "上游服务不可用", raw };
137
+ }
138
+ if (
139
+ lowered.includes("websocket error") ||
140
+ lowered.includes("stream disconnected") ||
141
+ lowered.includes("connection error") ||
142
+ lowered.includes("fetch failed") ||
143
+ lowered.includes("econnreset") ||
144
+ lowered.includes("etimedout")
145
+ ) {
146
+ return { kind: "network", summary: "网络连接中断", raw };
147
+ }
148
+ if (lowered.includes("aborted") || lowered.includes("terminated")) {
149
+ return { kind: "aborted", summary: "请求被中断", raw };
150
+ }
151
+ if (lowered.startsWith("429")) {
152
+ return { kind: "rate_limit", summary: "被限流 (429)", ...(resetAt ? { resetAt } : {}), raw };
153
+ }
154
+ return { kind: "unknown", summary: "上游返回未知错误", raw };
155
+ }
156
+
157
+ /**
158
+ * 从错误文本中提取服务端给出的重置时间。
159
+ *
160
+ * @param errorMessage 原始错误文本。
161
+ * @returns 含时区的重置时间原文, 不存在时返回 undefined。
162
+ */
163
+ export function extractResetTime(errorMessage: string): string | undefined {
164
+ const match = errorMessage.match(
165
+ /reset at (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\s+[+-]\d{4})?(?:\s+[A-Z]{2,5})?)/i,
166
+ );
167
+ return match?.[1]?.trim();
168
+ }
169
+
170
+ /**
171
+ * 从 session transcript 尾部读取最后一条 assistant 记录的失败信息。
172
+ *
173
+ * 只读取文件尾部有限窗口: 失败记录总是本次 turn 的最后一条, 不会出现在
174
+ * 很久以前的位置, 因此无需全文扫描。
175
+ *
176
+ * @param sessionFile Pi session 文件路径。
177
+ * @returns 失败信息; 最后一条 assistant 正常结束或无法读取时返回 undefined。
178
+ */
179
+ export async function readLatestFailure(sessionFile: string): Promise<TurnFailure | undefined> {
180
+ const handle = await open(sessionFile, "r").catch(() => undefined);
181
+ if (!handle) {
182
+ return undefined;
183
+ }
184
+ try {
185
+ const { size } = await handle.stat();
186
+ if (size === 0) {
187
+ return undefined;
188
+ }
189
+ let windowBytes = Math.min(size, TAIL_READ_BYTES);
190
+ for (;;) {
191
+ const start = size - windowBytes;
192
+ const chunk = Buffer.alloc(windowBytes);
193
+ await handle.read(chunk, 0, windowBytes, start);
194
+ const text = chunk.toString("utf8");
195
+ const buffer = start > 0 ? text.slice(text.indexOf("\n") + 1) : text;
196
+ const failure = scanFailureLines(buffer);
197
+ if (failure !== undefined) {
198
+ return failure;
199
+ }
200
+ if (start === 0 || windowBytes >= TAIL_READ_MAX_BYTES) {
201
+ return undefined;
202
+ }
203
+ windowBytes = Math.min(size, windowBytes * 2);
204
+ }
205
+ } finally {
206
+ await handle.close();
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 在一段 transcript 文本中从后向前定位最后一条 assistant 记录的失败信息。
212
+ *
213
+ * @param buffer 已剔除尾部半行的 transcript 文本片段。
214
+ * @returns 失败信息; 最后一条 assistant 正常结束时返回 undefined。
215
+ */
216
+ function scanFailureLines(buffer: string): TurnFailure | undefined {
217
+ const lines = buffer.split("\n");
218
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
219
+ const line = lines[index];
220
+ if (!line.trim()) {
221
+ continue;
222
+ }
223
+ let entry: unknown;
224
+ try {
225
+ entry = JSON.parse(line) as unknown;
226
+ } catch {
227
+ continue;
228
+ }
229
+ if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) {
230
+ continue;
231
+ }
232
+ const message = entry.message;
233
+ if (message.role !== "assistant") {
234
+ continue;
235
+ }
236
+ const stopReason = typeof message.stopReason === "string" ? message.stopReason : undefined;
237
+ const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : "";
238
+ if (errorMessage) {
239
+ return classifyFailure(errorMessage);
240
+ }
241
+ if (stopReason === "error") {
242
+ return { kind: "unknown", summary: "上游返回错误但未提供详情", raw: "stopReason=error" };
243
+ }
244
+ return undefined;
245
+ }
246
+ return undefined;
247
+ }
248
+
249
+ /**
250
+ * 将心跳年龄格式化为简短的中文描述。
251
+ *
252
+ * @param ageMs 距今毫秒数。
253
+ * @returns 形如 `8m` 或 `刚刚` 的文本。
254
+ */
255
+ export function formatDuration(ageMs: number): string {
256
+ const seconds = Math.floor(ageMs / 1000);
257
+ if (seconds < 10) {
258
+ return "刚刚";
259
+ }
260
+ if (seconds < 60) {
261
+ return `${seconds}s`;
262
+ }
263
+ const minutes = Math.floor(seconds / 60);
264
+ if (minutes < 60) {
265
+ return `${minutes}m`;
266
+ }
267
+ const hours = Math.floor(minutes / 60);
268
+ if (hours < 24) {
269
+ return `${hours}h`;
270
+ }
271
+ return `${Math.floor(hours / 24)}d`;
272
+ }
273
+
274
+ /**
275
+ * 将会话状态映射为总览表格使用的短标签。
276
+ *
277
+ * @param state 健康状态。
278
+ * @returns 带图标的短标签。
279
+ */
280
+ export function formatHealthState(state: HealthState): string {
281
+ switch (state) {
282
+ case "running":
283
+ return "🟢 运行中";
284
+ case "starting":
285
+ return "🟡 启动中";
286
+ case "stopping":
287
+ return "🟠 停止中";
288
+ case "error":
289
+ return "🔴 错误";
290
+ case "disconnected":
291
+ return "⚫ 断连";
292
+ case "idle":
293
+ return "⚪ 空闲";
294
+ }
295
+ }
296
+
297
+ /**
298
+ * 判断未知值是否为非数组对象。
299
+ *
300
+ * @param value 待检查值。
301
+ * @returns 值可安全读取字段时返回 true。
302
+ */
303
+ function isRecord(value: unknown): value is Record<string, unknown> {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }