argo-search 2.9.9 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.en.md +24 -21
  2. package/README.es.md +24 -21
  3. package/README.ja.md +23 -20
  4. package/README.ko.md +23 -20
  5. package/README.md +26 -21
  6. package/SKILL.md +5 -5
  7. package/backends/domain_profiles.json +76 -0
  8. package/backends/engine_registry.yaml +161 -5
  9. package/backends/quota_profiles.json +122 -2
  10. package/bin/argo +22 -1
  11. package/bin/argo.js +3 -3
  12. package/config.yaml +128 -21
  13. package/docs/ARGO_INTRO.md +4 -4
  14. package/docs/ENGINE_CATALOG.md +64 -44
  15. package/docs/MCP_SETUP.md +1 -1
  16. package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
  17. package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
  18. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
  19. package/engines/specs/clawhub.yaml +16 -15
  20. package/engines/specs/deepseek1024.yaml +46 -0
  21. package/engines/specs/dsh_hub.yaml +44 -0
  22. package/engines/specs/dshopen.yaml +32 -0
  23. package/engines/specs/explainx.yaml +32 -0
  24. package/engines/specs/gbfs_nyc.yaml +6 -1
  25. package/engines/specs/metaso_doc.yaml +49 -0
  26. package/engines/specs/metaso_image.yaml +65 -0
  27. package/engines/specs/metaso_podcast.yaml +60 -0
  28. package/engines/specs/metaso_scholar.yaml +57 -0
  29. package/engines/specs/metaso_video.yaml +62 -0
  30. package/engines/specs/ncpssd.yaml +41 -0
  31. package/engines/specs/sciverse.yaml +72 -0
  32. package/engines/specs/skills_sh.yaml +32 -0
  33. package/engines/specs/skillsmp.yaml +18 -16
  34. package/package.json +3 -2
  35. package/packages/dsh-plugin/README.md +3 -2
  36. package/packages/dsh-plugin/package.json +1 -1
  37. package/packages/dsh-plugin/test/size-gate.test.js +113 -0
  38. package/scripts/adaptive.py +41 -14
  39. package/scripts/article.py +6 -1
  40. package/scripts/article_meta.py +151 -2
  41. package/scripts/bench_general_pool.py +145 -0
  42. package/scripts/candidate_envelope.py +45 -4
  43. package/scripts/charset_decode.py +127 -0
  44. package/scripts/crawl.py +240 -74
  45. package/scripts/crawl_frontier.py +217 -0
  46. package/scripts/crawl_policy.py +174 -0
  47. package/scripts/engine_dispatch.py +22 -15
  48. package/scripts/engine_failure.py +15 -0
  49. package/scripts/engine_validate.py +8 -0
  50. package/scripts/engines.py +10 -0
  51. package/scripts/engines_base.py +12 -0
  52. package/scripts/engines_builders.py +14 -0
  53. package/scripts/engines_builders_dsh.py +330 -0
  54. package/scripts/engines_builders_skill.py +314 -0
  55. package/scripts/fetch_v3.py +37 -5
  56. package/scripts/gen_engine_catalog.py +218 -2
  57. package/scripts/general_pool.py +162 -0
  58. package/scripts/http_client.py +38 -42
  59. package/scripts/image_ops.py +4 -0
  60. package/scripts/install.ps1 +47 -19
  61. package/scripts/install.sh +45 -20
  62. package/scripts/matrix_search_eval.py +17 -1
  63. package/scripts/mcp_transport.py +1 -1
  64. package/scripts/ncpssd_bridge.py +123 -0
  65. package/scripts/paid_policy.py +109 -13
  66. package/scripts/pre-commit +19 -4
  67. package/scripts/query_signals.py +156 -3
  68. package/scripts/redskill/redskill_engine.py +29 -2
  69. package/scripts/release_check.py +209 -0
  70. package/scripts/retry_policy.py +22 -1
  71. package/scripts/robots_guard.py +26 -0
  72. package/scripts/route.py +11 -8
  73. package/scripts/route_cache.py +6 -0
  74. package/scripts/route_combo.py +37 -59
  75. package/scripts/route_domains.py +4 -1
  76. package/scripts/route_policy.py +6 -0
  77. package/scripts/search.py +9 -1
  78. package/scripts/search_cli.py +27 -0
  79. package/scripts/search_entry.py +9 -0
  80. package/scripts/search_output.py +29 -0
  81. package/scripts/search_pipeline.py +39 -1
  82. package/scripts/search_rank.py +1 -0
  83. package/scripts/social_engines/bilibili_engine.py +163 -26
  84. package/scripts/social_engines/reddit_engine.py +52 -51
  85. package/scripts/source_selection.py +302 -0
  86. package/scripts/video_fetch.py +303 -0
  87. package/scripts/video_meta.py +225 -0
  88. package/scripts/video_route.py +65 -0
  89. package/scripts/watch.py +123 -0
  90. package/scripts/local_engines.py +0 -321
