argo
Argo 阿尔戈 — 统一搜索、网页抓取与证据核验。当需要搜索/查一下/核实/抓取网页/爬取/深度研究/论文检索/新闻/舆情/公众号文章/招聘聚合时使用;支持影视/体育/金融/宏观/学术等垂直域与多语言查询。
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/taxueseek/argo with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/taxueseek/argo'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/taxueseek--argo)HTML
<a href="/listings/taxueseek--argo"><img src="/api/listings/taxueseek--argo/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
Zero-config works out of the box (API keys are optional). Pick your client:
- **Claude Code (MCP)**:
claude mcp add argo -- npx -y argo-search
- **Agent Skill (`skills.sh` — Claude Code, Cursor, Codex, Antigravity)**:
npx skills add taxueseek/argo # Or install all scenario skills (argo, argo-deep-research, argo-local-search): npx skills add taxueseek/argo --full-depth --all
- **Cursor / Windsurf / LibreChat (`mcpServers` JSON)**:
{
"mcpServers": {
"argo": { "command": "npx", "args": ["-y", "argo-search"] }
}
}- **Local CLI (recommended for long-term local use)**:
curl -fsSL https://raw.githubusercontent.com/taxueseek/argo/main/scripts/install.sh | bash # Windows (PowerShell): irm https://raw.githubusercontent.com/taxueseek/argo/main/scripts/install.ps1 | iex # or via npm: npm install -g argo-search
- **DeepSeek Harness (DSH) Plugin**:
dsh plugin --profile web add argo-search
<details> <summary>Verify installation, requirements & optional API keys</summary>
argo search "python asyncio error handling" --verify 2 --json --fields agent argo search --list-engines
- Requires **Python 3.9+** (`pip install pyyaml`) and **Node.js 18+** (for `npx`). - Optional keys (`DEEPSEEK_API_KEY`, `ARGO_YUANBAO_API_KEY`, `ARGO_TAVILY_API_KEY`, `EXA_API_KEY`, `ARGO_METASO_API_KEY`, `ARGO_BOCHA_API_KEY`) improve quality when present and are skipped automatically when missing. See [docs/MCP_SETUP.md](docs/MCP_SETUP.md) and [docs/ENGINE_CATALOG.md](docs/ENGINE_CATALOG.md).
</details>
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 136 lines
- ---
- name: argo
- description: Argo 阿尔戈 — 统一搜索、网页抓取与证据核验。当需要搜索/查一下/核实/抓取网页/爬取/深度研究/论文检索/新闻/舆情/公众号文章/招聘聚合时使用;支持影视/体育/金融/宏观/学术等垂直域与多语言查询。
- version: 2.15.0
- triggers:
- - 搜索
- - 查一下
- - 搜一下
- - 核实
- - 查证
- - 可信度
- - 抓取
- - 爬取
- - 深度研究
- - 论文
- - 舆情
- - 公众号
- - 招聘
- - search for
- - look up
- - fact check
- - fetch
- - crawl
- - research
- ---
- # Argo — 统一搜索与证据核验
- > 不止搜到,还要核到:高后果问题标 `fetch_required`、结果标 `fetch_suggested`,`--verify` 核验正文并回填证据分。源数见 docs/ENGINE_CATALOG.md;digup 默认关;deepseek_search 默认开、需 DEEPSEEK_API_KEY(按次计费,无 key 跳过)。
- ## 快速上手
- ```bash
- argo search "查询词" # 自动路由搜索(daemon 需显式启动)
- argo search "查询词" --json --fields agent # Agent 消费档
- argo search "查询词" --verify 3 # 核验 top-3 并回填证据分
- python3 scripts/research.py "复杂问题" --json # 取证包(扩词或多工作包 → dossier)
- ```
- 默认不附 candidates/sources;`--fields agent` 只留答案(~4.3 KB),要追溯或归档才加 `--envelope`(`--archive` 自动带)。
- 深度研究产出**取证包(dossier)**(来源/覆盖/缺口/达标,不是判断稿):先读 `references/research-protocol.md` 写工作包再取证,判断分事实/推断/建议。不要另装「专业深度研究」skill。
- 研究笔记归档(判断稿一等公民化):`argo note study|explore|list`,`research` 存证据、`note` 存结论。用法见 `references/usage.md`。
- ## 核心命令
- ### search — 统一搜索
- | 参数 | 说明 |
- |------|------|
- | `--engine <name>` | 强制引擎(见 `argo list-engines`) |
- | `--local-first` | 本地零成本聚合优先(local_search 子技能) |
- | `--include-local` / `--no-local` | 本机文件命中(fast/budget 默认开) |
- | `--mode fast|auto|deep|budget` | fast 免费 / auto 成本感知(默认)/ deep 质量 / budget 配额 |
- | `--explain` / `--no-cache` | 解释路由决策 / 跳过缓存 |
- | `--depth fast|balanced|deep` | 搜索深度 |
- | `--academic-deep` | 学术多源:depth=deep + domain=academic,禁用早停 |
- | `--since 7d|2026-08-01` `--until` `--sort relevance|newest|oldest` | 时间窗过滤 + 时间排序 |
- | `--video` `--min-duration SEC` `--max-duration SEC` | 视频模式(B 站 + YouTube)及时长筛选 |
- | `--verify [N]` | 对 top-N 抓正文回填证据分 |
- | `--numverify [N]` `--verify-with <引擎>` | 数值印证(对关键数字抓原文确认核对簇)+ 核对配对 |
- | `--domain` `--sub_domain` / `ARGO_USAGE_LOG=0` | 垂直域限定 / 关本地统计与查询落盘 |
- **按场景选引擎**:时事 → `--engine deepseek_search`,学术 → `--academic-deep`/exa,社交 → anysearch,技能/插件目录 → skill_search/dsh_plugin_search。口径见 `references/usage.md`。
- **explicit_only 源不进自动路由**:feed、deepseek_search、tracemoe/saucenao/google_lens/animetrace、wolframalpha、brave/ecosia/qwant/gdelt 等需显式 `--engine <名>`(例:`argo search "x" --engine deepseek_search`),全量见 `argo list-engines`。
- ### 图片检索
- 网络图走 `search`(`image_search` 域自动命中);本地素材走 `argo local-image`(Vision 索引/相似图/联络表;默认关,需 `ARGO_LOCAL_IMAGE=1`,见 `references/usage.md`)。反搜图(图→出处):`argo search "<图片URL>" --engine saucenao|animetrace|google_lens|tracemoe`,不进自动路由,saucenao/google_lens 需 key。
- ### 增强三工具
- ```bash
- # research — 取证(扩词或 --work-packages → 取证包 + 引用 + 达标检查)
- # 工作包可带 file_inputs / recompute(默认拒绝,需显式授权)
- # 社交舆情:--mode social-sentiment --platforms xiaohongshu,reddit,twitter
- python3 scripts/research.py "查询" [--work-packages PATH|JSON] [--depth deep] [--json] [--verify N]
- # evidence — 可信度评估(选拔×吸收两维)
- echo '{"results": [...]}' | python3 scripts/evidence.py "查询词" --stdin --json [--high-stakes]
- # clarify — 意图消歧
- python3 scripts/clarify.py "有歧义的查询" --json
- ```
- ### 抓取族(`bin/argo` 入口)
- ```bash
- argo fetch "https://example.com" [--focus "关键词"] [--use-browser]
- # 降级链见 references/usage.md
- argo screenshot "https://example.com" [--full-page]
- argo pdf "https://example.com/paper.pdf" [--pages "1-5"] [--password "secret"]
- argo paper "1706.03762" # 论文深读
- argo tweet "<x-url|id>" # X 帖子打包(正文+串/引用/转发+媒体)
- argo answer "query" [--scope <语料>] # 直答(语料见 usage.md)
- argo watch add|check|list|remove # 观察模式(--json 供 cron)
- argo ego-search status|search|fetch|merge # 登录态专业搜索(需先 enable)
- ```
- ## Agent 执行纪律
- 1. **高后果问题**(金融/医疗/法律/事实核查):search → evidence(或看 `credibility_fast`)→ fetch 高分 URL → 再下结论;`fetch_required=true` 时禁止跳过核验
- 2. **数字**:必须标注算法(全市场/主动/持仓市值 vs 占比);冲突时并列;关键财务/价格/指标推荐带 `--numverify` 抓原文印证
- 3. **SERP 链**(baidu/s、sogou/link):禁止当正文来源
- 4. **社交帖**:叙事/舆情,不进事实真值
- 5. **深度研究**:先读 `references/research-protocol.md`;有决策含义就交工作包,不要靠扩词充问题树;`quality_gate_results.passed=false` 必须降级表述
- 6. **引用**:讲给用户的事实带 URL 出处,日常档也要带(URL 在 `results[].url`,零成本)
- 7. **上下文纪律**:Agent 用 `--json --fields agent`、按需 `-n`;追溯/归档才加 `--envelope`;引擎状态用 `argo list-engines --detail --engine <名>`(~0.9 KB)。踩坑见 Gotchas
- ## Gotchas
- - **`--envelope` 与 `--fields agent` 别同给**:后者把 envelope 增量剥成 0 字节;要 provenance 就去掉 `--fields agent`。
- - **结果异常少**:看 `funnel` 六格阶段计数,哪格归零即塌陷点。
- - **慢查询**:看 `timing.dispatch` 的 `tail_wait_ms` / `abandoned_engine_ms`。
- - **引擎列表**:别加 `--all`(~54 KB)。
- - **缺密钥**:`argo settings list/set/unset`(set 值走 stdin)。
- - `-n` 超 10 无收益。
- ## 按需读取(低频操作细节)
- | 场景 | 读什么 |
- |------|--------|
- | MCP / DSH 插件 / 配额 / 工程纪律 | `references/operations.md` |
- | **使用指南**:全命令、参数、开关总表、输出体积陷阱 | `references/usage.md` |
- | 深度研究协议:约定、工作包、取证包 vs 判断稿 | `references/research-protocol.md` |
- | 约定 / 工作包 / 判断稿模板 | `references/research-templates.md` |
- | X 关键词搜索与查询模板 | `references/query-templates.md` |
- | 引擎全景:垂直域/社交/学术/本地引擎表 + 路由规则 | `references/engines.md` |
- | 学术检索:查询构造、相关性五因子排序、证据分级 | `references/academic-query.md` |
- | 架构:文件结构、证据流水线、输出 JSON Schema | `references/architecture.md` |
- | **搜索源使用文档**:全量清单 + 特别能力 | `docs/ENGINE_CATALOG.md`(生成,勿手改) |
- > 工程纪律(每个事实只定义一处)见 `references/operations.md` 末尾。
README.md · README · 231 lines · 2 findings marked
- <p align="center">
- <img src="assets/readme/hero.svg" width="100%" alt="Argo: unified search and evidence verification for AI agents across hundreds of sources and 18 languages">
- </p>
- <p align="center">
- <strong>English</strong> ·
- <a href="README.zh.md">中文</a> ·
- <a href="README.ja.md">日本語</a> ·
- <a href="README.ko.md">한국어</a> ·
- <a href="README.es.md">Español</a>
- </p>
- <p align="center">
- <a href="#quick-start">Quick Start</a> ·
- <a href="#why-argo">Why Argo</a> ·
- <a href="#query-shaped-routing">Routing Proof</a> ·
- <a href="#how-it-works">How It Works</a> ·
- <a href="#ai-search--sub-skills">AI Search & Sub-skills</a> ·
- <a href="#dsh-plugin">DSH Plugin</a> ·
- <a href="#docs--changelog">Docs</a>
- </p>
- <p align="center">
- <a href="https://github.com/taxueseek/argo/stargazers"><img alt="stars" src="https://img.shields.io/github/stars/taxueseek/argo?style=social"></a>
- <a href="https://www.npmjs.com/package/argo-search"><img alt="npm downloads" src="https://img.shields.io/npm/dm/argo-search?color=cb3837&label=npm%20downloads"></a>
- <a href="https://skills.sh/taxueseek/argo"><img alt="skills.sh" src="https://img.shields.io/badge/skills.sh-argo-black"></a>
- <img alt="license" src="https://img.shields.io/badge/license-Apache_2.0-blue">
- <img alt="python" src="https://img.shields.io/badge/python-3.9+-green">
- <img alt="version" src="https://img.shields.io/badge/version-2.15.0-informational">
- <img alt="engines" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Ftaxueseek%2Fargo%2Fmain%2Fassets%2Freadme%2Fcounts.json">
- <img alt="mcp" src="https://img.shields.io/badge/MCP-19%20tools-purple">
- </p>
- > **Part of the taxueseek skill series** (search & deep research): [plainspoken-writing](https://github.com/taxueseek/plainspoken-writing) 75★ (AI-tone removal) · [session-digger](https://github.com/taxueseek/session-digger) 34★ (cross-environment session mining) · [taxue-invest](https://github.com/taxueseek/taxue-invest) 30★ (investment analysis) · [taxueskills](https://github.com/taxueseek/taxueskills) 25★ (decision system) · [taxue-creative-style](https://github.com/taxueseek/taxue-creative-style) 19★ (creative illustration styles) · [ime-lexicon](https://github.com/taxueseek/ime-lexicon) 15★ (IME lexicon toolkit).
- >
- > **DeepSeek Harness (DSH) plugin ecosystem**: [dsh-files](https://github.com/taxueseek/dsh-files) 43★ (folder upload + document parsing) · [plugin-fast-adapt](https://github.com/taxueseek/plugin-fast-adapt) 15★ (plugin upgrade adapter) · [taxue-dsh-artisan](https://github.com/taxueseek/taxue-dsh-artisan) 3★ (visual creation) · [dsh-plugin-guard](https://github.com/taxueseek/dsh-plugin-guard) 2★ (pre-install audit).
- **Argo** is an open-source metasearch, web-fetch, and evidence-verification engine that lives inside your AI agent. It routes queries across **hundreds of sources** in **18 languages** (web, academic, finance, code, local files, and leading **AI search engines**), falls back to **keyless & local engines** when API keys are absent, and verifies facts from full page text instead of trusting search snippets.
- ---
- ## Quick Start
- Zero-config works out of the box (API keys are optional). Pick your client:
- - **Claude Code (MCP)**:
- ```bash
- claude mcp add argo -- npx -y argo-search
- ```
- - **Agent Skill (`skills.sh` — Claude Code, Cursor, Codex, Antigravity)**:
- ```bash
- npx skills add taxueseek/argo
- # Or install all scenario skills (argo, argo-deep-research, argo-local-search):
- npx skills add taxueseek/argo --full-depth --all
- ```
- - **Cursor / Windsurf / LibreChat (`mcpServers` JSON)**:
- ```json
- {
- "mcpServers": {
- "argo": { "command": "npx", "args": ["-y", "argo-search"] }
- }
- }
- ```
- - **Local CLI (recommended for long-term local use)**:
- ```bash
- curl -fsSL https://raw.githubusercontent.com/taxueseek/argo/main/scripts/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 66 on GitHub
- # Windows (PowerShell): irm https://raw.githubusercontent.com/taxueseek/argo/main/scripts/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 67 on GitHub
- # or via npm: npm install -g argo-search
- ```
- - **DeepSeek Harness (DSH) Plugin**:
- ```bash
- dsh plugin --profile web add argo-search
- ```
- <details>
- <summary>Verify installation, requirements & optional API keys</summary>
- ```bash
- argo search "python asyncio error handling" --verify 2 --json --fields agent
- argo search --list-engines
- ```
- - Requires **Python 3.9+** (`pip install pyyaml`) and **Node.js 18+** (for `npx`).
- - Optional keys (`DEEPSEEK_API_KEY`, `ARGO_YUANBAO_API_KEY`, `ARGO_TAVILY_API_KEY`, `EXA_API_KEY`, `ARGO_METASO_API_KEY`, `ARGO_BOCHA_API_KEY`) improve quality when present and are skipped automatically when missing. See [docs/MCP_SETUP.md](docs/MCP_SETUP.md) and [docs/ENGINE_CATALOG.md](docs/ENGINE_CATALOG.md).
- </details>
- ---
- ## Why Argo
- <p align="center">
- <img src="assets/readme/why-better.svg" width="100%" alt="Why Argo outperforms built-in search, single AI search APIs, and generic metasearch">
- </p>
- | Capability | Built-in Web Search | Commercial Search APIs (Tavily / Exa / Serper) | Argo |
- | :--- | :--- | :--- | :--- |
- | **Pricing & Keys** | Tied to host quota | Paid per call; API key required | **Free & keyless fallback** (optional keys boost quality) |
- | **AI Search Aggregation** | Single host backend | Single vendor index | **Unifies keyless (`tavily_free`, `parallel_free`, `anysearch`) + BYOK (DeepSeek Search, Tencent Yuanbao/Hunyuan, Metaso, Bocha, Tavily, Exa)** |
- | **Source Routing** | Single generic index | Generic web index | **Domain + 18-language routing** across academic, finance, code, news & local files |
- | **Fact Verification** | Snippet only | Snippet or raw chunks | **Built-in `--verify` & `--numverify`** (fetches source & scores credibility) |
- | **Context Efficiency** | Verbose HTML/JSON | Raw chunks | **Agent-compact output** (`--fields agent` ~4.3 KB) |
- ---
- ## Query-Shaped Routing
- <p align="center">
- <img src="assets/readme/proof-routes.svg" width="100%" alt="Argo query-shaped routing across finance, academic, code, and general domains">
- </p>
- Argo classifies each query by **domain and language** before dispatching, hitting first-party sources directly and triggering **early-stop** once consensus is reached:
- - **Academic** → `arxiv`, `semantic_scholar`, `openalex`, `crossref`, `pubmed` (`--academic-deep`)
- - **Finance & Macro** → `sec_edgar`, `yahoo_finance`, `sina_quote`, `eastmoney`
- - **Code & Tech** → `stackoverflow`, `github`, `octen`, `context7`
- - **AI Search** → `tavily_free`, `parallel_free`, `anysearch`, `deepseek_search`, `yuanbao`, `metaso`, `bocha`, `exa`, `tavily`, `you`
- - **Deep Research** → `python3 scripts/research.py "topic" --depth deep --json` outputs a structured **dossier** (sources, coverage gaps, quality gates)
- ---
- ## How It Works
- <p align="center">
- <img src="assets/readme/workflow.svg" width="100%" alt="Argo retrieval, RRF fusion, fetch degradation chain, and evidence scoring pipeline">
- </p>
- ### Evidence Scoring (Selection × Absorption)
- Search engines optimize for clicks; agents need **verifiable facts**. Argo scores every candidate along two orthogonal axes:
- - **Selection**: domain authority, consensus across engines (`RRF`), freshness, and SERP-shell rejection (blocks `baidu/s` and `sogou/link` redirect stubs from posing as primary sources).
- - **Absorption**: actual readable density after fetching the full page (`--verify N`) and numerical cross-checking (`--numverify N` for prices, financials, and dates).
- ### Budget Modes (`--mode`)
- | Mode | Behavior | Best for |
- | :--- | :--- | :--- |
- | **`fast`** | Free + local `local_*` engines only, zero API spend | High-frequency agent lookups |
- | **`auto`** | Cost-aware default: free first, escalates to keyed sources when needed | Daily coding & general research |
- | **`deep`** | Broad multi-source fan-out, disables early-stop, pairs with `--verify` | High-stakes finance, legal, academic dossiers |
- | **`budget`** | Strict daily/monthly quota caps with local fallback | Unattended batch & cron workflows |
- ---
- ## AI Search & Sub-skills
- ### Sub-skills (7, Single Directory)
- All sub-skills live in `sub-skills/`. Four are built-in pipelines driven by the main skill; three are standalone entry points (wide research orchestration, and two scenario bundles for deep research / zero-cost local search).
- | Sub-skill | Capability |
- | :--- | :--- |
- | **local-search** | Local file search + 32 zero-cost local aggregation engines (`--local-first`) |
- | **local-seek** | Hybrid BM25 + vector semantic search for local notes, markdown, and knowledge bases |
- | **ego-search** | Real-browser logged-in search for Zhihu, Xiaohongshu, WeChat Official Accounts (off by default) |
- | **js-run** | Sub-millisecond headless JS execution for environment probes and pure-compute pages |
- | **argo-wide-research** | Multi-track parallel deep research & forensics orchestration with citation ledger and quality gates |
- | **argo-deep-research** | Scenario entry: research dossier + multi-source fact/number verification (`research.py`, `evidence.py`, `--verify`) |
- | **argo-local-search** | Scenario entry: zero-cost keyless search bundle (`--local-first`, `seek.py`, `--include-local`) |
- ### 19 MCP Tools
- `argo_search`, `argo_local_search`, `argo_local_read`, `argo_recompute`, `argo_research`, `argo_evidence`, `argo_clarify`, `argo_fetch`, `argo_crawl`, `argo_screenshot`, `argo_pdf`, `argo_social_search`, `argo_article`, `argo_job`, `argo_extract`, `argo_preflight`, `argo_answer`, `argo_watch`, `argo_cite`.
- ---
- ## DSH Plugin
- Argo ships a first-class **DeepSeek Harness (DSH)** plugin (`@taxueseek/argo-dsh`) with three invocation channels from one capability set:
- 1. **19 `mcp__argo__*` tools** (full MCP bundle; default MCP surface exposes 4 core tools, set `ARGO_MCP_TOOLS=all` for all 19).
- 2. **Search + `wide_research` parallel orchestration** (subpackage).
- 3. **Host `web_search` / `web_fetch` seam replacement** (requires explicit provider pin in the web profile; see [packages/dsh-plugin/README.md](packages/dsh-plugin/README.md)).
- The built-in settings UI exposes **18 native first-class tools**, **35 behaviour switches**, and shares DSH's native `DEEPSEEK_API_KEY` credential store with zero plaintext echoing:
- <p align="center">
- <img src="assets/readme/settings-tools.webp" width="32%" alt="DSH Tools settings tab">
- <img src="assets/readme/settings-engines.webp" width="32%" alt="DSH Engines settings tab">
- <img src="assets/readme/settings-keys.webp" width="32%" alt="DSH Keys settings tab">
- </p>
- ---
- ## Docs & Changelog
- - [docs/ENGINE_CATALOG.md](docs/ENGINE_CATALOG.md) · [docs/MCP_SETUP.md](docs/MCP_SETUP.md) · [docs/ARGO_INTRO.md](docs/ARGO_INTRO.md) · [docs/为什么选择argo.md](docs/为什么选择argo.md) · [docs/CHANGELOG.md](docs/CHANGELOG.md)
- | Version | Highlights |
- | :--- | :--- |
- | **v2.15.0** | Zhihu full chain, evidence-layer authority passthrough, keyless 3-tier semantic fallback, MCP generic connector (`type: mcp`), route zero-based domain scoring, 311 sources |
- | **v2.14.1** | Architecture slimming, MCP 3+1 orthogonal tools + backward-compat aliases, 304 sources, fail-closed `secret_guard.py` redaction |
- | **v2.14.0** | Parser layer consolidation, 300 sources, badcase ledger loop |
- | **v2.13.0** | Documentation consolidation, 22-state-machine SSOT, dispatch tail grace |
- <details>
- <summary>v2.15.0 Release Summary & Capability Snapshot</summary>
- ### Capabilities (v2.15.0)
- v2.15.0 delivers the Zhihu full chain (question drill-down, curated answers, Keychain credentials, vote-quality weighting), evidence-layer `upstream_authority` passthrough, a keyless 3-tier semantic fallback (local 2-gram heuristics), the single-file research-report pipeline, route zero-based domain scoring, and the MCP generic connector (`type: mcp`, first integration grep.app). Sources 304→311, domains 306→313.
- ### v2.15.0: Zhihu Full Chain + Evidence Authority Passthrough + MCP Connector
- See [docs/RELEASE_NOTES_v2.15.0.md](docs/RELEASE_NOTES_v2.15.0.md) and [docs/CHANGELOG.md](docs/CHANGELOG.md).
- ### v2.14.1: Architecture Slimming + MCP 3+1 Tools + Security Redaction
- See [docs/RELEASE_NOTES_v2.14.1.md](docs/RELEASE_NOTES_v2.14.1.md) and [docs/CHANGELOG.md](docs/CHANGELOG.md).
- </details>
- ---
- > Good search is not about seeing more—it is about concluding with confidence, and knowing when you still should not.
- <p align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)"
- srcset="https://api.star-history.com/svg?repos=taxueseek/argo&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)"
- srcset="https://api.star-history.com/svg?repos=taxueseek/argo&type=Date" />
- <img alt="Star History Chart" width="560"
- src="https://api.star-history.com/svg?repos=taxueseek/argo&type=Date" />
- </picture>
- </p>
- If Argo has ever helped you reach a more confident conclusion, [give it a Star](https://github.com/taxueseek/argo/stargazers) to help more people find it.
- ## Contributing & License
- Issues and PRs are welcome (see [docs/ADDING_NEW_ENGINE.md](docs/ADDING_NEW_ENGINE.md) to add a source). Licensed under [Apache-2.0](LICENSE).
scripts/daemon.py · Bundled script · 970 lines · 3 findings marked
- #!/usr/bin/env python3
- """daemon.py — argo 常驻进程:把每次 CLI 调用的固定成本变成本次 UDS 往返。
- 背景(2026-10-11 实测,见仓库外分析底稿):一次 web 搜索 ~800ms 里,
- dispatch(引擎网络等待)占 97%;真正的 Python 计算只有几十毫秒。但**每次
- CLI 调用都要重付一遍「解释器启动 + 重模块 import」约 85–100ms**——engines
- 全家(builders/urllib/http)26ms、search_entry 9.9ms、recovery 2.8ms……
- agent 循环里一次研究任务调 15–20 次 argo,这笔固定成本就放大成 1.5–2s。
- 对照 OpenAI Habitat(Python→Rust)案例的结论是:argo 的可省成本来自
- 「每次调用的固定开销」,不是 Python 语言本身——所以正解是常驻进程把
- import 付一次,而不是重写语言。收益相同,成本差两个数量级。
- 设计:
- - 协议:UDS 上逐连接一行 JSON 请求 / 一行 JSON 响应(stdlib socket,无新依赖)
- - 执行:runpy.run_module 复刻 bin/argo 的原地执行语义(sys.argv 置换 +
- stdout/stderr 重定向捕获),daemon 与 CLI 的行为严格同源
- - 串行:请求执行持全局锁。原因:redirect_stdout 是进程级全局态,并发
- 会串流;且 argo 内部本就高并发(并行效率 >1),CLI 层串行不损吞吐。
- 连接接受与响应发送仍在多线程——排队不阻塞心跳/停止。
- - 快路径:bin/argo 侧零 import 直连(socket 指针文件 `.daemon_sock-<树指纹>` 落在
- bin/argo 可预测的缓存根下,解耦 argo_paths 的深层解析)
- - 生命周期:`argo daemon start|status|stop|restart`;空闲 --idle-exit 秒
- 自杀(默认 1800),不留僵尸;SIGTERM 同样清场
- - 安全:socket chmod 0600(UDS 连接权限跟随文件权限,默认 umask 会放出
- 0755 让同机其他用户连上);只放行白名单脚本
- 第一笔 run 请求会多付 ~100ms(search 全家首次 import),此后全部热路径。
- daemon 自身启动刻意轻:只 import argo_paths/engine_env,不预热引擎栈。
- 运行:
- python3 scripts/daemon.py start [--foreground] [--idle-exit 1800] [--json]
- python3 scripts/daemon.py status [--json]
- python3 scripts/daemon.py stop [--json]
- """
- from __future__ import annotations
- import argparse
- import contextlib
- import errno
- import glob
- import io
- import json
- import os
- import runpy
- import signal
- import socket
- import sys
- import threading
- import time
- SCRIPTS_DIR = os.path.dirname(os.path.realpath(__file__))
- ARGO_HOME = os.path.dirname(SCRIPTS_DIR)
- if SCRIPTS_DIR not in sys.path:
- sys.path.insert(0, SCRIPTS_DIR)
- from argo_paths import state_path, state_root # noqa: E402
- import engine_states # 状态词表唯一真源(2026-11-09 收口)
- SOCK_NAME = "daemon.sock"
- PID_NAME = "daemon.pid"
- LOG_NAME = "daemon.log"
- POINTER_NAME = ".daemon_sock" # 指针文件:落 bin/argo 可预测的缓存根,内容=真实 socket 路径
- MARKER_NAME = ".daemon_autostart" # 自启节流文件:落 _cache_root()
- MAX_REQ_BYTES = 1 << 20 # 单请求上限 1MB(args 很小,此值纯防失控)
- # 发送侧超时的兜底值(客户端未在请求里带 send_timeout 时的旧客户端路径)。
- # 正常路径由客户端按自己的 ARGO_DAEMON_TIMEOUT+5 下达,见 handle()。
- _SEND_TIMEOUT_S = 300.0
- # 可执行脚本白名单(键=客户端传的 script 名,值=runpy 模块名)。
- # 与 bin/argo.scripts 同源收窄:daemon 只收 CLI 映射表里真实存在的目标,
- # 客户端 v1 只路由 search;表先备全,后续放行只需在此加行 + bin/argo 改路由。
- RUNNABLE = {
- "search": "search",
- }
- _fp_memo: tuple[float, str] | None = None
- _FP_TTL_S = 1.0 # 与 config_stamp() 同口径:1s 内突发请求免扫 220 个文件
- def _code_fingerprint(force: bool = False) -> str:
- """仓库 Python 源码指纹:scripts/*.py + sub-skills 关键子技能 + bin/argo。
- 为什么需要它:daemon 是长驻进程,但 `runpy.run_module` 只重执行脚本顶层,
- 首次请求 import 进 sys.modules 的整棵依赖树(search_cli/search/search_pipeline/
- engines*/sub-skills/local-search/search_v3 …)**不会被刷新**(2026-10-12
- 审计实证:顶层体重执行、依赖仍是旧对象)。于是 `git pull` / 改动脚本后,
- daemon 存活期内每次 search 都在静默跑旧代码,最长到空闲自杀(默认 30
- 分钟);若新版脚本 import 了旧模块里不存在的符号,顶层 ImportError 还会
- 变成「ok=True + exit 1」的硬失败。
- 覆盖面必须包含 sub-skills:daemon 进程内经 engines.py 把 search_v3 固化
- 进 sys.modules,只 hash scripts/ 会让「只改子技能」的变更漏出保护面。
- 指纹不一致时客户端必须回退冷路径(见 _daemon_run),daemon 自身也退出,
- 下一笔冷调用会按需重启新代码。
- """
- global _fp_memo
- now = time.monotonic()
- if not force and _fp_memo is not None and now - _fp_memo[0] < _FP_TTL_S:
- return _fp_memo[1]
- import hashlib
- h = hashlib.sha1()
- targets: list[str] = sorted(glob.glob(os.path.join(SCRIPTS_DIR, "*.py")))
- base = os.path.dirname(SCRIPTS_DIR)
- for rel in ("sub-skills/local-search", "sub-skills/local-seek",
- "sub-skills/ego-search"):
- targets.extend(sorted(glob.glob(os.path.join(base, rel, "**", "*.py"),
- recursive=True)))
- for p in targets:
- try:
- st = os.stat(p)
- except OSError:
- continue
- h.update(f"{os.path.relpath(p, base)}:{st.st_mtime_ns}:{st.st_size}\n"
- .encode("utf-8"))
- # bin/argo 也在热路径上(客户端自己读),变更同样必须触发回退
- try:
- st = os.stat(os.path.join(ARGO_HOME, "bin", "argo"))
- h.update(f"bin/argo:{st.st_mtime_ns}:{st.st_size}\n".encode("utf-8"))
- except OSError:
- pass
- digest = h.hexdigest()
- _fp_memo = (now, digest)
- return digest
- _TREE_TAG: str | None = None
- def _tree_tag() -> str:
- """本检出目录(ARGO_HOME realpath)的短指纹:daemon 落盘名字全部按树隔离。
- 为什么需要(2026-10-16 实证):socket/pid/指针/自启标记/日志此前落在
- 共享状态根(~/.cache/unified-search)的固定名上,同机多个检出目录
- (git worktree、多宿主软链、他人另一份 clone)互相踩:
- - B 树 daemon 抢到固定 socket 名后,A 树 CLI 经指针连上的是 B 的进程
- ——跑的是 B 的代码与配置;而指纹检测在 B 进程内只比对 B 自己的源码
- 树,A 的改动永远触发不了 stale,「改了不生效」且无法解释;
- - pid 文件互相覆盖:A 树 `argo daemon stop` 杀的是 B 树的 daemon;
- - 自启节流标记共享:A 树刚自启过,B 树 60s 内拉不起自己的 daemon。
- 名字带 ARGO_HOME 指纹后每树一个 daemon,互不抢、互不误杀。
- 兼容:旧固定名的在跑实例照常服务到空闲自杀(默认 30 分钟),新客户端按
- 新名字自启本树实例,无迁移动作;stop/status 只作用于本树实例。
- 两侧必须同算法同输入:bin/argo._tree_tag 与这里逐字一致(sha1(ARGO_HOME)
- 前 12 hex),测试 test_daemon.py 锁这份契约。
- """
- global _TREE_TAG
- if _TREE_TAG is None:
- import hashlib
- _TREE_TAG = hashlib.sha1(ARGO_HOME.encode("utf-8")).hexdigest()[:12]
- return _TREE_TAG
- def _cache_root() -> str:
- """bin/argo 可预测的缓存根(与 bin/argo._default_cache_root 同一逻辑)。
- 指针文件必须落在客户端**不 import 任何模块**就能算出的位置——entrypoint
- 的零 import 纪律不可破,所以这里反向迁就它的简化解析(env → XDG → 历史
- 目录),而不是客户端迁就 argo_paths 的完整解析(config.yaml db_path 分支
- 客户端不读 yaml 就算不出来)。两边不一致时快路径静默失效退回常态执行,
- 不会错。
- """
- # ARGO_STATE_DIR 与 bin/argo 的 _PY_CACHE 同一优先级:env 覆盖是测试隔离
- # 的硬开关,指针文件必须跟 socket 一起落进被隔离的根,两端才对得上。
- env_dir = os.environ.get("ARGO_STATE_DIR", "").strip()
- if env_dir:
- return env_dir
- if os.name == "nt":
- base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
- return os.path.join(base, "unified-search")
- xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
- if xdg:
- return os.path.join(xdg, "unified-search")
- return os.path.expanduser("~/.cache/unified-search")
- def _sock_path() -> str:
- """socket 路径:默认与状态根同目录;超长时落短路径哈希位。
- macOS/Linux 的 AF_UNIX 路径上限是 104 字节(sun_path),pytest 的深层
- 临时目录、或用户把 ARGO_STATE_DIR 挪进深嵌套目录时,原生路径会超——
- 实测 bind 直接 OSError「AF_UNIX path too long」。此时退到
- /tmp/argo-daemon-<uid>/<state_root 哈希>.sock:目录 0700 保用户隔离,
- 哈希保不同状态根互不冲突;可预测性由指针文件承担(客户端只读指针,
- 不算 socket 路径),所以这里怎么挪都不影响两端契约。
- """
- native = str(state_path(SOCK_NAME + "-" + _tree_tag()))
- if os.name == "nt" or len(native.encode("utf-8")) <= 100:
- return native
- import hashlib
- h = hashlib.sha1(str(state_root()).encode("utf-8")).hexdigest()[:10]
- d = f"/tmp/argo-daemon-{os.getuid()}"
- return os.path.join(d, f"{h}-{_tree_tag()}.sock")
- def _pointer_path() -> str:
- return os.path.join(_cache_root(), POINTER_NAME + "-" + _tree_tag())
- def _marker_path() -> str:
- return os.path.join(_cache_root(), MARKER_NAME + "-" + _tree_tag())
- def _pid_path() -> str:
- return str(state_path(PID_NAME + "-" + _tree_tag()))
- def _pid_alive(pid: int) -> bool:
- if os.name == "nt":
- import subprocess
- try:
- r = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
- capture_output=True, text=True, timeout=5,
- encoding="utf-8", errors="replace")
- return f'"{pid}"' in (r.stdout or "")
- except OSError:
- return False
- try:
- os.kill(pid, 0)
- return True
- except OSError:
- return False
- def _pid_is_daemon(pid: int) -> bool:
- """核实 pid 的命令行确实是本 daemon(POSIX ps / Windows PowerShell CIM)。"""
- import subprocess
- if os.name == "nt":
- try:
- ps_cmd = f"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine"
- r = subprocess.run(["powershell", "-NoProfile", "-Command", ps_cmd],
- capture_output=True, text=True, timeout=5,
- encoding="utf-8", errors="replace")
- cmd = (r.stdout or "").strip()
- except OSError:
- return False
- else:
- try:
- r = subprocess.run(["ps", "-p", str(pid), "-o", "command="],
- capture_output=True, text=True, timeout=5,
- encoding="utf-8", errors="replace")
- cmd = (r.stdout or "").strip()
- except OSError:
- return False
- if not cmd:
- return False
- toks = cmd.split()
- if "start" not in toks: # 两种形态都以 start 收尾;无 start 一律排除
- return False
- if any(t.endswith("daemon.py") for t in toks) and SCRIPTS_DIR in cmd:
- return True # 形态 A
- # 形态 B:bin/argo 入口(绝对/相对路径均可能,按 basename 认)
- has_argo = any(os.path.basename(t.strip("'\"")) in ("argo", "argo.exe")
- for t in toks)
- return has_argo and "daemon" in toks
- def _log_path() -> str:
- return str(state_path(LOG_NAME + "-" + _tree_tag()))
- # 日志轮转:daemon 生命周期短(空闲自杀),增长慢,启动时检查一次足够。
- # 曾完全无轮转(只靠空闲自杀间接限速),18 天积 405 行属侥幸而非机制。
- _LOG_MAX_BYTES = 1 * 1024 * 1024
- def _rotate_log_if_needed() -> None:
- """日志超 1MB 时轮转为 .1(旧的 .1 直接淘汰,不保多代)。
- 轮转失败不拦启动:日志是观测件,写不进去也比起不来强。
- """
- p = _log_path()
- try:
- if os.path.exists(p) and os.path.getsize(p) > _LOG_MAX_BYTES:
- old = p + ".1"
- if os.path.exists(old):
- os.unlink(old)
- os.replace(p, old)
- except OSError:
- pass
- class _TimestampedStdout:
- """行级时间戳包装:daemon.log 曾零时间戳,重启频率与崩溃间隔无法回答
- (2026-11-14 运行时审计 C 类实锤)。服务输出统一加 [ISO-8601] 前缀。
- 只包装文本流;fd 重定向(dup2)不走这里,外部轮转不受影响。
- """
- def __init__(self, raw):
- self._raw = raw
- self._at_line_start = True
- def write(self, s):
- if not s:
- return 0
- now = time.strftime("%Y-%m-%dT%H:%M:%S")
- out = []
- for chunk in s.splitlines(keepends=True):
- if self._at_line_start and chunk.strip():
- out.append(f"[{now}] ")
- out.append(chunk)
- self._at_line_start = chunk.endswith("\n")
- return self._raw.write("".join(out))
- def flush(self):
- self._raw.flush()
- def _atomic_write(path: str, text: str) -> None:
- d = os.path.dirname(path)
- if d:
- os.makedirs(d, exist_ok=True)
- tmp = f"{path}.tmp.{os.getpid()}"
- with open(tmp, "w", encoding="utf-8") as f:
- f.write(text)
- os.replace(tmp, path)
- # ── 状态查询 ────────────────────────────────────────────────────────────────
- def ping(sock_path: str, timeout: float = 1.0) -> dict:
- """对 socket 发 ping;活着返回响应 dict,死了抛 OSError。"""
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- s.settimeout(timeout)
- try:
- s.connect(sock_path)
- s.sendall(b'{"op":"ping"}\n')
- buf = b""
- while not buf.endswith(b"\n"):
- chunk = s.recv(65536)
- if not chunk:
- break
- buf += chunk
- return json.loads(buf.decode("utf-8", "replace"))
- finally:
- s.close()
- def _alive() -> dict | None:
- """daemon 存活则返回 ping 响应,否则 None。
- 清场判据从紧(2026-10-12 审计修正):只在「连接被明确拒绝」时摘除
- socket/指针——ping 超时(daemon 被 GIL 硬占/负载高)不代表它死了,
- 此前任何异常都 unlink,会把活着 daemon 的入口摘掉,其监听 socket 成为
- 永久不可达的孤儿,直到空闲自杀。宁可不摘(下次 start 会再探),不误摘。
- """
- sp = _sock_path()
- if not os.path.exists(sp):
- with contextlib.suppress(OSError):
- os.unlink(_pointer_path())
- return None
- try:
- return ping(sp)
- except OSError as e:
- if e.errno in (errno.ECONNREFUSED, errno.ENOENT):
- for p in (sp, _pointer_path()):
- with contextlib.suppress(OSError):
- os.unlink(p)
- return None
- except Exception:
- return None
- # ── 请求执行 ────────────────────────────────────────────────────────────────
- # 执行锁:stdout 重定向是进程级全局态,运行请求必须串行。持有者超时前
- # 未释放时新请求不排队等待而是快速返回 busy——排队等待会让每个调用方的
- # 客户端超时预算含上排队时间,冷路径本来就能并行跑,排队在这儿没有任何
- # 收益(audit 2026-10-12)。
- _EXEC_LOCK = threading.Lock()
- _EXEC_WAIT_S = 0.2
- # 环境变量透传白名单判据在客户端(bin/argo._daemon_env):daemon 侧只负责
- # 应用/还原请求携带的覆盖。此处不再放第二份挑选规则——双份实现必然漂移,
- # 且 daemon 侧那份此前全仓无人调用(2026-10-12 审查发现)。
- _MAX_ENV_OVERRIDE_BYTES = 32768
- def _apply_env_overrides(overrides) -> dict:
- """请求级应用客户端环境;返回还原快照(键 → 旧值或 None)。"""
- saved: dict = {}
- if not isinstance(overrides, dict):
- return saved
- total = 0
- for k, v in overrides.items():
- if not isinstance(k, str) or not isinstance(v, str) or not k:
- continue
- total += len(k) + len(v)
- if total > _MAX_ENV_OVERRIDE_BYTES:
- return saved # 超限拒绝(防畸形请求灌爆环境);已应用的不回滚
- saved[k] = os.environ.get(k)
- os.environ[k] = v
- return saved
- def _restore_env(saved: dict) -> None:
- for k, prev in saved.items():
- if prev is None:
- os.environ.pop(k, None)
- else:
- os.environ[k] = prev
- def _run_request(req: dict) -> dict:
- """执行一笔 run 请求:与 bin/argo 原地路径严格同语义。
- run_module 而非直接调 main():与 bin/argo 的 runpy 路径一字不差,脚本
- 的 `if __name__ == "__main__"` / argparse / sys.exit 语义原样生效。代价
- 是每次重执行脚本顶层(__pycache__ 命中下 ~几 ms)——相对引擎 RTT 可忽略,
- 换来的是零特判的「和 CLI 完全一样」。
- 调用方必须已持有 _EXEC_LOCK(锁在 handle() 层做超时快失败)。
- """
- script = req.get("script")
- module = RUNNABLE.get(script or "")
- args = req.get("args") or []
- if module is None:
- return {"ok": False, "error": f"script 不在白名单: {script!r}"}
- if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
- return {"ok": False, "error": "args 必须是字符串列表"}
- script_path = os.path.join(SCRIPTS_DIR, f"{script}.py")
- t0 = time.perf_counter()
- out, err = io.StringIO(), io.StringIO()
- code = 0
- old_argv, old_cwd = sys.argv, os.getcwd()
- saved_env = _apply_env_overrides(req.get("env"))
- try:
- cwd = req.get("cwd")
- if cwd and os.path.isdir(cwd):
- os.chdir(cwd)
- sys.argv = [script_path] + args
- with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
- try:
- runpy.run_module(module, run_name="__main__")
- except SystemExit as e:
- # 与 CLI 退出码契约一致:None/0 → 0,整数原样,其余 → 1
- code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
- except BaseException as e: # 引擎栈漏出的非 SystemExit:按 CLI 语义退出码 1
- code = 1
- err.write(f"\n[daemon] {type(e).__name__}: {e}\n")
- finally:
- _restore_env(saved_env)
- sys.argv = old_argv
- with contextlib.suppress(OSError):
- os.chdir(old_cwd)
- return {
- "ok": True,
- "exit_code": code,
- "stdout": out.getvalue(),
- "stderr": err.getvalue(),
- "took_ms": round((time.perf_counter() - t0) * 1000, 1),
- }
- # ── 服务循环 ────────────────────────────────────────────────────────────────
- def _peer_closed(conn: socket.socket) -> bool:
- """对端是否已断开(不消费数据,MSG_PEEK 探测)。
- 用途:客户端超时/被杀后 socket 已关,但请求如果恰在排队或还没点火,
- daemon 不应该再把它跑一遍——那是同一查询的付费调用与 usage 双计
- (audit 2026-10-12)。已开始的执行不中断(引擎有各自超时且有缓存兜底),
- 只挡住「还没开跑」这一类。
- """
- import select
- try:
- r, _, _ = select.select([conn], [], [], 0)
- if not r:
- return False
- return conn.recv(1, socket.MSG_PEEK) == b""
- except OSError:
- return True
- # stop/SIGTERM 时等在途 run 收尾的上限:宁可 stop 慢几秒,也不腰斩一笔已
- # 开始的执行(腰斩会让客户端拿到 EOF 回退冷跑,同一查询双跑双计)。
- _STOP_GRACE_S = 20.0
- class _Server:
- def __init__(self, idle_exit_s: float) -> None:
- self.idle_exit_s = idle_exit_s
- self.stop_evt = threading.Event()
- self.active = 0
- self.active_lock = threading.Lock()
- self.last_activity = time.monotonic()
- self.started_at = time.monotonic()
- self.in_run = 0 # 正在执行的 run 数(0/1,受 _EXEC_LOCK 约束)
- self.fp = "" # 启动时的源码指纹;请求时比对,变更即 stale
- def handle(self, conn: socket.socket) -> None:
- with self.active_lock:
- self.active += 1
- try:
- conn.settimeout(60) # 兼容旧值 300s:哑连接不应把空闲退出推迟五分钟
- buf = b""
- while not buf.endswith(b"\n") and len(buf) < MAX_REQ_BYTES:
- chunk = conn.recv(65536)
- if not chunk:
- break
- buf += chunk
- resp: dict = {"ok": False, "error": "空请求"}
- # req 必须先绑定再使用:空请求 / 超 1MB / 解析失败 / 非 dict 体
- # (如 JSON 数组)时 475 行的 `req.get("send_timeout")` 会
- # NameError/AttributeError——两者都穿不透下面的 except OSError,
- # handler 线程带 traceback 死掉,上面特意准备的错误响应永远没
- # 发送,客户端拿 EOF 回退冷跑(2026-10-17 审查发现 2)。
- req: dict = {}
- if len(buf) > MAX_REQ_BYTES:
- resp = {"ok": False, "error": "请求超长"}
- buf = b""
- if buf.strip():
- try:
- parsed = json.loads(buf.decode("utf-8", "replace"))
- if isinstance(parsed, dict):
- req = parsed
- op = req.get("op")
- if op == "ping":
- now = time.monotonic()
- # state 是给机器读的唯一判据(词表见 engine_states §10);
- # 保留 ok/running 形态给旧客户端,新增字段不改旧语义。
- resp = {"ok": True, "pid": os.getpid(),
- "state": (engine_states.DAEMON_BUSY
- if self.in_run
- else engine_states.DAEMON_RUNNING),
- "in_run": self.in_run,
- "uptime_s": round(now - self.started_at, 1),
- "idle_s": round(now - self.last_activity, 1),
- "fp": self.fp}
- elif op == "stop":
- resp = {"ok": True, "stopping": True}
- self.stop_evt.set()
- elif op == "run":
- resp = self._handle_run(conn, req)
- else:
- resp = {"ok": False, "error": f"未知 op: {op!r}"}
- except Exception as e:
- resp = {"ok": False, "error": f"{type(e).__name__}: {e}"}
- # sendall 用的超时与 recv 的那把(60s)分开,且以**客户端声明
- # 的预算**为准:一笔 run 超过 60s 时 sendall 抛 socket.timeout
- # 会丢响应、逼客户端冷跑重来(同一查询双跑双计,2026-10-16 审查
- # 发现)。请求里的 send_timeout 由客户端按自己的
- # ARGO_DAEMON_TIMEOUT+5 填——服务端任何固定值都猜不到用户把
- # 客户端等限调到了多大;缺失(旧客户端)时回退模块常量。
- try:
- _send_tmo = float(req.get("send_timeout"))
- except (TypeError, ValueError):
- _send_tmo = _SEND_TIMEOUT_S
- conn.settimeout(_send_tmo if _send_tmo > 0 else None)
- conn.sendall((json.dumps(resp, ensure_ascii=False) + "\n").encode("utf-8"))
- except OSError:
- pass # 客户端超时先走:响应丢弃即可,引擎侧照常完成
- finally:
- with contextlib.suppress(OSError):
- conn.close()
- with self.active_lock:
- self.active -= 1
- def _handle_run(self, conn: socket.socket, req: dict) -> dict:
- """run 分支:忙时快失败;源码变更判 stale;对端已断不点火。"""
- if not _EXEC_LOCK.acquire(timeout=_EXEC_WAIT_S):
- return {"ok": False, "busy": True,
- "error": "daemon 正忙(客户端应回退冷路径)"}
- try:
- if self.stop_evt.is_set():
- # 已进入退役:不再点火(点火后进程退出会把它腰斩,客户端
- # 拿不到响应只能冷跑重来——正是本次要消除的双跑)。
- return {"ok": False, "error": "daemon 退役中(客户端应回退冷路径)"}
- fp = _code_fingerprint()
- if self.fp and fp and fp != self.fp:
- self.stop_evt.set() # 旧代码 daemon 退役,下次冷调用按需起新
- return {"ok": False, "stale": True,
- "error": "仓库源码已变更:daemon 退出,客户端回退冷路径"}
- if _peer_closed(conn):
- return {"ok": False, "error": "客户端已断开,跳过执行"}
- self.last_activity = time.monotonic()
- self.in_run += 1
- try:
- resp = _run_request(req)
- finally:
- self.in_run -= 1
- self.last_activity = time.monotonic()
- return resp
- finally:
- _EXEC_LOCK.release()
- def serve_forever(self) -> None:
- sp = _sock_path()
- # bind 前建目录:UDS bind 会在 socket 路径上落文件,目录不存在即
- # FileNotFoundError(测试隔离/新机器首次启动必踩——上一版就栽在这)
- d = os.path.dirname(sp)
- if d:
- os.makedirs(d, exist_ok=True)
- if d.startswith("/tmp/argo-daemon-"):
- os.chmod(d, 0o700) # 短路径位落在共享 /tmp:目录必须锁回本用户
- listen_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- try:
- listen_sock.bind(sp)
- except OSError as e:
- # 父进程只能看到「启动超时」,死因必须自己写进日志
- print(f"[daemon] bind 失败 {sp}: {e}", flush=True)
- raise
- os.chmod(sp, 0o600) # UDS 连接权限=文件权限;默认 umask 会放出组/其他可连
- listen_sock.listen(16)
- self.fp = _code_fingerprint() # 请求期比对;源码一变即 stale(见 _handle_run)
- _atomic_write(_pid_path(), f"{os.getpid()}\n")
- _atomic_write(_pointer_path(), sp + "\n")
- def _on_term(_sig, _frm) -> None:
- self.stop_evt.set()
- signal.signal(signal.SIGTERM, _on_term)
- signal.signal(signal.SIGINT, _on_term)
- def _watchdog() -> None:
- while not self.stop_evt.wait(5.0):
- if self.idle_exit_s > 0 and self.active == 0 \
- and time.monotonic() - self.last_activity > self.idle_exit_s:
- print(f"[daemon] 空闲 {self.idle_exit_s:.0f}s,自杀退出", flush=True)
- self.stop_evt.set()
- threading.Thread(target=_watchdog, daemon=True).start()
- def _prewarm() -> None:
- # 监听就绪后后台预热核心模块与域正则(与 mcp_handlers._warm_core_async 同构):
- # 既不拖慢 start 握手(~30ms),又消除首笔 search 请求的 ~118ms 冷加载税。
- if not _EXEC_LOCK.acquire(timeout=0.05):
- return
- try:
- if self.stop_evt.is_set():
- return
- import search # noqa: F401
- import search_cli # noqa: F401
- from route_domains import warm_compiled_domains
- warm_compiled_domains()
- except Exception:
- pass
- finally:
- _EXEC_LOCK.release()
- threading.Thread(target=_prewarm, name="argo-daemon-warm", daemon=True).start()
- print(f"[daemon] pid={os.getpid()} socket={sp} 就绪", flush=True)
- try:
- listen_sock.settimeout(2.0)
- while not self.stop_evt.is_set():
- try:
- conn, _ = listen_sock.accept()
- except socket.timeout:
- continue
- threading.Thread(target=self.handle, args=(conn,), daemon=True).start()
- # 收尾第一步:立刻关闭并摘除监听 socket——退役期间新客户端不再
- # 连进 backlog 干等(旧实现把 listen_sock 开到退出才关,
- # stop 后紧跟的 search 要等整个收尾窗口才拿到 RST)。此后新连接
- # 立即 ECONNREFUSED → 客户端静默回退冷路径。
- with contextlib.suppress(OSError):
- listen_sock.close()
- for p in (_sock_path(), _pointer_path(), _marker_path()):
- with contextlib.suppress(OSError):
- os.unlink(p)
- # 第二步:等在途 run 收尾(上限 _STOP_GRACE_S)——腰斩已开始的
- # 执行会逼客户端回退冷跑、同查询双计。无在途执行时立即退出。
- deadline = time.monotonic() + _STOP_GRACE_S
- while time.monotonic() < deadline and self.in_run > 0:
- time.sleep(0.05)
- finally:
- with contextlib.suppress(OSError):
- os.unlink(_pid_path())
- print("[daemon] 已退出", flush=True)
- # ── 子命令 ──────────────────────────────────────────────────────────────────
- def _quiet_stop(sp: str) -> bool:
- """向在跑 daemon 发 stop 并等 socket 消失;成功 True。
- 用于 start 的陈旧自愈:指纹不符的旧实例先请走,再起新代码的实例。
- connect 失败不再直接判失败——旧实例可能恰在自行退役(accept 循环已退出、
- socket 文件尚未清理),此时「连不上」= 已在停,视同成功(2026-10-12
- 审查:假阴性会让陈旧自愈在最需要它的时刻拒绝启动)。
- """
- try:
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- s.settimeout(2.0)
- s.connect(sp)
- s.sendall(b'{"op":"stop"}\n')
- s.close()
- except OSError:
- # 连不上:确认它确实不在响应(_alive 为 None)即视同已停
- return _alive() is None
- deadline = time.time() + 10
- while time.time() < deadline:
- if not os.path.exists(sp):
- return True
- time.sleep(0.1)
- return False
- def _terminate_pid(pid: int) -> None:
- if os.name == "nt":
- import subprocess
- subprocess.run(["taskkill", "/PID", str(pid), "/F"],
- capture_output=True, timeout=5)
- return
- os.kill(pid, signal.SIGTERM)
- def _redirect_stdio_to_log() -> None:
- log_dir = os.path.dirname(_log_path())
- if log_dir:
- os.makedirs(log_dir, exist_ok=True)
- _rotate_log_if_needed()
- log = open(_log_path(), "ab", buffering=0)
- os.dup2(log.fileno(), 0)
- Dismissed after review: Opens a shell for a remote machine (reverse shell)
- Line 720 on GitHub
- os.dup2(log.fileno(), 1)
- Dismissed after review: Opens a shell for a remote machine (reverse shell)
- Line 721 on GitHub
- os.dup2(log.fileno(), 2)
- Dismissed after review: Opens a shell for a remote machine (reverse shell)
- Line 722 on GitHub
- with contextlib.suppress(OSError):
- log.close()
- def _wait_ready_and_report(args: argparse.Namespace) -> int:
- deadline = time.time() + 10
- while time.time() < deadline:
- try:
- info = ping(_sock_path(), 0.5)
- msg = {"ok": True, "pid": info.get("pid")}
- print(json.dumps(msg, ensure_ascii=False) if args.json
- else f"argo daemon 已启动 pid={info.get('pid')} socket={_sock_path()}")
- return 0
- except Exception:
- time.sleep(0.05)
- print(json.dumps({"ok": False, "error": "启动超时", "log": _log_path()},
- ensure_ascii=False) if args.json
- else f"argo daemon 启动超时,看日志:{_log_path()}", file=sys.stderr)
- return 1
- def _start_detached_windows(args: argparse.Namespace) -> int:
- import subprocess
- flags = getattr(subprocess, "DETACHED_PROCESS", 0x00000008) | getattr(
- subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
- cmd = [sys.executable, os.path.abspath(__file__), "start",
- "--foreground", "--detached-log", "--idle-exit", str(args.idle_exit)]
- subprocess.Popen(cmd, creationflags=flags, close_fds=True,
- stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- return _wait_ready_and_report(args)
- def _start(args: argparse.Namespace) -> int:
- alive = _alive()
- if alive:
- # 陈旧自愈:在跑的实例指纹与当前源码不符(git pull / 改脚本后)时,
- # 老实例已进入「拒执行 + 准备退役」状态,但退役与重新拉起之间有时序
- # 缝——客户端自启的新 start 会因「ping 得到旧进程」直接报已在运行并
- # 退出,结果退役完成后无人接手(实测踩中:touch 脚本后 status 永为
- # 未运行)。这里对指纹不符的实例先停、等它出场,再走正常启动。
- cur_fp = _code_fingerprint(force=True)
- running_fp = alive.get("fp") or ""
- if running_fp and cur_fp and running_fp != cur_fp:
- if not args.json:
- print(f"argo daemon 检出旧代码实例(pid={alive.get('pid')}),重启",
- file=sys.stderr)
- if _quiet_stop(_sock_path()):
- alive = None # 让流程继续到启动
- else:
- print(json.dumps({"ok": False, "error": "旧实例未能停止"},
- ensure_ascii=False) if args.json
- else "旧代码 daemon 未能停止;先 `argo daemon stop`", file=sys.stderr)
- return 1
- else:
- print(json.dumps({"ok": True, "already_running": True, **alive},
- ensure_ascii=False) if args.json
- else f"argo daemon 已在运行 pid={alive.get('pid')}")
- return 0
- # 启动互斥(stub 文件 O_EXCL):两个并发 start 都通过 _alive 检查时会
- # 双双 fork,输家 bind 失败、赢家被后到的父进程误报;更糟的是赢家在
- # bind→listen 窗口内会被输家的 _alive 当陈尸。stub 让后来者等待赢家。
- stub = _pid_path() + ".starting"
- try:
- os.makedirs(os.path.dirname(stub), exist_ok=True)
- except OSError:
- pass
- acquired = False
- for _attempt in range(3):
- try:
- fd = os.open(stub, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- os.close(fd)
- acquired = True
- break
- except FileExistsError:
- # 旧 stub 可能是上次崩溃残留(>20s 视为陈尸):清掉后立刻重抢
- try:
- if time.time() - os.stat(stub).st_mtime > 20:
- os.unlink(stub)
- continue
- except OSError:
- pass
- # 活着的启动者:等它把 daemon 拉起来(或它中途放行 stub)
- deadline = time.time() + 10
- while time.time() < deadline:
- info = _alive()
- if info:
- print(json.dumps({"ok": True, "already_running": True, **info},
- ensure_ascii=False) if args.json
- else f"argo daemon 已在运行 pid={info.get('pid')}")
- return 0
- if not os.path.exists(stub):
- break # 对方放行:回到循环重抢 stub
- time.sleep(0.1)
- except OSError:
- break # stub 建不了(只读状态目录等):退回无互斥的老路,不阻断启动
- else:
- # 三次都没抢到:对方仍在启动流程里,如实报告
- print(json.dumps({"ok": False, "error": "另一进程正在启动 daemon,等待超时"},
- ensure_ascii=False) if args.json
- else "另一进程正在启动 argo daemon(等待超时)", file=sys.stderr)
- return 1
- try:
- # socket 还在但 ping 不通:可能是在途请求把 GIL 占满的活 daemon。
- # 不抢跑(bind 必失败、还可能把它的入口当陈尸摘掉),如实报告。
- sp = _sock_path()
- if os.path.exists(sp):
- try:
- ping(sp, 2.0)
- except OSError as e:
- if e.errno not in (errno.ECONNREFUSED, errno.ENOENT):
- print(json.dumps({"ok": False, "error": "daemon socket 存在但无响应"},
- ensure_ascii=False) if args.json
- else "argo daemon socket 存在但无响应;先 `argo daemon stop`",
- file=sys.stderr)
- return 1
- except Exception:
- pass
- if args.foreground:
- if getattr(args, "detached_log", False):
- _redirect_stdio_to_log()
- _serve_child(args)
- return 0
- if os.name == "nt":
- return _start_detached_windows(args)
- pid = os.fork()
- if pid > 0:
- return _wait_ready_and_report(args)
- os.setsid()
- _redirect_stdio_to_log()
- _serve_child(args)
- return 0
- finally:
- with contextlib.suppress(OSError):
- os.unlink(stub)
- def _serve_child(args: argparse.Namespace) -> None:
- # stdio 已 dup2 到日志文件;文本流再包一层时间戳,所有 print 落日志带
- # [ISO-8601] 前缀(观测缺失收口:无时间戳的日志无法回答重启频率)。
- sys.stdout = _TimestampedStdout(sys.stdout)
- sys.stderr = _TimestampedStdout(sys.stderr)
- try:
- from engine_env import sync_envfile_to_environ
- sync_envfile_to_environ()
- except Exception:
- pass # env 文件读不到不拦 daemon:引擎侧按各自缺 key 的既有口径失败
- _Server(args.idle_exit).serve_forever()
- def _stop(args: argparse.Namespace) -> int:
- sp = _sock_path()
- try:
- ping(sp, 1.0)
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- s.settimeout(2.0)
- s.connect(sp)
- s.sendall(b'{"op":"stop"}\n')
- buf = b""
- while not buf.endswith(b"\n"):
- chunk = s.recv(65536)
- if not chunk:
- break
- buf += chunk
- s.close()
- # 等 socket 文件消失(退役第一步就会 unlink,正常毫秒级);socket 消
- # 失后再给在途 run 一个收尾观察窗——文档口径是「上限 20s」,此前只
- # 等 5s 就无条件报成功,在途收尾还没完时紧随的 start 会因 socket
- # 仍在而报「先 stop」(用户被指回刚跑过的命令)。
- deadline = time.time() + 5
- while time.time() < deadline and os.path.exists(sp):
- time.sleep(0.05)
- pid = None
- try:
- with open(_pid_path(), encoding="utf-8") as f:
- pid = int(f.read().strip())
- except (OSError, ValueError):
- pass
- if pid:
- grace = time.time() + _STOP_GRACE_S
- while time.time() < grace:
- if not _pid_alive(pid):
- break # 进程已退出:真停
- time.sleep(0.1)
- with contextlib.suppress(OSError):
- os.unlink(_marker_path())
- print(json.dumps({"ok": True, "stopped": True, "pid": pid}, ensure_ascii=False)
- if args.json else "argo daemon 已停止")
- return 0
- except Exception:
- # socket 已死:靠 pid 文件兜底补刀,避免进程活着却没有入口的孤儿态。
- # kill 前先核实命令行确实是本 daemon——pid 文件可能陈旧,而 OS 的 pid
- # 会复用:裸 SIGTERM 一个恰好复用 pid 的无关进程是真实伤害。
- killed = None
- try:
- with open(_pid_path(), encoding="utf-8") as f:
- pid = int(f.read().strip())
- if _pid_is_daemon(pid):
- _terminate_pid(pid)
- killed = pid
- except (OSError, ValueError):
- pass
- for p in (sp, _pointer_path(), _pid_path(), _marker_path()):
- with contextlib.suppress(OSError):
- os.unlink(p)
- print(json.dumps({"ok": True, "stopped": True, "killed": killed},
- ensure_ascii=False) if args.json else "argo daemon 已清理")
- return 0
- def _status(args: argparse.Namespace) -> int:
- alive = _alive()
- state = (str(alive.get("state") or engine_states.DAEMON_RUNNING)
- if alive else engine_states.DAEMON_STOPPED)
- payload = {"ok": True, "running": bool(alive), "state": state,
- "socket": _sock_path(), "pid": (alive or {}).get("pid")}
- if args.json:
- print(json.dumps(payload, ensure_ascii=False))
- else:
- if alive:
- print(f"argo daemon 运行中 pid={alive.get('pid')} socket={_sock_path()}")
- else:
- print(f"argo daemon 未运行(socket={_sock_path()})")
- return 0
- def _cli() -> int:
- ap = argparse.ArgumentParser(description="argo 常驻 daemon(消 CLI 每次调用的启动+import 固定成本)")
- sub = ap.add_subparsers(dest="cmd", required=True)
- p_start = sub.add_parser("start", help="启动 daemon(默认后台化)")
- p_start.add_argument("--foreground", action="store_true", help="前台运行(调试用)")
- p_start.add_argument("--detached-log", action="store_true", help=argparse.SUPPRESS)
- p_start.add_argument("--idle-exit", type=float, default=1800.0,
- help="空闲 N 秒后自杀退出;0=常驻不退(默认 1800)")
- for p in (p_start, sub.add_parser("status"), sub.add_parser("stop")):
- p.add_argument("--json", action="store_true", help="机器可读输出")
- args = ap.parse_args()
- if args.cmd == "start":
- return _start(args)
- if args.cmd == "stop":
- return _stop(args)
- return _status(args)
- if __name__ == "__main__":
- raise SystemExit(_cli())
scripts/install.sh · Bundled script · 370 lines · 1 finding marked
- #!/usr/bin/env bash
- # Argo 安装脚本 —— 克隆/更新真源、装依赖、挂 Skill 入口、装提交门禁。
- #
- # 用法:
- # curl -fsSL https://raw.githubusercontent.com/taxueseek/argo/main/scripts/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 5 on GitHub
- # ARGO_HOME=/path/to/argo bash scripts/install.sh
- # bash scripts/install.sh --link ~/.claude/skills/argo
- # bash scripts/install.sh --dry-run # 只打印将执行的动作
- # bash scripts/install.sh --uninstall # 清理本脚本装的东西
- #
- # 环境变量:
- # ARGO_HOME 安装目录,默认 ~/.local/share/argo
- # ARGO_REPO 仓库地址,默认 https://github.com/taxueseek/argo.git
- # ARGO_BRANCH 分支,默认 main
- # ARGO_SKIP_PIP 设为 1 则跳过依赖安装
- # ARGO_LINK_TARGETS 冒号分隔的 Skill 入口路径(可选)
- # ARGO_PIN 固定 commit(供应链加固:克隆后校验 HEAD)
- #
- # 设计原则(对应 Agent Skills 规范对 scripts/ 的三条要求):
- # 1. 自包含:单文件、零外部依赖(除 git / python3 / uv 这三件可选工具);
- # 2. 错误信息可执行:每个失败点都给出「该装什么」或「该改哪个变量」;
- # 3. 边界优雅:已有仓库、已有链接、已有 hook、缺 uv、PEP 668 环境各自有明确出路。
- set -euo pipefail
- # 本脚本用 bash 语法(数组、[[ ]])。FreeBSD/OpenBSD/精简容器里 /bin/sh 不是 bash,
- # 直接跑会在解析期报一堆看不出原因的语法错误,所以先自证运行环境。
- if [ -z "${BASH_VERSION:-}" ]; then
- if command -v bash >/dev/null 2>&1; then
- exec bash "$0" "$@"
- fi
- echo "install.sh 需要 bash(本脚本使用数组与 [[ ]] 语法)。" >&2
- echo " Debian/Ubuntu: sudo apt-get install -y bash" >&2
- echo " Alpine: apk add bash" >&2
- echo " FreeBSD: pkg install -y bash" >&2
- echo " OpenBSD: pkg_add bash" >&2
- echo " macOS/多数 Linux 自带 bash,可直接: curl -fsSL <url> | bash" >&2
- exit 1
- fi
- # ── 输出与错误 ────────────────────────────────────────────────────────────────
- # 统一出口:info(步骤)、ok(成功)、warn(可继续的失败)、die(中止)。
- # die 的每条消息都必须可执行——「该装什么」或「该改哪个变量」,不留「出错了」。
- info() { printf '==> %s\n' "$*"; }
- ok() { printf ' [ok] %s\n' "$*"; }
- warn() { printf ' [warn] %s\n' "$*" >&2; }
- die() { printf ' [fail] %s\n' "$*" >&2; exit 1; }
- # ── 参数与默认值 ──────────────────────────────────────────────────────────────
- REPO="${ARGO_REPO:-https://github.com/taxueseek/argo.git}"
- BRANCH="${ARGO_BRANCH:-main}"
- PIN="${ARGO_PIN:-}"
- HOME_DIR="${HOME:-$(eval echo ~)}"
- INSTALL_DIR="${ARGO_HOME:-$HOME_DIR/.local/share/argo}"
- SKIP_PIP="${ARGO_SKIP_PIP:-0}"
- DRY_RUN=0
- UNINSTALL=0
- LINK_ARGS=()
- usage() { sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'; }
- while [[ $# -gt 0 ]]; do
- case "$1" in
- --home) INSTALL_DIR="$2"; shift 2 ;;
- --link) LINK_ARGS+=(--to "$2"); shift 2 ;;
- --skip-pip) SKIP_PIP=1; shift ;;
- --pin) PIN="$2"; shift 2 ;;
- --dry-run) DRY_RUN=1; shift ;;
- --uninstall) UNINSTALL=1; shift ;;
- -h|--help) usage; exit 0 ;;
- *) die "未知参数: $1(--help 看用法)" ;;
- esac
- done
- # dry-run 下所有会改系统的**简单命令**都只打印。
- # 注意:不要用它包「内部还有判断逻辑的函数」——被包的函数在 dry-run 时根本不执行,
- # 其内部状态(local 变量、副作用)全部跳过,反而制造假失败。函数自己处理 dry-run。
- run() {
- if [[ "$DRY_RUN" == "1" ]]; then
- printf ' [dry-run] %s\n' "$*"
- return 0
- fi
- "$@"
- }
- # ── 前置检查 ──────────────────────────────────────────────────────────────────
- command -v git >/dev/null 2>&1 || die "需要 git。Debian/Ubuntu: sudo apt-get install -y git;macOS: xcode-select --install"
- command -v python3 >/dev/null 2>&1 || die "需要 Python 3.9+。python.org 下载,或 pyenv install 3.12"
- # 版本下限与 bin/argo 的 MIN_PYTHON、install.ps1 三处必须一致。为什么是 3.9:
- # 唯一必需依赖 PyYAML 早已支持 3.9,脚本几乎都带 `from __future__ import annotations`;
- # 抬高门槛只会把 macOS 原生 python3.9、老 Debian、python:3.9 容器挡在门外。
- PY_VER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
- python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else 1)' \
- || die "当前 Python 为 ${PY_VER},需要 3.9+。装新版本后重跑本脚本即可(不会动系统 Python)"
- # ── 卸载 ──────────────────────────────────────────────────────────────────────
- if [[ "$UNINSTALL" == "1" ]]; then
- info "卸载 Argo(安装目录 ${INSTALL_DIR})"
- # 摘 Skill 链接:link_source.py 没有 --undo,手动删指向真源的符号链接。
- # 只删符号链接(-L 判定),绝不碰真实目录——误删用户数据的代价不可逆。
- for _target in "$HOME_DIR/.claude/skills/argo" "$HOME_DIR/.agents/skills/argo" \
- "$HOME_DIR/.grok/skills/argo" "$HOME_DIR/.codex/skills/argo"; do
- if [[ -L "$_target" && "$(readlink "$_target")" == "$INSTALL_DIR" ]]; then
- run rm -f "$_target"
- ok "已摘除链接 $_target"
- fi
- done
- # 摘 hook 调度器:保留用户的 pre-commit.user
- _common=$(cd "$INSTALL_DIR" 2>/dev/null && git rev-parse --git-common-dir 2>/dev/null || true)
- case "$_common" in
- /*) _hooks="$_common/hooks" ;;
- "") _hooks="" ;;
- *) _hooks="$INSTALL_DIR/$_common/hooks" ;;
- esac
- if [[ -n "$_hooks" && -f "$_hooks/pre-commit" ]] && grep -qF "# argo-hook-dispatcher v2" "$_hooks/pre-commit"; then
- run rm -f "$_hooks/pre-commit"
- run rm -f "$_hooks/pre-commit-argo"
- ok "已摘除 pre-commit 调度器"
- fi
- # 最后删目录
- if [[ -d "$INSTALL_DIR" ]]; then
- run rm -rf "$INSTALL_DIR"
- ok "已删除 $INSTALL_DIR"
- fi
- info "卸载完成。Skill 目录里的 argo 符号链接如仍存在,手动 rm 即可。"
- exit 0
- fi
- info "安装目录: $INSTALL_DIR"
- info "仓库来源: $REPO (分支 $BRANCH)"
- [[ -n "$PIN" ]] && info "供应链固定: commit $PIN"
- [[ "$DRY_RUN" == "1" ]] && warn "dry-run 模式:只打印动作,不实际执行"
- echo " 提示: 若以 curl|bash 执行,请确认来源可信;生产环境建议 ARGO_PIN 固定 commit。"
- # ── 1. 克隆 / 更新真源 ────────────────────────────────────────────────────────
- if [[ -d "$INSTALL_DIR/.git" ]]; then
- info "已有仓库,拉取更新 ($BRANCH)…"
- run git -C "$INSTALL_DIR" fetch --depth 1 origin "$BRANCH"
- run git -C "$INSTALL_DIR" checkout "$BRANCH"
- git -C "$INSTALL_DIR" pull --ff-only origin "$BRANCH" 2>/dev/null || warn "pull 失败(可能有本地改动),继续使用当前版本"
- elif [[ -d "$INSTALL_DIR" && -f "$INSTALL_DIR/scripts/search.py" ]]; then
- info "目录已存在且含 Argo 源码,跳过克隆: $INSTALL_DIR"
- else
- info "克隆仓库…"
- run mkdir -p "$(dirname "$INSTALL_DIR")"
- if [[ "$DRY_RUN" == "1" ]]; then
- printf ' [dry-run] git clone --depth 1 --branch %s %s %s\n' "$BRANCH" "$REPO" "$INSTALL_DIR"
- elif ! git clone --depth 1 --branch "$BRANCH" "$REPO" "$INSTALL_DIR"; then
- if [[ "$REPO" == *"github.com"* ]]; then
- MIRROR_REPO="https://ghfast.top/${REPO}"
- warn "从 GitHub 直连克隆失败,尝试加速镜像: $MIRROR_REPO"
- git clone --depth 1 --branch "$BRANCH" "$MIRROR_REPO" "$INSTALL_DIR" \
- || die "克隆失败(含镜像)。受限网络可:git clone --depth 1 $REPO $INSTALL_DIR 后重跑本脚本"
- else
- die "克隆失败。检查网络,或设置 ARGO_REPO 指向可达镜像"
- fi
- fi
- ok "仓库就绪"
- fi
- # 供应链加固:校验 HEAD 与预期 commit 一致(ARGO_PIN 固定时)
- if [[ -n "$PIN" ]]; then
- ACTUAL_HEAD=$(git -C "$INSTALL_DIR" rev-parse HEAD 2>/dev/null || echo "unknown")
- [[ "$ACTUAL_HEAD" == "$PIN" ]] || die "供应链校验失败:固定 commit 为 ${PIN},实际 HEAD 为 ${ACTUAL_HEAD}。仓库内容与预期不一致,拒绝继续"
- ok "供应链校验通过: HEAD=$PIN"
- fi
- # ── 2. 依赖安装 ───────────────────────────────────────────────────────────────
- # 装进 $INSTALL_DIR/.venv(bin/argo 的解释器候选链会自动发现它,见 _venv_python)。
- # 为什么必须 venv:PEP 668(Homebrew、Debian 12+、Ubuntu 23.04+)把系统 Python
- # 标记为 externally-managed,`pip install --user` 与全局安装都会被拒。venv 是解释器
- # 自己管的目录,不受该限制,也不污染用户 site-packages。
- #
- # 两条路径,优先 uv(解释器版本读 .python-version、依赖读 uv.lock,与 CI 完全一致):
- # 有 uv:uv venv + uv sync --frozen --group dev
- # 无 uv:python3 -m venv + pip install(回落)
- pinned_python() {
- local v="3.12"
- if [[ -f "$INSTALL_DIR/.python-version" ]]; then
- read -r v < "$INSTALL_DIR/.python-version" || v="3.12"
- v="${v//$'\r'/}"
- v="${v//$'\n'/}"
- fi
- printf '%s' "$v"
- }
- install_deps_with_uv() {
- local venv_dir="$INSTALL_DIR/.venv"
- local pinned
- pinned="$(pinned_python)"
- info "用 uv 按 .python-version(${pinned})+ uv.lock 同步环境…"
- # 显式传 --python,不能只靠 .python-version:环境变量 UV_PYTHON 会覆盖它
- # (实测本机 UV_PYTHON 指向 3.15 时,建对 3.14 的 venv 后 sync 会换成 3.15)。
- if [[ "$DRY_RUN" == "1" ]]; then
- printf ' [dry-run] uv venv %s --python %s\n' "$venv_dir" "$pinned"
- printf ' [dry-run] uv sync --frozen --group dev --python %s\n' "$pinned"
- return 0
- fi
- # venv 已存在时 uv venv 会直接报错退出(实测 exit=2,提示加 --clear)。
- # 安装场景下 venv 存在是常态(用户重跑安装),不该报错——存在就跳过创建,
- # 交给 uv sync 补齐(sync 对已存在的 venv 是增量更新)。
- if [[ ! -x "$venv_dir/bin/python" ]]; then
- uv venv "$venv_dir" --python "$pinned" >/dev/null 2>&1 || return 1
- fi
- uv sync --frozen --group dev --python "$pinned" >/dev/null 2>&1 || return 1
- # uv sync 的盲区:它只对照 lock 与 venv 的「已装记录」,不对照磁盘真实状态。
- # 手工 `pip uninstall pyyaml` 后 uv sync 报「Checked 17 packages」但包仍缺
- # (实测)。所以装完必须真 import 一次,缺则 --reinstall 强制重建。
- if ! "$venv_dir/bin/python" -c 'import yaml' >/dev/null 2>&1; then
- warn "uv sync 未补齐依赖(venv 记录与磁盘不一致),强制重装…"
- uv sync --frozen --group dev --python "$pinned" --reinstall >/dev/null 2>&1 || return 1
- fi
- ok "依赖就绪(解释器 $("$venv_dir/bin/python" --version 2>&1))"
- }
- install_deps_with_pip() {
- local venv_dir="$INSTALL_DIR/.venv"
- if [[ "$DRY_RUN" == "1" ]]; then
- printf ' [dry-run] python3 -m venv %s\n' "$venv_dir"
- printf ' [dry-run] %s/bin/pip install pyyaml curl_cffi rapidfuzz\n' "$venv_dir"
- return 0
- fi
- if python3 -m venv "$venv_dir" 2>/dev/null; then
- info "创建虚拟环境: ${venv_dir}(依赖装在这里,不碰系统 Python)"
- "$venv_dir/bin/pip" install -q pyyaml \
- || warn "venv 内 PyYAML 安装失败,可手动: $venv_dir/bin/pip install pyyaml"
- info "安装可选增强 (curl_cffi: TLS 指纹伪造;rapidfuzz: 去重模糊近重复复核)…"
- "$venv_dir/bin/pip" install -q curl_cffi rapidfuzz 2>/dev/null \
- || warn "可选增强安装失败(不影响核心功能);需要时手动: $venv_dir/bin/pip install curl_cffi rapidfuzz"
- ok "依赖就绪(解释器 $("$venv_dir/bin/python" --version 2>&1))"
- else
- warn "venv 创建失败(Debian/Ubuntu 需先 sudo apt install python3-venv),回退系统 pip 安装…"
- # PEP 668 下这段大概率三连败,但保留给非 PEP 668 的老系统。
- python3 -m pip install --user -q pyyaml 2>/dev/null \
- || python3 -m pip install -q pyyaml 2>/dev/null \
- || python3 -m pip install --user -q -i https://pypi.tuna.tsinghua.edu.cn/simple pyyaml 2>/dev/null \
- || warn "pip 安装 PyYAML 失败(PEP 668 环境属预期)。手动出路: python3 -m venv $venv_dir && $venv_dir/bin/pip install pyyaml"
- python3 -m pip install --user -q curl_cffi 2>/dev/null || python3 -m pip install -q curl_cffi 2>/dev/null || true
- python3 -m pip install --user -q rapidfuzz 2>/dev/null || python3 -m pip install -q rapidfuzz 2>/dev/null || true
- fi
- }
- if [[ "$SKIP_PIP" != "1" ]]; then
- if command -v uv >/dev/null 2>&1; then
- install_deps_with_uv || { warn "uv sync 失败,回退 python3 -m venv + pip…"; rm -rf "$INSTALL_DIR/.venv"; install_deps_with_pip; }
- else
- install_deps_with_pip
- fi
- fi
- # ── 3. pre-commit 门禁 hook ───────────────────────────────────────────────────
- # 调度器形态(2026-11-08 改):hooks/pre-commit 先跑用户原有 hook(pre-commit.user,
- # 内容不动),失败即中止;再直接跑仓内 scripts/pre-commit(不拷贝,始终是当前版本)。
- # 旧版两种形态都会静默失效:追加行在以 exit 0 结尾的 hook 后永远跑不到;拷贝件
- # 不随仓内门禁更新。
- install_hook_dispatcher() {
- [[ -d "$INSTALL_DIR/.git" || -f "$INSTALL_DIR/.git" ]] || return 0
- local _common _hooks _hook
- _common=$(cd "$INSTALL_DIR" && git rev-parse --git-common-dir 2>/dev/null || true)
- case "$_common" in
- /*) _hooks="$_common/hooks" ;;
- "") return 0 ;;
- *) _hooks="$INSTALL_DIR/$_common/hooks" ;;
- esac
- [[ -d "$_hooks" ]] || return 0
- _hook="$_hooks/pre-commit"
- if [[ "$DRY_RUN" == "1" ]]; then
- printf ' [dry-run] install pre-commit dispatcher into %s\n' "$_hooks"
- return 0
- fi
- mkdir -p "$_hooks"
- if [[ -f "$_hook" ]] && grep -qF "# argo-hook-dispatcher v2" "$_hook"; then
- ok "pre-commit 调度器已就位(无需重装)"
- return 0
- fi
- # 清理 argo 自产旧 hook:新版带标记;旧版 cp 件头行是「argo 提交前快门禁」。
- # 旧模式串与真实头行不符会导致分支永不命中(2026-11-08 审查修复)。
- if [[ -f "$_hook" ]] && { grep -qF "# argo-managed-hook" "$_hook" || grep -q "^# argo 提交前快门禁" "$_hook"; }; then
- rm -f "$_hook"
- elif [[ -f "$_hook" ]] && ! grep -q "pre-commit-argo" "$_hook"; then
- mv "$_hook" "$_hooks/pre-commit.user"
- elif [[ -f "$_hook" ]]; then
- # 旧版向用户 hook 末尾追加过调用行:剥离那两行,保留其余内容
- { grep -v -e "pre-commit-argo" -e "# argo 快门禁(2026-10-17 追加" "$_hook" || true; } > "$_hooks/pre-commit.user"
- if grep -qE '^[[:space:]]*[^#[:space:]]' "$_hooks/pre-commit.user"; then
- chmod +x "$_hooks/pre-commit.user"
- else
- rm -f "$_hooks/pre-commit.user"
- fi
- rm -f "$_hook"
- fi
- rm -f "$_hooks/pre-commit-argo"
- cat > "$_hook" <<'ARGO_HOOK_EOF'
- #!/bin/sh
- # argo-hook-dispatcher v2(由 argo scripts/install.sh 生成)
- # 1) 用户原有 hook(pre-commit.user)先跑,非 0 即中止
- # 2) 再跑仓内 scripts/pre-commit 快门禁(直接调用,不拷贝,始终是当前版本)
- here=$(cd "$(dirname "$0")" && pwd)
- if [ -x "$here/pre-commit.user" ]; then
- "$here/pre-commit.user" "$@" || exit $?
- fi
- root=$(git rev-parse --show-toplevel 2>/dev/null) || exit 1
- if [ -f "$root/scripts/pre-commit" ]; then
- exec sh "$root/scripts/pre-commit" "$@"
- fi
- exit 0
- ARGO_HOOK_EOF
- chmod +x "$_hook"
- ok "已装 pre-commit 调度器(原有 hook 保留为 pre-commit.user;git commit --no-verify 可跳过)"
- }
- install_hook_dispatcher
- # ── 4. Skill 入口链接 ─────────────────────────────────────────────────────────
- # 符号链接回真源,不复制代码——改源码即生效,不产生副本漂移。
- if [[ ${#LINK_ARGS[@]} -gt 0 || -n "${ARGO_LINK_TARGETS:-}" || -f "$INSTALL_DIR/installs.local.yaml" ]]; then
- info "链接 Skill 入口(符号链接回真源,不复制)…"
- run python3 "$INSTALL_DIR/scripts/link_source.py" "${LINK_ARGS[@]+"${LINK_ARGS[@]}"}" \
- || warn "链接未完成。可稍后手动: python3 $INSTALL_DIR/scripts/link_source.py --to ~/.claude/skills/argo"
- fi
- # ── 5. 安装后验证 ─────────────────────────────────────────────────────────────
- # 用 venv 的 python 真 import 一次,把「装好了但跑不起来」挡在安装时。
- RUN_PY="python3"
- [[ -x "$INSTALL_DIR/.venv/bin/python" ]] && RUN_PY="$INSTALL_DIR/.venv/bin/python"
- if [[ "$SKIP_PIP" != "1" && -x "$INSTALL_DIR/.venv/bin/python" ]]; then
- if "$INSTALL_DIR/.venv/bin/python" -c 'import yaml' >/dev/null 2>&1; then
- ok "依赖自检通过(PyYAML 可用)"
- else
- warn "venv 内 PyYAML 不可用。手动修复: $INSTALL_DIR/.venv/bin/pip install pyyaml"
- fi
- fi
- # ── 完成输出 ──────────────────────────────────────────────────────────────────
- echo ""
- echo "==> 安装完成"
- echo ""
- echo "快速验证:"
- echo " $RUN_PY $INSTALL_DIR/scripts/search.py \"Python asyncio\" --json"
- echo " $RUN_PY $INSTALL_DIR/scripts/search.py --list-engines"
- echo ""
- echo "启动 MCP(给 Claude / Kimi / Cursor 等用):"
- echo " $RUN_PY $INSTALL_DIR/scripts/mcp_server.py"
- echo ""
- echo "或用 npx(需 Node.js 18+):"
- echo " npx -y github:taxueseek/argo"
- echo ""
- echo "客户端 MCP 配置示例(路径请按本机替换):"
- cat <<EOF
- {
- "mcpServers": {
- "argo": {
- "command": "$RUN_PY",
- "args": ["$INSTALL_DIR/scripts/mcp_server.py"]
- }
- }
- }
- EOF
- echo ""
- echo "可选:把 Skill 挂到本机 Agent 目录(不复制代码):"
- echo " $RUN_PY $INSTALL_DIR/scripts/link_source.py --to ~/.claude/skills/argo"
- echo " $RUN_PY $INSTALL_DIR/scripts/link_source.py --to ~/.agents/skills/argo"
- echo ""
- echo "卸载: bash scripts/install.sh --uninstall"
- echo "文档: https://github.com/taxueseek/argo"
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.