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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(codex): preserve npm prefix during upgrades (#617)
Call White824e6e1a4d12
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex a45aaf2ec..1418c6dc2 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -1351,7 +1351,8 @@ def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):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.+ # different installer and not by blindly invoking the CLI self-updater. The+ # upgrade must stay in the npm prefix that owns the existing package.calls = []npm_path = tmp_path / ".nvm" / "versions" / "node" / "v22.18.0" / "bin" / "npm"npm_path.parent.mkdir(parents=True)@@ -1370,6 +1371,8 @@ def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):def fake_run(cmd, **kwargs):calls.append((cmd, kwargs.get("env", {})))+ if cmd == [str(npm_path), "config", "get", "prefix"]:+ return CompletedProcess(stdout=f"{npm_path.parent.parent}\n")if cmd == [str(npm_path), "install", "-g", "@openai/codex"]:return CompletedProcess(stdout="updated")raise AssertionError(f"unexpected command: {cmd}")@@ -1390,10 +1393,10 @@ def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):result = api.install_agent("codex")assert result["ok"] is True- assert len(calls) == 1- 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")+ update_calls = [c for c in calls if c[0] == [str(npm_path), "install", "-g", "@openai/codex"]]+ assert len(update_calls) == 1+ assert update_calls[0][1]["NPM_CONFIG_PREFIX"] == str(npm_path.parent.parent)+ assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(npm_path.parent)assert result["path"] == str(codex_path)@@ -1608,7 +1611,8 @@ def test_discord_list_channels_rejects_empty_guild_id(monkeypatch):def test_install_codex_detects_existing_install_via_npm_prefix_and_upgrades_with_npm(monkeypatch, tmp_path, only_tmp_binaries):# Codex already installed under the npm global prefix; resolve_cli_path# must discover it (via `npm config get prefix`) and install_agent must- # still upgrade by rerunning npm install -g @openai/codex.+ # still upgrade by rerunning npm install -g @openai/codex in that same+ # prefix instead of moving it to ~/.local.npm_path = tmp_path / "node" / "bin" / "npm"npm_path.parent.mkdir(parents=True, exist_ok=True)npm_path.write_text("#!/bin/sh\n")@@ -1646,6 +1650,121 @@ def test_install_codex_detects_existing_install_via_npm_prefix_and_upgrades_withassert result["path"] == str(codex_path)update_calls = [c for c in calls if c[0] == [str(npm_path), "install", "-g", "@openai/codex"]]assert len(update_calls) == 1+ assert update_calls[0][1]["NPM_CONFIG_PREFIX"] == str(prefix_path)+ assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(prefix_path / "bin")+++def test_install_codex_symlinked_npm_install_upgrades_in_real_prefix(monkeypatch, tmp_path, only_tmp_binaries):+ # Regression coverage for the Incus layout: ~/.local/bin/codex is a shim to+ # ~/.npm-global/bin/codex. Running npm with prefix ~/.local tries to replace+ # the shim and fails with EEXIST, so upgrades must follow the real package.+ npm_path = tmp_path / "node" / "bin" / "npm"+ npm_path.parent.mkdir(parents=True, exist_ok=True)+ npm_path.write_text("#!/bin/sh\n")+ npm_path.chmod(0o755)++ prefix_path = tmp_path / ".npm-global"+ package_bin = prefix_path / "lib" / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"+ package_bin.parent.mkdir(parents=True, exist_ok=True)+ package_bin.write_text("#!/usr/bin/env node\n")+ package_bin.chmod(0o755)+ npm_bin = prefix_path / "bin" / "codex"+ npm_bin.parent.mkdir(parents=True, exist_ok=True)+ npm_bin.symlink_to(package_bin)++ local_bin = tmp_path / ".local" / "bin" / "codex"+ local_bin.parent.mkdir(parents=True, exist_ok=True)+ local_bin.symlink_to(npm_bin)+ 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(npm_path), "config", "get", "prefix"]:+ return CompletedProcess(stdout=f"{prefix_path}\n")+ 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 str(local_bin)+ return None++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)+ monkeypatch.setattr(api.subprocess, "run", fake_run)+ monkeypatch.setattr(api.subprocess, "Popen", _PopenFromRun)+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)++ result = api.install_agent("codex")++ assert result["ok"] is True+ assert result["path"] == str(local_bin)+ update_calls = [c for c in calls if c[0] == [str(npm_path), "install", "-g", "@openai/codex"]]+ assert len(update_calls) == 1+ assert update_calls[0][1]["NPM_CONFIG_PREFIX"] == str(prefix_path)+ assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(prefix_path / "bin")+++def test_install_codex_project_local_node_modules_does_not_become_prefix(+ monkeypatch,+ tmp_path,+ only_tmp_binaries,+):+ npm_path = tmp_path / "node" / "bin" / "npm"+ npm_path.parent.mkdir(parents=True, exist_ok=True)+ npm_path.write_text("#!/bin/sh\n")+ npm_path.chmod(0o755)++ project_path = tmp_path / "project"+ codex_path = project_path / "lib" / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"+ codex_path.parent.mkdir(parents=True, exist_ok=True)+ codex_path.write_text("#!/usr/bin/env node\n")+ codex_path.chmod(0o755)+ global_prefix = tmp_path / ".npm-global"+ 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(npm_path), "config", "get", "prefix"]:+ return CompletedProcess(stdout=f"{global_prefix}\n")+ 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 str(codex_path)+ return None++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(api.shutil, "which", lambda binary: None)+ monkeypatch.setattr(api.subprocess, "run", fake_run)+ monkeypatch.setattr(api.subprocess, "Popen", _PopenFromRun)+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)++ result = api.install_agent("codex")++ assert result["ok"] is True+ update_calls = [c for c in calls if c[0] == [str(npm_path), "install", "-g", "@openai/codex"]]+ assert len(update_calls) == 1+ assert update_calls[0][1].get("NPM_CONFIG_PREFIX") != str(project_path)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")diff --git a/vibe/api.py b/vibe/api.pyindex 5459ff852..704004dce 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -218,46 +218,56 @@ def _npm_global_binary_candidates(binary: str) -> list[Path]:candidates: list[Path] = []for npm_path in npm_paths:- try:- result = subprocess.run(- [str(npm_path), "config", "get", "prefix"],- capture_output=True,- text=True,- timeout=5,- env=_command_env_for(str(npm_path)),- )- except Exception:- continue-- if result.returncode != 0:+ prefix_path = _npm_prefix_for(npm_path)+ if prefix_path is None:continue- prefix = (result.stdout or "").strip().splitlines()- if not prefix:- continue-- prefix_path = Path(os.path.expanduser(prefix[-1]))- derived_candidates = [- prefix_path / "bin" / binary,- prefix_path / binary,- prefix_path / "node_modules" / ".bin" / binary,- ]- if os.name == "nt":- derived_candidates.extend(- [- prefix_path / f"{binary}.cmd",- prefix_path / f"{binary}.exe",- prefix_path / "node_modules" / ".bin" / f"{binary}.cmd",- ]- )-- for candidate in derived_candidates:+ for candidate in _npm_binary_candidates_for_prefix(prefix_path, binary):if candidate not in candidates:candidates.append(candidate)return candidates+def _npm_prefix_for(npm_path: str | Path) -> Path | None:+ try:+ result = subprocess.run(+ [str(npm_path), "config", "get", "prefix"],+ capture_output=True,+ text=True,+ timeout=5,+ env=_command_env_for(str(npm_path)),+ )+ except Exception:+ return None++ if result.returncode != 0:+ return None++ prefix = (result.stdout or "").strip().splitlines()+ if not prefix:+ return None++ return Path(os.path.expanduser(prefix[-1]))+++def _npm_binary_candidates_for_prefix(prefix_path: Path, binary: str) -> list[Path]:+ derived_candidates = [+ prefix_path / "bin" / binary,+ prefix_path / binary,+ prefix_path / "node_modules" / ".bin" / binary,+ ]+ if os.name == "nt":+ derived_candidates.extend(+ [+ prefix_path / f"{binary}.cmd",+ prefix_path / f"{binary}.exe",+ prefix_path / "node_modules" / ".bin" / f"{binary}.cmd",+ ]+ )+ return derived_candidates++def _candidate_cli_paths(binary: str) -> list[Path]:if not binary:return []@@ -344,19 +354,70 @@ def _command_env_for(binary_path: str | None) -> dict[str, str]:return env-def _codex_npm_install_env(npm_path: str) -> dict[str, str]:+def _codex_npm_install_env(npm_path: str, *, prefix: str | Path | None = None) -> 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")+ install_prefix = Path(os.path.expanduser(str(prefix))) if prefix is not None else Path.home() / ".local"+ prefix = str(install_prefix)+ prefix_bin = str(install_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"] = prefixreturn env+def _npm_prefix_from_node_modules_path(codex_path: str) -> Path | None:+ try:+ paths = [Path(codex_path).expanduser(), Path(codex_path).expanduser().resolve()]+ except OSError:+ return None++ for path in paths:+ parts = path.parts+ for index in range(len(parts) - 2):+ if parts[index : index + 3] != ("node_modules", "@openai", "codex"):+ continue+ if index == 0 or parts[index - 1] != "lib":+ continue+ prefix_parts = parts[: index - 1]+ if prefix_parts:+ return Path(*prefix_parts)+ return None+++def _npm_prefix_for_existing_codex_install(npm_path: str, codex_path: str) -> Path | None:+ try:+ original = Path(codex_path).expanduser()+ resolved = original.resolve()+ except OSError:+ resolved = None++ npm_prefix = _npm_prefix_for(npm_path)+ if npm_prefix is None:+ return None++ inferred_prefix = _npm_prefix_from_node_modules_path(codex_path)+ if inferred_prefix is not None:+ try:+ if inferred_prefix.resolve() == npm_prefix.resolve():+ return npm_prefix+ except OSError:+ if inferred_prefix == npm_prefix:+ return npm_prefix++ for candidate in _npm_binary_candidates_for_prefix(npm_prefix, "codex"):+ try:+ candidate_resolved = candidate.resolve()+ except OSError:+ candidate_resolved = None+ if original == candidate or (resolved is not None and candidate_resolved == resolved):+ return npm_prefix++ return None++def _path_is_relative_to(path: Path, parent: Path) -> bool:try:path.resolve().relative_to(parent.resolve())@@ -465,7 +526,8 @@ def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str"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)+ prefix = _npm_prefix_for_existing_codex_install(npm_path, existing_path)+ return [npm_path, "install", "-g", "@openai/codex"], _codex_npm_install_env(npm_path, prefix=prefix)if _codex_cli_supports_update(existing_path):return [existing_path, "update"], None