@duanz/pi-d-reach 1.0.1 → 1.0.3
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 +636 -403
- package/plugin/pwa.ts +142 -25
- 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
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
|
|
|
@@ -877,6 +851,7 @@ function searchCacheKey(parts: {
|
|
|
877
851
|
domains: (parts.domains ?? [])
|
|
878
852
|
.map((d) => d.trim().toLowerCase())
|
|
879
853
|
.filter(Boolean)
|
|
854
|
+
.sort()
|
|
880
855
|
.join(","),
|
|
881
856
|
detail: parts.detail ?? "brief",
|
|
882
857
|
};
|
|
@@ -907,10 +882,9 @@ async function writeSearchCache(
|
|
|
907
882
|
const dir = searchCacheDir();
|
|
908
883
|
try {
|
|
909
884
|
await mkdir(dir, { recursive: true });
|
|
910
|
-
await
|
|
885
|
+
await atomicWriteFile(
|
|
911
886
|
join(dir, `${key}.json`),
|
|
912
887
|
JSON.stringify({ ...entry, ts: Date.now() }),
|
|
913
|
-
"utf8",
|
|
914
888
|
);
|
|
915
889
|
const cutoff = Date.now() - SEARCH_CACHE_KEEP_MS;
|
|
916
890
|
for (const name of await readdir(dir)) {
|
|
@@ -918,7 +892,9 @@ async function writeSearchCache(
|
|
|
918
892
|
const file = join(dir, name);
|
|
919
893
|
try {
|
|
920
894
|
if ((await stat(file)).mtimeMs < cutoff) await unlink(file);
|
|
921
|
-
} catch {
|
|
895
|
+
} catch {
|
|
896
|
+
// 单个缓存文件删不掉不影响本轮检索,下一轮还会再试
|
|
897
|
+
}
|
|
922
898
|
}
|
|
923
899
|
} catch {
|
|
924
900
|
// 缓存写失败不影响检索结果
|
|
@@ -926,19 +902,24 @@ async function writeSearchCache(
|
|
|
926
902
|
}
|
|
927
903
|
|
|
928
904
|
async function persist(md: string, tag: string): Promise<string> {
|
|
929
|
-
|
|
930
|
-
await
|
|
931
|
-
return
|
|
905
|
+
const dst = process.env.D_REACH_LAST_RUN || LAST_RUN;
|
|
906
|
+
await atomicWriteFile(dst, `<!-- ${tag} -->\n${md}`);
|
|
907
|
+
return dst;
|
|
932
908
|
}
|
|
933
909
|
|
|
934
910
|
// ---------------------------------------------------------------- 抓 URL
|
|
935
911
|
|
|
936
912
|
/** 走 load_key.sh 拿 key,与整个技能同一条查找链 */
|
|
937
|
-
async function loadKey(name: string): Promise<string | null> {
|
|
913
|
+
async function loadKey(name: string, signal?: AbortSignal): Promise<string | null> {
|
|
914
|
+
if (signal?.aborted) throw abortedError();
|
|
938
915
|
try {
|
|
939
|
-
const { stdout } = await
|
|
916
|
+
const { stdout } = await runCommand("sh", [KEY_SH, name, ""], {
|
|
917
|
+
timeoutMs: 8000,
|
|
918
|
+
signal,
|
|
919
|
+
});
|
|
940
920
|
return stdout.trim() || null;
|
|
941
|
-
} catch {
|
|
921
|
+
} catch (err) {
|
|
922
|
+
if (isAborted(err, signal)) throw abortedError();
|
|
942
923
|
return null;
|
|
943
924
|
}
|
|
944
925
|
}
|
|
@@ -1112,7 +1093,6 @@ function contentIsReal(text: string): { cls: FailClass; detail: string } | null
|
|
|
1112
1093
|
// 同一个站点上一轮已经确认「要登录 / 撞风控 / 付费墙」,下一轮不必把这套通道再捶一遍。
|
|
1113
1094
|
// 照 Agent-Reach 的后端暂停:只记确定性结论、带 6 小时时效、站点一旦抓通就清空。
|
|
1114
1095
|
// 只按主机名记 —— 登录态和风控是站点级,不是单页级。
|
|
1115
|
-
const DEAD_FILE = join(homedir(), ".agent-reach", "fetch-dead.json");
|
|
1116
1096
|
const DEAD_TTL = 6 * 3600 * 1000;
|
|
1117
1097
|
const DEAD_CLS: FailClass[] = ["login", "antibot", "paywall"];
|
|
1118
1098
|
|
|
@@ -1124,12 +1104,32 @@ function hostOf(url: string): string {
|
|
|
1124
1104
|
}
|
|
1125
1105
|
}
|
|
1126
1106
|
|
|
1107
|
+
function pruneDeadMap(
|
|
1108
|
+
all: Record<string, Record<string, { cls?: string; at?: number }>>,
|
|
1109
|
+
nowMs: number,
|
|
1110
|
+
): Record<string, Record<string, { cls: string; at: number }>> {
|
|
1111
|
+
const cleaned: Record<string, Record<string, { cls: string; at: number }>> = {};
|
|
1112
|
+
for (const [host, stages] of Object.entries(all)) {
|
|
1113
|
+
if (!stages || typeof stages !== "object" || Array.isArray(stages)) continue;
|
|
1114
|
+
const kept: Record<string, { cls: string; at: number }> = {};
|
|
1115
|
+
for (const [stage, rec] of Object.entries(stages)) {
|
|
1116
|
+
if (!rec || typeof rec !== "object") continue;
|
|
1117
|
+
if (!DEAD_CLS.includes(rec.cls as FailClass)) continue;
|
|
1118
|
+
const at = typeof rec.at === "number" ? rec.at : 0;
|
|
1119
|
+
if (nowMs - at >= DEAD_TTL) continue;
|
|
1120
|
+
kept[stage] = { cls: rec.cls as string, at };
|
|
1121
|
+
}
|
|
1122
|
+
if (Object.keys(kept).length) cleaned[host] = kept;
|
|
1123
|
+
}
|
|
1124
|
+
return cleaned;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
1127
|
async function loadDead(url: string): Promise<Map<string, FailClass>> {
|
|
1128
1128
|
const host = hostOf(url);
|
|
1129
1129
|
const out = new Map<string, FailClass>();
|
|
1130
1130
|
if (!host) return out;
|
|
1131
1131
|
try {
|
|
1132
|
-
const all = JSON.parse(await readFile(
|
|
1132
|
+
const all = JSON.parse(await readFile(deadFilePath(), "utf8")) as Record<
|
|
1133
1133
|
string,
|
|
1134
1134
|
Record<string, { cls?: string; at?: number }>
|
|
1135
1135
|
>;
|
|
@@ -1147,16 +1147,20 @@ async function loadDead(url: string): Promise<Map<string, FailClass>> {
|
|
|
1147
1147
|
async function saveDead(url: string, stage: string, cls: FailClass): Promise<void> {
|
|
1148
1148
|
const host = hostOf(url);
|
|
1149
1149
|
if (!host || !DEAD_CLS.includes(cls)) return;
|
|
1150
|
+
const deadPath = deadFilePath();
|
|
1150
1151
|
try {
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1152
|
+
await withFileLock(deadPath, async () => {
|
|
1153
|
+
let rawAll: Record<string, Record<string, { cls?: string; at?: number }>> = {};
|
|
1154
|
+
try {
|
|
1155
|
+
rawAll = JSON.parse(await readFile(deadPath, "utf8"));
|
|
1156
|
+
} catch {
|
|
1157
|
+
/* 首次写入 */
|
|
1158
|
+
}
|
|
1159
|
+
const nowMs = Date.now();
|
|
1160
|
+
const all = pruneDeadMap(rawAll, nowMs);
|
|
1161
|
+
all[host] = { ...(all[host] ?? {}), [stage]: { cls, at: nowMs } };
|
|
1162
|
+
await atomicWriteFile(deadPath, JSON.stringify(all, null, 2));
|
|
1163
|
+
});
|
|
1160
1164
|
} catch {
|
|
1161
1165
|
/* 记账失败不影响抓取 */
|
|
1162
1166
|
}
|
|
@@ -1165,11 +1169,22 @@ async function saveDead(url: string, stage: string, cls: FailClass): Promise<voi
|
|
|
1165
1169
|
async function clearDead(url: string): Promise<void> {
|
|
1166
1170
|
const host = hostOf(url);
|
|
1167
1171
|
if (!host) return;
|
|
1172
|
+
const deadPath = deadFilePath();
|
|
1168
1173
|
try {
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1174
|
+
await withFileLock(deadPath, async () => {
|
|
1175
|
+
let rawAll: Record<string, Record<string, { cls?: string; at?: number }>> = {};
|
|
1176
|
+
try {
|
|
1177
|
+
rawAll = JSON.parse(await readFile(deadPath, "utf8"));
|
|
1178
|
+
} catch {
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
const nowMs = Date.now();
|
|
1182
|
+
const all = pruneDeadMap(rawAll, nowMs);
|
|
1183
|
+
const hadHost = host in rawAll;
|
|
1184
|
+
delete all[host];
|
|
1185
|
+
if (!hadHost && Object.keys(all).length === Object.keys(rawAll).length) return;
|
|
1186
|
+
await atomicWriteFile(deadPath, JSON.stringify(all, null, 2));
|
|
1187
|
+
});
|
|
1173
1188
|
} catch {
|
|
1174
1189
|
/* ignore */
|
|
1175
1190
|
}
|
|
@@ -1875,28 +1890,76 @@ interface CurlHop {
|
|
|
1875
1890
|
* 刻意不用 -L:跳转由 curlFollow 自己跟,每一跳都要重新做内网校验,
|
|
1876
1891
|
* 否则一个公网 URL 302 到 127.0.0.1 就把本机服务读出来了。
|
|
1877
1892
|
*/
|
|
1893
|
+
function curlResolveArgs(rawUrl: string, targetInfo?: TargetInfo): string[] {
|
|
1894
|
+
if (!targetInfo || isIP(targetInfo.host) || targetInfo.addresses.length === 0) return [];
|
|
1895
|
+
let u: URL;
|
|
1896
|
+
try {
|
|
1897
|
+
u = new URL(rawUrl);
|
|
1898
|
+
} catch {
|
|
1899
|
+
return [];
|
|
1900
|
+
}
|
|
1901
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return [];
|
|
1902
|
+
const port = u.port || (u.protocol === "https:" ? "443" : "80");
|
|
1903
|
+
const addrs = targetInfo.addresses.map((ip) => {
|
|
1904
|
+
const clean = ip.replace(/%.*$/, "");
|
|
1905
|
+
return clean.includes(":") ? `[${clean}]` : clean;
|
|
1906
|
+
});
|
|
1907
|
+
return ["--resolve", `${targetInfo.host}:${port}:${addrs.join(",")}`];
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
/** 只允许 http/https,且跳转目标也只能是 http/https:本机 curl 默认开着 file/gopher/ftp/dict。 */
|
|
1911
|
+
const CURL_PROTO_ARGS = ["--proto", "=http,https", "--proto-redir", "=http,https"];
|
|
1912
|
+
|
|
1913
|
+
async function inspectHopUrl(rawUrl: string): Promise<TargetInfo> {
|
|
1914
|
+
let u: URL;
|
|
1915
|
+
try {
|
|
1916
|
+
u = new URL(rawUrl);
|
|
1917
|
+
} catch {
|
|
1918
|
+
throw new StageFail("network", `跳转目标 URL 非法:${rawUrl.slice(0, 120)}`);
|
|
1919
|
+
}
|
|
1920
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
1921
|
+
throw new StageFail("network", `跳转协议不被允许:${u.protocol}`);
|
|
1922
|
+
}
|
|
1923
|
+
try {
|
|
1924
|
+
return await inspectTarget(rawUrl);
|
|
1925
|
+
} catch (e) {
|
|
1926
|
+
if (e instanceof BlockedTarget) {
|
|
1927
|
+
throw new StageFail("network", `跳转被拦下:${e.message}`);
|
|
1928
|
+
}
|
|
1929
|
+
throw new StageFail(
|
|
1930
|
+
"network",
|
|
1931
|
+
`跳转地址校验失败:${e instanceof Error ? e.message.slice(0, 120) : String(e)}`,
|
|
1932
|
+
);
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1878
1936
|
async function curlOnce(
|
|
1879
1937
|
target: string,
|
|
1880
1938
|
extraArgs: string[],
|
|
1881
1939
|
outFile: string,
|
|
1940
|
+
signal?: AbortSignal,
|
|
1941
|
+
targetInfo?: TargetInfo,
|
|
1882
1942
|
): Promise<CurlHop> {
|
|
1883
|
-
const
|
|
1943
|
+
const resolveArgs = curlResolveArgs(target, targetInfo);
|
|
1944
|
+
const { stdout } = await runCommand(
|
|
1884
1945
|
"curl",
|
|
1885
1946
|
[
|
|
1886
1947
|
"-s",
|
|
1887
1948
|
"--compressed",
|
|
1949
|
+
...CURL_PROTO_ARGS,
|
|
1888
1950
|
"--max-time",
|
|
1889
1951
|
"15",
|
|
1890
1952
|
"-o",
|
|
1891
1953
|
outFile,
|
|
1892
1954
|
"-A",
|
|
1893
1955
|
UA,
|
|
1956
|
+
...resolveArgs,
|
|
1894
1957
|
...extraArgs,
|
|
1895
1958
|
"-w",
|
|
1896
1959
|
`\n${HTTP_MARK}%{http_code}\t%{content_type}\t%{redirect_url}\t%header{retry-after}`,
|
|
1897
1960
|
target,
|
|
1898
1961
|
],
|
|
1899
|
-
{ maxBuffer: 1 << 20,
|
|
1962
|
+
{ maxBuffer: 1 << 20, timeoutMs: 25_000, signal },
|
|
1900
1963
|
);
|
|
1901
1964
|
const cut = stdout.lastIndexOf(HTTP_MARK);
|
|
1902
1965
|
const meta = cut < 0 ? "" : stdout.slice(cut + HTTP_MARK.length);
|
|
@@ -1924,29 +1987,37 @@ async function curlFollow(
|
|
|
1924
1987
|
* cookie 档用它把 Cookie 限制在匹配域名内 —— 公网跳到第三方(或跳到 http)时不再带 cookie。
|
|
1925
1988
|
*/
|
|
1926
1989
|
argsFor?: (target: string) => string[],
|
|
1990
|
+
signal?: AbortSignal,
|
|
1927
1991
|
): Promise<{ hop: CurlHop; effective: string }> {
|
|
1992
|
+
if (signal?.aborted) throw abortedError();
|
|
1928
1993
|
let effective = start;
|
|
1929
|
-
let
|
|
1994
|
+
let hopInfo = await inspectHopUrl(effective);
|
|
1995
|
+
if (hopInfo.isPrivate && !allowPrivate)
|
|
1996
|
+
throw new StageFail("network", `地址被拦下:${blockedMessage(hopInfo)}`);
|
|
1997
|
+
let hop = await curlOnce(effective, argsFor ? argsFor(effective) : extraArgs, outFile, signal, hopInfo);
|
|
1930
1998
|
for (let n = 0; hop.status >= 300 && hop.status < 400 && hop.status !== 304; ) {
|
|
1999
|
+
if (signal?.aborted) throw abortedError();
|
|
1931
2000
|
if (!hop.redirect)
|
|
1932
2001
|
throw new StageFail("network", `HTTP ${hop.status} 跳转但没给 Location`);
|
|
1933
2002
|
if (++n > 5)
|
|
1934
2003
|
throw new StageFail("network", "重定向超过 5 跳(可能是跳转环)");
|
|
1935
2004
|
const next = hop.redirect;
|
|
1936
|
-
const info = await
|
|
2005
|
+
const info = await inspectHopUrl(next);
|
|
1937
2006
|
// 只有显式 allow_private 时才允许跳进内网
|
|
1938
|
-
if (info
|
|
2007
|
+
if (info.isPrivate && !allowPrivate)
|
|
1939
2008
|
throw new StageFail("network", `跳转被拦下:${blockedMessage(info)}`);
|
|
1940
2009
|
effective = next;
|
|
1941
|
-
|
|
2010
|
+
hopInfo = info;
|
|
2011
|
+
hop = await curlOnce(effective, argsFor ? argsFor(effective) : extraArgs, outFile, signal, hopInfo);
|
|
1942
2012
|
}
|
|
1943
2013
|
return { hop, effective };
|
|
1944
2014
|
}
|
|
1945
2015
|
|
|
1946
|
-
async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | null> {
|
|
1947
|
-
|
|
2016
|
+
async function viaCurl(url: string, allowPrivate = false, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2017
|
+
if (signal?.aborted) throw abortedError();
|
|
2018
|
+
const tmp = join(tmpdir(), `dreach-curl-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
1948
2019
|
try {
|
|
1949
|
-
const followed = await curlFollow(url, [], tmp, allowPrivate);
|
|
2020
|
+
const followed = await curlFollow(url, [], tmp, allowPrivate, undefined, signal);
|
|
1950
2021
|
const { status, ctype, retryAfter } = followed.hop;
|
|
1951
2022
|
const effective = followed.effective;
|
|
1952
2023
|
|
|
@@ -1973,9 +2044,10 @@ async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | nul
|
|
|
1973
2044
|
|
|
1974
2045
|
// PDF:本机有 pymupdf,直接抽文字层。不做这一步就会得到上百万字符的乱码并被判成功。
|
|
1975
2046
|
if (/application\/pdf/.test(ctype)) {
|
|
1976
|
-
const { stdout: pdfOut } = await
|
|
2047
|
+
const { stdout: pdfOut } = await runCommand("python3", [PDF2TEXT, tmp], {
|
|
1977
2048
|
maxBuffer: 32 << 20,
|
|
1978
|
-
|
|
2049
|
+
timeoutMs: 40_000,
|
|
2050
|
+
signal,
|
|
1979
2051
|
});
|
|
1980
2052
|
let parsed: {
|
|
1981
2053
|
ok?: boolean;
|
|
@@ -2058,10 +2130,14 @@ async function viaCurl(url: string, allowPrivate = false): Promise<Fetched | nul
|
|
|
2058
2130
|
async function viaPlaywright(
|
|
2059
2131
|
url: string,
|
|
2060
2132
|
allowPrivate = false,
|
|
2133
|
+
signal?: AbortSignal,
|
|
2061
2134
|
): Promise<Fetched | null> {
|
|
2062
|
-
|
|
2135
|
+
if (signal?.aborted) throw abortedError();
|
|
2136
|
+
const renderArgs = allowPrivate ? [RENDER, url, "--allow-private"] : [RENDER, url];
|
|
2137
|
+
const { stdout } = await runCommand("node", renderArgs, {
|
|
2063
2138
|
maxBuffer: 8 << 20,
|
|
2064
|
-
|
|
2139
|
+
timeoutMs: 40_000,
|
|
2140
|
+
signal,
|
|
2065
2141
|
});
|
|
2066
2142
|
const line = stdout.trim().split("\n").pop() ?? "";
|
|
2067
2143
|
let out: {
|
|
@@ -2080,6 +2156,8 @@ async function viaPlaywright(
|
|
|
2080
2156
|
const err = out.err ?? "";
|
|
2081
2157
|
// 没装 playwright 属于「本机不具备这一档」,不是这个站抓不到
|
|
2082
2158
|
if (/找不到 playwright|Cannot find package/.test(err)) return null;
|
|
2159
|
+
if (err.startsWith("SSRF_BLOCKED:"))
|
|
2160
|
+
throw new StageFail("network", err.replace("SSRF_BLOCKED:", "").trim());
|
|
2083
2161
|
// PDF/图片直链:浏览器只会弹下载,后面七档同样白跑
|
|
2084
2162
|
if (err.startsWith("NOT_A_PAGE"))
|
|
2085
2163
|
throw new StageFail("parse", err.replace("NOT_A_PAGE: ", ""), "binary");
|
|
@@ -2102,8 +2180,8 @@ async function viaPlaywright(
|
|
|
2102
2180
|
// 浏览器自己跟跳转:公网 URL 302 到 127.0.0.1/内网时,页面已经抓回来了,
|
|
2103
2181
|
// 必须在这里补一道校验,否则 SSRF 防护会被「先跳转再渲染」绕过。
|
|
2104
2182
|
if (out.finalUrl && out.finalUrl !== url) {
|
|
2105
|
-
const info = await
|
|
2106
|
-
if (info
|
|
2183
|
+
const info = await inspectHopUrl(out.finalUrl);
|
|
2184
|
+
if (info.isPrivate && !allowPrivate)
|
|
2107
2185
|
throw new StageFail("network", `跳转被拦下:${blockedMessage(info)}`);
|
|
2108
2186
|
}
|
|
2109
2187
|
// 渲染器会跟跳转走:被重定向到 passport./login. 这类域名就是明确的登录墙,
|
|
@@ -2129,8 +2207,8 @@ async function viaPlaywright(
|
|
|
2129
2207
|
return { via: "Playwright 本地渲染", text, chars: text.length };
|
|
2130
2208
|
}
|
|
2131
2209
|
|
|
2132
|
-
async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
2133
|
-
const key = await loadKey("TINYFISH_API_KEY");
|
|
2210
|
+
async function viaTinyfish(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2211
|
+
const key = await loadKey("TINYFISH_API_KEY", signal);
|
|
2134
2212
|
if (!key) return null;
|
|
2135
2213
|
const endpoint = "https://agent.tinyfish.ai/mcp";
|
|
2136
2214
|
const call = async (payload: unknown, sid?: string) => {
|
|
@@ -2140,14 +2218,28 @@ async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
|
2140
2218
|
"X-API-Key": key,
|
|
2141
2219
|
};
|
|
2142
2220
|
if (sid) hdr["Mcp-Session-Id"] = sid;
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2221
|
+
let res: { status: number; headers: Headers; text: string };
|
|
2222
|
+
try {
|
|
2223
|
+
res = await fetchTextWithTimeout(
|
|
2224
|
+
endpoint,
|
|
2225
|
+
{
|
|
2226
|
+
method: "POST",
|
|
2227
|
+
headers: hdr,
|
|
2228
|
+
body: JSON.stringify(payload),
|
|
2229
|
+
},
|
|
2230
|
+
30_000,
|
|
2231
|
+
signal,
|
|
2232
|
+
);
|
|
2233
|
+
} catch (err) {
|
|
2234
|
+
if (isAborted(err, signal)) throw abortedError();
|
|
2235
|
+
if ((err as { code?: string })?.code === "ETIMEDOUT") {
|
|
2236
|
+
throw new StageFail("network", "TinyFish fetch 请求超时(30s)");
|
|
2237
|
+
}
|
|
2238
|
+
throw err;
|
|
2239
|
+
}
|
|
2148
2240
|
return {
|
|
2149
2241
|
sid: res.headers.get("mcp-session-id") ?? undefined,
|
|
2150
|
-
body:
|
|
2242
|
+
body: res.text,
|
|
2151
2243
|
};
|
|
2152
2244
|
};
|
|
2153
2245
|
const init = await call({
|
|
@@ -2209,16 +2301,17 @@ async function viaTinyfish(url: string): Promise<Fetched | null> {
|
|
|
2209
2301
|
return { via: "TinyFish fetch", text, chars: text.length };
|
|
2210
2302
|
}
|
|
2211
2303
|
|
|
2212
|
-
async function viaJina(url: string): Promise<Fetched | null> {
|
|
2213
|
-
const key = await loadKey("JINA_API_KEY");
|
|
2304
|
+
async function viaJina(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2305
|
+
const key = await loadKey("JINA_API_KEY", signal);
|
|
2214
2306
|
const call = async (withKey: boolean) => {
|
|
2215
2307
|
const hdr = ["-H", "X-Return-Format: markdown"];
|
|
2216
2308
|
if (withKey && key) hdr.push("-H", `Authorization: Bearer ${key}`);
|
|
2217
|
-
const { stdout } = await
|
|
2309
|
+
const { stdout } = await runCommand(
|
|
2218
2310
|
"curl",
|
|
2219
2311
|
[
|
|
2220
2312
|
"-sL",
|
|
2221
2313
|
"--compressed",
|
|
2314
|
+
...CURL_PROTO_ARGS,
|
|
2222
2315
|
"--max-time",
|
|
2223
2316
|
"25",
|
|
2224
2317
|
"-A",
|
|
@@ -2226,7 +2319,7 @@ async function viaJina(url: string): Promise<Fetched | null> {
|
|
|
2226
2319
|
...hdr,
|
|
2227
2320
|
`https://r.jina.ai/${url}`,
|
|
2228
2321
|
],
|
|
2229
|
-
{ maxBuffer: 8 << 20,
|
|
2322
|
+
{ maxBuffer: 8 << 20, timeoutMs: 30_000, signal },
|
|
2230
2323
|
);
|
|
2231
2324
|
return stdout;
|
|
2232
2325
|
};
|
|
@@ -2246,13 +2339,13 @@ async function viaJina(url: string): Promise<Fetched | null> {
|
|
|
2246
2339
|
return { via: "Jina Reader", text, chars: text.length };
|
|
2247
2340
|
}
|
|
2248
2341
|
|
|
2249
|
-
async function viaMarkdownNew(url: string): Promise<Fetched | null> {
|
|
2342
|
+
async function viaMarkdownNew(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2250
2343
|
// markdown.new:免费、无 key,返回格式与 Jina 几乎一致(Title / URL Source / Markdown Content)。
|
|
2251
2344
|
// 价值在于 Jina 被限流或欠费时的等价备选,所以排在 Jina 之后。
|
|
2252
|
-
const { stdout } = await
|
|
2345
|
+
const { stdout } = await runCommand(
|
|
2253
2346
|
"curl",
|
|
2254
|
-
["-sL", "--compressed", "--max-time", "30", "-A", UA, `https://markdown.new/${url}`],
|
|
2255
|
-
{ maxBuffer: 8 << 20,
|
|
2347
|
+
["-sL", "--compressed", ...CURL_PROTO_ARGS, "--max-time", "30", "-A", UA, `https://markdown.new/${url}`],
|
|
2348
|
+
{ maxBuffer: 8 << 20, timeoutMs: 35_000, signal },
|
|
2256
2349
|
);
|
|
2257
2350
|
const text = stripInlineMedia(stdout).trim();
|
|
2258
2351
|
// 这个服务对抓不到的站会回一段自己的错误说明,不能当正文
|
|
@@ -2263,13 +2356,15 @@ async function viaMarkdownNew(url: string): Promise<Fetched | null> {
|
|
|
2263
2356
|
return { via: "markdown.new", text, chars: text.length };
|
|
2264
2357
|
}
|
|
2265
2358
|
|
|
2266
|
-
async function viaParallelFetch(url: string): Promise<Fetched | null> {
|
|
2359
|
+
async function viaParallelFetch(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2267
2360
|
// Parallel 免费 MCP(无 key、无账号):web_fetch 返回带 excerpts 的正文。
|
|
2268
2361
|
// 与 TinyFish 同为 hosted 服务,放在它后面作独立一路——两家索引不同,一方抽不出另一方可能行。
|
|
2269
2362
|
const args = JSON.stringify({ urls: [url], allow_live_fetch: true });
|
|
2270
|
-
const { stdout } = await
|
|
2363
|
+
const { stdout } = await runCommand("python3", [MCP_CALL, PARALLEL_MCP, "web_fetch", args], {
|
|
2271
2364
|
maxBuffer: 8 << 20,
|
|
2272
|
-
|
|
2365
|
+
timeoutMs: 50_000,
|
|
2366
|
+
env: { ...process.env, D_REACH_MCP_BUDGET: "45" },
|
|
2367
|
+
signal,
|
|
2273
2368
|
});
|
|
2274
2369
|
const raw = stdout.trim();
|
|
2275
2370
|
if (raw.startsWith("MCP_ERROR"))
|
|
@@ -2291,8 +2386,8 @@ async function viaParallelFetch(url: string): Promise<Fetched | null> {
|
|
|
2291
2386
|
return { via: "Parallel fetch", text, chars: text.length };
|
|
2292
2387
|
}
|
|
2293
2388
|
|
|
2294
|
-
async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
2295
|
-
const key = await loadKey("BRIGHTDATA_APITOKEN");
|
|
2389
|
+
async function viaBrightdata(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2390
|
+
const key = await loadKey("BRIGHTDATA_APITOKEN", signal);
|
|
2296
2391
|
if (!key) return null;
|
|
2297
2392
|
// 必须用 format:"json":raw+data_format:"markdown" 会把真实状态码覆盖成 200。
|
|
2298
2393
|
// 实测 example.com/definitely-404-page —— json 档回 status_code:404,markdown 档回 200
|
|
@@ -2303,10 +2398,11 @@ async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
|
2303
2398
|
format: "json",
|
|
2304
2399
|
url,
|
|
2305
2400
|
});
|
|
2306
|
-
const { stdout } = await
|
|
2401
|
+
const { stdout } = await runCommand(
|
|
2307
2402
|
"curl",
|
|
2308
2403
|
[
|
|
2309
2404
|
"-sL",
|
|
2405
|
+
...CURL_PROTO_ARGS,
|
|
2310
2406
|
"--max-time",
|
|
2311
2407
|
"30",
|
|
2312
2408
|
"-X",
|
|
@@ -2319,7 +2415,7 @@ async function viaBrightdata(url: string): Promise<Fetched | null> {
|
|
|
2319
2415
|
"-d",
|
|
2320
2416
|
body,
|
|
2321
2417
|
],
|
|
2322
|
-
{ maxBuffer: 8 << 20,
|
|
2418
|
+
{ maxBuffer: 8 << 20, timeoutMs: 35_000, signal },
|
|
2323
2419
|
);
|
|
2324
2420
|
const raw = stdout.trim();
|
|
2325
2421
|
// 错误体不一定以 { 开头:residential 模式的 bad_endpoint 是裸文本,
|
|
@@ -2421,7 +2517,9 @@ function sliceBalancedDiv(html: string, from: number): string {
|
|
|
2421
2517
|
async function viaWeixinDirect(
|
|
2422
2518
|
url: string,
|
|
2423
2519
|
allowPrivate = false,
|
|
2520
|
+
signal?: AbortSignal,
|
|
2424
2521
|
): Promise<Fetched | null> {
|
|
2522
|
+
if (signal?.aborted) throw abortedError();
|
|
2425
2523
|
// 两种链都认:短链 `/s/<token>` 和长链 `/s?__biz=…&sn=…`(后者在历史文章、
|
|
2426
2524
|
// 分享链接里更常见,只认 `/s/` 会让它们绕过专档、去走普通 curl
|
|
2427
2525
|
// 判定落在 host 上而不是整串 URL:`https://evil.example/mp.weixin.qq.com/s/x`
|
|
@@ -2438,10 +2536,10 @@ async function viaWeixinDirect(
|
|
|
2438
2536
|
// 微信的「总目录」类文章实测 8.8MB HTML(1152 条链接),而 execFile 的 maxBuffer
|
|
2439
2537
|
// 上限是 8<<20,多一个字节就抛 `stdout maxBuffer length exceeded` —— 那是个普通 Error,
|
|
2440
2538
|
// 会被归成「解析不出正文」,然后白降到 curl 档只拿到 1745 字(丢掉 1152 条链接)。
|
|
2441
|
-
const tmp = join(tmpdir(), `dreach-wx-${process.pid}-${Date.now()}.body`);
|
|
2539
|
+
const tmp = join(tmpdir(), `dreach-wx-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
2442
2540
|
try {
|
|
2443
2541
|
// 走 curlFollow 而不是 `curl -sL`:微信短链会 302,自动跟随就绕过了逐跳内网校验。
|
|
2444
|
-
const followed = await curlFollow(url, [], tmp, allowPrivate);
|
|
2542
|
+
const followed = await curlFollow(url, [], tmp, allowPrivate, undefined, signal);
|
|
2445
2543
|
const status = followed.hop.status;
|
|
2446
2544
|
if (status === 429 || status === 503)
|
|
2447
2545
|
throw new StageFail("ratelimit", `HTTP ${status}(微信风控限流)`);
|
|
@@ -2492,14 +2590,14 @@ const COOKIE_SLOTS: Array<{ domain: string; slot: string; name: string }> = [
|
|
|
2492
2590
|
* https://feishu.cn.evil.example/ → 命中
|
|
2493
2591
|
* 两者都会把用户飞书 cookie 发给攻击者。cookie 只在对应域名下有值,判定必须落在 host 上。
|
|
2494
2592
|
*/
|
|
2495
|
-
function hostMatchesDomain(rawUrl: string, domain: string): boolean {
|
|
2593
|
+
function hostMatchesDomain(rawUrl: string, domain: string, requireHttps = true): boolean {
|
|
2496
2594
|
let u: URL;
|
|
2497
2595
|
try {
|
|
2498
2596
|
u = new URL(rawUrl);
|
|
2499
2597
|
} catch {
|
|
2500
2598
|
return false;
|
|
2501
2599
|
}
|
|
2502
|
-
if (u.protocol !== "https:") return false;
|
|
2600
|
+
if (requireHttps && u.protocol !== "https:") return false;
|
|
2503
2601
|
const host = normalizeHost(u.hostname);
|
|
2504
2602
|
return host === domain || host.endsWith(`.${domain}`);
|
|
2505
2603
|
}
|
|
@@ -2507,12 +2605,14 @@ function hostMatchesDomain(rawUrl: string, domain: string): boolean {
|
|
|
2507
2605
|
async function viaCookieInject(
|
|
2508
2606
|
url: string,
|
|
2509
2607
|
allowPrivate = false,
|
|
2608
|
+
signal?: AbortSignal,
|
|
2510
2609
|
): Promise<Fetched | null> {
|
|
2610
|
+
if (signal?.aborted) throw abortedError();
|
|
2511
2611
|
// 域名判定只看 hostname:查询参数里塞 feishu.cn、或者 feishu.cn.evil.example
|
|
2512
2612
|
// 都不能让用户 cookie 跟着请求发出去。
|
|
2513
2613
|
const hit = COOKIE_SLOTS.find((s) => hostMatchesDomain(url, s.domain));
|
|
2514
2614
|
if (!hit) return null;
|
|
2515
|
-
const cookie = await loadKey(hit.slot);
|
|
2615
|
+
const cookie = await loadKey(hit.slot, signal);
|
|
2516
2616
|
if (!cookie) {
|
|
2517
2617
|
throw new StageFail(
|
|
2518
2618
|
"nocred",
|
|
@@ -2520,14 +2620,20 @@ async function viaCookieInject(
|
|
|
2520
2620
|
);
|
|
2521
2621
|
}
|
|
2522
2622
|
// 带 cookie 的请求同样自己跟跳转:否则 302 到内网/第三方也会把 cookie 带过去。
|
|
2523
|
-
const tmp = join(tmpdir(), `dreach-cookie-${process.pid}-${Date.now()}.body`);
|
|
2623
|
+
const tmp = join(tmpdir(), `dreach-cookie-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}.body`);
|
|
2524
2624
|
const cookieArgs = ["-H", `Cookie: ${cookie}`, "--max-time", "25"];
|
|
2525
2625
|
let stdout: string;
|
|
2526
2626
|
try {
|
|
2527
2627
|
// 每一跳重新判定:只有仍是该域名下的 https 才带 cookie,
|
|
2528
2628
|
// 否则 302 到 evil.example(或 http)就会把用户 cookie 一起送过去。
|
|
2529
|
-
const followed = await curlFollow(
|
|
2530
|
-
|
|
2629
|
+
const followed = await curlFollow(
|
|
2630
|
+
url,
|
|
2631
|
+
cookieArgs,
|
|
2632
|
+
tmp,
|
|
2633
|
+
allowPrivate,
|
|
2634
|
+
(target) =>
|
|
2635
|
+
hostMatchesDomain(target, hit.domain) ? cookieArgs : ["--max-time", "25"],
|
|
2636
|
+
signal,
|
|
2531
2637
|
);
|
|
2532
2638
|
if (followed.hop.status >= 400)
|
|
2533
2639
|
throw new StageFail("network", `HTTP ${followed.hop.status}`);
|
|
@@ -2545,19 +2651,20 @@ async function viaCookieInject(
|
|
|
2545
2651
|
}
|
|
2546
2652
|
|
|
2547
2653
|
/** 最后一档:公开存档。不改请求头、不冒充爬虫,风险最低的兜底。 */
|
|
2548
|
-
async function viaArchiveToday(url: string): Promise<Fetched | null> {
|
|
2549
|
-
const { stdout } = await
|
|
2654
|
+
async function viaArchiveToday(url: string, signal?: AbortSignal): Promise<Fetched | null> {
|
|
2655
|
+
const { stdout } = await runCommand(
|
|
2550
2656
|
"curl",
|
|
2551
2657
|
[
|
|
2552
2658
|
"-sL",
|
|
2553
2659
|
"--compressed",
|
|
2660
|
+
...CURL_PROTO_ARGS,
|
|
2554
2661
|
"--max-time",
|
|
2555
2662
|
"25",
|
|
2556
2663
|
"-A",
|
|
2557
2664
|
UA,
|
|
2558
2665
|
`https://archive.ph/newest/${url}`,
|
|
2559
2666
|
],
|
|
2560
|
-
{ maxBuffer: 8 << 20,
|
|
2667
|
+
{ maxBuffer: 8 << 20, timeoutMs: 30_000, signal },
|
|
2561
2668
|
);
|
|
2562
2669
|
if (
|
|
2563
2670
|
/We don't have that page archived|No results|Page cannot be crawled/i.test(
|
|
@@ -2576,7 +2683,8 @@ async function viaArchiveToday(url: string): Promise<Fetched | null> {
|
|
|
2576
2683
|
* 依次尝试,第一个达标就返回。每一档失败都带分类,全部失败时能说清「该不该重试」。
|
|
2577
2684
|
* 返回 null 表示该档不适用(域名不匹配 / 没配 key),不计入失败。
|
|
2578
2685
|
*/
|
|
2579
|
-
async function fetchUrl(url: string, allowPrivate = false) {
|
|
2686
|
+
async function fetchUrl(url: string, allowPrivate = false, signal?: AbortSignal) {
|
|
2687
|
+
if (signal?.aborted) throw abortedError();
|
|
2580
2688
|
// 国内电商在无登录态下对所有通道都是同一堵墙:实测 2026-11-08 京东商品页
|
|
2581
2689
|
// https://item.jd.com/10230695839309.html 跑完 curl/Playwright/TinyFish/Parallel/Jina
|
|
2582
2690
|
// 五档 78.2s(十档 99.7s)全判「要登录/反爬」,连 https://item.m.jd.com 也会
|
|
@@ -2586,29 +2694,23 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2586
2694
|
"jd.com", "jd.hk", "taobao.com", "tmall.com", "tmall.hk",
|
|
2587
2695
|
"pinduoduo.com", "yangkeduo.com", "1688.com", "suning.com", "vip.com",
|
|
2588
2696
|
];
|
|
2589
|
-
const ecHost = EC_HOSTS.some((h) =>
|
|
2590
|
-
try {
|
|
2591
|
-
return new URL(url).hostname.endsWith(h);
|
|
2592
|
-
} catch {
|
|
2593
|
-
return false;
|
|
2594
|
-
}
|
|
2595
|
-
});
|
|
2697
|
+
const ecHost = EC_HOSTS.some((h) => hostMatchesDomain(url, h, false));
|
|
2596
2698
|
const attempts: Array<[string, () => Promise<Fetched | null>]> = [
|
|
2597
|
-
["微信直连", () => viaWeixinDirect(url, allowPrivate)],
|
|
2598
|
-
["cookie 注入", () => viaCookieInject(url, allowPrivate)],
|
|
2599
|
-
["curl 直连", () => viaCurl(url, allowPrivate)],
|
|
2699
|
+
["微信直连", () => viaWeixinDirect(url, allowPrivate, signal)],
|
|
2700
|
+
["cookie 注入", () => viaCookieInject(url, allowPrivate, signal)],
|
|
2701
|
+
["curl 直连", () => viaCurl(url, allowPrivate, signal)],
|
|
2600
2702
|
...(ecHost
|
|
2601
|
-
? ([["Jina Reader", () => viaJina(url)]] as Array<
|
|
2703
|
+
? ([["Jina Reader", () => viaJina(url, signal)]] as Array<
|
|
2602
2704
|
[string, () => Promise<Fetched | null>]
|
|
2603
2705
|
>)
|
|
2604
2706
|
: ([
|
|
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)],
|
|
2707
|
+
["Playwright 渲染", () => viaPlaywright(url, allowPrivate, signal)],
|
|
2708
|
+
["TinyFish fetch", () => viaTinyfish(url, signal)],
|
|
2709
|
+
["Parallel fetch", () => viaParallelFetch(url, signal)],
|
|
2710
|
+
["Jina Reader", () => viaJina(url, signal)],
|
|
2711
|
+
["markdown.new", () => viaMarkdownNew(url, signal)],
|
|
2712
|
+
["BrightData", () => viaBrightdata(url, signal)],
|
|
2713
|
+
["archive.today", () => viaArchiveToday(url, signal)],
|
|
2612
2714
|
] as Array<[string, () => Promise<Fetched | null>]>) ),
|
|
2613
2715
|
];
|
|
2614
2716
|
/** 本机执行的档:allow_private 只对这几档生效。 */
|
|
@@ -2645,6 +2747,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2645
2747
|
}
|
|
2646
2748
|
throw e;
|
|
2647
2749
|
}
|
|
2750
|
+
if (signal?.aborted) throw abortedError();
|
|
2648
2751
|
if (target.isPrivate) {
|
|
2649
2752
|
if (!allowPrivate) {
|
|
2650
2753
|
const msg = blockedMessage(target);
|
|
@@ -2668,15 +2771,31 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2668
2771
|
// 融合层分流(pi-web-access):GitHub 仓库/文件/PR、YouTube、直链图片走专用通道;
|
|
2669
2772
|
// 放在地址校验之后,内网地址不会进这里。返回 null 表示交还下面的十档。
|
|
2670
2773
|
if (!target.isPrivate) {
|
|
2774
|
+
if (signal?.aborted) throw abortedError();
|
|
2671
2775
|
try {
|
|
2672
|
-
const special = await routeSpecialUrl(url, { maxChars: 200000 });
|
|
2673
|
-
if (special)
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2776
|
+
const special = await routeSpecialUrl(url, { maxChars: 200000, signal });
|
|
2777
|
+
if (special) {
|
|
2778
|
+
if (special.problem) {
|
|
2779
|
+
const cls: FailClass = /凭据|GEMINI_API_KEY|PERPLEXITY_API_KEY/i.test(special.text)
|
|
2780
|
+
? "nocred"
|
|
2781
|
+
: /超时|timed out|ECONNREFUSED|ENOTFOUND|network/i.test(special.text)
|
|
2782
|
+
? "network"
|
|
2783
|
+
: "parse";
|
|
2784
|
+
skipped.push({
|
|
2785
|
+
stage: special.via,
|
|
2786
|
+
cls,
|
|
2787
|
+
detail: special.text.slice(0, 200),
|
|
2788
|
+
});
|
|
2789
|
+
} else {
|
|
2790
|
+
return {
|
|
2791
|
+
ok: true as const,
|
|
2792
|
+
got: { via: special.via, text: special.text, chars: special.chars },
|
|
2793
|
+
skipped,
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2679
2797
|
} catch (e) {
|
|
2798
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
2680
2799
|
skipped.push({
|
|
2681
2800
|
stage: "专用分流",
|
|
2682
2801
|
cls: "parse",
|
|
@@ -2685,6 +2804,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2685
2804
|
}
|
|
2686
2805
|
}
|
|
2687
2806
|
|
|
2807
|
+
if (signal?.aborted) throw abortedError();
|
|
2688
2808
|
// 上次已确认过不去的档,本轮直接跳过并把原因写进 skipped(用户看到「已确认」,不是「没跑」)
|
|
2689
2809
|
const dead = await loadDead(url);
|
|
2690
2810
|
for (const [stage, cls] of dead) {
|
|
@@ -2697,6 +2817,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2697
2817
|
}
|
|
2698
2818
|
const liveAttempts = liveCandidates.filter(([stage]) => !dead.has(stage));
|
|
2699
2819
|
for (const [stage, fn] of liveAttempts) {
|
|
2820
|
+
if (signal?.aborted) throw abortedError();
|
|
2700
2821
|
try {
|
|
2701
2822
|
const got = await fn();
|
|
2702
2823
|
if (!got) continue;
|
|
@@ -2704,7 +2825,7 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2704
2825
|
const fake = contentIsReal(got.text);
|
|
2705
2826
|
if (fake) {
|
|
2706
2827
|
skipped.push({ stage, cls: fake.cls, detail: fake.detail });
|
|
2707
|
-
|
|
2828
|
+
await saveDead(url, stage, fake.cls);
|
|
2708
2829
|
if (fake.cls === "login" || fake.cls === "antibot") {
|
|
2709
2830
|
const walls = skipped.filter(
|
|
2710
2831
|
(s) => s.cls === "login" || s.cls === "antibot" || s.cls === "paywall",
|
|
@@ -2713,16 +2834,17 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2713
2834
|
}
|
|
2714
2835
|
continue;
|
|
2715
2836
|
}
|
|
2716
|
-
|
|
2837
|
+
await clearDead(url); // 站点抓通了,旧的死档记录作废
|
|
2717
2838
|
// 截断只在这里做:完整正文交给调用方存盘,避免存进半截内容
|
|
2718
2839
|
return { ok: true as const, got, skipped };
|
|
2719
2840
|
} catch (e) {
|
|
2841
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
2720
2842
|
if (e instanceof StageFail) {
|
|
2721
2843
|
skipped.push({ stage, cls: e.cls, detail: e.detail });
|
|
2722
2844
|
// 429/503 是对「我们这个 IP + 此刻这个节奏」的信号。换通道、换域名格式都没用,
|
|
2723
2845
|
// 唯一正确答案是停下等。实测继续把 TinyFish/Jina/BrightData/archive 走完要 50s+。
|
|
2724
2846
|
if (e.cls === "ratelimit") return bail({ ratelimited: e.detail });
|
|
2725
|
-
if (DEAD_CLS.includes(e.cls))
|
|
2847
|
+
if (DEAD_CLS.includes(e.cls)) await saveDead(url, stage, e.cls);
|
|
2726
2848
|
// 登录墙 / 反爬 / 付费墙是「这个页面」的定性判断:换通道换不来身份和订阅。实测京东商品页
|
|
2727
2849
|
// 十档全败 99.7s,每一档都在说「要登录」。四档都这样判就是定论,剩下的
|
|
2728
2850
|
// Jina / md.new / BrightData / archive 只会再烧 40–60s 和额度。
|
|
@@ -2749,16 +2871,17 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2749
2871
|
/超时|timed out/i.test(e.detail) &&
|
|
2750
2872
|
skipped.filter(
|
|
2751
2873
|
(s) => s.cls === "network" && /超时|timed out/i.test(s.detail),
|
|
2752
|
-
).length >=
|
|
2874
|
+
).length >= 2
|
|
2753
2875
|
)
|
|
2754
2876
|
return bail({ slow: true });
|
|
2755
2877
|
} else {
|
|
2756
|
-
// execFile 抛的错(curl 超时 / HTTP2 stream error / DNS):归 network,不归 parse。
|
|
2878
|
+
// execFile / runCommand 抛的错(curl 超时 / HTTP2 stream error / DNS):归 network,不归 parse。
|
|
2757
2879
|
// 实测 BrightData 对同一 URL 时成时败,失败时 curl 退出码 92(HTTP/2 stream error),
|
|
2758
2880
|
// 说成「解析不出正文」会让人以为内容格式不对。
|
|
2759
2881
|
const err = e as { code?: number | string; message?: string };
|
|
2760
2882
|
const curlCode = typeof err.code === "number" ? err.code : 0;
|
|
2761
2883
|
const isNet =
|
|
2884
|
+
err.code === "ETIMEDOUT" ||
|
|
2762
2885
|
[6, 7, 28, 35, 47, 52, 56, 92].includes(curlCode) ||
|
|
2763
2886
|
/timed out|Could not resolve|Connection (refused|reset)|stream error|TOO_MANY_REDIRECTS|too many redirects|redirect count exceeded/i.test(
|
|
2764
2887
|
err.message ?? "",
|
|
@@ -2768,7 +2891,9 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2768
2891
|
err.message ?? "",
|
|
2769
2892
|
);
|
|
2770
2893
|
const timedOut =
|
|
2771
|
-
|
|
2894
|
+
err.code === "ETIMEDOUT" ||
|
|
2895
|
+
curlCode === 28 ||
|
|
2896
|
+
/timed out/i.test(err.message ?? "");
|
|
2772
2897
|
skipped.push({
|
|
2773
2898
|
stage,
|
|
2774
2899
|
cls: isNet ? "network" : "parse",
|
|
@@ -2801,7 +2926,6 @@ async function fetchUrl(url: string, allowPrivate = false) {
|
|
|
2801
2926
|
* 同一 URL 的旧快照仍可被 id 精确读到(缓存靠 .json 里的 fetched_at 找最新一份)。
|
|
2802
2927
|
* 24 小时前的文件在启动和每次写入时清理。
|
|
2803
2928
|
*/
|
|
2804
|
-
const STORE_DIR = join(DATA_DIR, "fetch-store");
|
|
2805
2929
|
const STORE_TTL = 24 * 3600 * 1000;
|
|
2806
2930
|
const CACHE_TTL = 15 * 60 * 1000;
|
|
2807
2931
|
|
|
@@ -2812,6 +2936,7 @@ interface StoredMeta {
|
|
|
2812
2936
|
chars: number;
|
|
2813
2937
|
fetched_at: number;
|
|
2814
2938
|
fetched_iso: string;
|
|
2939
|
+
isPrivate?: boolean;
|
|
2815
2940
|
}
|
|
2816
2941
|
|
|
2817
2942
|
/** URL 规范化:只用于「同一页面」判定与缓存键,不改变实际请求的 URL。 */
|
|
@@ -2839,12 +2964,13 @@ function urlKey(url: string): string {
|
|
|
2839
2964
|
}
|
|
2840
2965
|
|
|
2841
2966
|
async function pruneStore(): Promise<void> {
|
|
2967
|
+
const dir = storeDirPath();
|
|
2842
2968
|
try {
|
|
2843
|
-
const names = await readdir(
|
|
2969
|
+
const names = await readdir(dir);
|
|
2844
2970
|
const now = Date.now();
|
|
2845
2971
|
await Promise.all(
|
|
2846
2972
|
names.map(async (n) => {
|
|
2847
|
-
const p = join(
|
|
2973
|
+
const p = join(dir, n);
|
|
2848
2974
|
const st = await stat(p).catch(() => null);
|
|
2849
2975
|
if (st && now - st.mtimeMs > STORE_TTL) await unlink(p).catch(() => {});
|
|
2850
2976
|
}),
|
|
@@ -2855,13 +2981,16 @@ async function pruneStore(): Promise<void> {
|
|
|
2855
2981
|
}
|
|
2856
2982
|
|
|
2857
2983
|
/** 写入一份快照,返回 id 与元数据。写失败不影响本次返回。 */
|
|
2858
|
-
|
|
2984
|
+
// exported for test/integration.mjs(A3 私网快照隔离的单测入口)
|
|
2985
|
+
export async function saveSnapshot(
|
|
2859
2986
|
url: string,
|
|
2860
2987
|
via: string,
|
|
2861
2988
|
text: string,
|
|
2989
|
+
isPrivate?: boolean,
|
|
2862
2990
|
): Promise<StoredMeta | null> {
|
|
2991
|
+
const dir = storeDirPath();
|
|
2863
2992
|
const now = Date.now();
|
|
2864
|
-
const id = `${urlKey(url)}-${now.toString(36)}`;
|
|
2993
|
+
const id = `${urlKey(url)}-${now.toString(36)}-${randomBytes(3).toString("hex")}`;
|
|
2865
2994
|
const meta: StoredMeta = {
|
|
2866
2995
|
id,
|
|
2867
2996
|
url,
|
|
@@ -2869,15 +2998,12 @@ async function saveSnapshot(
|
|
|
2869
2998
|
chars: text.length,
|
|
2870
2999
|
fetched_at: now,
|
|
2871
3000
|
fetched_iso: new Date(now).toISOString(),
|
|
3001
|
+
...(isPrivate !== undefined ? { isPrivate } : {}),
|
|
2872
3002
|
};
|
|
2873
3003
|
try {
|
|
2874
|
-
await mkdir(
|
|
2875
|
-
await
|
|
2876
|
-
await
|
|
2877
|
-
join(STORE_DIR, `${id}.json`),
|
|
2878
|
-
JSON.stringify(meta, null, 2),
|
|
2879
|
-
"utf8",
|
|
2880
|
-
);
|
|
3004
|
+
await mkdir(dir, { recursive: true });
|
|
3005
|
+
await atomicWriteFile(join(dir, `${id}.md`), text);
|
|
3006
|
+
await atomicWriteFile(join(dir, `${id}.json`), JSON.stringify(meta, null, 2));
|
|
2881
3007
|
void pruneStore();
|
|
2882
3008
|
return meta;
|
|
2883
3009
|
} catch {
|
|
@@ -2890,7 +3016,7 @@ async function readMeta(id: string): Promise<StoredMeta | null> {
|
|
|
2890
3016
|
if (!/^[\w-]+$/.test(id)) return null;
|
|
2891
3017
|
try {
|
|
2892
3018
|
return JSON.parse(
|
|
2893
|
-
await readFile(join(
|
|
3019
|
+
await readFile(join(storeDirPath(), `${id}.json`), "utf8"),
|
|
2894
3020
|
) as StoredMeta;
|
|
2895
3021
|
} catch {
|
|
2896
3022
|
return null;
|
|
@@ -2903,22 +3029,27 @@ async function readSnapshot(
|
|
|
2903
3029
|
const meta = await readMeta(id);
|
|
2904
3030
|
if (!meta) return null;
|
|
2905
3031
|
try {
|
|
2906
|
-
return { meta, text: await readFile(join(
|
|
3032
|
+
return { meta, text: await readFile(join(storeDirPath(), `${id}.md`), "utf8") };
|
|
2907
3033
|
} catch {
|
|
2908
3034
|
return null;
|
|
2909
3035
|
}
|
|
2910
3036
|
}
|
|
2911
3037
|
|
|
2912
3038
|
/** 15 分钟内的同 URL 快照(取最新一份)。 */
|
|
2913
|
-
|
|
3039
|
+
// exported for test/integration.mjs
|
|
3040
|
+
export async function findFreshSnapshot(
|
|
3041
|
+
url: string,
|
|
3042
|
+
allowPrivate = false,
|
|
3043
|
+
): Promise<StoredMeta | null> {
|
|
2914
3044
|
const key = urlKey(url);
|
|
2915
3045
|
try {
|
|
2916
|
-
const names = await readdir(
|
|
3046
|
+
const names = await readdir(storeDirPath());
|
|
2917
3047
|
const cands = names.filter((n) => n.startsWith(`${key}-`) && n.endsWith(".json"));
|
|
2918
3048
|
let best: StoredMeta | null = null;
|
|
2919
3049
|
for (const n of cands) {
|
|
2920
3050
|
const m = await readMeta(n.slice(0, -5));
|
|
2921
3051
|
if (!m) continue;
|
|
3052
|
+
if (!allowPrivate && m.isPrivate) continue;
|
|
2922
3053
|
if (Date.now() - m.fetched_at > CACHE_TTL) continue;
|
|
2923
3054
|
if (!best || m.fetched_at > best.fetched_at) best = m;
|
|
2924
3055
|
}
|
|
@@ -2954,7 +3085,7 @@ function sliceText(text: string, offset: number, maxChars: number): Slice {
|
|
|
2954
3085
|
};
|
|
2955
3086
|
}
|
|
2956
3087
|
|
|
2957
|
-
/** find:所有命中位置附近 ±600 字,最多 20 段,标出每段 offset
|
|
3088
|
+
/** find:所有命中位置附近 ±600 字,最多 20 段,标出每段 offset;限制单段与总字符避免高频词撑爆上下文。 */
|
|
2958
3089
|
function findSegments(
|
|
2959
3090
|
text: string,
|
|
2960
3091
|
needle: string,
|
|
@@ -2965,24 +3096,48 @@ function findSegments(
|
|
|
2965
3096
|
if (!q) return [];
|
|
2966
3097
|
const hay = text.toLowerCase();
|
|
2967
3098
|
const pin = q.toLowerCase();
|
|
3099
|
+
const maxSegmentChars = Math.max(radius * 4, 400);
|
|
3100
|
+
const maxTotalChars = 24_000;
|
|
2968
3101
|
const out: Array<{ offset: number; snippet: string }> = [];
|
|
3102
|
+
let totalChars = 0;
|
|
2969
3103
|
let from = 0;
|
|
2970
3104
|
let lastEnd = -1;
|
|
2971
|
-
while (out.length < maxHits) {
|
|
3105
|
+
while (out.length < maxHits && totalChars < maxTotalChars) {
|
|
2972
3106
|
const at = hay.indexOf(pin, from);
|
|
2973
3107
|
if (at < 0) break;
|
|
2974
3108
|
const start = Math.max(0, at - radius);
|
|
2975
3109
|
const end = Math.min(text.length, at + pin.length + radius);
|
|
2976
|
-
// 相邻命中合并成一段,避免同一处重复 20
|
|
2977
|
-
if (start <= lastEnd) {
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
lastEnd
|
|
2981
|
-
|
|
3110
|
+
// 相邻命中合并成一段,避免同一处重复 20 次;超过单段上限后不再延长,避免整页合并
|
|
3111
|
+
if (start <= lastEnd && out.length > 0) {
|
|
3112
|
+
const prev = out[out.length - 1];
|
|
3113
|
+
const prevCap = prev.offset + maxSegmentChars;
|
|
3114
|
+
if (lastEnd < prevCap) {
|
|
3115
|
+
const targetEnd = Math.min(end, prevCap, lastEnd + (maxTotalChars - totalChars));
|
|
3116
|
+
if (targetEnd > lastEnd) {
|
|
3117
|
+
prev.snippet = text.slice(prev.offset, targetEnd);
|
|
3118
|
+
totalChars += targetEnd - lastEnd;
|
|
3119
|
+
lastEnd = targetEnd;
|
|
3120
|
+
}
|
|
3121
|
+
from = at + pin.length;
|
|
3122
|
+
continue;
|
|
3123
|
+
}
|
|
3124
|
+
if (at < lastEnd) {
|
|
3125
|
+
from = lastEnd;
|
|
3126
|
+
continue;
|
|
3127
|
+
}
|
|
3128
|
+
}
|
|
3129
|
+
const segStart = Math.max(start, lastEnd);
|
|
3130
|
+
const avail = maxTotalChars - totalChars;
|
|
3131
|
+
if (avail <= 0) break;
|
|
3132
|
+
const segEnd = Math.min(end, segStart + maxSegmentChars, segStart + avail);
|
|
3133
|
+
if (segEnd <= segStart) {
|
|
3134
|
+
from = Math.max(at + pin.length, lastEnd);
|
|
2982
3135
|
continue;
|
|
2983
3136
|
}
|
|
2984
|
-
|
|
2985
|
-
|
|
3137
|
+
const snippet = text.slice(segStart, segEnd);
|
|
3138
|
+
out.push({ offset: segStart, snippet });
|
|
3139
|
+
totalChars += snippet.length;
|
|
3140
|
+
lastEnd = segEnd;
|
|
2986
3141
|
from = at + pin.length;
|
|
2987
3142
|
}
|
|
2988
3143
|
return out;
|
|
@@ -2997,13 +3152,24 @@ function cacheHeader(meta: StoredMeta): string {
|
|
|
2997
3152
|
function renderBody(
|
|
2998
3153
|
meta: StoredMeta,
|
|
2999
3154
|
slice: Slice,
|
|
3000
|
-
opts: {
|
|
3155
|
+
opts: {
|
|
3156
|
+
cached?: boolean;
|
|
3157
|
+
segments?: Array<{ offset: number; snippet: string }>;
|
|
3158
|
+
/** find 模式:只给命中片段,不把 12000 字正文整段塞回去。 */
|
|
3159
|
+
skipBody?: boolean;
|
|
3160
|
+
} = {},
|
|
3001
3161
|
): string {
|
|
3002
3162
|
const head = [
|
|
3003
3163
|
EXTERNAL_BEGIN(meta.url),
|
|
3004
3164
|
`来源:${meta.via} · 全文 ${meta.chars} 字符 · id=${meta.id}`,
|
|
3005
|
-
`本次返回:offset ${slice.offset}–${slice.offset + slice.text.length}`,
|
|
3006
3165
|
];
|
|
3166
|
+
if (opts.skipBody) {
|
|
3167
|
+
head.push(
|
|
3168
|
+
`本次只返回命中片段(正文 ${meta.chars} 字未展开;要读正文用 id=${meta.id} offset=0)`,
|
|
3169
|
+
);
|
|
3170
|
+
} else {
|
|
3171
|
+
head.push(`本次返回:offset ${slice.offset}–${slice.offset + slice.text.length}`);
|
|
3172
|
+
}
|
|
3007
3173
|
if (opts.cached) head.push(cacheHeader(meta));
|
|
3008
3174
|
const tail: string[] = [];
|
|
3009
3175
|
if (slice.next !== null) {
|
|
@@ -3030,7 +3196,7 @@ function renderBody(
|
|
|
3030
3196
|
return [
|
|
3031
3197
|
...head,
|
|
3032
3198
|
"",
|
|
3033
|
-
slice.text,
|
|
3199
|
+
...(opts.skipBody ? [] : [slice.text]),
|
|
3034
3200
|
...(tail.length ? ["", ...tail] : []),
|
|
3035
3201
|
...segBlock,
|
|
3036
3202
|
"",
|
|
@@ -3048,8 +3214,8 @@ const searchTool = defineTool({
|
|
|
3048
3214
|
"通用网页通道(tf/parallel/youcom/anysearch/tavily/serper/brave/fcs/exa/langsearch)中英各查一遍;" +
|
|
3049
3215
|
"社区/垂直站只用本站语言(知乎/掘金/SegmentFault/千帆/小红书/B站吃中文,StackExchange/HN/GitHub/OpenAlex/Crossref/Firecrawl 开发者与论文索引吃英文)。" +
|
|
3050
3216
|
"结果跨源去重合并排序,每条标〔中/英/中英〕,头部写中英各几条。" +
|
|
3051
|
-
"profile=auto(默认)= 固定底座 tf+parallel+
|
|
3052
|
-
"(gh 仓库 / oalex,fcres 论文 / se,fcdev 排障 / hn / jj,segfault / xhs,bili,zhihu 口碑 / wiki / qianfan
|
|
3217
|
+
"profile=auto(默认)= 固定底座 tf+parallel+anysearch+tavily(纯免费)+ 模型按意图补 0-3 个专项通道" +
|
|
3218
|
+
"(gh 仓库 / oalex,fcres 论文 / se,fcdev 排障 / hn / jj,segfault / xhs,bili,zhihu,zhihuall,zhihuhot,zhida 口碑 / wiki / qianfan / langsearch / serper / youcom 按需快搜)。" +
|
|
3053
3219
|
"规则覆盖不到时用 channels 显式指定(如 channels='hn,exa');显式 channels 是本轮白名单,不改默认清单。" +
|
|
3054
3220
|
"调研纪律(做方案调研/选型时):第一轮 query 禁止含产品名或技术栈(llama.cpp、Ollama、模型名、框架名、某库名),只写约束(硬件、平台、任务、时间、预算);先扫出 ≥3 个候选并列进表,再深挖单个选手。不确定该用哪家时,产品名一进 query 就把答案锁死了。" +
|
|
3055
3221
|
"执行纪律:一次铺开并发跑(串行单路再补查是浪费轮次),铺开结果出来前不下结论;" +
|
|
@@ -3069,7 +3235,7 @@ const searchTool = defineTool({
|
|
|
3069
3235
|
],
|
|
3070
3236
|
{
|
|
3071
3237
|
description:
|
|
3072
|
-
"auto=免费底座
|
|
3238
|
+
"auto=免费底座 4 路 + 模型补 0-3 个专项(默认);quick=3 路候选;base=22 条注册路由;deep=27 条注册路由;实际请求数受默认启用清单影响;任何档位都中英双查",
|
|
3073
3239
|
},
|
|
3074
3240
|
),
|
|
3075
3241
|
),
|
|
@@ -3233,7 +3399,7 @@ const searchTool = defineTool({
|
|
|
3233
3399
|
"fcdev 官方文档 / se 报错 / hn 技术观点 / jj,segfault 中文技术(仅技术) / " +
|
|
3234
3400
|
"oalex,crossref 学术元数据 / langsearch 时效 / exa 英文语义 / " +
|
|
3235
3401
|
"fcres 论文全文 / serper Google(本地生活/电商) / fcs Firecrawl v2 Search / wiki 维基百科 / " +
|
|
3236
|
-
"tavily 全网正文摘录(免key) / parallel 语义(免key) / youcom 快搜(
|
|
3402
|
+
"tavily 全网正文摘录(免key) / parallel 语义(免key) / youcom 快搜(按需/有key付费REST/无key兜底MCP) / " +
|
|
3237
3403
|
"anysearch 垂直专库 / gh GitHub 仓库 / xhs 国内版小红书 / bili B站";
|
|
3238
3404
|
const head =
|
|
3239
3405
|
`d-reach ${PROFILES[profile].label} · ${secs.toFixed(1)}s` +
|
|
@@ -3349,7 +3515,13 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3349
3515
|
),
|
|
3350
3516
|
}),
|
|
3351
3517
|
|
|
3352
|
-
async execute(_id, params: FetchParams) {
|
|
3518
|
+
async execute(_id, params: FetchParams, signal?: AbortSignal) {
|
|
3519
|
+
if (signal?.aborted) {
|
|
3520
|
+
return {
|
|
3521
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3522
|
+
details: { aborted: true },
|
|
3523
|
+
};
|
|
3524
|
+
}
|
|
3353
3525
|
const maxChars = Math.min(Math.max(params.max_chars ?? 12000, 500), 40000);
|
|
3354
3526
|
const offset = Math.max(Math.floor(params.offset ?? 0), 0);
|
|
3355
3527
|
const url = (params.url ?? "").trim();
|
|
@@ -3387,11 +3559,16 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3387
3559
|
const segments = params.find
|
|
3388
3560
|
? findSegments(snap.text, params.find)
|
|
3389
3561
|
: undefined;
|
|
3562
|
+
// 只给 find 不给 offset = 纯查找:命中就用片段回答,不再附 12000 字正文。
|
|
3563
|
+
const skipBody =
|
|
3564
|
+
params.find !== undefined &&
|
|
3565
|
+
params.offset === undefined &&
|
|
3566
|
+
(segments?.length ?? 0) > 0;
|
|
3390
3567
|
return {
|
|
3391
3568
|
content: [
|
|
3392
3569
|
{
|
|
3393
3570
|
type: "text" as const,
|
|
3394
|
-
text: renderBody(snap.meta, slice, { cached, segments }),
|
|
3571
|
+
text: renderBody(snap.meta, slice, { cached, segments, skipBody }),
|
|
3395
3572
|
},
|
|
3396
3573
|
],
|
|
3397
3574
|
details: {
|
|
@@ -3400,7 +3577,7 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3400
3577
|
via: snap.meta.via,
|
|
3401
3578
|
chars: snap.meta.chars,
|
|
3402
3579
|
offset: slice.offset,
|
|
3403
|
-
returned: slice.text.length,
|
|
3580
|
+
returned: skipBody ? 0 : slice.text.length,
|
|
3404
3581
|
nextOffset: slice.next,
|
|
3405
3582
|
cached,
|
|
3406
3583
|
fetchedAt: snap.meta.fetched_iso,
|
|
@@ -3426,16 +3603,71 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3426
3603
|
return serveStored(snap, false);
|
|
3427
3604
|
}
|
|
3428
3605
|
|
|
3606
|
+
const allowPrivate = params.allow_private === true;
|
|
3607
|
+
let urlIsPrivate = false;
|
|
3608
|
+
if (url) {
|
|
3609
|
+
let target: TargetInfo;
|
|
3610
|
+
try {
|
|
3611
|
+
target = await inspectTarget(url);
|
|
3612
|
+
} catch (e) {
|
|
3613
|
+
if (e instanceof BlockedTarget) {
|
|
3614
|
+
return {
|
|
3615
|
+
content: [
|
|
3616
|
+
{
|
|
3617
|
+
type: "text" as const,
|
|
3618
|
+
text: `抓取失败:${url}\n- 地址校验:网络不通 — ${e.message}\n\n**已拒绝**:这是安全策略拦截,不是抓取失败。确认目标可信后再考虑 allow_private。`,
|
|
3619
|
+
},
|
|
3620
|
+
],
|
|
3621
|
+
details: { url, blocked: e.message },
|
|
3622
|
+
isError: true,
|
|
3623
|
+
};
|
|
3624
|
+
}
|
|
3625
|
+
throw e;
|
|
3626
|
+
}
|
|
3627
|
+
urlIsPrivate = target.isPrivate;
|
|
3628
|
+
if (target.isPrivate && !allowPrivate) {
|
|
3629
|
+
const msg = blockedMessage(target);
|
|
3630
|
+
return {
|
|
3631
|
+
content: [
|
|
3632
|
+
{
|
|
3633
|
+
type: "text" as const,
|
|
3634
|
+
text: `抓取失败:${url}\n- 地址校验:网络不通 — ${msg}\n\n**已拒绝**:这是安全策略拦截,不是抓取失败。确认目标可信后再考虑 allow_private。`,
|
|
3635
|
+
},
|
|
3636
|
+
],
|
|
3637
|
+
details: { url, blocked: msg },
|
|
3638
|
+
isError: true,
|
|
3639
|
+
};
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3429
3643
|
// 15 分钟缓存:同一 URL(规范化后)直接复用存盘
|
|
3430
3644
|
if (!params.fresh) {
|
|
3431
|
-
const hit = await findFreshSnapshot(url);
|
|
3645
|
+
const hit = await findFreshSnapshot(url, allowPrivate);
|
|
3432
3646
|
if (hit) {
|
|
3433
3647
|
const snap = await readSnapshot(hit.id);
|
|
3434
|
-
if (snap
|
|
3648
|
+
if (snap && (allowPrivate || !snap.meta.isPrivate))
|
|
3649
|
+
return serveStored(snap, true);
|
|
3435
3650
|
}
|
|
3436
3651
|
}
|
|
3437
3652
|
|
|
3438
|
-
|
|
3653
|
+
let r: Awaited<ReturnType<typeof fetchUrl>>;
|
|
3654
|
+
try {
|
|
3655
|
+
r = await fetchUrl(url, allowPrivate, signal);
|
|
3656
|
+
} catch (err) {
|
|
3657
|
+
if (isAborted(err, signal)) {
|
|
3658
|
+
return {
|
|
3659
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3660
|
+
details: { aborted: true },
|
|
3661
|
+
};
|
|
3662
|
+
}
|
|
3663
|
+
throw err;
|
|
3664
|
+
}
|
|
3665
|
+
if (signal?.aborted) {
|
|
3666
|
+
return {
|
|
3667
|
+
content: [{ type: "text" as const, text: "已中止" }],
|
|
3668
|
+
details: { aborted: true },
|
|
3669
|
+
};
|
|
3670
|
+
}
|
|
3439
3671
|
const secs = ((Date.now() - t0) / 1000).toFixed(1);
|
|
3440
3672
|
|
|
3441
3673
|
if (!r.ok) {
|
|
@@ -3493,7 +3725,7 @@ const fetchTool = defineTool<any, Record<string, unknown>>({
|
|
|
3493
3725
|
|
|
3494
3726
|
// 完整正文(截断前)先落盘,再按 offset/max_chars 切片返回
|
|
3495
3727
|
const meta =
|
|
3496
|
-
(await saveSnapshot(url, r.got.via, r.got.text)) ?? {
|
|
3728
|
+
(await saveSnapshot(url, r.got.via, r.got.text, urlIsPrivate)) ?? {
|
|
3497
3729
|
id: "(未存盘)",
|
|
3498
3730
|
url,
|
|
3499
3731
|
via: r.got.via,
|
|
@@ -3546,11 +3778,26 @@ const quotaTool = defineTool({
|
|
|
3546
3778
|
),
|
|
3547
3779
|
}),
|
|
3548
3780
|
|
|
3549
|
-
async execute(_id, params) {
|
|
3781
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
3782
|
+
if (signal?.aborted) {
|
|
3783
|
+
return {
|
|
3784
|
+
content: [{ type: "text", text: "已中止" }],
|
|
3785
|
+
details: { aborted: true },
|
|
3786
|
+
};
|
|
3787
|
+
}
|
|
3550
3788
|
if (params.refresh) {
|
|
3551
3789
|
try {
|
|
3552
|
-
await
|
|
3553
|
-
|
|
3790
|
+
await runCommand("python3", [PROBE, "--max-age", "0"], {
|
|
3791
|
+
timeoutMs: 30_000,
|
|
3792
|
+
signal,
|
|
3793
|
+
});
|
|
3794
|
+
} catch (err) {
|
|
3795
|
+
if (isAborted(err, signal)) {
|
|
3796
|
+
return {
|
|
3797
|
+
content: [{ type: "text", text: "已中止" }],
|
|
3798
|
+
details: { aborted: true },
|
|
3799
|
+
};
|
|
3800
|
+
}
|
|
3554
3801
|
/* 校准失败不影响本地账本展示 */
|
|
3555
3802
|
}
|
|
3556
3803
|
}
|
|
@@ -3561,82 +3808,19 @@ const quotaTool = defineTool({
|
|
|
3561
3808
|
return {};
|
|
3562
3809
|
}
|
|
3563
3810
|
};
|
|
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", " ")}`);
|
|
3811
|
+
const quota = await readJson(quotaFilePath());
|
|
3812
|
+
const health = await readJson(healthFilePath());
|
|
3813
|
+
const summary = summarizeQuotaAndHealth(quota, health);
|
|
3637
3814
|
return {
|
|
3638
|
-
content: [{ type: "text", text: lines.join("\n") }],
|
|
3639
|
-
details: {
|
|
3815
|
+
content: [{ type: "text", text: summary.lines.join("\n") }],
|
|
3816
|
+
details: {
|
|
3817
|
+
quota: summary.normalizedQuota,
|
|
3818
|
+
health,
|
|
3819
|
+
rows: summary.rows,
|
|
3820
|
+
suspended: summary.bad,
|
|
3821
|
+
needsAction: summary.need,
|
|
3822
|
+
expiredSuspensions: summary.expiredSuspensions,
|
|
3823
|
+
},
|
|
3640
3824
|
};
|
|
3641
3825
|
},
|
|
3642
3826
|
});
|
|
@@ -3651,9 +3835,11 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3651
3835
|
pi.registerTool(decideTool);
|
|
3652
3836
|
// 融合层(pwa.ts):d_reach_check / d_reach_video;GitHub 与视频分流入口为 routeSpecialUrl
|
|
3653
3837
|
// 第二参数是 allowPrivate:融合层抓取一律按公网规则,绝不放行内网
|
|
3654
|
-
registerPwaTools(pi, (u: string
|
|
3838
|
+
registerPwaTools(pi, (u: string, _maxChars?: number, signal?: AbortSignal) =>
|
|
3839
|
+
fetchUrl(u, false, signal),
|
|
3840
|
+
);
|
|
3655
3841
|
|
|
3656
|
-
const
|
|
3842
|
+
const runSlashSearch = async (args: string, ctx: any, profile: Profile) => {
|
|
3657
3843
|
const query = args.trim();
|
|
3658
3844
|
if (!query) return ctx.ui.notify("用法:/reach <检索词>", "warning");
|
|
3659
3845
|
ctx.ui.notify(`d-reach ${profile} 检索中:${query}`, "info");
|
|
@@ -3670,6 +3856,10 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3670
3856
|
"info",
|
|
3671
3857
|
);
|
|
3672
3858
|
} catch (err) {
|
|
3859
|
+
if (isAborted(err, ctx?.signal)) {
|
|
3860
|
+
ctx.ui.notify("已中止", "warning");
|
|
3861
|
+
return;
|
|
3862
|
+
}
|
|
3673
3863
|
ctx.ui.notify(
|
|
3674
3864
|
`失败:${err instanceof Error ? err.message : String(err)}`,
|
|
3675
3865
|
"error",
|
|
@@ -3679,11 +3869,11 @@ export default function dReachExtension(pi: ExtensionAPI) {
|
|
|
3679
3869
|
|
|
3680
3870
|
pi.registerCommand("reach", {
|
|
3681
3871
|
description: "d-reach 检索(auto 按意图选路)",
|
|
3682
|
-
handler: (args, ctx) =>
|
|
3872
|
+
handler: (args, ctx) => runSlashSearch(args, ctx, "auto"),
|
|
3683
3873
|
});
|
|
3684
3874
|
pi.registerCommand("reach-deep", {
|
|
3685
3875
|
description: "d-reach 检索(deep 27 路含限额通道)",
|
|
3686
|
-
handler: (args, ctx) =>
|
|
3876
|
+
handler: (args, ctx) => runSlashSearch(args, ctx, "deep"),
|
|
3687
3877
|
});
|
|
3688
3878
|
}
|
|
3689
3879
|
|
|
@@ -3733,12 +3923,14 @@ const SOCIAL = {
|
|
|
3733
3923
|
type SocialPlatform = keyof typeof SOCIAL;
|
|
3734
3924
|
const SOCIAL_LABEL: Record<SocialPlatform, string> = { bili: "B站", xhs: "小红书" };
|
|
3735
3925
|
|
|
3736
|
-
async function probeSocial(p: SocialPlatform) {
|
|
3926
|
+
async function probeSocial(p: SocialPlatform, signal?: AbortSignal) {
|
|
3927
|
+
if (signal?.aborted) throw abortedError();
|
|
3737
3928
|
const meta = SOCIAL[p];
|
|
3738
3929
|
let installed = true;
|
|
3739
3930
|
try {
|
|
3740
|
-
await
|
|
3741
|
-
} catch {
|
|
3931
|
+
await runCommand(meta.bin, ["--version"], { timeoutMs: 6000, signal });
|
|
3932
|
+
} catch (e) {
|
|
3933
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3742
3934
|
installed = false;
|
|
3743
3935
|
}
|
|
3744
3936
|
if (!installed)
|
|
@@ -3750,21 +3942,25 @@ async function probeSocial(p: SocialPlatform) {
|
|
|
3750
3942
|
|
|
3751
3943
|
let authFileAge: string | null = null;
|
|
3752
3944
|
try {
|
|
3753
|
-
const { stdout } = await
|
|
3754
|
-
|
|
3945
|
+
const { stdout } = await runCommand("stat", ["-c", "%y", meta.authFile], {
|
|
3946
|
+
timeoutMs: 5000,
|
|
3947
|
+
signal,
|
|
3755
3948
|
});
|
|
3756
3949
|
authFileAge = stdout.trim().slice(0, 10);
|
|
3757
|
-
} catch {
|
|
3950
|
+
} catch (e) {
|
|
3951
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3758
3952
|
/* 文件不存在也算信息 */
|
|
3759
3953
|
}
|
|
3760
3954
|
|
|
3761
3955
|
let out = "";
|
|
3762
3956
|
try {
|
|
3763
|
-
const r = await
|
|
3764
|
-
|
|
3957
|
+
const r = await runCommand(meta.bin, meta.whoami.slice(1), {
|
|
3958
|
+
timeoutMs: 25_000,
|
|
3959
|
+
signal,
|
|
3765
3960
|
});
|
|
3766
3961
|
out = r.stdout + r.stderr;
|
|
3767
3962
|
} catch (e) {
|
|
3963
|
+
if (isAborted(e, signal)) throw abortedError();
|
|
3768
3964
|
// 未登录时通常非 0 退出码,真因在 stdout/stderr 里,别把 "Command failed" 当结论
|
|
3769
3965
|
out =
|
|
3770
3966
|
String((e as { stdout?: string; stderr?: string })?.stdout ?? "") +
|
|
@@ -3848,11 +4044,33 @@ const socialTool = defineTool({
|
|
|
3848
4044
|
),
|
|
3849
4045
|
}),
|
|
3850
4046
|
|
|
3851
|
-
async execute(_id, params) {
|
|
4047
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
4048
|
+
if (signal?.aborted) {
|
|
4049
|
+
return {
|
|
4050
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4051
|
+
details: { aborted: true },
|
|
4052
|
+
};
|
|
4053
|
+
}
|
|
3852
4054
|
const platforms = params.platform
|
|
3853
4055
|
? [params.platform]
|
|
3854
4056
|
: (["bili", "xhs"] as SocialPlatform[]);
|
|
3855
|
-
const
|
|
4057
|
+
const searching = Boolean(params.query);
|
|
4058
|
+
// 只搜索时不必先体检:B站公开搜索免登录,XHS 的登录错误由 CLI 自己报,
|
|
4059
|
+
// 多跑一次 CLI 只为了拿一行状态是浪费。
|
|
4060
|
+
let probes: Awaited<ReturnType<typeof probeSocial>>[] = [];
|
|
4061
|
+
try {
|
|
4062
|
+
if (!searching) {
|
|
4063
|
+
probes = await Promise.all(platforms.map((p) => probeSocial(p, signal)));
|
|
4064
|
+
}
|
|
4065
|
+
} catch (e) {
|
|
4066
|
+
if (isAborted(e, signal)) {
|
|
4067
|
+
return {
|
|
4068
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4069
|
+
details: { aborted: true },
|
|
4070
|
+
};
|
|
4071
|
+
}
|
|
4072
|
+
throw e;
|
|
4073
|
+
}
|
|
3856
4074
|
|
|
3857
4075
|
const lines: string[] = [];
|
|
3858
4076
|
for (const pr of probes) {
|
|
@@ -3882,55 +4100,53 @@ const socialTool = defineTool({
|
|
|
3882
4100
|
};
|
|
3883
4101
|
}
|
|
3884
4102
|
|
|
3885
|
-
//
|
|
3886
|
-
const
|
|
3887
|
-
if (!target) {
|
|
3888
|
-
return {
|
|
3889
|
-
content: [
|
|
3890
|
-
{
|
|
3891
|
-
type: "text",
|
|
3892
|
-
text: `${lines.join("\n")}\n\n登录态不可用,换个通道或先修登录态再搜。`,
|
|
3893
|
-
},
|
|
3894
|
-
],
|
|
3895
|
-
isError: true,
|
|
3896
|
-
};
|
|
3897
|
-
}
|
|
3898
|
-
|
|
4103
|
+
// 不指定 platform 也能直接搜:默认 B站(公开搜索免登录);要小红书请显式给 platform=xhs。
|
|
4104
|
+
const targetPlatform: SocialPlatform = params.platform ?? "bili";
|
|
3899
4105
|
const n = Math.min(Math.max(params.limit ?? 8, 1), 20);
|
|
3900
|
-
const meta = SOCIAL[
|
|
4106
|
+
const meta = SOCIAL[targetPlatform];
|
|
4107
|
+
const note = params.platform ? "" : "(未指定 platform,默认走 B站)\n\n";
|
|
3901
4108
|
try {
|
|
3902
|
-
const { stdout } = await
|
|
4109
|
+
const { stdout } = await runCommand(
|
|
3903
4110
|
meta.bin,
|
|
3904
4111
|
meta.search(params.query, n).slice(1),
|
|
3905
4112
|
{
|
|
3906
|
-
|
|
4113
|
+
timeoutMs: 40_000,
|
|
3907
4114
|
maxBuffer: 4 << 20,
|
|
4115
|
+
signal,
|
|
3908
4116
|
},
|
|
3909
4117
|
);
|
|
3910
4118
|
let rendered = stdout.trim();
|
|
3911
4119
|
try {
|
|
3912
4120
|
const parsed = JSON.parse(rendered) as { data?: any; result?: any };
|
|
3913
|
-
rendered = renderSocial(
|
|
4121
|
+
rendered = renderSocial(targetPlatform, parsed);
|
|
3914
4122
|
} catch {
|
|
3915
|
-
|
|
4123
|
+
if (rendered.length > 12_000) {
|
|
4124
|
+
rendered = `${rendered.slice(0, 12_000)}\n…(已截断)`;
|
|
4125
|
+
}
|
|
3916
4126
|
}
|
|
3917
4127
|
return {
|
|
3918
4128
|
content: [
|
|
3919
4129
|
{
|
|
3920
4130
|
type: "text",
|
|
3921
|
-
text:
|
|
4131
|
+
text: `${note}[${SOCIAL_LABEL[targetPlatform]}] 搜索「${params.query}」\n\n${rendered}`,
|
|
3922
4132
|
},
|
|
3923
4133
|
],
|
|
3924
|
-
details: { platform:
|
|
4134
|
+
details: { platform: targetPlatform, query: params.query, limit: n },
|
|
3925
4135
|
};
|
|
3926
4136
|
} catch (e) {
|
|
4137
|
+
if (isAborted(e, signal)) {
|
|
4138
|
+
return {
|
|
4139
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4140
|
+
details: { aborted: true },
|
|
4141
|
+
};
|
|
4142
|
+
}
|
|
3927
4143
|
return {
|
|
3928
4144
|
content: [
|
|
3929
4145
|
{
|
|
3930
4146
|
type: "text",
|
|
3931
4147
|
text:
|
|
3932
|
-
`[${SOCIAL_LABEL[
|
|
3933
|
-
`\n
|
|
4148
|
+
`[${SOCIAL_LABEL[targetPlatform]}] 搜索失败:${e instanceof Error ? e.message.slice(0, 200) : "未知"}。` +
|
|
4149
|
+
`\n如果是风控/限流,隔几分钟再试;想看登录态就不传 query 跑一次 d_reach_social。`,
|
|
3934
4150
|
},
|
|
3935
4151
|
],
|
|
3936
4152
|
isError: true,
|
|
@@ -3981,7 +4197,13 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
3981
4197
|
),
|
|
3982
4198
|
}),
|
|
3983
4199
|
|
|
3984
|
-
async execute(_id, params) {
|
|
4200
|
+
async execute(_id, params, signal?: AbortSignal) {
|
|
4201
|
+
if (signal?.aborted) {
|
|
4202
|
+
return {
|
|
4203
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4204
|
+
details: { aborted: true },
|
|
4205
|
+
};
|
|
4206
|
+
}
|
|
3985
4207
|
const questions: Record<string, unknown> = {};
|
|
3986
4208
|
for (const q of params.questions) {
|
|
3987
4209
|
const spec: Record<string, unknown> = {
|
|
@@ -3994,7 +4216,7 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
3994
4216
|
}
|
|
3995
4217
|
|
|
3996
4218
|
try {
|
|
3997
|
-
const { stdout } = await
|
|
4219
|
+
const { stdout } = await runCommand(
|
|
3998
4220
|
"python3",
|
|
3999
4221
|
[
|
|
4000
4222
|
MCP_CALL,
|
|
@@ -4002,7 +4224,12 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
4002
4224
|
"web_decisions",
|
|
4003
4225
|
JSON.stringify({ state: { topic: params.state }, questions }),
|
|
4004
4226
|
],
|
|
4005
|
-
{
|
|
4227
|
+
{
|
|
4228
|
+
maxBuffer: 8 << 20,
|
|
4229
|
+
timeoutMs: 90_000,
|
|
4230
|
+
env: { ...process.env, D_REACH_MCP_BUDGET: "85" },
|
|
4231
|
+
signal,
|
|
4232
|
+
},
|
|
4006
4233
|
);
|
|
4007
4234
|
const raw = stdout.trim();
|
|
4008
4235
|
if (raw.startsWith("MCP_ERROR")) {
|
|
@@ -4081,6 +4308,12 @@ questions=[{name:"ticket", type:"choice", instructions:"是否需要买票进入
|
|
|
4081
4308
|
details: { state: params.state, answers: d.answers, citations: cites },
|
|
4082
4309
|
};
|
|
4083
4310
|
} catch (e) {
|
|
4311
|
+
if (isAborted(e, signal)) {
|
|
4312
|
+
return {
|
|
4313
|
+
content: [{ type: "text", text: "已中止" }],
|
|
4314
|
+
details: { aborted: true },
|
|
4315
|
+
};
|
|
4316
|
+
}
|
|
4084
4317
|
return {
|
|
4085
4318
|
content: [
|
|
4086
4319
|
{
|