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 native config migration (#975)

Call White5921ad39294d
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
new file mode 100644
index 000000000..129ba5e2b
--- /dev/null
+++ b/core/handlers/model_hub/migration.py
@@ -0,0 +1,723 @@
+"""Read-only native-config discovery and copy-only Model Hub migration."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import os
+import re
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Awaitable, Callable, Literal, Optional, Protocol
+
+from config.v2_config import (
+ ModelHubConfig,
+ ModelHubModelConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+ ModelHubSourceUsageConfig,
+)
+from core.handlers.model_hub.events import contains_credential_material
+from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog
+from vibe.claude_config import read_claude_oauth_signed_in, read_claude_settings_env
+from vibe.codex_config import _load_auth, get_codex_config_paths, read_codex_auth_state
+from vibe.opencode_config import (
+ get_opencode_custom_provider_adapter,
+ load_first_opencode_user_config,
+ read_opencode_provider_auth_entries,
+)
+
+MigrationAction = Literal["import", "controlled_import", "keep_native", "reauth"]
+MigrationKind = Literal["api_key", "oauth_native", "opencode_provider"]
+_CUSTOM_ENDPOINT_NOTE = "settings.models.source.customEndpoint"
+_NATIVE_SUPPLY_NOTE = "settings.models.source.nativeSupply"
+_OPENCODE_BUILTIN_PROTOCOLS: dict[
+ str,
+ Literal["anthropic", "openai_compatible"],
+] = {
+ "deepseek": "openai_compatible",
+ "minimax": "anthropic",
+ "openrouter": "openai_compatible",
+}
+_OPENCODE_UNSUPPORTED_NATIVE_IDS = {"alibaba-cn", "poe"}
+
+
+class MigrationConflictError(ValueError):
+ pass
+
+
+class MigrationHost(Protocol):
+ store: Any
+ adapter: Any
+ _mutation_lock: Any
+ now: Callable[[], datetime]
+ migration_claude_oauth_probe: Optional[Callable[[], bool]]
+
+ @staticmethod
+ def _clone_config(config: ModelHubConfig) -> ModelHubConfig: ...
+
+ async def _engine_call(self, awaitable: Awaitable[Any]) -> Any: ...
+
+ async def _commit_synced(
+ self,
+ previous: ModelHubConfig,
+ updated: ModelHubConfig,
+ ) -> None: ...
+
+ async def _rollback_credential(
+ self,
+ source_id: str,
+ credential_ref: str,
+ ) -> None: ...
+
+ def _apply_discovered_models(
+ self,
+ source: ModelHubSourceConfig,
+ manual_models: list[ModelHubModelConfig],
+ discovered: list[str],
+ ) -> None: ...
+
+
+@dataclass(frozen=True)
+class NativeManualModel:
+ id: str
+ display_name: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class NativeMigrationItem:
+ id: str
+ source_id: str
+ backend: Literal["claude", "codex", "opencode"]
+ kind: MigrationKind
+ masked_detail: str
+ proposed_action: MigrationAction
+ selected: bool
+ notes_key: Optional[str]
+ vendor: str
+ protocol: Literal[
+ "anthropic",
+ "openai_responses",
+ "openai_chat",
+ "openai_compatible",
+ ]
+ display_name: str
+ base_url: Optional[str] = None
+ secret: Optional[str] = field(default=None, repr=False)
+ account_label: Optional[str] = None
+ manual_models: tuple[NativeManualModel, ...] = ()
+
+ def to_payload(self) -> dict[str, object]:
+ return {
+ "id": self.id,
+ "backend": self.backend,
+ "kind": self.kind,
+ "masked_detail": self.masked_detail,
+ "proposed_action": self.proposed_action,
+ "selected": self.selected,
+ "notes_key": self.notes_key,
+ }
+
+
+def _stable_suffix(*parts: str) -> str:
+ identity = "\0".join(parts).encode("utf-8")
+ return hashlib.sha256(identity).hexdigest()[:16]
+
+
+def _ids(
+ backend: str,
+ kind: str,
+ identity: str,
+ action: MigrationAction,
+ version: str = "",
+) -> tuple[str, str]:
+ source_id = f"src_{_stable_suffix('source', backend, kind, identity)}"
+ item_id = f"mig_{_stable_suffix('item', backend, kind, identity, action, version)}"
+ return item_id, source_id
+
+
+def _native_model_ids(backend: str) -> tuple[str, ...]:
+ catalog = load_bundled_catalog()
+ return tuple(entry["id"] for entry in backend_model_entries(backend, catalog))
+
+
+def _safe_account_label(value: object) -> Optional[str]:
+ if not isinstance(value, str):
+ return None
+ candidate = value.strip()
+ if (
+ not candidate
+ or len(candidate) > 64
+ or re.fullmatch(r"[^@\s]+@[^@\s]+", candidate) is None
+ or contains_credential_material(candidate)
+ ):
+ return None
+ return candidate
+
+
+def _claude_items(
+ *,
+ home: Optional[Path],
+ mask_credential: Callable[[str], str],
+ oauth_probe: Optional[Callable[[], bool]],
+) -> list[NativeMigrationItem]:
+ items: list[NativeMigrationItem] = []
+ env = read_claude_settings_env(home)
+ api_key = env.get("ANTHROPIC_API_KEY")
+ auth_token = env.get("ANTHROPIC_AUTH_TOKEN")
+ base_url = env.get("ANTHROPIC_BASE_URL")
+ if api_key:
+ action: MigrationAction = "import"
+ item_id, source_id = _ids(
+ "claude",
+ "api_key",
+ "settings-env",
+ action,
+ _stable_suffix(api_key, base_url or ""),
+ )
+ detail = mask_credential(api_key)
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="claude",
+ kind="api_key",
+ masked_detail=detail,
+ proposed_action=action,
+ selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="anthropic",
+ protocol="anthropic",
+ display_name="Anthropic",
+ base_url=base_url,
+ secret=api_key,
+ )
+ )
+
+ if auth_token:
+ action = "reauth"
+ item_id, source_id = _ids(
+ "claude",
+ "api_key",
+ "settings-auth-token",
+ action,
+ _stable_suffix(auth_token, base_url or ""),
+ )
+ detail = mask_credential(auth_token)
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="claude",
+ kind="api_key",
+ masked_detail=detail,
+ proposed_action=action,
+ selected=False,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="anthropic",
+ protocol="anthropic",
+ display_name="Anthropic",
+ base_url=base_url,
+ )
+ )
+
+ # Claude settings env takes precedence over the native OAuth store. A
+ # leftover OAuth credential must not outrank the auth the CLI will use.
+ if api_key or auth_token:
+ return items
+
+ oauth_signed_in = read_claude_oauth_signed_in(home)
+ if not oauth_signed_in and oauth_probe is not None:
+ try:
+ oauth_signed_in = bool(oauth_probe())
+ except Exception:
+ oauth_signed_in = False
+ if oauth_signed_in:
+ action = "keep_native"
+ item_id, source_id = _ids("claude", "oauth_native", "oauth", action)
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="claude",
+ kind="oauth_native",
+ masked_detail="",
+ proposed_action=action,
+ selected=True,
+ notes_key=_NATIVE_SUPPLY_NOTE,
+ vendor="anthropic",
+ protocol="anthropic",
+ display_name="Claude",
+ )
+ )
+ return items
+
+
+def _codex_items(
+ *,
+ home: Optional[Path],
+ mask_credential: Callable[[str], str],
+) -> list[NativeMigrationItem]:
+ _, auth_path = get_codex_config_paths(home)
+ auth_data = _load_auth(auth_path)
+ if not isinstance(auth_data, dict):
+ return []
+ state = read_codex_auth_state(home)
+ items: list[NativeMigrationItem] = []
+ raw_auth_mode = auth_data.get("auth_mode")
+ auth_mode = raw_auth_mode.strip().lower() if isinstance(raw_auth_mode, str) else None
+
+ api_key = auth_data.get("OPENAI_API_KEY")
+ has_api_key = isinstance(api_key, str) and bool(api_key.strip())
+ importable_api_key = state.get("file_store_active") is True and has_api_key
+ api_key_is_active = auth_mode != "chatgpt" and importable_api_key
+ oauth_is_active = auth_mode == "chatgpt" or (
+ auth_mode != "apikey" and not importable_api_key
+ )
+ if api_key_is_active:
+ assert isinstance(api_key, str)
+ api_key = api_key.strip()
+ base_url = state.get("base_url")
+ if not isinstance(base_url, str) or not base_url.strip():
+ base_url = None
+ wire_api = state.get("wire_api")
+ protocol = "openai_chat" if wire_api == "chat" else "openai_responses"
+ item_id, source_id = _ids(
+ "codex",
+ "api_key",
+ "auth-json-api-key",
+ "import",
+ _stable_suffix(api_key, base_url or "", protocol),
+ )
+ detail = mask_credential(api_key)
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="codex",
+ kind="api_key",
+ masked_detail=detail,
+ proposed_action="import",
+ selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="openai",
+ protocol=protocol,
+ display_name="OpenAI",
+ base_url=base_url,
+ secret=api_key,
+ )
+ )
+
+ tokens = auth_data.get("tokens")
+ if not oauth_is_active or not isinstance(tokens, dict) or not any(
+ isinstance(tokens.get(key), str) and bool(tokens[key].strip())
+ for key in ("access_token", "refresh_token", "id_token")
+ ):
+ return items
+
+ action: MigrationAction = "keep_native"
+ item_id, source_id = _ids(
+ "codex",
+ "oauth_native",
+ "auth-json",
+ action,
+ )
+ account = state.get("chatgpt_account")
+ account_label = _safe_account_label(account.get("email") if isinstance(account, dict) else None)
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="codex",
+ kind="oauth_native",
+ masked_detail=account_label or "",
+ proposed_action=action,
+ selected=True,
+ notes_key=_NATIVE_SUPPLY_NOTE,
+ vendor="openai",
+ protocol="openai_responses",
+ display_name="ChatGPT",
+ account_label=account_label,
+ )
+ )
+ return items
+
+
+def _load_opencode_provider_catalog(home: Optional[Path]) -> dict[str, dict[str, Any]]:
+ if home is not None:
+ path = home / ".cache" / "opencode" / "models.json"
+ else:
+ cache_home = os.environ.get("XDG_CACHE_HOME")
+ path = (
+ Path(cache_home).expanduser() / "opencode" / "models.json"
+ if cache_home
+ else Path.home() / ".cache" / "opencode" / "models.json"
+ )
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return {}
+ if not isinstance(payload, dict):
+ return {}
+ return {
+ provider_id.strip().lower(): provider
+ for provider_id, provider in payload.items()
+ if isinstance(provider_id, str) and provider_id.strip() and isinstance(provider, dict)
+ }
+
+
+def _opencode_protocol(
+ provider_id: str,
+ provider_config: dict[str, Any],
+ catalog_provider: dict[str, Any],
+) -> Optional[Literal["anthropic", "openai_responses", "openai_compatible"]]:
+ if provider_id == "anthropic":
+ return "anthropic"
+ if provider_id == "openai":
+ return "openai_responses"
+ custom_adapter = get_opencode_custom_provider_adapter(provider_id, provider_config)
+ if custom_adapter == "anthropic-compatible":
+ return "anthropic"
+ if custom_adapter == "openai-compatible":
+ return "openai_compatible"
+ builtin_protocol = _OPENCODE_BUILTIN_PROTOCOLS.get(provider_id)
+ if builtin_protocol is not None:
+ return builtin_protocol
+ npm = provider_config.get("npm") or catalog_provider.get("npm")
+ if npm == "@ai-sdk/anthropic":
+ return "anthropic"
+ if npm == "@ai-sdk/openai":
+ return "openai_responses"
+ if npm in {"@ai-sdk/openai-compatible", "@openrouter/ai-sdk-provider"}:
+ return "openai_compatible"
+ return None
+
+
+def _opencode_manual_models(
+ provider_config: dict[str, Any],
+) -> tuple[NativeManualModel, ...]:
+ raw_models = provider_config.get("models")
+ if not isinstance(raw_models, dict):
+ return ()
+ models: list[NativeManualModel] = []
+ for model_id, model_config in raw_models.items():
+ if (
+ not isinstance(model_id, str)
+ or not model_id.strip()
+ or contains_credential_material(model_id.strip())
+ ):
+ continue
+ raw_name = model_config.get("name") if isinstance(model_config, dict) else None
+ display_name = raw_name.strip() if isinstance(raw_name, str) and raw_name.strip() else None
+ if display_name and contains_credential_material(display_name):
+ display_name = None
+ models.append(
+ NativeManualModel(
+ id=model_id.strip(),
+ display_name=display_name,
+ )
+ )
+ return tuple(models)
+
+
+def _opencode_plaintext_key(value: object) -> Optional[str]:
+ if not isinstance(value, str) or not value.strip():
+ return None
+ candidate = value.strip()
+ if re.fullmatch(r"\{env:[^{}]+\}", candidate):
+ return None
+ return candidate
+
+
+def _opencode_items(
+ *,
+ home: Optional[Path],
+ mask_credential: Callable[[str], str],
+) -> list[NativeMigrationItem]:
+ probe = load_first_opencode_user_config(home=home)
+ provider_configs: dict[str, dict[str, Any]] = {}
+ if isinstance(probe.config, dict):
+ raw_providers = probe.config.get("provider")
+ if isinstance(raw_providers, dict):
+ provider_configs = {
+ provider_id.strip().lower(): provider_config
+ for provider_id, provider_config in raw_providers.items()
+ if isinstance(provider_id, str) and provider_id.strip() and isinstance(provider_config, dict)
+ }
+ auth_entries = {
+ provider_id.strip().lower(): entry
+ for provider_id, entry in read_opencode_provider_auth_entries(home=home).items()
+ if provider_id.strip()
+ }
+ provider_catalog = _load_opencode_provider_catalog(home)
+ provider_ids = set(provider_configs) | set(auth_entries)
+ items: list[NativeMigrationItem] = []
+ for provider_id in sorted(provider_ids):
+ if (
+ not provider_id
+ or len(provider_id) > 64
+ or any(char not in "abcdefghijklmnopqrstuvwxyz0123456789_.-" for char in provider_id)
+ or not provider_id[0].isalnum()
+ or contains_credential_material(provider_id)
+ ):
+ continue
+ if provider_id in _OPENCODE_UNSUPPORTED_NATIVE_IDS:
+ continue
+ provider_config = provider_configs.get(provider_id, {})
+ options = provider_config.get("options")
+ if not isinstance(options, dict):
+ options = {}
+ config_key = _opencode_plaintext_key(options.get("apiKey"))
+ auth_entry = auth_entries.get(provider_id, {})
+ auth_key = (
+ _opencode_plaintext_key(auth_entry.get("key"))
+ if auth_entry.get("type") == "api"
+ else None
+ )
+ secret = config_key or auth_key
+ if secret is None:
+ continue
+ raw_base_url = options.get("baseURL")
+ base_url = raw_base_url.strip() if isinstance(raw_base_url, str) and raw_base_url.strip() else None
+ catalog_provider = provider_catalog.get(provider_id, {})
+ if base_url is None:
+ catalog_api = catalog_provider.get("api")
+ if isinstance(catalog_api, str) and catalog_api.strip():
+ base_url = catalog_api.strip()
+ protocol = _opencode_protocol(provider_id, provider_config, catalog_provider)
+ if protocol is None:
+ continue
+ if base_url is None and provider_id not in {"anthropic", "openai"}:
+ continue
+ manual_models = _opencode_manual_models(provider_config)
+ action: MigrationAction = "import"
+ item_id, source_id = _ids(
+ "opencode",
+ "opencode_provider",
+ provider_id,
+ action,
+ _stable_suffix(
+ secret,
+ base_url or "",
+ protocol,
+ *(f"{model.id}\0{model.display_name or ''}" for model in manual_models),
+ ),
+ )
+ detail = f"{provider_id} · {mask_credential(secret)}"
+ items.append(
+ NativeMigrationItem(
+ id=item_id,
+ source_id=source_id,
+ backend="opencode",
+ kind="opencode_provider",
+ masked_detail=detail,
+ proposed_action=action,
+ selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor=provider_id,
+ protocol=protocol,
+ display_name=provider_id,
+ base_url=base_url,
+ secret=secret,
+ manual_models=manual_models,
+ )
+ )
+ return items
+
+
+def scan_native_configs(
+ config: ModelHubConfig,
+ *,
+ mask_credential: Callable[[str], str],
+ home: Optional[Path] = None,
+ claude_oauth_probe: Optional[Callable[[], bool]] = None,
+ validate_base_url: Optional[Callable[[object], Optional[str]]] = None,
+) -> list[NativeMigrationItem]:
+ """Read native stores without modifying or deleting any path."""
+
+ items = [
+ *_claude_items(
+ home=home,
+ mask_credential=mask_credential,
+ oauth_probe=claude_oauth_probe,
+ ),
+ *_codex_items(home=home, mask_credential=mask_credential),
+ *_opencode_items(home=home, mask_credential=mask_credential),
+ ]
+ if validate_base_url is not None:
+ valid_items: list[NativeMigrationItem] = []
+ for item in items:
+ try:
+ validate_base_url(item.base_url)
+ except Exception:
+ continue
+ valid_items.append(item)
+ items = valid_items
+ existing_source_ids = {source.id for source in config.sources}
+ existing_native_vendors = {
+ source.vendor
+ for source in config.sources
+ if source.kind == "subscription" and source.supply_channel == "native_cli"
+ }
+ return [
+ item
+ for item in items
+ if item.source_id not in existing_source_ids
+ and not (
+ item.proposed_action == "keep_native"
+ and item.vendor in existing_native_vendors
+ )
+ ]
+
+
+def _new_source(
+ item: NativeMigrationItem,
+ *,
+ now: datetime,
+ validate_base_url: Callable[[object], Optional[str]],
+) -> ModelHubSourceConfig:
+ keep_native = item.proposed_action == "keep_native"
+ controlled = item.proposed_action == "controlled_import"
+ discovered_at = now.isoformat()
+ models = (
+ [
+ ModelHubModelConfig(
+ id=model_id,
+ provenance="discovered",
+ discovered_at=discovered_at,
+ )
+ for model_id in _native_model_ids(item.backend)
+ ]
+ if keep_native
+ else []
+ )
+ return ModelHubSourceConfig(
+ id=item.source_id,
+ kind="subscription" if keep_native or controlled else "api_key",
+ vendor=item.vendor,
+ display_name=item.display_name,
+ protocol=item.protocol,
+ base_url=validate_base_url(item.base_url),
+ supply_channel="native_cli" if keep_native else "hub",
+ experimental_consent_at=discovered_at if controlled else None,
+ billing="monthly" if keep_native or controlled else "metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ usage=ModelHubSourceUsageConfig(),
+ models=models,
+ account_label=item.account_label,
+ )
+
+
+def _migration_rollback_id(source_id: str, credential_ref: str) -> str:
+ return f"{source_id}:migration:{_stable_suffix(credential_ref)}"
+
+
+async def apply_native_migration(
+ host: MigrationHost,
+ item_ids: object,
+ *,
+ mask_credential: Callable[[str], str],
+ validate_base_url: Callable[[object], Optional[str]],
+) -> int:
+ """Provision, probe, and atomically persist a selected migration batch."""
+
+ if (
+ not isinstance(item_ids, list)
+ or not all(isinstance(item_id, str) and item_id for item_id in item_ids)
+ or len(set(item_ids)) != len(item_ids)
+ ):
+ raise MigrationConflictError
+ if not item_ids:
+ return 0
+
+ async with host._mutation_lock:
+ previous = host.store.load()
+ available = await asyncio.to_thread(
+ scan_native_configs,
+ previous,
+ mask_credential=mask_credential,
+ claude_oauth_probe=host.migration_claude_oauth_probe,
+ validate_base_url=validate_base_url,
+ )
+ by_id = {item.id: item for item in available}
+ missing = [item_id for item_id in item_ids if item_id not in by_id]
+ if missing:
+ raise MigrationConflictError
+
+ selected = [by_id[item_id] for item_id in item_ids]
+ if any(item.proposed_action in {"controlled_import", "reauth"} for item in selected):
+ raise MigrationConflictError
+ selected.sort(key=lambda item: item.proposed_action != "keep_native")
+ updated = host._clone_config(previous)
+ existing_ids = {source.id for source in updated.sources}
+ if any(item.source_id in existing_ids for item in selected):
+ raise MigrationConflictError
+
+ provisioned: list[tuple[str, str]] = []
+ native_source_ids: list[str] = []
+ hub_source_ids: list[str] = []
+ persisted = False
+ try:
+ for item in selected:
+ source = _new_source(
+ item,
+ now=host.now(),
+ validate_base_url=validate_base_url,
+ )
+ if item.proposed_action == "import":
+ if not item.secret:
+ raise MigrationConflictError
+ credential_ref = await host._engine_call(
+ host.adapter.provision_credential(
+ item.vendor,
+ item.protocol,
+ item.secret,
+ source.base_url,
+ )
+ )
+ provisioned.append((source.id, credential_ref))
+ source.credential_ref = credential_ref
+ source.masked_credential = mask_credential(item.secret)
+ discovered = list(
+ await host._engine_call(
+ host.adapter.discover_models(
+ item.vendor,
+ item.protocol,
+ source.base_url,
+ credential_ref,
+ )
+ )
+ )
+ manual_models = [
+ ModelHubModelConfig(
+ id=model.id,
+ display_name=model.display_name,
+ provenance="manual",
+ )
+ for model in item.manual_models
+ ]
+ host._apply_discovered_models(source, manual_models, discovered)
+ updated.sources.append(source)
+ if item.proposed_action == "keep_native":
+ native_source_ids.append(source.id)
+ else:
+ hub_source_ids.append(source.id)
+
+ updated.priority_order = [
+ *updated.priority_order,
+ *native_source_ids,
+ *hub_source_ids,
+ ]
+
+ await host._commit_synced(previous, updated)
+ persisted = True
+ return len(selected)
+ finally:
+ if not persisted:
+ for source_id, credential_ref in reversed(provisioned):
+ await host._rollback_credential(
+ _migration_rollback_id(source_id, credential_ref),
+ credential_ref,
+ )
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 362e46d49..c6d8ae644 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -45,6 +45,11 @@ from .events import (
contains_credential_material,
)
from .identifiers import opencode_model_id, opencode_provider_id, parse_opencode_model_id
+from .migration import (
+ MigrationConflictError,
+ apply_native_migration,
+ scan_native_configs,
+)
from .oauth import (
NativeOAuthUnavailableError,
OAuthAdapter,
@@ -350,6 +355,7 @@ class ModelHubService:
native_oauth_adapter: Optional[OAuthAdapter] = None,
oauth_flows: Optional[OAuthFlowRegistry] = None,
revocations: Optional[CredentialRevocationJournal] = None,
+ migration_claude_oauth_probe: Optional[Callable[[], bool]] = None,
now: Callable[[], datetime] = _utc_now,
):
self.store = store
@@ -360,6 +366,7 @@ class ModelHubService:
self.revocations = revocations or CredentialRevocationJournal(
paths.get_state_dir() / "model_hub_pending_revocations.json"
)
+ self.migration_claude_oauth_probe = migration_claude_oauth_probe
self.now = now
self._mutation_lock = asyncio.Lock()
self._engine_synced = False
@@ -1112,13 +1119,30 @@ class ModelHubService:
return _runtime_payload(await self._engine_call(self.adapter.status()))
def migration_scan(self) -> dict:
- # L6 supplies the native-config scanner. Empty is valid and read-only.
- return {"items": []}
+ config = self.store.load()
+ return {
+ "items": [
+ item.to_payload()
+ for item in scan_native_configs(
+ config,
+ mask_credential=_mask_credential,
+ claude_oauth_probe=self.migration_claude_oauth_probe,
+ validate_base_url=_validated_base_url,
+ )
+ ]
+ }
- def migration_apply(self, item_ids: object) -> dict:
- if not isinstance(item_ids, list) or item_ids:
+ async def migration_apply(self, item_ids: object) -> dict:
+ try:
+ applied = await apply_native_migration(
+ self,
+ item_ids,
+ mask_credential=_mask_credential,
+ validate_base_url=_validated_base_url,
+ )
+ except MigrationConflictError:
raise ModelHubError("migration_item_conflict", status=409)
- return {"applied": 0, "sources": self.list_sources()}
+ return {"applied": applied, "sources": self.list_sources()}
async def _resolution_candidates(
self,
@@ -1369,6 +1393,28 @@ def create_default_service(
adapter: Optional[EngineAdapter] = None,
native_oauth_adapter: Optional[OAuthAdapter] = None,
) -> ModelHubService:
+ def claude_oauth_probe() -> bool:
+ from vibe.api import (
+ _build_claude_status_probe_env,
+ _read_claude_cli_oauth_signed_in,
+ _resolve_claude_status_probe_cwd,
+ )
+ from vibe.claude_config import build_claude_subprocess_env
+
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ config = default_config()
+ claude = config.agents.claude
+ env = _build_claude_status_probe_env(
+ build_claude_subprocess_env(claude, force_oauth=True)
+ )
+ return _read_claude_cli_oauth_signed_in(
+ claude.cli_path,
+ env=env,
+ cwd=_resolve_claude_status_probe_cwd(config),
+ ) is True
+
return ModelHubService(
store=V2ModelHubConfigStore(),
adapter=adapter or UnavailableEngineAdapter(),
@@ -1376,4 +1422,5 @@ def create_default_service(
native_oauth_adapter=native_oauth_adapter,
oauth_flows=OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json"),
revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
+ migration_claude_oauth_probe=claude_oauth_probe,
)
diff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.json
index e9bdaeac9..657995ab5 100644
--- a/docs/plans/model-hub-contracts/migration-scan.schema.json
+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json
@@ -20,7 +20,7 @@
"masked_detail": { "type": "string", "description": "e.g. 'sk-…dd3c + 自定义 Base URL'; never full secrets" },
"proposed_action": {
"enum": ["import", "controlled_import", "keep_native", "reauth"],
- "description": "Option 1: Claude oauth_native → keep_native (sanctioned as-is; NOT re-authed into the hub). Codex auth.json → controlled_import behind the consent-gated flag, else keep_native. Keys/base URLs → import."
+ "description": "Option 1: Claude oauth_native → keep_native (sanctioned as-is; NOT re-authed into the hub). Subscription OAuth (Claude AND Codex) → keep_native always: file-import of OAuth tokens is DEFERRED (2026-07-23, L6 review — adapter v1.2 forbids OAuth material in provision_credential; api_key storage cannot preserve refresh semantics). With subscription_hub_experimental on, hub-held subscriptions are established via the engine's own OAuth connect flow (start_oauth), never by file import. controlled_import remains in the enum only for a future engine-owned OAuth-import capability. Keys/base URLs → import."
},
"selected": { "type": "boolean" },
"notes_key": { "type": ["string", "null"], "description": "i18n key for the row's secondary line" }
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index c7187a937..80ad2bb08 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -154,7 +154,7 @@ OpenCode models are `provider/model-id`. Rules:
| --- | --- | --- |
| 01r | 设置 · 模型 main page | One page, two bands. **来源**: global list; drag handle + priority number; per-row icon, name, mono sub (account/key id; cooldown ETA lives here), usage column (subscription progress bar / monthly ¥), fixed-width aligned chip columns 包月/按量¥ and 使用中/备用/暂不可用; supply list appears ONLY as hover tooltip on icon/title; header = one-line policy sentence + status pill; 添加来源 button in card header. **Agent**: one row per backend — name + 菜单固定/菜单开放 badge, current supply as a composite pill `model | ● source` (UI, not copy; friendly names here), mode chip 中枢 Hub / 直连 Direct, action 模型菜单 / 接入中枢. Below: 最近切换 (3 rows, human phrasing, view-all) and a single 高级 row (跨厂商自动顶替 default-off · 请求日志 · 诊断). |
| 02 | 后端 · Claude Code | 供给方式 card: two radio options — 中枢模式 Hub (推荐·默认; supply managed on Models page; native config untouched; "打开模型页") and 直连模式 Direct (legacy behavior preserved verbatim; detect strip "检测到既有直连配置 → 导入中枢…"). CLI path + connectivity test cards unchanged from current page. |
-| 03 | 迁移对话框 | Non-destructive: per-item checklist grouped by backend. API keys + base URLs → direct import; subscription OAuth → **keep_native** by default (v1.1: stays in the CLI's sanctioned store and becomes a native_cli source; hub-held import only via the consent-gated experimental flag); Codex `auth.json` → controlled import behind the same flag. Footer promise: originals never modified/deleted; Direct always available. Triggers: first open after upgrade, setup wizard, backend-page banner. |
+| 03 | 迁移对话框 | Non-destructive: per-item checklist grouped by backend. API keys + base URLs → direct import; subscription OAuth → **keep_native** by default (v1.1: stays in the CLI's sanctioned store and becomes a native_cli source; hub-held import only via the consent-gated experimental flag); Codex `auth.json` → keep_native (file-import deferred; with the experimental flag on, re-auth in-engine via the connect flow instead). Footer promise: originals never modified/deleted; Direct always available. Triggers: first open after upgrade, setup wizard, backend-page banner. |
| 06r/07 | 添加来源 | Dropdown menu on the button (no type-chooser dialog): 连接 Claude 订阅 / 连接 ChatGPT 订阅 / 添加 API Key…. The API Key form is the only form dialog: vendor select (official vendors prefill base URL; 自定义 for compatible endpoints), key, base URL, test-and-add with model-discovery feedback ("发现 23 个可用模型"). |
| 09 | 连接订阅 | Reuses the existing `BackendOAuthPanel` / `AgentAuthService` state machine (start → 2s-poll → awaiting → verifying → success/failed/cancelled; 15-min timeout; cancel). Three declared flow forms, one shell: **A** paste auth code (Claude), **B** device code, self-completing (ChatGPT/Copilot), **C** paste redirected callback URL for replay (loopback unreachable from remote browsers). URL and device code always carry copy buttons (remote/phone operation). New OAuth subscriptions = declare a form, inherit the shell. |
| 04 | 模型菜单 · Claude Code | Mapping table: left = built-in real model IDs (mono, not editable), right = supply (default 跟随原生 · 按优先级供给; override e.g. → `glm-5.2` with per-row reset and a persistent capability warning: thinking/cache/tool semantics not fully equivalent). Per-agent scope. 恢复全部默认 in footer. |
@@ -228,6 +228,8 @@ behavior.
(中文已定: 中枢/直连; alternates 托管/自管、统一/独立 were considered and
dropped).
5. Implementation plan & lane split (separate doc once this spec is signed).
+6. Deferred capability: engine-owned OAuth import (adapter rev) — prerequisite
+ for any future auth-file controlled_import; revisit only with a concrete need.
## 11. Owner acceptance checklist (~10 min)
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 0411dae30..8436e1e1c 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -13,7 +13,8 @@ capabilities:
status: active
catalog: tests/scenarios/model_hub/catalog.yaml
observations: tests/scenarios/model_hub/observations.yaml
- scenario_tests: []
+ scenario_tests:
+ - tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
unit_or_contract_tests:
- tests/test_model_hub_api.py
- tests/test_model_hub_config.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index ef424ca29..fa3b4808d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -74,9 +74,22 @@ scenarios:
test: tests/test_model_hub_injection.py::test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations
- id: MH-MIG-001
name: Migration copies without modifying native configuration
- status: gap
+ status: covered
+ kind: migration
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_001_api_apply_keeps_native_tree_byte_identical
+ - id: MH-MIG-002
+ name: Native OAuth subscriptions remain in sanctioned CLI stores
+ status: covered
+ kind: migration
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_002_oauth_defaults_to_native_sources
+ - id: MH-MIG-003
+ name: Experimental mode keeps native OAuth files in their CLI stores
+ status: covered
kind: migration
layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_003_experimental_flag_keeps_oauth_native
- id: MH-OAUTH-A-001
name: Paste-code OAuth happy path
status: partial
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
new file mode 100644
index 000000000..77b70edbe
--- /dev/null
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -0,0 +1,1026 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import threading
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+from jsonschema import Draft7Validator
+
+from config.v2_config import (
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.events import BoundedEventLog
+from core.handlers.model_hub.migration import scan_native_configs
+from core.handlers.model_hub.oauth import OAuthFlowRegistry
+from core.handlers.model_hub.revocations import CredentialRevocationJournal
+from core.handlers.model_hub.service import (
+ ModelHubError,
+ ModelHubService,
+ _mask_credential,
+ create_default_service,
+)
+from core.services.settings import default_config
+from tests.ui_server_test_helpers import csrf_headers
+from vibe import ui_server
+from vibe.ui_server import app
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+
+
+class MemoryStore:
+ def __init__(self) -> None:
+ self.config = ModelHubConfig(
+ agents={
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
+ for backend in ("claude", "codex", "opencode")
+ }
+ )
+
+ def load(self) -> ModelHubConfig:
+ return self.config
+
+ def save(self, config: ModelHubConfig) -> None:
+ self.config = config
+
+
+class MigrationAdapter:
+ def __init__(self) -> None:
+ self.provisioned: list[tuple[str, int, str]] = []
+ self.revoked: list[str] = []
+ self.synced: list[tuple[object, ...]] = []
+ self.fail_discovery_ref: str | None = None
+ self.fail_revoke_refs: set[str] = set()
+ self.fail_sync_count = 0
+
+ async def provision_credential(
+ self,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ credential_ref = f"cred_migration_{len(self.provisioned) + 1}"
+ self.provisioned.append((vendor, len(secret), credential_ref))
+ return credential_ref
+
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ ) -> tuple[str, ...]:
+ if credential_ref == self.fail_discovery_ref:
+ raise RuntimeError("redacted upstream failure")
+ return (f"{vendor}-model",)
+
+ async def sync_sources(self, bindings) -> None:
+ self.synced.append(tuple(bindings))
+ if self.fail_sync_count:
+ self.fail_sync_count -= 1
+ raise RuntimeError("redacted sync failure")
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ if credential_ref in self.fail_revoke_refs:
+ raise RuntimeError("redacted revoke failure")
+ self.revoked.append(credential_ref)
+
+
+def _service(tmp_path: Path) -> tuple[ModelHubService, MemoryStore, MigrationAdapter]:
+ store = MemoryStore()
+ adapter = MigrationAdapter()
+ state = tmp_path / "avibe-state"
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(state / "events.json"),
+ oauth_flows=OAuthFlowRegistry(state / "oauth.json"),
+ revocations=CredentialRevocationJournal(state / "revocations.json"),
+ now=lambda: datetime(2026, 7, 23, 13, 30, tzinfo=timezone.utc),
+ )
+ return service, store, adapter
+
+
+def _isolate_native_home(monkeypatch: pytest.MonkeyPatch, home: Path) -> None:
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / ".claude"))
+ monkeypatch.setenv("CODEX_HOME", str(home / ".codex"))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config"))
+ monkeypatch.setenv("XDG_CACHE_HOME", str(home / ".cache"))
+ monkeypatch.setattr(Path, "home", lambda: home)
+
+
+def _write(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+
+
+def _write_claude(home: Path, *, malformed: bool = False) -> None:
+ if malformed:
+ _write(home / ".claude" / "settings.json", "{not-json")
+ _write(home / ".claude" / ".credentials.json", "[]")
+ return
+ _write(
+ home / ".claude" / "settings.json",
+ json.dumps(
+ {
+ "env": {
+ "ANTHROPIC_API_KEY": "sk-ant-test-123456789",
+ "ANTHROPIC_BASE_URL": "https://anthropic.example/v1",
+ },
+ "permissions": {"allow": ["Read"]},
+ },
+ indent=2,
+ )
+ + "\n",
+ )
+ _write(
+ home / ".claude" / ".credentials.json",
+ json.dumps({"claudeAiOauth": {"accessToken": "claude-oauth-token"}}),
+ )
+
+
+def _write_claude_oauth(home: Path) -> None:
+ _write(
+ home / ".claude" / ".credentials.json",
+ json.dumps({"claudeAiOauth": {"accessToken": "claude-oauth-token"}}),
+ )
+
+
+def _write_codex(home: Path, *, malformed: bool = False) -> None:
+ _write(
+ home / ".codex" / "auth.json",
+ (
+ "{broken"
+ if malformed
+ else json.dumps(
+ {
+ "OPENAI_API_KEY": "sk-openai-test-123456",
+ "tokens": {"access_token": "codex-access-123456"},
+ }
+ )
+ ),
+ )
+ if not malformed:
+ _write(
+ home / ".codex" / "config.toml",
+ """cli_auth_credentials_store = "file"
+model_provider = "Relay"
+
+[model_providers.Relay]
+base_url = "https://codex-relay.example/v1"
+wire_api = "chat"
+""",
+ )
+
+
+def _write_codex_oauth(home: Path) -> None:
+ _write(
+ home / ".codex" / "auth.json",
+ json.dumps(
+ {
+ "auth_mode": "chatgpt",
+ "tokens": {"access_token": "codex-access-123456"},
+ }
+ ),
+ )
+ _write(
+ home / ".codex" / "config.toml",
+ 'cli_auth_credentials_store = "file"\n',
+ )
+
+
+def _write_opencode(home: Path, *, malformed: bool = False) -> None:
+ if malformed:
+ _write(home / ".config" / "opencode" / "opencode.json", "{/*")
+ _write(home / ".local" / "share" / "opencode" / "auth.json", "[]")
+ return
+ _write(
+ home / ".config" / "opencode" / "opencode.json",
+ """{
+ // JSONC is part of the native OpenCode format.
+ "provider": {
+ "openrouter": {
+ "options": {
+ "apiKey": "{env:OPENROUTER_API_KEY}",
+ },
+ "models": {
+ "manual-openrouter-model": {"name": "Manual OpenRouter Model"},
+ },
+ },
+ "zhipuai": {
+ "options": {
+ "baseURL": "https://zhipu.example/v1",
+ },
+ },
+ },
+}
+""",
+ )
+ _write(
+ home / ".local" / "share" / "opencode" / "auth.json",
+ json.dumps(
+ {
+ "openrouter": {"type": "api", "key": "sk-openrouter-123456"},
+ "zhipuai": {"type": "api", "key": "sk-zhipu-123456"},
+ }
+ ),
+ )
+ _write(
+ home / ".cache" / "opencode" / "models.json",
+ json.dumps(
+ {
+ "openrouter": {
+ "id": "openrouter",
+ "npm": "@openrouter/ai-sdk-provider",
+ "api": "https://openrouter.ai/api/v1",
+ },
+ "zhipuai": {
+ "id": "zhipuai",
+ "npm": "@ai-sdk/openai-compatible",
+ "api": "https://zhipu.example/v1",
+ },
+ }
+ ),
+ )
+
+
+def _tree_digest(root: Path) -> str:
+ digest = hashlib.sha256()
+ for path in sorted(item for item in root.rglob("*") if item.is_file()):
+ digest.update(path.relative_to(root).as_posix().encode("utf-8"))
+ digest.update(b"\0")
+ digest.update(path.read_bytes())
+ digest.update(b"\0")
+ return digest.hexdigest()
+
+
+def _validate_scan(payload: dict) -> None:
+ schema = json.loads((CONTRACTS / "migration-scan.schema.json").read_text(encoding="utf-8"))
+ Draft7Validator(schema).validate(payload)
+
+
+def _translation_value(payload: dict, key: str) -> object:
+ value: object = payload
+ for part in key.split("."):
+ assert isinstance(value, dict)
+ value = value[part]
+ return value
+
+
+def test_native_config_parsers_cover_valid_malformed_and_absent(tmp_path: Path) -> None:
+ cases = (
+ ("claude", _write_claude, 1),
+ ("codex", _write_codex, 1),
+ ("opencode", _write_opencode, 2),
+ )
+ for backend, writer, expected in cases:
+ valid_home = tmp_path / f"{backend}-valid"
+ writer(valid_home)
+ valid = scan_native_configs(
+ ModelHubConfig(),
+ home=valid_home,
+ mask_credential=_mask_credential,
+ )
+ assert len(valid) == expected
+ assert {item.backend for item in valid} == {backend}
+ payload = {"items": [item.to_payload() for item in valid]}
+ _validate_scan(payload)
+ assert all(" + " not in item.masked_detail for item in valid)
+ serialized = json.dumps(payload)
+ assert "Claude OAuth" not in serialized
+ assert "Codex auth.json" not in serialized
+ for secret in (
+ "sk-ant-test-123456789",
+ "claude-oauth-token",
+ "codex-access-123456",
+ "sk-openai-test-123456",
+ "sk-openrouter-123456",
+ "sk-zhipu-123456",
+ ):
+ assert secret not in serialized
+
+ malformed_home = tmp_path / f"{backend}-malformed"
+ writer(malformed_home, malformed=True)
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=malformed_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+ absent_home = tmp_path / f"{backend}-absent"
+ absent = scan_native_configs(
+ ModelHubConfig(),
+ home=absent_home,
+ mask_credential=_mask_credential,
+ )
+ assert absent == []
+
+ keychain_home = tmp_path / "claude-keychain"
+ keychain_items = scan_native_configs(
+ ModelHubConfig(),
+ home=keychain_home,
+ mask_credential=_mask_credential,
+ claude_oauth_probe=lambda: True,
+ )
+ assert [(item.backend, item.kind, item.proposed_action) for item in keychain_items] == [
+ ("claude", "oauth_native", "keep_native")
+ ]
+
+
+def test_claude_settings_env_suppresses_stale_oauth_store(tmp_path: Path) -> None:
+ native_home = tmp_path / "native-home"
+ _write_claude(native_home)
+
+ items = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+
+ assert [(item.kind, item.proposed_action) for item in items] == [
+ ("api_key", "import")
+ ]
+
+
+ ("auth_mode", "expected_kind"),
+ (("chatgpt", "oauth_native"), ("apikey", "api_key")),
+)
+def test_codex_scan_respects_explicit_auth_mode(
+ tmp_path: Path,
+ auth_mode: str,
+ expected_kind: str,
+) -> None:
+ native_home = tmp_path / auth_mode
+ _write_codex(native_home)
+ auth_path = native_home / ".codex" / "auth.json"
+ auth = json.loads(auth_path.read_text(encoding="utf-8"))
+ auth["auth_mode"] = auth_mode
+ auth_path.write_text(json.dumps(auth), encoding="utf-8")
+
+ items = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+
+ assert [item.kind for item in items] == [expected_kind]
+
+
+def test_codex_scan_treats_tokens_as_stale_when_key_has_no_auth_mode(
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_codex(native_home)
+
+ items = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+
+ assert [item.kind for item in items] == ["api_key"]
+
+
[email protected]("credential_store", (None, "keyring"))
+def test_codex_scan_keeps_native_oauth_but_skips_key_outside_file_store(
+ tmp_path: Path,
+ credential_store: str | None,
+) -> None:
+ native_home = tmp_path / (credential_store or "auto")
+ _write_codex(native_home)
+ config_path = native_home / ".codex" / "config.toml"
+ config = config_path.read_text(encoding="utf-8")
+ replacement = (
+ ""
+ if credential_store is None
+ else f'cli_auth_credentials_store = "{credential_store}"\n'
+ )
+ config_path.write_text(
+ config.replace('cli_auth_credentials_store = "file"\n', replacement),
+ encoding="utf-8",
+ )
+
+ items = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+
+ assert [(item.kind, item.proposed_action) for item in items] == [
+ ("oauth_native", "keep_native")
+ ]
+
+
+def test_migration_note_keys_resolve_in_both_ui_locales(tmp_path: Path) -> None:
+ native_home = tmp_path / "native-home"
+ _write_claude(native_home)
+ _write_codex(native_home)
+ _write_opencode(native_home)
+ note_keys = {
+ item.notes_key
+ for item in scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ if item.notes_key is not None
+ }
+
+ for locale in ("en", "zh"):
+ translations = json.loads(
+ Path(f"ui/src/i18n/{locale}.json").read_text(encoding="utf-8")
+ )
+ assert all(
+ isinstance(_translation_value(translations, key), str)
+ for key in note_keys
+ )
+
+
+def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Scenario: MH-MIG-001."""
+
+ native_home = tmp_path / "native-home"
+ _write_claude(native_home)
+ _write_codex(native_home)
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ before = _tree_digest(native_home)
+
+ service, store, adapter = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+ headers = csrf_headers(client, base_url)
+
+ scan_response = client.post(
+ "/api/models/migration/scan",
+ headers=headers,
+ base_url=base_url,
+ )
+ assert scan_response.status_code == 200
+ scan = scan_response.get_json()
+ _validate_scan({"items": scan["items"]})
+ assert len(scan["items"]) == 4
+
+ apply_response = client.post(
+ "/api/models/migration/apply",
+ json={"item_ids": [item["id"] for item in scan["items"]]},
+ headers=headers,
+ base_url=base_url,
+ )
+ assert apply_response.status_code == 200
+ body = apply_response.get_json()
+ assert body["applied"] == 4
+ assert len(body["sources"]) == 4
+ assert len(store.config.sources) == 4
+ assert len(adapter.provisioned) == 4
+ assert adapter.revoked == []
+ assert before == _tree_digest(native_home)
+ by_id = {source.id: source for source in store.config.sources}
+ assert all(by_id[source_id].billing == "metered" for source_id in store.config.priority_order)
+ codex_source = next(
+ source for source in store.config.sources if source.vendor == "openai" and source.kind == "api_key"
+ )
+ assert codex_source.protocol == "openai_chat"
+ assert codex_source.base_url == "https://codex-relay.example/v1"
+ openrouter_source = next(source for source in store.config.sources if source.vendor == "openrouter")
+ assert openrouter_source.base_url == "https://openrouter.ai/api/v1"
+ assert openrouter_source.masked_credential == _mask_credential("sk-openrouter-123456")
+ assert any(
+ model.id == "manual-openrouter-model"
+ and model.display_name == "Manual OpenRouter Model"
+ and model.provenance == "manual"
+ for model in openrouter_source.models
+ )
+
+ serialized = json.dumps(body)
+ for secret in (
+ "sk-ant-test-123456789",
+ "claude-oauth-token",
+ "codex-access-123456",
+ "sk-openai-test-123456",
+ "sk-openrouter-123456",
+ "sk-zhipu-123456",
+ ):
+ assert secret not in serialized
+
+
+def test_mh_mig_002_oauth_defaults_to_native_sources(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Scenario: MH-MIG-002."""
+
+ native_home = tmp_path / "native-home"
+ _write_claude_oauth(native_home)
+ _write_codex_oauth(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+
+ scan = service.migration_scan()["items"]
+ oauth_items = [item for item in scan if item["kind"] == "oauth_native"]
+ assert {item["backend"] for item in oauth_items} == {"claude", "codex"}
+ assert {item["proposed_action"] for item in oauth_items} == {"keep_native"}
+
+ result = asyncio.run(service.migration_apply([item["id"] for item in oauth_items]))
+ assert result["applied"] == 2
+ assert {
+ (source.vendor, source.kind, source.supply_channel, source.credential_ref) for source in store.config.sources
+ } == {
+ ("anthropic", "subscription", "native_cli", None),
+ ("openai", "subscription", "native_cli", None),
+ }
+ assert adapter.provisioned == []
+
+
+def test_mh_mig_003_experimental_flag_keeps_oauth_native(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Scenario: MH-MIG-003."""
+
+ native_home = tmp_path / "native-home"
+ _write_codex_oauth(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ store.config.subscription_hub_experimental = True
+ oauth_item = next(item for item in service.migration_scan()["items"] if item["kind"] == "oauth_native")
+ assert oauth_item["proposed_action"] == "keep_native"
+ assert oauth_item["notes_key"] == "settings.models.source.nativeSupply"
+
+ result = asyncio.run(service.migration_apply([oauth_item["id"]]))
+ assert result["applied"] == 1
+ assert adapter.provisioned == []
+ assert len(store.config.sources) == 1
+ assert store.config.sources[0].supply_channel == "native_cli"
+
+
+ ("writer", "vendor", "protocol"),
+ (
+ (_write_claude_oauth, "anthropic", "anthropic"),
+ (_write_codex_oauth, "openai", "openai_responses"),
+ ),
+)
+def test_scan_suppresses_existing_native_subscription_semantically(
+ tmp_path: Path,
+ writer,
+ vendor: str,
+ protocol: str,
+) -> None:
+ native_home = tmp_path / vendor
+ writer(native_home)
+ config = ModelHubConfig(
+ sources=[
+ ModelHubSourceConfig(
+ id="src_existing_native",
+ kind="subscription",
+ vendor=vendor,
+ display_name="Existing native",
+ protocol=protocol,
+ supply_channel="native_cli",
+ billing="monthly",
+ state=ModelHubSourceStateConfig(),
+ models=[],
+ )
+ ]
+ )
+
+ assert (
+ scan_native_configs(
+ config,
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_opencode_auth_only_custom_provider_without_base_url_is_not_importable(
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".local" / "share" / "opencode" / "auth.json",
+ json.dumps({"custom-provider": {"type": "api", "key": "sk-custom-123456"}}),
+ )
+
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_claude_auth_token_requires_reauth_without_changing_header_semantics(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".claude" / "settings.json",
+ json.dumps(
+ {
+ "env": {
+ "ANTHROPIC_AUTH_TOKEN": "bearer-test-123456",
+ "ANTHROPIC_BASE_URL": "https://bearer-relay.example/v1",
+ }
+ }
+ ),
+ )
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+
+ [item] = service.migration_scan()["items"]
+ assert item["proposed_action"] == "reauth"
+ assert item["selected"] is False
+ assert item["notes_key"] == "settings.models.source.customEndpoint"
+ assert "bearer-test-123456" not in json.dumps(item)
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply([item["id"]]))
+ assert error.value.code == "migration_item_conflict"
+ assert adapter.provisioned == []
+ assert store.config.sources == []
+
+
+def test_codex_empty_token_bag_does_not_create_native_subscription(tmp_path: Path) -> None:
+ native_home = tmp_path / "native-home"
+ _write(native_home / ".codex" / "auth.json", json.dumps({"tokens": {}}))
+ _write(
+ native_home / ".codex" / "config.toml",
+ 'cli_auth_credentials_store = "file"\n',
+ )
+
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_codex_wire_protocol_change_invalidates_scanned_item(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_codex(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ item_id = next(
+ item["id"]
+ for item in service.migration_scan()["items"]
+ if item["kind"] == "api_key"
+ )
+ config_path = native_home / ".codex" / "config.toml"
+ config_path.write_text(
+ config_path.read_text(encoding="utf-8").replace(
+ 'wire_api = "chat"',
+ 'wire_api = "responses"',
+ ),
+ encoding="utf-8",
+ )
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply([item_id]))
+ assert error.value.code == "migration_item_conflict"
+ assert adapter.provisioned == []
+ assert store.config.sources == []
+
+
+def test_opencode_unsupported_native_sdk_is_not_guessed_as_compatible(tmp_path: Path) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".config" / "opencode" / "opencode.json",
+ json.dumps(
+ {
+ "provider": {
+ "google": {
+ "options": {
+ "apiKey": "google-test-123456",
+ "baseURL": "https://google.example/v1",
+ }
+ }
+ }
+ }
+ ),
+ )
+ _write(
+ native_home / ".cache" / "opencode" / "models.json",
+ json.dumps({"google": {"id": "google", "npm": "@ai-sdk/google"}}),
+ )
+
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_opencode_builtin_provider_is_importable_without_catalog_cache(
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".config" / "opencode" / "opencode.json",
+ json.dumps(
+ {
+ "provider": {
+ "openrouter": {
+ "options": {
+ "apiKey": "sk-openrouter-123456",
+ "baseURL": "https://openrouter.example/v1",
+ }
+ }
+ }
+ }
+ ),
+ )
+
+ [item] = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+
+ assert item.vendor == "openrouter"
+ assert item.protocol == "openai_compatible"
+ assert item.base_url == "https://openrouter.example/v1"
+
+
[email protected]("provider_id", ("alibaba-cn", "poe"))
+def test_opencode_native_provider_without_stable_identifier_is_not_imported(
+ tmp_path: Path,
+ provider_id: str,
+) -> None:
+ native_home = tmp_path / provider_id
+ _write(
+ native_home / ".config" / "opencode" / "opencode.json",
+ json.dumps(
+ {
+ "provider": {
+ provider_id: {
+ "options": {
+ "apiKey": "provider-test-123456",
+ "baseURL": "https://provider.example/v1",
+ }
+ }
+ }
+ }
+ ),
+ )
+ _write(
+ native_home / ".cache" / "opencode" / "models.json",
+ json.dumps(
+ {
+ provider_id: {
+ "npm": "@ai-sdk/openai-compatible",
+ "api": "https://provider.example/v1",
+ }
+ }
+ ),
+ )
+
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_scan_skips_invalid_endpoint_without_blocking_valid_items(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".claude" / "settings.json",
+ json.dumps(
+ {
+ "env": {
+ "ANTHROPIC_API_KEY": "sk-ant-test-123456789",
+ "ANTHROPIC_BASE_URL": "ftp://unsupported.example/v1",
+ }
+ }
+ ),
+ )
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, _ = _service(tmp_path)
+
+ scan = service.migration_scan()["items"]
+ assert {item["backend"] for item in scan} == {"opencode"}
+ result = asyncio.run(service.migration_apply([item["id"] for item in scan]))
+ assert result["applied"] == 2
+ assert {source.vendor for source in store.config.sources} == {
+ "openrouter",
+ "zhipuai",
+ }
+
+
+def test_opencode_env_placeholder_without_auth_fallback_is_not_importable(tmp_path: Path) -> None:
+ native_home = tmp_path / "native-home"
+ _write(
+ native_home / ".config" / "opencode" / "opencode.json",
+ json.dumps(
+ {
+ "provider": {
+ "openrouter": {
+ "options": {"apiKey": "{env:OPENROUTER_API_KEY}"}
+ }
+ }
+ }
+ ),
+ )
+ _write(
+ native_home / ".cache" / "opencode" / "models.json",
+ json.dumps(
+ {
+ "openrouter": {
+ "id": "openrouter",
+ "npm": "@openrouter/ai-sdk-provider",
+ "api": "https://openrouter.ai/api/v1",
+ }
+ }
+ ),
+ )
+
+ assert (
+ scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
+ )
+ == []
+ )
+
+
+def test_apply_scans_claude_oauth_off_the_event_loop(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _isolate_native_home(monkeypatch, native_home)
+ service, _, _ = _service(tmp_path)
+ probe_threads: list[int] = []
+ service.migration_claude_oauth_probe = lambda: (probe_threads.append(threading.get_ident()) or True)
+ item_id = service.migration_scan()["items"][0]["id"]
+ probe_threads.clear()
+ event_loop_thread = threading.get_ident()
+
+ asyncio.run(service.migration_apply([item_id]))
+
+ assert probe_threads
+ assert all(thread_id != event_loop_thread for thread_id in probe_threads)
+
+
+def test_default_service_claude_probe_uses_safe_runtime_cwd(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _isolate_native_home(monkeypatch, native_home)
+ config = default_config()
+ config.runtime.default_cwd = str(tmp_path / "runtime")
+ monkeypatch.setattr(
+ "core.handlers.model_hub.service.V2Config.load",
+ classmethod(lambda _cls: config),
+ )
+ monkeypatch.setattr(
+ "core.handlers.model_hub.service.paths.get_state_dir",
+ lambda: tmp_path / "state",
+ )
+
+ def fake_probe(_cli_path, *, env, cwd):
+ assert env is not None
+ assert cwd == str(tmp_path / "runtime")
+ return True
+
+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", fake_probe)
+ service = create_default_service()
+
+ assert service.migration_claude_oauth_probe is not None
+ assert service.migration_claude_oauth_probe() is True
+ assert (tmp_path / "runtime").is_dir()
+
+
+def test_failed_batch_revokes_every_provisioned_credential(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+ adapter.fail_discovery_ref = "cred_migration_2"
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply(item_ids))
+ assert error.value.code == "engine_down"
+ assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]
+ assert store.config.sources == []
+ assert store.config.priority_order == []
+
+
+def test_failed_persist_sync_restores_config_and_revokes_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+ adapter.fail_sync_count = 1
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply(item_ids))
+ assert error.value.code == "engine_down"
+ assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]
+ assert store.config.sources == []
+ assert store.config.priority_order == []
+
+
+def test_failed_revoke_survives_retry_with_same_source_id(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ item_id = service.migration_scan()["items"][0]["id"]
+ adapter.fail_discovery_ref = "cred_migration_1"
+ adapter.fail_revoke_refs.add("cred_migration_1")
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply([item_id]))
+ assert error.value.code == "engine_down"
+ [pending] = service.revocations.list()
+ assert ":migration:" in pending.source_id
+ assert pending.credential_ref == "cred_migration_1"
+
+ adapter.fail_discovery_ref = None
+ adapter.fail_revoke_refs.clear()
+ result = asyncio.run(service.migration_apply([item_id]))
+ assert result["applied"] == 1
+ [active] = store.config.sources
+ assert active.id != pending.source_id
+ assert active.credential_ref == "cred_migration_2"
+
+ asyncio.run(service._ensure_engine_synced())
+ assert adapter.revoked == ["cred_migration_1"]
+ assert service.revocations.list() == []
+
+
+def test_apply_rejects_a_credential_changed_after_scan(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ native_home = tmp_path / "native-home"
+ _write_opencode(native_home)
+ _isolate_native_home(monkeypatch, native_home)
+ service, store, adapter = _service(tmp_path)
+ stale_id = service.migration_scan()["items"][0]["id"]
+ auth_path = native_home / ".local" / "share" / "opencode" / "auth.json"
+ auth_path.write_text(
+ auth_path.read_text(encoding="utf-8").replace(
+ "sk-openrouter-123456",
+ "sk-openrouter-rotated",
+ ),
+ encoding="utf-8",
+ )
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply([stale_id]))
+ assert error.value.code == "migration_item_conflict"
+ assert adapter.provisioned == []
+ assert store.config.sources == []
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index ab6db8724..8ba5a3d4a 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -55,6 +55,7 @@ def test_codex_reads_base_url_from_user_titlecase_provider(tmp_path: Path) -> No
)
state = read_codex_auth_state(home=tmp_path)
assert state["base_url"] == "https://ai-relay.chainbot.io"
+ assert state["wire_api"] == "responses"
def test_codex_falls_back_to_managed_section_when_no_active_provider(tmp_path: Path) -> None:
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index 9c1c0cd7b..af4fa11d6 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -541,6 +541,7 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
providers = toml_data.get("model_providers")
base_url: Optional[str] = None
+ wire_api: Optional[str] = None
if isinstance(providers, dict):
# Codex's runtime selects the provider named by top-level
# ``model_provider``. When that's a user-defined section (e.g.
@@ -569,6 +570,9 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
raw = active_section.get("base_url")
if isinstance(raw, str) and raw.strip():
base_url = raw.strip()
+ raw_wire_api = active_section.get("wire_api")
+ if isinstance(raw_wire_api, str) and raw_wire_api.strip():
+ wire_api = raw_wire_api.strip()
store_raw = toml_data.get(CREDENTIALS_STORE_KEY)
credentials_store = store_raw if isinstance(store_raw, str) else None
@@ -586,9 +590,7 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
# guess rather than the truth and surface ``auth_mode_uncertain`` so
# the UI can say "we can't read your auth here" instead of "no key".
auth_mode_uncertain = (
- not file_store_active
- and not (isinstance(api_key, str) and api_key)
- and not has_chatgpt_tokens
+ not file_store_active and not (isinstance(api_key, str) and api_key) and not has_chatgpt_tokens
)
return {
"auth_mode": inferred_mode,
@@ -599,6 +601,7 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
# JSON directly.
"api_key_raw": api_key if isinstance(api_key, str) and api_key else None,
"base_url": base_url,
+ "wire_api": wire_api,
"has_chatgpt_tokens": has_chatgpt_tokens,
# ``chatgpt_account``: best-effort identity from the OAuth JWT in
# ``auth.json`` so the Settings page can show "Signed in as
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 027ac4ae4..4804408be 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3261,11 +3261,11 @@ def model_hub_migration_scan():
@app.route("/api/models/migration/apply", methods=["POST"])
-def model_hub_migration_apply():
+async def model_hub_migration_apply():
from core.handlers.model_hub import ModelHubError
try:
- result = _model_hub_service().migration_apply(
+ result = await _model_hub_service().migration_apply(
_model_hub_json_object("migration_item_conflict", status=409).get("item_ids")
)
return _model_hub_success(**result)