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(desktop): expose a relocatable bundled vibe CLI (#2250)

Maxf59f86d99a7b
diff --git a/desktop/README.md b/desktop/README.md
index a6416fca2..d5361bcd6 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -69,6 +69,21 @@ OpenCode are intentionally not part of the application payload: Avibe detects
an existing installation first and otherwise installs the selected backend into
its private application-data directory when the user clicks Install.
+Agents inherit a PATH led by the Runtime's dedicated `bin` directory. It provides
+`vibe` (`vibe.cmd` on Windows), which runs the bundled Python with `-I -B -m vibe`.
+The entry point is generated when building the bundle, covered by its manifest,
+and works after relocation, including installation paths containing spaces.
+The private Python directory is not added to PATH, so the user's `python3` and
+`pip` remain available. Build-machine Python console scripts are removed.
+
+**Login-shell limitation:** a user profile that prepends a new global CLI
+directory or replaces PATH can override the bundled `vibe`. Profiles that
+preserve its precedence continue to use the private Runtime. Desktop does not
+modify user profiles or force shell startup options. If a profile overrides it,
+put `$AVIBE_DESKTOP_RUNTIME_ROOT/bin` first after your PATH changes when that
+variable is set. Codex's caller-context `BASH_ENV` injection does not run in zsh
+and is not a fallback for this case.
+
The first launch verifies the embedded Runtime archive and installs it
atomically below the operating system's application-data directory. Installs
are versioned and content-addressed, so application updates never replace files
diff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rs
index cc45487ea..4f2580c64 100644
--- a/desktop/runtime-host/src/launcher.rs
+++ b/desktop/runtime-host/src/launcher.rs
@@ -536,11 +536,14 @@ impl RuntimeCommand {
inherited_path: Option<&OsStr>,
) -> Self {
let tools_dir = node.parent().expect("validated private Node has a parent");
- let mut path_entries = vec![tools_dir.to_owned()];
+ // The builder includes a relocatable vibe entry point in bin. Expose
+ // only that directory, never python/bin (which would shadow user tools).
+ let cli_dir = runtime_root.join("bin");
+ let mut path_entries = vec![cli_dir.clone(), tools_dir.to_owned()];
if let Some(path) = inherited_path {
path_entries.extend(env::split_paths(path).filter(|entry| !entry.as_os_str().is_empty()));
}
- let private_path = env::join_paths(path_entries).unwrap_or_else(|_| tools_dir.as_os_str().to_owned());
+ let private_path = env::join_paths(path_entries).unwrap_or_else(|_| cli_dir.into_os_string());
Self {
executable: python,
// Isolated mode excludes the user site and PYTHONPATH. The Avibe
@@ -2165,8 +2168,14 @@ mod tests {
let environment: std::collections::HashMap<_, _> = command.environment.into_iter().collect();
let path_entries: Vec<_> =
env::split_paths(environment.get(OsStr::new("PATH")).expect("private PATH")).collect();
- assert_eq!(path_entries.first().map(PathBuf::as_path), node.parent());
- assert_eq!(path_entries.get(1).map(PathBuf::as_path), Some(Path::new("/usr/bin")));
+ assert_eq!(
+ path_entries,
+ [
+ runtime_root.join("bin"),
+ node.parent().unwrap().to_owned(),
+ PathBuf::from("/usr/bin")
+ ]
+ );
assert_eq!(
environment.get(OsStr::new("VIBE_SHOW_RUNTIME_NODE_BIN")),
Some(&expected_node)
diff --git a/desktop/scripts/build-runtime-bundle.py b/desktop/scripts/build-runtime-bundle.py
index 97ebb2c39..454fec10a 100755
--- a/desktop/scripts/build-runtime-bundle.py
+++ b/desktop/scripts/build-runtime-bundle.py
@@ -7,6 +7,7 @@ import argparse
import hashlib
import json
import os
+import shlex
import shutil
import signal
import socket
@@ -19,7 +20,7 @@ import time
import urllib.parse
import urllib.request
import zipfile
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from typing import Any
@@ -30,6 +31,7 @@ DEFAULT_OUTPUT = DESKTOP_DIR / "src-tauri" / "resources" / "runtime"
COPY_CHUNK = 1024 * 1024
FIXED_ZIP_TIME = (2020, 1, 1, 0, 0, 0)
TREE_HASH_DOMAIN = b"avibe-runtime-tree-v1\0"
+CLI_BIN_DIR = "bin" # Also prepended by RuntimeCommand::private in launcher.rs.
# Everything the probe Runtime records about its own startup, relative to the
# probe HOME. The process logs are the runtime directory's sink files; the
@@ -228,6 +230,43 @@ for name in ("claude", "claude.exe"):
)
+def install_runtime_cli(target_config: dict[str, Any], payload: Path) -> None:
+ """Replace build-machine console scripts with one relocatable CLI.
+
+ Python dependencies are consumed as modules. Their generated console
+ scripts embed the build interpreter's path and cannot survive relocation.
+ Keep the interpreter binaries, but do not ship these unusable launchers.
+ """
+ for scripts in (payload / "python" / "bin", payload / "python" / "Scripts"):
+ if not scripts.is_dir():
+ continue
+ for path in scripts.iterdir():
+ if path.is_symlink() or not path.is_file():
+ continue
+ with path.open("rb") as source:
+ is_script = source.read(2) == b"#!"
+ if is_script or (scripts.name == "Scripts" and path.suffix.lower() in {".exe", ".py", ".pyw"}):
+ path.unlink()
+
+ cli_dir = payload / CLI_BIN_DIR
+ cli_dir.mkdir()
+ interpreter = PurePosixPath(target_config["python_entrypoint"])
+ if target_config["os"] == "windows":
+ relative_python = "\\".join(interpreter.parts)
+ (cli_dir / "vibe.cmd").write_bytes(
+ f'@echo off\r\n"%~dp0..\\{relative_python}" -I -B -m vibe %*\r\n'.encode("utf-8")
+ )
+ else:
+ cli = cli_dir / "vibe"
+ cli.write_text(
+ '#!/bin/sh\n'
+ 'here=$(CDPATH= cd -- "${0%/*}" && pwd -P) || exit 1\n'
+ f'exec "$here/../{interpreter.as_posix()}" -I -B -m vibe "$@"\n',
+ encoding="utf-8",
+ )
+ cli.chmod(0o755)
+
+
def install_node_toolchain(
target_config: dict[str, Any],
node_archive: Path,
@@ -477,7 +516,7 @@ def verify_payload(
raise
-def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path) -> dict[str, str]:
+def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path, payload: Path) -> dict[str, str]:
inherited_path = os.environ.get("PATH", "")
retained_env = {
name: value
@@ -498,6 +537,7 @@ def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path) -> di
return {
**retained_env,
"HOME": str(probe_home),
+ "ZDOTDIR": str(probe_home),
"USERPROFILE": str(probe_home),
"APPDATA": str(probe_home / "appdata"),
"LOCALAPPDATA": str(probe_home / "local-appdata"),
@@ -510,6 +550,7 @@ def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path) -> di
"PATH": os.pathsep.join(
part
for part in (
+ str(payload / CLI_BIN_DIR),
str(node.parent),
inherited_path,
)
@@ -519,6 +560,7 @@ def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path) -> di
"AVIBE_DESKTOP_NPM_CLI": str(npm_cli),
"AVIBE_DESKTOP_BACKENDS_ROOT": str(probe_home / "backends"),
"AVIBE_DESKTOP_MANAGED_RUNTIME": "1",
+ "AVIBE_DESKTOP_RUNTIME_ROOT": str(payload),
"VIBE_INSTALL_SKIP_SHOW_RUNTIME": "1",
"VIBE_INSTALL_SKIP_ASKILL": "1",
"VIBE_ASKILL_AUTO_UPDATE": "0",
@@ -596,8 +638,25 @@ def _verify_payload_with_home(
config_dir.mkdir(parents=True)
port = reserve_loopback_port()
config_path = config_dir / "config.json"
- env = private_probe_environment(probe_home, node, npm_cli)
- command = [str(python), "-I", "-m", "vibe"]
+ env = private_probe_environment(probe_home, node, npm_cli, payload)
+ command = [str(python), "-I", "-B", "-m", "vibe"]
+ agent_cwd = probe_home / "workspace"
+ agent_cwd.mkdir()
+
+ def agent_cli(*args: str) -> subprocess.CompletedProcess[str]:
+ # Use the same login-shell shape as macOS agents, not a direct Python
+ # module call that bypasses command discovery and the packaged shim.
+ shell_command = (
+ [env.get("COMSPEC", "cmd.exe"), "/d", "/c", "vibe", *args]
+ if target_config["os"] == "windows"
+ else ["/bin/zsh", "-lc", shlex.join(["vibe", *args])]
+ )
+ return subprocess.run(shell_command, cwd=agent_cwd, env=env, check=True, capture_output=True, text=True)
+
+ for skill in ("use-avibe", "use-avibe-vault"):
+ loaded = agent_cli("skill", "load", "--", skill)
+ if f'<skill_content name="{skill}"' not in loaded.stdout:
+ raise SystemExit(f"Bundled CLI did not load {skill}")
endpoint = subprocess.run(
[*command, "desktop", "endpoint", "--json"],
cwd=work_dir,
@@ -735,6 +794,7 @@ def main() -> int:
sources.get("sdist_build_allowlist", []),
)
verify_python_runtime_excludes_agent_backends(private_python, work_dir)
+ install_runtime_cli(target_config, payload)
install_node_toolchain(
target_config,
node_archive,
@@ -743,6 +803,12 @@ def main() -> int:
sources["npm_version"],
)
write_inventory(private_python, payload)
+ # The installed location differs from the build location and commonly
+ # contains spaces (Application Support / AppData). Probe that boundary
+ # before hashing the payload, so no install-time repair is necessary.
+ installed_payload = work_dir / "relocated runtime"
+ payload.rename(installed_payload)
+ payload = installed_payload
verify_payload(target_config, payload, work_dir, sources["npm_version"])
prune_payload(payload)
diff --git a/docs/plans/desktop-runtime-cli-2247.md b/docs/plans/desktop-runtime-cli-2247.md
new file mode 100644
index 000000000..3e7b53408
--- /dev/null
+++ b/docs/plans/desktop-runtime-cli-2247.md
@@ -0,0 +1,62 @@
+# Desktop Runtime CLI (#2247)
+
+## Contract
+
+Desktop-launched agents can resolve ordinary `vibe` commands to the bundled
+Runtime from an arbitrary working directory, including after relocation to an
+installation path containing spaces. The bundle builder owns the entry point;
+the archive and installed-tree digest cover it. CLI execution uses the private
+interpreter with `-I -B -m vibe` and must not mutate the verified payload.
+
+Only the dedicated CLI directory and existing Node directory are prepended to
+PATH. The private Python scripts directory must never shadow user Python tools.
+Remove build-bound Python console scripts before packaging. No install-time
+patching, runtime generation paths in commands, or user shell profile changes.
+
+## Scope decision
+
+The builder, Rust launcher, packaging probe, and their existing tests own this
+change. The baseline is `a78be44a1` on master. Another local working tree contains
+an uncommitted related candidate; it remains untouched.
+
+Login profiles run after inherited PATH is set. Profiles that introduce an
+earlier global CLI directory or replace PATH can override the bundled command.
+As explicitly permitted in the issue comment, document that limitation rather
+than taking ownership of user shell startup. Codex's BASH_ENV/zsh caller-context
+issue remains separate.
+
+## Validation
+
+- Extend the Rust launcher contract test to protect CLI precedence and preserve
+ user Python resolution; the old launcher exposes only Node.
+- Exercise the generated command through real shells after archive extraction
+ and relocation, including a conflicting inherited global CLI. Assert argument
+ forwarding and exit status. Existing tests only probe direct module startup.
+- Verify console-script removal and archive inclusion at the builder boundary.
+- Have the packaging probe invoke bare `vibe` through the platform shell and
+ load both reported built-in skills against a test-owned HOME.
+- Run the complete changed Python test file, Ruff, Rust formatting and runtime
+ host tests; require current-head automatic review, green CI and no unresolved
+ review threads before handoff. Do not merge or deploy.
+
+## Progress
+
+- [x] Confirm issue, constraints, baseline and isolated worktree.
+- [x] Implement builder, launcher and packaging probe.
+- [x] Verify regression against the unchanged baseline and fixed behavior.
+- [ ] Complete PR review and CI.
+
+Local checks: all 17 builder tests and 110 Runtime host library tests pass,
+along with Ruff, Rust formatting and the Workbench production build. Restoring
+the baseline launcher's PATH construction makes the updated consumer contract
+fail for the missing CLI directory; restoring the fix passes it. Real shell
+tests extract the generated archive, remove its build location, and check CLI
+precedence, unchanged Python/pip resolution, arguments and exit status.
+
+Full native bundle verification is in progress. The system Python and uv are
+older than the build pipeline requires, so use the existing development Python
+and an isolated invocation of CI's pinned uv 0.12.10.
+
+The current Codex desktop task has no Avibe Session ID; `vibe watch add` returns
+`missing_session_policy`. Do not create a callback in an unrelated Avibe session.
+Keep the bundled PR/CI waiter and its durable cursor associated with this task.
diff --git a/tests/test_desktop_runtime_bundle_builder.py b/tests/test_desktop_runtime_bundle_builder.py
index bf934c645..9b9455130 100644
--- a/tests/test_desktop_runtime_bundle_builder.py
+++ b/tests/test_desktop_runtime_bundle_builder.py
@@ -3,6 +3,9 @@ from __future__ import annotations
import importlib.util
import json
import os
+import shlex
+import shutil
+import stat
import subprocess
import zipfile
from pathlib import Path
@@ -26,17 +29,111 @@ def test_private_probe_environment_does_not_inherit_credentials(monkeypatch, tmp
probe_home = tmp_path / "probe"
node = tmp_path / "payload" / "tools" / "bin" / "node"
npm_cli = tmp_path / "payload" / "tools" / "npm" / "bin" / "npm-cli.js"
- environment = builder.private_probe_environment(probe_home, node, npm_cli)
+ payload = tmp_path / "payload"
+ environment = builder.private_probe_environment(probe_home, node, npm_cli, payload)
assert "OPENAI_API_KEY" not in environment
assert "ANTHROPIC_AUTH_TOKEN" not in environment
assert environment["HOME"] == str(probe_home)
assert environment["CODEX_HOME"] == str(probe_home / "codex")
- assert environment["PATH"].split(builder.os.pathsep)[0] == str(node.parent)
+ assert environment["PATH"].split(builder.os.pathsep)[:2] == [str(payload / "bin"), str(node.parent)]
+ assert str(payload / "python" / "bin") not in environment["PATH"].split(builder.os.pathsep)
+ assert environment["ZDOTDIR"] == str(probe_home)
assert environment["AVIBE_DESKTOP_NPM_CLI"] == str(npm_cli)
assert environment["AVIBE_DESKTOP_BACKENDS_ROOT"] == str(probe_home / "backends")
[email protected](os.name == "nt", reason="POSIX shells")
[email protected]("shell", ["/bin/sh", "/bin/bash", "/bin/zsh"])
[email protected]("global_cli", [False, True])
+def test_packaged_cli_survives_relocation_and_preserves_user_python(tmp_path, shell, global_cli):
+ if not Path(shell).is_file():
+ pytest.skip(f"{shell} is not installed")
+ payload = tmp_path / "build" / "payload"
+ payload.mkdir(parents=True)
+ builder.install_runtime_cli({"os": "macos", "python_entrypoint": "python/bin/python3"}, payload)
+ # This consumer records the invocation and exit status across the shell
+ # boundary. The packaging probe separately runs the real installed module.
+ python = payload / "python" / "bin" / "python3"
+ python.parent.mkdir(parents=True)
+ python.write_text('#!/bin/sh\nprintf "%s\\n" "$0" "$@"\nexit 23\n', encoding="utf-8")
+ python.chmod(0o755)
+ archive = tmp_path / "runtime.zip"
+ builder.create_runtime_zip(payload, archive)
+ installed = tmp_path / "Application Support" / "runtime" / "generation-repair"
+ with zipfile.ZipFile(archive) as source:
+ source.extractall(installed)
+ for member in source.infolist():
+ (installed / member.filename).chmod(stat.S_IMODE(member.external_attr >> 16))
+ shutil.rmtree(payload.parent)
+
+ user_bin = tmp_path / "user-bin"
+ user_bin.mkdir()
+ for name in ("python3", "pip", *(["vibe"] if global_cli else [])):
+ executable = user_bin / name
+ executable.write_text("#!/bin/sh\nexit 99\n", encoding="utf-8")
+ executable.chmod(0o755)
+ probe_home = tmp_path / "home"
+ probe_home.mkdir()
+ # Typical profiles and macOS path_helper may reconstruct PATH, but must
+ # preserve private CLI precedence when appending user directories.
+ (probe_home / ".zprofile").write_text('export PATH="$PATH:/profile-appended"\n', encoding="utf-8")
+ cwd = tmp_path / "unrelated working directory"
+ cwd.mkdir()
+ env = {
+ "HOME": str(probe_home),
+ "ZDOTDIR": str(probe_home),
+ "PATH": f"{installed / 'bin'}:{user_bin}:/usr/bin:/bin",
+ }
+ ordinary_tools = subprocess.run(
+ [shell, "-lc", "command -v python3; command -v pip"],
+ cwd=cwd, env={**env, "PATH": f"{user_bin}:/usr/bin:/bin"},
+ check=True, capture_output=True, text=True,
+ ).stdout.splitlines()
+ resolved = subprocess.run(
+ [shell, "-lc", "command -v vibe; command -v python3; command -v pip"],
+ cwd=cwd, env=env, check=True, capture_output=True, text=True,
+ ).stdout.splitlines()
+ assert Path(resolved[0]) == installed / "bin" / "vibe"
+ assert resolved[1:] == ordinary_tools
+ args = ["skill", "load", "--", "name with 空格", "literal $HOME;*'\"", ""]
+ result = subprocess.run(
+ [shell, "-lc", shlex.join(["vibe", *args])],
+ cwd=cwd, env=env, check=False, capture_output=True, text=True,
+ )
+ assert result.returncode == 23, result.stderr
+ interpreter, *actual_args = result.stdout.splitlines()
+ assert Path(interpreter).resolve() == (installed / "python" / "bin" / "python3").resolve()
+ assert actual_args == ["-I", "-B", "-m", "vibe", *args]
+
+
+def test_runtime_cli_removes_console_scripts_and_is_in_archive_digest(tmp_path):
+ payload = tmp_path / "payload"
+ scripts = payload / "python" / "bin"
+ scripts.mkdir(parents=True)
+ python = scripts / "python3"
+ python.write_bytes(b"binary interpreter")
+ (scripts / "vibe").write_text(f"#!{python}\nimport vibe\n", encoding="utf-8")
+ (scripts / "pip").write_text(f'#!/bin/sh\nexec "{python}" "$@"\n', encoding="utf-8")
+ windows_scripts = payload / "python" / "Scripts"
+ windows_scripts.mkdir()
+ (windows_scripts / "vibe.exe").write_bytes(b"MZ build-bound launcher")
+ (windows_scripts / "vibe-script.py").write_text("import vibe\n", encoding="utf-8")
+
+ builder.install_runtime_cli({"os": "windows", "python_entrypoint": "python/python.exe"}, payload)
+
+ assert list(scripts.iterdir()) == [python]
+ assert not list(windows_scripts.iterdir())
+ cli = payload / "bin" / "vibe.cmd"
+ assert cli.read_bytes() == b'@echo off\r\n"%~dp0..\\python\\python.exe" -I -B -m vibe %*\r\n'
+ archive = tmp_path / "runtime.zip"
+ _, _, digest = builder.create_runtime_zip(payload, archive)
+ with zipfile.ZipFile(archive) as source:
+ assert source.read("bin/vibe.cmd") == cli.read_bytes()
+ cli.write_bytes(cli.read_bytes() + b"rem changed\r\n")
+ assert builder.create_runtime_zip(payload, archive)[2] != digest
+
+
def test_runtime_sources_schema_two_contains_only_node_and_npm_tools():
sources = json.loads((SCRIPT.parents[1] / "runtime-sources.json").read_text(encoding="utf-8"))