@duanz/pi-d-reach 1.0.1 → 1.0.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.
- package/SKILL.md +7 -5
- package/package.json +1 -1
- package/plugin/index.ts +600 -378
- package/plugin/pwa.ts +93 -21
- package/plugin/runtime.ts +771 -0
- package/plugin/scripts/fanout.sh +290 -140
- package/plugin/scripts/mcp_call.py +39 -3
- package/plugin/scripts/quota.py +44 -11
- package/plugin/scripts/quota_probe.py +31 -8
- package/plugin/scripts/render.mjs +164 -5
- package/references/channels.md +6 -5
- package/scripts/fanout.sh +290 -140
- package/scripts/mcp_call.py +39 -3
- package/scripts/quota.py +44 -11
- package/scripts/quota_probe.py +31 -8
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared runtime primitives for d-reach plugin tools:
|
|
3
|
+
* - AbortSignal propagation & timeout-bounded fetch
|
|
4
|
+
* - Unified detached process-group subprocess runner
|
|
5
|
+
* - In-process + cross-process file locking and atomic writes
|
|
6
|
+
* - Normalized quota ledger & channel health aggregation
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
12
|
+
import { dirname } from "node:path";
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------- Abort & Timeout
|
|
15
|
+
|
|
16
|
+
export function abortedError(msg = "已中止"): Error {
|
|
17
|
+
const err = new Error(msg);
|
|
18
|
+
err.name = "AbortError";
|
|
19
|
+
return err;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isAborted(err: unknown, signal?: AbortSignal): boolean {
|
|
23
|
+
return (
|
|
24
|
+
signal?.aborted === true ||
|
|
25
|
+
(err instanceof Error && err.name === "AbortError")
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function fetchWithTimeout(
|
|
30
|
+
url: string,
|
|
31
|
+
init: RequestInit,
|
|
32
|
+
timeoutMs: number,
|
|
33
|
+
signal?: AbortSignal,
|
|
34
|
+
): Promise<Response> {
|
|
35
|
+
if (signal?.aborted) throw abortedError();
|
|
36
|
+
|
|
37
|
+
const ctrl = new AbortController();
|
|
38
|
+
let timedOut = false;
|
|
39
|
+
|
|
40
|
+
const onAbort = () => ctrl.abort(abortedError());
|
|
41
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
42
|
+
|
|
43
|
+
const timer = setTimeout(() => {
|
|
44
|
+
timedOut = true;
|
|
45
|
+
const err = new Error(`Request timed out (${Math.round(timeoutMs / 1000)}s): ${url}`) as Error & {
|
|
46
|
+
code?: string;
|
|
47
|
+
};
|
|
48
|
+
err.code = "ETIMEDOUT";
|
|
49
|
+
ctrl.abort(err);
|
|
50
|
+
}, timeoutMs);
|
|
51
|
+
timer.unref?.();
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
return await fetch(url, { ...init, signal: ctrl.signal });
|
|
55
|
+
} catch (err) {
|
|
56
|
+
if (signal?.aborted) throw abortedError();
|
|
57
|
+
if (timedOut) {
|
|
58
|
+
const timeoutErr = new Error(
|
|
59
|
+
`Request timed out (${Math.round(timeoutMs / 1000)}s): ${url}`,
|
|
60
|
+
) as Error & { code?: string };
|
|
61
|
+
timeoutErr.code = "ETIMEDOUT";
|
|
62
|
+
throw timeoutErr;
|
|
63
|
+
}
|
|
64
|
+
throw err;
|
|
65
|
+
} finally {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
signal?.removeEventListener("abort", onAbort);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function fetchTextWithTimeout(
|
|
72
|
+
url: string,
|
|
73
|
+
init: RequestInit,
|
|
74
|
+
timeoutMs: number,
|
|
75
|
+
signal?: AbortSignal,
|
|
76
|
+
): Promise<{ status: number; headers: Headers; text: string }> {
|
|
77
|
+
if (signal?.aborted) throw abortedError();
|
|
78
|
+
|
|
79
|
+
const ctrl = new AbortController();
|
|
80
|
+
let timedOut = false;
|
|
81
|
+
|
|
82
|
+
const onAbort = () => ctrl.abort(abortedError());
|
|
83
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
84
|
+
|
|
85
|
+
const timer = setTimeout(() => {
|
|
86
|
+
timedOut = true;
|
|
87
|
+
const err = new Error(`Request timed out (${Math.round(timeoutMs / 1000)}s): ${url}`) as Error & {
|
|
88
|
+
code?: string;
|
|
89
|
+
};
|
|
90
|
+
err.code = "ETIMEDOUT";
|
|
91
|
+
ctrl.abort(err);
|
|
92
|
+
}, timeoutMs);
|
|
93
|
+
timer.unref?.();
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetch(url, { ...init, signal: ctrl.signal });
|
|
97
|
+
const text = await res.text();
|
|
98
|
+
return { status: res.status, headers: res.headers, text };
|
|
99
|
+
} catch (err) {
|
|
100
|
+
if (signal?.aborted) throw abortedError();
|
|
101
|
+
if (timedOut) {
|
|
102
|
+
const timeoutErr = new Error(
|
|
103
|
+
`Request timed out (${Math.round(timeoutMs / 1000)}s): ${url}`,
|
|
104
|
+
) as Error & { code?: string };
|
|
105
|
+
timeoutErr.code = "ETIMEDOUT";
|
|
106
|
+
throw timeoutErr;
|
|
107
|
+
}
|
|
108
|
+
throw err;
|
|
109
|
+
} finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
signal?.removeEventListener("abort", onAbort);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---------------------------------------------------------------- Subprocess Runner
|
|
116
|
+
|
|
117
|
+
export interface RunCommandOptions {
|
|
118
|
+
timeoutMs?: number;
|
|
119
|
+
timeoutMessage?: string;
|
|
120
|
+
maxBuffer?: number;
|
|
121
|
+
env?: NodeJS.ProcessEnv;
|
|
122
|
+
signal?: AbortSignal;
|
|
123
|
+
killGraceMs?: number;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface RunCommandError extends Error {
|
|
127
|
+
code?: number | string;
|
|
128
|
+
stdout?: string;
|
|
129
|
+
stderr?: string;
|
|
130
|
+
killed?: "abort" | "timeout" | "maxBuffer";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function runCommand(
|
|
134
|
+
cmd: string,
|
|
135
|
+
args: string[],
|
|
136
|
+
opts: RunCommandOptions = {},
|
|
137
|
+
): Promise<{ stdout: string; stderr: string }> {
|
|
138
|
+
const {
|
|
139
|
+
timeoutMs,
|
|
140
|
+
timeoutMessage,
|
|
141
|
+
maxBuffer = 8 << 20,
|
|
142
|
+
env,
|
|
143
|
+
signal,
|
|
144
|
+
killGraceMs = 2000,
|
|
145
|
+
} = opts;
|
|
146
|
+
|
|
147
|
+
return new Promise((resolve, reject) => {
|
|
148
|
+
if (signal?.aborted) {
|
|
149
|
+
reject(abortedError());
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const child = spawn(cmd, args, {
|
|
154
|
+
detached: true,
|
|
155
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
156
|
+
env,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
const outChunks: Buffer[] = [];
|
|
160
|
+
const errChunks: Buffer[] = [];
|
|
161
|
+
let outBytes = 0;
|
|
162
|
+
let errBytes = 0;
|
|
163
|
+
let killed: "abort" | "timeout" | "maxBuffer" | "" = "";
|
|
164
|
+
let settled = false;
|
|
165
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
166
|
+
let timeTimer: NodeJS.Timeout | undefined;
|
|
167
|
+
|
|
168
|
+
const killGroup = (sig: NodeJS.Signals) => {
|
|
169
|
+
if (!child.pid) return;
|
|
170
|
+
try {
|
|
171
|
+
process.kill(-child.pid, sig);
|
|
172
|
+
} catch {
|
|
173
|
+
/* process group already gone */
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const groupAlive = (): boolean => {
|
|
178
|
+
if (!child.pid) return false;
|
|
179
|
+
try {
|
|
180
|
+
process.kill(-child.pid, 0);
|
|
181
|
+
return true;
|
|
182
|
+
} catch (e) {
|
|
183
|
+
return (e as NodeJS.ErrnoException)?.code === "EPERM";
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const terminate = (why: "abort" | "timeout" | "maxBuffer") => {
|
|
188
|
+
if (killed || settled) return;
|
|
189
|
+
killed = why;
|
|
190
|
+
killGroup("SIGTERM");
|
|
191
|
+
killTimer = setTimeout(() => {
|
|
192
|
+
killGroup("SIGKILL");
|
|
193
|
+
}, killGraceMs);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const onAbort = () => terminate("abort");
|
|
197
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
198
|
+
|
|
199
|
+
if (timeoutMs !== undefined && timeoutMs > 0) {
|
|
200
|
+
timeTimer = setTimeout(() => terminate("timeout"), timeoutMs);
|
|
201
|
+
timeTimer.unref?.();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
205
|
+
outBytes += chunk.length;
|
|
206
|
+
if (outBytes > maxBuffer) {
|
|
207
|
+
terminate("maxBuffer");
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
outChunks.push(chunk);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
child.stderr?.on("data", (chunk: Buffer) => {
|
|
214
|
+
if (errBytes >= maxBuffer) return;
|
|
215
|
+
errBytes += chunk.length;
|
|
216
|
+
errChunks.push(chunk);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
const cleanup = () => {
|
|
220
|
+
if (timeTimer) clearTimeout(timeTimer);
|
|
221
|
+
signal?.removeEventListener("abort", onAbort);
|
|
222
|
+
if (killTimer) {
|
|
223
|
+
if (!killed || !groupAlive()) {
|
|
224
|
+
clearTimeout(killTimer);
|
|
225
|
+
killTimer = undefined;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
child.on("error", (err) => {
|
|
231
|
+
if (settled) return;
|
|
232
|
+
settled = true;
|
|
233
|
+
cleanup();
|
|
234
|
+
if (killed === "abort" || signal?.aborted) {
|
|
235
|
+
reject(abortedError());
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
reject(err);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
child.on("close", (code, sig) => {
|
|
242
|
+
if (settled) return;
|
|
243
|
+
settled = true;
|
|
244
|
+
cleanup();
|
|
245
|
+
|
|
246
|
+
const stdout = Buffer.concat(outChunks).toString("utf8");
|
|
247
|
+
const stderr = Buffer.concat(errChunks).toString("utf8");
|
|
248
|
+
|
|
249
|
+
if (killed === "abort") {
|
|
250
|
+
reject(abortedError());
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (killed === "timeout") {
|
|
254
|
+
const msg =
|
|
255
|
+
timeoutMessage ??
|
|
256
|
+
`Command timed out (${Math.round((timeoutMs ?? 0) / 1000)}s): ${cmd}`;
|
|
257
|
+
const err = new Error(msg) as RunCommandError;
|
|
258
|
+
err.code = "ETIMEDOUT";
|
|
259
|
+
err.killed = "timeout";
|
|
260
|
+
err.stdout = stdout;
|
|
261
|
+
err.stderr = stderr;
|
|
262
|
+
reject(err);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (killed === "maxBuffer") {
|
|
266
|
+
const err = new Error("stdout maxBuffer length exceeded") as RunCommandError;
|
|
267
|
+
err.killed = "maxBuffer";
|
|
268
|
+
err.stdout = stdout;
|
|
269
|
+
err.stderr = stderr;
|
|
270
|
+
reject(err);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (code !== 0) {
|
|
274
|
+
const err = new Error(
|
|
275
|
+
`Command failed: ${cmd} ${args.join(" ")}\n${stderr}`.trimEnd(),
|
|
276
|
+
) as RunCommandError;
|
|
277
|
+
err.code = code ?? sig ?? 1;
|
|
278
|
+
err.stdout = stdout;
|
|
279
|
+
err.stderr = stderr;
|
|
280
|
+
reject(err);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
resolve({ stdout, stderr });
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ---------------------------------------------------------------- File Locking & Atomic Writes
|
|
289
|
+
|
|
290
|
+
export async function atomicWriteFile(filePath: string, content: string): Promise<void> {
|
|
291
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
292
|
+
const tmpPath = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString("hex")}`;
|
|
293
|
+
try {
|
|
294
|
+
const fh = await open(tmpPath, "w", 0o600);
|
|
295
|
+
try {
|
|
296
|
+
await fh.writeFile(content, "utf8");
|
|
297
|
+
} finally {
|
|
298
|
+
await fh.close();
|
|
299
|
+
}
|
|
300
|
+
await rename(tmpPath, filePath);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
await unlink(tmpPath).catch(() => {});
|
|
303
|
+
throw err;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const inProcessQueues = new Map<string, Promise<void>>();
|
|
308
|
+
|
|
309
|
+
async function withInProcessMutex<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
310
|
+
const prev = inProcessQueues.get(key) ?? Promise.resolve();
|
|
311
|
+
let release!: () => void;
|
|
312
|
+
const current = new Promise<void>((resolve) => {
|
|
313
|
+
release = resolve;
|
|
314
|
+
});
|
|
315
|
+
const tail = prev.then(() => current, () => current);
|
|
316
|
+
inProcessQueues.set(key, tail);
|
|
317
|
+
|
|
318
|
+
await prev;
|
|
319
|
+
try {
|
|
320
|
+
return await fn();
|
|
321
|
+
} finally {
|
|
322
|
+
release();
|
|
323
|
+
if (inProcessQueues.get(key) === tail) {
|
|
324
|
+
inProcessQueues.delete(key);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function isPidDead(pid: number): boolean {
|
|
330
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
331
|
+
try {
|
|
332
|
+
process.kill(pid, 0);
|
|
333
|
+
return false;
|
|
334
|
+
} catch (err) {
|
|
335
|
+
return (err as NodeJS.ErrnoException)?.code === "ESRCH";
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function sleep(ms: number): Promise<void> {
|
|
340
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export async function withFileLock<T>(
|
|
344
|
+
targetPath: string,
|
|
345
|
+
fn: () => Promise<T>,
|
|
346
|
+
opts: { timeoutMs?: number; staleMs?: number } = {},
|
|
347
|
+
): Promise<T> {
|
|
348
|
+
const lockPath = `${targetPath}.lock`;
|
|
349
|
+
const timeoutMs = opts.timeoutMs ?? 5000;
|
|
350
|
+
const staleMs = opts.staleMs ?? 15_000;
|
|
351
|
+
|
|
352
|
+
return withInProcessMutex(lockPath, async () => {
|
|
353
|
+
const deadline = Date.now() + timeoutMs;
|
|
354
|
+
await mkdir(dirname(lockPath), { recursive: true });
|
|
355
|
+
|
|
356
|
+
while (true) {
|
|
357
|
+
try {
|
|
358
|
+
const fh = await open(lockPath, "wx", 0o600);
|
|
359
|
+
try {
|
|
360
|
+
await fh.writeFile(`${process.pid}\n${Date.now()}\n`, "utf8");
|
|
361
|
+
} finally {
|
|
362
|
+
await fh.close();
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
return await fn();
|
|
366
|
+
} finally {
|
|
367
|
+
await unlink(lockPath).catch(() => {});
|
|
368
|
+
}
|
|
369
|
+
} catch (err) {
|
|
370
|
+
if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") {
|
|
371
|
+
throw err;
|
|
372
|
+
}
|
|
373
|
+
let stale = false;
|
|
374
|
+
try {
|
|
375
|
+
const [raw, st] = await Promise.all([
|
|
376
|
+
readFile(lockPath, "utf8").catch(() => ""),
|
|
377
|
+
stat(lockPath),
|
|
378
|
+
]);
|
|
379
|
+
const firstLine = raw.split("\n")[0]?.trim() ?? "";
|
|
380
|
+
const pid = /^\d+$/.test(firstLine) ? Number(firstLine) : 0;
|
|
381
|
+
if (Date.now() - st.mtimeMs > staleMs || (pid > 0 && isPidDead(pid))) {
|
|
382
|
+
stale = true;
|
|
383
|
+
}
|
|
384
|
+
} catch (statErr) {
|
|
385
|
+
if ((statErr as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (stale) {
|
|
390
|
+
await unlink(lockPath).catch(() => {});
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (Date.now() >= deadline) {
|
|
394
|
+
throw new Error(`Timed out waiting for lock: ${lockPath}`);
|
|
395
|
+
}
|
|
396
|
+
await sleep(15 + Math.floor(Math.random() * 25));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ---------------------------------------------------------------- Ledger & Health Aggregation
|
|
403
|
+
|
|
404
|
+
export const QUOTA_LIMITS: Record<string, readonly [number | null, number | null]> = {
|
|
405
|
+
brightdata: [5000, null],
|
|
406
|
+
exa: [2500, 50],
|
|
407
|
+
firecrawl: [1000, 200],
|
|
408
|
+
serper: [2500, null],
|
|
409
|
+
brave: [1000, null],
|
|
410
|
+
langsearch: [null, 50],
|
|
411
|
+
jina_reader: [null, 300],
|
|
412
|
+
xhs: [null, 200],
|
|
413
|
+
bili: [null, 200],
|
|
414
|
+
youcom: [null, 100],
|
|
415
|
+
twitter: [null, 100],
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
export const UNIT_PRICE_USD: Record<string, number> = {
|
|
419
|
+
youcom: 0.005,
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
export const SPEND_WARN_USD = 20.0;
|
|
423
|
+
|
|
424
|
+
export const RETIRED_CHANNELS = new Set(["bd", "yuanbao"]);
|
|
425
|
+
|
|
426
|
+
export const NEED_TITLE: Record<string, string> = {
|
|
427
|
+
login: "要登录",
|
|
428
|
+
antibot: "要过验证码",
|
|
429
|
+
auth: "凭据失效",
|
|
430
|
+
ratelimit: "限流中",
|
|
431
|
+
notfound: "端点失效",
|
|
432
|
+
setup: "依赖缺失",
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
export function parseReserve(raw?: string): number {
|
|
436
|
+
const src = raw ?? process.env.D_REACH_RESERVE ?? "0.30";
|
|
437
|
+
const parsed = Number.parseFloat(src);
|
|
438
|
+
if (!Number.isFinite(parsed)) return 0.3;
|
|
439
|
+
return Math.min(Math.max(parsed, 0.0), 0.9);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export function softLimit(limit: number | null, reserve: number): number | null {
|
|
443
|
+
if (limit === null) return null;
|
|
444
|
+
return Math.floor(limit * (1 - reserve));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function nonNegInt(v: unknown): number {
|
|
448
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
449
|
+
if (!Number.isFinite(n) || n < 0) return 0;
|
|
450
|
+
return Math.floor(n);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function normalizeQuotaBucket(
|
|
454
|
+
raw: unknown,
|
|
455
|
+
now: Date = new Date(),
|
|
456
|
+
): {
|
|
457
|
+
month: string;
|
|
458
|
+
day: string;
|
|
459
|
+
monthly: number;
|
|
460
|
+
daily: number;
|
|
461
|
+
staleMonth: boolean;
|
|
462
|
+
staleDay: boolean;
|
|
463
|
+
} {
|
|
464
|
+
const curMonth = now.toISOString().slice(0, 7);
|
|
465
|
+
const curDay = now.toISOString().slice(0, 10);
|
|
466
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
467
|
+
return {
|
|
468
|
+
month: curMonth,
|
|
469
|
+
day: curDay,
|
|
470
|
+
monthly: 0,
|
|
471
|
+
daily: 0,
|
|
472
|
+
staleMonth: false,
|
|
473
|
+
staleDay: false,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const rec = raw as Record<string, unknown>;
|
|
477
|
+
const staleMonth = rec.month !== curMonth;
|
|
478
|
+
const staleDay = rec.day !== curDay;
|
|
479
|
+
return {
|
|
480
|
+
month: curMonth,
|
|
481
|
+
day: curDay,
|
|
482
|
+
monthly: staleMonth ? 0 : nonNegInt(rec.monthly),
|
|
483
|
+
daily: staleDay ? 0 : nonNegInt(rec.daily),
|
|
484
|
+
staleMonth,
|
|
485
|
+
staleDay,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function suspendRemainingMs(
|
|
490
|
+
rec: { suspend_until?: string } | null | undefined,
|
|
491
|
+
nowMs: number = Date.now(),
|
|
492
|
+
): number {
|
|
493
|
+
const until = rec?.suspend_until;
|
|
494
|
+
if (!until || typeof until !== "string") return 0;
|
|
495
|
+
const ts = Date.parse(until);
|
|
496
|
+
if (!Number.isFinite(ts) || ts <= nowMs) return 0;
|
|
497
|
+
return ts - nowMs;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export type QuotaStatus = "充裕" | "已过裕度线" | "越免费线";
|
|
501
|
+
|
|
502
|
+
export interface QuotaRow {
|
|
503
|
+
svc: string;
|
|
504
|
+
monthly: number;
|
|
505
|
+
daily: number;
|
|
506
|
+
monthlyLimit: number | null;
|
|
507
|
+
dailyLimit: number | null;
|
|
508
|
+
monthlySoft: number | null;
|
|
509
|
+
dailySoft: number | null;
|
|
510
|
+
status: QuotaStatus;
|
|
511
|
+
spendUsd: number | null;
|
|
512
|
+
spendWarn: boolean;
|
|
513
|
+
staleMonth: boolean;
|
|
514
|
+
staleDay: boolean;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export interface OfficialRecord {
|
|
518
|
+
state?: string;
|
|
519
|
+
remaining?: number;
|
|
520
|
+
total?: number;
|
|
521
|
+
balance?: string;
|
|
522
|
+
currency?: string;
|
|
523
|
+
probed_at?: string;
|
|
524
|
+
period_end?: string;
|
|
525
|
+
items?: Array<{
|
|
526
|
+
id?: string;
|
|
527
|
+
name?: string;
|
|
528
|
+
remaining?: number;
|
|
529
|
+
total?: number;
|
|
530
|
+
used?: number;
|
|
531
|
+
}>;
|
|
532
|
+
[key: string]: unknown;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export interface QuotaHealthSummary {
|
|
536
|
+
lines: string[];
|
|
537
|
+
rows: QuotaRow[];
|
|
538
|
+
normalizedQuota: Record<string, unknown>;
|
|
539
|
+
bad: string[];
|
|
540
|
+
need: string[];
|
|
541
|
+
expiredSuspensions: string[];
|
|
542
|
+
unverifiedCount: number;
|
|
543
|
+
reserve: number;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function summarizeQuotaAndHealth(
|
|
547
|
+
rawQuota: Record<string, unknown>,
|
|
548
|
+
rawHealth: Record<string, unknown>,
|
|
549
|
+
opts: { now?: Date; reserve?: number } = {},
|
|
550
|
+
): QuotaHealthSummary {
|
|
551
|
+
const now = opts.now ?? new Date();
|
|
552
|
+
const nowMs = now.getTime();
|
|
553
|
+
const reserve = opts.reserve ?? parseReserve();
|
|
554
|
+
|
|
555
|
+
type HealthRec = {
|
|
556
|
+
streak_fail?: number;
|
|
557
|
+
code?: string;
|
|
558
|
+
last_ok?: string;
|
|
559
|
+
suspend_until?: string;
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
const bad: string[] = [];
|
|
563
|
+
const need: string[] = [];
|
|
564
|
+
const expiredSuspensions: string[] = [];
|
|
565
|
+
let unverifiedCount = 0;
|
|
566
|
+
|
|
567
|
+
for (const [key, val] of Object.entries(rawHealth)) {
|
|
568
|
+
if (RETIRED_CHANNELS.has(key) || !val || typeof val !== "object" || Array.isArray(val)) {
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
const rec = val as HealthRec;
|
|
572
|
+
if (!rec.last_ok) unverifiedCount += 1;
|
|
573
|
+
|
|
574
|
+
const remMs = suspendRemainingMs(rec, nowMs);
|
|
575
|
+
const hasNeedCode = Boolean(rec.code && NEED_TITLE[rec.code]);
|
|
576
|
+
const hasStreak = (rec.streak_fail ?? 0) >= 3 && Boolean(rec.last_ok);
|
|
577
|
+
|
|
578
|
+
if (hasNeedCode) {
|
|
579
|
+
if (remMs > 0) {
|
|
580
|
+
const mins = Math.ceil(remMs / 60_000);
|
|
581
|
+
need.push(`${key}(${NEED_TITLE[rec.code!]},${mins} 分钟后重试)`);
|
|
582
|
+
} else if (rec.suspend_until) {
|
|
583
|
+
expiredSuspensions.push(key);
|
|
584
|
+
}
|
|
585
|
+
} else if (hasStreak) {
|
|
586
|
+
if (remMs > 0) {
|
|
587
|
+
const mins = Math.ceil(remMs / 60_000);
|
|
588
|
+
bad.push(`${key}(${mins} 分钟后重试)`);
|
|
589
|
+
} else if (rec.suspend_until) {
|
|
590
|
+
expiredSuspensions.push(key);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const lines: string[] = [
|
|
596
|
+
"通道健康:",
|
|
597
|
+
bad.length
|
|
598
|
+
? ` 已验证后连败 ≥3(下轮自动跳过):${bad.join("、")}`
|
|
599
|
+
: " 没有已验证渠道处于连败挂起中(未验证不等于正常)",
|
|
600
|
+
];
|
|
601
|
+
if (unverifiedCount) lines.push(` 无成功记录/未验证:${unverifiedCount} 路`);
|
|
602
|
+
if (need.length) lines.push(` 要你出手:${need.join("、")}`);
|
|
603
|
+
if (expiredSuspensions.length) {
|
|
604
|
+
lines.push(` 挂起已到期(下次将自动重试):${expiredSuspensions.join("、")}`);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const official = ((rawQuota._official && typeof rawQuota._official === "object")
|
|
608
|
+
? rawQuota._official
|
|
609
|
+
: {}) as Record<string, OfficialRecord>;
|
|
610
|
+
|
|
611
|
+
const normalizedQuota: Record<string, unknown> = {};
|
|
612
|
+
for (const [k, v] of Object.entries(rawQuota)) {
|
|
613
|
+
if (k.startsWith("_")) normalizedQuota[k] = v;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const serviceKeys = [...Object.keys(QUOTA_LIMITS)];
|
|
617
|
+
for (const k of Object.keys(rawQuota)) {
|
|
618
|
+
if (
|
|
619
|
+
!k.startsWith("_") &&
|
|
620
|
+
!serviceKeys.includes(k) &&
|
|
621
|
+
rawQuota[k] &&
|
|
622
|
+
typeof rawQuota[k] === "object" &&
|
|
623
|
+
!Array.isArray(rawQuota[k])
|
|
624
|
+
) {
|
|
625
|
+
serviceKeys.push(k);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const rows: QuotaRow[] = [];
|
|
630
|
+
const spendRows: Array<{ svc: string; monthly: number; price: number; usd: number; warn: boolean }> = [];
|
|
631
|
+
|
|
632
|
+
for (const svc of serviceKeys) {
|
|
633
|
+
const rawBucket = rawQuota[svc];
|
|
634
|
+
const norm = normalizeQuotaBucket(rawBucket, now);
|
|
635
|
+
const prevObj =
|
|
636
|
+
rawBucket && typeof rawBucket === "object" && !Array.isArray(rawBucket)
|
|
637
|
+
? (rawBucket as Record<string, unknown>)
|
|
638
|
+
: {};
|
|
639
|
+
if (svc in rawQuota || norm.monthly > 0 || norm.daily > 0) {
|
|
640
|
+
normalizedQuota[svc] = {
|
|
641
|
+
...prevObj,
|
|
642
|
+
month: norm.month,
|
|
643
|
+
day: norm.day,
|
|
644
|
+
monthly: norm.monthly,
|
|
645
|
+
daily: norm.daily,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const [monthlyLimit, dailyLimit] = QUOTA_LIMITS[svc] ?? [null, null];
|
|
650
|
+
const monthlySoft = softLimit(monthlyLimit, reserve);
|
|
651
|
+
const dailySoft = softLimit(dailyLimit, reserve);
|
|
652
|
+
|
|
653
|
+
let status: QuotaStatus = "充裕";
|
|
654
|
+
if (
|
|
655
|
+
(monthlySoft !== null && norm.monthly >= monthlySoft) ||
|
|
656
|
+
(dailySoft !== null && norm.daily >= dailySoft)
|
|
657
|
+
) {
|
|
658
|
+
status = "已过裕度线";
|
|
659
|
+
}
|
|
660
|
+
if (
|
|
661
|
+
(monthlyLimit !== null && norm.monthly >= monthlyLimit) ||
|
|
662
|
+
(dailyLimit !== null && norm.daily >= dailyLimit)
|
|
663
|
+
) {
|
|
664
|
+
status = "越免费线";
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const price = UNIT_PRICE_USD[svc];
|
|
668
|
+
const spendUsd = price !== undefined ? norm.monthly * price : null;
|
|
669
|
+
const spendWarn = spendUsd !== null && spendUsd >= SPEND_WARN_USD;
|
|
670
|
+
if (price !== undefined && spendUsd !== null) {
|
|
671
|
+
spendRows.push({ svc, monthly: norm.monthly, price, usd: spendUsd, warn: spendWarn });
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
rows.push({
|
|
675
|
+
svc,
|
|
676
|
+
monthly: norm.monthly,
|
|
677
|
+
daily: norm.daily,
|
|
678
|
+
monthlyLimit,
|
|
679
|
+
dailyLimit,
|
|
680
|
+
monthlySoft,
|
|
681
|
+
dailySoft,
|
|
682
|
+
status,
|
|
683
|
+
spendUsd,
|
|
684
|
+
spendWarn,
|
|
685
|
+
staleMonth: norm.staleMonth,
|
|
686
|
+
staleDay: norm.staleDay,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
lines.push(
|
|
691
|
+
"",
|
|
692
|
+
`限额通道(保留 ${Math.round(reserve * 100)}% 裕度,裕度线 = 上限 ${Math.round((1 - reserve) * 100)}%):`,
|
|
693
|
+
);
|
|
694
|
+
|
|
695
|
+
for (const r of rows) {
|
|
696
|
+
const parts: string[] = [];
|
|
697
|
+
if (r.monthlyLimit !== null) {
|
|
698
|
+
parts.push(`本月 ${r.monthly}/${r.monthlyLimit}(裕度线 ${r.monthlySoft})`);
|
|
699
|
+
} else if (r.monthly > 0) {
|
|
700
|
+
parts.push(`本月 ${r.monthly}`);
|
|
701
|
+
}
|
|
702
|
+
if (r.dailyLimit !== null) {
|
|
703
|
+
parts.push(`今日 ${r.daily}/${r.dailyLimit}(裕度线 ${r.dailySoft})`);
|
|
704
|
+
} else if (r.daily > 0) {
|
|
705
|
+
parts.push(`今日 ${r.daily}`);
|
|
706
|
+
}
|
|
707
|
+
if (!parts.length) {
|
|
708
|
+
parts.push(`本月 ${r.monthly},今日 ${r.daily}`);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const statusTag =
|
|
712
|
+
r.status === "越免费线"
|
|
713
|
+
? " 🚫 越免费线"
|
|
714
|
+
: r.status === "已过裕度线"
|
|
715
|
+
? " ⚠️ 已过裕度线"
|
|
716
|
+
: "";
|
|
717
|
+
|
|
718
|
+
const off = official[r.svc];
|
|
719
|
+
const tail =
|
|
720
|
+
off?.state === "ok" && r.svc === "firecrawl"
|
|
721
|
+
? ` | 官方剩余 ${off.remaining}/${off.total}`
|
|
722
|
+
: off?.state === "ok" && r.svc === "tinyfish"
|
|
723
|
+
? ` | 钱包 ${off.balance} ${off.currency}`
|
|
724
|
+
: off?.state === "unavailable" || off?.state === "no_permission"
|
|
725
|
+
? " | 官方查不到"
|
|
726
|
+
: "";
|
|
727
|
+
|
|
728
|
+
lines.push(` ${r.svc}: ${parts.join(",")}${statusTag}${tail}`);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (official.tinyfish?.state === "ok" && !rows.some((r) => r.svc === "tinyfish")) {
|
|
732
|
+
lines.push(
|
|
733
|
+
` tinyfish: 钱包 ${official.tinyfish.balance} ${official.tinyfish.currency}(search/fetch $0/次)`,
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
if (spendRows.length) {
|
|
738
|
+
lines.push("", "按次计费估算($/次 × 本月次数):");
|
|
739
|
+
for (const s of spendRows) {
|
|
740
|
+
const cents = Number((s.price * 100).toFixed(4));
|
|
741
|
+
const warnTag = s.warn ? " ⚠️ 已过月度警戒线" : "";
|
|
742
|
+
lines.push(
|
|
743
|
+
` ${s.svc}: ${s.monthly} 次 × ${cents} 美分 = $${s.usd.toFixed(2)}(警戒线 $${SPEND_WARN_USD.toFixed(0)}/月)${warnTag}`,
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const zh = official.zhihu;
|
|
749
|
+
if (zh?.state === "ok" && zh.items?.length) {
|
|
750
|
+
lines.push("", "知乎开放平台(当日限免):");
|
|
751
|
+
for (const it of zh.items) {
|
|
752
|
+
lines.push(` ${it.name}: ${it.remaining}/${it.total}`);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
const stamp = Object.values(official).find((v) => v?.probed_at)?.probed_at;
|
|
757
|
+
if (stamp) {
|
|
758
|
+
lines.push("", `官方数据时间:${stamp.slice(0, 16).replace("T", " ")}`);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
return {
|
|
762
|
+
lines,
|
|
763
|
+
rows,
|
|
764
|
+
normalizedQuota,
|
|
765
|
+
bad,
|
|
766
|
+
need,
|
|
767
|
+
expiredSuspensions,
|
|
768
|
+
unverifiedCount,
|
|
769
|
+
reserve,
|
|
770
|
+
};
|
|
771
|
+
}
|