argo-search 2.17.0 → 2.18.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 (70) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.es.md +10 -5
  3. package/README.ja.md +10 -5
  4. package/README.ko.md +10 -5
  5. package/README.md +11 -6
  6. package/README.zh.md +11 -6
  7. package/SKILL.md +12 -11
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +3 -3
  10. package/backends/domain_profiles.json +6 -0
  11. package/backends/engine_registry.yaml +12 -0
  12. package/backends/quota_profiles.json +10 -0
  13. package/bin/argo +78 -12
  14. package/docs/CHANGELOG.md +19 -1
  15. package/docs/COMMIT_STANDARD.md +2 -2
  16. package/docs/ENGINE_CATALOG.md +7 -6
  17. package/docs/RELEASE_NOTES_v2.17.0.md +4 -2
  18. package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
  19. package/docs/RELEASING.md +1 -1
  20. package/engines/specs/twitter_cli.yaml +17 -0
  21. package/engines/specs/twitter_syndication.yaml +2 -3
  22. package/package.json +2 -1
  23. package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
  24. package/packages/dsh-plugin/dsh/workbench-io.js +34 -15
  25. package/packages/dsh-plugin/dsh/workbench-search.js +66 -6
  26. package/packages/dsh-plugin/dsh/workbench.js +43 -0
  27. package/packages/dsh-plugin/package.json +1 -1
  28. package/packages/dsh-plugin/test/workbench-concurrency.test.js +9 -11
  29. package/packages/dsh-plugin/test/workbench.test.js +85 -0
  30. package/scripts/affected_tests.py +324 -0
  31. package/scripts/badcase_ledger.py +93 -2
  32. package/scripts/check_commit_report.py +13 -9
  33. package/scripts/cli_io.py +8 -3
  34. package/scripts/engine_families.py +1 -0
  35. package/scripts/engine_states.py +4 -4
  36. package/scripts/engines.py +2 -0
  37. package/scripts/engines_base.py +12 -28
  38. package/scripts/engines_builders_intl.py +20 -94
  39. package/scripts/engines_twitter_cli.py +182 -0
  40. package/scripts/fetch_cli_output.py +75 -0
  41. package/scripts/fetch_dispatch.py +248 -0
  42. package/scripts/fetch_quality.py +11 -0
  43. package/scripts/fetch_v3.py +48 -114
  44. package/scripts/intent_router.py +224 -0
  45. package/scripts/mcp_compact.py +3 -0
  46. package/scripts/mcp_handlers.py +24 -4
  47. package/scripts/mcp_tools.py +2 -0
  48. package/scripts/mcp_transport.py +1 -1
  49. package/scripts/mcp_warm.py +15 -11
  50. package/scripts/output_transparency.py +10 -0
  51. package/scripts/pre-commit +9 -1
  52. package/scripts/release_check.py +1 -2
  53. package/scripts/research_notes.py +52 -5
  54. package/scripts/retry_policy.py +17 -3
  55. package/scripts/route_combo.py +8 -3
  56. package/scripts/search.py +29 -29
  57. package/scripts/search_cli.py +104 -8
  58. package/scripts/search_output.py +4 -1
  59. package/scripts/social_research.py +8 -6
  60. package/scripts/time_utils.py +28 -0
  61. package/scripts/twitter_single_read.py +107 -0
  62. package/scripts/x_keyword_route.py +138 -0
  63. package/scripts/x_search.py +24 -33
  64. package/scripts/zhihu_answer_body.py +96 -0
  65. package/scripts/zhihu_answer_fetch.py +66 -0
  66. package/scripts/zhihu_answer_lookup.py +138 -0
  67. package/sub-skills/local-seek/SKILL.md +3 -1
  68. package/sub-skills/local-seek/scripts/seek.py +80 -109
  69. package/sub-skills/local-seek/scripts/seek_git.py +65 -0
  70. package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
package/scripts/search.py CHANGED
@@ -782,38 +782,38 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
782
782
 
783
783
  # L1 并行化:本地搜索与主搜索并行提交(仅显式开启时在宽根下提示)。
784
784
  _local_seek_explicit = include_local is not None
785
- # 「用户没有显式关掉」= 自动路径或显式 True;显式 False 不报跳过
786
- # (用户说了不要,不必再解释)。None 是自动路径,必须算「请求过」。
787
785
  _include_local_requested = include_local is not False
