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.
- package/AGENTS.md +4 -2
- package/README.es.md +15 -5
- package/README.ja.md +15 -5
- package/README.ko.md +15 -5
- package/README.md +16 -6
- package/README.zh.md +16 -6
- package/SKILL.md +12 -11
- package/assets/readme/counts.json +1 -1
- package/assets/readme/hero.svg +3 -3
- package/assets/readme/hero.template.svg +121 -0
- package/assets/readme/proof-routes.svg +17 -16
- package/backends/domain_profiles.json +121 -18
- package/backends/engine_registry.yaml +23 -0
- package/backends/env_passthrough.txt +2 -0
- package/backends/quota_profiles.json +20 -0
- package/bin/argo +78 -12
- package/docs/CHANGELOG.md +35 -1
- package/docs/COMMIT_STANDARD.md +12 -2
- package/docs/ENGINE_CATALOG.md +36 -33
- package/docs/RELEASE_NOTES_v2.17.0.md +66 -0
- package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
- package/docs/RELEASING.md +2 -2
- package/engines/specs/crossref.yaml +2 -0
- package/engines/specs/hackernews.yaml +2 -0
- package/engines/specs/helve.yaml +49 -0
- package/engines/specs/hf_papers.yaml +2 -0
- package/engines/specs/openalex.yaml +9 -2
- package/engines/specs/twitter_cli.yaml +17 -0
- package/engines/specs/twitter_syndication.yaml +2 -3
- package/package.json +3 -1
- package/packages/dsh-plugin/README.md +5 -2
- package/packages/dsh-plugin/cordis.patch.yml +4 -1
- package/packages/dsh-plugin/dsh/client.js +57 -63
- package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
- package/packages/dsh-plugin/dsh/index.js +109 -21
- package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
- package/packages/dsh-plugin/dsh/route-guard.js +95 -0
- package/packages/dsh-plugin/dsh/runner.js +49 -6
- package/packages/dsh-plugin/dsh/wide-research.js +20 -18
- package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
- package/packages/dsh-plugin/dsh/workbench-io.js +182 -0
- package/packages/dsh-plugin/dsh/workbench-search.js +445 -0
- package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
- package/packages/dsh-plugin/dsh/workbench.js +277 -497
- package/packages/dsh-plugin/package.json +4 -3
- package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
- package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
- package/packages/dsh-plugin/test/client.test.js +26 -0
- package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
- package/packages/dsh-plugin/test/index.test.js +150 -1
- package/packages/dsh-plugin/test/workbench-concurrency.test.js +96 -0
- package/packages/dsh-plugin/test/workbench.test.js +422 -9
- package/scripts/adaptive.py +13 -11
- package/scripts/affected_tests.py +324 -0
- package/scripts/badcase_ledger.py +93 -2
- package/scripts/browser_auth.py +178 -4
- package/scripts/cache.py +68 -69
- package/scripts/check_commit_report.py +59 -9
- package/scripts/chrome_cdp.py +71 -0
- package/scripts/circuit_breaker.py +77 -12
- package/scripts/cli_io.py +8 -3
- package/scripts/config_cache.py +4 -3
- package/scripts/daemon.py +9 -2
- package/scripts/engine_add.py +45 -0
- package/scripts/engine_dispatch.py +27 -47
- package/scripts/engine_failure.py +33 -0
- package/scripts/engine_families.py +1 -0
- package/scripts/engine_fingerprint.py +114 -0
- package/scripts/engine_health.py +130 -0
- package/scripts/engine_states.py +54 -4
- package/scripts/engines.py +2 -0
- package/scripts/engines_base.py +19 -44
- package/scripts/engines_builders_intl.py +20 -94
- package/scripts/engines_builders_search.py +19 -8
- package/scripts/engines_builders_tech.py +16 -16
- package/scripts/engines_fields.py +23 -0
- package/scripts/engines_twitter_cli.py +182 -0
- package/scripts/evidence_grounding.py +182 -0
- package/scripts/fetch_browser.py +25 -10
- 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/gate_manifest_check.py +75 -0
- package/scripts/gen_readme_art.py +264 -0
- 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 +24 -5
- package/scripts/mcp_warm.py +15 -11
- package/scripts/numeric_verify.py +9 -0
- package/scripts/output_transparency.py +10 -0
- package/scripts/pre-commit +65 -8
- package/scripts/query_operators.py +229 -1
- package/scripts/quota.py +19 -37
- package/scripts/release.py +16 -1
- package/scripts/release_check.py +1 -2
- package/scripts/research_gates.py +85 -1
- package/scripts/research_notes.py +52 -5
- package/scripts/retry_policy.py +17 -3
- package/scripts/route_combo.py +21 -4
- 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/source_discovery.py +611 -0
- package/scripts/sync_backends.py +45 -0
- 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/ego-search/README.md +9 -0
- package/sub-skills/ego-search/scripts/ego_search.py +182 -15
- package/sub-skills/ego-search/scripts/pacing.py +291 -0
- package/sub-skills/ego-search/scripts/quality.py +262 -6
- package/sub-skills/ego-search/scripts/runtime.py +7 -1
- package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
- package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
- 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
|
@@ -80,6 +80,15 @@ argo ego-search fetch "https://example.com/article" --focus 关键词
|
|
|
80
80
|
# 同源 API 数据直取(登录态站点接口)
|
|
81
81
|
argo ego-search api "https://www.zhihu.com/api/v4/search_v3?t=general&q=AI代理&limit=5" --origin "https://www.zhihu.com"
|
|
82
82
|
|
|
83
|
+
# 声明式同源 API 预设(zhihu / xueqiu / bilibili / weibo / xiaohongshu)
|
|
84
|
+
argo ego-search api --preset zhihu --query "AI 搜索" --n 8
|
|
85
|
+
|
|
86
|
+
# 清除站点冷却期(人工登录恢复后解除 auth_failed / account_restricted 冷却)
|
|
87
|
+
argo ego-search status --clear-cooldown zhihu.com
|
|
88
|
+
|
|
89
|
+
# 主动体检围墙站账号是否被静默限权(L1 探针:healthy / account_restricted / auth_failed)
|
|
90
|
+
argo ego-search status --check-health xiaohongshu
|
|
91
|
+
|
|
83
92
|
# 指定任务空间名(同一目标的多轮操作复用同名空间)
|
|
84
93
|
argo ego-search search "竞品分析" --task-space "竞品调研"
|
|
85
94
|
```
|
|
@@ -35,9 +35,11 @@ if str(_SCRIPT_DIR) not in sys.path:
|
|
|
35
35
|
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
36
36
|
|
|
37
37
|
import merge as merge_mod # noqa: E402
|
|
38
|
+
import pacing as pacing # noqa: E402
|
|
38
39
|
import quality as quality # noqa: E402
|
|
39
40
|
import runtime as rt # noqa: E402
|
|
40
41
|
import safety as safety # noqa: E402
|
|
42
|
+
import site_profiles as site_profiles # noqa: E402
|
|
41
43
|
import webbridge_adapter as wb # noqa: E402
|
|
42
44
|
|
|
43
45
|
# argo 核心 scripts:query_enhance 归一化(词形规范化,保留平台语法);核心不可用时降级
|
|
@@ -120,11 +122,34 @@ def stamp_login_provenance(payload: dict[str, Any], *, runtime: str | None = Non
|
|
|
120
122
|
|
|
121
123
|
|
|
122
124
|
def emit_json(payload: dict[str, Any], *, runtime: str | None = None) -> None:
|
|
123
|
-
"""stdout 输出已打 provenance + 质量信号的 JSON
|
|
125
|
+
"""stdout 输出已打 provenance + 质量信号的 JSON;登录态判定失效时自动记站点冷却。"""
|
|
124
126
|
p = stamp_login_provenance(payload, runtime=runtime)
|
|
125
|
-
# fetch / act
|
|
126
|
-
if p.get("content") is not None or p.get("detail") is not None:
|
|
127
|
+
# fetch / act / api 挂 quality(登录墙/空页/Cookie 存在性)
|
|
128
|
+
if p.get("content") is not None or p.get("detail") is not None or p.get("api_url"):
|
|
127
129
|
p = quality.assess_body(p)
|
|
130
|
+
q_info = p.get("quality") if isinstance(p.get("quality"), dict) else {}
|
|
131
|
+
auth_state = str(q_info.get("auth_state") or "")
|
|
132
|
+
# 冷却只认登录态判定结论(auth_failed / account_restricted),不认裸的
|
|
133
|
+
# auth_wall_suspected 文本启发式:无画像站正文含 cloudflare/captcha 等
|
|
134
|
+
# 词就记 1h 站点冷却,是误封类同根因的第三分支(2026-11-21 探针 5 实证)。
|
|
135
|
+
# 怀疑但不定论时照常输出 payload,提示语已在 quality.hint 里。
|
|
136
|
+
if auth_state in quality.EGO_AUTH_COOLDOWN_STATES:
|
|
137
|
+
# 冷却键与读取侧 _target_site_key 同源:URL 优先(normalize 后得域名),
|
|
138
|
+
# 画像名只作兜底——旧顺序画像名优先导致写入键(如 xueqiu)与检查键
|
|
139
|
+
# (xueqiu.com)错位,冷却保护时灵时不灵(2026-11-21 审计)。
|
|
140
|
+
site_key = p.get("url") or p.get("api_url") or p.get("page_url") or q_info.get("site")
|
|
141
|
+
cd_secs = 7200 if auth_state == quality.EGO_AUTH_RESTRICTED else pacing.DEFAULT_COOLDOWN_SECONDS
|
|
142
|
+
if site_key:
|
|
143
|
+
try:
|
|
144
|
+
pacing.record_cooldown(
|
|
145
|
+
str(site_key),
|
|
146
|
+
auth_state,
|
|
147
|
+
seconds=cd_secs,
|
|
148
|
+
login_url=str(p.get("login_url") or q_info.get("login_url") or ""),
|
|
149
|
+
)
|
|
150
|
+
except (pacing.SlotBusyError, OSError) as exc:
|
|
151
|
+
# 冷却记账失败不吞结果:抓取已完成,stderr 留痕后照常输出
|
|
152
|
+
log(f"warning: record_cooldown failed ({exc}); result still emitted")
|
|
128
153
|
print(json.dumps(p, ensure_ascii=False, indent=2))
|
|
129
154
|
|
|
130
155
|
|
|
@@ -258,11 +283,17 @@ await openOrReuseTab('%%URL%%', { wait: true, timeout: 25 })
|
|
|
258
283
|
const info = await pageInfo()
|
|
259
284
|
const raw = await js(`%%BODY_IIFE%%`)
|
|
260
285
|
const d = JSON.parse(raw)
|
|
286
|
+
let cookieNames = []
|
|
287
|
+
try {
|
|
288
|
+
const ck = await js(`JSON.stringify((document.cookie || '').split(';').map(s => s.split('=')[0].trim()).filter(Boolean))`)
|
|
289
|
+
cookieNames = JSON.parse(ck)
|
|
290
|
+
} catch (e) {}
|
|
261
291
|
let body = d.content.replace(/\n{3,}/g, '\n\n').trim()
|
|
262
292
|
%%FOCUS_FILTER%%
|
|
263
293
|
cliLog('EGO_RESULT|' + JSON.stringify({
|
|
264
294
|
url: info.url, title: d.title,
|
|
265
295
|
content: body, word_count: body.split(/\s+/).length,
|
|
296
|
+
cookie_names: cookieNames,
|
|
266
297
|
fetch_method: 'browser',
|
|
267
298
|
task_space: '%%TASK_SPACE%%', task_id: task && task.id,
|
|
268
299
|
}))
|
|
@@ -309,12 +340,30 @@ try {
|
|
|
309
340
|
dataType = 'error'
|
|
310
341
|
data = String(e).slice(0, 300)
|
|
311
342
|
}
|
|
343
|
+
let cookieNames = []
|
|
344
|
+
try {
|
|
345
|
+
const ck = await js(`JSON.stringify((document.cookie || '').split(';').map(s => s.split('=')[0].trim()).filter(Boolean))`)
|
|
346
|
+
cookieNames = JSON.parse(ck)
|
|
347
|
+
} catch (e) {}
|
|
348
|
+
let healthProbe = null
|
|
349
|
+
const probeUrl = '%%HEALTH_PROBE_URL%%'
|
|
350
|
+
const looksEmpty = (dataType === 'error' || !data || (typeof data === 'object' && Array.isArray(data.items) && data.items.length === 0))
|
|
351
|
+
if (probeUrl && looksEmpty) {
|
|
352
|
+
try {
|
|
353
|
+
const pr = await browserFetch(probeUrl, {})
|
|
354
|
+
healthProbe = typeof pr === 'string' ? (() => { try { return JSON.parse(pr) } catch (e) { return pr.slice(0, 300) } })() : pr
|
|
355
|
+
} catch (e) {
|
|
356
|
+
healthProbe = String(e).slice(0, 200)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
312
359
|
cliLog('EGO_RESULT|' + JSON.stringify({
|
|
313
360
|
api_url: '%%API_URL%%',
|
|
314
361
|
page_url: info.url,
|
|
315
362
|
page_title: info.title,
|
|
316
363
|
data: data,
|
|
317
364
|
data_type: dataType,
|
|
365
|
+
cookie_names: cookieNames,
|
|
366
|
+
health_probe: healthProbe,
|
|
318
367
|
fetch_method: 'browser_api',
|
|
319
368
|
task_space: '%%TASK_SPACE%%', task_id: task && task.id,
|
|
320
369
|
}))
|
|
@@ -341,6 +390,20 @@ def _require_url(url: str, context: str) -> str:
|
|
|
341
390
|
return v["url"]
|
|
342
391
|
|
|
343
392
|
|
|
393
|
+
def _target_site_key(args: argparse.Namespace) -> str:
|
|
394
|
+
for attr in ("site", "preset", "url", "api_url", "origin"):
|
|
395
|
+
val = getattr(args, attr, None)
|
|
396
|
+
if val:
|
|
397
|
+
return pacing.normalize_site(str(val))
|
|
398
|
+
ts = getattr(args, "task_space", None)
|
|
399
|
+
if ts and str(ts).startswith("site:"):
|
|
400
|
+
return pacing.normalize_site(str(ts))
|
|
401
|
+
eng = getattr(args, "engine", None)
|
|
402
|
+
if eng:
|
|
403
|
+
return pacing.normalize_site(str(eng))
|
|
404
|
+
return "default"
|
|
405
|
+
|
|
406
|
+
|
|
344
407
|
def run_with_fallback(
|
|
345
408
|
args: argparse.Namespace,
|
|
346
409
|
*,
|
|
@@ -348,17 +411,52 @@ def run_with_fallback(
|
|
|
348
411
|
wb_fn,
|
|
349
412
|
label: str,
|
|
350
413
|
) -> tuple[dict[str, Any], str]:
|
|
351
|
-
"""
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
414
|
+
"""统一双运行时:冷却检查 → 跨进程槽位 + 同站节奏锁 → ego 优先 / auto 降级 WebBridge。"""
|
|
415
|
+
site_key = _target_site_key(args)
|
|
416
|
+
cd = pacing.check_cooldown(site_key)
|
|
417
|
+
if cd:
|
|
418
|
+
handoff = quality.build_handoff(
|
|
419
|
+
{"site": cd["site"], "auth_state": cd["reason"], "login_url": cd.get("login_url") or ""},
|
|
420
|
+
url=cd.get("login_url") or cd["site"],
|
|
421
|
+
)
|
|
422
|
+
print(json.dumps(
|
|
423
|
+
stamp_login_provenance({
|
|
424
|
+
"ok": False,
|
|
425
|
+
"cooldown_active": True,
|
|
426
|
+
"handoff_required": True,
|
|
427
|
+
"handoff": handoff,
|
|
428
|
+
"site": cd["site"],
|
|
429
|
+
"reason": cd["reason"],
|
|
430
|
+
"retry_after_seconds": cd["retry_after_seconds"],
|
|
431
|
+
"login_url": cd.get("login_url") or "",
|
|
432
|
+
"hint": (
|
|
433
|
+
f"站点 {cd['site']} 处于冷却期({cd['reason']},剩余 {cd['retry_after_seconds']}s)。"
|
|
434
|
+
f"人工处理后运行 `{handoff['clear_cooldown_cmd']}`,或按 handoff.public_fallback 退回 L0 公开检索。"
|
|
435
|
+
),
|
|
436
|
+
}),
|
|
437
|
+
ensure_ascii=False, indent=2,
|
|
438
|
+
))
|
|
439
|
+
sys.exit(2)
|
|
355
440
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
441
|
+
runtime = _pick_runtime(args)
|
|
442
|
+
try:
|
|
443
|
+
with pacing.browser_slot(site_key) as slot_meta:
|
|
444
|
+
if label in ("search", "act", "api"):
|
|
445
|
+
pacing.pace_site(site_key)
|
|
446
|
+
if runtime == "webbridge":
|
|
447
|
+
res, used = wb_fn(), "webbridge"
|
|
448
|
+
else:
|
|
449
|
+
res = ego_fn()
|
|
450
|
+
used = "ego"
|
|
451
|
+
auto = (getattr(args, "runtime", "auto") or "auto") == "auto"
|
|
452
|
+
if not res.get("ok") and auto and rt.webbridge_available(try_start=True).get("available"):
|
|
453
|
+
log(f"ego 失败,降级 WebBridge ({label}): {res.get('error')}")
|
|
454
|
+
res, used = wb_fn(), "webbridge"
|
|
455
|
+
if isinstance(res, dict) and isinstance(res.get("payload"), dict):
|
|
456
|
+
res["payload"].setdefault("slot_wait_ms", slot_meta["wait_ms"])
|
|
457
|
+
return res, used
|
|
458
|
+
except pacing.SlotBusyError as exc:
|
|
459
|
+
return {"ok": False, "error": f"浏览器并发槽位已满: {exc}"}, runtime
|
|
362
460
|
|
|
363
461
|
|
|
364
462
|
def _search_ego(args: argparse.Namespace) -> dict[str, Any]:
|
|
@@ -566,17 +664,35 @@ def _origin_from_url(url: str) -> str:
|
|
|
566
664
|
|
|
567
665
|
|
|
568
666
|
def cmd_api(args: argparse.Namespace) -> None:
|
|
667
|
+
if getattr(args, "preset", None):
|
|
668
|
+
if not getattr(args, "query", None):
|
|
669
|
+
sys.exit("错误: 使用 --preset 时必须提供 --query")
|
|
670
|
+
try:
|
|
671
|
+
spec = site_profiles.resolve_preset_api(
|
|
672
|
+
args.preset, args.query, n=getattr(args, "n", 10) or 10
|
|
673
|
+
)
|
|
674
|
+
except ValueError as exc:
|
|
675
|
+
sys.exit(f"错误: {exc}")
|
|
676
|
+
args.api_url = spec["api_url"]
|
|
677
|
+
if not args.origin:
|
|
678
|
+
args.origin = spec["origin"]
|
|
679
|
+
if not getattr(args, "site", None):
|
|
680
|
+
args.site = spec["site"]
|
|
681
|
+
elif not getattr(args, "api_url", None):
|
|
682
|
+
sys.exit("错误: 请提供 api_url 或 --preset <site> --query <q>")
|
|
569
683
|
apply_site_space(args)
|
|
570
684
|
args.api_url = _require_url(args.api_url, "api")
|
|
571
685
|
origin = args.origin or _origin_from_url(args.api_url)
|
|
572
686
|
origin = _require_url(origin, "api_origin")
|
|
573
687
|
|
|
574
688
|
def ego_fn():
|
|
689
|
+
prof = site_profiles.match_site(args.api_url) or site_profiles.match_site(origin)
|
|
575
690
|
js = build_js(
|
|
576
691
|
JS_API,
|
|
577
692
|
TASK_SPACE=args.task_space,
|
|
578
693
|
ORIGIN=origin,
|
|
579
694
|
API_URL=args.api_url,
|
|
695
|
+
HEALTH_PROBE_URL=(prof.health_probe_url if prof else ""),
|
|
580
696
|
KEEP_SPACE=_keep_js(args),
|
|
581
697
|
)
|
|
582
698
|
r = run_ego(js, args.timeout)
|
|
@@ -672,7 +788,39 @@ def cmd_disable(args: argparse.Namespace) -> None:
|
|
|
672
788
|
print("专业搜索模式已关闭:登录态专业搜索已禁用。")
|
|
673
789
|
|
|
674
790
|
|
|
791
|
+
def _run_site_health_check(site_name: str, args: argparse.Namespace) -> dict[str, Any]:
|
|
792
|
+
prof = site_profiles.get_profile(site_name) or site_profiles.match_site(site_name)
|
|
793
|
+
if prof is None or not prof.health_probe_url:
|
|
794
|
+
return {"ok": False, "site": site_name, "error": "该站点暂未声明 health_probe_url"}
|
|
795
|
+
if not mode_enabled():
|
|
796
|
+
return {"ok": False, "site": prof.name, "error": "专业搜索模式未开启,请先运行 argo ego-search enable"}
|
|
797
|
+
origin = prof.api_origin or _origin_from_url(prof.health_probe_url)
|
|
798
|
+
js = build_js(
|
|
799
|
+
JS_API, TASK_SPACE=f"site:{prof.domains[0]}", ORIGIN=origin,
|
|
800
|
+
API_URL=prof.health_probe_url, HEALTH_PROBE_URL="", KEEP_SPACE="true",
|
|
801
|
+
)
|
|
802
|
+
r = run_ego(js, DEFAULT_TIMEOUT)
|
|
803
|
+
if not r.get("ok"):
|
|
804
|
+
return {"ok": False, "site": prof.name, "error": r.get("error")}
|
|
805
|
+
verdict = quality.assess_health_probe(r["payload"].get("data"), site=prof.name)
|
|
806
|
+
out = {"ok": verdict.get("auth_state") == "healthy", "site": prof.name, "probe_url": prof.health_probe_url, **verdict}
|
|
807
|
+
if verdict.get("handoff_required"):
|
|
808
|
+
out["handoff"] = quality.build_handoff(verdict, url=prof.login_url)
|
|
809
|
+
return out
|
|
810
|
+
|
|
811
|
+
|
|
675
812
|
def cmd_status(args: argparse.Namespace) -> None:
|
|
813
|
+
check_site = getattr(args, "check_health", None)
|
|
814
|
+
if check_site:
|
|
815
|
+
res = _run_site_health_check(check_site, args)
|
|
816
|
+
print(json.dumps(stamp_login_provenance(res), ensure_ascii=False, indent=2))
|
|
817
|
+
if not res.get("ok"):
|
|
818
|
+
sys.exit(1)
|
|
819
|
+
return
|
|
820
|
+
cleared: list[str] = []
|
|
821
|
+
clear_target = getattr(args, "clear_cooldown", None)
|
|
822
|
+
if clear_target is not None:
|
|
823
|
+
cleared = pacing.clear_cooldown(None if clear_target == "__ALL__" else clear_target)
|
|
676
824
|
try_start = bool(getattr(args, "fix", False))
|
|
677
825
|
runtimes = rt.detect_runtimes(try_start_webbridge=try_start)
|
|
678
826
|
print(json.dumps(
|
|
@@ -680,8 +828,11 @@ def cmd_status(args: argparse.Namespace) -> None:
|
|
|
680
828
|
"pro_mode": mode_enabled(),
|
|
681
829
|
"state_file": STATE_PATH,
|
|
682
830
|
"architecture": "dual_runtime_complete",
|
|
683
|
-
"version": "1.
|
|
831
|
+
"version": "1.7.0",
|
|
684
832
|
"runtimes": runtimes,
|
|
833
|
+
"active_cooldowns": pacing.active_cooldowns(),
|
|
834
|
+
**({"cleared_cooldowns": cleared} if clear_target is not None else {}),
|
|
835
|
+
"api_presets": site_profiles.list_api_presets(),
|
|
685
836
|
"isolation": {
|
|
686
837
|
"public_search_cache": "~/.cache/unified-search/cache.db",
|
|
687
838
|
"login_partition": "cache_eligible=false / SearchCache 硬拒绝",
|
|
@@ -692,6 +843,8 @@ def cmd_status(args: argparse.Namespace) -> None:
|
|
|
692
843
|
"default_close_space": True,
|
|
693
844
|
"keep_space_flag": "--keep-space",
|
|
694
845
|
"site_sticky": "--site example.com → task-space site:example.com + keep",
|
|
846
|
+
"site_slots": pacing.SITE_SLOTS,
|
|
847
|
+
"browser_slots": pacing.BROWSER_SLOTS,
|
|
695
848
|
},
|
|
696
849
|
},
|
|
697
850
|
ensure_ascii=False, indent=2,
|
|
@@ -726,6 +879,14 @@ def main() -> None:
|
|
|
726
879
|
"--fix", action="store_true",
|
|
727
880
|
help="探测前幂等尝试启动 WebBridge 本地桥(永不 stop)",
|
|
728
881
|
)
|
|
882
|
+
p_status.add_argument(
|
|
883
|
+
"--clear-cooldown", nargs="?", const="__ALL__", default=None,
|
|
884
|
+
help="清除站点冷却期(不带参数清全部,或传站点名如 zhihu.com)",
|
|
885
|
+
)
|
|
886
|
+
p_status.add_argument(
|
|
887
|
+
"--check-health", default=None,
|
|
888
|
+
help="主动体检指定围墙站账号是否被静默限权(如 xiaohongshu/zhihu/xueqiu/bilibili)",
|
|
889
|
+
)
|
|
729
890
|
p_status.set_defaults(fn=cmd_status)
|
|
730
891
|
|
|
731
892
|
p_merge = sub.add_parser(
|
|
@@ -768,8 +929,14 @@ def main() -> None:
|
|
|
768
929
|
p_act.set_defaults(fn=cmd_act)
|
|
769
930
|
|
|
770
931
|
p_api = sub.add_parser("api", help="浏览器上下文数据直取(同源 API,继承登录态)")
|
|
771
|
-
p_api.add_argument("api_url", help="API 完整 URL
|
|
932
|
+
p_api.add_argument("api_url", nargs="?", default=None, help="API 完整 URL(与 --preset 二选一)")
|
|
772
933
|
p_api.add_argument("--origin", help="登录态上下文页面 URL(默认取 API URL 同源)")
|
|
934
|
+
p_api.add_argument(
|
|
935
|
+
"--preset", choices=site_profiles.list_api_presets(), default=None,
|
|
936
|
+
help="高频围墙站声明式同源搜索 API 预设(如 zhihu/xueqiu/bilibili/weibo)",
|
|
937
|
+
)
|
|
938
|
+
p_api.add_argument("--query", default=None, help="配合 --preset 使用的搜索词")
|
|
939
|
+
p_api.add_argument("--n", type=int, default=10, help="配合 --preset 使用的条数上限(默认 10)")
|
|
773
940
|
p_api.set_defaults(fn=cmd_api)
|
|
774
941
|
|
|
775
942
|
for p in (p_search, p_fetch, p_act, p_api):
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""ego-search 浏览器通道并发槽位、同站节奏锁与站点级终态冷却期。
|
|
4
|
+
|
|
5
|
+
无守护进程设计(基于 OS 文件锁实现跨进程防风控调度):
|
|
6
|
+
- 并发槽位:基于 OS 文件锁(fcntl.flock / msvcrt.locking),单站最多 SITE_SLOTS=2,
|
|
7
|
+
全局最多 BROWSER_SLOTS=4,防止多 Agent 并发挤爆浏览器或触发平台风控;
|
|
8
|
+
排队耗时单独统计(wait_ms),不扣减单次执行超时预算。
|
|
9
|
+
- 同站节奏锁:同站搜索/API 请求至少间隔 min_interval(默认 8.0s),
|
|
10
|
+
通过站点独占锁串行读写时间戳,避免双进程同时跳过冷却。
|
|
11
|
+
- 站点级终态冷却期:站点返回登录失效/限流/风控拦截时写入冷却记录,
|
|
12
|
+
冷却期内直接返回结构化 handoff_required,阻止 Agent 重试把账号刷封。
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from contextlib import ExitStack, contextmanager
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Iterator
|
|
25
|
+
|
|
26
|
+
SITE_SLOTS = 2
|
|
27
|
+
BROWSER_SLOTS = 4
|
|
28
|
+
DEFAULT_QUEUE_WAIT = 120.0
|
|
29
|
+
DEFAULT_SITE_INTERVAL = 8.0
|
|
30
|
+
DEFAULT_COOLDOWN_SECONDS = 3600
|
|
31
|
+
_POLL_SECONDS = 0.15
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def state_root() -> Path:
|
|
35
|
+
"""调用期解析 ego-search 状态根目录(不放导入期,避免测试 env 切换失配)。"""
|
|
36
|
+
override = os.environ.get("EGO_SEARCH_STATE_DIR", "").strip()
|
|
37
|
+
if override:
|
|
38
|
+
return Path(override).expanduser()
|
|
39
|
+
xdg = os.environ.get("XDG_STATE_HOME", "").strip()
|
|
40
|
+
base = Path(xdg).expanduser() if xdg else (Path.home() / ".local" / "state")
|
|
41
|
+
return base / "ego-search"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def default_site_interval() -> float:
|
|
45
|
+
raw = os.environ.get("EGO_SEARCH_SITE_INTERVAL", "").strip()
|
|
46
|
+
if raw:
|
|
47
|
+
try:
|
|
48
|
+
v = float(raw)
|
|
49
|
+
return max(0.0, v)
|
|
50
|
+
except ValueError:
|
|
51
|
+
return DEFAULT_SITE_INTERVAL
|
|
52
|
+
return DEFAULT_SITE_INTERVAL
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def normalize_site(site: str | None) -> str:
|
|
56
|
+
"""把站点/URL/task_space 归一为稳定主机键(如 zhihu.com)。"""
|
|
57
|
+
if not site:
|
|
58
|
+
return "default"
|
|
59
|
+
s = site.strip().lower()
|
|
60
|
+
if s.startswith("site:"):
|
|
61
|
+
s = s[5:]
|
|
62
|
+
for prefix in ("https://", "http://"):
|
|
63
|
+
if s.startswith(prefix):
|
|
64
|
+
s = s[len(prefix):]
|
|
65
|
+
host = s.split("/", 1)[0].split(":", 1)[0].strip(".")
|
|
66
|
+
if host.startswith("www."):
|
|
67
|
+
host = host[4:]
|
|
68
|
+
return host or "default"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class SlotBusyError(RuntimeError):
|
|
72
|
+
"""槽位排队超时。"""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@contextmanager
|
|
76
|
+
def _try_file_lock(name: str, *, root: Path | None = None) -> Iterator[None]:
|
|
77
|
+
"""非阻塞 OS 文件锁;已被占用时抛 SlotBusyError。"""
|
|
78
|
+
lock_dir = (root or state_root()) / "locks"
|
|
79
|
+
lock_dir.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:24]
|
|
81
|
+
path = lock_dir / f"{digest}.lock"
|
|
82
|
+
with path.open("a+b") as handle:
|
|
83
|
+
if handle.tell() == 0:
|
|
84
|
+
handle.write(b"0")
|
|
85
|
+
handle.flush()
|
|
86
|
+
handle.seek(0)
|
|
87
|
+
try:
|
|
88
|
+
if sys.platform == "win32":
|
|
89
|
+
import msvcrt
|
|
90
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
91
|
+
else:
|
|
92
|
+
import fcntl
|
|
93
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
94
|
+
except OSError as exc:
|
|
95
|
+
raise SlotBusyError(f"slot busy: {name}") from exc
|
|
96
|
+
try:
|
|
97
|
+
yield
|
|
98
|
+
finally:
|
|
99
|
+
try:
|
|
100
|
+
if sys.platform == "win32":
|
|
101
|
+
import msvcrt
|
|
102
|
+
handle.seek(0)
|
|
103
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
104
|
+
else:
|
|
105
|
+
import fcntl
|
|
106
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _acquire_any(
|
|
112
|
+
names: list[str],
|
|
113
|
+
*,
|
|
114
|
+
wait: float,
|
|
115
|
+
root: Path | None = None,
|
|
116
|
+
poll: float = _POLL_SECONDS,
|
|
117
|
+
) -> ExitStack:
|
|
118
|
+
deadline = time.monotonic() + max(0.0, wait)
|
|
119
|
+
while True:
|
|
120
|
+
for name in names:
|
|
121
|
+
stack = ExitStack()
|
|
122
|
+
try:
|
|
123
|
+
stack.enter_context(_try_file_lock(name, root=root))
|
|
124
|
+
return stack
|
|
125
|
+
except SlotBusyError:
|
|
126
|
+
stack.close()
|
|
127
|
+
if time.monotonic() >= deadline:
|
|
128
|
+
raise SlotBusyError(f"waited >{wait:.1f}s for slots {names[0]}..")
|
|
129
|
+
time.sleep(min(poll, max(0.01, deadline - time.monotonic())))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@contextmanager
|
|
133
|
+
def browser_slot(
|
|
134
|
+
site: str,
|
|
135
|
+
*,
|
|
136
|
+
wait: float = DEFAULT_QUEUE_WAIT,
|
|
137
|
+
site_slots: int = SITE_SLOTS,
|
|
138
|
+
browser_slots: int = BROWSER_SLOTS,
|
|
139
|
+
root: Path | None = None,
|
|
140
|
+
) -> Iterator[dict[str, Any]]:
|
|
141
|
+
"""占领单站 + 全局浏览器槽位,yield 排队统计(wait_ms)。"""
|
|
142
|
+
norm = normalize_site(site)
|
|
143
|
+
started = time.monotonic()
|
|
144
|
+
with ExitStack() as stack:
|
|
145
|
+
stack.enter_context(
|
|
146
|
+
_acquire_any(
|
|
147
|
+
[f"site:{norm}:{i}" for i in range(max(1, site_slots))],
|
|
148
|
+
wait=wait,
|
|
149
|
+
root=root,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
remain = max(0.0, wait - (time.monotonic() - started))
|
|
153
|
+
stack.enter_context(
|
|
154
|
+
_acquire_any(
|
|
155
|
+
[f"browser:slot:{i}" for i in range(max(1, browser_slots))],
|
|
156
|
+
wait=remain,
|
|
157
|
+
root=root,
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
yield {"site": norm, "wait_ms": int((time.monotonic() - started) * 1000)}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _pacing_path(root: Path | None = None) -> Path:
|
|
164
|
+
return (root or state_root()) / "pacing_state.json"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _load_json(path: Path) -> dict[str, Any]:
|
|
168
|
+
try:
|
|
169
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
170
|
+
except (FileNotFoundError, json.JSONDecodeError, OSError):
|
|
171
|
+
return {}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
|
|
175
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
# tmp 名带线程号:同进程两线程并发写同一文件时旧名(仅 pid)会互踩
|
|
177
|
+
# os.replace 抛 FileNotFoundError(2026-11-21 审计)
|
|
178
|
+
tmp = path.with_suffix(path.suffix + f".tmp.{os.getpid()}.{threading.get_ident()}")
|
|
179
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
180
|
+
os.replace(tmp, path)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def pace_site(
|
|
184
|
+
site: str,
|
|
185
|
+
*,
|
|
186
|
+
min_interval: float | None = None,
|
|
187
|
+
root: Path | None = None,
|
|
188
|
+
) -> float:
|
|
189
|
+
"""保证同站两次请求至少间隔 min_interval 秒,返回实际等待秒数。"""
|
|
190
|
+
interval = default_site_interval() if min_interval is None else max(0.0, float(min_interval))
|
|
191
|
+
if interval <= 0:
|
|
192
|
+
return 0.0
|
|
193
|
+
norm = normalize_site(site)
|
|
194
|
+
path = _pacing_path(root)
|
|
195
|
+
# 写侧锁名统一为 pacing:state:同一状态文件只允许一把写锁——旧 pace:{site}
|
|
196
|
+
# 与 record_cooldown 的 pacing:state 是两把名字不同的锁,跨进程并发时后写者
|
|
197
|
+
# 会整体覆盖前写者(丢冷却记录或节奏时间戳,2026-11-21 审计)。本锁内
|
|
198
|
+
# sleep 至多一个 interval(默认 8s),短于 record_cooldown 的 15s 等待预算。
|
|
199
|
+
with _acquire_any(["pacing:state"], wait=DEFAULT_QUEUE_WAIT, root=root):
|
|
200
|
+
data = _load_json(path)
|
|
201
|
+
starts = data.setdefault("request_starts", {})
|
|
202
|
+
last = starts.get(norm)
|
|
203
|
+
waited = 0.0
|
|
204
|
+
if isinstance(last, (int, float)):
|
|
205
|
+
gap = interval - max(0.0, time.time() - float(last))
|
|
206
|
+
if gap > 0:
|
|
207
|
+
time.sleep(gap)
|
|
208
|
+
waited = gap
|
|
209
|
+
starts[norm] = time.time()
|
|
210
|
+
_atomic_write_json(path, data)
|
|
211
|
+
return waited
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def check_cooldown(site: str, *, root: Path | None = None) -> dict[str, Any] | None:
|
|
215
|
+
"""检查站点是否处于终态冷却期;未冷却返回 None。"""
|
|
216
|
+
norm = normalize_site(site)
|
|
217
|
+
data = _load_json(_pacing_path(root))
|
|
218
|
+
entry = (data.get("cooldowns") or {}).get(norm)
|
|
219
|
+
if not isinstance(entry, dict):
|
|
220
|
+
return None
|
|
221
|
+
until = float(entry.get("until") or 0)
|
|
222
|
+
remain = int(until - time.time())
|
|
223
|
+
if remain <= 0:
|
|
224
|
+
return None
|
|
225
|
+
return {
|
|
226
|
+
"site": norm,
|
|
227
|
+
"reason": str(entry.get("reason") or "cooldown"),
|
|
228
|
+
"retry_after_seconds": max(1, remain),
|
|
229
|
+
"login_url": entry.get("login_url") or "",
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def record_cooldown(
|
|
234
|
+
site: str,
|
|
235
|
+
reason: str,
|
|
236
|
+
*,
|
|
237
|
+
seconds: int = DEFAULT_COOLDOWN_SECONDS,
|
|
238
|
+
login_url: str = "",
|
|
239
|
+
root: Path | None = None,
|
|
240
|
+
) -> dict[str, Any]:
|
|
241
|
+
"""写入站点级终态冷却期(登录失效/限流/风控拦截),防 Agent 重试刷封。"""
|
|
242
|
+
norm = normalize_site(site)
|
|
243
|
+
path = _pacing_path(root)
|
|
244
|
+
now = time.time()
|
|
245
|
+
entry = {
|
|
246
|
+
"reason": reason,
|
|
247
|
+
"at": now,
|
|
248
|
+
"until": now + max(1, int(seconds)),
|
|
249
|
+
"login_url": login_url,
|
|
250
|
+
}
|
|
251
|
+
with _acquire_any(["pacing:state"], wait=15.0, root=root):
|
|
252
|
+
data = _load_json(path)
|
|
253
|
+
data.setdefault("cooldowns", {})[norm] = entry
|
|
254
|
+
_atomic_write_json(path, data)
|
|
255
|
+
return {"site": norm, **entry}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def clear_cooldown(site: str | None = None, *, root: Path | None = None) -> list[str]:
|
|
259
|
+
"""清除指定站点(或全部站点)冷却记录,返回被清除的站点列表。"""
|
|
260
|
+
path = _pacing_path(root)
|
|
261
|
+
with _acquire_any(["pacing:state"], wait=15.0, root=root):
|
|
262
|
+
data = _load_json(path)
|
|
263
|
+
cds = data.get("cooldowns") or {}
|
|
264
|
+
if site is None:
|
|
265
|
+
cleared = sorted(cds.keys())
|
|
266
|
+
data["cooldowns"] = {}
|
|
267
|
+
else:
|
|
268
|
+
norm = normalize_site(site)
|
|
269
|
+
cleared = [norm] if norm in cds else []
|
|
270
|
+
cds.pop(norm, None)
|
|
271
|
+
data["cooldowns"] = cds
|
|
272
|
+
_atomic_write_json(path, data)
|
|
273
|
+
return cleared
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def active_cooldowns(*, root: Path | None = None) -> dict[str, dict[str, Any]]:
|
|
277
|
+
"""列出当前所有仍在生效的站点冷却记录(只读,供 status 展示)。"""
|
|
278
|
+
now = time.time()
|
|
279
|
+
data = _load_json(_pacing_path(root))
|
|
280
|
+
out: dict[str, dict[str, Any]] = {}
|
|
281
|
+
for site, entry in (data.get("cooldowns") or {}).items():
|
|
282
|
+
if not isinstance(entry, dict):
|
|
283
|
+
continue
|
|
284
|
+
remain = int(float(entry.get("until") or 0) - now)
|
|
285
|
+
if remain > 0:
|
|
286
|
+
out[site] = {
|
|
287
|
+
"reason": entry.get("reason") or "cooldown",
|
|
288
|
+
"retry_after_seconds": remain,
|
|
289
|
+
"login_url": entry.get("login_url") or "",
|
|
290
|
+
}
|
|
291
|
+
return out
|