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.
- package/AGENTS.md +3 -3
- package/README.es.md +10 -5
- package/README.ja.md +10 -5
- package/README.ko.md +10 -5
- package/README.md +11 -6
- package/README.zh.md +11 -6
- package/SKILL.md +12 -11
- package/assets/readme/counts.json +1 -1
- package/assets/readme/hero.svg +3 -3
- package/backends/domain_profiles.json +6 -0
- package/backends/engine_registry.yaml +12 -0
- package/backends/quota_profiles.json +10 -0
- package/bin/argo +78 -12
- package/docs/CHANGELOG.md +19 -1
- package/docs/COMMIT_STANDARD.md +2 -2
- package/docs/ENGINE_CATALOG.md +7 -6
- package/docs/RELEASE_NOTES_v2.17.0.md +4 -2
- package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
- package/docs/RELEASING.md +1 -1
- package/engines/specs/twitter_cli.yaml +17 -0
- package/engines/specs/twitter_syndication.yaml +2 -3
- package/package.json +2 -1
- package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
- package/packages/dsh-plugin/dsh/workbench-io.js +34 -15
- package/packages/dsh-plugin/dsh/workbench-search.js +66 -6
- package/packages/dsh-plugin/dsh/workbench.js +43 -0
- package/packages/dsh-plugin/package.json +1 -1
- package/packages/dsh-plugin/test/workbench-concurrency.test.js +9 -11
- package/packages/dsh-plugin/test/workbench.test.js +85 -0
- package/scripts/affected_tests.py +324 -0
- package/scripts/badcase_ledger.py +93 -2
- package/scripts/check_commit_report.py +13 -9
- package/scripts/cli_io.py +8 -3
- package/scripts/engine_families.py +1 -0
- package/scripts/engine_states.py +4 -4
- package/scripts/engines.py +2 -0
- package/scripts/engines_base.py +12 -28
- package/scripts/engines_builders_intl.py +20 -94
- package/scripts/engines_twitter_cli.py +182 -0
- package/scripts/fetch_cli_output.py +75 -0
- package/scripts/fetch_dispatch.py +248 -0
- package/scripts/fetch_quality.py +11 -0
- package/scripts/fetch_v3.py +48 -114
- package/scripts/intent_router.py +224 -0
- package/scripts/mcp_compact.py +3 -0
- package/scripts/mcp_handlers.py +24 -4
- package/scripts/mcp_tools.py +2 -0
- package/scripts/mcp_transport.py +1 -1
- package/scripts/mcp_warm.py +15 -11
- package/scripts/output_transparency.py +10 -0
- package/scripts/pre-commit +9 -1
- package/scripts/release_check.py +1 -2
- package/scripts/research_notes.py +52 -5
- package/scripts/retry_policy.py +17 -3
- package/scripts/route_combo.py +8 -3
- package/scripts/search.py +29 -29
- package/scripts/search_cli.py +104 -8
- package/scripts/search_output.py +4 -1
- package/scripts/social_research.py +8 -6
- package/scripts/time_utils.py +28 -0
- package/scripts/twitter_single_read.py +107 -0
- package/scripts/x_keyword_route.py +138 -0
- package/scripts/x_search.py +24 -33
- package/scripts/zhihu_answer_body.py +96 -0
- package/scripts/zhihu_answer_fetch.py +66 -0
- package/scripts/zhihu_answer_lookup.py +138 -0
- package/sub-skills/local-seek/SKILL.md +3 -1
- package/sub-skills/local-seek/scripts/seek.py +80 -109
- package/sub-skills/local-seek/scripts/seek_git.py +65 -0
- package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
package/scripts/engines_base.py
CHANGED
|
@@ -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
|
|
@@ -436,6 +437,8 @@ def _build_http_engine(spec: dict[str, Any]) -> Any:
|
|
|
436
437
|
# 失败返回空(与 urllib 失败行为一致,不抛异常)
|
|
437
438
|
raw = _http_get_raw(full_url, resolved_headers, to, engine=eng)
|
|
438
439
|
if raw is None:
|
|
440
|
+
if eng == "fxtwitter":
|
|
441
|
+
return [{"source": eng, "error": "FxTwitter HTTP request failed"}]
|
|
439
442
|
return []
|
|
440
443
|
return _parse_http_payload(raw, fmt, eng, n, output_map, spec)
|
|
441
444
|
else:
|
|
@@ -680,33 +683,6 @@ def _envelope_error(data: Any) -> str:
|
|
|
680
683
|
return ""
|
|
681
684
|
|
|
682
685
|
|
|
683
|
-
def _normalize_epoch(value: Any) -> str:
|
|
684
|
-
"""epoch 秒/毫秒 → `YYYY-MM-DD`,非 epoch 原样返回。
|
|
685
|
-
|
|
686
|
-
技能目录源的 updatedAt 单位不统一:SkillsMP 给秒(1786285295),ClawHub
|
|
687
|
-
给毫秒(1789594554485),相差 1000 倍。原样映射等于把一串数字当
|
|
688
|
-
published_at 交出去,既读不出日期也无法与别的源比较。
|
|
689
|
-
|
|
690
|
-
按量级判别而非按源声明:1e9~1e11 是秒(2001~5138 年),1e11~1e14 是
|
|
691
|
-
毫秒,两位差三个数量级,不存在擦边区间。范围外的值不猜,原样返回——
|
|
692
|
-
猜错会把一个可疑值变成看起来正常的值,比留着更糟。
|
|
693
|
-
"""
|
|
694
|
-
text = str(value).strip()
|
|
695
|
-
if not text.isdigit():
|
|
696
|
-
return text
|
|
697
|
-
num = int(text)
|
|
698
|
-
if 1_000_000_000 <= num < 100_000_000_000:
|
|
699
|
-
seconds = num
|
|
700
|
-
elif 100_000_000_000 <= num < 100_000_000_000_000:
|
|
701
|
-
seconds = num / 1000
|
|
702
|
-
else:
|
|
703
|
-
return text
|
|
704
|
-
try:
|
|
705
|
-
return datetime.fromtimestamp(seconds, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
706
|
-
except (OverflowError, OSError, ValueError):
|
|
707
|
-
return text
|
|
708
|
-
|
|
709
|
-
|
|
710
686
|
def _apply_url_kind(rows: list[dict[str, Any]], spec: dict) -> list[dict[str, Any]]:
|
|
711
687
|
"""声明式 spec 的 url_kind 落到行上(issue #29 口径 B):none = 本档条目不以
|
|
712
688
|
url 为身份,缺 url 的条目不按壳页整批吞。spec 未声明时行上不出现该字段。"""
|
|
@@ -735,7 +711,15 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
|
|
|
735
711
|
data = json.loads(raw)
|
|
736
712
|
except (json.JSONDecodeError, ValueError):
|
|
737
713
|
_get_logger().warning(f"HTTP 引擎解析失败: {eng} 非 JSON/XML 响应")
|
|
714
|
+
if eng == "fxtwitter":
|
|
715
|
+
return [{"source": eng, "error": "FxTwitter returned invalid JSON"}]
|
|
738
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"}]
|
|
739
723
|
# 业务错误封套优先于条数提取:强封套错误(ResponseMetadata.Error、顶层
|
|
740
724
|
# error 对象)表示本次调用失败,返回结果必然为空或不可信
|
|
741
725
|
env_err = _envelope_error(data)
|
|
@@ -798,7 +782,7 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
|
|
|
798
782
|
for r in parsed:
|
|
799
783
|
r.setdefault("source", eng)
|
|
800
784
|
if r.get("published_at"):
|
|
801
|
-
r["published_at"] = _normalize_epoch(r["published_at"])
|
|
785
|
+
r["published_at"] = _normalize_epoch(r["published_at"], precise=eng == "fxtwitter")
|
|
802
786
|
if _lic and r.get("image_url"):
|
|
803
787
|
r.setdefault("image_license", _lic)
|
|
804
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
|
-
|
|
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
|
-
"""
|
|
567
|
-
|
|
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 =
|
|
572
|
+
m = _TWEET_PATH.fullmatch(url.path)
|
|
570
573
|
if m:
|
|
571
574
|
return m.group(1)
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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
|
-
"""
|
|
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
|
-
|
|
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
|
-
|
|
621
|
-
|
|
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
|
|
|
@@ -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
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""抓取命令的 JSON 摘要与终端正文输出。"""
|
|
2
|
+
|
|
3
|
+
from cli_io import dumps
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# 人类可读输出的默认显示上限(字符)。--limit 管的是交付窗口,这里是显示上限;
|
|
7
|
+
# 显式 --full / --limit 时按调用方要求放开,截断时打印可翻页的提示。
|
|
8
|
+
_DISPLAY_CHARS = 2000
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def print_result(r: dict, *, json_only: bool, include_links: bool, focus: str,
|
|
12
|
+
pre_focus_len: int, full: bool, limit: int) -> None:
|
|
13
|
+
focus_requested = bool(focus)
|
|
14
|
+
summary = {k: r[k] for k in ("success", "fetch_method", "dispatch_handler",
|
|
15
|
+
"content_ok", "quality_score", "page_type",
|
|
16
|
+
"source_type", "is_official", "length",
|
|
17
|
+
"url", "title", "video_meta") if k in r}
|
|
18
|
+
if json_only and "content" in r:
|
|
19
|
+
summary["content"] = r["content"]
|
|
20
|
+
# 截断必须可见:只给 8,000 字却不说明「还有多少没给」,调用方会当全文用
|
|
21
|
+
for k in ("truncated", "full_length", "full_text_path", "total_length",
|
|
22
|
+
"offset", "full_source", "final_url",
|
|
23
|
+
"login_state_used", "cache_eligible"):
|
|
24
|
+
if k in r:
|
|
25
|
+
summary[k] = r[k]
|
|
26
|
+
if "content_type" in r and "next_offset" in r:
|
|
27
|
+
summary.update({k: r[k] for k in ("status", "content_type", "next_offset")})
|
|
28
|
+
if json_only:
|
|
29
|
+
summary["content"] = r["content"]
|
|
30
|
+
if focus_requested:
|
|
31
|
+
# 显式回报聚焦是否真的生效:正文过短时 focus_applied=False,
|
|
32
|
+
# 不谎报「已省 token」
|
|
33
|
+
summary["focus_applied"] = bool(r.get("focus_applied"))
|
|
34
|
+
if r.get("error"):
|
|
35
|
+
summary["error"] = r["error"]
|
|
36
|
+
if r.get("links"):
|
|
37
|
+
summary["links_count"] = len(r["links"])
|
|
38
|
+
if include_links:
|
|
39
|
+
summary["links"] = r["links"]
|
|
40
|
+
print(dumps(summary))
|
|
41
|
+
if not json_only:
|
|
42
|
+
if r.get("title"):
|
|
43
|
+
print(f"\nTitle: {r['title']}")
|
|
44
|
+
if focus_requested:
|
|
45
|
+
print(f"\n[focus] query={focus!r} applied={bool(r.get('focus_applied'))} "
|
|
46
|
+
f"chars={pre_focus_len} → {r.get('length', 0)}")
|
|
47
|
+
print(f"\n--- CONTENT ({r['length']} chars) ---")
|
|
48
|
+
# 默认档保持 2000 字显示上限(护住 agent 上下文),但显式 --full /
|
|
49
|
+
# --limit 时必须按调用方要求显示完整交付窗口:此前这行硬编码
|
|
50
|
+
# [:2000],与 --limit 的语义(本次输出字符数上限,0 表示不限)冲突,
|
|
51
|
+
# 且表头写的是交付长度,于是「说 8000 字、只给 2000 字、不说明还剩
|
|
52
|
+
# 多少」——调用方会把截断正文当全文用(证据核验场景尤其危险)。
|
|
53
|
+
delivered = r.get("content", "") or ""
|
|
54
|
+
show_all = bool(full) or bool(limit and limit > 0)
|
|
55
|
+
shown = delivered if show_all else delivered[:_DISPLAY_CHARS]
|
|
56
|
+
print(shown)
|
|
57
|
+
if len(shown) < len(delivered):
|
|
58
|
+
# 两个字段是不同代码路径写的同一事实:fetch_v3 路径给 full_length,
|
|
59
|
+
# _full_view 路径给 total_length,故这里按可用者兜底。
|
|
60
|
+
full_len = r.get("full_length") or r.get("total_length") or len(delivered)
|
|
61
|
+
if focus_requested:
|
|
62
|
+
# --focus 之后 content 是重排后的段落抽取,不再是正文的连续窗口,
|
|
63
|
+
# 按「本页起点 + 本页长度」推 --offset 会指向无关区间。宁可不给
|
|
64
|
+
# 翻页建议,也不能给错的。
|
|
65
|
+
print(f"\n[truncated] 已显示 {len(shown)}/{len(delivered)} 字"
|
|
66
|
+
f"(页面全文 {full_len} 字)。当前为 --focus 抽取结果,"
|
|
67
|
+
f"非正文连续窗口;要完整正文请用 --full")
|
|
68
|
+
else:
|
|
69
|
+
# --offset 是相对正文全文的绝对偏移(见 _full_view),所以下一页
|
|
70
|
+
# 要从「本页起点 + 本页长度」继续,否则已翻过页的调用方会原地打转。
|
|
71
|
+
next_offset = int(r.get("offset") or 0) + len(shown)
|
|
72
|
+
print(f"\n[truncated] 已显示 {len(shown)}/{len(delivered)} 字"
|
|
73
|
+
f"(页面全文 {full_len} 字)。"
|
|
74
|
+
f"继续读:--offset {next_offset} --limit {_DISPLAY_CHARS};"
|
|
75
|
+
f"全文:--full")
|