788
786
  include_local = _resolve_include_local(include_local, mode, query,
789
787
  decision.get("domain"))
790
- # 自动路径被判据跳过(公域查询 + 无本地信号):这是「没跑」而非「跑了没
791
- # 命中」,必须留痕,否则与显式 --no-local 无法区分(前者是系统优化,
792
- # 后者是用户选择)。显式 False 不写——用户已经说了不要,不必再报。
793
788
  _local_seek_intent_skipped = (_include_local_requested and not include_local)
789
+ from x_keyword_route import is_x_request, search_x_keywords
790
+ x_route = not local_first and not video_only and is_x_request(engine, query, decision)
791
+ if x_route:
792
+ include_local = _local_seek_intent_skipped = False
794
793
  _local_seek_future = None
795
794
  if include_local:
796
795
  _local_seek_future = _get_local_seek_executor().submit(
797
796
  _run_local_seek, query, n, warn=_local_seek_explicit,
798
797
  echo=not quiet)
799
798
 
800
- result = execute_search(
801
- query=search_query, decision=decision, max_results=n,
802
- timeout=timeout, depth=depth, cache=cache,
803
- skip_cache=skip_cache, mode=mode, on_progress=on_progress,
804
- since=since, until=until, sort=sort, timing=timing,
805
- engine_domain=engine_domain, engine_sub_domain=engine_sub_domain,
806
- )
799
+ if x_route:
800
+ result = search_x_keywords(query, n, engine=engine, since=since, until=until, timeout=timeout)
801
+ from time_utils import sort_results_by_time
802
+ result['results'] = sort_results_by_time(result['results'], sort)
803
+ result.update(mode=mode, depth=depth)
804
+ else:
805
+ result = execute_search(
806
+ query=search_query, decision=decision, max_results=n,
807
+ timeout=timeout, depth=depth, cache=cache,
808
+ skip_cache=skip_cache, mode=mode, on_progress=on_progress,
809
+ since=since, until=until, sort=sort, timing=timing,
810
+ engine_domain=engine_domain, engine_sub_domain=engine_sub_domain,
811
+ )
807
812
 
808
- # include-local 等待预算(H1,2026-09-29):deadline 跨两个等待点共享
809
- #(此处的预等待 + 下方 shape_response 的合并等待),总预算不叠加。
810
- # 主结果命中缓存时收窄到宽限窗(_local_seek_grace_s() 调用时取值:
811
- # 模块级常量只在 import 时读 env,MCP 常驻进程里改 ARGO_LOCAL_SEEK_GRACE_S
812
- # 不生效——与 _straggler_grace()/_serial_stagger() 同一原则)。
813
+ # 两个等待点共享截止时间;主结果命中缓存时使用更短的宽限窗。
813
814
  _local_wait_cached = isinstance(result, dict) and bool(result.get("cached"))
814
815
  _local_deadline = time.monotonic() + (_local_seek_grace_s() if _local_wait_cached
815
816
  else _LOCAL_SEEK_TIMEOUT_S)
816
- # 主搜索完成后,本地搜索应已就绪;若未完成则等待剩余预算
817
817
  if _local_seek_future is not None:
818
818
  try:
819
819
  _local_seek_future.result(timeout=max(_local_deadline - time.monotonic(), 0))
@@ -958,24 +958,24 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
958
958
  f"{_name}: registry 查无此引擎(拼写错误,或该源未随本版发布)")
959
959
 
960
960
  # 本机检索账(耗时/命中数/跳过):口径单点在 local_seek_accounting()。
961
- # 意图跳过(公域查询)与用户显式 --no-local 都要留痕,但语义不同:
962
- # 前者是系统判据,后者是用户选择——分开标记,日志里可归因。
961
+ # 意图跳过与用户显式 --no-local 都留痕,但语义不同——响应字段里分开标记。
962
+ # 跳过条目不落日志(2026-11-24):local_seek.jsonl 实测 93.7% 是跳过项
963
+ # (1490 条中 1412 条),stats / badcase_ledger 都不读这个流,唯一效果是
964
+ # 把「这次没查」刷成与「查了没有」同形的噪声;跳过率已在响应里逐次可见。
963
965
  try:
964
- _ls_acct = ({"local_seek_skipped": True,
965
- "skip_reason": "public_domain_intent"}
966
+ _ls_acct = ({"local_seek_skipped": True, "skip_reason": "public_domain_intent"}
966
967
  if _local_seek_intent_skipped else local_seek_accounting())
967
968
  result.update(_ls_acct)
968
969
  from usage_log import emit as _emit_usage_log
969
970
  from search_attribution import is_synthetic_run as _is_syn
970
- if include_local or _local_seek_intent_skipped:
971
- if not _is_syn(result.get("engines_used")):
972
- _ls_acct.update(query=(original_query or "")[:60],
973
- elapsed_ms=result.get("elapsed_ms"),
974
- count=result.get("count"))
975
- _emit_usage_log("local_seek", _ls_acct)
971
+ if include_local and not _local_seek_intent_skipped \
972
+ and not _is_syn(result.get("engines_used")):
973
+ _ls_acct.update(query=(original_query or "")[:60],
974
+ elapsed_ms=result.get("elapsed_ms"),
975
+ count=result.get("count"))
976
+ _emit_usage_log("local_seek", _ls_acct)
976
977
  except Exception:
977
978
  pass
978
-
979
979
  return result
980
980
 
981
981
 
@@ -229,6 +229,19 @@ def build_parser() -> argparse.ArgumentParser:
229
229
  "与 null 键,每条 result 留 title/url/snippet/source/score 等;"
230
230
  "fetch_required 保留)。默认 None=自动:stdout 非 tty 时"
231
231
  "启用 agent 档(Agent 消费),否则 full",)
