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(model-hub): manage CPA as a required dependency (#1862)

Call Whited936f0d6bdad
diff --git a/.github/workflows/model-hub-engine-release-guard.yml b/.github/workflows/model-hub-engine-release-guard.yml
new file mode 100644
index 000000000..a2183e9ae
--- /dev/null
+++ b/.github/workflows/model-hub-engine-release-guard.yml
@@ -0,0 +1,146 @@
+name: Guard Model Hub engine release
+
+on:
+ push:
+ branches: [master]
+ paths:
+ - "vibe/model_hub_runtime/cliproxyapi_manifest.json"
+ - "scripts/model_hub_engine_release_guard.py"
+ - ".github/workflows/model-hub-engine-release-guard.yml"
+ schedule:
+ - cron: "23 */6 * * *"
+ - cron: "53 4 * * 0"
+ workflow_dispatch:
+
+permissions:
+ actions: read
+ contents: write
+
+concurrency:
+ group: model-hub-engine-release-guard
+ cancel-in-progress: false
+
+jobs:
+ guard:
+ name: Verify and recover pinned assets
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+
+ - name: Resolve pinned manifest identity
+ id: manifest
+ shell: bash
+ run: |
+ echo "sha256=$(sha256sum vibe/model_hub_runtime/cliproxyapi_manifest.json | cut -d' ' -f1)" \
+ >> "$GITHUB_OUTPUT"
+
+ - name: Fetch and verify published assets
+ id: probe
+ continue-on-error: true
+ run: |
+ python3 scripts/model_hub_engine_release_guard.py fetch \
+ --output-dir "$RUNNER_TEMP/model-hub-engine-release"
+
+ - name: Restore the latest verified backup
+ id: backup
+ if: steps.probe.outcome == 'failure'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ MANIFEST_SHA: ${{ steps.manifest.outputs.sha256 }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ artifact_name="model-hub-engine-release-backup-$MANIFEST_SHA"
+ mapfile -t artifact_ids < <(
+ gh api --method GET \
+ "repos/$GITHUB_REPOSITORY/actions/artifacts" \
+ -f name="$artifact_name" \
+ -f per_page=100 \
+ --jq '.artifacts | sort_by(.created_at) | reverse | .[] | select(.expired == false) | .id'
+ )
+
+ for artifact_id in "${artifact_ids[@]}"; do
+ candidate="$RUNNER_TEMP/model-hub-engine-backup-$artifact_id"
+ archive="$RUNNER_TEMP/model-hub-engine-backup-$artifact_id.zip"
+ rm -rf "$candidate"
+ mkdir -p "$candidate"
+ if gh api \
+ "repos/$GITHUB_REPOSITORY/actions/artifacts/$artifact_id/zip" \
+ > "$archive" && unzip -q "$archive" -d "$candidate" && \
+ python3 scripts/model_hub_engine_release_guard.py verify \
+ --asset-dir "$candidate"; then
+ echo "asset_dir=$candidate" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ done
+
+ echo "::error::No verified backup is available for manifest $MANIFEST_SHA."
+ exit 1
+
+ - name: Recover missing release assets
+ if: steps.probe.outcome == 'failure'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RESTORE_DIR: ${{ steps.backup.outputs.asset_dir }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ manifest="vibe/model_hub_runtime/cliproxyapi_manifest.json"
+ release_tag="$(jq -er '.asset_release_tag' "$manifest")"
+ version="$(jq -er '.version' "$manifest")"
+ assets=("$RESTORE_DIR"/*)
+
+ if gh release view "$release_tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
+ declare -A existing_assets=()
+ while IFS= read -r asset_name; do
+ existing_assets["$asset_name"]=1
+ done < <(
+ gh release view "$release_tag" \
+ --repo "$GITHUB_REPOSITORY" \
+ --json assets \
+ --jq '.assets[].name'
+ )
+
+ missing_assets=()
+ for asset in "${assets[@]}"; do
+ asset_name="${asset##*/}"
+ if [ -z "${existing_assets[$asset_name]:-}" ]; then
+ missing_assets+=("$asset")
+ fi
+ done
+ if [ "${#missing_assets[@]}" -eq 0 ]; then
+ echo "::error::Every expected asset name exists but verification failed; refusing to overwrite pinned bytes."
+ exit 1
+ fi
+ gh release upload "$release_tag" \
+ --repo "$GITHUB_REPOSITORY" \
+ "${missing_assets[@]}"
+ else
+ gh release create "$release_tag" \
+ --repo "$GITHUB_REPOSITORY" \
+ --verify-tag \
+ --latest=false \
+ --title "Avibe Model Hub engine $version" \
+ --notes "Avibe-managed CPA assets recovered from a manifest-verified backup." \
+ "${assets[@]}"
+ fi
+
+ - name: Verify recovered release
+ if: steps.probe.outcome == 'failure'
+ run: |
+ python3 scripts/model_hub_engine_release_guard.py fetch \
+ --output-dir "$RUNNER_TEMP/model-hub-engine-release"
+
+ - name: Preserve verified release backup
+ if: >-
+ github.event_name != 'schedule' ||
+ github.event.schedule == '53 4 * * 0' ||
+ steps.probe.outcome == 'failure'
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: model-hub-engine-release-backup-${{ steps.manifest.outputs.sha256 }}
+ path: ${{ runner.temp }}/model-hub-engine-release
+ if-no-files-found: error
+ retention-days: 90
+ compression-level: 0
diff --git a/core/controller.py b/core/controller.py
index f0cf04ebd..6f7eb9085 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -550,13 +550,15 @@ class Controller:
pending.clear()
def _init_model_hub(self) -> None:
- """Create the Model Hub aggregate only for an explicit release opt-in."""
+ """Own the CPA dependency and opt in to the full Model Hub aggregate."""
from config.v2_config import V2Config, is_model_hub_enabled
+ from vibe.model_hub_runtime import get_model_hub_engine_adapter
self.model_hub_service = None
self.model_hub_turn_gateway = None
self.model_hub_runtime = None
+ self.model_hub_engine_adapter = get_model_hub_engine_adapter()
self._model_hub_snapshot_refresh_pending = threading.Event()
self._model_hub_snapshot_reconcile_task = None
self._model_hub_snapshot_reconcile_loop_task = None
@@ -674,6 +676,7 @@ class Controller:
await coordinator.request_restart(backend)
self.model_hub_service = create_default_service(
+ adapter=self.model_hub_engine_adapter,
requested_model_override=default_vibe_agent_model,
selected_agent_override=default_vibe_agent_name,
named_agents_override=named_vibe_agents,
diff --git a/core/handlers/model_hub/__init__.py b/core/handlers/model_hub/__init__.py
index 1c5b4e68d..c15748656 100644
--- a/core/handlers/model_hub/__init__.py
+++ b/core/handlers/model_hub/__init__.py
@@ -5,7 +5,9 @@ from .service import (
ModelHubError,
ModelHubService,
create_default_service,
+ ensure_runtime_dependency,
load_opencode_public_models,
+ runtime_dependency_payload,
)
__all__ = [
@@ -13,5 +15,7 @@ __all__ = [
"ModelHubError",
"ModelHubService",
"create_default_service",
+ "ensure_runtime_dependency",
"load_opencode_public_models",
+ "runtime_dependency_payload",
]
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 37d2e14f2..b419333a9 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -50,6 +50,12 @@ class EngineStatus:
error_key: str | None = None
+@dataclass(frozen=True)
+class EngineEnsureResult:
+ status: EngineStatus
+ changed: bool
+
+
class RuntimePlatformUnsupportedError(RuntimeError):
"""The pinned managed runtime has no asset for the server host."""
@@ -384,7 +390,12 @@ class EngineAdapter(Protocol):
async def recover_installation(self) -> EngineStatus: ...
- async def ensure_installed(self) -> EngineStatus: ...
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult: ...
async def start(self) -> EngineStatus: ...
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 9a5f3d22f..771ed13c1 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -220,6 +220,11 @@ async def dispatch_model_hub_rpc(
return await service.runtime_status()
if operation == "runtime_install":
return await service.runtime_install()
+ if operation == "runtime_ensure_dependency":
+ return await service.runtime_ensure_dependency(
+ force=payload.get("force") is True,
+ offline=payload.get("offline") is True,
+ )
if operation == "runtime_start":
return await service.runtime_start()
if operation == "runtime_stop":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 1c0682e42..1590e56e3 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -49,6 +49,7 @@ from vibe.model_hub_runtime.api_key_vendors import (
from .adapter import (
DiscoveredModel,
EngineAdapter,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
InvokeHandle,
@@ -296,8 +297,13 @@ class UnavailableEngineAdapter:
async def recover_installation(self) -> EngineStatus:
return await self.status()
- async def ensure_installed(self) -> EngineStatus:
- return await self.status()
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult:
+ return EngineEnsureResult(status=await self.status(), changed=False)
async def start(self) -> EngineStatus:
raise EngineUnavailableError
@@ -725,6 +731,54 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
}
+async def ensure_runtime_dependency(
+ adapter: EngineAdapter,
+ *,
+ force: bool = False,
+ offline: bool = False,
+) -> EngineEnsureResult:
+ """Converge the pinned engine through a controller-owned adapter."""
+
+ ensure = getattr(adapter, "ensure_installed", None)
+ if not callable(ensure):
+ raise ModelHubError("engine_down", status=503)
+ try:
+ return await ensure(force=force, offline=offline)
+ except RuntimePlatformUnsupportedError:
+ raise ModelHubError("runtime_platform_unsupported", status=422) from None
+ except EngineUnavailableError as exc:
+ reason = getattr(exc, "reason", None)
+ raise ModelHubError(
+ "engine_down",
+ status=503,
+ data={"reason": reason} if isinstance(reason, str) and reason else None,
+ ) from None
+ except ModelHubError:
+ raise
+ except Exception as exc:
+ reason = getattr(exc, "reason", None)
+ safe_reason = (
+ reason
+ if isinstance(reason, str) and reason.startswith("model_hub_engine_")
+ else None
+ )
+ raise ModelHubError(
+ "engine_down",
+ status=503,
+ data={"reason": safe_reason} if safe_reason else None,
+ ) from None
+
+
+def runtime_dependency_payload(
+ result: EngineEnsureResult,
+ *,
+ enabled: bool,
+) -> dict:
+ payload = _runtime_payload(result.status, enabled=enabled)
+ payload["changed"] = result.changed
+ return payload
+
+
class ModelHubService:
def __init__(
self,
@@ -1114,6 +1168,7 @@ class ModelHubService:
async def _prepare_engine_for_demand(self, *, already_synced: bool = False) -> None:
try:
+ await self._ensure_runtime_dependency()
if already_synced:
self._engine_preparation_failed = False
return
@@ -1154,6 +1209,18 @@ class ModelHubService:
await self._prepare_engine_for_demand()
await self._engine_call(self.adapter.start())
+ async def _ensure_runtime_dependency(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult:
+ return await ensure_runtime_dependency(
+ self.adapter,
+ force=force,
+ offline=offline,
+ )
+
async def stop(self) -> None:
async with self._runtime_lifecycle_lock:
await self.adapter.stop()
@@ -5798,6 +5865,25 @@ class ModelHubService:
enabled=enabled,
)
+ async def runtime_ensure_dependency(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> dict:
+ """Converge the pinned engine without changing persisted run intent."""
+
+ async with self._runtime_lifecycle_lock:
+ await self.reconcile_runtime_installation()
+ result = await self._ensure_runtime_dependency(
+ force=force,
+ offline=offline,
+ )
+ return runtime_dependency_payload(
+ result,
+ enabled=self.store.load().enabled,
+ )
+
async def runtime_start(self) -> dict:
async with self._runtime_lifecycle_lock:
await self.reconcile_runtime_installation()
diff --git a/core/internal_server.py b/core/internal_server.py
index 18c8c4dd7..7362226ec 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1940,24 +1940,38 @@ def create_app(
"""Dispatch UI operations to the controller-owned Model Hub aggregate."""
from config.v2_config import is_model_hub_enabled
- from core.handlers.model_hub import ModelHubError
+ from core.handlers.model_hub import (
+ ModelHubError,
+ ensure_runtime_dependency,
+ runtime_dependency_payload,
+ )
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
- if not is_model_hub_enabled():
+ body = await _safe_json(request)
+ operation = body.get("operation") if isinstance(body, dict) else None
+ payload = body.get("payload") if isinstance(body, dict) else None
+ dependency_operation = operation == "runtime_ensure_dependency"
+ if not is_model_hub_enabled() and not dependency_operation:
return JSONResponse(
status_code=404,
content={"ok": False, "contract_version": 1, "error": "feature_disabled"},
)
- body = await _safe_json(request)
- operation = body.get("operation") if isinstance(body, dict) else None
- payload = body.get("payload") if isinstance(body, dict) else None
if not isinstance(operation, str) or not isinstance(payload, dict):
return JSONResponse(status_code=400, content={"ok": False, "error": "discovery_failed"})
service = getattr(controller, "model_hub_service", None)
- if service is None:
+ adapter = getattr(controller, "model_hub_engine_adapter", None)
+ if service is None and (not dependency_operation or adapter is None):
return JSONResponse(status_code=503, content={"ok": False, "error": "engine_down"})
try:
- result = await dispatch_model_hub_rpc(service, operation, payload)
+ if service is not None:
+ result = await dispatch_model_hub_rpc(service, operation, payload)
+ else:
+ ensured = await ensure_runtime_dependency(
+ adapter,
+ force=payload.get("force") is True,
+ offline=payload.get("offline") is True,
+ )
+ result = runtime_dependency_payload(ensured, enabled=False)
except ModelHubError as exc:
response = {"ok": False, "error": exc.code}
if exc.detail:
diff --git a/docs/CLI.md b/docs/CLI.md
index e1a4e3827..8e7303bea 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -213,6 +213,7 @@ vibe doctor repair stale-restart-state --yes
vibe doctor repair askill --yes
vibe doctor repair avault --yes
vibe doctor repair git-runtime --yes
+vibe doctor repair model-hub-engine --yes
vibe doctor repair show-runtime --yes
vibe doctor repair tmux --yes
```
@@ -223,7 +224,7 @@ vibe doctor repair tmux --yes
- Agent CLI availability (Claude Code, OpenCode, Codex)
- Runtime home migration state
- Runtime process, install, and restart metadata state
-- askill, avault, Git Runtime, Show Runtime, tmux, and Node.js readiness through one dependency diagnostic group
+- askill, avault, Git Runtime, Model Hub engine (CPA), Show Runtime, tmux, and Node.js readiness through one dependency diagnostic group
- `vibe doctor --deep` also probes missing dependencies without downloading their bodies
- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index e3eb702dd..557d80de4 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -174,6 +174,7 @@ vibe doctor repair stale-restart-state --yes
vibe doctor repair askill --yes
vibe doctor repair avault --yes
vibe doctor repair git-runtime --yes
+vibe doctor repair model-hub-engine --yes
vibe doctor repair show-runtime --yes
vibe doctor repair tmux --yes
```
@@ -184,7 +185,7 @@ vibe doctor repair tmux --yes
- Agent CLI 可用性(Claude Code、OpenCode、Codex)
- runtime home 迁移状态
- runtime 进程、安装来源和重启元数据状态
-- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Show Runtime、tmux 和 Node.js
+- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Model Hub 引擎(CPA)、Show Runtime、tmux 和 Node.js
- `vibe doctor --deep` 还会在不下载正文的情况下探测缺失依赖的精确地址
- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index e3cdf65a1..1bcaff62c 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -614,7 +614,7 @@ vibe doctor
- checks backend CLI availability
- checks runtime home migration state
- checks runtime process, install, and restart metadata state
-- checks askill, avault, Git Runtime, Show Runtime, tmux, and Node.js through one dependency diagnostic group
+- checks askill, avault, Git Runtime, Model Hub engine (CPA), Show Runtime, tmux, and Node.js through one dependency diagnostic group
- `vibe doctor --deep` probes missing dependency endpoints without downloading their bodies
- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff
@@ -629,6 +629,7 @@ vibe doctor repair stale-restart-state --yes
vibe doctor repair askill --yes
vibe doctor repair avault --yes
vibe doctor repair git-runtime --yes
+vibe doctor repair model-hub-engine --yes
vibe doctor repair show-runtime --yes
vibe doctor repair tmux --yes
```
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 3f0d27c35..83332a000 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -592,7 +592,7 @@ vibe doctor
- 检查 backend CLI 是否可用
- 检查 runtime home 迁移状态
- 检查 runtime 进程、安装来源和重启元数据状态
-- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Show Runtime、tmux 和 Node.js
+- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Model Hub 引擎(CPA)、Show Runtime、tmux 和 Node.js
- `vibe doctor --deep` 会在不下载正文的情况下探测缺失依赖的地址
- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试
@@ -607,6 +607,7 @@ vibe doctor repair stale-restart-state --yes
vibe doctor repair askill --yes
vibe doctor repair avault --yes
vibe doctor repair git-runtime --yes
+vibe doctor repair model-hub-engine --yes
vibe doctor repair show-runtime --yes
vibe doctor repair tmux --yes
```
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 37d2e14f2..b419333a9 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -50,6 +50,12 @@ class EngineStatus:
error_key: str | None = None
+@dataclass(frozen=True)
+class EngineEnsureResult:
+ status: EngineStatus
+ changed: bool
+
+
class RuntimePlatformUnsupportedError(RuntimeError):
"""The pinned managed runtime has no asset for the server host."""
@@ -384,7 +390,12 @@ class EngineAdapter(Protocol):
async def recover_installation(self) -> EngineStatus: ...
- async def ensure_installed(self) -> EngineStatus: ...
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult: ...
async def start(self) -> EngineStatus: ...
diff --git a/docs/plans/model-hub-cpa-dependency.md b/docs/plans/model-hub-cpa-dependency.md
new file mode 100644
index 000000000..49b4ec87c
--- /dev/null
+++ b/docs/plans/model-hub-cpa-dependency.md
@@ -0,0 +1,80 @@
+# Model Hub CPA Dependency Lifecycle
+
+## Context
+
+Model Hub runs through a managed CLIProxyAPI (CPA) binary. Avibe already pins
+that binary in a packaged, checksummed manifest, but installation was previously
+entered only through Model Hub's feature-specific runtime flow. As a result, an
+Avibe upgrade could leave an older CPA selected on disk, and Settings did not
+show the dependency or its target version.
+
+## Decision
+
+CPA is a required Avibe dependency, independent of whether Model Hub is enabled
+or has ever been used. Each Avibe release owns one reviewed CPA target. User
+machines converge to that target; they never resolve an upstream `latest` tag at
+runtime.
+
+Installation and execution remain separate lifecycle decisions:
+
+- `vibe runtime prepare` and the background startup dependency reconcile install
+ or upgrade CPA to the manifest packaged with the current Avibe release.
+- The Dependencies settings page reports both the installed version and the
+ packaged target and offers install, update, or repair when convergence is
+ possible.
+- Installing or upgrading CPA does not enable Model Hub or start a stopped CPA
+ process. When the controller already owns a running process, replacement goes
+ through that owner so the process restarts on the verified target. A UI-side
+ reconcile probes the starting controller's health endpoint rather than
+ treating a Unix-socket pathname, including a stale one, as readiness. The
+ install-job poll budget outlasts the complete controller-readiness and CPA RPC
+ bounds.
+- Every Model Hub demand path verifies the packaged target before starting CPA,
+ so a stale pointer cannot be started after a failed or skipped background
+ reconcile.
+- CPA remains visible on hosts for which Avibe publishes no compatible asset,
+ but that `unsupported` capability state is derived from Avibe's fixed host
+ matrix and the selected manifest's asset set, not mutable install or pointer
+ state. It is nonfatal and offers no repair that cannot succeed.
+
+## Failure Policy
+
+CPA installation is atomic. A failed download, verification, or candidate
+preparation leaves the prior verified install and current pointer intact. It is
+reported in Dependencies and Doctor and can be retried manually or by the next
+startup reconcile. Every CPA failure token exposed by Dependencies has English
+and Chinese copy enforced by a backend-to-locale contract test. CPA failure does
+not roll back or fail an otherwise successful Avibe upgrade.
+
+A synchronous dependency ensure settles only the exact durable install state it
+observed on entry. Success clears an unchanged prior failure or orphaned install
+claim, while a claim replaced by a newer owner remains untouched.
+
+Successful replacement retains one prior managed install for rollback and
+cleans older generations through the existing managed-runtime cleanup policy.
+
+## Release Maintenance
+
+Updating CPA for an Avibe release requires changing the packaged manifest in the
+same change as its frozen contract test. The release tag and source commit are
+fixed, and every supported archive records its published byte size, archive
+SHA-256, and extracted binary SHA-256. The verified upstream bytes are published
+under an Avibe-owned release tag before the manifest is pinned. A scheduled
+guard verifies that release and preserves a manifest-keyed backup that can
+restore missing assets without overwriting a mismatched asset. For this change,
+the reviewed target is CLIProxyAPI `v7.2.149` at source commit
+`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`.
+
+## Acceptance Criteria
+
+- A user who never enables Model Hub receives the CPA target during normal Avibe
+ install, upgrade, or startup reconciliation.
+- A user upgrading Avibe from an older CPA pin converges to the new pin without
+ following future upstream releases.
+- A stopped Model Hub remains stopped after dependency convergence; a running
+ one restarts only after the replacement is verified and activated.
+- Dependencies and Doctor expose missing, stale, unsupported, and failed states
+ without claiming an unknown target is current; unsupported hosts receive a
+ warning rather than a failing required-dependency verdict.
+- A failed CPA update preserves the previous runnable version and does not block
+ the Avibe upgrade.
diff --git a/scripts/model_hub_engine_release_guard.py b/scripts/model_hub_engine_release_guard.py
new file mode 100755
index 000000000..62a0bcfab
--- /dev/null
+++ b/scripts/model_hub_engine_release_guard.py
@@ -0,0 +1,368 @@
+#!/usr/bin/env python3
+"""Verify and materialize the manifest-pinned Model Hub engine release."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import shutil
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.error
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_MANIFEST = REPO_ROOT / "vibe" / "model_hub_runtime" / "cliproxyapi_manifest.json"
+OWNED_RELEASE_ROOT = "https://github.com/avibe-bot/avibe/releases/download"
+UPSTREAM_RELEASE_ROOT = "https://github.com/router-for-me/CLIProxyAPI/releases/download"
+EXPECTED_PLATFORMS = frozenset(
+ {"darwin-arm64", "darwin-x64", "linux-amd64", "linux-arm64"}
+)
+UPSTREAM_PLATFORM_NAMES = {
+ "darwin-arm64": "darwin_aarch64",
+ "darwin-x64": "darwin_amd64",
+ "linux-amd64": "linux_amd64",
+ "linux-arm64": "linux_aarch64",
+}
+ASSET_TAG_RE = re.compile(
+ r"model-hub-engine-v[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*"
+)
+VERSION_RE = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+")
+SHA256_RE = re.compile(r"[0-9a-f]{64}")
+SOURCE_SHA_RE = re.compile(r"[0-9a-f]{40}")
+MAX_ARCHIVE_BYTES = 256 * 1024 * 1024
+
+
+class ReleaseGuardError(RuntimeError):
+ """Raised when a pinned CPA release cannot be trusted or materialized."""
+
+
+@dataclass(frozen=True)
+class ArchiveSpec:
+ platform: str
+ name: str
+ owned_url: str
+ upstream_url: str
+ size: int
+ sha256: str
+ binary_sha256: str
+ bin_path: str
+
+
+@dataclass(frozen=True)
+class ReleaseSpec:
+ manifest_bytes: bytes
+ version: str
+ upstream_release_tag: str
+ asset_release_tag: str
+ owned_release_url: str
+ archives: tuple[ArchiveSpec, ...]
+
+ @property
+ def expected_asset_names(self) -> set[str]:
+ names = {"model-hub-engine-manifest.json"}
+ for archive in self.archives:
+ names.add(archive.name)
+ names.add(f"{archive.name}.sha256")
+ return names
+
+
+def _required_string(payload: dict, key: str, context: str) -> str:
+ value = payload.get(key)
+ if not isinstance(value, str) or not value:
+ raise ReleaseGuardError(f"{context}.{key} must be a non-empty string")
+ return value
+
+
+def load_release_spec(manifest_path: Path) -> ReleaseSpec:
+ try:
+ manifest_bytes = manifest_path.read_bytes()
+ payload = json.loads(manifest_bytes)
+ except (OSError, json.JSONDecodeError) as exc:
+ raise ReleaseGuardError(f"cannot read Model Hub engine manifest: {exc}") from exc
+
+ if (
+ not isinstance(payload, dict)
+ or type(payload.get("schema_version")) is not int
+ or payload["schema_version"] != 1
+ ):
+ raise ReleaseGuardError("Model Hub engine manifest schema_version must be 1")
+ if payload.get("name") != "cliproxyapi":
+ raise ReleaseGuardError("Model Hub engine manifest name must be cliproxyapi")
+ if payload.get("source") != "router-for-me/CLIProxyAPI":
+ raise ReleaseGuardError("Model Hub engine manifest source is invalid")
+ if payload.get("license") != "MIT":
+ raise ReleaseGuardError("Model Hub engine manifest license is invalid")
+
+ version = _required_string(payload, "version", "manifest")
+ upstream_release_tag = _required_string(payload, "release_tag", "manifest")
+ asset_release_tag = _required_string(payload, "asset_release_tag", "manifest")
+ source_sha = _required_string(payload, "source_sha", "manifest")
+ source_url = _required_string(payload, "source_url", "manifest")
+ if VERSION_RE.fullmatch(version) is None or upstream_release_tag != version:
+ raise ReleaseGuardError("Model Hub engine version and upstream release tag are invalid")
+ if ASSET_TAG_RE.fullmatch(asset_release_tag) is None:
+ raise ReleaseGuardError("Model Hub engine asset release tag is invalid")
+ if not asset_release_tag.startswith(f"model-hub-engine-{version}-"):
+ raise ReleaseGuardError("Model Hub engine asset release tag does not match version")
+ if SOURCE_SHA_RE.fullmatch(source_sha) is None:
+ raise ReleaseGuardError("Model Hub engine source SHA is invalid")
+ if source_url != f"https://github.com/router-for-me/CLIProxyAPI/tree/{source_sha}":
+ raise ReleaseGuardError("Model Hub engine source URL is invalid")
+
+ owned_release_url = f"{OWNED_RELEASE_ROOT}/{asset_release_tag}"
+ upstream_release_url = f"{UPSTREAM_RELEASE_ROOT}/{upstream_release_tag}"
+ raw_assets = payload.get("assets")
+ if not isinstance(raw_assets, list):
+ raise ReleaseGuardError("Model Hub engine manifest assets must be a list")
+
+ archives: list[ArchiveSpec] = []
+ seen_platforms: set[str] = set()
+ seen_names: set[str] = set()
+ for index, raw in enumerate(raw_assets):
+ context = f"assets[{index}]"
+ if not isinstance(raw, dict):
+ raise ReleaseGuardError(f"{context} must be an object")
+ platform = _required_string(raw, "platform", context)
+ owned_url = _required_string(raw, "url", context)
+ sha256 = _required_string(raw, "sha256", context)
+ binary_sha256 = _required_string(raw, "binary_sha256", context)
+ bin_path = _required_string(raw, "bin_path", context)
+ size = raw.get("size_bytes")
+ name = owned_url.rsplit("/", 1)[-1]
+ expected_name = (
+ f"CLIProxyAPI_{version.removeprefix('v')}_"
+ f"{UPSTREAM_PLATFORM_NAMES.get(platform, '')}.tar.gz"
+ )
+ if platform in seen_platforms or platform not in EXPECTED_PLATFORMS:
+ raise ReleaseGuardError(f"{context}.platform is invalid or duplicated")
+ if Path(name).name != name or name in seen_names or name != expected_name:
+ raise ReleaseGuardError(f"{context}.url has an invalid asset name")
+ if owned_url != f"{owned_release_url}/{name}":
+ raise ReleaseGuardError(f"{context}.url is outside the Avibe-owned release")
+ if SHA256_RE.fullmatch(sha256) is None or SHA256_RE.fullmatch(binary_sha256) is None:
+ raise ReleaseGuardError(f"{context} has an invalid digest")
+ if not isinstance(size, int) or isinstance(size, bool) or not 0 < size <= MAX_ARCHIVE_BYTES:
+ raise ReleaseGuardError(f"{context}.size_bytes is invalid")
+ if bin_path != "cli-proxy-api":
+ raise ReleaseGuardError(f"{context}.bin_path is invalid")
+ seen_platforms.add(platform)
+ seen_names.add(name)
+ archives.append(
+ ArchiveSpec(
+ platform=platform,
+ name=name,
+ owned_url=owned_url,
+ upstream_url=f"{upstream_release_url}/{name}",
+ size=size,
+ sha256=sha256,
+ binary_sha256=binary_sha256,
+ bin_path=bin_path,
+ )
+ )
+ if seen_platforms != EXPECTED_PLATFORMS:
+ raise ReleaseGuardError("Model Hub engine manifest platform set is invalid")
+
+ return ReleaseSpec(
+ manifest_bytes=manifest_bytes,
+ version=version,
+ upstream_release_tag=upstream_release_tag,
+ asset_release_tag=asset_release_tag,
+ owned_release_url=owned_release_url,
+ archives=tuple(sorted(archives, key=lambda archive: archive.platform)),
+ )
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _verify_archive(path: Path, archive: ArchiveSpec) -> None:
+ if not path.is_file() or path.stat().st_size != archive.size:
+ raise ReleaseGuardError(f"Model Hub engine archive size mismatch: {archive.name}")
+ if _sha256(path) != archive.sha256:
+ raise ReleaseGuardError(f"Model Hub engine archive checksum mismatch: {archive.name}")
+ try:
+ with tarfile.open(path, "r:gz") as bundle:
+ member = bundle.getmember(archive.bin_path)
+ stream = bundle.extractfile(member)
+ binary_sha256 = (
+ hashlib.sha256(stream.read()).hexdigest()
+ if stream is not None and member.isfile()
+ else ""
+ )
+ except (KeyError, OSError, tarfile.TarError) as exc:
+ raise ReleaseGuardError(f"invalid Model Hub engine archive: {archive.name}") from exc
+ if binary_sha256 != archive.binary_sha256:
+ raise ReleaseGuardError(f"Model Hub engine binary checksum mismatch: {archive.name}")
+
+
+def _verify_sidecar(path: Path, archive: ArchiveSpec) -> None:
+ if not path.is_file():
+ raise ReleaseGuardError(f"missing Model Hub engine checksum: {path.name}")
+ try:
+ fields = path.read_text(encoding="utf-8").strip().split()
+ except OSError as exc:
+ raise ReleaseGuardError(f"cannot read Model Hub engine checksum: {path.name}") from exc
+ if fields != [archive.sha256, archive.name]:
+ raise ReleaseGuardError(f"Model Hub engine checksum sidecar mismatch: {path.name}")
+
+
+def verify_release_assets(manifest_path: Path, asset_dir: Path) -> ReleaseSpec:
+ spec = load_release_spec(manifest_path)
+ if not asset_dir.is_dir():
+ raise ReleaseGuardError("Model Hub engine asset directory is missing")
+ entries = list(asset_dir.iterdir())
+ if any(path.is_symlink() or not path.is_file() for path in entries):
+ raise ReleaseGuardError("Model Hub engine asset directory contains unsafe entries")
+ actual_names = {path.name for path in entries}
+ if actual_names != spec.expected_asset_names:
+ raise ReleaseGuardError(
+ "Model Hub engine asset set mismatch: "
+ f"missing={sorted(spec.expected_asset_names - actual_names)}, "
+ f"unexpected={sorted(actual_names - spec.expected_asset_names)}"
+ )
+ if (asset_dir / "model-hub-engine-manifest.json").read_bytes() != spec.manifest_bytes:
+ raise ReleaseGuardError("published Model Hub engine manifest differs from the packaged manifest")
+ for archive in spec.archives:
+ _verify_archive(asset_dir / archive.name, archive)
+ _verify_sidecar(asset_dir / f"{archive.name}.sha256", archive)
+ return spec
+
+
+def _download(url: str, destination: Path, *, max_bytes: int, attempts: int = 3) -> None:
+ request = urllib.request.Request(
+ url,
+ headers={"User-Agent": "avibe-model-hub-engine-release-guard/1"},
+ )
+ for attempt in range(1, attempts + 1):
+ try:
+ with urllib.request.urlopen(request, timeout=60) as response, destination.open("wb") as output:
+ downloaded = 0
+ while chunk := response.read(1024 * 1024):
+ downloaded += len(chunk)
+ if downloaded > max_bytes:
+ raise ReleaseGuardError(f"release asset exceeds its size limit: {url}")
+ output.write(chunk)
+ return
+ except ReleaseGuardError:
+ destination.unlink(missing_ok=True)
+ raise
+ except urllib.error.HTTPError as exc:
+ destination.unlink(missing_ok=True)
+ retryable = exc.code == 429 or 500 <= exc.code < 600
+ if not retryable or attempt == attempts:
+ raise ReleaseGuardError(f"release asset download failed ({exc.code}): {url}") from exc
+ except (OSError, urllib.error.URLError) as exc:
+ destination.unlink(missing_ok=True)
+ if attempt == attempts:
+ raise ReleaseGuardError(f"release asset download failed: {url}: {exc}") from exc
+ time.sleep(float(attempt))
+
+
+def _materialize(
+ manifest_path: Path,
+ output_dir: Path,
+ *,
+ from_upstream: bool,
+) -> ReleaseSpec:
+ spec = load_release_spec(manifest_path)
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(prefix=f".{output_dir.name}-", dir=output_dir.parent))
+ try:
+ (staging / "model-hub-engine-manifest.json").write_bytes(spec.manifest_bytes)
+ for archive in spec.archives:
+ url = archive.upstream_url if from_upstream else archive.owned_url
+ _download(url, staging / archive.name, max_bytes=archive.size)
+ if (staging / archive.name).stat().st_size != archive.size:
+ raise ReleaseGuardError(f"Model Hub engine archive size mismatch: {archive.name}")
+ if from_upstream:
+ (staging / f"{archive.name}.sha256").write_text(
+ f"{archive.sha256} {archive.name}\n",
+ encoding="utf-8",
+ )
+ else:
+ _download(
+ f"{archive.owned_url}.sha256",
+ staging / f"{archive.name}.sha256",
+ max_bytes=256,
+ )
+ if not from_upstream:
+ _download(
+ f"{spec.owned_release_url}/model-hub-engine-manifest.json",
+ staging / "model-hub-engine-manifest.json",
+ max_bytes=max(len(spec.manifest_bytes), 1),
+ )
+ verify_release_assets(manifest_path, staging)
+ if output_dir.exists():
+ if not output_dir.is_dir() or output_dir.is_symlink():
+ raise ReleaseGuardError("Model Hub engine output path is not a safe directory")
+ shutil.rmtree(output_dir)
+ staging.replace(output_dir)
+ finally:
+ if staging.exists():
+ shutil.rmtree(staging)
+ return spec
+
+
+def fetch_release_assets(manifest_path: Path, output_dir: Path) -> ReleaseSpec:
+ return _materialize(manifest_path, output_dir, from_upstream=False)
+
+
+def fetch_upstream_assets(manifest_path: Path, output_dir: Path) -> ReleaseSpec:
+ return _materialize(manifest_path, output_dir, from_upstream=True)
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+ fetch = subparsers.add_parser("fetch", help="Fetch and verify Avibe-owned release assets.")
+ fetch.add_argument("--output-dir", type=Path, required=True)
+ fetch_source = subparsers.add_parser(
+ "fetch-source",
+ help="Fetch verified upstream bytes for initial Avibe release publication.",
+ )
+ fetch_source.add_argument("--output-dir", type=Path, required=True)
+ verify = subparsers.add_parser("verify", help="Verify a materialized release directory.")
+ verify.add_argument("--asset-dir", type=Path, required=True)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _build_parser().parse_args(argv)
+ try:
+ if args.command == "fetch":
+ spec = fetch_release_assets(args.manifest, args.output_dir)
+ elif args.command == "fetch-source":
+ spec = fetch_upstream_assets(args.manifest, args.output_dir)
+ else:
+ spec = verify_release_assets(args.manifest, args.asset_dir)
+ except ReleaseGuardError as exc:
+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)
+ return 1
+ print(
+ json.dumps(
+ {
+ "ok": True,
+ "version": spec.version,
+ "asset_release_tag": spec.asset_release_tag,
+ "asset_count": len(spec.expected_asset_names),
+ }
+ )
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index 3292fd55e..da0de2bf0 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -26,6 +26,7 @@ from config.v2_config import (
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -131,8 +132,13 @@ class ModelHubScenarioAdapter:
self.invocations: list[tuple[str, str, str]] = []
self.requests: list[Mapping[str, object]] = []
- async def ensure_installed(self) -> EngineStatus:
- return await self.status()
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult:
+ return EngineEnsureResult(status=await self.status(), changed=force)
async def start(self) -> EngineStatus:
return await self.status()
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 4b658ba31..ec8ddf7a3 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -145,6 +145,7 @@ capabilities:
- tests/test_model_hub_runtime.py
- tests/test_model_hub_l3.py
- tests/test_model_hub_usage.py
+ - tests/test_local_deps.py
- tests/test_opencode_server.py
- tests/test_runtime_activation.py
- ui/src/components/settings/models/UsageTab.test.tsx
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index dce818871..04af7cdeb 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -10,6 +10,7 @@ capability:
- tests/test_model_hub_runtime.py
- tests/test_model_hub_l3.py
- tests/test_model_hub_usage.py
+ - tests/test_local_deps.py
- tests/test_opencode_server.py
- tests/test_runtime_activation.py
# The user-visible half of metering. A vitest case is the only place these
@@ -221,6 +222,12 @@ scenarios:
kind: concurrency
layer: unit
test: tests/test_runtime_activation.py::test_mh_runtime_007_opencode_overlay_restart_retires_pre_native_start_owner
+ - id: MH-RUNTIME-008
+ name: Avibe startup converges CPA to its packaged pin without enabling or starting Model Hub
+ status: covered
+ kind: lifecycle
+ layer: unit
+ test: tests/test_local_deps.py::test_reconcile_startup_dependencies_uses_automatic_runtime_admission
- id: MH-USAGE-001
name: Tokens an upstream reported before the turn ended are still metered
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
index 918ab742a..8794d750d 100644
--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
@@ -25,6 +25,7 @@ from config.v2_config import (
model_hub_fixed_menu_ids,
)
from core.handlers.model_hub.adapter import (
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
RawCallOutcome,
@@ -122,6 +123,14 @@ class AdapterBoundaryFake:
self.requests: list[object] = []
self.refreshable_credential_refs = frozenset(refreshable_credential_refs)
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult:
+ return EngineEnsureResult(status=await self.start(), changed=force)
+
async def start(self) -> EngineStatus:
return EngineStatus(EngineHealth.OK, "test", True, "127.0.0.1", 18443, None)
diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.py
index ffc73a5fd..b4efaa4a2 100644
--- a/tests/test_controller_model_hub_gate.py
+++ b/tests/test_controller_model_hub_gate.py
@@ -15,8 +15,10 @@ from modules.agents.model_hub import resolve_model_hub_launch, resolve_opencode_
def test_controller_leaves_model_hub_aggregate_absent_by_default(monkeypatch):
import core.handlers.model_hub as model_hub
+ import vibe.model_hub_runtime as model_hub_runtime
factory_calls = 0
+ adapter = object()
def create_service():
nonlocal factory_calls
@@ -25,6 +27,11 @@ def test_controller_leaves_model_hub_aggregate_absent_by_default(monkeypatch):
monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
monkeypatch.setattr(model_hub, "create_default_service", create_service)
+ monkeypatch.setattr(
+ model_hub_runtime,
+ "get_model_hub_engine_adapter",
+ lambda: adapter,
+ )
controller = Controller.__new__(Controller)
controller._init_model_hub()
@@ -32,6 +39,7 @@ def test_controller_leaves_model_hub_aggregate_absent_by_default(monkeypatch):
assert controller.model_hub_service is None
assert controller.model_hub_turn_gateway is None
assert controller.model_hub_runtime is None
+ assert controller.model_hub_engine_adapter is adapter
assert factory_calls == 0
@@ -39,6 +47,7 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
import core.handlers.model_hub as model_hub
import core.handlers.model_hub.turn_gateway as turn_gateway
import modules.agents.model_hub as agent_model_hub
+ import vibe.model_hub_runtime as model_hub_runtime
from vibe import api, backend_model_catalog
service = SimpleNamespace(
@@ -59,6 +68,7 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
self.turn_gateway = turn_gateway
monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ adapter = object()
captured = {}
def create_service(**kwargs):
@@ -66,6 +76,11 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
return service
monkeypatch.setattr(model_hub, "create_default_service", create_service)
+ monkeypatch.setattr(
+ model_hub_runtime,
+ "get_model_hub_engine_adapter",
+ lambda: adapter,
+ )
monkeypatch.setattr(turn_gateway, "ModelHubTurnGateway", Gateway)
monkeypatch.setattr(agent_model_hub, "ModelHubRuntimeRouter", Router)
refresh_callbacks = []
@@ -114,6 +129,7 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
assert controller.model_hub_turn_gateway.service is service
assert controller.model_hub_runtime.service is service
assert controller.model_hub_runtime.turn_gateway is controller.model_hub_turn_gateway
+ assert captured["adapter"] is adapter
assert captured["requested_model_override"]("codex") == "agent-model"
assert captured["requested_model_override"]("claude") is None
assert captured["cli_present_override"]("codex") is True
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 3ef450257..ba5536113 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -1019,6 +1019,26 @@ def test_socket_verifier_skips_posix_mode_check_on_windows(monkeypatch, socket_p
assert internal_client._verified_socket_path(socket_path) == socket_path
+def test_health_sync_rejects_a_stale_socket_path(socket_path) -> None:
+ assert internal_client.health_sync(socket_path, timeout=0.05) is False
+
+
+def test_health_sync_accepts_a_healthy_controller(socket_path) -> None:
+ class HealthyClient:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def get(self, path):
+ assert path == "/internal/health"
+ return httpx.Response(200, json={"ok": True})
+
+ with patch("vibe.internal_client.httpx.Client", return_value=HealthyClient()):
+ assert internal_client.health_sync(socket_path, timeout=0.05) is True
+
+
def test_show_access_clients_round_trip(socket_path):
app = FastAPI()
captured: list[tuple[str, dict]] = []
diff --git a/tests/test_internal_client_timeouts.py b/tests/test_internal_client_timeouts.py
index aecc41bfd..470239086 100644
--- a/tests/test_internal_client_timeouts.py
+++ b/tests/test_internal_client_timeouts.py
@@ -53,6 +53,8 @@ from vibe.internal_client import (
memory_status_sync,
memory_wake,
)
+from vibe.model_hub_client import MODEL_HUB_RPC_TIMEOUT_SECONDS
+from vibe.runtime import SERVICE_SLOW_START_TIMEOUT_SECONDS
def _ui_dependency_poll_budget_seconds() -> float:
@@ -165,12 +167,9 @@ def test_memory_operations_have_no_reporting_timeout() -> None:
assert "timeout" not in inspect.signature(operation).parameters
-def test_install_client_covers_the_dependency_job_budget() -> None:
- # The UI polls the install job for its full budget. A shorter transport
- # deadline marks the job failed while the controller is still downloading,
- # extracting, and activating.
+def test_dependency_poller_outlasts_every_install_transport() -> None:
+ # The UI must keep polling past both direct Memory installation and CPA's
+ # sequential controller-readiness plus install-RPC bounds.
budget = _ui_dependency_poll_budget_seconds()
- assert MEMORY_INSTALL_TIMEOUT_SECONDS >= budget - 30
- # ...but not beyond it: outliving the poller only moves the false failure to
- # the UI side.
assert MEMORY_INSTALL_TIMEOUT_SECONDS <= budget
+ assert SERVICE_SLOW_START_TIMEOUT_SECONDS + MODEL_HUB_RPC_TIMEOUT_SECONDS < budget
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index c6f31d4d0..161f3b502 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -2237,6 +2237,58 @@ def test_model_hub_rpc_is_stably_disabled_without_touching_service(monkeypatch):
assert controller.model_hub_service.mock_calls == []
+def test_model_hub_dependency_rpc_remains_available_when_feature_is_disabled(monkeypatch):
+ from core.handlers.model_hub.adapter import (
+ EngineEnsureResult,
+ EngineHealth,
+ EngineStatus,
+ )
+
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ controller = _build_controller_double()
+ controller.model_hub_service = None
+ controller.model_hub_engine_adapter = SimpleNamespace(
+ ensure_installed=AsyncMock(
+ return_value=EngineEnsureResult(
+ status=EngineStatus(
+ health=EngineHealth.NOT_STARTED,
+ installed_version="v7.2.149",
+ verified=True,
+ listen_host="127.0.0.1",
+ listen_port=None,
+ last_check_iso="2026-09-05T00:00:00Z",
+ host_platform="linux-amd64",
+ ),
+ changed=True,
+ )
+ )
+ )
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post(
+ "/internal/model-hub",
+ json={
+ "operation": "runtime_ensure_dependency",
+ "payload": {"force": True, "offline": True},
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 200
+ result = response.json()["result"]
+ assert result["enabled"] is False
+ assert result["changed"] is True
+ assert result["status"]["installed_version"] == "v7.2.149"
+ controller.model_hub_engine_adapter.ensure_installed.assert_awaited_once_with(
+ force=True,
+ offline=True,
+ )
+
+
async def _publish_event_round_trip():
from core import inbox_events
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 1bd6325ba..147045ab4 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -1254,6 +1254,23 @@ def test_dependencies_status_shape(monkeypatch):
}
monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())
+ monkeypatch.setattr(
+ api,
+ "_model_hub_engine_dependency_status",
+ lambda: {
+ "id": "model-hub-engine",
+ "kind": "runtime",
+ "required": True,
+ "installed": True,
+ "version": "v7.2.149",
+ "latest_version": "v7.2.149",
+ "has_update": False,
+ "status": "ready",
+ "action_class": "none",
+ "reason": None,
+ "download_error": None,
+ },
+ )
monkeypatch.setattr(
api,
"_memory_dependencies_status",
@@ -1296,6 +1313,7 @@ def test_dependencies_status_shape(monkeypatch):
"askill",
"avault",
"show-runtime",
+ "model-hub-engine",
"memory-package",
"memory-runtime",
"tmux",
@@ -1309,6 +1327,9 @@ def test_dependencies_status_shape(monkeypatch):
assert by["show-runtime"]["installed"] and by["show-runtime"]["version"] == "1.4.0"
assert by["show-runtime"]["latest_version"] == "1.4.0"
assert by["show-runtime"]["has_update"] is False
+ assert by["model-hub-engine"]["version"] == "v7.2.149"
+ assert by["model-hub-engine"]["latest_version"] == "v7.2.149"
+ assert by["model-hub-engine"]["status"] == "ready"
assert by["memory-package"]["readiness"] == "ready"
assert by["memory-runtime"] == {
"id": "memory-runtime",
@@ -1327,6 +1348,517 @@ def test_dependencies_status_shape(monkeypatch):
assert by["node"]["installed"] and by["node"]["version"] == "20.11"
+ ("managed", "platform_supported", "expected"),
+ (
+ pytest.param(
+ {
+ "installed": True,
+ "version": "v7.2.149",
+ "selected_version": "v7.2.149",
+ "matches_manifest": True,
+ "status": "ready",
+ "reason": None,
+ },
+ True,
+ ("ready", "none", False),
+ id="pinned-target-ready",
+ ),
+ pytest.param(
+ {
+ "installed": True,
+ "version": "v7.2.105",
+ "selected_version": "v7.2.149",
+ "matches_manifest": False,
+ "status": "ready",
+ "reason": None,
+ },
+ True,
+ ("upgrade_required", "repairable", True),
+ id="older-avibe-pin-installed",
+ ),
+ pytest.param(
+ {
+ "installed": False,
+ "version": None,
+ "selected_version": "v7.2.149",
+ "matches_manifest": None,
+ "status": "missing",
+ "reason": None,
+ },
+ True,
+ ("missing", "repairable", False),
+ id="not-installed",
+ ),
+ pytest.param(
+ {
+ "installed": False,
+ "version": None,
+ "selected_version": "v7.2.149",
+ "matches_manifest": None,
+ "status": "missing",
+ "reason": "model_hub_engine_platform_unsupported",
+ },
+ False,
+ ("unsupported", "none", False),
+ id="unsupported-platform",
+ ),
+ pytest.param(
+ {
+ "installed": False,
+ "version": None,
+ "selected_version": "v7.2.149",
+ "matches_manifest": None,
+ "status": "error",
+ "reason": "model_hub_engine_install_inspection_failed",
+ },
+ True,
+ ("error", "repairable", False),
+ id="repairable-inspection-failure",
+ ),
+ pytest.param(
+ {
+ "installed": False,
+ "version": None,
+ "selected_version": "v7.2.149",
+ "matches_manifest": None,
+ "status": "error",
+ "reason": "model_hub_engine_install_inspection_failed",
+ },
+ False,
+ ("unsupported", "none", False),
+ id="foreign-pointer-cannot-hide-unsupported-host",
+ ),
+ pytest.param(
+ {
+ "installed": True,
+ "version": "v7.2.105",
+ "selected_version": "v7.2.149",
+ "matches_manifest": False,
+ "status": "error",
+ "reason": "model_hub_engine_archive_download_failed",
+ },
+ True,
+ ("error", "repairable", True),
+ id="failed-upgrade-preserves-installed-version",
+ ),
+ pytest.param(
+ {
+ "installed": False,
+ "version": None,
+ "selected_version": None,
+ "matches_manifest": None,
+ "status": "error",
+ "reason": "model_hub_engine_manifest_invalid",
+ },
+ True,
+ ("error", "operator_only", False),
+ id="unresolved-target",
+ ),
+ ),
+)
+def test_model_hub_engine_dependency_status_projects_exact_avibe_pin(
+ monkeypatch,
+ managed,
+ platform_supported,
+ expected,
+):
+ class Manager:
+ def __init__(self, *, offline):
+ assert offline is True
+
+ def status(self):
+ return managed
+
+ def supports_host_platform(self):
+ return platform_supported
+
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ Manager,
+ )
+
+ dependency = api._model_hub_engine_dependency_status()
+
+ status, action_class, has_update = expected
+ assert dependency["required"] is platform_supported
+ assert dependency["latest_version"] == managed["selected_version"]
+ assert dependency["status"] == status
+ assert dependency["action_class"] == action_class
+ assert dependency["has_update"] is has_update
+
+
[email protected]("locale", ("en", "zh"))
+def test_every_model_hub_dependency_failure_reason_is_localized(
+ tmp_path,
+ locale,
+):
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+
+ translations = json.loads(
+ (Path("ui/src/i18n") / f"{locale}.json").read_text(encoding="utf-8")
+ )["errors"]
+ reasons = EngineRuntimeManager(
+ runtime_dir=tmp_path / "runtime",
+ offline=True,
+ ).dependency_failure_reasons()
+
+ missing = sorted(reason for reason in reasons if not translations.get(reason))
+ assert missing == []
+
+
+def test_model_hub_engine_ensure_uses_direct_manager_without_a_controller(
+ monkeypatch,
+ tmp_path,
+):
+ calls = []
+
+ class Manager:
+ def __init__(self, *, offline):
+ calls.append(("manager", offline))
+
+ def ensure(self, *, force):
+ calls.append(("ensure", force))
+ return {"ok": True, "version": "v7.2.149"}
+
+ monkeypatch.setattr(
+ "vibe.internal_client.default_socket_path",
+ lambda: tmp_path / "missing-controller.sock",
+ )
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: None,
+ )
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ Manager,
+ )
+
+ result = api.ensure_model_hub_engine_installed(force=True)
+
+ assert result["ok"] is True
+ assert calls == [("manager", None), ("ensure", True)]
+
+
+def test_model_hub_engine_ensure_uses_controller_for_a_live_runtime(
+ monkeypatch,
+ tmp_path,
+):
+ socket_path = tmp_path / "controller.sock"
+ socket_path.touch()
+ calls = []
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ calls.append((force, offline))
+ return {
+ "changed": True,
+ "status": {
+ "verified": True,
+ "installed_version": "v7.2.149",
+ "health": "not_started",
+ },
+ }
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("a live controller owns engine replacement"),
+ )
+
+ result = api.ensure_model_hub_engine_installed(force=True, offline=True)
+
+ assert result == {
+ "ok": True,
+ "installed": True,
+ "changed": True,
+ "version": "v7.2.149",
+ "status": {
+ "verified": True,
+ "installed_version": "v7.2.149",
+ "health": "not_started",
+ },
+ "reason": None,
+ }
+ assert calls == [(True, True)]
+
+
[email protected]("controller_error", ("feature_disabled", "source_not_found"))
+def test_model_hub_engine_ensure_does_not_bypass_a_live_older_controller(
+ monkeypatch,
+ tmp_path,
+ controller_error,
+):
+ from core.handlers.model_hub import ModelHubError
+
+ socket_path = tmp_path / "controller.sock"
+ socket_path.touch()
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ raise ModelHubError(controller_error, status=404)
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("a live controller owns engine replacement"),
+ )
+
+ result = api.ensure_model_hub_engine_installed(force=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == controller_error
+
+
+def test_model_hub_engine_ensure_does_not_retry_a_controller_install_failure(
+ monkeypatch,
+ tmp_path,
+):
+ from core.handlers.model_hub import ModelHubError
+
+ socket_path = tmp_path / "controller.sock"
+ socket_path.touch()
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ raise ModelHubError(
+ "engine_down",
+ status=503,
+ data={"reason": "model_hub_engine_archive_download_failed"},
+ )
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("a failed download must not be repeated"),
+ )
+
+ result = api.ensure_model_hub_engine_installed()
+
+ assert result["ok"] is False
+ assert result["reason"] == "model_hub_engine_archive_download_failed"
+
+
+def test_model_hub_engine_ensure_waits_for_a_starting_controller(
+ monkeypatch,
+ tmp_path,
+):
+ socket_path = tmp_path / "controller.sock"
+ calls = []
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ calls.append((force, offline))
+ return {
+ "changed": False,
+ "status": {
+ "verified": True,
+ "installed_version": "v7.2.149",
+ },
+ }
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr(
+ "vibe.internal_client.health_sync",
+ lambda path, **_kwargs: path.exists(),
+ )
+ monkeypatch.setattr(
+ api.time,
+ "sleep",
+ lambda _seconds: socket_path.touch(),
+ )
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("the starting controller owns engine replacement"),
+ )
+
+ result = api.ensure_model_hub_engine_installed()
+
+ assert result["ok"] is True
+ assert calls == [(False, False)]
+
+
+def test_model_hub_engine_ensure_waits_past_a_stale_socket(
+ monkeypatch,
+ tmp_path,
+):
+ socket_path = tmp_path / "stale-controller.sock"
+ socket_path.touch()
+ readiness = iter((False, True))
+ probes = []
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ return {
+ "changed": False,
+ "status": {
+ "verified": True,
+ "installed_version": "v7.2.149",
+ },
+ }
+
+ def probe(path, **_kwargs):
+ probes.append(path)
+ return next(readiness)
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", probe)
+ monkeypatch.setattr(api.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("the starting controller owns engine replacement"),
+ )
+
+ result = api.ensure_model_hub_engine_installed()
+
+ assert result["ok"] is True
+ assert probes == [socket_path, socket_path]
+
+
+def test_model_hub_engine_ensure_never_falls_back_while_controller_owns_runtime(
+ monkeypatch,
+ tmp_path,
+):
+ from core.handlers.model_hub import ModelHubError
+
+ socket_path = tmp_path / "missing-controller.sock"
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ raise ModelHubError("engine_down", status=503)
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr(
+ "vibe.runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS",
+ 0,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", lambda *_args, **_kwargs: False)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("a controller owner excludes direct replacement"),
+ )
+
+ result = api.ensure_model_hub_engine_installed(force=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "engine_down"
+
+
+def test_model_hub_engine_ensure_treats_an_unsupported_host_as_nonfatal(
+ monkeypatch,
+ tmp_path,
+):
+ class Manager:
+ def __init__(self, *, offline):
+ assert offline is None
+
+ def ensure(self, *, force):
+ assert force is False
+ return {
+ "ok": False,
+ "installed": False,
+ "changed": False,
+ "skipped": False,
+ "reason": "model_hub_engine_platform_unsupported",
+ "version": "v7.2.149",
+ }
+
+ monkeypatch.setattr(
+ "vibe.internal_client.default_socket_path",
+ lambda: tmp_path / "missing-controller.sock",
+ )
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: None,
+ )
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ Manager,
+ )
+
+ result = api.ensure_model_hub_engine_installed()
+
+ assert result == {
+ "ok": True,
+ "installed": False,
+ "changed": False,
+ "skipped": True,
+ "reason": "model_hub_engine_platform_unsupported",
+ "version": "v7.2.149",
+ "status": "unsupported",
+ }
+
+
+def test_model_hub_engine_ensure_treats_controller_unsupported_as_nonfatal(
+ monkeypatch,
+ tmp_path,
+):
+ from core.handlers.model_hub import ModelHubError
+
+ socket_path = tmp_path / "controller.sock"
+ socket_path.touch()
+
+ class Remote:
+ def ensure_runtime_dependency(self, *, force, offline):
+ raise ModelHubError("runtime_platform_unsupported", status=422)
+
+ monkeypatch.setattr("vibe.internal_client.default_socket_path", lambda: socket_path)
+ monkeypatch.setattr(
+ "vibe.runtime.resolve_service_owner_pid",
+ lambda *, include_starting: 314,
+ )
+ monkeypatch.setattr("vibe.internal_client.health_sync", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr("vibe.model_hub_client.ModelHubRemoteService", Remote)
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda **_kwargs: pytest.fail("a live controller owns dependency admission"),
+ )
+
+ result = api.ensure_model_hub_engine_installed()
+
+ assert result == {
+ "ok": True,
+ "installed": False,
+ "changed": False,
+ "reason": "model_hub_engine_platform_unsupported",
+ "message": "modelHub.errors.runtime_platform_unsupported",
+ "skipped": True,
+ "status": "unsupported",
+ }
+
+
@pytest.mark.parametrize(
("runtime_status", "expected"),
(
@@ -2175,8 +2707,11 @@ def test_dependencies_status_node_unsupported_not_ready(monkeypatch):
def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeypatch):
+ """MH-RUNTIME-008: startup converges CPA without changing run intent."""
+
askill_calls = []
avault_calls = []
+ model_hub_calls = []
memory_calls = []
def reconcile_memory_package():
@@ -2196,6 +2731,12 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeyp
return {"ok": True, "installed": True, "changed": False, "path": "/x/avault"}
monkeypatch.setattr(api, "ensure_avault_installed", fake_ensure_avault)
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda *, force=False: model_hub_calls.append(force)
+ or {"ok": True, "installed": True, "changed": True, "version": "v7.2.149"},
+ )
import core.show_runtime as srt_mod
@@ -2234,6 +2775,8 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeyp
assert out["memory_package"]["reason"] == "memory_not_required"
assert askill_calls == [False]
assert avault_calls == [False]
+ assert model_hub_calls == [False]
+ assert out["model_hub_engine"]["version"] == "v7.2.149"
assert manager.prepared == [(False, True)]
assert out["node"]["status"] == "ready"
assert out["show_runtime"]["ok"] is True
@@ -2310,6 +2853,11 @@ def test_startup_memory_repair_continues_other_dependencies_before_service_resta
"ensure_avault_installed",
lambda **_kwargs: events.append("avault") or {"ok": True},
)
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda **_kwargs: events.append("model-hub-engine") or {"ok": True},
+ )
monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")
import core.show_runtime as srt_mod
@@ -2326,7 +2874,7 @@ def test_startup_memory_repair_continues_other_dependencies_before_service_resta
result = api.reconcile_startup_dependencies()
- assert events == ["askill", "avault"]
+ assert events == ["askill", "avault", "model-hub-engine"]
assert result["memory_package"]["restarting"] is True
assert result["show_runtime"]["status"] == "failed"
@@ -2371,6 +2919,11 @@ def test_memory_indep_028_startup_retries_after_restart_admission(monkeypatch):
"ensure_avault_installed",
lambda **_kwargs: events.append("avault") or {"ok": True},
)
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda **_kwargs: events.append("model-hub-engine") or {"ok": True},
+ )
restart_pending = iter((True, False))
monkeypatch.setattr(api, "restart_is_pending", lambda: next(restart_pending))
monkeypatch.setattr(api.time, "sleep", lambda _seconds: events.append("wait"))
@@ -2394,6 +2947,7 @@ def test_memory_indep_028_startup_retries_after_restart_admission(monkeypatch):
"memory_package_upgrade_busy",
"askill",
"avault",
+ "model-hub-engine",
"wait",
"memory_package_ready",
]
@@ -2490,6 +3044,11 @@ def test_startup_memory_repair_failure_keeps_other_dependency_reconcile_running(
"ensure_avault_installed",
lambda *, force: events.append("avault") or {"ok": True},
)
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda *, force: events.append("model-hub-engine") or {"ok": True},
+ )
import core.show_runtime as srt_mod
@@ -2502,7 +3061,7 @@ def test_startup_memory_repair_failure_keeps_other_dependency_reconcile_running(
result = api.reconcile_startup_dependencies()
- assert events == ["askill", "avault"]
+ assert events == ["askill", "avault", "model-hub-engine"]
assert result["ok"] is False
assert result["memory_package"]["reason"] == "memory_package_install_failed"
@@ -2510,6 +3069,11 @@ def test_startup_memory_repair_failure_keeps_other_dependency_reconcile_running(
def test_reconcile_startup_dependencies_reports_runtime_install_failure_without_node(monkeypatch):
monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: {"ok": True, "installed": True})
monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda force=False: {"ok": True, "installed": True},
+ )
import core.show_runtime as srt_mod
@@ -2547,6 +3111,11 @@ def test_reconcile_startup_dependencies_can_be_disabled(monkeypatch):
monkeypatch.setenv("VIBE_STARTUP_DEPENDENCY_RECONCILE", "0")
monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: pytest.fail("should not reconcile"))
monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: pytest.fail("should not reconcile"))
+ monkeypatch.setattr(
+ api,
+ "ensure_model_hub_engine_installed",
+ lambda force=False: pytest.fail("should not reconcile"),
+ )
out = api.reconcile_startup_dependencies()
@@ -3189,3 +3758,34 @@ def test_start_dependency_install_job_runs_avault(monkeypatch):
_t.sleep(0.02)
assert flag["called"] is True
assert cur["status"] == "succeeded" and cur["ok"] is True
+
+
+def test_start_dependency_install_job_runs_model_hub_engine(monkeypatch):
+ import time as _t
+
+ calls = []
+
+ def fake_ensure(*, force=False):
+ calls.append(force)
+ return {
+ "ok": True,
+ "installed": True,
+ "changed": True,
+ "version": "v7.2.149",
+ }
+
+ monkeypatch.setattr(api, "ensure_model_hub_engine_installed", fake_ensure)
+ job = api.start_dependency_install_job("model-hub-engine")
+ cur = job
+ for _ in range(100):
+ cur = api.get_agent_install_job(
+ job["job_id"],
+ backend="model-hub-engine",
+ )
+ if cur.get("status") != "running":
+ break
+ _t.sleep(0.02)
+
+ assert calls == [True]
+ assert cur["status"] == "succeeded"
+ assert cur["version"] == "v7.2.149"
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 0428ec5a9..fafbe7f36 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -28,6 +28,7 @@ from config.v2_config import (
from core.agent_auth_service import BackendLoginInProgressError
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -161,6 +162,8 @@ class FakeAdapter:
self.start_calls = 0
self.stop_runtime_calls = 0
self.install_calls = 0
+ self.ensure_calls: list[bool] = []
+ self.ensure_offline_calls: list[bool] = []
self.credential_count = 0
self.observation: SourceObservation | None = None
self.observed_protocol_orders: list[tuple[str, ...]] = []
@@ -168,8 +171,13 @@ class FakeAdapter:
self.refreshable_credential_refs: set[str] = set()
self.discovery_credential_refs: list[str] = []
- async def ensure_installed(self):
- return await self.status()
+ async def ensure_installed(self, *, force=False, offline=False):
+ self.ensure_calls.append(force)
+ self.ensure_offline_calls.append(offline)
+ return EngineEnsureResult(
+ status=await self.status(),
+ changed=force,
+ )
async def install(self):
self.install_calls += 1
@@ -945,6 +953,7 @@ def test_runtime_recovery_starts_only_for_persisted_user_intent(tmp_path):
asyncio.run(service.recover_runtime_intent())
assert adapter.start_calls == 0
+ assert adapter.ensure_calls == []
store.config.enabled = True
restarted = ModelHubService(
@@ -958,6 +967,7 @@ def test_runtime_recovery_starts_only_for_persisted_user_intent(tmp_path):
asyncio.run(restarted.recover_runtime_intent())
assert adapter.start_calls == 1
+ assert adapter.ensure_calls == [False]
def test_runtime_start_syncs_sources_before_starting_once(tmp_path):
@@ -1169,6 +1179,32 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
assert calls == [("runtime_install", None)]
+def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypatch):
+ from vibe import model_hub_client
+
+ calls = []
+
+ def rpc(operation, payload=None):
+ calls.append((operation, payload))
+ return {
+ "contract_version": 7,
+ "changed": True,
+ "status": {"health": "not_started", "verified": True},
+ }
+
+ monkeypatch.setattr(model_hub_client, "_rpc_sync", rpc)
+
+ runtime = ModelHubRemoteService().ensure_runtime_dependency(
+ force=True,
+ offline=True,
+ )
+
+ assert runtime["changed"] is True
+ assert calls == [
+ ("runtime_ensure_dependency", {"force": True, "offline": True})
+ ]
+
+
def test_reorder_client_preserves_explicit_null_order(monkeypatch):
from vibe import model_hub_client
@@ -1249,6 +1285,64 @@ def test_runtime_install_is_allowlisted_by_controller_rpc(tmp_path):
assert adapter.install_calls == 1
+def test_runtime_dependency_ensure_is_allowlisted_without_starting_engine(tmp_path):
+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+
+ class PinnedAdapter(FakeAdapter):
+ async def status(self):
+ return EngineStatus(
+ health=EngineHealth.NOT_STARTED,
+ installed_version="v7.2.149",
+ verified=True,
+ listen_host="127.0.0.1",
+ listen_port=None,
+ last_check_iso=None,
+ )
+
+ adapter = PinnedAdapter()
+ service = ModelHubService(
+ store=MemoryStore(),
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ )
+
+ runtime = asyncio.run(
+ dispatch_model_hub_rpc(
+ service,
+ "runtime_ensure_dependency",
+ {"force": True, "offline": True},
+ )
+ )
+
+ assert runtime["changed"] is True
+ assert runtime["enabled"] is False
+ assert runtime["status"]["installed_version"] == "v7.2.149"
+ assert adapter.ensure_calls == [True]
+ assert adapter.ensure_offline_calls == [True]
+ assert adapter.start_calls == 0
+
+
+def test_runtime_dependency_ensure_preserves_closed_install_failure_reason(tmp_path):
+ class InstallFailure(RuntimeError):
+ reason = "model_hub_engine_archive_download_failed"
+
+ class FailingAdapter(FakeAdapter):
+ async def ensure_installed(self, *, force=False, offline=False):
+ raise InstallFailure
+
+ service, _store, _adapter = _service(tmp_path, adapter=FailingAdapter())
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.runtime_ensure_dependency())
+
+ assert exc_info.value.code == "engine_down"
+ assert exc_info.value.data == {
+ "reason": "model_hub_engine_archive_download_failed"
+ }
+
+
def test_runtime_status_reports_observed_not_installed_state(tmp_path):
class NotInstalledAdapter(FakeAdapter):
async def start(self):
diff --git a/tests/test_model_hub_engine_release_guard.py b/tests/test_model_hub_engine_release_guard.py
new file mode 100644
index 000000000..810ff8f0f
--- /dev/null
+++ b/tests/test_model_hub_engine_release_guard.py
@@ -0,0 +1,204 @@
+from __future__ import annotations
+
+import gzip
+import hashlib
+import io
+import json
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from scripts import model_hub_engine_release_guard as guard
+
+
+def _archive(binary: bytes) -> bytes:
+ output = io.BytesIO()
+ with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:
+ with tarfile.open(fileobj=compressed, mode="w") as bundle:
+ member = tarfile.TarInfo("cli-proxy-api")
+ member.mode = 0o755
+ member.size = len(binary)
+ bundle.addfile(member, io.BytesIO(binary))
+ return output.getvalue()
+
+
+def _manifest(tmp_path: Path) -> tuple[Path, dict[str, bytes], dict[str, bytes]]:
+ version = "v7.2.149"
+ asset_release_tag = "model-hub-engine-v7.2.149-1"
+ owned_root = f"{guard.OWNED_RELEASE_ROOT}/{asset_release_tag}"
+ upstream_root = f"{guard.UPSTREAM_RELEASE_ROOT}/{version}"
+ source_sha = "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa"
+ owned: dict[str, bytes] = {}
+ upstream: dict[str, bytes] = {}
+ assets = []
+ for platform in sorted(guard.EXPECTED_PLATFORMS):
+ upstream_platform = guard.UPSTREAM_PLATFORM_NAMES[platform]
+ name = f"CLIProxyAPI_7.2.149_{upstream_platform}.tar.gz"
+ archive = _archive(f"{platform}-binary".encode())
+ archive_sha = hashlib.sha256(archive).hexdigest()
+ binary_sha = hashlib.sha256(f"{platform}-binary".encode()).hexdigest()
+ url = f"{owned_root}/{name}"
+ assets.append(
+ {
+ "platform": platform,
+ "url": url,
+ "size_bytes": len(archive),
+ "sha256": archive_sha,
+ "binary_sha256": binary_sha,
+ "bin_path": "cli-proxy-api",
+ }
+ )
+ owned[url] = archive
+ owned[f"{url}.sha256"] = f"{archive_sha} {name}\n".encode()
+ upstream[f"{upstream_root}/{name}"] = archive
+
+ payload = {
+ "schema_version": 1,
+ "name": "cliproxyapi",
+ "version": version,
+ "source": "router-for-me/CLIProxyAPI",
+ "source_url": f"https://github.com/router-for-me/CLIProxyAPI/tree/{source_sha}",
+ "source_sha": source_sha,
+ "release_tag": version,
+ "asset_release_tag": asset_release_tag,
+ "license": "MIT",
+ "assets": assets,
+ }
+ manifest_path = tmp_path / "cliproxyapi_manifest.json"
+ manifest_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ owned[f"{owned_root}/model-hub-engine-manifest.json"] = manifest_path.read_bytes()
+ return manifest_path, owned, upstream
+
+
+def _fake_download(remote: dict[str, bytes]):
+ def download(url: str, destination: Path, **_kwargs) -> None:
+ try:
+ payload = remote[url]
+ except KeyError as exc:
+ raise guard.ReleaseGuardError(f"missing test asset: {url}") from exc
+ destination.write_bytes(payload)
+
+ return download
+
+
+def test_fetch_owned_release_materializes_exact_verified_assets(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path, owned, _upstream = _manifest(tmp_path)
+ monkeypatch.setattr(guard, "_download", _fake_download(owned))
+
+ spec = guard.fetch_release_assets(manifest_path, tmp_path / "backup")
+ verified = guard.verify_release_assets(manifest_path, tmp_path / "backup")
+
+ assert spec.asset_release_tag == "model-hub-engine-v7.2.149-1"
+ assert verified.expected_asset_names == {
+ path.name for path in (tmp_path / "backup").iterdir()
+ }
+
+
+def test_fetch_source_verifies_upstream_bytes_and_builds_publishable_release(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path, _owned, upstream = _manifest(tmp_path)
+ monkeypatch.setattr(guard, "_download", _fake_download(upstream))
+
+ spec = guard.fetch_upstream_assets(manifest_path, tmp_path / "publish")
+
+ assert spec.upstream_release_tag == "v7.2.149"
+ guard.verify_release_assets(manifest_path, tmp_path / "publish")
+
+
+ ("mutate", "match"),
+ [
+ (lambda path: path.write_bytes(path.read_bytes() + b"tampered"), "size mismatch"),
+ (lambda path: path.write_text("wrong checksum\n", encoding="utf-8"), "sidecar mismatch"),
+ ],
+)
+def test_verify_rejects_changed_release_bytes(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ mutate,
+ match,
+) -> None:
+ manifest_path, owned, _upstream = _manifest(tmp_path)
+ monkeypatch.setattr(guard, "_download", _fake_download(owned))
+ backup = tmp_path / "backup"
+ guard.fetch_release_assets(manifest_path, backup)
+ target = next(backup.glob("*.tar.gz" if match == "size mismatch" else "*.sha256"))
+ mutate(target)
+
+ with pytest.raises(guard.ReleaseGuardError, match=match):
+ guard.verify_release_assets(manifest_path, backup)
+
+
[email protected]("entry_kind", ["unexpected", "directory"])
+def test_verify_rejects_non_release_entries(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ entry_kind: str,
+) -> None:
+ manifest_path, owned, _upstream = _manifest(tmp_path)
+ monkeypatch.setattr(guard, "_download", _fake_download(owned))
+ backup = tmp_path / "backup"
+ guard.fetch_release_assets(manifest_path, backup)
+ if entry_kind == "unexpected":
+ (backup / "unexpected.txt").write_text("unexpected", encoding="utf-8")
+ expected = "unexpected=.*unexpected.txt"
+ else:
+ (backup / "nested").mkdir()
+ expected = "unsafe entries"
+
+ with pytest.raises(guard.ReleaseGuardError, match=expected):
+ guard.verify_release_assets(manifest_path, backup)
+
+
+def test_failed_fetch_preserves_last_verified_backup(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path, owned, _upstream = _manifest(tmp_path)
+ del owned[next(url for url in owned if url.endswith(".tar.gz"))]
+ monkeypatch.setattr(guard, "_download", _fake_download(owned))
+ backup = tmp_path / "backup"
+ backup.mkdir()
+ marker = backup / "last-good"
+ marker.write_text("preserve", encoding="utf-8")
+
+ with pytest.raises(guard.ReleaseGuardError, match="missing test asset"):
+ guard.fetch_release_assets(manifest_path, backup)
+
+ assert marker.read_text(encoding="utf-8") == "preserve"
+
+
+def test_manifest_rejects_non_owned_release_url(tmp_path: Path) -> None:
+ manifest_path, _owned, _upstream = _manifest(tmp_path)
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ payload["assets"][0]["url"] = (
+ "https://github.com/router-for-me/CLIProxyAPI/releases/download/"
+ "v7.2.149/CLIProxyAPI_7.2.149_darwin_aarch64.tar.gz"
+ )
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ with pytest.raises(guard.ReleaseGuardError, match="outside the Avibe-owned release"):
+ guard.load_release_spec(manifest_path)
+
+
+def test_workflow_has_scheduled_backup_and_non_clobbering_recovery() -> None:
+ workflow = (
+ guard.REPO_ROOT / ".github/workflows/model-hub-engine-release-guard.yml"
+ ).read_text(encoding="utf-8")
+
+ assert "schedule:" in workflow
+ assert "continue-on-error: true" in workflow
+ assert 'actions/artifacts"' in workflow
+ assert "MANIFEST_SHA: ${{ steps.manifest.outputs.sha256 }}" in workflow
+ assert "model-hub-engine-release-backup-${{ steps.manifest.outputs.sha256 }}" in workflow
+ assert "retention-days: 90" in workflow
+ assert "--verify-tag" in workflow
+ assert "--latest=false" in workflow
+ assert "missing_assets" in workflow
+ assert "--clobber" not in workflow
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 6a2cff3a3..955490a20 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -35,6 +35,7 @@ from config.v2_config import (
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
RawCallOutcome,
@@ -1128,6 +1129,14 @@ class ProbeAdapter:
self.refreshable_credential_refs: set[str] = set()
self.capability_queries: list[str] = []
+ async def ensure_installed(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> EngineEnsureResult:
+ return EngineEnsureResult(status=await self.status(), changed=force)
+
async def sync_sources(self, _bindings) -> None:
return None
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index f6880dfba..0b70e7d26 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -24,6 +24,7 @@ from config.v2_config import (
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -179,8 +180,8 @@ class FakeAdapter:
self.refreshable_credential_refs: set[str] = set()
self.capability_queries: list[str] = []
- async def ensure_installed(self):
- return await self.status()
+ async def ensure_installed(self, *, force=False, offline=False):
+ return EngineEnsureResult(status=await self.status(), changed=force)
async def start(self):
return await self.status()
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 49a094166..a3bb96652 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -774,32 +774,32 @@ def test_packaged_manifest_matches_frozen_runtime_dependency_values(
assert manifest == {
"name": "cliproxyapi",
"resolution": "resolved",
- "version": "v7.2.105",
- "source_sha": "4a2eb54dc6bf943196be4fb515e6a9407a4db143",
+ "version": "v7.2.149",
+ "source_sha": "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",
"assets": [
{
"platform": "darwin-arm64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_darwin_aarch64.tar.gz",
- "size_bytes": 18975205,
- "sha256": "641de855c486d373b3c69704bec55a5c5ce3efa523149cc9bd253f76040470d7",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_aarch64.tar.gz",
+ "size_bytes": 19723285,
+ "sha256": "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",
},
{
"platform": "darwin-x64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_darwin_amd64.tar.gz",
- "size_bytes": 20513376,
- "sha256": "c9332b8401cd54d357e7c66e88bce603fdb497701a7fa86ee2f82bb1aad846b9",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_amd64.tar.gz",
+ "size_bytes": 21334889,
+ "sha256": "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",
},
{
"platform": "linux-amd64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_linux_amd64.tar.gz",
- "size_bytes": 20558559,
- "sha256": "f432872815fe85ac4b0f83b5598253725eea70aae4c95025194cf558f6acef31",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_amd64.tar.gz",
+ "size_bytes": 21385633,
+ "sha256": "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",
},
{
"platform": "linux-arm64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_linux_aarch64.tar.gz",
- "size_bytes": 18559648,
- "sha256": "b72245cf1958251330eae9e17f1fc5a077f94146b2eea30e23ab5012c6059981",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_aarch64.tar.gz",
+ "size_bytes": 19287559,
+ "sha256": "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",
},
],
}
@@ -839,11 +839,58 @@ def test_contract_manifest_filters_unsupported_override_assets(
assert "win32-x64" not in {asset["platform"] for asset in manager.contract_manifest()["assets"]}
monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "win32-x64")
+ assert manager.supports_host_platform() is False
unsupported = manager.ensure()
assert unsupported["ok"] is False
assert unsupported["reason"] == "model_hub_engine_platform_unsupported"
+def test_host_support_requires_an_asset_in_the_selected_manifest(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-x64")
+ payload = json.loads(
+ Path("vibe/model_hub_runtime/cliproxyapi_manifest.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "probe", offline=True)
+ host_platform = manager.host_platform()
+ payload["assets"] = [
+ asset for asset in payload["assets"] if asset["platform"] != host_platform
+ ]
+ manifest_path = tmp_path / "missing-host-asset.json"
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ manager = EngineRuntimeManager(
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ offline=True,
+ )
+
+ assert manager.supports_host_platform() is False
+
+
+def test_foreign_pointer_inspection_cannot_hide_an_unsupported_host(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ runtime_dir.mkdir()
+ (runtime_dir / "current.json").write_text(
+ json.dumps({"platform": "linux-amd64"}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "win32-x64")
+ manager = EngineRuntimeManager(runtime_dir=runtime_dir, offline=True)
+
+ status = manager.status()
+
+ assert status["reason"] == "model_hub_engine_install_inspection_failed"
+ assert manager.supports_host_platform() is False
+
+
def test_install_admission_fetches_an_uncached_remote_manifest(tmp_path: Path) -> None:
archive, binary = _write_fixture_archive(tmp_path / "remote")
manifest = _write_fixture_manifest(tmp_path / "remote", archive, binary)
@@ -1248,30 +1295,30 @@ def test_installing_projection_matches_live_owner_or_resumable_claim(
(
"darwin-arm64",
"darwin-arm64",
- 18975205,
- "641de855c486d373b3c69704bec55a5c5ce3efa523149cc9bd253f76040470d7",
- "e8da44e6bf9d85fe7b98a2843d33ff509156727222d6a1ad5dd1a79709849337",
+ 19723285,
+ "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",
+ "048c0089aa53948af91249bb97f172b2392cce5968473a5a3dbb06f3d742c2e7",
),
(
"darwin-x64",
"darwin-x64",
- 20513376,
- "c9332b8401cd54d357e7c66e88bce603fdb497701a7fa86ee2f82bb1aad846b9",
- "07a607965a40f782f63625c557eeeddb39b08e08b1a3057881bb13fe6e887109",
+ 21334889,
+ "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",
+ "05388e65f58493325aff1e2dfa33e727e7fa732b2d9eb651ec13315689e418e5",
),
(
"linux-x64",
"linux-amd64",
- 20558559,
- "f432872815fe85ac4b0f83b5598253725eea70aae4c95025194cf558f6acef31",
- "2717656b33a0d76a7c02b451797341e8791f740a72d4e71577140886f42ba628",
+ 21385633,
+ "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",
+ "b0f163bfd94e8cd64895000662f26f255d2a72b5c3f5009a97e8dc91ed9b8107",
),
(
"linux-arm64",
"linux-arm64",
- 18559648,
- "b72245cf1958251330eae9e17f1fc5a077f94146b2eea30e23ab5012c6059981",
- "8c389d565b8555d5788314e56258c64d675ff76bb9e32047d339088f2789b07e",
+ 19287559,
+ "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",
+ "24799863d478579ec3eef5ccc83769f79df749a30282ce1e2063708a03826e5b",
),
],
)
@@ -3164,15 +3211,184 @@ def test_adapter_applies_changed_install_to_running_engine(
state_store=EngineStateStore(tmp_path / "state"),
)
- status = await adapter.ensure_installed()
+ result = await adapter.ensure_installed()
- assert status.installed_version == "v7.2.95"
- assert status.verified is True
+ assert result.status.installed_version == "v7.2.95"
+ assert result.status.verified is True
+ assert result.changed is changed
assert supervisor.restarts == expected_restarts
asyncio.run(run())
+def test_adapter_routes_offline_dependency_ensure_through_its_supervisor(
+ tmp_path: Path,
+) -> None:
+ calls: list[object] = []
+
+ class OfflineInstaller:
+ def ensure(self, *, force=False):
+ calls.append(("offline-ensure", force))
+ return {"ok": True, "changed": True}
+
+ class Installer:
+ def offline_copy(self):
+ calls.append("offline-copy")
+ return OfflineInstaller()
+
+ def ensure(self, *, force=False):
+ raise AssertionError("offline ensure must not use the online installer")
+
+ class Supervisor:
+ def __init__(self) -> None:
+ self.installer = Installer()
+
+ def restart_if_running(self) -> None:
+ calls.append("restart")
+
+ def status(self):
+ return {
+ "status": {
+ "health": "not_started",
+ "installed_version": "v7.2.149",
+ "verified": True,
+ "listening": None,
+ "last_check": None,
+ }
+ }
+
+ async def run() -> None:
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(), # type: ignore[arg-type]
+ state_store=EngineStateStore(tmp_path / "state"),
+ )
+
+ result = await adapter.ensure_installed(force=True, offline=True)
+
+ assert result.changed is True
+ assert result.status.installed_version == "v7.2.149"
+ assert calls == ["offline-copy", ("offline-ensure", True), "restart"]
+
+ asyncio.run(run())
+
+
+def test_direct_ensure_failure_is_durable_across_manager_reload(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ reason = "model_hub_engine_archive_download_failed"
+
+ def fail_ensure(_manager, **kwargs):
+ kwargs["on_resolved"](RUNTIME_INSTALL_TARGET)
+ return {"ok": False, "reason": reason}
+
+ monkeypatch.setattr(managed_runtime.ManagedRuntimeManager, "ensure", fail_ensure)
+ runtime_dir = tmp_path / "runtime"
+
+ result = EngineRuntimeManager(runtime_dir=runtime_dir, offline=True).ensure()
+ reloaded = EngineRuntimeManager(runtime_dir=runtime_dir, offline=True)
+
+ assert result == {"ok": False, "reason": reason}
+ assert reloaded.install_state()["reason"] == reason
+ assert reloaded.status()["status"] == "error"
+ assert reloaded.status()["reason"] == reason
+
+ def succeed_ensure(_manager, **kwargs):
+ kwargs["on_resolved"](RUNTIME_INSTALL_TARGET)
+ return {"ok": True, "changed": False}
+
+ monkeypatch.setattr(managed_runtime.ManagedRuntimeManager, "ensure", succeed_ensure)
+
+ assert reloaded.ensure()["ok"] is True
+ assert EngineRuntimeManager(runtime_dir=runtime_dir, offline=True).install_state() is None
+
+
+def test_dependency_ensure_settles_an_orphaned_install_claim(
+ tmp_path: Path,
+) -> None:
+ archive, binary = _write_fixture_archive(tmp_path / "fixture")
+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)
+ installer = EngineRuntimeManager(
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ manifest = installer._load_manifest(allow_network=False)
+ assert manifest is not None
+ manifest_archive = installer._manifest_archive_for_platform(manifest)
+ assert manifest_archive is not None
+ target = installer._install_target_identity(manifest, manifest_archive)
+ assert installer.transition_install_claim(
+ InstallClaimTransition.CREATE,
+ generation=RUNTIME_INSTALL_GENERATION_A,
+ target=target,
+ )
+ adapter = CLIProxyEngineAdapter(
+ supervisor=EngineSupervisor(
+ installer=installer,
+ state_store=EngineStateStore(tmp_path / "state"),
+ )
+ )
+
+ result = asyncio.run(adapter.ensure_installed())
+
+ assert result.status.health is EngineHealth.NOT_STARTED
+ assert result.status.verified is True
+ assert installer.install_state() is None
+
+
+def test_direct_ensure_success_preserves_a_newer_install_claim(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)
+ _create_runtime_install_claim(installer)
+
+ def succeed_after_claim_moves(_manager, **kwargs):
+ kwargs["on_resolved"](RUNTIME_INSTALL_TARGET)
+ assert installer.transition_install_claim(
+ InstallClaimTransition.RESUME,
+ generation=RUNTIME_INSTALL_GENERATION_B,
+ previous_generation=RUNTIME_INSTALL_GENERATION_A,
+ target=RUNTIME_INSTALL_TARGET,
+ )
+ return {"ok": True, "changed": False}
+
+ monkeypatch.setattr(
+ managed_runtime.ManagedRuntimeManager,
+ "ensure",
+ succeed_after_claim_moves,
+ )
+
+ assert installer.ensure()["ok"] is True
+ surviving = installer.install_state()
+ assert surviving is not None
+ assert surviving["state"] == "installing"
+ assert surviving["generation"] == RUNTIME_INSTALL_GENERATION_B
+
+
+def test_direct_ensure_lock_contention_is_transient(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ def contend(_manager, **_kwargs):
+ return {
+ "ok": False,
+ "changed": False,
+ "reason": "model_hub_engine_install_already_running",
+ "skipped": True,
+ }
+
+ monkeypatch.setattr(managed_runtime.ManagedRuntimeManager, "ensure", contend)
+ runtime_dir = tmp_path / "runtime"
+
+ result = EngineRuntimeManager(runtime_dir=runtime_dir, offline=True).ensure()
+ reloaded = EngineRuntimeManager(runtime_dir=runtime_dir, offline=True)
+
+ assert result["reason"] == "model_hub_engine_install_already_running"
+ assert reloaded.install_state() is None
+ assert reloaded.status()["status"] != "error"
+
+
def test_runtime_install_state_survives_adapter_reload_and_settles_once(
tmp_path: Path,
) -> None:
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index a94b7dfec..3c9644623 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -134,6 +134,25 @@ def test_dependency_install_route_allows_avault(monkeypatch, tmp_path):
assert response.get_json()["backend"] == "avault"
+def test_dependency_install_route_allows_model_hub_engine(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(
+ api,
+ "start_dependency_install_job",
+ lambda dep: {"ok": True, "job_id": "job-cpa", "backend": dep, "status": "running"},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/dependencies/model-hub-engine/install",
+ headers=csrf_headers(client, "http://127.0.0.1:15131"),
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["backend"] == "model-hub-engine"
+
+
def test_dependency_install_route_allows_memory_runtime(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
monkeypatch.setattr(
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 43119d3f7..e5266239f 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1892,6 +1892,13 @@ def test_managed_dependencies_doctor_uses_one_status_contract(monkeypatch):
"deps": [
{"id": "askill", "required": True, "installed": False, "status": "missing"},
{"id": "avault", "required": True, "installed": True, "status": "ready", "version": "0.1.6"},
+ {
+ "id": "model-hub-engine",
+ "required": True,
+ "installed": False,
+ "status": "upgrade_required",
+ "version": "v7.2.105",
+ },
{"id": "show-runtime", "required": True, "installed": False, "status": "missing"},
{"id": "tmux", "required": False, "installed": False, "status": "missing"},
{"id": "git-runtime", "required": False, "installed": True, "status": "ready"},
@@ -1907,6 +1914,9 @@ def test_managed_dependencies_doctor_uses_one_status_contract(monkeypatch):
assert offline_calls == [True]
assert next(item for item in items if item.get("code") == "dependencies.askill.not_ready")["repair"]["target"] == "askill"
assert next(item for item in items if item.get("code") == "dependencies.avault.ready")["status"] == "pass"
+ assert next(
+ item for item in items if item.get("code") == "dependencies.model-hub-engine.not_ready"
+ )["repair"]["target"] == "model-hub-engine"
assert next(item for item in items if item.get("code") == "dependencies.git-runtime.ready")["status"] == "pass"
assert next(item for item in items if item.get("code") == "dependencies.tmux.not_ready")["status"] == "warn"
assert next(item for item in items if item.get("code") == "dependencies.node.not_ready")["status"] == "fail"
@@ -2010,6 +2020,97 @@ def test_managed_dependencies_doctor_reports_memory_runtime_states(
)
+def test_managed_dependencies_doctor_probes_model_hub_engine_archive(monkeypatch):
+ monkeypatch.setattr(
+ cli.api,
+ "dependencies_status",
+ lambda **_kwargs: {
+ "deps": [
+ {
+ "id": "model-hub-engine",
+ "required": True,
+ "installed": False,
+ "status": "missing",
+ },
+ {
+ "id": "git-runtime",
+ "required": False,
+ "installed": True,
+ "status": "ready",
+ },
+ ]
+ },
+ )
+ probes = []
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.installer.EngineRuntimeManager",
+ lambda: SimpleNamespace(
+ probe_archive_reachability=lambda: probes.append(True)
+ or {"ok": True, "checked": True}
+ ),
+ )
+
+ items = cli._managed_dependencies_doctor_items(deep=True)
+
+ missing = next(
+ item
+ for item in items
+ if item.get("code") == "dependencies.model-hub-engine.not_ready"
+ )
+ assert missing["repair"]["target"] == "model-hub-engine"
+ assert probes == [True]
+
+
+ ("language", "expected_label"),
+ [("en", "Model Hub engine (CPA)"), ("zh", "Model Hub 引擎(CPA)")],
+)
+ ("status", "installed", "code"),
+ [("ready", True, "ready"), ("missing", False, "not_ready")],
+)
+def test_managed_dependencies_doctor_localizes_model_hub_engine_label(
+ monkeypatch,
+ language,
+ expected_label,
+ status,
+ installed,
+ code,
+):
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)
+ monkeypatch.setattr(
+ cli.api,
+ "dependencies_status",
+ lambda **_kwargs: {
+ "deps": [
+ {
+ "id": "model-hub-engine",
+ "required": True,
+ "installed": installed,
+ "status": status,
+ },
+ {
+ "id": "git-runtime",
+ "required": False,
+ "installed": True,
+ "status": "ready",
+ },
+ ]
+ },
+ )
+
+ items = cli._managed_dependencies_doctor_items()
+
+ item = next(
+ item
+ for item in items
+ if item.get("code") == f"dependencies.model-hub-engine.{code}"
+ )
+ assert expected_label in item["message"]
+ if language == "zh":
+ assert "Model Hub engine (CPA)" not in item["message"]
+
+
def test_managed_dependencies_doctor_suppresses_unsupported_askill_repair(monkeypatch):
monkeypatch.setattr(
cli.api,
@@ -2058,6 +2159,44 @@ def test_managed_dependencies_doctor_does_not_offer_unsupported_platform_repair(
assert not any(item.get("code") == "dependencies.tmux.not_ready" for item in items)
+def test_managed_dependencies_doctor_treats_unsupported_cpa_as_nonfatal(monkeypatch):
+ monkeypatch.setattr(
+ cli.api,
+ "dependencies_status",
+ lambda **_kwargs: {
+ "deps": [
+ {
+ "id": "model-hub-engine",
+ "required": False,
+ "installed": False,
+ "status": "unsupported",
+ "reason": "model_hub_engine_platform_unsupported",
+ },
+ {
+ "id": "git-runtime",
+ "required": False,
+ "installed": True,
+ "status": "ready",
+ },
+ ]
+ },
+ )
+
+ items = cli._managed_dependencies_doctor_items(deep=False)
+
+ unsupported = next(
+ item
+ for item in items
+ if item.get("code") == "dependencies.model-hub-engine.platform_unsupported"
+ )
+ assert unsupported["status"] == "warn"
+ assert "repair" not in unsupported
+ assert not any(
+ item.get("code") == "dependencies.model-hub-engine.not_ready"
+ for item in items
+ )
+
+
def test_managed_dependencies_doctor_accepts_usable_system_git(monkeypatch):
monkeypatch.setattr(cli.api, "dependencies_status", lambda **_kwargs: {"deps": []})
monkeypatch.setattr(
@@ -2584,6 +2723,7 @@ def test_runtime_prepare_strict_does_not_report_policy_skip_as_ready(monkeypatch
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_model_hub_engine_during_prepare", lambda **_kwargs: {"ok": True})
exit_code = cli.cmd_runtime(
SimpleNamespace(
@@ -2601,6 +2741,119 @@ def test_runtime_prepare_strict_does_not_report_policy_skip_as_ready(monkeypatch
assert "VIBE_INSTALL_SKIP_SHOW_RUNTIME" in captured.err
+def test_runtime_prepare_reports_cpa_failure_without_blocking_avibe_upgrade(
+ monkeypatch,
+ capsys,
+):
+ manager = SimpleNamespace(
+ prepare=lambda **_kwargs: {
+ "ok": True,
+ "policy": {"state": "allowed", "reason": None},
+ "install": {"state": "installed", "reason": None},
+ "runtime": {"state": "unchecked", "reason": None},
+ "status": {
+ "install": {
+ "state": "installed",
+ "install_dir": "/runtime/show",
+ }
+ },
+ }
+ )
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda _args: manager)
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(
+ cli,
+ "_ensure_model_hub_engine_during_prepare",
+ lambda **_kwargs: {
+ "ok": False,
+ "reason": "model_hub_engine_archive_download_failed",
+ },
+ )
+
+ exit_code = cli.cmd_runtime(
+ SimpleNamespace(
+ runtime_command="prepare",
+ offline=False,
+ force=False,
+ json=True,
+ strict=True,
+ )
+ )
+
+ payload = json.loads(capsys.readouterr().out)
+ assert exit_code == 0
+ assert payload["model_hub_engine"] == {
+ "ok": False,
+ "reason": "model_hub_engine_archive_download_failed",
+ }
+
+
+ ("cpa_result", "expected", "stream"),
+ (
+ ({"ok": True, "changed": True}, "Model Hub 引擎已安装。", "out"),
+ ({"ok": True, "changed": False}, "Model Hub 引擎已就绪。", "out"),
+ (
+ {"ok": False, "skipped": True, "reason": "offline"},
+ "Model Hub 引擎:已跳过(offline)。",
+ "out",
+ ),
+ (
+ {"ok": False, "reason": "download_failed"},
+ "Model Hub 引擎尚未就绪:download_failed",
+ "err",
+ ),
+ ),
+)
+def test_runtime_prepare_localizes_cpa_output(
+ monkeypatch,
+ capsys,
+ cpa_result,
+ expected,
+ stream,
+):
+ manager = SimpleNamespace(
+ prepare=lambda **_kwargs: {
+ "ok": True,
+ "policy": {"state": "allowed", "reason": None},
+ "install": {"state": "installed", "reason": None},
+ "runtime": {"state": "unchecked", "reason": None},
+ "status": {"install": {"state": "installed", "install_dir": None}},
+ }
+ )
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda _args: manager)
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(
+ cli,
+ "_ensure_model_hub_engine_during_prepare",
+ lambda **_kwargs: cpa_result,
+ )
+
+ assert (
+ cli.cmd_runtime(
+ SimpleNamespace(
+ runtime_command="prepare",
+ offline=False,
+ force=False,
+ json=False,
+ strict=False,
+ )
+ )
+ == 0
+ )
+
+ captured = capsys.readouterr()
+ assert expected in getattr(captured, stream)
+ assert "Model Hub engine" not in captured.out + captured.err
+
+
def test_runtime_prepare_force_does_not_report_explicit_command_as_replaced(monkeypatch, capsys):
manager = SimpleNamespace(
prepare=lambda **_kwargs: {
@@ -2620,6 +2873,7 @@ def test_runtime_prepare_force_does_not_report_explicit_command_as_replaced(monk
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_model_hub_engine_during_prepare", lambda **_kwargs: {"ok": True})
exit_code = cli.cmd_runtime(
SimpleNamespace(
diff --git a/ui/src/components/settings/SettingsDependenciesPage.logic.ts b/ui/src/components/settings/SettingsDependenciesPage.logic.ts
index 47e8371ca..a6e16f37c 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.logic.ts
+++ b/ui/src/components/settings/SettingsDependenciesPage.logic.ts
@@ -3,6 +3,7 @@ import type { DependencyItem, MemoryStatusResult } from '@/context/ApiContext';
const INSTALLABLE_DEPENDENCIES = new Set([
'askill',
'avault',
+ 'model-hub-engine',
'show-runtime',
'memory-package',
'memory-runtime',
diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.ts b/ui/src/components/settings/SettingsDependenciesPage.test.ts
index 74e68d7be..c0ad8a3ed 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.test.ts
+++ b/ui/src/components/settings/SettingsDependenciesPage.test.ts
@@ -21,6 +21,7 @@ describe('dependencyHasInstallAction', () => {
expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'ready', action_class: 'repairable' })).toBe(true);
expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'ready' })).toBe(true);
expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'missing', action_class: 'repairable' })).toBe(true);
+ expect(dependencyHasInstallAction({ id: 'model-hub-engine', status: 'upgrade_required', action_class: 'repairable' })).toBe(true);
expect(dependencyHasInstallAction({ id: 'node', status: 'missing' })).toBe(false);
});
});
diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsx
index e103e729c..60825b08e 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx
@@ -24,7 +24,11 @@ vi.mock('@/context/ToastContext', () => ({
}));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => (
+ values?.version ? `${key}:${String(values.version)}` : key
+ ),
+ }),
}));
vi.mock('./SettingsPageShell', () => ({
@@ -108,6 +112,31 @@ describe('SettingsDependenciesPage Show Runtime status', () => {
});
});
+describe('SettingsDependenciesPage Model Hub engine', () => {
+ it('shows the installed and pinned CPA versions and offers the update action', async () => {
+ api.listDependencies.mockResolvedValue({
+ ok: true,
+ deps: [dependency({
+ id: 'model-hub-engine',
+ required: true,
+ installed: true,
+ version: 'v7.2.105',
+ latest_version: 'v7.2.149',
+ has_update: true,
+ status: 'upgrade_required',
+ action_class: 'repairable',
+ })],
+ });
+
+ renderPage();
+
+ expect(await screen.findByText('settings.dependencies.targetVersion:7.2.149')).toBeTruthy();
+ expect(screen.getByText('settings.dependencies.statusUpgradeRequired · v7.2.105')).toBeTruthy();
+ await userEvent.click(screen.getByRole('button', { name: 'settings.dependencies.update' }));
+ await waitFor(() => expect(api.installDependency).toHaveBeenCalledWith('model-hub-engine'));
+ });
+});
+
describe('SettingsDependenciesPage Memory runtime', () => {
it('routes repairable Python package bootstrap through its own dependency action', async () => {
api.listDependencies.mockResolvedValue({
diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsx
index fa25e8747..498083626 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx
@@ -9,6 +9,7 @@ import {
KeyRound,
LayoutDashboard,
Loader2,
+ Network,
RefreshCw,
ShieldCheck,
SquareTerminal,
@@ -30,8 +31,8 @@ import { errorMessage } from '@/lib/errorMessage';
// Mirrors design.pen "vibe-remote — Settings · Dependencies": one card per
// required local runtime (icon tile + name/REQUIRED + detail + status pill +
// action), reusing the Backends-page card shape. askill + the Show Page
-// runtime auto-install during `vibe runtime prepare`; this page surfaces their
-// status and offers manual re-check / install / repair. Backend CLIs are
+// runtime and CPA auto-install during `vibe runtime prepare`; this page surfaces
+// their status and offers manual re-check / install / repair. Backend CLIs are
// managed on the Backends tab — linked, not duplicated.
type DepMeta = { icon: LucideIcon; tileCls: string; iconCls: string };
@@ -39,6 +40,7 @@ type DepMeta = { icon: LucideIcon; tileCls: string; iconCls: string };
const DEP_META: Record<string, DepMeta> = {
askill: { icon: WandSparkles, tileCls: 'bg-mint-soft', iconCls: 'text-mint-ink' },
avault: { icon: KeyRound, tileCls: 'bg-gold-soft', iconCls: 'text-gold-ink' },
+ 'model-hub-engine': { icon: Network, tileCls: 'bg-mint-soft', iconCls: 'text-mint-ink' },
'show-runtime': { icon: LayoutDashboard, tileCls: 'bg-cyan-soft', iconCls: 'text-cyan-ink' },
'memory-package': { icon: Brain, tileCls: 'bg-gold-soft', iconCls: 'text-gold-ink' },
'memory-runtime': { icon: Brain, tileCls: 'bg-violet-soft', iconCls: 'text-violet-ink' },
@@ -127,7 +129,10 @@ export const SettingsDependenciesPage: React.FC = () => {
if (d.status === 'error') return t('settings.dependencies.statusError');
if (d.status === 'not_required') return t('settings.dependencies.statusNotRequired');
if (!d.installed) return t('settings.dependencies.statusMissing');
- if (d.status === 'upgrade_required') return t('settings.dependencies.statusUpgradeRequired');
+ if (d.status === 'upgrade_required') {
+ const word = t('settings.dependencies.statusUpgradeRequired');
+ return d.version ? `${word} · v${String(d.version).replace(/^v/i, '')}` : word;
+ }
const word = d.kind === 'node' ? t('settings.dependencies.statusDetected') : t('settings.dependencies.statusReady');
return d.version ? `${word} · v${String(d.version).replace(/^v/i, '')}` : word;
};
@@ -139,6 +144,19 @@ export const SettingsDependenciesPage: React.FC = () => {
return d.installed ? 'success' : 'destructive';
};
+ const actionText = (d: DependencyItem, installing: boolean): string => {
+ if (installing) return t('settings.dependencies.installing');
+ if (d.status === 'upgrade_required') return t('settings.dependencies.update');
+ if (d.id === 'model-hub-engine' && d.status === 'error') {
+ return t('settings.dependencies.repair');
+ }
+ if (!d.installed) return t('settings.dependencies.install');
+ if (d.id === 'show-runtime' || d.id === 'memory-runtime') {
+ return t('settings.dependencies.repair');
+ }
+ return t('settings.dependencies.reinstall');
+ };
+
return (
<SettingsPageShell
activeTab="dependencies"
@@ -185,7 +203,18 @@ export const SettingsDependenciesPage: React.FC = () => {
</Badge>
)
}
- detail={t(`settings.dependencies.items.${d.id}.detail`)}
+ detail={
+ <>
+ {t(`settings.dependencies.items.${d.id}.detail`)}
+ {d.id === 'model-hub-engine' && d.latest_version && (
+ <span className="mt-1 block font-mono text-[11px]">
+ {t('settings.dependencies.targetVersion', {
+ version: String(d.latest_version).replace(/^v/i, ''),
+ })}
+ </span>
+ )}
+ </>
+ }
actions={
<>
<Badge variant={statusVariant(d)} className="font-mono">
@@ -208,18 +237,12 @@ export const SettingsDependenciesPage: React.FC = () => {
>
{installing ? (
<Loader2 className="size-3.5 animate-spin" />
- ) : d.installed ? (
+ ) : d.installed || d.status === 'error' ? (
<RefreshCw className="size-3.5" />
) : (
<Download className="size-3.5" />
)}
- {installing
- ? t('settings.dependencies.installing')
- : d.installed
- ? d.id === 'show-runtime' || d.id === 'memory-runtime'
- ? t('settings.dependencies.repair')
- : t('settings.dependencies.reinstall')
- : t('settings.dependencies.install')}
+ {actionText(d, installing)}
</Button>
)}
</>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 599d86adf..201b89c76 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1887,6 +1887,8 @@ export type DependencyItem = {
required: boolean | null;
installed: boolean | null;
version: string | null;
+ latest_version?: string | null;
+ has_update?: boolean;
status: 'ready' | 'not_required' | 'missing' | 'upgrade_required' | 'unsupported' | 'error';
readiness?: 'ready' | 'not_required' | 'not_ready' | 'memory_requirement_unreadable';
action_class?: 'none' | 'repairable' | 'operator_only';
@@ -3521,7 +3523,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const jobId = typeof started?.job_id === 'string' ? started.job_id : null;
if (!jobId) return started;
- const deadline = Date.now() + 310_000;
+ // Covers the 120s controller readiness bound plus the 300s CPA RPC bound.
+ const deadline = Date.now() + 430_000;
let last = started;
while (Date.now() < deadline) {
await sleep(1000);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a0514e4ec..f04e0dfbb 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -389,8 +389,10 @@
"statusNotRequired": "Not required",
"statusUpgradeRequired": "Upgrade required",
"install": "Install",
+ "update": "Update",
"reinstall": "Reinstall",
"repair": "Repair",
+ "targetVersion": "Target v{{version}}",
"installing": "Installing…",
"installed": "{{name}} is ready.",
"installFailed": "Install failed.",
@@ -407,6 +409,10 @@
"label": "avault",
"detail": "Vault custody core — required for local Vault operations."
},
+ "model-hub-engine": {
+ "label": "Model Hub engine (CPA)",
+ "detail": "Pinned CLIProxyAPI runtime used by Model Hub."
+ },
"show-runtime": {
"label": "Show Page runtime",
"detail": "Renders visual Show Pages on your machine."
@@ -1957,6 +1963,35 @@
},
"errors": {
"runtime_install_inspection_failed": "Show Runtime status could not be inspected. No install or repair was attempted.",
+ "model_hub_engine_archive_checksum_mismatch": "The CPA download failed its integrity check. Retry the installation.",
+ "model_hub_engine_archive_download_failed": "CPA could not be downloaded. Check your network connection and retry.",
+ "model_hub_engine_archive_size_mismatch": "The CPA download size did not match this Avibe release.",
+ "model_hub_engine_archive_unavailable": "The CPA package for this Avibe release is unavailable.",
+ "model_hub_engine_archive_unavailable_offline": "CPA is not cached locally and Avibe is offline.",
+ "model_hub_engine_archive_url_unsupported": "This Avibe release has an unsupported CPA download URL.",
+ "model_hub_engine_binary_checksum_mismatch": "The installed CPA binary failed its integrity check.",
+ "model_hub_engine_binary_not_runnable": "The CPA binary cannot run on this machine.",
+ "model_hub_engine_binary_prepare_failed": "Avibe could not prepare the CPA binary.",
+ "model_hub_engine_candidate_validation_failed": "The downloaded CPA binary is incompatible with this Avibe release.",
+ "model_hub_engine_install_abandoned": "The interrupted CPA installation stopped before it finished.",
+ "model_hub_engine_install_already_running": "Another CPA installation is already running.",
+ "model_hub_engine_install_claim_failed": "Avibe could not reserve the CPA installation.",
+ "model_hub_engine_install_claim_invalid": "The interrupted CPA installation record is invalid. Retry the repair.",
+ "model_hub_engine_install_failed": "CPA installation failed.",
+ "model_hub_engine_install_inspection_failed": "Avibe could not verify the installed CPA runtime.",
+ "model_hub_engine_install_lock_failed": "Avibe could not lock the CPA runtime for installation.",
+ "model_hub_engine_install_lock_timeout": "CPA installation timed out waiting for another installer to finish.",
+ "model_hub_engine_install_missing_binary": "The CPA package did not contain the expected binary.",
+ "model_hub_engine_install_schedule_failed": "Avibe could not resume the interrupted CPA installation.",
+ "model_hub_engine_install_target_changed": "The CPA target changed during installation. Retry with the current Avibe version.",
+ "model_hub_engine_manifest_download_failed": "Avibe could not download the CPA release manifest.",
+ "model_hub_engine_manifest_invalid": "The CPA release manifest is invalid.",
+ "model_hub_engine_manifest_missing": "This Avibe release does not include a CPA release manifest.",
+ "model_hub_engine_manifest_unavailable": "The CPA release manifest is unavailable.",
+ "model_hub_engine_manifest_unavailable_offline": "The CPA release manifest is not cached locally and Avibe is offline.",
+ "model_hub_engine_manifest_url_unsupported": "The CPA manifest uses an unsupported URL.",
+ "model_hub_engine_platform_unsupported": "CPA is not available for this platform.",
+ "model_hub_engine_pointer_write_failed": "CPA was installed, but Avibe could not activate it.",
"task_owner_session_unavailable": "This Task's managing Session is no longer available. Create a replacement Task from an available Agent Session.",
"share_id_taken": "That custom link is already taken. Pick another.",
"invalid_share_id": "A custom link may use only 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1a993387f..c64823afe 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -389,8 +389,10 @@
"statusNotRequired": "无需安装",
"statusUpgradeRequired": "需要升级",
"install": "安装",
+ "update": "更新",
"reinstall": "重新安装",
"repair": "修复",
+ "targetVersion": "目标版本 v{{version}}",
"installing": "安装中…",
"installed": "{{name}} 已就绪。",
"installFailed": "安装失败。",
@@ -407,6 +409,10 @@
"label": "avault",
"detail": "Vault 托管核心 —— 本地 Vault 操作的必需依赖。"
},
+ "model-hub-engine": {
+ "label": "Model Hub 引擎(CPA)",
+ "detail": "Model Hub 使用的固定版本 CLIProxyAPI 运行时。"
+ },
"show-runtime": {
"label": "Show Page 运行时",
"detail": "在你本机渲染可视化 Show 页面。"
@@ -1957,6 +1963,35 @@
},
"errors": {
"runtime_install_inspection_failed": "无法检查 Show Runtime 状态。未执行安装或修复。",
+ "model_hub_engine_archive_checksum_mismatch": "CPA 下载文件未通过完整性校验,请重试安装。",
+ "model_hub_engine_archive_download_failed": "无法下载 CPA,请检查网络连接后重试。",
+ "model_hub_engine_archive_size_mismatch": "CPA 下载文件的大小与当前 Avibe 版本不匹配。",
+ "model_hub_engine_archive_unavailable": "当前 Avibe 版本所需的 CPA 安装包不可用。",
+ "model_hub_engine_archive_unavailable_offline": "本地没有缓存 CPA,且 Avibe 当前处于离线状态。",
+ "model_hub_engine_archive_url_unsupported": "当前 Avibe 版本配置了不受支持的 CPA 下载地址。",
+ "model_hub_engine_binary_checksum_mismatch": "已安装的 CPA 二进制文件未通过完整性校验。",
+ "model_hub_engine_binary_not_runnable": "CPA 二进制文件无法在此设备上运行。",
+ "model_hub_engine_binary_prepare_failed": "Avibe 无法准备 CPA 二进制文件。",
+ "model_hub_engine_candidate_validation_failed": "下载的 CPA 二进制文件与当前 Avibe 版本不兼容。",
+ "model_hub_engine_install_abandoned": "中断的 CPA 安装在完成前已停止。",
+ "model_hub_engine_install_already_running": "另一个 CPA 安装任务正在运行。",
+ "model_hub_engine_install_claim_failed": "Avibe 无法取得 CPA 安装任务的执行权。",
+ "model_hub_engine_install_claim_invalid": "中断的 CPA 安装记录无效,请重新修复。",
+ "model_hub_engine_install_failed": "CPA 安装失败。",
+ "model_hub_engine_install_inspection_failed": "Avibe 无法验证已安装的 CPA 运行时。",
+ "model_hub_engine_install_lock_failed": "Avibe 无法锁定 CPA 运行时以执行安装。",
+ "model_hub_engine_install_lock_timeout": "CPA 安装等待另一个安装任务结束时超时。",
+ "model_hub_engine_install_missing_binary": "CPA 安装包中缺少预期的二进制文件。",
+ "model_hub_engine_install_schedule_failed": "Avibe 无法恢复中断的 CPA 安装。",
+ "model_hub_engine_install_target_changed": "安装期间 CPA 目标版本发生变化,请使用当前 Avibe 版本重试。",
+ "model_hub_engine_manifest_download_failed": "Avibe 无法下载 CPA 发布清单。",
+ "model_hub_engine_manifest_invalid": "CPA 发布清单无效。",
+ "model_hub_engine_manifest_missing": "当前 Avibe 版本未包含 CPA 发布清单。",
+ "model_hub_engine_manifest_unavailable": "CPA 发布清单不可用。",
+ "model_hub_engine_manifest_unavailable_offline": "本地没有缓存 CPA 发布清单,且 Avibe 当前处于离线状态。",
+ "model_hub_engine_manifest_url_unsupported": "CPA 发布清单使用了不受支持的地址。",
+ "model_hub_engine_platform_unsupported": "当前平台不支持 CPA。",
+ "model_hub_engine_pointer_write_failed": "CPA 已安装,但 Avibe 无法将其激活。",
"task_owner_session_unavailable": "这个 Task 的管理 Session 已不可用。请从可用的 Agent Session 创建替代 Task。",
"share_id_taken": "这个自定义链接已被占用,换一个。",
"invalid_share_id": "自定义链接只能用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",
diff --git a/vibe/api.py b/vibe/api.py
index 002677b41..5d6a92c7b 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8676,6 +8676,7 @@ def reconcile_askill_auto_update() -> dict:
_ALLOWED_DEP_INSTALLS = {
"askill",
"avault",
+ "model-hub-engine",
"show-runtime",
"memory-package",
"memory-runtime",
@@ -8688,6 +8689,10 @@ _MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS = 3
_MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION = 1
_STARTUP_MEMORY_PACKAGE_RETRY_INTERVAL_SECONDS = 0.25
_STARTUP_MEMORY_PACKAGE_RETRY_TIMEOUT_SECONDS = 60.0
+_MODEL_HUB_CONTROLLER_POLL_INTERVAL_SECONDS = 0.05
+_MODEL_HUB_ENGINE_PLATFORM_UNSUPPORTED_REASON = (
+ "model_hub_engine_platform_unsupported"
+)
@dataclass(frozen=True)
@@ -9093,6 +9098,175 @@ def _memory_dependencies_status(*, offline: bool) -> tuple[dict, dict]:
)
+def _model_hub_engine_dependency_status() -> dict:
+ """Project the pinned CPA runtime into the shared dependency contract."""
+
+ try:
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+
+ manager = EngineRuntimeManager(offline=True)
+ managed = manager.status()
+ platform_supported = manager.supports_host_platform()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Could not inspect the Model Hub engine dependency", exc_info=True)
+ return {
+ "id": "model-hub-engine",
+ "kind": "runtime",
+ "required": True,
+ "installed": None,
+ "version": None,
+ "latest_version": None,
+ "has_update": False,
+ "status": "error",
+ "action_class": "operator_only",
+ "reason": "model_hub_engine_install_inspection_failed",
+ "inspection_error": {"kind": type(exc).__name__, "message": str(exc)},
+ }
+
+ installed = bool(managed.get("installed"))
+ selected_version = managed.get("selected_version")
+ matches_manifest = managed.get("matches_manifest")
+ reason = managed.get("reason")
+ if not platform_supported:
+ status = "unsupported"
+ action_class = "none"
+ elif not selected_version:
+ status = "error"
+ action_class = "operator_only"
+ elif managed.get("status") == "error":
+ status = "error"
+ action_class = "repairable"
+ elif installed and matches_manifest is True:
+ status = "ready"
+ action_class = "none"
+ elif installed:
+ status = "upgrade_required"
+ action_class = "repairable"
+ else:
+ status = "missing"
+ action_class = "repairable"
+ return {
+ "id": "model-hub-engine",
+ "kind": "runtime",
+ "required": platform_supported,
+ "installed": installed,
+ "version": managed.get("version"),
+ "latest_version": selected_version,
+ "has_update": bool(installed and matches_manifest is False),
+ "status": status,
+ "action_class": action_class,
+ "reason": reason,
+ "download_error": managed.get("download_error"),
+ }
+
+
+def _model_hub_controller_owns_engine(socket_path: Path) -> bool:
+ """Wait out controller startup before deciding direct-install ownership.
+
+ A missing dispatch socket means only that the endpoint is not ready. The
+ service pid reservation and instance lock identify the controller owner
+ before durable recovery completes and the socket is bound. If that owner
+ remains alive through the startup deadline, it retains ownership even when
+ the endpoint never becomes ready; returning true prevents a competing
+ direct install from mutating the runtime under it.
+ """
+
+ from vibe import runtime
+
+ owner_pid = runtime.resolve_service_owner_pid(include_starting=True)
+ if owner_pid is None:
+ return False
+
+ deadline = time.monotonic() + runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS
+ from vibe.internal_client import health_sync
+
+ while True:
+ owner_pid = runtime.resolve_service_owner_pid(include_starting=True)
+ if owner_pid is None:
+ return False
+ remaining = deadline - time.monotonic()
+ if health_sync(
+ socket_path,
+ timeout=min(1.0, max(0.05, remaining)),
+ ):
+ return True
+ if remaining <= 0:
+ return True
+ time.sleep(min(_MODEL_HUB_CONTROLLER_POLL_INTERVAL_SECONDS, remaining))
+
+
+def _model_hub_engine_ensure_result(result: dict) -> dict:
+ """Project an unsupported host as a successful non-applicable ensure."""
+
+ if result.get("reason") != _MODEL_HUB_ENGINE_PLATFORM_UNSUPPORTED_REASON:
+ return result
+ return {
+ **result,
+ "ok": True,
+ "installed": False,
+ "changed": False,
+ "skipped": True,
+ "status": "unsupported",
+ }
+
+
+def ensure_model_hub_engine_installed(
+ *,
+ force: bool = False,
+ offline: bool | None = None,
+) -> dict:
+ """Converge CPA to this Avibe release's pin without changing run intent."""
+
+ from core.handlers.model_hub import ModelHubError
+ from vibe.internal_client import default_socket_path
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+
+ def ensure_directly() -> dict:
+ return _model_hub_engine_ensure_result(
+ EngineRuntimeManager(offline=offline).ensure(force=force)
+ )
+
+ socket_path = default_socket_path().expanduser().resolve()
+ if not _model_hub_controller_owns_engine(socket_path):
+ return ensure_directly()
+
+ try:
+ from vibe.model_hub_client import ModelHubRemoteService
+
+ runtime = ModelHubRemoteService().ensure_runtime_dependency(
+ force=force,
+ offline=offline is True,
+ )
+ except ModelHubError as exc:
+ if exc.code == "runtime_platform_unsupported":
+ return _model_hub_engine_ensure_result(
+ {
+ "ok": False,
+ "installed": False,
+ "changed": False,
+ "reason": _MODEL_HUB_ENGINE_PLATFORM_UNSUPPORTED_REASON,
+ "message": exc.detail,
+ }
+ )
+ dependency_reason = exc.data.get("reason")
+ return {
+ "ok": False,
+ "reason": dependency_reason or exc.code,
+ "message": exc.detail,
+ }
+
+ status = runtime.get("status") if isinstance(runtime.get("status"), dict) else {}
+ installed = bool(status.get("verified"))
+ return {
+ "ok": installed,
+ "installed": installed,
+ "changed": bool(runtime.get("changed")),
+ "version": status.get("installed_version"),
+ "status": status,
+ "reason": None if installed else status.get("error_key") or "model_hub_engine_install_failed",
+ }
+
+
def dependencies_status(*, offline: bool = False) -> dict:
"""Status of the required local runtime dependencies for the Dependencies
settings page: askill, local managed runtimes, and the shared Node.js
@@ -9164,6 +9338,8 @@ def dependencies_status(*, offline: bool = False) -> dict:
}
)
+ deps.append(_model_hub_engine_dependency_status())
+
memory_package, memory_runtime = _memory_dependencies_status(offline=offline)
deps.extend((memory_package, memory_runtime))
@@ -9837,6 +10013,7 @@ def reconcile_startup_dependencies() -> dict:
"node": {"ok": False, "status": "unknown"},
"askill": {"ok": False, "status": "unknown"},
"avault": {"ok": False, "status": "unknown"},
+ "model_hub_engine": {"ok": False, "status": "unknown"},
"show_runtime": {"ok": False, "status": "unknown"},
"tmux": {"ok": False, "status": "unknown"},
}
@@ -9858,6 +10035,17 @@ def reconcile_startup_dependencies() -> dict:
avault = {"ok": False, "message": str(exc)}
result["avault"] = avault
+ try:
+ model_hub_engine = ensure_model_hub_engine_installed(force=False)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "Startup dependency reconcile failed to ensure the Model Hub engine: %s",
+ exc,
+ exc_info=True,
+ )
+ model_hub_engine = {"ok": False, "message": str(exc)}
+ result["model_hub_engine"] = model_hub_engine
+
try:
from core.show_runtime import ShowRuntimeAvailability, get_show_runtime_manager
@@ -9920,6 +10108,7 @@ def reconcile_startup_dependencies() -> dict:
bool(result["memory_package"].get("ok"))
and bool(result["askill"].get("ok"))
and bool(result["avault"].get("ok"))
+ and bool(result["model_hub_engine"].get("ok"))
and bool(result["show_runtime"].get("ok"))
)
return result
@@ -9970,6 +10159,8 @@ def start_dependency_install_job(dep: str) -> dict:
result = ensure_askill_installed(force=True)
elif dep == "avault":
result = ensure_avault_installed(force=True)
+ elif dep == "model-hub-engine":
+ result = ensure_model_hub_engine_installed(force=True)
elif dep == "show-runtime":
result = _prepare_show_runtime_job()
elif dep == "memory-package":
diff --git a/vibe/cli.py b/vibe/cli.py
index 27ecf9a30..442f527d1 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -129,6 +129,7 @@ DOCTOR_REPAIR_TARGETS = (
"stale-restart-state",
"askill",
"avault",
+ "model-hub-engine",
"git-runtime",
"memory-runtime",
"show-runtime",
@@ -143,6 +144,7 @@ DOCTOR_REPAIR_DRY_RUN_I18N_KEYS = {
"stale-restart-state": "doctor.repair.dryStaleRestart",
"askill": "doctor.repair.dryAskill",
"avault": "doctor.repair.dryAvault",
+ "model-hub-engine": "doctor.repair.dryModelHubEngine",
"git-runtime": "doctor.repair.dryGitRuntime",
"memory-runtime": "doctor.repair.dryMemoryRuntime",
"show-runtime": "doctor.repair.dryShowRuntime",
@@ -11160,6 +11162,7 @@ def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:
labels = {
"askill": "askill",
"avault": "avault",
+ "model-hub-engine": i18n_t("doctor.value.modelHubEngine", language),
"tmux": "tmux runtime",
"git-runtime": "Git Runtime",
"memory-runtime": i18n_t("doctor.value.memoryRuntime", language),
@@ -11168,6 +11171,7 @@ def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:
repair_targets = {
"askill": "askill",
"avault": "avault",
+ "model-hub-engine": "model-hub-engine",
"git-runtime": "git-runtime",
"memory-runtime": "memory-runtime",
"tmux": "tmux",
@@ -11285,6 +11289,10 @@ def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:
from core.tmux_runtime import TmuxRuntimeManager
probe = TmuxRuntimeManager().probe_archive_reachability()
+ elif deep and dependency_id == "model-hub-engine":
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+
+ probe = EngineRuntimeManager().probe_archive_reachability()
elif deep and dependency_id == "git-runtime":
from core.git_runtime import GitRuntimeManager
@@ -12953,6 +12961,14 @@ def _repair_avault(*, dry_run: bool = False) -> dict:
return _repair_managed_dependency("avault", api.ensure_avault_installed, dry_run=dry_run)
+def _repair_model_hub_engine(*, dry_run: bool = False) -> dict:
+ return _repair_managed_dependency(
+ "model-hub-engine",
+ api.ensure_model_hub_engine_installed,
+ dry_run=dry_run,
+ )
+
+
def _repair_tmux(*, dry_run: bool = False) -> dict:
from core.tmux_runtime import ensure_tmux_installed
@@ -13158,6 +13174,7 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: b
"stale-restart-state": _repair_stale_restart_state,
"askill": _repair_askill,
"avault": _repair_avault,
+ "model-hub-engine": _repair_model_hub_engine,
"git-runtime": _repair_git_runtime,
"memory-runtime": _repair_memory_runtime,
"show-runtime": _repair_show_runtime,
@@ -15177,8 +15194,13 @@ def cmd_runtime(args) -> int:
tmux = _ensure_tmux_during_prepare(offline=bool(offline), force=force)
git = _ensure_git_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),
+ force=force,
+ )
payload["askill"] = askill
payload["avault"] = avault
+ payload["model_hub_engine"] = model_hub_engine
payload["tmux"] = tmux
payload["git"] = git
install = payload.get("install") if isinstance(payload.get("install"), dict) else {}
@@ -15229,6 +15251,38 @@ def cmd_runtime(args) -> int:
print("avault installed." if avault.get("changed") else "avault ready.")
else:
print(f"avault not ready: {avault.get('message') or 'install failed'}", file=sys.stderr)
+ if model_hub_engine.get("skipped"):
+ print(
+ i18n_t(
+ "runtime.prepare.modelHubEngineSkipped",
+ language,
+ reason=model_hub_engine.get("reason") or "skipped",
+ )
+ )
+ elif model_hub_engine.get("ok"):
+ print(
+ i18n_t(
+ (
+ "runtime.prepare.modelHubEngineInstalled"
+ if model_hub_engine.get("changed")
+ else "runtime.prepare.modelHubEngineReady"
+ ),
+ language,
+ )
+ )
+ else:
+ print(
+ i18n_t(
+ "runtime.prepare.modelHubEngineNotReady",
+ language,
+ reason=(
+ model_hub_engine.get("message")
+ or model_hub_engine.get("reason")
+ or "install failed"
+ ),
+ ),
+ file=sys.stderr,
+ )
if tmux.get("skipped") or tmux.get("status") == "skipped":
print(f"tmux: skipped ({tmux.get('reason') or 'skipped'}).")
elif tmux.get("ok"):
@@ -15713,6 +15767,21 @@ def _ensure_avault_during_prepare(offline: bool = False, force: bool = False) ->
return {"ok": False, "message": str(exc)}
+def _ensure_model_hub_engine_during_prepare(
+ offline: bool = False,
+ force: bool = False,
+) -> dict:
+ """Converge CPA to the Avibe pin without making upgrade success depend on it."""
+
+ try:
+ return api.ensure_model_hub_engine_installed(
+ force=force,
+ offline=True if offline else None,
+ )
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
def cmd_restart():
"""Restart all services (stop + start)."""
return _cmd_restart_with_delay(0.0)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 2ebdeb3b5..5b7cdaa78 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1031,7 +1031,11 @@
"prepared": "Show Runtime prepared.",
"skipped": "Show Runtime preparation skipped: {reason}",
"failed": "Show Runtime preparation failed: {reason}",
- "unsupportedSource": "Show Runtime preparation failed: {reason}. Remove VIBE_SHOW_RUNTIME_SOURCE and use the packaged runtime, or set VIBE_SHOW_RUNTIME_BIN to a runtime you built."
+ "unsupportedSource": "Show Runtime preparation failed: {reason}. Remove VIBE_SHOW_RUNTIME_SOURCE and use the packaged runtime, or set VIBE_SHOW_RUNTIME_BIN to a runtime you built.",
+ "modelHubEngineSkipped": "Model Hub engine: skipped ({reason}).",
+ "modelHubEngineInstalled": "Model Hub engine installed.",
+ "modelHubEngineReady": "Model Hub engine ready.",
+ "modelHubEngineNotReady": "Model Hub engine not ready: {reason}"
},
"clean": {
"commandHelp": "Remove stale Show, Git, Memory, Model Hub, and tmux runtime installs and archives; exit nonzero if any cleanup fails.",
@@ -1090,6 +1094,7 @@
"unknownError": "unknown error",
"missing": "missing",
"memoryRuntime": "Memory Runtime",
+ "modelHubEngine": "Model Hub engine (CPA)",
"currentPlatform": "this platform",
"selectedDependencyUrl": "the selected dependency URL",
"tunnelStateHealthy": "healthy",
@@ -1436,6 +1441,7 @@
"dryStaleRestart": "Would remove stale restart metadata and refresh runtime status.",
"dryAskill": "Would install or refresh askill with the official installer.",
"dryAvault": "Would install or refresh the manifest-pinned avault release.",
+ "dryModelHubEngine": "Would install or refresh the Avibe-pinned Model Hub engine (CPA).",
"dryGitRuntime": "Would install or refresh the manifest-pinned Git Runtime.",
"dryShowRuntime": "Would prepare the manifest-pinned Show Runtime archive when it is missing or invalid.",
"dryTmux": "Would install or refresh the manifest-pinned tmux runtime."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index ca87d7ffb..382bac226 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1031,7 +1031,11 @@
"prepared": "Show Runtime 已准备完成。",
"skipped": "Show Runtime 准备已跳过:{reason}",
"failed": "Show Runtime 准备失败:{reason}",
- "unsupportedSource": "Show Runtime 准备失败:{reason}。请移除 VIBE_SHOW_RUNTIME_SOURCE 以使用随 Avibe 发布的运行时,或将 VIBE_SHOW_RUNTIME_BIN 指向你自行构建的运行时。"
+ "unsupportedSource": "Show Runtime 准备失败:{reason}。请移除 VIBE_SHOW_RUNTIME_SOURCE 以使用随 Avibe 发布的运行时,或将 VIBE_SHOW_RUNTIME_BIN 指向你自行构建的运行时。",
+ "modelHubEngineSkipped": "Model Hub 引擎:已跳过({reason})。",
+ "modelHubEngineInstalled": "Model Hub 引擎已安装。",
+ "modelHubEngineReady": "Model Hub 引擎已就绪。",
+ "modelHubEngineNotReady": "Model Hub 引擎尚未就绪:{reason}"
},
"clean": {
"commandHelp": "清理过期的 Show、Git、Memory、Model Hub 和 tmux 运行时安装与归档;任一清理失败时以非零状态退出。",
@@ -1090,6 +1094,7 @@
"unknownError": "未知错误",
"missing": "缺失",
"memoryRuntime": "Memory Runtime",
+ "modelHubEngine": "Model Hub 引擎(CPA)",
"currentPlatform": "当前平台",
"selectedDependencyUrl": "所选依赖 URL",
"tunnelStateHealthy": "健康",
@@ -1436,6 +1441,7 @@
"dryStaleRestart": "将移除过期重启元数据并刷新运行时状态。",
"dryAskill": "将使用官方安装器安装或刷新 askill。",
"dryAvault": "将安装或刷新清单固定的 avault 版本。",
+ "dryModelHubEngine": "将安装或刷新 Avibe 固定的 Model Hub 引擎(CPA)版本。",
"dryGitRuntime": "将安装或刷新清单固定的 Git Runtime。",
"dryShowRuntime": "当清单固定的 Show Runtime 归档缺失或无效时准备它。",
"dryTmux": "将安装或刷新清单固定的 tmux runtime。"
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 959e0d465..e14218f7a 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -1249,3 +1249,32 @@ async def health(socket_path: Optional[Path] = None) -> bool:
return resp.status_code == 200 and (resp.json() or {}).get("ok") is True
except Exception:
return False
+
+
+def health_sync(
+ socket_path: Optional[Path] = None,
+ *,
+ timeout: float = 2.0,
+) -> bool:
+ """Synchronously probe the controller health endpoint.
+
+ Dependency reconciliation runs in a worker thread and must distinguish a
+ connectable controller from a stale Unix-socket pathname left by a crashed
+ process.
+ """
+
+ try:
+ target = _verified_socket_path(socket_path)
+ except InternalServerUnavailable:
+ return False
+ transport = httpx.HTTPTransport(uds=str(target))
+ try:
+ with httpx.Client(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(timeout, connect=min(timeout, 1.0)),
+ ) as client:
+ resp = client.get("/internal/health")
+ return resp.status_code == 200 and (resp.json() or {}).get("ok") is True
+ except Exception:
+ return False
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 5c45ad451..11621ea61 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -12,7 +12,7 @@ from vibe.internal_client import default_socket_path
_TRANSPORT_ERRORS = (httpx.ConnectError, httpx.TimeoutException, OSError)
-_RPC_TIMEOUT_SECONDS = 300.0
+MODEL_HUB_RPC_TIMEOUT_SECONDS = 300.0
_REORDER_ORDER_UNSET = object()
@@ -47,7 +47,7 @@ def _rpc_sync(operation: str, payload: Optional[dict[str, Any]] = None) -> Any:
with httpx.Client(
transport=transport,
base_url="http://localhost",
- timeout=httpx.Timeout(_RPC_TIMEOUT_SECONDS, connect=2.0),
+ timeout=httpx.Timeout(MODEL_HUB_RPC_TIMEOUT_SECONDS, connect=2.0),
) as client:
response = client.post(
"/internal/model-hub",
@@ -67,7 +67,7 @@ async def _rpc(operation: str, payload: Optional[dict[str, Any]] = None) -> Any:
async with httpx.AsyncClient(
transport=transport,
base_url="http://localhost",
- timeout=httpx.Timeout(_RPC_TIMEOUT_SECONDS, connect=2.0),
+ timeout=httpx.Timeout(MODEL_HUB_RPC_TIMEOUT_SECONDS, connect=2.0),
) as client:
response = await client.post(
"/internal/model-hub",
@@ -296,6 +296,17 @@ class ModelHubRemoteService:
async def runtime_install(self) -> dict:
return await _rpc("runtime_install")
+ def ensure_runtime_dependency(
+ self,
+ *,
+ force: bool = False,
+ offline: bool = False,
+ ) -> dict:
+ return _rpc_sync(
+ "runtime_ensure_dependency",
+ {"force": force, "offline": offline},
+ )
+
async def runtime_start(self) -> dict:
return await _rpc("runtime_start")
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index e90b81db0..99aa09f60 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -17,6 +17,7 @@ import aiohttp
from config.v2_config import normalize_model_hub_base_url
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -43,7 +44,14 @@ from vibe.model_hub_runtime.client import (
upstream_api_url,
)
from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocol
-from vibe.model_hub_runtime.installer import InstallClaimTransition
+from vibe.model_hub_runtime.installer import (
+ INSTALL_ALREADY_RUNNING_REASON,
+ INSTALL_PLATFORM_UNSUPPORTED_REASON,
+ INSTALL_RECOVERY_ABANDONED_REASON,
+ INSTALL_RECOVERY_SCHEDULE_FAILED_REASON,
+ INSTALL_RECOVERY_TIMEOUT_REASON,
+ InstallClaimTransition,
+)
from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
from vibe.model_hub_runtime.supervisor import (
EngineSupervisor,
@@ -58,11 +66,6 @@ _OAUTH_ENDPOINTS = {
"codex": ("/codex-auth-url", "codex", "codex"),
}
_WEBUI_OAUTH_VENDORS = frozenset(_OAUTH_ENDPOINTS)
-_INSTALL_ALREADY_RUNNING_REASON = "model_hub_engine_install_already_running"
-_INSTALL_PLATFORM_UNSUPPORTED_REASON = "model_hub_engine_platform_unsupported"
-_INSTALL_RECOVERY_TIMEOUT_REASON = "model_hub_engine_install_lock_timeout"
-_INSTALL_RECOVERY_ABANDONED_REASON = "model_hub_engine_install_abandoned"
-_INSTALL_RECOVERY_SCHEDULE_FAILED_REASON = "model_hub_engine_install_schedule_failed"
_INSTALL_RECOVERY_WAIT_SECONDS = 30.0
_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS = 0.25
_INSTALL_RECOVERY_MAX_DELAY_SECONDS = 4.0
@@ -983,7 +986,7 @@ class CLIProxyEngineAdapter:
await self._abandon_install_claim(
generation=generation,
target=install_state["target"],
- reason=_INSTALL_RECOVERY_SCHEDULE_FAILED_REASON,
+ reason=INSTALL_RECOVERY_SCHEDULE_FAILED_REASON,
)
return await self.status()
@@ -1096,7 +1099,7 @@ class CLIProxyEngineAdapter:
except EngineUnavailableError as exc:
if (
expected_target is None
- or exc.reason != _INSTALL_ALREADY_RUNNING_REASON
+ or exc.reason != INSTALL_ALREADY_RUNNING_REASON
):
raise
if self._installation_stopping:
@@ -1119,7 +1122,7 @@ class CLIProxyEngineAdapter:
)
raise EngineUnavailableError(
"models.engine.install_failed",
- reason=_INSTALL_RECOVERY_TIMEOUT_REASON,
+ reason=INSTALL_RECOVERY_TIMEOUT_REASON,
)
await asyncio.sleep(min(recovery_delay, remaining))
recovery_delay = min(
@@ -1156,7 +1159,7 @@ class CLIProxyEngineAdapter:
)
except Exception: # noqa: BLE001
logger.exception("Failed to persist Model Hub runtime install failure")
- elif admission is not None and reason != _INSTALL_PLATFORM_UNSUPPORTED_REASON:
+ elif admission is not None and reason != INSTALL_PLATFORM_UNSUPPORTED_REASON:
try:
await asyncio.to_thread(
self.supervisor.installer.transition_install_claim,
@@ -1174,7 +1177,7 @@ class CLIProxyEngineAdapter:
*,
generation: str,
target: Mapping[str, str] | None,
- reason: str = _INSTALL_RECOVERY_ABANDONED_REASON,
+ reason: str = INSTALL_RECOVERY_ABANDONED_REASON,
) -> None:
self._install_owner_active = False
try:
@@ -1207,38 +1210,59 @@ class CLIProxyEngineAdapter:
@staticmethod
def _install_failure_reason(error: Exception) -> str:
if isinstance(error, RuntimePlatformUnsupportedError):
- return _INSTALL_PLATFORM_UNSUPPORTED_REASON
+ return INSTALL_PLATFORM_UNSUPPORTED_REASON
if isinstance(error, EngineUnavailableError) and error.reason:
return error.reason
return "model_hub_engine_install_failed"
@staticmethod
def _install_failure(reason: str) -> Exception:
- if reason == _INSTALL_PLATFORM_UNSUPPORTED_REASON:
+ if reason == INSTALL_PLATFORM_UNSUPPORTED_REASON:
return RuntimePlatformUnsupportedError()
return EngineUnavailableError("models.engine.install_failed", reason=reason)
async def ensure_installed(
self,
*,
+ force: bool = False,
+ offline: bool = False,
expected_target: Mapping[str, str] | None = None,
on_resolved: Callable[[dict[str, str]], None] | None = None,
- ) -> EngineStatus:
+ ) -> EngineEnsureResult:
async with self._routing_lock:
+ installer = (
+ self.supervisor.installer.offline_copy()
+ if offline
+ else self.supervisor.installer
+ )
if expected_target is None and on_resolved is None:
- install = await asyncio.to_thread(self.supervisor.installer.ensure)
+ if force:
+ install = await asyncio.to_thread(
+ installer.ensure,
+ force=True,
+ )
+ else:
+ install = await asyncio.to_thread(installer.ensure)
else:
+ ensure_kwargs: dict[str, Any] = {
+ "expected_target": expected_target,
+ "on_resolved": on_resolved,
+ }
+ if force:
+ ensure_kwargs["force"] = True
install = await asyncio.to_thread(
- self.supervisor.installer.ensure,
- expected_target=expected_target,
- on_resolved=on_resolved,
+ installer.ensure,
+ **ensure_kwargs,
)
if not install.get("ok"):
reason = str(install.get("reason") or "engine_install_failed")
raise self._install_failure(reason)
if install.get("changed"):
await asyncio.to_thread(self.supervisor.restart_if_running)
- return await self.status()
+ return EngineEnsureResult(
+ status=await self.status(),
+ changed=bool(install.get("changed")),
+ )
async def start(self) -> EngineStatus:
async with self._installation_lock:
diff --git a/vibe/model_hub_runtime/cliproxyapi_manifest.json b/vibe/model_hub_runtime/cliproxyapi_manifest.json
index 2697e3467..89a88e1f8 100644
--- a/vibe/model_hub_runtime/cliproxyapi_manifest.json
+++ b/vibe/model_hub_runtime/cliproxyapi_manifest.json
@@ -1,43 +1,44 @@
{
"schema_version": 1,
"name": "cliproxyapi",
- "version": "v7.2.105",
+ "version": "v7.2.149",
"source": "router-for-me/CLIProxyAPI",
- "source_url": "https://github.com/router-for-me/CLIProxyAPI/tree/4a2eb54dc6bf943196be4fb515e6a9407a4db143",
- "source_sha": "4a2eb54dc6bf943196be4fb515e6a9407a4db143",
- "release_tag": "v7.2.105",
+ "source_url": "https://github.com/router-for-me/CLIProxyAPI/tree/2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",
+ "source_sha": "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",
+ "release_tag": "v7.2.149",
+ "asset_release_tag": "model-hub-engine-v7.2.149-1",
"license": "MIT",
"assets": [
{
"platform": "darwin-arm64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_darwin_aarch64.tar.gz",
- "size_bytes": 18975205,
- "sha256": "641de855c486d373b3c69704bec55a5c5ce3efa523149cc9bd253f76040470d7",
- "binary_sha256": "e8da44e6bf9d85fe7b98a2843d33ff509156727222d6a1ad5dd1a79709849337",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_aarch64.tar.gz",
+ "size_bytes": 19723285,
+ "sha256": "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",
+ "binary_sha256": "048c0089aa53948af91249bb97f172b2392cce5968473a5a3dbb06f3d742c2e7",
"bin_path": "cli-proxy-api"
},
{
"platform": "darwin-x64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_darwin_amd64.tar.gz",
- "size_bytes": 20513376,
- "sha256": "c9332b8401cd54d357e7c66e88bce603fdb497701a7fa86ee2f82bb1aad846b9",
- "binary_sha256": "07a607965a40f782f63625c557eeeddb39b08e08b1a3057881bb13fe6e887109",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_amd64.tar.gz",
+ "size_bytes": 21334889,
+ "sha256": "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",
+ "binary_sha256": "05388e65f58493325aff1e2dfa33e727e7fa732b2d9eb651ec13315689e418e5",
"bin_path": "cli-proxy-api"
},
{
"platform": "linux-amd64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_linux_amd64.tar.gz",
- "size_bytes": 20558559,
- "sha256": "f432872815fe85ac4b0f83b5598253725eea70aae4c95025194cf558f6acef31",
- "binary_sha256": "2717656b33a0d76a7c02b451797341e8791f740a72d4e71577140886f42ba628",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_amd64.tar.gz",
+ "size_bytes": 21385633,
+ "sha256": "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",
+ "binary_sha256": "b0f163bfd94e8cd64895000662f26f255d2a72b5c3f5009a97e8dc91ed9b8107",
"bin_path": "cli-proxy-api"
},
{
"platform": "linux-arm64",
- "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.105/CLIProxyAPI_7.2.105_linux_aarch64.tar.gz",
- "size_bytes": 18559648,
- "sha256": "b72245cf1958251330eae9e17f1fc5a077f94146b2eea30e23ab5012c6059981",
- "binary_sha256": "8c389d565b8555d5788314e56258c64d675ff76bb9e32047d339088f2789b07e",
+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_aarch64.tar.gz",
+ "size_bytes": 19287559,
+ "sha256": "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",
+ "binary_sha256": "24799863d478579ec3eef5ccc83769f79df749a30282ce1e2063708a03826e5b",
"bin_path": "cli-proxy-api"
}
]
diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.py
index bec3f83ea..568f3cd09 100644
--- a/vibe/model_hub_runtime/installer.py
+++ b/vibe/model_hub_runtime/installer.py
@@ -6,11 +6,12 @@ import os
import re
import subprocess
import threading
+import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
from config import paths
from core import managed_runtime
@@ -41,7 +42,22 @@ _INSTALL_STATE_SUPPORTED_SCHEMA_VERSIONS = frozenset(
{*_INSTALL_STATE_RELEASED_SCHEMA_VERSIONS, _INSTALL_STATE_SCHEMA_VERSION}
)
_INSTALL_FAILURE_KEY = "settings.models.install.fail.detail"
-_INSTALL_CLAIM_INVALID_REASON = "model_hub_engine_install_claim_invalid"
+INSTALL_ALREADY_RUNNING_REASON = "model_hub_engine_install_already_running"
+INSTALL_PLATFORM_UNSUPPORTED_REASON = "model_hub_engine_platform_unsupported"
+INSTALL_CLAIM_INVALID_REASON = "model_hub_engine_install_claim_invalid"
+INSTALL_RECOVERY_TIMEOUT_REASON = "model_hub_engine_install_lock_timeout"
+INSTALL_RECOVERY_ABANDONED_REASON = "model_hub_engine_install_abandoned"
+INSTALL_RECOVERY_SCHEDULE_FAILED_REASON = "model_hub_engine_install_schedule_failed"
+INSTALL_INSPECTION_FAILED_REASON = "model_hub_engine_install_inspection_failed"
+_DEPENDENCY_LIFECYCLE_FAILURE_REASONS = frozenset(
+ {
+ INSTALL_CLAIM_INVALID_REASON,
+ INSTALL_RECOVERY_TIMEOUT_REASON,
+ INSTALL_RECOVERY_ABANDONED_REASON,
+ INSTALL_RECOVERY_SCHEDULE_FAILED_REASON,
+ INSTALL_INSPECTION_FAILED_REASON,
+ }
+)
_INSTALL_GENERATION_RE = re.compile(r"^[0-9a-f]{32}$")
_INSTALL_TARGET_FIELDS = frozenset(
{
@@ -112,6 +128,91 @@ class EngineRuntimeManager(ManagedRuntimeManager):
self._install_state_lock = threading.RLock()
self._install_state_override: object | _InstallStateOverride = _INSTALL_STATE_UNSET
+ def offline_copy(self) -> EngineRuntimeManager:
+ """Return the same runtime target with network access disabled."""
+
+ if self.offline:
+ return self
+ return EngineRuntimeManager(
+ runtime_dir=self.runtime_dir,
+ manifest_path=self.manifest_path,
+ manifest_url=self.manifest_url,
+ offline=True,
+ )
+
+ def ensure(
+ self,
+ *,
+ force: bool = False,
+ expected_target: Mapping[str, str] | None = None,
+ on_resolved: Callable[[dict[str, str]], None] | None = None,
+ validate_candidate: Callable[[Path], str | None] | None = None,
+ ) -> dict[str, Any]:
+ if on_resolved is not None or expected_target is not None:
+ return super().ensure(
+ force=force,
+ expected_target=expected_target,
+ on_resolved=on_resolved,
+ validate_candidate=validate_candidate,
+ )
+
+ generation = uuid.uuid4().hex
+ resolved_target: dict[str, str] | None = None
+ previous_state = self.install_state()
+
+ def capture_target(target: dict[str, str]) -> None:
+ nonlocal resolved_target
+ resolved_target = dict(target)
+
+ result = super().ensure(
+ force=force,
+ expected_target=expected_target,
+ on_resolved=capture_target,
+ validate_candidate=validate_candidate,
+ )
+ reason = str(result.get("reason") or "model_hub_engine_install_failed")
+ try:
+ if result.get("ok") and previous_state is not None:
+ self._clear_superseded_install_state(previous_state)
+ elif not result.get("ok") and reason not in {
+ INSTALL_ALREADY_RUNNING_REASON,
+ INSTALL_PLATFORM_UNSUPPORTED_REASON,
+ }:
+ self.transition_install_claim(
+ InstallClaimTransition.ADMISSION_FAILURE,
+ generation=generation,
+ target=resolved_target,
+ reason=reason,
+ )
+ except Exception: # noqa: BLE001
+ logger.exception("Failed to persist direct Model Hub runtime ensure outcome")
+ return result
+
+ def _clear_superseded_install_state(self, expected: Mapping[str, Any]) -> bool:
+ """Forget the exact pre-ensure state without disturbing a newer owner."""
+
+ with self._install_state_lock:
+ with MigrationFileLock(self.install_state_lock_path):
+ current = self._read_install_state_file()
+ if current != expected:
+ return False
+ try:
+ self.install_state_path.unlink()
+ except FileNotFoundError:
+ pass
+ self._install_state_override = _INSTALL_STATE_UNSET
+ return True
+
+ def status(self) -> dict[str, Any]:
+ managed = super().status()
+ install_state = self.install_state()
+ if install_state and install_state.get("state") == "not_installed":
+ reason = install_state.get("reason")
+ if isinstance(reason, str) and reason:
+ managed["status"] = "error"
+ managed["reason"] = reason
+ return managed
+
@property
def install_state_path(self) -> Path:
return self.runtime_dir / "install-state.json"
@@ -123,6 +224,17 @@ class EngineRuntimeManager(ManagedRuntimeManager):
def host_platform(self) -> str:
return self._normalize_engine_platform(managed_runtime.runtime_platform_tag())
+ def supports_host_platform(self) -> bool:
+ """Return whether Avibe's fixed CPA target has an asset for this host."""
+
+ if self.host_platform() not in _ENGINE_ASSET_PLATFORMS:
+ return False
+ manifest = self._load_manifest(allow_network=False)
+ if manifest is None:
+ return True
+ resolution, _archive = self._resolve_manifest_state(manifest)
+ return resolution is not ManifestResolution.UNSUPPORTED
+
@staticmethod
def _normalize_engine_platform(platform_tag: str) -> str:
return _ENGINE_PLATFORM_MAP.get(platform_tag, platform_tag)
@@ -132,6 +244,11 @@ class EngineRuntimeManager(ManagedRuntimeManager):
return self._base_install_failure_reasons()
+ def dependency_failure_reasons(self) -> frozenset[str]:
+ """Return every CPA failure token exposed by Dependencies."""
+
+ return self.install_failure_reasons() | _DEPENDENCY_LIFECYCLE_FAILURE_REASONS
+
def install_state(self) -> dict[str, Any] | None:
with self._install_state_lock:
durable = self._read_install_state_file()
@@ -204,7 +321,7 @@ class EngineRuntimeManager(ManagedRuntimeManager):
assert reason is not None
payload = self._failed_install_state(
generation=generation,
- target=None,
+ target=resolved_target,
reason=reason,
)
self._write_owned_failure(generation, payload)
@@ -271,7 +388,7 @@ class EngineRuntimeManager(ManagedRuntimeManager):
return self._failed_install_state(
generation=generation,
target=None,
- reason=_INSTALL_CLAIM_INVALID_REASON,
+ reason=INSTALL_CLAIM_INVALID_REASON,
)
payload["target"] = target
payload["generation"] = generation
@@ -468,7 +585,7 @@ class EngineRuntimeManager(ManagedRuntimeManager):
self._install_reason = "model_hub_engine_manifest_invalid"
return None
if resolution is ManifestResolution.UNSUPPORTED:
- self._install_reason = "model_hub_engine_platform_unsupported"
+ self._install_reason = INSTALL_PLATFORM_UNSUPPORTED_REASON
return None
return archive
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 377d98b8e..e43e15b4c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7907,6 +7907,7 @@ def backend_restart(name):
_ALLOWED_DEPENDENCIES = {
"askill",
"avault",
+ "model-hub-engine",
"show-runtime",
"memory-package",
"memory-runtime",
@@ -16271,19 +16272,29 @@ async def _reconcile_startup_dependencies_task() -> None:
logger.info("Startup dependencies reconciled in %sms", duration_ms)
else:
askill = result.get("askill") if isinstance(result.get("askill"), dict) else {}
+ model_hub_engine = (
+ result.get("model_hub_engine")
+ if isinstance(result.get("model_hub_engine"), dict)
+ else {}
+ )
memory_package = (
result.get("memory_package")
if isinstance(result.get("memory_package"), dict)
else {}
)
logger.warning(
- "Startup dependency reconcile completed with issues in %sms: memory_package=%s askill=%s show_runtime=%s",
+ "Startup dependency reconcile completed with issues in %sms: "
+ "memory_package=%s askill=%s model_hub_engine=%s show_runtime=%s",
duration_ms,
memory_package.get("message")
or memory_package.get("reason")
or memory_package.get("status")
or memory_package.get("ok"),
askill.get("message") or askill.get("status") or askill.get("ok"),
+ model_hub_engine.get("message")
+ or model_hub_engine.get("reason")
+ or model_hub_engine.get("status")
+ or model_hub_engine.get("ok"),
show_runtime.get("reason") or show_runtime.get("status") or show_runtime.get("ok"),
)
except Exception: