Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agent): add 'vibe agent models' to discover models + reasoning efforts (#470)
Call White7f23c95dec90
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex f68de2e58..a9e7cf351 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -784,12 +784,35 @@ creation; description, model, reasoning effort, and system prompt can be edited.| --- | --- || `vibe agent list` | List Agents || `vibe agent show <name>` | Show one Agent |+| `vibe agent models [<name>]` | List available models + reasoning efforts for an Agent or backend || `vibe agent create` | Create an Agent || `vibe agent update <name>` | Edit mutable Agent fields || `vibe agent remove <name>` | Remove an Agent || `vibe agent import` | Import global Agents or a portable Agent file || `vibe agent run` | Run an Agent once |+### `vibe agent models`++List the models and reasoning-effort levels available to an Agent (by name) or to a+backend directly. Reasoning efforts are returned per model, because they are a property+of the model (Claude's `xhigh` / `max` depend on the model; OpenCode varies by variant).+For OpenCode the list includes custom providers and user-added models.++```+vibe agent models <name> # an Agent: resolves its backend + current model+vibe agent models --backend claude # a backend directly, before creating an Agent+vibe agent models --backend opencode --provider deepseek+```++- pass exactly one of `<name>` or `--backend`+- `--provider <id>` filters to one provider and applies to the OpenCode backend only+- `--model <id>` narrows the output to a single model's reasoning efforts++When queried by `<name>`, the result includes `current` — the Agent's configured+`model` / `reasoning_effort` and whether they are still valid. `create` / `update`+accept any value but warn (without rejecting) when it is not in the known set and+point back to this command.+### `vibe agent run````bashdiff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 9c4428d1c..d395c3b39 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -763,12 +763,32 @@ model、reasoning effort、system prompt 可以编辑。| --- | --- || `vibe agent list` | 列出 Agent || `vibe agent show <name>` | 查看单个 Agent |+| `vibe agent models [<name>]` | 列出某个 Agent 或后端可用的模型与推理强度 || `vibe agent create` | 创建 Agent || `vibe agent update <name>` | 修改可编辑字段 || `vibe agent remove <name>` | 删除 Agent || `vibe agent import` | 导入全局 Agent 或通用 Agent 文件 || `vibe agent run` | 运行一次 Agent |+### `vibe agent models`++列出某个 Agent(按名)或某个后端可用的模型与推理强度。推理强度按模型返回,因为它是模型的属性+(Claude 的 `xhigh` / `max` 取决于模型;OpenCode 因 variant 而异)。对 OpenCode,列表会包含自定义+provider 与用户手动添加的模型。++```+vibe agent models <name> # 某个 Agent:解析其后端与当前模型+vibe agent models --backend claude # 直接查后端,用于创建 Agent 之前+vibe agent models --backend opencode --provider deepseek+```++- `<name>` 与 `--backend` 二选一+- `--provider <id>` 按 provider 过滤,仅对 OpenCode 后端有效+- `--model <id>` 只返回单个模型的推理强度++按 `<name>` 查询时,结果包含 `current`——该 Agent 配置的 `model` / `reasoning_effort` 及其是否仍然有效。+`create` / `update` 接受任意取值,但当取值不在已知集合中时会给出警告(不拒绝),并指回本命令。+### `vibe agent run````bashdiff --git a/docs/plans/agent-models-query.md b/docs/plans/agent-models-query.mdnew file mode 100644index 000000000..b98c8e7bf--- /dev/null+++ b/docs/plans/agent-models-query.md@@ -0,0 +1,92 @@+# `vibe agent models` — query available models + reasoning efforts++## Background++`vibe agent create / update` accept `--model` and `--reasoning-effort` as free-form+strings with no `choices`, no validation, and no discovery path. An agent (or user)+calling the CLI to configure another Agent has no way to learn which models or+reasoning-effort levels a backend actually supports — it can only guess. The+knowledge already exists in the codebase (Claude catalog, Codex built-in list ++caches, OpenCode live providers incl. PR #461 custom providers / user models) but+nothing surfaces it through the CLI.++## Goal++Add `vibe agent models` so an agent can discover, for a given Agent (or backend),+the available models and the reasoning-effort levels valid for each — including+OpenCode custom providers and user-added models — and feed that back into+`create` / `update`.++## Design (approved)++Command, Agent-centric to match `vibe agent show / update / remove`:++```+vibe agent models <name> # an Agent: resolve its backend + current model+ --backend {claude,codex,opencode} # query a backend directly (pre-creation)+ --provider <id> # OpenCode-only filter (error on other backends)+ --model <id> # narrow to one model's reasoning efforts+ --json # no-op; JSON is the default envelope+```++Exactly one of `<name>` or `--backend`. Output `kind: "agent_models"`:++```+{ ok, kind: "agent_models", agent, backend,+ current: { model, reasoning_effort, model_known, reasoning_effort_valid, valid } | null,+ default_model,+ providers: [ { id, name, custom } ], # OpenCode only+ models: [ { value, default?, provider?, source?, reasoning_efforts: [...] } ],+ source, live, notes }+```++Reasoning efforts are nested **per model** because they are a property of the model+(Claude `xhigh`/`max` depend on the model; OpenCode varies by provider variant).++## Architecture — reuse, don't rebuild++- New backend-agnostic `api.agent_model_options(backend, *, model, provider, cwd)`+ wraps the three existing producers into one shape:+ - `claude_models()` → models + per-model reasoning options (already returns both)+ - `codex_models()` → **extend** to also return `reasoning_options`+ (`build_codex_reasoning_options()` already exists; just surface it)+ - `opencode_options(cwd)` → already overlays custom providers + user models+ (PR #461: `_read_opencode_custom_provider_ids` + `_merge_opencode_user_models`),+ so reusing it covers them for free. Annotate `source: user|catalog`+ (`opencode_config._is_vibe_user_model`) and `custom` providers+ (`read_opencode_custom_providers`). `--provider` filters via the existing+ `allowed_providers` concept. cwd resolved internally (`runtime.default_cwd`),+ never a CLI flag.+- The same resolver can later back the existing `/api/{claude,codex}/models`+ endpoints so the Claude reasoning rules stop being duplicated in TS+ (`RoutingConfigPanel.tsx`). Out of scope for this PR (follow-up).++## Validation policy — warn, don't reject (decision #1)++`create` / `update` keep accepting free-form values (catalogs are best-effort and+can lag a new model). When a set value is not in the known set, attach a non-fatal+`warnings` + `hint` pointing at `vibe agent models <name>`. Uses only the cheap+file-based sources (claude/codex); OpenCode is skipped (its list is live) to keep+`create`/`update` fast.++## Scope (decision #2)++In: the query command, the resolver, `codex_models()` reasoning, the create/update+warning. Out (follow-up PR): consolidating the duplicated TS reasoning rules onto+the Python source.++## Todo++- [ ] `api.agent_model_options` + `codex_models()` reasoning+- [ ] `vibe agent models` parser + `cmd_agent_models`+- [ ] create/update warn-not-reject hint+- [ ] tests (resolver, CLI, codex reasoning, warning)+- [ ] docs + ruff + targeted pytest+- [ ] reviewer subagent → PR (non-draft) → Codex review watch++## Evidence layers++- unit: codex reasoning, resolver per backend, warning helper+- contract: `cmd_agent_models` name / `--backend` / `--provider` error envelope+- scenario: n/a (no catalog entry for CLI agent mgmt yet)+- manual: `vibe agent models` against claude/codex/opencode in an isolated homediff --git a/tests/test_cli_agent_models.py b/tests/test_cli_agent_models.pynew file mode 100644index 000000000..938734891--- /dev/null+++ b/tests/test_cli_agent_models.py@@ -0,0 +1,209 @@+from __future__ import annotations++import io+import json+import sys+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from vibe import cli+++def _run(handler, args_ns):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = handler(args_ns)+ raw = out.getvalue().strip() or err.getvalue().strip()+ return code, json.loads(raw)+++def _models_ns(**overrides):+ base = {"name": None, "backend": None, "provider": None, "model": None}+ base.update(overrides)+ return SimpleNamespace(**base)+++def test_parser_registers_agent_models():+ ns = cli.build_parser().parse_args(["agent", "models", "my-agent"])+ assert ns.agent_command == "models"+ assert ns.name == "my-agent"++ ns2 = cli.build_parser().parse_args(["agent", "models", "--backend", "codex", "--provider", "x"])+ assert ns2.name is None+ assert ns2.backend == "codex"+ assert ns2.provider == "x"+++def test_cmd_agent_models_by_backend(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "backend": "codex",+ "default_model": None,+ "models": [{"value": "gpt-5.5", "default": False, "reasoning_efforts": ["high"]}],+ "providers": None,+ "source": "codex built-in list",+ "live": False,+ "notes": None,+ },+ )+ code, payload = _run(cli.cmd_agent_models, _models_ns(backend="codex"))+ assert code == 0+ assert payload["ok"] is True+ assert payload["kind"] == "agent_models"+ assert payload["backend"] == "codex"+ assert payload["agent"] is None+ assert payload["current"] is None+ assert payload["models"][0]["value"] == "gpt-5.5"+++def test_cmd_agent_models_requires_exactly_one_target():+ code, payload = _run(cli.cmd_agent_models, _models_ns())+ assert code == 1+ assert payload["ok"] is False+ assert payload["code"] == "invalid_agent_models_target"+++def test_cmd_agent_models_rejects_provider_for_non_opencode():+ code, payload = _run(cli.cmd_agent_models, _models_ns(backend="claude", provider="foo"))+ assert code == 1+ assert payload["code"] == "provider_not_supported"+++def test_cmd_agent_models_by_name_echoes_current(monkeypatch):+ agent = SimpleNamespace(+ name="my-audit", backend="claude", model="claude-opus-4-8", reasoning_effort="high"+ )+ monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "backend": "claude",+ "default_model": None,+ "models": [+ {"value": "claude-opus-4-8", "default": True, "reasoning_efforts": ["high", "max"]}+ ],+ "providers": None,+ "source": "catalog",+ "live": False,+ "notes": None,+ },+ )+ code, payload = _run(cli.cmd_agent_models, _models_ns(name="my-audit"))+ assert code == 0+ assert payload["agent"] == "my-audit"+ assert payload["backend"] == "claude"+ assert payload["current"]["model_known"] is True+ assert payload["current"]["reasoning_effort_valid"] is True+ assert payload["current"]["valid"] is True+++def test_cmd_agent_models_current_flags_invalid_effort(monkeypatch):+ agent = SimpleNamespace(+ name="drifted", backend="claude", model="claude-opus-4-8", reasoning_effort="bogus"+ )+ monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "backend": "claude",+ "default_model": None,+ "models": [{"value": "claude-opus-4-8", "default": True, "reasoning_efforts": ["high"]}],+ "providers": None,+ "source": "catalog",+ "live": False,+ "notes": None,+ },+ )+ code, payload = _run(cli.cmd_agent_models, _models_ns(name="drifted"))+ assert code == 0+ assert payload["current"]["reasoning_effort_valid"] is False+ assert payload["current"]["valid"] is False+++def test_cmd_agent_models_model_filter_keeps_current_honest(monkeypatch):+ agent = SimpleNamespace(+ name="my-audit", backend="claude", model="claude-opus-4-8", reasoning_effort="high"+ )+ monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "backend": "claude",+ "default_model": None,+ "models": [+ {"value": "claude-opus-4-8", "default": True, "reasoning_efforts": ["high", "max"]},+ {"value": "claude-sonnet-4-6", "default": False, "reasoning_efforts": ["high"]},+ ],+ "providers": None,+ "source": "catalog",+ "live": False,+ "notes": None,+ },+ )+ # query the Agent but narrow the display to a different model+ code, payload = _run(+ cli.cmd_agent_models, _models_ns(name="my-audit", model="claude-sonnet-4-6")+ )+ assert code == 0+ # --model narrows the displayed list ...+ assert [m["value"] for m in payload["models"]] == ["claude-sonnet-4-6"]+ # ... but current still reflects the Agent's real (unfiltered) model and stays valid+ assert payload["current"]["model"] == "claude-opus-4-8"+ assert payload["current"]["model_known"] is True+ assert payload["current"]["valid"] is True+++def test_agent_models_current_normalizes_opencode_bare_model():+ # OpenCode Agent stored a bare model id; it routes via the default provider, so the+ # current check must normalize it to provider/model before declaring it unknown.+ options = {+ "default_provider": "deepseek",+ "models": [{"value": "deepseek/deepseek-chat", "reasoning_efforts": ["low", "high"]}],+ }+ agent = SimpleNamespace(model="deepseek-chat", reasoning_effort="high")+ current = cli._agent_models_current(agent, options)+ assert current["model"] == "deepseek-chat" # echoes the original value+ assert current["model_known"] is True # resolved via default_provider+ assert current["reasoning_effort_valid"] is True+ assert current["valid"] is True+++def test_agent_value_warning_effort_only_unknown(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "models": [{"value": "gpt-5.5", "reasoning_efforts": ["minimal", "low", "high"]}],+ },+ )+ agent = SimpleNamespace(name="x", backend="codex", model=None, reasoning_effort="bogus")+ fields = cli._agent_value_warning_fields(agent)+ assert "warnings" in fields+ assert "bogus" in fields["warnings"][0]+ assert "vibe agent models x" in fields["hint"]+++def test_agent_value_warning_effort_only_valid(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "agent_model_options",+ lambda *a, **k: {+ "ok": True,+ "models": [{"value": "gpt-5.5", "reasoning_efforts": ["minimal", "low", "high"]}],+ },+ )+ agent = SimpleNamespace(name="x", backend="codex", model=None, reasoning_effort="high")+ assert cli._agent_value_warning_fields(agent) == {}diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 30344c796..2c1c35328 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -1594,6 +1594,103 @@ def test_codex_models_falls_back_when_cli_cache_missing(monkeypatch, tmp_path):assert "gpt-5.1-codex-mini" in result["models"]+def test_codex_models_includes_static_reasoning(monkeypatch, tmp_path):+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ result = api.codex_models()+ 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+++def test_agent_model_options_claude_strips_default_and_marks_default(monkeypatch):+ monkeypatch.setattr(+ api,+ "claude_models",+ lambda: {+ "ok": True,+ "models": ["claude-opus-4-8", "claude-sonnet-4-6"],+ "reasoning_options": {+ "claude-opus-4-8": [+ {"value": "__default__", "label": "(Default)"},+ {"value": "low", "label": "Low"},+ {"value": "max", "label": "Max"},+ ],+ "claude-sonnet-4-6": [+ {"value": "__default__", "label": "(Default)"},+ {"value": "high", "label": "High"},+ ],+ },+ },+ )+ monkeypatch.setattr(api, "_backend_default_model", lambda config, backend: "claude-opus-4-8")++ result = api.agent_model_options("claude")++ assert result["ok"] is True+ assert result["backend"] == "claude"+ assert result["live"] is False+ by_value = {m["value"]: m for m in result["models"]}+ # the UI "__default__" sentinel is stripped from the CLI-facing list+ assert by_value["claude-opus-4-8"]["reasoning_efforts"] == ["low", "max"]+ assert by_value["claude-opus-4-8"]["default"] is True+ assert by_value["claude-sonnet-4-6"]["default"] is False+++def test_agent_model_options_unknown_backend():+ result = api.agent_model_options("bogus")+ assert result["ok"] is False+ assert "bogus" in result.get("error", "")+++def test_agent_model_options_opencode_overlay_and_provider_filter(monkeypatch):+ import vibe.opencode_config as opencode_config++ fake_opencode = {+ "ok": True,+ "data": {+ "models": {+ "providers": [+ {"id": "anthropic", "name": "Anthropic", "models": {"claude-x": {}}},+ {+ "id": "deepseek",+ "name": "DeepSeek",+ "models": {"deepseek-chat": {"vibe_remote": {"user_model": True}}},+ },+ ],+ "default": {"anthropic": "claude-x"},+ },+ "reasoning_options": {+ "anthropic/claude-x": [{"value": "__default__"}, {"value": "low"}, {"value": "high"}],+ "deepseek/deepseek-chat": [{"value": "low"}],+ },+ },+ }+ monkeypatch.setattr(api, "opencode_options", lambda cwd: fake_opencode)+ monkeypatch.setattr(api, "_backend_default_model", lambda config, backend: None)+ monkeypatch.setattr(opencode_config, "read_opencode_custom_providers", lambda **kw: {"deepseek": {}})++ result = api.agent_model_options("opencode")++ assert result["ok"] is True+ assert result["live"] is True+ providers = {p["id"]: p for p in result["providers"]}+ assert providers["deepseek"]["custom"] is True+ assert providers["anthropic"]["custom"] is False+ by_value = {m["value"]: m for m in result["models"]}+ # custom-provider models + reasoning + source annotation flow through unchanged+ assert by_value["anthropic/claude-x"]["reasoning_efforts"] == ["low", "high"]+ assert by_value["anthropic/claude-x"]["default"] is True+ assert by_value["anthropic/claude-x"]["source"] == "catalog"+ assert by_value["deepseek/deepseek-chat"]["source"] == "user"++ filtered = api.agent_model_options("opencode", provider="deepseek")+ assert [p["id"] for p in filtered["providers"]] == ["deepseek"]+ assert all(m["provider"] == "deepseek" for m in filtered["models"])++def test_codex_agents_merges_global_and_project(monkeypatch, tmp_path):global_agent_dir = tmp_path / ".codex" / "agents"global_agent_dir.mkdir(parents=True)diff --git a/vibe/api.py b/vibe/api.pyindex be8bf53e3..9f89cf3d1 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2283,6 +2283,202 @@ def claude_models() -> dict:return {"ok": True, "models": options, "reasoning_options": reasoning_options}+def _effort_values(reasoning_entries: object) -> list[str]:+ """Extract settable reasoning-effort values, dropping the UI ``__default__`` sentinel."""+ out: list[str] = []+ if not isinstance(reasoning_entries, list):+ return out+ for entry in reasoning_entries:+ if not isinstance(entry, dict):+ continue+ value = entry.get("value")+ if isinstance(value, str) and value and value != "__default__" and value not in out:+ out.append(value)+ return out+++def _backend_default_model(config: Optional[V2Config], backend: str) -> Optional[str]:+ if config is None:+ return None+ agents = getattr(config, "agents", None)+ backend_cfg = getattr(agents, backend, None) if agents is not None else None+ value = getattr(backend_cfg, "default_model", None) if backend_cfg is not None else None+ return value or None+++def _flat_catalog_models(catalog: dict, default_model: Optional[str]) -> list[dict]:+ """Shape claude_models()/codex_models() output into the unified models list."""+ reasoning_map = catalog.get("reasoning_options") or {}+ models: list[dict] = []+ for model_id in catalog.get("models") or []:+ if not isinstance(model_id, str) or not model_id:+ continue+ models.append(+ {+ "value": model_id,+ "default": bool(default_model) and model_id == default_model,+ "reasoning_efforts": _effort_values(reasoning_map.get(model_id)),+ }+ )+ return models+++def _opencode_model_options(+ *,+ provider: Optional[str],+ cwd: Optional[str],+ config: Optional[V2Config],+) -> dict:+ """OpenCode model options, including custom providers and user-added models.++ Reuses ``opencode_options`` whose async path already overlays custom+ providers (``_read_opencode_custom_provider_ids``) and user models+ (``_merge_opencode_user_models``), so this only normalizes the shape and+ applies the optional ``provider`` filter.+ """++ resolved_cwd = cwd+ if not resolved_cwd:+ runtime_cfg = getattr(config, "runtime", None) if config is not None else None+ resolved_cwd = getattr(runtime_cfg, "default_cwd", None) if runtime_cfg is not None else None+ if not resolved_cwd:+ resolved_cwd = "."++ raw = opencode_options(resolved_cwd)+ if not raw.get("ok"):+ return {"ok": False, "backend": "opencode", "error": raw.get("error") or "opencode options unavailable"}++ data = raw.get("data") or {}+ models_block = data.get("models") if isinstance(data.get("models"), dict) else {}+ reasoning_map = data.get("reasoning_options") or {}+ default_block = models_block.get("default") if isinstance(models_block.get("default"), dict) else {}+ providers_raw = models_block.get("providers") if isinstance(models_block.get("providers"), list) else []++ try:+ from vibe.opencode_config import _is_vibe_user_model as _oc_is_user_model+ from vibe.opencode_config import read_opencode_custom_providers++ custom_ids = set(read_opencode_custom_providers().keys())+ except Exception:+ _oc_is_user_model = None+ custom_ids = set()++ provider_filter = (provider or "").strip().lower() or None+ providers_out: list[dict] = []+ models_out: list[dict] = []+ for prov in providers_raw:+ if not isinstance(prov, dict):+ continue+ pid = prov.get("id") or prov.get("provider_id") or prov.get("name")+ if not isinstance(pid, str) or not pid:+ continue+ if provider_filter and pid.lower() != provider_filter:+ continue+ providers_out.append({"id": pid, "name": prov.get("name") or pid, "custom": pid in custom_ids})+ prov_models = prov.get("models")+ if isinstance(prov_models, dict):+ model_items = list(prov_models.items())+ elif isinstance(prov_models, list):+ model_items = [(m.get("id"), m) for m in prov_models if isinstance(m, dict) and m.get("id")]+ else:+ model_items = []+ for model_id, model_info in model_items:+ if not isinstance(model_id, str) or not model_id:+ continue+ value = f"{pid}/{model_id}"+ source = "catalog"+ if _oc_is_user_model is not None and isinstance(model_info, dict) and _oc_is_user_model(model_id, model_info):+ source = "user"+ models_out.append(+ {+ "value": value,+ "provider": pid,+ "default": default_block.get(pid) == model_id,+ "source": source,+ "reasoning_efforts": _effort_values(reasoning_map.get(value)),+ }+ )++ opencode_cfg = getattr(getattr(config, "agents", None), "opencode", None) if config is not None else None+ default_provider = getattr(opencode_cfg, "default_provider", None) if opencode_cfg is not None else None++ notes: list[str] = []+ if provider_filter and not providers_out:+ notes.append(f"no configured OpenCode provider matches '{provider}'")+ return {+ "ok": True,+ "backend": "opencode",+ "default_model": _backend_default_model(config, "opencode"),+ "default_provider": default_provider or None,+ "providers": providers_out,+ "models": models_out,+ "source": "opencode server (live) + user config overlay",+ "live": True,+ "notes": notes or None,+ }+++def agent_model_options(+ backend: str,+ *,+ provider: Optional[str] = None,+ cwd: Optional[str] = None,+) -> dict:+ """Backend-agnostic available models + per-model reasoning efforts.++ Single entry point wrapping ``claude_models`` / ``codex_models`` /+ ``opencode_options`` into one shape so the CLI and the Web UI can share it::++ {ok, backend, default_model, models: [{value, default, reasoning_efforts,+ provider?, source?}], providers?: [{id, name, custom}], source, live, notes}++ ``provider`` filters OpenCode results (ignored for other backends). Narrowing+ to a single model is a presentation concern left to the caller.+ """++ normalized_backend = (backend or "").strip().lower()+ if normalized_backend not in ("claude", "codex", "opencode"):+ return {"ok": False, "error": f"unknown backend '{backend}'", "backend": normalized_backend}++ try:+ config: Optional[V2Config] = V2Config.load()+ except Exception:+ config = None++ if normalized_backend == "claude":+ data = claude_models()+ if not data.get("ok"):+ return {"ok": False, "backend": normalized_backend, "error": data.get("error") or "claude model lookup failed"}+ default_model = _backend_default_model(config, "claude")+ result = {+ "ok": True,+ "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."],+ }+ elif normalized_backend == "codex":+ data = codex_models()+ if not data.get("ok"):+ return {"ok": False, "backend": normalized_backend, "error": data.get("error") or "codex model lookup failed"}+ default_model = _backend_default_model(config, "codex")+ result = {+ "ok": True,+ "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."],+ }+ else:+ result = _opencode_model_options(provider=provider, cwd=cwd, config=config)++ return result++_AGENT_INSTALL_JOB_LOCK = threading.Lock()_AGENT_INSTALL_JOBS: dict[str, dict] = {}_AGENT_INSTALL_LATEST_BY_BACKEND: dict[str, str] = {}@@ -5556,6 +5752,18 @@ def codex_models() -> dict: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",@@ -5610,7 +5818,7 @@ def codex_models() -> dict:tomllib = Noneif tomllib is None:- return {"ok": True, "models": options}+ return _result(options)data = tomllib.loads(config_path.read_text(encoding="utf-8"))if isinstance(data, dict):@@ -5625,7 +5833,7 @@ def codex_models() -> dict:except Exception as exc:logger.warning("Failed to read Codex config.toml: %s", exc, exc_info=True)- return {"ok": True, "models": options}+ return _result(options)def _lark_api_base(domain: str = "feishu") -> str:diff --git a/vibe/cli.py b/vibe/cli.pyindex 37bcc5de2..cb7e948c7 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -2269,6 +2269,140 @@ def cmd_agent_show(args):return 1+def _agent_models_current(agent, options: dict) -> dict:+ """Echo an Agent's currently-set model/effort and whether they remain valid."""+ by_value = {entry.get("value"): entry for entry in options.get("models") or []}+ model = agent.model+ effort = agent.reasoning_effort+ # An OpenCode Agent may store a bare model id that routes through the configured+ # default provider; normalize it to the catalog's provider/model key before lookup+ # so a valid bare-id Agent is not reported as unknown.+ resolved = model+ if model and model not in by_value and "/" not in model:+ default_provider = options.get("default_provider")+ if default_provider and f"{default_provider}/{model}" in by_value:+ resolved = f"{default_provider}/{model}"+ model_known: bool | None = (resolved in by_value) if model else None+ effort_valid: bool | None = None+ if effort and model and model_known:+ effort_valid = effort in (by_value[resolved].get("reasoning_efforts") or [])+ valid = not (model_known is False or effort_valid is False)+ return {+ "model": model,+ "reasoning_effort": effort,+ "model_known": model_known,+ "reasoning_effort_valid": effort_valid,+ "valid": valid,+ }+++def cmd_agent_models(args):+ try:+ name = getattr(args, "name", None)+ backend_arg = getattr(args, "backend", None)+ provider = getattr(args, "provider", None)+ model = getattr(args, "model", None)+ if bool(name) == bool(backend_arg):+ raise TaskCliError(+ "provide exactly one of <name> or --backend",+ code="invalid_agent_models_target",+ hint="Pass an Agent name to use its backend, or --backend to query a backend directly.",+ help_command="vibe agent models --help",+ )+ agent = None+ if name:+ try:+ agent = _agent_store().require(name)+ except Exception as exc:+ raise TaskCliError(str(exc), code="agent_not_found", details={"agent": name}) from exc+ backend = agent.backend+ else:+ backend = validate_agent_backend(backend_arg)+ if provider and backend != "opencode":+ raise TaskCliError(+ f"--provider is only supported for the opencode backend, not '{backend}'",+ code="provider_not_supported",+ hint="Providers are an OpenCode concept; drop --provider for claude/codex.",+ help_command="vibe agent models --help",+ )+ options = api.agent_model_options(backend, provider=provider)+ if not options.get("ok"):+ raise TaskCliError(+ options.get("error") or "failed to load model options",+ code="agent_models_unavailable",+ details={"backend": backend},+ help_command="vibe agent models --help",+ )+ # `current` validity is checked against the full set; --model only narrows+ # the displayed list, so an Agent's real model is never hidden from it.+ current = _agent_models_current(agent, options) if agent else None+ models = options.get("models", [])+ if model:+ models = [entry for entry in models if entry.get("value") == model]+ _print_cli_payload(+ "agent_models",+ agent=agent.name if agent else None,+ backend=backend,+ current=current,+ default_model=options.get("default_model"),+ providers=options.get("providers"),+ models=models,+ source=options.get("source"),+ live=options.get("live", False),+ notes=options.get("notes"),+ )+ return 0+ except Exception as exc:+ _print_task_error(exc, help_command="vibe agent models --help")+ return 1+++def _agent_value_warning_fields(agent) -> dict:+ """Best-effort, non-fatal warnings when an Agent's model/effort is unknown.++ Cheap (file-based) check for claude/codex only; OpenCode availability is+ live (needs the OpenCode server) so it is skipped here to keep create/update+ fast — ``vibe agent models`` is the place for the full OpenCode check.+ """+ if agent.backend not in ("claude", "codex"):+ return {}+ if not agent.model and not agent.reasoning_effort:+ return {}+ try:+ options = api.agent_model_options(agent.backend)+ except Exception:+ return {}+ if not options.get("ok"):+ return {}+ by_value = {entry.get("value"): entry for entry in options.get("models") or []}+ model_unknown = bool(agent.model) and agent.model not in by_value+ warnings: list[str] = []+ if model_unknown:+ warnings.append(+ f"model '{agent.model}' is not in the known {agent.backend} model list; "+ "it may be a typo or newer than the catalog"+ )+ if agent.reasoning_effort:+ if agent.model and not model_unknown:+ allowed = set(by_value[agent.model].get("reasoning_efforts") or [])+ scope = f"model '{agent.model}'"+ else:+ # model unset or unknown: accept any effort valid for some model of this backend+ # (Codex efforts are backend-wide; Claude's widest set still lives in some model)+ allowed = set()+ for entry in by_value.values():+ allowed.update(entry.get("reasoning_efforts") or [])+ scope = f"backend '{agent.backend}'"+ if allowed and agent.reasoning_effort not in allowed:+ warnings.append(f"reasoning_effort '{agent.reasoning_effort}' is not valid for {scope}")+ if not warnings:+ return {}+ return {+ "warnings": warnings,+ "hint": f"Run `vibe agent models {agent.name}` to list valid models and reasoning efforts.",+ }++def cmd_agent_create(args):try:system_prompt = args.system_prompt@@ -2284,7 +2418,7 @@ def cmd_agent_create(args):metadata=_parse_metadata_json(args.metadata),enabled=not bool(getattr(args, "disabled", False)),)- _print_cli_payload("agent", agent=_agent_payload(agent))+ _print_cli_payload("agent", agent=_agent_payload(agent), **_agent_value_warning_fields(agent))return 0except Exception as exc:_print_task_error(exc)@@ -2325,7 +2459,7 @@ def cmd_agent_update(args):hint="Pass at least one editable field. Agent name and backend are immutable.",)agent = _agent_store().update(args.name, **kwargs)- _print_cli_payload("agent", agent=_agent_payload(agent))+ _print_cli_payload("agent", agent=_agent_payload(agent), **_agent_value_warning_fields(agent))return 0except Exception as exc:_print_task_error(exc)@@ -4974,7 +5108,7 @@ def build_parser():)agent_subparsers = agent_parser.add_subparsers(dest="agent_command",- metavar="{list,show,create,update,enable,disable,remove,import,run}",+ metavar="{list,show,models,create,update,enable,disable,remove,import,run}",)agent_subparsers.required = True@@ -4989,6 +5123,29 @@ def build_parser():agent_show_parser.add_argument("name", help="Agent name")_add_json_noop(agent_show_parser)+ agent_models_parser = agent_subparsers.add_parser(+ "models",+ help="List available models and reasoning efforts for an Agent or backend",+ description=(+ "List the models and reasoning-effort levels available to an Agent (by name) "+ "or to a backend directly. Reasoning efforts are nested per model. For OpenCode "+ "this includes custom providers and user-added models; use --provider to filter."+ ),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe agent models --help",+ )+ agent_models_parser.add_argument(+ "name", nargs="?", help="Agent name. Omit and pass --backend to query a backend directly."+ )+ agent_models_parser.add_argument(+ "--backend", choices=("codex", "claude", "opencode"), help="Query a backend directly instead of an Agent."+ )+ agent_models_parser.add_argument(+ "--provider", help="Filter to one OpenCode provider id (OpenCode backend only)."+ )+ agent_models_parser.add_argument("--model", help="Only show reasoning efforts for this model id.")+ _add_json_noop(agent_models_parser)+agent_create_parser = agent_subparsers.add_parser("create", help="Create a Vibe Agent")agent_create_parser.add_argument("name", help="Globally unique Agent name")agent_create_parser.add_argument("--backend", required=True, choices=("codex", "claude", "opencode"))@@ -5770,6 +5927,8 @@ def main():sys.exit(cmd_agent_list(args))if args.agent_command == "show":sys.exit(cmd_agent_show(args))+ if args.agent_command == "models":+ sys.exit(cmd_agent_models(args))if args.agent_command == "create":sys.exit(cmd_agent_create(args))if args.agent_command == "update":