Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

feat: smooth upgrade from 1.5

Pnant9293bb6eb221
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3787f509..73b6bee8 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -46,6 +46,12 @@ jobs:
/tmp/smoke/bin/pip install --quiet dist/*.whl
/tmp/smoke/bin/agent-reach version
/tmp/smoke/bin/agent-reach channels > /dev/null
+ # Fixed name so docs can always point at
+ # releases/latest/download/agent-reach.zip instead of a version number.
+ git archive --format=zip --prefix=agent-reach/ -o dist/agent-reach.zip HEAD
+ python -m venv /tmp/smoke-zip
+ /tmp/smoke-zip/bin/pip install --quiet dist/agent-reach.zip
+ /tmp/smoke-zip/bin/agent-reach version
- name: Release notes from CHANGELOG
run: |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 888ecd6d..0abfd364 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ All notable changes to this project will be documented in this file.
- 专用浏览器按扩展保存在它自己配置里的编号识别,不会再把用户日常的 Chrome 认成专用浏览器;登录窗口开着时查询不再把它收掉。
- 浏览器渠道可以并行查询:同一平台最多 2 条、合计 4 条同时跑,多出来的排队而不是立刻报"正忙";登录窗口、退出登录等操作等正在跑的查询结束再做。
- 没登录时报"需要登录"而不是"上游工具坏了":雪球社区(错误码 400016)、B站字幕(没有 B站登录)、LinkedIn(专用浏览器里没有 LinkedIn 登录)。
+- 从 1.5 升级更顺:update.md 先看版本再分流;`agent-reach update` 遇到 pip/pipx 装的旧版会自己换成 uv 安装;`setup` 删掉旧版 Agent Reach 程序(只删它自己,不动其他工具),安装汇报说明保留了什么、变了什么、以前用过哪些渠道可以加回来。安装地址改为始终指向最新正式版。
English:
- Browser channels share one profile, close after ten idle minutes and reopen on demand.
@@ -30,6 +31,7 @@ English:
- The dedicated browser is identified by the id its extension saves inside its own profile, so the user's own Chrome is never mistaken for it; a query no longer closes an open login window.
- Browser channels run queries in parallel: up to 2 per platform and 4 in total, with the rest queued instead of failing BUSY at once; login windows, logout and browser setup wait for running queries.
- Report NEED_LOGIN instead of UPSTREAM_BROKEN when not logged in: Xueqiu community (error 400016), Bilibili subtitles (no Bilibili login), LinkedIn (no LinkedIn login in the dedicated browser).
+- Smoother upgrade from 1.5: update.md checks the version first; `agent-reach update` moves a pip/pipx install to uv by itself; `setup` removes the old Agent Reach program (only Agent Reach itself) and the install report explains what was kept, what changed and which old channels can be added back. Install URLs always point at the latest release.
中文:
diff --git a/agent_reach/runtime/legacy.py b/agent_reach/runtime/legacy.py
new file mode 100644
index 00000000..298e0c6c
--- /dev/null
+++ b/agent_reach/runtime/legacy.py
@@ -0,0 +1,108 @@
+"""Old (1.5 and earlier) Agent Reach installs: find them and remove only Agent Reach itself.
+
+1.5 was installed with pipx or into `~/.agent-reach-venv`. After the user moves to
+the uv install, those copies would keep an old `agent-reach` on PATH, and a later
+`pipx upgrade-all` could put 1.5 back. Only Agent Reach's own package is removed;
+the user's other tools (twitter-cli, bili, ...) and data are never touched.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Dict, List
+
+from agent_reach.utils.paths import home_dir
+
+_WIN = os.name == "nt"
+
+
+def _pipx_venvs() -> List[Path]:
+ home = home_dir()
+ roots = [os.environ.get("PIPX_HOME", ""),
+ str(home / ".local" / "pipx"),
+ str(home / "Library" / "Application Support" / "pipx"),
+ str(home / ".local" / "share" / "pipx"),
+ str(home / "pipx")]
+ return [Path(r) / "venvs" / "agent-reach" for r in roots if r]
+
+
+def _has_agent_reach(venv: Path) -> bool:
+ lib = venv / "Lib" / "site-packages" if _WIN else None
+ sites = [lib] if lib else sorted((venv / "lib").glob("python*/site-packages"))
+ return any((s / "agent_reach").is_dir() for s in sites if s and s.is_dir())
+
+
+def _python(venv: Path) -> Path:
+ return venv / ("Scripts/python.exe" if _WIN else "bin/python")
+
+
+def _current() -> Path:
+ return Path(sys.prefix).resolve()
+
+
+def find() -> List[Dict[str, str]]:
+ """Old Agent Reach copies other than the one running now."""
+ found: List[Dict[str, str]] = []
+ seen = set()
+ for kind, venv in [("pipx", v) for v in _pipx_venvs()] + [("venv", home_dir() / ".agent-reach-venv")]:
+ try:
+ real = venv.resolve()
+ except OSError:
+ continue
+ if real in seen or real == _current() or not _has_agent_reach(venv):
+ continue
+ seen.add(real)
+ found.append({"kind": kind, "path": str(venv)})
+ return found
+
+
+def _drop_pipx_shims(venv: Path) -> None:
+ """Remove `agent-reach` launchers that still point into the old pipx venv."""
+ dirs = {os.environ.get("PIPX_BIN_DIR", ""), str(home_dir() / ".local" / "bin")}
+ for d in filter(None, dirs):
+ shim = Path(d) / ("agent-reach.exe" if _WIN else "agent-reach")
+ try:
+ if shim.is_symlink() and Path(os.path.realpath(shim)).is_relative_to(venv.resolve()):
+ shim.unlink()
+ except OSError:
+ pass
+
+
+def _uninstall_package(venv: Path) -> bool:
+ python = _python(venv)
+ for cmd in ([str(python), "-m", "pip", "uninstall", "-y", "-q", "agent-reach"],
+ [shutil.which("uv") or "uv", "pip", "uninstall", "-q", "--python", str(python), "agent-reach"]):
+ try:
+ if subprocess.run(cmd, capture_output=True, timeout=120).returncode == 0:
+ return True
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+ return False
+
+
+def remove() -> Dict[str, List[Dict[str, str]]]:
+ """Remove old Agent Reach copies. A pipx venv holds only Agent Reach, so it goes away;
+ `~/.agent-reach-venv` may hold other packages, so only Agent Reach is uninstalled there."""
+ removed, failed = [], []
+ for item in find():
+ venv = Path(item["path"])
+ try:
+ if item["kind"] == "pipx":
+ _drop_pipx_shims(venv)
+ shutil.rmtree(venv)
+ elif not _uninstall_package(venv):
+ raise OSError("pip uninstall failed")
+ removed.append(item)
+ except OSError as exc:
+ failed.append({**item, "reason": str(exc)[:200]})
+ return {"removed": removed, "failed": failed}
+
+
+def manual_command(item: Dict[str, str]) -> str:
+ if item["kind"] == "pipx":
+ return "pipx uninstall agent-reach"
+ return f"{_python(Path(item['path']))} -m pip uninstall -y agent-reach"
diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.py
index 1aefc05a..26833294 100644
--- a/agent_reach/runtime/manage.py
+++ b/agent_reach/runtime/manage.py
@@ -604,27 +604,53 @@ def _skill_uninstall_targets() -> List[Path]:
# ── setup / migrate ──
+#: 1.5 config keys and CLI tools that show which channels the user relied on.
+_LEGACY_KEYS = {"twitter_auth_token": "twitter", "twitter_ct0": "twitter", "xueqiu_cookie": "xueqiu",
+ "xhs_cookie": "xiaohongshu"}
+_LEGACY_COMMANDS = {"twitter": "twitter", "xhs": "xiaohongshu", "opencli": "xiaohongshu", "rdt": "reddit",
+ "bili": "bilibili", "boss": "boss"}
+#: 1.5 channels that 1.6 no longer has; the report says what replaces them.
+RETIRED_CHANNELS = ("rss", "exa_search")
+
+
def migrate() -> dict:
- """First run after an older Agent Reach: create state, keep credentials, suggest channels."""
+ """First run after an older Agent Reach: create state, keep credentials, suggest channels.
+
+ The result is kept in state so the first install report can explain the upgrade even
+ when another process (the new uv copy) renders it.
+ """
from agent_reach.config import Config
cfg = Config(read_only=True)
- hints = []
- for cmd, channel in (("bili", "bilibili"), ("opencli", "xiaohongshu"), ("boss", "boss")):
- if shutil.which(cmd):
- hints.append(channel)
- if cfg.get("xueqiu_cookie"):
- hints.append("xueqiu")
+ hints = {ch for key, ch in _LEGACY_KEYS.items() if cfg.get(key)}
+ hints |= {ch for cmd, ch in _LEGACY_COMMANDS.items() if shutil.which(cmd)}
defaults = {c.name for c in _channels() if c.level == "default"}
- data = state.load()
- data["migrated_from"] = "1.5"
- state.save(data)
- return {
+ result = {
"migrated": True,
"kept": "~/.agent-reach/config.yaml (keys and cookies unchanged)",
- "suggested_channels": sorted(set(hints) - defaults),
+ "suggested_channels": sorted(hints - defaults),
+ "retired_channels": list(RETIRED_CHANNELS),
"note": "Your own global tools were not removed. Browser login must be completed by the user in the Reach dedicated window.",
}
+ data = state.load()
+ data["migrated_from"] = "1.5"
+ data["migration"] = result
+ state.save(data)
+ return result
+
+
+def _cleanup_old_copies() -> dict:
+ """From the uv install, remove 1.5 copies (pipx / ~/.agent-reach-venv) so they cannot shadow it."""
+ if install_method() != "uv":
+ return {"removed": [], "failed": []}
+ from . import legacy
+ return legacy.remove()
+
+
+def _old_copy_actions(old: dict) -> List[str]:
+ from . import legacy
+ return [f"An old Agent Reach copy could not be removed ({i['path']}); run `{legacy.manual_command(i)}`."
+ for i in old["failed"]]
def _optional_entry(c) -> dict:
@@ -635,10 +661,14 @@ def _optional_entry(c) -> dict:
def setup() -> dict:
"""Add the default channels (except ones the user removed) and place the skill."""
- migration = migrate() if not state.exists() and (state.root() / "config.yaml").exists() else None
+ if not state.exists() and (state.root() / "config.yaml").exists():
+ migrate()
if not state.exists():
state.save(state.load())
- user_actions = _retired_mcp_notice()
+ saved_migration = state.load()
+ migration = None if saved_migration.get("migration_reported") else saved_migration.get("migration")
+ old_copies = _cleanup_old_copies()
+ user_actions = _retired_mcp_notice() + _old_copy_actions(old_copies)
if state.load()["tools"].get("mcporter", {}).get("owner") == tools.OURS:
tools.remove_private("mcporter") # retired LinkedIn MCP transport, only our private copy
state.mutate(lambda saved: [saved.pop(key, None) for key in ("reuse_sources", "ask_pending", "pending")])
@@ -667,6 +697,7 @@ def setup() -> dict:
"when": "only_if_required"} for c in defaults if _has_login(c)],
"capability_summary": capability_summary(registered, current),
"migration": migration,
+ "old_copies": old_copies,
}
from agent_reach.utils.paths import PrivatePathError, atomic_write_private_text
@@ -679,6 +710,8 @@ def setup() -> dict:
# The receipt remains in stdout even if its local copy cannot be saved.
report["write_error"] = "安装报告未能保存;完整表格仍在 installation_report.markdown。"
result["installation_report"] = report
+ if migration:
+ state.mutate(lambda saved: saved.__setitem__("migration_reported", True))
return result
@@ -791,8 +824,53 @@ def sync() -> dict:
expired = [a for a, code in (check.get("codes") or {}).items() if code == "NEED_LOGIN" and previous.get(a)]
if expired:
actions.append(f"The user needs to log in to {c.name} again: run `agent-reach login {c.name}`.")
+ old_copies = _cleanup_old_copies()
+ actions += _old_copy_actions(old_copies)
return {"version": __version__, "tools": synced, "problems": problems, "removed_tools": _prune(state.load()),
- "dropped_channels": dropped, "user_actions": actions, "skill": place_skill(), "migration": migration}
+ "dropped_channels": dropped, "user_actions": actions, "skill": place_skill(), "migration": migration,
+ "old_copies": old_copies}
+
+
+def _move_to_uv(info: dict) -> dict:
+ """This copy was installed with pip/pipx (1.5 style). Install the release with uv, let the
+ new copy set itself up (it removes known old copies), then remove this copy too."""
+ fresh = not state.exists()
+ if fresh and (state.root() / "config.yaml").exists():
+ migrate() # recorded in state; the new copy's install report explains the upgrade
+ uv = tools.resolve("uv")
+ if not uv:
+ tools.ensure("uv")
+ uv = tools.resolve("uv")
+ if not uv:
+ raise ReachError(NEED_SETUP, "uv could not be installed",
+ hint="Install uv: https://docs.astral.sh/uv/getting-started/installation/")
+ newest = update_notice.version_tuple(info["latest"]) >= update_notice.version_tuple(__version__)
+ cmd = upgrade_command(info["latest"] if newest else __version__)
+ proc = subprocess.run([uv, *cmd[1:]], capture_output=True, text=True, timeout=900)
+ if proc.returncode != 0:
+ raise ReachError(UPSTREAM_BROKEN, f"upgrade failed: {proc.stderr.strip()[-300:]}",
+ hint=f"Run manually: {' '.join(cmd)}")
+ bin_dir = subprocess.run([uv, "tool", "dir", "--bin"], capture_output=True, text=True, timeout=60).stdout.strip()
+ exe = Path(bin_dir) / ("agent-reach.exe" if os.name == "nt" else "agent-reach")
+ child = [str(exe), "setup"] if fresh else [str(exe), "update", "--sync-only"]
+ out = subprocess.run(child, capture_output=True, text=True, timeout=1800)
+ try:
+ result = json.loads(out.stdout.strip().splitlines()[-1]).get("result") or {}
+ except (ValueError, IndexError):
+ result = {"raw": out.stdout[-500:]}
+ actions = list(result.get("user_actions") or [])
+ package = Path(__file__).resolve().parents[1]
+ if package.exists(): # a copy the new one does not know about (pip --user, conda, ...)
+ gone = subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "-q", "agent-reach"],
+ capture_output=True, timeout=120).returncode == 0
+ if not gone:
+ actions.append(f"Remove the old Agent Reach copy: `{sys.executable} -m pip uninstall agent-reach`.")
+ found = shutil.which("agent-reach")
+ if not found or os.path.realpath(found) != os.path.realpath(exe):
+ actions.append("Open a new terminal so `agent-reach` runs the new version; if it still does not, "
+ f"run `{uv} tool update-shell`.")
+ return {**info, "upgraded": True, "method": "moved_to_uv", "sync": result,
+ "installation_report": result.get("installation_report"), "user_actions": actions}
def update(check_only: bool = False) -> dict:
@@ -801,14 +879,10 @@ def update(check_only: bool = False) -> dict:
if check_only:
return info
method = install_method()
+ if method == "other":
+ return _move_to_uv(info)
if info["update_available"] and method != "editable":
cmd = upgrade_command(info["latest"])
- if method != "uv":
- raise ReachError(
- NEED_SETUP, "this copy of Agent Reach was not installed with uv, so it cannot update itself",
- hint=f"Reinstall once with uv: `{' '.join(cmd)}`, then remove the old copy "
- "(e.g. `pipx uninstall agent-reach` or `pip uninstall agent-reach`).",
- )
run = [tools.resolve("uv") or cmd[0], *cmd[1:]]
try:
proc = subprocess.run(run, capture_output=True, text=True, timeout=900)
diff --git a/agent_reach/runtime/onboarding.py b/agent_reach/runtime/onboarding.py
index 1d9ebcd4..dff32070 100644
--- a/agent_reach/runtime/onboarding.py
+++ b/agent_reach/runtime/onboarding.py
@@ -90,6 +90,28 @@ def _local_greeting():
return '晚上好,想搜点什么?'
return '夜深了,想搜点什么?🌙'
+def _upgrade_lines(result):
+ """Only for users coming from 1.5: what was kept, what changed, what is left to do."""
+ migration = result.get('migration')
+ if not migration:
+ return []
+ lines = ['**这次是从旧版本(1.5)升级上来的:**', '',
+ '- 你的密钥和设置都保留了。',
+ '- RSS 订阅和 Exa 全网搜索不再单独提供,搜资料、读网页统一用"网页"。',
+ '- 推特、小红书这类要登录的平台,现在用 Agent Reach 自己的专用浏览器;第一次用时会先尝试复用你 Chrome 里的登录。',
+ '- 你以前另外装的命令行工具(比如 twitter-cli、bili)原样保留,没有删。']
+ suggested = [_DISPLAY_NAMES.get(n, n) for n in migration.get('suggested_channels') or []]
+ if suggested:
+ lines.append('- 你以前用过' + '、'.join(suggested) + ',想继续用直接跟我说"加上 XX"。')
+ old = result.get('old_copies') or {}
+ if old.get('removed'):
+ lines.append('- 旧版程序已经删掉,以后不会和新版冲突。')
+ for item in old.get('failed') or []:
+ from .legacy import manual_command
+ lines.append(f"- 旧版程序没删成,请运行:`{manual_command(item)}`")
+ return lines + ['']
+
+
def installation_report(result):
"""Render one short receipt; keep detailed evidence in the structured summary."""
@@ -104,6 +126,7 @@ def installation_report(result):
_local_greeting(), '',
f"**Agent Reach {result['version']} {'安装完成' if completed else '安装还差一步'}。** "
f'默认功能:{installed}/{len(installs)} 项准备成功。', '',
+ *_upgrade_lines(result),
'✅ 不用登录;❌ 登录后再试;🔑 需 Key;— 不用额外登录。', '',
'| 平台 | 不登录可以查什么 | 需要登录后再试 |', '|---|---|---|',
]
diff --git a/agent_reach/skill/SKILL.md b/agent_reach/skill/SKILL.md
index c87b9ee2..ae087e77 100644
--- a/agent_reach/skill/SKILL.md
+++ b/agent_reach/skill/SKILL.md
@@ -54,7 +54,7 @@ agent-reach read <链接> # 按链接自动选渠道
## 登录与专用浏览器
-所有浏览器渠道共用一个专用浏览器(优先 CloakBrowser,装不上时用本机 Chrome),默认无头不弹窗,闲置 10 分钟自动关闭,下次调用自动重开。可以并行调用(包括子代理同时查):同一平台最多同时 2 条,所有平台合计 4 条,多出来的自动排队;同一平台的搜索之间自动间隔几秒。
+所有浏览器渠道共用一个专用浏览器(优先 CloakBrowser,装不上时用本机 Chrome),默认无头不弹窗,闲置 10 分钟自动关闭,下次调用自动重开。可以并行调用(包括子代理同时查):同一平台最多同时 2 条,所有平台合计 4 条,多出来的自动排队;同一平台的两次搜索之间至少隔 10 秒。
第一次用某个网站时,如果用户的 Chrome 已连接 OpenCLI 扩展,程序会把该站登录自动复制一次到专用浏览器,之后一直复用;只复制该站,不动原浏览器。登录失效或没有可复制的来源时,才请用户本人 `agent-reach login <渠道>`。刷新、选来源、退出等细节见 [会话与专用浏览器](references/sessions.md):用户要登录、退出、换账号,或遇到 `NEED_LOGIN` 时读它。
diff --git a/agent_reach/skill/SKILL_en.md b/agent_reach/skill/SKILL_en.md
index 3d888124..0099b616 100644
--- a/agent_reach/skill/SKILL_en.md
+++ b/agent_reach/skill/SKILL_en.md
@@ -55,7 +55,7 @@ On `PLATFORM_BLOCKED`, `RATE_LIMITED`, `NEED_LOGIN` or `BUSY`, stop this attempt
## Login and the dedicated browser
-All browser channels share one dedicated browser (CloakBrowser preferred, falling back to installed Chrome). It runs headless by default, closes after 10 idle minutes and reopens on the next call. Calls may run in parallel, including from subagents: up to 2 per platform and 4 in total run at once, the rest wait in line, and same-platform searches are spaced a few seconds apart.
+All browser channels share one dedicated browser (CloakBrowser preferred, falling back to installed Chrome). It runs headless by default, closes after 10 idle minutes and reopens on the next call. Calls may run in parallel, including from subagents: up to 2 per platform and 4 in total run at once, the rest wait in line, and two searches on the same platform start at least 10 seconds apart.
The first time a site is used, if the user's Chrome is connected to the OpenCLI extension, that site's login is copied once into the dedicated browser and reused afterwards; only that site is copied and the source browser is untouched. Only when the login has expired or there is no source to copy from does the user run `agent-reach login <channel>` and log in themselves. Refreshing, choosing a source and logging out are in [Sessions](references/sessions.md): read it when the user wants to log in, log out or switch accounts, or on `NEED_LOGIN`.
diff --git a/agent_reach/skill/references/sessions.md b/agent_reach/skill/references/sessions.md
index a0dafa0c..80708ace 100644
--- a/agent_reach/skill/references/sessions.md
+++ b/agent_reach/skill/references/sessions.md
@@ -9,7 +9,7 @@
- `agent-reach add <渠道>` 自动准备 Node、OpenCLI、内核和扩展。工具按本版测试过的版本安装。Windows 上用 Chrome 回退时,可能需要用户点一次"添加至 Chrome"。
- 默认无头,不弹窗。只有 `agent-reach login <渠道>` 会显示窗口;窗口开着时查询直接用这个窗口,不会收掉它,用户登录期间等用户说登好了再查。窗口关闭后,之后的查询回到无头。
- 闲置 10 分钟自动关闭,下次调用自动重开;真实页面操作和 Reach 调用会重置计时。登录期间定期保存,用户不用关窗。
-- 可以并行:同一平台最多同时 2 条,所有平台合计 4 条,多出来的排队,最多等 2 分钟,等不到才返回 `BUSY`。同一平台的搜索之间自动间隔几秒。打开登录窗口、退出登录、重装浏览器会等正在跑的查询结束再做。
+- 可以并行:同一平台最多同时 2 条,所有平台合计 4 条,多出来的排队,最多等 2 分钟,等不到才返回 `BUSY`。同一平台的两次搜索之间至少隔 10 秒。打开登录窗口、退出登录、重装浏览器会等正在跑的查询结束再做。
- `agent-reach browser status` 查看状态,`browser setup` 准备内核和扩展,`browser stop` 关闭程序管理的浏览器。
## 自动复用已有登录
diff --git a/docs/install.md b/docs/install.md
index f57006fc..3db3b6d3 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1,13 +1,15 @@
# Install Agent Reach
-For the AI doing the install. Run every command yourself. Each `agent-reach` command prints one JSON object; read `ok`, `result` and `error.hint`.
+For the AI doing the install. Run every command yourself. Each `agent-reach` command (1.6 and later) prints one JSON object; read `ok`, `result` and `error.hint`.
> ⚠️ The PyPI package named `agent-reach` is NOT this project. Never install it from PyPI; only use the GitHub URL below.
## 0. Before you start
- You must be able to run terminal commands. If you can't, tell the user: "Please turn on command execution for me in my settings, then ask again."
-- Already have it (`command -v agent-reach` prints a path)? Run `agent-reach update` and stop here. Coming from 1.5 or earlier: follow [update.md](update.md).
+- Already installed (`command -v agent-reach` prints a path)? Run `agent-reach version`:
+ - it prints JSON → run `agent-reach update` and stop here.
+ - it prints a plain line like `Agent Reach v1.5.0` → this is an old version; follow [update.md](update.md) instead.
- `uv` missing (`uv --version` fails)? Tell the user: "I'm installing uv, a small tool that installs command-line programs. It needs no admin password." Then run:
- macOS / Linux: `curl -LsSf https://astral.sh/uv/install.sh | sh`
- Windows: `powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"`
@@ -16,7 +18,7 @@ For the AI doing the install. Run every command yourself. Each `agent-reach` com
## 1. Install and set up
```bash
-uv tool install https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v1.6.0.zip
+uv tool install https://github.com/Panniantong/Agent-Reach/releases/latest/download/agent-reach.zip
agent-reach setup
```
diff --git a/docs/update.md b/docs/update.md
index 4ba93c3c..cbf74121 100644
--- a/docs/update.md
+++ b/docs/update.md
@@ -1,26 +1,45 @@
# Update Agent Reach
-## 1.6 and later
+For the AI doing the update. Run every command yourself.
+
+## 1. Which version is installed?
```bash
-agent-reach update
+agent-reach version
```
-One command does everything:
+- Prints JSON (1.6 and later) → go to step 2.
+- Prints a plain line like `Agent Reach v1.5.0`, or `agent-reach update` says "invalid choice" → it is 1.5 or earlier; go to step 3.
+- `agent-reach` not found → follow [install.md](install.md).
-- upgrades the program to the latest GitHub release (`uv tool install --force <release zip>`)
-- reinstalls the tools of every added channel, even when Agent Reach itself has no new release: tools with a tested version stay at that version, other tools get the newest version inside their supported range (known-bad versions are skipped); tools no channel uses any more are removed
-- refreshes the Agent Reach skill (the one real copy, and the links that let your other AIs read it)
+## 2. Update (1.6 and later)
-Default channels you removed stay removed; `agent-reach add <channel>` brings one back.
+```bash
+agent-reach update
+```
-`result.user_actions` lists, in plain sentences, anything the user must do afterwards (e.g. a channel now needs a login). Tell the user each one.
+It upgrades the program, every added channel's tools and the skill, and removes old copies. Show the user each line of `result.user_actions`, and `result.installation_report.markdown` as is when it is present. Then `agent-reach check --text` confirms the channels still work.
-Only want to know if there is a new version? `agent-reach update --check`. Agent Reach also checks by itself at most once a day in the background; when a newer version exists, every command's JSON carries `meta.update` with the version and its release notes.
+If it fails, `error.hint` holds the exact command to run.
-Afterwards, `agent-reach check --text` confirms your channels still work.
+## 3. Upgrade from 1.5 or earlier
-If the upgrade step fails, the error `hint` holds the exact command to run by hand. Installed some other way than uv? The hint says to reinstall once with uv, as below.
+1.6 is installed with uv, a small tool that installs command-line programs; 1.5 was installed with pipx or pip. Tell the user: "This is a big upgrade. Your keys and settings are kept; I'm moving Agent Reach to the new installer." Then:
+
+1. `uv --version` fails? Install uv (no admin password):
+ - macOS / Linux: `curl -LsSf https://astral.sh/uv/install.sh | sh`
+ - Windows: `powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"`
+2. Install 1.6:
+ ```bash
+ uv tool install --force https://github.com/Panniantong/Agent-Reach/releases/latest/download/agent-reach.zip
+ ```
+3. Open a new shell and check `agent-reach version` prints JSON. If it still prints the old line, run `uv tool update-shell`, open a new shell and check again.
+4. Set it up:
+ ```bash
+ agent-reach setup
+ ```
+ It keeps `~/.agent-reach/config.yaml`, removes the old Agent Reach program (only Agent Reach itself, never the user's other tools) and refreshes the skill for every AI.
+5. Show `result.installation_report.markdown` to the user as is. It explains what changed and which old channels they can add back.
## Roll back
@@ -31,26 +50,4 @@ uv tool install --force https://github.com/Panniantong/Agent-Reach/archive/refs/
agent-reach update --sync-only
```
-`--sync-only` brings the channel tools and the skill in line with the installed version without upgrading the program again. Channels, keys and logins under `~/.agent-reach/` are kept.
-
-## Coming from 1.5 or earlier
-
-Older versions installed differently, so reinstall once with the same command as [install.md](install.md) (no `uv` yet? see step 0 there):
-
-```bash
-uv tool install --force https://github.com/Panniantong/Agent-Reach/archive/refs/tags/v1.6.0.zip
-agent-reach setup
-```
-
-`agent-reach setup` migrates the old install:
-
-- keys in `~/.agent-reach/config.yaml` stay as they are
-- `result.migration.suggested_channels` lists channels you used before; add them again with `agent-reach add <channel>`
-- tools the old version installed globally are not removed; Agent Reach 1.6 uses its own private copies
-- old CLI logins (bilibili, boss) can be copied over instead of logging in again:
-
-```bash
-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>`.
+Channels, keys and logins under `~/.agent-reach/` are kept.
diff --git a/tests/test_manage.py b/tests/test_manage.py
index 5a88a144..c6b554e7 100644
--- a/tests/test_manage.py
+++ b/tests/test_manage.py
@@ -335,14 +335,87 @@ def test_upgrade_reinstalls_the_release_with_uv():
assert cmd[:4] == ["uv", "tool", "install", "--force"] and cmd[-1].endswith("/v2.0.1.zip")
-def test_update_from_a_non_uv_install_asks_for_one_uv_reinstall(monkeypatch):
+def test_update_from_a_non_uv_install_moves_itself_to_uv(env, monkeypatch, tmp_path):
monkeypatch.setattr(manage, "update_check", lambda: {"current": "2.0.0", "latest": "2.0.1",
"update_available": True})
monkeypatch.setattr(manage, "install_method", lambda: "other")
- monkeypatch.setattr(manage.subprocess, "run", lambda *a, **k: pytest.fail("must not run an installer"))
- with pytest.raises(ReachError) as info:
- manage.update()
- assert "uv tool install --force" in info.value.hint
+ monkeypatch.setattr(manage.tools, "resolve", lambda c: "/fake/uv" if c == "uv" else None)
+ calls = []
+
+ class Done:
+ def __init__(self, stdout=""):
+ self.returncode, self.stdout, self.stderr = 0, stdout, ""
+
+ def run(cmd, **kw):
+ calls.append(cmd)
+ if cmd[1:4] == ["tool", "dir", "--bin"]:
+ return Done(str(tmp_path))
+ if cmd[0] == str(tmp_path / "agent-reach"):
+ return Done(json.dumps({"ok": True, "result": {"user_actions": ["log in to x"],
+ "installation_report": {"markdown": "r"}}}))
+ return Done()
+
+ monkeypatch.setattr(manage.subprocess, "run", run)
+ out = manage.update()
+ assert calls[0][:4] == ["/fake/uv", "tool", "install", "--force"] and calls[0][-1].endswith("/v2.0.1.zip")
+ assert calls[2] == [str(tmp_path / "agent-reach"), "setup"] # no state yet: the new copy sets itself up
+ assert out["upgraded"] and out["installation_report"] == {"markdown": "r"}
+ assert "log in to x" in out["user_actions"]
+
+
+def test_migration_suggests_channels_from_the_old_config(env):
+ (state.root()).mkdir(parents=True, exist_ok=True)
+ (state.root() / "config.yaml").write_text("twitter_auth_token: t\nxueqiu_cookie: c\n")
+ result = manage.migrate()
+ assert result["suggested_channels"] == ["twitter", "xueqiu"]
+ assert result["retired_channels"] == ["rss", "exa_search"]
+ assert state.load()["migration"] == result
+
+
+def test_upgrade_report_explains_the_move_from_1_5():
+ from agent_reach.runtime import onboarding
+ assert onboarding._upgrade_lines({"migration": None}) == []
+ text = "\n".join(onboarding._upgrade_lines({
+ "migration": {"suggested_channels": ["twitter"]},
+ "old_copies": {"removed": [], "failed": [{"kind": "pipx", "path": "/x"}]}}))
+ assert "1.5" in text and "X / Twitter" in text and "pipx uninstall agent-reach" in text
+
+
+def _old_venv(root):
+ site = root / ("Lib/site-packages" if os.name == "nt" else "lib/python3.12/site-packages")
+ (site / "agent_reach").mkdir(parents=True)
+ return root
+
+
+def test_old_pipx_copy_and_its_launcher_are_removed(monkeypatch, tmp_path):
+ from agent_reach.runtime import legacy
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("PIPX_HOME", raising=False)
+ monkeypatch.delenv("PIPX_BIN_DIR", raising=False)
+ venv = _old_venv(tmp_path / ".local" / "pipx" / "venvs" / "agent-reach")
+ (venv / "bin").mkdir()
+ (venv / "bin" / "agent-reach").write_text("")
+ shim = tmp_path / ".local" / "bin" / "agent-reach"
+ shim.parent.mkdir(parents=True)
+ shim.symlink_to(venv / "bin" / "agent-reach")
+ (tmp_path / ".agent-reach-venv").mkdir() # a venv without Agent Reach is not ours to touch
+ assert [i["kind"] for i in legacy.find()] == ["pipx"]
+ out = legacy.remove()
+ assert len(out["removed"]) == 1 and not venv.exists() and not shim.is_symlink()
+ assert (tmp_path / ".agent-reach-venv").is_dir()
+
+
+def test_old_shared_venv_only_loses_agent_reach(monkeypatch, tmp_path):
+ from agent_reach.runtime import legacy
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("PIPX_HOME", raising=False)
+ venv = _old_venv(tmp_path / ".agent-reach-venv")
+ ran = []
+ monkeypatch.setattr(legacy.subprocess, "run",
+ lambda cmd, **k: ran.append(cmd) or type("P", (), {"returncode": 0})())
+ out = legacy.remove()
+ assert len(out["removed"]) == 1 and venv.is_dir() # the venv stays; only the package is uninstalled
+ assert ran[0][-4:] == ["uninstall", "-y", "-q", "agent-reach"]
def test_update_without_new_release_still_upgrades_tools(env, monkeypatch):