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.

refactor(models): centralize backend model catalogs (#856)

Call White9c9271958922
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index b8bb0c7ee..6116a2f59 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -34,6 +34,7 @@ from core.caller_context import caller_env_for_platform_payload
from core.resource_governance import governor_from_controller
from core.services.session_fork import pending_native_fork_source
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
+from vibe import backend_model_catalog
from .base import BaseHandler
@@ -813,7 +814,11 @@ class SessionHandler(BaseHandler):
effective_model = explicit_model or agent_model or self.config.claude.default_model
from modules.agents.opencode.utils import normalize_claude_reasoning_effort
- effective_effort = normalize_claude_reasoning_effort(effective_model, explicit_effort)
+ effective_effort = normalize_claude_reasoning_effort(
+ effective_model,
+ explicit_effort,
+ backend_model_catalog.catalog_reasoning_efforts_for_model("claude", effective_model),
+ )
# Determine final system prompt: agent prompt takes precedence over config.
# Always append avibe system prompt injection so transport
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 9eae3b563..2a88d3e72 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -1,11 +1,13 @@
"""Settings and configuration handlers"""
+import asyncio
import logging
from typing import Optional
from modules.agents import get_agent_display_name
from modules.im import MessageContext, InlineKeyboard, InlineButton
from core.modals import RoutingModalData, RoutingModalSelection
+from vibe import backend_model_catalog
from .base import BaseHandler
@@ -446,6 +448,7 @@ class SettingsHandler(BaseHandler):
claude_models = []
codex_agents = []
codex_models = []
+ backend_reasoning_options = {}
if "opencode" in backends_to_load:
try:
@@ -469,9 +472,12 @@ class SettingsHandler(BaseHandler):
agents_result = get_claude_agents(cwd)
if agents_result.get("ok"):
claude_agents = agents_result.get("agents", [])
- models_result = get_claude_models()
+ models_result = await asyncio.to_thread(get_claude_models)
if models_result.get("ok"):
claude_models = models_result.get("models", [])
+ reasoning_options = models_result.get("reasoning_options")
+ if isinstance(reasoning_options, dict):
+ backend_reasoning_options["claude"] = reasoning_options
except Exception as e:
logger.warning(f"Failed to fetch Claude data: {e}")
@@ -479,9 +485,12 @@ class SettingsHandler(BaseHandler):
try:
from vibe.api import codex_agents as get_codex_agents, codex_models as get_codex_models
- models_result = get_codex_models()
+ models_result = await asyncio.to_thread(get_codex_models)
if models_result.get("ok"):
codex_models = models_result.get("models", [])
+ reasoning_options = models_result.get("reasoning_options")
+ if isinstance(reasoning_options, dict):
+ backend_reasoning_options["codex"] = reasoning_options
cwd = self.controller.get_cwd(context)
agents_result = get_codex_agents(cwd)
if agents_result.get("ok"):
@@ -500,6 +509,7 @@ class SettingsHandler(BaseHandler):
claude_models=claude_models,
codex_agents=codex_agents,
codex_models=codex_models,
+ backend_reasoning_options=backend_reasoning_options,
)
def _is_backend_enabled(self, backend: str) -> bool:
@@ -783,6 +793,7 @@ class SettingsHandler(BaseHandler):
claude_models=routing_data.claude_models,
codex_agents=routing_data.codex_agents,
codex_models=routing_data.codex_models,
+ backend_reasoning_options=routing_data.backend_reasoning_options,
selected_backend=visible_selected_backend,
selected_opencode_agent=selection.selected_opencode_agent,
selected_opencode_model=selection.selected_opencode_model,
@@ -833,6 +844,7 @@ class SettingsHandler(BaseHandler):
normalized_claude_reasoning_effort = normalize_claude_reasoning_effort(
claude_model,
claude_reasoning_effort,
+ backend_model_catalog.catalog_reasoning_efforts_for_model("claude", claude_model),
)
if backend == "codex" and codex_agent is _UNSET:
resolved_codex_agent = existing_routing.codex_agent if existing_routing else None
diff --git a/core/modals.py b/core/modals.py
index a9ef58116..1ea0049ab 100644
--- a/core/modals.py
+++ b/core/modals.py
@@ -22,6 +22,7 @@ class RoutingModalData:
claude_models: list[str]
codex_agents: list[str]
codex_models: list[str]
+ backend_reasoning_options: dict[str, dict[str, list[dict[str, str]]]]
def as_kwargs(self) -> dict[str, Any]:
return {
@@ -35,6 +36,7 @@ class RoutingModalData:
"claude_models": self.claude_models,
"codex_agents": self.codex_agents,
"codex_models": self.codex_models,
+ "backend_reasoning_options": self.backend_reasoning_options,
}
diff --git a/docs/plans/backend-model-catalog-service.md b/docs/plans/backend-model-catalog-service.md
new file mode 100644
index 000000000..a339df86b
--- /dev/null
+++ b/docs/plans/backend-model-catalog-service.md
@@ -0,0 +1,152 @@
+# Shared backend model catalog service
+
+**Status:** implemented for review
+**Scope:** Claude Code and Codex model discovery for Web, IM, and `vibe agent models`
+**Supersedes:** PR #853 implementation approach (requirements and regression cases remain valid)
+
+## Background
+
+Claude Code and Codex model choices are currently assembled in `vibe/api.py`,
+while reasoning-effort choices are partially duplicated across Python IM
+renderers and TypeScript. Adding a newly released model therefore requires an
+Avibe release, and incremental attempts to add remote/live sources exposed four
+coupled concerns: source precedence, hidden-model withdrawal, cache freshness,
+and request-path latency.
+
+The product requirement is narrower and cleaner:
+
+1. silently refresh a GitHub-owned catalog for Claude Code and Codex;
+2. merge it with local and bundled knowledge;
+3. expose per-model reasoning efforts to every selection surface;
+4. never delay a Web or IM interaction on network or CLI discovery.
+
+## Goals
+
+- One shared catalog contract and merge implementation for Claude and Codex.
+- Immediate snapshots from memory/disk/bundled/local sources.
+- Background-only remote refresh with strict validation and atomic persistence.
+- Source visibility is authoritative: hidden entries are tombstones and cannot
+ be reintroduced by lower-priority fallbacks.
+- Web, Slack, Discord, Telegram, and Feishu consume the same per-model effort map.
+- Existing free-form model entry remains supported for unreleased/custom models.
+
+## Non-goals
+
+- No synchronous `codex debug models` probe. Codex's maintained
+ `~/.codex/models_cache.json` is the local runtime source; request paths never
+ launch the Codex CLI.
+- No OpenCode redesign. Its live provider server remains its source of truth.
+- No rejection of custom model or reasoning strings at persistence boundaries.
+- No service restart or migration of user configuration.
+
+## Contract
+
+The bundled and remote JSON use schema version 1:
+
+```json
+{
+ "schema_version": 1,
+ "backends": {
+ "codex": {
+ "models": [
+ {
+ "id": "gpt-5.6-terra",
+ "label": "GPT-5.6-Terra",
+ "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
+ "visibility": "visible",
+ "priority": 10
+ }
+ ]
+ }
+ }
+}
+```
+
+Normalized snapshot returned to callers:
+
+```json
+{
+ "ok": true,
+ "backend": "codex",
+ "models": ["gpt-5.6-terra"],
+ "model_labels": {"gpt-5.6-terra": "GPT-5.6-Terra"},
+ "reasoning_options": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"}
+ ]
+ },
+ "catalog_refresh_pending": false,
+ "sources": ["remote", "local", "bundled"]
+}
+```
+
+`models`, `model_labels`, and `reasoning_options` are the only selection data
+consumed by UI/IM adapters. Source details are diagnostic metadata.
+
+## Source and merge rules
+
+### Claude
+
+1. cached remote GitHub catalog;
+2. bundled catalog;
+3. repository Claude catalog and aliases;
+4. explicit model values from `~/.claude/settings.json`.
+
+### Codex
+
+1. hidden tombstones from `~/.codex/models_cache.json`;
+2. hidden tombstones from the cached remote GitHub catalog;
+3. visible entries from the cached remote GitHub catalog;
+4. bundled catalog;
+5. remaining visible entries from `~/.codex/models_cache.json`;
+6. legacy built-in fallback ids;
+7. explicit model and migration ids from `~/.codex/config.toml`.
+
+Hidden decisions from the runtime or remote catalog are tombstones; lower-priority
+visible entries cannot resurrect those ids. Remote and bundled entries determine
+the presentation order so newly published models stay prominent, while reasoning
+efforts from the local Codex cache override matching catalog entries because they
+reflect the installed CLI's account-visible capabilities. Lower sources may fill
+missing metadata but cannot replace populated values.
+
+## Refresh model
+
+- `snapshot()` never performs network I/O.
+- If the persisted remote payload is absent/stale, `snapshot()` starts one
+ daemon refresh thread and returns immediately.
+- Remote payloads are strictly validated before replacing the cache.
+- Success/failure timestamps use separate TTLs; writes are atomic.
+- Responses expose `catalog_refresh_pending`. The shared TypeScript loader delivers the
+ immediate snapshot, then performs bounded silent re-fetches while pending.
+
+## Integration
+
+- `vibe/api.py`: `claude_models()` and `codex_models()` become thin adapters to
+ the service; `agent_model_options()` keeps its existing public envelope.
+- `core/modals.py`: routing data carries Codex per-model reasoning options.
+- IM adapters: select efforts through one shared Python resolver.
+- Web: `fetchBackendModels` handles Claude and Codex identically; effort
+ resolution consults per-model options for both.
+- Claude dispatch keeps its existing normalization behavior, fed by the same
+ bundled/remote effort lookup rather than duplicated model-name heuristics.
+
+## Verification matrix
+
+- remote visible + bundled visible: remote metadata wins, no duplicate;
+- remote hidden + local/bundled visible: absent;
+- local Codex hidden + remote visible: absent;
+- malformed remote payload: previous cache retained;
+- first request with stale cache: returns before network refresh completes;
+- refreshed snapshot: newly fetched model/effort appears without restart;
+- backend/model switch: stale model and effort options cannot leak;
+- Slack, Discord, Telegram, Feishu: catalog-only effort such as `ultra` renders;
+- existing custom model: remains typeable/preservable.
+
+## Delivery
+
+- Unit: parser, merge, tombstones, cache TTL, local adapters, effort resolver.
+- Contract: API snapshot and `agent_model_options()` envelopes.
+- Scenario: no catalog scenario exists; platform payload tests cover IM surfaces.
+- Residual manual: local Incus cross-platform picker verification is deferred
+ until the PR is review-clean and CI-green.
diff --git a/modules/agents/opencode/__init__.py b/modules/agents/opencode/__init__.py
index 935389913..f4193d81e 100644
--- a/modules/agents/opencode/__init__.py
+++ b/modules/agents/opencode/__init__.py
@@ -12,6 +12,7 @@ from .utils import (
build_claude_reasoning_options,
build_codex_reasoning_options,
build_reasoning_effort_options,
+ resolve_model_reasoning_options,
)
__all__ = [
@@ -20,6 +21,7 @@ __all__ = [
"build_claude_reasoning_options",
"build_codex_reasoning_options",
"build_reasoning_effort_options",
+ "resolve_model_reasoning_options",
]
diff --git a/modules/agents/opencode/utils.py b/modules/agents/opencode/utils.py
index 7680ed24b..aa0412a88 100644
--- a/modules/agents/opencode/utils.py
+++ b/modules/agents/opencode/utils.py
@@ -15,7 +15,7 @@ _REASONING_FALLBACK_OPTIONS = [
{"value": "high", "label": "High"},
]
-_REASONING_VARIANT_ORDER = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
+_REASONING_VARIANT_ORDER = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]
_REASONING_VARIANT_LABELS = {
"none": "None",
@@ -25,6 +25,7 @@ _REASONING_VARIANT_LABELS = {
"high": "High",
"xhigh": "Extra High",
"max": "Max",
+ "ultra": "Ultra",
}
_UTILITY_MODEL_KEYWORDS = ["embedding", "tts", "whisper", "ada", "davinci", "turbo-instruct"]
@@ -501,7 +502,7 @@ def format_claude_model_label(model: object) -> str:
return model_id
-def build_codex_reasoning_options() -> List[Dict[str, str]]:
+def build_codex_reasoning_options(reasoning_efforts: Optional[List[str]] = None) -> List[Dict[str, str]]:
"""Return the canonical Codex reasoning-effort option list.
The returned format mirrors ``build_reasoning_effort_options`` so that
@@ -509,7 +510,14 @@ def build_codex_reasoning_options() -> List[Dict[str, str]]:
helper logic.
"""
options: List[Dict[str, str]] = [{"value": "__default__", "label": "(Default)"}]
- for effort in _CODEX_REASONING_EFFORTS:
+ seen: set[str] = set()
+ for effort in reasoning_efforts if reasoning_efforts is not None else _CODEX_REASONING_EFFORTS:
+ if not isinstance(effort, str):
+ continue
+ effort = effort.strip()
+ if not effort or effort in seen:
+ continue
+ seen.add(effort)
options.append(
{
"value": effort,
@@ -519,7 +527,10 @@ def build_codex_reasoning_options() -> List[Dict[str, str]]:
return options
-def build_claude_reasoning_options(target_model: Optional[str]) -> List[Dict[str, str]]:
+def build_claude_reasoning_options(
+ target_model: Optional[str],
+ reasoning_efforts: Optional[List[str]] = None,
+) -> List[Dict[str, str]]:
"""Return the canonical Claude reasoning-effort option list for a model.
Claude currently supports `low` / `medium` / `high` broadly. Newer
@@ -527,14 +538,22 @@ def build_claude_reasoning_options(target_model: Optional[str]) -> List[Dict[str
4.7, 4.6, Sonnet 5, and Sonnet 4.6 also support `max`.
"""
- efforts = list(_CLAUDE_REASONING_EFFORTS)
- if _supports_claude_xhigh_reasoning(target_model):
- efforts.append("xhigh")
- if _supports_claude_max_reasoning(target_model):
- efforts.append("max")
+ efforts = list(reasoning_efforts) if reasoning_efforts is not None else list(_CLAUDE_REASONING_EFFORTS)
+ if reasoning_efforts is None:
+ if _supports_claude_xhigh_reasoning(target_model):
+ efforts.append("xhigh")
+ if _supports_claude_max_reasoning(target_model):
+ efforts.append("max")
options: List[Dict[str, str]] = [{"value": "__default__", "label": "(Default)"}]
+ seen: set[str] = set()
for effort in efforts:
+ if not isinstance(effort, str):
+ continue
+ effort = effort.strip()
+ if not effort or effort in seen:
+ continue
+ seen.add(effort)
options.append(
{
"value": effort,
@@ -544,10 +563,31 @@ def build_claude_reasoning_options(target_model: Optional[str]) -> List[Dict[str
return options
-def normalize_claude_reasoning_effort(target_model: Optional[str], effort: Optional[str]) -> Optional[str]:
+def resolve_model_reasoning_options(
+ reasoning_options: Optional[Dict[str, List[Dict[str, str]]]],
+ target_model: Optional[str],
+ fallback: List[Dict[str, str]],
+) -> List[Dict[str, str]]:
+ """Resolve per-model catalog options without leaking another backend's state."""
+ if isinstance(reasoning_options, dict):
+ model_key = (target_model or "").strip()
+ if model_key == "__default__":
+ model_key = ""
+ for key in (model_key, ""):
+ entries = reasoning_options.get(key)
+ if isinstance(entries, list) and entries:
+ return entries
+ return fallback
+
+
+def normalize_claude_reasoning_effort(
+ target_model: Optional[str],
+ effort: Optional[str],
+ reasoning_efforts: Optional[List[str]] = None,
+) -> Optional[str]:
"""Return a Claude effort only when it is valid for the target model."""
if not effort:
return None
- allowed = {item["value"] for item in build_claude_reasoning_options(target_model)}
+ allowed = {item["value"] for item in build_claude_reasoning_options(target_model, reasoning_efforts)}
return effort if effort in allowed else None
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 39174bf6a..69e9fa73c 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -26,6 +26,7 @@ from modules.agents.opencode.utils import (
build_codex_reasoning_options,
format_claude_model_label,
build_reasoning_effort_options,
+ resolve_model_reasoning_options,
resolve_opencode_allowed_providers,
resolve_opencode_default_model,
resolve_opencode_provider_preferences,
@@ -1457,6 +1458,7 @@ class DiscordBot(BaseIMClient):
claude_models: list,
codex_agents: list,
codex_models: list,
+ backend_reasoning_options: Optional[dict] = None,
):
interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
@@ -1783,15 +1785,21 @@ class DiscordBot(BaseIMClient):
model_select.callback = claude_model_callback
self.add_item(model_select)
- claude_reasoning_entries = build_claude_reasoning_options(
+ target_claude_model = (
self.claude_model if self.claude_model not in (None, "__default__") else None
)
+ claude_reasoning_entries = resolve_model_reasoning_options(
+ (backend_reasoning_options or {}).get("claude"),
+ target_claude_model,
+ build_claude_reasoning_options(target_claude_model),
+ )
selected_cl_reasoning = (
self.claude_reasoning if self.claude_reasoning not in (None, "__default__") else "__default__"
)
available_cl_reasoning = {entry.get("value") for entry in claude_reasoning_entries}
if selected_cl_reasoning not in available_cl_reasoning:
selected_cl_reasoning = "__default__"
+ self.claude_reasoning = None
reasoning_options = []
for entry in claude_reasoning_entries:
value = entry.get("value")
@@ -1884,18 +1892,32 @@ class DiscordBot(BaseIMClient):
async def codex_model_callback(select_interaction: discord.Interaction):
if model_select.values:
self.codex_model = model_select.values[0]
- await select_interaction.response.defer()
+ self.codex_reasoning = None
+ self._render()
+ updated_embed = discord.Embed(
+ title=self._content(),
+ description=self.outer._t("discord.routingSubtitle"),
+ )
+ await select_interaction.response.edit_message(embed=updated_embed, view=self)
model_select.callback = codex_model_callback
self.add_item(model_select)
- codex_reasoning_entries = build_codex_reasoning_options()
+ target_codex_model = (
+ self.codex_model if self.codex_model not in (None, "__default__") else None
+ )
+ codex_reasoning_entries = resolve_model_reasoning_options(
+ (backend_reasoning_options or {}).get("codex"),
+ target_codex_model,
+ build_codex_reasoning_options(),
+ )
selected_cx_reasoning = (
self.codex_reasoning if self.codex_reasoning not in (None, "__default__") else "__default__"
)
available_cx_reasoning = {entry.get("value") for entry in codex_reasoning_entries}
if selected_cx_reasoning not in available_cx_reasoning:
selected_cx_reasoning = "__default__"
+ self.codex_reasoning = None
reasoning_options = []
for entry in codex_reasoning_entries:
value = entry.get("value")
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 8d1cb92f3..eda663633 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -28,6 +28,7 @@ from modules.agents.opencode.utils import (
format_claude_model_label,
build_opencode_model_option_items,
build_reasoning_effort_options,
+ resolve_model_reasoning_options,
resolve_opencode_allowed_providers,
resolve_opencode_provider_preferences,
)
@@ -2514,6 +2515,7 @@ class FeishuBot(BaseIMClient):
"claude_models": kwargs.get("claude_models", []),
"codex_agents": kwargs.get("codex_agents", []),
"codex_models": kwargs.get("codex_models", []),
+ "backend_reasoning_options": kwargs.get("backend_reasoning_options", {}),
}
# --- Backend selector options ---
@@ -2601,6 +2603,7 @@ class FeishuBot(BaseIMClient):
claude_models = kwargs.get("claude_models", [])
codex_agents = kwargs.get("codex_agents", [])
codex_models = kwargs.get("codex_models", [])
+ backend_reasoning_options = kwargs.get("backend_reasoning_options", {})
def _routing_value(field_name: str) -> Optional[str]:
if field_name in draft_routing:
@@ -2738,7 +2741,13 @@ class FeishuBot(BaseIMClient):
)
cl_current_re = _routing_value("claude_reasoning_effort")
- cl_re_defs = build_claude_reasoning_options(cl_current_model)
+ cl_re_defs = resolve_model_reasoning_options(
+ backend_reasoning_options.get("claude"),
+ cl_current_model,
+ build_claude_reasoning_options(cl_current_model),
+ )
+ if cl_current_re not in {item["value"] for item in cl_re_defs}:
+ cl_current_re = None
cl_re_options = []
for item in cl_re_defs:
cl_re_options.append({"text": {"tag": "plain_text", "content": item["label"]}, "value": item["value"]})
@@ -2790,11 +2799,18 @@ class FeishuBot(BaseIMClient):
}
)
- codex_re_defs = build_codex_reasoning_options()
+ cx_current_model = _routing_value("codex_model")
+ codex_re_defs = resolve_model_reasoning_options(
+ backend_reasoning_options.get("codex"),
+ cx_current_model,
+ build_codex_reasoning_options(),
+ )
cx_re_options = []
for item in codex_re_defs:
cx_re_options.append({"text": {"tag": "plain_text", "content": item["label"]}, "value": item["value"]})
cx_current_re = _routing_value("codex_reasoning_effort")
+ if cx_current_re not in {item["value"] for item in codex_re_defs}:
+ cx_current_re = None
form_elements.append({"tag": "markdown", "content": t("modal.routing.codexReasoningEffort")})
form_elements.append(
{
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 4b538ab54..12c53a9c2 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -33,6 +33,7 @@ from modules.agents.opencode.utils import (
build_codex_reasoning_options,
format_claude_model_label,
build_reasoning_effort_options,
+ resolve_model_reasoning_options,
resolve_opencode_allowed_providers,
resolve_opencode_provider_preferences,
)
@@ -3310,6 +3311,7 @@ class SlackBot(BaseIMClient):
claude_models: list = None,
codex_agents: list = None,
codex_models: list = None,
+ backend_reasoning_options: dict = None,
selected_backend: object = _UNSET,
selected_opencode_agent: object = _UNSET,
selected_opencode_model: object = _UNSET,
@@ -3676,7 +3678,11 @@ class SlackBot(BaseIMClient):
"initial_option": initial_cl_model,
}
- cl_reasoning_entries = build_claude_reasoning_options(current_cl_model)
+ cl_reasoning_entries = resolve_model_reasoning_options(
+ (backend_reasoning_options or {}).get("claude"),
+ current_cl_model,
+ build_claude_reasoning_options(current_cl_model),
+ )
selected_cl_reasoning = (
current_cl_reasoning if current_cl_reasoning not in (None, "__default__") else "__default__"
)
@@ -3843,7 +3849,11 @@ class SlackBot(BaseIMClient):
}
# Build reasoning effort options from centralized Codex definition
- codex_reasoning_entries = build_codex_reasoning_options()
+ codex_reasoning_entries = resolve_model_reasoning_options(
+ (backend_reasoning_options or {}).get("codex"),
+ current_cx_model,
+ build_codex_reasoning_options(),
+ )
selected_cx_reasoning = (
current_cx_reasoning if current_cx_reasoning not in (None, "__default__") else "__default__"
)
@@ -4100,6 +4110,7 @@ class SlackBot(BaseIMClient):
claude_models: list = None,
codex_agents: list = None,
codex_models: list = None,
+ backend_reasoning_options: dict = None,
):
"""Open a modal dialog for agent/model routing settings"""
self._ensure_clients()
@@ -4116,6 +4127,7 @@ class SlackBot(BaseIMClient):
claude_models=claude_models,
codex_agents=codex_agents,
codex_models=codex_models,
+ backend_reasoning_options=backend_reasoning_options,
)
try:
@@ -4139,6 +4151,7 @@ class SlackBot(BaseIMClient):
claude_models: list = None,
codex_agents: list = None,
codex_models: list = None,
+ backend_reasoning_options: dict = None,
selected_backend: Optional[str] = None,
selected_opencode_agent: Optional[str] = None,
selected_opencode_model: Optional[str] = None,
@@ -4165,6 +4178,7 @@ class SlackBot(BaseIMClient):
claude_models=claude_models,
codex_agents=codex_agents,
codex_models=codex_models,
+ backend_reasoning_options=backend_reasoning_options,
selected_backend=selected_backend,
selected_opencode_agent=selected_opencode_agent,
selected_opencode_model=selected_opencode_model,
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index 97d7ea4c6..83e8ad3ff 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -51,6 +51,7 @@ class _TelegramRoutingState:
claude_agents: list[Any]
claude_models: list[Any]
codex_models: list[Any]
+ backend_reasoning_options: dict[str, dict[str, list[dict[str, str]]]]
backend: str
opencode_agent: Optional[str] = None
opencode_model: Optional[str] = None
@@ -1500,6 +1501,7 @@ class TelegramBot(BaseIMClient):
claude_agents=list(kwargs.get("claude_agents") or []),
claude_models=list(kwargs.get("claude_models") or []),
codex_models=list(kwargs.get("codex_models") or []),
+ backend_reasoning_options=dict(kwargs.get("backend_reasoning_options") or {}),
backend=backend,
opencode_agent=getattr(current_routing, "opencode_agent", None),
opencode_model=current_model if backend == "opencode" else None,
@@ -1510,6 +1512,30 @@ class TelegramBot(BaseIMClient):
codex_model=current_model if backend == "codex" else None,
codex_reasoning_effort=current_effort if backend == "codex" else None,
)
+ if backend in {"claude", "codex"}:
+ from modules.agents.opencode.utils import (
+ build_claude_reasoning_options,
+ build_codex_reasoning_options,
+ resolve_model_reasoning_options,
+ )
+
+ target_model = state.claude_model if backend == "claude" else state.codex_model
+ fallback = (
+ build_claude_reasoning_options(target_model)
+ if backend == "claude"
+ else build_codex_reasoning_options()
+ )
+ available_efforts = {
+ entry.get("value")
+ for entry in resolve_model_reasoning_options(
+ state.backend_reasoning_options.get(backend),
+ target_model,
+ fallback,
+ )
+ }
+ effort_field = f"{backend}_reasoning_effort"
+ if getattr(state, effort_field) not in available_efforts:
+ setattr(state, effort_field, None)
text, keyboard = self._render_routing_state(state)
message_id = await self.send_message_with_buttons(context, text, keyboard)
state.message_id = message_id
@@ -1737,6 +1763,7 @@ class TelegramBot(BaseIMClient):
build_codex_reasoning_options,
build_opencode_model_option_items,
build_reasoning_effort_options,
+ resolve_model_reasoning_options,
resolve_opencode_allowed_providers,
resolve_opencode_default_model,
resolve_opencode_provider_preferences,
@@ -1805,7 +1832,11 @@ class TelegramBot(BaseIMClient):
self._option_label(None if entry.get("value") == "__default__" else str(entry.get("value"))),
None if entry.get("value") == "__default__" else str(entry.get("value")),
)
- for entry in build_claude_reasoning_options(state.claude_model)
+ for entry in resolve_model_reasoning_options(
+ state.backend_reasoning_options.get("claude"),
+ state.claude_model,
+ build_claude_reasoning_options(state.claude_model),
+ )
if entry.get("value")
]
if field == "codex_model":
@@ -1813,10 +1844,17 @@ class TelegramBot(BaseIMClient):
if field == "codex_reasoning_effort":
return [
(
- self._option_label(None if entry.get("value") == "__default__" else str(entry.get("value"))),
+ self._option_label(
+ None if entry.get("value") == "__default__" else str(entry.get("value")),
+ str(entry.get("label") or entry.get("value") or ""),
+ ),
None if entry.get("value") == "__default__" else str(entry.get("value")),
)
- for entry in build_codex_reasoning_options()
+ for entry in resolve_model_reasoning_options(
+ state.backend_reasoning_options.get("codex"),
+ state.codex_model,
+ build_codex_reasoning_options(),
+ )
if entry.get("value")
]
return []
@@ -1830,6 +1868,8 @@ class TelegramBot(BaseIMClient):
state.claude_reasoning_effort = None
if field == "claude_model" and value is not None:
state.claude_reasoning_effort = None
+ if field == "codex_model":
+ state.codex_reasoning_effort = None
state.picker_field = None
state.picker_page = 0
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
new file mode 100644
index 000000000..1dcd3bc18
--- /dev/null
+++ b/tests/test_backend_model_catalog.py
@@ -0,0 +1,404 @@
+import builtins
+import json
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from vibe import backend_model_catalog
+
+
+class _FakeResponse:
+ def __init__(self, payload: dict):
+ self.payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return json.dumps(self.payload).encode("utf-8")
+
+
[email protected](autouse=True)
+def _reset_remote_cache(monkeypatch):
+ backend_model_catalog._REMOTE_MEMORY_CACHE.clear()
+ monkeypatch.setattr(backend_model_catalog, "_REMOTE_REFRESH_IN_FLIGHT", False)
+ yield
+ backend_model_catalog._REMOTE_MEMORY_CACHE.clear()
+
+
+def test_backend_model_entries_normalize_runtime_catalog_shape():
+ catalog = {
+ "schema_version": 1,
+ "backends": {
+ "codex": {
+ "models": [
+ "gpt-custom",
+ {
+ "slug": "gpt-5.6-sol",
+ "display_name": "GPT-5.6-Sol",
+ "visibility": "list",
+ "supported_reasoning_levels": [
+ {"effort": "low"},
+ {"effort": "ultra"},
+ ],
+ },
+ ]
+ }
+ },
+ }
+
+ assert backend_model_catalog.backend_model_entries("codex", catalog) == [
+ {"id": "gpt-custom"},
+ {
+ "id": "gpt-5.6-sol",
+ "label": "GPT-5.6-Sol",
+ "visibility": "list",
+ "reasoning_efforts": ["low", "ultra"],
+ },
+ ]
+
+
+def test_merge_sources_applies_tombstones_and_fills_missing_metadata():
+ merged = backend_model_catalog.merge_model_sources(
+ [
+ (
+ "remote",
+ [
+ {"id": "hidden-model", "visibility": "hidden"},
+ {"id": "shared-model", "label": "Remote label"},
+ ],
+ ),
+ (
+ "local",
+ [
+ {"id": "hidden-model", "reasoning_efforts": ["ultra"]},
+ {"id": "shared-model", "reasoning_efforts": ["low", "high"]},
+ {"id": "local-model"},
+ ],
+ ),
+ ]
+ )
+
+ assert [entry["id"] for entry in merged] == ["shared-model", "local-model"]
+ assert merged[0] == {
+ "id": "shared-model",
+ "label": "Remote label",
+ "reasoning_efforts": ["low", "high"],
+ "source": "remote",
+ }
+
+
+def test_codex_local_hidden_tombstone_overrides_remote_visible(monkeypatch, tmp_path):
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "models_cache.json").write_text(
+ json.dumps(
+ {
+ "models": [
+ {"slug": "account-hidden", "visibility": "hide"},
+ {"slug": "account-visible", "visibility": "list"},
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "load_cached_remote_catalog",
+ lambda **kwargs: {
+ "schema_version": 1,
+ "backends": {
+ "codex": {
+ "models": [
+ {"id": "account-hidden"},
+ {"id": "remote-model"},
+ ]
+ }
+ },
+ },
+ )
+ monkeypatch.setattr(backend_model_catalog, "load_bundled_catalog", lambda: {})
+
+ snapshot = backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=False)
+
+ assert "account-hidden" not in snapshot["models"]
+ assert snapshot["models"][:2] == ["remote-model", "account-visible"]
+
+
+def test_codex_local_efforts_override_remote_metadata(monkeypatch, tmp_path):
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "models_cache.json").write_text(
+ json.dumps(
+ {
+ "models": [
+ {
+ "slug": "shared-model",
+ "visibility": "list",
+ "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}],
+ }
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "load_cached_remote_catalog",
+ lambda **kwargs: {
+ "schema_version": 1,
+ "backends": {
+ "codex": {
+ "models": [
+ {
+ "id": "shared-model",
+ "reasoning_efforts": ["low", "high", "ultra"],
+ }
+ ]
+ }
+ },
+ },
+ )
+ monkeypatch.setattr(backend_model_catalog, "load_bundled_catalog", lambda: {})
+
+ snapshot = backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=False)
+
+ assert [entry["value"] for entry in snapshot["reasoning_options"]["shared-model"]] == [
+ "__default__",
+ "low",
+ "high",
+ ]
+
+
+def test_claude_snapshot_merges_configured_custom_models(monkeypatch, tmp_path):
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ (claude_home / "settings.json").write_text(
+ json.dumps(
+ {
+ "model": "custom-claude-model",
+ "env": {"ANTHROPIC_SMALL_FAST_MODEL": "custom-fast-model"},
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(backend_model_catalog.Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(backend_model_catalog, "load_cached_remote_catalog", lambda **kwargs: {})
+
+ snapshot = backend_model_catalog.backend_model_snapshot("claude", schedule_refresh=False)
+
+ assert "custom-claude-model" in snapshot["models"]
+ assert "custom-fast-model" in snapshot["models"]
+ assert snapshot["model_labels"]["claude-opus-4-6"] == "claude-opus-4-6 [1M]"
+
+
+def test_remote_hidden_tombstone_overrides_stale_local_visible(monkeypatch, tmp_path):
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "models_cache.json").write_text(
+ json.dumps({"models": [{"slug": "retired-model", "visibility": "list"}]}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "load_cached_remote_catalog",
+ lambda **kwargs: {
+ "schema_version": 1,
+ "backends": {
+ "codex": {
+ "models": [{"id": "retired-model", "visibility": "hidden"}]
+ }
+ },
+ },
+ )
+ monkeypatch.setattr(backend_model_catalog, "load_bundled_catalog", lambda: {})
+
+ snapshot = backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=False)
+
+ assert "retired-model" not in snapshot["models"]
+
+
+def test_snapshot_returns_immediately_while_remote_refresh_runs(monkeypatch, tmp_path):
+ refresh_started = threading.Event()
+ release_refresh = threading.Event()
+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setattr(backend_model_catalog, "load_bundled_catalog", lambda: {})
+
+ def slow_refresh(url=None):
+ refresh_started.set()
+ release_refresh.wait(timeout=2)
+ return {}
+
+ monkeypatch.setattr(backend_model_catalog, "refresh_remote_catalog_now", slow_refresh)
+
+ started_at = time.monotonic()
+ snapshot = backend_model_catalog.backend_model_snapshot("claude")
+ elapsed = time.monotonic() - started_at
+
+ assert elapsed < 0.5
+ assert refresh_started.wait(timeout=1)
+ assert snapshot["catalog_refresh_pending"] is True
+ release_refresh.set()
+ deadline = time.monotonic() + 1
+ while backend_model_catalog._REMOTE_REFRESH_IN_FLIGHT and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert backend_model_catalog._REMOTE_REFRESH_IN_FLIGHT is False
+
+
+def test_refresh_remote_catalog_persists_validated_cache(monkeypatch, tmp_path):
+ payload = {
+ "schema_version": 1,
+ "backends": {
+ "claude": {
+ "models": [{"id": "claude-fable-6", "reasoning_efforts": ["low", "max"]}]
+ }
+ },
+ }
+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setattr(
+ backend_model_catalog.urllib.request,
+ "urlopen",
+ lambda request, timeout: _FakeResponse(payload),
+ )
+
+ catalog = backend_model_catalog.refresh_remote_catalog_now("https://example.test/catalog.json")
+
+ assert backend_model_catalog.backend_model_entries("claude", catalog)[0]["id"] == "claude-fable-6"
+ persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))
+ assert persisted["catalog"] == catalog
+ assert persisted["error"] is None
+
+
+def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):
+ previous_catalog = {
+ "schema_version": 1,
+ "backends": {"claude": {"models": [{"id": "claude-fable-6"}]}},
+ }
+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setattr(
+ backend_model_catalog.urllib.request,
+ "urlopen",
+ lambda request, timeout: _FakeResponse({"schema_version": 2, "models": []}),
+ )
+ backend_model_catalog._write_cached_remote_payload(
+ {"fetched_at": 100.0, "catalog": previous_catalog, "error": None}
+ )
+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)
+ monkeypatch.setattr(backend_model_catalog, "_REMOTE_REFRESH_IN_FLIGHT", True)
+
+ backend_model_catalog._refresh_remote_catalog_worker()
+
+ persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))
+ assert persisted["catalog"] == previous_catalog
+ assert persisted["fetched_at"] == 100.0
+ assert persisted["failed_at"] == 200.0
+ assert "Unsupported backend model catalog schema version" in persisted["error"]
+
+
+def test_fetch_remote_catalog_rejects_invalid_model_entries(monkeypatch):
+ monkeypatch.setattr(
+ backend_model_catalog.urllib.request,
+ "urlopen",
+ lambda request, timeout: _FakeResponse(
+ {
+ "schema_version": 1,
+ "backends": {"codex": {"models": [{"label": "missing id"}]}},
+ }
+ ),
+ )
+
+ with pytest.raises(ValueError, match="invalid model entry"):
+ backend_model_catalog.fetch_remote_catalog("https://example.test/catalog.json")
+
+
+ "model_entry, error",
+ [
+ ({"id": "gpt-invalid", "visibility": "sometimes"}, "invalid visibility"),
+ ({"id": "gpt-invalid", "priority": "first"}, "invalid priority"),
+ ({"id": "gpt-invalid", "reasoning_efforts": "ultra"}, "invalid reasoning efforts"),
+ ],
+)
+def test_fetch_remote_catalog_rejects_malformed_model_metadata(monkeypatch, model_entry, error):
+ monkeypatch.setattr(
+ backend_model_catalog.urllib.request,
+ "urlopen",
+ lambda request, timeout: _FakeResponse(
+ {
+ "schema_version": 1,
+ "backends": {"codex": {"models": [model_entry]}},
+ }
+ ),
+ )
+
+ with pytest.raises(ValueError, match=error):
+ backend_model_catalog.fetch_remote_catalog("https://example.test/catalog.json")
+
+
+def test_fetch_remote_catalog_rejects_unknown_backend(monkeypatch):
+ monkeypatch.setattr(
+ backend_model_catalog.urllib.request,
+ "urlopen",
+ lambda request, timeout: _FakeResponse(
+ {
+ "schema_version": 1,
+ "backends": {"codxe": {"models": [{"id": "gpt-typo"}]}},
+ }
+ ),
+ )
+
+ with pytest.raises(ValueError, match="unsupported backend"):
+ backend_model_catalog.fetch_remote_catalog("https://example.test/catalog.json")
+
+
+def test_bundled_codex_56_efforts_include_ultra():
+ snapshot = backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=False)
+
+ values = {
+ entry["value"]
+ for entry in snapshot["reasoning_options"]["gpt-5.6-terra"]
+ }
+ assert "ultra" in values
+
+
+def test_codex_catalog_readers_expand_codex_home(monkeypatch, tmp_path):
+ codex_home = tmp_path / "codex-state"
+ codex_home.mkdir()
+ (codex_home / "models_cache.json").write_text(
+ json.dumps({"models": [{"slug": "gpt-expanded", "visibility": "list"}]}),
+ encoding="utf-8",
+ )
+ (codex_home / "config.toml").write_text('model = "gpt-configured"', encoding="utf-8")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("CODEX_HOME", "~/codex-state")
+
+ assert backend_model_catalog._read_codex_models_cache() == [
+ {"id": "gpt-expanded", "visibility": "list"}
+ ]
+ assert backend_model_catalog._read_codex_config_models()[0]["id"] == "gpt-configured"
+
+
+def test_parse_toml_falls_back_to_tomli_when_tomllib_is_unavailable(monkeypatch):
+ real_import = builtins.__import__
+ fallback = SimpleNamespace(loads=lambda raw: {"model": "gpt-python-310"})
+
+ def fake_import(name, *args, **kwargs):
+ if name == "tomllib":
+ raise ModuleNotFoundError("No module named 'tomllib'")
+ if name == "tomli":
+ return fallback
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+
+ assert backend_model_catalog._parse_toml('model = "gpt-python-310"') == {
+ "model": "gpt-python-310"
+ }
diff --git a/tests/test_claude_reasoning_options.py b/tests/test_claude_reasoning_options.py
index b3d7a38da..614606b84 100644
--- a/tests/test_claude_reasoning_options.py
+++ b/tests/test_claude_reasoning_options.py
@@ -20,6 +20,7 @@ _utils = _load_utils_module()
build_claude_reasoning_options = _utils.build_claude_reasoning_options
format_claude_model_label = _utils.format_claude_model_label
normalize_claude_reasoning_effort = _utils.normalize_claude_reasoning_effort
+resolve_model_reasoning_options = _utils.resolve_model_reasoning_options
def test_claude_reasoning_options_default_to_low_medium_high() -> None:
@@ -90,6 +91,29 @@ def test_claude_reasoning_options_add_xhigh_for_opus_aliases() -> None:
]
+def test_catalog_efforts_support_future_models_without_code_changes() -> None:
+ options = build_claude_reasoning_options("claude-future-6", ["low", "ultra"])
+
+ assert [item["value"] for item in options] == ["__default__", "low", "ultra"]
+ assert normalize_claude_reasoning_effort("claude-future-6", "ultra", ["low", "ultra"]) == "ultra"
+
+
+def test_model_reasoning_resolver_does_not_leak_another_model_map() -> None:
+ fallback = build_claude_reasoning_options(None)
+ reasoning_options = {
+ "future-model": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+
+ assert [
+ item["value"]
+ for item in resolve_model_reasoning_options(reasoning_options, "future-model", fallback)
+ ] == ["__default__", "ultra"]
+ assert resolve_model_reasoning_options(reasoning_options, "other-model", fallback) == fallback
+
+
def test_normalize_claude_reasoning_effort_drops_invalid_efforts() -> None:
assert normalize_claude_reasoning_effort("claude-sonnet-4-5", "max") is None
assert normalize_claude_reasoning_effort("claude-opus-4-6", "xhigh") is None
diff --git a/tests/test_discord_model_picker.py b/tests/test_discord_model_picker.py
index f9b9ad08f..5752bf914 100644
--- a/tests/test_discord_model_picker.py
+++ b/tests/test_discord_model_picker.py
@@ -1,11 +1,15 @@
from __future__ import annotations
+import asyncio
import sys
from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from modules.im.discord import _prioritize_claude_model_choices
+from config.v2_config import DiscordConfig
+from modules.im.discord import DiscordBot, _prioritize_claude_model_choices
def test_prioritize_pulls_aliases_ahead_of_catalog_tail():
@@ -47,3 +51,55 @@ def test_prioritized_aliases_survive_discord_25_cap():
result = _prioritize_claude_model_choices(models, None)
assert {"opus", "sonnet", "haiku"} <= set(result[:24])
+
+
+def test_codex_routing_uses_shared_catalog_reasoning_options():
+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))
+ channel = SimpleNamespace(send=AsyncMock())
+ current_routing = SimpleNamespace(
+ model="gpt-5.6-terra",
+ reasoning_effort=None,
+ opencode_agent=None,
+ opencode_model=None,
+ opencode_reasoning_effort=None,
+ claude_agent=None,
+ claude_model=None,
+ claude_reasoning_effort=None,
+ codex_agent=None,
+ codex_model=None,
+ codex_reasoning_effort=None,
+ )
+
+ with patch.object(bot, "_fetch_channel", new=AsyncMock(return_value=channel)):
+ asyncio.run(
+ bot.open_routing_modal(
+ trigger_id=None,
+ channel_id="C123",
+ registered_backends=["codex"],
+ current_backend="codex",
+ current_routing=current_routing,
+ opencode_agents=[],
+ opencode_models={},
+ opencode_default_config={},
+ claude_agents=[],
+ claude_models=[],
+ codex_agents=[],
+ codex_models=["gpt-5.6-terra"],
+ backend_reasoning_options={
+ "codex": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+ },
+ )
+ )
+
+ view = channel.send.await_args.kwargs["view"]
+ option_sets = [
+ [option.value for option in child.options]
+ for child in view.children
+ if getattr(child, "options", None)
+ ]
+ assert ["__default__", "ultra"] in option_sets
diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.py
index 743496ea7..4c7cd431a 100644
--- a/tests/test_feishu_routing_card.py
+++ b/tests/test_feishu_routing_card.py
@@ -56,6 +56,37 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
return element
raise AssertionError(f"select_static {field_name} not found")
+ async def test_codex_reasoning_uses_shared_catalog_options(self):
+ bot = self._make_bot()
+ current_routing = SimpleNamespace(
+ codex_agent=None,
+ codex_model="gpt-5.6-terra",
+ codex_reasoning_effort=None,
+ )
+ card = bot._build_routing_backend_options_card(
+ "chat",
+ "codex",
+ current_routing=current_routing,
+ draft_routing=bot._routing_draft_from_current(current_routing, "codex"),
+ codex_agents=[],
+ codex_models=["gpt-5.6-terra"],
+ backend_reasoning_options={
+ "codex": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+ },
+ _user_id="user",
+ )
+
+ reasoning_select = self._find_select(card, "codex_reasoning")
+ self.assertEqual(
+ [option["value"] for option in reasoning_select["options"]],
+ ["__default__", "ultra"],
+ )
+
async def test_claude_model_change_refreshes_reasoning_options(self):
bot = self._make_bot()
bot._patch_card_message = AsyncMock()
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index 3e5c601d3..e74616729 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -191,6 +191,35 @@ def test_handle_routing_update_handles_first_codex_save_without_existing_routing
send_message.assert_not_awaited()
+def test_handle_routing_update_preserves_catalog_claude_effort() -> None:
+ settings_manager = _StubSettingsManager(None)
+ handler, send_message = _make_handler(settings_manager)
+
+ with patch(
+ "core.handlers.settings_handler.backend_model_catalog.catalog_reasoning_efforts_for_model",
+ return_value=["low", "ultra"],
+ ):
+ asyncio.run(
+ handler.handle_routing_update(
+ user_id="42",
+ channel_id="-100123",
+ backend="claude",
+ opencode_agent=None,
+ opencode_model=None,
+ claude_agent="reviewer",
+ claude_model="claude-future-6",
+ claude_reasoning_effort="ultra",
+ notify_user=False,
+ platform="telegram",
+ )
+ )
+
+ assert settings_manager.saved_routing is not None
+ assert settings_manager.saved_routing.model == "claude-future-6"
+ assert settings_manager.saved_routing.reasoning_effort == "ultra"
+ send_message.assert_not_awaited()
+
+
def test_handle_routing_update_warns_flat_scope_with_existing_backend_session() -> None:
handler, send_message, sessions = _make_flat_scope_handler(row={"agent_backend": "opencode"})
@@ -477,9 +506,19 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N
context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="telegram")
with patch("vibe.api.claude_agents", return_value={"ok": True, "agents": [{"id": "reviewer"}]}), patch(
- "vibe.api.claude_models", return_value={"ok": True, "models": ["claude-sonnet-4-6"]}
+ "vibe.api.claude_models",
+ return_value={
+ "ok": True,
+ "models": ["claude-sonnet-4-6"],
+ "reasoning_options": {"claude-sonnet-4-6": [{"value": "max", "label": "Max"}]},
+ },
), patch("vibe.api.codex_agents", return_value={"ok": True, "agents": [{"id": "builder"}]}), patch(
- "vibe.api.codex_models", return_value={"ok": True, "models": ["gpt-5.4"]}
+ "vibe.api.codex_models",
+ return_value={
+ "ok": True,
+ "models": ["gpt-5.4"],
+ "reasoning_options": {"gpt-5.4": [{"value": "ultra", "label": "Ultra"}]},
+ },
):
data = asyncio.run(handler._gather_routing_modal_data(context, include_all_backend_data=True))
@@ -489,6 +528,10 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N
assert data.claude_models == ["claude-sonnet-4-6"]
assert data.codex_agents == [{"id": "builder"}]
assert data.codex_models == ["gpt-5.4"]
+ assert data.backend_reasoning_options == {
+ "claude": {"claude-sonnet-4-6": [{"value": "max", "label": "Max"}]},
+ "codex": {"gpt-5.4": [{"value": "ultra", "label": "Ultra"}]},
+ }
assert server.calls == [
"ensure_running",
"agents:/tmp/workspace",
diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.py
index 19add4d81..94a017491 100644
--- a/tests/test_slack_app_mention_empty.py
+++ b/tests/test_slack_app_mention_empty.py
@@ -230,6 +230,42 @@ class SlackRoutingModalTests(unittest.TestCase):
self.assertEqual(model_select["initial_option"]["value"], "__default__")
self.assertEqual(reasoning_select["initial_option"]["value"], "__default__")
+ def test_codex_reasoning_uses_shared_catalog_options(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ current_routing = SimpleNamespace(
+ agent_backend="codex",
+ model="gpt-5.6-terra",
+ reasoning_effort=None,
+ codex_agent=None,
+ codex_model=None,
+ codex_reasoning_effort=None,
+ )
+
+ view = slack._build_routing_modal_view(
+ channel_id="C123",
+ registered_backends=["codex"],
+ current_backend="codex",
+ current_routing=current_routing,
+ opencode_agents=[],
+ opencode_models={},
+ opencode_default_config={},
+ codex_models=["gpt-5.6-terra"],
+ backend_reasoning_options={
+ "codex": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+ },
+ )
+
+ reasoning_select = self._find_select(view, "codex_reasoning_block")
+ self.assertEqual(
+ [option["value"] for option in reasoning_select["options"]],
+ ["__default__", "ultra"],
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index c1d37f8fd..8ff26b198 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -970,6 +970,66 @@ def test_routing_state_marks_current_backend_in_first_row() -> None:
assert keyboard.buttons[0][1].text.startswith("☑️ ")
+def test_routing_codex_reasoning_uses_shared_catalog_options() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ state = SimpleNamespace(
+ picker_field="codex_reasoning_effort",
+ codex_model="gpt-5.6-terra",
+ backend_reasoning_options={
+ "codex": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+ },
+ )
+
+ assert bot._routing_picker_options(state) == [
+ (bot._t("common.default"), None),
+ ("Ultra", "ultra"),
+ ]
+
+
+def test_open_routing_modal_clears_stale_catalog_effort() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ message_id="88",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ current_routing = SimpleNamespace(
+ model="gpt-5.6-terra",
+ reasoning_effort="minimal",
+ codex_agent=None,
+ )
+
+ with patch.object(bot, "send_message_with_buttons", new=AsyncMock(return_value="99")):
+ asyncio.run(
+ bot.open_routing_modal(
+ context,
+ context.channel_id,
+ current_routing=current_routing,
+ current_backend="codex",
+ registered_backends=["codex"],
+ codex_models=["gpt-5.6-terra"],
+ backend_reasoning_options={
+ "codex": {
+ "gpt-5.6-terra": [
+ {"value": "__default__", "label": "(Default)"},
+ {"value": "ultra", "label": "Ultra"},
+ ]
+ }
+ },
+ )
+ )
+
+ state = bot._routing_states[bot._interaction_scope_key(context)]
+ assert state.codex_reasoning_effort is None
+
+
def test_routing_callback_backend_switches_without_nested_picker() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 63ea15810..d01a1e8ea 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -19,7 +19,7 @@ from config.v2_config import (
from config import paths
from core.vibe_agents import VibeAgentStore
from core import chat_discovery
-from vibe import api
+from vibe import api, backend_model_catalog
from vibe.opencode_config import parse_jsonc_object
@@ -1906,27 +1906,13 @@ def test_claude_models_merge_catalog_and_settings(monkeypatch, tmp_path):
encoding="utf-8",
)
- monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
- monkeypatch.setattr(
- api,
- "load_catalog_models",
- lambda: [
- "claude-opus-4-6",
- "claude-sonnet-4-6",
- "claude-haiku-4-5",
- "claude-opus-4-5",
- ],
- )
+ monkeypatch.setattr(backend_model_catalog.Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(backend_model_catalog, "load_cached_remote_catalog", lambda **kwargs: {})
- result = api.claude_models()
+ result = api.claude_models(schedule_refresh=False)
assert result["ok"] is True
- assert result["models"][:4] == [
- "claude-opus-4-6",
- "claude-sonnet-4-6",
- "claude-haiku-4-5",
- "claude-opus-4-5",
- ]
+ assert result["models"][0] == "claude-fable-5"
assert "opus" in result["models"]
assert "sonnet" in result["models"]
assert "haiku" in result["models"]
@@ -1949,7 +1935,7 @@ def test_claude_models_merge_catalog_and_settings(monkeypatch, tmp_path):
]
-def test_codex_models_prefers_cli_cache_and_filters_hidden_models(monkeypatch, tmp_path):
+def test_codex_models_merges_cli_cache_and_filters_hidden_models(monkeypatch, tmp_path):
codex_dir = tmp_path / ".codex"
codex_dir.mkdir(parents=True, exist_ok=True)
(codex_dir / "models_cache.json").write_text(
@@ -1977,20 +1963,17 @@ def test_codex_models_prefers_cli_cache_and_filters_hidden_models(monkeypatch, t
encoding="utf-8",
)
- monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("CODEX_HOME", str(codex_dir))
+ monkeypatch.setattr(backend_model_catalog, "load_cached_remote_catalog", lambda **kwargs: {})
- result = api.codex_models()
+ result = api.codex_models(schedule_refresh=False)
assert result["ok"] is True
- assert result["models"][:4] == [
- "gpt-5.5",
- "gpt-5.4",
- "gpt-5.4-mini",
- "gpt-5.4-nano",
- ]
+ assert result["models"][:3] == ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"]
+ assert result["models"].index("gpt-5.4") < result["models"].index("gpt-5.4-mini")
assert "gpt-5.3-codex-spark" in result["models"]
assert "gpt-5.1-codex-mini" in result["models"]
- assert "gpt-5.1" in result["models"]
+ assert "gpt-5.1" not in result["models"]
assert "gpt-5.2" in result["models"]
assert result["models"].count("gpt-5.4") == 1
@@ -2009,12 +1992,13 @@ def test_codex_models_falls_back_when_cli_cache_missing(monkeypatch, tmp_path):
encoding="utf-8",
)
- monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("CODEX_HOME", str(codex_dir))
+ monkeypatch.setattr(backend_model_catalog, "load_cached_remote_catalog", lambda **kwargs: {})
- result = api.codex_models()
+ result = api.codex_models(schedule_refresh=False)
assert result["ok"] is True
- assert result["models"][:4] == ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-nano"]
+ assert result["models"][:3] == ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"]
assert "custom-codex-model" in result["models"]
assert "legacy-codex" in result["models"]
assert "gpt-5.1-codex-max" in result["models"]
@@ -2022,14 +2006,14 @@ def test_codex_models_falls_back_when_cli_cache_missing(monkeypatch, tmp_path):
def test_codex_models_includes_static_reasoning(monkeypatch, tmp_path):
- monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
- result = api.codex_models()
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
+ monkeypatch.setattr(backend_model_catalog, "load_cached_remote_catalog", lambda **kwargs: {})
+ result = api.codex_models(schedule_refresh=False)
assert result["ok"] is True
expected = ["__default__", "minimal", "low", "medium", "high", "xhigh"]
# static set, surfaced under the default "" key and per-model
assert [o["value"] for o in result["reasoning_options"][""]] == expected
- first_model = result["models"][0]
- assert [o["value"] for o in result["reasoning_options"][first_model]] == expected
+ assert [o["value"] for o in result["reasoning_options"]["gpt-5.1-codex-max"]] == expected
def test_agent_model_options_claude_strips_default_and_marks_default(monkeypatch):
diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsx
index 6aee8cccf..67bfa771d 100644
--- a/ui/src/components/workbench/AgentRoutePicker.tsx
+++ b/ui/src/components/workbench/AgentRoutePicker.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Bot, ChevronDown, Loader2, Plus, Search, Sparkles } from 'lucide-react';
@@ -6,8 +6,8 @@ import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import type { VibeAgentBrief } from '../../context/ApiContext';
-import { fetchBackendModels, modelOptionLabel } from '../../lib/backendModels';
-import { resolveEffortOptions } from '../../lib/effortOptions';
+import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';
+import { isEffortSupported, resolveEffortOptions } from '../../lib/effortOptions';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
@@ -55,6 +55,10 @@ interface AgentRoutePickerProps {
onNavigateAway?: () => void;
}
+type ReasoningOption = { value: string; label: string };
+
+const EMPTY_REASONING_OPTIONS: Record<string, ReasoningOption[]> = {};
+
// design.pen Q5xIZa — one cyan-ringed trigger showing `[backend] agent · model ·
// effort` that opens a three-column cascading menu (Agent → Model → Effort).
// Picking an agent seeds model/effort from its defaults; the model column is
@@ -83,10 +87,10 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
const [open, setOpen] = useState(false);
const [modelsByBackend, setModelsByBackend] = useState<Record<string, string[]>>({});
const [modelLabelsByBackend, setModelLabelsByBackend] = useState<Record<string, Record<string, string>>>({});
- // Claude reasoning efforts are MODEL-specific (newer Opus/Sonnet add xhigh/max),
- // so the backend returns them keyed by model. Cached so the effort column offers
- // exactly the efforts the selected model supports.
- const [claudeReasoning, setClaudeReasoning] = useState<Record<string, { value: string; label: string }[]>>({});
+ const [reasoningByBackend, setReasoningByBackend] = useState<
+ Record<string, Record<string, ReasoningOption[]>>
+ >({});
+ const loadedModelBackendsRef = useRef<Set<string>>(new Set());
const [loadingModels, setLoadingModels] = useState(false);
const [patching, setPatching] = useState(false);
// Free-text filter for the model column — long backends (OpenCode) list dozens.
@@ -152,6 +156,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
useEffect(() => {
const clearOpenCodeModels = () => {
+ loadedModelBackendsRef.current.delete('opencode');
setModelsByBackend((prev) => {
if (!prev.opencode) return prev;
const next = { ...prev };
@@ -182,27 +187,32 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
// Fetch the active backend's model list the first time the menu opens for it;
// cached per backend so toggling agents doesn't refetch.
useEffect(() => {
- if (!open || !backend || modelsByBackend[backend]) return;
- let cancelled = false;
+ const loadedBackends = loadedModelBackendsRef.current;
+ if (!open || !backend || loadedBackends.has(backend)) return;
+ loadedBackends.add(backend);
+ let reloadOnNextOpen = true;
setLoadingModels(true);
- (async () => {
- try {
- const { models, modelLabels, reasoningOptions } = await fetchBackendModels(api, backend);
- if (!cancelled) {
- if (reasoningOptions) setClaudeReasoning(reasoningOptions);
- setModelsByBackend((prev) => ({ ...prev, [backend]: models }));
- setModelLabelsByBackend((prev) => ({ ...prev, [backend]: modelLabels ?? {} }));
- }
- } catch {
- if (!cancelled) setModelsByBackend((prev) => ({ ...prev, [backend]: [] }));
- } finally {
- if (!cancelled) setLoadingModels(false);
- }
- })();
+ const cancel = loadBackendModelsWithRefresh(
+ api,
+ backend,
+ ({ models, modelLabels, reasoningOptions, catalogRefreshPending }) => {
+ reloadOnNextOpen = Boolean(catalogRefreshPending);
+ setReasoningByBackend((prev) => ({ ...prev, [backend]: reasoningOptions ?? {} }));
+ setModelsByBackend((prev) => ({ ...prev, [backend]: models }));
+ setModelLabelsByBackend((prev) => ({ ...prev, [backend]: modelLabels ?? {} }));
+ setLoadingModels(false);
+ },
+ () => {
+ loadedBackends.delete(backend);
+ setModelsByBackend((prev) => ({ ...prev, [backend]: [] }));
+ setLoadingModels(false);
+ },
+ );
return () => {
- cancelled = true;
+ cancel();
+ if (reloadOnNextOpen) loadedBackends.delete(backend);
};
- }, [open, backend, api, modelsByBackend]);
+ }, [open, backend, api]);
// Start each open (and every backend switch) from the full, unfiltered list.
useEffect(() => {
@@ -211,6 +221,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
const models = modelsByBackend[backend] ?? [];
const modelLabels = modelLabelsByBackend[backend] ?? {};
+ const backendReasoning = reasoningByBackend[backend] ?? EMPTY_REASONING_OPTIONS;
// Show the search field only when the list is long enough to warrant it, so
// claude/codex (a handful of models) stay uncluttered.
const showModelSearch = models.length > 8;
@@ -223,8 +234,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
)
: models;
const effortOptions = useMemo(
- () => resolveEffortOptions(backend, currentModel, claudeReasoning),
- [backend, currentModel, claudeReasoning],
+ () => resolveEffortOptions(backend, currentModel, backendReasoning),
+ [backend, currentModel, backendReasoning],
);
return (
@@ -387,12 +398,11 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
disabled={patching}
onClick={() => {
const patch: AgentRoutePatch = { model };
- // Switching to a Claude model whose effort set no longer includes
+ // Switching to a model whose effort set no longer includes
// the current effort: clear it in the same patch so the displayed
// route matches what dispatches.
- if (backend === 'claude' && currentEffort) {
- const opts = claudeReasoning[model];
- if (opts && !opts.some((o) => o.value === currentEffort)) patch.reasoning_effort = null;
+ if (!isEffortSupported(backend, model, currentEffort, backendReasoning)) {
+ patch.reasoning_effort = null;
}
void applyPatch(patch);
}}
@@ -408,7 +418,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
)}
</RouteColumn>
- {/* Column 3 — Effort (Claude: model-specific; others: backend superset) */}
+ {/* Column 3 — Effort (uses per-model catalog entries when available) */}
<RouteColumn title={t('chat.picker.effort')}>
{effortOptions.map((opt) => (
<RouteItem
@@ -417,7 +427,9 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
disabled={patching}
onClick={() => void applyPatch({ reasoning_effort: opt })}
>
- <span className="flex-1 capitalize">{t(`chat.picker.effortOptions.${opt}`)}</span>
+ <span className="flex-1 capitalize">
+ {t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}
+ </span>
</RouteItem>
))}
</RouteColumn>
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 1e35d6d4a..faea95b8c 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -37,7 +37,7 @@ import { Textarea } from '../ui/textarea';
import { EditorDialog } from '../ui/editor-dialog';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { estimateTokens } from '../../lib/tokenEstimate';
-import { fetchBackendModels, modelOptionLabel } from '../../lib/backendModels';
+import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';
import { resolveEffortOptions } from '../../lib/effortOptions';
import { WorkbenchPageHeader } from './WorkbenchPageHeader';
import { CapabilityTabs } from './CapabilityTabs';
@@ -669,10 +669,21 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, onChange, o
const [systemPrompt, setSystemPrompt] = useState(agent.system_prompt ?? '');
const [systemPromptOpen, setSystemPromptOpen] = useState(false);
const [editorOpen, setEditorOpen] = useState(false);
- const [modelOptions, setModelOptions] = useState<ComboboxOption[]>([]);
- const [reasoningOptions, setReasoningOptions] = useState<Record<string, { value: string; label: string }[]>>({});
+ const [modelCatalogs, setModelCatalogs] = useState<
+ Record<
+ string,
+ {
+ modelOptions: ComboboxOption[];
+ reasoningOptions: Record<string, { value: string; label: string }[]>;
+ }
+ >
+ >({});
const [running, setRunning] = useState(false);
+ const activeModelCatalog = modelCatalogs[agent.backend];
+ const modelOptions = activeModelCatalog?.modelOptions ?? [];
+ const reasoningOptions = activeModelCatalog?.reasoningOptions ?? {};
+
useEffect(() => {
setName(agent.name);
setDescription(agent.description ?? '');
@@ -687,27 +698,29 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, onChange, o
// suggestions. Keeps `allowCustomValue` so users can type a model the
// backend doesn't know about yet (e.g. a freshly-released preview).
useEffect(() => {
- let cancelled = false;
- async function loadModels() {
- try {
- const { models, modelLabels, reasoningOptions: opts } = await fetchBackendModels(api, agent.backend);
- if (!cancelled) {
- setModelOptions(models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })));
- setReasoningOptions(opts ?? {});
- }
- } catch {
- if (!cancelled) setModelOptions([]);
- }
- }
- loadModels();
- return () => {
- cancelled = true;
- };
+ return loadBackendModelsWithRefresh(
+ api,
+ agent.backend,
+ ({ models, modelLabels, reasoningOptions: opts }) => {
+ setModelCatalogs((current) => ({
+ ...current,
+ [agent.backend]: {
+ modelOptions: models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })),
+ reasoningOptions: opts ?? {},
+ },
+ }));
+ },
+ () => {
+ setModelCatalogs((current) => ({
+ ...current,
+ [agent.backend]: { modelOptions: [], reasoningOptions: {} },
+ }));
+ },
+ );
}, [agent.backend, api]);
const systemPromptTokens = estimateTokens(systemPrompt);
- // Effort options follow the backend + selected model — Claude is per-model via
- // the catalog's reasoning_options; Codex/OpenCode use the backend superset.
+ // Effort options follow the backend + selected model when the catalog provides them.
const effortOptions = resolveEffortOptions(agent.backend, model, reasoningOptions);
// Backend rejects PATCH /agents/<name> with a new name; the supported
diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsx
index efedd6345..b79a48d07 100644
--- a/ui/src/components/workbench/NewAgentDialog.tsx
+++ b/ui/src/components/workbench/NewAgentDialog.tsx
@@ -5,7 +5,7 @@ import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import type { VibeAgentFull } from '../../context/ApiContext';
-import { fetchBackendModels, modelOptionLabel } from '../../lib/backendModels';
+import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';
import { resolveEffortOptions } from '../../lib/effortOptions';
import { estimateTokens } from '../../lib/tokenEstimate';
import { Combobox } from '../ui/combobox';
@@ -77,26 +77,15 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o
// freshly-released model IDs can still be typed in.
useEffect(() => {
if (!open) return;
- let cancelled = false;
- async function loadModels() {
- try {
- const { models, modelLabels, reasoningOptions: opts } = await fetchBackendModels(api, backend);
- if (!cancelled) {
- setModelOptions(models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })));
- setReasoningOptions(opts ?? {});
- // Clear model when the backend changes if the previous choice
- // isn't in the new catalog — avoids silently mismatched pairs.
- if (model && !models.includes(model)) setModel('');
- }
- } catch {
- if (!cancelled) setModelOptions([]);
- }
- }
- loadModels();
- return () => {
- cancelled = true;
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ return loadBackendModelsWithRefresh(
+ api,
+ backend,
+ ({ models, modelLabels, reasoningOptions: opts }) => {
+ setModelOptions(models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })));
+ setReasoningOptions(opts ?? {});
+ },
+ () => setModelOptions([]),
+ );
}, [backend, open, api]);
const modelComboboxOptions = useMemo(() => modelOptions, [modelOptions]);
@@ -198,7 +187,14 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o
<button
key={opt.key}
type="button"
- onClick={() => setBackend(opt.key)}
+ onClick={() => {
+ if (backend === opt.key) return;
+ setBackend(opt.key);
+ setModel('');
+ setEffort('medium');
+ setModelOptions([]);
+ setReasoningOptions({});
+ }}
className={clsx(
'flex flex-col items-center justify-center gap-1.5 rounded-lg border-2 px-3 py-3.5 transition',
active ? `${cc.border} ${cc.bg}` : 'border-border-strong bg-surface-2 hover:bg-foreground/[0.04]',
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 614341189..ddb1ef6e5 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -452,9 +452,9 @@ export type ApiContextType = {
opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;
opencodePermissionStatus: () => Promise<{ ok: boolean; permission_allowed: boolean; config_path: string }>;
claudeAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string }[]; error?: string }>;
- claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; model_labels?: Record<string, string>; error?: string }>;
+ claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; model_labels?: Record<string, string>; catalog_refresh_pending?: boolean; error?: string }>;
codexAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string; description?: string }[]; error?: string }>;
- codexModels: () => Promise<{ ok: boolean; models?: string[]; error?: string }>;
+ codexModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; model_labels?: Record<string, string>; catalog_refresh_pending?: boolean; error?: string }>;
getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;
getVersion: () => Promise<VersionInfo>;
doUpgrade: () => Promise<UpgradeResult>;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 2c1ddc516..412193754 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2180,7 +2180,8 @@
"medium": "Medium",
"high": "High",
"xhigh": "Extra High",
- "max": "Max"
+ "max": "Max",
+ "ultra": "Ultra"
}
},
"compose": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d23572ad9..1e59375cf 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2180,7 +2180,8 @@
"medium": "中",
"high": "高",
"xhigh": "极高",
- "max": "最高"
+ "max": "最高",
+ "ultra": "Ultra"
}
},
"compose": {
diff --git a/ui/src/lib/backendModels.test.ts b/ui/src/lib/backendModels.test.ts
new file mode 100644
index 000000000..262440b53
--- /dev/null
+++ b/ui/src/lib/backendModels.test.ts
@@ -0,0 +1,41 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { ApiContextType } from '../context/ApiContext';
+import { loadBackendModelsWithRefresh } from './backendModels';
+
+describe('loadBackendModelsWithRefresh', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('delivers the immediate snapshot and silently refetches after refresh', async () => {
+ vi.useFakeTimers();
+ const codexModels = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ models: ['gpt-old'],
+ catalog_refresh_pending: true,
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ models: ['gpt-old', 'gpt-new'],
+ catalog_refresh_pending: false,
+ });
+ const api = { codexModels } as unknown as ApiContextType;
+ const snapshots: string[][] = [];
+
+ const cancel = loadBackendModelsWithRefresh(api, 'codex', (result) => {
+ snapshots.push(result.models);
+ });
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(snapshots).toEqual([['gpt-old']]);
+
+ await vi.advanceTimersByTimeAsync(3_500);
+ expect(snapshots).toEqual([['gpt-old'], ['gpt-old', 'gpt-new']]);
+ expect(codexModels).toHaveBeenCalledTimes(2);
+
+ cancel();
+ });
+});
diff --git a/ui/src/lib/backendModels.ts b/ui/src/lib/backendModels.ts
index ec7e44da1..184d87e42 100644
--- a/ui/src/lib/backendModels.ts
+++ b/ui/src/lib/backendModels.ts
@@ -5,10 +5,15 @@ export interface BackendModels {
models: string[];
/** Optional display labels keyed by model identifier; values remain raw ids. */
modelLabels?: Record<string, string>;
- /** Per-model reasoning-effort option sets (Claude only); undefined elsewhere. */
+ /** Per-model reasoning-effort option sets; undefined when a backend has none. */
reasoningOptions?: Record<string, { value: string; label: string }[]>;
+ /** True while a background remote-catalog refresh may produce a newer snapshot. */
+ catalogRefreshPending?: boolean;
}
+const CATALOG_REFRESH_RETRY_DELAY_MS = 3_500;
+const CATALOG_REFRESH_MAX_RETRIES = 2;
+
export function modelOptionLabel(model: string, labels?: Record<string, string>): string {
return labels?.[model] || model;
}
@@ -36,11 +41,17 @@ export async function fetchBackendModels(
models: res.ok && res.models ? res.models : [],
modelLabels: res.model_labels,
reasoningOptions: res.reasoning_options,
+ catalogRefreshPending: res.catalog_refresh_pending,
};
}
if (backend === 'codex') {
const res = await api.codexModels();
- return { models: res.ok && res.models ? res.models : [] };
+ return {
+ models: res.ok && res.models ? res.models : [],
+ modelLabels: res.model_labels,
+ reasoningOptions: res.reasoning_options,
+ catalogRefreshPending: res.catalog_refresh_pending,
+ };
}
if (backend === 'opencode') {
const res = await api.getOpencodeProviders();
@@ -51,3 +62,34 @@ export async function fetchBackendModels(
}
return { models: [] };
}
+
+export function loadBackendModelsWithRefresh(
+ api: ApiContextType,
+ backend: string,
+ onResult: (result: BackendModels) => void,
+ onInitialError?: () => void,
+): () => void {
+ let cancelled = false;
+ let delivered = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const load = async (retriesRemaining: number) => {
+ try {
+ const result = await fetchBackendModels(api, backend);
+ if (cancelled) return;
+ delivered = true;
+ onResult(result);
+ if (result.catalogRefreshPending && retriesRemaining > 0) {
+ timer = setTimeout(() => void load(retriesRemaining - 1), CATALOG_REFRESH_RETRY_DELAY_MS);
+ }
+ } catch {
+ if (!cancelled && !delivered) onInitialError?.();
+ }
+ };
+
+ void load(CATALOG_REFRESH_MAX_RETRIES);
+ return () => {
+ cancelled = true;
+ if (timer !== undefined) clearTimeout(timer);
+ };
+}
diff --git a/ui/src/lib/effortOptions.test.ts b/ui/src/lib/effortOptions.test.ts
new file mode 100644
index 000000000..b99241430
--- /dev/null
+++ b/ui/src/lib/effortOptions.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { isEffortSupported, resolveEffortOptions } from './effortOptions';
+
+describe('effort options', () => {
+ it('uses the backend fallback for an unknown model', () => {
+ const reasoningOptions = {
+ 'gpt-5.6-sol': [
+ { value: '__default__', label: 'Default' },
+ { value: 'ultra', label: 'Ultra' },
+ ],
+ };
+
+ expect(resolveEffortOptions('codex', 'custom-model', reasoningOptions)).toEqual([
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ ]);
+ expect(isEffortSupported('codex', 'custom-model', 'ultra', reasoningOptions)).toBe(false);
+ });
+
+ it('accepts catalog-only efforts for Claude and Codex models', () => {
+ const reasoningOptions = {
+ 'future-model': [
+ { value: '__default__', label: 'Default' },
+ { value: 'ultra', label: 'Ultra' },
+ ],
+ };
+
+ expect(isEffortSupported('claude', 'future-model', 'ultra', reasoningOptions)).toBe(true);
+ expect(isEffortSupported('codex', 'future-model', 'ultra', reasoningOptions)).toBe(true);
+ });
+});
diff --git a/ui/src/lib/effortOptions.ts b/ui/src/lib/effortOptions.ts
index 4147b0fc0..69643ccaf 100644
--- a/ui/src/lib/effortOptions.ts
+++ b/ui/src/lib/effortOptions.ts
@@ -1,8 +1,8 @@
// Single source of truth for reasoning-effort options, shared by ChatPage, the
// Agents detail panel, and the New Agent dialog. Mirrors the backend lists in
-// modules/agents/opencode/utils.py: Codex is minimal..xhigh, Claude is
+// modules/agents/opencode/utils.py: Codex falls back to minimal..xhigh, Claude is
// low/medium/high (+ xhigh/max on models that support it), OpenCode uses the
-// broad superset.
+// broad superset. Codex/Claude model catalogs override these fallbacks.
export const EFFORT_BY_BACKEND: Record<string, string[]> = {
claude: ['low', 'medium', 'high'],
codex: ['minimal', 'low', 'medium', 'high', 'xhigh'],
@@ -13,21 +13,15 @@ const DEFAULT_EFFORTS = ['low', 'medium', 'high'];
export const effortOptionsFor = (backend: string): string[] => EFFORT_BY_BACKEND[backend] ?? DEFAULT_EFFORTS;
-// Backends whose model catalog actually ships per-model reasoning options.
-// Today only Claude — Codex/OpenCode return a flat list, so a stale options map
-// left over from a previous backend (e.g. ChatPage's claudeReasoning cache,
-// which isn't cleared on backend switch) must NOT leak into their effort set.
-const PER_MODEL_EFFORT_BACKENDS = new Set(['claude']);
+const PER_MODEL_EFFORT_BACKENDS = new Set(['claude', 'codex']);
-// Resolve the selectable effort values for a backend + model. Only backends that
-// publish per-model reasoning options (Claude) consult ``reasoningOptions``; the
-// rest always use their backend superset, so a stale map can't leak. A known
-// model uses its own set (Opus exposes xhigh/max, Haiku doesn't); an inherited
-// (empty) or unknown/custom model uses the catalog's "" default set. We do NOT
-// union across all models: the backend re-derives the effective model and runs
-// normalize_claude_reasoning_effort, so a broader UI list would just surface
-// efforts the backend silently drops (a false affordance). ``reasoningOptions``
-// may be {} before the catalog loads — that yields the backend fallback.
+// Resolve the selectable effort values for a backend + model. Claude and Codex
+// consult their catalog maps; other backends always use their static superset so
+// stale state cannot leak across backend switches. A known model uses its own
+// set, while an inherited or custom model uses the catalog's "" default set.
+// We do not union across models because that would offer unsupported pairs.
+// ``reasoningOptions`` may be {} before the catalog loads, which yields the
+// backend fallback until the immediate snapshot arrives.
export function resolveEffortOptions(
backend: string,
model: string | null | undefined,
@@ -40,3 +34,12 @@ export function resolveEffortOptions(
}
return effortOptionsFor(backend);
}
+
+export function isEffortSupported(
+ backend: string,
+ model: string | null | undefined,
+ effort: string | null | undefined,
+ reasoningOptions: Record<string, { value: string; label: string }[]> | undefined,
+): boolean {
+ return !effort || resolveEffortOptions(backend, model, reasoningOptions).includes(effort);
+}
diff --git a/vibe/api.py b/vibe/api.py
index 7f211efc5..10e961eaf 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -54,7 +54,7 @@ from vibe.upgrade import (
should_skip_show_runtime_prepare,
)
from vibe.restart_supervisor import schedule_restart
-from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_models
+from vibe import backend_model_catalog
from vibe.i18n import t as backend_t
from modules.agents.catalog import (
agent_backend_catalog_payload,
@@ -5347,64 +5347,9 @@ def codex_agents(cwd: Optional[str] = None) -> dict:
return {"ok": False, "error": str(e)}
-def claude_models() -> dict:
- """Best-effort merged list of Claude Code model options.
-
- Claude Code does not expose a stable `list models` CLI subcommand.
- We merge suggestions from:
- - The repository-owned Claude model catalog
- - ~/.claude/settings.json model/env values
- """
-
- def _append_unique(options: list[str], seen: set[str], value: object) -> None:
- if not isinstance(value, str):
- return
- model = value.strip()
- if not model or model in seen:
- return
- seen.add(model)
- options.append(model)
-
- options: list[str] = []
- seen: set[str] = set()
-
- for model in load_catalog_models():
- _append_unique(options, seen, model)
-
- for model in DEFAULT_CLAUDE_MODEL_ALIASES:
- _append_unique(options, seen, model)
-
- settings_path = Path.home() / ".claude" / "settings.json"
- try:
- if settings_path.exists() and settings_path.is_file():
- data = json.loads(settings_path.read_text(encoding="utf-8"))
- if isinstance(data, dict):
- _append_unique(options, seen, data.get("model"))
- env = data.get("env")
- if isinstance(env, dict):
- for key in (
- "ANTHROPIC_MODEL",
- "ANTHROPIC_SMALL_FAST_MODEL",
- ):
- _append_unique(options, seen, env.get(key))
- except Exception as exc:
- logger.warning("Failed to read Claude settings.json: %s", exc, exc_info=True)
-
- from modules.agents.opencode.utils import build_claude_reasoning_options, format_claude_model_label
-
- reasoning_options = {"": build_claude_reasoning_options(None)}
- model_labels = {}
- for model in options:
- reasoning_options[model] = build_claude_reasoning_options(model)
- label = format_claude_model_label(model)
- if label != model:
- model_labels[model] = label
- return {
- "ok": True,
- "models": options,
- "reasoning_options": reasoning_options,
- "model_labels": model_labels,
- }
+def claude_models(*, schedule_refresh: bool = True) -> dict:
+ """Return the immediate shared Claude model-catalog snapshot."""
+ return backend_model_catalog.backend_model_snapshot("claude", schedule_refresh=schedule_refresh)
def _effort_values(reasoning_entries: object) -> list[str]:
@@ -5580,9 +5525,10 @@ def agent_model_options(
"backend": "claude",
"default_model": default_model,
"models": _flat_catalog_models(data, default_model),
- "source": "claude model catalog + ~/.claude/settings.json",
- "live": False,
- "notes": ["Claude Code has no stable list-models command; this is a best-effort merged list."],
+ "source": data.get("source"),
+ "live": bool(data.get("live")),
+ "notes": data.get("notes"),
+ "catalog_refresh_pending": bool(data.get("catalog_refresh_pending")),
}
elif normalized_backend == "codex":
data = codex_models()
@@ -5594,9 +5540,10 @@ def agent_model_options(
"backend": "codex",
"default_model": default_model,
"models": _flat_catalog_models(data, default_model),
- "source": "codex built-in list + ~/.codex caches",
- "live": False,
- "notes": ["Codex CLI has no stable list-models command; this is a best-effort merged list."],
+ "source": data.get("source"),
+ "live": bool(data.get("live")),
+ "notes": data.get("notes"),
+ "catalog_refresh_pending": bool(data.get("catalog_refresh_pending")),
}
else:
result = _opencode_model_options(provider=provider, cwd=cwd, config=config)
@@ -10468,107 +10415,9 @@ def set_opencode_default_provider(payload: dict) -> dict:
return {"ok": True, "default_provider": provider_id}
-def codex_models() -> dict:
- """Best-effort merged list of Codex model options.
-
- Codex CLI does not expose a stable `list models` command.
- We merge suggestions from:
- - Built-in known model ids
- - ~/.codex/models_cache.json (maintained by Codex CLI)
- - ~/.codex/config.toml (user-selected model and migration hints)
- """
-
- def _append_unique(options: list[str], seen: set[str], value: object) -> None:
- if not isinstance(value, str):
- return
- model = value.strip()
- if not model or model in seen:
- return
- seen.add(model)
- options.append(model)
-
- def _result(model_options: list[str]) -> dict:
- # Codex reasoning-effort levels are static (model-independent). Surface
- # them per-model so the shape matches claude_models(), letting a single
- # caller (agent_model_options / the UI) treat both backends uniformly.
- from modules.agents.opencode.utils import build_codex_reasoning_options
-
- codex_reasoning = build_codex_reasoning_options()
- reasoning_options = {"": codex_reasoning}
- for model_id in model_options:
- reasoning_options[model_id] = codex_reasoning
- return {"ok": True, "models": model_options, "reasoning_options": reasoning_options}
-
- built_in_options: list[str] = [
- "gpt-5.5",
- "gpt-5.4",
- "gpt-5.4-mini",
- "gpt-5.4-nano",
- "gpt-5.3-codex",
- "gpt-5.3-codex-spark",
- "gpt-5.2-codex",
- "gpt-5.2",
- "gpt-5.1-codex-max",
- "gpt-5.1-codex-mini",
- "gpt-5.1",
- "gpt-5",
- ]
-
- options: list[str] = []
- seen: set[str] = set()
- codex_home = Path.home() / ".codex"
- models_cache_path = codex_home / "models_cache.json"
- config_path = codex_home / "config.toml"
-
- for model in built_in_options:
- _append_unique(options, seen, model)
-
- try:
- if models_cache_path.exists() and models_cache_path.is_file():
- cache_data = json.loads(models_cache_path.read_text(encoding="utf-8"))
- models = cache_data.get("models")
- if isinstance(models, list):
- visible_models: list[tuple[int, int, str]] = []
- for index, item in enumerate(models):
- if not isinstance(item, dict):
- continue
- slug = item.get("slug")
- if not isinstance(slug, str) or not slug.strip():
- continue
- priority = item.get("priority")
- if not isinstance(priority, int):
- priority = 10**9
- visible_models.append((priority, index, slug.strip()))
-
- for _, _, slug in sorted(visible_models):
- _append_unique(options, seen, slug)
- except Exception as exc:
- logger.warning("Failed to read Codex models_cache.json: %s", exc, exc_info=True)
-
- try:
- if config_path.exists() and config_path.is_file():
- try:
- import tomllib # py3.11+
- except Exception: # pragma: no cover
- tomllib = None
-
- if tomllib is None:
- return _result(options)
-
- data = tomllib.loads(config_path.read_text(encoding="utf-8"))
- if isinstance(data, dict):
- _append_unique(options, seen, data.get("model"))
- notice = data.get("notice")
- if isinstance(notice, dict):
- migrations = notice.get("model_migrations")
- if isinstance(migrations, dict):
- for k, v in migrations.items():
- _append_unique(options, seen, k)
- _append_unique(options, seen, v)
- except Exception as exc:
- logger.warning("Failed to read Codex config.toml: %s", exc, exc_info=True)
-
- return _result(options)
+def codex_models(*, schedule_refresh: bool = True) -> dict:
+ """Return the immediate shared Codex model-catalog snapshot."""
+ return backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=schedule_refresh)
def _lark_api_base(domain: str = "feishu") -> str:
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
new file mode 100644
index 000000000..8ea549104
--- /dev/null
+++ b/vibe/backend_model_catalog.py
@@ -0,0 +1,622 @@
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import threading
+import time
+import urllib.request
+from pathlib import Path
+from typing import Any, Iterable, Sequence
+
+from config import paths
+from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_models
+from vibe.codex_config import get_codex_home
+
+
+REMOTE_CATALOG_URL_ENV = "AVIBE_BACKEND_MODEL_CATALOG_URL"
+DEFAULT_REMOTE_CATALOG_URL = (
+ "https://raw.githubusercontent.com/avibe-bot/avibe/master/vibe/data/backend_models.json"
+)
+REMOTE_CATALOG_TTL_SECONDS = 6 * 60 * 60
+REMOTE_CATALOG_FAILURE_TTL_SECONDS = 10 * 60
+REMOTE_CATALOG_TIMEOUT_SECONDS = 3.0
+REMOTE_CATALOG_USER_AGENT = "avibe/backend-model-catalog"
+
+_HIDDEN_VISIBILITIES = {"hide", "hidden"}
+_SUPPORTED_BACKENDS = {"claude", "codex"}
+_SUPPORTED_VISIBILITIES = {"visible", "list", *_HIDDEN_VISIBILITIES}
+_DEFAULT_REASONING_EFFORTS = {
+ "claude": ["low", "medium", "high"],
+ "codex": ["minimal", "low", "medium", "high", "xhigh"],
+}
+_CODEX_BUILT_IN_MODELS = [
+ "gpt-5.5",
+ "gpt-5.4",
+ "gpt-5.4-mini",
+ "gpt-5.4-nano",
+ "gpt-5.3-codex",
+ "gpt-5.3-codex-spark",
+ "gpt-5.2-codex",
+ "gpt-5.2",
+ "gpt-5.1-codex-max",
+ "gpt-5.1-codex-mini",
+ "gpt-5.1",
+ "gpt-5",
+]
+_REASONING_LABELS = {
+ "none": "None",
+ "minimal": "Minimal",
+ "low": "Low",
+ "medium": "Medium",
+ "high": "High",
+ "xhigh": "Extra High",
+ "max": "Max",
+ "ultra": "Ultra",
+}
+
+_REMOTE_LOCK = threading.Lock()
+_REMOTE_REFRESH_IN_FLIGHT = False
+_REMOTE_MEMORY_CACHE: dict[str, Any] = {}
+
+
+def get_bundled_catalog_path(repo_root: Path | None = None) -> Path:
+ base_dir = repo_root if repo_root is not None else Path(__file__).resolve().parent
+ return base_dir / "data" / "backend_models.json"
+
+
+def get_cached_catalog_path() -> Path:
+ return paths.get_state_dir() / "backend_model_catalog.json"
+
+
+def load_bundled_catalog(path: Path | None = None) -> dict[str, Any]:
+ return _read_catalog(path or get_bundled_catalog_path()) or {}
+
+
+def load_cached_remote_catalog(*, schedule_refresh: bool = True) -> dict[str, Any]:
+ cached = _cached_remote_payload()
+ if schedule_refresh and _remote_cache_stale(cached):
+ schedule_remote_catalog_refresh()
+ catalog = cached.get("catalog")
+ return catalog if isinstance(catalog, dict) else {}
+
+
+def remote_catalog_token() -> tuple[float | None, float | None]:
+ payload = _cached_remote_payload()
+ fetched_at = payload.get("fetched_at")
+ failed_at = payload.get("failed_at")
+ return (
+ float(fetched_at) if isinstance(fetched_at, (int, float)) else None,
+ float(failed_at) if isinstance(failed_at, (int, float)) else None,
+ )
+
+
+def remote_catalog_refresh_pending(since: tuple[float | None, float | None]) -> bool:
+ with _REMOTE_LOCK:
+ refresh_in_flight = _REMOTE_REFRESH_IN_FLIGHT
+ return refresh_in_flight or remote_catalog_token() != since
+
+
+def schedule_remote_catalog_refresh() -> bool:
+ global _REMOTE_REFRESH_IN_FLIGHT
+
+ with _REMOTE_LOCK:
+ if _REMOTE_REFRESH_IN_FLIGHT:
+ return False
+ _REMOTE_REFRESH_IN_FLIGHT = True
+
+ thread = threading.Thread(
+ target=_refresh_remote_catalog_worker,
+ name="avibe-model-catalog-refresh",
+ daemon=True,
+ )
+ thread.start()
+ return True
+
+
+def refresh_remote_catalog_now(url: str | None = None) -> dict[str, Any]:
+ catalog = fetch_remote_catalog(url=url)
+ payload = {"fetched_at": time.time(), "catalog": catalog, "error": None}
+ _write_cached_remote_payload(payload)
+ return catalog
+
+
+def fetch_remote_catalog(url: str | None = None) -> dict[str, Any]:
+ request_url = (url or os.environ.get(REMOTE_CATALOG_URL_ENV) or DEFAULT_REMOTE_CATALOG_URL).strip()
+ request = urllib.request.Request(request_url, headers={"User-Agent": REMOTE_CATALOG_USER_AGENT})
+ with urllib.request.urlopen( # noqa: S310 - fixed public catalog or explicit operator override
+ request,
+ timeout=REMOTE_CATALOG_TIMEOUT_SECONDS,
+ ) as response:
+ return _normalize_catalog(json.loads(response.read().decode("utf-8")), strict=True)
+
+
+def backend_model_entries(backend: str, catalog: dict[str, Any] | None) -> list[dict[str, Any]]:
+ if not isinstance(catalog, dict):
+ return []
+ backend_key = (backend or "").strip().lower()
+ backends = catalog.get("backends")
+ raw_backend = backends.get(backend_key) if isinstance(backends, dict) else None
+ if not isinstance(raw_backend, dict):
+ return []
+ raw_models = raw_backend.get("models")
+ if not isinstance(raw_models, list):
+ return []
+ entries = [_normalize_model_entry(item) for item in raw_models]
+ return [entry for entry in entries if entry]
+
+
+def backend_model_snapshot(backend: str, *, schedule_refresh: bool = True) -> dict[str, Any]:
+ backend_key = (backend or "").strip().lower()
+ if backend_key not in _SUPPORTED_BACKENDS:
+ return {"ok": False, "backend": backend_key, "error": f"unsupported backend '{backend}'"}
+
+ refresh_token = remote_catalog_token()
+ remote_catalog = load_cached_remote_catalog(schedule_refresh=schedule_refresh)
+ bundled_catalog = load_bundled_catalog()
+
+ if backend_key == "claude":
+ sources = _claude_sources(remote_catalog, bundled_catalog)
+ blocked: set[str] = set()
+ else:
+ local_catalog = _read_codex_models_cache()
+ remote_entries = backend_model_entries("codex", remote_catalog)
+ blocked = {
+ entry["id"]
+ for entry in [*local_catalog, *remote_entries]
+ if _model_hidden(entry)
+ }
+ sources = _codex_sources(remote_entries, local_catalog, bundled_catalog)
+
+ merged = merge_model_sources(sources, blocked_model_ids=blocked)
+ default_efforts = _DEFAULT_REASONING_EFFORTS[backend_key]
+ models = [entry["id"] for entry in merged]
+ model_labels = {
+ entry["id"]: entry["label"]
+ for entry in merged
+ if isinstance(entry.get("label"), str) and entry["label"] != entry["id"]
+ }
+ reasoning_options = {"": _reasoning_option_items(default_efforts)}
+ for entry in merged:
+ efforts = entry.get("reasoning_efforts") or default_efforts
+ reasoning_options[entry["id"]] = _reasoning_option_items(efforts)
+
+ cached_payload = _cached_remote_payload()
+ notes = []
+ error = cached_payload.get("error")
+ if isinstance(error, str) and error:
+ notes.append(f"remote catalog refresh failed: {error}")
+
+ return {
+ "ok": True,
+ "backend": backend_key,
+ "models": models,
+ "model_labels": model_labels,
+ "reasoning_options": reasoning_options,
+ "sources": [name for name, entries in sources if entries],
+ "source": " + ".join(name for name, entries in sources if entries),
+ "live": False,
+ "notes": notes or None,
+ "catalog_refresh_pending": remote_catalog_refresh_pending(refresh_token),
+ }
+
+
+def catalog_reasoning_efforts_for_model(backend: str, model: str | None) -> list[str] | None:
+ if not model:
+ return None
+ snapshot = backend_model_snapshot(backend, schedule_refresh=False)
+ if not snapshot.get("ok"):
+ return None
+ entries = snapshot.get("reasoning_options", {}).get(model)
+ if not isinstance(entries, list):
+ return None
+ efforts = []
+ for entry in entries:
+ value = entry.get("value") if isinstance(entry, dict) else None
+ if isinstance(value, str) and value and value != "__default__":
+ efforts.append(value)
+ return efforts or None
+
+
+def merge_model_sources(
+ sources: Sequence[tuple[str, Sequence[dict[str, Any]]]],
+ *,
+ blocked_model_ids: Iterable[str] = (),
+) -> list[dict[str, Any]]:
+ blocked = {model.strip() for model in blocked_model_ids if isinstance(model, str) and model.strip()}
+ merged: dict[str, dict[str, Any]] = {}
+ order: list[str] = []
+
+ for source_name, raw_entries in sources:
+ for entry in _ordered_entries(raw_entries):
+ model = entry["id"]
+ if model in blocked:
+ continue
+ if _model_hidden(entry):
+ if model not in merged:
+ blocked.add(model)
+ continue
+
+ current = merged.get(model)
+ if current is None:
+ current = {
+ "id": model,
+ "label": entry.get("label") or model,
+ "reasoning_efforts": list(entry.get("reasoning_efforts") or []),
+ "source": source_name,
+ }
+ merged[model] = current
+ order.append(model)
+ continue
+
+ if current.get("label") == model and entry.get("label"):
+ current["label"] = entry["label"]
+ if not current.get("reasoning_efforts") and entry.get("reasoning_efforts"):
+ current["reasoning_efforts"] = list(entry["reasoning_efforts"])
+
+ return [merged[model] for model in order]
+
+
+def _claude_sources(
+ remote_catalog: dict[str, Any],
+ bundled_catalog: dict[str, Any],
+) -> list[tuple[str, list[dict[str, Any]]]]:
+ from modules.agents.opencode.utils import format_claude_model_label
+
+ legacy_entries = []
+ for model in [*load_catalog_models(), *DEFAULT_CLAUDE_MODEL_ALIASES]:
+ entry = {
+ "id": model,
+ "reasoning_efforts": _legacy_claude_reasoning_efforts(model),
+ }
+ label = format_claude_model_label(model)
+ if label != model:
+ entry["label"] = label
+ legacy_entries.append(entry)
+ return [
+ ("remote", backend_model_entries("claude", remote_catalog)),
+ ("bundled", backend_model_entries("claude", bundled_catalog)),
+ ("legacy", legacy_entries),
+ ("config", _read_claude_settings_models()),
+ ]
+
+
+def _codex_sources(
+ remote_entries: list[dict[str, Any]],
+ local_catalog: list[dict[str, Any]],
+ bundled_catalog: dict[str, Any],
+) -> list[tuple[str, list[dict[str, Any]]]]:
+ visible_local = [entry for entry in local_catalog if not _model_hidden(entry)]
+ local_by_id = {entry["id"]: entry for entry in visible_local}
+ bundled_entries = backend_model_entries("codex", bundled_catalog)
+ built_in = [
+ {"id": model, "reasoning_efforts": _DEFAULT_REASONING_EFFORTS["codex"]}
+ for model in _CODEX_BUILT_IN_MODELS
+ ]
+ return [
+ (
+ "remote",
+ _overlay_local_reasoning_efforts(
+ [entry for entry in remote_entries if not _model_hidden(entry)],
+ local_by_id,
+ ),
+ ),
+ ("bundled", _overlay_local_reasoning_efforts(bundled_entries, local_by_id)),
+ ("local", visible_local),
+ ("legacy", built_in),
+ ("config", _read_codex_config_models()),
+ ]
+
+
+def _overlay_local_reasoning_efforts(
+ catalog_entries: list[dict[str, Any]],
+ local_by_id: dict[str, dict[str, Any]],
+) -> list[dict[str, Any]]:
+ overlaid = []
+ for entry in catalog_entries:
+ merged = dict(entry)
+ local_efforts = local_by_id.get(entry["id"], {}).get("reasoning_efforts")
+ if local_efforts:
+ merged["reasoning_efforts"] = list(local_efforts)
+ overlaid.append(merged)
+ return overlaid
+
+
+def _read_claude_settings_models() -> list[dict[str, Any]]:
+ settings_path = Path.home() / ".claude" / "settings.json"
+ try:
+ payload = json.loads(settings_path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
+ return []
+ if not isinstance(payload, dict):
+ return []
+ values = [payload.get("model")]
+ env = payload.get("env")
+ if isinstance(env, dict):
+ values.extend((env.get("ANTHROPIC_MODEL"), env.get("ANTHROPIC_SMALL_FAST_MODEL")))
+ return [{"id": value.strip()} for value in values if isinstance(value, str) and value.strip()]
+
+
+def _read_codex_models_cache() -> list[dict[str, Any]]:
+ cache_path = get_codex_home() / "models_cache.json"
+ try:
+ payload = json.loads(cache_path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
+ return []
+ raw_models = payload.get("models") if isinstance(payload, dict) else None
+ if not isinstance(raw_models, list):
+ return []
+ entries = [_normalize_model_entry(item) for item in raw_models]
+ return [entry for entry in entries if entry]
+
+
+def _read_codex_config_models() -> list[dict[str, Any]]:
+ config_path = get_codex_home() / "config.toml"
+ try:
+ payload = _parse_toml(config_path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, ValueError):
+ return []
+ if not isinstance(payload, dict):
+ return []
+ values = [payload.get("model")]
+ notice = payload.get("notice")
+ migrations = notice.get("model_migrations") if isinstance(notice, dict) else None
+ if isinstance(migrations, dict):
+ for source, target in migrations.items():
+ values.extend((source, target))
+ return [
+ {"id": value.strip(), "reasoning_efforts": _DEFAULT_REASONING_EFFORTS["codex"]}
+ for value in values
+ if isinstance(value, str) and value.strip()
+ ]
+
+
+def _parse_toml(raw: str) -> dict[str, Any]:
+ try:
+ import tomllib
+ except ModuleNotFoundError: # pragma: no cover - exercised on Python 3.10
+ import tomli as tomllib
+
+ payload = tomllib.loads(raw)
+ return payload if isinstance(payload, dict) else {}
+
+
+def _legacy_claude_reasoning_efforts(model: str) -> list[str]:
+ from modules.agents.opencode.utils import build_claude_reasoning_options
+
+ return [
+ entry["value"]
+ for entry in build_claude_reasoning_options(model)
+ if entry.get("value") != "__default__"
+ ]
+
+
+def _reasoning_option_items(efforts: Iterable[object]) -> list[dict[str, str]]:
+ options = [{"value": "__default__", "label": "(Default)"}]
+ for effort in _dedupe_str_values(efforts):
+ options.append({"value": effort, "label": _REASONING_LABELS.get(effort, effort.capitalize())})
+ return options
+
+
+def _model_hidden(entry: dict[str, Any]) -> bool:
+ visibility = entry.get("visibility")
+ return isinstance(visibility, str) and visibility.strip().lower() in _HIDDEN_VISIBILITIES
+
+
+def _ordered_entries(entries: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
+ indexed = []
+ for index, entry in enumerate(entries):
+ normalized = _normalize_model_entry(entry)
+ if not normalized:
+ continue
+ priority = normalized.get("priority")
+ indexed.append((priority if isinstance(priority, int) else 10**9, index, normalized))
+ return [entry for _, _, entry in sorted(indexed, key=lambda value: (value[0], value[1]))]
+
+
+def _cached_remote_payload() -> dict[str, Any]:
+ with _REMOTE_LOCK:
+ if _REMOTE_MEMORY_CACHE:
+ return dict(_REMOTE_MEMORY_CACHE)
+
+ payload = _read_cached_remote_payload(get_cached_catalog_path())
+ with _REMOTE_LOCK:
+ _REMOTE_MEMORY_CACHE.clear()
+ _REMOTE_MEMORY_CACHE.update(payload)
+ return payload
+
+
+def _remote_cache_stale(payload: dict[str, Any]) -> bool:
+ fetched_at = payload.get("fetched_at")
+ failed_at = payload.get("failed_at")
+ if isinstance(failed_at, (int, float)) and (
+ not isinstance(fetched_at, (int, float)) or float(failed_at) >= float(fetched_at)
+ ):
+ return time.time() - float(failed_at) >= REMOTE_CATALOG_FAILURE_TTL_SECONDS
+ if not isinstance(fetched_at, (int, float)):
+ return True
+ return time.time() - float(fetched_at) >= REMOTE_CATALOG_TTL_SECONDS
+
+
+def _refresh_remote_catalog_worker() -> None:
+ global _REMOTE_REFRESH_IN_FLIGHT
+ try:
+ refresh_remote_catalog_now()
+ except Exception as exc:
+ previous = _cached_remote_payload()
+ payload = {
+ "failed_at": time.time(),
+ "catalog": previous.get("catalog"),
+ "error": str(exc),
+ }
+ if isinstance(previous.get("fetched_at"), (int, float)):
+ payload["fetched_at"] = previous["fetched_at"]
+ _write_cached_remote_payload(payload)
+ finally:
+ with _REMOTE_LOCK:
+ _REMOTE_REFRESH_IN_FLIGHT = False
+
+
+def _read_catalog(path: Path) -> dict[str, Any] | None:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
+ return None
+ return _normalize_catalog(payload)
+
+
+def _read_cached_remote_payload(path: Path) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
+ return {}
+ if not isinstance(payload, dict):
+ return {}
+
+ normalized: dict[str, Any] = {}
+ catalog_valid = False
+ raw_catalog = payload.get("catalog")
+ if isinstance(raw_catalog, dict):
+ try:
+ normalized["catalog"] = _normalize_catalog(raw_catalog, strict=True)
+ catalog_valid = True
+ except ValueError:
+ pass
+ for key in ("fetched_at", "failed_at"):
+ value = payload.get(key)
+ if isinstance(value, (int, float)) and (key != "fetched_at" or catalog_valid):
+ normalized[key] = value
+ error = payload.get("error")
+ if isinstance(error, str) or error is None:
+ normalized["error"] = error
+ return normalized
+
+
+def _write_cached_remote_payload(payload: dict[str, Any]) -> None:
+ cache_path = get_cached_catalog_path()
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{cache_path.name}.", suffix=".tmp", dir=str(cache_path.parent))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, indent=2, sort_keys=True)
+ handle.write("\n")
+ Path(tmp_name).replace(cache_path)
+ finally:
+ Path(tmp_name).unlink(missing_ok=True)
+ with _REMOTE_LOCK:
+ _REMOTE_MEMORY_CACHE.clear()
+ _REMOTE_MEMORY_CACHE.update(payload)
+
+
+def _normalize_catalog(payload: object, *, strict: bool = False) -> dict[str, Any]:
+ if not isinstance(payload, dict):
+ if strict:
+ raise ValueError("Backend model catalog must be an object")
+ return {}
+ schema_version = payload.get("schema_version")
+ if strict and schema_version != 1:
+ raise ValueError(f"Unsupported backend model catalog schema version: {schema_version!r}")
+ backends = payload.get("backends")
+ if not isinstance(backends, dict):
+ if strict:
+ raise ValueError("Backend model catalog must contain a backends object")
+ return {}
+
+ normalized_backends: dict[str, Any] = {}
+ for backend, raw_backend in backends.items():
+ if not isinstance(backend, str) or not isinstance(raw_backend, dict):
+ if strict:
+ raise ValueError("Backend model catalog contains an invalid backend entry")
+ continue
+ backend_key = backend.strip().lower()
+ if strict and backend_key not in _SUPPORTED_BACKENDS:
+ raise ValueError(f"Backend model catalog contains an unsupported backend: {backend_key}")
+ models = raw_backend.get("models")
+ if not backend_key or not isinstance(models, list):
+ if strict:
+ raise ValueError(f"Backend model catalog models must be a list: {backend_key}")
+ continue
+ if strict:
+ for item in models:
+ _validate_catalog_model_entry(item, backend_key)
+ entries = [_normalize_model_entry(item) for item in models]
+ if strict and any(not entry for entry in entries):
+ raise ValueError(f"Backend model catalog contains an invalid model entry: {backend_key}")
+ normalized_backends[backend_key] = {"models": [entry for entry in entries if entry]}
+ if strict and not normalized_backends:
+ raise ValueError("Backend model catalog must contain at least one backend")
+ return {"schema_version": schema_version or 1, "backends": normalized_backends}
+
+
+def _validate_catalog_model_entry(item: object, backend: str) -> None:
+ if not isinstance(item, dict):
+ raise ValueError(f"Backend model catalog contains an invalid model entry: {backend}")
+ raw_id = item.get("id")
+ if not isinstance(raw_id, str) or not raw_id.strip():
+ raise ValueError(f"Backend model catalog contains an invalid model entry: {backend}")
+
+ for key in ("label", "visibility"):
+ value = item.get(key)
+ if value is not None and (not isinstance(value, str) or not value.strip()):
+ raise ValueError(f"Backend model catalog contains an invalid {key}: {backend}/{raw_id}")
+ visibility = item.get("visibility")
+ if isinstance(visibility, str) and visibility.strip().lower() not in _SUPPORTED_VISIBILITIES:
+ raise ValueError(f"Backend model catalog contains an invalid visibility: {backend}/{raw_id}")
+
+ priority = item.get("priority")
+ if priority is not None and (not isinstance(priority, int) or isinstance(priority, bool)):
+ raise ValueError(f"Backend model catalog contains an invalid priority: {backend}/{raw_id}")
+
+ efforts = item.get("reasoning_efforts")
+ if efforts is not None:
+ if not isinstance(efforts, list) or any(not isinstance(value, str) or not value.strip() for value in efforts):
+ raise ValueError(f"Backend model catalog contains invalid reasoning efforts: {backend}/{raw_id}")
+
+
+def _normalize_model_entry(item: object) -> dict[str, Any]:
+ if isinstance(item, str):
+ model = item.strip()
+ return {"id": model} if model else {}
+ if not isinstance(item, dict):
+ return {}
+ raw_id = item.get("id") or item.get("slug") or item.get("model") or item.get("value")
+ if not isinstance(raw_id, str) or not raw_id.strip():
+ return {}
+ entry: dict[str, Any] = {"id": raw_id.strip()}
+ label = item.get("label") or item.get("display_name") or item.get("name")
+ if isinstance(label, str) and label.strip():
+ entry["label"] = label.strip()
+ if isinstance(item.get("priority"), int):
+ entry["priority"] = item["priority"]
+ visibility = item.get("visibility")
+ if isinstance(visibility, str) and visibility.strip():
+ entry["visibility"] = visibility.strip().lower()
+ efforts = _coerce_reasoning_efforts(
+ item.get("reasoning_efforts") or item.get("supported_reasoning_levels")
+ )
+ if efforts:
+ entry["reasoning_efforts"] = efforts
+ return entry
+
+
+def _coerce_reasoning_efforts(values: object) -> list[str]:
+ if not isinstance(values, list):
+ return []
+ efforts = []
+ for value in values:
+ efforts.append(value.get("effort") if isinstance(value, dict) else value)
+ return _dedupe_str_values(efforts)
+
+
+def _dedupe_str_values(values: Iterable[object]) -> list[str]:
+ seen: set[str] = set()
+ normalized = []
+ for value in values:
+ if not isinstance(value, str):
+ continue
+ candidate = value.strip()
+ if not candidate or candidate in seen:
+ continue
+ seen.add(candidate)
+ normalized.append(candidate)
+ return normalized
diff --git a/vibe/data/backend_models.json b/vibe/data/backend_models.json
new file mode 100644
index 000000000..ea0801fdc
--- /dev/null
+++ b/vibe/data/backend_models.json
@@ -0,0 +1,37 @@
+{
+ "schema_version": 1,
+ "backends": {
+ "claude": {
+ "models": [
+ {"id": "claude-fable-5", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "claude-opus-4-8", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "claude-opus-4-7", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "claude-opus-4-6", "reasoning_efforts": ["low", "medium", "high", "max"]},
+ {"id": "claude-sonnet-5", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "claude-sonnet-4-6", "reasoning_efforts": ["low", "medium", "high", "max"]},
+ {"id": "claude-haiku-4-5", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "claude-opus-4-5", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "claude-sonnet-4-5", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "claude-opus-4", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "claude-sonnet-4", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "claude-haiku-4", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "opus", "label": "opus [1M]", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "sonnet", "label": "sonnet [1M]", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "haiku", "reasoning_efforts": ["low", "medium", "high"]},
+ {"id": "opus[1m]", "label": "opus[1m] [1M]", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "sonnet[1m]", "label": "sonnet[1m] [1M]", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]}
+ ]
+ },
+ "codex": {
+ "models": [
+ {"id": "gpt-5.6-sol", "label": "GPT-5.6-Sol", "priority": 1, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]},
+ {"id": "gpt-5.6-terra", "label": "GPT-5.6-Terra", "priority": 2, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]},
+ {"id": "gpt-5.6-luna", "label": "GPT-5.6-Luna", "priority": 3, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},
+ {"id": "gpt-5.5", "label": "GPT-5.5", "priority": 7, "reasoning_efforts": ["low", "medium", "high", "xhigh"]},
+ {"id": "gpt-5.4", "label": "GPT-5.4", "priority": 16, "reasoning_efforts": ["low", "medium", "high", "xhigh"]},
+ {"id": "gpt-5.4-mini", "label": "GPT-5.4-Mini", "priority": 23, "reasoning_efforts": ["low", "medium", "high", "xhigh"]},
+ {"id": "gpt-5.2", "label": "GPT-5.2", "priority": 29, "reasoning_efforts": ["low", "medium", "high", "xhigh"]}
+ ]
+ }
+ }
+}