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
@@ -0,0 +1,383 @@
1
+ #!/usr/bin/env python3
2
+ """engines_mcp.py — MCP 通用连接器适配器(spec type: mcp)。
3
+
4
+ 把任意 MCP server(stdio 子进程或 Streamable HTTP)接入为 argo 搜索引擎。
5
+ 分层契约:
6
+
7
+ - 协议层通用:initialize 握手 → notifications/initialized → tools/call。
8
+ 响应可能是 application/json 或 text/event-stream(实测 mcp.grep.app 返回
9
+ SSE),Mcp-Session-Id 响应头存在则全程回传。
10
+ - 内容层声明式:structuredContent / JSON 文本走标准 output_map(与 http 引擎
11
+ 同一套字段映射、url_kind、引擎出处打标);纯文本工具声明 mode: text,用
12
+ text_split 分块正则 + item_*_regex 逐块抽字段。两类都不写每源代码。
13
+
14
+ spec 契约(engines/specs/<engine_id>.yaml)::
15
+
16
+ engine_id: grepapp_mcp
17
+ type: mcp
18
+ transport: http # http(Streamable HTTP)| stdio(子进程)
19
+ url: https://mcp.grep.app # http 传输端点
20
+ # command: [uvx, -y, some-server] # stdio 传输命令——必须是列表,禁 shell
21
+ tool: searchGitHub # 工具单一 allowlist,只可调用这一个
22
+ arguments: # 参数模板:{query}/{n}/{depth} 与 {ENV}
23
+ query: "{query}"
24
+ perPage: "{n}"
25
+ required_env: [ARGO_GREP_APP_API_KEY] # env 白名单真源;未配置的头不发送
26
+ headers: {} # http 可选;{ENV} 走 required_env 白名单
27
+ timeout: 20
28
+ output_map:
29
+ mode: json # 默认 json;纯文本工具显式声明 text
30
+ text_split: '\\n(?=Repository: )'
31
+ item_title_regex: 'Path: (.+)'
32
+ item_url_regex: 'URL: (\\S+)'
33
+ item_summary_regex: '(?s)--- Snippet 1 \\(Line \\d+\\) ---\\n(.*)'
34
+ explicit_only: true # 连接器默认不占自动路由预算
35
+ synthesized: true # 合成/新接入标记,人工确认后摘除
36
+
37
+ 安全边界:stdio 用列表参数 + build_child_env 白名单环境(禁 shell);
38
+ 不 eval 远端 payload;密钥不落日志;isError 的结果不产出条目(fail-visible)。
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import re
45
+ import select
46
+ import subprocess
47
+ import urllib.error
48
+ import urllib.request
49
+ from typing import Any
50
+
51
+ from engine_env import allowed_placeholders_for, build_child_env
52
+ from engines_base import (
53
+ _apply_url_kind,
54
+ _ensure_engine_source,
55
+ _get_logger,
56
+ _header_meaningful,
57
+ _parse_http_payload,
58
+ _resolve,
59
+ http_open,
60
+ safe_search,
61
+ )
62
+
63
+ _PROTOCOL_VERSION = "2025-06-18"
64
+ _TRANSPORTS = ("http", "stdio")
65
+ _JSON_RE = re.compile(r"^data:\s*(.+?)\s*$")
66
+
67
+
68
+ # ── JSON-RPC 响应解析(application/json 或 SSE data: 帧)─────────────────────
69
+
70
+ def _parse_jsonrpc_body(text: str) -> dict[str, Any] | None:
71
+ """整段 JSON 优先,SSE 逐 data: 行兜底,返回首个完整 JSON-RPC 对象。"""
72
+ try:
73
+ obj = json.loads(text)
74
+ if isinstance(obj, dict):
75
+ return obj
76
+ except (json.JSONDecodeError, ValueError):
77
+ pass
78
+ for line in text.splitlines():
79
+ line = line.strip()
80
+ if not line.startswith("data:"):
81
+ continue
82
+ payload = line[5:].strip()
83
+ if not payload:
84
+ continue
85
+ try:
86
+ obj = json.loads(payload)
87
+ except (json.JSONDecodeError, ValueError):
88
+ continue
89
+ if isinstance(obj, dict):
90
+ return obj
91
+ return None
92
+
93
+
94
+ # ── Streamable HTTP 通道 ─────────────────────────────────────────────────────
95
+
96
+ class _HttpChannel:
97
+ """Streamable HTTP JSON-RPC 通道(握手/回执/工具调用按 MCP 2025-06-18)。
98
+
99
+ HTTP 出口统一走 engines_base.http_open(egress 门禁 + 代理解析 + 失败
100
+ 归因,issue #13),与 http 引擎同一出口;不直连 urlopen。
101
+ """
102
+
103
+ def __init__(self, url: str, headers: dict[str, str], timeout: float,
104
+ eng: str = "") -> None:
105
+ self._url = url
106
+ self._headers = headers
107
+ self._timeout = timeout
108
+ self._eng = eng
109
+ self._session: str | None = None
110
+ self._next_id = 1
111
+
112
+ def _post(self, payload: dict[str, Any]) -> str:
113
+ body = json.dumps(payload).encode("utf-8")
114
+ headers = {
115
+ "Content-Type": "application/json",
116
+ "Accept": "application/json, text/event-stream",
117
+ **self._headers,
118
+ }
119
+ if self._session:
120
+ headers["Mcp-Session-Id"] = self._session
121
+ req = urllib.request.Request(self._url, data=body, headers=headers, method="POST")
122
+ with http_open(req, timeout=self._timeout, engine=self._eng) as resp:
123
+ sid = resp.headers.get("Mcp-Session-Id")
124
+ if sid:
125
+ self._session = sid
126
+ return resp.read().decode("utf-8", "replace")
127
+
128
+ def _request(self, method: str, params: dict[str, Any] | None = None,
129
+ *, notify: bool = False) -> dict[str, Any] | None:
130
+ payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
131
+ if notify:
132
+ payload.pop("id", None)
133
+ else:
134
+ payload["id"] = self._next_id
135
+ self._next_id += 1
136
+ if params is not None:
137
+ payload["params"] = params
138
+ raw = self._post(payload)
139
+ return None if notify else _parse_jsonrpc_body(raw)
140
+
141
+ def handshake(self) -> None:
142
+ self._request("initialize", {
143
+ "protocolVersion": _PROTOCOL_VERSION,
144
+ "capabilities": {},
145
+ "clientInfo": {"name": "argo", "version": "2.14.1"},
146
+ })
147
+ self._request("notifications/initialized", notify=True)
148
+
149
+ def call_tool(self, tool: str, arguments: dict[str, Any]) -> dict[str, Any] | None:
150
+ obj = self._request("tools/call", {"name": tool, "arguments": arguments})
151
+ if obj is None:
152
+ return None
153
+ if obj.get("error"):
154
+ err = obj["error"]
155
+ raise RuntimeError(f"MCP tools/call error: {err.get('code')} {err.get('message', '')[:200]}")
156
+ return obj.get("result")
157
+
158
+
159
+ # ── stdio 通道 ───────────────────────────────────────────────────────────────
160
+
161
+ class _StdioChannel:
162
+ """stdio 子进程 JSON-RPC 通道:换行分隔帧 + select 截止期读。"""
163
+
164
+ def __init__(self, command: list[str], env: dict[str, str], timeout: float) -> None:
165
+ self._timeout = timeout
166
+ self._proc = subprocess.Popen(
167
+ command,
168
+ stdin=subprocess.PIPE,
169
+ stdout=subprocess.PIPE,
170
+ stderr=subprocess.DEVNULL,
171
+ env=env,
172
+ shell=False,
173
+ text=True,
174
+ encoding="utf-8",
175
+ bufsize=1,
176
+ )
177
+ self._next_id = 1
178
+
179
+ def _exchange(self, payload: dict[str, Any], *, notify: bool) -> dict[str, Any] | None:
180
+ assert self._proc.stdin is not None and self._proc.stdout is not None
181
+ self._proc.stdin.write(json.dumps(payload) + "\n")
182
+ self._proc.stdin.flush()
183
+ if notify:
184
+ return None
185
+ deadline = self._timeout
186
+ stream = self._proc.stdout
187
+ while deadline > 0:
188
+ ready, _, _ = select.select([stream], [], [], min(deadline, 1.0))
189
+ if not ready:
190
+ deadline -= 1.0
191
+ continue
192
+ line = stream.readline()
193
+ if not line:
194
+ break
195
+ line = line.strip()
196
+ if not line:
197
+ continue
198
+ try:
199
+ obj = json.loads(line)
200
+ except (json.JSONDecodeError, ValueError):
201
+ continue
202
+ if isinstance(obj, dict) and obj.get("id") == payload.get("id"):
203
+ return obj
204
+ raise TimeoutError(f"MCP stdio 响应超时(工具 {payload.get('method')})")
205
+
206
+ def handshake(self) -> None:
207
+ self._exchange({
208
+ "jsonrpc": "2.0", "id": self._next_id, "method": "initialize",
209
+ "params": {
210
+ "protocolVersion": _PROTOCOL_VERSION,
211
+ "capabilities": {},
212
+ "clientInfo": {"name": "argo", "version": "2.14.1"},
213
+ },
214
+ }, notify=False)
215
+ self._next_id += 1
216
+ self._exchange({"jsonrpc": "2.0", "method": "notifications/initialized"}, notify=True)
217
+
218
+ def call_tool(self, tool: str, arguments: dict[str, Any]) -> dict[str, Any] | None:
219
+ self._next_id += 1
220
+ obj = self._exchange({
221
+ "jsonrpc": "2.0", "id": self._next_id, "method": "tools/call",
222
+ "params": {"name": tool, "arguments": arguments},
223
+ }, notify=False)
224
+ if obj is None:
225
+ return None
226
+ if obj.get("error"):
227
+ err = obj["error"]
228
+ raise RuntimeError(f"MCP tools/call error: {err.get('code')} {err.get('message', '')[:200]}")
229
+ return obj.get("result")
230
+
231
+ def close(self) -> None:
232
+ try:
233
+ self._proc.kill()
234
+ except OSError:
235
+ pass
236
+
237
+
238
+ # ── 内容层:MCP 结果 → argo 标准条目 ─────────────────────────────────────────
239
+
240
+ def _text_blocks(result: dict[str, Any]) -> str:
241
+ parts = []
242
+ for block in result.get("content") or []:
243
+ if isinstance(block, dict) and block.get("type") == "text":
244
+ t = block.get("text")
245
+ if isinstance(t, str) and t.strip():
246
+ parts.append(t)
247
+ return "\n\n".join(parts)
248
+
249
+
250
+ def _regex_first(pattern: str, text: str) -> str:
251
+ if not pattern:
252
+ return ""
253
+ m = re.search(pattern, text)
254
+ return (m.group(1) if m and m.groups() else m.group(0)) if m else ""
255
+
256
+
257
+ def _text_items(text: str, om: dict[str, Any], eng: str, n: int, spec: dict) -> list[dict[str, Any]]:
258
+ """mode: text——按 text_split 分块,逐块正则抽 title/url/snippet。"""
259
+ split_re = om.get("text_split") or ""
260
+ try:
261
+ chunks = re.split(split_re, text) if split_re else [text]
262
+ except re.error as e:
263
+ raise ValueError(f"output_map.text_split 非法正则: {e}") from e
264
+ rows: list[dict[str, Any]] = []
265
+ for chunk in chunks:
266
+ chunk = chunk.strip()
267
+ if not chunk:
268
+ continue
269
+ row = {
270
+ "title": _regex_first(om.get("item_title_regex", ""), chunk),
271
+ "url": _regex_first(om.get("item_url_regex", ""), chunk),
272
+ "snippet": _regex_first(om.get("item_summary_regex", ""), chunk),
273
+ }
274
+ if not (row["title"] or row["url"] or row["snippet"]):
275
+ continue
276
+ if row["snippet"]:
277
+ row["snippet"] = row["snippet"][:300]
278
+ if row["title"]:
279
+ row["title"] = row["title"][:200]
280
+ rows.append(row)
281
+ if len(rows) >= n:
282
+ break
283
+ return _apply_url_kind(_ensure_engine_source(rows, eng), spec)
284
+
285
+
286
+ def _result_to_items(result: dict[str, Any] | None, spec: dict, eng: str, n: int) -> list[dict[str, Any]]:
287
+ om = spec.get("output_map") or {}
288
+ mode = str(om.get("mode", "json")).lower()
289
+ if not isinstance(result, dict):
290
+ return []
291
+ if result.get("isError"):
292
+ _get_logger().warning(f"引擎 {eng} MCP 工具 isError: {_text_blocks(result)[:200]}")
293
+ return []
294
+ if mode == "text":
295
+ return _text_items(_text_blocks(result), om, eng, n, spec)
296
+ data = result.get("structuredContent")
297
+ if data is None:
298
+ blob = _text_blocks(result).strip()
299
+ if not blob:
300
+ return []
301
+ try:
302
+ data = json.loads(blob)
303
+ except (json.JSONDecodeError, ValueError):
304
+ raise ValueError(
305
+ f"引擎 {eng} 工具返回非 JSON 文本;纯文本工具须在 output_map 声明 mode: text")
306
+ return _parse_http_payload(json.dumps(data, ensure_ascii=False), "json", eng, n, om, spec)
307
+
308
+
309
+ # ── builder ──────────────────────────────────────────────────────────────────
310
+
311
+ def _build_mcp_engine(spec: dict[str, Any]) -> Any:
312
+ """type: mcp 统一构造(stdio / Streamable HTTP 双传输)。"""
313
+ eng = spec.get("_name", "")
314
+ transport = str(spec.get("transport", "")).lower()
315
+ if transport not in _TRANSPORTS:
316
+ raise ValueError(f"引擎 {eng} type: mcp 需要 transport: http|stdio,得 {transport!r}")
317
+ tool = str(spec.get("tool", "")).strip()
318
+ if not tool:
319
+ raise ValueError(f"引擎 {eng} type: mcp 必须声明 tool(单一 allowlist)")
320
+ timeout = float(spec.get("timeout", 20))
321
+ arguments_template = dict(spec.get("arguments") or {})
322
+ allowed = allowed_placeholders_for(eng, spec)
323
+
324
+ command: list[str] = []
325
+ if transport == "stdio":
326
+ raw_command = spec.get("command")
327
+ # 必须是列表:字符串会被逐字符拆开(且 shell 形态在禁用之列)
328
+ if not isinstance(raw_command, list) or not raw_command or \
329
+ not all(isinstance(c, str) and c.strip() for c in raw_command):
330
+ raise ValueError(
331
+ f"引擎 {eng} stdio 传输必须声明非空 command 字符串列表(禁 shell)")
332
+ command = [str(c) for c in raw_command]
333
+ elif not str(spec.get("url", "")).strip().startswith(("http://", "https://")):
334
+ raise ValueError(f"引擎 {eng} http 传输需要合法 url")
335
+
336
+ @safe_search
337
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, depth: str = "fast", **kwargs) -> list[dict[str, Any]]:
338
+ to = _timeout or timeout
339
+ # env/header 在每次请求时解析(对齐 http builder):daemon 下密钥热轮换
340
+ # 与 envfile 热读不失效;未配置的 {ENV} 头由 _header_meaningful 过滤。
341
+ env = build_child_env(eng, spec) if transport == "stdio" else {}
342
+ headers = {}
343
+ if transport == "http":
344
+ headers = {
345
+ k: v for k, v in (
346
+ (k, _resolve(str(v), query, n, allowed_env=allowed, **kwargs))
347
+ for k, v in (spec.get("headers") or {}).items()
348
+ ) if _header_meaningful(v)
349
+ }
350
+ args: dict[str, Any] = {}
351
+ for k, v in arguments_template.items():
352
+ resolved = _resolve(str(v), query, n, allowed_env=allowed, depth=depth, **kwargs)
353
+ if isinstance(resolved, list):
354
+ resolved = " ".join(resolved)
355
+ if resolved.lower() == "true":
356
+ args[k] = True
357
+ elif resolved.lower() == "false":
358
+ args[k] = False
359
+ else:
360
+ try:
361
+ args[k] = int(resolved)
362
+ except ValueError:
363
+ try:
364
+ args[k] = float(resolved)
365
+ except ValueError:
366
+ args[k] = resolved
367
+ channel: Any
368
+ if transport == "stdio":
369
+ channel = _StdioChannel(command, env, to)
370
+ else:
371
+ channel = _HttpChannel(str(spec.get("url")), headers, to, eng=eng)
372
+ try:
373
+ channel.handshake()
374
+ result = channel.call_tool(tool, args)
375
+ except (urllib.error.URLError, TimeoutError, RuntimeError, OSError) as e:
376
+ _get_logger().warning(f"引擎 {eng} MCP 调用失败: {type(e).__name__}: {e}")
377
+ return []
378
+ finally:
379
+ if isinstance(channel, _StdioChannel):
380
+ channel.close()
381
+ return _result_to_items(result, spec, eng, n)
382
+
383
+ return _engine
@@ -38,8 +38,19 @@ image_url / upstream(均为可选,缺省由下游补)。
38
38
  from __future__ import annotations
39
39
 
40
40
  import html as _htmllib
41
+ import re
42
+ from pathlib import Path
41
43
  from typing import Any, Callable
42
44
 
45
+ # 字段取值与模板渲染下沉到 engines_fields(无反向依赖),供本模块与
46
+ # engines_schema_drift 共用,消除 parsers ↔ drift 的循环导入。
47
+ from engines_fields import (
48
+ _coerce_field,
49
+ _dig,
50
+ _format_url_template,
51
+ extract_items,
52
+ )
53
+
43
54
  # 解析器签名:(原始数据, spec) -> 标准结果行列表
44
55
  Parser = Callable[[Any, dict], list[dict]]
45
56
 
@@ -98,6 +109,105 @@ def resolve(spec: dict) -> list[Parser]:
98
109
  return [get(n) for n in names]
99
110
 
100
111
 
112
+ # ─────────────────────────────────────────────────────────────────────────────
113
+ # 声明式字段映射(output_map 的通用实现)
114
+ # ─────────────────────────────────────────────────────────────────────────────
115
+ #
116
+ # 为什么放在这里:2026-11-10 归一 13 个专用 builder 时发现,原 builder 常把
117
+ # 多个上游字段拼进 snippet(cleveland 的 `tombstone · 授权 CC0`、deezer 的
118
+ # `Deezer 音乐人 · 专辑 N · 粉丝 M`),而 output_map 只能取单个字段——归一后
119
+ # 这类信息会静默丢失。把「拼接」变成声明式能力,属于解析层职责,故与
120
+ # `parse_*` 解析器同文件维护;engines_base 只做委托调用。
121
+
122
+ def _render_field_template(template: str, item: dict) -> str:
123
+ """模板插值:`{field}` 取条目字段(支持点分路径),空值置空并折叠分隔符。
124
+
125
+ 与 URL 模板的区别:URL 模板任一占位为空则整体落空(否则拼出半截链接),
126
+ 而文本模板把空占位折叠掉——少一段仍是有效文本。
127
+ 连续/首尾的 `·`/`⇄`/`|` 分隔符会折叠,避免缺字段留下 `a · · b` 残渣。
128
+ """
129
+ def _repl(m: re.Match) -> str:
130
+ return _coerce_field(_dig(item, m.group(1)))
131
+
132
+ out = re.sub(r"\{([^}]+)\}", _repl, template)
133
+ out = re.sub(r"(?:\s*[·⇄|]\s*)+", lambda m: " " + next(
134
+ (ch for ch in m.group(0) if ch in "·⇄|"), "·") + " ", out)
135
+ out = out.strip()
136
+ out = re.sub(r"(?:^\s*[·⇄|]\s*|\s*[·⇄|]\s*$)", "", out)
137
+ return out.strip()
138
+
139
+
140
+ def make_field_parser(path: str, fields: dict[str, str], url_template: str | None = None,
141
+ max_items: int = 10, templates: dict[str, str] | None = None,
142
+ url_item_template: str | None = None) -> Callable:
143
+ """构造声明式 parser。支持点分路径字段、url_template(含嵌套占位)与模板拼接。
144
+
145
+ `templates` 是可选的模板字段映射(`{item_title, item_summary}`),声明后
146
+ 覆盖同名 `fields` 条目——用于需要多字段拼接的源(见 `_render_field_template`)。
147
+
148
+ `url_item_template` 是**逐条目**的 URL 拼接模板(如 eu_opendata 的
149
+ `landing_page.0.resource` 数组取首项)。与 `url_template` 的区别:后者用
150
+ `_format_url_template` 且任一占位为空即整体落空;前者在取不到值时保持
151
+ 「不声明 URL」,交给通用推断或下游补。
152
+ """
153
+ templates = templates or {}
154
+
155
+ def parser(data: Any) -> list[dict[str, Any]]:
156
+ if isinstance(data, list) and path in ("", ".", "$", "[]"):
157
+ items = data
158
+ elif isinstance(data, dict):
159
+ items = extract_items(data, path)
160
+ else:
161
+ items = []
162
+ results = []
163
+ for item in items:
164
+ if not isinstance(item, dict):
165
+ continue
166
+ r: dict[str, Any] = {}
167
+ for ok, ik in fields.items():
168
+ if not ik:
169
+ continue
170
+ raw = _dig(item, ik) if "." in str(ik) else item.get(ik, "")
171
+ if raw in ("", None) and "." not in str(ik):
172
+ raw = item.get(ik, "")
173
+ coerced = _coerce_field(raw, max_len=300 if ok == "snippet" else 500)
174
+ if coerced:
175
+ r[ok] = coerced
176
+ # 模板字段优先于同名单字段映射(声明式拼接覆盖单字段取值)。
177
+ # 键名是 output_map 的声明名(item_title_template),落到标准行字段
178
+ # 名(title/snippet)——不转换会把结果写进 `item_summary_template` 键。
179
+ # 模板渲染为空时**回落**到单字段映射(如 tatoeba 无译文时用 lang),
180
+ # 而不是把已取到的值覆盖成空。
181
+ for ok, tmpl in templates.items():
182
+ if not tmpl:
183
+ continue
184
+ std = {"item_title_template": "title",
185
+ "item_summary_template": "snippet",
186
+ "item_image_template": "image_url"}.get(ok, ok)
187
+ rendered = (_format_url_template(tmpl, item) if std == "image_url"
188
+ else _render_field_template(tmpl, item))
189
+ if rendered:
190
+ r[std] = rendered[:300 if std == "snippet" else 500]
191
+ if url_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
192
+ built = _format_url_template(url_template, item)
193
+ if built.startswith(("http://", "https://")):
194
+ r["url"] = built
195
+ else:
196
+ r.pop("url", None)
197
+ # 逐条目 URL 模板:占位取自条目自身(如 landing_page.0.resource),
198
+ # 取不到就保持无 URL(不造半截链接)。
199
+ if url_item_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
200
+ built = _format_url_template(url_item_template, item)
201
+ if built.startswith(("http://", "https://")):
202
+ r["url"] = built
203
+ if isinstance(r.get("url"), str) and r["url"].startswith("//"):
204
+ r["url"] = "https:" + r["url"]
205
+ if r.get("title") or r.get("url"):
206
+ results.append(r)
207
+ return results[:max_items]
208
+ return parser
209
+
210
+
101
211
  # ─────────────────────────────────────────────────────────────────────────────
102
212
  # 内置解析器
103
213
  # ─────────────────────────────────────────────────────────────────────────────
@@ -167,24 +277,6 @@ def _strip_tags(text: str) -> str:
167
277
  return _TAG_RE.sub("", text)
168
278
 
169
279
 
170
- def _dig(obj: Any, path: str) -> Any:
171
- """按点分路径取嵌套值;路径段为数字时按数组索引。"""
172
- if not path:
173
- return obj
174
- cur = obj
175
- for seg in path.split("."):
176
- if isinstance(cur, list):
177
- try:
178
- cur = cur[int(seg)]
179
- except (ValueError, IndexError):
180
- return None
181
- elif isinstance(cur, dict):
182
- cur = cur.get(seg)
183
- else:
184
- return None
185
- return cur
186
-
187
-
188
280
  def _flatten_segments(val: Any) -> str:
189
281
  """把 [{value, is_bold}, ...] 数组展平成纯文本。
190
282
 
@@ -231,11 +323,55 @@ def parse_mwmbl(data: Any, spec: dict) -> list[dict]:
231
323
  return results
232
324
 
233
325
 
326
+ def parse_artic(data: Any, spec: dict) -> list[dict]:
327
+ """Art Institute of Chicago 响应解析(L2:IIIF 图片需响应级 config 拼接)。
328
+
329
+ 上游把 IIIF 基础地址放在响应的 `config.iiif_url`(不在条目里),图片直链
330
+ 是 `{iiif_url}/{image_id}/full/843,/0/default.jpg`。这类「拼接依赖响应级
331
+ 配置」的解析无法用 output_map 声明,故注册专用解析器——协议标准、解析变体。
332
+
333
+ image_id 为空时**不产出** image_url(不得凭空造链接,见 test_image_sources)。
334
+ """
335
+ if not isinstance(data, dict):
336
+ return []
337
+ source = spec.get("engine_id", "artic")
338
+ iiif = str(((data.get("config") or {}).get("iiif_url") or "")).rstrip("/")
339
+ rows = data.get("data") if isinstance(data.get("data"), list) else []
340
+ results = []
341
+ for _rk, it in enumerate(rows):
342
+ if not isinstance(it, dict):
343
+ continue
344
+ title = str(it.get("title") or "").strip()
345
+ art_id = it.get("id")
346
+ url_ = f"https://www.artic.edu/artworks/{art_id}" if art_id else ""
347
+ if not title and not url_:
348
+ continue
349
+ row = {
350
+ "title": title[:200],
351
+ "url": url_,
352
+ "snippet": str(it.get("artist_display") or "")[:300],
353
+ "source": source,
354
+ "score": max(0.0, 0.7 - _rk * 0.05),
355
+ }
356
+ image_id = str(it.get("image_id") or "").strip()
357
+ if iiif and image_id:
358
+ row["image_url"] = f"{iiif}/{image_id}/full/843,/0/default.jpg"
359
+ # AIC 是 CC0 开放图像;授权缺失时按无授权处理,不凭空标注
360
+ lic = str(it.get("copyright_notice") or "").strip()
361
+ if lic:
362
+ row["image_license"] = lic
363
+ else:
364
+ row["image_license"] = "CC0(芝加哥艺术博物馆开放图像)"
365
+ results.append(row)
366
+ return results
367
+
368
+
234
369
  # 注册通用解析器
235
370
  register("array_at", parse_array_at)
236
371
  register("object_root", parse_object_root)
237
372
  register("strip_fields", parse_strip_fields)
238
373
  register("mwmbl", parse_mwmbl)
374
+ register("artic", parse_artic)
239
375
 
240
376
 
241
377
  def parse_smart_generic(data: Any, engine_name: str = "?",
@@ -297,34 +433,66 @@ def parse_smart_generic(data: Any, engine_name: str = "?",
297
433
  if not isinstance(i, dict):
298
434
  continue
299
435
  flat = dict(i)
300
- for nested_k in ("paper", "item", "data", "node", "article", "entry"):
436
+ for nested_k in ("paper", "item", "data", "node", "article", "entry", "show", "bibjson"):
301
437
  if isinstance(i.get(nested_k), dict):
302
438
  for k, v in i[nested_k].items():
303
439
  flat.setdefault(k, v)
304
440
 
305
441
  title = (
306
442
  flat.get("title") or flat.get("name") or flat.get("heading")
307
- or flat.get("Title") or flat.get("titleNullable")
308
- or flat.get("headline") or flat.get("subject") or flat.get("topic") or ""
443
+ or flat.get("Title") or flat.get("titleNullable") or flat.get("title_s")
444
+ or flat.get("headline") or flat.get("subject") or flat.get("topic")
445
+ or flat.get("text") or flat.get("cycle") or ""
309
446
  )
310
- if isinstance(title, list):
447
+ if isinstance(title, dict):
448
+ # 多语言字典(如 EU Open Data):优先取 en/zh/fr/de,否则取首个
449
+ for lang in ("en", "zh", "fr", "de"):
450
+ if title.get(lang):
451
+ title = title[lang]
452
+ break
453
+ if isinstance(title, dict) and title:
454
+ title = next(iter(title.values()))
455
+ elif isinstance(title, list):
311
456
  title = title[0] if title else ""
312
457
  raw_id = flat.get("id") or flat.get("objectID") or flat.get("ID") or ""
313
458
  url = (
314
459
  flat.get("url") or flat.get("URL") or flat.get("html_url")
315
460
  or flat.get("link") or flat.get("href") or flat.get("urlNullable")
316
- or flat.get("web_url") or flat.get("canonical_url") or ""
461
+ or flat.get("web_url") or flat.get("canonical_url") or flat.get("guid")
462
+ or flat.get("uri_s") or flat.get("url_public_html")
463
+ or flat.get("resource") or flat.get("landing_page") or ""
317
464
  )
318
- if not url and url_template and raw_id:
465
+ if isinstance(url, list) and url:
466
+ if isinstance(url[0], dict):
467
+ url = url[0].get("url") or url[0].get("href") or url[0].get("resource") or ""
468
+ else:
469
+ url = str(url[0])
470
+ if not url and url_template:
319
471
  url = url_template.replace("{id}", str(raw_id))
472
+ for _k, _v in flat.items():
473
+ if f"{{{_k}}}" in url:
474
+ url = url.replace(f"{{{_k}}}", str(_v))
320
475
 
321
476
  snippet = (
322
477
  flat.get("snippet") or flat.get("summary") or flat.get("content")
323
- or flat.get("description") or flat.get("abstract")
478
+ or flat.get("description") or flat.get("abstract") or flat.get("abstract_s")
324
479
  or flat.get("subtitleNullable") or flat.get("subtitle")
325
480
  or flat.get("extract") or flat.get("details") or flat.get("text") or ""
326
481
  )
327
- if isinstance(snippet, list):
482
+ if not snippet and (flat.get("eol") or flat.get("latest")):
483
+ _sp = [f"最新 {flat['latest']}" if flat.get("latest") else "",
484
+ f"发布 {flat['releaseDate']}" if flat.get("releaseDate") else "",
485
+ f"支持至 {flat['support']}" if flat.get("support") else "",
486
+ f"EOL {flat['eol']}" if flat.get("eol") else ""]
487
+ snippet = " · ".join(x for x in _sp if x)
488
+ if isinstance(snippet, dict):
489
+ for lang in ("en", "zh", "fr", "de"):
490
+ if snippet.get(lang):
491
+ snippet = snippet[lang]
492
+ break
493
+ if isinstance(snippet, dict) and snippet:
494
+ snippet = next(iter(snippet.values()))
495
+ elif isinstance(snippet, list):
328
496
  snippet = snippet[0] if snippet else ""
329
497
 
330
498
  # 文本标签剥离与 HTML 实体反转义
@@ -339,7 +507,8 @@ def parse_smart_generic(data: Any, engine_name: str = "?",
339
507
 
340
508
  published_at = (
341
509
  flat.get("published_at") or flat.get("publishedAt")
342
- or flat.get("created_at") or flat.get("pubdate") or flat.get("date") or ""
510
+ or flat.get("created_at") or flat.get("pubdate") or flat.get("date")
511
+ or flat.get("premiered") or flat.get("first_air_date") or ""
343
512
  )
344
513
  if published_at:
345
514
  try: