Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(api): use installer-aware codex upgrades

cyh7efcf95cef66
diff --git a/docs/CODEX_SETUP.md b/docs/CODEX_SETUP.md
index f5d69db3c..7b2d1224c 100644
--- a/docs/CODEX_SETUP.md
+++ b/docs/CODEX_SETUP.md
@@ -5,7 +5,9 @@ Vibe Remote can route individual chat scopes to Codex instead of Claude Code. (O
## 1. Install and authenticate Codex CLI
```bash
-brew install codex # or follow https://github.com/openai/codex
+npm install -g @openai/codex
+# or: brew install --cask codex
+# or: download a release binary from https://github.com/openai/codex/releases
codex --help # verify installation
codex # sign in when prompted
```
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 2467cffb3..93f75dca9 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -298,11 +298,11 @@ def test_install_agent_returns_resolved_path(monkeypatch):
assert result["path"] == "/Users/test/.opencode/bin/opencode"
-def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch):
+def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):
# Fresh-install path: codex is not yet on disk, but npm is resolvable.
# install_agent must shell out to `npm install -g @openai/codex` and
- # prepend the resolved npm's directory to PATH so the post-install
- # resolve_cli_path can locate the freshly placed binary.
+ # use a user-owned npm prefix so backend lifecycle installs do not write
+ # into system-owned global node directories.
calls = []
class CompletedProcess:
@@ -326,50 +326,199 @@ def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch):
monkeypatch.setattr(api.subprocess, "run", fake_run)
monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
result = api.install_agent("codex")
assert result["ok"] is True
assert len(calls) == 1
assert calls[0][0] == ["/Users/test/.nvm/versions/node/v22.18.0/bin/npm", "install", "-g", "@openai/codex"]
- assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == "/Users/test/.nvm/versions/node/v22.18.0/bin"
+ assert calls[0][1]["NPM_CONFIG_PREFIX"] == str(api.Path.home() / ".local")
+ assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(api.Path.home() / ".local" / "bin")
assert result["path"] == "/Users/test/.nvm/versions/node/v22.18.0/bin/codex"
-def test_install_codex_when_already_installed_runs_self_update(monkeypatch):
- # Upgrade path: when codex is already on disk, install_agent must defer
- # to `codex update` (which internally re-runs npm install -g @openai/codex)
- # rather than calling npm directly. Locks in the self-update branch in
- # install_agent so we don't regress to npm-bootstrap and orphan native
- # installs.
+def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):
+ # Npm-owned Codex installs should upgrade through npm, not through a
+ # different installer and not by blindly invoking the CLI self-updater.
calls = []
+ npm_path = tmp_path / ".nvm" / "versions" / "node" / "v22.18.0" / "bin" / "npm"
+ npm_path.parent.mkdir(parents=True)
+ npm_path.write_text("#!/bin/sh\n")
+ npm_path.chmod(0o755)
+ codex_path = npm_path.parent.parent / "lib" / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
+ codex_path.parent.mkdir(parents=True)
+ codex_path.write_text("#!/usr/bin/env node\n")
+ codex_path.chmod(0o755)
class CompletedProcess:
- returncode = 0
- stdout = "updated"
- stderr = ""
+ def __init__(self, returncode=0, stdout="", stderr=""):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs.get("env", {})))
- return CompletedProcess()
+ if cmd == [str(npm_path), "install", "-g", "@openai/codex"]:
+ return CompletedProcess(stdout="updated")
+ raise AssertionError(f"unexpected command: {cmd}")
def fake_resolve(binary):
+ if binary == "npm":
+ return str(npm_path)
if binary == "codex":
- return "/Users/test/.nvm/versions/node/v22.18.0/bin/codex"
+ return str(codex_path)
return None
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
monkeypatch.setattr(api.subprocess, "run", fake_run)
monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)
result = api.install_agent("codex")
assert result["ok"] is True
assert len(calls) == 1
- assert calls[0][0] == ["/Users/test/.nvm/versions/node/v22.18.0/bin/codex", "update"]
- # PATH still gets the codex binary's dir prepended so any child npm it
- # spawns picks up the same node toolchain.
- assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == "/Users/test/.nvm/versions/node/v22.18.0/bin"
- assert result["path"] == "/Users/test/.nvm/versions/node/v22.18.0/bin/codex"
+ assert calls[0][0] == [str(npm_path), "install", "-g", "@openai/codex"]
+ assert calls[0][1]["NPM_CONFIG_PREFIX"] == str(tmp_path / ".local")
+ assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(tmp_path / ".local" / "bin")
+ assert result["path"] == str(codex_path)
+
+
+def test_install_codex_homebrew_install_runs_brew_upgrade(monkeypatch, tmp_path):
+ brew_path = tmp_path / "homebrew" / "bin" / "brew"
+ brew_path.parent.mkdir(parents=True)
+ brew_path.write_text("#!/bin/sh\n")
+ brew_path.chmod(0o755)
+ codex_path = tmp_path / "homebrew" / "bin" / "codex"
+ codex_path.write_text("#!/bin/sh\n")
+ codex_path.chmod(0o755)
+ calls = []
+
+ class CompletedProcess:
+ def __init__(self, returncode=0, stdout="", stderr=""):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs.get("env", {})))
+ if cmd == [str(brew_path), "list", "--cask", "codex"]:
+ return CompletedProcess()
+ if cmd == [str(brew_path), "--prefix"]:
+ return CompletedProcess(stdout=f"{tmp_path / 'homebrew'}\n")
+ if cmd == [str(brew_path), "--prefix", "--cask"]:
+ return CompletedProcess(stdout=f"{tmp_path / 'homebrew' / 'Caskroom'}\n")
+ if cmd == [str(brew_path), "upgrade", "--cask", "codex"]:
+ return CompletedProcess(stdout="upgraded")
+ raise AssertionError(f"unexpected command: {cmd}")
+
+ def fake_resolve(binary):
+ if binary == "brew":
+ return str(brew_path)
+ if binary == "codex":
+ return str(codex_path)
+ return None
+
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is True
+ assert result["path"] == str(codex_path)
+ assert [str(brew_path), "upgrade", "--cask", "codex"] in [call[0] for call in calls]
+
+
+def test_install_codex_unknown_install_falls_back_to_cli_update(monkeypatch, tmp_path):
+ codex_path = tmp_path / "bin" / "codex"
+ codex_path.parent.mkdir(parents=True)
+ codex_path.write_text("#!/bin/sh\n")
+ codex_path.chmod(0o755)
+ calls = []
+
+ class CompletedProcess:
+ def __init__(self, returncode=0, stdout="", stderr=""):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs.get("env", {})))
+ if cmd == [str(codex_path), "--help"]:
+ return CompletedProcess(stdout="Commands:\n update Update Codex to the latest version\n")
+ if cmd == [str(codex_path), "update"]:
+ return CompletedProcess(stdout="updated")
+ raise AssertionError(f"unexpected command: {cmd}")
+
+ def fake_resolve(binary):
+ if binary == "codex":
+ return str(codex_path)
+ return None
+
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is True
+ assert [call[0] for call in calls] == [[str(codex_path), "--help"], [str(codex_path), "update"]]
+ assert result["path"] == str(codex_path)
+
+
+def test_install_codex_unknown_install_without_update_command_fails(monkeypatch, tmp_path):
+ codex_path = tmp_path / "bin" / "codex"
+ codex_path.parent.mkdir(parents=True)
+ codex_path.write_text("#!/bin/sh\n")
+ codex_path.chmod(0o755)
+
+ class CompletedProcess:
+ returncode = 0
+ stdout = "Commands:\n exec Run Codex non-interactively\n"
+ stderr = ""
+
+ def fake_run(cmd, **kwargs):
+ if cmd == [str(codex_path), "--help"]:
+ return CompletedProcess()
+ raise AssertionError(f"unexpected command: {cmd}")
+
+ def fake_resolve(binary):
+ if binary == "codex":
+ return str(codex_path)
+ return None
+
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is False
+ assert "does not expose an update command" in result["message"]
+
+
+def test_install_codex_npm_install_without_npm_fails(monkeypatch, tmp_path):
+ codex_path = tmp_path / "lib" / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
+ codex_path.parent.mkdir(parents=True)
+ codex_path.write_text("#!/usr/bin/env node\n")
+ codex_path.chmod(0o755)
+
+ def fake_resolve(binary):
+ if binary == "codex":
+ return str(codex_path)
+ return None
+
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is False
+ assert "npm was not found" in result["message"]
def test_discord_list_channels_rejects_empty_guild_id(monkeypatch):
@@ -386,10 +535,10 @@ def test_discord_list_channels_rejects_empty_guild_id(monkeypatch):
assert result["error"] == "Discord guild_id is required"
-def test_install_codex_detects_existing_install_via_npm_prefix_and_self_updates(monkeypatch, tmp_path):
+def test_install_codex_detects_existing_install_via_npm_prefix_and_upgrades_with_npm(monkeypatch, tmp_path):
# Codex already installed under the npm global prefix; resolve_cli_path
# must discover it (via `npm config get prefix`) and install_agent must
- # then defer to `codex update` instead of re-bootstrapping through npm.
+ # still upgrade by rerunning npm install -g @openai/codex.
npm_path = tmp_path / "node" / "bin" / "npm"
npm_path.parent.mkdir(parents=True, exist_ok=True)
npm_path.write_text("#!/bin/sh\n")
@@ -412,7 +561,7 @@ def test_install_codex_detects_existing_install_via_npm_prefix_and_self_updates(
calls.append((cmd, kwargs.get("env", {})))
if cmd == [str(npm_path), "config", "get", "prefix"]:
return CompletedProcess(stdout=f"{prefix_path}\n")
- if cmd == [str(codex_path), "update"]:
+ if cmd == [str(npm_path), "install", "-g", "@openai/codex"]:
return CompletedProcess(stdout="updated")
raise AssertionError(f"unexpected command: {cmd}")
@@ -424,11 +573,10 @@ def test_install_codex_detects_existing_install_via_npm_prefix_and_self_updates(
assert result["ok"] is True
assert result["path"] == str(codex_path)
- update_calls = [c for c in calls if c[0] == [str(codex_path), "update"]]
+ update_calls = [c for c in calls if c[0] == [str(npm_path), "install", "-g", "@openai/codex"]]
assert len(update_calls) == 1
- # PATH for the update call must have codex's bin dir first so npm /
- # node spawned by `codex update` use the same toolchain.
- assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(codex_path.parent)
+ assert update_calls[0][1]["NPM_CONFIG_PREFIX"] == str(tmp_path / ".local")
+ assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(tmp_path / ".local" / "bin")
def test_claude_models_merge_catalog_and_settings(monkeypatch, tmp_path):
diff --git a/vibe/api.py b/vibe/api.py
index 4d24cdc0e..af077106a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -314,6 +314,139 @@ def _command_env_for(binary_path: str | None) -> dict[str, str]:
return env
+def _codex_npm_install_env(npm_path: str) -> dict[str, str]:
+ env = _command_env_for(npm_path)
+ if os.name == "nt":
+ return env
+
+ prefix = str(Path.home() / ".local")
+ prefix_bin = str(Path(prefix) / "bin")
+ path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry and entry != prefix_bin]
+ env["PATH"] = os.pathsep.join([prefix_bin, *path_entries])
+ env["NPM_CONFIG_PREFIX"] = prefix
+ return env
+
+
+def _path_is_relative_to(path: Path, parent: Path) -> bool:
+ try:
+ path.resolve().relative_to(parent.resolve())
+ return True
+ except (OSError, ValueError):
+ return False
+
+
+def _is_npm_codex_install(codex_path: str) -> bool:
+ try:
+ resolved = Path(codex_path).expanduser().resolve()
+ except OSError:
+ return False
+ parts = resolved.parts
+ if "node_modules" in parts and "@openai" in parts and "codex" in parts:
+ return True
+
+ try:
+ original = Path(codex_path).expanduser()
+ except OSError:
+ return False
+ for candidate in _npm_global_binary_candidates("codex"):
+ if original == candidate or resolved == candidate.resolve():
+ return True
+ return False
+
+
+def _is_homebrew_codex_install(codex_path: str) -> bool:
+ brew_path = resolve_cli_path("brew")
+ if not brew_path:
+ return False
+
+ try:
+ result = subprocess.run(
+ [brew_path, "list", "--cask", "codex"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=_command_env_for(brew_path),
+ )
+ except Exception:
+ return False
+ if result.returncode != 0:
+ return False
+
+ try:
+ resolved = Path(codex_path).expanduser().resolve()
+ except OSError:
+ return False
+
+ brew_prefixes: list[Path] = []
+ for command in ([brew_path, "--prefix"], [brew_path, "--prefix", "--cask"]):
+ try:
+ prefix_result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=_command_env_for(brew_path),
+ )
+ except Exception:
+ continue
+ if prefix_result.returncode != 0:
+ continue
+ prefix = (prefix_result.stdout or "").strip().splitlines()
+ if prefix:
+ brew_prefixes.append(Path(os.path.expanduser(prefix[-1])))
+
+ brew_prefixes.extend([Path("/opt/homebrew"), Path("/usr/local"), Path("/home/linuxbrew/.linuxbrew")])
+ return any(_path_is_relative_to(resolved, prefix) for prefix in brew_prefixes)
+
+
+def _codex_cli_supports_update(codex_path: str) -> bool:
+ try:
+ result = subprocess.run(
+ [codex_path, "--help"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=_command_env_for(codex_path),
+ )
+ except Exception:
+ return False
+ if result.returncode != 0:
+ return False
+ output = f"{result.stdout}\n{result.stderr}"
+ return re.search(r"(?m)^\s*update\s+", output) is not None
+
+
+def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str] | None] | dict:
+ if _is_npm_codex_install(existing_path):
+ npm_path = resolve_cli_path("npm")
+ if not npm_path:
+ return {
+ "ok": False,
+ "message": "Codex appears to be installed via npm, but npm was not found. Please install Node.js or upgrade Codex manually.",
+ "output": None,
+ }
+ return [npm_path, "install", "-g", "@openai/codex"], _codex_npm_install_env(npm_path)
+
+ if _is_homebrew_codex_install(existing_path):
+ brew_path = resolve_cli_path("brew")
+ if not brew_path:
+ return {
+ "ok": False,
+ "message": "Codex appears to be installed via Homebrew, but brew was not found. Please upgrade Codex manually.",
+ "output": None,
+ }
+ return [brew_path, "upgrade", "--cask", "codex"], None
+
+ if _codex_cli_supports_update(existing_path):
+ return [existing_path, "update"], None
+
+ return {
+ "ok": False,
+ "message": "Could not determine how Codex was installed, and this Codex CLI does not expose an update command. Please upgrade Codex with the installer you originally used.",
+ "output": None,
+ }
+
+
def browse_directory(path: str, show_hidden: bool = False) -> dict:
"""List sub-directories of *path* for the directory browser UI.
@@ -1604,21 +1737,22 @@ def claude_models() -> dict:
def install_agent(name: str) -> dict:
"""Install (or upgrade) an agent CLI tool.
- Upgrade path (binary already on disk): defer to the tool's own
- ``update`` / ``upgrade`` subcommand. Each CLI knows how it was
- installed (npm-global, native, curl, brew, …) and updates in place
- via the matching package manager. Without this, our previous flow
- bricked Claude installs whenever the user's bootstrap method
- differed from our hard-coded installer URL — e.g. the Dockerfile
- bootstraps via ``npm install -g @anthropic-ai/claude-code`` but our
- upgrade ran ``curl https://claude.ai/install.sh | bash``, which
- migrated the binary to ``~/.local/bin/claude`` and left V2Config
- pointing at the now-empty ``/usr/local/bin/claude``.
-
- Self-update commands:
+ Upgrade path (binary already on disk): keep the user's install method
+ stable. Without this, our previous flow bricked Claude installs whenever
+ the user's bootstrap method differed from our hard-coded installer URL —
+ e.g. the Dockerfile bootstraps via ``npm install -g
+ @anthropic-ai/claude-code`` but our upgrade ran ``curl
+ https://claude.ai/install.sh | bash``, which migrated the binary to
+ ``~/.local/bin/claude`` and left V2Config pointing at the now-empty
+ ``/usr/local/bin/claude``.
+
+ Upgrade commands:
- ``claude update`` — auto-detects npm-global vs native install
- - ``codex update`` — runs ``npm install -g @openai/codex`` internally
- ``opencode upgrade`` — auto-detects curl/npm/pnpm/bun/brew/choco/scoop
+ - Codex npm installs use ``npm install -g @openai/codex`` with a
+ user-owned npm prefix.
+ - Codex Homebrew installs use ``brew upgrade --cask codex``.
+ - Unknown Codex installs fall back to ``codex update``.
Fresh-install path (binary missing) keeps the bootstrap commands
below — the user has no install yet, so we have no install method
@@ -1646,27 +1780,31 @@ def install_agent(name: str) -> dict:
return output
return "...(truncated)\n" + output[-MAX_OUTPUT_CHARS:]
- # Self-update branch: if the binary is already on disk, ask it to
- # update itself. Each CLI's update subcommand knows the install
- # method it lives in and updates without changing its binary path —
- # which means V2Config's stored ``cli_path`` stays valid across
- # upgrades, and an npm-bootstrapped install doesn't get half-
- # migrated to ``~/.local/bin`` and orphaned.
+ # Upgrade branch: if the binary is already on disk, keep the install
+ # source stable. Some CLIs own a reliable self-update command; Codex has
+ # multiple install sources, so choose npm/brew/self-update by source.
existing_path = resolve_cli_path(name)
if existing_path:
if name == "claude":
cmd = [existing_path, "update"]
- elif name == "codex":
- cmd = [existing_path, "update"]
+ command_env = None
elif name == "opencode":
# ``opencode upgrade`` auto-detects the install method; we
# don't pass ``--method`` so the user's bootstrap choice
# wins (curl on our Dockerfile, brew/npm/bun on user machines).
cmd = [existing_path, "upgrade"]
+ command_env = None
+ elif name == "codex":
+ upgrade = _codex_upgrade_command(existing_path)
+ if isinstance(upgrade, dict):
+ return upgrade
+ cmd, command_env = upgrade
else:
cmd = None
if cmd is not None:
- return _run_install_command(name, cmd, _truncate_output, mode="upgrade")
+ return _run_install_command(name, cmd, _truncate_output, mode="upgrade", env=command_env)
+
+ command_env: dict[str, str] | None = None
if name == "opencode":
# OpenCode: use curl installer (not supported on Windows)
@@ -1699,21 +1837,12 @@ def install_agent(name: str) -> dict:
return {"ok": False, "message": error, "output": None}
cmd = ["bash", "-c", "set -euo pipefail; curl -fsSL https://claude.ai/install.sh | bash"]
elif name == "codex":
- # Codex: prefer npm, fallback to brew on macOS
+ # Fresh installs use npm because it is the documented cross-platform
+ # package source that does not require OS package-manager privileges.
npm_path = resolve_cli_path("npm")
if npm_path:
cmd = [npm_path, "install", "-g", "@openai/codex"]
- elif system == "darwin":
- # macOS: try brew cask
- brew_path = resolve_cli_path("brew")
- if brew_path:
- cmd = [brew_path, "install", "--cask", "codex"]
- else:
- return {
- "ok": False,
- "message": "npm or brew not found. Please install Node.js or Homebrew first.",
- "output": None,
- }
+ command_env = _codex_npm_install_env(npm_path)
else:
return {
"ok": False,
@@ -1723,7 +1852,7 @@ def install_agent(name: str) -> dict:
else:
return {"ok": False, "message": f"Unknown agent: {name}", "output": None}
- return _run_install_command(name, cmd, _truncate_output, mode="install")
+ return _run_install_command(name, cmd, _truncate_output, mode="install", env=command_env)
def _run_install_command(
@@ -1732,6 +1861,7 @@ def _run_install_command(
truncate_output,
*,
mode: str = "install",
+ env: dict[str, str] | None = None,
) -> dict:
"""Shared subprocess + post-success bookkeeping for install / upgrade.
@@ -1743,7 +1873,7 @@ def _run_install_command(
label = "Upgrading" if mode == "upgrade" else "Installing"
try:
logger.info("%s agent %s with command: %s", label, name, cmd)
- command_env = _command_env_for(cmd[0] if cmd and os.path.isabs(cmd[0]) else None)
+ command_env = env or _command_env_for(cmd[0] if cmd and os.path.isabs(cmd[0]) else None)
result = subprocess.run(
cmd,
capture_output=True,