Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): forward declared tools unchanged and give only Codex CLI the engine's image tool (#2556)
Call White9097bd197c72
diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.mdindex 653c8d89e..aa88f7a68 100644--- a/docs/plans/backend-model-catalogs.md+++ b/docs/plans/backend-model-catalogs.md@@ -560,7 +560,10 @@ display names, no protocol chatter.`User-Agent` reaches the upstream unchanged; other transport headers and upstream auth arethe engine's own. Responses bodies toward a `codex-api-key` upstreamare rewritten by the engine (S3): the implementation verifies each real `openai_responses`- Source still serves such requests and files the engine follow-up. A Hub-held Claude+ Source still serves such requests and files the engine follow-up. Tools are the exception:+ with `disable-image-generation: passthrough` the engine forwards exactly the declared tools,+ and only Codex CLI requests get the hosted image tool, from the gateway+ (`vibey-hosted-tools.md` §7.1). A Hub-held Claudesubscription (OAuth credential) keeps the engine's cloaking: the vendor accepts those tokensonly from the Claude Code identity the cloak reproduces, so rows served by a subscriptionget the reasoning-preserving path of S4, not the body-identical guarantee. The engine has onediff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.mdindex 987505a25..af0deced3 100644--- a/docs/plans/model-hub-contracts/opencode-overlay.md+++ b/docs/plans/model-hub-contracts/opencode-overlay.md@@ -85,9 +85,11 @@ contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that sunchanged (measured on CLIProxyAPI v7.3.16, which otherwise sends `CLIProxyAPI/<version>`),so an upstream sees the calling agent's identity. Upstream auth is the engine's Bearer form. A Responses-frontend body reaching a `codex-api-key` upstreamis rewritten by the engine's Codex executor regardless of flags (`max_output_tokens`- dropped; `parallel_tool_calls: true`, `instructions: ""`, and an `image_generation` tool- added) — a known engine limitation the implementation verifies against each real+ dropped; `parallel_tool_calls: true`, `instructions: ""`) — a known engine limitation the implementation verifies against each real`openai_responses` Source before enabling the route, and tracks as an engine follow-up.+ The engine no longer adds its hosted `image_generation` tool: it runs with+ `disable-image-generation: passthrough`, and the gateway adds that tool back for Codex CLI+ requests only (`vibey-hosted-tools.md` §7.1).When the hop's protocol differs, the engine's automatic translation applies; S4 records whatsurvives: Responses-frontend effort reaches an `anthropic` upstream intact, anAnthropic-frontend `output_config.effort` is dropped on the way to an `openai_chat` upstreamdiff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 2d3d531b9..4855db6fc 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -86,6 +86,7 @@ capabilities:- tests/test_opencode_model_hub_retry.py- ui/src/lib/modelHubRecovery.test.ts- tests/test_model_hub_request_body_budget.py+ - tests/test_model_hub_codex_image_tool.py- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py- tests/test_ui_server_fastapi.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex e03e966ef..bb2452f81 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -30,6 +30,7 @@ capability:- tests/test_opencode_model_hub_retry.py- ui/src/lib/modelHubRecovery.test.ts- tests/test_model_hub_request_body_budget.py+ - tests/test_model_hub_codex_image_tool.py- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py- tests/test_ui_server_fastapi.py@@ -617,6 +618,15 @@ scenarios:kind: securitylayer: unittest: tests/test_model_hub_request_body_budget.py::test_bad_auth_does_not_parse_or_admit+ - id: MH-HOSTED-GATEWAY-001+ name: The engine forwards declared tools unchanged; only Codex CLI gets the engine's hosted image tool, byte for byte under its skip conditions+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_codex_image_tool.py::test_codex_requests_reach_the_engine_with_the_engines_own_image_tool+ related_tests:+ - tests/test_model_hub_codex_image_tool.py::test_other_callers_reach_the_engine_with_exactly_their_declared_tools+ - tests/test_model_hub_runtime.py::test_mixed_anthropic_credentials_disable_cloak_only_for_api_key_entry- id: MH-PROTOCOL-001name: Source protocol is response-observed before persistence with no transient residuestatus: covereddiff --git a/tests/test_model_hub_codex_image_tool.py b/tests/test_model_hub_codex_image_tool.pynew file mode 100644index 000000000..75fa91f62--- /dev/null+++ b/tests/test_model_hub_codex_image_tool.py@@ -0,0 +1,231 @@+"""MH-HOSTED-GATEWAY-001: with the engine in passthrough, only Codex CLI gets the hosted image tool.++The engine used to add ``{"type": "image_generation", "output_format": "png"}``+to every request its Codex executor served, for any caller. It now forwards+declared tools unchanged, and the gateway adds the tool back for Codex CLI+alone, under the engine's own skip conditions. Each case drives the real+gateway and engine adapter against a loopback engine and compares the exact+body bytes it receives with what the engine itself would have produced+(CLIProxyAPI ``ensureImageGenerationTool`` at d318bcc3).+"""++from __future__ import annotations++import base64+import json+from contextlib import asynccontextmanager+from dataclasses import replace+from types import SimpleNamespace++import aiohttp+import pytest+from aiohttp import web++from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from modules.agents.model_hub import ModelHubRuntimeRouter+from tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _service, _source+from tests.test_model_hub_vibey_consumer import _vibey_service+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+from vibe.model_hub_runtime.client import EngineClient, EngineConnection+from vibe.model_hub_runtime.state import EngineStateStore++IMAGE_TOOL = {"type": "image_generation", "output_format": "png"}+SHELL = {"type": "function", "name": "shell", "parameters": {"type": "object", "properties": {}}}+DECLARED_IMAGE = {"type": "image_generation", "quality": "high"}+INPUT = [{"role": "user", "content": [{"type": "input_text", "text": "画一只猫 café"}]}]+LITE = "ws_request_header_x_openai_internal_codex_responses_lite"+COMPLETED = {+ "/v1/responses": (+ b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"ok"}\n\n'+ b'event: response.completed\ndata: {"type":"response.completed","response":'+ b'{"id":"resp_1","status":"completed","usage":{"input_tokens":2,"output_tokens":1}}}\n\n'+ ),+ "/v1/messages": (+ b'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","usage":'+ b'{"input_tokens":2,"output_tokens":0}}}\n\n'+ b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,'+ b'"delta":{"type":"text_delta","text":"ok"}}\n\n'+ b'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},'+ b'"usage":{"output_tokens":1}}\n\n'+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'+ ),+}+++def _id_token(claims: dict) -> str:+ def part(value: dict) -> str:+ return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")++ return f"{part({'alg': 'none'})}.{part(claims)}.signature"+++@asynccontextmanager+async def _engine(received: list[bytes]):+ async def respond(request: web.Request) -> web.Response:+ received.append(await request.read())+ return web.Response(body=COMPLETED[request.path], content_type="text/event-stream")++ app = web.Application()+ app.router.add_post("/{path:.*}", respond)+ runner = web.AppRunner(app)+ await runner.setup()+ await web.TCPSite(runner, "127.0.0.1", 0).start()+ try:+ yield f"http://127.0.0.1:{runner.addresses[0][1]}"+ finally:+ await runner.cleanup()+++def _wire(service, tmp_path, root: str, grants: dict[str, dict]) -> EngineStateStore:+ """Bind every configured Source in a real engine state store and adapter at ``root``."""++ state = EngineStateStore(tmp_path / "engine")+ for configured in service.store.config.sources:+ if configured.id in grants:+ configured.credential_ref = state.bind_oauth_credential(configured.id, configured.vendor, "grant.json")+ state.write_oauth_auth_file("grant.json", {+ "type": "codex",+ "prefix": state.credential_metadata(configured.credential_ref)["prefix"],+ "access_token": "private-access-fixture",+ **grants[configured.id],+ })+ else:+ configured.credential_ref = state.store_api_key(+ "fixture-key", vendor=configured.vendor, protocol=configured.protocol,+ )+ state.sync_sources(service._bindings(service.store.load()))+ client = EngineClient(EngineConnection(root, "fixture-management", "fixture-gateway"))+ adapter = CLIProxyEngineAdapter(supervisor=SimpleNamespace(client=lambda: client), state_store=state)+ adapter.ensure_installed = service.adapter.ensure_installed+ service.adapter = adapter+ service._engine_synced = True+ return state+++async def _post(url: str, token: str, body: dict) -> None:+ async with aiohttp.ClientSession() as downstream:+ async with downstream.post(url, json=body, headers={"Authorization": f"Bearer {token}"}) as response:+ assert response.status == 200, await response.text()+ await response.read()+++def _subscription(source):+ return replace(source, kind="subscription", billing="monthly")+++# (case, request fields after model/stream/input, hop model, ChatGPT grant or None for an API key,+# the tools the engine must receive; ABSENT when the request has no tools key and gets none)+ABSENT = object()+CODEX_CASES = [+ ("no_tools", {}, "gpt-fixture", None, [IMAGE_TOOL]),+ ("tools_null", {"tools": None}, "gpt-fixture", None, [IMAGE_TOOL]),+ ("tools_object", {"tools": {"type": "function"}}, "gpt-fixture", None, [IMAGE_TOOL]),+ ("other_tools", {"tools": [SHELL]}, "gpt-fixture", None, [SHELL, IMAGE_TOOL]),+ ("image_tool_present", {"tools": [DECLARED_IMAGE, SHELL]}, "gpt-fixture", None, [DECLARED_IMAGE, SHELL]),+ (+ "image_gen_function",+ {"tools": [SHELL, {"type": "function", "name": "image_gen.imagegen"}]},+ "gpt-fixture", None,+ [SHELL, {"type": "function", "name": "image_gen.imagegen"}],+ ),+ (+ "image_gen_namespace",+ {"tools": [{"type": "namespace", "name": "image_gen", "tools": [{"type": "function", "name": "imagegen"}]}]},+ "gpt-fixture", None,+ [{"type": "namespace", "name": "image_gen", "tools": [{"type": "function", "name": "imagegen"}]}],+ ),+ (+ "namespace_without_imagegen",+ {"tools": [{"type": "namespace", "name": "image_gen", "tools": [{"type": "function", "name": "edit"}]}]},+ "gpt-fixture", None,+ [{"type": "namespace", "name": "image_gen", "tools": [{"type": "function", "name": "edit"}]}, IMAGE_TOOL],+ ),+ ("spark", {"tools": [SHELL]}, "gpt-fixture-codex-spark", None, [SHELL]),+ ("spark_with_thinking_suffix", {}, "gpt-fixture-spark(high)", None, ABSENT),+ ("plan_free", {}, "gpt-fixture", {"plan_type": " Free "}, ABSENT),+ ("plan_plus", {}, "gpt-fixture", {"plan_type": "plus"}, [IMAGE_TOOL]),+ ("token_plan_free", {}, "gpt-fixture", {"id_token": _id_token({"https://api.openai.com/auth": {}})}, ABSENT),+ (+ "token_plan_pro",+ {}, "gpt-fixture",+ {"id_token": _id_token({"https://api.openai.com/auth": {"chatgpt_plan_type": "pro"}})},+ [IMAGE_TOOL],+ ),+ ("token_unreadable", {}, "gpt-fixture", {"id_token": "not-a-jwt"}, ABSENT),+ ("grant_without_plan", {}, "gpt-fixture", {}, [IMAGE_TOOL]),+ ("lite_true", {"client_metadata": {LITE: True}}, "gpt-fixture", None, ABSENT),+ ("lite_string", {"client_metadata": {LITE: " TRUE "}}, "gpt-fixture", None, ABSENT),+ ("lite_false", {"client_metadata": {LITE: "false"}}, "gpt-fixture", None, [IMAGE_TOOL]),+]++[email protected](("fields", "model", "grant", "tools"), [case[1:] for case in CODEX_CASES],+ ids=[case[0] for case in CODEX_CASES])+async def test_codex_requests_reach_the_engine_with_the_engines_own_image_tool(+ tmp_path, fields, model, grant, tools,+):+ """MH-HOSTED-GATEWAY-001: one row per CPA condition; the engine receives exactly CPA's bytes."""+ configured = _source("src_codex001", "Codex", model_id=model)+ if grant is not None:+ configured = _subscription(configured)+ service = _service(tmp_path, sources=[configured])+ models = _canonicalize_fixed_test_routes(service)+ received: list[bytes] = []+ async with _engine(received) as root:+ state = _wire(service, tmp_path, root, {configured.id: grant} if grant is not None else {})+ gateway = ModelHubTurnGateway(service)+ try:+ base_url, token = await gateway.endpoint(+ "codex", process_scope="/repo", turn_id="turn_image_tool",+ requested_model_id=models["codex"], resolved_model_id=model, source_id=configured.id,+ )+ await _post(f"{base_url}/v1/responses", token, {"model": model, "stream": True, "input": INPUT, **fields})+ finally:+ await gateway.close()+ routed = f"{state.get_source(configured.id).prefix}/{model}"+ expected = {"model": routed, "stream": True, "input": INPUT, **fields}+ if tools is not ABSENT:+ expected["tools"] = tools+ # The engine appends a missing key at the end of the object and replaces an existing one in place.+ assert received == [json.dumps(expected).encode()]++[email protected]("declared", [False, True], ids=["undeclared", "declared"])[email protected](("backend", "path"), [+ ("claude", "messages"), ("opencode", "responses"), ("vibey", "responses"),+])+async def test_other_callers_reach_the_engine_with_exactly_their_declared_tools(tmp_path, backend, path, declared):+ """MH-HOSTED-GATEWAY-001: Claude, OpenCode and Vibey get no image tool they did not declare."""+ configured = _source("src_shared001", "Responses key")+ tools = [SHELL, DECLARED_IMAGE] if declared else [SHELL]+ if backend == "claude":+ tools = [{"name": "shell", "input_schema": {"type": "object"}}, *([DECLARED_IMAGE] if declared else [])]+ received: list[bytes] = []+ async with _engine(received) as root:+ if backend == "vibey":+ service = _vibey_service(tmp_path, [configured])+ else:+ service = _service(tmp_path, sources=[configured])+ _canonicalize_fixed_test_routes(service)+ service.store.requested_models["opencode"] = "shared-model"+ _wire(service, tmp_path, root, {})+ gateway = ModelHubTurnGateway(service)+ try:+ if backend == "vibey":+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:image", turn_id="turn-image")+ url, token, model = f'{hop["base_url"]}/{path}', hop["token"], hop["runtime_model"]+ else:+ base_url, token = await gateway.endpoint(+ backend, process_scope="/repo", turn_id="turn_image_tool",+ requested_model_id=service.store.requested_models[backend],+ resolved_model_id="shared-model", source_id=configured.id,+ )+ url, model = f"{base_url}/v1/{path}", "shared-model"+ await _post(url, token, {"model": model, "stream": True, "tools": tools, "input": INPUT})+ finally:+ await gateway.close()+ assert len(received) == 1+ assert json.loads(received[0])["tools"] == toolsdiff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 56f11b7db..1aa87fee4 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1932,6 +1932,8 @@ def test_mixed_anthropic_credentials_disable_cloak_only_for_api_key_entry(payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))assert payload["disable-claude-cloak-mode"] is True+ # The engine forwards declared image tools unchanged; Codex CLI gets its own from the gateway.+ assert payload["disable-image-generation"] == "passthrough"assert payload["claude-api-key"] == [{"api-key": "api-key-fixture",@@ -7511,6 +7513,9 @@ def test_slow_source_prelude_is_bounded_without_blocking_other_routes(def get_source(self, source_id: str) -> SourceRecord | None:return self.sources.get(source_id)+ def codex_plan_type(self, *_args, **_kwargs) -> str | None:+ return None # API keys carry no plan+class Supervisor:def __init__(self, client: EngineClient) -> None:self._client = clientdiff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex f3a59c951..3b57270a4 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -59,6 +59,7 @@ from vibe.model_hub_runtime.client import (upstream_api_url,)from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocol, validate_api_key_auth_scheme+from vibe.model_hub_runtime.codex_image_tool import with_codex_image_toolfrom vibe.model_hub_runtime.installer import (INSTALL_ALREADY_RUNNING_REASON,INSTALL_PLATFORM_UNSUPPORTED_REASON,@@ -2821,6 +2822,17 @@ class CLIProxyEngineAdapter:raise EngineStateError("source is not registered")if source.allowed_origins and origin not in source.allowed_origins:raise OriginNotAllowedError(f"origin {origin!r} is not allowed to use source {source_id!r}")+ # The engine serves every Responses Source through its Codex executor+ # (an API key or the ChatGPT grant), where it used to add its image tool.+ codex_image_tool = origin == "codex" and source.protocol == "openai_responses"+ plan_type = (+ await asyncio.to_thread(+ self.state_store.codex_plan_type,+ source.credential_ref, source_id=source.source_id, vendor=source.vendor,+ )+ if codex_image_tool+ else None+ )try:client = await asyncio.to_thread(self.supervisor.client)except EngineUnavailableError as exc:@@ -2850,6 +2862,8 @@ class CLIProxyEngineAdapter:"claude": "anthropic","codex": "openai_responses",}.get(origin, getattr(request, "protocol", None) or source.protocol)+ if codex_image_tool:+ request = with_codex_image_tool(request, model_id=model_id, plan_type=plan_type)return await client.invoke(source,model_id,diff --git a/vibe/model_hub_runtime/codex_image_tool.py b/vibe/model_hub_runtime/codex_image_tool.pynew file mode 100644index 000000000..8c8bcae9a--- /dev/null+++ b/vibe/model_hub_runtime/codex_image_tool.py@@ -0,0 +1,86 @@+"""The hosted image tool for Codex CLI requests, added by Avibe instead of the engine.++The engine runs with ``disable-image-generation: passthrough`` (``config.py``), so+it forwards exactly the tools a client declares and adds none. Through Model Hub,+the hosted tool the engine used to inject is Codex's only image path+(``docs/plans/vibey-hosted-tools.md`` §7.1), so the gateway adds it back for Codex+CLI requests alone, with the engine's own tool and skip conditions. Every other+caller reaches the upstream with exactly the tools it declared.++Ported from CLIProxyAPI (MIT), ``internal/runtime/executor/codex_executor_request.go``+(``ensureImageGenerationTool``, ``isImageGenerationFunctionTool``,+``isCodexFreePlanAuth``), ``internal/util/codex.go`` (``IsCodexResponsesLiteRequest``)+and ``internal/thinking/suffix.go`` (``ParseSuffix``), at d318bcc3 (v8.0.23).+"""++from __future__ import annotations++import copy+from typing import Any, Final, Mapping++IMAGE_GENERATION_TOOL: Final = {"type": "image_generation", "output_format": "png"}+_RESPONSES_LITE_METADATA: Final = "ws_request_header_x_openai_internal_codex_responses_lite"+++def with_codex_image_tool(+ request: Mapping[str, Any], *, model_id: str, plan_type: str | None+) -> Mapping[str, Any]:+ """Return a Codex Responses request with the engine's image tool, as the engine added it.++ Call it only for a Codex CLI request to a Source the engine serves through its+ Codex executor. ``model_id`` is the hop's model and ``plan_type`` the plan the+ engine derives for the credential (None for an API key). The request is+ returned unchanged when the engine would have skipped it: Responses-Lite+ metadata, a ``spark`` model, a free plan, or an image tool already present.+ Otherwise the tool is appended to ``tools``, or ``tools`` becomes that one+ tool when it is absent or not a list.+ """++ if _responses_lite(request) or _base_model(model_id).endswith("spark"):+ return request+ if plan_type is not None and plan_type.strip().casefold() == "free":+ return request+ tools = request.get("tools")+ if isinstance(tools, list):+ if any(_declares_image_tool(tool) for tool in tools):+ return request+ injected_tools = [*tools, dict(IMAGE_GENERATION_TOOL)]+ else:+ injected_tools = [dict(IMAGE_GENERATION_TOOL)]+ # A shallow copy keeps the request's metadata (protocol, caller headers).+ injected = copy.copy(request)+ injected["tools"] = injected_tools+ return injected+++def _responses_lite(request: Mapping[str, Any]) -> bool:+ # The header form is not forwarded by the gateway, so only the body mirror counts.+ metadata = request.get("client_metadata")+ value = metadata.get(_RESPONSES_LITE_METADATA) if isinstance(metadata, Mapping) else None+ return value is True or (isinstance(value, str) and value.strip().casefold() == "true")+++def _base_model(model_id: str) -> str:+ """The model without a ``(value)`` thinking suffix, as the engine compares it."""++ opening = model_id.rfind("(")+ if opening == -1 or not model_id.endswith(")"):+ return model_id+ return model_id[:opening]+++def _declares_image_tool(tool: Any) -> bool:+ if not isinstance(tool, Mapping):+ return False+ kind = tool.get("type")+ if kind == "image_generation":+ return True+ if kind == "function":+ return tool.get("name") == "image_gen.imagegen"+ if kind == "namespace" and tool.get("name") == "image_gen":+ nested = tool.get("tools")+ return isinstance(nested, list) and any(+ isinstance(item, Mapping) and item.get("type") == "function" and item.get("name") == "imagegen"+ for item in nested+ )+ return Falsediff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex 1ad52cff6..a5a13a51b 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -96,6 +96,10 @@ def render_engine_config("max-retry-interval": 0,"disable-cooling": True,"disable-claude-cloak-mode": True,+ # Forward exactly the tools a client declares: never add the hosted image+ # tool, never strip one. Codex CLI requests get it from the gateway instead+ # (codex_image_tool.py), and Vibey declares it only when the user enabled it.+ "disable-image-generation": "passthrough","save-cooldown-status": False,"transient-error-cooldown-seconds": -1,"quota-exceeded": {diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 54d5e3066..536a94843 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -1,5 +1,6 @@from __future__ import annotations+import base64import hashlibimport hmacimport json@@ -1058,6 +1059,40 @@ class EngineStateStore:self, credential_ref: str, *, source_id: str, vendor: str, auth_provider: str,) -> str | None:"""Project optional identity without changing custody or repairing files."""+ payload = self._bound_oauth_payload(+ credential_ref, source_id=source_id, vendor=vendor, auth_provider=auth_provider,+ )+ return _oauth_account_label(payload) if payload is not None else None++ def codex_plan_type(self, credential_ref: str, *, source_id: str, vendor: str) -> str | None:+ """The plan the engine derives for a bound Codex grant; None for any other credential.++ It is the engine's own reading of the auth file it watches (CLIProxyAPI,+ MIT, ``internal/watcher/synthesizer/file.go`` at d318bcc3): the file's+ ``plan_type``, which the engine rewrites on every refresh, else the+ ``id_token`` claim ``chatgpt_plan_type``, defaulting to ``free`` when+ the token carries none or does not parse.+ """++ payload = self._bound_oauth_payload(+ credential_ref, source_id=source_id, vendor=vendor, auth_provider="codex",+ )+ if payload is None:+ return None+ plan = payload.get("plan_type")+ if isinstance(plan, str) and plan.strip():+ return plan.strip()+ id_token = payload.get("id_token")+ if not isinstance(id_token, str) or not id_token.strip():+ return None+ auth = _jwt_claims(id_token).get("https://api.openai.com/auth")+ plan = auth.get("chatgpt_plan_type") if isinstance(auth, dict) else None+ return plan.strip() if isinstance(plan, str) and plan.strip() else "free"++ def _bound_oauth_payload(+ self, credential_ref: str, *, source_id: str, vendor: str, auth_provider: str,+ ) -> dict[str, Any] | None:+ """Read a Source's active grant as the engine holds it, or None; never repairs."""try:with self._lock:_validated_source_id(source_id)@@ -1081,10 +1116,10 @@ class EngineStateStore:if not isinstance(payload, dict):return Noneself._assert_oauth_payload_identity(metadata, auth_name, payload, auth_provider=auth_provider)- return _oauth_account_label(payload)+ return payloadexcept (EngineStateError, OSError, ValueError, TypeError):- # Display metadata is optional. A missing/unsafe grant stays under- # its existing auth recovery policy; listing must not repair it.+ # Grant metadata is optional. A missing/unsafe grant stays under+ # its existing auth recovery policy; reading must not repair it.return Nonedef oauth_credential_ref(self, auth_name: str) -> str | None:@@ -1474,6 +1509,18 @@ class EngineStateStore:raise EngineStateError(message)+def _jwt_claims(token: str) -> dict[str, Any]:+ """A token's claims as local grant metadata, never a signature verdict; {} when unreadable."""+ parts = token.split(".")+ if len(parts) != 3:+ return {}+ try:+ claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4)))+ except (ValueError, UnicodeError):+ return {}+ return claims if isinstance(claims, dict) else {}++def _oauth_account_label(payload: dict[str, Any]) -> str | None:"""Only provider-declared public identity fields can become UI metadata."""secrets = {