@@ -0,0 +1,72 @@
1
+ # Sciverse · 学术题录检索(官方 HTTP API,POST /meta-search,需 token)
2
+ #
3
+ # 上游:OpenDataLab / MinerU(上海人工智能实验室)的科研数据基座,
4
+ # base https://api.sciverse.space,鉴权头 Authorization: Bearer <token>。
5
+ # 契约取自官方 Python SDK sciverse 0.14.3 源码(client.py:155-182 的
6
+ # search_papers 与 client.py:34-101 的 _to_backend_payload),本档不依赖 SDK。
7
+ #
8
+ # 本档给什么:结构化元数据——title / author / abstract / 刊名 / 年份 /
9
+ # subjects / doi / citation_count,另带 unique_id(引用关系查询用)与
10
+ # is_content_accessible(该条是否真有全文)。
11
+ # 本档不给什么:证据句与页码——argo 条目放不下偏移量与页码,要证据句用技能 sciverse 的 sv.py;读正文要拿
12
+ # doc_id 走 GET /content,本档不做。
13
+ #
14
+ # 覆盖边界:外文(英/德/法)文献为主;中文只有海外中国学与开放获取刊物
15
+ # (Hanspub / MDPI / Asiatische Studien 之类),**不含 CNKI / 万方 / CSSCI
16
+ # 中文核心**,古籍与 PhilPapers 也不覆盖。
17
+ #
18
+ # 年份粒度:上游只给 publication_published_year(四位年份,无月日),下面
19
+ # published_at 映出来就是「2023」这样的串;本引擎也不在 argo 的
20
+ # TIME_CAPABLE_ENGINES 里,--since/--until 对它不生效。
21
+ #
22
+ # 计费:官方未公布单价,故声明 cost_tier: api(按调用计)而不写免费;在价格
23
+ # 与额度核实之前用 explicit_only 把它挡在域 combo 之外,避免「自动花钱却
24
+ # 算不出花了多少」。
25
+ #
26
+ # key 名与官方 SDK 对齐(SDK 还认 ~/.sciverse/credentials.json,走本档要写进
27
+ # 环境变量):ARGO_SCIVERSE_API_TOKEN 或 SCIVERSE_API_TOKEN。
28
+ #
29
+ # 实测(2026-10-28,带 token):engine_validate --stage all --admit 通过
30
+ # (health + quality,q=1.0);argo_search 有结果,url 由 doi 经 url_template
31
+ # 生成。无 token 时 health 门按设计 skipped,不算失败。
32
+ # 注意 published_at 是四位年份字符串(上游只给年,无月日)。
33
+ #
34
+ # 验证:
35
+ # python3 scripts/engine_validate.py --engine sciverse --stage all --admit --write-doc
36
+
37
+ engine_id: sciverse
38
+ type: http
39
+ enabled: true
40
+ explicit_only: true
41
+ cost_tier: api
42
+ method: POST
43
+ url: https://api.sciverse.space/meta-search
44
+ timeout: 20
45
+ canary_query: "Kant transcendental deduction objectivity"
46
+ label: Sciverse(题录)
47
+ family: academic
48
+ priority: 56
49
+ required_env:
50
+ - [ARGO_SCIVERSE_API_TOKEN, SCIVERSE_API_TOKEN]
51
+
52
+ headers:
53
+ Authorization: Bearer {SCIVERSE_API_TOKEN}
54
+ Content-Type: application/json
55
+
56
+ body:
57
+ query: "{query}"
58
+ page: 1
59
+ page_size: 20
60
+ freshness_boost: MILD
61
+
62
+ output_map:
63
+ items: results
64
+ item_title: title
65
+ item_url: doi
66
+ item_summary: abstract
67
+ item_published_at: publication_published_year
68
+ item_upstream_authority: publication_venue_name_unified
69
+ item_upstream_score: citation_count
70
+ url_template: "https://doi.org/{doi}"
71
+
72
+ coverage: [academic, paper, english]
@@ -0,0 +1,32 @@
1
+ # skills_sh — 由 `argo engine add` 接入(2026-10-26)。
2
+ # 字段说明见 docs/ADDING_NEW_ENGINE.md;路由元数据(family/coverage/langs/
3
+ # domain_hints)由 engine_add 自动派生,可手工微调。
4
+ engine_id: skills_sh
5
+ type: skills_sh
6
+ enabled: true
7
+ cost_tier: free
8
+ label: skills.sh 技能目录
9
+ family: misc_vertical
10
+ priority: 51
11
+ qps: 2
12
+ period: minute
13
+ limit: null
14
+ cost_per_call: 0.0
15
+ cost_unit: free
16
+ timeout: 15
17
+ canary_query: git commit
18
+ coverage:
19
+ - skill
20
+ - developer
21
+ - tech
22
+ desc: skills.sh 技能目录(57k+,免认证,Vercel 官方安装遥测)
23
+ quality_queries:
24
+ - query: git commit
25
+ - query: code review
26
+ - query: pdf
27
+ langs:
28
+ - en
29
+ domain_hints:
30
+ - skill_search
31
+ - dsh_plugin_search
32
+ - rfc_search
@@ -1,14 +1,24 @@
1
1
  # SkillsMP — Agent Skills 聚合目录(skill 域跨生态技能索引,GET JSON,keyless)
