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
@@ -12,11 +12,15 @@
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
- import os
16
- from typing import Any
15
+ from typing import Any, Callable
17
16
 
18
17
  from config import get_engines
18
+ from general_pool import (configured_general_pool as _configured_general_pool,
19
+ general_fallback as _general_fallback,
20
+ general_kwargs,
21
+ ranked_general as _ranked_general)
19
22
  from quota import get_quota_manager
23
+ from source_selection import candidate_allowed
20
24
  from route_lang import (_enabled_local_engines, _filter_lang_bound_family,
21
25
  _get_registry, _lang_must_keep, _specs_snapshot,
22
26
  lang_allows)
@@ -81,46 +85,8 @@ def _expand_local_search(engine_list: list[str], features: dict | None = None) -
81
85
  return result
82
86
 
83
87
 
84
- def _general_fallback(enabled: set[str]) -> list[str]:
85
- """通用免费源领队 + 本地检索保底(清单唯一来源 engine_policy.GENERAL_FREE_FALLBACK)。
86
-
87
- 域内引擎全被过滤 / 无匹配域时的回退组合。通用免费源在前、local_search 殿后,
88
- 清单与 recovery L3 共用同一常量,避免两处清单漂移。
89
-
90
- local_search 殿后而非领队(2026-10-15 实测定案):日常档 combo_budget=2
91
- (见 engine_policy.combo_budget,fast/auto+fast 都只取前 2 位),
92
- `_expand_local_search` 又把展开出的本地子引擎**追加尾部**——它一旦占住前排,
93
- 尾部子引擎必被预算截断,只剩 local_search 聚合器**独跑**。1059 条真实查询里
94
- 它独跑 109 次、中位 2.9s、45% 超 3s,占全部查询墙钟 369s,而其中纯英文
95
- 技术查询("zig comptime explained" 类)占 82%——本地文件检索对这类 query
96
- 语义上无效,纯亏延迟。改为通用源领队后:常规查询直接落 anysearch/local_bing
97
- (实测 ~1.1-1.7s),local_search 只在通用源全部不可用(熔断/配额耗尽)时
98
- 才顶上前预算位,本地检索能力不减,只是不再无条件霸占首轮。
99
- """
100
- try:
101
- from engine_policy import GENERAL_FREE_FALLBACK
102
- except ImportError:
103
- GENERAL_FREE_FALLBACK = ("anysearch", "octen", "local_bing")
104
- order = list(GENERAL_FREE_FALLBACK)
105
- # 领队覆盖(2026-10-21):A/B 与线上回退都走这里,避免为了复测改常量。
106
- # 传引擎名即把它提到首位(例:ARGO_GENERAL_FALLBACK_LEAD=anysearch 复现
107
- # 2026-10-21 之前的顺位);传空/未知值不生效。与下面的 LEGACY 开关正交。
108
- lead_override = (os.environ.get("ARGO_GENERAL_FALLBACK_LEAD") or "").strip()
109
- if lead_override and lead_override in order:
110
- order = [lead_override] + [e for e in order if e != lead_override]
111
- # 逃生开关:A/B 与线上回退都走这条,避免为了复测改常量。
112
- # 2026-10-17 对拍(交错、随机序):octen 入第二顺位后,anysearch 抖动
113
- # 窗口 p90 3273→1614ms、max 6266→1928ms、错误 9→0;健康窗口中位无差。
114
- try:
115
- from engine_env import env_flag
116
- if env_flag("ARGO_GENERAL_FALLBACK_LEGACY", default=False):
117
- order = [e for e in order if e != "octen"]
118
- except ImportError:
119
- pass
120
- lead = [e for e in order if e in enabled]
121
- # 保底项同样受 enabled 约束:不在 enabled 说明本机压根没注册/被禁用,
122
- # 选它只会在执行层撞 "未知引擎" 空跑。
123
- return lead + (["local_search"] if "local_search" in enabled else [])
88
+ # 通用候选池的顺序策略在 general_pool.py(route_combo 曾因它逼近 1000 行)。
89
+ # 顶部别名保留,既有调用方与测试的 import 路径不变。
124
90
 
125
91
 
126
92
  def _breaker_blocked(engine_id: str) -> bool:
@@ -269,37 +235,49 @@ TFIDF_STRONG_SCORE = 0.15
269
235
 
270
236
 
