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
@@ -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
+ }
@@ -50,14 +50,14 @@ try { page = task.page("p1"); } catch (e) { page = null; }
50
50
  if (!page) page = await task.newPage();
51
51
  await page.goto(%(base)s + "?q=" + encodeURIComponent(CFG.query) + "&f=" + CFG.sort);
52
52
  // 等首屏:出 article 视为渲染完成;出「无结果」文案也视为渲染完成(真·空结果)
53
- let rendered = false;
53
+ let rendered = false, empty = false;
54
54
  for (let i = 0; i < %(wait_s)d; i++) {
55
55
  await page.waitForTimeout(1000);
56
56
  const st = await page.evaluate(() => ({
57
57
  arts: document.querySelectorAll('[data-testid="cellInnerDiv"] article').length,
58
58
  empty: /没有结果|No results for|无结果/i.test(document.body.innerText || ""),
59
59
  }));
60
- if (st.arts > 0 || st.empty) { rendered = true; break; }
60
+ if (st.arts > 0 || st.empty) { rendered = true; empty = st.empty && !st.arts; break; }
61
61
  }
62
62
  let items = [];
63
63
  if (rendered) {
@@ -99,7 +99,7 @@ if (rendered) {
99
99
  return out;
100
100
  });
101
101
  }
102
- console.log("%(marker)s" + JSON.stringify({ok: rendered, items: items.slice(0, CFG.n)}));
102
+ console.log("%(marker)s" + JSON.stringify({ok: rendered, empty, items: items.slice(0, CFG.n)}));
103
103
  """
104
104
 
105
105
 
@@ -164,6 +164,24 @@ def _rows(items: list[dict], n: int) -> list[dict]:
164
164
  return rows
165
165
 
166
166
 
167
+ def search_browser(query: str, n: int, timeout: float, sort: str = "latest") -> list[dict]:
168
+ """Fetch rendered posts; an empty list requires an explicit no-results page."""
169
+ if not shutil.which("ego-browser"):
170
+ raise FileNotFoundError("ego-browser CLI 不存在")
171
+ proc = subprocess.run(
172
+ ["ego-browser", "nodejs", "-e", _build_js(query, n, "top" if sort == "top" else "live")],
173
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
174
+ if proc.returncode:
175
+ raise RuntimeError(f"ego-browser rc={proc.returncode}")
176
+ data = _extract_json(proc.stdout) or _extract_json(proc.stderr)
177
+ if not data or not data.get("ok") or not isinstance(data.get("items"), list):
178
+ raise RuntimeError("x.com/search 无可解析结果(未登录 / 未渲染 / 页面结构异常)")
179
+ rows = _rows(data["items"], n)
180
+ if not rows and not data.get("empty"):
181
+ raise RuntimeError("x.com/search 未提取到可识别帖子")
182
+ return rows
183
+
184
+
167
185
  def main(argv: list | None = None) -> int:
168
186
  ap = argparse.ArgumentParser(
169
187
  prog="argo x-search",
@@ -181,38 +199,11 @@ def main(argv: list | None = None) -> int:
181
199
  print("x_search: 搜索词为空", file=sys.stderr)
182
200
  return 1
183
201
 
184
- if not shutil.which("ego-browser"):
185
- print("x_search: ego-browser CLI 不存在(Ego Lite 未安装?)", file=sys.stderr)
186
- return 1
187
-
188
- sort = "top" if args.sort == "top" else "live"
189
202
  try:
190
- proc = subprocess.run(
191
- ["ego-browser", "nodejs", "-e", _build_js(query, max(1, args.n), sort)],
192
- capture_output=True, text=True, encoding="utf-8",
193
- errors="replace", timeout=args.timeout)
194
- except subprocess.TimeoutExpired:
195
- print(f"x_search: ego-browser 超时(>{args.timeout:.0f}s)", file=sys.stderr)
203
+ rows = search_browser(query, max(1, args.n), args.timeout, args.sort)
204
+ except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc:
205
+ print(f"x_search: {exc}", file=sys.stderr)
196
206
  return 1
197
- except FileNotFoundError:
198
- print("x_search: ego-browser 调用失败", file=sys.stderr)
199
- return 1
200
-
201
- if proc.returncode != 0:
202
- tail = (proc.stderr or "").strip()[:200]
203
- print(f"x_search: ego-browser rc={proc.returncode}: {tail}", file=sys.stderr)
204
- return 1
205
-
206
- data = _extract_json(proc.stdout) or _extract_json(proc.stderr)
207
- if not data:
208
- print("x_search: 未能解析 ego-browser 输出", file=sys.stderr)
209
- return 1
210
- if not data.get("ok"):
211
- # 页面没渲染:多半是未登录、被风控拦下,或 X 改版
212
- print("x_search: x.com/search 未渲染(未登录 / 风控 / 改版?)", file=sys.stderr)
213
- return 1
214
-
215
- rows = _rows(data.get("items") or [], max(1, args.n))
216
207
 
217
208
  if args.json:
218
209
  print(json.dumps(rows, ensure_ascii=False))
@@ -0,0 +1,96 @@
1
+ """Read the visible text of one verified, expanded Zhihu answer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ import time
9
+ import threading
10
+
11
+ from browser_auth import auth_profile_for_fetch
12
+ from chrome_cdp import ChromeCDP
13
+
14
+
15
+ _INSPECT = r"""(url, current) => {
16
+ if (current !== url || document.readyState !== 'complete') return '';
17
+ const visible = el => el.getClientRects().length && el.checkVisibility();
18
+ const all = (root, selector) => Array.from(root.querySelectorAll(selector));
19
+ if (all(document, '[role="dialog"], .Modal-wrapper, .Captcha').some(visible)) return '';
20
+ const cards = all(document, '.AnswerItem').filter(c =>
21
+ all(c, ':scope > meta[itemprop="url"]').some(m => m.content === url));
22
+ if (cards.length !== 1) return '';
23
+ const card = cards[0];
24
+ const sections = all(card, '.RichContent').filter(e => e.closest('.AnswerItem') === card);
25
+ if (sections.length !== 1) return '';
26
+ const section = sections[0];
27
+ const bodies = all(section, '.RichContent-inner .RichText.ztext[itemprop="text"]');
28
+ if (bodies.length !== 1) return '';
29
+ const body = bodies[0];
30
+ if (!visible(body) || body.closest('.is-collapsed, [aria-hidden="true"]') ||
31
+ card.querySelector('[class*="Paywall" i], [class*="PaidMask" i], [class*="Preview" i], .RichContent-cover, .RichContent-inner--collapsed')) return '';
32
+ const buttons = all(section, 'button').filter(visible);
33
+ const label = b => b.innerText.replace(/[\s\u200b]/g, '');
34
+ if (!buttons.some(b => !body.contains(b) && b.matches('.ContentItem-rightButton') && label(b) === '收起')) return '';
35
+ if (buttons.some(b => /阅读全文|展开全文|继续阅读|购买|解锁/.test(label(b))) ||
36
+ /付费阅读|购买后.{0,6}阅读|开通.{0,8}查看全文|试读结束|最低.{0,8}查看完整内容/.test(card.innerText)) return '';
37
+ for (let e = body; e && e !== card; e = e.parentElement) {
38
+ const css = getComputedStyle(e);
39
+ if ((['hidden','clip','auto','scroll'].includes(css.overflowY) && e.scrollHeight > e.clientHeight + 1) ||
40
+ (css.webkitLineClamp && css.webkitLineClamp !== 'none')) return '';
41
+ }
42
+ return body.innerText.trim();
43
+ }"""
44
+
45
+
46
+ def read_body(question: str, answer: str, timeout: float) -> str:
47
+ """Return expanded answer text, or an empty string when verification fails."""
48
+ if not all(isinstance(i, str) and re.fullmatch(r'[1-9][0-9]{0,19}', i) for i in (question, answer)):
49
+ return ''
50
+ if not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
51
+ return ''
52
+ url = f'https://www.zhihu.com/question/{question}/answer/{answer}'
53
+ deadline = time.monotonic() + timeout
54
+ if not _PROFILE_BUSY.acquire(blocking=False):
55
+ return ''
56
+ result = []
57
+
58
+ def run():
59
+ try:
60
+ result.append(_read(url, deadline))
61
+ finally:
62
+ _PROFILE_BUSY.release()
63
+
64
+ # ChromeCDP owns its own startup, evaluation and shutdown timeouts. Keep
65
+ # ownership until its context manager exits, even after the caller times out.
66
+ worker = threading.Thread(target=run, name='zhihu-answer-body', daemon=False)
67
+ try:
68
+ worker.start()
69
+ except RuntimeError:
70
+ _PROFILE_BUSY.release()
71
+ return ''
72
+ worker.join(min(threading.TIMEOUT_MAX, max(0, deadline - time.monotonic())))
73
+ return result[0] if result and time.monotonic() < deadline else ''
74
+
75
+
76
+ _PROFILE_BUSY = threading.Lock()
77
+
78
+
79
+ def _read(url: str, deadline: float) -> str:
80
+ probe = f'({_INSPECT})({json.dumps(url)}, location.origin + location.pathname)'
81
+ try:
82
+ profile = auth_profile_for_fetch(url)
83
+ if profile:
84
+ with ChromeCDP(user_data_dir=profile) as browser:
85
+ if time.monotonic() >= deadline:
86
+ return ''
87
+ browser.navigate(url, wait_until='load', timeout=min(5.0, deadline - time.monotonic()))
88
+ while time.monotonic() < deadline:
89
+ text = browser.evaluate(probe)
90
+ if isinstance(text, str) and text and time.monotonic() < deadline:
91
+ return text
92
+ time.sleep(max(0.0, min(0.2, deadline - time.monotonic())))
93
+ except Exception:
94
+ # The public result does not carry browser, transport, or session diagnostics.
95
+ return ''
96
+ return ''
@@ -0,0 +1,66 @@
1
+ """Fetch a verified Zhihu answer or an explicitly labelled API summary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ import time
8
+
9
+
10
+ _ANSWER = re.compile(
11
+ r"https://www\.zhihu\.com/question/([1-9][0-9]{0,19})/answer/([1-9][0-9]{0,19})"
12
+ )
13
+
14
+
15
+ def match_answer(url: str):
16
+ return _ANSWER.fullmatch(url)
17
+
18
+
19
+ def finish_focus(result, max_chars):
20
+ if "next_offset" in result and max_chars > 0:
21
+ content = result["content"][:max_chars]
22
+ result.update(content=content, length=len(content),
23
+ truncated=result["truncated"] or result.get("focus_applied", False)
24
+ or len(content) < result["full_length"])
25
+ return result
26
+
27
+
28
+ def fetch_answer(url, *, offset, max_chars, timeout, deadline_s=None, browser=True):
29
+ def result(status, kind, text, next_offset=None):
30
+ content = text[:max_chars] if max_chars > 0 else text
31
+ return dict(
32
+ url=url,
33
+ status=status,
34
+ content_type=kind,
35
+ content=content,
36
+ success=status == "found",
37
+ next_offset=next_offset,
38
+ length=len(content),
39
+ full_length=len(text),
40
+ truncated=content != text,
41
+ )
42
+
43
+ match = match_answer(url)
44
+ if not match or (offset is not None and (type(offset) is not int or offset < 0)):
45
+ return result(
46
+ "error", "status", "需要精确的知乎回答 URL 和非负整数 answer_offset。"
47
+ )
48
+ if not math.isfinite(timeout) or timeout <= 0 or max_chars < 0:
49
+ return result("error", "status", "抓取预算无效。")
50
+ budget = min(timeout, deadline_s) if deadline_s and deadline_s > 0 else timeout
51
+ deadline = time.monotonic() + budget
52
+ question, answer = match.groups()
53
+ if offset is None and browser:
54
+ from zhihu_answer_body import read_body
55
+
56
+ text = read_body(question, answer, max(0, deadline - time.monotonic()) / 2)
57
+ if text and time.monotonic() < deadline:
58
+ return result("found", "body", text)
59
+ from zhihu_answer_lookup import lookup
60
+
61
+ item = lookup(question, answer, offset or 0, deadline)
62
+ if item["url"] != url:
63
+ return result("error", "status", "摘要来源与目标回答不符。")
64
+ return result(
65
+ item["status"], item["content_type"], item["text"], item.get("next_offset")
66
+ )
@@ -0,0 +1,138 @@
1
+ """按问题、回答 ID 读取知乎开放平台的回答摘要。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ import threading
9
+ from concurrent.futures import Future, TimeoutError as WaitTimeout
10
+ from http.client import HTTPException
11
+ from time import monotonic
12
+ from urllib.error import HTTPError
13
+ from urllib.parse import urlencode
14
+ from urllib.request import Request
15
+
16
+ from engine_env import get_env
17
+ from net_proxy import open_url
18
+ from social_engines.zhihu_engine import (
19
+ ZHIHU_QUESTION_ANSWERS_API,
20
+ strip_html_tags,
21
+ zhihu_headers,
22
+ )
23
+
24
+ _PAGE_LIMIT = 50
25
+ _MAX_PAGES = 4
26
+ _MAX_BYTES = 2 * 1024 * 1024
27
+ _IN_FLIGHT = threading.BoundedSemaphore(8)
28
+
29
+
30
+ def _request(question_url, offset, secret, deadline):
31
+ params = urlencode(
32
+ {"QuestionUrl": question_url, "Limit": _PAGE_LIMIT, "Offset": offset}
33
+ )
34
+ req = Request(f"{ZHIHU_QUESTION_ANSWERS_API}?{params}")
35
+ for key, value in zhihu_headers(secret).items():
36
+ req.add_unredirected_header(key, value)
37
+ remaining = deadline - monotonic()
38
+ if remaining <= 0:
39
+ raise TimeoutError
40
+ with open_url(req, timeout=remaining) as response:
41
+ body = response.read(_MAX_BYTES + 1)
42
+ if len(body) > _MAX_BYTES:
43
+ raise ValueError("page exceeds size limit")
44
+ return json.loads(body)
45
+
46
+
47
+ def _page(question_url, offset, secret, deadline):
48
+ # urllib 的 socket 超时按单次 I/O 计;调用方只等待总预算内的时间。
49
+ future = Future()
50
+ if not _IN_FLIGHT.acquire(blocking=False):
51
+ raise OSError("lookup capacity reached")
52
+
53
+ def run():
54
+ try:
55
+ future.set_result(_request(question_url, offset, secret, deadline))
56
+ except Exception as exc:
57
+ future.set_exception(exc)
58
+ finally:
59
+ _IN_FLIGHT.release()
60
+
61
+ try:
62
+ threading.Thread(target=run, daemon=True).start()
63
+ except RuntimeError:
64
+ _IN_FLIGHT.release()
65
+ raise
66
+ return future.result(timeout=max(0.0, deadline - monotonic()))
67
+
68
+
69
+ def lookup(question: str, answer: str, offset: int, deadline: float) -> dict:
70
+ """读取最多四页。continue 的 next_offset 指向首个尚未检查的页。"""
71
+ url = ""
72
+
73
+ def result(status, text, **extra):
74
+ return dict(
75
+ status=status,
76
+ text=text,
77
+ url=url,
78
+ content_type="summary" if status == "found" else "status",
79
+ **extra,
80
+ )
81
+
82
+ if not all(
83
+ isinstance(x, str) and re.fullmatch("[0-9]+", x) for x in (question, answer)
84
+ ):
85
+ return result("error", "问题 ID 和回答 ID 必须是十进制数字。")
86
+ question_url = f"https://www.zhihu.com/question/{question}"
87
+ url = f"{question_url}/answer/{answer}"
88
+ if type(offset) is not int or offset < 0 or not math.isfinite(deadline):
89
+ return result("error", "查询偏移或截止时间无效。")
90
+ secret = get_env(["ARGO_ZHIHU_ACCESS_SECRET", "ZHIHU_ACCESS_SECRET"])
91
+ if not secret:
92
+ return result("error", "缺少知乎开放平台凭据。")
93
+ for _ in range(_MAX_PAGES):
94
+ if monotonic() >= deadline:
95
+ break
96
+ try:
97
+ payload = _page(question_url, offset, secret, deadline)
98
+ except (TimeoutError, WaitTimeout):
99
+ if monotonic() >= deadline:
100
+ break
101
+ return result("error", "知乎接口请求超时。")
102
+ except HTTPError as exc:
103
+ exc.close()
104
+ return result("error", f"知乎接口返回 HTTP {exc.code}。")
105
+ except (OSError, HTTPException, ValueError, RuntimeError) as exc:
106
+ return result("error", f"知乎接口读取失败({type(exc).__name__})。")
107
+ if not isinstance(payload, dict) or type(payload.get("Code")) is not int:
108
+ return result("error", "知乎接口响应缺少有效状态码。")
109
+ if payload["Code"] != 0:
110
+ return result("error", f"知乎接口错误:Code={payload['Code']}。")
111
+ data = payload.get("Data")
112
+ if not isinstance(data, dict) or not isinstance(data.get("Items"), list):
113
+ return result("error", "知乎接口回答列表格式异常。")
114
+ for item in data["Items"]:
115
+ if not isinstance(item, dict):
116
+ return result("error", "知乎接口回答条目格式异常。")
117
+ if (
118
+ item.get("Url") == url
119
+ and str(item.get("ContentToken")) == answer
120
+ and str(item.get("ContentType")).lower() == "answer"
121
+ ):
122
+ raw = item.get("Summary")
123
+ text = strip_html_tags(raw) if isinstance(raw, str) else ""
124
+ if text:
125
+ return result("found", text)
126
+ return result("error", "已定位回答,知乎接口未提供摘要。")
127
+ paging = data.get("Paging")
128
+ if not isinstance(paging, dict) or type(paging.get("IsEnd")) is not bool:
129
+ return result("error", "知乎接口缺少有效末页标记。")
130
+ if paging["IsEnd"]:
131
+ return result("not_found", "已到知乎接口末页,本次查询范围内未找到该回答。")
132
+ cursor = paging.get("NextOffset")
133
+ if type(cursor) is not int or cursor <= offset:
134
+ return result("error", "知乎接口未提供有效的下一页偏移。")
135
+ offset = cursor
136
+ return result(
137
+ "continue", f"尚未查完,可从偏移 {offset} 继续查询。", next_offset=offset
138
+ )