2
2
  # 技能域的广覆盖目录源:独立索引 200 万+ 开源技能,支持语言/职业过滤,
3
3
  # 与 redskill(小红书生态 47650 技能本地缓存)互补不重复(不同上游、不同生态)。
4
- # 免费 REST API 无需密钥(bearerAuth 仅用于提额);sortBy=stars 按仓库热度排序,
5
- # stars 口径是源仓库星数非安装量,与 skills.sh 安装遥测、ClawHub 下载量互不可比。
6
- # 可选过滤参数(按需加进 extra_params):language(ISO 码,如 zh)、category、occupation。
4
+ # 免费 REST API 无需密钥(bearerAuth 仅用于提额);sortBy=stars 按仓库热度排序。
5
+ #
6
+ # 为什么是 L3(2026-10-26 从 L1 声明式改过来):
7
+ # 上游有 `stars`(源仓库星数)与 `githubUrl`(**能安装**的 GitHub 目录),
8
+ # 而 L1 的 output_map 只能把单字段映射成 summary——星数与「哪个地址能装」
9
+ # 这两个最有用的维度都透不出来。改 builder 后:摘要前缀带 ★ 星数,
10
+ # url 优先给 githubUrl(缺失时回落市场页 skillUrl)。
11
+ #
12
+ # 口径:stars 是**源仓库星数**(不是安装量),与 skills.sh 的 Vercel 遥测、
13
+ # explainx 的平台统计、ClawHub 的生态下载量互不可比,别混用。
14
+ # 可选过滤参数(builder 未接,按需加):language(ISO 码,如 zh)、category、occupation。
15
+ #
16
+ # 实现: scripts/engines_builders_skill.py::_build_skillsmp_engine
7
17
  # 验证:
