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/x_search.py
CHANGED
|
@@ -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
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
+
)
|
|
@@ -35,10 +35,12 @@ argo seek "查询词" --filename # 按文件名
|
|
|
35
35
|
argo seek "查询词" --spotlight # 全盘兜底
|
|
36
36
|
argo seek "查询词" --type py,ts
|
|
37
37
|
argo seek "查询词" --json # 结构化输出
|
|
38
|
+
argo seek "查询词" --agent # Agent 单开关(紧凑 JSON + 默认 --max 20,零命中附 handoff_hint)
|
|
38
39
|
argo seek "查询词" --exact # 精确匹配(关扩展)
|
|
39
40
|
argo seek "符号名" --symbol # 精确符号/词边界匹配
|
|
40
41
|
argo seek "查询词" --exclude 某文件 # 额外排除(可重复)
|
|
41
|
-
argo seek --outline 文件路径 #
|
|
42
|
+
argo seek --outline 文件路径 # 文件结构与精确起止行跨度(def/class/标题/顶层key)
|
|
43
|
+
argo seek --symbol-body 符号 文件 # 一跳直读符号定义源码(≤200 行封顶,超限附续读范围)
|
|
42
44
|
argo seek --lines 10-50 文件路径 # 按行读取,替代 read_file 全文
|
|
43
45
|
argo seek "裸except" --structural # 结构搜索(空catch/裸except/装饰函数等)
|
|
44
46
|
argo seek --git-log 文件路径 # 文件的最近提交历史
|
|
@@ -1390,84 +1390,23 @@ def filter_by_mtime(results, since: str | None, until: str | None):
|
|
|
1390
1390
|
if _in_time_window(fp, since_ts, until_ts)]
|
|
1391
1391
|
|
|
1392
1392
|
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
|
|
1411
|
-
".bash": [re.compile(r'^\s*function\s+\w+'),
|
|
1412
|
-
re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
|
|
1413
|
-
".zsh": [re.compile(r'^\s*function\s+\w+'),
|
|
1414
|
-
re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
|
|
1415
|
-
".md": [re.compile(r'^#{1,6}\s+')],
|
|
1416
|
-
".mdx": [re.compile(r'^#{1,6}\s+')],
|
|
1417
|
-
".json": [re.compile(r'^\s*"[^"]+"\s*:')],
|
|
1418
|
-
".yaml": [re.compile(r'^[a-zA-Z_][\w.-]*\s*:')],
|
|
1419
|
-
".yml": [re.compile(r'^[a-zA-Z_][\w.-]*\s*:')],
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
def outline_file(path):
|
|
1424
|
-
"""输出代码/文档文件结构,替代整文件读取。返回 (输出文本, 退出码)。"""
|
|
1425
|
-
p = Path(path)
|
|
1426
|
-
if not p.is_file():
|
|
1427
|
-
return f"local-seek: {path} 不是文件", 1
|
|
1428
|
-
try:
|
|
1429
|
-
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
1430
|
-
except OSError as e:
|
|
1431
|
-
return f"local-seek: 读取失败 {e}", 1
|
|
1432
|
-
rules = _OUTLINE_RULES.get(p.suffix.lower())
|
|
1433
|
-
if not rules:
|
|
1434
|
-
return (f"local-seek: {p.name} 共 {len(lines)} 行"
|
|
1435
|
-
f"({p.suffix or '无扩展名'} 暂无结构规则)"), 0
|
|
1436
|
-
hits = []
|
|
1437
|
-
for i, ln in enumerate(lines, 1):
|
|
1438
|
-
if any(r.match(ln) for r in rules):
|
|
1439
|
-
hits.append(f"{i}: {ln.strip()[:100]}")
|
|
1440
|
-
head = f"local-seek: {p.name} 结构 {len(hits)} 处 / 共 {len(lines)} 行"
|
|
1441
|
-
return "\n".join([head] + hits), 0
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
def read_lines(path, spec):
|
|
1445
|
-
"""按行读取文件(单遍流式,不加载全文)。返回 (输出文本, 退出码)。"""
|
|
1446
|
-
m = re.fullmatch(r"(\d+)-(\d+)", spec)
|
|
1447
|
-
if not m:
|
|
1448
|
-
return "local-seek: --lines 格式应为 N-M(如 10-20)", 1
|
|
1449
|
-
a, b = int(m.group(1)), int(m.group(2))
|
|
1450
|
-
if a < 1 or b < a:
|
|
1451
|
-
return f"local-seek: 行范围无效 {spec}", 1
|
|
1452
|
-
p = Path(path)
|
|
1453
|
-
if not p.is_file():
|
|
1454
|
-
return f"local-seek: {path} 不是文件", 1
|
|
1455
|
-
# 单遍流式读取:边数总行数边收集目标区间。原实现先 open 数行、再 open
|
|
1456
|
-
# 读区间,同一文件开两遍——大文件时 IO 翻倍(2026-10-06 收口)。
|
|
1457
|
-
picked, total = [], 0
|
|
1458
|
-
try:
|
|
1459
|
-
with open(p, encoding="utf-8", errors="replace") as f:
|
|
1460
|
-
for i, ln in enumerate(f, 1):
|
|
1461
|
-
total = i
|
|
1462
|
-
if a <= i <= b:
|
|
1463
|
-
picked.append(f"{i}: {ln.rstrip()}")
|
|
1464
|
-
except OSError as e:
|
|
1465
|
-
return f"local-seek: 读取失败 {e}", 1
|
|
1466
|
-
if a > total:
|
|
1467
|
-
return f"local-seek: {p.name} 只有 {total} 行,请求从 {a} 行开始", 1
|
|
1468
|
-
end = min(b, total)
|
|
1469
|
-
out = [f"local-seek: {p.name} 第 {a}-{end} 行 / 共 {total} 行"]
|
|
1470
|
-
return "\n".join(out + picked), 0
|
|
1393
|
+
# 精读层与历史层已拆至 seek_inspect.py / seek_git.py(保持同名 re-export 兼容既有测试)
|
|
1394
|
+
_SEEK_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
|
|
1395
|
+
if _SEEK_SCRIPTS_DIR not in sys.path:
|
|
1396
|
+
sys.path.insert(0, _SEEK_SCRIPTS_DIR)
|
|
1397
|
+
|
|
1398
|
+
from seek_inspect import ( # noqa: E402
|
|
1399
|
+
_OUTLINE_RULES,
|
|
1400
|
+
_compute_outline_entries,
|
|
1401
|
+
_outline_level,
|
|
1402
|
+
outline_file,
|
|
1403
|
+
read_lines,
|
|
1404
|
+
read_symbol_body,
|
|
1405
|
+
)
|
|
1406
|
+
from seek_git import ( # noqa: E402
|
|
1407
|
+
git_blame as _git_blame_impl,
|
|
1408
|
+
git_log as _git_log_impl,
|
|
1409
|
+
)
|
|
1471
1410
|
|
|
1472
1411
|
|
|
1473
1412
|
STRUCTURAL_RULES = {
|
|
@@ -1561,33 +1500,13 @@ def structural_search(rule_name, path, excludes, max_results, dots=False,
|
|
|
1561
1500
|
|
|
1562
1501
|
|
|
1563
1502
|
def git_log(path, n=10, timeout=None):
|
|
1564
|
-
"""
|
|
1565
|
-
|
|
1566
|
-
if not p.is_file():
|
|
1567
|
-
return f"local-seek: {path} 不是文件", 1
|
|
1568
|
-
proc = run(["git", "-C", str(p.parent), "log", "--oneline", f"-{n}", "--", p.name],
|
|
1569
|
-
timeout=timeout)
|
|
1570
|
-
if proc is None:
|
|
1571
|
-
return "local-seek: git 执行失败", 1
|
|
1572
|
-
if proc.returncode == 128 or (proc.returncode == 0 and not proc.stdout.strip()):
|
|
1573
|
-
inside = run(["git", "-C", str(p.parent), "rev-parse", "--is-inside-work-tree"])
|
|
1574
|
-
if inside is None or inside.returncode != 0:
|
|
1575
|
-
return f"local-seek: {p.name} 不在 git 仓库中", 1
|
|
1576
|
-
return f"local-seek: {p.name} 无提交历史", 0
|
|
1577
|
-
lines = proc.stdout.splitlines()
|
|
1578
|
-
return "\n".join([f"local-seek: {p.name} 最近 {len(lines)} 条提交"] + lines), 0
|
|
1503
|
+
"""输出文件的最近提交历史(委托至 seek_git,注入本模块 run 以兼容单测 monkeypatch)。"""
|
|
1504
|
+
return _git_log_impl(path, n=n, timeout=timeout, runner=run)
|
|
1579
1505
|
|
|
1580
1506
|
|
|
1581
1507
|
def git_blame(path, line, timeout=None):
|
|
1582
|
-
"""输出文件第 N 行的 blame
|
|
1583
|
-
|
|
1584
|
-
if not p.is_file():
|
|
1585
|
-
return f"local-seek: {path} 不是文件", 1
|
|
1586
|
-
proc = run(["git", "-C", str(p.parent), "blame", "-L", f"{line},{line}", "--", p.name],
|
|
1587
|
-
timeout=timeout)
|
|
1588
|
-
if proc is None or proc.returncode != 0:
|
|
1589
|
-
return f"local-seek: git blame 失败({p.name} 可能在 git 仓库外或行号无效)", 1
|
|
1590
|
-
return f"local-seek: {p.name} 第 {line} 行\n{proc.stdout.strip()}", 0
|
|
1508
|
+
"""输出文件第 N 行的 blame 信息(委托至 seek_git)。"""
|
|
1509
|
+
return _git_blame_impl(path, line, timeout=timeout, runner=run)
|
|
1591
1510
|
|
|
1592
1511
|
|
|
1593
1512
|
def _run_grep_fallback(args, patterns, fixed, path, excludes, exts, max_results,
|
|
@@ -1671,6 +1590,8 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
|
|
|
1671
1590
|
ap.add_argument("--count", action="store_true", help="只输出每文件命中数")
|
|
1672
1591
|
ap.add_argument("--context", type=int, default=0, help="上下文行数(默认 0)")
|
|
1673
1592
|
ap.add_argument("--json", action="store_true", help="JSON 输出")
|
|
1593
|
+
ap.add_argument("--agent", action="store_true",
|
|
1594
|
+
help="Agent 消费单开关:等价 --json + 紧凑序列化 + 默认 --max 20 上限")
|
|
1674
1595
|
ap.add_argument("--max", type=int, default=0, help="最大结果数(默认读配置)")
|
|
1675
1596
|
ap.add_argument("--exact", action="store_true", help="关闭中文扩展(精确匹配)")
|
|
1676
1597
|
ap.add_argument("--symbol", action="store_true",
|
|
@@ -1681,9 +1602,11 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
|
|
|
1681
1602
|
help="文件修改时间下限(7d / 2026-08-01),过滤命中文件的 mtime")
|
|
1682
1603
|
ap.add_argument("--until", default=None,
|
|
1683
1604
|
help="文件修改时间上限(7d / 2026-08-01),过滤命中文件的 mtime")
|
|
1684
|
-
ap.add_argument("--outline", action="store_true", help="
|
|
1605
|
+
ap.add_argument("--outline", action="store_true", help="输出文件结构与精确起止行跨度(文件路径为位置参数)")
|
|
1685
1606
|
ap.add_argument("--lines", default="", metavar="N-M",
|
|
1686
1607
|
help="按行读取文件(文件路径为位置参数)")
|
|
1608
|
+
ap.add_argument("--symbol-body", default="", metavar="NAME",
|
|
1609
|
+
help="按符号名一跳读取定义区间源码,≤200 行封顶(文件路径为位置参数)")
|
|
1687
1610
|
ap.add_argument("--structural", action="store_true",
|
|
1688
1611
|
help="结构搜索:按语义检索(裸except/空catch/装饰函数/函数定义等)")
|
|
1689
1612
|
ap.add_argument("--git-log", action="store_true",
|
|
@@ -1693,18 +1616,44 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
|
|
|
1693
1616
|
ap.add_argument("--domains", action="store_true", help="列出知识域与排除规则")
|
|
1694
1617
|
args = ap.parse_args(argv)
|
|
1695
1618
|
|
|
1619
|
+
# --agent 单开关展开:等价 --json + 预算封顶(默认 --max 20,防止大仓库吐爆上下文)
|
|
1620
|
+
if args.agent:
|
|
1621
|
+
args.json = True
|
|
1622
|
+
if not args.max:
|
|
1623
|
+
args.max = 20
|
|
1624
|
+
|
|
1625
|
+
# 互斥动作模式 Fail-Fast 校验(避免位置参数在「查询词」与「文件路径」间静默误判)
|
|
1626
|
+
_active_modes: list[str] = []
|
|
1627
|
+
if args.outline or args.lines or args.symbol_body:
|
|
1628
|
+
_active_modes.append("精读模式(--outline/--lines/--symbol-body)")
|
|
1629
|
+
if args.git_log or args.git_blame:
|
|
1630
|
+
_active_modes.append("历史模式(--git-log/--git-blame)")
|
|
1631
|
+
if args.structural:
|
|
1632
|
+
_active_modes.append("结构搜索(--structural)")
|
|
1633
|
+
if args.filename:
|
|
1634
|
+
_active_modes.append("文件名搜索(--filename)")
|
|
1635
|
+
if args.spotlight:
|
|
1636
|
+
_active_modes.append("Spotlight(--spotlight)")
|
|
1637
|
+
if len(_active_modes) > 1:
|
|
1638
|
+
return f"local-seek: 动作模式互斥({' 与 '.join(_active_modes)} 不能同时指定)", 2
|
|
1639
|
+
if (args.outline or args.lines or args.symbol_body) and (args.count or args.context):
|
|
1640
|
+
return "local-seek: 精读模式与 --count/--context 互斥", 2
|
|
1641
|
+
|
|
1696
1642
|
# 知识域展示模式
|
|
1697
1643
|
if args.domains:
|
|
1698
1644
|
if DOMAINS_FILE.exists():
|
|
1699
1645
|
return DOMAINS_FILE.read_text(encoding="utf-8"), 0
|
|
1700
1646
|
return "未找到 config/domains.yaml,使用内置默认规则", 0
|
|
1701
1647
|
|
|
1702
|
-
# 文件结构 / 按行读取模式(文件路径优先取位置参数,否则取 --path)
|
|
1703
|
-
if args.outline or args.lines:
|
|
1648
|
+
# 文件结构 / 符号体 / 按行读取模式(文件路径优先取位置参数,否则取 --path)
|
|
1649
|
+
if args.outline or args.lines or args.symbol_body:
|
|
1704
1650
|
target = args.query or str(args.path)
|
|
1651
|
+
if args.symbol_body:
|
|
1652
|
+
cap = args.max if (args.max and not args.agent) else 200
|
|
1653
|
+
return read_symbol_body(target, args.symbol_body, max_lines=cap, as_json=args.json)
|
|
1705
1654
|
if args.lines:
|
|
1706
|
-
return read_lines(target, args.lines)
|
|
1707
|
-
return outline_file(target)
|
|
1655
|
+
return read_lines(target, args.lines, as_json=args.json)
|
|
1656
|
+
return outline_file(target, as_json=args.json)
|
|
1708
1657
|
|
|
1709
1658
|
# git 联动模式:查文件提交历史 / 单行归属
|
|
1710
1659
|
if args.git_log or args.git_blame:
|
|
@@ -1933,13 +1882,35 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
|
|
|
1933
1882
|
pass
|
|
1934
1883
|
|
|
1935
1884
|
if err:
|
|
1885
|
+
if args.agent:
|
|
1886
|
+
return json.dumps({"ok": False, "query": args.query, "engine": engine, "error": err}, ensure_ascii=False), 1
|
|
1936
1887
|
return f"local-seek: {err}", 1
|
|
1937
1888
|
if not results:
|
|
1889
|
+
if args.agent:
|
|
1890
|
+
handoff = {
|
|
1891
|
+
"expand_path": f'argo seek "{args.query}" --path ~ --spotlight',
|
|
1892
|
+
"web_fallback": f'argo search "{args.query}" --agent',
|
|
1893
|
+
}
|
|
1894
|
+
return json.dumps({
|
|
1895
|
+
"query": args.query,
|
|
1896
|
+
"engine": engine,
|
|
1897
|
+
"mode": mode,
|
|
1898
|
+
"scope": scope,
|
|
1899
|
+
"path": str(path),
|
|
1900
|
+
"elapsed_ms": elapsed,
|
|
1901
|
+
"count": 0,
|
|
1902
|
+
"results": [],
|
|
1903
|
+
"handoff_hint": handoff,
|
|
1904
|
+
}, ensure_ascii=False), 1
|
|
1938
1905
|
return f"local-seek: 未找到匹配({engine} · {path} · {elapsed}ms)", 1
|
|
1939
1906
|
|
|
1940
1907
|
if args.json:
|
|
1941
|
-
|
|
1942
|
-
|
|
1908
|
+
raw_json = to_json(results, engine, mode, scope, path, elapsed, args.query,
|
|
1909
|
+
since=args.since, until=args.until)
|
|
1910
|
+
if args.agent:
|
|
1911
|
+
# --agent 输出紧凑单行 JSON(省空白字节)
|
|
1912
|
+
return json.dumps(json.loads(raw_json), ensure_ascii=False, separators=(",", ":")), 0
|
|
1913
|
+
return raw_json, 0
|
|
1943
1914
|
return format_output(results, engine, mode, path, elapsed, args.query,
|
|
1944
1915
|
len(results)), 0
|
|
1945
1916
|
|