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
@@ -0,0 +1,248 @@
1
+ #!/usr/bin/env python3
2
+ """fetch_dispatch.py — argo fetch 统一 URL 专用提取器自动分发层。
3
+
4
+ 让调用方只需记住 `argo fetch <url>`,由本模块按 URL 特征自动路由至对应专有提取器:
5
+ - wechat : mp.weixin.qq.com/s... → wechat_article.fetch_wechat_article
6
+ - tweet : x.com|twitter.com/*/status/* → tweet.build_bundle + _render_text
7
+ - paper : arxiv.org/abs|html/<id> → paper.fetch_meta(结构化摘要与元数据)
8
+ - pdf : *.pdf 或 arxiv.org/pdf/<id> → pdf_extract.extract_pdf
9
+
10
+ 回落原则:
11
+ - 微信与 PDF 链接保持显式失败契约(提取失败、空正文或抛出异常时均返回
12
+ `success=False` 及对应 `FETCH_*_FAILED`,不落回通用 HTML 抓取链);
13
+ - tweet / paper 专用提取失败时返回 None,交由 fetch_v3 常规多级降级链兜底。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from typing import Any
20
+ from urllib.parse import urlparse
21
+
22
+ import engine_states
23
+
24
+ _TWEET_URL_RE = re.compile(
25
+ r"^https?://(?:(?:www|mobile)\.)?(?:x\.com|twitter\.com)/[^/]+/status/\d+",
26
+ re.IGNORECASE,
27
+ )
28
+ _ARXIV_ABS_RE = re.compile(
29
+ r"^https?://(?:www\.)?arxiv\.org/(?:abs|html)/([0-9]{4}\.[0-9]{4,5}(?:v\d+)?)",
30
+ re.IGNORECASE,
31
+ )
32
+ _ARXIV_PDF_RE = re.compile(
33
+ r"^https?://(?:www\.)?arxiv\.org/pdf/([0-9]{4}\.[0-9]{4,5}(?:v\d+)?)(?:\.pdf)?",
34
+ re.IGNORECASE,
35
+ )
36
+
37
+
38
+ def classify_specialized_url(url: str) -> str | None:
39
+ """识别适合走专有提取器的 URL 类型;普通网页返回 None。"""
40
+ if not url or not isinstance(url, str):
41
+ return None
42
+ u = url.strip()
43
+ try:
44
+ parsed = urlparse(u)
45
+ except ValueError:
46
+ return None
47
+ host = (parsed.hostname or "").lower()
48
+ path = parsed.path or ""
49
+
50
+ if host == "mp.weixin.qq.com" and (path == "/s" or path.startswith("/s/")):
51
+ return "wechat"
52
+ if _TWEET_URL_RE.match(u):
53
+ return "tweet"
54
+ if _ARXIV_PDF_RE.match(u) or path.lower().endswith(".pdf"):
55
+ return "pdf"
56
+ if _ARXIV_ABS_RE.match(u):
57
+ return "paper"
58
+ return None
59
+
60
+
61
+ def _dispatch_wechat(url: str, max_chars: int) -> dict[str, Any]:
62
+ try:
63
+ from wechat_article import fetch_wechat_article
64
+ wx = fetch_wechat_article(url)
65
+ except Exception as exc:
66
+ wx = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
67
+ if wx and wx.get("ok"):
68
+ content = (wx.get("content") or "")[:max_chars]
69
+ return {
70
+ "url": url,
71
+ "title": wx.get("title") or "",
72
+ "content": content,
73
+ "html": "",
74
+ "length": int(wx.get("char_count") or len(content)),
75
+ "success": True,
76
+ "fetch_method": engine_states.FETCH_WECHAT + str(
77
+ wx.get("fetch_method") or engine_states.FETCH_HTTP_DIRECT
78
+ ),
79
+ "author": wx.get("author") or "",
80
+ "publish_time": wx.get("publish_time") or "",
81
+ "dispatch_handler": "wechat",
82
+ }
83
+ return {
84
+ "url": url,
85
+ "title": "",
86
+ "content": "",
87
+ "html": "",
88
+ "length": 0,
89
+ "success": False,
90
+ "error": (wx or {}).get("error")
91
+ or "微信公众号文章抓取失败(HTTP/浏览器/搜狗三通道均未取到正文)",
92
+ "fetch_method": engine_states.FETCH_WECHAT_FAILED,
93
+ "dispatch_handler": "wechat",
94
+ }
95
+
96
+
97
+ def _dispatch_tweet(url: str, max_chars: int, timeout: float) -> dict[str, Any] | None:
98
+ try:
99
+ import tweet as tweet_mod
100
+ status_id, bundle = tweet_mod.build_bundle(
101
+ url, mode="status", timeout=max(5, int(timeout))
102
+ )
103
+ if not bundle or not bundle.get("main"):
104
+ return None
105
+ rendered = tweet_mod._render_text(status_id, "status", bundle)
106
+ main_post = bundle.get("main") or {}
107
+ author = tweet_mod._author_handle(main_post)
108
+ content = (rendered or "")[:max_chars]
109
+ if not content.strip():
110
+ return None
111
+ return {
112
+ "url": url,
113
+ "title": f"X 帖子 @{author} ({status_id})" if author else f"X 帖子 ({status_id})",
114
+ "content": content,
115
+ "html": "",
116
+ "length": len(content),
117
+ "success": True,
118
+ "fetch_method": engine_states.FETCH_X_ARTICLE,
119
+ "author": author,
120
+ "dispatch_handler": "tweet",
121
+ }
122
+ except Exception:
123
+ return None
124
+
125
+
126
+ def _dispatch_paper(url: str, max_chars: int) -> dict[str, Any] | None:
127
+ m = _ARXIV_ABS_RE.match(url.strip())
128
+ if not m:
129
+ return None
130
+ arxiv_id = m.group(1)
131
+ try:
132
+ import paper as paper_mod
133
+ meta = paper_mod.fetch_meta(paper_mod.normalize_arxiv_id(arxiv_id))
134
+ if not meta or not meta.get("title"):
135
+ return None
136
+ authors = ", ".join(meta.get("authors") or [])
137
+ abstract = str(meta.get("abstract") or meta.get("summary") or "").strip()
138
+ lines = [
139
+ f"# {meta['title']}",
140
+ f"- arXiv: {meta.get('id') or meta.get('arxiv_id') or arxiv_id}",
141
+ ]
142
+ if authors:
143
+ lines.append(f"- Authors: {authors}")
144
+ if meta.get("published"):
145
+ lines.append(f"- Published: {meta['published']}")
146
+ if meta.get("pdf_url"):
147
+ lines.append(f"- PDF: {meta['pdf_url']}")
148
+ if abstract:
149
+ lines.extend(["", "## Abstract", abstract])
150
+ content = "\n".join(lines)[:max_chars]
151
+ return {
152
+ "url": url,
153
+ "title": str(meta["title"]),
154
+ "content": content,
155
+ "html": "",
156
+ "length": len(content),
157
+ "success": True,
158
+ "fetch_method": engine_states.FETCH_HTTP,
159
+ "author": authors,
160
+ "publish_time": str(meta.get("published") or ""),
161
+ "dispatch_handler": "paper",
162
+ }
163
+ except Exception:
164
+ return None
165
+
166
+
167
+ def _dispatch_pdf(url: str, max_chars: int) -> dict[str, Any] | None:
168
+ try:
169
+ from pdf_extract import extract_pdf
170
+ res = extract_pdf(url)
171
+ if not res:
172
+ return None
173
+ # 依赖缺失是**明确失败**,不是「交给通用链」:pdfplumber / PyMuPDF
174
+ # 属可选 extras,未装时 extract_pdf 返回 success=False + error。
175
+ # 旧实现一律 return None,于是调用方回落到通用抓取链——那条链把 PDF
176
+ # 二进制当 HTML 抓回、正文抽取为空,最终给出 `success=True, length=0`
177
+ # 的假成功(2026-11-24 实测)。这里把失败显式传回去,让 fetch_v3
178
+ # 至少能报「为什么没拿到」。
179
+ if not res.get("success"):
180
+ err = str(res.get("error") or "PDF 提取失败")
181
+ return {
182
+ "url": url,
183
+ "title": "",
184
+ "content": "",
185
+ "html": "",
186
+ "length": 0,
187
+ "success": False,
188
+ "error": err,
189
+ "fetch_method": engine_states.FETCH_PDF_FAILED,
190
+ "dispatch_handler": "pdf",
191
+ }
192
+ content = str(res.get("content") or "")[:max_chars]
193
+ if not content.strip():
194
+ return {
195
+ "url": url,
196
+ "title": str(res.get("title") or ""),
197
+ "content": "",
198
+ "html": "",
199
+ "length": 0,
200
+ "success": False,
201
+ "error": "PDF 正文为空(可能为扫描图片页,需启用 OCR)",
202
+ "fetch_method": engine_states.FETCH_PDF_FAILED,
203
+ "dispatch_handler": "pdf",
204
+ }
205
+ return {
206
+ "url": url,
207
+ "title": str(res.get("title") or url.rsplit("/", 1)[-1]),
208
+ "content": content,
209
+ "html": "",
210
+ "length": len(content),
211
+ "success": True,
212
+ "fetch_method": engine_states.FETCH_HTTP,
213
+ "pages": res.get("pages"),
214
+ "dispatch_handler": "pdf",
215
+ }
216
+ except Exception as exc:
217
+ return {
218
+ "url": url,
219
+ "title": "",
220
+ "content": "",
221
+ "html": "",
222
+ "length": 0,
223
+ "success": False,
224
+ "error": f"PDF 提取异常: {type(exc).__name__}: {exc}",
225
+ "fetch_method": engine_states.FETCH_PDF_FAILED,
226
+ "dispatch_handler": "pdf",
227
+ }
228
+
229
+
230
+ def dispatch_specialized_fetch(
231
+ url: str,
232
+ *,
233
+ max_chars: int = 8000,
234
+ timeout: float = 15.0,
235
+ ) -> dict[str, Any] | None:
236
+ """按 URL 特征自动分发至专有提取器;非专用链接或可回落失败时返回 None。"""
237
+ kind = classify_specialized_url(url)
238
+ if kind is None:
239
+ return None
240
+ if kind == "wechat":
241
+ return _dispatch_wechat(url, max_chars)
242
+ if kind == "tweet":
243
+ return _dispatch_tweet(url, max_chars, timeout)
244
+ if kind == "paper":
245
+ return _dispatch_paper(url, max_chars)
246
+ if kind == "pdf":
247
+ return _dispatch_pdf(url, max_chars)
248
+ return None
@@ -236,3 +236,14 @@ def _compute_quality(content: str, html: str) -> float:
236
236
  return quality_breakdown(content, html)["total"]
237
237
 
238
238
 
239
+ def guard_empty_unknown_result(result: dict[str, Any]) -> dict[str, Any]:
240
+ """修正「成功但零正文 + page_type 未识别」的假成功(如二进制页被当 HTML 抓回)。"""
241
+ if (result.get("success") and not (result.get("content") or "").strip()
242
+ and result.get("page_type") in (None, "", "unknown")):
243
+ result["success"] = False
244
+ result["error"] = result.get("error") or (
245
+ "抓取成功但正文为空(URL 可能指向二进制文件或需专用解析器)"
246
+ )
247
+ return result
248
+
249
+
@@ -75,7 +75,7 @@ import fetch_quality as _quality
75
75
  import argo_paths as _paths
76
76
  from net_proxy import open_url # 出口调度唯一入口(issue #13 同类修复)
77
77
  from engine_env import env_flag, get_env # env_flag 判开关;get_env 读密钥(os.environ 优先,env 文件热读保底)
78
- from cli_io import dumps
78
+ from fetch_cli_output import print_result
79
79
  from fetch_jsrun import _jsrun_challenge_fetch, _jsrun_enabled # js-run 轻量车道(拆出独立模块)
80
80
 
81
81
 
@@ -1202,7 +1202,8 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1202
1202
  force_browser: bool = False,
1203
1203
  skip_cache: bool = False,
1204
1204
  need_html: bool = False,
1205
- deadline_s: float | None = None) -> dict:
1205
+ deadline_s: float | None = None,
1206
+ answer_offset: int | None = None) -> dict:
1206
1207
  """多级抓取降级链主函数(逐级升级,受全局 deadline 约束)。
