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
@@ -27,8 +27,7 @@ except ImportError:
27
27
  sys.path.insert(0, str(Path(__file__).parent))
28
28
  from config import load_config, get_engines
29
29
 
30
- # 图片许可判定 / 字段收尾 / CLI 字段契约收敛都在 image_ops(体积门禁要求,
31
- # 且同属「引擎输出 → 对外契约」这一层)。转发导入保持调用点不变。
30
+ # 图片许可判定 / 字段收尾 / CLI 字段契约收敛都在 image_ops(转发导入保持调用点不变)。
32
31
  from image_ops import ( # noqa: E402
33
32
  CLI_PASSTHROUGH_FIELDS as _CLI_PASSTHROUGH_FIELDS,
34
33
  _cli_result_row,
@@ -60,8 +59,7 @@ def _get_logger():
60
59
  _FAIL_NOTES: dict[str, dict[str, Any]] = {}
61
60
  _FAIL_NOTES_LOCK = threading.Lock()
62
61
 
63
- # HTTPError 错误体的读取上限:只用于归因(下游截 400 字符),
64
- # 无限读会把几十 MB 错误页吃进内存并写进磁盘状态
62
+ # HTTPError 错误体读取上限:只用于归因(下游截 400 字符),防大错误页吃进内存/落盘
65
63
  _HTTP_ERROR_BODY_CAP = 64 * 1024
66
64
 
67
65
  # 归因细节里可能回显凭证(OpenAI 风格 "Incorrect API key: sk-…"),
@@ -104,6 +102,18 @@ def pop_failure_note(engine: str) -> dict[str, Any] | None:
104
102
  return _FAIL_NOTES.pop(engine, None)
105
103
 
106
104
 
105
+ def peek_failure_note(engine: str) -> dict[str, Any] | None:
106
+ """只读失败归因,不清除。
107
+
108
+ 调度层要在**重试之前**判断这次失败是不是确定性的(配额/鉴权/反爬),
109
+ 但归因本身还要留给 `_run_one` 落进 outcome 与熔断器。读后即清会让
110
+ 「为什么坏」在重试路径上丢失,故单独开一个只读口。
111
+ """
112
+ with _FAIL_NOTES_LOCK:
113
+ note = _FAIL_NOTES.get(engine)
114
+ return dict(note) if note else None
115
+
116
+
107
117
  def _lang_param(param: str, query: str) -> str:
108
118
  """按查询主语言返回引擎语言参数;表在 lang_detect 单来源维护。
109
119
 
@@ -310,11 +320,12 @@ def _coerce_field(val: Any, *, max_len: int | None = None) -> str:
310
320
 
311
321
 
312
322
  def _format_url_template(template: str, item: dict) -> str:
313
- """支持 {field} 与 {a.b.c} 点分路径的 URL 模板。"""
314
- def repl(m: re.Match) -> str:
315
- return _coerce_field(_get_path(item, m.group(1)))
323
+ """支持 {field} 与 {a.b.c} 点分路径的 URL 模板;任一占位为空则返回空串。"""
324
+ vals = {m.group(1): _coerce_field(_get_path(item, m.group(1))) for m in re.finditer(r"\{([^}]+)\}", template)}
325
+ if any(not v for v in vals.values()):
326
+ return ""
316
327
  try:
317
- return re.sub(r"\{([^}]+)\}", repl, template)
328
+ return re.sub(r"\{([^}]+)\}", lambda m: vals[m.group(1)], template)
318
329
  except Exception:
319
330
  return ""
320
331
 
@@ -353,7 +364,6 @@ def _make_field_parser(path: str, fields: dict[str, str], url_template: str | No
353
364
  if not ik:
354
365
  continue
355
366
  raw = _get_path(item, ik) if "." in str(ik) else item.get(ik, "")
356
- # 兼容顶层点分键名不存在时回退 get
357
367
  if raw in ("", None) and "." not in str(ik):
358
368
  raw = item.get(ik, "")
359
369
  coerced = _coerce_field(raw, max_len=300 if ok == "snippet" else 500)
@@ -363,6 +373,8 @@ def _make_field_parser(path: str, fields: dict[str, str], url_template: str | No
363
373
  built = _format_url_template(url_template, item)
364
374
  if built.startswith(("http://", "https://")):
365
375
  r["url"] = built
376
+ else:
377
+ r.pop("url", None)
366
378
  if isinstance(r.get("url"), str) and r["url"].startswith("//"):
367
379
  r["url"] = "https:" + r["url"]
368
380
  if r.get("title") or r.get("url"):
@@ -394,8 +406,10 @@ def _build_cli_engine(spec: dict[str, Any]) -> Any:
394
406
  args += _resolve(tmpl, query, n, mode=mode, **kwargs)
395
407
  env = os.environ.copy()
396
408
  env.update(env_overrides)
397
- return _parse_text_output(_run(cmd + args, timeout=timeout, engine_name=spec.get("_name", "cli")),
398
- spec.get("_name", "cli"), output_format=output_format, n=n)
409
+ return _apply_url_kind(
410
+ _parse_text_output(_run(cmd + args, timeout=timeout, engine_name=spec.get("_name", "cli")),
411
+ spec.get("_name", "cli"), output_format=output_format, n=n),
412
+ spec)
399
413
  return _engine
400
414
 
401
415
 
@@ -749,6 +763,18 @@ def _normalize_epoch(value: Any) -> str:
749
763
  return text
750
764
 
751
765
 
766
+ def _apply_url_kind(rows: list[dict[str, Any]], spec: dict) -> list[dict[str, Any]]:
767
+ """声明式 spec 的 url_kind 落到行上(issue #29 口径 B):none = 本档条目不以
768
+ url 为身份,缺 url 的条目不按壳页整批吞。spec 未声明时行上不出现该字段。"""
769
+ kind = spec.get("url_kind")
770
+ if not kind:
771
+ return rows
772
+ for r in rows:
773
+ if isinstance(r, dict):
774
+ r.setdefault("url_kind", kind)
775
+ return rows
776
+
777
+
752
778
  def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
753
779
  output_map: dict, spec: dict) -> list[dict[str, Any]]:
754
780
  """HTTP 引擎响应体解析(GET/POST 共用)。"""
@@ -769,7 +795,7 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
769
795
  # 专用 JSON 解析器优先(DDG Instant Answer / UAPI / Semantic Scholar 等)
770
796
  custom = _CUSTOM_JSON_PARSERS.get(eng)
771
797
  if custom:
772
- return _ensure_engine_source(custom(data), eng)[:limit]
798
+ return _apply_url_kind(_ensure_engine_source(custom(data), eng)[:limit], spec)
773
799
  if output_map:
774
800
  items_path = output_map.get("items", "")
775
801
  # 根节点即为数组时(HF / dev.to / polymarket),items 用 "."
@@ -814,9 +840,11 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
814
840
  # 自定义 builder、通用兜底),只覆盖一条会让契约对一半结果生效。
815
841
  finalize_image_fields(parsed, _lic or "")
816
842
  # preserve_source(声明式 spec):保留 API 返回的真实来源标注
817
- return _ensure_engine_source(
818
- parsed, eng, preserve=bool(spec.get("preserve_source"))
819
- )[:limit]
843
+ return _apply_url_kind(
844
+ _ensure_engine_source(
845
+ parsed, eng, preserve=bool(spec.get("preserve_source"))
846
+ )[:limit],
847
+ spec)
820
848
  if isinstance(data, list):
821
849
  return _ensure_engine_source(
822
850
  _parse_generic({"results": data}, eng, limit), eng
@@ -176,6 +176,15 @@ from engines_builders_intl import (
176
176
  from engines_builders_feeds import (
177
177
  _build_rss_feed_engine,
178
178
  )
179
+ from engines_builders_dsh import (
180
+ _build_dshopen_engine,
181
+ )
182
+ from engines_builders_skill import (
183
+ _build_explainx_engine,
184
+ _build_skills_sh_engine,
185
+ _build_skillsmp_engine,
186
+ _build_clawhub_engine,
187
+ )
179
188
 
180
189
  __all__ = [
181
190
  "_build_em_miaoxiang_engine",
@@ -306,5 +315,10 @@ __all__ = [
306
315
  "_build_tle_mirror_engine",
307
316
  "_build_nhtsa_vpic_engine",
308
317
  "_build_rss_feed_engine",
318
+ "_build_dshopen_engine",
319
+ "_build_explainx_engine",
320
+ "_build_skills_sh_engine",
321
+ "_build_skillsmp_engine",
322
+ "_build_clawhub_engine",
309
323
  ]
310
324
 
@@ -669,10 +669,12 @@ def _build_models_dev_engine(spec: dict[str, Any]) -> Any:
669
669
  # ── Finviz 美股筛选引擎(HTML 抓取)─────────────────────────────────────────────
670
670
 
671
671
  def _build_finviz_engine(spec: dict[str, Any]) -> Any:
672
- """Finviz 个股快照(finviz.com/quote.ashx?t=TICKER)
672
+ """Finviz 个股快照(finviz.com/stock?t=TICKER)
673
673
 
674
674
  从 snapshot 表格提取:公司名、行业、市值、PE、价格、涨跌幅。
675
675
  query 视为 ticker(大写);非纯字母时取首个字母 token 作 ticker。
676
+ (2026-10-28:旧地址 /quote.ashx 全站 301 到 /stock,http_open 不跟随重定向,
677
+ 端点随之切换;新页 snapshot 表结构与解析器兼容,实测 AAPL 全字段命中。)
676
678
  """
677
679
  timeout = spec.get("timeout", 10)
678
680
 
@@ -683,7 +685,7 @@ def _build_finviz_engine(spec: dict[str, Any]) -> Any:
683
685
  if not m:
684
686
  return []
685
687
  ticker = m.group(0).upper()
686
- url = f"https://finviz.com/quote.ashx?t={ticker}"
688
+ url = f"https://finviz.com/stock?t={ticker}"
687
689
  headers = {
688
690
  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
689
691
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
@@ -2552,12 +2554,16 @@ def _build_thesportsdb_engine(spec: dict[str, Any]) -> Any:
2552
2554
  # ── OpenCorporates 全球公司注册 ──────────────────────────────────────────────
2553
2555
 
2554
2556
  def _build_opencorporates_engine(spec: dict[str, Any]) -> Any:
2555
- """OpenCorporates 全球公司注册(api.opencorporates.com/v0.4/companies/search,免认证)。
2557
+ """OpenCorporates 全球公司注册(api.opencorporates.com/v0.4/companies/search)。
2556
2558
 
2557
2559
  公司尽调/反欺诈:公司名、注册号、司法辖区、成立日期、状态。
2558
2560
  argo 现有引擎无公司注册数据源,这是尽调类查询的核心空白。
2561
+ (2026-10-28:匿名请求已被上游全面拒 401,API 需 api_token;直连实测确认。
2562
+ 支持 ARGO_OPENCORPORATES_API_TOKEN / OPENCORPORATES_API_TOKEN 双别名,
2563
+ spec required_env 已声明,无 token 时被 env 门自动跳过而非报错。)
2559
2564
  """
2560
2565
  timeout = spec.get("timeout", 10)
2566
+ _token = get_env(["ARGO_OPENCORPORATES_API_TOKEN", "OPENCORPORATES_API_TOKEN"]) or ""
2561
2567
 
2562
2568
  @safe_search
2563
2569
  def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
@@ -2569,6 +2575,7 @@ def _build_opencorporates_engine(spec: dict[str, Any]) -> Any:
2569
2575
  url = (
2570
2576
  "https://api.opencorporates.com/v0.4/companies/search"
2571
2577
  f"?q={urllib.parse.quote(q2)}&per_page={min(n, 10)}"
2578
+ + (f"&api_token={urllib.parse.quote(_token)}" if _token else "")
2572
2579
  )
2573
2580
  headers = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
2574
2581
  try:
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env python3
2
+ """DSH 插件目录构建器 —— DeepSeek Harness 插件生态检索。
3
+
4
+ 三个 DSH 插件数据源的形态各不相同,接入方式也分三档:
5
+
6
+ · deepseek1024(13855 条)/ dsh_hub(18933 条)—— 标准搜索 API,
7
+ 走 L1 声明式(`engines/specs/deepseek1024.yaml`、`engines/specs/dsh_hub.yaml`),
8
+ 本文件不含它们的实现。
9
+ · dshopen(894 条精选)—— **无搜索 API**:`/index.json` 是静态全量目录,
10
+ 任何 query 参数都返回同一份 1.3MB 文件(实测 `/index.json?query=x` 与不带参数
11
+ 逐字节相同)。这类「全量目录 + 本地匹配」没有声明式表达方式,故落到 L3。
12
+
13
+ 为什么 dshopen 值得单独一个 builder:它是四个候选源里**精选质量最高**的一个
14
+ (894 条零空标题/零空描述、53 条 verified 标签、labels 体系规范、601 条带
15
+ `engines.dsh` 版本约束),且与 deepseek1024 只重叠 562 条——两个源是互补而非
16
+ 替代。它缺的是 API,不是数据。
17
+
18
+ 缓存策略(为什么不用 ETag):上游支持 ETag,但 `http_open` 会把 304 归因为
19
+ 「HTTP 失败」(非 2xx 一律走 `_note_http_failure`),一次正常的缓存命中会在
20
+ 失败寄存器里留一条假记录。改用 TTL 缓存绕开:1.3MB 全量、每天重建,12h TTL
21
+ 意味着最多半天延迟,比污染归因划算。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import math
28
+ import re
29
+ import time
30
+ import urllib.request
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ from engines_base import safe_search, http_open, rank_score
35
+
36
+ # 上游:静态全量目录。Cloudflare 前置,支持 ETag(本 builder 刻意不用,见文件头)。
37
+ _DSHOPEN_INDEX_URL = "https://dshopen.org/index.json"
38
+
39
+ # 12h。dshopen 每天全量重建(sitemap 的 lastmod 全为当天),半天延迟可接受;
40
+ # 再短就会让「同一天多次搜索」反复拉 1.3MB。
41
+ _CACHE_TTL = 12 * 3600
42
+
43
+ _CACHE_FILE = "dshopen_index.json"
44
+ _META_FILE = "dshopen_index.meta.json"
45
+
46
+ # 字段权重:名字最重(用户找的往往是包名),中文描述次之,分类与英文再次。
47
+ # 与 find_dsh_plugin.py 的 FIELD_WEIGHT 同一口径,便于两处结果互相对照。
48
+ _FIELD_WEIGHTS: dict[str, float] = {
49
+ "name": 3.0,
50
+ "title_zh": 2.0,
51
+ "title_en": 1.5,
52
+ "desc_zh": 1.5,
53
+ "desc_en": 1.0,
54
+ "keywords": 1.2,
55
+ "category": 0.8,
56
+ }
57
+
58
+ # 引擎档位分(rank_score 的 base):dshopen 是精选源、覆盖最小,档位低于
59
+ # 通用源但高于长尾垂直源——它「条条可信」的优势要能压过「只有 894 条」的劣势。
60
+ _BASE_SCORE = 0.75
61
+
62
+ # 上游把星数写进了描述开头(881/894 条形如「★ 15 │ 分层蒸馏记忆:…」),
63
+ # 方便它自己的卡片渲染。搜素结果里星数已有独立字段,这个前缀只剩噪音,剥掉。
64
+ # 星号可能是 ★ 或 *,数字含千分位与小数(如 ★ 89,165 │)。
65
+ _STAR_PREFIX_RE = re.compile(r"^[★*]\s*\d[\d,\.]*\s*│\s*")
66
+
67
+ # dshopen 的 11 个分类 → 中文展示名(取自上游 metadata.categories 的 zh 标题)。
68
+ # 用于摘要前缀,让用户一眼看出「这是哪类插件」。
69
+ _CATEGORY_ZH: dict[str, str] = {
70
+ "interface": "界面",
71
+ "tools": "工具",
72
+ "skills": "技能",
73
+ "memory": "记忆",
74
+ "providers": "模型供应商",
75
+ "usage": "用量与费用",
76
+ "integrations": "集成",
77
+ "appearance": "外观",
78
+ "workflow": "工作流与协作",
79
+ "development": "开发与运维",
80
+ "knowledge": "知识",
81
+ }
82
+
83
+
84
+ def _cache_dir() -> Path:
85
+ """缓存目录。优先走 argo_paths(与 cache.db 同根),失败回落 ~/.cache。"""
86
+ try:
87
+ from argo_paths import ensure_state_dir
88
+
89
+ return ensure_state_dir("engines")
90
+ except Exception:
91
+ return Path.home() / ".cache" / "unified-search" / "engines"
92
+
93
+
94
+ def _load_plugins(timeout: float) -> list[dict[str, Any]]:
95
+ """读 dshopen 全量目录:缓存新鲜直接用,否则拉取并落盘。
96
+
97
+ 任何一步失败都返回已缓存的那份(哪怕过期)——目录搜索是「有旧数据胜过
98
+ 没数据」的场景,上游抖动不该让整个引擎空转。
99
+ """
100
+ cdir = _cache_dir()
101
+ cache_file = cdir / _CACHE_FILE
102
+ meta_file = cdir / _META_FILE
103
+
104
+ stale: list[dict[str, Any]] | None = None
105
+ try:
106
+ meta = json.loads(meta_file.read_text(encoding="utf-8"))
107
+ data = json.loads(cache_file.read_text(encoding="utf-8"))
108
+ plugins = data.get("plugins")
109
+ if isinstance(plugins, list):
110
+ stale = plugins
111
+ if time.time() - float(meta.get("ts") or 0) < _CACHE_TTL:
112
+ return plugins
113
+ except Exception:
114
+ stale = None
115
+
116
+ try:
117
+ req = urllib.request.Request(
118
+ _DSHOPEN_INDEX_URL,
119
+ headers={"User-Agent": "argo-search/1.0", "Accept": "application/json"},
120
+ )
121
+ with http_open(req, timeout=timeout, engine="dshopen") as resp:
122
+ payload = json.loads(resp.read())
123
+ plugins = payload.get("plugins") if isinstance(payload, dict) else None
124
+ if not isinstance(plugins, list):
125
+ return stale or []
126
+ try:
127
+ cdir.mkdir(parents=True, exist_ok=True)
128
+ cache_file.write_text(
129
+ json.dumps(payload, ensure_ascii=False), encoding="utf-8"
130
+ )
131
+ meta_file.write_text(
132
+ json.dumps({"ts": time.time()}), encoding="utf-8"
133
+ )
134
+ except OSError:
135
+ pass # 只读挂载 / 权限受限:内存里这份仍然可用
136
+ return plugins
137
+ except Exception:
138
+ return stale or []
139
+
140
+
141
+ def _entry_fields(entry: dict[str, Any]) -> dict[str, str]:
142
+ """摊平成待匹配文本。title/description 是 {en, zh} 双语对象,缺失侧留空。"""
143
+ meta = entry.get("metadata") or {}
144
+ title = entry.get("title") or {}
145
+ desc = entry.get("description") or {}
146
+ return {
147
+ "name": entry.get("name") or "",
148
+ "title_zh": title.get("zh") or "",
149
+ "title_en": title.get("en") or "",
150
+ "desc_zh": desc.get("zh") or "",
151
+ "desc_en": desc.get("en") or "",
152
+ "keywords": " ".join(meta.get("keywords") or []),
153
+ "category": meta.get("category") or "",
154
+ }
155
+
156
+
157
+ def _tokens(query: str) -> list[str]:
158
+ """查询切分:英文按词(≥2 字符)、中文按 2 字以上片段,去重保序。
159
+
160
+ 英文单词不切单字符——`a`/`x` 这类在包名里无处不在,切了只会把不相关的
161
+ 条目全捞进来。中文同理:单字噪音大,2 字片段是「记忆」「插件」这类词的
162
+ 自然粒度。整段中文(如「后台任务」)作为一个 token 保留,比切成二字
163
+ 滑窗更准。
164
+ """
165
+ q = (query or "").lower().strip()
166
+ if not q:
167
+ return []
168
+ toks: list[str] = []
169
+ for w in re.findall(r"[a-z0-9]+", q):
170
+ if len(w) >= 2:
171
+ toks.append(w)
172
+ for seg in re.findall(r"[一-鿿]{2,}", q):
173
+ toks.append(seg)
174
+ if not toks:
175
+ toks = re.findall(r"[一-鿿]", q)
176
+ seen: set[str] = set()
177
+ out: list[str] = []
178
+ for t in toks:
179
+ if t and t not in seen:
180
+ seen.add(t)
181
+ out.append(t)
182
+ return out
183
+
184
+
185
+ def _build_idf(plugins: list[dict[str, Any]], tokens: list[str]) -> dict[str, float]:
186
+ """IDF:罕见 token 权重大,满语料 token 权重小。
187
+
188
+ 为什么必须有:dshopen 的 894 条里几乎每条都含「dsh」(包名前缀),
189
+ 纯布尔命中下「dsh」对**所有**条目同加 3.0 分——区分度为零,top-10
190
+ 会退化成「按星数排」。实测查询「dsh 插件 记忆」有 887/894 条命中,
191
+ 真正相关的「记忆」类条目排不上来。IDF 把这类满语料词压到接近 0。
192
+ """
193
+ n = len(plugins) or 1
194
+ idf: dict[str, float] = {}
195
+ for tok in tokens:
196
+ hits = 0
197
+ for entry in plugins:
198
+ fields = _entry_fields(entry)
199
+ if any(tok in (v or "").lower() for v in fields.values()):
200
+ hits += 1
201
+ if hits >= n: # 满语料:不必再数
202
+ break
203
+ # +1 平滑:避免 log(0);满语料词得 ≈1.0(不是 0,仍保留微弱信号)
204
+ idf[tok] = math.log((n + 1) / (hits + 1)) + 1.0
205
+ return idf
206
+
207
+
208
+ def _score(
209
+ fields: dict[str, str], tokens: list[str], idf: dict[str, float]
210
+ ) -> float:
211
+ """命中字段权重 × token IDF 求和。未命中任何字段的条目直接淘汰。"""
212
+ lowered = {k: v.lower() for k, v in fields.items()}
213
+ total = 0.0
214
+ for tok in tokens:
215
+ w_tok = idf.get(tok, 1.0)
216
+ for field, weight in _FIELD_WEIGHTS.items():
217
+ if tok in lowered.get(field, ""):
218
+ total += weight * w_tok
219
+ return total
220
+
221
+
222
+ def _star_boost(entry: dict[str, Any]) -> float:
223
+ """星数加权:log 尺度,避免大仓碾压。
224
+
225
+ 注意 dshopen 的星数有**父仓污染**:19 个多包仓库(58 个条目,占 6.5%)取的是
226
+ 父仓星数(如 @linxin666/* 显示 9511 星,repo 实为 zhu1090093659/dsh-web)。
227
+ 这个偏差无法在索引侧修正,只能在解读时留意——加权幅度因此压得很低
228
+ (log1p/10,0 星与 1 万星只差约 0.92 倍)。
229
+ """
230
+ meta = entry.get("metadata") or {}
231
+ stars = (meta.get("sortKeys") or {}).get("github-stars") or 0
232
+ try:
233
+ stars = float(stars)
234
+ except (TypeError, ValueError):
235
+ return 1.0
236
+ if stars <= 0:
237
+ return 1.0
238
+ return 1.0 + math.log1p(stars) / 10.0
239
+
240
+
241
+ def _iso(epoch: Any) -> str:
242
+ try:
243
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(int(epoch)))
244
+ except (TypeError, ValueError, OSError):
245
+ return ""
246
+
247
+
248
+ def _build_dshopen_engine(spec: dict[str, Any]) -> Any:
249
+ """dshopen 插件目录(静态全量索引 + 本地匹配)。"""
250
+ timeout = float(spec.get("timeout", 15))
251
+
252
+ @safe_search
253
+ def _engine(
254
+ query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
255
+ ) -> list[dict[str, Any]]:
256
+ to = _timeout or timeout
257
+ tokens = _tokens(query)
258
+ if not tokens:
259
+ return []
260
+ plugins = _load_plugins(to)
261
+
262
+ idf = _build_idf(plugins, tokens)
263
+ scored: list[tuple[float, dict[str, Any]]] = []
264
+ for entry in plugins:
265
+ if not isinstance(entry, dict):
266
+ continue
267
+ s = _score(_entry_fields(entry), tokens, idf)
268
+ if s <= 0:
269
+ continue
270
+ scored.append((s * _star_boost(entry), entry))
271
+
272
+ # 稳定排序:同分按包名字典序,避免同批查询的结果顺序抖动
273
+ scored.sort(key=lambda x: (-x[0], (x[1].get("name") or "")))
274
+
275
+ results: list[dict[str, Any]] = []
276
+ for rank, (_, entry) in enumerate(scored[: max(1, n)]):
277
+ repo = (entry.get("repository") or {}).get("url") or ""
278
+ url = repo or entry.get("homepage") or ""
279
+ if not url:
280
+ continue
281
+ meta = entry.get("metadata") or {}
282
+ desc = (entry.get("description") or {}).get("zh") or ""
283
+ desc = _STAR_PREFIX_RE.sub("", desc).strip()
284
+ # 摘要前缀带分类。两个理由:一是给用户看「这是哪类插件」;二是
285
+ # 五维精排的「相关性」维度比对摘要与查询——上游摘要只写功能
286
+ # (「为 DSH 接入记忆服务」),不含「插件」二字,中文查询
287
+ # 「dsh 插件 记忆」的 CJK 二元组匹配不上,实测同批条目会输给
288
+ # 通用源的文章标题(那边标题恰好含「DSH 记忆插件」全词)。
289
+ # 前缀是真实分类信息,不是凑词。
290
+ cat = _CATEGORY_ZH.get(meta.get("category") or "", "")
291
+ if cat:
292
+ desc = f"DSH 插件({cat}):{desc}" if desc else f"DSH 插件({cat})"
293
+ versions = entry.get("versions") or []
294
+ published = versions[0].get("publishTimestamp") if versions else None
295
+ # 标题取中文展示名(title.zh),不是 npm 包名。原因:五维精排的
296
+ # 「相关性」维度比对标题与查询,中文查询(「dsh 记忆插件」)对上
297
+ # 中文标题(「OpenViking 记忆」)得分高,对上英文包名
298
+ # (@openviking/dsh-memory-plugin)几乎不得分——实测同一批条目
299
+ # 因标题形态不同,最终 top-6 全被通用源占据。包名仍保留在
300
+ # upstream(install 的权威答案)与 metadata 里,不丢。
301
+ title_obj = entry.get("title") or {}
302
+ title = (
303
+ title_obj.get("zh")
304
+ or title_obj.get("en")
305
+ or entry.get("name")
306
+ or ""
307
+ )
308
+ results.append(
309
+ {
310
+ "title": title,
311
+ "url": url,
312
+ "snippet": desc[:300],
313
+ "source": "dshopen",
314
+ "score": rank_score(_BASE_SCORE, rank),
315
+ "published_at": _iso(published),
316
+ # 可验证出处:npm 包名是「装什么」的权威答案
317
+ "upstream": entry.get("name") or "",
318
+ "metadata": {
319
+ "category": meta.get("category") or "",
320
+ "labels": meta.get("labels") or [],
321
+ "stars": (meta.get("sortKeys") or {}).get("github-stars") or 0,
322
+ "engines_dsh": (
323
+ (versions[0].get("engines") or {}).get("dsh") if versions else ""
324
+ ) or "",
325
+ },
326
+ }
327
+ )
328
+ return results
329
+
330
+ return _engine