argo-search 2.14.0 → 2.15.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 (207) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +56 -824
  3. package/README.ja.md +55 -825
  4. package/README.ko.md +55 -823
  5. package/README.md +128 -868
  6. package/README.zh.md +206 -0
  7. package/SKILL.md +17 -18
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +23 -23
  10. package/backends/concept_vectors.bin +0 -0
  11. package/backends/domain_profiles.json +66 -0
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +193 -46
  14. package/backends/quota_profiles.json +110 -0
  15. package/bin/argo +30 -17
  16. package/config.yaml +196 -36
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +45 -0
  20. package/docs/ENGINE_CATALOG.md +128 -112
  21. package/docs/MCP_SETUP.md +2 -2
  22. package/docs/RELEASE_NOTES_v2.14.0.md +12 -1
  23. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  24. package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
  25. package/docs/RELEASING.md +53 -1
  26. package/engines/specs/ai_labs.yaml +89 -0
  27. package/engines/specs/artic.yaml +11 -1
  28. package/engines/specs/bilibili_hot.yaml +11 -1
  29. package/engines/specs/brave.yaml +3 -3
  30. package/engines/specs/cisa_alerts.yaml +40 -0
  31. package/engines/specs/cleveland.yaml +15 -1
  32. package/engines/specs/clinicaltrials.yaml +16 -1
  33. package/engines/specs/cn_ai_news.yaml +10 -8
  34. package/engines/specs/cnii.yaml +15 -4
  35. package/engines/specs/deezer.yaml +12 -1
  36. package/engines/specs/digup.yaml +11 -6
  37. package/engines/specs/doaj.yaml +14 -1
  38. package/engines/specs/douyin_hot.yaml +11 -1
  39. package/engines/specs/dw_news.yaml +4 -2
  40. package/engines/specs/endoflife.yaml +16 -1
  41. package/engines/specs/eng_blogs.yaml +63 -0
  42. package/engines/specs/eu_opendata.yaml +11 -1
  43. package/engines/specs/europeana.yaml +22 -5
  44. package/engines/specs/feed.yaml +62 -0
  45. package/engines/specs/felo.yaml +3 -3
  46. package/engines/specs/figshare.yaml +12 -1
  47. package/engines/specs/firecrawl.yaml +3 -0
  48. package/engines/specs/fourget.yaml +5 -2
  49. package/engines/specs/france24.yaml +6 -4
  50. package/engines/specs/fxtwitter.yaml +29 -6
  51. package/engines/specs/grepapp_mcp.yaml +62 -0
  52. package/engines/specs/guardian_rss.yaml +6 -4
  53. package/engines/specs/hackernews.yaml +17 -2
  54. package/engines/specs/hal.yaml +19 -1
  55. package/engines/specs/hf_datasets.yaml +59 -0
  56. package/engines/specs/hf_papers.yaml +17 -1
  57. package/engines/specs/itotii.yaml +13 -1
  58. package/engines/specs/jikan.yaml +12 -10
  59. package/engines/specs/kaggle.yaml +5 -3
  60. package/engines/specs/lobsters.yaml +41 -0
  61. package/engines/specs/local_seek.yaml +6 -0
  62. package/engines/specs/maven.yaml +61 -0
  63. package/engines/specs/nasa_cmr.yaml +12 -1
  64. package/engines/specs/nuget.yaml +57 -0
  65. package/engines/specs/open_meteo.yaml +1 -1
  66. package/engines/specs/redskill.yaml +2 -0
  67. package/engines/specs/searxng.yaml +4 -2
  68. package/engines/specs/sec_edgar.yaml +8 -3
  69. package/engines/specs/tatoeba.yaml +14 -1
  70. package/engines/specs/tinyfish.yaml +2 -0
  71. package/engines/specs/tinyfish_news.yaml +2 -0
  72. package/engines/specs/tinyfish_paper.yaml +2 -0
  73. package/engines/specs/toutiao_hot.yaml +11 -1
  74. package/engines/specs/train.yaml +3 -0
  75. package/engines/specs/tvmaze.yaml +5 -1
  76. package/engines/specs/twitter.yaml +4 -0
  77. package/engines/specs/unpaywall.yaml +6 -0
  78. package/engines/specs/usda.yaml +14 -1
  79. package/engines/specs/vam.yaml +17 -3
  80. package/engines/specs/weibo_hot.yaml +11 -1
  81. package/engines/specs/wolframalpha.yaml +3 -3
  82. package/engines/specs/xiaohongshu.yaml +2 -0
  83. package/engines/specs/zhihu.yaml +3 -18
  84. package/engines/specs/zhihu_kb.yaml +18 -0
  85. package/engines/specs/zhihu_questions.yaml +19 -0
  86. package/package.json +4 -2
  87. package/packages/dsh-plugin/README.md +9 -14
  88. package/packages/dsh-plugin/dsh/client.js +467 -1024
  89. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  90. package/packages/dsh-plugin/dsh/native-tools.mjs +61 -113
  91. package/packages/dsh-plugin/dsh/runner.js +2 -0
  92. package/packages/dsh-plugin/dsh/wide-research.js +1 -1
  93. package/packages/dsh-plugin/package.json +8 -3
  94. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  95. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  96. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  97. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  98. package/scripts/adaptive.py +7 -1
  99. package/scripts/archive_run.py +112 -53
  100. package/scripts/argo_paths.py +40 -3
  101. package/scripts/badcase_ledger.py +153 -10
  102. package/scripts/build_concept_table.py +112 -55
  103. package/scripts/build_release_assets.sh +43 -15
  104. package/scripts/cache.py +5 -1
  105. package/scripts/caliber_isolation.py +60 -23
  106. package/scripts/circuit_breaker.py +56 -8
  107. package/scripts/cli_io.py +20 -2
  108. package/scripts/config_cache.py +31 -0
  109. package/scripts/daemon.py +146 -51
  110. package/scripts/dormant_ledger.py +239 -0
  111. package/scripts/engine_dispatch.py +3 -3
  112. package/scripts/engine_env.py +182 -1
  113. package/scripts/engine_families.py +50 -7
  114. package/scripts/engine_states.py +9 -51
  115. package/scripts/engine_validate.py +150 -6
  116. package/scripts/engines.py +15 -67
  117. package/scripts/engines_base.py +68 -124
  118. package/scripts/engines_builders.py +0 -51
  119. package/scripts/engines_builders_batch10.py +346 -100
  120. package/scripts/engines_builders_batch11.py +2 -75
  121. package/scripts/engines_builders_batch9.py +15 -228
  122. package/scripts/engines_builders_cn.py +0 -194
  123. package/scripts/engines_builders_feeds.py +203 -35
  124. package/scripts/engines_builders_intl.py +15 -443
  125. package/scripts/engines_builders_pixiv.py +2 -16
  126. package/scripts/engines_builders_science.py +0 -85
  127. package/scripts/engines_builders_search.py +7 -14
  128. package/scripts/engines_builders_tech.py +5 -112
  129. package/scripts/engines_builders_weather.py +236 -0
  130. package/scripts/engines_fields.py +91 -0
  131. package/scripts/engines_http.py +135 -0
  132. package/scripts/engines_mcp.py +383 -0
  133. package/scripts/engines_parsers.py +196 -27
  134. package/scripts/engines_schema_drift.py +260 -0
  135. package/scripts/evidence.py +13 -0
  136. package/scripts/evidence_loop.py +93 -5
  137. package/scripts/fetch_jsrun.py +15 -11
  138. package/scripts/fetch_v3.py +28 -28
  139. package/scripts/fulltext_store.py +42 -1
  140. package/scripts/fxtwitter_api.py +8 -7
  141. package/scripts/gen_engine_catalog.py +4 -4
  142. package/scripts/gen_native_tools.py +2 -1
  143. package/scripts/general_pool.py +15 -4
  144. package/scripts/health_check.py +1 -1
  145. package/scripts/link_source.py +65 -24
  146. package/scripts/local_intent.py +51 -15
  147. package/scripts/local_seek.py +37 -4
  148. package/scripts/local_seek_adapter.py +57 -17
  149. package/scripts/mcp_handlers.py +173 -99
  150. package/scripts/mcp_handlers_surface.py +6 -18
  151. package/scripts/mcp_server.py +1 -1
  152. package/scripts/mcp_tools.py +143 -61
  153. package/scripts/mcp_transport.py +42 -10
  154. package/scripts/min_version_scan.py +7 -3
  155. package/scripts/network_aware.py +7 -13
  156. package/scripts/pre-commit +57 -31
  157. package/scripts/query_understanding.py +30 -6
  158. package/scripts/quota.py +6 -1
  159. package/scripts/rank_signals.py +9 -0
  160. package/scripts/recompute.py +15 -5
  161. package/scripts/recovery.py +21 -15
  162. package/scripts/release.py +29 -32
  163. package/scripts/release_check.py +6 -26
  164. package/scripts/replay_eval.py +2 -2
  165. package/scripts/research_cli.py +40 -0
  166. package/scripts/research_notes.py +368 -0
  167. package/scripts/route.py +32 -70
  168. package/scripts/route_audit.py +259 -0
  169. package/scripts/route_combo.py +10 -4
  170. package/scripts/route_domains.py +150 -23
  171. package/scripts/route_lang.py +20 -7
  172. package/scripts/route_log.py +26 -9
  173. package/scripts/route_policy.py +91 -7
  174. package/scripts/route_telemetry_export.py +199 -0
  175. package/scripts/rrf_classic.py +5 -22
  176. package/scripts/search.py +2 -1
  177. package/scripts/search_attribution.py +33 -10
  178. package/scripts/search_cli.py +44 -7
  179. package/scripts/search_entry.py +5 -1
  180. package/scripts/search_output.py +5 -4
  181. package/scripts/search_pipeline.py +12 -0
  182. package/scripts/search_rank.py +21 -11
  183. package/scripts/secret_guard.py +106 -0
  184. package/scripts/semantic_evidence.py +539 -117
  185. package/scripts/settings_page.py +83 -11
  186. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  187. package/scripts/social_engines/zhihu_engine.py +251 -43
  188. package/scripts/sogou_weixin_browser.py +5 -6
  189. package/scripts/source_audit.py +77 -0
  190. package/scripts/source_ledger.py +2 -15
  191. package/scripts/source_selection.py +45 -20
  192. package/scripts/straggler_policy.py +1 -2
  193. package/scripts/sync_backends.py +24 -0
  194. package/scripts/tfidf_router.py +23 -11
  195. package/scripts/time_utils.py +54 -1
  196. package/scripts/train.py +68 -2
  197. package/scripts/usage_log.py +26 -1
  198. package/sub-skills/argo-wide-research/SKILL.md +68 -0
  199. package/sub-skills/ego-search/SKILL.md +1 -1
  200. package/sub-skills/local-seek/scripts/seek_fts.py +67 -4
  201. package/README.en.md +0 -826
  202. package/scripts/caliber_dedupe.py +0 -66
  203. package/scripts/engines_builders_batch16.py +0 -186
  204. package/scripts/health_probe.py +0 -253
  205. package/scripts/image_vision/vision_probe +0 -0
  206. package/scripts/social_engines/twitter_engine.py +0 -514
  207. package/scripts/sync_installs.py +0 -29
