argo-search 2.16.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 (126) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.es.md +15 -5
  3. package/README.ja.md +15 -5
  4. package/README.ko.md +15 -5
  5. package/README.md +16 -6
  6. package/README.zh.md +16 -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/assets/readme/hero.template.svg +121 -0
  11. package/assets/readme/proof-routes.svg +17 -16
  12. package/backends/domain_profiles.json +121 -18
  13. package/backends/engine_registry.yaml +23 -0
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +20 -0
  16. package/bin/argo +78 -12
  17. package/docs/CHANGELOG.md +35 -1
  18. package/docs/COMMIT_STANDARD.md +12 -2
  19. package/docs/ENGINE_CATALOG.md +36 -33
  20. package/docs/RELEASE_NOTES_v2.17.0.md +66 -0
  21. package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
  22. package/docs/RELEASING.md +2 -2
  23. package/engines/specs/crossref.yaml +2 -0
  24. package/engines/specs/hackernews.yaml +2 -0
  25. package/engines/specs/helve.yaml +49 -0
  26. package/engines/specs/hf_papers.yaml +2 -0
  27. package/engines/specs/openalex.yaml +9 -2
  28. package/engines/specs/twitter_cli.yaml +17 -0
  29. package/engines/specs/twitter_syndication.yaml +2 -3
  30. package/package.json +3 -1
  31. package/packages/dsh-plugin/README.md +5 -2
  32. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  33. package/packages/dsh-plugin/dsh/client.js +57 -63
  34. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  35. package/packages/dsh-plugin/dsh/index.js +109 -21
  36. package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
  37. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  38. package/packages/dsh-plugin/dsh/runner.js +49 -6
  39. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  40. package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
  41. package/packages/dsh-plugin/dsh/workbench-io.js +182 -0
  42. package/packages/dsh-plugin/dsh/workbench-search.js +445 -0
  43. package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
  44. package/packages/dsh-plugin/dsh/workbench.js +277 -497
  45. package/packages/dsh-plugin/package.json +4 -3
  46. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  47. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  48. package/packages/dsh-plugin/test/client.test.js +26 -0
  49. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  50. package/packages/dsh-plugin/test/index.test.js +150 -1
  51. package/packages/dsh-plugin/test/workbench-concurrency.test.js +96 -0
  52. package/packages/dsh-plugin/test/workbench.test.js +422 -9
  53. package/scripts/adaptive.py +13 -11
  54. package/scripts/affected_tests.py +324 -0
  55. package/scripts/badcase_ledger.py +93 -2
  56. package/scripts/browser_auth.py +178 -4
  57. package/scripts/cache.py +68 -69
  58. package/scripts/check_commit_report.py +59 -9
  59. package/scripts/chrome_cdp.py +71 -0
  60. package/scripts/circuit_breaker.py +77 -12
  61. package/scripts/cli_io.py +8 -3
  62. package/scripts/config_cache.py +4 -3
  63. package/scripts/daemon.py +9 -2
  64. package/scripts/engine_add.py +45 -0
  65. package/scripts/engine_dispatch.py +27 -47
  66. package/scripts/engine_failure.py +33 -0
  67. package/scripts/engine_families.py +1 -0
  68. package/scripts/engine_fingerprint.py +114 -0
  69. package/scripts/engine_health.py +130 -0
  70. package/scripts/engine_states.py +54 -4
  71. package/scripts/engines.py +2 -0
  72. package/scripts/engines_base.py +19 -44
  73. package/scripts/engines_builders_intl.py +20 -94
  74. package/scripts/engines_builders_search.py +19 -8
  75. package/scripts/engines_builders_tech.py +16 -16
  76. package/scripts/engines_fields.py +23 -0
  77. package/scripts/engines_twitter_cli.py +182 -0
  78. package/scripts/evidence_grounding.py +182 -0
  79. package/scripts/fetch_browser.py +25 -10
  80. package/scripts/fetch_cli_output.py +75 -0
  81. package/scripts/fetch_dispatch.py +248 -0
  82. package/scripts/fetch_quality.py +11 -0
  83. package/scripts/fetch_v3.py +48 -114
  84. package/scripts/gate_manifest_check.py +75 -0
  85. package/scripts/gen_readme_art.py +264 -0
  86. package/scripts/intent_router.py +224 -0
  87. package/scripts/mcp_compact.py +3 -0
  88. package/scripts/mcp_handlers.py +24 -4
  89. package/scripts/mcp_tools.py +2 -0
  90. package/scripts/mcp_transport.py +24 -5
  91. package/scripts/mcp_warm.py +15 -11
  92. package/scripts/numeric_verify.py +9 -0
  93. package/scripts/output_transparency.py +10 -0
  94. package/scripts/pre-commit +65 -8
  95. package/scripts/query_operators.py +229 -1
  96. package/scripts/quota.py +19 -37
  97. package/scripts/release.py +16 -1
  98. package/scripts/release_check.py +1 -2
  99. package/scripts/research_gates.py +85 -1
  100. package/scripts/research_notes.py +52 -5
  101. package/scripts/retry_policy.py +17 -3
  102. package/scripts/route_combo.py +21 -4
  103. package/scripts/search.py +29 -29
  104. package/scripts/search_cli.py +104 -8
  105. package/scripts/search_output.py +4 -1
  106. package/scripts/social_research.py +8 -6
  107. package/scripts/source_discovery.py +611 -0
  108. package/scripts/sync_backends.py +45 -0
  109. package/scripts/time_utils.py +28 -0
  110. package/scripts/twitter_single_read.py +107 -0
  111. package/scripts/x_keyword_route.py +138 -0
  112. package/scripts/x_search.py +24 -33
  113. package/scripts/zhihu_answer_body.py +96 -0
  114. package/scripts/zhihu_answer_fetch.py +66 -0
  115. package/scripts/zhihu_answer_lookup.py +138 -0
  116. package/sub-skills/ego-search/README.md +9 -0
  117. package/sub-skills/ego-search/scripts/ego_search.py +182 -15
  118. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  119. package/sub-skills/ego-search/scripts/quality.py +262 -6
  120. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  121. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  122. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
  123. package/sub-skills/local-seek/SKILL.md +3 -1
  124. package/sub-skills/local-seek/scripts/seek.py +80 -109
  125. package/sub-skills/local-seek/scripts/seek_git.py +65 -0
  126. package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
@@ -16,7 +16,7 @@ import threading
16
16
  import engine_states as _st # 失败归因词表唯一真源
17
17
  # UA 与礼貌池邮箱单源(engines_http 顶层无反向依赖,不成环)
18
18
  from engines_http import UA, contact_email as _contact_email, normalize_ua_headers
19
- from engines_fields import _coerce_field # 字段取值原语真源在 engines_fields(无依赖底层),本模块复导出
19
+ from engines_fields import _coerce_body_value, _coerce_field # 取值/收敛原语真源在 engines_fields(无依赖底层),本模块复导出
20
20
 
21
21
  import serp_kill_log # noqa: E402 守卫接线+误杀账本(2026-10-10 拆出,stdlib 级轻量)
22
22
  import time
@@ -25,6 +25,7 @@ from contextlib import contextmanager
25
25
  from datetime import datetime, timezone
26
26
  from pathlib import Path
27
27
  from typing import Any, Callable
28
+ from time_utils import normalize_epoch as _normalize_epoch
28
29
 
29
30
  try:
30
31
  from config import load_config, get_engines
@@ -61,10 +62,9 @@ def _get_logger():
61
62
  # 拿到引擎名、状态码、响应体的位置。HTML 引擎的反爬命中走「静默返回空」路径,
62
63
  # 没有任何错误文本可供聚合层事后反推;不在这里寄存,封锁就永远伪装成空结果,
63
64
  # 被封的引擎会被当成故障累计到熔断里(封错人)。
64
- _FAIL_NOTES: dict[str, dict[str, Any]] = {}
65
+ from engine_failure import ThreadLocalNotes as _ThreadLocalNotes
66
+ _FAIL_NOTES = _ThreadLocalNotes()
65
67
  _FAIL_NOTES_LOCK = threading.Lock()
66
-
67
- # HTTPError 错误体读取上限:只用于归因(下游截 400 字符),防大错误页吃进内存/落盘
68
68
  _HTTP_ERROR_BODY_CAP = 64 * 1024
69
69
 
70
70
  # 归因细节里可能回显凭证(OpenAI 风格 "Incorrect API key: sk-…"),
@@ -437,6 +437,8 @@ def _build_http_engine(spec: dict[str, Any]) -> Any:
437
437
  # 失败返回空(与 urllib 失败行为一致,不抛异常)
438
438
  raw = _http_get_raw(full_url, resolved_headers, to, engine=eng)
439
439
  if raw is None:
440
+ if eng == "fxtwitter":
441
+ return [{"source": eng, "error": "FxTwitter HTTP request failed"}]
440
442
  return []
441
443
  return _parse_http_payload(raw, fmt, eng, n, output_map, spec)
442
444
  else:
@@ -445,19 +447,11 @@ def _build_http_engine(spec: dict[str, Any]) -> Any:
445
447
  resolved = _resolve(str(v), query, n, allowed_env=_allowed, **kwargs)
446
448
  if k == "search_depth":
447
449
  body[k] = {"fast": "fast", "balanced": "basic", "deep": "advanced", "basic": "basic", "advanced": "advanced", "ultra-fast": "ultra-fast"}.get(str(depth), resolved or "basic")
448
- elif resolved.lower() == "true":
449
- body[k] = True
450
- elif resolved.lower() == "false":
451
- body[k] = False
452
450
  else:
453
- try:
454
- body[k] = int(resolved)
455
- except ValueError:
456
- try:
457
- body[k] = float(resolved)
458
- except ValueError:
459
- body[k] = resolved
460
- # 与 GET 路径保持一致:过滤空/认证前缀残留头;POST 默认走 HttpClient 连接池
451
+ body[k] = _coerce_body_value(resolved)
452
+ if eng == "tavily":
453
+ from query_operators import compile_provider_params
454
+ body.update(compile_provider_params("tavily", query, operators=kwargs.get("operators"), since=kwargs.get("since"), until=kwargs.get("until"), depth=depth))
461
455
  resolved_url = _resolve(url_template, query, n, allowed_env=_allowed, **kwargs)
462
456
  resolved_headers = {k: v for k, v in ((k, _resolve(v, query, n, allowed_env=_allowed, **kwargs))
463
457
  for k, v in headers.items()) if _header_meaningful(v)}
@@ -689,33 +683,6 @@ def _envelope_error(data: Any) -> str:
689
683
  return ""
690
684
 
691
685
 
692
- def _normalize_epoch(value: Any) -> str:
693
- """epoch 秒/毫秒 → `YYYY-MM-DD`,非 epoch 原样返回。
694
-
695
- 技能目录源的 updatedAt 单位不统一:SkillsMP 给秒(1786285295),ClawHub
696
- 给毫秒(1789594554485),相差 1000 倍。原样映射等于把一串数字当
697
- published_at 交出去,既读不出日期也无法与别的源比较。
698
-
699
- 按量级判别而非按源声明:1e9~1e11 是秒(2001~5138 年),1e11~1e14 是
700
- 毫秒,两位差三个数量级,不存在擦边区间。范围外的值不猜,原样返回——
701
- 猜错会把一个可疑值变成看起来正常的值,比留着更糟。
702
- """
703
- text = str(value).strip()
704
- if not text.isdigit():
705
- return text
706
- num = int(text)
707
- if 1_000_000_000 <= num < 100_000_000_000:
708
- seconds = num
709
- elif 100_000_000_000 <= num < 100_000_000_000_000:
710
- seconds = num / 1000
711
- else:
712
- return text
713
- try:
714
- return datetime.fromtimestamp(seconds, tz=timezone.utc).strftime("%Y-%m-%d")
715
- except (OverflowError, OSError, ValueError):
716
- return text
717
-
718
-
719
686
  def _apply_url_kind(rows: list[dict[str, Any]], spec: dict) -> list[dict[str, Any]]:
720
687
  """声明式 spec 的 url_kind 落到行上(issue #29 口径 B):none = 本档条目不以
721
688
  url 为身份,缺 url 的条目不按壳页整批吞。spec 未声明时行上不出现该字段。"""
@@ -744,7 +711,15 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
744
711
  data = json.loads(raw)
745
712
  except (json.JSONDecodeError, ValueError):
746
713
  _get_logger().warning(f"HTTP 引擎解析失败: {eng} 非 JSON/XML 响应")
714
+ if eng == "fxtwitter":
715
+ return [{"source": eng, "error": "FxTwitter returned invalid JSON"}]
747
716
  return []
717
+ if eng == "fxtwitter" and (not isinstance(data, dict) or data.get("code", 200) != 200
718
+ or not isinstance(data.get("results"), list)):
719
+ return [{"source": eng, "error": "FxTwitter returned an unsuccessful or invalid search envelope"}]
720
+ if eng == "fxtwitter" and any(not isinstance(item, dict) or not item.get("url") or "error" in item
721
+ for item in data["results"]):
722
+ return [{"source": eng, "error": "FxTwitter returned an invalid post row"}]
748
723
  # 业务错误封套优先于条数提取:强封套错误(ResponseMetadata.Error、顶层
749
724
  # error 对象)表示本次调用失败,返回结果必然为空或不可信
750
725
  env_err = _envelope_error(data)
@@ -807,7 +782,7 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
807
782
  for r in parsed:
808
783
  r.setdefault("source", eng)
809
784
  if r.get("published_at"):
810
- r["published_at"] = _normalize_epoch(r["published_at"])
785
+ r["published_at"] = _normalize_epoch(r["published_at"], precise=eng == "fxtwitter")
811
786
  if _lic and r.get("image_url"):
812
787
  r.setdefault("image_license", _lic)
813
788
  for _fk, _cap in (("title", 500), ("snippet", 300)):
@@ -554,120 +554,46 @@ def _build_qq_music_engine(spec: dict[str, Any]) -> Any:
554
554
 
555
555
  # ── X/Twitter 单条推文(syndication 免登录通道)─────────────────────────────
556
556
 
557
- # 推文 URL / 裸 ID 提取:覆盖两代域名、/statuses/ 老路径与 query 参数形态;
558
- # URL/query 允许 1~25 位早期短 ID,裸数字仍按 10~20 位防普通数字误判。
559
- _TWEET_URL_RE = re.compile(
560
- r"(?:x\.com|twitter\.com)/[^/\s]+/(?:status|statuses)/(\d{1,25})", re.I)
561
- _TWEET_BARE_ID_RE = re.compile(r"^\d{10,20}$")
562
- _TWEET_QUERY_ID_RE = re.compile(r"[?&](?:tweet_id|status_id|id)=(\d{1,25})")
557
+ _TWEET_PATH = re.compile(r"/(?:[\w]+|i/web)/status(?:es)?/([0-9]{1,25})(?:/.*)?$")
563
558
 
564
559
 
565
560
  def extract_tweet_id(text: str) -> str | None:
566
- """从查询词提取推文 ID:完整 URL、分享链接参数、裸 ID 均可。"""
567
- if not text:
561
+ """接受 X/Twitter 的状态链接、分享参数或 10–20 位裸 ID。"""
562
+ text = (text or "").strip()
563
+ if re.fullmatch(r"[0-9]{10,20}", text):
564
+ return text
565
+ try:
566
+ url = urllib.parse.urlsplit(text if "://" in text else "https://" + text)
567
+ if url.scheme not in ("http", "https") or url.hostname not in {
568
+ "x.com", "www.x.com", "twitter.com", "www.twitter.com", "mobile.twitter.com"}:
569
+ return None
570
+ except ValueError:
568
571
  return None
569
- m = _TWEET_URL_RE.search(text)
572
+ m = _TWEET_PATH.fullmatch(url.path)
570
573
  if m:
571
574
  return m.group(1)
572
- m = _TWEET_QUERY_ID_RE.search(text)
573
- if m:
574
- return m.group(1)
575
- text = text.strip()
576
- if _TWEET_BARE_ID_RE.match(text):
577
- return text
575
+ for key, value in urllib.parse.parse_qsl(url.query):
576
+ if key in ("tweet_id", "status_id", "id") and re.fullmatch(r"[0-9]{1,25}", value):
577
+ return value
578
578
  return None
579
579
 
580
580
 
581
- # syndication 端点要求 token 参数存在,但值不参与校验。
582
- # 实测 2026-09-12(推文 1585841080431321088):token=a、token=0、
583
- # token=aaaaaaaaaaaa 三者都返回完整推文,省略 token 参数则返回空响应体。
584
- # 因此这里用固定值——按 id 推导 base36 没有意义:那段手写浮点实现既与服务端
585
- # 计算方式无关(服务端不校验),也与它自己声称的公式不一致(固定 12 位小数 vs
586
- # 最短往返表示;只去首尾 0 vs 去所有 0),测试还把它锁成了金标。
587
- # 若将来服务端真的开始校验,再按公开公式
588
- # ((id / 1e15) * π).toString(36) 去掉所有 '0' 与 '.'
589
- # 重做推导,并在此处补真实向量测试。
590
- _SYNDICATION_TOKEN = "argo"
591
-
592
-
593
581
  def syndication_token(tweet_id: str) -> str:
594
- """syndication 展示参数(服务端不校验值,见上方常量注释)。
595
-
596
- 保留函数签名:调用方与测试按「请求必须带非空 token」这一契约依赖它。
597
- """
598
- return _SYNDICATION_TOKEN
582
+ """公开嵌入端点要求非空 token 参数。"""
583
+ return "argo"
599
584
 
600
585
 
601
586
  def _build_twitter_syndication_engine(spec: dict[str, Any]) -> Any:
602
- """X/Twitter 单条推文(syndication 通道,免登录、零 key)。
603
-
604
- 为什么需要第二条通道:X 的网页与官方 API 对未登录请求一律拒绝,
605
- 唯一常年开放的入口是面向第三方网页嵌入的 syndication 接口——它
606
- 本来就是给外部站点引用单条推文用的,天然公开且带完整正文与媒体。
587
+ from twitter_single_read import read_tweet
607
588
 
608
- 语义是「按推文取单条」的抽取型引擎,不是搜索:查询词接受推文 URL
609
- (x.com / twitter.com / 带 tweet_id 参数的分享链接)或裸 ID。拿它搜
610
- 关键词时诚实返回空列表,不回落到伪造结果——syndication 没有搜索端点。
611
- """
612
589
  timeout = spec.get("timeout", 8)
613
590
 
614
- @safe_search
615
591
  def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
616
- to = _timeout or timeout
617
592
  tweet_id = extract_tweet_id(query)
618
593
  if not tweet_id:
619
594
  return []
620
- token = syndication_token(tweet_id)
621
- url = (f"https://cdn.syndication.twimg.com/tweet-result"
622
- f"?id={tweet_id}&token={token}")
623
- headers = {
624
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
625
- "AppleWebKit/537.36 (KHTML, like Gecko) "
626
- "Chrome/150.0.0.0 Safari/537.36",
627
- "Accept": "application/json",
628
- "Referer": "https://platform.twitter.com/",
629
- }
630
- from engines_base import _http_get_raw
631
- raw = _http_get_raw(url, headers, to, engine="twitter_syndication")
632
- if not raw:
633
- return []
634
- try:
635
- data = json.loads(raw)
636
- except json.JSONDecodeError:
637
- return []
638
- # 正常推文 __typename="Tweet";墓碑(已删除/受限)返回 TweetTombstone
639
- # 等其他类型或空对象,一律按无结果处理,不伪造占位
640
- if not isinstance(data, dict) or not data:
641
- return []
642
- if data.get("__typename") and data["__typename"] != "Tweet":
643
- return []
644
- text = str(data.get("text") or "")
645
- # 作者字段:现行响应在 user 键(author 为历史兼容候选)
646
- author = data.get("user") or data.get("author") or {}
647
- screen_name = str(author.get("screen_name") or "")
648
- display_name = str(author.get("name") or "")
649
- created = str(data.get("created_at") or "")
650
- media = data.get("mediaDetails") or (data.get("entities") or {}).get("media") or []
651
- media_note = f"(含 {len(media)} 项媒体)" if media else ""
652
- canonical_url = (f"https://x.com/{screen_name}/status/{tweet_id}"
653
- if screen_name else
654
- f"https://x.com/i/web/status/{tweet_id}")
655
- title = f"@{screen_name}: {text[:80]}" if screen_name else text[:80]
656
- snippet_parts = []
657
- if created:
658
- snippet_parts.append(created)
659
- if display_name:
660
- snippet_parts.append(display_name)
661
- snippet_parts.append(text[:280])
662
- if media_note:
663
- snippet_parts.append(media_note)
664
- return [{
665
- "title": title[:100],
666
- "url": canonical_url,
667
- "snippet": " | ".join(p for p in snippet_parts if p),
668
- "source": "twitter_syndication",
669
- "score": 0.9,
670
- }]
595
+ return read_tweet(tweet_id, syndication_token(tweet_id), _timeout or timeout)
596
+
671
597
  return _engine
672
598
 
673
599
 
@@ -78,12 +78,13 @@ def _build_parallel_engine(spec: dict[str, Any]) -> Any:
78
78
  "excerpt_settings": {"max_chars_per_result": 300},
79
79
  },
80
80
  }
