diff --git a/CHANGELOG.md b/CHANGELOG.md index 119dfe76f65..bfb78457936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,6 +95,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- `deploy/t3code/agy-acp`: preserve `yolo` (Full access) when `agy` reports `accept-edits` back to + T3 Code instead of unconditionally rewriting it to `auto_edit` (Accept edits), and clamp + out-of-range `thought_level` updates to the active model's offered levels. +- Antigravity CLI `/v1beta/models` catalog: deduplicate effort-suffixed/aliased models and expand + thinking-capable models into `agy`-supported effort levels (within `agy`'s 32-entry cap) so T3 + Code shows thinking levels under **Effort** instead of separate models. - Config hot reload keeps working after the config file is saved by renaming a temp file over it, as many editors and tools do. The watcher used to watch the file itself, so after one such save every later change was ignored until the hub restarted. It now watches the config diff --git a/deploy/t3code/agy-acp b/deploy/t3code/agy-acp index 5f78d160159..d2f2c8e7744 100755 --- a/deploy/t3code/agy-acp +++ b/deploy/t3code/agy-acp @@ -12,6 +12,15 @@ runtime's names; the standalone CLI uses different ones: auto_edit accept-edits yolo accept-edits (T3 Code answers permission requests itself in Full access) +Because both `auto_edit` and `yolo` map to `accept-edits`, this wrapper remembers the last +mode T3 Code requested per session so `accept-edits` coming back from `agy` is reported as +`yolo` when Full access is active instead of downgrading it to `auto_edit`. + +It also tracks each session's offered `thought_level` options (and caches them per model) so +a `session/set_config_option` request carrying a level outside the active model's range (for +example `xhigh` or `max` sent to a model capped at `high`) is clamped to the nearest offered +level instead of failing with `-32602`. + Everything else passes through byte for byte. To stop using this, clear the Antigravity "Binary path" in T3 Code's provider settings. """ @@ -22,7 +31,8 @@ import sys import threading TO_AGY = {"auto_edit": "accept-edits", "yolo": "accept-edits"} -FROM_AGY = {"accept-edits": "auto_edit"} +THOUGHT_LEVEL_ORDER = ("low", "medium", "high", "xhigh", "max") +THOUGHT_LEVEL_RANK = {level: idx for idx, level in enumerate(THOUGHT_LEVEL_ORDER)} T3_MODES = [ {"value": "default", "name": "Default", "id": "default"}, {"value": "auto_edit", "name": "Accept edits", "id": "auto_edit"}, @@ -30,49 +40,256 @@ T3_MODES = [ ] -def to_agent(message): - """Rewrite T3 Code's mode names in requests it sends to the CLI.""" - params = message.get("params") - if not isinstance(params, dict): +def _is_request_id(value): + return isinstance(value, (int, str)) and not isinstance(value, bool) + + +def _session_key(container): + if isinstance(container, dict): + session_id = container.get("sessionId") + if isinstance(session_id, str): + return session_id + return None + + +def _clamp_thought_level(requested, offered): + if not offered or requested in offered: + return requested + req_rank = THOUGHT_LEVEL_RANK.get(requested.lower()) + if req_rank is None: + return offered[-1] + ranked = [ + (THOUGHT_LEVEL_RANK[lvl.lower()], lvl) + for lvl in offered + if isinstance(lvl, str) and lvl.lower() in THOUGHT_LEVEL_RANK + ] + if not ranked: + return offered[-1] + # Pick the closest offered level; break ties toward the lower supported level + # so out-of-range requests never exceed what the model supports. + _, best = min(ranked, key=lambda item: (abs(item[0] - req_rank), item[0])) + return best + + +class ModeBridge: + """Translate ACP session modes and clamp thought levels between T3 Code and standalone `agy`.""" + + def __init__(self): + self._lock = threading.Lock() + self._requested = {} + self._pending = {} + self._pending_sessions = {} + self._session_model = {} + self._session_thought_levels = {} + self._model_thought_levels = {} + + @staticmethod + def _from_agy(value, wanted): + if value == "accept-edits": + return "yolo" if wanted == "yolo" else "auto_edit" + return value + + def _fix_config_options(self, options, wanted): + reported = None + if not isinstance(options, list): + return reported + for option in options: + if isinstance(option, dict) and (option.get("id") == "mode" or option.get("category") == "mode"): + raw = option.get("currentValue") + if isinstance(raw, str): + reported = raw + option["options"] = [{"value": m["value"], "name": m["name"]} for m in T3_MODES] + option["currentValue"] = self._from_agy(raw, wanted) + return reported + + def _record_thought_levels_locked(self, session_id, options, models=None): + current_model = None + if isinstance(models, dict) and isinstance(models.get("currentModelId"), str): + current_model = models["currentModelId"] + + if isinstance(options, list): + offered_levels = None + for option in options: + if not isinstance(option, dict): + continue + opt_id = option.get("id") + opt_cat = option.get("category") + if opt_id == "model" or opt_cat == "model": + if isinstance(option.get("currentValue"), str): + current_model = option["currentValue"] + elif opt_id == "thought_level" or opt_cat == "thought_level": + raw_opts = option.get("options") + if isinstance(raw_opts, list): + offered_levels = [ + item["value"] + for item in raw_opts + if isinstance(item, dict) and isinstance(item.get("value"), str) + ] + if offered_levels is None: + offered_levels = [] + if session_id is not None: + self._session_thought_levels[session_id] = offered_levels + if current_model is not None: + self._model_thought_levels[current_model] = offered_levels + + if session_id is not None and current_model is not None: + self._session_model[session_id] = current_model + + def _fix_modes(self, modes, wanted): + reported = None + if not isinstance(modes, dict): + return reported + raw = modes.get("currentModeId") + if isinstance(raw, str): + reported = raw + modes["availableModes"] = [{"id": m["id"], "name": m["name"]} for m in T3_MODES] + modes["currentModeId"] = self._from_agy(raw, wanted) + return reported + + def to_agent(self, message): + """Rewrite T3 Code's mode names and clamp out-of-range thought levels sent to the CLI.""" + if not isinstance(message, dict): + return message + params = message.get("params") + if not isinstance(params, dict): + return message + method = message.get("method") + session_id = _session_key(params) + msg_id = message.get("id") + + if method == "session/set_model" and isinstance(params.get("modelId"), str): + with self._lock: + if session_id is not None: + self._session_model[session_id] = params["modelId"] + if _is_request_id(msg_id): + self._pending_sessions[msg_id] = session_id + return message + + if method == "session/set_config_option": + config_id = params.get("configId") + value = params.get("value") + if config_id == "model" and isinstance(value, str): + with self._lock: + if session_id is not None: + self._session_model[session_id] = value + if _is_request_id(msg_id): + self._pending_sessions[msg_id] = session_id + return message + if config_id == "thought_level" and isinstance(value, str): + with self._lock: + if session_id is not None and _is_request_id(msg_id): + self._pending_sessions[msg_id] = session_id + model_id = self._session_model.get(session_id) + offered = None + if model_id is not None and model_id in self._model_thought_levels: + offered = self._model_thought_levels[model_id] + elif session_id in self._session_thought_levels: + offered = self._session_thought_levels[session_id] + if offered: + params["value"] = _clamp_thought_level(value, offered) + return message + + if method == "session/set_mode" and isinstance(params.get("modeId"), str): + field = "modeId" + elif ( + method == "session/set_config_option" + and params.get("configId") == "mode" + and isinstance(params.get("value"), str) + ): + field = "value" + else: + return message + + requested = params[field] + with self._lock: + prev = self._requested.get(session_id) + self._requested[session_id] = requested + if _is_request_id(msg_id): + self._pending[msg_id] = (session_id, prev, requested) + + if requested in TO_AGY: + params[field] = TO_AGY[requested] return message - method = message.get("method") - if method == "session/set_mode" and params.get("modeId") in TO_AGY: - params["modeId"] = TO_AGY[params["modeId"]] - elif method == "session/set_config_option" and params.get("configId") == "mode" and params.get("value") in TO_AGY: - params["value"] = TO_AGY[params["value"]] - return message + def to_client(self, message): + """Present the CLI's modes under the names T3 Code expects and record offered thought levels.""" + if not isinstance(message, dict): + return message + + msg_id = message.get("id") + is_response = "result" in message or "error" in message + result = message.get("result") + params = message.get("params") + + with self._lock: + pending_entry = None + pending_session = None + if is_response and _is_request_id(msg_id): + pending_entry = self._pending.pop(msg_id, None) + pending_session = self._pending_sessions.pop(msg_id, None) + + if "error" in message: + if pending_entry is not None: + session_id, prev, requested = pending_entry + if self._requested.get(session_id) == requested: + if prev is None: + self._requested.pop(session_id, None) + else: + self._requested[session_id] = prev + return message + + if pending_entry is not None: + session_id = pending_entry[0] + wanted = pending_entry[2] + else: + session_id = _session_key(result) + if session_id is None: + session_id = _session_key(params) + if session_id is None: + session_id = pending_session + wanted = self._requested.get(session_id) -def fix_config_options(options): - if not isinstance(options, list): - return - for option in options: - if isinstance(option, dict) and (option.get("id") == "mode" or option.get("category") == "mode"): - option["options"] = [{"value": m["value"], "name": m["name"]} for m in T3_MODES] - option["currentValue"] = FROM_AGY.get(option.get("currentValue"), option.get("currentValue")) + reported = [] + if isinstance(result, dict): + r_opt = self._fix_config_options(result.get("configOptions"), wanted) + r_mode = self._fix_modes(result.get("modes"), wanted) + self._record_thought_levels_locked(session_id, result.get("configOptions"), result.get("models")) + reported.extend(r for r in (r_opt, r_mode) if r is not None) + if isinstance(params, dict): + update = params.get("update") + if isinstance(update, dict): + r_opt = self._fix_config_options(update.get("configOptions"), wanted) + r_mode = self._fix_modes(update.get("modes"), wanted) + if "configOptions" in update or "models" in update: + self._record_thought_levels_locked(session_id, update.get("configOptions"), update.get("models")) + reported.extend(r for r in (r_opt, r_mode) if r is not None) + if "currentModeId" in update: + raw = update.get("currentModeId") + if isinstance(raw, str): + reported.append(raw) + update["currentModeId"] = self._from_agy(raw, wanted) -def fix_modes(modes): - if not isinstance(modes, dict): - return - modes["availableModes"] = [{"id": m["id"], "name": m["name"]} for m in T3_MODES] - modes["currentModeId"] = FROM_AGY.get(modes.get("currentModeId"), modes.get("currentModeId")) + has_pending = any(sid == session_id for sid, _, _ in self._pending.values()) + if reported and not has_pending: + last_reported = reported[-1] + if last_reported != "accept-edits": + self._requested[session_id] = last_reported + + return message + + +_DEFAULT_BRIDGE = ModeBridge() + + +def to_agent(message): + """Rewrite T3 Code's mode names in requests it sends to the CLI.""" + return _DEFAULT_BRIDGE.to_agent(message) def to_client(message): """Present the CLI's modes under the names T3 Code expects.""" - result = message.get("result") - if isinstance(result, dict): - fix_config_options(result.get("configOptions")) - fix_modes(result.get("modes")) - params = message.get("params") - if isinstance(params, dict): - update = params.get("update") - if isinstance(update, dict): - fix_config_options(update.get("configOptions")) - if update.get("currentModeId") in FROM_AGY: - update["currentModeId"] = FROM_AGY[update["currentModeId"]] - return message + return _DEFAULT_BRIDGE.to_client(message) def pump(source, sink, rewrite): @@ -94,10 +311,11 @@ def pump(source, sink, rewrite): def main(): agy = os.path.expanduser("~/.local/bin/agy") + bridge = ModeBridge() child = subprocess.Popen([agy, "acp", *sys.argv[1:]], stdin=subprocess.PIPE, stdout=subprocess.PIPE) - inbound = threading.Thread(target=pump, args=(sys.stdin.buffer, child.stdin, to_agent), daemon=True) + inbound = threading.Thread(target=pump, args=(sys.stdin.buffer, child.stdin, bridge.to_agent), daemon=True) inbound.start() - pump(child.stdout, sys.stdout.buffer, to_client) + pump(child.stdout, sys.stdout.buffer, bridge.to_client) sys.exit(child.wait()) diff --git a/deploy/t3code/agy_acp_test.py b/deploy/t3code/agy_acp_test.py new file mode 100644 index 00000000000..24616a563eb --- /dev/null +++ b/deploy/t3code/agy_acp_test.py @@ -0,0 +1,411 @@ +"""Unit tests for deploy/t3code/agy-acp mode translation.""" +import importlib.machinery +import importlib.util +import pathlib +import unittest + + +def _load_agy_acp(): + script_path = pathlib.Path(__file__).resolve().with_name("agy-acp") + loader = importlib.machinery.SourceFileLoader("agy_acp", str(script_path)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +agy_acp = _load_agy_acp() + + +class ModeBridgeTests(unittest.TestCase): + def test_preserves_yolo_across_set_mode_and_updates(self): + bridge = agy_acp.ModeBridge() + + outbound = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "yolo"}, + }) + self.assertEqual(outbound["params"]["modeId"], "accept-edits") + + update = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "s1", + "update": { + "sessionUpdate": "current_mode_update", + "currentModeId": "accept-edits", + }, + }, + }) + self.assertEqual(update["params"]["update"]["currentModeId"], "yolo") + + resp = bridge.to_client({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "modes": { + "availableModes": [{"id": "default", "name": "Default"}], + "currentModeId": "accept-edits", + }, + }, + }) + self.assertEqual(resp["result"]["modes"]["currentModeId"], "yolo") + + def test_preserves_yolo_for_set_config_option_without_session_id_in_result(self): + bridge = agy_acp.ModeBridge() + + outbound = bridge.to_agent({ + "jsonrpc": "2.0", + "id": "req-42", + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "mode", "value": "yolo"}, + }) + self.assertEqual(outbound["params"]["value"], "accept-edits") + + resp = bridge.to_client({ + "jsonrpc": "2.0", + "id": "req-42", + "result": { + "configOptions": [ + {"id": "mode", "category": "mode", "currentValue": "accept-edits", "options": []}, + ], + }, + }) + self.assertEqual(resp["result"]["configOptions"][0]["currentValue"], "yolo") + + cfg_update = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "s1", + "update": { + "sessionUpdate": "config_option_update", + "configOptions": [ + {"id": "mode", "category": "mode", "currentValue": "accept-edits", "options": []}, + ], + }, + }, + }) + self.assertEqual(cfg_update["params"]["update"]["configOptions"][0]["currentValue"], "yolo") + + def test_auto_edit_and_default_sessions_stay_isolated_from_yolo(self): + bridge = agy_acp.ModeBridge() + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s-yolo", "modeId": "yolo"}, + }) + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/set_mode", + "params": {"sessionId": "s-auto", "modeId": "auto_edit"}, + }) + + u_yolo = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s-yolo", "update": {"currentModeId": "accept-edits"}}, + }) + u_auto = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s-auto", "update": {"currentModeId": "accept-edits"}}, + }) + u_fresh = bridge.to_client({ + "jsonrpc": "2.0", + "id": 99, + "result": { + "sessionId": "s-fresh", + "modes": {"currentModeId": "accept-edits", "availableModes": []}, + }, + }) + + self.assertEqual(u_yolo["params"]["update"]["currentModeId"], "yolo") + self.assertEqual(u_auto["params"]["update"]["currentModeId"], "auto_edit") + self.assertEqual(u_fresh["result"]["modes"]["currentModeId"], "auto_edit") + + def test_switching_from_yolo_to_auto_edit_or_default_clears_yolo(self): + bridge = agy_acp.ModeBridge() + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "yolo"}, + }) + bridge.to_client({"jsonrpc": "2.0", "id": 1, "result": {}}) + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "auto_edit"}, + }) + u_auto = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "accept-edits"}}, + }) + self.assertEqual(u_auto["params"]["update"]["currentModeId"], "auto_edit") + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "default"}, + }) + u_default = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "default"}}, + }) + self.assertEqual(u_default["params"]["update"]["currentModeId"], "default") + + def test_error_response_reverts_remembered_mode(self): + bridge = agy_acp.ModeBridge() + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "auto_edit"}, + }) + bridge.to_client({"jsonrpc": "2.0", "id": 1, "result": {}}) + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "yolo"}, + }) + bridge.to_client({ + "jsonrpc": "2.0", + "id": 2, + "error": {"code": -32602, "message": "mode rejected"}, + }) + + u_after_err = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "accept-edits"}}, + }) + self.assertEqual(u_after_err["params"]["update"]["currentModeId"], "auto_edit") + + def test_inflight_default_update_does_not_clobber_pending_yolo(self): + bridge = agy_acp.ModeBridge() + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "yolo"}, + }) + # Stale update from before set_mode took effect arrives while id=1 is still pending. + stale = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "default"}}, + }) + self.assertEqual(stale["params"]["update"]["currentModeId"], "default") + + # Subsequent accept-edits update must still map back to yolo. + applied = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "accept-edits"}}, + }) + self.assertEqual(applied["params"]["update"]["currentModeId"], "yolo") + + def test_agent_initiated_default_clears_yolo_when_idle(self): + bridge = agy_acp.ModeBridge() + + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_mode", + "params": {"sessionId": "s1", "modeId": "yolo"}, + }) + bridge.to_client({"jsonrpc": "2.0", "id": 1, "result": {}}) + + bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "default"}}, + }) + later = bridge.to_client({ + "jsonrpc": "2.0", + "method": "session/update", + "params": {"sessionId": "s1", "update": {"currentModeId": "accept-edits"}}, + }) + self.assertEqual(later["params"]["update"]["currentModeId"], "auto_edit") + + def test_clamps_out_of_range_thought_level_for_active_model(self): + bridge = agy_acp.ModeBridge() + + bridge.to_client({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "sessionId": "s1", + "configOptions": [ + {"id": "model", "category": "model", "currentValue": "claude-opus-5.5", "options": []}, + { + "id": "thought_level", + "category": "thought_level", + "currentValue": "high", + "options": [ + {"value": "low", "name": "Low"}, + {"value": "medium", "name": "Medium"}, + {"value": "high", "name": "High"}, + ], + }, + ], + }, + }) + + clamped_xhigh = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "xhigh"}, + }) + self.assertEqual(clamped_xhigh["params"]["value"], "high") + + clamped_max = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "max"}, + }) + self.assertEqual(clamped_max["params"]["value"], "high") + + supported = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 4, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "low"}, + }) + self.assertEqual(supported["params"]["value"], "low") + + def test_thought_level_tracks_model_switch_and_pipelined_switch(self): + bridge = agy_acp.ModeBridge() + + bridge.to_client({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "sessionId": "s1", + "configOptions": [ + {"id": "model", "category": "model", "currentValue": "claude-opus-4.6", "options": []}, + { + "id": "thought_level", + "category": "thought_level", + "currentValue": "high", + "options": [ + {"value": "low", "name": "Low"}, + {"value": "medium", "name": "Medium"}, + {"value": "high", "name": "High"}, + {"value": "xhigh", "name": "XHigh"}, + {"value": "max", "name": "Max"}, + ], + }, + ], + }, + }) + + # Switch to claude-opus-5.5 whose response has no sessionId (correlates via msg_id). + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "model", "value": "claude-opus-5.5"}, + }) + bridge.to_client({ + "jsonrpc": "2.0", + "id": 2, + "result": { + "configOptions": [ + {"id": "model", "category": "model", "currentValue": "claude-opus-5.5", "options": []}, + { + "id": "thought_level", + "category": "thought_level", + "currentValue": "high", + "options": [ + {"value": "low", "name": "Low"}, + {"value": "medium", "name": "Medium"}, + {"value": "high", "name": "High"}, + ], + }, + ], + }, + }) + + # Switch back to claude-opus-4.6 and pipeline thought_level=max before response arrives. + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "model", "value": "claude-opus-4.6"}, + }) + pipelined_max = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 4, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "max"}, + }) + self.assertEqual(pipelined_max["params"]["value"], "max") + + # Pipeline switch back to cached claude-opus-5.5 and thought_level=xhigh. + bridge.to_agent({ + "jsonrpc": "2.0", + "id": 5, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "model", "value": "claude-opus-5.5"}, + }) + pipelined_clamped = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 6, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "xhigh"}, + }) + self.assertEqual(pipelined_clamped["params"]["value"], "high") + + def test_thought_level_passthrough_when_unknown_or_empty(self): + bridge = agy_acp.ModeBridge() + + before_init = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 1, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "xhigh"}, + }) + self.assertEqual(before_init["params"]["value"], "xhigh") + + # Model without thought_level configOption leaves request unchanged. + bridge.to_client({ + "jsonrpc": "2.0", + "id": 2, + "result": { + "sessionId": "s1", + "configOptions": [ + {"id": "model", "category": "model", "currentValue": "gpt-oss-120b", "options": []}, + ], + }, + }) + after_flat = bridge.to_agent({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/set_config_option", + "params": {"sessionId": "s1", "configId": "thought_level", "value": "high"}, + }) + self.assertEqual(after_flat["params"]["value"], "high") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/t3code.md b/docs/t3code.md index 1d7cbf0639f..498df4752a8 100644 --- a/docs/t3code.md +++ b/docs/t3code.md @@ -67,12 +67,17 @@ GPT-OSS models Google offers) to T3 Code's Antigravity provider. Two pieces make - **The Antigravity-only endpoint.** The Antigravity CLI's gateway mode takes its model list from the endpoint it is pointed at. `https:///provider/antigravity` lists only the hub's - Antigravity accounts, so the CLI never offers your Claude or Codex subscription models. + Antigravity accounts, so the CLI never offers your Claude or Codex subscription models. For + `antigravity/cli/` requests it expands each thinking-capable model into its supported effort + variants and deduplicates aliased base/suffixed IDs so T3 Code shows one entry per model with + its effort levels under **Effort**. - **The standalone CLI.** T3 Code's bundled Antigravity runtime ignores gateway mode and always offers its own fixed Gemini list. The standalone `agy` CLI (1.5.9 or later) honours it. - [`deploy/t3code/agy-acp`](../deploy/t3code/agy-acp) starts `agy acp` for T3 Code and renames - the session modes between the two runtimes (`auto_edit` and `yolo` become `accept-edits`); - everything else passes through unchanged. + [`deploy/t3code/agy-acp`](../deploy/t3code/agy-acp) starts `agy acp` for T3 Code, renames + the session modes between the two runtimes (`auto_edit` and `yolo` both map to `accept-edits` + for `agy`, while preserving `yolo` in responses back to T3 Code so Full access is not downgraded + to Accept edits), and clamps out-of-range `thought_level` updates to the active model's offered + levels; everything else passes through unchanged. Setup on the machine running T3 Code: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 0565ae53114..1a8f82d639c 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -143,6 +143,20 @@ Check its service user and provider config directory, then start a fresh provide Choose **Use existing CLI** for Codex. Follow [T3 Code](t3code.md) and [the client settings](providers.md#point-clients-at-the-hub). +## T3 Code prompts for approval in Full access mode + +Command approvals happen locally between T3 Code and each provider CLI; they do not pass through +`t3code-proxy`. + +- **Antigravity (`agy-acp`):** Make sure you copied the current [`deploy/t3code/agy-acp`](../deploy/t3code/agy-acp) + wrapper to each environment running it. Earlier copies mapped `accept-edits` back to `auto_edit` + even when T3 Code requested `yolo` (Full access). +- **Codex (`Use existing CLI`):** On the machine running the environment, check `~/.codex/config.toml` + and `~/.codex/rules/*.rules` for an `approval_policy`, `sandbox_mode`, `approvals_reviewer` or + `prompt` rule forcing approvals. +- If approvals still appear across providers or after switching agents in a Full access thread with + clean CLI config, the fix belongs in T3 Code itself rather than `t3code-proxy`. + ## Windows and WSL show the wrong environment or stop after closing terminals Use separate provider installations, user homes and T3 listener ports. Check Windows' Serve diff --git a/internal/api/server_antigravity_cli_models_test.go b/internal/api/server_antigravity_cli_models_test.go new file mode 100644 index 00000000000..a0a4ad29c04 --- /dev/null +++ b/internal/api/server_antigravity_cli_models_test.go @@ -0,0 +1,341 @@ +package api + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/rune-oai/t3code-proxy/internal/home" + "github.com/rune-oai/t3code-proxy/internal/registry" + "github.com/rune-oai/t3code-proxy/internal/runtime/executor" + _ "github.com/rune-oai/t3code-proxy/internal/thinking/provider/antigravity" + _ "github.com/rune-oai/t3code-proxy/internal/translator" + "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + "github.com/rune-oai/t3code-proxy/sdk/pluginapi" +) + +const testAntigravityCLIUA = "antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=gateway)" + +func registerAntigravityCLICatalogForTest(t *testing.T, server *Server) *auth.Auth { + t.Helper() + a := &auth.Auth{ + ID: "antigravity-cli-test-auth", + Provider: "antigravity", + Status: auth.StatusActive, + Metadata: map[string]any{ + "access_token": "test-access-token", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "test-project", + }, + } + if _, errRegister := server.handlers.AuthManager.Register(context.Background(), a); errRegister != nil { + t.Fatal(errRegister) + } + models := []*registry.ModelInfo{ + { + ID: "claude-opus-4-6-thinking", + DisplayName: "Claude Opus 4.6 (Thinking)", + Description: "Claude Opus 4.6 (Thinking)", + ContextLength: 200000, + MaxCompletionTokens: 64000, + OwnedBy: "antigravity", + Type: "antigravity", + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true}, + }, + { + ID: "claude-opus-5-5-high", + DisplayName: "Claude Opus 5.5 (High)", + Description: "Claude Opus 5.5 (High)", + ContextLength: 1000000, + MaxCompletionTokens: 128000, + OwnedBy: "antigravity", + Type: "antigravity", + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "gemini-4-hydrogen-xhigh", + DisplayName: "Gemini 4 Hydrogen", + Description: "Gemini 4 Hydrogen (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 1048576, + OwnedBy: "antigravity", + Type: "antigravity", + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + // Forked alias alongside upstream model — should collapse to one model group. + { + ID: "gemini-4-hydrogen", + MetadataModelID: "gemini-4-hydrogen-xhigh", + DisplayName: "Gemini 4 Hydrogen", + Description: "Gemini 4 Hydrogen (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 1048576, + OwnedBy: "antigravity", + Type: "antigravity", + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + { + ID: "gemini-3-flash", + DisplayName: "Gemini 3 Flash", + Description: "Gemini 3 Flash", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + OwnedBy: "antigravity", + Type: "antigravity", + Thinking: ®istry.ThinkingSupport{Min: 128, Max: 32768, DynamicAllowed: true, Levels: []string{"minimal", "low", "medium", "high"}}, + }, + { + ID: "gpt-oss-120b-medium", + DisplayName: "GPT-OSS 120B (Medium)", + Description: "GPT-OSS 120B (Medium)", + ContextLength: 114000, + MaxCompletionTokens: 32768, + OwnedBy: "antigravity", + Type: "antigravity", + }, + } + registry.GetGlobalRegistry().RegisterClient(a.ID, "antigravity", models) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(a.ID) }) + return a +} + +func TestAntigravityCLIGeminiModelsEndpoint(t *testing.T) { + server := newTestServer(t) + registerAntigravityCLICatalogForTest(t, server) + + // Antigravity CLI User-Agent receives expanded effort variants and deduplicated aliases. + cliResp := scopedRequest(server, http.MethodGet, "/provider/antigravity/v1beta/models", "", map[string]string{ + "User-Agent": testAntigravityCLIUA, + }) + if cliResp.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", cliResp.Code, cliResp.Body.String()) + } + if !strings.Contains(strings.ToLower(cliResp.Header().Get("Vary")), "user-agent") { + t.Fatalf("expected Vary: User-Agent, got %q", cliResp.Header().Get("Vary")) + } + + var listBody struct { + Models []map[string]any `json:"models"` + } + if err := json.Unmarshal(cliResp.Body.Bytes(), &listBody); err != nil { + t.Fatalf("unmarshal CLI models: %v", err) + } + byName := make(map[string]map[string]any, len(listBody.Models)) + for _, m := range listBody.Models { + name, _ := m["name"].(string) + byName[name] = m + if strings.Contains(name, "(minimal)") { + t.Fatalf("unsupported level leaked into CLI catalog: %q", name) + } + } + + if gotFirst := listBody.Models[0]["name"]; gotFirst != "models/claude-opus-4-6-thinking(low)" { + t.Fatalf("first model = %v, want models/claude-opus-4-6-thinking(low)", gotFirst) + } + for _, lvl := range []string{"low", "medium", "high"} { + entry, ok := byName["models/claude-opus-5-5-high("+lvl+")"] + if !ok || entry["displayName"] != "Claude Opus 5.5 ("+lvl+")" { + t.Fatalf("claude-opus-5-5-high(%s) = %#v", lvl, entry) + } + } + for _, lvl := range []string{"low", "medium", "high", "xhigh"} { + entry, ok := byName["models/gemini-4-hydrogen-xhigh("+lvl+")"] + if !ok || entry["displayName"] != "Gemini 4 Hydrogen ("+lvl+")" { + t.Fatalf("gemini-4-hydrogen-xhigh(%s) = %#v", lvl, entry) + } + if _, dup := byName["models/gemini-4-hydrogen("+lvl+")"]; dup { + t.Fatalf("duplicate alias models/gemini-4-hydrogen(%s) should be collapsed", lvl) + } + } + if _, ok := byName["models/gpt-oss-120b-medium"]; !ok { + t.Fatalf("non-thinking model gpt-oss-120b-medium missing") + } + + // Single-model GET supports expanded names (bare or models/-prefixed) and 404s unknown models. + for _, path := range []string{ + "/provider/antigravity/v1beta/models/claude-opus-5-5-high(high)", + "/provider/antigravity/v1beta/models/models/gemini-4-hydrogen-xhigh(xhigh)", + } { + getResp := scopedRequest(server, http.MethodGet, path, "", map[string]string{ + "User-Agent": testAntigravityCLIUA, + }) + if getResp.Code != http.StatusOK { + t.Fatalf("GET %s status = %d body = %s", path, getResp.Code, getResp.Body.String()) + } + } + notFound := scopedRequest(server, http.MethodGet, "/provider/antigravity/v1beta/models/no-such-model(high)", "", map[string]string{ + "User-Agent": testAntigravityCLIUA, + }) + if notFound.Code != http.StatusNotFound { + t.Fatalf("GET unknown status = %d, want 404", notFound.Code) + } + + // Standard Gemini clients keep the original unexpanded catalog. + stdResp := scopedRequest(server, http.MethodGet, "/provider/antigravity/v1beta/models", "", map[string]string{ + "User-Agent": "curl/8.7.1", + }) + if stdResp.Code != http.StatusOK { + t.Fatalf("standard GET status = %d body = %s", stdResp.Code, stdResp.Body.String()) + } + if strings.Contains(stdResp.Body.String(), "claude-opus-5-5-high(low)") { + t.Fatalf("standard client should not receive CLI effort expansion: %s", stdResp.Body.String()) + } + if !strings.Contains(stdResp.Body.String(), `"models/claude-opus-5-5-high"`) { + t.Fatalf("standard client should receive base model entry: %s", stdResp.Body.String()) + } +} + +func TestAntigravityCLIExpandedModelExecutionAppliesThinkingSuffix(t *testing.T) { + var capturedBodies []string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + capturedBodies = append(capturedBodies, string(raw)) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"response\":{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n") + })) + defer upstream.Close() + + server := newTestServer(t) + server.handlers.AuthManager.RegisterExecutor(executor.NewAntigravityExecutor(server.cfg)) + a := registerAntigravityCLICatalogForTest(t, server) + a.Attributes = map[string]string{"base_url": upstream.URL} + if _, errUpdate := server.handlers.AuthManager.Update(context.Background(), a); errUpdate != nil { + t.Fatal(errUpdate) + } + + cases := []struct { + name string + pathModel string + body string + wantModel string + wantLevel string + wantBudget int64 + wantNoBudget bool + wantNoLevel bool + }{ + { + name: "level model suffix overrides body thinkingBudget", + pathModel: "claude-opus-5-5-high(low)", + body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingBudget":0,"includeThoughts":true}}}`, + wantModel: "claude-opus-5-5-high", + wantLevel: "low", + wantNoBudget: true, + }, + { + name: "xhigh level suffix on gemini-4-hydrogen-xhigh", + pathModel: "gemini-4-hydrogen-xhigh(xhigh)", + body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingLevel":"low","includeThoughts":true}}}`, + wantModel: "gemini-4-hydrogen-xhigh", + wantLevel: "xhigh", + wantNoBudget: true, + }, + { + name: "budget-only claude-opus-4-6-thinking converts medium to budget", + pathModel: "claude-opus-4-6-thinking(medium)", + body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"includeThoughts":true}}}`, + wantModel: "claude-opus-4-6-thinking", + wantBudget: 8192, + wantNoLevel: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + before := len(capturedBodies) + path := "/provider/antigravity/v1beta/models/" + tc.pathModel + ":streamGenerateContent?alt=sse" + resp := scopedRequest(server, http.MethodPost, path, tc.body, map[string]string{ + "User-Agent": testAntigravityCLIUA, + }) + if resp.Code != http.StatusOK { + t.Fatalf("POST %s status = %d body = %s", path, resp.Code, resp.Body.String()) + } + if len(capturedBodies) != before+1 { + t.Fatalf("upstream call count = %d, want %d", len(capturedBodies)-before, 1) + } + sent := capturedBodies[len(capturedBodies)-1] + if gotModel := ojson.Get(sent, "model").String(); gotModel != tc.wantModel { + t.Fatalf("upstream model = %q, want %q; body=%s", gotModel, tc.wantModel, sent) + } + if tc.wantLevel != "" { + if gotLevel := ojson.Get(sent, "request.generationConfig.thinkingConfig.thinkingLevel").String(); gotLevel != tc.wantLevel { + t.Fatalf("thinkingLevel = %q, want %q; body=%s", gotLevel, tc.wantLevel, sent) + } + } + if tc.wantNoBudget && ojson.Get(sent, "request.generationConfig.thinkingConfig.thinkingBudget").Exists() { + t.Fatalf("expected thinkingBudget to be stripped; body=%s", sent) + } + if tc.wantBudget > 0 { + if gotBudget := ojson.Get(sent, "request.generationConfig.thinkingConfig.thinkingBudget").Int(); gotBudget != tc.wantBudget { + t.Fatalf("thinkingBudget = %d, want %d; body=%s", gotBudget, tc.wantBudget, sent) + } + } + if tc.wantNoLevel && ojson.Get(sent, "request.generationConfig.thinkingConfig.thinkingLevel").Exists() { + t.Fatalf("expected thinkingLevel to be stripped; body=%s", sent) + } + }) + } +} + +func TestAntigravityCLIGeminiModels_HomeModeAndPluginInterceptor(t *testing.T) { + server := newTestServer(t) + server.cfg.Home.Enabled = true + + var intercepted bool + server.handlers.SetPluginHost(&mockModelListInterceptorHost{ + interceptResponse: func(_ context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + intercepted = true + headers := req.ResponseHeaders.Clone() + headers.Set("X-CLI-Intercepted", "yes") + return pluginapi.ResponseInterceptResponse{Headers: headers, Body: req.Body} + }, + }) + + client := newHomeCatalogClient(t, `{ + "antigravity": [ + { + "id": "claude-opus-5-5-high", + "display_name": "Claude Opus 5.5 (High)", + "context_length": 1000000, + "max_completion_tokens": 128000, + "thinking": {"levels": ["low", "medium", "high"]} + } + ] + }`) + previousHome := home.Current() + home.SetCurrent(client) + t.Cleanup(func() { home.SetCurrent(previousHome) }) + + engine := gin.New() + engine.GET("/v1beta/models", server.geminiModelsHandler(nil)) + engine.GET("/v1beta/models/*action", server.geminiGetHandler(nil)) + + listReq := httptest.NewRequest(http.MethodGet, "/v1beta/models", nil) + listReq.Header.Set("User-Agent", testAntigravityCLIUA) + listRec := httptest.NewRecorder() + engine.ServeHTTP(listRec, listReq) + + if listRec.Code != http.StatusOK { + t.Fatalf("Home CLI list status = %d body = %s", listRec.Code, listRec.Body.String()) + } + if !intercepted || listRec.Header().Get("X-CLI-Intercepted") != "yes" { + t.Fatalf("expected plugin interceptor to run for Antigravity CLI model list") + } + if !strings.Contains(listRec.Body.String(), `"models/claude-opus-5-5-high(high)"`) { + t.Fatalf("expected expanded Home model list, got: %s", listRec.Body.String()) + } + + getReq := httptest.NewRequest(http.MethodGet, "/v1beta/models/claude-opus-5-5-high(medium)", nil) + getReq.Header.Set("User-Agent", testAntigravityCLIUA) + getRec := httptest.NewRecorder() + engine.ServeHTTP(getRec, getReq) + if getRec.Code != http.StatusOK || !strings.Contains(getRec.Body.String(), `"Claude Opus 5.5 (medium)"`) { + t.Fatalf("Home CLI get status = %d body = %s", getRec.Code, getRec.Body.String()) + } +} diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go index e810cafdff7..33f4789987a 100644 --- a/internal/api/server_routes.go +++ b/internal/api/server_routes.go @@ -15,6 +15,7 @@ import ( "github.com/gin-gonic/gin" managementHandlers "github.com/rune-oai/t3code-proxy/internal/api/handlers/management" "github.com/rune-oai/t3code-proxy/internal/api/middleware" + "github.com/rune-oai/t3code-proxy/internal/client/antigravitycli" claudemodels "github.com/rune-oai/t3code-proxy/internal/client/claude/models" codexlive "github.com/rune-oai/t3code-proxy/internal/client/codex/live" codexmodels "github.com/rune-oai/t3code-proxy/internal/client/codex/models" @@ -1030,6 +1031,11 @@ func (s *Server) loadMuseCodeHomeModels(c *gin.Context) ([]musecode.ModelInput, func (s *Server) geminiModelsHandler(geminiHandler *gemini.GeminiAPIHandler) gin.HandlerFunc { return func(c *gin.Context) { + appendVaryToken(c.Writer.Header(), "User-Agent") + if antigravitycli.IsAntigravityCLIUserAgent(c.GetHeader("User-Agent")) { + s.handleAntigravityCLIModels(c) + return + } if cfg := s.getConfig(); cfg != nil && cfg.Home.Enabled && auth.ProviderScopeFromContext(c.Request.Context()) == "" { s.handleHomeGeminiModels(c) return @@ -1041,6 +1047,11 @@ func (s *Server) geminiModelsHandler(geminiHandler *gemini.GeminiAPIHandler) gin func (s *Server) geminiGetHandler(geminiHandler *gemini.GeminiAPIHandler) gin.HandlerFunc { return func(c *gin.Context) { + appendVaryToken(c.Writer.Header(), "User-Agent") + if antigravitycli.IsAntigravityCLIUserAgent(c.GetHeader("User-Agent")) { + s.handleAntigravityCLIModel(c) + return + } if cfg := s.getConfig(); cfg != nil && cfg.Home.Enabled && auth.ProviderScopeFromContext(c.Request.Context()) == "" { s.handleHomeGeminiModel(c) return @@ -1050,6 +1061,85 @@ func (s *Server) geminiGetHandler(geminiHandler *gemini.GeminiAPIHandler) gin.Ha } } +func appendVaryToken(header http.Header, token string) { + if header == nil || token == "" { + return + } + for _, existing := range header.Values("Vary") { + for _, part := range strings.Split(existing, ",") { + if strings.EqualFold(strings.TrimSpace(part), token) { + return + } + } + } + header.Add("Vary", token) +} + +func (s *Server) antigravityCLIModelInfos(c *gin.Context) ([]*registry.ModelInfo, bool) { + if scope := auth.ProviderScopeFromContext(c.Request.Context()); scope != "" { + return registry.GetGlobalRegistry().GetAvailableModelsByProvider(scope), true + } + if cfg := s.getConfig(); cfg != nil && cfg.Home.Enabled { + entries, ok := s.loadHomeModelEntries(c) + if !ok { + return nil, false + } + return homeModelEntriesToRegistryInfos(entries), true + } + return registry.GetGlobalRegistry().GetAvailableModelInfos(), true +} + +func homeModelEntriesToRegistryInfos(entries []homeModelEntry) []*registry.ModelInfo { + out := make([]*registry.ModelInfo, 0, len(entries)) + for _, entry := range entries { + out = append(out, ®istry.ModelInfo{ + ID: entry.id, + Name: entry.modelName, + MetadataModelID: entry.metadataModelID, + Created: entry.created, + OwnedBy: entry.ownedBy, + Type: entry.modelType, + DisplayName: entry.displayName, + Description: entry.description, + ContextLength: entry.contextLength, + MaxContextLength: entry.maxContextLength, + MaxCompletionTokens: entry.maxCompletionTokens, + Thinking: entry.thinking, + SupportedInputModalities: entry.supportedInputModalities, + SupportedOutputModalities: entry.supportedOutputModalities, + }) + } + return out +} + +func (s *Server) handleAntigravityCLIModels(c *gin.Context) { + infos, ok := s.antigravityCLIModelInfos(c) + if !ok { + return + } + s.writeModelListResponse(c, "gemini", gin.H{ + "models": antigravitycli.BuildModels(infos), + }) +} + +func (s *Server) handleAntigravityCLIModel(c *gin.Context) { + infos, ok := s.antigravityCLIModelInfos(c) + if !ok { + return + } + action := strings.TrimPrefix(c.Param("action"), "/") + if model := antigravitycli.FindModel(infos, action); model != nil { + c.JSON(http.StatusOK, model) + return + } + c.JSON(http.StatusNotFound, handlers.ErrorResponse{ + Error: handlers.ErrorDetail{ + Message: "Not Found", + Type: "not_found", + }, + }) +} + type homeModelRoute struct { provider string modelName string diff --git a/internal/client/antigravitycli/models.go b/internal/client/antigravitycli/models.go new file mode 100644 index 00000000000..921656d2355 --- /dev/null +++ b/internal/client/antigravitycli/models.go @@ -0,0 +1,746 @@ +package antigravitycli + +import ( + "sort" + "strings" + + "github.com/rune-oai/t3code-proxy/internal/registry" + "github.com/rune-oai/t3code-proxy/internal/thinking" +) + +// maxCatalogEntries is the maximum number of `/v1beta/models` entries that the +// standalone Antigravity CLI (`agy`) loads in gateway mode before silently +// discarding the remainder. Keeping the expanded catalog within this ceiling +// guarantees no model is dropped and no effort group is truncated mid-group. +const maxCatalogEntries = 32 + +// supportedLevels lists the thinking effort levels recognized by the standalone +// Antigravity CLI (`agy`) in canonical order. Values outside this set (such as +// "minimal", "none", "auto" or "ultra") are not grouped into `thought_level` by +// `agy` and would instead appear as separate models in the picker. +var supportedLevels = []string{"low", "medium", "high", "xhigh", "max"} + +var supportedLevelSet = map[string]struct{}{ + "low": {}, + "medium": {}, + "high": {}, + "xhigh": {}, + "max": {}, +} + +// IsAntigravityCLIUserAgent reports whether userAgent identifies the standalone +// Antigravity CLI (`agy`). +func IsAntigravityCLIUserAgent(userAgent string) bool { + return strings.HasPrefix(strings.ToLower(strings.TrimSpace(userAgent)), "antigravity/cli/") +} + +// ResolveLevels returns the Antigravity CLI effort levels supported by support +// in canonical order. +func ResolveLevels(support *registry.ThinkingSupport) []string { + if support == nil { + return nil + } + if len(support.Levels) > 0 { + present := make(map[string]struct{}, len(support.Levels)) + for _, raw := range support.Levels { + level := strings.ToLower(strings.TrimSpace(raw)) + if _, ok := supportedLevelSet[level]; ok { + present[level] = struct{}{} + } + } + out := make([]string, 0, len(present)) + for _, level := range supportedLevels { + if _, ok := present[level]; ok { + out = append(out, level) + } + } + return out + } + + // Budget-only thinking models (for example claude-opus-4-6-thinking and + // claude-sonnet-4-6) map discrete effort levels to token budgets inside + // thinking.ValidateConfig. Derive distinct levels within [Min, Max]. + if support.Min <= 0 && support.Max <= 0 { + return nil + } + + type budgetChoice struct { + level string + distance int + } + byClamped := make(map[int]budgetChoice, len(supportedLevels)) + clampedOrder := make([]int, 0, len(supportedLevels)) + for _, level := range supportedLevels { + rawBudget, ok := thinking.ConvertLevelToBudget(level) + if !ok || rawBudget <= 0 { + continue + } + clamped := rawBudget + if support.Min > 0 && clamped < support.Min { + clamped = support.Min + } + if support.Max > 0 && clamped > support.Max { + clamped = support.Max + } + dist := rawBudget - clamped + if dist < 0 { + dist = -dist + } + if prev, exists := byClamped[clamped]; exists { + if dist < prev.distance { + byClamped[clamped] = budgetChoice{level: level, distance: dist} + } + continue + } + byClamped[clamped] = budgetChoice{level: level, distance: dist} + clampedOrder = append(clampedOrder, clamped) + } + + out := make([]string, 0, len(clampedOrder)) + for _, clamped := range clampedOrder { + out = append(out, byClamped[clamped].level) + } + return out +} + +type modelMember struct { + info *registry.ModelInfo + id string + baseID string + suffixLevel string + levels []string + hasDisplay bool +} + +type modelGroup struct { + key string + members []modelMember + primary modelMember + dedicatedByLevel map[string]modelMember + primaryLevelSet map[string]struct{} + availableLevels []string + explicitLevels bool + flatEntries []map[string]any + allocatedSlots int + expanded bool + levels []string + entries []map[string]any +} + +// BuildModels formats available models for Antigravity CLI's `/v1beta/models` +// endpoint so thinking levels appear under the `thought_level` effort selector +// instead of as duplicate or level-suffixed models, while staying within the +// CLI's 32-entry gateway model limit. +func BuildModels(infos []*registry.ModelInfo) []map[string]any { + return buildModelsWithCap(infos, maxCatalogEntries) +} + +func buildModelsWithCap(infos []*registry.ModelInfo, maxEntries int) []map[string]any { + if len(infos) == 0 { + return []map[string]any{} + } + + normalized := make([]*registry.ModelInfo, 0, len(infos)) + byLowerID := make(map[string]*registry.ModelInfo, len(infos)) + for _, info := range infos { + if info == nil { + continue + } + id := normalizeModelID(info) + if id == "" { + continue + } + lowerID := strings.ToLower(id) + if _, dup := byLowerID[lowerID]; dup { + continue + } + byLowerID[lowerID] = info + normalized = append(normalized, info) + } + sort.Slice(normalized, func(i, j int) bool { + return strings.ToLower(normalizeModelID(normalized[i])) < strings.ToLower(normalizeModelID(normalized[j])) + }) + + groupsByKey := make(map[string]*modelGroup, len(normalized)) + groupOrder := make([]string, 0, len(normalized)) + passthrough := make([]map[string]any, 0) + + for _, info := range normalized { + id := normalizeModelID(info) + // Preserve models that already carry an explicit `(suffix)` thinking marker + // as-is instead of appending a second suffix. + if parsed := thinking.ParseSuffix(id); parsed.HasSuffix { + passthrough = append(passthrough, buildGeminiModelMap(info, id, defaultDisplayName(info, id), info.Thinking != nil)) + continue + } + + baseID, suffixLevel := splitEffortSuffix(id) + groupKey := strings.ToLower(baseID) + + // Merge a forked alias like `claude-opus-4-6` with its target + // `claude-opus-4-6-thinking` when they share the same cleaned display name. + if metaID := normalizeRawID(info.MetadataModelID); metaID != "" { + if target, ok := byLowerID[strings.ToLower(metaID)]; ok && target != nil { + targetID := normalizeModelID(target) + targetBase, _ := splitEffortSuffix(targetID) + if strings.EqualFold(baseID, targetBase) { + groupKey = strings.ToLower(targetBase) + } else if strings.EqualFold(stripTrailingThinkingSegment(targetID), id) && + strings.EqualFold(cleanDisplayName(info.DisplayName, id), cleanDisplayName(target.DisplayName, targetID)) { + groupKey = strings.ToLower(targetBase) + } + } + } + + member := modelMember{ + info: info, + id: id, + baseID: baseID, + suffixLevel: suffixLevel, + levels: ResolveLevels(info.Thinking), + hasDisplay: strings.TrimSpace(info.DisplayName) != "", + } + group := groupsByKey[groupKey] + if group == nil { + group = &modelGroup{key: groupKey} + groupsByKey[groupKey] = group + groupOrder = append(groupOrder, groupKey) + } + group.members = append(group.members, member) + } + + groups := make([]*modelGroup, 0, len(groupOrder)) + for _, key := range groupOrder { + group := groupsByKey[key] + prepareGroup(group) + groups = append(groups, group) + } + + allocateSlotBudgets(groups, len(passthrough), maxEntries) + + expandedGroups := make([]*modelGroup, 0, len(groups)) + flatEntries := make([]map[string]any, 0, len(passthrough)) + + for _, group := range groups { + materializeGroupEntries(group) + if group.expanded { + expandedGroups = append(expandedGroups, group) + } else { + flatEntries = append(flatEntries, group.entries...) + } + } + flatEntries = append(flatEntries, passthrough...) + + // Place expanded models first, with the broadest thinking-level set at index 0. + // Antigravity CLI initializes `session/new` on the first model and populates the + // initial `thought_level` configOption from that model's offered levels. + sort.Slice(expandedGroups, func(i, j int) bool { + if len(expandedGroups[i].levels) != len(expandedGroups[j].levels) { + return len(expandedGroups[i].levels) > len(expandedGroups[j].levels) + } + return compareGroupPriority(expandedGroups[i], expandedGroups[j]) + }) + + result := make([]map[string]any, 0, len(normalized)*3) + for _, group := range expandedGroups { + result = append(result, group.entries...) + } + result = append(result, flatEntries...) + return result +} + +// FindModel looks up one model by action name (with or without the "models/" +// prefix) in the Antigravity CLI formatted catalog. +func FindModel(infos []*registry.ModelInfo, action string) map[string]any { + action = strings.TrimPrefix(strings.TrimSpace(action), "/") + if action == "" { + return nil + } + normalizedAction := strings.TrimPrefix(action, "models/") + for _, model := range BuildModels(infos) { + if matchesModelAction(model, action, normalizedAction) { + return model + } + } + // Fall back to uncapped expansion so explicit GETs for valid unbudgeted levels + // still succeed. + for _, model := range buildModelsWithCap(infos, 0) { + if matchesModelAction(model, action, normalizedAction) { + return model + } + } + return nil +} + +func matchesModelAction(model map[string]any, action, normalizedAction string) bool { + name, _ := model["name"].(string) + return name == action || name == "models/"+action || strings.TrimPrefix(name, "models/") == normalizedAction +} + +func prepareGroup(group *modelGroup) { + if group == nil || len(group.members) == 0 { + return + } + + // Detect distinct non-alias dedicated effort-suffixed models in this group (e.g., + // `claude-opus-5-5-low`, `claude-opus-5-5-medium`, `claude-opus-5-5-high`). + dedicatedByLevel := make(map[string]modelMember) + for _, m := range group.members { + if m.suffixLevel == "" || strings.TrimSpace(m.info.MetadataModelID) != "" { + continue + } + existing, exists := dedicatedByLevel[m.suffixLevel] + if !exists || preferMember(m, existing) { + dedicatedByLevel[m.suffixLevel] = m + } + } + + primary := selectPrimaryMember(group.members) + + // Collect all supported effort levels offered by this group. + primaryLevelSet := make(map[string]struct{}, len(primary.levels)) + levelSet := make(map[string]struct{}, len(supportedLevels)) + for _, lvl := range primary.levels { + primaryLevelSet[lvl] = struct{}{} + levelSet[lvl] = struct{}{} + } + if len(dedicatedByLevel) >= 2 { + for lvl := range dedicatedByLevel { + levelSet[lvl] = struct{}{} + } + // If another member in the same group declares a superset of levels (for + // example an alias with explicit thinking config), include them when using + // dedicated variants. + for _, m := range group.members { + for _, lvl := range m.levels { + levelSet[lvl] = struct{}{} + } + } + } else if len(primary.levels) > 0 { + // If the group pairs an unsuffixed model (e.g., low..high) with a single + // non-alias effort-suffixed variant (e.g., -xhigh) whose level is missing + // from primary, expose that level too and route it to the dedicated variant. + for lvl, dedicated := range dedicatedByLevel { + if dedicated.id != primary.id { + if _, covered := primaryLevelSet[lvl]; !covered { + levelSet[lvl] = struct{}{} + } + } + } + } + + levels := make([]string, 0, len(levelSet)) + for _, lvl := range supportedLevels { + if _, ok := levelSet[lvl]; ok { + levels = append(levels, lvl) + } + } + + explicitLevels := len(dedicatedByLevel) >= 2 || (primary.info.Thinking != nil && len(primary.info.Thinking.Levels) > 0) + + group.primary = primary + group.dedicatedByLevel = dedicatedByLevel + group.primaryLevelSet = primaryLevelSet + group.availableLevels = levels + group.explicitLevels = explicitLevels + group.flatEntries = buildFlatGroupEntries(group.members, primary) +} + +func allocateSlotBudgets(groups []*modelGroup, passthroughCount int, maxEntries int) { + if maxEntries <= 0 { + for _, g := range groups { + if len(g.availableLevels) >= 2 { + g.allocatedSlots = len(g.availableLevels) + } else { + g.allocatedSlots = len(g.flatEntries) + } + } + return + } + + totalDesired := passthroughCount + used := passthroughCount + expandable := make([]*modelGroup, 0, len(groups)) + for _, g := range groups { + if len(g.availableLevels) >= 2 { + totalDesired += len(g.availableLevels) + g.allocatedSlots = 1 + used++ + expandable = append(expandable, g) + } else { + g.allocatedSlots = len(g.flatEntries) + totalDesired += g.allocatedSlots + used += g.allocatedSlots + } + } + + // Everything fits comfortably without trimming. + if totalDesired <= maxEntries { + for _, g := range expandable { + g.allocatedSlots = len(g.availableLevels) + } + return + } + + remaining := maxEntries - used + if remaining <= 0 { + return + } + + // Sort expandable groups in priority order for fair water-filling. + sort.Slice(expandable, func(i, j int) bool { + return compareGroupPriority(expandable[i], expandable[j]) + }) + + // Pass 1: give every thinking model at least 2 slots so every thinking model + // gets an Effort selector in `agy` before any model takes a 3rd/4th/5th slot. + for _, g := range expandable { + if remaining <= 0 { + return + } + g.allocatedSlots = 2 + remaining-- + } + + // Subsequent passes: distribute remaining slots one level at a time across + // groups in priority order until the 32-entry budget is full. + for remaining > 0 { + progressed := false + for _, g := range expandable { + if remaining <= 0 { + break + } + if g.allocatedSlots < len(g.availableLevels) { + g.allocatedSlots++ + remaining-- + progressed = true + } + } + if !progressed { + break + } + } +} + +func compareGroupPriority(a, b *modelGroup) bool { + if tierA, tierB := groupPriorityTier(a), groupPriorityTier(b); tierA != tierB { + return tierA < tierB + } + if len(a.availableLevels) != len(b.availableLevels) { + return len(a.availableLevels) > len(b.availableLevels) + } + return a.key < b.key +} + +func groupPriorityTier(g *modelGroup) int { + key := g.key + isSecondaryVariant := strings.Contains(key, "lite") || strings.Contains(key, "tiered") + hasXHigh := false + for _, lvl := range g.availableLevels { + if lvl == "xhigh" { + hasXHigh = true + break + } + } + switch { + case !isSecondaryVariant && g.explicitLevels && hasXHigh: + return 0 + case !isSecondaryVariant && g.explicitLevels: + return 1 + case !isSecondaryVariant: + return 2 + default: + return 3 + } +} + +func materializeGroupEntries(group *modelGroup) { + if group == nil || len(group.members) == 0 { + return + } + + // Antigravity CLI requires at least two effort levels to expose `thought_level`. + if len(group.availableLevels) < 2 || group.allocatedSlots < 2 { + group.expanded = false + group.levels = nil + group.entries = group.flatEntries + return + } + + levels := selectLevelsForBudget(group.availableLevels, group.allocatedSlots) + baseDisplay := cleanDisplayName(group.primary.info.DisplayName, group.primary.baseID) + if baseDisplay == "" { + baseDisplay = group.primary.baseID + } + + entries := make([]map[string]any, 0, len(levels)) + useDedicated := len(group.dedicatedByLevel) >= 2 + for _, lvl := range levels { + displayName := baseDisplay + " (" + lvl + ")" + if dedicated, ok := group.dedicatedByLevel[lvl]; ok { + _, primaryCovers := group.primaryLevelSet[lvl] + if useDedicated || (dedicated.id != group.primary.id && !primaryCovers) { + entries = append(entries, buildGeminiModelMap(dedicated.info, dedicated.id, displayName, true)) + continue + } + } + entries = append(entries, buildGeminiModelMap(group.primary.info, group.primary.id+"("+lvl+")", displayName, true)) + } + + group.expanded = true + group.levels = levels + group.entries = entries +} + +// selectLevelsForBudget picks k levels from available (already in canonical +// order), always retaining the lowest and highest levels and preferring high, +// medium, then xhigh for interior picks. +func selectLevelsForBudget(available []string, k int) []string { + if k >= len(available) { + return append([]string(nil), available...) + } + if k <= 0 { + return nil + } + if k == 1 { + return []string{available[len(available)-1]} + } + + chosen := make(map[string]struct{}, k) + chosen[available[0]] = struct{}{} + chosen[available[len(available)-1]] = struct{}{} + + interiorSet := make(map[string]struct{}, len(available)-2) + for _, lvl := range available[1 : len(available)-1] { + interiorSet[lvl] = struct{}{} + } + for _, preferred := range []string{"high", "medium", "xhigh"} { + if len(chosen) >= k { + break + } + if _, ok := interiorSet[preferred]; ok { + chosen[preferred] = struct{}{} + } + } + for _, lvl := range available { + if len(chosen) >= k { + break + } + chosen[lvl] = struct{}{} + } + + out := make([]string, 0, k) + for _, lvl := range available { + if _, ok := chosen[lvl]; ok { + out = append(out, lvl) + } + } + return out +} + +func buildFlatGroupEntries(members []modelMember, primary modelMember) []map[string]any { + if len(members) <= 1 { + return []map[string]any{ + buildGeminiModelMap(primary.info, primary.id, defaultDisplayName(primary.info, primary.id), primary.info.Thinking != nil), + } + } + // Preserve distinct real catalog models when neither supports thinking expansion, + // while still dropping forked aliases and empty-display adopted stubs. + entries := make([]map[string]any, 0, len(members)) + for _, m := range members { + if strings.TrimSpace(m.info.MetadataModelID) != "" { + continue + } + if !m.hasDisplay && primary.hasDisplay { + continue + } + entries = append(entries, buildGeminiModelMap(m.info, m.id, defaultDisplayName(m.info, m.id), m.info.Thinking != nil)) + } + if len(entries) == 0 { + return []map[string]any{ + buildGeminiModelMap(primary.info, primary.id, defaultDisplayName(primary.info, primary.id), primary.info.Thinking != nil), + } + } + return entries +} + +func selectPrimaryMember(members []modelMember) modelMember { + best := members[0] + for _, candidate := range members[1:] { + if preferMember(candidate, best) { + best = candidate + } + } + return best +} + +// preferMember picks the canonical member within a deduplicated model group. +// Real catalog definitions with display names beat empty adopted stubs, models +// with richer thinking metadata beat models without, and non-alias canonical +// models beat forked aliases targeting them. +func preferMember(candidate, current modelMember) bool { + if candidate.hasDisplay != current.hasDisplay { + return candidate.hasDisplay + } + if len(candidate.levels) != len(current.levels) { + return len(candidate.levels) > len(current.levels) + } + candAlias := strings.TrimSpace(candidate.info.MetadataModelID) != "" + currAlias := strings.TrimSpace(current.info.MetadataModelID) != "" + if candAlias != currAlias { + return !candAlias + } + candUnsuffixed := candidate.suffixLevel == "" + currUnsuffixed := current.suffixLevel == "" + if candUnsuffixed != currUnsuffixed { + return candUnsuffixed + } + return candidate.id < current.id +} + +func buildGeminiModelMap(info *registry.ModelInfo, modelID, displayName string, thinkingEnabled bool) map[string]any { + name := modelID + if !strings.HasPrefix(name, "models/") { + name = "models/" + name + } + if strings.TrimSpace(displayName) == "" { + displayName = modelID + } + description := strings.TrimSpace(info.Description) + if description == "" { + description = displayName + } + + // Emit only standard Gemini Model fields. Antigravity CLI validates the + // `/v1beta/models` JSON schema and uses the boolean `thinking` field to enable + // `includeThoughts` for non-Gemini models such as Claude. + result := map[string]any{ + "name": name, + "displayName": displayName, + "description": description, + } + if thinkingEnabled { + result["thinking"] = true + } + if info.Version != "" { + result["version"] = info.Version + } + inputTokenLimit := info.InputTokenLimit + if inputTokenLimit <= 0 { + inputTokenLimit = info.ContextLength + } + if inputTokenLimit > 0 { + result["inputTokenLimit"] = inputTokenLimit + } + outputTokenLimit := info.OutputTokenLimit + if outputTokenLimit <= 0 { + outputTokenLimit = info.MaxCompletionTokens + } + // Antigravity CLI rejects models whose outputTokenLimit >= inputTokenLimit + // when constructing its planner executor (contextWindow - maxOutputTokens <= 0). + if outputTokenLimit > 0 && (inputTokenLimit <= 0 || outputTokenLimit < inputTokenLimit) { + result["outputTokenLimit"] = outputTokenLimit + } + if len(info.SupportedGenerationMethods) > 0 { + result["supportedGenerationMethods"] = append([]string(nil), info.SupportedGenerationMethods...) + } else { + result["supportedGenerationMethods"] = []string{"generateContent"} + } + if len(info.SupportedInputModalities) > 0 { + result["supportedInputModalities"] = append([]string(nil), info.SupportedInputModalities...) + } + if len(info.SupportedOutputModalities) > 0 { + result["supportedOutputModalities"] = append([]string(nil), info.SupportedOutputModalities...) + } + return result +} + +func normalizeModelID(info *registry.ModelInfo) string { + if info == nil { + return "" + } + if id := normalizeRawID(info.ID); id != "" { + return id + } + return normalizeRawID(info.Name) +} + +func normalizeRawID(raw string) string { + return strings.TrimPrefix(strings.TrimSpace(raw), "models/") +} + +func defaultDisplayName(info *registry.ModelInfo, fallbackID string) string { + if info != nil && strings.TrimSpace(info.DisplayName) != "" { + return strings.TrimSpace(info.DisplayName) + } + return fallbackID +} + +// splitEffortSuffix splits a trailing "-low", "-medium", "-high", "-xhigh" or +// "-max" effort marker from the last path segment of a model ID. +func splitEffortSuffix(id string) (base string, level string) { + prefix := "" + segment := id + if slash := strings.LastIndexByte(id, '/'); slash >= 0 { + prefix = id[:slash+1] + segment = id[slash+1:] + } + lower := strings.ToLower(segment) + for _, candidate := range supportedLevels { + suffix := "-" + candidate + if strings.HasSuffix(lower, suffix) && len(segment) > len(suffix) { + return prefix + segment[:len(segment)-len(suffix)], candidate + } + } + return id, "" +} + +func stripTrailingThinkingSegment(id string) string { + lower := strings.ToLower(id) + const suffix = "-thinking" + if strings.HasSuffix(lower, suffix) && len(id) > len(suffix) { + return id[:len(id)-len(suffix)] + } + return id +} + +// cleanDisplayName removes trailing thinking/effort parentheticals (such as +// "(High)" or "(Thinking)") and unwraps remaining parenthetical qualifiers +// (such as "(Tiered)") so appending " ()" produces clean model names +// and slugified ACP model IDs in Antigravity CLI. +func cleanDisplayName(raw, fallbackID string) string { + name := strings.TrimSpace(raw) + if name == "" { + name = strings.TrimSpace(fallbackID) + } + for { + open := strings.LastIndexByte(name, '(') + if open <= 0 || !strings.HasSuffix(name, ")") { + break + } + inner := strings.TrimSpace(name[open+1 : len(name)-1]) + prefix := strings.TrimSpace(name[:open]) + if prefix == "" { + break + } + if isThinkingQualifier(inner) { + name = prefix + continue + } + if inner != "" { + name = prefix + " " + inner + continue + } + name = prefix + } + return strings.TrimSpace(name) +} + +func isThinkingQualifier(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "thinking", "none", "auto", "minimal", "low", "medium", "high", "xhigh", "extra", "extra high", "max": + return true + default: + return false + } +} diff --git a/internal/client/antigravitycli/models_test.go b/internal/client/antigravitycli/models_test.go new file mode 100644 index 00000000000..8a2cd0ff247 --- /dev/null +++ b/internal/client/antigravitycli/models_test.go @@ -0,0 +1,543 @@ +package antigravitycli + +import ( + "reflect" + "strings" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/registry" +) + +func TestIsAntigravityCLIUserAgent(t *testing.T) { + cases := []struct { + ua string + want bool + }{ + {"antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=gateway)", true}, + {"Antigravity/CLI/1.6.0", true}, + {" antigravity/cli/1.5.14 ", true}, + {"antigravity/hub/2.29.0", false}, + {"antigravity", false}, + {"curl/8.7.1", false}, + {"", false}, + } + for _, tc := range cases { + if got := IsAntigravityCLIUserAgent(tc.ua); got != tc.want { + t.Errorf("IsAntigravityCLIUserAgent(%q) = %v, want %v", tc.ua, got, tc.want) + } + } +} + +func TestResolveLevels(t *testing.T) { + cases := []struct { + name string + support *registry.ThinkingSupport + want []string + }{ + { + name: "nil thinking", + support: nil, + want: nil, + }, + { + name: "filters unsupported minimal/none/auto/ultra and preserves canonical order", + support: ®istry.ThinkingSupport{Levels: []string{"high", "minimal", "low", "none", "medium", "ultra", "auto"}}, + want: []string{"low", "medium", "high"}, + }, + { + name: "xhigh level preserved", + support: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high", "xhigh"}}, + want: []string{"low", "medium", "high", "xhigh"}, + }, + { + name: "single supported level after filtering minimal", + support: ®istry.ThinkingSupport{Levels: []string{"minimal", "high"}}, + want: []string{"high"}, + }, + { + name: "budget-only claude 4.6 range derives distinct levels", + support: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true}, + want: []string{"low", "medium", "high", "xhigh", "max"}, + }, + { + name: "budget-only capped at 24576 drops xhigh and max", + support: ®istry.ThinkingSupport{Min: 1, Max: 24576}, + want: []string{"low", "medium", "high"}, + }, + { + name: "budget pinned to one value yields single level", + support: ®istry.ThinkingSupport{Min: 32768, Max: 32768}, + want: []string{"xhigh"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ResolveLevels(tc.support) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("ResolveLevels() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestBuildModels_AntigravityCatalogAndForkedAliases(t *testing.T) { + infos := []*registry.ModelInfo{ + { + ID: "claude-opus-4-6-thinking", + DisplayName: "Claude Opus 4.6 (Thinking)", + Description: "Claude Opus 4.6 (Thinking)", + ContextLength: 200000, + MaxCompletionTokens: 64000, + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true}, + }, + { + ID: "claude-opus-5-5-high", + DisplayName: "Claude Opus 5.5 (High)", + Description: "Claude Opus 5.5 (High)", + ContextLength: 1000000, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "claude-sonnet-5-5-high", + DisplayName: "Claude Sonnet 5.5 (High)", + Description: "Claude Sonnet 5.5 (High)", + ContextLength: 1000000, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000, ZeroAllowed: true, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + // Forked alias alongside its upstream model — must deduplicate to one model. + { + ID: "gemini-4-neon", + MetadataModelID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon", + Description: "Gemini 4 Neon (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + { + ID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon", + Description: "Gemini 4 Neon (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + // Adopted stub alongside catalog model — catalog model must win. + { + ID: "gemini-4-argon", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "gemini-4-argon-high", + DisplayName: "Gemini 4 Argon", + Description: "Gemini 4 Argon (High)", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "gemini-3.8-flash-tiered", + DisplayName: "Gemini 3.8 Flash (Tiered)", + Description: "Gemini 3.8 Flash (Tiered)", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "gemini-3-flash", + DisplayName: "Gemini 3 Flash", + Description: "Gemini 3 Flash", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Min: 128, Max: 32768, DynamicAllowed: true, Levels: []string{"minimal", "low", "medium", "high"}}, + }, + { + ID: "gemini-3.1-flash-image", + DisplayName: "Gemini 3.1 Flash Image", + Description: "Gemini 3.1 Flash Image", + Thinking: ®istry.ThinkingSupport{Min: 128, Max: 32768, DynamicAllowed: true, Levels: []string{"minimal", "high"}}, + }, + { + ID: "gpt-oss-120b-medium", + DisplayName: "GPT-OSS 120B (Medium)", + Description: "GPT-OSS 120B (Medium)", + ContextLength: 114000, + MaxCompletionTokens: 32768, + }, + } + + got := BuildModels(infos) + byName := make(map[string]map[string]any, len(got)) + for _, entry := range got { + name, _ := entry["name"].(string) + if _, dup := byName[name]; dup { + t.Fatalf("duplicate model entry %q", name) + } + byName[name] = entry + // Ensure no minimal/none suffixes leak out as separate models. + if strings.Contains(name, "(minimal)") || strings.Contains(name, "(none)") { + t.Fatalf("unexpected unsupported level entry %q", name) + } + // Ensure strict Gemini Model schema (no unknown fields). + for key := range entry { + switch key { + case "name", "version", "displayName", "description", "thinking", "inputTokenLimit", "outputTokenLimit", "supportedGenerationMethods", "supportedInputModalities", "supportedOutputModalities": + default: + t.Fatalf("unexpected non-Gemini field %q on %q", key, name) + } + } + } + + if len(got) > maxCatalogEntries { + t.Fatalf("len(got) = %d, exceeds Antigravity CLI 32-entry limit", len(got)) + } + + // First entry must belong to a widest-level expanded model so `agy acp`'s + // initial session/new exposes the broadest thought_level range. + firstName, _ := got[0]["name"].(string) + if firstName != "models/claude-opus-4-6-thinking(low)" { + t.Fatalf("first entry = %q, want models/claude-opus-4-6-thinking(low)", firstName) + } + if got[0]["thinking"] != true { + t.Fatalf("expected thinking=true on expanded Claude model, got %#v", got[0]["thinking"]) + } + + // Check Claude Opus 5.5 expansion and cleaned display name. + for _, lvl := range []string{"low", "medium", "high"} { + entry, ok := byName["models/claude-opus-5-5-high("+lvl+")"] + if !ok { + t.Fatalf("missing claude-opus-5-5-high(%s)", lvl) + } + if dn := entry["displayName"]; dn != "Claude Opus 5.5 ("+lvl+")" { + t.Fatalf("claude-opus-5-5-high(%s) displayName = %q", lvl, dn) + } + if entry["thinking"] != true { + t.Fatalf("claude-opus-5-5-high(%s) thinking = %#v, want true", lvl, entry["thinking"]) + } + } + if _, exists := byName["models/claude-opus-5-5-high"]; exists { + t.Fatal("unexpanded claude-opus-5-5-high should not be emitted alongside expanded levels") + } + + // Check Gemini 4 Neon deduplication: only one model group (using canonical ID), no duplicate flat entry. + for _, lvl := range []string{"low", "medium", "high", "xhigh"} { + entry, ok := byName["models/gemini-4-neon-xhigh("+lvl+")"] + if !ok { + t.Fatalf("missing gemini-4-neon-xhigh(%s)", lvl) + } + if dn := entry["displayName"]; dn != "Gemini 4 Neon ("+lvl+")" { + t.Fatalf("gemini-4-neon-xhigh(%s) displayName = %q", lvl, dn) + } + if _, dup := byName["models/gemini-4-neon("+lvl+")"]; dup { + t.Fatalf("duplicate forked alias entry models/gemini-4-neon(%s) should be deduplicated", lvl) + } + } + if _, exists := byName["models/gemini-4-neon"]; exists { + t.Fatal("flat gemini-4-neon should not exist alongside expanded group") + } + if _, exists := byName["models/gemini-4-neon-xhigh"]; exists { + t.Fatal("flat gemini-4-neon-xhigh should not exist alongside expanded group") + } + + // Check adopted stub deduplication against catalog model. + for _, lvl := range []string{"low", "medium", "high"} { + if _, ok := byName["models/gemini-4-argon-high("+lvl+")"]; !ok { + t.Fatalf("missing gemini-4-argon-high(%s)", lvl) + } + if _, dup := byName["models/gemini-4-argon("+lvl+")"]; dup { + t.Fatalf("adopted stub gemini-4-argon(%s) should be deduplicated", lvl) + } + } + + // Check Tiered display name flattening avoids double parentheses. + if dn := byName["models/gemini-3.8-flash-tiered(low)"]["displayName"]; dn != "Gemini 3.8 Flash Tiered (low)" { + t.Fatalf("tiered displayName = %q, want Gemini 3.8 Flash Tiered (low)", dn) + } + + // Check single-level and non-thinking models remain flat and at the end. + if entry, ok := byName["models/gpt-oss-120b-medium"]; !ok || entry["displayName"] != "GPT-OSS 120B (Medium)" { + t.Fatalf("gpt-oss-120b-medium = %#v", entry) + } else if _, hasThinking := entry["thinking"]; hasThinking { + t.Fatalf("non-thinking model should not set thinking=true: %#v", entry) + } + if entry, ok := byName["models/gemini-3.1-flash-image"]; !ok || entry["displayName"] != "Gemini 3.1 Flash Image" { + t.Fatalf("gemini-3.1-flash-image = %#v", entry) + } +} + +func TestBuildModels_FullEmbeddedCatalogFits32SlotLimitWithoutDroppingModels(t *testing.T) { + infos := append([]*registry.ModelInfo(nil), registry.GetAntigravityModels()...) + // Add gemini-4-neon-xhigh and forked aliases matching a live account. + infos = append(infos, + ®istry.ModelInfo{ + ID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon", + Description: "Gemini 4 Neon (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 1048576, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + ®istry.ModelInfo{ + ID: "gemini-4-neon", + MetadataModelID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon", + Description: "Gemini 4 Neon (XHigh)", + ContextLength: 1048576, + MaxCompletionTokens: 1048576, + Thinking: ®istry.ThinkingSupport{Min: 1, Max: 65535, DynamicAllowed: true, Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + ®istry.ModelInfo{ + ID: "gemini-4-argon", + MetadataModelID: "gemini-4-argon-high", + DisplayName: "Gemini 4 Argon", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + }, + ) + + got := BuildModels(infos) + if len(got) > maxCatalogEntries { + t.Fatalf("len(got) = %d, want <= %d", len(got), maxCatalogEntries) + } + + // Count levels per model base ID; every single model must appear and every + // multi-level thinking model must retain at least 2 effort levels. + levelsByModel := make(map[string][]string) + for _, entry := range got { + name := strings.TrimPrefix(entry["name"].(string), "models/") + if idx := strings.IndexByte(name, '('); idx > 0 && strings.HasSuffix(name, ")") { + base := name[:idx] + lvl := name[idx+1 : len(name)-1] + levelsByModel[base] = append(levelsByModel[base], lvl) + } else { + levelsByModel[name] = nil + } + } + + wantThinkingModels := []string{ + "claude-opus-4-6-thinking", + "claude-sonnet-4-6", + "claude-opus-5-5-high", + "claude-sonnet-5-5-high", + "gemini-4-neon-xhigh", + "gemini-4-hydrogen-xhigh", + "gemini-4-argon-high", + "gemini-4-carbon-high", + "gemini-3.8-flash-high", + "gemini-3.8-flash-tiered", + "gemini-3-flash", + "gemini-3.1-flash-lite", + "gemini-3.5-flash-lite", + } + for _, id := range wantThinkingModels { + lvls, ok := levelsByModel[id] + if !ok { + t.Errorf("thinking model %q was dropped from 32-slot catalog", id) + continue + } + if len(lvls) < 2 { + t.Errorf("thinking model %q got %v (< 2 effort levels)", id, lvls) + } + } + for _, flatID := range []string{"gemini-3.1-flash-image", "gpt-oss-120b-medium"} { + if lvls, ok := levelsByModel[flatID]; !ok || len(lvls) != 0 { + t.Errorf("flat model %q missing or unexpectedly expanded: ok=%v lvls=%v", flatID, ok, lvls) + } + } + if _, dup := levelsByModel["gemini-4-neon"]; dup { + t.Error("forked alias gemini-4-neon should be deduplicated") + } + if _, dup := levelsByModel["gemini-4-argon"]; dup { + t.Error("forked alias gemini-4-argon should be deduplicated") + } + + // Ensure models whose catalog max_completion_tokens equals context_length + // (like gemini-4-hydrogen-xhigh at 1048576/1048576) omit outputTokenLimit so + // agy's planner executor does not compute zero available prompt tokens. + for _, entry := range got { + inLim, hasIn := entry["inputTokenLimit"].(int) + outLim, hasOut := entry["outputTokenLimit"].(int) + if hasIn && hasOut && outLim >= inLim { + t.Errorf("model %q has outputTokenLimit (%d) >= inputTokenLimit (%d)", entry["name"], outLim, inLim) + } + } +} + +func TestBuildModels_DistinctEffortVariantUpstreamModels(t *testing.T) { + infos := []*registry.ModelInfo{ + {ID: "claude-opus-5-5-low", DisplayName: "Claude Opus 5.5 (Low)"}, + {ID: "claude-opus-5-5-medium", DisplayName: "Claude Opus 5.5 (Medium)"}, + {ID: "claude-opus-5-5-high", DisplayName: "Claude Opus 5.5 (High)"}, + {ID: "claude-opus-5-5-max", DisplayName: "Claude Opus 5.5 (Max)"}, + } + + got := BuildModels(infos) + if len(got) != 4 { + t.Fatalf("len(got) = %d, want 4: %#v", len(got), got) + } + wantNames := []string{ + "models/claude-opus-5-5-low", + "models/claude-opus-5-5-medium", + "models/claude-opus-5-5-high", + "models/claude-opus-5-5-max", + } + wantDisplays := []string{ + "Claude Opus 5.5 (low)", + "Claude Opus 5.5 (medium)", + "Claude Opus 5.5 (high)", + "Claude Opus 5.5 (max)", + } + for i := range wantNames { + if got[i]["name"] != wantNames[i] { + t.Errorf("got[%d].name = %q, want %q", i, got[i]["name"], wantNames[i]) + } + if got[i]["displayName"] != wantDisplays[i] { + t.Errorf("got[%d].displayName = %q, want %q", i, got[i]["displayName"], wantDisplays[i]) + } + } +} + +func TestBuildModels_PreservesCustomNamedAliasAndPreSuffixedIDs(t *testing.T) { + infos := []*registry.ModelInfo{ + { + ID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high", "xhigh"}}, + ContextLength: 1048576, + OutputTokenLimit: 65536, + }, + { + ID: "my-custom-neon", + MetadataModelID: "gemini-4-neon-xhigh", + DisplayName: "My Custom Neon", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high", "xhigh"}}, + }, + { + ID: "pinned-model(high)", + DisplayName: "Pinned Model (high)", + }, + { + ID: "team/gemini-4-argon-high", + DisplayName: "Team Gemini 4 Argon", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + }, + } + + got := BuildModels(infos) + byName := make(map[string]map[string]any, len(got)) + for _, entry := range got { + byName[entry["name"].(string)] = entry + } + if _, ok := byName["models/my-custom-neon(xhigh)"]; !ok { + t.Fatalf("custom alias should remain expanded separately, got keys: %v", mapKeys(byName)) + } + if _, ok := byName["models/pinned-model(high)"]; !ok { + t.Fatalf("pre-suffixed model should pass through untouched, got keys: %v", mapKeys(byName)) + } + if _, ok := byName["models/team/gemini-4-argon-high(medium)"]; !ok { + t.Fatalf("prefixed model should expand cleanly, got keys: %v", mapKeys(byName)) + } +} + +func TestBuildModels_ForkedClaudeThinkingAliasDeduplicates(t *testing.T) { + infos := []*registry.ModelInfo{ + { + ID: "claude-opus-4-6", + MetadataModelID: "claude-opus-4-6-thinking", + DisplayName: "Claude Opus 4.6 (Thinking)", + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000}, + }, + { + ID: "claude-opus-4-6-thinking", + DisplayName: "Claude Opus 4.6 (Thinking)", + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000}, + }, + } + + got := BuildModels(infos) + if len(got) != 5 { + t.Fatalf("len(got) = %d, want 5: %#v", len(got), got) + } + for _, entry := range got { + name := entry["name"].(string) + if !strings.HasPrefix(name, "models/claude-opus-4-6-thinking(") { + t.Fatalf("unexpected entry %q", name) + } + } +} + +func TestBuildModels_SupplementalEffortVariantAndNonThinkingPair(t *testing.T) { + infos := []*registry.ModelInfo{ + // Unsuffixed model covers low..high while a dedicated -xhigh variant adds xhigh. + { + ID: "gemini-4-neon", + DisplayName: "Gemini 4 Neon", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + }, + { + ID: "gemini-4-neon-xhigh", + DisplayName: "Gemini 4 Neon (XHigh)", + }, + // Distinct non-thinking catalog models are not silently dropped. + { + ID: "gpt-oss-120b", + DisplayName: "GPT-OSS 120B", + }, + { + ID: "gpt-oss-120b-medium", + DisplayName: "GPT-OSS 120B (Medium)", + }, + } + + got := BuildModels(infos) + byName := make(map[string]map[string]any, len(got)) + for _, entry := range got { + byName[entry["name"].(string)] = entry + } + for _, lvl := range []string{"low", "medium", "high"} { + entry, ok := byName["models/gemini-4-neon("+lvl+")"] + if !ok || entry["displayName"] != "Gemini 4 Neon ("+lvl+")" { + t.Fatalf("missing/invalid gemini-4-neon(%s): %#v", lvl, entry) + } + } + if entry, ok := byName["models/gemini-4-neon-xhigh"]; !ok || entry["displayName"] != "Gemini 4 Neon (xhigh)" { + t.Fatalf("expected dedicated xhigh route, got: %#v", entry) + } + if _, ok := byName["models/gpt-oss-120b"]; !ok { + t.Fatalf("expected gpt-oss-120b to be preserved, got keys: %v", mapKeys(byName)) + } + if _, ok := byName["models/gpt-oss-120b-medium"]; !ok { + t.Fatalf("expected gpt-oss-120b-medium to be preserved, got keys: %v", mapKeys(byName)) + } +} + +func TestFindModel(t *testing.T) { + infos := []*registry.ModelInfo{ + { + ID: "claude-opus-5-5-high", + DisplayName: "Claude Opus 5.5 (High)", + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + }, + } + if m := FindModel(infos, "claude-opus-5-5-high(medium)"); m == nil || m["displayName"] != "Claude Opus 5.5 (medium)" { + t.Fatalf("FindModel(bare) = %#v", m) + } + if m := FindModel(infos, "models/claude-opus-5-5-high(high)"); m == nil || m["displayName"] != "Claude Opus 5.5 (high)" { + t.Fatalf("FindModel(prefixed) = %#v", m) + } + if m := FindModel(infos, "nonexistent"); m != nil { + t.Fatalf("FindModel(nonexistent) = %#v, want nil", m) + } +} + +func mapKeys(m map[string]map[string]any) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +}