argo-search 2.9.9 → 2.10.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.
Files changed (90) hide show
  1. package/README.en.md +24 -21
  2. package/README.es.md +24 -21
  3. package/README.ja.md +23 -20
  4. package/README.ko.md +23 -20
  5. package/README.md +26 -21
  6. package/SKILL.md +5 -5
  7. package/backends/domain_profiles.json +76 -0
  8. package/backends/engine_registry.yaml +161 -5
  9. package/backends/quota_profiles.json +122 -2
  10. package/bin/argo +22 -1
  11. package/bin/argo.js +3 -3
  12. package/config.yaml +128 -21
  13. package/docs/ARGO_INTRO.md +4 -4
  14. package/docs/ENGINE_CATALOG.md +64 -44
  15. package/docs/MCP_SETUP.md +1 -1
  16. package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
  17. package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
  18. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
  19. package/engines/specs/clawhub.yaml +16 -15
  20. package/engines/specs/deepseek1024.yaml +46 -0
  21. package/engines/specs/dsh_hub.yaml +44 -0
  22. package/engines/specs/dshopen.yaml +32 -0
  23. package/engines/specs/explainx.yaml +32 -0
  24. package/engines/specs/gbfs_nyc.yaml +6 -1
  25. package/engines/specs/metaso_doc.yaml +49 -0
  26. package/engines/specs/metaso_image.yaml +65 -0
  27. package/engines/specs/metaso_podcast.yaml +60 -0
  28. package/engines/specs/metaso_scholar.yaml +57 -0
  29. package/engines/specs/metaso_video.yaml +62 -0
  30. package/engines/specs/ncpssd.yaml +41 -0
  31. package/engines/specs/sciverse.yaml +72 -0
  32. package/engines/specs/skills_sh.yaml +32 -0
  33. package/engines/specs/skillsmp.yaml +18 -16
  34. package/package.json +3 -2
  35. package/packages/dsh-plugin/README.md +3 -2
  36. package/packages/dsh-plugin/package.json +1 -1
  37. package/packages/dsh-plugin/test/size-gate.test.js +113 -0
  38. package/scripts/adaptive.py +41 -14
  39. package/scripts/article.py +6 -1
  40. package/scripts/article_meta.py +151 -2
  41. package/scripts/bench_general_pool.py +145 -0
  42. package/scripts/candidate_envelope.py +45 -4
  43. package/scripts/charset_decode.py +127 -0
  44. package/scripts/crawl.py +240 -74
  45. package/scripts/crawl_frontier.py +217 -0
  46. package/scripts/crawl_policy.py +174 -0
  47. package/scripts/engine_dispatch.py +22 -15
  48. package/scripts/engine_failure.py +15 -0
  49. package/scripts/engine_validate.py +8 -0
  50. package/scripts/engines.py +10 -0
  51. package/scripts/engines_base.py +12 -0
  52. package/scripts/engines_builders.py +14 -0
  53. package/scripts/engines_builders_dsh.py +330 -0
  54. package/scripts/engines_builders_skill.py +314 -0
  55. package/scripts/fetch_v3.py +37 -5
  56. package/scripts/gen_engine_catalog.py +218 -2
  57. package/scripts/general_pool.py +162 -0
  58. package/scripts/http_client.py +38 -42
  59. package/scripts/image_ops.py +4 -0
  60. package/scripts/install.ps1 +47 -19
  61. package/scripts/install.sh +45 -20
  62. package/scripts/matrix_search_eval.py +17 -1
  63. package/scripts/mcp_transport.py +1 -1
  64. package/scripts/ncpssd_bridge.py +123 -0
  65. package/scripts/paid_policy.py +109 -13
  66. package/scripts/pre-commit +19 -4
  67. package/scripts/query_signals.py +156 -3
  68. package/scripts/redskill/redskill_engine.py +29 -2
  69. package/scripts/release_check.py +209 -0
  70. package/scripts/retry_policy.py +22 -1
  71. package/scripts/robots_guard.py +26 -0
  72. package/scripts/route.py +11 -8
  73. package/scripts/route_cache.py +6 -0
  74. package/scripts/route_combo.py +37 -59
  75. package/scripts/route_domains.py +4 -1
  76. package/scripts/route_policy.py +6 -0
  77. package/scripts/search.py +9 -1
  78. package/scripts/search_cli.py +27 -0
  79. package/scripts/search_entry.py +9 -0
  80. package/scripts/search_output.py +29 -0
  81. package/scripts/search_pipeline.py +39 -1
  82. package/scripts/search_rank.py +1 -0
  83. package/scripts/social_engines/bilibili_engine.py +163 -26
  84. package/scripts/social_engines/reddit_engine.py +52 -51
  85. package/scripts/source_selection.py +302 -0
  86. package/scripts/video_fetch.py +303 -0
  87. package/scripts/video_meta.py +225 -0
  88. package/scripts/video_route.py +65 -0
  89. package/scripts/watch.py +123 -0
  90. package/scripts/local_engines.py +0 -321
@@ -53,6 +53,14 @@ if SCRIPT_DIR not in sys.path:
53
53
 
54
54
  # 渲染层(第二级A):TinyFish 直连渲染,独立模块以保持本文件聚焦主链调度
55
55
  import fetch_render_tinyfish as _render_tinyfish
56
+
57
+ # 解码统一入口(2026-10-26,charset 是只依赖 re 的叶子模块,顶层导入无负担):
58
+ # urllib 兜底车道与主链共享「头声明 > meta 嗅探 > 猜测链」,GBK 老站不再满屏 U+FFFD
59
+ try:
60
+ from charset_decode import decode_response_body as _decode_charset
61
+ except ImportError:
62
+ def _decode_charset(raw: bytes, _ct: str) -> str:
63
+ return raw.decode("utf-8", errors="replace")
56
64
  from clock_bridge import clock # 统一时钟(测试=虚拟;生产=monotonic)