232
+ parser.add_argument(
233
+ "--agent", action="store_true",
234
+ help="Agent 消费单开关:等价于 --json --fields agent;与 --envelope / "
235
+ "--fields full 互斥(入口直接报错,避免静默剥离 envelope)",
236
+ )
237
+ parser.add_argument(
238
+ "--intent",
239
+ choices=("news", "academic", "social", "image-reverse", "calc"),
240
+ default=None,
241
+ help="高层意图路由(免记 explicit_only 引擎名):news=时事(有 key/预算自动用 "
242
+ "deepseek_search,否则降级)、academic=学术多源、social=社交、image-reverse=反搜图、"
243
+ "calc=精确计算(wolframalpha)",
244
+ )
232
245
  parser.add_argument(
233
246
  "--archive",
234
247
  action="store_true",
@@ -400,6 +413,24 @@ def main():
400
413
  parser = build_parser()
401
414
  args = parser.parse_args()
402
415
 
416
+ # --agent 单开关展开与契约互斥校验(Fail-Fast):
417
+ # 此前 --envelope 与 --fields agent 同给只在 stderr 告警,随后静默剥成 0 字节。
418
+ # 入口直接报错可省去整轮无效搜索与重试。
419
+ if args.agent:
420
+ if args.fields == "full":
421
+ parser.error(
422
+ "--agent 与 --fields full 互斥:--agent 等价于 --json --fields agent;"
423
+ "需要全量字段请用 --json --fields full"
424
+ )
425
+ args.json_output = True
426
+ args.fields = "agent"
427
+
428
+ if args.envelope and args.fields == "agent":
429
+ parser.error(
430
+ "--envelope 与 --agent / --fields agent 互斥(agent 档会剥离 envelope 视图);"
431
+ "要 provenance 追溯请用 --json --envelope,只要瘦身答案请用 --agent"
432
+ )
433
+
403
434
  if args.json_output:
404
435
  # issue #34 第 7 条:引擎 builder 的 logger.warning(如「OCTEN_API_KEY
405
436
  # 未设置」)经 logging 的最后兜底 handler 打到 stderr,调用方一旦
@@ -564,6 +595,9 @@ def main():
564
595
  # 同一进程、同一路径上付的那一笔,否则只是把支出提前,不是省下。
565
596
  # 回归守卫见 tests/test_plan_a_optimizations.py::TestNoUnconditionalPrewarm。
566
597
  # --academic-deep:学术多源模式,自动设置 depth=deep + domain=academic
598
+ # _user_domain 记录「用户显式传了 --domain/--sub_domain」——内部模式
599
+ # (--academic-deep / --intent)设置的 engine_domain 不需要作用域告警。
600
+ _user_domain = bool(args.domain or args.sub_domain)
567
601
  if args.academic_deep:
568
602
  depth = "deep"
569
603
  engine_domain = "academic"
@@ -571,9 +605,27 @@ def main():
571
605
  depth = args.depth
572
606
  engine_domain = args.domain or None
573
607
 
608
+ # --intent 高层意图路由(仅显式传入时懒加载,默认路径零开销)
609
+ resolved_engine = args.engine
610
+ intent_boost: list[str] | None = None
611
+ intent_res: dict[str, Any] | None = None
612
+ if args.intent:
613
+ from intent_router import resolve_intent
614
+ intent_res = resolve_intent(
615
+ args.intent,
616
+ engine=resolved_engine,
617
+ domain=engine_domain,
618
+ depth=depth,
619
+ mode=args.mode,
620
+ )
621
+ resolved_engine = intent_res["engine"]
622
+ engine_domain = intent_res["domain"]
623
+ depth = intent_res["depth"]
624
+ intent_boost = intent_res.get("engines_boost")
625
+
574
626
  results = super_search(
575
627
  query=args.query,
576
- engine=args.engine,
628
+ engine=resolved_engine,
577
629
  n=args.max_results,
578
630
  explain=args.explain,
579
631
  skip_cache=args.no_cache,
@@ -585,6 +637,7 @@ def main():
585
637
  plan_only=args.plan_only,
586
638
  force_search=args.force_search,
587
639
  envelope=use_envelope,
640
+ engines_boost=intent_boost,
588
641
  since=args.since,
589
642
  until=args.until,
590
643
  sort=args.sort,
@@ -777,6 +830,56 @@ def main():
777
830
  _vw_ms = (time.perf_counter() - _t_verifywith0) * 1000.0
778
831
  _merge_verify_timing(results["timing"], _vw_ms, stage="verify_with")
779
832
 
833
+ # 若启用了 --intent,将精简解析记录与降级告警附加到结果中
834
+ if intent_res is not None:
835
+ ir_out: dict[str, Any] = {
836
+ "intent": intent_res["intent"],
837
+ "engine": intent_res["engine"],
838
+ "domain": intent_res["domain"],
839
+ "depth": intent_res["depth"],
840
+ "degraded": intent_res["degraded"],
841
+ "reason": intent_res["reason"],
842
+ }
843
+ if intent_res.get("engines_boost"):
844
+ ir_out["engines_boost"] = intent_res["engines_boost"]
845
+ # domain 字段的作用域标注(2026-11-24):intent 会设 domain,而该字段
846
+ # 不参与选源(route_query 从不读 engine_domain),只在引擎级缓存键上生效。
847
+ # 标出来,避免调用方把 `intent_resolution.domain` 读成「结果已被限定在该域」。
848
+ if intent_res.get("domain"):
849
+ ir_out["domain_scope"] = "cache_key_only"
850
+ results["intent_resolution"] = ir_out
851
+ if intent_res.get("warnings"):
852
+ existing_w = results.setdefault("warnings", [])
853
+ for w in intent_res["warnings"]:
854
+ if w not in existing_w:
855
+ existing_w.append(w)
856
+
857
+ # --domain / --sub_domain 的作用域提示(2026-11-24)。
858
+ #
859
+ # 实测:这两个参数**不参与选源**——路由决策(route_query)从不读它们,
860
+ # 全仓也只有 anysearch 的 builder 把 `domain` 下推进上游请求体
861
+ # (engines_builders_tech._build_anysearch_engine),其余 312 个源的
862
+ # builder 签名里没有这个入参。它们真正的作用是 ① 隔离引擎级缓存键
863
+ # (search_entry)、② 给 anysearch 传垂直域。
864
+ #
865
+ # 于是 `--domain finance` 配任何非 anysearch 的自动路由都是静默无效的:
866
+ # 退出码 0、无告警、结果与不传给定位「金融域」完全相同。这与 SKILL.md
867
+ # 写的「垂直域限定」承诺不符。这里不改行为(选了什么源仍由路由决定),
868
+ # 只让「该参数本次未影响选源」可见——与 issue #34 的 warnings[] 纪律同构。
869
+ if _user_domain:
870
+ # 判据用**实际调用过**的引擎(engines_used),不是路由 combo——
871
+ # combo 尾部常挂着一串 backup,anysearch 在里面并不代表它真被调用。
872
+ _used = results.get("engines_used") or []
873
+ if "anysearch" not in _used:
874
+ _w = (
875
+ f"--domain/--sub_domain 不参与选源:本次实际调用的引擎 {_used[:3]} "
876
+ "均不消费该参数,它只隔离了引擎级缓存键;要对单引擎下推垂直域请"
877
+ "显式 --engine anysearch"
878
+ )
879
+ results.setdefault("warnings", [])
880
+ if _w not in results["warnings"]:
881
+ results["warnings"].append(_w)
882
+
780
883
  # 敏感信息自动脱敏拦截(防止真实 API Key / 通用敏感凭据在输出流泄露)
781
884
  try:
782
885
  from secret_guard import redact_data
@@ -796,13 +899,6 @@ def main():
796
899
  and not args.envelope
797
900
  )
798
901
  if args.fields == "agent" or _auto_agent:
799
- if args.envelope:
800
- print(
801
- " [warning] --envelope 与 --fields agent 同时给时 envelope 会被"
802
- "剥光(实测增量 0 字节):要 provenance 请去掉 --fields agent;"
803
- "只要瘦身就别加 --envelope。",
804
- file=sys.stderr,
805
- )
806
902
  public = _strip_for_agent(public)
807
903
  print(dumps(public))
808
904
  else:
@@ -73,7 +73,8 @@ _AGENT_RESULT_FIELDS = (
73
73
  # 中间档,借鉴 DeepSeek Search 的 summary 语义。只在确有核验证据时
74
74
  # 出现(backfill_results 回填),未核验结果不造假摘要。
75
75
  "summary",
76
- "image_url", "image_license",
76
+ "image_url", "image_url_preview", "image_license",
77
+ "author", "tags", "similarity",
77
78
  # 双通道引擎(同一引擎名背后有匿名与认证两条取数通路)标出本条实际走的
78
79
  # 通道:内容范围差异正是两条通路的区别,剥掉它就只能靠猜。
79
80
  "channel",
@@ -240,6 +241,8 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
240
241
  # 数值印证与核对配对(2026-11-01):同上「花了墙钟换来的」逻辑——
241
242
  # 摘要数字与原文冲突、独立官方核对簇,都是 Agent 引用前的直接依据。
242
243
  "numverify", "numeric_reorder", "verify_with",
244
+ # 高层意图路由解析(--intent 显式传入时存在,默认路径不出现、零增量)
245
+ "intent_resolution",
243
246
  )
244
247
  out: dict[str, Any] = {k: payload[k] for k in keep_top
245
248
  if payload.get(k) is not None}
@@ -32,12 +32,13 @@ def social_sentiment_research(query: str, platforms: list[str] | None = None,
32
32
  engines_used: set[str] = set()
33
33
  t0 = time.time()
34
34
 
35
- def _one(platform: str) -> tuple[str, list[dict], set[str]]:
36
- try:
35
+ def _one(platform: str):
36
+ if platform in ("twitter", "x"):
37
+ from x_keyword_route import search_x_keywords
38
+ result = search_x_keywords(query, max_results)
39
+ else:
37
40
  result = super_search(query, engine=platform, n=max_results, mode="fast")
38
- return platform, result.get("results", []), set(result.get("engines_used", []))
39
- except Exception:
40
- return platform, [], set()
41
+ return platform, result.get("results", []), result.get("engines_used", []), result.get("errors", [])
41
42
 
42
43
  # 并行抓取各平台(串行时 3 平台 × 秒级延迟累积;并行取最慢平台耗时)。
43
44
  # 总时限 90s:到点就拿已完成部分返回,没完成的平台记空结果,不再被卡住的
@@ -50,7 +51,8 @@ def social_sentiment_research(query: str, platforms: list[str] | None = None,
50
51
  platform_results[platform] = []
51
52
  social_errors.append(f"{platform}: {type(value.exc).__name__}")
52
53
  continue
53
- _platform, results, used = value
54
+ _platform, results, used, errors = value
55
+ social_errors.extend(errors)
54
56
  platform_results[_platform] = results
55
57
  all_results.extend(results)
56
58
  engines_used.update(used)
@@ -284,3 +284,31 @@ def weather_chronological(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
284
284
  return published, current_first
285
285
 
286
286
  return sorted(rows, key=_key)
287
+
288
+
289
+ def normalize_epoch(value: Any, *, precise: bool = False) -> str:
290
+ """epoch 秒/毫秒 → `YYYY-MM-DD`,非 epoch 原样返回。
291
+
292
+ 技能目录源的 updatedAt 单位不统一:SkillsMP 给秒(1786285295),ClawHub
293
+ 给毫秒(1789594554485),相差 1000 倍。原样映射等于把一串数字当
294
+ published_at 交出去,既读不出日期也无法与别的源比较。
295
+
296
+ 按量级判别而非按源声明:1e9~1e11 是秒(2001~5138 年),1e11~1e14 是
297
+ 毫秒,两位差三个数量级,不存在擦边区间。范围外的值不猜,原样返回——
298
+ 猜错会把一个可疑值变成看起来正常的值,比留着更糟。
299
+ """
300
+ text = str(value).strip()
301
+ if not text.isdigit():
302
+ return text
303
+ num = int(text)
304
+ if 1_000_000_000 <= num < 100_000_000_000:
305
+ seconds = num
306
+ elif 100_000_000_000 <= num < 100_000_000_000_000:
307
+ seconds = num / 1000
308
+ else:
309
+ return text
310
+ try:
311
+ instant = datetime.fromtimestamp(seconds, tz=timezone.utc)
312
+ return instant.isoformat() if precise else instant.strftime("%Y-%m-%d")
313
+ except (OverflowError, OSError, ValueError):
314
+ return text
@@ -0,0 +1,107 @@
1
+ """按 ID 读取公开推文。每个通道一次 GET,按请求内的响应决定是否补读。"""
2
+ from __future__ import annotations
3
+
4
+ import http.client
5
+ import json
6
+ import re
7
+ import time
8
+ import urllib.error
9
+
10
+ import engine_states as st
11
+ from engines_base import note_failure
12
+ from fxtwitter_api import FxTwitterError, http_get
13
+
14
+ ENGINE = "twitter_syndication"
15
+ FX_SOURCE = f"{ENGINE}/fxtwitter"
16
+ _RESTRICTED = re.compile(r"private|protected|forbidden|unauthori[sz]ed|not found|does not exist|deleted|log[ -]?in|sign[ -]?in|not authorized|authentication required|tweet (?:is )?unavailable", re.I)
17
+
18
+
19
+ class ReadFailure(Exception):
20
+ def __init__(self, reason, *, temporary=False, category=st.FAILURE_UPSTREAM, status=None):
21
+ super().__init__(reason)
22
+ self.temporary = temporary
23
+ self.category = category
24
+ self.status = status
25
+
26
+
27
+ def _request(url, headers, timeout):
28
+ try:
29
+ raw, code = http_get(url, headers=headers, timeout=timeout, max_retries=0)
30
+ except FxTwitterError as exc:
31
+ code = exc.code
32
+ if code is None:
33
+ network = isinstance(exc.__cause__, (OSError, urllib.error.URLError))
34
+ raise ReadFailure("network failure" if network else "request refused", temporary=network,
35
+ category=st.FAILURE_NETWORK if network else st.FAILURE_BLOCKED) from exc
36
+ if _RESTRICTED.search(str(exc)):
37
+ raise ReadFailure(f"restricted response (HTTP {code})", category=st.FAILURE_BLOCKED, status=code) from exc
38
+ raw = b""
39
+ except http.client.HTTPException as exc:
40
+ raise ReadFailure("incomplete response", temporary=True, category=st.FAILURE_NETWORK) from exc
41
+ if code != 200:
42
+ category = {401: st.FAILURE_AUTH, 403: st.FAILURE_BLOCKED, 429: st.FAILURE_RATE_LIMITED}
43
+ raise ReadFailure(f"HTTP {code}", temporary=code in (408, 429) or 500 <= code < 600,
44
+ category=category.get(code, st.FAILURE_UPSTREAM), status=code)
45
+ try:
46
+ data = json.loads(raw)
47
+ except (ValueError, UnicodeDecodeError):
48
+ denied = _RESTRICTED.search(raw[:4096].decode("utf-8", errors="replace"))
49
+ raise ReadFailure("restricted response" if denied else "invalid JSON", temporary=not denied) from None
50
+ if data == {} or data is None:
51
+ raise ReadFailure("empty response", temporary=True)
52
+ if not isinstance(data, dict):
53
+ raise ReadFailure("unexpected response shape")
54
+ return data
55
+
56
+
57
+ def _result(data, tweet_id, source):
58
+ fx = source == FX_SOURCE
59
+ if fx:
60
+ if data.get("code") not in (None, 200, "200") or data.get("error") or data.get("errors"):
61
+ raise ReadFailure("FxTwitter rejected lookup")
62
+ data = data.get("tweet")
63
+ if not isinstance(data, dict) or data.get("__typename", "Tweet") != "Tweet" or data.get("errors") or data.get("error"):
64
+ raise ReadFailure("tweet unavailable")
65
+ author = data.get("author" if fx else "user") or {}
66
+ if not isinstance(author, dict) or author.get("protected") or data.get("protected"):
67
+ raise ReadFailure("author unavailable")
68
+ if str(data.get("id" if fx else "id_str")) != tweet_id:
69
+ raise ReadFailure("unverified tweet ID")
70
+ text = data.get("text")
71
+ if not isinstance(text, str) or not text.strip():
72
+ raise ReadFailure("missing tweet text")
73
+ handle = author.get("screen_name") or ""
74
+ if not isinstance(handle, str) or not re.fullmatch(r"[a-zA-Z0-9_]{1,15}", handle):
75
+ handle = ""
76
+ container = data.get("media" if fx else "entities")
77
+ media = container.get("all" if fx else "media") if isinstance(container, dict) else None
78
+ if not fx:
79
+ media = data.get("mediaDetails") or media
80
+ snippet = ["FxTwitter" if fx else "", data.get("created_at"), author.get("name"), text[:280]]
81
+ if isinstance(media, list) and media:
82
+ snippet.append(f"(含 {len(media)} 项媒体)")
83
+ return [{"title": (f"@{handle}: {text[:80]}" if handle else text[:80])[:100],
84
+ "url": f"https://x.com/{handle or 'i/web'}/status/{tweet_id}",
85
+ "snippet": " | ".join(s for s in snippet if isinstance(s, str) and s),
86
+ "source": source, "score": 0.9}]
87
+
88
+
89
+ def read_tweet(tweet_id, token, timeout):
90
+ deadline = time.monotonic() + timeout
91
+ primary = f"https://cdn.syndication.twimg.com/tweet-result?id={tweet_id}&token={token}"
92
+ endpoints = [(ENGINE, primary, {"Referer": "https://platform.twitter.com/"}),
93
+ (FX_SOURCE, f"https://api.fxtwitter.com/status/{tweet_id}", {})]
94
+ reasons = []
95
+ for source, url, headers in endpoints:
96
+ try:
97
+ remaining = deadline - time.monotonic()
98
+ if remaining <= 0:
99
+ raise ReadFailure("timeout", category=st.FAILURE_NETWORK)
100
+ budget = remaining * 0.6 if source == ENGINE else remaining
101
+ return _result(_request(url, headers, budget), tweet_id, source)
102
+ except ReadFailure as exc:
103
+ reasons.append(f"{source}: {exc}")
104
+ if source == ENGINE and exc.temporary:
105
+ continue
106
+ note_failure(ENGINE, exc.category, "tweet-read-failed", "; ".join(reasons), status=exc.status)
107
+ return []
@@ -0,0 +1,138 @@
1
+ """X keyword channels share a bounded deadline and per-attempt search outcomes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ import time
8
+
9
+ import engine_states as st
10
+
11
+ X_ENGINES = frozenset({"twitter", "twitter_cli", "fxtwitter"})
12
+
13
+
14
+ def is_x_request(engine, query, decision):
15
+ if engine != "auto":
16
+ return engine in X_ENGINES
17
+ from route_domains import platform_native_engine
18
+
19
+ return (
20
+ decision.get("domain") == "social"
21
+ and platform_native_engine(query) == "fxtwitter"
22
+ or bool(re.search(r"(?:^|\s)from:@?[A-Za-z0-9_]{1,15}(?:\s|$)", query, re.I))
23
+ )
24
+
25
+
26
+ def _call(engine, query, n, timeout, since, until):
27
+ from engines import get_registry
28
+
29
+ handler = get_registry().get(engine)
30
+ if handler is None:
31
+ raise FileNotFoundError(f"{engine} not enabled or available")
32
+ if engine == "twitter":
33
+ from x_search import search_browser
34
+
35
+ return search_browser(query, n, timeout)
36
+ return handler(query, n, timeout=timeout, since=since, until=until)
37
+
38
+
39
+ def search_x_keywords(query, n=5, *, engine="auto", since=None, until=None, timeout=20):
40
+ from engine_dispatch import classify_engine_outcome
41
+ from engines_twitter_cli import parse_x_constraints, matches_x_constraints
42
+ from time_utils import parse_time_value
43
+
44
+ start = time.monotonic()
45
+
46
+ def bound(value):
47
+ if value and re.fullmatch(r"\d+\s*[dhw]|\d+", str(value), re.I):
48
+ return parse_time_value(value)[0] or value
49
+ return value
50
+
51
+ since, until = bound(since), bound(until)
52
+ attempts, errors, hits = [], [], []
53
+ try:
54
+ constraints = parse_x_constraints(query, since, until)
55
+ except ValueError as exc:
56
+ errors.append(f"X: invalid query window: {exc}")
57
+ order = []
58
+ else:
59
+ order = (
60
+ (
61
+ ["twitter_cli", "fxtwitter", "twitter"]
62
+ if constraints.strict
63
+ else ["fxtwitter", "twitter_cli", "twitter"]
64
+ )
65
+ if engine == "auto"
66
+ else [engine]
67
+ )
68
+ for name in order:
69
+ before = time.monotonic()
70
+ remaining = timeout - (before - start)
71
+ if remaining <= 0:
72
+ errors.append("X: search deadline exceeded")
73
+ break
74
+ try:
75
+ channel_timeout = (
76
+ min(10, remaining)
77
+ if name == "fxtwitter" and engine == "auto"
78
+ else remaining
79
+ )
80
+ rows = _call(name, query, n, channel_timeout, since, until)
81
+ except FileNotFoundError as exc:
82
+ rows = [{"error": str(exc), "error_kind": st.PLUGIN_UNAVAILABLE}]
83
+ except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
84
+ rows = (
85
+ [{"error": f"{name}: {type(exc).__name__}"}]
86
+ if isinstance(exc, subprocess.TimeoutExpired)
87
+ else [{"error": str(exc)}]
88
+ )
89
+ checked = []
90
+ for row in rows:
91
+ if "error" in row:
92
+ checked.append(row)
93
+ continue
94
+ if not row.get("url"):
95
+ checked.append({"error": "response row has no post URL"})
96
+ continue
97
+ author = row.get("author") or (row.get("social_meta") or {}).get("author")
98
+ if name == "fxtwitter" and row.get("source") != "fxtwitter":
99
+ author = row.get("source")
100
+ published = row.get("published_at")
101
+ if (constraints.author and not author) or (
102
+ (constraints.since or constraints.until) and not published
103
+ ):
104
+ checked.append(
105
+ {
106
+ "error": "post lacks metadata needed to verify X search constraints"
107
+ }
108
+ )
109
+ elif matches_x_constraints(constraints, author, published):
110
+ checked.append(row)
111
+ outcome = classify_engine_outcome(
112
+ name, checked, round((time.monotonic() - before) * 1000)
113
+ )
114
+ for row in checked:
115
+ if "error" in row:
116
+ kind = row.get("error_kind")
117
+ if kind:
118
+ outcome["error_kind"] = kind
119
+ errors.append(
120
+ f"{name}: {kind + ': ' if kind else ''}{str(row['error'])[:200]}"
121
+ )
122
+ else:
123
+ hits.append(row)
124
+ attempts.append(outcome)
125
+ if hits or not rows or (checked == [] and engine != "auto"):
126
+ break
127
+ used = [o["engine"] for o in attempts]
128
+ return {
129
+ "query": query,
130
+ "domain": "social",
131
+ "engine": used[-1] if used else engine,
132
+ "engines_used": used,
133
+ "results": hits[:n],
134
+ "count": len(hits[:n]),
135
+ "errors": errors,
136
+ "engine_outcomes": attempts,
137
+ "elapsed_ms": round((time.monotonic() - start) * 1000),
138
+ }