Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

feat: 2.0 install: one skill copy + links, bilibili default, uv only, browser auto open/close; drop watch, doctor --live, browser start

Pnant1d3e1a568c63
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15081553..dafee22a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,24 +14,27 @@ v2 是重构版本:Agent 只调一个命令 `agent-reach`,Agent Reach 装的
### ✨ New / 新增
- **Unified entry / 统一入口**: `agent-reach <channel> <action>`, `agent-reach read <url>`, `agent-reach channels`. One JSON envelope per call, unified error codes with hints, per-call timeout, automatic fallback to the next backend.
-- **Management / 管理命令**: `setup`, `add` / `remove <channel>`, `login` / `logout <channel>`, `doctor`, `check`, `watch`, `update`, `configure`, `uninstall`.
+- **Management / 管理命令**: `setup`, `add` / `remove <channel>`, `login` / `logout <channel>`, `doctor`, `check`, `skill`, `skill link <dir>`, `update`, `configure`, `uninstall`.
+- **One-step setup / 一步装好**: `setup` adds every default channel through the same path as `add` (bili-cli goes into `~/.agent-reach/tools/`) and reports what works, which AIs can read the skill, optional channels and optional logins. / `setup` 用和 `add` 同一套逻辑开启全部默认渠道,并汇报哪些能用、哪些 AI 能读到 skill、可选渠道和可选登录。
+- **Skill placement / skill 放置**: one real copy at `~/.agents/skills/agent-reach/SKILL.md` (read directly by Codex, OpenCode, Cline, Warp, Zed); a link to it in the skill folder of Claude Code, OpenClaw, Hermes, Cursor, Gemini CLI, GitHub Copilot and Windsurf when installed (a copy where links are not allowed, e.g. Windows). `agent-reach skill link <dir>` covers any other AI. / 只放一份真文件,其他 AI 的 skill 目录里放指向它的链接(链接:一个指向原文件的快捷方式)。
- **Private, pinned upstream installs / 上游私有安装**: tools go into `~/.agent-reach/tools/` at versions we tested; the user's own copies are untouched. Single-instance tools (OpenCLI) reuse the user's copy and are upgraded only with `--allow-upgrade`.
-- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser (`agent-reach browser setup`). Agent Reach never logs in for the user and never reads the user's own browser cookies.
-- **doctor states / 体检**: not_added, needs_setup, needs_login, unverified, ready, broken. `watch` reports only what broke since the last check.
-- **update** upgrades the program with its original installer, syncs tools to pinned versions and refreshes the agent skill. Pre-2.0 installs are migrated on first `setup` / `update`; `config.yaml` keys are kept.
+- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser (`agent-reach browser setup` once). The browser opens by itself when a channel needs it and closes after 10 minutes without use. Agent Reach never logs in for the user and never reads the user's own browser cookies. / 专用浏览器按需自动打开,10 分钟不用自动关闭。
+- **doctor states / 体检**: not_added, needs_setup, needs_login, unverified, ready, broken; plus `regressed` per channel (passed in the previous check, fails in the latest).
+- **update** runs `uv tool install --force` on the latest release, syncs tools to pinned versions and refreshes the skill. uv is the only supported installer. Pre-2.0 installs are migrated on first `setup` / `update`; `config.yaml` keys are kept.
- Xueqiu quotes and stock search via Tencent public quotes (no login); Xueqiu community data uses a session the user imports with `agent-reach login xueqiu --sync`.
- YouTube `transcribe`; LinkedIn uses its own MCP registration in `~/.agent-reach/mcporter.json`.
### 🔄 Changed / 变更
-- Default channels: web (fallback only), YouTube, GitHub, V2EX. Optional: 小红书, B站, Reddit, LinkedIn, Boss直聘, 小宇宙, 雪球. Experimental: Twitter, Facebook, Instagram.
+- Default channels: web (fallback only), YouTube, GitHub, V2EX, B站. Optional: 小红书, Reddit, LinkedIn, Boss直聘, 小宇宙, 雪球. Experimental: Twitter, Facebook, Instagram.
- The agent skill is generated from the channel list and replaced on every update.
### 🗑️ Removed / 移除
- RSS channel (agents read feeds themselves).
- xhs-cli, rdt-cli, twitter-cli backends: they read browser cookies by themselves.
-- `configure --from-browser`, `twitter-cookies`, `xhs-cookies`, the old `install --channels`, `skill`, `format`, `check-update`, MCP server entry.
+- `configure --from-browser`, `twitter-cookies`, `xhs-cookies`, the old `install --channels`, the old `skill --install`, `format`, `check-update`, MCP server entry.
+- `watch` (use `doctor`, which now reports `regressed`), `doctor --live` (use `check`), `browser start` (the browser opens by itself), pipx installs.
### 🐛 Bug Fixes / 修复
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 42855c9e..96bf2be0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -40,6 +40,16 @@ Rules:
- Everything a channel stores lives under `~/.agent-reach/`.
- Don't install anything globally; add the tool to `runtime.tools.TOOLS` with a pinned version.
+## Dependency locking
+
+Use `constraints.txt` with the development install to keep local and CI dependencies reproducible:
+
+```bash
+python -m pip install -c constraints.txt -e ".[dev]"
+```
+
+When changing dependency ranges, validate compatible versions, update the pinned entries in `constraints.txt`, then run `pytest -q`, `ruff check agent_reach tests`, and `mypy agent_reach`. Include dependency and validation notes in the pull request.
+
## Before merging a channel
A new or changed channel must pass a live check on your machine:
diff --git a/README.md b/README.md
index efbbb2de..e5feaa55 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ agent-reach read https://www.v2ex.com/t/123 # 按链接自动选渠道
### ✅ 在你用之前,你可能想知道
-- **适用于哪些 Agent?** 任何能执行命令行的 Agent。`agent-reach setup` 会把使用说明(skill)装进 Claude Code、Codex、OpenCode、OpenClaw 等的 skill 目录。
+- **适用于哪些 Agent?** 任何能执行命令行的 Agent。`agent-reach setup` 会放一份使用说明(skill,就是告诉 AI 怎么用 Agent Reach 的说明文件),Codex、OpenCode 等直接能读到;Claude Code、OpenClaw、Cursor 等装了的话,会在它们的 skill 目录里放一个指向这份说明的链接(相当于快捷方式)。
- **要花钱吗?** 程序和后端工具都是开源免费的。只有两处可能要你自己的 Key:播客/视频转文字用 Groq(有免费额度)或 OpenAI 的 Whisper 接口。
- **会碰我的浏览器和账号吗?** 不会读你自己浏览器里的 Cookie,也从不替你登录。需要登录的渠道,由你本人在 Agent Reach 专用浏览器里登录。详见[安全性](#安全性)。
- **支持哪些系统?** 优先保证 macOS,Linux 可用,Windows 尽力支持。
@@ -95,8 +95,8 @@ agent-reach read https://www.v2ex.com/t/123 # 按链接自动选渠道
| youtube | 默认 | 视频信息、搜索、字幕、语音转文字 | 无;转文字需要 Groq 或 OpenAI Key |
| v2ex | 默认 | 热门、节点、帖子和回复、用户 | 无 |
| web | 默认 | 网页搜索、网页阅读(保底) | 无 |
+| bilibili | 默认 | 搜索、视频信息、热门、字幕 | 无;字幕需要登录(扫码) |
| xiaohongshu | 可选 | 搜笔记、读笔记 | 浏览器 + 登录 |
-| bilibili | 可选 | 搜索、视频信息、热门、字幕 | 字幕需要登录(扫码) |
| reddit | 可选 | 搜索、读帖子和评论、看版块 | 浏览器 + 登录 |
| linkedin | 可选 | 搜职位 | 登录(需要 Node.js 和 uv) |
| boss | 可选 | 搜职位和 JD | 浏览器 + 登录(需要 git) |
@@ -109,7 +109,7 @@ agent-reach read https://www.v2ex.com/t/123 # 按链接自动选渠道
- **默认**:装好就能用。
- **可选**:用 `agent-reach add <渠道>` 按需开启,Agent Reach 会把它要的工具装到自己的目录里。
- **实验**:能用,但平台反爬更严,可能随时失效。
-- **浏览器**:指 Agent Reach 专用浏览器,一个独立的 Chrome 窗口(需要已安装 Google Chrome 和 Node.js),第一次用要在里面装一个 OpenCLI 扩展,`agent-reach browser setup` 会带你完成。
+- **浏览器**:指 Agent Reach 专用浏览器,一个独立的 Chrome 窗口(需要已安装 Google Chrome 和 Node.js)。第一次用要在里面装一个 OpenCLI 扩展,`agent-reach browser setup` 会带你完成。之后需要时它会自己打开(第一次打开大约要 40 秒),10 分钟没用就自动关掉。
---
@@ -121,14 +121,18 @@ agent-reach read https://www.v2ex.com/t/123 # 按链接自动选渠道
帮我安装 Agent Reach:https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/install.md
```
-Agent 会照着 [install.md](docs/install.md) 做完这几步:
+剩下的 Agent 会照着 [install.md](docs/install.md) 自己做完。过程中你可能会被问到:
-1. 安装程序:`uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip`
-2. 运行 `agent-reach setup`:检查环境,把使用说明装进 Agent 的 skill 目录
-3. 把可选渠道列给你,你选要哪些,它运行 `agent-reach add <渠道>`
-4. 需要登录的渠道,它运行 `agent-reach login <渠道>` 打开登录页,**由你本人登录**
+- **允许它执行命令**:如果 Agent 说自己不能运行命令,去它的设置里打开"允许执行命令"。
+- **装 uv**:uv 是一个安装命令行程序的小工具,不需要管理员密码。电脑上没有的话 Agent 会先装它,会跟你说一声。
+- **要不要加可选渠道**:装完后 Agent 会告诉你哪些已经能用(网页、YouTube、GitHub、V2EX、B站),以及还能加哪些、各自需要什么。你选了再加,也可以以后随时说"帮我加上小红书"。
-> ⚠️ PyPI 上叫 `agent-reach` 的包不是本项目,请勿从 PyPI 安装,只用上面的 GitHub 地址。
+需要你本人做的只有登录,Agent 从不替你登录,也不会要你的密码:
+
+- 小红书、Reddit、Twitter 等:在 Agent Reach 专用浏览器里自己登录。
+- B站:字幕要扫码登录;不登录也能搜索和看视频信息。
+
+> ⚠️ PyPI 上叫 `agent-reach` 的包不是本项目,请勿从 PyPI 安装,只用 install.md 里的 GitHub 地址。
想自己动手也一样,照着 [install.md](docs/install.md) 敲命令就行。
@@ -145,19 +149,20 @@ flowchart LR
---
-## 装好就能用
+## 装好之后怎么管
+
+直接用大白话跟 Agent 说就行,它会替你运行对应的命令:
-装好后,日常只会用到这几条(大多由 Agent 替你运行):
+| 你说 | Agent 运行 | 作用 |
+|---|---|---|
+| "看看 Agent Reach 状态" | `agent-reach doctor --text` | 每个渠道的状态:未开启 / 待配置 / 待登录 / 未验证 / 可用 / 故障,并标出"上次还好、现在坏了"的渠道 |
+| "加上小红书" / "去掉小红书" | `agent-reach add` / `remove <渠道>` | 开启 / 关闭渠道,加完再 `agent-reach login <渠道>` |
+| "B站登录过期了" / "退出登录" | `agent-reach login` / `logout <渠道>` | 登录(你本人操作)/ 清除登录 |
+| "升级 Agent Reach" | `agent-reach update` | 一次更新程序、后端工具和 skill,见 [update.md](docs/update.md) |
+| "卸载 Agent Reach" | `agent-reach uninstall` | 见下面"安全性"里的卸载说明 |
+| "让另一个 AI 也能用" | `agent-reach skill link <它的 skill 目录>` | 给不在自动名单里的 AI 也放一个说明链接 |
-| 命令 | 作用 |
-|---|---|
-| `agent-reach doctor --text` | 看每个渠道的状态:未开启 / 待配置 / 待登录 / 未验证 / 可用 / 故障 |
-| `agent-reach check [渠道] --text` | 真实跑一遍测试,确认渠道能用 |
-| `agent-reach watch --text` | 只报告"上次还好、现在坏了"的渠道,以及有没有新版本 |
-| `agent-reach update` | 一次更新程序、后端工具和 skill,见 [update.md](docs/update.md) |
-| `agent-reach add` / `remove <渠道>` | 开启 / 关闭可选渠道 |
-| `agent-reach login` / `logout <渠道>` | 登录(你本人操作)/ 清除登录 |
-| `agent-reach configure <项> [值]` | 保存 `groq-key`、`openai-key`、`proxy`、`github-token` |
+其他:`agent-reach check [渠道] --text` 真实跑一遍测试;`agent-reach configure <项>` 保存 `groq-key`、`openai-key`、`proxy`、`github-token`。
出错时,JSON 里的 `error.code` 会告诉 Agent 下一步该做什么。每种错误和状态的处理办法见 [troubleshooting.md](docs/troubleshooting.md)。
@@ -194,9 +199,9 @@ Agent Reach 装的工具(OpenCLI、bili-cli、boss-agent-cli、mcporter)都
## 安全性
-- **所有东西都在 `~/.agent-reach/` 下**:`config.yaml`(Key 和代理)、`state.json`、`tools/`(私有工具)、`sessions/`(命令行工具的登录状态)、`browser/`(专用浏览器的资料目录)、`mcporter.json`。
+- **所有东西都在 `~/.agent-reach/` 下**:`config.yaml`(Key 和代理)、`state.json`、`tools/`(私有工具)、`sessions/`(命令行工具的登录状态)、`browser/`(专用浏览器的资料目录)、`mcporter.json`。唯一例外是使用说明:一份放在 `~/.agents/skills/agent-reach/`,其他 AI 的 skill 目录里只放指向它的链接。
- **从不替你登录,也不读你自己浏览器的 Cookie。** 需要登录的渠道,由你本人在 Agent Reach 专用浏览器或工具自己的登录流程(比如 B站扫码)里完成。
-- **专用浏览器的调试端口只监听本机**(127.0.0.1:9222),但本机任何程序都能通过它控制这个浏览器。不用的时候请关掉那个窗口。
+- **专用浏览器的调试端口只监听本机**(127.0.0.1:9222),但它开着时本机任何程序都能通过它控制这个浏览器。所以它 10 分钟没用就会自动关掉。
- **建议用小号登录。** 平台可能限制自动化访问的账号,别拿主账号冒险。
- **API Key 不要发在聊天里**:在你自己的终端运行 `agent-reach configure groq-key`,会隐藏输入。
diff --git a/agent_reach/channels/mcporter.py b/agent_reach/backends/mcporter.py
similarity index 100%
rename from agent_reach/channels/mcporter.py
rename to agent_reach/backends/mcporter.py
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.py
index 689e5817..89f9edd5 100644
--- a/agent_reach/backends/opencli.py
+++ b/agent_reach/backends/opencli.py
@@ -43,7 +43,10 @@ def _opencli_error(text: str, login_hint: str):
def _dedicated_profile_env() -> dict:
- """OPENCLI_PROFILE for the Agent Reach browser; fail fast instead of letting OpenCLI hang."""
+ """OPENCLI_PROFILE for the Agent Reach browser, opening the browser if it is closed.
+
+ Fails fast with NEED_SETUP when the browser was never set up, instead of letting OpenCLI hang.
+ """
from agent_reach.runtime import browser
from agent_reach.runtime.result import NEED_SETUP, ReachError
@@ -53,16 +56,7 @@ def _dedicated_profile_env() -> dict:
NEED_SETUP, "the Agent Reach browser is not set up",
hint="Ask the user to run `agent-reach browser setup` and install the OpenCLI extension in the window it opens.",
)
- if not browser.is_running():
- raise ReachError(
- NEED_SETUP, "the Agent Reach browser is not running",
- hint="Run `agent-reach browser start` (or ask the user to), then retry.",
- )
- if ctx not in browser.connected_contexts():
- raise ReachError(
- NEED_SETUP, "the Agent Reach browser is running but OpenCLI is not connected to it",
- hint="Ask the user to check the OpenCLI extension is enabled in the Agent Reach browser window.",
- )
+ browser.ensure_running(ctx)
return {"OPENCLI_PROFILE": ctx}
diff --git a/agent_reach/channels/bilibili.py b/agent_reach/channels/bilibili.py
index 98b592a7..82ac99a9 100644
--- a/agent_reach/channels/bilibili.py
+++ b/agent_reach/channels/bilibili.py
@@ -120,7 +120,7 @@ class BilibiliChannel(Channel):
name = "bilibili"
description = "B站视频、字幕和搜索"
- level = "optional"
+ level = "default"
session = "bili-cli"
login_argv = ("bili", "login")
legacy_state = (".bilibili-cli",)
diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.py
index 37951eba..a798188a 100644
--- a/agent_reach/channels/boss.py
+++ b/agent_reach/channels/boss.py
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
"""Boss直聘 — boss-agent-cli drives the Agent Reach browser over CDP (127.0.0.1:9222).
-headless is off-limits (triggers code 36 risk control), so search only runs
-against the already-running Agent Reach browser with the user's own login.
+headless is off-limits (triggers code 36 risk control), so search runs against
+the Agent Reach browser with the user's own login (opened on demand).
Two login stores, both required:
- the session under ~/.agent-reach/sessions/boss-agent-cli/ (`boss login --cdp`
@@ -12,7 +12,6 @@ Two login stores, both required:
"""
import json
-import socket
from agent_reach.runtime.result import (
NEED_LOGIN,
@@ -61,15 +60,15 @@ class BossChannel(Channel):
# ── unified entry backends ──
def _cli_search(self, *, query: str, city, limit: int, timeout: float) -> list:
- with socket.socket() as s:
- s.settimeout(1)
- cdp_up = s.connect_ex(("127.0.0.1", 9222)) == 0
- if not cdp_up:
+ from agent_reach.runtime import browser
+
+ if not (browser.is_running() or browser.profile_dir().is_dir()):
raise ReachError(
NEED_SETUP,
- "the Agent Reach browser (port 9222) is not running",
+ "the Agent Reach browser has never been opened",
hint="Run `agent-reach login boss`, let the user log in to zhipin.com in that window, then run `agent-reach login boss --sync`.",
)
+ browser.ensure_running()
args = ["boss", "--json", "--browser-source", "existing-browser", "--cdp-url", _CDP_URL, "search", query]
if city:
args += ["--city", city]
diff --git a/agent_reach/channels/linkedin.py b/agent_reach/channels/linkedin.py
index 6a088e62..5298c9f7 100644
--- a/agent_reach/channels/linkedin.py
+++ b/agent_reach/channels/linkedin.py
@@ -3,11 +3,11 @@
import json
+from agent_reach.backends.mcporter import configured_server_names
from agent_reach.runtime.result import NEED_SETUP, UPSTREAM_BROKEN, ReachError, make_item
from agent_reach.runtime.run import CommandFailed, run_cmd
from .base import Action, Channel, Param
-from .mcporter import configured_server_names
_LINKEDIN_MCP_VERSION = "4.26.2"
diff --git a/agent_reach/config.py b/agent_reach/config.py
index 49b7c845..510b5746 100644
--- a/agent_reach/config.py
+++ b/agent_reach/config.py
@@ -102,14 +102,6 @@ class Config:
CONFIG_DIR = home_dir() / ".agent-reach"
CONFIG_FILE = CONFIG_DIR / "config.yaml"
- # Feature → required config keys
- FEATURE_REQUIREMENTS = {
- "exa_search": ["exa_api_key"],
- "twitter_xreach": ["twitter_auth_token", "twitter_ct0"], # legacy key name; used by twitter-cli
- "groq_whisper": ["groq_api_key"],
- "openai_whisper": ["openai_api_key"],
- "github_token": ["github_token"],
- }
def __init__(
self,
@@ -196,38 +188,3 @@ class Config:
self.data[key] = previous
raise
- def is_configured(self, feature: str) -> bool:
- """Check if a feature has all required config."""
- required = self.FEATURE_REQUIREMENTS.get(feature, [])
- return all(self.get(k) for k in required)
-
- def get_configured_features(self) -> dict:
- """Return status of all optional features."""
- return {
- feature: self.is_configured(feature)
- for feature in self.FEATURE_REQUIREMENTS
- }
-
- def to_dict(self) -> dict:
- """Return config as dict (masks sensitive values)."""
- sensitive_markers = (
- "key",
- "token",
- "password",
- "proxy",
- "cookie",
- "secret",
- "session",
- "sessdata",
- "csrf",
- "auth",
- "cred",
- "ct0",
- )
- masked = {}
- for k, v in self.data.items():
- if any(s in k.lower() for s in sensitive_markers):
- masked[k] = "[REDACTED]" if v else None
- else:
- masked[k] = v
- return masked
diff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.py
index f1404b3e..8dee242e 100644
--- a/agent_reach/runtime/browser.py
+++ b/agent_reach/runtime/browser.py
@@ -6,12 +6,19 @@ installs the OpenCLI extension in it once; `agent-reach browser setup` then
records which OpenCLI profile it is (~/.agent-reach/browser/state.json).
The user's own ~/.opencli settings are never modified.
+Browser channels open it on demand (`ensure_running`). Every Agent Reach use
+touches ~/.agent-reach/browser/last_used; when Agent Reach launches the
+browser it also starts one detached watcher (runtime.browser_watcher) that
+closes the browser after IDLE_LIMIT seconds without use and exits when the
+browser is gone.
+
Debugging is bound to 127.0.0.1:9222 only. Any local process that can reach
-that port can control this browser; close it when not in use.
+that port can control this browser; that is why it closes when idle.
"""
from __future__ import annotations
+import contextlib
import json
import os
import platform
@@ -19,10 +26,12 @@ import re
import shutil
import socket
import subprocess
+import sys
+import time
import urllib.parse
import urllib.request
from pathlib import Path
-from typing import List, Optional
+from typing import Callable, Iterator, List, Optional
from agent_reach.utils.paths import (
PrivatePathError,
@@ -36,6 +45,14 @@ CDP_PORT = 9222
CDP_URL = f"http://127.0.0.1:{CDP_PORT}"
_CONTEXT_RE = re.compile(r"^\s*(\S+)\s+[—-]\s+connected\b", re.M)
+#: Close the browser after this many seconds without Agent Reach use.
+IDLE_LIMIT = 600.0
+#: Longest wait for a cold start (measured ~42 s to OpenCLI connect on a Mac).
+START_WAIT = 90.0
+#: Extra wait for a browser that has been up longer than START_WAIT.
+_RUNNING_GRACE = 5.0
+_LOCK_WAIT = START_WAIT + 30.0
+
def browser_root() -> Path:
return home_dir() / ".agent-reach" / "browser"
@@ -49,6 +66,18 @@ def _state_path() -> Path:
return browser_root() / "state.json"
+def _last_used_path() -> Path:
+ return browser_root() / "last_used"
+
+
+def _start_lock_path() -> Path:
+ return browser_root() / "start.lock"
+
+
+def watcher_lock_path() -> Path:
+ return browser_root() / "watcher.lock"
+
+
def _load_state() -> dict:
try:
text = read_small_text_no_follow(_state_path(), max_bytes=64 * 1024)
@@ -65,6 +94,83 @@ def _save_state(state: dict) -> None:
atomic_write_private_text(_state_path(), json.dumps(state, indent=2))
+# ── last use ──
+
+
+def touch() -> None:
+ """Record an Agent Reach use of the browser (resets the idle timer)."""
+ make_private_dir(browser_root())
+ path = _last_used_path()
+ if not path.exists():
+ atomic_write_private_text(path, "")
+ os.utime(path)
+
+
+def last_used() -> Optional[float]:
+ try:
+ return _last_used_path().stat().st_mtime
+ except OSError:
+ return None
+
+
+# ── cross-process locks ──
+
+
+def _open_lock(path: Path) -> int:
+ make_private_dir(path.parent)
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
+ return os.open(path, flags, 0o600)
+
+
+def try_lock(fd: int) -> bool:
+ """Take an exclusive lock on `fd` without blocking."""
+ try:
+ if os.name == "nt":
+ import msvcrt
+
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return False
+ return True
+
+
+def _locked(path: Path, wait: float) -> Iterator[None]:
+ """Hold an exclusive lock on `path`; ReachError after `wait` seconds."""
+ fd = _open_lock(path)
+ try:
+ deadline = time.monotonic() + wait
+ while not try_lock(fd):
+ if time.monotonic() >= deadline:
+ from .result import UPSTREAM_BROKEN, ReachError
+
+ raise ReachError(UPSTREAM_BROKEN, "another Agent Reach process is still starting the browser")
+ time.sleep(0.2)
+ yield
+ finally:
+ os.close(fd) # closing releases the lock
+
+
+def start_lock(wait: float = _LOCK_WAIT):
+ """Serializes launching (and idle-closing) the browser across processes."""
+ return _locked(_start_lock_path(), wait)
+
+
+def watcher_running() -> bool:
+ fd = _open_lock(watcher_lock_path())
+ try:
+ return not try_lock(fd)
+ finally:
+ os.close(fd)
+
+
+# ── process ──
+
+
def chrome_binary() -> Optional[str]:
system = platform.system()
candidates = []
@@ -86,11 +192,8 @@ def is_running() -> bool:
return s.connect_ex(("127.0.0.1", CDP_PORT)) == 0
-def start(url: str = "about:blank") -> None:
- """Launch the dedicated browser if it is not running; otherwise open `url` in it."""
- if is_running():
- open_url(url)
- return
+def _launch(url: str) -> None:
+ """Start Chrome on the dedicated profile, then the idle watcher. Caller holds start_lock()."""
exe = chrome_binary()
if not exe:
from .result import NEED_SETUP, ReachError
@@ -112,6 +215,114 @@ def start(url: str = "about:blank") -> None:
stderr=subprocess.DEVNULL,
start_new_session=(os.name != "nt"),
)
+ state = _load_state()
+ state["started_at"] = time.time()
+ _save_state(state)
+ if not wait_for(is_running, START_WAIT):
+ from .result import UPSTREAM_BROKEN, ReachError
+
+ raise ReachError(UPSTREAM_BROKEN, f"the Agent Reach browser did not open within {START_WAIT:.0f}s")
+ _spawn_watcher()
+
+
+def _spawn_watcher() -> None:
+ """Start the detached idle watcher unless one is already running."""
+ if watcher_running():
+ return
+ kwargs: dict = {}
+ if os.name == "nt":
+ kwargs["creationflags"] = (
+ subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
+ )
+ else:
+ kwargs["start_new_session"] = True
+ subprocess.Popen(
+ [sys.executable, "-m", "agent_reach.runtime.browser_watcher"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ **kwargs,
+ )
+ # Hold start_lock until the watcher owns its lock, so a racing launch sees it.
+ wait_for(watcher_running, 5.0, interval=0.1)
+
+
+def wait_for(check: Callable[[], bool], seconds: float, interval: float = 1.0) -> bool:
+ deadline = time.monotonic() + seconds
+ while True:
+ if check():
+ return True
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(interval)
+
+
+def _remaining_start_wait() -> float:
+ """How long a browser that is open but not ready yet still gets."""
+ started = _load_state().get("started_at") or 0.0
+ return max(_RUNNING_GRACE, started + START_WAIT - time.time())
+
+
+def start(url: str = "about:blank") -> None:
+ """Show `url` in the dedicated browser, launching it if needed (login, setup)."""
+ touch()
+ if is_running():
+ open_url(url)
+ return
+ with start_lock():
+ if is_running():
+ open_url(url)
+ return
+ _launch(url)
+
+
+def ensure_running(context: Optional[str] = None) -> None:
+ """Make the dedicated browser ready for an action, launching it if needed.
+
+ With `context`, also wait until that OpenCLI profile is connected.
+ The wait does not count against the action's --timeout.
+ Raises ReachError when it is not ready within START_WAIT.
+ """
+ from .clock import off_the_clock
+ from .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
+
+ touch()
+
+ def ready() -> bool:
+ return is_running() and (context is None or context in connected_contexts())
+
+ if ready():
+ return
+ with off_the_clock(), start_lock():
+ if not is_running():
+ _launch("about:blank")
+ if not wait_for(ready, _remaining_start_wait()):
+ if not is_running():
+ raise ReachError(UPSTREAM_BROKEN, "the Agent Reach browser closed while starting")
+ raise ReachError(
+ NEED_SETUP, "the Agent Reach browser is running but OpenCLI is not connected to it",
+ hint="Ask the user to check the OpenCLI extension is enabled in the Agent Reach browser window.",
+ )
+ touch()
+
+
+def stop(timeout: float = 10.0) -> bool:
+ """Close the dedicated browser: CDP Browser.close, then terminate. True if it is closed."""
+ if not is_running():
+ return True
+ from . import cdp
+
+ info = cdp.call("SystemInfo.getProcessInfo") or {}
+ pid = next((p.get("id") for p in info.get("processInfo", []) if p.get("type") == "browser"), None)
+ cdp.call("Browser.close")
+ if wait_for(lambda: not is_running(), timeout, interval=0.2):
+ return True
+ if pid:
+ import signal
+
+ with contextlib.suppress(OSError):
+ os.kill(int(pid), signal.SIGTERM)
+ return wait_for(lambda: not is_running(), 5.0, interval=0.2)
def open_url(url: str) -> None:
@@ -121,6 +332,9 @@ def open_url(url: str) -> None:
pass
+# ── OpenCLI binding ──
+
+
def connected_contexts() -> List[str]:
"""OpenCLI Browser Bridge profiles connected right now."""
from .run import run_cmd
@@ -172,6 +386,7 @@ def status() -> dict:
"running": running,
"opencli_context": ctx,
"opencli_connected": connected,
+ "idle_close_after_s": int(IDLE_LIMIT),
}
diff --git a/agent_reach/runtime/browser_watcher.py b/agent_reach/runtime/browser_watcher.py
new file mode 100644
index 00000000..70330ce9
--- /dev/null
+++ b/agent_reach/runtime/browser_watcher.py
@@ -0,0 +1,52 @@
+"""Idle watcher for the Agent Reach browser (`python -m agent_reach.runtime.browser_watcher`).
+
+Started detached by runtime.browser when Agent Reach launches the browser.
+Holds ~/.agent-reach/browser/watcher.lock so only one runs; exits when the
+browser is gone, and closes it after `idle` seconds without Agent Reach use.
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import os
+import time
+from typing import Optional
+
+from . import browser
+
+
+def watch(idle: Optional[float] = None, poll: float = 15.0) -> str:
+ """Run until the browser is gone. Returns why it stopped."""
+ idle = browser.IDLE_LIMIT if idle is None else idle
+ fd = browser._open_lock(browser.watcher_lock_path())
+ try:
+ # A probe (watcher_running) holds the lock for an instant; a live watcher holds it for good.
+ if not browser.wait_for(lambda: browser.try_lock(fd), 2.0, interval=0.1):
+ return "another watcher is running"
+ began = time.time()
+ while True:
+ if not browser.is_running():
+ return "browser closed"
+ used = max(began, browser.last_used() or 0.0)
+ left = used + idle - time.time()
+ if left <= 0:
+ with contextlib.suppress(Exception), browser.start_lock(wait=5.0):
+ used = max(began, browser.last_used() or 0.0)
+ if used + idle <= time.time() and browser.stop():
+ return "closed after idle"
+ left = poll # used again meanwhile, or close failed: check later
+ time.sleep(min(poll, left + 0.5))
+ finally:
+ os.close(fd)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(prog="agent_reach.runtime.browser_watcher")
+ parser.add_argument("--idle", type=float, default=None, help="seconds without use before closing")
+ ns = parser.parse_args()
+ watch(ns.idle)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.py
index fdad621f..c140a75d 100644
--- a/agent_reach/runtime/cli.py
+++ b/agent_reach/runtime/cli.py
@@ -1,12 +1,12 @@
"""Unified entry for Agent Reach.
Agent commands: <channel> <action>, read <url>, channels
-Management commands: setup, add, remove, login, logout, browser, doctor, check,
- watch, update, uninstall, configure, version
+Management commands: setup, add, remove, login, logout, browser, skill, doctor,
+ check, update, uninstall, configure, version
Everything prints one JSON object to stdout so agents never parse prose; logs
go to stderr. Exit code 0 = ok, 1 = error. Exceptions for humans: `help`, and
-`--text` on doctor / check / watch. `login` shows the upstream's interactive
+`--text` on doctor / check. `login` shows the upstream's interactive
output (QR codes, prompts) on stderr so stdout still carries only the JSON.
"""
@@ -36,7 +36,7 @@ from .result import (
from .sessions import clear_session, has_login_state, import_legacy_state, session_env
_MANAGEMENT = (
- "setup", "add", "remove", "update", "doctor", "watch", "uninstall", "configure", "version",
+ "setup", "add", "remove", "update", "doctor", "uninstall", "configure", "version",
)
HELP = """agent-reach — internet access for AI agents (all output is JSON)
@@ -47,13 +47,13 @@ For agents:
agent-reach read <url> read a link with the matching channel
For the user:
- agent-reach setup first run: check prerequisites, install the agent skill
+ agent-reach setup first run: install the default channels and the agent skill
agent-reach add|remove <channel> install / remove an optional channel
agent-reach login|logout <channel> log in (the user does it) / forget the login
- agent-reach browser setup|start|status the Agent Reach browser for browser-login channels
- agent-reach doctor [--live] [--text] status of every channel
+ agent-reach browser setup|status the Agent Reach browser for browser-login channels
+ agent-reach skill [link <skills-dir>] where the agent skill is; link it for another AI
+ agent-reach doctor [--text] status of every channel (no network)
agent-reach check [channel] [--text] live-test channels
- agent-reach watch [--text] report only what broke since last check, and updates
agent-reach update [--check] upgrade Agent Reach, its tools and the skill
agent-reach configure <key> [value] groq-key | openai-key | proxy | github-token
agent-reach uninstall [--dry-run] remove everything Agent Reach installed
@@ -62,7 +62,7 @@ For the user:
def unified_channels() -> List[Channel]:
"""Channels exposed on the command line."""
- return [ch for ch in get_all_channels() if ch.level]
+ return get_all_channels()
def _channel(name: str) -> Optional[Channel]:
@@ -231,36 +231,31 @@ def _cmd_doctor(args: Sequence[str]) -> int:
from . import manage
parser = _Parser(prog="doctor", add_help=False)
- parser.add_argument("--live", action="store_true")
parser.add_argument("--text", action="store_true")
try:
ns = parser.parse_args(list(args))
except _ArgError as exc:
return _bad_input(None, "doctor", str(exc))
if not ns.text:
- return _mgmt("doctor", manage.doctor, live=ns.live)
- result = manage.doctor(live=ns.live)
+ return _mgmt("doctor", manage.doctor)
+ result = manage.doctor()
sys.stdout.write(f"Agent Reach {result['version']}\n\n")
for c in result["channels"]:
extra = "; ".join(c["problems"]) or c.get("hint", "")
+ if c["regressed"]:
+ extra = f"REGRESSED (worked at the previous check) {extra}"
sys.stdout.write(f"{c['status']:<12} {c['channel']:<12} {c['level']:<13} {extra}\n")
return 0
-def _cmd_watch(args: Sequence[str]) -> int:
+def _cmd_skill(args: Sequence[str]) -> int:
from . import manage
- if "--text" not in args:
- return _mgmt("watch", manage.watch)
- result = manage.watch()
- if result["all_good"]:
- sys.stdout.write("Agent Reach: all good\n")
- return 0
- for r in result["regressions"]:
- sys.stdout.write(f"BROKEN {r['channel']} {r['action']} (worked at the previous check)\n")
- if result["update"].get("update_available"):
- sys.stdout.write(f"UPDATE {result['update']['current']} -> {result['update']['latest']}: run `agent-reach update`\n")
- return 1
+ if not args:
+ return _mgmt("skill", manage.skill_status)
+ if args[0] != "link" or len(args) != 2:
+ return _bad_input(None, "skill", "usage: agent-reach skill [link <skills-dir>]")
+ return _mgmt("skill link", manage.link_skill, args[1])
def _cmd_management(head: str, args: Sequence[str]) -> int:
@@ -421,16 +416,15 @@ def _cmd_browser(args: Sequence[str]) -> int:
from agent_reach.backends.opencli import OPENCLI_EXTENSION_URL
parser = _Parser(prog="browser", add_help=False)
- parser.add_argument("op", choices=("setup", "start", "status"))
+ parser.add_argument("op", choices=("setup", "status"))
try:
ns = parser.parse_args(list(args))
except _ArgError as exc:
- return _bad_input(None, "browser", f"{exc}; usage: agent-reach browser setup|start|status")
+ return _bad_input(None, "browser", f"{exc}; usage: agent-reach browser setup|status")
action = f"browser {ns.op}"
try:
- if ns.op == "start":
- browser.start()
- elif ns.op == "setup":
+ if ns.op == "setup":
+ browser.touch()
result = browser.bind()
if result["status"] == "waiting_for_extension":
browser.start(OPENCLI_EXTENSION_URL)
@@ -469,8 +463,8 @@ def main(argv: Sequence[str]) -> int:
return _cmd_browser(rest)
if head == "doctor":
return _cmd_doctor(rest)
- if head == "watch":
- return _cmd_watch(rest)
+ if head == "skill":
+ return _cmd_skill(rest)
if head in _MANAGEMENT:
return _cmd_management(head, rest)
channel = _channel(head)
diff --git a/agent_reach/runtime/clock.py b/agent_reach/runtime/clock.py
new file mode 100644
index 00000000..a1d8c6f8
--- /dev/null
+++ b/agent_reach/runtime/clock.py
@@ -0,0 +1,61 @@
+"""An action's --timeout budget that setup waits (browser cold start) can pause."""
+
+from __future__ import annotations
+
+import contextlib
+import threading
+import time
+from typing import Iterator, Optional
+
+
+class Clock:
+ """Seconds left for one action; paused time is added back on resume."""
+
+ def __init__(self, budget: float) -> None:
+ self._lock = threading.Lock()
+ self._deadline = time.monotonic() + budget
+ self._paused_at: Optional[float] = None
+ self._depth = 0
+
+ def remaining(self) -> float:
+ with self._lock:
+ return self._deadline - (self._paused_at or time.monotonic())
+
+ def paused(self) -> bool:
+ with self._lock:
+ return self._depth > 0
+
+ def pause(self) -> None:
+ with self._lock:
+ if self._depth == 0:
+ self._paused_at = time.monotonic()
+ self._depth += 1
+
+ def resume(self) -> None:
+ with self._lock:
+ self._depth -= 1
+ if self._depth == 0 and self._paused_at is not None:
+ self._deadline += time.monotonic() - self._paused_at
+ self._paused_at = None
+
+
+_current = threading.local()
+
+
+def bind(clock: Clock) -> None:
+ """Make `clock` the running action's clock in this thread."""
+ _current.clock = clock
+
+
+def off_the_clock() -> Iterator[None]:
+ """Time spent inside does not count against the running action's --timeout."""
+ clock: Optional[Clock] = getattr(_current, "clock", None)
+ if clock is None:
+ yield
+ return
+ clock.pause()
+ try:
+ yield
+ finally:
+ clock.resume()
diff --git a/agent_reach/runtime/dispatch.py b/agent_reach/runtime/dispatch.py
index 1902d9d6..edc37a6b 100644
--- a/agent_reach/runtime/dispatch.py
+++ b/agent_reach/runtime/dispatch.py
@@ -8,6 +8,7 @@ from typing import Any, Dict, List, Optional
from agent_reach.channels.base import Action, Channel
+from .clock import Clock, bind
from .result import (
BAD_INPUT,
FINAL_CODES,
@@ -45,25 +46,34 @@ def _validate(action: Action, params: Dict[str, Any]) -> Dict[str, Any]:
return clean
-def _call_with_deadline(fn, params: Dict[str, Any], timeout: float) -> List[dict]:
- """Run fn(timeout=..., **params); give up after `timeout` seconds.
+def _call_with_deadline(fn, params: Dict[str, Any], clock: Clock) -> List[dict]:
+ """Run fn(timeout=..., **params); give up when the clock runs out.
In-process HTTP calls cannot be interrupted, so the call runs in a daemon
thread. Subprocess backends also receive `timeout` and kill themselves.
+ The backend may pause the clock (off_the_clock) while it waits for setup.
"""
box: Dict[str, Any] = {}
+ budget = clock.remaining()
def target() -> None:
+ bind(clock)
try:
- box["items"] = fn(timeout=timeout, **params)
+ box["items"] = fn(timeout=budget, **params)
except BaseException as exc: # noqa: BLE001 - forwarded to classify()
box["error"] = exc
worker = threading.Thread(target=target, daemon=True)
worker.start()
- worker.join(timeout + 1.0)
+ while True:
+ left = clock.remaining() + 1.0
+ if left <= 0 and not clock.paused():
+ break
+ worker.join(max(left, 0.2))
+ if not worker.is_alive():
+ break
if worker.is_alive():
- raise ReachError(TIMEOUT, f"backend did not answer within {timeout:.0f}s")
+ raise ReachError(TIMEOUT, f"backend did not answer within {budget:.0f}s")
if "error" in box:
raise box["error"]
return list(box.get("items") or [])
@@ -102,17 +112,16 @@ def run_action(
return envelope(channel=channel.name, action=action_name, elapsed_ms=elapsed(), error=err)
backends = [b for b in action.backends if only_backend in (None, b[0])]
- deadline = started + timeout
+ clock = Clock(timeout - (time.monotonic() - started))
attempts: List[dict] = []
errors: List[ReachError] = []
for label, method_name in backends:
- remaining = deadline - time.monotonic()
- if remaining <= 0:
+ if clock.remaining() <= 0:
attempts.append({"backend": label, "result": TIMEOUT})
errors.append(ReachError(TIMEOUT, "no time left for this backend"))
continue
try:
- items = _call_with_deadline(getattr(channel, method_name), clean, remaining)
+ items = _call_with_deadline(getattr(channel, method_name), clean, clock)
except BaseException as exc: # noqa: BLE001
err = classify(exc)
attempts.append({"backend": label, "result": err.code, "message": err.message})
diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.py
index 35b4abcf..0cb70fc2 100644
--- a/agent_reach/runtime/manage.py
+++ b/agent_reach/runtime/manage.py
@@ -1,4 +1,4 @@
-"""Management commands: setup, add, remove, update, doctor, watch, uninstall, configure.
+"""Management commands: setup, add, remove, update, doctor, skill, uninstall, configure.
Each public function returns a plain dict `result` or raises ReachError; the CLI
wraps it in {schema_version, ok, action, result, error}.
@@ -16,6 +16,7 @@ from pathlib import Path
from typing import Dict, List, Optional
from agent_reach import __version__
+from agent_reach.utils.paths import home_dir
from . import state, tools
from .result import BAD_INPUT, NEED_SETUP, UPSTREAM_BROKEN, ReachError
@@ -24,18 +25,12 @@ REPO = "Panniantong/Agent-Reach"
CHECK_FRESH_SECONDS = 24 * 3600
-
def _chrome_present() -> bool:
from .browser import chrome_binary
return chrome_binary() is not None
-def home_dir_skills() -> Path:
- """Fallback skill root when no agent's skill directory exists yet."""
- from agent_reach.utils.paths import home_dir
-
- return home_dir() / ".agents" / "skills"
# ── prerequisites we only check and explain ──
PREREQS: Dict[str, dict] = {
@@ -71,10 +66,14 @@ def missing_prereqs(ch) -> List[str]:
return [p for p in ch.prereqs if not PREREQS[p]["check"]()]
+def _has_login(ch) -> bool:
+ return bool(ch.login_url or ch.login_argv or ch.logout_keys)
+
+
# ── checks ──
def run_checks(names: Optional[List[str]] = None, timeout: float = 60.0) -> dict:
- """Live-test every backend of every action with a live_test; persist results in state."""
+ """Live-test the added channels (or the named ones); persist results in state."""
from .dispatch import run_action
selected = _channels()
@@ -83,6 +82,9 @@ def run_checks(names: Optional[List[str]] = None, timeout: float = 60.0) -> dict
if unknown:
raise ReachError(BAD_INPUT, f"unknown channel(s): {', '.join(sorted(unknown))}")
selected = [c for c in selected if c.name in names]
+ else:
+ data = state.load()
+ selected = [c for c in selected if is_added(c, data)]
results = []
for ch in selected:
for action in ch.actions:
@@ -109,11 +111,20 @@ def run_checks(names: Optional[List[str]] = None, timeout: float = 60.0) -> dict
actions = {a: ok for (c, a), ok in by_action.items() if c == ch.name}
if actions:
failed = {a: codes[(ch.name, a)] for a, ok in actions.items() if not ok}
- data["checks"][ch.name] = {"at": state.now(), "actions": actions, "codes": failed}
+ previous = data["checks"].get(ch.name, {}).get("actions", {})
+ data["checks"][ch.name] = {"at": state.now(), "actions": actions, "codes": failed, "previous": previous}
state.save(data)
return {"ok": bool(results) and all(by_action.values()), "results": results}
+def regressed(check: Optional[dict]) -> bool:
+ """An action passed in the previous check and fails in the latest one."""
+ if not check:
+ return False
+ previous = check.get("previous", {})
+ return any(previous.get(a) and not ok for a, ok in check.get("actions", {}).items())
+
+
def channel_status(ch, data: dict) -> dict:
if not is_added(ch, data):
return {"status": "not_added", "problems": [], "hint": f"agent-reach add {ch.name}"}
@@ -136,38 +147,20 @@ def channel_status(ch, data: dict) -> dict:
return {"status": "unverified", "problems": [], "hint": f"agent-reach check {ch.name}"}
-def doctor(live: bool = False) -> dict:
- if live:
- added = [c.name for c in _channels() if is_added(c)]
- run_checks(added)
+def doctor() -> dict:
+ """Status of every channel from local state only (no network); `check` runs the live tests."""
data = state.load()
channels = []
for ch in _channels():
- channels.append({"channel": ch.name, "level": ch.level, **channel_status(ch, data)})
+ channels.append({"channel": ch.name, "level": ch.level, **channel_status(ch, data),
+ "regressed": regressed(data["checks"].get(ch.name))})
return {"version": __version__, "channels": channels}
-def watch() -> dict:
- before = state.load()["checks"]
- added = [c.name for c in _channels() if is_added(c)]
- run_checks(added)
- after = state.load()["checks"]
- regressions = []
- for name, check in after.items():
- prev = before.get(name, {}).get("actions", {})
- for action, ok in check["actions"].items():
- if prev.get(action) and not ok:
- regressions.append({"channel": name, "action": action})
- upd = update_check(quiet=True)
- return {"regressions": regressions, "update": upd, "all_good": not regressions and not upd.get("update_available")}
-
-
# ── add / remove ──
def add(name: str, *, allow_upgrade: bool = False) -> dict:
ch = _channel(name)
- if ch.level == "default":
- return {"channel": name, "added": True, "note": "default channel, always available"}
missing = missing_prereqs(ch)
if missing:
raise ReachError(NEED_SETUP, f"missing prerequisites: {', '.join(missing)}",
@@ -178,7 +171,7 @@ def add(name: str, *, allow_upgrade: bool = False) -> dict:
data["channels"][name] = {"added_at": state.now()}
state.save(data)
nxt = list(ch.setup_problems())
- if ch.login_url or ch.login_argv or ch.logout_keys:
+ if _has_login(ch):
nxt.append(f"log in: `agent-reach login {name}`")
return {"channel": name, "added": True, "tools": installed, "next": nxt}
@@ -209,17 +202,50 @@ def remove(name: str) -> dict:
# ── skill (the agent-facing instructions) ──
+#
+# One real copy in ~/.agents/skills/agent-reach (read natively by Codex, OpenCode,
+# Cline, Warp, Zed). AIs that do not read that folder get a symlink in their own
+# skills folder, but only when their config folder exists. Source for the folders:
+# the vercel-labs/skills supported-agents table.
-def skill_roots() -> List[Path]:
- from agent_reach.utils.paths import home_dir
+SKILL_NAME = "agent-reach"
- home = home_dir()
- roots = [home / ".agents" / "skills", home / ".claude" / "skills",
- home / ".config" / "opencode" / "skills", home / ".openclaw" / "skills"]
+
+def _openclaw_home() -> Path:
oc = os.environ.get("OPENCLAW_HOME")
- if oc:
- roots.insert(0, Path(oc) / ".openclaw" / "skills")
- return roots
+ return (Path(oc) if oc else home_dir()) / ".openclaw"
+
+
+def _config_home() -> Path:
+ xdg = os.environ.get("XDG_CONFIG_HOME")
+ return Path(xdg) if xdg else home_dir() / ".config"
+
+
+def linked_agents() -> Dict[str, tuple]:
+ """AIs that need a link: name -> (config folder that proves it is installed, its skills folder)."""
+ home = home_dir()
+ return {
+ "claude-code": (home / ".claude", home / ".claude" / "skills"),
+ "openclaw": (_openclaw_home(), _openclaw_home() / "skills"),
+ "hermes": (home / ".hermes", home / ".hermes" / "skills"),
+ "cursor": (home / ".cursor", home / ".cursor" / "skills"),
+ "gemini-cli": (home / ".gemini", home / ".gemini" / "skills"),
+ "github-copilot": (home / ".copilot", home / ".copilot" / "skills"),
+ "windsurf": (home / ".codeium" / "windsurf", home / ".codeium" / "windsurf" / "skills"),
+ }
+
+
+def native_agents() -> Dict[str, tuple]:
+ """AIs that read ~/.agents/skills themselves: name -> (config folder, their own old skills folder)."""
+ home = home_dir()
+ return {
+ "codex": (home / ".codex", home / ".codex" / "skills"),
+ "opencode": (_config_home() / "opencode", _config_home() / "opencode" / "skills"),
+ }
+
+
+def skill_dir() -> Path:
+ return home_dir() / ".agents" / "skills" / SKILL_NAME
def _skill_lang() -> str:
@@ -238,29 +264,181 @@ def render_skill(lang: Optional[str] = None) -> str:
labels = {"default": "default", "optional": "optional", "experimental": "experimental"}
rows = ["| channel | level | actions | login |", "|---|---|---|---|"]
for ch in _channels():
- login = f"`agent-reach login {ch.name}`" if (ch.login_url or ch.login_argv or ch.logout_keys) else "-"
+ login = f"`agent-reach login {ch.name}`" if _has_login(ch) else "-"
rows.append(f"| {ch.name} | {labels[ch.level]} | {', '.join(a.name for a in ch.actions)} | {login} |")
return template.replace("{{CHANNEL_TABLE}}", "\n".join(rows)).replace("{{VERSION}}", __version__)
-def install_skill() -> List[str]:
- text = render_skill()
- roots = [r for r in skill_roots() if r.is_dir()] or [home_dir_skills()]
- written = []
- for root in roots:
- target = root / "agent-reach"
- if target.is_symlink():
- continue
- if target.exists():
- shutil.rmtree(target) # old instructions are replaced, not merged
- target.mkdir(parents=True)
- (target / "SKILL.md").write_text(text, encoding="utf-8")
- written.append(str(target))
- return written
+def _is_our_copy(path: Path) -> bool:
+ """A real folder holding our SKILL.md (frontmatter `name: agent-reach`)."""
+ if path.is_symlink() or not path.is_dir():
+ return False
+ try:
+ lines = (path / "SKILL.md").read_text("utf-8").splitlines()
+ except (OSError, UnicodeDecodeError):
+ return False
+ if not lines or lines[0].strip() != "---":
+ return False
+ for line in lines[1:]:
+ if line.strip() == "---":
+ return False
+ key, _, value = line.partition(":")
+ if key.strip() == "name":
+ return value.strip().strip("'\"") == SKILL_NAME
+ return False
+
+
+def _links_to_real(path: Path) -> bool:
+ if not path.is_symlink():
+ return False
+ try:
+ return Path(os.path.realpath(path)) == Path(os.path.realpath(skill_dir()))
+ except OSError:
+ return False
+
+
+def _remove(path: Path) -> None:
+ if path.is_symlink() or path.is_file():
+ path.unlink()
+ elif path.exists():
+ shutil.rmtree(path)
+
+
+def _write_real_copy(text: str) -> Path:
+ real = skill_dir()
+ _remove(real) # old instructions are replaced, not merged
+ real.mkdir(parents=True)
+ (real / "SKILL.md").write_text(text, encoding="utf-8")
+ return real
+
+
+def _write_copy(target: Path, text: str) -> None:
+ target.mkdir(parents=True)
+ (target / "SKILL.md").write_text(text, encoding="utf-8")
+
+
+def _link_into(skills_dir: Path, text: str) -> tuple:
+ """Make `<skills_dir>/agent-reach` point at the real copy.
+
+ Returns (kind, reason): kind is "link" | "copy" | None (left alone; reason says why).
+ Our own old real copy is replaced; anything else already there is left untouched.
+ """
+ target = skills_dir / SKILL_NAME
+ if _links_to_real(target):
+ return "link", None
+ if target.is_symlink():
+ return None, f"a symlink to {os.readlink(target)} is already there"
+ if target.exists():
+ if not _is_our_copy(target):
+ return None, "a different skill named agent-reach is already there"
+ shutil.rmtree(target)
+ skills_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ target.symlink_to(skill_dir(), target_is_directory=True)
+ return "link", None
+ except (OSError, NotImplementedError):
+ # Windows without symlink rights: fall back to a copy that update refreshes.
+ _write_copy(target, text)
+ return "copy", None
+
+
+def _remove_native_old_copies() -> List[str]:
+ """Our old real copies in folders of AIs that now read ~/.agents/skills (so they don't see two)."""
+ removed = []
+ for _, skills in native_agents().values():
+ target = skills / SKILL_NAME
+ if _is_our_copy(target):
+ shutil.rmtree(target)
+ removed.append(str(target))
+ return removed
+
+
+def _agent_for(skills_dir: Path) -> str:
+ return next((name for name, (_, d) in linked_agents().items() if d == skills_dir), "custom")
-def installed_skill_dirs() -> List[Path]:
- return [r / "agent-reach" for r in skill_roots() if (r / "agent-reach").exists() or (r / "agent-reach").is_symlink()]
+def place_skill() -> dict:
+ """Write the real copy, link every detected AI, refresh recorded links/copies."""
+ text = render_skill()
+ _write_real_copy(text)
+ data = state.load()
+ targets: Dict[Path, str] = {}
+ for name, (config, skills) in linked_agents().items():
+ if config.is_dir():
+ targets[skills] = name
+ for rec in data["skill"]["links"]:
+ parent = Path(rec["path"]).parent
+ if parent.is_dir():
+ targets.setdefault(parent, rec.get("agent", "custom"))
+ links, not_linked = [], []
+ for skills, agent in targets.items():
+ target = skills / SKILL_NAME
+ kind, reason = _link_into(skills, text)
+ if kind:
+ links.append({"agent": agent, "path": str(target), "kind": kind})
+ else:
+ not_linked.append({"agent": agent, "path": str(target), "reason": reason})
+ data["skill"]["links"] = links
+ state.save(data)
+ return {**skill_status(), "not_linked": not_linked, "removed_old_copies": _remove_native_old_copies()}
+
+
+def skill_status() -> dict:
+ real = skill_dir()
+ recorded = state.load()["skill"]["links"]
+ links = [r for r in recorded
+ if _links_to_real(Path(r["path"])) or (r["kind"] == "copy" and _is_our_copy(Path(r["path"])))]
+ installed = (real / "SKILL.md").is_file()
+ agents = []
+ if installed:
+ agents = [name for name, (config, _) in native_agents().items() if config.is_dir()]
+ agents += [r["agent"] for r in links if r["agent"] not in agents and r["agent"] != "custom"]
+ return {"path": str(real / "SKILL.md"), "installed": installed, "agents": agents,
+ "links": [r["path"] for r in links if r["kind"] == "link"],
+ "copies": [r["path"] for r in links if r["kind"] == "copy"]}
+
+
+def link_skill(skills_dir: str) -> dict:
+ """Link the skill into the skills folder of an AI that is not in the table."""
+ target_dir = Path(skills_dir).expanduser()
+ if not target_dir.is_absolute():
+ target_dir = Path.cwd() / target_dir
+ if target_dir.name == SKILL_NAME:
+ raise ReachError(BAD_INPUT, f"give the skills folder, not the {SKILL_NAME} folder inside it",
+ hint=f"agent-reach skill link {target_dir.parent}")
+ if os.path.realpath(target_dir) == os.path.realpath(skill_dir().parent):
+ return skill_status()
+ text = render_skill()
+ if not (skill_dir() / "SKILL.md").is_file():
+ _write_real_copy(text)
+ kind, reason = _link_into(target_dir, text)
+ if kind is None:
+ raise ReachError(BAD_INPUT, f"{target_dir / SKILL_NAME}: {reason}; left it untouched",
+ hint="Ask the user to move it away, then run this again.")
+ data = state.load()
+ path = str(target_dir / SKILL_NAME)
+ data["skill"]["links"] = [r for r in data["skill"]["links"] if r["path"] != path]
+ data["skill"]["links"].append({"agent": _agent_for(target_dir), "path": path, "kind": kind})
+ state.save(data)
+ return skill_status()
+
+
+def _skill_uninstall_targets() -> List[Path]:
+ """Real copy, recorded links/copies, and our links/old copies in every known skills folder."""
+ found: List[Path] = []
+ for rec in state.load()["skill"]["links"]:
+ p = Path(rec["path"])
+ if _links_to_real(p) or _is_our_copy(p):
+ found.append(p)
+ known = [skills for _, skills in linked_agents().values()] + [skills for _, skills in native_agents().values()]
+ for skills in known:
+ p = skills / SKILL_NAME
+ if _links_to_real(p) or _is_our_copy(p):
+ found.append(p)
+ real = skill_dir()
+ if real.exists() or real.is_symlink():
+ found.append(real)
+ return list(dict.fromkeys(found))
# ── setup / migrate ──
@@ -278,23 +456,37 @@ def migrate() -> dict:
hints.append("xueqiu")
if cfg.get("groq_api_key"):
hints.append("xiaoyuzhou")
+ defaults = {c.name for c in _channels() if c.level == "default"}
data = state.load()
data["migrated_from"] = "pre-2.0"
state.save(data)
return {
"migrated": True,
"kept": "~/.agent-reach/config.yaml (keys and cookies unchanged)",
- "suggested_channels": sorted(set(hints)),
+ "suggested_channels": sorted(set(hints) - defaults),
"note": "Your own global tools were not removed. Old logins can be copied with `agent-reach login <channel> --import-existing`.",
}
def setup() -> dict:
- prereqs = {p: PREREQS[p]["check"]() for p in PREREQS}
migration = migrate() if not state.exists() and (state.root() / "config.yaml").exists() else None
if not state.exists():
state.save(state.load())
- skills = install_skill()
+ skill = place_skill()
+ defaults = [c for c in _channels() if c.level == "default"]
+ added = []
+ for ch in defaults:
+ try:
+ out = add(ch.name)
+ added.append({"channel": ch.name, "ok": True, "tools": out["tools"]})
+ except ReachError as err:
+ added.append({"channel": ch.name, "ok": False, "tools": [],
+ "error": {"code": err.code, "message": err.message, "hint": err.hint}})
+ needed = list(dict.fromkeys(p for ch in defaults for p in ch.prereqs))
+ prereqs = {}
+ for p in needed:
+ ok = PREREQS[p]["check"]()
+ prereqs[p] = {"ok": ok, **({} if ok else {"hint": PREREQS[p]["hint"]})}
optional = [
{"channel": c.name, "level": c.level, "add": f"agent-reach add {c.name}",
"needs": list(c.prereqs) + (["login"] if (c.login_url or c.login_argv) else [])}
@@ -302,10 +494,11 @@ def setup() -> dict:
]
return {
"version": __version__,
- "default_channels": [c.name for c in _channels() if c.level == "default"],
- "prerequisites": {p: {"ok": ok, **({} if ok else {"hint": PREREQS[p]["hint"]})} for p, ok in prereqs.items()},
- "skill_installed": skills,
+ "default_channels": added,
+ "prerequisites": prereqs,
+ "skill": skill,
"optional_channels": optional,
+ "logins": [{"channel": c.name, "command": f"agent-reach login {c.name}"} for c in defaults if _has_login(c)],
"migration": migration,
}
@@ -319,15 +512,13 @@ def _version_tuple(v: str) -> tuple:
return ()
-def update_check(quiet: bool = False) -> dict:
+def update_check() -> dict:
try:
req = urllib.request.Request(f"https://api.github.com/repos/{REPO}/releases/latest",
headers={"User-Agent": "agent-reach", "Accept": "application/vnd.github+json"})
with urllib.request.urlopen(req, timeout=15) as resp:
rel = json.loads(resp.read())
except Exception as exc: # noqa: BLE001
- if quiet:
- return {"current": __version__, "error": str(exc)[:200]}
raise ReachError(UPSTREAM_BROKEN, f"could not reach GitHub: {exc}") from None
latest = str(rel.get("tag_name", "")).lstrip("v")
return {
@@ -339,7 +530,7 @@ def update_check(quiet: bool = False) -> dict:
def install_method() -> str:
- """How this copy of Agent Reach was installed: uv | pipx | pip | editable."""
+ """How this copy of Agent Reach was installed: uv | editable | other."""
try:
from importlib.metadata import distribution
@@ -348,25 +539,20 @@ def install_method() -> str:
return "editable"
except Exception: # noqa: BLE001
pass
- prefix = sys.prefix.replace("\\", "/")
- if "/uv/tools/" in prefix:
+ if (Path(sys.prefix) / "uv-receipt.toml").is_file():
return "uv"
- if "/pipx/venvs/" in prefix:
- return "pipx"
- return "pip"
+ return "other"
def _source(version: str) -> str:
return f"https://github.com/{REPO}/archive/refs/tags/v{version}.zip"
-def upgrade_command(method: str, version: str) -> List[str]:
- src = _source(version)
- if method == "uv":
- return ["uv", "tool", "install", "--force", src]
- if method == "pipx":
- return ["pipx", "install", "--force", src]
- return [sys.executable, "-m", "pip", "install", "--upgrade", src]
+def upgrade_command(version: str) -> List[str]:
+ return ["uv", "tool", "install", "--force", _source(version)]
+
+
+UNINSTALL_PROGRAM = "uv tool uninstall agent-reach"
def sync() -> dict:
@@ -375,7 +561,7 @@ def sync() -> dict:
data = state.load()
synced, problems = [], []
for ch in _channels():
- if ch.level == "default" or ch.name not in data["channels"]:
+ if not is_added(ch, data):
continue
for t in ch.tools:
try:
@@ -384,7 +570,7 @@ def sync() -> dict:
problems.append({"tool": t, "code": err.code, "message": err.message, "hint": err.hint})
ch.on_add()
return {"version": __version__, "tools": synced, "problems": problems,
- "skill_installed": install_skill(), "migration": migration}
+ "skill": place_skill(), "migration": migration}
def update(check_only: bool = False) -> dict:
@@ -393,8 +579,17 @@ def update(check_only: bool = False) -> dict:
return info
method = install_method()
if info["update_available"] and method != "editable":
- cmd = upgrade_command(method, info["latest"])
- proc = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
+ cmd = upgrade_command(info["latest"])
+ if method != "uv":
+ raise ReachError(
+ NEED_SETUP, "this copy of Agent Reach was not installed with uv, so it cannot update itself",
+ hint=f"Reinstall once with uv: `{' '.join(cmd)}`, then remove the old copy "
+ "(e.g. `pipx uninstall agent-reach` or `pip uninstall agent-reach`).",
+ )
+ try:
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
+ except FileNotFoundError:
+ raise ReachError(NEED_SETUP, "uv is not on PATH", hint=PREREQS["uv"]["hint"]) from None
if proc.returncode != 0:
raise ReachError(UPSTREAM_BROKEN, f"upgrade failed: {proc.stderr.strip()[-300:]}",
hint=f"Run manually: {' '.join(cmd)}")
@@ -416,21 +611,17 @@ _OWNED = ("config.yaml", "state.json", "mcporter.json", "sessions", "browser")
def uninstall(dry_run: bool = False) -> dict:
from . import browser
- if browser.is_running() and not dry_run:
- raise ReachError(BAD_INPUT, "the Agent Reach browser is still open", hint="Close that Chrome window, then run uninstall again.")
root = state.root()
- targets = [root / n for n in _OWNED]
+ targets = _skill_uninstall_targets() # before state.json goes: it records the links
+ targets += [root / n for n in _OWNED]
targets += [tools.tool_dir(n) for n in tools.TOOLS] + [root / "tools" / "xiaoyuzhou"]
- targets += installed_skill_dirs()
targets = [t for t in targets if t.exists() or t.is_symlink()]
globals_ = tools.uninstall_global_owned(dry_run=True)
if not dry_run:
+ browser.stop()
tools.uninstall_global_owned(dry_run=False)
for t in targets:
- if t.is_symlink() or t.is_file():
- t.unlink()
- else:
- shutil.rmtree(t)
+ _remove(t)
for d in (root / "tools", root):
try:
d.rmdir()
@@ -438,11 +629,8 @@ def uninstall(dry_run: bool = False) -> dict:
pass
removing = {str(t) for t in targets} | {str(root / "tools")}
kept = sorted(str(p) for p in root.iterdir() if str(p) not in removing) if root.exists() else []
- method = install_method()
- program = {"uv": "uv tool uninstall agent-reach", "pipx": "pipx uninstall agent-reach"}.get(
- method, f"{sys.executable} -m pip uninstall agent-reach")
return {"dry_run": dry_run, "removed": [str(t) for t in targets], "global_tools_removed": globals_,
- "kept_unrecognized": kept, "remove_program": program}
+ "kept_unrecognized": kept, "remove_program": UNINSTALL_PROGRAM}
# ── configure ──
diff --git a/agent_reach/runtime/state.py b/agent_reach/runtime/state.py
index 72220a68..cfac72e7 100644
--- a/agent_reach/runtime/state.py
+++ b/agent_reach/runtime/state.py
@@ -4,10 +4,12 @@
"version": 1,
"channels": {"bilibili": {"added_at": "..."}},
"tools": {"bili-cli": {"spec": "...", "owner": "agent-reach" | "user", "scope": "private" | "global"}},
- "checks": {"bilibili": {"at": "...", "actions": {"search": true}}}
+ "checks": {"bilibili": {"at": "...", "actions": {"search": true}, "previous": {"search": true}}},
+ "skill": {"links": [{"agent": "claude-code", "path": "...", "kind": "link" | "copy"}]}
}
`owner` decides what uninstall may delete: only "agent-reach" entries.
+`skill.links` are the skill links/copies we made; update refreshes them, uninstall removes them.
"""
from __future__ import annotations
@@ -46,8 +48,9 @@ def load() -> dict:
except (OSError, ValueError, PrivatePathError):
data = {}
data.setdefault("version", STATE_VERSION)
- for key in ("channels", "tools", "checks"):
+ for key in ("channels", "tools", "checks", "skill"):
data.setdefault(key, {})
+ data["skill"].setdefault("links", [])
return data
diff --git a/agent_reach/skill/SKILL.md b/agent_reach/skill/SKILL.md
index 823e9b8f..6e5d624e 100644
--- a/agent_reach/skill/SKILL.md
+++ b/agent_reach/skill/SKILL.md
@@ -49,6 +49,20 @@ agent-reach read <链接> # 给链接,自动认出渠道
`default` 装好就能用;其余要用户先 `agent-reach add <渠道>`。
-## 给用户的管理命令
+## 浏览器
-`agent-reach setup`(首次)· `add` / `remove <渠道>` · `login` / `logout <渠道>` · `doctor` · `update` · `uninstall`
+小红书、Reddit、Twitter、Boss直聘、雪球热帖等渠道要用 Agent Reach 专用浏览器。它会自己打开,不用你启动;第一次打开大约要 40 秒,别当成卡住。10 分钟没用会自动关掉。
+
+## 用户要管理 Agent Reach 时
+
+| 用户说 | 你运行 |
+|---|---|
+| 看看状态 / 哪些能用 | `agent-reach doctor --text`(要实测再跑 `agent-reach check --text`) |
+| 加上某个平台(如"加上小红书") | `agent-reach add <渠道>`,照 `result.next` 做,再 `agent-reach login <渠道>` 让用户本人登录 |
+| 登录过期了 | `agent-reach login <渠道>`(用户本人登录) |
+| 去掉某个平台 / 退出登录 | `agent-reach remove <渠道>` / `agent-reach logout <渠道>` |
+| 升级 / 更新 | `agent-reach update` |
+| 卸载 | 先 `agent-reach uninstall --dry-run` 给用户看,确认后 `agent-reach uninstall` |
+| 让另一个 AI 也能用 | `agent-reach skill link <那个 AI 的 skill 目录>`;`agent-reach skill` 查看现在放在哪 |
+
+首次安装:`agent-reach setup`。
diff --git a/agent_reach/skill/SKILL_en.md b/agent_reach/skill/SKILL_en.md
index 64b387c7..fcb2b7ae 100644
--- a/agent_reach/skill/SKILL_en.md
+++ b/agent_reach/skill/SKILL_en.md
@@ -50,6 +50,20 @@ Results:
`default` channels work right away; others need `agent-reach add <channel>` first.
-## Management commands (for the user)
+## Browser
-`agent-reach setup` (first run) · `add` / `remove <channel>` · `login` / `logout <channel>` · `doctor` · `update` · `uninstall`
+Xiaohongshu, Reddit, Twitter, Boss Zhipin, Xueqiu hot posts and similar channels use the dedicated Agent Reach browser. It opens by itself; you never start it. The first open can take about 40 seconds, so don't treat that as a hang. It closes after 10 minutes without use.
+
+## When the user wants to manage Agent Reach
+
+| User asks | You run |
+|---|---|
+| Status / what works | `agent-reach doctor --text` (for a live test, `agent-reach check --text`) |
+| Add a platform ("add Xiaohongshu") | `agent-reach add <channel>`, follow `result.next`, then `agent-reach login <channel>` so the user logs in |
+| Login expired | `agent-reach login <channel>` (the user logs in) |
+| Remove a platform / log out | `agent-reach remove <channel>` / `agent-reach logout <channel>` |
+| Upgrade / update | `agent-reach update` |
+| Uninstall | show `agent-reach uninstall --dry-run` first, then `agent-reach uninstall` once they confirm |
+| Another AI should use it | `agent-reach skill link <that AI's skills folder>`; `agent-reach skill` shows where it is placed now |
+
+First install: `agent-reach setup`.
diff --git a/docs/README_en.md b/docs/README_en.md
index df391e61..2b7889e0 100644
--- a/docs/README_en.md
+++ b/docs/README_en.md
@@ -80,7 +80,7 @@ Every command prints the same JSON shape, so the agent doesn't have to learn eac
### ✅ Before you start, you might want to know
-- **Which agents?** Any agent that can run shell commands. `agent-reach setup` installs the usage instructions (a skill) into the skill folders of Claude Code, Codex, OpenCode, OpenClaw and others.
+- **Which agents?** Any agent that can run shell commands. `agent-reach setup` places one copy of the usage instructions (a skill) that Codex, OpenCode and others read directly, and links it into the skill folders of Claude Code, OpenClaw, Cursor and others when they are installed.
- **Does it cost money?** The program and its backends are open source and free. The only keys you may need are for speech-to-text: Groq (has a free tier) or OpenAI Whisper.
- **Does it touch my browser or accounts?** It never reads your own browser's cookies and never logs in for you. For login channels, you log in yourself in the dedicated Agent Reach browser. See [Security](#security).
- **Which OS?** macOS first, Linux works, Windows best effort.
@@ -97,8 +97,8 @@ Every command prints the same JSON shape, so the agent doesn't have to learn eac
| youtube | default | video info, search, subtitles, speech-to-text | nothing; speech-to-text needs a Groq or OpenAI key |
| v2ex | default | hot topics, nodes, topics with replies, users | nothing |
| web | default | web search, page reading (fallback) | nothing |
+| bilibili | default | search, video info, trending, subtitles | nothing; subtitles need a login (QR scan) |
| xiaohongshu | optional | search notes, read a note | browser + login |
-| bilibili | optional | search, video info, trending, subtitles | subtitles need a login (QR scan) |
| reddit | optional | search, read posts with comments, browse a subreddit | browser + login |
| linkedin | optional | job search | login (needs Node.js and uv) |
| boss | optional | job and JD search | browser + login (needs git) |
@@ -111,7 +111,7 @@ Every command prints the same JSON shape, so the agent doesn't have to learn eac
- **default**: works right after install.
- **optional**: turn on with `agent-reach add <channel>`; Agent Reach installs the tools it needs into its own folder.
- **experimental**: works, but the platform fights automation harder and it can break at any time.
-- **browser**: the Agent Reach browser, a separate Chrome window (needs Google Chrome and Node.js). The first time, you add the OpenCLI extension to it; `agent-reach browser setup` walks you through it.
+- **browser**: the Agent Reach browser, a separate Chrome window (needs Google Chrome and Node.js). The first time, you add the OpenCLI extension to it; `agent-reach browser setup` walks you through it. After that it opens by itself when needed (the first open takes about 40 seconds) and closes after 10 minutes without use.
---
@@ -123,14 +123,18 @@ Send this to your agent:
Install Agent Reach: https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/install.md
```
-The agent follows [install.md](install.md):
+The agent does the rest by following [install.md](install.md). Along the way you may be asked to:
-1. Install the program: `uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip`
-2. Run `agent-reach setup`: checks prerequisites and installs the skill for your agent
-3. Shows you the optional channels; for the ones you pick it runs `agent-reach add <channel>`
-4. For login channels it runs `agent-reach login <channel>` to open the login page, and **you log in yourself**
+- **Let it run commands**: if the agent says it can't run commands, turn on command execution in its settings.
+- **Allow installing uv**: uv is a small tool that installs command-line programs; no admin password needed. The agent installs it first if it's missing and tells you.
+- **Pick optional channels**: afterwards the agent tells you what works now (web, YouTube, GitHub, V2EX, Bilibili) and what else you can add and what each needs. Pick now, or later just say "add Xiaohongshu".
-> ⚠️ The PyPI package named `agent-reach` is NOT this project. Don't install it from PyPI; use the GitHub URL above.
+The only thing you do yourself is log in; the agent never logs in for you and never asks for your password:
+
+- Xiaohongshu, Reddit, Twitter and the like: log in yourself in the Agent Reach browser.
+- Bilibili: subtitles need a QR-scan login; search and video info work without it.
+
+> ⚠️ The PyPI package named `agent-reach` is NOT this project. Don't install it from PyPI; use the GitHub URL in install.md.
Prefer doing it by hand? Run the commands in [install.md](install.md) yourself.
@@ -147,19 +151,20 @@ flowchart LR
---
-## Works Out of the Box
+## After Install: Managing It
+
+Just tell your agent in plain words; it runs the command for you:
-After install these are the commands you'll see (your agent usually runs them for you):
+| You say | Agent runs | What it does |
+|---|---|---|
+| "How is Agent Reach doing?" | `agent-reach doctor --text` | status of every channel: not_added / needs_setup / needs_login / unverified / ready / broken, and which ones broke since the last check |
+| "Add Xiaohongshu" / "Remove Xiaohongshu" | `agent-reach add` / `remove <channel>` | turn a channel on / off; after adding, `agent-reach login <channel>` |
+| "My Bilibili login expired" / "Log out" | `agent-reach login` / `logout <channel>` | log in (you do it) / forget the login |
+| "Upgrade Agent Reach" | `agent-reach update` | update the program, its tools and the skill in one go, see [update.md](update.md) |
+| "Uninstall Agent Reach" | `agent-reach uninstall` | see Uninstall under Security below |
+| "Let my other AI use it too" | `agent-reach skill link <its skills folder>` | link the instructions for an AI not covered automatically |
-| Command | What it does |
-|---|---|
-| `agent-reach doctor --text` | status of every channel: not_added / needs_setup / needs_login / unverified / ready / broken |
-| `agent-reach check [channel] --text` | run live tests to confirm a channel works |
-| `agent-reach watch --text` | report only what broke since the last check, and whether an update is out |
-| `agent-reach update` | update the program, its tools and the skill in one go, see [update.md](update.md) |
-| `agent-reach add` / `remove <channel>` | turn an optional channel on / off |
-| `agent-reach login` / `logout <channel>` | log in (you do it) / forget the login |
-| `agent-reach configure <key> [value]` | save `groq-key`, `openai-key`, `proxy`, `github-token` |
+Also: `agent-reach check [channel] --text` runs live tests; `agent-reach configure <key>` saves `groq-key`, `openai-key`, `proxy`, `github-token`.
When something fails, `error.code` in the JSON tells the agent what to do next. Every error code and status is explained in [troubleshooting.md](troubleshooting.md).
@@ -196,9 +201,9 @@ On failure `ok` is `false` and `error` holds a `code` (`NEED_SETUP` / `NEED_LOGI
## Security
-- **Everything lives under `~/.agent-reach/`**: `config.yaml` (keys and proxy), `state.json`, `tools/` (private tool installs), `sessions/` (logins of CLI tools), `browser/` (the dedicated browser profile), `mcporter.json`.
+- **Everything lives under `~/.agent-reach/`**: `config.yaml` (keys and proxy), `state.json`, `tools/` (private tool installs), `sessions/` (logins of CLI tools), `browser/` (the dedicated browser profile), `mcporter.json`. The one exception is the skill: one copy in `~/.agents/skills/agent-reach/`, with only links to it in other AIs' skill folders.
- **Agent Reach never logs in for you and never reads your own browser's cookies.** For login channels you log in yourself, in the Agent Reach browser or in the tool's own login flow (e.g. Bilibili QR scan).
-- **The Agent Reach browser's debugging port listens on loopback only** (127.0.0.1:9222), but any local process can use it to control that browser. Close the window when you're not using it.
+- **The Agent Reach browser's debugging port listens on loopback only** (127.0.0.1:9222), but while it is open any local process can use it to control that browser. That's why it closes itself after 10 minutes without use.
- **Use a secondary account for login channels.** Platforms may restrict accounts used for automated access.
- **Don't paste API keys into chat**: run `agent-reach configure groq-key` in your own terminal; input is hidden.
diff --git a/docs/dependency-locking.md b/docs/dependency-locking.md
deleted file mode 100644
index 23a3fdb4..00000000
--- a/docs/dependency-locking.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Dependency Locking Guide
-
-Agent Reach uses `constraints.txt` as a reproducible dependency baseline.
-
-## Why
-
-- Keep local/CI dependency graph stable
-- Reduce "works on my machine" drift
-- Make regression results easier to compare
-
-## Install with constraints
-
-```bash
-pip install -c constraints.txt -e '.[dev]'
-```
-
-## Update workflow
-
-1. Update `pyproject.toml` dependency ranges as needed.
-2. Validate against latest compatible versions locally.
-3. Update pinned versions in `constraints.txt`.
-4. Run validation:
-
-```bash
-pytest -q
-ruff check agent_reach tests
-mypy agent_reach
-```
-
-5. Open PR with dependency and validation notes.
diff --git a/docs/install.md b/docs/install.md
index 6b7ed929..e2f3b61f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1,80 +1,39 @@
# Install Agent Reach
-Instructions for the AI agent doing the install. Run the commands yourself; ask the user only where a step says so. Every `agent-reach` command prints one JSON object; read `ok`, `result` and `error.hint`.
+For the AI doing the install. Run every command yourself. Each `agent-reach` command prints one JSON object; read `ok`, `result` and `error.hint`.
> ⚠️ The PyPI package named `agent-reach` is NOT this project. Never install it from PyPI; only use the GitHub URL below.
-## 1. Install the program
+## 0. Before you start
-Already installed? Run `agent-reach update` instead and stop here (see [update.md](update.md)).
+- You must be able to run terminal commands. If you can't, tell the user: "Please turn on command execution for me in my settings, then ask again."
+- Already have `agent-reach`? Run `agent-reach update` and stop here. Coming from a version before 2.0: follow [update.md](update.md).
+- `uv` missing (`uv --version` fails)? Tell the user: "I'm installing uv, a small tool that installs command-line programs. It needs no admin password." Then run:
+ - macOS / Linux: `curl -LsSf https://astral.sh/uv/install.sh | sh`
+ - Windows: `powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"`
+ - Still `uv: command not found`? Open a new shell and try again.
-```bash
-uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip
-```
-
-No `uv`? Use pipx with the same URL:
-
-```bash
-pipx install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip
-```
-
-If `agent-reach` is not found afterwards, run `uv tool update-shell` (or `pipx ensurepath`) and open a new shell.
-
-## 2. Set up
+## 1. Install and set up
```bash
+uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip
agent-reach setup
+agent-reach check --text
```
-This checks prerequisites, installs the Agent Reach skill into your skill folder, and keeps keys from an older install. The default channels (github, youtube, v2ex, web) work now.
-
-If `result.prerequisites` shows something missing (node, git, chrome, ffmpeg, uv), tell the user the `hint`; only the channels that need it are affected.
-
-## 3. Let the user pick optional channels
-
-Show the user `result.optional_channels` from the setup output, with what each `needs`. Mention that `experimental` channels can break at any time. Then, for each channel they pick:
-
-```bash
-agent-reach add <channel>
-```
-
-Follow the `result.next` list it returns.
-
-## 4. Logins and keys (the user does these)
-
-Never log in for the user, never ask for their password, never read their browser's cookies.
-
-**Browser channels** (xiaohongshu, reddit, twitter, facebook, instagram, boss, xueqiu): once, first run
-
-```bash
-agent-reach browser setup
-```
-
-It opens the Agent Reach browser (a separate Chrome window) at the OpenCLI extension page. Ask the user to click "Add to Chrome" there, then run `agent-reach browser setup` again until `ok` is true. Then for each channel:
-
-```bash
-agent-reach login <channel>
-```
-
-The login page opens in the Agent Reach browser; the user logs in. If the output says to, run `agent-reach login <channel> --sync` after they are done.
-
-**bilibili / linkedin**: `agent-reach login <channel>` runs the tool's own login (QR code or a browser window). Run it where the user can see the output.
+`agent-reach` not found after install? Run `uv tool update-shell` and open a new shell.
-**Keys** (xiaoyuzhou, youtube transcribe): ask the user to get a free key at https://console.groq.com and run this in their own terminal (hidden input):
+`setup` turns on the default channels (web, YouTube, GitHub, V2EX, Bilibili) and gives every AI on this machine the Agent Reach instructions (a "skill"). If `result.prerequisites` lists something missing, tell the user its `hint`; only the channels that need it are affected.
-```bash
-agent-reach configure groq-key
-```
+## 2. Report to the user
-If you must run it yourself, pipe the value: `agent-reach configure groq-key --stdin`.
+Keep it short and plain:
-Suggest a secondary account for login channels.
+1. **Works now**: the channels in `result.default_channels` with `ok: true`, and what `check --text` passed.
+2. **Which AIs can use it**: `result.skill.agents`.
+3. **Optional, add any time**: each entry of `result.optional_channels` with what it `needs`; mention that `experimental` ones can break at any time. Optional logins for channels already on: `result.logins` (e.g. Bilibili login unlocks subtitles).
+4. **How to add one later**: "Just tell me, e.g. 'add Xiaohongshu'."
-## 5. Verify
-
-```bash
-agent-reach check --text
-agent-reach doctor --text
-```
+When the user asks for a channel, run `agent-reach add <channel>`, follow its `result.next`, then `agent-reach login <channel>`. The user logs in themselves: never log in for them, never ask for their password, never read their browser's cookies. Suggest a secondary account. Keys (e.g. a free Groq key from https://console.groq.com for podcast transcripts) are entered by the user in their own terminal with `agent-reach configure groq-key` (hidden input); if you must run it yourself, pipe the value: `agent-reach configure groq-key --stdin`.
-Report to the user what is `ready` and what still needs something. Fixes for each status and error code: [troubleshooting.md](troubleshooting.md).
+Problems: [troubleshooting.md](troubleshooting.md).
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 28cff452..1303968d 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -32,17 +32,25 @@ Every failed command returns `ok: false` and an `error` with `code`, `message` a
| `ready` | passed a live check in the last 24 hours | nothing |
| `broken` | the last live check failed for another reason | `agent-reach update`, then `agent-reach check <channel> --text`; see `UPSTREAM_BROKEN` |
-`agent-reach doctor --live` runs the live checks first, then reports.
+Run `agent-reach check` first if you want fresh live results. In the `doctor` output, `regressed: true` on a channel means an action passed in the previous check and fails in the latest one.
## Agent Reach browser
-Used by xiaohongshu, reddit, twitter, facebook, instagram, boss and xueqiu. It is a separate Chrome window with its own profile in `~/.agent-reach/browser/`.
+Used by xiaohongshu, reddit, twitter, facebook, instagram, boss and xueqiu. It is a separate Chrome window with its own profile in `~/.agent-reach/browser/`. It opens by itself when one of these channels needs it (the first open can take about 40 seconds) and closes after 10 minutes without Agent Reach use.
- **`agent-reach browser setup` keeps saying it is waiting for the extension**: in the Agent Reach window, click "Add to Chrome" on the OpenCLI extension page, then run `agent-reach browser setup` again.
- **"more than one new OpenCLI profile connected"**: close other Chrome windows that have the OpenCLI extension, then run setup again.
- **Chrome not installed**: install Google Chrome, then retry.
-- **Window closed**: `agent-reach browser start` reopens it; `agent-reach browser status` shows its state.
-- Close the window when you're done; any local process can control it through its debugging port.
+- **Window closed by hand**: nothing to do; the next command that needs it opens it again. `agent-reach browser status` shows its state.
+- While it is open, any local process can control it through its debugging port; it closes itself after 10 idle minutes.
+
+## Skill not picked up by an AI
+
+`agent-reach skill` shows the one real copy of the instructions (`~/.agents/skills/agent-reach/SKILL.md`) and the links made for other AIs. An AI not covered automatically: `agent-reach skill link <its skills folder>`. On Windows, where links may not be allowed, a copy is made instead and refreshed by `agent-reach update`.
+
+## Install and update
+
+Agent Reach is installed with uv only. If `agent-reach update` says the program was installed another way, reinstall once as in [install.md](install.md); your channels, keys and logins under `~/.agent-reach/` are kept.
## Proxy
diff --git a/docs/update.md b/docs/update.md
index 5df1042f..186c27b0 100644
--- a/docs/update.md
+++ b/docs/update.md
@@ -8,27 +8,25 @@ agent-reach update
One command does everything:
-- upgrades the program with the installer you used (uv or pipx) to the latest GitHub release
+- upgrades the program to the latest GitHub release (`uv tool install --force <release zip>`)
- moves the tools of your added channels to the versions pinned by that release
-- refreshes the Agent Reach skill in your agent's skill folder
+- refreshes the Agent Reach skill (the one real copy, and the links that let your other AIs read it)
-Only want to know if there is a new version? `agent-reach update --check`. `agent-reach watch --text` also reports available updates.
+Only want to know if there is a new version? `agent-reach update --check`.
Afterwards, `agent-reach check --text` confirms your channels still work.
-If the upgrade step fails, the error `hint` holds the exact command to run by hand.
+If the upgrade step fails, the error `hint` holds the exact command to run by hand. Installed some other way than uv? The hint says to reinstall once with uv, as below.
## Coming from a version before 2.0
-Older versions installed differently, so reinstall once with the same command as [install.md](install.md):
+Older versions installed differently, so reinstall once with the same command as [install.md](install.md) (no `uv` yet? see step 0 there):
```bash
uv tool install --force https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip
agent-reach setup
```
-(pipx: `pipx install --force <same URL>`.)
-
`agent-reach setup` migrates the old install:
- keys in `~/.agent-reach/config.yaml` stay as they are
diff --git a/llms.txt b/llms.txt
index f48b0c6c..0831aad6 100644
--- a/llms.txt
+++ b/llms.txt
@@ -5,7 +5,8 @@
## Install
- [Installation Guide](https://github.com/Panniantong/Agent-Reach/blob/main/docs/install.md): agent-executable steps
-- Install from GitHub only: `uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip` (or `pipx install` with the same URL), then `agent-reach setup`. The PyPI package named `agent-reach` is NOT this project.
+- Install from GitHub only, with uv: `uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v2.0.0.zip`, then `agent-reach setup`. The PyPI package named `agent-reach` is NOT this project.
+- `setup` turns on the default channels and places one copy of the skill at `~/.agents/skills/agent-reach/SKILL.md`, linked into the skill folders of other AIs found on the machine; `agent-reach skill link <skills-dir>` adds another AI.
## Commands
@@ -13,12 +14,13 @@
- `agent-reach <channel> <action> [args]`: e.g. `agent-reach bilibili search python`
- `agent-reach read <url>`: read a link with the matching channel
- Output: `{schema_version, ok, channel, action, backend, items, meta, error}`; error codes NEED_SETUP, NEED_LOGIN, UPSTREAM_BROKEN, TIMEOUT, RATE_LIMITED, NOT_FOUND, BAD_INPUT
-- Management: `setup`, `add|remove <channel>`, `login|logout <channel>` (the user logs in), `browser setup|start|status`, `doctor`, `check`, `watch`, `update`, `configure`, `uninstall`
+- Management: `setup`, `add|remove <channel>`, `login|logout <channel>` (the user logs in), `browser setup|status`, `doctor`, `check`, `skill`, `skill link <dir>`, `update`, `configure`, `uninstall`
+- Browser channels open the dedicated Agent Reach browser by themselves; it closes after 10 minutes without use.
## Channels
-- default: github, youtube, v2ex, web (web is a fallback when the agent's own search/fetch fails)
-- optional: xiaohongshu, bilibili, reddit, linkedin, boss, xiaoyuzhou, xueqiu
+- default: web, youtube, github, v2ex, bilibili (web is a fallback when the agent's own search/fetch fails)
+- optional: xiaohongshu, reddit, linkedin, boss, xiaoyuzhou, xueqiu
- experimental: twitter, facebook, instagram
## Docs
diff --git a/tests/test_config.py b/tests/test_config.py
index 51408a38..79b9de8d 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -61,80 +61,6 @@ class TestConfig:
tmp_config.delete("to_delete")
assert tmp_config.get("to_delete") is None
- def test_is_configured(self, tmp_config):
- assert not tmp_config.is_configured("exa_search")
- tmp_config.set("exa_api_key", "test-key")
- assert tmp_config.is_configured("exa_search")
-
- def test_get_configured_features(self, tmp_config):
- features = tmp_config.get_configured_features()
- assert isinstance(features, dict)
- assert "exa_search" in features
- assert all(v is False for v in features.values())
-
- def test_to_dict_redacts_long_secret_without_leaking_prefix(self, tmp_config):
- secret = "super-secret-key-12345"
- tmp_config.set("exa_api_key", secret)
- tmp_config.set("normal_setting", "visible")
- masked = tmp_config.to_dict()
-
- assert masked["exa_api_key"] == "[REDACTED]"
- assert secret not in str(masked)
- assert masked["normal_setting"] == "visible"
-
- @pytest.mark.parametrize(
- "secret",
- (
- "!",
- "!@",
- "!@#",
- "!@#$",
- "!@#$%",
- "!@#$%^",
- "!@#$%^&",
- "!@#$%^&*",
- ),
- )
- def test_to_dict_redacts_short_secrets_without_leaking_value(
- self, tmp_config, secret
- ):
- tmp_config.set("api_key", secret)
-
- masked = tmp_config.to_dict()
-
- assert masked["api_key"] == "[REDACTED]"
- assert secret not in str(masked)
-
- @pytest.mark.parametrize("empty_value", (None, ""))
- def test_to_dict_keeps_empty_sensitive_values_as_none(
- self, tmp_config, empty_value
- ):
- tmp_config.set("api_key", empty_value)
-
- assert tmp_config.to_dict()["api_key"] is None
-
- def test_to_dict_redacts_sensitive_credential_markers(self, tmp_config):
- secrets = {
- "twitter_ct0": "csrf-secret-value",
- "xhs_cookie": "web_session=xhs-secret",
- "browser_session": "browser-session-secret",
- "https_proxy": "socks5://proxy.example:1080",
- "xueqiu_cookie": "xq_a_token=xueqiu-secret",
- "bilibili_sessdata": "bili-session-secret",
- "bilibili_csrf": "bili-csrf-secret",
- "twitter_auth_token": "twitter-auth-secret",
- }
- for key, value in secrets.items():
- tmp_config.set(key, value)
-
- tmp_config.set("normal_setting", "visible")
- masked = tmp_config.to_dict()
-
- dumped = str(masked)
- for key, value in secrets.items():
- assert masked[key] == "[REDACTED]"
- assert value not in dumped
- assert masked["normal_setting"] == "visible"
def test_save_creates_file_with_restricted_permissions(self, tmp_path):
import stat
diff --git a/tests/test_manage.py b/tests/test_manage.py
index 339ddf20..2a4e916c 100644
--- a/tests/test_manage.py
+++ b/tests/test_manage.py
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
-"""Management commands: private installs, add/remove, doctor, watch, uninstall, update, skill."""
+"""Management commands: private installs, add/remove, setup, doctor, uninstall, update, skill."""
import json
+import os
import pytest
@@ -59,8 +60,10 @@ def env(monkeypatch):
b.write_text("")
monkeypatch.setattr(tools, "_install", fake_install)
+ stopped = []
monkeypatch.setattr(browser, "is_running", lambda: False)
- return {"chans": chans, "installs": installs}
+ monkeypatch.setattr(browser, "stop", lambda: stopped.append(True), raising=False)
+ return {"chans": chans, "installs": installs, "stopped": stopped}
# ── private installs ──
@@ -124,7 +127,7 @@ def test_default_channels_cannot_be_removed(env):
manage.remove("web")
-# ── doctor / watch ──
+# ── doctor ──
def _status(name):
@@ -156,19 +159,56 @@ def test_doctor_reports_missing_tool_as_needs_setup(env, monkeypatch):
assert _status("bili") == "needs_setup"
-def test_watch_reports_only_what_broke_since_last_check(env, monkeypatch):
- monkeypatch.setattr(manage, "update_check", lambda quiet=False: {"update_available": False})
+def test_check_without_names_tests_only_default_and_added_channels(env):
manage.add("bili")
- assert manage.watch()["all_good"] is True
+ tested = {r["channel"] for r in manage.run_checks()["results"]}
+ assert tested == {"web", "bili"}
+
+
+def test_doctor_marks_regressed_only_when_the_previous_check_passed(env):
+ manage.add("bili")
+ manage.run_checks(["bili"])
+ assert _doctor("bili")["regressed"] is False
Bili.passes = False
try:
- result = manage.watch()
- assert result["regressions"] == [{"channel": "bili", "action": "search"}]
- assert manage.watch()["regressions"] == [], "an already-broken channel is not reported again"
+ manage.run_checks(["bili"])
+ assert _doctor("bili")["regressed"] is True
+ manage.run_checks(["bili"])
+ assert _doctor("bili")["regressed"] is False, "an already-broken channel is not a regression"
finally:
Bili.passes = True
+def _doctor(name):
+ return next(c for c in manage.doctor()["channels"] if c["channel"] == name)
+
+
+# ── setup ──
+
+
+class Broken(_Base):
+ name, level, actions, tools = "broken", "default", _actions(), ("bili-cli",)
+ login_argv = ("bili", "login")
+
+
+def test_setup_adds_default_channels_and_survives_a_failing_install(env, monkeypatch):
+ env["chans"].append(Broken())
+
+ def failing_install(tool, *, global_=False):
+ raise ReachError("UPSTREAM_BROKEN", "install failed: no network")
+
+ monkeypatch.setattr(tools, "_install", failing_install)
+ result = manage.setup()
+ by_name = {c["channel"]: c for c in result["default_channels"]}
+ assert set(by_name) == {"web", "broken"}
+ assert by_name["web"]["ok"] is True
+ assert by_name["broken"]["ok"] is False and by_name["broken"]["error"]["code"] == "UPSTREAM_BROKEN"
+ assert result["prerequisites"] == {}, "only prerequisites of default channels are reported"
+ assert result["logins"] == [{"channel": "broken", "command": "agent-reach login broken"}]
+ assert {c["channel"] for c in result["optional_channels"]} == {"bili", "bili2", "needy"}
+ assert result["skill"]["installed"] is True
+
+
# ── uninstall ──
@@ -181,16 +221,16 @@ def test_uninstall_removes_only_what_we_own(env):
dry = manage.uninstall(dry_run=True)
assert (root / "state.json").exists(), "dry run changes nothing"
assert str(tools.tool_dir("bili-cli")) in dry["removed"]
+ assert env["stopped"] == []
manage.uninstall()
assert not (root / "state.json").exists() and not (root / "config.yaml").exists()
assert not tools.tool_dir("bili-cli").exists()
assert (root / "my-notes").exists() and (root / "tools" / "someone-elses-tool").exists()
-def test_uninstall_refuses_while_browser_open(env, monkeypatch):
- monkeypatch.setattr(browser, "is_running", lambda: True)
- with pytest.raises(ReachError):
- manage.uninstall()
+def test_uninstall_closes_the_browser_instead_of_refusing(env):
+ manage.uninstall()
+ assert env["stopped"] == [True]
# ── update ──
@@ -213,10 +253,19 @@ def test_update_check_compares_versions(monkeypatch, latest, available):
assert manage.update_check()["update_available"] is available
[email protected]("method, head", [("uv", ["uv", "tool"]), ("pipx", ["pipx", "install"])])
-def test_upgrade_uses_the_same_installer_as_the_original_install(method, head):
- cmd = manage.upgrade_command(method, "2.0.1")
- assert cmd[:2] == head and cmd[-1].endswith("/v2.0.1.zip")
+def test_upgrade_reinstalls_the_release_with_uv():
+ cmd = manage.upgrade_command("2.0.1")
+ assert cmd[:4] == ["uv", "tool", "install", "--force"] and cmd[-1].endswith("/v2.0.1.zip")
+
+
+def test_update_from_a_non_uv_install_asks_for_one_uv_reinstall(monkeypatch):
+ monkeypatch.setattr(manage, "update_check", lambda: {"current": "2.0.0", "latest": "2.0.1",
+ "update_available": True})
+ monkeypatch.setattr(manage, "install_method", lambda: "other")
+ monkeypatch.setattr(manage.subprocess, "run", lambda *a, **k: pytest.fail("must not run an installer"))
+ with pytest.raises(ReachError) as info:
+ manage.update()
+ assert "uv tool install --force" in info.value.hint
# ── skill ──
@@ -230,12 +279,78 @@ def test_skill_lists_every_channel_and_has_no_placeholders(env):
assert f"| {ch.name} |" in text
-def test_skill_install_replaces_old_instructions(env):
- old = home_dir() / ".claude" / "skills" / "agent-reach"
- (old / "references").mkdir(parents=True)
- (old / "references" / "social.md").write_text("old")
- assert str(old) in manage.install_skill()
- assert (old / "SKILL.md").exists() and not (old / "references").exists()
+def _seed_our_copy(path):
+ path.mkdir(parents=True)
+ (path / "SKILL.md").write_text("---\nname: agent-reach\ndescription: old\n---\nold\n")
+ (path / "references").mkdir()
+
+
+def test_skill_one_real_copy_linked_only_for_present_ais(env):
+ home = home_dir()
+ for d in (".claude", ".codex", ".openclaw"):
+ (home / d).mkdir()
+ result = manage.place_skill()
+ real = home / ".agents" / "skills" / "agent-reach"
+ assert (real / "SKILL.md").is_file()
+ for link in (home / ".claude" / "skills" / "agent-reach", home / ".openclaw" / "skills" / "agent-reach"):
+ assert link.is_symlink() and os.path.realpath(link) == os.path.realpath(real)
+ assert not (home / ".codex" / "skills").exists(), "codex reads ~/.agents/skills itself"
+ assert not (home / ".cursor").exists(), "absent AIs get nothing"
+ assert set(result["agents"]) == {"claude-code", "codex", "openclaw"}
+ assert len(state.load()["skill"]["links"]) == 2
+
+
+def test_skill_replaces_our_old_copy_but_not_a_foreign_one(env):
+ home = home_dir()
+ ours = home / ".claude" / "skills" / "agent-reach"
+ _seed_our_copy(ours)
+ foreign = home / ".cursor" / "skills" / "agent-reach"
+ foreign.mkdir(parents=True)
+ (foreign / "SKILL.md").write_text("---\nname: someone-else\n---\n")
+ native_old = home / ".codex" / "skills" / "agent-reach"
+ _seed_our_copy(native_old)
+ result = manage.place_skill()
+ assert ours.is_symlink()
+ assert not foreign.is_symlink() and "someone-else" in (foreign / "SKILL.md").read_text()
+ assert [n["agent"] for n in result["not_linked"]] == ["cursor"]
+ assert not native_old.exists() and result["removed_old_copies"] == [str(native_old)]
+
+
+def test_skill_falls_back_to_a_copy_without_symlink_rights(env, monkeypatch):
+ home = home_dir()
+ (home / ".claude").mkdir()
+
+ def no_symlinks(self, *a, **k):
+ raise OSError("symlinks not permitted")
+
+ monkeypatch.setattr(type(home), "symlink_to", no_symlinks)
+ result = manage.place_skill()
+ copy = home / ".claude" / "skills" / "agent-reach"
+ assert not copy.is_symlink() and (copy / "SKILL.md").is_file()
+ assert result["copies"] == [str(copy)] and result["links"] == []
+ (copy / "SKILL.md").write_text("---\nname: agent-reach\n---\nstale\n")
+ manage.place_skill()
+ assert "stale" not in (copy / "SKILL.md").read_text(), "update refreshes recorded copies"
+ manage.uninstall()
+ assert not copy.exists()
+
+
+def test_skill_link_for_an_unlisted_ai_and_uninstall_removes_everything(env):
+ home = home_dir()
+ (home / ".claude").mkdir()
+ manage.place_skill()
+ other = home / "my-ai" / "skills"
+ manage.link_skill(str(other))
+ assert (other / "agent-reach").is_symlink()
+ stray = home / ".gemini" / "skills" / "agent-reach"
+ stray.parent.mkdir(parents=True)
+ stray.symlink_to(home / ".agents" / "skills" / "agent-reach")
+ manage.place_skill()
+ assert (other / "agent-reach").is_symlink(), "update keeps recorded links"
+ manage.uninstall()
+ for p in (other / "agent-reach", home / ".claude" / "skills" / "agent-reach", stray,
+ home / ".agents" / "skills" / "agent-reach"):
+ assert not p.exists() and not p.is_symlink()
# ── configure ──
diff --git a/tests/test_transcribe.py b/tests/test_transcribe.py
index 279ead47..29680bed 100644
--- a/tests/test_transcribe.py
+++ b/tests/test_transcribe.py
@@ -859,13 +859,3 @@ class TestSubprocessDecoding:
tr._probe_audio_duration(tmp_path / "audio.m4a")
-# --- Config feature requirement --------------------------------------- #
-
-
-class TestConfigOpenAIWhisper:
- def test_openai_whisper_feature_registered(self, fake_config):
- assert "openai_whisper" in Config.FEATURE_REQUIREMENTS
- assert Config.FEATURE_REQUIREMENTS["openai_whisper"] == ["openai_api_key"]
- assert not fake_config.is_configured("openai_whisper")
- fake_config.set("openai_api_key", "sk-test")
- assert fake_config.is_configured("openai_whisper")
diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.py
index ceadb8f9..3bc2589c 100644
--- a/tests/test_unified_entry.py
+++ b/tests/test_unified_entry.py
@@ -213,6 +213,25 @@ def test_check_fails_when_backend_returns_nothing(capsys, fake_cli):
assert out["results"][0]["error"]["code"] == "EMPTY"
+def test_skill_command_links_a_skills_dir_and_reports_it(capsys, fake_cli):
+ from agent_reach.utils.paths import home_dir
+
+ target = home_dir() / "my-ai" / "skills"
+ code, out = _run(capsys, ["skill", "link", str(target)])
+ assert code == 0 and out["action"] == "skill link"
+ assert out["result"]["links"] == [str(target / "agent-reach")]
+ code, out = _run(capsys, ["skill"])
+ assert code == 0 and out["result"]["installed"] is True
+ code, out = _run(capsys, ["skill", "unlink"])
+ assert code == 1 and out["error"]["code"] == "BAD_INPUT"
+
+
+def test_doctor_reports_regressed_per_channel(capsys, fake_cli):
+ code, out = _run(capsys, ["doctor"])
+ assert code == 0
+ assert out["result"]["channels"][0]["regressed"] is False
+
+
# ── parsers ──
@@ -337,13 +356,133 @@ def fake_browser(monkeypatch, tmp_path):
from agent_reach.runtime import browser
monkeypatch.setenv("HOME", str(tmp_path))
- state = {"contexts": ["daily"], "running": True, "opened": []}
+ state = {"contexts": ["daily"], "running": True, "opened": [], "launches": 0, "launch_delay": 0.0}
+
+ def fake_launch(url):
+ state["launches"] += 1
+ time.sleep(state["launch_delay"])
+ state["running"] = True
+ state["contexts"].append("dedicated")
+
monkeypatch.setattr(browser, "connected_contexts", lambda: list(state["contexts"]))
monkeypatch.setattr(browser, "is_running", lambda: state["running"])
monkeypatch.setattr(browser, "start", lambda url="about:blank": state["opened"].append(url))
+ monkeypatch.setattr(browser, "_launch", fake_launch)
+ monkeypatch.setattr(browser, "_RUNNING_GRACE", 0.0)
return state
+def _bind_dedicated(fake_browser):
+ from agent_reach.runtime import browser
+
+ browser.bind()
+ fake_browser["contexts"].append("dedicated")
+ browser.bind()
+
+
+def test_browser_action_opens_closed_browser_only_when_set_up(fake_browser):
+ from agent_reach.backends.opencli import _dedicated_profile_env
+ from agent_reach.runtime import browser
+
+ fake_browser["running"] = False
+ with pytest.raises(ReachError) as info:
+ _dedicated_profile_env()
+ assert info.value.code == "NEED_SETUP"
+ assert "browser setup" in info.value.hint
+ assert fake_browser["launches"] == 0
+
+ fake_browser["running"] = True
+ _bind_dedicated(fake_browser)
+ assert _dedicated_profile_env() == {"OPENCLI_PROFILE": "dedicated"}
+ assert fake_browser["launches"] == 0 # already open: no second browser
+
+ fake_browser["running"] = False
+ fake_browser["contexts"].remove("dedicated")
+ assert _dedicated_profile_env() == {"OPENCLI_PROFILE": "dedicated"}
+ assert fake_browser["launches"] == 1
+ assert browser.last_used() is not None
+
+
+def test_browser_cold_start_does_not_count_against_timeout(fake_browser):
+ from agent_reach.runtime import browser
+
+ _bind_dedicated(fake_browser)
+ fake_browser["running"] = False
+ fake_browser["contexts"].remove("dedicated")
+ fake_browser["launch_delay"] = 1.5
+ seen = {}
+
+ def opencli_backend(**kw):
+ browser.ensure_running("dedicated")
+ seen["timeout"] = kw["timeout"]
+ time.sleep(0.5)
+ return [{"title": "ok"}]
+
+ ch = FakeChannel(first=opencli_backend, second=_raise("UPSTREAM_BROKEN"))
+ out = run_action(ch, "search", {"query": "q"}, timeout=1.0)
+ assert out["ok"] is True, out
+ assert out["backend"] == "first"
+ assert fake_browser["launches"] == 1
+
+
+def test_concurrent_actions_start_one_browser(fake_browser):
+ import threading
+
+ from agent_reach.runtime import browser
+
+ _bind_dedicated(fake_browser)
+ fake_browser["running"] = False
+ fake_browser["contexts"].remove("dedicated")
+ fake_browser["launch_delay"] = 0.5
+ errors = []
+
+ def call():
+ try:
+ browser.ensure_running("dedicated")
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target=call) for _ in range(3)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(10)
+ assert errors == []
+ assert fake_browser["launches"] == 1
+
+
+def test_only_one_idle_watcher_and_it_closes_idle_browser(fake_browser, monkeypatch):
+ import threading
+
+ from agent_reach.runtime import browser, browser_watcher
+
+ stopped = []
+
+ def fake_stop(timeout=10.0):
+ stopped.append(time.time())
+ fake_browser["running"] = False
+ return True
+
+ monkeypatch.setattr(browser, "stop", fake_stop)
+ browser.touch()
+ result = {}
+ first = threading.Thread(target=lambda: result.setdefault("first", browser_watcher.watch(idle=3.0, poll=0.1)))
+ first.start()
+ assert browser.wait_for(browser.watcher_running, 2.0, interval=0.05)
+ assert browser_watcher.watch(idle=3.0, poll=0.1) == "another watcher is running"
+ first.join(8)
+ assert result["first"] == "closed after idle"
+ assert len(stopped) == 1
+ assert not browser.watcher_running()
+
+
+def test_idle_watcher_exits_when_browser_is_closed(fake_browser):
+ from agent_reach.runtime import browser_watcher
+
+ fake_browser["running"] = False
+ assert browser_watcher.watch(idle=600, poll=0.1) == "browser closed"
+
+
def test_bind_ignores_profiles_that_were_already_connected(fake_browser):
from agent_reach.runtime import browser