feat(subagents): discover Antigravity models and surface catalog sources (#2897, part 1)

This commit is contained in:
XingyuHou
2026-12-02 05:42:29 -05:00
committed by Bingxi Zhao (Frank)
parent 841aa1af68
commit 845e45bf33
11 changed files with 467 additions and 47 deletions

View File

@@ -1,5 +1,5 @@
{
"fingerprint": "5c446253403279c15a2e275ba48fb4c995165603a215dc90ccb48df4f1b30e3f",
"fingerprint": "4dc565c7d0102c853bc2b88c24e6e328e4ae981e85176f6034ddf1b7c8d48a81",
"routers": {
"deeptutor.api.routers.auth:router": [
{

View File

@@ -62,13 +62,17 @@ async def detect_subagents():
@router.get("/backends/options")
async def backend_options():
"""Synced model + reasoning-effort options per backend (settings page sync)."""
from deeptutor.multi_user.context import get_current_user
from deeptutor.services.subagent.models import list_backend_options
options = await list_backend_options()
if get_current_user().is_admin:
options = await list_backend_options()
else:
options = await list_backend_options(include_account_catalogs=False)
return {"backends": [o.to_dict() for o in options]}
@router.post("/backends/{kind}/sync")
@router.post("/backends/{kind}/sync", dependencies=[Depends(require_admin)])
async def sync_backend(kind: str):
"""Re-pull one backend's model catalog (the settings "sync" button).

View File

@@ -19,7 +19,7 @@ in a same-named field:
Sessions resume with ``--conversation <conversation_id>`` (the id the ``init``
event hands back), the model is pinned with ``--model`` and reasoning depth with
``--effort low|medium|high``.
``--effort low|medium|high|xhigh|max``.
Permissions differ from Gemini CLI in a way worth stating: headless ``agy``
*soft-denies* tools that would need approval rather than blocking on them, so an
@@ -76,7 +76,7 @@ _SKIP_PERMISSION_MODES = frozenset({"bypassPermissions", "acceptEdits"})
# `--effort` accepts exactly these; anything else is dropped rather than passed
# through to a non-zero exit on an unknown value.
_EFFORTS = frozenset({"low", "medium", "high"})
_EFFORTS = frozenset({"low", "medium", "high", "xhigh", "max"})
# Terminal statuses the CLI reports in its `result` event.
_FAILED_STATUSES = frozenset({"ERROR", "CANCELED", "INTERRUPTED", "INVALID"})

View File

@@ -44,25 +44,46 @@ def _cache_path():
return get_path_service().get_settings_file(_CACHE_FILE)
def load_cached_claude_models() -> tuple[list[dict[str, str]], str]:
"""Return ``(models, fetched_at)`` from the cache, or ``([], "")`` if none.
def load_cached_claude_catalog() -> tuple[list[dict[str, str]], str, str]:
"""Return ``(models, fetched_at, source)`` from the cache.
Each model is ``{"slug", "display_name"}``. Pure read — no capture.
Each model is ``{"slug", "display_name"}``. ``source`` is ``"sdk"`` or
``"tui"`` for caches written with provenance, ``"cache"`` for legacy caches
that predate source tracking, or ``""`` when no cached models exist.
"""
path = _cache_path()
if not path.exists():
return [], ""
return [], "", ""
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
logger.warning("failed to read %s; ignoring", path, exc_info=True)
return [], ""
return [], "", ""
if not isinstance(data, dict):
return [], "", ""
models = [
{"slug": str(m["slug"]), "display_name": str(m.get("display_name") or m["slug"])}
for m in data.get("models", [])
if isinstance(m, dict) and m.get("slug")
]
return models, str(data.get("fetched_at") or "")
fetched_at = str(data.get("fetched_at") or "")
raw_source = str(data.get("source") or "").strip().lower()
if not models:
source = ""
elif raw_source in {"sdk", "tui"}:
source = raw_source
else:
source = "cache"
return models, fetched_at, source
def load_cached_claude_models() -> tuple[list[dict[str, str]], str]:
"""Return ``(models, fetched_at)`` from the cache, or ``([], "")`` if none.
Each model is ``{"slug", "display_name"}``. Pure read — no capture.
"""
models, fetched_at, _ = load_cached_claude_catalog()
return models, fetched_at
async def sync_claude_models() -> tuple[list[dict[str, str]], str]:
@@ -80,7 +101,7 @@ async def sync_claude_models() -> tuple[list[dict[str, str]], str]:
models = []
if models:
fetched_at = datetime.now(timezone.utc).isoformat()
_write_cache(models, fetched_at)
_write_cache(models, fetched_at, source="sdk")
return models, fetched_at
try:
@@ -95,7 +116,7 @@ async def sync_claude_models() -> tuple[list[dict[str, str]], str]:
logger.warning("claude /model capture parsed no models")
return [], ""
fetched_at = datetime.now(timezone.utc).isoformat()
_write_cache(models, fetched_at)
_write_cache(models, fetched_at, source="tui")
return models, fetched_at
@@ -105,10 +126,12 @@ async def _discover_sdk_models() -> list[dict[str, str]]:
return await discover_models()
def _write_cache(models: list[dict[str, str]], fetched_at: str) -> None:
def _write_cache(models: list[dict[str, str]], fetched_at: str, source: str = "") -> None:
path = _cache_path()
path.parent.mkdir(parents=True, exist_ok=True)
payload = {"fetched_at": fetched_at, "models": models}
payload: dict[str, object] = {"fetched_at": fetched_at, "models": models}
if source:
payload["source"] = source
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
@@ -249,4 +272,4 @@ def _cleanup_dir(path: str) -> None:
shutil.rmtree(path, ignore_errors=True)
__all__ = ["load_cached_claude_models", "sync_claude_models"]
__all__ = ["load_cached_claude_catalog", "load_cached_claude_models", "sync_claude_models"]

View File

@@ -29,12 +29,16 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
import json
import logging
import os
from pathlib import Path
import re
import signal
import time
from typing import Any
from deeptutor.services.subagent.process import (
@@ -57,8 +61,12 @@ _CLAUDE_MODELS = (
)
_CLAUDE_EFFORTS = ("low", "medium", "high", "xhigh", "max")
# Antigravity CLI: ``--effort`` accepts exactly these three.
_ANTIGRAVITY_EFFORTS = ("low", "medium", "high")
# Antigravity CLI: ``--effort`` accepts low|medium|high|xhigh|max.
_ANTIGRAVITY_EFFORTS = ("low", "medium", "high", "xhigh", "max")
_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
_AGY_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]*$")
_AGY_HEADER_SLUGS = frozenset({"model", "models", "id", "slug"})
_AGY_HEADER_NAMES = frozenset({"name", "display", "display name", "description"})
# opencode family: ``--variant`` — provider-relative reasoning effort.
_OPENCODE_EFFORTS = ("minimal", "high", "max")
@@ -118,6 +126,9 @@ class BackendOptions:
allow_custom_model: bool = False
# Freshness of a synced source, if any (Codex cache fetch time).
synced_at: str = ""
# Where the current ``models`` list came from: "sdk", "tui", "cache", "cli",
# "fallback", or "none" when the backend has no enumerable catalog.
catalog_source: str = ""
detail: str = ""
def to_dict(self) -> dict[str, Any]:
@@ -131,6 +142,7 @@ class BackendOptions:
"efforts": list(self.efforts),
"allow_custom_model": self.allow_custom_model,
"synced_at": self.synced_at,
"catalog_source": self.catalog_source,
"detail": self.detail,
}
@@ -154,13 +166,13 @@ def _codex_default_model() -> str:
async def _claude_options() -> BackendOptions:
from deeptutor.services.subagent.claude_models import load_cached_claude_models
from deeptutor.services.subagent.claude_models import load_cached_claude_catalog
backend = get_backend("claude_code")
ok, text = await probe_version([backend.cli_command, "--version"]) if backend else (False, "")
# Prefer a live-synced catalog (scraped from ``/model``); fall back to the
# curated aliases until the user syncs.
cached, synced_at = load_cached_claude_models()
# Prefer a live-synced catalog (SDK handshake or ``/model`` scrape); fall
# back to curated aliases until the user syncs.
cached, synced_at, cached_source = load_cached_claude_catalog()
pairs = [(m["slug"], m["display_name"]) for m in cached] or list(_CLAUDE_MODELS)
return BackendOptions(
kind="claude_code",
@@ -175,6 +187,7 @@ async def _claude_options() -> BackendOptions:
efforts=list(_CLAUDE_EFFORTS),
allow_custom_model=True,
synced_at=synced_at,
catalog_source=cached_source if cached else "fallback",
detail="" if ok else (text or "claude CLI not found on PATH"),
)
@@ -220,6 +233,7 @@ async def _codex_options() -> BackendOptions:
efforts=["none", "minimal", "low", "medium", "high", "xhigh"],
allow_custom_model=True,
synced_at=synced_at,
catalog_source="cache" if models else "none",
detail="" if ok else (version or "codex CLI not found on PATH"),
)
@@ -231,23 +245,146 @@ async def _probe(kind: str) -> tuple[bool, str]:
return await probe_version([backend.cli_command, "--version"])
async def _antigravity_options() -> BackendOptions:
def _parse_antigravity_models(text: str) -> list[ModelOption]:
"""Parse ``agy models`` output into ``ModelOption`` entries.
Non-TTY stdout uses ``<slug>\\t<display name>``; TTY output uses padded
columns (2+ spaces) and may prepend spinner frames separated by ``\\r``.
"""
models: list[ModelOption] = []
seen: set[str] = set()
for raw in text.splitlines():
line = _ANSI_ESCAPE_RE.sub("", raw.rsplit("\r", 1)[-1]).strip()
if not line:
continue
parts = re.split(r"\t+|\s{2,}", line, maxsplit=1)
slug = parts[0].strip()
display = parts[1].strip() if len(parts) > 1 else ""
if (
not slug
or slug.endswith(".")
or ".." in slug
or not _AGY_SLUG_RE.match(slug)
):
continue
if slug.lower() in _AGY_HEADER_SLUGS and display.lower() in _AGY_HEADER_NAMES:
continue
if slug in seen:
continue
seen.add(slug)
models.append(
ModelOption(
slug=slug,
display_name=display or slug,
efforts=list(_ANTIGRAVITY_EFFORTS),
)
)
return models
_ANTIGRAVITY_CACHE_TTL_S = 300.0
_antigravity_models_cache: tuple[str, list[ModelOption], str, float] | None = None
async def _terminate_subprocess(
process: asyncio.subprocess.Process,
*,
force_group: bool = False,
) -> None:
"""Terminate a timed-out or cancelled subprocess (and its POSIX process group).
When ``force_group`` is true, signal the POSIX process group even if the
group leader already exited (a descendant may still hold stdout open).
"""
if process.returncode is not None and not force_group:
return
if os.name == "posix":
with suppress(ProcessLookupError, PermissionError, OSError):
os.killpg(process.pid, signal.SIGKILL)
if process.returncode is None:
with suppress(ProcessLookupError, OSError):
process.kill()
with suppress(TimeoutError, asyncio.TimeoutError, OSError):
await asyncio.wait_for(process.wait(), timeout=2.0)
async def _list_antigravity_models(cli_command: str) -> list[ModelOption]:
"""Run ``agy models`` and return its live account model catalog."""
cmd = resolve_cli_command([cli_command, "models"])
process: asyncio.subprocess.Process | None = None
timed_out_or_cancelled = False
spawn_kwargs: dict[str, Any] = {
"stdin": asyncio.subprocess.DEVNULL,
"stdout": asyncio.subprocess.PIPE,
"stderr": asyncio.subprocess.DEVNULL,
}
if os.name == "posix":
spawn_kwargs["start_new_session"] = True
try:
process = await asyncio.create_subprocess_exec(*cmd, **spawn_kwargs)
out, _ = await asyncio.wait_for(process.communicate(), timeout=20.0)
except FileNotFoundError:
return []
except (TimeoutError, asyncio.TimeoutError):
timed_out_or_cancelled = True
return []
except asyncio.CancelledError:
timed_out_or_cancelled = True
raise
except Exception: # pragma: no cover - defensive
logger.warning("failed to enumerate %s models", cli_command, exc_info=True)
return []
finally:
if process is not None and (process.returncode is None or timed_out_or_cancelled):
await asyncio.shield(
_terminate_subprocess(process, force_group=timed_out_or_cancelled)
)
if process.returncode != 0:
return []
return _parse_antigravity_models((out or b"").decode("utf-8", "replace"))
async def _antigravity_options(
*,
include_models: bool = True,
refresh: bool = False,
) -> BackendOptions:
global _antigravity_models_cache
from deeptutor.services.subagent.antigravity import (
_NOT_FOUND_DETAIL as _ANTIGRAVITY_NOT_FOUND,
)
backend = get_backend("antigravity")
cli = backend.cli_command if backend else "agy"
ok, version = await _probe("antigravity")
models: list[ModelOption] = []
synced_at = ""
if ok and include_models:
now = time.monotonic()
cached = _antigravity_models_cache
if (
not refresh
and cached is not None
and cached[0] == cli
and now - cached[3] < _ANTIGRAVITY_CACHE_TTL_S
):
models = list(cached[1])
synced_at = cached[2]
else:
models = await _list_antigravity_models(cli)
synced_at = datetime.now(timezone.utc).isoformat() if models else ""
if models:
_antigravity_models_cache = (cli, list(models), synced_at, now)
return BackendOptions(
kind="antigravity",
display_name="Antigravity CLI",
available=ok,
version=version if ok else "",
# `agy models` prints the live list, and the slugs move with the Gemini
# releases behind them; naming a stale set here would be worse than
# letting the operator paste the one they ran.
models=[],
models=models,
efforts=list(_ANTIGRAVITY_EFFORTS),
allow_custom_model=True,
synced_at=synced_at,
catalog_source="cli" if models else "none",
detail="" if ok else not_found_detail(version, _ANTIGRAVITY_NOT_FOUND),
)
@@ -262,6 +399,7 @@ async def _kimi_options() -> BackendOptions:
models=[], # no model-list surface; free text only
efforts=[],
allow_custom_model=True,
catalog_source="none",
detail="" if ok else (version or "kimi CLI not found on PATH"),
)
@@ -279,6 +417,7 @@ async def _grok_options() -> BackendOptions:
models=[],
efforts=[],
allow_custom_model=True,
catalog_source="none",
detail=detected.detail if detected else "Grok CLI backend unavailable",
)
@@ -329,6 +468,8 @@ async def _opencode_family_options(
models=models,
efforts=list(_OPENCODE_EFFORTS),
allow_custom_model=True,
synced_at=datetime.now(timezone.utc).isoformat() if models else "",
catalog_source="cli" if models else "none",
detail="" if ok else (version or f"{cli} CLI not found on PATH"),
)
@@ -361,6 +502,7 @@ async def _free_text_options(
models=[],
efforts=list(efforts),
allow_custom_model=True,
catalog_source="none",
detail="" if available else not_found_detail(version, f"{cli} CLI not found on PATH"),
)
@@ -380,6 +522,7 @@ async def _hermes_remote_options() -> BackendOptions:
models=[],
efforts=list(_HERMES_EFFORTS),
allow_custom_model=True,
catalog_source="none",
detail=detected.detail if detected else "incompatible",
)
@@ -410,9 +553,15 @@ _PROVIDERS: dict[str, Callable[..., Awaitable[BackendOptions]]] = {
}
async def list_backend_options() -> list[BackendOptions]:
async def list_backend_options(*, include_account_catalogs: bool = True) -> list[BackendOptions]:
"""Synced model/effort options for every backend (the /settings sync source)."""
results = await asyncio.gather(*(provider() for provider in _PROVIDERS.values()))
async def _run(kind: str, provider: Callable[..., Awaitable[BackendOptions]]) -> BackendOptions:
if kind == "antigravity" and not include_account_catalogs:
return await _antigravity_options(include_models=False)
return await provider()
results = await asyncio.gather(*(_run(k, p) for k, p in _PROVIDERS.items()))
return list(results)
@@ -421,14 +570,17 @@ async def sync_backend_options(kind: str) -> BackendOptions:
Claude Code has no machine-readable catalog, so we actively scrape its
``/model`` TUI and cache the result. Codex's cache is maintained by its own
CLI (a fresh read suffices), and the opencode family re-runs ``models
--refresh``. The rest have nothing external to refresh.
CLI (a fresh read suffices), Antigravity re-runs ``agy models``, and the
opencode family re-runs ``models --refresh``. The rest have nothing
external to refresh.
"""
if kind == "claude_code":
from deeptutor.services.subagent.claude_models import sync_claude_models
await sync_claude_models() # writes the cache that _claude_options reads
return await _claude_options()
if kind == "antigravity":
return await _antigravity_options(include_models=True, refresh=True)
if kind in ("opencode", "mimo"):
return await _PROVIDERS[kind](refresh=True)
provider = _PROVIDERS.get(kind, _codex_options)

View File

@@ -305,6 +305,42 @@ def test_backend_sync_endpoint(client, monkeypatch):
assert client.post("/api/subagents/backends/bogus/sync").status_code == 400
def test_non_admin_options_skip_account_catalogs(client, monkeypatch, tmp_path):
from deeptutor.multi_user.models import CurrentUser, UserScope
from deeptutor.multi_user.paths import user_context
from deeptutor.services.subagent import models as models_mod
from deeptutor.services.subagent.models import BackendOptions
seen_flags: list[bool] = []
async def fake_options(*, include_account_catalogs: bool = True):
seen_flags.append(include_account_catalogs)
return [
BackendOptions(
kind="antigravity",
display_name="Antigravity CLI",
available=True,
version="1.5.15",
models=[],
efforts=["low", "medium", "high", "xhigh", "max"],
allow_custom_model=True,
catalog_source="none",
)
]
monkeypatch.setattr(models_mod, "list_backend_options", fake_options)
reader = CurrentUser(
id="u_reader",
username="reader",
role="user",
scope=UserScope(kind="user", user_id="u_reader", root=tmp_path / "reader"),
)
with user_context(reader):
res = client.get("/api/subagents/backends/options")
assert res.status_code == 200
assert seen_flags == [False]
def test_settings_put_merges_per_field_and_backend(client):
# Save one field for claude_code …
r1 = client.put(

View File

@@ -90,8 +90,17 @@ def test_cautious_modes_keep_the_clis_soft_deny(mode: str) -> None:
assert "--dangerously-skip-permissions" not in cmd
@pytest.mark.parametrize("effort", ["low", "medium", "high", "xhigh", "max"])
def test_supported_efforts_are_passed_through(effort: str) -> None:
cmd = AntigravityBackend()._build_command(
"hi", session_id=None, config=BackendConfig(effort=effort)
)
assert cmd[cmd.index("--effort") + 1] == effort
def test_unknown_effort_is_dropped_rather_than_passed_through() -> None:
"""`--effort` only accepts low/medium/high; anything else exits non-zero."""
"""`--effort` only accepts low/medium/high/xhigh/max; anything else exits non-zero."""
cmd = AntigravityBackend()._build_command(
"hi", session_id=None, config=BackendConfig(effort="ultra")
)
@@ -258,14 +267,133 @@ def test_gemini_cli_is_retired_from_the_subagent_registry() -> None:
@pytest.mark.asyncio
async def test_options_expose_the_effort_flag_and_free_text_models() -> None:
from deeptutor.services.subagent.models import sync_backend_options
async def test_options_expose_live_models_and_full_effort_scale(monkeypatch) -> None:
from deeptutor.services.subagent import models as models_mod
from deeptutor.services.subagent.models import ModelOption, sync_backend_options
async def fake_probe(_kind: str) -> tuple[bool, str]:
return True, "1.5.15"
async def fake_list(_cli: str) -> list[ModelOption]:
return [
ModelOption(
slug="gemini-4-neon-xhigh",
display_name="Gemini 4 Neon (XHigh)",
efforts=list(models_mod._ANTIGRAVITY_EFFORTS),
)
]
monkeypatch.setattr(models_mod, "_probe", fake_probe)
monkeypatch.setattr(models_mod, "_list_antigravity_models", fake_list)
options = await sync_backend_options("antigravity")
assert options.kind == "antigravity"
assert [e for e in options.efforts] == ["low", "medium", "high"]
assert options.efforts == ["low", "medium", "high", "xhigh", "max"]
assert options.allow_custom_model is True
assert options.catalog_source == "cli"
assert options.synced_at
assert [m.slug for m in options.models] == ["gemini-4-neon-xhigh"]
assert options.models[0].display_name == "Gemini 4 Neon (XHigh)"
def test_parse_antigravity_models_handles_tsv_padded_and_spinner_noise() -> None:
from deeptutor.services.subagent.models import _parse_antigravity_models
raw = (
"\r⠋ Fetching available models...\r⠙ Fetching available models...\r"
"gemini-4-neon-high\tGemini 4 Neon (High)\n"
"\x1b[32mgemini-4-neon-xhigh\x1b[0m Gemini 4 Neon (XHigh)\n"
"MODEL DISPLAY NAME\n"
"gemini-4-neon-high\tDuplicate Should Be Dropped\n"
"Fetching available models...\n"
"claude-opus-5-5-high\tClaude Opus 5.5 (High)\n"
)
parsed = _parse_antigravity_models(raw)
assert [(m.slug, m.display_name) for m in parsed] == [
("gemini-4-neon-high", "Gemini 4 Neon (High)"),
("gemini-4-neon-xhigh", "Gemini 4 Neon (XHigh)"),
("claude-opus-5-5-high", "Claude Opus 5.5 (High)"),
]
assert parsed[0].efforts == ["low", "medium", "high", "xhigh", "max"]
@pytest.mark.asyncio
async def test_list_antigravity_models_ignores_nonzero_exit(monkeypatch) -> None:
from deeptutor.services.subagent import models as models_mod
class _FailedProc:
returncode = 1
async def communicate(self):
return b"not-logged-in\tShould Not Parse\n", b""
async def fake_exec(*_args, **_kwargs):
return _FailedProc()
monkeypatch.setattr(models_mod.asyncio, "create_subprocess_exec", fake_exec)
monkeypatch.setattr(models_mod, "resolve_cli_command", lambda cmd: cmd)
assert await models_mod._list_antigravity_models("agy") == []
@pytest.mark.asyncio
async def test_list_antigravity_models_terminates_subprocess_on_cancel(monkeypatch) -> None:
import asyncio
from deeptutor.services.subagent import models as models_mod
started = asyncio.Event()
killed = False
class _HangingProc:
pid = 999_999_999
returncode = None
async def communicate(self):
started.set()
await asyncio.Event().wait()
def kill(self):
nonlocal killed
killed = True
self.returncode = -9
async def wait(self):
return -9
async def fake_exec(*_args, **_kwargs):
return _HangingProc()
monkeypatch.setattr(models_mod.asyncio, "create_subprocess_exec", fake_exec)
monkeypatch.setattr(models_mod, "resolve_cli_command", lambda cmd: cmd)
task = asyncio.create_task(models_mod._list_antigravity_models("agy"))
await started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert killed is True
@pytest.mark.asyncio
async def test_antigravity_options_skip_account_models_for_non_admin(monkeypatch) -> None:
from deeptutor.services.subagent import models as models_mod
async def fake_probe(_kind: str) -> tuple[bool, str]:
return True, "1.5.15"
async def forbidden_list(_cli: str):
raise AssertionError("agy models must not run when include_models=False")
monkeypatch.setattr(models_mod, "_probe", fake_probe)
monkeypatch.setattr(models_mod, "_list_antigravity_models", forbidden_list)
opts = await models_mod._antigravity_options(include_models=False)
assert opts.available is True
assert opts.models == []
assert opts.catalog_source == "none"
def test_missing_cli_detail_says_something_the_status_chip_does_not() -> None:

View File

@@ -170,3 +170,49 @@ async def test_user_cancellation_does_not_launch_fallback(monkeypatch, cache):
)
with pytest.raises(asyncio.CancelledError):
await module.sync_claude_models()
@pytest.mark.asyncio
async def test_claude_catalog_tracks_sdk_tui_legacy_and_fallback_sources(monkeypatch, cache):
from deeptutor.services.subagent import models as models_mod
monkeypatch.setattr(models_mod, "probe_version", lambda _cmd: _async_val((True, "2.x")))
# 1) No cache -> fallback
opts = await models_mod._claude_options()
assert opts.catalog_source == "fallback"
# 2) SDK sync -> source="sdk"
async def discover():
return claude_sdk.parse_models(ROWS)
monkeypatch.setattr(module, "_discover_sdk_models", discover)
await module.sync_claude_models()
models, stamp, source = module.load_cached_claude_catalog()
assert models and stamp and source == "sdk"
assert (await models_mod._claude_options()).catalog_source == "sdk"
# 3) TUI fallback sync -> source="tui"
async def missing():
raise ImportError("no sdk")
monkeypatch.setattr(module, "_discover_sdk_models", missing)
monkeypatch.setattr(
module,
"_capture_model_screen",
lambda: "Select model\n 1. Sonnet Sonnet Test · Fast",
)
await module.sync_claude_models()
_, _, source = module.load_cached_claude_catalog()
assert source == "tui"
assert (await models_mod._claude_options()).catalog_source == "tui"
# 4) Legacy cache without "source" key -> source="cache"
module._write_cache([{"slug": "opus", "display_name": "Opus"}], "2026-01-01T00:00:00Z")
_, _, source = module.load_cached_claude_catalog()
assert source == "cache"
assert (await models_mod._claude_options()).catalog_source == "cache"
async def _async_val(value):
return value

View File

@@ -794,8 +794,12 @@ async def test_claude_options_prefers_synced_cache(monkeypatch) -> None:
monkeypatch.setattr(
cm,
"load_cached_claude_models",
lambda: ([{"slug": "opus", "display_name": "Opus 4.8 (synced)"}], "2026-06-17T00:00:00Z"),
"load_cached_claude_catalog",
lambda: (
[{"slug": "opus", "display_name": "Opus 4.8 (synced)"}],
"2026-06-17T00:00:00Z",
"sdk",
),
)
async def fake_probe(cmd):
@@ -807,6 +811,7 @@ async def test_claude_options_prefers_synced_cache(monkeypatch) -> None:
assert [m.slug for m in opts.models] == ["opus"]
assert opts.models[0].display_name == "Opus 4.8 (synced)"
assert opts.synced_at == "2026-06-17T00:00:00Z"
assert opts.catalog_source == "sdk"
# ---- persistent session registry (cross-turn continuity) ---------------------

View File

@@ -108,7 +108,7 @@ const KIND_FEATURES: Record<string, KindFeatures> = {
forwardImages: false,
},
antigravity: {
effort: true, // --effort low|medium|high
effort: true, // --effort low|medium|high|xhigh|max
systemPrompt: true,
permissionMode: true, // permissive modes map onto --dangerously-skip-permissions
codexSandbox: false,
@@ -189,6 +189,7 @@ const DISPLAY_NAMES: Record<string, string> = {
claude_code: "Claude Code",
codex: "Codex",
grok: "Grok CLI",
antigravity: "Antigravity CLI",
kimi: "Kimi CLI",
opencode: "opencode",
mimo: "MiMo Code",
@@ -205,6 +206,10 @@ const SYSTEM_PROMPT_HINT: Record<string, Lang> = {
zh: "通过 Grok CLI 的 rules 参数传入额外教学或委派指令。",
en: "Additional teaching or delegation instructions are passed through Grok CLI's rules option.",
},
antigravity: {
zh: "Antigravity CLI 没有系统提示 flag——该指令会前缀在每个新会话的第一条消息上。",
en: "Antigravity CLI has no system-prompt flag — the instruction is prefixed to each new session's first message.",
},
claude_code: {
zh: "追加到该智能体的系统提示(--append-system-prompt)。",
en: "Appended to the agent's system prompt (--append-system-prompt).",
@@ -428,6 +433,21 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
[options, config.effort, save],
);
const catalogSourceLabel = useMemo(() => {
switch (options?.catalog_source) {
case "sdk":
return tr({ zh: "来源:Claude Agent SDK", en: "Source: Claude Agent SDK" });
case "tui":
return tr({ zh: "来源:CLI /model 缓存", en: "Source: CLI /model cache" });
case "cache":
return tr({ zh: "来源:本地 CLI 缓存", en: "Source: local CLI cache" });
case "cli":
return tr({ zh: "来源:CLI 实时模型列表", en: "Source: live CLI model list" });
default:
return "";
}
}, [options?.catalog_source, tr]);
const displayName = options?.display_name ?? DISPLAY_NAMES[kind] ?? kind;
return (
@@ -531,18 +551,23 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
en: "No model catalog is assumed. Enter a model supported by your Grok CLI; sync only detects the CLI again.",
})
: options.synced_at
? t("Last synced: {{when}}", {
? `${t("Last synced: {{when}}", {
when: formatTs(options.synced_at, i18n.language),
})
: isRemote
})}${catalogSourceLabel ? ` · ${catalogSourceLabel}` : ""}`
: options.catalog_source === "fallback"
? tr({
zh: "远程网关当前不提供模型枚举;可以留空使用网关默认值,或手动填写模型名。",
en: "The remote gateway does not currently enumerate models here; use its default or enter a model name manually.",
})
: tr({
zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",
en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",
zh: "当前显示内置常用别名(未命中实时 SDK/缓存);点击同步拉取当前账号可用模型。",
en: "Showing built-in fallback aliases (no synced SDK/cache catalog yet); click Sync to pull your account's models.",
})
: isRemote
? tr({
zh: "远程网关当前不提供模型枚举;可以留空使用网关默认值,或手动填写模型名。",
en: "The remote gateway does not currently enumerate models here; use its default or enter a model name manually.",
})
: tr({
zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",
en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",
})
}
control={
isRemote ? (

View File

@@ -85,6 +85,7 @@ export interface SubagentBackendOptions {
efforts: string[];
allow_custom_model: boolean;
synced_at: string;
catalog_source?: string;
detail: string;
}