271
237
  def tfidf_lead_combo(tfidf_best: str | None, tfidf_best_score: float,
272
- enabled: set[str]) -> list[str]:
273
- """TF-IDF 分支的初始 combo:强证据推荐领队 + anysearch 对冲。
238
+ enabled: set[str], *, mode: str = "auto",
239
+ depth: str = "fast", context: str = "search",
240
+ lang: str = "",
241
+ score_fn: Callable[[str, str, str, str],
242
+ tuple[float, int]] | None = None
243
+ ) -> list[str]:
244
+ """TF-IDF 分支的初始 combo:强证据推荐领队 + 通用源对冲。
274
245
 
275
246
  弱证据(≤TFIDF_STRONG_SCORE)时反过来:通用保底领队,推荐引擎殿后
276
247
  作辅源——仍在 combo 里并行竞速,能力不减,只是不再占 primary 位
277
248
  (含 primary 宽限/充分性判定对它的偏袒)。
249
+
250
+ 2026-10-26:对冲位不再写死 octen/anysearch,改由 `_ranked_general`
251
+ 给出当前最优的通用源。静态清单与实测排序的分叉此前导致「走 TF-IDF
252
+ 分支的查询永远用不到 tavily/yuanbao」,同一个无匹配域查询换条路径
253
+ 就换了源。两条路径现在共用同一排序。
278
254
  """
279
255
  strong = bool(tfidf_best and tfidf_best_score > TFIDF_STRONG_SCORE)
256
+ generals = _ranked_general(
257
+ enabled, mode=mode, depth=depth, context=context, lang=lang,
258
+ score_fn=score_fn)
280
259
  lead: list[str] = []
281
260
  if strong:
282
261
  lead = [tfidf_best]
283
- # 垂直领队用 octen 对冲、anysearch 第三;anysearch 领队则反过来。
284
- hedges = ("octen", "anysearch") if tfidf_best != "anysearch" \
285
- else ("anysearch", "octen")
286
- for e in hedges:
287
- if e in enabled and e not in lead:
262
+ for e in generals:
263
+ if len(lead) >= 3:
264
+ break
265
+ if e not in lead:
288
266
  lead.append(e)
289
267
  else:
290
- # 弱证据/无推荐:通用保底领队,弱推荐作为辅源跟在后面(既有契约,
291
- # tests/test_route_tfidf_weak_score.py 锁死),octen 排第三。日常
292
- # budget=2 会截掉第三位,所以弱证据不额外占 octen 的位;低分回退
293
- # 分支(score < TFIDF_MIN_SCORE)走通用兜底链,那里 octen 已在第二。
294
- if "anysearch" in enabled:
295
- lead.append("anysearch")
296
- if tfidf_best and tfidf_best not in lead:
268
+ # 弱证据/无推荐:通用保底领队,弱推荐作为辅源紧跟其后(既有契约,
269
+ # tests/test_route_tfidf_weak_score.py 锁死)。弱推荐占第二槽而不是
270
+ # 第三槽:日常 budget=2 时它仍能参与竞速,与改动前逐位一致;第二个
271
+ # 通用源顺延到第三位。
272
+ lead = list(generals[:1])
273
+ if tfidf_best and tfidf_best not in lead and tfidf_best in enabled:
297
274
  lead.append(tfidf_best)
298
- if "octen" in enabled and "octen" not in lead:
299
- lead.append("octen")
275
+ lead.extend(e for e in generals[1:] if e not in lead)
300
276
  out: list[str] = []
301
277
  for e in lead:
302
- if e in enabled and e not in out:
278
+ # 与 source_selection 同一判据:enabled 成员,或预算内的白名单付费源。
279
+ # 只查 `e in enabled` 会把池排序里已放行的 DeepSeek 在装配阶段再剔掉。
280
+ if candidate_allowed(e, enabled, mode) and e not in out:
303
281
  out.append(e)
304
282
  return out
305
283
 
@@ -323,7 +323,10 @@ def _social_domain_first(hits: list[dict[str, Any]]) -> list[dict[str, Any]]:
323
323
  idx_first_social = hits.index(social[0])
324
324
  # 「热搜/热榜」是比泛 social 更具体的意图:查询里带微博/抖音这类平台名时,
325
325
  # social 会被提前,把 hot_trending 顶掉——用户问的是榜单,不是社交帖子。
326
- _SPECIFIC_BEFORE_SOCIAL = ("redskill_search", "zhihu_user_data", "hot_trending")
326
+ # video 同理:「抖音视频 红烧肉」要的是视频,不是社交帖子;2026-10-27
327
+ # 加 video 域时一并登记,否则 social 提权会把它压回第二位。
328
+ _SPECIFIC_BEFORE_SOCIAL = ("redskill_search", "zhihu_user_data",
329
+ "hot_trending", "video")
327
330
  idx_specific = next(
328
331
  (i for i, h in enumerate(hits)
329
332
  if h.get("name") in _SPECIFIC_BEFORE_SOCIAL), None
@@ -44,6 +44,12 @@ _VERTICAL_NEW_SOURCE: dict[str, tuple[str, ...]] = {
44
44
  # cinii 声明 langs=ja,靠 engines_demote_for_lang 的语言专用源降级,
45
45
  # 只在日语查询里占位;zbmath 语言中立,数学查询与 deep 档可达。
46
46
  "soil_agri": ("openfoodfacts",), # 食品成分库:补 usda(单一国别)之外的多国食品数据
47
+ # 2026-10-26:技能域两个新专源。explainx 给「安装量 + 分类 + 官方标记」,
48
+ # skills.sh 给 Vercel 官方安装遥测——两者都是「这个技能多少人在用」的硬
49
+ # 指标,而此前三个技能源(skillsmp 只有仓库星数、clawhub 只有生态下载量、
50
+ # redskill 只有小红书站内口径)都给不出。声明在既有源之后,由本表加槽,
51
+ # 不挤掉 skillsmp/clawhub/redskill 的位次。
52
+ "skill_search": ("explainx", "skills_sh"),
47
53
  }
48
54
 
49
55
 
package/scripts/search.py CHANGED
@@ -563,6 +563,9 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
563
563
  since: str | None = None,
564
564
  until: str | None = None,
565
565
  sort: str = "relevance",
566
+ video_only: bool = False,
567
+ min_duration: int | None = None,
568
+ max_duration: int | None = None,
566
569
  include_local: bool | None = None,
567
570
  include_domains: list[str] | None = None,
568
571
  exclude_domains: list[str] | None = None,
@@ -735,7 +738,10 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
735
738
  from route import route_query_cached
736
739
 
737
740
  _op_langs = (decision_operators or {}).get("langs") or None
738
- if local_first:
741
+ if video_only and not local_first and engine == "auto":
742
+ from video_route import video_decision
743
+ decision = video_decision(min_duration, max_duration)
744
+ elif local_first:
739
745
  _tk_route = _tick(timing)
740
746
  decision = route_query_cached(
741
747
  original_query, engine_override="local_search", mode=mode,
@@ -751,6 +757,8 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
751
757
  lang_override=_op_langs,
752
758
  )
753
759
  _tock(timing, "route", _tk_route)
760
+ decision.update(video_only=video_only, min_duration=min_duration,
761
+ max_duration=max_duration)
754
762
  if decision_operators:
755
763
  decision["operators"] = decision_operators
756
764
  if context == "research":
@@ -102,6 +102,17 @@ def _max_results_arg(value: str) -> int:
102
102
  return n
103
103
 
104
104
 
105
+ def _non_negative_int(value: str) -> int:
106
+ """argparse 的 `type=`:时长等非负整数(负值不是「不限」,是坏输入)。"""
107
+ try:
108
+ n = int(value)
109
+ except (TypeError, ValueError):
110
+ raise argparse.ArgumentTypeError(f"必须是整数,收到 {value!r}") from None
111
+ if n < 0:
112
+ raise argparse.ArgumentTypeError(f"不能为负(收到 {n})")
113
+ return n
114
+
115
+
105
116
  def build_parser() -> argparse.ArgumentParser:
106
117
  """构造 CLI 参数解析器。
