@duanz/pi-d-reach 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -91,11 +91,24 @@ _TBS=""
91
91
  case "$RECENCY" in
92
92
  day) _TBS=qdr:d ;; week) _TBS=qdr:w ;; month) _TBS=qdr:m ;; year) _TBS=qdr:y ;;
93
93
  esac
94
- # include/exclude 域名列表(JSON 数组):本地过滤与 Tavily/Exa 原生参数共用同一份解析。
95
- _DOM_JSON=$(python3 - "$DOMAINS" <<'PYDOM'
96
- import json, sys
94
+ export D_REACH_RECENCY="$RECENCY" D_REACH_DOMAINS="$DOMAINS" D_REACH_TBS="$_TBS"
95
+
96
+ # 启动期一次性算完 5 件小事(原来各起一个 python3,每个 ~20–40ms):
97
+ # ① include/exclude 域名 JSON ② CJK 检测 ③ 路由默认清单(route_config.load_data)
98
+ # ④ 健康挂起清单 ⑤ 导出给子进程的域名过滤环境变量
99
+ # 合并成一个 python3 后 eval 回 bash;路由配置错误仍按原样 exit 2。
100
+ HEALTH="${D_REACH_HEALTH:-$HOME/.agent-reach/channels.json}"
101
+ _PRELUDE=$(python3 - "$DIR" "$0" "$DEFAULTS_FILE" "$BASE_CHANNELS" "$DEEP_CHANNELS" "$DOMAINS" "$ENQ" "$HEALTH" <<'PYPRELUDE'
102
+ import json, re, shlex, sys
103
+ from datetime import datetime, timezone
104
+ from pathlib import Path
105
+
106
+ DIR, SCRIPT, DEFAULTS, BASE, DEEP, DOMAINS, ENQ, HEALTH = sys.argv[1:9]
107
+ sys.path.insert(0, DIR)
108
+ import route_config
109
+
97
110
  inc, exc = [], []
98
- for raw in (sys.argv[1] or "").split(","):
111
+ for raw in (DOMAINS or "").split(","):
99
112
  d = raw.strip().lower()
100
113
  if not d:
101
114
  continue
@@ -106,19 +119,47 @@ for raw in (sys.argv[1] or "").split(","):
106
119
  if not d:
107
120
  continue
108
121
  (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
122
 
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#*|}"
123
+ cjk = "1" if re.search(r"[\u4e00-\u9fff\u3400-\u4dbf]", ENQ or "") else "0"
124
+
125
+ bad = []
126
+ try:
127
+ health_data = json.load(open(HEALTH, encoding="utf-8"))
128
+ except Exception:
129
+ health_data = {}
130
+ now = datetime.now(timezone.utc)
131
+ for key, val in (health_data or {}).items():
132
+ if not isinstance(val, dict):
133
+ continue
134
+ until = val.get("suspend_until")
135
+ if not until:
136
+ continue # 没有到期时间 = 该放行一次,让 mark 补上退避
137
+ try:
138
+ if datetime.fromisoformat(until) > now:
139
+ bad.append(key) # 还在挂起期内
140
+ except Exception:
141
+ continue # 时间戳坏了也放行,别把通道永久判死
142
+
143
+ try:
144
+ data = route_config.load_data(Path(SCRIPT), Path(DEFAULTS), BASE, DEEP)
145
+ except Exception as err:
146
+ prefix = "route-registry: " if isinstance(err, route_config.RegistryError) else "defaults: "
147
+ print(prefix + str(err), file=sys.stderr)
148
+ raise SystemExit(2)
149
+ if data["defaults_error"]:
150
+ print(data["defaults_error"], file=sys.stderr)
151
+ raise SystemExit(2)
152
+
153
+ print("D_REACH_INC_JSON=" + shlex.quote(json.dumps(inc)))
154
+ print("D_REACH_EXC_JSON=" + shlex.quote(json.dumps(exc)))
155
+ print("ENCJK=" + shlex.quote(cjk))
156
+ print("HEALTH_BAD=" + shlex.quote(" ".join(bad)))
157
+ print("DEFAULT_LISTS_BASE=" + shlex.quote(",".join(data["enabledByDefault"])))
158
+ print("DEFAULT_LISTS_DEEP=" + shlex.quote(",".join(data["enabledForDeep"])))
159
+ PYPRELUDE
160
+ ) || { echo "[fanout] 路由配置加载失败(原因见上一条);配置文件:$DEFAULTS_FILE" >&2; exit 2; }
161
+ eval "$_PRELUDE"
162
+ export D_REACH_INC_JSON D_REACH_EXC_JSON
122
163
 
123
164
  # --on 是本轮白名单;未知项剔除,若没有有效项则报错,避免意外跑全量。
124
165
  if [ "$ON_SET" = "1" ]; then
@@ -161,44 +202,31 @@ fi
161
202
 
162
203
  # CJK 检测:Crossref / OpenAlex 对中文 query 相关性差(c2 实测:中文 query 返回「水质监测站 /
163
204
  # 变电站 / 暖通」这类匹配到"配置/安装"字样的噪声)→ 中文 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
205
  # 英文通道真正吃的是 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)
206
+ # ENCJK 在启动期的 python prelude 里已算好,这里不再另起进程。
167
207
  # 双语:中英两版检索词不同 → 通用网页通道各查一遍(结果合并时标「中/英」)
168
208
  DUAL=0; [ "$ZHQ" != "$ENQ" ] && DUAL=1
169
209
  BILINGUAL=" tf serper tavily parallel youcom anysearch fcs brave exa langsearch "
210
+ # You.com 配了付费 key 时按次计费($5/1K)→ 只打一版,不做中英双查,避免一轮扣两次。
211
+ # 只有本轮真的会跑到 youcom 时才探 key,不给其他检索白加一次 load_key。
212
+ if [ "$DUAL" = "1" ]; then
213
+ _youcom_active=0
214
+ if [ "$ON_SET" = "1" ]; then
215
+ case ",$ON," in *",youcom,"*) _youcom_active=1 ;; esac
216
+ else
217
+ case ",$DEFAULT_LISTS_BASE," in *",youcom,"*) _youcom_active=1 ;; esac
218
+ fi
219
+ if [ "$_youcom_active" = "1" ] && sh "$DIR/load_key.sh" YOU_API_KEY https://you.com/platform >/dev/null 2>&1; then
220
+ BILINGUAL="${BILINGUAL/ youcom / }"
221
+ fi
222
+ fi
170
223
 
171
224
  TMP="$(mktemp -d)"
172
225
  trap 'rm -rf "$TMP"' EXIT
173
226
  # 被插件中止时:GNU timeout 默认另起进程组,已统一加 --foreground 留在本组,插件杀整组即可带走
174
- trap 'kill $(jobs -p) 2>/dev/null; exit 143' TERM INT
227
+ trap 'pids=$(jobs -p); [ -n "$pids" ] && kill $pids 2>/dev/null || true; exit 143' TERM INT
175
228
  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
- )
229
+ # HEALTH / HEALTH_BAD 已由上面的启动期 python prelude 统一算好(挂起只看未到期项)。
202
230
 
203
231
  # ---------- 记账闸门(两段式)----------
204
232
  # gate 只 check 不扣;请求成功后才 charge 真扣(失败由调用方 refund 或干脆不扣)。
@@ -221,6 +249,11 @@ gate() {
221
249
  # Serper = Google 结果,2,500 次一次性赠送(不是每月重置),之后 $1/1000
222
250
  # 实测 1.85s 回 5 条,比 BrightData 快 5 倍、便宜得多 → 本地生活/电商首选
223
251
  SP_KEY=$(sh "$DIR/load_key.sh" SERPER_API_KEY https://serper.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
252
+ elif [ "$svc" = "firecrawl" ]; then
253
+ # f_fcdev 已在同一 shell 里取过 key(_fck)时直接复用,不重复 fork load_key
254
+ if [ -z "${_fck:-}" ]; then
255
+ _fck=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
256
+ fi
224
257
  elif [ "$svc" = "firecrawl_search" ]; then
225
258
  # Firecrawl v2 Search uses the same key; f_fcs passes an estimated credit cost to this gate.
226
259
  FC_KEY=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || { echo "key" > "$TMP/skip.$svc"; return 1; }
@@ -251,7 +284,7 @@ want() {
251
284
  }
252
285
 
253
286
  # ---------- 免费免 Key 通道 ----------
254
- f_gh() { # GitHub 仓库搜索(免 key,10 次/分钟)
287
+ f_gh() { # GitHub 仓库搜索(免 key 10 次/分钟;有 GITHUB_TOKEN 30 次/分钟)
255
288
  # GitHub 只认英文且整句是 AND 匹配:「Home Assistant 3D floorplan dashboard card github」
256
289
  # 整句传过去 total_count=0。所以抽 ASCII 词、剔掉 github/the/for 这类噪声、取前 4 个。
257
290
  GQ=$(echo "$ENQ" | grep -oE '[A-Za-z0-9][A-Za-z0-9._+-]*' \
@@ -260,29 +293,48 @@ f_gh() { # GitHub 仓库搜索(免 key,10 次/分钟)
260
293
  # 抽不出英文词不是失败(中文 query 很正常)——写 skip 而不是空结果,
261
294
  # 否则每轮都会显示「GitHub:0 命中」并计入「1 路 0 命中」,看着像通道坏了。
262
295
  [ -z "$GQ" ] && { echo "no-english" > "$TMP/skip.gh"; return; }
296
+ _ght=$(sh "$DIR/load_key.sh" GITHUB_TOKEN https://github.com/settings/tokens 2>/dev/null) || _ght=""
297
+ local _gh_auth=()
298
+ [ -n "$_ght" ] && _gh_auth=(-H "Authorization: Bearer $_ght")
263
299
  curl -s --max-time 12 -G "https://api.github.com/search/repositories" \
264
- -H "Accept: application/vnd.github+json" \
300
+ -H "Accept: application/vnd.github+json" ${_gh_auth[@]+"${_gh_auth[@]}"} \
265
301
  --data-urlencode "q=$GQ" --data-urlencode "sort=stars" \
266
302
  --data-urlencode "order=desc" --data-urlencode "per_page=5" \
267
303
  -o "$TMP/gh.json" -w '%{http_code}' > "$TMP/gh.http" 2>/dev/null
304
+ if [ "$(cat "$TMP/gh.http" 2>/dev/null)" = "403" ]; then
305
+ if [ -z "$_ght" ] || grep -qiE "rate limit|secondary rate|abuse" "$TMP/gh.json" 2>/dev/null; then
306
+ echo "ratelimit" > "$TMP/gh.cls"
307
+ fi
308
+ fi
268
309
  }
269
310
 
270
311
  # 登录态社交通道按平台使用独立冷却;冷却期内跳过,减少连续请求触发风控。
271
312
  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"))
313
+ python3 - "${D_REACH_SOCIAL_LAST:-$HOME/.agent-reach/social-last.json}" "$1" "$2" <<'PY'
314
+ import fcntl, json, os, pathlib, sys, time
315
+ f = pathlib.Path(sys.argv[1])
316
+ p, cd = sys.argv[2], int(sys.argv[3])
317
+ f.parent.mkdir(parents=True, exist_ok=True)
318
+ lock_path = f.with_name(f.name + ".lock")
319
+ with open(lock_path, "a+") as lh:
320
+ fcntl.flock(lh, fcntl.LOCK_EX)
321
+ try:
322
+ try:
323
+ d = json.loads(f.read_text(encoding="utf-8"))
324
+ if not isinstance(d, dict):
325
+ d = {}
326
+ except Exception:
327
+ d = {}
328
+ left = cd - (time.time() - d.get(p, 0))
329
+ if left > 0:
330
+ print(int(left // 60) + 1)
331
+ sys.exit(1)
332
+ d[p] = int(time.time())
333
+ tmp = f.with_name(f"{f.name}.tmp.{os.getpid()}")
334
+ tmp.write_text(json.dumps(d), encoding="utf-8")
335
+ tmp.replace(f)
336
+ finally:
337
+ fcntl.flock(lh, fcntl.LOCK_UN)
286
338
  PY
287
339
  }
288
340
 
@@ -290,14 +342,28 @@ run_command_with_timeout() {
290
342
  local seconds="$1" output="$2" error="$3"
291
343
  shift 3
292
344
  python3 -c '
293
- import subprocess, sys
345
+ import os, signal, subprocess, sys
294
346
  seconds, output, error = float(sys.argv[1]), sys.argv[2], sys.argv[3]
295
347
  with open(output, "wb") as out, open(error, "wb") as err:
348
+ proc = subprocess.Popen(sys.argv[4:], stdout=out, stderr=err, start_new_session=True)
349
+ def _stop(signum, _frame):
350
+ try:
351
+ os.killpg(proc.pid, signal.SIGTERM)
352
+ except Exception:
353
+ proc.terminate()
354
+ sys.exit(128 + signum)
355
+ signal.signal(signal.SIGTERM, _stop)
356
+ signal.signal(signal.SIGINT, _stop)
296
357
  try:
297
- result = subprocess.run(sys.argv[4:], stdout=out, stderr=err, timeout=seconds)
358
+ rc = proc.wait(timeout=seconds)
298
359
  except subprocess.TimeoutExpired:
360
+ try:
361
+ os.killpg(proc.pid, signal.SIGKILL)
362
+ except Exception:
363
+ proc.kill()
364
+ proc.wait()
299
365
  sys.exit(124)
300
- sys.exit(result.returncode)
366
+ sys.exit(rc)
301
367
  ' "$seconds" "$output" "$error" "$@"
302
368
  }
303
369
 
@@ -404,6 +470,7 @@ f_fcdev() { # Firecrawl Developer Index(70M+ 一手源)
404
470
  # 没 key 才落 keyless 免费档,仍能跑但随时可能被限
405
471
  _fck=$(sh "$DIR/load_key.sh" FIRECRAWL_API_KEY https://firecrawl.dev 2>/dev/null) || _fck=""
406
472
  if [ -n "$_fck" ]; then
473
+ gate firecrawl || return 0
407
474
  curl -s --max-time 18 -G "https://api.firecrawl.dev/v2/search/developer" -H "Authorization: Bearer $_fck" \
408
475
  --data-urlencode "query=$ENQ" --data-urlencode "k=5" -o "$TMP/fcdev.json" -w '%{http_code}' > "$TMP/fcdev.http" 2>/dev/null
409
476
  [ "$(cat "$TMP/fcdev.http" 2>/dev/null)" = "200" ] && charge firecrawl
@@ -414,7 +481,7 @@ f_fcdev() { # Firecrawl Developer Index(70M+ 一手源)
414
481
  }
415
482
  f_qianfan() { # 百度千帆:生成式综合答案(非来源链接!)
416
483
  [ -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" \
484
+ run_command_with_timeout 30 "$TMP/qianfan.raw" "$TMP/qianfan.err" \
418
485
  python3 "$BAIDU/smart_search.py" search "$ZHQ"
419
486
  _qrc=$?
420
487
  sed -e '/^--- 配额状态 ---/,$d' -e '/^\[调度\]/d' "$TMP/qianfan.raw" > "$TMP/qianfan.txt" 2>/dev/null
@@ -457,20 +524,24 @@ PYQ
457
524
 
458
525
  f_tf() { # TinyFish Search(官方 hosted MCP,$0/次;JSON-RPC tools/call search)
459
526
  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
527
+ TF_KEY="$TF_KEY" timeout --foreground 25 python3 - "$ENQ" > "$TMP/tf.json" 2>"$TMP/tf.err" <<'PYEOF'
528
+ import json, os, sys, time, urllib.request
462
529
 
463
530
  q = sys.argv[1]
464
531
  key = os.environ["TF_KEY"]
465
532
  URL = "https://agent.tinyfish.ai/mcp"
533
+ deadline = time.monotonic() + 22.0
466
534
 
467
535
  def rpc(payload, session=None):
536
+ rem = deadline - time.monotonic()
537
+ if rem <= 0:
538
+ raise TimeoutError("TinyFish MCP 总超时(22s)")
468
539
  h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
469
540
  "X-API-Key": key}
470
541
  if session:
471
542
  h["Mcp-Session-Id"] = session
472
543
  req = urllib.request.Request(URL, data=json.dumps(payload).encode(), headers=h)
473
- with urllib.request.urlopen(req, timeout=30) as r:
544
+ with urllib.request.urlopen(req, timeout=max(1.0, min(15.0, rem))) as r:
474
545
  # hosted 强制:initialize 响应头下发 mcp-session-id,后续请求必须回带
475
546
  return r.headers.get("mcp-session-id"), r.read().decode("utf-8", "replace")
476
547
 
@@ -543,7 +614,7 @@ print(json.dumps(b))' "$ENQ")" \
543
614
  f_parallel() { # Parallel 免费 MCP(web_search):无 key 无账号,结果带 excerpts + 发布日期
544
615
  # 握手 3 步、每步 40s 上限,卡住时会把整轮拖到 2 分钟(2026-12-04 实测 126s)→ 外层统一 25s 封顶
545
616
  # 走 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 \
617
+ D_REACH_MCP_BUDGET=22 timeout --foreground 25 python3 "$DIR/mcp_call.py" https://mcp.parallel.ai/mcp web_search \
547
618
  "$(python3 -c 'import json,sys;q=sys.argv[1];print(json.dumps({"objective":q,"search_queries":[q]}))' "$ENQ")" \
548
619
  > "$TMP/parallel.json" 2>/dev/null
549
620
  # 失败时脚本打 MCP_ERROR 行(不是 JSON),标 skip 而不是让解析器报「无响应」
@@ -557,6 +628,7 @@ f_youcom() { # You.com 官方 Search API(X-API-Key),免费档 100 次/
557
628
  # 官方 REST 端点 2 秒就回,所以换成带 key 的 REST。没配 key 时退回旧的 MCP 档。
558
629
  _yck=$(sh "$DIR/load_key.sh" YOU_API_KEY https://you.com/platform 2>/dev/null) || _yck=""
559
630
  if [ -n "$_yck" ]; then
631
+ gate youcom || return 0
560
632
  curl -s --max-time 15 -G "https://api.you.com/v1/search" -H "X-API-Key: $_yck" \
561
633
  --data-urlencode "query=$ENQ" --data-urlencode "count=6" \
562
634
  -o "$TMP/youcom.json" -w '%{http_code}' > "$TMP/youcom.http" 2>/dev/null
@@ -564,7 +636,7 @@ f_youcom() { # You.com 官方 Search API(X-API-Key),免费档 100 次/
564
636
  return
565
637
  fi
566
638
  # 免 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 \
639
+ D_REACH_MCP_BUDGET=22 timeout --foreground 25 python3 "$DIR/mcp_call.py" "https://api.you.com/mcp?profile=free" you-search \
568
640
  "$(python3 -c 'import json,sys;print(json.dumps({"query":sys.argv[1],"count":6}))' "$ENQ")" \
569
641
  > "$TMP/youcom.json" 2>/dev/null
570
642
  if [ "$(head -c 11 "$TMP/youcom.json" 2>/dev/null)" = "MCP_ERROR: " ]; then
@@ -670,6 +742,7 @@ PY
670
742
  }
671
743
  f_wiki() { # Wikipedia REST summary:概念/人物/术语/地名,0.7s、完全免费、无限量
672
744
  gate wiki || return 0
745
+ local _wt0=$SECONDS
673
746
  # 「紫砂壶是什么」这种疑问句直接搜 opensearch 会返回空数组(没有条目叫这个名字),
674
747
  # 要先剥掉疑问词再搜,否则回退成整个 query 去取 summary 必然 404
675
748
  STRIP='import re,sys
@@ -679,7 +752,7 @@ q=re.sub(r"^(什么是|介绍一下|讲讲)", "", q)
679
752
  print(q.strip() or sys.argv[1])'
680
753
  BASEQ=$(python3 -c "$STRIP" "$ZHQ" 2>/dev/null || echo "$ZHQ")
681
754
  os_search() {
682
- curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
755
+ curl -s --max-time 8 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
683
756
  "https://zh.wikipedia.org/w/api.php" \
684
757
  --data-urlencode "action=opensearch" --data-urlencode "search=$1" \
685
758
  --data-urlencode "limit=1" --data-urlencode "format=json" \
@@ -691,7 +764,7 @@ except Exception: print("")' 2>/dev/null
691
764
  # 多词 query(「杭州 西湖 门票」)opensearch 常返空;再用 list=search 兜底取首条标题。
692
765
  # 两轮都空说明维基确实没有对应条目 —— 此时记 0 命中,不能留 404(会被误判成通道故障)。
693
766
  ls_search() {
694
- curl -s --max-time 12 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
767
+ curl -s --max-time 8 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
695
768
  "https://zh.wikipedia.org/w/api.php" \
696
769
  --data-urlencode "action=query" --data-urlencode "list=search" \
697
770
  --data-urlencode "srsearch=$1" --data-urlencode "srlimit=1" \
@@ -702,9 +775,9 @@ try:
702
775
  except Exception: print("")' 2>/dev/null
703
776
  }
704
777
  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")
778
+ [ -z "$TITLE" ] && [ $((SECONDS - _wt0)) -lt 20 ] && TITLE=$(os_search "$BASEQ")
779
+ [ -z "$TITLE" ] && [ $((SECONDS - _wt0)) -lt 20 ] && TITLE=$(ls_search "$BASEQ")
780
+ [ -z "$TITLE" ] && [ $((SECONDS - _wt0)) -lt 20 ] && TITLE=$(ls_search "$ZHQ")
708
781
  if [ -z "$TITLE" ]; then
709
782
  printf '{"type":"none"}' > "$TMP/wiki.json"
710
783
  printf '200' > "$TMP/wiki.http"
@@ -713,7 +786,7 @@ except Exception: print("")' 2>/dev/null
713
786
  # REST summary 端点自己会跟随繁简重定向(/w/api.php?redirects=1 对中文维基的繁简重定向不生效,
714
787
  # 「紫砂壶」会拿到「簡繁重定向」那段说明文字而不是正文)
715
788
  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" \
789
+ curl -s --max-time 8 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" "https://zh.wikipedia.org/api/rest_v1/page/summary/$ENC" \
717
790
  -o "$TMP/wiki.json" -w '%{http_code}' > "$TMP/wiki.http" 2>/dev/null
718
791
 
719
792
  # 中文条目常常只有一句话(实测「小米手环」64 字符、「RAG」174 字符,
@@ -721,8 +794,8 @@ except Exception: print("")' 2>/dev/null
721
794
  ZH_LEN=$(python3 -c 'import json,sys
722
795
  try: print(len(json.load(open(sys.argv[1])).get("extract") or ""))
723
796
  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 \
797
+ if [ "${ZH_LEN:-0}" -lt 300 ] && [ -n "$ENQ" ] && [ "$ENQ" != "$ZHQ" ] && [ $((SECONDS - _wt0)) -lt 20 ]; then
798
+ EN_TITLE=$(curl -s --max-time 8 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" -G \
726
799
  "https://en.wikipedia.org/w/api.php" \
727
800
  --data-urlencode "action=query" --data-urlencode "list=search" \
728
801
  --data-urlencode "srsearch=$ENQ" --data-urlencode "srlimit=1" \
@@ -731,9 +804,9 @@ except Exception: print(0)' "$TMP/wiki.json" 2>/dev/null || echo 0)
731
804
  try:
732
805
  d=json.load(sys.stdin); s=(d.get("query") or {}).get("search") or []; print(s[0]["title"] if s else "")
733
806
  except Exception: print("")' 2>/dev/null)
734
- if [ -n "$EN_TITLE" ]; then
807
+ if [ -n "$EN_TITLE" ] && [ $((SECONDS - _wt0)) -lt 20 ]; then
735
808
  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)" \
809
+ curl -s --max-time 8 -A "d-reach/1.0 (+https://github.com/DuanZGit/D-reach)" \
737
810
  "https://en.wikipedia.org/api/rest_v1/page/summary/$EN_ENC" -o "$TMP/wiki_en.json" 2>/dev/null
738
811
  python3 - "$TMP/wiki.json" "$TMP/wiki_en.json" <<'PYPICK'
739
812
  import json, sys
@@ -782,23 +855,48 @@ launch() { # $1 = 函数名;失败不拖垮整体
782
855
  if [ "$DUAL" = "1" ]; then
783
856
  # 通用网页通道:中文版、英文版各打一次,各写各的子目录,渲染时合并
784
857
  ( TMP="$TMP/zh"; Q="$ZHQ"; ENQ="$ZHQ"; "$fn" ) &
785
- ( TMP="$TMP/en"; Q="$ENQ"; "$fn" ) &
858
+ if [ "$key" = "brave" ]; then
859
+ # Brave 免费套餐限制 1 QPS:英文子进程错峰 1.1s 避免并发撞 429
860
+ ( sleep 1.1; TMP="$TMP/en"; Q="$ENQ"; "$fn" ) &
861
+ else
862
+ ( TMP="$TMP/en"; Q="$ENQ"; "$fn" ) &
863
+ fi
786
864
  return 0
787
865
  fi ;;
788
866
  esac
789
867
  ( "$fn" ) &
790
868
  }
869
+ # 本轮起始时间必须在 launch 之前确定(调用方已给就沿用,比如插件那边能算得更准)
870
+ [ -n "${D_REACH_T0:-}" ] || D_REACH_T0=$(date +%s)
871
+ export D_REACH_T0
791
872
  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
873
  # --on 显式点名时也要跑 deep 档通道,否则 deep 通道的结果会丢掉
793
874
  if [ "$DEEP" = 1 ] || [ -n "$ON" ]; then
794
875
  for fn in f_langsearch f_exa f_fcres; do launch "$fn"; done
795
876
  fi
796
- wait
877
+ wait_stragglers() {
878
+ # 慢尾巴软超时:等第一路返回后,其余还在跑的路再给 D_REACH_STRAGGLER_GRACE 秒(默认 15)。
879
+ # 还超时的那几路就放弃(本轮记为超时,下轮照常重跑,不会长期判死)。
880
+ # 正常路径几乎零开销:先 wait -n 拿第一路,再普通 wait 收尾;只有一个守护进程。
881
+ local grace="${D_REACH_STRAGGLER_GRACE:-15}"
882
+ case "$grace" in ''|*[!0-9]*) grace=15 ;; esac
883
+ if [ "$grace" = "0" ]; then wait; return 0; fi
884
+ wait -n 2>/dev/null || true # 第一路返回(同时也 reap 了它)
885
+ local -a rest=()
886
+ mapfile -t rest < <(jobs -rp 2>/dev/null)
887
+ if [ "${#rest[@]}" -eq 0 ]; then wait; return 0; fi
888
+ # 守护进程不能继承 stdout/stderr:否则调用方读管道要等它退出,等于白等满 grace
889
+ ( sleep "$grace"; for p in "${rest[@]}"; do kill "$p" 2>/dev/null; done ) >/dev/null 2>&1 &
890
+ local wd=$!
891
+ # 只等剩下的通道,不能裸 wait(会连守护进程一起等满 grace)
892
+ wait "${rest[@]}" 2>/dev/null || true
893
+ kill "$wd" 2>/dev/null || true
894
+ wait "$wd" 2>/dev/null || true
895
+ }
896
+
897
+ wait_stragglers
797
898
 
798
899
  # ---------- 渲染 ----------
799
- # 本轮起始时间:给 history.jsonl 算耗时用(调用方已给就沿用,比如插件那边能算得更准)
800
- [ -n "${D_REACH_T0:-}" ] || D_REACH_T0=$(date +%s)
801
- export D_REACH_T0
802
900
  # 脚本指纹:通道的「这路坏了/要登录」结论绑定它。改了脚本旧结论自动作废,
803
901
  # 不用手删 channels.json(照 Agent-Reach 的 fingerprint 失效机制)。
804
902
  D_REACH_FP=$(cat "$DIR/fanout.sh" "$DIR/route_config.py" | md5sum 2>/dev/null | cut -c1-8)
@@ -1400,7 +1498,7 @@ SECTIONS = [
1400
1498
  "⚠️ AI 浓缩回答、非来源链接 —— 关键结论必须另找一手源验证",
1401
1499
  lambda: load_text("qianfan.txt"), False),
1402
1500
  ("gh", "GitHub 仓库搜索(★ 排序,免 Key)", "免 Key 10 次/分钟;只认英文关键词", r_gh, False),
1403
- ("fcdev", "Firecrawl Developer Index(编程一手源 70M+)", "免 Key 不限量", r_fcdev, False),
1501
+ ("fcdev", "Firecrawl Developer Index(编程一手源 70M+)", "免 Key 不限量;有 key 走 key(1 credit/次,受 firecrawl 月度闸门)", r_fcdev, False),
1404
1502
  ("se", "StackExchange(报错排障)", "免 Key 不限量", r_se, False),
1405
1503
  ("hn", "Hacker News(深技术讨论)", "免 Key 不限量", r_hn, False),
1406
1504
  ("jj", "掘金(中文技术长尾)", "免 Key 不限量", r_jj, False),
@@ -1500,7 +1598,42 @@ def _atomic_write(path, text):
1500
1598
  tmpf.write_text(text, encoding="utf-8")
1501
1599
  tmpf.replace(path)
1502
1600
 
1503
- TOUCHED = set() # 本轮真正改过的通道键:保存时只合并这些,别整份覆盖别的进程的更新
1601
+ TOUCHED = set() # 本轮真正改过的通道键:保存时只合并这些,别整份覆盖别的进程的更新
1602
+ ROUND_OUTCOMES = {} # key -> (status, code),在文件锁内按磁盘最新状态重放,防止并发丢增量
1603
+
1604
+ def _apply_mark(store, key, status, code, stamp_iso, now_dt):
1605
+ if status == "not-configured":
1606
+ v = store.get(key)
1607
+ if isinstance(v, dict):
1608
+ v["streak_fail"] = 0
1609
+ for f in ("suspend_until", "suspend_secs", "code"):
1610
+ v.pop(f, None)
1611
+ if FP:
1612
+ v["fp"] = FP
1613
+ return
1614
+ v = store.setdefault(key, {"streak_fail": 0})
1615
+ if FP:
1616
+ v["fp"] = FP
1617
+ if status == "ok":
1618
+ v["streak_fail"] = 0
1619
+ v["last_ok"] = stamp_iso
1620
+ for f in ("suspend_until", "suspend_secs", "code"): # 成功即解除挂起
1621
+ v.pop(f, None)
1622
+ elif status == "fail":
1623
+ v["last_fail"] = stamp_iso
1624
+ code = code or "upstream"
1625
+ v["code"] = code
1626
+ if code in NEEDS:
1627
+ secs = CODE_TTL.get(code, NEEDS_TTL)
1628
+ else:
1629
+ v["streak_fail"] = v.get("streak_fail", 0) + 1
1630
+ n = v["streak_fail"]
1631
+ secs = BACKOFF[min(n - 3, len(BACKOFF) - 1)] if n >= 3 else 0
1632
+ if secs:
1633
+ v["suspend_until"] = (
1634
+ now_dt + timedelta(seconds=secs)
1635
+ ).isoformat(timespec="seconds")
1636
+ v["suspend_secs"] = secs
1504
1637
 
1505
1638
  def save_health(h):
1506
1639
  try:
@@ -1516,8 +1649,16 @@ def save_health(h):
1516
1649
  if isinstance(_v, dict) and _v.get("fp") and FP and _v["fp"] != FP:
1517
1650
  for _f in ("suspend_until", "suspend_secs", "code", "streak_fail"):
1518
1651
  _v.pop(_f, None)
1652
+ now_dt = datetime.now(timezone.utc)
1519
1653
  for _k in TOUCHED:
1520
- if _k in h:
1654
+ if _k in ROUND_OUTCOMES:
1655
+ _st, _cd = ROUND_OUTCOMES[_k]
1656
+ _apply_mark(disk, _k, _st, _cd, now_iso, now_dt)
1657
+ if _k in disk:
1658
+ h[_k] = disk[_k]
1659
+ else:
1660
+ h.pop(_k, None)
1661
+ elif _k in h:
1521
1662
  disk[_k] = h[_k]
1522
1663
  _atomic_write(HEALTH, json.dumps(disk, indent=2, ensure_ascii=False))
1523
1664
  except Exception:
@@ -1547,6 +1688,7 @@ NEEDS_TITLE = {
1547
1688
  "ratelimit": "限流中", "notfound": "端点失效", "setup": "依赖缺失",
1548
1689
  }
1549
1690
  NEEDS_TTL = 6 * 3600 # 确定性结论挂 6 小时,到期给一次自愈机会,不永久静默
1691
+ CODE_TTL = {"ratelimit": 120} # 限流窗口短退避 2 分钟(GitHub 免 Key 10次/分、Brave 1 QPS)
1550
1692
  FP = os.environ.get("D_REACH_FP") or ""
1551
1693
 
1552
1694
  # 脚本改过 → 旧的「这路坏了」结论可能已不成立,作废重测
@@ -1563,31 +1705,10 @@ def mark(key, status, code=None):
1563
1705
  确定性类(NEEDS)首次失败就挂 6 小时,并在输出里点名该做什么。
1564
1706
  到期自动重试一次:成功清零、失败继续升级。通道不会「跳过→不跑→永不成功」死锁。
1565
1707
  """
1566
- v = health.setdefault(key, {"streak_fail": 0})
1567
1708
  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
1709
+ ROUND.append({"key": key, "status": "skip" if status == "not-configured" else status})
1710
+ ROUND_OUTCOMES[key] = (status, code)
1711
+ _apply_mark(health, key, status, code, now_iso, datetime.now(timezone.utc))
1591
1712
 
1592
1713
  total, okc, zero = 0, 0, 0
1593
1714
  txt_only = 0 # 只给 AI 摘要、没有来源链接的路数(千帆),不能算「有结果」
@@ -1709,15 +1830,9 @@ for key, name, note, fn, deep_only, LANG, CUR_DUAL in _iter_sections():
1709
1830
  failed.append(KL); mark(key, "fail", "antibot")
1710
1831
  continue
1711
1832
  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
1833
  detail = load_text(key + ".txt") or "本机未配置此渠道。"
1719
1834
  print(f"### 🔇 {name} —— 未配置,已跳过且不计失败:{detail.strip()[:180]}\n")
1720
- skipped.append(KL); mark(key, "skip")
1835
+ skipped.append(KL); mark(key, "not-configured")
1721
1836
  continue
1722
1837
  if skip == "err":
1723
1838
  detail = load_text(key + ".txt") or ""
@@ -1737,7 +1852,9 @@ for key, name, note, fn, deep_only, LANG, CUR_DUAL in _iter_sections():
1737
1852
  if code and code not in ("200", "000") and (rows is None or rows == [] or isinstance(rows, tuple)):
1738
1853
  # 状态码本身就是结论:429 是限流(再打更糟)、401/403 是凭据、404 是端点没了,
1739
1854
  # 这三类都算确定性失败;5xx 才当上游抖动、靠退避自愈。
1740
- _cls = ("ratelimit" if code == "429" else
1855
+ _cls_hint = (load_text(key + ".cls") or "").strip()
1856
+ _cls = (_cls_hint if _cls_hint in NEEDS else
1857
+ "ratelimit" if code == "429" else
1741
1858
  "auth" if code in ("401", "403") else
1742
1859
  "notfound" if code == "404" else "upstream")
1743
1860
  print(f"### ⚠️ {name} —— HTTP {code}({NEEDS_TITLE.get(_cls, '上游异常')},不是「没搜到」)\n")
@@ -1773,17 +1890,27 @@ for key, name, note, fn, deep_only, LANG, CUR_DUAL in _iter_sections():
1773
1890
  print = _orig_print
1774
1891
  tmp = TMP0
1775
1892
  CUR_DUAL = False
1893
+ dual_partial = []
1776
1894
  for _k, _lst in _DUALMARK.items():
1777
1895
  _st = [x[0] for x in _lst]
1896
+ _fail_codes = [c for st, c in _lst if st == "fail"]
1778
1897
  if "ok" in _st:
1779
- _orig_mark(_k, "ok")
1898
+ if "ratelimit" in _fail_codes:
1899
+ _orig_mark(_k, "fail", "ratelimit")
1900
+ dual_partial.append(f"{_k}(单侧 429 限流,另一侧成功)")
1901
+ else:
1902
+ _orig_mark(_k, "ok")
1903
+ if _fail_codes:
1904
+ # 单边持续失败不能永远被「另一边成功」掩盖:再记一次 degraded 连败,
1905
+ # 连续 3 轮才进退避阶梯(成功轮的半边结果照常保留)。
1906
+ _orig_mark(_k, "fail", "degraded")
1907
+ dual_partial.append(f"{_k}(单侧失败:{','.join(c or 'upstream' for c in _fail_codes)})")
1780
1908
  elif "fail" in _st:
1781
1909
  _orig_mark(_k, "fail", next(c for st, c in _lst if st == "fail"))
1782
1910
  else:
1783
1911
  _orig_mark(_k, "skip")
1784
-
1785
1912
  def norm_url(u):
1786
- """URL 归一化:去 fragment / utm 类参数 / www 前缀 / 尾斜杠,用于跨源判重。"""
1913
+ """URL 归一化:只作跨源判重键(去 fragment / utm 类参数 / www 前缀 / 尾斜杠),不用于展示。"""
1787
1914
  try:
1788
1915
  from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
1789
1916
  s = urlsplit(str(u).strip())
@@ -1798,22 +1925,39 @@ def norm_url(u):
1798
1925
  except Exception:
1799
1926
  return str(u).strip().lower()
1800
1927
 
1928
+
1929
+ def display_url(u):
1930
+ """展示用 URL:保留原样,只剥跟踪参数(不动 www / 业务 ref 参数)。"""
1931
+ try:
1932
+ from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
1933
+ s = urlsplit(str(u).strip())
1934
+ q = [(k, v) for k, v in parse_qsl(s.query)
1935
+ if k.lower() not in ("utm_source", "utm_medium", "utm_campaign", "utm_term",
1936
+ "utm_content", "fbclid", "gclid")]
1937
+ return urlunsplit((s.scheme, s.netloc, s.path, urlencode(q), ""))
1938
+ except Exception:
1939
+ return str(u).strip()
1940
+
1801
1941
  agg = {}
1802
1942
  for key, name, t, u, x, rank, lang in MERGE_ROWS:
1803
1943
  nu = norm_url(u)
1804
1944
  d = agg.get(nu)
1805
1945
  if d is None:
1806
- # url 存归一化后的:判重靠它,展示也靠它(原 URL 常带 utm/rankingId 这类跟踪参数)
1807
- d = agg[nu] = {"title": t, "url": nu, "snippet": x or "", "hits": [], "langs": set()}
1946
+ # 判重靠 norm_url;展示保留原始 URL(只剥跟踪参数)
1947
+ d = agg[nu] = {"title": t, "url": display_url(u), "snippet": x or "", "hits": [], "langs": set()}
1808
1948
  d["hits"].append((key, rank, lang))
1809
1949
  d["langs"].add(lang)
1810
1950
  if not d["snippet"] and x:
1811
1951
  d["snippet"] = x
1812
1952
 
1813
1953
  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"])
1954
+ # 按去重后的独立通道数计票:同一网页中英双查各命中一次,只算 1 个来源通道
1955
+ uniq = {k for k, _r, _l in d["hits"]}
1956
+ d["sources"] = len(uniq)
1957
+ d["score"] = d["sources"] * sum(CH_W.get(k, DW) / (r + 1) for k, r, _l in d["hits"])
1958
+ # 中英都命中:内容在两套检索词下都相关,作为次级加分,不能当成多一个来源
1959
+ if len(d["langs"]) > 1:
1960
+ d["score"] *= 1.15
1817
1961
 
1818
1962
  def _ltag(d):
1819
1963
  return "中英" if len(d["langs"]) > 1 else next(iter(d["langs"]))
@@ -1821,7 +1965,7 @@ def _ltag(d):
1821
1965
  LANG_N = {"中": 0, "英": 0, "中英": 0}
1822
1966
  for d in agg.values():
1823
1967
  LANG_N[_ltag(d)] += 1
1824
- ranked = sorted(agg.values(), key=lambda d: (-d["score"], -len(d["hits"])))
1968
+ ranked = sorted(agg.values(), key=lambda d: (-d["score"], -d["sources"], -len(d["hits"])))
1825
1969
  MERGE_TOP = max(15, N * 3)
1826
1970
 
1827
1971
  if ranked:
@@ -1830,7 +1974,7 @@ if ranked:
1830
1974
  for d in ranked[:MERGE_TOP]:
1831
1975
  srcs = " · ".join(f"{k}#{r + 1}{'' if not DUAL else '·' + l}"
1832
1976
  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})"
1977
+ print(f"- 〔{_ltag(d)}〕**[{d['title']}]({d['url']})** — {d['sources']} 源({srcs})"
1834
1978
  + (f" — {d['snippet']}" if d["snippet"] else ""))
1835
1979
  print()
1836
1980
 
@@ -1860,14 +2004,11 @@ for k, v in health.items():
1860
2004
  left = _left(v)
1861
2005
  _code = v.get("code") or ""
1862
2006
  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
- )
2007
+ if left:
2008
+ # 确定性结论:只报还在挂起窗口内的;已到期的留待下次重试,不再刷屏警告
2009
+ need.append(f"{k}({NEEDS_TITLE.get(_code, '异常')},{left // 60 + 1} 分钟后重试)")
2010
+ elif v.get("streak_fail", 0) >= 3 and left:
2011
+ weak.append(f"{k}({v['streak_fail']} 连败,挂起 {left // 60 + 1} 分钟)")
1871
2012
  _head = (
1872
2013
  f"{okc - txt_only} 路有结果,共 {total} 条来源"
1873
2014
  if total
@@ -1878,6 +2019,7 @@ if agg:
1878
2019
  print(f"---\n**汇总**:{_head}"
1879
2020
  + (f";{zero} 路 0 命中" if zero else "")
1880
2021
  + (f";{len(failed)} 路失败({ '、'.join(failed) })" if failed else "")
2022
+ + (f";双语部分异常({'、'.join(dual_partial)})" if dual_partial else "")
1881
2023
  + (f";{len(skipped)} 路跳过({ '、'.join(skipped) })" if skipped else "")
1882
2024
  + (f";网站过滤去掉 {DOMAIN_DROPPED} 条" if DOMAIN_DROPPED else "") + "。\n")
1883
2025
  if weak:
@@ -1940,5 +2082,13 @@ except Exception:
1940
2082
  PY
1941
2083
 
1942
2084
  # 跑完自动校准官方额度(本地计数 ≠ 厂商剩余;校准结果写入 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
2085
+ # 改为后台跑:它只是校准,不该让本轮检索多等一次网络往返。
2086
+ # 输出重定向到日志文件(不能留给本轮 stdout/stderr:调用方要读到 EOF 才认为本轮结束)。
2087
+ # D_REACH_SKIP_PROBE=1 可关;失败只进日志,不影响本轮结果。
2088
+ if [ "${D_REACH_SKIP_PROBE:-0}" != "1" ]; then
2089
+ _probe_log="${D_REACH_PROBE_LOG:-$HOME/.agent-reach/quota-probe.log}"
2090
+ mkdir -p "$(dirname "$_probe_log")" 2>/dev/null
2091
+ python3 "$DIR/quota_probe.py" --quiet >>"$_probe_log" 2>&1 &
2092
+ # 脱离 job 表:否则上面的软超时/收尾会把这次校准当成本轮通道一起等
2093
+ disown 2>/dev/null || true
2094
+ fi