8
18
  # python3 scripts/engine_validate.py --engine skillsmp --stage all --admit --write-doc
9
19
 
10
20
  engine_id: skillsmp
11
- type: http
21
+ type: skillsmp
12
22
  enabled: true
13
23
  cost_tier: free
14
24
  label: SkillsMP 技能目录
@@ -19,30 +29,22 @@ period: second
19
29
  limit: null
20
30
  cost_per_call: 0.0
21
31
  cost_unit: free
22
- method: GET
23
- url: https://skillsmp.com/api/v1/skills/search
24
32
  timeout: 15
25
33
  canary_query: "git commit"
26
34
  coverage:
27
35
  - skill
28
36
  - developer
29
37
  - tech
30
- desc: "SkillsMP Agent 技能聚合目录(200万+ 开源技能独立索引,免费 keyless REST API,stars 排序)"
31
- format: json
32
- query_param: q
33
- extra_params:
34
- limit: "{n}"
35
- sortBy: stars
38
+ desc: "SkillsMP Agent 技能聚合目录(200万+ 开源技能独立索引,免认证,带仓库星数与可安装的 GitHub 目录)"
39
+ # 可验证出处声明(L3 builder 自行拼字段,不读本表;保留它是为了把「这个源
40
+ # 必须给出能装的地址」写成声明,由 tests/test_skill_registry_contract.py 把守)。
41
+ # builder 侧对应实现:url 优先 githubUrl(缺失回落 skillUrl),摘要前缀带星数。
36
42
  output_map:
37
43
  items: data.skills
38
44
  item_title: name
39
45
  item_url: skillUrl
40
46
  item_summary: description
41
- # 可验证出处:githubUrl 指向该技能在上游仓里的**目录**(…/tree/main/.agents/
42
- # skills/xxx),是能核对、能安装的那个地址;skillUrl 只是市场页。
43
47
  item_upstream: githubUrl
44
- # updatedAt 是 epoch **秒**(ClawHub 同名字段是毫秒,差 1000 倍,由
45
- # engines_base._normalize_epoch 按量级归一成日期)。
46
48
  item_published_at: updatedAt
47
49
  quality_queries:
48
50
  - query: "git commit"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "argo-search",
