Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
Python agent-infrastructureai-agentai-searchautomationbilibiliclaude-codeclicursorfree-apillm-toolsmcppythonreddit-scrapertwitter-scraperweb-scraperxiaohongshuyoutube-transcript
feat: Agent Reach dedicated browser for browser-login channels
Pnantfef836651d7f
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.pyindex e081370f..751d157b 100644--- a/agent_reach/backends/opencli.py+++ b/agent_reach/backends/opencli.py@@ -226,12 +226,37 @@ def _opencli_error(text: str, login_hint: str):return ReachError(UPSTREAM_BROKEN, f"OpenCLI: {message}")+def _dedicated_profile_env() -> dict:+ """OPENCLI_PROFILE for the Agent Reach browser; fail fast instead of letting OpenCLI hang."""+ from agent_reach.runtime import browser+ from agent_reach.runtime.result import NEED_SETUP, ReachError++ ctx = browser.bound_context()+ if not ctx:+ raise ReachError(+ NEED_SETUP, "the Agent Reach browser is not set up",+ hint="Ask the user to run `agent-reach browser setup` and install the OpenCLI extension in the window it opens.",+ )+ if not browser.is_running():+ raise ReachError(+ NEED_SETUP, "the Agent Reach browser is not running",+ hint="Run `agent-reach browser start` (or ask the user to), then retry.",+ )+ if ctx not in browser.connected_contexts():+ raise ReachError(+ NEED_SETUP, "the Agent Reach browser is running but OpenCLI is not connected to it",+ hint="Ask the user to check the OpenCLI extension is enabled in the Agent Reach browser window.",+ )+ return {"OPENCLI_PROFILE": ctx}++def opencli_call(site: str, args, *, timeout: float, login_hint: str = ""):- """Run `opencli <site> <args> -f json` and return parsed JSON, or raise ReachError."""+ """Run `opencli <site> <args> -f json` in the Agent Reach browser and return parsed JSON."""from agent_reach.runtime.run import CommandFailed, run_cmd+ env = _dedicated_profile_env()try:- out = run_cmd(["opencli", site, *args, "-f", "json"], timeout=timeout)+ out = run_cmd(["opencli", site, *args, "-f", "json"], timeout=timeout, env=env)except CommandFailed as exc:raise _opencli_error(exc.stdout or exc.stderr, login_hint) from Nonetry:diff --git a/agent_reach/channels/base.py b/agent_reach/channels/base.pyindex 504946ba..5548a796 100644--- a/agent_reach/channels/base.py+++ b/agent_reach/channels/base.py@@ -78,6 +78,8 @@ class Channel(ABC):#: 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, ...] = ()+ #: Page the user logs in on, opened in the Agent Reach browser by `agent-reach login`.+ login_url: str = ""#: Backend currently serving this channel; set by check(), None = unavailable.active_backend: Optional[str] = Nonediff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.pyindex 499e65f3..f643b254 100644--- a/agent_reach/channels/boss.py+++ b/agent_reach/channels/boss.py@@ -266,6 +266,7 @@ class BossChannel(Channel):tier = 2level = "optional"+ login_url = "https://www.zhipin.com/web/user/?ka=header-login"session = "boss-agent-cli"login_argv = ("boss", "--cdp-url", "http://localhost:9222", "login", "--cdp")legacy_state = (".boss-agent",)@@ -372,8 +373,8 @@ class BossChannel(Channel):if not cdp_up:raise ReachError(NEED_SETUP,- "the dedicated Chrome (port 9222) is not running",- hint=f"Ask the user to start it with: {_chrome_launch_command()} and log in to zhipin.com themselves.",+ "the Agent Reach browser (port 9222) is not running",+ hint="Run `agent-reach login boss`, let the user log in to zhipin.com in that window, then run `agent-reach login boss --sync`.",)args = ["boss", "--json", "--browser-source", "existing-browser", "--cdp-url", _CDP_URL, "search", query]if city:diff --git a/agent_reach/channels/facebook.py b/agent_reach/channels/facebook.pyindex b36e830f..7c229915 100644--- a/agent_reach/channels/facebook.py+++ b/agent_reach/channels/facebook.py@@ -14,6 +14,7 @@ class FacebookChannel(OpenCLISiteChannel):login_hint = "facebook.com"level = "experimental"+ login_url = "https://www.facebook.com/login"actions = (Action("search",diff --git a/agent_reach/channels/instagram.py b/agent_reach/channels/instagram.pyindex 08c92b0c..7b1a2bc3 100644--- a/agent_reach/channels/instagram.py+++ b/agent_reach/channels/instagram.py@@ -14,6 +14,7 @@ class InstagramChannel(OpenCLISiteChannel):login_hint = "instagram.com"level = "experimental"+ login_url = "https://www.instagram.com/accounts/login/"actions = (Action("search",diff --git a/agent_reach/channels/reddit.py b/agent_reach/channels/reddit.pyindex 85a9d528..a31999f5 100644--- a/agent_reach/channels/reddit.py+++ b/agent_reach/channels/reddit.py@@ -50,6 +50,7 @@ class RedditChannel(Channel):tier = 1 # no zero-config path exists — see module docstringlevel = "optional"+ login_url = "https://www.reddit.com/login/"actions = (Action("search",diff --git a/agent_reach/channels/twitter.py b/agent_reach/channels/twitter.pyindex 2e66a58b..7544f6d4 100644--- a/agent_reach/channels/twitter.py+++ b/agent_reach/channels/twitter.py@@ -54,6 +54,7 @@ class TwitterChannel(Channel):# twitter-cli is not used here: even with explicit credentials it re-reads# browser cookies whenever verification fails.level = "experimental"+ login_url = "https://x.com/i/flow/login"actions = (Action("search",diff --git a/agent_reach/channels/xiaohongshu.py b/agent_reach/channels/xiaohongshu.pyindex 5e082c1e..f4dfcfaa 100644--- a/agent_reach/channels/xiaohongshu.py+++ b/agent_reach/channels/xiaohongshu.py@@ -170,6 +170,7 @@ class XiaoHongShuChannel(Channel):tier = 1level = "optional"+ login_url = "https://www.xiaohongshu.com/explore"actions = (Action("search",diff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.pynew file mode 100644index 00000000..5b054d24--- /dev/null+++ b/agent_reach/runtime/browser.py@@ -0,0 +1,175 @@+"""The Agent Reach dedicated browser.++A separate Chrome whose profile lives in ~/.agent-reach/browser/profile/, so+every browser login Agent Reach relies on stays under ~/.agent-reach/. The user+installs the OpenCLI extension in it once; `agent-reach browser setup` then+records which OpenCLI profile it is (~/.agent-reach/browser/state.json).+The user's own ~/.opencli settings are never modified.++Debugging is bound to 127.0.0.1:9222 only. Any local process that can reach+that port can control this browser; close it when not in use.+"""++from __future__ import annotations++import json+import os+import platform+import re+import shutil+import socket+import subprocess+import urllib.parse+import urllib.request+from pathlib import Path+from typing import List, Optional++from agent_reach.utils.paths import (+ PrivatePathError,+ atomic_write_private_text,+ home_dir,+ make_private_dir,+ read_small_text_no_follow,+)++CDP_PORT = 9222+CDP_URL = f"http://127.0.0.1:{CDP_PORT}"+_CONTEXT_RE = re.compile(r"^\s*(\S+)\s+[—-]\s+connected\b", re.M)+++def browser_root() -> Path:+ return home_dir() / ".agent-reach" / "browser"+++def profile_dir() -> Path:+ return browser_root() / "profile"+++def _state_path() -> Path:+ return browser_root() / "state.json"+++def _load_state() -> dict:+ try:+ text = read_small_text_no_follow(_state_path(), max_bytes=64 * 1024)+ except (OSError, PrivatePathError):+ return {}+ try:+ return json.loads(text) if text else {}+ except ValueError:+ return {}+++def _save_state(state: dict) -> None:+ make_private_dir(browser_root())+ atomic_write_private_text(_state_path(), json.dumps(state, indent=2))+++def chrome_binary() -> Optional[str]:+ system = platform.system()+ candidates = []+ if system == "Darwin":+ candidates = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]+ elif system == "Windows":+ for env in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):+ base = os.environ.get(env)+ if base:+ candidates.append(os.path.join(base, "Google", "Chrome", "Application", "chrome.exe"))+ else:+ candidates = [shutil.which(n) for n in ("google-chrome", "google-chrome-stable", "chromium")]+ return next((c for c in candidates if c and os.path.exists(c)), None)+++def is_running() -> bool:+ with socket.socket() as s:+ s.settimeout(1)+ return s.connect_ex(("127.0.0.1", CDP_PORT)) == 0+++def start(url: str = "about:blank") -> None:+ """Launch the dedicated browser if it is not running; otherwise open `url` in it."""+ if is_running():+ open_url(url)+ return+ exe = chrome_binary()+ if not exe:+ from .result import NEED_SETUP, ReachError++ raise ReachError(NEED_SETUP, "Google Chrome is not installed", hint="Ask the user to install Google Chrome.")+ make_private_dir(profile_dir())+ subprocess.Popen(+ [+ exe,+ "--remote-debugging-address=127.0.0.1",+ f"--remote-debugging-port={CDP_PORT}",+ f"--user-data-dir={profile_dir()}",+ "--no-first-run",+ "--no-default-browser-check",+ url,+ ],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=(os.name != "nt"),+ )+++def open_url(url: str) -> None:+ """Open a new tab in the running dedicated browser."""+ req = urllib.request.Request(f"{CDP_URL}/json/new?{urllib.parse.quote(url, safe='')}", method="PUT")+ with urllib.request.urlopen(req, timeout=5):+ pass+++def connected_contexts() -> List[str]:+ """OpenCLI Browser Bridge profiles connected right now."""+ from .run import run_cmd++ out = run_cmd(["opencli", "profile", "list"], timeout=20)+ return _CONTEXT_RE.findall(out)+++def bound_context() -> Optional[str]:+ """The OpenCLI profile recorded as the dedicated browser, or None."""+ return _load_state().get("opencli_context") or None+++def bind() -> dict:+ """Record which OpenCLI profile is the dedicated browser.++ The first call snapshots profiles already connected (the user's own+ Chrome). After the user installs the extension in the dedicated window,+ the next call finds exactly one new profile and records it.+ """+ state = _load_state()+ now = connected_contexts()+ if state.get("opencli_context") in now:+ return {"status": "ready", "context": state["opencli_context"]}+ if "baseline" not in state:+ state["baseline"] = now+ _save_state(state)+ new = [c for c in now if c not in state["baseline"]]+ if len(new) == 1:+ state["opencli_context"] = new[0]+ _save_state(state)+ return {"status": "ready", "context": new[0]}+ if len(new) > 1:+ return {"status": "ambiguous", "candidates": new}+ return {"status": "waiting_for_extension"}+++def status() -> dict:+ ctx = bound_context()+ running = is_running()+ connected = None+ if ctx and running:+ try:+ connected = ctx in connected_contexts()+ except Exception: # noqa: BLE001 - status must never raise+ connected = False+ return {+ "profile_dir": str(profile_dir()),+ "running": running,+ "opencli_context": ctx,+ "opencli_connected": connected,+ }diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.pyindex d7959751..74926dec 100644--- a/agent_reach/runtime/cli.py+++ b/agent_reach/runtime/cli.py@@ -19,11 +19,12 @@ from typing import Dict, List, Optional, Sequencefrom agent_reach.channels import get_all_channelsfrom agent_reach.channels.base import Action, Channel+from . import browserfrom .dispatch import DEFAULT_TIMEOUT, find_action, run_actionfrom .result import BAD_INPUT, NEED_SETUP, SCHEMA_VERSION, UPSTREAM_BROKEN, ReachError, envelopefrom .sessions import clear_session, has_login_state, import_legacy_state, session_env-_TOP_LEVEL = ("channels", "check", "read", "login", "logout")+_TOP_LEVEL = ("channels", "check", "read", "login", "logout", "browser")def unified_channels() -> List[Channel]:@@ -128,10 +129,7 @@ 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}",- },+ "login": _login_info(ch),"actions": [{"name": a.name,@@ -219,30 +217,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]):+def _login_info(ch: Channel):+ if ch.login_url:+ return {"via": "browser", "logged_in": None, "command": f"agent-reach login {ch.name}"}+ if ch.session:+ return {"via": "session", "logged_in": has_login_state(ch.session), "command": f"agent-reach login {ch.name}"}+ return None+++def _login_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")+ parser.add_argument("--sync", 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:+ if cmd == "logout" and not ch.session:+ 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):raise _ArgError(f"{ch.name} has no login managed by Agent Reach")return ch, nsdef _cmd_login(args: Sequence[str]) -> int:try:- ch, ns = _session_channel("login", args)+ ch, ns = _login_channel("login", args)except _ArgError as exc:return _bad_input(None, "login", str(exc))- if ns.import_existing:+ if ns.import_existing and ch.session: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}]))+ if ch.login_url and not ns.sync:+ try:+ browser.start(ch.login_url)+ except ReachError as err:+ return _emit(envelope(channel=ch.name, action="login", error=err))+ 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."+ )+ 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])if not exe:return _emit(envelope(channel=ch.name, action="login",@@ -259,13 +280,45 @@ def _cmd_login(args: Sequence[str]) -> int:def _cmd_logout(args: Sequence[str]) -> int:try:- ch, _ = _session_channel("logout", args)+ 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}]))+def _cmd_browser(args: Sequence[str]) -> int:+ from agent_reach.backends.opencli import OPENCLI_EXTENSION_URL++ parser = _Parser(prog="browser", add_help=False)+ parser.add_argument("op", choices=("setup", "start", "status"))+ try:+ ns = parser.parse_args(list(args))+ except _ArgError as exc:+ return _bad_input(None, "browser", f"{exc}; usage: agent-reach browser setup|start|status")+ action = f"browser {ns.op}"+ try:+ if ns.op == "start":+ browser.start()+ elif ns.op == "setup":+ result = browser.bind()+ if result["status"] == "waiting_for_extension":+ browser.start(OPENCLI_EXTENSION_URL)+ raise ReachError(+ NEED_SETUP, "waiting for the OpenCLI extension in the Agent Reach browser",+ hint="Ask the user to click 'Add to Chrome' in the window that just opened, then run `agent-reach browser setup` again.",+ )+ if result["status"] == "ambiguous":+ raise ReachError(+ NEED_SETUP, f"more than one new OpenCLI profile connected: {', '.join(result['candidates'])}",+ hint="Ask the user to close other Chrome windows that have the OpenCLI extension, then run setup again.",+ )+ except ReachError as err:+ return _emit(envelope(channel=None, action=action, error=err))+ return _emit(envelope(channel=None, action=action, backend="agent-reach-browser", items=[browser.status()]))+++def main(argv: Sequence[str]) -> int:head, rest = argv[0], argv[1:]if head == "channels":@@ -278,6 +331,8 @@ def main(argv: Sequence[str]) -> int:return _cmd_login(rest)if head == "logout":return _cmd_logout(rest)+ if head == "browser":+ return _cmd_browser(rest)channel = _channel(head)assert channel is not None # guaranteed by handles()return _cmd_action(channel, rest)diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.pyindex f1bc7735..f1e518a6 100644--- a/tests/test_unified_entry.py+++ b/tests/test_unified_entry.py@@ -321,8 +321,74 @@ def test_channels_reports_login_status(capsys, session_cli):_, 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 sess["login"] == {"via": "session", "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+++# ── Agent Reach dedicated browser ──+++def fake_browser(monkeypatch, tmp_path):+ from agent_reach.runtime import browser++ monkeypatch.setenv("HOME", str(tmp_path))+ state = {"contexts": ["daily"], "running": True, "opened": []}+ monkeypatch.setattr(browser, "connected_contexts", lambda: list(state["contexts"]))+ monkeypatch.setattr(browser, "is_running", lambda: state["running"])+ monkeypatch.setattr(browser, "start", lambda url="about:blank": state["opened"].append(url))+ return state+++def test_bind_ignores_profiles_that_were_already_connected(fake_browser):+ from agent_reach.runtime import browser++ assert browser.bind()["status"] == "waiting_for_extension"+ fake_browser["contexts"].append("dedicated")+ assert browser.bind() == {"status": "ready", "context": "dedicated"}+ assert browser.bound_context() == "dedicated"+++def test_bind_refuses_to_guess_between_two_new_profiles(fake_browser):+ from agent_reach.runtime import browser++ browser.bind()+ fake_browser["contexts"] += ["a", "b"]+ assert browser.bind()["status"] == "ambiguous"+ assert browser.bound_context() is None+++def test_opencli_calls_fail_fast_without_dedicated_browser(fake_browser):+ from agent_reach.backends.opencli import opencli_call++ with pytest.raises(ReachError) as info:+ opencli_call("reddit", ["search", "x"], timeout=5)+ assert info.value.code == "NEED_SETUP"+++def test_opencli_calls_fail_fast_when_dedicated_browser_disconnected(fake_browser):+ from agent_reach.backends.opencli import opencli_call+ from agent_reach.runtime import browser++ browser.bind()+ fake_browser["contexts"].append("dedicated")+ browser.bind()+ fake_browser["contexts"].remove("dedicated")+ with pytest.raises(ReachError) as info:+ opencli_call("reddit", ["search", "x"], timeout=5)+ assert info.value.code == "NEED_SETUP"+ assert "not connected" in info.value.message+++def test_login_opens_site_in_dedicated_browser(capsys, monkeypatch, fake_browser):+ class BrowserChannel(FakeChannel):+ name = "web2"+ login_url = "https://example.test/login"++ monkeypatch.setattr(unified, "get_all_channels", lambda: [BrowserChannel()])+ code, out = _run(capsys, ["login", "web2"])+ assert code == 0+ assert fake_browser["opened"] == ["https://example.test/login"]