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): add managed engine runtime (#962)

Call White181b1500555c
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
new file mode 100644
index 000000000..3d238c5b4
--- /dev/null
+++ b/core/handlers/model_hub/adapter.py
@@ -0,0 +1,225 @@
+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.2 (2026-07-23 11:12 +08:00).
+
+v1.2 changelog (L1 implementation findings — credential & model lifecycle):
+- Secret provisioning path closed: ``provision_credential`` moves an API-key
+ secret (transient parameter, never logged, never persisted by L2) into the
+ ENGINE-OWNED store and returns the opaque ``credential_ref``;
+ ``revoke_credential`` releases it on source deletion. L2's config persists
+ refs only. Flow: provision → discover (probe) → persist Source → sync.
+- ``SourceBinding.model_ids`` added: the declared supply list (discovered +
+ manual custom entries) — required by the engine's generic/API-key config.
+- ``discover_models`` re-signed as a PROBE (vendor/protocol/base_url/
+ credential_ref) so discovery works BEFORE registration; it no longer takes
+ a ``source_id``.
+
+v1.1 changelog (L1 review findings, routed via orchestrator):
+- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes
+ the pre-created (pending) ``source_id``; a ``success`` ``OAuthFlowState``
+ carries the resulting opaque ``credential_ref``. Concurrent same-vendor
+ flows can never cross-bind.
+- Client binding made enforceable at the engine boundary:
+ ``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +
+ ``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters
+ first — defense in depth per README invariant 3).
+
+Canonical text: docs/plans/model-hub-contracts/adapter-interface.py (this file).
+Dual-copy rule: BOTH lane L1 and lane L2 copy this file VERBATIM to
+``core/handlers/model_hub/adapter.py`` in their branches (byte-identical, so the
+merge is a no-op). L2 owns the in-repo copy on master thereafter. Any change
+routes through the orchestrator and bumps the version line above.
+
+Seam semantics (from spike S1, binding):
+- L1 implements this protocol (engine facade). L1 must NOT classify errors,
+ retry, or fall back across sources — per-source invocation only; the
+ engine's internal fallback and usage feed stay disabled/bypassed.
+- L2 consumes it: picks exactly one source per call (priority resolution),
+ classifies ``RawCallOutcome`` into the canonical taxonomy, emits redacted
+ resolution events.
+- No credential material may appear in any field defined here.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, AsyncIterator, Mapping, Protocol, Sequence
+
+
+class EngineHealth(str, Enum):
+ OK = "ok"
+ DEGRADED = "degraded"
+ DOWN = "down"
+ NOT_INSTALLED = "not_installed"
+
+
+@dataclass(frozen=True)
+class EngineStatus:
+ health: EngineHealth
+ installed_version: str | None
+ verified: bool
+ listen_host: str # always "127.0.0.1"
+ listen_port: int | None
+ last_check_iso: str | None
+
+
+@dataclass(frozen=True)
+class SourceBinding:
+ """Engine-side registration of one hub-channel source (projection of config)."""
+
+ source_id: str
+ vendor: str
+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "openai_compatible"
+ base_url: str | None # None => vendor official default
+ credential_ref: str # opaque handle; never secret material
+ allowed_origins: tuple[str, ...] # agent names allowed to draw on this
+ # source. Empty tuple = unrestricted (api_key default). Subscription
+ # sources MUST be non-empty (README invariant 3); L2 populates, L1
+ # enforces as backstop.
+ model_ids: tuple[str, ...] # declared supply list (discovered + manual
+ # custom entries); required by the engine's generic/API-key config. Bare
+ # model ids, no provider prefix.
+
+
+class OriginNotAllowedError(Exception):
+ """Raised by the adapter when ``invoke(origin=...)`` violates the source's
+ ``allowed_origins``. A programming/policy error — never converted into a
+ ``RawCallOutcome`` and never triggers fallback."""
+
+
+class RawOutcomeKind(str, Enum):
+ SUCCESS = "success"
+ HTTP_ERROR = "http_error"
+ NETWORK_ERROR = "network_error"
+ TIMEOUT = "timeout"
+ PROTOCOL_ERROR = "protocol_error" # malformed/unparseable upstream response
+
+
+@dataclass(frozen=True)
+class RawCallOutcome:
+ """Uninterpreted per-call result. Classification is L2's job, not L1's."""
+
+ kind: RawOutcomeKind
+ http_status: int | None
+ error_code: str | None # upstream machine code if parseable, else None
+ redacted_message: str | None # L1 guarantees no credential material
+ stream_started: bool
+ model_id: str
+ source_id: str
+
+
+@dataclass(frozen=True)
+class OAuthFlowState:
+ """Engine-held (experimental hub-channel) subscription OAuth flow state.
+
+ Deterministic binding: the flow is created FOR a pre-existing pending
+ ``source_id`` and, on ``state == "success"``, carries the opaque
+ ``credential_ref`` of the auth record the engine created — L2 binds it to
+ that source and never guesses, even with concurrent same-vendor flows.
+ Mirrors ``oauth-flow.schema.json`` presentation semantics
+ (runtime-declared; UI renders from ``expects``).
+ """
+
+ flow_id: str
+ source_id: str
+ vendor: str
+ state: str # "starting" | "awaiting_action" | "verifying" | "success" | "failed" | "cancelled"
+ auth_url: str | None
+ device_code: str | None
+ expects: str # "none" | "paste_code" | "paste_callback_url"
+ instructions_key: str | None
+ error_key: str | None
+ expires_at_iso: str | None
+ credential_ref: str | None # set iff state == "success"
+
+
+class InvokeHandle(Protocol):
+ """One in-flight upstream call.
+
+ ``stream`` is None iff the call failed before the first byte (outcome is
+ then immediately awaitable). When ``stream`` is not None, the caller must
+ consume it; ``outcome()`` resolves after the stream ends and reports
+ ``stream_started=True`` — per spec §4.2 no transparent retry then.
+ """
+
+ @property
+ def stream(self) -> AsyncIterator[bytes] | None: ...
+
+ async def outcome(self) -> RawCallOutcome: ...
+
+
+class EngineAdapter(Protocol):
+ # --- lifecycle -------------------------------------------------------
+ async def ensure_installed(self) -> EngineStatus: ...
+
+ async def start(self) -> EngineStatus: ...
+
+ async def stop(self) -> None: ...
+
+ async def status(self) -> EngineStatus: ...
+
+ # --- gateway ---------------------------------------------------------
+ async def gateway_token(self) -> str:
+ """Local gateway token for backend injection (the ONLY credential
+ backends ever receive)."""
+ ...
+
+ # --- credential provisioning (engine-owned store) ---------------------
+ async def provision_credential(
+ self,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ """Store an API-key secret in the ENGINE-OWNED credential store and
+ return the opaque ``credential_ref``.
+
+ ``secret`` is transient: the adapter must never log it; L2 must never
+ persist it (config stores refs only). OAuth credentials never pass
+ through here — they are created engine-side by the OAuth flow and
+ surfaced via ``OAuthFlowState.credential_ref``."""
+ ...
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ """Release the stored credential (source deletion / key replacement)."""
+ ...
+
+ # --- source registry (L2 calls on every config change) ---------------
+ async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None: ...
+
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ ) -> Sequence[str]:
+ """PROBE the upstream for supplyable model ids. Works before any
+ registration (test-and-add flow: provision → discover → persist →
+ sync); does not require or create a source binding."""
+ ...
+
+ # --- engine-held subscription OAuth (experimental flag only) ----------
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState: ...
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
+ """``value`` per ``expects``: pasted code or callback URL."""
+ ...
+
+ async def cancel_oauth(self, flow_id: str) -> None: ...
+
+ # --- invocation primitive (exactly one source; no engine fallback) ---
+ async def invoke(
+ self,
+ source_id: str,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ origin: str,
+ ) -> InvokeHandle:
+ """``origin`` = requesting agent name ("claude"|"codex"|"opencode"|...).
+ Raises ``OriginNotAllowedError`` when the binding's ``allowed_origins``
+ excludes it (backstop; L2 must have filtered already)."""
+ ...
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index fb1b245f2..e23099d84 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -68,6 +68,9 @@ class ManagedRuntimeSpec:
version_field: str
default_bin_path: str
package: str = "vibe"
+ archives_field: str = "archives"
+ archive_size_field: str = "size"
+ platform_aliases: tuple[tuple[str, str], ...] = ()
@property
def metadata_filename(self) -> str:
@@ -235,7 +238,7 @@ class ManagedRuntimeManager:
def status(self) -> dict[str, Any]:
manifest = self._load_manifest(allow_network=False)
platform_tag = runtime_platform_tag()
- archive = manifest.archives.get(platform_tag) if manifest else None
+ archive = self._manifest_archive_for_platform(manifest) if manifest else None
install_dir = self._manifest_install_dir(manifest, archive) if manifest and archive else None
binary = self.resolve_binary() if manifest and archive else None
return {
@@ -423,15 +426,23 @@ class ManagedRuntimeManager:
if not isinstance(data, dict):
raise ValueError("manifest root must be an object")
archives: dict[str, ManagedRuntimeArchive] = {}
- for platform_tag, item in (data.get("archives") or {}).items():
+ raw_archives = data.get(self.spec.archives_field) or {}
+ if isinstance(raw_archives, dict):
+ archive_entries = raw_archives.items()
+ elif isinstance(raw_archives, list):
+ archive_entries = ((item.get("platform"), item) for item in raw_archives if isinstance(item, dict))
+ else:
+ raise ValueError("invalid archive collection")
+ for platform_tag, item in archive_entries:
if not isinstance(platform_tag, str) or not isinstance(item, dict):
raise ValueError("invalid archive entry")
- name = str(item["name"])
url = str(item["url"])
+ name = str(item.get("name") or Path(urllib.parse.urlparse(url).path).name)
sha256 = str(item["sha256"]).lower()
binary_sha256 = str(item["binary_sha256"]).lower()
bin_path = str(item.get("bin_path") or self.spec.default_bin_path)
- size = int(item["size"]) if item.get("size") is not None else None
+ raw_size = item.get(self.spec.archive_size_field)
+ size = int(raw_size) if raw_size is not None else None
if Path(name).name != name or not name:
raise ValueError("unsafe archive name")
if not _SHA256_RE.fullmatch(sha256):
@@ -474,7 +485,12 @@ class ManagedRuntimeManager:
self,
manifest: ManagedRuntimeManifest,
) -> ManagedRuntimeArchive | None:
- archive = manifest.archives.get(runtime_platform_tag())
+ platform_tag = runtime_platform_tag()
+ platform_aliases = dict(self.spec.platform_aliases)
+ archive = manifest.archives.get(platform_tag)
+ if archive is None:
+ alias = platform_aliases.get(platform_tag)
+ archive = manifest.archives.get(alias) if alias else None
if archive is None:
self._install_reason = self._reason("platform_unsupported")
return archive
diff --git a/pyproject.toml b/pyproject.toml
index 517b4d67c..246b6b725 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -98,6 +98,7 @@ artifacts = [
"vibe/show_runtime_manifest.json",
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
+ "vibe/model_hub_runtime/cliproxyapi_manifest.json",
]
[tool.hatch.build.targets.wheel]
@@ -120,6 +121,7 @@ include = [
"vibe/show_runtime_manifest.json",
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
+ "vibe/model_hub_runtime/cliproxyapi_manifest.json",
"README.md",
"LICENSE",
]
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
new file mode 100644
index 000000000..6f058eead
--- /dev/null
+++ b/tests/test_managed_runtime.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from core import managed_runtime
+from core.managed_runtime import ManagedRuntimeManager, ManagedRuntimeSpec
+
+
+class FixtureRuntimeManager(ManagedRuntimeManager):
+ def _binary_version(self, binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ return binary.read_text(encoding="utf-8").strip()
+
+
+ ("include_direct_platform", "expected_platform"),
+ [(False, "linux-amd64"), (True, "linux-x64")],
+)
+def test_list_asset_manifest_prefers_direct_platform_then_falls_back_to_alias(
+ tmp_path: Path,
+ monkeypatch,
+ include_direct_platform: bool,
+ expected_platform: str,
+) -> None:
+ archive = tmp_path / "fixture-linux_amd64.tar.gz"
+ binary_payload = b"v1\n"
+ with tarfile.open(archive, "w:gz") as tar:
+ member = tarfile.TarInfo("fixture")
+ member.mode = 0o755
+ member.size = len(binary_payload)
+ tar.addfile(member, io.BytesIO(binary_payload))
+
+ assets = [
+ {
+ "platform": "linux-amd64",
+ "url": archive.as_uri(),
+ "size_bytes": archive.stat().st_size,
+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),
+ "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),
+ }
+ ]
+ if include_direct_platform:
+ assets.append({**assets[0], "platform": "linux-x64"})
+ manifest = tmp_path / "manifest.json"
+ manifest.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "version": "v1",
+ "source": "example/fixture",
+ "assets": assets,
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-x64")
+ manager = FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture",
+ manifest_resource="unused.json",
+ version_field="version",
+ default_bin_path="fixture",
+ archives_field="assets",
+ archive_size_field="size_bytes",
+ platform_aliases=(("linux-x64", "linux-amd64"),),
+ ),
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest,
+ )
+
+ result = manager.ensure()
+
+ assert result["ok"] is True
+ assert result["changed"] is True
+ assert result["platform"] == expected_platform
+ assert Path(result["path"]).read_bytes() == binary_payload
+ assert manager.ensure()["changed"] is False
+ assert manager.status()["installed"] is True
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
new file mode 100644
index 000000000..65fe791be
--- /dev/null
+++ b/tests/test_model_hub_runtime.py
@@ -0,0 +1,1418 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import io
+import json
+import logging
+import subprocess
+import stat
+import sys
+import tarfile
+import threading
+import time
+from contextlib import contextmanager
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+
+import pytest
+import yaml
+
+from core import managed_runtime
+from core.handlers.model_hub.adapter import (
+ EngineHealth,
+ OriginNotAllowedError,
+ RawOutcomeKind,
+ SourceBinding,
+)
+from vibe.model_hub_runtime import client as client_module
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.client import EngineClient, EngineClientError
+from vibe.model_hub_runtime.config import write_engine_config
+from vibe.model_hub_runtime.installer import EngineRuntimeManager
+from vibe.model_hub_runtime.environment import engine_subprocess_environment
+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
+from vibe.model_hub_runtime.supervisor import EngineSupervisor, EngineUnavailableError
+
+
+def _write_fixture_archive(tmp_path: Path, *, version: str = "7.2.95") -> tuple[Path, bytes]:
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ binary = (
+ f'#!/bin/sh\nif [ "$1" = "--help" ]; then\n echo \'CLIProxyAPI Version: {version}, Commit: fixture\' >&2\nfi\n'
+ ).encode()
+ archive = tmp_path / "CLIProxyAPI_fixture.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ member = tarfile.TarInfo("cli-proxy-api")
+ member.mode = 0o755
+ member.size = len(binary)
+ tar.addfile(member, io.BytesIO(binary))
+ return archive, binary
+
+
+def _write_fixture_manifest(
+ tmp_path: Path,
+ archive: Path,
+ binary: bytes,
+ *,
+ archive_sha256: str | None = None,
+) -> Path:
+ platform_tag = managed_runtime.runtime_platform_tag()
+ manifest_platform = "linux-amd64" if platform_tag == "linux-x64" else platform_tag
+ manifest = tmp_path / "manifest.json"
+ manifest.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source": "router-for-me/CLIProxyAPI",
+ "source_url": "https://example.test/source",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "release_tag": "v7.2.95",
+ "license": "MIT",
+ "assets": [
+ {
+ "platform": manifest_platform,
+ "url": archive.as_uri(),
+ "size_bytes": archive.stat().st_size,
+ "sha256": archive_sha256 or hashlib.sha256(archive.read_bytes()).hexdigest(),
+ "binary_sha256": hashlib.sha256(binary).hexdigest(),
+ "bin_path": "cli-proxy-api",
+ }
+ ],
+ }
+ ),
+ encoding="utf-8",
+ )
+ return manifest
+
+
+def _binding(credential_ref: str, **overrides: object) -> SourceBinding:
+ payload = {
+ "source_id": "src_fixture123",
+ "vendor": "custom",
+ "protocol": "openai_compatible",
+ "base_url": "https://api.example.test/v1",
+ "credential_ref": credential_ref,
+ "allowed_origins": (),
+ "model_ids": ("model-a",),
+ }
+ payload.update(overrides)
+ return SourceBinding(**payload) # type: ignore[arg-type]
+
+
+def test_packaged_manifest_matches_frozen_runtime_dependency_values(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)
+
+ manifest = manager.contract_manifest()
+
+ assert manifest == {
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "assets": [
+ {
+ "platform": "darwin-arm64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_darwin_aarch64.tar.gz",
+ "size_bytes": 14384655,
+ "sha256": "c7ccc28b7db5d1799999a9e22725ccc6bd0e36d9aa023da6b52b7c1a71aad978",
+ },
+ {
+ "platform": "linux-amd64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_linux_amd64.tar.gz",
+ "size_bytes": 15401775,
+ "sha256": "826604e2dbf11913b0f373047f7bca1829eb2bab8a45d3a1916cc2534c7a9fd5",
+ },
+ ],
+ }
+
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "darwin-x64")
+ unsupported = EngineRuntimeManager(
+ runtime_dir=tmp_path / "unsupported-runtime",
+ offline=True,
+ ).ensure()
+ assert unsupported["ok"] is False
+ assert unsupported["reason"] == "model_hub_engine_platform_unsupported"
+
+
+def test_engine_installer_is_idempotent_and_rejects_tampered_archive(tmp_path: Path) -> None:
+ archive, binary = _write_fixture_archive(tmp_path / "good")
+ manifest = _write_fixture_manifest(tmp_path / "good", archive, binary)
+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ first = manager.ensure()
+ second = manager.ensure()
+
+ assert first["ok"] is True
+ assert first["changed"] is True
+ assert second["ok"] is True
+ assert second["changed"] is False
+ assert manager.status()["installed"] is True
+
+ bad_archive, bad_binary = _write_fixture_archive(tmp_path / "bad")
+ bad_manifest = _write_fixture_manifest(
+ tmp_path / "bad",
+ bad_archive,
+ bad_binary,
+ archive_sha256="1" * 64,
+ )
+ rejected = EngineRuntimeManager(
+ runtime_dir=tmp_path / "bad-runtime",
+ manifest_path=bad_manifest,
+ ).ensure()
+ assert rejected["ok"] is False
+ assert rejected["reason"] == "model_hub_engine_archive_checksum_mismatch"
+
+
+def test_engine_version_check_uses_minimal_environment(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured_env: dict[str, str] = {}
+
+ def run(*args, **kwargs):
+ captured_env.update(kwargs["env"])
+ return subprocess.CompletedProcess(args[0], 0, "", "CLIProxyAPI Version: 7.2.95")
+
+ monkeypatch.setenv("OPENAI_API_KEY", "unrelated-openai-secret")
+ monkeypatch.setenv("GITHUB_TOKEN", "unrelated-github-secret")
+ monkeypatch.setattr("vibe.model_hub_runtime.installer.subprocess.run", run)
+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)
+
+ assert manager._binary_version(tmp_path / "cli-proxy-api") == "v7.2.95"
+ assert "OPENAI_API_KEY" not in captured_env
+ assert "GITHUB_TOKEN" not in captured_env
+ assert captured_env == engine_subprocess_environment()
+
+
+def test_config_generation_is_private_and_never_logs_secrets(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level(logging.DEBUG)
+ store = EngineStateStore(tmp_path / "state")
+ instance_dir, runtime_secrets = store.prepare_instance("install-1")
+ credential_ref = store.store_api_key(
+ "upstream-secret-value",
+ base_url="https://api.example.test/v1",
+ )
+ responses_ref = store.store_api_key(
+ "responses-secret-value",
+ vendor="openai",
+ protocol="openai_responses",
+ )
+ store.sync_sources(
+ [
+ _binding(credential_ref),
+ _binding(
+ responses_ref,
+ source_id="src_responses1",
+ vendor="openai",
+ protocol="openai_responses",
+ base_url=None,
+ ),
+ ]
+ )
+ config_path = instance_dir / "config.yaml"
+
+ write_engine_config(
+ config_path,
+ host="127.0.0.1",
+ port=18231,
+ auth_dir=store.auth_dir,
+ runtime_secrets=runtime_secrets,
+ sources=store.list_sources(),
+ state_store=store,
+ )
+
+ payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert payload["host"] == "127.0.0.1"
+ assert payload["usage-statistics-enabled"] is False
+ assert payload["force-model-prefix"] is True
+ assert payload["request-retry"] == 0
+ assert payload["max-retry-credentials"] == 1
+ assert payload["plugins"]["enabled"] is False
+ assert payload["remote-management"]["allow-remote"] is False
+ assert payload["remote-management"]["disable-control-panel"] is True
+ assert payload["openai-compatibility"][0]["api-key-entries"][0]["api-key"] == ("upstream-secret-value")
+ assert payload["codex-api-key"][0]["base-url"] == "https://api.openai.com/v1"
+ assert stat.S_IMODE(config_path.stat().st_mode) == 0o600
+ assert stat.S_IMODE(store.auth_dir.stat().st_mode) == 0o700
+ credential_path = next((store.root / "credentials").iterdir())
+ assert stat.S_IMODE(credential_path.stat().st_mode) == 0o600
+ for secret in (
+ runtime_secrets.management_key,
+ runtime_secrets.gateway_token,
+ "upstream-secret-value",
+ "responses-secret-value",
+ ):
+ assert secret not in caplog.text
+
+ secrets_path = instance_dir / "runtime-secrets.json"
+ secrets_path.chmod(0o644)
+ with pytest.raises(EngineStateError, match="runtime secret permissions are unsafe"):
+ store.prepare_instance("install-1")
+
+
+def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ credential_ref = store.store_api_key(
+ "secret",
+ base_url="https://api.example.test/v1",
+ )
+
+ with pytest.raises(EngineStateError, match="invalid source base URL"):
+ store.sync_sources([_binding(credential_ref, base_url="https://user:[email protected]/v1")])
+
+ incomplete_ref = store.store_api_key("secret", base_url=None)
+ with pytest.raises(EngineStateError, match="requires a base URL"):
+ store.sync_sources([_binding(incomplete_ref, base_url=None)])
+
+ custom_anthropic_ref = store.store_api_key(
+ "secret",
+ vendor="custom",
+ protocol="anthropic",
+ base_url=None,
+ )
+ with pytest.raises(EngineStateError, match="requires a base URL"):
+ store.sync_sources(
+ [
+ _binding(
+ custom_anthropic_ref,
+ vendor="custom",
+ protocol="anthropic",
+ base_url=None,
+ )
+ ]
+ )
+
+ with pytest.raises(EngineStateError, match="at least one model"):
+ store.sync_sources([_binding(credential_ref, model_ids=())])
+
+ official_anthropic_ref = store.store_api_key(
+ "secret",
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url=None,
+ )
+ official = store.sync_sources(
+ [
+ _binding(
+ official_anthropic_ref,
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url=None,
+ )
+ ]
+ )
+ assert official[0].base_url is None
+
+ auth_file = store.auth_dir / "oauth.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o644)
+ with pytest.raises(EngineStateError, match="credential permissions are unsafe"):
+ store.audit_auth_permissions()
+ store.audit_auth_permissions(enforce=True)
+ assert stat.S_IMODE(auth_file.stat().st_mode) == 0o600
+
+
+def test_state_removes_secret_bearing_configs_on_upgrade_and_revocation(tmp_path: Path) -> None:
+ store = EngineStateStore(tmp_path / "state")
+ old_instance, _ = store.prepare_instance("install-old")
+ old_config = old_instance / "config.yaml"
+ old_config.write_text("api-key: old-secret\n", encoding="utf-8")
+ old_config.chmod(0o600)
+
+ current_instance, _ = store.prepare_instance("install-current")
+ assert not old_instance.exists()
+
+ current_config = current_instance / "config.yaml"
+ current_config.write_text("api-key: current-secret\n", encoding="utf-8")
+ current_config.chmod(0o600)
+ store.clear_runtime_configs()
+ assert not current_config.exists()
+
+
+def test_oauth_source_bindings_are_scoped_and_follow_reauthentication(tmp_path: Path) -> None:
+ store = EngineStateStore(tmp_path / "state")
+ credentials_dir = store.root / "credentials"
+ credentials_dir.mkdir(parents=True, mode=0o700)
+ interrupted_write = credentials_dir / ".cred_interrupted.json.temporary"
+ interrupted_write.write_text("{}", encoding="utf-8")
+ interrupted_write.chmod(0o600)
+ first_ref = store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ "claude-first.json",
+ )
+ assert stat.S_IMODE(store.root.stat().st_mode) == 0o700
+ binding = _binding(
+ first_ref,
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url=None,
+ allowed_origins=("claude",),
+ )
+
+ with pytest.raises(EngineStateError, match="requires at least one allowed origin"):
+ store.sync_sources([SourceBinding(**{**binding.__dict__, "allowed_origins": ()})])
+ with pytest.raises(EngineStateError, match="does not match"):
+ store.sync_sources([SourceBinding(**{**binding.__dict__, "source_id": "src_other1234"})])
+ with pytest.raises(EngineStateError, match="does not match"):
+ store.sync_sources(
+ [
+ SourceBinding(
+ **{
+ **binding.__dict__,
+ "vendor": "openai",
+ "base_url": "https://api.openai.com/v1",
+ }
+ )
+ ]
+ )
+
+ first = store.sync_sources([binding])[0]
+ assert first.prefix == store.credential_metadata(first_ref)["prefix"]
+
+ replacement_ref = store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ "claude-replacement.json",
+ )
+ replacement = store.sync_sources([SourceBinding(**{**binding.__dict__, "credential_ref": replacement_ref})])[0]
+ assert replacement.prefix == store.credential_metadata(replacement_ref)["prefix"]
+ assert replacement.prefix != first.prefix
+
+ assert (
+ store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ "claude-replacement.json",
+ )
+ == replacement_ref
+ )
+ with pytest.raises(EngineStateError, match="already bound to another source"):
+ store.bind_oauth_credential(
+ "src_other1234",
+ "anthropic",
+ "claude-replacement.json",
+ )
+
+
+@contextmanager
+def _models_endpoint():
+ class Handler(BaseHTTPRequestHandler):
+ authorization: str | None = None
+
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ Handler.authorization = self.headers.get("Authorization")
+ body = json.dumps({"data": [{"id": "model-a"}, {"id": "model-b"}]}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ midpoint = len(body) // 2
+ self.wfile.write(body[:midpoint])
+ self.wfile.flush()
+ time.sleep(0.05)
+ self.wfile.write(body[midpoint:])
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ host, port = server.server_address
+ yield f"http://{host}:{port}/v1", Handler
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+
+def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> None:
+ class Supervisor:
+ def __init__(self, store: EngineStateStore) -> None:
+ self.state_store = store
+
+ def invalidate_configs(self) -> None:
+ self.state_store.clear_runtime_configs()
+
+ async def run(base_url: str, handler) -> None:
+ store = EngineStateStore(tmp_path / "state")
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+ credential_ref = await adapter.provision_credential(
+ "custom",
+ "openai_compatible",
+ "probe-secret",
+ base_url,
+ )
+
+ models = await adapter.discover_models(
+ "custom",
+ "openai_compatible",
+ f"{base_url}/",
+ credential_ref,
+ )
+
+ assert models == ("model-a", "model-b")
+ assert handler.authorization == "Bearer probe-secret"
+ with pytest.raises(EngineStateError, match="does not match"):
+ await adapter.discover_models(
+ "custom",
+ "openai_compatible",
+ "https://different.example/v1",
+ credential_ref,
+ )
+ unsafe_instance = store.root / "instances" / "unsafe-entry"
+ unsafe_instance.parent.mkdir(parents=True, exist_ok=True)
+ unsafe_instance.write_text("not a directory", encoding="utf-8")
+ with pytest.raises(EngineStateError, match="instance directory is unsafe"):
+ await adapter.revoke_credential(credential_ref)
+ assert store.credential_metadata(credential_ref)["value"] == "probe-secret"
+ unsafe_instance.unlink()
+ await adapter.revoke_credential(credential_ref)
+ with pytest.raises(EngineStateError, match="unavailable"):
+ store.credential_metadata(credential_ref)
+
+ with _models_endpoint() as (base_url, handler):
+ asyncio.run(run(base_url, handler))
+
+
+def _write_mock_engine(path: Path) -> None:
+ script = f"""#!{sys.executable}
+import json
+import sys
+import time
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+import yaml
+
+config_path = sys.argv[sys.argv.index('-config') + 1]
+with open(config_path, encoding='utf-8') as handle:
+ config = yaml.safe_load(handle)
+gateway = config['api-keys'][0]
+management = config['remote-management']['secret-key']
+
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _json(self, status, payload):
+ body = json.dumps(payload).encode()
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ if self.path == '/v1/models' and self.headers.get('Authorization') == f'Bearer {{gateway}}':
+ self._json(200, {{'object': 'list', 'data': []}})
+ return
+ if self.path == '/v0/management/config' and self.headers.get('X-Management-Key') == management:
+ self._json(200, {{'host': config['host']}})
+ return
+ if self.path.startswith('/v0/management/auth-files/models'):
+ self._json(200, {{'models': [{{'id': 'model-a'}}]}})
+ return
+ self._json(401, {{'error': {{'type': 'unauthorized'}}}})
+
+ def do_POST(self):
+ length = int(self.headers.get('Content-Length', '0'))
+ payload = json.loads(self.rfile.read(length))
+ if self.headers.get('Authorization') != f'Bearer {{gateway}}':
+ self._json(401, {{'error': {{'type': 'unauthorized'}}}})
+ return
+ if payload['model'].endswith('/rate-limited'):
+ self._json(429, {{'error': {{'type': 'quota_exceeded', 'message': 'upstream-secret'}}}})
+ return
+ if payload['model'].endswith('/unsafe-error-code'):
+ self._json(400, {{'error': {{'type': 'invalid_key_upstream-secret'}}}})
+ return
+ if payload['model'].endswith('/redirected'):
+ self.send_response(307)
+ self.send_header('Location', 'https://example.test/credential-leak')
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+ return
+ if payload['model'].endswith('/stalled-first-byte'):
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', '1')
+ self.end_headers()
+ self.wfile.flush()
+ time.sleep(1)
+ return
+ if payload['model'].endswith('/stalled-error-body'):
+ self.send_response(429)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', '1')
+ self.end_headers()
+ self.wfile.flush()
+ time.sleep(1)
+ return
+ if payload['model'].endswith('/stalled-non-stream'):
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', '2')
+ self.end_headers()
+ self.wfile.write(b'{{')
+ self.wfile.flush()
+ time.sleep(1)
+ return
+ if payload['model'].endswith('/invalid-json'):
+ body = b'not-json'
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ if payload['model'].endswith('/oversized-non-stream'):
+ body = b'{{"payload":"too-large"}}'
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ if payload['model'].endswith('/slow-stream'):
+ first = b'data: {{"type":"content_block_delta"}}\\n\\n'
+ second = b'data: {{"type":"message_stop"}}\\n\\n'
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.send_header('Content-Length', str(len(first) + len(second)))
+ self.end_headers()
+ self.wfile.write(first)
+ self.wfile.flush()
+ time.sleep(0.15)
+ self.wfile.write(second)
+ return
+ if payload.get('stream'):
+ body = b'data: {{"type":"message_stop"}}\\n\\n'
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ self._json(200, {{'id': 'response-1', 'model': payload['model']}})
+
+HTTPServer((config['host'], config['port']), Handler).serve_forever()
+"""
+ path.write_text(script, encoding="utf-8")
+ path.chmod(0o755)
+
+
+class _FixtureInstaller:
+ def __init__(self, binary: Path, install_dir: Path) -> None:
+ self.binary = binary
+ self.install_dir = install_dir
+ self.changed = True
+
+ def ensure(self):
+ result = {
+ "ok": True,
+ "path": str(self.binary),
+ "install_dir": str(self.install_dir),
+ "version": "v7.2.95",
+ "changed": self.changed,
+ }
+ self.changed = False
+ return result
+
+ def status(self):
+ return {"installed": True, "version": "v7.2.95"}
+
+ def contract_manifest(self):
+ return {
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source_sha": "f" * 40,
+ "assets": [],
+ }
+
+
+def _fixture_supervisor(
+ tmp_path: Path,
+ *,
+ process_factory=subprocess.Popen,
+) -> tuple[EngineSupervisor, EngineStateStore]:
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ binary = tmp_path / "mock-engine"
+ _write_mock_engine(binary)
+ installer = _FixtureInstaller(binary, tmp_path / "versions" / "install-1")
+ store = EngineStateStore(tmp_path / "state")
+ return (
+ EngineSupervisor(
+ installer=installer,
+ state_store=store,
+ startup_timeout=5,
+ process_factory=process_factory,
+ ),
+ store,
+ )
+
+
+def test_supervisor_starts_checks_health_and_stops_mock_engine(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured_env: dict[str, str] = {}
+
+ def spawn(*args, **kwargs):
+ captured_env.update(kwargs["env"])
+ return subprocess.Popen(*args, **kwargs)
+
+ monkeypatch.setenv("MANAGEMENT_PASSWORD", "untrusted-management-secret")
+ monkeypatch.setenv("OPENAI_API_KEY", "unrelated-openai-secret")
+ monkeypatch.setenv("GITHUB_TOKEN", "unrelated-github-secret")
+ monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:1")
+ monkeypatch.setenv("NO_PROXY", "")
+ monkeypatch.setenv("PATH", "/usr/bin:/bin")
+ supervisor, store = _fixture_supervisor(tmp_path, process_factory=spawn)
+
+ first = supervisor.ensure_running()
+ assert first.base_url.startswith("http://127.0.0.1:")
+ assert "MANAGEMENT_PASSWORD" not in captured_env
+ assert "OPENAI_API_KEY" not in captured_env
+ assert "GITHUB_TOKEN" not in captured_env
+ assert "HTTP_PROXY" not in captured_env
+ assert captured_env == engine_subprocess_environment()
+ assert supervisor.status()["status"]["health"] == "ok"
+ config_path = store.root / "instances" / "install-1" / "config.yaml"
+ first_config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert first_config["api-keys"] == [first.gateway_token]
+ assert first_config["remote-management"]["secret-key"] == first.management_key
+
+ supervisor.stop()
+ assert supervisor.status()["status"]["health"] == "down"
+ second = supervisor.ensure_running()
+ assert second.gateway_token == first.gateway_token
+ assert second.management_key == first.management_key
+ supervisor.stop()
+
+
+def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> None:
+ async def run() -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)
+ credential_ref = await adapter.provision_credential(
+ "custom",
+ "openai_compatible",
+ "upstream-secret",
+ "https://api.example.test/v1",
+ )
+ await adapter.sync_sources(
+ [
+ _binding(
+ credential_ref,
+ allowed_origins=("codex",),
+ model_ids=("model-a", "rate-limited", "unsafe-error-code", "redirected"),
+ )
+ ]
+ )
+
+ started = await adapter.start()
+ assert started.health is EngineHealth.OK
+ assert started.listen_host == "127.0.0.1"
+ assert await adapter.gateway_token()
+
+ with pytest.raises(OriginNotAllowedError):
+ await adapter.invoke("src_fixture123", "model-a", {}, False, "claude")
+
+ handle = await adapter.invoke("src_fixture123", "model-a", {}, False, "codex")
+ assert handle.stream is not None
+ payload = b"".join([chunk async for chunk in handle.stream])
+ assert json.loads(payload)["model"].endswith("/model-a")
+ outcome = await handle.outcome()
+ assert outcome.kind is RawOutcomeKind.SUCCESS
+ assert outcome.stream_started is True
+
+ failed = await adapter.invoke("src_fixture123", "rate-limited", {}, False, "codex")
+ assert failed.stream is None
+ failure = await failed.outcome()
+ assert failure.kind is RawOutcomeKind.HTTP_ERROR
+ assert failure.http_status == 429
+ assert failure.error_code == "quota_exceeded"
+ assert "upstream-secret" not in (failure.redacted_message or "")
+ unsafe_code = await adapter.invoke("src_fixture123", "unsafe-error-code", {}, False, "codex")
+ assert (await unsafe_code.outcome()).error_code is None
+ redirected = await adapter.invoke("src_fixture123", "redirected", {}, False, "codex")
+ redirect_outcome = await redirected.outcome()
+ assert redirect_outcome.kind is RawOutcomeKind.HTTP_ERROR
+ assert redirect_outcome.http_status == 307
+ await adapter.stop()
+ with pytest.raises(EngineStateError, match="still bound"):
+ await adapter.revoke_credential(credential_ref)
+ await adapter.sync_sources([])
+ await adapter.revoke_credential(credential_ref)
+
+ asyncio.run(run())
+
+
+def test_adapter_restores_source_projection_when_restart_fails(tmp_path: Path) -> None:
+ class Supervisor:
+ def __init__(self) -> None:
+ self.restore_calls = 0
+
+ def client_if_running(self):
+ return object()
+
+ def restart_if_running(self) -> None:
+ raise EngineUnavailableError("models.engine.health_failed")
+
+ def ensure_running(self):
+ self.restore_calls += 1
+ return object()
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ old_ref = store.store_api_key(
+ "old-secret",
+ base_url="https://old.example.test/v1",
+ )
+ new_ref = store.store_api_key(
+ "new-secret",
+ base_url="https://new.example.test/v1",
+ )
+ old_binding = _binding(old_ref, base_url="https://old.example.test/v1")
+ store.sync_sources([old_binding])
+ supervisor = Supervisor()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=supervisor, # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ with pytest.raises(EngineUnavailableError, match="models.engine.health_failed"):
+ await adapter.sync_sources(
+ [_binding(new_ref, base_url="https://new.example.test/v1")]
+ )
+
+ restored = store.get_source("src_fixture123")
+ assert restored is not None
+ assert restored.credential_ref == old_ref
+ assert supervisor.restore_calls == 1
+
+ asyncio.run(run())
+
+
+def test_adapter_serializes_source_sync_with_new_invocations(tmp_path: Path) -> None:
+ restart_started = threading.Event()
+ allow_restart = threading.Event()
+ invoked_refs: list[str] = []
+
+ class Client:
+ async def invoke(self, source, model_id, request, *, stream):
+ invoked_refs.append(source.credential_ref)
+ return object()
+
+ class Supervisor:
+ def __init__(self) -> None:
+ self._client = Client()
+
+ def client_if_running(self):
+ return self._client
+
+ def restart_if_running(self) -> None:
+ restart_started.set()
+ assert allow_restart.wait(timeout=2)
+
+ def client(self):
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ old_ref = store.store_api_key(
+ "old-secret",
+ base_url="https://old.example.test/v1",
+ )
+ new_ref = store.store_api_key(
+ "new-secret",
+ base_url="https://new.example.test/v1",
+ )
+ store.sync_sources([_binding(old_ref, base_url="https://old.example.test/v1")])
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ sync_task = asyncio.create_task(
+ adapter.sync_sources([_binding(new_ref, base_url="https://new.example.test/v1")])
+ )
+ assert await asyncio.to_thread(restart_started.wait, 2)
+ invoke_task = asyncio.create_task(
+ adapter.invoke("src_fixture123", "model-a", {}, False, "codex")
+ )
+ await asyncio.sleep(0.05)
+ assert not invoke_task.done()
+
+ allow_restart.set()
+ await sync_task
+ await invoke_task
+ assert invoked_refs == [new_ref]
+
+ asyncio.run(run())
+
+
+def test_adapter_engine_unavailable_does_not_forge_an_upstream_error_code(tmp_path: Path) -> None:
+ class Supervisor:
+ def client(self):
+ raise EngineUnavailableError("models.engine.health_failed")
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ store.sync_sources([_binding(credential_ref)])
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ handle = await adapter.invoke("src_fixture123", "model-a", {}, False, "codex")
+ outcome = await handle.outcome()
+
+ assert outcome.kind is RawOutcomeKind.NETWORK_ERROR
+ assert outcome.error_code is None
+ assert outcome.redacted_message is None
+
+ asyncio.run(run())
+
+
[email protected](("changed", "expected_restarts"), [(False, 0), (True, 1)])
+def test_adapter_applies_changed_install_to_running_engine(
+ tmp_path: Path,
+ changed: bool,
+ expected_restarts: int,
+) -> None:
+ class Installer:
+ def ensure(self):
+ return {"ok": True, "changed": changed}
+
+ class Supervisor:
+ def __init__(self) -> None:
+ self.installer = Installer()
+ self.restarts = 0
+
+ def restart_if_running(self) -> None:
+ self.restarts += 1
+
+ def status(self):
+ return {
+ "status": {
+ "health": "down",
+ "installed_version": "v7.2.95",
+ "verified": True,
+ "listening": None,
+ "last_check": None,
+ }
+ }
+
+ async def run() -> None:
+ supervisor = Supervisor()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=supervisor, # type: ignore[arg-type]
+ state_store=EngineStateStore(tmp_path / "state"),
+ )
+
+ status = await adapter.ensure_installed()
+
+ assert status.installed_version == "v7.2.95"
+ assert status.verified is True
+ assert supervisor.restarts == expected_restarts
+
+ asyncio.run(run())
+
+
+def test_adapter_stream_outcome_commits_after_first_byte(tmp_path: Path) -> None:
+ async def run() -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)
+ credential_ref = await adapter.provision_credential(
+ "custom",
+ "openai_compatible",
+ "upstream-secret",
+ "https://api.example.test/v1",
+ )
+ await adapter.sync_sources([_binding(credential_ref)])
+ await adapter.start()
+
+ handle = await adapter.invoke("src_fixture123", "model-a", {}, True, "codex")
+ assert handle.stream is not None
+ body = b"".join([chunk async for chunk in handle.stream])
+ assert body.startswith(b"data:")
+ outcome = await handle.outcome()
+ assert outcome.kind is RawOutcomeKind.SUCCESS
+ assert outcome.stream_started is True
+ await adapter.stop()
+
+ asyncio.run(run())
+
+
+def test_engine_client_does_not_apply_a_total_turn_timeout(tmp_path: Path) -> None:
+ async def run() -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ store.sync_sources([_binding(credential_ref, model_ids=("slow-stream",))])
+ connection = supervisor.ensure_running()
+ source = store.get_source("src_fixture123")
+ assert source is not None
+
+ handle = await EngineClient(connection, timeout=0.05).invoke(
+ source,
+ "slow-stream",
+ {},
+ stream=True,
+ )
+ assert handle.stream is not None
+ body = b"".join([chunk async for chunk in handle.stream])
+ assert b"content_block_delta" in body
+ assert b"message_stop" in body
+ assert (await handle.outcome()).kind is RawOutcomeKind.SUCCESS
+ supervisor.stop()
+
+ asyncio.run(run())
+
+
+ ("model_id", "stream", "expected_kind", "expected_status", "stream_started"),
+ [
+ ("stalled-first-byte", True, RawOutcomeKind.TIMEOUT, None, False),
+ ("stalled-error-body", True, RawOutcomeKind.HTTP_ERROR, 429, False),
+ ("stalled-non-stream", False, RawOutcomeKind.TIMEOUT, 200, True),
+ ],
+)
+def test_engine_client_times_out_before_completion(
+ tmp_path: Path,
+ model_id: str,
+ stream: bool,
+ expected_kind: RawOutcomeKind,
+ expected_status: int | None,
+ stream_started: bool,
+) -> None:
+ async def run() -> None:
+ supervisor, store = _fixture_supervisor(tmp_path / model_id)
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ store.sync_sources([_binding(credential_ref, model_ids=(model_id,))])
+ connection = supervisor.ensure_running()
+ source = store.get_source("src_fixture123")
+ assert source is not None
+
+ handle = await EngineClient(connection, timeout=0.05).invoke(
+ source,
+ model_id,
+ {},
+ stream=stream,
+ )
+
+ assert handle.stream is None
+ outcome = await handle.outcome()
+ assert outcome.kind is expected_kind
+ assert outcome.http_status == expected_status
+ assert outcome.stream_started is stream_started
+ supervisor.stop()
+
+ asyncio.run(run())
+
+
+ ("model_id", "response_limit"),
+ [("invalid-json", 1024), ("oversized-non-stream", 8)],
+)
+def test_engine_client_non_stream_failures_after_first_byte_block_retry(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ model_id: str,
+ response_limit: int,
+) -> None:
+ async def run() -> None:
+ supervisor, store = _fixture_supervisor(tmp_path / model_id)
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ store.sync_sources([_binding(credential_ref, model_ids=(model_id,))])
+ source = store.get_source("src_fixture123")
+ assert source is not None
+ connection = supervisor.ensure_running()
+ monkeypatch.setattr(client_module, "_MAX_RESPONSE_BYTES", response_limit)
+
+ handle = await EngineClient(connection).invoke(
+ source,
+ model_id,
+ {},
+ stream=False,
+ )
+
+ assert handle.stream is None
+ outcome = await handle.outcome()
+ assert outcome.kind is RawOutcomeKind.PROTOCOL_ERROR
+ assert outcome.http_status == 200
+ assert outcome.stream_started is True
+ supervisor.stop()
+
+ asyncio.run(run())
+
+
+ ("vendor", "endpoint", "expected_query", "device_flow"),
+ [
+ ("anthropic", "/anthropic-auth-url", {"is_webui": "true"}, False),
+ ("openai", "/codex-auth-url", {"is_webui": "true"}, False),
+ ("codex", "/codex-auth-url", {"is_webui": "true"}, False),
+ ("antigravity", "/antigravity-auth-url", {"is_webui": "true"}, False),
+ ("kimi", "/kimi-auth-url", None, True),
+ ("xai", "/xai-auth-url", None, True),
+ ],
+)
+def test_oauth_start_uses_webui_callback_only_for_browser_flows(
+ tmp_path: Path,
+ vendor: str,
+ endpoint: str,
+ expected_query: dict[str, str] | None,
+ device_flow: bool,
+) -> None:
+ class Client:
+ def __init__(self) -> None:
+ self.start_query = None
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ if path == "/auth-files":
+ return {"files": []}
+ if path == endpoint:
+ self.start_query = query
+ response = {"state": "engine-state", "url": "https://example.test/oauth"}
+ if device_flow:
+ response.update({"flow": "device", "user_code": "ABCD-EFGH"})
+ return response
+ raise AssertionError((method, path, query, payload, timeout))
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+
+ def client(self):
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ client = Client()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ flow = await adapter.start_oauth("src_fixture123", vendor)
+
+ assert client.start_query == expected_query
+ assert flow.expects == ("none" if device_flow else "paste_callback_url")
+
+ asyncio.run(run())
+
+
+def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path) -> None:
+ class Client:
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ assert (method, path) == ("GET", "/auth-files/models")
+ assert query == {"name": "claude-account.json"}
+ return {
+ "models": [
+ {"id": "model-id", "alias": "ignored-alias"},
+ {"alias": "model-alias", "name": "ignored-name"},
+ {"name": "model-name"},
+ ]
+ }
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore) -> None:
+ self.state_store = store
+
+ def client(self):
+ return Client()
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ (store.auth_dir / "claude-account.json").write_text("{}", encoding="utf-8")
+ credential_ref = store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ "claude-account.json",
+ )
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ models = await adapter.discover_models(
+ "anthropic",
+ "anthropic",
+ None,
+ credential_ref,
+ )
+
+ assert models == ("model-id", "model-alias", "model-name")
+
+ asyncio.run(run())
+
+
+ "oauth_record_case",
+ ["new", "refresh", "conflict", "patch_failure", "new_patch_failure"],
+)
+def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
+ tmp_path: Path,
+ oauth_record_case: str,
+) -> None:
+ class Client:
+ def __init__(self) -> None:
+ self.auth_calls = 0
+ self.patches: list[dict[str, object]] = []
+ self.deletes: list[str] = []
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ if path == "/auth-files":
+ if method == "DELETE":
+ self.deletes.append(str((query or {}).get("name")))
+ return {"status": "ok"}
+ self.auth_calls += 1
+ if self.auth_calls == 1:
+ if oauth_record_case in {"new", "new_patch_failure"}:
+ return {"files": []}
+ return {
+ "files": [
+ {
+ "id": "claude-account.json",
+ "name": "claude-account.json",
+ "provider": "claude",
+ "modtime": "2026-07-23T04:00:00Z",
+ }
+ ]
+ }
+ return {
+ "files": [
+ {
+ "id": "claude-account.json",
+ "name": "claude-account.json",
+ "provider": "claude",
+ "modtime": "2026-07-23T04:01:00Z",
+ }
+ ]
+ }
+ if path == "/anthropic-auth-url":
+ return {"state": "engine-state", "url": "https://example.test/oauth"}
+ if path == "/get-auth-status":
+ return {"status": "ok"}
+ if path == "/auth-files/fields":
+ if oauth_record_case in {"patch_failure", "new_patch_failure"}:
+ raise EngineClientError("patch failed")
+ self.patches.append(dict(payload or {}))
+ return {"status": "ok"}
+ raise AssertionError((method, path, query, payload, timeout))
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+
+ def client(self):
+ return self._client
+
+ def client_if_running(self):
+ return None
+
+ def invalidate_configs(self) -> None:
+ self.state_store.clear_runtime_configs()
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ (store.auth_dir / "claude-account.json").write_text("{}", encoding="utf-8")
+ (store.auth_dir / "claude-account.json").chmod(0o600)
+ existing_ref = None
+ existing_prefix = None
+ if oauth_record_case not in {"new", "new_patch_failure"}:
+ existing_ref = store.bind_oauth_credential(
+ "src_other1234" if oauth_record_case == "conflict" else "src_fixture123",
+ "anthropic",
+ "claude-account.json",
+ )
+ existing_prefix = store.credential_metadata(existing_ref)["prefix"]
+ if oauth_record_case == "patch_failure":
+ store.sync_sources(
+ [
+ _binding(
+ existing_ref,
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url=None,
+ allowed_origins=("claude",),
+ )
+ ]
+ )
+ client = Client()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ flow = await adapter.start_oauth("src_fixture123", "anthropic")
+ with pytest.raises(EngineStateError, match="already active"):
+ await adapter.start_oauth("src_other1234", "anthropic")
+ completed, concurrent = await asyncio.gather(
+ adapter.oauth_status(flow.flow_id),
+ adapter.oauth_status(flow.flow_id),
+ )
+
+ if oauth_record_case == "conflict":
+ assert completed.state == "failed"
+ assert completed.error_key == "models.oauth.binding_failed"
+ assert concurrent.state == "failed"
+ retry = await adapter.start_oauth("src_fixture123", "anthropic")
+ assert retry.state == "awaiting_action"
+ assert not client.patches
+ return
+
+ if oauth_record_case in {"patch_failure", "new_patch_failure"}:
+ assert completed.state == "failed"
+ assert completed.error_key == "models.oauth.binding_failed"
+ assert concurrent.state == "failed"
+ if oauth_record_case == "patch_failure":
+ assert store.credential_metadata(existing_ref)["prefix"] == existing_prefix
+ assert (store.auth_dir / "claude-account.json").exists()
+ assert not client.deletes
+ else:
+ assert client.deletes == ["claude-account.json"]
+ assert not (store.auth_dir / "claude-account.json").exists()
+ assert not list((store.root / "credentials").glob("*.json"))
+ retry = await adapter.start_oauth("src_fixture123", "anthropic")
+ assert retry.state == "awaiting_action"
+ return
+
+ assert completed.state == "success"
+ assert completed.source_id == "src_fixture123"
+ assert completed.credential_ref and completed.credential_ref.startswith("cred_")
+ if oauth_record_case == "refresh":
+ assert completed.credential_ref == existing_ref
+ assert concurrent.credential_ref == completed.credential_ref
+ assert client.patches[0]["name"] == "claude-account.json"
+ assert str(client.patches[0]["prefix"]).startswith("avibe-")
+ if oauth_record_case == "refresh":
+ assert client.patches[0]["prefix"] == existing_prefix
+ assert len(list((store.root / "credentials").glob("*.json"))) == 1
+ repeated = await adapter.oauth_status(flow.flow_id)
+ assert repeated.credential_ref == completed.credential_ref
+ assert len(client.patches) == 1
+ await adapter.cancel_oauth(flow.flow_id)
+ assert (await adapter.oauth_status(flow.flow_id)).state == "success"
+ await adapter.revoke_credential(completed.credential_ref)
+ assert not (store.auth_dir / "claude-account.json").exists()
+ with pytest.raises(EngineStateError, match="unavailable"):
+ store.credential_metadata(completed.credential_ref)
+
+ asyncio.run(run())
+
+
+def test_oauth_flow_releases_provider_after_engine_failure_or_expiry(tmp_path: Path) -> None:
+ class Client:
+ def __init__(self) -> None:
+ self.starts = 0
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ if path == "/auth-files":
+ return {"files": []}
+ if path == "/anthropic-auth-url":
+ self.starts += 1
+ return {
+ "state": f"engine-state-{self.starts}",
+ "url": "https://example.test/oauth",
+ }
+ raise AssertionError((method, path, query, payload, timeout))
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+ self.unavailable = False
+
+ def client(self):
+ if self.unavailable:
+ raise EngineUnavailableError("engine unavailable")
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ client = Client()
+ supervisor = Supervisor(store, client)
+ adapter = CLIProxyEngineAdapter(
+ supervisor=supervisor, # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ with pytest.raises(EngineStateError, match="unsupported OAuth vendor"):
+ await adapter.start_oauth("src_fixture123", "gemini")
+
+ failed_flow = await adapter.start_oauth("src_fixture123", "anthropic")
+ supervisor.unavailable = True
+ failed = await adapter.oauth_status(failed_flow.flow_id)
+ assert failed.state == "failed"
+ assert failed.error_key == "models.oauth.engine_unavailable"
+
+ supervisor.unavailable = False
+ expiring_flow = await adapter.start_oauth("src_other1234", "anthropic")
+ adapter._oauth_flows[expiring_flow.flow_id].expires_at_iso = "2000-01-01T00:00:00+00:00"
+ replacement = await adapter.start_oauth("src_third1234", "anthropic")
+ assert replacement.state == "awaiting_action"
+ expired = await adapter.oauth_status(expiring_flow.flow_id)
+ assert expired.state == "failed"
+ assert expired.error_key == "models.oauth.expired"
+
+ asyncio.run(run())
+
+
+def test_supervisor_fails_closed_with_direct_mode_escape(tmp_path: Path) -> None:
+ class FailedInstaller:
+ def ensure(self):
+ return {"ok": False, "reason": "model_hub_engine_archive_checksum_mismatch"}
+
+ def status(self):
+ return {"installed": False, "version": None}
+
+ def contract_manifest(self):
+ return {
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source_sha": "f" * 40,
+ "assets": [],
+ }
+
+ supervisor = EngineSupervisor(
+ installer=FailedInstaller(),
+ state_store=EngineStateStore(tmp_path / "state"),
+ )
+
+ with pytest.raises(EngineUnavailableError) as exc_info:
+ supervisor.ensure_running()
+ assert exc_info.value.error_key == "models.engine.install_failed"
+ assert exc_info.value.reason == "model_hub_engine_archive_checksum_mismatch"
+ assert exc_info.value.direct_mode_available is True
diff --git a/vibe/model_hub_runtime/__init__.py b/vibe/model_hub_runtime/__init__.py
new file mode 100644
index 000000000..320e6e233
--- /dev/null
+++ b/vibe/model_hub_runtime/__init__.py
@@ -0,0 +1,12 @@
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter, get_model_hub_engine_adapter
+from vibe.model_hub_runtime.installer import EngineRuntimeManager
+from vibe.model_hub_runtime.supervisor import EngineSupervisor, EngineUnavailableError
+
+
+__all__ = [
+ "CLIProxyEngineAdapter",
+ "EngineRuntimeManager",
+ "EngineSupervisor",
+ "EngineUnavailableError",
+ "get_model_hub_engine_adapter",
+]
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
new file mode 100644
index 000000000..0c44bef66
--- /dev/null
+++ b/vibe/model_hub_runtime/adapter.py
@@ -0,0 +1,583 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import secrets
+import threading
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from typing import Any, Mapping, Sequence
+
+from core.handlers.model_hub.adapter import (
+ EngineHealth,
+ EngineStatus,
+ OAuthFlowState,
+ OriginNotAllowedError,
+ RawCallOutcome,
+ RawOutcomeKind,
+ SourceBinding,
+)
+from vibe.model_hub_runtime.client import (
+ EngineClient,
+ EngineClientError,
+ EngineInvokeHandle,
+ completed_handle,
+ probe_models,
+)
+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
+from vibe.model_hub_runtime.supervisor import (
+ EngineSupervisor,
+ EngineUnavailableError,
+ get_engine_supervisor,
+)
+
+
+_OAUTH_ENDPOINTS = {
+ "anthropic": ("/anthropic-auth-url", "anthropic", "claude"),
+ "openai": ("/codex-auth-url", "codex", "codex"),
+ "codex": ("/codex-auth-url", "codex", "codex"),
+ "antigravity": ("/antigravity-auth-url", "antigravity", "antigravity"),
+ "kimi": ("/kimi-auth-url", "kimi", "kimi"),
+ "xai": ("/xai-auth-url", "xai", "xai"),
+}
+_WEBUI_OAUTH_VENDORS = frozenset({"anthropic", "openai", "codex", "antigravity"})
+
+
+@dataclass(frozen=True)
+class _AuthRecord:
+ identity: str
+ name: str
+ provider: str
+ fingerprint: str
+
+
+@dataclass
+class _OAuthFlow:
+ flow_id: str
+ source_id: str
+ engine_state: str
+ vendor: str
+ callback_provider: str
+ auth_provider: str
+ expects: str
+ auth_url: str | None
+ device_code: str | None
+ expires_at_iso: str
+ before_auth_fingerprints: dict[str, str]
+ state: str = "awaiting_action"
+ error_key: str | None = None
+ credential_ref: str | None = None
+ operation_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
+
+ def snapshot(self) -> OAuthFlowState:
+ return OAuthFlowState(
+ flow_id=self.flow_id,
+ source_id=self.source_id,
+ vendor=self.vendor,
+ state=self.state,
+ auth_url=self.auth_url,
+ device_code=self.device_code,
+ expects=self.expects,
+ instructions_key=f"models.oauth.{self.vendor}.{self.expects}",
+ error_key=self.error_key,
+ expires_at_iso=self.expires_at_iso,
+ credential_ref=self.credential_ref,
+ )
+
+
+class CLIProxyEngineAdapter:
+ """Managed CLIProxyAPI implementation of the frozen EngineAdapter contract."""
+
+ def __init__(
+ self,
+ *,
+ supervisor: EngineSupervisor | None = None,
+ state_store: EngineStateStore | None = None,
+ ) -> None:
+ self.supervisor = supervisor or get_engine_supervisor()
+ self.state_store = state_store or self.supervisor.state_store
+ self._routing_lock = asyncio.Lock()
+ self._oauth_flows: dict[str, _OAuthFlow] = {}
+ self._active_oauth_providers: set[str] = set()
+ self._oauth_lock = threading.RLock()
+
+ async def ensure_installed(self) -> EngineStatus:
+ async with self._routing_lock:
+ install = await asyncio.to_thread(self.supervisor.installer.ensure)
+ if not install.get("ok"):
+ reason = str(install.get("reason") or "engine_install_failed")
+ raise EngineUnavailableError("models.engine.install_failed", reason=reason)
+ if install.get("changed"):
+ await asyncio.to_thread(self.supervisor.restart_if_running)
+ return await self.status()
+
+ async def start(self) -> EngineStatus:
+ await asyncio.to_thread(self.supervisor.ensure_running)
+ return await self.status()
+
+ async def stop(self) -> None:
+ await asyncio.to_thread(self.supervisor.stop)
+
+ async def status(self) -> EngineStatus:
+ raw = await asyncio.to_thread(self.supervisor.status)
+ status = raw["status"]
+ listening = status.get("listening") or {}
+ return EngineStatus(
+ health=EngineHealth(status["health"]),
+ installed_version=status.get("installed_version"),
+ verified=bool(status.get("verified")),
+ listen_host="127.0.0.1",
+ listen_port=listening.get("port"),
+ last_check_iso=status.get("last_check"),
+ )
+
+ async def gateway_token(self) -> str:
+ connection = await asyncio.to_thread(self.supervisor.ensure_running)
+ return connection.gateway_token
+
+ async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None:
+ async with self._routing_lock:
+ previous = await asyncio.to_thread(self.state_store.list_sources)
+ was_running = await asyncio.to_thread(self.supervisor.client_if_running) is not None
+ await asyncio.to_thread(self.state_store.sync_sources, bindings)
+ try:
+ await asyncio.to_thread(self.supervisor.restart_if_running)
+ except Exception:
+ await asyncio.to_thread(self.state_store.replace_sources, previous)
+ if was_running:
+ try:
+ await asyncio.to_thread(self.supervisor.ensure_running)
+ except Exception as restore_error:
+ raise EngineStateError(
+ "source sync failed and the previous engine state could not be restored"
+ ) from restore_error
+ raise
+
+ async def provision_credential(
+ self,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ return await asyncio.to_thread(
+ self.state_store.store_api_key,
+ secret,
+ vendor=vendor,
+ protocol=protocol,
+ base_url=base_url,
+ )
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ await asyncio.to_thread(
+ self.state_store.assert_credential_unbound,
+ credential_ref,
+ )
+ metadata = await asyncio.to_thread(
+ self.state_store.credential_metadata,
+ credential_ref,
+ )
+ auth_name = metadata.get("auth_name") if metadata["kind"] == "oauth" else None
+ if auth_name:
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ if client is not None:
+ try:
+ await asyncio.to_thread(
+ client.management_request,
+ "DELETE",
+ "/auth-files",
+ query={"name": str(auth_name)},
+ timeout=1.0,
+ )
+ except EngineClientError:
+ pass
+ await asyncio.to_thread(self.state_store.delete_oauth_auth_file, str(auth_name))
+ await asyncio.to_thread(self.state_store.audit_auth_permissions, enforce=True)
+ await asyncio.to_thread(self.supervisor.invalidate_configs)
+ await asyncio.to_thread(self.state_store.revoke_credential, credential_ref)
+
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ ) -> Sequence[str]:
+ metadata = await asyncio.to_thread(
+ self.state_store.credential_metadata,
+ credential_ref,
+ )
+ normalized_vendor = vendor.strip().lower()
+ if metadata["kind"] == "oauth":
+ if metadata.get("vendor") != normalized_vendor or base_url is not None:
+ raise EngineStateError("credential does not match discovery target")
+ client = await asyncio.to_thread(self.supervisor.client)
+ payload = await asyncio.to_thread(
+ client.management_request,
+ "GET",
+ "/auth-files/models",
+ query={"name": str(metadata["auth_name"])},
+ )
+ return _model_ids(payload)
+ normalized_base_url = await asyncio.to_thread(
+ self.state_store.validate_api_key_target,
+ credential_ref,
+ vendor=normalized_vendor,
+ protocol=protocol,
+ base_url=base_url,
+ )
+ secret = await asyncio.to_thread(self.state_store.read_api_key, credential_ref)
+ try:
+ return await probe_models(
+ vendor=normalized_vendor,
+ protocol=protocol,
+ base_url=normalized_base_url,
+ secret=secret,
+ )
+ except EngineClientError as exc:
+ raise EngineStateError("model discovery failed") from exc
+
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:
+ await asyncio.to_thread(self.state_store.validate_source_id, source_id)
+ normalized_vendor = vendor.strip().lower()
+ endpoint = _OAUTH_ENDPOINTS.get(normalized_vendor)
+ if endpoint is None:
+ raise EngineStateError("unsupported OAuth vendor")
+ engine_endpoint, callback_provider, auth_provider = endpoint
+ with self._oauth_lock:
+ self._expire_oauth_flows_locked()
+ if auth_provider in self._active_oauth_providers:
+ raise EngineStateError("an OAuth flow for this provider is already active")
+ self._active_oauth_providers.add(auth_provider)
+ try:
+ client = await asyncio.to_thread(self.supervisor.client)
+ before = await asyncio.to_thread(_auth_inventory, client)
+ payload = await asyncio.to_thread(
+ client.management_request,
+ "GET",
+ engine_endpoint,
+ query={"is_webui": "true"} if normalized_vendor in _WEBUI_OAUTH_VENDORS else None,
+ )
+ engine_state = str(payload.get("state") or "").strip()
+ if not engine_state:
+ raise EngineStateError("engine OAuth response omitted state")
+ device_code = str(payload.get("user_code") or "").strip() or None
+ flow_kind = str(payload.get("flow") or "").strip().lower()
+ expects = "none" if device_code or flow_kind == "device" else "paste_callback_url"
+ expires_in = max(1, int(payload.get("expires_in") or 300))
+ flow = _OAuthFlow(
+ flow_id=f"oaf_{secrets.token_hex(12)}",
+ source_id=source_id,
+ engine_state=engine_state,
+ vendor=normalized_vendor,
+ callback_provider=callback_provider,
+ auth_provider=auth_provider,
+ expects=expects,
+ auth_url=str(payload.get("url") or payload.get("verification_uri") or "").strip() or None,
+ device_code=device_code,
+ expires_at_iso=(datetime.now(timezone.utc) + timedelta(seconds=expires_in)).isoformat(),
+ before_auth_fingerprints={identity: record.fingerprint for identity, record in before.items()},
+ )
+ except Exception:
+ with self._oauth_lock:
+ self._active_oauth_providers.discard(auth_provider)
+ raise
+ with self._oauth_lock:
+ self._oauth_flows[flow.flow_id] = flow
+ return flow.snapshot()
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState:
+ flow = self._get_flow(flow_id)
+ async with flow.operation_lock:
+ self._expire_oauth_flow(flow)
+ if flow.state in {"success", "failed", "cancelled"}:
+ return flow.snapshot()
+ try:
+ client = await asyncio.to_thread(self.supervisor.client)
+ payload = await asyncio.to_thread(
+ client.management_request,
+ "GET",
+ "/get-auth-status",
+ query={"state": flow.engine_state},
+ )
+ status = str(payload.get("status") or "").strip().lower()
+ if status == "ok":
+ await self._complete_oauth(flow, client)
+ elif status == "error":
+ self._fail_flow(flow, "models.oauth.upstream_failed")
+ elif flow.state != "verifying":
+ flow.state = "awaiting_action"
+ except (EngineClientError, EngineUnavailableError):
+ self._fail_flow(flow, "models.oauth.engine_unavailable")
+ return flow.snapshot()
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
+ flow = self._get_flow(flow_id)
+ async with flow.operation_lock:
+ self._expire_oauth_flow(flow)
+ if flow.state in {"success", "failed", "cancelled"}:
+ raise EngineStateError("OAuth flow is no longer active")
+ if flow.expects == "none":
+ raise EngineStateError("this OAuth flow does not accept a submission")
+ submitted = value.strip()
+ if not submitted:
+ raise EngineStateError("OAuth submission is empty")
+ payload: dict[str, str] = {
+ "provider": flow.callback_provider,
+ "state": flow.engine_state,
+ }
+ if submitted.startswith(("http://", "https://")):
+ payload["redirect_url"] = submitted
+ else:
+ payload["code"] = submitted
+ try:
+ client = await asyncio.to_thread(self.supervisor.client)
+ await asyncio.to_thread(
+ client.management_request,
+ "POST",
+ "/oauth-callback",
+ payload=payload,
+ )
+ except (EngineClientError, EngineUnavailableError):
+ self._fail_flow(flow, "models.oauth.submission_failed")
+ return flow.snapshot()
+ flow.state = "verifying"
+ return flow.snapshot()
+
+ async def cancel_oauth(self, flow_id: str) -> None:
+ flow = self._get_flow(flow_id)
+ async with flow.operation_lock:
+ self._expire_oauth_flow(flow)
+ if flow.state in {"success", "failed", "cancelled"}:
+ return
+ try:
+ client = await asyncio.to_thread(self.supervisor.client)
+ await asyncio.to_thread(
+ client.management_request,
+ "DELETE",
+ "/oauth-session",
+ query={"state": flow.engine_state},
+ )
+ except (EngineClientError, EngineUnavailableError):
+ pass
+ flow.state = "cancelled"
+ self._release_provider(flow)
+
+ async def invoke(
+ self,
+ source_id: str,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ origin: str,
+ ) -> EngineInvokeHandle:
+ async with self._routing_lock:
+ source = await asyncio.to_thread(self.state_store.get_source, source_id)
+ if source is None:
+ raise EngineStateError("source is not registered")
+ if source.allowed_origins and origin not in source.allowed_origins:
+ raise OriginNotAllowedError(
+ f"origin {origin!r} is not allowed to use source {source_id!r}"
+ )
+ try:
+ client = await asyncio.to_thread(self.supervisor.client)
+ except EngineUnavailableError:
+ return completed_handle(
+ RawCallOutcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ http_status=None,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ model_id=model_id,
+ source_id=source_id,
+ )
+ )
+ return await client.invoke(source, model_id, request, stream=stream)
+
+ async def _complete_oauth(self, flow: _OAuthFlow, client: EngineClient) -> None:
+ inventory = await asyncio.to_thread(_auth_inventory, client)
+ provider_records = [record for record in inventory.values() if record.provider == flow.auth_provider]
+ candidates = [
+ record
+ for record in provider_records
+ if flow.before_auth_fingerprints.get(record.identity) != record.fingerprint
+ ]
+ if not candidates and len(provider_records) == 1:
+ candidates = provider_records
+ if len(candidates) != 1:
+ if not candidates:
+ flow.state = "verifying"
+ return
+ self._fail_flow(flow, "models.oauth.ambiguous_engine_binding")
+ return
+ auth = candidates[0]
+ try:
+ existing_credential_ref = await asyncio.to_thread(
+ self.state_store.oauth_credential_ref,
+ auth.name,
+ )
+ credential_ref = await asyncio.to_thread(
+ self.state_store.bind_oauth_credential,
+ flow.source_id,
+ flow.vendor,
+ auth.name,
+ )
+ credential = await asyncio.to_thread(
+ self.state_store.credential_metadata,
+ credential_ref,
+ )
+ except EngineStateError:
+ self._fail_flow(flow, "models.oauth.binding_failed")
+ return
+ try:
+ await asyncio.to_thread(
+ client.management_request,
+ "PATCH",
+ "/auth-files/fields",
+ payload={"name": auth.name, "prefix": credential["prefix"]},
+ )
+ await asyncio.to_thread(self.state_store.audit_auth_permissions, enforce=True)
+ except (EngineClientError, EngineStateError):
+ if existing_credential_ref is None:
+ if auth.identity not in flow.before_auth_fingerprints:
+ try:
+ await asyncio.to_thread(
+ client.management_request,
+ "DELETE",
+ "/auth-files",
+ query={"name": auth.name},
+ )
+ except EngineClientError:
+ pass
+ try:
+ await asyncio.to_thread(
+ self.state_store.delete_oauth_auth_file,
+ auth.name,
+ )
+ except EngineStateError:
+ pass
+ try:
+ await asyncio.to_thread(
+ self.state_store.revoke_credential,
+ credential_ref,
+ )
+ except EngineStateError:
+ pass
+ self._fail_flow(flow, "models.oauth.binding_failed")
+ return
+ flow.credential_ref = credential_ref
+ flow.state = "success"
+ self._release_provider(flow)
+
+ def _get_flow(self, flow_id: str) -> _OAuthFlow:
+ with self._oauth_lock:
+ self._expire_oauth_flows_locked()
+ flow = self._oauth_flows.get(flow_id)
+ if flow is None:
+ raise EngineStateError("OAuth flow is unknown")
+ return flow
+
+ def _fail_flow(self, flow: _OAuthFlow, error_key: str) -> None:
+ flow.state = "failed"
+ flow.error_key = error_key
+ self._release_provider(flow)
+
+ def _release_provider(self, flow: _OAuthFlow) -> None:
+ with self._oauth_lock:
+ self._active_oauth_providers.discard(flow.auth_provider)
+
+ def _expire_oauth_flow(self, flow: _OAuthFlow) -> None:
+ with self._oauth_lock:
+ self._expire_oauth_flow_locked(flow, datetime.now(timezone.utc))
+
+ def _expire_oauth_flows_locked(self) -> None:
+ now = datetime.now(timezone.utc)
+ for flow in self._oauth_flows.values():
+ if flow.operation_lock.locked():
+ continue
+ self._expire_oauth_flow_locked(flow, now)
+
+ def _expire_oauth_flow_locked(self, flow: _OAuthFlow, now: datetime) -> None:
+ if flow.state in {"success", "failed", "cancelled"}:
+ return
+ try:
+ expires_at = datetime.fromisoformat(flow.expires_at_iso)
+ except ValueError:
+ expires_at = now
+ if expires_at.tzinfo is None:
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
+ if expires_at <= now:
+ flow.state = "failed"
+ flow.error_key = "models.oauth.expired"
+ self._active_oauth_providers.discard(flow.auth_provider)
+
+
+def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:
+ payload = client.management_request("GET", "/auth-files")
+ files = payload.get("files")
+ if not isinstance(files, list):
+ raise EngineClientError("engine auth inventory is invalid", error_type="invalid_json")
+ inventory: dict[str, _AuthRecord] = {}
+ for item in files:
+ if not isinstance(item, dict):
+ continue
+ identity = str(item.get("id") or item.get("auth_index") or item.get("name") or "").strip()
+ name = str(item.get("name") or item.get("id") or "").strip()
+ provider = str(item.get("provider") or item.get("type") or "").strip().lower()
+ if identity and name and provider:
+ fingerprint = json.dumps(
+ {
+ key: item.get(key)
+ for key in (
+ "modtime",
+ "updated_at",
+ "last_refresh",
+ "status",
+ "status_message",
+ "size",
+ "disabled",
+ "unavailable",
+ )
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ inventory[identity] = _AuthRecord(
+ identity=identity,
+ name=name,
+ provider=provider,
+ fingerprint=fingerprint,
+ )
+ return inventory
+
+
+def _model_ids(payload: Mapping[str, Any]) -> tuple[str, ...]:
+ models = payload.get("models")
+ if not isinstance(models, list):
+ return ()
+ result: list[str] = []
+ for item in models:
+ value = (
+ item.get("id") or item.get("alias") or item.get("name")
+ if isinstance(item, dict)
+ else item
+ )
+ if isinstance(value, str) and value and value not in result:
+ result.append(value)
+ return tuple(result)
+
+
+_adapter: CLIProxyEngineAdapter | None = None
+
+
+def get_model_hub_engine_adapter() -> CLIProxyEngineAdapter:
+ global _adapter
+ if _adapter is None:
+ _adapter = CLIProxyEngineAdapter()
+ return _adapter
+
+
+def set_model_hub_engine_adapter_for_tests(adapter: CLIProxyEngineAdapter | None) -> None:
+ global _adapter
+ _adapter = adapter
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
new file mode 100644
index 000000000..38fc2860d
--- /dev/null
+++ b/vibe/model_hub_runtime/client.py
@@ -0,0 +1,542 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import socket
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass, field
+from typing import Any, AsyncIterator, Mapping
+
+import aiohttp
+
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+from vibe.model_hub_runtime.state import SourceRecord
+
+
+_MAX_RESPONSE_BYTES = 16 * 1024 * 1024
+_STREAM_CHUNK_BYTES = 64 * 1024
+_MODEL_PROBE_BYTES = 4 * 1024 * 1024
+_SAFE_ERROR_CODES = frozenset(
+ {
+ "api_error",
+ "authentication_error",
+ "billing_error",
+ "context_length_exceeded",
+ "insufficient_quota",
+ "invalid_api_key",
+ "invalid_request_error",
+ "model_not_found",
+ "not_found_error",
+ "overloaded_error",
+ "permission_error",
+ "quota_exceeded",
+ "rate_limit_error",
+ "rate_limit_exceeded",
+ "request_too_large",
+ "server_error",
+ }
+)
+_OFFICIAL_BASE_URLS = {
+ "anthropic": "https://api.anthropic.com/v1",
+ "openai": "https://api.openai.com/v1",
+ "codex": "https://api.openai.com/v1",
+}
+
+
+class EngineClientError(RuntimeError):
+ def __init__(
+ self,
+ message: str,
+ *,
+ status_code: int | None = None,
+ error_type: str | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+ self.error_type = error_type
+
+
+class _ResponseTooLargeError(RuntimeError):
+ pass
+
+
+@dataclass(frozen=True)
+class EngineConnection:
+ base_url: str
+ management_key: str = field(repr=False)
+ gateway_token: str = field(repr=False)
+
+
+class EngineInvokeHandle:
+ """Concrete InvokeHandle with one-shot streaming ownership."""
+
+ def __init__(
+ self,
+ *,
+ stream: AsyncIterator[bytes] | None,
+ outcome: asyncio.Future[RawCallOutcome],
+ ) -> None:
+ self._stream = stream
+ self._outcome = outcome
+
+ @property
+ def stream(self) -> AsyncIterator[bytes] | None:
+ return self._stream
+
+ async def outcome(self) -> RawCallOutcome:
+ return await asyncio.shield(self._outcome)
+
+
+class EngineClient:
+ """Narrow loopback-only client for the engine data and management APIs."""
+
+ def __init__(self, connection: EngineConnection, *, timeout: float = 60.0) -> None:
+ parsed = urllib.parse.urlparse(connection.base_url)
+ if parsed.scheme != "http" or parsed.hostname != "127.0.0.1" or parsed.username or parsed.password:
+ raise ValueError("engine client requires a credential-free 127.0.0.1 URL")
+ self.connection = connection
+ self.timeout = timeout
+
+ def health(self) -> bool:
+ try:
+ models = self._request_json(
+ "GET",
+ "/v1/models",
+ headers={"Authorization": f"Bearer {self.connection.gateway_token}"},
+ timeout=min(self.timeout, 1.0),
+ )
+ config = self.management_request("GET", "/config", timeout=min(self.timeout, 1.0))
+ except EngineClientError:
+ return False
+ return models.get("object") == "list" and isinstance(config, dict)
+
+ def management_request(
+ self,
+ method: str,
+ path: str,
+ *,
+ query: Mapping[str, str] | None = None,
+ payload: Mapping[str, Any] | None = None,
+ timeout: float | None = None,
+ ) -> dict[str, Any]:
+ if not path.startswith("/") or path.startswith("//"):
+ raise ValueError("management path must be relative to the allowlisted API root")
+ return self._request_json(
+ method,
+ f"/v0/management{path}",
+ query=query,
+ payload=payload,
+ headers={"X-Management-Key": self.connection.management_key},
+ timeout=timeout,
+ )
+
+ async def invoke(
+ self,
+ source: SourceRecord,
+ model_id: str,
+ request: Mapping[str, Any],
+ *,
+ stream: bool,
+ ) -> EngineInvokeHandle:
+ endpoint = _endpoint_for_protocol(source.protocol)
+ body = dict(request)
+ body["model"] = f"{source.prefix}/{model_id}"
+ body["stream"] = stream
+ headers = {
+ "Authorization": f"Bearer {self.connection.gateway_token}",
+ "Content-Type": "application/json",
+ }
+ if source.protocol == "anthropic":
+ headers["anthropic-version"] = "2023-06-01"
+
+ timeout = aiohttp.ClientTimeout(
+ total=None,
+ connect=self.timeout,
+ sock_connect=self.timeout,
+ sock_read=None,
+ )
+ session = aiohttp.ClientSession(timeout=timeout, trust_env=False)
+ response: aiohttp.ClientResponse | None = None
+ first_received = False
+ try:
+ response = await asyncio.wait_for(
+ session.post(
+ self._url(endpoint),
+ json=body,
+ headers=headers,
+ allow_redirects=False,
+ ),
+ timeout=self.timeout,
+ )
+ if response.status >= 300:
+ try:
+ payload = await asyncio.wait_for(
+ _read_limited(response.content, _MAX_RESPONSE_BYTES),
+ timeout=self.timeout,
+ )
+ except (_ResponseTooLargeError, asyncio.TimeoutError, aiohttp.ClientError):
+ payload = b""
+ outcome = _outcome(
+ kind=RawOutcomeKind.HTTP_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ error_code=_error_code(payload),
+ message=f"upstream returned HTTP {response.status}",
+ )
+ response.close()
+ await session.close()
+ return completed_handle(outcome)
+
+ first = await asyncio.wait_for(
+ response.content.read(_STREAM_CHUNK_BYTES),
+ timeout=self.timeout,
+ )
+ if not first:
+ response.close()
+ await session.close()
+ return completed_handle(
+ _outcome(
+ kind=RawOutcomeKind.PROTOCOL_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream response ended before the first byte",
+ )
+ )
+ first_received = True
+ if not stream:
+ try:
+ first = await asyncio.wait_for(
+ _read_limited(
+ response.content,
+ _MAX_RESPONSE_BYTES,
+ initial=first,
+ ),
+ timeout=self.timeout,
+ )
+ except _ResponseTooLargeError:
+ response.close()
+ await session.close()
+ return completed_handle(
+ _outcome(
+ kind=RawOutcomeKind.PROTOCOL_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream response exceeded the local limit",
+ stream_started=True,
+ )
+ )
+ if not _is_json(first):
+ response.close()
+ await session.close()
+ return completed_handle(
+ _outcome(
+ kind=RawOutcomeKind.PROTOCOL_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream returned an invalid JSON response",
+ stream_started=True,
+ )
+ )
+ except asyncio.TimeoutError:
+ if response is not None:
+ response.close()
+ await session.close()
+ return completed_handle(
+ _outcome(
+ kind=RawOutcomeKind.TIMEOUT,
+ source=source,
+ model_id=model_id,
+ http_status=response.status if response is not None and first_received else None,
+ message="upstream request timed out",
+ stream_started=first_received,
+ )
+ )
+ except aiohttp.ClientError:
+ if response is not None:
+ response.close()
+ await session.close()
+ return completed_handle(
+ _outcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status if response is not None and first_received else None,
+ message="upstream request failed",
+ stream_started=first_received,
+ )
+ )
+
+ loop = asyncio.get_running_loop()
+ outcome_future: asyncio.Future[RawCallOutcome] = loop.create_future()
+ response_stream = _response_stream(
+ response=response,
+ session=session,
+ first=first,
+ source=source,
+ model_id=model_id,
+ outcome_future=outcome_future,
+ )
+ return EngineInvokeHandle(stream=response_stream, outcome=outcome_future)
+
+ def _request_json(
+ self,
+ method: str,
+ path: str,
+ *,
+ query: Mapping[str, str] | None = None,
+ payload: Mapping[str, Any] | None = None,
+ headers: Mapping[str, str] | None = None,
+ timeout: float | None = None,
+ ) -> dict[str, Any]:
+ url = self._url(path, query=query)
+ data = None if payload is None else json.dumps(payload, separators=(",", ":")).encode()
+ request_headers = dict(headers or {})
+ if data is not None:
+ request_headers["Content-Type"] = "application/json"
+ request = urllib.request.Request(url, data=data, headers=request_headers, method=method)
+ try:
+ opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({}),
+ _NoRedirectHandler(),
+ )
+ with opener.open(request, timeout=timeout or self.timeout) as response:
+ raw = response.read(_MAX_RESPONSE_BYTES + 1)
+ except urllib.error.HTTPError as exc:
+ raw = exc.read(_MAX_RESPONSE_BYTES)
+ raise EngineClientError(
+ f"engine API returned HTTP {exc.code}",
+ status_code=exc.code,
+ error_type=_error_code(raw),
+ ) from None
+ except (urllib.error.URLError, TimeoutError, socket.timeout, OSError) as exc:
+ raise EngineClientError("engine API is unavailable", error_type=type(exc).__name__) from None
+ if len(raw) > _MAX_RESPONSE_BYTES:
+ raise EngineClientError("engine API response is too large", error_type="response_too_large")
+ try:
+ decoded = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError):
+ raise EngineClientError("engine API returned an invalid payload", error_type="invalid_json") from None
+ if not isinstance(decoded, dict):
+ raise EngineClientError("engine API returned an invalid payload", error_type="invalid_json")
+ return decoded
+
+ def _url(self, path: str, *, query: Mapping[str, str] | None = None) -> str:
+ url = f"{self.connection.base_url.rstrip('/')}{path}"
+ if query:
+ url = f"{url}?{urllib.parse.urlencode(query)}"
+ return url
+
+
+async def probe_models(
+ *,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ secret: str,
+ timeout: float = 15.0,
+) -> tuple[str, ...]:
+ """Probe the one allowlisted models path without redirecting credentials."""
+ normalized_vendor = vendor.strip().lower()
+ root = base_url or _OFFICIAL_BASE_URLS.get(normalized_vendor)
+ if not root:
+ raise EngineClientError("source requires a base URL for model discovery")
+ parsed = urllib.parse.urlparse(root)
+ if (
+ parsed.scheme not in {"http", "https"}
+ or not parsed.netloc
+ or parsed.username
+ or parsed.password
+ or parsed.query
+ or parsed.fragment
+ ):
+ raise EngineClientError("source base URL is invalid")
+ headers = {"Authorization": f"Bearer {secret}", "Accept": "application/json"}
+ if protocol == "anthropic":
+ headers = {
+ "x-api-key": secret,
+ "anthropic-version": "2023-06-01",
+ "Accept": "application/json",
+ }
+ url = f"{root.rstrip('/')}/models"
+ client_timeout = aiohttp.ClientTimeout(total=timeout)
+ try:
+ async with aiohttp.ClientSession(timeout=client_timeout) as session:
+ async with session.get(url, headers=headers, allow_redirects=False) as response:
+ if response.status >= 300:
+ raise EngineClientError(
+ f"model discovery returned HTTP {response.status}",
+ status_code=response.status,
+ )
+ payload = await _read_limited(response.content, _MODEL_PROBE_BYTES)
+ except _ResponseTooLargeError:
+ raise EngineClientError("model discovery response is too large") from None
+ except asyncio.TimeoutError:
+ raise EngineClientError("model discovery timed out", error_type="timeout") from None
+ except aiohttp.ClientError:
+ raise EngineClientError("model discovery failed", error_type="network_error") from None
+ try:
+ decoded = json.loads(payload.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError):
+ raise EngineClientError("model discovery returned an invalid payload") from None
+ if not isinstance(decoded, dict):
+ raise EngineClientError("model discovery returned an invalid payload")
+ items = decoded.get("data", decoded.get("models"))
+ if not isinstance(items, list):
+ raise EngineClientError("model discovery returned an invalid payload")
+ model_ids: list[str] = []
+ for item in items:
+ value = item.get("id") if isinstance(item, dict) else item
+ if isinstance(value, str) and value and value not in model_ids:
+ model_ids.append(value)
+ return tuple(model_ids)
+
+
+class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, request, fp, code, message, headers, new_url):
+ return None
+
+
+async def _read_limited(
+ content: aiohttp.StreamReader,
+ limit: int,
+ *,
+ initial: bytes = b"",
+) -> bytes:
+ payload = bytearray(initial)
+ if len(payload) > limit:
+ raise _ResponseTooLargeError
+ while True:
+ chunk = await content.read(min(_STREAM_CHUNK_BYTES, limit + 1 - len(payload)))
+ if not chunk:
+ return bytes(payload)
+ payload.extend(chunk)
+ if len(payload) > limit:
+ raise _ResponseTooLargeError
+
+
+async def _response_stream(
+ *,
+ response: aiohttp.ClientResponse,
+ session: aiohttp.ClientSession,
+ first: bytes,
+ source: SourceRecord,
+ model_id: str,
+ outcome_future: asyncio.Future[RawCallOutcome],
+) -> AsyncIterator[bytes]:
+ outcome: RawCallOutcome | None = None
+ try:
+ yield first
+ async for chunk in response.content.iter_chunked(_STREAM_CHUNK_BYTES):
+ if chunk:
+ yield chunk
+ outcome = _outcome(
+ kind=RawOutcomeKind.SUCCESS,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ stream_started=True,
+ )
+ except asyncio.TimeoutError:
+ outcome = _outcome(
+ kind=RawOutcomeKind.TIMEOUT,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream response timed out after streaming started",
+ stream_started=True,
+ )
+ except aiohttp.ClientError:
+ outcome = _outcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream response failed after streaming started",
+ stream_started=True,
+ )
+ finally:
+ response.close()
+ await session.close()
+ if outcome is None:
+ outcome = _outcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=response.status,
+ message="upstream response stream was not fully consumed",
+ stream_started=True,
+ )
+ if not outcome_future.done():
+ outcome_future.set_result(outcome)
+
+
+def completed_handle(outcome: RawCallOutcome) -> EngineInvokeHandle:
+ future = asyncio.get_running_loop().create_future()
+ future.set_result(outcome)
+ return EngineInvokeHandle(stream=None, outcome=future)
+
+
+def _outcome(
+ *,
+ kind: RawOutcomeKind,
+ source: SourceRecord,
+ model_id: str,
+ http_status: int | None = None,
+ error_code: str | None = None,
+ message: str | None = None,
+ stream_started: bool = False,
+) -> RawCallOutcome:
+ return RawCallOutcome(
+ kind=kind,
+ http_status=http_status,
+ error_code=error_code,
+ redacted_message=message,
+ stream_started=stream_started,
+ model_id=model_id,
+ source_id=source.source_id,
+ )
+
+
+def _endpoint_for_protocol(protocol: str) -> str:
+ if protocol == "anthropic":
+ return "/v1/messages"
+ if protocol == "openai_responses":
+ return "/v1/responses"
+ if protocol in {"openai_chat", "openai_compatible"}:
+ return "/v1/chat/completions"
+ raise ValueError("unsupported source protocol")
+
+
+def _error_code(payload: bytes) -> str | None:
+ try:
+ decoded = json.loads(payload.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError):
+ return None
+ if not isinstance(decoded, dict):
+ return None
+ error = decoded.get("error")
+ if isinstance(error, dict):
+ value = error.get("type") or error.get("code")
+ return _safe_error_code(value)
+ value = decoded.get("code")
+ return _safe_error_code(value)
+
+
+def _safe_error_code(value: object) -> str | None:
+ if not isinstance(value, str) or value not in _SAFE_ERROR_CODES:
+ return None
+ return value
+
+
+def _is_json(payload: bytes) -> bool:
+ try:
+ json.loads(payload.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError):
+ return False
+ return True
diff --git a/vibe/model_hub_runtime/cliproxyapi_manifest.json b/vibe/model_hub_runtime/cliproxyapi_manifest.json
new file mode 100644
index 000000000..5cd889e60
--- /dev/null
+++ b/vibe/model_hub_runtime/cliproxyapi_manifest.json
@@ -0,0 +1,28 @@
+{
+ "schema_version": 1,
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source": "router-for-me/CLIProxyAPI",
+ "source_url": "https://github.com/router-for-me/CLIProxyAPI/tree/f71ec0eb6776854457892452cf28c47f0d658251",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "release_tag": "v7.2.95",
+ "license": "MIT",
+ "assets": [
+ {
+ "platform": "darwin-arm64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_darwin_aarch64.tar.gz",
+ "size_bytes": 14384655,
+ "sha256": "c7ccc28b7db5d1799999a9e22725ccc6bd0e36d9aa023da6b52b7c1a71aad978",
+ "binary_sha256": "ad81a4c82700bf96eaa4cf5811690b0498ebcfe6087e26ffc0498b8fc8e867af",
+ "bin_path": "cli-proxy-api"
+ },
+ {
+ "platform": "linux-amd64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_linux_amd64.tar.gz",
+ "size_bytes": 15401775,
+ "sha256": "826604e2dbf11913b0f373047f7bca1829eb2bab8a45d3a1916cc2534c7a9fd5",
+ "binary_sha256": "2be8e4581fe802fe522126b273bc099c01910b6179dca4a4e1b451dd0c80a1c0",
+ "bin_path": "cli-proxy-api"
+ }
+ ]
+}
diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.py
new file mode 100644
index 000000000..b47444ab0
--- /dev/null
+++ b/vibe/model_hub_runtime/config.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, Iterable
+
+import yaml
+
+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, RuntimeSecrets, SourceRecord
+
+
+def write_engine_config(
+ path: Path,
+ *,
+ host: str,
+ port: int,
+ auth_dir: Path,
+ runtime_secrets: RuntimeSecrets,
+ sources: Iterable[SourceRecord],
+ state_store: EngineStateStore,
+) -> None:
+ if host != "127.0.0.1":
+ raise EngineStateError("model hub engine must bind to 127.0.0.1")
+ payload: dict[str, Any] = {
+ "host": host,
+ "port": port,
+ "tls": {"enable": False, "cert": "", "key": ""},
+ "remote-management": {
+ "allow-remote": False,
+ "secret-key": runtime_secrets.management_key,
+ "disable-control-panel": True,
+ "disable-auto-update-panel": True,
+ },
+ "auth-dir": str(auth_dir),
+ "api-keys": [runtime_secrets.gateway_token],
+ "debug": False,
+ "pprof": {"enable": False, "addr": "127.0.0.1:0"},
+ "plugins": {"enabled": False, "dir": str(path.parent / "plugins"), "configs": {}},
+ "commercial-mode": True,
+ "logging-to-file": False,
+ "request-log": False,
+ "usage-statistics-enabled": False,
+ "redis-usage-queue-retention-seconds": 60,
+ "proxy-url": "",
+ "force-model-prefix": True,
+ "passthrough-headers": False,
+ "request-retry": 0,
+ "max-retry-credentials": 1,
+ "max-retry-interval": 0,
+ "disable-cooling": True,
+ "save-cooldown-status": False,
+ "transient-error-cooldown-seconds": -1,
+ "quota-exceeded": {
+ "switch-project": False,
+ "switch-preview-model": False,
+ "antigravity-credits": False,
+ },
+ "routing": {"strategy": "fill-first", "session-affinity": False},
+ "ws-auth": True,
+ }
+ for source in sources:
+ _append_source(payload, source, state_store)
+ _secure_write_yaml(path, payload)
+
+
+def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineStateStore) -> None:
+ credential = store.credential_metadata(source.credential_ref)
+ if credential["kind"] == "oauth":
+ # OAuth credentials are engine auth files, not YAML credential values.
+ return
+ api_key = store.read_api_key(source.credential_ref)
+ models = [{"name": model, "alias": model} for model in source.model_ids]
+ if source.protocol == "anthropic":
+ entry: dict[str, Any] = {"api-key": api_key, "prefix": source.prefix}
+ if models:
+ entry["models"] = models
+ if source.base_url:
+ entry["base-url"] = source.base_url
+ payload.setdefault("claude-api-key", []).append(entry)
+ return
+ if source.protocol == "openai_responses":
+ base_url = source.base_url
+ if not base_url and source.vendor in {"openai", "codex"}:
+ base_url = "https://api.openai.com/v1"
+ if not base_url:
+ raise EngineStateError("Responses API source requires a base URL")
+ entry = {"api-key": api_key, "prefix": source.prefix, "base-url": base_url}
+ if models:
+ entry["models"] = models
+ payload.setdefault("codex-api-key", []).append(entry)
+ return
+ if source.protocol in {"openai_chat", "openai_compatible"}:
+ base_url = source.base_url
+ if not base_url and source.vendor == "openai":
+ base_url = "https://api.openai.com/v1"
+ if not base_url:
+ raise EngineStateError("OpenAI-compatible source requires a base URL")
+ payload.setdefault("openai-compatibility", []).append(
+ {
+ "name": source.prefix,
+ "prefix": source.prefix,
+ "base-url": base_url,
+ "api-key-entries": [{"api-key": api_key}],
+ "models": models,
+ }
+ )
+ return
+ raise EngineStateError("unsupported source protocol")
+
+
+def _secure_write_yaml(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.parent.chmod(0o700)
+ descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ yaml.safe_dump(payload, handle, sort_keys=False, default_flow_style=False)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.chmod(0o600)
+ temporary.replace(path)
+ path.chmod(0o600)
+ finally:
+ temporary.unlink(missing_ok=True)
diff --git a/vibe/model_hub_runtime/environment.py b/vibe/model_hub_runtime/environment.py
new file mode 100644
index 000000000..9814a9b81
--- /dev/null
+++ b/vibe/model_hub_runtime/environment.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+import os
+from typing import Mapping
+
+
+_ENGINE_ENV_ALLOWLIST = frozenset(
+ {
+ "HOME",
+ "LANG",
+ "LC_ALL",
+ "LC_CTYPE",
+ "PATH",
+ "SSL_CERT_DIR",
+ "SSL_CERT_FILE",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "TZ",
+ "USERPROFILE",
+ }
+)
+
+
+def engine_subprocess_environment(
+ base_env: Mapping[str, str] | None = None,
+) -> dict[str, str]:
+ source = os.environ if base_env is None else base_env
+ return {name: source[name] for name in _ENGINE_ENV_ALLOWLIST if name in source}
diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.py
new file mode 100644
index 000000000..1f005efed
--- /dev/null
+++ b/vibe/model_hub_runtime/installer.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from config import paths
+from core.managed_runtime import (
+ ManagedRuntimeManager,
+ ManagedRuntimeManifest,
+ ManagedRuntimeSpec,
+ env_flag_enabled,
+)
+from core.process_isolation import isolated_subprocess_kwargs
+from vibe.model_hub_runtime.environment import engine_subprocess_environment
+
+
+_ENGINE_VERSION_RE = re.compile(r"CLIProxyAPI Version:\s*([\w.-]+)")
+_ENGINE_SPEC = ManagedRuntimeSpec(
+ runtime_id="model_hub_engine",
+ manifest_resource="model_hub_runtime/cliproxyapi_manifest.json",
+ version_field="version",
+ default_bin_path="cli-proxy-api",
+ archives_field="assets",
+ archive_size_field="size_bytes",
+ platform_aliases=(("linux-x64", "linux-amd64"),),
+)
+
+
+class EngineRuntimeManager(ManagedRuntimeManager):
+ """Install and verify the pinned CLIProxyAPI engine dependency."""
+
+ def __init__(
+ self,
+ *,
+ runtime_dir: Path | None = None,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool | None = None,
+ ) -> None:
+ super().__init__(
+ spec=_ENGINE_SPEC,
+ runtime_dir=runtime_dir or paths.get_runtime_dir() / "model-hub" / "engine",
+ manifest_path=manifest_path or os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH"),
+ manifest_url=(
+ manifest_url if manifest_url is not None else os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_URL")
+ ),
+ offline=(env_flag_enabled("VIBE_MODEL_HUB_ENGINE_OFFLINE") if offline is None else offline),
+ )
+
+ def resolve_engine_path(self) -> Path | None:
+ return self.resolve_binary()
+
+ def contract_manifest(self) -> dict[str, Any]:
+ manifest = self._load_manifest(allow_network=False)
+ if manifest is None:
+ return {"name": "cliproxyapi", "version": "", "source_sha": "", "assets": []}
+ payload = manifest.payload
+ return {
+ "name": str(payload.get("name") or ""),
+ "version": manifest.runtime_version,
+ "source_sha": str(payload.get("source_sha") or ""),
+ "assets": [
+ {
+ "platform": asset["platform"],
+ "url": asset["url"],
+ "size_bytes": asset["size_bytes"],
+ "sha256": asset["sha256"],
+ }
+ for asset in payload.get("assets", [])
+ ],
+ }
+
+ def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
+ payload = manifest.payload
+ if not (
+ payload.get("name") == "cliproxyapi"
+ and payload.get("release_tag") == manifest.runtime_version
+ and payload.get("license") == "MIT"
+ and re.fullmatch(r"[0-9a-f]{40}", str(payload.get("source_sha") or ""))
+ ):
+ self._install_reason = "model_hub_engine_manifest_invalid"
+ return False
+ return True
+
+ def _binary_version(self, binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ try:
+ result = subprocess.run(
+ [str(binary), "--help"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ env=engine_subprocess_environment(),
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ match = _ENGINE_VERSION_RE.search(f"{result.stdout}\n{result.stderr}")
+ if match is None:
+ return None
+ return f"v{match.group(1).lstrip('v')}"
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
new file mode 100644
index 000000000..dca835be4
--- /dev/null
+++ b/vibe/model_hub_runtime/state.py
@@ -0,0 +1,517 @@
+from __future__ import annotations
+
+import json
+import os
+import re
+import secrets
+import shutil
+import stat
+import tempfile
+import threading
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Sequence
+from urllib.parse import urlparse
+
+
+_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")
+_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")
+_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "openai_compatible"}
+
+
+class EngineStateError(RuntimeError):
+ pass
+
+
+@dataclass(frozen=True)
+class RuntimeSecrets:
+ management_key: str
+ gateway_token: str
+
+
+@dataclass(frozen=True)
+class SourceRecord:
+ source_id: str
+ vendor: str
+ protocol: str
+ base_url: str | None
+ credential_ref: str
+ allowed_origins: tuple[str, ...]
+ model_ids: tuple[str, ...]
+ prefix: str
+
+ @classmethod
+ def from_payload(cls, payload: dict[str, Any]) -> SourceRecord:
+ return cls(
+ source_id=str(payload["source_id"]),
+ vendor=str(payload["vendor"]),
+ protocol=str(payload["protocol"]),
+ base_url=str(payload["base_url"]) if payload.get("base_url") else None,
+ credential_ref=str(payload["credential_ref"]),
+ allowed_origins=tuple(str(item) for item in payload.get("allowed_origins", [])),
+ model_ids=tuple(str(model) for model in payload.get("model_ids", [])),
+ prefix=str(payload["prefix"]),
+ )
+
+
+class EngineStateStore:
+ """Restricted local state for engine-only keys and upstream credentials."""
+
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ self._lock = threading.RLock()
+
+ @property
+ def auth_dir(self) -> Path:
+ return self.root / "auth"
+
+ def prepare_instance(self, install_id: str, *, rotate: bool = False) -> tuple[Path, RuntimeSecrets]:
+ with self._lock:
+ self._ensure_private_dir(self.root)
+ self.audit_auth_permissions()
+ instance_dir = self.root / "instances" / _safe_identifier(install_id)
+ self._ensure_private_dir(instance_dir)
+ self._remove_obsolete_instances(instance_dir)
+ secrets_path = instance_dir / "runtime-secrets.json"
+ if not rotate:
+ self._assert_private_file(secrets_path, "runtime secret permissions are unsafe")
+ existing = self._read_json(secrets_path)
+ if existing:
+ management_key = existing.get("management_key")
+ gateway_token = existing.get("gateway_token")
+ if isinstance(management_key, str) and isinstance(gateway_token, str):
+ return instance_dir, RuntimeSecrets(management_key, gateway_token)
+ generated = RuntimeSecrets(
+ management_key=secrets.token_urlsafe(48),
+ gateway_token=secrets.token_urlsafe(48),
+ )
+ self._secure_write_json(secrets_path, asdict(generated))
+ return instance_dir, generated
+
+ def list_sources(self) -> list[SourceRecord]:
+ with self._lock:
+ payload = self._read_json(self.root / "sources.json") or {}
+ raw_sources = payload.get("sources", [])
+ if not isinstance(raw_sources, list):
+ raise EngineStateError("invalid engine source state")
+ return [SourceRecord.from_payload(item) for item in raw_sources if isinstance(item, dict)]
+
+ def get_source(self, source_id: str) -> SourceRecord | None:
+ return next((source for source in self.list_sources() if source.source_id == source_id), None)
+
+ def validate_source_id(self, source_id: str) -> None:
+ _validated_source_id(source_id)
+
+ def store_api_key(
+ self,
+ value: str,
+ *,
+ vendor: str = "custom",
+ protocol: str = "openai_compatible",
+ base_url: str | None = None,
+ ) -> str:
+ if not isinstance(value, str) or not value:
+ raise EngineStateError("credential is empty")
+ normalized_vendor = vendor.strip().lower()
+ if not normalized_vendor:
+ raise EngineStateError("credential vendor is empty")
+ if protocol not in _PROTOCOLS:
+ raise EngineStateError("unsupported source protocol")
+ normalized_base_url = _validated_base_url(base_url)
+ with self._lock:
+ credential_ref = f"cred_{secrets.token_hex(16)}"
+ self._secure_write_json(
+ self._credential_path(credential_ref),
+ {
+ "kind": "api_key",
+ "vendor": normalized_vendor,
+ "protocol": protocol,
+ "base_url": normalized_base_url,
+ "value": value,
+ },
+ )
+ return credential_ref
+
+ def bind_oauth_credential(self, source_id: str, vendor: str, auth_name: str) -> str:
+ _validated_source_id(source_id)
+ if not vendor.strip() or not auth_name.strip():
+ raise EngineStateError("OAuth credential binding is incomplete")
+ normalized_vendor = vendor.strip().lower()
+ normalized_auth_name = auth_name.strip()
+ with self._lock:
+ matches = [
+ (credential_ref, payload)
+ for credential_ref, payload in self._oauth_credentials()
+ if payload.get("auth_name") == normalized_auth_name
+ ]
+ if matches:
+ if len(matches) != 1:
+ raise EngineStateError("OAuth auth record binding is ambiguous")
+ credential_ref, payload = matches[0]
+ if payload.get("source_id") != source_id or payload.get("vendor") != normalized_vendor:
+ raise EngineStateError("OAuth auth record is already bound to another source")
+ return credential_ref
+ credential_ref = f"cred_{secrets.token_hex(16)}"
+ prefix = f"avibe-{secrets.token_hex(12)}"
+ self._secure_write_json(
+ self._credential_path(credential_ref),
+ {
+ "kind": "oauth",
+ "source_id": source_id,
+ "vendor": normalized_vendor,
+ "auth_name": normalized_auth_name,
+ "prefix": prefix,
+ },
+ )
+ return credential_ref
+
+ def sync_sources(self, bindings: Sequence[Any]) -> list[SourceRecord]:
+ """Atomically replace the engine projection using opaque credential refs."""
+ with self._lock:
+ existing = {source.source_id: source for source in self.list_sources()}
+ records: list[SourceRecord] = []
+ seen: set[str] = set()
+ for binding in bindings:
+ source_id = _validated_source_id(str(binding.source_id))
+ if source_id in seen:
+ raise EngineStateError("duplicate source binding")
+ seen.add(source_id)
+ credential_ref = str(binding.credential_ref)
+ credential = self.credential_metadata(credential_ref)
+ protocol = str(binding.protocol)
+ if protocol not in _PROTOCOLS:
+ raise EngineStateError("unsupported source protocol")
+ vendor = str(binding.vendor).strip().lower()
+ base_url = _validated_base_url(binding.base_url)
+ _validate_source_target(vendor, protocol, base_url)
+ if credential["kind"] == "api_key":
+ if (
+ credential.get("vendor") != vendor
+ or credential.get("protocol") != protocol
+ or credential.get("base_url") != base_url
+ ):
+ raise EngineStateError("credential does not match source binding")
+ elif (
+ credential.get("source_id") != source_id
+ or credential.get("vendor") != vendor
+ or base_url is not None
+ ):
+ raise EngineStateError("OAuth credential does not match source binding")
+ allowed_origins = tuple(dict.fromkeys(str(origin).strip() for origin in binding.allowed_origins))
+ if any(not origin for origin in allowed_origins):
+ raise EngineStateError("allowed origin cannot be empty")
+ if credential["kind"] == "oauth" and not allowed_origins:
+ raise EngineStateError("OAuth source requires at least one allowed origin")
+ previous = existing.get(source_id)
+ model_ids = tuple(dict.fromkeys(str(model).strip() for model in binding.model_ids))
+ if not model_ids:
+ raise EngineStateError("source requires at least one model id")
+ if any(not model for model in model_ids):
+ raise EngineStateError("model id cannot be empty")
+ records.append(
+ SourceRecord(
+ source_id=source_id,
+ vendor=vendor,
+ protocol=protocol,
+ base_url=base_url,
+ credential_ref=credential_ref,
+ allowed_origins=allowed_origins,
+ model_ids=model_ids,
+ prefix=(
+ str(credential["prefix"])
+ if credential.get("prefix")
+ else previous.prefix
+ if previous
+ else f"avibe-{secrets.token_hex(12)}"
+ ),
+ )
+ )
+ self._write_sources(records)
+ return records
+
+ def replace_sources(self, sources: Sequence[SourceRecord]) -> None:
+ """Restore a previously validated source projection."""
+ with self._lock:
+ self._write_sources(sources)
+
+ def set_models(self, source_id: str, model_ids: Sequence[str]) -> SourceRecord:
+ with self._lock:
+ sources = self.list_sources()
+ current = next((source for source in sources if source.source_id == source_id), None)
+ if current is None:
+ raise EngineStateError("source is not registered")
+ models = tuple(dict.fromkeys(str(model).strip() for model in model_ids))
+ if not models:
+ raise EngineStateError("source requires at least one model id")
+ if any(not model for model in models):
+ raise EngineStateError("model id cannot be empty")
+ updated_record = SourceRecord(**{**asdict(current), "model_ids": models})
+ self._write_sources([updated_record if source.source_id == source_id else source for source in sources])
+ return updated_record
+
+ def credential_metadata(self, credential_ref: str) -> dict[str, Any]:
+ path = self._credential_path(credential_ref)
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ mode = 0
+ if mode and (not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600):
+ raise EngineStateError("credential permissions are unsafe")
+ payload = self._read_json(path)
+ kind = payload.get("kind") if payload else None
+ if kind not in {"api_key", "oauth"}:
+ raise EngineStateError("credential is unavailable")
+ return payload
+
+ def validate_api_key_target(
+ self,
+ credential_ref: str,
+ *,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ ) -> str | None:
+ metadata = self.credential_metadata(credential_ref)
+ normalized_base_url = _validated_base_url(base_url)
+ if (
+ metadata["kind"] != "api_key"
+ or metadata.get("vendor") != vendor.strip().lower()
+ or metadata.get("protocol") != protocol
+ or metadata.get("base_url") != normalized_base_url
+ ):
+ raise EngineStateError("credential does not match discovery target")
+ return normalized_base_url
+
+ def assert_credential_unbound(self, credential_ref: str) -> None:
+ if any(source.credential_ref == credential_ref for source in self.list_sources()):
+ raise EngineStateError("credential is still bound to a source")
+
+ def revoke_credential(self, credential_ref: str) -> None:
+ with self._lock:
+ self.assert_credential_unbound(credential_ref)
+ path = self._credential_path(credential_ref)
+ if not path.exists():
+ return
+ self.credential_metadata(credential_ref)
+ path.unlink()
+
+ def clear_runtime_configs(self) -> None:
+ """Remove persisted engine configs after any credential is revoked."""
+ with self._lock:
+ self._ensure_private_dir(self.root)
+ instances_dir = self.root / "instances"
+ if not instances_dir.exists():
+ return
+ self._ensure_private_dir(instances_dir)
+ for instance_dir in instances_dir.iterdir():
+ mode = instance_dir.lstat().st_mode
+ if not stat.S_ISDIR(mode):
+ raise EngineStateError("engine instance directory is unsafe")
+ config_path = instance_dir / "config.yaml"
+ try:
+ config_mode = config_path.lstat().st_mode
+ except FileNotFoundError:
+ continue
+ if not stat.S_ISREG(config_mode):
+ raise EngineStateError("engine config path is unsafe")
+ config_path.unlink()
+
+ def read_api_key(self, credential_ref: str) -> str:
+ payload = self.credential_metadata(credential_ref)
+ value = payload.get("value") if payload.get("kind") == "api_key" else None
+ if not isinstance(value, str) or not value:
+ raise EngineStateError("API key credential is unavailable")
+ return value
+
+ def oauth_auth_name(self, credential_ref: str) -> str | None:
+ payload = self.credential_metadata(credential_ref)
+ value = payload.get("auth_name") if payload.get("kind") == "oauth" else None
+ return str(value) if value else None
+
+ def oauth_credential_ref(self, auth_name: str) -> str | None:
+ normalized = auth_name.strip()
+ with self._lock:
+ matches = [
+ credential_ref
+ for credential_ref, payload in self._oauth_credentials()
+ if payload.get("auth_name") == normalized
+ ]
+ if len(matches) > 1:
+ raise EngineStateError("OAuth auth record binding is ambiguous")
+ return matches[0] if matches else None
+
+ def delete_oauth_auth_file(self, auth_name: str) -> None:
+ """Delete one managed OAuth file without requiring a running engine."""
+ normalized = auth_name.strip()
+ if (
+ not normalized
+ or "\x00" in normalized
+ or "\\" in normalized
+ or Path(normalized).name != normalized
+ or not normalized.lower().endswith(".json")
+ ):
+ raise EngineStateError("invalid OAuth auth file name")
+ with self._lock:
+ self.audit_auth_permissions(enforce=True)
+ path = self.auth_dir / normalized
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ return
+ if not stat.S_ISREG(mode):
+ raise EngineStateError("engine auth credential path is unsafe")
+ path.unlink()
+
+ def audit_auth_permissions(self, *, enforce: bool = False) -> None:
+ self._ensure_private_dir(self.root)
+ if not self.auth_dir.exists():
+ self.auth_dir.mkdir(parents=True, mode=0o700)
+ auth_mode = self.auth_dir.lstat().st_mode
+ if not stat.S_ISDIR(auth_mode):
+ raise EngineStateError("engine auth directory is unsafe")
+ if stat.S_IMODE(self.auth_dir.stat().st_mode) != 0o700:
+ raise EngineStateError("engine auth directory permissions are unsafe")
+ for entry in self.auth_dir.iterdir():
+ mode = entry.lstat().st_mode
+ if not stat.S_ISREG(mode):
+ raise EngineStateError("engine auth directory contains an unsafe entry")
+ if stat.S_IMODE(mode) == 0o600:
+ continue
+ if not enforce:
+ raise EngineStateError("engine auth credential permissions are unsafe")
+ entry.chmod(0o600)
+
+ def _credential_path(self, credential_ref: str) -> Path:
+ if _CREDENTIAL_REF_RE.fullmatch(credential_ref) is None:
+ raise EngineStateError("invalid credential reference")
+ self._ensure_private_dir(self.root)
+ credentials_dir = self.root / "credentials"
+ self._ensure_private_dir(credentials_dir)
+ return credentials_dir / f"{credential_ref}.json"
+
+ def _oauth_credentials(self) -> list[tuple[str, dict[str, Any]]]:
+ self._ensure_private_dir(self.root)
+ credentials_dir = self.root / "credentials"
+ self._ensure_private_dir(credentials_dir)
+ result: list[tuple[str, dict[str, Any]]] = []
+ for path in credentials_dir.glob("cred_*.json"):
+ mode = path.lstat().st_mode
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise EngineStateError("credential permissions are unsafe")
+ credential_ref = path.stem
+ if path.suffix != ".json" or _CREDENTIAL_REF_RE.fullmatch(credential_ref) is None:
+ raise EngineStateError("credential state contains an unsafe entry")
+ payload = self._read_json(path)
+ if payload and payload.get("kind") == "oauth":
+ result.append((credential_ref, payload))
+ return result
+
+ def _write_sources(self, sources: Sequence[SourceRecord]) -> None:
+ self._secure_write_json(
+ self.root / "sources.json",
+ {
+ "sources": [
+ {
+ **asdict(source),
+ "allowed_origins": list(source.allowed_origins),
+ "model_ids": list(source.model_ids),
+ }
+ for source in sources
+ ]
+ },
+ )
+
+ def _remove_obsolete_instances(self, active_instance: Path) -> None:
+ instances_dir = active_instance.parent
+ self._ensure_private_dir(instances_dir)
+ for instance_dir in instances_dir.iterdir():
+ if instance_dir == active_instance:
+ continue
+ mode = instance_dir.lstat().st_mode
+ if not stat.S_ISDIR(mode):
+ raise EngineStateError("engine instance directory is unsafe")
+ shutil.rmtree(instance_dir)
+
+ @staticmethod
+ def _read_json(path: Path) -> dict[str, Any] | None:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError) as exc:
+ raise EngineStateError(f"invalid engine state file: {path.name}") from exc
+ if not isinstance(payload, dict):
+ raise EngineStateError(f"invalid engine state file: {path.name}")
+ return payload
+
+ @classmethod
+ def _secure_write_json(cls, path: Path, payload: dict[str, Any]) -> None:
+ cls._ensure_private_dir(path.parent)
+ descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, sort_keys=True)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.chmod(0o600)
+ temporary.replace(path)
+ path.chmod(0o600)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ @staticmethod
+ def _ensure_private_dir(path: Path) -> None:
+ if path.exists():
+ if not stat.S_ISDIR(path.lstat().st_mode):
+ raise EngineStateError("engine state path is unsafe")
+ else:
+ path.mkdir(parents=True, mode=0o700)
+ path.chmod(0o700)
+
+ @staticmethod
+ def _assert_private_file(path: Path, message: str) -> None:
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ return
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise EngineStateError(message)
+
+
+def _safe_identifier(value: str) -> str:
+ cleaned = "".join(character if character.isalnum() or character in "._-" else "_" for character in value)
+ return cleaned or "unknown"
+
+
+def _validated_source_id(value: str) -> str:
+ if _SOURCE_ID_RE.fullmatch(value) is None:
+ raise EngineStateError("invalid source id")
+ return value
+
+
+def _validated_base_url(value: str | None) -> str | None:
+ if value is None:
+ return None
+ normalized = str(value).strip().rstrip("/")
+ parsed = urlparse(normalized)
+ if (
+ parsed.scheme not in {"http", "https"}
+ or not parsed.netloc
+ or parsed.username
+ or parsed.password
+ or parsed.query
+ or parsed.fragment
+ ):
+ raise EngineStateError("invalid source base URL")
+ return normalized
+
+
+def _validate_source_target(vendor: str, protocol: str, base_url: str | None) -> None:
+ if protocol == "anthropic" and base_url is None and vendor != "anthropic":
+ raise EngineStateError("Anthropic-compatible source requires a base URL")
+ if protocol == "openai_responses" and base_url is None and vendor not in {"openai", "codex"}:
+ raise EngineStateError("Responses API source requires a base URL")
+ if protocol in {"openai_chat", "openai_compatible"} and base_url is None and vendor != "openai":
+ raise EngineStateError("OpenAI-compatible source requires a base URL")
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
new file mode 100644
index 000000000..4738a0926
--- /dev/null
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -0,0 +1,242 @@
+from __future__ import annotations
+
+import atexit
+import logging
+import signal
+import socket
+import subprocess
+import threading
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+from config import paths
+from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+from vibe.model_hub_runtime.client import EngineClient, EngineConnection
+from vibe.model_hub_runtime.config import write_engine_config
+from vibe.model_hub_runtime.environment import engine_subprocess_environment
+from vibe.model_hub_runtime.installer import EngineRuntimeManager
+from vibe.model_hub_runtime.state import EngineStateStore
+
+
+logger = logging.getLogger(__name__)
+
+
+class EngineUnavailableError(RuntimeError):
+ """The Hub path is unavailable; callers may use explicitly configured Direct mode."""
+
+ def __init__(self, error_key: str, *, reason: str | None = None) -> None:
+ super().__init__(error_key)
+ self.error_key = error_key
+ self.reason = reason
+ self.direct_mode_available = True
+
+
+class EngineSupervisor:
+ """Start-on-demand supervisor for one loopback-only Model Hub engine."""
+
+ def __init__(
+ self,
+ *,
+ installer: EngineRuntimeManager | Any | None = None,
+ state_store: EngineStateStore | None = None,
+ startup_timeout: float = 10.0,
+ process_factory: Callable[..., subprocess.Popen[bytes]] = subprocess.Popen,
+ port_allocator: Callable[[], int] | None = None,
+ ) -> None:
+ self.installer = installer or EngineRuntimeManager()
+ self.state_store = state_store or EngineStateStore(paths.get_runtime_dir() / "model-hub" / "state")
+ self.startup_timeout = startup_timeout
+ self._process_factory = process_factory
+ self._port_allocator = port_allocator or _allocate_loopback_port
+ self._lock = threading.RLock()
+ self._process: subprocess.Popen[bytes] | None = None
+ self._connection: EngineConnection | None = None
+ self._last_check: str | None = None
+
+ def ensure_running(self) -> EngineConnection:
+ with self._lock:
+ if self._is_running_locked() and self._healthy_locked():
+ assert self._connection is not None
+ return self._connection
+ self._stop_locked()
+ return self._start_locked()
+
+ def stop(self) -> None:
+ with self._lock:
+ self._stop_locked()
+
+ def restart_if_running(self) -> None:
+ with self._lock:
+ if not self._is_running_locked():
+ return
+ self._stop_locked()
+ self._start_locked()
+
+ def invalidate_configs(self) -> None:
+ """Remove secret-bearing configs and recreate one only for a live engine."""
+ with self._lock:
+ should_restart = self._is_running_locked() and self._healthy_locked()
+ if self._is_running_locked():
+ self._stop_locked()
+ self.state_store.clear_runtime_configs()
+ if should_restart:
+ try:
+ self._start_locked()
+ except EngineUnavailableError:
+ logger.warning("Model Hub engine remains stopped after credential revocation")
+
+ def status(self) -> dict[str, Any]:
+ with self._lock:
+ managed = self.installer.status()
+ installed = bool(managed.get("installed"))
+ listening = None
+ if self._is_running_locked() and self._connection is not None:
+ parsed_port = int(self._connection.base_url.rsplit(":", 1)[1])
+ listening = {"host": "127.0.0.1", "port": parsed_port}
+ health = "ok" if self._healthy_locked() else "degraded"
+ elif installed:
+ health = "down"
+ else:
+ health = "not_installed"
+ return {
+ "manifest": self.installer.contract_manifest(),
+ "status": {
+ "installed_version": managed.get("version") if installed else None,
+ "verified": installed,
+ "listening": listening,
+ "health": health,
+ "last_check": self._last_check,
+ },
+ }
+
+ def client(self) -> EngineClient:
+ return EngineClient(self.ensure_running())
+
+ def client_if_running(self) -> EngineClient | None:
+ """Return a client for the current process without starting or repairing it."""
+ with self._lock:
+ if not self._is_running_locked() or self._connection is None:
+ return None
+ return EngineClient(self._connection)
+
+ def _start_locked(self) -> EngineConnection:
+ install = self.installer.ensure()
+ if not install.get("ok"):
+ reason = str(install.get("reason") or "engine_install_failed")
+ raise EngineUnavailableError("models.engine.install_failed", reason=reason)
+ binary = Path(str(install["path"]))
+ install_id = Path(str(install.get("install_dir") or binary.parent)).name
+ instance_dir, runtime_secrets = self.state_store.prepare_instance(
+ install_id,
+ rotate=bool(install.get("changed")),
+ )
+ port = self._port_allocator()
+ config_path = instance_dir / "config.yaml"
+ write_engine_config(
+ config_path,
+ host="127.0.0.1",
+ port=port,
+ auth_dir=self.state_store.auth_dir,
+ runtime_secrets=runtime_secrets,
+ sources=self.state_store.list_sources(),
+ state_store=self.state_store,
+ )
+ connection = EngineConnection(
+ base_url=f"http://127.0.0.1:{port}",
+ management_key=runtime_secrets.management_key,
+ gateway_token=runtime_secrets.gateway_token,
+ )
+ try:
+ process = self._process_factory(
+ [str(binary), "-config", str(config_path)],
+ cwd=instance_dir,
+ env=engine_subprocess_environment(),
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ umask=0o077,
+ **isolated_subprocess_kwargs(),
+ )
+ except (OSError, ValueError) as exc:
+ raise EngineUnavailableError("models.engine.start_failed") from exc
+ self._process = process
+ self._connection = connection
+ deadline = time.monotonic() + self.startup_timeout
+ client = EngineClient(connection, timeout=1.0)
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ break
+ if client.health():
+ try:
+ self.state_store.audit_auth_permissions()
+ except Exception as exc:
+ self._stop_locked()
+ raise EngineUnavailableError("models.engine.unsafe_permissions") from exc
+ self._last_check = _utc_now()
+ logger.info("Model Hub engine started on 127.0.0.1 with managed version %s", install.get("version"))
+ return connection
+ time.sleep(0.05)
+ self._stop_locked()
+ raise EngineUnavailableError("models.engine.health_failed")
+
+ def _healthy_locked(self) -> bool:
+ if not self._is_running_locked() or self._connection is None:
+ return False
+ healthy = EngineClient(self._connection, timeout=1.0).health()
+ self._last_check = _utc_now()
+ return healthy
+
+ def _is_running_locked(self) -> bool:
+ return self._process is not None and self._process.poll() is None
+
+ def _stop_locked(self) -> None:
+ process = self._process
+ self._process = None
+ self._connection = None
+ if process is None or process.poll() is not None:
+ return
+ signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")
+ try:
+ process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ signal_process_tree(process, KILL_SIGNAL, logger, "Model Hub engine")
+ process.wait(timeout=3)
+
+
+def _allocate_loopback_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
+ listener.bind(("127.0.0.1", 0))
+ return int(listener.getsockname()[1])
+
+
+def _utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+_supervisor: EngineSupervisor | None = None
+
+
+def get_engine_supervisor() -> EngineSupervisor:
+ global _supervisor
+ if _supervisor is None:
+ _supervisor = EngineSupervisor()
+ return _supervisor
+
+
+def set_engine_supervisor_for_tests(supervisor: EngineSupervisor | None) -> None:
+ global _supervisor
+ if _supervisor is not None and _supervisor is not supervisor:
+ _supervisor.stop()
+ _supervisor = supervisor
+
+
+def stop_engine_supervisor() -> None:
+ global _supervisor
+ if _supervisor is not None:
+ _supervisor.stop()
+ _supervisor = None
+
+
+atexit.register(stop_engine_supervisor)