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: keep tool login state under ~/.agent-reach/sessions

Pnant2719e7832a4a
diff --git a/agent_reach/channels/base.py b/agent_reach/channels/base.py
index 21399812..504946ba 100644
--- a/agent_reach/channels/base.py
+++ b/agent_reach/channels/base.py
@@ -71,6 +71,13 @@ class Channel(ABC):
level: str = ""
#: Unified actions this channel exposes.
actions: Tuple[Action, ...] = ()
+ #: Tool whose login lives in ~/.agent-reach/sessions/<session>/ ("" = none).
+ session: str = ""
+ #: Interactive command the user runs to log in (run with HOME = session dir).
+ login_argv: Tuple[str, ...] = ()
+ #: Directories under the real home where the tool used to keep its login,
+ #: copied into the session only when the user asks (`login --import-existing`).
+ legacy_state: Tuple[str, ...] = ()
#: 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 5b0cab0f..b7c5d81e 100644
--- a/agent_reach/channels/bilibili.py
+++ b/agent_reach/channels/bilibili.py
@@ -10,7 +10,6 @@ YouTube backend; it just no longer serves bilibili.
"""
import json
-import os
import re
import urllib.request
@@ -25,6 +24,7 @@ from agent_reach.runtime.result import (
unix_to_iso,
)
from agent_reach.runtime.run import CommandFailed, http_request, run_cmd
+from agent_reach.runtime.sessions import session_env, sessions_root
from .base import Action, Channel, Param
@@ -54,7 +54,7 @@ def _bvid(target: str, timeout: float) -> str:
def _bili_json(args: list, timeout: float) -> dict:
"""Run bili-cli with --json; map its error envelope to unified codes."""
try:
- out = run_cmd(["bili", *args, "--json"], timeout=timeout)
+ out = run_cmd(["bili", *args, "--json"], timeout=timeout, env=session_env("bili-cli"))
except CommandFailed as exc:
out = exc.stdout
if "{" not in out:
@@ -137,6 +137,9 @@ class BilibiliChannel(Channel):
tier = 1
level = "optional"
+ session = "bili-cli"
+ login_argv = ("bili", "login")
+ legacy_state = (".bilibili-cli",)
actions = (
Action(
"search",
@@ -276,7 +279,7 @@ class BilibiliChannel(Channel):
data = _bili_json(["video", _bvid(target, timeout), "--subtitle"], timeout)
sub = data.get("subtitle") or {}
if not sub.get("available"):
- if not os.path.exists(os.path.expanduser("~/.bilibili-cli/credential.json")):
+ if not (sessions_root() / "bili-cli" / ".bilibili-cli" / "credential.json").exists():
raise ReachError(NEED_LOGIN, "Bilibili is not logged in", hint=_BILI_LOGIN_HINT)
raise ReachError(NOT_FOUND, "this video has no subtitles")
text = sub.get("text") or "\n".join(i.get("content", "") for i in sub.get("items") or [])
diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.py
index cf54eefb..499e65f3 100644
--- a/agent_reach/channels/boss.py
+++ b/agent_reach/channels/boss.py
@@ -43,6 +43,7 @@ from agent_reach.runtime.result import (
make_item,
)
from agent_reach.runtime.run import CommandFailed, run_cmd
+from agent_reach.runtime.sessions import session_env
from agent_reach.utils.url import host_matches
from .base import Action, Channel, Param
@@ -265,6 +266,9 @@ class BossChannel(Channel):
tier = 2
level = "optional"
+ session = "boss-agent-cli"
+ login_argv = ("boss", "--cdp-url", "http://localhost:9222", "login", "--cdp")
+ legacy_state = (".boss-agent",)
actions = (
Action(
"search",
@@ -375,7 +379,7 @@ class BossChannel(Channel):
if city:
args += ["--city", city]
try:
- out = run_cmd(args, timeout=timeout)
+ out = run_cmd(args, timeout=timeout, env=session_env("boss-agent-cli"))
except CommandFailed as exc:
out = exc.stdout
if "{" not in out:
diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.py
index 0ce8f6ad..d7959751 100644
--- a/agent_reach/runtime/cli.py
+++ b/agent_reach/runtime/cli.py
@@ -1,13 +1,18 @@
-"""Unified entry: `agent-reach <channel> <action>`, `read <url>`, `channels`, `check`.
+"""Unified entry: `agent-reach <channel> <action>`, `read <url>`, `channels`, `check`, `login`, `logout`.
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.
"""
from __future__ import annotations
import argparse
import json
+import os
+import shutil
+import subprocess
import sys
from typing import Dict, List, Optional, Sequence
@@ -15,9 +20,10 @@ from agent_reach.channels import get_all_channels
from agent_reach.channels.base import Action, Channel
from .dispatch import DEFAULT_TIMEOUT, find_action, run_action
-from .result import BAD_INPUT, SCHEMA_VERSION, ReachError, envelope
+from .result import BAD_INPUT, 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")
+_TOP_LEVEL = ("channels", "check", "read", "login", "logout")
def unified_channels() -> List[Channel]:
@@ -122,6 +128,10 @@ def _cmd_channels(_args: Sequence[str]) -> int:
"name": ch.name,
"description": ch.description,
"level": ch.level,
+ "login": None if not ch.session else {
+ "logged_in": has_login_state(ch.session),
+ "command": f"agent-reach login {ch.name}",
+ },
"actions": [
{
"name": a.name,
@@ -209,6 +219,53 @@ def _cmd_check(args: Sequence[str]) -> int:
return _emit({"schema_version": SCHEMA_VERSION, "ok": ok, "results": results})
+def _session_channel(cmd: str, args: Sequence[str]):
+ parser = _Parser(prog=cmd, add_help=False)
+ parser.add_argument("channel")
+ if cmd == "login":
+ parser.add_argument("--import-existing", action="store_true")
+ ns = parser.parse_args(list(args))
+ ch = _channel(ns.channel)
+ if ch is None:
+ raise _ArgError(f"unknown channel: {ns.channel}")
+ if not ch.session:
+ raise _ArgError(f"{ch.name} has no login managed by Agent Reach")
+ return ch, ns
+
+
+def _cmd_login(args: Sequence[str]) -> int:
+ try:
+ ch, ns = _session_channel("login", args)
+ except _ArgError as exc:
+ return _bad_input(None, "login", str(exc))
+ if ns.import_existing:
+ copied = import_legacy_state(ch.session, ch.legacy_state)
+ if copied:
+ return _emit(envelope(channel=ch.name, action="login", backend=ch.session,
+ items=[{"imported": copied}]))
+ exe = shutil.which(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")))
+ env = dict(os.environ)
+ 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)
+ 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})")))
+ return _emit(envelope(channel=ch.name, action="login", backend=ch.session, items=[{"logged_in": True}]))
+
+
+def _cmd_logout(args: Sequence[str]) -> int:
+ try:
+ ch, _ = _session_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}]))
+
+
def main(argv: Sequence[str]) -> int:
head, rest = argv[0], argv[1:]
if head == "channels":
@@ -217,6 +274,10 @@ def main(argv: Sequence[str]) -> int:
return _cmd_check(rest)
if head == "read":
return _cmd_read(rest)
+ if head == "login":
+ return _cmd_login(rest)
+ if head == "logout":
+ return _cmd_logout(rest)
channel = _channel(head)
assert channel is not None # guaranteed by handles()
return _cmd_action(channel, rest)
diff --git a/agent_reach/runtime/sessions.py b/agent_reach/runtime/sessions.py
new file mode 100644
index 00000000..3df4fc2c
--- /dev/null
+++ b/agent_reach/runtime/sessions.py
@@ -0,0 +1,57 @@
+"""Login state for upstream tools, kept under ~/.agent-reach/sessions/<tool>/.
+
+Command-line tools store their login in the user's home directory. We run
+each one with HOME pointed at its own session directory, so its login lives
+under Agent Reach and nowhere else. Uninstall removes it with the rest of
+~/.agent-reach/.
+"""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+from agent_reach.utils.paths import ensure_no_symlink_path, home_dir, make_private_dir
+
+
+def sessions_root() -> Path:
+ return home_dir() / ".agent-reach" / "sessions"
+
+
+def session_dir(tool: str) -> Path:
+ """The tool's private home directory (created on first use)."""
+ return make_private_dir(sessions_root() / tool)
+
+
+def session_env(tool: str) -> dict:
+ """Environment overrides that make `tool` store its login in session_dir()."""
+ home = str(session_dir(tool))
+ return {"HOME": home, "USERPROFILE": home}
+
+
+def has_login_state(tool: str) -> bool:
+ """Whether the tool has saved anything in its session directory."""
+ root = sessions_root() / tool
+ return root.is_dir() and any(p.is_file() for p in root.rglob("*"))
+
+
+def clear_session(tool: str) -> bool:
+ """Delete the tool's session directory. Returns whether anything was removed."""
+ root = sessions_root() / tool
+ if not root.exists():
+ return False
+ ensure_no_symlink_path(root, "登录目录")
+ shutil.rmtree(root)
+ return True
+
+
+def import_legacy_state(tool: str, names) -> list:
+ """Copy the tool's existing login from the real home into its session (explicit opt-in)."""
+ copied = []
+ target = session_dir(tool)
+ for name in names:
+ src = home_dir() / name
+ if src.is_dir() and not src.is_symlink():
+ shutil.copytree(src, target / name, dirs_exist_ok=True)
+ copied.append(str(src))
+ return copied
diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.py
index ac462992..f1bc7735 100644
--- a/tests/test_unified_entry.py
+++ b/tests/test_unified_entry.py
@@ -263,3 +263,66 @@ def test_v2ex_topic_id_forms():
assert _parse_topic_id("https://www.v2ex.com/t/1000#reply3") == 1000
with pytest.raises(ReachError):
_parse_topic_id("https://example.com/t/1000")
+
+
+# ── login state under ~/.agent-reach/sessions ──
+
+
+class SessionChannel(FakeChannel):
+ name = "sess"
+ session = "fake-tool"
+ login_argv = ("fake-login",)
+ legacy_state = (".fake-tool",)
+
+
+def session_cli(monkeypatch, tmp_path):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ ch = SessionChannel()
+ monkeypatch.setattr(unified, "get_all_channels", lambda: [ch, FakeChannel()])
+ return tmp_path
+
+
+def test_session_env_points_tool_home_into_agent_reach(session_cli):
+ from agent_reach.runtime.sessions import session_env
+
+ env = session_env("fake-tool")
+ assert env["HOME"] == str(session_cli / ".agent-reach" / "sessions" / "fake-tool")
+
+
+def test_import_existing_copies_old_login_only_on_request(capsys, session_cli):
+ old = session_cli / ".fake-tool"
+ old.mkdir()
+ (old / "credential.json").write_text("{}")
+ code, out = _run(capsys, ["login", "sess", "--import-existing"])
+ assert code == 0
+ assert (session_cli / ".agent-reach" / "sessions" / "fake-tool" / ".fake-tool" / "credential.json").exists()
+ assert old.exists(), "the original login is left untouched"
+
+
+def test_logout_removes_only_that_session(capsys, session_cli):
+ from agent_reach.runtime.sessions import session_dir
+
+ (session_dir("fake-tool") / "x").write_text("1")
+ (session_dir("other") / "y").write_text("1")
+ code, out = _run(capsys, ["logout", "sess"])
+ assert code == 0 and out["items"] == [{"removed": True}]
+ assert not (session_cli / ".agent-reach" / "sessions" / "fake-tool").exists()
+ assert (session_cli / ".agent-reach" / "sessions" / "other" / "y").exists()
+
+
+def test_login_rejects_channels_without_managed_login(capsys, session_cli):
+ code, out = _run(capsys, ["login", "fake"])
+ assert code == 1 and out["error"]["code"] == "BAD_INPUT"
+
+
+def test_channels_reports_login_status(capsys, session_cli):
+ from agent_reach.runtime.sessions import session_dir
+
+ _, out = _run(capsys, ["channels"])
+ sess = next(c for c in out["channels"] if c["name"] == "sess")
+ assert sess["login"] == {"logged_in": False, "command": "agent-reach login sess"}
+ assert next(c for c in out["channels"] if c["name"] == "fake")["login"] is None
+ (session_dir("fake-tool") / "cookie").write_text("1")
+ _, out = _run(capsys, ["channels"])
+ assert next(c for c in out["channels"] if c["name"] == "sess")["login"]["logged_in"] is True