argo-search 2.9.9 → 2.10.1

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 (104) hide show
  1. package/README.en.md +39 -22
  2. package/README.es.md +39 -22
  3. package/README.ja.md +38 -21
  4. package/README.ko.md +38 -21
  5. package/README.md +41 -22
  6. package/SKILL.md +13 -12
  7. package/backends/domain_profiles.json +76 -0
  8. package/backends/engine_registry.yaml +163 -7
  9. package/backends/quota_profiles.json +122 -2
  10. package/backends/source_types_cn.json +9 -0
  11. package/bin/argo +22 -1
  12. package/bin/argo.js +3 -3
  13. package/config.yaml +150 -30
  14. package/docs/ARGO_INTRO.md +4 -4
  15. package/docs/ENGINE_CATALOG.md +68 -48
  16. package/docs/MCP_SETUP.md +1 -1
  17. package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
  18. package/docs/RELEASE_NOTES_v2.10.1.md +57 -0
  19. package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
  20. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
  21. package/engines/_template_http.yaml +2 -0
  22. package/engines/specs/clawhub.yaml +16 -15
  23. package/engines/specs/deepseek1024.yaml +46 -0
  24. package/engines/specs/dsh_hub.yaml +44 -0
  25. package/engines/specs/dshopen.yaml +32 -0
  26. package/engines/specs/explainx.yaml +32 -0
  27. package/engines/specs/gbfs_nyc.yaml +6 -1
  28. package/engines/specs/metaso_doc.yaml +49 -0
  29. package/engines/specs/metaso_image.yaml +65 -0
  30. package/engines/specs/metaso_podcast.yaml +60 -0
  31. package/engines/specs/metaso_scholar.yaml +57 -0
  32. package/engines/specs/metaso_video.yaml +62 -0
  33. package/engines/specs/ncpssd.yaml +44 -0
  34. package/engines/specs/sciverse.yaml +73 -0
  35. package/engines/specs/skills_sh.yaml +32 -0
  36. package/engines/specs/skillsmp.yaml +18 -16
  37. package/package.json +4 -2
  38. package/packages/dsh-plugin/README.md +3 -2
  39. package/packages/dsh-plugin/package.json +1 -1
  40. package/packages/dsh-plugin/test/size-gate.test.js +113 -0
  41. package/scripts/adaptive.py +41 -14
  42. package/scripts/article.py +6 -1
  43. package/scripts/article_meta.py +151 -2
  44. package/scripts/bench_general_pool.py +145 -0
  45. package/scripts/candidate_envelope.py +45 -4
  46. package/scripts/charset_decode.py +127 -0
  47. package/scripts/ci_drift_gate.py +47 -24
  48. package/scripts/crawl.py +240 -74
  49. package/scripts/crawl_frontier.py +217 -0
  50. package/scripts/crawl_policy.py +174 -0
  51. package/scripts/engine_dispatch.py +23 -18
  52. package/scripts/engine_failure.py +15 -0
  53. package/scripts/engine_status.py +12 -5
  54. package/scripts/engine_validate.py +8 -0
  55. package/scripts/engines.py +15 -0
  56. package/scripts/engines_base.py +43 -15
  57. package/scripts/engines_builders.py +14 -0
  58. package/scripts/engines_builders_data.py +10 -3
  59. package/scripts/engines_builders_dsh.py +330 -0
  60. package/scripts/engines_builders_skill.py +314 -0
  61. package/scripts/evidence.py +26 -5
  62. package/scripts/fetch_v3.py +37 -5
  63. package/scripts/gen_engine_catalog.py +218 -2
  64. package/scripts/general_pool.py +162 -0
  65. package/scripts/http_client.py +38 -42
  66. package/scripts/image_ops.py +4 -0
  67. package/scripts/install.ps1 +47 -19
  68. package/scripts/install.sh +45 -20
  69. package/scripts/local_seek.py +53 -11
  70. package/scripts/matrix_search_eval.py +17 -1
  71. package/scripts/mcp_transport.py +1 -1
  72. package/scripts/ncpssd_bridge.py +123 -0
  73. package/scripts/paid_policy.py +109 -13
  74. package/scripts/pre-commit +19 -4
  75. package/scripts/query_signals.py +156 -3
  76. package/scripts/redskill/redskill_engine.py +29 -2
  77. package/scripts/release.py +398 -0
  78. package/scripts/release_check.py +209 -0
  79. package/scripts/retry_policy.py +22 -1
  80. package/scripts/robots_guard.py +26 -0
  81. package/scripts/route.py +11 -8
  82. package/scripts/route_cache.py +6 -0
  83. package/scripts/route_combo.py +37 -59
  84. package/scripts/route_domains.py +22 -3
  85. package/scripts/route_policy.py +6 -0
  86. package/scripts/search.py +13 -3
  87. package/scripts/search_cli.py +49 -0
  88. package/scripts/search_entry.py +9 -0
  89. package/scripts/search_output.py +43 -0
  90. package/scripts/search_pipeline.py +43 -3
  91. package/scripts/search_rank.py +4 -1
  92. package/scripts/serp_guard.py +11 -0
  93. package/scripts/social_engines/bilibili_engine.py +163 -26
  94. package/scripts/social_engines/reddit_engine.py +52 -51
  95. package/scripts/source_selection.py +302 -0
  96. package/scripts/url_canon.py +2 -1
  97. package/scripts/video_fetch.py +303 -0
  98. package/scripts/video_meta.py +225 -0
  99. package/scripts/video_route.py +65 -0
  100. package/scripts/watch.py +123 -0
  101. package/sub-skills/local-seek/scripts/seek.py +19 -4
  102. package/engines/specs/_cisa_kev.yaml +0 -54
  103. package/engines/specs/_osv.yaml +0 -63
  104. package/scripts/local_engines.py +0 -321
@@ -7,16 +7,25 @@
7
7
  研究/报告场景里作者与站点名也是引用格式的必需字段。它们都在同一份 HTML 里,
8
8
  一次解析就能拿到,不该让调用方付第二次网络往返。
9
9
 
10
+ 2026-10-26 补 JSON-LD(对标 pagesift 的结构化数据提取):新闻站的日期与
11
+ 作者最可靠来源是 <script type="application/ld+json"> 的 datePublished/author,
12
+ 很多站没有 article:published_time meta 却一定有 JSON-LD。同一次解析顺手拿到,
13
+ 零新增请求。meta 标签与 JSON-LD 同时存在时 meta 优先(既有行为不变)。
14
+
10
15
  边界:
11
16
  - 纯标准库 HTMLParser,毫秒级;不做正文判定(那是 readability 的职责)。
12
17
  - 链接只取 <article>/<main> 内。没有语义容器时宁可不给,也不把
13
18
  nav/header/footer 的导航链接当正文引用;相对链接按页面 URL 解析。
14
- - 标题/摘要/站点名只读 meta,不从正文猜;猜错比缺失更糟。
19
+ - 标题/摘要/站点名只读 meta 与 JSON-LD,不从正文猜;猜错比缺失更糟。
20
+ - JSON-LD 日期解析不出时交空串丢弃,不透传原文(原样透传「有字段但读不出
21
+ 日期」比缺失更糟,同 engines_builders_batch15._norm_date 的教训)。
15
22
  - 全部字段都可能缺失,调用方按 key 是否存在判断,不返回空字符串占位。