107
118
 
@@ -159,6 +170,16 @@ def build_parser() -> argparse.ArgumentParser:
159
170
  parser.add_argument("--sort", default="relevance",
160
171
  choices=["relevance", "oldest", "newest"],
161
172
  help="时间排序:relevance=相关度(默认), oldest=最早在前(溯源), newest=最新在前")
173
+ parser.add_argument("--video", action="store_true",
174
+ help="只搜视频源(B 站 + anysearch),并只保留视频结果;"
175
+ "不带此开关时视频源只按显式意图路由进入 combo")
176
+ parser.add_argument("--min-duration", type=_non_negative_int, default=None,
177
+ metavar="SEC",
178
+ help="视频最短时长(秒);B 站下推 duration 档位,"
179
+ "其他源按已返回的时长字段后过滤,时长未知的保留")
180
+ parser.add_argument("--max-duration", type=_non_negative_int, default=None,
181
+ metavar="SEC",
182
+ help="视频最长时长(秒);语义同 --min-duration")
162
183
  parser.add_argument("--include-domains", default="",
163
184
  help="仅保留这些域名(含子域),逗号分隔,如 github.com,arxiv.org")
164
185
  parser.add_argument("--exclude-domains", default="",
@@ -438,6 +459,9 @@ def main():
438
459
 
439
460
  if not args.query:
440
461
  parser.error("必须提供搜索关键词")
462
+ if (args.min_duration is not None and args.max_duration is not None
463
+ and args.min_duration > args.max_duration):
464
+ parser.error("--min-duration 不能大于 --max-duration")
441
465
 
442
466
  # envelope 默认**关**,要时显式开(--envelope / --archive)。
443
467
  #
@@ -499,6 +523,9 @@ def main():
499
523
  since=args.since,
500
524
  until=args.until,
501
525
  sort=args.sort,
526
+ video_only=args.video,
527
+ min_duration=args.min_duration,
528
+ max_duration=args.max_duration,
502
529
  include_domains=[d for d in args.include_domains.split(",") if d.strip()] or None,
503
530
  exclude_domains=[d for d in args.exclude_domains.split(",") if d.strip()] or None,
504
531
  engine_domain=engine_domain,
@@ -209,6 +209,15 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
209
209
  cache_engine_key += f"|since={since_iso}"
210
210
  if until_iso and time_aware:
211
211
  cache_engine_key += f"|until={until_iso}"
212
+ # 视频模式与时长过滤进缓存键:--video 与 auto 的结果集不同(前者强制
213
+ # 只留视频),--min-duration 也会改变最终条数;不隔离就会把未过滤的
214
+ # 旧结果当成带条件的答案发回去。
215
+ if (decision or {}).get("video_only"):
216
+ cache_engine_key += "|video=1"
217
+ _min_d = (decision or {}).get("min_duration")
218
+ _max_d = (decision or {}).get("max_duration")
219
+ if _min_d is not None or _max_d is not None:
220
+ cache_engine_key += f"|dur={_min_d or 0}-{_max_d or 0}"
212
221
 
213
222
  if on_progress:
214
223
  on_progress(Stage.ROUTING, {"domain": domain, "engine": engine_label, "engines": engines})
@@ -85,6 +85,31 @@ _AGENT_RESULT_FIELDS = (
85
85
  )
86
86
 
87
87
 
88
+ def _ensure_authority_levels(results: list[dict[str, Any]]) -> None:
89
+ """把上游原生 authority(DeepSeek 0-4)转成离散等级,补齐非精排路径。
90
+
91
+ `search_rank.local_five_dim_rerank` 只在五维精排里写 `authority_level`;
92
+ 单引擎 `--engine`、付费对冲的第二位、以及部分 fast 路径不走精排,于是
93
+ `upstream_authority` 明明在结果里,agent 档的 `authority_level` 却是空。
94
+ DeepSeek 搜索最大的差异点就是这套结构化字段(v2.9.6 接入时的定位),
95
+ 输出层丢掉它等于把价值重新埋回去。这里按 `authority_level` 的唯一实现
96
+ 回填:上游 0-4 优先,缺失/不可解析再走自有分数映射。
97
+ """
98
+ try:
99
+ from rank_signals import authority_level
100
+ except Exception:
101
+ return
102
+ for r in results:
103
+ if not isinstance(r, dict):
104
+ continue
105
+ if r.get("authority_level") is not None:
106
+ continue
107
+ upstream = r.get("upstream_authority")
108
+ if upstream in (None, ""):
109
+ continue
110
+ r["authority_level"] = authority_level(r.get("authority"), upstream)
111
+
112
+
88
113
  def _slim_verify(v: Any) -> dict[str, Any] | None:
89
114
  """verify 块的 agent 精简版:保留「核验后改了什么」,丢掉逐条细节。
90
115
 
@@ -600,6 +625,10 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
600
625
  except Exception:
601
626
  pass
602
627
 
628
+ # 上游权威等级回填(DeepSeek 0-4):单引擎/对冲路径不走五维精排,
629
+ # 不补这一步 agent 档只能看到空 authority_level。
630
+ _ensure_authority_levels(result.get("results") or [])
631
+
603
632
  # 域过滤(后置,引擎无关):融合排序之后裁剪,sources 与 results 保持一致。
604
633
  # 裁剪导致不足 n 条是调用方过滤条件的诚实结果,不回填。
605
634
  if include_domains or exclude_domains:
@@ -433,6 +433,27 @@ def postprocess(req: _SearchRequest, run: _SearchRun, hooks: Any) -> _SearchRun:
433
433
  except OPT_IMPORT + SHAPE_BENIGN: # 软排序增强,任何失败按「不排序」处理
434
434
  pass
435
435
 
436
+ # ── 视频模式/时长过滤(--video / --min-duration)──
437
+ # 必须在 _pool_limit 截断之前:--video 的候选池同时混着 anysearch 的
438
+ # 网页结果,若先截 top-N 再过滤,B 站结果可能整批落在池外(实测
439
+ # --video --min-duration 600 时 6 条 B 站结果在过滤前就被截掉,只剩
440
+ # 1 条 YouTube)。先过滤再截断,池里才都是候选视频。
441
+ video_filtered = 0
442
+ duration_filtered = 0
443
+ duration_unknown = 0
444
+ _video_only = bool((decision or {}).get("video_only"))
445
+ _min_d = (decision or {}).get("min_duration")
446
+ _max_d = (decision or {}).get("max_duration")
447
+ if merged and (_video_only or _min_d is not None or _max_d is not None):
448
+ from video_meta import filter_duration, filter_video_results
449
+ if _video_only:
450
+ merged, video_filtered = filter_video_results(merged)
451
+ if _min_d is not None or _max_d is not None:
452
+ merged, duration_filtered, duration_unknown = filter_duration(
453
+ merged, _min_d, _max_d)
454
+ _log(f"视频过滤:非视频 {video_filtered},时长不符 {duration_filtered},"
455
+ f"时长未知保留 {duration_unknown}")
456
+
436
457
  # 放宽截断:rerank 阶段看到 _pool_limit 条,最终输出再截断 max_results
437
458
  merged = merged[:_pool_limit]
438
459
 
@@ -511,7 +532,11 @@ def postprocess(req: _SearchRequest, run: _SearchRun, hooks: Any) -> _SearchRun:
511
532
  _echo_triggered = _echo_needed(merged, query)
512
533
  except OPT_IMPORT + SHAPE_BENIGN: # 守卫不可用不设卡(fail-open)
513
534
  _echo_triggered = False
514
- if not merged or _echo_triggered:
535
+ # 视频/时长模式不做恢复链:恢复链会跨域补搜普通网页,补进来的结果要么
536
+ # 被 video_only 过滤掉(白付一轮网络),要么绕过时长过滤(把已筛掉的
537
+ # 长/短视频重新带回来)。0 条就直接返回空,条件由调用方自己放宽。
538
+ _video_scope = (_video_only or _min_d is not None or _max_d is not None)
539
+ if (not merged or _echo_triggered) and not _video_scope:
515
540
  from recovery_runner import run_pipeline_recovery
516
541
  _dk = {k: v for k in ("domain", "sub_domain") if (v := getattr(req, "engine_" + k, None))}
517
542
  merged, _rec_info = run_pipeline_recovery(
@@ -671,6 +696,14 @@ def postprocess(req: _SearchRequest, run: _SearchRun, hooks: Any) -> _SearchRun:
671
696
  "noise_dropped": _noise_dropped,
672
697
  "funnel": funnel,
673
698
  }
699
+ # 只有真的用了视频/时长过滤才输出这三个账;普通搜索不塞无意义的 0
700
+ # (输出契约:不适用就整个键缺席)。
701
+ if _video_only or _min_d is not None or _max_d is not None:
702
+ result_payload.update(
703
+ video_filtered=video_filtered,
704
+ duration_filtered=duration_filtered,
705
+ duration_unknown=duration_unknown,
706
+ )
674
707
  if _site_include or _site_exclude:
675
708
  result_payload["site_filter"] = {
676
709
  "sites": _site_include, "exclude_sites": _site_exclude,
@@ -914,6 +947,11 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
914
947
  if result_payload.get("site_filter") is not None:
915
948
  out["site_filter"] = result_payload["site_filter"]
916
949
  out["site_filtered"] = result_payload.get("site_filtered", 0)
950
+ # 视频/时长过滤账:用于解释「--min-duration 后为什么只剩 N 条」,
951
+ # duration_unknown 明确告诉调用方有多少条没有时长、未被严格过滤。
952
+ for _key in ("video_filtered", "duration_filtered", "duration_unknown"):
953
+ if _key in result_payload:
954
+ out[_key] = result_payload[_key]
917
955
  if lang_pref_info is not None:
918
956
  out["lang_pref"] = lang_pref_info
919
957
  if timing is not None:
@@ -102,6 +102,7 @@ _ENGINE_FUSION_WEIGHTS: dict[str, float] = {
102
102
  "core": 1.3, "openreview": 1.3, "zenodo": 1.2, "datacite": 1.2,
103
103
  "sec_edgar": 1.3, "federal_register": 1.3, "eu_opendata": 1.3,
104
104
  "egov_law": 1.3, "openstd": 1.3, "who_gho": 1.3, "usgs": 1.3, "nasa_cmr": 1.3,
105
+ "dshopen": 1.2, "deepseek1024": 1.2, "dsh_hub": 1.15, # DSH 插件目录三源(答案型;理由见 config.yaml dsh_plugin_search.score_floors)
105
106
  # 通用引擎(基线)
106
107
  "duckduckgo": 1.0, "local_bing": 1.0, "local_duckduckgo": 1.0,
107
108
  "local_google": 1.0, "anysearch": 1.05, "byted": 1.1, "bocha": 1.0,
@@ -2,21 +2,38 @@
2
2
  """B站搜索引擎
3
3
 
4
4
  使用 B站公开搜索 API(无需登录可搜索视频)。
5
+
6
+ 2026-10-27 起补三件事(此前搜到视频但读不出「这是视频、多长、谁发的」):
7
+ - 时长筛选:把 --min-duration/--max-duration 映射成 B 站 API 的 duration
8
+ 档位(1=<10min、2=10-30、3=30-60、4=>60min),档位表达不了的范围
9
+ 再按解析出的秒数后过滤;
10
+ - 元数据完整化:发布时间转 ISO、收藏/投币/分享一并带出(envelope 只映射
11
+ 它认识的键,但引擎层不该先丢);
12
+ - snippet 前置「UP主 · 时长 · 播放量」:否则五维排序和下游模型只看到标题,
13
+ 视频结果无法按「长视频/高播放」判断。
5
14
  """
6
15
 
16
+ from __future__ import annotations
17
+
18
+ import html
7
19
  import json
20
+ import os
21
+ import re
22
+ import sys
8
23
  import time
9
24
  import urllib.error
10
25
  import urllib.parse
11
26
  import urllib.request
27
+ from datetime import datetime, timedelta, timezone
12
28
 
13
29
  # 出口调度唯一入口(issue #13 同类修复):urlopen 原生只认标准 HTTP(S)_PROXY
14
30
  # 环境变量,**不认** config.yaml 的 network.proxy —— 裸用会在「必须经代理才能
15
31
  # 出网」的环境里整源连不上。本文件在 scripts/ 子目录,父目录不在 sys.path 上。
16
- import os
17
- import sys
18
32
  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19
33
  from net_proxy import open_url # noqa: E402
34
+ from video_meta import parse_duration_seconds # noqa: E402
35
+
36
+ _TZ_CN = timezone(timedelta(hours=8))
20
37
 
21
38
 
22
39
  def _http_get_with_retry(url: str, headers: dict, timeout: int = 10, max_retries: int = 2):
@@ -44,55 +61,169 @@ def _http_get_with_retry(url: str, headers: dict, timeout: int = 10, max_retries
44
61
  return b"", 0
45
62
 
46
63
 
47
- def search(query: str, n: int = 5) -> list[dict]:
48
- """通过 B站搜索 API 搜索"""
49
- encoded = urllib.parse.quote(query)
50
- url = (
51
- f"https://api.bilibili.com/x/web-interface/search/all/v2"
52
- f"?keyword={encoded}&page=1&pagesize={n}"
53
- )
64
+ def _duration_bucket(min_seconds, max_seconds):
65
+ """把秒级范围映射成 B 站搜索的 duration 档位;跨档返回 None(只后过滤)。
66
+
67
+ 档位语义来自 B 站 search/all/v2:1=<10min、2=10-30min、3=30-60min、
68
+ 4=>60min。档位只做**粗召回**,精确范围仍由 _parse_bilibili_response
69
+ 里的后过滤保证;两者都做,才不会为了精确而丢掉「档位内但不在区间」的
70
+ 大量候选。
71
+ """
72
+ if min_seconds is None and max_seconds is None:
73
+ return None
74
+ if min_seconds is None:
75
+ # 只有上限时唯一安全的档位是「≤10 分钟」(档位 1 正好覆盖全集)。
76
+ # 上限 30/60 分钟不能用档位 2/3:那会把更短的视频一起排除,而用户
77
+ # 只要求「不超过」,没有要求「至少 10/30 分钟」。
78
+ return 1 if max_seconds <= 600 else None
79
+ if max_seconds is None:
80
+ # 只有下限时同理:档位 4(>60 分钟)是下限 ≥60 分钟的安全超集;
81
+ # 下限 10/30 分钟不能用档位 2/3,否则会丢掉更长(>30/>60)的视频。
82
+ return 4 if min_seconds >= 3600 else None
83
+ if min_seconds >= 3600:
84
+ return 4
85
+ if 600 <= min_seconds and max_seconds <= 1800:
86
+ return 2
87
+ if 1800 <= min_seconds and max_seconds <= 3600:
88
+ return 3
89
+ if max_seconds <= 600:
90
+ return 1
91
+ return None
92
+
93
+
94
+ def _format_play(count) -> str:
95
+ try:
96
+ n = int(count)
97
+ except (TypeError, ValueError):
98
+ return ""
99
+ if n >= 10000:
100
+ text = f"{n / 10000:.1f}万"
101
+ return text.replace(".0万", "万")
102
+ return str(n)
103
+
104
+
105
+ def _published_iso(ts) -> str:
106
+ try:
107
+ return datetime.fromtimestamp(int(ts), tz=_TZ_CN).isoformat()
108
+ except (TypeError, ValueError, OSError):
109
+ return ""
110
+
111
+
112
+ def _clean_title(raw: str) -> str:
113
+ """B 站搜索标题带 <em class="keyword"> 高亮和 HTML 实体。"""
114
+ text = re.sub(r"<[^>]+>", "", raw or "")
115
+ return html.unescape(text).strip()
116
+
117
+
118
+ def _snippet_of(item: dict, title: str) -> str:
119
+ """把视频元数据前置到摘要:排序器与模型都需要「多长、谁发的、多少人看」。"""
120
+ meta = []
121
+ author = (item.get("author") or "").strip()
122
+ duration = (item.get("duration") or "").strip()
123
+ play = _format_play(item.get("play"))
124
+ if author:
125
+ meta.append(f"UP主 {author}")
126
+ if duration:
127
+ meta.append(f"时长 {duration}")
128
+ if play:
129
+ meta.append(f"播放 {play}")
130
+ desc = (item.get("description") or "").strip()
131
+ parts = meta + ([desc] if desc else [])
132
+ return " · ".join(parts)[:300] or title[:300]
133
+
134
+
135
+ def search(query: str, n: int = 5, min_duration=None, max_duration=None) -> list[dict]:
136
+ """通过 B站搜索 API 搜索。
137
+
138
+ min_duration/max_duration 单位是秒;None 表示不限制。带时长条件时多取
139
+ 一些候选(档位粗召回后还要后过滤),避免筛完不足 n 条。
140
+
141
+ B 站 search API 单页上限实测 20 条(pagesize=50 仍只回 20),所以
142
+ 「档位表达不了、只能后过滤」时按页取 3 页再按 bvid 去重,而不是把
143
+ pagesize 调大(调大无效)。
144
+ """
145
+ bucket = _duration_bucket(min_duration, max_duration)
146
+ filtered = min_duration is not None or max_duration is not None
147
+ pages = 3 if filtered and bucket is None else 1
148
+ # 翻页场景取满单页(20 条),否则 3 页只有 3n 条、长视频更容易筛空。
149
+ page_size = 20 if pages > 1 else min(20, max(n, 1))
54
150
  headers = {
55
151
  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
56
152
  "Referer": "https://www.bilibili.com"
57
153
  }
58
- try:
59
- body, _ = _http_get_with_retry(url, headers, timeout=10, max_retries=2)
60
- data = json.loads(body.decode("utf-8"))
61
- return _parse_bilibili_response(data, n)
62
- except Exception as e:
154
+ results: list[dict] = []
155
+ seen: set[str] = set()
156
+ last_error: Exception | None = None
157
+ for page in range(1, pages + 1):
158
+ params = {"keyword": query, "page": page, "pagesize": page_size}
159
+ if bucket is not None:
160
+ params["duration"] = bucket
161
+ url = ("https://api.bilibili.com/x/web-interface/search/all/v2?"
162
+ + urllib.parse.urlencode(params))
163
+ try:
164
+ body, _ = _http_get_with_retry(url, headers, timeout=10, max_retries=2)
165
+ data = json.loads(body.decode("utf-8"))
166
+ except Exception as e:
167
+ last_error = e
168
+ break
169
+ for item in _parse_bilibili_response(
170
+ data, n, min_duration=min_duration, max_duration=max_duration):
171
+ url_key = item.get("url") or ""
172
+ if url_key in seen:
173
+ continue
174
+ seen.add(url_key)
175
+ results.append(item)
176
+ if len(results) >= n:
177
+ break
178
+ if results:
179
+ return results[:n]
180
+ if last_error is not None:
63
181
  # 吞异常返空会让 MCP 社交搜索把网络故障静默报成「平台成功、0 结果」
64
182
  # (mcp_handlers 的 err=None 设计依赖引擎抛异常或返 error 占位,
65
183
  # 见 tests/test_regression_p0p1.py「零结果应以 errors 提示」契约)。
66
184
  # 对齐 zhihu_engine 范式:失败必须带着 error 字段浮上来。
67
- return [{"error": f"bilibili {type(e).__name__}: {e}", "source": "bilibili"}]
185
+ return [{"error": f"bilibili {type(last_error).__name__}: {last_error}",
186
+ "source": "bilibili"}]
187
+ return []
68
188
 
69
189
 
70
- def _parse_bilibili_response(data: dict, n: int) -> list[dict]:
71
- """解析 B站 API 响应"""
190
+ def _parse_bilibili_response(data: dict, n: int,
191
+ min_duration=None, max_duration=None) -> list[dict]:
192
+ """解析 B站 API 响应;时长条件在这里做精确后过滤。"""
72
193
  results = []
73
194
  data_data = data.get("data", {})
74
195
  for result_type in data_data.get("result", []):
75
196
  if result_type.get("result_type") != "video":
76
197
  continue
77
- for item in result_type.get("data", [])[:n]:
78
- title = item.get("title", "")
79
- # 清理 HTML 标签
80
- import re
81
- title = re.sub(r'<[^>]+>', '', title)
198
+ for item in result_type.get("data", []):
199
+ duration_text = item.get("duration", "")
200
+ seconds = parse_duration_seconds(duration_text)
201
+ if seconds is not None:
202
+ if min_duration is not None and seconds < min_duration:
203
+ continue
204
+ if max_duration is not None and seconds > max_duration:
205
+ continue
206
+ title = _clean_title(item.get("title", ""))
207
+ play = item.get("play", 0)
82
208
  results.append({
83
209
  "title": title[:100] + ("..." if len(title) > 100 else ""),
84
210
  "url": f"https://www.bilibili.com/video/{item.get('bvid', '')}",
85
- "snippet": (item.get("description", "") or title)[:300],
211
+ "snippet": _snippet_of(item, title),
86
212
  "source": "bilibili",
87
213
  "score": max(1.0 - len(results) * 0.1, 0.1),
88
214
  "social_meta": {
89
215
  "platform": "bilibili",
90
216
  "content_type": "video",
91
217
  "author": item.get("author", ""),
92
- "duration": item.get("duration", ""),
93
- "play_count": item.get("play", 0),
218
+ "duration": duration_text,
219
+ "duration_seconds": seconds,
220
+ "play_count": play,
94
221
  "danmu_count": item.get("video_review", 0),
95
222
  "like_count": item.get("like", 0),
223
+ "favorite_count": item.get("favorites", 0),
224
+ "coin_count": item.get("coin", 0),
225
+ "share_count": item.get("share", 0),
226
+ "published_at": _published_iso(item.get("pubdate")),
96
227
  "bvid": item.get("bvid", ""),
97
228
  }
98
229
  })
@@ -109,6 +240,10 @@ def main():
109
240
  parser.add_argument("action", nargs="?", default="search")
110
241
  parser.add_argument("query", nargs="?")
111
242
  parser.add_argument("-n", type=int, default=5)
243
+ parser.add_argument("--min-duration", type=int, default=None,
244
+ help="最小时长(秒)")
245
+ parser.add_argument("--max-duration", type=int, default=None,
246
+ help="最大时长(秒)")
112
247
  parser.add_argument("--json", action="store_true")
113
248
  args = parser.parse_args()
114
249
 
@@ -116,7 +251,9 @@ def main():
116
251
  print("[]")
117
252
  return
118
253
 
119
- results = search(args.query, args.n)
254
+ results = search(args.query, args.n,
255
+ min_duration=args.min_duration,
256
+ max_duration=args.max_duration)
120
257
  if args.json:
121
258
  print(json.dumps(results, ensure_ascii=False))
122
259
  else: