@duanz/pi-d-reach 1.0.0 → 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 +49 -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 +49 -11
- package/scripts/quota_probe.py +31 -8
package/plugin/index.ts
CHANGED
|
@@ -13,30 +13,39 @@
|
|
|
13
13
|
* 所有检索/记账逻辑仍在 skill 的 scripts/ 里,插件不复制一份。
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
-
import {
|
|
17
|
-
import { createHash } from "node:crypto";
|
|
16
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
18
17
|
import { lookup } from "node:dns/promises";
|
|
19
|
-
import { existsSync } from "node:fs";
|
|
20
|
-
import { mkdir, readdir, readFile, stat, unlink
|
|
18
|
+
import { existsSync, statSync } from "node:fs";
|
|
19
|
+
import { mkdir, readdir, readFile, stat, unlink } from "node:fs/promises";
|
|
21
20
|
import { isIP } from "node:net";
|
|
22
21
|
import { homedir, tmpdir } from "node:os";
|
|
23
22
|
import { dirname, join } from "node:path";
|
|
24
23
|
import { fileURLToPath } from "node:url";
|
|
25
|
-
import { promisify } from "node:util";
|
|
26
24
|
|
|
27
25
|
import { Type } from "@earendil-works/pi-ai";
|
|
28
26
|
import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
29
27
|
|
|
30
28
|
import { registerPwaTools, routeSpecialUrl } from "./pwa.ts";
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
29
|
+
import {
|
|
30
|
+
abortedError,
|
|
31
|
+
atomicWriteFile,
|
|
32
|
+
fetchTextWithTimeout,
|
|
33
|
+
isAborted,
|
|
34
|
+
runCommand,
|
|
35
|
+
summarizeQuotaAndHealth,
|
|
36
|
+
withFileLock,
|
|
37
|
+
} from "./runtime.ts";
|
|
38
|
+
|
|
39
|
+
// 脚本目录解析:优先仓库自带 scripts/,其次扩展自身 scripts/(npm 包/软链),
|
|
40
|
+
// 再回退到历史路径 ~/.agents/skills/d-reach。
|
|
36
41
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
37
|
-
const SKILL_DIR =
|
|
38
|
-
?
|
|
39
|
-
: join(
|
|
42
|
+
const SKILL_DIR = process.env.D_REACH_SKILL_DIR
|
|
43
|
+
? process.env.D_REACH_SKILL_DIR
|
|
44
|
+
: existsSync(join(HERE, "..", "scripts", "fanout.sh"))
|
|
45
|
+
? join(HERE, "..")
|
|
46
|
+
: existsSync(join(HERE, "scripts", "fanout.sh"))
|
|
47
|
+
? HERE
|
|
48
|
+
: join(homedir(), ".agents/skills/d-reach");
|
|
40
49
|
const FANOUT = join(SKILL_DIR, "scripts", "fanout.sh");
|
|
41
50
|
const KEY_SH = join(SKILL_DIR, "scripts", "load_key.sh");
|
|
42
51
|
const PROBE = join(SKILL_DIR, "scripts", "quota_probe.py");
|
|
@@ -45,8 +54,18 @@ const PDF2TEXT = join(HERE, "scripts", "pdf2text.py");
|
|
|
45
54
|
const MCP_CALL = join(SKILL_DIR, "scripts", "mcp_call.py");
|
|
46
55
|
const PARALLEL_MCP = "https://mcp.parallel.ai/mcp";
|
|
47
56
|
const DATA_DIR = join(homedir(), ".agent-reach");
|
|
48
|
-
const
|
|
57
|
+
const defaultsFilePath = () =>
|
|
58
|
+
process.env.D_REACH_DEFAULTS_FILE || join(DATA_DIR, "fanout-defaults.json");
|
|
59
|
+
const deadFilePath = () =>
|
|
60
|
+
process.env.D_REACH_DEAD_FILE || join(DATA_DIR, "fetch-dead.json");
|
|
61
|
+
const quotaFilePath = () =>
|
|
62
|
+
process.env.D_REACH_QUOTA_FILE || join(DATA_DIR, "quota.json");
|
|
63
|
+
const healthFilePath = () =>
|
|
64
|
+
process.env.D_REACH_HEALTH || join(DATA_DIR, "channels.json");
|
|
65
|
+
const storeDirPath = () =>
|
|
66
|
+
process.env.D_REACH_STORE_DIR || join(DATA_DIR, "fetch-store");
|
|
49
67
|
const LAST_RUN = join(DATA_DIR, "last-run.md");
|
|
68
|
+
const REWRITE_TIMEOUT_MS = 15_000;
|
|
50
69
|
const SEARCH_CACHE_TTL_MS = 15 * 60_000;
|
|
51
70
|
const SEARCH_CACHE_KEEP_MS = 60 * 60_000;
|
|
52
71
|
const FANOUT_TIMEOUT_MS = 200_000;
|
|
@@ -167,24 +186,65 @@ const CHANNEL_MENU: [string, string][] = [
|
|
|
167
186
|
["gh", "GitHub — 找开源项目、仓库、轮子"],
|
|
168
187
|
["xhs", "国内版 XHS — 真实体验、种草、避坑、生活决策(需登录)"],
|
|
169
188
|
["bili", "B站 — 视频实测、教程、评测"],
|
|
170
|
-
["youcom", "
|
|
189
|
+
["youcom", "通用快搜(按需;配 YOU_API_KEY 走官方付费 REST / 无 key 兜底 MCP)"],
|
|
171
190
|
["anysearch", "垂直专库(法律/医疗/金融)"],
|
|
172
191
|
];
|
|
173
192
|
|
|
174
193
|
const VALID_CHANNELS = CHANNEL_MENU.map(([k]) => k);
|
|
175
194
|
|
|
176
|
-
|
|
195
|
+
/**
|
|
196
|
+
* 路由清单(--list --json)的进程内缓存。
|
|
197
|
+
*
|
|
198
|
+
* 每次 auto 检索都会读一次启用清单;实测一次 `bash fanout.sh --list --json` 要 ~45ms,
|
|
199
|
+
* 其中几乎全是 bash + python 启动开销,与清单内容无关。这里按「脚本/注册表/默认配置的
|
|
200
|
+
* mtime+size」做失效判断:改过任何一处就重读,没改就一直复用。
|
|
201
|
+
* D_REACH_ROUTE_CACHE_MS=0 可关掉(测试/排查用)。
|
|
202
|
+
*/
|
|
203
|
+
const ROUTE_CACHE_TTL_MS = (() => {
|
|
204
|
+
const raw = Number(process.env.D_REACH_ROUTE_CACHE_MS ?? "30000");
|
|
205
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 30_000;
|
|
206
|
+
})();
|
|
207
|
+
let routeCache: { key: string; at: number; parsed: unknown } | null = null;
|
|
208
|
+
|
|
209
|
+
function routeCacheKey(): string {
|
|
210
|
+
const paths = [FANOUT, join(dirname(FANOUT), "route_config.py"), defaultsFilePath()];
|
|
211
|
+
return paths
|
|
212
|
+
.map((path) => {
|
|
213
|
+
try {
|
|
214
|
+
const st = statSync(path);
|
|
215
|
+
return `${st.mtimeMs}:${st.size}`;
|
|
216
|
+
} catch {
|
|
217
|
+
return "-";
|
|
218
|
+
}
|
|
219
|
+
})
|
|
220
|
+
.join("|");
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function defaultChannelAllowlist(signal?: AbortSignal): Promise<{
|
|
177
224
|
enabledByDefault: string[];
|
|
178
225
|
enabledForDeep: string[];
|
|
179
226
|
knownChannels: string[];
|
|
180
227
|
deepChannels: string[];
|
|
181
228
|
}> {
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
229
|
+
const cacheKey = routeCacheKey();
|
|
230
|
+
const cacheable = ROUTE_CACHE_TTL_MS > 0;
|
|
231
|
+
let parsed: Record<string, unknown> | null = null;
|
|
232
|
+
if (cacheable && routeCache && routeCache.key === cacheKey
|
|
233
|
+
&& Date.now() - routeCache.at < ROUTE_CACHE_TTL_MS) {
|
|
234
|
+
parsed = routeCache.parsed as Record<string, unknown> | null;
|
|
235
|
+
} else {
|
|
236
|
+
const { stdout } = await runCommand("bash", [FANOUT, "--list", "--json"], {
|
|
237
|
+
timeoutMs: 15_000,
|
|
238
|
+
maxBuffer: 1 << 20,
|
|
239
|
+
env: { ...process.env, D_REACH_DEFAULTS_FILE: defaultsFilePath() },
|
|
240
|
+
signal,
|
|
241
|
+
});
|
|
242
|
+
parsed = JSON.parse(stdout) as Record<string, unknown> | null;
|
|
243
|
+
if (cacheable && parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
244
|
+
&& !(typeof parsed.defaults_error === "string" && parsed.defaults_error)) {
|
|
245
|
+
routeCache = { key: cacheKey, at: Date.now(), parsed };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
188
248
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
189
249
|
throw new Error("D-Reach returned an invalid route config response");
|
|
190
250
|
if (typeof parsed.defaults_error === "string" && parsed.defaults_error)
|
|
@@ -226,11 +286,11 @@ async function defaultChannelAllowlist(): Promise<{
|
|
|
226
286
|
*/
|
|
227
287
|
const INTENT_MODEL = process.env.D_REACH_INTENT_MODEL || "";
|
|
228
288
|
|
|
229
|
-
// auto
|
|
289
|
+
// auto 档的固定底座:纯免费的通用网页搜索,每轮都跑、中英各查一遍。
|
|
230
290
|
// 业内做法(Google AI Mode 的 query fan-out、ChatGPT/Claude 的 query rewrite、
|
|
231
291
|
// Perplexity 的多子查询、SearXNG 的分类引擎组)都是「模型写检索词,后端固定」,
|
|
232
292
|
// 模型不负责挑通用搜索引擎;所以这里底座写死,模型只补 0-3 个专项通道。
|
|
233
|
-
const AUTO_BASE = ["tf", "parallel", "
|
|
293
|
+
const AUTO_BASE = ["tf", "parallel", "anysearch", "tavily"];
|
|
234
294
|
|
|
235
295
|
// 专项通道:站内/垂直库,只在问题需要时由模型挑;通用网页通道已在底座里,不进菜单
|
|
236
296
|
const SPECIAL_MENU = CHANNEL_MENU.filter(([k]) => !AUTO_BASE.includes(k));
|
|
@@ -251,7 +311,8 @@ const ROUTE_PROMPT =
|
|
|
251
311
|
"- 概念定义/人物/地名 → wiki\n" +
|
|
252
312
|
"- 中文政策/本地生活/中文长尾 → qianfan,zhihuall\n" +
|
|
253
313
|
"- 最新动态/新闻 → langsearch\n" +
|
|
254
|
-
"- 电商/本地商家/Google 才有的 → serper\n
|
|
314
|
+
"- 电商/本地商家/Google 才有的 → serper\n" +
|
|
315
|
+
"- 通用网页补充快搜(按需) → youcom\n\n" +
|
|
255
316
|
"只输出三行,格式严格如下(不要解释、不要编号、不要加任何其他内容):\n" +
|
|
256
317
|
"中文:家用 NAS 选购 推荐 2026\n" +
|
|
257
318
|
"英文:best home NAS 2026 buying guide\n" +
|
|
@@ -316,7 +377,9 @@ function parseChinese(text: string): string {
|
|
|
316
377
|
async function rewriteQuery(
|
|
317
378
|
query: string,
|
|
318
379
|
ctx: unknown,
|
|
380
|
+
signal?: AbortSignal,
|
|
319
381
|
): Promise<{ zh: string; en: string; extra: string[] } | null> {
|
|
382
|
+
if (signal?.aborted) throw abortedError();
|
|
320
383
|
const reg = (ctx as { modelRegistry?: any })?.modelRegistry;
|
|
321
384
|
const dbg = async (m: string) => {
|
|
322
385
|
try {
|
|
@@ -346,6 +409,11 @@ async function rewriteQuery(
|
|
|
346
409
|
}
|
|
347
410
|
|
|
348
411
|
let raw = "";
|
|
412
|
+
const ctrl = new AbortController();
|
|
413
|
+
const onAbort = () => ctrl.abort(abortedError());
|
|
414
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
415
|
+
const timer = setTimeout(() => ctrl.abort(new Error("rewriteQuery timeout")), REWRITE_TIMEOUT_MS);
|
|
416
|
+
timer.unref?.();
|
|
349
417
|
try {
|
|
350
418
|
const res = await reg.complete(
|
|
351
419
|
model,
|
|
@@ -355,12 +423,15 @@ async function rewriteQuery(
|
|
|
355
423
|
role: "user",
|
|
356
424
|
// 全部指令放 user:pi 的 complete 会叠加自己的默认 system 提示,
|
|
357
425
|
// system 里的约束实测被冲淡过两次(先回正文、后回 "search")。
|
|
358
|
-
content: `${ROUTE_PROMPT}\n\n搜索意图:${query}\n\n只输出那三行,不要回答这个问题。`,
|
|
426
|
+
content: `${ROUTE_PROMPT}\n\n搜索意图:${query.slice(0, 500)}\n\n只输出那三行,不要回答这个问题。`,
|
|
359
427
|
},
|
|
360
428
|
],
|
|
361
429
|
},
|
|
362
|
-
{ maxTokens: 160, temperature: 0 },
|
|
430
|
+
{ maxTokens: 160, temperature: 0, signal: ctrl.signal },
|
|
363
431
|
);
|
|
432
|
+
if (signal?.aborted || (res?.stopReason === "aborted" && signal?.aborted)) {
|
|
433
|
+
throw abortedError();
|
|
434
|
+
}
|
|
364
435
|
raw = Array.isArray(res?.content)
|
|
365
436
|
? res.content
|
|
366
437
|
.filter((c: any) => c?.type === "text")
|
|
@@ -368,9 +439,14 @@ async function rewriteQuery(
|
|
|
368
439
|
.join(" ")
|
|
369
440
|
: String(res?.content ?? "");
|
|
370
441
|
} catch (err) {
|
|
442
|
+
if (isAborted(err, signal)) throw abortedError();
|
|
371
443
|
await dbg(`选路调用异常:${err instanceof Error ? err.message : String(err)}`);
|
|
372
444
|
return null;
|
|
445
|
+
} finally {
|
|
446
|
+
clearTimeout(timer);
|
|
447
|
+
signal?.removeEventListener("abort", onAbort);
|
|
373
448
|
}
|
|
449
|
+
if (signal?.aborted) throw abortedError();
|
|
374
450
|
|
|
375
451
|
const extra = parseChannels(raw);
|
|
376
452
|
const zh = parseChinese(raw);
|
|
@@ -641,7 +717,7 @@ async function runFanout(
|
|
|
641
717
|
let extra: string[] = [];
|
|
642
718
|
let rewritten = false;
|
|
643
719
|
if (!zh || !en || (!on && profile === "auto")) {
|
|
644
|
-
const r = await rewriteQuery(query, ctx);
|
|
720
|
+
const r = await rewriteQuery(query, ctx, signal);
|
|
645
721
|
if (r) {
|
|
646
722
|
rewritten = true;
|
|
647
723
|
zh = zh || r.zh;
|
|
@@ -649,6 +725,7 @@ async function runFanout(
|
|
|
649
725
|
extra = r.extra;
|
|
650
726
|
}
|
|
651
727
|
}
|
|
728
|
+
if (signal?.aborted) throw abortedError();
|
|
652
729
|
const isZh = /[\u4e00-\u9fff]/.test(query);
|
|
653
730
|
if (!zh && isZh) zh = query;
|
|
654
731
|
if (!en && !isZh) en = query;
|
|
@@ -667,7 +744,8 @@ async function runFanout(
|
|
|
667
744
|
unclear = !rewritten && !extra.length;
|
|
668
745
|
}
|
|
669
746
|
if (!explicitChannels && on) {
|
|
670
|
-
const defaults = await defaultChannelAllowlist();
|
|
747
|
+
const defaults = await defaultChannelAllowlist(signal);
|
|
748
|
+
if (signal?.aborted) throw abortedError();
|
|
671
749
|
const known = on
|
|
672
750
|
.split(",")
|
|
673
751
|
.map((value) => value.trim())
|
|
@@ -710,20 +788,8 @@ async function runFanout(
|
|
|
710
788
|
return { md: stdout, secs: (Date.now() - t0) / 1000, on, why, unclear, warn, zh, en };
|
|
711
789
|
}
|
|
712
790
|
|
|
713
|
-
/** 被 abort 时统一抛这个;execute 里据此返回「已中止」,不写缓存。 */
|
|
714
|
-
function abortedError(): Error {
|
|
715
|
-
const err = new Error("已中止");
|
|
716
|
-
err.name = "AbortError";
|
|
717
|
-
return err;
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
function isAborted(err: unknown, signal?: AbortSignal): boolean {
|
|
721
|
-
return signal?.aborted === true || (err instanceof Error && err.name === "AbortError");
|
|
722
|
-
}
|
|
723
|
-
|
|
724
791
|
/**
|
|
725
|
-
* 跑 fanout.sh
|
|
726
|
-
* 但改成 detached 子进程:fanout 是新进程组的组长,abort/超时时杀整个进程组,
|
|
792
|
+
* 跑 fanout.sh:使用 detached 进程组运行,abort/超时时按 -pid 杀整组,
|
|
727
793
|
* 连带 curl、python 这些孙进程一起终止,不会留下孤儿在后台继续跑。
|
|
728
794
|
*/
|
|
729
795
|
function runFanoutProcess(
|
|
@@ -731,104 +797,12 @@ function runFanoutProcess(
|
|
|
731
797
|
env: NodeJS.ProcessEnv,
|
|
732
798
|
signal?: AbortSignal,
|
|
733
799
|
): Promise<{ stdout: string; stderr: string }> {
|
|
734
|
-
return
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
detached: true,
|
|
741
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
742
|
-
env,
|
|
743
|
-
});
|
|
744
|
-
const outChunks: Buffer[] = [];
|
|
745
|
-
const errChunks: Buffer[] = [];
|
|
746
|
-
let outBytes = 0;
|
|
747
|
-
let errBytes = 0;
|
|
748
|
-
let killed: "abort" | "timeout" | "maxBuffer" | "" = "";
|
|
749
|
-
let settled = false;
|
|
750
|
-
let killTimer: NodeJS.Timeout | undefined;
|
|
751
|
-
let timeTimer: NodeJS.Timeout | undefined;
|
|
752
|
-
|
|
753
|
-
// 负的 pid = 整个进程组;组已不存在时 ESRCH,忽略即可
|
|
754
|
-
const killGroup = (sig: NodeJS.Signals) => {
|
|
755
|
-
if (!child.pid) return;
|
|
756
|
-
try {
|
|
757
|
-
process.kill(-child.pid, sig);
|
|
758
|
-
} catch {}
|
|
759
|
-
};
|
|
760
|
-
const terminate = (why: "abort" | "timeout" | "maxBuffer") => {
|
|
761
|
-
if (killed || settled) return;
|
|
762
|
-
killed = why;
|
|
763
|
-
killGroup("SIGTERM");
|
|
764
|
-
// 2 秒还活着(比如 python 正在收尾)就 SIGKILL 整个组。
|
|
765
|
-
// 定时器不 unref:即使 bash 已经先退出、close 已触发,也要保证这颗
|
|
766
|
-
// 「补刀」真的落地,否则忽略 SIGTERM 的孙进程会变成孤儿。
|
|
767
|
-
killTimer = setTimeout(() => killGroup("SIGKILL"), 2000);
|
|
768
|
-
};
|
|
769
|
-
const onAbort = () => terminate("abort");
|
|
770
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
771
|
-
timeTimer = setTimeout(() => terminate("timeout"), FANOUT_TIMEOUT_MS);
|
|
772
|
-
timeTimer.unref?.();
|
|
773
|
-
|
|
774
|
-
child.stdout?.on("data", (chunk: Buffer) => {
|
|
775
|
-
outBytes += chunk.length;
|
|
776
|
-
if (outBytes > FANOUT_MAX_BUFFER) {
|
|
777
|
-
terminate("maxBuffer");
|
|
778
|
-
return;
|
|
779
|
-
}
|
|
780
|
-
outChunks.push(chunk);
|
|
781
|
-
});
|
|
782
|
-
child.stderr?.on("data", (chunk: Buffer) => {
|
|
783
|
-
if (errBytes >= FANOUT_MAX_BUFFER) return;
|
|
784
|
-
errBytes += chunk.length;
|
|
785
|
-
errChunks.push(chunk);
|
|
786
|
-
});
|
|
787
|
-
|
|
788
|
-
const cleanup = () => {
|
|
789
|
-
if (timeTimer) clearTimeout(timeTimer);
|
|
790
|
-
// 终止流程里的 SIGKILL 补刀不能取消:close 只代表 bash 退了,
|
|
791
|
-
// 进程组里可能还有 curl/python 在跑。
|
|
792
|
-
if (killTimer && !killed) clearTimeout(killTimer);
|
|
793
|
-
signal?.removeEventListener("abort", onAbort);
|
|
794
|
-
};
|
|
795
|
-
child.on("error", (err) => {
|
|
796
|
-
if (settled) return;
|
|
797
|
-
settled = true;
|
|
798
|
-
cleanup();
|
|
799
|
-
reject(err);
|
|
800
|
-
});
|
|
801
|
-
child.on("close", (code) => {
|
|
802
|
-
if (settled) return;
|
|
803
|
-
settled = true;
|
|
804
|
-
cleanup();
|
|
805
|
-
if (killed === "abort") {
|
|
806
|
-
reject(abortedError());
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
if (killed === "timeout") {
|
|
810
|
-
reject(
|
|
811
|
-
new Error(`d-reach 检索超时(${FANOUT_TIMEOUT_MS / 1000}s),已终止进程组`),
|
|
812
|
-
);
|
|
813
|
-
return;
|
|
814
|
-
}
|
|
815
|
-
if (killed === "maxBuffer") {
|
|
816
|
-
reject(new Error("stdout maxBuffer length exceeded"));
|
|
817
|
-
return;
|
|
818
|
-
}
|
|
819
|
-
const stdout = Buffer.concat(outChunks).toString("utf8");
|
|
820
|
-
const stderr = Buffer.concat(errChunks).toString("utf8");
|
|
821
|
-
if (code !== 0) {
|
|
822
|
-
// 与 execFile 的报错形状保持一致(execute 里只取前 300 字符)
|
|
823
|
-
reject(
|
|
824
|
-
new Error(
|
|
825
|
-
`Command failed: bash ${args.join(" ")}\n${stderr}`.trimEnd(),
|
|
826
|
-
),
|
|
827
|
-
);
|
|
828
|
-
return;
|
|
829
|
-
}
|
|
830
|
-
resolve({ stdout, stderr });
|
|
831
|
-
});
|
|
800
|
+
return runCommand("bash", args, {
|
|
801
|
+
env,
|
|
802
|
+
signal,
|
|
803
|
+
timeoutMs: FANOUT_TIMEOUT_MS,
|
|
804
|
+
maxBuffer: FANOUT_MAX_BUFFER,
|
|
805
|
+
timeoutMessage: `d-reach 检索超时(${FANOUT_TIMEOUT_MS / 1000}s),已终止进程组`,
|
|
832
806
|
});
|
|
833
807
|
}
|
|
834
808
|
|
|
@@ -907,10 +881,9 @@ async function writeSearchCache(
|
|
|
907
881
|
const dir = searchCacheDir();
|
|
908
882
|
try {
|
|
909
883
|
await mkdir(dir, { recursive: true });
|
|
910
|
-
await
|
|
884
|
+
await atomicWriteFile(
|
|
911
885
|
join(dir, `${key}.json`),
|
|
912
886
|
JSON.stringify({ ...entry, ts: Date.now() }),
|
|
913
|
-
"utf8",
|
|
914
887
|
);
|
|
915
888
|
const cutoff = Date.now() - SEARCH_CACHE_KEEP_MS;
|
|
916
889
|
for (const name of await readdir(dir)) {
|
|
@@ -918,7 +891,9 @@ async function writeSearchCache(
|
|
|
918
891
|
const file = join(dir, name);
|
|
919
892
|
try {
|
|
920
893
|
if ((await stat(file)).mtimeMs < cutoff) await unlink(file);
|
|
921
|
-
} catch {
|
|
894
|
+
} catch {
|
|
895
|
+
// 单个缓存文件删不掉不影响本轮检索,下一轮还会再试
|
|
896
|
+
}
|
|
922
897
|
}
|
|
923
898
|
} catch {
|
|
924
899
|
// 缓存写失败不影响检索结果
|
|
@@ -926,19 +901,24 @@ async function writeSearchCache(
|
|
|
926
901
|
}
|
|
927
902
|
|
|
928
903
|
async function persist(md: string, tag: string): Promise<string> {
|
|
929
|
-
|
|
930
|
-
await
|
|
931
|
-
return
|
|
904
|
+
const dst = process.env.D_REACH_LAST_RUN || LAST_RUN;
|
|
905
|
+
await atomicWriteFile(dst, `<!-- ${tag} -->\n${md}`);
|
|
906
|
+
return dst;
|
|
932
907
|
}
|
|
933
908
|
|
|
934
909
|
// ---------------------------------------------------------------- 抓 URL
|
|
935
910
|
|
|
936
911
|
/** 走 load_key.sh 拿 key,与整个技能同一条查找链 */
|
|
937
|
-
async function loadKey(name: string): Promise<string | null> {
|
|
912
|
+
async function loadKey(name: string, signal?: AbortSignal): Promise<string | null> {
|
|
913
|
+
if (signal?.aborted) throw abortedError();
|
|
938
914
|
try {
|
|
939
|
-
const { stdout } = await
|
|
915
|
+
const { stdout } = await runCommand("sh", [KEY_SH, name, ""], {
|
|
916
|
+
timeoutMs: 8000,
|
|
917
|
+
signal,
|
|
918
|
+
});
|
|
940
919
|
return stdout.trim() || null;
|
|
941
|
-
} catch {
|
|
920
|
+
} catch (err) {
|
|
921
|
+
if (isAborted(err, signal)) throw abortedError();
|
|
942
922
|
return null;
|
|
943
923
|
}
|
|
944
924
|
}
|
|
@@ -1112,7 +1092,6 @@ function contentIsReal(text: string): { cls: FailClass; detail: string } | null
|
|
|
1112
1092
|
// 同一个站点上一轮已经确认「要登录 / 撞风控 / 付费墙」,下一轮不必把这套通道再捶一遍。
|
|
1113
1093
|
// 照 Agent-Reach 的后端暂停:只记确定性结论、带 6 小时时效、站点一旦抓通就清空。
|
|
1114
1094
|
// 只按主机名记 —— 登录态和风控是站点级,不是单页级。
|
|
1115
|
-
const DEAD_FILE = join(homedir(), ".agent-reach", "fetch-dead.json");
|
|
1116
1095
|
const DEAD_TTL = 6 * 3600 * 1000;
|
|
1117
1096
|
const DEAD_CLS: FailClass[] = ["login", "antibot", "paywall"];
|
|
1118
1097
|
|
|
@@ -1124,12 +1103,32 @@ function hostOf(url: string): string {
|
|
|
1124
1103
|
}
|
|
1125
1104
|
}
|
|
1126
1105
|
|
|
1106
|
+
function pruneDeadMap(
|
|
1107
|
+
all: Record<string, Record<string, { cls?: string; at?: number }>>,
|
|
1108
|
+
nowMs: number,
|
|
1109
|
+
): Record<string, Record<string, { cls: string; at: number }>> {
|
|
1110
|
+
const cleaned: Record<string, Record<string, { cls: string; at: number }>> = {};
|
|
1111
|
+
for (const [host, stages] of Object.entries(all)) {
|
|
1112
|
+
if (!stages || typeof stages !== "object" || Array.isArray(stages)) continue;
|
|
1113
|
+
const kept: Record<string, { cls: string; at: number }> = {};
|
|
1114
|
+
for (const [stage, rec] of Object.entries(stages)) {
|
|
1115
|
+
if (!rec || typeof rec !== "object") continue;
|
|
1116
|
+
if (!DEAD_CLS.includes(rec.cls as FailClass)) continue;
|
|
1117
|
+
const at = typeof rec.at === "number" ? rec.at : 0;
|
|
1118
|
+
if (nowMs - at >= DEAD_TTL) continue;
|
|
1119
|
+
kept[stage] = { cls: rec.cls as string, at };
|
|
1120
|
+
}
|
|
1121
|
+
if (Object.keys(kept).length) cleaned[host] = kept;
|
|
1122
|
+
}
|
|
1123
|
+
return cleaned;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1127
1126
|
async function loadDead(url: string): Promise<Map<string, FailClass>> {
|
|
1128
1127
|
const host = hostOf(url);
|
|
1129
1128
|
const out = new Map<string, FailClass>();
|
|
1130
1129
|
if (!host) return out;
|
|
1131
1130
|
try {
|
|
1132
|
-
const all = JSON.parse(await readFile(
|
|
1131
|
+
const all = JSON.parse(await readFile(deadFilePath(), "utf8")) as Record<
|
|
1133
1132
|
string,
|
|
1134
1133
|
Record<string, { cls?: string; at?: number }>
|
|
1135
1134
|
>;
|
|
@@ -1147,16 +1146,20 @@ async function loadDead(url: string): Promise<Map<string, FailClass>> {
|
|
|
1147
1146
|
async function saveDead(url: string, stage: string, cls: FailClass): Promise<void> {
|
|
1148
1147
|
const host = hostOf(url);
|
|
1149
1148
|
if (!host || !DEAD_CLS.includes(cls)) return;
|
|
1149
|
+
const deadPath = deadFilePath();
|
|
1150
1150
|
try {
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1151
|
+
await withFileLock(deadPath, async () => {
|
|
1152
|
+
let rawAll: Record<string, Record<string, { cls?: string; at?: number }>> = {};
|
|
1153
|
+
try {
|
|
1154
|
+
rawAll = JSON.parse(await readFile(deadPath, "utf8"));
|
|
1155
|
+
} catch {
|
|
1156
|
+
/* 首次写入 */
|
|
1157
|
+
}
|
|
1158
|
+
const nowMs = Date.now();
|
|
1159
|
+
const all = pruneDeadMap(rawAll, nowMs);
|
|
1160
|
+
all[host] = { ...(all[host] ?? {}), [stage]: { cls, at: nowMs } };
|
|
1161
|
+
await atomicWriteFile(deadPath, JSON.stringify(all, null, 2));
|
|
1162
|
+
});
|
|
1160
1163
|
} catch {
|
|
1161
1164
|
/* 记账失败不影响抓取 */
|
|
1162
1165
|
}
|
|
@@ -1165,11 +1168,22 @@ async function saveDead(url: string, stage: string, cls: FailClass): Promise<voi
|
|
|
1165
1168
|
async function clearDead(url: string): Promise<void> {
|
|
1166
1169
|
const host = hostOf(url);
|
|
1167
1170
|
if (!host) return;
|
|
1171
|
+
const deadPath = deadFilePath();
|
|
1168
1172
|
try {
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
+
await withFileLock(deadPath, async () => {
|
|
1174
|
+
let rawAll: Record<string, Record<string, { cls?: string; at?: number }>> = {};
|
|
1175
|
+
try {
|
|
1176
|
+
rawAll = JSON.parse(await readFile(deadPath, "utf8"));
|
|
1177
|
+
} catch {
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
const nowMs = Date.now();
|
|
1181
|
+
const all = pruneDeadMap(rawAll, nowMs);
|
|
1182
|
+
const hadHost = host in rawAll;
|
|
1183
|
+
delete all[host];
|
|
1184
|
+
if (!hadHost && Object.keys(all).length === Object.keys(rawAll).length) return;
|
|
1185
|
+
await atomicWriteFile(deadPath, JSON.stringify(all, null, 2));
|
|
1186
|
+
});
|
|
1173
1187
|
} catch {
|
|
1174
1188
|
/* ignore */
|
|
1175
1189
|
}
|
|
@@ -1875,28 +1889,76 @@ interface CurlHop {
|
|
|
1875
1889
|
* 刻意不用 -L:跳转由 curlFollow 自己跟,每一跳都要重新做内网校验,
|
|
1876
1890
|
* 否则一个公网 URL 302 到 127.0.0.1 就把本机服务读出来了。
|
|
1877
1891
|
*/
|
|
1892
|
+
function curlResolveArgs(rawUrl: string, targetInfo?: TargetInfo): string[] {
|
|
1893
|
+
if (!targetInfo || isIP(targetInfo.host) || targetInfo.addresses.length === 0) return [];
|
|
1894
|
+
let u: URL;
|
|
1895
|
+
try {
|
|
1896
|
+
u = new URL(rawUrl);
|
|
1897
|
+
} catch {
|
|
1898
|
+
return [];
|
|
1899
|
+
}
|
|
1900
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return [];
|
|
1901
|
+
const port = u.port || (u.protocol === "https:" ? "443" : "80");
|
|
1902
|
+
const addrs = targetInfo.addresses.map((ip) => {
|
|
1903
|
+
const clean = ip.replace(/%.*$/, "");
|
|
1904
|
+
return clean.includes(":") ? `[${clean}]` : clean;
|
|
1905
|
+
});
|
|
1906
|
+
return ["--resolve", `${targetInfo.host}:${port}:${addrs.join(",")}`];
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/** 只允许 http/https,且跳转目标也只能是 http/https:本机 curl 默认开着 file/gopher/ftp/dict。 */
|
|
1910
|
+
const CURL_PROTO_ARGS = ["--proto", "=http,https", "--proto-redir", "=http,https"];
|
|
1911
|
+
|
|
1912
|
+
async function inspectHopUrl(rawUrl: string): Promise<TargetInfo> {
|
|
1913
|
+
let u: URL;
|
|
1914
|
+
try {
|
|
1915
|
+
u = new URL(rawUrl);
|
|
1916
|
+
} catch {
|
|
1917
|
+
throw new StageFail("network", `跳转目标 URL 非法:${rawUrl.slice(0, 120)}`);
|
|
1918
|
+
}
|
|
1919
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
1920
|
+
throw new StageFail("network", `跳转协议不被允许:${u.protocol}`);
|
|
1921
|
+
}
|
|
1922
|
+
try {
|
|
1923
|
+
return await inspectTarget(rawUrl);
|
|
1924
|
+
} catch (e) {
|
|
1925
|
+
if (e instanceof BlockedTarget) {
|
|
1926
|
+
throw new StageFail("network", `跳转被拦下:${e.message}`);
|
|
1927
|
+
}
|
|
1928
|
+
throw new StageFail(
|
|
1929
|
+
"network",
|
|
1930
|
+
`跳转地址校验失败:${e instanceof Error ? e.message.slice(0, 120) : String(e)}`,
|
|
1931
|
+
);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1878
1935
|
async function curlOnce(
|
|
1879
1936
|
target: string,
|
|
1880
1937
|
extraArgs: string[],
|
|
1881
1938
|
outFile: string,
|
|
1939
|
+
signal?: AbortSignal,
|
|
1940
|
+
targetInfo?: TargetInfo,
|
|
1882
1941
|
): Promise<CurlHop> {
|
|
1883
|
-
const
|
|
1942
|
+
const resolveArgs = curlResolveArgs(target, targetInfo);
|
|
1943
|
+
const { stdout } = await runCommand(
|
|
1884
1944
|
"curl",
|
|
1885
1945
|
[
|
|
1886
1946
|
"-s",
|
|
1887
1947
|
"--compressed",
|
|
1948
|
+
...CURL_PROTO_ARGS,
|
|
1888
1949
|
"--max-time",
|
|
1889
1950
|
"15",
|
|
1890
1951
|
"-o",
|
|
1891
1952
|
outFile,
|
|
1892
1953
|
"-A",
|
|
1893
1954
|
UA,
|
|
1955
|
+
...resolveArgs,
|
|
1894
1956
|
...extraArgs,
|
|
1895
1957
|
"-w",
|
|
1896
1958
|
`\n${HTTP_MARK}%{http_code}\t%{content_type}\t%{redirect_url}\t%header{retry-after}`,
|
|
1897
1959
|
target,
|
|
1898
1960
|
],
|
|
1899
|
-
{ maxBuffer: 1 << 20,
|
|
1961
|
+
{ maxBuffer: 1 << 20, timeoutMs: 25_000, signal },
|
|
1900
1962
|
);
|
|
1901
1963
|
const cut = stdout.lastIndexOf(HTTP_MARK);
|
|
1902
1964
|
const meta = cut < 0 ? "" : stdout.slice(cut + HTTP_MARK.length);
|
|
@@ -1924,29 +1986,37 @@ async function curlFollow(
|
|
|
1924
1986
|
* cookie 档用它把 Cookie 限制在匹配域名内 —— 公网跳到第三方(或跳到 http)时不再带 cookie。
|
|
1925
1987
|
*/
|
|
1926
1988
|
argsFor?: (target: string) => string[],
|
|
1989
|
+
signal?: AbortSignal,
|
|
1927
1990
|
): Promise<{ hop: CurlHop; effective: string }> {
|
|
1991
|
+
if (signal?.aborted) throw abortedError();
|
|
1928
1992
|
let effective = start;
|
|
1929
|
-
let
|
|
1993
|
+
let hopInfo = await inspectHopUrl(effective);
|
|
1994
|
+
if (hopInfo.isPrivate && !allowPrivate)
|
|
1995
|
+
throw new StageFail("network", `地址被拦下:${blockedMessage(hopInfo)}`);
|
|
1996
|
+
let hop = await curlOnce(effective, argsFor ? argsFor(effective) : extraArgs, outFile, signal, hopInfo);
|
|
1930
1997
|
for (let n = 0; hop.status >= 300 && hop.status < 400 && hop.status !== 304; ) {
|
|
1998
|
+
if (signal?.aborted) throw abortedError();
|
|
1931
1999
|
if (!hop.redirect)
|
|
1932
2000
|
throw new StageFail("network", `HTTP ${hop.status} 跳转但没给 Location`);
|
|
1933
2001
|
if (++n > 5)
|
|
1934
2002
|
throw new StageFail("network", "重定向超过 5 跳(可能是跳转环)");
|
|
1935
2003
|
const next = hop.redirect;
|
|
1936
|
-
const info = await
|
|
2004
|
+
const info = await inspectHopUrl(next);
|
|
1937
2005
|
// 只有显式 allow_private 时才允许跳进内网
|
|
1938
|
-
if (info
|
|
2006
|
+
if (info.isPrivate && !allowPrivate)
|
|
1939
2007
|
throw new StageFail("network", `跳转被拦下:${blockedMessage(info)}`);
|
|
1940
2008
|
effective = next;
|
|
1941
|
-
|
|
2009
|
+
hopInfo = info;
|
|
2010
|
+
hop = await curlOnce(effective, argsFor ? argsFor(effective) : extraArgs, outFile, signal, hopInfo);
|
|
1942
2011
|
}
|
|
1943
2012
|
return { hop, effective };
|
|
1944
2013
|
}
|
|
1945
2014
|
|
|
1946
|
-
async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | null> {
|
|
1947
|
-
|
|
2015
|
+
async function viaCurl(url: string, allowPrivate = false, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2016
|
+
if (signal?.aborted) throw abortedError();
|
|
2017
|
+
const tmp = join(tmpdir(), `dreach-curl-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
1948
2018
|
try {
|
|
1949
|
-
const followed = await curlFollow(url, [], tmp, allowPrivate);
|
|
2019
|
+
const followed = await curlFollow(url, [], tmp, allowPrivate, undefined, signal);
|
|
1950
2020
|
const { status, ctype, retryAfter } = followed.hop;
|
|
1951
2021
|
const effective = followed.effective;
|
|
1952
2022
|
|
|
@@ -1973,9 +2043,10 @@ async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | nul
|
|
|
1973
2043
|
|
|
1974
2044
|
// PDF:本机有 pymupdf,直接抽文字层。不做这一步就会得到上百万字符的乱码并被判成功。
|
|
1975
2045
|
if (/application\/pdf/.test(ctype)) {
|
|
1976
|
-
const { stdout: pdfOut } = await
|
|
2046
|
+
const { stdout: pdfOut } = await runCommand("python3", [PDF2TEXT, tmp], {
|
|
1977
2047
|
maxBuffer: 32 << 20,
|
|
1978
|
-
|
|
2048
|
+
timeoutMs: 40_000,
|
|
2049
|
+
signal,
|
|
1979
2050
|
});
|
|
1980
2051
|
let parsed: {
|
|
1981
2052
|
ok?: boolean;
|
|
@@ -2058,10 +2129,14 @@ async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | nul
|
|
|
2058
2129
|
async function viaPlaywright(
|
|
2059
2130
|
url: string,
|
|
2060
2131
|
allowPrivate = false,
|
|
2132
|
+
signal?: AbortSignal,
|
|
2061
2133
|
): Promise<Fetched | null> {
|
|
2062
|
-
|
|
2134
|
+
if (signal?.aborted) throw abortedError();
|
|
2135
|
+
const renderArgs = allowPrivate ? [RENDER, url, "--allow-private"] : [RENDER, url];
|
|
2136
|
+
const { stdout } = await runCommand("node", renderArgs, {
|
|
2063
2137
|
maxBuffer: 8 << 20,
|
|
2064
|
-
|
|
2138
|
+
timeoutMs: 40_000,
|
|
2139
|
+
signal,
|
|
2065
2140
|
});
|
|
2066
2141
|
const line = stdout.trim().split("\n").pop() ?? "";
|
|
2067
2142
|
let out: {
|
|
@@ -2080,6 +2155,8 @@ async function viaPlaywright(
|
|
|
2080
2155
|
const err = out.err ?? "";
|
|
2081
2156
|
// 没装 playwright 属于「本机不具备这一档」,不是这个站抓不到
|
|
2082
2157
|
if (/找不到 playwright|Cannot find package/.test(err)) return null;
|
|
2158
|
+
if (err.startsWith("SSRF_BLOCKED:"))
|
|
2159
|
+
throw new StageFail("network", err.replace("SSRF_BLOCKED:", "").trim());
|
|
2083
2160
|
// PDF/图片直链:浏览器只会弹下载,后面七档同样白跑
|
|
2084
2161
|
if (err.startsWith("NOT_A_PAGE"))
|
|
2085
2162
|
throw new StageFail("parse", err.replace("NOT_A_PAGE: ", ""), "binary");
|
|
@@ -2102,8 +2179,8 @@ async function viaPlaywright(
|
|
|
2102
2179
|
// 浏览器自己跟跳转:公网 URL 302 到 127.0.0.1/内网时,页面已经抓回来了,
|
|
2103
2180
|
// 必须在这里补一道校验,否则 SSRF 防护会被「先跳转再渲染」绕过。
|
|
2104
2181
|
if (out.finalUrl && out.finalUrl !== url) {
|
|
2105
|
-
const info = await
|
|
2106
|
-
if (info
|
|
2182
|
+
const info = await inspectHopUrl(out.finalUrl);
|
|
2183
|
+
if (info.isPrivate && !allowPrivate)
|
|
2107
2184
|
throw new StageFail("network", `跳转被拦下:${blockedMessage(info)}`);
|
|
2108
2185
|
}
|
|
2109
2186
|
// 渲染器会跟跳转走:被重定向到 passport./login. 这类域名就是明确的登录墙,
|
|
@@ -2129,8 +2206,8 @@ async function viaPlaywright(
|
|
|
2129
2206
|
return { via: "Playwright 本地渲染", text, chars: text.length };
|
|
2130
2207
|
}
|
|
2131
2208
|
|
|
2132
|
-
async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
2133
|
-
const key = await loadKey("TINYFISH_API_KEY");
|
|
2209
|
+
async function viaTinyfish(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2210
|
+
const key = await loadKey("TINYFISH_API_KEY", signal);
|
|
2134
2211
|
if (!key) return null;
|
|
2135
2212
|
const endpoint = "https://agent.tinyfish.ai/mcp";
|
|
2136
2213
|
const call = async (payload: unknown, sid?: string) => {
|
|
@@ -2140,14 +2217,28 @@ async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
|
2140
2217
|
"X-API-Key": key,
|
|
2141
2218
|
};
|
|
2142
2219
|
if (sid) hdr["Mcp-Session-Id"] = sid;
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2220
|
+
let res: { status: number; headers: Headers; text: string };
|
|
2221
|
+
try {
|
|
2222
|
+
res = await fetchTextWithTimeout(
|
|
2223
|
+
endpoint,
|
|
2224
|
+
{
|
|
2225
|
+
method: "POST",
|
|
2226
|
+
headers: hdr,
|
|
2227
|
+
body: JSON.stringify(payload),
|
|
2228
|
+
},
|
|
2229
|
+
30_000,
|
|
2230
|
+
signal,
|
|
2231
|
+
);
|
|
2232
|
+
} catch (err) {
|
|
2233
|
+
if (isAborted(err, signal)) throw abortedError();
|
|
2234
|
+
if ((err as { code?: string })?.code === "ETIMEDOUT") {
|
|
2235
|
+
throw new StageFail("network", "TinyFish fetch 请求超时(30s)");
|
|
2236
|
+
}
|
|
2237
|
+
throw err;
|
|
2238
|
+
}
|
|
2148
2239
|
return {
|
|
2149
2240
|
sid: res.headers.get("mcp-session-id") ?? undefined,
|
|
2150
|
-
body:
|
|
2241
|
+
body: res.text,
|
|
2151
2242
|
};
|
|
2152
2243
|
};
|
|
2153
2244
|
const init = await call({
|
|
@@ -2209,16 +2300,17 @@ async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
|
2209
2300
|
return { via: "TinyFish fetch", text, chars: text.length };
|
|
2210
2301
|
}
|
|
2211
2302
|
|
|
2212
|
-
async function viaJina(url: string): Promise<Fetched | null> {
|
|
2213
|
-
const key = await loadKey("JINA_API_KEY");
|
|
2303
|
+
async function viaJina(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2304
|
+
const key = await loadKey("JINA_API_KEY", signal);
|
|
2214
2305
|
const call = async (withKey: boolean) => {
|
|
2215
2306
|
const hdr = ["-H", "X-Return-Format: markdown"];
|
|
2216
2307
|
if (withKey && key) hdr.push("-H", `Authorization: Bearer ${key}`);
|
|
2217
|
-
const { stdout } = await
|
|
2308
|
+
const { stdout } = await runCommand(
|
|
2218
2309
|
"curl",
|
|
2219
2310
|
[
|
|
2220
2311
|
"-sL",
|
|
2221
2312
|
"--compressed",
|
|
2313
|
+
...CURL_PROTO_ARGS,
|
|
2222
2314
|
"--max-time",
|
|
2223
2315
|
"25",
|
|
2224
2316
|
"-A",
|
|
@@ -2226,7 +2318,7 @@ async function viaJina(url: string): Promise<Fetched | null> {
|
|
|
2226
2318
|
...hdr,
|
|
2227
2319
|
`https://r.jina.ai/${url}`,
|
|
2228
2320
|
],
|
|
2229
|
-
{ maxBuffer: 8 << 20,
|
|
2321
|
+
{ maxBuffer: 8 << 20, timeoutMs: 30_000, signal },
|
|
2230
2322
|
);
|
|
2231
2323
|
return stdout;
|
|
2232
2324
|
};
|
|
@@ -2246,13 +2338,13 @@ async function viaJina(url: string): Promise<Fetched | null> {
|
|
|
2246
2338
|
return { via: "Jina Reader", text, chars: text.length };
|
|
2247
2339
|
}
|
|
2248
2340
|
|
|
2249
|
-
async function viaMarkdownNew(url: string): Promise<Fetched | null> {
|
|
2341
|
+
async function viaMarkdownNew(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2250
2342
|
// markdown.new:免费、无 key,返回格式与 Jina 几乎一致(Title / URL Source / Markdown Content)。
|
|
2251
2343
|
// 价值在于 Jina 被限流或欠费时的等价备选,所以排在 Jina 之后。
|
|
2252
|
-
const { stdout } = await
|
|
2344
|
+
const { stdout } = await runCommand(
|
|
2253
2345
|
"curl",
|
|
2254
|
-
["-sL", "--compressed", "--max-time", "30", "-A", UA, `https://markdown.new/${url}`],
|
|
2255
|
-
{ maxBuffer: 8 << 20,
|
|
2346
|
+
["-sL", "--compressed", ...CURL_PROTO_ARGS, "--max-time", "30", "-A", UA, `https://markdown.new/${url}`],
|
|
2347
|
+
{ maxBuffer: 8 << 20, timeoutMs: 35_000, signal },
|
|
2256
2348
|
);
|
|
2257
2349
|
const text = stripInlineMedia(stdout).trim();
|
|
2258
2350
|
// 这个服务对抓不到的站会回一段自己的错误说明,不能当正文
|
|
@@ -2263,13 +2355,15 @@ async function viaMarkdownNew(url: string): Promise<Fetched | null> {
|
|
|
2263
2355
|
return { via: "markdown.new", text, chars: text.length };
|
|
2264
2356
|
}
|
|
2265
2357
|
|
|
2266
|
-
async function viaParallelFetch(url: string): Promise<Fetched | null> {
|
|
2358
|
+
async function viaParallelFetch(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2267
2359
|
// Parallel 免费 MCP(无 key、无账号):web_fetch 返回带 excerpts 的正文。
|
|
2268
2360
|
// 与 TinyFish 同为 hosted 服务,放在它后面作独立一路——两家索引不同,一方抽不出另一方可能行。
|
|
2269
2361
|
const args = JSON.stringify({ urls: [url], allow_live_fetch: true });
|
|
2270
|
-
const { stdout } = await
|
|
2362
|
+
const { stdout } = await runCommand("python3", [MCP_CALL, PARALLEL_MCP, "web_fetch", args], {
|
|
2271
2363
|
maxBuffer: 8 << 20,
|
|
2272
|
-
|
|
2364
|
+
timeoutMs: 50_000,
|
|
2365
|
+
env: { ...process.env, D_REACH_MCP_BUDGET: "45" },
|
|
2366
|
+
signal,
|
|
2273
2367
|
});
|
|
2274
2368
|
const raw = stdout.trim();
|
|
2275
2369
|
if (raw.startsWith("MCP_ERROR"))
|
|
@@ -2291,8 +2385,8 @@ async function viaParallelFetch(url: string): Promise<Fetched | null> {
|
|
|
2291
2385
|
return { via: "Parallel fetch", text, chars: text.length };
|
|
2292
2386
|
}
|
|
2293
2387
|
|
|
2294
|
-
async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
2295
|
-
const key = await loadKey("BRIGHTDATA_APITOKEN");
|
|
2388
|
+
async function viaBrightdata(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2389
|
+
const key = await loadKey("BRIGHTDATA_APITOKEN", signal);
|
|
2296
2390
|
if (!key) return null;
|
|
2297
2391
|
// 必须用 format:"json":raw+data_format:"markdown" 会把真实状态码覆盖成 200。
|
|
2298
2392
|
// 实测 example.com/definitely-404-page —— json 档回 status_code:404,markdown 档回 200
|
|
@@ -2303,10 +2397,11 @@ async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
|
2303
2397
|
format: "json",
|
|
2304
2398
|
url,
|
|
2305
2399
|
});
|
|
2306
|
-
const { stdout } = await
|
|
2400
|
+
const { stdout } = await runCommand(
|
|
2307
2401
|
"curl",
|
|
2308
2402
|
[
|
|
2309
2403
|
"-sL",
|
|
2404
|
+
...CURL_PROTO_ARGS,
|
|
2310
2405
|
"--max-time",
|
|
2311
2406
|
"30",
|
|
2312
2407
|
"-X",
|
|
@@ -2319,7 +2414,7 @@ async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
|
2319
2414
|
"-d",
|
|
2320
2415
|
body,
|
|
2321
2416
|
],
|
|
2322
|
-
{ maxBuffer: 8 << 20,
|
|
2417
|
+
{ maxBuffer: 8 << 20, timeoutMs: 35_000, signal },
|
|
2323
2418
|
);
|
|
2324
2419
|
const raw = stdout.trim();
|
|
2325
2420
|
// 错误体不一定以 { 开头:residential 模式的 bad_endpoint 是裸文本,
|
|
@@ -2421,7 +2516,9 @@ function sliceBalancedDiv(html: string, from: number): string {
|
|
|
2421
2516
|
async function viaWeixinDirect(
|
|
2422
2517
|
url: string,
|
|
2423
2518
|
allowPrivate = false,
|
|
2519
|
+
signal?: AbortSignal,
|
|
2424
2520
|
): Promise<Fetched | null> {
|
|
2521
|
+
if (signal?.aborted) throw abortedError();
|
|
2425
2522
|
// 两种链都认:短链 `/s/<token>` 和长链 `/s?__biz=…&sn=…`(后者在历史文章、
|
|
2426
2523
|
// 分享链接里更常见,只认 `/s/` 会让它们绕过专档、去走普通 curl
|
|
2427
2524
|
// 判定落在 host 上而不是整串 URL:`https://evil.example/mp.weixin.qq.com/s/x`
|
|
@@ -2438,10 +2535,10 @@ async function viaWeixinDirect(
|
|
|
2438
2535
|
// 微信的「总目录」类文章实测 8.8MB HTML(1152 条链接),而 execFile 的 maxBuffer
|
|
2439
2536
|
// 上限是 8<<20,多一个字节就抛 `stdout maxBuffer length exceeded` —— 那是个普通 Error,
|
|
2440
2537
|
// 会被归成「解析不出正文」,然后白降到 curl 档只拿到 1745 字(丢掉 1152 条链接)。
|
|
2441
|
-
const tmp = join(tmpdir(), `dreach-wx-${process.pid}-${Date.now()}.body`);
|
|
2538
|
+
const tmp = join(tmpdir(), `dreach-wx-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
2442
2539
|
try {
|
|
2443
2540
|
// 走 curlFollow 而不是 `curl -sL`:微信短链会 302,自动跟随就绕过了逐跳内网校验。
|
|
2444
|
-
const followed = await curlFollow(url, [], tmp, allowPrivate);
|
|
2541
|
+
const followed = await curlFollow(url, [], tmp, allowPrivate, undefined, signal);
|
|
2445
2542
|
const status = followed.hop.status;
|
|
2446
2543
|
if (status === 429 || status === 503)
|
|
2447
2544
|
throw new StageFail("ratelimit", `HTTP ${status}(微信风控限流)`);
|
|
@@ -2492,14 +2589,14 @@ const COOKIE_SLOTS: Array<{ domain: string; slot: string; name: string }> = [
|
|
|
2492
2589
|
* https://feishu.cn.evil.example/ → 命中
|
|
2493
2590
|
* 两者都会把用户飞书 cookie 发给攻击者。cookie 只在对应域名下有值,判定必须落在 host 上。
|
|
2494
2591
|
*/
|
|
2495
|
-
function hostMatchesDomain(rawUrl: string, domain: string): boolean {
|
|
2592
|
+
function hostMatchesDomain(rawUrl: string, domain: string, requireHttps = true): boolean {
|
|
2496
2593
|
let u: URL;
|
|
2497
2594
|
try {
|
|
2498
2595
|
u = new URL(rawUrl);
|
|
2499
2596
|
} catch {
|
|
2500
2597
|
return false;
|
|
2501
2598
|
}
|
|
2502
|
-
if (u.protocol !== "https:") return false;
|
|
2599
|
+
if (requireHttps && u.protocol !== "https:") return false;
|
|
2503
2600
|
const host = normalizeHost(u.hostname);
|
|
2504
2601
|
return host === domain || host.endsWith(`.${domain}`);
|
|
2505
2602
|
}
|
|
@@ -2507,12 +2604,14 @@ function hostMatchesDomain(rawUrl: string, domain: string): boolean {
|
|
|
2507
2604
|
async function viaCookieInject(
|
|
2508
2605
|
url: string,
|
|
2509
2606
|
allowPrivate = false,
|
|
2607
|
+
signal?: AbortSignal,
|
|
2510
2608
|
): Promise<Fetched | null> {
|
|
2609
|
+
if (signal?.aborted) throw abortedError();
|
|
2511
2610
|
// 域名判定只看 hostname:查询参数里塞 feishu.cn、或者 feishu.cn.evil.example
|
|
2512
2611
|
// 都不能让用户 cookie 跟着请求发出去。
|
|
2513
2612
|
const hit = COOKIE_SLOTS.find((s) => hostMatchesDomain(url, s.domain));
|
|
2514
2613
|
if (!hit) return null;
|
|
2515
|
-
const cookie = await loadKey(hit.slot);
|
|
2614
|
+
const cookie = await loadKey(hit.slot, signal);
|
|
2516
2615
|
if (!cookie) {
|
|
2517
2616
|
throw new StageFail(
|
|
2518
2617
|
"nocred",
|
|
@@ -2520,14 +2619,20 @@ async function viaCookieInject(
|
|
|
2520
2619
|
);
|
|
2521
2620
|
}
|
|
2522
2621
|
// 带 cookie 的请求同样自己跟跳转:否则 302 到内网/第三方也会把 cookie 带过去。
|
|
2523
|
-
const tmp = join(tmpdir(), `dreach-cookie-${process.pid}-${Date.now()}.body`);
|
|
2622
|
+
const tmp = join(tmpdir(), `dreach-cookie-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
2524
2623
|
const cookieArgs = ["-H", `Cookie: ${cookie}`, "--max-time", "25"];
|
|
2525
2624
|
let stdout: string;
|
|
2526
2625
|
try {
|
|
2527
2626
|
// 每一跳重新判定:只有仍是该域名下的 https 才带 cookie,
|
|
2528
2627
|
// 否则 302 到 evil.example(或 http)就会把用户 cookie 一起送过去。
|
|
2529
|
-
const followed = await curlFollow(
|
|
2530
|
-
|
|
2628
|
+
const followed = await curlFollow(
|
|
2629
|
+
url,
|
|
2630
|
+
cookieArgs,
|
|
2631
|
+
tmp,
|
|
2632
|
+
allowPrivate,
|
|
2633
|
+
(target) =>
|
|
2634
|
+
hostMatchesDomain(target, hit.domain) ? cookieArgs : ["--max-time", "25"],
|
|
2635
|
+
signal,
|
|
2531
2636
|
);
|
|
2532
2637
|
if (followed.hop.status >= 400)
|
|
2533
2638
|
throw new StageFail("network", `HTTP ${followed.hop.status}`);
|
|
@@ -2545,19 +2650,20 @@ async function viaCookieInject(
|
|
|
2545
2650
|
}
|
|
2546
2651
|
|
|
2547
2652
|
/** 最后一档:公开存档。不改请求头、不冒充爬虫,风险最低的兜底。 */
|
|
2548
|
-
async function viaArchiveToday(url: string): Promise<Fetched | null> {
|
|
2549
|
-
const { stdout } = await
|
|
2653
|
+
async function viaArchiveToday(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2654
|
+
const { stdout } = await runCommand(
|
|
2550
2655
|
"curl",
|
|
2551
2656
|
[
|
|
2552
2657
|
"-sL",
|
|
2553
2658
|
"--compressed",
|
|
2659
|
+
...CURL_PROTO_ARGS,
|
|
2554
2660
|
"--max-time",
|
|
2555
2661
|
"25",
|
|
2556
2662
|
"-A",
|
|
2557
2663
|
UA,
|
|
2558
2664
|
`https://archive.ph/newest/${url}`,
|
|
2559
2665
|
],
|
|
2560
|
-
{ maxBuffer: 8 << 20,
|
|
2666
|
+
{ maxBuffer: 8 << 20, timeoutMs: 30_000, signal },
|
|
2561
2667
|
);
|
|
2562
2668
|
if (
|
|
2563
2669
|
/We don't have that page archived|No results|Page cannot be crawled/i.test(
|
|
@@ -2576,7 +2682,8 @@ async function viaArchiveToday(url: string): Promise<Fetched | null> {
|
|
|
2576
2682
|
* 依次尝试,第一个达标就返回。每一档失败都带分类,全部失败时能说清「该不该重试」。
|
|
2577
2683
|
* 返回 null 表示该档不适用(域名不匹配 / 没配 key),不计入失败。
|
|
2578
2684
|
*/
|
|
2579
|
-
async function fetchUrl(url: string, allowPrivate = false) {
|
|
2685
|
+
async function fetchUrl(url: string, allowPrivate = false, signal?: AbortSignal) {
|
|
2686
|
+
if (signal?.aborted) throw abortedError();
|
|
2580
2687
|
// 国内电商在无登录态下对所有通道都是同一堵墙:实测 2026-11-08 京东商品页
|
|
2581
2688
|
// https://item.jd.com/10230695839309.html 跑完 curl/Playwright/TinyFish/Parallel/Jina
|
|
2582
2689
|
// 五档 78.2s(十档 99.7s)全判「要登录/反爬」,连 https://item.m.jd.com 也会
|
|
@@ -2586,29 +2693,23 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2586
2693
|
"jd.com", "jd.hk", "taobao.com", "tmall.com", "tmall.hk",
|
|
2587
2694
|
"pinduoduo.com", "yangkeduo.com", "1688.com", "suning.com", "vip.com",
|
|
2588
2695
|
];
|
|
2589
|
-
const ecHost = EC_HOSTS.some((h) =>
|
|
2590
|
-
try {
|
|
2591
|
-
return new URL(url).hostname.endsWith(h);
|
|
2592
|
-
} catch {
|
|
2593
|
-
return false;
|
|
2594
|
-
}
|
|
2595
|
-
});
|
|
2696
|
+
const ecHost = EC_HOSTS.some((h) => hostMatchesDomain(url, h, false));
|
|
2596
2697
|
const attempts: Array<[string, () => Promise<Fetched | null>]> = [
|
|
2597
|
-
["微信直连", () => viaWeixinDirect(url, allowPrivate)],
|
|
2598
|
-
["cookie 注入", () => viaCookieInject(url, allowPrivate)],
|
|
2599
|
-
["curl 直连", () => viaCurl(url, allowPrivate)],
|
|
2698
|
+
["微信直连", () => viaWeixinDirect(url, allowPrivate, signal)],
|
|
2699
|
+
["cookie 注入", () => viaCookieInject(url, allowPrivate, signal)],
|
|
2700
|
+
["curl 直连", () => viaCurl(url, allowPrivate, signal)],
|
|
2600
2701
|
...(ecHost
|
|
2601
|
-
? ([["Jina Reader", () => viaJina(url)]] as Array<
|
|
2702
|
+
? ([["Jina Reader", () => viaJina(url, signal)]] as Array<
|
|
2602
2703
|
[string, () => Promise<Fetched | null>]
|
|
2603
2704
|
>)
|
|
2604
2705
|
: ([
|
|
2605
|
-
["Playwright 渲染", () => viaPlaywright(url, allowPrivate)],
|
|
2606
|
-
["TinyFish fetch", () => viaTinyfish(url)],
|
|
2607
|
-
["Parallel fetch", () => viaParallelFetch(url)],
|
|
2608
|
-
["Jina Reader", () => viaJina(url)],
|
|
2609
|
-
["markdown.new", () => viaMarkdownNew(url)],
|
|
2610
|
-
["BrightData", () => viaBrightdata(url)],
|
|
2611
|
-
["archive.today", () => viaArchiveToday(url)],
|
|
2706
|
+
["Playwright 渲染", () => viaPlaywright(url, allowPrivate, signal)],
|
|
2707
|
+
["TinyFish fetch", () => viaTinyfish(url, signal)],
|
|
2708
|
+
["Parallel fetch", () => viaParallelFetch(url, signal)],
|
|
2709
|
+
["Jina Reader", () => viaJina(url, signal)],
|
|
2710
|
+
["markdown.new", () => viaMarkdownNew(url, signal)],
|
|
2711
|
+
["BrightData", () => viaBrightdata(url, signal)],
|
|
2712
|
+
["archive.today", () => viaArchiveToday(url, signal)],
|
|
2612
2713
|
] as Array<[string, () => Promise<Fetched | null>]>) ),
|
|
2613
2714
|
];
|
|
2614
2715
|
/** 本机执行的档:allow_private 只对这几档生效。 */
|
|
@@ -2645,6 +2746,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2645
2746
|
}
|
|
2646
2747
|
throw e;
|
|
2647
2748
|
}
|
|
2749
|
+
if (signal?.aborted) throw abortedError();
|
|
2648
2750
|
if (target.isPrivate) {
|
|
2649
2751
|
if (!allowPrivate) {
|
|
2650
2752
|
const msg = blockedMessage(target);
|
|
@@ -2668,15 +2770,31 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2668
2770
|
// 融合层分流(pi-web-access):GitHub 仓库/文件/PR、YouTube、直链图片走专用通道;
|
|
2669
2771
|
// 放在地址校验之后,内网地址不会进这里。返回 null 表示交还下面的十档。
|
|
2670
2772
|
if (!target.isPrivate) {
|
|
2773
|
+
if (signal?.aborted) throw abortedError();
|
|
2671
2774
|
try {
|
|
2672
|
-
const special = await routeSpecialUrl(url, { maxChars: 200000 });
|
|
2673
|
-
if (special)
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2775
|
+
const special = await routeSpecialUrl(url, { maxChars: 200000, signal });
|
|
2776
|
+
if (special) {
|
|
2777
|
+
if (special.problem) {
|
|
2778
|
+
const cls: FailClass = /凭据|GEMINI_API_KEY|PERPLEXITY_API_KEY/i.test(special.text)
|
|
2779
|
+
? "nocred"
|
|
2780
|
+
: /超时|timed out|ECONNREFUSED|ENOTFOUND|network/i.test(special.text)
|
|
2781
|
+
? "network"
|
|
2782
|
+
: "parse";
|
|
2783
|
+
skipped.push({
|
|
2784
|
+
stage: special.via,
|
|
2785
|
+
cls,
|
|
2786
|
+
detail: special.text.slice(0, 200),
|
|
2787
|
+
});
|
|
2788
|
+
} else {
|
|
2789
|
+
return {
|
|
2790
|
+
ok: true as const,
|
|
2791
|
+
got: { via: special.via, text: special.text, chars: special.chars },
|
|
2792
|
+
skipped,
|
|
2793
|
+
};
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2679
2796
|
} catch (e) {
|
|
2797
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
2680
2798
|
skipped.push({
|
|
2681
2799
|
stage: "专用分流",
|
|
2682
2800
|
cls: "parse",
|
|
@@ -2685,6 +2803,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2685
2803
|
}
|
|
2686
2804
|
}
|
|
2687
2805
|
|
|
2806
|
+
if (signal?.aborted) throw abortedError();
|
|
2688
2807
|
// 上次已确认过不去的档,本轮直接跳过并把原因写进 skipped(用户看到「已确认」,不是「没跑」)
|
|
2689
2808
|
const dead = await loadDead(url);
|
|
2690
2809
|
for (const [stage, cls] of dead) {
|
|
@@ -2697,6 +2816,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2697
2816
|
}
|
|
2698
2817
|
const liveAttempts = liveCandidates.filter(([stage]) => !dead.has(stage));
|
|
2699
2818
|
for (const [stage, fn] of liveAttempts) {
|
|
2819
|
+
if (signal?.aborted) throw abortedError();
|
|
2700
2820
|
try {
|
|
2701
2821
|
const got = await fn();
|
|
2702
2822
|
if (!got) continue;
|
|
@@ -2704,7 +2824,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2704
2824
|
const fake = contentIsReal(got.text);
|
|
2705
2825
|
if (fake) {
|
|
2706
2826
|
skipped.push({ stage, cls: fake.cls, detail: fake.detail });
|
|
2707
|
-
|
|
2827
|
+
await saveDead(url, stage, fake.cls);
|
|
2708
2828
|
if (fake.cls === "login" || fake.cls === "antibot") {
|
|
2709
2829
|
const walls = skipped.filter(
|
|
2710
2830
|
(s) => s.cls === "login" || s.cls === "antibot" || s.cls === "paywall",
|
|
@@ -2713,16 +2833,17 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2713
2833
|
}
|
|
2714
2834
|
continue;
|
|
2715
2835
|
}
|
|
2716
|
-
|
|
2836
|
+
await clearDead(url); // 站点抓通了,旧的死档记录作废
|
|
2717
2837
|
// 截断只在这里做:完整正文交给调用方存盘,避免存进半截内容
|
|
2718
2838
|
return { ok: true as const, got, skipped };
|
|
2719
2839
|
} catch (e) {
|
|
2840
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
2720
2841
|
if (e instanceof StageFail) {
|
|
2721
2842
|
skipped.push({ stage, cls: e.cls, detail: e.detail });
|
|
2722
2843
|
// 429/503 是对「我们这个 IP + 此刻这个节奏」的信号。换通道、换域名格式都没用,
|
|
2723
2844
|
// 唯一正确答案是停下等。实测继续把 TinyFish/Jina/BrightData/archive 走完要 50s+。
|
|
2724
2845
|
if (e.cls === "ratelimit") return bail({ ratelimited: e.detail });
|
|
2725
|
-
if (DEAD_CLS.includes(e.cls))
|
|
2846
|
+
if (DEAD_CLS.includes(e.cls)) await saveDead(url, stage, e.cls);
|
|
2726
2847
|
// 登录墙 / 反爬 / 付费墙是「这个页面」的定性判断:换通道换不来身份和订阅。实测京东商品页
|
|
2727
2848
|
// 十档全败 99.7s,每一档都在说「要登录」。四档都这样判就是定论,剩下的
|
|
2728
2849
|
// Jina / md.new / BrightData / archive 只会再烧 40–60s 和额度。
|
|
@@ -2749,16 +2870,17 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2749
2870
|
/超时|timed out/i.test(e.detail) &&
|
|
2750
2871
|
skipped.filter(
|
|
2751
2872
|
(s) => s.cls === "network" && /超时|timed out/i.test(s.detail),
|
|
2752
|
-
).length >=
|
|
2873
|
+
).length >= 2
|
|
2753
2874
|
)
|
|
2754
2875
|
return bail({ slow: true });
|
|
2755
2876
|
} else {
|
|
2756
|
-
// execFile 抛的错(curl 超时 / HTTP2 stream error / DNS):归 network,不归 parse。
|
|
2877
|
+
// execFile / runCommand 抛的错(curl 超时 / HTTP2 stream error / DNS):归 network,不归 parse。
|
|
2757
2878
|
// 实测 BrightData 对同一 URL 时成时败,失败时 curl 退出码 92(HTTP/2 stream error),
|
|
2758
2879
|
// 说成「解析不出正文」会让人以为内容格式不对。
|
|
2759
2880
|
const err = e as { code?: number | string; message?: string };
|
|
2760
2881
|
const curlCode = typeof err.code === "number" ? err.code : 0;
|
|
2761
2882
|
const isNet =
|
|
2883
|
+
err.code === "ETIMEDOUT" ||
|
|
2762
2884
|
[6, 7, 28, 35, 47, 52, 56, 92].includes(curlCode) ||
|
|
2763
2885
|
/timed out|Could not resolve|Connection (refused|reset)|stream error|TOO_MANY_REDIRECTS|too many redirects|redirect count exceeded/i.test(
|
|
2764
2886
|
err.message ?? "",
|
|
@@ -2768,7 +2890,9 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2768
2890
|
err.message ?? "",
|
|
2769
2891
|
);
|
|
2770
2892
|
const timedOut =
|
|
2771
|
-
|
|
2893
|
+
err.code === "ETIMEDOUT" ||
|
|
2894
|
+
curlCode === 28 ||
|
|
2895
|
+
/timed out/i.test(err.message ?? "");
|
|
2772
2896
|
skipped.push({
|
|
2773
2897
|
stage,
|
|
2774
2898
|
cls: isNet ? "network" : "parse",
|
|
@@ -2801,7 +2925,6 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2801
2925
|
* 同一 URL 的旧快照仍可被 id 精确读到(缓存靠 .json 里的 fetched_at 找最新一份)。
|
|
2802
2926
|
* 24 小时前的文件在启动和每次写入时清理。
|
|
2803
2927
|
*/
|
|
2804
|
-
const STORE_DIR = join(DATA_DIR, "fetch-store");
|
|
2805
2928
|
const STORE_TTL = 24 * 3600 * 1000;
|
|
2806
2929
|
const CACHE_TTL = 15 * 60 * 1000;
|
|
2807
2930
|
|
|
@@ -2812,6 +2935,7 @@ interface StoredMeta {
|
|
|
2812
2935
|
chars: number;
|
|
2813
2936
|
fetched_at: number;
|
|
2814
2937
|
fetched_iso: string;
|
|
2938
|
+
isPrivate?: boolean;
|
|
2815
2939
|
}
|
|
2816
2940
|
|
|
2817
2941
|
/** URL 规范化:只用于「同一页面」判定与缓存键,不改变实际请求的 URL。 */
|
|
@@ -2839,12 +2963,13 @@ function urlKey(url: string): string {
|
|
|
2839
2963
|
}
|
|
2840
2964
|
|
|
2841
2965
|
async function pruneStore(): Promise<void> {
|
|
2966
|
+
const dir = storeDirPath();
|
|
2842
2967
|
try {
|
|
2843
|
-
const names = await readdir(
|
|
2968
|
+
const names = await readdir(dir);
|
|
2844
2969
|
const now = Date.now();
|
|
2845
2970
|
await Promise.all(
|
|
2846
2971
|
names.map(async (n) => {
|
|
2847
|
-
const p = join(
|
|
2972
|
+
const p = join(dir, n);
|
|
2848
2973
|
const st = await stat(p).catch(() => null);
|
|
2849
2974
|
if (st && now - st.mtimeMs > STORE_TTL) await unlink(p).catch(() => {});
|
|
2850
2975
|
}),
|
|
@@ -2855,13 +2980,16 @@ async function pruneStore(): Promise<void> {
|
|
|
2855
2980
|
}
|
|
2856
2981
|
|
|
2857
2982
|
/** 写入一份快照,返回 id 与元数据。写失败不影响本次返回。 */
|
|
2858
|
-
|
|
2983
|
+
// exported for test/integration.mjs(A3 私网快照隔离的单测入口)
|
|
2984
|
+
export async function saveSnapshot(
|
|
2859
2985
|
url: string,
|
|
2860
2986
|
via: string,
|
|
2861
2987
|
text: string,
|
|
2988
|
+
isPrivate?: boolean,
|
|
2862
2989
|
): Promise<StoredMeta | null> {
|
|
2990
|
+
const dir = storeDirPath();
|
|
2863
2991
|
const now = Date.now();
|
|
2864
|
-
const id = `${urlKey(url)}-${now.toString(36)}`;
|
|
2992
|
+
const id = `${urlKey(url)}-${now.toString(36)}-${randomBytes(3).toString("hex")}`;
|
|
2865
2993
|
const meta: StoredMeta = {
|
|
2866
2994
|
id,
|
|
2867
2995
|
url,
|
|
@@ -2869,15 +2997,12 @@ async function saveSnapshot(
|
|
|
2869
2997
|
chars: text.length,
|
|
2870
2998
|
fetched_at: now,
|
|
2871
2999
|
fetched_iso: new Date(now).toISOString(),
|
|
3000
|
+
...(isPrivate !== undefined ? { isPrivate } : {}),
|
|
2872
3001
|
};
|
|
2873
3002
|
try {
|
|
2874
|
-
await mkdir(
|
|
2875
|
-
await
|
|
2876
|
-
await
|
|
2877
|
-
join(STORE_DIR, `${id}.json`),
|
|
2878
|
-
JSON.stringify(meta, null, 2),
|
|
2879
|
-
"utf8",
|
|
2880
|
-
);
|
|
3003
|
+
await mkdir(dir, { recursive: true });
|
|
3004
|
+
await atomicWriteFile(join(dir, `${id}.md`), text);
|
|
3005
|
+
await atomicWriteFile(join(dir, `${id}.json`), JSON.stringify(meta, null, 2));
|
|
2881
3006
|
void pruneStore();
|
|
2882
3007
|
return meta;
|
|
2883
3008
|
} catch {
|
|
@@ -2890,7 +3015,7 @@ async function readMeta(id: string): Promise<StoredMeta | null> {
|
|
|
2890
3015
|
if (!/^[\w-]+$/.test(id)) return null;
|
|
2891
3016
|
try {
|
|
2892
3017
|
return JSON.parse(
|
|
2893
|
-
await readFile(join(
|
|
3018
|
+
await readFile(join(storeDirPath(), `${id}.json`), "utf8"),
|
|
2894
3019
|
) as StoredMeta;
|
|
2895
3020
|
} catch {
|
|
2896
3021
|
return null;
|
|
@@ -2903,22 +3028,27 @@ async function readSnapshot(
|
|
|
2903
3028
|
const meta = await readMeta(id);
|
|
2904
3029
|
if (!meta) return null;
|
|
2905
3030
|
try {
|
|
2906
|
-
return { meta, text: await readFile(join(
|
|
3031
|
+
return { meta, text: await readFile(join(storeDirPath(), `${id}.md`), "utf8") };
|
|
2907
3032
|
} catch {
|
|
2908
3033
|
return null;
|
|
2909
3034
|
}
|
|
2910
3035
|
}
|
|
2911
3036
|
|
|
2912
3037
|
/** 15 分钟内的同 URL 快照(取最新一份)。 */
|
|
2913
|
-
|
|
3038
|
+
// exported for test/integration.mjs
|
|
3039
|
+
export async function findFreshSnapshot(
|
|
3040
|
+
url: string,
|
|
3041
|
+
allowPrivate = false,
|
|
3042
|
+
): Promise<StoredMeta | null> {
|
|
2914
3043
|
const key = urlKey(url);
|
|
2915
3044
|
try {
|
|
2916
|
-
const names = await readdir(
|
|
3045
|
+
const names = await readdir(storeDirPath());
|
|
2917
3046
|
const cands = names.filter((n) => n.startsWith(`${key}-`) && n.endsWith(".json"));
|
|
2918
3047
|
let best: StoredMeta | null = null;
|
|
2919
3048
|
for (const n of cands) {
|
|
2920
3049
|
const m = await readMeta(n.slice(0, -5));
|
|
2921
3050
|
if (!m) continue;
|
|
3051
|
+
if (!allowPrivate && m.isPrivate) continue;
|
|
2922
3052
|
if (Date.now() - m.fetched_at > CACHE_TTL) continue;
|
|
2923
3053
|
if (!best || m.fetched_at > best.fetched_at) best = m;
|
|
2924
3054
|
}
|
|
@@ -2954,7 +3084,7 @@ function sliceText(text: string, offset: number, maxChars: number): Slice {
|
|
|
2954
3084
|
};
|
|
2955
3085
|
}
|
|
2956
3086
|
|
|
2957
|
-
/** find:所有命中位置附近 ±600 字,最多 20 段,标出每段 offset
|
|
3087
|
+
/** find:所有命中位置附近 ±600 字,最多 20 段,标出每段 offset;限制单段与总字符避免高频词撑爆上下文。 */
|
|
2958
3088
|
function findSegments(
|
|
2959
3089
|
text: string,
|
|
2960
3090
|
needle: string,
|
|
@@ -2965,24 +3095,48 @@ function findSegments(
|
|
|
2965
3095
|
if (!q) return [];
|
|
2966
3096
|
const hay = text.toLowerCase();
|
|
2967
3097
|
const pin = q.toLowerCase();
|
|
3098
|
+
const maxSegmentChars = Math.max(radius * 4, 400);
|
|
3099
|
+
const maxTotalChars = 24_000;
|
|
2968
3100
|
const out: Array<{ offset: number; snippet: string }> = [];
|
|
3101
|
+
let totalChars = 0;
|
|
2969
3102
|
let from = 0;
|
|
2970
3103
|
let lastEnd = -1;
|
|
2971
|
-
while (out.length < maxHits) {
|
|
3104
|
+
while (out.length < maxHits && totalChars < maxTotalChars) {
|
|
2972
3105
|
const at = hay.indexOf(pin, from);
|
|
2973
3106
|
if (at < 0) break;
|
|
2974
3107
|
const start = Math.max(0, at - radius);
|
|
2975
3108
|
const end = Math.min(text.length, at + pin.length + radius);
|
|
2976
|
-
// 相邻命中合并成一段,避免同一处重复 20
|
|
2977
|
-
if (start <= lastEnd) {
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
lastEnd
|
|
2981
|
-
|
|
3109
|
+
// 相邻命中合并成一段,避免同一处重复 20 次;超过单段上限后不再延长,避免整页合并
|
|
3110
|
+
if (start <= lastEnd && out.length > 0) {
|
|
3111
|
+
const prev = out[out.length - 1];
|
|
3112
|
+
const prevCap = prev.offset + maxSegmentChars;
|
|
3113
|
+
if (lastEnd < prevCap) {
|
|
3114
|
+
const targetEnd = Math.min(end, prevCap, lastEnd + (maxTotalChars - totalChars));
|
|
3115
|
+
if (targetEnd > lastEnd) {
|
|
3116
|
+
prev.snippet = text.slice(prev.offset, targetEnd);
|
|
3117
|
+
totalChars += targetEnd - lastEnd;
|
|
3118
|
+
lastEnd = targetEnd;
|
|
3119
|
+
}
|
|
3120
|
+
from = at + pin.length;
|
|
3121
|
+
continue;
|
|
3122
|
+
}
|
|
3123
|
+
if (at < lastEnd) {
|
|
3124
|
+
from = lastEnd;
|
|
3125
|
+
continue;
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
const segStart = Math.max(start, lastEnd);
|
|
3129
|
+
const avail = maxTotalChars - totalChars;
|
|
3130
|
+
if (avail <= 0) break;
|
|
3131
|
+
const segEnd = Math.min(end, segStart + maxSegmentChars, segStart + avail);
|
|
3132
|
+
if (segEnd <= segStart) {
|
|
3133
|
+
from = Math.max(at + pin.length, lastEnd);
|
|
2982
3134
|
continue;
|
|
2983
3135
|
}
|
|
2984
|
-
|
|
2985
|
-
|
|
3136
|
+
const snippet = text.slice(segStart, segEnd);
|
|
3137
|
+
out.push({ offset: segStart, snippet });
|
|
3138
|
+
totalChars += snippet.length;
|
|
3139
|
+
lastEnd = segEnd;
|
|
2986
3140
|
from = at + pin.length;
|
|
2987
3141
|
}
|
|
2988
3142
|
return out;
|
|
@@ -3048,8 +3202,8 @@ const searchTool = defineTool({
|
|
|
3048
3202
|
"通用网页通道(tf/parallel/youcom/anysearch/tavily/serper/brave/fcs/exa/langsearch)中英各查一遍;" +
|
|
3049
3203
|
"社区/垂直站只用本站语言(知乎/掘金/SegmentFault/千帆/小红书/B站吃中文,StackExchange/HN/GitHub/OpenAlex/Crossref/Firecrawl 开发者与论文索引吃英文)。" +
|
|
3050
3204
|
"结果跨源去重合并排序,每条标〔中/英/中英〕,头部写中英各几条。" +
|
|
3051
|
-
"profile=auto(默认)= 固定底座 tf+parallel+
|
|
3052
|
-
"(gh 仓库 / oalex,fcres 论文 / se,fcdev 排障 / hn / jj,segfault / xhs,bili,zhihu 口碑 / wiki / qianfan,zhihuall / langsearch / serper
|
|
3205
|
+
"profile=auto(默认)= 固定底座 tf+parallel+anysearch+tavily(纯免费)+ 模型按意图补 0-3 个专项通道" +
|
|
3206
|
+
"(gh 仓库 / oalex,fcres 论文 / se,fcdev 排障 / hn / jj,segfault / xhs,bili,zhihu 口碑 / wiki / qianfan,zhihuall / langsearch / serper / youcom 按需快搜)。" +
|
|
3053
3207
|
"规则覆盖不到时用 channels 显式指定(如 channels='hn,exa');显式 channels 是本轮白名单,不改默认清单。" +
|
|
3054
3208
|
"调研纪律(做方案调研/选型时):第一轮 query 禁止含产品名或技术栈(llama.cpp、Ollama、模型名、框架名、某库名),只写约束(硬件、平台、任务、时间、预算);先扫出 ≥3 个候选并列进表,再深挖单个选手。不确定该用哪家时,产品名一进 query 就把答案锁死了。" +
|
|
3055
3209
|
"执行纪律:一次铺开并发跑(串行单路再补查是浪费轮次),铺开结果出来前不下结论;" +
|
|
@@ -3069,7 +3223,7 @@ const searchTool = defineTool({
|
|
|
3069
3223
|
],
|
|
3070
3224
|
{
|
|
3071
3225
|
description:
|
|
3072
|
-
"auto=免费底座
|
|
3226
|
+
"auto=免费底座 4 路 + 模型补 0-3 个专项(默认);quick=3 路候选;base=22 条注册路由;deep=27 条注册路由;实际请求数受默认启用清单影响;任何档位都中英双查",
|
|
3073
3227
|
},
|
|
3074
3228
|
),
|
|
3075
3229
|
),
|
|
@@ -3233,7 +3387,7 @@ const searchTool = defineTool({
|
|
|
3233
3387
|
"fcdev 官方文档 / se 报错 / hn 技术观点 / jj,segfault 中文技术(仅技术) / " +
|
|
3234
3388
|
"oalex,crossref 学术元数据 / langsearch 时效 / exa 英文语义 / " +
|
|
3235
3389
|
"fcres 论文全文 / serper Google(本地生活/电商) / fcs Firecrawl v2 Search / wiki 维基百科 / " +
|
|
3236
|
-
"tavily 全网正文摘录(免key) / parallel 语义(免key) / youcom 快搜(
|
|
3390
|
+
"tavily 全网正文摘录(免key) / parallel 语义(免key) / youcom 快搜(按需/有key付费REST/无key兜底MCP) / " +
|
|
3237
3391
|
"anysearch 垂直专库 / gh GitHub 仓库 / xhs 国内版小红书 / bili B站";
|
|
3238
3392
|
const head =
|
|
3239
3393
|
`d-reach ${PROFILES[profile].label} · ${secs.toFixed(1)}s` +
|
|
@@ -3349,7 +3503,13 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3349
3503
|
),
|
|
3350
3504
|
}),
|
|
3351
3505
|
|
|
3352
|
-
async execute(_id, params: FetchParams) {
|
|
3506
|
+
async execute(_id, params: FetchParams, signal?: AbortSignal) {
|
|
3507
|
+
if (signal?.aborted) {
|
|
3508
|
+
return {
|
|
3509
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3510
|
+
details: { aborted: true },
|
|
3511
|
+
};
|
|
3512
|
+
}
|
|
3353
3513
|
const maxChars = Math.min(Math.max(params.max_chars ?? 12000, 500), 40000);
|
|
3354
3514
|
const offset = Math.max(Math.floor(params.offset ?? 0), 0);
|
|
3355
3515
|
const url = (params.url ?? "").trim();
|
|
@@ -3426,16 +3586,71 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3426
3586
|
return serveStored(snap, false);
|
|
3427
3587
|
}
|
|
3428
3588
|
|
|
3589
|
+
const allowPrivate = params.allow_private === true;
|
|
3590
|
+
let urlIsPrivate = false;
|
|
3591
|
+
if (url) {
|
|
3592
|
+
let target: TargetInfo;
|
|
3593
|
+
try {
|
|
3594
|
+
target = await inspectTarget(url);
|
|
3595
|
+
} catch (e) {
|
|
3596
|
+
if (e instanceof BlockedTarget) {
|
|
3597
|
+
return {
|
|
3598
|
+
content: [
|
|
3599
|
+
{
|
|
3600
|
+
type: "text" as const,
|
|
3601
|
+
text: `抓取失败:${url}\n- 地址校验:网络不通 — ${e.message}\n\n**已拒绝**:这是安全策略拦截,不是抓取失败。确认目标可信后再考虑 allow_private。`,
|
|
3602
|
+
},
|
|
3603
|
+
],
|
|
3604
|
+
details: { url, blocked: e.message },
|
|
3605
|
+
isError: true,
|
|
3606
|
+
};
|
|
3607
|
+
}
|
|
3608
|
+
throw e;
|
|
3609
|
+
}
|
|
3610
|
+
urlIsPrivate = target.isPrivate;
|
|
3611
|
+
if (target.isPrivate && !allowPrivate) {
|
|
3612
|
+
const msg = blockedMessage(target);
|
|
3613
|
+
return {
|
|
3614
|
+
content: [
|
|
3615
|
+
{
|
|
3616
|
+
type: "text" as const,
|
|
3617
|
+
text: `抓取失败:${url}\n- 地址校验:网络不通 — ${msg}\n\n**已拒绝**:这是安全策略拦截,不是抓取失败。确认目标可信后再考虑 allow_private。`,
|
|
3618
|
+
},
|
|
3619
|
+
],
|
|
3620
|
+
details: { url, blocked: msg },
|
|
3621
|
+
isError: true,
|
|
3622
|
+
};
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3429
3626
|
// 15 分钟缓存:同一 URL(规范化后)直接复用存盘
|
|
3430
3627
|
if (!params.fresh) {
|
|
3431
|
-
const hit = await findFreshSnapshot(url);
|
|
3628
|
+
const hit = await findFreshSnapshot(url, allowPrivate);
|
|
3432
3629
|
if (hit) {
|
|
3433
3630
|
const snap = await readSnapshot(hit.id);
|
|
3434
|
-
if (snap
|
|
3631
|
+
if (snap && (allowPrivate || !snap.meta.isPrivate))
|
|
3632
|
+
return serveStored(snap, true);
|
|
3435
3633
|
}
|
|
3436
3634
|
}
|
|
3437
3635
|
|
|
3438
|
-
|
|
3636
|
+
let r: Awaited<ReturnType<typeof fetchUrl>>;
|
|
3637
|
+
try {
|
|
3638
|
+
r = await fetchUrl(url, allowPrivate, signal);
|
|
3639
|
+
} catch (err) {
|
|
3640
|
+
if (isAborted(err, signal)) {
|
|
3641
|
+
return {
|
|
3642
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3643
|
+
details: { aborted: true },
|
|
3644
|
+
};
|
|
3645
|
+
}
|
|
3646
|
+
throw err;
|
|
3647
|
+
}
|
|
3648
|
+
if (signal?.aborted) {
|
|
3649
|
+
return {
|
|
3650
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3651
|
+
details: { aborted: true },
|
|
3652
|
+
};
|
|
3653
|
+
}
|
|
3439
3654
|
const secs = ((Date.now() - t0) / 1000).toFixed(1);
|
|
3440
3655
|
|
|
3441
3656
|
if (!r.ok) {
|
|
@@ -3493,7 +3708,7 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3493
3708
|
|
|
3494
3709
|
// 完整正文(截断前)先落盘,再按 offset/max_chars 切片返回
|
|
3495
3710
|
const meta =
|
|
3496
|
-
(await saveSnapshot(url, r.got.via, r.got.text)) ?? {
|
|
3711
|
+
(await saveSnapshot(url, r.got.via, r.got.text, urlIsPrivate)) ?? {
|
|
3497
3712
|
id: "(未存盘)",
|
|
3498
3713
|
url,
|
|
3499
3714
|
via: r.got.via,
|
|
@@ -3546,11 +3761,26 @@ const quotaTool = defineTool({
|
|
|
3546
3761
|
),
|
|
3547
3762
|
}),
|
|
3548
3763
|
|
|
3549
|
-
async execute(_id, params) {
|
|
3764
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
3765
|
+
if (signal?.aborted) {
|
|
3766
|
+
return {
|
|
3767
|
+
content: [{ type: "text", text: "已中止" }],
|
|
3768
|
+
details: { aborted: true },
|
|
3769
|
+
};
|
|
3770
|
+
}
|
|
3550
3771
|
if (params.refresh) {
|
|
3551
3772
|
try {
|
|
3552
|
-
await
|
|
3553
|
-
|
|
3773
|
+
await runCommand("python3", [PROBE, "--max-age", "0"], {
|
|
3774
|
+
timeoutMs: 30_000,
|
|
3775
|
+
signal,
|
|
3776
|
+
});
|
|
3777
|
+
} catch (err) {
|
|
3778
|
+
if (isAborted(err, signal)) {
|
|
3779
|
+
return {
|
|
3780
|
+
content: [{ type: "text", text: "已中止" }],
|
|
3781
|
+
details: { aborted: true },
|
|
3782
|
+
};
|
|
3783
|
+
}
|
|
3554
3784
|
/* 校准失败不影响本地账本展示 */
|
|
3555
3785
|
}
|
|
3556
3786
|
}
|
|
@@ -3561,82 +3791,19 @@ const quotaTool = defineTool({
|
|
|
3561
3791
|
return {};
|
|
3562
3792
|
}
|
|
3563
3793
|
};
|
|
3564
|
-
const quota = await readJson(
|
|
3565
|
-
const health = await readJson(
|
|
3566
|
-
const
|
|
3567
|
-
string,
|
|
3568
|
-
{
|
|
3569
|
-
state?: string;
|
|
3570
|
-
remaining?: number;
|
|
3571
|
-
total?: number;
|
|
3572
|
-
balance?: string;
|
|
3573
|
-
currency?: string;
|
|
3574
|
-
probed_at?: string;
|
|
3575
|
-
items?: { id?: string; name?: string; remaining?: number; total?: number; used?: number }[];
|
|
3576
|
-
}
|
|
3577
|
-
>;
|
|
3578
|
-
|
|
3579
|
-
// bd(BrightData Google)已从搜索档位移除;它的历史记录不代表当前 fanout 通道健康状态。
|
|
3580
|
-
const RETIRED = new Set(["bd"]);
|
|
3581
|
-
type HRec = { streak_fail?: number; code?: string; last_ok?: string };
|
|
3582
|
-
const NEED_TITLE: Record<string, string> = {
|
|
3583
|
-
login: "要登录",
|
|
3584
|
-
antibot: "要过验证码",
|
|
3585
|
-
auth: "凭据失效",
|
|
3586
|
-
ratelimit: "限流中",
|
|
3587
|
-
notfound: "端点失效",
|
|
3588
|
-
setup: "依赖缺失",
|
|
3589
|
-
};
|
|
3590
|
-
// 两类要分开报:连败是「它自己坏了、等退避」,code 是「确定性结论、要人出手」。
|
|
3591
|
-
const bad: string[] = [];
|
|
3592
|
-
const need: string[] = [];
|
|
3593
|
-
for (const [k, v] of Object.entries(health)) {
|
|
3594
|
-
if (RETIRED.has(k)) continue;
|
|
3595
|
-
const rec = v as HRec;
|
|
3596
|
-
if (rec.code && NEED_TITLE[rec.code]) need.push(`${k}(${NEED_TITLE[rec.code]})`);
|
|
3597
|
-
else if ((rec.streak_fail ?? 0) >= 3 && rec.last_ok) bad.push(k);
|
|
3598
|
-
}
|
|
3599
|
-
|
|
3600
|
-
const unverifiedCount = Object.entries(health).filter(
|
|
3601
|
-
([k, v]) => !RETIRED.has(k) && !(v as HRec)?.last_ok,
|
|
3602
|
-
).length;
|
|
3603
|
-
const lines: string[] = [
|
|
3604
|
-
"通道健康:",
|
|
3605
|
-
bad.length
|
|
3606
|
-
? ` 已验证后连败 ≥3(下轮自动跳过):${bad.join(", ")}`
|
|
3607
|
-
: " 没有已验证渠道达到连败阈值(未验证不等于正常)",
|
|
3608
|
-
];
|
|
3609
|
-
if (unverifiedCount) lines.push(` 无成功记录/未验证:${unverifiedCount} 路`);
|
|
3610
|
-
if (need.length) lines.push(` 要你出手:${need.join("、")}`);
|
|
3611
|
-
lines.push("", "限额通道:");
|
|
3612
|
-
for (const [svc, v] of Object.entries(quota)) {
|
|
3613
|
-
if (svc.startsWith("_") || typeof v !== "object" || v === null) continue;
|
|
3614
|
-
const used = (v as { monthly?: number }).monthly ?? 0;
|
|
3615
|
-
const off = official[svc];
|
|
3616
|
-
const tail =
|
|
3617
|
-
off?.state === "ok" && svc === "firecrawl"
|
|
3618
|
-
? ` | 官方剩余 ${off.remaining}/${off.total}`
|
|
3619
|
-
: off?.state === "ok" && svc === "tinyfish"
|
|
3620
|
-
? ` | 钱包 ${off.balance} ${off.currency}`
|
|
3621
|
-
: off?.state === "unavailable" || off?.state === "no_permission"
|
|
3622
|
-
? " | 官方查不到"
|
|
3623
|
-
: "";
|
|
3624
|
-
lines.push(` ${svc}: 本月已用 ${used}${tail}`);
|
|
3625
|
-
}
|
|
3626
|
-
const stamp = Object.values(official)[0]?.probed_at;
|
|
3627
|
-
// 知乎开放平台:9 项能力各自独立日额度,官方接口实时返回,不占限额通道
|
|
3628
|
-
const zh = official.zhihu;
|
|
3629
|
-
if (zh?.state === "ok" && zh.items?.length) {
|
|
3630
|
-
lines.push("", "知乎开放平台(当日限免):");
|
|
3631
|
-
for (const it of zh.items) {
|
|
3632
|
-
lines.push(` ${it.name}: ${it.remaining}/${it.total}`);
|
|
3633
|
-
}
|
|
3634
|
-
}
|
|
3635
|
-
if (stamp)
|
|
3636
|
-
lines.push("", `官方数据时间:${stamp.slice(0, 16).replace("T", " ")}`);
|
|
3794
|
+
const quota = await readJson(quotaFilePath());
|
|
3795
|
+
const health = await readJson(healthFilePath());
|
|
3796
|
+
const summary = summarizeQuotaAndHealth(quota, health);
|
|
3637
3797
|
return {
|
|
3638
|
-
content: [{ type: "text", text: lines.join("\n") }],
|
|
3639
|
-
details: {
|
|
3798
|
+
content: [{ type: "text", text: summary.lines.join("\n") }],
|
|
3799
|
+
details: {
|
|
3800
|
+
quota: summary.normalizedQuota,
|
|
3801
|
+
health,
|
|
3802
|
+
rows: summary.rows,
|
|
3803
|
+
suspended: summary.bad,
|
|
3804
|
+
needsAction: summary.need,
|
|
3805
|
+
expiredSuspensions: summary.expiredSuspensions,
|
|
3806
|
+
},
|
|
3640
3807
|
};
|
|
3641
3808
|
},
|
|
3642
3809
|
});
|
|
@@ -3651,9 +3818,11 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3651
3818
|
pi.registerTool(decideTool);
|
|
3652
3819
|
// 融合层(pwa.ts):d_reach_check / d_reach_video;GitHub 与视频分流入口为 routeSpecialUrl
|
|
3653
3820
|
// 第二参数是 allowPrivate:融合层抓取一律按公网规则,绝不放行内网
|
|
3654
|
-
registerPwaTools(pi, (u: string
|
|
3821
|
+
registerPwaTools(pi, (u: string, _maxChars?: number, signal?: AbortSignal) =>
|
|
3822
|
+
fetchUrl(u, false, signal),
|
|
3823
|
+
);
|
|
3655
3824
|
|
|
3656
|
-
const
|
|
3825
|
+
const runSlashSearch = async (args: string, ctx: any, profile: Profile) => {
|
|
3657
3826
|
const query = args.trim();
|
|
3658
3827
|
if (!query) return ctx.ui.notify("用法:/reach <检索词>", "warning");
|
|
3659
3828
|
ctx.ui.notify(`d-reach ${profile} 检索中:${query}`, "info");
|
|
@@ -3670,6 +3839,10 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3670
3839
|
"info",
|
|
3671
3840
|
);
|
|
3672
3841
|
} catch (err) {
|
|
3842
|
+
if (isAborted(err, ctx?.signal)) {
|
|
3843
|
+
ctx.ui.notify("已中止", "warning");
|
|
3844
|
+
return;
|
|
3845
|
+
}
|
|
3673
3846
|
ctx.ui.notify(
|
|
3674
3847
|
`失败:${err instanceof Error ? err.message : String(err)}`,
|
|
3675
3848
|
"error",
|
|
@@ -3679,11 +3852,11 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3679
3852
|
|
|
3680
3853
|
pi.registerCommand("reach", {
|
|
3681
3854
|
description: "d-reach 检索(auto 按意图选路)",
|
|
3682
|
-
handler: (args, ctx) =>
|
|
3855
|
+
handler: (args, ctx) => runSlashSearch(args, ctx, "auto"),
|
|
3683
3856
|
});
|
|
3684
3857
|
pi.registerCommand("reach-deep", {
|
|
3685
3858
|
description: "d-reach 检索(deep 27 路含限额通道)",
|
|
3686
|
-
handler: (args, ctx) =>
|
|
3859
|
+
handler: (args, ctx) => runSlashSearch(args, ctx, "deep"),
|
|
3687
3860
|
});
|
|
3688
3861
|
}
|
|
3689
3862
|
|
|
@@ -3733,12 +3906,14 @@ const SOCIAL = {
|
|
|
3733
3906
|
type SocialPlatform = keyof typeof SOCIAL;
|
|
3734
3907
|
const SOCIAL_LABEL: Record<SocialPlatform, string> = { bili: "B站", xhs: "小红书" };
|
|
3735
3908
|
|
|
3736
|
-
async function probeSocial(p: SocialPlatform) {
|
|
3909
|
+
async function probeSocial(p: SocialPlatform, signal?: AbortSignal) {
|
|
3910
|
+
if (signal?.aborted) throw abortedError();
|
|
3737
3911
|
const meta = SOCIAL[p];
|
|
3738
3912
|
let installed = true;
|
|
3739
3913
|
try {
|
|
3740
|
-
await
|
|
3741
|
-
} catch {
|
|
3914
|
+
await runCommand(meta.bin, ["--version"], { timeoutMs: 6000, signal });
|
|
3915
|
+
} catch (e) {
|
|
3916
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3742
3917
|
installed = false;
|
|
3743
3918
|
}
|
|
3744
3919
|
if (!installed)
|
|
@@ -3750,21 +3925,25 @@ async function probeSocial(p: SocialPlatform) {
|
|
|
3750
3925
|
|
|
3751
3926
|
let authFileAge: string | null = null;
|
|
3752
3927
|
try {
|
|
3753
|
-
const { stdout } = await
|
|
3754
|
-
|
|
3928
|
+
const { stdout } = await runCommand("stat", ["-c", "%y", meta.authFile], {
|
|
3929
|
+
timeoutMs: 5000,
|
|
3930
|
+
signal,
|
|
3755
3931
|
});
|
|
3756
3932
|
authFileAge = stdout.trim().slice(0, 10);
|
|
3757
|
-
} catch {
|
|
3933
|
+
} catch (e) {
|
|
3934
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3758
3935
|
/* 文件不存在也算信息 */
|
|
3759
3936
|
}
|
|
3760
3937
|
|
|
3761
3938
|
let out = "";
|
|
3762
3939
|
try {
|
|
3763
|
-
const r = await
|
|
3764
|
-
|
|
3940
|
+
const r = await runCommand(meta.bin, meta.whoami.slice(1), {
|
|
3941
|
+
timeoutMs: 25_000,
|
|
3942
|
+
signal,
|
|
3765
3943
|
});
|
|
3766
3944
|
out = r.stdout + r.stderr;
|
|
3767
3945
|
} catch (e) {
|
|
3946
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3768
3947
|
// 未登录时通常非 0 退出码,真因在 stdout/stderr 里,别把 "Command failed" 当结论
|
|
3769
3948
|
out =
|
|
3770
3949
|
String((e as { stdout?: string; stderr?: string })?.stdout ?? "") +
|
|
@@ -3848,11 +4027,28 @@ const socialTool = defineTool({
|
|
|
3848
4027
|
),
|
|
3849
4028
|
}),
|
|
3850
4029
|
|
|
3851
|
-
async execute(_id, params) {
|
|
4030
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
4031
|
+
if (signal?.aborted) {
|
|
4032
|
+
return {
|
|
4033
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4034
|
+
details: { aborted: true },
|
|
4035
|
+
};
|
|
4036
|
+
}
|
|
3852
4037
|
const platforms = params.platform
|
|
3853
4038
|
? [params.platform]
|
|
3854
4039
|
: (["bili", "xhs"] as SocialPlatform[]);
|
|
3855
|
-
|
|
4040
|
+
let probes: Awaited<ReturnType<typeof probeSocial>>[];
|
|
4041
|
+
try {
|
|
4042
|
+
probes = await Promise.all(platforms.map((p) => probeSocial(p, signal)));
|
|
4043
|
+
} catch (e) {
|
|
4044
|
+
if (isAborted(e, signal)) {
|
|
4045
|
+
return {
|
|
4046
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4047
|
+
details: { aborted: true },
|
|
4048
|
+
};
|
|
4049
|
+
}
|
|
4050
|
+
throw e;
|
|
4051
|
+
}
|
|
3856
4052
|
|
|
3857
4053
|
const lines: string[] = [];
|
|
3858
4054
|
for (const pr of probes) {
|
|
@@ -3899,12 +4095,13 @@ const socialTool = defineTool({
|
|
|
3899
4095
|
const n = Math.min(Math.max(params.limit ?? 8, 1), 20);
|
|
3900
4096
|
const meta = SOCIAL[target.platform];
|
|
3901
4097
|
try {
|
|
3902
|
-
const { stdout } = await
|
|
4098
|
+
const { stdout } = await runCommand(
|
|
3903
4099
|
meta.bin,
|
|
3904
4100
|
meta.search(params.query, n).slice(1),
|
|
3905
4101
|
{
|
|
3906
|
-
|
|
4102
|
+
timeoutMs: 40_000,
|
|
3907
4103
|
maxBuffer: 4 << 20,
|
|
4104
|
+
signal,
|
|
3908
4105
|
},
|
|
3909
4106
|
);
|
|
3910
4107
|
let rendered = stdout.trim();
|
|
@@ -3912,7 +4109,9 @@ const socialTool = defineTool({
|
|
|
3912
4109
|
const parsed = JSON.parse(rendered) as { data?: any; result?: any };
|
|
3913
4110
|
rendered = renderSocial(target.platform, parsed);
|
|
3914
4111
|
} catch {
|
|
3915
|
-
|
|
4112
|
+
if (rendered.length > 12_000) {
|
|
4113
|
+
rendered = `${rendered.slice(0, 12_000)}\n…(已截断)`;
|
|
4114
|
+
}
|
|
3916
4115
|
}
|
|
3917
4116
|
return {
|
|
3918
4117
|
content: [
|
|
@@ -3924,6 +4123,12 @@ const socialTool = defineTool({
|
|
|
3924
4123
|
details: { platform: target.platform, query: params.query, limit: n },
|
|
3925
4124
|
};
|
|
3926
4125
|
} catch (e) {
|
|
4126
|
+
if (isAborted(e, signal)) {
|
|
4127
|
+
return {
|
|
4128
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4129
|
+
details: { aborted: true },
|
|
4130
|
+
};
|
|
4131
|
+
}
|
|
3927
4132
|
return {
|
|
3928
4133
|
content: [
|
|
3929
4134
|
{
|
|
@@ -3981,7 +4186,13 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
3981
4186
|
),
|
|
3982
4187
|
}),
|
|
3983
4188
|
|
|
3984
|
-
async execute(_id, params) {
|
|
4189
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
4190
|
+
if (signal?.aborted) {
|
|
4191
|
+
return {
|
|
4192
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4193
|
+
details: { aborted: true },
|
|
4194
|
+
};
|
|
4195
|
+
}
|
|
3985
4196
|
const questions: Record<string, unknown> = {};
|
|
3986
4197
|
for (const q of params.questions) {
|
|
3987
4198
|
const spec: Record<string, unknown> = {
|
|
@@ -3994,7 +4205,7 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
3994
4205
|
}
|
|
3995
4206
|
|
|
3996
4207
|
try {
|
|
3997
|
-
const { stdout } = await
|
|
4208
|
+
const { stdout } = await runCommand(
|
|
3998
4209
|
"python3",
|
|
3999
4210
|
[
|
|
4000
4211
|
MCP_CALL,
|
|
@@ -4002,7 +4213,12 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
4002
4213
|
"web_decisions",
|
|
4003
4214
|
JSON.stringify({ state: { topic: params.state }, questions }),
|
|
4004
4215
|
],
|
|
4005
|
-
{
|
|
4216
|
+
{
|
|
4217
|
+
maxBuffer: 8 << 20,
|
|
4218
|
+
timeoutMs: 90_000,
|
|
4219
|
+
env: { ...process.env, D_REACH_MCP_BUDGET: "85" },
|
|
4220
|
+
signal,
|
|
4221
|
+
},
|
|
4006
4222
|
);
|
|
4007
4223
|
const raw = stdout.trim();
|
|
4008
4224
|
if (raw.startsWith("MCP_ERROR")) {
|
|
@@ -4081,6 +4297,12 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
4081
4297
|
details: { state: params.state, answers: d.answers, citations: cites },
|
|
4082
4298
|
};
|
|
4083
4299
|
} catch (e) {
|
|
4300
|
+
if (isAborted(e, signal)) {
|
|
4301
|
+
return {
|
|
4302
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4303
|
+
details: { aborted: true },
|
|
4304
|
+
};
|
|
4305
|
+
}
|
|
4084
4306
|
return {
|
|
4085
4307
|
content: [
|
|
4086
4308
|
{
|