diff --git a/docs/architecture/rfcs/manager-runtime-profile-v0.md b/docs/architecture/rfcs/manager-runtime-profile-v0.md index ef9ffcea8e..70ca710f9f 100644 --- a/docs/architecture/rfcs/manager-runtime-profile-v0.md +++ b/docs/architecture/rfcs/manager-runtime-profile-v0.md @@ -53,7 +53,17 @@ These defaults do not change ordinary Goal Chat models or grant other Agents too sandbox. Trusted-owner remains limited to the existing verified owner audience. Governed Task execution, workspace filesystem grants and native managed steward identity preparation retain their existing Codex owner; selecting Antigravity does not widen those contracts. - Argon tiers must be offered by the local account and match the requested reasoning effort. + Registered Argon and Carbon tiers must be offered by the local account and match the + `reasoning_effort` (`low`, `medium`, or `high`). Model discovery reads the same + account metadata without opening a cascade; an unavailable catalog is an explicit error, + not a static list of supposedly available models. Antigravity's default remains Argon; + operators who want another offered tier (such as Carbon `gemini-4-carbon-high`) for an + endpoint on a specific machine configure it explicitly via top-level `executor_model` or + optional per-endpoint `endpoint_models` entries on `steward_executor_machine_defaults_v1`. + Ordered `eligible_endpoints` and bidirectional flexible failover between `codex` and + `antigravity` route exhausted Codex stewards onto the configured fallback endpoint (and back + to Codex once restored) with model-isolated reasoning effort and native steward monitor/report + parity on the qualified fallback Session. A missing original cascade fails resume without silently starting a replacement. Stop waits for the native cascade to become idle; timeout or partial output is not successful completion. During execution, native `IDLE` alone is not completion: it can appear between input, tool @@ -131,6 +141,32 @@ owner-private bindings reuse Core's fresh audience/resource verification before reusing a host; no channel-name inference, persisted proof or manager-specific ACL replaces it. A revoked binding or changed App/owner stops admission. +Saving machine defaults does not move an existing steward to another executor endpoint. +The original private conversation's model menu offers **Apply to this conversation** for +the saved preferred/pinned executor, model and reasoning effort. Its preview opens no +native thread. Apply requires an idle Session with no active or reserved queued work, +registered worker, parked native work or answer-review route. It prepares the selected +host without dispatching a model Turn, after closing the old idle transport and capturing +the complete visible history. When only the Codex model or reasoning effort changes +and the current working checkpoint is available, apply reuses the model-resume path +to verify and continue the same native thread without reinjecting history. If that +checkpoint fails verification, apply stops before closing the original transport. +An executor migration restores the visible history on the new native thread. +Only provider-observed model and effort can be committed to the same Session. +The source binding remains unchanged; +Core verifies its live owner, source and resource grant again, and subsequent inputs use +the explicitly accepted Session allocation with retained original native provenance. + +The Session store checks the original identity, selected binding, saved configuration, +queue and captured transcript again under its publication locks. A changed source, +revoked owner, new queued input, returned message or unconfirmed host setting rejects +publication and closes the unpublished transport. Canonical history and queued work +remain available for recovery. After a lost response, read the actual Session first: +an already applied allocation needs no second preparation. The menu displays that actual +executor/model readback; saving defaults, preparing a host, executing a model Turn and +installing the changed service remain distinct observations. Other conversations, +ordinary model settings and flexible quota recovery retain their existing owners. + This slice implements only the private-owner M1 journey in [capable-manager-semantic-handoff-v0](capable-manager-semantic-handoff-v0.md), targeting A1–A3/A12. It does not implement the M2 collaboration request, the M3 outbox, or treat manager Session fields @@ -156,8 +192,9 @@ delivery. Follow [roadmap](loopx-overall-roadmap-v0.md) R2 for those remaining q 4. A profile change rotates the upstream thread while preserving the LoopX Session and visible history. 5. An unrelated machine-configuration change does not rotate the thread. -6. A non-Codex endpoint fails closed for `trusted_owner` and recommends selecting Codex or - restoring `restricted`. +6. Codex and Antigravity support the verified private owner's `trusted_owner` profile while + retaining their native permission and approval boundaries. An unsupported endpoint fails + closed and recommends a supported executor or restoring `restricted`. 7. Desktop and mobile Dashboard show the effective profile; invalid configuration shows its fallback state. 8. An external audience without an existing scoped grant remains `read-only` and exposes the diff --git a/docs/architecture/rfcs/manager-runtime-profile-v0.zh-CN.md b/docs/architecture/rfcs/manager-runtime-profile-v0.zh-CN.md index ca5836b5c9..7e1128b688 100644 --- a/docs/architecture/rfcs/manager-runtime-profile-v0.zh-CN.md +++ b/docs/architecture/rfcs/manager-runtime-profile-v0.zh-CN.md @@ -43,7 +43,15 @@ LoopX 管家最初只有受限的规划会话:它可以读取 LoopX 提供的 planner 模式,不继承上一回合的工具配置。这是 provider 工具限制,不是 Codex 或操作 系统 sandbox。强能力模式仍限于既有核验过的本人受众。受治理 Task 执行、工作区文件 系统授权和原生受管理管家身份准备仍由既有 Codex owner 承接;选择 Antigravity 不扩展 - 这些契约。Argon 档位必须由本地账号提供,并与请求的思考深度一致。原始 cascade 丢失 + 这些契约。已注册的 Argon 与 Carbon 档位必须由本地账号提供,并与请求的思考深度 + (`low`、`medium` 或 `high`)一致。模型发现读取相同的账号元数据,不创建 cascade; + 目录不可用时明确报错,不用静态清单冒充可用模型。Antigravity 的默认模型仍为 Argon; + 需要在本机为特定执行器优先指定其他已提供档位(例如 Carbon `gemini-4-carbon-high`)时, + 可通过 `executor_model` 或 `steward_executor_machine_defaults_v1` 上可选的按执行器映射 + `endpoint_models` 显式配置。配合有序的 `eligible_endpoints` 与 `codex`、`antigravity` 之间 + 的双向弹性故障转移,可在 Codex 耗尽时按可观测配额切换至配置的回退执行器(并在恢复后 + 切回),同时隔离模型专属的推理强度配置并在合格回退 Session 上保持原生管家 monitor 与报告 + 能力对齐。原始 cascade 丢失 时续接失败,不静默创建替代会话。停止等待原生 cascade 回到 idle;超时或部分输出 不代表成功完成。 执行时,原生 `IDLE` 本身不代表完成:输入、工具与 planner 步骤之间也可能出现此状态。 @@ -106,6 +114,22 @@ profile 或权限状态。原生本人私聊在启动或复用宿主前重新核 的 M1 私有 Owner 旅程,目标验收为 A1–A3/A12。它不实现 M2 collaboration request、M3 outbox,也不把管家 session 字段当成工作、请求或送达权威。 +保存机器默认配置不会把既有管家移到另一执行器 endpoint。原私有对话的模型菜单提供 +**应用到此对话**,采用已保存的 preferred/pinned 执行器、模型与思考深度。预览不创建 +原生线程。应用要求 Session 空闲,没有活动或已预留的排队工作、注册 worker、停放的 +原生工作或答案复核路径。它先关闭旧空闲 transport、捕获完整可见历史,再准备所选宿主, +不派发模型 Turn。如果只调整 Codex 内的模型或思考深度,且当前工作检查点可用,应用会 +沿用同一模型续接路径,核验后恢复原生线程,省去重新注入历史。检查点核验失败时,应用在 +关闭原 transport 之前停止。跨执行器迁移会在新的原生线程恢复完整可见历史。 +同一 Session 只保存宿主实际回报的模型与思考深度。来源绑定保持不变;Core 再次校验当前 owner、来源和资源授权,后续输入使用该 Session +明确接受的 allocation,并保留原始原生执行器的沿革。 + +Session store 在发布锁内再次核验原身份、选定绑定、已保存配置、队列与捕获的完整文本。 +来源改变、owner 撤权、新排队输入、返回消息或宿主设置未确认都会拒绝发布,并关闭未发布的 +transport。原历史与排队工作仍可恢复。响应丢失后先读取实际 Session;已经应用的 allocation +无需再次准备。菜单显示实际执行器/模型回读;保存默认值、准备宿主、执行模型 Turn 和安装 +变更后的服务分别记录。其他会话、普通模型设置及 flexible 配额恢复沿用原有 owner。 + ### 实现与后继 `43d362532` 引入机器模式。原生本人管家私聊在打开、续接和授权范围刷新时,将 Core @@ -123,8 +147,9 @@ outbox,也不把管家 session 字段当成工作、请求或送达权威。 `AGENTS.md` 不再包含只读限制。 4. profile 改变会旋转上游 thread,但保留 LoopX Session 和可见历史。 5. 不相关机器配置变化不会旋转 thread。 -6. 非 Codex endpoint 对 `trusted_owner` fail closed,并给出切换 endpoint 或恢复 - `restricted` 的动作提示。 +6. Codex 与 Antigravity 支持已验证私有本人的 `trusted_owner` 模式,并保留各自原生权限和 + 审批边界。不支持的 endpoint 必须拒绝,并给出切换到受支持执行器或恢复 `restricted` + 的动作提示。 7. 桌面和移动 Dashboard 显示有效 profile;配置损坏时显示回退状态。 8. 外部 audience 在没有既有 scoped grant 时继续 `read-only`,并显示真实降级状态。 9. 已核验的原生本人管家私聊沿用实际机器策略,模式改变或服务重启保留 Session 与历史; diff --git a/loopx/capabilities/native_chat/antigravity_adapter.py b/loopx/capabilities/native_chat/antigravity_adapter.py index e97bae2a91..f5d989f069 100644 --- a/loopx/capabilities/native_chat/antigravity_adapter.py +++ b/loopx/capabilities/native_chat/antigravity_adapter.py @@ -18,6 +18,7 @@ import urllib.request from urllib.parse import urlsplit import uuid +from contextlib import AbstractContextManager, nullcontext from datetime import datetime from ...chat import ( @@ -39,6 +40,9 @@ "gemini-4-argon-high": "MODEL_PLACEHOLDER_M417", "gemini-4-argon-medium": "MODEL_PLACEHOLDER_M418", "gemini-4-argon-low": "MODEL_PLACEHOLDER_M419", + "gemini-4-carbon-high": "MODEL_PLACEHOLDER_M427", + "gemini-4-carbon-medium": "MODEL_PLACEHOLDER_M437", + "gemini-4-carbon-low": "MODEL_PLACEHOLDER_M438", } _SETTLED_STEP_STATUSES = { @@ -64,12 +68,13 @@ def _step_allows_completed_turn(step: dict[str, Any], *, final: dict[str, Any]) ANTIGRAVITY_MODEL_OPTIONS: tuple[dict[str, Any], ...] = tuple( { - "id": f"gemini-4-argon-{effort}", - "display_name": f"Gemini 4 Argon ({effort.title()})", - "is_default": effort == "high", + "id": f"gemini-4-{family}-{effort}", + "display_name": f"Gemini 4 {family.title()} ({effort.title()})", + "is_default": family == "argon" and effort == "high", "default_reasoning_effort": effort, "supported_reasoning_efforts": [{"reasoning_effort": effort}], } + for family in ("argon", "carbon") for effort in ("high", "medium", "low") ) @@ -251,7 +256,7 @@ def _rpc_post( def discover_antigravity_language_server( env: Mapping[str, str] | None = None, - *, deadline: float | None = None, + *, deadline: float | None = None, include_model_config: bool = False, ) -> dict[str, Any] | None: """Discover a running local endpoint without reusing an availability verdict. @@ -269,7 +274,7 @@ def discover_antigravity_language_server( timeout = 2.5 if deadline is None else min(2.5, deadline - time.monotonic()) if timeout <= 0: return None - _rpc_post( + model_data = _rpc_post( explicit_url, explicit_token, "GetCascadeModelConfigData", @@ -281,6 +286,7 @@ def discover_antigravity_language_server( "csrf_token": explicit_token, "pid": None, "source": "environment", + **({"model_config_data": model_data} if include_model_config else {}), } except (CodexChatAgentError, ValueError): return None @@ -341,12 +347,13 @@ def discover_antigravity_language_server( break url = f"http://127.0.0.1:{port}" try: - _rpc_post(url, token, "GetCascadeModelConfigData", {}, timeout=min(1.5, remaining)) + model_data = _rpc_post(url, token, "GetCascadeModelConfigData", {}, timeout=min(1.5, remaining)) return { "url": url, "csrf_token": token, "pid": pid, "source": "process_discovery", + **({"model_config_data": model_data} if include_model_config else {}), } except CodexChatAgentError: continue @@ -395,24 +402,78 @@ def resolve_antigravity_model_placeholder( gate=None, error_code="unsupported_configuration") if not raw_model or raw_model in {"argon", "gemini-4-argon"}: canonical = f"gemini-4-argon-{effort or 'high'}" + elif raw_model in {"carbon", "gemini-4-carbon"}: + canonical = f"gemini-4-carbon-{effort or 'high'}" else: canonical = raw_model if (canonical not in ANTIGRAVITY_MODEL_PLACEHOLDERS - or effort and canonical != f"gemini-4-argon-{effort}"): - raise CodexChatAgentError("Choose a supported Argon model and its matching reasoning effort.", + or effort and canonical.rsplit("-", 1)[-1] != effort): + raise CodexChatAgentError("Choose a supported Antigravity model and its matching reasoning effort.", gate=None, error_code="unsupported_configuration") placeholder = ANTIGRAVITY_MODEL_PLACEHOLDERS[canonical] if dynamic_configs is not None: match = next((row for row in dynamic_configs - if row.get("modelId") == canonical - or (row.get("modelOrAlias") or {}).get("model") == placeholder), None) + if isinstance(row.get("modelOrAlias") or {}, dict) + and (row.get("modelId") == canonical + or (not row.get("modelId") + and (row.get("modelOrAlias") or {}).get("model") == placeholder))), None) if match is None: - raise CodexChatAgentError("The local Antigravity account did not offer this Argon model.", + raise CodexChatAgentError("The local Antigravity account did not offer this model.", gate=None, error_code="unsupported_configuration") placeholder = str((match.get("modelOrAlias") or {}).get("model") or placeholder) return canonical, placeholder +def _discovered_model_configs(discovered: Mapping[str, Any]) -> list[dict[str, Any]]: + """Reuse verified metadata, or read it for an endpoint-only record.""" + data = discovered.get("model_config_data") + if not isinstance(data, dict): + data = _rpc_post(discovered["url"], discovered["csrf_token"], + "GetCascadeModelConfigData", {}, timeout=3.0) + raw = data.get("clientModelConfigs") + return [row for row in raw if isinstance(row, dict)] if isinstance(raw, list) else [] + + +def offered_antigravity_model_options( + *, discovered: Mapping[str, Any] | None = None, +) -> list[dict[str, Any]]: + """Read registered choices from the local account without opening a cascade.""" + if discovered is None: + discovered = discover_antigravity_language_server(include_model_config=True) + if discovered is None: + raise CodexChatAgentError("Antigravity local language_server is not running or reachable", + gate=None, error_code="antigravity_unavailable") + configs = _discovered_model_configs(discovered) + options = [] + for item in ANTIGRAVITY_MODEL_OPTIONS: + try: + resolve_antigravity_model_placeholder(item["id"], dynamic_configs=configs) + except CodexChatAgentError: + continue + options.append(item) + if not options: + raise CodexChatAgentError("The local Antigravity account did not offer a supported model. Retry model discovery.", + gate=None, error_code="unsupported_configuration") + return options + + +def _matching_antigravity_model_config(rows: list[Any], model_id: str) -> list[dict[str, Any]]: + """Match clientModelConfigs entries by modelId or placeholder when LS omits modelId.""" + expected_placeholder = ANTIGRAVITY_MODEL_PLACEHOLDERS.get(model_id) + return [ + row for row in rows + if isinstance(row, dict) and ( + row.get("modelId") == model_id + or ( + not row.get("modelId") + and expected_placeholder is not None + and isinstance(row.get("modelOrAlias"), dict) + and row["modelOrAlias"].get("model") == expected_placeholder + ) + ) + ] + + def _native_user_input_text(step: dict[str, Any]) -> str | None: """Read the one native text item; any redundant response must agree.""" content = step.get("userInput") @@ -661,7 +722,7 @@ def read(method: str, payload: dict[str, Any]) -> dict[str, Any]: if not isinstance(account, str) or not account.strip(): return None rows = user["cascadeModelConfigData"]["clientModelConfigs"] - matching = [row for row in rows if row.get("modelId") == model_id] + matching = _matching_antigravity_model_config(rows, model_id) if len(matching) != 1: return None quota = matching[0]["quotaInfo"] @@ -681,6 +742,49 @@ def read(method: str, payload: dict[str, Any]) -> dict[str, Any]: except (KeyError, TypeError, ValueError, AttributeError, CodexChatAgentError): return None + @staticmethod + def endpoint_model_capacity( + *, + model_id: str, + env: Mapping[str, str] | None = None, + discovered: Mapping[str, Any] | None = None, + ) -> dict[str, Any] | None: + """Observe the live LS account's quota for one offered model without opening a cascade.""" + try: + found = discovered or discover_antigravity_language_server(env=env, include_model_config=True) + if found is None: + return None + status = _rpc_post(str(found["url"]), str(found["csrf_token"]), "GetUserStatus", {}, timeout=5.0) + user = status["userStatus"] + account = user.get("email") + if not isinstance(account, str) or not account.strip(): + return None + rows = (user.get("cascadeModelConfigData") or {}).get("clientModelConfigs") + if not isinstance(rows, list): + rows = (found.get("model_config_data") or {}).get("clientModelConfigs") or [] + matching = _matching_antigravity_model_config(rows, model_id) + if len(matching) != 1: + return None + quota = matching[0]["quotaInfo"] + fraction, reset = quota.get("remainingFraction", 0), quota.get("resetTime") + if (type(fraction) not in (int, float) or not math.isfinite(fraction) + or not 0 <= fraction <= 1 or not isinstance(reset, str) + or datetime.fromisoformat(reset).tzinfo is None): + return None + exhausted = fraction <= 0 + return { + "model_id": model_id, + "account_ref": hashlib.sha256(account.strip().casefold().encode()).hexdigest(), + "remaining_fraction": fraction, + "reset_time": reset, + "execution_id": f"endpoint-probe:{uuid.uuid4().hex}", + "observed_at": time.time(), + "quota_exhausted": exhausted, + "normal_completion": not exhausted, + } + except (KeyError, TypeError, ValueError, AttributeError, CodexChatAgentError): + return None + @staticmethod def completed_result_observation(*, cascade_id: str, request_ref: str, message: str, started_at: str, completed_at: str, @@ -829,6 +933,8 @@ def __init__( self._send_lock = threading.Lock() self._active_turn_id: str | None = None self._cancel_acknowledged = False + self._launch_guard: Callable[[], AbstractContextManager[None]] | None = None + self._steward_report_reader: Callable[[str, Any], dict[str, Any]] | None = None @property def current_model_id(self) -> str: @@ -861,7 +967,7 @@ def start( # Validate user intent before creating an upstream cascade. requested = dict(executor_model or {}) resolve_antigravity_model_placeholder(requested.get("model"), requested.get("reasoning_effort")) - discovered = discover_antigravity_language_server(env=env) + discovered = discover_antigravity_language_server(env=env, include_model_config=True) if discovered is None: raise CodexChatAgentError( "Antigravity local language_server is not running or reachable", @@ -871,9 +977,7 @@ def start( ls_url = str(discovered["url"]) csrf_token = str(discovered["csrf_token"]) - model_data = _rpc_post(ls_url, csrf_token, "GetCascadeModelConfigData", {}, timeout=3.0) - raw_configs = model_data.get("clientModelConfigs") - dynamic_configs = [item for item in raw_configs if isinstance(item, dict)] if isinstance(raw_configs, list) else [] + dynamic_configs = _discovered_model_configs(discovered) requested_model = ( str(executor_model.get("model") or "").strip() @@ -1073,15 +1177,16 @@ def _run_turn( **({"media": media} if media else {}), } with self._send_lock: - self._check_interrupted() - self._active_turn_id = turn_id - if event_sink is not None: - event_sink("turn.started", {"upstream_turn_id": turn_id, "threadId": self.cascade_id, - "native_input": {"thread_id": self.cascade_id, "start_step_index": start_step_index, - "input_sha256": hashlib.sha256(full_prompt.encode()).hexdigest()}}) - _rpc_post(self.ls_url, self.csrf_token, "SendUserCascadeMessage", send_payload, timeout=15.0) - self._system_primed = True - self._pending_history.clear() + with (self._launch_guard() if self._launch_guard is not None else nullcontext()): + self._check_interrupted() + self._active_turn_id = turn_id + if event_sink is not None: + event_sink("turn.started", {"upstream_turn_id": turn_id, "threadId": self.cascade_id, + "native_input": {"thread_id": self.cascade_id, "start_step_index": start_step_index, + "input_sha256": hashlib.sha256(full_prompt.encode()).hexdigest()}}) + _rpc_post(self.ls_url, self.csrf_token, "SendUserCascadeMessage", send_payload, timeout=15.0) + self._system_primed = True + self._pending_history.clear() stream_filter = VisibleResponseStreamFilter() emitted_visible_delta = False diff --git a/loopx/capabilities/native_chat/model_settings.py b/loopx/capabilities/native_chat/model_settings.py index 0e9306126b..127b6aecbd 100644 --- a/loopx/capabilities/native_chat/model_settings.py +++ b/loopx/capabilities/native_chat/model_settings.py @@ -133,14 +133,16 @@ def inspect_agent_model_options(controller: ChatRuntimeController, agent_id: str }, } if agent_id == "antigravity": - from .antigravity_adapter import ANTIGRAVITY_DEFAULT_MODEL, ANTIGRAVITY_MODEL_OPTIONS + from .antigravity_adapter import ANTIGRAVITY_DEFAULT_MODEL, offered_antigravity_model_options + options = offered_antigravity_model_options() return { "agent_id": agent_id, "supported": True, "model": { "id": "model", "label": "Model", - "selected": ANTIGRAVITY_DEFAULT_MODEL, + "selected": (ANTIGRAVITY_DEFAULT_MODEL + if any(item["id"] == ANTIGRAVITY_DEFAULT_MODEL for item in options) else None), "options": [ { "value": str(item["id"]), @@ -154,7 +156,7 @@ def inspect_agent_model_options(controller: ChatRuntimeController, agent_id: str if isinstance(effort, dict) and effort.get("reasoning_effort") ], } - for item in ANTIGRAVITY_MODEL_OPTIONS + for item in options ], }, } diff --git a/loopx/capabilities/native_chat/steward_managed_mode.py b/loopx/capabilities/native_chat/steward_managed_mode.py index 83c3366b05..c6bab096a6 100644 --- a/loopx/capabilities/native_chat/steward_managed_mode.py +++ b/loopx/capabilities/native_chat/steward_managed_mode.py @@ -167,7 +167,7 @@ def health(self, binding_id: str) -> dict[str, Any]: return {"available": True, "prepared": True, **(self.bindings._core("collaboration.steward.managed_mode.executor", { "binding": binding, "session": session}) - if binding["executor_endpoint_id"] != "codex" else {}), + if binding["executor_endpoint_id"] != "codex" or session.get("agent_id") != "codex" else {}), "scheduling_enabled": bool(active and monitor and monitor.get("status") == "open"), "goal_active": active, "report": StewardReports(self.controller).health(binding_id), "monitor": ({"todo_id": monitor["todo_id"], "status": monitor["status"], diff --git a/loopx/capabilities/native_chat/steward_reports.py b/loopx/capabilities/native_chat/steward_reports.py index da82967192..473b5e4ab7 100644 --- a/loopx/capabilities/native_chat/steward_reports.py +++ b/loopx/capabilities/native_chat/steward_reports.py @@ -438,7 +438,8 @@ def prepare(self, request: dict[str, Any], adapter: Any, *, authorization_scope_ _, window = self.current_window(request["actor"]["goal_id"].removeprefix("steward-agent-")) if not window or window["window_id"] != request["report_window_id"]: raise ValueError("the admitted original report window is unavailable") - reader = getattr(adapter.session, "read_tool_handler", None) + reader = (getattr(adapter.session, "read_tool_handler", None) + if hasattr(adapter, "session") else getattr(adapter, "_steward_report_reader", None)) if reader is None or not authorization_scope_id: raise ValueError("the original scoped report reader is unavailable") session = self.controller.store.load_session(request["actor"]["session_id"]) diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index d430286b47..faf881fe7e 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -844,6 +844,7 @@ def execute(self, *, session_id: str, turn_id: str, adapter: Any, from ...cli import build_parser from ...cli_commands.turn import handle_turn_command from ...control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt, parse_model_json, build_result + from .antigravity_adapter import AntigravityAdapter from .codex_adapter import CodexAppServerAdapter turn = self.store.load_turn(session_id, turn_id) @@ -878,8 +879,10 @@ def execute(self, *, session_id: str, turn_id: str, adapter: Any, monitor = StewardMonitor(self.controller) todo = next((row for row in monitor.todos(actor) if row["todo_id"] == request["todo_id"]), None) return monitor.observe(host=self, request=request, turn=turn, context=context, todo=todo) - if not isinstance(adapter, CodexAppServerAdapter): + if local_session and not isinstance(adapter, CodexAppServerAdapter): raise ValueError("native steward work requires the original Codex app-server adapter") + if not local_session and not isinstance(adapter, (CodexAppServerAdapter, AntigravityAdapter)): + raise ValueError("native steward work requires the original Codex app-server or Antigravity adapter") original_thread = adapter.upstream_thread_id from .steward_reports import report_service reports, report_owner_key = report_service(self.controller, actor) if report_work else (None, None) @@ -997,7 +1000,8 @@ def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]: "source_todo_id": basis["definition"]["source_task"]["todo_id"], "window_start": basis["window"]["start_at"], "window_end": basis["window"]["due_at"], }, ensure_ascii=False) - previous_guard = adapter.session._launch_guard + guard_owner = adapter.session if isinstance(adapter, CodexAppServerAdapter) else adapter + previous_guard = guard_owner._launch_guard @contextmanager def launch(): @@ -1022,7 +1026,7 @@ def launch(): raise BuiltInHostError(str(exc), failure_kind="contract_rejected") from exc yield - adapter.session._launch_guard = launch + guard_owner._launch_guard = launch try: if managed_turn and not governance_work: from ...control_plane.effect_runtime import effect_runtime_result @@ -1033,7 +1037,7 @@ def launch(): else: response = adapter.start_turn(prompt, event_sink) finally: - adapter.session._launch_guard = previous_guard + guard_owner._launch_guard = previous_guard current() # Revocation/stop/retarget after a long model call wins. candidate = parse_model_json(str(response.get("message") or "")) kernel_candidate = dict(candidate) if candidate is not None else None @@ -1054,7 +1058,8 @@ def launch(): # The kernel still runs its independent validator and lease # fence before closing only this window's generation Todo. kernel_candidate["result_kind"] = "validated_completion" - built = build_result(native_request, kernel_candidate, host_name="Codex app-server", + built = build_result(native_request, kernel_candidate, + host_name="Antigravity" if isinstance(adapter, AntigravityAdapter) else "Codex app-server", **({"allow_completion": True} if (report_work or managed_turn or steward_advancement) and not governance_work else {})) managed_answer = str(built.get("summary") or "") if (managed_turn or steward_advancement) else "" return built diff --git a/loopx/capabilities/steward_executor/__init__.py b/loopx/capabilities/steward_executor/__init__.py index 5c045c47f4..d1ba32a149 100644 --- a/loopx/capabilities/steward_executor/__init__.py +++ b/loopx/capabilities/steward_executor/__init__.py @@ -14,6 +14,7 @@ ) from .machine_defaults import ( ELIGIBLE_ENDPOINTS_FIELD, + ENDPOINT_MODELS_FIELD, FLEXIBLE_SELECTION_POLICY, PINNED_SELECTION_POLICY, PREFERRED_SELECTION_POLICY, @@ -33,6 +34,7 @@ __all__ = [ "ELIGIBLE_ENDPOINTS_FIELD", + "ENDPOINT_MODELS_FIELD", "FLEXIBLE_SELECTION_POLICY", "MANAGER_ALLOCATION_REASON_CONFIGURED_PREFERENCE", "MANAGER_ALLOCATION_REASON_FLEXIBLE_FALLBACK", diff --git a/loopx/capabilities/steward_executor/machine_defaults.py b/loopx/capabilities/steward_executor/machine_defaults.py index 9d97981709..efa385e67a 100644 --- a/loopx/capabilities/steward_executor/machine_defaults.py +++ b/loopx/capabilities/steward_executor/machine_defaults.py @@ -75,6 +75,7 @@ REASONING_EFFORT_FIELD = "executor_reasoning_effort" SELECTION_POLICY_FIELD = "selection_policy" ELIGIBLE_ENDPOINTS_FIELD = "eligible_endpoints" +ENDPOINT_MODELS_FIELD = "endpoint_models" PREFERRED_SELECTION_POLICY = "preferred" PINNED_SELECTION_POLICY = "pinned" FLEXIBLE_SELECTION_POLICY = "flexible" @@ -132,7 +133,7 @@ def normalize_steward_executor_machine_defaults( "steward_executor must use " f"{STEWARD_EXECUTOR_SCHEMA_V0} or {STEWARD_EXECUTOR_SCHEMA}" ) - v1_fields = {SELECTION_POLICY_FIELD, ELIGIBLE_ENDPOINTS_FIELD} + v1_fields = {SELECTION_POLICY_FIELD, ELIGIBLE_ENDPOINTS_FIELD, ENDPOINT_MODELS_FIELD} unknown = sorted( set(raw) - { @@ -205,11 +206,22 @@ def normalize_steward_executor_machine_defaults( raise ValueError( "steward_executor.eligible_endpoints is only valid for flexible selection" ) - return { - **normalized, - SELECTION_POLICY_FIELD: selection_policy, - ELIGIBLE_ENDPOINTS_FIELD: eligible_endpoints, - } + raw_ep = raw.get(ENDPOINT_MODELS_FIELD) + if raw_ep is not None and not isinstance(raw_ep, Mapping): + raise TypeError("steward_executor.endpoint_models must be an object") + ep_models: dict[str, dict[str, str | None]] = {} + for ep_key, ep_val in (raw_ep or {}).items(): + ep = str(ep_key or "").strip() + if ep not in supported or not isinstance(ep_val, Mapping) or set(ep_val) - {"model", "reasoning_effort"}: + raise ValueError(f"steward_executor.endpoint_models.{ep or ep_key} is invalid") + ep_m = _optional_text(ep_val.get("model"), field=f"endpoint_models.{ep}.model") + ep_e = _optional_text(ep_val.get("reasoning_effort"), field=f"endpoint_models.{ep}.reasoning_effort") + if ep_e is not None and ep_e not in supported_efforts: + raise ValueError("steward_executor.endpoint_models reasoning_effort must be one of " + ", ".join(supported_efforts)) + if ep_m is not None or ep_e is not None: + ep_models[ep] = {"model": ep_m, "reasoning_effort": ep_e} + return {**normalized, SELECTION_POLICY_FIELD: selection_policy, ELIGIBLE_ENDPOINTS_FIELD: eligible_endpoints, + **({ENDPOINT_MODELS_FIELD: ep_models} if ep_models else {})} def steward_executor_machine_configuration_namespace() -> ( @@ -260,6 +272,7 @@ def _projection( reasoning_effort: str | None = None, selection_policy: str = PREFERRED_SELECTION_POLICY, eligible_endpoints: list[str] | None = None, + endpoint_models: dict[str, dict[str, str | None]] | None = None, repair: str = "", ) -> Payload: return { @@ -272,6 +285,7 @@ def _projection( REASONING_EFFORT_FIELD: reasoning_effort, SELECTION_POLICY_FIELD: selection_policy, ELIGIBLE_ENDPOINTS_FIELD: list(eligible_endpoints or []), + **({ENDPOINT_MODELS_FIELD: dict(endpoint_models)} if endpoint_models else {}), **({"repair": repair} if repair else {}), } @@ -313,22 +327,16 @@ def effective_steward_executor_defaults( "machine_configuration.namespaces.steward_executor must be an object" ) normalized = normalize_steward_executor_machine_defaults(raw) - raw_model = normalized[MODEL_FIELD] - raw_effort = normalized[REASONING_EFFORT_FIELD] - raw_eligible = normalized.get(ELIGIBLE_ENDPOINTS_FIELD) + raw_model, raw_effort = normalized[MODEL_FIELD], normalized[REASONING_EFFORT_FIELD] + raw_eligible, raw_endpoint_models = normalized.get(ELIGIBLE_ENDPOINTS_FIELD), normalized.get(ENDPOINT_MODELS_FIELD) return _projection( - status="ready", - source="machine_configuration", - revision=machine_configuration_revision(normalized), + status="ready", source="machine_configuration", revision=machine_configuration_revision(normalized), executor_endpoint=str(normalized[EXECUTOR_ENDPOINT_FIELD]), model=raw_model if isinstance(raw_model, str) else None, reasoning_effort=raw_effort if isinstance(raw_effort, str) else None, - selection_policy=str( - normalized.get(SELECTION_POLICY_FIELD) or PREFERRED_SELECTION_POLICY - ), - eligible_endpoints=[str(item) for item in raw_eligible] - if isinstance(raw_eligible, list) - else [], + selection_policy=str(normalized.get(SELECTION_POLICY_FIELD) or PREFERRED_SELECTION_POLICY), + eligible_endpoints=[str(item) for item in raw_eligible] if isinstance(raw_eligible, list) else [], + endpoint_models=dict(raw_endpoint_models) if isinstance(raw_endpoint_models, dict) and raw_endpoint_models else None, ) diff --git a/loopx/chat/coordination.py b/loopx/chat/coordination.py index ec58cd8fa3..55b79e6e77 100644 --- a/loopx/chat/coordination.py +++ b/loopx/chat/coordination.py @@ -400,7 +400,15 @@ def prepare_turn_context(controller, adapter, session, turn_id, event_sink, *, s ) if execution_catalog["bindings"] or not execution_catalog["available"]: context["context_execution"] = execution_catalog - if isinstance(adapter, CodexAppServerAdapter): + from ..capabilities.native_chat.antigravity_adapter import AntigravityAdapter + current_turn = controller.store.load_turn(session_id, turn_id) or {} + antigravity_report = ( + not isinstance(adapter, CodexAppServerAdapter) + and isinstance(adapter, AntigravityAdapter) + and (current_turn.get("loopx_request") or {}).get("operation") == "native_turn" + and (current_turn.get("loopx_request") or {}).get("work_kind") == "report" + ) + if isinstance(adapter, CodexAppServerAdapter) or antigravity_report: from ..capabilities.manager_context.inspection import ManagerInspection, manager_index from ..chat_manager_context import manager_authorization_scope_is_current expected_scope_id = context.get("authorization_scope_id") @@ -438,19 +446,22 @@ def scope_valid() -> bool: session_id, turn_id, kind="manager.evidence_read", payload=result, ), ) - adapter.session.read_tool_handler = inspection.read - adapter._managed_read_turn_guard = None - if (session.get("managed_agent_id") and turn.get("origin") == "web" - and not turn.get("loopx_request") and not turn.get("loopx_execution") - and not session.get("loopx_tools") and not (session.get("loopx_mode") or {}).get("enabled") - and not adapter.session.execution_mode and not adapter.session.read_only_review - and getattr(adapter, "goal_driver", None) is None - and scope["kind"] == "owner_goal" and session.get("upstream_mode") == "chat"): - adapter.session.read_tool_handler = _GoalSessionCheckPreparation( - controller, adapter, session, turn_id, inspection.read) - adapter._managed_read_turn_guard = adapter.session.read_tool_handler._current - context["evidence_sources"] = inspection.sources() - context = manager_index(context, status_on_demand=status_on_demand) + if isinstance(adapter, CodexAppServerAdapter): + adapter.session.read_tool_handler = inspection.read + adapter._managed_read_turn_guard = None + if (session.get("managed_agent_id") and turn.get("origin") == "web" + and not turn.get("loopx_request") and not turn.get("loopx_execution") + and not session.get("loopx_tools") and not (session.get("loopx_mode") or {}).get("enabled") + and not adapter.session.execution_mode and not adapter.session.read_only_review + and getattr(adapter, "goal_driver", None) is None + and scope["kind"] == "owner_goal" and session.get("upstream_mode") == "chat"): + adapter.session.read_tool_handler = _GoalSessionCheckPreparation( + controller, adapter, session, turn_id, inspection.read) + adapter._managed_read_turn_guard = adapter.session.read_tool_handler._current + context["evidence_sources"] = inspection.sources() + context = manager_index(context, status_on_demand=status_on_demand) + else: + adapter._steward_report_reader = inspection.read from ..capabilities.native_chat.external_conversations import ChatExternalConversations recovery = ChatExternalConversations(controller).recovery_context( session, controller.store.load_turn(session_id, turn_id) or {}) if scope.get("bound_steward") else None diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py index 7185aedd8d..615baf76d7 100644 --- a/loopx/chat/session_open.py +++ b/loopx/chat/session_open.py @@ -853,7 +853,7 @@ def check_route_configuration() -> None: if ( defaults.get("status") != "ready" or defaults.get("selection_policy") != "flexible" - or defaults.get("executor_endpoint") != "antigravity" + or defaults.get("executor_endpoint") not in {"antigravity", "codex"} or set(defaults.get("eligible_endpoints") or []) != {"antigravity", "codex"} or defaults.get("configuration_revision") != allocation.get("configuration_revision") ): diff --git a/loopx/chat_manager.py b/loopx/chat_manager.py index eb25e82423..f6214b2e68 100644 --- a/loopx/chat_manager.py +++ b/loopx/chat_manager.py @@ -364,6 +364,32 @@ def _machine_default_text( return str(machine_defaults.get(field) or "").strip() +def _machine_default_endpoint_text( + machine_defaults: Mapping[str, Any] | None, + endpoint: str | None, + field: str, +) -> str: + """Return one machine-configured model or reasoning_effort for an endpoint.""" + + if not isinstance(machine_defaults, Mapping): + return "" + configured_endpoint = _machine_default_text(machine_defaults, "executor_endpoint") + if not endpoint or not configured_endpoint or endpoint == configured_endpoint: + primary_value = _machine_default_text(machine_defaults, f"executor_{field}") + if primary_value: + return primary_value + target = str(endpoint or configured_endpoint or "").strip() + if not target: + return "" + per_endpoint = machine_defaults.get("endpoint_models") + if not isinstance(per_endpoint, Mapping): + return "" + entry = per_endpoint.get(target) + if not isinstance(entry, Mapping): + return "" + return str(entry.get(field) or "").strip() + + def _resolve_manager_endpoint( environ: dict[str, str] | None = None, *, @@ -530,7 +556,6 @@ def manager_executor_allocation( environ, endpoint=endpoint, machine_defaults=defaults ) configured_endpoint = _machine_default_text(defaults, "executor_endpoint") - defaults_apply = not configured_endpoint or endpoint == configured_endpoint return normalize_manager_executor_allocation({ "schema_version": MANAGER_EXECUTOR_ALLOCATION_SCHEMA_VERSION, "selection_policy": policy, @@ -550,14 +575,10 @@ def manager_executor_allocation( "model_source": model_source, "reasoning_effort": model_config["reasoning_effort"], "configured_model": ( - _machine_default_text(defaults, "executor_model") or None - if defaults_apply - else None + _machine_default_endpoint_text(defaults, endpoint, "model") or None ), "configured_reasoning_effort": ( - _machine_default_text(defaults, "executor_reasoning_effort") or None - if defaults_apply - else None + _machine_default_endpoint_text(defaults, endpoint, "reasoning_effort") or None ), }) @@ -866,18 +887,17 @@ def manager_model_resolution( vendor default. A credential never picks a model. """ - configured = _machine_default_text(machine_defaults, "executor_model") - configured_endpoint = _machine_default_text( - machine_defaults, "executor_endpoint" + resolved_endpoint = ( + endpoint or _resolve_manager_endpoint(environ, machine_defaults=machine_defaults)[0] ) - if configured and (not endpoint or not configured_endpoint or endpoint == configured_endpoint): + configured = _machine_default_endpoint_text( + machine_defaults, resolved_endpoint, "model" + ) + if configured: return configured, MANAGER_MODEL_SOURCE_MACHINE_CONFIGURATION override = env_text(MANAGER_MODEL_ENV_VAR, environ) if override: return override, MANAGER_MODEL_SOURCE_ENV_OVERRIDE - resolved_endpoint = ( - endpoint or _resolve_manager_endpoint(environ, machine_defaults=machine_defaults)[0] - ) if MANAGER_ENDPOINT_KINDS.get(resolved_endpoint) == MANAGER_EXECUTOR_KIND_MANAGED: profile = managed_execution_profile(environ) return str(profile["model"]), MANAGER_MODEL_SOURCE_MANAGED_PROFILE @@ -949,9 +969,10 @@ def manager_session_quota_route(controller: Any, session: Mapping[str, Any]) -> """ defaults = steward_machine_defaults(controller) previous = session.get("manager_executor_allocation") or {} + primary = _machine_default_text(defaults, "executor_endpoint") if (not defaults or defaults.get("status") != "ready" or _manager_selection_policy(defaults) != FLEXIBLE_SELECTION_POLICY - or _machine_default_text(defaults, "executor_endpoint") != "antigravity" + or primary not in {"antigravity", "codex"} or set(_manager_eligible_endpoints(defaults)) != {"antigravity", "codex"} or previous.get("allocation_reason") == MANAGER_ALLOCATION_REASON_USER_EXPLICIT or session.get("requested_agent_model_id") or session.get("requested_agent_reasoning_effort") @@ -960,37 +981,56 @@ def manager_session_quota_route(controller: Any, session: Mapping[str, Any]) -> native = session if session.get("agent_id") == "antigravity" else next((row for row in reversed(session.get("upstream_context_history") or []) if row.get("agent_id") == "antigravity"), None) try: - from .capabilities.native_chat.antigravity_adapter import AntigravityAdapter, ANTIGRAVITY_DEFAULT_MODEL + from .capabilities.native_chat.antigravity_adapter import ( + ANTIGRAVITY_DEFAULT_MODEL, + AntigravityAdapter, + ) from loopx_codex_provider_routing.native import NativeAccounts environment = dict(operator_credential_resolution(controller)["environ"]) - codex_environment = {key: value for key, value in environment.items() + clean_environment = {key: value for key, value in environment.items() if key not in (MANAGER_MODEL_ENV_VAR, MANAGER_REASONING_EFFORT_ENV_VAR)} accounts = NativeAccounts(controller.coordination_runtime_root) - route_inputs = dict(codex_home=controller.codex_home, primary="antigravity", + route_inputs = dict(codex_home=controller.codex_home, primary=primary, pool=_manager_eligible_endpoints(defaults), current=str(session["agent_id"]), blocked_primary=session.get("manager_quota_block")) if callable(getattr(accounts, "model_transport", None)): - route_inputs["model"] = manager_model_resolution(codex_environment, endpoint="codex", machine_defaults=defaults)[0] + route_inputs["model"] = manager_model_resolution(clean_environment, endpoint="codex", machine_defaults=defaults)[0] capacity = None - # Explicit API primary does not depend on an unrelated subscription - # transport being up. The same owner holds when that role is absent. - route = accounts.steward_route(**route_inputs, primary_capacity=None) - if route.get("endpoint") is None and native: - capacity = AntigravityAdapter.metadata_review_capacity( - cascade_id=str(native.get("upstream_thread_id") or native.get("thread_id")), - model_id=str(native.get("agent_model_id") or ANTIGRAVITY_DEFAULT_MODEL)) - route = accounts.steward_route(**route_inputs, primary_capacity=capacity) + if primary == "antigravity": + # Explicit API primary does not depend on an unrelated subscription + # transport being up. The same owner holds when that role is absent. + route = accounts.steward_route(**route_inputs, primary_capacity=None) + if route.get("endpoint") is None and native: + capacity = AntigravityAdapter.metadata_review_capacity( + cascade_id=str(native.get("upstream_thread_id") or native.get("thread_id")), + model_id=str(native.get("agent_model_id") or ANTIGRAVITY_DEFAULT_MODEL)) + route = accounts.steward_route(**route_inputs, primary_capacity=capacity) + else: + route = accounts.steward_route(**route_inputs, primary_capacity=None, fallback_capacity=None) + if route.get("endpoint") is None: + target_ag_model = manager_model_resolution( + clean_environment, endpoint="antigravity", machine_defaults=defaults, + )[0] + capacity = AntigravityAdapter.endpoint_model_capacity(model_id=target_ag_model) + if capacity is not None: + route = accounts.steward_route( + **route_inputs, primary_capacity=None, fallback_capacity=capacity, + ) endpoint = route.get("endpoint") if endpoint is None: return None capabilities = controller.capabilities() if not any(row.get("agent_id") == endpoint and row.get("available") is True for row in capabilities): return None - if endpoint != "antigravity": - environment.pop("LOOPX_MANAGER_MODEL", None) - environment.pop("LOOPX_MANAGER_REASONING_EFFORT", None) - allocation = manager_executor_allocation(controller, machine_defaults=defaults, environ=environment, - endpoint_capabilities=[{**row, "available": row.get("agent_id") == endpoint} for row in capabilities]) + if endpoint != primary: + environment.pop(MANAGER_MODEL_ENV_VAR, None) + environment.pop(MANAGER_REASONING_EFFORT_ENV_VAR, None) + allocation = manager_executor_allocation( + controller, + machine_defaults=defaults, + environ=environment, + endpoint_capabilities=[{**row, "available": row.get("agent_id") == endpoint} for row in capabilities], + ) return {"allocation": allocation, "blocked_primary": route.get("blocked_primary"), "observed_at": capacity["observed_at"] if capacity else time.time()} except Exception as exc: @@ -1018,8 +1058,8 @@ def manager_session_model_allocation( if (session.get("goal_id") != MANAGER_AGENT_GOAL_ID or defaults is None or defaults.get("status") != "ready" or _machine_default_text(defaults, "executor_endpoint") != endpoint - or not any(_machine_default_text(defaults, name) for name in - ("executor_model", "executor_reasoning_effort"))): + or not any(_machine_default_endpoint_text(defaults, str(endpoint), name) for name in + ("model", "reasoning_effort"))): return None proposed = manager_executor_allocation(controller, endpoint, machine_defaults=defaults, environ=operator_credential_resolution(controller)["environ"]) @@ -1153,18 +1193,18 @@ def manager_model_config( environ, machine_defaults=machine_defaults )[0] model, _source = manager_model_resolution( - environ, endpoint=endpoint, machine_defaults=machine_defaults - ) - configured_endpoint = _machine_default_text( - machine_defaults, "executor_endpoint" + environ, + endpoint=endpoint, + machine_defaults=machine_defaults, ) - effort = ( - _machine_default_text(machine_defaults, "executor_reasoning_effort") - if not configured_endpoint or endpoint == configured_endpoint - else "" + effort = _machine_default_endpoint_text( + machine_defaults, endpoint, "reasoning_effort" ) if not effort: effort = env_text(MANAGER_REASONING_EFFORT_ENV_VAR, environ) + if not effort and endpoint == "antigravity": + tier = model.rsplit("-", 1)[-1] + effort = tier if tier in {"low", "medium", "high"} else "high" if not effort and MANAGER_ENDPOINT_KINDS.get(endpoint) == MANAGER_EXECUTOR_KIND_MANAGED: effort = str(managed_execution_profile(environ)["reasoning_effort"]) effort = effort or MANAGER_REASONING_EFFORT_DEFAULT diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index 29e1ce9f2f..0be9917d82 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -952,6 +952,10 @@ def event_sink(kind: str, payload: dict[str, Any]) -> None: if conversation_scope(session)["kind"] == "owner_goal" else None ) + else: + from .capabilities.native_chat.antigravity_adapter import AntigravityAdapter + if isinstance(adapter, AntigravityAdapter): + adapter._steward_report_reader = None native_command = None if current_turn.get("origin") == "peer" else parse_native_goal_command(message) if native_command is not None: validate_goal_chat(session, attachments) diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 64fff16914..bf61f54424 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -523,7 +523,7 @@ def update_session(self, session_id: str, *, expected_statuses: set[str] | None and str(active.get("client_turn_id")).endswith( "-metadata-1" if metadata_review else "-review-1" if answer_review_admission else "-quota-1"))) or allocation["selection_policy"] != "flexible" - or allocation["configured_endpoint"] != "antigravity" + or allocation["configured_endpoint"] not in {"antigravity", "codex"} or set(allocation["eligible_endpoints"]) != {"antigravity", "codex"} or endpoint not in {"antigravity", "codex"} or endpoint == payload.get("agent_id") or changes.get("executor_endpoint_id") != endpoint or allocation["executor_endpoint"] != endpoint diff --git a/loopx/control_plane/collaboration/conversation_scope.ts b/loopx/control_plane/collaboration/conversation_scope.ts index eb2718afa3..f49892744d 100644 --- a/loopx/control_plane/collaboration/conversation_scope.ts +++ b/loopx/control_plane/collaboration/conversation_scope.ts @@ -220,15 +220,18 @@ export function resolveConversationScope(input: Record): Conver export function boundConversationExecutorMatches(row: Record, session: Record): boolean { if (session.agent_id === row.executor_endpoint_id && session.executor_endpoint_id === row.executor_endpoint_id) return true; const allocation = session.manager_executor_allocation as Record | undefined; + const configured = row.executor_endpoint_id; + if (configured !== "antigravity" && configured !== "codex") return false; + const fallback = configured === "antigravity" ? "codex" : "antigravity"; return row.context_kind === "steward" && row.audience !== "group" - && row.executor_endpoint_id === "antigravity" && session.agent_id === "codex" - && session.executor_endpoint_id === "codex" && allocation?.schema_version === "manager_executor_allocation_v0" - && allocation.selection_policy === "flexible" && allocation.configured_endpoint === "antigravity" - && allocation.executor_endpoint === "codex" && allocation.allocation_reason === "flexible_availability_fallback" + && session.agent_id === fallback && session.executor_endpoint_id === fallback + && allocation?.schema_version === "manager_executor_allocation_v0" + && allocation.selection_policy === "flexible" && allocation.configured_endpoint === configured + && allocation.executor_endpoint === fallback && allocation.allocation_reason === "flexible_availability_fallback" && typeof allocation.configuration_revision === "string" && allocation.configuration_revision.length > 0 && Array.isArray(allocation.eligible_endpoints) && allocation.eligible_endpoints.length === 2 && allocation.eligible_endpoints.includes("antigravity") && allocation.eligible_endpoints.includes("codex") && Array.isArray(session.upstream_context_history) && session.upstream_context_history.some(value => - value && typeof value === "object" && !Array.isArray(value) && (value as Record).agent_id === "antigravity" + value && typeof value === "object" && !Array.isArray(value) && (value as Record).agent_id === configured && typeof (value as Record).thread_id === "string"); } diff --git a/loopx/control_plane/collaboration/steward_managed_mode.ts b/loopx/control_plane/collaboration/steward_managed_mode.ts index 05ad062b08..e5132094bc 100644 --- a/loopx/control_plane/collaboration/steward_managed_mode.ts +++ b/loopx/control_plane/collaboration/steward_managed_mode.ts @@ -464,8 +464,10 @@ export function normalizeStewardManagedActor(value: unknown): JsonObject { export function observeStewardNativeExecutor(params: JsonObject): JsonObject { const binding = requireJsonObject(params.binding, "steward binding"); const session = requireJsonObject(params.session, "original steward Session"); - const supported = session.agent_id === "codex" && (binding.executor_endpoint_id === "codex" - || boundConversationExecutorMatches(binding, session)); + const supported = (session.agent_id === "codex" && (binding.executor_endpoint_id === "codex" + || boundConversationExecutorMatches(binding, session))) + || (binding.executor_endpoint_id === "codex" && session.agent_id === "antigravity" + && boundConversationExecutorMatches(binding, session)); return {execution_available: supported, ...(!supported ? {execution_error_code: "unsupported_executor"} : {})}; } diff --git a/packages/loopx-codex-provider-routing/pyproject.toml b/packages/loopx-codex-provider-routing/pyproject.toml index 6f6a7fbcdd..fda176a2ba 100644 --- a/packages/loopx-codex-provider-routing/pyproject.toml +++ b/packages/loopx-codex-provider-routing/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "loopx-codex-provider-routing" -version = "0.15.8" +version = "0.15.9" description = "Native Codex account slots and exhausted-account handoff for LoopX" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native.py b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native.py index 44355291c4..942178cfdb 100644 --- a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native.py +++ b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native.py @@ -246,25 +246,31 @@ def conversation_epoch(self, *, codex_home: Path, consumer: str = "worker", mode return (revision, slot) if isinstance(revision, str) and revision and isinstance(slot, str) and slot else None def steward_route(self, *, codex_home: Path, primary: str, pool: list[str], current: str, - primary_capacity: dict | None, blocked_primary: dict | None = None, model: str | None = None) -> dict: + primary_capacity: dict | None, fallback_capacity: dict | None = None, + blocked_primary: dict | None = None, model: str | None = None) -> dict: """Observe the existing account owner; never start a second watcher.""" state = self._load() adapter = state.get("adapter") if adapter and Path(adapter.get("profile", {}).get("home", "")).resolve() != codex_home.resolve(): return {"endpoint": None, "blocked_primary": blocked_primary} - api_ready = bool(self.api_keys().candidates(model or "")) if state["policy"].get("steward_api_role") == "primary" else False - if api_ready: + policy_cfg = state.get("policy") or {} + role = policy_cfg.get("steward_api_role") + api_enabled = role == "primary" or (role != "disabled" and policy_cfg.get("api_fallback") is True) + api_ready = bool(self.api_keys().candidates(model or "")) if api_enabled else False + if role == "primary" and api_ready: return policy({"operation": "steward-route", "now": self.clock(), "primary": primary, "pool": pool, "current": current, "native": self._projection(state), "api_ready": True, - "primary_capacity": primary_capacity, "blocked_primary": blocked_primary}) - if primary_capacity is None: + "primary_capacity": primary_capacity, "fallback_capacity": fallback_capacity, + "blocked_primary": blocked_primary}) + if primary == "antigravity" and primary_capacity is None: return {"endpoint": None, "blocked_primary": blocked_primary} - if state["policy"].get("enabled") is not True or not adapter: + if policy_cfg.get("enabled") is not True or not adapter: return {"endpoint": None, "blocked_primary": blocked_primary} native = self.transport(adapter, "status") return policy({"operation": "steward-route", "now": self.clock(), "primary": primary, "pool": pool, "current": current, - "native": self._projection(state, native), "primary_capacity": primary_capacity, + "native": self._projection(state, native), "api_ready": api_ready, + "primary_capacity": primary_capacity, "fallback_capacity": fallback_capacity, "blocked_primary": blocked_primary}) def model_transport(self, *, codex_home: Path, consumer: str, model: str | None = None) -> dict | None: diff --git a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_policy.ts b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_policy.ts index b15a8bbdd3..1460f60cb9 100644 --- a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_policy.ts +++ b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_policy.ts @@ -48,12 +48,13 @@ export function modelRoute(input: {consumer: string; native: Record export function stewardRoute(input: { now: number; primary: string; pool: string[]; current: string; native: Record; primary_capacity: Record | null; + fallback_capacity?: Record | null; blocked_primary?: Record | null; api_ready?: boolean; }) { const no = {endpoint: null, blocked_primary: input.blocked_primary ?? null}; if (!Number.isFinite(input.now) || !["antigravity", "codex"].includes(input.current) - || input.primary !== "antigravity" || !Array.isArray(input.pool) + || !["antigravity", "codex"].includes(input.primary) || !Array.isArray(input.pool) || input.pool.length !== 2 || new Set(input.pool).size !== 2 || !input.pool.includes("antigravity") || !input.pool.includes("codex")) return no; const validCapacity = (row: Record | null | undefined) => row @@ -65,32 +66,64 @@ export function stewardRoute(input: { && typeof row.quota_exhausted === "boolean" && typeof row.normal_completion === "boolean" && row.quota_exhausted !== row.normal_completion; if (input.blocked_primary != null && !validCapacity(input.blocked_primary)) return no; - if (modelRoute({consumer: "steward", native: input.native, api_ready: input.api_ready === true}).api - && apiRole(input.native.policy, "steward") === "primary") return {endpoint: "codex", blocked_primary: input.blocked_primary ?? null}; - const capacity = input.primary_capacity; - if (!validCapacity(capacity) || !capacity || input.now < capacity.observed_at - || input.now - capacity.observed_at > 120) return no; - let blocked = input.blocked_primary ?? null; - if (capacity.quota_exhausted && (!blocked || blocked.execution_id !== capacity.execution_id)) blocked = capacity; - const restored = blocked && (blocked.account_ref !== capacity.account_ref - || blocked.model_id !== capacity.model_id || blocked.reset_time !== capacity.reset_time - || input.now >= Date.parse(blocked.reset_time) / 1000); - if (capacity.remaining_fraction > 0 && (!blocked || restored) && (!capacity.quota_exhausted || restored)) { - return {endpoint: "antigravity", blocked_primary: blocked}; - } const native = input.native; - // API connection/model-list checks do not prove generation allowance. An - // already active, explicitly authorized API route remains the native owner's - // selection; its pre-output key failover retains that owner's own guards. + const role = apiRole(native.policy, "steward"); + const codexApiPrimary = modelRoute({consumer: "steward", native, api_ready: input.api_ready === true}).api && role === "primary"; const current = Array.isArray(native.accounts) ? native.accounts.find((a: any) => a.slot === native.active_slot) : null; const fresh = current && Number.isFinite(current.observed_at) && current.observed_at <= input.now && input.now - current.observed_at <= 120; - const usable = native.policy?.enabled === true && native.login_matches === true + // API connection/model-list checks do not prove generation allowance. An + // already active, explicitly authorized API route remains the native owner's + // selection; its pre-output key failover retains that owner's own guards. + const codexUsable = codexApiPrimary || (native.policy?.enabled === true && native.login_matches === true && native.recovery_required === false && (native.api_active === true ? modelRoute({consumer: "steward", native, api_ready: input.api_ready === true}).api - : native.action === "ready" && fresh && current.availability === "available"); - return {endpoint: usable ? "codex" : null, blocked_primary: blocked}; + : native.action === "ready" && fresh && current.availability === "available")); + + if (input.primary === "antigravity") { + if (codexApiPrimary) return {endpoint: "codex", blocked_primary: input.blocked_primary ?? null}; + const capacity = input.primary_capacity; + if (!validCapacity(capacity) || !capacity || input.now < capacity.observed_at + || input.now - capacity.observed_at > 120) return no; + let blocked = input.blocked_primary ?? null; + if (capacity.quota_exhausted && (!blocked || blocked.execution_id !== capacity.execution_id)) blocked = capacity; + const restored = blocked && (blocked.account_ref !== capacity.account_ref + || blocked.model_id !== capacity.model_id || blocked.reset_time !== capacity.reset_time + || input.now >= Date.parse(blocked.reset_time) / 1000); + if (capacity.remaining_fraction > 0 && (!blocked || restored) && (!capacity.quota_exhausted || restored)) { + return {endpoint: "antigravity", blocked_primary: blocked}; + } + return {endpoint: codexUsable ? "codex" : null, blocked_primary: blocked}; + } + + if (codexUsable) return {endpoint: "codex", blocked_primary: input.blocked_primary ?? null}; + const slots: unknown[] = Array.isArray(native.policy?.slots) ? native.policy.slots : []; + const accountsBySlot = new Map( + Array.isArray(native.accounts) ? native.accounts.map((a: any) => [a?.slot, a]) : [], + ); + const allSlotsExhausted = slots.length > 0 && native.policy?.enabled === true + && native.login_matches === true && native.recovery_required === false + && slots.every(slot => { + const a = accountsBySlot.get(slot); + return a && a.availability === "exhausted" + && ((Number.isFinite(a.observed_at) && a.observed_at <= input.now && input.now - a.observed_at <= 120) + || (Number.isFinite(a.reset_at) && a.reset_at > input.now)); + }); + const apiFallback = role === "fallback" || native.policy?.api_fallback === true; + if (!allSlotsExhausted || (apiFallback && input.api_ready === true)) return no; + const fallback = input.fallback_capacity; + if (!validCapacity(fallback) || !fallback || fallback.observed_at > input.now + || input.now - fallback.observed_at > 120) return no; + const blocked = input.blocked_primary ?? null; + const unblockedFallback = !blocked || blocked.account_ref !== fallback.account_ref + || blocked.model_id !== fallback.model_id || blocked.reset_time !== fallback.reset_time + || input.now >= Date.parse(blocked.reset_time) / 1000; + if (fallback.remaining_fraction > 0 && !fallback.quota_exhausted + && fallback.normal_completion === true && unblockedFallback) { + return {endpoint: "antigravity", blocked_primary: blocked}; + } + return no; } /** Diagnostic liveness only; this never grants switching or process authority. */ diff --git a/packages/loopx-codex-provider-routing/tests/steward_route.test.ts b/packages/loopx-codex-provider-routing/tests/steward_route.test.ts index 87d9d53e6a..58e6830557 100644 --- a/packages/loopx-codex-provider-routing/tests/steward_route.test.ts +++ b/packages/loopx-codex-provider-routing/tests/steward_route.test.ts @@ -56,3 +56,35 @@ test("invalid retained epochs and ambiguous observations stay unselected", () => assert.equal(stewardRoute({...input, native: {...input.native, api_active: true, action: "api_active", policy: {...input.native.policy, api_fallback: false}}}).endpoint, null); }); + +test("codex primary fails over to antigravity only when all codex slots are exhausted and restores when ready", () => { + const futureReset = now + 3600; + const agCapacity = {observed_at: now, account_ref: "b".repeat(64), model_id: "gemini-4-carbon-high", + execution_id: "endpoint-probe:ok", remaining_fraction: 0.9, reset_time: "2026-01-02T00:00:00Z", + quota_exhausted: false, normal_completion: true}; + const exhausted = { + now, primary: "codex", pool: ["codex", "antigravity"], current: "codex", + primary_capacity: null, fallback_capacity: agCapacity, api_ready: false, + native: { + policy: {enabled: true, slots: ["slot-a", "slot-b"], api_fallback: true}, + active_slot: "slot-a", action: "selection_changed", login_matches: true, recovery_required: false, + accounts: [ + {slot: "slot-a", observed_at: now - 600, availability: "exhausted", reset_at: futureReset}, + {slot: "slot-b", observed_at: now - 600, availability: "exhausted", reset_at: futureReset}, + ], + }, + }; + assert.equal(stewardRoute(exhausted).endpoint, "antigravity"); + assert.equal(stewardRoute({...exhausted, api_ready: true}).endpoint, null); + assert.equal(stewardRoute({...exhausted, native: {...exhausted.native, recovery_required: true}}).endpoint, null); + assert.equal(stewardRoute({...exhausted, fallback_capacity: {...agCapacity, quota_exhausted: true, normal_completion: false, remaining_fraction: 0}}).endpoint, null); + assert.equal(stewardRoute({ + ...exhausted, + current: "antigravity", + native: { + ...exhausted.native, + action: "ready", + accounts: [{slot: "slot-a", observed_at: now, availability: "available"}, exhausted.native.accounts[1]], + }, + }).endpoint, "codex"); +}); diff --git a/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py b/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py index e7d1a269c7..e8448247b3 100644 --- a/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py +++ b/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py @@ -45,3 +45,65 @@ def transport(adapter, operation): state["action"] = "handoff_interrupted" atomic(owner.path, state) assert owner.conversation_epoch(codex_home=home) is None + + +def test_codex_primary_steward_route_switches_to_antigravity_fallback_when_exhausted(tmp_path): + now = 1767225600 + home = tmp_path / "codex-home" + native = { + "active_slot": "slot-a", + "selection_revision": "revision-a", + "current_login_matches": True, + "recovery_required": False, + "action": "selection_changed", + } + owner = NativeAccounts( + tmp_path / "runtime", + transport=lambda _adapter, _op: native, + clock=lambda: now, + ) + owner.root.mkdir(parents=True) + state = owner._load() + state.update( + policy={"enabled": True, "slots": ["slot-a", "slot-b"], "api_fallback": False}, + adapter={"profile": {"home": str(home)}}, + action="selection_changed", + accounts=[ + {"slot": "slot-a", "availability": "exhausted", "observed_at": now - 600, "reset_at": now + 3600}, + {"slot": "slot-b", "availability": "exhausted", "observed_at": now - 600, "reset_at": now + 3600}, + ], + ) + atomic(owner.path, state) + fallback = { + "observed_at": now, + "account_ref": "b" * 64, + "model_id": "gemini-4-carbon-high", + "execution_id": "endpoint-probe:ok", + "remaining_fraction": 0.99, + "reset_time": "2026-01-02T00:00:00Z", + "quota_exhausted": False, + "normal_completion": True, + } + assert owner.steward_route( + codex_home=home, + primary="codex", + pool=["codex", "antigravity"], + current="codex", + primary_capacity=None, + fallback_capacity=fallback, + model="gpt-6.2-sol", + )["endpoint"] == "antigravity" + state.update(action="ready", accounts=[ + {"slot": "slot-a", "availability": "available", "observed_at": now}, + state["accounts"][1], + ]) + atomic(owner.path, state) + assert owner.steward_route( + codex_home=home, + primary="codex", + pool=["codex", "antigravity"], + current="antigravity", + primary_capacity=None, + fallback_capacity=fallback, + model="gpt-6.2-sol", + )["endpoint"] == "codex" diff --git a/tests/capabilities/test_steward_executor_machine_defaults.py b/tests/capabilities/test_steward_executor_machine_defaults.py index 2c12817d8d..ca01868214 100644 --- a/tests/capabilities/test_steward_executor_machine_defaults.py +++ b/tests/capabilities/test_steward_executor_machine_defaults.py @@ -351,3 +351,41 @@ def test_restored_executor_model_ignores_partial_pre_v0_and_validates_v0() -> No } ) == {"model": "legacy-model"} assert restored_executor_model({"loopx_tools": False, "loopx_executor": {"model": "x"}}) is None + + +def test_flexible_endpoint_models_normalize_validate_and_project() -> None: + base = { + "schema_version": "steward_executor_machine_defaults_v1", + "selection_policy": "flexible", + "executor_endpoint": "codex", + "eligible_endpoints": ["codex", "antigravity"], + "executor_model": "gpt-6.2-sol", + "executor_reasoning_effort": "xhigh", + } + normalized = normalize_steward_executor_machine_defaults({ + **base, + "endpoint_models": { + "antigravity": {"model": "gemini-4-carbon-high", "reasoning_effort": "high"}, + "codex": {"model": None, "reasoning_effort": None}, + }, + }) + assert normalized["endpoint_models"] == { + "antigravity": {"model": "gemini-4-carbon-high", "reasoning_effort": "high"}, + } + effective = effective_steward_executor_defaults(_document({"steward_executor": normalized})) + assert effective["endpoint_models"] == { + "antigravity": {"model": "gemini-4-carbon-high", "reasoning_effort": "high"}, + } + without = effective_steward_executor_defaults(_document({"steward_executor": { + **base, + "endpoint_models": {"antigravity": {"model": "", "reasoning_effort": None}}, + }})) + assert "endpoint_models" not in without + for bad in [ + {"endpoint_models": "bad"}, + {"endpoint_models": {"dhs": {"model": "x"}}}, + {"endpoint_models": {"antigravity": {"unknown": "x"}}}, + {"endpoint_models": {"antigravity": {"reasoning_effort": "maximum"}}}, + ]: + with pytest.raises((TypeError, ValueError)): + normalize_steward_executor_machine_defaults({**base, **bad}) diff --git a/tests/control_plane_ts/conversation_scope.test.ts b/tests/control_plane_ts/conversation_scope.test.ts index 3683040fe6..5cc9d99365 100644 --- a/tests/control_plane_ts/conversation_scope.test.ts +++ b/tests/control_plane_ts/conversation_scope.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import {resolveConversationScope, projectConversationIdentity, stewardConversationIdentity} from "../../loopx/control_plane/collaboration/conversation_scope.ts"; +import {boundConversationExecutorMatches, resolveConversationScope, projectConversationIdentity, stewardConversationIdentity} from "../../loopx/control_plane/collaboration/conversation_scope.ts"; test("result review narrows runtime effects without rewriting the original grant or native store", () => { const context = {kind: "project_workspace", project_ref: "a".repeat(24), workspace_path: "/synthetic/project", @@ -98,3 +98,30 @@ test("steward metadata formatting keeps the original audience with no execution assert.equal(review.host_config.permissions.loopx_workspace_only_read.network.enabled, false); assert.throws(() => stewardConversationIdentity({context: {...context, audience: "bound_group"}, metadata_review: true})); }); + +test("boundConversationExecutorMatches validates bidirectional flexible fallback", () => { + const row = {context_kind: "steward", audience: "owner", executor_endpoint_id: "codex"}; + const allocation = { + schema_version: "manager_executor_allocation_v0", + selection_policy: "flexible", + configured_endpoint: "codex", + executor_endpoint: "antigravity", + allocation_reason: "flexible_availability_fallback", + configuration_revision: "rev-1", + eligible_endpoints: ["codex", "antigravity"], + }; + const valid = { + agent_id: "antigravity", + executor_endpoint_id: "antigravity", + manager_executor_allocation: allocation, + upstream_context_history: [{agent_id: "codex", thread_id: "orig-codex-thread"}], + }; + assert.equal(boundConversationExecutorMatches(row, valid), true); + assert.equal(boundConversationExecutorMatches(row, {...valid, upstream_context_history: []}), false); + assert.equal(boundConversationExecutorMatches(row, { + ...valid, + manager_executor_allocation: {...allocation, allocation_reason: "configured_preference"}, + }), false); + assert.equal(boundConversationExecutorMatches({...row, audience: "group"}, valid), false); + assert.equal(boundConversationExecutorMatches(row, {...valid, executor_endpoint_id: "codex"}), false); +}); diff --git a/tests/control_plane_ts/steward_managed_mode.test.ts b/tests/control_plane_ts/steward_managed_mode.test.ts index 2ee64fe2a8..bab62ebfb9 100644 --- a/tests/control_plane_ts/steward_managed_mode.test.ts +++ b/tests/control_plane_ts/steward_managed_mode.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import {admitStewardManagedTurn, bindStewardManagedActor, planStewardManagedMode, +import {admitStewardManagedTurn, bindStewardManagedActor, observeStewardNativeExecutor, planStewardManagedMode, planStewardMonitor, observeStewardPortfolio, observeStewardSignalMonitor} from "../../loopx/control_plane/collaboration/steward_managed_mode.ts"; import {planConversationBinding} from "../../loopx/control_plane/collaboration/conversation_binding.ts"; @@ -325,3 +325,39 @@ test("custom steward signal monitors admit model-free probes while excluding loc assert.equal(unavailable.material_change, false); assert.equal(unavailable.result_hash, first.result_hash); }); + +test("observeStewardNativeExecutor admits qualified codex-to-antigravity fallback while rejecting unallocated antigravity", () => { + const {params} = fixture(); + assert.equal(observeStewardNativeExecutor(params).execution_available, true); + const pureAntigravity = { + binding: {...params.binding, executor_endpoint_id: "antigravity"}, + session: {...params.session, agent_id: "antigravity", executor_endpoint_id: "antigravity"}, + }; + assert.deepEqual(observeStewardNativeExecutor(pureAntigravity), { + execution_available: false, + execution_error_code: "unsupported_executor", + }); + const qualifiedFallback = { + binding: params.binding, + session: { + ...params.session, + agent_id: "antigravity", + executor_endpoint_id: "antigravity", + upstream_context_history: [{agent_id: "codex", thread_id: params.session.upstream_thread_id}], + manager_executor_allocation: { + schema_version: "manager_executor_allocation_v0", + selection_policy: "flexible", + configured_endpoint: "codex", + executor_endpoint: "antigravity", + allocation_reason: "flexible_availability_fallback", + configuration_revision: "rev-1", + eligible_endpoints: ["codex", "antigravity"], + }, + }, + }; + assert.equal(observeStewardNativeExecutor(qualifiedFallback).execution_available, true); + assert.equal(observeStewardNativeExecutor({ + ...qualifiedFallback, + session: {...qualifiedFallback.session, upstream_context_history: []}, + }).execution_available, false); +}); diff --git a/tests/test_antigravity_steward_adapter.py b/tests/test_antigravity_steward_adapter.py index ffb9c81a8e..c9623fb339 100644 --- a/tests/test_antigravity_steward_adapter.py +++ b/tests/test_antigravity_steward_adapter.py @@ -1,4 +1,4 @@ -"""Focused tests for Antigravity (Gemini 4 Argon) Steward & Chat adapter.""" +"""Focused tests for the Antigravity Steward & Chat adapter.""" from __future__ import annotations @@ -122,14 +122,15 @@ def do_POST(self): self.end_headers() return if method == "GetCascadeModelConfigData": - response = {"clientModelConfigs": [ + response = {"clientModelConfigs": state.get("model_configs", [ {"modelId": f"gemini-4-argon-{tier}", "modelOrAlias": {"model": f"MODEL_PLACEHOLDER_M{number}"}} - for tier, number in (("high", 417), ("medium", 418), ("low", 419))]} + for tier, number in (("high", 417), ("medium", 418), ("low", 419))])} elif method == "GetUserStatus": from datetime import timedelta reset = state.setdefault("quota_reset", (datetime.now(timezone.utc) + timedelta(days=7)).isoformat()) - response = {"userStatus": {"email": state.get("quota_account", "synthetic@invalid.example"), + response = state["user_status_response"] if "user_status_response" in state else { + "userStatus": {"email": state.get("quota_account", "synthetic@invalid.example"), "cascadeModelConfigData": {"clientModelConfigs": [{ "modelId": "gemini-4-argon-high", "quotaInfo": { "remainingFraction": state.get("quota_fraction", 1), "resetTime": reset}}]}}} @@ -779,6 +780,115 @@ def test_canonical_model_and_effort_readback_agree(tmp_path, language_server): assert observed_model_settings(adapter, "low", "argon")["agent_reasoning_effort"] == "low" +@pytest.mark.parametrize("effort,placeholder", [ + ("high", "MODEL_PLACEHOLDER_M427"), + ("medium", "MODEL_PLACEHOLDER_M437"), + ("low", "MODEL_PLACEHOLDER_M438"), +]) +def test_carbon_native_request_and_same_conversation_resume(tmp_path, language_server, effort, placeholder): + from loopx.capabilities.native_chat.model_settings import observed_model_settings + + model = f"gemini-4-carbon-{effort}" + language_server["model_configs"] = [{"modelId": model, "modelOrAlias": {"model": placeholder}}] + adapter = adapter_for(tmp_path, executor_model={"model": "carbon", "reasoning_effort": effort}) + assert adapter.current_model_id == model + assert observed_model_settings(adapter, effort, "carbon")["agent_reasoning_effort"] == effort + adapter.start_turn("Synthetic Carbon request") + adapter.close_session() + resumed = adapter_for(tmp_path, resume_thread_id="synthetic-cascade", + executor_model={"model": model, "reasoning_effort": effort}) + resumed.start_turn("Continue the same synthetic conversation") + sends = [body for method, body in language_server["calls"] if method == "SendUserCascadeMessage"] + assert len(sends) == 2 + for body in sends: + assert body["cascadeId"] == "synthetic-cascade" + planner = body["cascadeConfig"]["plannerConfig"] + assert planner["planModel"] == placeholder + assert planner["requestedModel"] == {"model": placeholder} + assert planner["toolConfig"]["forceDisableToolCalling"] is True + assert sum(method == "StartCascade" for method, _ in language_server["calls"]) == 1 + + +@pytest.mark.parametrize("configs", [[], [ + {"modelId": "another-model", "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}}, +], [{"modelId": "gemini-4-carbon-high", "modelOrAlias": "malformed"}]]) +def test_carbon_not_offered_by_account_cannot_create_or_resume(tmp_path, language_server, configs): + from loopx.chat_agent import CodexChatAgentError + + language_server["model_configs"] = configs + with pytest.raises(CodexChatAgentError, match="did not offer"): + adapter_for(tmp_path, resume_thread_id="original", + executor_model={"model": "gemini-4-carbon-high", "reasoning_effort": "high"}) + assert {method for method, _ in language_server["calls"]} == {"GetCascadeModelConfigData"} + + +@pytest.mark.parametrize("model,effort", [("carbon", "xhigh"), ("gemini-4-carbon-high", "low"), + ("gemini-4-carbon-unknown", None)]) +def test_invalid_carbon_selection_is_rejected_before_native_reads(tmp_path, language_server, model, effort): + from loopx.chat_agent import CodexChatAgentError + + with pytest.raises(CodexChatAgentError) as error: + adapter_for(tmp_path, executor_model={"model": model, "reasoning_effort": effort}) + assert error.value.error_code == "unsupported_configuration" + assert language_server["calls"] == [] + + +def test_model_discovery_http_reads_account_choices_without_execution_and_can_recover( + tmp_path, language_server, monkeypatch, +): + import http.client + from loopx.chat_runtime import ChatRuntimeController + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + from loopx.chat_store import ChatSessionStore + + store = ChatSessionStore(tmp_path / "runtime") + runtime = ChatRuntimeController(store=store, codex_bin="unused") + monkeypatch.setattr(runtime, "capabilities", lambda: [{"agent_id": "antigravity", "available": True}]) + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.verbose = False + server.chat_store, server.runtime_controller = store, runtime + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + def read(): + connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5) + try: + connection.request("POST", "/api/chat/agent-model-options", body=json.dumps({"agent_id": "antigravity"}), + headers={"Content-Type": "application/json", + "Origin": f"http://127.0.0.1:{server.server_port}"}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + try: + status, argon = read() + assert status == 200, argon + assert [row["value"] for row in argon["model"]["options"]] == [ + "gemini-4-argon-high", "gemini-4-argon-medium", "gemini-4-argon-low"] + assert argon["model"]["selected"] == "gemini-4-argon-high" + language_server["model_configs"] = [] + status, failed = read() + assert status == 424 and failed["error_code"] == "unsupported_configuration" + language_server["model_configs"] = [ + {"modelId": "gemini-4-carbon-medium", "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M437"}}, + {"modelId": "unknown-model", "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M999"}}, + ] + status, recovered = read() + assert status == 200, recovered + assert recovered["model"]["selected"] is None + assert recovered["model"]["options"] == [{"value": "gemini-4-carbon-medium", + "label": "Gemini 4 Carbon (Medium)", "description": "", "is_default": False, + "default_reasoning_effort": "medium", "reasoning_efforts": ["medium"]}] + assert [method for method, _ in language_server["calls"]] == ["GetCascadeModelConfigData"] * 3 + assert store.list_sessions() == [] + finally: + server.shutdown() + thread.join(timeout=5) + server.server_close() + runtime.close() + + def test_failed_resume_does_not_create_a_hidden_new_conversation(tmp_path, language_server): from loopx.chat_agent import CodexChatAgentError language_server["missing_resume"] = True @@ -1512,3 +1622,134 @@ def test_antigravity_attachment_turn_sends_inline_media(tmp_path, language_serve "inlineData": base64.b64encode(png_bytes).decode("ascii"), "description": "screen.png", }] + + +def test_carbon_and_argon_offered_together_with_argon_product_default(tmp_path, language_server, monkeypatch): + import http.client + from loopx.capabilities.native_chat.antigravity_adapter import ( + ANTIGRAVITY_MODEL_OPTIONS, + ANTIGRAVITY_MODEL_PLACEHOLDERS, + ) + from loopx.chat_runtime import ChatRuntimeController + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + from loopx.chat_store import ChatSessionStore + + ordered_ids = [item["id"] for item in ANTIGRAVITY_MODEL_OPTIONS] + assert ordered_ids[:3] == [ + "gemini-4-argon-high", + "gemini-4-argon-medium", + "gemini-4-argon-low", + ] + assert ANTIGRAVITY_MODEL_PLACEHOLDERS["gemini-4-carbon-high"] == "MODEL_PLACEHOLDER_M427" + + language_server["model_configs"] = [ + {"modelOrAlias": {"model": "MODEL_PLACEHOLDER_M417"}}, + {"modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}}, + ] + store = ChatSessionStore(tmp_path / "runtime") + runtime = ChatRuntimeController(store=store, codex_bin="unused") + monkeypatch.setattr(runtime, "capabilities", lambda: [{"agent_id": "antigravity", "available": True}]) + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.verbose = False + server.chat_store, server.runtime_controller = store, runtime + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5) + try: + connection.request( + "POST", + "/api/chat/agent-model-options", + body=json.dumps({"agent_id": "antigravity"}), + headers={"Content-Type": "application/json", "Origin": f"http://127.0.0.1:{server.server_port}"}, + ) + response = connection.getresponse() + assert response.status == 200 + payload = json.loads(response.read()) + finally: + connection.close() + assert [row["value"] for row in payload["model"]["options"]] == [ + "gemini-4-argon-high", + "gemini-4-carbon-high", + ] + assert payload["model"]["selected"] == "gemini-4-argon-high" + assert payload["model"]["options"][0]["is_default"] is True + assert payload["model"]["options"][1]["is_default"] is False + finally: + server.shutdown() + thread.join(timeout=5) + server.server_close() + runtime.close() + + +def test_capacity_observation_matches_model_or_alias_without_model_id(tmp_path, language_server): + from datetime import timedelta + from loopx.capabilities.native_chat.antigravity_adapter import AntigravityAdapter + + language_server["model_configs"] = [ + { + "label": "Gemini 4 Carbon (High)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}, + } + ] + language_server["steps"] = [ + { + "type": "CORTEX_STEP_TYPE_USER_INPUT", + "status": "CORTEX_STEP_STATUS_DONE", + "metadata": {"sourceTrajectoryStepInfo": {"stepIndex": 0}, "executionId": "exec-carbon"}, + "userInput": {"items": [{"text": "probe"}]}, + }, + { + "type": "CORTEX_STEP_TYPE_PLANNER_RESPONSE", + "status": "CORTEX_STEP_STATUS_DONE", + "metadata": {"sourceTrajectoryStepInfo": {"stepIndex": 1}, "executionId": "exec-carbon"}, + "plannerResponse": {"response": "Carbon answer", "stopReason": "STOP_REASON_STOP_PATTERN"}, + }, + ] + reset = (datetime.now(timezone.utc) + timedelta(days=3)).isoformat() + language_server["user_status_response"] = { + "userStatus": { + "email": "synthetic@invalid.example", + "cascadeModelConfigData": { + "clientModelConfigs": [ + { + "label": "Gemini 4 Carbon (High)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}, + "quotaInfo": {"remainingFraction": 0.99, "resetTime": reset}, + } + ] + }, + } + } + adapter = adapter_for( + tmp_path, + executor_model={"model": "gemini-4-carbon-high", "reasoning_effort": "high"}, + ) + adapter.start_turn("probe") + reviewed = AntigravityAdapter.metadata_review_capacity( + cascade_id="synthetic-cascade", + model_id="gemini-4-carbon-high", + ) + assert reviewed is not None and reviewed["model_id"] == "gemini-4-carbon-high" + assert reviewed["remaining_fraction"] == 0.99 + endpoint_cap = AntigravityAdapter.endpoint_model_capacity(model_id="gemini-4-carbon-high") + assert endpoint_cap is not None and endpoint_cap["model_id"] == "gemini-4-carbon-high" + assert endpoint_cap["remaining_fraction"] == 0.99 and endpoint_cap["normal_completion"] is True + + +def test_antigravity_launch_guard_runs_pre_publication_once(tmp_path, language_server): + from contextlib import contextmanager + + adapter = adapter_for(tmp_path) + events = [] + + @contextmanager + def guard(): + events.append(("guard_enter", len([m for m, _ in language_server["calls"] if m == "SendUserCascadeMessage"]))) + yield + events.append(("guard_exit", len([m for m, _ in language_server["calls"] if m == "SendUserCascadeMessage"]))) + + adapter._launch_guard = guard + result = adapter.start_turn("guarded turn") + assert result["message"] == "Argon answer 1" + assert events == [("guard_enter", 0), ("guard_exit", 1)] diff --git a/tests/test_chat_manager_model_adoption.py b/tests/test_chat_manager_model_adoption.py index 3e5ea47b18..6a603990d6 100644 --- a/tests/test_chat_manager_model_adoption.py +++ b/tests/test_chat_manager_model_adoption.py @@ -30,7 +30,7 @@ from loopx.extensions.lark.conversation_identity import identity_ref -def configure(root, *, model, effort, endpoint="codex", policy="preferred"): +def configure(root, *, model, effort, endpoint="codex", policy="preferred", endpoint_models=None): document = { "schema_version": "loopx_machine_configuration_v0", "namespaces": {"steward_executor": { @@ -40,6 +40,7 @@ def configure(root, *, model, effort, endpoint="codex", policy="preferred"): "executor_endpoint": endpoint, "executor_model": model, "executor_reasoning_effort": effort, + **({"endpoint_models": endpoint_models} if endpoint_models is not None else {}), }}, } registry = build_builtin_machine_configuration_registry() @@ -748,3 +749,145 @@ def test_manager_session_model_allocation_ignores_partial_pre_v0_record(conversa partial_session = {**session, "manager_executor_allocation": partial_allocation} assert manager_session_model_allocation(runtime, partial_session) is None assert partial_session["manager_executor_allocation"] == partial_allocation + + +def test_codex_primary_flexible_quota_route_selects_carbon_and_restores_codex(conversation, monkeypatch): + import sys + from datetime import datetime, timedelta, timezone + from types import ModuleType + from loopx.capabilities.native_chat.antigravity_adapter import AntigravityAdapter + from loopx.chat_manager import manager_session_quota_route + + root, store, runtime, session, _starts = conversation + configure(root, model="gpt-6.2-sol", effort="xhigh", endpoint="codex", policy="flexible") + store.update_session(session["session_id"], upstream_thread_id="codex-thread-1", + agent_model_id="gpt-6.2-sol", agent_reasoning_effort="xhigh") + + parent = ModuleType("loopx_codex_provider_routing") + module = ModuleType("loopx_codex_provider_routing.native") + + class Accounts: + def __init__(self, path): + assert path == runtime.coordination_runtime_root + + def model_transport(self, **_parameters): + return None + + def steward_route(self, *, codex_home, primary, pool, current, primary_capacity, + fallback_capacity=None, blocked_primary=None, model=None): + assert primary == "codex" and set(pool) == {"codex", "antigravity"} + if current == "antigravity": + return {"endpoint": "codex", "blocked_primary": blocked_primary} + if fallback_capacity is None: + return {"endpoint": None, "blocked_primary": blocked_primary} + return {"endpoint": "antigravity", "blocked_primary": blocked_primary} + + module.NativeAccounts = Accounts + monkeypatch.setitem(sys.modules, parent.__name__, parent) + monkeypatch.setitem(sys.modules, module.__name__, module) + monkeypatch.setattr(runtime, "capabilities", lambda: [ + {"agent_id": "codex", "available": True}, + {"agent_id": "antigravity", "available": True}, + ]) + monkeypatch.setattr( + AntigravityAdapter, + "endpoint_model_capacity", + staticmethod(lambda *, model_id, **_kw: { + "observed_at": 1767225600.0, + "account_ref": "b" * 64, + "model_id": model_id, + "execution_id": "probe-1", + "remaining_fraction": 0.99, + "reset_time": (datetime.now(timezone.utc) + timedelta(days=1)).isoformat(), + "quota_exhausted": False, + "normal_completion": True, + }), + ) + + loaded = store.load_session(session["session_id"]) + neutral_route = manager_session_quota_route(runtime, loaded) + assert neutral_route is not None + neutral_alloc = neutral_route["allocation"] + assert neutral_alloc["executor_endpoint"] == "antigravity" + assert neutral_alloc["model"] == "gemini-4-argon-high" + assert neutral_alloc["model_source"] == "vendor_default" + assert neutral_alloc["reasoning_effort"] == "high" + assert neutral_alloc["configured_model"] is None + + configure( + root, + model="gpt-6.2-sol", + effort="xhigh", + endpoint="codex", + policy="flexible", + endpoint_models={"antigravity": {"model": "gemini-4-carbon-high", "reasoning_effort": "high"}}, + ) + routed_to_ag = manager_session_quota_route(runtime, loaded) + assert routed_to_ag is not None + alloc_ag = routed_to_ag["allocation"] + assert alloc_ag["executor_endpoint"] == "antigravity" + assert alloc_ag["allocation_reason"] == "flexible_availability_fallback" + assert alloc_ag["model"] == "gemini-4-carbon-high" + assert alloc_ag["model_source"] == "machine_configuration" + assert alloc_ag["reasoning_effort"] == "high" + assert alloc_ag["configured_model"] == "gemini-4-carbon-high" + assert alloc_ag["configured_reasoning_effort"] == "high" + + # Store transition preserves Codex provenance and allows subsequent recovery back to Codex. + turn1, _ = store.create_turn(session["session_id"], client_turn_id="switch-ag", message="Switch to Carbon") + store.update_session( + session["session_id"], + status="ready", + active_turn_id=turn1["turn_id"], + expected_upstream_thread_id="codex-thread-1", + agent_id="antigravity", + executor_endpoint_id="antigravity", + adapter_kind="antigravity_ls", + upstream_mode="default", + upstream_thread_id="ag-cascade-1", + agent_model_id=alloc_ag["model"], + agent_reasoning_effort=alloc_ag["reasoning_effort"], + manager_executor_allocation=alloc_ag, + upstream_context_history=[{ + "thread_id": "codex-thread-1", + "manager_context_version": loaded.get("manager_context_version"), + "agent_id": "codex", + "agent_model_id": "gpt-6.2-sol", + }], + ) + store.update_turn(session["session_id"], turn1["turn_id"], status="completed") + store.update_session(session["session_id"], active_turn_id=None) + + on_ag = store.load_session(session["session_id"]) + routed_back = manager_session_quota_route(runtime, on_ag) + assert routed_back is not None + alloc_codex = routed_back["allocation"] + assert alloc_codex["executor_endpoint"] == "codex" + assert alloc_codex["model"] == "gpt-6.2-sol" + assert alloc_codex["reasoning_effort"] == "xhigh" + + turn2, _ = store.create_turn(session["session_id"], client_turn_id="restore-codex", message="Back to Codex") + store.update_session( + session["session_id"], + status="ready", + active_turn_id=turn2["turn_id"], + expected_upstream_thread_id="ag-cascade-1", + agent_id="codex", + executor_endpoint_id="codex", + adapter_kind="codex_app_server", + upstream_mode="chat", + upstream_thread_id="codex-thread-2", + agent_model_id=alloc_codex["model"], + agent_reasoning_effort=alloc_codex["reasoning_effort"], + manager_executor_allocation=alloc_codex, + upstream_context_history=[ + *on_ag["upstream_context_history"], + { + "thread_id": "ag-cascade-1", + "manager_context_version": on_ag.get("manager_context_version"), + "agent_id": "antigravity", + "agent_model_id": "gemini-4-carbon-high", + }, + ], + ) + assert store.load_session(session["session_id"])["agent_id"] == "codex" diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index 3c11caab85..b1a94f9630 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -1120,3 +1120,154 @@ def test_managed_host_does_not_borrow_another_execution_lease(steward, tmp_path, retained = cli(runtime, "task-lease", "inspect", "--goal-id", actor["goal_id"], "--todo-id", todo_id) assert retained["active"] is True and retained["lease"] == original assert store.load_session(session["session_id"])["upstream_thread_id"] == session["upstream_thread_id"] + + +def test_native_steward_advancement_and_report_run_on_qualified_antigravity_fallback(steward, tmp_path, monkeypatch): + import re + from test_chat_manager_model_adoption import configure + from test_native_steward_reports import configured, fake_report_model + from loopx.capabilities.native_chat.antigravity_adapter import AntigravityAdapter + from loopx.capabilities.native_chat.steward_monitor import pump_steward_monitors + from loopx.chat_manager import steward_machine_defaults + + sid, actor, reports, _ = configured(steward, tmp_path, monkeypatch, "sqlite") + store, runtime, _, transport, binding, capture, workspace = steward + configure(runtime.coordination_runtime_root, model="gpt-6.2-sol", effort="xhigh", endpoint="codex", policy="flexible") + defaults = steward_machine_defaults(runtime) + added = cli( + runtime, + "todo", + "add", + "--goal-id", + actor["goal_id"], + "--role", + "agent", + "--text", + "Advance native steward triage on Carbon fallback.", + "--claimed-by", + "steward", + "--action-kind", + "inspect", + "--continuation-policy", + "same_agent_non_delivery", + "--execute", + ) + session = store.load_session(sid) + orig_thread = session["upstream_thread_id"] + turn_switch, _ = store.create_turn(sid, client_turn_id="fallback-switch", message="Failover to Antigravity") + store.update_turn(sid, turn_switch["turn_id"], status="queued") + store.update_session(sid, status="ready", active_turn_id=turn_switch["turn_id"], agent_model_id="gpt-6.2-sol") + session = store.load_session(sid) + allocation = { + "schema_version": "manager_executor_allocation_v0", + "selection_policy": "flexible", + "allocation_reason": "flexible_availability_fallback", + "executor_endpoint": "antigravity", + "executor_endpoint_source": "flexible_pool", + "executor_endpoint_default_reason": "", + "configured_endpoint": "codex", + "eligible_endpoints": ["codex", "antigravity"], + "configuration_revision": defaults["configuration_revision"], + "available": True, + "model": "gemini-4-carbon-high", + "model_source": "vendor_default", + "reasoning_effort": "high", + "configured_model": "gpt-6.2-sol", + "configured_reasoning_effort": "xhigh", + } + store.update_session( + sid, + status="ready", + active_turn_id=turn_switch["turn_id"], + expected_upstream_thread_id=orig_thread, + agent_id="antigravity", + executor_endpoint_id="antigravity", + adapter_kind="antigravity_ls", + upstream_mode="default", + upstream_thread_id="ag-cascade-1", + agent_model_id="gemini-4-carbon-high", + agent_reasoning_effort="high", + manager_executor_allocation=allocation, + upstream_context_history=[ + *(session.get("upstream_context_history") or []), + { + "thread_id": orig_thread, + "manager_context_version": session.get("manager_context_version"), + "agent_id": "codex", + "agent_model_id": "gpt-6.2-sol", + }, + ], + ) + store.update_turn(sid, turn_switch["turn_id"], status="completed") + store.update_session(sid, active_turn_id=None) + if sid in runtime.adapters: + runtime.adapters.pop(sid).close_session() + + guards = [] + + def fake_start(cls, *, work_dir, objective, resume_thread_id=None, history=None, + runtime_profile="restricted", team_plan_context=None, executor_model=None, + env=None, hard_timeout_sec=None): + return cls( + work_dir=work_dir, + objective=objective, + cascade_id=resume_thread_id or "ag-cascade-1", + ls_url="http://127.0.0.1:1", + csrf_token="tok", + model_id=(executor_model or {}).get("model") or "gemini-4-carbon-high", + model_placeholder="MODEL_PLACEHOLDER_M427", + reasoning_effort="high", + runtime_profile=runtime_profile, + ) + + def fake_turn(self, message, event_sink=None, **_kwargs): + with (self._launch_guard() if self._launch_guard is not None else contextlib.nullcontext()): + guards.append((type(self).__name__, self._steward_report_reader is not None)) + match = re.search(r'"editorial_request_path":\s*"([^"\n]+)"', message) + if match: + body = fake_report_model({"input": [{"text": message}]}) + else: + body = json.dumps({ + "result_kind": "validated_completion", + "classification": "steward_triage", + "summary": "Steward triage completed on Antigravity Carbon.", + "next_action": "Continue monitoring.", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Current steward route holds.", + "work_evidence": ["Observed Goal state on Antigravity fallback"], + "validation_evidence": ["Scoped readback verified"], + "steward_user_actions": [{ + "dedupe_key": "ag-fallback-digest", + "priority": "P1", + "text": "Review batched Carbon digest.", + }], + }, ensure_ascii=False) + return {"message": body} + + monkeypatch.setattr(AntigravityAdapter, "start", classmethod(fake_start)) + monkeypatch.setattr(AntigravityAdapter, "start_turn", fake_turn) + + before_codex = capture.read_bytes() + assert transport.managed_steward.health(binding["binding_id"])["execution_available"] is True + + # 1. Native report window runs and publishes via AntigravityAdapter + _steward_report_reader. + report_turn = pump_steward_monitors(runtime)[0] + report_done = finish(runtime, report_turn) + assert report_done["status"] == "completed", report_done + assert report_done["response"]["native_loopx"].get("status") == "committed", report_done + assert transport.steward_reports.reconcile() == 1 + assert reports.health(binding["binding_id"])["publication_verified"] is True + + # 2. Native steward advancement runs via AntigravityAdapter without CodexAppServerAdapter error. + adv_turn, _ = StewardTurnHost(runtime).submit( + binding["binding_id"], + turn_instance_id="advancement-on-carbon", + todo_id=added["todo_id"], + ) + adv_done = finish(runtime, adv_turn) + assert adv_done["status"] == "completed", adv_done + assert adv_done["response"]["native_loopx"].get("status") == "committed", adv_done + assert adv_done["response"].get("steward_user_action_receipts") + assert guards == [("AntigravityAdapter", True), ("AntigravityAdapter", False)] + assert capture.read_bytes() == before_codex