57
65
  # 质量信号层(第三级):来源分类 / 页面类型 / 质量分 / 内容安全
58
66
  import fetch_quality as _quality
@@ -635,8 +643,8 @@ def _mobile_http_fetch(url: str, max_chars: int = 8000,
635
643
  req = urllib.request.Request(url, headers={"User-Agent": _MOBILE_UA})
636
644
  try:
637
645
  with open_url(req, timeout=timeout) as r:
638
- text = r.read().decode("utf-8", errors="replace")
639
- return _make_result(url, text, max_chars, "http_mobile")
646
+ return _make_result(url, _decode_charset(r.read(), r.headers.get("Content-Type", "")),
647
+ max_chars, "http_mobile")
640
648
  except Exception as e:
641
649
  return _make_result(url, "", 0, "http_mobile", ok=False,
642
650
  error=str(e)[:100])
@@ -703,8 +711,8 @@ def _http_fetch(url: str, max_chars: int = 8000, timeout: float = 8.0,
703
711
  })
704
712
  try:
705
713
  with open_url(req, timeout=timeout) as r:
706
- text = r.read().decode("utf-8", errors="replace")
707
- return _make_result(url, text, max_chars, "http")
714
+ return _make_result(url, _decode_charset(r.read(), r.headers.get("Content-Type", "")),
715
+ max_chars, "http")
708
716
  except Exception as e:
709
717
  return _make_result(url, "", 0, "http", ok=False, error=str(e)[:100])
710
718
 
@@ -1257,6 +1265,29 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1257
1265
  # URL 优化(Reddit 重写、追踪参数清理)
1258
1266
  url = _optimize_url(url)
1259
1267
 
1268
+ # 视频页走平台 API,不走 HTML 正文链:B 站/YouTube 的播放页正文不在
1269
+ # HTML 里(实测只抓到推荐位/页脚),通用链会把「0 字正文」当抓取失败。
1270
+ # need_html/actions/force_browser 是调用方的显式抓取意图,出现时让路。
1271
+ if not need_html and not actions and not force_browser:
1272
+ try:
1273
+ from video_fetch import fetch_video
1274
+ _video = fetch_video(url, max_chars=max_chars, timeout=timeout)
1275
+ except Exception:
1276
+ _video = None
1277
+ if _video is not None:
1278
+ # quality 评估会按正文长度重算 content_ok;视频的「有内容」判据
1279
+ # 是简介/字幕,不是长度,故先存声明值再恢复。
1280
+ _declared_ok = _video.get("content_ok")
1281
+ try:
1282
+ _video = _assess_quality(_video)
1283
+ except Exception:
1284
+ pass
1285
+ _video["content_ok"] = bool(_declared_ok)
1286
+ _video["page_type"] = "video"
1287
+ _video["source_type"] = "video"
1288
+ _video["cached"] = False
1289
+ return _strip_html_unless_needed(_video, need_html)
1290
+
1260
1291
  # robots.txt 尊重(合规检查):被禁路径直接拒绝,抓取失败放行
1261
1292
  try:
1262
1293
  from robots_guard import robots_blocked
@@ -1748,7 +1779,8 @@ if __name__ == "__main__":
1748
1779
  # 输出摘要
1749
1780
  summary = {k: r[k] for k in ("success", "fetch_method", "content_ok",
1750
1781
  "quality_score", "page_type", "source_type",
1751
- "is_official", "length", "url") if k in r}
1782
+ "is_official", "length", "url",
1783
+ "video_meta") if k in r}
1752
1784
  # 截断必须可见:只给 8,000 字却不说明「还有多少没给」,调用方会当全文用