16
23
  """
17
24
 
18
25
  from __future__ import annotations
19
26
 
27
+ import json
28
+ import re
20
29
  from html.parser import HTMLParser
21
30
  from urllib.parse import urljoin, urlparse
22
31
 
@@ -34,6 +43,11 @@ _META_KEYS = {
34
43
  "twitter:description": "excerpt",
35
44
  "article:published_time": "published_at",
36
45
  }
46
+ _LDJSON_TYPE = "application/ld+json"
47
+ _LD_SCRIPT_CAP = 8 # 只吃前 8 段 ld+json,防御性上限
48
+ _LD_SCRIPT_MAX = 262144 # 单段 256KB,防御超大内联 JSON
49
+ _LD_ARTICLE_HINTS = ("article", "posting", "news", "blog", "report",
50
+ "webpage", "itempage")
37
51
 
38
52
 
39
53
  class _MetaParser(HTMLParser):
@@ -41,10 +55,14 @@ class _MetaParser(HTMLParser):
41
55
  super().__init__(convert_charrefs=True)
42
56
  self.meta: dict[str, str] = {}
43
57
  self.article_links: list[dict[str, str]] = []
58
+ self.ld_jsons: list[str] = []
44
59
  self._in_article = 0
45
60
  self._skip = 0
46
61
  self._href: str | None = None
47
62
  self._text: list[str] = []
63
+ self._ld_active = False
64
+ self._ld_buf: list[str] = []
65
+ self._ld_len = 0
48
66
 
49
67
  def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
50
68
  tag = tag.lower()
@@ -56,6 +74,11 @@ class _MetaParser(HTMLParser):
56
74
  if field and value and field not in self.meta:
57
75
  self.meta[field] = value.strip()[:MAX_TEXT]
58
76
  return
77
+ if tag == "script":
78
+ data = {k.lower(): (v or "") for k, v in attrs if k}
79
+ self._ld_active = (data.get("type") or "").strip().lower() == _LDJSON_TYPE
80
+ self._ld_buf = []
81
+ self._ld_len = 0
59
82
  if tag in _SKIP_TAGS:
60
83
  self._skip += 1
61
84
  return
@@ -73,6 +96,11 @@ class _MetaParser(HTMLParser):
73
96
 
74
97
  def handle_endtag(self, tag: str) -> None:
75
98
  tag = tag.lower()
99
+ if tag == "script":
100
+ if self._ld_active:
101
+ self._ld_active = False
102
+ if self._ld_buf:
103
+ self.ld_jsons.append("".join(self._ld_buf))
76
104
  if tag in _SKIP_TAGS:
77
105
  self._skip = max(0, self._skip - 1)
78
106
  return
@@ -86,14 +114,132 @@ class _MetaParser(HTMLParser):
86
114
  self._text = []
87
115
 
88
116
  def handle_data(self, data: str) -> None:
117
+ if self._ld_active:
118
+ if self._ld_len < _LD_SCRIPT_MAX:
119
+ self._ld_buf.append(data)
120
+ self._ld_len += len(data)
121
+ return
89
122
  if self._href is not None and self._skip == 0:
90
123
  self._text.append(data)
91
124
 
92
125
 
126
+ # ─── JSON-LD 展开与字段提取 ─────────────────────────────────────────────────
127
+
128
+ def _iter_ld_nodes(data) -> list[dict]:
129
+ """展开 ld+json 常见容器:顶层数组、@graph(含嵌套),保持文档顺序。"""
130
+ out: list[dict] = []
131
+ queue = [data]
132
+ while queue:
133
+ cur = queue.pop(0)
134
+ if isinstance(cur, list):
135
+ queue.extend(cur)
136
+ elif isinstance(cur, dict):
137
+ out.append(cur)
138
+ graph = cur.get("@graph")
139
+ if graph is not None:
140
+ queue.extend(graph if isinstance(graph, list) else [graph])
141
+ return out
142
+
143
+
144
+ def _ld_is_article(node: dict) -> bool:
145
+ t = node.get("@type")
146
+ if isinstance(t, list):
147
+ t = " ".join(str(x) for x in t)
148
+ t = str(t or "").lower()
149
+ return any(h in t for h in _LD_ARTICLE_HINTS)
150
+
151
+
152
+ def _ld_name(value) -> str:
153
+ """author/publisher 的形态归一:str / {name} / [{name},...]。"""
154
+ if isinstance(value, str):
155
+ return value.strip()
156
+ if isinstance(value, dict):
157
+ name = value.get("name")
158
+ return name.strip() if isinstance(name, str) else ""
159
+ if isinstance(value, list):
160
+ parts = [n for n in (_ld_name(v) for v in value) if n]
161
+ return ", ".join(parts)
162
+ return ""
163
+
164
+
165
+ def _ld_date(value) -> str:
166
+ """JSON-LD 日期 → ISO 前缀规整;解析不出交空串(原样透传比空更糟)。
167
+
168
+ ISO 带时区的(datePublished 主流形态)原样保留;`2026/10/1`、
169
+ `2026年10月1日` 规整成 `2026-10-01`;裸时间补 T。
170
+ """
171
+ text = str(value or "").strip()
172
+ if not text:
173
+ return ""
174
+ m = re.match(r"(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})", text)
175
+ if not m:
176
+ m = re.match(r"(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?", text)
177
+ if not m:
178
+ return ""
179
+ y, mo, d = (int(g) for g in m.groups())
180
+ if not (1 <= mo <= 12 and 1 <= d <= 31):
181
+ return ""
182
+ tail = text[m.end():].strip()
183
+ if tail and (tail[0].isdigit() or tail[0].isspace()):
184
+ tail = "T" + tail.lstrip() # `2026-10-01 08:00` → ISO 的 T 分隔
185
+ return f"{y:04d}-{mo:02d}-{d:02d}" + tail
186
+
187
+
188
+ def _ld_fields(raw_list: list[str]) -> dict:
189
+ """从 ld+json 原文里提取元数据字段;文章类节点优先,缺失字段再放宽到全节点。"""
190
+ nodes: list[dict] = []
191
+ for raw in raw_list[:_LD_SCRIPT_CAP]:
192
+ try:
193
+ nodes.extend(_iter_ld_nodes(json.loads(raw)))
194
+ except Exception:
195
+ continue # 非法 JSON/非容器:跳过这一段,不影响其余
196
+ if not nodes:
197
+ return {}
198
+ article_nodes = [n for n in nodes if _ld_is_article(n)]
199
+ fields: dict[str, str] = {}
200
+
201
+ def harvest(pool: list[dict]) -> None:
202
+ for node in pool:
203
+ if "published_at" not in fields:
204
+ d = _ld_date(node.get("datePublished"))
205
+ if d:
206
+ fields["published_at"] = d
207
+ if "headline" not in fields:
208
+ h = node.get("headline")
209
+ if isinstance(h, str) and h.strip():
210
+ fields["headline"] = h.strip()[:MAX_TEXT]
211
+ if "byline" not in fields:
212
+ a = _ld_name(node.get("author") or node.get("creator"))
213
+ if a:
214
+ fields["byline"] = a[:MAX_TEXT]
215
+ if "site_name" not in fields:
216
+ s = _ld_name(node.get("publisher"))
217
+ if not s:
218
+ # 无 publisher 时,WebSite/Organization 的 name 即站点名;
219
+ # WebPage/Product 等的 name 是页面标题/商品名,不收
220
+ t = str(node.get("@type") or "").lower()
221
+ if "website" in t or "organization" in t:
222
+ s = _ld_name(node.get("name"))
223
+ if s:
224
+ fields["site_name"] = s[:MAX_TEXT]
225
+ if "excerpt" not in fields:
226
+ e = node.get("description")
227
+ if isinstance(e, str) and e.strip():
228
+ fields["excerpt"] = " ".join(e.split())[:MAX_TEXT]
229
+
230
+ harvest(article_nodes)
231
+ if len(fields) < 5 and len(article_nodes) < len(nodes):
232
+ rest = [n for n in nodes if n not in article_nodes]
233
+ harvest(rest)
234
+ return fields
235
+
236
+
93
237
  def extract_article_meta(html: str, base_url: str,
94
238
  max_links: int = MAX_LINKS) -> dict:
95
- """返回 {byline, excerpt, site_name, published_at, links},缺失的键不出现。
239
+ """返回 {byline, excerpt, site_name, published_at, headline, links},缺失的键不出现。
96
240
 
241
+ headline 仅 JSON-LD 提供(meta 标签没有对应声明位);其余字段 meta 与
242
+ JSON-LD 双源,meta 优先。
97
243
  links: [{"url": 绝对 URL, "text": 锚文本}],按出现顺序去重,最多 max_links。
98
244
  同页锚点、javascript/mailto、非 http(s)、空文本一律丢弃。
99
245
  """
