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(cli): fail closed on credential setup errors
Pnantec4c69652784
diff --git a/agent_reach/channels/youtube.py b/agent_reach/channels/youtube.pyindex 954a58ea..728a3206 100644--- a/agent_reach/channels/youtube.py+++ b/agent_reach/channels/youtube.py@@ -5,8 +5,12 @@ import reimport shutilfrom agent_reach.probe import probe_command-from agent_reach.utils.paths import get_ytdlp_config_path, render_ytdlp_fix_command-from agent_reach.utils.text import read_utf8_text+from agent_reach.utils.paths import (+ PrivatePathError,+ get_ytdlp_config_path,+ read_small_text_no_follow,+ render_ytdlp_fix_command,+)from .base import Channel@@ -23,10 +27,12 @@ def _parse_ytdlp_version(version: str):def _has_js_runtime_config(config_path) -> bool:"""Return whether yt-dlp config explicitly enables a JS runtime."""try:- if not config_path.exists():- return False- return "--js-runtimes" in read_utf8_text(config_path)- except OSError:+ payload = read_small_text_no_follow(+ config_path,+ max_bytes=1024 * 1024,+ )+ return payload is not None and "--js-runtimes" in payload+ except (OSError, UnicodeError, PrivatePathError):return False@@ -46,10 +52,13 @@ class YouTubeChannel(Channel):probe = probe_command("yt-dlp", ["--version"], timeout=10, package="yt-dlp")if probe.status == "missing":self.active_backend = None- return "off", "yt-dlp 未安装。安装:pip install yt-dlp"+ return "off", f"yt-dlp 未安装。安装:{_YTDLP_UPGRADE_COMMAND}"if probe.status == "broken":self.active_backend = None- return "error", f"yt-dlp 已安装但无法执行\n{probe.hint}"+ return "error", (+ "yt-dlp 已安装但无法执行。重装(含 JS 支持):\n"+ f" {_YTDLP_UPGRADE_COMMAND}\n{probe.hint}"+ )if not probe.ok: # timeout / error:装了但跑不动self.active_backend = Nonedetail = probe.hint or probe.output or probe.status@@ -93,8 +102,17 @@ class YouTubeChannel(Channel):if config.is_configured("openai_whisper"):providers.append("openai")if providers:- if not shutil.which("ffmpeg"):- msg += "(音频转写需安装 ffmpeg)"+ missing_media_tools = [+ tool+ for tool in ("ffmpeg", "ffprobe")+ if not shutil.which(tool)+ ]+ if missing_media_tools:+ msg += (+ "(音频转写需安装 "+ + "、".join(missing_media_tools)+ + ")"+ )else:msg += f",可转写音频({'→'.join(providers)})"return "ok", msgdiff --git a/agent_reach/cli.py b/agent_reach/cli.pyindex 8936b46e..7e662383 100644--- a/agent_reach/cli.py+++ b/agent_reach/cli.py@@ -158,6 +158,10 @@ def main():f"{args.platform} requires Cookie-Editor export; use "f"`agent-reach configure {manual_keys[args.platform]} ...`")+ if args.profile and args.from_browser not in {"chrome", "edge", "brave"}:+ p_conf.error(+ "--profile is supported only for Chrome/Edge/Brave"+ )if args.sync_legacy_twitter:p_conf.error("--sync-legacy-twitter is only valid with twitter-cookies")elif args.command == "configure":@@ -205,29 +209,14 @@ def main():def _cmd_install(args):"""One-shot deterministic installer."""import os+from agent_reach.config import Configfrom agent_reach.doctor import check_all, format_reportsafe_mode = args.safedry_run = args.dry_run- config = Config()- print()- print("Agent Reach Installer")- print("=" * 40)-- # Ensure tools directory exists (for upstream tool repos)- tools_dir = os.path.expanduser("~/.agent-reach/tools")- os.makedirs(tools_dir, exist_ok=True)-- if dry_run:- print("DRY RUN — showing what would be done (no changes)")- print()- if safe_mode:- print("SAFE MODE — skipping automatic system changes")- print()-- # ── Parse --channels ──+ # Validate channel names before constructing config or changing the system.CHANNEL_INSTALLERS = {"twitter": _install_twitter_deps,"xiaoyuzhou": _install_xiaoyuzhou_deps,@@ -240,17 +229,48 @@ def _cmd_install(args):# xueqiu: cookie-only, no install step# linkedin: manual setup, no auto-install}+ supported_channels = set(CHANNEL_INSTALLERS) | {"xueqiu", "linkedin"}+ raw_channels = [+ channel.strip().lower()+ for channel in args.channels.split(",")+ if channel.strip()+ ]+ unknown_channels = set(raw_channels) - supported_channels - {"all"}+ if unknown_channels:+ supported = ", ".join(sorted(supported_channels | {"all"}))+ unknown = ", ".join(sorted(unknown_channels))+ print(+ f"agent-reach install: error: unknown channel(s): {unknown}. "+ f"Supported: {supported}",+ file=sys.stderr,+ )+ raise SystemExit(2)++ if "all" in raw_channels:+ requested_channels = supported_channels+ else:+ requested_channels = set(raw_channels)++ config = Config(read_only=dry_run or safe_mode)+ print()+ print("Agent Reach Installer")+ print("=" * 40)++ if dry_run:+ print("DRY RUN — showing what would be done (no changes)")+ print()+ if safe_mode:+ print("SAFE MODE — skipping automatic system changes")+ print()++ # Only a real installation may create persistent directories.+ if not dry_run and not safe_mode:+ tools_dir = os.path.expanduser("~/.agent-reach/tools")+ os.makedirs(tools_dir, exist_ok=True)+OPENCLI_ONLY_CHANNELS = {"opencli", "facebook", "instagram"}COOKIE_CHANNELS = {"twitter", "xueqiu", "bilibili", "xiaohongshu"}- requested_channels = set()- if args.channels:- raw = [c.strip().lower() for c in args.channels.split(",") if c.strip()]- if "all" in raw:- requested_channels = set(CHANNEL_INSTALLERS.keys()) | {"xueqiu", "linkedin"}- else:- requested_channels = set(raw)-# Auto-detect environmentenv = args.envif env == "auto":@@ -269,8 +289,9 @@ def _cmd_install(args):# Apply explicit flagsif args.proxy:- if dry_run:- print(f"[dry-run] Would save network proxy")+ if dry_run or safe_mode:+ mode = "dry-run" if dry_run else "safe"+ print(f"[{mode}] Would save network proxy")else:config.set("proxy", args.proxy)config.set("bilibili_proxy", args.proxy) # legacy key@@ -361,23 +382,29 @@ def _cmd_install(args):print(format_report(results))print()- # ── Install agent skill ──- _install_skill()+ if safe_mode:+ print(+ "Safe mode check complete. No changes were made. "+ f"{ok}/{total} channels active."+ )+ else:+ # ── Install agent skill ──+ _install_skill()- print(f"✅ Installation complete! {ok}/{total} channels active.")+ print(f"✅ Installation complete! {ok}/{total} channels active.")- if not requested_channels:- # First install — hint about optional channels- print()- print("More channels available! Use --channels to install:")- print(" agent-reach install --channels=twitter,xiaohongshu,reddit,facebook,instagram,...")- print(" agent-reach install --channels=all (install everything)")+ if not requested_channels:+ # First install — hint about optional channels+ print()+ print("More channels available! Use --channels to install:")+ print(" agent-reach install --channels=twitter,xiaohongshu,reddit,facebook,instagram,...")+ print(" agent-reach install --channels=all (install everything)")- # Star reminder- print()- print("如果 Agent Reach 帮到了你,给个 Star 让更多人发现它吧:")- print(" https://github.com/Panniantong/Agent-Reach")- print(" 只需一秒,对独立开发者意义很大。谢谢!")+ # Star reminder+ print()+ print("如果 Agent Reach 帮到了你,给个 Star 让更多人发现它吧:")+ print(" https://github.com/Panniantong/Agent-Reach")+ print(" 只需一秒,对独立开发者意义很大。谢谢!")else:print()print("Dry run complete. No changes were made.")@@ -664,24 +691,82 @@ def _install_system_deps():print(" -- undici install failed (optional — may not work behind proxies)")# ── yt-dlp JS runtime config (YouTube requires external JS runtime) ──- if shutil.which("node"):- from agent_reach.utils.paths import get_ytdlp_config_path-- ytdlp_config = get_ytdlp_config_path()- needs_config = True- if ytdlp_config.exists():- with ytdlp_config.open("r", encoding="utf-8") as f:- if "--js-runtimes" in f.read():- needs_config = False- print(" ✅ yt-dlp JS runtime already configured")- if needs_config:+ if shutil.which("deno"):+ print(" ✅ yt-dlp can use the installed Deno JS runtime")+ elif shutil.which("node"):+ from agent_reach.channels.youtube import (+ _JS_RUNTIMES_SUPPORTED_FROM,+ _parse_ytdlp_version,+ )+ from agent_reach.utils.paths import (+ PrivatePathError,+ atomic_write_private_text,+ get_ytdlp_config_path,+ read_small_text_no_follow,+ )++ ytdlp_cmd = shutil.which("yt-dlp")+ installed_version = None+ if ytdlp_cmd:try:- ytdlp_config.parent.mkdir(parents=True, exist_ok=True)- with ytdlp_config.open("a", encoding="utf-8") as f:- f.write("--js-runtimes node\n")- print(" ✅ yt-dlp configured to use Node.js as JS runtime (YouTube)")- except Exception:- print(" -- Could not configure yt-dlp JS runtime (YouTube may not work)")+ version_result = subprocess.run(+ [ytdlp_cmd, "--version"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=10,+ )+ if version_result.returncode == 0:+ installed_version = _parse_ytdlp_version(+ version_result.stdout.strip()+ )+ except (OSError, subprocess.TimeoutExpired):+ installed_version = None++ if (+ installed_version is None+ or installed_version < _JS_RUNTIMES_SUPPORTED_FROM+ ):+ print(+ " -- 未写入 yt-dlp JS runtime 配置:yt-dlp 缺失、过旧或"+ "版本无法确认。先升级:python -m pip install -U "+ '"yt-dlp[default]"'+ )+ else:+ ytdlp_config = get_ytdlp_config_path()+ try:+ existing_config = read_small_text_no_follow(+ ytdlp_config,+ max_bytes=1024 * 1024,+ )+ if (+ existing_config is not None+ and "--js-runtimes" in existing_config+ ):+ print(" ✅ yt-dlp JS runtime already configured")+ else:+ existing_config = existing_config or ""+ separator = (+ ""+ if not existing_config+ or existing_config.endswith(("\n", "\r"))+ else "\n"+ )+ atomic_write_private_text(+ ytdlp_config,+ existing_config+ + separator+ + "--js-runtimes node\n",+ )+ print(+ " ✅ yt-dlp configured to use Node.js as JS runtime "+ "(YouTube)"+ )+ except (OSError, UnicodeError, ValueError, PrivatePathError):+ print(+ " -- Could not configure yt-dlp JS runtime "+ "(YouTube may not work)"+ )# NOTE: twitter-cli, xiaoyuzhou, xhs-cli etc. are optional.# They are installed via --channels flag, not here.@@ -758,8 +843,8 @@ def _install_xhs_deps():"""Set up XiaoHongShu — backend depends on environment.Desktop: OpenCLI (reuses the browser session, zero config).- Server: xiaohongshu-mcp guide (self-contained headless browser + QR- login; we don't manage long-running services, so guide only).+ Server: xiaohongshu-mcp guide with an explicit Cookie-Editor export;+ we don't manage long-running services, so guide only.xhs-cli is no longer installed by default — upstream unmaintainedsince 2026-03; existing installs keep working as a fallback backend."""@@ -767,12 +852,14 @@ def _install_xhs_deps():print("Setting up XiaoHongShu...")if _detect_environment() == "server":- print(" 服务器环境推荐 xiaohongshu-mcp(自带无头浏览器,扫码登录):")+ print(" 服务器环境推荐 xiaohongshu-mcp:")print(" 1. 下载 binary:https://github.com/xpzouying/xiaohongshu-mcp/releases")print(" (建议放到 ~/.agent-reach/tools/ 下)")print(" 2. 启动服务(首次运行会下载约 150MB 浏览器,请等待完成)")- print(" 3. 扫码登录后接入:mcporter config add xiaohongshu http://localhost:18060/mcp --scope home")- print(" 4. 验证:agent-reach doctor")+ print(" 3. 用 Cookie-Editor 从 xiaohongshu.com 明确导出 Cookie")+ print(" agent-reach configure xhs-cookies '<Cookie-Editor JSON or Header String>'")+ print(" 4. 接入:mcporter config add xiaohongshu http://localhost:18060/mcp --scope home")+ print(" 5. 验证:agent-reach doctor")return_install_opencli_deps()@@ -974,11 +1061,23 @@ def _install_mcporter():# Configure Exa MCP (free, no key needed)try:+ from agent_reach.channels.mcporter import (+ McporterConfigError,+ configured_server_names,+ )+r = subprocess.run(- ["mcporter", "config", "list"], capture_output=True, encoding="utf-8", errors="replace", timeout=5+ ["mcporter", "config", "list", "--json"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=5,)- if "exa" not in r.stdout:- subprocess.run(+ if r.returncode != 0:+ raise McporterConfigError("mcporter 配置查询失败")+ server_names = configured_server_names(r.stdout)+ if "exa" not in server_names:+ add_result = subprocess.run(["mcporter","config",@@ -990,7 +1089,13 @@ def _install_mcporter():],capture_output=True, encoding="utf-8", errors="replace", timeout=10,)- print(" ✅ Exa search configured (free, no API key needed)")+ if add_result.returncode == 0:+ print(" ✅ Exa search configured (free, no API key needed)")+ else:+ print(+ " [!] Could not configure Exa. Run manually: "+ "mcporter config add exa https://mcp.exa.ai/mcp --scope home"+ )else:print(" ✅ Exa search already configured")except Exception:@@ -1059,6 +1164,8 @@ def _detect_environment():def _cmd_configure(args):"""Set a config value and test it, or auto-extract from browser."""import shutil+ from typing import cast+from agent_reach.config import Configconfig = Config()@@ -1072,12 +1179,22 @@ def _cmd_configure(args):print(f"Extracting {args.platform} cookies from {browser}...")print()- results = configure_from_browser(- browser,- config,- platform=platform,- profile=args.profile,- )+ try:+ results = configure_from_browser(+ browser,+ config,+ platform=platform,+ profile=args.profile,+ )+ except ValueError as exc:+ from agent_reach.utils.text import scrub_url_credentials++ print(+ f"agent-reach configure: error: "+ f"{scrub_url_credentials(exc)}",+ file=sys.stderr,+ )+ raise SystemExit(2) from Nonefound_any = Falsefor result in results:@@ -1087,7 +1204,8 @@ def _cmd_configure(args):message = result.messagetargets = getattr(result, "targets", ())else:- result_platform, success, message = result+ legacy_result = cast(tuple[str, bool, str], result)+ result_platform, success, message = legacy_resulttargets = ()if success:print(f" ✅ {result_platform}: {message}")@@ -1102,6 +1220,7 @@ def _cmd_configure(args):print("✅ Cookies configured! Run `agent-reach doctor` to see updated status.")else:print(f"No cookies found. Make sure you're logged into the platforms in {browser}.")+ raise SystemExit(1)return# ── Manual configure ──@@ -1109,14 +1228,14 @@ def _cmd_configure(args):print("Usage: agent-reach configure <key> <value>")print(" or: agent-reach configure --from-browser chrome "- "--platform twitter"+ "--platform xueqiu")returnvalue = " ".join(args.value) if args.value else ""if not value:print(f"Missing value for {args.key}")- return+ raise SystemExit(1)if args.key == "proxy":# Generic network proxy for restricted environments. Nothing reads@@ -1138,51 +1257,48 @@ def _cmd_configure(args):config.set("twitter_auth_token", auth_token)config.set("twitter_ct0", ct0)- print("✅ Twitter cookies configured!")+ print("✅ Twitter cookies 已保存到 ~/.agent-reach/config.yaml")if getattr(args, "sync_legacy_twitter", False):from agent_reach.cookie_extract import (_sync_bird_env,_sync_xfetch_session,)- _sync_xfetch_session(auth_token, ct0)- _sync_bird_env(auth_token, ct0)+ legacy_results = (+ (+ "~/.config/xfetch/session.json",+ _sync_xfetch_session(auth_token, ct0),+ ),+ (+ "~/.config/bird/credentials.env",+ _sync_bird_env(auth_token, ct0),+ ),+ )+ for path, success in legacy_results:+ outcome = "written" if success else "failed"+ print(f" {outcome}: {path}")+ if all(success for _, success in legacy_results):+ print(" Legacy copies written successfully.")++ print(+ " 凭据未实时验证:不会执行 `twitter status`,因为上游在"+ "验证失败时会自动读取浏览器 Cookie。"+ )+ if not shutil.which("twitter"):print(- " Legacy copies written to "- "~/.config/xfetch/session.json and "- "~/.config/bird/credentials.env"+ " [!] twitter-cli 未安装。运行:pipx install twitter-cli"+ )+ else:+ print(+ " 注意:独立 `twitter` 命令不会读取 Agent Reach 配置;"+ "直接使用时需显式设置 TWITTER_AUTH_TOKEN/TWITTER_CT0。")-- print("Testing Twitter access...", end=" ")- try:- import subprocess- twitter_bin = shutil.which("twitter")- if not twitter_bin:- print("[!] twitter-cli not installed. Run: pipx install twitter-cli")- else:- import os-- from agent_reach.channels.twitter import twitter_cli_child_env-- env = os.environ.copy()- env.update(twitter_cli_child_env(config))- result = subprocess.run(- [twitter_bin, "status"],- capture_output=True, encoding="utf-8", errors="replace", timeout=15,- env=env,- )- output = (result.stdout or "") + (result.stderr or "")- if "ok: true" in output:- print("✅ Twitter access works!")- else:- print("[!] Auth check failed (cookies might be wrong)")- except Exception as e:- print(f"[X] Failed: {e}")else:print("[X] Could not find auth_token and ct0 in your input.")print(" Accepted formats:")print(" 1. agent-reach configure twitter-cookies AUTH_TOKEN CT0")print(' 2. agent-reach configure twitter-cookies "auth_token=xxx; ct0=yyy; ..."')+ raise SystemExit(1)elif args.key == "youtube-cookies":config.set("youtube_cookies_from", value)@@ -1190,7 +1306,8 @@ def _cmd_configure(args):print(" yt-dlp will use cookies from this browser for age-restricted/member videos.")elif args.key == "xhs-cookies":- _configure_xhs_cookies(value)+ if not _configure_xhs_cookies(value):+ raise SystemExit(1)elif args.key == "github-token":config.set("github_token", value)@@ -1210,11 +1327,12 @@ def _cmd_transcribe(args):from pathlib import Pathfrom agent_reach.transcribe import TranscribeError, transcribe+ from agent_reach.utils.text import scrub_url_credentialstry:text = transcribe(args.source, provider=args.provider)except TranscribeError as e:- print(f"❌ {e}")+ print(f"❌ {scrub_url_credentials(e)}")sys.exit(1)if args.output:@@ -1245,7 +1363,7 @@ def _parse_twitter_cookie_input(value: str):return auth_token, ct0-def _configure_xhs_cookies(value):+def _configure_xhs_cookies(value) -> bool:"""Import cookies into xiaohongshu-mcp Docker container.Accepts two formats:@@ -1265,7 +1383,7 @@ def _configure_xhs_cookies(value):if not value:print("[X] Missing cookie value.")print(" Usage: agent-reach configure xhs-cookies '<cookie JSON or header string>'")- return+ return False# Detect format and parsecookies_json = None@@ -1275,20 +1393,54 @@ def _configure_xhs_cookies(value):try:parsed = json.loads(value)if isinstance(parsed, list) and parsed:- # Validate it looks like cookie objects- first = parsed[0]- if isinstance(first, dict) and "name" in first and "value" in first:- cookies_json = json.dumps(parsed)- print(f" Parsed {len(parsed)} cookies from JSON format")- else:- print("[X] JSON array doesn't contain cookie objects (need name/value fields)")- return+ from agent_reach.utils.url import domain_matches++ valid_cookies = []+ ignored_domains = 0+ ignored_invalid = 0+ for cookie in parsed:+ if (+ not isinstance(cookie, dict)+ or not isinstance(cookie.get("name"), str)+ or not cookie["name"]+ or not isinstance(cookie.get("value"), str)+ ):+ ignored_invalid += 1+ continue+ if not domain_matches(+ cookie.get("domain", ""),+ "xiaohongshu.com",+ ):+ ignored_domains += 1+ continue+ valid_cookies.append(cookie)++ if ignored_domains:+ print(+ f" [!] 已忽略 {ignored_domains} 个非 "+ "xiaohongshu.com 域 Cookie"+ )+ if ignored_invalid:+ print(+ f" [!] 已忽略 {ignored_invalid} 个格式无效的 Cookie"+ )+ if not valid_cookies:+ print(+ "[X] Cookie-Editor JSON 中没有有效的 "+ "xiaohongshu.com 域 Cookie"+ )+ return False+ cookies_json = json.dumps(valid_cookies)+ print(+ f" Parsed {len(valid_cookies)} "+ "xiaohongshu.com cookies from JSON format"+ )else:print("[X] Empty or invalid JSON array")- return+ return Falseexcept json.JSONDecodeError as e:print(f"[X] Invalid JSON: {e}")- return+ return False# Header String format: "key1=val1; key2=val2; ..."if cookies_json is None and "=" in value:@@ -1318,49 +1470,38 @@ def _configure_xhs_cookies(value):print(f" Parsed {len(cookies)} cookies from Header String format")else:print("[X] Could not parse any cookies from input")- return+ return Falseif not cookies_json:print("[X] Could not parse cookies. Accepted formats:")print(' 1. JSON array: \'[{"name":"x","value":"y","domain":".xiaohongshu.com",...}]\'')print(' 2. Header String: "key1=val1; key2=val2; ..."')- return+ return False# Find the containerdocker = shutil.which("docker")if not docker:# No Docker - write to a local file for manual import.- # Create with 0o600 atomically so the file is never world-readable- # between open() and a follow-up chmod() (same pattern Config.save()- # uses in config.py).- import stat+ from pathlib import Path- from agent_reach.utils.paths import make_private_dir+ from agent_reach.utils.paths import (+ PrivatePathError,+ atomic_write_private_text,+ )- cookie_dir = make_private_dir(os.path.expanduser("~/.agent-reach"))- cookie_path = cookie_dir / "xhs-cookies.json"+ cookie_path = (+ Path(os.path.expanduser("~/.agent-reach"))+ / "xhs-cookies.json"+ )try:- fd = os.open(- str(cookie_path),- os.O_WRONLY | os.O_CREAT | os.O_TRUNC,- stat.S_IRUSR | stat.S_IWUSR, # 0o600- )- if os.name != "nt":- os.chmod(cookie_path, stat.S_IRUSR | stat.S_IWUSR)- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(cookies_json)- except OSError:- # Windows / unsupported flags — fall back to plain open + chmod.- with open(cookie_path, "w", encoding="utf-8") as f:- f.write(cookies_json)- try:- os.chmod(cookie_path, 0o600)- except OSError:- pass+ atomic_write_private_text(cookie_path, cookies_json)+ except (OSError, PrivatePathError) as exc:+ print(f"[X] Could not save cookies safely: {exc}")+ return Falseprint(f" Cookies saved to {cookie_path}")print(" Docker not found. Copy manually:")print(f" docker cp {cookie_path} xiaohongshu-mcp:/app/data/cookies.json")- return+ return True# Check if xiaohongshu-mcp container is runningtry:@@ -1373,10 +1514,10 @@ def _configure_xhs_cookies(value):print("[X] xiaohongshu-mcp container is not running.")print(" Start it first:")print(" docker run -d --name xiaohongshu-mcp -p 18060:18060 xpzouying/xiaohongshu-mcp")- return+ return Falseexcept Exception as e:print(f"[X] Could not check Docker: {e}")- return+ return False# Find the cookies path inside the containertry:@@ -1406,7 +1547,7 @@ def _configure_xhs_cookies(value):if result.returncode != 0:print(f"[X] Failed to copy cookies: {result.stderr}")- return+ return Falseprint(f"✅ Cookies written to {container_name}:{cookie_path_in_container}")# Restart container so it reloads cookies from disk@@ -1422,7 +1563,7 @@ def _configure_xhs_cookies(value):print(f" Restart manually: docker restart {container_name}")except Exception as e:print(f"[X] Failed to write cookies: {e}")- return+ return Falsefinally:if tmp_path:try:@@ -1451,6 +1592,7 @@ def _configure_xhs_cookies(value):print(f"[!] Could not verify: {e}")else:print(" (mcporter not found, skipping verification)")+ return Truedef _cmd_uninstall(args):@@ -1470,6 +1612,7 @@ def _cmd_uninstall(args):print()removed_any = False+ mcporter_cleanup_skipped = False# ── 1. Config directory (~/.agent-reach/) ──config_dir = os.path.expanduser("~/.agent-reach")@@ -1490,6 +1633,22 @@ def _cmd_uninstall(args):else:print(f" Skipping config directory (--keep-config): {config_dir}")+ # Opt-in legacy copies may be shared with upstream tools. Without a+ # provenance marker it would be unsafe to delete them automatically, so+ # surface every exact path that may still contain Twitter credentials.+ legacy_credential_paths = (+ os.path.expanduser("~/.config/xfetch/session.json"),+ os.path.expanduser("~/.config/bird/credentials.env"),+ )+ present_legacy_paths = [+ path for path in legacy_credential_paths if os.path.lexists(path)+ ]+ if present_legacy_paths:+ print(" [!] 检测到可选的 Twitter legacy 凭据副本;不会自动删除:")+ for path in present_legacy_paths:+ print(f" {path}")+ print(" 若确认不再被 xfetch/bird 使用,请手动删除。")+# ── 2. Skill files ──skill_dirs = [("~/.openclaw/skills/agent-reach", "OpenClaw"),@@ -1515,23 +1674,46 @@ def _cmd_uninstall(args):# ── 3. mcporter MCP entries ──if shutil.which("mcporter"):- for mcp_name in ("exa", "xiaohongshu"):- try:- r = subprocess.run(- ["mcporter", "list"], capture_output=True, encoding="utf-8", errors="replace", timeout=10+ from agent_reach.channels.mcporter import (+ McporterConfigError,+ configured_server_names,+ )++ try:+ result = subprocess.run(+ [+ "mcporter",+ "config",+ "list",+ "--json",+ ],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=10,+ )+ if result.returncode != 0:+ raise McporterConfigError("mcporter config query failed")+ server_names = configured_server_names(result.stdout)+ except (+ McporterConfigError,+ OSError,+ subprocess.TimeoutExpired,+ ):+ mcporter_cleanup_skipped = True+ print(+ " [!] 无法安全核验 mcporter 配置来源;"+ "不会自动删除 exa/xiaohongshu 项。"+ )+ else:+ for mcp_name in ("exa", "xiaohongshu"):+ if mcp_name not in server_names:+ continue+ mcporter_cleanup_skipped = True+ print(+ f" [!] mcporter entry {mcp_name} 来源无法证明由 "+ "Agent Reach 管理;已保留。若确认不再需要,请手动移除。")- if mcp_name in r.stdout:- if dry_run:- print(f"[dry-run] Would remove mcporter entry: {mcp_name}")- else:- subprocess.run(- ["mcporter", "config", "remove", mcp_name],- capture_output=True, encoding="utf-8", errors="replace", timeout=10,- )- print(f" Removed mcporter entry: {mcp_name}")- removed_any = True- except Exception:- pass# ── 4. Summary and optional steps ──print()@@ -1541,6 +1723,8 @@ def _cmd_uninstall(args):else:if removed_any:print("Agent Reach data removed.")+ elif mcporter_cleanup_skipped:+ print("No proven Agent Reach-managed mcporter data was removed.")else:print("Nothing to remove — already clean.")@@ -1594,10 +1778,21 @@ def _cmd_setup():print()else:try:+ from agent_reach.channels.mcporter import (+ McporterConfigError,+ configured_server_names,+ )+r = subprocess.run(- ["mcporter", "config", "list"], capture_output=True, encoding="utf-8", errors="replace", timeout=10+ ["mcporter", "config", "list", "--json"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=10,)- if "exa" in r.stdout.lower():+ if r.returncode != 0:+ raise McporterConfigError("mcporter 配置查询失败")+ if "exa" in configured_server_names(r.stdout):print(" 当前状态: ✅ 已配置")else:print(" 当前状态: -- 未配置")@@ -1860,7 +2055,7 @@ def _cmd_watch():from agent_reach.doctor import check_allfrom agent_reach import __version__- config = Config()+ config = Config(read_only=True)issues = []# Check channelsdiff --git a/agent_reach/cookie_extract.py b/agent_reach/cookie_extract.pyindex 03a90085..89564d71 100644--- a/agent_reach/cookie_extract.py+++ b/agent_reach/cookie_extract.py@@ -61,6 +61,7 @@ _PLATFORM_SPECS_BY_KEY: Dict[str, PlatformSpec] = {}SUPPORTED_BROWSERS = ("chrome", "firefox", "edge", "brave", "opera")PROFILE_SELECTABLE_BROWSERS = ("chrome", "edge", "brave")+_MAX_XFETCH_SESSION_BYTES = 64 * 1024_COOKIE_EDITOR_ONLY = {"twitter": "twitter-cookies","xhs": "xhs-cookies",@@ -330,31 +331,22 @@ def extract_all(return results-def _open_owner_only(path: str):- """Open *path* for writing, atomically creating it with mode 0o600.+def _read_xfetch_session(path: Path) -> dict:+ """Read a small regular legacy session file without following symlinks."""+ import json- Mirrors the pattern used by Config.save() in config.py: O_WRONLY|O_CREAT|- O_TRUNC + an explicit mode argument so the file is never briefly- world-readable between open() and a later os.chmod(). On Windows (or any- OS that rejects the open flags) we fall back to a plain open().- """- import os- import stat+ from agent_reach.utils.paths import read_small_text_no_follow- try:- fd = os.open(- path,- os.O_WRONLY | os.O_CREAT | os.O_TRUNC,- stat.S_IRUSR | stat.S_IWUSR, # 0o600- )- if os.name != "nt":- os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)- return os.fdopen(fd, "w", encoding="utf-8")- except OSError:- handle = open(path, "w", encoding="utf-8")- if os.name != "nt":- os.chmod(path, 0o600)- return handle+ payload = read_small_text_no_follow(+ path,+ max_bytes=_MAX_XFETCH_SESSION_BYTES,+ )+ if payload is None:+ return {}+ loaded = json.loads(payload)+ if not isinstance(loaded, dict):+ raise ValueError("xfetch 会话文件必须是 JSON object")+ return loadeddef _sync_xfetch_session(auth_token: str, ct0: str) -> bool:@@ -363,22 +355,21 @@ def _sync_xfetch_session(auth_token: str, ct0: str) -> bool:import ostry:- from agent_reach.utils.paths import make_private_dir+ from agent_reach.utils.paths import (+ atomic_write_private_text,+ make_private_dir,+ )xfetch_dir = os.path.join(os.path.expanduser("~"), ".config", "xfetch")make_private_dir(xfetch_dir)- session_path = os.path.join(xfetch_dir, "session.json")- session_data: dict = {}- if os.path.exists(session_path):- try:- with open(session_path, "r", encoding="utf-8") as sf:- session_data = json.load(sf)- except (json.JSONDecodeError, OSError):- session_data = {}+ session_path = Path(xfetch_dir) / "session.json"+ session_data = _read_xfetch_session(session_path)session_data["authToken"] = auth_tokensession_data["ct0"] = ct0- with _open_owner_only(session_path) as sf:- json.dump(session_data, sf, indent=2)+ atomic_write_private_text(+ session_path,+ json.dumps(session_data, indent=2),+ )return Trueexcept Exception:# Non-fatal: agent-reach config is the source of truth, xfetch sync is best-effort@@ -397,14 +388,19 @@ def _sync_bird_env(auth_token: str, ct0: str) -> bool:import shlextry:- from agent_reach.utils.paths import make_private_dir+ from agent_reach.utils.paths import (+ atomic_write_private_text,+ make_private_dir,+ )bird_dir = os.path.join(os.path.expanduser("~"), ".config", "bird")make_private_dir(bird_dir)env_path = os.path.join(bird_dir, "credentials.env")- with _open_owner_only(env_path) as f:- f.write(f"AUTH_TOKEN={shlex.quote(auth_token)}\n")- f.write(f"CT0={shlex.quote(ct0)}\n")+ atomic_write_private_text(+ env_path,+ f"AUTH_TOKEN={shlex.quote(auth_token)}\n"+ f"CT0={shlex.quote(ct0)}\n",+ )return Trueexcept Exception:# Non-fatal: agent-reach config is the source of truth, bird env sync is best-effortdiff --git a/tests/test_cli.py b/tests/test_cli.pyindex ddcdf41c..6981957c 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -115,34 +115,34 @@ class TestCLI:assert auth_token == "token123"assert ct0 == "ct0abc"- def test_twitter_config_verification_preserves_existing_env_priority(+ def test_twitter_config_does_not_run_unsafe_verification_or_mutate_env(self, monkeypatch, capsys):monkeypatch.setenv("TWITTER_AUTH_TOKEN", "shell-auth")monkeypatch.setenv("TWITTER_CT0", "shell-ct0")monkeypatch.setattr(shutil, "which", lambda name: "/bin/twitter")- calls = []-- def fake_run(cmd, **kwargs):- calls.append((cmd, kwargs))- return subprocess.CompletedProcess(cmd, 0, "ok: true\n", "")-- monkeypatch.setattr(subprocess, "run", fake_run)+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *_args, **_kwargs: pytest.fail(+ "configure must not execute twitter status"+ ),+ )cli._cmd_configure(Namespace(from_browser=None,key="twitter-cookies",value=["saved-auth", "saved-ct0"],+ sync_legacy_twitter=False,))- child_env = calls[0][1]["env"]- assert child_env["TWITTER_AUTH_TOKEN"] == "shell-auth"- assert child_env["TWITTER_CT0"] == "shell-ct0"+ output = capsys.readouterr().out+ assert "未实时验证" in output+ assert "不会执行 `twitter status`" in outputassert cli.os.environ["TWITTER_AUTH_TOKEN"] == "shell-auth"assert cli.os.environ["TWITTER_CT0"] == "shell-ct0"- assert "Twitter access works" in capsys.readouterr().outdef test_install_rdt_cli_prefers_github_source(self, monkeypatch, capsys):state = {"rdt_installed": False}diff --git a/tests/test_p0_cli.py b/tests/test_p0_cli.pyindex 800db005..1003b0e9 100644--- a/tests/test_p0_cli.py+++ b/tests/test_p0_cli.py@@ -3,6 +3,7 @@from __future__ import annotations+import jsonimport subprocessimport sysfrom argparse import Namespace@@ -14,8 +15,9 @@ import agent_reach.cli as cliclass _MemoryConfig:- def __init__(self):+ def __init__(self, *args, **kwargs):self.data = {}+ self.read_only = kwargs.get("read_only", False)def get(self, key, default=None):return self.data.get(key, default)@@ -87,6 +89,40 @@ def test_browser_cookie_import_passes_explicit_platform_and_profile(assert "Cookies configured" in capsys.readouterr().out+def test_browser_cookie_import_without_cookie_exits_one(monkeypatch, capsys):+ """An unsuccessful browser import is a CLI failure, not a silent success."""+ import agent_reach.config as config_module+ import agent_reach.cookie_extract as cookie_extract++ monkeypatch.setattr(config_module, "Config", _MemoryConfig)+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)+ monkeypatch.setattr(+ cookie_extract,+ "configure_from_browser",+ lambda *_args, **_kwargs: [+ ("Xueqiu", False, "No Xueqiu cookies found")+ ],+ )+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "agent-reach",+ "configure",+ "--from-browser",+ "chrome",+ "--platform",+ "xueqiu",+ ],+ )++ with pytest.raises(SystemExit) as exc:+ cli.main()++ assert exc.value.code == 1+ assert "No cookies found" in capsys.readouterr().out++@pytest.mark.parametrize(("platform", "manual_key"),[("twitter", "twitter-cookies"), ("xiaohongshu", "xhs-cookies")],@@ -167,6 +203,52 @@ def test_install_does_not_implicitly_read_browser_cookies(monkeypatch, tmp_path,assert "Importing cookies from browser" not in output+def test_install_rejects_unknown_channel_before_side_effects(+ monkeypatch, capsys+):+ """A typo in --channels fails before config or system installation starts."""+ import agent_reach.config as config_module++ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)+ monkeypatch.setattr(+ config_module,+ "Config",+ lambda *_args, **_kwargs: pytest.fail(+ "Config must not be constructed for an invalid channel"+ ),+ )+ monkeypatch.setattr(+ cli,+ "_install_system_deps",+ lambda: pytest.fail("system dependencies must not be installed"),+ )+ monkeypatch.setattr(+ cli.os,+ "makedirs",+ lambda *_args, **_kwargs: pytest.fail(+ "install directories must not be created"+ ),+ )+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "agent-reach",+ "install",+ "--env",+ "local",+ "--channels",+ "twiter",+ ],+ )++ with pytest.raises(SystemExit) as exc:+ cli.main()++ assert exc.value.code == 2+ assert "twiter" in capsys.readouterr().err++@pytest.mark.parametrize("sync_legacy", [False, True])def test_manual_twitter_cookie_legacy_copies_are_opt_in(monkeypatch, capsys, sync_legacy@@ -184,12 +266,12 @@ def test_manual_twitter_cookie_legacy_copies_are_opt_in(monkeypatch.setattr(cookie_extract,"_sync_xfetch_session",- lambda auth, ct0: calls.append(("xfetch", auth, ct0)),+ lambda auth, ct0: calls.append(("xfetch", auth, ct0)) or True,)monkeypatch.setattr(cookie_extract,"_sync_bird_env",- lambda auth, ct0: calls.append(("bird", auth, ct0)),+ lambda auth, ct0: calls.append(("bird", auth, ct0)) or True,)cli._cmd_configure(@@ -208,6 +290,87 @@ def test_manual_twitter_cookie_legacy_copies_are_opt_in(assert ("Legacy copies written" in output) is sync_legacy+ ("xfetch_ok", "bird_ok", "written_count", "failed_count"),+ [+ (True, True, 2, 0),+ (True, False, 1, 1),+ (False, True, 1, 1),+ (False, False, 0, 2),+ ],+)+def test_legacy_twitter_sync_reports_only_confirmed_results(+ monkeypatch,+ capsys,+ xfetch_ok,+ bird_ok,+ written_count,+ failed_count,+):+ import shutil++ import agent_reach.config as config_module+ import agent_reach.cookie_extract as cookie_extract++ monkeypatch.setattr(config_module, "Config", _MemoryConfig)+ monkeypatch.setattr(shutil, "which", lambda _name: None)+ monkeypatch.setattr(+ cookie_extract,+ "_sync_xfetch_session",+ lambda *_args: xfetch_ok,+ )+ monkeypatch.setattr(+ cookie_extract,+ "_sync_bird_env",+ lambda *_args: bird_ok,+ )++ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key="twitter-cookies",+ value=["auth-value", "ct0-value"],+ sync_legacy_twitter=True,+ )+ )++ output = capsys.readouterr().out+ assert output.count(" written:") == written_count+ assert output.count(" failed:") == failed_count+++def test_twitter_configure_never_runs_upstream_browser_fallback(+ monkeypatch, capsys+):+ import shutil++ import agent_reach.config as config_module++ monkeypatch.setattr(config_module, "Config", _MemoryConfig)+ monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/twitter")+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *_args, **_kwargs: pytest.fail(+ "configure must not execute twitter status"+ ),+ )++ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key="twitter-cookies",+ value=["auth-value", "ct0-value"],+ sync_legacy_twitter=False,+ )+ )++ output = capsys.readouterr().out+ assert "已保存" in output+ assert "未实时验证" in output+ assert "Twitter access works" not in output++def test_doctor_never_installs_or_updates_skill(monkeypatch, capsys):"""A diagnostic command is read-only and must not mutate agent instructions."""import agent_reach.config as config_module@@ -226,6 +389,51 @@ def test_doctor_never_installs_or_updates_skill(monkeypatch, capsys):assert "report" in capsys.readouterr().out+def test_watch_uses_read_only_config(monkeypatch, capsys):+ """Scheduled diagnostics must enforce the same no-write boundary as doctor."""+ import agent_reach.config as config_module++ created = []++ class RecordingConfig(_MemoryConfig):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ created.append(self)++ class _Release:+ status_code = 200++ @staticmethod+ def json():+ return {"tag_name": "v0.0.0", "body": ""}++ monkeypatch.setattr(config_module, "Config", RecordingConfig)+ monkeypatch.setattr(+ "agent_reach.doctor.check_all",+ lambda _config: {+ "web": {+ "status": "ok",+ "name": "网页",+ "message": "可用",+ "tier": 0,+ "backends": ["Jina Reader"],+ "active_backend": "Jina Reader",+ }+ },+ )+ monkeypatch.setattr(+ cli,+ "_github_get_with_retry",+ lambda *_args, **_kwargs: (_Release(), None, 1),+ )++ cli._cmd_watch()++ assert len(created) == 1+ assert created[0].read_only is True+ assert "全部正常" in capsys.readouterr().out++def _docker_result(args, returncode=0, stdout="", stderr=""):return subprocess.CompletedProcess(args, returncode, stdout, stderr)@@ -289,16 +497,17 @@ def test_xhs_docker_cookie_copy_always_removes_temporary_file(monkeypatch, capsyassert "Failed to copy cookies: copy failed" in capsys.readouterr().out-def test_system_install_uses_platform_specific_ytdlp_config(+def test_system_install_uses_ytdlp_first_user_config(monkeypatch, tmp_path):- """macOS installation writes the same config path that doctor reads."""+ """Installer writes the first config directory that real yt-dlp reads."""import shutilimport agent_reach.utils.paths as pathsmonkeypatch.setattr(paths.sys, "platform", "darwin")monkeypatch.setattr(paths.Path, "home", classmethod(lambda cls: tmp_path))+ monkeypatch.delenv("XDG_CONFIG_HOME")monkeypatch.setattr(cli.os.path,"expanduser",@@ -309,26 +518,85 @@ def test_system_install_uses_platform_specific_ytdlp_config(monkeypatch.setattr(shutil,"which",- lambda name: f"/usr/bin/{name}" if name in {"gh", "node", "npm"} else None,+ lambda name: f"/usr/bin/{name}"+ if name in {"gh", "node", "npm", "yt-dlp"}+ else None,)- monkeypatch.setattr(- subprocess,- "run",- lambda args, **_kwargs: _docker_result(++ def fake_run(args, **_kwargs):+ if args[-1:] == ["--version"] and args[0].endswith("yt-dlp"):+ return _docker_result(args, stdout="2026.07.04\n")+ return _docker_result(args,- stdout="/tmp/npm-root\n" if args[1:3] == ["root", "-g"] else "",- ),- )+ stdout="/tmp/npm-root\n"+ if args[1:3] == ["root", "-g"]+ else "",+ )++ monkeypatch.setattr(subprocess, "run", fake_run)cli._install_system_deps()- config_path = (- tmp_path / "Library" / "Application Support" / "yt-dlp" / "config"- )+ config_path = tmp_path / ".config" / "yt-dlp" / "config"assert config_path.read_text(encoding="utf-8") == "--js-runtimes node\n"assert not (tmp_path / ".legacy-config" / "config").exists()+ "yt_dlp_version",+ [None, "2025.10.22", "not-a-stable-version"],+)+def test_system_install_never_writes_unsupported_ytdlp_flag(+ monkeypatch, tmp_path, yt_dlp_version+):+ """A missing, old, or unknown yt-dlp must not receive a fatal option."""+ import shutil++ import agent_reach.utils.paths as paths++ monkeypatch.setattr(paths.sys, "platform", "darwin")+ monkeypatch.setattr(paths.Path, "home", classmethod(lambda cls: tmp_path))+ monkeypatch.delenv("XDG_CONFIG_HOME")++ def fake_which(name):+ if name in {"gh", "node", "npm"}:+ return f"/usr/bin/{name}"+ if name == "yt-dlp" and yt_dlp_version is not None:+ return "/usr/bin/yt-dlp"+ return None++ def fake_run(args, **_kwargs):+ if args[-1:] == ["--version"] and args[0].endswith("yt-dlp"):+ return _docker_result(args, stdout=f"{yt_dlp_version}\n")+ return _docker_result(+ args,+ stdout="/tmp/npm-root\n"+ if args[1:3] == ["root", "-g"]+ else "",+ )++ monkeypatch.setattr(shutil, "which", fake_which)+ monkeypatch.setattr(subprocess, "run", fake_run)++ cli._install_system_deps()++ config_path = tmp_path / ".config" / "yt-dlp" / "config"+ assert not config_path.exists()+++def test_update_guide_preserves_ytdlp_default_extra():+ """Every documented upgrade path keeps yt-dlp's default/EJS dependencies."""+ guide = (+ Path(__file__).resolve().parents[1] / "docs" / "update.md"+ ).read_text(encoding="utf-8")+ update_line = next(+ line for line in guide.splitlines() if line.startswith("which yt-dlp")+ )++ assert update_line.count("yt-dlp[default]") == 3+ assert "pipx install --force 'yt-dlp[default]'" in update_line++def test_mcporter_install_adds_exa_to_home_scope(monkeypatch):"""Installer config remains available across working directories."""import shutil@@ -343,7 +611,7 @@ def test_mcporter_install_adds_exa_to_home_scope(monkeypatch):def fake_run(args, **_kwargs):calls.append(args)- if args[:3] == ["mcporter", "config", "list"]:+ if args == ["mcporter", "config", "list", "--json"]:return _docker_result(args, stdout='{"servers": []}')return _docker_result(args)@@ -360,3 +628,276 @@ def test_mcporter_install_adds_exa_to_home_scope(monkeypatch):"--scope","home",] in calls+ assert ["mcporter", "config", "list", "--json"] in calls+++def test_mcporter_install_does_not_treat_metadata_as_exa_server(+ monkeypatch,+):+ """Only a server object's exact name may suppress Exa setup."""+ import json+ import shutil++ calls = []+ payload = {+ "servers": [+ {+ "name": "unrelated",+ "source": {"path": "/tmp/exa-project/mcporter.json"},+ "url": "https://example.test/?note=exa",+ }+ ]+ }++ monkeypatch.setattr(+ shutil,+ "which",+ lambda name: "/usr/bin/mcporter" if name == "mcporter" else None,+ )++ def fake_run(args, **_kwargs):+ calls.append(args)+ if args == ["mcporter", "config", "list", "--json"]:+ return _docker_result(args, stdout=json.dumps(payload))+ return _docker_result(args)++ monkeypatch.setattr(subprocess, "run", fake_run)++ cli._install_mcporter()++ assert [+ "mcporter",+ "config",+ "add",+ "exa",+ "https://mcp.exa.ai/mcp",+ "--scope",+ "home",+ ] in calls+++def test_server_xhs_install_never_recommends_qr_or_browser_extraction(+ monkeypatch, capsys+):+ """Project policy requires an explicit Cookie-Editor export for XHS."""+ monkeypatch.setattr(cli, "_detect_environment", lambda: "server")++ cli._install_xhs_deps()++ output = capsys.readouterr().out+ assert "Cookie-Editor" in output+ assert "configure xhs-cookies" in output+ assert "扫码" not in output+ assert "二维码" not in output+++def test_configure_usage_does_not_recommend_blocked_twitter_browser_import(+ capsys,+):+ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key=None,+ value=[],+ sync_legacy_twitter=False,+ )+ )++ output = capsys.readouterr().out+ assert "--platform xueqiu" in output+ assert "--platform twitter" not in output+++def test_configure_missing_value_exits_one(monkeypatch, capsys):+ """A selected config key without a value must fail at the CLI boundary."""+ import agent_reach.config as config_module++ monkeypatch.setattr(config_module, "Config", _MemoryConfig)+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)+ monkeypatch.setattr(+ sys,+ "argv",+ ["agent-reach", "configure", "github-token"],+ )++ with pytest.raises(SystemExit) as exc:+ cli.main()++ assert exc.value.code == 1+ assert "Missing value for github-token" in capsys.readouterr().out+++def test_twitter_cookie_parse_failure_exits_one(monkeypatch, capsys):+ """Malformed Twitter cookie input must not produce a successful CLI status."""+ import agent_reach.config as config_module++ config = _MemoryConfig()+ monkeypatch.setattr(config_module, "Config", lambda: config)+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)+ monkeypatch.setattr(+ sys,+ "argv",+ ["agent-reach", "configure", "twitter-cookies", "not-a-cookie"],+ )++ with pytest.raises(SystemExit) as exc:+ cli.main()++ assert exc.value.code == 1+ assert "Could not find auth_token and ct0" in capsys.readouterr().out+ assert config.data == {}+++def test_profile_rejects_unsupported_browser_before_cookie_backend(+ monkeypatch, capsys+):+ import agent_reach.cookie_extract as cookie_extract++ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)+ monkeypatch.setattr(+ cookie_extract,+ "configure_from_browser",+ lambda *_args, **_kwargs: pytest.fail(+ "unsupported profile must fail before browser access"+ ),+ )+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "agent-reach",+ "configure",+ "--from-browser",+ "firefox",+ "--platform",+ "xueqiu",+ "--profile",+ "default-release",+ ],+ )++ with pytest.raises(SystemExit) as exc:+ cli.main()++ assert exc.value.code == 2+ assert "Chrome/Edge/Brave" in capsys.readouterr().err+++def test_missing_profile_is_clean_cli_error_without_traceback(+ monkeypatch, capsys+):+ import agent_reach.config as config_module+ import agent_reach.cookie_extract as cookie_extract++ monkeypatch.setattr(config_module, "Config", _MemoryConfig)+ monkeypatch.setattr(+ cookie_extract,+ "configure_from_browser",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ ValueError(+ "Profile 'secret-profile' not found for chrome; "+ "https://user:[email protected]/?token=hidden"+ )+ ),+ )++ with pytest.raises(SystemExit) as exc:+ cli._cmd_configure(+ Namespace(+ from_browser="chrome",+ platform="xueqiu",+ profile="Missing",+ key=None,+ value=[],+ sync_legacy_twitter=False,+ )+ )++ error = capsys.readouterr().err+ assert exc.value.code == 2+ assert "Traceback" not in error+ assert "user:pass" not in error+ assert "hidden" not in error+ assert "***" in error+++def test_install_dry_run_does_not_create_agent_reach_directory(+ isolated_home, monkeypatch+):+ monkeypatch.setattr(cli, "_install_system_deps_dryrun", lambda: None)++ cli._cmd_install(+ Namespace(+ env="local",+ proxy="",+ safe=False,+ dry_run=True,+ channels="",+ )+ )++ assert not (isolated_home / ".agent-reach").exists()+++def test_uninstall_warns_about_opt_in_legacy_credential_copies(+ isolated_home, capsys+):+ xfetch = isolated_home / ".config" / "xfetch" / "session.json"+ bird = isolated_home / ".config" / "bird" / "credentials.env"+ xfetch.parent.mkdir(parents=True)+ bird.parent.mkdir(parents=True)+ xfetch.write_text("{}", encoding="utf-8")+ bird.write_text("AUTH_TOKEN=secret\n", encoding="utf-8")++ cli._cmd_uninstall(Namespace(dry_run=True, keep_config=False))++ output = capsys.readouterr().out+ assert str(xfetch) in output+ assert str(bird) in output+ assert "不会自动删除" in output+ assert xfetch.exists()+ assert bird.exists()+++def test_uninstall_preserves_mcporter_entries_without_agent_reach_provenance(+ isolated_home, monkeypatch, capsys+):+ """Names and endpoints alone do not prove Agent Reach owns an MCP entry."""+ calls = []+ payload = {+ "servers": [+ {+ "name": "exa",+ "source": {+ "kind": "local",+ "path": str(isolated_home / ".mcporter" / "mcporter.json"),+ },+ "baseUrl": "https://mcp.exa.ai/mcp",+ },+ {+ "name": "xiaohongshu",+ "source": {+ "kind": "local",+ "path": str(isolated_home / ".mcporter" / "mcporter.json"),+ },+ "baseUrl": "http://localhost:18060/mcp",+ },+ ]+ }++ monkeypatch.setattr(+ "shutil.which",+ lambda name: "/usr/bin/mcporter" if name == "mcporter" else None,+ )++ def fake_run(args, **_kwargs):+ calls.append(args)+ return _docker_result(args, stdout=json.dumps(payload))++ monkeypatch.setattr(subprocess, "run", fake_run)++ cli._cmd_uninstall(Namespace(dry_run=False, keep_config=True))++ output = capsys.readouterr().out+ assert not any("remove" in call for call in calls)+ assert "来源无法证明" in outputdiff --git a/tests/test_paths.py b/tests/test_paths.pyindex 95f83af3..1f3425f1 100644--- a/tests/test_paths.py+++ b/tests/test_paths.py@@ -2,6 +2,7 @@"""Behavior tests for cross-platform path and remediation helpers."""import subprocess+from pathlib import Pathfrom agent_reach.utils import paths@@ -11,6 +12,7 @@ def test_posix_ytdlp_fix_is_single_line_executable_and_idempotent():monkeypatch.setattr(paths.sys, "platform", "linux")monkeypatch.setattr(paths.Path, "home", classmethod(lambda cls: tmp_path))+ monkeypatch.delenv("XDG_CONFIG_HOME")command = paths.render_ytdlp_fix_command()@@ -20,3 +22,16 @@ def test_posix_ytdlp_fix_is_single_line_executable_and_idempotent(config = tmp_path / ".config" / "yt-dlp" / "config"assert config.read_text(encoding="utf-8") == "--js-runtimes node\n"+++def test_ytdlp_config_dir_matches_upstream_first_user_location(+ monkeypatch, tmp_path+):+ from yt_dlp.options import get_user_config_dirs++ config_home = tmp_path / "xdg-config"+ monkeypatch.setenv("XDG_CONFIG_HOME", str(config_home))++ expected = Path(next(get_user_config_dirs("yt-dlp")))++ assert paths.get_ytdlp_config_dir() == expecteddiff --git a/tests/test_private_file_writes.py b/tests/test_private_file_writes.pynew file mode 100644index 00000000..eb6b72ed--- /dev/null+++ b/tests/test_private_file_writes.py@@ -0,0 +1,421 @@+"""Security regressions for local credential and tool configuration writes."""++from __future__ import annotations++import json+import os+import stat+import subprocess+from argparse import Namespace++import pytest++from agent_reach import cli+from agent_reach.cookie_extract import _sync_bird_env, _sync_xfetch_session+from agent_reach.utils import paths++[email protected](os.name == "nt", reason="POSIX permission semantics")+def test_atomic_private_text_write_is_0600(tmp_path):+ target = tmp_path / "private" / "secret.txt"++ paths.atomic_write_private_text(target, "secret")++ assert stat.S_IMODE(target.stat().st_mode) == 0o600+ assert stat.S_IMODE(target.parent.stat().st_mode) == 0o700+++def test_atomic_private_text_write_preserves_old_file_on_replace_failure(+ tmp_path, monkeypatch+):+ target = tmp_path / "private" / "secret.txt"+ target.parent.mkdir()+ target.write_text("keep-old", encoding="utf-8")++ def fail_replace(*_args, **_kwargs):+ raise OSError("simulated replace failure")++ monkeypatch.setattr(paths.os, "replace", fail_replace)++ with pytest.raises(OSError, match="replace failure"):+ paths.atomic_write_private_text(target, "new-secret")++ assert target.read_text(encoding="utf-8") == "keep-old"+ assert list(target.parent.glob(".secret.txt.*.tmp")) == []+++def test_legacy_xfetch_sync_refuses_target_symlink(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ session_path = tmp_path / ".config" / "xfetch" / "session.json"+ session_path.parent.mkdir(parents=True)+ victim = tmp_path / "victim.json"+ victim.write_text('{"keep": "unchanged"}', encoding="utf-8")+ try:+ session_path.symlink_to(victim)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ assert _sync_xfetch_session("new-auth", "new-ct0") is False+ assert victim.read_text(encoding="utf-8") == '{"keep": "unchanged"}'+ assert session_path.is_symlink()+++def test_legacy_xfetch_sync_refuses_parent_symlink(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ config_dir = tmp_path / ".config"+ config_dir.mkdir()+ victim_dir = tmp_path / "victim-dir"+ victim_dir.mkdir()+ xfetch_dir = config_dir / "xfetch"+ try:+ xfetch_dir.symlink_to(victim_dir, target_is_directory=True)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ assert _sync_xfetch_session("new-auth", "new-ct0") is False+ assert not (victim_dir / "session.json").exists()+ assert xfetch_dir.is_symlink()+++def test_legacy_xfetch_sync_refuses_ancestor_symlink(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ victim_dir = tmp_path / "victim-config"+ victim_dir.mkdir()+ config_dir = tmp_path / ".config"+ try:+ config_dir.symlink_to(victim_dir, target_is_directory=True)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ assert _sync_xfetch_session("new-auth", "new-ct0") is False+ assert list(victim_dir.iterdir()) == []+ assert config_dir.is_symlink()+++def test_legacy_xfetch_sync_refuses_oversized_existing_session(+ tmp_path, monkeypatch+):+ monkeypatch.setenv("HOME", str(tmp_path))+ session_path = tmp_path / ".config" / "xfetch" / "session.json"+ session_path.parent.mkdir(parents=True)+ previous = json.dumps({"untrusted": "x" * (1024 * 1024)})+ session_path.write_text(previous, encoding="utf-8")++ assert _sync_xfetch_session("new-auth", "new-ct0") is False+ assert session_path.read_text(encoding="utf-8") == previous+++def test_legacy_bird_sync_refuses_target_symlink(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ env_path = tmp_path / ".config" / "bird" / "credentials.env"+ env_path.parent.mkdir(parents=True)+ victim = tmp_path / "victim.env"+ victim.write_text("KEEP=unchanged\n", encoding="utf-8")+ try:+ env_path.symlink_to(victim)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ assert _sync_bird_env("new-auth", "new-ct0") is False+ assert victim.read_text(encoding="utf-8") == "KEEP=unchanged\n"+ assert env_path.is_symlink()+++def test_xhs_cookie_editor_json_ignores_non_xhs_domains(+ tmp_path, monkeypatch, capsys+):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr("shutil.which", lambda name: None)+ exported = [+ {+ "name": "web_session",+ "value": "valid-root",+ "domain": ".xiaohongshu.com",+ "path": "/",+ },+ {+ "name": "a1",+ "value": "valid-subdomain",+ "domain": "www.xiaohongshu.com",+ "path": "/",+ },+ {+ "name": "foreign",+ "value": "must-not-persist",+ "domain": ".example.com",+ "path": "/",+ },+ {+ "name": "lookalike",+ "value": "must-not-persist",+ "domain": ".notxiaohongshu.com",+ "path": "/",+ },+ ]++ cli._configure_xhs_cookies(json.dumps(exported))++ cookie_path = tmp_path / ".agent-reach" / "xhs-cookies.json"+ saved = json.loads(cookie_path.read_text(encoding="utf-8"))+ assert [cookie["name"] for cookie in saved] == ["web_session", "a1"]+ output = capsys.readouterr().out+ assert "忽略" in output+ assert "2" in output+++def test_xhs_cookie_editor_json_fails_without_valid_xhs_cookie(+ tmp_path, monkeypatch, capsys+):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(+ "shutil.which",+ lambda name: pytest.fail("invalid cookies must fail before tool lookup"),+ )+ exported = [+ {+ "name": "session",+ "value": "foreign",+ "domain": ".example.com",+ },+ {+ "name": "lookalike",+ "value": "foreign",+ "domain": ".xiaohongshu.com.evil.test",+ },+ ]++ monkeypatch.setattr("agent_reach.config.Config", lambda: object())+ with pytest.raises(SystemExit) as exc:+ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key="xhs-cookies",+ value=[json.dumps(exported)],+ sync_legacy_twitter=False,+ )+ )++ assert exc.value.code == 1+ assert not (tmp_path / ".agent-reach" / "xhs-cookies.json").exists()+ output = capsys.readouterr().out+ assert "没有有效的 xiaohongshu.com" in output+++def test_xhs_local_fallback_refuses_target_symlink(+ tmp_path, monkeypatch, capsys+):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr("shutil.which", lambda name: None)+ cookie_path = tmp_path / ".agent-reach" / "xhs-cookies.json"+ cookie_path.parent.mkdir()+ victim = tmp_path / "victim.json"+ victim.write_text('{"keep": "unchanged"}', encoding="utf-8")+ try:+ cookie_path.symlink_to(victim)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ result = cli._configure_xhs_cookies("web_session=xhs-secret")++ assert result is False+ assert victim.read_text(encoding="utf-8") == '{"keep": "unchanged"}'+ assert cookie_path.is_symlink()+ assert "Could not save cookies" in capsys.readouterr().out+++def test_xhs_docker_success_via_configure_command_does_not_exit(+ monkeypatch, capsys+):+ monkeypatch.setattr("agent_reach.config.Config", lambda: object())+ monkeypatch.setattr(+ "shutil.which",+ lambda name: "/usr/bin/docker" if name == "docker" else None,+ )++ def fake_run(args, **_kwargs):+ if args[1] == "ps":+ return subprocess.CompletedProcess(+ args, 0, stdout="xiaohongshu-mcp\n", stderr=""+ )+ if args[1:3] == ["exec", "xiaohongshu-mcp"]:+ return subprocess.CompletedProcess(+ args, 0, stdout="/app/data/cookies.json\n", stderr=""+ )+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")++ monkeypatch.setattr(subprocess, "run", fake_run)++ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key="xhs-cookies",+ value=["web_session=xhs-secret"],+ sync_legacy_twitter=False,+ )+ )++ assert "Cookies written to" in capsys.readouterr().out+++def test_xhs_docker_failure_via_configure_command_exits_one(+ monkeypatch, capsys+):+ monkeypatch.setattr("agent_reach.config.Config", lambda: object())+ monkeypatch.setattr(+ "shutil.which",+ lambda name: "/usr/bin/docker" if name == "docker" else None,+ )++ def fake_run(args, **_kwargs):+ if args[1] == "ps":+ return subprocess.CompletedProcess(+ args, 0, stdout="xiaohongshu-mcp\n", stderr=""+ )+ if args[1:3] == ["exec", "xiaohongshu-mcp"]:+ return subprocess.CompletedProcess(+ args, 0, stdout="/app/data/cookies.json\n", stderr=""+ )+ if args[1] == "cp":+ return subprocess.CompletedProcess(+ args, 1, stdout="", stderr="copy failed"+ )+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")++ monkeypatch.setattr(subprocess, "run", fake_run)++ with pytest.raises(SystemExit) as exc:+ cli._cmd_configure(+ Namespace(+ from_browser=None,+ key="xhs-cookies",+ value=["web_session=xhs-secret"],+ sync_legacy_twitter=False,+ )+ )++ assert exc.value.code == 1+ assert "Failed to copy cookies" in capsys.readouterr().out+++def test_ytdlp_config_write_refuses_target_symlink(+ tmp_path, monkeypatch, capsys+):+ import shutil++ import agent_reach.utils.paths as paths++ monkeypatch.setattr(paths.sys, "platform", "darwin")+ monkeypatch.setattr(+ paths.Path,+ "home",+ classmethod(lambda cls: tmp_path),+ )+ monkeypatch.delenv("XDG_CONFIG_HOME")+ config_path = tmp_path / ".config" / "yt-dlp" / "config"+ config_path.parent.mkdir(parents=True)+ victim = tmp_path / "victim.conf"+ victim.write_text("# keep unchanged\n", encoding="utf-8")+ try:+ config_path.symlink_to(victim)+ except OSError:+ pytest.skip("symlinks are not supported on this platform")++ def fake_which(name):+ if name in {"gh", "node", "npm", "yt-dlp"}:+ return f"/usr/bin/{name}"+ return None++ def fake_run(args, **_kwargs):+ if args[-1:] == ["--version"] and args[0].endswith("yt-dlp"):+ return subprocess.CompletedProcess(+ args, 0, stdout="2026.07.04\n", stderr=""+ )+ stdout = "/tmp/npm-root\n" if args[1:3] == ["root", "-g"] else ""+ return subprocess.CompletedProcess(args, 0, stdout=stdout, stderr="")++ monkeypatch.setattr(shutil, "which", fake_which)+ monkeypatch.setattr(subprocess, "run", fake_run)++ cli._install_system_deps()++ assert victim.read_text(encoding="utf-8") == "# keep unchanged\n"+ assert config_path.is_symlink()+ assert "Could not configure yt-dlp JS runtime" in capsys.readouterr().out+++def test_transcribe_cli_scrubs_credentials_from_errors(+ monkeypatch, capsys+):+ import agent_reach.transcribe as transcribe_module++ secret_url = (+ "https://alice:[email protected]/audio"+ "?access_token=hidden-token"+ )++ def fail_transcribe(*_args, **_kwargs):+ raise transcribe_module.TranscribeError(+ f"yt-dlp failed for {secret_url}"+ )++ monkeypatch.setattr(transcribe_module, "transcribe", fail_transcribe)++ with pytest.raises(SystemExit) as exc:+ cli._cmd_transcribe(+ Namespace(+ source=secret_url,+ provider="auto",+ output=None,+ )+ )++ assert exc.value.code == 1+ output = capsys.readouterr().out+ assert "alice:super-secret" not in output+ assert "hidden-token" not in output+ assert "***" in output+++def test_safe_install_with_proxy_makes_no_persistent_writes(+ isolated_home, monkeypatch, capsys+):+ observed_configs = []+ skill_calls = []++ monkeypatch.setattr(cli, "_install_system_deps_safe", lambda: None)+ monkeypatch.setattr(cli, "_install_mcporter_safe", lambda: None)+ monkeypatch.setattr(+ "agent_reach.doctor.check_all",+ lambda config: observed_configs.append(config) or {},+ )+ monkeypatch.setattr(+ "agent_reach.doctor.format_report",+ lambda _results: "report",+ )+ monkeypatch.setattr(+ cli,+ "_install_skill",+ lambda: skill_calls.append("installed"),+ )++ cli._cmd_install(+ Namespace(+ env="local",+ proxy="http://user:[email protected]:8080",+ safe=True,+ dry_run=False,+ channels="twitter",+ )+ )++ assert len(observed_configs) == 1+ assert observed_configs[0].read_only is True+ assert skill_calls == []+ assert not (isolated_home / ".agent-reach").exists()+ assert not (isolated_home / ".agent-reach" / "tools").exists()+ assert not (isolated_home / ".openclaw" / "skills" / "agent-reach").exists()+ assert not (isolated_home / ".claude" / "skills" / "agent-reach").exists()+ assert not (isolated_home / ".agents" / "skills" / "agent-reach").exists()+ output = capsys.readouterr().out+ assert "SAFE MODE" in output+ assert "Would save network proxy" in outputdiff --git a/tests/test_youtube_channel.py b/tests/test_youtube_channel.pyindex 940ac8b7..e48dac8b 100644--- a/tests/test_youtube_channel.py+++ b/tests/test_youtube_channel.py@@ -4,7 +4,7 @@YouTube's readiness is layered: yt-dlp must probe alive (missing / broken /unrunnable are distinct), a JS runtime is mandatory (deno works out of thebox, Node needs an explicit ``--js-runtimes`` config), and transcription-readiness (whisper provider + ffmpeg) is surfaced for ``doctor`` without+readiness (whisper provider + ffmpeg/ffprobe) is surfaced for ``doctor`` withoutgating the backend. These tests stub ``probe_command`` / ``shutil.which``so every branch runs offline. Follow-up to #331 — extends dedicatedchannel coverage after rss (#360), github (#361), web (#363),@@ -57,10 +57,13 @@ def test_has_js_runtime_config_false_when_flag_absent(tmp_path):assert _has_js_runtime_config(cfg) is False-def test_has_js_runtime_config_swallows_oserror():- bad = Mock()- bad.exists.return_value = True- with patch.object(yt, "read_utf8_text", side_effect=OSError("denied")):+def test_has_js_runtime_config_swallows_oserror(tmp_path):+ bad = tmp_path / "config"+ with patch.object(+ yt,+ "read_small_text_no_follow",+ side_effect=OSError("denied"),+ ):assert _has_js_runtime_config(bad) is False@@ -71,6 +74,7 @@ def test_check_off_when_ytdlp_missing():with patch.object(yt, "probe_command", return_value=ProbeResult("missing")):status, message = ch.check()assert status == "off"+ assert "yt-dlp[default]" in messageassert ch.active_backend is None@@ -80,6 +84,7 @@ def test_check_error_when_ytdlp_broken():status, message = ch.check()assert status == "error"assert "relink venv" in message+ assert "yt-dlp[default]" in messageassert ch.active_backend is None@@ -193,7 +198,7 @@ def test_check_ok_reports_transcription_when_provider_and_ffmpeg_present():cfg = Mock()cfg.is_configured = lambda key: key == "groq_whisper"with patch.object(yt, "probe_command", return_value=ProbeResult("ok")), \- patch("shutil.which", side_effect=_which("deno", "ffmpeg")):+ patch("shutil.which", side_effect=_which("deno", "ffmpeg", "ffprobe")):status, message = ch.check(config=cfg)assert status == "ok"assert "groq" in message@@ -209,3 +214,15 @@ def test_check_ok_flags_missing_ffmpeg_for_transcription():status, message = ch.check(config=cfg)assert status == "ok"assert "ffmpeg" in message+++def test_check_ok_flags_missing_ffprobe_for_transcription():+ ch = YouTubeChannel()+ cfg = Mock()+ cfg.is_configured = lambda key: key == "openai_whisper"+ with patch.object(yt, "probe_command", return_value=ProbeResult("ok")), \+ patch("shutil.which", side_effect=_which("deno", "ffmpeg")):+ status, message = ch.check(config=cfg)+ assert status == "ok"+ assert "ffprobe" in message+ assert "可转写音频" not in message