@duanz/pi-d-reach 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1944 @@
1
+ #!/usr/bin/env bash
2
+ # fanout.sh —— d-reach 并行铺开器(「全加全扩」落地件)
3
+ #
4
+ # 一条命令并发运行启用清单里的通道;--deep 追加 enabledForDeep 清单里的 deep 通道。
5
+ # 轮 1 发现一律走它,别一条一条串行试:
6
+ # 实测 3 路串行 2.95s vs 并行 1.30s —— 铺开耗时 ≈ 最慢一路,与路数基本无关。
7
+ #
8
+ # 用法:
9
+ # fanout.sh "<query>" # 运行 enabledByDefault 正向清单
10
+ # fanout.sh "<query>" --deep # 追加 enabledForDeep 清单
11
+ # fanout.sh "<query>" --n 8 # 每路最多列几条(默认 5)
12
+ # fanout.sh "<query>" --on hn,oalex # 本轮白名单
13
+ # fanout.sh "<query>" --recency week # 只要最近一周(day|week|month|year)
14
+ # fanout.sh "<query>" --domains "a.com,-b.a.com" # 站内/排除(无前缀=只要这些站,- 前缀=排除)
15
+ # fanout.sh --list # 列出通道与默认启用状态
16
+ # fanout.sh --list --json # 插件和网关共用的机器可读路由信息
17
+ # 默认清单:~/.agent-reach/fanout-defaults.json;D_REACH_DEFAULTS_FILE 可覆盖路径。
18
+ #
19
+ # 记账: 免费免 Key 通道不记账;deep 下 LangSearch/Exa 调用前自动
20
+ # `quota.py use`,退出码 1(越免费线)→ 自动跳过该路并在输出里标注,
21
+ # 不拖死其他路。百度千帆由它自己的计数器记账,这里不双扣。
22
+ # tf(TinyFish)需 TINYFISH_API_KEY 但 search $0.00/次 → 只 gate key 不记账。
23
+ #
24
+ # 通道命名(--on 用):
25
+ # se hn jj zhihu zhihuall oalex crossref segfault fcdev qianfan tf xhs bili | deep: langsearch exa fcres zhihuhot zhida
26
+ #
27
+ # 已退役通道(别往回加):
28
+ # · 博客园 zzk.cnblogs.com —— 302→zzkx 后返回 5.7KB 壳页、0 结果
29
+ # · V2EX search —— /search?q= 302→/go/search,返回节点帖子列表、与 query 无关(假结果)
30
+ # 中文社区长尾现在靠 掘金 + SegmentFault + 知乎。
31
+
32
+ set -u
33
+
34
+ # 解析自身软链再取目录:plugin/scripts 里是逐文件软链(指向本技能真目录),
35
+ # 直接取 dirname($0) 会停在 plugin/scripts,那里没有 route_config.py 这类新加脚本。
36
+ _SELF=$(readlink -f -- "$0" 2>/dev/null) || _SELF="$0"
37
+ DIR="$(CDPATH= cd -- "$(dirname -- "$_SELF")" && pwd -P)"
38
+ QUOTA="$DIR/quota.py"
39
+ DEFAULTS_FILE="${D_REACH_DEFAULTS_FILE:-$HOME/.agent-reach/fanout-defaults.json}"
40
+ SKILLS="$HOME/.agents/skills"; [ -d "$SKILLS" ] || SKILLS=/var/minis/skills
41
+ # 千帆配套技能目录名有两版:历史/本机 baiduaisearchwithquota,viking 分发版按 slug 落成
42
+ # baidu-ai-search。两个都探,先命中先用;都没有时 qianfan 标记未配置并跳过。
43
+ BAIDU=""
44
+ for _bd in "$SKILLS/baiduaisearchwithquota/scripts" "$SKILLS/baidu-ai-search/scripts"; do
45
+ [ -f "$_bd/smart_search.py" ] && { BAIDU="$_bd"; break; }
46
+ done
47
+ [ -n "$BAIDU" ] || BAIDU="$SKILLS/baiduaisearchwithquota/scripts"
48
+ UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"
49
+ BASE_CHANNELS="qianfan gh fcdev se hn jj zhihu zhihuall brave segfault oalex crossref tf serper tavily parallel youcom anysearch fcs wiki xhs bili"
50
+ DEEP_CHANNELS="zhihuhot zhida langsearch exa fcres"
51
+ KNOWN="$BASE_CHANNELS $DEEP_CHANNELS"
52
+
53
+ # ---------- 参数 ----------
54
+ Q=""; ENQ=""; ZHQ=""; DEEP=0; N=5; N_SET=0; ON=""; DEFAULT_DISABLED=""; ON_SET=0; FORCE=0
55
+ RECENCY=""; DOMAINS=""
56
+ LIST=0; LIST_FORMAT=table
57
+ while [ $# -gt 0 ]; do
58
+ case "$1" in
59
+ --deep) DEEP=1 ;;
60
+ --n) shift; N="${1:-5}"; N_SET=1 ;;
61
+ --on) shift; ON="${1:-}"; ON_SET=1 ;;
62
+ --en) shift; ENQ="${1:-}" ;; # 英文检索词:LLM 把 query 译好后传进来,英文通道用它
63
+ --zh) shift; ZHQ="${1:-}" ;; # 中文检索词:同上,中文通道用它;--zh 与 --en 不同时,通用网页通道中英各查一遍
64
+ --force) FORCE=1 ;; # 忽略健康状态,强制跑(调试/复检用)
65
+ --recency) shift; RECENCY="${1:-}" ;; # 时间过滤:day|week|month|year(能原生传的通道传原生参数)
66
+ --domains) shift; DOMAINS="${1:-}" ;; # 网站过滤:a.com 只要这些站;-c.com 排除(- 优先)
67
+ --list) LIST=1 ;;
68
+ --json) LIST_FORMAT=json ;; # 配合 --list;与它前后顺序无关
69
+ -h|--help) sed -n '2,30p' "$0" | grep '^#' | sed 's/^# \{0,1\}//'; exit 0 ;;
70
+ --*) echo "[fanout] 未知参数:$1" >&2; exit 2 ;;
71
+ *) [ -z "$Q" ] && Q="$1" ;;
72
+ esac
73
+ shift
74
+ done
75
+ if [ "$LIST" = "1" ]; then
76
+ python3 "$DIR/route_config.py" --script "$0" --defaults "$DEFAULTS_FILE" \
77
+ --base "$BASE_CHANNELS" --deep "$DEEP_CHANNELS" --format "$LIST_FORMAT"
78
+ exit $?
79
+ fi
80
+ ENQ="${ENQ:-$Q}" # 没给 --en 时英文通道退回原 query,行为与改动前一致
81
+ ZHQ="${ZHQ:-$Q}" # 没给 --zh 时中文通道退回原 query
82
+ if [ -z "$Q" ]; then echo "usage: fanout.sh \"<query>\" [--deep] [--n N] [--on chans] [--zh \"<中文>\"] [--en \"<english>\"] [--recency day|week|month|year] [--domains \"a.com,-b.com\"]"; exit 2; fi
83
+ case "$RECENCY" in
84
+ ""|day|week|month|year) ;;
85
+ *) echo "[fanout] --recency 只能是 day|week|month|year" >&2; exit 2 ;;
86
+ esac
87
+
88
+ # 时间/网站过滤:原生支持的通道走各家 API 参数,其余在 python 合并阶段按 URL 主机名本地过滤。
89
+ # Serper 用 tbs=qdr:d/w/m/y;Brave 用 freshness=pd/pw/pm/py;Tavily/Exa/LangSearch 在各自 JSON body 里传。
90
+ _TBS=""
91
+ case "$RECENCY" in
92
+ day) _TBS=qdr:d ;; week) _TBS=qdr:w ;; month) _TBS=qdr:m ;; year) _TBS=qdr:y ;;
93
+ esac
94
+ # include/exclude 域名列表(JSON 数组):本地过滤与 Tavily/Exa 原生参数共用同一份解析。
95
+ _DOM_JSON=$(python3 - "$DOMAINS" <<'PYDOM'
96
+ import json, sys
97
+ inc, exc = [], []
98
+ for raw in (sys.argv[1] or "").split(","):
99
+ d = raw.strip().lower()
100
+ if not d:
101
+ continue
102
+ neg = d.startswith("-")
103
+ if neg:
104
+ d = d[1:]
105
+ d = d.split("://", 1)[-1].split("/", 1)[0].strip(".")
106
+ if not d:
107
+ continue
108
+ (exc if neg else inc).append(d)
109
+ print(json.dumps([inc, exc]))
110
+ PYDOM
111
+ ) || _DOM_JSON='[[],[]]'
112
+ _INC_JSON=$(python3 -c 'import json,sys;print(json.dumps(json.loads(sys.argv[1])[0]))' "$_DOM_JSON" 2>/dev/null || echo '[]')
113
+ _EXC_JSON=$(python3 -c 'import json,sys;print(json.dumps(json.loads(sys.argv[1])[1]))' "$_DOM_JSON" 2>/dev/null || echo '[]')
114
+ export D_REACH_RECENCY="$RECENCY" D_REACH_DOMAINS="$DOMAINS" D_REACH_TBS="$_TBS"
115
+ export D_REACH_INC_JSON="$_INC_JSON" D_REACH_EXC_JSON="$_EXC_JSON"
116
+
117
+ DEFAULT_LISTS=$(python3 "$DIR/route_config.py" --script "$0" --defaults "$DEFAULTS_FILE" \
118
+ --base "$BASE_CHANNELS" --deep "$DEEP_CHANNELS" --format lists) \
119
+ || { echo "[fanout] 路由配置加载失败(原因见上一条);配置文件:$DEFAULTS_FILE" >&2; exit 2; }
120
+ DEFAULT_LISTS_BASE="${DEFAULT_LISTS%%|*}"
121
+ DEFAULT_LISTS_DEEP="${DEFAULT_LISTS#*|}"
122
+
123
+ # --on 是本轮白名单;未知项剔除,若没有有效项则报错,避免意外跑全量。
124
+ if [ "$ON_SET" = "1" ]; then
125
+ [ -n "$ON" ] || { echo "[fanout] --on 需要通道名" >&2; exit 2; }
126
+ _bad=""; _good=""
127
+ for _c in $(echo "$ON" | tr ',' ' '); do
128
+ case " $KNOWN " in *" $_c "*) _good="$_good,$_c" ;; *) _bad="$_bad $_c" ;; esac
129
+ done
130
+ if [ -n "$_bad" ]; then
131
+ echo "[fanout] 忽略未知 --on 通道:$_bad(可用: $KNOWN)" >&2
132
+ fi
133
+ ON="${_good#,}"
134
+ [ -n "$ON" ] || { echo "[fanout] --on 没有匹配到可用通道" >&2; exit 2; }
135
+ fi
136
+ case "$N" in ''|*[!0-9]*) echo "[fanout] --n 必须是正整数" >&2; exit 2 ;; esac
137
+
138
+ # --on 里点名了 deep 专属通道 → 自动按 deep 跑(省得再写一遍 --deep)
139
+ case ",$ON," in
140
+ *,langsearch,*|*,exa,*|*,fcres,*|*,zhihuhot,*|*,zhida,*) DEEP=1 ;;
141
+ esac
142
+
143
+ # Default runs use the positive allowlist; --on supplies a one-call override.
144
+ if [ "$ON_SET" != "1" ]; then
145
+ _default_scope="$BASE_CHANNELS"
146
+ _default_active="$DEFAULT_LISTS_BASE"
147
+ if [ "$DEEP" = "1" ]; then
148
+ _default_scope="$BASE_CHANNELS $DEEP_CHANNELS"
149
+ _default_active="${DEFAULT_LISTS_BASE:+$DEFAULT_LISTS_BASE,}$DEFAULT_LISTS_DEEP"
150
+ fi
151
+ _defaults_disabled=""
152
+ for _c in $(echo "$_default_scope" | tr ' ' '\n'); do
153
+ case ",$_default_active," in
154
+ *,"$_c",*) ;;
155
+ *) _defaults_disabled="$_defaults_disabled,$_c" ;;
156
+ esac
157
+ done
158
+ _defaults_disabled="${_defaults_disabled#,}"
159
+ DEFAULT_DISABLED="$_defaults_disabled"
160
+ fi
161
+
162
+ # CJK 检测:Crossref / OpenAlex 对中文 query 相关性差(c2 实测:中文 query 返回「水质监测站 /
163
+ # 变电站 / 暖通」这类匹配到"配置/安装"字样的噪声)→ 中文 query 时自动跳过 Crossref
164
+ CJK=$(python3 -c 'import sys,re;print("1" if re.search(r"[\u4e00-\u9fff\u3400-\u4dbf]",sys.argv[1]) else "0")' "$Q" 2>/dev/null || echo 0)
165
+ # 英文通道真正吃的是 ENQ:只有拿不到英文版(ENQ 仍含中文)时才跳过只认英文的站
166
+ ENCJK=$(python3 -c 'import sys,re;print("1" if re.search(r"[\u4e00-\u9fff\u3400-\u4dbf]",sys.argv[1]) else "0")' "$ENQ" 2>/dev/null || echo 0)
167
+ # 双语:中英两版检索词不同 → 通用网页通道各查一遍(结果合并时标「中/英」)
168
+ DUAL=0; [ "$ZHQ" != "$ENQ" ] && DUAL=1
169
+ BILINGUAL=" tf serper tavily parallel youcom anysearch fcs brave exa langsearch "
170
+
171
+ TMP="$(mktemp -d)"
172
+ trap 'rm -rf "$TMP"' EXIT
173
+ # 被插件中止时:GNU timeout 默认另起进程组,已统一加 --foreground 留在本组,插件杀整组即可带走
174
+ trap 'kill $(jobs -p) 2>/dev/null; exit 143' TERM INT
175
+ mkdir -p "$TMP/zh" "$TMP/en"
176
+ HEALTH="${D_REACH_HEALTH:-$HOME/.agent-reach/channels.json}"
177
+ HEALTH_BAD=$(python3 - "$HEALTH" <<'PY' 2>/dev/null
178
+ import json, sys
179
+ from datetime import datetime, timezone
180
+ bad = []
181
+ try:
182
+ h = json.load(open(sys.argv[1], encoding="utf-8"))
183
+ except Exception:
184
+ h = {}
185
+ now = datetime.now(timezone.utc)
186
+ for k, v in h.items():
187
+ if not isinstance(v, dict):
188
+ continue
189
+ until = v.get("suspend_until")
190
+ if not until:
191
+ continue # 没有到期时间 = 该放行一次,让 mark 补上退避
192
+ # 挂起现在按「失败性质」写:确定性结论(要登录/限流)首败就挂,
193
+ # 自愈类连败 3 次才挂 —— 所以这里只看有没有未到期的挂起,不再看连败次数。
194
+ try:
195
+ if datetime.fromisoformat(until) > now:
196
+ bad.append(k) # 还在挂起期内
197
+ except Exception:
198
+ continue # 时间戳坏了也放行,别把通道永久判死
199
+ print(" ".join(bad))
200
+ PY
201
+ )
202
+
203
+ # ---------- 记账闸门(两段式)----------
204
+ # gate 只 check 不扣;请求成功后才 charge 真扣(失败由调用方 refund 或干脆不扣)。
205
+ # 返回 0=可跑;1=越免费线/key 缺失(写好 skip 原因)
206
+ gate() {
207
+ svc="$1"
208
+ quota_n="${2:-1}"
209
+ if [ "$svc" = "fcres" ]; then
210
+ # Firecrawl Research Index 论文端点官方免费 → 只验 key,不记账(2026-10-26 定价页核实)
211
+ FC_KEY=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
212
+ return 0
213
+ elif [ "$svc" = "exa" ]; then
214
+ EXA_KEY=$(sh "$DIR/load_key.sh" EXA_API_KEY https://dashboard.exa.ai 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
215
+ elif [ "$svc" = "langsearch" ]; then
216
+ LS_KEY=$(sh "$DIR/load_key.sh" LANGSEARCH_API_KEY https://langsearch.com 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
217
+ elif [ "$svc" = "tinyfish" ]; then
218
+ TF_KEY=$(sh "$DIR/load_key.sh" TINYFISH_API_KEY https://agent.tinyfish.ai/api-keys 2>/dev/null) || { echo "key" > "$TMP/skip.tinyfish"; return 1; }
219
+ return 0 # TinyFish search $0.00/次 → 不走 quota 记账
220
+ elif [ "$svc" = "serper" ]; then
221
+ # Serper = Google 结果,2,500 次一次性赠送(不是每月重置),之后 $1/1000
222
+ # 实测 1.85s 回 5 条,比 BrightData 快 5 倍、便宜得多 → 本地生活/电商首选
223
+ SP_KEY=$(sh "$DIR/load_key.sh" SERPER_API_KEY https://serper.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
224
+ elif [ "$svc" = "firecrawl_search" ]; then
225
+ # Firecrawl v2 Search uses the same key; f_fcs passes an estimated credit cost to this gate.
226
+ FC_KEY=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
227
+ svc="firecrawl"
228
+ elif [ "$svc" = "wiki" ]; then
229
+ return 0 # Wikipedia REST API 完全免费无限量,不验 key 不记账
230
+ fi
231
+ python3 "$QUOTA" check "$svc" "$quota_n" >/dev/null 2>&1; _qrc=$?
232
+ # 0=正常,2=已过裕度线(仍可跑);1=越免费线 → 跳过
233
+ if [ "$_qrc" = "1" ]; then
234
+ echo "quota" > "$TMP/skip.$svc"; return 1
235
+ fi
236
+ return 0
237
+ }
238
+
239
+ # 成功后真扣额度(失败不扣:宁少记不多记)
240
+ charge() {
241
+ python3 "$QUOTA" use "$1" "${2:-1}" >/dev/null 2>&1 || true
242
+ }
243
+ want() {
244
+ local channel="$1"
245
+ if [ "$ON_SET" = "1" ]; then
246
+ case ",$ON," in *",$channel,"*) ;; *) return 1 ;; esac
247
+ fi
248
+ case " $DEEP_CHANNELS " in *" $channel "*) [ "$DEEP" = "1" ] || return 1 ;; esac
249
+ case ",$DEFAULT_DISABLED," in *",$channel,"*) return 1 ;; esac
250
+ return 0
251
+ }
252
+
253
+ # ---------- 免费免 Key 通道 ----------
254
+ f_gh() { # GitHub 仓库搜索(免 key,10 次/分钟)
255
+ # GitHub 只认英文且整句是 AND 匹配:「Home Assistant 3D floorplan dashboard card github」
256
+ # 整句传过去 total_count=0。所以抽 ASCII 词、剔掉 github/the/for 这类噪声、取前 4 个。
257
+ GQ=$(echo "$ENQ" | grep -oE '[A-Za-z0-9][A-Za-z0-9._+-]*' \
258
+ | grep -viE '^(github|repo|repository|the|a|an|of|for|and|to|in|on|with|how|what|best|ui|ux|api|app|web|ai|ml|ios|os)$' \
259
+ | head -4 | tr '\n' ' ')
260
+ # 抽不出英文词不是失败(中文 query 很正常)——写 skip 而不是空结果,
261
+ # 否则每轮都会显示「GitHub:0 命中」并计入「1 路 0 命中」,看着像通道坏了。
262
+ [ -z "$GQ" ] && { echo "no-english" > "$TMP/skip.gh"; return; }
263
+ curl -s --max-time 12 -G "https://api.github.com/search/repositories" \
264
+ -H "Accept: application/vnd.github+json" \
265
+ --data-urlencode "q=$GQ" --data-urlencode "sort=stars" \
266
+ --data-urlencode "order=desc" --data-urlencode "per_page=5" \
267
+ -o "$TMP/gh.json" -w '%{http_code}' > "$TMP/gh.http" 2>/dev/null
268
+ }
269
+
270
+ # 登录态社交通道按平台使用独立冷却;冷却期内跳过,减少连续请求触发风控。
271
+ social_gate() { # $1=平台 $2=冷却秒数;0=放行,1=冷却中(stdout 给剩余分钟)
272
+ python3 - "$HOME/.agent-reach/social-last.json" "$1" "$2" <<'PY'
273
+ import json, os, sys, time
274
+ f, p, cd = sys.argv[1], sys.argv[2], int(sys.argv[3])
275
+ try:
276
+ d = json.load(open(f))
277
+ except Exception:
278
+ d = {}
279
+ left = cd - (time.time() - d.get(p, 0))
280
+ if left > 0:
281
+ print(int(left // 60) + 1)
282
+ sys.exit(1)
283
+ d[p] = int(time.time())
284
+ os.makedirs(os.path.dirname(f), exist_ok=True)
285
+ json.dump(d, open(f, "w"))
286
+ PY
287
+ }
288
+
289
+ run_command_with_timeout() {
290
+ local seconds="$1" output="$2" error="$3"
291
+ shift 3
292
+ python3 -c '
293
+ import subprocess, sys
294
+ seconds, output, error = float(sys.argv[1]), sys.argv[2], sys.argv[3]
295
+ with open(output, "wb") as out, open(error, "wb") as err:
296
+ try:
297
+ result = subprocess.run(sys.argv[4:], stdout=out, stderr=err, timeout=seconds)
298
+ except subprocess.TimeoutExpired:
299
+ sys.exit(124)
300
+ sys.exit(result.returncode)
301
+ ' "$seconds" "$output" "$error" "$@"
302
+ }
303
+
304
+ f_xhs() { # 国内版小红书(需 xhs CLI 登录态;冷却 2 分钟)
305
+ local left rc
306
+ command -v xhs >/dev/null 2>&1 || {
307
+ echo "not-configured" > "$TMP/skip.xhs"
308
+ echo "未安装可选依赖 xhs CLI,国内版 XHS 路线已跳过。" > "$TMP/xhs.txt"
309
+ return 0
310
+ }
311
+ left=$(social_gate xhs 120) || { echo "cooldown:$left" > "$TMP/skip.xhs"; return 0; }
312
+ if timeout --foreground 22 xhs search "$ZHQ" --json > "$TMP/xhs.json" 2> "$TMP/xhs.err"; then
313
+ rc=0
314
+ else
315
+ rc=$?
316
+ fi
317
+ if grep -qi 'verification_required\|captcha' "$TMP/xhs.json" "$TMP/xhs.err" 2>/dev/null; then
318
+ echo captcha > "$TMP/skip.xhs"
319
+ rm -f "$TMP/xhs.json" "$TMP/xhs.err"
320
+ return 0
321
+ fi
322
+ if [ "$rc" != "0" ]; then
323
+ echo err > "$TMP/skip.xhs"
324
+ if [ "$rc" = "124" ]; then
325
+ echo "国内版 XHS 搜索超时(22 秒)。" > "$TMP/xhs.txt"
326
+ else
327
+ echo "国内版 XHS 搜索失败(退出码 $rc)。" > "$TMP/xhs.txt"
328
+ fi
329
+ fi
330
+ [ -s "$TMP/xhs.json" ] || rm -f "$TMP/xhs.json"
331
+ }
332
+
333
+ f_bili() { # B 站视频搜索(需登录态;冷却 90 秒)
334
+ local left
335
+ left=$(social_gate bili 90) || { echo "cooldown:$left" > "$TMP/skip.bili"; return; }
336
+ # B 站搜索是多词 AND:「智能家居 值得买 评测」0 条、「智能家居」3 条。
337
+ # 中文 query 没空格,`set -- $Q` 会切出「研究下」这种动词当首词,搜出来全是
338
+ # 无关视频(实测「研究下 家庭平面图 有什么好方案」→ 捞出「研究下政策力度」)。
339
+ # 所以先把口语前缀剥掉再截断。截断必须按字符不能用 cut -c(那是按字节,
340
+ # 中文会被切出半个字变成乱码)。
341
+ BQ=$(printf '%s' "$ZHQ" | python3 -c "import sys,re; s=re.sub(r'^(研究下|研究一下|研究|看看|看一下|看下|帮我|帮忙|帮忙看|查一下|查下|搜一下|搜下|找一下|找下|请问|想知道|有没有|有什么|什么|怎么|如何|能不能)\\s*','',sys.stdin.read().strip()); print(s[:20] or s)")
342
+ timeout --foreground 22 bilibili video search --keyword "$BQ" --num 6 --json > "$TMP/bili.json" 2>/dev/null \
343
+ || { rm -f "$TMP/bili.json"; return; }
344
+ case "$(python3 -c "import json;print(json.load(open('$TMP/bili.json')).get('result',{}).get('count',0))" 2>/dev/null)" in
345
+ 0) BQ2=$(printf '%s' "$BQ" | python3 -c "import sys; print(sys.stdin.read().strip()[:8])")
346
+ timeout --foreground 15 bilibili video search --keyword "$BQ2" --num 6 --json > "$TMP/bili.json" 2>/dev/null \
347
+ || rm -f "$TMP/bili.json" ;;
348
+ esac
349
+ }
350
+
351
+ f_se() { # StackExchange 排障
352
+ # 中文 query(调用方没给 --en)打 SO 恒 0 命中:q 是全词 AND,中文词组在 SO 上
353
+ # 几乎无索引。实测 8 天里 23 轮中文 query 送去 se,全部 0 命中 → 直接跳过省 15s。
354
+ if [ "$ENCJK" = "1" ]; then
355
+ echo "cjk" > "$TMP/skip.se"
356
+ return 0
357
+ fi
358
+ # q 是全词 AND 匹配:长句/长中文会 0 命中 → 只取前 5 个词
359
+ # shellcheck disable=SC2086
360
+ set -- $ENQ
361
+ SEQ="${1:-} ${2:-} ${3:-} ${4:-} ${5:-}"
362
+ curl -s --compressed --max-time 15 -G "https://api.stackexchange.com/2.3/search/advanced" \
363
+ --data-urlencode "order=desc" --data-urlencode "sort=relevance" \
364
+ --data-urlencode "q=$SEQ" --data-urlencode "site=stackoverflow" \
365
+ --data-urlencode "pagesize=5" -o "$TMP/se.json" -w '%{http_code}' > "$TMP/se.http" 2>/dev/null
366
+ }
367
+ f_hn() { # HN 深技术讨论
368
+ # 同 f_se:HN 只认英文,中文 query 恒 0 命中(实测 8 天 6 次空转)
369
+ if [ "$ENCJK" = "1" ]; then
370
+ echo "cjk" > "$TMP/skip.hn"
371
+ return 0
372
+ fi
373
+ curl -s --max-time 12 -G "https://hn.algolia.com/api/v1/search" \
374
+ --data-urlencode "query=$ENQ" --data-urlencode "hitsPerPage=5" -o "$TMP/hn.json" -w '%{http_code}' > "$TMP/hn.http" 2>/dev/null
375
+ }
376
+ f_jj() { # 掘金 中文技术长尾
377
+ curl -s --max-time 12 -H 'Content-Type: application/json' -X POST \
378
+ "https://api.juejin.cn/search_api/v1/search" \
379
+ -d "$(python3 -c 'import json,sys;print(json.dumps({"key_word":sys.argv[1],"id_type":0,"cursor":"0","limit":5,"search_type":0}))' "$ZHQ")" \
380
+ -o "$TMP/jj.json" -w '%{http_code}' > "$TMP/jj.http" 2>/dev/null
381
+ }
382
+ f_oalex() { # OpenAlex 学术
383
+ curl -s --max-time 12 -G "https://api.openalex.org/works" \
384
+ --data-urlencode "search=$ENQ" --data-urlencode "per-page=5" \
385
+ --data-urlencode 'mailto=d-reach@local' -o "$TMP/oalex.json" -w '%{http_code}' > "$TMP/oalex.http" 2>/dev/null
386
+ }
387
+ f_crossref() { # DOI 权威元数据(⚠️ 中文 query 会跑偏 → CJK 时跳过)
388
+ if [ "$ENCJK" = "1" ]; then
389
+ echo "cjk" > "$TMP/skip.crossref"
390
+ return 0
391
+ fi
392
+ curl -s --max-time 12 -G "https://api.crossref.org/works" \
393
+ --data-urlencode "query=$ENQ" --data-urlencode "rows=5" \
394
+ --data-urlencode 'select=title,DOI,URL,published' -o "$TMP/crossref.json" -w '%{http_code}' > "$TMP/crossref.http" 2>/dev/null
395
+ }
396
+ f_segfault() { # SegmentFault 中文技术长尾(-L 跟跳转;博客园已废弃)
397
+ # 实测同站响应 2.3–11.4s 波动(q=rust 2.8s,q="rust tokio" 11.4s),
398
+ # 14s 上限在并发时会被掐掉,放宽到 20s 让它跑完。
399
+ curl -sL --compressed --max-time 20 -A "$UA" -G "https://segmentfault.com/search" \
400
+ --data-urlencode "q=$ZHQ" -o "$TMP/segfault.html" -w '%{http_code}' > "$TMP/segfault.http" 2>/dev/null
401
+ }
402
+ f_fcdev() { # Firecrawl Developer Index(70M+ 一手源)
403
+ # 有 key 走 key:keyless 是 IP 级免费额度,耗尽后 429 要等十几小时(实测 retry_after 40699s)
404
+ # 没 key 才落 keyless 免费档,仍能跑但随时可能被限
405
+ _fck=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || _fck=""
406
+ if [ -n "$_fck" ]; then
407
+ curl -s --max-time 18 -G "https://api.firecrawl.dev/v2/search/developer" -H "Authorization: Bearer $_fck" \
408
+ --data-urlencode "query=$ENQ" --data-urlencode "k=5" -o "$TMP/fcdev.json" -w '%{http_code}' > "$TMP/fcdev.http" 2>/dev/null
409
+ [ "$(cat "$TMP/fcdev.http" 2>/dev/null)" = "200" ] && charge firecrawl
410
+ else
411
+ curl -s --max-time 18 -G "https://api.firecrawl.dev/v2/search/developer" \
412
+ --data-urlencode "query=$ENQ" --data-urlencode "k=5" -o "$TMP/fcdev.json" -w '%{http_code}' > "$TMP/fcdev.http" 2>/dev/null
413
+ fi
414
+ }
415
+ f_qianfan() { # 百度千帆:生成式综合答案(非来源链接!)
416
+ [ -f "$BAIDU/smart_search.py" ] || { echo "not-configured" > "$TMP/skip.qianfan"; echo "千帆配套技能未安装;本轮按未配置跳过,不计为渠道故障。" > "$TMP/qianfan.txt"; return 0; }
417
+ run_command_with_timeout 50 "$TMP/qianfan.raw" "$TMP/qianfan.err" \
418
+ python3 "$BAIDU/smart_search.py" search "$ZHQ"
419
+ _qrc=$?
420
+ sed -e '/^--- 配额状态 ---/,$d' -e '/^\[调度\]/d' "$TMP/qianfan.raw" > "$TMP/qianfan.txt" 2>/dev/null
421
+ # 千帆报错时绝不能把错误文本当「AI 答案」渲染:报错、空输出、或 stderr 有内容 → 标 err
422
+ if [ "$_qrc" != "0" ] || [ ! -s "$TMP/qianfan.txt" ] || [ -s "$TMP/qianfan.err" ]; then
423
+ echo "err" > "$TMP/skip.qianfan"
424
+ head -c 300 "$TMP/qianfan.err" >> "$TMP/qianfan.txt" 2>/dev/null
425
+ fi
426
+ # 免费额度降到 ≤20% 时 smart_search.py 会自动切备用 API,此时它吐的是裸 JSON
427
+ # ([⚠️ 自动跳过] ... 加一个 JSON 数组)。直接渲染就是把 JSON 当答案塞给用户。
428
+ # 识别出来转成正常条目,并标明这是降档结果而不是 AI 摘要。
429
+ if grep -qE '^\[\s*$' "$TMP/qianfan.txt" 2>/dev/null; then
430
+ python3 - "$TMP/qianfan.txt" > "$TMP/qianfan.md" <<'PYQ'
431
+ import json, re, sys
432
+ raw = open(sys.argv[1], encoding="utf-8", errors="replace").read()
433
+ m = re.search(r"\[\s*\{.*\}\s*\]", raw, re.S)
434
+ rows = []
435
+ if m:
436
+ try:
437
+ rows = json.loads(m.group(0))
438
+ except Exception:
439
+ rows = []
440
+ if not rows:
441
+ print(raw.strip()[:600])
442
+ else:
443
+ out = []
444
+ for r in rows[:8]:
445
+ t = (r.get("title") or "").strip()
446
+ u = (r.get("url") or "").strip()
447
+ d = (r.get("date") or "").strip()[:10]
448
+ if not t:
449
+ continue
450
+ meta = " · ".join(x for x in (d, "百度降档结果") if x)
451
+ out.append(f"- [{t}]({u}) — {meta}" if u else f"- {t} — {meta}")
452
+ print("\n".join(out))
453
+ PYQ
454
+ mv "$TMP/qianfan.md" "$TMP/qianfan.txt"
455
+ fi
456
+ }
457
+
458
+ f_tf() { # TinyFish Search(官方 hosted MCP,$0/次;JSON-RPC tools/call search)
459
+ gate tinyfish || return 0
460
+ TF_KEY="$TF_KEY" python3 - "$ENQ" > "$TMP/tf.json" 2>"$TMP/tf.err" <<'PYEOF'
461
+ import json, os, sys, urllib.request
462
+
463
+ q = sys.argv[1]
464
+ key = os.environ["TF_KEY"]
465
+ URL = "https://agent.tinyfish.ai/mcp"
466
+
467
+ def rpc(payload, session=None):
468
+ h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
469
+ "X-API-Key": key}
470
+ if session:
471
+ h["Mcp-Session-Id"] = session
472
+ req = urllib.request.Request(URL, data=json.dumps(payload).encode(), headers=h)
473
+ with urllib.request.urlopen(req, timeout=30) as r:
474
+ # hosted 强制:initialize 响应头下发 mcp-session-id,后续请求必须回带
475
+ return r.headers.get("mcp-session-id"), r.read().decode("utf-8", "replace")
476
+
477
+ sid, _ = rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize",
478
+ "params": {"protocolVersion": "2025-03-26", "capabilities": {},
479
+ "clientInfo": {"name": "d-reach-fanout", "version": "1.0"}}})
480
+ rpc({"jsonrpc": "2.0", "method": "notifications/initialized"}, sid)
481
+ sys.stdout.write(rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
482
+ "params": {"name": "search",
483
+ "arguments": {"query": q,
484
+ "purpose": "d-reach parallel multi-channel web fanout"}}}, sid)[1])
485
+ PYEOF
486
+ }
487
+
488
+ # ---------- deep 追加通道 ----------
489
+ f_langsearch() {
490
+ gate langsearch || return 0
491
+ curl -s --max-time 30 -X POST "https://api.langsearch.com/v1/web-search" \
492
+ -H "Authorization: Bearer $LS_KEY" -H 'Content-Type: application/json' \
493
+ -d "$(python3 -c 'import json,os,sys;b={"query":sys.argv[1],"count":20};f={"day":"oneDay","week":"oneWeek","month":"oneMonth","year":"oneYear"}.get(os.environ.get("D_REACH_RECENCY",""));b.update({"freshness":f} if f else {});print(json.dumps(b))' "$ENQ")" \
494
+ -o "$TMP/langsearch.json" -w '%{http_code}' > "$TMP/langsearch.http" 2>/dev/null
495
+ [ "$(cat "$TMP/langsearch.http" 2>/dev/null)" = "200" ] && charge langsearch
496
+ }
497
+ f_exa() {
498
+ gate exa || return 0
499
+ curl -s --max-time 20 -X POST "https://api.exa.ai/search" \
500
+ -H "x-api-key: $EXA_KEY" -H 'Content-Type: application/json' \
501
+ -d "$(python3 -c 'import json,os,sys
502
+ from datetime import datetime,timedelta,timezone
503
+ b={"query":sys.argv[1],"numResults":10}
504
+ days={"day":1,"week":7,"month":30,"year":365}.get(os.environ.get("D_REACH_RECENCY",""))
505
+ if days: b["startPublishedDate"]=(datetime.now(timezone.utc)-timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
506
+ inc=json.loads(os.environ.get("D_REACH_INC_JSON") or "[]"); exc=json.loads(os.environ.get("D_REACH_EXC_JSON") or "[]")
507
+ if inc: b["includeDomains"]=inc
508
+ if exc: b["excludeDomains"]=exc
509
+ print(json.dumps(b))' "$ENQ")" \
510
+ -o "$TMP/exa.json" -w '%{http_code}' > "$TMP/exa.http" 2>/dev/null
511
+ [ "$(cat "$TMP/exa.http" 2>/dev/null)" = "200" ] && charge exa
512
+ }
513
+ f_fcres() {
514
+ gate fcres || return 0
515
+ curl -s --max-time 20 -H "Authorization: Bearer $FC_KEY" -G \
516
+ "https://api.firecrawl.dev/v2/search/research/papers" \
517
+ --data-urlencode "query=$ENQ" --data-urlencode "k=5" \
518
+ -o "$TMP/fcres.json" -w '%{http_code}' > "$TMP/fcres.http" 2>/dev/null
519
+ }
520
+ f_serper() {
521
+ gate serper || return 0
522
+ curl -s --max-time 20 -X POST "https://google.serper.dev/search" \
523
+ -H "X-API-KEY: $SP_KEY" -H 'Content-Type: application/json' \
524
+ -d "$(python3 -c 'import json,os,sys,re;q=sys.argv[1];b={"q":q,"num":10,"gl":"cn" if re.search(r"[\u4e00-\u9fff]",q) else "us","hl":"zh-cn" if re.search(r"[\u4e00-\u9fff]",q) else "en"};t=os.environ.get("D_REACH_TBS","");b.update({"tbs":t} if t else {});print(json.dumps(b))' "$Q")" \
525
+ -o "$TMP/serper.json" -w '%{http_code}' > "$TMP/serper.http" 2>/dev/null
526
+ [ "$(cat "$TMP/serper.http" 2>/dev/null)" = "200" ] && charge serper
527
+ }
528
+ f_tavily() { # Tavily keyless:无账号无 key,结果带 1400 字级正文摘录
529
+ # 免费档按 IP 限速(官方称约 30 次/IP 后 429 hourly_cap_reached),不记账。
530
+ # 与 serper 的区别:serper 只给标题+两行 snippet,它给整段正文,中文 query 实测 5/5 命中。
531
+ curl -s --max-time 20 -X POST "https://api.tavily.com/search" \
532
+ -H 'Content-Type: application/json' -H 'X-Tavily-Access-Mode: keyless' \
533
+ -d "$(python3 -c 'import json,os,sys
534
+ b={"query":sys.argv[1],"max_results":8}
535
+ tr=os.environ.get("D_REACH_RECENCY","")
536
+ if tr in ("day","week","month","year"): b["time_range"]=tr
537
+ inc=json.loads(os.environ.get("D_REACH_INC_JSON") or "[]"); exc=json.loads(os.environ.get("D_REACH_EXC_JSON") or "[]")
538
+ if inc: b["include_domains"]=inc
539
+ if exc: b["exclude_domains"]=exc
540
+ print(json.dumps(b))' "$ENQ")" \
541
+ -o "$TMP/tavily.json" -w '%{http_code}' > "$TMP/tavily.http" 2>/dev/null
542
+ }
543
+ f_parallel() { # Parallel 免费 MCP(web_search):无 key 无账号,结果带 excerpts + 发布日期
544
+ # 握手 3 步、每步 40s 上限,卡住时会把整轮拖到 2 分钟(2026-12-04 实测 126s)→ 外层统一 25s 封顶
545
+ # 走 MCP 握手(initialize → notifications/initialized → tools/call),交给 mcp_call.py。
546
+ timeout --foreground 25 python3 "$DIR/mcp_call.py" https://mcp.parallel.ai/mcp web_search \
547
+ "$(python3 -c 'import json,sys;q=sys.argv[1];print(json.dumps({"objective":q,"search_queries":[q]}))' "$ENQ")" \
548
+ > "$TMP/parallel.json" 2>/dev/null
549
+ # 失败时脚本打 MCP_ERROR 行(不是 JSON),标 skip 而不是让解析器报「无响应」
550
+ if [ "$(head -c 11 "$TMP/parallel.json" 2>/dev/null)" = "MCP_ERROR: " ]; then
551
+ head -c 300 "$TMP/parallel.json" > "$TMP/skip.parallel"
552
+ : > "$TMP/parallel.json"
553
+ fi
554
+ }
555
+ f_youcom() { # You.com 官方 Search API(X-API-Key),免费档 100 次/天
556
+ # 2026-12-04 改:免 Key MCP(?profile=free)实测握手每次都要 40 秒以上、英文查询 100% 超时,
557
+ # 官方 REST 端点 2 秒就回,所以换成带 key 的 REST。没配 key 时退回旧的 MCP 档。
558
+ _yck=$(sh "$DIR/load_key.sh" YOU_API_KEY https://you.com/platform 2>/dev/null) || _yck=""
559
+ if [ -n "$_yck" ]; then
560
+ curl -s --max-time 15 -G "https://api.you.com/v1/search" -H "X-API-Key: $_yck" \
561
+ --data-urlencode "query=$ENQ" --data-urlencode "count=6" \
562
+ -o "$TMP/youcom.json" -w '%{http_code}' > "$TMP/youcom.http" 2>/dev/null
563
+ [ "$(cat "$TMP/youcom.http" 2>/dev/null)" = "200" ] && charge youcom
564
+ return
565
+ fi
566
+ # 免 Key MCP 兜底:网关会 403 掉 Python-urllib 默认 UA,mcp_call.py 里已固定 d-reach/1.0。
567
+ timeout --foreground 25 python3 "$DIR/mcp_call.py" "https://api.you.com/mcp?profile=free" you-search \
568
+ "$(python3 -c 'import json,sys;print(json.dumps({"query":sys.argv[1],"count":6}))' "$ENQ")" \
569
+ > "$TMP/youcom.json" 2>/dev/null
570
+ if [ "$(head -c 11 "$TMP/youcom.json" 2>/dev/null)" = "MCP_ERROR: " ]; then
571
+ head -c 300 "$TMP/youcom.json" > "$TMP/skip.youcom"
572
+ : > "$TMP/youcom.json"
573
+ fi
574
+ }
575
+ f_anysearch() { # AnySearch:1000 次/天免费,20+ 垂直领域(法律/医疗/金融专库)
576
+ # 带 key 与匿名共享同一个 daily free quota,但带 key 不按 IP 算 —— 共享出口 IP 更稳。
577
+ # zone 按 query 语言自动切 cn / intl。
578
+ _ask=$(sh "$DIR/load_key.sh" ANYSEARCH_API_KEY https://anysearch.com 2>/dev/null) || _ask=""
579
+ _abody=$(python3 -c 'import json,re,sys
580
+ q=sys.argv[1]
581
+ z="cn" if re.search(r"[\u4e00-\u9fff]", q) else "intl"
582
+ print(json.dumps({"query":q,"max_results":6,"zone":z}))' "$Q")
583
+ if [ -n "$_ask" ]; then
584
+ curl -s --max-time 22 -X POST "https://api.anysearch.com/v1/search" \
585
+ -H "Authorization: Bearer $_ask" -H 'Content-Type: application/json' \
586
+ -d "$_abody" -o "$TMP/anysearch.json" -w '%{http_code}' > "$TMP/anysearch.http" 2>/dev/null
587
+ else
588
+ curl -s --max-time 22 -X POST "https://api.anysearch.com/v1/search" \
589
+ -H 'Content-Type: application/json' \
590
+ -d "$_abody" -o "$TMP/anysearch.json" -w '%{http_code}' > "$TMP/anysearch.http" 2>/dev/null
591
+ fi
592
+ }
593
+ f_zhihu() { # 知乎开放平台站内搜索:需 ZHIHU_SEARCH_API_KEY(官方 API,非爬虫)
594
+ # 返回标题/摘要/赞同数/评论数;免费额度按开放平台控制台发放规则。
595
+ _zk=$(sh "$DIR/load_key.sh" ZHIHU_SEARCH_API_KEY https://developer.zhihu.com 2>/dev/null) || { echo "key" > "$TMP/skip.zhihu"; return 1; }
596
+ curl -s --max-time 20 -G 'https://developer.zhihu.com/api/v1/content/zhihu_search' \
597
+ --data-urlencode "Query=$ZHQ" -d "Count=8" \
598
+ -H "Authorization: Bearer $_zk" \
599
+ -H "X-Request-Timestamp: $(date +%s)" \
600
+ -o "$TMP/zhihu.json" -w '%{http_code}' > "$TMP/zhihu.http" 2>/dev/null
601
+ }
602
+ f_zhihuall() { # 知乎开放平台全网搜索:5000 次/日限免,中文全网(权威分级),需 ZHIHU_SEARCH_API_KEY
603
+ _zk=$(sh "$DIR/load_key.sh" ZHIHU_SEARCH_API_KEY https://developer.zhihu.com 2>/dev/null) || { echo "key" > "$TMP/skip.zhihuall"; return 1; }
604
+ curl -s --max-time 20 -G 'https://developer.zhihu.com/api/v1/content/global_search' \
605
+ --data-urlencode "Query=$ZHQ" -d 'Count=8' \
606
+ -H "Authorization: Bearer $_zk" \
607
+ -H "X-Request-Timestamp: $(date +%s)" \
608
+ -o "$TMP/zhihuall.json" -w '%{http_code}' > "$TMP/zhihuall.http" 2>/dev/null
609
+ }
610
+ f_zhihuhot() { # 知乎热榜:全站热点,与查询词无关(100 次/日限免),deep 档或 --on 时跑
611
+ _zk=$(sh "$DIR/load_key.sh" ZHIHU_SEARCH_API_KEY https://developer.zhihu.com 2>/dev/null) || { echo "key" > "$TMP/skip.zhihuhot"; return 1; }
612
+ curl -s --max-time 15 -G 'https://developer.zhihu.com/api/v1/content/hot_list' \
613
+ -d 'Limit=15' \
614
+ -H "Authorization: Bearer $_zk" \
615
+ -H "X-Request-Timestamp: $(date +%s)" \
616
+ -o "$TMP/zhihuhot.json" -w '%{http_code}' > "$TMP/zhihuhot.http" 2>/dev/null
617
+ }
618
+ f_zhida() { # 知乎直答(OpenAI 兼容 /v1/chat/completions):AI 摘要,非来源(100 次/日)
619
+ _zk=$(sh "$DIR/load_key.sh" ZHIHU_SEARCH_API_KEY https://developer.zhihu.com 2>/dev/null) || { echo "key" > "$TMP/skip.zhida"; return 1; }
620
+ _zbody=$(python3 -c 'import json,sys;print(json.dumps({"model":"zhida-fast-1p5","messages":[{"role":"user","content":sys.argv[1]}],"stream":False}))' "$ZHQ")
621
+ curl -s --max-time 45 -X POST 'https://developer.zhihu.com/v1/chat/completions' \
622
+ -H "Authorization: Bearer $_zk" \
623
+ -H "X-Request-Timestamp: $(date +%s)" \
624
+ -H 'Content-Type: application/json' -d "$_zbody" \
625
+ -o "$TMP/zhida.json" -w '%{http_code}' > "$TMP/zhida.http" 2>/dev/null
626
+ }
627
+ f_brave() { # Brave Search API:自有索引(不经 Google/Bing),每月 $5 免费 credits ≈ 1000 次
628
+ gate brave || return 0
629
+ _bk=$(sh "$DIR/load_key.sh" BRAVE_API_KEY https://api-dashboard.search.brave.com/app/keys 2>/dev/null) || { echo "key" > "$TMP/skip.brave"; return 1; }
630
+ local _bfresh=()
631
+ case "$RECENCY" in
632
+ day) _bfresh=(-d "freshness=pd") ;; week) _bfresh=(-d "freshness=pw") ;;
633
+ month) _bfresh=(-d "freshness=pm") ;; year) _bfresh=(-d "freshness=py") ;;
634
+ esac
635
+ curl -s --max-time 20 -G 'https://api.search.brave.com/res/v1/web/search' \
636
+ --data-urlencode "q=$Q" -d 'count=8' -d 'safesearch=moderate' ${_bfresh[@]+"${_bfresh[@]}"} \
637
+ -H "X-Subscription-Token: $_bk" -H 'Accept: application/json' \
638
+ -o "$TMP/brave.json" -w '%{http_code}' > "$TMP/brave.http" 2>/dev/null
639
+ [ "$(cat "$TMP/brave.http" 2>/dev/null)" = "200" ] && charge brave
640
+ }
641
+ f_fcs() { # Firecrawl v2 Search:全站搜索,结果质量高(GitHub issue/官方文档/论文都能中)
642
+ local fcs_limit=8 fcs_estimate actual_credits curl_rc=0
643
+ [ "$N_SET" = "1" ] && fcs_limit="$N"
644
+ [ "$fcs_limit" -lt 1 ] && fcs_limit=1
645
+ [ "$fcs_limit" -gt 100 ] && fcs_limit=100
646
+ # Search costs 2 credits per 10 requested results (rounded up); charge actual creditsUsed below.
647
+ fcs_estimate=$((2 * ((fcs_limit + 9) / 10)))
648
+ gate firecrawl_search "$fcs_estimate" || return 0
649
+ curl -sS --max-time 25 -X POST "https://api.firecrawl.dev/v2/search" \
650
+ -H "Authorization: Bearer $FC_KEY" -H 'Content-Type: application/json' \
651
+ -d "$(python3 -c 'import json,sys;print(json.dumps({"query":sys.argv[1],"limit":int(sys.argv[2])}))' "$ENQ" "$fcs_limit")" \
652
+ -o "$TMP/fcs.json" -w '%{http_code}' > "$TMP/fcs.http" 2> "$TMP/fcs.err" || curl_rc=$?
653
+ printf '%s' "$curl_rc" > "$TMP/fcs.rc"
654
+ if [ "$(cat "$TMP/fcs.http" 2>/dev/null)" = "200" ]; then
655
+ actual_credits=$(python3 - "$TMP/fcs.json" "$fcs_estimate" <<'PY'
656
+ import json, sys
657
+ credits = int(sys.argv[2])
658
+ try:
659
+ response = json.load(open(sys.argv[1], encoding="utf-8"))
660
+ value = response.get("creditsUsed") if isinstance(response, dict) else None
661
+ if type(value) is int and value > 0:
662
+ credits = value
663
+ except Exception:
664
+ pass
665
+ print(credits)
666
+ PY
667
+ )
668
+ charge firecrawl "$actual_credits"
669
+ fi
670
+ }
671
+ f_wiki() { # Wikipedia REST summary:概念/人物/术语/地名,0.7s、完全免费、无限量
672
+ gate wiki || return 0
673
+ # 「紫砂壶是什么」这种疑问句直接搜 opensearch 会返回空数组(没有条目叫这个名字),
674
+ # 要先剥掉疑问词再搜,否则回退成整个 query 去取 summary 必然 404
675
+ STRIP='import re,sys
676
+ q=sys.argv[1]
677
+ q=re.sub(r"(是什么|是谁|什么是|的定义是什么|的定义|的原理是什么|的原理|的历史|的由来|怎么用|如何使用|有什么用|介绍一下|是什么意思)[??。,,]*$","",q.strip())
678
+ q=re.sub(r"^(什么是|介绍一下|讲讲)", "", q)
679
+ print(q.strip() or sys.argv[1])'
680
+ BASEQ=$(python3 -c "$STRIP" "$ZHQ" 2>/dev/null || echo "$ZHQ")
681
+ os_search() {
682
+ curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
683
+ "https://zh.wikipedia.org/w/api.php" \
684
+ --data-urlencode "action=opensearch" --data-urlencode "search=$1" \
685
+ --data-urlencode "limit=1" --data-urlencode "format=json" \
686
+ | python3 -c 'import json,sys
687
+ try:
688
+ d=json.load(sys.stdin); print(d[1][0] if d[1] else "")
689
+ except Exception: print("")' 2>/dev/null
690
+ }
691
+ # 多词 query(「杭州 西湖 门票」)opensearch 常返空;再用 list=search 兜底取首条标题。
692
+ # 两轮都空说明维基确实没有对应条目 —— 此时记 0 命中,不能留 404(会被误判成通道故障)。
693
+ ls_search() {
694
+ curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
695
+ "https://zh.wikipedia.org/w/api.php" \
696
+ --data-urlencode "action=query" --data-urlencode "list=search" \
697
+ --data-urlencode "srsearch=$1" --data-urlencode "srlimit=1" \
698
+ --data-urlencode "format=json" \
699
+ | python3 -c 'import json,sys
700
+ try:
701
+ d=json.load(sys.stdin); s=(d.get("query") or {}).get("search") or []; print(s[0]["title"] if s else "")
702
+ except Exception: print("")' 2>/dev/null
703
+ }
704
+ TITLE=$(os_search "$ZHQ")
705
+ [ -z "$TITLE" ] && TITLE=$(os_search "$BASEQ")
706
+ [ -z "$TITLE" ] && TITLE=$(ls_search "$BASEQ")
707
+ [ -z "$TITLE" ] && TITLE=$(ls_search "$ZHQ")
708
+ if [ -z "$TITLE" ]; then
709
+ printf '{"type":"none"}' > "$TMP/wiki.json"
710
+ printf '200' > "$TMP/wiki.http"
711
+ return 0
712
+ fi
713
+ # REST summary 端点自己会跟随繁简重定向(/w/api.php?redirects=1 对中文维基的繁简重定向不生效,
714
+ # 「紫砂壶」会拿到「簡繁重定向」那段说明文字而不是正文)
715
+ ENC=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote(sys.argv[1].replace(" ","_")))' "$TITLE" 2>/dev/null)
716
+ curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" "https://zh.wikipedia.org/api/rest_v1/page/summary/$ENC" \
717
+ -o "$TMP/wiki.json" -w '%{http_code}' > "$TMP/wiki.http" 2>/dev/null
718
+
719
+ # 中文条目常常只有一句话(实测「小米手环」64 字符、「RAG」174 字符,
720
+ # 而英文同条目 689 字符)。内容太短就用英文 query 再查一遍英文维基,取长的那个。
721
+ ZH_LEN=$(python3 -c 'import json,sys
722
+ try: print(len(json.load(open(sys.argv[1])).get("extract") or ""))
723
+ except Exception: print(0)' "$TMP/wiki.json" 2>/dev/null || echo 0)
724
+ if [ "${ZH_LEN:-0}" -lt 300 ] && [ -n "$ENQ" ] && [ "$ENQ" != "$ZHQ" ]; then
725
+ EN_TITLE=$(curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
726
+ "https://en.wikipedia.org/w/api.php" \
727
+ --data-urlencode "action=query" --data-urlencode "list=search" \
728
+ --data-urlencode "srsearch=$ENQ" --data-urlencode "srlimit=1" \
729
+ --data-urlencode "format=json" \
730
+ | python3 -c 'import json,sys
731
+ try:
732
+ d=json.load(sys.stdin); s=(d.get("query") or {}).get("search") or []; print(s[0]["title"] if s else "")
733
+ except Exception: print("")' 2>/dev/null)
734
+ if [ -n "$EN_TITLE" ]; then
735
+ EN_ENC=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote(sys.argv[1].replace(" ","_")))' "$EN_TITLE" 2>/dev/null)
736
+ curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" \
737
+ "https://en.wikipedia.org/api/rest_v1/page/summary/$EN_ENC" -o "$TMP/wiki_en.json" 2>/dev/null
738
+ python3 - "$TMP/wiki.json" "$TMP/wiki_en.json" <<'PYPICK'
739
+ import json, sys
740
+ zh_f, en_f = sys.argv[1], sys.argv[2]
741
+ def load(f):
742
+ try: return json.load(open(f))
743
+ except Exception: return {}
744
+ zh, en = load(zh_f), load(en_f)
745
+ if len(en.get("extract") or "") > len(zh.get("extract") or ""):
746
+ json.dump(en, open(zh_f, "w"))
747
+ print("en", file=sys.stderr)
748
+ else:
749
+ print("zh", file=sys.stderr)
750
+ PYPICK
751
+ fi
752
+ fi
753
+ }
754
+ # 已退役通道(2026-09-25 实测,别往回加):
755
+ # · V2EX /search?q= —— 302 → /go/search,返回「搜索引擎技术研究」节点帖子,与 query 无关
756
+ # (会给假结果;假结果比无响应更毒,故整路移除)
757
+ # · 博客园 zzk.cnblogs.com —— 302→zzkx 后返回 5.7KB 壳页、0 结果
758
+ # 中文社区长尾现在靠 掘金 + SegmentFault + 知乎开放平台 API;cn.bing 已投毒。
759
+
760
+ # ---------- 并发发射 ----------
761
+ launch() { # $1 = 函数名;失败不拖垮整体
762
+ fn="$1"; key="${fn#f_}"
763
+ want "$key" || return 0
764
+ if [ "$key" = "qianfan" ] && [ ! -f "$BAIDU/smart_search.py" ]; then
765
+ echo "not-configured" > "$TMP/skip.qianfan"
766
+ echo "千帆配套技能未安装;本轮按未配置跳过,不计为渠道故障。" > "$TMP/qianfan.txt"
767
+ return 0
768
+ fi
769
+ if [ "$key" = "bili" ] && ! command -v bilibili >/dev/null 2>&1; then
770
+ echo "not-configured" > "$TMP/skip.bili"
771
+ echo "bilibili CLI 未安装;本轮按未配置跳过,不计为渠道故障。" > "$TMP/bili.txt"
772
+ return 0
773
+ fi
774
+ # 健康状态:连续失败 ≥3 次的路默认不再发请求(除非 --force 或 --on 显式点名)
775
+ if [ "$FORCE" != "1" ] && [ -z "$ON" ]; then
776
+ case " $HEALTH_BAD " in
777
+ *" $key "*) echo "health" > "$TMP/skip.$key"; return 0 ;;
778
+ esac
779
+ fi
780
+ case "$BILINGUAL" in
781
+ *" $key "*)
782
+ if [ "$DUAL" = "1" ]; then
783
+ # 通用网页通道:中文版、英文版各打一次,各写各的子目录,渲染时合并
784
+ ( TMP="$TMP/zh"; Q="$ZHQ"; ENQ="$ZHQ"; "$fn" ) &
785
+ ( TMP="$TMP/en"; Q="$ENQ"; "$fn" ) &
786
+ return 0
787
+ fi ;;
788
+ esac
789
+ ( "$fn" ) &
790
+ }
791
+ for fn in f_se f_hn f_jj f_zhihu f_zhihuall f_zhihuhot f_zhida f_oalex f_crossref f_segfault f_fcdev f_gh f_qianfan f_tf f_serper f_fcs f_wiki f_tavily f_parallel f_youcom f_anysearch f_brave f_xhs f_bili; do launch "$fn"; done
792
+ # --on 显式点名时也要跑 deep 档通道,否则 deep 通道的结果会丢掉
793
+ if [ "$DEEP" = 1 ] || [ -n "$ON" ]; then
794
+ for fn in f_langsearch f_exa f_fcres; do launch "$fn"; done
795
+ fi
796
+ wait
797
+
798
+ # ---------- 渲染 ----------
799
+ # 本轮起始时间:给 history.jsonl 算耗时用(调用方已给就沿用,比如插件那边能算得更准)
800
+ [ -n "${D_REACH_T0:-}" ] || D_REACH_T0=$(date +%s)
801
+ export D_REACH_T0
802
+ # 脚本指纹:通道的「这路坏了/要登录」结论绑定它。改了脚本旧结论自动作废,
803
+ # 不用手删 channels.json(照 Agent-Reach 的 fingerprint 失效机制)。
804
+ D_REACH_FP=$(cat "$DIR/fanout.sh" "$DIR/route_config.py" | md5sum 2>/dev/null | cut -c1-8)
805
+ export D_REACH_FP
806
+
807
+ D_REACH_ZHQ="$ZHQ" D_REACH_ENQ="$ENQ" D_REACH_DUAL="$DUAL" D_REACH_BILINGUAL="$BILINGUAL" \
808
+ python3 - "$TMP" "$Q" "$N" "$DEEP" "$ON" "$DEFAULT_DISABLED" <<'PY'
809
+ import contextlib, fcntl, json, os, re, sys, html, pathlib, time
810
+ from datetime import datetime, timezone, timedelta
811
+ from urllib.parse import urlsplit
812
+
813
+ # 收集本轮全部输出,历史详情(网关点一条看全文)要用 —— 覆盖 print 而不是到处插 buf.append
814
+ _REAL_PRINT = print
815
+ _OUT = []
816
+ def print(*a, **k):
817
+ import io as _io
818
+ _b = _io.StringIO()
819
+ k2 = dict(k); k2["file"] = _b
820
+ _REAL_PRINT(*a, **k2)
821
+ _OUT.append(_b.getvalue())
822
+ if k.get("file") is sys.stdout or "file" not in k:
823
+ _REAL_PRINT(*a)
824
+
825
+ tmp, Q, N, DEEP, ON, DEFAULT_DISABLED = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], sys.argv[5], sys.argv[6]
826
+ N = max(1, min(N, 20))
827
+ ONLY = {c for c in ON.split(",") if c} if ON else None # None = 按默认启用清单
828
+ DISABLED = {c for c in DEFAULT_DISABLED.split(",") if c}
829
+
830
+ def load_text(name):
831
+ p = os.path.join(tmp, name)
832
+ if not os.path.exists(p) or os.path.getsize(p) == 0:
833
+ return None
834
+ raw = pathlib.Path(p).read_bytes()
835
+ if not raw.strip():
836
+ return None
837
+ for enc in ("utf-8", "gb18030"):
838
+ try:
839
+ return raw.decode(enc)
840
+ except Exception:
841
+ pass
842
+ return raw.decode("utf-8", "replace")
843
+
844
+ def load_json(name):
845
+ t = load_text(name)
846
+ if t is None:
847
+ return None
848
+ try:
849
+ return json.loads(t)
850
+ except Exception:
851
+ return None
852
+
853
+ def clean(s):
854
+ out = str(s if s is not None else "")
855
+ out = re.sub(r"<[^>]+>", " ", out)
856
+ for _ in range(3): # Crossref 有双重转义记录(&amp;amp;),解到底
857
+ new = html.unescape(out)
858
+ if new == out:
859
+ break
860
+ out = new
861
+ return re.sub(r"\s+", " ", out).strip()
862
+
863
+ def trunc(s, n=110):
864
+ s = clean(s)
865
+ return s[:n] + ("…" if len(s) > n else "")
866
+
867
+ # ---------- 网站过滤(本地兜底)----------
868
+ # 原生支持 include/exclude domains 的通道(Tavily/Exa)已在请求里传了;其余通道在这里按
869
+ # URL 主机名过滤。无前缀=只要这些站,`-` 前缀=排除且优先;子域算命中(a.com 命中 www.a.com)。
870
+ # recency 本地无法判断发布日期的结果不做二次过滤(保留,避免误杀)。
871
+ DOMAIN_DROPPED = 0
872
+ def _dom_tags(raw):
873
+ try:
874
+ return {str(x).lower().strip(".") for x in json.loads(raw or "[]") if str(x).strip()}
875
+ except Exception:
876
+ return set()
877
+ _DOM_INC = _dom_tags(os.environ.get("D_REACH_INC_JSON"))
878
+ _DOM_EXC = _dom_tags(os.environ.get("D_REACH_EXC_JSON"))
879
+
880
+ def _host_match(host, d):
881
+ return bool(host) and (host == d or host.endswith("." + d))
882
+
883
+ def _domain_ok(u):
884
+ global DOMAIN_DROPPED
885
+ if not _DOM_INC and not _DOM_EXC:
886
+ return True
887
+ try:
888
+ host = (urlsplit(u).hostname or "").lower().rstrip(".")
889
+ except Exception:
890
+ host = ""
891
+ keep = (not _DOM_INC or any(_host_match(host, d) for d in _DOM_INC)) \
892
+ and not any(_host_match(host, d) for d in _DOM_EXC)
893
+ if not keep:
894
+ DOMAIN_DROPPED += 1
895
+ return keep
896
+
897
+ def rowify(pairs):
898
+ """去重 + 截断;URL 必须是 http(s) 才算来源。"""
899
+ out, seen = [], set()
900
+ for t, u, x in pairs:
901
+ t, u, x = clean(t), str(u or "").strip(), clean(x)
902
+ if not t or not u.startswith("http") or u in seen:
903
+ continue
904
+ if not _domain_ok(u):
905
+ continue
906
+ seen.add(u)
907
+ out.append((t[:170], u, x[:120]))
908
+ if len(out) >= N:
909
+ break
910
+ return out
911
+
912
+ def walk_generic(d):
913
+ """兜底:递归抓 {title/name, url/link} 对(结构未知的通道用它)。"""
914
+ out = []
915
+ def walk(o):
916
+ if isinstance(o, dict):
917
+ u = o.get("url") or o.get("link") or o.get("html_url") or o.get("landing_page_url")
918
+ t = o.get("title") or o.get("name")
919
+ if isinstance(u, str) and u.startswith("http") and t:
920
+ out.append((t, u, trunc(o.get("snippet") or o.get("description")
921
+ or o.get("summary") or o.get("text"), 100)))
922
+ for v in o.values():
923
+ walk(v)
924
+ elif isinstance(o, list):
925
+ for v in o:
926
+ walk(v)
927
+ walk(d)
928
+ return out
929
+
930
+ # ---------- 每路专用解析(字段名各通道不同,别合并) ----------
931
+ def _query_tokens(q):
932
+ """把 query 切成可比对的 token:西文 ≥4 字母词 + 中文二字片段。"""
933
+ q = clean(q).lower()
934
+ toks = set(re.findall(r"[a-z]{4,}", q))
935
+ cjk = re.sub(r"[^\u4e00-\u9fff]", "", q)
936
+ toks.update(cjk[i:i + 2] for i in range(len(cjk) - 1))
937
+ return toks
938
+
939
+ def r_bing():
940
+ t = load_text("bing.html")
941
+ if not t:
942
+ return None
943
+ out = []
944
+ for m in re.finditer(r'<h2[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', t, re.S | re.I):
945
+ u, ti = m.group(1), clean(m.group(2))
946
+ if ti and u.startswith("http"):
947
+ out.append((ti, u, ""))
948
+ rows = rowify(out)
949
+ # 🕳️ 投毒闸门(2026-10-05 实测):cn.bing 对本机 HTTP 200 + 页面结构正常,但返回与 query
950
+ # 完全无关的填充页(「意式咖啡豆 中深烘 拿铁」→ 法语「巴西米饭做法」;同 query 稳定复现;
951
+ # 随机参数 / no-cache 头 / 换 UA / 换 mkt 全部无效)→ 服务端反爬投毒,非缓存串号也非解析 bug。
952
+ # 假结果比无响应更毒(同 V2EX 教训):标题与 query 无 ≥2 个 token 重合的条目一律剔除,
953
+ # 全被剔除则报 ⚠️ 而不是 ✅。
954
+ if rows:
955
+ toks = _query_tokens(Q)
956
+ if toks:
957
+ need = 2 if len(toks) >= 3 else 1
958
+ keep = [r for r in rows if sum(k in r[0].lower() for k in toks) >= need]
959
+ if not keep:
960
+ return ("ERR", f"返回 {len(rows)} 条但与查询完全无关(疑似反爬投毒:本机实测 "
961
+ f"cn.bing 返回法语食谱/乌尔都语诗歌等填充页,同 query 稳定复现;"
962
+ f"加随机参数 / no-cache / 换 UA 均无效)")
963
+ rows = keep
964
+ return rows
965
+
966
+ def r_se():
967
+ d = load_json("se.json")
968
+ if d is None:
969
+ return None
970
+ out = []
971
+ for i in d.get("items") or []:
972
+ x = f"score {i.get('score', '-')} · {i.get('answer_count', 0)} 答"
973
+ if i.get("is_answered"):
974
+ x += " · ✅已采纳"
975
+ out.append((i.get("title", ""), i.get("link", ""), x))
976
+ return rowify(out)
977
+
978
+ def r_hn():
979
+ d = load_json("hn.json")
980
+ if d is None:
981
+ return None
982
+ out = []
983
+ for h in d.get("hits") or []:
984
+ u = h.get("url") or (f"https://news.ycombinator.com/item?id={h['objectID']}"
985
+ if h.get("objectID") else "")
986
+ out.append((h.get("title", ""), u,
987
+ f"{h.get('points', 0)} 分 · {h.get('num_comments', 0)} 评论"))
988
+ return rowify(out)
989
+
990
+ def r_jj():
991
+ d = load_json("jj.json")
992
+ if d is None:
993
+ return None
994
+ out = []
995
+ def walk(o): # 标题埋在 article_info 里,article_id 要拼 URL
996
+ if isinstance(o, dict):
997
+ ai = o.get("article_info")
998
+ if isinstance(ai, dict) and ai.get("title"):
999
+ aid = ai.get("article_id") or o.get("article_id")
1000
+ out.append((ai.get("title", ""),
1001
+ f"https://juejin.cn/post/{aid}" if aid else "",
1002
+ trunc(ai.get("brief_content", ""), 90)))
1003
+ for v in o.values():
1004
+ walk(v)
1005
+ elif isinstance(o, list):
1006
+ for v in o:
1007
+ walk(v)
1008
+ walk(d)
1009
+ return rowify(out)
1010
+
1011
+ def r_oalex():
1012
+ d = load_json("oalex.json")
1013
+ if d is None:
1014
+ return None
1015
+ return rowify([(w.get("display_name") or w.get("title") or "",
1016
+ w.get("id") or w.get("doi") or "",
1017
+ f"被引 {w.get('cited_by_count', 0)}")
1018
+ for w in d.get("results") or []])
1019
+
1020
+ def r_crossref():
1021
+ d = load_json("crossref.json")
1022
+ if d is None:
1023
+ return None
1024
+ out = []
1025
+ for it in (d.get("message") or {}).get("items") or []:
1026
+ ti = it.get("title") or []
1027
+ ti = ti[0] if isinstance(ti, list) and ti else (ti if isinstance(ti, str) else "")
1028
+ yr = ""
1029
+ try:
1030
+ yr = str(it["published"]["date-parts"][0][0])
1031
+ except Exception:
1032
+ pass
1033
+ out.append((ti, it.get("URL") or it.get("DOI") or "", yr))
1034
+ return rowify(out)
1035
+
1036
+ def r_segfault():
1037
+ t = load_text("segfault.html")
1038
+ if not t:
1039
+ return None
1040
+ return rowify([(clean(m.group(2)), "https://segmentfault.com" + m.group(1), "")
1041
+ for m in re.finditer(
1042
+ r'<a[^>]+href="(/a/[0-9A-Za-z_-]+)"[^>]*>(.*?)</a>', t, re.S | re.I)
1043
+ if len(clean(m.group(2))) > 4])
1044
+
1045
+ def r_gh():
1046
+ d = load_json("gh.json")
1047
+ if d is None:
1048
+ return None
1049
+ items = d.get("items")
1050
+ if not isinstance(items, list):
1051
+ return None
1052
+ return rowify([("%s ★%s" % (it.get("full_name", ""), it.get("stargazers_count", 0)),
1053
+ it.get("html_url", ""),
1054
+ trunc(it.get("description") or "", 100))
1055
+ for it in items])
1056
+
1057
+ def r_xhs():
1058
+ d = load_json("xhs.json")
1059
+ if not isinstance(d, dict):
1060
+ return None
1061
+ items = (d.get("data") or {}).get("items")
1062
+ if not isinstance(items, list):
1063
+ return None
1064
+ rows = []
1065
+ for it in items[:6]:
1066
+ nc = it.get("note_card") or {}
1067
+ title = nc.get("display_title") or nc.get("desc") or ""
1068
+ note_id = it.get("id") or ""
1069
+ if not title or not note_id:
1070
+ continue
1071
+ author = ((nc.get("user") or {}).get("nickname") or "").strip()
1072
+ likes = ((nc.get("interact_info") or {}).get("liked_count") or "").strip()
1073
+ meta = " · ".join(value for value in (author, (likes + " 赞") if likes else "") if value) or "小红书笔记"
1074
+ rows.append((trunc(title, 80), "https://www.xiaohongshu.com/explore/" + note_id, meta))
1075
+ return rowify(rows)
1076
+
1077
+ def r_bili():
1078
+ d = load_json("bili.json")
1079
+ if not isinstance(d, dict):
1080
+ return None
1081
+ vs = (d.get("result") or {}).get("videos")
1082
+ if not isinstance(vs, list):
1083
+ return None
1084
+ return rowify([(trunc(v.get("title", ""), 80),
1085
+ "https://www.bilibili.com/video/" + v.get("bvid", ""),
1086
+ "%s · %s 播放 · %s" % (v.get("author", ""), v.get("play", ""), v.get("duration", "")))
1087
+ for v in vs[:6] if v.get("bvid")])
1088
+
1089
+ def r_fcdev():
1090
+ d = load_json("fcdev.json")
1091
+ if d is None:
1092
+ return None
1093
+ items = d.get("data") if isinstance(d.get("data"), list) else None
1094
+ if items is None:
1095
+ return rowify(walk_generic(d))
1096
+ return rowify([(it.get("title", ""), it.get("url", ""),
1097
+ trunc(it.get("description") or it.get("snippet") or "", 100))
1098
+ for it in items])
1099
+
1100
+ def r_tf():
1101
+ """TinyFish search:hosted MCP tools/call 的 JSON-RPC 响应。
1102
+ hosted 返回可能是裸 JSON 或 SSE data: 行;results 可能在 structuredContent
1103
+ 或 content[0].text 内嵌 JSON 里,逐个兼容,最后 walk_generic 兜底。"""
1104
+ t = load_text("tf.json")
1105
+ if not t:
1106
+ return None
1107
+ r = None
1108
+ if t.lstrip().startswith("{"):
1109
+ r = json.loads(t)
1110
+ else:
1111
+ for line in t.splitlines():
1112
+ if line.startswith("data:"):
1113
+ d = line[5:].strip()
1114
+ if d.startswith("{"):
1115
+ r = json.loads(d)
1116
+ break
1117
+ if not isinstance(r, dict):
1118
+ return None
1119
+ if r.get("error"):
1120
+ return ("ERR", "TinyFish API 错误:" + str(r["error"].get("message", r["error"]))[:120])
1121
+ res = r.get("result") or {}
1122
+ results = None
1123
+ sc = res.get("structuredContent")
1124
+ if isinstance(sc, dict):
1125
+ results = sc.get("results") or sc.get("data")
1126
+ if results is None:
1127
+ for block in (res.get("content") or []):
1128
+ txt = block.get("text") if isinstance(block, dict) else None
1129
+ if not txt:
1130
+ continue
1131
+ try:
1132
+ inner = json.loads(txt)
1133
+ except Exception:
1134
+ continue
1135
+ results = inner.get("results") or inner.get("data")
1136
+ if results is not None:
1137
+ break
1138
+ if results is None:
1139
+ rows = rowify(walk_generic(res))
1140
+ else:
1141
+ rows = rowify([(it.get("title", ""), it.get("url", ""),
1142
+ trunc(it.get("snippet") or it.get("description") or "", 100))
1143
+ for it in results])
1144
+ if not rows:
1145
+ return ("ERR", "TinyFish 返回 0 条(凭据无效或限流时也会 0 条;看 tf.err)")
1146
+ return rows
1147
+
1148
+ def r_langsearch():
1149
+ d = load_json("langsearch.json")
1150
+ if d is None:
1151
+ return None
1152
+ if d.get("code") not in (None, 200):
1153
+ return ("ERR", f"body code={d.get('code')} {trunc(d.get('msg', ''), 160)}")
1154
+ vals = ((d.get("data") or {}).get("webPages") or {}).get("value") or []
1155
+ out = []
1156
+ for v in vals:
1157
+ x = trunc(v.get("snippet") or v.get("text") or "", 100)
1158
+ if v.get("datePublished"):
1159
+ x = (x + " · " + v["datePublished"][:10])
1160
+ out.append((v.get("name", ""), v.get("url", ""), x))
1161
+ return rowify(out)
1162
+
1163
+ def r_exa():
1164
+ d = load_json("exa.json")
1165
+ if d is None:
1166
+ return None
1167
+ if d.get("error"):
1168
+ return ("ERR", trunc(d.get("error"), 200))
1169
+ return rowify([(x.get("title", ""), x.get("url", ""),
1170
+ trunc(x.get("snippet") or x.get("text") or "", 100))
1171
+ for x in d.get("results") or []])
1172
+
1173
+ def r_tavily():
1174
+ d = load_json("tavily.json")
1175
+ if d is None:
1176
+ return None
1177
+ if d.get("error") or d.get("detail"):
1178
+ return ("ERR", trunc(str(d.get("error") or d.get("detail")), 200))
1179
+ items = d.get("results") if isinstance(d.get("results"), list) else None
1180
+ if items is None:
1181
+ return rowify(walk_generic(d))
1182
+ # content 是整段正文(实测 1300–1500 字),截到 120 字作摘要
1183
+ return rowify([(it.get("title", ""), it.get("url", ""), trunc(it.get("content") or "", 120))
1184
+ for it in items])
1185
+
1186
+ def r_parallel():
1187
+ d = load_json("parallel.json")
1188
+ if d is None:
1189
+ return None
1190
+ items = d.get("results") if isinstance(d.get("results"), list) else None
1191
+ if items is None:
1192
+ return rowify(walk_generic(d))
1193
+ rows = []
1194
+ for it in items:
1195
+ ex = it.get("excerpts") or []
1196
+ snip = trunc(" ".join(str(e) for e in ex), 120) if ex else ""
1197
+ # 发布日期对「最新/时效」类问题有用,拼进摘要最前面
1198
+ if it.get("publish_date"):
1199
+ snip = f"[{it['publish_date']}] {snip}"
1200
+ rows.append((it.get("title", ""), it.get("url", ""), snip))
1201
+ return rowify(rows)
1202
+
1203
+ def r_serper():
1204
+ d = load_json("serper.json")
1205
+ if d is None:
1206
+ return None
1207
+ if d.get("message") or d.get("error"):
1208
+ return ("ERR", trunc(str(d.get("message") or d.get("error")), 200))
1209
+ rows = list(d.get("organic") or [])
1210
+ # knowledgeGraph(实体卡:门店/品牌/景点)常常是本地生活最准的那条,排在最前
1211
+ kg = d.get("knowledgeGraph") or {}
1212
+ if kg.get("title") and kg.get("descriptionLink"):
1213
+ rows.insert(0, {"title": kg.get("title"), "link": kg.get("descriptionLink"),
1214
+ "snippet": kg.get("description", "")})
1215
+ return rowify([(x.get("title", ""), x.get("link", ""),
1216
+ trunc(x.get("snippet") or "", 100)) for x in rows])
1217
+
1218
+ def r_youcom():
1219
+ d = load_json("youcom.json")
1220
+ if d is None:
1221
+ return None
1222
+ web = (d.get("results") or {}).get("web") if isinstance(d.get("results"), dict) else None
1223
+ if not isinstance(web, list):
1224
+ return rowify(walk_generic(d))
1225
+ rows = []
1226
+ for it in web:
1227
+ hl = ((it.get("contents") or {}).get("highlights") or [])
1228
+ snip = trunc(str(hl[0]), 120) if hl else trunc(it.get("description") or "", 120)
1229
+ # page_age 对「最新/时效」类问题有用
1230
+ if it.get("page_age"):
1231
+ snip = f"[{str(it['page_age'])[:10]}] {snip}"
1232
+ rows.append((it.get("title", ""), it.get("url", ""), snip))
1233
+ return rowify(rows)
1234
+
1235
+ def r_anysearch():
1236
+ d = load_json("anysearch.json")
1237
+ if d is None:
1238
+ return None
1239
+ # 成功是 code==0;402 是额度耗尽,403 是 key 过期
1240
+ if d.get("code") not in (0, None):
1241
+ return ("ERR", trunc(str(d.get("message") or "code != 0"), 200))
1242
+ items = (d.get("data") or {}).get("results") if isinstance(d.get("data"), dict) else None
1243
+ if not isinstance(items, list):
1244
+ return rowify(walk_generic(d))
1245
+ # 实测 snippet 常是站点侧栏推荐语(与 query 无关),content 才是正文 —— 优先 content。
1246
+ rows = []
1247
+ for it in items:
1248
+ body = it.get("content") or ""
1249
+ # content 是一整行压平的 markdown("# 标题 # 站点名 > 栏目 ..."),
1250
+ # 按 # 切开取第一段够长的实义文字,否则摘要会全是标题和面包屑
1251
+ if body:
1252
+ parts = [x.strip() for x in re.split(r"#+", body) if len(x.strip()) > 20]
1253
+ body = parts[0] if parts else body.strip()
1254
+ rows.append((it.get("title", ""), it.get("url", ""),
1255
+ trunc(body or it.get("snippet") or "", 120)))
1256
+ return rowify(rows)
1257
+
1258
+ def _zhihu_rows(fname):
1259
+ """知乎开放平台 zhihu_search / global_search 共用:Data.Items[] 同构。"""
1260
+ d = load_json(fname)
1261
+ if d is None:
1262
+ return None
1263
+ code = d.get("Code")
1264
+ if code not in (0, None):
1265
+ return ("ERR", trunc(f'{code}: {d.get("Message") or "zhihu error"}', 160))
1266
+ data = d.get("Data") or {}
1267
+ items = data.get("Items") if isinstance(data, dict) else None
1268
+ if not isinstance(items, list):
1269
+ return rowify(walk_generic(d))
1270
+ rows = []
1271
+ for it in items:
1272
+ meta = f'[赞{it.get("VoteUpCount", 0)}·评{it.get("CommentCount", 0)}] '
1273
+ ts = it.get("EditTime") or it.get("CreateTime")
1274
+ if isinstance(ts, (int, float)) and ts > 0:
1275
+ meta += time.strftime("%Y-%m-%d", time.localtime(ts)) + " "
1276
+ rows.append((it.get("Title", ""), it.get("Url", ""),
1277
+ meta + trunc(it.get("ContentText") or "", 100)))
1278
+ return rowify(rows)
1279
+
1280
+ def r_zhihu():
1281
+ return _zhihu_rows("zhihu.json")
1282
+
1283
+ def r_zhihuall():
1284
+ return _zhihu_rows("zhihuall.json")
1285
+
1286
+ def r_zhihuhot():
1287
+ d = load_json("zhihuhot.json")
1288
+ if d is None:
1289
+ return None
1290
+ code = d.get("Code")
1291
+ if code not in (0, None):
1292
+ return ("ERR", trunc(f'{code}: {d.get("Message") or "hot_list error"}', 160))
1293
+ items = (d.get("Data") or {}).get("Items") or []
1294
+ return rowify([(it.get("Title", ""), it.get("Url", ""),
1295
+ trunc(it.get("Summary") or "", 100)) for it in items])
1296
+
1297
+ def r_zhida():
1298
+ """直答是 OpenAI 兼容对话:没有来源链接,返回纯文本(走 txt_only 分支)。"""
1299
+ d = load_json("zhida.json")
1300
+ if d is None:
1301
+ return None
1302
+ err = d.get("error")
1303
+ if isinstance(err, dict):
1304
+ return ("ERR", trunc(str(err.get("message") or err.get("code") or "zhida error"), 160))
1305
+ ch = (d.get("choices") or [{}])[0]
1306
+ txt = ((ch.get("message") or {}).get("content") or "").strip()
1307
+ return txt or None
1308
+
1309
+ def r_brave():
1310
+ """Brave Web Search:web.results[] 里 title/url/description,description 是 1-2 句摘要。"""
1311
+ d = load_json("brave.json")
1312
+ if d is None:
1313
+ return None
1314
+ if d.get("error") or d.get("type") == "ErrorResponse":
1315
+ msg = d.get("message") or (d.get("error") or {}).get("detail") or "brave error"
1316
+ return ("ERR", trunc(str(msg), 160))
1317
+ rows = []
1318
+ for it in ((d.get("web") or {}).get("results") or []):
1319
+ if not isinstance(it, dict):
1320
+ continue
1321
+ rows.append((it.get("title") or "", it.get("url") or "",
1322
+ it.get("description") or it.get("snippet") or ""))
1323
+ return rowify(rows)
1324
+
1325
+ def r_fcs():
1326
+ raw = load_text("fcs.json")
1327
+ status = http_code("fcs")
1328
+ if raw is None:
1329
+ if status == "200":
1330
+ return ("ERR", "Firecrawl v2 returned HTTP 200 with an empty response body")
1331
+ curl_rc = load_text("fcs.rc") or "unknown"
1332
+ curl_error = load_text("fcs.err") or "no curl diagnostic"
1333
+ return ("ERR", f"Firecrawl v2 request produced HTTP {status or 'unknown'}, curl exit {curl_rc}: {trunc(curl_error, 120)}")
1334
+ try:
1335
+ d = json.loads(raw)
1336
+ except Exception:
1337
+ if status == "200":
1338
+ return ("ERR", f"Firecrawl v2 returned HTTP 200 with non-JSON body: {trunc(raw, 120)}")
1339
+ curl_rc = load_text("fcs.rc") or "unknown"
1340
+ curl_error = load_text("fcs.err") or "no curl diagnostic"
1341
+ return ("ERR", f"Firecrawl v2 request produced HTTP {status or 'unknown'}, curl exit {curl_rc}: {trunc(curl_error, 120)}")
1342
+ if not isinstance(d, dict):
1343
+ return ("ERR", "Firecrawl v2 returned a non-object JSON response")
1344
+ if d.get("success") is False:
1345
+ return ("ERR", trunc(str(d.get("error") or "firecrawl search failed"), 200))
1346
+ payload = d.get("data")
1347
+ if isinstance(payload, dict):
1348
+ items = payload.get("web") or []
1349
+ elif isinstance(payload, list): # tolerate a legacy-shaped cached response
1350
+ items = payload
1351
+ else:
1352
+ items = []
1353
+ rows = []
1354
+ for item in items:
1355
+ if not isinstance(item, dict):
1356
+ continue
1357
+ rows.append((item.get("title") or "", item.get("url") or "",
1358
+ trunc(item.get("description") or item.get("markdown") or "", 100)))
1359
+ return rowify(rows)
1360
+
1361
+ def r_wiki():
1362
+ d = load_json("wiki.json")
1363
+ if d is None:
1364
+ return None
1365
+ if d.get("type") == "none":
1366
+ return [] # 无对应条目 = 0 命中,不是通道故障
1367
+ if d.get("type") == "disambiguation" or d.get("title") is None:
1368
+ return ("ERR", "维基百科没有这个条目(或只有消歧义页)")
1369
+ title = d.get("title") or ""
1370
+ ex = (d.get("extract") or "").strip()
1371
+ if not title or not ex:
1372
+ return ("ERR", "维基百科条目没有正文")
1373
+ url = ((d.get("content_urls") or {}).get("desktop") or {}).get("page") \
1374
+ or "https://zh.wikipedia.org/wiki/" + title.replace(" ", "_")
1375
+ return rowify([(title, url, trunc(ex, 100))])
1376
+
1377
+ def r_fcres():
1378
+ d = load_json("fcres.json")
1379
+ if d is None:
1380
+ return None
1381
+ for k in ("results", "data", "papers"): # 顶层是 results(不是 data)
1382
+ rows = d.get(k)
1383
+ if not isinstance(rows, list):
1384
+ continue
1385
+ out = []
1386
+ for x in rows:
1387
+ u = x.get("url") or x.get("pdf_url") or ""
1388
+ pid = str(x.get("primaryId") or "")
1389
+ if not u and pid.startswith("arxiv:"):
1390
+ u = "https://arxiv.org/abs/" + pid[6:]
1391
+ elif not u and pid.startswith("DOI:"):
1392
+ u = "https://doi.org/" + pid[4:]
1393
+ out.append((x.get("title", ""), u, trunc(x.get("abstract") or "", 110)))
1394
+ return rowify(out)
1395
+ return rowify(walk_generic(d))
1396
+
1397
+ # (key, 通道名, 说明, 解析函数, 仅 deep)
1398
+ SECTIONS = [
1399
+ ("qianfan", "百度千帆(生成式综合答案)",
1400
+ "⚠️ AI 浓缩回答、非来源链接 —— 关键结论必须另找一手源验证",
1401
+ lambda: load_text("qianfan.txt"), False),
1402
+ ("gh", "GitHub 仓库搜索(★ 排序,免 Key)", "免 Key 10 次/分钟;只认英文关键词", r_gh, False),
1403
+ ("fcdev", "Firecrawl Developer Index(编程一手源 70M+)", "免 Key 不限量", r_fcdev, False),
1404
+ ("se", "StackExchange(报错排障)", "免 Key 不限量", r_se, False),
1405
+ ("hn", "Hacker News(深技术讨论)", "免 Key 不限量", r_hn, False),
1406
+ ("jj", "掘金(中文技术长尾)", "免 Key 不限量", r_jj, False),
1407
+ ("zhihu", "知乎站内搜索(开放平台官方 API)", "需 ZHIHU_SEARCH_API_KEY;结果带赞同/评论数", r_zhihu, False),
1408
+ ("zhihuall", "知乎全网搜索(开放平台官方 API)", "需 ZHIHU_SEARCH_API_KEY;5000 次/日,中文全网带权威分级", r_zhihuall, False),
1409
+ ("zhihuhot", "知乎热榜(全站热点,与查询词无关)", "需 ZHIHU_SEARCH_API_KEY;100 次/日,deep 档才跑", r_zhihuhot, True),
1410
+ ("zhida", "知乎直答(AI 摘要,非来源链接)", "需 ZHIHU_SEARCH_API_KEY;100 次/日,deep 档才跑", r_zhida, True),
1411
+ ("brave", "Brave Search(自有索引,不经 Google/Bing)", "需 BRAVE_API_KEY;每月 $5 免费 credits≈1000 次,用完自动停", r_brave, False),
1412
+ ("segfault", "SegmentFault(中文技术长尾)", "免 Key 不限量", r_segfault, False),
1413
+ ("oalex", "OpenAlex(学术 2.5 亿篇)", "免 Key 不限量", r_oalex, False),
1414
+ ("crossref", "Crossref(DOI 权威元数据)", "免 Key 不限量", r_crossref, False),
1415
+ ("tf", "TinyFish Search(官方 hosted MCP,$0/次)", "需 TINYFISH_API_KEY", r_tf, False),
1416
+ ("serper", "Serper Google(本地生活/电商最强)", "2,500 次一次性赠送,已 quota.py use", r_serper, False),
1417
+ ("tavily", "Tavily keyless(无账号,正文摘录)", "免费无 key;约 30 次/IP 后 429,不记账", r_tavily, False),
1418
+ ("parallel", "Parallel MCP(无 key,excerpts + 日期)", "免费无 key;匿名限流,不记账", r_parallel, False),
1419
+ ("youcom", "You.com 免 key MCP(100 次/天,0.4s)", "免 key 无账号;每天 100 次", r_youcom, False),
1420
+ ("anysearch","AnySearch(1000 次/天,20+ 垂直域)", "带 key 额度不按 IP;每天 1000 次", r_anysearch, False),
1421
+ ("fcs", "Firecrawl v2 Search(全文搜索,质量高)", "消耗 firecrawl credits,已 quota.py use", r_fcs, False),
1422
+ ("wiki", "Wikipedia(概念/人物/地名)", "完全免费无限量", r_wiki, False),
1423
+ ("xhs", "国内版小红书(真实体验/种草/避坑)", "可选 xhs CLI;缺少时按未配置跳过;需登录态;冷却 2 分钟", r_xhs, False),
1424
+ ("bili", "B 站视频(实测/教程/评测)", "可选 bilibili CLI;缺少时按未配置跳过;需登录态;冷却 90 秒", r_bili, False),
1425
+ ("langsearch", "LangSearch count=20(时效/限域)", "每日 token 额度;本技能自设 50/日保守线,已 quota.py use", r_langsearch, True),
1426
+ ("exa", "Exa(语义/英文)", "已 quota.py use", r_exa, True),
1427
+ ("fcres", "Firecrawl Research Index(学术论文全文)", "需 key、不记账(官方论文端点免费)", r_fcres, True),
1428
+ # V2EX 已退役(会返回与 query 无关的假结果),见文件头「已退役通道」
1429
+ ]
1430
+ SKIPMAP = {"langsearch": "langsearch", "exa": "exa", "fcres": "fcres", "tf": "tinyfish", "serper": "serper", "fcs": ("firecrawl", "firecrawl_search"), "wiki": "wiki", "tavily": "tavily", "parallel": "parallel"}
1431
+
1432
+ def read_skip(key):
1433
+ aliases = SKIPMAP.get(key, ())
1434
+ if isinstance(aliases, str):
1435
+ aliases = (aliases,)
1436
+ for c in (key, *aliases):
1437
+ p = os.path.join(tmp, f"skip.{c}")
1438
+ if os.path.exists(p):
1439
+ return pathlib.Path(p).read_text().strip()
1440
+ return None
1441
+
1442
+ def http_code(key):
1443
+ """付费通道的 HTTP 状态码;没有记录返回 None。"""
1444
+ t = load_text(key + ".http")
1445
+ return t.strip() if t else None
1446
+
1447
+ _default_n = sum(1 for _s in SECTIONS if not _s[4] and _s[0] not in DISABLED)
1448
+ if ON:
1449
+ _selected = (ONLY or set()) - DISABLED
1450
+ _label = f"指定通道({len(_selected)} 路)"
1451
+ elif DEEP == "1":
1452
+ _deep_n = sum(1 for _s in SECTIONS if _s[0] not in DISABLED)
1453
+ _label = f"deep 深调研档({_deep_n} 路)"
1454
+ else:
1455
+ _label = f"默认档({_default_n} 路)"
1456
+ if DISABLED:
1457
+ _label += f";未运行 {', '.join(sorted(DISABLED))}"
1458
+ print(f"## fanout「{Q}」— {_label}\n")
1459
+ ZHQ = os.environ.get("D_REACH_ZHQ") or Q
1460
+ ENQ = os.environ.get("D_REACH_ENQ") or Q
1461
+ DUAL = os.environ.get("D_REACH_DUAL") == "1"
1462
+ BILINGUAL = set((os.environ.get("D_REACH_BILINGUAL") or "").split())
1463
+ _cjk = lambda q: bool(re.search(r"[\u4e00-\u9fff\u3400-\u4dbf]", q or ""))
1464
+ if DUAL:
1465
+ print(f"> 双语检索:中文「{ZHQ}」|英文「{ENQ}」;通用网页通道中英各查一遍,社区站只用本站语言\n")
1466
+ # 每路实际吃的是哪种语言:英文站吃 ENQ,中文站吃 ZHQ,其余单查时看原 query
1467
+ NATIVE_EN = {"se", "hn", "gh", "oalex", "crossref", "fcdev", "fcres"}
1468
+ NATIVE_ZH = {"qianfan", "jj", "segfault", "zhihu", "zhihuall", "zhihuhot", "zhida", "xhs", "bili", "wiki"}
1469
+ def native_lang(key):
1470
+ if key in NATIVE_EN:
1471
+ return "中" if _cjk(ENQ) else "英"
1472
+ if key in NATIVE_ZH:
1473
+ return "中" if _cjk(ZHQ) else "英"
1474
+ return "中" if _cjk(Q) else "英"
1475
+ # ---------- 通道健康状态(跨轮记忆)----------
1476
+ HEALTH = pathlib.Path(os.environ.get("D_REACH_HEALTH") or os.path.expanduser("~/.agent-reach/channels.json"))
1477
+
1478
+ def load_health():
1479
+ try:
1480
+ return json.loads(HEALTH.read_text(encoding="utf-8"))
1481
+ except Exception:
1482
+ return {}
1483
+
1484
+ @contextlib.contextmanager
1485
+ def _file_lock(path):
1486
+ """跨进程互斥(照 quota.py 的 fcntl.flock 写法);锁文件与数据文件同目录。"""
1487
+ path.parent.mkdir(parents=True, exist_ok=True)
1488
+ lock_path = path.with_name(path.name + ".lock")
1489
+ fh = open(lock_path, "a+")
1490
+ fcntl.flock(fh, fcntl.LOCK_EX)
1491
+ try:
1492
+ yield
1493
+ finally:
1494
+ fcntl.flock(fh, fcntl.LOCK_UN)
1495
+ fh.close()
1496
+
1497
+ def _atomic_write(path, text):
1498
+ """tmp + replace:读者永远看到完整文件,不会读到写一半的 JSON。"""
1499
+ tmpf = path.with_name(f"{path.name}.tmp.{os.getpid()}")
1500
+ tmpf.write_text(text, encoding="utf-8")
1501
+ tmpf.replace(path)
1502
+
1503
+ TOUCHED = set() # 本轮真正改过的通道键:保存时只合并这些,别整份覆盖别的进程的更新
1504
+
1505
+ def save_health(h):
1506
+ try:
1507
+ with _file_lock(HEALTH):
1508
+ try:
1509
+ disk = json.loads(HEALTH.read_text(encoding="utf-8"))
1510
+ except Exception:
1511
+ disk = {}
1512
+ if not isinstance(disk, dict):
1513
+ disk = {}
1514
+ # 脚本指纹变了 → 磁盘上的旧结论也一并作废(与内存里启动时的处理保持一致)
1515
+ for _k, _v in disk.items():
1516
+ if isinstance(_v, dict) and _v.get("fp") and FP and _v["fp"] != FP:
1517
+ for _f in ("suspend_until", "suspend_secs", "code", "streak_fail"):
1518
+ _v.pop(_f, None)
1519
+ for _k in TOUCHED:
1520
+ if _k in h:
1521
+ disk[_k] = h[_k]
1522
+ _atomic_write(HEALTH, json.dumps(disk, indent=2, ensure_ascii=False))
1523
+ except Exception:
1524
+ pass
1525
+
1526
+ health = load_health()
1527
+ now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds")
1528
+
1529
+ # 挂起退避阶梯(秒):第 3 次连败挂 10 分钟,第 4 次 30 分钟,第 5 次起 2 小时封顶。
1530
+ # 取小值是为了「坏通道别永久静默」——挂起到期会自动重试一次,通了就清零。
1531
+ BACKOFF = [600, 1800, 7200]
1532
+
1533
+ # 失败的「性质」决定要不要等它自己好。照 Agent-Reach 的错误码分层:
1534
+ # 自愈类(timeout/upstream/empty)—— 连败 3 次才进退避阶梯;
1535
+ # 确定性结论(登录墙/风控/凭据/限流/端点没了)—— 重试只会撞同一堵墙,
1536
+ # 首次就挂起,并且文案要说清「谁该出手」,而不是干巴巴一句「连败 N 次」。
1537
+ NEEDS = {
1538
+ "login": "站点要登录:浏览器里登录过一次,或换公开来源",
1539
+ "antibot": "撞了风控验证码:等几小时或换检索词",
1540
+ "auth": "key 失效或被拒:换 key 后自动恢复",
1541
+ "ratelimit": "平台限流:冷却窗口内不再打",
1542
+ "notfound": "端点 404:脚本里的地址要更新",
1543
+ "setup": "本机依赖不可用:先修依赖",
1544
+ }
1545
+ NEEDS_TITLE = {
1546
+ "login": "要登录", "antibot": "要过验证码", "auth": "凭据失效",
1547
+ "ratelimit": "限流中", "notfound": "端点失效", "setup": "依赖缺失",
1548
+ }
1549
+ NEEDS_TTL = 6 * 3600 # 确定性结论挂 6 小时,到期给一次自愈机会,不永久静默
1550
+ FP = os.environ.get("D_REACH_FP") or ""
1551
+
1552
+ # 脚本改过 → 旧的「这路坏了」结论可能已不成立,作废重测
1553
+ for _k, _v in health.items():
1554
+ if isinstance(_v, dict) and _v.get("fp") and FP and _v["fp"] != FP:
1555
+ for _f in ("suspend_until", "suspend_secs", "code", "streak_fail"):
1556
+ _v.pop(_f, None)
1557
+
1558
+ ROUND = [] # 本轮每路的结果,最后写进 history.jsonl
1559
+ def mark(key, status, code=None):
1560
+ """记「失败性质 + 连败次数 + 成败时间 + 挂起到期」。skip 不计失败,避免本轮没请求把通道判死。
1561
+
1562
+ 自愈类连败 ≥3 进退避:10 分钟 → 30 分钟 → 2 小时封顶;
1563
+ 确定性类(NEEDS)首次失败就挂 6 小时,并在输出里点名该做什么。
1564
+ 到期自动重试一次:成功清零、失败继续升级。通道不会「跳过→不跑→永不成功」死锁。
1565
+ """
1566
+ v = health.setdefault(key, {"streak_fail": 0})
1567
+ TOUCHED.add(key)
1568
+ ROUND.append({"key": key, "status": status})
1569
+ if FP:
1570
+ v["fp"] = FP
1571
+ if status == "ok":
1572
+ v["streak_fail"] = 0
1573
+ v["last_ok"] = now_iso
1574
+ for f in ("suspend_until", "suspend_secs", "code"): # 成功即解除挂起
1575
+ v.pop(f, None)
1576
+ elif status == "fail":
1577
+ v["last_fail"] = now_iso
1578
+ code = code or "upstream"
1579
+ v["code"] = code
1580
+ if code in NEEDS:
1581
+ secs = NEEDS_TTL
1582
+ else:
1583
+ v["streak_fail"] = v.get("streak_fail", 0) + 1
1584
+ n = v["streak_fail"]
1585
+ secs = BACKOFF[min(n - 3, len(BACKOFF) - 1)] if n >= 3 else 0
1586
+ if secs:
1587
+ v["suspend_until"] = (
1588
+ datetime.now(timezone.utc) + timedelta(seconds=secs)
1589
+ ).isoformat(timespec="seconds")
1590
+ v["suspend_secs"] = secs
1591
+
1592
+ total, okc, zero = 0, 0, 0
1593
+ txt_only = 0 # 只给 AI 摘要、没有来源链接的路数(千帆),不能算「有结果」
1594
+
1595
+ # ---------- 跨源合并:先把每路输出缓冲住,最后统一排序 ----------
1596
+ # 同一 URL 在 3 个源都出现就重复 3 遍,读者得自己判可信度。SearXNG 的做法是全局合并:
1597
+ # 同 URL 只留一条,按「被几个源同时排到前面」打分(score = 命中源数 × Σ 权重/名次)。
1598
+ # 多个独立源都排前面的才是真信号。分节视图保留在合并段之后,不缺信息。
1599
+ CHAN_OUT = [] # 各通道的 markdown 块(缓冲区)
1600
+ MERGE_ROWS = [] # (key, name, title, url, snippet, rank)
1601
+ CH_W = { # 通道权重:直接给正文的源比只给标题的高
1602
+ "serper": 1.0, "tavily": 1.0, "fcs": 1.0, "fcdev": 1.0, "tf": 1.0,
1603
+ "exa": 1.0, "qianfan": 1.0, "fcres": 1.0,
1604
+ "langsearch": 0.9, "parallel": 0.9, "youcom": 0.9, "anysearch": 1.0,
1605
+ "oalex": 0.8, "crossref": 0.8, "se": 0.8,
1606
+ "hn": 0.7,
1607
+ "jj": 0.6, "wiki": 0.6, "segfault": 0.6, "zhihu": 0.8, "zhihuall": 0.9, "zhihuhot": 0.4,
1608
+ "brave": 1.0,
1609
+ }
1610
+ DW = 0.7
1611
+
1612
+ _orig_print = print
1613
+
1614
+ def cprint(*a, **k):
1615
+ """循环内的 print:写进缓冲区,不立即上屏(等合并段算完再统一输出)。"""
1616
+ if k.get("file") not in (None, sys.stdout):
1617
+ _orig_print(*a, **k) # stderr 等旁路,不缓冲
1618
+ return
1619
+ import io as _io
1620
+ _b = _io.StringIO()
1621
+ k2 = dict(k); k2["file"] = _b
1622
+ _REAL_PRINT(*a, **k2)
1623
+ CHAN_OUT.append(_b.getvalue())
1624
+ _OUT.append(_b.getvalue()) # 历史详情仍要完整
1625
+
1626
+ print = cprint
1627
+ skipped, failed = [], []
1628
+ TMP0 = tmp
1629
+ _orig_mark = mark
1630
+ _DUALMARK = {} # 双查通道:中英两次的结论先攒着,最后合成一次(任一成功即成功)
1631
+ CUR_DUAL = False
1632
+ def mark(key, status, code=None):
1633
+ if CUR_DUAL:
1634
+ _DUALMARK.setdefault(key, []).append((status, code))
1635
+ return
1636
+ _orig_mark(key, status, code)
1637
+
1638
+ def _iter_sections():
1639
+ global tmp
1640
+ for key, name, note, fn, deep_only in SECTIONS:
1641
+ tmp = TMP0
1642
+ # 健康挂起写在根目录(发射前就判掉了,没真打)→ 按单路渲染一次
1643
+ if DUAL and key in BILINGUAL and read_skip(key) is None:
1644
+ for sub, lang in (("zh", "中"), ("en", "英")):
1645
+ tmp = os.path.join(TMP0, sub)
1646
+ yield key, f"{name} · {lang}文检索", note, fn, deep_only, lang, True
1647
+ tmp = TMP0
1648
+ else:
1649
+ yield key, name, note, fn, deep_only, native_lang(key), False
1650
+
1651
+ for key, name, note, fn, deep_only, LANG, CUR_DUAL in _iter_sections():
1652
+ KL = f"{key}·{LANG}" if CUR_DUAL else key
1653
+ if ONLY and key not in ONLY:
1654
+ continue # 本轮没请求这条路 → 不渲染(≠无响应)
1655
+ if key in DISABLED:
1656
+ continue # 不在本轮启用清单
1657
+ # --on 显式点名时,deep 档通道也要渲染,否则点名结果会被丢掉
1658
+ if deep_only and DEEP != "1" and key not in [c for c in (ON or "").split(",") if c] \
1659
+ and not os.path.exists(os.path.join(tmp, "skip." + key)):
1660
+ continue
1661
+ skip = read_skip(key)
1662
+ if skip == "health":
1663
+ v = health.get(key) or {}
1664
+ bad = v.get("streak_fail", 0)
1665
+ _code = v.get("code") or ""
1666
+ until = v.get("suspend_until")
1667
+ left = ""
1668
+ if until:
1669
+ try:
1670
+ delta = (datetime.fromisoformat(until) - datetime.now(timezone.utc)).total_seconds()
1671
+ if delta > 0:
1672
+ left = f",{int(delta // 60) + 1} 分钟后自动重试"
1673
+ except Exception:
1674
+ pass
1675
+ if _code in NEEDS:
1676
+ print(f"### 🔇 {name} —— {NEEDS_TITLE.get(_code, '通道异常')},先不打了{left}"
1677
+ f"({NEEDS[_code]};`--force` 可强跑)\n")
1678
+ else:
1679
+ print(f"### 🔇 {name} —— 连续失败 {bad} 次,挂起中{left}(`--force` 可强跑)\n")
1680
+ skipped.append(KL); mark(key, "skip")
1681
+ continue
1682
+ if skip == "key":
1683
+ print(f"### 🔇 {name} —— 未配置 API key(写入 `~/.config/agents/env` 即解锁)\n")
1684
+ skipped.append(KL); mark(key, "skip")
1685
+ continue
1686
+ if skip == "quota":
1687
+ print(f"### 🔇 {name} —— 已越免费线,本轮自动跳过\n")
1688
+ skipped.append(KL); mark(key, "skip")
1689
+ continue
1690
+ if skip == "cjk":
1691
+ print(f"### 🔇 {name} —— 检测到中文 query,本轮自动跳过(这个通道只认英文词:"
1692
+ f"中文打过去恒 0 命中,或只匹配上\"配置/安装\"这类字面词返回噪声;"
1693
+ f"调用方给出英文检索词就会自动放行)\n")
1694
+ skipped.append(KL); mark(key, "skip")
1695
+ continue
1696
+ if skip and skip.startswith("cooldown:"):
1697
+ print(f"### 🔇 {name} —— {skip.split(':', 1)[1]} 分钟内刚搜过"
1698
+ f"(这类通道连打会触发风控验证码,所以设了最小间隔)\n")
1699
+ skipped.append(KL); mark(key, "skip")
1700
+ continue
1701
+ if skip == "no-english":
1702
+ # 插件侧会包一层「跳过(note)」,这里不要再写「本轮跳过」否则双重嵌套
1703
+ print(f"### 🔇 {name} —— query 里没有英文关键词(GitHub 只认英文,中文搜不到)\n")
1704
+ skipped.append(KL); mark(key, "skip")
1705
+ continue
1706
+ if skip == "captcha":
1707
+ print(f"### 🔇 {name} —— 平台风控要验证码,已挂起 6 小时不再打"
1708
+ f"({NEEDS['antibot']};`--force` 可强跑;不影响其余通道)\n")
1709
+ failed.append(KL); mark(key, "fail", "antibot")
1710
+ continue
1711
+ if skip == "not-configured":
1712
+ v = health.get(key)
1713
+ if isinstance(v, dict):
1714
+ v["streak_fail"] = 0
1715
+ v.pop("suspend_until", None)
1716
+ v.pop("suspend_secs", None)
1717
+ v.pop("code", None)
1718
+ detail = load_text(key + ".txt") or "本机未配置此渠道。"
1719
+ print(f"### 🔇 {name} —— 未配置,已跳过且不计失败:{detail.strip()[:180]}\n")
1720
+ skipped.append(KL); mark(key, "skip")
1721
+ continue
1722
+ if skip == "err":
1723
+ detail = load_text(key + ".txt") or ""
1724
+ if key == "xhs":
1725
+ print(f"### ⚠️ {name} —— xhs CLI 搜索失败:{detail.strip()[:200]}\n")
1726
+ failed.append(KL); mark(key, "fail")
1727
+ else:
1728
+ print(f"### ⚠️ {name} —— 本机依赖不可用:{detail.strip()[:200]}\n")
1729
+ failed.append(KL); mark(key, "fail", "setup")
1730
+ continue
1731
+ try:
1732
+ rows = fn()
1733
+ except Exception as e:
1734
+ rows = None
1735
+ print(f"<!-- {key} 解析异常: {type(e).__name__}: {str(e)[:120]} -->", file=sys.stderr)
1736
+ code = http_code(key)
1737
+ if code and code not in ("200", "000") and (rows is None or rows == [] or isinstance(rows, tuple)):
1738
+ # 状态码本身就是结论:429 是限流(再打更糟)、401/403 是凭据、404 是端点没了,
1739
+ # 这三类都算确定性失败;5xx 才当上游抖动、靠退避自愈。
1740
+ _cls = ("ratelimit" if code == "429" else
1741
+ "auth" if code in ("401", "403") else
1742
+ "notfound" if code == "404" else "upstream")
1743
+ print(f"### ⚠️ {name} —— HTTP {code}({NEEDS_TITLE.get(_cls, '上游异常')},不是「没搜到」)\n")
1744
+ failed.append(KL); mark(key, "fail", _cls)
1745
+ continue
1746
+ if isinstance(rows, str): # 千帆文本
1747
+ body = rows.strip()
1748
+ if body:
1749
+ okc += 1; txt_only += 1; mark(key, "ok")
1750
+ print(f"### 💬 {name}\n_{note}_\n\n{body[:1800]}\n")
1751
+ else:
1752
+ print(f"### ❌ {name} —— 无返回\n"); failed.append(KL); mark(key, "fail", "empty")
1753
+ elif isinstance(rows, tuple): # ("ERR", msg)
1754
+ _msg = str(rows[1])
1755
+ _low = _msg.lower()
1756
+ _cls = "timeout" if ("超时" in _msg or "timed out" in _low or "timeout" in _low) else "upstream"
1757
+ print(f"### ⚠️ {name} —— {_msg}\n"); failed.append(KL); mark(key, "fail", _cls)
1758
+ elif rows is None:
1759
+ print(f"### ❌ {name} —— 通道无响应 / 超时\n"); failed.append(KL); mark(key, "fail", "timeout")
1760
+ elif not rows:
1761
+ zero += 1; mark(key, "ok")
1762
+ print(f"### ⚪ {name} —— 通道正常,0 命中\n")
1763
+ else:
1764
+ okc += 1; mark(key, "ok")
1765
+ total += len(rows)
1766
+ print(f"### ✅ {name}\n_{note}_\n")
1767
+ for rank, (t, u, x) in enumerate(rows):
1768
+ print(f"- [{t}]({u})" + (f" — {x}" if x else ""))
1769
+ MERGE_ROWS.append((key, name, t, u, x, rank, LANG))
1770
+ print()
1771
+
1772
+ # ---------- 恢复直输出:先出合并段,再放分节 ----------
1773
+ print = _orig_print
1774
+ tmp = TMP0
1775
+ CUR_DUAL = False
1776
+ for _k, _lst in _DUALMARK.items():
1777
+ _st = [x[0] for x in _lst]
1778
+ if "ok" in _st:
1779
+ _orig_mark(_k, "ok")
1780
+ elif "fail" in _st:
1781
+ _orig_mark(_k, "fail", next(c for st, c in _lst if st == "fail"))
1782
+ else:
1783
+ _orig_mark(_k, "skip")
1784
+
1785
+ def norm_url(u):
1786
+ """URL 归一化:去 fragment / utm 类参数 / www 前缀 / 尾斜杠,用于跨源判重。"""
1787
+ try:
1788
+ from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
1789
+ s = urlsplit(str(u).strip())
1790
+ host = (s.hostname or "").lower()
1791
+ if host.startswith("www."):
1792
+ host = host[4:]
1793
+ q = [(k, v) for k, v in parse_qsl(s.query)
1794
+ if not k.lower().startswith(("utm_", "ref", "fbclid", "gclid", "spm"))
1795
+ and k.lower() not in ("rankingid", "ranking_id")]
1796
+ path = s.path.rstrip("/") or "/"
1797
+ return urlunsplit(((s.scheme or "https").lower(), host, path, urlencode(q), ""))
1798
+ except Exception:
1799
+ return str(u).strip().lower()
1800
+
1801
+ agg = {}
1802
+ for key, name, t, u, x, rank, lang in MERGE_ROWS:
1803
+ nu = norm_url(u)
1804
+ d = agg.get(nu)
1805
+ if d is None:
1806
+ # url 存归一化后的:判重靠它,展示也靠它(原 URL 常带 utm/rankingId 这类跟踪参数)
1807
+ d = agg[nu] = {"title": t, "url": nu, "snippet": x or "", "hits": [], "langs": set()}
1808
+ d["hits"].append((key, rank, lang))
1809
+ d["langs"].add(lang)
1810
+ if not d["snippet"] and x:
1811
+ d["snippet"] = x
1812
+
1813
+ for d in agg.values():
1814
+ n = len(d["hits"])
1815
+ # 同一网页中英两轮都命中 = 两票(hits 里本来就是两条)
1816
+ d["score"] = n * sum(CH_W.get(k, DW) / (r + 1) for k, r, _l in d["hits"])
1817
+
1818
+ def _ltag(d):
1819
+ return "中英" if len(d["langs"]) > 1 else next(iter(d["langs"]))
1820
+
1821
+ LANG_N = {"中": 0, "英": 0, "中英": 0}
1822
+ for d in agg.values():
1823
+ LANG_N[_ltag(d)] += 1
1824
+ ranked = sorted(agg.values(), key=lambda d: (-d["score"], -len(d["hits"])))
1825
+ MERGE_TOP = max(15, N * 3)
1826
+
1827
+ if ranked:
1828
+ print(f"### 🔀 合并排序(去重后 {len(ranked)} 条:中文 {LANG_N['中']} · 英文 {LANG_N['英']}"
1829
+ f" · 中英都命中 {LANG_N['中英']};前 {min(len(ranked), MERGE_TOP)} 条)\n")
1830
+ for d in ranked[:MERGE_TOP]:
1831
+ srcs = " · ".join(f"{k}#{r + 1}{'' if not DUAL else '·' + l}"
1832
+ for k, r, l in sorted(d["hits"], key=lambda h: h[1]))
1833
+ print(f"- 〔{_ltag(d)}〕**[{d['title']}]({d['url']})** — {len(d['hits'])} 源({srcs})"
1834
+ + (f" — {d['snippet']}" if d["snippet"] else ""))
1835
+ print()
1836
+
1837
+ # 分节视图(保留「哪路出的」这个维度,合并段看不到的细节靠它)
1838
+ for _blk in CHAN_OUT:
1839
+ _REAL_PRINT(_blk, end="")
1840
+
1841
+ save_health(health)
1842
+ def _left(v):
1843
+ """挂起还剩几秒;None = 没挂起(含已到期)。"""
1844
+ u = v.get("suspend_until")
1845
+ if not u:
1846
+ return None
1847
+ try:
1848
+ d = (datetime.fromisoformat(u) - datetime.now(timezone.utc)).total_seconds()
1849
+ return int(d) if d > 0 else None
1850
+ except Exception:
1851
+ return None
1852
+
1853
+ weak, need = [], []
1854
+ _active_keys = {_s[0] for _s in SECTIONS}
1855
+ for k, v in health.items():
1856
+ if k not in _active_keys: # 已从档位移除的通道(如 bd)不再报
1857
+ continue
1858
+ if not isinstance(v, dict):
1859
+ continue
1860
+ left = _left(v)
1861
+ _code = v.get("code") or ""
1862
+ if _code in NEEDS:
1863
+ # 确定性结论:不是「次数到了」,是「这条路需要人处理」,措辞必须不同
1864
+ need.append(f"{k}({NEEDS_TITLE.get(_code, '异常')}"
1865
+ + (f",{left // 60 + 1} 分钟后重试" if left else "") + ")")
1866
+ elif v.get("streak_fail", 0) >= 3:
1867
+ weak.append(
1868
+ f"{k}({v['streak_fail']} 连败,挂起 {left // 60 + 1} 分钟)" if left
1869
+ else f"{k}({v['streak_fail']} 连败,已到期下次会重试)"
1870
+ )
1871
+ _head = (
1872
+ f"{okc - txt_only} 路有结果,共 {total} 条来源"
1873
+ if total
1874
+ else "0 条来源" + (f"({txt_only} 路只给了 AI 摘要,没有来源链接)" if txt_only else "")
1875
+ )
1876
+ if agg:
1877
+ _head += f",去重后 {len(agg)} 条(中文 {LANG_N['中']} · 英文 {LANG_N['英']} · 中英都命中 {LANG_N['中英']})"
1878
+ print(f"---\n**汇总**:{_head}"
1879
+ + (f";{zero} 路 0 命中" if zero else "")
1880
+ + (f";{len(failed)} 路失败({ '、'.join(failed) })" if failed else "")
1881
+ + (f";{len(skipped)} 路跳过({ '、'.join(skipped) })" if skipped else "")
1882
+ + (f";网站过滤去掉 {DOMAIN_DROPPED} 条" if DOMAIN_DROPPED else "") + "。\n")
1883
+ if weak:
1884
+ print(f"**通道健康**:{'、'.join(weak)}。\n")
1885
+ if need:
1886
+ print(f"**要你出手**:{'、'.join(need)}。\n")
1887
+ print("**下一步**:把上面冒出的人名/机构/版本号/术语回灌成第二轮(追深),"
1888
+ "再单独跑一轮反证(`<主题> 缺点/失败/不推荐/争议/vs 替代`)。"
1889
+ "要更全就 `fanout.sh \"<query>\" --deep`(追加 LangSearch / Exa / Firecrawl-Research)。")
1890
+
1891
+ # ---------- 历史记录 ----------
1892
+ # 网关和插件都靠它显示「最近查了什么、谁发起的、哪几路给了结果」。
1893
+ # 写失败不影响本轮输出:历史只是附加物。
1894
+ try:
1895
+ hist = pathlib.Path(os.path.expanduser(
1896
+ os.environ.get("D_REACH_HISTORY") or "~/.agent-reach/history.jsonl"))
1897
+ hist.parent.mkdir(parents=True, exist_ok=True)
1898
+ try:
1899
+ secs = round(time.time() - float(os.environ.get("D_REACH_T0") or 0), 1)
1900
+ except Exception:
1901
+ secs = 0.0
1902
+ rec = {
1903
+ "ts": datetime.now().astimezone().isoformat(timespec="seconds"),
1904
+ "query": Q,
1905
+ "zh": ZHQ if DUAL else "",
1906
+ "en": ENQ if DUAL else "",
1907
+ "on": ON or "",
1908
+ "deep": DEEP == "1",
1909
+ "source": os.environ.get("D_REACH_SOURCE") or "cli",
1910
+ "secs": secs,
1911
+ "ok": okc, "zero": zero, "fail": len(failed), "skip": len(skipped),
1912
+ "results": ROUND,
1913
+ }
1914
+ # 追加 + 裁剪必须在同一把锁里:并发轮次各读各的旧文件再整写会互相吞记录。
1915
+ with _file_lock(hist):
1916
+ try:
1917
+ keep = hist.read_text(encoding="utf-8").splitlines()
1918
+ except Exception:
1919
+ keep = []
1920
+ keep.append(json.dumps(rec, ensure_ascii=False))
1921
+ _atomic_write(hist, "\n".join(keep[-200:]) + "\n")
1922
+ # 每轮的完整 markdown 落一份,网关「点历史看详情」用
1923
+ # 文件名用 ts 前缀(精度到秒,与 rec.ts 对得上);同秒并发用 -2/-3 后缀,别覆盖
1924
+ rdir = hist.parent / "rounds"
1925
+ rdir.mkdir(parents=True, exist_ok=True)
1926
+ stamp = rec["ts"].replace("-", "").replace(":", "").replace("T", "-").split("+")[0]
1927
+ for _i in range(1, 1000):
1928
+ cand = rdir / (f"{stamp}.md" if _i == 1 else f"{stamp}-{_i}.md")
1929
+ try:
1930
+ with cand.open("x", encoding="utf-8") as _fh:
1931
+ _fh.write("".join(_OUT))
1932
+ break
1933
+ except FileExistsError:
1934
+ continue
1935
+ olds = sorted(rdir.glob("*.md"))
1936
+ for o in olds[:-30]:
1937
+ o.unlink(missing_ok=True)
1938
+ except Exception:
1939
+ pass
1940
+ PY
1941
+
1942
+ # 跑完自动校准官方额度(本地计数 ≠ 厂商剩余;校准结果写入 quota.json 的 _official 段)
1943
+ # 失败只写 stderr,不阻塞、不影响本轮结果。D_REACH_SKIP_PROBE=1 可关。
1944
+ [ "${D_REACH_SKIP_PROBE:-0}" = "1" ] || python3 "$DIR/quota_probe.py" --quiet 2>&1 >/dev/null | sed 's/^/ /' || true