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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agents): register Avibe as an in-process backend (#2344)
Call White05bfef01fe1e
diff --git a/config/v2_compat.py b/config/v2_compat.pyindex 679f18024..a05f31bba 100644--- a/config/v2_compat.py+++ b/config/v2_compat.py@@ -6,6 +6,7 @@ from config.v2_config import (DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS,DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,+ AvibeAgentConfig,V2Config,SlackConfig,DiscordConfig,@@ -78,6 +79,7 @@ class AppCompatConfig:wechat: Optional[WeChatConfig] = Nonecodex: Optional[CodexCompatConfig] = Noneopencode: Optional[OpenCodeCompatConfig] = None+ avibe: Optional[AvibeAgentConfig] = Noneshow_duration: bool = Falseinclude_time_info: bool = Trueinclude_user_info: bool = True@@ -202,6 +204,7 @@ def to_app_config(claude=claude,codex=codex,opencode=opencode,+ avibe=AvibeAgentConfig(enabled=True) if v2.agents.avibe.enabled else None,log_level=v2.runtime.log_level,ack_mode=v2.ack_mode,language=v2.language,diff --git a/config/v2_config.py b/config/v2_config.pyindex cf4fa407e..c20241ddf 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -35,7 +35,7 @@ from config.platform_registry import (supported_platform_ids,supported_platform_set,)-from modules.agents.catalog import DEFAULT_AGENT_BACKEND+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, AgentBackend, DEFAULT_AGENT_BACKENDfrom modules.im.base import BaseIMConfigfrom vibe.i18n import normalize_languagefrom vibe.trace_retention_policy import validate_retention_days@@ -176,7 +176,7 @@ MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20DEFAULT_AGENT_PROGRESS_STYLE = "off"MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"-MODEL_HUB_BACKENDS = ("claude", "codex", "opencode", "avibe")+MODEL_HUB_BACKENDS = tuple(sorted(AGENT_BACKENDS, key=lambda name: (name not in NATIVE_CLI_BACKENDS, name)))MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"_LEGACY_CLAUDE_FAMILY_ALIASES = {"opus": "opus",@@ -1146,6 +1146,7 @@ def _reset_recoverable_config_section("opencode": dict(defaults.opencode.__dict__),"claude": dict(defaults.claude.__dict__),"codex": dict(defaults.codex.__dict__),+ "avibe": dict(defaults.avibe.__dict__),"avault": dict(defaults.avault.__dict__),}return True@@ -2003,12 +2004,22 @@ class AVaultConfig:cli_path: str = "avault"+@dataclass+class AvibeAgentConfig:+ enabled: bool = False++ def __post_init__(self) -> None:+ if not isinstance(self.enabled, bool):+ raise ValueError("Config 'agents.avibe.enabled' must be a boolean")++@dataclassclass AgentsConfig:default_backend: str = DEFAULT_AGENT_BACKENDopencode: OpenCodeConfig = field(default_factory=OpenCodeConfig)claude: ClaudeConfig = field(default_factory=ClaudeConfig)codex: CodexConfig = field(default_factory=CodexConfig)+ avibe: AvibeAgentConfig = field(default_factory=AvibeAgentConfig)avault: AVaultConfig = field(default_factory=AVaultConfig)@@ -2799,7 +2810,7 @@ class ModelHubAgentSourcesConfig:@dataclassclass ModelHubAgentSupplyConfig:- backend: Literal["claude", "codex", "opencode", "avibe"]+ backend: AgentBackendmode: Literal["hub", "direct"]menu_kind: Literal["fixed", "open"]sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)@@ -3743,6 +3754,10 @@ class V2Config:if not isinstance(codex_payload, dict):raise ValueError("Config 'agents.codex' must be an object")+ avibe_payload = agents_payload.get("avibe", {})+ if not isinstance(avibe_payload, dict):+ raise ValueError("Config 'agents.avibe' must be an object")+avault_payload = agents_payload.get("avault") or {}if not isinstance(avault_payload, dict):raise ValueError("Config 'agents.avault' must be an object")@@ -3750,6 +3765,7 @@ class V2Config:opencode = OpenCodeConfig(**_filter_dataclass_fields(OpenCodeConfig, opencode_payload))claude = ClaudeConfig(**_filter_dataclass_fields(ClaudeConfig, claude_payload))codex = CodexConfig(**_filter_dataclass_fields(CodexConfig, codex_payload))+ avibe_agent = AvibeAgentConfig(**_filter_dataclass_fields(AvibeAgentConfig, avibe_payload))for backend_name, backend_config in (("opencode", opencode), ("claude", claude), ("codex", codex)):# Unattended upgrades run on this switch, so ``"false"`` must read as off.backend_config.auto_update = _named_bool(@@ -3761,6 +3777,7 @@ class V2Config:opencode=opencode,claude=claude,codex=codex,+ avibe=avibe_agent,avault=avault,)@@ -4071,6 +4088,7 @@ class V2Config:"opencode": self.agents.opencode.__dict__,"claude": self.agents.claude.__dict__,"codex": self.agents.codex.__dict__,+ "avibe": self.agents.avibe.__dict__,"avault": self.agents.avault.__dict__,},"model_hub": self.model_hub.to_payload(),diff --git a/config/v2_settings.py b/config/v2_settings.pyindex 920673f5b..b0b9968a2 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -11,6 +11,7 @@ from pathlib import Pathfrom typing import Dict, List, Optional, Tuplefrom config import paths+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDSlogger = logging.getLogger(__name__)@@ -150,7 +151,7 @@ class RoutingSettings:codex_reasoning_effort: Optional[str] = Nonedef _backend_specific_value(routing: RoutingSettings, backend: Optional[str], field: str) -> Optional[str]:- if backend not in {"opencode", "claude", "codex"}:+ if backend not in NATIVE_CLI_BACKENDS:return Nonereturn getattr(routing, f"{backend}_{field}", None)@@ -166,7 +167,7 @@ def normalize_routing_settings(routing: Optional[RoutingSettings]) -> RoutingSetif routing is None:return RoutingSettings()agent_name = getattr(routing, "agent_name", None)- builtin_agent_backend = agent_name if agent_name in {"opencode", "claude", "codex"} else None+ builtin_agent_backend = agent_name if agent_name in AGENT_BACKENDS else Nonemodel = getattr(routing, "model", None)reasoning_effort = getattr(routing, "reasoning_effort", None)return RoutingSettings(@@ -205,7 +206,7 @@ def routing_reasoning_effort_for_backend(def _routing_backend_matches(routing: RoutingSettings, backend: Optional[str]) -> bool:agent_name = getattr(routing, "agent_name", None)- if agent_name in {"opencode", "claude", "codex"}:+ if agent_name in AGENT_BACKENDS:return agent_name == backendreturn Truediff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 221e9aa78..0a234f949 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -17,6 +17,7 @@ from collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Coroutine, Optional+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDSfrom core.backend_failure import terminal_backend_failure_outputfrom core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation@@ -905,7 +906,7 @@ class AgentAuthService:await self._send_message(context, f"❌ {self._t('command.setup.claudeMethodUsage')}")return- if backend_hint and backend_hint not in {"claude", "codex", "opencode"}:+ if backend_hint and backend_hint not in NATIVE_CLI_BACKENDS:await self._send_message(context, f"❌ {self._t('command.setup.unsupportedBackend', backend=backend_hint)}")return@@ -934,7 +935,7 @@ class AgentAuthService:) -> None:"""Start an auth flow for the resolved backend."""resolved_backend = backend or self.controller.resolve_agent_for_context(context)- if resolved_backend not in {"claude", "codex", "opencode"}:+ if resolved_backend not in NATIVE_CLI_BACKENDS:await self._send_message(context,f"❌ {self._t('command.setup.unsupportedBackend', backend=resolved_backend)}",@@ -2241,7 +2242,7 @@ class AgentAuthService:return [backend- for backend in ("opencode", "claude", "codex")+ for backend in AGENT_BACKENDSif bool(getattr(getattr(agent_config, backend, None), "enabled", False))]@@ -2862,7 +2863,7 @@ class AgentAuthService:return {"ok": True}async def test_web_auth(self, backend: str, **kwargs: Any) -> dict[str, Any]:- if backend not in {"claude", "codex", "opencode"}:+ if backend not in NATIVE_CLI_BACKENDS:return {"ok": False, "error": "unsupported_backend"}lease = self._acquire_native_lease(backend)try:diff --git a/core/backend_restart.py b/core/backend_restart.pyindex 9a333dac0..2bc8335bb 100644--- a/core/backend_restart.py+++ b/core/backend_restart.py@@ -13,6 +13,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom contextlib import AsyncExitStack, asynccontextmanagerfrom pathlib import Pathfrom typing import Any, TypeVar+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDSlogger = logging.getLogger(__name__)@@ -27,7 +28,7 @@ _POLL_INTERVAL_SECONDS = 0.1# accurate and a retry afterwards proceeds. It stays well inside the 300 s# Model Hub RPC timeout the Web UI waits under._INTERRUPT_SETTLE_SECONDS = 120.0-_NATIVE_BACKENDS = frozenset({"claude", "codex", "opencode"})+_NATIVE_BACKENDS = frozenset(NATIVE_CLI_BACKENDS)_T = TypeVar("_T")@@ -787,7 +788,10 @@ class BackendRestartCoordinator:# stays registered with an explicit flag. Use loaded state, never disk# or a stale successful outcome to excuse unexpected missing agents.if isinstance(config, AppCompatConfig):- disabled = (backend in {"codex", "opencode"} and getattr(config, backend) is None and not registered) or (+ disabled = (+ backend in AGENT_BACKENDS and backend != "claude"+ and getattr(config, backend) is None and not registered+ ) or (backend == "claude" and registered and config.claude.enabled is False)if disabled:diff --git a/core/controller.py b/core/controller.pyindex aeb7b3317..8420c7eef 100644--- a/core/controller.py+++ b/core/controller.py@@ -19,6 +19,7 @@ from modules.im import BaseIMClient, MessageContext, IMFactoryfrom modules.im.multi import MultiIMClientfrom modules.agent_router import AgentRouterfrom modules.agents.service import AgentService+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDSfrom modules.claude_client import ClaudeClientfrom modules.session_manager import SessionManagerfrom modules.settings_manager import SettingsManager, MultiSettingsManager@@ -169,7 +170,7 @@ def _target_agent_variant(value: Any, backend: Any = None, agent_name: Any = Nonvariant = _optional_target_str(value)if variant is None:return None- sentinel_values = {"default", "claude", "codex", "opencode"}+ sentinel_values = {"default", *AGENT_BACKENDS}backend_text = _optional_target_str(backend)if backend_text:sentinel_values.add(backend_text)@@ -353,7 +354,7 @@ class Controller:agent_config = getattr(self.config, "agents", None)if agent_config is None:return list(getattr(self.agent_service, "agents", {}).keys()) or [DEFAULT_AGENT_BACKEND]- for backend in ("opencode", "claude", "codex"):+ for backend in AGENT_BACKENDS:cfg = getattr(agent_config, backend, None)if bool(getattr(cfg, "enabled", False)):result.append(backend)@@ -1570,7 +1571,7 @@ class Controller:)if vibe_agent:return vibe_agent.backend- if target_backend and str(target_backend) in {"opencode", "claude", "codex"}:+ if target_backend and str(target_backend) in AGENT_BACKENDS:return str(target_backend)vibe_agent = self.resolve_vibe_agent_for_context(context, required=False)@@ -2599,7 +2600,7 @@ class Controller:backends: tuple[str, ...] | None = None,) -> None:nonlocal cli_presence, next_cli_presence_generation- selected_backends = backends or ("claude", "codex", "opencode")+ selected_backends = backends or tuple(sorted(NATIVE_CLI_BACKENDS))with cli_presence_lock:next_cli_presence_generation += 1generation = next_cli_presence_generationdiff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex b7cd59b7e..81e0ee78e 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -20,7 +20,7 @@ from core.native_dispatch_phase import (set_dispatch_phase,)from modules.agents.base import AgentRequest-from modules.agents.catalog import display_name_for_backend, is_agent_backend+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backend, is_agent_backendfrom modules.im import MessageContextfrom modules.im.base import FileAttachment@@ -37,7 +37,7 @@ def _target_agent_variant(value: Any, backend: Optional[str], agent_name: Optionvariant = str(value).strip()if not variant:return None- sentinel_values = {"default", "claude", "codex", "opencode"}+ sentinel_values = {"default", *AGENT_BACKENDS}if backend:sentinel_values.add(str(backend).strip())if agent_name:@@ -399,7 +399,7 @@ class MessageHandler(BaseHandler):routing_agent = getattr(routing, "claude_agent", None)elif agent_name == "codex":routing_agent = getattr(routing, "codex_agent", None)- if not routing_agent and agent_name in {"opencode", "claude", "codex"}:+ if not routing_agent and agent_name in AGENT_BACKENDS:routing_agent = _target_agent_variant(resolved_target.get("agent_variant"),agent_name,@@ -533,7 +533,7 @@ class MessageHandler(BaseHandler):spec = dict(context.platform_specific or {})spec["routing_subagent"] = subagent_namecontext.platform_specific = spec- elif agent_name in ["opencode", "claude", "codex"]:+ elif agent_name in NATIVE_CLI_BACKENDS:from modules.agents.subagent_router import (load_codex_subagent,load_claude_subagent,diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.pyindex 02b2d12c3..8904155e7 100644--- a/core/handlers/model_hub/events.py+++ b/core/handlers/model_hub/events.py@@ -15,7 +15,9 @@ from vibe.i18n import t as i18n_tfrom .state_file import write_state_document-EventAgent = Literal["claude", "codex", "opencode", "avibe", "system"]+from modules.agents.catalog import AgentBackend++EventAgent = Literal[AgentBackend, "system"]EventKind = Literal["switch","cooldown",diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex b4ba63f59..333f2d051 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -11,6 +11,7 @@ import refrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom pathlib import Path+from modules.agents.catalog import NATIVE_CLI_BACKENDS, NativeCliBackend, display_name_for_backendfrom typing import Any, Awaitable, Callable, Collection, Literal, Mapping, Optional, Protocol, castfrom config.v2_config import (@@ -203,7 +204,7 @@ class NativeManualModel:class NativeMigrationItem:id: strsource_id: str- backend: Literal["claude", "codex", "opencode"]+ backend: NativeCliBackendkind: MigrationKindmasked_detail: strproposed_action: MigrationAction@@ -591,7 +592,7 @@ def _blocked_item(selected=False, notes_key=f"settings.models.migration.blocked.{reason}",vendor={"claude": "anthropic", "codex": "openai", "opencode": "opencode"}[backend],protocol="anthropic" if backend == "claude" else "openai_responses",- display_name={"claude": "Claude Code", "codex": "Codex", "opencode": "OpenCode"}[backend],+ display_name=display_name_for_backend(backend),source_paths=source_paths, shell_variables=shell_variables,shell_auth_variables=shell_auth_variables, config_blocker=config_blocker,)@@ -2262,7 +2263,7 @@ async def apply_native_migration(scan_native_configs, host.store.load(), mask_credential=mask_credential,home=host.migration_home,validate_base_url=validate_base_url,- legacy_auth=_native_auth_snapshot(host, ("claude", "codex", "opencode")),+ legacy_auth=_native_auth_snapshot(host, tuple(sorted(NATIVE_CLI_BACKENDS))),project_roots=host.migration_project_roots(),clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),retained_native_ids=(host.migration_journal.completed() or {}).get("retained_native_ids"),@@ -2292,7 +2293,7 @@ async def apply_native_migration(item for item in await asyncio.to_thread(scan_native_configs, host.store.load(), mask_credential=mask_credential,home=host.migration_home, validate_base_url=validate_base_url,- legacy_auth=_native_auth_snapshot(host, ("claude", "codex", "opencode")),+ legacy_auth=_native_auth_snapshot(host, tuple(sorted(NATIVE_CLI_BACKENDS))),project_roots=host.migration_project_roots(),clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),)diff --git a/core/handlers/model_hub/migration_journal.py b/core/handlers/model_hub/migration_journal.pyindex 7b271d7a1..6fdaff2f8 100644--- a/core/handlers/model_hub/migration_journal.py+++ b/core/handlers/model_hub/migration_journal.py@@ -6,6 +6,7 @@ CPA exposure. The completed receipt contains opaque IDs, not secrets."""from __future__ import annotations+from modules.agents.catalog import NATIVE_CLI_BACKENDSimport base64import json@@ -238,7 +239,7 @@ class NativeTakeoverJournal:or not isinstance(payload.get("items"), list)or not isinstance(payload.get("backends"), list)or not payload["backends"]- or any(backend not in {"claude", "codex", "opencode"} for backend in payload["backends"])+ or any(backend not in NATIVE_CLI_BACKENDS for backend in payload["backends"])or len(set(payload["backends"])) != len(payload["backends"])or not isinstance(payload.get("source_ids"), list)or any(not isinstance(value, str) or not value for value in payload["source_ids"])diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 56457aee5..9c5ae98c3 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import Any, Callable, Iterable, Literal, Mapping, Optionalfrom config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig+from modules.agents.catalog import display_name_for_backendfrom core.os_errors import format_os_errnofrom core.run_settlement import (@@ -590,7 +591,7 @@ def render_turn_outcome_copy()params["blockers"] = ", ".join(rendered)if params.get("backend"):- params["backend"] = i18n_t(f"modelHub.backends.{params['backend']}", language)+ params["backend"] = display_name_for_backend(params["backend"])return i18n_t(copy.key, language, **params)diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex 57536e79c..a0202c711 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -17,7 +17,9 @@ from config.v2_config import ()-BackendName = Literal["claude", "codex", "opencode", "avibe"]+from modules.agents.catalog import AgentBackend++BackendName = AgentBackendResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]RouteOrigin = Literal["automatic", "manual", "passthrough"]diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex e8a298f14..36ab0a1f0 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -1,6 +1,7 @@"""Allowlisted RPC surface for the controller-owned Model Hub service."""from __future__ import annotations+from modules.agents.catalog import NATIVE_CLI_BACKENDSimport asynciofrom typing import Any@@ -66,7 +67,7 @@ async def _refresh_payload_backend(service: ModelHubService,backend: object,) -> None:- if backend in ("claude", "codex", "opencode"):+ if backend in NATIVE_CLI_BACKENDS:await _refresh_agent_presence(service, (backend,))@@ -121,7 +122,7 @@ async def dispatch_model_hub_rpc()if operation == "agent_model_candidates":backend = payload.get("backend")- if backend in ("claude", "codex", "opencode"):+ if backend in NATIVE_CLI_BACKENDS:await _refresh_agent_presence(service, (backend,))if backend != "opencode":await service.reconcile_builtin_models((backend,))diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 62ad6dc16..57df1a465 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -17,6 +17,7 @@ from typing import Any, Awaitable, Callable, Iterable, Literal, Mapping, Optionafrom sqlalchemy import func, selectfrom config import paths+from modules.agents.catalog import NATIVE_CLI_BACKENDSfrom config.v2_config import (CONFIG_LOCK,MODEL_HUB_BACKENDS,@@ -1735,7 +1736,7 @@ class ModelHubService:except (TakeoverStateError, OSError):# Unknown recovery state cannot authorize any native credential# writer or native launch. Controller recovery preserves this gate.- self.migration_blocked_backends.update(("claude", "codex", "opencode"))+ self.migration_blocked_backends.update(NATIVE_CLI_BACKENDS)raise ModelHubError("migration_item_conflict", status=409) from Nonetask = self._runtime_resume_taskif task is None or task.done():@@ -7309,7 +7310,7 @@ class ModelHubService:clean_native_stores=(self.migration_journal.completed() or {}).get("clean_native_stores"),retained_native_ids=(self.migration_journal.completed() or {}).get("retained_native_ids"),legacy_auth=(- self.store.native_auth_snapshot(("claude", "codex", "opencode"))+ self.store.native_auth_snapshot(tuple(sorted(NATIVE_CLI_BACKENDS)))if isinstance(self.store, V2ModelHubConfigStore) else None),)@@ -7363,7 +7364,7 @@ class ModelHubService:try:pending = self.migration_journal.load()except (TakeoverStateError, OSError):- self.migration_blocked_backends.update(("claude", "codex", "opencode"))+ self.migration_blocked_backends.update(NATIVE_CLI_BACKENDS)raise ModelHubError("migration_configuration_blocked", status=409) from Noneif pending is not None and pending["phase"] == "exposed":raise ModelHubError("migration_recovery_pending", status=409) from Nonediff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex 7279b45dc..2acf9df8b 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -5,6 +5,7 @@ import loggingfrom typing import Optionalfrom modules.agents import get_agent_display_name+from modules.agents.catalog import AGENT_BACKENDSfrom modules.im import MessageContext, InlineKeyboard, InlineButtonfrom core.modals import RoutingModalData, RoutingModalSelectionfrom vibe import backend_model_catalog@@ -538,7 +539,7 @@ class SettingsHandler(BaseHandler):if not agent_name:return Nonename = str(agent_name)- if name in {"opencode", "claude", "codex"}:+ if name in AGENT_BACKENDS:return namestore = getattr(self.controller, "vibe_agent_store", None)if store is None:@@ -554,7 +555,7 @@ class SettingsHandler(BaseHandler):def _routing_target_from_row(row: dict) -> tuple[str, str, str, str, str]:backend = str(row.get("agent_backend") or "").strip()agent_name = str(row.get("agent_name") or "").strip()- if not agent_name and backend in {"opencode", "claude", "codex"}:+ if not agent_name and backend in AGENT_BACKENDS:agent_name = backendvariant = str(row.get("agent_variant") or "").strip()if variant == backend and agent_name == backend:diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 17b8f3bca..9aae9dfb5 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -17,6 +17,7 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable, Mapping, Optional, Sequencefrom urllib.parse import urljoin+from modules.agents.catalog import AGENT_BACKENDSfrom config.platform_registry import get_platform_descriptorfrom config.v2_config import DEFAULT_AGENT_PROGRESS_STYLE@@ -1810,7 +1811,7 @@ class ConsolidatedMessageDispatcher:if (not session_idor not base_session_id- or backend not in {"claude", "codex", "opencode"}+ or backend not in AGENT_BACKENDS):if lease is not None:release_lease = getattr(diff --git a/core/prompt_studio_catalog.py b/core/prompt_studio_catalog.pyindex 896866ce9..951d3fee5 100644--- a/core/prompt_studio_catalog.py+++ b/core/prompt_studio_catalog.py@@ -8,6 +8,7 @@ import jsonimport refrom pathlib import Pathfrom typing import Any, get_type_hints+from modules.agents.catalog import AGENT_BACKENDSfrom markdown_it import MarkdownItfrom pydantic import TypeAdapter, ValidationError@@ -232,7 +233,7 @@ def render_prompt_context(request: dict[str, Any]) -> dict[str, Any]:if not isinstance(request, dict) or set(request) - {"backend", "agent_instructions", "options"}:raise PromptRenderInputError("invalidContext")backend = request.get("backend")- if backend not in ("claude", "codex", "opencode"):+ if backend not in AGENT_BACKENDS:raise PromptRenderInputError("invalidBackend")agent_instructions = request.get("agent_instructions", "")if not isinstance(agent_instructions, str):diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.pyindex 160ee466a..d10a11954 100644--- a/core/services/agent_run_target.py+++ b/core/services/agent_run_target.py@@ -26,6 +26,7 @@ from core.message_context import ()from config.v2_settings import make_thread_native_idfrom modules.im import MessageContext+from modules.agents.catalog import AGENT_BACKENDSfrom storage.agent_session_rows import (SESSION_PROJECT_BASE_METADATA_KEY,create_agent_session_row,@@ -546,7 +547,7 @@ def _agent_target_from_vibe_agent(agent: Any, *, scope_row: Optional[dict[str, Adef _supported_backend(value: Any) -> Optional[str]:backend = _optional_str(value)- if backend in {"opencode", "claude", "codex"}:+ if backend in AGENT_BACKENDS:return backendreturn Nonediff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex 3fe64a8dc..8ae4596e0 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom typing import Any, Mapping, Optionalfrom config import paths+from modules.agents.catalog import AGENT_BACKENDSfrom vibe.authorization import (AuthorizationContext,require_instance_role,@@ -252,7 +253,7 @@ def reserve_forked_session(raise SessionForkError(f"agent session is archived: {source_session_id}")source_backend = str(row["agent_backend"] or "").strip()- if source_backend not in {"codex", "claude", "opencode"}:+ if source_backend not in AGENT_BACKENDS:raise SessionForkError(f"session backend cannot be forked: {source_backend or 'unknown'}")source_native = str(row["native_session_id"] or "").strip()if not source_native:diff --git a/core/vibe_agents.py b/core/vibe_agents.pyindex 1562f6575..a33c51226 100644--- a/core/vibe_agents.py+++ b/core/vibe_agents.py@@ -17,6 +17,7 @@ from sqlalchemy.engine import Connectionfrom sqlalchemy.exc import IntegrityErrorfrom config import paths+from modules.agents.catalog import AGENT_BACKENDSfrom storage.agent_session_rows import reserve_write_lockfrom storage.db import SqliteInvalidationProbe, create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config@@ -51,7 +52,6 @@ ARCHIVED_AGENT_NAME_PREFIX = "_"LEGACY_ARCHIVED_AGENT_NAME_PREFIX = "_archived_"ARCHIVED_AGENT_SLUG_LENGTH = 12ARCHIVED_AGENT_TOKEN_LENGTH = 4-SUPPORTED_AGENT_BACKENDS = {"codex", "claude", "opencode"}RECOMMENDED_AGENT_MODELS = {"claude": "claude-opus-5-5","codex": "gpt-5.6-sol",@@ -201,14 +201,16 @@ def _validated_public_agent_name(name: str) -> tuple[str, str]:def validate_agent_backend(backend: str) -> str:value = str(backend or "").strip().lower()- if value not in SUPPORTED_AGENT_BACKENDS:- supported = ", ".join(sorted(SUPPORTED_AGENT_BACKENDS))+ if value not in AGENT_BACKENDS:+ supported = ", ".join(sorted(AGENT_BACKENDS))raise ValueError(f"unsupported agent backend: {backend}. Supported backends: {supported}")return value-def recommended_agent_model(backend: str) -> str:- return RECOMMENDED_AGENT_MODELS[validate_agent_backend(backend)]+def recommended_agent_model(backend: str) -> Optional[str]:+ # In-process backends select only a configured Model Hub route. An empty+ # catalog has no recommendation; do not invent an upstream model.+ return RECOMMENDED_AGENT_MODELS.get(validate_agent_backend(backend))def _json_dumps(value: Any) -> str:diff --git a/docs/plans/avibe-agent-registration-fixtures.md b/docs/plans/avibe-agent-registration-fixtures.mdnew file mode 100644index 000000000..30be67086--- /dev/null+++ b/docs/plans/avibe-agent-registration-fixtures.md@@ -0,0 +1,171 @@+# Avibe Agent registration: test fixture inventory++Inventory date: 2026-10-02.++The first `rg` pass searched `tests/**/*.py` and fixture JSON/YAML for the+exact backend ids. An AST pass then retained literal lists, tuples, sets, and+dict keys containing at least two distinct ids. The baseline scan found 328 Python container+sites in 87 Python files, plus two relevant JSON fixtures. Nested containers+with the same purpose are grouped below. Function-call arguments, per-record+mapping values, provider/model text, and scenario records are excluded unless+the enclosing container is itself a backend membership fixture.++Locators below refer to that baseline. This inventory records final decisions,+not pending recommendations. Native sample fixtures do not declare the Agent+universe. In particular, native inherited/default routes and Direct mode must+not be widened to Avibe's explicit-route-only C-4 contract.++The decision boundary is:++- `AGENT_BACKENDS`: Agent creation, routing, listings, Model Hub consumers,+ shared prompt/output behavior, and ordinary IM selectors. These sites gain+ `avibe`.+- `NATIVE_CLI_BACKENDS`: CLI presence, install, OAuth, native session/process+ discovery, direct mode, restart, native files, and native-only protocol+ behavior. These remain native.+- A fixed native subset or released compatibility shape stays literal when the+ test is intentionally proving that subset or historical data shape.++Parent updates already applied and therefore not pending in this inventory:++- `tests/test_agent_service.py` uses `AGENT_BACKENDS`.+- `tests/test_v2_config_platform_registry.py` compares against+ `list(AGENT_BACKENDS)`.+- `tests/test_v2_compat_platforms.py` covers the compat `None` lifecycle.+- `tests/test_backend_restart.py` uses the catalog-derived optional-backend+ snapshot.+- `core/backend_restart.py` no longer carries the obsolete native pair.+- `tests/test_model_hub_failure_presentation.py` uses `AGENT_BACKENDS` for the+ shared failure/evidence projection; its native HTTP recorder pair remains+ native-only.+- `tests/test_prompt_render_export.py` uses `AGENT_BACKENDS` for generic+ product/parameterization sites; its approved-guidance digest remains a+ historical native-only fixture.++## A. Agent-surface candidates: final disposition++| File and literal site | Updated to catalog or intentionally retained native scope |+| --- | --- |+| `tests/e2e/test_model_hub_migration_persisted.py:34`, `_seed_hub` | Retained native credential-migration setup; no in-process native credential store is invented. |+| `tests/scenario_harness/model_hub.py:306`, `config_with_sources` | Retained native seed map. `ModelHubConfig` already supplies the empty Avibe row, and Avibe explicit-route consumers populate it. This is not an exhaustive-map assertion. |+| `tests/scenario_harness/model_hub_native_oauth.py:82`, `MemoryStore.__init__` | Retained native OAuth setup; maps at 131 and 209 are credential subsets. |+| `tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py:72,108,140,182,233` | Retained native automatic/passthrough/default routing and Hub/Direct products. Avibe intentionally does not inherit native routes. |+| `tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py:231,234`, `_config`; `397,405-414`, gateway switch; `1360`, unlisted model | Retained native requested-model/protocol fixtures, Direct-to-Hub switch, and native-launch refusal. Avibe has no native requested-model fallback. |+| `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py:56,720-721,818` | Retained native vendor catalog placement, credential migration and adoption-mode assertions. |+| `tests/test_api_save_config_merge.py:62-83,169,1276` | Merge/deprecated-field and serializer completeness assertions now use `AGENT_BACKENDS` (plus `avault`). The old input payload deliberately omits Avibe and retains deprecated default-model fields to test compatibility. |+| `tests/test_controller_config_reload.py:21-26`; `tests/test_discord_guild_settings.py:25-30` | Retained released-compatible native config inputs, as detailed in C; omitted optional Avibe must still load. |+| `tests/test_backend_failure_retry.py:234` | Updated canonical-continue/draft matrix to `AGENT_BACKENDS`; native restart-receipt fixture at 99 is retained. |+| `tests/test_harness_failure_retry.py:133` | Retained native start-receipt lifecycle via `_bind_test_native_start`. Generic retry and callback settlement are expanded separately. |+| `tests/test_model_hub_api.py:142,4086,4135,4151,9833` | Catalog ID edit/admission/reload matrices use `AGENT_BACKENDS`. Retained MemoryStore native seed map and native automatic Source-order example; Avibe's normalized empty row and explicit routes are tested separately. |+| `tests/test_model_hub_api.py:1049`, `test_runtime_stop_protects_configured_avibe_models`; `4477-4486` and `4867-4876` | These already expose Avibe explicitly. Keep them as the boundary checks while deriving surrounding expected backend maps from the Agent catalog. |+| `tests/test_model_hub_avibe_consumer.py:705`, `test_terminal_response_origin_follows_its_carrier` | Already includes `avibe`; it is the correct shape for an all-Agent origin matrix. |+| `tests/test_model_hub_config.py:1410,3132,3154` | Serializer and empty-route normalization/recovery matrices now use `AGENT_BACKENDS`; native Direct-mode recovery expectations remain fixed. |+| `tests/test_model_hub_failure_presentation.py:44` | Parent updated the shared failure/evidence projection to `AGENT_BACKENDS`; its native HTTP recorder pair remains native-only. |+| `tests/test_model_hub_injection.py:267` | Explicit route-alias metadata matrix now uses `AGENT_BACKENDS`; native overlay assertions remain conditional. |+| `tests/test_model_hub_l3.py:691-695,1177` | Retained native requested-model and configured native-route templates, not exhaustive Agent membership assertions. |+| `tests/test_model_hub_resolution.py:317,456,2363` | Cross-backend Hub Source eligibility now uses `AGENT_BACKENDS`; retained native catalog/default seed and vendor placement examples (including 2377/2387). |+| `tests/test_model_hub_routing_modes.py:376,409,439,472,512,560,595,619,643,673,731,739,763,799` | Retained native inherited automatic/passthrough/default-route behavior, Hub/Direct products and native legacy-ID compatibility matrix. Avibe's explicit-route policy must not inherit those expectations. Line 457 is a historical native fixed-menu pair. Shared catalog admission now includes Avibe in `test_model_hub_api.py`. |+| `tests/test_prompt_render_export.py:100,154,180,210,223,259,287,310,522` | Parent audit already assigned all product/parameterization sites to `AGENT_BACKENDS`. Keep line 522, `test_approved_guidance_changes_preserve_all_other_injection_bytes`, as the historical native-only digest fixture. |+| `tests/test_runtime_ownership.py:303` | Shared AgentService probe loop uses `AGENT_BACKENDS`; actual OpenCode process-resource assertions in the same test remain native-specific. |+| `tests/test_scheduled_tasks.py:7434` | Callback terminal-once matrix now uses `AGENT_BACKENDS`; native binding example at 13055 remains fixed. |+| `tests/test_settings_handler.py:510-514,532,601,650,607-610` | Registered/enabled fixture and whole-set assertions derive from `AGENT_BACKENDS`; Avibe stays visible when native peers are disabled. Claude/Codex reasoning metadata remains a capability-specific expectation. |+| `tests/test_telegram_bot.py:1336,1434,1460,1498` | Routing fixture derives from `AGENT_BACKENDS`; fourth-backend picker cases exercise both Avibe and the unknown-extra-backend case. |+| `tests/test_ui_api.py:4183` | Built-in preference test now supplies `AGENT_BACKENDS`; fixed two-backend enablement examples at 4084/4092 remain. |+| `tests/test_managed_skills.py:709` | Backend-neutral prompt/skill matrix now uses `AGENT_BACKENDS` and actually passes the selected backend to the renderer (previously it rendered the same default three times). |++## B. Intentionally retained native capability fixtures++These fixtures retain their native literal memberships. They exercise CLI,+native files, credentials, session/process or protocol behavior, and are not+Agent-universe declarations. No Avibe native resource is fabricated.++| File and literal site | Native boundary |+| --- | --- |+| `tests/scenario_harness/auth_setup.py:13`, `save_direct_auth_config` | Direct-mode auth setup; Avibe only supports Hub mode. |+| `tests/test_agent_auth_service.py:41`, `_IsolatedClaudeConfigDirMixin.setUp` | Native auth isolation and Direct-mode setup. Lines `2421-2455` belong to the explicit C-8 classifier inventory and are excluded from this audit. |+| `tests/test_backend_connection.py:64`, `connection`; `152,160,187`; `255,263`; `885` | Native direct readiness, install application, disabled native configuration, and pending takeover. The separate Avibe connection test is already present at lines 436-460. |+| `tests/test_backend_restart.py:174-180,202` | Fixed native restart/IPC examples. The new catalog-derived optional-backend projection test covers Avibe's disabled state separately. |+| `tests/test_claude_cli_path.py:235-239,302` | Desktop/native executable resolution and missing private CLI selectors. |+| `tests/test_controller_model_hub_gate.py:147,338` | CLI presence probe and direct-mode fallback. Avibe has no CLI and cannot be forced into Direct mode. |+| `tests/test_desktop_backends.py:117,997` | Native install publication and private backend removal. |+| `tests/test_global_agents_md.py:90,136` | Global prompt files are owned by native CLI backends in production. |+| `tests/test_internal_client.py:372,378,380-383`; `tests/test_internal_server.py:846,852-856` | Backend restart/reconcile IPC contract; keep the selector native. |+| `tests/test_member_management_parity.py:168` | Native backend connection management route; Avibe has no native connection projection. |+| `tests/test_model_hub_api.py:820, runtime-stop branch`; `1041,1049,1064,1143,1524`; `2341,2681`; `5344,9629` | Fixed native Direct-mode setup, native protocol projection and recovery; explicit Avibe Hub-only cases remain in A. |+| `tests/test_model_hub_avibe_consumer.py:347,350`, native history; `897`, native transport clients | Explicit native callers do not carry Avibe origin metadata. |+| `tests/test_model_hub_retry_lifecycle.py:33-37`, `BACKENDS`; `156`, native failure recovery | Protocol endpoint map and native failure behavior are native-only. |+| `tests/test_native_login_single_flight.py:49`; `tests/test_settings_disk_fallback.py:38` | Native auth fixtures force Direct mode. |+| `tests/test_native_process_inventory.py:46,119,139,263,310,204,241` | Native executable/process inventory and smaller native credential subsets, not in-process runtime ownership. |+| `tests/test_native_session_providers.py:590` | Native session visibility and provider behavior. |+| `tests/test_native_takeover_lifecycle.py:28,138-139,492,526,584,699` | Native takeover journal, process inventory, auth service, and native writer ownership. |+| `tests/test_native_writer_custody.py:42,65,263` | Native credential custody and writer refusal. |+| `tests/test_ui_api.py:2263,2291,2314,2392,2440,2532` | Desktop install, private runtime ownership, update checks, and CLI path resolution. |+| `tests/test_ui_server_fastapi.py:2278`; `tests/test_ui_server_install.py:159,210` | Native runtime projection and installation jobs. |+| `tests/test_update_checker_platforms.py:1099-1103,1162` | Native package update and admission behavior. |+| `tests/test_web_oauth_flow.py:47,505` | Native Web OAuth setup and callback failure recovery. |++## C. Keep as intentional native-only, subset, or historical fixtures++These sites should not be expanded to an unimplemented in-process adapter.+They either encode a released shape, a credential store subset, a fixed native+vendor example, or a native adapter-specific comparison. They may retain+literal ids; where the test means “every native backend”, replacing the literal+with `NATIVE_CLI_BACKENDS` is optional only if it does not weaken the historical+or subset assertion.++| File and literal site | Why the native-only shape is intentional |+| --- | --- |+| `tests/e2e/test_api.py:14-19`, `_VALID_CONFIG`; `tests/test_controller_config_reload.py:21-26`; `tests/test_discord_guild_settings.py:25-30`; `tests/test_ui_server_mutation_protection.py:144-149,185-190,217-222,259-264,431-436` | Minimal/released-compatible config POST fixtures. They prove old payloads remain loadable; absent optional Avibe config is part of the compatibility contract. |+| `tests/fixtures/agent_registration/released_agents.json` | Released config snapshots with only native agent sections. Keep unchanged to prove missing optional Avibe loads disabled. |+| `tests/fixtures/model_hub/released_pre_avibe_consumer.json` and `tests/test_model_hub_avibe_consumer.py:538-539` | Pre-Avibe Model Hub snapshot. The test explicitly proves native rows are preserved and an empty Avibe row is added. |+| `tests/test_agent_organization_onboarding.py:82` | Explicit two-backend system-agent onboarding count fixture; it is a controlled example, not the Agent universe. |+| `tests/test_backend_model_catalog.py:1660,1678-1681`; `tests/test_latest_version_cache.py:177,182-185,245,264` | Native package/model cache neighbor fixtures. Avibe has no native CLI/latest probe. |+| `tests/test_model_hub_api.py:2295`, fixed Claude/Codex built-in catalogs; `2783`, provider candidate pair | Native fixed-menu/provider examples, not all Agent rows. |+| `tests/test_model_hub_config.py:1486`, legacy payload; `2747`, legacy Direct mode; `3166`, recovered native Direct modes | Released legacy/recovery shapes. They intentionally assert native rows stay Direct while Avibe stays Hub. |+| `tests/test_model_hub_config_read_compatibility.py:280` | Compatibility fixture for a native pending runtime service. |+| `tests/test_model_hub_l3.py:1258`, `_canonicalize_fixed_test_routes; 2259` | Fixed native menu route examples used by native resolution tests. |+| `tests/test_model_hub_migration_auth_mirror.py:54,84`; `tests/test_model_hub_migration_review_boundaries.py:135-152`; `tests/test_model_hub_migration_source_identity.py:29,83,207` | Native credential-file, journal-guard, and source-identity subsets. |+| `tests/test_model_hub_migration_custody_history.py:107,140,172,197,226,243,331,435,443` | OAuth custody/history examples deliberately cover Claude/Codex and selected OpenCode API-key combinations. |+| `tests/test_model_hub_native_takeover.py:28,175,271,430`; `tests/test_model_hub_takeover_integration.py:154`; `tests/test_model_hub_takeover_inventory.py:111` | Native takeover, credential cleanup, keychain, and journal fixtures. |+| `tests/test_model_hub_persisted_inventory.py:90,190-191,367-368`; `tests/test_model_hub_persisted_migration.py:139-151` | Shared credential consent examples for selected native stores. |+| `tests/test_model_hub_provenance.py:360` | Historical native catalog identity persisted in provenance. |+| `tests/test_model_hub_resolution.py:2377,2387` | Subscription vendor placement expected only for the fixed native vendor catalogs; Avibe has no such native vendor catalog. |+| `tests/test_model_hub_retry_policy.py:78,255`; `tests/test_opencode_model_hub_retry.py:65` | Native retry/protocol examples and cross-native launch comparison. |+| `tests/test_model_hub_runtime_default_upgrade.py:33,145-148,167,244,265,278` | Legacy on-disk upgrade fixtures intentionally omit Avibe, then assert the migration adds an empty Hub row without changing native Direct rows. |+| `tests/test_prepare_regression.py:230-234,282-286,301-305` | Regression layout/config fixtures for installed native executables. |+| `tests/test_save_opencode_provider_auth.py:484-489,718-723` | OpenCode provider-auth fixtures with disabled native peers; not a backend-universe selector. |+| `tests/test_session_fork.py:2113`; `tests/test_scheduled_tasks.py:13055` | Explicit native session/binding examples; product Session fork and Harness behavior are broader, but these fixtures exercise native ids and state. |+| `tests/test_skills_service.py:174,200-240,658,709-720,763,888,925` | CLI skill command arguments target the three native skill adapters. Do not add Avibe until an in-process skill adapter exists. |+| `tests/test_memory_removal.py:20,45` | Historical config includes native agent keys and the separate `avault` section while proving a retired top-level section is ignored. |+| `tests/test_model_hub_avibe_consumer.py:679-687` | Synthetic historical native provenance records intentionally omit Avibe origin fields. |+| `tests/e2e/test_model_hub_runtime.py:749,758` | Fixed native Direct-to-Hub switch setup and its three configured runtime blockers; empty Avibe does not block runtime stop. |+| `tests/test_agent_steering.py:288` | Constructs the real three native adapters and checks native attachment steering; no in-process adapter double is substituted. |+| `tests/test_cli_task_command.py:3652`; `tests/test_command_handler_user_names.py:760`; `tests/test_controller_im_ready.py:17`; `tests/test_controller_vibe_agent_routing.py:63,84,175`; `tests/test_runtime_activation.py:595`; `tests/test_slack_app_mention_empty.py:271` | Explicit two-native-Agent examples for default selection, cleanup, startup failures, legacy routing, activation and backend-switch isolation. They do not claim exhaustive backend membership. |+| `tests/test_incus_regression.py:1071` | Verifies installed native executable files, not Agent availability. |+| `tests/test_managed_skills.py:355,381,437` | Expected fixture skill names under native CLI home directories, not backend-universe declarations. |+| `tests/test_resume_session.py:106,176,276,299,320` | Fixed native session import/resume bindings and native hook implementations. |+| `tests/test_sqlite_sessions_store.py:679,1501,1874,4158,4285`; `tests/test_sqlite_state_migration.py:5968` | Native binding/legacy adoption and historical multi-backend native session-map conflicts. |++The following literal sites were intentionally not classified as backend+universe fixtures:++- `tests/test_backend_registration_contract.py:37-84` is the explicit C-8+ classification inventory itself.+- `tests/test_model_hub_avibe_contract_matrix.py:88` scans schema membership+ and already names all four backends; it is a contract expectation.+- `tests/test_agent_backend_catalog.py:22` and+ `tests/test_v2_config_platform_registry.py` are already catalog-derived or+ parent-fixed.+- Dicts that map one test record to a backend-specific object, such as the+ controller/resume/session-store fixtures, are per-record data rather than+ universe declarations.+- `tests/scenarios/**/catalog.yaml` backend fields identify individual+ scenarios; they are not membership lists. Other YAML/JSON hits are prose,+ observations, or single scenario records.++## Outcome++Each enumerated fixture is catalog-expanded or intentionally retained as a+native capability/example/historical shape. The production C-8 contract remains+the single automatic guard against unclassified backend declarations. Tests+do not invent native Avibe login, CLI, model defaults, Direct mode or sessions.diff --git a/docs/plans/avibe-agent-registration.md b/docs/plans/avibe-agent-registration.mdnew file mode 100644index 000000000..1b4db4d46--- /dev/null+++ b/docs/plans/avibe-agent-registration.md@@ -0,0 +1,191 @@+# Avibe Agent registration (C-8)++## Change contract++Avibe Agent is an opt-in, in-process backend. The backend catalog declares the+Agent universe and the native-CLI subset. Agent creation, routing, listings,+configuration, Model Hub and ordinary IM selectors consume the Agent universe.+Native authentication, install/version probes, native session discovery/import,+native configuration files and manual process restart consume the CLI subset.++The existing backend cards, settings page, Agent picker and model-route controls+are reused. Catalog capabilities hide unsupported native operations. A checked-in+TypeScript projection of the Python catalog supplies frontend capabilities and+types; its exact contents are contract-tested.++Persisted configs without `agents.avibe` load with it disabled. The new section+contains only `enabled`. A successful enablement mutation uses the existing+controller reconciliation IPC path. Adapter registration and controller refresh+implementation belong to `feat/avibe-agent-adapter`.++## Validation boundaries++- Catalog/classification contract: all full-universe declarations equal the Agent+ or CLI catalog set; explicit capability subsets/supersets retain their relation.+ A newly introduced literal list must fail the inventory test.+- Released config fixtures and round trips: old backend settings remain unchanged,+ absent Avibe stays off, invalid optional Avibe config recovers off on disk load.+- Agent store and run target: create, list, select and resolve an Avibe Agent using+ temporary SQLite state. Existing tests cover only CLI-backed Agents.+- UI rendering: Avibe is selectable and configurable with no native action or CLI+ probe; Model Hub exposes its existing backend model controls.+- Native boundaries: installing, authenticating, restarting or resuming a native+ Avibe session is rejected before touching any native state.+- Changed-file Ruff, focused pytest/Vitest and UI production build; exact-head+ Codex review, CI and unresolved-thread gates before delivery.++## Known by design++- No default model is invented for an empty Avibe model catalog. Model Hub owns+ its available models and the selected Agent stores the model.+- Native resume modals in Slack/Discord/Feishu are not ordinary Agent pickers;+ Avibe has no native session store and is excluded there.+- Product Session fork and Ask-in-new keep their existing UI. The adapter lane+ supplies C-5 context anchors; native-session exclusion does not disable them.+- Native setup onboarding, import and global native prompt files remain CLI-only.+- No new visual element, dependency, production restart or merge is authorized.++## Validation recorded++- Catalog, config load, readiness and regression-script batch: 143 passed.+- Expanded config-save/API/auth/native-session/IM batch: 490 passed, 99 subtests.+- Routing, dispatch, C-8 inventory, Model Hub and IM batch: 176 passed, 2 subtests.+- UI focused suites, ESLint, test type checking and production build passed.+- Changed Python Ruff and whitespace checks passed.++These are hermetic boundary checks, not a live adapter/provider acceptance run.+The adapter dependency and a later integrated Incus acceptance pass remain+explicit handoff work; no local service was restarted.++## Review ledger++### Round 1 — `f5ea8124b`++One findings-bearing reviewed head; no repeated root-cause class and no+architecture rewrite. The circuit breaker has not tripped.++- Public-symbol migration: the only removed public Python name is+ `core.vibe_agents.SUPPORTED_AGENT_BACKENDS`. Whole-repository search, including+ tests, scripts and UI, found one stale consumer module:+ `tests/test_agent_service.py` (import and parametrization). It now imports the+ catalog directly. The contract document's historical mention remains prose,+ not a caller. No compatibility alias is retained.+- No TypeScript public export was removed or renamed. `AssistantId`,+ `ASSISTANT_ORDER`, the two `BACKEND_ORDER` exports, `Backend`, `BackendId`,+ `OAuthBackend`, `AgentBackend`, `NativeCliBackend`, `AGENT_BACKENDS`,+ `AGENT_ID_TO_BACKEND` and `backendsFromAgents` keep their public names and+ derive/re-export the relevant catalog types. Private `BackendKey` and+ `BackendOption` were removed; whole-repository search found no references.+ Python `MODEL_HUB_BACKENDS`, script `SUPPORTED_BACKENDS`,+ `recommended_agent_model` and `default_cli_for_backend` retain their names.+- Reproduction: `pytest --collect-only tests/test_agent_service.py` failed with+ the reported import error before the fix. The complete file passes 104 tests+ after the import correction, including Avibe model-selection cases.+- Backend brand ownership: all four backend display names belong to catalog+ metadata and are locale-invariant product names. Translated surrounding+ prose/descriptions remain in i18n. UI maps must project the catalog rather+ than define a second literal name table; the redundant `avibeTitle` keys+ are removed.+- CI native-boundary drift: widening `DirectHome` to all Agent backends caused+ key coverage to expand a nonexistent Avibe Direct-mode description. The+ native-only landing is narrowed again; no Avibe Direct key or test exception+ is introduced.+- CI test registration: `test_v2_config_platform_registry` now compares the API+ projection with the catalog. With the orchestrator's explicit authorization,+ `tests/test_backend_registration_contract.py` is registered exactly once in+ the **I7 contract-completion implementation (backend)** binding row of+ `docs/plans/model-hub-implementation.md`; no checker/schema change was made.+ The complete Model Hub/config/registration batch passes 202 tests locally,+ including the O1 live ownership guard.+- Cross-lane integration, same round: disabled Avibe compat configuration must+ be `None`, just like Codex/OpenCode, so rolling refresh unregisters it.+ `AppCompatConfig.avibe` is optional and `to_app_config` creates it only when+ enabled. The compat-boundary regression failed first on the disabled state;+ prior config tests checked persisted fields, not the runtime absence sentinel.+ A distinct coordinator projection regression failed first because its old+ two-backend subset labeled disabled Avibe unavailable. That predicate now+ uses the Agent catalog, retaining Claude's registered-with-flag exception.+ Disabled optional backends are applied; enabled-but-unregistered backends+ remain unavailable. The obsolete native-only classification was removed.+- Compat reader audit: current-tree `.avibe` attribute reads outside tests are+ V2 config serialization/recovery, not the optional compat field. Dynamic+ compat consumers in `AgentAuthService` resolve/load `None` safely, unregister+ on absence, and skip absent auth-mirror targets; `SettingsHandler` reports+ absent config disabled. The native process inventory's CLI-path fallback is+ native-only and accepts absence. The coordinator snapshot is corrected above.+ The adapter branch at the inspected remote SHA `b64957872` guards startup+ registration with `getattr(config, "avibe", None)` and receives non-None config+ for refresh registration. Its owner retains responsibility for the requested+ `.enabled` guards and real-wiring enable/disable test; no adapter code changed+ here. Compat/coordinator/connection/registration batch: 151 passed.+- Test-fixture enumeration is recorded in+ [the fixture inventory](avibe-agent-registration-fixtures.md): the baseline+ search covered 328 literal container sites in 87 Python files and two JSON+ fixtures. A final AST pass also checks that every container-bearing test+ file is represented. Shared serializers, prompt/skill renderers, retry,+ callback, ownership probes, model catalog/metadata and IM picker matrices+ now include Avibe through the catalog. Native inherited/passthrough routes,+ Direct mode, native launch receipts, credentials and released inputs retain+ their specific semantics; they are not generalized into invented Avibe+ native behavior.++#### Backend display-name consumers++The shared path is `catalog.display_name` -> generated frontend projection ->+`AGENT_BACKENDS.label` -> `getBackendUiMeta` or derived `BACKEND_LABEL`.++| Surface | Enumerated rendering sites |+| --- | --- |+| Settings | `SettingsBackendsPage` row/configure label; `SettingsBackendPage` title/card; `BackendLifecycleChip`; `BackendRuntimeCard` through the generic page and all three native provider-config callers |+| Agent management | `NewAgentDialog` choices; `AgentsPage` group headings, filter trigger/items, import menu, import-none toast, detail prose; `GlobalPromptsDialog` native tabs/save/sync/effect; `AgentGraphOrphanStrip`; `ReadyBanner` |+| Model Hub | `AgentCard` headings/direct explanation; `SettingsModelsPage` Direct headings; `BackendSupplyModeCard`; `BackendModelCatalogDialog`; `BackendModelPickerDialog` title/builtin group; `BackendModelEditorDialog`; `SourceRow`; `SourceDetailPanel`; `SourceOrderDrawer`; `RouteChainDialog`; `RouteOriginBadge`; `GuardImpact`; `GuardGapList`; `MigrationDialog` |+| Onboarding and routing | `CollaborationStory` card/ARIA label; provider `DestinationRow`; `AssistantRow`; `BackendConnectionDialog`; `AgentDetection`; `UserList`; `ChannelList` |+| Python/IM | Slack/Discord/Feishu ordinary backend selectors; Telegram summary/inline/overflow picker; Slack/Feishu question titles; CLI doctor native-backend rows; Model Hub terminal-copy backend interpolation and blocked native-migration item names |++Removed duplicate locale keys (English and Chinese):+`settings.backends.avibeTitle`, `settings.models.backends.*`,+`onboarding.story.<native>.name`, and `agents.importFromClaude`,+`agents.importFromCodex`, `agents.importFromOpenCode`. Whole-UI search confirms+no remaining consumers. `agents.importFrom` localizes prose with backend-name+interpolation, never a display-name-derived key.++The orchestrator separately authorized catalog-only label projections/imports+in `core/handlers/model_hub/provenance.py` and+`core/handlers/model_hub/migration.py::_blocked_item`. Failure policy, vendor and+protocol mappings, Source subscription identities and non-brand copy keys are+unchanged. The three affected Model Hub fixture expectations were updated.+Python `modelHub.backends.*`, Telegram `backend.*`, and unused+`modal.question.*` brand keys were removed from both locale catalogs. Telegram's+existing overflow-picker regression first failed with `Backend: avibe`, then+passed with the catalog name.++The final repository-wide Python/TypeScript/JSON search finds no obsolete+brand-key consumers or competing rendered backend-name literals. Exact-name+hits outside the catalog/generated projection are independent test expectations,+non-rendered documentation comments, and the explicitly retained Source+subscription identities below.++Retained exceptions are Source subscription/vendor identities (`Claude`,+`ChatGPT`, etc.), complete localized native provider-page titles+(`SettingsClaudeProviderPage`, `SettingsCodexProviderPage`,+`SettingsOpencodeProviderPage`), authored+onboarding example prose/geometry, and diagnostic/monospace backend IDs. These+are not competing standalone backend display names.++UI regressions failed first for the old picker name, import-key construction,+and English/Chinese Model Hub brand ownership. Final validation: 173 focused+tests plus 2,142 Model Hub/onboarding/related tests; ESLint, test type checking+and production build pass. Existing key-coverage collector dedup fixtures remain;+the application case now guards native Direct descriptions and the absence of+an Avibe Direct key.++Additional round-1 final checks: 515 AgentService/prompt/config/Model Hub tests;+151 compat/coordinator/connection/registration tests; 20 catalog-ID cases;+11 shared delivery/ownership/default/eligibility cases; 8 planning-metadata+cases; and 269 doctor/Telegram/provenance/failure/migration/live-route tests.+These batches overlap earlier checks and are not a unique-test total.+The final i18n/migration batch passed 172 tests. Feishu/Slack routing fixture+files passed separately (8 and 7 tests): combining their existing module-level+`aiohttp` stubs with real HTTP scenario imports causes collection pollution,+so those isolated adapter fixtures were not used as a shared scenario harness.+No unrelated test bootstrap was changed.diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex f4c52fe89..a8e276fb2 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -227,7 +227,7 @@ that reconciliation may change content but is not expected to change file owners| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/**`; `tests/test_model_hub_runtime.py`; after #1312 merges, `tests/test_model_hub_l3.py` transfers to I2 for managed-Gateway runtime behavior, except for I7's one authorized AC-50 strict-xfail marker deletion. I2 owns authoritative raw shaped-error and `stream_started` facts produced by the managed Gateway only; this boundary flips at the first user-visible model-output byte, never at HTTP status, headers, or another response byte. Native backend callback facts and every classification/state decision belong to I7. The K4 increment additionally owns AC-38's install worker, persisted status/lease, orphan reconciliation, and runtime-level no-op assertions without moving the HTTP/API boundary out of I7. **Native failure ownership revised 2026-08-11 22:37.** | I1 + K4 merged; `test_model_hub_l3.py` transfer waits for #1312 merged || **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree. The K4 increment owns AC-48's OAuth registry: it atomically claims the exact nonce/vendor/channel tuple before provider work, coalesces concurrent retries to one pending terminal result, releases failure/task cancellation only before a flow exists, atomically converts success to one echoed-nonce flow, retains an explicitly canceled nonce-bearing flow as the same terminal `cancelled` flow until its existing expiry, and releases the tuple at expiry. AUTH-SETUP-210 blocks the first provider call, overlaps the same-nonce retry, and proves provider invocation exactly once. For AC-52, AUTH-SETUP-109 is the Hub-held re-auth closed loop: missing/false acknowledgement rejects before any adapter/provider call, true acknowledgement starts exactly one Hub flow, and terminal status/repair projection agrees; I7 owns the API/service gate and I5 only consumes the completed scenario. **Explicit-cancel totality revised 2026-08-12 00:37; Hub re-auth scenario binding revised 2026-08-12 01:30.** | K4 merged + #1312 merged || **I4 Sources / Gateway UI** *(tentative; one lane, two increments)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive. The current increment consumes the already-specified install/unsupported-host surfaces for AC-38/AC-43; each model row may open frame 02, render the drawing, and consume the chain read projection, but no chain-write caller is wired and Save remains disabled. Exact-chain editing and its UI tests belong to the second increment only after K5's third-round G-32 specification merges. That second increment sends visible noninterrupting hop removal as one ordinary PUT and echoes both refusal-plan arrays unchanged only when protected supply would be interrupted, after I7 freezes both fixtures; the current increment continues to consume master's pre-I7 refusal shape and must not add inactive confirmation fields. It consumes AC-36/37/39–42/44–50 only after K5 round 2 changes their G rows from gaps to contract references and registers the live-backoff presentation; AC-51's read-before-retry client rule activates in the second increment after I7 freezes the deletion/recreate fixture. AC-53's materialization-error `interrupted_pairs` consumer activates only in that second increment after K5 round 2 registers E6 and I7 freezes positive/negative API payload fixtures. AC-54's `accept_unavailable_inventory` producer also belongs to the second increment after K5 round 2 names state ⑤ and I7 freezes both server-result cells; clean creation and pull-origin state ⑤′ never emit it. This is an ordering split inside I4, not a new lane identity. **Revised through the 2026-08-12 04:40 PM ruling.** | current increment: I1 envelopes + K4 contracts; second increment: K5 rounds 1–3 merged + frozen I7/I2/I3 fixtures |-| **I7 contract-completion implementation (backend)** | codex | After K6 merges, exclusive ownership transfers from I1 for `config/v2_config.py`; `core/handlers/model_hub/{service,resolver,classification,rpc,request,errors,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; and `tests/test_model_hub_resolution.py`. For the Model Hub failure-callback seam only, I7 also exclusively owns `modules/agents/base.py`, `modules/agents/claude_agent.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`, exact cross-backend phase fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py`, and mechanical signature consumers in `tests/{test_claude_cli_path,test_multi_platform_runtime}.py`. I7 owns AC-35–AC-47 and AC-50–AC-54's backend producers/tests plus AC-48's API/service half. `service.py` is the sole shared guard-plan owner and implements every guard-totality row and the error-to-required-array relation; it also enforces AC-52's both-channel re-auth acknowledgement before any OAuth adapter call and AC-53's materialization-error response condition, and AC-54's unavailable-inventory consent gate against the repeated server observation. `modules/agents/model_hub.py` owns the native classification/state decision: backend callbacks supply raw failure shape and phase only, and no native path writes a persistent network cooldown. The transferred resolver/classifier/event boundary owns `retired: false` filtering and all four network-failure cells; its post-output executor/provenance fixture consumes K6's G-34 row without inventing an outcome id, copy key, or payload shape. I7 delegates OAuth tuple claim/coalescing and terminal-flow expiry to I3's registry; its service/API half branches explicit cancellation by nonce presence, retaining the I3 flow for nonce-bearing reconciliation and forgetting only no-nonce flows. Its first AC-50 mechanical action is the sole owner-authorized I2-file exception: delete the strict xfail marker from `tests/test_model_hub_l3.py::test_probe_transport_failures_await_ac50_backoff_contract` in the same commit that makes its forward contract assertions XPASS; it otherwise consumes I2 managed-Gateway facts and I3 OAuth fixtures without editing their files. It never edits contracts, UI/i18n, scenario trees, or any other I2–I5 file. **Revised through the 2026-08-12 04:40 PM ruling.** | K4 + #1312 + K6 merged; every listed transfer and native callback seam activates only after all three merge |+| **I7 contract-completion implementation (backend)** | codex | After K6 merges, exclusive ownership transfers from I1 for `config/v2_config.py`; `core/handlers/model_hub/{service,resolver,classification,rpc,request,errors,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; `tests/test_backend_registration_contract.py`; and `tests/test_model_hub_resolution.py`. For the Model Hub failure-callback seam only, I7 also exclusively owns `modules/agents/base.py`, `modules/agents/claude_agent.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`, exact cross-backend phase fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py`, and mechanical signature consumers in `tests/{test_claude_cli_path,test_multi_platform_runtime}.py`. I7 owns AC-35–AC-47 and AC-50–AC-54's backend producers/tests plus AC-48's API/service half. `service.py` is the sole shared guard-plan owner and implements every guard-totality row and the error-to-required-array relation; it also enforces AC-52's both-channel re-auth acknowledgement before any OAuth adapter call and AC-53's materialization-error response condition, and AC-54's unavailable-inventory consent gate against the repeated server observation. `modules/agents/model_hub.py` owns the native classification/state decision: backend callbacks supply raw failure shape and phase only, and no native path writes a persistent network cooldown. The transferred resolver/classifier/event boundary owns `retired: false` filtering and all four network-failure cells; its post-output executor/provenance fixture consumes K6's G-34 row without inventing an outcome id, copy key, or payload shape. I7 delegates OAuth tuple claim/coalescing and terminal-flow expiry to I3's registry; its service/API half branches explicit cancellation by nonce presence, retaining the I3 flow for nonce-bearing reconciliation and forgetting only no-nonce flows. Its first AC-50 mechanical action is the sole owner-authorized I2-file exception: delete the strict xfail marker from `tests/test_model_hub_l3.py::test_probe_transport_failures_await_ac50_backoff_contract` in the same commit that makes its forward contract assertions XPASS; it otherwise consumes I2 managed-Gateway facts and I3 OAuth fixtures without editing their files. It never edits contracts, UI/i18n, scenario trees, or any other I2–I5 file. **Revised through the 2026-08-12 04:40 PM ruling.** | K4 + #1312 + K6 merged; every listed transfer and native callback seam activates only after all three merge || **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 + I7 || **I8 bounded recovery and readiness observation** *(orchestrator-approved)* | codex | `core/model_hub_progress.py` consumes canonical resolver timestamps and the read-only request recovery snapshot for the existing live working/activity surface. `vibe/api.py` projects backend connection readiness from canonical eligibility/runnability and an engine-owned boolean credential-ownership check, following the native takeover contract. Neither observer classifies, retries, writes Source health, or owns another recovery timer. Controller, native-terminal and UI integration remain orchestrator-owned; each resolver consumer has one explicit owner without transferring core policy ownership. | Approved recovery contracts, native takeover connection-ownership contract, and the core policy/provenance hooks || **I6 default-on availability** *(owner-approved 2026-09-06)* | codex | Replace the shared capability resolver's absent-variable default with enabled; retain its explicit deployment/emergency opt-out. Verify controller aggregate construction, public API/capability projection and internal RPC with no environment opt-in. Saved backend modes, routing, model selection and engine-install consent remain unchanged. This supersedes the historical default-off and full gate-deletion directions below; it is not a constant-true shell. | Owner requested a PR to make Model Hub available by default. Full merged LOCAL live/visual acceptance remains outstanding and is not waived or claimed by this release-default change. |diff --git a/modules/agents/catalog.py b/modules/agents/catalog.pyindex 6842daa26..d1d2b7027 100644--- a/modules/agents/catalog.py+++ b/modules/agents/catalog.py@@ -3,11 +3,16 @@from __future__ import annotationsfrom dataclasses import asdict, dataclass-from typing import Final+from typing import Final, Literal++NativeCliBackend = Literal["opencode", "claude", "codex"]+AgentBackend = Literal[NativeCliBackend, "avibe"]@dataclass(frozen=True)class AgentBackendCapabilities:+ supports_cli: bool = True+ supports_native_sessions: bool = Truesupports_runtime_refresh: bool = Truesupports_web_oauth: bool = Truesupports_install: bool = True@@ -18,7 +23,7 @@ class AgentBackendDescriptor:id: strdisplay_name: strconfig_key: str- default_cli: str+ default_cli: str | Nonedefault_enabled: boollatest_probe: tuple[str, str] | Nonecapabilities: AgentBackendCapabilities@@ -66,9 +71,29 @@ AGENT_BACKEND_REGISTRY: Final[dict[str, AgentBackendDescriptor]] = {latest_probe=("npm", "@openai/codex"),capabilities=AgentBackendCapabilities(),),+ "avibe": AgentBackendDescriptor(+ id="avibe",+ display_name="Avibe Agent",+ config_key="avibe",+ default_cli=None,+ default_enabled=False,+ latest_probe=None,+ capabilities=AgentBackendCapabilities(+ supports_cli=False,+ supports_native_sessions=False,+ supports_runtime_refresh=False,+ supports_web_oauth=False,+ supports_install=False,+ ),+ ),}AGENT_BACKENDS: Final[tuple[str, ...]] = tuple(AGENT_BACKEND_REGISTRY)+NATIVE_CLI_BACKENDS: Final[tuple[str, ...]] = tuple(+ descriptor.id+ for descriptor in AGENT_BACKEND_REGISTRY.values()+ if descriptor.capabilities.supports_cli+)DEFAULT_AGENT_BACKEND: Final[str] = "opencode"RUNTIME_REFRESH_BACKENDS: Final[frozenset[str]] = frozenset(descriptor.id@@ -116,7 +141,7 @@ def agent_backend_catalog_payload() -> list[dict]:return [descriptor.to_public_dict() for descriptor in agent_backend_descriptors()]-def default_cli_for_backend(name: str) -> str:+def default_cli_for_backend(name: str) -> str | None:"""Return the default CLI command for *name*."""return get_agent_backend_descriptor(name).default_cli@@ -145,6 +170,11 @@ def supports_runtime_refresh(name: str) -> bool:return name in RUNTIME_REFRESH_BACKENDS+def is_native_cli_backend(name: str) -> bool:+ """Return whether a backend owns an external CLI and native configuration."""+ return name in NATIVE_CLI_BACKENDS++def supports_web_oauth(name: str) -> bool:"""Return whether *name* supports Web Settings OAuth setup."""return name in WEB_OAUTH_BACKENDSdiff --git a/modules/agents/native_sessions/types.py b/modules/agents/native_sessions/types.pyindex 36a29bd0d..51fb3cb08 100644--- a/modules/agents/native_sessions/types.py+++ b/modules/agents/native_sessions/types.py@@ -5,7 +5,9 @@ from datetime import datetimefrom typing import Any, Literal-AgentName = Literal["opencode", "claude", "codex"]+from modules.agents.catalog import NativeCliBackend++AgentName = NativeCliBackendAgentPrefix = Literal["oc", "cc", "cx"]diff --git a/modules/agents/service.py b/modules/agents/service.pyindex 712ea62c3..1e72cddee 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -365,9 +365,9 @@ class AgentService:# never break the turn.await self._begin_turn_status(request.context)from core.agent_model_selection import require_agent_model- from core.vibe_agents import SUPPORTED_AGENT_BACKENDS+ from modules.agents.catalog import AGENT_BACKENDS- if agent.name in SUPPORTED_AGENT_BACKENDS:+ if agent.name in AGENT_BACKENDS:has_subagent_model = request.subagent_model is not Noneselected_model = require_agent_model(request.subagent_model if has_subagent_model else request.vibe_agent_model,diff --git a/modules/im/discord.py b/modules/im/discord.pyindex c6f02548a..a5984f462 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -1,4 +1,5 @@import asyncio+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backendimport ioimport jsonimport logging@@ -1423,11 +1424,11 @@ class DiscordBot(BaseIMClient):):interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else Nonet = lambda key, **kw: self._t(key, channel_id, **kw)- common_agents = ["claude", "codex", "opencode"]+ common_agents = NATIVE_CLI_BACKENDSregistered_backends = Noneif getattr(self, "_controller", None) and getattr(self._controller, "agent_service", None):registered_backends = list(self._controller.agent_service.agents.keys())- allowed_agents = set(registered_backends or common_agents)+ allowed_agents = set(registered_backends or common_agents) & set(NATIVE_CLI_BACKENDS)sessions = [item for item in sessions if item.agent in allowed_agents]options = []@@ -1585,9 +1586,7 @@ class DiscordBot(BaseIMClient):interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else Nonebackend_display_names = {- "claude": "ClaudeCode",- "codex": "Codex",- "opencode": "OpenCode",+ backend: display_name_for_backend(backend) for backend in AGENT_BACKENDS}def _prefixed_label(prefix_key: str, label: str, limit: int = 100) -> str:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex ea90171f2..3bf464ce0 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -1,6 +1,7 @@"""Feishu/Lark implementation of the IM client using lark-oapi SDK."""import asyncio+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backendimport ioimport jsonimport logging@@ -2103,7 +2104,7 @@ class FeishuBot(BaseIMClient):draft: Dict[str, Optional[str]] = {}for field_name in fields:draft[field_name] = getattr(current_routing, field_name, None) if current_routing else None- if selected_backend in {"opencode", "claude", "codex"} and current_routing:+ if selected_backend in AGENT_BACKENDS and current_routing:model = getattr(current_routing, "model", None)reasoning_effort = getattr(current_routing, "reasoning_effort", None)draft[f"{selected_backend}_model"] = draft.get(f"{selected_backend}_model") or model@@ -2628,7 +2629,7 @@ class FeishuBot(BaseIMClient):for b in registered_backends:backend_options.append({- "text": {"tag": "plain_text", "content": b},+ "text": {"tag": "plain_text", "content": display_name_for_backend(b)},"value": b,})@@ -2995,11 +2996,11 @@ class FeishuBot(BaseIMClient):sessions_by_agent = {}# --- Build agent options (from registered backends or fallback) ---- common_agents = ["claude", "codex", "opencode"]+ common_agents = NATIVE_CLI_BACKENDSregistered_backends = Noneif getattr(self, "_controller", None) and getattr(self._controller, "agent_service", None):registered_backends = list(self._controller.agent_service.agents.keys())- allowed_agents = set(registered_backends) if registered_backends else set(common_agents)+ allowed_agents = set(registered_backends or common_agents) & set(NATIVE_CLI_BACKENDS)agent_options = []for agent in sorted(allowed_agents):agent_options.append({"text": {"tag": "plain_text", "content": agent.capitalize()}, "value": agent})@@ -3273,7 +3274,7 @@ class FeishuBot(BaseIMClient):})- title = t("modal.question.claudeCode")+ title = display_name_for_backend("claude")card = {"schema": "2.0",diff --git a/modules/im/slack.py b/modules/im/slack.pyindex ffe910034..b172ea78c 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1,4 +1,5 @@import asyncio+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backendimport hashlibimport jsonimport logging@@ -3305,11 +3306,11 @@ class SlackBot(BaseIMClient):self._ensure_clients()# Build agent options limited to enabled backends when available- common_agents = ["claude", "codex", "opencode"]+ common_agents = NATIVE_CLI_BACKENDSregistered_backends = Noneif getattr(self, "_controller", None) and getattr(self._controller, "agent_service", None):registered_backends = list(self._controller.agent_service.agents.keys())- allowed_agents = set(registered_backends) if registered_backends else set(common_agents)+ allowed_agents = set(registered_backends or common_agents) & set(NATIVE_CLI_BACKENDS)agent_keys = allowed_agentsagent_options = []for agent in sorted(agent_keys):@@ -3541,9 +3542,7 @@ class SlackBot(BaseIMClient):"""Build modal view for agent/model routing settings."""# Build backend optionsbackend_display_names = {- "claude": "ClaudeCode",- "codex": "Codex",- "opencode": "OpenCode",+ backend: display_name_for_backend(backend) for backend in AGENT_BACKENDS}backend_options = []for backend in registered_backends:@@ -4286,11 +4285,7 @@ class SlackBot(BaseIMClient):# Use callback_prefix to generate callback_idcallback_id = f"{callback_prefix}_modal"- title = (- self._t("modal.question.claudeCode")- if callback_prefix.startswith("claude")- else self._t("modal.question.claudeCode")- )+ title = display_name_for_backend("claude")view = {"type": "modal",diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex a85a3aa76..a39ecacf6 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, Optionalfrom config.v2_config import TelegramConfig+from modules.agents.catalog import display_name_for_backendfrom core import chat_discoveryfrom core.message_context import resolve_context_scope_settings_key, resolve_context_thread_idfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -1799,8 +1800,7 @@ class TelegramBot(BaseIMClient):state.message_id = await self.send_message_with_buttons(target_context, text, keyboard)def _get_backend_label(self, backend: str) -> str:- translated = self._t(f"backend.{backend}")- return translated if translated != f"backend.{backend}" else backend+ return display_name_for_backend(backend)def _option_label(self, value: Optional[str], default_label: Optional[str] = None) -> str:if not value:diff --git a/scripts/generate_agent_backend_catalog.py b/scripts/generate_agent_backend_catalog.pynew file mode 100644index 000000000..ae4422836--- /dev/null+++ b/scripts/generate_agent_backend_catalog.py@@ -0,0 +1,21 @@+"""Project the Python backend declaration into the frontend's typed catalog."""++from __future__ import annotations++import json++from modules.agents.catalog import agent_backend_catalog_payload+++def render() -> str:+ return (+ "// Generated from modules/agents/catalog.py; do not edit.\n"+ "// Regenerate with: uv run python -m scripts.generate_agent_backend_catalog\n"+ "export const BACKEND_CATALOG = "+ + json.dumps(agent_backend_catalog_payload(), ensure_ascii=False, indent=2)+ + " as const;\n"+ )+++if __name__ == "__main__":+ print(render(), end="")diff --git a/scripts/incus_tenant.py b/scripts/incus_tenant.pyindex 9fa63186b..64e3a3530 100755--- a/scripts/incus_tenant.py+++ b/scripts/incus_tenant.py@@ -12,6 +12,7 @@ import errnoimport ipaddressimport jsonimport re+import runpyimport shleximport shutilimport socket@@ -22,6 +23,10 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Sequence+_BACKEND_CATALOG = runpy.run_path(str(Path(__file__).resolve().parents[1] / "modules/agents/catalog.py"))+AGENT_BACKENDS = _BACKEND_CATALOG["AGENT_BACKENDS"]+NATIVE_CLI_BACKENDS = _BACKEND_CATALOG["NATIVE_CLI_BACKENDS"]+PROJECT_PREFIX = "vr-"INSTANCE_NAME_PREFIX = "vibe-"@@ -197,7 +202,7 @@ def yaml_block(value: str, indent: int = 6) -> str:def default_config(spec: TenantSpec) -> dict:- enabled = {spec.backend, "opencode", "claude", "codex"}+ enabled = {spec.backend, *NATIVE_CLI_BACKENDS}return {"platform": "slack","platforms": {"enabled": ["slack"], "primary": "slack"},@@ -213,6 +218,7 @@ def default_config(spec: TenantSpec) -> dict:"opencode": {"enabled": "opencode" in enabled, "cli_path": "opencode", "error_retry_limit": 1},"claude": {"enabled": "claude" in enabled, "cli_path": "claude"},"codex": {"enabled": "codex" in enabled, "cli_path": "codex"},+ "avibe": {"enabled": "avibe" in enabled},},"gateway": None,"ui": {"setup_host": "0.0.0.0", "setup_port": spec.ui_port, "open_browser": False},@@ -652,7 +658,7 @@ def build_parser() -> argparse.ArgumentParser:help="Host address for the optional Web UI proxy. Use 0.0.0.0 only behind a firewall or reverse proxy.",)create.add_argument("--ui-host-port", type=int, help="Optional host port proxy for the tenant Web UI.")- create.add_argument("--backend", choices=["opencode", "claude", "codex"], default="opencode", help="Default agent backend.")+ create.add_argument("--backend", choices=AGENT_BACKENDS, default="opencode", help="Default agent backend.")create.add_argument("--install-package-spec",help="Optional package spec passed to the avibe installer, e.g. git+https://github.com/avibe-bot/avibe.git@master.",diff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.pyindex 930e0c920..40d2eb1db 100755--- a/scripts/prepare_regression.py+++ b/scripts/prepare_regression.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport argparseimport jsonimport os+import runpyimport shutilimport sqlite3import sys@@ -49,7 +50,11 @@ PLATFORM_DEFS = {},}-SUPPORTED_BACKENDS = {"opencode", "claude", "codex"}+# Load the stdlib-only declaration without importing the application package:+# this bootstrap script also runs before application dependencies are installed.+SUPPORTED_BACKENDS = frozenset(+ runpy.run_path(str(Path(__file__).resolve().parents[1] / "modules/agents/catalog.py"))["AGENT_BACKENDS"]+)RESET_MODES = {"none", "config", "all"}CONTAINER_HOME = Path("/home/avibe")CONTAINER_AVIBE_HOME = CONTAINER_HOME / ".avibe"@@ -207,6 +212,9 @@ def _build_config_payload() -> dict:"enabled": True,"cli_path": "codex",},+ "avibe": {+ "enabled": any(_env(definition["backend_env"]) == "avibe" for definition in PLATFORM_DEFS.values()),+ },},"gateway": None,"ui": {diff --git a/storage/background.py b/storage/background.pyindex 0e8ce46c7..c5c01dea5 100644--- a/storage/background.py+++ b/storage/background.py@@ -3240,9 +3240,9 @@ def _capture_run_backend(conn: Any, values: dict[str, Any]) -> Optional[str]:if cleaned_agent_backend:return cleaned_agent_backend- from core.vibe_agents import SUPPORTED_AGENT_BACKENDS+ from modules.agents.catalog import AGENT_BACKENDS- return agent_name if agent_name in SUPPORTED_AGENT_BACKENDS else None+ return agent_name if agent_name in AGENT_BACKENDS else Nonedef enqueue_run_in_connection(conn: Any, values: dict[str, Any]) -> None:diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 571154cc2..60cf96d49 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -13,6 +13,7 @@ from sqlalchemy.dialects.sqlite import insert as sqlite_insertfrom sqlalchemy.exc import IntegrityErrorfrom config import paths+from modules.agents.catalog import AGENT_BACKENDS, display_name_for_backendfrom config.v2_config import V2Configfrom config.v2_sessions import ActivePollInfo, SessionStatefrom config.v2_settings import _split_scoped_key@@ -218,7 +219,10 @@ def _set_native_once(conn: Connection, row_id: str, encoded_session_id: str) ->return False-_BACKEND_LABELS = {"claude": "Claude", "codex": "Codex", "opencode": "OpenCode"}+_BACKEND_LABELS = {+ backend: "Claude" if backend == "claude" else display_name_for_backend(backend)+ for backend in AGENT_BACKENDS+}def session_agent_display_label(row: Mapping[str, Any]) -> str | None:@@ -2437,7 +2441,7 @@ def _infer_scope_type(platform: str, native_id: str) -> str:return "channel"-_BACKEND_AGENT_NAMES = {"codex", "claude", "opencode"}+_BACKEND_AGENT_NAMES = frozenset(AGENT_BACKENDS)_ROUTING_SENTINEL_VARIANTS = {"", "default", *_BACKEND_AGENT_NAMES}diff --git a/tests/fixtures/agent_registration/released_agents.json b/tests/fixtures/agent_registration/released_agents.jsonnew file mode 100644index 000000000..553965648--- /dev/null+++ b/tests/fixtures/agent_registration/released_agents.json@@ -0,0 +1,44 @@+[+ {+ "name": "legacy_backend_defaults",+ "agents": {+ "default_backend": "codex",+ "opencode": {"enabled": true, "cli_path": "/opt/opencode", "default_model": "old-model", "default_agent": "build"},+ "claude": {"enabled": false, "cli_path": "/opt/claude"},+ "codex": {"enabled": true, "cli_path": "/opt/codex"}+ },+ "preserved": {+ "opencode": {"enabled": true, "cli_path": "/opt/opencode", "default_agent": "build"},+ "claude": {"enabled": false, "cli_path": "/opt/claude"},+ "codex": {"enabled": true, "cli_path": "/opt/codex"}+ }+ },+ {+ "name": "native_auth_and_vault",+ "agents": {+ "opencode": {"enabled": false, "default_provider": "custom-provider"},+ "claude": {"enabled": true, "auth_mode": "api_key", "api_key": "fixture-key", "base_url": "https://fixture.invalid", "auth_mode_set": true},+ "codex": {"enabled": false, "auth_mode": "oauth", "oauth_relay_marker": {"provider_id": "custom", "base_url": "https://relay.invalid"}},+ "avault": {"cli_path": "/fixture/avault"}+ },+ "preserved": {+ "opencode": {"enabled": false, "default_provider": "custom-provider"},+ "claude": {"enabled": true, "auth_mode": "api_key", "api_key": "fixture-key", "base_url": "https://fixture.invalid", "auth_mode_set": true},+ "codex": {"enabled": false, "auth_mode": "oauth", "oauth_relay_marker": {"provider_id": "custom", "base_url": "https://relay.invalid"}},+ "avault": {"cli_path": "/fixture/avault"}+ }+ },+ {+ "name": "runtime_lifecycle_settings",+ "agents": {+ "opencode": {"enabled": true, "auto_update": false, "active_turn_timeout_seconds": 7200, "legacy_turn_timeout_neutralized": true},+ "claude": {"enabled": true, "auto_update": false, "idle_timeout_seconds": 900},+ "codex": {"enabled": true, "auto_update": true, "idle_timeout_seconds": 1200}+ },+ "preserved": {+ "opencode": {"enabled": true, "auto_update": false, "active_turn_timeout_seconds": 7200},+ "claude": {"enabled": true, "auto_update": false, "idle_timeout_seconds": 900},+ "codex": {"enabled": true, "auto_update": true, "idle_timeout_seconds": 1200}+ }+ }+]diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.pyindex 503354d24..144542050 100644--- a/tests/scenario_harness/model_hub.py+++ b/tests/scenario_harness/model_hub.py@@ -367,10 +367,11 @@ def unlisted_model_copy(backend: str, language: str = "en") -> str:"""The one refusal every backend shows for a turn on ``UNLISTED_MODEL``."""from vibe.i18n import t+ from modules.agents.catalog import display_name_for_backendreturn t("modelHub.launch.model_unlisted",language,model=UNLISTED_MODEL,- backend=t(f"modelHub.backends.{backend}", language),+ backend=display_name_for_backend(backend),)diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex 5a640ffdf..0d0dc8b00 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -12,6 +12,7 @@ from typing import AsyncIterator, Callableimport aiohttpimport pytest+from modules.agents.catalog import display_name_for_backendfrom config.v2_config import (ModelHubAgentSourcesConfig,@@ -1423,7 +1424,7 @@ def test_mh_unlisted_001_removed_model_fails_its_next_turn_with_one_clear_reason"modelHub.launch.model_unlisted",language,model=model_id,- backend=i18n_t(f"modelHub.backends.{backend}", language),+ backend=display_name_for_backend(backend),)assert str(refused.value) == expectedassert model_id in expected@@ -1522,7 +1523,7 @@ def test_opencode_refuses_an_unlisted_model_its_retained_route_cannot_address("modelHub.launch.model_unlisted","en",model=model_id,- backend=i18n_t("modelHub.backends.opencode", "en"),+ backend=display_name_for_backend("opencode"),)assert prewrite_failure_evidence(context) == {"reason": "model_hub_model_unlisted", "requires_explicit_retry": True,diff --git a/tests/test_agent_backend_catalog.py b/tests/test_agent_backend_catalog.pyindex 5d7b8e6a9..01649f10c 100644--- a/tests/test_agent_backend_catalog.py+++ b/tests/test_agent_backend_catalog.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom modules.agents.catalog import (AGENT_BACKENDS,+ NATIVE_CLI_BACKENDS,DEFAULT_AGENT_BACKEND,agent_backend_catalog_payload,default_cli_for_backend,@@ -18,10 +19,10 @@ from vibe import apidef test_agent_catalog_is_backend_management_source_of_truth() -> None:- assert AGENT_BACKENDS == ("opencode", "claude", "codex")+ assert AGENT_BACKENDS == ("opencode", "claude", "codex", "avibe")assert DEFAULT_AGENT_BACKEND == "opencode"- for backend in AGENT_BACKENDS:+ for backend in NATIVE_CLI_BACKENDS:assert is_agent_backend(backend)assert supports_runtime_refresh(backend)assert supports_web_oauth(backend)@@ -33,6 +34,14 @@ def test_agent_catalog_is_backend_management_source_of_truth() -> None:assert display_name_for_backend("opencode") == "OpenCode"assert display_name_for_backend("claude") == "Claude Code"assert default_enabled_for_backend("codex") is False+ assert is_agent_backend("avibe")+ assert display_name_for_backend("avibe") == "Avibe Agent"+ assert not default_enabled_for_backend("avibe")+ assert default_cli_for_backend("avibe") is None+ assert latest_probe_for_backend("avibe") is None+ assert not supports_runtime_refresh("avibe")+ assert not supports_web_oauth("avibe")+ assert not supports_install("avibe")assert not is_agent_backend("unknown")assert not supports_runtime_refresh("unknown")assert not supports_web_oauth("unknown")diff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 85f1b9ae6..bcb2942d3 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -16,7 +16,7 @@ from core.native_dispatch_phase import (set_dispatch_phase,)from core.session_activities import SessionActivityRegistry-from core.vibe_agents import SUPPORTED_AGENT_BACKENDS+from modules.agents.catalog import AGENT_BACKENDSfrom modules.agents import service as service_modulefrom modules.agents.service import AgentServicefrom modules.agents.codex.transport import CodexTransport@@ -337,7 +337,7 @@ def _request(message: str, runtime_key: str = "session:/repo"):)[email protected]("backend", sorted(SUPPORTED_AGENT_BACKENDS))[email protected]("backend", sorted(AGENT_BACKENDS))@pytest.mark.parametrize("model", [None, "", " ", "default", "fixture-avibe-model", " padded-model "])@pytest.mark.parametrize("selection_field", ["vibe_agent_model", "subagent_model"])def test_model_selection_is_required_before_any_backend_dispatch(backend, model, selection_field):diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 42c1b76e5..8ca067afd 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -15,6 +15,7 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from config import paths+from modules.agents.catalog import AGENT_BACKENDSfrom config.v2_config import (_FIELD_SCOPED_RECOVERY_SECTIONS,AudioAsrConfig,@@ -166,7 +167,7 @@ def test_save_config_merges_partial_payload(monkeypatch, tmp_path, sqlite_schemaassert original.update.auto_update is Falseassert all(not hasattr(getattr(original.agents, backend), "default_model")- for backend in ("claude", "codex", "opencode")+ for backend in AGENT_BACKENDS)updated = api.save_config({"show_duration": False, "include_time_info": False, "update": {"auto_update": True}})@@ -1273,7 +1274,7 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path,# ``platform_configs`` is the internal per-platform aggregate; it is emitted# under each platform's own key, not as a top-level ``platform_configs`` key.top_level = {f.name for f in fields(V2Config)} - {"platform_configs"}- agents = {"opencode", "claude", "codex", "avault"}+ agents = set(AGENT_BACKENDS) | {"avault"}def _assert_complete(label: str, payload: dict) -> None:assert top_level <= set(payload), f"{label} top-level missing: {top_level - set(payload)}"diff --git a/tests/test_avibe_backend_registration.py b/tests/test_avibe_backend_registration.pynew file mode 100644index 000000000..e4f0e2edc--- /dev/null+++ b/tests/test_avibe_backend_registration.py@@ -0,0 +1,149 @@+"""C-8 behavioral boundaries absent from the released three-CLI fixtures."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from config.v2_config import V2Config+from config.v2_compat import to_app_config+from config.v2_settings import RoutingSettings+from core.controller import Controller+from core.services.agent_run_target import resolve_agent_run_target+from core.vibe_agents import VibeAgentStore+from modules.im import MessageContext+from tests.test_api_save_config_merge import _full_config_payload+from vibe import api+++RELEASED = json.loads((Path(__file__).parent / "fixtures/agent_registration/released_agents.json").read_text())++[email protected]("fixture", RELEASED, ids=lambda fixture: fixture["name"])+def test_released_config_shapes_preserve_native_settings_and_keep_avibe_off(tmp_path, fixture):+ """A new optional backend must not change released config values or enable itself."""+ payload = _full_config_payload()+ payload["agents"] = fixture["agents"]+ path = tmp_path / "config.json"+ path.write_text(json.dumps(payload))+ loaded = V2Config.load(path, persist_migrations=False)+ for config in (loaded, V2Config.from_payload(api.config_to_payload(loaded, include_secrets=True))):+ assert config.agents.avibe.enabled is False+ assert config.agents.avibe.__dict__ == {"enabled": False}+ for backend, expected in fixture["preserved"].items():+ actual = getattr(config.agents, backend).__dict__+ assert {field: actual[field] for field in expected} == expected++[email protected]("invalid", [None, [], "invalid", {"enabled": "false"}, {"enabled": 1}])+def test_invalid_optional_avibe_config_recovers_off_without_disabling_native_backends(tmp_path, invalid):+ """Malformed new optional state must recover locally, not prevent startup."""+ payload = _full_config_payload()+ payload["agents"]["avibe"] = invalid+ path = tmp_path / "config.json"+ path.write_text(json.dumps(payload))+ loaded = V2Config.load(path, persist_migrations=False)+ assert loaded.agents.avibe.enabled is False+ assert loaded.agents.codex.enabled is True+ assert loaded.agents.opencode.active_turn_timeout_seconds == 7200+ assert loaded.load_warnings+++def test_avibe_agent_can_be_created_listed_selected_and_routed(tmp_path, sqlite_db_factory):+ """The store and shared run-target resolver must agree on the fourth backend."""+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ blank = store.create(name="unconfigured", backend="avibe")+ assert blank.model is None # No native model recommendation for an empty Hub catalog.+ created = store.create(name="worker-工作助手", backend="avibe", model="team-model", system_prompt="Follow the plan.")+ store.set_default_agent_name(created.name)+ assert [(agent.name, agent.backend) for agent in store.list_agents() if agent.id == created.id] == [+ ("worker-工作助手", "avibe")+ ]+ config = V2Config.from_payload(_full_config_payload())+ config.agents.avibe.enabled = True+ controller = Controller.__new__(Controller)+ controller.primary_platform = "slack"+ controller.sqlite_engine = store.engine+ controller.config = to_app_config(config, resolve_agent_paths=False)+ controller.agent_service = SimpleNamespace(agents={"avibe": object()})+ controller.vibe_agent_store = store+ controller._get_settings_key = lambda context: context.channel_id+ controller.get_settings_manager_for_context = lambda _context: SimpleNamespace(+ get_channel_routing=lambda _key: RoutingSettings(agent_name=created.name),+ )+ context = MessageContext(user_id="test", channel_id="C-test", platform="slack")+ assert controller.resolve_agent_for_context(context) == "avibe"+ target = resolve_agent_run_target(context, controller=controller, create_session=False)+ assert target.agent_backend == "avibe"+ assert target.agent_name == "worker-工作助手"+ assert target.model == "team-model"+ assert api._enabled_agent_backends_from_config(config)[-1] == "avibe"+ finally:+ store.close()+++def test_avibe_native_operations_are_rejected_before_any_native_probe(monkeypatch):+ """Expanding Agent registration must not enable the same id on native APIs."""+ from vibe import cli, global_agents_md++ def forbidden(*_args, **_kwargs):+ pytest.fail("in-process backend reached a native/CLI path")++ monkeypatch.setattr(api, "resolve_cli_path", forbidden)+ monkeypatch.setattr(api, "load_config", forbidden)+ monkeypatch.setattr(api, "_runtime_command_dir", forbidden)+ monkeypatch.setattr(api, "MigrationFileLock", forbidden)+ assert api.start_agent_install_job("avibe")["ok"] is False+ assert api.install_agent("avibe")["ok"] is False+ assert api.get_backend_runtime("avibe")["ok"] is False+ assert api.restart_backend("avibe")["ok"] is False+ with pytest.raises(ValueError):+ global_agents_md.global_instruction_path("avibe")+ parser = cli.build_parser()+ assert parser.parse_args(["agent", "create", "worker", "--backend", "avibe"]).backend == "avibe"+ assert parser.parse_args(["agent", "models", "--backend", "avibe"]).backend == "avibe"+ with pytest.raises(SystemExit):+ parser.parse_args(["agent", "import", "--from", "avibe", "--all"])+++def test_native_auth_refresh_preserves_enabled_avibe_builtin(tmp_path, sqlite_db_factory, monkeypatch):+ """Native auth refresh synchronizes all built-ins; CLI-only fixtures miss cross-backend disablement."""+ from core.agent_auth_service import AgentAuthService++ config = V2Config.from_payload(_full_config_payload())+ config.agents.avibe.enabled = True+ monkeypatch.setattr(V2Config, "load", lambda: config)+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ store.ensure_builtin_default_agents(["avibe"])+ service = AgentAuthService(SimpleNamespace(vibe_agent_store=store))+ service._sync_builtin_default_agents()+ avibe = store.get("avibe")+ assert avibe is not None and avibe.enabled+ assert avibe.backend == "avibe"+ finally:+ store.close()+++def test_avibe_model_options_come_from_configured_hub_catalog(monkeypatch):+ """A new backend must not fall through to the OpenCode provider reader."""+ from config.v2_config import ModelHubBackendModelConfig++ config = V2Config.from_payload(_full_config_payload())+ config.model_hub.agents["avibe"].models = [+ ModelHubBackendModelConfig(+ id="team-model", origin="manual", display_name="Team Model",+ reasoning_efforts=["low", "high"], supports_reasoning=True,+ )+ ]+ monkeypatch.setattr(V2Config, "load", lambda: config)+ monkeypatch.setattr(api, "_opencode_model_options", lambda **_: pytest.fail("native model lookup"))+ assert api.agent_model_options("avibe")["models"] == [+ {"value": "team-model", "label": "Team Model", "reasoning_efforts": ["low", "high"]}+ ]+ config.model_hub.agents["avibe"].models = []+ assert api.agent_model_options("avibe")["models"] == []diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.pyindex 279652f55..141087437 100644--- a/tests/test_backend_connection.py+++ b/tests/test_backend_connection.py@@ -433,6 +433,33 @@ def _store_hub_credential(source):return store+def test_avibe_connection_uses_hub_supply_without_any_native_probe(hub_connection, monkeypatch):+ """The new backend has no CLI; the existing native cases cannot protect that boundary."""+ from core import backend_restart++ def forbidden(*_args, **_kwargs):+ pytest.fail("Avibe connection inspected a native CLI or takeover journal")++ monkeypatch.setattr(api, "resolve_cli_path", forbidden)+ monkeypatch.setattr(backend_restart, "pending_native_backends", forbidden)+ hub_connection.config.agents.avibe.enabled = True+ hub_connection.config.save()+ empty = asyncio.run(api.get_backend_connection("avibe"))+ assert empty["installed"] and empty["enabled"]+ assert empty["auth"] == "none" and not empty["ready"]++ _place_hub_source(hub_connection, "avibe", _hub_source())+ response = ui_server.app.test_client().get("/api/backend/avibe/connection")+ assert response.status_code == 200+ state = response.get_json()+ assert state["ready"] and state["entry_eligible"]+ assert state["supply_mode"] == "hub" and state["auth"] == "api_key"+ hub_connection.native_read.assert_not_called()+ hub_connection.config.agents.avibe.enabled = False+ hub_connection.config.save()+ assert not asyncio.run(api.get_backend_connection("avibe"))["ready"]++@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])@pytest.mark.parametrize("kind", ["api_key", "subscription"])def test_hub_takeover_connection_uses_current_source_not_cleared_native_store(hub_connection, backend, kind):diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.pyindex 87d82d742..f80611e31 100644--- a/tests/test_backend_failure_retry.py+++ b/tests/test_backend_failure_retry.py@@ -9,6 +9,7 @@ import pytestfrom sqlalchemy import updatefrom core.session_turns import DeliveryRequest+from modules.agents.catalog import AGENT_BACKENDSfrom storage import message_deliveries, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.db import create_sqlite_engine@@ -231,7 +232,7 @@ def test_retry_notice_preserves_authorized_local_details(isolated_state, tmp_patassert ("local_error_detail" in json.loads(projected)["data"]["metadata"]) is can_manage[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_failure_retry_canonical_continue_and_draft(isolated_state, tmp_path, backend):from vibe.ui_server import appdiff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.pynew file mode 100644index 000000000..5599f7d4c--- /dev/null+++ b/tests/test_backend_registration_contract.py@@ -0,0 +1,184 @@+"""C-8/A7: a backend cannot silently fall out of an unclassified universe.++Runtime and schema assertions protect the public backend vocabulary. The source+inventory catches a new literal before it silently excludes an in-process backend;+behavioral tests alone cannot discover a newly added, unexercised selector.+Tests/fixtures are examples, not declarations. Released migrations are inventoried+explicitly, without changing their historical meaning.+"""++from __future__ import annotations++import ast+import json+import re+from collections import Counter+from pathlib import Path+from typing import get_args++from config.v2_config import MODEL_HUB_BACKENDS+from core.handlers.model_hub.events import EventAgent+from core.handlers.model_hub.resolver import BackendName+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, AgentBackend, NativeCliBackend+from modules.agents.native_sessions.types import AgentName+from scripts.generate_agent_backend_catalog import render+++ROOT = Path(__file__).resolve().parents[1]+AGENTS = frozenset(AGENT_BACKENDS)+NATIVE = frozenset(NATIVE_CLI_BACKENDS)++# (path, AST kind, backend members) -> (occurrences, relation, reason).+# Counts matter: copying even an already-classified literal creates an+# unclassified declaration. Member fingerprints survive identifier-only edits.+# Mappings remain literal when their per-backend values are the implementation.+PYTHON_DECLARATIONS = {+ ("config/v2_config.py", "Dict", AGENTS): (2, "agent", "Config serialization/recovery plus the avault tool."),+ ("config/v2_config.py", "Set", frozenset({"claude", "codex"})): (3, "native_subset", "Built-in model catalogs and legacy vendor credentials."),+ ("config/v2_config.py", "Tuple", frozenset({"claude", "codex"})): (3, "native_subset", "Released two-vendor model/credential migration."),+ ("config/v2_config.py", "Pairs", NATIVE): (1, "native", "Per-CLI auto-update config objects."),+ ("core/agent_auth_service.py", "Set", frozenset({"claude", "codex"})): (3, "native_subset", "Two vendor-specific login implementations."),+ ("core/agent_auth_service.py", "Tuple", frozenset({"claude", "codex"})): (1, "native_subset", "Login-output noise tokens, not a backend selector."),+ ("core/backend_restart.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Vendor-to-native-custody mapping."),+ ("core/handlers/command_handlers.py", "Dict", NATIVE): (1, "native", "Native resume command aliases."),+ ("core/handlers/message_handler.py", "Set", frozenset({"claude", "codex"})): (3, "native_subset", "Native subagent names and prompt injection."),+ ("core/handlers/model_hub/migration.py", "Dict", frozenset({"claude", "codex"})): (2, "native_subset", "Vendor credential and native environment maps."),+ ("core/handlers/model_hub/migration.py", "Dict", NATIVE): (1, "native", "Native migration vendor descriptors."),+ ("core/handlers/model_hub/migration.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "First-party subscription import."),+ ("core/handlers/model_hub/migration.py", "Tuple", frozenset({"claude", "codex"})): (2, "native_subset", "Subscription provider Literal types."),+ ("core/handlers/model_hub/migration_files.py", "Pairs", NATIVE): (1, "native", "Native credential document paths."),+ ("core/handlers/model_hub/migration_journal.py", "Set", frozenset({"claude", "codex"})): (2, "native_subset", "OAuth journal providers."),+ ("core/handlers/model_hub/migration_persisted.py", "Dict", NATIVE): (2, "native", "Native persisted credential snapshots."),+ ("core/handlers/model_hub/service.py", "Dict", frozenset({"claude", "codex"})): (2, "native_subset", "Native API-key environment and OAuth event reasons."),+ ("core/handlers/model_hub/service.py", "Tuple", frozenset({"claude", "codex"})): (3, "native_subset", "Backends with bundled model lists."),+ ("core/services/session_fork.py", "Set", frozenset({"codex", "opencode"})): (1, "native_subset", "Native forks that can trim a running turn."),+ ("core/services/skills.py", "Dict", NATIVE): (1, "native", "askill native CLI ids."),+ ("core/session_turns.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Runtimes whose running turns cannot restore."),+ ("core/vibe_agents.py", "Dict", NATIVE): (1, "native", "Native recommendations; Avibe uses its configured Hub catalog."),+ ("modules/im/telegram.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Native subagent routing controls."),+ ("scripts/incus_tenant.py", "Dict", AGENTS): (1, "agent", "Bootstrap config with backend-specific fields."),+ ("scripts/prepare_regression.py", "Dict", AGENTS): (1, "agent", "Regression config with backend-specific fields."),+ ("scripts/prepare_regression.py", "Dict", NATIVE): (1, "native", "Known legacy CLI executable paths."),+ ("vibe/api.py", "Dict", AGENTS): (1, "agent", "Public runtime config plus the avault tool."),+ ("vibe/api.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "OAuth relay configuration."),+ ("vibe/api.py", "Tuple", frozenset({"claude", "codex"})): (1, "native_subset", "Masked vendor credentials."),+ ("vibe/backend_model_catalog.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Bundled model catalog files."),+ ("vibe/backend_model_catalog.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Backends with bundled model catalogs."),+ ("vibe/cli.py", "Tuple", frozenset({"claude", "codex"})): (1, "native_subset", "Native-only model picker refresh."),+ ("vibe/desktop_backends.py", "Dict", NATIVE): (1, "native", "CLI package install specifications."),+ ("vibe/global_agents_md.py", "Dict", NATIVE): (1, "native", "Native global instruction filenames."),+ ("vibe/model_hub_runtime/adapter.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Native subscription vendors."),+ ("vibe/model_hub_runtime/state.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Vendor aliases, including provider names."),+ ("storage/alembic/versions/20260529_0007_backfill_scope_agent_names.py", "Set", NATIVE): (1, "native", "Immutable released migration predating Avibe."),+ ("storage/alembic/versions/20260530_0008_remove_legacy_default_agent.py", "Set", NATIVE): (1, "native", "Immutable released migration predating Avibe."),+}++TYPESCRIPT_DECLARATIONS = {+ ("ui/src/context/ApiContext.tsx", frozenset({"claude", "codex"})): (+ 4, "native_subset", "Account-level native auth endpoints; OpenCode uses provider auth.",+ ),+ ("ui/src/components/settings/BackendTestPanel.tsx", frozenset({"claude", "codex"})): (+ 1, "native_subset", "Account-level native auth testing.",+ ),+ ("ui/src/lib/effortOptions.ts", frozenset({"claude", "codex"})): (+ 1, "native_subset", "Backends with shared-default reasoning effort metadata.",+ ),+}+++def _python_declarations(path: Path):+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):+ if isinstance(node, ast.Dict):+ elements = node.keys+ elif isinstance(node, (ast.List, ast.Set, ast.Tuple)):+ elements = node.elts+ else:+ continue+ kind = type(node).__name__+ if elements and all(isinstance(item, ast.Tuple) and len(item.elts) == 2 for item in elements):+ elements = [item.elts[0] for item in elements]+ kind = "Pairs"+ values = frozenset(+ item.value for item in elements+ if isinstance(item, ast.Constant) and isinstance(item.value, str)+ )+ members = values & AGENTS+ if len(members) >= 2:+ yield (path.relative_to(ROOT).as_posix(), kind, members), node.lineno+++def _schema_enums(value, location=""):+ if isinstance(value, dict):+ for key, child in value.items():+ if key == "enum" and isinstance(child, list) and all(isinstance(item, str) for item in child):+ if len(AGENTS & set(child)) >= 2:+ yield location + "/enum", set(child)+ else:+ yield from _schema_enums(child, location + "/" + key)+ elif isinstance(value, list):+ for index, child in enumerate(value):+ yield from _schema_enums(child, location + "/" + str(index))+++def test_backend_universes_are_catalog_owned_and_literals_are_classified():+ assert set(get_args(AgentBackend)) == set(get_args(BackendName)) == set(MODEL_HUB_BACKENDS) == AGENTS+ assert set(get_args(NativeCliBackend)) == set(get_args(AgentName)) == NATIVE+ assert set(get_args(EventAgent)) == AGENTS | {"system"} # C-8 superset: runtime events also name the system.+ assert (ROOT / "ui/src/lib/agentBackendCatalog.generated.ts").read_text() == render()++ observed = Counter()+ locations = {}+ for directory in ("config", "core", "modules", "vibe", "storage", "scripts"):+ for path in (ROOT / directory).rglob("*.py"):+ if path == ROOT / "modules/agents/catalog.py":+ continue # The sole authoritative declaration.+ for key, line in _python_declarations(path):+ observed[key] += 1+ locations.setdefault(key, []).append(line)+ assert observed == Counter({key: rule[0] for key, rule in PYTHON_DECLARATIONS.items()}), (+ "Unclassified backend literals (import the catalog or document a capability relation): "+ f"{[(key, locations[key]) for key in observed if observed[key] != PYTHON_DECLARATIONS.get(key, (0,))[0]]}; "+ f"stale classifications: {set(PYTHON_DECLARATIONS) - set(observed)}"+ )+ for (_path, _kind, members), (_count, relation, reason) in PYTHON_DECLARATIONS.items():+ assert reason+ if relation == "agent":+ assert members == AGENTS+ elif relation == "native":+ assert members == NATIVE+ else:+ assert relation == "native_subset" and members < NATIVE++ for path in (ROOT / "docs/plans/model-hub-contracts").glob("*.json"):+ for location, members in _schema_enums(json.loads(path.read_text())):+ if path.name == "migration-scan.schema.json":+ expected = NATIVE # Native credential migration only.+ elif path.name == "resolution-event.schema.json" and location == "/properties/agent/enum":+ expected = AGENTS | {"system"}+ elif path.name == "agent-supply.schema.json" and location == "/allOf/8/if/properties/backend/enum":+ expected = AGENTS - {"opencode"} # Fixed menus do not expose OpenCode's provider menu.+ else:+ expected = AGENTS+ assert members == expected, (path.name, location, members)++ # TS needs its checked-in projection to infer literal types at build time.+ # Catch newly copied literal arrays/unions outside the generated declaration.+ literal_list = re.compile(r"\[\s*((?:['\"][\w-]+['\"]\s*,?\s*){2,})\]")+ literal_union = re.compile(r"['\"][\w-]+['\"](?:\s*\|\s*['\"][\w-]+['\"])+")+ observed_ts = Counter()+ locations_ts = {}+ for path in (ROOT / "ui/src").rglob("*"):+ if path.suffix not in {".ts", ".tsx"} or ".test." in path.name or path.name.endswith(".generated.ts"):+ continue+ source = re.sub(r"/\*.*?\*/|//[^\n]*", "", path.read_text(), flags=re.S)+ for match in [*literal_list.finditer(source), *literal_union.finditer(source)]:+ members = frozenset(re.findall(r"['\"]([\w-]+)['\"]", match.group())) & AGENTS+ if len(members) >= 2:+ key = (str(path.relative_to(ROOT)), members)+ observed_ts[key] += 1+ locations_ts.setdefault(key, []).append(match.group())+ assert observed_ts == Counter({key: rule[0] for key, rule in TYPESCRIPT_DECLARATIONS.items()}), (+ f"Import catalog-derived Agent/native types or classify capability subsets: {locations_ts}"+ )+ for (_path, members), (_count, relation, reason) in TYPESCRIPT_DECLARATIONS.items():+ assert reason and relation == "native_subset" and members < NATIVEdiff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.pyindex c38f40dd4..6c36f8402 100644--- a/tests/test_backend_restart.py+++ b/tests/test_backend_restart.py@@ -8,6 +8,7 @@ import pytestfrom core.backend_restart import BackendRestartCoordinator, NativeCredentialLease, NativeMigrationBlockedErrorfrom core.controller import Controller+from modules.agents.catalog import AGENT_BACKENDSclass _AgentService:@@ -238,6 +239,26 @@ def test_application_projection_tracks_prepare_drain_failure_retry_and_registratasyncio.run(run())[email protected]("backend", [backend for backend in AGENT_BACKENDS if backend != "claude"])+def test_application_projection_accepts_disabled_optional_compat_backends(backend):+ """No registered runtime is expected only after its compat section is disabled."""+ from config.v2_compat import to_app_config+ from config.v2_config import V2Config++ config = V2Config.default()+ getattr(config.agents, backend).enabled = False+ controller = SimpleNamespace(+ config=to_app_config(config, resolve_agent_paths=False),+ agent_service=SimpleNamespace(agents={}),+ )+ coordinator = BackendRestartCoordinator(controller, AsyncMock())+ assert coordinator.snapshot(backend) == {"state": "applied", "disabled": True}++ getattr(config.agents, backend).enabled = True+ controller.config = to_app_config(config, resolve_agent_paths=False)+ assert coordinator.snapshot(backend) == {"state": "unavailable"}++@pytest.mark.parametrize("failure", [RuntimeError("prepare failed"), asyncio.CancelledError()])def test_application_projection_retains_prepare_failure_and_cancellation(failure):async def run():diff --git a/tests/test_im_backend_registration.py b/tests/test_im_backend_registration.pynew file mode 100644index 000000000..a76c119e1--- /dev/null+++ b/tests/test_im_backend_registration.py@@ -0,0 +1,76 @@+"""C-8 IM payload boundary: Agent selection includes Avibe, native resume does not.++The existing per-platform picker tests use only native backends and cannot catch+accidentally sharing a whole-universe list with a native-session selector.+"""++import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from config.v2_config import DiscordConfig, LarkConfig, SlackConfig+from modules.im.discord import DiscordBot+from modules.im.feishu import FeishuBot+from modules.im.slack import SlackBot+++def _options(payload):+ if isinstance(payload, dict):+ for key, value in payload.items():+ if key == "options":+ yield from value+ else:+ yield from _options(value)+ elif isinstance(payload, list):+ for value in payload:+ yield from _options(value)++[email protected]("platform", ["slack", "discord", "feishu"])+async def test_agent_picker_includes_avibe_but_native_resume_excludes_it(platform):+ routing = dict(+ channel_id="fixture-channel", registered_backends=["codex", "avibe"],+ current_backend="avibe", current_routing=None,+ opencode_agents=[], opencode_models={}, opencode_default_config={},+ claude_agents=[], claude_models=[], codex_agents=[], codex_models=[],+ )+ if platform == "slack":+ bot = SlackBot(SlackConfig(bot_token="fixture-token"))+ bot._ensure_clients = Mock()+ bot.web_client = SimpleNamespace(views_open=AsyncMock())+ options = list(_options(bot._build_routing_modal_view(**routing)))+ elif platform == "discord":+ bot = DiscordBot(DiscordConfig(bot_token="fixture-token"))+ channel = SimpleNamespace(send=AsyncMock())+ bot._fetch_channel = AsyncMock(return_value=channel)+ await bot.open_routing_modal(trigger_id=None, **routing)+ view = channel.send.await_args.kwargs["view"]+ options = [+ {"value": option.value, "text": option.label}+ for child in view.children for option in getattr(child, "options", [])+ ]+ else:+ bot = FeishuBot(LarkConfig(app_id="fixture-app", app_secret="fixture-secret"))+ bot._send_card_to_channel = AsyncMock()+ await bot.open_routing_modal(trigger_id=None, **routing)+ options = list(_options(bot._send_card_to_channel.await_args.args[1]))+ avibe = next(option for option in options if option["value"] == "avibe")+ assert "Avibe Agent" in json.dumps(avibe)++ bot._controller = SimpleNamespace(agent_service=SimpleNamespace(agents={"codex": object(), "avibe": object()}))+ await bot.open_resume_session_modal(+ trigger_id=None, sessions=[], channel_id="fixture-channel", thread_id=None, host_message_ts=None,+ )+ if platform == "slack":+ metadata = json.loads(bot.web_client.views_open.await_args.kwargs["view"]["private_metadata"])+ values = [option["value"] for option in metadata["agent_options"]]+ elif platform == "discord":+ view = channel.send.await_args.kwargs["view"]+ values = [option.value for child in view.children for option in getattr(child, "options", [])]+ else:+ values = [option["value"] for option in _options(bot._send_card_to_channel.await_args.args[1])]+ assert "codex" in values+ assert "avibe" not in valuesdiff --git a/tests/test_managed_skills.py b/tests/test_managed_skills.pyindex 07cd4ce51..bfb5d0cab 100644--- a/tests/test_managed_skills.py+++ b/tests/test_managed_skills.py@@ -679,6 +679,8 @@ def test_system_prompt_catalog_is_backend_neutral_for_remote_sessions(tmp_path: Path,monkeypatch,) -> None:+ from modules.agents.catalog import AGENT_BACKENDS+cwd = tmp_path / "project"cwd.mkdir()home = tmp_path / "home"@@ -702,11 +704,12 @@ def test_system_prompt_catalog_is_backend_neutral_for_remote_sessions()prompts = {backend: build_system_prompt_injection(+ backend=backend,context=context,fallback_platform="avibe",skills_cwd=cwd,)- for backend in ("claude", "codex", "opencode")+ for backend in AGENT_BACKENDS}assert all("- shared: Shared" in prompt for prompt in prompts.values())diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 1b7f3c529..6cb289693 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -703,6 +703,27 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):{"id": "agent-default", "name": "default", "backend": "codex"},)+ async def test_avibe_message_prefix_never_reads_native_codex_subagents(self):+ """C-8: the native prefix dispatcher must not treat a new backend as Codex."""+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ agent = controller.resolve_vibe_agent_for_context(None)+ agent.backend = "avibe"+ agent.model = "team-model"+ controller.resolve_agent_for_context = lambda _context: "avibe"+ controller.resolve_vibe_agent_for_context = lambda *_args, **_kwargs: agent+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(user_id="U1", channel_id="C1", message_id="avibe-prefix", platform="slack")++ with patch("modules.agents.subagent_router.load_codex_subagent") as load_native:+ await handler.handle_user_message(context, "reviewer: inspect the change")+ load_native.assert_not_called()+ backend, request = controller.agent_service.requests[0]+ self.assertEqual(backend, "avibe")+ self.assertEqual(request.vibe_agent_model, "team-model")+ self.assertEqual(request.message, "reviewer: inspect the change")+ self.assertIsNone(request.subagent_name)+async def test_scope_model_and_reasoning_override_vibe_agent_defaults(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)controller.settings_manager.routing = type(diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 4a04a59fa..449cf8b09 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -17,6 +17,7 @@ from urllib.parse import quoteimport pytestfrom jsonschema import Draft7Validator, FormatCheckerfrom referencing import Registry, Resource+from modules.agents.catalog import AGENT_BACKENDSfrom config.v2_config import (ModelHubAgentSupplyConfig,@@ -4083,7 +4084,7 @@ def test_backend_catalog_preserves_requested_insertion_position_for_a_new_model(][email protected]("backend", ("claude", "codex", "opencode"))[email protected]("backend", AGENT_BACKENDS)def test_backend_catalog_allows_editing_a_persisted_legacy_long_id(tmp_path, backend):service, store, _adapter = _service(tmp_path)legacy_id = "legacy-" + "模型🧪/e\u0301" * 3000@@ -4132,7 +4133,7 @@ def test_backend_catalog_allows_a_persisted_legacy_claude_alias_to_round_trip(assert response["agent"]["catalog_models"][1]["display_name"] == "Unrelated edit"[email protected]("backend", ("claude", "codex", "opencode"))[email protected]("backend", AGENT_BACKENDS)def test_backend_catalog_rejects_a_new_unencodable_id(tmp_path, backend):service, _store, _adapter = _service(tmp_path)baseline = service.backend_catalog_models(backend)@@ -4148,7 +4149,7 @@ def test_backend_catalog_rejects_a_new_unencodable_id(tmp_path, backend):assert raised.value.code == "backend_model_id_invalid"[email protected]("backend", ("claude", "codex", "opencode"))[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("identifier", ["x" * 257, "模型🧪/e\u0301" * 3000, "x" * 17000],ids=("past-former-bound", "long-unicode", "past-lexical-budget"),diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 5ee90877b..8c0c2c967 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -13,6 +13,7 @@ import pytestfrom jsonschema import Draft7Validator, FormatChecker, ValidationErrorimport config.v2_config as v2_config+from modules.agents.catalog import AGENT_BACKENDSfrom config.v2_config import (MODEL_HUB_ENABLED_ENV,MODEL_HUB_LEGACY_CREATED_AT,@@ -1407,7 +1408,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm"sources": [source_example],"agents": {backend: ModelHubAgentSupplyConfig.default(backend, mode="hub").to_payload()- for backend in ("claude", "codex", "opencode")+ for backend in AGENT_BACKENDS},}config = default_config()@@ -3129,7 +3130,7 @@ def test_config_reload_preserves_legacy_routes_without_seeding_missing_models(tmassert next(model for model in migrated_models if model.id == stale_id).origin == "manual"[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_v2_empty_route_normalizes_on_load_without_writing_until_save(tmp_path, backend):from tests.test_model_hub_routing_modes import MODEL, _loaded_catalog_configfrom tests.test_model_hub_resolution import _source@@ -3151,7 +3152,7 @@ def test_v2_empty_route_normalizes_on_load_without_writing_until_save(tmp_path,assert json.loads(path.read_text())["model_hub"] == expected[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("bad_key", ["", "authorization=sk-unsafe-fixture"])def test_invalid_empty_route_key_keeps_v2_recovery_fence(tmp_path, backend, bad_key):payload = api.config_to_payload(default_config())diff --git a/tests/test_model_hub_failure_presentation.py b/tests/test_model_hub_failure_presentation.pyindex da9a834f5..1d272a953 100644--- a/tests/test_model_hub_failure_presentation.py+++ b/tests/test_model_hub_failure_presentation.py@@ -7,7 +7,12 @@ from unittest.mock import AsyncMock, Mockimport aiohttpimport pytest-from config.v2_config import ModelHubBackendModelConfig, ModelHubSourceStateConfig+from config.v2_config import (+ ModelHubBackendModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,+ ModelHubSourceStateConfig,+)from core.backend_failure import emit_backend_failure, emit_replayed_backend_failurefrom core.controller import Controllerfrom core.handlers.model_hub.adapter import RawOutcomeKind@@ -16,6 +21,7 @@ from core.handlers.model_hub.provenance import (render_turn_outcome_copy,)from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from modules.agents.catalog import AGENT_BACKENDSfrom modules.agents.model_hub import ModelHubRuntimeRouter, bind_launchfrom modules.im import MessageContextfrom tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _outcome@@ -34,6 +40,9 @@ def unavailable(tmp_path, backend="codex"):)config = _config([source], model="模型/alpha")config.agents[backend].models.append(ModelHubBackendModelConfig(id="模型/alpha", origin="manual"))+ config.agents[backend].routes["模型/alpha"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "模型/alpha"),),+ )service, _, _ = _service(tmp_path, config)config, resolution = service._inspect_terminal_chain(backend=backend, model_id="模型/alpha")return service._produce_exhausted_terminal_outcome(@@ -41,7 +50,7 @@ def unavailable(tmp_path, backend="codex"):)[email protected]("backend", ["codex", "claude", "opencode"])[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("platform", ["avibe", "slack"])@pytest.mark.parametrize("language", ["en", "zh"])async def test_shared_failure_uses_exact_hub_copy_and_preserves_terminal_evidence(diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 0e00414b7..5c9679cb7 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -15,6 +15,7 @@ from core.handlers.model_hub.service import (PRE_ATTEMPT_SETTLEMENT_GENERATION,ModelHubError,)+from modules.agents.catalog import AGENT_BACKENDSfrom modules.agents.model_hub import (ModelHubLaunch,build_claude_hub_env,@@ -264,7 +265,7 @@ def test_hub_connection_settings_preserve_explicit_limits_without_promoting_cataassert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == launch.gateway_token[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("has_metadata", [False, True])def test_route_alias_keeps_its_own_planning_metadata(tmp_path, monkeypatch, backend, has_metadata):from unittest.mock import AsyncMockdiff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 1696cd09b..f61f5a5bb 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -440,6 +440,8 @@ def test_runtime_opencode_resolution_preserves_absent_selection():def test_hub_subscription_is_cross_backend_eligible_and_origin_unrestricted():+ from modules.agents.catalog import AGENT_BACKENDS+source = _source("src_hubsub002",("shared-model",),@@ -453,7 +455,7 @@ def test_hub_subscription_is_cross_backend_eligible_and_origin_unrestricted():)config.agents["codex"].sources.order = [source.id]- assert all(ModelHubConfig.source_eligible_for_backend(source, backend) for backend in ("claude", "codex", "opencode"))+ assert all(ModelHubConfig.source_eligible_for_backend(source, backend) for backend in AGENT_BACKENDS)assert allowed_origins(source) == ("claude", "codex", "opencode", "avibe")resolution = resolve_model_hub_turn(config, "codex", "shared-model")assert resolution.source is sourcediff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.pyindex 853f37f81..ae666c2fa 100644--- a/tests/test_prompt_render_export.py+++ b/tests/test_prompt_render_export.py@@ -17,6 +17,7 @@ from core.managed_skills import ManagedSkillfrom core.prompt_registry import PROMPT_MODULES, prompt_textfrom core.prompt_studio_catalog import export_prompt_studio_catalog, render_prompt_contextfrom core.system_prompt_injection import build_system_prompt_injection+from modules.agents.catalog import AGENT_BACKENDSfrom modules.agents.codex.agent import CodexAgentfrom modules.im import MessageContextfrom vibe import cli@@ -97,7 +98,7 @@ def _environment(monkeypatch, history="managed", skill_mode="pages"):@pytest.mark.parametrize("backend,history,skill_mode", itertools.product(- ("claude", "codex", "opencode"), ("off", "managed", "self-managed"), ("empty", "manual", "single", "pages"),+ AGENT_BACKENDS, ("off", "managed", "self-managed"), ("empty", "manual", "single", "pages"),))def test_export_reconstructs_production_text_with_source_for_every_block(monkeypatch, backend, history, skill_mode):_environment(monkeypatch, history, skill_mode)@@ -151,7 +152,7 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeypassert "reuse an earlier successful load that remains in context" not in production[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("custom", ["", "中文 {verbatim}\n\nKeep my spacing.\n"])def test_custom_instructions_only_change_the_final_content_block(monkeypatch, backend, custom):_environment(monkeypatch)@@ -177,7 +178,7 @@ def test_custom_instructions_only_change_the_final_content_block(monkeypatch, ba][email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_evidence_led_principle_is_shared_by_production_export_and_studio(monkeypatch, backend):_environment(monkeypatch)request = _inputs(backend)@@ -207,7 +208,7 @@ def test_runtime_snapshot_has_only_tags_and_verbatim_content():)[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("skill_mode", ["empty", "manual", "single", "pages"])def test_skill_reuse_clarification_is_codex_only(monkeypatch, backend, skill_mode):_environment(monkeypatch, skill_mode=skill_mode)@@ -220,7 +221,7 @@ def test_skill_reuse_clarification_is_codex_only(monkeypatch, backend, skill_mod@pytest.mark.parametrize("backend,history,skill_mode", itertools.product(- ("claude", "codex", "opencode"), ("off", "managed", "self-managed"),+ AGENT_BACKENDS, ("off", "managed", "self-managed"),("empty", "manual", "single", "pages"),))def test_separated_capabilities_keep_independent_markdown_sections(monkeypatch, backend, history, skill_mode):@@ -256,7 +257,7 @@ def test_separated_capabilities_keep_independent_markdown_sections(monkeypatch,assert ("Codex-generated images" in sections) == (backend == "codex")[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_working_principles_remain_without_session_skills_or_optional_capabilities(backend):request = {"backend": backend,@@ -284,7 +285,7 @@ def test_working_principles_remain_without_session_skills_or_optional_capabilitidef test_exported_sources_cover_all_rendered_branches(monkeypatch):visited = set()for backend, history, skill_mode in itertools.product(- ("claude", "codex", "opencode"), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),+ AGENT_BACKENDS, ("off", "managed", "self-managed"), ("empty", "manual", "pages"),):_environment(monkeypatch, history, skill_mode)result = render_prompt_context(_inputs(backend, history, skill_mode))@@ -307,7 +308,7 @@ def test_pagination_keeps_its_own_source_provenance(monkeypatch):assert "| Agent Name | Backend | Agent Description |" in prompt_text("harness-agents-prompt")[email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_history_state_is_not_a_prompt_dependency(monkeypatch, backend):_environment(monkeypatch)request = _inputs(backend)diff --git a/tests/test_runtime_ownership.py b/tests/test_runtime_ownership.pyindex 9474c2058..5a51360f7 100644--- a/tests/test_runtime_ownership.py+++ b/tests/test_runtime_ownership.py@@ -297,10 +297,11 @@ async def test_hfr_146_shared_codex_target_and_claude_mapping_use_exact_bindingsdef test_hfr_145_every_backend_invalidation_path_consumes_exact_ownership() -> None:- """HFR-145: Claude, Codex, and OpenCode invalidation probes fail closed."""+ """HFR-145: shared Agent invalidation probes fail closed."""+ from modules.agents.catalog import AGENT_BACKENDSblocking = SimpleNamespace(blocks_reclamation=True)- for backend in ("claude", "codex", "opencode"):+ for backend in AGENT_BACKENDS:probe = Mock(return_value=(blocking,))service = AgentService(SimpleNamespace())service.register(diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 17e750d91..6619a8ac8 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -19,6 +19,7 @@ from unittest.mock import AsyncMock, Mockimport pytestfrom sqlalchemy import select, update+from modules.agents.catalog import AGENT_BACKENDSsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -7431,7 +7432,7 @@ def test_silent_terminal_skips_callback_and_keeps_directed_run(][email protected]("backend", ["claude", "codex", "opencode"])[email protected]("backend", AGENT_BACKENDS)def test_callback_consumes_only_full_terminal_once_across_backends(tmp_path: Path,monkeypatch,diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex d0bf48fcc..c5f83202d 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -8,6 +8,7 @@ from unittest.mock import patchfrom config.v2_settings import RoutingSettingsfrom core.handlers.settings_handler import SettingsHandlerfrom core.modals import RoutingModalSelection+from modules.agents.catalog import AGENT_BACKENDSfrom modules.im import MessageContext@@ -496,9 +497,7 @@ def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:config=SimpleNamespace(platform="slack",language="en",- opencode=SimpleNamespace(enabled=True),- claude=SimpleNamespace(enabled=True),- codex=SimpleNamespace(enabled=True),+ **{backend: SimpleNamespace(enabled=True) for backend in AGENT_BACKENDS},),im_client=SimpleNamespace(send_message=AsyncMock()),settings_manager=_RoutingSettingsManager(),@@ -509,8 +508,7 @@ def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:agent_service=SimpleNamespace(agents={"opencode": _FakeOpenCodeAgent(server),- "claude": object(),- "codex": object(),+ **{backend: object() for backend in AGENT_BACKENDS if backend != "opencode"},}),)@@ -529,7 +527,8 @@ def test_gather_routing_modal_data_only_fetches_current_backend() -> None:data = asyncio.run(handler._gather_routing_modal_data(context))assert data.current_backend == "opencode"- assert data.registered_backends == ["opencode", "claude", "codex"]+ assert set(data.registered_backends) == set(AGENT_BACKENDS)+ assert data.registered_backends[0] == "opencode"assert server.calls == ["ensure_running","agents:/tmp/workspace",@@ -598,7 +597,8 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N):data = asyncio.run(handler._gather_routing_modal_data(context, include_all_backend_data=True))- assert data.registered_backends == ["opencode", "claude", "codex"]+ assert set(data.registered_backends) == set(AGENT_BACKENDS)+ assert data.registered_backends[0] == "opencode"assert data.opencode_agents == [{"name": "build"}]assert data.claude_agents == [{"id": "reviewer"}]assert data.claude_models == ["claude-sonnet-4-6"]@@ -624,7 +624,7 @@ def test_gather_routing_modal_data_hides_disabled_backends() -> None:data = asyncio.run(handler._gather_routing_modal_data(context))- assert data.registered_backends == ["opencode"]+ assert data.registered_backends == ["opencode", "avibe"]assert server.calls == ["ensure_running","agents:/tmp/workspace",@@ -647,7 +647,7 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_isdata = asyncio.run(handler._gather_routing_modal_data(context))assert data.current_backend == "opencode"- assert data.registered_backends == ["opencode", "codex"]+ assert data.registered_backends == ["opencode", "avibe", "codex"]assert data.opencode_agents == [{"name": "build"}]assert server.calls == ["ensure_running",diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex b34e0de37..12f35584e 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -20,6 +20,7 @@ from core.processing_indicator import ()from core.message_context import resolve_context_thread_idfrom modules.agents.native_sessions import NativeResumeSession+from modules.agents.catalog import AGENT_BACKENDSfrom modules.im import InlineButton, InlineKeyboard, MessageContextfrom modules.im.multi import MultiIMClientfrom modules.im.telegram import TelegramBot@@ -27,6 +28,9 @@ from modules.im import telegram_apifrom config.v2_config import TelegramConfig+ROUTING_BACKENDS = ["opencode", *(backend for backend in AGENT_BACKENDS if backend != "opencode")]++@pytest.fixture(autouse=True)def _reset_chat_discovery_cache():"""chat_discovery keeps a process-global debounce cache keyed on@@ -1333,7 +1337,7 @@ def test_routing_callback_save_persists_selected_backend() -> None:def test_routing_state_marks_current_backend_in_first_row() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))state = SimpleNamespace(- registered_backends=["opencode", "claude", "codex"],+ registered_backends=list(ROUTING_BACKENDS),backend="claude",opencode_agent=None,opencode_model=None,@@ -1431,7 +1435,7 @@ def test_routing_callback_backend_switches_without_nested_picker() -> None:channel_id=context.channel_id,user_id=context.user_id,is_dm=False,- registered_backends=["opencode", "claude", "codex"],+ registered_backends=list(ROUTING_BACKENDS),backend="opencode",opencode_agent=None,opencode_model=None,@@ -1454,11 +1458,12 @@ def test_routing_callback_backend_switches_without_nested_picker() -> None:edit_mock.assert_awaited_once()-def test_routing_state_keeps_backend_picker_entry_for_extra_backends() -> None:[email protected]("extra_backend", ["avibe", "extra"])+def test_routing_state_keeps_backend_picker_entry_for_extra_backends(extra_backend) -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))state = SimpleNamespace(- registered_backends=["opencode", "claude", "codex", "extra"],- backend="extra",+ registered_backends=[*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])],+ backend=extra_backend,opencode_agent=None,opencode_model=None,opencode_reasoning_effort=None,@@ -1471,7 +1476,9 @@ def test_routing_state_keeps_backend_picker_entry_for_extra_backends() -> None:picker_page=0,)- _, keyboard = bot._render_routing_state(state)+ text, keyboard = bot._render_routing_state(state)+ if extra_backend == "avibe":+ assert "Avibe Agent" in textassert [button.callback_data for button in keyboard.buttons[0]] == ["tg_route:backend:opencode",@@ -1481,7 +1488,8 @@ def test_routing_state_keeps_backend_picker_entry_for_extra_backends() -> None:assert keyboard.buttons[1][0].callback_data == "tg_route:field:backend"-def test_routing_callback_backend_picker_can_select_extra_backend() -> None:[email protected]("extra_backend", ["avibe", "extra"])+def test_routing_callback_backend_picker_can_select_extra_backend(extra_backend) -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))context = MessageContext(user_id="42",@@ -1495,7 +1503,7 @@ def test_routing_callback_backend_picker_can_select_extra_backend() -> None:channel_id=context.channel_id,user_id=context.user_id,is_dm=False,- registered_backends=["opencode", "claude", "codex", "extra"],+ registered_backends=[*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])],backend="opencode",opencode_agent=None,opencode_model=None,@@ -1511,10 +1519,13 @@ def test_routing_callback_backend_picker_can_select_extra_backend() -> None:with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:asyncio.run(bot._handle_routing_callback(context, "tg_route:field:backend"))- asyncio.run(bot._handle_routing_callback(context, "tg_route:option:3"))+ state = bot._routing_states[bot._interaction_scope_key(context)]+ asyncio.run(bot._handle_routing_callback(+ context, f"tg_route:option:{state.registered_backends.index(extra_backend)}",+ ))state = bot._routing_states[bot._interaction_scope_key(context)]- assert state.backend == "extra"+ assert state.backend == extra_backendassert state.picker_field is Noneassert edit_mock.await_count == 2diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 483792b76..834359f30 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -24,6 +24,7 @@ from config import pathsfrom config.v2_settings import ChannelSettings, SettingsStorefrom core.vibe_agents import VibeAgentStorefrom core import chat_discovery+from modules.agents.catalog import AGENT_BACKENDSfrom vibe import api, backend_model_catalog, cli_pathsfrom vibe.opencode_config import parse_jsonc_object@@ -4180,7 +4181,7 @@ def test_builtin_default_agent_uses_first_enabled_backend_when_no_default_existsmonkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))store = VibeAgentStore()try:- store.ensure_builtin_default_agents(["opencode", "claude", "codex"])+ store.ensure_builtin_default_agents(list(AGENT_BACKENDS))assert store.get_default_agent_name() == "opencode"finally:store.close()diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 1532adff6..445f939b4 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -2304,14 +2304,15 @@ def test_changed_agent_backend_runtimes_keeps_saved_selector_changes_visible(mon) == ["claude"]-def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path):[email protected]("backend", ["codex", "avibe"])+def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path, backend):"""Scenario: AUTH-SETUP-902."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))from vibe import apifrom vibe import internal_clientpayload = _full_config_payload()- payload["agents"]["codex"]["enabled"] = False+ payload["agents"].setdefault(backend, {})["enabled"] = Falseapi.save_config(payload)reconcile_calls = []@@ -2323,7 +2324,7 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tm"body": {"ok": True,"backends": backends,- "states": {"codex": "restarted"},+ "states": {backend: "restarted"},},}@@ -2334,9 +2335,9 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tm"/api/config",json={"agents": {- "codex": {+ backend: {"enabled": True,- "cli_path": "/opt/codex",+ **({"cli_path": "/opt/codex"} if backend == "codex" else {}),}}},@@ -2345,18 +2346,20 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmassert response.status_code == 200data = response.get_json()- assert data["agents"]["codex"]["enabled"] is True+ assert data["agents"][backend]["enabled"] is True+ if backend == "avibe":+ assert data["agents"][backend] == {"enabled": True}assert data["agent_backend_runtime"] == {"ok": True,"hot_reconciled": True,- "backends": ["codex"],+ "backends": [backend],"body": {"ok": True,- "backends": ["codex"],- "states": {"codex": "restarted"},+ "backends": [backend],+ "states": {backend: "restarted"},},}- assert reconcile_calls == [["codex"]]+ assert reconcile_calls == [[backend]]def test_config_post_defers_backend_reconcile_until_next_start_when_service_is_stopped(diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.pyindex 970744d49..6d932f1fa 100644--- a/tests/test_v2_compat_platforms.py+++ b/tests/test_v2_compat_platforms.py@@ -131,6 +131,28 @@ def test_to_app_config_uses_shared_agent_defaults() -> None:assert DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS == 0+def test_to_app_config_avibe_presence_tracks_enablement() -> None:+ """Rolling refresh uses None, not enabled=False, to unregister a backend."""+ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ update=UpdateConfig(),+ )++ for enabled in (False, True, False):+ config.agents.avibe.enabled = enabled+ compat = to_app_config(config, resolve_agent_paths=False)+ if enabled:+ assert compat.avibe is not None+ assert compat.avibe.enabled is True+ else:+ assert compat.avibe is None++def test_config_load_neutralizes_legacy_opencode_turn_timeout_default(monkeypatch, tmp_path) -> None:diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.pyindex 5b196f1f6..28f40a9c2 100644--- a/tests/test_v2_config_platform_registry.py+++ b/tests/test_v2_config_platform_registry.py@@ -23,6 +23,7 @@ from config.v2_config import (VibeCloudRemoteAccessConfig,WeChatConfig,)+from modules.agents.catalog import AGENT_BACKENDSfrom vibe import api@@ -208,11 +209,7 @@ def test_config_payload_includes_platform_catalog_and_setup_state() -> None:"wechat","avibe",]- assert [backend["id"] for backend in payload["agent_backend_catalog"]] == [- "opencode",- "claude",- "codex",- ]+ assert [backend["id"] for backend in payload["agent_backend_catalog"]] == list(AGENT_BACKENDS)assert payload["setup_state"]["configured_platforms"] == ["slack", "discord", "telegram", "lark", "wechat"]assert payload["setup_state"]["needs_setup"] is Falseassert payload["ui"]["chat_message_font_size"] == 14diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 151dbe9f9..0874c5796 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -28,6 +28,7 @@ import { SettingsBackendsPage } from './components/settings/SettingsBackendsPageimport { SettingsDependenciesPage } from './components/settings/SettingsDependenciesPage';import { SettingsClaudeProviderPage } from './components/settings/SettingsClaudeProviderPage';import { SettingsCodexProviderPage } from './components/settings/SettingsCodexProviderPage';+import { SettingsBackendPage } from './components/settings/SettingsBackendPage';import { SettingsOpencodeProviderPage } from './components/settings/SettingsOpencodeProviderPage';import { SettingsLogsPage } from './components/settings/SettingsLogsPage';import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';@@ -718,6 +719,7 @@ const settingsRoute = () => (<Route path="backends/opencode" element={<SettingsOpencodeProviderPage />} /><Route path="backends/claude" element={<SettingsClaudeProviderPage />} /><Route path="backends/codex" element={<SettingsCodexProviderPage />} />+ <Route path="backends/avibe" element={<SettingsBackendPage backend="avibe" />} /><Routepath="models"element={diff --git a/ui/src/components/onboarding/BackendConnectionDialog.tsx b/ui/src/components/onboarding/BackendConnectionDialog.tsxindex b2c3732c2..6dbde0651 100644--- a/ui/src/components/onboarding/BackendConnectionDialog.tsx+++ b/ui/src/components/onboarding/BackendConnectionDialog.tsx@@ -30,7 +30,7 @@ import { VendorGlyph } from '../settings/models/vendorGlyph';import { CUSTOM_VENDOR } from '../settings/models/apiKeyVendors';import { providerBrandLabel, providerLabel, providerVendorId, setupPrimaryRank, SETUP_PRIMARY_VENDORS } from '../settings/providers/providerIdentity';import { BackendConnectionForm } from '../settings/providers/BackendConnectionForm';-import type { BackendId } from '../settings/shared/useBackendRuntime';+import type { NativeCliBackend as BackendId } from '@/lib/agentBackends';/** One provider choice: its brand mark, the name a person recognises, and the id* OpenCode files it under — shown because that id is what the rest of OpenCode,diff --git a/ui/src/components/onboarding/CollaborationStory.tsx b/ui/src/components/onboarding/CollaborationStory.tsxindex d53c794dc..45bd6ef35 100644--- a/ui/src/components/onboarding/CollaborationStory.tsx+++ b/ui/src/components/onboarding/CollaborationStory.tsx@@ -1,6 +1,7 @@import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';import { Check, CodeXml, FileText, ListChecks } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { getBackendUiMeta } from '@/lib/agentBackends';import { BackendIcon } from '../visual';import { Card } from '../ui/card';import { ASSISTANT_ORDER, WORK_LINES, collaborationFrame } from './collaborationTimeline';@@ -226,13 +227,13 @@ export function CollaborationStory({ active = true }: { active?: boolean }) {const Icon = ICONS[index];return (<Card key={backend} className="onboarding-collaboration-card" data-active={active}- data-state={state} aria-label={t(`onboarding.story.${backend}.name`)}>+ data-state={state} aria-label={getBackendUiMeta(backend).label}>{/* The same identity header the connection step wears, in the sameplace: logo, name, and the trailing slot this step fills with theassistant's role and the next one with its enable switch. */}<div className="onboarding-card-identity"><span className="onboarding-card-logo"><BackendIcon backend={backend} size={28} variant="brand" aria-hidden="true" /></span>- <strong className="onboarding-card-name">{t(`onboarding.story.${backend}.name`)}</strong>+ <strong className="onboarding-card-name">{getBackendUiMeta(backend).label}</strong><span className="onboarding-card-role">{t(`onboarding.story.${backend}.role`)}</span></div><div className="onboarding-story-status" aria-hidden="true">diff --git a/ui/src/components/onboarding/collaborationTimeline.ts b/ui/src/components/onboarding/collaborationTimeline.tsindex 9e05446fd..5459a70a6 100644--- a/ui/src/components/onboarding/collaborationTimeline.ts+++ b/ui/src/components/onboarding/collaborationTimeline.ts@@ -1,5 +1,7 @@-export const ASSISTANT_ORDER = ['claude', 'codex', 'opencode'] as const;-export type AssistantId = typeof ASSISTANT_ORDER[number];+import { NATIVE_SETUP_BACKENDS, type NativeCliBackend } from '@/lib/agentBackends';++export const ASSISTANT_ORDER = NATIVE_SETUP_BACKENDS;+export type AssistantId = NativeCliBackend;/*** The authored relay from the approved Welcome design: each assistant works fordiff --git a/ui/src/components/onboarding/providers/DestinationRow.tsx b/ui/src/components/onboarding/providers/DestinationRow.tsxindex 0dae53076..62a9a0844 100644--- a/ui/src/components/onboarding/providers/DestinationRow.tsx+++ b/ui/src/components/onboarding/providers/DestinationRow.tsx@@ -5,13 +5,12 @@// question screen 3 owns, and the handoff would have to animate it appearing. The// row says who the routing is for and nothing else.import type { FC } from 'react';-import { useTranslation } from 'react-i18next';+import { getBackendUiMeta } from '@/lib/agentBackends';import { ASSISTANT_ORDER } from '../collaborationTimeline';import { BackendIcon } from '../../visual';export const DestinationRow: FC = () => {- const { t } = useTranslation();return (<div className="setup-destinations">{ASSISTANT_ORDER.map((backend) => (@@ -19,7 +18,7 @@ export const DestinationRow: FC = () => {<span className="setup-destination-logo"><BackendIcon backend={backend} size={28} variant="brand" aria-hidden="true" /></span>- <span className="setup-destination-name">{t(`onboarding.story.${backend}.name`)}</span>+ <span className="setup-destination-name">{getBackendUiMeta(backend).label}</span></div>))}</div>diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsxindex a6bf2b8f2..d862312ce 100644--- a/ui/src/components/settings/BackendOAuthPanel.tsx+++ b/ui/src/components/settings/BackendOAuthPanel.tsx@@ -12,8 +12,9 @@ import { surfaceBackendNotices } from './shared/surfaceBackendNotices';import { HubOwnedAuthNotice } from './shared/HubOwnedAuthNotice';import { errorMessage } from '@/lib/errorMessage';import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';+import type { WebOAuthBackend } from '@/lib/agentBackends';-type Backend = 'claude' | 'codex' | 'opencode';+type Backend = WebOAuthBackend;export type BackendOAuthPanelProps = {backend: Backend;diff --git a/ui/src/components/settings/SettingsBackendPage.tsx b/ui/src/components/settings/SettingsBackendPage.tsxnew file mode 100644index 000000000..8137126d0--- /dev/null+++ b/ui/src/components/settings/SettingsBackendPage.tsx@@ -0,0 +1,47 @@+import { Link } from 'react-router-dom';+import { ArrowLeft } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { getBackendUiMeta, type AgentBackendId } from '@/lib/agentBackends';+import { SettingsPageShell } from './SettingsPageShell';+import { BackendRuntimeCard } from './shared/BackendRuntimeCard';+import { useBackendRuntime } from './shared/useBackendRuntime';+import { BackendSupplyModeCard } from './models/BackendSupplyModeCard';+import { useModelHubCapability } from './models/useModelHubCapability';++/** Shared settings body for backends whose runtime is owned by Avibe. */+export function SettingsBackendPage({ backend }: { backend: AgentBackendId }) {+ const { t } = useTranslation();+ const meta = getBackendUiMeta(backend);+ const runtime = useBackendRuntime({ backend });+ const modelHubEnabled = useModelHubCapability();++ return (+ <SettingsPageShell+ activeTab="backends"+ title={meta.label}+ subtitle={t(meta.descriptionKey)}+ breadcrumb={+ <Link to="/settings/backends" className="inline-flex items-center gap-1.5 hover:text-foreground">+ <ArrowLeft className="size-3" />+ {t('settings.backends.backToBackends')}+ </Link>+ }+ >+ {!runtime.loaded ? <p>{t('common.loading')}</p> : (+ <div className="flex flex-col gap-4">+ <BackendRuntimeCard+ backend={backend}+ label={meta.label}+ description={t(meta.descriptionKey)}+ Icon={meta.Icon}+ iconTileClassName={meta.tileCls}+ iconClassName={meta.iconCls}+ runtime={runtime}+ />+ {modelHubEnabled === true && <BackendSupplyModeCard backend={backend} />}+ </div>+ )}+ </SettingsPageShell>+ );+}diff --git a/ui/src/components/settings/SettingsBackendsPage.test.tsx b/ui/src/components/settings/SettingsBackendsPage.test.tsxnew file mode 100644index 000000000..210878b5a--- /dev/null+++ b/ui/src/components/settings/SettingsBackendsPage.test.tsx@@ -0,0 +1,90 @@+/* @vitest-environment jsdom */+import type { ReactNode } from 'react';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { I18nextProvider } from 'react-i18next';+import { MemoryRouter, Route, Routes } from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { SettingsBackendPage } from './SettingsBackendPage';+import { SettingsBackendsPage } from './SettingsBackendsPage';++const mocks = vi.hoisted(() => ({+ api: {+ getConfig: vi.fn(),+ detectCli: vi.fn(),+ mutateConfig: vi.fn(),+ getBackendRuntime: vi.fn(),+ installAgent: vi.fn(),+ restartBackend: vi.fn(),+ },+ showToast: vi.fn(),+}));++vi.mock('@/context/ApiContext', () => ({ useApi: () => mocks.api }));+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast: mocks.showToast }) }));+vi.mock('./SettingsPageShell', () => ({+ SettingsPageShell: ({ children, title }: { children: ReactNode; title: string }) => <main><h1>{title}</h1>{children}</main>,+}));+vi.mock('./models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));+vi.mock('./BackendLifecycleChip', () => ({+ BackendLifecycleChip: ({ name }: { name: string }) => <span data-testid={`lifecycle-${name}`} />,+}));++beforeEach(async () => {+ vi.clearAllMocks();+ await i18n.changeLanguage('en');+ mocks.api.getConfig.mockResolvedValue({ agents: {} });+ mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: true, path: binary }));+ mocks.api.mutateConfig.mockResolvedValue({ agents: { avibe: { enabled: true } } });+});++afterEach(cleanup);++describe('in-process backend settings', () => {+ // Native-only fixtures never reached the missing-CLI default or showed which+ // lifecycle the Avibe row inherited when added to the backend catalog.+ it('opens Avibe settings from the backend list and saves availability without native actions', async () => {+ render(+ <I18nextProvider i18n={i18n}>+ <MemoryRouter initialEntries={['/settings/backends']}>+ <Routes>+ <Route path="/settings/backends" element={<SettingsBackendsPage />} />+ <Route path="/settings/backends/avibe" element={<SettingsBackendPage backend="avibe" />} />+ </Routes>+ </MemoryRouter>+ </I18nextProvider>,+ );++ await screen.findByText('Avibe Agent');+ for (const name of ['Claude Code', 'Codex', 'OpenCode', 'Avibe Agent']) {+ expect(screen.getByText(name)).toBeTruthy();+ }+ const label = screen.getByText('Avibe Agent');+ const row = label.closest('.rounded-xl') as HTMLElement;+ expect(within(row).getByRole('switch').getAttribute('aria-checked')).toBe('false');+ expect(within(row).queryByTestId('lifecycle-avibe')).toBeNull();+ await waitFor(() => expect(mocks.api.detectCli).toHaveBeenCalledTimes(3));+ expect(mocks.api.detectCli.mock.calls.map(([binary]) => binary).sort()).toEqual(['claude', 'codex', 'opencode']);+ const configure = within(row).getByRole('link', { name: 'Configure' });+ expect(configure.getAttribute('href')).toBe('/settings/backends/avibe');+ fireEvent.click(configure);++ await screen.findByRole('heading', { level: 1, name: 'Avibe Agent' });+ await screen.findByRole('switch');+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.queryByRole('button', { name: /Detect|Install|Restart|Save|Sign in/i })).toBeNull();+ expect(screen.queryByTestId('lifecycle-avibe')).toBeNull();+ const toggle = screen.getByRole('switch');+ expect(toggle.getAttribute('aria-checked')).toBe('false');+ fireEvent.click(toggle);+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledWith([+ { kind: 'set', path: ['agents', 'avibe', 'enabled'], value: true },+ ]));+ expect(toggle.getAttribute('aria-checked')).toBe('true');+ expect(mocks.api.detectCli).toHaveBeenCalledTimes(3);+ expect(mocks.api.getBackendRuntime).not.toHaveBeenCalled();+ expect(mocks.api.installAgent).not.toHaveBeenCalled();+ expect(mocks.api.restartBackend).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsxindex 65517de04..7d9fe6441 100644--- a/ui/src/components/settings/SettingsBackendsPage.tsx+++ b/ui/src/components/settings/SettingsBackendsPage.tsx@@ -9,7 +9,7 @@ import { BackendLifecycleChip } from './BackendLifecycleChip';import { SettingsPageShell } from './SettingsPageShell';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';-import { AGENT_BACKENDS, DEFAULT_AGENT_STATE } from '@/lib/agentBackends';+import { AGENT_BACKENDS, DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';import { configChanges } from '@/lib/configMutations';import { errorMessage } from '@/lib/errorMessage';@@ -24,7 +24,7 @@ type CliStatus = 'unknown' | 'ok' | 'missing';type AgentState = {enabled: boolean;- cli_path: string;+ cli_path?: string;status: CliStatus;};@@ -79,7 +79,7 @@ export const SettingsBackendsPage: React.FC = () => {let cancelled = false;(async () => {const results = await Promise.all(- Object.entries(agents).map(async ([name, agent]) => {+ Object.entries(agents).filter(([name]) => getBackendUiMeta(name).capabilities.supports_cli).map(async ([name, agent]) => {try {const result = await api.detectCli(agent.cli_path || name);return [name, result] as const;@@ -126,7 +126,7 @@ export const SettingsBackendsPage: React.FC = () => {await persistBackendField(name, { enabled });};- const refreshDetectionFor = async (name: string, cli_path: string) => {+ const refreshDetectionFor = async (name: string, cli_path?: string) => {try {const result = await api.detectCli(cli_path || name);setAgents((prev) => ({@@ -164,14 +164,14 @@ export const SettingsBackendsPage: React.FC = () => {tileClassName={meta.tileCls}iconClassName={meta.iconCls}title={meta.label}- detail={t(`settings.backends.${meta.id}Description`)}+ detail={t(meta.descriptionKey)}actions={<>- <BackendLifecycleChip+ {meta.capabilities.supports_runtime_refresh && <BackendLifecycleChipname={meta.id}enabled={agent.enabled}cliStatus={agent.status}- cliPath={agent.cli_path}+ cliPath={agent.cli_path || ''}onChanged={async (info) => {const installedPath = info?.installedPath || null;if (installedPath) {@@ -182,7 +182,7 @@ export const SettingsBackendsPage: React.FC = () => {}await refreshDetectionFor(meta.id, installedPath || agent.cli_path);}}- />+ />}<ToggleSwitchenabled={agent.enabled}onClick={() => void handleToggle(meta.id, !agent.enabled)}diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 4586f5b5c..9e2d63d65 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -30,7 +30,7 @@ const localeInstance = (lng: 'en' | 'zh') => {void instance.use(initReactI18next).init({lng,fallbackLng: 'en',- resources: { en: { translation: en }, zh: { translation: zh } },+ resources: { en: { translation: structuredClone(en) }, zh: { translation: structuredClone(zh) } },interpolation: { escapeValue: false },});return instance;@@ -70,6 +70,32 @@ const openCodeAgent: AgentSupply = {afterEach(cleanup);+describe('backend brand ownership', () => {+ // Card headings previously came from a second i18n brand table. Existing+ // fixtures used identical translations, masking divergence from the catalog.+ it.each(['en', 'zh'] as const)('keeps every backend brand catalog-owned in %s', (language) => {+ const locale = localeInstance(language);+ const rows = [+ { backend: 'claude', label: 'Claude Code' },+ { backend: 'codex', label: 'Codex' },+ { backend: 'opencode', label: 'OpenCode' },+ { backend: 'avibe', label: 'Avibe Agent' },+ ] as const;+ for (const { backend } of rows) {+ locale.addResource(language, 'translation', `settings.models.backends.${backend}`, 'Obsolete localized brand');+ }+ render(<I18nextProvider i18n={locale}><AgentCard+ agents={rows.map(({ backend }) => ({ ...hubAgent, backend }))}+ sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()}+ connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()}+ onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()}+ /></I18nextProvider>);+ expect(screen.getAllByRole('heading', { level: 2 }).map((heading) => heading.textContent))+ .toEqual(rows.map(({ label }) => label));+ expect(screen.queryByText('Obsolete localized brand')).toBeNull();+ });+});+describe('AgentCard origin help ownership', () => {const agents: AgentSupply[] = ['claude', 'codex'].map((backend) => ({...hubAgent,diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 11851d6de..278d55b1c 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -15,6 +15,7 @@ import { gatewayRouteStatus } from './supply';import { agentHasLiveChainProjection, type FreshRuntimeProjection } from './runtimeLifecycle';import { currentChainLink, isTakeoverChain } from './takeover';import { ACCENT_ICON, ACCENT_TILE, backendVisual } from './vendorMeta';+import { getBackendUiMeta } from '@/lib/agentBackends';import type { AgentSupply, Source } from './types';const sourceName = (sources: Source[], id: string): string => sources.find((source) => source.id === id)?.display_name ?? id;@@ -261,7 +262,7 @@ const AgentModelCard: React.FC<{<div className="model-hub-agent-head-summary flex min-w-0 items-center justify-between gap-2"><div className="flex min-w-0 items-center gap-[9px]"><span className={cn('flex size-[30px] shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE[accent])}><Icon className={cn('size-[15px]', ACCENT_ICON[accent])} /></span>- <h2 className="truncate text-[14px] font-bold leading-[17px] text-foreground">{t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</h2>+ <h2 className="truncate text-[14px] font-bold leading-[17px] text-foreground">{getBackendUiMeta(agent.backend).label}</h2></div>{agent.mode === 'hub' && (<ResponsiveMenu@@ -292,7 +293,7 @@ const AgentModelCard: React.FC<{</span><Check className="model-hub-ink-mint mt-0.5 size-4 shrink-0" aria-hidden="true" /></button>- <button+ {getBackendUiMeta(agent.backend).capabilities.supports_cli && <buttontype="button"aria-pressed="false"disabled={pending}@@ -305,9 +306,9 @@ const AgentModelCard: React.FC<{<Power className="mt-0.5 size-4 shrink-0 text-muted" aria-hidden="true" /><span className="min-w-0"><span className="block text-[12px] font-bold text-foreground">{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.gateway.switchToDirect')}</span>- <span className="mt-0.5 block text-[10.5px] leading-[15px] text-muted">{t('settings.models.gateway.modeMenu.directDescription', { backend: t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) })}</span>+ <span className="mt-0.5 block text-[10.5px] leading-[15px] text-muted">{t('settings.models.gateway.modeMenu.directDescription', { backend: getBackendUiMeta(agent.backend).label })}</span></span>- </button>+ </button>}</div></ResponsiveMenu>)}diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxindex c4db5b767..a6aecdd96 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -20,6 +20,7 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { useLatestRef } from '@/lib/useLatestRef';import type { PendingWrite } from './asyncLifetime';import {@@ -757,7 +758,7 @@ export const BackendModelCatalogDialog: React.FC<{><DialogHeader className="model-hub-catalog-head shrink-0 justify-center border-b border-border"><DialogTitle className="model-hub-catalog-title">- {t('settings.models.gateway.catalog.title', { backend: t(`settings.models.backends.${backend}`) })}+ {t('settings.models.gateway.catalog.title', { backend: getBackendUiMeta(backend).label })}</DialogTitle><DialogDescription className="sr-only">{t('settings.models.gateway.catalog.description')}</DialogDescription></DialogHeader>diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsxindex c77273ad4..20015c247 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx@@ -21,6 +21,7 @@ import { SegmentedRadio } from '@/components/ui/segmented';import { isComposingKey } from '@/lib/imeComposition';import { NO_REASONING_EFFORT } from '@/lib/effortOptions';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { applyModelsDevMatch, backendModelId, blankBackendModel, draftWithId, retireModelsDevMatch } from './backendCatalog';import { Field } from './dialogFields';import { formatTokensCompact } from './format';@@ -398,7 +399,7 @@ export const BackendModelEditorDialog: React.FC<{// A suggestion is not a capability declaration: Off stays unchecked until// the operator adds it to this exact model, just like any custom effort.const efforts = [...new Set([NO_REASONING_EFFORT, ...effortSuggestions, ...draft.reasoning_efforts])];- const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend });+ const backendName = getBackendUiMeta(backend).label;const protocolLabel = t('settings.models.gateway.modelEditor.nativeProtocol.label') as string;const idHint = submitted && idError ? t(`settings.models.gateway.modelEditor.id.${idError}`) as string : null;diff --git a/ui/src/components/settings/models/BackendModelPickerDialog.tsx b/ui/src/components/settings/models/BackendModelPickerDialog.tsxindex a227b1042..0a7a7c606 100644--- a/ui/src/components/settings/models/BackendModelPickerDialog.tsx+++ b/ui/src/components/settings/models/BackendModelPickerDialog.tsx@@ -18,6 +18,7 @@ import { Checkbox } from '@/components/ui/checkbox';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { chosenCandidate, EMPTY_PICKER_GROUPS, pickerGroups } from './backendCatalog';import type { ChosenCandidate, PickerGroups } from './backendCatalog';import { modelsApi } from './modelsApi';@@ -173,7 +174,7 @@ export const BackendModelPickerDialog: React.FC<{><DialogHeader className="model-hub-catalog-head shrink-0 justify-center border-b border-border"><DialogTitle className="model-hub-catalog-title">- {t('settings.models.gateway.picker.title', { backend: t(`settings.models.backends.${backend}`) })}+ {t('settings.models.gateway.picker.title', { backend: getBackendUiMeta(backend).label })}</DialogTitle><DialogDescription className="sr-only">{t('settings.models.gateway.picker.description')}</DialogDescription></DialogHeader>@@ -224,7 +225,7 @@ export const BackendModelPickerDialog: React.FC<{</div>) : (<div className="model-hub-picker-list">- {group('builtin', t('settings.models.gateway.picker.groupBuiltin', { backend: t(`settings.models.backends.${backend}`) }) as string, shown.builtin)}+ {group('builtin', t('settings.models.gateway.picker.groupBuiltin', { backend: getBackendUiMeta(backend).label }) as string, shown.builtin)}{group('providers', t('settings.models.gateway.picker.groupProviders') as string, shown.providers)}{group('listed', t('settings.models.gateway.picker.groupListed') as string, shown.listed)}</div>diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex 180974211..8865c4efa 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx@@ -62,6 +62,23 @@ const renderCard = () =>);describe('BackendSupplyModeCard', () => {+ it('offers the Avibe gateway model link without native configuration scanning or direct mode', async () => {+ vi.mocked(modelsApi.listAgents).mockResolvedValue([{ backend: 'avibe', cli_present: false, mode: 'hub', menu_kind: 'fixed' }]);+ const setMode = vi.spyOn(modelsApi, 'setAgentMode');+ render(+ <MemoryRouter>+ <I18nextProvider i18n={i18n}><BackendSupplyModeCard backend="avibe" /></I18nextProvider>+ </MemoryRouter>,+ );+ const hub = await screen.findByRole('radio', { name: /Gateway mode/ });+ expect(hub.getAttribute('aria-checked')).toBe('true');+ expect(screen.getByRole('link', { name: 'Open Models page' }).getAttribute('href')).toBe('/settings/models');+ expect(screen.queryByRole('radio', { name: /Direct mode/ })).toBeNull();+ await userEvent.click(hub);+ expect(modelsApi.scanMigration).not.toHaveBeenCalled();+ expect(setMode).not.toHaveBeenCalled();+ });+it.each([['switching to the gateway', /Gateway mode/, true],['importing from the Direct strip', null, false],diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsxindex 87542d213..ea04e5fbe 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx@@ -12,6 +12,7 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { createAgentCollectionReadAuthority } from './collectionReadAuthority';import { useToast } from '@/context/ToastContext';import { modelsApi } from './modelsApi';@@ -79,6 +80,7 @@ const OptionCard: React.FC<{export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ backend }) => {const { t } = useTranslation();const { showToast } = useToast();+ const supportsDirect = getBackendUiMeta(backend).capabilities.supports_cli;const [agent, setAgent] = React.useState<AgentSupply | null>(null);const [detected, setDetected] = React.useState<MigrationItem[]>([]);@@ -105,13 +107,14 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac}, [agentReads, backend]);const scan = React.useCallback(async () => {+ if (!supportsDirect) return;try {const s = await modelsApi.scanMigration();if (aliveRef.current) setDetected(s.items.filter((i) => i.backend === backend));} catch {/* detect strip is best-effort */}- }, [backend]);+ }, [backend, supportsDirect]);React.useEffect(() => {void load();@@ -119,7 +122,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac}, [load, scan]);const setMode = async (mode: AgentMode, offerMigration = true) => {- if (!agent || agent.mode === mode || switching) return;+ if (!supportsDirect || !agent || agent.mode === mode || switching) return;setSwitching(mode);try {const next = mode === 'hub'@@ -202,7 +205,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac</Link>}description={t('settings.models.supplyMode.hub.description', {- backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),+ backend: getBackendUiMeta(backend).label,}) as string}>{/* The banner asks the supply question. `fixHint` is appended only@@ -220,13 +223,13 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac)}</OptionCard>- <OptionCard+ {supportsDirect && <OptionCardselected={mode === 'direct'}disabled={switching !== null}onSelect={() => void setMode('direct')}title={<span className="text-[15px] font-semibold text-foreground">{t('settings.models.supplyMode.direct.title')}</span>}description={t('settings.models.supplyMode.direct.description', {- backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }),+ backend: getBackendUiMeta(backend).label,}) as string}>{mode === 'direct' && detectItem && (@@ -251,11 +254,11 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac</Button></div>)}- </OptionCard>+ </OptionCard>}</CardContent>{/* Migration is optional: declining it still makes the requested switch. */}- <MigrationDialog+ {supportsDirect && <MigrationDialogopen={migrateOpen !== null}eligible={(item) => item.backend === backend}onDecline={migrateOpen === 'switch' ? () => void setMode('hub', false) : undefined}@@ -265,7 +268,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bacvoid load();void scan();}}- />+ />}</Card>);};diff --git a/ui/src/components/settings/models/GuardGapList.tsx b/ui/src/components/settings/models/GuardGapList.tsxindex c8b11e73d..3634037c5 100644--- a/ui/src/components/settings/models/GuardGapList.tsx+++ b/ui/src/components/settings/models/GuardGapList.tsx@@ -1,6 +1,7 @@import type { TranslationKey } from '@/i18n/types';import * as React from "react";import { useTranslation } from "react-i18next";+import { getBackendUiMeta } from "@/lib/agentBackends";import type { SupplyGap } from "./types";@@ -27,9 +28,7 @@ export const GuardGapList: React.FC<{ gaps: SupplyGap[]; labelKey?: TranslationK<span className="min-w-0 flex-1"><strong>{t("settings.models.guard.gap.subject", {- backend: t(`settings.models.backends.${gap.backend}`, {- defaultValue: gap.backend,- }),+ backend: getBackendUiMeta(gap.backend).label,menuModel: gap.model_id,})}</strong>diff --git a/ui/src/components/settings/models/GuardImpact.tsx b/ui/src/components/settings/models/GuardImpact.tsxindex fe069bf6d..1b86c168f 100644--- a/ui/src/components/settings/models/GuardImpact.tsx+++ b/ui/src/components/settings/models/GuardImpact.tsx@@ -1,6 +1,7 @@import * as React from 'react';import { Info } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { getBackendUiMeta } from '@/lib/agentBackends';import { GuardGapList } from './GuardGapList';import type { RouteHopRef, SupplyGap } from './types';@@ -63,7 +64,7 @@ export const GuardImpact: React.FC<GuardPicture & {><span className="min-w-0 flex-1"><strong>- {t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}+ {getBackendUiMeta(hop.backend).label} · {hop.menu_model}</strong>{/* The supplier and the model it serves, in the Agent card'sown mapping copy rather than a second string that woulddiff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex c2dc5e8f9..5eaa0b8c7 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -15,6 +15,7 @@ import {DialogTitle,} from '@/components/ui/dialog';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { useToast } from '@/context/ToastContext';import type { TranslationKey } from '@/i18n/types';import { providerLabel, providerVendorId } from '../providers/providerIdentity';@@ -462,14 +463,14 @@ export const MigrationDialog: React.FC<{{grouped.map((group) => (<div key={group.backend} className="flex flex-col gap-2"><span className="px-1 font-mono text-[11px] font-semibold uppercase tracking-normal text-muted">- {t(`settings.models.backends.${group.backend}`, { defaultValue: group.backend })}+ {getBackendUiMeta(group.backend).label}</span>{group.required.size > 1 && (<p className="px-1 text-[12px] leading-relaxed text-muted">{t('settings.models.migration.sharedFiles', {backends: BACKEND_ORDER.filter((backend) => group.required.has(backend))- .map((backend) => t(`settings.models.backends.${backend}`))+ .map((backend) => getBackendUiMeta(backend).label).join(', '),})}</p>diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsxindex 854b7f969..33705e1bb 100644--- a/ui/src/components/settings/models/RouteChainDialog.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.tsx@@ -20,6 +20,7 @@ import { Button } from "@/components/ui/button";import { ResponsiveMenu } from "@/components/ui/responsive-menu";import { SegmentedRadio } from "@/components/ui/segmented";import { cn } from "@/lib/utils";+import { getBackendUiMeta } from "@/lib/agentBackends";import { useIsMobile } from "@/lib/useIsMobile";import { GuardDialog } from "./GuardDialog";import { GuardImpact, type GuardPlan } from "./GuardImpact";@@ -225,11 +226,7 @@ export const RouteChainDialog: React.FC<{const targetSources = agent ? eligibleSources(sources, agent) : [];const canEditRoute = draft.length > 0 || addCandidates.length > 0|| targetSources.some((source) => source.kind === 'api_key');- const backend = agent- ? (t(`settings.models.backends.${agent.backend}`, {- defaultValue: agent.backend,- }) as string)- : "";+ const backend = agent ? getBackendUiMeta(agent.backend).label : "";const valid = agent? validateRouteDraft(agent, sources, origin, draft): { invalidIndexes: [], valid: false };diff --git a/ui/src/components/settings/models/RouteOriginBadge.tsx b/ui/src/components/settings/models/RouteOriginBadge.tsxindex 6ca2a5656..df63a6241 100644--- a/ui/src/components/settings/models/RouteOriginBadge.tsx+++ b/ui/src/components/settings/models/RouteOriginBadge.tsx@@ -1,6 +1,7 @@import * as React from 'react';import { useTranslation } from 'react-i18next';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { getBackendUiMeta } from '@/lib/agentBackends';import type { AgentBackend, RouteOrigin } from './types';type RouteOriginBadgeProps = {@@ -62,7 +63,7 @@ export function RouteOriginBadge({ origin, backend, interactive = true, open = fonCloseAutoFocus={(event) => event.preventDefault()}onEscapeKeyDown={(event) => { event.stopPropagation(); close(); }}onClick={(event) => event.stopPropagation()}- >{t(`settings.models.routing.help.${key}`, { backend: t(`settings.models.backends.${backend}`) })}</PopoverContent>+ >{t(`settings.models.routing.help.${key}`, { backend: getBackendUiMeta(backend).label })}</PopoverContent></Popover>);}diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex ddf214de5..8630f38c3 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -660,7 +660,7 @@ describe('SettingsModelsPage surface branches', () => {});it('renders Frame 09 as the sources tab when every backend is direct and no source exists', async () => {- renderPage([]);+ renderPage([], [directAgent('claude'), directAgent('codex'), directAgent('opencode')]);expect(await screen.findByText(/^Currently: direct$|^当前:直连$/i)).toBeTruthy();expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到模型网关$/i })).toHaveLength(3);@@ -916,8 +916,8 @@ describe('SettingsModelsPage surface branches', () => {expect(await screen.findByText('Retained source')).toBeTruthy();});- // Upgrades always return an empty Avibe row. Existing native-only responses- // missed both the lost Direct landing and the unusable runtime Stop control.+ // The in-process catalog is configurable even when empty and without a CLI.+ // Runtime Stop still depends on whether that catalog actually owns models.it.each([false, true])('MH-AVIBE-003 derives runtime use from Avibe catalog presence: %s', async (configured) => {const catalogModel: BackendModel = {id: 'menu-alias', display_name: null, origin: 'manual', models_dev_id: null,@@ -933,12 +933,18 @@ describe('SettingsModelsPage surface branches', () => {name: configured ? /Avibe models use|Avibe 的模型通过/i : /Turn model gateway off|关闭模型网关/i,});expect((toggle as HTMLButtonElement).disabled).toBe(configured);+ const avibeCard = (await screen.findByText('Avibe Agent')).closest('[data-agent-backend]') as HTMLElement;+ expect(within(avibeCard).getAllByRole('button', { name: /^Manage models$|^管理模型$/i }).length).toBeGreaterThan(0);+ await userEvent.click(within(avibeCard).getByRole('button', { name: /Runtime mode:|运行模式[::]/i }));+ const modeGroup = await screen.findByRole('group', { name: /Runtime mode|运行模式/i });+ expect(within(modeGroup).queryByRole('button', { name: /Switch to direct|切到直连/i })).toBeNull();+ await userEvent.click(within(modeGroup).getByRole('button', { pressed: true }));if (configured) {expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();await userEvent.click(toggle);expect(stop).not.toHaveBeenCalled();} else {- expect(await screen.findByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeTruthy();+ expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到模型网关$/i })).toHaveLength(3);await userEvent.click(toggle);await waitFor(() => expect(stop).toHaveBeenCalledOnce());diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex bb5773f4e..ad4853bfa 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -73,7 +73,8 @@ import { groupMigrationCandidates } from './migrationGrouping';import { SUBSCRIPTION_MENU_ROWS } from './subscriptionOptions';import { VendorGlyph } from './vendorGlyph';import { backendVisual } from './vendorMeta';-import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type NativeCliBackend, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';+import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';+import { getBackendUiMeta, isNativeCliBackend, type NativeCliBackend } from '@/lib/agentBackends';const CHAIN_READ_CONCURRENCY = 6;const EVENT_PAGE = 20;@@ -371,7 +372,7 @@ const DirectHome: React.FC<{<span className="model-hub-direct-tile flex size-[34px] shrink-0 items-center justify-center rounded-[9px]"><Icon className="size-[17px]" /></span><span className="model-hub-direct-backend-copy"><span className="flex min-w-0 items-center gap-1.5">- <span className="model-hub-direct-backend-name truncate text-foreground">{t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</span>+ <span className="model-hub-direct-backend-name truncate text-foreground">{getBackendUiMeta(agent.backend).label}</span><span className="model-hub-pill model-hub-direct-kind-pill border">{t('settings.models.direct.pill.direct')}</span></span>{switchFailed@@ -1156,7 +1157,10 @@ export const SettingsModelsPage: React.FC = () => {: supplyRead;const directEmpty = modelsSurfaceKindFromReads(supplyDisplayRead, sourcesDisplayRead) === 'direct_empty';const installedAgents = agents.filter(- (agent): agent is AgentSupply & { backend: NativeCliBackend } => agent.backend !== 'avibe' && agent.cli_present,+ (agent) => !getBackendUiMeta(agent.backend).capabilities.supports_cli || agent.cli_present,+ );+ const installedNativeAgents = installedAgents.filter(+ (agent): agent is AgentSupply & { backend: NativeCliBackend } => isNativeCliBackend(agent.backend),);const hubBackends = agents.filter(agentUsesHubRuntime).map((agent) => agent.backend);const activeBackends = supplyRead.kind === 'ready' ? new Set(hubBackends) : undefined;@@ -1172,7 +1176,7 @@ export const SettingsModelsPage: React.FC = () => {|| stopBlocked;const runtimeSwitchLabel = stopBlocked? supplyRead.kind === 'ready'- ? hubBackends.includes('avibe')+ ? hubBackends.some((backend) => !getBackendUiMeta(backend).capabilities.supports_cli)? t('settings.models.shell.toggle.stopAvibeBlocked'): t('settings.models.shell.toggle.stopBlocked', { names: hubBackends.join(', ') }): t('settings.models.shell.toggle.stopUnavailable')@@ -1552,7 +1556,7 @@ export const SettingsModelsPage: React.FC = () => {read={runtimeRead}starting={startingRuntime}stopping={stoppingRuntime}- directCount={directEmpty ? installedAgents.length : undefined}+ directCount={directEmpty ? installedNativeAgents.length : undefined}/>{runtimeConfigurationVisible && migrationAvailable === true && (<Button@@ -1617,7 +1621,7 @@ export const SettingsModelsPage: React.FC = () => {/>: tab === 'usage' ? <UsageTab usage={usageRead} windowKey={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />- : directEmpty ? <DirectHome agents={installedAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />+ : directEmpty ? <DirectHome agents={installedNativeAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />: <div className="model-hub-overview"><div className="model-hub-overview-body"><div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex ccead06f5..3066c1dea 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -8,6 +8,7 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Input } from '@/components/ui/input';import { ResponsiveMenu } from '@/components/ui/responsive-menu';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { formatRelativeTime } from '@/lib/relativeTime';import { AddApiKeyDialog } from './AddApiKeyDialog';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';@@ -633,7 +634,7 @@ export const SourceDetailPanel: React.FC<{if (guard.kind === 'removeModel') void remove(guard.model, guard.plan);};const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);- const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];+ const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => getBackendUiMeta(backend).label))];const state = sourceStatePresentation(source.state, 'detail', i18n.language, now, {known: adoptedBy !== undefined,backends: adoptedBackends,diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsxindex cfe091ff0..b0652a8c6 100644--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { ModelHubInfoHint } from './ModelHubInfoHint';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';import type { PendingWrite } from './asyncLifetime';@@ -278,7 +279,7 @@ export const SourceOrderDrawer: React.FC<{});};- const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });+ const backend = getBackendUiMeta(agent.backend).label;const title = t('settings.models.order.title', { backend });const announcementText = announcement ? t(`settings.models.order.${announcement.key}`, announcement) : '';const saveEnabled = readState === 'ready' && (!sameIds(saved, order) || saveFailed);diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex d17f8e561..db3b27e27 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -3,6 +3,7 @@ import { ChevronRight } from 'lucide-react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';+import { getBackendUiMeta } from '@/lib/agentBackends';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';import { sourceDetail } from './sourcePresentation';import { SourcePrivateValue } from './SourcePrivacy';@@ -22,7 +23,7 @@ export const SourceRow: React.FC<{const detail = sourceDetail(source);const interfaceLabel = t(PROTOCOL_COPY_KEYS[source.protocol]);const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);- const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];+ const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => getBackendUiMeta(backend).label))];const state = sourceStatePresentation(source.state, 'card', i18n.language, now, {known: adoptedBy !== undefined,backends: adoptedBackends,diff --git a/ui/src/components/settings/models/migrationGrouping.ts b/ui/src/components/settings/models/migrationGrouping.tsindex ea0ef048b..e697a84c5 100644--- a/ui/src/components/settings/models/migrationGrouping.ts+++ b/ui/src/components/settings/models/migrationGrouping.ts@@ -9,6 +9,7 @@// native config cannot be parsed at all.import type { TranslationKey } from '@/i18n/types';import type { AgentBackend, MigrationItem, MigrationScan } from './types';+import { NATIVE_SETUP_BACKENDS } from '@/lib/agentBackends';/*** A scan plus the backends consented to against it.@@ -22,7 +23,7 @@ export type MigrationSelection = {selectedBackends: AgentBackend[];};-export const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];+export const BACKEND_ORDER = NATIVE_SETUP_BACKENDS;export const isImportable = (item: MigrationItem) => item.proposed_action === 'import';diff --git a/ui/src/components/settings/models/modelHubSurfaceState.ts b/ui/src/components/settings/models/modelHubSurfaceState.tsindex ca0074780..982f4a075 100644--- a/ui/src/components/settings/models/modelHubSurfaceState.ts+++ b/ui/src/components/settings/models/modelHubSurfaceState.ts@@ -1,14 +1,17 @@import { foldRegionRead, type RegionRead } from './regionRead';import type { AgentSupply, Source } from './types';+import { getBackendUiMeta } from '@/lib/agentBackends';export type ModelsSurfaceKind = 'direct_empty' | 'gateway';/** Match runtime_stop: the upgrade-added empty Avibe catalog holds no runtime. */export const agentUsesHubRuntime = (agent: AgentSupply): boolean =>- agent.mode === 'hub' && (agent.backend !== 'avibe' || (agent.catalog_models?.length ?? 0) > 0);+ agent.mode === 'hub' && (getBackendUiMeta(agent.backend).capabilities.supports_cli || (agent.catalog_models?.length ?? 0) > 0);export const modelsSurfaceKind = (agents: AgentSupply[], sources: Source[]): ModelsSurfaceKind =>- !agents.some(agentUsesHubRuntime) && sources.length === 0+ // An empty in-process catalog still needs the gateway card's model editor.+ // Whether it currently holds the runtime is a separate question above.+ !agents.some((agent) => agent.mode === 'hub') && sources.length === 0? 'direct_empty': 'gateway';diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 1a059c16b..a214b967f 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -155,8 +155,9 @@ export type Source = {// per-backend subset, carried by `AgentSupply.sources` below.// ── agent-supply.schema.json ────────────────────────────────────────────-export type NativeCliBackend = 'claude' | 'codex' | 'opencode';-export type AgentBackend = NativeCliBackend | 'avibe';+import type { AgentBackendId, NativeCliBackend } from '@/lib/agentBackends';+export type { NativeCliBackend } from '@/lib/agentBackends';+export type AgentBackend = AgentBackendId;export type AgentMode = 'hub' | 'direct';export type MenuKind = 'fixed' | 'open';diff --git a/ui/src/components/settings/oauth/useBackendOAuth.ts b/ui/src/components/settings/oauth/useBackendOAuth.tsindex 3dd866b50..c29e78cbc 100644--- a/ui/src/components/settings/oauth/useBackendOAuth.ts+++ b/ui/src/components/settings/oauth/useBackendOAuth.ts@@ -4,8 +4,9 @@ import { useApi, type OAuthWebStartResult, type OAuthWebState } from '@/context/import { useToast } from '@/context/ToastContext';import { errorMessage } from '@/lib/errorMessage';import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';+import type { WebOAuthBackend } from '@/lib/agentBackends';-export type OAuthBackend = 'claude' | 'codex' | 'opencode';+export type OAuthBackend = WebOAuthBackend;const POLL_INTERVAL_MS = 2000;const POLL_DEADLINE_MS = 16 * 60 * 1000;diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxindex 7fb02c948..6787c9b5e 100644--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -7,6 +7,7 @@ import { useBackendRuntime } from '../shared/useBackendRuntime';import { BackendTestPanel } from '../BackendTestPanel';import { BackendConnectionForm } from './BackendConnectionForm';import { Card, CardContent } from '@/components/ui/card';+import { getBackendUiMeta } from '@/lib/agentBackends';export function ClaudeProviderConfig({ hideEnableToggle }: { hideEnableToggle?: boolean } = {}) {const { t } = useTranslation();@@ -14,7 +15,7 @@ export function ClaudeProviderConfig({ hideEnableToggle }: { hideEnableToggle?:const modelHubEnabled = useModelHubCapability();if (!runtime.loaded) return <p>{t('common.loading')}</p>;return <div className="flex flex-col gap-4">- <BackendRuntimeCard backend="claude" label="Claude Code" description={t('settings.backends.claudeDescription')}+ <BackendRuntimeCard backend="claude" label={getBackendUiMeta('claude').label} description={t('settings.backends.claudeDescription')}Icon={Sparkles} iconTileClassName="bg-cyan-soft" iconClassName="text-cyan-ink" runtime={runtime} hideEnableToggle={hideEnableToggle} />{modelHubEnabled === true && <BackendSupplyModeCard backend="claude" />}<Card><CardContent className="p-6"><BackendConnectionForm backend="claude" connectionRevision={runtime.connectionRevision} /></CardContent></Card>diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsxindex 63caa2597..5000d389d 100644--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx@@ -7,6 +7,7 @@ import { useBackendRuntime } from '../shared/useBackendRuntime';import { BackendTestPanel } from '../BackendTestPanel';import { BackendConnectionForm } from './BackendConnectionForm';import { Card, CardContent } from '@/components/ui/card';+import { getBackendUiMeta } from '@/lib/agentBackends';export function CodexProviderConfig({ hideEnableToggle }: { hideEnableToggle?: boolean } = {}) {const { t } = useTranslation();@@ -14,7 +15,7 @@ export function CodexProviderConfig({ hideEnableToggle }: { hideEnableToggle?: bconst modelHubEnabled = useModelHubCapability();if (!runtime.loaded) return <p>{t('common.loading')}</p>;return <div className="flex flex-col gap-4">- <BackendRuntimeCard backend="codex" label="Codex" description={t('settings.backends.codexDescription')}+ <BackendRuntimeCard backend="codex" label={getBackendUiMeta('codex').label} description={t('settings.backends.codexDescription')}Icon={Bot} iconTileClassName="bg-gold" iconClassName="text-gold-foreground" runtime={runtime} hideEnableToggle={hideEnableToggle} />{modelHubEnabled === true && <BackendSupplyModeCard backend="codex" />}<Card><CardContent className="p-6"><BackendConnectionForm backend="codex" connectionRevision={runtime.connectionRevision} /></CardContent></Card>diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxindex 240ea3f8f..48d73a435 100644--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -42,6 +42,7 @@ import type {} from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { errorMessage } from '@/lib/errorMessage';+import { getBackendUiMeta } from '@/lib/agentBackends';import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';import { EFFORT_BY_BACKEND, NO_REASONING_EFFORT, sortEffortsByVocabulary } from '@/lib/effortOptions';import { HubOwnedAuthNotice } from '../shared/HubOwnedAuthNotice';@@ -735,7 +736,7 @@ export const OpencodeProviderConfig: React.FC<{<div className="flex flex-col gap-4"><BackendRuntimeCardbackend={BACKEND_ID}- label="OpenCode"+ label={getBackendUiMeta('opencode').label}description={t('settings.backends.opencodeDescription')}Icon={Terminal}iconTileClassName="bg-violet-soft"diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsxindex c091ab933..c6f46a4e2 100644--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx@@ -6,7 +6,6 @@ import {Save,Search,} from 'lucide-react';-import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';import { Button } from '../../ui/button';@@ -17,6 +16,7 @@ import { InstallOutcome } from '../../shared/InstallOutcome';import { BackendLifecycleChip } from '../BackendLifecycleChip';import { ToggleSwitch } from '../SettingsPrimitives';import type { BackendRuntimeState, BackendId } from './useBackendRuntime';+import { getBackendUiMeta, type BackendUiMeta } from '@/lib/agentBackends';export interface BackendRuntimeCardProps {/** Backend id used by ``BackendLifecycleChip`` + ``installAgent``. */@@ -26,7 +26,7 @@ export interface BackendRuntimeCardProps {/** Short description sentence under the name. */description: string;/** Lucide icon component used in the header tile. */- Icon: LucideIcon;+ Icon: BackendUiMeta['Icon'];/*** Tailwind class string for the icon tile background, e.g.* ``"bg-cyan-soft"`` (Claude) / ``"bg-gold"`` (Codex) /@@ -81,6 +81,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({}) => {const { t } = useTranslation();const inputId = `${backend}-cli-path`;+ const { capabilities } = getBackendUiMeta(backend);return (<Card>@@ -101,21 +102,21 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({</div></div><div className="flex items-center gap-3">- <BackendLifecycleChip+ {capabilities.supports_runtime_refresh && <BackendLifecycleChipname={backend}enabled={runtime.enabled}cliStatus={runtime.cliStatus}cliPath={runtime.cliPath}onChanged={runtime.handleLifecycleChanged}onOperationChange={(busy) => { if (!busy) void runtime.handleLifecycleChanged(null); }}- />+ />}{!hideEnableToggle && (<ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />)}</div></div>- <div className="flex flex-col gap-2">+ {capabilities.supports_cli && <div className="flex flex-col gap-2"><Label htmlFor={inputId} className="text-xs font-medium uppercase text-muted">{t('agentDetection.cliPath')}</Label>@@ -146,9 +147,9 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({</Button></div><p className="text-[12px] text-muted">{t('settings.backends.cliPathHint')}</p>- </div>+ </div>}- {runtime.cliStatus === 'missing' && (+ {capabilities.supports_install && runtime.cliStatus === 'missing' && (<div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5"><p className="text-[12px] text-cyan-ink">{t('agentDetection.installHint')}</p><Button@@ -174,7 +175,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({{extraSlot}- {runtime.runtimeDirty && (+ {capabilities.supports_cli && runtime.runtimeDirty && (<div className="flex justify-end"><Buttonvariant="brand"diff --git a/ui/src/components/settings/shared/useBackendRuntime.test.tsx b/ui/src/components/settings/shared/useBackendRuntime.test.tsxindex 7031c08a3..8d1074e9d 100644--- a/ui/src/components/settings/shared/useBackendRuntime.test.tsx+++ b/ui/src/components/settings/shared/useBackendRuntime.test.tsx@@ -51,6 +51,21 @@ const mountRuntime = async () => {};describe('persisted backend install paths', () => {+ it('keeps an in-process backend disabled by default and rejects CLI work at the hook boundary', async () => {+ const hook = renderHook(() => useBackendRuntime({ backend: 'avibe' }));+ await waitFor(() => expect(hook.result.current.loaded).toBe(true));+ expect(hook.result.current.enabled).toBe(false);+ expect(hook.result.current.cliPath).toBe('');+ await act(async () => {+ await hook.result.current.detect();+ await hook.result.current.install();+ await hook.result.current.onSaveRuntime();+ });+ expect(mocks.api.detectCli).not.toHaveBeenCalled();+ expect(mocks.api.installAgent).not.toHaveBeenCalled();+ expect(hook.result.current.runtimeDirty).toBe(false);+ });+it('does not mark a lifecycle install as an unsaved path edit', async () => {const hook = await mountRuntime();diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsindex aeed5e3a3..2043e2b32 100644--- a/ui/src/components/settings/shared/useBackendRuntime.ts+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -5,16 +5,17 @@ import { useApi, type InstallResult } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { setConfigField } from '@/lib/configMutations';import { errorMessage } from '@/lib/errorMessage';+import { getBackendUiMeta, type AgentBackendId } from '@/lib/agentBackends';export type CliStatus = 'unknown' | 'ok' | 'missing';-export type BackendId = 'claude' | 'codex' | 'opencode';+export type BackendId = AgentBackendId;export interface UseBackendRuntimeOptions {/** Backend identifier used in V2Config keys and install_agent dispatch. */backend: BackendId;/** Fallback CLI binary name when V2Config carries no override. */- defaultCli: string;+ defaultCli?: string | null;}export interface BackendRuntimeState {@@ -99,15 +100,18 @@ const assertBackendRuntimeApplied = (*/export function useBackendRuntime({backend,- defaultCli,+ defaultCli: cliOverride,}: UseBackendRuntimeOptions): BackendRuntimeState {const api = useApi();const { showToast } = useToast();const { t } = useTranslation();+ const { capabilities, defaultEnabled, defaultCli: catalogCli } = getBackendUiMeta(backend);+ const defaultCli = cliOverride ?? catalogCli ?? '';+ const { supports_cli: supportsCli, supports_install: supportsInstall } = capabilities;const [loaded, setLoaded] = useState(false);const [configError, setConfigError] = useState(false);- const [enabled, setEnabled] = useState(true);+ const [enabled, setEnabled] = useState(defaultEnabled);const [cliPath, setCliPath] = useState(defaultCli);const [savedCliPath, setSavedCliPath] = useState(defaultCli);const [cliStatus, setCliStatus] = useState<CliStatus>('unknown');@@ -130,6 +134,7 @@ export function useBackendRuntime({const detect = useCallback(async (binary?: string) => {+ if (!supportsCli) return;const token = ++detectionToken.current;const intent = pathIntent.current;setDetecting(true);@@ -147,7 +152,7 @@ export function useBackendRuntime({if (mounted.current && detectionToken.current === token) setDetecting(false);}},- [api, cliPath, defaultCli, showToast, t],+ [api, cliPath, defaultCli, showToast, supportsCli, t],);// Initial load: read V2Config for ``enabled`` + ``cli_path`` and then@@ -160,14 +165,14 @@ export function useBackendRuntime({.then((config) => {if (cancelled) return;const agent = config?.agents?.[backend];- const initialEnabled = typeof agent?.enabled === 'boolean' ? agent.enabled : true;- const initialPath = agent?.cli_path || defaultCli;+ const initialEnabled = typeof agent?.enabled === 'boolean' ? agent.enabled : defaultEnabled;+ const initialPath = supportsCli ? agent?.cli_path || defaultCli : '';setEnabled(initialEnabled);setCliPath(initialPath);setSavedCliPath(initialPath);setConfigError(false);setLoaded(true);- void detect(initialPath);+ if (supportsCli) void detect(initialPath);}).catch((e: any) => {if (cancelled) return;@@ -185,9 +190,10 @@ export function useBackendRuntime({cancelled = true;};// eslint-disable-next-line react-hooks/exhaustive-deps- }, [api, backend, defaultCli]);+ }, [api, backend, defaultCli, defaultEnabled, supportsCli]);const install = useCallback(async () => {+ if (!supportsInstall) return;const intent = pathIntent.current;setInstalling(true);setInstallResult(null);@@ -217,9 +223,10 @@ export function useBackendRuntime({setInstalling(false);}}- }, [api, backend, cliPath, detect, showToast, t]);+ }, [api, backend, cliPath, detect, showToast, supportsInstall, t]);const onSaveRuntime = useCallback(async () => {+ if (!supportsCli) return;setSavingRuntime(true);const path = cliPath || defaultCli;// Save edits only the CLI field. Enablement has its own serialized toggle;@@ -242,7 +249,7 @@ export function useBackendRuntime({});mutationQueue.current = operation;await operation;- }, [api, backend, cliPath, defaultCli, showToast, t]);+ }, [api, backend, cliPath, defaultCli, showToast, supportsCli, t]);const toggleEnabled = useCallback(() => {const next = !enabled;@@ -296,7 +303,7 @@ export function useBackendRuntime({[detect],);- const runtimeDirty = cliPath !== savedCliPath;+ const runtimeDirty = supportsCli && cliPath !== savedCliPath;return {loaded,diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 98800f385..0928bbd68 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -27,10 +27,10 @@ import { setConfigField } from '@/lib/configMutations';import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';import { modelHubEnabledFromConfig } from '../settings/models/featureFlags';import type { SetupAction, SetupFlowState, SetupScreenHandle, SetupScreenId } from '../onboarding/setupFlow';-import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';+import type { NativeCliBackend as RuntimeBackendId } from '@/lib/agentBackends';import { useOpencodePermission } from '../settings/shared/useOpencodePermission';import { Button } from '../ui/button';-import { DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';+import { DEFAULT_NATIVE_AGENT_STATE, NATIVE_CLI_BACKENDS, getBackendUiMeta } from '@/lib/agentBackends';import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';import { MODEL_HUB_SETTINGS_PATH } from '../settings/models/modelHubRoutes';import { RouteChainDialog, type RouteChainSelection } from '../settings/models/RouteChainDialog';@@ -90,12 +90,12 @@ type EnableReceipt = { intent: number; message: string };*/type ConnectionRefresh = { acknowledge?: boolean };-const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;+const DEFAULT_AGENTS = DEFAULT_NATIVE_AGENT_STATE as Record<string, AgentState>;// Backends with a dedicated provider config body (rendered in the wizard// modal / the settings route). Mirrors ``BackendProviderConfig``'s switch —// anything outside this set has no provider UI to configure.-const PROVIDER_BACKENDS: ReadonlySet<string> = new Set(['claude', 'codex', 'opencode']);+const PROVIDER_BACKENDS: ReadonlySet<string> = new Set(NATIVE_CLI_BACKENDS);const normalizeAgents = (source: any): Record<string, AgentState> => {const raw = source?.agents || {};diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex a4b4a611e..3b5a918c7 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -30,6 +30,7 @@ import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';import { TelegramTopicList } from './TelegramTopicList';+import { getBackendUiMeta } from '@/lib/agentBackends';const PLATFORM_BRAND_COLORS: Record<string, string> = {slack: '#4A154B',@@ -1470,11 +1471,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB? channelConfig.routing.claude_model: effectiveBackend === 'codex'? channelConfig.routing.codex_model- : channelConfig.routing.opencode_model+ : effectiveBackend === 'opencode' ? channelConfig.routing.opencode_model : undefined);const agentSummary = selectedAgent? `${selectedAgent.display_name || selectedAgent.name}${selectedAgent.model ? ` / ${selectedAgent.model}` : ''}`- : `${effectiveBackend === 'claude' ? 'Claude' : effectiveBackend === 'codex' ? 'Codex' : 'OpenCode'}${backendModel ? ` / ${backendModel}` : ''}`;+ : `${getBackendUiMeta(effectiveBackend).label}${backendModel ? ` / ${backendModel}` : ''}`;return (<divdiff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex fbc7ebb22..ee43444dc 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';+import { getBackendUiMeta } from '../../lib/agentBackends';import { getEnabledPlatforms, platformSupportsToolcallDelivery } from '../../lib/platforms';import { FolderBrowser } from '../ui/folder-browser';import { copyTextToClipboard } from '../../lib/utils';@@ -621,13 +622,6 @@ export const UserList: React.FC = () => {const totalCount = aggregated.length;- // Backend label helper- const backendLabel = (backend: string) => {- if (backend === 'claude') return 'Claude';- if (backend === 'codex') return 'Codex';- return 'OpenCode';- };-return (<><div className="flex h-full flex-col gap-5">@@ -709,7 +703,7 @@ export const UserList: React.FC = () => {const metaPrefix = userConfig.enabled? selectedAgent? `${selectedAgent.display_name || selectedAgent.name}${selectedAgent.model ? `/${selectedAgent.model}` : ''}`- : `${backendLabel(effectiveBackend)}${backendModel ? `/${backendModel}` : ''}`+ : `${getBackendUiMeta(effectiveBackend).label}${backendModel ? `/${backendModel}` : ''}`: t('userList.disabled');const updateRow = (patch: Partial<UserConfig>) => updateUser(u.platform, u.userId, patch);diff --git a/ui/src/components/steps/Welcome.tsx b/ui/src/components/steps/Welcome.tsxindex b52a2b9ee..5336a5d08 100644--- a/ui/src/components/steps/Welcome.tsx+++ b/ui/src/components/steps/Welcome.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';import { CollaborationStory } from '../onboarding/CollaborationStory';import { ASSISTANT_ORDER } from '../onboarding/collaborationTimeline';-import { DEFAULT_AGENT_STATE } from '@/lib/agentBackends';+import { DEFAULT_NATIVE_AGENT_STATE } from '@/lib/agentBackends';import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';import type { SetupAction, SetupScreenHandle } from '../onboarding/setupFlow';import '../onboarding/onboarding.css';@@ -36,7 +36,7 @@ export function Welcome({ data, onNext, active, ref, onActionChange }: WelcomePrsetError(null);try {const results = await Promise.all(ASSISTANT_ORDER.map(async (name) => {- const agent = { ...DEFAULT_AGENT_STATE[name], ...data?.agents?.[name] };+ const agent = { ...DEFAULT_NATIVE_AGENT_STATE[name], ...data?.agents?.[name] };const result = await api.detectCli(agent.cli_path || name);return [name, { ...agent, cli_path: result.path || agent.cli_path, status: result.found ? 'ok' : 'missing' }];}));diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsxindex 777cd9594..001ddeee2 100644--- a/ui/src/components/workbench/AgentsPage.test.tsx+++ b/ui/src/components/workbench/AgentsPage.test.tsx@@ -231,6 +231,35 @@ describe('AgentsPage load requests follow the rank that can serve them', () => {});describe('AgentsPage contextual selection', () => {+ it('lists, selects and edits an Avibe Agent without a native import option or CLI detail', async () => {+ const agent = { ...brief('local-helper', 'before'), backend: 'avibe' };+ const changed = { ...agent, description: 'updated in place' };+ const updateVibeAgent = vi.fn().mockResolvedValue(fullAgent(changed, 'prompt'));+ const api = makeApi(+ vi.fn().mockResolvedValue(listResult(agent)),+ vi.fn().mockResolvedValue(fullAgent(agent, 'prompt')),+ undefined, undefined, updateVibeAgent,+ );+ renderPage(api, { canManageAgents: true, entry: '/agents?agent=local-helper' });+ expect(await screen.findByText('Avibe Agent')).toBeTruthy();+ const row = screen.getAllByText('local-helper').find((node) => node.closest('button'))?.closest('button');+ expect(row).toBeTruthy();+ fireEvent.click(row!);+ const description = await screen.findByDisplayValue('before');+ fireEvent.change(description, { target: { value: 'updated in place' } });+ fireEvent.blur(description);+ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('local-helper', { description: 'updated in place' }));+ expect(screen.queryByText(/Avibe Agent CLI/)).toBeNull();+ expect(screen.getByText('agents.detail.backendName:{"backend":"Avibe Agent"}')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'agents.import' }));+ expect(screen.queryByText('agents.importFrom:{"backend":"Avibe Agent"}')).toBeNull();+ // Display names are not translation-key suffixes: a catalog brand change+ // must keep the native import actions translated and correctly scoped.+ for (const label of ['Claude Code', 'OpenCode', 'Codex']) {+ expect(screen.getByText(`agents.importFrom:{"backend":"${label}"}`)).toBeTruthy();+ }+ });+it('opens the Agent named by ?agent= instead of the default one', async () => {const agentA = brief('agent-a', 'A');const agentB = brief('agent-b', 'B');diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex c5de29f60..bd7d35098 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -58,10 +58,12 @@ import { CapabilityTabs } from './CapabilityTabs';// with the Skills surface (BACKEND_TEXT is this page's old BACKEND_ICON_CLASS).import {BACKEND_ORDER,+ NATIVE_BACKEND_ORDER,BACKEND_LABEL,BACKEND_TEXT as BACKEND_ICON_CLASS,type Backend,} from '../../lib/backendAccent';+import { getBackendUiMeta, type NativeCliBackend } from '@/lib/agentBackends';import { errorMessage } from '@/lib/errorMessage';// Tab set + its cross-visit memory live together so the remembered value can// never name a tab this page no longer renders (see agentsViewMemory).@@ -319,7 +321,7 @@ export const AgentsPage: React.FC = () => {const mutationErrorSequenceRef = useRef(0);const [search, setSearch] = useState('');const [backendFilter, setBackendFilter] = useState<Backend | 'all'>('all');- const [importing, setImporting] = useState<Backend | null>(null);+ const [importing, setImporting] = useState<NativeCliBackend | null>(null);const [onboardingInventory, setOnboardingInventory] = useState<VibeAgentOnboardingResult | null>(null);const [onboardingExpanded, setOnboardingExpanded] = useState(false);const [onboardingSubmitting, setOnboardingSubmitting] = useState(false);@@ -1296,7 +1298,7 @@ export const AgentsPage: React.FC = () => {}, [agents, search, backendFilter]);const grouped = useMemo(() => {- const groups: Record<Backend, VibeAgentBrief[]> = { claude: [], opencode: [], codex: [] };+ const groups = Object.fromEntries(BACKEND_ORDER.map((backend) => [backend, [] as VibeAgentBrief[]])) as Record<Backend, VibeAgentBrief[]>;for (const agent of filtered) {const key = (agent.backend as Backend) in groups ? (agent.backend as Backend) : null;if (key) groups[key].push(agent);@@ -1386,7 +1388,7 @@ export const AgentsPage: React.FC = () => {}};- const onImport = async (from: Backend) => {+ const onImport = async (from: NativeCliBackend) => {setImporting(from);try {const result = await api.importVibeAgents({ from, all: true });@@ -1871,8 +1873,8 @@ const BackendFilter: React.FC<BackendFilterProps> = ({ value, onChange }) => {};interface ImportMenuProps {- onImport: (from: Backend) => void;- importing: Backend | null;+ onImport: (from: NativeCliBackend) => void;+ importing: NativeCliBackend | null;}// Outline Button that opens a popover with one entry per backend. The@@ -1891,7 +1893,7 @@ const ImportMenu: React.FC<ImportMenuProps> = ({ onImport, importing }) => {</Button></PopoverTrigger><PopoverContent align="end" className="w-[200px] p-1">- {BACKEND_ORDER.map((backend) => (+ {NATIVE_BACKEND_ORDER.map((backend) => (<buttonkey={backend}type="button"@@ -1903,7 +1905,7 @@ const ImportMenu: React.FC<ImportMenuProps> = ({ onImport, importing }) => {className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:opacity-50"><Bot className={clsx('size-3.5', BACKEND_ICON_CLASS[backend])} />- <span>{t(`agents.importFrom${BACKEND_LABEL[backend]}` as const)}</span>+ <span>{t('agents.importFrom', { backend: BACKEND_LABEL[backend] })}</span></button>))}</PopoverContent>@@ -2372,7 +2374,10 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca{agent.backend}</span><span className="text-[11px] text-muted">·</span>- <span className="text-[11px] text-muted">{BACKEND_LABEL[agent.backend as Backend] || agent.backend} CLI</span>+ <span className="text-[11px] text-muted">{t(+ getBackendUiMeta(agent.backend).capabilities.supports_cli ? 'agents.detail.nativeBackend' : 'agents.detail.backendName',+ { backend: BACKEND_LABEL[agent.backend as Backend] || agent.backend },+ )}</span><span className="ml-auto font-mono text-[9px] text-muted">{t('agents.detail.backendLocked')}</span></div></Field>diff --git a/ui/src/components/workbench/GlobalPromptsDialog.test.tsx b/ui/src/components/workbench/GlobalPromptsDialog.test.tsxnew file mode 100644index 000000000..93e7ea068--- /dev/null+++ b/ui/src/components/workbench/GlobalPromptsDialog.test.tsx@@ -0,0 +1,41 @@+/* @vitest-environment jsdom */+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { GlobalPromptsDialog } from './GlobalPromptsDialog';++const mocks = vi.hoisted(() => ({+ getGlobalPrompts: vi.fn(),+ saveGlobalPrompts: vi.fn(),+}));+vi.mock('../../context/ApiContext', () => ({ useApi: () => mocks }));+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../ui/markdown-editor', () => ({ MarkdownEditor: () => null }));++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('native global prompts', () => {+ // Growing the Agent catalog must not invent a native prompt file for Avibe.+ // The sync payload is as important as the tabs: a hidden target is still a write.+ it('offers and synchronizes only native backend files', async () => {+ const files = ['claude', 'opencode', 'codex', 'avibe'].map((backend) => ({+ backend, content: 'Instructions', path: `/fixture/${backend}/AGENTS.md`,+ filename: 'AGENTS.md', exists: true, read_error: false,+ }));+ mocks.getGlobalPrompts.mockResolvedValue({ backends: files });+ mocks.saveGlobalPrompts.mockResolvedValue({ backends: files });+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ render(<GlobalPromptsDialog open onClose={vi.fn()} />);+ await screen.findByRole('tab', { name: 'Claude Code' });+ expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['Claude Code', 'OpenCode', 'Codex']);+ expect(screen.queryByRole('tab', { name: 'Avibe Agent' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'globalPrompts.sync' }));+ await waitFor(() => expect(mocks.saveGlobalPrompts).toHaveBeenCalledWith({+ content: 'Instructions', backends: ['claude', 'opencode', 'codex'],+ }));+ });+});diff --git a/ui/src/components/workbench/GlobalPromptsDialog.tsx b/ui/src/components/workbench/GlobalPromptsDialog.tsxindex ea711c250..fb6a307d1 100644--- a/ui/src/components/workbench/GlobalPromptsDialog.tsx+++ b/ui/src/components/workbench/GlobalPromptsDialog.tsx@@ -10,12 +10,13 @@ import { useToast } from '../../context/ToastContext';import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog';import { Button } from '../ui/button';import { MarkdownEditor } from '../ui/markdown-editor';-import { BACKEND_ORDER, BACKEND_LABEL, BACKEND_TEXT, BACKEND_DOT, type Backend } from '../../lib/backendAccent';+import { NATIVE_BACKEND_ORDER as BACKEND_ORDER, BACKEND_LABEL, BACKEND_TEXT, BACKEND_DOT } from '../../lib/backendAccent';+import type { NativeCliBackend as Backend } from '@/lib/agentBackends';type FileMeta = { path: string; filename: string; exists: boolean; readError: boolean };-const emptyStringMap = (): Record<Backend, string> => ({ claude: '', opencode: '', codex: '' });-const emptyMetaMap = (): Record<Backend, FileMeta | null> => ({ claude: null, opencode: null, codex: null });+const emptyStringMap = () => Object.fromEntries(BACKEND_ORDER.map((id) => [id, ''])) as Record<Backend, string>;+const emptyMetaMap = () => Object.fromEntries(BACKEND_ORDER.map((id) => [id, null])) as Record<Backend, FileMeta | null>;// Index an API response (one entry per backend) into a per-backend map over the// canonical BACKEND_ORDER, so missing/extra ids never desync the editor state.diff --git a/ui/src/components/workbench/NewAgentDialog.test.tsx b/ui/src/components/workbench/NewAgentDialog.test.tsxindex e80926a73..10740ef6d 100644--- a/ui/src/components/workbench/NewAgentDialog.test.tsx+++ b/ui/src/components/workbench/NewAgentDialog.test.tsx@@ -97,6 +97,29 @@ afterEach(() => {});describe('NewAgentDialog', () => {+ // The picker used a second label table, so its Claude label disagreed with+ // Settings and Model Hub. All backend choices share the catalog brands.+ it('uses the catalog brand names for every backend choice', () => {+ renderDialog();+ for (const label of ['Claude Code', 'OpenCode', 'Codex', 'Avibe Agent']) {+ expect(screen.getByRole('button', { name: new RegExp(label) }).textContent).toContain(label);+ }+ expect(screen.queryByText('Claude', { exact: true })).toBeNull();+ });++ it('creates an Avibe Agent through the existing backend and model pickers', async () => {+ modelCatalog = { models: ['avibe-model'], reasoningOptions: { 'avibe-model': [] } };+ const { createVibeAgent } = renderDialog();+ fireEvent.click(screen.getByRole('button', { name: /Avibe Agent/ }));+ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'local-helper' } });+ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.click(screen.getByRole('option', { name: 'avibe-model' }));+ submit();+ await waitFor(() => expect(createVibeAgent).toHaveBeenCalledWith(expect.objectContaining({+ name: 'local-helper', backend: 'avibe', model: 'avibe-model', reasoning_effort: null,+ })));+ });+it("keeps the form while the user adds a model in the Model Hub catalog", async () => {// Settings hides the page this dialog sits in; closing it would clear the// Agent the user was halfway through defining.diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex 0e02b36ec..de624bd1e 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -17,24 +17,15 @@ import { EditorDialog } from '../ui/editor-dialog';import { Button } from '../ui/button';import { errorMessage } from '@/lib/errorMessage';import { useRouteSurfaceWindowEvent } from '@/lib/routeSurfaceActivity';+import { getBackendUiMeta, type AgentBackendId } from '@/lib/agentBackends';+import { BACKEND_ORDER, BACKEND_LABEL } from '@/lib/backendAccent';-type BackendKey = 'claude' | 'opencode' | 'codex';--interface BackendOption {- key: BackendKey;- label: string;- publisher: string;- color: 'mint' | 'cyan' | 'violet';-}--const BACKEND_OPTIONS: BackendOption[] = [- { key: 'claude', label: 'Claude', publisher: 'Anthropic', color: 'mint' },- // OpenCode is the upstream project at opencode.ai (not sst.dev — that- // was an older publisher attribution that doesn't match the current- // project page).- { key: 'opencode', label: 'OpenCode', publisher: 'opencode.ai', color: 'cyan' },- { key: 'codex', label: 'Codex', publisher: 'OpenAI', color: 'violet' },-];+const BACKEND_OPTIONS = BACKEND_ORDER.map((id) => ({+ key: id,+ label: BACKEND_LABEL[id],+ publisher: getBackendUiMeta(id).publisher,+ color: getBackendUiMeta(id).accent,+}));interface NewAgentDialogProps {/** When false the modal renders nothing — controlled by the parent. */@@ -49,7 +40,7 @@ interface NewAgentDialogProps {export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, onCreated }) => {const { t } = useTranslation();const api = useApi();- const [backend, setBackend] = useState<BackendKey>('claude');+ const [backend, setBackend] = useState<AgentBackendId>('claude');const [name, setName] = useState('');const [description, setDescription] = useState('');const [model, setModel] = useState('');@@ -170,7 +161,7 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o}};- const colorClasses: Record<BackendOption['color'], { border: string; bg: string; text: string }> = {+ const colorClasses = {mint: { border: 'border-mint', bg: 'bg-mint/[0.08]', text: 'text-mint-ink' },cyan: { border: 'border-cyan', bg: 'bg-cyan/[0.08]', text: 'text-cyan-ink' },violet: { border: 'border-violet', bg: 'bg-violet/[0.08]', text: 'text-violet-ink' },@@ -205,7 +196,7 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o<div className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('agents.create.backend')}</div>- <div className="grid grid-cols-3 gap-2.5">+ <div className="grid grid-cols-2 gap-2.5 sm:grid-cols-4">{BACKEND_OPTIONS.map((opt) => {const active = backend === opt.key;const cc = colorClasses[opt.color];diff --git a/ui/src/components/workbench/skills/AddSkillDialog.tsx b/ui/src/components/workbench/skills/AddSkillDialog.tsxindex f0a98a597..78ed16ca3 100644--- a/ui/src/components/workbench/skills/AddSkillDialog.tsx+++ b/ui/src/components/workbench/skills/AddSkillDialog.tsx@@ -10,6 +10,7 @@ import { SegmentedRadio } from '../../ui/segmented';import { Checkbox } from '../../ui/checkbox';import { FileDropzone } from './FileDropzone';import { errorMessage } from '@/lib/errorMessage';+import { AGENT_ID_TO_BACKEND } from '@/lib/backendAccent';export interface AddSkillDialogProps {defaultScope: SkillScope;@@ -114,7 +115,7 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,return ['askill add',baseSource,- '-a claude-code opencode codex',+ `-a ${Object.keys(AGENT_ID_TO_BACKEND).join(' ')}`,selector,scope === 'global' ? '-g' : '','-y',diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex cf2370295..adbb082d4 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -2,6 +2,7 @@ import React, { createContext, useContext, useEffect, useMemo, useRef } from 'reimport { useTranslation } from 'react-i18next';import { useToast } from './ToastContext';import type { AgentSupply } from '../components/settings/models/types';+import type { AgentBackendId, NativeCliBackend, WebOAuthBackend } from '../lib/agentBackends';import { apiFetch, recoverRemoteAuthFromSessionProbe, withApiDeadline } from '../lib/apiFetch';import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import type { TurnActivityGroupWire } from '../lib/agentActivity';@@ -581,7 +582,7 @@ export type ApiContextType = {installAgent: (name: string) => Promise<InstallResult>;listDependencies: (options?: DependencyReadOptions) => Promise<DependenciesResult>;installDependency: (dep: string) => Promise<InstallResult>;- getBackendConnection: (name: 'claude' | 'codex' | 'opencode') => Promise<BackendConnectionState>;+ getBackendConnection: (name: AgentBackendId) => Promise<BackendConnectionState>;getBackendRuntime: (name: string) => Promise<BackendRuntimeInfo>;restartBackend: (name: string) => Promise<BackendRestartResult>;getCodexAuth: () => Promise<CodexAuthState>;@@ -594,16 +595,16 @@ export type ApiContextType = {forceReset?: boolean,) => Promise<OAuthWebStartResult>;getOAuthWebStatus: (- backend: 'claude' | 'codex' | 'opencode',+ backend: WebOAuthBackend,flowId: string,) => Promise<OAuthWebStatus>;submitOAuthWebCode: (- backend: 'claude' | 'codex' | 'opencode',+ backend: WebOAuthBackend,flowId: string,code: string,) => Promise<OAuthWebMutationResult>;cancelOAuthWeb: (- backend: 'claude' | 'codex' | 'opencode',+ backend: WebOAuthBackend,flowId: string,) => Promise<OAuthWebMutationResult>;removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;@@ -835,7 +836,7 @@ export type ApiContextType = {signVaultDigest: (payload: Record<string, unknown>) => Promise<{ ok: boolean; signature?: Record<string, unknown>; request?: VaultRequest; code?: string; message?: string }>;pinVaultPubkey: (payload: Record<string, unknown>) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;getVaultAudit: (params?: { secret?: string; limit?: number }) => Promise<{ ok: boolean; events: VaultAuditEvent[] }>;- importVibeAgents: (payload: { from?: 'claude' | 'codex' | 'opencode'; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;+ importVibeAgents: (payload: { from?: NativeCliBackend; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;// Agent Skills — thin shells over the askill CLI (see /api/skills*).listSkills: (params?: { scope?: SkillScope | 'all'; projectId?: string; backends?: string[] }) => Promise<SkillsListResult>;previewSkillSource: (source: string, params?: { projectId?: string }) => Promise<SkillsPreviewResult>;@@ -1930,7 +1931,7 @@ export type DependencyReadOptions = { ids?: readonly string[]; signal?: AbortSigexport type BackendConnectionState = {ok: boolean;- backend: 'claude' | 'codex' | 'opencode';+ backend: AgentBackendId;installed: boolean;enabled: boolean;auth: 'subscription' | 'api_key' | 'none' | 'unknown';@@ -2111,7 +2112,7 @@ export type OAuthWebState =export type OAuthWebStartResult = {ok: boolean;flow_id?: string;- backend?: 'claude' | 'codex' | 'opencode';+ backend?: WebOAuthBackend;state?: OAuthWebState;url?: string | null;device_code?: string | null;@@ -2125,7 +2126,7 @@ export type OAuthWebStartResult = {export type OAuthWebStatus = {ok: boolean;flow_id?: string;- backend?: 'claude' | 'codex' | 'opencode';+ backend?: WebOAuthBackend;state?: OAuthWebState;url?: string | null;device_code?: string | null;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex cf3ced10c..aacbb3b51 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -584,6 +584,8 @@"claudeSubtitle": "Detect or install the Claude Code CLI. Sign in or supply an API key from the CLI itself.","claudeDescription": "Anthropic agent · sign in with Claude or supply an API key","codexDescription": "OpenAI agent · ChatGPT login or OPENAI_API_KEY",+ "avibeDescription": "Built-in agent · models and routes managed in Model Hub",+ "backToBackends": "Back to backends","openProviderPage": "Configure provider","providerOauth": "OAuth (default)","providerApiKey": "API key",@@ -2075,12 +2077,6 @@"opencode": "OpenCode configuration"}},- "backends": {- "claude": "Claude Code",- "codex": "Codex",- "opencode": "OpenCode",- "avibe": "Avibe Agent"- },"sourceTest": {"open": "Test","testNow": "Test now",@@ -4007,9 +4003,7 @@"statusDisabled": "disabled","newAgent": "New agent","import": "Import",- "importFromClaude": "Import from Claude",- "importFromCodex": "Import from Codex",- "importFromOpenCode": "Import from OpenCode",+ "importFrom": "Import from {{backend}}","importSuccess": "Imported {{imported}}, skipped {{skipped}}.","importFailed": "Import failed: {{error}}","importNoneFound": "No {{backend}} agents found on disk to import.",@@ -4037,6 +4031,8 @@"descriptionPlaceholder": "What this agent is for…","backend": "Backend","backendLocked": "creation-time only · locked",+ "nativeBackend": "{{backend}} CLI",+ "backendName": "{{backend}}","model": "Model","modelPlaceholder": "Pick or type a model","modelEmpty": "No matches — you can type a custom value.",@@ -5203,20 +5199,17 @@"caption": "Plan · Build · Test · Deliver","returnCaption": "Tests passed · back to the PM","claude": {- "name": "Claude Code","role": "PM","working": "Writing the project brief","complete": "Project brief ready","summary": "Summarizing the delivery"},"codex": {- "name": "Codex","role": "Developer","working": "Writing code","complete": "Implementation ready"},"opencode": {- "name": "OpenCode","role": "Tester","working": "Writing and running tests","complete": "All tests passed"diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.tsindex e15cb47d0..7cf648d57 100644--- a/ui/src/i18n/keyCoverage.test.ts+++ b/ui/src/i18n/keyCoverage.test.ts@@ -1245,13 +1245,14 @@ describe('app i18n key coverage', () => {'remoteAuthorization.unavailable.body',]),);- // A name two kinds of call reach. `RouteOriginBadge` asks for the copy- // outright; a dozen sites pass `agent.backend` as their own fallback. Both- // belong here, and while the dedup key was the failure label the fallback- // calls buried the outright one — so the whole family sat outside the- // existence check, in the one place the app names its backends.- expect(referenced).toContainEqual({ key: 'settings.models.backends.claude', counted: false, listed: false, demand: 'exact' });- expect(referenced).toContainEqual({ key: 'settings.models.backends.claude', counted: false, listed: false, demand: 'none' });+ // DirectHome is native-only. Widening its props to every backend made the+ // checker demand nonexistent Avibe Direct prose. Brand names themselves+ // now belong to catalog metadata; exact/defaulted dedup stays covered by+ // fixture.both in the collector test above.+ for (const backend of ['claude', 'codex', 'opencode']) {+ expect(referenced).toContainEqual({ key: `settings.models.direct.backend.${backend}.detail`, counted: false, listed: false, demand: 'exact' });+ }+ expect(referenced.some(({ key }) => key === 'settings.models.direct.backend.avibe.detail')).toBe(false);});// A name the bundles never had is not an existence gap: nothing here can telldiff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c63d113f4..bd8594456 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -584,6 +584,8 @@"claudeSubtitle": "检测或安装 Claude Code CLI。登录与 API Key 请直接通过 CLI 完成。","claudeDescription": "Anthropic Agent · 通过 Claude 登录或填入 API Key","codexDescription": "OpenAI Agent · 通过 ChatGPT 登录或 OPENAI_API_KEY",+ "avibeDescription": "内置 Agent · 在模型中枢管理模型和路由",+ "backToBackends": "返回后端列表","openProviderPage": "配置 Provider","providerOauth": "OAuth(默认)","providerApiKey": "API Key",@@ -2075,12 +2077,6 @@"opencode": "OpenCode 配置"}},- "backends": {- "claude": "Claude Code",- "codex": "Codex",- "opencode": "OpenCode",- "avibe": "Avibe Agent"- },"sourceTest": {"open": "测试","testNow": "立即测试",@@ -4007,9 +4003,7 @@"statusDisabled": "已停用","newAgent": "新建 Agent","import": "导入",- "importFromClaude": "从 Claude 导入",- "importFromCodex": "从 Codex 导入",- "importFromOpenCode": "从 OpenCode 导入",+ "importFrom": "从 {{backend}} 导入","importSuccess": "已导入 {{imported}} 个,跳过 {{skipped}} 个。","importFailed": "导入失败:{{error}}","importNoneFound": "磁盘上没有找到可导入的 {{backend}} Agent。",@@ -4037,6 +4031,8 @@"descriptionPlaceholder": "这个 Agent 用来做什么…","backend": "后端","backendLocked": "创建时确定 · 不可改",+ "nativeBackend": "{{backend}} CLI",+ "backendName": "{{backend}}","model": "模型","modelPlaceholder": "选择或输入模型","modelEmpty": "找不到匹配的模型,可以直接输入。",@@ -5203,20 +5199,17 @@"caption": "规划 · 开发 · 测试 · 交付","returnCaption": "测试通过,回传 PM","claude": {- "name": "Claude Code","role": "PM","working": "编写需求文档","complete": "需求文档已就绪","summary": "汇总结果,完成交付"},"codex": {- "name": "Codex","role": "开发","working": "编写功能代码","complete": "功能代码已就绪"},"opencode": {- "name": "OpenCode","role": "测试","working": "编写并执行用例","complete": "测试全部通过"diff --git a/ui/src/lib/agentBackendCatalog.generated.ts b/ui/src/lib/agentBackendCatalog.generated.tsnew file mode 100644index 000000000..ec14650fc--- /dev/null+++ b/ui/src/lib/agentBackendCatalog.generated.ts@@ -0,0 +1,81 @@+// Generated from modules/agents/catalog.py; do not edit.+// Regenerate with: uv run python -m scripts.generate_agent_backend_catalog+export const BACKEND_CATALOG = [+ {+ "id": "opencode",+ "display_name": "OpenCode",+ "config_key": "opencode",+ "default_cli": "opencode",+ "default_enabled": true,+ "latest_probe": [+ "github",+ "sst/opencode"+ ],+ "capabilities": {+ "supports_cli": true,+ "supports_native_sessions": true,+ "supports_runtime_refresh": true,+ "supports_web_oauth": true,+ "supports_install": true+ },+ "description_key": "settings.backends.opencodeDescription",+ "settings_route": "/settings/backends/opencode"+ },+ {+ "id": "claude",+ "display_name": "Claude Code",+ "config_key": "claude",+ "default_cli": "claude",+ "default_enabled": true,+ "latest_probe": [+ "npm",+ "@anthropic-ai/claude-code"+ ],+ "capabilities": {+ "supports_cli": true,+ "supports_native_sessions": true,+ "supports_runtime_refresh": true,+ "supports_web_oauth": true,+ "supports_install": true+ },+ "description_key": "settings.backends.claudeDescription",+ "settings_route": "/settings/backends/claude"+ },+ {+ "id": "codex",+ "display_name": "Codex",+ "config_key": "codex",+ "default_cli": "codex",+ "default_enabled": false,+ "latest_probe": [+ "npm",+ "@openai/codex"+ ],+ "capabilities": {+ "supports_cli": true,+ "supports_native_sessions": true,+ "supports_runtime_refresh": true,+ "supports_web_oauth": true,+ "supports_install": true+ },+ "description_key": "settings.backends.codexDescription",+ "settings_route": "/settings/backends/codex"+ },+ {+ "id": "avibe",+ "display_name": "Avibe Agent",+ "config_key": "avibe",+ "default_cli": null,+ "default_enabled": false,+ "latest_probe": null,+ "capabilities": {+ "supports_cli": false,+ "supports_native_sessions": false,+ "supports_runtime_refresh": false,+ "supports_web_oauth": false,+ "supports_install": false+ },+ "description_key": "settings.backends.avibeDescription",+ "settings_route": "/settings/backends/avibe"+ }+] as const;diff --git a/ui/src/lib/agentBackends.ts b/ui/src/lib/agentBackends.tsindex 0cf0a130f..9bd2c788a 100644--- a/ui/src/lib/agentBackends.ts+++ b/ui/src/lib/agentBackends.ts@@ -1,14 +1,26 @@import type React from 'react';import { Bot, Sparkles, Terminal } from 'lucide-react';+import { BACKEND_CATALOG } from './agentBackendCatalog.generated';-export type BackendId = 'opencode' | 'claude' | 'codex' | string;+type BackendDescriptor = (typeof BACKEND_CATALOG)[number];+export type AgentBackendId = BackendDescriptor['id'];+export type NativeCliBackend = Extract<BackendDescriptor, { capabilities: { supports_cli: true } }>['id'];+export type WebOAuthBackend = Extract<BackendDescriptor, { capabilities: { supports_web_oauth: true } }>['id'];+export type BackendId = string;+type BackendCapabilities = { [K in keyof BackendDescriptor['capabilities']]: boolean };export type BackendUiMeta = {id: BackendId;label: string;- defaultCli: string;+ defaultCli: string | null;defaultEnabled: boolean;settingsRoute: string;+ descriptionKey: string;+ capabilities: BackendCapabilities;+ agentOrder: number;+ nativeOrder: number;+ publisher: string;+ accent: 'mint' | 'cyan' | 'violet';Icon: React.ComponentType<{ size?: number; className?: string }>;initials: string;blockCls: string;@@ -17,13 +29,13 @@ export type BackendUiMeta = {iconCls: string;};-export const AGENT_BACKENDS = [- {- id: 'opencode',- label: 'OpenCode',- defaultCli: 'opencode',- defaultEnabled: true,- settingsRoute: '/settings/backends/opencode',+// Presentation only. Membership, defaults and capabilities come from Python.+const BACKEND_VISUALS = {+ opencode: {+ agentOrder: 1,+ nativeOrder: 2,+ publisher: 'opencode.ai',+ accent: 'cyan',Icon: Terminal,initials: 'OP',blockCls: 'border-mint/40 bg-mint/[0.10] text-mint-ink',@@ -31,12 +43,11 @@ export const AGENT_BACKENDS = [tileCls: 'bg-violet-soft',iconCls: 'text-violet-ink',},- {- id: 'claude',- label: 'Claude Code',- defaultCli: 'claude',- defaultEnabled: true,- settingsRoute: '/settings/backends/claude',+ claude: {+ agentOrder: 0,+ nativeOrder: 0,+ publisher: 'Anthropic',+ accent: 'mint',Icon: Sparkles,initials: 'CL',blockCls: 'border-[rgba(217,119,87,0.4)] bg-[rgba(217,119,87,0.10)] text-[#e8a87c]',@@ -44,12 +55,11 @@ export const AGENT_BACKENDS = [tileCls: 'bg-cyan-soft',iconCls: 'text-cyan-ink',},- {- id: 'codex',- label: 'Codex',- defaultCli: 'codex',- defaultEnabled: false,- settingsRoute: '/settings/backends/codex',+ codex: {+ agentOrder: 2,+ nativeOrder: 1,+ publisher: 'OpenAI',+ accent: 'violet',Icon: Bot,initials: 'CO',blockCls: 'border-violet/40 bg-violet/[0.10] text-violet-ink',@@ -57,7 +67,43 @@ export const AGENT_BACKENDS = [tileCls: 'bg-gold',iconCls: 'text-gold-foreground',},-] as const satisfies readonly BackendUiMeta[];+ avibe: {+ agentOrder: 3,+ nativeOrder: 3,+ publisher: 'Avibe',+ accent: 'mint',+ Icon: Bot,+ initials: 'AV',+ blockCls: 'border-mint/40 bg-mint/[0.10] text-mint-ink',+ glyphCls: 'text-mint-ink',+ tileCls: 'bg-mint-soft',+ iconCls: 'text-mint-ink',+ },+} as const satisfies Record<AgentBackendId, Pick<BackendUiMeta,+ 'agentOrder' | 'nativeOrder' | 'publisher' | 'accent' | 'Icon' | 'initials' | 'blockCls' | 'glyphCls' | 'tileCls' | 'iconCls'>>;++export const AGENT_BACKENDS = BACKEND_CATALOG.map((backend) => ({+ ...BACKEND_VISUALS[backend.id],+ id: backend.id,+ label: backend.display_name,+ defaultCli: backend.default_cli,+ defaultEnabled: backend.default_enabled,+ settingsRoute: backend.settings_route,+ descriptionKey: backend.description_key,+ capabilities: backend.capabilities,+}));++export const NATIVE_CLI_BACKENDS = BACKEND_CATALOG+ .filter((backend): backend is Extract<BackendDescriptor, { capabilities: { supports_cli: true } }> =>+ backend.capabilities.supports_cli)+ .map((backend) => backend.id);++export const NATIVE_SETUP_BACKENDS = [...NATIVE_CLI_BACKENDS]+ .sort((left, right) => BACKEND_VISUALS[left].nativeOrder - BACKEND_VISUALS[right].nativeOrder);++export function isNativeCliBackend(id: string): id is NativeCliBackend {+ return (NATIVE_CLI_BACKENDS as readonly string[]).includes(id);+}export const DEFAULT_BACKEND_ID = 'opencode';@@ -70,20 +116,38 @@ export const DEFAULT_AGENT_STATE = Object.fromEntries(backend.id,{enabled: backend.defaultEnabled,- cli_path: backend.defaultCli,+ ...(backend.capabilities.supports_cli ? { cli_path: backend.defaultCli } : {}),status: 'unknown',},]),);+export const DEFAULT_NATIVE_AGENT_STATE = Object.fromEntries(+ NATIVE_CLI_BACKENDS.map((id) => [id, DEFAULT_AGENT_STATE[id]]),+);++export function getBackendUiMeta(id: AgentBackendId): (typeof AGENT_BACKENDS)[number];+export function getBackendUiMeta(id: string): BackendUiMeta;export function getBackendUiMeta(id: string): BackendUiMeta {return (AGENT_BACKEND_BY_ID[id] || {id,label: id.replace(/_/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()),- defaultCli: id,+ defaultCli: null,defaultEnabled: false,settingsRoute: `/settings/backends/${id}`,+ descriptionKey: `settings.backends.${id}Description`,+ capabilities: {+ supports_cli: false,+ supports_native_sessions: false,+ supports_runtime_refresh: false,+ supports_web_oauth: false,+ supports_install: false,+ },+ agentOrder: Number.MAX_SAFE_INTEGER,+ nativeOrder: Number.MAX_SAFE_INTEGER,+ publisher: '',+ accent: 'mint',Icon: Bot,initials: id.slice(0, 2).toUpperCase(),blockCls: 'border-border bg-surface-2 text-foreground',diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.tsindex c750d1e09..40130a956 100644--- a/ui/src/lib/applicationRoutes.ts+++ b/ui/src/lib/applicationRoutes.ts@@ -1,3 +1,5 @@+import { AGENT_BACKENDS } from './agentBackends';+// Exact routes declared in App.tsx. Keep this as the shared policy for any// feature that must distinguish an AppShell destination from another// same-origin path, such as local-file Markdown links and iOS PWA navigation.@@ -55,9 +57,7 @@ export const APPLICATION_ROUTE_PATHS = ['/settings/platforms/users','/settings/remote-access','/settings/backends',- '/settings/backends/opencode',- '/settings/backends/claude',- '/settings/backends/codex',+ ...AGENT_BACKENDS.map((backend) => backend.settingsRoute),'/settings/models','/settings/dependencies','/settings/replies',diff --git a/ui/src/lib/backendAccent.ts b/ui/src/lib/backendAccent.tsindex 8e8bdf2c3..d3c7c9bdb 100644--- a/ui/src/lib/backendAccent.ts+++ b/ui/src/lib/backendAccent.ts@@ -4,20 +4,24 @@// carries Settings-page backend-tile chrome (icons, tile classes, CLI// defaults) for a different visual context.-export const BACKEND_ORDER = ['claude', 'opencode', 'codex'] as const;-export type Backend = (typeof BACKEND_ORDER)[number];+import { AGENT_BACKENDS, isNativeCliBackend, type AgentBackendId, type NativeCliBackend } from './agentBackends';-export const BACKEND_LABEL = {- claude: 'Claude',- opencode: 'OpenCode',- codex: 'Codex',-} as const satisfies Record<Backend, string>;+export const BACKEND_ORDER = [...AGENT_BACKENDS]+ .sort((left, right) => left.agentOrder - right.agentOrder)+ .map((backend) => backend.id);+export const NATIVE_BACKEND_ORDER = BACKEND_ORDER.filter(isNativeCliBackend);+export type Backend = AgentBackendId;++export const BACKEND_LABEL = Object.fromEntries(+ AGENT_BACKENDS.map(({ id, label }) => [id, label]),+) as Record<Backend, string>;// Text / icon accent — e.g. <Icon className={BACKEND_TEXT[b]} />.export const BACKEND_TEXT: Record<Backend, string> = {claude: 'text-mint-ink',opencode: 'text-cyan-ink',codex: 'text-violet-ink',+ avibe: 'text-mint-ink',};// Solid dot fill — e.g. a status dot inside a chip.@@ -25,6 +29,7 @@ export const BACKEND_DOT: Record<Backend, string> = {claude: 'bg-mint',opencode: 'bg-cyan',codex: 'bg-violet',+ avibe: 'bg-mint',};// Full pill surface (soft bg + 40% border + accent text) for backend chips.@@ -32,6 +37,7 @@ export const BACKEND_CHIP: Record<Backend, string> = {claude: 'bg-mint-soft border-mint/40 text-mint-ink',opencode: 'bg-cyan-soft border-cyan/40 text-cyan-ink',codex: 'bg-violet-soft border-violet/40 text-violet-ink',+ avibe: 'bg-mint-soft border-mint/40 text-mint-ink',};export function isBackend(value: string): value is Backend {@@ -40,7 +46,7 @@ export function isBackend(value: string): value is Backend {// askill agent id (e.g. "claude-code") -> our backend id. Agents we don't// surface (cursor, windsurf, …) are intentionally absent.-export const AGENT_ID_TO_BACKEND: Record<string, Backend> = {+export const AGENT_ID_TO_BACKEND: Record<string, NativeCliBackend> = {'claude-code': 'claude',opencode: 'opencode',codex: 'codex',@@ -48,11 +54,11 @@ export const AGENT_ID_TO_BACKEND: Record<string, Backend> = {// Distinct backends a skill serves, in canonical order, from its linked// askill agents. Unknown/unsupported agents are dropped.-export function backendsFromAgents(agents: ReadonlyArray<{ id: string }> | null | undefined): Backend[] {- const seen = new Set<Backend>();+export function backendsFromAgents(agents: ReadonlyArray<{ id: string }> | null | undefined): NativeCliBackend[] {+ const seen = new Set<NativeCliBackend>();for (const agent of agents ?? []) {const backend = AGENT_ID_TO_BACKEND[agent.id];if (backend) seen.add(backend);}- return BACKEND_ORDER.filter((backend) => seen.has(backend));+ return NATIVE_BACKEND_ORDER.filter((backend) => seen.has(backend));}diff --git a/ui/src/lib/backendModels.test.ts b/ui/src/lib/backendModels.test.tsindex 0df0789a6..d168007ad 100644--- a/ui/src/lib/backendModels.test.ts+++ b/ui/src/lib/backendModels.test.ts@@ -135,6 +135,26 @@ describe('fetchBackendModels for OpenCode', () => {});describe('fetchBackendModels in gateway mode', () => {+ it('projects Avibe models and effort metadata without a CLI fallback', async () => {+ const readModelHubAgentCatalogForModelPicker = vi.fn().mockResolvedValue(hubAgent('avibe', {+ cli_present: false,+ catalog_models: [model('local-model', { display_name: 'Local model', supports_reasoning: false })],+ }));+ const claudeModels = vi.fn();+ const codexModels = vi.fn();+ const readOpencodeOptionsForModelPicker = vi.fn();+ const api = { readModelHubAgentCatalogForModelPicker, claudeModels, codexModels, readOpencodeOptionsForModelPicker } as unknown as ApiContextType;+ expect(await fetchBackendModels(api, 'avibe')).toEqual({+ models: ['local-model'], modelLabels: { 'local-model': 'Local model' }, reasoningOptions: { 'local-model': [] },+ });+ expect(readModelHubAgentCatalogForModelPicker).toHaveBeenCalledWith('avibe');+ readModelHubAgentCatalogForModelPicker.mockResolvedValue(null);+ expect(await fetchBackendModels(api, 'avibe')).toEqual({ models: [] });+ expect(claudeModels).not.toHaveBeenCalled();+ expect(codexModels).not.toHaveBeenCalled();+ expect(readOpencodeOptionsForModelPicker).not.toHaveBeenCalled();+ });+it('does not use inherited Object properties as model labels', () => {expect(modelOptionLabel('constructor', {})).toBe('constructor');});diff --git a/ui/src/lib/backendModels.ts b/ui/src/lib/backendModels.tsindex c15abd289..59ab5cdea 100644--- a/ui/src/lib/backendModels.ts+++ b/ui/src/lib/backendModels.ts@@ -8,6 +8,7 @@ import { ApiError, useApi, type ApiContextType } from '../context/ApiContext';import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';import { useRouteSurfaceActive } from './routeSurfaceActivity';import { settingsOverlayContinuationState } from './settingsOverlay';+import { getBackendUiMeta } from './agentBackends';export interface BackendModels {/** Selectable model identifiers for the backend. */@@ -80,6 +81,7 @@ export async function fetchBackendModels(): Promise<BackendModels> {const hub = hubCatalogModels(await api.readModelHubAgentCatalogForModelPicker(backend), backend);if (hub) return hub;+ if (!getBackendUiMeta(backend).capabilities.supports_cli) return { models: [] };if (backend === 'claude') {const res = await api.claudeModels();return {diff --git a/ui/src/lib/pwaRouteMemory.ts b/ui/src/lib/pwaRouteMemory.tsindex d3c548b55..dc1a1c070 100644--- a/ui/src/lib/pwaRouteMemory.ts+++ b/ui/src/lib/pwaRouteMemory.ts@@ -1,4 +1,5 @@import { LEGACY_SETTINGS_REDIRECTS } from './settingsRoutes';+import { AGENT_BACKENDS } from './agentBackends';const STORAGE_KEY = 'avibe.pwa.last-route.v1';@@ -29,9 +30,7 @@ const RESTORABLE_EXACT_PATHS = new Set(['/settings/platforms/users','/settings/remote-access','/settings/backends',- '/settings/backends/opencode',- '/settings/backends/claude',- '/settings/backends/codex',+ ...AGENT_BACKENDS.map((backend) => backend.settingsRoute),'/settings/models','/settings/dependencies','/settings/replies',diff --git a/ui/src/lib/wizardConfigMutations.ts b/ui/src/lib/wizardConfigMutations.tsindex 222916f69..20722e9aa 100644--- a/ui/src/lib/wizardConfigMutations.ts+++ b/ui/src/lib/wizardConfigMutations.ts@@ -5,6 +5,7 @@ import {type ConfigMutation,} from './configMutations';import { getEnabledPlatforms, platformHasRunnableConfig } from './platforms';+import { NATIVE_CLI_BACKENDS } from './agentBackends';import {withoutConfiguredSecretMarker,withSecretDraft,@@ -12,7 +13,7 @@ import {} from './secretFields';const WIZARD_PLATFORMS = ['slack', 'discord', 'telegram', 'lark', 'wechat'] as const;-const WIZARD_BACKENDS = ['opencode', 'claude', 'codex'] as const;+const WIZARD_BACKENDS = NATIVE_CLI_BACKENDS;const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);diff --git a/vibe/api.py b/vibe/api.pyindex b2a5f696f..73a62f358 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -103,13 +103,17 @@ from vibe.restart_supervisor import schedule_restartfrom vibe import backend_model_catalogfrom vibe.i18n import t as backend_tfrom modules.agents.catalog import (+ AGENT_BACKENDS,+ NATIVE_CLI_BACKENDS,agent_backend_catalog_payload,agent_backend_descriptors,display_name_for_backend,is_agent_backend,+ is_native_cli_backend,latest_probe_for_backend,runtime_refresh_success_message,supports_runtime_refresh,+ supports_install,supports_web_oauth,)from modules.agents.subagent_router import list_codex_subagents@@ -172,7 +176,7 @@ def _native_auth_write(def decorate(function):def acquire(args, kwargs):target = str(backend or kwargs.get("backend") or (args[0] if args else "")).strip().lower()- if target not in {"claude", "codex", "opencode"}:+ if target not in NATIVE_CLI_BACKENDS:raise NativeMigrationBlockedError("unsupported_backend", ())lease = NativeCredentialLease((target,)).acquire()try:@@ -255,7 +259,7 @@ def _enabled_agent_backends_from_config(config: Optional[V2Config] = None) -> liresult: list[str] = []agents = getattr(cfg, "agents", None)if agents is not None:- for backend in ("opencode", "claude", "codex"):+ for backend in AGENT_BACKENDS:backend_cfg = getattr(agents, backend, None)if backend_cfg is not None and bool(getattr(backend_cfg, "enabled", True)):result.append(backend)@@ -340,7 +344,7 @@ def resolve_cli_paths(for binary, path in resolved.items():if path is None:name = Path(os.path.expanduser(binary)).name- if name in {"claude", "codex", "opencode"}:+ if name in NATIVE_CLI_BACKENDS:resolved[binary] = resolve_published_desktop_backend(name)return resolved@@ -1293,6 +1297,7 @@ def config_to_payload("opencode": config.agents.opencode.__dict__,"claude": _agent_payload(config.agents.claude.__dict__, include_secrets=include_secrets),"codex": _agent_payload(config.agents.codex.__dict__, include_secrets=include_secrets),+ "avibe": config.agents.avibe.__dict__,# Mirror ``V2Config.save`` — avault must be emitted here too, or every# UI save (which uses this payload as the deep-merge base) silently# resets ``agents.avault.cli_path`` to the dataclass default.@@ -4966,7 +4971,7 @@ def import_vibe_agents(payload: dict, *, user_context: Any = None) -> dict:path = _validate_direct_agent_import_path(Path(file_path).expanduser())candidates.append(_parse_agent_import_file(path, backend=backend))else:- if source not in {"claude", "codex", "opencode"}:+ if source not in NATIVE_CLI_BACKENDS:raise ValueError("from must be one of: claude, codex, opencode")if name and import_all:raise ValueError("Use either name or all, not both")@@ -6858,7 +6863,7 @@ def agent_model_options("""normalized_backend = (backend or "").strip().lower()- if normalized_backend not in ("claude", "codex", "opencode"):+ if normalized_backend not in AGENT_BACKENDS:return {"ok": False, "error": f"unknown backend '{backend}'", "backend": normalized_backend}try:@@ -6866,6 +6871,26 @@ def agent_model_options(except Exception:config = None+ if not is_native_cli_backend(normalized_backend):+ if config is None:+ return {"ok": False, "backend": normalized_backend, "error": "config_unavailable"}+ supply = config.model_hub.agents[normalized_backend]+ return {+ "ok": True,+ "backend": normalized_backend,+ "models": [+ {+ "value": model.id,+ "label": model.display_name or model.id,+ "reasoning_efforts": (+ [] if model.supports_reasoning is False else list(model.reasoning_efforts)+ ),+ }+ for model in supply.models+ ],+ "source": "model_hub",+ "live": False,+ }if normalized_backend == "claude":data = claude_models()if not data.get("ok"):@@ -6968,7 +6993,7 @@ def start_agent_install_job(name: str) -> dict:install/upgrade implementation as the CLI card used before; only theexecution boundary changes."""- if not is_agent_backend(name):+ if not supports_install(name):return {"ok": False, "message": f"Unknown agent: {name}"}job_id = uuid.uuid4().hex@@ -7119,9 +7144,7 @@ def _persist_agent_cli_path(name: str, installed_path: str, *, required: bool =_DESKTOP_BACKEND_LABELS = {- "claude": "Claude Code",- "codex": "Codex",- "opencode": "OpenCode",+ backend: display_name_for_backend(backend) for backend in NATIVE_CLI_BACKENDS}_DESKTOP_BACKEND_ERROR_I18N_KEYS = {"unknown_backend": "desktopBackendInstall.unknownBackend",@@ -7189,6 +7212,8 @@ def install_agent(name: str) -> dict:Settings runs this in the UI process and backend auto-update in thecontroller, so only a file lock keeps two installers off one CLI."""+ if not supports_install(name):+ return {"ok": False, "message": f"Unknown agent: {name}"}lock = MigrationFileLock(paths.get_state_dir() / "agent_install" / f"{name}.lock", timeout_seconds=0)try:lock.acquire()@@ -10050,7 +10075,11 @@ async def get_backend_connection(name: str) -> dict:backend_config = getattr(config.agents, name)enabled = bool(backend_config.enabled)supply_mode = config.model_hub.agents[name].mode- installed = await asyncio.to_thread(resolve_cli_path, backend_config.cli_path or name) is not None+ native = is_native_cli_backend(name)+ installed = (+ await asyncio.to_thread(resolve_cli_path, backend_config.cli_path or name) is not None+ if native else True+ )result = {"ok": True, "backend": name, "installed": installed, "enabled": enabled,"supply_mode": supply_mode,@@ -10085,7 +10114,7 @@ async def get_backend_connection(name: str) -> dict:result["message"] = receipt.get("message") or receipt.get("error")if not installed or config.load_warnings:return result- if name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):+ if native and name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):return resulttry:if supply_mode == "hub":@@ -10123,7 +10152,7 @@ async def get_backend_connection(name: str) -> dict:return result# An ownership transition may have started while the observation awaited# IPC or native read-only checks. Do not admit against a pending journal.- if name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):+ if native and name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):return resultcredential_ready = enabled and result["auth"] in {"subscription", "api_key"} and not result.get("permission_required")result["ready"] = credential_ready and result["application"] == "applied"@@ -10137,7 +10166,7 @@ def get_backend_runtime(name: str) -> dict:Versions are cached for short windows so popovers and re-renders do notfan out into many CLI invocations or registry HTTP calls."""- if not is_agent_backend(name):+ if not is_native_cli_backend(name):return {"ok": False, "error": f"Unknown backend: {name}"}try:diff --git a/vibe/cli.py b/vibe/cli.pyindex 66837f501..843bd3cd9 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -35,6 +35,7 @@ from sqlalchemy import selectfrom config import pathsfrom config.atomic_io import write_atomicfrom config.v2_config import V2Config+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backendfrom core.scheduled_tasks import (AGENT_RUN_CLOSE_AFTER_METADATA_KEY,AGENT_RUN_DELIVERY_QUEUE,@@ -5791,7 +5792,7 @@ def cmd_agent_import(args):raise TaskCliError("--backend is required when importing an arbitrary file",code="missing_agent_backend",- hint="Pass --backend codex, --backend claude, or --backend opencode.",+ hint=f"Pass --backend with one of: {', '.join(AGENT_BACKENDS)}.",)candidates.append(parse_agent_file(Path(args.file), backend=args.backend))else:@@ -12325,75 +12326,30 @@ def _doctor(*, deep: bool = False):# Agent Backends Groupagent_items = []if config:- # OpenCode- if config.agents.opencode.enabled:- cli_path = config.agents.opencode.cli_path- found_path = api.detect_cli(cli_path).get("path") if cli_path else None- if found_path:- _add_doctor_item(- agent_items,- "pass",- i18n_t("doctor.item.agentCliFound", language, agent="OpenCode", path=found_path),- )- summary["pass"] += 1- else:- _add_doctor_item(- agent_items,- "warn",- i18n_t("doctor.item.agentCliMissing", language, agent="OpenCode", path=cli_path),- i18n_t("doctor.action.agentCliMissing", language, agent="OpenCode"),- )- summary["warn"] += 1- else:- _add_doctor_item(agent_items, "pass", i18n_t("doctor.item.agentDisabled", language, agent="OpenCode"))- summary["pass"] += 1-- # Claude- if config.agents.claude.enabled:- cli_path = config.agents.claude.cli_path- found_path = api.detect_cli(cli_path).get("path") if cli_path else None-- if found_path:- _add_doctor_item(- agent_items,- "pass",- i18n_t("doctor.item.agentCliFound", language, agent="Claude", path=found_path),- )- summary["pass"] += 1+ for backend in NATIVE_CLI_BACKENDS:+ backend_config = getattr(config.agents, backend)+ label = display_name_for_backend(backend)+ if backend_config.enabled:+ cli_path = backend_config.cli_path+ found_path = api.detect_cli(cli_path).get("path") if cli_path else None+ if found_path:+ _add_doctor_item(+ agent_items,+ "pass",+ i18n_t("doctor.item.agentCliFound", language, agent=label, path=found_path),+ )+ summary["pass"] += 1+ else:+ _add_doctor_item(+ agent_items,+ "warn",+ i18n_t("doctor.item.agentCliMissing", language, agent=label, path=cli_path),+ i18n_t("doctor.action.agentCliMissing", language, agent=label),+ )+ summary["warn"] += 1else:- _add_doctor_item(- agent_items,- "warn",- i18n_t("doctor.item.agentCliMissing", language, agent="Claude", path=cli_path),- i18n_t("doctor.action.agentCliMissing", language, agent="Claude"),- )- summary["warn"] += 1- else:- _add_doctor_item(agent_items, "pass", i18n_t("doctor.item.agentDisabled", language, agent="Claude"))- summary["pass"] += 1-- # Codex- if config.agents.codex.enabled:- cli_path = config.agents.codex.cli_path- found_path = api.detect_cli(cli_path).get("path") if cli_path else None- if found_path:- _add_doctor_item(- agent_items,- "pass",- i18n_t("doctor.item.agentCliFound", language, agent="Codex", path=found_path),- )+ _add_doctor_item(agent_items, "pass", i18n_t("doctor.item.agentDisabled", language, agent=label))summary["pass"] += 1- else:- _add_doctor_item(- agent_items,- "warn",- i18n_t("doctor.item.agentCliMissing", language, agent="Codex", path=cli_path),- i18n_t("doctor.action.agentCliMissing", language, agent="Codex"),- )- summary["warn"] += 1- else:- _add_doctor_item(agent_items, "pass", i18n_t("doctor.item.agentDisabled", language, agent="Codex"))- summary["pass"] += 1# Default Agent checkdefault_agent_name = None@@ -16926,7 +16882,7 @@ def build_parser():agent_list_parser = agent_subparsers.add_parser("list", help="List Avibe Agents")agent_list_parser.add_argument("--brief", action="store_true", help=argparse.SUPPRESS)- agent_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")+ agent_list_parser.add_argument("--backend", choices=AGENT_BACKENDS, help="Filter by backend")agent_list_parser.add_argument("--include-disabled",action="store_true",@@ -16959,7 +16915,7 @@ def build_parser():"name", nargs="?", help="Agent name. Omit and pass --backend to query a backend directly.")agent_models_parser.add_argument(- "--backend", choices=("codex", "claude", "opencode"), help="Query a backend directly instead of an Agent."+ "--backend", choices=AGENT_BACKENDS, help="Query a backend directly instead of an Agent.")agent_models_parser.add_argument("--provider", help="Filter to one OpenCode provider id (OpenCode backend only)."@@ -16970,7 +16926,7 @@ def build_parser():agent_create_parser = agent_subparsers.add_parser("create", help="Create an Avibe Agent")agent_create_parser.add_argument("name", help="Globally unique Agent name")- agent_create_parser.add_argument("--backend", required=True, choices=("codex", "claude", "opencode"))+ agent_create_parser.add_argument("--backend", required=True, choices=AGENT_BACKENDS)agent_create_parser.add_argument("--description")agent_create_parser.add_argument("--model")agent_create_parser.add_argument("--reasoning-effort")@@ -17016,8 +16972,8 @@ def build_parser():agent_import_parser = agent_subparsers.add_parser("import", help="Import global or file-based Agents")import_source_group = agent_import_parser.add_mutually_exclusive_group(required=True)import_source_group.add_argument("--file", help="Import one markdown Agent file")- import_source_group.add_argument("--from", dest="from_source", choices=("claude", "codex", "opencode"))- agent_import_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Backend for --file imports")+ import_source_group.add_argument("--from", dest="from_source", choices=NATIVE_CLI_BACKENDS)+ agent_import_parser.add_argument("--backend", choices=AGENT_BACKENDS, help="Backend for --file imports")agent_import_parser.add_argument("--name", help="Import one named global Agent from --from source")agent_import_parser.add_argument("--all", action="store_true", help="Import all global Agents from --from source")_add_json_noop(agent_import_parser)@@ -17114,7 +17070,7 @@ def build_parser():runs_list_parser.add_argument("--status", help="Filter by run status")runs_list_parser.add_argument("--type", help="Filter by run type")runs_list_parser.add_argument("--agent", help="Filter by Avibe Agent name")- runs_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")+ runs_list_parser.add_argument("--backend", choices=AGENT_BACKENDS, help="Filter by backend")runs_list_parser.add_argument("--session-id", help="Filter by Agent Session ID")runs_list_parser.add_argument("--current-session", action="store_true", help="Filter to this current Agent Session")runs_list_parser.add_argument("--definition-id", help="Filter by task or watch definition ID")diff --git a/vibe/cli_paths.py b/vibe/cli_paths.pyindex 2e6860418..727a21cbc 100644--- a/vibe/cli_paths.py+++ b/vibe/cli_paths.py@@ -8,6 +8,7 @@ import reimport shutilimport subprocessfrom pathlib import Path+from modules.agents.catalog import NATIVE_CLI_BACKENDSfrom vibe.desktop_backends import is_desktop_backend_path, resolve_published_desktop_backend@@ -268,7 +269,7 @@ def resolve_cli_path(has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)if expanded.is_absolute() and is_desktop_backend_path(expanded):lookup_name = expanded.stem if expanded.suffix.lower() == ".exe" else expanded.name- if include_desktop and lookup_name in {"claude", "codex", "opencode"}:+ if include_desktop and lookup_name in NATIVE_CLI_BACKENDS:return resolve_published_desktop_backend(lookup_name)return Noneif expanded.is_absolute() or has_path_separator:@@ -289,7 +290,7 @@ def resolve_cli_path(return fallbackif include_desktop:lookup_name = expanded.name if expanded.is_absolute() or has_path_separator else binary- if lookup_name in {"claude", "codex", "opencode"}:+ if lookup_name in NATIVE_CLI_BACKENDS:return resolve_published_desktop_backend(lookup_name)return Nonediff --git a/vibe/global_agents_md.py b/vibe/global_agents_md.pyindex 2b0e4f5fc..473d7e24f 100644--- a/vibe/global_agents_md.py+++ b/vibe/global_agents_md.py@@ -27,7 +27,7 @@ from collections.abc import Iterablefrom pathlib import Pathfrom config.atomic_io import write_atomic-from modules.agents.catalog import AGENT_BACKENDS, is_agent_backend+from modules.agents.catalog import NATIVE_CLI_BACKENDS, is_agent_backendfrom vibe.claude_config import get_claude_homefrom vibe.codex_config import get_codex_homefrom vibe.opencode_config import get_opencode_config_paths@@ -96,7 +96,7 @@ def read_global_agents_md(backend: str, home: Path | None = None) -> dict:def read_all_global_agents_md(home: Path | None = None) -> list[dict]:"""Return the editor seed for every known backend, in catalog order."""- return [read_global_agents_md(backend, home) for backend in AGENT_BACKENDS]+ return [read_global_agents_md(backend, home) for backend in NATIVE_CLI_BACKENDS]def write_global_agents_md(backend: str, content: str, home: Path | None = None) -> dict:diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex f8e490f1d..d984c4ffe 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -468,6 +468,9 @@"routingUpdateNeedsNewSession": "Use /new to create a new session for this setting change to take effect. The new session will replace the current session."},"settings": {+ "backends": {+ "avibeDescription": "Avibe's built-in agent, powered by models configured in Model Hub."+ },"personalizationTitle": "Personalization Settings","personalizationDesc": "Configure how {agent} messages appear in your Slack workspace.","visibilityTitle": "Settings - Message Visibility",@@ -629,10 +632,6 @@"selectCodexAgent": "Select Codex agent","codexReasoningEffort": "Reasoning Effort","tip": "Select (Default) to use the backend's configured defaults."- },- "question": {- "opencode": "OpenCode",- "claudeCode": "Claude Code"}},"command": {@@ -773,11 +772,6 @@"quickReplyNote": "Reply: {text}","citationUnresolved": "(source unavailable)"},- "backend": {- "claude": "ClaudeCode",- "codex": "Codex",- "opencode": "OpenCode"- },"reasoning": {"none": "None","minimal": "Minimal",@@ -907,12 +901,6 @@"routingCanceled": "Routing update canceled."},"modelHub": {- "backends": {- "claude": "Claude Code",- "codex": "Codex",- "opencode": "OpenCode",- "avibe": "Avibe Agent"- },"errors": {"source_not_found": "Model source not found.","flow_not_found": "Authorization flow not found.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex ed8a71329..a40d4cc59 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -468,6 +468,9 @@"routingUpdateNeedsNewSession": "请使用 /new 命令创建新会话,以使设置变更生效。新会话创建后将覆盖当前会话。"},"settings": {+ "backends": {+ "avibeDescription": "Avibe 内置智能体,使用 Model Hub 中配置的模型。"+ },"personalizationTitle": "个性化设置","personalizationDesc": "配置 {agent} 的消息在你的 Slack 工作区中的展示方式。","visibilityTitle": "设置 - 消息可见性",@@ -629,10 +632,6 @@"selectCodexAgent": "选择 Codex Agent","codexReasoningEffort": "推理强度","tip": "选择“(默认)”以使用后端的配置默认值。"- },- "question": {- "opencode": "OpenCode",- "claudeCode": "Claude Code"}},"command": {@@ -773,11 +772,6 @@"quickReplyNote": "回复:{text}","citationUnresolved": "(来源不可用)"},- "backend": {- "claude": "ClaudeCode",- "codex": "Codex",- "opencode": "OpenCode"- },"reasoning": {"none": "无","minimal": "最小",@@ -907,12 +901,6 @@"routingCanceled": "已取消更新 Agent 路由设置。"},"modelHub": {- "backends": {- "claude": "Claude Code",- "codex": "Codex",- "opencode": "OpenCode",- "avibe": "Avibe Agent"- },"errors": {"source_not_found": "未找到模型供应商。","flow_not_found": "未找到授权流程。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 7a4ca289a..f2bcd2eea 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -72,7 +72,7 @@ from core.show_session_events import (show_event_requests_dispatch,)from core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_id-from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, supports_runtime_refreshfrom vibe.i18n import get_supported_languages, tfrom vibe.logging_config import application_log_pathsfrom vibe.runtime import get_ui_dist_path, get_working_dir@@ -8105,7 +8105,7 @@ def codex_models():@app.route("/api/agent/<name>/install", methods=["POST"])def agent_install(name):"""Install an agent CLI tool (opencode, claude, codex)."""- if name not in _ALLOWED_BACKENDS:+ if name not in NATIVE_CLI_BACKENDS:return jsonify({"ok": False, "message": f"Unknown agent: {name}"}), 400from vibe import api@@ -8117,7 +8117,7 @@ def agent_install(name):@app.route("/api/agent/<name>/install/<job_id>", methods=["GET"])def agent_install_status(name, job_id):"""Poll a background agent CLI install/upgrade job."""- if name not in _ALLOWED_BACKENDS:+ if name not in NATIVE_CLI_BACKENDS:return jsonify({"ok": False, "message": f"Unknown agent: {name}"}), 400from vibe import api@@ -8147,7 +8147,7 @@ async def backend_connection(name: str, starlette_request: FastAPIRequest):@app.route("/api/backend/<name>/runtime")def backend_runtime(name):"""Return lifecycle info (version, update, process status) for a backend."""- if name not in _ALLOWED_BACKENDS:+ if name not in NATIVE_CLI_BACKENDS:return jsonify({"ok": False, "error": f"Unknown backend: {name}"}), 400from vibe import api