1207
1208
 
1208
1209
  执行顺序:
@@ -1248,6 +1249,16 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1248
1249
  except ImportError:
1249
1250
  pass
1250
1251
 
1252
+ from zhihu_answer_fetch import fetch_answer, match_answer
1253
+ if answer_offset is not None or (not need_html and not actions and match_answer(url)):
1254
+ if deadline_s is None:
1255
+ try:
1256
+ deadline_s = float(os.environ.get("ARGO_FETCH_DEADLINE_S", "60") or 60)
1257
+ except ValueError:
1258
+ deadline_s = 60.0
1259
+ return fetch_answer(url, offset=answer_offset, max_chars=max_chars, timeout=timeout,
1260
+ deadline_s=deadline_s, browser=force_browser or use_browser_fallback)
1261
+
1251
1262
  # URL 优化(Reddit 重写、追踪参数清理)
1252
1263
  url = _optimize_url(url)
1253
1264
 
@@ -1274,46 +1285,19 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1274
1285
  _video["cached"] = False
1275
1286
  return _strip_html_unless_needed(_video, need_html)
1276
1287
 
1277
- # 微信专用降级链(HTTP→CDP→搜狗,wechat_article.py,`argo wx` 同实现——用户
1278
- # 显式取文不走匿名爬虫 robots 口径)【必须在 robots 闸前】mp.weixin/robots.txt
1279
- # 是 Disallow: /(11-15 实测),闸先跑分支永不可达(6ebb625 实跑复现)。让路同前。
1280
- if (_is_wechat_article_url(url) and not need_html and not actions
1281
- and not force_browser):
1282
- try:
1283
- from wechat_article import fetch_wechat_article
1284
- _wx = fetch_wechat_article(url)
1285
- except Exception:
1286
- _wx = None
1287
- if _wx and _wx.get("ok"):
1288
- _wx_result = {
1289
- "url": url,
1290
- "title": _wx.get("title") or "",
1291
- "content": (_wx.get("content") or "")[:max_chars],
1292
- "html": "",
1293
- "length": int(_wx.get("char_count") or 0),
1294
- "success": True,
1295
- "fetch_method": engine_states.FETCH_WECHAT + str(
1296
- _wx.get("fetch_method") or engine_states.FETCH_HTTP_DIRECT),
1297
- "author": _wx.get("author") or "",
1298
- "publish_time": _wx.get("publish_time") or "",
1299
- }
1300
- try:
1301
- _wx_result = _assess_quality(_wx_result)
1302
- except SHAPE_BENIGN:
1303
- pass
1304
- _wx_result["cached"] = False
1305
- return _strip_html_unless_needed(_wx_result, need_html)
1306
- # 专用链三级全败即结构化失败、不落回通用链:通用链对 mp.weixin 只会拿
1307
- # JS 骨架冒充成功(11-01 实测病灶);_has_content 保证到这里的是真失败。
1308
- return _strip_html_unless_needed({
1309
- "url": url,
1310
- "title": "", "content": "", "html": "",
1311
- "length": 0, "success": False,
1312
- "error": (_wx or {}).get("error")
1313
- or "微信公众号文章抓取失败(HTTP/浏览器/搜狗三通道均未取到正文)",
1314
- "fetch_method": engine_states.FETCH_WECHAT_FAILED,
1315
- "cached": False,
1316
- }, need_html)
1288
+ # 专用 URL 自动分发(微信 / X 推文 / arXiv 论文 / PDF,fetch_dispatch.py)
1289
+ # 【必须在 robots 闸前】mp.weixin/robots.txt 为 Disallow: /,让路同前。
1290
+ if not need_html and not actions and not force_browser:
1291
+ from fetch_dispatch import dispatch_specialized_fetch
1292
+ _spec = dispatch_specialized_fetch(url, max_chars=max_chars, timeout=timeout)
1293
+ if _spec is not None:
1294
+ if _spec.get("success"):
1295
+ try:
1296
+ _spec = _assess_quality(_spec)
1297
+ except SHAPE_BENIGN:
1298
+ pass
1299
+ _spec["cached"] = False
1300
+ return _strip_html_unless_needed(_spec, need_html)
1317
1301
 