3
- "version": "2.9.9",
4
- "description": "Argo 阿尔戈 — 统一搜索与证据核验。推荐 npx -y argo-search(npm 发布版)或 install.sh 安装。多语言路由、272 个源(235 个免密钥开箱可用)、影视/体育/金融等垂直源、19 个 MCP 工具(与 CLI 能力面对齐)。",
3
+ "version": "2.10.0",
4
+ "description": "Argo 阿尔戈 — 统一搜索与证据核验。推荐 npx -y argo-search(npm 发布版)或 install.sh 安装。多语言路由、284 个源(241 个免密钥开箱可用)、影视/体育/金融等垂直源、19 个 MCP 工具(与 CLI 能力面对齐)。",
5
5
  "keywords": [
6
6
  "mcp",
7
7
  "mcp-server",
@@ -53,6 +53,7 @@
53
53
  "docs/RELEASE_NOTES_v2.8.8.md",
54
54
  "docs/RELEASE_NOTES_v2.8.9.md",
55
55
  "docs/RELEASE_NOTES_v2.9.0.md",
56
+ "docs/RELEASE_NOTES_v2.10.0.md",
56
57
  "docs/RELEASE_NOTES_v2.9.9.md",
57
58
  "docs/RELEASE_NOTES_v2.9.8.md",
58
59
  "docs/assets/",
@@ -5,7 +5,7 @@ DeepSeek Harness 插件:一行同时挂上 [Argo](https://github.com/taxueseek
5
5
  ## 安装
6
6
 
7
7
  ```bash
8
- dsh plugin --profile web add @taxueseek/argo-dsh # npm 发布版,已支持,当前 2.9.9
8
+ dsh plugin --profile web add @taxueseek/argo-dsh # npm 发布版,已支持,当前 2.10.0
9
9
  dsh plugin --profile web add "github:taxueseek/argo#main&path:packages/dsh-plugin" # GitHub main
10
10
  ```
11
11
 
@@ -102,7 +102,8 @@ argo 的 `deepseek_search` 引擎(官方 `api.deepseek.com/v1/tools/search`,
102
102
 
103
103
  | argo-dsh | DSH Harness | 说明 |
104
104
  |----------|-------------|------|
105
- | 2.9.9(当前) | 0.2.1-rc.2(当前,运行中) | 自带设置页(接入 / 工具 / API 密钥 / 研究 / 高级)新增路由观测卡片(getRouteHealth 只读本机 usage_log / route.jsonl 汇总最近路由决策,无日志不假装有数据)与工具推荐组合(按场景一键套用工具勾选,中英双语);双栈入口 `startActivation({provider, label, request, signal, delivery})`;rc.2 移除 `toolFilter` 启动期字段后由插件内 tool guard 阻止 worker 嵌套调用 `wide_research`;`wide_research` 端到端实测通过(planner → 2 worker → synthesis,passed=true / 14 sources) |
105
+ | 2.10.0(当前) | 0.2.1-rc.2(当前,运行中) | 与 2.9.9 同一套宿主适配;本版新增的技能索引/DSH 插件目录源与视频抓取都走既有工具面,插件侧无需改动 |
106
+ | 2.9.9(上一版,兼容) | 0.2.1-rc.2(当前,运行中) | 自带设置页(接入 / 工具 / API 密钥 / 研究 / 高级)新增路由观测卡片(getRouteHealth 只读本机 usage_log / route.jsonl 汇总最近路由决策,无日志不假装有数据)与工具推荐组合(按场景一键套用工具勾选,中英双语);双栈入口 `startActivation({provider, label, request, signal, delivery})`;rc.2 移除 `toolFilter` 启动期字段后由插件内 tool guard 阻止 worker 嵌套调用 `wide_research`;`wide_research` 端到端实测通过(planner → 2 worker → synthesis,passed=true / 14 sources) |
106
107
  | 2.9.7(上一版,兼容) | 0.2.1-alpha.1(实测,兼容) | 旧宿主走 `start(provider, request)` 分支,`toolFilter` 启动期字段仍认;该分支由插件单测覆盖,未在 alpha.x 上重跑端到端 |
107
108
  | 2.9.2 | 0.2.1-alpha.1(实测) | 上一轮适配验证基线;rc.2 的新入口与 tool guard 自 2.9.4 起进入 |
108
109
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taxueseek/argo-dsh",
3
- "version": "2.9.9",
3
+ "version": "2.10.0",
4
4
  "description": "Argo 阿尔戈 — DSH plugin:argo 原生搜索/抓取工具 + web_search seam + wide_research 编排;自带设置页(接入/工具/API 密钥/研究/高级);argo MCP 19 工具全量面按需挂载。安装:dsh plugin --profile web add @taxueseek/argo-dsh(或从 GitHub main 装:dsh plugin --profile web add \"github:taxueseek/argo#main&path:packages/dsh-plugin\")",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -0,0 +1,113 @@
1
+ // size-gate.test.js — dsh-plugin 单文件体积门禁(防「千行文件」复发)。
2
+ //
3
+ // ## 为什么要这道门
4
+ //
5
+ // Python 侧自 2026-09-22 起有 tests/test_module_size_gate.py(1000 行上限 +
6
+ // 祖父清单),这里补的是同一条门禁的 JS 对等物:2026-10-22 拆客户端时
7
+ // client.js 1,533 行,到 10-26 已涨到 1,599 行——两周 +66,且**没有任何
8
+ // 门禁会说话**。单文件超过千行后,改一处的定位成本(读完整条渲染链)比
9
+ // 拆模块的迁移成本涨得更快;趋势必须先钉住,再谈拆。
10
+ //
11
+ // ## 规则(与 Python 侧逐条对齐)
12
+ //
13
+ // 1. 上限 1000 行:dsh/ 下任何生产文件不得超过;
14
+ // 2. 祖父清单:拆不动的大文件显式登记「上限 = 登记时的行数」,只能减不能增;
15
+ // 3. 新增文件天然合规:不在清单里,直接吃 1000 上限;
16
+ // 4. 上限不得高于实际行数(清单不许虚高),每条必须写拆不开的理由。
17
+ //
18
+ // ## 清单怎么维护
19
+ //
20
+ // 拆走一块 → 把上限改成新的行数(或整条删掉,若已 ≤ 1000);想加功能又
21
+ // 超上限时,正解是拆模块,不是把数字往上调;真要上调,理由写进 reason。
22
+
23
+ import { test } from 'node:test'
24
+ import assert from 'node:assert/strict'
25
+ import { readFileSync, readdirSync } from 'node:fs'
26
+ import { dirname, join, relative } from 'node:path'
27
+ import { fileURLToPath } from 'node:url'
28
+
29
+ const PKG_ROOT = dirname(dirname(fileURLToPath(import.meta.url)))
30
+ const DSH_DIR = join(PKG_ROOT, 'dsh')
31
+
32
+ const HARD_LIMIT = 1000
33
+
34
+ // 路径 → [上限行数, 为什么不拆/拆到哪一步]
35
+ const GRANDFATHERED = new Map([
36
+ ['dsh/client.js', [
37
+ 1599,
38
+ 'web 设置面板单页(接入/工具/密钥/研究/高级五段 UI + 状态机);' +
39
+ '2026-10-26 面板升级后 1,533 → 1,599,功能与测试同批落地;' +
40
+ '拆分候选:把各段表单渲染抽成 render-* 模块,状态机留在本文件',
41
+ ]],
42
+ ])
43
+
44
+ function lineCount(file) {
45
+ const text = readFileSync(file, 'utf8')
46
+ const lines = text.split('\n')
47
+ // 与 wc -l / Python splitlines 同口径:以换行结尾时不算多一行
48
+ return text.endsWith('\n') ? lines.length - 1 : lines.length
49
+ }
50
+
51
+ function productionFiles() {
52
+ return readdirSync(DSH_DIR)
53
+ .filter((name) => name.endsWith('.js') || name.endsWith('.mjs'))
54
+ .sort()
55
+ .map((name) => join(DSH_DIR, name))
56
+ }
57
+
58
+ test('没有生产文件超过 1000 行且未登记', () => {
59
+ const offenders = []
60
+ for (const file of productionFiles()) {
61
+ const rel = relative(PKG_ROOT, file)
62
+ if (GRANDFATHERED.has(rel)) continue
63
+ const n = lineCount(file)
64
+ if (n > HARD_LIMIT) {
65
+ offenders.push(`${rel}: ${n} 行(上限 ${HARD_LIMIT})`)
66
+ }
67
+ }
68
+ assert.deepEqual(
69
+ offenders,
70
+ [],
71
+ '文件超过 1000 行且未登记。请先拆模块;确有必要登记时在 GRANDFATHERED 里写明理由:\n ' +
72
+ offenders.join('\n '),
73
+ )
74
+ })
75
+
76
+ test('祖父文件只能减不能增', () => {
77
+ const grown = []
78
+ for (const [rel, [ceiling]] of GRANDFATHERED) {
79
+ const file = join(PKG_ROOT, rel)
80
+ const n = lineCount(file)
81
+ if (n > ceiling) grown.push(`${rel}: ${n} 行 > 登记上限 ${ceiling}`)
82
+ }
83
+ assert.deepEqual(
84
+ grown,
85
+ [],
86
+ '祖父文件变大了。正解是拆模块并把上限调低;确要上调请在 GRANDFATHERED 里改数字并说明理由:\n ' +
87
+ grown.join('\n '),
88
+ )
89
+ })
90
+
91
+ test('祖父上限不得高于实际行数(清单不许虚高)', () => {
92
+ const inflated = []
93
+ for (const [rel, [ceiling]] of GRANDFATHERED) {
94
+ const n = lineCount(join(PKG_ROOT, rel))
95
+ if (ceiling > n) {
96
+ inflated.push(`${rel}: 上限 ${ceiling} > 实际 ${n}(请下调到 ${n})`)
97
+ }
98
+ }
99
+ assert.deepEqual(
100
+ inflated,
101
+ [],
102
+ '祖父清单的上限比实际行数高——把上限收到实际行数:\n ' + inflated.join('\n '),
103
+ )
104
+ })
105
+
106
+ test('每条祖父登记都必须写拆不开的理由', () => {
107
+ for (const [rel, [, reason]] of GRANDFATHERED) {
108
+ assert.ok(
109
+ typeof reason === 'string' && reason.trim().length >= 12,
110
+ `${rel} 的 reason 太短,写清楚卡在哪(数据表性质?缺测试?边界不清?)`,
111
+ )
112
+ }
113
+ })
@@ -106,7 +106,9 @@ class AdaptiveLearner:
106
106
  def __init__(self):
107
107
  self._lock = threading.Lock()
108
108
  self._local = threading.local()
109
- self._score_cache: dict[str, tuple[float, float]] = {} # engine -> (score, expires_at)
109
+ # (engine, domain, lang, purpose) -> (score, samples, expires_at)
110
+ self._score_cache: dict[
111
+ tuple[str, str, str, str], tuple[float, int, float]] = {}
110
112
  self._session_engines: set[str] = set()
111
113
  self._batch_depth = 0
112
114
  self._batch_dirty = False
@@ -239,8 +241,14 @@ class AdaptiveLearner:
239
241
  for _k in [k for k in self._score_cache if k[0] == engine]:
240
242
  self._score_cache.pop(_k, None)
241
243
 
242
- def _score_from_row(self, row) -> float:
243
- """把一条聚合行转成 0~1 推荐分(口径见 get_score)。"""
244
+ def _score_from_row(self, row, purpose: str = "daily") -> float:
245
+ """把一条聚合行转成 0~1 推荐分(口径见 get_score)。
246
+
247
+ `purpose="research"` 把延迟悬崖从 2s 抬到 8s:2s 是**日常档的等待
248
+ 政策**(慢源不该定义第一响应),不是质量判断。研究场景里同一台源
249
+ 4s 交出的扎实证据值得等;沿用 2s 悬崖会让「慢而高质」的源在深研
250
+ 排序里系统性输给「快而泛」的源——正是 2026-10-26 审查发现的偏差。
251
+ """
244
252
  total, judged, judged_ok, avg_latency, avg_cost, avg_q, sum_q, last_ts = row
245
253
  total = int(total or 0)
246
254
  judged = int(judged or 0)
@@ -252,7 +260,8 @@ class AdaptiveLearner:
252
260
  if judged == 0:
253
261
  return 0.5
254
262
  success_rate = (judged_ok or 0) / judged
255
- latency_factor = min(1.0, 2000.0 / max(avg_latency or 2000, 1))
263
+ latency_cap = 8000.0 if purpose == "research" else 2000.0
264
+ latency_factor = min(1.0, latency_cap / max(avg_latency or latency_cap, 1))
256
265
  cost_factor = max(0.3, 1.0 - (avg_cost or 0.0) * 10)
257
266
  return round(success_rate * latency_factor * cost_factor
258
267
  * quality_factor(avg_q, sum_q), 4)
@@ -283,7 +292,7 @@ class AdaptiveLearner:
283
292
  ).fetchone()
284
293
 
285
294
  def get_score(self, engine: str, domain: str | None = None,
286
- lang: str | None = None) -> float:
295
+ lang: str | None = None, purpose: str = "daily") -> float:
287
296
  """获取引擎的综合推荐分数(0.0 ~ 1.0)。
288
297
 
289
298
  **只按「有明确结果」的调用算成功率**(`empty=0`)。
@@ -302,28 +311,46 @@ class AdaptiveLearner:
302
311
  lang) 聚合出「桶分」,与全局分加权融合(桶样本 <3 时权重 0.3,≥3 时 0.5)。
303
312
  这让「引擎在 A 域强、B 域弱」可表达,新引擎也能在建议域里被更快识别。
304
313
  桶为空时回退全局分——旧调用方(不传 domain/lang)行为逐位不变。
314
+
315
+ `purpose`:daily(默认)沿用 2s 延迟悬崖;research 抬到 8s,见
316
+ `_score_from_row`。默认值保证旧调用方逐位不变。
317
+ """
318
+ return self.get_score_with_samples(
319
+ engine, domain, lang, purpose)[0]
320
+
321
+ def get_score_with_samples(self, engine: str, domain: str | None = None,
322
+ lang: str | None = None,
323
+ purpose: str = "daily") -> tuple[float, int]:
324
+ """同 get_score,额外返回有效样本数。
325
+
326
+ 选源层需要区分「0.5 分是因为没数据」与「0.5 分是因为确实平庸」:
327
+ 对无样本的源,实测先验应当做主,而不是被自适应默认分稀释。样本数
328
+ 取场景桶的 judged(桶为空时取全局 judged)。
305
329
  """
306
- key = (engine, domain or "", lang or "")
330
+ key = (engine, domain or "", lang or "", purpose)
307
331
  now = time.time()
308
332
  cached = self._score_cache.get(key)
309
- if cached and cached[1] > now:
310
- return cached[0]
333
+ if cached and cached[2] > now:
334
+ return cached[0], cached[1]
311
335
 
312
336
  with self._lock:
313
337
  cached = self._score_cache.get(key)
314
- if cached and cached[1] > now:
315
- return cached[0]
316
- score = self._score_from_row(self._global_row(engine))
338
+ if cached and cached[2] > now:
339
+ return cached[0], cached[1]
340
+ grow = self._global_row(engine)
341
+ score = self._score_from_row(grow, purpose)
342
+ samples = int((grow[1] if grow else 0) or 0)
317
343
  if domain or lang:
318
344
  brow = self._bucket_row(engine, domain or "", lang or "")
319
345
  b_judged = int(brow[1] or 0)
320
346
  if b_judged > 0:
321
- b_score = self._score_from_row(brow)
347
+ b_score = self._score_from_row(brow, purpose)
322
348
  w = 0.5 if b_judged >= 3 else 0.3
323
349
  score = round((1 - w) * score + w * b_score, 4)
350
+ samples = b_judged
324
351
 
325
- self._score_cache[key] = (score, now + self.SCORE_CACHE_TTL)
326
- return score
352
+ self._score_cache[key] = (score, samples, now + self.SCORE_CACHE_TTL)
353
+ return score, samples
327
354
 
328
355
  def get_ranking(self) -> list[tuple[str, float]]:
329
356
  """获取所有引擎的推荐排名(降序)。空结果的排除口径同 `get_score`。"""
@@ -29,7 +29,12 @@ def fetch(url: str, timeout: int = 30) -> str:
29
29
  # (http/https scheme + 非本机/内网目标),被拒即抛错而非跟随
30
30
  opener = urllib.request.build_opener(_SafeRedirectHandler)
31
31
  with opener.open(req, timeout=timeout) as r:
32
- return r.read().decode("utf-8", errors="ignore")
32
+ raw = r.read()
33
+ try:
34
+ from http_client import decode_response_body
35
+ return decode_response_body(raw, r.headers.get("Content-Type", ""))
36
+ except ImportError:
37
+ return raw.decode("utf-8", errors="ignore")
33
38
 
34
39
 
35
40
  class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
@@ -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]] = []