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: management commands (setup, add, remove, update, doctor, watch, uninstall, configure)

Pnant2104fdfa851a
diff --git a/agent_reach/channels/_opencli_site.py b/agent_reach/channels/_opencli_site.py
index 794b0053..38df41a7 100644
--- a/agent_reach/channels/_opencli_site.py
+++ b/agent_reach/channels/_opencli_site.py
@@ -22,6 +22,13 @@ class OpenCLISiteChannel(Channel):
backends = ["OpenCLI"]
tier = 1
+ tools = ("opencli",)
+ prereqs = ("node", "chrome")
+
+ def setup_problems(self):
+ from agent_reach.runtime.browser import setup_problems
+
+ return setup_problems()
def can_handle(self, url: str) -> bool:
return host_matches(url, *self.domains)
diff --git a/agent_reach/channels/base.py b/agent_reach/channels/base.py
index 5548a796..33863137 100644
--- a/agent_reach/channels/base.py
+++ b/agent_reach/channels/base.py
@@ -80,6 +80,32 @@ class Channel(ABC):
legacy_state: Tuple[str, ...] = ()
#: Page the user logs in on, opened in the Agent Reach browser by `agent-reach login`.
login_url: str = ""
+ #: Upstream tools (keys of runtime.tools.TOOLS) `agent-reach add` installs.
+ tools: Tuple[str, ...] = ()
+ #: Machine prerequisites we only check (keys of runtime.manage.PREREQS).
+ prereqs: Tuple[str, ...] = ()
+ #: Config keys `agent-reach logout` clears.
+ logout_keys: Tuple[str, ...] = ()
+ #: Run login_argv / tool calls with HOME = the session dir. False when the tool
+ #: takes an explicit path instead (login_argv may use the `{session}` placeholder).
+ session_home: bool = True
+
+ def setup_problems(self) -> List[str]:
+ """What still blocks this channel after its tools are installed (keys, browser...)."""
+ return []
+
+ def on_add(self) -> None:
+ """Extra setup after tools are installed (e.g. register an MCP server)."""
+
+ def on_remove(self) -> None:
+ """Undo on_add."""
+
+ def sync_login(self) -> Optional[dict]:
+ """Pull login state from the Agent Reach browser after the user logged in there.
+
+ Return a result dict, or None to fall back to running `login_argv`.
+ """
+ return None
#: Backend currently serving this channel; set by check(), None = unavailable.
active_backend: Optional[str] = None
diff --git a/agent_reach/channels/bilibili.py b/agent_reach/channels/bilibili.py
index b7c5d81e..72cce46a 100644
--- a/agent_reach/channels/bilibili.py
+++ b/agent_reach/channels/bilibili.py
@@ -140,6 +140,7 @@ class BilibiliChannel(Channel):
session = "bili-cli"
login_argv = ("bili", "login")
legacy_state = (".bilibili-cli",)
+ tools = ("bili-cli",)
actions = (
Action(
"search",
diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.py
index f643b254..e8c272f2 100644
--- a/agent_reach/channels/boss.py
+++ b/agent_reach/channels/boss.py
@@ -270,6 +270,8 @@ class BossChannel(Channel):
session = "boss-agent-cli"
login_argv = ("boss", "--cdp-url", "http://localhost:9222", "login", "--cdp")
legacy_state = (".boss-agent",)
+ tools = ("boss-agent-cli",)
+ prereqs = ("git", "chrome")
actions = (
Action(
"search",
diff --git a/agent_reach/channels/github.py b/agent_reach/channels/github.py
index 2282b9c9..dc36ad4c 100644
--- a/agent_reach/channels/github.py
+++ b/agent_reach/channels/github.py
@@ -143,6 +143,10 @@ def _gh_get(path: str, timeout: float, accept: str = "application/vnd.github+jso
def _api_get(path: str, timeout: float, accept: str = "application/vnd.github+json") -> bytes:
headers = {"Accept": accept, "User-Agent": "agent-reach"}
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
+ if not token:
+ from agent_reach.config import Config
+
+ token = Config(read_only=True).get("github_token")
if token:
headers["Authorization"] = f"Bearer {token}"
try:
diff --git a/agent_reach/channels/linkedin.py b/agent_reach/channels/linkedin.py
index 8c9cfe42..c81c0dc8 100644
--- a/agent_reach/channels/linkedin.py
+++ b/agent_reach/channels/linkedin.py
@@ -22,6 +22,29 @@ _CONFIG_COMMAND = (
"mcporter config add linkedin --command uvx "
"--arg mcp-server-linkedin@latest --env UV_HTTP_TIMEOUT=300 --scope home"
)
+_LINKEDIN_MCP_VERSION = "4.26.2"
+
+
+def _own_config_path():
+ from agent_reach.runtime import state
+
+ return state.root() / "mcporter.json"
+
+
+def _own_servers() -> dict:
+ path = _own_config_path()
+ try:
+ return dict(json.loads(path.read_text(encoding="utf-8")).get("mcpServers") or {})
+ except (OSError, ValueError):
+ return {}
+
+
+def _write_own_servers(servers: dict) -> None:
+ from agent_reach.runtime import state
+ from agent_reach.utils.paths import atomic_write_private_text, make_private_dir
+
+ make_private_dir(state.root())
+ atomic_write_private_text(_own_config_path(), json.dumps({"mcpServers": servers}, indent=2))
class LinkedInChannel(Channel):
@@ -31,6 +54,34 @@ class LinkedInChannel(Channel):
tier = 2
level = "optional"
+ tools = ("mcporter",)
+ prereqs = ("node", "uv")
+ session = "linkedin-mcp"
+ session_home = False
+ login_argv = (
+ "uvx", f"mcp-server-linkedin@{_LINKEDIN_MCP_VERSION}", "--login",
+ "--user-data-dir", "{session}/profile", "--claim-profile-root",
+ )
+
+ def on_add(self) -> None:
+ from agent_reach.runtime.sessions import session_dir
+
+ servers = _own_servers()
+ servers["linkedin"] = {
+ "command": "uvx",
+ "args": [
+ f"mcp-server-linkedin@{_LINKEDIN_MCP_VERSION}",
+ "--user-data-dir", f"{session_dir(self.session)}/profile", "--claim-profile-root",
+ ],
+ "env": {"UV_HTTP_TIMEOUT": "300"},
+ }
+ _write_own_servers(servers)
+
+ def on_remove(self) -> None:
+ servers = _own_servers()
+ if servers.pop("linkedin", None) is not None:
+ _write_own_servers(servers)
+
actions = (
Action(
"jobs",
@@ -91,18 +142,23 @@ class LinkedInChannel(Channel):
# ── unified entry backends ──
def _mcp_jobs(self, *, query: str, location, limit: int, timeout: float) -> list:
- out = run_cmd(["mcporter", "config", "list", "--json"], timeout=min(timeout, 20))
- names = configured_server_names(out)
- server = next((n for n in ("linkedin", "mcp-server-linkedin", "linkedin-scraper", "linkedin-scraper-mcp") if n in names), None)
- if server is None:
- raise ReachError(NEED_SETUP, "no LinkedIn MCP server is registered in mcporter", hint=f"Set up: {_CONFIG_COMMAND}")
+ # Prefer our own registration; fall back to one the user set up globally.
+ if "linkedin" in _own_servers():
+ base, server = ["mcporter", "--config", str(_own_config_path())], "linkedin"
+ else:
+ out = run_cmd(["mcporter", "config", "list", "--json"], timeout=min(timeout, 20))
+ names = configured_server_names(out)
+ server = next((n for n in ("linkedin", "mcp-server-linkedin", "linkedin-scraper", "linkedin-scraper-mcp") if n in names), None)
+ base = ["mcporter"]
+ if server is None:
+ raise ReachError(NEED_SETUP, "LinkedIn is not set up", hint="Run `agent-reach add linkedin`, then `agent-reach login linkedin`.")
# The official server names the query `keywords`; the scraper variants use `query`.
args = {"keywords": query} if server in ("linkedin", "mcp-server-linkedin") else {"query": query, "max_results": limit}
if location:
args["location"] = location
try:
raw = run_cmd(
- ["mcporter", "call", f"{server}.search_jobs", "--args", json.dumps(args), "--output", "json"],
+ [*base, "call", f"{server}.search_jobs", "--args", json.dumps(args), "--output", "json"],
timeout=timeout,
)
except CommandFailed as exc:
diff --git a/agent_reach/channels/reddit.py b/agent_reach/channels/reddit.py
index a31999f5..2382d4d4 100644
--- a/agent_reach/channels/reddit.py
+++ b/agent_reach/channels/reddit.py
@@ -51,6 +51,14 @@ class RedditChannel(Channel):
level = "optional"
login_url = "https://www.reddit.com/login/"
+ tools = ("opencli",)
+ prereqs = ("node", "chrome")
+
+ def setup_problems(self):
+ from agent_reach.runtime.browser import setup_problems
+
+ return setup_problems()
+
actions = (
Action(
"search",
diff --git a/agent_reach/channels/twitter.py b/agent_reach/channels/twitter.py
index 7544f6d4..c4d274dc 100644
--- a/agent_reach/channels/twitter.py
+++ b/agent_reach/channels/twitter.py
@@ -55,6 +55,14 @@ class TwitterChannel(Channel):
# browser cookies whenever verification fails.
level = "experimental"
login_url = "https://x.com/i/flow/login"
+ tools = ("opencli",)
+ prereqs = ("node", "chrome")
+
+ def setup_problems(self):
+ from agent_reach.runtime.browser import setup_problems
+
+ return setup_problems()
+
actions = (
Action(
"search",
diff --git a/agent_reach/channels/xiaohongshu.py b/agent_reach/channels/xiaohongshu.py
index f4dfcfaa..86eaaa7d 100644
--- a/agent_reach/channels/xiaohongshu.py
+++ b/agent_reach/channels/xiaohongshu.py
@@ -171,6 +171,14 @@ class XiaoHongShuChannel(Channel):
level = "optional"
login_url = "https://www.xiaohongshu.com/explore"
+ tools = ("opencli",)
+ prereqs = ("node", "chrome")
+
+ def setup_problems(self):
+ from agent_reach.runtime.browser import setup_problems
+
+ return setup_problems()
+
actions = (
Action(
"search",
diff --git a/agent_reach/channels/xiaoyuzhou.py b/agent_reach/channels/xiaoyuzhou.py
index 24db14d9..96fc12c8 100644
--- a/agent_reach/channels/xiaoyuzhou.py
+++ b/agent_reach/channels/xiaoyuzhou.py
@@ -22,6 +22,13 @@ class XiaoyuzhouChannel(Channel):
tier = 1
level = "optional"
+ prereqs = ("ffmpeg",)
+
+ def setup_problems(self):
+ if os.environ.get("GROQ_API_KEY") or Config(read_only=True).get("groq_api_key"):
+ return []
+ return ["no Groq API key: get one free at https://console.groq.com, then `agent-reach configure groq-key`"]
+
actions = (
Action(
"transcribe",
diff --git a/agent_reach/channels/xueqiu.py b/agent_reach/channels/xueqiu.py
index 765837b5..e5a05778 100644
--- a/agent_reach/channels/xueqiu.py
+++ b/agent_reach/channels/xueqiu.py
@@ -15,9 +15,9 @@ from agent_reach.runtime.run import http_request
from .base import Action, Channel, Param
_XQ_LOGIN_HINT = (
- "Xueqiu community data needs a browser session. Ask the user to open "
- "https://xueqiu.com in Chrome, then run `agent-reach configure --from-browser "
- "chrome --platform xueqiu`. The session expires within hours."
+ "Xueqiu community data needs a browser session. Run `agent-reach login xueqiu`, "
+ "let the user open xueqiu.com in the Agent Reach browser, then run "
+ "`agent-reach login xueqiu --sync`. While that browser is open, Agent Reach renews the session itself."
)
_UA = (
@@ -148,15 +148,43 @@ def _xueqiu_symbol(market: str, code: str) -> str:
return code.split(".")[0].upper()
-def _xq_json(url: str) -> Any:
+def _refresh_from_browser() -> bool:
+ """Pull a fresh Xueqiu session from the Agent Reach browser, if it is running."""
+ global _cookies_initialized
+ from agent_reach.runtime import browser, cdp
+
+ if not browser.is_running():
+ return False
+ jar = {c["name"]: c["value"] for c in cdp.cookies("xueqiu.com")}
+ if "xq_a_token" not in jar:
+ try:
+ browser.open_url("https://xueqiu.com/")
+ except Exception: # noqa: BLE001
+ return False
+ import time
+
+ time.sleep(4)
+ jar = {c["name"]: c["value"] for c in cdp.cookies("xueqiu.com")}
+ if "xq_a_token" not in jar:
+ return False
+ from agent_reach.config import Config
+
+ Config().set("xueqiu_cookie", "; ".join(f"{k}={v}" for k, v in jar.items()))
+ _cookie_jar.clear()
+ _cookies_initialized = False
+ return True
+
+
+def _xq_json(url: str, _retried: bool = False) -> Any:
try:
return _get_json(url)
- except urllib.error.HTTPError as exc:
- if exc.code in (400, 401, 403):
- raise ReachError(NEED_LOGIN, f"Xueqiu rejected the session (HTTP {exc.code})", hint=_XQ_LOGIN_HINT) from None
- raise
- except json.JSONDecodeError:
- raise ReachError(NEED_LOGIN, "Xueqiu returned a verification page instead of data", hint=_XQ_LOGIN_HINT) from None
+ except (urllib.error.HTTPError, json.JSONDecodeError) as exc:
+ rejected = isinstance(exc, json.JSONDecodeError) or exc.code in (400, 401, 403)
+ if not rejected:
+ raise
+ if not _retried and _refresh_from_browser():
+ return _xq_json(url, _retried=True)
+ raise ReachError(NEED_LOGIN, "Xueqiu rejected the session", hint=_XQ_LOGIN_HINT) from None
_HOT_POSTS_URL = (
@@ -196,6 +224,17 @@ class XueqiuChannel(Channel):
tier = 1
level = "optional"
+ login_url = "https://xueqiu.com/"
+ logout_keys = ("xueqiu_cookie",)
+
+ def sync_login(self):
+ if not _refresh_from_browser():
+ raise ReachError(
+ NEED_LOGIN, "no Xueqiu session found in the Agent Reach browser",
+ hint="Run `agent-reach login xueqiu`, let the user open xueqiu.com there, then `agent-reach login xueqiu --sync`.",
+ )
+ return {"synced": "xueqiu_cookie"}
+
actions = (
Action(
"quote",
diff --git a/agent_reach/channels/youtube.py b/agent_reach/channels/youtube.py
index a546019b..9206f2a0 100644
--- a/agent_reach/channels/youtube.py
+++ b/agent_reach/channels/youtube.py
@@ -153,6 +153,13 @@ class YouTubeChannel(Channel):
(("yt-dlp", "_ytdlp_subtitle"),),
live_test={"target": "https://www.youtube.com/watch?v=jNQXAC9IVRw"},
),
+ Action(
+ "transcribe",
+ "Speech-to-text of a video's audio (uses Groq/OpenAI Whisper quota)",
+ (Param("target", "video link or id"),),
+ (("whisper", "_whisper_transcribe"),),
+ timeout=1800,
+ ),
)
def can_handle(self, url: str) -> bool:
@@ -318,3 +325,19 @@ class YouTubeChannel(Channel):
title = next((ln for ln in out.splitlines() if ln.strip()), None)
code = best.rsplit(".", 2)[-2] if best.count(".") >= 2 else None
return [make_item(title=title, url=url, text=text, raw={"lang": code})]
+
+ def _whisper_transcribe(self, *, target: str, timeout: float) -> list:
+ from agent_reach.transcribe import NoProviderConfigured, TranscribeError
+ from agent_reach.transcribe import transcribe as _transcribe
+
+ url = _video_url(target)
+ try:
+ text = _transcribe(url)
+ except NoProviderConfigured:
+ raise ReachError(
+ "NEED_SETUP", "no Whisper API key configured",
+ hint="Ask the user for a free key from https://console.groq.com, then run `agent-reach configure groq-key`.",
+ ) from None
+ except TranscribeError as exc:
+ raise ReachError("UPSTREAM_BROKEN", str(exc)[:300]) from None
+ return [make_item(url=url, text=text)]
diff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.py
index 5b054d24..f1404b3e 100644
--- a/agent_reach/runtime/browser.py
+++ b/agent_reach/runtime/browser.py
@@ -173,3 +173,10 @@ def status() -> dict:
"opencli_context": ctx,
"opencli_connected": connected,
}
+
+
+def setup_problems() -> List[str]:
+ """What blocks browser-login channels right now (offline checks only)."""
+ if not bound_context():
+ return ["Agent Reach browser not set up: run `agent-reach browser setup`"]
+ return []
diff --git a/agent_reach/runtime/cdp.py b/agent_reach/runtime/cdp.py
new file mode 100644
index 00000000..00f89d2f
--- /dev/null
+++ b/agent_reach/runtime/cdp.py
@@ -0,0 +1,116 @@
+"""Minimal Chrome DevTools Protocol client for the Agent Reach browser (127.0.0.1 only).
+
+Only used against the dedicated browser, never the user's own Chrome.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import os
+import socket
+import struct
+import urllib.request
+from typing import List, Optional
+from urllib.parse import urlparse
+
+from .browser import CDP_URL
+
+_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+_TIMEOUT = 5
+
+
+def _json(path: str):
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never proxy
+ try:
+ with opener.open(f"{CDP_URL}{path}", timeout=_TIMEOUT) as resp:
+ return json.loads(resp.read())
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _read_frame(sock: socket.socket, buf: bytes):
+ while True:
+ while len(buf) < 2:
+ chunk = sock.recv(4096)
+ if not chunk:
+ return None, buf
+ buf += chunk
+ opcode, length, head = buf[0] & 0x0F, buf[1] & 0x7F, 2
+ if length in (126, 127):
+ need = 2 if length == 126 else 8
+ while len(buf) < head + need:
+ chunk = sock.recv(4096)
+ if not chunk:
+ return None, buf
+ buf += chunk
+ length = struct.unpack(">H" if need == 2 else ">Q", buf[head:head + need])[0]
+ head += need
+ while len(buf) < head + length:
+ chunk = sock.recv(65536)
+ if not chunk:
+ return None, buf
+ buf += chunk
+ payload, buf = buf[head:head + length], buf[head + length:]
+ if opcode == 0x8:
+ return None, buf
+ if opcode in (0x0, 0x1, 0x2):
+ return payload, buf
+
+
+def _send(sock: socket.socket, text: str) -> None:
+ payload = text.encode("utf-8")
+ mask = os.urandom(4)
+ n = len(payload)
+ head = bytes([0x81]) + (
+ bytes([0x80 | n]) if n < 126
+ else bytes([0x80 | 126]) + struct.pack(">H", n) if n < 65536
+ else bytes([0x80 | 127]) + struct.pack(">Q", n)
+ )
+ sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
+
+
+def call(method: str, params: Optional[dict] = None) -> Optional[dict]:
+ """One browser-level CDP call; returns `result` or None if unreachable."""
+ ws = (_json("/json/version") or {}).get("webSocketDebuggerUrl")
+ if not ws:
+ return None
+ u = urlparse(ws)
+ host, port = u.hostname or "127.0.0.1", u.port or 80
+ try:
+ with socket.create_connection((host, port), timeout=_TIMEOUT) as sock:
+ sock.settimeout(_TIMEOUT)
+ key = base64.b64encode(os.urandom(16)).decode()
+ sock.sendall(
+ (f"GET {u.path or '/'} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\n"
+ f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode()
+ )
+ resp = b""
+ while b"\r\n\r\n" not in resp:
+ chunk = sock.recv(4096)
+ if not chunk:
+ return None
+ resp += chunk
+ head, _, buf = resp.partition(b"\r\n\r\n")
+ accept = base64.b64encode(hashlib.sha1((key + _GUID).encode()).digest()).decode()
+ if head.split(b"\r\n", 1)[0].split()[1:2] != [b"101"] or accept not in head.decode("latin-1"):
+ return None
+ _send(sock, json.dumps({"id": 1, "method": method, "params": params or {}}))
+ for _ in range(32):
+ payload, buf = _read_frame(sock, buf)
+ if payload is None:
+ return None
+ msg = json.loads(payload.decode("utf-8"))
+ if msg.get("id") == 1:
+ return msg.get("result")
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def cookies(domain: str) -> List[dict]:
+ """Cookies the dedicated browser holds for `domain` (and its subdomains)."""
+ result = call("Storage.getCookies") or {}
+ d = domain.lstrip(".")
+ return [c for c in result.get("cookies", []) if c.get("domain", "").lstrip(".").endswith(d)]
diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.py
index 74926dec..68071678 100644
--- a/agent_reach/runtime/cli.py
+++ b/agent_reach/runtime/cli.py
@@ -1,9 +1,13 @@
-"""Unified entry: `agent-reach <channel> <action>`, `read <url>`, `channels`, `check`, `login`, `logout`.
+"""Unified entry for Agent Reach.
-Everything here prints JSON to stdout (one object per invocation) so agents
-never parse prose. Logs and warnings go to stderr. Exit code 0 = ok, 1 = error.
-`login` is for the user: the upstream's interactive output (QR codes, prompts)
-goes to stderr so stdout still carries only the final JSON.
+Agent commands: <channel> <action>, read <url>, channels
+Management commands: setup, add, remove, login, logout, browser, doctor, check,
+ watch, 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
+output (QR codes, prompts) on stderr so stdout still carries only the JSON.
"""
from __future__ import annotations
@@ -11,7 +15,6 @@ from __future__ import annotations
import argparse
import json
import os
-import shutil
import subprocess
import sys
from typing import Dict, List, Optional, Sequence
@@ -21,10 +24,41 @@ from agent_reach.channels.base import Action, Channel
from . import browser
from .dispatch import DEFAULT_TIMEOUT, find_action, run_action
-from .result import BAD_INPUT, NEED_SETUP, SCHEMA_VERSION, UPSTREAM_BROKEN, ReachError, envelope
+from .result import (
+ BAD_INPUT,
+ DEFAULT_HINTS,
+ NEED_SETUP,
+ SCHEMA_VERSION,
+ UPSTREAM_BROKEN,
+ ReachError,
+ envelope,
+)
from .sessions import clear_session, has_login_state, import_legacy_state, session_env
-_TOP_LEVEL = ("channels", "check", "read", "login", "logout", "browser")
+_MANAGEMENT = (
+ "setup", "add", "remove", "update", "doctor", "watch", "uninstall", "configure", "version",
+)
+_TOP_LEVEL = ("channels", "check", "read", "login", "logout", "browser", "help", "-h", "--help") + _MANAGEMENT
+
+HELP = """agent-reach — internet access for AI agents (all output is JSON)
+
+For agents:
+ agent-reach channels list channels, actions, params
+ agent-reach <channel> <action> [args] e.g. agent-reach bilibili search python
+ 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 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 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
+"""
def unified_channels() -> List[Channel]:
@@ -39,11 +73,22 @@ def _channel(name: str) -> Optional[Channel]:
def handles(argv: Sequence[str]) -> bool:
"""Whether this argv belongs to the unified entry (vs. legacy commands)."""
if not argv:
- return False
+ return True
head = argv[0]
return head in _TOP_LEVEL or _channel(head) is not None
+def _mgmt(action: str, fn, *args, **kwargs) -> int:
+ """Run a management function and print {schema_version, ok, action, result, error}."""
+ try:
+ result, error = fn(*args, **kwargs), None
+ except ReachError as err:
+ result = None
+ error = {"code": err.code, "message": err.message, "hint": err.hint or DEFAULT_HINTS.get(err.code, "")}
+ return _emit({"schema_version": SCHEMA_VERSION, "ok": error is None, "action": action,
+ "result": result, "error": error})
+
+
class _ArgError(Exception):
pass
@@ -165,56 +210,127 @@ def _cmd_channels(_args: Sequence[str]) -> int:
def _cmd_check(args: Sequence[str]) -> int:
+ from . import manage
+
parser = _Parser(prog="check", add_help=False)
parser.add_argument("channels", nargs="*")
parser.add_argument("--text", action="store_true")
parser.add_argument("--timeout", type=float, default=60.0)
try:
ns = parser.parse_args(list(args))
+ out = manage.run_checks(ns.channels or None, timeout=ns.timeout)
except _ArgError as exc:
return _bad_input(None, "check", str(exc))
- selected = unified_channels()
- if ns.channels:
- unknown = set(ns.channels) - {ch.name for ch in selected}
- if unknown:
- return _bad_input(None, "check", f"unknown channel(s): {', '.join(sorted(unknown))}")
- selected = [ch for ch in selected if ch.name in ns.channels]
-
- results = []
- for ch in selected:
- for action in ch.actions:
- if action.live_test is None:
- continue
- for label, _ in action.backends:
- out = run_action(ch, action.name, dict(action.live_test), timeout=ns.timeout, only_backend=label)
- passed = bool(out["ok"] and out["items"])
- err = out["error"] or ({"code": "EMPTY", "message": "succeeded but returned no items"} if not passed else None)
- results.append(
- {
- "channel": ch.name,
- "action": action.name,
- "backend": label,
- "passed": passed,
- "elapsed_ms": out["meta"]["elapsed_ms"],
- "error": err and {"code": err["code"], "message": err["message"]},
- }
- )
-
- # An action passes when at least one of its backends works.
- by_action: Dict[tuple, bool] = {}
- for r in results:
- key = (r["channel"], r["action"])
- by_action[key] = by_action.get(key, False) or r["passed"]
- ok = bool(results) and all(by_action.values())
-
+ except ReachError as err:
+ return _bad_input(None, "check", err.message)
if ns.text:
- for r in results:
+ by_action: Dict[tuple, bool] = {}
+ for r in out["results"]:
mark = "PASS" if r["passed"] else "FAIL"
why = "" if r["passed"] else f" {r['error']['code']}: {r['error']['message']}"
sys.stdout.write(f"{mark} {r['channel']} {r['action']} [{r['backend']}] {r['elapsed_ms']}ms{why}\n")
+ key = (r["channel"], r["action"])
+ by_action[key] = by_action.get(key, False) or r["passed"]
sys.stdout.write(f"\n{sum(by_action.values())}/{len(by_action)} actions working\n")
- return 0 if ok else 1
- return _emit({"schema_version": SCHEMA_VERSION, "ok": ok, "results": results})
+ return 0 if out["ok"] else 1
+ return _emit({"schema_version": SCHEMA_VERSION, **out})
+
+
+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)
+ sys.stdout.write(f"Agent Reach {result['version']}\n\n")
+ for c in result["channels"]:
+ extra = "; ".join(c["problems"]) or c.get("hint", "")
+ sys.stdout.write(f"{c['status']:<12} {c['channel']:<12} {c['level']:<13} {extra}\n")
+ return 0
+
+
+def _cmd_watch(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
+
+
+def _cmd_management(head: str, args: Sequence[str]) -> int:
+ from agent_reach import __version__
+
+ from . import manage
+
+ parser = _Parser(prog=head, add_help=False)
+ if head in ("add", "remove"):
+ parser.add_argument("channel")
+ if head == "add":
+ parser.add_argument("--allow-upgrade", action="store_true")
+ elif head == "update":
+ parser.add_argument("--check", action="store_true")
+ parser.add_argument("--sync-only", action="store_true")
+ elif head == "uninstall":
+ parser.add_argument("--dry-run", action="store_true")
+ elif head == "configure":
+ parser.add_argument("key")
+ parser.add_argument("value", nargs="?")
+ parser.add_argument("--stdin", action="store_true")
+ try:
+ ns = parser.parse_args(list(args))
+ except _ArgError as exc:
+ return _bad_input(None, head, str(exc))
+ if head == "setup":
+ return _mgmt(head, manage.setup)
+ if head == "add":
+ return _mgmt(head, manage.add, ns.channel, allow_upgrade=ns.allow_upgrade)
+ if head == "remove":
+ return _mgmt(head, manage.remove, ns.channel)
+ if head == "update":
+ if ns.sync_only:
+ return _mgmt(head, manage.sync)
+ return _mgmt(head, manage.update, check_only=ns.check)
+ if head == "uninstall":
+ return _mgmt(head, manage.uninstall, dry_run=ns.dry_run)
+ if head == "configure":
+ value = ns.value
+ if ns.stdin:
+ value = sys.stdin.read().strip()
+ elif value is None and sys.stdin.isatty():
+ import getpass
+
+ value = getpass.getpass(f"{ns.key}: ").strip()
+ return _mgmt(head, manage.configure, ns.key, value or "")
+ return _mgmt(head, lambda: {"version": __version__, "install_method": manage.install_method()})
+
+
+def _apply_saved_proxy() -> None:
+ """Use the proxy saved by `configure proxy` unless the shell already sets one."""
+ if os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy"):
+ return
+ try:
+ from agent_reach.config import Config
+
+ proxy = Config(read_only=True).get("proxy")
+ except Exception: # noqa: BLE001
+ return
+ if proxy:
+ os.environ["HTTPS_PROXY"] = os.environ["HTTP_PROXY"] = str(proxy)
def _login_info(ch: Channel):
@@ -235,7 +351,7 @@ def _login_channel(cmd: str, args: Sequence[str]):
ch = _channel(ns.channel)
if ch is None:
raise _ArgError(f"unknown channel: {ns.channel}")
- if cmd == "logout" and not ch.session:
+ if cmd == "logout" and not (ch.session or ch.logout_keys):
hint = " Log out in the Agent Reach browser window instead." if ch.login_url else ""
raise _ArgError(f"{ch.name} has no login state managed by Agent Reach.{hint}")
if cmd == "login" and not (ch.session or ch.login_url):
@@ -258,20 +374,35 @@ def _cmd_login(args: Sequence[str]) -> int:
browser.start(ch.login_url)
except ReachError as err:
return _emit(envelope(channel=ch.name, action="login", error=err))
+ needs_sync = bool(ch.session) or type(ch).sync_login is not Channel.sync_login
nxt = (
f"After the user logs in, run `agent-reach login {ch.name} --sync`."
- if ch.session else "The user logs in in that window; then retry the action."
+ if needs_sync else "The user logs in in that window; then retry the action."
)
return _emit(envelope(channel=ch.name, action="login", backend="agent-reach-browser",
items=[{"opened": ch.login_url, "next": nxt}]))
- exe = shutil.which(ch.login_argv[0])
+ try:
+ synced = ch.sync_login()
+ except ReachError as err:
+ return _emit(envelope(channel=ch.name, action="login", error=err))
+ if synced is not None:
+ return _emit(envelope(channel=ch.name, action="login", backend="agent-reach-browser", items=[synced]))
+ if not ch.login_argv:
+ return _bad_input(ch.name, "login", f"{ch.name} has nothing to sync; just log in in the Agent Reach browser")
+ from .tools import resolve
+
+ exe = resolve(ch.login_argv[0])
if not exe:
- return _emit(envelope(channel=ch.name, action="login",
- error=ReachError(NEED_SETUP, f"{ch.login_argv[0]} is not installed")))
+ return _emit(envelope(channel=ch.name, action="login", error=ReachError(
+ NEED_SETUP, f"{ch.login_argv[0]} is not installed", hint=f"Run `agent-reach add {ch.name}` first.")))
+ from .sessions import session_dir
+
+ argv = [a.replace("{session}", str(session_dir(ch.session))) for a in ch.login_argv[1:]]
env = dict(os.environ)
- env.update(session_env(ch.session))
+ if ch.session_home:
+ env.update(session_env(ch.session))
# Interactive: the user sees the QR code / prompts on stderr; stdout stays JSON.
- code = subprocess.call([exe, *ch.login_argv[1:]], env=env, stdout=sys.stderr, stderr=sys.stderr)
+ code = subprocess.call([exe, *argv], env=env, stdout=sys.stderr, stderr=sys.stderr)
if code != 0 or not has_login_state(ch.session):
return _emit(envelope(channel=ch.name, action="login",
error=ReachError(UPSTREAM_BROKEN, f"login did not complete (exit {code})")))
@@ -283,8 +414,16 @@ def _cmd_logout(args: Sequence[str]) -> int:
ch, _ = _login_channel("logout", args)
except _ArgError as exc:
return _bad_input(None, "logout", str(exc))
- removed = clear_session(ch.session)
- return _emit(envelope(channel=ch.name, action="logout", backend=ch.session, items=[{"removed": removed}]))
+ removed = clear_session(ch.session) if ch.session else False
+ if ch.logout_keys:
+ from agent_reach.config import Config
+
+ cfg = Config()
+ for key in ch.logout_keys:
+ if cfg.get(key):
+ cfg.delete(key)
+ removed = True
+ return _emit(envelope(channel=ch.name, action="logout", backend=ch.session or "config", items=[{"removed": removed}]))
def _cmd_browser(args: Sequence[str]) -> int:
@@ -320,6 +459,10 @@ def _cmd_browser(args: Sequence[str]) -> int:
def main(argv: Sequence[str]) -> int:
+ if not argv or argv[0] in ("help", "-h", "--help"):
+ sys.stdout.write(HELP)
+ return 0
+ _apply_saved_proxy()
head, rest = argv[0], argv[1:]
if head == "channels":
return _cmd_channels(rest)
@@ -333,6 +476,12 @@ def main(argv: Sequence[str]) -> int:
return _cmd_logout(rest)
if head == "browser":
return _cmd_browser(rest)
+ if head == "doctor":
+ return _cmd_doctor(rest)
+ if head == "watch":
+ return _cmd_watch(rest)
+ if head in _MANAGEMENT:
+ return _cmd_management(head, rest)
channel = _channel(head)
assert channel is not None # guaranteed by handles()
return _cmd_action(channel, rest)
diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.py
new file mode 100644
index 00000000..35b4abcf
--- /dev/null
+++ b/agent_reach/runtime/manage.py
@@ -0,0 +1,461 @@
+"""Management commands: setup, add, remove, update, doctor, watch, uninstall, configure.
+
+Each public function returns a plain dict `result` or raises ReachError; the CLI
+wraps it in {schema_version, ok, action, result, error}.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import urllib.request
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from agent_reach import __version__
+
+from . import state, tools
+from .result import BAD_INPUT, NEED_SETUP, UPSTREAM_BROKEN, ReachError
+
+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] = {
+ "node": {"check": lambda: bool(shutil.which("node") and shutil.which("npm")),
+ "hint": "Install Node.js: https://nodejs.org (macOS: brew install node)"},
+ "git": {"check": lambda: bool(shutil.which("git")), "hint": "Install git (macOS: xcode-select --install)"},
+ "chrome": {"check": lambda: _chrome_present(), "hint": "Install Google Chrome: https://www.google.com/chrome"},
+ "ffmpeg": {"check": lambda: bool(shutil.which("ffmpeg")), "hint": "Install ffmpeg (macOS: brew install ffmpeg)"},
+ "uv": {"check": lambda: bool(shutil.which("uvx")),
+ "hint": "Install uv: https://docs.astral.sh/uv/getting-started/installation/"},
+}
+
+
+def _channels():
+ from .cli import unified_channels
+
+ return unified_channels()
+
+
+def _channel(name: str):
+ ch = next((c for c in _channels() if c.name == name), None)
+ if ch is None:
+ valid = ", ".join(c.name for c in _channels())
+ raise ReachError(BAD_INPUT, f"unknown channel: {name}; valid: {valid}")
+ return ch
+
+
+def is_added(ch, data: Optional[dict] = None) -> bool:
+ return ch.level == "default" or ch.name in (data or state.load())["channels"]
+
+
+def missing_prereqs(ch) -> List[str]:
+ return [p for p in ch.prereqs if not PREREQS[p]["check"]()]
+
+
+# ── 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."""
+ from .dispatch import run_action
+
+ selected = _channels()
+ if names:
+ unknown = set(names) - {c.name for c in selected}
+ if unknown:
+ raise ReachError(BAD_INPUT, f"unknown channel(s): {', '.join(sorted(unknown))}")
+ selected = [c for c in selected if c.name in names]
+ results = []
+ for ch in selected:
+ for action in ch.actions:
+ if action.live_test is None:
+ continue
+ for label, _ in action.backends:
+ out = run_action(ch, action.name, dict(action.live_test), timeout=timeout, only_backend=label)
+ passed = bool(out["ok"] and out["items"])
+ err = out["error"] or (None if passed else {"code": "EMPTY", "message": "succeeded but returned no items"})
+ results.append({
+ "channel": ch.name, "action": action.name, "backend": label, "passed": passed,
+ "elapsed_ms": out["meta"]["elapsed_ms"],
+ "error": err and {"code": err["code"], "message": err["message"]},
+ })
+ by_action: Dict[tuple, bool] = {}
+ codes: Dict[tuple, str] = {}
+ for r in results:
+ key = (r["channel"], r["action"])
+ by_action[key] = by_action.get(key, False) or r["passed"]
+ if not r["passed"] and key not in codes:
+ codes[key] = r["error"]["code"]
+ data = state.load()
+ for ch in selected:
+ 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}
+ state.save(data)
+ return {"ok": bool(results) and all(by_action.values()), "results": results}
+
+
+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}"}
+ problems = [f"missing {p}: {PREREQS[p]['hint']}" for p in missing_prereqs(ch)]
+ problems += [f"{t} not installed: run `agent-reach add {ch.name}`" for t in ch.tools
+ if not tools.resolve(tools.TOOLS[t].commands[0])]
+ problems += ch.setup_problems()
+ if problems:
+ return {"status": "needs_setup", "problems": problems}
+ check = data["checks"].get(ch.name)
+ if check and state.age_seconds(check["at"]) < CHECK_FRESH_SECONDS:
+ failed = [a for a, ok in check["actions"].items() if not ok]
+ if failed:
+ codes = check.get("codes", {})
+ if all(codes.get(a) == "NEED_LOGIN" for a in failed):
+ return {"status": "needs_login", "problems": [f"needs login for: {', '.join(failed)}"],
+ "hint": f"agent-reach login {ch.name}", "checked_at": check["at"]}
+ return {"status": "broken", "problems": [f"live check failed: {', '.join(failed)}"], "checked_at": check["at"]}
+ return {"status": "ready", "problems": [], "checked_at": check["at"]}
+ 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)
+ data = state.load()
+ channels = []
+ for ch in _channels():
+ channels.append({"channel": ch.name, "level": ch.level, **channel_status(ch, data)})
+ 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)}",
+ hint="; ".join(PREREQS[p]["hint"] for p in missing))
+ installed = [tools.ensure(t, allow_upgrade=allow_upgrade) for t in ch.tools]
+ ch.on_add()
+ data = state.load()
+ 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:
+ nxt.append(f"log in: `agent-reach login {name}`")
+ return {"channel": name, "added": True, "tools": installed, "next": nxt}
+
+
+def remove(name: str) -> dict:
+ ch = _channel(name)
+ if ch.level == "default":
+ raise ReachError(BAD_INPUT, f"{name} is a default channel and cannot be removed")
+ from .sessions import clear_session
+
+ data = state.load()
+ was_added = data["channels"].pop(name, None) is not None
+ data["checks"].pop(name, None)
+ state.save(data)
+ ch.on_remove()
+ if ch.session:
+ clear_session(ch.session)
+ if ch.logout_keys:
+ from agent_reach.config import Config
+
+ cfg = Config()
+ for key in ch.logout_keys:
+ if cfg.get(key):
+ cfg.delete(key)
+ still_needed = {t for c in _channels() if c.name != name and is_added(c, data) for t in c.tools}
+ removed_tools = [t for t in ch.tools if t not in still_needed and tools.remove_private(t)]
+ return {"channel": name, "removed": was_added, "removed_tools": removed_tools}
+
+
+# ── skill (the agent-facing instructions) ──
+
+def skill_roots() -> List[Path]:
+ from agent_reach.utils.paths import home_dir
+
+ home = home_dir()
+ roots = [home / ".agents" / "skills", home / ".claude" / "skills",
+ home / ".config" / "opencode" / "skills", home / ".openclaw" / "skills"]
+ oc = os.environ.get("OPENCLAW_HOME")
+ if oc:
+ roots.insert(0, Path(oc) / ".openclaw" / "skills")
+ return roots
+
+
+def _skill_lang() -> str:
+ for var in ("AGENT_REACH_LANG", "LC_ALL", "LC_MESSAGES", "LANG"):
+ v = os.environ.get(var, "").strip().lower()
+ if v.startswith("en"):
+ return "en"
+ return "zh"
+
+
+def render_skill(lang: Optional[str] = None) -> str:
+ from importlib.resources import files
+
+ lang = lang or _skill_lang()
+ template = files("agent_reach").joinpath("skill", "SKILL_en.md" if lang == "en" else "SKILL.md").read_text("utf-8")
+ 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 "-"
+ 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 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()]
+
+
+# ── setup / migrate ──
+
+def migrate() -> dict:
+ """First run after an older Agent Reach: create state, keep credentials, suggest channels."""
+ from agent_reach.config import Config
+
+ cfg = Config(read_only=True)
+ hints = []
+ for cmd, channel in (("bili", "bilibili"), ("opencli", "xiaohongshu"), ("boss", "boss"), ("mcporter", "linkedin")):
+ if shutil.which(cmd):
+ hints.append(channel)
+ if cfg.get("xueqiu_cookie"):
+ hints.append("xueqiu")
+ if cfg.get("groq_api_key"):
+ hints.append("xiaoyuzhou")
+ 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)),
+ "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()
+ 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 [])}
+ for c in _channels() if c.level != "default"
+ ]
+ 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,
+ "optional_channels": optional,
+ "migration": migration,
+ }
+
+
+# ── update ──
+
+def _version_tuple(v: str) -> tuple:
+ try:
+ return tuple(int(x) for x in v.strip().lstrip("v").split("."))
+ except ValueError:
+ return ()
+
+
+def update_check(quiet: bool = False) -> 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 {
+ "current": __version__,
+ "latest": latest,
+ "update_available": _version_tuple(latest) > _version_tuple(__version__),
+ "notes": (rel.get("body") or "")[:2000],
+ }
+
+
+def install_method() -> str:
+ """How this copy of Agent Reach was installed: uv | pipx | pip | editable."""
+ try:
+ from importlib.metadata import distribution
+
+ direct = distribution("agent-reach").read_text("direct_url.json") or "{}"
+ if json.loads(direct).get("dir_info", {}).get("editable"):
+ return "editable"
+ except Exception: # noqa: BLE001
+ pass
+ prefix = sys.prefix.replace("\\", "/")
+ if "/uv/tools/" in prefix:
+ return "uv"
+ if "/pipx/venvs/" in prefix:
+ return "pipx"
+ return "pip"
+
+
+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 sync() -> dict:
+ """After the program itself changed: bring tools to this version's pins, refresh the skill."""
+ migration = migrate() if not state.exists() else None
+ data = state.load()
+ synced, problems = [], []
+ for ch in _channels():
+ if ch.level == "default" or ch.name not in data["channels"]:
+ continue
+ for t in ch.tools:
+ try:
+ synced.append(tools.ensure(t))
+ except ReachError as err:
+ 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}
+
+
+def update(check_only: bool = False) -> dict:
+ info = update_check()
+ if check_only:
+ 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)
+ if proc.returncode != 0:
+ raise ReachError(UPSTREAM_BROKEN, f"upgrade failed: {proc.stderr.strip()[-300:]}",
+ hint=f"Run manually: {' '.join(cmd)}")
+ exe = shutil.which("agent-reach") or sys.argv[0]
+ out = subprocess.run([exe, "update", "--sync-only"], capture_output=True, text=True, timeout=1800)
+ try:
+ synced = json.loads(out.stdout.strip().splitlines()[-1]).get("result")
+ except (ValueError, IndexError):
+ synced = {"raw": out.stdout[-500:]}
+ return {**info, "upgraded": True, "method": method, "sync": synced}
+ return {**info, "upgraded": False, "method": method, "sync": sync()}
+
+
+# ── uninstall ──
+
+_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 += [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:
+ 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)
+ for d in (root / "tools", root):
+ try:
+ d.rmdir()
+ except OSError:
+ 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}
+
+
+# ── configure ──
+
+CONFIG_KEYS = {"groq-key": "groq_api_key", "openai-key": "openai_api_key", "proxy": "proxy", "github-token": "github_token"}
+
+
+def configure(key: str, value: str) -> dict:
+ from agent_reach.config import Config
+
+ if key not in CONFIG_KEYS:
+ raise ReachError(BAD_INPUT, f"unknown key: {key}; valid: {', '.join(CONFIG_KEYS)}")
+ if not value:
+ raise ReachError(BAD_INPUT, "empty value")
+ Config().set(CONFIG_KEYS[key], value)
+ return {"key": key, "saved": True}
diff --git a/agent_reach/runtime/run.py b/agent_reach/runtime/run.py
index 91e5457f..9a9b7a49 100644
--- a/agent_reach/runtime/run.py
+++ b/agent_reach/runtime/run.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import os
-import shutil
import signal
import subprocess
import urllib.request
@@ -40,8 +39,10 @@ def run_cmd(
whatever project the agent happens to be in. On timeout the whole process
group is killed.
"""
+ from .tools import resolve
+
name = label or Path(argv[0]).name
- exe = shutil.which(argv[0])
+ exe = resolve(argv[0]) if not os.path.isabs(argv[0]) else (argv[0] if os.path.exists(argv[0]) else None)
if not exe:
raise ReachError(NEED_SETUP, f"{name} is not installed")
run_env = utf8_subprocess_env()
diff --git a/agent_reach/runtime/state.py b/agent_reach/runtime/state.py
new file mode 100644
index 00000000..72220a68
--- /dev/null
+++ b/agent_reach/runtime/state.py
@@ -0,0 +1,68 @@
+"""~/.agent-reach/state.json: which channels are added, which tools we installed, last checks.
+
+ {
+ "version": 1,
+ "channels": {"bilibili": {"added_at": "..."}},
+ "tools": {"bili-cli": {"spec": "...", "owner": "agent-reach" | "user", "scope": "private" | "global"}},
+ "checks": {"bilibili": {"at": "...", "actions": {"search": true}}}
+ }
+
+`owner` decides what uninstall may delete: only "agent-reach" entries.
+"""
+
+from __future__ import annotations
+
+import datetime as _dt
+import json
+from pathlib import Path
+
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ atomic_write_private_text,
+ home_dir,
+ make_private_dir,
+ read_small_text_no_follow,
+)
+
+STATE_VERSION = 1
+
+
+def root() -> Path:
+ return home_dir() / ".agent-reach"
+
+
+def state_path() -> Path:
+ return root() / "state.json"
+
+
+def exists() -> bool:
+ return state_path().is_file()
+
+
+def load() -> dict:
+ try:
+ text = read_small_text_no_follow(state_path(), max_bytes=1024 * 1024)
+ data = json.loads(text) if text else {}
+ except (OSError, ValueError, PrivatePathError):
+ data = {}
+ data.setdefault("version", STATE_VERSION)
+ for key in ("channels", "tools", "checks"):
+ data.setdefault(key, {})
+ return data
+
+
+def save(data: dict) -> None:
+ make_private_dir(root())
+ atomic_write_private_text(state_path(), json.dumps(data, indent=2, ensure_ascii=False))
+
+
+def now() -> str:
+ return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def age_seconds(iso: str) -> float:
+ try:
+ then = _dt.datetime.strptime(iso, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_dt.timezone.utc)
+ except (TypeError, ValueError):
+ return float("inf")
+ return (_dt.datetime.now(_dt.timezone.utc) - then).total_seconds()
diff --git a/agent_reach/runtime/tools.py b/agent_reach/runtime/tools.py
new file mode 100644
index 00000000..a021cac5
--- /dev/null
+++ b/agent_reach/runtime/tools.py
@@ -0,0 +1,186 @@
+"""Upstream tools Agent Reach installs, at pinned versions.
+
+Two kinds:
+- private: installed into ~/.agent-reach/tools/<name>/ (its own venv or npm
+ prefix). Never on the user's PATH; the user's own copy, if any, is untouched.
+- singleton: tools that can only exist once per machine (OpenCLI owns a fixed
+ daemon port and a Chrome extension). If the user already has one that is new
+ enough we use theirs; if it is too old we upgrade only with explicit consent;
+ if it is missing we install it globally and record it as ours.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional, Tuple
+
+from . import state
+from .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
+
+
+@dataclass(frozen=True)
+class Tool:
+ name: str
+ kind: str # "pip" | "npm"
+ spec: str # pinned install spec
+ commands: Tuple[str, ...] # executables it provides
+ singleton: bool = False
+ min_version: str = "" # singleton only: oldest user copy we accept
+
+
+TOOLS = {
+ t.name: t
+ for t in (
+ Tool("bili-cli", "pip", "bilibili-cli==0.6.2", ("bili",)),
+ Tool(
+ "boss-agent-cli", "pip",
+ "boss-agent-cli @ git+https://github.com/can4hou6joeng4/boss-agent-cli.git"
+ "@4c991b77086a203173bf08a4cb64a23af6514fe6",
+ ("boss",),
+ ),
+ Tool("mcporter", "npm", "[email protected]", ("mcporter",)),
+ Tool("opencli", "npm", "@jackwener/[email protected]", ("opencli",), singleton=True, min_version="1.8.6"),
+ )
+}
+
+#: Command name → tool, for resolving executables.
+_BY_COMMAND = {c: t for t in TOOLS.values() for c in t.commands}
+
+
+def tools_root() -> Path:
+ return state.root() / "tools"
+
+
+def tool_dir(name: str) -> Path:
+ return tools_root() / name
+
+
+def _private_bin(tool: Tool, command: str) -> Path:
+ base = tool_dir(tool.name)
+ if tool.kind == "pip":
+ sub = "Scripts" if os.name == "nt" else "bin"
+ return base / "venv" / sub / (command + (".exe" if os.name == "nt" else ""))
+ return base / "node_modules" / ".bin" / (command + (".cmd" if os.name == "nt" else ""))
+
+
+def resolve(command: str) -> Optional[str]:
+ """Absolute path for `command`: our private copy first, then the user's PATH."""
+ tool = _BY_COMMAND.get(command)
+ if tool and not tool.singleton:
+ private = _private_bin(tool, command)
+ if private.exists():
+ return str(private)
+ return shutil.which(command)
+
+
+def _version_tuple(text: str) -> tuple:
+ m = re.search(r"(\d+)\.(\d+)\.(\d+)", text or "")
+ return tuple(int(x) for x in m.groups()) if m else ()
+
+
+def installed_version(tool: Tool) -> Optional[str]:
+ exe = resolve(tool.commands[0])
+ if not exe:
+ return None
+ try:
+ out = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=20)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ m = re.search(r"\d+\.\d+\.\d+", out.stdout + out.stderr)
+ return m.group(0) if m else None
+
+
+def _run(argv, timeout: float = 600) -> None:
+ try:
+ proc = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
+ except FileNotFoundError:
+ raise ReachError(NEED_SETUP, f"{Path(argv[0]).name} is not installed") from None
+ except subprocess.TimeoutExpired:
+ raise ReachError(UPSTREAM_BROKEN, f"installing timed out: {' '.join(argv[:3])}") from None
+ if proc.returncode != 0:
+ last = next((ln for ln in reversed(proc.stderr.splitlines()) if ln.strip()), "")
+ raise ReachError(UPSTREAM_BROKEN, f"install failed: {last[:300]}")
+
+
+def _install(tool: Tool, *, global_: bool = False) -> None:
+ if tool.kind == "pip":
+ venv = tool_dir(tool.name) / "venv"
+ shutil.rmtree(venv, ignore_errors=True)
+ venv.parent.mkdir(parents=True, exist_ok=True)
+ _run([sys.executable, "-m", "venv", str(venv)])
+ py = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ _run([str(py), "-m", "pip", "install", "--quiet", "--disable-pip-version-check", tool.spec])
+ return
+ npm = shutil.which("npm")
+ if not npm:
+ raise ReachError(NEED_SETUP, "npm is not installed", hint="Ask the user to install Node.js (https://nodejs.org).")
+ if global_:
+ _run([npm, "install", "-g", tool.spec])
+ else:
+ prefix = tool_dir(tool.name)
+ prefix.mkdir(parents=True, exist_ok=True)
+ _run([npm, "install", "--prefix", str(prefix), "--no-fund", "--no-audit", tool.spec])
+
+
+def ensure(name: str, *, allow_upgrade: bool = False) -> dict:
+ """Make sure the tool is installed at an acceptable version; record it in state."""
+ tool = TOOLS[name]
+ data = state.load()
+ entry = data["tools"].get(name)
+
+ if tool.singleton:
+ current = installed_version(tool)
+ if current is None:
+ _install(tool, global_=True)
+ entry = {"spec": tool.spec, "owner": "agent-reach", "scope": "global"}
+ elif _version_tuple(current) < _version_tuple(tool.min_version):
+ if not allow_upgrade:
+ raise ReachError(
+ NEED_SETUP,
+ f"{name} {current} is older than the required {tool.min_version}",
+ hint=f"Ask the user whether to upgrade their {name}; if yes, rerun with --allow-upgrade.",
+ )
+ _install(tool, global_=True)
+ entry = {"spec": tool.spec, "owner": (entry or {}).get("owner", "user"), "scope": "global"}
+ elif entry is None:
+ entry = {"spec": f"user:{current}", "owner": "user", "scope": "global"}
+ elif not entry or entry.get("spec") != tool.spec or not _private_bin(tool, tool.commands[0]).exists():
+ _install(tool)
+ entry = {"spec": tool.spec, "owner": "agent-reach", "scope": "private"}
+
+ data["tools"][name] = entry
+ state.save(data)
+ return {"tool": name, **entry}
+
+
+def remove_private(name: str) -> bool:
+ """Delete a private install. Singletons are never removed here."""
+ tool = TOOLS[name]
+ if tool.singleton:
+ return False
+ data = state.load()
+ removed = data["tools"].pop(name, None) is not None
+ if tool_dir(name).exists():
+ shutil.rmtree(tool_dir(name))
+ removed = True
+ state.save(data)
+ return removed
+
+
+def uninstall_global_owned(dry_run: bool) -> list:
+ """Global singletons we installed (owner agent-reach); uninstall them."""
+ out = []
+ for name, entry in state.load()["tools"].items():
+ tool = TOOLS.get(name)
+ if tool and tool.singleton and entry.get("owner") == "agent-reach" and entry.get("scope") == "global":
+ out.append(f"npm -g {tool.spec.rsplit('@', 1)[0]}")
+ if not dry_run and shutil.which("npm"):
+ subprocess.run([shutil.which("npm"), "uninstall", "-g", tool.spec.rsplit("@", 1)[0]],
+ capture_output=True, timeout=300)
+ return out
diff --git a/agent_reach/skill/SKILL.md b/agent_reach/skill/SKILL.md
index 462f4c28..823e9b8f 100644
--- a/agent_reach/skill/SKILL.md
+++ b/agent_reach/skill/SKILL.md
@@ -1,165 +1,54 @@
---
name: agent-reach
description: >
- MUST USE when user wants to 调研/research/搜索/search/查/找/look up anything
- on the internet — e.g. 全网调研 X / 帮我调研一下 X / 查一下 X / 搜搜 X /
- 看看大家怎么评价 X / X 上有什么讨论 / research this topic。
-
- Also MUST USE when user mentions any platform or shares any URL/链接:
- 小红书/xiaohongshu/xhs, Twitter/推特/X, B站/bilibili, Reddit, Facebook,
- Instagram, V2EX, LinkedIn/领英/Boss直聘/招聘/求职/jobs, YouTube, GitHub code search, 小宇宙播客,
- 雪球/股票行情, RSS feeds, or any web URL.
-
- 16 platforms, multi-backend routing (OpenCLI / per-platform CLIs / APIs).
- Zero config for 6 channels. Run `agent-reach doctor --json` to see which
- backend serves each platform right now.
-
- NOT for: 写报告/数据分析/翻译等内容加工(本 skill 只负责从互联网获取内容);
- 发帖/评论/点赞等写操作;已有专门 skill 的平台(先用专门 skill)。
-
- 【路由方式】SKILL.md 包含路由表和常用命令,复杂场景需按需阅读对应分类的 references/*.md。
- 分类:search / social (小红书/推特/B站/V2EX/Reddit/Facebook/Instagram) / career(LinkedIn/Boss直聘) / dev(github) / web(网页/文章/RSS) / video(YouTube/B站/播客) / finance(雪球/股票)。
+ Use when the user wants content from platforms your own tools can't reach:
+ 小红书/xiaohongshu, B站/bilibili, Twitter/X, Reddit, Facebook, Instagram,
+ YouTube (subtitles, transcripts), 小宇宙播客, V2EX, 雪球/股票行情, GitHub, LinkedIn/Boss直聘 jobs,
+ or when your built-in web search / fetch is missing or fails.
+ Read-only: never post, comment, like, or log in on the user's behalf.
metadata:
homepage: https://github.com/Panniantong/Agent-Reach
+ version: "{{VERSION}}"
---
-# Agent Reach — 互联网能力路由器
-
-16 平台、多后端。**本 skill 存在时必须用它访问这些平台,不要自己发明方案。**
-
-## 常驻规则(全程适用)
-
-1. **动手前先体检**:多后端/登录态平台(小红书/Reddit/B站/Twitter/Facebook/Instagram/Boss直聘)先跑
- `agent-reach doctor --json`。`active_backend` 有值时按它选命令组;`active_backend: null`
- 表示 Doctor 为避免触发浏览器 Cookie 读取或远端写入而没有做实时验证,不代表后端不存在。
- Doctor 结果是「某一时刻的快照」,通道/登录态可能已变化;执行只读命令前若怀疑失效,
- 按对应 reference 的「体检与恢复」runbook 重新确认(如 career.md 的 Boss直聘 CDP 排查)。
-2. **声明你在用什么**:开始干活前说一句「使用 agent-reach 的 X 平台 / Y 后端」。
-3. **失败按 references 里的重试链处理**,不要瞎猜命令。
-4. **全网调研类任务**:组合多平台(Exa 搜索 + Twitter/Reddit 看讨论 + 小红书/B站看中文场景),并行收集再汇总。
-5. **替用户盯版本**:完成一次较大的调研/多平台任务后,顺手跑
- `agent-reach check-update`(很快,一个 API 调用)。有新版就在收尾汇报里附一句:
- 「Agent Reach 有新版 vX.Y.Z,复制这句话给我即可更新:帮我更新 Agent Reach:
- https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/update.md」。
- 不要中断当前任务去更新,也不要重复提醒同一个版本。
-
-## 路由表
-
-| 用户意图 | 分类 | 详细文档 |
-|---------|------|---------|
-| 网页搜索/代码搜索 | search | [references/search.md](references/search.md) |
-| 小红书/推特/B站/V2EX/Reddit/Facebook/Instagram | social | [references/social.md](references/social.md) |
-| 招聘/职位/LinkedIn/Boss直聘 | career | [references/career.md](references/career.md) |
-| GitHub/代码 | dev | [references/dev.md](references/dev.md) |
-| 网页/文章/RSS | web | [references/web.md](references/web.md) |
-| YouTube/B站/播客字幕 | video | [references/video.md](references/video.md) |
-| 雪球/股票行情 | finance | [references/finance.md](references/finance.md) |
-
-## 零配置快速命令
-
-```bash
-# Exa 网页搜索
-mcporter call exa.web_search_exa query="query" numResults=5
-
-# 通用网页阅读
-curl -s "https://r.jina.ai/URL"
-
-# GitHub 搜索
-gh search repos "query" --sort stars --limit 10
-
-# YouTube 字幕(注意:B站不要用 yt-dlp,失败重试链见 video.md)
-yt-dlp --write-sub --write-auto-sub --skip-download -o "/tmp/%(id)s" "URL"
+# Agent Reach
-# V2EX 热门
-curl -s "https://www.v2ex.com/api/topics/hot.json" -H "User-Agent: agent-reach/1.0"
-
-# B站搜索(bili-cli,无需登录)
-bili search "query" --type video -n 5
-```
-
-## 需登录态的平台(按 doctor 的 active_backend 选命令)
-
-Twitter 注意:`agent-reach configure twitter-cookies` 保存的 Cookie 只供
-`doctor` 检查配置是否齐全;`doctor` 不执行 `twitter status`,也不会设置当前
-Shell。直接运行 `twitter` 前,必须在子进程环境中显式提供
-`TWITTER_AUTH_TOKEN` 和 `TWITTER_CT0`,不得在日志或命令回显中暴露值。
-
-小红书注意:Agent Reach 不替用户登录,也不读取浏览器 Cookie。OpenCLI 只用
-用户已有且明确控制的 Chrome 会话;没有现成会话时不要自动登录,改用
-Cookie-Editor 手工导出后配置 xiaohongshu-mcp / 存量工具。
-
-Boss直聘配置触发:当用户说“帮我配 Boss直聘”时,先读取 `references/career.md`
-的 Boss 章节,然后在获得安装授权后运行
-`agent-reach install --env=local --system --channels=boss`。Agent 负责按系统启动
-只绑定 `127.0.0.1:9222` 的专用 Chrome;**拉起后第一步是暂停并让用户肉眼确认**
-窗口内是已登录状态(右上角有头像),未登录则让用户登录/扫码,用户确认后再运行
-`boss --cdp-url http://localhost:9222 login --cdp` 和 `agent-reach doctor` 验收。
-不要让用户自己研究端口参数。
-专用 Chrome profile 必须长期复用,不要每次创建,也不要默认改用日常主 Chrome。
-
-判断 CDP 浏览器登录态**不要信 `boss status`**(它只校验本地 session.enc,与
-浏览器登录态互不代表),以 `agent-reach doctor` 的浏览器 cookie 探测(wt2)
-为准,并配合用户肉眼确认。绝不用当前页 URL 判断登录态:
-`security-check` / `zhipin-security` / `_security_check` 安全校验页是 Boss 反爬挑战,
-与登录无关——已登录也会出现(带 CDP 调试端口的 Chrome 几乎必现)。看到它不要
-当成“未登录”,先跑 `agent-reach doctor` 看浏览器 cookie,再决定是否需要用户登录。
-搜索报 `AUTH_EXPIRED` 即浏览器未登录的 ground truth:直接走登录流程 + `login --cdp`,
-不要往安全校验方向解释。
-
-执行搜索时必须使用
-`boss --browser-source existing-browser --cdp-url http://localhost:9222 search ...`;
-遇到 `ENVIRONMENT_RISK` 立即停止,不刷新、不重新登录、不自动重试。
-
-```bash
-# Twitter 搜索(twitter-cli 首选;失败重试链见 social.md)
-twitter search "query" -n 10
-
-# Reddit(无零配置路径:OpenCLI 或 rdt-cli,必须登录态)
-opencli reddit search "query" -f yaml # 桌面
-rdt search "query" --limit 10 # 存量/服务器
-
-# 小红书(桌面首选 OpenCLI)
-opencli xiaohongshu search "query" -f yaml
-
-# Facebook / Instagram(桌面 OpenCLI,复用浏览器登录态)
-opencli facebook search "query" -f yaml
-opencli facebook groups -f yaml
-opencli instagram search "query" -f yaml # 搜用户
-opencli instagram user USERNAME -f yaml # 读指定用户最近帖子
-```
+一个命令接所有平台:`agent-reach`。只读,输出永远是一段 JSON。
-## 环境检查
+## 怎么用
```bash
-# 检查可用 channel 与每个平台当前激活的后端
-agent-reach doctor --json
+agent-reach channels # 每个渠道有哪些动作、要什么参数(不确定就先跑这个)
+agent-reach <渠道> <动作> [参数] # 例:agent-reach xiaohongshu search "咖啡" --limit 5
+agent-reach read <链接> # 给链接,自动认出渠道
```
-## OpenCLI 适配器发现
+结果:
-路由表没有覆盖用户需要的平台或命令时,先用 `opencli list` 查已有适配器,再用
-`opencli <平台> --help` 查看公开命令。发现适配器只证明命令存在,不证明登录态或
-目标内容可用;仅在用户任务明确需要该平台时执行只读命令,并以实际非空内容验收。
+- `ok: true` → 内容在 `items` 里,每条有 `title / url / author / published_at / text`,原始数据在 `raw`。
+- `ok: false` → 看 `error.code`,按 `error.hint` 做:
-## 工作区规则
+| error.code | 怎么办 |
+|---|---|
+| `NEED_SETUP` | 告诉用户 hint 里的命令(常见:`agent-reach add <渠道>`) |
+| `NEED_LOGIN` | 让用户自己登录(`agent-reach login <渠道>`),**绝不替用户登录、不读用户浏览器的 Cookie** |
+| `UPSTREAM_BROKEN` | 这个渠道暂时不可用,告诉用户,不要反复重试 |
+| `TIMEOUT` / `RATE_LIMITED` | 稍后再试 |
+| `NOT_FOUND` / `BAD_INPUT` | 检查链接或参数,必要时跑 `agent-reach channels` |
-**不要在 agent workspace 创建文件。** 使用 `/tmp/` 存放临时输出,`~/.agent-reach/` 存放持久数据。
+## 规则
-## 详细文档
+1. 你自己有能用的网页搜索 / 读网页工具就先用自己的;`web` 渠道只当保底。
+2. 开始前说一句"用 agent-reach 的 X 渠道"。
+3. 多平台调研时并行调几个渠道再汇总。
+4. 只做读取。发帖、评论、点赞一律不做。
-根据用户需求,阅读对应的详细文档:
+## 渠道
-- [搜索工具](references/search.md) — Exa AI 搜索
-- [社交媒体](references/social.md) — 小红书, Twitter, B站, V2EX, Reddit, Facebook, Instagram(多后端/登录态命令组)
-- [职场招聘](references/career.md) — LinkedIn, Boss直聘
-- [开发工具](references/dev.md) — GitHub CLI
-- [网页阅读](references/web.md) — Jina Reader, RSS
-- [视频播客](references/video.md) — YouTube, B站, 小宇宙
-- [金融行情](references/finance.md) — 雪球股票行情、搜索、热门内容
+{{CHANNEL_TABLE}}
-## 配置渠道
+`default` 装好就能用;其余要用户先 `agent-reach add <渠道>`。
-如果某个 channel 需要配置,获取安装指南:
-https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/install.md
+## 给用户的管理命令
-用户只需提供 cookies,其他配置由 agent 完成。
+`agent-reach setup`(首次)· `add` / `remove <渠道>` · `login` / `logout <渠道>` · `doctor` · `update` · `uninstall`
diff --git a/agent_reach/skill/SKILL_en.md b/agent_reach/skill/SKILL_en.md
index 4d7466d9..64b387c7 100644
--- a/agent_reach/skill/SKILL_en.md
+++ b/agent_reach/skill/SKILL_en.md
@@ -1,174 +1,55 @@
---
name: agent-reach
description: >
- MUST USE when user wants to research/search/look up/find anything on the
- internet — e.g. "research this topic", "do a deep dive on X", "search the
- web for X", "see what people say about X", "look this up".
-
- Also MUST USE when user mentions any platform or shares any URL/link:
- Twitter/X, Reddit, Facebook, Instagram, YouTube, GitHub, Bilibili, XiaoHongShu,
- Xiaoyuzhou Podcast, LinkedIn/Boss直聘/jobs/recruiting, V2EX, Xueqiu (stocks), RSS.
-
- 16 platforms, multi-backend routing (OpenCLI / per-platform CLIs / APIs).
- Zero config for 6 channels. Run `agent-reach doctor --json` to see which
- backend serves each platform right now.
-
- NOT for: writing reports/analysis/translation (this skill only FETCHES
- internet content); posting/commenting/liking (write operations); platforms
- that already have a dedicated skill installed (prefer that skill).
+ Use when the user wants content from platforms your own tools can't reach:
+ Xiaohongshu, Bilibili, Twitter/X, Reddit, Facebook, Instagram, YouTube
+ (subtitles, transcripts), Xiaoyuzhou podcasts, V2EX, Xueqiu stock quotes,
+ GitHub, LinkedIn / Boss Zhipin jobs, or when your built-in web search / fetch
+ is missing or fails. Read-only: never post, comment, like, or log in on the
+ user's behalf.
metadata:
homepage: https://github.com/Panniantong/Agent-Reach
+ version: "{{VERSION}}"
---
-# Agent Reach — internet capability router
-
-16 platforms, multiple backends each. **When this skill exists, use it for
-these platforms — do not invent your own approach.**
-
-## Standing rules (apply for the whole session)
-
-1. **Health-check before acting**: for multi-backend/login-backed platforms (XiaoHongShu /
- Reddit / Bilibili / Twitter / Facebook / Instagram), run `agent-reach doctor --json` first.
- Use a populated `active_backend`; `active_backend: null` means Doctor deliberately skipped a
- live probe to avoid browser-cookie reads or remote writes, not that no backend exists. Only when
- the user's task requires that platform, run the reference's read-only command to verify it.
-2. **Announce what you use**: say "using agent-reach, platform X via backend Y"
- before starting.
-3. **On failure, follow the retry chains in references/** — never guess
- commands.
-4. **For broad research tasks**: combine platforms (Exa for web search +
- Twitter/Reddit for discussions + XiaoHongShu/Bilibili for Chinese
- perspectives), collect in parallel, then synthesize.
-5. **Watch versions for the user**: after finishing a substantial
- multi-platform task, run `agent-reach check-update` (fast, one API call).
- If a new version exists, append one line to your wrap-up: "Agent Reach
- vX.Y.Z is available — paste this to me to update: 帮我更新 Agent Reach:
- https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/update.md".
- Never interrupt the current task to update; never nag about the same version twice.
-
-## Routing table
+# Agent Reach
-| User intent | Category | Details |
-|---------|------|---------|
-| Web / code search | search | [references/search.md](references/search.md) |
-| XiaoHongShu / Twitter / Bilibili / V2EX / Reddit / Facebook / Instagram | social | [references/social.md](references/social.md) |
-| Jobs / LinkedIn | career | [references/career.md](references/career.md) |
-| GitHub / code | dev | [references/dev.md](references/dev.md) |
-| Web pages / articles / RSS | web | [references/web.md](references/web.md) |
-| YouTube / Bilibili / podcast transcripts | video | [references/video.md](references/video.md) |
-| Xueqiu / stock quotes | finance | [references/finance.md](references/finance.md) |
+One command for every platform: `agent-reach`. Read-only; output is always one JSON object.
-## Zero-config quick commands
+## Usage
```bash
-# Exa web search
-mcporter call exa.web_search_exa query="query" numResults=5
-
-# Read any web page
-curl -s "https://r.jina.ai/URL"
-
-# GitHub search
-gh search repos "query" --sort stars --limit 10
-
-# YouTube subtitles (never use yt-dlp for Bilibili; retry chain in video.md)
-yt-dlp --write-sub --write-auto-sub --skip-download -o "/tmp/%(id)s" "URL"
-
-# V2EX hot topics
-curl -s "https://www.v2ex.com/api/topics/hot.json" -H "User-Agent: agent-reach/1.0"
-
-# Bilibili search (bili-cli, no login needed)
-bili search "query" --type video -n 5
+agent-reach channels # actions and params per channel (run this when unsure)
+agent-reach <channel> <action> [args] # e.g. agent-reach reddit search "rust async" --limit 5
+agent-reach read <url> # picks the channel from the URL
```
-## Login-backed platforms (pick by doctor's active_backend)
-
-Twitter boundary: cookies saved by `agent-reach configure twitter-cookies`
-are used only by `doctor` to check whether explicit credentials are present.
-`doctor` does not run `twitter status` or configure the current shell. Before
-calling `twitter` directly, explicitly provide `TWITTER_AUTH_TOKEN` and
-`TWITTER_CT0` in the child-process environment without logging their values.
-
-XiaoHongShu boundary: Agent Reach must not log the user in or read browser
-cookies. OpenCLI may use only an existing Chrome session explicitly controlled
-by the user. If none exists, do not automate login; use a manual Cookie-Editor
-export with xiaohongshu-mcp or a legacy tool instead.
-
-```bash
-# Twitter search (twitter-cli preferred; retry chain in social.md)
-twitter search "query" -n 10
-
-# Reddit (NO zero-config path — OpenCLI or rdt-cli, login required)
-opencli reddit search "query" -f yaml # desktop
-rdt search "query" --limit 10 # legacy/server
-
-# XiaoHongShu (desktop prefers OpenCLI)
-opencli xiaohongshu search "query" -f yaml
-
-# Facebook / Instagram (desktop OpenCLI, browser session)
-opencli facebook search "query" -f yaml
-opencli facebook groups -f yaml
-opencli instagram search "query" -f yaml # user search
-opencli instagram user USERNAME -f yaml # recent posts from one user
-```
-
-## Environment check
-
-```bash
-# Channel availability + which backend serves each platform
-agent-reach doctor --json
-```
-
-When the user asks “help me configure Boss Zhipin” / “帮我配 Boss直聘”, read the
-Boss section in `references/career.md`. After explicit install approval, run
-`agent-reach install --env=local --system --channels=boss`, launch the dedicated
-loopback-only Chrome profile for their OS, then **pause and have the user visually
-confirm** the window is logged in (avatar in the top-right); if not, have them log
-in manually. Then verify with `boss --cdp-url http://localhost:9222 login --cdp`
-and `agent-reach doctor`. Do not make the user assemble CDP flags.
-Keep reusing the dedicated Chrome profile; do not recreate it for every run or
-switch to the user's daily profile by default. Search with
-`boss --browser-source existing-browser --cdp-url http://localhost:9222 search ...`.
-On `ENVIRONMENT_RISK`, stop without refreshing, relogging, or retrying.
-
-**Do not trust `boss status` for CDP browser login state** — it only validates the
-local `~/.boss-agent/auth/session.enc` store, which does not represent the
-dedicated Chrome profile's cookies that `existing-browser` searches actually use. Use
-the browser `wt2` cookie probe in `agent-reach doctor` plus the user's visual
-confirmation. Never judge login state from the page URL: `security-check` /
-`zhipin-security` / `_security_check` pages are anti-bot challenges that appear
-even when logged in. `AUTH_EXPIRED` from a search is the ground truth for a
-logged-out browser — go straight to the login flow + `login --cdp` instead of
-interpreting it as a security check.
-
-## Discovering OpenCLI adapters
+Results:
-When the routing table lacks a needed platform or command, run `opencli list`,
-then inspect `opencli <platform> --help`. Discovery proves only that an adapter
-exists, not that authentication or target content works. Run read-only commands
-only when the user's task requires that platform, and require non-empty content.
+- `ok: true` → content in `items`; each has `title / url / author / published_at / text`, upstream data in `raw`.
+- `ok: false` → branch on `error.code` and follow `error.hint`:
-## Workspace rules
+| error.code | What to do |
+|---|---|
+| `NEED_SETUP` | Tell the user the command in the hint (usually `agent-reach add <channel>`) |
+| `NEED_LOGIN` | The user logs in themselves (`agent-reach login <channel>`). **Never log in for them or read their browser cookies** |
+| `UPSTREAM_BROKEN` | Channel is down right now; tell the user, don't retry in a loop |
+| `TIMEOUT` / `RATE_LIMITED` | Retry later |
+| `NOT_FOUND` / `BAD_INPUT` | Check the link or args; run `agent-reach channels` if needed |
-**Never create files in the agent workspace.** Use `/tmp/` for temporary
-output and `~/.agent-reach/` for persistent data.
+## Rules
-## Detailed references
+1. If your own web search / fetch works, use it first; the `web` channel is a fallback.
+2. Say "using agent-reach channel X" before you start.
+3. For multi-platform research, call several channels in parallel, then summarize.
+4. Read only. Never post, comment, or like.
-Read the matching file when you need specifics (commands above cover the
-common cases; references hold per-backend command groups, caveats, retry
-chains — note: reference docs are written in Chinese, commands are universal):
+## Channels
-- [Search](references/search.md) — Exa AI search
-- [Social](references/social.md) — XiaoHongShu, Twitter, Bilibili, V2EX, Reddit, Facebook, Instagram (multi-backend/login-backed groups)
-- [Career](references/career.md) — LinkedIn
-- [Dev](references/dev.md) — GitHub CLI
-- [Web](references/web.md) — Jina Reader, RSS
-- [Video](references/video.md) — YouTube, Bilibili, Xiaoyuzhou
-- [Finance](references/finance.md) — Xueqiu quotes, search and market content
+{{CHANNEL_TABLE}}
-## Configure a channel
+`default` channels work right away; others need `agent-reach add <channel>` first.
-If a channel needs setup, fetch the install guide:
-https://raw.githubusercontent.com/Panniantong/agent-reach/main/docs/install.md
+## Management commands (for the user)
-The user only provides cookies / one extension click; the agent does the rest.
+`agent-reach setup` (first run) · `add` / `remove <channel>` · `login` / `logout <channel>` · `doctor` · `update` · `uninstall`
diff --git a/agent_reach/transcribe.py b/agent_reach/transcribe.py
index e7a0c6c4..34e9fa19 100644
--- a/agent_reach/transcribe.py
+++ b/agent_reach/transcribe.py
@@ -250,11 +250,12 @@ def _assert_safe_public_url(url: str) -> None:
def download_audio(url: str, out_dir: Path) -> Path:
"""Download audio with yt-dlp into out_dir; return the resulting file path."""
_assert_safe_public_url(url)
- _require("yt-dlp")
+ import sys
+
template = out_dir / "source.%(ext)s"
_run(
[
- "yt-dlp",
+ sys.executable, "-m", "yt_dlp",
"-x",
"--audio-format",
"m4a",
diff --git a/tests/test_manage.py b/tests/test_manage.py
new file mode 100644
index 00000000..339ddf20
--- /dev/null
+++ b/tests/test_manage.py
@@ -0,0 +1,260 @@
+# -*- coding: utf-8 -*-
+"""Management commands: private installs, add/remove, doctor, watch, uninstall, update, skill."""
+
+import json
+
+import pytest
+
+from agent_reach.channels.base import Action, Channel, Param
+from agent_reach.runtime import browser, manage, state, tools
+from agent_reach.runtime.result import ReachError
+from agent_reach.utils.paths import home_dir
+
+
+class _Base(Channel):
+ description = "x"
+ passes = True
+
+ def can_handle(self, url):
+ return False
+
+ def _go(self, **kw):
+ if not type(self).passes:
+ raise ReachError("UPSTREAM_BROKEN", "down")
+ return [{"title": "ok"}]
+
+
+def _actions():
+ return (Action("search", "s", (Param("query", "q"),), (("b", "_go"),), live_test={"query": "x"}),)
+
+
+class Web(_Base):
+ name, level, actions = "web", "default", _actions()
+
+
+class Bili(_Base):
+ name, level, actions, tools = "bili", "optional", _actions(), ("bili-cli",)
+
+
+class Bili2(_Base):
+ name, level, actions, tools = "bili2", "optional", _actions(), ("bili-cli",)
+
+
+class Needy(_Base):
+ name, level, actions, prereqs = "needy", "optional", _actions(), ("x",)
+
+
+def env(monkeypatch):
+ chans = [Web(), Bili(), Bili2(), Needy()]
+ monkeypatch.setattr(manage, "_channels", lambda: chans)
+ monkeypatch.setitem(manage.PREREQS, "x", {"check": lambda: False, "hint": "install x"})
+ installs = []
+
+ def fake_install(tool, *, global_=False):
+ installs.append((tool.name, global_))
+ if not global_:
+ b = tools._private_bin(tool, tool.commands[0])
+ b.parent.mkdir(parents=True, exist_ok=True)
+ b.write_text("")
+
+ monkeypatch.setattr(tools, "_install", fake_install)
+ monkeypatch.setattr(browser, "is_running", lambda: False)
+ return {"chans": chans, "installs": installs}
+
+
+# ── private installs ──
+
+
+def test_private_copy_wins_over_path(env, monkeypatch):
+ monkeypatch.setattr(tools.shutil, "which", lambda c: "/usr/bin/" + c)
+ assert tools.resolve("bili") == "/usr/bin/bili"
+ tools.ensure("bili-cli")
+ assert tools.resolve("bili") == str(tools._private_bin(tools.TOOLS["bili-cli"], "bili"))
+
+
+def test_private_install_is_recorded_as_ours_and_not_repeated(env):
+ assert tools.ensure("bili-cli")["owner"] == "agent-reach"
+ tools.ensure("bili-cli")
+ assert env["installs"] == [("bili-cli", False)]
+
+
+ "user_version, allow, expect_install, expect_owner",
+ [("1.9.0", False, False, "user"), ("1.8.0", True, True, "user"), (None, False, True, "agent-reach")],
+)
+def test_singleton_reuses_user_copy_and_upgrades_only_with_consent(
+ env, monkeypatch, user_version, allow, expect_install, expect_owner
+):
+ monkeypatch.setattr(tools, "installed_version", lambda t: user_version)
+ entry = tools.ensure("opencli", allow_upgrade=allow)
+ assert entry["owner"] == expect_owner and entry["scope"] == "global"
+ assert (env["installs"] == [("opencli", True)]) is expect_install
+
+
+def test_singleton_too_old_without_consent_changes_nothing(env, monkeypatch):
+ monkeypatch.setattr(tools, "installed_version", lambda t: "1.0.0")
+ with pytest.raises(ReachError) as info:
+ tools.ensure("opencli")
+ assert info.value.code == "NEED_SETUP" and "--allow-upgrade" in info.value.hint
+ assert env["installs"] == []
+
+
+# ── add / remove ──
+
+
+def test_add_with_missing_prerequisite_installs_nothing(env):
+ with pytest.raises(ReachError) as info:
+ manage.add("needy")
+ assert info.value.code == "NEED_SETUP" and "install x" in info.value.hint
+ assert "needy" not in state.load()["channels"]
+
+
+def test_remove_keeps_tool_still_used_by_another_channel(env):
+ manage.add("bili")
+ manage.add("bili2")
+ assert manage.remove("bili")["removed_tools"] == []
+ assert tools.resolve("bili") is not None
+ assert manage.remove("bili2")["removed_tools"] == ["bili-cli"]
+ assert not tools.tool_dir("bili-cli").exists()
+
+
+def test_default_channels_cannot_be_removed(env):
+ with pytest.raises(ReachError):
+ manage.remove("web")
+
+
+# ── doctor / watch ──
+
+
+def _status(name):
+ return next(c for c in manage.doctor()["channels"] if c["channel"] == name)["status"]
+
+
+def test_doctor_states(env):
+ assert _status("bili") == "not_added"
+ manage.add("bili")
+ assert _status("bili") == "unverified"
+ manage.run_checks(["bili"])
+ assert _status("bili") == "ready"
+ Bili.passes = False
+ try:
+ manage.run_checks(["bili"])
+ assert _status("bili") == "broken"
+ finally:
+ Bili.passes = True
+ data = state.load()
+ data["checks"]["bili"]["at"] = "2000-01-01T00:00:00Z"
+ state.save(data)
+ assert _status("bili") == "unverified"
+
+
+def test_doctor_reports_missing_tool_as_needs_setup(env, monkeypatch):
+ monkeypatch.setattr(tools.shutil, "which", lambda c: None)
+ manage.add("bili")
+ tools.remove_private("bili-cli")
+ 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})
+ manage.add("bili")
+ assert manage.watch()["all_good"] is True
+ 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"
+ finally:
+ Bili.passes = True
+
+
+# ── uninstall ──
+
+
+def test_uninstall_removes_only_what_we_own(env):
+ manage.add("bili")
+ root = state.root()
+ (root / "config.yaml").write_text("x: 1")
+ (root / "my-notes").mkdir()
+ (root / "tools" / "someone-elses-tool").mkdir(parents=True)
+ 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"]
+ 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()
+
+
+# ── update ──
+
+
[email protected]("latest, available", [("v2.0.1", True), ("v2.0.0", False), ("v1.9.9", False)])
+def test_update_check_compares_versions(monkeypatch, latest, available):
+ class Resp:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def read(self):
+ return json.dumps({"tag_name": latest}).encode()
+
+ monkeypatch.setattr(manage, "__version__", "2.0.0")
+ monkeypatch.setattr(manage.urllib.request, "urlopen", lambda *a, **k: Resp())
+ 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")
+
+
+# ── skill ──
+
+
+def test_skill_lists_every_channel_and_has_no_placeholders(env):
+ for lang in ("zh", "en"):
+ text = manage.render_skill(lang)
+ assert "{{" not in text
+ for ch in env["chans"]:
+ 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()
+
+
+# ── configure ──
+
+
+def test_configure_saves_known_keys_only(env):
+ from agent_reach.config import Config
+
+ manage.configure("groq-key", "gsk_test")
+ assert Config(read_only=True).get("groq_api_key") == "gsk_test"
+ with pytest.raises(ReachError):
+ manage.configure("twitter-cookies", "x")
+
+
+def test_doctor_separates_needs_login_from_broken(env, monkeypatch):
+ def need_login(self, **kw):
+ raise ReachError("NEED_LOGIN", "log in")
+
+ monkeypatch.setattr(Bili, "_go", need_login)
+ manage.add("bili")
+ manage.run_checks(["bili"])
+ assert _status("bili") == "needs_login"
diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.py
index f1e518a6..5ca2c298 100644
--- a/tests/test_unified_entry.py
+++ b/tests/test_unified_entry.py
@@ -184,9 +184,9 @@ def test_read_routes_by_url(capsys, fake_cli):
def test_handles_only_claims_unified_commands(fake_cli):
assert unified.handles(["fake", "search"])
assert unified.handles(["channels"])
- assert not unified.handles(["doctor"])
+ assert unified.handles(["doctor"])
+ assert unified.handles([])
assert not unified.handles(["check-update"])
- assert not unified.handles([])
def test_channels_lists_usage_for_agents(capsys, fake_cli):