1318
1302
  # robots.txt 尊重(合规检查):被禁路径直接拒绝,抓取失败放行
1319
1303
  try:
@@ -1593,8 +1577,10 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1593
1577
  if deadline_hit["flag"]:
1594
1578
  result["deadline_exhausted"] = True
1595
1579
 
1596
- # 第三级:质量评估
1580
+ # 第三级:质量评估 + 空正文假成功守卫(统一收口在 fetch_quality)
1597
1581
  result = _assess_quality(result)
1582
+ from fetch_quality import guard_empty_unknown_result
1583
+ result = guard_empty_unknown_result(result)
1598
1584
 
1599
1585
  # 文章级元数据(链接/作者/站点名/摘要):与正文同源于本次 HTML,一次解析
1600
1586
  # 拿全;调用方不必为了顺着引用继续取证而重抓页面。缓存一起存(链接上限
@@ -1711,7 +1697,8 @@ def _full_view(url: str, args) -> dict:
1711
1697
  有了这条通道,「先看 8,000 字摘要、需要时再翻全文」才成立。
1712
1698
  """
1713
1699
  from_archive = True
1714
- text = _read_archived(url)
1700
+ from zhihu_answer_fetch import match_answer
1701
+ text = None if match_answer(url) else _read_archived(url)
1715
1702
  if text is None:
1716
1703
  from_archive = False
1717
1704
  r = fetch_v3(url, max_chars=0, timeout=args.timeout,
@@ -1733,23 +1720,17 @@ def _full_view(url: str, args) -> dict:
1733
1720
  "fetch_method": (engine_states.FETCH_FULLTEXT if from_archive
1734
1721
  else r.get("fetch_method", "full")),
1735
1722
  })
1723
+ if "next_offset" in out:
1724
+ out["truncated"] = out["length"] < out["total_length"]
1736
1725
  return out
1737
1726
 
1738
1727
 
1739
1728
  # ─── CLI ─────────────────────────────────────────────────────────────────────
1740
1729
 
1741
- # 人类可读输出的默认显示上限(字符)。--limit 管的是交付窗口,这里是显示上限;
1742
- # 显式 --full / --limit 时按调用方要求放开,截断时打印可翻页的提示。
1743
- _DISPLAY_CHARS = 2000
1744
-
1745
-
1746
1730
  def build_parser():
1747
- """CLI 参数表(独立成函数以便测试校验旗标契约)。
1748
-
1749
- `--use-browser` 与 `--browser` 同义:文档两处都写过前者,入口若只认后者,
1750
- 用户照文档敲命令即报错。两个名字都收,避免再出现「文档有、代码无」。
1751
- """
1731
+ """构建抓取命令的参数解析器。"""
1752
1732
  import argparse
1733
+
1753
1734
  p = argparse.ArgumentParser(description="Argo fetch v3 — 四级抓取(零依赖)")
1754
1735
  p.add_argument("url", help="目标 URL")
1755
1736
  p.add_argument("--max-chars", type=int, default=8000)
@@ -1767,6 +1748,7 @@ def build_parser():
1767
1748
  p.add_argument("--full", action="store_true",
1768
1749
  help="取全文:优先读本地全文存档,没有则按抓取全量取回,"
1769
1750
  "不受 --max-chars 限制(用于复核被截断的部分)")
1751
+ p.add_argument("--answer-offset", type=int, help="仅在用户明确要求续查知乎回答摘要时传入 next_offset")
1770
1752
  p.add_argument("--offset", type=int, default=0,
1771
1753
  help="从正文第 N 个字符开始输出(配合 --limit 翻页读长文)")
1772
1754
  p.add_argument("--limit", type=int, default=0,
@@ -1781,7 +1763,10 @@ def build_parser():
1781
1763
 
1782
1764
 
1783
1765
  if __name__ == "__main__":
1784
- args = build_parser().parse_args()
1766
+ parser = build_parser()
1767
+ args = parser.parse_args()
1768
+ if args.answer_offset is not None and (args.full or args.offset or args.limit or args.actions):
1769
+ parser.error("--answer-offset 仅用于回答摘要续查,不能与正文切片或页面交互组合。")
1785
1770
 
1786
1771
  actions = None
1787
1772
  if args.actions:
@@ -1797,68 +1782,17 @@ if __name__ == "__main__":
1797
1782
  timeout=args.timeout,
1798
1783
  force_browser=args.browser,
1799
1784
  use_browser_fallback=not args.no_fallback,
1800
- actions=actions)
1785
+ actions=actions, answer_offset=args.answer_offset)
1801
1786
 
1802
1787
  focus_requested = bool(args.focus)
1803
1788
  pre_focus_len = r.get("length", 0)
1804
1789
  r = _apply_focus_to_result(r, args.focus, top_k=args.focus_top,
1805
1790
  max_chars=args.max_chars)
1806
1791
 
1807
- # 输出摘要
1808
- summary = {k: r[k] for k in ("success", "fetch_method", "content_ok",
1809
- "quality_score", "page_type", "source_type",
1810
- "is_official", "length", "url",
1811
- "video_meta") if k in r}
1812
- # 截断必须可见:只给 8,000 字却不说明「还有多少没给」,调用方会当全文用
1813
- for k in ("truncated", "full_length", "full_text_path", "total_length",
1814
- "offset", "full_source", "final_url",
1815
- "login_state_used", "cache_eligible"):
1816
- if k in r:
1817
- summary[k] = r[k]
1818
- if focus_requested:
1819
- # 显式回报聚焦是否真的生效:正文过短时 focus_applied=False,
1820
- # 不谎报「已省 token」
1821
- summary["focus_applied"] = bool(r.get("focus_applied"))
1822
- if r.get("error"):
1823
- summary["error"] = r["error"]
1824
- if r.get("links"):
1825
- summary["links_count"] = len(r["links"])
1826
- if args.include_links:
1827
- summary["links"] = r["links"]
1828
- print(dumps(summary))
1829
- # __main__ 块是模块级代码,不能用 return 短路——用 if 包住人类可读段
1830
- if not args.json:
1831
- if r.get("title"):
1832
- print(f"\nTitle: {r['title']}")
1833
- if focus_requested:
1834
- print(f"\n[focus] query={args.focus!r} applied={bool(r.get('focus_applied'))} "
1835
- f"chars={pre_focus_len} → {r.get('length', 0)}")
1836
- print(f"\n--- CONTENT ({r['length']} chars) ---")
1837
- # 默认档保持 2000 字显示上限(护住 agent 上下文),但显式 --full /
1838
- # --limit 时必须按调用方要求显示完整交付窗口:此前这行硬编码
1839
- # [:2000],与 --limit 的语义(本次输出字符数上限,0 表示不限)冲突,
1840
- # 且表头写的是交付长度,于是「说 8000 字、只给 2000 字、不说明还剩
1841
- # 多少」——调用方会把截断正文当全文用(证据核验场景尤其危险)。
1842
- delivered = r.get("content", "") or ""
1843
- show_all = bool(args.full) or bool(args.limit and args.limit > 0)
1844
- shown = delivered if show_all else delivered[:_DISPLAY_CHARS]
1845
- print(shown)
1846
- if len(shown) < len(delivered):
1847
- # 两个字段是不同代码路径写的同一事实:fetch_v3 路径给 full_length,
1848
- # _full_view 路径给 total_length,故这里按可用者兜底。
1849
- full_len = r.get("full_length") or r.get("total_length") or len(delivered)
1850
- if focus_requested:
1851
- # --focus 之后 content 是重排后的段落抽取,不再是正文的连续窗口,
1852
- # 按「本页起点 + 本页长度」推 --offset 会指向无关区间。宁可不给
1853
- # 翻页建议,也不能给错的。
1854
- print(f"\n[truncated] 已显示 {len(shown)}/{len(delivered)} 字"
1855
- f"(页面全文 {full_len} 字)。当前为 --focus 抽取结果,"
1856
- f"非正文连续窗口;要完整正文请用 --full")
1857
- else:
1858
- # --offset 是相对正文全文的绝对偏移(见 _full_view),所以下一页
1859
- # 要从「本页起点 + 本页长度」继续,否则已翻过页的调用方会原地打转。
1860
- next_offset = int(r.get("offset") or 0) + len(shown)
1861
- print(f"\n[truncated] 已显示 {len(shown)}/{len(delivered)} 字"
1862
- f"(页面全文 {full_len} 字)。"
1863
- f"继续读:--offset {next_offset} --limit {_DISPLAY_CHARS};"
1864
- f"全文:--full")
1792
+ if focus_requested and not (args.full or args.offset or args.limit):
1793
+ from zhihu_answer_fetch import finish_focus
1794
+ finish_focus(r, args.max_chars)
1795
+
1796
+ print_result(r, json_only=args.json, include_links=args.include_links,
1797
+ focus=args.focus, pre_focus_len=pre_focus_len,
1798
+ full=args.full, limit=args.limit)