81
- # argo 时间窗 --since → after_date(官方 --after-date)
82
- since = kwargs.get("since")
83
- if since:
84
- date_str = str(since)[:10]
85
- if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str):
86
- body["advanced_settings"]["source_policy"] = {"after_date": date_str}
81
+ # argo 原生能力下推:since/until/sites/exclude_sites → source_policy
82
+ from query_operators import compile_provider_params
83
+ _p_hints = compile_provider_params(
84
+ "parallel", query, operators=kwargs.get("operators"),
85
+ since=kwargs.get("since"), until=kwargs.get("until"), depth=depth)
86
+ if _p_hints.get("source_policy"):
87
+ body["advanced_settings"]["source_policy"] = _p_hints["source_policy"]
87
88
  req = urllib.request.Request(
88
89
  _PARALLEL_URL,
89
90
  data=json.dumps(body).encode("utf-8"),
@@ -325,10 +326,20 @@ def _build_you_engine(spec: dict[str, Any]) -> Any:
325
326
  if not key:
326
327
  return [{"error": "YDC_API_KEY 未设置", "source": "you"}]
327
328
  body: dict[str, Any] = {"query": query, "count": max(1, int(n or 5))}
328
- freshness = _you_freshness(query)
329
+ from query_operators import compile_provider_params, is_evergreen_tech_query
330
+ _y_hints = compile_provider_params(
331
+ "you", query, operators=kwargs.get("operators"),
332
+ since=kwargs.get("since"), until=kwargs.get("until"))
333
+ # you 分支只产出 boost_domains/country/language(query_operators.compile_provider_params),
334
+ # 不产 freshness——此前的 _y_hints.get("freshness") 是永远取不到值的死读取
335
+ # (2026-11-20 审计:接线到一半),freshness 走下面的动态兜底。
336
+ freshness = "" if is_evergreen_tech_query(query) else _you_freshness(query)
329
337
  if freshness:
330
338
  body["freshness"] = freshness
331
- body["language"] = _you_language(query)
339
+ body["language"] = _y_hints.get("language") or _you_language(query)
340
+ for _k in ("country", "boost_domains"):
341
+ if _k in _y_hints:
342
+ body[_k] = _y_hints[_k]
332
343
  req = urllib.request.Request(
333
344
  _YOU_URL,
334
345
  data=json.dumps(body).encode("utf-8"),
@@ -181,40 +181,40 @@ def _build_exa_engine(spec: dict[str, Any]) -> Any:
181
181
  if not api_key:
182
182
  return _exa_mcp_keyless(query, n, to, spec)
183
183
  url = "https://api.exa.ai/search"
184
- body = json.dumps({
184
+ payload: dict[str, Any] = {
185
185
  "query": query,
186
186
  "type": "auto",
187
187
  "numResults": min(n, 10),
188
188
  "contents": {"text": {"maxCharacters": 400}},
189
- }).encode("utf-8")
189
+ }
190
+ from query_operators import compile_provider_params, format_exa_notices
191
+ payload.update(compile_provider_params(
192
+ "exa", query, operators=kwargs.get("operators"),
193
+ since=kwargs.get("since"), until=kwargs.get("until"), depth=depth))
194
+ body = json.dumps(payload).encode("utf-8")
190
195
  headers = {"x-api-key": api_key, "Content-Type": "application/json"}
191
196
  req = urllib.request.Request(url, data=body, headers=headers)
192
197
  try:
193
198
  with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
194
199
  data = json.loads(resp.read().decode("utf-8"))
200
+ notices = format_exa_notices(data.get("notices"))
195
201
  results = []
196
202
  for r in data.get("results", []):
197
203
  snippet = (r.get("text") or r.get("snippet") or "")[:300]
198
- # 轻量清洗:去掉 YAML front-matter(--- 开头的内容块)与导航噪声
199
204
  if snippet.startswith("---"):
200
205
  idx = snippet.find("---", 3)
201
206
  if idx != -1:
202
207
  snippet = snippet[idx + 3:].strip()
203
- # type:auto 模式不返回 score 字段(恒 0 会被 RRF 埋没),
204
- # 无 score 时给固定基线分;并叠加位次衰减。
205
- # 用 None/空串哨兵而不是 `or`:显式 0 分(上游判定不相关)
206
- # 会经 or 被抬成 0.75,与 2026-09-30 修过的同类
207
- # 「0 分垫底变中游」逐字同构。
208
208
  _raw_score = r.get("score")
209
- _base_score = 0.75 if _raw_score is None or _raw_score == "" \
210
- else _raw_score
211
- results.append({
212
- "title": r.get("title", ""),
213
- "url": r.get("url", ""),
214
- "snippet": snippet,
215
- "source": "exa",
209
+ _base_score = 0.75 if _raw_score is None or _raw_score == "" else _raw_score
210
+ item = {
211
+ "title": r.get("title", ""), "url": r.get("url", ""),
212
+ "snippet": snippet, "source": "exa",
216
213
  "score": rank_score(_base_score, len(results)),
217
- })
214
+ }
215
+ if notices and not results:
216
+ item["_notices"] = notices
217
+ results.append(item)
218
218
  return results
219
219
  except Exception as e:
220
220
  logger.warning(f"Exa 引擎失败: {e}")
@@ -89,3 +89,26 @@ def extract_items(data: Any, path: str) -> list:
89
89
  if isinstance(obj, dict):
90
90
  return [obj]
91
91
  return []
92
+
93
+
94
+ _NUMERIC_VALUE_RE = re.compile(r"[-+]?\d+(\.\d+)?([eE][-+]?\d+)?")
95
+
96
+
97
+ def _coerce_body_value(resolved: str) -> Any:
98
+ """body 模板值的类型收敛(唯一出口):bool → int → 数值 → 字符串。
99
+
100
+ 数值门用全等正则:旧 try/float 会把 "nan"/"inf" 放行成浮点,
101
+ json.dumps 产出非法 JSON(2026-11-21 审计)。非数值一律保留字符串。
102
+ 放在本模块:与 _coerce_field 同属取值/收敛原语,且 engines_base 的
103
+ 祖父行数上限经不起内联增长(拆出后回到 1473 内)。
104
+ """
105
+ lowered = resolved.lower()
106
+ if lowered == "true":
107
+ return True
108
+ if lowered == "false":
109
+ return False
110
+ if resolved.lstrip("-").isdigit():
111
+ return int(resolved)
112
+ if _NUMERIC_VALUE_RE.fullmatch(resolved):
113
+ return float(resolved)
114
+ return resolved
@@ -0,0 +1,182 @@
1
+ """Read-only X keyword search using the twitter-cli 0.8.5 JSON contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import time
10
+ from dataclasses import dataclass
11
+ from datetime import date, datetime, time as day_time, timedelta, timezone
12
+ from pathlib import Path
13
+
14
+ from engine_env import build_child_env
15
+
16
+ _HANDLE = re.compile(r"[A-Za-z0-9_]{1,15}")
17
+ _DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
18
+ _CANDIDATE_CAP = 100
19
+
20
+
21
+ def _instant(value: str, *, allow_date: bool = False) -> datetime:
22
+ if not isinstance(value, str):
23
+ raise ValueError("expected an absolute ISO date or timestamp")
24
+ if allow_date and _DATE.fullmatch(value):
25
+ return datetime.combine(date.fromisoformat(value), day_time.min, timezone.utc)
26
+ parsed = datetime.fromisoformat(value)
27
+ if parsed.tzinfo is None:
28
+ raise ValueError("timestamp requires an explicit timezone")
29
+ try:
30
+ return parsed.astimezone(timezone.utc)
31
+ except OverflowError:
32
+ raise ValueError("timestamp outside representable UTC range") from None
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class XConstraints:
37
+ query: str
38
+ author: str | None
39
+ since: datetime | None
40
+ until: datetime | None
41
+ complex_query: bool
42
+
43
+ @property
44
+ def strict(self) -> bool:
45
+ return bool(self.author or self.since or self.until)
46
+
47
+
48
+ def parse_x_constraints(query: str, since: str | None = None, until: str | None = None) -> XConstraints:
49
+ """Extract only unambiguous positive operators; bare dates mean UTC midnight."""
50
+ lower = _instant(since, allow_date=True) if since else None
51
+ upper = _instant(until, allow_date=True) if until else None
52
+ terms, ops = [], {}
53
+ complex_query = False
54
+ for token in query.split():
55
+ if any(ch in token for ch in "()\"'\\|"):
56
+ complex_query = True
57
+ break
58
+ key, sep, value = token.partition(":")
59
+ key = key.lower()
60
+ if sep and key in {"from", "since", "until"} and key not in ops:
61
+ if key != "from" or _HANDLE.fullmatch(value.removeprefix("@")):
62
+ ops[key] = value
63
+ continue
64
+ if not re.fullmatch(r"[#@]?\w+(?:[.-]\w+)*", token) or token.upper() in {"OR", "AND", "NOT"}:
65
+ complex_query = True
66
+ break
67
+ terms.append(token)
68
+ if not complex_query:
69
+ if "since" in ops:
70
+ bound = _instant(ops["since"], allow_date=True)
71
+ lower = max(lower, bound) if lower else bound
72
+ if "until" in ops:
73
+ bound = _instant(ops["until"], allow_date=True)
74
+ upper = min(upper, bound) if upper else bound
75
+ if lower and upper and lower >= upper:
76
+ raise ValueError("since must precede until")
77
+ if complex_query:
78
+ return XConstraints(query, None, lower, upper, True)
79
+ return XConstraints(" ".join(terms), ops.get("from", "").removeprefix("@") or None, lower, upper, False)
80
+
81
+
82
+ def matches_x_constraints(c: XConstraints, screen_name: str | None, created_at_iso: str | None) -> bool:
83
+ if c.author and (not isinstance(screen_name, str) or c.author.lower() != screen_name.lower()):
84
+ return False
85
+ if c.since or c.until:
86
+ try:
87
+ instant = _instant(created_at_iso)
88
+ except ValueError:
89
+ return False
90
+ return (not c.since or c.since <= instant) and (not c.until or instant < c.until)
91
+ return True
92
+
93
+
94
+ def _args(binary, c, count):
95
+ args = [binary, "search", "--json", "--type", "latest", "--max", str(count)]
96
+ if c.author:
97
+ args += ["--from", c.author]
98
+ # X day operators can omit posts near a UTC boundary. Include adjacent days
99
+ # upstream; only createdAtISO determines membership in the requested window.
100
+ if c.since and c.since.date() > date.min:
101
+ args += ["--since", (c.since.date() - timedelta(days=1)).isoformat()]
102
+ if c.until:
103
+ day = c.until.date()
104
+ pad = timedelta(days=1 if c.until.time() == day_time.min else 2)
105
+ if day <= date.max - pad:
106
+ args += ["--until", (day + pad).isoformat()]
107
+ if c.query:
108
+ args += ["--", c.query]
109
+ return args
110
+
111
+
112
+ def _error(message, kind="error"):
113
+ return [{"source": "twitter_cli", "error": message, "error_kind": kind}]
114
+
115
+
116
+ def _build_twitter_cli_engine(spec):
117
+ def search(query, n=5, timeout=None, *, since=None, until=None, **kwargs):
118
+ deadline = time.monotonic() + (spec.get("timeout", 20) if timeout is None else timeout)
119
+ try:
120
+ c = parse_x_constraints(query, since, until)
121
+ except ValueError:
122
+ return _error("invalid absolute X search window")
123
+ binary = shutil.which("twitter")
124
+ if not binary or Path(binary).suffix.lower() in {".cmd", ".bat"}:
125
+ return _error("twitter-cli executable unavailable", "unavailable")
126
+ # v0.8.5 caches both tweet lists and transaction data under Path.home().
127
+ # A regular file as child home makes both cache paths non-writable.
128
+ home = str(Path(binary).resolve())
129
+ env = build_child_env("twitter_cli", spec, extra_env={
130
+ "HOME": home, "USERPROFILE": home, "PYTHONDONTWRITEBYTECODE": "1",
131
+ })
132
+ if not (env.get("TWITTER_AUTH_TOKEN") and env.get("TWITTER_CT0")):
133
+ return _error("twitter-cli credentials unavailable", "unavailable")
134
+ target = max(1, min(int(n), _CANDIDATE_CAP))
135
+ count = target
136
+ results, seen = [], set()
137
+ for attempt in range(2):
138
+ remaining = deadline - time.monotonic()
139
+ if remaining <= 0:
140
+ return _error("twitter-cli search timed out")
141
+ try:
142
+ response = subprocess.run(_args(binary, c, count), env=env, timeout=remaining,
143
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
144
+ stderr=subprocess.DEVNULL, check=False)
145
+ except FileNotFoundError:
146
+ return _error("twitter-cli executable unavailable", "unavailable")
147
+ except subprocess.TimeoutExpired:
148
+ return _error("twitter-cli search timed out")
149
+ except OSError:
150
+ return _error("twitter-cli could not execute search")
151
+ if response.returncode:
152
+ return _error("twitter-cli search failed")
153
+ try:
154
+ payload = json.loads(response.stdout)
155
+ except (ValueError, UnicodeError):
156
+ return _error("invalid twitter-cli JSON")
157
+ if not (isinstance(payload, dict) and payload.get("ok") is True
158
+ and payload.get("schema_version") == "1" and isinstance(payload.get("data"), list)):
159
+ return _error("invalid twitter-cli search response")
160
+ batch = payload["data"]
161
+ for item in batch:
162
+ if not isinstance(item, dict) or not isinstance(item.get("author"), dict):
163
+ return _error("invalid twitter-cli tweet record")
164
+ handle = item["author"].get("screenName")
165
+ created, tid, text = item.get("createdAtISO"), item.get("id"), item.get("text")
166
+ if not isinstance(tid, str) or not re.fullmatch(r"[0-9]{1,20}", tid) or not isinstance(text, str):
167
+ return _error("invalid twitter-cli tweet record")
168
+ if tid in seen or not matches_x_constraints(c, handle, created):
169
+ continue
170
+ if not isinstance(handle, str) or not _HANDLE.fullmatch(handle):
171
+ return _error("invalid twitter-cli tweet author")
172
+ seen.add(tid)
173
+ results.append({"source": "twitter_cli", "tweet_id": tid, "author": handle,
174
+ "url": f"https://x.com/{handle}/status/{tid}", "published_at": created,
175
+ "title": f"@{handle}: {text[:100]}", "summary": text, "snippet": text})
176
+ if len(results) == target:
177
+ return results
178
+ if attempt or not c.strict or len(batch) < count or count >= _CANDIDATE_CAP:
179
+ break
180
+ count = min(_CANDIDATE_CAP, max(10, count * 2))
181
+ return results
182
+ return search