@@ -106,6 +252,9 @@ def extract_article_meta(html: str, base_url: str,
106
252
  except Exception:
107
253
  return {}
108
254
  out: dict = dict(p.meta)
255
+ for key, value in _ld_fields(p.ld_jsons).items():
256
+ if value and key not in out:
257
+ out[key] = value # meta 已有的字段不被 JSON-LD 覆盖(缺失才补)
109
258
  raw_links = p.article_links
110
259
  if raw_links:
111
260
  links: list[dict[str, str]] = []
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env python3
2
+ """bench_general_pool.py — 通用层选源的 static/dynamic 交错对拍。
3
+
4
+ 用途:`source_selection.GENERAL_PRIORS` 的先验不是拍脑袋写的,重测/改表
5
+ 前后用这个脚本给出同一网络时刻的两臂读数。两臂各自使用**独立的隔离状态
6
+ 目录**,并关闭路由缓存——否则静态臂先跑会把 decision 缓存给动态臂,
7
+ 两臂读到同一组合,A/B 变成自欺(2026-10-26 实测踩中)。
8
+
9
+ python3 scripts/bench_general_pool.py --rounds 2
10
+ python3 scripts/bench_general_pool.py --queries "git commit,上海 地铁 线路图" --json
11
+
12
+ 输出:每条查询的墙钟、结果数、词面相关代理(query_signals.result_relevance)
13
+ 与贡献引擎;末尾给两臂的 p50/mean/相关均值。词面相关只是代理,不等于内容
14
+ 正确性——要看正确性得走 `--verify` 核正文。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import time
26
+
27
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
29
+
30
+ from query_signals import result_relevance # noqa: E402
31
+
32
+ DEFAULT_QUERIES = [
33
+ "git commit",
34
+ "quiet mechanical keyboard office use review",
35
+ "ergonomic keyboard wrist pain 2026",
36
+ "best budget laptop 2026",
37
+ "how to clean a cast iron pan",
38
+ "nanjing food recommendations",
39
+ "Как написать скрипт",
40
+ "software architecture review checklist",
41
+ ]
42
+
43
+
44
+ def _run(argo: str, query: str, static: bool, state_dir: str,
45
+ timeout: float) -> dict:
46
+ env = dict(os.environ, ARGO_USAGE_LOG="0", ARGO_ROUTE_CACHE="0",
47
+ ARGO_STATE_DIR=state_dir)
48
+ for key in ("ARGO_GENERAL_FALLBACK_STATIC", "ARGO_GENERAL_FALLBACK_LEAD",
49
+ "ARGO_GENERAL_FALLBACK_LEGACY"):
50
+ env.pop(key, None)
51
+ if static:
52
+ env["ARGO_GENERAL_FALLBACK_STATIC"] = "1"
53
+ started = time.perf_counter()
54
+ try:
55
+ proc = subprocess.run(
56
+ [argo, "search", query, "--json", "--no-cache", "-n", "8"],
57
+ capture_output=True, text=True, encoding="utf-8",
58
+ timeout=timeout, env=env)
59
+ elapsed = int((time.perf_counter() - started) * 1000)
60
+ payload = json.loads(proc.stdout) if proc.stdout.strip().startswith("{") else {}
61
+ results = [r for r in (payload.get("results") or [])
62
+ if isinstance(r, dict) and "error" not in r]
63
+ except Exception as exc: # 超时/非 JSON:如实记失败,不替它编读数
64
+ return {"ms": int((time.perf_counter() - started) * 1000),
65
+ "n": 0, "rel": None, "engines": [], "error": repr(exc)[:160]}
66
+ return {
67
+ "ms": elapsed,
68
+ "n": len(results),
69
+ # agent 档真实字节:与 drift 门禁同一口径(stdout 的实际大小)。
70
+ # 排序不读它(见 source_selection 的说明),但 A/B 必须能量出来,
71
+ # 否则「体积换速度」的取舍永远只能凭感觉。
72
+ "bytes": len(proc.stdout.encode("utf-8")),
73
+ "rel": result_relevance(query, results) if results else None,
74
+ "engines": payload.get("engines_used") or [],
75
+ }
76
+
77
+
78
+ def _summary(rows: list[dict]) -> dict:
79
+ latencies = sorted(r["ms"] for r in rows)
80
+ rels = [r["rel"] for r in rows if r.get("rel") is not None]
81
+ if not latencies:
82
+ return {"n": 0}
83
+ sizes = [r.get("bytes", 0) for r in rows if r.get("bytes")]
84
+ return {
85
+ "n": len(rows),
86
+ "p50_ms": latencies[len(latencies) // 2],
87
+ "mean_ms": round(sum(latencies) / len(latencies)),
88
+ "mean_bytes": round(sum(sizes) / len(sizes)) if sizes else None,
89
+ "rel_mean": round(sum(rels) / len(rels), 3) if rels else None,
90
+ }
91
+
92
+
93
+ def main() -> int:
94
+ parser = argparse.ArgumentParser(description="通用层选源 static/dynamic 对拍")
95
+ parser.add_argument("--queries", help="逗号分隔;默认 8 条混合中英查询")
96
+ parser.add_argument("--rounds", type=int, default=2,
97
+ help="每臂轮数;两轮交错臂顺序,抵消网络漂移")
98
+ parser.add_argument("--timeout", type=float, default=45.0)
99
+ parser.add_argument("--argo", default=os.path.expanduser("~/.local/bin/argo"))
100
+ parser.add_argument("--json", action="store_true")
101
+ args = parser.parse_args()
102
+
103
+ queries = ([q.strip() for q in args.queries.split(",") if q.strip()]
104
+ if args.queries else DEFAULT_QUERIES)
105
+ root = tempfile.mkdtemp(prefix="argo-bench-gp-")
106
+ state = {"static": os.path.join(root, "static"),
107
+ "dynamic": os.path.join(root, "dynamic")}
108
+ for path in state.values():
109
+ os.makedirs(path, exist_ok=True)
110
+
111
+ rows: list[dict] = []
112
+ for rnd in range(max(1, args.rounds)):
113
+ for query in queries:
114
+ order = [True, False] if rnd % 2 == 0 else [False, True]
115
+ for static in order:
116
+ arm = "static" if static else "dynamic"
117
+ reading = _run(args.argo, query, static, state[arm], args.timeout)
118
+ reading.update(query=query, arm=arm, round=rnd)
119
+ rows.append(reading)
120
+ if not args.json:
121
+ print(f"r{rnd} {query[:30]:30s} {arm:7s} "
122
+ f"{reading['ms']:5d}ms n={reading['n']} "
123
+ f"bytes={reading.get('bytes', 0)} "
124
+ f"rel={reading['rel']} {reading['engines']}", flush=True)
125
+
126
+ report = {
127
+ "state_root": root,
128
+ "queries": queries,
129
+ "rounds": max(1, args.rounds),
130
+ "static": _summary([r for r in rows if r["arm"] == "static"]),
131
+ "dynamic": _summary([r for r in rows if r["arm"] == "dynamic"]),
132
+ "rows": rows,
133
+ }
134
+ if args.json:
135
+ # 紧凑 stdout:仓库门禁禁止脚本向终端输出 pretty JSON(上下文预算)。
136
+ print(json.dumps(report, ensure_ascii=False))
137
+ else:
138
+ print("\n=== summary ===")
139
+ for arm in ("static", "dynamic"):
140
+ print(arm, report[arm])
141
+ return 0
142
+
143
+
144
+ if __name__ == "__main__":
145
+ raise SystemExit(main())
@@ -22,13 +22,23 @@ from datetime import datetime, timezone, timedelta
22
22
  from typing import Any
23
23
  from urllib.parse import urlparse
24
24
 
25
+ from video_meta import VIDEO_PLATFORMS, parse_duration_seconds
26
+
25
27
  _TZ_CN = timezone(timedelta(hours=8))
26
28
 
27
29
  # 技能目录源(engines/specs/*.yaml 里声明 `coverage: skill` 的那些,加上走
28
30
  # 自定义引擎的 redskill)。这里用常量而非运行时读 spec:本函数在输出路径上,
29
31
  # config.yaml 有 130KB+,为一句局限声明去解析它是拿延迟换措辞。
30
32
  # 与 spec 的一致性由 tests/test_skill_registry_contract.py 断言,不靠人记。
31
- SKILL_REGISTRY_ENGINES = frozenset({"redskill", "skillsmp", "clawhub"})
33
+ # DSH 插件三源(dshopen / deepseek1024 / dsh_hub)同属此列:它们都是「可安装
34
+ # 扩展的目录」,命中时带 SKILL_REGISTRY_LIMITATION 提示(市场列表不等于已验证
35
+ # 包,装前看上游引用)。与 spec 的 coverage: skill 声明对账,由
36
+ # tests/test_skill_registry_contract.py 把守。
37
+ SKILL_REGISTRY_ENGINES = frozenset({
38
+ "redskill", "skillsmp", "clawhub",
39
+ "explainx", "skills_sh",
40
+ "dshopen", "deepseek1024", "dsh_hub",
41
+ })
32
42
 
33
43
  SKILL_REGISTRY_LIMITATION = (
34
44
  "Skill directory hits are marketplace listings, not verified packages; "
@@ -71,6 +81,20 @@ def _platform_of(url: str, source: str) -> str:
71
81
  return "weibo"
72
82
  if "youtube.com" in host or "youtu.be" in host:
73
83
  return "youtube"
84
+ if "douyin.com" in host:
85
+ return "douyin"
86
+ if "kuaishou.com" in host:
87
+ return "kuaishou"
88
+ if "vimeo.com" in host:
89
+ return "vimeo"
90
+ if "v.qq.com" in host:
91
+ return "tencent_video"
92
+ if "youku.com" in host:
93
+ return "youku"
94
+ if "iqiyi.com" in host:
95
+ return "iqiyi"
96
+ if "ixigua.com" in host or "xigua.com" in host:
97
+ return "xigua"
74
98
  if host in {"x.com", "twitter.com"} or host.endswith(".x.com"):
75
99
  return "x"
76
100
  if "mp.weixin.qq.com" in host:
@@ -142,12 +166,28 @@ def result_to_candidate(
142
166
  platform = _platform_of(url, source)
143
167
  canon = canonicalize_url(url) or url
144
168
  social = item.get("social_meta") if isinstance(item.get("social_meta"), dict) else {}
169
+ duration_seconds = parse_duration_seconds(social.get("duration")) if social else None
170
+ if duration_seconds is None:
171
+ duration_seconds = parse_duration_seconds(item.get("duration"))
172
+ if social.get("content_type") == "video" or platform in VIDEO_PLATFORMS:
173
+ content_type = "video"
174
+ elif social:
175
+ content_type = "social_post"
176
+ else:
177
+ content_type = "web_page"
145
178
  metrics = {
146
- "likes": social.get("likes") if social else None,
179
+ "likes": next(
180
+ (social[k] for k in ("likes", "like_count") if social.get(k) is not None),
181
+ None),
147
182
  "comments": social.get("comments") if social else None,
148
183
  "collects": social.get("collects") if social else None,
149
184
  "shares": social.get("shares") or social.get("retweets"),
150
- "views": social.get("views") or social.get("play"),
185
+ # B 站引擎的字段名是 play_count;旧写法只认 views/play,实测播放量
186
+ # 恒为 null,与「统一 engagement 口径」的目标相反。
187
+ "views": next(
188
+ (social[k] for k in ("views", "play", "play_count")
189
+ if social.get(k) is not None),
190
+ None),
151
191
  }
152
192
  # 明确后端给了 0 才保留 0;否则 null
153
193
  for k, v in list(metrics.items()):
@@ -173,7 +213,8 @@ def result_to_candidate(
173
213
  "snippet": (item.get("snippet") or "")[:300],
174
214
  "author": social.get("author") if social else None,
175
215
  "published_at": item.get("published_at") or social.get("published_at"),
176
- "content_type": "social_post" if social else "web_page",
216
+ "content_type": content_type,
217
+ "duration_seconds": duration_seconds,
177
218
  "language": None,
178
219
  "metrics": metrics,
179
220
  "access": {
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python3
2
+ """charset_decode.py — 响应体解码:响应头声明 > HTML meta 嗅探 > 严格猜测链。
3
+
4
+ 为什么独立成模块(2026-10-26,对标 pagesift 的字符集检测):HTTP 头缺失
5
+ charset 是常态(老站尤甚),此前 http_client 对这些响应一律 utf-8 replace,
6
+ GBK/GB2312 页面解出满屏 U+FFFD(实测 zol/4399/pconline 三站各 1.6 万~5 万个)。
7
+ 解码层是纯函数、无网络依赖,拆出既让 http_client 体积门禁随动下调,也让
8
+ fetch_v3/article.py 的 urllib 兜底车道能直接复用(它们在 http_client 不可
9
+ 导入时同样要能正确解码)。
10
+
11
+ 解码顺序:
12
+ 1. 响应头显式声明且 codec 已注册 → 信任头(与浏览器一致),即使解出替换符
13
+ 也不回退猜测——显式声明的二进制残余不许被误猜成别的编码;
14
+ 2. 头缺失/不可识别 → 按 WHATWG prescan 语义嗅探 HTML 前 2KB 的 <meta>
15
+ 声明(content-type meta 的 content 值优先于 charset 属性;带 content 的
16
+ 其他 meta 跳过——description 正文里的「charset=」是数据不是声明);
17
+ 3. 仍无果 → 严格猜测链:utf-8 严格成功即原样;失败且高字节占比达标
18
+ (西文页零星弯引号 <2%,GBK 中文页即便混排标记也 >10%)时依次试
19
+ gb18030/big5(严格);全败 utf-8 replace 兜底,任何失败不丢 body。
20
+
21
+ gb18030 是 GBK/GB2312 的超集,一个 codec 覆盖中文生态,无需 chardet 依赖。
22
+ 纯标准库,零 pip 依赖。
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+
29
+
30
+ def _header_charset(content_type: str) -> str | None:
31
+ """Content-Type 头里可用(codec 已注册)的 charset;缺失或不可识别返回 None。
32
+
33
+ None 与显式 "utf-8" 语义不同:前者允许进入嗅探/猜测链,后者必须信任头。
34
+ 未知编码必须先判定再解码:`bytes.decode("x-unknown-8bit")` 会抛 LookupError,
35
+ 而 LookupError 不是 OSError 子类,会被 HttpClient.get 的 `except Exception`
36
+ 吞掉并返回 status=0——一个正常的 200 响应被静默降级成「连接失败」,
37
+ 还被归因为 network。运维现实里 `charset=x-unknown-8bit`、
38
+ `charset=gb2312;` 这类脏头并不罕见。
39
+ """
40
+ import codecs
41
+ if "charset=" in content_type:
42
+ charset = content_type.split("charset=")[-1].strip().split(";")[0].strip().strip('"\'')
43
+ try:
44
+ codecs.lookup(charset)
45
+ return charset
46
+ except (LookupError, ValueError):
47
+ pass
48
+ return None
49
+
50
+
51
+ def _charset_of(content_type: str) -> str:
52
+ """从 Content-Type 解析 charset;缺失或无法识别时回落 utf-8。"""
53
+ return _header_charset(content_type) or "utf-8"
54
+
55
+
56
+ # ─── HTML 字符集嗅探(对标 pagesift 的 mojibake 防线)────────────────────────
57
+
58
+ _PRESCAN_WINDOW = 2048
59
+ _HIGH_BYTE_SAMPLE = 65536
60
+ _HIGH_BYTE_RATIO = 0.1 # 西文页零星弯引号 <2%,GBK 中文页即便混排标记也 >10%
61
+ _META_TAG_RE = re.compile(rb"<meta\b[^>]*>", re.I)
62
+ _META_CHARSET_ATTR_RE = re.compile(
63
+ rb"""[\s"']charset\s*=\s*["']?\s*([a-zA-Z0-9._\-]+)""", re.I)
64
+ _CONTENT_TYPE_META_RE = re.compile(
65
+ rb"""(?:http-equiv|name)\s*=\s*["']?content-type["']?""", re.I)
66
+ _CONTENT_ATTR_RE = re.compile(
67
+ rb"""content\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", re.I)
68
+
69
+
70
+ def _sniff_meta_charset(raw_body: bytes) -> str:
71
+ """从 HTML 前 2KB 嗅探 <meta> 声明的字符集;无声明或 codec 不存在返回空。
72
+
73
+ 按 WHATWG prescan 语义:content-type meta(http-equiv/name 均收,现实里
74
+ 两种写法都有)的 content 值优先,其次 charset 属性。只做字节层正则,
75
+ 不建 DOM,毫秒级;声明不可信的残留 damage 由 errors="replace" 兜住。
76
+ """
77
+ window = raw_body[:_PRESCAN_WINDOW]
78
+ if b"<meta" not in window.lower():
79
+ return ""
80
+ candidates: list[str] = []
81
+ for tag in _META_TAG_RE.finditer(window):
82
+ tag_bytes = tag.group(0)
83
+ if _CONTENT_TYPE_META_RE.search(tag_bytes):
84
+ m = _CONTENT_ATTR_RE.search(tag_bytes)
85
+ if m:
86
+ value = next(g for g in m.groups() if g is not None)
87
+ text = value.decode("ascii", "ignore")
88
+ idx = text.lower().find("charset=")
89
+ if idx >= 0:
90
+ name = text[idx + 8:].split(";")[0].strip().strip("\"'")
91
+ candidates.append(name)
92
+ continue
93
+ if _CONTENT_ATTR_RE.search(tag_bytes):
94
+ continue
95
+ m = _META_CHARSET_ATTR_RE.search(b" " + tag_bytes)
96
+ if m:
97
+ candidates.append(m.group(1).decode("ascii", "ignore"))
98
+ import codecs
99
+ for name in candidates:
100
+ try:
101
+ codecs.lookup(name)
102
+ return name
103
+ except (LookupError, ValueError):
104
+ continue
105
+ return ""
106
+
107
+
108
+ def decode_response_body(raw_body: bytes, content_type: str) -> str:
109
+ """按「响应头声明 > HTML meta 嗅探 > 严格解码链」解出文本,任何失败都不丢 body。"""
110
+ declared = _header_charset(content_type)
111
+ if declared is not None:
112
+ return raw_body.decode(declared, errors="replace")
113
+ sniffed = _sniff_meta_charset(raw_body)
114
+ if sniffed and sniffed.lower() not in ("utf-8", "utf8", "ascii", "us-ascii"):
115
+ return raw_body.decode(sniffed, errors="replace")
116
+ try:
117
+ return raw_body.decode("utf-8", errors="strict")
118
+ except UnicodeDecodeError:
119
+ pass
120
+ sample = raw_body[:_HIGH_BYTE_SAMPLE]
121
+ if sample and sum(1 for b in sample if b >= 0x80) / len(sample) >= _HIGH_BYTE_RATIO:
122
+ for enc in ("gb18030", "big5"):
123
+ try:
124
+ return raw_body.decode(enc, errors="strict")
125
+ except (UnicodeDecodeError, ValueError):
126
+ continue
127
+ return raw_body.decode("utf-8", errors="replace")