argo-search 2.9.8 → 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 (110) hide show
  1. package/README.en.md +48 -35
  2. package/README.es.md +48 -35
  3. package/README.ja.md +47 -34
  4. package/README.ko.md +47 -34
  5. package/README.md +50 -35
  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 +26 -1
  11. package/bin/argo.js +3 -3
  12. package/config.yaml +180 -26
  13. package/docs/ARGO_INTRO.md +7 -5
  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/RELEASE_NOTES_v2.9.9.md +78 -0
  19. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
  20. package/engines/specs/clawhub.yaml +16 -15
  21. package/engines/specs/deepseek1024.yaml +46 -0
  22. package/engines/specs/dsh_hub.yaml +44 -0
  23. package/engines/specs/dshopen.yaml +32 -0
  24. package/engines/specs/explainx.yaml +32 -0
  25. package/engines/specs/gbfs_nyc.yaml +6 -1
  26. package/engines/specs/metaso_doc.yaml +49 -0
  27. package/engines/specs/metaso_image.yaml +65 -0
  28. package/engines/specs/metaso_podcast.yaml +60 -0
  29. package/engines/specs/metaso_scholar.yaml +57 -0
  30. package/engines/specs/metaso_video.yaml +62 -0
  31. package/engines/specs/ncpssd.yaml +41 -0
  32. package/engines/specs/sciverse.yaml +72 -0
  33. package/engines/specs/skills_sh.yaml +32 -0
  34. package/engines/specs/skillsmp.yaml +18 -16
  35. package/package.json +4 -2
  36. package/packages/dsh-plugin/README.md +4 -2
  37. package/packages/dsh-plugin/dsh/client.js +98 -32
  38. package/packages/dsh-plugin/dsh/diagnostics.js +43 -0
  39. package/packages/dsh-plugin/dsh/index.js +23 -1
  40. package/packages/dsh-plugin/package.json +2 -2
  41. package/packages/dsh-plugin/test/client.test.js +2 -1
  42. package/packages/dsh-plugin/test/size-gate.test.js +113 -0
  43. package/scripts/adaptive.py +135 -48
  44. package/scripts/article.py +6 -1
  45. package/scripts/article_meta.py +151 -2
  46. package/scripts/bench_general_pool.py +145 -0
  47. package/scripts/bench_tail_ab.py +281 -0
  48. package/scripts/bounded_run.py +91 -49
  49. package/scripts/candidate_envelope.py +45 -4
  50. package/scripts/charset_decode.py +127 -0
  51. package/scripts/clock_bridge.py +22 -0
  52. package/scripts/content_security.py +119 -4
  53. package/scripts/crawl.py +240 -74
  54. package/scripts/crawl_frontier.py +217 -0
  55. package/scripts/crawl_policy.py +174 -0
  56. package/scripts/dispatch_result.py +9 -2
  57. package/scripts/engine_add.py +602 -0
  58. package/scripts/engine_dispatch.py +31 -15
  59. package/scripts/engine_failure.py +15 -0
  60. package/scripts/engine_validate.py +8 -0
  61. package/scripts/engines.py +10 -0
  62. package/scripts/engines_base.py +12 -0
  63. package/scripts/engines_builders.py +14 -0
  64. package/scripts/engines_builders_dsh.py +330 -0
  65. package/scripts/engines_builders_skill.py +314 -0
  66. package/scripts/evidence_loop.py +4 -0
  67. package/scripts/fetch_quality.py +13 -0
  68. package/scripts/fetch_v3.py +39 -7
  69. package/scripts/gen_engine_catalog.py +218 -2
  70. package/scripts/general_pool.py +162 -0
  71. package/scripts/http_client.py +62 -80
  72. package/scripts/image_ops.py +4 -0
  73. package/scripts/image_vision/vision_probe +0 -0
  74. package/scripts/install.ps1 +47 -19
  75. package/scripts/install.sh +45 -20
  76. package/scripts/matrix_search_eval.py +128 -2
  77. package/scripts/mcp_transport.py +1 -1
  78. package/scripts/ncpssd_bridge.py +123 -0
  79. package/scripts/net_proxy.py +27 -0
  80. package/scripts/paid_policy.py +109 -13
  81. package/scripts/pre-commit +19 -4
  82. package/scripts/query_signals.py +156 -3
  83. package/scripts/recovery.py +7 -3
  84. package/scripts/redskill/redskill_engine.py +29 -2
  85. package/scripts/release_check.py +209 -0
  86. package/scripts/retry_policy.py +22 -1
  87. package/scripts/robots_guard.py +26 -0
  88. package/scripts/route.py +11 -8
  89. package/scripts/route_cache.py +6 -0
  90. package/scripts/route_combo.py +56 -64
  91. package/scripts/route_domains.py +142 -13
  92. package/scripts/route_policy.py +6 -0
  93. package/scripts/safe_conn.py +52 -0
  94. package/scripts/search.py +9 -1
  95. package/scripts/search_cli.py +27 -0
  96. package/scripts/search_entry.py +10 -0
  97. package/scripts/search_output.py +29 -0
  98. package/scripts/search_pipeline.py +59 -3
  99. package/scripts/search_rank.py +7 -0
  100. package/scripts/serp_guard.py +23 -0
  101. package/scripts/social_engines/bilibili_engine.py +163 -26
  102. package/scripts/social_engines/reddit_engine.py +52 -51
  103. package/scripts/source_selection.py +302 -0
  104. package/scripts/tail_completion.py +212 -0
  105. package/scripts/url_safety.py +126 -3
  106. package/scripts/usage_log.py +45 -0
  107. package/scripts/video_fetch.py +303 -0
  108. package/scripts/video_meta.py +225 -0
  109. package/scripts/video_route.py +65 -0
  110. package/scripts/watch.py +123 -0
@@ -57,6 +57,13 @@ RANK_LISTS = {
57
57
  "today": "todayList",
58
58
  "author": "authorList",
59
59
  }
60
+
61
+ # 「非可安装」这个关键信息为什么进摘要前缀,而不是 metadata:
62
+ # argo 的 CLI builder 用 image_ops._cli_result_row 做字段白名单,只保留
63
+ # title/url/snippet/source/published_at + 图片字段——metadata 与 upstream
64
+ # **都不透传**(实测 redskill 输出带 metadata,Argo 结果里是 null)。
65
+ # snippet 是 CLI 引擎唯一能自由填充的字段,故把使用方式写在最前面。
66
+ _USAGE_PREFIX = "【小红书技能·APP 内使用】"
60
67
  RANK_LABELS = {
61
68
  "use": "使用人数榜",
62
69
  "new": "7天新增榜",
@@ -216,10 +223,21 @@ def _search_all(data: dict[str, Any], query: str, n: int) -> list[dict[str, Any]
216
223
  results.append({
217
224
  "title": name,
218
225
  "url": url,
219
- "snippet": str(s.get("skill_description", ""))[:500],
226
+ "snippet": f"{_USAGE_PREFIX}{str(s.get('skill_description', ''))}"[:500],
220
227
  "score": round(score, 3),
221
228
  "source": "redskill",
222
229
  "skill_id": sid,
230
+ # 小红书技能是**提示词/方法论**,不是可安装的代码包。上游数据
231
+ # (allSkills 52314 条)只有 skill_id / skill_name /
232
+ # skill_description 三个字段,**零安装地址**——实测 githubUrl /
233
+ # url / installUrl / repoUrl / note_id 全部为 0 命中;只有 300 条
234
+ # 榜单技能带 note_id。明确标注,避免用户以为「搜到就能装」。
235
+ "metadata": {
236
+ "platform": "xiaohongshu",
237
+ "installable": False,
238
+ "note_id": note,
239
+ "usage": "小红书站内技能:在小红书 APP 内使用,或复制描述作提示词",
240
+ },
223
241
  })
224
242
  return results
225
243
 
@@ -242,7 +260,7 @@ def _rank_list(data: dict[str, Any], rank_type: str, n: int) -> list[dict[str, A
242
260
  note = item.get("note_id")
243
261
  url = EXPLORE_URL.format(note) if note else PAGE_URL
244
262
 
245
- snippet = str(item.get("skill_description", ""))[:500]
263
+ snippet = f"{_USAGE_PREFIX}{str(item.get('skill_description', ''))}"[:500]
246
264
  results.append({
247
265
  "title": item.get("skill_name", ""),
248
266
  "url": url,
@@ -253,6 +271,15 @@ def _rank_list(data: dict[str, Any], rank_type: str, n: int) -> list[dict[str, A
253
271
  "skill_id": item.get("skill_id"),
254
272
  "use_cnt": item.get("use_cnt") if rank_type in ("use", "today") else item.get("new7_cnt"),
255
273
  "use_users": item.get("use_users") if rank_type in ("use", "today") else None,
274
+ # 榜单技能有 note_id(可跳笔记),但笔记里也没有「安装包」——
275
+ # 小红书技能的使用入口是 APP 本身,不是下载。同 _search_all。
276
+ "metadata": {
277
+ "platform": "xiaohongshu",
278
+ "installable": False,
279
+ "note_id": note,
280
+ "rank": i + 1,
281
+ "usage": "小红书站内技能:在小红书 APP 内使用,或复制描述作提示词",
282
+ },
256
283
  })
257
284
  return results
258
285
 
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env python3
2
+ """release_check.py — 发布一致性预检(10 秒回答「这棵树能不能发」)。
3
+
4
+ ## 为什么要这道预检
5
+
6
+ 版本号散在 16 处声明(pyproject / package.json / dsh 插件包 / 插件市场清单 /
7
+ MCP Registry 清单 / ZCode 插件清单 / argo_search.__version__ / SKILL.md 前置
8
+ 字段 / MCP 与面板源码常量 + 五语 README 的徽标),外加五语 README 的发布记录
9
+ 行、docs/RELEASE_NOTES_v<ver>.md 与 package.json 的 files 白名单(带版本号的
10
+ 文件名,漏改就是 npm 包里静默缺文件)。历史上 v2.9.8 漏过 README「最近更新」
11
+ 条目、版本号清单靠人肉逐处核对——每次发版三十到四十分钟,且漏改不一定当场
12
+ 发现(npm 包发出去了才看到 README 还是旧版)。
13
+
14
+ ## 检什么(全部是结构化事实,不做散文匹配)
15
+
16
+ 1. 十一处机器声明与 pyproject.toml 的 version 完全一致;
17
+ 2. 五语 README 的徽标 `badge/version-<v>-` 与发布表行 `| **v<v>** |` 都在;
18
+ 3. `docs/RELEASE_NOTES_v<v>.md` 存在;
19
+ 4. package.json 的 files 白名单包含当前发布说明,且**盘上每份**发布说明都在
20
+ 白名单里(新增 RELEASE_NOTES 忘登记 = npm 包缺文件,与版本号无关)。
21
+
22
+ 不检查散文里的版本提法(「当前 2.9.9」这类句子五语各有写法,正则匹配只会
23
+ 制造假红;结构化位置全绿即可保证对外可见的版本事实一致)。
24
+
25
+ 用法:
26
+ python3 scripts/release_check.py # 预检,非零退出码 = 不能发
27
+ python3 scripts/release_check.py --root . # 指定检出根(测试用)
28
+
29
+ 被 tests/test_release_consistency.py 锁进 pre-commit 快门禁:版本漂移会在
30
+ 提交时就被拦下,而不是等发版当天。
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import re
38
+ import sys
39
+ from pathlib import Path
40
+
41
+ # 十一处机器声明的相对路径(顺序即报错输出顺序)
42
+ JSON_DECLS = (
43
+ "package.json",
44
+ "packages/dsh-plugin/package.json",
45
+ "server.json",
46
+ "packages/argo-zcode/.zcode-plugin/plugin.json",
47
+ )
48
+ README_LANGS = ("README.md", "README.en.md", "README.ja.md", "README.ko.md", "README.es.md")
49
+
50
+ # 源码里的版本常量(正则取,避免 import 副作用)
51
+ SRC_DECLS = (
52
+ ("scripts/mcp_transport.py", r'ARGO_MCP_VERSION\s*=\s*"([^"]+)"'),
53
+ ("packages/argo-zcode/server/panel_server.mjs",
54
+ r'SERVER_INFO\s*=\s*\{[^}]*version:\s*"([^"]+)"'),
55
+ ("packages/argo-zcode/ui/panel.html",
56
+ r'new App\(\{\s*name:\s*"argo-panel",\s*version:\s*"([^"]+)"'),
57
+ )
58
+
59
+
60
+ def _read(root: Path, rel: str) -> str:
61
+ return (root / rel).read_text(encoding="utf-8")
62
+
63
+
64
+ def _safe_read(root: Path, rel: str, problems: list[str]) -> str | None:
65
+ """读文件;缺失/不可读记一条问题而不是抛 traceback。
66
+
67
+ --root 指错目录(或检出被裁剪)是常见的误用,预检工具必须给一句可读的
68
+ 话,而不是让 FileNotFoundError 穿出去——那会让「预检」本身看起来像坏了。
69
+ """
70
+ try:
71
+ return _read(root, rel)
72
+ except OSError as e:
73
+ problems.append(f"{rel}: 读取失败({e.strerror or e})")
74
+ return None
75
+
76
+
77
+ def _pyproject_version(root: Path) -> str:
78
+ m = re.search(r'(?m)^version\s*=\s*"([^"]+)"', _read(root, "pyproject.toml"))
79
+ return m.group(1) if m else ""
80
+
81
+
82
+ def check(root: Path) -> list[str]:
83
+ """返回问题清单;空列表 = 一致。"""
84
+ problems: list[str] = []
85
+ if not (root / "pyproject.toml").is_file():
86
+ return [f"{root} 不像 argo 检出(缺 pyproject.toml)"]
87
+ ver = _pyproject_version(root)
88
+ if not ver:
89
+ return ["pyproject.toml 读不出 version(真源缺失,预检无法进行)"]
90
+
91
+ # 1) JSON 声明
92
+ for rel in JSON_DECLS:
93
+ text = _safe_read(root, rel, problems)
94
+ if text is None:
95
+ continue
96
+ try:
97
+ got = str(json.loads(text).get("version") or "")
98
+ except ValueError as e:
99
+ problems.append(f"{rel}: JSON 解析失败({e})")
100
+ continue
101
+ if got != ver:
102
+ problems.append(f"{rel}: {got} ≠ pyproject {ver}")
103
+
104
+ # 2) 插件市场清单(plugins[] 每个都要对上)
105
+ text = _safe_read(root, "packages/marketplace.json", problems)
106
+ if text is not None:
107
+ try:
108
+ market = json.loads(text)
109
+ for plugin in market.get("plugins") or []:
110
+ got = str(plugin.get("version") or "")
111
+ if got != ver:
112
+ problems.append(
113
+ f"packages/marketplace.json[{plugin.get('name')}]: {got} ≠ {ver}")
114
+ except (OSError, ValueError) as e:
115
+ problems.append(f"packages/marketplace.json: 读取失败({e})")
116
+
117
+ # 2b) MCP Registry 清单(packages[] 每条的版本也要对上)
118
+ text = _safe_read(root, "server.json", problems)
119
+ if text is not None:
120
+ try:
121
+ for pkg in json.loads(text).get("packages") or []:
122
+ got = str(pkg.get("version") or "")
123
+ if got != ver:
124
+ problems.append(
125
+ f"server.json[{pkg.get('identifier')}]: {got} ≠ {ver}")
126
+ except ValueError as e:
127
+ problems.append(f"server.json: JSON 解析失败({e})")
128
+
129
+ # 2c) 源码常量(MCP 握手自报版本、ZCode 面板版本)
130
+ for rel, pat in SRC_DECLS:
131
+ if not (root / rel).is_file():
132
+ continue
133
+ m = re.search(pat, _read(root, rel))
134
+ if not m:
135
+ problems.append(f"{rel}: 找不到版本声明")
136
+ elif m.group(1) != ver:
137
+ problems.append(f"{rel}: {m.group(1)} ≠ {ver}")
138
+
139
+ # 3) Python 包内声明(MCP/库调用方读它)
140
+ text = _safe_read(root, "argo_search/__init__.py", problems)
141
+ if text is not None:
142
+ m = re.search(r'(?m)^__version__\s*=\s*"([^"]+)"', text)
143
+ if not m:
144
+ problems.append("argo_search/__init__.py: 找不到 __version__")
145
+ elif m.group(1) != ver:
146
+ problems.append(f"argo_search/__init__.py: {m.group(1)} ≠ {ver}")
147
+
148
+ # 4) SKILL.md 前置字段
149
+ text = _safe_read(root, "SKILL.md", problems)
150
+ if text is not None:
151
+ m = re.search(r"(?m)^version:\s*(\S+)\s*$", text[:2000])
152
+ if not m:
153
+ problems.append("SKILL.md: 前置字段缺 version")
154
+ elif m.group(1) != ver:
155
+ problems.append(f"SKILL.md: {m.group(1)} ≠ {ver}")
156
+
157
+ # 5) 五语 README:徽标 + 发布表行
158
+ for rel in README_LANGS:
159
+ text = _safe_read(root, rel, problems)
160
+ if text is None:
161
+ continue
162
+ if f"badge/version-{ver}-" not in text:
163
+ problems.append(f"{rel}: 徽标不是 {ver}")
164
+ if f"| **v{ver}** |" not in text:
165
+ problems.append(f"{rel}: 发布记录表缺 | **v{ver}** | 行")
166
+
167
+ # 6) 发布说明文件 + npm files 白名单
168
+ notes = f"docs/RELEASE_NOTES_v{ver}.md"
169
+ if not (root / notes).is_file():
170
+ problems.append(f"{notes}: 发布说明不存在")
171
+ text = _safe_read(root, "package.json", problems)
172
+ files = []
173
+ if text is not None:
174
+ try:
175
+ files = json.loads(text).get("files") or []
176
+ except ValueError:
177
+ files = []
178
+ if notes not in files:
179
+ problems.append(f"package.json files 白名单缺 {notes}(npm 包会缺发布说明)")
180
+ for path in sorted((root / "docs").glob("RELEASE_NOTES_v*.md")):
181
+ rel = f"docs/{path.name}"
182
+ if rel not in files:
183
+ problems.append(f"package.json files 白名单缺 {rel}(盘上有、包里没有)")
184
+
185
+ return problems
186
+
187
+
188
+ def main(argv: list[str] | None = None) -> int:
189
+ ap = argparse.ArgumentParser(description="发布一致性预检")
190
+ ap.add_argument("--root", default=str(Path(__file__).resolve().parent.parent),
191
+ help="检出根目录(默认本仓库)")
192
+ args = ap.parse_args(argv)
193
+ root = Path(args.root)
194
+ problems = check(root)
195
+ try:
196
+ ver = _pyproject_version(root) or "?"
197
+ except OSError:
198
+ ver = "?" # 非检出目录:check() 已记问题,这里只负责别在报错路径上再炸
199
+ if problems:
200
+ print(f"release_check: v{ver} 不一致,{len(problems)} 项待修:", file=sys.stderr)
201
+ for p in problems:
202
+ print(f" !! {p}", file=sys.stderr)
203
+ return 1
204
+ print(f"release_check: v{ver} 一致(11 处机器声明 + 五语 README + 发布说明与白名单)")
205
+ return 0
206
+
207
+
208
+ if __name__ == "__main__":
209
+ sys.exit(main())
@@ -18,6 +18,7 @@ from __future__ import annotations
18
18
  from typing import Any
19
19
 
20
20
  from cache_guard import _QUOTA_ERROR_KEYWORDS
21
+ from engine_failure import NOTE_STATUS as _NOTE_STATUS
21
22
 
22
23
  # 拦截页特征词(唯一来源):error 文本里出现即判 blocked。HTML 引擎的反爬
23
24
  # 命中没有 error 文本(静默空结果),走 engines_base 的归因寄存器;
@@ -34,6 +35,17 @@ _BLOCKED_ERROR_KEYWORDS = (
34
35
  # 结束、bot-wall 短退避,只有 transient 才重试一次)。
35
36
  NON_RETRYABLE_STATUS = frozenset({"quota-exhausted", "auth-failed", "blocked"})
36
37
 
38
+ # 归因寄存器(engines_base.note_failure)的类别 → 是否确定性失败。
39
+ # 与上面的状态表同义,只是入口不同:HTML 抓取类引擎失败时往往返回空列表,
40
+ # 错误文本只写进归因寄存器,`classify_error_status` 看不到。2026-10-26 实测:
41
+ # octen 余额不足返回 [],调度层把它当「空结果可重试」,跑满 3 次(1934ms);
42
+ # local_bing 被反爬时同样重试。归因类别是同一事实的另一个出口,判据必须一致。
43
+ # 从 NOTE_STATUS(唯一映射表)派生,不另抄一份类别名单:rate_limited 映射到
44
+ # 非 NON_RETRYABLE_STATUS 的 "rate-limited",自动保持「限流可重试」。
45
+ _DETERMINISTIC_NOTE_CATEGORIES = frozenset(
46
+ cat for cat, status in _NOTE_STATUS.items()
47
+ if status in NON_RETRYABLE_STATUS)
48
+
37
49
 
38
50
  def classify_error_status(message: Any) -> str:
39
51
  """错误文本 → 失败类别。**重试判据与归因判据的共同定义点**。
@@ -55,12 +67,21 @@ def classify_error_status(message: Any) -> str:
55
67
  return "error"
56
68
 
57
69
 
58
- def is_retryable_failure(res: list[Any] | None) -> bool:
70
+ def is_retryable_failure(res: list[Any] | None,
71
+ failure_note: dict[str, Any] | None = None) -> bool:
59
72
  """这组结果值不值得再试一次(纯函数,门禁可直接打到)。
60
73
 
61
74
  判据取自 `classify_error_status`,与归因同源。空结果与无错误条目返回
62
75
  True——沿用既有「重试一次」语义,本次只收紧确定性失败这一类。
76
+
77
+ `failure_note` 是归因寄存器的只读快照(engines_base.peek_failure_note):
78
+ 抓取类引擎失败时返回空列表,错误只落在寄存器里,只查 `res` 会把配额耗尽
79
+ 当空结果重试。两个入口共用同一张确定性类别表,避免「重试按一套判据、
80
+ 熔断按另一套判据」。
63
81
  """
82
+ note_category = str((failure_note or {}).get("category") or "")
83
+ if note_category in _DETERMINISTIC_NOTE_CATEGORIES:
84
+ return False
64
85
  for r in res or []:
65
86
  if isinstance(r, dict) and "error" in r:
66
87
  return classify_error_status(r.get("error")) not in NON_RETRYABLE_STATUS
@@ -241,6 +241,32 @@ def robots_blocked(url: str, timeout: float = 5.0) -> bool:
241
241
  return False # 解析异常 → 放行
242
242
 
243
243
 
244
+ def crawl_delay(url: str, timeout: float = 5.0) -> float | None:
245
+ """robots.txt 为该站声明的 Crawl-delay(秒);没有声明或取不到返回 None。
246
+
247
+ 只取通配 UA 的声明:本技能 UA 轮换,具体 UA 的 delay 会漏掉 `User-agent: *`。
248
+ 与 robots_blocked 共用同一个解析器缓存,不会为此多抓一次 robots.txt。
249
+ """
250
+ if not _robots_enabled():
251
+ return None
252
+ scheme, host = _domain_key(url)
253
+ if not host:
254
+ return None
255
+ rp = _get_parser(scheme, host, timeout)
256
+ if rp is None:
257
+ return None
258
+ try:
259
+ value = rp.crawl_delay("*")
260
+ except Exception:
261
+ return None
262
+ if value is None:
263
+ return None
264
+ try:
265
+ return float(value)
266
+ except (TypeError, ValueError):
267
+ return None
268
+
269
+
244
270
  # ─── 测试辅助 ────────────────────────────────────────────────────────────────
245
271
 
246
272
  def clear_cache() -> None:
package/scripts/route.py CHANGED
@@ -132,6 +132,7 @@ from paid_policy import insert_hedge
132
132
  from route_combo import ( # noqa: E402
133
133
  _expand_local_search,
134
134
  _general_fallback,
135
+ general_kwargs,
135
136
  _filter_breaker_blocked,
136
137
  _maybe_add_geo_engine,
137
138
  _apply_intent_parallelism,
@@ -425,9 +426,8 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
425
426
  engines_combo = declared
426
427
  if not engines_combo:
427
428
  # 域内引擎全被过滤,回退(本地优先 + 通用免费源唯一来源)
428
- engines_combo = _general_fallback(enabled)
429
- if not engines_combo:
430
- engines_combo = sorted(enabled)[:2] if enabled else ["anysearch"]
429
+ engines_combo = _general_fallback(
430
+ enabled, **general_kwargs(features, mode, depth, context))
431
431
  # 扩展 local_search → 子引擎
432
432
  engines_combo = _expand_local_search(engines_combo, features)
433
433
 
@@ -599,7 +599,9 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
599
599
  # 双引擎默认串行,利于 early-stop(答案域)
600
600
  parallel = parallel and len(engines_combo) > 2
601
601
 
602
- engines_combo = insert_hedge(engines_combo, domain.get("name", ""), mode, enabled)
602
+ engines_combo = insert_hedge(
603
+ engines_combo, domain.get("name", ""), mode, enabled,
604
+ lang=str((features or {}).get("primary_lang") or ""))
603
605
 
604
606
  return _done(
605
607
  engine=engines_combo[0],
@@ -650,7 +652,9 @@ def _route_by_tfidf(ctx: _RouteCtx) -> dict[str, Any]:
650
652
  _done = ctx.done
651
653
  domain = None # 能走到这里说明没有域命中(含兜底域)
652
654
  # 弱证据推荐只作辅源跟跑、通用保底领队;强证据维持推荐领队(route_combo)
653
- engines_combo = tfidf_lead_combo(tfidf_best, tfidf_best_score, enabled)
655
+ engines_combo = tfidf_lead_combo(
656
+ tfidf_best, tfidf_best_score, enabled,
657
+ **general_kwargs(features, mode, depth, context))
654
658
  # 🔑 展开 local_search → 子引擎
655
659
  engines_combo = _expand_local_search(engines_combo, features)
656
660
  # 🔑 为中文/学术查询追加本地引擎
@@ -724,9 +728,8 @@ def _route_by_fallback(ctx: _RouteCtx) -> dict[str, Any]:
724
728
  tfidf_scores = ctx.tfidf_scores
725
729
  _done = ctx.done
726
730
  # 保底:免费通用引擎(零分 TF-IDF 也走这里)——本地优先 + 通用免费源唯一来源
727
- fallback_combo = _general_fallback(enabled)
728
- if not fallback_combo:
729
- fallback_combo = sorted(enabled)[:2] if enabled else ["anysearch"]
731
+ fallback_combo = _general_fallback(
732
+ enabled, **general_kwargs(features, mode, depth, context))
730
733
  # 日/韩主查询:优先 anysearch(多语言源对日/韩结果语言匹配更好),
731
734
  # 再并语言专用本地引擎;避免旧逻辑只锁 local_bing(zh 参数)返回中文站。
732
735
  # 注:byted 经实测对 ja/ko 也可,但其被 test_multilingual 定义为中文引擎,
@@ -111,6 +111,12 @@ def _route_state_fingerprint() -> str:
111
111
  _get_env = lambda k, d="": os.environ.get(k, d) # noqa: E731
112
112
  parts.append("lead=" + (_get_env("ARGO_GENERAL_FALLBACK_LEAD") or ""))
113
113
  parts.append("legacy=" + (_get_env("ARGO_GENERAL_FALLBACK_LEGACY") or ""))
114
+ # 静态臂同样是「改通用兜底链顺序」的开关(2026-10-26 新增)。不进指纹
115
+ # 会让「设了 STATIC=1 但缓存命中」读到动态排序,A/B 两臂变成同一臂。
116
+ parts.append("static=" + (_get_env("ARGO_GENERAL_FALLBACK_STATIC") or ""))
117
+ # 付费对冲位置同样改变 combo:常驻第二位 vs 第三位(免费源先跑)。
118
+ # 不进指纹会让 A/B 两臂在缓存命中时读到同一组合。
119
+ parts.append("hedge_defer=" + (_get_env("ARGO_PAID_HEDGE_DEFER") or ""))
114
120
  # 付费对冲开关与月度预算同样改变 combo;不纳入指纹会让开关或预算变更在缓存命中时静默不生效。
115
121
  parts.append("paid=" + (_get_env("ARGO_PAID_SEARCH") or ""))
116
122
  try:
@@ -12,11 +12,15 @@
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
- import os
16
- from typing import Any
15
+ from typing import Any, Callable
17
16
 
18
17
  from config import get_engines
18
+ from general_pool import (configured_general_pool as _configured_general_pool,
19
+ general_fallback as _general_fallback,
20
+ general_kwargs,
21
+ ranked_general as _ranked_general)
19
22
  from quota import get_quota_manager
23
+ from source_selection import candidate_allowed
20
24
  from route_lang import (_enabled_local_engines, _filter_lang_bound_family,
21
25
  _get_registry, _lang_must_keep, _specs_snapshot,
22
26
  lang_allows)
@@ -81,46 +85,8 @@ def _expand_local_search(engine_list: list[str], features: dict | None = None) -
81
85
  return result
82
86
 
83
87
 
84
- def _general_fallback(enabled: set[str]) -> list[str]:
85
- """通用免费源领队 + 本地检索保底(清单唯一来源 engine_policy.GENERAL_FREE_FALLBACK)。
86
-
87
- 域内引擎全被过滤 / 无匹配域时的回退组合。通用免费源在前、local_search 殿后,
88
- 清单与 recovery L3 共用同一常量,避免两处清单漂移。
89
-
90
- local_search 殿后而非领队(2026-10-15 实测定案):日常档 combo_budget=2
91
- (见 engine_policy.combo_budget,fast/auto+fast 都只取前 2 位),
92
- `_expand_local_search` 又把展开出的本地子引擎**追加尾部**——它一旦占住前排,
93
- 尾部子引擎必被预算截断,只剩 local_search 聚合器**独跑**。1059 条真实查询里
94
- 它独跑 109 次、中位 2.9s、45% 超 3s,占全部查询墙钟 369s,而其中纯英文
95
- 技术查询("zig comptime explained" 类)占 82%——本地文件检索对这类 query
96
- 语义上无效,纯亏延迟。改为通用源领队后:常规查询直接落 anysearch/local_bing
97
- (实测 ~1.1-1.7s),local_search 只在通用源全部不可用(熔断/配额耗尽)时
98
- 才顶上前预算位,本地检索能力不减,只是不再无条件霸占首轮。
99
- """
100
- try:
101
- from engine_policy import GENERAL_FREE_FALLBACK
102
- except ImportError:
103
- GENERAL_FREE_FALLBACK = ("anysearch", "octen", "local_bing")
104
- order = list(GENERAL_FREE_FALLBACK)
105
- # 领队覆盖(2026-10-21):A/B 与线上回退都走这里,避免为了复测改常量。
106
- # 传引擎名即把它提到首位(例:ARGO_GENERAL_FALLBACK_LEAD=anysearch 复现
107
- # 2026-10-21 之前的顺位);传空/未知值不生效。与下面的 LEGACY 开关正交。
108
- lead_override = (os.environ.get("ARGO_GENERAL_FALLBACK_LEAD") or "").strip()
109
- if lead_override and lead_override in order:
110
- order = [lead_override] + [e for e in order if e != lead_override]
111
- # 逃生开关:A/B 与线上回退都走这条,避免为了复测改常量。
112
- # 2026-10-17 对拍(交错、随机序):octen 入第二顺位后,anysearch 抖动
113
- # 窗口 p90 3273→1614ms、max 6266→1928ms、错误 9→0;健康窗口中位无差。
114
- try:
115
- from engine_env import env_flag
116
- if env_flag("ARGO_GENERAL_FALLBACK_LEGACY", default=False):
117
- order = [e for e in order if e != "octen"]
118
- except ImportError:
119
- pass
120
- lead = [e for e in order if e in enabled]
121
- # 保底项同样受 enabled 约束:不在 enabled 说明本机压根没注册/被禁用,
122
- # 选它只会在执行层撞 "未知引擎" 空跑。
123
- return lead + (["local_search"] if "local_search" in enabled else [])
88
+ # 通用候选池的顺序策略在 general_pool.py(route_combo 曾因它逼近 1000 行)。
89
+ # 顶部别名保留,既有调用方与测试的 import 路径不变。
124
90
 
125
91
 
126
92
  def _breaker_blocked(engine_id: str) -> bool:
@@ -269,37 +235,49 @@ TFIDF_STRONG_SCORE = 0.15
269
235
 
270
236
 
271
237
  def tfidf_lead_combo(tfidf_best: str | None, tfidf_best_score: float,
272
- enabled: set[str]) -> list[str]:
273
- """TF-IDF 分支的初始 combo:强证据推荐领队 + anysearch 对冲。
238
+ enabled: set[str], *, mode: str = "auto",
239
+ depth: str = "fast", context: str = "search",
240
+ lang: str = "",
241
+ score_fn: Callable[[str, str, str, str],
242
+ tuple[float, int]] | None = None
243
+ ) -> list[str]:
244
+ """TF-IDF 分支的初始 combo:强证据推荐领队 + 通用源对冲。
274
245
 
275
246
  弱证据(≤TFIDF_STRONG_SCORE)时反过来:通用保底领队,推荐引擎殿后
276
247
  作辅源——仍在 combo 里并行竞速,能力不减,只是不再占 primary 位
277
248
  (含 primary 宽限/充分性判定对它的偏袒)。
249
+
250
+ 2026-10-26:对冲位不再写死 octen/anysearch,改由 `_ranked_general`
251
+ 给出当前最优的通用源。静态清单与实测排序的分叉此前导致「走 TF-IDF
252
+ 分支的查询永远用不到 tavily/yuanbao」,同一个无匹配域查询换条路径
253
+ 就换了源。两条路径现在共用同一排序。
278
254
  """
279
255
  strong = bool(tfidf_best and tfidf_best_score > TFIDF_STRONG_SCORE)
256
+ generals = _ranked_general(
257
+ enabled, mode=mode, depth=depth, context=context, lang=lang,
258
+ score_fn=score_fn)
280
259
  lead: list[str] = []
281
260
  if strong:
282
261
  lead = [tfidf_best]
283
- # 垂直领队用 octen 对冲、anysearch 第三;anysearch 领队则反过来。
284
- hedges = ("octen", "anysearch") if tfidf_best != "anysearch" \
285
- else ("anysearch", "octen")
286
- for e in hedges:
287
- if e in enabled and e not in lead:
262
+ for e in generals:
263
+ if len(lead) >= 3:
264
+ break
265
+ if e not in lead:
288
266
  lead.append(e)
289
267
  else:
290
- # 弱证据/无推荐:通用保底领队,弱推荐作为辅源跟在后面(既有契约,
291
- # tests/test_route_tfidf_weak_score.py 锁死),octen 排第三。日常
292
- # budget=2 会截掉第三位,所以弱证据不额外占 octen 的位;低分回退
293
- # 分支(score < TFIDF_MIN_SCORE)走通用兜底链,那里 octen 已在第二。
294
- if "anysearch" in enabled:
295
- lead.append("anysearch")
296
- if tfidf_best and tfidf_best not in lead:
268
+ # 弱证据/无推荐:通用保底领队,弱推荐作为辅源紧跟其后(既有契约,
269
+ # tests/test_route_tfidf_weak_score.py 锁死)。弱推荐占第二槽而不是
270
+ # 第三槽:日常 budget=2 时它仍能参与竞速,与改动前逐位一致;第二个
271
+ # 通用源顺延到第三位。
272
+ lead = list(generals[:1])
273
+ if tfidf_best and tfidf_best not in lead and tfidf_best in enabled:
297
274
  lead.append(tfidf_best)
298
- if "octen" in enabled and "octen" not in lead:
299
- lead.append("octen")
275
+ lead.extend(e for e in generals[1:] if e not in lead)
300
276
  out: list[str] = []
301
277
  for e in lead:
302
- if e in enabled and e not in out:
278
+ # 与 source_selection 同一判据:enabled 成员,或预算内的白名单付费源。
279
+ # 只查 `e in enabled` 会把池排序里已放行的 DeepSeek 在装配阶段再剔掉。
280
+ if candidate_allowed(e, enabled, mode) and e not in out:
303
281
  out.append(e)
304
282
  return out
305
283
 
@@ -502,6 +480,20 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
502
480
  # 学习器在此处首次解析(惰性,见模块顶部 _get_learner):走到这里说明
503
481
  # 真的要装配 combo,这笔钱躲不掉;不进本函数的路径(缓存命中等)不付。
504
482
  _adaptive_learner = _get_learner()
483
+
484
+ # 场景分桶取分(2026-10-24):优先用 (engine, domain, lang) 的桶分,
485
+ # 桶无样本时 adaptive.get_score 自动回退全局分。判据与旧口径一致,
486
+ # 只是多了一个维度——「引擎在 A 域强、B 域弱」现在可被路由区分。
487
+ _dom_name = str(domain.get("name") or "")
488
+ _q_lang = str((features or {}).get("primary_lang") or "")
489
+
490
+ def _score_of(e: str) -> float:
491
+ try:
492
+ return _adaptive_learner.get_score(e, _dom_name, _q_lang)
493
+ except TypeError:
494
+ # 旧版 adaptive(无 domain/lang 形参)回退全局分
495
+ return _adaptive_learner.get_score(e)
496
+
505
497
  combo = domain.get("engines_combo", [])
506
498
  primary = domain.get("primary", "anysearch")
507
499
  fallback = domain.get("fallback")
@@ -581,7 +573,7 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
581
573
  # 成员与 fallback,自动进入恢复链 L3 兜底。
582
574
  if primary and (
583
575
  _adaptive_learner is None
584
- or _adaptive_learner.get_score(primary) >= _VERTICAL_FLOOR):
576
+ or _score_of(primary) >= _VERTICAL_FLOOR):
585
577
  protect.add(primary)
586
578
  # 仅 modal_card 整 combo 免 cost 裁剪(结构化路径不可被 anysearch 顶替)
587
579
  if domain_name == "modal_card":
@@ -608,14 +600,14 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
608
600
  # 自动回归 combo,且它仍是域 fallback(恢复链 L3 候选)。
609
601
  if domain_name in _VERTICAL_PROTECT:
610
602
  protect = {e for e in original
611
- if _adaptive_learner.get_score(e) >= _VERTICAL_FLOOR
603
+ if _score_of(e) >= _VERTICAL_FLOOR
612
604
  } | protect
613
605
  filtered = [
614
606
  e for e in filtered
615
607
  if e in protect
616
608
  or (e == primary
617
- and _adaptive_learner.get_score(e) >= _VERTICAL_FLOOR)
618
- or _adaptive_learner.get_score(e) >= 0.3
609
+ and _score_of(e) >= _VERTICAL_FLOOR)
610
+ or _score_of(e) >= 0.3
619
611
  ]
620
612
  if not filtered:
621
613
  filtered = original
@@ -662,7 +654,7 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
662
654
  seen_fam.add(f)
663
655
  members = [x for x in rest if _fam(x) == f]
664
656
  if len(members) > 1:
665
- scored = [(x, _adaptive_learner.get_score(x)) for x in members]
657
+ scored = [(x, _score_of(x)) for x in members]
666
658
  top_score = max(s for _, s in scored)
667
659
  laggards = [x for x, s in scored if top_score - s >= 0.15]
668
660
  if laggards and len(laggards) < len(scored):