@@ -1,66 +0,0 @@
1
- #!/usr/bin/env python3
2
- """caliber_dedupe.py — 跨口径同 URL 合并(口径拼接之后的最后一道去重)。
3
-
4
- ## 为什么必须在口径拼接之后再做一次
5
-
6
- `caliber_isolation.merge_within_caliber` 只在**同一口径内**按 URL 折叠。
7
- 同一 URL 被不同口径的引擎同时命中时(维基词条既被百科源也被通用源返回),
8
- 拼接路径会让它出现两次:
9
-
10
- - 用户看到重复条目;
11
- - `ranking_eval` 的 nDCG 因为「同一相关项被计两次」算出大于 1 的值
12
- (实测金标 `consensus_vs_longtext` nDCG=1.4525,而定义上界是 1)。
13
-
14
- ## 去重不删证据
15
-
16
- 合并 `consensus_engines`、取最大 `_rrf_score`、保留更长的标题/摘要、
17
- 拼接 `source`。跨口径共识信号因此保留,而不是被当成重复丢掉。
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- from typing import Any
23
-
24
-
25
- def merge_cross_caliber_duplicates(
26
- rows: list[dict[str, Any]],
27
- canonical_url=None,
28
- ) -> list[dict[str, Any]]:
29
- """按归一 URL 合并跨口径重复条;无重复时原样返回。"""
30
- if not rows or len(rows) <= 1:
31
- return rows
32
- if canonical_url is None:
33
- from url_canon import canonical_url
34
- index: dict[str, dict[str, Any]] = {}
35
- out: list[dict[str, Any]] = []
36
- for r in rows:
37
- if not isinstance(r, dict):
38
- continue
39
- key = (
40
- canonical_url(r.get("url", ""))
41
- or (f"__title__:{r.get('title', '')}" if r.get("title") else "")
42
- or (f"__card__:{r.get('card_type', '')}" if r.get("card_type") else "")
43
- or f"__idx__:{id(r)}"
44
- )
45
- cur = index.get(key)
46
- if cur is None:
47
- index[key] = r
48
- out.append(r)
49
- continue
50
- cons = list(cur.get("consensus_engines") or [])
51
- for eng in r.get("consensus_engines") or []:
52
- if eng and eng not in cons:
53
- cons.append(eng)
54
- cur["consensus_engines"] = cons
55
- s_cur = float(cur.get("_rrf_score") or 0.0)
56
- s_new = float(r.get("_rrf_score") or 0.0)
57
- # IASF 跨口径独立共振:不同口径独立命中同一 URL 时叠加次口径 0.35 边际共振增益
58
- cur["_rrf_score"] = round(max(s_cur, s_new) + 0.35 * min(s_cur, s_new), 6)
59
- sources = {cur.get("source", ""), r.get("source", "")}
60
- cur["source"] = "/".join(s for s in sources if s)
61
- new_txt = f"{r.get('title', '')} {r.get('snippet', '')}"
62
- cur_txt = f"{cur.get('title', '')} {cur.get('snippet', '')}"
63
- if len(new_txt) > len(cur_txt):
64
- cur["title"] = r.get("title", cur.get("title"))
65
- cur["snippet"] = r.get("snippet", cur.get("snippet"))
66
- return out
@@ -1,186 +0,0 @@
1
- #!/usr/bin/env python3
2
- """批次十六构建器:独立搜索 / 数据集 / 学术论文(2026-11-10)。
3
-
4
- mwmbl Mwmbl 开源非盈利独立搜索引擎(JSON API,免 key)
5
- kaggle Kaggle 数据集搜索(免认证,含许可证/大小/版本)
6
- hf_papers Hugging Face Papers 论文检索(免认证,含 upvotes/作者)
7
-
8
- 为什么放 batch 而不是 engines_builders_data:data 是登记上限 2923 的
9
- 祖父文件,新引擎的下一站按既有惯例是 batch 模块(同 batch13/14/15)。
10
- 三源均经实测验证(health + quality 准入通过)后入库。
11
-
12
- 接口事实(2026-11-10 本机实测,非文档抄录):
13
-
14
- Mwmbl: GET https://mwmbl.org/api/v1/search/?s={q}&limit={n}
15
- 返回 [{"url","title":[{"value","is_bold"}],"extract":[{"value","is_bold"}],"source"}]
16
- title/extract 是 {value,is_bold} 数组,需拍平为字符串。
17
- 与 Marginalia/Wiby/Lieu/Mojeek 同族但索引互补(更偏技术社区与个人站)。
18
-
19
- Kaggle: GET https://www.kaggle.com/api/v1/datasets/list?search={q}&page=1
20
- 返回 [{"titleNullable","subtitleNullable","urlNullable","licenseNameNullable",
21
- "totalBytesNullable","usabilityRatingNullable","ref",...}]
22
- 字段名带 Nullable 后缀(Kaggle API 的 Java 序列化遗留)。
23
-
24
- HF Papers: GET https://huggingface.co/api/papers/search?q={q}&limit={n}
25
- 返回 [{"paper":{"id","title","authors","publishedAt","summary","upvotes"},
26
- "title","publishedAt","summary","upvotes",...}]
27
- 注意:/api/papers?search= 不过滤(只返回最新),必须用 /api/papers/search?q=。
28
- 与 arXiv/OpenAlex 互补:HF Papers 有社交信号(upvotes)与 AI 论文摘要。
29
- """
30
-
31
- from __future__ import annotations
32
-
33
- import json
34
- import logging
35
- import urllib.parse
36
- import urllib.request
37
- from typing import Any
38
-
39
- from engines_base import http_open, rank_score, safe_search
40
-
41
- logger = logging.getLogger("unified_search.engines")
42
-
43
- _UA = "argo-search/2.6 (unified-search@local)"
44
-
45
-
46
- def _flatten_segments(segments: Any) -> str:
47
- """把 Mwmbl 的 [{value, is_bold}] 数组拍平成纯文本。"""
48
- if not isinstance(segments, list):
49
- return ""
50
- return "".join(
51
- str(seg.get("value", "")) for seg in segments if isinstance(seg, dict)
52
- ).strip()
53
-
54
-
55
- def _build_mwmbl_engine(spec: dict[str, Any]) -> Any:
56
- """Mwmbl 开源非盈利独立搜索引擎(JSON API,免认证)。
57
-
58
- 与 Marginalia/Wiby/Lieu/Mojeek 同族但索引互补:Mwmbl 更偏技术社区与个人站。
59
- 上游返回的 title/extract 是 {value, is_bold} 数组,需拍平。
60
- """
61
- timeout = spec.get("timeout", 12)
62
-
63
- @safe_search
64
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
65
- to = _timeout or timeout
66
- url = "https://mwmbl.org/api/v1/search/?s=" + urllib.parse.quote(query) + "&limit=" + str(max(1, min(int(n or 5), 50)))
67
- try:
68
- with http_open(urllib.request.Request(
69
- url, headers={"User-Agent": _UA}), timeout=to, engine=spec.get("_name", "")) as resp:
70
- data = json.loads(resp.read().decode("utf-8", "replace"))
71
- except Exception as e:
72
- logger.warning(f"Mwmbl 失败: {e}")
73
- return []
74
- if not isinstance(data, list):
75
- return []
76
- results = []
77
- for _rk, r in enumerate(data[:n]):
78
- if not isinstance(r, dict):
79
- continue
80
- title = _flatten_segments(r.get("title"))
81
- extract = _flatten_segments(r.get("extract"))
82
- url_ = r.get("url") or ""
83
- if not title and not url_:
84
- continue
85
- results.append({
86
- "title": title[:200] or url_[:200],
87
- "url": url_,
88
- "snippet": extract[:300],
89
- "source": "mwmbl",
90
- "score": rank_score(0.7, _rk),
91
- })
92
- return results
93
- return _engine
94
-
95
-
96
- def _build_kaggle_engine(spec: dict[str, Any]) -> Any:
97
- """Kaggle 数据集搜索(免认证,结构化元数据)。
98
-
99
- 与 DataCite/Zenodo 互补:Kaggle 是社区数据集,含许可证/大小/版本/URL。
100
- 上游字段名带 Nullable 后缀(Kaggle API 的 Java 序列化遗留)。
101
- """
102
- timeout = spec.get("timeout", 12)
103
-
104
- @safe_search
105
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
106
- to = _timeout or timeout
107
- url = "https://www.kaggle.com/api/v1/datasets/list?search=" + urllib.parse.quote(query) + "&page=1"
108
- try:
109
- with http_open(urllib.request.Request(
110
- url, headers={"User-Agent": _UA}), timeout=to, engine=spec.get("_name", "")) as resp:
111
- data = json.loads(resp.read().decode("utf-8", "replace"))
112
- except Exception as e:
113
- logger.warning(f"Kaggle 失败: {e}")
114
- return []
115
- if not isinstance(data, list):
116
- return []
117
- results = []
118
- for _rk, r in enumerate(data[:n]):
119
- if not isinstance(r, dict):
120
- continue
121
- title = r.get("titleNullable") or r.get("title") or ""
122
- url_ = r.get("urlNullable") or r.get("url") or ""
123
- if not title and not url_:
124
- continue
125
- subtitle = r.get("subtitleNullable") or ""
126
- license_ = r.get("licenseNameNullable") or ""
127
- size = r.get("totalBytesNullable")
128
- parts = [p for p in (license_, f"{size} bytes" if size else "") if p]
129
- snippet = (subtitle[:200] + " · " + " · ".join(parts)) if parts else subtitle[:300]
130
- results.append({
131
- "title": title[:200],
132
- "url": url_,
133
- "snippet": snippet,
134
- "source": "kaggle",
135
- "score": rank_score(0.7, _rk),
136
- })
137
- return results
138
- return _engine
139
-
140
-
141
- def _build_hf_papers_engine(spec: dict[str, Any]) -> Any:
142
- """Hugging Face Papers 论文检索(免认证,含 upvotes/作者/发布日期)。
143
-
144
- 注意:/api/papers?search= 不过滤(只返回最新),必须用 /api/papers/search?q=。
145
- 与 arXiv/OpenAlex 互补:HF Papers 有社交信号(upvotes)与 AI 论文摘要。
146
- """
147
- timeout = spec.get("timeout", 15)
148
-
149
- @safe_search
150
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
151
- to = _timeout or timeout
152
- url = "https://huggingface.co/api/papers/search?q=" + urllib.parse.quote(query) + "&limit=" + str(max(1, min(int(n or 5), 20)))
153
- try:
154
- with http_open(urllib.request.Request(
155
- url, headers={"User-Agent": _UA}), timeout=to, engine=spec.get("_name", "")) as resp:
156
- data = json.loads(resp.read().decode("utf-8", "replace"))
157
- except Exception as e:
158
- logger.warning(f"HF Papers 失败: {e}")
159
- return []
160
- if not isinstance(data, list):
161
- return []
162
- results = []
163
- for _rk, r in enumerate(data[:n]):
164
- if not isinstance(r, dict):
165
- continue
166
- paper = r.get("paper") or {}
167
- pid = paper.get("id") or r.get("id") or ""
168
- title = paper.get("title") or r.get("title") or ""
169
- url_ = f"https://huggingface.co/papers/{pid}" if pid else ""
170
- if not title and not url_:
171
- continue
172
- authors = [a.get("name", "") for a in (paper.get("authors") or []) if isinstance(a, dict)][:3]
173
- published = paper.get("publishedAt") or r.get("publishedAt") or ""
174
- upvotes = paper.get("upvotes") or r.get("upvotes") or 0
175
- summary = paper.get("summary") or r.get("summary") or ""
176
- parts = [p for p in (published[:10], f"upvotes: {upvotes}" if upvotes else "", ", ".join(authors) if authors else "") if p]
177
- snippet = (summary[:200] + " · " + " · ".join(parts)) if parts else summary[:300]
178
- results.append({
179
- "title": title[:200],
180
- "url": url_,
181
- "snippet": snippet,
182
- "source": "hf_papers",
183
- "score": rank_score(0.7, _rk),
184
- })
185
- return results
186
- return _engine
@@ -1,253 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- health_probe.py — 引擎健康探针(v2.5 新增)
4
-
5
- 对 HTTP 引擎做可达性检查,结果写入 SQLite 供 route.py 查询。
6
- - 启动时全量探测
7
- - 每 5 分钟后台自动刷新
8
- - 连续 2 次失败标记 unavailable,1 次成功恢复
9
-
10
- 用法:
11
- python3 health_probe.py # 单次探测
12
- python3 health_probe.py --watch # 后台持续监控(每 5 分钟)
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import os
18
- import sqlite3
19
- import sys
20
- import threading
21
- import time
22
- import urllib.request
23
- from pathlib import Path
24
- from typing import Any
25
- from net_proxy import open_url # 出口调度唯一入口(issue #13 同类修复)
26
- from cli_io import dumps
27
- # 状态词表唯一真源:探针三态(2026-11-09 收口)
28
- import engine_states
29
-
30
- SCRIPT_DIR = Path(__file__).parent
31
- sys.path.insert(0, str(SCRIPT_DIR))
32
-
33
- try:
34
- from config import load_config, get_engines
35
- except ImportError:
36
- from config import load_config, get_engines
37
-
38
-
39
- # ── 路径 ──────────────────────────────────────────────────────────────────────
40
-
41
- def _db_path() -> Path:
42
- """状态库路径(惰性派生,支持 ARGO_STATE_DIR 覆盖)。"""
43
- import argo_paths
44
- return argo_paths.state_path("health.db")
45
-
46
-
47
- DB_PATH = _db_path() # 兼容旧引用
48
- PROBE_INTERVAL = 300 # 5 分钟
49
- PROBE_TIMEOUT = 1.5 # 单次探测超时(快,不能拖慢启动)
50
- MAX_FAILURES = engine_states.PROBE_MAX_FAILURES # 阈值真源见词表 §16
51
-
52
-
53
- # ── SQLite 存储 ───────────────────────────────────────────────────────────────
54
-
55
- def _connect():
56
- DB_PATH.parent.mkdir(parents=True, exist_ok=True)
57
- conn = sqlite3.connect(str(DB_PATH), timeout=5)
58
- import argo_paths
59
- argo_paths.apply_state_pragmas(conn)
60
- return conn
61
-
62
-
63
- def _init_db():
64
- with _connect() as conn:
65
- conn.execute("""
66
- CREATE TABLE IF NOT EXISTS engine_health (
67
- engine TEXT PRIMARY KEY,
68
- status TEXT NOT NULL DEFAULT 'unknown',
69
- consecutive_failures INTEGER DEFAULT 0,
70
- last_probe_at REAL DEFAULT 0,
71
- last_latency_ms REAL DEFAULT 0,
72
- last_error TEXT DEFAULT ''
73
- )
74
- """)
75
-
76
-
77
- def _probe_http(url: str, timeout: float = PROBE_TIMEOUT) -> tuple[bool, float, str]:
78
- """探测 HTTP 引擎:发起 HEAD 请求检查可达性。"""
79
- try:
80
- req = urllib.request.Request(url, method="HEAD")
81
- t0 = time.time()
82
- with open_url(req, timeout=timeout) as resp:
83
- elapsed = (time.time() - t0) * 1000
84
- return True, elapsed, ""
85
- except Exception as e:
86
- return False, 0, str(e)
87
-
88
-
89
- def _probe_cli(cmd: list[str], timeout: float = 2) -> tuple[bool, float, str]:
90
- """探测 CLI 引擎:检查命令是否存在。"""
91
- import subprocess
92
- if not cmd:
93
- return False, 0, "empty command"
94
- exe = cmd[0]
95
- if isinstance(exe, str) and exe.startswith("~"):
96
- exe = str(Path(exe).expanduser())
97
- try:
98
- import shutil
99
- if shutil.which(exe):
100
- return True, 0, ""
101
- return False, 0, f"command not found: {exe}"
102
- except Exception as e:
103
- return False, 0, str(e)
104
-
105
-
106
- def probe_all_engines():
107
- """探测 local_* 子引擎(route 健康过滤的唯一消费面)。
108
-
109
- 非 local 引擎不做 HEAD 探测:1.5s 超时对慢源误报严重(wikipedia 曾因
110
- 9 次探测失败被标 unavailable),且探测结果无人消费。网络延迟估计
111
- 以 adaptive 数据为主,health_probe 仅保底。
112
- """
113
- _init_db()
114
- cfg = load_config()
115
- engines = get_engines(cfg)
116
- results = {}
117
-
118
- for name, spec in engines.items():
119
- if not name.startswith("local_"):
120
- continue
121
- engine_type = spec.get("type", "")
122
- url = spec.get("url", "")
123
- cmd = spec.get("cmd", [])
124
-
125
- if engine_type == "http" and url:
126
- ok, latency, err = _probe_http(url)
127
- elif engine_type == "cli" and cmd:
128
- ok, latency, err = _probe_cli(cmd)
129
- else:
130
- continue
131
-
132
- # 更新数据库
133
- with _connect() as conn:
134
- row = conn.execute(
135
- "SELECT consecutive_failures FROM engine_health WHERE engine = ?",
136
- (name,),
137
- ).fetchone()
138
-
139
- if ok:
140
- new_status = engine_states.PROBE_STATUS_AVAILABLE
141
- new_failures = 0
142
- else:
143
- prev_failures = row[0] if row else 0
144
- new_failures = prev_failures + 1
145
- new_status = (engine_states.PROBE_STATUS_UNAVAILABLE
146
- if new_failures >= MAX_FAILURES
147
- else engine_states.PROBE_STATUS_DEGRADED)
148
-
149
- conn.execute(
150
- """INSERT OR REPLACE INTO engine_health
151
- (engine, status, consecutive_failures, last_probe_at, last_latency_ms, last_error)
152
- VALUES (?, ?, ?, ?, ?, ?)""",
153
- (name, new_status, new_failures, time.time(), latency, err),
154
- )
155
- conn.commit()
156
-
157
- results[name] = {
158
- "status": (engine_states.PROBE_STATUS_AVAILABLE if ok
159
- else engine_states.PROBE_STATUS_UNAVAILABLE),
160
- "latency_ms": round(latency, 1),
161
- "error": err,
162
- }
163
-
164
- return results
165
-
166
-
167
- def get_engine_status(engine: str) -> dict[str, Any]:
168
- """查询单个引擎的健康状态。单一真源:优先对齐熔断器证据。"""
169
- try:
170
- from circuit_breaker import get_breaker
171
- allowed, _ = get_breaker().allow(engine)
172
- if not allowed:
173
- return {
174
- "status": engine_states.PROBE_STATUS_UNAVAILABLE,
175
- "consecutive_failures": 999,
176
- "last_probe_at": time.time(),
177
- "last_latency_ms": None,
178
- "available": False,
179
- }
180
- except Exception:
181
- pass
182
-
183
- _init_db()
184
- with _connect() as conn:
185
- row = conn.execute(
186
- "SELECT status, consecutive_failures, last_probe_at, last_latency_ms FROM engine_health WHERE engine = ?",
187
- (engine,),
188
- ).fetchone()
189
- if not row:
190
- return {"status": engine_states.PROBE_STATUS_UNKNOWN,
191
- "consecutive_failures": 0, "available": True}
192
- return {
193
- "status": row[0],
194
- "consecutive_failures": row[1],
195
- "last_probe_at": row[2],
196
- "last_latency_ms": row[3],
197
- "available": engine_states.is_probe_available(row[0]),
198
- }
199
-
200
-
201
- def get_all_status() -> dict[str, dict[str, Any]]:
202
- """获取所有引擎的健康状态。"""
203
- _init_db()
204
- with _connect() as conn:
205
- rows = conn.execute(
206
- "SELECT engine, status, consecutive_failures, last_probe_at, last_latency_ms FROM engine_health"
207
- ).fetchall()
208
- return {
209
- row[0]: {
210
- "status": row[1],
211
- "consecutive_failures": row[2],
212
- "last_probe_at": row[3],
213
- "last_latency_ms": row[4],
214
- "available": engine_states.is_probe_available(row[1]),
215
- }
216
- for row in rows
217
- }
218
-
219
-
220
- def watch_background():
221
- """后台持续监控模式。在后台线程中运行,不阻塞 MCP 启动。"""
222
- def _loop():
223
- # 首次探测延迟 10 秒,让 MCP 先完成 initialize 握手
224
- time.sleep(10)
225
- try:
226
- probe_all_engines()
227
- except Exception:
228
- pass
229
- while True:
230
- time.sleep(PROBE_INTERVAL)
231
- try:
232
- probe_all_engines()
233
- except Exception:
234
- pass
235
-
236
- t = threading.Thread(target=_loop, daemon=True)
237
- t.start()
238
-
239
-
240
- # ── CLI ───────────────────────────────────────────────────────────────────────
241
-
242
- if __name__ == "__main__":
243
- if "--watch" in sys.argv:
244
- print("启动后台健康监控(每 5 分钟)...", file=sys.stderr)
245
- watch_background()
246
- try:
247
- while True:
248
- time.sleep(60)
249
- except KeyboardInterrupt:
250
- pass
251
- else:
252
- results = probe_all_engines()
253
- print(dumps(results))
Binary file