1753
1785
  for k in ("truncated", "full_length", "full_text_path", "total_length",
1754
1786
  "offset", "full_source", "final_url",
@@ -7,16 +7,19 @@ config.yaml / engines/specs/*.yaml / quota_profiles.json / engine_env 四处,
7
7
  实际 14 个」「文档说 150+ 引擎、分不清收录与可用」)。这里的做法是:
8
8
  文档从**运行时同一批函数**取事实,`--check` 比对磁盘上的文档,
9
9
  `tests/test_engine_catalog.py` 把 `--check` 挂进检查——文档改不动也漂不掉。
10
+ 同一批数字还要露在五种语言的 README、徽章与包描述里,那几处也一起校正
11
+ (`sync_counts()`):源数、免密钥数、业务域数、MCP 工具数、版本号都只看真源。
10
12
 
11
13
  用法:
12
- python3 scripts/gen_engine_catalog.py # 生成/覆盖文档
13
- python3 scripts/gen_engine_catalog.py --check # 只校验,过期退出码 1
14
+ python3 scripts/gen_engine_catalog.py # 生成/覆盖文档并校正计数
15
+ python3 scripts/gen_engine_catalog.py --check # 只校验,过期或不一致退出码 1
14
16
  """
15
17
 
16
18
  from __future__ import annotations
17
19
 
18
20
  import argparse
19
21
  import json
22
+ import re
20
23
  import sys
21
24
  from collections import defaultdict
22
25
  from pathlib import Path
@@ -339,6 +342,210 @@ def _names(rows: list[dict[str, Any]]) -> str:
339
342
  return "、".join(f"`{r['engine_id']}`" for r in rows) if rows else "无"
340
343
 
341
344
 
345
+ # ── 对外计数:五语 README、徽章与包描述 ────────────────────────────────
346
+ # 源数、免密钥数、业务域数、MCP 工具数散落在五种语言与四个包描述里,
347
+ # 发布时靠手改必然漏:2026-10 的基线里中文写「覆盖 97 个业务领域」、
348
+ # 日文写「97 の業務ドメイン」、韩文还停在「272개의 검색 소스」、西班牙文
349
+ # 写「235 disponibles」,四处彼此矛盾。这里让文档生成器顺带把数字校正
350
+ # 到真源(catalog 的收录/开箱可用行、config 的域清单、mcp_tools 的工具表、
351
+ # SKILL.md 的版本号),`--check` 一并校验——改了引擎却忘了改 README 会红。
352
+ #
353
+ # 规则里只锚定「整句模板」,不做全局数字替换:发布说明里的历史数字
354
+ # (如「218 → 220 fuentes」「fuentes 237→253」)是事实,不能跟着变。
355
+ COUNT_RULES: dict[str, list[tuple[str, str]]] = {
356
+ "README.md": [
357
+ (r"badge/engines-(?P<total>\d+)-orange", "badge/engines-{total}-orange"),
358
+ (r"badge/version-(?P<version>[\d.]+)-informational", "badge/version-{version}-informational"),
359
+ (r"badge/MCP-(?P<tools>\d+)%20tools-purple", "badge/MCP-{tools}%20tools-purple"),
360
+ (r'(?P<pre>alt="Argo 阿尔戈:[^"]*?,)(?P<total>\d+)(?P<post> 个搜索源,)',
361
+ "{pre}{total}{post}"),
362
+ (r"背后连着 (?P<total>\d+) 个搜索源,覆盖 (?P<domains>\d+) 个业务领域",
363
+ "背后连着 {total} 个搜索源,覆盖 {domains} 个业务领域"),
364
+ (r"另有 1 个 `wide_research` 并行研究和 (?P<tools>\d+) 个 MCP 工具按需开启",
365
+ "另有 1 个 `wide_research` 并行研究和 {tools} 个 MCP 工具按需开启"),
366
+ # 这句原本写死「其余 271 个源不受影响」,可它说的其实是「缺 key 时哪些源
367
+ # 停用」,算不出发版数减几——去掉数字,只说事实(其余源不受影响)。
368
+ (r"其余 (?P<n>\d+) 个源不受影响", "其余源不受影响"),
369
+ (r"\*\*(?P<total>\d+) 个源,(?P<usable>\d+) 个免密钥开箱可用。\*\*",
370
+ "**{total} 个源,{usable} 个免密钥开箱可用。**"),
371
+ (r"目前 (?P<total>\d+) 个源((?P<usable>\d+) 个免密钥开箱可用)、(?P<domains>\d+) 个业务域",
372
+ "目前 {total} 个源({usable} 个免密钥开箱可用)、{domains} 个业务域"),
373
+ (r"((?P<usable>\d+) 个免配置源)", "({usable} 个免配置源)"),
374
+ (r"在 v2\.9\.x 系列里全部落地:(?P<total>\d+) 个源、(?P<domains>\d+) 个领域、"
375
+ r"(?P<usable>\d+) 个免配置开箱",
376
+ "在 v2.9.x 系列里全部落地:{total} 个源、{domains} 个领域、{usable} 个免配置开箱"),
377
+ (r"当前配置 \*\*(?P<total>\d+)\*\* 个源(\*\*(?P<usable>\d+)\*\* 个免密钥开箱可用)、\*\*(?P<domains>\d+)\*\* 个业务域",
378
+ "当前配置 **{total}** 个源(**{usable}** 个免密钥开箱可用)、**{domains}** 个业务域"),
379
+ (r"搜索、抓取、核验、本机文件检索走同一条管线,(?P<tools>\d+) 个 MCP 工具和 CLI 命令一一对应",
380
+ "搜索、抓取、核验、本机文件检索走同一条管线,{tools} 个 MCP 工具和 CLI 命令一一对应"),
381
+ ],
382
+ "README.en.md": [
383
+ (r"badge/engines-(?P<total>\d+)-orange", "badge/engines-{total}-orange"),
384
+ (r"badge/version-(?P<version>[\d.]+)-informational", "badge/version-{version}-informational"),
385
+ (r"badge/MCP-(?P<tools>\d+)%20tools-purple", "badge/MCP-{tools}%20tools-purple"),
386
+ (r'(?P<pre>alt="Argo: search and deep research for agents — )(?P<total>\d+)(?P<post> search sources,)',
387
+ "{pre}{total}{post}"),
388
+ (r"It connects to (?P<total>\d+) search sources across (?P<domains>\d+) business domains",
389
+ "It connects to {total} search sources across {domains} business domains"),
390
+ (r"and (?P<tools>\d+) MCP tools you can enable on demand",
391
+ "and {tools} MCP tools you can enable on demand"),
392
+ (r"and the other (?P<n>\d+) sources are unaffected", "and the other sources are unaffected"),
393
+ (r"\*\*(?P<total>\d+) sources, (?P<usable>\d+) keyless and ready out of the box\.\*\*",
394
+ "**{total} sources, {usable} keyless and ready out of the box.**"),
395
+ (r"\((?P<usable>\d+) keyless sources\)", "({usable} keyless sources)"),
396
+ (r"All five are already shipped across the v2\.9\.x line: (?P<total>\d+) sources, "
397
+ r"(?P<domains>\d+) domains, (?P<usable>\d+) keyless out of the box",
398
+ "All five are already shipped across the v2.9.x line: {total} sources, "
399
+ "{domains} domains, {usable} keyless out of the box"),
400
+ (r"the (?P<tools>\d+) MCP tools map one-to-one onto CLI commands",
401
+ "the {tools} MCP tools map one-to-one onto CLI commands"),
402
+ (r"\*\*(?P<total>\d+) sources \((?P<usable>\d+) usable with no key\), "
403
+ r"(?P<domains>\d+) domains\*\*",
404
+ "**{total} sources ({usable} usable with no key), {domains} domains**"),
405
+ (r"Config currently has \*\*(?P<total>\d+)\*\* sources \(\*\*(?P<usable>\d+)\*\* usable "
406
+ r"with no key\) and \*\*(?P<domains>\d+)\*\* domains",
407
+ "Config currently has **{total}** sources (**{usable}** usable with no key) "
408
+ "and **{domains}** domains"),
409
+ ],
410
+ "README.es.md": [
411
+ (r"badge/engines-(?P<total>\d+)-orange", "badge/engines-{total}-orange"),
412
+ (r"badge/version-(?P<version>[\d.]+)-informational", "badge/version-{version}-informational"),
413
+ (r"badge/MCP-(?P<tools>\d+)%20tools-purple", "badge/MCP-{tools}%20tools-purple"),
414
+ (r"(?P<pre>alt=\"Argo: búsqueda e investigación profunda para agentes, )(?P<total>\d+)(?P<post> fuentes de búsqueda,)",
415
+ "{pre}{total}{post}"),
416
+ (r"Detrás tiene (?P<total>\d+) fuentes de búsqueda que cubren (?P<domains>\d+) dominios de negocio",
417
+ "Detrás tiene {total} fuentes de búsqueda que cubren {domains} dominios de negocio"),
418
+ (r"Además hay 1 `wide_research` de investigación en paralelo y (?P<tools>\d+) herramientas MCP",
419
+ "Además hay 1 `wide_research` de investigación en paralelo y {tools} herramientas MCP"),
420
+ (r"y las otras (?P<n>\d+) fuentes no se ven afectadas", "y las demás fuentes no se ven afectadas"),
421
+ (r"\*\*(?P<total>\d+) fuentes, (?P<usable>\d+) disponibles sin clave desde el primer momento\.\*\*",
422
+ "**{total} fuentes, {usable} disponibles sin clave desde el primer momento.**"),
423
+ (r"Los cinco puntos ya están implementados en la serie v2\.9\.x: "
424
+ r"(?P<total>\d+) fuentes, (?P<domains>\d+) dominios, (?P<usable>\d+) sin clave",
425
+ "Los cinco puntos ya están implementados en la serie v2.9.x: "
426
+ "{total} fuentes, {domains} dominios, {usable} sin clave"),
427
+ (r"(?P<tools>\d+) herramientas MCP se corresponden una a una",
428
+ "{tools} herramientas MCP se corresponden una a una"),
429
+ (r"docs/ENGINE_CATALOG\.md: (?P<total>\d+) fuentes, (?P<usable>\d+) sin clave, (?P<domains>\d+) dominios",
430
+ "docs/ENGINE_CATALOG.md: {total} fuentes, {usable} sin clave, {domains} dominios"),
431
+ (r"La config tiene ahora \*\*(?P<total>\d+)\*\* fuentes \(\*\*(?P<usable>\d+)\*\* sin clave\) "
432
+ r"y \*\*(?P<domains>\d+)\*\* dominios",
433
+ "La config tiene ahora **{total}** fuentes (**{usable}** sin clave) y **{domains}** dominios"),
434
+ ],
435
+ "README.ja.md": [
436
+ (r"badge/engines-(?P<total>\d+)-orange", "badge/engines-{total}-orange"),
437
+ (r"badge/version-(?P<version>[\d.]+)-informational", "badge/version-{version}-informational"),
438
+ (r"badge/MCP-(?P<tools>\d+)%20tools-purple", "badge/MCP-{tools}%20tools-purple"),
439
+ (r"(?P<pre>alt=\"Argo アルゴ:[^\"]*?、)(?P<total>\d+)(?P<post> の検索ソース、)", "{pre}{total}{post}"),
440
+ (r"背後には (?P<total>\d+) の検索ソースがあり、(?P<domains>\d+) の業務ドメイン",
441
+ "背後には {total} の検索ソースがあり、{domains} の業務ドメイン"),
442
+ (r"(?P<tools>\d+) 個の MCP ツール", "{tools} 個の MCP ツール"),
443
+ (r"\*\*(?P<total>\d+) のソース、うち (?P<usable>\d+) はキー不要ですぐ使える。\*\*",
444
+ "**{total} のソース、うち {usable} はキー不要ですぐ使える。**"),
445
+ (r"((?P<usable>\d+) ソースが無設定)", "({usable} ソースが無設定)"),
446
+ (r"v2\.9\.x 系で全て実装済み:(?P<total>\d+) ソース / (?P<domains>\d+) ドメイン / (?P<usable>\d+) 無設定",
447
+ "v2.9.x 系で全て実装済み:{total} ソース / {domains} ドメイン / {usable} 無設定"),
448
+ (r"ENGINE_CATALOG\.md に清单されている:(?P<total>\d+) ソース、(?P<usable>\d+) 無設定、"
449
+ r"(?P<domains>\d+) ドメイン",
450
+ "ENGINE_CATALOG.md に清单されている:{total} ソース、{usable} 無設定、{domains} ドメイン"),
451
+ (r"設定上は \*\*(?P<total>\d+)\*\* ソース(うち \*\*(?P<usable>\d+)\*\* はキー不要)、"
452
+ r"\*\*(?P<domains>\d+)\*\* ドメイン",
453
+ "設定上は **{total}** ソース(うち **{usable}** はキー不要)、**{domains}** ドメイン"),
454
+ ],
455
+ "README.ko.md": [
456
+ (r"badge/engines-(?P<total>\d+)-orange", "badge/engines-{total}-orange"),
457
+ (r"badge/version-(?P<version>[\d.]+)-informational", "badge/version-{version}-informational"),
458
+ (r"badge/MCP-(?P<tools>\d+)%20tools-purple", "badge/MCP-{tools}%20tools-purple"),
459
+ (r"뒤에는 (?P<total>\d+)개의 검색 소스가 있고 (?P<domains>\d+)개 업무 영역",
460
+ "뒤에는 {total}개의 검색 소스가 있고 {domains}개 업무 영역"),
461
+ (r"(?P<tools>\d+)개의 MCP 도구", "{tools}개의 MCP 도구"),
462
+ (r"\*\*(?P<total>\d+)개 소스, 그중 (?P<usable>\d+)개는 키 없이 바로 사용\.\*\*",
463
+ "**{total}개 소스, 그중 {usable}개는 키 없이 바로 사용.**"),
464
+ (r"\(무설정 (?P<usable>\d+)개\)", "(무설정 {usable}개)"),
465
+ (r"v2\.9\.x 계열에서 모두 구현되었습니다: (?P<total>\d+) 소스 / (?P<domains>\d+) 도메인 / "
466
+ r"(?P<usable>\d+) 무설정",
467
+ "v2.9.x 계열에서 모두 구현되었습니다: {total} 소스 / {domains} 도메인 / {usable} 무설정"),
468
+ (r"ENGINE_CATALOG\.md에 있다: (?P<total>\d+) 소스, (?P<usable>\d+) 무설정, (?P<domains>\d+) 도메인",
469
+ "ENGINE_CATALOG.md에 있다: {total} 소스, {usable} 무설정, {domains} 도메인"),
470
+ (r"설정에는 현재 \*\*(?P<total>\d+)\*\* 소스\(\*\*(?P<usable>\d+)\*\*개는 키 불필요\)와 "
471
+ r"\*\*(?P<domains>\d+)\*\* 도메인",
472
+ "설정에는 현재 **{total}** 소스(**{usable}**개는 키 불필요)와 **{domains}** 도메인"),
473
+ ],
474
+ "SKILL.md": [
475
+ (r"收录 (?P<total>\d+) 个源、(?P<usable>\d+) 免密钥", "收录 {total} 个源、{usable} 免密钥"),
476
+ ],
477
+ "package.json": [
478
+ (r"(?P<total>\d+) 个源((?P<usable>\d+) 个免密钥开箱可用)",
479
+ "{total} 个源({usable} 个免密钥开箱可用)"),
480
+ (r"(?P<tools>\d+) 个 MCP 工具(与 CLI 能力面对齐)", "{tools} 个 MCP 工具(与 CLI 能力面对齐)"),
481
+ ],
482
+ "packages/marketplace.json": [
483
+ (r"over (?P<total>\d+) sources", "over {total} sources"),
484
+ (r"((?P<total>\d+) 源)", "({total} 源)"),
485
+ ],
486
+ "packages/argo-zcode/.zcode-plugin/plugin.json": [
487
+ (r"over (?P<total>\d+) sources \((?P<usable>\d+) keyless\)",
488
+ "over {total} sources ({usable} keyless)"),
489
+ (r"over (?P<total>\d+) sources(?! \()", "over {total} sources"),
490
+ (r"(?P<total>\d+) 个源、(?P<usable>\d+) 个免密钥可用", "{total} 个源、{usable} 个免密钥可用"),
491
+ ],
492
+ "packages/argo-zcode/skills/argo/SKILL.md": [
493
+ (r"收录 (?P<total>\d+) 个源、(?P<usable>\d+) 个免密钥可用",
494
+ "收录 {total} 个源、{usable} 个免密钥可用"),
495
+ (r"((?P<total>\d+) 源、(?P<usable>\d+) 免密钥)", "({total} 源、{usable} 免密钥)"),
496
+ ],
497
+ "server.json": [
498
+ (r'"description": "Metasearch (?P<total>\d+) sources',
499
+ '"description": "Metasearch {total} sources'),
500
+ ],
501
+ }
502
+
503
+
504
+ def _count_truth() -> dict[str, str]:
505
+ """对外计数的唯一真源:catalog 分档 + config 域表 + mcp_tools 工具表 + 版本号。"""
506
+ from config import get_domains, load_config # noqa: PLC0415 (与运行时同源)
507
+ from mcp_tools import TOOLS # noqa: PLC0415
508
+
509
+ rows = _collect()["rows"]
510
+ total = len(rows)
511
+ # 与 render() 里「开箱可用」同一口径:enabled 且不挑密钥、不挑后端工具。
512
+ usable = sum(1 for row in rows if row["enabled"] and not row["required_env"] and not row["requires"])
513
+ version = re.search(r"^version:\s*(\S+)", (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8"), re.M)
514
+ if version is None:
515
+ raise SystemExit("SKILL.md 缺 version 行,无法同步徽章")
516
+ return {
517
+ "total": str(total),
518
+ "usable": str(usable),
519
+ "domains": str(len(get_domains(load_config()))),
520
+ "tools": str(len(TOOLS)),
521
+ "version": version.group(1),
522
+ }
523
+
524
+
525
+ def sync_counts(write: bool) -> list[str]:
526
+ """把 README / 徽章 / 包描述里的计数校正到真源,返回有差异的文件。"""
527
+ truth = _count_truth()
528
+ stale: list[str] = []
529
+ for rel, rules in COUNT_RULES.items():
530
+ path = SKILL_DIR / rel
531
+ if not path.exists():
532
+ continue
533
+ text = path.read_text(encoding="utf-8")
534
+ fixed = text
535
+ for pattern, template in rules:
536
+ # 具名组只提供 pre/post 这类字面片段,数字一律用真源里的 total/usable…
537
+ fixed = re.sub(
538
+ pattern,
539
+ lambda m, t=template: t.format(**{**m.groupdict(), **truth}),
540
+ fixed,
541
+ )
542
+ if fixed != text:
543
+ stale.append(rel)
544
+ if write:
545
+ path.write_text(fixed, encoding="utf-8", newline="\n")
546
+ return stale
547
+
548
+
342
549
  def main() -> int:
343
550
  ap = argparse.ArgumentParser(description="生成搜索源使用文档")
344
551
  ap.add_argument("--check", action="store_true", help="只校验文档是否过期")
@@ -352,11 +559,20 @@ def main() -> int:
352
559
  print("❌ 搜索源文档已过期,重新生成:python3 scripts/gen_engine_catalog.py",
353
560
  file=sys.stderr)
354
561
  return 1
562
+ stale = sync_counts(write=False)
563
+ if stale:
564
+ print("❌ 以下文件的计数与引擎真源不一致:", file=sys.stderr)
565
+ for rel in stale:
566
+ print(f" - {rel}", file=sys.stderr)
567
+ print(" 重新生成:python3 scripts/gen_engine_catalog.py", file=sys.stderr)
568
+ return 1
355
569
  print(f"✅ 搜索源文档与当前引擎声明一致({len(_collect()['rows'])} 个源)")
356
570
  return 0
357
571
  DOC_PATH.parent.mkdir(parents=True, exist_ok=True)
358
572
  DOC_PATH.write_text(text, encoding="utf-8")
359
573
  print(f"已生成 {DOC_PATH.relative_to(SKILL_DIR)}({len(_collect()['rows'])} 个源)")
574
+ for rel in sync_counts(write=True):
575
+ print(f"已校正计数:{rel}")
360
576
  return 0
361
577
 
362
578
 
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env python3
2
+ """general_pool.py — 通用候选池的顺序策略(单一入口)。
3
+
4
+ ## 为什么独立成模块
5
+
6
+ 通用源顺序此前有两个真源:`route_combo._general_fallback` 读静态元组,
7
+ `route_combo.tfidf_lead_combo` 写死 anysearch/octen。同一个「无匹配域」的
8
+ 查询走哪条分支,就换了源——2026-10-26 实测:走 TF-IDF 分支的查询永远
9
+ 用不到 tavily_free/yuanbao,即使它们更快更准。
10
+
11
+ 顺序策略(池子从哪来、逃生门、按什么排序)统一在这里;route_combo 只留
12
+ `tfidf_lead_combo` 的组合逻辑,避免它继续长过 1000 行硬上限。
13
+
14
+ ## 两道逃生门(逐位复现旧行为)
15
+
16
+ · ARGO_GENERAL_FALLBACK_STATIC=1:完全回到 engine_policy 静态元组;
17
+ · ARGO_GENERAL_FALLBACK_LEAD=<engine> / LEGACY=1:旧语义,且钉住顺序。
18
+
19
+ 钉住时不再排序——A/B 需要固定臂,线上回滚也需要可预期。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ from typing import Callable
26
+
27
+ # 静态兜底常量不可用时的最后一行(与 engine_policy 的历史默认同值)。
28
+ _STATIC_FALLBACK = ("anysearch", "octen", "local_bing")
29
+
30
+
31
+ def configured_general_pool() -> list[str] | None:
32
+ """通用候选池(config.yaml 的 general_fallback.engines)。
33
+
34
+ 只声明「谁有资格进池」,不声明优先级——优先级由 source_selection 按
35
+ 实测先验 × 自适应分排序。配置缺失时回落到 engine_policy 常量,保证
36
+ 旧部署行为可预期。
37
+ """
38
+ try:
39
+ from config import load_config
40
+ pool = (load_config().get("general_fallback") or {}).get("engines")
41
+ if isinstance(pool, list):
42
+ clean = [str(e).strip() for e in pool if str(e).strip()]
43
+ if clean:
44
+ return clean
45
+ except Exception:
46
+ return None
47
+ return None
48
+
49
+
50
+ def _static_fallback() -> tuple[str, ...]:
51
+ try:
52
+ from engine_policy import GENERAL_FREE_FALLBACK
53
+ return tuple(GENERAL_FREE_FALLBACK)
54
+ except ImportError:
55
+ return _STATIC_FALLBACK
56
+
57
+
58
+ def general_kwargs(features: dict | None, mode: str, depth: str,
59
+ context: str) -> dict[str, str]:
60
+ """通用选源需要的上下文参数(路由三条分支共用一个样板)。
61
+
62
+ 选源按用途(日常/研究)与语言排序;把四个参数散在各调用点复制,既容易
63
+ 漏传,也把 route.py 顶过行数门禁。放在池模块,因为它只服务选源。
64
+ """
65
+ return {
66
+ "mode": mode, "depth": depth, "context": context,
67
+ "lang": str((features or {}).get("primary_lang") or ""),
68
+ }
69
+
70
+
71
+ def _env_flag(name: str, default: bool = False) -> bool:
72
+ try:
73
+ from engine_env import env_flag
74
+ return bool(env_flag(name, default=default))
75
+ except Exception:
76
+ return default
77
+
78
+
79
+ def _get_env(name: str, default: str = "") -> str:
80
+ """与 route_cache 指纹同源地读旋钮(含 ~/.config/argo/env 文件)。
81
+
82
+ 只读 os.environ 会让写在 env 文件里的 LEAD/STATIC 被指纹看见、却不被
83
+ 选源层看见——开关显示已设置,行为没变,A/B 两臂还会串味。
84
+ """
85
+ try:
86
+ from engine_env import get_env
87
+ return str(get_env(name, default) or "")
88
+ except Exception:
89
+ return os.environ.get(name, default)
90
+
91
+
92
+ def general_order() -> tuple[list[str], bool]:
93
+ """原始候选顺序 + 是否被逃生门钉住(排序在 ranked_general)。"""
94
+ static_fallback = _static_fallback()
95
+ static = _env_flag("ARGO_GENERAL_FALLBACK_STATIC")
96
+ order = (list(static_fallback) if static
97
+ else (configured_general_pool() or list(static_fallback)))
98
+
99
+ # 领队覆盖(2026-10-21):A/B 与线上回退都走这里,避免为了复测改常量。
100
+ # 只有**生效的**覆盖才钉住顺序;拼错引擎名不得让动态排序静默失效。
101
+ lead_override = _get_env("ARGO_GENERAL_FALLBACK_LEAD").strip()
102
+ pinned = bool(lead_override and lead_override in order)
103
+ if pinned:
104
+ order = [lead_override] + [e for e in order if e != lead_override]
105
+ # 逃生开关:A/B 与线上回退都走这条,避免为了复测改常量。
106
+ if _env_flag("ARGO_GENERAL_FALLBACK_LEGACY"):
107
+ order = [e for e in order if e != "octen"]
108
+ pinned = True
109
+ return order, (static or pinned)
110
+
111
+
112
+ def ranked_general(enabled: set[str], *, mode: str = "auto",
113
+ depth: str = "fast", context: str = "search",
114
+ lang: str = "",
115
+ score_fn: Callable[[str, str, str, str],
116
+ tuple[float, int]] | None = None
117
+ ) -> list[str]:
118
+ """通用候选池的当前排序(`_general_fallback` 与 `tfidf_lead_combo` 共用)。
119
+
120
+ `score_fn` 仅供测试注入假学习器;生产路径留空,走真实 adaptive.db。
121
+ """
122
+ order, pinned = general_order()
123
+ if pinned:
124
+ return [e for e in order if e in enabled]
125
+ try:
126
+ from source_selection import rank_general_candidates
127
+ ranked = rank_general_candidates(
128
+ order, enabled=enabled, mode=mode, depth=depth,
129
+ context=context, lang=lang, score_fn=score_fn)
130
+ if ranked:
131
+ return ranked
132
+ except Exception as exc:
133
+ # 排序是加速器不是依赖:失败退回池顺序,但必须留痕——静默回退会让
134
+ # 「新排序好像没生效」成为线上唯一症状(与 engine_dispatch 的反爬
135
+ # 收紧同一条纪律)。
136
+ import logging
137
+ logging.getLogger("unified_search").debug(
138
+ "通用池排序失败,按池顺序回退: %r", exc)
139
+ # 配置池与本轮 enabled 无交集(手工 enabled 集合 / 极端降级)或排序失败:
140
+ # 退回**池**顺序,不再用先验表当成员白名单——那会把 config 明确排除的
141
+ # local_baidu/wikipedia 重新放回来,也会漏掉未进先验表的新源。
142
+ return [e for e in order if e in enabled]
143
+
144
+
145
+ def general_fallback(enabled: set[str], *, mode: str = "auto",
146
+ depth: str = "fast", context: str = "search",
147
+ lang: str = "") -> list[str]:
148
+ """通用候选池排序 + local_search 殿后。
149
+
150
+ local_search 殿后(2026-10-15 实测定案):日常档 combo_budget=2,它一旦
151
+ 占住前排,展开出的本地子引擎必被截断、只剩聚合器独跑(1059 条查询里
152
+ 独跑 109 次、中位 2.9s、占墙钟 369s,82% 是纯英文技术查询)。
153
+ """
154
+ order = ranked_general(
155
+ enabled, mode=mode, depth=depth, context=context, lang=lang)
156
+ if not order:
157
+ # 最后一道 fail-open:池子与本轮 enabled 完全无交集时,任取两个
158
+ # 可用源也比空 combo 好(执行层至少能暴露真实错误)。
159
+ order = sorted(enabled)[:2] if enabled else ["anysearch"]
160
+ if "local_search" in enabled and "local_search" not in order:
161
+ order.append("local_search")
162
+ return order
@@ -111,26 +111,18 @@ def _random_headers(extra: dict | None = None) -> dict:
111
111
  def _charset_of(content_type: str) -> str:
112
112
  """从 Content-Type 解析 charset;缺失或无法识别时回落 utf-8。
113
113
 
114
- 未知编码必须先判定再解码:`bytes.decode("x-unknown-8bit")` 会抛 LookupError,
115
- 而 LookupError 不是 OSError 子类,会被 HttpClient.get 的 `except Exception`
116
- 吞掉并返回 status=0——一个正常的 200 响应被静默降级成「连接失败」,
117
- 还被归因为 network。运维现实里 `charset=x-unknown-8bit`、
118
- `charset=gb2312;` 这类脏头并不罕见。
114
+ 解码实现(meta 嗅探 + 严格猜测链)在 charset_decode(2026-10-26 拆出,
115
+ fetch_v3/article.py 的 urllib 兜底车道同享);此处保留旧名作兼容入口。
119
116
  """
120
- import codecs
121
- if "charset=" in content_type:
122
- charset = content_type.split("charset=")[-1].strip().split(";")[0].strip().strip('"\'')
123
- try:
124
- codecs.lookup(charset)
125
- return charset
126
- except (LookupError, ValueError):
127
- pass
128
- return "utf-8"
117
+ from charset_decode import _charset_of as _impl
118
+ return _impl(content_type)
129
119
 
130
120
 
131
- def _decode_body(raw_body: bytes, content_type: str) -> str:
132
- """按 Content-Type 的 charset 解码响应体,任何失败都不丢 body。"""
133
- return raw_body.decode(_charset_of(content_type), errors="replace")
121
+ try:
122
+ from charset_decode import decode_response_body
123
+ except ImportError: # pragma: no cover
124
+ def decode_response_body(raw_body: bytes, content_type: str) -> str:
125
+ return raw_body.decode("utf-8", errors="replace")
134
126
 
135
127
 
136
128
  # ─── Retry-After 尊重(合规限速信号)────────────────────────────────────────
@@ -636,7 +628,7 @@ class HttpClient:
636
628
 
637
629
  # 解码
638
630
  content_type = resp.getheader("Content-Type", "")
639
- text = _decode_body(raw_body, content_type)
631
+ text = decode_response_body(raw_body, content_type)
640
632
 
641
633
  elapsed = int((time.time() - start) * 1000)
642
634
 
@@ -686,9 +678,9 @@ class HttpClient:
686
678
  "elapsed_ms": int((time.time() - start) * 1000),
687
679
  "error": "重定向目标被 SSRF 防护拦截"}
688
680
 
689
- cmd = ["curl", "-s", "--max-redirs", "0", "--max-time",
681
+ cmd = ["curl", "-s", "--compressed", "--max-redirs", "0", "--max-time",
690
682
  str(int(self.timeout)),
691
- "-w", "\\n%{http_code}\\n%{url_effective}"]
683
+ "-w", "\\n%{http_code}\\n%{url_effective}\\n%{content_type}"]
692
684
  # 出口调度(issue #13):curl 原生只认标准小写 env,argo 级配置
693
685
  # (ARGO_PROXY/rules)须显式 -x 下发
694
686
  try:
@@ -703,17 +695,19 @@ class HttpClient:
703
695
  cmd.append(final_url)
704
696
 
705
697
  try:
706
- r = subprocess.run(cmd, capture_output=True, text=True,
707
- encoding="utf-8", errors="replace",
708
- timeout=self.timeout + 5)
709
- output = r.stdout.strip()
710
- lines = output.rsplit("\n", 2)
711
- if len(lines) >= 2:
712
- text = lines[0] if len(lines) == 2 else "\n".join(lines[:-2])
713
- status = int(lines[-2]) if lines[-2].isdigit() and lines[-2].isascii() else 0
714
- final_url = lines[-1]
698
+ # bytes 模式收 stdout:text=True 会把 GBK body 在这里先解坏,再想嗅探
699
+ # 就晚了一步。body 编码统一交给 decode_response_body 处理。
700
+ r = subprocess.run(cmd, capture_output=True, timeout=self.timeout + 5)
701
+ output = (r.stdout or b"").strip()
702
+ lines = output.rsplit(b"\n", 3)
703
+ if len(lines) >= 3:
704
+ raw_text = lines[0] if len(lines) == 3 else b"\n".join(lines[:-3])
705
+ status_line, url_line, ct_line = lines[-3:]
706
+ status = int(status_line) if status_line.isdigit() and status_line.isascii() else 0
707
+ final_url = url_line.decode("utf-8", "replace") or url
708
+ text = decode_response_body(raw_text, ct_line.decode("latin-1", "replace"))
715
709
  else:
716
- text = output
710
+ text = output.decode("utf-8", "replace")
717
711
  status = 0
718
712
  final_url = url
719
713
 
@@ -952,7 +946,7 @@ class HttpClient:
952
946
  except ImportError:
953
947
  return self._do_post_fallback(url, payload, extra_headers)
954
948
  content_type = resp.getheader("Content-Type", "")
955
- text = _decode_body(raw_body, content_type)
949
+ text = decode_response_body(raw_body, content_type)
956
950
  return {"status": status, "headers": resp_headers, "text": text,
957
951
  "url": current_url,
958
952
  "elapsed_ms": int((time.time() - start) * 1000),
@@ -962,8 +956,9 @@ class HttpClient:
962
956
  extra_headers: dict | None) -> dict:
963
957
  """POST 的 curl fallback(brotli 不可用时)。"""
964
958
  headers = _random_headers(extra_headers)
965
- cmd = ["curl", "-s", "--max-time", str(int(self.timeout)), "-X", "POST",
966
- "-w", "\\n%{http_code}\\n%{url_effective}"]
959
+ cmd = ["curl", "-s", "--compressed", "--max-time", str(int(self.timeout)),
960
+ "-X", "POST",
961
+ "-w", "\\n%{http_code}\\n%{url_effective}\\n%{content_type}"]
967
962
  # 出口调度(issue #13):与 GET 路径同一判据——此前这条分支漏了
968
963
  # resolve_proxy,「须代理出网」环境里 POST 必然直连失败(2026-09-28 复核)
969
964
  try:
@@ -980,18 +975,19 @@ class HttpClient:
980
975
  cmd.append(url)
981
976
  try:
982
977
  import subprocess
983
- # payload 恒为 bytes(post() 已 encode),故不用 text 模式:
984
- # text=True 收 bytes input 会 TypeError;stdout 手动按 UTF-8 解
985
- # (网页字节流本就 UTF-8,显式解也修掉 Windows GBK 乱码)
978
+ # payload 恒为 bytes(post() 已 encode),stdout 同样收 bytes:
979
+ # body 编码统一交给 decode_response_body(charset 头 + meta 嗅探 + 猜测链)
986
980
  r = subprocess.run(cmd, input=payload, capture_output=True,
987
981
  timeout=self.timeout + 5)
988
- output = (r.stdout or b"").decode("utf-8", errors="replace").strip()
989
- lines = output.rsplit("\n", 2)
990
- if len(lines) >= 2:
991
- text = lines[0] if len(lines) == 2 else "\n".join(lines[:-2])
992
- status = int(lines[-2]) if lines[-2].isdigit() and lines[-2].isascii() else 0
982
+ output = (r.stdout or b"").strip()
983
+ lines = output.rsplit(b"\n", 3)
984
+ if len(lines) >= 3:
985
+ raw_text = lines[0] if len(lines) == 3 else b"\n".join(lines[:-3])
986
+ status_line, _url_line, ct_line = lines[-3:]
987
+ status = int(status_line) if status_line.isdigit() and status_line.isascii() else 0
988
+ text = decode_response_body(raw_text, ct_line.decode("latin-1", "replace"))
993
989
  else:
994
- text, status = output, 0
990
+ text, status = output.decode("utf-8", "replace"), 0
995
991
  return {"status": status, "headers": {}, "text": text, "url": url,
996
992
  "elapsed_ms": 0, "from_cache": False}
997
993
  except Exception as e:
@@ -260,6 +260,10 @@ CLI_PASSTHROUGH_FIELDS = (
260
260
  "image", "thumbnail", "width", "height", "duration", "provider",
261
261
  "image_url", "image_license", "image_license_url",
262
262
  "image_width", "image_height", "image_commercial_ok",
263
+ # 视频引擎(B 站)把时长/UP 主/播放量/弹幕放在 social_meta 里;不在这份
264
+ # 白名单里就会被解析层整块丢掉,下游只能看到 content_type=web_page 和
265
+ # 全 null 的 metrics(2026-10-27 实测 13 条视频候选元数据全丢的根因)。
266
+ "social_meta",
263
267
  )
264
268
 
265
269