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
fix: enforce dedicated-browser ownership and release acceptance
LohseZSaic27c485da7e2
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4d2cc1e0..3787f509 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -35,6 +35,9 @@ jobs:pip install -c constraints.txt -e ".[dev]"pytest -q+ - name: Require real channel acceptance for this source+ run: python scripts/check_release_acceptance.py+- name: Build and smoke-install the wheelrun: |python -m pip install builddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2d8e64ae..4b162bee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ All notable changes to this project will be documented in this file.- 添加渠道自动准备工具;删除时只清理该网站的登录。- 公开内容继续先读,不强制登录;安装后用简短表格说明能查什么。- 保留小宇宙转录;去掉额外模型配置和重复的网站抓取实现。+- Bridge 随专用浏览器管理;按真实页面操作计时、定期保存登录。清理失败保留渠道,卸载只删台账文件。发布前必须有渠道真实验收。English:- Browser channels share one profile, close after ten idle minutes and reopen on demand.@@ -27,14 +28,14 @@ English:- 加一个平台只要一句话,需要的软件(Node.js、Chrome、ffmpeg、浏览器扩展)都会自动装好,不需要管理员密码;你只需要登录或者填一个 Key。- 默认平台也能去掉,去掉后更新不会再加回来;去掉时会一起清掉它的登录和专用工具。- 更新会把各平台用到的工具升到最新版;有新版本时,AI 会用大白话告诉你改了什么,你同意了才更新。-- 登录由你本人完成;默认复用专用浏览器已有会话,可明确授权做一次指定网站的导入。+- 登录由你本人在专用窗口完成;只复用专用浏览器已有会话,程序不读取个人 Chrome 登录。English:- Adding a platform takes one sentence. Whatever it needs (Node.js, Chrome, ffmpeg, the browser extension) is installed for you, with no admin password; you only log in or enter a key.- Default platforms can be removed, and updates won't add them back; removing one also clears its login and private tools.- Updating also moves each platform's tools to their latest versions. When a new version is out, your AI tells you in plain words what changed and updates only if you say yes.-- Reuse the shared dedicated session; a one-time site import from a connected Chrome requires explicit authorization.+- Reuse only the shared dedicated session; personal-browser authentication import is unavailable.1.6 is a rebuild. Agents call one command, `agent-reach`; everything Agent Reach installs or stores lives under `~/.agent-reach/`.1.6 是重构版本:Agent 只调一个命令 `agent-reach`,Agent Reach 装的、存的东西全部在 `~/.agent-reach/` 下。@@ -47,14 +48,14 @@ English:- **Skill placement / skill 放置**: one real copy at `~/.agents/skills/agent-reach/SKILL.md` (read directly by Codex, OpenCode, Cline, Warp, Zed); a link to it in the skill folder of Claude Code, OpenClaw, Hermes, Cursor, Gemini CLI, GitHub Copilot and Windsurf when installed (a copy where links are not allowed, e.g. Windows). `agent-reach skill link <dir>` covers any other AI. / 只放一份真文件,其他 AI 的 skill 目录里放指向它的链接(链接:一个指向原文件的快捷方式)。- **Private upstream installs, latest allowed version / 上游私有安装,用最新可用版本**: tools go into `~/.agent-reach/tools/`; the user's own copies are untouched. New installations use the declared tested versions where available; otherwise they install the latest allowed version. `floor` and `exclude` define acceptable existing tools. `state.json` records the version actually installed and `doctor` shows it. Single-instance tools (OpenCLI) reuse the user's copy; if it is older than the floor, it is upgraded only with `--allow-upgrade`. / 优先安装已验收版本;已有工具按兼容范围复用;doctor 显示实际版本。- **`add` gives a finished result / `add` 一步到位**: missing prerequisites are installed without an admin password: uv (official script), ffmpeg (`imageio-ffmpeg` in a private venv), Node.js (official release under `~/.agent-reach/tools/node/` when the system has none), CloakBrowser (falling back to installed Chrome on download failure). git is no longer needed (Boss installs from a GitHub archive). The user only logs in or enters a key. / 缺的依赖自动装好,用户只需登录或填 Key。-- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser. The browser opens by itself when a channel needs it and closes after 10 minutes without use. The OpenCLI extension is loaded automatically on each CloakBrowser launch; Windows system-Chrome fallback may need one Web Store click. Explicit site imports never read personal Chrome Cookie databases. / 专用浏览器按需自动打开,10 分钟不用自动关闭;macOS/Linux 自动装好扩展。+- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser. The browser opens by itself when a channel needs it and closes after 10 minutes without use. The OpenCLI extension is loaded automatically on each CloakBrowser launch; Windows system-Chrome fallback may need one Web Store click. Personal-browser authentication is never read or imported. / 专用浏览器按需自动打开,10 分钟不用自动关闭;macOS/Linux 自动装好扩展。- **remove cleans up / 去掉渠道会清理干净**: deletes the channel's private tools nobody else uses, its CLI session, its login keys and its site cookies in the Agent Reach browser. The shared browser profile is retained for explicit logout/reuse; unused private tools are pruned.- **Removable default channels / 默认渠道可去掉**: `state.json` records `removed_defaults`; `setup` and `update` never add them back; `add` brings one back.- **doctor states / 体检**: not_added, needs_setup, needs_login, unverified, ready, broken; plus `regressed` per channel (passed in the previous check, fails in the latest).- **update** runs `uv tool install --force` on the latest release, upgrades every added channel's tools to the latest allowed version (also when Agent Reach itself has no new release), prunes tools no added channel uses, drops channels no longer in the registry, and refreshes the skill. `result.user_actions` lists in plain sentences what the user must do afterwards. Rollback: `uv tool install --force <previous release zip>`, then `agent-reach update --sync-only`. uv is the only supported installer. 1.5 and earlier installs are migrated on first `setup` / `update`; `config.yaml` keys are kept.-- **Update notice / 新版本提醒**: at most once per 24 h, any command except `update` starts a short background check of the latest GitHub release (never waits on the network; offline is silent). When a newer version exists, every JSON envelope carries `meta.update = {current, latest, notes}`; the skill tells the AI to explain the notes to the user and update only with their yes. / 有新版本时 AI 用大白话告诉用户,用户同意才更新。+- **Update notice / 新版本提醒**: explicit `update --check` refreshes the release cache. Ordinary queries never start a background version check or update dependencies. Cached newer releases appear in `meta.update`; updating requires the user’s agreement. / 只在明确检查后提示新版本,用户同意才更新。- **Release notes / 发布说明**: every CHANGELOG version section starts with a plain summary for users in Chinese and English; it becomes the GitHub release body the AI shows users.-- Xueqiu quotes and stock search via Tencent public quotes (no login); Xueqiu community data uses a session the user imports with `agent-reach login xueqiu --sync`.+- Xueqiu quotes and stock search via Tencent public quotes (no login); Xueqiu community data uses a session synced from the dedicated browser with `agent-reach login xueqiu --sync`.- YouTube `transcribe`; LinkedIn reuses OpenCLI search and job-detail in the shared dedicated browser.### 🔄 Changed / 变更diff --git a/agent_reach/backends/boss_native.py b/agent_reach/backends/boss_native.pyindex 56e1cf39..7d526309 100644--- a/agent_reach/backends/boss_native.py+++ b/agent_reach/backends/boss_native.py@@ -18,17 +18,11 @@ def main():from boss_agent_cli.auth.manager import AuthManagerauth = AuthManager(Path(spec['data_dir']))with BossClient(auth, cdp_url=spec['cdp_url'], browser_source='existing-browser') as boss:- raw = (boss.job_detail(spec['job_id']) if spec.get('action') == 'read' else- boss.search_jobs(spec['query'], city=spec.get('city') or '全国', page=1))+ raw = boss.search_jobs(spec['query'], city=spec.get('city') or '全国', page=1)if raw.get('code') != 0:code = raw.get('code')mapped = {36: 'PLATFORM_BLOCKED', 37: 'PLATFORM_BLOCKED', 9: 'RATE_LIMITED', 1: 'NEED_LOGIN'}.get(code, 'UPSTREAM_BROKEN')return {'ok': False, 'error': {'code': mapped, 'message': str(raw.get('message', 'Boss search failed'))[:300]}}- if spec.get('action') == 'read':- from boss_agent_cli.api.models import JobDetail- detail = JobDetail.from_api(raw.get('zpData') or {})- return {'ok': True, 'data': {name: getattr(detail, name) for name in- ('job_id', 'title', 'company', 'salary', 'city', 'experience', 'education', 'description')}}rows = raw.get('zpData', {}).get('jobList', [])# Do not export securityId/lid or raw browser credentials in unified results.return {'ok': True, 'data': [{'title': r.get('jobName'), 'company': r.get('brandName'),diff --git a/agent_reach/backends/cloak.py b/agent_reach/backends/cloak.pyindex 27e4c29e..9421255d 100644--- a/agent_reach/backends/cloak.py+++ b/agent_reach/backends/cloak.py@@ -12,6 +12,7 @@ def setup() -> dict:from agent_reach.runtime import state, toolsfrom agent_reach.runtime.run import run_cmd+ state.remember_path(state.root() / "cloak-binaries", "dedicated browser binaries")tools.ensure("cloakbrowser")exe = tools.resolve("cloakbrowser")if not exe:diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.pyindex 9834f23e..d487e5ee 100644--- a/agent_reach/backends/opencli.py+++ b/agent_reach/backends/opencli.py@@ -109,27 +109,3 @@ def opencli_items(rows) -> list:))return items---def export_site_cookies(profile: str, domain: str):- """One explicit site-scoped Bridge export; do not inspect Chrome's database."""- from pathlib import Path-- from agent_reach.runtime.result import NEED_SETUP, ReachError- from agent_reach.runtime.run import run_cmd- from agent_reach.runtime.tools import resolve- exe = resolve("opencli")- if not exe:- raise ReachError(NEED_SETUP, "OpenCLI is not installed")- entry = Path(exe).resolve()- # POSIX bins are symlinks into the package; Windows npm .cmd shims live- # beside node_modules. Both use the shipped Page API without editing it.- module = next((root / "dist/src/browser/page.js" for parent in entry.parents- for root in (parent, parent / "node_modules/@jackwener/opencli")- if (root / "dist/src/browser/page.js").is_file()), None)- if module is None:- raise ReachError(NEED_SETUP, "Cannot locate OpenCLI's public Page API; use --state-file")- script = (f"import {{Page}} from {json.dumps(module.as_uri())};"- "const p=new Page('reach-explicit-import',undefined,process.argv[1]);"- "console.log(JSON.stringify(await p.getCookies({domain:process.argv[2]}))); ")- return json.loads(run_cmd(["node", "--input-type=module", "-e", script, profile, domain], timeout=20))diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.pyindex 222a2e6b..0eecb97d 100644--- a/agent_reach/channels/boss.py+++ b/agent_reach/channels/boss.py@@ -47,7 +47,7 @@ class BossChannel(Channel):timeout=90,),Action("read", "Read a direct BOSS job URL", (Param("target", "full job URL"),),- (("boss-agent-cli", "_cli_read"),), timeout=60),+ (("opencli", "_opencli_read"),), timeout=90),)def can_handle(self, url: str) -> bool:@@ -120,26 +120,15 @@ class BossChannel(Channel):return opencli_items(rows)[:limit]- def _cli_read(self, *, target: str, timeout: float) -> list:+ def _opencli_read(self, *, target: str, timeout: float) -> list:import re- from agent_reach.runtime.onboarding import require_boss_cdp+ from agent_reach.backends.opencli import opencli_call, opencli_itemsif not host_matches(str(target), "zhipin.com"):raise ReachError("BAD_INPUT", "Expected a direct zhipin.com job URL")match = re.search(r"/job_detail/([A-Za-z0-9_-]+)\.html", str(target))if not match:raise ReachError("BAD_INPUT", "Expected a direct BOSS job URL")- exe = resolve("boss")- if not exe:- raise ReachError(NEED_SETUP, "Run agent-reach add boss")- python = Path(exe).with_name("python.exe" if os.name == "nt" else "python")- spec = {"action": "read", "job_id": match.group(1), "cdp_url": require_boss_cdp(),- "data_dir": str(session_dir(self.session) / ".boss-agent")}- runner = Path(__file__).parents[1] / "backends" / "boss_native.py"- result = json.loads(run_cmd([str(python), str(runner), json.dumps(spec)], timeout=timeout))- if not result.get("ok"):- err = result.get("error") or {}- raise ReachError(err.get("code", UPSTREAM_BROKEN), err.get("message", "BOSS detail unavailable"))- row = result["data"]- return [make_item(title=row.get("title"), url=str(target), author=row.get("company"),- text=row.get("description"), raw=row)]+ rows = opencli_call("boss", ["detail", match.group(1)], timeout=timeout,+ login_hint="Run agent-reach login boss; complete login yourself in the dedicated browser.")+ return opencli_items(rows)[:1]diff --git a/agent_reach/channels/xiaohongshu.py b/agent_reach/channels/xiaohongshu.pyindex 6ab5ebec..07305e74 100644--- a/agent_reach/channels/xiaohongshu.py+++ b/agent_reach/channels/xiaohongshu.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--"""XiaoHongShu — persistent Cloak session with an existing-Chrome fallback."""+"""XiaoHongShu through upstream OpenCLI in the Reach-owned browser."""from agent_reach.backends.opencli import opencli_call, opencli_itemsfrom agent_reach.runtime.result import BAD_INPUT, NOT_FOUND, UPSTREAM_BROKEN, ReachError@@ -7,8 +7,8 @@ from agent_reach.runtime.result import BAD_INPUT, NOT_FOUND, UPSTREAM_BROKEN, Refrom .base import Action, Channel, Param_XHS_LOGIN_HINT = (- "Ask the user to log in to xiaohongshu.com in their own Chrome (the one with "- "the OpenCLI extension). Never log in or read browser cookies for them."+ "Run agent-reach login xiaohongshu to open the Agent Reach dedicated browser. "+ "The user completes login there. Never ask for a password or read their personal browser login.")diff --git a/agent_reach/config.py b/agent_reach/config.pyindex 510b5746..2e84e981 100644--- a/agent_reach/config.py+++ b/agent_reach/config.py@@ -146,6 +146,9 @@ class Config:if self.read_only:raise ConfigReadOnlyError("当前配置是只读的,不能保存")self._ensure_dir()+ if self.config_path == home_dir() / ".agent-reach" / "config.yaml":+ from agent_reach.runtime import state+ state.remember_path(self.config_path, "configuration")_atomic_write_yaml(self.config_path, self.data)def get(self, key: str, default: Any = None) -> Any:diff --git a/agent_reach/runtime/bridge.py b/agent_reach/runtime/bridge.pynew file mode 100644index 00000000..170da23f--- /dev/null+++ b/agent_reach/runtime/bridge.py@@ -0,0 +1,95 @@+"""Official OpenCLI Bridge, supervised only while the dedicated browser is open.++No upstream edits. Existing compatible user processes are borrowed, never killed.+"""+from __future__ import annotations++import json+import subprocess+import time+import urllib.request+from pathlib import Path++from . import tools+from .result import NEED_SETUP, ReachError++URL = "http://127.0.0.1:19825"+++def status() -> dict:+ request = urllib.request.Request(URL + "/status", headers={"X-OpenCLI": "1"})+ try:+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))+ with opener.open(request, timeout=1) as response:+ value = json.loads(response.read(128 * 1024))+ return value if isinstance(value, dict) and value.get("ok") else {}+ except (OSError, ValueError):+ return {}+++def launch_spec() -> tuple[list[str], str]:+ exe = tools.resolve("opencli")+ node = tools.resolve("node")+ if not exe or not node:+ raise ReachError(NEED_SETUP, "Run agent-reach add CHANNEL to install Node and OpenCLI")+ resolved = Path(exe).resolve()+ # npm on Windows uses a .cmd shim beside node_modules; POSIX uses a symlink.+ candidates = [*resolved.parents, Path(exe).parent / "node_modules" / "@jackwener" / "opencli"]+ for root in candidates:+ daemon = root / "dist" / "src" / "daemon.js"+ package = root / "package.json"+ if daemon.is_file() and package.is_file():+ return [node, str(daemon)], str(json.loads(package.read_text("utf-8"))["version"])+ raise ReachError(NEED_SETUP, "Unsupported OpenCLI package layout; reinstall official OpenCLI")+++def require_compatible() -> dict:+ """Do not let upstream CLI auto-restart an unrelated older daemon."""+ _, version = launch_spec()+ current = status()+ if current and current.get("daemonVersion") != version:+ raise ReachError(NEED_SETUP, "An OpenCLI Bridge of another version is running; left it unchanged",+ hint="Close that OpenCLI session yourself, then retry. Reach will not restart it.")+ return current+++def start():+ """Return a child handle only when Reach started this process."""+ argv, _ = launch_spec()+ if require_compatible():+ return None+ proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL)+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ current = require_compatible()+ if current:+ if current.get("pid") == proc.pid:+ return proc+ proc.wait(timeout=5) # another starter won the port; never claim its process+ return None+ if proc.poll() is not None:+ break+ time.sleep(0.1)+ proc.terminate()+ proc.wait(timeout=5)+ raise ReachError(NEED_SETUP, "OpenCLI Bridge could not start alongside the dedicated browser")+++def close(proc, context: str | None) -> str | None:+ """Reap our child; preserve it if another browser has adopted it."""+ if proc is None:+ return None+ current = status()+ foreign = [p for p in current.get("profiles", []) if p.get("contextId") != context]+ if current.get("pid") == proc.pid and foreign:+ return "Bridge retained: another browser is using it. Close it through OpenCLI after that session ends."+ # Popen is our ownership handle, not a PID discovered on the user's machine.+ if proc.poll() is None:+ proc.terminate()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=5)+ return Nonediff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.pyindex 833d1acd..c92d8349 100644--- a/agent_reach/runtime/browser.py+++ b/agent_reach/runtime/browser.py@@ -97,7 +97,9 @@ def _load_state() -> dict:def _save_state(state: dict) -> None:+ from . import state as ledgermake_private_dir(browser_root())+ ledger.remember_path(_state_path(), "browser lifecycle state")atomic_write_private_text(_state_path(), json.dumps(state, indent=2))@@ -132,11 +134,47 @@ def last_used() -> Optional[float]:return None+# Generic activity signal only: no site selectors, content or credentials.+_ACTIVITY = """(() => {+ if (!window.__reachActivityInstalled) {+ window.__reachActivityInstalled = true;+ window.__reachLastInput = 0;+ for (const name of ['pointerdown', 'keydown', 'wheel', 'touchstart'])+ addEventListener(name, event => {+ if (event.isTrusted) window.__reachLastInput = Date.now();+ }, {capture: true, passive: true});+ }+ return window.__reachLastInput;+})()"""+++def observe_activity() -> None:+ """Poll trusted human input and remember origins for later site-only logout."""+ from . import cdp+ origins = set(_load_state().get("visited_origins", []))+ before = set(origins)+ for target in cdp._json("/json/list") or []:+ if target.get("type") != "page":+ continue+ parsed = urllib.parse.urlsplit(target.get("url", ""))+ if parsed.scheme in {"http", "https"} and parsed.netloc:+ origins.add(f"{parsed.scheme}://{parsed.netloc}")+ result = cdp.call("Runtime.evaluate", {"expression": _ACTIVITY, "returnByValue": True},+ target_id=target.get("id")) or {}+ value = result.get("result", {}).get("value")+ if isinstance(value, (int, float)) and (last_used() or 0) < value / 1000 <= time.time() + 1:+ touch()+ if origins != before:+ update_state(visited_origins=sorted(origins))++# ── cross-process locks ──def _open_lock(path: Path) -> int:+ from . import state as ledgermake_private_dir(path.parent)+ ledger.remember_path(path, "browser lock")flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)return os.open(path, flags, 0o600)@@ -321,7 +359,7 @@ def extension_version() -> Optional[str]:return None-def refresh_extension() -> dict:+def refresh_extension(*, upgrade: bool = False) -> dict:"""Install or update the OpenCLI extension from the latest OpenCLI release.Keeps the current copy when GitHub is unreachable; raises only if there is none.@@ -330,6 +368,8 @@ def refresh_extension() -> dict:from .result import UPSTREAM_BROKEN, ReachErrorcurrent = extension_version()+ if current and not upgrade:+ return {"version": current, "updated": False}try:release = json.loads(_fetch(OPENCLI_RELEASE_API))asset = next(a for a in release.get("assets", []) if _EXTENSION_ASSET_RE.match(a.get("name", "")))@@ -340,7 +380,9 @@ def refresh_extension() -> dict:state = _load_state()if current and state.get("extension_asset") == asset["name"]:return {"version": current, "updated": False}+ from . import state as ledgermake_private_dir(browser_root())+ ledger.remember_path(extension_dir(), "OpenCLI extension")work = Path(tempfile.mkdtemp(prefix=".extension-", dir=browser_root()))try:archive = work / "extension.zip"@@ -406,6 +448,10 @@ def _launch(url: str) -> None:exe = ensure_chrome()_prepare_shared_profile()make_private_dir(profile_dir())+ from . import state as ledger+ ledger.remember_path(profile_dir(), "dedicated browser profile")+ for name in ("watcher.log", "session.json", "last_used", "watcher.lock", "start.lock", "session.lock"):+ ledger.remember_path(browser_root() / name, "browser lifecycle")update_state(started_at=time.time())if not can_load_extension():subprocess.Popen(chrome_argv(exe, url, pipe=False), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,@@ -466,6 +512,8 @@ def _prepare_shared_profile() -> None:launcher_python=selected.get("launcher_python"))backup = browser_root() / ("profile-before-cloak-" + str(time.time_ns()))profile_dir().rename(backup)+ from . import state as ledger+ ledger.remember_path(backup, "previous dedicated profile backup")update_state(profile_backend="cloakbrowser", profile_backup=str(backup))@@ -636,50 +684,73 @@ def _clear_running_site(domains: List[str]) -> int:from . import cdpfrom .result import UPSTREAM_BROKEN, ReachError# Stop the removed site's open pages from refreshing its login in memory.- pages = [t for t in (cdp._json("/json/list") or []) if t.get("type") == "page"]+ targets = cdp._json("/json/list")+ cookies = cdp.call("Storage.getCookies")+ if not isinstance(targets, list) or cookies is None:+ raise ReachError(UPSTREAM_BROKEN, "Could not inspect site data; login cleanup is incomplete")+ pages = [t for t in targets if t.get("type") == "page"]closing = [t for t in pages if any(cdp.domain_matches(urllib.parse.urlsplit(t.get("url", "")).hostname or "", d) for d in domains)]+ page_origins = {urllib.parse.urlsplit(t["url"]).scheme + "://" + urllib.parse.urlsplit(t["url"]).netloc+ for t in closing if urllib.parse.urlsplit(t["url"]).scheme in {"http", "https"}}+ visited = set(_load_state().get("visited_origins", []))+ page_origins |= {o for o in visited if any(cdp.domain_matches(urllib.parse.urlsplit(o).hostname or "", d) for d in domains)}if closing and len(closing) == len(pages):if cdp.call("Target.createTarget", {"url": "about:blank"}) is None:raise ReachError(UPSTREAM_BROKEN, "Could not retain the shared browser while logging out")for target in closing:if cdp.call("Target.closeTarget", {"targetId": target["id"]}) is None:raise ReachError(UPSTREAM_BROKEN, "Could not close the removed site's page")- doomed = [c for c in (cdp.call("Storage.getCookies") or {}).get("cookies", [])+ doomed = [c for c in cookies.get("cookies", [])if any(cdp.domain_matches(c.get("domain", ""), d) for d in domains)]keys = ("name", "domain", "path", "secure", "httpOnly", "sameSite", "partitionKey", "sourceScheme", "sourcePort")expired = [{**{k: c[k] for k in keys if k in c}, "value": "", "expires": 1} for c in doomed]if expired and cdp.call("Storage.setCookies", {"cookies": expired}) is None:from .result import UPSTREAM_BROKEN, ReachErrorraise ReachError(UPSTREAM_BROKEN, "Could not clear this site's cookies in the dedicated browser")- origins = {d.lstrip(".") for d in domains} | {c["domain"].lstrip(".") for c in doomed}- for host in origins:- for origin in ("https://" + host, "http://" + host):- if cdp.call("Storage.clearDataForOrigin", {"origin": origin,- "storageTypes": "local_storage,indexeddb,cache_storage,service_workers"}, page=True) is None:- from .result import UPSTREAM_BROKEN, ReachError- raise ReachError(UPSTREAM_BROKEN, "Could not clear this site's browser storage")+ hosts = {d.lstrip(".") for d in domains} | {c["domain"].lstrip(".") for c in doomed}+ # Include the site's conventional www origin even when no www cookie exists.+ hosts |= {"www." + d.lstrip(".") for d in domains}+ origins = page_origins | {scheme + h for h in hosts for scheme in ("https://", "http://")}+ for origin in origins:+ if cdp.call("Storage.clearDataForOrigin", {"origin": origin,+ "storageTypes": "all"}, page=True) is None:+ raise ReachError(UPSTREAM_BROKEN, "Could not clear this site's browser storage; channel retained")_save_session_unlocked()- left = {(c.get("name"), c.get("domain"), c.get("path")) for c in (cdp.call("Storage.getCookies") or {}).get("cookies", [])}+ after = cdp.call("Storage.getCookies")+ if after is None or any(any(cdp.domain_matches(c.get("domain", ""), d) for d in domains) for c in after.get("cookies", [])):+ raise ReachError(UPSTREAM_BROKEN, "Site login cleanup could not be verified; channel retained")+ update_state(visited_origins=sorted(visited - origins))+ left = {(c.get("name"), c.get("domain"), c.get("path")) for c in after.get("cookies", [])}return sum((c.get("name"), c.get("domain"), c.get("path")) not in left for c in doomed)def delete_profile() -> bool:- """Close the dedicated browser and remove ~/.agent-reach/browser/. True if something was removed."""+ """Remove recorded browser artifacts only, preserving unknown files."""+ from . import state as ledgerroot = browser_root()if not root.exists():return False- with contextlib.suppress(Exception), start_lock(wait=15.0):- stop()- pids = _profile_pids()- for pid in pids:- with contextlib.suppress(OSError):- os.kill(pid, signal.SIGTERM)- if not wait_for(lambda: not _profile_pids(), 5.0, interval=0.2):- for pid in _profile_pids():- with contextlib.suppress(OSError):- os.kill(pid, signal.SIGKILL)- wait_for(lambda: not watcher_running(), 20.0, interval=0.2)- shutil.rmtree(root, ignore_errors=True)+ paths = [root.parent / n for n in ledger.load().get("owned_paths", {})+ if n.startswith("browser/") and ".." not in Path(n).parts]+ if not paths:+ return False+ if not stop():+ from .result import UPSTREAM_BROKEN, ReachError+ raise ReachError(UPSTREAM_BROKEN, "The dedicated browser could not close; its files were retained")+ wait_for(lambda: not watcher_running(), 20.0, interval=0.2)+ paths = [root.parent / n for n in ledger.load().get("owned_paths", {})+ if n.startswith("browser/") and ".." not in Path(n).parts]+ for path in sorted(paths, key=lambda p: len(p.parts), reverse=True):+ from agent_reach.utils.paths import ensure_no_symlink_path+ ensure_no_symlink_path(path.parent, "browser artifact parent")+ if path.is_file() or path.is_symlink():+ path.unlink(missing_ok=True)+ elif path.is_dir():+ shutil.rmtree(path)+ try:+ root.rmdir()+ except OSError:+ passreturn not root.exists()@@ -688,10 +759,10 @@ def delete_profile() -> bool:def connected_contexts() -> List[str]:"""OpenCLI Browser Bridge profiles connected right now."""- from .run import run_cmd+ from . import bridge- out = run_cmd(["opencli", "profile", "list"], timeout=20)- return _CONTEXT_RE.findall(out)+ current = bridge.require_compatible()+ return [p["contextId"] for p in current.get("profiles", []) if p.get("extensionConnected")]def bound_context() -> Optional[str]:@@ -822,6 +893,7 @@ def status() -> dict:"opencli_context": ctx,"opencli_connected": connected,"idle_close_after_s": int(IDLE_LIMIT),+ "bridge_note": _load_state().get("bridge_note"),}@@ -833,82 +905,3 @@ def setup_problems() -> List[str]:if not can_load_extension() and not bound_context():return ["Agent Reach browser not set up: run `agent-reach browser setup`"]return []---def import_session(channel: str, *, state_file=None, opencli_profile=None, only_missing: bool = False) -> dict:- """Explicit one-time, site-scoped import. Source data stays untouched."""- from . import cdp, manage, state- from .browser_binding import execution_lock- from .result import BAD_INPUT, UPSTREAM_BROKEN, ReachError- if bool(state_file) == bool(opencli_profile):- raise ReachError(BAD_INPUT, "Choose exactly one of --state-file or --opencli-profile")- ch = manage._channel(channel)- domains = manage.site_domains(ch)- if not domains:- raise ReachError(BAD_INPUT, "This channel has no browser login")- if state_file:- try:- data = json.loads(read_small_text_no_follow(Path(state_file), max_bytes=2 * 1024 * 1024) or "null")- except (ValueError, OSError, PrivatePathError):- raise ReachError(BAD_INPUT, "Cannot read the supplied session file") from None- else:- from agent_reach.backends.opencli import export_site_cookies- data = []- for domain in domains:- data.extend(export_site_cookies(opencli_profile, domain))- rows = data.get("cookies", []) if isinstance(data, dict) else data- if not isinstance(rows, list):- raise ReachError(BAD_INPUT, "Expected a cookie array or storage-state JSON")- cookies = []- for row in rows:- if not isinstance(row, dict) or not any(cdp.domain_matches(str(row.get("domain", "")), d) for d in domains):- continue- if not isinstance(row.get("name"), str) or not isinstance(row.get("value"), str):- continue- expiry = row.get("expires", row.get("expirationDate", -1))- if not isinstance(expiry, (int, float)) or (expiry > 0 and expiry <= time.time()):- continue- cookie = {k: row[k] for k in ("name", "value", "domain", "path", "secure", "httpOnly", "sameSite") if k in row}- if expiry > 0:- cookie["expires"] = expiry- if cookie.get("sameSite") not in {"Strict", "Lax", "None"}:- cookie.pop("sameSite", None)- cookies.append(cookie)- if not cookies:- raise ReachError(BAD_INPUT, "No unexpired cookies for the selected site; the source login may need renewal")- ensure_running()- with execution_lock("browser:shared"):- if only_missing:- present = cdp.call("Storage.getCookies")- if present is None:- raise ReachError(UPSTREAM_BROKEN, "Could not inspect the saved dedicated session")- keys = {(c["name"], c["domain"], c.get("path", "/")) for c in present.get("cookies", [])}- cookies = [c for c in cookies if (c["name"], c["domain"], c.get("path", "/")) not in keys]- if cookies and cdp.call("Storage.setCookies", {"cookies": cookies}) is None:- raise ReachError(UPSTREAM_BROKEN, "The dedicated browser did not accept the imported session")- def invalidate(saved):- saved["checks"].pop(channel, None)- saved.get("reuse_sources", {}).pop(channel, None)- saved.setdefault("session_revisions", {})[channel] = state.now()- state.mutate(invalidate)- save_session()- touch()- return {"channel": channel, "imported_cookies": len(cookies), "original_browser_changed": False,- "logged_in": None, "authorization": "one_time_site_import", "next": f"agent-reach check {channel} --search --text"}---def migrate_owned_session(channel: str) -> None:- """Merge old Reach-owned site snapshots once, without replacing a newer login."""- from . import state- from .result import BAD_INPUT, ReachError- source = state.root() / "sessions" / (channel + "-cloak") / "profile" / "reach-session.json"- if not source.is_file() or state.load().get("session_migrations", {}).get(channel):- return- try:- result = import_session(channel, state_file=source, only_missing=True)- status = {"at": state.now(), "imported_cookies": result["imported_cookies"]}- except ReachError as exc:- if exc.code != BAD_INPUT:- raise- status = {"at": state.now(), "imported_cookies": 0, "reason": "old snapshot unavailable or expired"}- state.mutate(lambda saved: saved.setdefault("session_migrations", {}).__setitem__(channel, status))diff --git a/agent_reach/runtime/browser_binding.py b/agent_reach/runtime/browser_binding.pyindex ca2aa419..141ad3d1 100644--- a/agent_reach/runtime/browser_binding.py+++ b/agent_reach/runtime/browser_binding.py@@ -26,6 +26,9 @@ def environment(channel: str):profile = browser.bound_context()if not profile:raise ReachError(NEED_SETUP, "OpenCLI has not connected to the dedicated browser")+ from . import bridge+ if not bridge.require_compatible():+ raise ReachError(NEED_SETUP, "The dedicated browser Bridge disconnected; reopen the Reach browser")browser.touch()return {"OPENCLI_PROFILE": profile, "OPENCLI_WINDOW": "background","OPENCLI_CDP_ENDPOINT": "", "OPENCLI_CDP_TARGET": ""}@@ -62,6 +65,8 @@ def execution_lock(profile: str):except OSError:raise ReachError("BUSY", "Another Reach command is using this Chrome profile") from Nonetry:+ if profile != "reach-state-write":+ state.remember_path(path, "execution lock")yieldfinally:if sys.platform == "win32":diff --git a/agent_reach/runtime/browser_watcher.py b/agent_reach/runtime/browser_watcher.pyindex f76bc519..9c373b57 100644--- a/agent_reach/runtime/browser_watcher.py+++ b/agent_reach/runtime/browser_watcher.py@@ -20,7 +20,7 @@ import timefrom typing import Optionalfrom urllib.parse import unquote, urlsplit-from . import browser+from . import bridge, browserdef _launch_with_pipe(chrome: str, url: str):@@ -101,12 +101,13 @@ def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[s"""Run until the browser is gone. Returns why it stopped."""idle = browser.IDLE_LIMIT if idle is None else idlefd = browser._open_lock(browser.watcher_lock_path())- proc = conn = ctx = None+ proc = conn = ctx = bridge_proc = Nonetry:# A probe (watcher_running) holds the lock for an instant; a live watcher holds it for good.# A watcher of a browser that just closed may still be on its way out: give it a moment.if not browser.wait_for(lambda: browser.try_lock(fd), 10.0 if launch else 2.0, interval=0.1):return "another watcher is running"+ bridge_proc = bridge.start()if launch is not None:if browser.is_running():return "a browser is already using the debugging port"@@ -118,6 +119,7 @@ def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[sbrowser.update_state(running_backend="cloakbrowser" if cloak else "chrome",profile_backend="cloakbrowser" if cloak else "chrome")browser.restore_session()+ browser.update_state(bridge_pid=bridge_proc.pid if bridge_proc else None, bridge_note=None)began = time.time()def gone() -> bool:@@ -128,6 +130,9 @@ def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[swhile True:if gone():return "browser closed"+ if bridge_proc is not None and bridge_proc.poll() is not None:+ return "owned Bridge exited; browser closed with it"+ browser.observe_activity()browser.save_session()used = max(began, browser.last_used() or 0.0)left = used + idle - time.time()@@ -162,6 +167,10 @@ def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[sexcept subprocess.TimeoutExpired:proc.kill()proc.wait(5)+ note = bridge.close(bridge_proc, browser.bound_context())+ browser.update_state(bridge_note=note, bridge_pid=None)+ if note:+ print(note, file=sys.stderr, flush=True)os.close(fd)diff --git a/agent_reach/runtime/cdp.py b/agent_reach/runtime/cdp.pyindex 12c4dc1d..b563f1a0 100644--- a/agent_reach/runtime/cdp.py+++ b/agent_reach/runtime/cdp.py@@ -74,10 +74,12 @@ def _send(sock: socket.socket, text: str) -> None:sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))-def call(method: str, params: Optional[dict] = None, *, page: bool = False) -> Optional[dict]:+def call(method: str, params: Optional[dict] = None, *, page: bool = False,+ target_id: Optional[str] = None) -> Optional[dict]:"""One browser-level CDP call; returns `result` or None if unreachable."""- target = (next((t for t in (_json("/json/list") or []) if t.get("type") == "page"), {})- if page else (_json("/json/version") or {}))+ target = (next((t for t in (_json("/json/list") or []) if+ (t.get("id") == target_id if target_id else t.get("type") == "page")), {})+ if page or target_id else (_json("/json/version") or {}))ws = target.get("webSocketDebuggerUrl")if not ws:return Nonediff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.pyindex 9fe771e7..84f9c3e4 100644--- a/agent_reach/runtime/cli.py+++ b/agent_reach/runtime/cli.py@@ -9,8 +9,7 @@ go to stderr. Exit code 0 = ok, 1 = error. Exceptions for humans: `help`, and`--text` on setup / doctor / check. `login` shows the upstream's interactiveoutput (QR codes, prompts) on stderr so stdout still carries only the JSON.-When a newer release is known (cached by a background check at most once a-day, never waited on), every JSON object carries meta.update = {current, latest, notes}.+When a newer release is known (cached by an explicit update --check), every JSON object carries meta.update = {current, latest, notes}."""from __future__ import annotations@@ -57,9 +56,6 @@ For the user:agent-reach add <channel> install channel dependencies and prepare its browseragent-reach remove <channel> remove a channel (defaults too) and what only it usedagent-reach login|logout <channel> log in (the user does it) / forget the login- agent-reach browser profiles list connected login sources- agent-reach browser import CHANNEL --opencli-profile ID one-time site login import- agent-reach browser import CHANNEL --state-file FILE import an explicit local session fileagent-reach browser setup|status|stop shared dedicated browseragent-reach skill [link <skills-dir>] where the agent skill is; link it for another AIagent-reach doctor [--text] status of every channel and installed tool versions (no network)@@ -408,6 +404,8 @@ def _cmd_login(args: Sequence[str]) -> int:ch, ns = _login_channel("login", args)except _ArgError as exc:return _bad_input(None, "login", str(exc))+ if ns.import_existing and ch.login_url:+ return _bad_input(ch.name, "login", "Personal-browser authentication import is unavailable; log in in the Reach dedicated window")if ns.import_existing and ch.session:copied = import_legacy_state(ch.session, ch.legacy_state)if copied:@@ -463,7 +461,9 @@ def _cmd_logout(args: Sequence[str]) -> int:from . import manage, statebrowser.clear_site(manage.site_domains(ch))# Retired per-site snapshots must not revive a login after logout.- manage._remove(state.root() / "sessions" / (ch.name + "-cloak"))+ legacy = state.root() / "sessions" / (ch.name + "-cloak")+ if state.owned_path(legacy):+ manage._remove(legacy)def forget(saved):saved["checks"].pop(ch.name, None)saved.get("reuse_sources", {}).pop(ch.name, None)@@ -484,10 +484,7 @@ def _cmd_logout(args: Sequence[str]) -> int:def _cmd_browser(args: Sequence[str]) -> int:parser = _Parser(prog="browser", add_help=False)- parser.add_argument("op", choices=("setup", "status", "stop", "profiles", "import"))- parser.add_argument("channel", nargs="?")- parser.add_argument("--state-file")- parser.add_argument("--opencli-profile")+ parser.add_argument("op", choices=("setup", "status", "stop"))parser.add_argument("--retry-cloak", action="store_true")try:ns = parser.parse_args(list(args))@@ -495,16 +492,6 @@ def _cmd_browser(args: Sequence[str]) -> int:raise _ArgError("--retry-cloak applies only to browser setup")if ns.op == "setup":return _mgmt("browser setup", browser.setup, retry_cloak=ns.retry_cloak)- if ns.op == "import":- if not ns.channel:- raise _ArgError("browser import requires a channel")- return _mgmt("browser import", browser.import_session, ns.channel,- state_file=ns.state_file, opencli_profile=ns.opencli_profile)- if ns.channel or ns.state_file or ns.opencli_profile:- raise _ArgError("session import arguments apply only to browser import")- if ns.op == "profiles":- from .onboarding import profiles- return _mgmt("browser profiles", profiles)return _mgmt("browser " + ns.op, getattr(browser, ns.op))except _ArgError as exc:return _bad_input(None, "browser", str(exc))@@ -525,23 +512,18 @@ def _cmd_flow(head: str, args: Sequence[str]) -> int:else:parser.add_argument("--action")parser.add_argument("--no-verify", action="store_true")- parser.add_argument("--forget-source", action="store_true")- parser.add_argument("--reuse-profile")try:ns = parser.parse_args(list(args))if head == "resume":from .flow import resumeresult = resume(ns.operation_id)elif head == "ensure":- result = (flow.forget_source(ns.channel) if ns.forget_source else- flow.ensure(ns.channel, action=ns.action, source_profile=ns.reuse_profile,- verify=not ns.no_verify))+ result = flow.ensure(ns.channel, action=ns.action, verify=not ns.no_verify)else:params = json.loads(ns.params)if not isinstance(params, dict):raise _ArgError("--params must be a JSON object")- result = flow.execute(ns.channel, ns.channel_action, params, timeout=ns.timeout,- source_profile=ns.reuse_profile)+ result = flow.execute(ns.channel, ns.channel_action, params, timeout=ns.timeout)except (ValueError, _ArgError) as exc:return _bad_input(None, head, str(exc))except ReachError as err:@@ -556,12 +538,10 @@ def main(argv: Sequence[str]) -> int:if not argv or argv[0] in ("help", "-h", "--help"):sys.stdout.write(HELP)return 0- from . import tools, update_notice+ from . import toolstools.extend_path()_SHOW_NOTICE = argv[0] != "update"- if argv[0] not in ("update", "uninstall"):- update_notice.maybe_refresh()_apply_saved_proxy()head, rest = argv[0], argv[1:]if head == "channels":diff --git a/agent_reach/runtime/flow.py b/agent_reach/runtime/flow.pyindex 040bbd6f..dd837704 100644--- a/agent_reach/runtime/flow.py+++ b/agent_reach/runtime/flow.py@@ -1,7 +1,7 @@"""Resumable setup and execution for the CLI.The caller selects a channel and action. Reach handles its declared primary-backend, supports an explicit one-time site import, and records a real+backend, reuses only its dedicated session, and records a realquery result. No password, cookie, or browser database is exposed here."""@@ -66,7 +66,7 @@ def _record(channel: str, action: str, out: dict) -> None:state.mutate(change)-def prepare(channel: str, *, action: Optional[str] = None, source_profile: Optional[str] = None,+def prepare(channel: str, *, action: Optional[str] = None,install: bool = True) -> dict:"""Prepare dependencies and the shared browser. No model and no implicit cookie export."""ch = manage._channel(channel)@@ -84,18 +84,13 @@ def prepare(channel: str, *, action: Optional[str] = None, source_profile: Optioif ch.login_url:from . import browserbrowser.ensure_running()- browser.migrate_owned_session(channel)- if source_profile:- browser.import_session(channel, opencli_profile=source_profile)- elif source_profile:- raise ReachError(BAD_INPUT, "This channel does not use the shared browser")return {"ok": True, "status": "prepared", "channel": channel,"action": selected.name, "backend": selected.backends[0][0]}-def ensure(channel: str, *, action: Optional[str] = None, source_profile: Optional[str] = None,+def ensure(channel: str, *, action: Optional[str] = None,verify: bool = True, install: bool = True) -> dict:- prepared = prepare(channel, action=action, source_profile=source_profile, install=install)+ prepared = prepare(channel, action=action, install=install)if not prepared["ok"] or not verify:return preparedselected = _action(manage._channel(channel), prepared["action"])@@ -122,12 +117,12 @@ def _failure(channel: str, action: str, out: dict) -> dict:def execute(channel: str, action: str, params: dict[str, Any], *, timeout: float = 60,- source_profile: Optional[str] = None, operation_id: Optional[str] = None) -> dict:+ operation_id: Optional[str] = None) -> dict:if not isinstance(params, dict):raise ReachError(BAD_INPUT, "params must be an object")ch = manage._channel(channel)_, params = validate_action(ch, action, params, timeout=timeout)- prepared = prepare(channel, action=action, source_profile=source_profile)+ prepared = prepare(channel, action=action)if not prepared["ok"]:result = preparedelse:@@ -165,11 +160,3 @@ def resume(operation_id: str) -> dict:result = execute(pending["channel"], pending["action"], pending["params"],timeout=pending["timeout"], operation_id=operation_id)return result---def forget_source(channel: str) -> dict:- manage._channel(channel)- with execution_lock("prepare:" + channel):- removed = state.mutate(lambda data: data.setdefault("reuse_sources", {}).pop(channel, None) is not None)- return {"ok": True, "status": "source_forget", "channel": channel, "source_grant_removed": removed,- "existing_browser_and_cloak_sessions_changed": False}diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.pyindex 53e00b61..9d91c967 100644--- a/agent_reach/runtime/manage.py+++ b/agent_reach/runtime/manage.py@@ -12,6 +12,7 @@ import osimport shutilimport subprocessimport sys+from functools import lru_cachefrom pathlib import Pathfrom typing import Dict, List, Optionalfrom urllib.parse import urlparse@@ -57,6 +58,18 @@ def _uses_browser(ch) -> bool:+@lru_cache(maxsize=1)+def code_signature() -> str:+ """A candidate with the same version must not inherit another build's passes."""+ root = Path(__file__).parents[1]+ digest = hashlib.sha256()+ for path in sorted(root.rglob("*.py")):+ if "api" not in path.relative_to(root).parts:+ digest.update(path.relative_to(root).as_posix().encode())+ digest.update(path.read_bytes())+ return digest.hexdigest()[:16]++def fingerprint(channel: str) -> str:"""Invalidate checks when this build, channel dependencies, source, or network changes."""from agent_reach.config import Config@@ -69,7 +82,7 @@ def fingerprint(channel: str) -> str:relevant = set(ch.prereqs) | set(ch.tools) | set(channel_tools(ch))relevant.update(name for action in ch.actions for name, _ in action.backends)session_revision = data.get("session_revisions", {}).get(channel)- value = [__version__, channel, profile_for(channel),+ value = [__version__, code_signature(), channel, profile_for(channel),cfg.get("proxy"), session_revision,{k: data["tools"].get(k, {}).get("version") for k in sorted(relevant)}]return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()[:16]@@ -252,7 +265,6 @@ def _install_channel(ch, *, allow_upgrade: bool = False) -> List[dict]:if _uses_browser(ch):from . import browserbrowser.setup()- browser.migrate_owned_session(ch.name)ch.on_add()return installed@@ -307,14 +319,14 @@ def remove(name: str) -> dict:ch = _channel(name)data = state.load()was_added = is_added(ch, data)- data["channels"].pop(name, None)- data["checks"].pop(name, None)- if ch.level == "default" and name not in data["removed_defaults"]:- data["removed_defaults"].append(name)- state.save(data)+ if not was_added:+ return {"channel": name, "removed": False, "removed_tools": [], "cleared_cookies": 0,+ "browser_deleted": False, "warnings": []}+ # Keep the registration and its tools until required login cleanup succeeds.+ cookies = browser.clear_site(site_domains(ch)) if _uses_browser(ch) else 0ch.on_remove()legacy_profile = state.root() / "sessions" / (name + "-cloak")- if legacy_profile.exists():+ if state.owned_path(legacy_profile) and legacy_profile.exists():_remove(legacy_profile)if ch.session:clear_session(ch.session)@@ -325,13 +337,11 @@ def remove(name: str) -> dict:for key in ch.logout_keys:if cfg.get(key):cfg.delete(key)- cookies, browser_deleted, warnings = 0, False, []- if _uses_browser(ch):- try:- cookies = browser.clear_site(site_domains(ch))- except ReachError as err:- warnings.append(err.message)def forget(saved):+ saved["channels"].pop(name, None)+ saved["checks"].pop(name, None)+ if ch.level == "default" and name not in saved["removed_defaults"]:+ saved["removed_defaults"].append(name)for key in ("reuse_sources", "setup_failures", "backend_health", "cooldowns"):saved.get(key, {}).pop(name, None)for key in ("pending", "ask_pending"):@@ -340,8 +350,8 @@ def remove(name: str) -> dict:saved[key].pop(ident, None)saved.setdefault("session_revisions", {})[name] = state.now()state.mutate(forget)- return {"channel": name, "removed": was_added, "removed_tools": _prune(data),- "cleared_cookies": cookies, "browser_deleted": browser_deleted, "warnings": warnings}+ return {"channel": name, "removed": True, "removed_tools": _prune(state.load()),+ "cleared_cookies": cookies, "browser_deleted": False, "warnings": []}# ── skill (the agent-facing instructions) ──@@ -451,7 +461,8 @@ def _remove(path: Path) -> None:def _write_real_copy(text: str) -> Path:real = skill_dir()- _remove(real) # old instructions are replaced, not merged+ if (real / "SKILL.md").exists() and not _is_our_copy(real):+ raise ReachError(BAD_INPUT, "A different skill already occupies the Reach instruction path; left untouched")_write_copy(real, text)return real@@ -459,13 +470,19 @@ def _write_real_copy(text: str) -> Path:def _write_copy(target: Path, text: str) -> None:from importlib.resources import files- target.mkdir(parents=True)- (target / "SKILL.md").write_text(text, encoding="utf-8")+ from agent_reach.utils.paths import atomic_write_private_text, ensure_no_symlink_path+ ensure_no_symlink_path(target, "skill directory")+ target.mkdir(parents=True, exist_ok=True)+ atomic_write_private_text(target / "SKILL.md", text)+ written = [str(target / "SKILL.md")]references = target / "references"+ ensure_no_symlink_path(references, "skill references")references.mkdir(exist_ok=True)for source in files("agent_reach").joinpath("skill").joinpath("references").iterdir():if source.is_file() and source.name.endswith(".md"):- (references / source.name).write_text(source.read_text("utf-8"), encoding="utf-8")+ atomic_write_private_text(references / source.name, source.read_text("utf-8"))+ written.append(str(references / source.name))+ state.mutate(lambda data: data["skill"].setdefault("files", {}).update({str(target): written}))def _link_into(skills_dir: Path, text: str) -> tuple:@@ -482,7 +499,8 @@ def _link_into(skills_dir: Path, text: str) -> tuple:if target.exists():if not _is_our_copy(target):return None, "a different skill named agent-reach is already there"- shutil.rmtree(target)+ _write_copy(target, text)+ return "copy", Noneskills_dir.mkdir(parents=True, exist_ok=True)try:target.symlink_to(skill_dir(), target_is_directory=True)@@ -493,17 +511,6 @@ def _link_into(skills_dir: Path, text: str) -> tuple:return "copy", None-def _remove_native_old_copies() -> List[str]:- """Our old real copies in folders of AIs that now read ~/.agents/skills (so they don't see two)."""- removed = []- for _, skills in native_agents().values():- target = skills / SKILL_NAME- if _is_our_copy(target):- shutil.rmtree(target)- removed.append(str(target))- return removed--def _agent_for(skills_dir: Path) -> str:return next((name for name, (_, d) in linked_agents().items() if d == skills_dir), "custom")@@ -529,9 +536,8 @@ def place_skill() -> dict:links.append({"agent": agent, "path": str(target), "kind": kind})else:not_linked.append({"agent": agent, "path": str(target), "reason": reason})- data["skill"]["links"] = links- state.save(data)- return {**skill_status(), "not_linked": not_linked, "removed_old_copies": _remove_native_old_copies()}+ state.mutate(lambda saved: saved["skill"].update(links=links))+ return {**skill_status(), "not_linked": not_linked, "removed_old_copies": []}def skill_status() -> dict:@@ -575,20 +581,21 @@ def link_skill(skills_dir: str) -> dict:def _skill_uninstall_targets() -> List[Path]:- """Real copy, recorded links/copies, and our links/old copies in every known skills folder."""- found: List[Path] = []- for rec in state.load()["skill"]["links"]:- p = Path(rec["path"])- if _links_to_real(p) or _is_our_copy(p):- found.append(p)- known = [skills for _, skills in linked_agents().values()] + [skills for _, skills in native_agents().values()]- for skills in known:- p = skills / SKILL_NAME- if _links_to_real(p) or _is_our_copy(p):- found.append(p)- real = skill_dir()- if real.exists() or real.is_symlink():- found.append(real)+ """Only recorded files and still-matching shortcuts; preserve user additions."""+ data = state.load()["skill"]+ found = []+ for rec in data["links"]:+ path = Path(rec["path"])+ if rec["kind"] == "link" and _links_to_real(path):+ found.append(path)+ for folder, files in data.get("files", {}).items():+ base = Path(folder)+ if base.is_symlink():+ continue+ for name in files:+ path = Path(name)+ if path.is_relative_to(base) and not any(p.is_symlink() for p in path.parents if p != base.parent):+ found.append(path)return list(dict.fromkeys(found))@@ -613,7 +620,7 @@ def migrate() -> dict:"migrated": True,"kept": "~/.agent-reach/config.yaml (keys and cookies unchanged)","suggested_channels": sorted(set(hints) - defaults),- "note": "Your own global tools were not removed. Old logins can be copied with `agent-reach login <channel> --import-existing`.",+ "note": "Your own global tools were not removed. Browser login must be completed by the user in the Reach dedicated window.",}@@ -628,7 +635,7 @@ def setup() -> dict:migration = migrate() if not state.exists() and (state.root() / "config.yaml").exists() else Noneif not state.exists():state.save(state.load())- _cleanup_retired_mcp()+ user_actions = _retired_mcp_notice()if state.load()["tools"].get("mcporter", {}).get("owner") == tools.OURS:tools.remove_private("mcporter") # retired LinkedIn MCP transport, only our private copystate.mutate(lambda saved: (saved.pop("reuse_sources", None), saved.pop("ask_pending", None)))@@ -649,6 +656,7 @@ def setup() -> dict:current = [{"channel": c.name, **channel_status(c, state.load())} for c in registered]result = {"version": __version__,+ "user_actions": user_actions,"default_channels": added,"skill": skill,"optional_channels": optional,@@ -662,6 +670,7 @@ def setup() -> dict:markdown = installation_report(result)report = {"markdown": markdown, "path": None}try:+ state.remember_path(state.root() / "installation-report.md", "installation receipt")report["path"] = str(atomic_write_private_text(state.root() / "installation-report.md", markdown))except (OSError, PrivatePathError):# The receipt remains in stdout even if its local copy cannot be saved.@@ -670,29 +679,11 @@ def setup() -> dict:return result-def _cleanup_retired_mcp() -> None:- """Remove only the unchanged Cursor entry recorded as ours by an older build."""- from agent_reach.utils.paths import (- PrivatePathError,- atomic_write_private_text,- read_small_text_no_follow,- )- old = state.load().get("mcp", {}).get("cursor", {})- path = home_dir() / ".cursor" / "mcp.json"- if old.get("path") != str(path) or not path.is_file():- return- try:- data = json.loads(read_small_text_no_follow(path, max_bytes=1024 * 1024) or "{}")- if not isinstance(data, dict):- return- servers = data.get("mcpServers", {})- if not isinstance(servers, dict) or servers.get("agent-reach") != old.get("entry"):- return- servers.pop("agent-reach")- atomic_write_private_text(path, json.dumps(data, ensure_ascii=False, indent=2))- except (OSError, ValueError, PrivatePathError):- return # Preserve an unreadable or externally changed config.- state.mutate(lambda saved: saved.pop("mcp", None))+def _retired_mcp_notice() -> list:+ """Read the old ledger only; never edit another application's configuration."""+ if state.load().get("mcp"):+ return ["An older Reach build registered an MCP server. Remove the agent-reach entry in your AI application's MCP settings; Reach no longer edits those settings."]+ return []# ── update ──@@ -838,24 +829,38 @@ def update(check_only: bool = False) -> dict:# ── uninstall ──-_OWNED = ("config.yaml", "state.json", "mcporter.json", "sessions", "browser", "cloak-binaries",- "update-check.json", "update-check.started")-def uninstall(dry_run: bool = False) -> dict:from . import browserroot = state.root()targets = _skill_uninstall_targets() # before state.json goes: it records the links- targets += [root / n for n in _OWNED]- targets += [tools.tool_dir(n) for n in tools.TOOLS] + [tools.npm_global_dir(), root / "tools" / "xiaoyuzhou"]+ data = state.load()+ for name in data.get("owned_paths", {}):+ path = root / name+ if name and ".." not in Path(name).parts and path.is_relative_to(root) and not Path(name).is_absolute():+ targets.append(path)+ targets += [tools.tool_dir(n) for n, entry in data["tools"].items()+ if entry.get("owner") == tools.OURS and entry.get("scope") == "private"+ and tools._SAFE_NAME.fullmatch(n)]targets = [t for t in targets if t.exists() or t.is_symlink()]globals_ = tools.uninstall_global_owned(dry_run=True)if not dry_run:- browser.stop()+ if state.owned_path(browser.browser_root()) or browser._load_state().get("backend"):+ if not browser.stop():+ raise ReachError(UPSTREAM_BROKEN, "The dedicated browser could not close; uninstall stopped before deleting its files")tools.uninstall_global_owned(dry_run=False)- for t in targets:+ # Children first; directory entries do not authorize deleting unrecorded siblings.+ for t in sorted(set(targets), key=lambda p: len(p.parts), reverse=True):+ from agent_reach.utils.paths import ensure_no_symlink_path+ ensure_no_symlink_path(t.parent, "uninstall parent")_remove(t)+ for folder in data.get("skill", {}).get("files", {}):+ for directory in (Path(folder) / "references", Path(folder)):+ try:+ directory.rmdir()+ except OSError:+ passfor d in (root / "tools", root):try:d.rmdir()diff --git a/agent_reach/runtime/onboarding.py b/agent_reach/runtime/onboarding.pyindex 9f45d9ac..8ac3989c 100644--- a/agent_reach/runtime/onboarding.py+++ b/agent_reach/runtime/onboarding.py@@ -4,7 +4,6 @@ import urllib.requestfrom datetime import datetimefrom urllib.parse import urlsplit-from agent_reach.config import Configfrom agent_reach.utils.url import host_matchesfrom .result import BAD_INPUT, ReachError@@ -215,19 +214,3 @@ def require_boss_cdp():browser.open_url('https://www.zhipin.com/web/geek/jobs')browser.touch()return browser.CDP_URL-----def profiles():- from .browser import connected_contexts- from .result import ReachError- from .tools import resolve- if not resolve('opencli'):- return {'profiles': [], 'discovery_error': 'OpenCLI is not installed'}- try:- contexts = connected_contexts()- except ReachError as exc:- return {'profiles': [], 'discovery_error': exc.message}- labels = Config(read_only=True).get('browser_labels', {})- return {'profiles': [{'id': c, 'label': labels.get(c, c), 'connected': True} for c in contexts]}diff --git a/agent_reach/runtime/sessions.py b/agent_reach/runtime/sessions.pyindex 3df4fc2c..e8ad7037 100644--- a/agent_reach/runtime/sessions.py+++ b/agent_reach/runtime/sessions.py@@ -20,7 +20,14 @@ def sessions_root() -> Path:def session_dir(tool: str) -> Path:"""The tool's private home directory (created on first use)."""- return make_private_dir(sessions_root() / tool)+ from . import state+ path = sessions_root() / tool+ if path.exists() and not state.owned_path(path) and state.load()["tools"].get(tool, {}).get("owner") != "agent-reach":+ from .result import NEED_SETUP, ReachError+ raise ReachError(NEED_SETUP, "Unrecorded files occupy the native session directory; left untouched")+ path = make_private_dir(path)+ state.remember_path(path, "native session")+ return pathdef session_env(tool: str) -> dict:@@ -38,7 +45,8 @@ def has_login_state(tool: str) -> bool: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():+ from . import state+ if not state.owned_path(root) or not root.exists():return Falseensure_no_symlink_path(root, "登录目录")shutil.rmtree(root)diff --git a/agent_reach/runtime/state.py b/agent_reach/runtime/state.pyindex 2d01dd05..244383f0 100644--- a/agent_reach/runtime/state.py+++ b/agent_reach/runtime/state.py@@ -63,6 +63,10 @@ def load() -> dict:def save(data: dict) -> None:+ data.setdefault("owned_paths", {})["state.json"] = "state ledger"+ import hashlib+ name = hashlib.sha256(b"reach-state-write").hexdigest() + ".lock"+ data["owned_paths"]["browser-locks/" + name] = "state lock"make_private_dir(root())atomic_write_private_text(state_path(), json.dumps(data, indent=2, ensure_ascii=False))@@ -96,3 +100,24 @@ def age_seconds(iso: str) -> float:except (TypeError, ValueError):return float("inf")return (_dt.datetime.now(_dt.timezone.utc) - then).total_seconds()+++def owned_path(path: Path, data: dict | None = None) -> bool:+ """Deletion permission comes from the ledger, never a familiar filename."""+ try:+ relative = Path(path).absolute().relative_to(root().absolute()).as_posix()+ except ValueError:+ return False+ return relative in (data if data is not None else load()).get("owned_paths", {})+++def remember_path(path: Path, purpose: str) -> None:+ from agent_reach.utils.paths import ensure_no_symlink_path++ ensure_no_symlink_path(path, "owned path")+ relative = Path(path).absolute().relative_to(root().absolute()).as_posix()+ if relative in {".", ""} or ".." in Path(relative).parts:+ raise ValueError("Cannot own the entire Reach root")+ if owned_path(path):+ return+ mutate(lambda data: data.setdefault("owned_paths", {}).update({relative: purpose}))diff --git a/agent_reach/runtime/tools.py b/agent_reach/runtime/tools.pyindex d621315f..1ecc956d 100644--- a/agent_reach/runtime/tools.py+++ b/agent_reach/runtime/tools.py@@ -254,6 +254,11 @@ def install_env() -> dict:"""extend_path()env = dict(os.environ)+ cache = state.root() / "cache"+ cache.mkdir(parents=True, exist_ok=True)+ state.remember_path(cache, "download caches")+ env.update(PIP_CACHE_DIR=str(cache / "pip"), UV_CACHE_DIR=str(cache / "uv"),+ npm_config_cache=str(cache / "npm"), XDG_CACHE_HOME=str(cache))https = env.get("HTTPS_PROXY") or env.get("https_proxy")http = env.get("HTTP_PROXY") or env.get("http_proxy")all_proxy = env.get("ALL_PROXY") or env.get("all_proxy")@@ -368,7 +373,7 @@ def _install_node(tool: Tool) -> None:import zipfileos_name, arch, ext = _node_platform()- with tempfile.TemporaryDirectory(prefix="agent-reach-node-") as tmp:+ with tempfile.TemporaryDirectory(prefix="node-", dir=_work_dir()) as tmp:index = Path(tmp) / "index.json"_download("https://nodejs.org/dist/index.json", index)key = {"darwin": f"osx-{arch}-tar", "linux": f"linux-{arch}", "win": f"win-{arch}-zip"}[os_name]@@ -410,7 +415,7 @@ def _install_uv(tool: Tool) -> None:if _WIN:_run(["powershell", "-ExecutionPolicy", "ByPass", "-c", "irm https://astral.sh/uv/install.ps1 | iex"], env=env)else:- with tempfile.TemporaryDirectory(prefix="agent-reach-uv-") as tmp:+ with tempfile.TemporaryDirectory(prefix="uv-", dir=_work_dir()) as tmp:script = Path(tmp) / "install.sh"_download("https://astral.sh/uv/install.sh", script)_run(["sh", str(script)], env=env)@@ -423,8 +428,19 @@ def _install_uv(tool: Tool) -> None:raise ReachError(UPSTREAM_BROKEN, "the uv installer finished but uvx is missing")+def _work_dir() -> Path:+ folder = state.root() / "tmp"+ folder.mkdir(parents=True, exist_ok=True)+ state.remember_path(folder, "installer temporary files")+ return folder++def _install(tool: Tool, *, global_: bool = False) -> None:"""Install (or upgrade) one tool. Singletons: global_=True (our npm -g prefix)."""+ folder = npm_global_dir() if global_ else tool_dir(tool.name)+ if folder.exists() and not state.owned_path(folder) and state.load()["tools"].get(tool.name, {}).get("owner") != OURS:+ raise ReachError(NEED_SETUP, f"Unrecorded files occupy the {tool.name} install directory; left untouched")+ state.remember_path(folder, "installed dependency")if tool.kind in ("pip", "ffmpeg"):_install_pip(tool)elif tool.kind == "npm":@@ -484,7 +500,7 @@ def ensure(name: str, *, allow_upgrade: bool = False, upgrade: bool = False) ->if entry.get("version") != current:return record(name, current, **{k: v for k, v in entry.items() if k != "version"})return {"tool": name, **entry}- if ours:+ if ours and (upgrade or allow_upgrade):if entry.get("prefix"):_install(tool, global_=True)else:@@ -507,9 +523,12 @@ def ensure(name: str, *, allow_upgrade: bool = False, upgrade: bool = False) ->if private_ok and tool.name == "boss-agent-cli":venv = tool_dir(tool.name) / "venv"sources = list(venv.glob("**/boss_agent_cli-*.dist-info/direct_url.json"))- expected = tool.package.rsplit("@", 1)[-1]+ expected = tool.package.split(" @ ", 1)[-1].strip()try:- pinned_mismatch = not sources or json.loads(sources[0].read_text()).get("vcs_info", {}).get("commit_id") != expected+ source = json.loads(sources[0].read_text()) if sources else {}+ commit = expected.rsplit("/", 1)[-1].removesuffix(".zip")+ pinned_mismatch = not (source.get("url") == expected or+ source.get("vcs_info", {}).get("commit_id") == commit)except (OSError, ValueError):pinned_mismatch = Trueif not private_ok or not ours or upgrade or pinned_mismatch:@@ -552,10 +571,12 @@ def remove_private(name: str) -> bool:data["tools"].pop(name, None)state.save(data)return entry.get("owner") == OURS- if entry is not None and entry.get("owner") not in (None, OURS):+ if not entry or entry.get("owner") != OURS:return Falseremoved = data["tools"].pop(name, None) is not None- if _SAFE_NAME.match(name) and tool_dir(name).exists():+ if _SAFE_NAME.fullmatch(name) and tool_dir(name).exists():+ from agent_reach.utils.paths import ensure_no_symlink_path+ ensure_no_symlink_path(tool_dir(name), "private tool")shutil.rmtree(tool_dir(name))removed = Truestate.save(data)diff --git a/agent_reach/runtime/update_notice.py b/agent_reach/runtime/update_notice.pyindex 3311d5b5..039299d7 100644--- a/agent_reach/runtime/update_notice.py+++ b/agent_reach/runtime/update_notice.py@@ -1,20 +1,8 @@-"""Background "new version" notice.--Commands never wait on the network. At most once per 24 h a command starts a-short detached process (`python -m agent_reach.runtime.update_notice`) that-reads the latest GitHub release (10 s timeout) and writes-~/.agent-reach/update-check.json {checked_at, latest, notes}. No network = no-file change, silently. `notice()` reads that cache only: it returns-{current, latest, notes} when the cached latest is newer than this version.-"""+"""Version notices from an explicit update --check only; no background process."""from __future__ import annotationsimport json-import os-import subprocess-import sys-import timeimport urllib.requestfrom pathlib import Pathfrom typing import Optional@@ -30,22 +18,14 @@ from agent_reach.utils.paths import (from . import stateREPO = "Panniantong/Agent-Reach"-INTERVAL = 24 * 3600FETCH_TIMEOUT = 10.0NOTES_MAX = 2000-#: Set to any value to never start the background check (tests, CI).-DISABLE_ENV = "AGENT_REACH_NO_UPDATE_CHECK"def cache_path() -> Path:return state.root() / "update-check.json"-def started_path() -> Path:- """Touched when a background check starts: limits starts to one per INTERVAL, online or not."""- return state.root() / "update-check.started"--def version_tuple(v: str) -> tuple:try:return tuple(int(x) for x in str(v).strip().lstrip("v").split("."))@@ -64,6 +44,7 @@ def fetch_latest(timeout: float = FETCH_TIMEOUT) -> dict:def write_cache(info: dict) -> None:make_private_dir(state.root())+ state.remember_path(cache_path(), "explicit update check")atomic_write_private_text(cache_path(), json.dumps({"checked_at": state.now(), "latest": info["latest"], "notes": info["notes"]}, ensure_ascii=False))@@ -86,40 +67,3 @@ def notice() -> Optional[dict]:if not current or version_tuple(latest) <= current:return Nonereturn {"current": __version__, "latest": latest, "notes": str(data.get("notes") or "")}---def _due() -> bool:- try:- return time.time() - started_path().stat().st_mtime >= INTERVAL- except OSError:- return True---def maybe_refresh() -> None:- """Start the detached background check if the last one began over 24 h ago. Never blocks or raises."""- if os.environ.get(DISABLE_ENV) or not _due():- return- try:- make_private_dir(state.root())- started_path().touch()- kwargs: dict = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL,- "close_fds": True, "cwd": str(state.root())}- if sys.platform == "win32":- kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP- else:- kwargs["start_new_session"] = True- subprocess.Popen([sys.executable, "-m", "agent_reach.runtime.update_notice"], **kwargs)- except (OSError, PrivatePathError):- pass---def _main() -> int:- try:- write_cache(fetch_latest())- except Exception: # noqa: BLE001 - offline or GitHub down: stay silent- return 1- return 0---if __name__ == "__main__":- sys.exit(_main())diff --git a/agent_reach/skill/SKILL.md b/agent_reach/skill/SKILL.mdindex 235b24b6..fd5311ad 100644--- a/agent_reach/skill/SKILL.md+++ b/agent_reach/skill/SKILL.md@@ -34,17 +34,17 @@ metadata:1. **公开信息**:有链接先用已有网页工具打开;找内容先用已有搜索工具,按需加 `site:平台域名`。正文、评论、字幕分别检查是否已满足请求。已有结果足够就直接回答,不准备渠道或登录。2. **补充能力**:公开结果缺少用户需要的部分、现有工具不可用,或用户要求 Reach 已声明的结构化/站内动作时,再查 `agent-reach channels`,调用对应动作。已有免登录原生工具或公开接口可直接复用;不要求每个任务先重复做一次网页搜索。网页工具不可用时,Reach `web search` / `web read` 提供匿名保底。-3. **按需认证**:仅当尚未满足的任务所选路径确实要求登录时,再加载 [会话配置](references/sessions.md),复用已授权会话或请用户本人登录。没有配置浏览器说明需要配置;403、验证码、DNS/TLS 错误、限流、超时按各自原因处理。正文旁的登录按钮不算登录墙。+3. **按需认证**:仅当尚未满足的任务所选路径确实要求登录时,再加载 [会话配置](references/sessions.md),复用专用浏览器已保存的会话或请用户本人登录。没有配置浏览器说明需要配置;403、验证码、DNS/TLS 错误、限流、超时按各自原因处理。正文旁的登录按钮不算登录墙。4. **交付已有结果**:保留公开结果,说明缺少正文、哪些评论或字幕;登录仅服务于剩余缺口。用户跳过登录也能拿到已读取的内容。评论计数、字幕轨道清单、页面壳、搜索摘要分别标注,不当成评论正文、字幕正文或完整文章。-平台名称和 URL 用来识别来源,不自动触发安装、`ensure` 或登录。用户要求安装、登录、导入或退出时读会话配置;故障、升级或卸载时读 [维护说明](references/maintenance.md),查询时按需加载。+平台名称和 URL 用来识别来源,不自动触发安装、`ensure` 或登录。用户要求安装、登录或退出时读会话配置;故障、升级或卸载时读 [维护说明](references/maintenance.md),查询时按需加载。Reddit 公开帖可搜索 `site:reddit.com 关键词` 再打开原帖,公开 JSON 有时包含评论父子 ID;以本次实际返回为准。YouTube/B站简介与字幕、视频内容分别验收;X 的单帖公开内容与评论流分别验收。某台机器的失败不能推广为平台必须登录,也不固化“某平台总能匿名读全”。网络路径不同的结果分别记录。```bashagent-reach channels # 每个渠道有哪些动作、要什么参数(不确定就先跑这个)-agent-reach ensure <渠道> # 安装、复用授权会话并实测+agent-reach ensure <渠道> # 安装、复用专用会话并实测agent-reach <渠道> <动作> [参数] # 例:agent-reach xiaohongshu search "咖啡" --limit 5agent-reach read <链接> # 给链接,自动认出渠道```@@ -67,7 +67,7 @@ agent-reach read <链接> # 给链接,自动认出渠道2. 实际调用 Reach 渠道前说一句"用 agent-reach 的 X 渠道"。3. 多平台调研按会话分组;共用浏览器的命令串行,独立会话可以并行。4. 只做读取。发帖、评论、点赞一律不做。-5. 禁止隐式提取登录态。用户明确授权后,只导入指定站点的登录态;不得输出 Cookie、Token 或凭据。已有授权无需反复询问。+5. 不读取或导入个人浏览器登录。需要认证时,只在 Reach 专用窗口由用户本人登录;不得输出 Cookie、Token 或凭据。## 渠道@@ -81,7 +81,7 @@ agent-reach read <链接> # 给链接,自动认出渠道-`setup` 安装默认渠道;`add` 为浏览器渠道自动准备共用浏览器和插件。`login <渠道>` 打开该网站,由用户登录。已有会话先复用;导入只授权一次,不保存长期读取个人浏览器的权限。业务访问需要实际验证。+`setup` 安装默认渠道;`add` 为浏览器渠道自动准备共用浏览器和插件。`login <渠道>` 打开该网站,由用户登录。先复用专用浏览器已保存的会话;程序定期保存登录,无需关窗。业务访问需要实际验证。小红书 read 仅返回文字描述,不声称理解图片/视频。BOSS 搜索若 salary_encoded=true,不能猜数字;read 职位链接获取详情中的可读薪资。@@ -122,6 +122,8 @@ agent-reach read <链接> # 给链接,自动认出渠道需要 Reach 时可直接运行 `agent-reach execute CHANNEL ACTION --params '{...}'`,程序准备依赖并执行真实动作,无需先额外搜索一次。`ensure CHANNEL` 留给安装验收和排障;需要本人登录会返回明确提示。`execute` 返回 `operation_id` 时,在用户完成后运行 `agent-reach resume OPERATION_ID`。本版没有 ask 或 Reach MCP 服务,无需模型 API Key。-默认复用专用浏览器已保存的会话。用户授权导入某站登录后,使用 `agent-reach browser import CHANNEL --opencli-profile ID` 或 `--state-file FILE`;只做一次该站导入,不保存长期读取个人 Chrome 的授权。导入成功后仍需实测,不把 Cookie 存在视为已登录。详细步骤见 [sessions.md](references/sessions.md)。+只复用专用浏览器已保存的登录,不读取或导入个人 Chrome 的登录。定期保存会话;真实页面操作和 Reach 调用重置十分钟计时。OpenCLI Bridge 随浏览器启动和回收;已有用户进程保留,版本冲突交由用户处理。详细步骤见 [sessions.md](references/sessions.md)。`agent-reach add CHANNEL` 会准备渠道所需依赖、专用浏览器和插件;`remove CHANNEL` 清除该网站的登录和存储,保留其他网站。小宇宙保留为可选转录渠道,需要 Groq Key。++安装、升级和清理只处理台账记录的 Reach 文件。普通查询不升级依赖、不启动更新检查、不写其他软件配置。渠道需完成真实查询验收才能发布;doctor 和单元测试不代替验收。diff --git a/agent_reach/skill/SKILL_en.md b/agent_reach/skill/SKILL_en.mdindex de4c9657..dc683fbf 100644--- a/agent_reach/skill/SKILL_en.md+++ b/agent_reach/skill/SKILL_en.md@@ -38,7 +38,7 @@ Route by the evidence needed, on every platform:3. Load [Sessions](references/sessions.md) only when the remaining task's chosen path actually requires authentication or session setup. Reuse authorized sessions before requesting login. Missing browser setup, 403, challenges, DNS/TLS failures, rate limits and timeouts need their own diagnosis. A login button beside readable content is not a login wall.4. Keep public evidence and deliver it even if login is skipped. Identify the remaining gap. Counts, subtitle track lists, page shells and search snippets do not establish comment text, subtitle text or complete bodies.-A platform name or URL identifies a source; it does not automatically trigger installation, ensure or login. Read Sessions for explicit setup/login/import/logout requests and [Maintenance](references/maintenance.md) for failures/updates/uninstall.+A platform name or URL identifies a source; it does not automatically trigger installation, ensure or login. Read Sessions for explicit setup/login/logout requests and [Maintenance](references/maintenance.md) for failures/updates/uninstall.Public Reddit JSON may expose parent IDs; verify actual coverage. YouTube/Bilibili descriptions, subtitles and video content are separate evidence. Public X posts and reply streams are separate capabilities. Do not generalize a local failure into a platform-wide login requirement, or promise universal anonymous access. Distinguish local HTTP, proxy and built-in web-tool results.@@ -69,7 +69,7 @@ Results:2. Say "using agent-reach channel X" before calling a Reach channel.3. Serialize commands sharing one browser profile; independent sessions may run in parallel.4. Read only. Never post, comment, or like.-5. Never extract login state implicitly. Explicit authorization permits importing only the selected site's state. Never output cookies, tokens or credentials. Do not ask again for existing authorization.+5. Never read or import personal-browser authentication. The user logs in only in the Reach browser. Never output credentials.## Channels@@ -82,7 +82,7 @@ The login column lists authentication entry points, not prerequisites for public## Reuse before login-`setup` installs defaults; adding a browser channel prepares the shared browser and extension. `login CHANNEL` opens the site for the user to log in. Imports are one-time and explicitly authorized; verify the requested action after import.+`setup` installs defaults; adding a browser channel prepares the shared browser and extension. `login CHANNEL` opens the site for the user to log in. Reuse saved dedicated sessions and verify the requested action. Never import personal-browser login.XHS read returns text descriptions, not image/video understanding. Never guess BOSS salary digits when salary_encoded=true; read the job detail instead.@@ -121,6 +121,6 @@ All browser channels use `~/.agent-reach/browser/profile`. CloakBrowser is prefeUse `agent-reach execute CHANNEL ACTION --params '{...}'` to prepare and perform the real action once. Reserve `ensure CHANNEL` for setup checks and diagnosis. After the user completes a requested login, use `agent-reach resume OPERATION_ID` when an operation ID was returned. There is no Reach MCP server or model planner in this version, and no model API key is required.-Reuse the dedicated browser's saved login first. Explicit one-time site imports use `agent-reach browser import CHANNEL --opencli-profile ID` or `--state-file FILE`; they do not grant continuing access to personal Chrome. Verify the requested action after import. See [Sessions](references/sessions.md).+Reuse only the dedicated browser’s saved login. Never read or import personal-browser authentication. The user logs in in the Reach window; sessions are saved periodically. Human page input and Reach calls reset the idle timer. The official Bridge is supervised alongside the browser; existing user processes are preserved. See [Sessions](references/sessions.md).`add CHANNEL` prepares dependencies, browser and extension. `remove CHANNEL` clears only that site's login/storage, preserving other sites. Xiaoyuzhou remains an optional transcription channel requiring a Groq key.diff --git a/agent_reach/skill/references/capabilities.md b/agent_reach/skill/references/capabilities.mdindex b68ef598..4e87eb24 100644--- a/agent_reach/skill/references/capabilities.md+++ b/agent_reach/skill/references/capabilities.md@@ -6,7 +6,7 @@ Use only when evidence depth needs clarification. Declared actions and local acc## 三层说明- **公开可尝试**:Agent 已有网页工具、原生工具或公开接口可能已满足任务;不要求安装浏览器、登录。按实际取得的证据回答。-- **Reach 补充**:当前发布版声明的动作,见 `agent-reach channels`。需要配置时先复用授权会话,所选路径实际要求登录时才本人登录。+- **Reach 补充**:当前发布版声明的动作,见 `agent-reach channels`。需要配置时先复用专用浏览器已保存的会话,所选路径实际要求登录时才本人登录。- **本机已验证**:只列本机最近成功验收的具体动作;安装、保存会话和网络可达均不等于业务验收。## 本版渠道(包含小宇宙)diff --git a/agent_reach/skill/references/sessions.md b/agent_reach/skill/references/sessions.mdindex 03627b4a..46335909 100644--- a/agent_reach/skill/references/sessions.md+++ b/agent_reach/skill/references/sessions.md@@ -11,24 +11,16 @@3. 只有实际返回 NEED_LOGIN 才请用户登录;`agent-reach login CHANNEL` 打开专用浏览器,登录由用户本人完成。BOSS 等原生工具按返回提示执行 `login CHANNEL --sync`。4. 若返回 operation_id,用户完成后使用 `agent-reach resume OPERATION_ID`。保存的是任务参数,不会为等待登录另起常驻任务服务。-## 一次性继承登录+## 保存与复用-专用浏览器已有登录优先复用。用户明确同意导入指定网站后:+只复用 Reach 专用浏览器中已保存的登录。程序不读取个人 Chrome 的 Cookie、登录文件或账号,也不提供导入入口。首次需要登录时,由用户在专用窗口完成。-```bash-agent-reach browser profiles-agent-reach browser import xiaohongshu --opencli-profile SOURCE_ID-# 或者只读用户指定的本地登录文件:-agent-reach browser import xiaohongshu --state-file /absolute/path/session.json-agent-reach check xiaohongshu --search --text-```+登录期间会定期保存会话,无需关窗才能保存。鼠标点击、键盘和滚动等真实页面操作以及 Reach 调用会重置十分钟计时;没有操作时自动关闭,下次查询自动重开。网站要求扫码、验证码或确认时交给用户,失败不反复开窗。-来源是用户选定的已连接 OpenCLI profile;不读取 Chrome Cookie 数据库,不导出其他网站,不输出 Cookie/Token。导入只复制该站 Cookie,无法保证所有平台都接受新环境,需要实际查询确认。没有长期自动导入授权。原浏览器和原文件保持不变。--旧版 Reach 自有会话会从 `sessions/CHANNEL-cloak/profile/reach-session.json` 一次性合并到共用配置,只补缺失 Cookie,保留已有的新登录。来源属于 Reach 自己;个人 Chrome 仍需明确授权导入。+OpenCLI Bridge 随专用浏览器由计时程序启动、回收。已有的兼容 Bridge 可复用,Reach 不关闭用户启动的进程;若另一个浏览器正在使用 Reach 启动的桥,保留并在状态中说明。版本冲突时提示用户处理,不自动重启别人的服务。CloakBrowser 下载失败后会记住 Chrome 回退,避免每次查询重新下载。修好网络后可用 `agent-reach browser setup --retry-cloak` 重试。## 退出和删除-`agent-reach logout CHANNEL` 清除专用浏览器中该站登录和渠道自有状态。`remove CHANNEL` 还清理该渠道授权与待完成任务,保留其他网站登录。退出不修改来源 Chrome。限流或验证码时停止,不换账号或浏览器反复尝试。+`agent-reach logout CHANNEL` 清除专用浏览器中该站登录和渠道自有状态。`remove CHANNEL` 还清理该渠道授权与待完成任务,保留其他网站登录。清理失败保留渠道记录,用户可重试清理。限流或验证码时停止,不换账号或浏览器反复尝试。diff --git a/docs/cloakbrowser.md b/docs/cloakbrowser.mdindex 1968c5d4..16f7056a 100644--- a/docs/cloakbrowser.md+++ b/docs/cloakbrowser.md@@ -4,7 +4,7 @@ CloakBrowser supplies the browser, and OpenCLI/boss-agent-cli supply website ext`add` prepares Node, OpenCLI, the browser and extension. CloakBrowser runs through its public persistent-context launcher in a private tool environment. Its binaries are cached under `~/.agent-reach/cloak-binaries`; installation/download failure falls back to installed Chrome. The next browser action automatically prepares/reopens the same profile. BOSS uses this browser's CDP endpoint. On Windows the Cloak extension is loaded automatically; a system-Chrome fallback may need Web Store installation.-Cookie inheritance is explicit and site-scoped via `browser import CHANNEL --opencli-profile ID` or `--state-file FILE`. It is a one-time operation. No Chrome cookie database is read, no standing source grant is retained, and import is not authentication acceptance. `remove` clears the selected site's cookies/storage and native session, retaining other sites and the source browser.+Only the shared dedicated profile is reused. Personal-browser authentication import is unavailable. Human login is periodically saved; trusted page input and Reach calls reset idle closure. The official OpenCLI Bridge is supervised with the dedicated browser. Existing user-owned bridges are preserved; version conflicts require user action.Previous Reach-owned per-site snapshots are merged once without replacing newer shared cookies. Logout/removal clears the retired per-site state too. Chrome fallback is remembered; use `agent-reach browser setup --retry-cloak` after fixing the download connection.diff --git a/docs/install.md b/docs/install.mdindex db083835..38802a9b 100644--- a/docs/install.md+++ b/docs/install.md@@ -15,12 +15,26 @@ For the AI doing the install. Run every command yourself. Each `agent-reach` com## 1. Install and set up+**This branch is an unpublished 1.6.0 candidate.** The latest verified official release is v1.5.0 and does not include the candidate's browser/setup changes.++For the official stable version:++```bash+uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v1.5.0.zip+```++Continue with the [v1.5.0 installation instructions](https://github.com/Panniantong/Agent-Reach/blob/v1.5.0/docs/install.md). Stop here for a stable install; do not run this candidate's commands against 1.5.0.++For this candidate's local test package, use the supplied wheel:+```bash-uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v1.6.0.zip+uv tool install --force /path/to/agent_reach-1.6.0-py3-none-any.whlagent-reach setupagent-reach doctor --text```+Do not run the stable install command over a candidate. Once v1.6.0 has actually been released, the official URL can advance to that tag. Already-installed ordinary users run `agent-reach update` explicitly; local candidate users keep the candidate source until it is released.+`agent-reach setup --text` prints the same compact capability table directly. Plain `setup` preserves the JSON contract and saves `installation-report.md` under the private Reach directory.`agent-reach` not found after install? Run `uv tool update-shell` and open a new shell.@@ -43,10 +57,10 @@ Before selecting Reach for a platform mention, check whether existing public tooWhen the user asks for a channel, run `agent-reach add <channel>`. Browser channels install Node, OpenCLI, the dedicated browser and its extension automatically. One profile under `~/.agent-reach/browser/profile` is shared by all sites. CloakBrowser is preferred; download failure falls back to installed Chrome. The owned browser closes after 10 idle minutes and reopens on the next action. The Chrome fallback on Windows may need one Web Store click.-Reuse already-saved Reach sessions. To import a login from a connected source Chrome, obtain the user's explicit site-scoped authorization, list `agent-reach browser profiles`, then run `agent-reach browser import CHANNEL --opencli-profile ID`. This is a one-time copy, not a standing export permission. An explicitly supplied local session file is supported with `--state-file FILE`. Never inspect Chrome's cookie database, print credentials, or log in for the user. Cookie import does not prove access; verify the requested action.+Reuse only already-saved Reach dedicated sessions. Never read or import personal-browser cookies or login files. The user logs in in the Reach window. Login is periodically saved without requiring the user to close the window. Human page interactions and Reach calls reset the idle timer. The Bridge is supervised with the browser; existing user-owned Bridge processes are preserved, and version conflicts are reported without restarting them.If login is still needed, `agent-reach login CHANNEL` opens the shared dedicated browser. The user logs in there; for native tools, follow the returned sync instruction. `agent-reach execute CHANNEL ACTION --params '{...}'` prepares and executes the actual task once. If it returns `operation_id`, use `agent-reach resume OPERATION_ID` after the user finishes login. No additional model key is required.-Removing a browser channel clears only that site's login/storage in the dedicated browser and its native session. Other sites and the original source Chrome are retained. Xiaoyuzhou remains optional and needs a Groq key for transcription.+Removing a browser channel clears only that site's login/storage in the dedicated browser and its native session. Other sites are retained. If required cleanup fails, the channel remains registered and the error is returned. Xiaoyuzhou remains optional and needs a Groq key for transcription.Problems: [troubleshooting.md](troubleshooting.md).diff --git a/docs/plans/2026-10-20-release-policy-guards.md b/docs/plans/2026-10-20-release-policy-guards.mdnew file mode 100644index 00000000..b74a44dd--- /dev/null+++ b/docs/plans/2026-10-20-release-policy-guards.md@@ -0,0 +1,15 @@+# Dedicated browser and release policy implementation plan++**Goal:** Respect all eight user rules and fix the five reviewed defects, without claiming a release or a channel pass from unit tests.++**Architecture:** Keep one Reach-owned Cloak profile and watcher. Keep the verified official OpenCLI 1.8.7 Bridge path. The user approved Bridge supervision bound to the dedicated browser lifetime after official 2.0.1 CDP failed the new Xiaohongshu layout. Personal-browser login is never inspected. Browser login happens only in this profile. BOSS detail uses an existing upstream browser-backed action. Owned paths and failed cleanup remain visible in the local ledger.++**Tech stack:** Python standard library, existing CloakBrowser SDK, untouched OpenCLI and boss-agent-cli.++1. Reproduce the reviewed issues; record facts and limits. Work on a feature branch, never main. Keep unrelated local API/research files out of commits and packages.+2. Remove external cookie import/profile discovery and all writes to other programs' configuration. Keep dedicated saved sessions and explicit user login. Replace misleading login hints.+3. Verify OpenCLI direct CDP against the owned browser. Keep automatic prepare/reopen, record its compatibility result, and supervise the verified Bridge route without spawning CLI discovery or background update checks. The watcher observes real browser activity and explicit login time.+4. Fix BOSS ZIP provenance reuse. Route detail through an upstream browser adapter. Never modify upstream files or silently upgrade an existing dependency.+5. Make removal fail before deleting channel registration when site cleanup fails. Clear observed subdomain origins and validate the result; preserve other sites. Restrict deletion to recorded owned paths and skill files/links.+6. Separate the latest real official release install from unreleased candidate installation. Add an executable release gate requiring real per-action channel evidence; pending/blocked channels prevent release. No tag, merge or release this turn.+7. Run discriminating regressions, full tests, lint/types, and owned-browser live checks. Stop on verification/rate-limit errors. Build a sanitized candidate with an explicit pending-channel record, update the PR as draft, and report what passed and what did not.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 6991ae55..0a884c47 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -42,7 +42,7 @@ Some channel tools install at tested versions; others use a supported range. `ag## Reusing existing sessions-`login CHANNEL` inspects existing connections, without opening a browser. For OpenCLI use `browser profiles` and explicitly select `browser use ID`. Install/reconnect the extension in that same Chrome profile. A disconnected selection is never replaced automatically.+`login CHANNEL` opens the Reach dedicated window. The user logs in there. Personal Chrome sessions are never imported. `browser setup` prepares the dedicated extension and connection; an incompatible existing Bridge is left untouched and reported.Boss requires an existing CDP BOSS page. Select it with `browser bind boss http://127.0.0.1:PORT`. Only explicit `login boss --new-browser` may open its persistent dedicated profile. After the user confirms login and stability, run `login boss --sync`. Do not clear risk locks or switch profiles to retry a platform block.diff --git a/docs/update.md b/docs/update.mdindex b11addbe..b9519127 100644--- a/docs/update.md+++ b/docs/update.md@@ -50,7 +50,7 @@ agent-reach setup- old CLI logins (bilibili, boss) can be copied over instead of logging in again:```bash-agent-reach login <channel> --import-existing+agent-reach login <channel> # Browser channels: user logs in in the dedicated Reach window```Browser-login channels (xiaohongshu, reddit, twitter, ...) no longer use your own browser's cookies. Add them again with `agent-reach add <channel>` (it sets up the Agent Reach browser by itself), then log in there with `agent-reach login <channel>`.diff --git a/docs/validation/dedicated-policy-20261020.md b/docs/validation/dedicated-policy-20261020.mdnew file mode 100644index 00000000..7ff1b8d9--- /dev/null+++ b/docs/validation/dedicated-policy-20261020.md@@ -0,0 +1,61 @@+# Dedicated browser policy audit — 2026-10-20++Candidate only. PR #815 remains a draft against `release/1.6`. No merge, tag or official release. Package version remains 1.6.0. The earlier 63c272a claim of complete acceptance was too broad.++## Review findings and fixes++All five concrete code defects were confirmed. The changes below distinguish regression coverage from live business acceptance.++| Finding | Final change | Evidence |+|---|---|---|+| BOSS detail used native HTTP authentication | `boss read` now invokes the official OpenCLI `boss detail` browser adapter, pinned to the shared dedicated profile. Native BOSS helper handles browser search only. | Route/parameter regression passed. **Real JD acceptance still pending** after the earlier platform block; no repeated risk requests. |+| Removal reported success after login cleanup failed | Required browser cleanup runs before channel/task/tool deregistration. Failure propagates; the channel remains registered. | Failure injection passed; real synthetic site cleanup passed. |+| www/subdomain storage was missed | Capture open and previously visited origins, include www/cookie origins, clear selected site data and verify remaining cookies. | Regression passed; real local subdomain localStorage/cookie cleared, another site cookie retained. This does not claim discovery of every historical origin from older builds. |+| BOSS archive source caused repeated installation | Accept the installed archive URL or the exact expected VCS commit; repeated prepare reuses it. | Two ensure calls caused zero installs in provenance regression. |+| XHS error hint pointed to personal Chrome | Hint now opens Reach login; all personal-browser export/import commands and source flags removed. | Retired-source commands fail before credential/browser access. |++## Eight-rule implementation++- Work stayed on a feature branch. PR stays draft; release workflow now requires real per-action evidence for the exact source digest. Unit tests and doctor cannot satisfy the gate.+- No maintainer account, credential, absolute home path, browser profile, binary or local API/research prototype is included in the candidate.+- Official OpenCLI 1.8.7 was compared with its npm archive: **2,340 published files matched; no extra non-dependency files**. No upstream source edits.+- Authentication is completed by the human in one dedicated Reach profile. Only already-saved dedicated state is reused. Personal Chrome cookies/files are never imported.+- Ordinary commands no longer launch detached update checks. Existing tools/extensions are reused; an explicit update or allow-upgrade is required to change installed versions.+- Cursor/other application MCP configuration is never changed. A retired entry recorded by old Reach is reported as a manual action only.+- Created artifacts are recorded. Deletion uses this ledger or existing owned-tool records. Unknown files, unrecorded sessions and extra Skill notes survive. If the browser cannot close, uninstall stops before deleting files.+- The user approved an official OpenCLI Bridge companion. The watcher starts/reaps its own child; a failed owned Bridge closes the browser. An existing compatible user Bridge is borrowed, never killed. If another browser adopts our child, it is retained with a visible status note. Incompatible existing versions are left unchanged.++## Browser lifetime++- Login cookies are periodically saved; closing the window is not required to save them.+- Trusted page clicks, keyboard input, scrolling and touch, plus Reach calls, reset idle closure. Script-generated input does not. Browser toolbar activity outside the page is not measured.+- Real accelerated lifecycle test: 6-second idle closed the browser and watcher. Production default remains **600 seconds**. Existing user-owned Bridge PID was preserved.+- Shared profile, automatic extension, Chrome fallback and on-demand reopening remain. Windows execution is **not accepted in this round**.++## Real console acceptance++All rows below came from `python -m agent_reach.cli`, including saved proxy/PATH preparation. A preliminary in-process probe skipped that preparation and produced YouTube/V2EX errors; it is excluded from release evidence.++| Channel | Action | Backend | Items | ms |+|---|---|---|---:|---:|+| github | search | gh | 2 | 1859 |+| youtube | search | yt-dlp | 2 | 5435 |+| bilibili | search | bili-cli | 2 | 1048 |+| v2ex | hot | v2ex-api | 3 | 1539 |+| web | search | exa | 2 | 1588 |+| xiaohongshu | search | opencli | 2 | 5123 |+| xiaohongshu | read | opencli | 1 | 8755 |+| xiaohongshu | comments | opencli | 24 | 9282 |++XHS comments are the records actually loaded by upstream, including replies; this is not a complete-comment export guarantee.+**8 of 40 declared actions accepted on macOS. 32 remain without current candidate acceptance.** BOSS requires human verification before another business request. Other platforms/actions need their own acceptance; no status/installation/old success is promoted to a new pass.++## Quality and distribution++- 399 unit/regression tests passed; Ruff passed; Mypy checked 47 source files. Tests include failure retention, www/observed subdomains, archive reuse, BOSS browser detail routing, unknown-file preservation, trusted activity, Bridge ownership and source-bound release evidence.+- `scripts/check_release_acceptance.py` intentionally fails for this manifest until all missing actions are truly accepted. A v* tag therefore cannot publish this candidate through the release workflow.+- Formal stable installation points to the verified v1.5.0 release and its instructions. This unpublished 1.6.0 candidate uses its supplied wheel; it never points users at an absent v1.6.0 tag. Ordinary installed users may explicitly run update.+- Xiaoyuzhou remains present. ask/Reach MCP/custom Cloak site scraping/OpenCLI patching remain removed.+- Archive and wheel are built only from reviewed Git files. Installed Skill files are generated from that source, not copied from a maintainer-specific working profile.++Source digest: `35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c`. Sanitized machine-readable evidence: [release-acceptance.json](release-acceptance.json).diff --git a/docs/validation/release-acceptance.json b/docs/validation/release-acceptance.jsonnew file mode 100644index 00000000..24366029--- /dev/null+++ b/docs/validation/release-acceptance.json@@ -0,0 +1,279 @@+{+ "candidate": true,+ "version": "1.6.0",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "recorded_at": "2026-10-20T15:36:46Z",+ "release_ready": false,+ "results": [+ {+ "channel": "github",+ "action": "search",+ "at": "2026-10-20T15:34:29Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "gh",+ "passed": true,+ "item_count": 2,+ "elapsed_ms": 1859,+ "error": null+ },+ {+ "channel": "youtube",+ "action": "search",+ "at": "2026-10-20T15:34:35Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "yt-dlp",+ "passed": true,+ "item_count": 2,+ "elapsed_ms": 5435,+ "error": null+ },+ {+ "channel": "bilibili",+ "action": "search",+ "at": "2026-10-20T15:34:36Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "bili-cli",+ "passed": true,+ "item_count": 2,+ "elapsed_ms": 1048,+ "error": null+ },+ {+ "channel": "v2ex",+ "action": "hot",+ "at": "2026-10-20T15:34:38Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "v2ex-api",+ "passed": true,+ "item_count": 3,+ "elapsed_ms": 1539,+ "error": null+ },+ {+ "channel": "web",+ "action": "search",+ "at": "2026-10-20T15:34:39Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "exa",+ "passed": true,+ "item_count": 2,+ "elapsed_ms": 1588,+ "error": null+ },+ {+ "channel": "xiaohongshu",+ "action": "search",+ "at": "2026-10-20T15:34:45Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "opencli",+ "passed": true,+ "item_count": 2,+ "elapsed_ms": 5123,+ "error": null+ },+ {+ "channel": "xiaohongshu",+ "action": "read",+ "at": "2026-10-20T15:35:01Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "opencli",+ "passed": true,+ "item_count": 1,+ "elapsed_ms": 8755,+ "error": null+ },+ {+ "channel": "xiaohongshu",+ "action": "comments",+ "at": "2026-10-20T15:35:19Z",+ "os": "macOS",+ "method": "real-cli",+ "source_sha256": "35c255b6b581976e90b7aafc93236e12a81b5d6d7899d20e646ae082c06fda1c",+ "backend": "opencli",+ "passed": true,+ "item_count": 24,+ "elapsed_ms": 9282,+ "error": null+ }+ ],+ "pending": [+ {+ "channel": "bilibili",+ "action": "hot",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "bilibili",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "bilibili",+ "action": "subtitle",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "boss",+ "action": "read",+ "reason": "Requires human platform verification before another request"+ },+ {+ "channel": "boss",+ "action": "search",+ "reason": "Requires human platform verification before another request"+ },+ {+ "channel": "facebook",+ "action": "profile",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "facebook",+ "action": "search",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "github",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "instagram",+ "action": "posts",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "instagram",+ "action": "profile",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "instagram",+ "action": "search",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "linkedin",+ "action": "jobs",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "linkedin",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "reddit",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "reddit",+ "action": "search",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "reddit",+ "action": "subreddit",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "twitter",+ "action": "profile",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "twitter",+ "action": "search",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "twitter",+ "action": "thread",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "twitter",+ "action": "tweets",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "v2ex",+ "action": "node",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "v2ex",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "v2ex",+ "action": "user",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "web",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "xiaoyuzhou",+ "action": "transcribe",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "xueqiu",+ "action": "hot_posts",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "xueqiu",+ "action": "hot_stocks",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "xueqiu",+ "action": "quote",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "xueqiu",+ "action": "search",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "youtube",+ "action": "read",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "youtube",+ "action": "subtitle",+ "reason": "Not accepted on this candidate"+ },+ {+ "channel": "youtube",+ "action": "transcribe",+ "reason": "Not accepted on this candidate"+ }+ ],+ "additional_required_validation": [+ "Windows dedicated browser, extension connection, manual login, reopen and site cleanup"+ ],+ "privacy": "Counts, timings and error codes only; no credentials, accounts or content URLs"+}diff --git a/docs/validation/shared-browser-20261020.md b/docs/validation/shared-browser-20261020.mdindex d065879d..ebfdd1c7 100644--- a/docs/validation/shared-browser-20261020.md+++ b/docs/validation/shared-browser-20261020.md@@ -1,3 +1,5 @@+> Historical test record, superseded by the dedicated-only policy audit. The import path described below has been removed. These earlier passes do not certify the current candidate.+# Shared browser acceptance — 2026-10-20Candidate: **1.6.0**, targeting `release/1.6`. This record separates implementation checks from actual platform access. It does not certify every platform or Windows browser operation.@@ -13,7 +15,7 @@ Candidate: **1.6.0**, targeting `release/1.6`. This record separates implementat| One dedicated browser | Passed locally | Shared `~/.agent-reach/browser/profile`; CloakBrowser launched by the existing watcher with OpenCLI extension 1.0.26 loaded automatically. No per-channel browser contexts. || Ten idle minutes / automatic reopen | Passed with shortened live timer | Default is 600 seconds. Live test used 3 seconds: browser closed, watcher exited successfully; next call reopened and connected. The test did not wait ten wall-clock minutes. || Chrome fallback | Unit-tested | Installation/download failure selects installed Chrome and remembers the fallback. `browser setup --retry-cloak` retries Cloak. No live network failure was deliberately induced. |-| Login inheritance | Passed locally | Explicit one-time import of Xiaohongshu cookies from the user-selected leetengx Bridge profile; source unchanged; subsequent search returned a result. No personal Chrome Cookie database access. |+| Login inheritance | Passed locally | Explicit one-time import of Xiaohongshu cookies from the user-selected Bridge profile; source unchanged; subsequent search returned a result. No personal Chrome Cookie database access. || Preserve login on reopen | Passed locally | Session cookie survived close/reopen; Xiaohongshu and BOSS cookie counts remained 16 and 12. Cookie presence alone does not prove platform authentication. Private snapshot mode: 0600. || BOSS shares browser | Wiring done; business check blocked | Native CLI uses the owned CDP endpoint. Actual search returned **PLATFORM_BLOCKED**. Stopped immediately without backend/account retries; search and JD remain for manual verification. || Browser channel dependencies | Unit-tested; Xiaohongshu add exercised locally | Node, OpenCLI, browser and extension prepared by add. BOSS adds its native CLI too. Cloak download failure can use installed Chrome. |diff --git a/scripts/check_release_acceptance.py b/scripts/check_release_acceptance.pynew file mode 100644index 00000000..28d1d5ea--- /dev/null+++ b/scripts/check_release_acceptance.py@@ -0,0 +1,67 @@+"""A tag cannot publish an untested channel/action. No network or credentials here."""+from __future__ import annotations++import argparse+import hashlib+import json+from datetime import datetime, timezone+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+++def source_digest(root: Path = ROOT) -> str:+ digest = hashlib.sha256()+ paths = sorted((root / "agent_reach").rglob("*.py"))+ paths += [root / "pyproject.toml", root / "constraints.txt"]+ for path in paths:+ if "api" in path.relative_to(root).parts:+ continue+ digest.update(path.relative_to(root).as_posix().encode())+ digest.update(path.read_bytes())+ return digest.hexdigest()+++def validate(data: dict, required: set[tuple[str, str]], digest: str) -> list[str]:+ errors = []+ if data.get("source_sha256") != digest:+ errors.append("Acceptance belongs to different source code")+ passed = set()+ for row in data.get("results", []):+ key = (row.get("channel"), row.get("action"))+ if key not in required:+ errors.append(f"Unknown acceptance action: {key}")+ continue+ try:+ at = datetime.fromisoformat(row["at"].replace("Z", "+00:00"))+ age = (datetime.now(timezone.utc) - at).total_seconds()+ except (KeyError, TypeError, ValueError):+ age = float("inf")+ if (row.get("source_sha256") == digest and row.get("method") == "real-cli" and row.get("passed") is True+ and isinstance(row.get("item_count"), int) and row["item_count"] > 0+ and row.get("backend") and row.get("os") and 0 <= age <= 7 * 86400):+ passed.add(key)+ errors += [f"Missing real acceptance: {channel}/{action}" for channel, action in sorted(required - passed)]+ return errors+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("manifest", nargs="?", default="docs/validation/release-acceptance.json")+ args = parser.parse_args()+ from agent_reach.runtime.cli import unified_channels+ required = {(channel.name, action.name) for channel in unified_channels() for action in channel.actions}+ try:+ data = json.loads(Path(args.manifest).read_text("utf-8"))+ errors = validate(data, required, source_digest())+ except (OSError, ValueError, TypeError) as exc:+ errors = [f"Acceptance manifest unavailable: {exc}"]+ for error in errors:+ print(error)+ if errors:+ print("Release blocked. Unit tests and doctor do not replace real channel acceptance.")+ return bool(errors)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/conftest.py b/tests/conftest.pyindex ecc507b9..3cdb3cc2 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -84,7 +84,10 @@ def isolated_home(tmp_path, monkeypatch):# never start the background release check from testsmonkeypatch.setenv("AGENT_REACH_NO_UPDATE_CHECK", "1")- from agent_reach.runtime import cdp+ from agent_reach.runtime import bridge, cdp+ monkeypatch.setattr(bridge, "status", lambda: {"ok": True, "daemonVersion": "1.8.7", "profiles": []})+ monkeypatch.setattr(bridge, "launch_spec", lambda: (["node", "daemon.js"], "1.8.7"))+ monkeypatch.setattr(bridge, "start", lambda: None)monkeypatch.setattr(cdp, "_json", lambda *a, **k: None) # unit tests never inspect the real dedicated browseroriginal_popen = subprocess.Popendef local_commands_only(argv, *args, **kwargs):diff --git a/tests/test_browser.py b/tests/test_browser.pyindex d215e3e3..3ffbe755 100644--- a/tests/test_browser.py+++ b/tests/test_browser.py@@ -50,7 +50,8 @@ def test_extension_installs_at_a_stable_path_and_refreshes_only_on_new_release(hassert browser.refresh_extension() == {"version": "1.0.1", "updated": False}release["assets"] = [{"name": "opencli-extension-v1.0.2.zip", "browser_download_url": "u2"}]- assert browser.refresh_extension() == {"version": "1.0.2", "updated": True}+ assert browser.refresh_extension() == {"version": "1.0.1", "updated": False}+ assert browser.refresh_extension(upgrade=True) == {"version": "1.0.2", "updated": True}assert browser.extension_version() == "1.0.2"assert browser._load_state()["extension_version"] == "1.0.2"@@ -115,6 +116,7 @@ def test_clear_site_expires_only_that_sites_cookies(home, monkeypatch):browser.profile_dir().mkdir(parents=True)monkeypatch.setattr(browser, "ensure_running", lambda context=None: None)monkeypatch.setattr(cdp, "call", fake_call)+ monkeypatch.setattr(cdp, "_json", lambda *a: [])assert browser.clear_site(["reddit.com"]) == 2assert [c["name"] for c in jar] == ["c"]@@ -128,6 +130,9 @@ def test_delete_profile_removes_the_browser_folder(home, monkeypatch):monkeypatch.setattr(browser, "stop", lambda timeout=10.0: True)browser.profile_dir().mkdir(parents=True)browser.touch()+ from agent_reach.runtime import state+ for path in (browser.profile_dir(), browser._last_used_path()):+ state.remember_path(path, "test browser")assert browser.delete_profile() is Trueassert not browser.browser_root().exists()assert browser.delete_profile() is Falsediff --git a/tests/test_manage.py b/tests/test_manage.pyindex 55f8f0bf..352418fb 100644--- a/tests/test_manage.py+++ b/tests/test_manage.py@@ -11,7 +11,6 @@ import jsonimport osimport reimport shutil-import timeimport pytest@@ -102,7 +101,7 @@ def env(monkeypatch):def fake_install(tool, *, global_=False):installs.append(tool.name)- version = versions.get(tool.name, "1.2.3")+ version = versions.get(tool.name, "1.8.7" if tool.name == "opencli" else "1.2.3")if tool.kind in ("pip", "ffmpeg"):shutil.rmtree(tools.tool_dir(tool.name) / "venv", ignore_errors=True) # as the real installerpaths = ([tools._npm_global_bin() / (c + (".cmd" if tools._WIN else "")) for c in tool.commands] if global_@@ -188,7 +187,7 @@ def test_install_spec_uses_tested_versions_or_floor_and_exclude():"user_version, allow, expect_install, expect_owner, expect_version",[("1.9.0", False, [], "user", "1.9.0"),("1.8.0", True, [("user-upgrade", "opencli")], "user", "1.9.0"),- (None, False, ["opencli"], "agent-reach", "1.2.3")],+ (None, False, ["opencli"], "agent-reach", "1.8.7")],)def test_singleton_reuses_user_copy_and_upgrades_only_with_consent(env, user_version, allow, expect_install, expect_owner, expect_version@@ -380,30 +379,22 @@ def test_every_json_output_carries_meta_update_only_when_newer(env, capsys, monkassert "meta" not in _cli_json(capsys, ["doctor"])-def test_background_check_starts_at_most_once_a_day(monkeypatch):- monkeypatch.delenv(update_notice.DISABLE_ENV)- started = []- monkeypatch.setattr(update_notice.subprocess, "Popen", lambda argv, **k: started.append(argv))- update_notice.maybe_refresh()- update_notice.maybe_refresh()- assert len(started) == 1 and started[0][-1] == "agent_reach.runtime.update_notice"- old = time.time() - update_notice.INTERVAL - 5- os.utime(update_notice.started_path(), (old, old))- update_notice.maybe_refresh()- assert len(started) == 2+def test_queries_never_spawn_background_update_checks(env, monkeypatch, capsys):+ import subprocess+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: pytest.fail("background process"))+ assert _cli_json(capsys, ["doctor"])["ok"]+ assert not hasattr(update_notice, "maybe_refresh")-def test_background_check_writes_cache_or_stays_silent(monkeypatch):- def offline(timeout=10):+def test_explicit_update_check_preserves_offline_error_and_writes_success_cache(env, monkeypatch):+ monkeypatch.setattr(update_notice, "fetch_latest", lambda **k: {"latest": "9.9.9", "notes": "n"})+ assert manage.update_check()["latest"] == "9.9.9"+ assert update_notice.read_cache()["latest"] == "9.9.9"+ def offline(**kwargs):raise OSError("offline")-monkeypatch.setattr(update_notice, "fetch_latest", offline)- assert update_notice._main() == 1 and not update_notice.cache_path().exists()- monkeypatch.setattr(update_notice, "fetch_latest", lambda timeout=10: {"latest": "9.9.9", "notes": "n"})- assert update_notice._main() == 0 and update_notice.read_cache()["latest"] == "9.9.9"---# ── doctor ──+ with pytest.raises(ReachError, match="offline"):+ manage.update_check()def _status(name):@@ -543,7 +534,8 @@ def test_setup_receipt_never_overwrites_a_linked_foreign_file(env, tmp_path):def test_uninstall_removes_only_what_we_own(env):manage.add("bili")root = state.root()- (root / "config.yaml").write_text("x: 1")+ from agent_reach.config import Config+ Config().set("test", 1)(root / "my-notes").mkdir()(root / "tools" / "someone-elses-tool").mkdir(parents=True)update_notice.write_cache({"latest": "1.0.0", "notes": ""})@@ -560,7 +552,7 @@ def test_uninstall_removes_only_what_we_own(env):def test_uninstall_closes_the_browser_instead_of_refusing(env):manage.uninstall()- assert env["stopped"] == [True]+ assert env["stopped"] == [], "no owned browser was recorded"# ── skill ──@@ -606,10 +598,10 @@ def test_skill_replaces_our_old_copy_but_not_a_foreign_one(env):native_old = home / ".codex" / "skills" / "agent-reach"_seed_our_copy(native_old)result = manage.place_skill()- assert ours.is_symlink()+ assert ours.is_dir() and not ours.is_symlink()assert not foreign.is_symlink() and "someone-else" in (foreign / "SKILL.md").read_text(encoding="utf-8")assert [n["agent"] for n in result["not_linked"]] == ["cursor"]- assert not native_old.exists() and result["removed_old_copies"] == [str(native_old)]+ assert native_old.exists() and result["removed_old_copies"] == [], "unrecorded files are retained"def test_skill_falls_back_to_a_copy_without_symlink_rights(env, monkeypatch):@@ -641,13 +633,14 @@ def test_skill_link_for_an_unlisted_ai_and_uninstall_removes_everything(env):other = home / "my-ai" / "skills"manage.link_skill(str(other))assert (other / "agent-reach").is_symlink()+ manage.place_skill()stray = home / ".gemini" / "skills" / "agent-reach"stray.parent.mkdir(parents=True)stray.symlink_to(home / ".agents" / "skills" / "agent-reach")- manage.place_skill()assert (other / "agent-reach").is_symlink(), "update keeps recorded links"manage.uninstall()- for p in (other / "agent-reach", home / ".claude" / "skills" / "agent-reach", stray,+ assert stray.is_symlink(), "unrecorded shortcut is retained"+ for p in (other / "agent-reach", home / ".claude" / "skills" / "agent-reach",home / ".agents" / "skills" / "agent-reach"):assert not p.exists() and not p.is_symlink()@@ -689,15 +682,15 @@ def test_remove_browser_channel_forgets_grants_pending_and_only_its_login(env):assert state.load()["pending"] == {"b":{"channel":"site2"}}-def test_setup_removes_only_recorded_unchanged_legacy_mcp_entry(env):+def test_setup_reports_legacy_mcp_without_editing_external_configuration(env):path=home_dir()/".cursor"/"mcp.json"path.parent.mkdir()entry={"command":"/test/agent-reach","args":["mcp"]}path.write_text(json.dumps({"mcpServers":{"agent-reach":entry,"keep":{"command":"other"}}}))state.mutate(lambda data:data.update(mcp={"cursor":{"path":str(path),"entry":entry}}))- manage.setup()- assert json.loads(path.read_text())["mcpServers"]=={"keep":{"command":"other"}}- assert "mcp" not in state.load()+ result = manage.setup()+ assert json.loads(path.read_text())["mcpServers"]["agent-reach"] == entry+ assert result["user_actions"] and "mcp" in state.load()def test_setup_preserves_unowned_or_changed_mcp_configuration(env):@@ -728,5 +721,5 @@ def test_retired_mcp_cleanup_preserves_changed_private_path(env, monkeypatch):def changed(*args, **kwargs):raise paths.PrivatePathError("externally changed path")monkeypatch.setattr(paths, "read_small_text_no_follow", changed)- manage._cleanup_retired_mcp()+ assert manage._retired_mcp_notice()assert path.read_text() == "unchanged"diff --git a/tests/test_reach_flow.py b/tests/test_reach_flow.pyindex 527c6879..efbb405a 100644--- a/tests/test_reach_flow.py+++ b/tests/test_reach_flow.py@@ -40,16 +40,15 @@ def test_unknown_resume_is_explicit_bad_input():flow.resume("missing")-def test_prepare_reuses_one_shared_browser_and_imports_only_when_explicit(monkeypatch):+def test_prepare_reuses_only_the_shared_dedicated_browser(monkeypatch):from agent_reach.runtime import browser, manage, toolsmonkeypatch.setattr(manage, "is_added", lambda *a: True)monkeypatch.setattr(tools, "present", lambda *a: True)- ready, importing = Mock(), Mock()+ ready = Mock()monkeypatch.setattr(browser, "ensure_running", ready)- monkeypatch.setattr(browser, "import_session", importing)- flow.prepare("xiaohongshu", source_profile="consented-source")+ assert not hasattr(browser, "import_session")flow.prepare("xiaohongshu")- assert ready.call_count == 2 and importing.call_count == 1+ assert ready.call_count == 1assert not state.load().get("reuse_sources"), "no indefinite export authorization"diff --git a/tests/test_release_policy.py b/tests/test_release_policy.pynew file mode 100644index 00000000..8872c53c--- /dev/null+++ b/tests/test_release_policy.py@@ -0,0 +1,191 @@+"""Regression cases from the 63c272a audit; no real accounts or user processes."""+import json+import time+from unittest.mock import Mock++import pytest++from agent_reach.runtime import bridge, browser, cdp, manage, state, tools+from agent_reach.runtime.result import ReachError+++def test_cleanup_failure_retains_channel_tools_and_pending_request(monkeypatch):+ from agent_reach.channels.xiaohongshu import XiaoHongShuChannel+ ch = XiaoHongShuChannel()+ state.mutate(lambda data: data["channels"].update(xiaohongshu={"added_at": state.now()}))+ state.mutate(lambda data: data.update(pending={"id": {"channel": ch.name}}))+ monkeypatch.setattr(browser, "clear_site", Mock(side_effect=ReachError("UPSTREAM_BROKEN", "clear failed")))+ monkeypatch.setattr(tools, "prune", lambda *a: pytest.fail("pruned before cleanup succeeded"))+ with pytest.raises(ReachError, match="clear failed"):+ manage.remove(ch.name)+ assert manage.is_added(ch) and "id" in state.load()["pending"]+++def test_cleanup_includes_www_and_remembered_subdomains_preserving_other_sites(monkeypatch):+ browser.update_state(visited_origins=["https://edith.xiaohongshu.com", "https://other.example"])+ jar = [{"name": "sid", "value": "test", "domain": ".xiaohongshu.com", "path": "/"},+ {"name": "sid", "value": "keep", "domain": "other.example", "path": "/"}]+ cleared = []+ monkeypatch.setattr(cdp, "_json", lambda _: [{"type": "page", "id": "note", "url": "https://www.xiaohongshu.com/explore/a"},+ {"type": "page", "id": "other", "url": "https://other.example"}])+ def call(method, params=None, **kwargs):+ if method == "Storage.getCookies":+ return {"cookies": list(jar)}+ if method == "Storage.setCookies":+ jar[:] = [c for c in jar if c["domain"] == "other.example"]+ if method == "Storage.clearDataForOrigin":+ cleared.append(params["origin"])+ return {}+ monkeypatch.setattr(cdp, "call", call)+ assert browser._clear_running_site(["xiaohongshu.com"]) == 1+ assert {"https://www.xiaohongshu.com", "https://edith.xiaohongshu.com"} <= set(cleared)+ assert not any("other.example" in url for url in cleared)+ assert browser._load_state()["visited_origins"] == ["https://other.example"]+ assert jar[0]["value"] == "keep"+++def test_cleanup_never_claims_success_if_cookie_remains(monkeypatch):+ monkeypatch.setattr(cdp, "_json", lambda _: [])+ monkeypatch.setattr(cdp, "call", lambda method, *a, **k: {"cookies": [{"name": "sid", "domain": "reddit.com"}]} if method == "Storage.getCookies" else {})+ with pytest.raises(ReachError, match="verified"):+ browser._clear_running_site(["reddit.com"])+++def test_boss_detail_uses_upstream_browser_adapter_without_native_http(monkeypatch):+ from agent_reach.backends import opencli+ from agent_reach.channels.boss import BossChannel+ call = Mock(return_value=[{"title": "Data Engineer", "description": "JD"}])+ monkeypatch.setattr(opencli, "opencli_call", call)+ ch = BossChannel()+ assert ch.actions[1].backends == (("opencli", "_opencli_read"),)+ assert ch._opencli_read(target="https://www.zhipin.com/job_detail/abc123.html", timeout=20)[0]["text"] == "JD"+ assert call.call_args.args == ("boss", ["detail", "abc123"])+++def test_boss_zip_install_provenance_is_reused(monkeypatch):+ tool = tools.TOOLS["boss-agent-cli"]+ binpath = tools._private_bin(tool, "boss")+ binpath.parent.mkdir(parents=True)+ binpath.touch()+ direct = tools.tool_dir(tool.name) / "venv/lib/python3.12/site-packages/boss_agent_cli-1.0.dist-info/direct_url.json"+ direct.parent.mkdir(parents=True)+ direct.write_text(json.dumps({"url": tool.package.split(" @ ")[1], "archive_info": {}}))+ tools.record(tool.name, "1.0")+ install = Mock()+ monkeypatch.setattr(tools, "_install", install)+ tools.ensure(tool.name)+ tools.ensure(tool.name)+ install.assert_not_called()+++def test_unknown_tool_and_session_are_preserved():+ from agent_reach.runtime.sessions import clear_session+ unknown = tools.tool_dir("bili-cli")+ unknown.mkdir(parents=True)+ (unknown / "notes").write_text("keep")+ session = state.root() / "sessions/bili-cli"+ session.mkdir(parents=True)+ assert not tools.remove_private("bili-cli")+ assert not clear_session("bili-cli")+ assert unknown.exists() and session.exists()+++def test_uninstall_keeps_unknown_root_and_skill_files(monkeypatch):+ monkeypatch.setattr(manage, "linked_agents", lambda: {})+ manage.place_skill()+ note = manage.skill_dir() / "my-notes.md"+ note.write_text("keep")+ foreign = state.root() / "config.yaml"+ foreign.write_text("unrecorded")+ manage.uninstall()+ assert foreign.exists() and note.read_text() == "keep"+ assert not (manage.skill_dir() / "SKILL.md").exists()+++def test_trusted_page_activity_extends_idle_but_script_activity_does_not(monkeypatch):+ browser.touch()+ before = browser.last_used()+ monkeypatch.setattr(cdp, "_json", lambda _: [{"type": "page", "id": "owned", "url": "https://example.com"}])+ monkeypatch.setattr(cdp, "call", lambda *a, **k: {"result": {"value": 0}})+ browser.observe_activity()+ assert browser.last_used() == before+ time.sleep(0.01)+ monkeypatch.setattr(cdp, "call", lambda *a, **k: {"result": {"value": time.time() * 1000}})+ browser.observe_activity()+ assert browser.last_used() > before+ assert browser._load_state()["visited_origins"] == ["https://example.com"]+++def test_bridge_shutdown_reaps_our_child_and_preserves_foreign_clients(monkeypatch):+ proc = Mock(pid=123)+ proc.poll.return_value = None+ monkeypatch.setattr(bridge, "status", lambda: {"pid": 123, "profiles": [{"contextId": "reach"}]})+ assert bridge.close(proc, "reach") is None+ proc.terminate.assert_called_once()+ proc.wait.assert_called_once()+ proc.reset_mock()+ monkeypatch.setattr(bridge, "status", lambda: {"pid": 123, "profiles": [{"contextId": "other"}]})+ assert "retained" in bridge.close(proc, "reach")+ proc.terminate.assert_not_called()+ assert bridge.close(None, "reach") is None+++def test_release_gate_rejects_doctor_stale_and_wrong_source():+ from scripts.check_release_acceptance import validate+ row = {"channel": "web", "action": "search", "passed": True, "item_count": 1,+ "backend": "exa", "os": "macOS", "at": state.now(), "method": "doctor", "source_sha256": "source"}+ data = {"source_sha256": "source", "results": [row]}+ assert validate(data, {("web", "search")}, "source")+ row["method"] = "real-cli"+ assert not validate(data, {("web", "search")}, "source")+ assert validate(data, {("web", "search"), ("web", "read")}, "source")+ assert validate(data, {("web", "search")}, "changed")+ row["at"] = "2020-01-01T00:00:00Z"+ assert validate(data, {("web", "search")}, "source")+++def test_existing_incompatible_bridge_is_never_restarted(monkeypatch):+ monkeypatch.setattr(bridge, "launch_spec", lambda: (["node", "daemon.js"], "1.8.7"))+ monkeypatch.setattr(bridge, "status", lambda: {"ok": True, "daemonVersion": "2.0.1", "pid": 123})+ with pytest.raises(ReachError, match="left it unchanged"):+ bridge.require_compatible()+++def test_unknown_browser_files_are_not_deleted(monkeypatch):+ monkeypatch.setattr(browser, "stop", lambda: pytest.fail("unowned browser was stopped"))+ browser.browser_root().mkdir(parents=True)+ note = browser.browser_root() / "my-notes"+ note.write_text("keep")+ assert not browser.delete_profile()+ assert note.read_text() == "keep"+++def test_uninstall_stops_before_deleting_files_if_browser_cannot_close(monkeypatch):+ browser.update_state(backend="cloakbrowser")+ note = state.root() / "must-keep.txt"+ note.write_text("keep")+ state.remember_path(note, "test owned artifact")+ monkeypatch.setattr(browser, "stop", lambda: False)+ with pytest.raises(ReachError, match="could not close"):+ manage.uninstall()+ assert note.read_text() == "keep" and state.exists()+++def test_watcher_closes_with_its_failed_bridge(monkeypatch):+ from agent_reach.runtime import browser_watcher+ proc = Mock(pid=123)+ proc.poll.return_value = 1+ monkeypatch.setattr(bridge, "start", lambda: proc)+ monkeypatch.setattr(browser, "is_running", lambda: True)+ monkeypatch.setattr(browser, "observe_activity", lambda: pytest.fail("used browser after bridge failed"))+ assert "Bridge exited" in browser_watcher.watch(poll=0.01)+++def test_unrecorded_native_session_cannot_be_claimed_on_use():+ from agent_reach.runtime.sessions import session_dir+ path = state.root() / "sessions/unknown"+ path.mkdir(parents=True)+ (path / "notes").write_text("keep")+ with pytest.raises(ReachError, match="Unrecorded"):+ session_dir("unknown")+ assert not state.owned_path(path)diff --git a/tests/test_session_onboarding.py b/tests/test_session_onboarding.pyindex 4dd05810..7bea94b9 100644--- a/tests/test_session_onboarding.py+++ b/tests/test_session_onboarding.py@@ -1,64 +1,12 @@-"""Shared destination, explicit source import, no source-browser mutation."""+"""Dedicated-only authentication: prohibited imports never touch a source browser."""import json-import time-from unittest.mock import Mockimport pytest-from agent_reach.runtime import browser, cdp, state+from agent_reach.runtime import browser, cdp, cli, statefrom agent_reach.runtime.result import ReachError-def _cookie(domain, name="session", **extra):- return {"name": name, "value": "test-value", "domain": domain, "path": "/", **extra}---def test_import_filters_other_sites_and_expired_cookies_before_browser_access(monkeypatch, tmp_path):- source = tmp_path / "session.json"- source.write_text(json.dumps({"cookies": [_cookie(".xiaohongshu.com"), _cookie(".example.com"),- _cookie(".xiaohongshu.com", "expired", expires=time.time()-1)]}))- start = Mock()- monkeypatch.setattr(browser, "ensure_running", start)- jar = []- def call(method, params=None):- if method == "Storage.setCookies":- jar.extend(params["cookies"])- return {}- return {"cookies": jar}- monkeypatch.setattr(cdp, "call", call)- result = browser.import_session("xiaohongshu", state_file=source)- assert result["imported_cookies"] == 1 and result["logged_in"] is None- assert result["original_browser_changed"] is False and start.call_count == 1- assert json.loads(source.read_text())["cookies"][0]["value"] == "test-value"- assert len(json.loads((browser.browser_root()/"session.json").read_text())["cookies"]) == 1- assert not state.load().get("reuse_sources")---def test_import_with_no_matching_cookies_does_not_launch(monkeypatch, tmp_path):- source = tmp_path / "session.json"- source.write_text(json.dumps([_cookie(".example.com")]))- monkeypatch.setattr(browser, "ensure_running", lambda: pytest.fail("unusable import opened browser"))- with pytest.raises(ReachError, match="No unexpired"):- browser.import_session("xiaohongshu", state_file=source)---def test_import_requires_exactly_one_explicit_source():- with pytest.raises(ReachError, match="exactly one"):- browser.import_session("xiaohongshu")- with pytest.raises(ReachError, match="exactly one"):- browser.import_session("xiaohongshu", state_file="x", opencli_profile="y")---def test_source_export_is_scoped_to_selected_site(monkeypatch):- from agent_reach.backends import opencli- export = Mock(return_value=[_cookie(".xiaohongshu.com")])- monkeypatch.setattr(opencli, "export_site_cookies", export)- monkeypatch.setattr(browser, "ensure_running", lambda: None)- monkeypatch.setattr(cdp, "call", lambda *a, **k: {})- browser.import_session("xiaohongshu", opencli_profile="user-selected")- export.assert_called_once_with("user-selected", "xiaohongshu.com")--def test_unmanaged_debugging_port_is_never_closed_or_navigated(monkeypatch):monkeypatch.setattr(browser, "is_running", lambda: True)monkeypatch.setattr(browser, "watcher_running", lambda: False)@@ -69,56 +17,22 @@ def test_unmanaged_debugging_port_is_never_closed_or_navigated(monkeypatch):operation()-def test_owned_snapshot_migration_preserves_a_newer_shared_login(monkeypatch):- source=state.root()/"sessions/xiaohongshu-cloak/profile/reach-session.json"- source.parent.mkdir(parents=True)- source.write_text(json.dumps({"cookies":[_cookie(".xiaohongshu.com", "auth"),_cookie(".xiaohongshu.com", "extra")]}))- jar=[{**_cookie(".xiaohongshu.com","auth"),"value":"newer-login"}]- def call(method,params=None,**kwargs):- if method=="Storage.setCookies":- jar.extend(params["cookies"])- return {}- return {"cookies":list(jar)}- monkeypatch.setattr(browser,"ensure_running",lambda:None)- monkeypatch.setattr(cdp,"call",call)- browser.migrate_owned_session("xiaohongshu")- browser.migrate_owned_session("xiaohongshu")- assert next(c for c in jar if c["name"]=="auth")["value"]=="newer-login"- assert len(jar)==2 and source.exists()- assert state.load()["session_migrations"]["xiaohongshu"]["imported_cookies"]==1--def test_logout_cannot_reimport_an_old_owned_snapshot(monkeypatch, capsys):- from agent_reach.runtime import cli- old = state.root() / "sessions/xiaohongshu-cloak/profile/reach-session.json"- old.parent.mkdir(parents=True)- old.write_text(json.dumps({"cookies": [_cookie(".xiaohongshu.com")]}))- state.mutate(lambda saved: saved.update(reuse_sources={"xiaohongshu": {"profile": "old"}}))- clear = Mock(return_value=1)- monkeypatch.setattr(browser, "clear_site", clear)- assert cli.main(["logout", "xiaohongshu"]) == 0- assert json.loads(capsys.readouterr().out)["ok"]- clear.assert_called_once_with(["xiaohongshu.com"])- assert not old.exists() and not state.load()["reuse_sources"]- monkeypatch.setattr(browser, "import_session", lambda *a, **k: pytest.fail("revived logged-out session"))- browser.migrate_owned_session("xiaohongshu")[email protected]("args", [+ ["browser", "import", "xiaohongshu", "--opencli-profile", "foreign"],+ ["browser", "profiles"],+ ["ensure", "xiaohongshu", "--reuse-profile", "foreign"],+ ["browser", "import", "xiaohongshu", "--state-file", "private.json"],+])+def test_personal_login_import_is_unavailable(args, monkeypatch, capsys):+ monkeypatch.setattr(browser, "ensure_running", lambda: pytest.fail("opened browser"))+ monkeypatch.setattr(cdp, "call", lambda *a, **k: pytest.fail("read credentials"))+ assert cli.main(args) == 1+ assert json.loads(capsys.readouterr().out)["error"]["code"] == "BAD_INPUT"+ assert not state.load().get("reuse_sources")[email protected]("shim", [False, True])-def test_source_export_locates_the_unmodified_page_api_for_npm_layouts(monkeypatch, tmp_path, shim):- from agent_reach.backends.opencli import export_site_cookies- from agent_reach.runtime import run, tools- package = tmp_path / "node_modules/@jackwener/opencli"- page = package / "dist/src/browser/page.js"- page.parent.mkdir(parents=True)- page.write_text("// upstream fixture")- entry = tmp_path / "opencli.cmd" if shim else package / "dist/src/main.js"- entry.parent.mkdir(parents=True, exist_ok=True)- entry.write_text("shim or upstream entry")- monkeypatch.setattr(tools, "resolve", lambda _: str(entry))- call = Mock(return_value="[]")- monkeypatch.setattr(run, "run_cmd", call)- assert export_site_cookies("chosen-profile", "xiaohongshu.com") == []- argv = call.call_args.args[0]- assert page.as_uri() in argv[3] and argv[-2:] == ["chosen-profile", "xiaohongshu.com"]- assert page.read_text() == "// upstream fixture"+def test_legacy_cookie_export_and_import_implementations_are_removed():+ from agent_reach.backends import opencli+ assert not hasattr(browser, "import_session")+ assert not hasattr(opencli, "export_site_cookies")