Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(agents): make the Avibe Agent the built-in backend, listed first and always on (#2369)

Call Whiteed48b9dde78a
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 18fe6b11e..a0a1a1ae9 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -6,7 +6,6 @@ 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,7 +77,6 @@ class AppCompatConfig:
wechat: Optional[WeChatConfig] = None
codex: Optional[CodexCompatConfig] = None
opencode: Optional[OpenCodeCompatConfig] = None
- avibe: Optional[AvibeAgentConfig] = None
show_duration: bool = False
include_time_info: bool = True
include_user_info: bool = True
@@ -202,7 +200,6 @@ 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.py
index c20241ddf..58753829a 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -176,7 +176,7 @@ MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
-MODEL_HUB_BACKENDS = tuple(sorted(AGENT_BACKENDS, key=lambda name: (name not in NATIVE_CLI_BACKENDS, name)))
+MODEL_HUB_BACKENDS = AGENT_BACKENDS
MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"
_LEGACY_CLAUDE_FAMILY_ALIASES = {
"opus": "opus",
@@ -1146,7 +1146,6 @@ 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
@@ -1604,6 +1603,24 @@ def is_model_hub_enabled(environ: Optional[Mapping[str, str]] = None) -> bool:
return source.get(MODEL_HUB_ENABLED_ENV, "1").strip().lower() in {"1", "true", "yes", "on"}
+HubSupplyBlock = Literal["hub_disabled", "gateway_off"]
+
+
+def hub_supply_block(backend: str, hub: Optional["ModelHubConfig"]) -> Optional[HubSupplyBlock]:
+ """Why the Model Hub leaves ``backend`` no model to run on now, or ``None``: the one owner of that answer.
+
+ A backend without its own CLI gets every model through the Hub, so the operator's
+ Model Hub switch (``VIBE_MODEL_HUB_ENABLED``) leaves it none. Any backend the Hub
+ supplies has none while the user has turned the gateway off in Models.
+ """
+
+ if not is_model_hub_enabled():
+ return None if backend in NATIVE_CLI_BACKENDS else "hub_disabled"
+ if hub is not None and not hub.enabled and hub.agents[backend].mode == "hub":
+ return "gateway_off"
+ return None
+
+
def _validate_optional_datetime(value: object, field_path: str) -> Optional[str]:
if value is None:
return None
@@ -2004,22 +2021,12 @@ 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")
-
-
@dataclass
class AgentsConfig:
default_backend: str = DEFAULT_AGENT_BACKEND
opencode: 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)
@@ -3754,10 +3761,6 @@ 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")
@@ -3765,7 +3768,6 @@ 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(
@@ -3777,7 +3779,6 @@ class V2Config:
opencode=opencode,
claude=claude,
codex=codex,
- avibe=avibe_agent,
avault=avault,
)
@@ -4088,7 +4089,6 @@ 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/core/agent_auth_service.py b/core/agent_auth_service.py
index 5b2603eb7..c285bd2fe 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -17,7 +17,7 @@ from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional
-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS
+from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, is_builtin_backend
from core.backend_failure import terminal_backend_failure_output
from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation
@@ -2393,14 +2393,6 @@ class AgentAuthService:
self.controller.config.opencode = runtime_config
agent_service.register(OpenCodeAgent(self.controller, runtime_config))
- elif backend == "avibe":
- from modules.agents.avibe import AvibeAgent
-
- if not getattr(runtime_config, "enabled", True):
- return False
-
- self.controller.config.avibe = runtime_config
- agent_service.register(AvibeAgent(self.controller))
else:
return False
@@ -2409,29 +2401,17 @@ class AgentAuthService:
logger.info("Registered %s backend after runtime config refresh", backend)
return True
- async def _recover_after_live_registration(self, backend: str) -> None:
- """A backend registered after startup: its recovery owner hands over to the registered adapter.
-
- For ``avibe`` the controller's single ``AvibeRecovery`` retires any pending retry
- (an unregistered adapter's) and runs the next pass on the registered adapter, so
- two adapters never settle the same Session at once.
- """
- recovery = getattr(self.controller, "avibe_recovery", None) if backend == "avibe" else None
- if recovery is None:
- return
- try:
- await recovery.start()
- except Exception:
- logger.exception("Failed to recover %s runtime state after live registration", backend)
-
async def renew_backend_runtime(self, backend: str, config_save: bool = False) -> None:
"""Apply persisted runtime config.
An enabled backend renews in place without waiting for or interrupting
work, so each runtime unit moves at its next turn, and a newly enabled
backend registers at once. Disabling is the one exception: the user
- turned the backend off, so its work stops now.
+ turned the backend off, so its work stops now. A built-in backend has
+ no runtime config and is never disabled, so there is nothing to apply.
"""
+ if is_builtin_backend(backend):
+ return
runtime_config = self._load_backend_runtime_config(backend)
if runtime_config is None:
await self._stop_disabled_backend(backend, unregister=True)
@@ -2444,7 +2424,6 @@ class AgentAuthService:
):
if backend == "opencode":
await self._restore_polls_after_enable()
- await self._recover_after_live_registration(backend)
return
agent_service = getattr(self.controller, "agent_service", None)
agent = getattr(agent_service, "agents", {}).get(backend) if agent_service else None
@@ -2486,7 +2465,6 @@ class AgentAuthService:
backend,
runtime_config,
):
- await self._recover_after_live_registration(backend)
return
if force and backend == "opencode":
agent = getattr(agent_service, "agents", {}).get(backend)
diff --git a/core/backend_restart.py b/core/backend_restart.py
index c6c30653b..8bceb8362 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -13,7 +13,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import AsyncExitStack, asynccontextmanager
from pathlib import Path
from typing import Any, TypeVar
-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS
+from modules.agents.catalog import NATIVE_CLI_BACKENDS
logger = logging.getLogger(__name__)
@@ -775,7 +775,7 @@ class BackendRestartCoordinator:
# or a stale successful outcome to excuse unexpected missing agents.
if isinstance(config, AppCompatConfig):
disabled = (
- backend in AGENT_BACKENDS and backend != "claude"
+ backend in NATIVE_CLI_BACKENDS and backend != "claude"
and getattr(config, backend) is None and not registered
) or (
backend == "claude" and registered and config.claude.enabled is False
diff --git a/core/controller.py b/core/controller.py
index 61b60d568..3723edf52 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -733,6 +733,7 @@ class Controller:
def _init_agents(self):
from core.session_activities import SessionActivityRegistry
+ from modules.agents.avibe import AvibeAgent
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.codex import CodexAgent
from modules.agents.opencode import OpenCodeAgent
@@ -759,14 +760,8 @@ class Controller:
self.agent_service.register(OpenCodeAgent(self, self.config.opencode))
except Exception as e:
logger.error(f"Failed to initialize OpenCode agent: {e}")
- avibe_config = getattr(self.config, "avibe", None)
- if avibe_config is not None and getattr(avibe_config, "enabled", True):
- try:
- from modules.agents.avibe import AvibeAgent
-
- self.agent_service.register(AvibeAgent(self))
- except Exception as e:
- logger.error(f"Failed to initialize Avibe Agent: {e}")
+ # Built in: always registered, never unregistered.
+ self.agent_service.register(AvibeAgent(self))
def _setup_callbacks(self):
"""Setup callback connections between modules"""
@@ -1046,8 +1041,6 @@ class Controller:
async def _recover_avibe_agent_runtime_state(self) -> None:
"""Settle what the previous process left of the Avibe Agent's work (T2, T3 admission, J5).
- Not gated on ``agents.avibe.enabled``: a foreground job the previous process left
- running must be handed to its Watch even when the backend admits no new Turns.
``avibe_recovery`` is the single owner, retrying until every Session has settled.
"""
await self.avibe_recovery.start()
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 442ce5e23..49b2df94f 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -5,7 +5,7 @@ import logging
from typing import Optional
from modules.agents import get_agent_display_name
-from modules.agents.catalog import AGENT_BACKENDS
+from modules.agents.catalog import AGENT_BACKENDS, implicit_default_rank, is_builtin_backend
from modules.im import MessageContext, InlineKeyboard, InlineButton
from core.modals import RoutingModalData, RoutingModalSelection
from vibe import backend_model_catalog
@@ -433,8 +433,11 @@ class SettingsHandler(BaseHandler):
enabled_backends = [backend for backend in all_backends if self._is_backend_enabled(backend)]
if not enabled_backends and current_backend:
enabled_backends = [current_backend]
- registered_backends = sorted(enabled_backends, key=lambda x: (x != "opencode", x))
- active_backend = registered_backends[0] if registered_backends else current_backend
+ # Catalog order, the built-in backend first. As for the default Agent, the fallback
+ # selection is the built-in backend only when no other backend is enabled.
+ catalog_order = {backend: index for index, backend in enumerate(AGENT_BACKENDS)}
+ registered_backends = sorted(enabled_backends, key=lambda x: catalog_order.get(x, len(catalog_order)))
+ active_backend = min(registered_backends, key=implicit_default_rank, default=current_backend)
if current_backend in registered_backends:
active_backend = current_backend
if selected_backend in registered_backends:
@@ -528,6 +531,8 @@ class SettingsHandler(BaseHandler):
)
def _is_backend_enabled(self, backend: str) -> bool:
+ if is_builtin_backend(backend):
+ return True
backend_config = getattr(self.config, backend, None)
if backend_config is None:
return False
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index a33c51226..071532721 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -17,7 +17,7 @@ from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
from config import paths
-from modules.agents.catalog import AGENT_BACKENDS
+from modules.agents.catalog import AGENT_BACKENDS, BUILTIN_AGENT_BACKENDS, implicit_default_rank, is_builtin_backend
from storage.agent_session_rows import reserve_write_lock
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
@@ -47,6 +47,8 @@ DEFAULT_AGENT_NAME = "default"
DEFAULT_AGENT_META_KEY = "default_agent_name"
BUILTIN_DEFAULT_AGENT_METADATA = {"builtin": True, "builtin_default": True, "lock_delete": True}
BUILTIN_BACKEND_ENABLED_META_KEY = "backend_enabled"
+# Catalog-owned: only the store writes them, and only on rows it created (``source == "builtin"``).
+BUILTIN_AGENT_MARKER_KEYS = frozenset((*BUILTIN_DEFAULT_AGENT_METADATA, BUILTIN_BACKEND_ENABLED_META_KEY))
AGENT_ARCHIVE_METADATA_KEY = "_avibe_archive"
ARCHIVED_AGENT_NAME_PREFIX = "_"
LEGACY_ARCHIVED_AGENT_NAME_PREFIX = "_archived_"
@@ -108,6 +110,16 @@ class AgentArchivedEditError(ValueError):
self.agent_name = str(agent_name)
+class AgentAlwaysEnabledError(ValueError):
+ """The built-in Agent of a built-in backend is part of the platform and stays enabled."""
+
+ code = "agent_always_enabled"
+
+ def __init__(self, *, agent_name: str) -> None:
+ super().__init__(self.code)
+ self.agent_name = str(agent_name)
+
+
class AgentReferenceRewriteError(ValueError):
"""A durable Agent reference cannot be rewritten without losing data."""
@@ -532,8 +544,8 @@ def resolve_effective_default_agent(connection, *, enabled_only: bool = True) ->
if not enabled_only:
return None
- row = connection.execute(select(agents).where(agents.c.enabled == 1).order_by(agents.c.name).limit(1)).mappings().first()
- return VibeAgentStore._from_row(row) if row is not None else None
+ rows = connection.execute(select(agents).where(agents.c.enabled == 1).order_by(agents.c.name)).mappings().all()
+ return _implicit_default(VibeAgentStore._from_row(row) for row in rows)
# Default routing surfaces -- the instance-wide default Agent and a project's
@@ -596,8 +608,8 @@ def resolve_usable_default_agent(
)
candidates = [VibeAgentStore._from_row(row) for row in rows]
# Builtins first: they are the shape every install has and the one a caller
- # is most likely to be entitled to.
- candidates.sort(key=lambda item: 0 if item.source == "builtin" else 1)
+ # is most likely to be entitled to. A built-in backend's Agents still come last.
+ candidates.sort(key=lambda item: (implicit_default_rank(item.backend), 0 if item.source == "builtin" else 1))
for candidate in candidates:
if agent is not None and candidate.id == agent.id:
continue
@@ -999,7 +1011,7 @@ class VibeAgentStore:
enabled=bool(enabled),
source=str(source or "user"),
source_ref=_clean_optional(source_ref),
- metadata=dict(metadata or {}),
+ metadata=dict(metadata or {}) if source == "builtin" else _without_builtin_markers(metadata),
created_at=now,
updated_at=now,
)
@@ -1067,8 +1079,15 @@ class VibeAgentStore:
if system_prompt is not _UNSET:
values["system_prompt"] = _clean_optional(system_prompt)
if metadata is not _UNSET:
- values["metadata_json"] = _json_dumps(dict(metadata or {}))
+ # The built-in markers belong to the catalog: a caller neither sets nor clears them.
+ metadata = _without_builtin_markers(metadata)
+ metadata.update(
+ (key, existing.metadata[key]) for key in BUILTIN_AGENT_MARKER_KEYS if key in existing.metadata
+ )
+ values["metadata_json"] = _json_dumps(metadata)
if enabled is not _UNSET:
+ if not enabled and is_always_enabled_agent(existing):
+ raise AgentAlwaysEnabledError(agent_name=existing.name)
values["enabled"] = 1 if bool(enabled) else 0
result = conn.execute(
agents.update()
@@ -1561,7 +1580,7 @@ class VibeAgentStore:
for candidate in candidates:
if candidate.backend == archived.backend:
return candidate
- return candidates[0] if candidates else None
+ return _implicit_default(candidates)
@staticmethod
def _effective_default_agent(conn: Any) -> Optional[VibeAgent]:
@@ -1587,14 +1606,13 @@ class VibeAgentStore:
if fallback is not None:
return VibeAgentStore._from_row(fallback)
- first_enabled = conn.execute(
+ enabled = conn.execute(
select(agents)
.where(agents.c.enabled == 1)
.where(agents.c.archived_at.is_(None))
.order_by(agents.c.name)
- .limit(1)
- ).mappings().first()
- return VibeAgentStore._from_row(first_enabled) if first_enabled is not None else None
+ ).mappings()
+ return _implicit_default(VibeAgentStore._from_row(row) for row in enabled)
def import_candidates(
self,
@@ -1647,9 +1665,15 @@ class VibeAgentStore:
def ensure_builtin_default_agent(self, *, backend: str, name: str | None = None) -> VibeAgent:
backend = validate_agent_backend(backend)
- agent_name = str(name or backend).strip()
- metadata = dict(BUILTIN_DEFAULT_AGENT_METADATA)
- metadata["backend"] = backend
+ metadata = {**BUILTIN_DEFAULT_AGENT_METADATA, "backend": backend}
+ if name is None:
+ current = self.get_builtin_default_agent_for_backend(backend, enabled_only=False)
+ if current is not None:
+ return self._write_builtin_state(current, metadata={**current.metadata, **metadata})
+ # An always-enabled backend needs its own row: when another Agent holds the
+ # backend's name, the built-in takes the next free one.
+ name = self._free_agent_name(backend) if is_builtin_backend(backend) else backend
+ agent_name = str(name).strip()
existing = self.get(agent_name)
if existing:
if existing.backend != backend:
@@ -1657,16 +1681,10 @@ class VibeAgentStore:
f"agent '{agent_name}' already exists with backend '{existing.backend}', "
f"cannot use it as the built-in default for '{backend}'"
)
- if not is_builtin_default_agent(existing):
+ if existing.source != "builtin":
+ # A user's Agent keeps its own identity.
return existing
- merged = {**existing.metadata, **metadata}
- if existing.source != "builtin" or existing.metadata != merged:
- return self.update(
- existing.name,
- metadata=merged,
- user_context=instance_owner_context(),
- )
- return existing
+ return self._write_builtin_state(existing, metadata={**existing.metadata, **metadata})
return self.create(
name=agent_name,
backend=backend,
@@ -1676,30 +1694,44 @@ class VibeAgentStore:
enabled=True,
)
+ def _free_agent_name(self, name: str) -> str:
+ candidate, suffix = name, 1
+ while self.get(candidate) is not None:
+ suffix += 1
+ candidate = f"{name}-{suffix}"
+ return candidate
+
+ def _write_builtin_state(self, agent: VibeAgent, *, metadata: Any = _UNSET, enabled: Any = _UNSET) -> VibeAgent:
+ """The catalog's own write to a built-in row: its markers and enabled state."""
+ values: dict[str, Any] = {}
+ if metadata is not _UNSET and metadata != agent.metadata:
+ values["metadata_json"] = _json_dumps(metadata)
+ if enabled is not _UNSET and bool(enabled) != agent.enabled:
+ values["enabled"] = 1 if enabled else 0
+ if not values:
+ return agent
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ conn.execute(
+ agents.update().where(agents.c.id == agent.id).values(updated_at=_utc_now_iso(), **values)
+ )
+ row = conn.execute(select(agents).where(agents.c.id == agent.id).limit(1)).mappings().one()
+ return self._from_row(row)
+
def sync_builtin_default_agent(self, *, backend: str, backend_enabled: bool, name: str | None = None) -> VibeAgent:
backend = validate_agent_backend(backend)
agent = self.ensure_builtin_default_agent(backend=backend, name=name)
if not is_builtin_default_agent(agent):
return agent
+ always_enabled = is_always_enabled_agent(agent)
+ backend_enabled = bool(backend_enabled) or always_enabled
previous_backend_enabled = agent.metadata.get(BUILTIN_BACKEND_ENABLED_META_KEY)
- metadata = {**agent.metadata, BUILTIN_BACKEND_ENABLED_META_KEY: bool(backend_enabled)}
- should_enable = bool(backend_enabled) and previous_backend_enabled is not True
- should_disable = not bool(backend_enabled) and agent.enabled
- updates: dict[str, Any] = {}
- if metadata != agent.metadata:
- updates["metadata"] = metadata
- if should_enable:
- updates["enabled"] = True
- elif should_disable:
- updates["enabled"] = False
- if updates:
- return self.update(
- agent.name,
- user_context=instance_owner_context(),
- **updates,
- )
- return agent
+ metadata = {**agent.metadata, BUILTIN_BACKEND_ENABLED_META_KEY: backend_enabled}
+ should_enable = (backend_enabled and previous_backend_enabled is not True) or (always_enabled and not agent.enabled)
+ should_disable = not backend_enabled and agent.enabled
+ enabled: Any = True if should_enable else False if should_disable else _UNSET
+ return self._write_builtin_state(agent, metadata=metadata, enabled=enabled)
def ensure_builtin_default_agents(
self,
@@ -1707,7 +1739,8 @@ class VibeAgentStore:
) -> list[VibeAgent]:
ensured: list[VibeAgent] = []
enabled_backends: list[str] = []
- for backend in backends:
+ # A built-in backend is always enabled, whatever the caller read from config.
+ for backend in (*backends, *BUILTIN_AGENT_BACKENDS):
normalized_backend = validate_agent_backend(backend)
if normalized_backend not in enabled_backends:
enabled_backends.append(normalized_backend)
@@ -1731,29 +1764,40 @@ class VibeAgentStore:
enabled_ensured = [agent for agent in ensured if agent.enabled]
if (default_agent is None or not default_agent.enabled) and enabled_ensured:
self.set_default_agent_name(
- enabled_ensured[0].name,
+ _implicit_default(enabled_ensured).name,
user_context=instance_owner_context(),
)
return ensured
def get_builtin_default_agent_for_backend(self, backend: str, *, enabled_only: bool = True) -> Optional[VibeAgent]:
+ """The backend's built-in Agent: the one owner of built-in identity.
+
+ It is a row the store created for the backend (``source == "builtin"``, which no
+ caller can write), under any name; its markers are only a projection the sync
+ keeps current. A marked row wins over one an earlier build left without
+ markers, then the oldest. The legacy instance default, also store-made, is a
+ backend's built-in only if marked. ``enabled_only`` reports a disabled one as
+ missing.
+ """
backend = validate_agent_backend(backend)
- for candidate in (backend, DEFAULT_AGENT_NAME):
- agent = self.get(candidate)
- if (
- agent
- and agent.backend == backend
- and is_builtin_default_agent(agent)
- and (agent.enabled or not enabled_only)
- ):
- return agent
with self.engine.connect() as conn:
- rows = conn.execute(select(agents).where(agents.c.backend == backend).order_by(agents.c.name)).mappings()
- for row in rows:
- agent = self._from_row(row)
- if is_builtin_default_agent(agent) and (agent.enabled or not enabled_only):
- return agent
- return None
+ rows = conn.execute(
+ select(agents)
+ .where(agents.c.backend == backend, agents.c.source == "builtin", agents.c.archived_at.is_(None))
+ .order_by(agents.c.created_at, agents.c.id)
+ ).mappings().all()
+ built_in = min(
+ (
+ agent
+ for agent in map(self._from_row, rows)
+ if _has_builtin_markers(agent) or agent.normalized_name != DEFAULT_AGENT_NAME
+ ),
+ key=lambda agent: not _has_builtin_markers(agent),
+ default=None,
+ )
+ if built_in is None or (enabled_only and not built_in.enabled):
+ return None
+ return built_in
def get_default_agent_name(self) -> Optional[str]:
with self.engine.connect() as conn:
@@ -1873,10 +1917,29 @@ def parse_agent_file(path: Path, *, backend: str) -> AgentImportCandidate:
)
-def is_builtin_default_agent(agent: VibeAgent) -> bool:
+def _has_builtin_markers(agent: VibeAgent) -> bool:
return bool(agent.metadata.get("builtin_default") or agent.metadata.get("lock_delete"))
+def _without_builtin_markers(metadata: Any) -> dict[str, Any]:
+ return {key: value for key, value in dict(metadata or {}).items() if key not in BUILTIN_AGENT_MARKER_KEYS}
+
+
+def is_builtin_default_agent(agent: VibeAgent) -> bool:
+ """A backend's built-in Agent: store-made (``source == "builtin"``) and marked by the catalog."""
+ return agent.source == "builtin" and _has_builtin_markers(agent)
+
+
+def is_always_enabled_agent(agent: VibeAgent) -> bool:
+ """The built-in Agent of a built-in backend: model, prompt and effort stay editable, ``enabled`` does not."""
+ return is_builtin_default_agent(agent) and is_builtin_backend(agent.backend)
+
+
+def _implicit_default(candidates: Iterable[VibeAgent]) -> Optional[VibeAgent]:
+ """The first candidate by ``implicit_default_rank``, keeping the given order among equals."""
+ return min(candidates, key=lambda agent: implicit_default_rank(agent.backend), default=None)
+
+
def iter_global_agent_files(source: str) -> list[tuple[Path, str]]:
source_key = str(source or "").strip().lower()
home = Path.home()
diff --git a/docs/plans/agent-core-contracts/backend-registration.md b/docs/plans/agent-core-contracts/backend-registration.md
index c11921a86..359c19d2d 100644
--- a/docs/plans/agent-core-contracts/backend-registration.md
+++ b/docs/plans/agent-core-contracts/backend-registration.md
@@ -13,6 +13,12 @@ and they mean two different things. This contract makes the difference explicit.
`avibe` has no CLI, CLI auth, native session store, or native fork. It must never be added to a native-CLI list, and
it must be added to every agent-backend list.
+`avibe` is also the one **built-in** backend (`AgentBackendDescriptor.builtin`, owner decision 2026-10-06): part of the
+platform, so it is always enabled. It has no `agents.avibe` config section and no enable switch, the controller
+registers it at startup and never unregisters it, and its built-in Agent cannot be disabled. Registry order is display
+order, and the built-in backend comes first. Being listed first does not make it the default: any fallback that picks
+a backend or Agent nobody chose ranks it last ([`avibe-agent-always-on.md`](../avibe-agent-always-on.md)).
+
## 2. One declaration
`modules/agents/catalog.py` declares both sets. Every other list imports them; literals of backend names are removed.
diff --git a/docs/plans/avibe-agent-always-on.md b/docs/plans/avibe-agent-always-on.md
new file mode 100644
index 000000000..7ce63a23c
--- /dev/null
+++ b/docs/plans/avibe-agent-always-on.md
@@ -0,0 +1,61 @@
+# Avibe Agent is the built-in backend
+
+## Owner decision (2026-10-06)
+
+The Avibe Agent is Avibe's own agent and takes part in the platform's core operation. It is listed first in every
+backend list, it is always enabled, and it cannot be turned off.
+
+## Change contract
+
+- **One descriptor fact.** `AgentBackendDescriptor.builtin` marks the built-in backend (`avibe`).
+ `BUILTIN_AGENT_BACKENDS` and `is_builtin_backend()` derive from it; the generated UI catalog projects it as
+ `builtin`. No consumer special-cases the id.
+- **Order.** `AGENT_BACKEND_REGISTRY` lists `avibe` first, and registry order is the one display order:
+ Settings → Backends, the Models page routes (`MODEL_HUB_BACKENDS` is now the registry order, whose ordering had no
+ processing meaning), the Agent create picker, the Agents page groups and filter, the Global prompts tabs (the UI's
+ `BACKEND_ORDER`, derived from the catalog; the separate `agentOrder` is gone), and IM routing pickers. Native
+ backends therefore read OpenCode, Claude Code, Codex everywhere a backend list is shown.
+- **Not the default.** `DEFAULT_AGENT_BACKEND` stays `opencode`. `implicit_default_rank` (`modules/agents/catalog.py`) is the
+ one rule for a backend or Agent nobody chose: the built-in backend comes last, so it is chosen only when nothing else
+ is enabled. Every implicit pick goes through it: the built-in sync's default, the effective-default fallbacks
+ (`resolve_effective_default_agent`, `_effective_default_agent`), the per-principal fallback
+ (`resolve_usable_default_agent`), the archived default's replacement after its same-backend preference, and the
+ IM routing modal's fallback selection.
+- **Always on, by construction.** `agents.avibe` no longer exists: `AvibeAgentConfig`, its compat projection and every
+ branch reading it are removed. A config written by an earlier build loads unchanged otherwise and drops the key on
+ its next save. The controller registers the adapter at startup and never unregisters it; runtime renewal is a no-op
+ for it.
+- **Built-in Agent.** `get_builtin_default_agent_for_backend` is the one owner of built-in identity: the row the store
+ created for the backend (`source == "builtin"`, which no caller can write), under any name. A marked row wins, then
+ the oldest; the legacy instance default (`default`) counts only if marked. The built-in markers (`builtin`,
+ `builtin_default`, `lock_delete`, `backend_enabled`) are a projection only the store writes: `create` and `update`
+ drop them from caller metadata and keep the row's own. `ensure_builtin_default_agents` always includes the built-in
+ backend, restores the markers of whatever row the lookup names and re-enables it, so the row exists and is enabled
+ when controller startup's sync returns (Model Hub seeds the Avibe supply onto it next). Without such a row it is
+ created at `avibe`, or at the next free name (`avibe-2`) when a user's Agent holds `avibe`. `VibeAgentStore.update`
+ refuses to disable it (`agent_always_enabled`); its model, effort, prompt and description stay editable.
+- **Refusals.** `POST /api/config` with `agents.avibe` returns 400 (`errors.builtinBackendConfig`, in the configured
+ language); `PATCH /api/agents/avibe` with `enabled: false` returns 400 `agent_always_enabled`; the CLI reports the
+ same code.
+- **UI.** The built-in backend shows a "Built-in" badge where other backends have their enable switch, in the list and
+ on its page. The built-in Avibe Agent's enable switch is locked on.
+- **Model Hub cannot supply.** `hub_supply_block(backend, hub_config)` (`config/v2_config.py`) is the one owner of why
+ the Model Hub leaves a backend no model to run on now. The shared model gate and the adapter's preflight render its
+ copy (`hub_supply_refusal`), `get_backend_connection` reports such a backend unready, and `GET /api/config` carries
+ it as `agent_supply_blocks`, which the Backends pages show. The backend stays listed and enabled in both cases.
+ - Gateway off (Models → Start/Stop): its row says "Gateway off", its page links to Models, and a Turn refuses with
+ `errors.modelGatewayOff`.
+ - Model Hub disabled on the instance (`VIBE_MODEL_HUB_ENABLED=0`): a backend without its own CLI gets every model
+ through the Hub, so its row says "Model Hub disabled", its page says so without a Models link, and a Turn refuses
+ with `errors.modelHubDisabled`.
+
+## Known by design
+
+- The setup wizard lists only native CLIs here. Its Avibe Agent card (built-in, model picker, providers destination)
+ is a follow-up owner decision, delivered separately as `feat/avibe-agent-setup-wizard`.
+- The setup wizard keeps its own native setup sequence (Claude Code, Codex, OpenCode: `nativeOrder`). It is an
+ ordered onboarding flow, not a backend list: its intro geometry is indexed and its first ready backend decides the
+ default Agent after setup, which this lane leaves unchanged.
+- The Agents page detail panel mirrors `is_builtin_default_agent` from the Agent's `source` and markers;
+ `setupTargets.isBuiltinAgent` reads the markers, which callers can no longer write.
+- Making the Avibe Agent the default for new chats is a separate owner decision.
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index bcfe9da01..777eaccd3 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -42,8 +42,9 @@ sits below the product boundary Avibe must own: loop semantics, persistence, and
- The tension system itself. v1 guarantees only the seams it will need: steer, follow-up, hooks, events.
- Any terminal UI, and any new Web UI beyond registering the backend where backends already appear.
-- Becoming the default agent for new installs. v1 is opt-in; the default is decided after the P4 regression with real
- usage evidence.
+- Becoming the default agent for new installs. v1 is the built-in backend, always enabled and listed first
+ ([`avibe-agent-always-on.md`](avibe-agent-always-on.md)), but not the default for new chats; that default is decided
+ after the P4 regression with real usage evidence.
- Hosting MCP servers (Avibe is an MCP client only). Sandboxing beyond Avibe's existing cwd policy.
- Failover and credentials inside the agent; they stay in Model Hub.
- Interactive terminal programs (planned, §5.4).
diff --git a/docs/plans/avibe-agent-registration.md b/docs/plans/avibe-agent-registration.md
index 1b4db4d46..54aab6b99 100644
--- a/docs/plans/avibe-agent-registration.md
+++ b/docs/plans/avibe-agent-registration.md
@@ -1,5 +1,9 @@
# Avibe Agent registration (C-8)
+> Superseded in part by [`avibe-agent-always-on.md`](avibe-agent-always-on.md): the Avibe Agent is the built-in
+> backend, always enabled, and `agents.avibe` no longer exists. The opt-in and disabled-state statements below are
+> this lane's history.
+
## Change contract
Avibe Agent is an opt-in, in-process backend. The backend catalog declares the
diff --git a/modules/agents/avibe/agent.py b/modules/agents/avibe/agent.py
index 3ef67b962..946ac1530 100644
--- a/modules/agents/avibe/agent.py
+++ b/modules/agents/avibe/agent.py
@@ -432,18 +432,6 @@ class AvibeAgent(BaseAgent):
).scalars()
return any((moment := instant(value)) is not None and moment >= created for value in committed)
- async def shutdown_runtime(self, settle_reason: Optional[str] = None) -> None:
- """Disabling the backend ends its runs now.
-
- The core settles their Turns and Activities with ``settle_reason``. The
- runs live in this process, so ending them is all this adapter stops.
- """
- for runtime in list(self._runtimes.values()):
- if runtime.run is not None:
- runtime.run.stop_requested = True
- if runtime.run.agent is not None:
- runtime.run.agent.abort("backend disabled")
-
async def prepare_resume_binding(self, *, base_session_id: str, session_key: str, working_path: str) -> None:
"""Nothing to prepare: the transcript is the Session's own rows, read at the next run."""
return None
@@ -1190,13 +1178,19 @@ class AvibeAgent(BaseAgent):
)
async def _fail_preflight(self, request: AgentRequest, error: BaseException) -> None:
- from modules.agents.model_hub import launch_refusal_copy
+ from modules.agents.model_hub import hub_supply_refusal, launch_refusal_copy
logger.warning("Avibe Agent could not resolve its model route: %s", error)
- refusal = launch_refusal_copy(self.controller, error)
+ language = self._language()
+ # Every route runs through the Model Hub: when it is disabled or its gateway is off, that explains the failure.
+ refusal = (
+ await asyncio.to_thread(hub_supply_refusal, self.controller, BACKEND, language)
+ or launch_refusal_copy(self.controller, error)
+ or error_text("generic", language)
+ )
# Recorded on every start failure, as the other backends do: a no-op unless a launch is bound.
await self.record_model_hub_native_failure(request.context, str(error))
- display = f"❌ {refusal}" if refusal is not None else f"❌ {error_text('generic', self._language())}"
+ display = f"❌ {refusal}"
await emit_backend_failure(
self.controller,
request.context,
diff --git a/modules/agents/avibe/recovery.py b/modules/agents/avibe/recovery.py
index a1822c76c..eeca21c91 100644
--- a/modules/agents/avibe/recovery.py
+++ b/modules/agents/avibe/recovery.py
@@ -2,15 +2,10 @@
Settlement outside a Turn is T2 (open tool calls), T3 admission (accepted inputs
no run consumed), and J5 (pruning settled jobs). The controller holds one
-``AvibeRecovery`` and so at most one recovery task: two adapters settling the
-same Session would each take their own locks and could both append a
-``tool_result``.
-
-A pass runs on the registered adapter, or, while ``agents.avibe`` is disabled,
-on one unregistered adapter it keeps for as long as it needs one: recovery
-needs only the transcript store, the job host, and the Watch hand-over. Every
-pass re-derives its candidates from the rows, so the unsettled set carries over
-to whichever adapter runs the next pass.
+``AvibeRecovery`` and so at most one recovery task, whose passes run on the
+adapter the controller registered at startup. Every pass re-derives its
+candidates from the rows, so a retry picks up whatever the last pass left
+unsettled.
"""
from __future__ import annotations
@@ -32,9 +27,8 @@ class AvibeRecovery:
def __init__(self, controller: Any) -> None:
self._controller = controller
self._task: Optional[asyncio.Task] = None
- self._transient: Any = None
# Serializes every pass, immediate or retried, and the scheduling around it, so
- # two passes never run at once (a start racing a registration, or a retry).
+ # two passes never run at once (a start racing a retry).
self._lock = asyncio.Lock()
@property
@@ -45,10 +39,10 @@ class AvibeRecovery:
async def start(self) -> list[str]:
"""Retire any pending retry, run one pass now, and keep retrying while Sessions stay unsettled.
- The entry point for startup and for live registration of the backend. Under
- the lock a pending retry is only ever sleeping or waiting for the lock, never
- mid-pass, so it is retired without interrupting a write and there are never
- two passes at once. Returns the Sessions this pass left unsettled.
+ The entry point at startup. Under the lock a pending retry is only ever
+ sleeping or waiting for the lock, never mid-pass, so it is retired without
+ interrupting a write and there are never two passes at once. Returns the
+ Sessions this pass left unsettled.
"""
async with self._lock:
await self.stop()
@@ -63,7 +57,7 @@ class AvibeRecovery:
self._task = asyncio.create_task(self._retry(), name="avibe-agent-recovery")
async def stop(self) -> None:
- """Stop retrying (service stop, or a new owner taking over); the next start recovers again."""
+ """Stop retrying (service stop); the next start recovers again."""
task, self._task = self._task, None
if task is not None and not task.done():
task.cancel()
@@ -83,23 +77,8 @@ class AvibeRecovery:
logger.error("Avibe Agent recovery could not settle Sessions %s; retrying", ", ".join(unsettled))
async def _pass(self) -> list[str]:
- agent = self._agent()
try:
- unsettled = await agent.recover_runtime_state()
+ return await self._controller.agent_service.agents["avibe"].recover_runtime_state()
except Exception:
logger.exception("Avibe Agent recovery pass failed")
return ["*"]
- if not unsettled:
- self._transient = None
- return unsettled
-
- def _agent(self) -> Any:
- registered = getattr(getattr(self._controller, "agent_service", None), "agents", {}).get("avibe")
- if registered is not None:
- self._transient = None
- return registered
- if self._transient is None:
- from modules.agents.avibe.agent import AvibeAgent
-
- self._transient = AvibeAgent(self._controller)
- return self._transient
diff --git a/modules/agents/catalog.py b/modules/agents/catalog.py
index c1b96df23..b8d021733 100644
--- a/modules/agents/catalog.py
+++ b/modules/agents/catalog.py
@@ -27,6 +27,8 @@ class AgentBackendDescriptor:
default_enabled: bool
latest_probe: tuple[str, str] | None
capabilities: AgentBackendCapabilities
+ # Part of the platform itself: always enabled, with no switch and no configuration section.
+ builtin: bool = False
@property
def description_key(self) -> str:
@@ -43,7 +45,24 @@ class AgentBackendDescriptor:
return payload
+# Registry order is the order every backend list shows: the built-in Avibe Agent first.
AGENT_BACKEND_REGISTRY: Final[dict[str, AgentBackendDescriptor]] = {
+ "avibe": AgentBackendDescriptor(
+ id="avibe",
+ display_name="Avibe Agent",
+ config_key="avibe",
+ default_cli=None,
+ default_enabled=True,
+ latest_probe=None,
+ capabilities=AgentBackendCapabilities(
+ supports_cli=False,
+ supports_native_sessions=False,
+ supports_runtime_refresh=False,
+ supports_web_oauth=False,
+ supports_install=False,
+ ),
+ builtin=True,
+ ),
"opencode": AgentBackendDescriptor(
id="opencode",
display_name="OpenCode",
@@ -71,21 +90,6 @@ 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)
@@ -94,6 +98,9 @@ NATIVE_CLI_BACKENDS: Final[tuple[str, ...]] = tuple(
for descriptor in AGENT_BACKEND_REGISTRY.values()
if descriptor.capabilities.supports_cli
)
+BUILTIN_AGENT_BACKENDS: Final[tuple[str, ...]] = tuple(
+ descriptor.id for descriptor in AGENT_BACKEND_REGISTRY.values() if descriptor.builtin
+)
DEFAULT_AGENT_BACKEND: Final[str] = "opencode"
RUNTIME_REFRESH_BACKENDS: Final[frozenset[str]] = frozenset(
descriptor.id
@@ -144,6 +151,20 @@ def default_enabled_for_backend(name: str) -> bool:
return get_agent_backend_descriptor(name).default_enabled
+def is_builtin_backend(name: str) -> bool:
+ """Return whether *name* is a built-in backend, which is always enabled."""
+ return name in BUILTIN_AGENT_BACKENDS
+
+
+def implicit_default_rank(name: str) -> int:
+ """The one rule for a default nobody chose, among backends or their Agents: a built-in backend comes last.
+
+ Making the Avibe Agent the default for new chats is its own decision, so no fallback
+ picks it while another candidate exists.
+ """
+ return 1 if is_builtin_backend(name) else 0
+
+
def display_name_for_backend(name: str) -> str:
"""Return the user-facing display name for *name*."""
if name in AGENT_BACKEND_REGISTRY:
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index a932dd0dc..8f75014f5 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -52,7 +52,9 @@ from core.handlers.model_hub.service import (
from core.services.settings import load_config_or_default
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from core.native_dispatch_phase import mark_prewrite_recovery_required
+from modules.agents.catalog import display_name_for_backend
from vibe.codex_config import format_toml_basic_string
+from vibe.i18n import t
from vibe.opencode_config import managed_opencode_runtime_config_content
@@ -358,6 +360,21 @@ def launch_refusal_copy(controller: Any, error: BaseException) -> str | None:
return render_turn_outcome_copy(outcome, _language(controller))
+_HUB_SUPPLY_REFUSALS = {"hub_disabled": "errors.modelHubDisabled", "gateway_off": "errors.modelGatewayOff"}
+
+
+def hub_supply_refusal(controller: Any, backend: str, language: str) -> str | None:
+ """The copy a turn shows when ``hub_supply_block`` names why ``backend`` has no model, else ``None``."""
+
+ from config.v2_config import hub_supply_block
+
+ store = getattr(getattr(controller, "model_hub_service", None), "store", None)
+ block = hub_supply_block(backend, store.load() if store is not None else None)
+ if block is None:
+ return None
+ return t(_HUB_SUPPLY_REFUSALS[block], language, backend=display_name_for_backend(backend))
+
+
def _hold_unrunnable_input(context: Any, error: ModelHubError) -> None:
"""Keep an input whose model the backend does not list for an explicit retry.
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 4e0d298f0..abe91ba16 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -480,11 +480,16 @@ class AgentService:
if agent.name in AGENT_BACKENDS:
has_subagent_model = request.subagent_model is not None
- selected_model = require_agent_model(
- request.subagent_model if has_subagent_model else request.vibe_agent_model,
- agent.name,
- getattr(getattr(self.controller, "config", None), "language", "en"),
- )
+ requested_model = request.subagent_model if has_subagent_model else request.vibe_agent_model
+ language = getattr(getattr(self.controller, "config", None), "language", "en")
+ if not str(requested_model or "").strip():
+ from modules.agents.model_hub import hub_supply_refusal
+
+ # When the Model Hub is why there is no model to select, say so, not "select a model".
+ refusal = await asyncio.to_thread(hub_supply_refusal, self.controller, agent.name, language)
+ if refusal is not None:
+ raise ValueError(refusal)
+ selected_model = require_agent_model(requested_model, agent.name, language)
if has_subagent_model:
request.subagent_model = selected_model
else:
diff --git a/scripts/incus_tenant.py b/scripts/incus_tenant.py
index 64e3a3530..9dd9d78b5 100755
--- a/scripts/incus_tenant.py
+++ b/scripts/incus_tenant.py
@@ -218,7 +218,6 @@ 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},
diff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.py
index 40d2eb1db..48f34dd53 100755
--- a/scripts/prepare_regression.py
+++ b/scripts/prepare_regression.py
@@ -212,9 +212,6 @@ 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/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 8e85167b5..c7735bda4 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -608,7 +608,8 @@ def test_mh_supply_gap_001_manual_target_survives_inventory_loss(
result = asyncio.run(service.refresh_source(supplied.id))
assert result["removed_hops"] == []
- model_supply = next(row for row in service.list_agents()[0]["model_supply"] if row["model_id"] == menu_model)
+ claude = next(agent for agent in service.list_agents() if agent["backend"] == "claude")
+ model_supply = next(row for row in claude["model_supply"] if row["model_id"] == menu_model)
assert model_supply["chain_length"] == 1
chain = service.agent_chain("claude", menu_model)
assert chain["route_origin"] == "manual"
diff --git a/tests/test_agent_backend_catalog.py b/tests/test_agent_backend_catalog.py
index a16168942..d13fdef8c 100644
--- a/tests/test_agent_backend_catalog.py
+++ b/tests/test_agent_backend_catalog.py
@@ -9,6 +9,7 @@ from modules.agents.catalog import (
default_enabled_for_backend,
display_name_for_backend,
is_agent_backend,
+ is_builtin_backend,
latest_probe_for_backend,
supports_install,
supports_runtime_refresh,
@@ -18,7 +19,8 @@ from vibe import api
def test_agent_catalog_is_backend_management_source_of_truth() -> None:
- assert AGENT_BACKENDS == ("opencode", "claude", "codex", "avibe")
+ # The built-in Avibe Agent leads every backend list; the default backend is unchanged.
+ assert AGENT_BACKENDS == ("avibe", "opencode", "claude", "codex")
assert DEFAULT_AGENT_BACKEND == "opencode"
for backend in NATIVE_CLI_BACKENDS:
@@ -28,13 +30,15 @@ def test_agent_catalog_is_backend_management_source_of_truth() -> None:
assert supports_install(backend)
assert default_cli_for_backend(backend)
assert latest_probe_for_backend(backend) is not None
+ assert not is_builtin_backend(backend)
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 is_builtin_backend("avibe")
+ assert 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")
@@ -50,8 +54,9 @@ def test_agent_backend_catalog_payload_exposes_public_metadata() -> None:
payload = agent_backend_catalog_payload()
assert [item["id"] for item in payload] == list(AGENT_BACKENDS)
- assert payload[0]["settings_route"] == "/settings/backends/opencode"
- assert payload[0]["capabilities"]["supports_runtime_refresh"] is True
+ assert [item["builtin"] for item in payload] == [True, False, False, False]
+ assert payload[1]["settings_route"] == "/settings/backends/opencode"
+ assert payload[1]["capabilities"]["supports_runtime_refresh"] is True
def test_api_exposes_agent_backend_catalog() -> None:
diff --git a/tests/test_agent_organization_onboarding.py b/tests/test_agent_organization_onboarding.py
index b2cf801ad..228c4c462 100644
--- a/tests/test_agent_organization_onboarding.py
+++ b/tests/test_agent_organization_onboarding.py
@@ -79,29 +79,30 @@ def test_upgrade_onboarding_inventories_custom_and_system_agents_as_private(monk
backend="codex",
system_prompt="legacy prompt",
)
+ # Every install also has the built-in Avibe Agent.
builtins = store.ensure_builtin_default_agents(["codex", "claude"])
before = store.organization_onboarding_inventory(user_context=_organization_context())
assert before["counts"] == {
- "total": 3,
- "system": 2,
+ "total": 4,
+ "system": 3,
"custom": 1,
- "not_onboarded": 3,
+ "not_onboarded": 4,
"private": 0,
"published": 0,
"conflicts": 0,
}
result = store.onboard_organization_agents(user_context=_organization_context())
- assert result["created"] == 3
- assert result["counts"]["private"] == 3
+ assert result["created"] == 4
+ assert result["counts"]["private"] == 4
with store.engine.connect() as connection:
policies = resource_access_service.list_resource_policies(
resource_kind="agent",
organization_id="org-1",
connection=connection,
)
- assert len(policies) == 3
+ assert len(policies) == 4
assert all(policy["access_level"] == "private" for policy in policies)
assert all(policy["group_ids"] == [] for policy in policies)
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 483103df5..848de781d 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -366,6 +366,42 @@ def test_model_selection_is_required_before_any_backend_dispatch(backend, model,
asyncio.run(run())
+ ("backend", "hub_switch", "gateway_enabled", "refusal"),
+ [
+ ("avibe", "1", False, "The model gateway is off, so Avibe Agent has no model to run on"),
+ ("avibe", "1", True, "Select a model"),
+ ("avibe", "0", True, "Model Hub is disabled on this instance, so Avibe Agent has no model to run on"),
+ # A native backend runs direct without the Hub: choosing a model is still the fix.
+ ("codex", "0", True, "Select a model"),
+ ],
+)
+def test_a_missing_model_the_model_hub_explains_names_the_model_hub(
+ monkeypatch, backend, hub_switch, gateway_enabled, refusal
+):
+ """The Avibe Agent's models come only through the Model Hub: while it cannot supply any, choosing a model is not the fix."""
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", hub_switch)
+
+ async def run():
+ controller = _Controller()
+ hub = SimpleNamespace(enabled=gateway_enabled, agents={backend: SimpleNamespace(mode="hub")})
+ controller.model_hub_service = SimpleNamespace(store=SimpleNamespace(load=lambda: hub))
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ agent = _RuntimeAgent()
+ agent.name = backend
+ service.register(agent)
+ request = _request("hello")
+ request.vibe_agent_model = None
+ request.failure_handler = AsyncMock(return_value=True)
+
+ with pytest.raises(ValueError, match=refusal):
+ await service.handle_message(backend, request)
+ assert agent.started == []
+
+ asyncio.run(run())
+
+
def test_agent_service_dispatches_runtime_config_refresh() -> None:
service = AgentService(controller=SimpleNamespace())
runtime_config = object()
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 8ca067afd..125848d16 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -15,7 +15,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
-from modules.agents.catalog import AGENT_BACKENDS
+from modules.agents.catalog import BUILTIN_AGENT_BACKENDS, NATIVE_CLI_BACKENDS
from config.v2_config import (
_FIELD_SCOPED_RECOVERY_SECTIONS,
AudioAsrConfig,
@@ -142,10 +142,11 @@ def test_config_save_initializes_real_state_with_or_without_schema_preparation(
assert connection.execute("PRAGMA integrity_check").fetchone() == ("ok",)
store = api.VibeAgentStore()
try:
+ # The configured backends, plus the built-in one, which has no config section.
enabled = {
backend for backend, options in _full_config_payload()["agents"].items()
if isinstance(options, dict) and options.get("enabled")
- }
+ } | set(BUILTIN_AGENT_BACKENDS)
assert {agent.backend for agent in store.list_agents() if agent.enabled} == enabled
assert store.get_default_agent_name() in {agent.name for agent in store.list_agents()}
finally:
@@ -167,7 +168,7 @@ def test_save_config_merges_partial_payload(monkeypatch, tmp_path, sqlite_schema
assert original.update.auto_update is False
assert all(
not hasattr(getattr(original.agents, backend), "default_model")
- for backend in AGENT_BACKENDS
+ for backend in NATIVE_CLI_BACKENDS
)
updated = api.save_config({"show_duration": False, "include_time_info": False, "update": {"auto_update": True}})
@@ -1274,7 +1275,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 = set(AGENT_BACKENDS) | {"avault"}
+ agents = set(NATIVE_CLI_BACKENDS) | {"avault"} # The built-in backend has no config section.
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_agent.py b/tests/test_avibe_agent.py
index c1fcd48dc..834712224 100644
--- a/tests/test_avibe_agent.py
+++ b/tests/test_avibe_agent.py
@@ -1318,20 +1318,33 @@ async def test_a_failure_while_settling_reaches_the_shared_owner(engine, session
await harness.agent.handle_message(harness.request("hello"))
-async def test_a_refused_model_route_fails_before_the_input_is_written(engine, session, tmp_path, published) -> None:
[email protected](("hub_switch", "gateway_enabled"), [("1", True), ("1", False), ("0", True)])
+async def test_a_refused_model_route_fails_before_the_input_is_written(
+ engine, session, tmp_path, published, monkeypatch, hub_switch, gateway_enabled
+) -> None:
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", hub_switch)
harness = _Harness(engine, tmp_path, "telegram", [])
async def refuse(*_args, **_kwargs):
raise RuntimeError("no source serves this model")
harness.controller.model_hub_runtime = SimpleNamespace(resolve=refuse)
+ hub = SimpleNamespace(enabled=gateway_enabled, agents={"avibe": SimpleNamespace(mode="hub")})
+ harness.controller.model_hub_service = SimpleNamespace(store=SimpleNamespace(load=lambda: hub))
request = harness.request("hello")
await harness.agent.handle_message(request)
assert harness.controller.started == []
assert await harness.context_rows() == []
assert harness.provider.requests == []
- assert harness.controller.im_client.sent == [f"❌ {i18n_t('avibeAgent.error.generic', 'en')}"]
+ # Every route runs through the Model Hub: disabled, or its gateway off, the copy names that cause.
+ if hub_switch == "0":
+ expected = i18n_t("errors.modelHubDisabled", "en", backend="Avibe Agent")
+ elif not gateway_enabled:
+ expected = i18n_t("errors.modelGatewayOff", "en", backend="Avibe Agent")
+ else:
+ expected = i18n_t("avibeAgent.error.generic", "en")
+ assert harness.controller.im_client.sent == [f"❌ {expected}"]
assert [terminal["is_error"] for terminal in harness.controller.terminals] == [True]
@@ -1539,48 +1552,6 @@ async def test_a_stop_after_the_final_reply_committed_loses_the_race(
}
-async def test_the_config_refresh_registers_and_retires_the_backend(engine, monkeypatch) -> None:
- from config.v2_compat import to_app_config
- from config.v2_config import V2Config
- from core.agent_auth_service import AgentAuthService
-
- agents: dict[str, Any] = {}
- recovered: list[AvibeAgent] = []
-
- async def recover(agent) -> list[str]:
- recovered.append(agent)
- return []
-
- # A backend enabled after startup missed the startup recovery (T2, J5); it runs on registration.
- monkeypatch.setattr(AvibeAgent, "recover_runtime_state", recover)
-
- async def refresh_runtime_config(name, runtime_config) -> bool:
- return False
-
- service = SimpleNamespace(
- agents=agents,
- register=lambda agent: agents.__setitem__(agent.name, agent),
- refresh_runtime_config=refresh_runtime_config,
- runtime_turn_tokens_for_backend=lambda _backend: {},
- release_runtime_turn_tokens=lambda _tokens: None,
- )
- config = V2Config.default()
- from modules.agents.avibe.recovery import AvibeRecovery
-
- controller = SimpleNamespace(
- agent_service=service, im_client=_IMClient(), settings_manager=_SettingsManager(), config=None
- )
- controller.avibe_recovery = AvibeRecovery(controller)
- owner = AgentAuthService(controller)
- for enabled in (True, False, True):
- config.agents.avibe.enabled = enabled
- config.save()
- controller.config = to_app_config(config)
- await owner._apply_backend_runtime_refresh("avibe")
- assert isinstance(agents.get("avibe"), AvibeAgent) is enabled
- assert len(recovered) == 2 and recovered[-1] is agents["avibe"]
-
-
async def test_startup_hands_an_orphaned_foreground_job_to_its_watch(engine, session, tmp_path, published) -> None:
jobs = FakeJobHost()
rendered: list[tuple] = []
@@ -2152,13 +2123,13 @@ async def test_resume_settles_a_reused_call_id_from_the_job_its_own_call_started
await suite.jobs.kill(current)
-def _disabled_controller() -> SimpleNamespace:
- """A controller with ``agents.avibe`` disabled: no registered adapter, and its single recovery owner."""
+def _controller_with(agent: AvibeAgent) -> SimpleNamespace:
+ """A controller with the registered adapter and its single recovery owner."""
from modules.agents.avibe.recovery import AvibeRecovery
controller = SimpleNamespace(
- agent_service=SimpleNamespace(agents={}),
- config=SimpleNamespace(avibe=None, platform="avibe", language="en"),
+ agent_service=SimpleNamespace(agents={"avibe": agent}),
+ config=SimpleNamespace(platform="avibe", language="en"),
im_client=None,
settings_manager=SimpleNamespace(),
)
@@ -2166,36 +2137,6 @@ def _disabled_controller() -> SimpleNamespace:
return controller
-async def test_startup_hands_a_foreground_job_to_its_watch_with_the_backend_disabled(
- engine, session, tmp_path, published
-) -> None:
- from core.controller import Controller
- from core.watches import ManagedWatchStore
-
- harness = _Harness(engine, tmp_path, "avibe", [], suite=local_tool_suite())
- request = harness.request("run it")
- harness.controller._native_start(request.context)
- await harness.agent.store.consume_input(
- SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
- )
- call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": "sleep 30"})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
- suite = harness.suite
- job_id = await _real_job(suite, "sleep 30", call_id="call_bash", cwd=tmp_path)
- # The process restarts with agents.avibe disabled: no adapter is registered.
- controller = _disabled_controller()
- try:
- await Controller._recover_avibe_agent_runtime_state(controller)
-
- watch_id = ManagedWatchStore().find_job_watch(job_id)
- assert watch_id is not None and not controller.avibe_recovery.retrying
- result = (await harness.context_rows())[-1]
- assert result.kind == "tool_result" and f"now Watch {watch_id}" in result.message.content[0].text
- finally:
- if suite.jobs.status(job_id).state == "running":
- await suite.jobs.kill(job_id)
-
-
async def _two_sessions_with_open_calls(engine, tmp_path, suite) -> tuple[_Harness, str, str]:
"""SESSION's open call has a running job; ses_b's has one that exited."""
with engine.begin() as conn:
@@ -2247,18 +2188,14 @@ async def _results(engine, session_id: str) -> list[str]:
).scalars())
[email protected]("registered", [True, False])
async def test_recovery_retries_a_session_it_could_not_settle(
- engine, session, tmp_path, published, monkeypatch, registered
+ engine, session, tmp_path, published, monkeypatch
) -> None:
from core.watches import ManagedWatchStore
_hand_over_failing_once(monkeypatch)
harness, running, _exited = await _two_sessions_with_open_calls(engine, tmp_path, local_tool_suite())
- controller = _disabled_controller()
- if registered:
- controller.agent_service.agents["avibe"] = harness.new_agent()
- recovery = controller.avibe_recovery
+ recovery = _controller_with(harness.new_agent()).avibe_recovery
try:
# The first pass settles ses_b and reports SESSION, never success over a failure.
assert await recovery.start() == [SESSION]
@@ -2306,52 +2243,19 @@ async def test_two_recovery_passes_racing_on_one_open_call_settle_it_once(engine
assert len(renders) == 2 and len(results) == 1
-async def test_enabling_the_backend_hands_recovery_to_the_registered_adapter(
- engine, session, tmp_path, published, monkeypatch
-) -> None:
- import modules.agents.avibe as avibe_module
- import modules.agents.avibe.recovery as recovery_module
- from config.v2_config import AvibeAgentConfig
+async def test_applying_saved_config_never_retires_the_built_in_backend(engine, tmp_path) -> None:
+ """It has no config section, which for an optional backend reads as disabled."""
from core.agent_auth_service import AgentAuthService
- from core.controller import Controller
- from core.watches import ManagedWatchStore
- from modules.agents.service import AgentService
- calls = _hand_over_failing_once(monkeypatch)
- # The detached retry would wait long; live registration must not leave it beside the new owner.
- monkeypatch.setattr(recovery_module, "RETRY_DELAYS_S", (60.0,))
- harness, running, _exited = await _two_sessions_with_open_calls(engine, tmp_path, local_tool_suite())
- controller = _disabled_controller()
- controller.agent_service = AgentService(controller)
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ controller = _controller_with(harness.agent)
auth = AgentAuthService(controller)
+ auth._load_backend_runtime_config = lambda _backend: None
auth._sync_builtin_default_agents = lambda: None
- monkeypatch.setattr(avibe_module, "AvibeAgent", lambda _controller: harness.new_agent())
- try:
- # Startup with agents.avibe disabled: SESSION's hand-over fails and a retry is pending.
- await Controller._recover_avibe_agent_runtime_state(controller)
- # agents.avibe is saved enabled: applying it registers an adapter and recovers on it.
- auth._load_backend_runtime_config = lambda _backend: AvibeAgentConfig(enabled=True)
- await auth.renew_backend_runtime("avibe", config_save=True)
-
- # One owner: the registered adapter settled everything, and no detached retry remains.
- assert "avibe" in controller.agent_service.agents
- pending = [task for task in asyncio.all_tasks() if task.get_name().startswith("avibe-agent-recovery")]
- assert [task for task in pending if not task.done()] == []
- assert ManagedWatchStore().find_job_watch(running) is not None
- assert len(await _results(engine, SESSION)) == 1 and calls.count(running) == 2
-
- # Saved disabled again: the adapter leaves routing and its stop completes, leaving
- # no teardown for the idle sweep to retry.
- auth._load_backend_runtime_config = lambda _backend: None
- await auth.renew_backend_runtime("avibe", config_save=True)
- assert "avibe" not in controller.agent_service.agents and controller.config.avibe is None
- assert controller.agent_service._pending_operations == {}
- finally:
- await controller.avibe_recovery.stop()
- for task in asyncio.all_tasks():
- if task.get_name().startswith("avibe-agent-recovery"):
- task.cancel()
- await harness.suite.jobs.kill(running)
+
+ await auth.renew_backend_runtime("avibe", config_save=True)
+
+ assert controller.agent_service.agents["avibe"] is harness.agent
async def test_recovery_admits_a_returned_input_whose_admission_failed(engine, session, tmp_path, published) -> None:
diff --git a/tests/test_avibe_backend_registration.py b/tests/test_avibe_backend_registration.py
index e4f0e2edc..903e421fe 100644
--- a/tests/test_avibe_backend_registration.py
+++ b/tests/test_avibe_backend_registration.py
@@ -13,7 +13,8 @@ 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 core.vibe_agents import BUILTIN_DEFAULT_AGENT_METADATA, VibeAgentStore, is_always_enabled_agent
+from modules.agents.catalog import NATIVE_CLI_BACKENDS
from modules.im import MessageContext
from tests.test_api_save_config_merge import _full_config_payload
from vibe import api
@@ -23,33 +24,98 @@ RELEASED = json.loads((Path(__file__).parent / "fixtures/agent_registration/rele
@pytest.mark.parametrize("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."""
+def test_released_config_shapes_preserve_native_settings(tmp_path, fixture):
+ """A new backend must not change released config values."""
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."""
[email protected]("persisted", [{"enabled": False}, {"enabled": True}, None, "invalid", {"enabled": "false"}])
+def test_a_persisted_avibe_switch_loads_as_on_and_leaves_on_the_next_save(tmp_path, sqlite_db_factory, persisted):
+ """Builds with an Avibe Agent switch wrote ``agents.avibe``; the built-in backend has no switch to honor.
+
+ Such a build also left its built-in Agent disabled while the switch was off.
+ """
payload = _full_config_payload()
- payload["agents"]["avibe"] = invalid
+ payload["agents"]["avibe"] = persisted
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 not loaded.load_warnings
assert loaded.agents.codex.enabled is True
assert loaded.agents.opencode.active_turn_timeout_seconds == 7200
- assert loaded.load_warnings
+
+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))
+ try:
+ store.create(
+ name="avibe",
+ backend="avibe",
+ source="builtin",
+ metadata={**BUILTIN_DEFAULT_AGENT_METADATA, "backend": "avibe", "backend_enabled": False},
+ enabled=False,
+ )
+ store.ensure_builtin_default_agents(api._enabled_agent_backends_from_config(loaded))
+ assert store.get("avibe").enabled
+ assert store.get_default_agent_name() == "opencode"
+ finally:
+ store.close()
+
+ loaded.save(path)
+ saved = json.loads(path.read_text())
+ assert "avibe" not in saved["agents"]
+ assert saved["agents"]["codex"]["enabled"] is True
+
+
+# Rows an earlier build may have left: (name, backend, source, metadata, enabled).
+_BUILT_IN = {**BUILTIN_DEFAULT_AGENT_METADATA, "backend": "avibe", "backend_enabled": True}
+_EARLIER_ROWS = {
+ "absent": None,
+ "disabled": ("avibe", "avibe", "builtin", _BUILT_IN, False),
+ # Before the markers were the catalog's, a metadata update could strip them, and the row could then be renamed.
+ "markers-stripped": ("avibe", "avibe", "builtin", {}, False),
+ "markers-stripped-and-renamed": ("assistant", "avibe", "builtin", {}, False),
+ "user-agent-same-backend": ("avibe", "avibe", "user", {}, False),
+ "user-agent-other-backend": ("avibe", "claude", "user", {}, True),
+}
+
+
[email protected]("earlier_row", list(_EARLIER_ROWS))
[email protected]("enabled_backends", [[], ["claude"], list(NATIVE_CLI_BACKENDS)])
+def test_the_startup_sync_leaves_the_built_in_avibe_agent_enabled(tmp_path, sqlite_db_factory, earlier_row, enabled_backends):
+ """Controller startup runs this sync first; Model Hub then seeds the Avibe supply onto that Agent row.
+
+ Whatever backends the caller read from config, and whatever an earlier build left, exactly one
+ built-in Avibe Agent exists and is enabled once the sync returns, and the identity lookup names
+ it. A row the store created stays the built-in under any name; a user's own Agent keeps its name
+ and state.
+ """
+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))
+ try:
+ row = _EARLIER_ROWS[earlier_row]
+ earlier = None
+ if row is not None:
+ name, backend, source, metadata, enabled = row
+ earlier = store.create(name=name, backend=backend, source=source, metadata=metadata, enabled=enabled)
+ store.ensure_builtin_default_agents(enabled_backends)
+
+ built_in = [agent for agent in store.list_agents() if agent.backend == "avibe" and is_always_enabled_agent(agent)]
+ assert len(built_in) == 1 and built_in[0].enabled
+ assert store.get_builtin_default_agent_for_backend("avibe") == built_in[0]
+ if earlier is not None and earlier.source == "builtin":
+ assert built_in[0].id == earlier.id
+ if earlier is not None and earlier.source == "user":
+ kept = store.get_by_id(earlier.id)
+ assert (kept.name, kept.backend, kept.enabled, kept.source) == ("avibe", row[1], row[4], "user")
+ assert built_in[0].name == "avibe-2"
+ finally:
+ store.close()
def test_avibe_agent_can_be_created_listed_selected_and_routed(tmp_path, sqlite_db_factory):
@@ -64,7 +130,6 @@ def test_avibe_agent_can_be_created_listed_selected_and_routed(tmp_path, sqlite_
("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
@@ -81,7 +146,6 @@ def test_avibe_agent_can_be_created_listed_selected_and_routed(tmp_path, sqlite_
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()
@@ -111,11 +175,10 @@ def test_avibe_native_operations_are_rejected_before_any_native_probe(monkeypatc
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."""
+ """Native auth refresh synchronizes all built-ins from config, which has no section for the built-in backend."""
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:
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index d66184561..c594c9511 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -442,8 +442,6 @@ def test_avibe_connection_uses_hub_supply_without_any_native_probe(hub_connectio
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"]
@@ -455,9 +453,18 @@ def test_avibe_connection_uses_hub_supply_without_any_native_probe(hub_connectio
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
+ # With the Model Hub disabled on the instance, or its gateway turned off, the built-in backend
+ # stays enabled with nothing to run on, whatever source is saved.
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "0")
+ disabled = asyncio.run(api.get_backend_connection("avibe"))
+ assert disabled["enabled"] and disabled["auth"] == "none"
+ assert not disabled["ready"] and not disabled["entry_eligible"]
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ hub_connection.config.model_hub.enabled = False
hub_connection.config.save()
- assert not asyncio.run(api.get_backend_connection("avibe"))["ready"]
+ stopped = asyncio.run(api.get_backend_connection("avibe"))
+ assert stopped["enabled"] and stopped["auth"] == "none"
+ assert not stopped["ready"] and not stopped["entry_eligible"]
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
diff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.py
index 7bc2f1860..36fa01a9a 100644
--- a/tests/test_backend_registration_contract.py
+++ b/tests/test_backend_registration_contract.py
@@ -33,7 +33,7 @@ NATIVE = frozenset(NATIVE_CLI_BACKENDS)
# 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", "Dict", NATIVE): (2, "native", "Config serialization/recovery plus the avault tool; the built-in backend has no section."),
("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."),
@@ -56,10 +56,9 @@ PYTHON_DECLARATIONS = {
("core/session_turns.py", "Set", frozenset({"claude", "codex", "avibe"})): (1, "agent_subset", "Runtimes whose accepted turns cannot survive a service restart (process-bound, including Avibe's in-process loop)."),
("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."),
+ ("scripts/incus_tenant.py", "Dict", NATIVE): (1, "native", "Bootstrap config with backend-specific fields."),
+ ("scripts/prepare_regression.py", "Dict", NATIVE): (2, "native", "Regression config with backend-specific fields; known legacy CLI executable paths."),
+ ("vibe/api.py", "Dict", NATIVE): (1, "native", "Public runtime config plus the avault tool; the built-in backend has no section."),
("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."),
diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.py
index 87ad3e3b2..c6f956def 100644
--- a/tests/test_backend_restart.py
+++ b/tests/test_backend_restart.py
@@ -8,7 +8,7 @@ import pytest
from core.backend_restart import BackendRestartCoordinator, NativeCredentialLease, NativeMigrationBlockedError
from core.controller import Controller
-from modules.agents.catalog import AGENT_BACKENDS
+from modules.agents.catalog import NATIVE_CLI_BACKENDS
from core.run_settlement import SETTLED_BY_BACKEND_DISABLED
@@ -131,7 +131,7 @@ def test_controller_rejects_unknown_backend_reconcile() -> None:
controller.backend_restart_coordinator.request_restart.assert_not_awaited()
[email protected]("backend", [backend for backend in AGENT_BACKENDS if backend != "claude"])
[email protected]("backend", [backend for backend in NATIVE_CLI_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
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 2ecccbf15..cc2ba9d60 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -736,7 +736,9 @@ def test_api_response_conformance_diagnostic_names_the_offending_field(tmp_path)
"contract_version": CONTRACT_VERSION,
"agents": service.list_agents(),
}
- body["agents"][0]["model_supply"][0].pop("has_runnable_hop")
+ # The first backend with a model menu; the built-in Avibe Agent leads the list with none.
+ index = next(index for index, agent in enumerate(body["agents"]) if agent["model_supply"])
+ body["agents"][index]["model_supply"][0].pop("has_runnable_hop")
validator = Draft7Validator(
{"$ref": ("model-hub/api-response.schema.json#/definitions/AgentListResponse")},
registry=_api_response_registry(),
@@ -745,7 +747,7 @@ def test_api_response_conformance_diagnostic_names_the_offending_field(tmp_path)
error = _response_validation_error(list(validator.iter_errors(body)))
- assert _response_error_path(error) == ("$.agents[0].model_supply[0].has_runnable_hop")
+ assert _response_error_path(error) == f"$.agents[{index}].model_supply[0].has_runnable_hop"
def test_oauth_result_response_discriminates_terminal_intent_and_tail():
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index f61f5a5bb..c50824429 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -456,7 +456,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 AGENT_BACKENDS)
- assert allowed_origins(source) == ("claude", "codex", "opencode", "avibe")
+ assert allowed_origins(source) == ("avibe", "opencode", "claude", "codex")
resolution = resolve_model_hub_turn(config, "codex", "shared-model")
assert resolution.source is source
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index d1b32a93f..cdee4e616 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -527,8 +527,7 @@ 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 set(data.registered_backends) == set(AGENT_BACKENDS)
- assert data.registered_backends[0] == "opencode"
+ assert data.registered_backends == list(AGENT_BACKENDS) # Catalog order: the built-in Avibe Agent first.
assert server.calls == [
"current_server",
"agents:/tmp/workspace",
@@ -597,8 +596,7 @@ 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 set(data.registered_backends) == set(AGENT_BACKENDS)
- assert data.registered_backends[0] == "opencode"
+ assert data.registered_backends == list(AGENT_BACKENDS)
assert data.opencode_agents == [{"name": "build"}]
assert data.claude_agents == [{"id": "reviewer"}]
assert data.claude_models == ["claude-sonnet-4-6"]
@@ -624,7 +622,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", "avibe"]
+ assert data.registered_backends == ["avibe", "opencode"]
assert server.calls == [
"current_server",
"agents:/tmp/workspace",
@@ -646,8 +644,9 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is
):
data = asyncio.run(handler._gather_routing_modal_data(context))
+ # Listed first, the built-in backend is still not the fallback while another is enabled.
assert data.current_backend == "opencode"
- assert data.registered_backends == ["opencode", "avibe", "codex"]
+ assert data.registered_backends == ["avibe", "opencode", "codex"]
assert data.opencode_agents == [{"name": "build"}]
assert server.calls == [
"current_server",
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 12f35584e..9ec1f5cef 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -28,7 +28,8 @@ from modules.im import telegram_api
from config.v2_config import TelegramConfig
-ROUTING_BACKENDS = ["opencode", *(backend for backend in AGENT_BACKENDS if backend != "opencode")]
+# The settings handler lists routing backends in catalog order, the built-in Avibe Agent first.
+ROUTING_BACKENDS = list(AGENT_BACKENDS)
@pytest.fixture(autouse=True)
@@ -1354,11 +1355,11 @@ def test_routing_state_marks_current_backend_in_first_row() -> None:
_, keyboard = bot._render_routing_state(state)
assert [button.callback_data for button in keyboard.buttons[0]] == [
+ "tg_route:backend:avibe",
"tg_route:backend:opencode",
"tg_route:backend:claude",
- "tg_route:backend:codex",
]
- assert keyboard.buttons[0][1].text.startswith("☑️ ")
+ assert keyboard.buttons[0][2].text.startswith("☑️ ")
def test_routing_codex_reasoning_uses_shared_catalog_options() -> None:
@@ -1481,9 +1482,9 @@ def test_routing_state_keeps_backend_picker_entry_for_extra_backends(extra_backe
assert "Avibe Agent" in text
assert [button.callback_data for button in keyboard.buttons[0]] == [
+ "tg_route:backend:avibe",
"tg_route:backend:opencode",
"tg_route:backend:claude",
- "tg_route:backend:codex",
]
assert keyboard.buttons[1][0].callback_data == "tg_route:field:backend"
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 1ffadb274..7b498e0ba 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -3916,6 +3916,8 @@ def test_builtin_default_agent_enabled_state_follows_backend_config(tmp_path, mo
assert store.require("opencode").enabled is True
assert store.require("claude").enabled is False
+ # The built-in backend has no config entry and is always enabled.
+ assert store.require("avibe").enabled is True
assert "claude" not in [agent.name for agent in store.list_agents(include_disabled=False)]
assert "claude" in [agent.name for agent in store.list_agents(include_disabled=True)]
finally:
@@ -3995,12 +3997,85 @@ def test_vibe_agent_api_rejects_non_boolean_enabled(tmp_path, monkeypatch):
assert api.update_vibe_agent("reviewer", {"enabled": False})["agent"]["enabled"] is False
-def test_builtin_default_agent_uses_first_enabled_backend_when_no_default_exists(tmp_path, monkeypatch):
+ ("backends", "expected"),
+ [(list(AGENT_BACKENDS), "opencode"), (["claude", "avibe"], "claude"), ([], "avibe")],
+)
+def test_builtin_default_agent_uses_first_enabled_backend_when_no_default_exists(
+ tmp_path, monkeypatch, backends, expected
+):
+ """The built-in backend leads the catalog, but becomes the default only when nothing else is enabled."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
store = VibeAgentStore()
try:
- store.ensure_builtin_default_agents(list(AGENT_BACKENDS))
- assert store.get_default_agent_name() == "opencode"
+ store.ensure_builtin_default_agents(backends)
+ assert store.get_default_agent_name() == expected
+ finally:
+ store.close()
+
+
+def test_a_default_nobody_chose_is_not_the_built_in_avibe_agent(tmp_path, monkeypatch):
+ """With the chosen default disabled, new chats fall back to an enabled Agent, as before Avibe was built in."""
+ from core.vibe_agents import resolve_effective_default_agent
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents(["opencode", "claude"])
+ store.set_enabled("opencode", False)
+ with store.engine.connect() as conn:
+ assert resolve_effective_default_agent(conn).name == "claude"
+ store.set_enabled("claude", False)
+ with store.engine.connect() as conn:
+ assert resolve_effective_default_agent(conn).name == "avibe"
+ finally:
+ store.close()
+
+
[email protected]("explicit_default", [True, False])
+def test_archiving_the_default_never_hands_new_chats_to_the_built_in_agent(tmp_path, monkeypatch, explicit_default):
+ """The replacement for an archived default, chosen or implicit, ranks the built-in backend last."""
+ from core.vibe_agents import BUILTIN_DEFAULT_AGENT_METADATA
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ store = VibeAgentStore()
+ try:
+ store.create(
+ name="avibe", backend="avibe", source="builtin",
+ metadata={**BUILTIN_DEFAULT_AGENT_METADATA, "backend": "avibe"},
+ )
+ store.create(name="omega", backend="claude")
+ store.create(name="zeta", backend="opencode")
+ if explicit_default:
+ store.set_default_agent_name("omega")
+ # Archiving the default (explicit, or implicit when none was chosen) needs a replacement;
+ # with no other Claude Agent, it is the first non-built-in one.
+ assert api.remove_vibe_agent("omega")["ok"] is True
+ assert store.get_default_agent_name() == "zeta"
+ finally:
+ store.close()
+
+
+def test_the_built_in_avibe_agent_cannot_be_disabled_and_stays_editable(tmp_path, monkeypatch):
+ """Turning it off would turn off the backend; its model, prompt and metadata stay editable."""
+ from core.vibe_agents import AgentAlwaysEnabledError
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ refused = api.update_vibe_agent("avibe", {"enabled": False})
+ assert refused["ok"] is False and refused["code"] == "agent_always_enabled"
+ # Dropping the built-in markers first is no way around it.
+ assert api.update_vibe_agent("avibe", {"metadata": {}})["ok"] is True
+ with pytest.raises(AgentAlwaysEnabledError):
+ store.set_enabled("avibe", False)
+ updated = api.update_vibe_agent("avibe", {"model": "team-model", "system_prompt": "Be brief."})
+ assert updated["agent"]["model"] == "team-model"
+ assert store.require("avibe").enabled is True
+ # Any other Avibe Agent is an ordinary Agent.
+ store.create(name="helper", backend="avibe")
+ assert api.update_vibe_agent("helper", {"enabled": False})["agent"]["enabled"] is False
finally:
store.close()
@@ -4025,6 +4100,31 @@ def test_api_builtin_default_agents_ignore_legacy_config_default_backend(tmp_pat
store.close()
[email protected]("enabled", [False, True])
+def test_callers_cannot_forge_or_strip_built_in_markers(tmp_path, monkeypatch, enabled):
+ """The markers are the catalog's: forging them on an Agent must not make it an undeletable,
+ always-on pseudo-built-in, not even in the same write that disables it."""
+ from core.vibe_agents import is_always_enabled_agent, is_builtin_default_agent
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ forged = {"builtin": True, "builtin_default": True, "lock_delete": True, "backend_enabled": True, "note": "kept"}
+ created = api.create_vibe_agent({"name": "helper", "backend": "avibe", "metadata": forged})
+ assert created["agent"]["metadata"] == {"note": "kept"}
+
+ updated = api.update_vibe_agent("helper", {"metadata": forged, "enabled": enabled})
+ assert updated["ok"] is True and updated["agent"]["enabled"] is enabled
+ assert updated["agent"]["metadata"] == {"note": "kept"}
+ store = VibeAgentStore()
+ try:
+ helper = store.require("helper")
+ assert not is_builtin_default_agent(helper) and not is_always_enabled_agent(helper)
+ # It renames like any Agent; deleting it is never refused as a built-in.
+ assert store.rename("helper", "helper-renamed").name == "helper-renamed"
+ assert api.remove_vibe_agent("helper-renamed").get("code") != "agent_builtin"
+ finally:
+ store.close()
+
+
def test_builtin_default_agent_does_not_reuse_conflicting_user_agent(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
store = VibeAgentStore()
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 445f939b4..d3e7d92bb 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -2096,6 +2096,68 @@ def test_config_routes_redact_platform_and_gateway_secrets(monkeypatch, tmp_path
assert "client_secret" not in data["gateway"]
+ ("hub_switch", "gateway_enabled", "blocks"),
+ [("1", True, {}), ("1", False, {"avibe": "gateway_off"}), ("0", True, {"avibe": "hub_disabled"})],
+)
+def test_config_api_carries_why_the_model_hub_leaves_a_backend_no_model(monkeypatch, tmp_path, hub_switch, gateway_enabled, blocks):
+ """The Backends page shows the server's answer; it keeps no rule of its own."""
+ from modules.agents.catalog import NATIVE_CLI_BACKENDS
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", hub_switch)
+ from vibe import api
+
+ config = api.save_config(_full_config_payload())
+ # The gateway turns off only while no native backend is in Hub mode (``runtime_in_use``).
+ for backend in NATIVE_CLI_BACKENDS:
+ config.model_hub.agents[backend].mode = "direct"
+ config.model_hub.enabled = gateway_enabled
+ config.save()
+
+ assert app.test_client().get("/api/config").get_json()["agent_supply_blocks"] == blocks
+
+
+ ("method", "path", "body", "code"),
+ [
+ ("post", "/api/config", {"agents": {"avibe": {"enabled": False}}}, None),
+ ("patch", "/api/agents/avibe", {"enabled": False}, "agent_always_enabled"),
+ ],
+)
+def test_requests_to_turn_off_the_built_in_avibe_agent_fail_with_a_client_error(
+ monkeypatch, tmp_path, method, path, body, code
+):
+ """It has no switch: a request to turn it off is refused instead of silently ignored."""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.vibe_agents import VibeAgentStore
+ from vibe import api
+
+ api.save_config(_full_config_payload())
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ finally:
+ store.close()
+ client = app.test_client()
+
+ response = getattr(client, method)(path, json=body, headers=csrf_headers(client))
+
+ assert response.status_code == 400
+ payload = response.get_json()
+ assert payload["ok"] is False
+ if code is None:
+ assert "always enabled" in payload["error"]
+ else:
+ assert payload["code"] == code and payload["message"]
+ assert "avibe" not in api.config_to_payload(api.load_config())["agents"]
+ store = VibeAgentStore()
+ try:
+ assert store.require("avibe").enabled is True
+ finally:
+ store.close()
+
+
def test_config_post_hot_reconciles_platform_enablement(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from vibe import api
@@ -2304,15 +2366,14 @@ def test_changed_agent_backend_runtimes_keeps_saved_selector_changes_visible(mon
) == ["claude"]
[email protected]("backend", ["codex", "avibe"])
-def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path, backend):
+def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path):
"""Scenario: AUTH-SETUP-902."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from vibe import api
from vibe import internal_client
payload = _full_config_payload()
- payload["agents"].setdefault(backend, {})["enabled"] = False
+ payload["agents"]["codex"]["enabled"] = False
api.save_config(payload)
reconcile_calls = []
@@ -2324,7 +2385,7 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tm
"body": {
"ok": True,
"backends": backends,
- "states": {backend: "restarted"},
+ "states": {"codex": "restarted"},
},
}
@@ -2335,9 +2396,9 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tm
"/api/config",
json={
"agents": {
- backend: {
+ "codex": {
"enabled": True,
- **({"cli_path": "/opt/codex"} if backend == "codex" else {}),
+ "cli_path": "/opt/codex",
}
}
},
@@ -2346,20 +2407,18 @@ def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tm
assert response.status_code == 200
data = response.get_json()
- assert data["agents"][backend]["enabled"] is True
- if backend == "avibe":
- assert data["agents"][backend] == {"enabled": True}
+ assert data["agents"]["codex"]["enabled"] is True
assert data["agent_backend_runtime"] == {
"ok": True,
"hot_reconciled": True,
- "backends": [backend],
+ "backends": ["codex"],
"body": {
"ok": True,
- "backends": [backend],
- "states": {backend: "restarted"},
+ "backends": ["codex"],
+ "states": {"codex": "restarted"},
},
}
- assert reconcile_calls == [[backend]]
+ assert reconcile_calls == [["codex"]]
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.py
index 6d932f1fa..970744d49 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -131,28 +131,6 @@ 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/ui/src/components/settings/SettingsBackendPage.tsx b/ui/src/components/settings/SettingsBackendPage.tsx
index 8137126d0..5e769e0b8 100644
--- a/ui/src/components/settings/SettingsBackendPage.tsx
+++ b/ui/src/components/settings/SettingsBackendPage.tsx
@@ -1,12 +1,15 @@
+import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
-import { ArrowLeft } from 'lucide-react';
+import { ArrowLeft, ArrowRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { useApi } from '@/context/ApiContext';
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 { hubSupplyBlocks, type HubSupplyBlock } from './models/featureFlags';
import { useModelHubCapability } from './models/useModelHubCapability';
/** Shared settings body for backends whose runtime is owned by Avibe. */
@@ -15,6 +18,20 @@ export function SettingsBackendPage({ backend }: { backend: AgentBackendId }) {
const meta = getBackendUiMeta(backend);
const runtime = useBackendRuntime({ backend });
const modelHubEnabled = useModelHubCapability();
+ const { getConfig } = useApi();
+ const [supplyBlock, setSupplyBlock] = useState<HubSupplyBlock | undefined>();
+
+ useEffect(() => {
+ let cancelled = false;
+ getConfig()
+ .then((config) => {
+ if (!cancelled) setSupplyBlock(hubSupplyBlocks(config).get(backend));
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [getConfig, backend]);
return (
<SettingsPageShell
@@ -38,6 +55,22 @@ export function SettingsBackendPage({ backend }: { backend: AgentBackendId }) {
iconTileClassName={meta.tileCls}
iconClassName={meta.iconCls}
runtime={runtime}
+ extraSlot={supplyBlock && (
+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-gold/40 bg-gold/10 px-3 py-2.5">
+ <p className="text-[12px] text-gold-ink">
+ {supplyBlock === 'hub_disabled'
+ ? t('settings.backends.hubDisabledNotice', { name: meta.label })
+ : t('settings.backends.gatewayOff', { name: meta.label })}
+ </p>
+ {supplyBlock === 'gateway_off' && <Link
+ to="/settings/models"
+ className="model-hub-action-mint inline-flex shrink-0 items-center gap-1 text-[13px] font-medium transition-colors"
+ >
+ {t('settings.models.supplyMode.hub.openModels')}
+ <ArrowRight className="size-3.5" />
+ </Link>}
+ </div>
+ )}
/>
{modelHubEnabled === true && <BackendSupplyModeCard backend={backend} />}
</div>
diff --git a/ui/src/components/settings/SettingsBackendsPage.test.tsx b/ui/src/components/settings/SettingsBackendsPage.test.tsx
index d65973c32..d13c73502 100644
--- a/ui/src/components/settings/SettingsBackendsPage.test.tsx
+++ b/ui/src/components/settings/SettingsBackendsPage.test.tsx
@@ -46,47 +46,51 @@ afterEach(() => {
vi.restoreAllMocks();
});
-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 renderBackends = () => 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>,
+);
+
+const rowOf = async (name: string) => (await screen.findByText(name)).closest('.rounded-xl') as HTMLElement;
+
+describe('built-in backend settings', () => {
+ // The built-in Avibe Agent is part of the platform: listed first, always on,
+ // and marked Built-in where every other backend has its enable switch.
+ it('lists Avibe first as Built-in with no switch, and its page has no switch or native actions', async () => {
+ renderBackends();
+
+ const avibe = await rowOf('Avibe Agent');
+ const rows = [...document.querySelectorAll('.rounded-xl')];
+ expect(rows.map((row) => row.querySelector('span.font-semibold')?.textContent)).toEqual([
+ 'Avibe Agent', 'OpenCode', 'Claude Code', 'Codex',
+ ]);
+ expect(within(avibe).getByText('Built-in')).toBeTruthy();
+ expect(within(avibe).queryByRole('switch')).toBeNull();
+ expect(within(avibe).queryByTestId('lifecycle-avibe')).toBeNull();
+ for (const name of ['OpenCode', 'Claude Code', 'Codex']) {
+ const row = await rowOf(name);
+ expect(within(row).getByRole('switch')).toBeTruthy();
+ expect(within(row).queryByText('Built-in')).toBeNull();
}
- 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' });
+ const configure = within(avibe).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(await screen.findByText('Built-in')).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
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.mutateConfig).not.toHaveBeenCalled();
expect(mocks.api.detectCli).toHaveBeenCalledTimes(3);
expect(mocks.api.getBackendRuntime).not.toHaveBeenCalled();
expect(mocks.api.installAgent).not.toHaveBeenCalled();
@@ -95,36 +99,66 @@ describe('in-process backend settings', () => {
});
describe('backend attention', () => {
- it('flags the backend whose Agent has no model once enabling it creates that Agent', async () => {
- const withoutModel = [
- {
- backend: 'avibe', cli_present: false, mode: 'hub', menu_kind: 'fixed',
- named_agents: [{ name: 'avibe', effective_model_id: null, supply_status: null }],
- },
- {
- backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',
- named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-5-5', supply_status: 'ok' }],
- },
- ] as AgentSupply[];
- // Disabled, the backend has no named Agent yet; enabling it creates the built-in one.
- const listAgents = vi.spyOn(modelsApi, 'listAgents')
- .mockResolvedValueOnce(withoutModel.slice(1))
- .mockResolvedValue(withoutModel);
- render(
- <I18nextProvider i18n={i18n}>
- <MemoryRouter initialEntries={['/settings/backends']}>
- <SettingsBackendsPage />
- </MemoryRouter>
- </I18nextProvider>,
- );
- const row = async (name: string) => (await screen.findByText(name)).closest('.rounded-xl') as HTMLElement;
- const avibe = await row('Avibe Agent');
- await waitFor(() => expect(listAgents).toHaveBeenCalledTimes(1));
- expect(within(avibe).queryByText('No model selected')).toBeNull();
+ const withoutModel = [
+ {
+ backend: 'avibe', cli_present: false, mode: 'hub', menu_kind: 'fixed',
+ named_agents: [{ name: 'avibe', effective_model_id: null, supply_status: null }],
+ },
+ {
+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',
+ named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-5-5', supply_status: 'ok' }],
+ },
+ ] as AgentSupply[];
+ // GET /api/config carries the server's answer for each blocked backend.
+ const modelHubConfig = (enabled: boolean) => ({
+ agents: {},
+ capabilities: { model_hub: { enabled: true } },
+ agent_supply_blocks: enabled ? {} : { avibe: 'gateway_off' },
+ });
- fireEvent.click(within(avibe).getByRole('switch'));
+ it('flags the always-on backend whose Agent has no model', async () => {
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue(withoutModel);
+ mocks.api.getConfig.mockResolvedValue(modelHubConfig(true));
+ renderBackends();
+ const avibe = await rowOf('Avibe Agent');
expect(await within(avibe).findByText('No model selected')).toBeTruthy();
- expect(within(await row('Claude Code')).queryByText('No model selected')).toBeNull();
+ expect(within(avibe).queryByText('Gateway off')).toBeNull();
+ expect(within(await rowOf('Claude Code')).queryByText('No model selected')).toBeNull();
+ });
+
+ // Turning the gateway off leaves the backend enabled with nothing to run on;
+ // its status names the cause and its page leads to Models.
+ it('says the gateway is off instead, on the row and on the backend page', async () => {
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue(withoutModel);
+ mocks.api.getConfig.mockResolvedValue(modelHubConfig(false));
+ renderBackends();
+
+ const avibe = await rowOf('Avibe Agent');
+ expect(await within(avibe).findByText('Gateway off')).toBeTruthy();
+ expect(within(avibe).queryByText('No model selected')).toBeNull();
+ expect(within(await rowOf('Claude Code')).queryByText('Gateway off')).toBeNull();
+
+ fireEvent.click(within(avibe).getByRole('link', { name: 'Configure' }));
+ expect(await screen.findByText('The model gateway is off, so Avibe Agent has no model to run on.')).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'Open Models page' }).getAttribute('href')).toBe('/settings/models');
+ });
+
+ // The operator's Model Hub switch leaves the always-on backend nothing to run on,
+ // and there is no Models page to open.
+ it('says Model Hub is disabled when the instance turns it off', async () => {
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue(withoutModel);
+ mocks.api.getConfig.mockResolvedValue({
+ agents: {}, capabilities: { model_hub: { enabled: false } }, agent_supply_blocks: { avibe: 'hub_disabled' },
+ });
+ renderBackends();
+
+ const avibe = await rowOf('Avibe Agent');
+ expect(await within(avibe).findByText('Model Hub disabled')).toBeTruthy();
+ expect(within(await rowOf('Claude Code')).queryByText('Model Hub disabled')).toBeNull();
+
+ fireEvent.click(within(avibe).getByRole('link', { name: 'Configure' }));
+ expect(await screen.findByText('Model Hub is disabled on this instance, so Avibe Agent has no model to run on.')).toBeTruthy();
+ expect(screen.queryByRole('link', { name: 'Open Models page' })).toBeNull();
});
});
diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsx
index bb8936b7c..b333b1212 100644
--- a/ui/src/components/settings/SettingsBackendsPage.tsx
+++ b/ui/src/components/settings/SettingsBackendsPage.tsx
@@ -8,6 +8,7 @@ import { Button } from '../ui/button';
import { SettingsResourceRow, ToggleSwitch } from './SettingsPrimitives';
import { BackendLifecycleChip } from './BackendLifecycleChip';
import { SettingsPageShell } from './SettingsPageShell';
+import { hubSupplyBlocks, type HubSupplyBlock } from './models/featureFlags';
import { modelsApi } from './models/modelsApi';
import { agentsWithoutModel } from './models/supply';
import { useApi } from '@/context/ApiContext';
@@ -16,9 +17,10 @@ import { AGENT_BACKENDS, DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/age
import { configChanges } from '@/lib/configMutations';
import { errorMessage } from '@/lib/errorMessage';
-// Mirrors design.pen qVHh4 (VR/CM/Backends): three horizontal cards
-// (OpenCode/Claude/Codex). Each card
-// surfaces icon + name/description + status chip + enable toggle + a
+// Mirrors design.pen qVHh4 (VR/CM/Backends): one horizontal card per backend,
+// in catalog order with the built-in Avibe Agent first. Each card
+// surfaces icon + name/description + status chip + enable toggle (a
+// "Built-in" badge instead for the always-enabled backend) + a
// "Configure" link that drills into the level-2 provider page. CLI path,
// detect, install, and permission profile live on the provider page now —
// keep the level-1 page about backend availability, not Agent defaults.
@@ -57,6 +59,7 @@ export const SettingsBackendsPage: React.FC = () => {
const [loaded, setLoaded] = useState(false);
const [agents, setAgents] = useState<Record<string, AgentState>>(DEFAULT_AGENTS);
+ const [supplyBlocks, setSupplyBlocks] = useState<ReadonlyMap<string, HubSupplyBlock>>(() => new Map());
// Backends with an enabled Agent whose next turn fails for want of a model (the Models page's reading).
const [withoutModel, setWithoutModel] = useState<ReadonlySet<string>>(() => new Set());
@@ -79,6 +82,7 @@ export const SettingsBackendsPage: React.FC = () => {
.then((config) => {
if (cancelled) return;
setAgents(normalizeAgents(config));
+ setSupplyBlocks(hubSupplyBlocks(config));
setLoaded(true);
})
.catch(() => {
@@ -183,10 +187,17 @@ export const SettingsBackendsPage: React.FC = () => {
tileClassName={meta.tileCls}
iconClassName={meta.iconCls}
title={meta.label}
+ badges={meta.builtin && <Badge variant="secondary">{t('settings.backends.builtinBadge')}</Badge>}
detail={t(meta.descriptionKey)}
actions={
<>
- {agent.enabled && withoutModel.has(meta.id) && (
+ {supplyBlocks.has(meta.id) ? (
+ <Badge variant="warning">
+ {supplyBlocks.get(meta.id) === 'hub_disabled'
+ ? t('settings.backends.hubDisabled')
+ : t('settings.models.shell.stopped')}
+ </Badge>
+ ) : agent.enabled && withoutModel.has(meta.id) && (
<Badge variant="warning">{t('settings.models.gateway.agentIssues.modelMissing')}</Badge>
)}
{meta.capabilities.supports_runtime_refresh && <BackendLifecycleChip
@@ -205,10 +216,12 @@ export const SettingsBackendsPage: React.FC = () => {
await refreshDetectionFor(meta.id, installedPath || agent.cli_path);
}}
/>}
- <ToggleSwitch
- enabled={agent.enabled}
- onClick={() => void handleToggle(meta.id, !agent.enabled)}
- />
+ {!meta.builtin && (
+ <ToggleSwitch
+ enabled={agent.enabled}
+ onClick={() => void handleToggle(meta.id, !agent.enabled)}
+ />
+ )}
{route && (
<Button asChild variant="secondary" size="xs">
<Link to={route} aria-label={t('settings.backends.configure', { name: meta.label }) as string}>
diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.ts
index 0d2896ab3..be0b7c678 100644
--- a/ui/src/components/settings/models/featureFlags.ts
+++ b/ui/src/components/settings/models/featureFlags.ts
@@ -12,3 +12,16 @@ export const modelHubEnabledFromConfig = (config: unknown): boolean => {
(modelHub as { enabled?: unknown }).enabled === true,
);
};
+
+export type HubSupplyBlock = 'hub_disabled' | 'gateway_off';
+
+// Backends left with no model to run on by the Model Hub's state, and why. The
+// server decides (``hub_supply_block``) and GET /api/config carries the answer.
+export const hubSupplyBlocks = (config: unknown): ReadonlyMap<string, HubSupplyBlock> => {
+ const blocks = (config as { agent_supply_blocks?: unknown } | null)?.agent_supply_blocks;
+ if (!blocks || typeof blocks !== 'object') return new Map();
+ return new Map(
+ Object.entries(blocks).filter((entry): entry is [string, HubSupplyBlock] =>
+ entry[1] === 'hub_disabled' || entry[1] === 'gateway_off'),
+ );
+};
diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
index c6f46a4e2..1fb9f321a 100644
--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx
+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
@@ -8,6 +8,7 @@ import {
} from 'lucide-react';
import clsx from 'clsx';
+import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Card, CardContent } from '../../ui/card';
import { Input } from '../../ui/input';
@@ -81,7 +82,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
}) => {
const { t } = useTranslation();
const inputId = `${backend}-cli-path`;
- const { capabilities } = getBackendUiMeta(backend);
+ const { capabilities, builtin } = getBackendUiMeta(backend);
return (
<Card>
@@ -110,7 +111,9 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
onChanged={runtime.handleLifecycleChanged}
onOperationChange={(busy) => { if (!busy) void runtime.handleLifecycleChanged(null); }}
/>}
- {!hideEnableToggle && (
+ {builtin ? (
+ <Badge variant="secondary">{t('settings.backends.builtinBadge')}</Badge>
+ ) : !hideEnableToggle && (
<ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />
)}
</div>
diff --git a/ui/src/components/settings/shared/useBackendRuntime.test.tsx b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
index 8d1074e9d..402ee9948 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.test.tsx
+++ b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
@@ -51,10 +51,10 @@ 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 () => {
+ it('reads the built-in backend as enabled without a config section 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.enabled).toBe(true);
expect(hook.result.current.cliPath).toBe('');
await act(async () => {
await hook.result.current.detect();
diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsx
index 4630b1e99..371e532c8 100644
--- a/ui/src/components/workbench/AgentsPage.test.tsx
+++ b/ui/src/components/workbench/AgentsPage.test.tsx
@@ -287,6 +287,25 @@ describe('AgentsPage contextual selection', () => {
}
});
+ // The built-in Avibe Agent is part of the platform: model, effort and prompt
+ // stay editable, but nothing turns it off. Another Avibe Agent is ordinary.
+ it.each([
+ ['avibe', 'builtin', { builtin: true, builtin_default: true, lock_delete: true }, true],
+ ['local-helper', 'custom', {}, false],
+ ])('locks the enable switch of %s only when it is the built-in Avibe Agent', async (name, source, metadata, locked) => {
+ const agent = { ...brief(name, 'avibe agent'), backend: 'avibe', source };
+ const full = fullAgent(agent, 'prompt');
+ const api = makeApi(
+ vi.fn().mockResolvedValue(listResult(agent)),
+ vi.fn().mockResolvedValue({ ...full, agent: { ...full.agent, metadata } }),
+ );
+ renderPage(api, { canManageAgents: true, entry: `/agents?agent=${name}` });
+
+ const toggle = await screen.findByRole('switch', { name: 'agents.detail.enabled' });
+ expect(toggle.hasAttribute('disabled')).toBe(locked);
+ expect(Boolean(screen.queryByText('agents.detail.alwaysEnabledHint'))).toBe(locked);
+ });
+
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.tsx
index 0d676250a..ea94d4b71 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -64,6 +64,7 @@ import {
type Backend,
} from '../../lib/backendAccent';
import { getBackendUiMeta, type NativeCliBackend } from '@/lib/agentBackends';
+import { isBuiltinAgent } from '../onboarding/setupTargets';
import { modelsApi } from '../settings/models/modelsApi';
import { agentsWithoutModel } from '../settings/models/supply';
import { errorMessage } from '@/lib/errorMessage';
@@ -1969,6 +1970,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
// System agents are locked everywhere; remote access locks every agent.
const locked = isSystemAgent(agent) || !canEdit;
const system = isSystemAgent(agent);
+ // The built-in Agent of the built-in backend is part of the platform: it stays enabled.
+ const alwaysEnabled = agent.source === 'builtin' && isBuiltinAgent(agent) && getBackendUiMeta(agent.backend).builtin;
const [name, setName] = useState(agent.name);
const [renaming, setRenaming] = useState(false);
const [settingDefault, setSettingDefault] = useState(false);
@@ -2292,14 +2295,16 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
>
<div className="flex min-w-0 flex-col gap-0.5">
<span className="text-[13px] font-bold text-foreground">{t('agents.detail.enabled')}</span>
- <span className="text-[11px] text-muted">{t('agents.detail.enabledHint')}</span>
+ <span className="text-[11px] text-muted">
+ {t(alwaysEnabled ? 'agents.detail.alwaysEnabledHint' : 'agents.detail.enabledHint')}
+ </span>
</div>
<Switch
checked={agent.enabled}
onCheckedChange={(next) => {
consumeBackgroundMutation(onChange({ enabled: next }));
}}
- disabled={!canEdit}
+ disabled={!canEdit || alwaysEnabled}
title={canEdit ? undefined : t('agents.remoteReadOnlyHint')}
label={t('agents.detail.enabled')}
/>
diff --git a/ui/src/components/workbench/GlobalPromptsDialog.test.tsx b/ui/src/components/workbench/GlobalPromptsDialog.test.tsx
index 93e7ea068..29f8fb737 100644
--- a/ui/src/components/workbench/GlobalPromptsDialog.test.tsx
+++ b/ui/src/components/workbench/GlobalPromptsDialog.test.tsx
@@ -31,11 +31,11 @@ describe('native global prompts', () => {
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.getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['OpenCode', 'Claude Code', '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'],
+ content: 'Instructions', backends: ['opencode', 'claude', 'codex'],
}));
});
});
diff --git a/ui/src/components/workbench/NewAgentDialog.test.tsx b/ui/src/components/workbench/NewAgentDialog.test.tsx
index 10740ef6d..d6526c079 100644
--- a/ui/src/components/workbench/NewAgentDialog.test.tsx
+++ b/ui/src/components/workbench/NewAgentDialog.test.tsx
@@ -98,12 +98,18 @@ 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', () => {
+ // Settings and Model Hub. All backend choices share the catalog brands, and
+ // they follow catalog order, the built-in Avibe Agent first.
+ it('uses the catalog brand names and order for every backend choice', () => {
renderDialog();
- for (const label of ['Claude Code', 'OpenCode', 'Codex', 'Avibe Agent']) {
+ const labels = ['Avibe Agent', 'OpenCode', 'Claude Code', 'Codex'];
+ for (const label of labels) {
expect(screen.getByRole('button', { name: new RegExp(label) }).textContent).toContain(label);
}
+ const order = screen.getAllByRole('button')
+ .map((button) => labels.find((label) => button.textContent?.includes(label)))
+ .filter(Boolean);
+ expect(order).toEqual(labels);
expect(screen.queryByText('Claude', { exact: true })).toBeNull();
});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fdf34c84b..debe92aa1 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -586,6 +586,10 @@
"codexDescription": "OpenAI agent · ChatGPT login or OPENAI_API_KEY",
"avibeDescription": "Built-in agent · models and routes managed in Model Hub",
"backToBackends": "Back to backends",
+ "gatewayOff": "The model gateway is off, so {{name}} has no model to run on.",
+ "hubDisabled": "Model Hub disabled",
+ "hubDisabledNotice": "Model Hub is disabled on this instance, so {{name}} has no model to run on.",
+ "builtinBadge": "Built-in",
"openProviderPage": "Configure provider",
"providerOauth": "OAuth (default)",
"providerApiKey": "API key",
@@ -4021,6 +4025,7 @@
"detail": {
"enabled": "Enabled",
"enabledHint": "Disabling keeps the agent in the registry but excludes it from new sessions; running sessions are unaffected.",
+ "alwaysEnabledHint": "The built-in Avibe Agent is always enabled. You can still adjust its model, effort, and system prompt.",
"defaultTitle": "Default agent",
"defaultHint": "New chats and IM messages without an explicit agent route to this one.",
"defaultActive": "Default",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index aa29e7e3e..0ee6e21a6 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -586,6 +586,10 @@
"codexDescription": "OpenAI Agent · 通过 ChatGPT 登录或 OPENAI_API_KEY",
"avibeDescription": "内置 Agent · 在模型中枢管理模型和路由",
"backToBackends": "返回后端列表",
+ "gatewayOff": "模型网关已关闭,{{name}} 没有可用的模型。",
+ "hubDisabled": "模型中枢已停用",
+ "hubDisabledNotice": "本实例已停用模型中枢,{{name}} 没有可用的模型。",
+ "builtinBadge": "内置",
"openProviderPage": "配置 Provider",
"providerOauth": "OAuth(默认)",
"providerApiKey": "API Key",
@@ -4021,6 +4025,7 @@
"detail": {
"enabled": "已启用",
"enabledHint": "关掉后此 Agent 不会被新会话选用,已运行的会话不受影响",
+ "alwaysEnabledHint": "内置的 Avibe Agent 始终启用,仍可调整模型、Effort 与系统提示词。",
"defaultTitle": "默认 Agent",
"defaultHint": "未指定 Agent 的新会话和 IM 消息都会路由到这个 Agent。",
"defaultActive": "默认",
diff --git a/ui/src/lib/agentBackendCatalog.generated.ts b/ui/src/lib/agentBackendCatalog.generated.ts
index ec14650fc..a41706f01 100644
--- a/ui/src/lib/agentBackendCatalog.generated.ts
+++ b/ui/src/lib/agentBackendCatalog.generated.ts
@@ -1,6 +1,24 @@
// 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": "avibe",
+ "display_name": "Avibe Agent",
+ "config_key": "avibe",
+ "default_cli": null,
+ "default_enabled": true,
+ "latest_probe": null,
+ "capabilities": {
+ "supports_cli": false,
+ "supports_native_sessions": false,
+ "supports_runtime_refresh": false,
+ "supports_web_oauth": false,
+ "supports_install": false
+ },
+ "builtin": true,
+ "description_key": "settings.backends.avibeDescription",
+ "settings_route": "/settings/backends/avibe"
+ },
{
"id": "opencode",
"display_name": "OpenCode",
@@ -18,6 +36,7 @@ export const BACKEND_CATALOG = [
"supports_web_oauth": true,
"supports_install": true
},
+ "builtin": false,
"description_key": "settings.backends.opencodeDescription",
"settings_route": "/settings/backends/opencode"
},
@@ -38,6 +57,7 @@ export const BACKEND_CATALOG = [
"supports_web_oauth": true,
"supports_install": true
},
+ "builtin": false,
"description_key": "settings.backends.claudeDescription",
"settings_route": "/settings/backends/claude"
},
@@ -58,24 +78,8 @@ export const BACKEND_CATALOG = [
"supports_web_oauth": true,
"supports_install": true
},
+ "builtin": false,
"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.ts
index 9bd2c788a..c8bbf2587 100644
--- a/ui/src/lib/agentBackends.ts
+++ b/ui/src/lib/agentBackends.ts
@@ -14,10 +14,11 @@ export type BackendUiMeta = {
label: string;
defaultCli: string | null;
defaultEnabled: boolean;
+ /** Part of the platform: always enabled, with no switch. */
+ builtin: boolean;
settingsRoute: string;
descriptionKey: string;
capabilities: BackendCapabilities;
- agentOrder: number;
nativeOrder: number;
publisher: string;
accent: 'mint' | 'cyan' | 'violet';
@@ -32,7 +33,6 @@ export type BackendUiMeta = {
// Presentation only. Membership, defaults and capabilities come from Python.
const BACKEND_VISUALS = {
opencode: {
- agentOrder: 1,
nativeOrder: 2,
publisher: 'opencode.ai',
accent: 'cyan',
@@ -44,7 +44,6 @@ const BACKEND_VISUALS = {
iconCls: 'text-violet-ink',
},
claude: {
- agentOrder: 0,
nativeOrder: 0,
publisher: 'Anthropic',
accent: 'mint',
@@ -56,7 +55,6 @@ const BACKEND_VISUALS = {
iconCls: 'text-cyan-ink',
},
codex: {
- agentOrder: 2,
nativeOrder: 1,
publisher: 'OpenAI',
accent: 'violet',
@@ -68,7 +66,6 @@ const BACKEND_VISUALS = {
iconCls: 'text-gold-foreground',
},
avibe: {
- agentOrder: 3,
nativeOrder: 3,
publisher: 'Avibe',
accent: 'mint',
@@ -80,7 +77,7 @@ const BACKEND_VISUALS = {
iconCls: 'text-mint-ink',
},
} as const satisfies Record<AgentBackendId, Pick<BackendUiMeta,
- 'agentOrder' | 'nativeOrder' | 'publisher' | 'accent' | 'Icon' | 'initials' | 'blockCls' | 'glyphCls' | 'tileCls' | 'iconCls'>>;
+ 'nativeOrder' | 'publisher' | 'accent' | 'Icon' | 'initials' | 'blockCls' | 'glyphCls' | 'tileCls' | 'iconCls'>>;
export const AGENT_BACKENDS = BACKEND_CATALOG.map((backend) => ({
...BACKEND_VISUALS[backend.id],
@@ -88,6 +85,7 @@ export const AGENT_BACKENDS = BACKEND_CATALOG.map((backend) => ({
label: backend.display_name,
defaultCli: backend.default_cli,
defaultEnabled: backend.default_enabled,
+ builtin: backend.builtin,
settingsRoute: backend.settings_route,
descriptionKey: backend.description_key,
capabilities: backend.capabilities,
@@ -135,6 +133,7 @@ export function getBackendUiMeta(id: string): BackendUiMeta {
label: id.replace(/_/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()),
defaultCli: null,
defaultEnabled: false,
+ builtin: false,
settingsRoute: `/settings/backends/${id}`,
descriptionKey: `settings.backends.${id}Description`,
capabilities: {
@@ -144,7 +143,6 @@ export function getBackendUiMeta(id: string): BackendUiMeta {
supports_web_oauth: false,
supports_install: false,
},
- agentOrder: Number.MAX_SAFE_INTEGER,
nativeOrder: Number.MAX_SAFE_INTEGER,
publisher: '',
accent: 'mint',
diff --git a/ui/src/lib/backendAccent.ts b/ui/src/lib/backendAccent.ts
index d3c7c9bdb..aa1efbf35 100644
--- a/ui/src/lib/backendAccent.ts
+++ b/ui/src/lib/backendAccent.ts
@@ -6,9 +6,8 @@
import { AGENT_BACKENDS, isNativeCliBackend, type AgentBackendId, type NativeCliBackend } from './agentBackends';
-export const BACKEND_ORDER = [...AGENT_BACKENDS]
- .sort((left, right) => left.agentOrder - right.agentOrder)
- .map((backend) => backend.id);
+// Catalog order, the built-in Avibe Agent first: the one order every backend list shows.
+export const BACKEND_ORDER = AGENT_BACKENDS.map((backend) => backend.id);
export const NATIVE_BACKEND_ORDER = BACKEND_ORDER.filter(isNativeCliBackend);
export type Backend = AgentBackendId;
diff --git a/vibe/api.py b/vibe/api.py
index db0ae6a4a..b3014347b 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -34,6 +34,7 @@ from config.v2_config import (
config_file_lock,
AGENT_CREDENTIAL_SECTIONS,
config_recovery_refusal,
+ hub_supply_block,
)
from config.v2_settings import (
SettingsStore,
@@ -104,11 +105,13 @@ from vibe import backend_model_catalog
from vibe.i18n import t as backend_t
from modules.agents.catalog import (
AGENT_BACKENDS,
+ BUILTIN_AGENT_BACKENDS,
NATIVE_CLI_BACKENDS,
agent_backend_catalog_payload,
agent_backend_descriptors,
display_name_for_backend,
is_agent_backend,
+ is_builtin_backend,
is_native_cli_backend,
latest_probe_for_backend,
supports_runtime_refresh,
@@ -117,6 +120,7 @@ from modules.agents.catalog import (
)
from modules.agents.subagent_router import list_codex_subagents
from core.vibe_agents import (
+ AgentAlwaysEnabledError,
AgentArchivedEditError,
AgentArchiveError,
AgentNameValidationError,
@@ -779,6 +783,23 @@ def _strip_agent_auth_fields(payload: dict) -> dict:
return {**payload, "agents": cleaned_agents}
+def _reject_builtin_backend_config(payload: dict) -> None:
+ """A built-in backend has no config section, so a request to set one, such as disabling it, fails."""
+ agents = payload.get("agents")
+ if not isinstance(agents, dict):
+ return
+ for backend in BUILTIN_AGENT_BACKENDS:
+ if backend in agents:
+ raise ValueError(
+ backend_t(
+ "errors.builtinBackendConfig",
+ _configured_backend_language(),
+ backend=display_name_for_backend(backend),
+ section=f"agents.{backend}",
+ )
+ )
+
+
def _strip_preserved_config_secrets(payload: dict) -> dict:
"""Drop redacted secret placeholders from generic config saves.
@@ -997,6 +1018,7 @@ def save_config(
# as a read-only projection here rather than accepting a potentially stale
# client snapshot.
payload = {key: value for key, value in payload.items() if key != "model_hub"}
+ _reject_builtin_backend_config(payload)
payload = _strip_agent_auth_fields(payload)
payload = _strip_preserved_config_secrets(payload)
payload = _mark_explicit_audio_asr_enabled(payload)
@@ -1296,7 +1318,6 @@ 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.
@@ -2181,8 +2202,8 @@ def update_vibe_agent(name: str, payload: dict, *, user_context: Any = None) ->
)
except AgentNameValidationError as exc:
return _agent_name_validation_error(exc)
- except AgentArchivedEditError as exc:
- return _agent_archived_edit_error(exc)
+ except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ return _agent_lifecycle_error(exc)
except AgentReferenceRewriteError as exc:
return _agent_reference_rewrite_error(exc)
return {"ok": True, "agent": _vibe_agent_payload(agent)}
@@ -2204,7 +2225,7 @@ def _agent_name_validation_error(exc: AgentNameValidationError) -> dict:
}
-def _agent_archived_edit_error(exc: AgentArchivedEditError) -> dict:
+def _agent_lifecycle_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError) -> dict:
try:
lang = V2Config.load().language
except Exception:
@@ -10001,8 +10022,6 @@ def _hub_backend_connection_auth(config: V2Config, backend: str) -> str:
from vibe.model_hub_runtime.state import EngineStateStore
hub = config.model_hub
- if not hub.enabled:
- return "none"
source_ids = list(dict.fromkeys([
*hub.effective_source_order(backend),
*(hop.source_id for route in hub.agents[backend].routes.values() for hop in route.hops),
@@ -10055,8 +10074,9 @@ async def get_backend_connection(name: str) -> dict:
if not is_agent_backend(name):
return {"ok": False, "error": "unsupported_backend"}
config = await asyncio.to_thread(load_config)
- backend_config = getattr(config.agents, name)
- enabled = bool(backend_config.enabled)
+ builtin = is_builtin_backend(name)
+ backend_config = None if builtin else getattr(config.agents, name)
+ enabled = builtin or bool(backend_config.enabled)
supply_mode = config.model_hub.agents[name].mode
native = is_native_cli_backend(name)
installed = (
@@ -10101,7 +10121,11 @@ async def get_backend_connection(name: str) -> dict:
return result
try:
if supply_mode == "hub":
- result["auth"] = await asyncio.to_thread(_hub_backend_connection_auth, config, name)
+ # A backend the Hub cannot supply now has no credential to run on, whatever is saved.
+ result["auth"] = (
+ "none" if hub_supply_block(name, config.model_hub) is not None
+ else await asyncio.to_thread(_hub_backend_connection_auth, config, name)
+ )
elif name == "opencode":
if not enabled:
return result
diff --git a/vibe/cli.py b/vibe/cli.py
index 3e3e393c9..d07fd6e6e 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -57,7 +57,7 @@ from core.caller_context import (
from core.command_runner import command_line_preview
from core.cron_weekday import ambiguous_weekday_field, weekday_readings
from core.install_integrity import verify_python_environment, verify_site_packages
-from core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentAccessError, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
+from core.vibe_agents import AgentAlwaysEnabledError, AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentAccessError, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
NO_EVENT_EXIT_CODE,
@@ -5690,8 +5690,8 @@ def cmd_agent_update(args):
agent = _agent_store().update(args.name, **kwargs)
_print_cli_payload("agent", agent=_agent_payload(agent), **_agent_value_warning_fields(agent))
return 0
- except AgentArchivedEditError as exc:
- _print_task_error(_agent_archived_edit_cli_error(exc))
+ except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ _print_task_error(_agent_lifecycle_cli_error(exc))
return 1
except Exception as exc:
_print_task_error(exc)
@@ -5703,15 +5703,15 @@ def cmd_agent_set_enabled(args, *, enabled: bool):
agent = _agent_store().set_enabled(args.name, enabled)
_print_cli_payload("agent", agent=_agent_payload(agent))
return 0
- except AgentArchivedEditError as exc:
- _print_task_error(_agent_archived_edit_cli_error(exc))
+ except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ _print_task_error(_agent_lifecycle_cli_error(exc))
return 1
except Exception as exc:
_print_task_error(exc)
return 1
-def _agent_archived_edit_cli_error(exc: AgentArchivedEditError) -> TaskCliError:
+def _agent_lifecycle_cli_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError) -> TaskCliError:
try:
lang = V2Config.load().language
except Exception:
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 9562ca1b2..c1a9b156d 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -6,6 +6,9 @@
},
"errors": {
"agentModelRequired": "Select a model for the {backend} Agent or Session in Avibe before running it.",
+ "builtinBackendConfig": "{backend} is built in and always enabled, so `{section}` cannot be set.",
+ "modelHubDisabled": "Model Hub is disabled on this instance, so {backend} has no model to run on.",
+ "modelGatewayOff": "The model gateway is off, so {backend} has no model to run on. Turn it on in Models, then choose a model.",
"opencodeModelProviderRequired": "Select an OpenCode model with a provider in Avibe, or configure its Model Hub route."
},
"status": {
@@ -390,6 +393,10 @@
}
},
"agentLifecycle": {
+ "agent_always_enabled": {
+ "message": "Agent `{agent}` is the built-in Avibe Agent and is always enabled.",
+ "hint": "You can still change its model, effort, and system prompt."
+ },
"agent_archived_read_only": {
"message": "Agent `{agent}` is archived and cannot be edited.",
"hint": "Archived Agents are read-only and remain available only to existing durable references."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index f4c0c690d..d48f2c03e 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -6,6 +6,9 @@
},
"errors": {
"agentModelRequired": "请先在 Avibe 中为 {backend} Agent 或会话选择模型。",
+ "builtinBackendConfig": "{backend} 是内置后端,始终启用,不能设置 `{section}`。",
+ "modelHubDisabled": "本实例已停用模型中枢,{backend} 没有可用的模型。",
+ "modelGatewayOff": "模型网关已关闭,{backend} 没有可用的模型。请在「模型」页开启网关并选择模型。",
"opencodeModelProviderRequired": "请在 Avibe 中选择带供应商的 OpenCode 模型,或配置它的 Model Hub 路由。"
},
"status": {
@@ -390,6 +393,10 @@
}
},
"agentLifecycle": {
+ "agent_always_enabled": {
+ "message": "Agent `{agent}` 是内置的 Avibe Agent,始终启用。",
+ "hint": "仍可调整它的模型、Effort 与系统提示词。"
+ },
"agent_archived_read_only": {
"message": "Agent `{agent}` 已归档,无法编辑。",
"hint": "已归档 Agent 为只读状态,仅供现有持久引用继续使用。"
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 356be3f6f..5c7a7e2a0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4512,10 +4512,17 @@ def _config_payload_for_context(config: Any, authorization_context: Any) -> dict
def _config_api_payload_for_context(config: Any, authorization_context: Any) -> dict[str, Any]:
"""Return the complete payload exposed by the config API."""
- from config.v2_config import is_model_hub_enabled
+ from config.v2_config import hub_supply_block, is_model_hub_enabled
+ from modules.agents.catalog import AGENT_BACKENDS
payload = _config_payload_for_context(config, authorization_context)
payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
+ # Read-only, like ``capabilities``: why the Model Hub leaves a backend no model to run on.
+ payload["agent_supply_blocks"] = {
+ backend: block
+ for backend in AGENT_BACKENDS
+ if (block := hub_supply_block(backend, config.model_hub)) is not None
+ }
return payload