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.

feat(remote-access): pin cloudflared as a managed runtime (#2464)

Call White682c8ca45f43
diff --git a/.github/workflows/release-mirror.yml b/.github/workflows/release-mirror.yml
index 683664bd5..ff068467e 100644
--- a/.github/workflows/release-mirror.yml
+++ b/.github/workflows/release-mirror.yml
@@ -13,7 +13,7 @@ on:
types: [completed]
# Safety net for missed triggers and renamed workflows, and the trigger for
# the other mirrored repositories' releases (askill, avault, tmux-builds,
- # ripgrep).
+ # ripgrep, cloudflared).
schedule:
- cron: "41 * * * *"
workflow_dispatch:
diff --git a/core/cloudflared_runtime.py b/core/cloudflared_runtime.py
new file mode 100644
index 000000000..561b973cc
--- /dev/null
+++ b/core/cloudflared_runtime.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+
+from config import paths
+from core.managed_runtime import ManagedRuntimeManager, ManagedRuntimeSpec, env_flag_enabled
+from core.process_isolation import isolated_subprocess_kwargs
+
+
+_CLOUDFLARED_SPEC = ManagedRuntimeSpec(
+ runtime_id="cloudflared",
+ manifest_resource="cloudflared_runtime_manifest.json",
+ version_field="cloudflared_version",
+ default_bin_path="cloudflared",
+ # Cloudflare ships no windows-arm64 build; Windows 11 on ARM runs the x64 one.
+ platform_aliases=(("win32-arm64", "win32-x64"),),
+)
+
+
+class CloudflaredRuntimeManager(ManagedRuntimeManager):
+ """Install and resolve the pinned cloudflared release remote access runs."""
+
+ def __init__(
+ self,
+ *,
+ runtime_dir: Path | None = None,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool | None = None,
+ ) -> None:
+ super().__init__(
+ spec=_CLOUDFLARED_SPEC,
+ runtime_dir=runtime_dir or paths.get_runtime_dir() / "cloudflared",
+ manifest_path=manifest_path or os.environ.get("VIBE_CLOUDFLARED_MANIFEST_PATH"),
+ manifest_url=(
+ manifest_url if manifest_url is not None else os.environ.get("VIBE_CLOUDFLARED_MANIFEST_URL")
+ ),
+ offline=env_flag_enabled("VIBE_CLOUDFLARED_OFFLINE") if offline is None else offline,
+ )
+
+ def _binary_version(self, binary: Path | None) -> str | None:
+ return _probe_cloudflared_version(binary)
+
+
+def _probe_cloudflared_version(binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ try:
+ proc = subprocess.run(
+ [str(binary), "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ # Status polls run this probe, so it must not flash a console on Windows.
+ **isolated_subprocess_kwargs(console=False),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if proc.returncode != 0:
+ return None
+ # ``cloudflared version 2026.10.0 (built 2026-10-05-17:37 UTC)``
+ words = (proc.stdout or "").strip().split()
+ return words[2] if len(words) > 2 and words[:2] == ["cloudflared", "version"] else None
diff --git a/core/dependency_network.py b/core/dependency_network.py
index b56cda68f..c08a8d3fe 100644
--- a/core/dependency_network.py
+++ b/core/dependency_network.py
@@ -40,6 +40,7 @@ RELEASE_MIRRORS = {
"https://github.com/avibe-bot/avault/releases/download/": "https://dl.avibe.bot/avault/releases/",
"https://github.com/tmux/tmux-builds/releases/download/": "https://dl.avibe.bot/tmux/releases/",
"https://github.com/BurntSushi/ripgrep/releases/download/": "https://dl.avibe.bot/ripgrep/releases/",
+ "https://github.com/cloudflare/cloudflared/releases/download/": "https://dl.avibe.bot/cloudflared/releases/",
}
# Index into download_sources() of the source that last completed a download.
_preferred_source = 0
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index c13460c92..e5bfde395 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -125,6 +125,8 @@ class ManagedRuntimeArchive:
binary_sha256: str | None
size: int | None
bin_path: str
+ # One of ARCHIVE_FORMATS; ``binary`` means the asset is the executable itself.
+ format: str = "tar.gz"
@dataclass(frozen=True)
@@ -344,8 +346,7 @@ class ManagedRuntimeManager:
staging_dir = Path(tempfile.mkdtemp(prefix="install-", dir=self.runtime_dir))
candidate_install_dir: Path | None = None
try:
- with tarfile.open(archive_path, "r:gz") as archive_file:
- safe_extract_tar(archive_file, staging_dir)
+ stage_archive(archive_path, archive.format, staging_dir, bin_path=archive.bin_path)
staged_binary = staging_dir / archive.bin_path
if not _is_regular_file(staged_binary):
return self._failure(
@@ -1771,6 +1772,7 @@ class ManagedRuntimeManager:
else None
)
bin_path = str(item.get("bin_path") or self.spec.default_bin_path)
+ archive_format = str(item.get("format") or "tar.gz")
raw_size = item.get(self.spec.archive_size_field)
size = int(raw_size) if raw_size is not None else None
if not self._archive_name_is_owned(name):
@@ -1794,6 +1796,9 @@ class ManagedRuntimeManager:
raise ValueError("invalid archive size")
if archive_path_is_unsafe(bin_path):
raise ValueError("unsafe binary path")
+ if archive_format not in ARCHIVE_FORMATS:
+ # An older client given a newer format refuses the manifest.
+ raise ValueError("unsupported archive format")
archives[platform_tag] = ManagedRuntimeArchive(
platform=platform_tag,
name=name,
@@ -1802,6 +1807,7 @@ class ManagedRuntimeManager:
binary_sha256=binary_sha256,
size=size,
bin_path=bin_path,
+ format=archive_format,
)
runtime_version = str(data.get(self.spec.version_field) or "")
if not _safe_metadata_value(runtime_version):
@@ -2279,6 +2285,28 @@ def install_lock_for(runtime_id: str) -> threading.Lock:
return _INSTALL_LOCKS.setdefault(runtime_id, threading.Lock())
+ARCHIVE_FORMATS = frozenset({"tar.gz", "binary"})
+
+
+def stage_archive(archive_path: Path, archive_format: str, staging_dir: Path, *, bin_path: str) -> None:
+ """Unpack a verified download into ``staging_dir``, one branch per archive format.
+
+ ``bin_path`` is relative to ``staging_dir`` and was checked at manifest parse to
+ stay inside it. A ``binary`` asset is the executable itself and lands at
+ ``bin_path``; archives place it there through their own layout.
+ """
+
+ if archive_format == "tar.gz":
+ with tarfile.open(archive_path, "r:gz") as archive_file:
+ safe_extract_tar(archive_file, staging_dir)
+ elif archive_format == "binary":
+ target = staging_dir / bin_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(archive_path, target)
+ else:
+ raise ValueError(f"unsupported archive format: {archive_format}")
+
+
def safe_extract_tar(archive: tarfile.TarFile, destination: Path) -> None:
supports_data_filter = hasattr(tarfile, "data_filter")
destination_resolved = destination.resolve()
diff --git a/docs/plans/cloudflared-runtime.md b/docs/plans/cloudflared-runtime.md
new file mode 100644
index 000000000..9ef394c49
--- /dev/null
+++ b/docs/plans/cloudflared-runtime.md
@@ -0,0 +1,91 @@
+# Managed cloudflared Runtime
+
+## Background
+
+Remote access runs cloudflared as its tunnel connector. Released versions
+downloaded `releases/latest` into `~/.avibe/bin/cloudflared` the first time
+remote access was enabled, without verifying it, and never refreshed it, or
+used a cloudflared found on PATH. An install therefore froze on whatever was
+latest that day. 2026.8.0 and 2026.8.1 both carry "Do not use this version"
+warnings, and installs from that window stayed on them.
+
+## Design
+
+- `vibe/cloudflared_runtime_manifest.json` pins one cloudflared release
+ (`release_tag`) for every platform: version, URL, size, archive sha256, and
+ the sha256 of the binary. Archive digests come from the GitHub asset
+ `digest`. For the darwin `.tgz` assets, the release notes' checksum is the
+ extracted binary's, not the archive's.
+- `core.cloudflared_runtime.CloudflaredRuntimeManager` installs it through the
+ shared managed-runtime core into
+ `~/.avibe/runtime/cloudflared/versions/<version>/<platform>/<fingerprint>/`,
+ mirror first, verified. Linux and Windows assets are the executable itself:
+ a manifest archive's optional `format` is `tar.gz` (the default) or
+ `binary`, which `stage_archive()` dispatches on. An unknown format fails the
+ manifest instead of being treated as `tar.gz`.
+- Platforms: darwin and linux on arm64 and x64, and Windows x64. Cloudflare
+ ships no windows-arm64 build, so win32-arm64 installs the x64 executable,
+ which Windows 11 on ARM runs under emulation. Windows 10 on ARM emulates
+ only 32-bit x86, so there the connector fails to start and remote access
+ reports the start error.
+- The runtime never resolves `releases/latest`; the pin moves with Avibe
+ releases.
+- `vibe runtime prepare` installs it while remote access is enabled and no
+ explicit `cloudflared_path` resolves, and
+ `vibe runtime clean` reclaims superseded versions.
+
+## Binary precedence
+
+1. An explicit `remote_access.vibe_cloud.cloudflared_path`.
+2. A verified managed pin: the packaged one, or an earlier one until the
+ packaged one installs.
+3. The binary recorded for the tracked connector, while it is still an
+ executable file.
+
+Nothing searches PATH, so a Homebrew cloudflared is replaced by the pinned
+copy. One ensure-pinned step runs before the connector lifecycle lock on every
+start and every automatic restart: unless an explicit path is set, it installs
+the packaged pin when that pin is missing. The lifecycle lock never waits on a
+download.
+
+A failed download never breaks a running tunnel. That is a property of the
+tracked connector, not of a location: the connector's state record holds the
+binary it runs, so status, settings changes, route recovery, and restarts keep
+resolving it, whether it came from the unpinned `~/.avibe/bin/cloudflared`,
+Homebrew, or an explicit path since cleared. `stop()` and the cleanup of an
+exited connector's records clear that record, and from then on only a pin
+serves. A stopped install whose download fails therefore gets the install
+error, exactly like a fresh install, and the monitor's restart backoff keeps
+retrying the download for a requested connector. The unpinned
+`~/.avibe/bin/cloudflared` is removed once the connector runs from another
+binary.
+
+## Upgrade
+
+The binary path is part of the connector's runtime signature, so after an
+upgrade the connector moves to the pinned binary once, during the reconcile at
+UI start: `start()` stops the old connector and starts the pinned one. The
+restart supervisor keeps the connector alive across a UI restart, so this is
+one short disconnect per pin change (up to `stop_pid`'s 8 s plus
+registration). Make-before-break through a candidate is not used for it: the
+candidate path needs readiness waits and promotion inside start(), which holds
+the connector lock throughout, for a change that happens once per release.
+
+## Availability
+
+Avibe cannot republish a third-party release, so the download mirror is the
+backup, as for ripgrep: `scripts/release_mirror.py` mirrors only releases a
+manifest pins under `cloudflared/`, fails the run when GitHub's assets diverge
+from the manifest, and keeps earlier pinned releases.
+
+## Maintenance
+
+- A maintainer checks upstream monthly and opens a bump PR for a security
+ fix, a bug on a path Avibe uses, or when the pin is six months old.
+ Cloudflare supports a release for one year.
+- Cloudflare stops publishing darwin-amd64 builds in 2027. From then on
+ darwin-x64 stays on its last build while the other platforms move on, which
+ needs per-platform release tags in the manifest schema.
+- Do not add `--no-prechecks`: with DNS unavailable at start, 2026.3.0 and
+ 2026.10.0 both exit in about a second, and the pre-checks only add an early
+ exit when DNS works but port 7844 is blocked for UDP and TCP.
diff --git a/docs/plans/release-download-mirror.md b/docs/plans/release-download-mirror.md
index 9805b267f..bbcf09022 100644
--- a/docs/plans/release-download-mirror.md
+++ b/docs/plans/release-download-mirror.md
@@ -36,14 +36,16 @@ Each mirrored repository owns one bucket root:
| `avibe-bot/avault` | `avault/` |
| `tmux/tmux-builds` | `tmux/` |
| `BurntSushi/ripgrep` | `ripgrep/` |
+| `cloudflare/cloudflared` | `cloudflared/` |
`tmux/tmux-builds` is third-party: the ISC-licensed tmux builds the managed
tmux runtime pins. Its releases are mirrored like Avibe's own, with their
`LICENSES.tar.gz`.
-`BurntSushi/ripgrep` is third-party too, and only the releases that
-`vibe/ripgrep_runtime_manifest.json` pins or once pinned are mirrored. See
-`docs/plans/ripgrep-runtime.md`.
+`BurntSushi/ripgrep` and `cloudflare/cloudflared` are third-party too, and
+only the releases that `vibe/ripgrep_runtime_manifest.json` and
+`vibe/cloudflared_runtime_manifest.json` pin or once pinned are mirrored. See
+`docs/plans/ripgrep-runtime.md` and `docs/plans/cloudflared-runtime.md`.
- `https://dl.avibe.bot/<root>releases/<tag>/<asset>` is byte-identical to
`https://github.com/<repository>/releases/download/<tag>/<asset>`.
@@ -101,8 +103,8 @@ tmux runtime pins. Its releases are mirrored like Avibe's own, with their
- tmux-builds keeps no prereleases. Its `preview` prerelease is rebuilt in
place, changing bytes under unchanged asset names, which the reconciler must
treat as published bytes changing.
-- ripgrep keeps every release a manifest has pinned, and nothing else; its
- root only grows. The mirror is those releases' backup. When GitHub no longer
+- ripgrep and cloudflared keep every release a manifest has pinned, and nothing
+ else; their roots only grow. The mirror is those releases' backup. When GitHub no longer
publishes a currently pinned archive with the manifest's size and digest, the
run fails before planning. A release an earlier manifest pinned stays in the
index and the bucket after the pin moves, because released Avibe versions
@@ -159,8 +161,9 @@ Cloudflare configuration lives outside the repository. The expected state:
## Client downloads
-The managed git, tmux, and ripgrep runtimes, the model hub engine, Show
-Runtime manifest archives, and the askill and avault binaries download through
+The managed git, tmux, ripgrep, and cloudflared runtimes, the model hub
+engine, Show Runtime manifest archives, and the askill and avault binaries
+download through
`core.dependency_network.fetch_to_path`:
- A mirrored repository's release URL without a query tries the mirror, then
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
index 9fbd123db..8d9adc942 100644
--- a/docs/plans/tunnel-quality-and-route-recovery.md
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -637,8 +637,8 @@ busy, because a later tick repeats them, and a startup orphan-candidate
reconciliation that found it busy is retried on later ticks. Record cleanups
that nothing repeats (a discarded candidate, a drained connector, a cleared
tail rollback) wait up to 60 seconds, three times the longest hold, and
-otherwise log an error and leave the records for reconciliation. Waits such as candidate warm-up and downloading a
-missing cloudflared run outside it, and the OS releases it when its holder
+otherwise log an error and leave the records for reconciliation. Waits such as candidate warm-up and installing the
+cloudflared pin run outside it, and the OS releases it when its holder
dies. A request path that is not a regular file is no request.
So only an explicit `stop()` withdraws the request, and no stop or start in
diff --git a/docs/release.md b/docs/release.md
index f0c65146e..e1f8d97d9 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -33,7 +33,7 @@ Published managed-runtime manifests are availability contracts. Keep their
release URLs under the scheduled manifest-verified backup/recovery guard.
Publish replacement assets before changing a pinned manifest so the guard never
restores bytes from a different release. A manifest that pins a third-party
-release that Avibe cannot republish (ripgrep) relies on the download mirror as
+release that Avibe cannot republish (ripgrep, cloudflared) relies on the download mirror as
that guard: the mirror holds the pinned release, verified against the manifest.
## Download mirror
diff --git a/pyproject.toml b/pyproject.toml
index 538911065..9de2c30ea 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -109,6 +109,7 @@ artifacts = [
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
"vibe/ripgrep_runtime_manifest.json",
+ "vibe/cloudflared_runtime_manifest.json",
"vibe/model_hub_runtime/cliproxyapi_manifest.json",
]
@@ -142,6 +143,7 @@ include = [
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
"vibe/ripgrep_runtime_manifest.json",
+ "vibe/cloudflared_runtime_manifest.json",
"vibe/model_hub_runtime/cliproxyapi_manifest.json",
"README.md",
"LICENSE",
diff --git a/scripts/release_mirror.py b/scripts/release_mirror.py
index 151caa8d8..a8e97ff02 100644
--- a/scripts/release_mirror.py
+++ b/scripts/release_mirror.py
@@ -34,13 +34,17 @@ REPOSITORIES = {
"avibe-bot/avault": "avault/",
"tmux/tmux-builds": "tmux/",
"BurntSushi/ripgrep": "ripgrep/",
+ "cloudflare/cloudflared": "cloudflared/",
}
# Repositories mirrored only for the releases packaged managed-runtime
# manifests pin. The mirror is those releases' backup: a pinned archive GitHub
# no longer publishes with the manifest's bytes fails the run, and a release an
# earlier manifest pinned stays, since released Avibe versions still name it.
# ripgrep's older releases also carry no GitHub digest.
-PINNED_BY_MANIFEST = {"BurntSushi/ripgrep": REPO_ROOT / "vibe" / "ripgrep_runtime_manifest.json"}
+PINNED_BY_MANIFEST = {
+ "BurntSushi/ripgrep": REPO_ROOT / "vibe" / "ripgrep_runtime_manifest.json",
+ "cloudflare/cloudflared": REPO_ROOT / "vibe" / "cloudflared_runtime_manifest.json",
+}
# Repositories mirrored without prereleases. tmux-builds rebuilds its
# ``preview`` prerelease in place, changing bytes under unchanged asset names,
# which the mirror must treat as published bytes changing.
diff --git a/tests/test_cloudflared_runtime.py b/tests/test_cloudflared_runtime.py
new file mode 100644
index 000000000..d625e5793
--- /dev/null
+++ b/tests/test_cloudflared_runtime.py
@@ -0,0 +1,341 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from pathlib import Path
+
+import psutil
+import pytest
+
+from core import managed_runtime
+from core.cloudflared_runtime import CloudflaredRuntimeManager
+from tests.test_remote_access_vibe_cloud import _config
+from vibe import remote_access, runtime
+
+UPSTREAM = "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0"
+
+
+def _fake_cloudflared(path: Path, version: str) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ "#!/bin/sh\n"
+ f'if [ "$1" = "--version" ]; then echo "cloudflared version {version} (built test)"; exit 0; fi\n'
+ "while :; do sleep 0.2; done\n",
+ encoding="utf-8",
+ )
+ path.chmod(0o755)
+ return path
+
+
+def _pin_test_cloudflared(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, version: str = "2026.10.0", **overrides
+) -> Path:
+ """Pin a stand-in raw cloudflared executable in a test manifest the default manager reads."""
+
+ asset = _fake_cloudflared(tmp_path / "release" / version / "cloudflared-test", version)
+ digest = hashlib.sha256(asset.read_bytes()).hexdigest()
+ entry = {
+ "name": asset.name,
+ "url": asset.as_uri(),
+ "format": "binary",
+ "sha256": digest,
+ "binary_sha256": digest,
+ "size": asset.stat().st_size,
+ "bin_path": "cloudflared",
+ **overrides,
+ }
+ manifest = tmp_path / "cloudflared_runtime_manifest.json"
+ manifest.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "cloudflared_version": version,
+ "source": "test",
+ "release_tag": version,
+ "archives": {managed_runtime.runtime_platform_tag(): entry},
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("VIBE_CLOUDFLARED_MANIFEST_PATH", str(manifest))
+ return asset
+
+
+def test_packaged_manifest_pins_one_release_for_every_platform(tmp_path: Path) -> None:
+ manifest = CloudflaredRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)._load_manifest(
+ allow_network=False
+ )
+
+ assert manifest is not None
+ assert manifest.runtime_version == manifest.payload["release_tag"] == "2026.10.0"
+ assets = {
+ "darwin-arm64": ("cloudflared-darwin-arm64.tgz", "tar.gz", "cloudflared"),
+ "darwin-x64": ("cloudflared-darwin-amd64.tgz", "tar.gz", "cloudflared"),
+ "linux-arm64": ("cloudflared-linux-arm64", "binary", "cloudflared"),
+ "linux-x64": ("cloudflared-linux-amd64", "binary", "cloudflared"),
+ "win32-x64": ("cloudflared-windows-amd64.exe", "binary", "cloudflared.exe"),
+ }
+ assert set(manifest.archives) == set(assets)
+ for platform_tag, (name, archive_format, bin_path) in assets.items():
+ archive = manifest.archives[platform_tag]
+ assert (archive.name, archive.format, archive.bin_path) == (name, archive_format, bin_path)
+ assert archive.url == f"{UPSTREAM}/{name}"
+ # A raw asset is the executable; a darwin archive's digest is not the binary's.
+ assert (archive.sha256 == archive.binary_sha256) == (archive_format == "binary")
+
+
+def test_raw_binary_asset_installs_verified_at_its_bin_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ asset = _pin_test_cloudflared(tmp_path, monkeypatch)
+
+ result = CloudflaredRuntimeManager().ensure()
+
+ assert result["ok"] is True
+ binary = CloudflaredRuntimeManager().resolve_binary()
+ assert binary is not None and binary.name == "cloudflared"
+ assert binary.read_bytes() == asset.read_bytes()
+ assert os.access(binary, os.X_OK)
+
+
+ ("override", "reason"),
+ [
+ ({"binary_sha256": "0" * 64}, "cloudflared_binary_checksum_mismatch"),
+ ({"format": "zip"}, "cloudflared_manifest_invalid"),
+ ],
+)
+def test_unverifiable_or_unknown_assets_do_not_install(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, override: dict, reason: str
+) -> None:
+ _pin_test_cloudflared(tmp_path, monkeypatch, **override)
+
+ result = CloudflaredRuntimeManager().ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == reason
+ assert CloudflaredRuntimeManager().resolve_binary() is None
+
+
+def test_windows_arm64_installs_the_x64_executable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ manager = CloudflaredRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)
+ manifest = manager._load_manifest(allow_network=False)
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "win32-arm64")
+
+ archive = manager._manifest_archive_for_platform(manifest)
+
+ assert archive is not None and archive.name == "cloudflared-windows-amd64.exe"
+
+
+def remote_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ # No pin until a test sets one: nothing downloads from the network.
+ monkeypatch.setenv("VIBE_CLOUDFLARED_MANIFEST_PATH", str(tmp_path / "no-pin.json"))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ monkeypatch.setattr(remote_access, "_PREFERRED_PROTOCOL", None)
+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)
+
+ def process_command(pid: int) -> str | None:
+ # The macOS fallback runs setuid ``ps``, which a sandboxed test cannot exec.
+ try:
+ return " ".join(psutil.Process(pid).cmdline()) or None
+ except psutil.Error:
+ return None
+
+ monkeypatch.setattr(runtime, "get_process_command", process_command)
+ yield config
+ remote_access.stop()
+
+
+def _start_released_connector(monkeypatch: pytest.MonkeyPatch, binary: Path) -> int:
+ """Run a connector from ``binary`` the way a released version resolved it."""
+
+ with monkeypatch.context() as patched:
+ patched.setattr(remote_access, "_resolve_binary", lambda config=None: str(binary))
+ result = remote_access.start()
+ assert result["ok"] is True and result["started"] is True
+ return int(result["pid"])
+
+
+def _recorded_binary() -> str | None:
+ return (remote_access._read_state() or {}).get("binary_path")
+
+
[email protected]("released_source", ["unpinned_managed_copy", "homebrew_on_path"])
+def test_existing_connector_moves_to_the_pinned_copy(
+ remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, released_source: str
+) -> None:
+ if released_source == "unpinned_managed_copy":
+ released = _fake_cloudflared(remote_access._legacy_cloudflared_path(), "2026.8.0")
+ else:
+ released = _fake_cloudflared(tmp_path / "homebrew" / "bin" / "cloudflared", "2026.3.0")
+ monkeypatch.setenv("PATH", f"{released.parent}{os.pathsep}{os.environ.get('PATH', '')}")
+ released_pid = _start_released_connector(monkeypatch, released)
+ _pin_test_cloudflared(tmp_path, monkeypatch)
+
+ # UI-start reconcile after the upgrade.
+ result = remote_access.start()
+
+ pinned = CloudflaredRuntimeManager().resolve_binary()
+ assert result["ok"] is True and result["started"] is True
+ assert pinned is not None and _recorded_binary() == str(pinned)
+ assert remote_access._is_cloudflared_pid(result["pid"])
+ assert not remote_access._is_cloudflared_pid(released_pid)
+ assert remote_access._legacy_cloudflared_path().exists() is False
+ if released_source == "homebrew_on_path":
+ assert released.exists() # never touched
+
+
[email protected]("released_source", ["unpinned_managed_copy", "homebrew_on_path"])
+def test_failed_download_keeps_the_running_connector_and_its_binary(
+ remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, released_source: str
+) -> None:
+ if released_source == "unpinned_managed_copy":
+ released = _fake_cloudflared(remote_access._legacy_cloudflared_path(), "2026.8.0")
+ else:
+ released = _fake_cloudflared(tmp_path / "homebrew" / "bin" / "cloudflared", "2026.3.0")
+ monkeypatch.setenv("PATH", f"{released.parent}{os.pathsep}{os.environ.get('PATH', '')}")
+ released_pid = _start_released_connector(monkeypatch, released)
+ _pin_test_cloudflared(tmp_path, monkeypatch, url=(tmp_path / "missing").as_uri())
+
+ result = remote_access.start()
+
+ assert result["ok"] is True and result["started"] is False
+ assert remote_access._read_pid() == released_pid
+ assert remote_access._is_cloudflared_pid(released_pid)
+ assert released.exists()
+ # status, settings, recovery, and restart resolve the binary the tracked connector runs.
+ assert remote_access._resolve_binary(remote_home) == str(released)
+ assert remote_access.status(remote_home)["binary_found"] is True
+
+ remote_access.stop()
+
+ # Without a tracked connector nothing falls back to that binary, and PATH is never searched.
+ assert remote_access._resolve_binary(remote_home) is None
+
+
+def test_failed_download_does_not_start_from_the_unpinned_copy(
+ remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ legacy = _fake_cloudflared(remote_access._legacy_cloudflared_path(), "2026.8.0")
+ _pin_test_cloudflared(tmp_path, monkeypatch, url=(tmp_path / "missing").as_uri())
+
+ result = remote_access.start()
+
+ # Same as a fresh install: the install error, and the request lets the monitor retry.
+ assert result["ok"] is False and result["error"] == "cloudflared_install_failed"
+ assert remote_access._read_pid() is None
+ assert remote_access._connector_requested_path().is_file()
+ assert legacy.exists()
+
+
+def test_explicit_cloudflared_path_wins_and_path_is_not_consulted(
+ remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ homebrew = _fake_cloudflared(tmp_path / "homebrew" / "bin" / "cloudflared", "2026.3.0")
+ monkeypatch.setenv("PATH", f"{homebrew.parent}{os.pathsep}{os.environ.get('PATH', '')}")
+ explicit = _fake_cloudflared(tmp_path / "explicit" / "cloudflared", "2026.9.0")
+
+ assert remote_access._resolve_binary(remote_home) is None # nothing pinned installed, PATH ignored
+ remote_home.remote_access.vibe_cloud.cloudflared_path = str(explicit)
+ remote_home.save()
+
+ result = remote_access.start()
+
+ assert result["ok"] is True and _recorded_binary() == str(explicit)
+ assert remote_access._is_cloudflared_pid(result["pid"])
+
+
+def test_prepare_installs_the_pin_only_while_remote_access_is_enabled(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from vibe import cli
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _pin_test_cloudflared(tmp_path, monkeypatch)
+ config = _config()
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+
+ assert cli._ensure_cloudflared_during_prepare() == {"ok": True, "skipped": True, "reason": "remote_access_disabled"}
+ assert CloudflaredRuntimeManager().resolve_binary() is None
+
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+
+ assert cli._ensure_cloudflared_during_prepare()["ok"] is True
+ assert CloudflaredRuntimeManager().resolve_binary() is not None
+
+
+def test_prepare_skips_the_pin_when_an_explicit_cloudflared_path_resolves(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from vibe import cli
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _pin_test_cloudflared(tmp_path, monkeypatch)
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.remote_access.vibe_cloud.cloudflared_path = str(
+ _fake_cloudflared(tmp_path / "explicit" / "cloudflared", "2026.9.0")
+ )
+ config.save()
+
+ assert cli._ensure_cloudflared_during_prepare() == {
+ "ok": True,
+ "skipped": True,
+ "reason": "explicit_cloudflared_path",
+ }
+ assert CloudflaredRuntimeManager().resolve_binary() is None
+
+
+def test_version_probe_runs_without_a_console(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from core import cloudflared_runtime
+
+ consoles = []
+
+ def isolated_subprocess_kwargs(*, console: bool = True) -> dict:
+ consoles.append(console)
+ return {}
+
+ monkeypatch.setattr(cloudflared_runtime, "isolated_subprocess_kwargs", isolated_subprocess_kwargs)
+
+ version = cloudflared_runtime._probe_cloudflared_version(_fake_cloudflared(tmp_path / "cloudflared", "2026.10.0"))
+
+ assert version == "2026.10.0"
+ assert consoles == [False]
+
+
+def test_a_new_pin_replaces_an_earlier_verified_install(remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _pin_test_cloudflared(tmp_path, monkeypatch, version="2026.9.0")
+ first = remote_access.start()
+ earlier = CloudflaredRuntimeManager().resolve_binary()
+ assert first["ok"] is True and earlier is not None and _recorded_binary() == str(earlier)
+
+ # The next Avibe release packages a newer pin; UI-start reconcile moves to it.
+ _pin_test_cloudflared(tmp_path, monkeypatch, version="2026.10.0")
+ result = remote_access.start()
+
+ pinned = CloudflaredRuntimeManager().resolve_binary()
+ assert result["ok"] is True and result["started"] is True
+ assert pinned is not None and pinned != earlier
+ assert "2026.10.0" in str(pinned) and _recorded_binary() == str(pinned)
+ assert not remote_access._is_cloudflared_pid(first["pid"])
+
+
+def test_explicit_legacy_path_through_an_alias_is_never_removed(
+ remote_home, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ legacy = _fake_cloudflared(remote_access._legacy_cloudflared_path(), "2026.8.0")
+ alias = tmp_path / "vibe_remote_alias"
+ alias.symlink_to(legacy.parent.parent, target_is_directory=True)
+ remote_home.remote_access.vibe_cloud.cloudflared_path = str(alias / "bin" / legacy.name)
+ remote_home.save()
+
+ result = remote_access.start()
+
+ assert result["ok"] is True and result["started"] is True
+ assert legacy.exists()
diff --git a/tests/test_release_mirror.py b/tests/test_release_mirror.py
index 4c104fcf5..339abf153 100644
--- a/tests/test_release_mirror.py
+++ b/tests/test_release_mirror.py
@@ -334,3 +334,19 @@ def test_every_publishing_workflow_named_by_the_mirror_trigger_exists():
triggers = workflow("release-mirror.yml")[True]["workflow_run"]["workflows"]
assert triggers and set(triggers) <= names
+
+
[email protected]("repository", sorted(mirror.PINNED_BY_MANIFEST))
+def test_pinned_manifest_archives_download_from_the_mirrored_release(repository):
+ from core import dependency_network
+
+ manifest = json.loads(mirror.PINNED_BY_MANIFEST[repository].read_text(encoding="utf-8"))
+ tag = manifest["release_tag"]
+ for archive in manifest["archives"].values():
+ url = f"https://github.com/{repository}/releases/download/{tag}/{archive['name']}"
+ # The mirror holds only the pinned release, so every archive must come from it.
+ assert archive["url"] == url
+ assert dependency_network.download_sources(url) == [
+ f"https://dl.avibe.bot/{mirror.REPOSITORIES[repository]}releases/{tag}/{archive['name']}",
+ url,
+ ]
diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.py
index f2020b571..9df27ac5c 100644
--- a/tests/test_tunnel_recovery.py
+++ b/tests/test_tunnel_recovery.py
@@ -1880,6 +1880,7 @@ def test_ra_tq_034_missing_cloudflared_downloads_outside_the_lifecycle_lock(monk
config, _ = _setup_exiting_connector(monkeypatch, tmp_path)
config.remote_access.vibe_cloud.cloudflared_path = ""
config.save()
+ monkeypatch.setattr(remote_access, "_cloudflared_pin_needed", lambda loaded=None: True)
monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded=None: None)
downloads = []
@@ -1996,11 +1997,11 @@ def test_ra_tq_034_concurrent_starts_share_one_cloudflared_download(monkeypatch,
checks = []
downloads = []
- def resolve_binary(loaded=None):
+ def pin_needed(loaded=None):
checks.append(threading.current_thread().name)
if len(checks) >= 2:
both_checked.set()
- return "/fake/cloudflared" if installed.is_set() else None
+ return not installed.is_set()
def install_cloudflared():
downloads.append(threading.current_thread().name)
@@ -2008,11 +2009,11 @@ def test_ra_tq_034_concurrent_starts_share_one_cloudflared_download(monkeypatch,
installed.set()
return {"ok": True, "path": "/fake/cloudflared"}
- monkeypatch.setattr(remote_access, "_resolve_binary", resolve_binary)
+ monkeypatch.setattr(remote_access, "_cloudflared_pin_needed", pin_needed)
monkeypatch.setattr(remote_access, "install_cloudflared", install_cloudflared)
def download():
- remote_access._download_missing_cloudflared(config)
+ remote_access._ensure_cloudflared_pin(config)
threads = [threading.Thread(target=download, name=f"start-{i}") for i in range(2)]
for thread in threads:
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 5e242bf04..ec6f22b22 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -4097,8 +4097,8 @@ def test_runtime_clean_json_keeps_nested_failure_payload_and_exits_nonzero(monke
@pytest.mark.parametrize(
("language", "consumer_scope", "failure_contract"),
[
- ("en", "Show, Git, Model Hub, tmux, and ripgrep", "exit nonzero if any cleanup fails"),
- ("zh", "Show、Git、Model Hub、tmux 和 ripgrep", "任一清理失败时以非零状态退出"),
+ ("en", "Show, Git, Model Hub, tmux, ripgrep, and cloudflared", "exit nonzero if any cleanup fails"),
+ ("zh", "Show、Git、Model Hub、tmux、ripgrep 和 cloudflared", "任一清理失败时以非零状态退出"),
],
)
def test_runtime_clean_help_names_consumers_and_failure_exit(
@@ -4867,7 +4867,7 @@ def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(
def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatch):
- from core import ripgrep_runtime, tmux_runtime
+ from core import cloudflared_runtime, ripgrep_runtime, tmux_runtime
from vibe.model_hub_runtime import installer as model_hub_installer
calls = []
@@ -4896,6 +4896,7 @@ def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatc
lambda: FakeManager("tmux"),
)
monkeypatch.setattr(ripgrep_runtime, "RipgrepRuntimeManager", lambda: FakeManager("ripgrep"))
+ monkeypatch.setattr(cloudflared_runtime, "CloudflaredRuntimeManager", lambda: FakeManager("cloudflared"))
results = cli._clean_managed_runtime_consumers(keep_previous=2, dry_run=True)
@@ -4904,12 +4905,14 @@ def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatc
"model_hub_engine",
"tmux",
"ripgrep",
+ "cloudflared",
]
assert calls == [
("git", 2, True),
("model_hub_engine", 2, True),
("tmux", 2, True),
("ripgrep", 2, True),
+ ("cloudflared", 2, True),
]
diff --git a/vibe/cli.py b/vibe/cli.py
index 966ac2396..433323aed 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -16256,6 +16256,7 @@ def cmd_runtime(args) -> int:
tmux = _ensure_tmux_during_prepare(offline=bool(offline), force=force)
git = _ensure_git_during_prepare(offline=offline, force=force)
ripgrep = _ensure_ripgrep_during_prepare(offline=offline, force=force)
+ cloudflared = _ensure_cloudflared_during_prepare(offline=offline, force=force)
avault = _ensure_avault_during_prepare(offline=bool(offline), force=force)
model_hub_engine = _ensure_model_hub_engine_during_prepare(
offline=bool(offline),
@@ -16267,6 +16268,7 @@ def cmd_runtime(args) -> int:
payload["tmux"] = tmux
payload["git"] = git
payload["ripgrep"] = ripgrep
+ payload["cloudflared"] = cloudflared
install = payload.get("install") if isinstance(payload.get("install"), dict) else {}
policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else {}
runtime_prepared = bool(payload.get("ok"))
@@ -16378,6 +16380,28 @@ def cmd_runtime(args) -> int:
),
file=sys.stderr,
)
+ if cloudflared.get("skipped"):
+ pass
+ elif cloudflared.get("ok"):
+ print(
+ i18n_t(
+ (
+ "runtime.prepare.cloudflaredInstalled"
+ if cloudflared.get("changed")
+ else "runtime.prepare.cloudflaredReady"
+ ),
+ language,
+ )
+ )
+ else:
+ print(
+ i18n_t(
+ "runtime.prepare.cloudflaredNotReady",
+ language,
+ reason=cloudflared.get("message") or cloudflared.get("reason") or "install failed",
+ ),
+ file=sys.stderr,
+ )
strict_ok = runtime_prepared and _git_prepare_satisfies_strict(git)
return 1 if getattr(args, "strict", False) and not strict_ok else 0
if command == "clean":
@@ -16593,6 +16617,26 @@ def _ensure_ripgrep_during_prepare(offline: bool | None = None, force: bool = Fa
return {"ok": False, "message": str(exc)}
+def _ensure_cloudflared_during_prepare(offline: bool | None = None, force: bool = False) -> dict:
+ """Prepare the pinned cloudflared while remote access is enabled; never fails prepare."""
+
+ try:
+ config = V2Config.load()
+ cloud = config.remote_access.vibe_cloud
+ if not (config.remote_access.provider == "vibe_cloud" and cloud.enabled and cloud.tunnel_token):
+ return {"ok": True, "skipped": True, "reason": "remote_access_disabled"}
+ from vibe import remote_access
+
+ if remote_access._explicit_cloudflared(config):
+ # The connector runs the configured binary, so the pin would go unused.
+ return {"ok": True, "skipped": True, "reason": "explicit_cloudflared_path"}
+ from core.cloudflared_runtime import CloudflaredRuntimeManager
+
+ return CloudflaredRuntimeManager(offline=offline).ensure(force=force)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
def _format_byte_size(size: int) -> str:
if size < 1024:
return f"{size} B"
@@ -16606,6 +16650,7 @@ def _format_byte_size(size: int) -> str:
def _managed_runtime_cleaners() -> tuple[tuple[str, Callable[..., dict[str, Any]]], ...]:
"""Return the shared-runtime cleanup passes in stable output order."""
+ from core.cloudflared_runtime import CloudflaredRuntimeManager
from core.ripgrep_runtime import RipgrepRuntimeManager
from core.tmux_runtime import get_tmux_runtime_manager
from vibe.model_hub_runtime.installer import EngineRuntimeManager
@@ -16629,11 +16674,18 @@ def _managed_runtime_cleaners() -> tuple[tuple[str, Callable[..., dict[str, Any]
dry_run=dry_run,
)
+ def clean_cloudflared(*, keep_previous: int, dry_run: bool) -> dict[str, Any]:
+ return CloudflaredRuntimeManager().clean(
+ keep_previous=keep_previous,
+ dry_run=dry_run,
+ )
+
return (
("git", _clean_git_runtime),
("model_hub_engine", clean_model_hub),
("tmux", clean_tmux),
("ripgrep", clean_ripgrep),
+ ("cloudflared", clean_cloudflared),
)
@@ -16695,6 +16747,7 @@ def _managed_runtime_label(runtime_id: str) -> str:
"model_hub_engine": "Model Hub Runtime",
"tmux": "tmux Runtime",
"ripgrep": "ripgrep Runtime",
+ "cloudflared": "cloudflared Runtime",
}
return labels.get(runtime_id, runtime_id.replace("-", " ").replace("_", " ").title())
diff --git a/vibe/cloudflared_runtime_manifest.json b/vibe/cloudflared_runtime_manifest.json
new file mode 100644
index 000000000..4b301611f
--- /dev/null
+++ b/vibe/cloudflared_runtime_manifest.json
@@ -0,0 +1,52 @@
+{
+ "schema_version": 1,
+ "cloudflared_version": "2026.10.0",
+ "source": "cloudflare/cloudflared",
+ "source_url": "https://github.com/cloudflare/cloudflared/releases/tag/2026.10.0",
+ "release_tag": "2026.10.0",
+ "archives": {
+ "darwin-arm64": {
+ "name": "cloudflared-darwin-arm64.tgz",
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-darwin-arm64.tgz",
+ "sha256": "a2f79ff7b9420aa537d74af239f376da170bbabeb529aec416002adac6a72e70",
+ "binary_sha256": "72edfd3eea463aef4d5cb89e2e209cecb048cc756c2b01915de2e0ad7cb39830",
+ "size": 19809074,
+ "bin_path": "cloudflared"
+ },
+ "darwin-x64": {
+ "name": "cloudflared-darwin-amd64.tgz",
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-darwin-amd64.tgz",
+ "sha256": "903845b81828c8cb3c5d13d816a2de71c06a3da5785469df8eb0e1b736d92f9f",
+ "binary_sha256": "0560c9ab7281ac3f746055323623ed23bc0405b6dab9400474020cba33a978da",
+ "size": 21741581,
+ "bin_path": "cloudflared"
+ },
+ "linux-arm64": {
+ "name": "cloudflared-linux-arm64",
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-arm64",
+ "format": "binary",
+ "sha256": "e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08",
+ "binary_sha256": "e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08",
+ "size": 37687584,
+ "bin_path": "cloudflared"
+ },
+ "linux-x64": {
+ "name": "cloudflared-linux-amd64",
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-amd64",
+ "format": "binary",
+ "sha256": "d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db",
+ "binary_sha256": "d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db",
+ "size": 40129756,
+ "bin_path": "cloudflared"
+ },
+ "win32-x64": {
+ "name": "cloudflared-windows-amd64.exe",
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-windows-amd64.exe",
+ "format": "binary",
+ "sha256": "86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c",
+ "binary_sha256": "86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c",
+ "size": 55365048,
+ "bin_path": "cloudflared.exe"
+ }
+ }
+}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index e1c0b9583..c1b70df05 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1211,10 +1211,13 @@
"modelHubEngineNotReady": "Model Hub engine not ready: {reason}",
"ripgrepInstalled": "ripgrep installed.",
"ripgrepReady": "ripgrep ready.",
- "ripgrepNotReady": "ripgrep not ready: {reason}"
+ "ripgrepNotReady": "ripgrep not ready: {reason}",
+ "cloudflaredInstalled": "cloudflared installed.",
+ "cloudflaredReady": "cloudflared ready.",
+ "cloudflaredNotReady": "cloudflared not ready: {reason}"
},
"clean": {
- "commandHelp": "Remove stale Show, Git, Model Hub, tmux, and ripgrep runtime installs and archives; exit nonzero if any cleanup fails.",
+ "commandHelp": "Remove stale Show, Git, Model Hub, tmux, ripgrep, and cloudflared runtime installs and archives; exit nonzero if any cleanup fails.",
"dryRunHelp": "Report stale archives and cache entries without removing anything.",
"wouldRemoveItems": "Would remove {count} Show Runtime cache item(s).",
"wouldRemoveArchives": "Would remove {count} downloaded Show Runtime archive(s) ({size}).",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 638e32c6b..7996040f9 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1211,10 +1211,13 @@
"modelHubEngineNotReady": "Model Hub 引擎尚未就绪:{reason}",
"ripgrepInstalled": "ripgrep 已安装。",
"ripgrepReady": "ripgrep 已就绪。",
- "ripgrepNotReady": "ripgrep 尚未就绪:{reason}"
+ "ripgrepNotReady": "ripgrep 尚未就绪:{reason}",
+ "cloudflaredInstalled": "cloudflared 已安装。",
+ "cloudflaredReady": "cloudflared 已就绪。",
+ "cloudflaredNotReady": "cloudflared 尚未就绪:{reason}"
},
"clean": {
- "commandHelp": "清理过期的 Show、Git、Model Hub、tmux 和 ripgrep 运行时安装与归档;任一清理失败时以非零状态退出。",
+ "commandHelp": "清理过期的 Show、Git、Model Hub、tmux、ripgrep 和 cloudflared 运行时安装与归档;任一清理失败时以非零状态退出。",
"dryRunHelp": "仅报告可清理的归档与缓存条目,不删除任何内容。",
"wouldRemoveItems": "将清理 {count} 项 Show Runtime 缓存。",
"wouldRemoveArchives": "将清理 {count} 个已下载的 Show Runtime 归档({size})。",
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index dc4626118..7ea610757 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -15,16 +15,12 @@ import json
import logging
import ntpath
import os
-import platform
import re
import shlex
import secrets
-import shutil
import socket
import ssl
-import stat
import subprocess
-import tarfile
import tempfile
import threading
import time
@@ -45,7 +41,6 @@ from vibe import tunnel_quality
logger = logging.getLogger(__name__)
-CLOUDFLARED_BASE_URL = "https://github.com/cloudflare/cloudflared/releases/latest/download"
SESSION_COOKIE_NAME = "__Host-vibe_remote_session"
PERSONAL_SESSION_TTL_SECONDS = 24 * 60 * 60
PERSONAL_SESSION_RENEW_AFTER_SECONDS = PERSONAL_SESSION_TTL_SECONDS // 2
@@ -231,13 +226,11 @@ class OAuthCodeExchangeError(Exception):
self.detail = detail or ""
-def _bin_dir() -> Path:
- return paths.get_vibe_remote_dir() / "bin"
+def _legacy_cloudflared_path() -> Path:
+ """The unpinned copy released versions installed before the managed runtime."""
-
-def _managed_cloudflared_path() -> Path:
suffix = ".exe" if os.name == "nt" else ""
- return _bin_dir() / f"cloudflared{suffix}"
+ return paths.get_vibe_remote_dir() / "bin" / f"cloudflared{suffix}"
def _pid_path() -> Path:
@@ -354,21 +347,6 @@ def _clear_cloudflared_logs() -> None:
pass
-def _asset_name() -> str:
- system = platform.system().lower()
- machine = platform.machine().lower()
- arch = "amd64" if machine in {"x86_64", "amd64"} else "arm64" if machine in {"aarch64", "arm64"} else ""
- if not arch:
- raise ValueError(f"Unsupported architecture for cloudflared: {machine}")
- if system == "linux":
- return f"cloudflared-linux-{arch}"
- if system == "darwin":
- return f"cloudflared-darwin-{arch}.tgz"
- if system == "windows" and arch == "amd64":
- return "cloudflared-windows-amd64.exe"
- raise ValueError(f"Unsupported OS for cloudflared: {system}")
-
-
def _version(path: str) -> str | None:
try:
result = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=8, check=False)
@@ -378,68 +356,22 @@ def _version(path: str) -> str | None:
return output[0] if output else None
-def _make_executable(path: Path) -> None:
- if os.name == "nt":
- return
- mode = path.stat().st_mode
- path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
-
-
-def _copy_stream_atomically(source: Any, target: Path) -> None:
- target.parent.mkdir(parents=True, exist_ok=True)
- temp_target = target.with_name(f".{target.name}.tmp")
- temp_target.unlink(missing_ok=True)
- try:
- with temp_target.open("wb") as output:
- shutil.copyfileobj(source, output)
- os.replace(temp_target, target)
- except Exception:
- temp_target.unlink(missing_ok=True)
- raise
-
-
-def _safe_extract_cloudflared(archive: tarfile.TarFile, target: Path) -> None:
- for member in archive.getmembers():
- member_name = Path(member.name)
- if member_name.name != "cloudflared":
- continue
- if member_name.is_absolute() or ".." in member_name.parts or not member.isfile():
- raise RuntimeError("Downloaded cloudflared archive contained an unsafe entry")
- source = archive.extractfile(member)
- if source is None:
- raise RuntimeError("Downloaded cloudflared archive did not contain a readable binary")
- _copy_stream_atomically(source, target)
- return
- raise RuntimeError("Downloaded cloudflared archive did not contain cloudflared")
+def install_cloudflared() -> dict[str, Any]:
+ """Install the pinned cloudflared release through the managed-runtime core."""
+ from core.cloudflared_runtime import CloudflaredRuntimeManager
-def install_cloudflared() -> dict[str, Any]:
- try:
- paths.ensure_data_dirs()
- asset = _asset_name()
- url = f"{CLOUDFLARED_BASE_URL}/{asset}"
- target = _managed_cloudflared_path()
- with tempfile.TemporaryDirectory() as tmp:
- download_path = Path(tmp) / asset
- with requests.get(url, stream=True, timeout=60) as response:
- response.raise_for_status()
- with download_path.open("wb") as output:
- for chunk in response.iter_content(chunk_size=1024 * 1024):
- if chunk:
- output.write(chunk)
- if asset.endswith(".tgz"):
- with tarfile.open(download_path, "r:gz") as archive:
- _safe_extract_cloudflared(archive, target)
- else:
- with download_path.open("rb") as source:
- _copy_stream_atomically(source, target)
- _make_executable(target)
- return {"ok": True, "path": str(target), "version": _version(str(target)), "source_url": url}
- except Exception as exc:
- return {"ok": False, "error": "cloudflared_install_failed", "detail": str(exc)}
+ result = CloudflaredRuntimeManager().ensure()
+ if result.get("ok") and result.get("path"):
+ return {"ok": True, "path": str(result["path"]), "version": result.get("version")}
+ return {
+ "ok": False,
+ "error": "cloudflared_install_failed",
+ "detail": str(result.get("message") or result.get("reason") or ""),
+ }
-def _resolve_binary(config: V2Config | None = None) -> str | None:
+def _explicit_cloudflared(config: V2Config | None) -> str | None:
configured = ""
if config is not None:
configured = getattr(config.remote_access.vibe_cloud, "cloudflared_path", "") or ""
@@ -447,10 +379,65 @@ def _resolve_binary(config: V2Config | None = None) -> str | None:
expanded = Path(configured).expanduser()
if expanded.exists() and os.access(expanded, os.X_OK):
return str(expanded)
- managed = _managed_cloudflared_path()
- if managed.exists() and os.access(managed, os.X_OK):
+ return None
+
+
+def _resolve_binary(config: V2Config | None = None) -> str | None:
+ """An explicit ``cloudflared_path``, else a verified managed pin, else the tracked connector's binary.
+
+ The managed pin may be an earlier one until the packaged pin installs. The
+ tracked connector's recorded binary keeps a running tunnel manageable after
+ a failed download, until stop() or the exited-record cleanup clears the
+ record. Nothing searches PATH.
+ """
+
+ explicit = _explicit_cloudflared(config)
+ if explicit:
+ return explicit
+ from core.cloudflared_runtime import CloudflaredRuntimeManager
+
+ managed = CloudflaredRuntimeManager().resolve_binary()
+ if managed is not None:
return str(managed)
- return shutil.which("cloudflared")
+ recorded = (_read_state() or {}).get("binary_path")
+ if isinstance(recorded, str) and recorded and Path(recorded).is_file() and os.access(recorded, os.X_OK):
+ return recorded
+ return None
+
+
+def _retire_legacy_cloudflared(config: V2Config, binary: str) -> None:
+ """Remove the unpinned copy once the connector runs from another binary."""
+
+ legacy = _legacy_cloudflared_path()
+ configured = config.remote_access.vibe_cloud.cloudflared_path
+ # Compare file identities: ~/.vibe_remote may be a back-symlink to ~/.avibe.
+ if _same_file(Path(binary), legacy) or (configured and _same_file(Path(configured).expanduser(), legacy)):
+ return
+ try:
+ legacy.unlink(missing_ok=True)
+ except OSError:
+ logger.warning("Could not remove the unpinned cloudflared at %s", legacy, exc_info=True)
+
+
+def _cloudflared_pin_needed(config: V2Config | None) -> bool:
+ """Whether the packaged pin is missing and no explicit ``cloudflared_path`` replaces it.
+
+ ``resolve_binary()`` keeps returning an earlier verified pin, so only the
+ status says whether the packaged one is installed.
+ """
+
+ if _explicit_cloudflared(config):
+ return False
+ from core.cloudflared_runtime import CloudflaredRuntimeManager
+
+ return CloudflaredRuntimeManager().status().get("matches_manifest") is not True
+
+
+def _same_file(first: Path, second: Path) -> bool:
+ try:
+ return os.path.samefile(first, second)
+ except OSError:
+ return False
def _read_pid_file(path: Path) -> int | None:
@@ -3712,7 +3699,7 @@ def _restart_exited_connector(
return False
if now < schedule.due_at:
return False
- install_failure = _download_missing_cloudflared(config)
+ install_failure = _ensure_cloudflared_pin(config)
# Lock order is L, then _RECOVERY_LOCK, then _CONNECTOR_LOCK. The lane check
# above released both before L. Under L no stop or start in any process
# interleaves, so the request check, spawn, and publish below are one step.
@@ -4295,7 +4282,7 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
loaded = config or V2Config.load()
except Exception:
loaded = None
- install_failure = _download_missing_cloudflared(loaded)
+ install_failure = _ensure_cloudflared_pin(loaded)
try:
with _connector_lifecycle():
return _start(loaded or config, record_request=True, install_failure=install_failure)
@@ -4303,19 +4290,20 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
return {"ok": False, "error": "remote_access_busy", "started": False}
-def _download_missing_cloudflared(config: V2Config | None) -> dict[str, Any] | None:
- """Download a missing cloudflared before the lifecycle lock; return the failure, if any.
+def _ensure_cloudflared_pin(config: V2Config | None) -> dict[str, Any] | None:
+ """Install a missing packaged pin before the lifecycle lock; return the failure, if any.
The lock is held only around short check, spawn, and publish sections, so
- _start() never downloads.
+ _start() never downloads. After a failure _start() still uses whatever
+ _resolve_binary() finds, so a running tunnel keeps its binary.
"""
cloud = config.remote_access.vibe_cloud if config is not None else None
- if cloud is None or not cloud.enabled or not cloud.tunnel_token or _resolve_binary(config):
+ if cloud is None or not cloud.enabled or not cloud.tunnel_token or not _cloudflared_pin_needed(config):
return None
# The installer writes one fixed temporary path, so concurrent starts share one download.
with _CLOUDFLARED_DOWNLOAD_LOCK:
- if _resolve_binary(config):
+ if not _cloudflared_pin_needed(config):
return None
result = install_cloudflared()
return None if result.get("ok") else result
@@ -4379,6 +4367,7 @@ def _start(
running_sig = _running_signature(current.get("pid"))
desired_sig = _runtime_signature(config, binary)
if running_sig == desired_sig and _running_connector_has_metrics(current.get("pid")):
+ _retire_legacy_cloudflared(config, binary)
_report_runtime_status_async(config, event="start")
return {**current, "ok": True, "started": False}
stop_result = _stop_connector(config)
@@ -4459,6 +4448,7 @@ def _start(
_report_runtime_status_async(config, event="start_failed", last_error="cloudflared_exited")
return {**current, "ok": False, "error": "cloudflared_exited"}
result = {**current, "ok": True, "started": True, "pid": pid}
+ _retire_legacy_cloudflared(config, binary)
_report_runtime_status_async(config, event="start")
return result