diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index 49a07c3f84f..8823ada7e33 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -780,7 +780,7 @@ del proceso de OpenCodex. Si la variable se fija únicamente en el proceso de An no la detecta. En Windows `agy` no está probado, porque Google lo publica solo para macOS y Linux. Para conservar el JSON de Gemini, inicia sesión con `ocx login google-antigravity` y configura -`protocols.rollout.geminiNativeAntigravity` como `true` en el JSON de OpenCodex. Esta opción se +`protocols.rollout.geminiNativeAntigravity` como `true` en el JSON de OpenCodex. También puedes activar la transmisión nativa de Gemini en la pestaña **Cuentas** de Google Antigravity. Esta opción se aplica a las solicitudes de generación Gemini de `/v1beta` que se enrutan al proveedor OAuth canónico `google-antigravity`. Las demás rutas usan el puente de Chat. Consulta [Gemini nativo con Antigravity](/es/reference/proxy-formats/#native-gemini-with-antigravity). diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index ce8e7caa6ad..a4fd7616b9b 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -524,6 +524,9 @@ Responses (`/v1/responses`) y Chat Completions (`/v1/chat/completions`) siempre | Clave | Tipo | Predeterminado | Descripción | | --- | --- | --- | --- | | `apiSurfaces.messages.enabled?` | `boolean` | herede | `true` sirve el Messages API, `false` rechaza ambas rutas con 403. Unset hereda `claudeCode.enabled`, por lo que una integración Claude que está desactivada también cierra Messages. | +| `apiSurfaces.gemini.enabled?` | `boolean` | `true` | `false` devuelve 403 para el catálogo, las operaciones de modelos y las interacciones de Gemini, incluidas las rutas compatibles bajo `/v1beta` y `/v1`. | + +La tarjeta **API de Gemini** del panel controla este ajuste y su interruptor guarda solo `apiSurfaces.gemini.enabled`. El acceso nativo a Antigravity se configura por separado. Un valor presente pero mal formado (un no objeto `apiSurfaces` o `messages`, o un no booleano `enabled`) cierra el Messages API en lugar de volver al valor heredado. Ambas rutas siempre están de acuerdo. diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 18ebf2ddb4f..eda90539e8a 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -491,10 +491,10 @@ Las respuestas de la lista de credenciales se enmascaran deliberadamente. Los to | Método y ruta | Finalidad | Errores notables | | --- | --- | --- | -| `GET /api/protocols` | Devuelve la versión del contrato de protocolo, qué API se sirven, la configuración del protocolo, la revisión de directiva actual y las características de la solicitud que entiende una vista previa | — | +| `GET /api/protocols` | Devuelve la versión del contrato de protocolo, qué API se sirven (incluido `geminiSurface` en el nivel superior), la configuración del protocolo, la revisión de directiva actual y las características de la solicitud que entiende una vista previa | — | | `GET /api/protocols?provider=` | El mismo cuerpo más `provider`: `{ name, adapter, adapterSource, authMode, upstream, modelOverrides: [{ model, adapter, source }] }` — el cable que recibe el proveedor y quién lo decidió (`hard-pin`, `operator`, `registry`, `provider-default`), con hasta 64 modelos en un cable diferente (`modelOverridesTruncated: true` más allá de eso). Ninguna credencial o base URL | 400 caracteres vacíos, repetidos, más de 200 caracteres o caracteres de control; 404 ningún proveedor con ese nombre | | `POST /api/protocols/plan` | Vista previa de la ruta que tomaría una solicitud: `{ "model": "...", "inbound": "responses" \| "chat" \| "messages", "features": [...] }` devuelve la ruta de solicitud y respuesta de cada candidato de ruta, el modo de entrega, la fidelidad, los efectos de características y las razones | 400 inválido JSON, campo desconocido, modelo de más de 200 caracteres, desconocido entrante, o más de 24 / características desconocidas | -| `PATCH /api/protocols/settings` | Cambiar la configuración del protocolo: `{ "messagesEnabled"?: boolean, "unrepresentable"?: "legacy" \| "reject", "rollout"?: { ...boolean switches } }`. Devuelve el mismo cuerpo que `GET /api/protocols`. Cierre Messages también establece `claudeCode.enabled` a `false` en el mismo salvo; al abrirlo escribe solamente `apiSurfaces.messages.enabled` | 400 inválido JSON, cuerpo vacío, campo desconocido, tipo incorrecto, o `rollout.managedMessagesNativeOAuth` sin `rollout.managedMessagesNative`; 409 configuración ocupada; 500 guardar falló (nada cambia) | +| `PATCH /api/protocols/settings` | Cambiar la configuración del protocolo: `{ "messagesEnabled"?: boolean, "geminiEnabled"?: boolean, "unrepresentable"?: "legacy" \| "reject", "rollout"?: { ...boolean switches } }`. Devuelve el mismo cuerpo que `GET /api/protocols`. Cierre Messages también establece `claudeCode.enabled` a `false` en el mismo salvo; al abrirlo escribe solamente `apiSurfaces.messages.enabled` | 400 inválido JSON, cuerpo vacío, campo desconocido, tipo incorrecto, o `rollout.managedMessagesNativeOAuth` sin `rollout.managedMessagesNative`; 409 configuración ocupada; 500 guardar falló (nada cambia) | Una vista previa se calcula a partir de la configuración sola. No envía nada a ningún proveedor, no cuesta nada, no avanza la rotación combinada y no se registra. La página API en el panel muestra la misma vista previa en **Solicitar vista previa de ruta**. Un modo de entrega de `native` describe cómo se desplaza la solicitud; no es una verificación de compatibilidad. diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index f589367d761..9c272a0f37c 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -471,6 +471,9 @@ La instantánea sigue siendo un contrato de lista de modelos de solo lectura; no ## API de Gemini: `/v1beta/models` y `/v1beta/interactions` +El interruptor **API de Gemini** del panel controla el acceso a estas rutas. Mientras la API +está habilitada, los ejemplos de uso muestran una solicitud `generateContent` que se puede copiar. + Los clientes de Gemini, como el SDK google-genai con una URL base personalizada, la CLI `agy` o un cliente que lee `GOOGLE_GEMINI_BASE_URL`, pueden usar las rutas de proveedor configuradas con la forma REST de Google. El proxy normalmente traduce la generación a su ruta de Chat Completions, que admite cualquier proveedor. La generación elegible con Antigravity puede usar la [ruta nativa](#gemini-nativo-con-antigravity) si está habilitada. Autentíquese con una clave API del proxy en `x-goog-api-key` o en el parámetro de consulta `?key=`; la clave se quita de la URL y de las cabeceras antes de registrar o reenviar la solicitud. Los errores usan la forma de Google `{ "error": { "code", "message", "status" } }`. - `GET /v1beta/models` lista `models//` para las rutas que la clave puede usar, y `GET /v1beta/models/{model}` devuelve una. Un modelo incluye `inputTokenLimit` y `outputTokenLimit` cuando se conocen. Para `inputTokenLimit`, tienen prioridad los límites de entrada y de ventana de contexto configurados en el proveedor, seguidos de `customModels[].contextWindow` del modelo correspondiente y de los metadatos generados. @@ -661,8 +664,11 @@ La opción está desactivada por defecto. Usa la API compatible con Gemini en `/ envía una clave de admisión de OpenCodex en `x-goog-api-key` o `?key=`. Un selector como `google-antigravity/gemini-3.8-flash` usa el transporte nativo para `generateContent` y `streamGenerateContent`. El proxy elige el modelo de Cloud Code Assist a partir de la ruta -resuelta y usa el token y el proyecto de la cuenta OAuth activa. Las solicitudes de -`/v1` y las de otros proveedores usan el puente de Chat. +resuelta. Si está activada la conmutación de cuentas OAuth, puede elegir otra cuenta disponible +según los modelos descubiertos para esa cuenta y la estrategia configurada. Si la cuenta +seleccionada carece del modelo y no se permite usar otra cuenta, el proxy devuelve 403. El token +y el proyecto siempre proceden de la misma cuenta. Las solicitudes de `/v1` y las de otros +proveedores usan el puente de Chat. El proxy conserva el JSON de la solicitud y de las respuestas correctas, incluidos los campos desconocidos, los enteros grandes, los argumentos de funciones y las firmas de @@ -670,6 +676,13 @@ razonamiento. La transmisión usa SSE con `alt=sse` y una matriz JSON en los dem El listado mediante `GET /v1beta/models` y la consulta de modelos conservan el catálogo permitido por la clave e incluyen los alias nativos que se enrutan al modelo de Antigravity correspondiente. +La columna `~$` muestra el coste estimado según el precio de la API de Gemini y el uso +informado. La tabla de intentos muestra el estado, la etiqueta opaca de la cuenta y el motivo +del reintento de cada envío. Si un 401 del proveedor da lugar a una actualización de las +credenciales y a un nuevo envío, el rechazo y el reintento aparecen como intentos separados. +Si solo algunos intentos tienen un coste estimado, el registro muestra el subtotal conocido +y cuántos intentos quedaron sin estimación. + Si una respuesta del proveedor contiene credenciales de la cuenta vinculada, el proxy devuelve un error genérico de Gemini. Un `[DONE]` válido del proveedor o un error de Gemini pone fin a la transmisión. @@ -677,7 +690,9 @@ Envía JSON con codificación `identity`. El cuerpo de la solicitud, la respuest en búfer y cada evento SSE tienen un límite de 16 MiB. Si `maxInboundBodyBytes` es menor, se aplica a la solicitud. La inactividad durante la carga tiene su propio tiempo de espera. El envío inicial y un reintento como máximo tras un 401 de la misma cuenta cuentan -para el límite de envíos del flujo. Un límite de tokens aplicable al flujo raíz, a la -identidad o al grupo devuelve 503 con `gemini_native_spend_limits_unsupported` porque el -transporte nativo no contabiliza los tokens. Desactiva la opción para contabilizarlos en -esta ruta de Gemini. +para el límite de envíos del flujo. Para los presupuestos de tokens del flujo raíz, la +identidad y el grupo, cada envío reserva una estimación de la entrada y el valor solicitado +de `maxOutputTokens` por candidato. Un presupuesto insuficiente devuelve 429 con +`workflow_spend_exhausted`. Las solicitudes completadas se contabilizan con los recuentos +de entrada y salida que informa Gemini. Un envío sin datos de uso finales conserva el +importe de la reserva como consumo sin resolver. diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index ca562c0c91c..ee2ab5c3b83 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1265,7 +1265,8 @@ status warns about organization settings and environment overrides it can see. I OpenCodex process environment. An override set only in the Antigravity process will not appear. On Windows `agy` is untested because Google lists it for macOS and Linux only. -To preserve Gemini JSON, sign in with `ocx login google-antigravity` and set -`protocols.rollout.geminiNativeAntigravity` to `true` in OpenCodex's JSON config. This opt-in +To preserve Gemini JSON, sign in with `ocx login google-antigravity` and turn on **Native Gemini +passthrough** in the Google Antigravity **Accounts** tab. The JSON setting is +`protocols.rollout.geminiNativeAntigravity`. This opt-in applies to `/v1beta` Gemini generation routed to the canonical `google-antigravity` OAuth provider. Other routes use the Chat bridge. See [Native Gemini with Antigravity](/reference/proxy-formats/#native-gemini-with-antigravity). diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 72cbddad330..89b1434b65d 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -713,19 +713,20 @@ Read recent detections with `ocx provider resets` or `GET /api/quota-resets`. ## API surfaces (`apiSurfaces`) Responses (`/v1/responses`) and Chat Completions (`/v1/chat/completions`) are always served. -The Messages API (`/v1/messages` and `/v1/messages/count_tokens`) can be closed on its own. +The Messages API (`/v1/messages` and `/v1/messages/count_tokens`) and the Gemini API each have their own switch. | Key | Type | Default | Description | | --- | --- | --- | --- | | `apiSurfaces.messages.enabled?` | `boolean` | inherit | `true` serves the Messages API, `false` refuses both routes with 403. Unset inherits `claudeCode.enabled`, so a Claude integration that is off also closes Messages. | +| `apiSurfaces.gemini.enabled?` | `boolean` | `true` | `false` refuses Gemini discovery, model actions and Interactions with 403. This includes Gemini-compatible routes under both `/v1beta` and `/v1`. | -A present but malformed value (a non-object `apiSurfaces` or `messages`, or a non-boolean -`enabled`) closes the Messages API rather than falling back to the inherited value. Both -routes always agree. +A malformed `apiSurfaces` object closes both switchable APIs. A malformed surface entry or +non-boolean `enabled` closes that API. -The dashboard's API page shows one card per API with the setting's source (explicit, -inherited from Claude settings, or invalid) and a toggle for Messages. Turning Messages off -there writes `apiSurfaces.messages.enabled: false` **and** `claudeCode.enabled: false` in the +The dashboard lists each API and its setting source under **Gateway endpoints**. The Gemini +switch saves only `apiSurfaces.gemini.enabled`. Eligible requests use the independently +configured [Antigravity passthrough](/reference/proxy-formats/#native-gemini-with-antigravity). +Turning Messages off writes `apiSurfaces.messages.enabled: false` **and** `claudeCode.enabled: false` in the same save, so a proxy version older than this setting, which only reads `claudeCode.enabled`, keeps the endpoint closed after a downgrade. Turning it on writes only `apiSurfaces.messages.enabled: true`; an older version then still follows diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index f91b09ddc56..e726ef347e2 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -757,10 +757,10 @@ keys are not returned to dashboard clients. | Method and path | Purpose | Notable errors | | --- | --- | --- | -| `GET /api/protocols` | Return the protocol contract version, which APIs are served, the protocol settings, the current policy revision, and the request features a preview understands | — | +| `GET /api/protocols` | Return the protocol contract version, which APIs are served (including the top-level `geminiSurface`), the protocol settings, the current policy revision, and the request features a preview understands | — | | `GET /api/protocols?provider=` | The same body plus `provider`: `{ name, adapter, adapterSource, authMode, upstream, modelOverrides: [{ model, adapter, source }] }` — the wire the provider receives and who decided it (`hard-pin`, `operator`, `registry`, `provider-default`), with up to 64 models on a different wire (`modelOverridesTruncated: true` past that). No credential or base URL | 400 empty, repeated, over 200 characters, or control characters; 404 no provider with that name | | `POST /api/protocols/plan` | Preview the path a request would take: `{ "model": "...", "inbound": "responses" \| "chat" \| "messages", "features": [...] }` returns each route candidate's request and response path, delivery mode, fidelity, feature effects, and reasons | 400 invalid JSON, unknown field, model over 200 characters, unknown inbound, or more than 24 / unknown features | -| `PATCH /api/protocols/settings` | Change protocol settings: `{ "messagesEnabled"?: boolean, "unrepresentable"?: "legacy" \| "reject", "rollout"?: { ...boolean switches } }`. Returns the same body as `GET /api/protocols`. Closing Messages also sets `claudeCode.enabled` to `false` in the same save; opening it writes only `apiSurfaces.messages.enabled` | 400 invalid JSON, empty body, unknown field, wrong type, or `rollout.managedMessagesNativeOAuth` without `rollout.managedMessagesNative`; 409 configuration busy; 500 save failed (nothing changes) | +| `PATCH /api/protocols/settings` | Change protocol settings: `{ "messagesEnabled"?: boolean, "geminiEnabled"?: boolean, "unrepresentable"?: "legacy" \| "reject", "rollout"?: { ...boolean switches } }`. Returns the same body as `GET /api/protocols`. Closing Messages also sets `claudeCode.enabled` to `false` in the same save; opening it writes only `apiSurfaces.messages.enabled` | 400 invalid JSON, empty body, unknown field, wrong type, or `rollout.managedMessagesNativeOAuth` without `rollout.managedMessagesNative`; 409 configuration busy; 500 save failed (nothing changes) | A preview is computed from configuration alone. It sends nothing to any provider, costs nothing, does not advance combo rotation, and is not logged. The API page in the dashboard shows the same diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index b457bbf0274..def6d1b613e 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -854,6 +854,10 @@ Thinking replay and prompt-cache work remain separate in [#3719](https://github. ## Gemini API: `/v1beta/models` and `/v1beta/interactions` +The **Gemini API** switch under the dashboard's **Gateway endpoints** controls access to these +routes. While the API is open, **Usage examples** includes a copyable `generateContent` request. +See [API surfaces](/reference/configuration/server/#api-surfaces-apisurfaces). + Gemini clients, such as the google-genai SDK with a custom base URL, the `agy` CLI or a client reading `GOOGLE_GEMINI_BASE_URL`, can reach the configured provider routes in Google's REST shape. The proxy normally translates generation onto its Chat Completions path, so the route behind it can be any @@ -1153,7 +1157,8 @@ A repair must decode to a JSON object. Valid JSON values containing those tags a ## Native Gemini with Antigravity Enable the canonical `google-antigravity` provider, sign in with `ocx login google-antigravity`, -and add this optional setting to OpenCodex's JSON config: +then open the Google Antigravity **Accounts** tab and turn on **Native Gemini passthrough**. +The dashboard and JSON config use the same setting: ```json { @@ -1169,14 +1174,31 @@ The default is off. Use the usual Gemini-compatible API at `/v1beta` with `x-goog-api-key` or `?key=` for an OpenCodex admission key. An eligible selector such as `google-antigravity/gemini-3.8-flash` uses the native leg for `generateContent` and `streamGenerateContent`. The proxy chooses the Cloud Code Assist model from the resolved -route and uses the active OAuth account's token and project. Other providers and `/v1` -requests use the Chat bridge. +route. With OAuth account failover enabled, it can choose another usable account according +to that account's discovered models and the configured strategy. If the selected account +is known to lack the model and no replacement is allowed, the proxy returns 403. The token +and project always come from the same account. Other providers and `/v1` requests use the +Chat bridge. The proxy preserves successful request and response JSON source, including unknown fields, large integers, function arguments, and thought signatures. Streaming uses SSE with -`alt=sse` or a streamed JSON array otherwise. `GET /v1beta/models` and model lookup keep the -configured, scoped catalog and also expose eligible native wire aliases that route back -to their Antigravity model. +`alt=sse` or a streamed JSON array otherwise. `GET /v1beta/models` and model lookup include +eligible, live-discovered Gemini models from the Antigravity discovery cache alongside configured +models. Refresh the Antigravity model list in OpenCodex to populate the cache. Native wire aliases +are available when the exact selector routes to that Antigravity model and the admission key +allows it. Requests sent through the native path show **Gemini → Gemini · Native** in the +dashboard's request logs. When a completed response reports token counts, the log displays +them and computes the end-to-end output rate. For models with a matched official rate, the +`~$` column estimates the equivalent Gemini API cost from reported input, output and cache-hit +tokens. The amount is an API price reference for Antigravity OAuth sessions. +The log details show the selected provider and model and the router's selection reason. +The upstream attempts table shows each send's status, opaque account label and recovery reason. +If an upstream 401 triggers a successful credential refresh and replay, the refusal and replay appear +as separate attempts. When only some attempts have an estimate, the log shows the known cost subtotal +and the number of attempts that could not be priced. +The log details also show the named reasoning tier or explicit thinking control and the first +visible output time for a stream. Decode throughput is estimated from the observed output +window when it includes the reported reasoning output. If an upstream payload contains bound account credentials, the proxy returns a generic Gemini error. A valid upstream `[DONE]` or a Gemini error ends stream delivery. @@ -1184,6 +1206,8 @@ Gemini error. A valid upstream `[DONE]` or a Gemini error ends stream delivery. Send identity-encoded JSON. Request and buffered response bodies and SSE events have a 16 MiB cap. A lower `maxInboundBodyBytes` also applies to requests. Upload inactivity has its own timeout. The first send and up to one 401 recovery on the same account count -against workflow physical-send ceilings. Applicable root, identity, or pool token ceilings -return 503 with `gemini_native_spend_limits_unsupported` because native token spend is -unreported. Turn off the opt-in to use token-spend accounting on this Gemini route. +against workflow physical-send ceilings. For root, identity, and pool token budgets, each +send reserves estimated input and the requested `maxOutputTokens` for each candidate. +An insufficient budget returns 429 with `workflow_spend_exhausted`. Completed requests +settle against Gemini's reported input and output counts. A send without final usage retains +its reservation amount as unresolved spend. diff --git a/gui/src/components/apikeys-workspace/ApiKeysWorkspace.tsx b/gui/src/components/apikeys-workspace/ApiKeysWorkspace.tsx index 0432c0db6bd..9456235f643 100644 --- a/gui/src/components/apikeys-workspace/ApiKeysWorkspace.tsx +++ b/gui/src/components/apikeys-workspace/ApiKeysWorkspace.tsx @@ -601,7 +601,11 @@ export default function ApiKeysWorkspace({ />
- +
diff --git a/gui/src/components/protocols/ProtocolTracePanel.tsx b/gui/src/components/protocols/ProtocolTracePanel.tsx index 80c336c8ab5..0b332d3371e 100644 --- a/gui/src/components/protocols/ProtocolTracePanel.tsx +++ b/gui/src/components/protocols/ProtocolTracePanel.tsx @@ -1,3 +1,4 @@ +import { isProtocol } from "../../../../src/protocols/contract"; import { parseProtocolTraceV1 } from "../../../../src/protocols/dto"; import type { TFn } from "../../i18n/shared"; import { openCompatibilityPair, protocolPairUpstream } from "../../protocol-deep-links"; @@ -12,6 +13,8 @@ import { FEATURE_DISPOSITION_KEYS, PROTOCOL_MODE_KEYS, protocolHopLabel, protoco */ export function ProtocolTracePanel({ trace, t }: { trace: unknown; t: TFn }) { const parsed = parseProtocolTraceV1(trace); + const inbound = parsed?.inbound; + const upstream = parsed?.upstream; return (

{t("logs.detail.protocol.section")}

@@ -64,13 +67,15 @@ export function ProtocolTracePanel({ trace, t }: { trace: unknown; t: TFn }) { )} - + {isProtocol(inbound) && ( + + )} ) : (

{t("logs.detail.protocol.none")}

diff --git a/gui/src/components/protocols/protocol-labels.ts b/gui/src/components/protocols/protocol-labels.ts index 4c73f03e561..9b248e01184 100644 --- a/gui/src/components/protocols/protocol-labels.ts +++ b/gui/src/components/protocols/protocol-labels.ts @@ -1,5 +1,5 @@ import type { DeliveryMode, ProtocolHop } from "../../../../src/protocols/contract"; -import type { ProtocolTraceV1 } from "../../../../src/protocols/dto"; +import type { ProtocolTraceHop, ProtocolTraceV1 } from "../../../../src/protocols/dto"; import type { FeatureDisposition } from "../../../../src/protocols/features"; import type { TFn, TKey } from "../../i18n/shared"; @@ -33,11 +33,11 @@ const HOP_KEYS: Record = { const ARROW = " → "; -export function protocolHopLabel(hop: ProtocolHop, t: TFn): string { - return t(HOP_KEYS[hop]); +export function protocolHopLabel(hop: ProtocolTraceHop, t: TFn): string { + return hop === "gemini" ? "Gemini" : t(HOP_KEYS[hop]); } -export function protocolPathLabel(path: readonly ProtocolHop[], t: TFn): string { +export function protocolPathLabel(path: readonly ProtocolTraceHop[], t: TFn): string { return path.map(hop => protocolHopLabel(hop, t)).join(ARROW); } diff --git a/gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx b/gui/src/components/provider-workspace/NativePassthroughSetting.tsx similarity index 58% rename from gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx rename to gui/src/components/provider-workspace/NativePassthroughSetting.tsx index 83f4005c101..c17128e2d08 100644 --- a/gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx +++ b/gui/src/components/provider-workspace/NativePassthroughSetting.tsx @@ -1,23 +1,32 @@ -/** - * Claude Code's native passthrough (`claudeCode.nativePassthrough`, default on), shown under the - * Claude account pool because it decides whether Claude Code's own traffic can reach the pool at - * all: while it is on, a bare Claude id unclaimed by an alias or model map goes straight to - * Anthropic when Claude Code sends its own login. It is one global setting, saved immediately through - * the Claude Code settings patch, which changes only the field it is sent. - */ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { useT } from "../../i18n/shared"; import { isApiTargetCaptureCurrent, targetFetch } from "../../api"; import { useRenderTargetCapture } from "../../use-render-target-capture"; -export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { apiBase: string; targetKey?: string }) { +type NativeProtocol = "claude" | "gemini"; + +function readPassthrough(payload: unknown, protocol: NativeProtocol): boolean | null { + const info = payload as { + nativePassthrough?: unknown; + settings?: { rollout?: { geminiNativeAntigravity?: unknown } }; + } | null; + const value = protocol === "gemini" ? info?.settings?.rollout?.geminiNativeAntigravity : info?.nativePassthrough; + return typeof value === "boolean" ? value : null; +} + +/** A provider account card that saves just its protocol's native passthrough setting. */ +export default function NativePassthroughSetting({ + apiBase, targetKey, protocol, +}: { apiBase: string; targetKey?: string; protocol: NativeProtocol }) { const t = useT(); + const gemini = protocol === "gemini"; + const readPath = gemini ? "/api/protocols" : "/api/claude-code"; + const title = t(gemini ? "pws.geminiNativePassthrough" : "claude.nativePassthrough"); const capture = useRenderTargetCapture(apiBase, targetKey); const [enabled, setEnabled] = useState(null); const [loadFailed, setLoadFailed] = useState(false); const [saving, setSaving] = useState(false); const [saveFailed, setSaveFailed] = useState(false); - // GET /api/claude-code gathers the catalog and can answer 503 while it is busy; Retry reloads. const [reloadVersion, setReloadVersion] = useState(0); const mountedRef = useRef(true); @@ -29,15 +38,16 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { useEffect(() => { let cancelled = false; const ac = new AbortController(); - void targetFetch(capture, `${apiBase}/api/claude-code`, { signal: ac.signal, cache: "no-store" }) + void targetFetch(capture, `${apiBase}${readPath}`, { signal: ac.signal, cache: "no-store" }) .then(response => { if (!response.ok) throw new Error("load"); - return response.json() as Promise<{ nativePassthrough?: unknown }>; + return response.json() as Promise; }) .then(json => { if (cancelled || !isApiTargetCaptureCurrent(capture)) return; - if (typeof json?.nativePassthrough !== "boolean") throw new Error("load"); - setEnabled(json.nativePassthrough); + const saved = readPassthrough(json, protocol); + if (saved === null) throw new Error("load"); + setEnabled(saved); setLoadFailed(false); }) .catch(() => { @@ -49,7 +59,7 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { cancelled = true; ac.abort(); }; - }, [apiBase, capture, reloadVersion]); + }, [apiBase, capture, protocol, readPath, reloadVersion]); const toggle = async () => { if (enabled === null || saving) return; @@ -57,17 +67,20 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { setSaving(true); setSaveFailed(false); try { - const response = await targetFetch(capture, `${apiBase}/api/claude-code`, { - method: "PUT", + const response = await targetFetch(capture, `${apiBase}${gemini ? "/api/protocols/settings" : readPath}`, { + method: gemini ? "PATCH" : "PUT", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ nativePassthrough: requested }), + body: JSON.stringify(gemini + ? { rollout: { geminiNativeAntigravity: requested } } + : { nativePassthrough: requested }), }); if (!mountedRef.current || !isApiTargetCaptureCurrent(capture)) return; if (!response.ok) throw new Error("save"); - const json = await response.json() as { nativePassthrough?: unknown } | null; + const json: unknown = await response.json(); if (!mountedRef.current || !isApiTargetCaptureCurrent(capture)) return; - if (json?.nativePassthrough !== requested) throw new Error("save"); - setEnabled(json.nativePassthrough); + const saved = readPassthrough(json, protocol); + if (saved !== requested) throw new Error("save"); + setEnabled(saved); } catch { if (mountedRef.current && isApiTargetCaptureCurrent(capture)) { setEnabled(null); @@ -81,12 +94,14 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { const loading = enabled === null && !loadFailed; return ( -
+
- {t("claude.nativePassthrough")} + {title}
- {loadFailed ? t("claude.nativePassthroughLoadFailed") : loading ? t("common.loading") : t("claude.nativePassthroughDesc")} + {loadFailed + ? t(gemini ? "pws.geminiNativePassthroughLoadFailed" : "claude.nativePassthroughLoadFailed") + : loading ? t("common.loading") : t(gemini ? "pws.geminiNativePassthroughDesc" : "claude.nativePassthroughDesc")}
); diff --git a/gui/src/pages/api-keys-utils.ts b/gui/src/pages/api-keys-utils.ts index 3a5fe54f044..e0d30fbde35 100644 --- a/gui/src/pages/api-keys-utils.ts +++ b/gui/src/pages/api-keys-utils.ts @@ -75,14 +75,14 @@ export function isApiAuthMatrix(value: unknown): value is ApiAuthMatrixRow[] { export const API_KEY_NAME_MAX_LENGTH = 64; /** Who decided a surface's state; mirrors `ApiSurfaceSource` in src/protocols/settings.ts. */ -export type ApiSurfaceSource = "fixed" | "api-surfaces" | "claude-code-legacy" | "invalid"; +export type ApiSurfaceSource = "fixed" | "default" | "api-surfaces" | "claude-code-legacy" | "invalid"; export interface ApiSurfaceInfo { enabled: boolean; source: ApiSurfaceSource; } -export type ApiSurfacesInfo = Record; +export type ApiSurfacesInfo = Record & { gemini?: ApiSurfaceInfo }; -const SURFACE_SOURCES = new Set(["fixed", "api-surfaces", "claude-code-legacy", "invalid"]); +const SURFACE_SOURCES = new Set(["fixed", "default", "api-surfaces", "claude-code-legacy", "invalid"]); const SURFACE_NAMES = ["responses", "chat", "messages"] as const satisfies readonly GatewayInboundProtocol[]; /** @@ -93,8 +93,9 @@ export function parseApiSurfaces(value: unknown): ApiSurfacesInfo | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; const record = value as Record; const surfaces = {} as ApiSurfacesInfo; - for (const name of SURFACE_NAMES) { + for (const name of [...SURFACE_NAMES, "gemini"] as const) { const surface = record[name]; + if (name === "gemini" && surface === undefined) continue; if (!surface || typeof surface !== "object" || Array.isArray(surface)) return undefined; const { enabled, source } = surface as Record; if (typeof enabled !== "boolean" || !SURFACE_SOURCES.has(source as ApiSurfaceSource)) return undefined; @@ -109,6 +110,7 @@ export interface ApiEndpointInfo { chatCompletions: string; messages: string; models: string; + geminiModels?: string; audio?: AudioApiInfo; } diff --git a/gui/src/pages/api-surface-cards.tsx b/gui/src/pages/api-surface-cards.tsx index 430791aacd8..a4eb4a7d611 100644 --- a/gui/src/pages/api-surface-cards.tsx +++ b/gui/src/pages/api-surface-cards.tsx @@ -1,19 +1,13 @@ /** - * One card per public API (Responses, Chat Completions, Messages): whether it is served, where - * it lives, and who decided that. The server resolves every state - * (`resolveApiSurfaceSettings`); this component only names it. - * - * Messages is the one switchable surface. Its card stays visible while closed, so the operator - * can see the endpoint that is being refused and reopen it. The toggle writes through - * `PATCH /api/protocols/settings` on the target `apiBase` names, then asks the page to reload - * the keys payload rather than predicting the new state. + * Gateway endpoint cards show the state reported by the server. Closed APIs stay visible so + * the operator can reopen them. Toggles patch protocol settings on the selected target and + * reload the keys payload. */ import { useState } from "react"; import { Notice, Switch } from "../ui"; import { useI18n, type TKey } from "../i18n/shared"; import { navigateHash } from "../hash-routing"; import { patchProtocolSettings } from "../protocol-api"; -import type { GatewayInboundProtocol } from "../api-access-models"; import type { ApiEndpointInfo, ApiSurfaceInfo, ApiSurfaceSource, ApiSurfacesInfo } from "./api-keys-utils"; import { EndpointUrl } from "./api-keys-copy"; @@ -21,18 +15,26 @@ const CLAUDE_HASH = "claude/code"; const SOURCE_KEYS: Record = { fixed: "api.surface.source.fixed", + default: "api.surface.source.default", "api-surfaces": "api.surface.source.explicit", "claude-code-legacy": "api.surface.source.inherited", invalid: "api.surface.source.invalid", }; -const CARDS: ReadonlyArray<{ id: GatewayInboundProtocol; titleKey: TKey; url: (endpoints: ApiEndpointInfo) => string }> = [ +const CARDS: ReadonlyArray<{ id: keyof ApiSurfacesInfo; titleKey: TKey; url: (endpoints: ApiEndpointInfo) => string | undefined }> = [ { id: "responses", titleKey: "api.responsesEndpoint", url: endpoints => endpoints.responses }, { id: "chat", titleKey: "api.chatCompletionsEndpoint", url: endpoints => endpoints.chatCompletions }, { id: "messages", titleKey: "api.messagesEndpoint", url: endpoints => endpoints.messages }, + { id: "gemini", titleKey: "api.geminiEndpoint", url: endpoints => endpoints.geminiModels }, ]; -type ToggleError = "failed" | "unavailable" | null; +const TOGGLES = { + messages: { label: "api.surface.messagesToggle", failed: "api.surface.toggleFailed", unavailable: "api.surface.toggleUnavailable" }, + gemini: { label: "api.surface.geminiToggle", failed: "api.surface.geminiToggleFailed", unavailable: "api.surface.geminiToggleUnavailable" }, +} as const satisfies Record; + +type SwitchableSurface = keyof typeof TOGGLES; +type ToggleError = { surface: SwitchableSurface; kind: "failed" | "unavailable" }; export function ApiSurfaceCards({ apiBase, @@ -47,16 +49,18 @@ export function ApiSurfaceCards({ }) { const { t } = useI18n(); const [pending, setPending] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); - const toggleMessages = async (messages: ApiSurfaceInfo) => { + const toggleSurface = async (id: SwitchableSurface, surface: ApiSurfaceInfo) => { if (pending) return; setPending(true); setError(null); try { - const result = await patchProtocolSettings(apiBase, { messagesEnabled: !messages.enabled }); + const result = await patchProtocolSettings(apiBase, id === "messages" + ? { messagesEnabled: !surface.enabled } + : { geminiEnabled: !surface.enabled }); if (result.kind === "ok") onChanged(); - else setError(result.kind === "unavailable" ? "unavailable" : "failed"); + else setError({ surface: id, kind: result.kind === "unavailable" ? "unavailable" : "failed" }); } finally { setPending(false); } @@ -66,6 +70,10 @@ export function ApiSurfaceCards({
{CARDS.map(card => { const surface = surfaces[card.id]; + const url = card.url(endpoints); + if (!surface || !url) return null; + const switchable = card.id === "messages" || card.id === "gemini" ? card.id : undefined; + const toggle = switchable && TOGGLES[switchable]; const stateLabel = surface.enabled ? t("api.surface.on") : t("api.surface.off"); return (
{t(card.titleKey)} - {card.id === "messages" ? ( + {switchable && toggle ? ( { void toggleMessages(surface); }} - label={`${t("api.surface.messagesToggle")}: ${stateLabel}`} + onClick={() => { void toggleSurface(switchable, surface); }} + label={`${t(toggle.label)}: ${stateLabel}`} /> ) : null} {stateLabel}
- + {t(SOURCE_KEYS[surface.source])} + {toggle && !surface.enabled ? {t("api.surface.closedNote")} : null} {card.id === "messages" ? ( <> - {!surface.enabled ? {t("api.surface.closedNote")} : null} {surface.enabled ? {t("api.surface.messagesCloseNote")} : null} - {error ? ( - {t(error === "unavailable" ? "api.surface.toggleUnavailable" : "api.surface.toggleFailed")} - ) : null} ) : null} + {toggle && error?.surface === card.id ? {t(toggle[error.kind])} : null}
); })} diff --git a/gui/src/pages/logs-cost-format.ts b/gui/src/pages/logs-cost-format.ts index fa943763d57..85421e8f570 100644 --- a/gui/src/pages/logs-cost-format.ts +++ b/gui/src/pages/logs-cost-format.ts @@ -52,11 +52,13 @@ export function estimateReasonsForBilling( return reasons.filter(reason => !TOKEN_PRICE_REASONS.has(reason)); } +export type PartialCostResult = { kind: "partial"; subtotalUsd: number; unpricedAttempts: number }; + type EstimatedCostResult = { kind: "value"; estimate: { cost: { total: number }; priorityLowerBound?: boolean; billing?: CostBilling; estimated?: boolean }; estimateReasons?: readonly CostEstimateReason[]; -} | { kind: "unavailable" }; +} | PartialCostResult | { kind: "unavailable" }; /** * Cost cells render a fixed `$0.1401` in every locale. The column header is the untranslated @@ -141,6 +143,9 @@ export function formatEstimatedUsd( localeTag?: string, ): string { if (!result || result.kind === "unavailable") return t("logs.cost.unavailable"); + if (result.kind === "partial") { + return t("logs.cost.partial", { amount: formatEstimatedUsdValue(result.subtotalUsd, t, localeTag) }); + } return formatEstimatedUsdValue( result.estimate.cost.total, t, diff --git a/gui/src/protocol-api.ts b/gui/src/protocol-api.ts index 0e906520741..81f971bd7b3 100644 --- a/gui/src/protocol-api.ts +++ b/gui/src/protocol-api.ts @@ -119,6 +119,7 @@ export async function fetchProtocolPlan( export interface ProtocolSettingsPatchBody { messagesEnabled?: boolean; + geminiEnabled?: boolean; } export type ProtocolSettingsPatchResult = diff --git a/gui/src/styles-apikeys-workspace.css b/gui/src/styles-apikeys-workspace.css index 9a36acfb2b5..7c67ff70a09 100644 --- a/gui/src/styles-apikeys-workspace.css +++ b/gui/src/styles-apikeys-workspace.css @@ -1003,7 +1003,7 @@ /* API surface cards (PF-04): one card per public API. Inherits the endpoint URL styling from .api-endpoints; a closed surface stays visible, dimmed rather than hidden. */ .api-endpoints.api-surface-cards { - grid-template-columns: repeat(3, minmax(0, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); } .api-surface-card { padding: var(--space-3); diff --git a/gui/tests/api-surface-cards.test.tsx b/gui/tests/api-surface-cards.test.tsx index 0ea6bc19849..3ba3d004d7d 100644 --- a/gui/tests/api-surface-cards.test.tsx +++ b/gui/tests/api-surface-cards.test.tsx @@ -4,6 +4,7 @@ import { act } from "react"; import type { Root } from "react-dom/client"; import { LanguageProvider } from "../src/i18n/provider"; import { DICTS } from "../src/i18n/shared"; +import { ApiKeysUsagePanel } from "../src/pages/api-keys-panels"; import { ApiKeysEndpointsPanel } from "../src/pages/api-keys-endpoints-panel"; import { parseApiSurfaces, type ApiSurfacesInfo } from "../src/pages/api-keys-utils"; import { patchProtocolSettings } from "../src/protocol-api"; @@ -20,6 +21,7 @@ const endpoints = { chatCompletions: "http://127.0.0.1:10100/v1/chat/completions", messages: "http://127.0.0.1:10100/v1/messages", models: "http://127.0.0.1:10100/v1/models", + geminiModels: "http://127.0.0.1:10100/v1beta/models", }; const authMatrix = [{ endpoint: "/v1/responses", bearer: "rejected" as const, dedicated: "required" as const, xApiKey: "rejected" as const }]; @@ -150,6 +152,28 @@ describe("API surface cards", () => { await act(async () => root.unmount()); }); + test("Gemini keeps its own card and patches only its setting on the selected gateway", async () => { + const calls: Array<{ url: string; method?: string; body: string }> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + calls.push({ url: String(input), method: init?.method, body: String(init?.body) }); + return Response.json({ ...INFO, geminiSurface: { enabled: true, source: "api-surfaces" } }); + }) as typeof fetch; + const remote = parseApiSurfaces({ ...INFO.surfaces, gemini: { enabled: false, source: "api-surfaces" } }); + let changed = 0; + const { root, container } = await mount({ + surfaces: remote, + apiBase: "http://hub.example:10100", + onSurfacesChanged: () => { changed++; }, + }); + const card = container.querySelector('[data-surface="gemini"]')!; + expect(card.textContent).toContain(endpoints.geminiModels); + expect(card.textContent).toContain(en["api.surface.closedNote"]); + await act(async () => { card.querySelector(".switch")!.click(); }); + expect(calls).toEqual([{ url: "http://hub.example:10100/api/protocols/settings", method: "PATCH", body: JSON.stringify({ geminiEnabled: true }) }]); + expect(changed).toBe(1); + await act(async () => root.unmount()); + }); + test("a failed toggle says so and does not reload", async () => { globalThis.fetch = (async () => new Response(JSON.stringify({ error: { code: "write_failed" } }), { status: 500 })) as unknown as typeof fetch; let changed = 0; @@ -165,6 +189,25 @@ describe("API surface cards", () => { }); }); +test("the Gemini example follows the API switch and uses the advertised models URL", async () => { + const { root, container } = await mount({}); + const render = (geminiEnabled: boolean) => act(async () => { + root.render( + + + , + ); + }); + await render(true); + expect(container.textContent).toContain(en["api.usageGeminiTitle"]); + expect(container.textContent).toContain(`${endpoints.geminiModels}/google-antigravity/gemini-3.8-flash:generateContent`); + expect(container.textContent).toContain('"parts": [{"text":'); + await render(false); + expect(container.textContent).not.toContain(en["api.usageGeminiTitle"]); + expect(container.textContent).toContain(en["api.usageMessagesTitle"]); + await act(async () => root.unmount()); +}); + describe("patchProtocolSettings", () => { test("an older server without the route reads as unavailable", async () => { globalThis.fetch = (async () => new Response("{}", { status: 404 })) as unknown as typeof fetch; diff --git a/gui/tests/claude-native-passthrough-setting.test.tsx b/gui/tests/claude-native-passthrough-setting.test.tsx index 417e1ab99b0..dd9f41efb34 100644 --- a/gui/tests/claude-native-passthrough-setting.test.tsx +++ b/gui/tests/claude-native-passthrough-setting.test.tsx @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { Window } from "happy-dom"; import { act } from "react"; import type { Root } from "react-dom/client"; -import ClaudeNativePassthroughSetting from "../src/components/provider-workspace/ClaudeNativePassthroughSetting"; +import NativePassthroughSetting from "../src/components/provider-workspace/NativePassthroughSetting"; import { LanguageProvider } from "../src/i18n/provider"; import { DICTS } from "../src/i18n/shared"; @@ -68,7 +68,7 @@ function stubClaudeCode( return calls; } -async function mount(): Promise { +async function mount(protocol: "claude" | "gemini" = "claude"): Promise { const host = testWindow.document.createElement("div"); testWindow.document.body.appendChild(host as never); const { createRoot } = await import("react-dom/client"); @@ -77,7 +77,7 @@ async function mount(): Promise { mountedRoots.push(root); root.render( - + , ); }); @@ -175,3 +175,41 @@ describe("Claude native passthrough setting", () => { expect(toggleOf(host).getAttribute("aria-pressed")).toBe("false"); }); }); + +describe("Gemini native passthrough setting", () => { + const settings = (enabled: boolean) => ({ settings: { rollout: { geminiNativeAntigravity: enabled } } }); + + test("reads the live setting and saves only the Gemini rollout switch", async () => { + const patches: unknown[] = []; + let enabled = false; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input) === "http://proxy/api/protocols" && !init?.method) return Response.json(settings(enabled)); + expect(String(input)).toBe("http://proxy/api/protocols/settings"); + expect(init?.method).toBe("PATCH"); + const patch = JSON.parse(String(init?.body)); + patches.push(patch); + enabled = patch.rollout.geminiNativeAntigravity; + return Response.json(settings(enabled)); + }) as typeof fetch; + + const host = await mount("gemini"); + expect(toggleOf(host).getAttribute("aria-label")).toBe(DICTS.en["pws.geminiNativePassthrough"]); + expect(toggleOf(host).getAttribute("aria-pressed")).toBe("false"); + await act(async () => { toggleOf(host).click(); await flush(); }); + expect(toggleOf(host).getAttribute("aria-pressed")).toBe("true"); + await act(async () => { toggleOf(host).click(); await flush(); }); + expect(toggleOf(host).getAttribute("aria-pressed")).toBe("false"); + expect(patches).toEqual([ + { rollout: { geminiNativeAntigravity: true } }, + { rollout: { geminiNativeAntigravity: false } }, + ]); + }); + + test("does not enable the switch on a server that omits the Gemini flag", async () => { + globalThis.fetch = (async () => Response.json({ settings: { rollout: {} } })) as typeof fetch; + const host = await mount("gemini"); + expect(toggleOf(host).disabled).toBe(true); + expect(toggleOf(host).hasAttribute("aria-pressed")).toBe(false); + expect(host.textContent).toContain(DICTS.en["pws.geminiNativePassthroughLoadFailed"]); + }); +}); diff --git a/gui/tests/logs-protocol-trace.test.tsx b/gui/tests/logs-protocol-trace.test.tsx index 9b942b63c56..4d146bf176f 100644 --- a/gui/tests/logs-protocol-trace.test.tsx +++ b/gui/tests/logs-protocol-trace.test.tsx @@ -31,6 +31,14 @@ const native: ProtocolTraceV1 = { attempts: undefined, }; +const gemini: ProtocolTraceV1 = { + ...native, + inbound: "gemini", + upstream: "gemini", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], +}; + describe("ProtocolBadge", () => { test("writes the path and the mode as text", () => { const html = renderToStaticMarkup(); @@ -38,6 +46,15 @@ describe("ProtocolBadge", () => { expect(html).toContain('data-protocol-mode="native"'); }); + test("labels native Gemini in both the list and the detail", () => { + const translate: TFn = (key, vars) => interpolate(DICTS.zh[key], vars); + const badge = renderToStaticMarkup(); + const panel = renderToStaticMarkup(); + expect(badge).toContain("Gemini → Gemini · 原生"); + expect(panel).toContain("Gemini → Gemini"); + expect(panel).not.toContain("protocol-deep-link"); + }); + test("renders nothing for a row without a valid trace", () => { expect(renderToStaticMarkup()).toBe(""); expect(renderToStaticMarkup()).toBe(""); diff --git a/gui/tests/logs-upstream-faults.test.tsx b/gui/tests/logs-upstream-faults.test.tsx index 76a2715d6f4..0dc5ba18d0b 100644 --- a/gui/tests/logs-upstream-faults.test.tsx +++ b/gui/tests/logs-upstream-faults.test.tsx @@ -203,12 +203,41 @@ test.each([ test("multiple attempts preserve their recovery reason without inventing retries", async () => { const row = fixture(429, "rate-limit", 2); const attempt = (row.attempts as Record[])[0]!; - row.attempts = [{ ...attempt, sendCount: 1, recoveryKinds: ["rate-limit-429"] }, - { ...attempt, ordinal: 2, sendCount: 1 }]; + row.attempts = [ + { ...attempt, status: 401, sendCount: 1, failureCause: "credential-rejected" }, + { ...attempt, ordinal: 2, sendCount: 1, failureCause: "rate-limit", recoveryKinds: ["oauth-401"] }, + ]; const { root } = await show(row); try { - expect(document.querySelector(".log-detail-attempts")?.textContent).toContain("Rate-limited (429)"); + const attempts = [...document.querySelectorAll(".log-detail-attempts tbody tr")]; + expect(attempts[0]?.textContent).toContain("401 · Credentials rejected"); + expect(attempts[1]?.textContent).toContain("429 · Rate limited"); + expect(attempts[1]?.textContent).toContain("OAuth re-authentication"); expect(value("Upstream sends")).toBe("2"); expect(value("Retries")).toBeUndefined(); } finally { await act(async () => { root.unmount(); }); } }); + +test("native retry detail shows an opaque account label and a separately qualified subtotal", async () => { + const row = fixture(200, "credential-rejected", 2); + const attempt = (row.attempts as Record[])[0]!; + row.displayMetrics = { + tokPerSecond: { kind: "unavailable", reason: "usage_missing" }, + cost: { kind: "partial", subtotalUsd: 0.0123, unpricedAttempts: 1 }, + }; + row.attempts = [ + { ...attempt, status: 401, sendCount: 1, accountLogLabel: "o123abc" }, + { ...attempt, ordinal: 2, sendCount: 1, accountLogLabel: "raw-account-identifier", recoveryKinds: ["oauth-401"] }, + ]; + const { root, container } = await show(row); + try { + expect(container.querySelector("td[title='Attempts without a cost estimate (1)']")?.textContent).toBe("Known $0.0123"); + const cost = document.getElementById("log-detail-cost")?.closest("section")?.textContent; + expect(cost).toContain("Known cost subtotal"); + expect(cost).toContain("$0.0123"); + expect(cost).toContain("Attempts without a cost estimate (1)"); + const table = document.querySelector(".log-detail-attempts")?.textContent; + expect(table).toContain("Account o123abc"); + expect(table).not.toContain("raw-account-identifier"); + } finally { await act(async () => { root.unmount(); }); } +}); diff --git a/gui/tests/provider-account-import.test.tsx b/gui/tests/provider-account-import.test.tsx index 4888005d02b..a841cd9068d 100644 --- a/gui/tests/provider-account-import.test.tsx +++ b/gui/tests/provider-account-import.test.tsx @@ -43,7 +43,17 @@ beforeEach(() => { Object.defineProperties(globalThis, { document: { configurable: true, value: win.document }, window: { configurable: true, value: win }, navigator: { configurable: true, value: win.navigator }, localStorage: { configurable: true, value: win.localStorage }, - fetch: { configurable: true, value: fetchMock }, + fetch: { + configurable: true, + value: async (url: RequestInfo | URL, init?: RequestInit) => { + // The native passthrough card reads its setting upon mount. Keep that read + // separate so the import assertions still count every other network call. + if (url === "/proxy/api/protocols" && (init?.method ?? "GET") === "GET") { + return Response.json({ settings: { rollout: { geminiNativeAntigravity: false } } }); + } + return fetchMock(url, init); + }, + }, }); (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; host = win.document.createElement("div") as unknown as HTMLElement; diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index 245e242e4e5..05ce1c30f46 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -1,4 +1,5 @@ { + "usage-cost-antigravity-gemini4.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-credit-ledger-regressions.test.ts": "usage", "usage-provider-credit-price.test.ts": "usage", diff --git a/src/adapters/google-usage.ts b/src/adapters/google-usage.ts new file mode 100644 index 00000000000..6b039c30a73 --- /dev/null +++ b/src/adapters/google-usage.ts @@ -0,0 +1,28 @@ +import type { OcxUsage } from "../types"; + +function tokenCount(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +/** Translate Gemini usageMetadata without retaining provider payload fields. */ +export function usageFromGemini(usage: unknown): OcxUsage | undefined { + if (!usage || typeof usage !== "object" || Array.isArray(usage)) return undefined; + const counters = usage as Record; + const prompt = tokenCount(counters.promptTokenCount); + const toolPrompt = tokenCount(counters.toolUsePromptTokenCount); + const candidates = tokenCount(counters.candidatesTokenCount); + const thoughts = tokenCount(counters.thoughtsTokenCount); + const cached = tokenCount(counters.cachedContentTokenCount); + if ([prompt, toolPrompt, candidates, thoughts, cached].every(count => count === undefined)) return undefined; + + // Tool-use prompts are billed as input and thinking tokens are billed as output. + const inputTokens = (prompt ?? 0) + (toolPrompt ?? 0); + const outputTokens = (candidates ?? 0) + (thoughts ?? 0); + if (!Number.isSafeInteger(inputTokens + outputTokens)) return undefined; + return { + inputTokens, + outputTokens, + ...(cached !== undefined ? { cachedInputTokens: cached } : {}), + ...(thoughts !== undefined ? { reasoningOutputTokens: thoughts } : {}), + }; +} diff --git a/src/adapters/google.ts b/src/adapters/google.ts index 74bfb61f21b..99ab08443e4 100644 --- a/src/adapters/google.ts +++ b/src/adapters/google.ts @@ -28,6 +28,7 @@ import { readDisplaySafeErrorPayloadText } from "./upstream-http-error"; import { googleModeLabel, googlePromptBlockedEvent, googleStopReason, isGoogleTruncatedTurn, vertexTruncationErrorEvent } from "./google-truncation"; import { antigravitySessionAnchor, antigravityUserAgentForWireModel, antigravitySessionId, isLikelyRealThoughtSignature, sanitizeAntigravityClaudeSignatures } from "./google-antigravity-wire"; import { summarizeGoogleWireShape } from "./google-wire-shape"; +import { usageFromGemini } from "./google-usage"; import { compileGoogleWireBody } from "./google-wire-compiler"; import type { GoogleToolSchemaLossReport, GoogleToolSchemaProfile } from "./google-tool-schema"; import { identifyRoutedModel } from "./identity"; @@ -685,19 +686,6 @@ function toolChoiceToGeminiToolConfig(parsed: OcxParsedRequest): Record | undefined): OcxUsage | undefined { - if (!usage) return undefined; - return { - // Google reports tool-use prompt tokens (search grounding, URL context) beside the prompt. - inputTokens: (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0), - // Google reports thinking beside candidates. Every other adapter's output includes reasoning - // (telemetry clamps reasoning to output, src/telemetry/aggregate.ts), and Google bills it as output. - outputTokens: (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0), - ...(usage.cachedContentTokenCount !== undefined ? { cachedInputTokens: usage.cachedContentTokenCount } : {}), - ...(usage.thoughtsTokenCount !== undefined ? { reasoningOutputTokens: usage.thoughtsTokenCount } : {}), - }; -} - /** * Cap on the buffered non-streaming response body (100 MiB), matching * IMAGES_RESPONSE_MAX_BYTES in src/server/images.ts. Enforced by streaming the @@ -1434,11 +1422,10 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte } // usageMetadata is a top-level field independent of candidates; read it BEFORE the // candidates guard so a usage-only final chunk is not dropped. - const usageMeta = root.usageMetadata as Record | undefined; - if (usageMeta) { + if (root.usageMetadata) { // Accumulate usage; emit a single terminal `done` post-loop so usage is never // dropped on EOF and the stream never yields two `done` events. - pendingUsage = usageFromGemini(usageMeta); + pendingUsage = usageFromGemini(root.usageMetadata) ?? pendingUsage; sawTerminalSignal = true; } const rawCandidates = root.candidates; @@ -1767,7 +1754,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte const feedback = (json as { promptFeedback?: unknown }).promptFeedback; if (isGoogleRecord(feedback) && typeof feedback.blockReason === "string" && feedback.blockReason) { return finish([googlePromptBlockedEvent(googleModeLabel(provider.googleMode), feedback.blockReason, - usageFromGemini(json.usageMetadata as Record | undefined))]); + usageFromGemini(json.usageMetadata))]); } return finish([{ type: "error", message: "google response contained no candidates" }]); } @@ -1851,12 +1838,12 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte return finish([vertexTruncationErrorEvent( candidate.finishReason, toolCallsStarted, - usageFromGemini(json.usageMetadata as Record | undefined), + usageFromGemini(json.usageMetadata), googleModeLabel(provider.googleMode), )]); } - const usage = json.usageMetadata as Record | undefined; + const usage = usageFromGemini(json.usageMetadata); // Mirror the streaming path: a buffered turn cut off by the token limit or a content filter // must carry its stop reason, or the bridge sees a clean `done` and reports the truncated // turn as completed — and, on a compaction turn, installs the half-written summary as @@ -1865,7 +1852,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte const stopReason = googleStopReason(finishReason); events.push({ type: "done", - usage: usageFromGemini(usage), + usage, ...(stopReason ? { stopReason } : {}), }); return finish(events); diff --git a/src/codex/account-label.ts b/src/codex/account-label.ts index 21858d39ad7..4af666c6b5a 100644 --- a/src/codex/account-label.ts +++ b/src/codex/account-label.ts @@ -23,7 +23,7 @@ export const CODEX_ACCOUNT_LOG_LABEL_RE = /^p[a-f0-9]{6}$/; */ export const OAUTH_ACCOUNT_LOG_LABEL_RE = /^o[a-f0-9]{6}$/; export const KEY_ACCOUNT_LOG_LABEL_RE = /^k[a-f0-9]{32}$/; -export const ACCOUNT_LOG_LABEL_RE = /^(?:main|[po][a-f0-9]{6}|k[a-f0-9]{32})$/; +export { ACCOUNT_LOG_LABEL_RE } from "../usage/telemetry-contract"; /** Digest the request-owned configured selection, never serialize its key/reference. */ export function apiKeyAccountLogLabel(provider: string, selection: ProviderApiKeySelection | undefined): `k${string}` | undefined { diff --git a/src/protocols/dto.ts b/src/protocols/dto.ts index 3d96365879d..17181a0bb6f 100644 --- a/src/protocols/dto.ts +++ b/src/protocols/dto.ts @@ -87,15 +87,18 @@ export interface ProtocolAttemptTraceV1 { responsePath?: ProtocolHop[]; } +/** A hop in an observed trace. Gemini native delivery does not go through the protocol planner. */ +export type ProtocolTraceHop = ProtocolHop | "gemini"; + /** What one request actually did, recorded at the send boundary and persisted with the log row. */ export interface ProtocolTraceV1 { v: typeof PROTOCOL_TRACE_SCHEMA_VERSION; - inbound: Protocol; + inbound: Protocol | "gemini"; /** Final attempt's mode, or `blocked` when refused before any send. */ mode: DeliveryMode; - upstream?: UpstreamWire; - requestPath: ProtocolHop[]; - responsePath: ProtocolHop[]; + upstream?: UpstreamWire | "gemini"; + requestPath: ProtocolTraceHop[]; + responsePath: ProtocolTraceHop[]; reasonCodes: ProtocolReasonCode[]; featureEffects?: ProtocolFeatureEffectV1[]; attempts?: ProtocolAttemptTraceV1[]; @@ -202,15 +205,24 @@ function isAttemptTrace(value: unknown): value is ProtocolAttemptTraceV1 { && (value.responsePath === undefined || isPath(value.responsePath)); } +function isNativeGeminiPath(value: unknown): boolean { + return Array.isArray(value) && value.length === 2 && value[0] === "gemini" && value[1] === "gemini"; +} + export function isProtocolTraceV1(value: unknown): value is ProtocolTraceV1 { - if (!isRec(value) || value.v !== PROTOCOL_TRACE_SCHEMA_VERSION) return false; - if (!isProtocol(value.inbound) || !isDeliveryMode(value.mode)) return false; - if (value.upstream !== undefined && !isUpstreamWire(value.upstream)) return false; - const pathsOk = value.mode === "blocked" - ? Array.isArray(value.requestPath) && value.requestPath.length === 0 - && Array.isArray(value.responsePath) && value.responsePath.length === 0 - : isPath(value.requestPath) && isPath(value.responsePath); - if (!pathsOk || !isReasonCodes(value.reasonCodes) || typeof value.contractVersion !== "string") return false; + if (!isRec(value) || value.v !== PROTOCOL_TRACE_SCHEMA_VERSION || !isDeliveryMode(value.mode)) return false; + if (value.inbound === "gemini") { + if (value.mode !== "native" || value.upstream !== "gemini" || value.attempts !== undefined + || !isNativeGeminiPath(value.requestPath) || !isNativeGeminiPath(value.responsePath)) return false; + } else { + if (!isProtocol(value.inbound) || (value.upstream !== undefined && !isUpstreamWire(value.upstream))) return false; + const pathsOk = value.mode === "blocked" + ? Array.isArray(value.requestPath) && value.requestPath.length === 0 + && Array.isArray(value.responsePath) && value.responsePath.length === 0 + : isPath(value.requestPath) && isPath(value.responsePath); + if (!pathsOk) return false; + } + if (!isReasonCodes(value.reasonCodes) || typeof value.contractVersion !== "string") return false; if (value.featureEffects !== undefined && !boundedArray(value.featureEffects, PROTOCOL_DTO_LIMITS.featureEffects, isFeatureEffect)) return false; if (value.attempts !== undefined && !boundedArray(value.attempts, PROTOCOL_DTO_LIMITS.attempts, isAttemptTrace)) return false; diff --git a/src/protocols/settings.ts b/src/protocols/settings.ts index 670a5b7b55b..b963912649d 100644 --- a/src/protocols/settings.ts +++ b/src/protocols/settings.ts @@ -13,6 +13,8 @@ import type { Protocol } from "./contract"; export type ApiSurfaceSource = /** Responses and Chat Completions: always served. */ | "fixed" + /** Gemini: open when no setting is supplied. */ + | "default" /** An explicit boolean in `apiSurfaces`. */ | "api-surfaces" /** No explicit value; inherited from `claudeCode.enabled`. */ @@ -32,28 +34,30 @@ function isRec(value: unknown): value is Rec { return !!value && typeof value === "object" && !Array.isArray(value); } -function resolveMessagesSurface(config: Pick): ApiSurfaceSetting { - const raw: unknown = config.apiSurfaces; - if (raw !== undefined) { - if (!isRec(raw)) return { enabled: false, source: "invalid" }; - const messages = raw.messages; - if (messages !== undefined) { - if (!isRec(messages)) return { enabled: false, source: "invalid" }; - if (Object.hasOwn(messages, "enabled")) { - return typeof messages.enabled === "boolean" - ? { enabled: messages.enabled, source: "api-surfaces" } - : { enabled: false, source: "invalid" }; - } - } - } - return { enabled: config.claudeCode?.enabled !== false, source: "claude-code-legacy" }; +function resolveOptionalSurface(raw: unknown, name: "messages" | "gemini", fallback: ApiSurfaceSetting): ApiSurfaceSetting { + if (raw === undefined) return fallback; + if (!isRec(raw)) return { enabled: false, source: "invalid" }; + const surface = raw[name]; + if (surface === undefined) return fallback; + if (!isRec(surface)) return { enabled: false, source: "invalid" }; + if (!Object.hasOwn(surface, "enabled")) return fallback; + return typeof surface.enabled === "boolean" + ? { enabled: surface.enabled, source: "api-surfaces" } + : { enabled: false, source: "invalid" }; +} + +export function resolveGeminiApiSurface(config: Pick): ApiSurfaceSetting { + return resolveOptionalSurface(config.apiSurfaces, "gemini", { enabled: true, source: "default" }); } export function resolveApiSurfaceSettings(config: Pick): ApiSurfaceSettings { return Object.freeze({ responses: Object.freeze({ enabled: true, source: "fixed" as const }), chat: Object.freeze({ enabled: true, source: "fixed" as const }), - messages: Object.freeze(resolveMessagesSurface(config)), + messages: Object.freeze(resolveOptionalSurface(config.apiSurfaces, "messages", { + enabled: config.claudeCode?.enabled !== false, + source: "claude-code-legacy", + })), }); } diff --git a/src/protocols/shadow.ts b/src/protocols/shadow.ts index fbe147d0a31..ff5c388eb40 100644 --- a/src/protocols/shadow.ts +++ b/src/protocols/shadow.ts @@ -18,8 +18,7 @@ * - A blocked trace agrees with a blocked plan. A compatibility reject is Claude-integration * policy the planner does not model, so it is not compared. */ -import type { ProtocolHop } from "./contract"; -import type { ProtocolPlanCandidateV1, ProtocolPlanV1, ProtocolTraceV1 } from "./dto"; +import type { ProtocolPlanCandidateV1, ProtocolPlanV1, ProtocolTraceHop, ProtocolTraceV1 } from "./dto"; /** The route the request settled on, as the request log context records it. */ export interface ShadowSettledRoute { @@ -27,7 +26,7 @@ export interface ShadowSettledRoute { model?: string; } -function samePath(a: readonly ProtocolHop[], b: readonly ProtocolHop[]): boolean { +function samePath(a: readonly ProtocolTraceHop[], b: readonly ProtocolTraceHop[]): boolean { return a.length === b.length && a.every((hop, index) => hop === b[index]); } diff --git a/src/protocols/trace.ts b/src/protocols/trace.ts index d0c1994d23d..723b16e5495 100644 --- a/src/protocols/trace.ts +++ b/src/protocols/trace.ts @@ -62,7 +62,7 @@ export interface ProtocolTraceAttempt { adapter: string; } -const requestMarks = new WeakMap(); +const requestMarks = new WeakMap(); const attemptMarks = new WeakMap(); const shadowInputs = new WeakMap(); const suppressedContexts = new WeakSet(); @@ -121,12 +121,22 @@ export function markProtocolEntry( } } +/** Record an actual native Gemini send without inspecting the payload. */ +export function markNativeGeminiProtocol(logCtx: object): void { + if (protocolTraceSuppressed(logCtx)) return; + try { + requestMarks.set(logCtx, { kind: "gemini-native" }); + } catch { + /* a trace must never fail the request it describes */ + } +} + /** Features the request's entry or blocked mark recorded, for the shadow plan input. */ export function protocolMarkFeatures(logCtx: object): readonly ProtocolFeature[] | undefined { if (protocolTraceSuppressed(logCtx)) return undefined; try { const mark = requestMarks.get(logCtx); - return mark ? [...mark.features] : undefined; + return mark && mark.kind !== "gemini-native" ? [...mark.features] : undefined; } catch { return undefined; } @@ -292,6 +302,18 @@ function observedTrace( ): ProtocolTraceV1 | undefined { try { const mark = requestMarks.get(logCtx); + if (mark?.kind === "gemini-native") { + return { + v: PROTOCOL_TRACE_SCHEMA_VERSION, + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + reasonCodes: ["same-wire-native"], + contractVersion: PROTOCOL_CONTRACT_VERSION, + }; + } if (mark?.kind === "blocked") { return { v: PROTOCOL_TRACE_SCHEMA_VERSION, diff --git a/src/server/credential-recovery-attempt.ts b/src/server/credential-recovery-attempt.ts index 8b2ca2adb0d..8c5703861df 100644 --- a/src/server/credential-recovery-attempt.ts +++ b/src/server/credential-recovery-attempt.ts @@ -18,8 +18,8 @@ export function sealCredentialRefusal(logCtx: RequestLogContext, status: number, type AttemptSendProvider = Parameters[2]; type AttemptSendRecovery = Parameters[4]; -/** Open a native compact attempt at its first physical send and count each send against it. */ -export function noteCompactAttemptSend( +/** Open an attempt at its first physical send and count each send against it. */ +export function noteCredentialAttemptSend( logCtx: RequestLogContext, route: { providerName: string; modelId: string }, provider: AttemptSendProvider, recovery?: AttemptSendRecovery, ): void { const { providerName, modelId } = route; diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts index 2b298779bdf..6ff831de6ad 100644 --- a/src/server/gemini-inbound.ts +++ b/src/server/gemini-inbound.ts @@ -3,8 +3,8 @@ * /v1beta|v1/models/{model}:generateContent|streamGenerateContent (countTokens and the embed * methods answer 501). * - * Same shape as the Ollama inbound (./ollama-inbound): the model list describes configured - * provider routes, generation is translated into an internal Chat Completions request handled by + * Like the Ollama inbound (./ollama-inbound), the catalog starts with configured + * provider routes. Unless the native leg applies, generation is translated into an internal Chat Completions request handled by * the ordinary Chat path, and this handler owns the final request-log row. Errors use the Gemini * `{ error: { code, message, status } }` body with a fixed message chosen by HTTP status. */ @@ -21,7 +21,7 @@ import { estimateInputTokens } from "./responses/input-admission"; import type { DataPlaneAdmission } from "./auth-cors"; import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; import type { GeminiMethod } from "./gemini-native-paths"; -import { geminiNativeCatalogAliases, geminiNativeCatalogLookup } from "./gemini-native-catalog"; +import { geminiNativeCatalogAliases, geminiNativeCatalogLookup, geminiNativeDiscoveredRoutes } from "./gemini-native-catalog"; import { applyLocalRefusalCode, commitCancelled, @@ -66,10 +66,11 @@ export function toGeminiRefusal(response: Response): Response { return applyLocalRefusalCode(geminiError(parts.status, parts.message, parts.retryAfter), parts.localRefusalCode); } -function eligibleRoutes(config: OcxConfig, req: Request, admission: DataPlaneAdmission) { - const scope = resolveAdmissionModelScope(config, admission); - return listOllamaRoutes(config, req) - .filter(row => routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })); +function geminiCatalogRoutes(config: OcxConfig, req: Request) { + const configured = listOllamaRoutes(config, req); + const selectors = new Set(configured.map(row => row.selector)); + const discovered = geminiNativeDiscoveredRoutes(config, req).filter(row => !selectors.has(row.selector)); + return [...configured, ...discovered]; } /** Token limits from configuration first, then generated model metadata; omitted when unknown. */ @@ -96,16 +97,19 @@ const modelResource = (config: OcxConfig, row: { selector: string; route: RouteR }); export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response { - const rows = eligibleRoutes(config, req, admission); - const aliases = geminiNativeCatalogAliases(config, req, rows, resolveAdmissionModelScope(config, admission)); + const scope = resolveAdmissionModelScope(config, admission); + const candidates = geminiCatalogRoutes(config, req); + const rows = candidates.filter(row => routeAllowedByScope(scope, row.route)); + // A key can allow a concrete effort tier while excluding its source family. + const aliases = geminiNativeCatalogAliases(config, req, candidates, scope); return Response.json({ models: [...rows, ...aliases].map(row => modelResource(config, row)) }); } function findGeminiCatalogRow(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string) { - const row = findOllamaRoute(config, model, req); + const row = findOllamaRoute(config, model, req) ?? geminiNativeDiscoveredRoutes(config, req, model)[0]; const scope = resolveAdmissionModelScope(config, admission); if (row && routeAllowedByScope(scope, row.route)) return row; - return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, admission), scope); + return geminiNativeCatalogLookup(config, req, model, () => geminiCatalogRoutes(config, req), scope); } export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { diff --git a/src/server/gemini-native-catalog.ts b/src/server/gemini-native-catalog.ts index 70813403c54..d87619cd7c2 100644 --- a/src/server/gemini-native-catalog.ts +++ b/src/server/gemini-native-catalog.ts @@ -1,5 +1,8 @@ +import { getStaleCached } from "../codex/model-cache"; +import { filterCatalogVisibleModels } from "../codex/catalog/model-visibility"; import { resolveProtocolSettings } from "../protocols/settings"; import { resolveAntigravityEffortWireModel } from "../providers/antigravity-models"; +import { slugEquals } from "../providers/slug-codec"; import { effectiveGoogleMode } from "../providers/registry"; import type { RouteResult } from "../router"; import type { OcxConfig } from "../types"; @@ -35,7 +38,7 @@ export function nativeGeminiDestination(config: OcxConfig, req: Request, selecto /** A native alias must route to the same wire ID and pass scope under its own resolved destination. */ function allowedWireAlias(config: OcxConfig, req: Request, alias: string, scope?: AdmissionModelScope): CatalogRow | undefined { - if (!GEMINI_MODEL.test(alias)) return undefined; + if (!GEMINI_MODEL.test(alias) || nativeModelDisabled(config, alias)) return undefined; const destination = resolveNativeDestination(config, req, alias); if (destination?.wireModel !== alias || !routeAllowedByScope(scope, destination.route)) return undefined; return { selector: alias, route: destination.route }; @@ -43,6 +46,27 @@ function allowedWireAlias(config: OcxConfig, req: Request, alias: string, scope? type CatalogRow = { selector: string; route: RouteResult }; +/** Read the same accepted provider roster as the other catalogs; do not start discovery here. */ +export function geminiNativeDiscoveredRoutes(config: OcxConfig, req: Request, selector?: string): CatalogRow[] { + const provider = config.providers[PROVIDER]; + if (!resolveProtocolSettings(config).rollout.geminiNativeAntigravity + || !provider || provider.disabled === true || provider.liveModels === false + || (selector !== undefined && !selector.startsWith(`${PROVIDER}/`))) return []; + const cached = getStaleCached(PROVIDER) ?? []; + const models = filterCatalogVisibleModels(cached.filter(model => + model.provider === PROVIDER && GEMINI_MODEL.test(model.id)), config); + return models.flatMap(({ id }) => { + const qualified = `${PROVIDER}/${id}`; + if (selector !== undefined && selector !== qualified) return []; + const destination = resolveNativeDestination(config, req, qualified); + return destination?.route.modelId === id ? [{ selector: qualified, route: destination.route }] : []; + }); +} + +function nativeModelDisabled(config: OcxConfig, modelId: string): boolean { + return config.disabledModels?.some(slug => slugEquals(slug, PROVIDER, modelId)) ?? false; +} + export function geminiNativeCatalogLookup( config: OcxConfig, req: Request, alias: string, rows: () => readonly CatalogRow[], scope?: AdmissionModelScope, ): CatalogRow | undefined { @@ -52,7 +76,8 @@ export function geminiNativeCatalogLookup( } function advertisedWireModels(config: OcxConfig, route: RouteResult): string[] { - return [undefined, "low", "medium", "high"].flatMap(effort => nativeWireModel(config, route, effort) ?? []); + if (route.providerName !== PROVIDER || nativeModelDisabled(config, route.modelId)) return []; + return [undefined, "low", "medium", "high", "xhigh"].flatMap(effort => nativeWireModel(config, route, effort) ?? []); } export function geminiNativeCatalogAliases( diff --git a/src/server/gemini-native-wire.ts b/src/server/gemini-native-wire.ts index e195b8eca38..369c812086c 100644 --- a/src/server/gemini-native-wire.ts +++ b/src/server/gemini-native-wire.ts @@ -1,11 +1,46 @@ +import { usageFromGemini } from "../adapters/google-usage"; +import type { OcxUsage } from "../types"; + /** Gemini payloads remain source text: parsing is validation, never serialization. */ export const GEMINI_NATIVE_MAX_BYTES = 16 * 1024 * 1024; export const GEMINI_NATIVE_ERROR_CODE = "gemini_native_upstream_error"; const SAFE_UPSTREAM_ERROR = '{"error":{"code":502,"message":"Antigravity upstream rejected the request","status":"INTERNAL"}}'; -export function validateGeminiObject(raw: string): void { - const value: unknown = JSON.parse(raw); - if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected a JSON object"); +function jsonObject(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : undefined; +} + +export function validateGeminiObject(raw: string): Record { + const object = jsonObject(JSON.parse(raw)); + if (!object) throw new Error("expected a JSON object"); + return object; +} + +const GEMINI_THINKING_LEVEL = /^(minimal|low|medium|high|xhigh)$/i; +const ANTIGRAVITY_WIRE_EFFORT = /-(low|medium|high|xhigh)$/; + +/** Capture only reasoning values sent on the wire, without rewriting the request. */ +export function geminiNativeReasoningFields(body: Record, model: string) { + const wireEffort = ANTIGRAVITY_WIRE_EFFORT.exec(model)?.[1]; + const generation = jsonObject(body.generationConfig ?? body.generation_config); + const thinking = jsonObject(generation?.thinkingConfig ?? generation?.thinking_config); + const level = thinking?.thinkingLevel ?? thinking?.thinking_level; + if (typeof level === "string" && GEMINI_THINKING_LEVEL.test(level)) { + const requestedEffort = level.toLowerCase(); + return { + requestedEffort, effectiveEffort: wireEffort ?? requestedEffort, + reasoningWireField: "thinkingLevel", reasoningWireValue: level, + }; + } + const budget = thinking?.thinkingBudget ?? thinking?.thinking_budget; + if (level === undefined && typeof budget === "number" && Number.isSafeInteger(budget) && budget >= -1) { + return { + requestedEffort: budget === -1 ? "auto" : budget === 0 ? "none" : String(budget), + effectiveEffort: wireEffort, + reasoningWireField: "thinkingBudget", reasoningWireValue: budget === -1 ? "-1" : budget, + }; + } + return { effectiveEffort: wireEffort }; } /** Find a top-level member's original value, including exact numeric/string spelling. */ @@ -74,10 +109,16 @@ export function wrapGeminiRequest(raw: string, model: string, project: string): return `${envelope.slice(0, -1)},"request":${raw}}`; } +interface GeminiStreamObservers { + onNativeError?: () => void; + onUsage?: (usage: OcxUsage) => void; + onOutput?: (visible: boolean, thought: boolean) => void; +} + /** Decode bounded upstream SSE events and frame the unwrapped JSON for the client. */ export function geminiSseTransform( maxBytes = GEMINI_NATIVE_MAX_BYTES, - onNativeError?: () => void, + observers?: GeminiStreamObservers, format: "sse" | "array" = "sse", credentials: readonly string[] = [], ): TransformStream { @@ -86,25 +127,47 @@ export function geminiSseTransform( let lineParts: string[] = [], data: string[] = [], eventBytes = 0, afterCR = false; const candidates = new Map(); let terminal = false, blocked = false, arrayOpened = false; + let usage: OcxUsage | undefined; + const reportUsage = () => { + if (!usage) return; + try { observers?.onUsage?.(usage); } catch { /* Observational callbacks never change delivery. */ } + }; const complete = () => candidates.size ? [...candidates.values()].every(Boolean) : blocked; const closeArray = (controller: TransformStreamDefaultController) => { if (format === "array") controller.enqueue(encoder.encode("\n]")); }; function observe(raw: string) { - const value = JSON.parse(raw) as { candidates?: Array<{ index?: number; finishReason?: string }>; error?: unknown; promptFeedback?: { blockReason?: string } }; + const value = JSON.parse(raw) as { + candidates?: Array<{ index?: number; finishReason?: string; content?: { parts?: unknown } }>; + promptFeedback?: { blockReason?: string }; + usageMetadata?: unknown; + }; if (Object.hasOwn(value, "error") || containsGeminiCredential(raw, credentials)) { terminal = true; - try { onNativeError?.(); } catch { /* Observational callbacks never change delivery. */ } + try { observers?.onNativeError?.(); } catch { /* Observational callbacks never change delivery. */ } return SAFE_UPSTREAM_ERROR; } blocked ||= !!value.promptFeedback?.blockReason; if (value.candidates !== undefined && !Array.isArray(value.candidates)) throw new Error("invalid Gemini candidates"); + let visible = false, thought = false; for (const [position, candidate] of (value.candidates ?? []).entries()) { if (!candidate || typeof candidate !== "object") throw new Error("invalid Gemini candidate"); const index = candidate.index ?? position; if (!Number.isSafeInteger(index) || index < 0 || candidates.size >= 1024 && !candidates.has(index)) throw new Error("invalid Gemini candidate index"); candidates.set(index, candidates.get(index) === true || typeof candidate.finishReason === "string" && candidate.finishReason.length > 0); + if (observers?.onOutput && Array.isArray(candidate.content?.parts)) { + for (const rawPart of candidate.content.parts) { + const part = jsonObject(rawPart); + if (!part || !(typeof part.text === "string" && part.text.length > 0) && !jsonObject(part.functionCall ?? part.function_call)) continue; + if (part.thought === true) thought = true; + else visible = true; + } + } + } + if (visible || thought) { + try { observers?.onOutput?.(visible, thought); } catch { /* Observational callbacks never change delivery. */ } } + if (observers?.onUsage) usage = usageFromGemini(value.usageMetadata) ?? usage; return raw; } function emit(controller: TransformStreamDefaultController) { @@ -112,6 +175,7 @@ export function geminiSseTransform( const payload = data.join("\n"); if (payload.trim() === "[DONE]") { if (!complete()) throw new Error("premature Gemini stream terminator"); + reportUsage(); terminal = true; } else { const response = observe(unwrapGeminiResponse(payload)); @@ -168,6 +232,7 @@ export function geminiSseTransform( if (tail) lineParts.push(tail); if (lineParts.join("").trim() || data.length) throw new Error("truncated Gemini SSE event"); if (!complete()) throw new Error("incomplete Gemini generation"); + reportUsage(); closeArray(controller); }, }); diff --git a/src/server/gemini-native.ts b/src/server/gemini-native.ts index f34511bc358..8468c8a906b 100644 --- a/src/server/gemini-native.ts +++ b/src/server/gemini-native.ts @@ -1,68 +1,87 @@ -import type { OcxConfig } from "../types"; +import type { OcxConfig, OcxUsage } from "../types"; +import { markNativeGeminiProtocol } from "../protocols/trace"; import { getValidAccessSnapshotForAccount, forceRefreshOAuthAccessSnapshot, OAuthLoginRequiredError, OAuthAccountPausedError, OAuthTokenRefreshBusyError, OAuthTokenRefreshStaleError, type OAuthAccessSnapshot } from "../oauth"; import { getAccountSet, getAccountCredentialWithStatus } from "../oauth/store"; +import { + antigravityModelRefusal, isProactivePreferenceEnabled, noteGenericPoolSelection, preferredInitialAccount, routeAntigravityModel, +} from "../oauth/generic-account-failover"; +import { stampOAuthAccountLabel } from "../providers/label"; import { getProviderRegistryEntry } from "../providers/registry"; import { sendTrackingRequestSlot, waitForProviderRequestSlot, RequestPacingQueueOverloadError, RequestPacingProviderRemovedError } from "../providers/request-pacing"; +import { usageFromGemini } from "../adapters/google-usage"; import { antigravityUserAgentForWireModel } from "../adapters/google-antigravity-wire"; import { fetchWithAttemptDeadline, releaseResponseBodyBestEffort } from "../lib/upstream-retry"; import { reserveWorkflowSend } from "../lib/workflow-budget"; import { currentWorkflowBudgetPolicy } from "../lib/workflow-budget-config"; import { spendPolicyFromConfig } from "../lib/spend-reservation-ledger"; import { carryWorkflowRefusal, workflowRefusalResponse } from "./workflow-refusal"; -import { geminiErrorBody } from "./gemini-inbound"; -import type { RequestLogContext } from "./request-log"; +import { geminiErrorBody, toGeminiRefusal } from "./gemini-inbound"; +import { estimateTokens } from "../lib/token-estimate"; +import { createPhysicalSendReporter } from "../lib/request-execution-budget"; +import { createInferenceSendBudget } from "./inference/context"; +import { attachRequestSpendTracker } from "./responses/request-spend"; +import { markLocalRequestLogRefusal, type RequestLogContext } from "./request-log"; +import { recordGenerationOutput } from "./request-log-generation-window"; +import { noteCredentialAttemptSend, sealCredentialRefusal } from "./credential-recovery-attempt"; import { DEFAULT_STALL_TIMEOUT_SEC, resolveStallTimeoutMs } from "../stall-timeout"; import { isLocalUpstream } from "../lib/local-upstream"; import { assertProviderDestinationAllowed } from "../lib/destination-policy"; +import { clientFacingModelLabel, type ClientFacingModelLabel } from "../lib/error-destination"; import { registerTurn, unregisterTurn, type ActiveTurnLease } from "./lifecycle"; -import { containsGeminiCredential, geminiSseTransform, readGeminiText, validateGeminiObject, GEMINI_NATIVE_MAX_BYTES, GEMINI_NATIVE_ERROR_CODE, unwrapGeminiResponse, wrapGeminiRequest } from "./gemini-native-wire"; +import { containsGeminiCredential, geminiNativeReasoningFields, geminiSseTransform, readGeminiText, validateGeminiObject, GEMINI_NATIVE_MAX_BYTES, GEMINI_NATIVE_ERROR_CODE, unwrapGeminiResponse, wrapGeminiRequest } from "./gemini-native-wire"; export const GEMINI_NATIVE_PROVIDER = "google-antigravity"; class NativeWorkflowSendDenied extends Error {} -class NativeSpendLimitsUnsupported extends Error {} class NativeRequestBodyTimeout extends Error {} class NativeConfigurationInvalid extends Error {} +class NativeModelUnavailable extends Error {} export function geminiNativeError(status: number, message: string, reason?: string): Response { const { error } = geminiErrorBody(status, message); return Response.json({ error: { ...error, ...(reason ? { details: [{ reason }] } : {}) } }, { status }); } export interface GeminiNativeDeps { - access: () => Promise; + access: (config: OcxConfig, model: string, clientModel: ClientFacingModelLabel) => Promise; refresh: (snapshot: OAuthAccessSnapshot) => Promise; fetch: typeof globalThis.fetch; } const defaults: Omit = { - access: async () => { + access: async (config, model, clientModel) => { const set = getAccountSet(GEMINI_NATIVE_PROVIDER); if (!set) throw new OAuthLoginRequiredError(GEMINI_NATIVE_PROVIDER); - return getValidAccessSnapshotForAccount(GEMINI_NATIVE_PROVIDER, set.activeAccountId, { requireUsableAccount: true }); + const now = Date.now(); + const planned = preferredInitialAccount(config, GEMINI_NATIVE_PROVIDER, now, model) ?? set.activeAccountId; + const route = routeAntigravityModel(config, GEMINI_NATIVE_PROVIDER, planned, model, now, clientModel); + if (route.kind === "refuse") throw new NativeModelUnavailable(route.message); + const accountId = route.kind === "reroute" ? route.accountId : planned; + return getValidAccessSnapshotForAccount(GEMINI_NATIVE_PROVIDER, accountId, { requireUsableAccount: true }); }, refresh: forceRefreshOAuthAccessSnapshot, }; -/** Active-account native leg; no internal messages, tool-schema repair or model rewriting. */ +/** Native leg using an account-scoped Antigravity token and project. */ export async function handleGeminiNative( req: Request, config: OcxConfig, model: string, streamFormat: "sse" | "array" | undefined, - lease: ActiveTurnLease, deps: GeminiNativeDeps = { ...defaults, fetch: globalThis.fetch }, logCtx?: RequestLogContext, + lease: ActiveTurnLease, deps: GeminiNativeDeps = { ...defaults, fetch: globalThis.fetch }, logCtx?: RequestLogContext, start?: number, ): Promise { const rootId = req.headers.get("x-codex-parent-thread-id")?.trim() || undefined; - // This source-preserving path does not yet book or settle token spend. Refuse applicable - // ceilings rather than allowing an unmeasured request to escape the common ledger. - const spendUnsupported = () => { + if (!logCtx) { const policy = spendPolicyFromConfig(config.spend); - return policy.identity.maxTokens !== undefined || policy.pool.maxTokens !== undefined - || rootId !== undefined && policy.root.maxTokens !== undefined; - }; - const unsupportedSpend = () => geminiNativeError(503, - "Gemini native requests do not support configured token spend limits; use a translated OC route", - "gemini_native_spend_limits_unsupported"); - if (spendUnsupported()) return unsupportedSpend(); + if (policy.identity.maxTokens !== undefined || policy.pool.maxTokens !== undefined + || (rootId !== undefined && policy.root.maxTokens !== undefined)) { + return geminiNativeError(503, "Token budget accounting is unavailable for this request"); + } + } const provider = config.providers[GEMINI_NATIVE_PROVIDER]; if (!provider || provider.disabled === true) return geminiNativeError(503, "Enable google-antigravity and sign in before using Gemini native requests"); if (provider.adapter !== "google" || (provider.authMode && provider.authMode !== "oauth") || (provider.googleMode && provider.googleMode !== "cloud-code-assist")) { return geminiNativeError(503, "Gemini native requests require a Google Antigravity OAuth provider"); } if (req.headers.get("content-encoding") && req.headers.get("content-encoding") !== "identity") return geminiNativeError(415, "Gemini native requests require identity content encoding"); + // Native admission accepts the canonical provider's implicit OAuth mode. Account helpers + // require an explicit mode, so give them the same default without changing saved settings. + const accountConfig: OcxConfig = provider.authMode === undefined ? { + ...config, providers: { ...config.providers, [GEMINI_NATIVE_PROVIDER]: { ...provider, authMode: "oauth" } }, + } : config; const ac = new AbortController(); const onAbort = () => ac.abort(req.signal.reason); req.signal.addEventListener("abort", onAbort, { once: true }); @@ -89,6 +108,23 @@ export async function handleGeminiNative( const noteNativeError = () => { if (logCtx) { logCtx.errorCode = GEMINI_NATIVE_ERROR_CODE; logCtx.terminalSource = "upstream"; } }; + let sawThoughtOutput = false; + const noteUsage = logCtx ? (usage: OcxUsage) => { + logCtx.usage = usage; + // Reported thought tokens count in the numerator. Their generation must also be observed. + if (usage.reasoningOutputTokens && !sawThoughtOutput) { + delete logCtx.generationStartedAt; + delete logCtx.lastOutputAt; + } + } : undefined; + const noteOutput = logCtx && start !== undefined ? (visible: boolean, thought: boolean) => { + const now = Date.now(); + sawThoughtOutput ||= thought; + recordGenerationOutput(logCtx, now); + if (visible) logCtx.firstOutputMs ??= Math.max(0, now - start); + } : undefined; + const spendTracker = logCtx ? attachRequestSpendTracker(req, logCtx) : undefined; + const physicalBudget = logCtx ? createInferenceSendBudget(req, logCtx) : undefined; let upstream: Response | undefined; try { const maxBytes = Math.min(GEMINI_NATIVE_MAX_BYTES, config.maxInboundBodyBytes ?? GEMINI_NATIVE_MAX_BYTES); @@ -110,9 +146,25 @@ export async function handleGeminiNative( finish(); return geminiNativeError(400, "Gemini request body must be readable UTF-8 JSON"); } finally { clearTimeout(bodyReadTimer); bodyReadTimer = undefined; } if (raw === null) { finish(); return geminiNativeError(413, "Gemini native request exceeds the body limit"); } - try { validateGeminiObject(raw); } - catch { finish(); return geminiNativeError(400, "Expected a Gemini JSON object"); } - let access = await deps.access(); + let reasoning: ReturnType | undefined; + try { + const payload = validateGeminiObject(raw); + if (logCtx) { + reasoning = geminiNativeReasoningFields(payload, model); + const generation = (payload.generationConfig ?? payload.generation_config) as Record | undefined; + const maxOutput = generation?.maxOutputTokens ?? generation?.max_output_tokens; + const candidates = generation?.candidateCount ?? generation?.candidate_count; + const candidateCount = typeof candidates === "number" && Number.isSafeInteger(candidates) && candidates > 0 ? candidates : 1; + // Measure the native JSON for reservation only. Usage comes from the upstream response. + logCtx.spendInputEstimateTokens = estimateTokens(raw, model); + if (typeof maxOutput === "number" && Number.isSafeInteger(maxOutput) && maxOutput > 0) { + logCtx.spendOutputCeilingTokens = Math.min(Number.MAX_SAFE_INTEGER, maxOutput * candidateCount); + } + } + } catch { finish(); return geminiNativeError(400, "Expected a Gemini JSON object"); } + ac.signal.throwIfAborted(); + const clientModel = clientFacingModelLabel(logCtx?.requestedModel ?? model); + let access = await deps.access(accountConfig, model, clientModel); const boundCredentials = new Set(); for (let attempt = 0; attempt < 2; attempt++) { ac.signal.throwIfAborted(); @@ -124,34 +176,61 @@ export async function handleGeminiNative( } catch { throw new NativeConfigurationInvalid(); } const method = streamFormat ? "streamGenerateContent?alt=sse" : "generateContent"; const slot = await waitForProviderRequestSlot(GEMINI_NATIVE_PROVIDER, provider, model, ac.signal); - upstream = await sendTrackingRequestSlot(slot, () => { + upstream = await sendTrackingRequestSlot(slot, async () => { ac.signal.throwIfAborted(); // A pacing wait must not outlive an operator pause, reauth mark or account removal. const account = getAccountCredentialWithStatus(GEMINI_NATIVE_PROVIDER, access.accountId); if (!account) throw new OAuthLoginRequiredError(GEMINI_NATIVE_PROVIDER); if (account.paused) throw new OAuthAccountPausedError(); if (account.needsReauth) throw new OAuthLoginRequiredError(GEMINI_NATIVE_PROVIDER); - if (spendUnsupported()) throw new NativeSpendLimitsUnsupported(); - if (!reserveWorkflowSend(rootId, currentWorkflowBudgetPolicy())) throw new NativeWorkflowSendDenied(); + const refusal = antigravityModelRefusal(accountConfig, GEMINI_NATIVE_PROVIDER, access.accountId, model, undefined, clientModel); + if (refusal) throw new NativeModelUnavailable(refusal); const { credential } = account; // Keep both generations across a 401 recovery. The store can also rotate during pacing. for (const value of [access.accessToken, access.projectId, access.accountId, credential.access, credential.refresh, credential.projectId, credential.accountId, credential.email]) { if (value) boundCredentials.add(value); } - return fetchWithAttemptDeadline(`${baseUrl.replace(/\/$/, "")}/v1internal:${method}`, { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${access.accessToken}`, "User-Agent": antigravityUserAgentForWireModel(model) }, - body: wrapGeminiRequest(raw, model, access.projectId!), - }, config.connectTimeoutMs ?? 200_000, ac.signal, true, deps.fetch); + const body = wrapGeminiRequest(raw, model, access.projectId!); + if (logCtx) stampOAuthAccountLabel(logCtx, GEMINI_NATIVE_PROVIDER, { authMode: "oauth" }, access.accountId); + const report = physicalBudget && createPhysicalSendReporter(physicalBudget, () => ({ + poolId: GEMINI_NATIVE_PROVIDER, identityId: logCtx?.accountLogLabel, + })); + let dispatched = false; + try { + if (report ? !report.beforeSend?.(attempt > 0) : !reserveWorkflowSend(rootId, currentWorkflowBudgetPolicy())) { + throw new NativeWorkflowSendDenied(); + } + if (attempt === 0 && isProactivePreferenceEnabled(accountConfig, GEMINI_NATIVE_PROVIDER, Date.now())) { + noteGenericPoolSelection(accountConfig, GEMINI_NATIVE_PROVIDER, access.accountId, model); + } + if (logCtx) { + Object.assign(logCtx, reasoning); + markNativeGeminiProtocol(logCtx); + noteCredentialAttemptSend(logCtx, { providerName: GEMINI_NATIVE_PROVIDER, modelId: model }, provider, + attempt === 0 ? undefined : "oauth-401"); + Object.assign(logCtx.activeAttempt!, reasoning); + } + dispatched = true; + return await fetchWithAttemptDeadline(`${baseUrl.replace(/\/$/, "")}/v1internal:${method}`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${access.accessToken}`, "User-Agent": antigravityUserAgentForWireModel(model) }, + body, + }, config.connectTimeoutMs ?? 200_000, ac.signal, true, deps.fetch); + } finally { + try { if (dispatched) report?.(1); } + finally { report?.close?.(); } + } }); if (upstream.status !== 401 || attempt === 1) break; + if (logCtx) sealCredentialRefusal(logCtx, 401, "oauth-401"); await releaseResponseBodyBestEffort(upstream.body, ac.signal); ac.signal.throwIfAborted(); access = await deps.refresh(access); } if (!upstream) throw new Error("missing upstream response"); if (!upstream.ok) { + if (logCtx) logCtx.terminalSource = "upstream"; void upstream.body?.cancel().catch(() => {}); finish(); const response = geminiNativeError(upstream.status >= 400 ? upstream.status : 502, "Antigravity upstream rejected the request"); @@ -179,15 +258,20 @@ export async function handleGeminiNative( const credentials = [...boundCredentials]; if (streamFormat) { const headers = { "Content-Type": streamFormat === "sse" ? "text/event-stream" : "application/json", "Cache-Control": "no-cache" }; - return new Response(body.pipeThrough(geminiSseTransform(GEMINI_NATIVE_MAX_BYTES, noteNativeError, streamFormat, credentials)), { headers }); + return new Response(body.pipeThrough(geminiSseTransform( + GEMINI_NATIVE_MAX_BYTES, { onNativeError: noteNativeError, onUsage: noteUsage, onOutput: noteOutput }, streamFormat, credentials, + )), { headers }); } const text = await readGeminiText(body, GEMINI_NATIVE_MAX_BYTES, ac.signal); if (text === null) return geminiNativeError(502, "Gemini upstream response exceeds the body limit"); const response = unwrapGeminiResponse(text); - if (Object.hasOwn(JSON.parse(response), "error") || containsGeminiCredential(response, credentials)) { + const payload = JSON.parse(response) as { usageMetadata?: unknown }; + if (Object.hasOwn(payload, "error") || containsGeminiCredential(response, credentials)) { noteNativeError(); return geminiNativeError(502, "Antigravity upstream rejected the request"); } + const usage = usageFromGemini(payload.usageMetadata); + if (usage) noteUsage?.(usage); return new Response(response, { headers: { "Content-Type": "application/json" } }); } catch (error) { ac.abort(); finish(); @@ -208,8 +292,19 @@ export async function handleGeminiNative( if (error instanceof RequestPacingProviderRemovedError || error instanceof NativeConfigurationInvalid) { return geminiNativeError(503, "Antigravity provider configuration is unavailable or invalid; check its baseUrl and destination policy in OC settings"); } - if (error instanceof NativeSpendLimitsUnsupported) return unsupportedSpend(); + if (error instanceof NativeModelUnavailable) { + if (logCtx) { + logCtx.errorCode = "gemini_native_model_unlisted"; + markLocalRequestLogRefusal(logCtx, "gemini_native_model_unlisted"); + } + return geminiNativeError(403, error.message, "gemini_native_model_unlisted"); + } if (error instanceof NativeWorkflowSendDenied) { + const denial = spendTracker?.lastRefusal; + if (denial) { + const refusal = workflowRefusalResponse(denial.reason, logCtx, undefined, undefined, denial.spend); + return carryWorkflowRefusal(refusal, toGeminiRefusal(refusal)); + } const refusal = workflowRefusalResponse("workflow-sends-exhausted", logCtx, undefined, rootId); return carryWorkflowRefusal(refusal, geminiNativeError(429, "OpenCodex workflow physical-send budget exhausted")); } diff --git a/src/server/index/gemini-routes.ts b/src/server/index/gemini-routes.ts index 0d3c62780ed..357fa2b536f 100644 --- a/src/server/index/gemini-routes.ts +++ b/src/server/index/gemini-routes.ts @@ -15,6 +15,7 @@ import { SIDECAR_INTERNAL_CAPABILITY_HEADER } from "../advisor-admission-scope"; import { withCallerSessionIdentity } from "../caller-session-identity"; import { captureAdmissionPolicy } from "../capture-admission-policy"; import { isDraining } from "../lifecycle"; +import { resolveGeminiApiSurface } from "../../protocols/settings"; import { geminiRouteAllowHeader, geminiRouteAllows, parseGeminiNativePath, type GeminiNativeRoute } from "../gemini-native-paths"; import { geminiError, handleGeminiCountTokens, handleGeminiGeneration, handleGeminiModel, handleGeminiModels, toGeminiRefusal } from "../gemini-inbound"; import { handleGeminiInteraction, handleGeminiInteractionResource } from "../gemini-interactions-inbound"; @@ -62,6 +63,9 @@ async function handleGeminiRoute(route: GeminiNativeRoute, original: Request, ur refused.headers.set("Allow", geminiRouteAllowHeader(route)); return withCors(refused, original, policy); } + if (!resolveGeminiApiSurface(config).enabled) { + return withCors(geminiError(403, "Gemini API is disabled"), original, policy); + } const generation = route.kind === "interactions" || (route.kind === "method" && (route.method === "generateContent" || route.method === "streamGenerateContent")); if (generation) disableResponsesRequestTimeout(original, deps.requestServer); @@ -126,8 +130,9 @@ async function handleGeminiRoute(route: GeminiNativeRoute, original: Request, ur } else { logCtx.model = native.route.modelId; logCtx.provider = native.route.providerName; + logCtx.routeDecision = native.route.routeDecision; const delivery = route.method === "streamGenerateContent" ? (sse ? "sse" : "array") : undefined; - result = await handleGeminiNative(sessionReq, config, native.wireModel, delivery, turnAdmissionLease, undefined, logCtx); + result = await handleGeminiNative(sessionReq, config, native.wireModel, delivery, turnAdmissionLease, undefined, logCtx, start); } return withCors(logGeminiNativeDelivery(result, sessionReq, requestId, start, logCtx), original, policy); } diff --git a/src/server/management/api-access.ts b/src/server/management/api-access.ts index b840430d875..a4740cd801f 100644 --- a/src/server/management/api-access.ts +++ b/src/server/management/api-access.ts @@ -3,7 +3,7 @@ import { isWildcardHostname } from "../../codex/loopback-target"; import { localCredentialDestinationHostname, localInferenceDestination } from "../../lib/local-destinations"; import { isCanonicalOpenAiForwardProvider, OPENAI_API_PROVIDER_ID, OPENAI_CODEX_PROVIDER_ID } from "../../providers/openai-tiers-destination"; import { LIVE_AUDIO_MODEL, TRANSCRIPTION_MODEL } from "../audio-upstream"; -import { resolveApiSurfaceSettings, type ApiSurfaceSettings } from "../../protocols/settings"; +import { resolveApiSurfaceSettings, resolveGeminiApiSurface, type ApiSurfaceSetting, type ApiSurfaceSettings } from "../../protocols/settings"; export interface AudioApiAccess { transcriptionEndpoint: string; @@ -24,8 +24,9 @@ export interface ApiAccessEndpoints { chatCompletionsEndpoint: string; messagesEndpoint: string; modelsEndpoint: string; + geminiModelsEndpoint: string; /** Which public APIs are served and who decided it, from `resolveApiSurfaceSettings`. */ - surfaces: ApiSurfaceSettings; + surfaces: ApiSurfaceSettings & { gemini: ApiSurfaceSetting }; /** * Back-compat for dashboards that predate `surfaces`: they hide the Messages endpoint when * this is false. It mirrors `surfaces.messages.enabled`, not `claudeCode.enabled`, so an @@ -180,7 +181,8 @@ export function buildApiAccessEndpoints( chatCompletionsEndpoint: `${baseUrl}/chat/completions`, messagesEndpoint: `${baseUrl}/messages`, modelsEndpoint: `${baseUrl}/models`, - surfaces, + geminiModelsEndpoint: baseUrl.replace(/\/v1$/, "/v1beta/models"), + surfaces: { ...surfaces, gemini: resolveGeminiApiSurface(config) }, claudeCodeEnabled: surfaces.messages.enabled, audio: { transcriptionEndpoint: `${baseUrl}/audio/transcriptions`, diff --git a/src/server/management/protocol-routes.ts b/src/server/management/protocol-routes.ts index 2eca1eea959..73a5072c6f0 100644 --- a/src/server/management/protocol-routes.ts +++ b/src/server/management/protocol-routes.ts @@ -18,7 +18,7 @@ import { isProtocol, PROTOCOL_CONTRACT_VERSION } from "../../protocols/contract" import { isProtocolFeature, PROTOCOL_FEATURES, type ProtocolFeature } from "../../protocols/features"; import { previewProtocolPlan, type ProtocolPlanRequest } from "../../protocols/plan-snapshot"; import { buildProtocolProviderSummary } from "../../protocols/provider-summary"; -import { protocolPolicyRevision, resolveApiSurfaceSettings, resolveProtocolSettings } from "../../protocols/settings"; +import { protocolPolicyRevision, resolveApiSurfaceSettings, resolveGeminiApiSurface, resolveProtocolSettings } from "../../protocols/settings"; import type { OcxConfig } from "../../types"; import type { ManagementContext } from "./context"; import { readManagementJsonBodyOr } from "./body"; @@ -71,6 +71,8 @@ function protocolInfo(config: OcxConfig) { contractVersion: PROTOCOL_CONTRACT_VERSION, policyRevision: protocolPolicyRevision(config), surfaces: resolveApiSurfaceSettings(config), + // Older dashboards require exactly the three planning protocols inside surfaces. + geminiSurface: resolveGeminiApiSurface(config), settings: resolveProtocolSettings(config), features: PROTOCOL_FEATURES, }; diff --git a/src/server/management/protocol-settings-patch.ts b/src/server/management/protocol-settings-patch.ts index 05188aefa5e..f44ed43de44 100644 --- a/src/server/management/protocol-settings-patch.ts +++ b/src/server/management/protocol-settings-patch.ts @@ -17,6 +17,7 @@ import type { OcxConfig } from "../../types"; export interface ProtocolSettingsPatch { messagesEnabled?: boolean; + geminiEnabled?: boolean; unrepresentable?: UnrepresentablePolicy; rollout?: Partial; } @@ -25,7 +26,7 @@ export type ParsedProtocolSettingsPatch = | { ok: true; patch: ProtocolSettingsPatch } | { ok: false; code: string; message: string }; -const PATCH_KEYS = new Set(["messagesEnabled", "unrepresentable", "rollout"]); +const PATCH_KEYS = new Set(["messagesEnabled", "geminiEnabled", "unrepresentable", "rollout"]); export const PROTOCOL_ROLLOUT_KEYS = [ "nativeChatCombos", "managedMessagesNative", @@ -50,15 +51,19 @@ function invalid(code: string, message: string): ParsedProtocolSettingsPatch { export function parseProtocolSettingsPatch(body: unknown): ParsedProtocolSettingsPatch { if (!isRec(body)) return invalid("invalid_body", "body must be a JSON object"); const keys = Object.keys(body); - if (keys.length === 0) return invalid("empty_body", "body must set messagesEnabled, unrepresentable or rollout"); + if (keys.length === 0) return invalid("empty_body", "body must set messagesEnabled, geminiEnabled, unrepresentable or rollout"); for (const key of keys) { - if (!PATCH_KEYS.has(key)) return invalid("unknown_field", "body accepts only messagesEnabled, unrepresentable and rollout"); + if (!PATCH_KEYS.has(key)) return invalid("unknown_field", "body accepts only messagesEnabled, geminiEnabled, unrepresentable and rollout"); } const patch: ProtocolSettingsPatch = {}; if (body.messagesEnabled !== undefined) { if (typeof body.messagesEnabled !== "boolean") return invalid("invalid_messages_enabled", "messagesEnabled must be a boolean"); patch.messagesEnabled = body.messagesEnabled; } + if (body.geminiEnabled !== undefined) { + if (typeof body.geminiEnabled !== "boolean") return invalid("invalid_gemini_enabled", "geminiEnabled must be a boolean"); + patch.geminiEnabled = body.geminiEnabled; + } if (body.unrepresentable !== undefined) { if (body.unrepresentable !== "legacy" && body.unrepresentable !== "reject") { return invalid("invalid_unrepresentable", "unrepresentable must be \"legacy\" or \"reject\""); @@ -131,14 +136,24 @@ export function applyProtocolSettingsPatch(config: OcxConfig, patch: ProtocolSet } let claudeCodeChanged = false; - if (patch.messagesEnabled !== undefined) { - // A malformed block is replaced, not merged: the explicit value is what the operator asked for. - const surfaces: Rec = isRec(config.apiSurfaces) ? { ...config.apiSurfaces } : {}; - const messages: Rec = isRec(surfaces.messages) ? { ...surfaces.messages } : {}; - messages.enabled = patch.messagesEnabled; - surfaces.messages = messages; + if (patch.messagesEnabled !== undefined || patch.geminiEnabled !== undefined) { + const current = config.apiSurfaces; + const surfaces: Rec = isRec(current) ? { ...current } : {}; + for (const [name, enabled] of [ + ["messages", patch.messagesEnabled], + ["gemini", patch.geminiEnabled], + ] as const) { + if (enabled === undefined) continue; + const surface = surfaces[name]; + surfaces[name] = { ...(isRec(surface) ? surface : {}), enabled }; + } + if (current !== undefined && !isRec(current)) { + // Repairing the malformed parent must preserve closed sibling surfaces. + if (patch.messagesEnabled === undefined) surfaces.messages = { enabled: false }; + if (patch.geminiEnabled === undefined) surfaces.gemini = { enabled: false }; + } config.apiSurfaces = surfaces as OcxConfig["apiSurfaces"]; - if (!patch.messagesEnabled && config.claudeCode?.enabled !== false) { + if (patch.messagesEnabled === false && config.claudeCode?.enabled !== false) { commitClaudeCodeBlock(config, { ...(config.claudeCode ?? {}), enabled: false }); claudeCodeChanged = true; } diff --git a/src/server/management/shared.ts b/src/server/management/shared.ts index d4575d07e19..9713b9851c4 100644 --- a/src/server/management/shared.ts +++ b/src/server/management/shared.ts @@ -59,7 +59,7 @@ import type { OcxClaudeCodeConfig, OcxClaudeDesktopProfile, OcxConfig, OcxCustom import type { DesktopProfileModel } from "../../claude/desktop-profile"; import { drainAndShutdown } from "../lifecycle"; import { filterRequestLogs, getRequestLogEntries, type RequestLogEntry } from "../request-log"; -import { creditChargeUnrepresentable, estimateComboCost, estimateRequestCost, serviceTierContext, normalizeCostTokens, tokensPerSecond } from "../../usage/cost"; +import { creditChargeUnrepresentable, estimateAttemptCost, estimateComboCost, estimateRequestCost, serviceTierContext, normalizeCostTokens, tokensPerSecond } from "../../usage/cost"; import { costTokensWithinBound, isRepresentableCreditCount } from "../../usage/credit-billing"; import type { PersistedUsageAttempt } from "../../usage/log"; import { usageModelPriceOptions } from "../../usage/model-identity"; @@ -87,7 +87,7 @@ export type MetricUnavailableReason = | "usage_missing" | "usage_unsupported" | "output_missing" | "invalid_duration" | "price_unmatched" | "invalid_cache_breakdown" | "invalid_usage" | "combo_attempt_unavailable" - | "ttft_missing" | "decode_window_too_short" + | "ttft_missing" | "decode_window_missing" | "decode_window_too_short" // The row is credit-priced, but `providerCredits x creditPriceUsd` cannot be represented (an // out-of-bound price or credit count, or an overflowing product). It is deliberately not // `price_unmatched`-with-a-token-estimate: falling back would report a different amount than @@ -112,9 +112,10 @@ export type CostEstimateReason = export type CostResult = | { kind: "value"; estimate: NonNullable>; estimateReasons: CostEstimateReason[] } + | { kind: "partial"; subtotalUsd: number; unpricedAttempts: number } | { kind: "unavailable"; reason: MetricUnavailableReason }; -export type MetricSource = Pick & { +export type MetricSource = Pick & { attempts?: readonly PersistedUsageAttempt[]; }; @@ -162,7 +163,7 @@ export const MIN_DECODE_WINDOW_MS = 1_000; * generation window spans both and stops at the last delta rather than at stream close. */ export function decodeTokPerSecondResult( - entry: Pick, + entry: Pick, ): DecodeTokPerSecondResult { if (!entry.usage) return { kind: "unavailable", reason: "usage_missing" }; if (entry.usageStatus === "unsupported") return { kind: "unavailable", reason: "usage_unsupported" }; @@ -176,6 +177,7 @@ export function decodeTokPerSecondResult( return value === null ? { kind: "unavailable", reason: "invalid_duration" } : { kind: "value", value, estimated: true, timingBasis: "generation-window" }; } + if (entry.protocolTrace?.inbound === "gemini") return { kind: "unavailable", reason: "decode_window_missing" }; // A row that predates TTFT capture, or a non-streaming turn that never recorded one, has no // window to measure. That is a different fact from a bad duration, so it gets its own reason. if (entry.firstOutputMs === undefined) return { kind: "unavailable", reason: "ttft_missing" }; @@ -245,7 +247,20 @@ export function costResult(entry: MetricSource): CostResult { const estimate = attempts?.length ? estimateComboCost(attempts, undefined, tier) : estimateRequestCost({ provider: entry.provider, model: entry.model, usage: entry.usage, usageStatus: entry.usageStatus, serviceTier: tier, ...usageModelPriceOptions(entry, entry) }); - if (!estimate) return { kind: "unavailable", reason: unavailableCostReason(entry) }; + if (!estimate) { + // Keep the shared request-total contract. Native Gemini credential replays can show a + // separate subtotal from the attempts for which we do have a price. + if (entry.protocolTrace?.inbound === "gemini" && entry.protocolTrace.mode === "native" + && attempts?.some(attempt => attempt.recoveryKinds.includes("oauth-401"))) { + const priced = attempts.flatMap(attempt => estimateAttemptCost(attempt, undefined, tier) ?? []); + const unpricedAttempts = attempts.length - priced.length; + const subtotalUsd = priced.reduce((sum, attempt) => sum + attempt.cost.total, 0); + if (priced.length && unpricedAttempts > 0 && Number.isFinite(subtotalUsd)) { + return { kind: "partial", subtotalUsd, unpricedAttempts }; + } + } + return { kind: "unavailable", reason: unavailableCostReason(entry) }; + } // Provenance follows the basis that produced the amount. A credit charge is // `providerCredits x creditPriceUsd`; the token rates were resolved only to decide whether the // row falls back to them, so anything derived from those rates — a cache-detail caveat, a price diff --git a/src/server/request-log-generation-window.ts b/src/server/request-log-generation-window.ts index 38503d38581..000ddd20e53 100644 --- a/src/server/request-log-generation-window.ts +++ b/src/server/request-log-generation-window.ts @@ -18,11 +18,16 @@ export function recordGenerationEvent(logCtx: RequestLogContext, type: unknown, if (type === "content_block_start" || type === "response.output_item.added") { logCtx.generationStartedAt ??= now; } else if (type === "content_block_delta" || (type.startsWith("response.") && type.endsWith(".delta"))) { - logCtx.generationStartedAt ??= now; - logCtx.lastOutputAt = now; + recordGenerationOutput(logCtx, now); } } +/** Mark the receipt of a generated delta after the protocol-specific decoder recognizes it. */ +export function recordGenerationOutput(logCtx: RequestLogContext, now = Date.now()): void { + logCtx.generationStartedAt ??= now; + logCtx.lastOutputAt = now; +} + /** Request-relative `genStartMs` / `lastOutputMs`, present only when both ends were observed. */ export function generationWindowFields( logCtx: Pick, diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index c087a7fd41d..88be963b493 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -210,7 +210,7 @@ import { usageFromResponsesPayload, type RequestLogContext, } from "../request-log"; -import { noteCompactAttemptSend, sealCredentialRefusal } from "../credential-recovery-attempt"; +import { noteCredentialAttemptSend, sealCredentialRefusal } from "../credential-recovery-attempt"; import type { AttemptRecoveryKind } from "../../usage/log"; import { consumeForInspection, @@ -1290,7 +1290,7 @@ export async function handleResponsesCompact( { ...init, headers: sendHeaders, body: JSON.stringify({ ...buildCompactSendBody() as typeof compactBody, model: route.modelId }) }, init.signal ?? req.signal, connectMs(), false, physicalFetch); } : undefined, - onPhysicalDispatch: () => { noteCompactAttemptSend(logCtx, route, sendProvider, receipt?.recovery ?? upstreamRecovery); receipt?.onDispatch?.(); }, + onPhysicalDispatch: () => { noteCredentialAttemptSend(logCtx, route, sendProvider, receipt?.recovery ?? upstreamRecovery); receipt?.onDispatch?.(); }, }), // Every credential-bearing forward send gets manual redirects, not only // pool sends: direct mode carries the caller's credential too (#914). diff --git a/src/types/config.ts b/src/types/config.ts index 1c2d01c51f3..e760899f19a 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -24,6 +24,8 @@ export interface OcxApiSurfacesConfig { * `claudeCode.enabled !== false`"; a present non-boolean value disables the surface. */ messages?: { enabled?: boolean }; + /** Gemini-compatible routes. The surface is open by default. */ + gemini?: { enabled?: boolean }; } /** Protocol delivery policy (devlog/_plan/260924_protocol_first_class). */ diff --git a/src/usage/expected-prices.ts b/src/usage/expected-prices.ts index 74c224af113..a4cca5d3dac 100644 --- a/src/usage/expected-prices.ts +++ b/src/usage/expected-prices.ts @@ -98,6 +98,16 @@ const GEMINI_38_FLASH: Cost4 = { input: 0.75, output: 3.75, cacheRead: 0.075, ca // per 1M through 2026-11-30, stepping up to $4 / $20 / $0.20 on 2026-12-01. Revisit this row // then. No free tier. Implicit caching only, so there is no per-token cache-write price. const GEMINI_4_ARGON: Cost4 = { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 }; +// Standard paid Gemini API rates. Antigravity uses the same token rates as an +// estimated reference. Its generation usage reports cache hits but no cache-write count. +const GEMINI_4_API_RATES = [ + { modelId: "gemini-4-hydrogen", cost4: { input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 0 } }, + { modelId: "gemini-4-neon", cost4: { input: 3, output: 15, cacheRead: 0.15, cacheWrite: 0 } }, +].map(row => ({ + ...row, + source: `https://ai.google.dev/gemini-api/docs/pricing#${row.modelId} (Standard paid tier)`, + verifiedAt: "2026-11-19", +})); const MINIMAX_M21_HIGHSPEED: Cost4 = { input: 0.6, output: 2.4, cacheRead: 0.03, cacheWrite: 0.375 }; const KIMI_K3: Cost4 = { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3 }; // K3.1 Pro and its highspeed variant: flat 1M-context pricing (no context tiering). Like K3, @@ -412,6 +422,12 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ // 3.7 Flash rides CCA, whose billing equivalence to the Developer API list price is // not published, so this is `verified-derived` rather than `verified`: the number is // proven, the claim that Antigravity charges it is inferred. + ...GEMINI_4_API_RATES.flatMap(row => [ + row.modelId, ...["low", "medium", "high", "xhigh"].map(effort => `${row.modelId}-${effort}`), + ].map(modelId => ({ + ...row, provider: "google-antigravity", modelId, + source: `derived: Gemini API reference price ${row.source}`, status: "verified-derived" as const, + }))), // Gemini 4 Argon on Antigravity (AI Ultra / Enterprise only): the picker id plus its three // verified CCA wire ids. Billing equivalence to the API price is inferred. { provider: "google-antigravity", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: `derived: Gemini 4 Argon introductory rate through 2026-11-30 ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, @@ -471,6 +487,7 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ { provider: "google-antigravity", modelId: "gemini-3.5-flash-high", cost4: GEMINI_36_FLASH, source: `compat alias -> gemini-3.6-flash-high ${GEMINI_PRICING}`, verifiedAt: "2026-07-22", status: "verified-derived" }, { provider: "google-antigravity", modelId: "gemini-3-flash-agent", cost4: GEMINI_36_FLASH, source: `compat alias -> gemini-3.6-flash-high ${GEMINI_PRICING}`, verifiedAt: "2026-07-22", status: "verified-derived" }, // Direct Google Gemini API current model (verified — published table). + ...GEMINI_4_API_RATES.map(row => ({ ...row, provider: "google", status: "verified" as const })), { provider: "google", modelId: "gemini-3.6-flash", cost4: GEMINI_36_FLASH, source: GEMINI_PRICING, verifiedAt: "2026-07-22", status: "verified" }, // Developer API row: the price IS published for this surface, so `verified`. { provider: "google", modelId: "gemini-3.7-flash", cost4: GEMINI_37_FLASH, source: GEMINI_37_PRICING, verifiedAt: "2026-08-14", status: "verified" }, diff --git a/src/usage/telemetry-contract.ts b/src/usage/telemetry-contract.ts index e6056ab1dcf..bce04d35474 100644 --- a/src/usage/telemetry-contract.ts +++ b/src/usage/telemetry-contract.ts @@ -12,6 +12,9 @@ * being a contract. */ +/** Public, opaque account labels used by the usage log and dashboard. */ +export const ACCOUNT_LOG_LABEL_RE = /^(?:main|[po][a-f0-9]{6}|k[a-f0-9]{32})$/; + /** * Recovery kinds recorded per attempt in the usage log; the dashboard renders localized labels * for these wire values. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 01a766602da..2ee9dce4013 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -331,7 +331,7 @@ selectors, a vendor-only inferred price is unavailable; exact provider and user eligible. Missing trace evidence is not reconstructed from today's configuration. Provider-detail model shares use that provider's token total, not the global total. Unknown reserved `policy/` selectors are rejected before upstream dispatch; historical rows remain unchanged. -Haiku 5.5 in `src/usage/expected-prices.ts` uses 0.10/0.50/0.01/0.125 USD per MTok (input/output/cache read/5m write), with all four rates multiplied by five above 100,000 raw prompt tokens; exactly 100,000 stays base. Exact provider/id bands include Cursor regular effort spellings and reference-priced preemptive surfaces; Kilo stays untiered. Sonnet 5.5 cache read is 0.10 (0.05x input), except Bedrock retains partner rates and Venice has its 1.25x exact overlay. Expected-price overlays are estimates, not billing reproductions: the Z.AI GLM rows (`zai`, `zhipu-bigmodel`, `zhipu-bigmodel-coding`, `zhipu-bigmodel-responses`) display the published z.ai USD list price on surfaces that actually bill by Coding Plan subscription or CNY-tiered domestic PAYG, and every such row is marked `verified-derived` so the estimate flag reaches the UI. Antigravity Claude Sonnet and Opus 5.5 base/tier overlays in `src/usage/expected-prices.ts` likewise use Anthropic reference prices with `verified-derived`, so even reported tokens retain an estimated-cost flag. +Haiku 5.5 in `src/usage/expected-prices.ts` uses 0.10/0.50/0.01/0.125 USD per MTok (input/output/cache read/5m write), with all four rates multiplied by five above 100,000 raw prompt tokens; exactly 100,000 stays base. Exact provider/id bands include Cursor regular effort spellings and reference-priced preemptive surfaces; Kilo stays untiered. Sonnet 5.5 cache read is 0.10 (0.05x input), except Bedrock retains partner rates and Venice has its 1.25x exact overlay. Expected-price overlays are estimates, not billing reproductions: the Z.AI GLM rows (`zai`, `zhipu-bigmodel`, `zhipu-bigmodel-coding`, `zhipu-bigmodel-responses`) display the published z.ai USD list price on surfaces that actually bill by Coding Plan subscription or CNY-tiered domestic PAYG, and every such row is marked `verified-derived` so the estimate flag reaches the UI. Antigravity base and effort overlays in `src/usage/expected-prices.ts` use Anthropic API reference prices for Claude Sonnet and Opus 5.5 and standard Gemini API rates for Gemini 4 Neon and Hydrogen. These rows carry `verified-derived`, so reported tokens still produce an estimated cost. The management API retains the compact accumulator plus bounded query summaries; it never retains normalized per-request rows after a response. File identity changes, shrinkage, same-size metadata @@ -568,10 +568,10 @@ labels collapse for reporting; configured provider names ending in `-main` remai The Logs request detail headline prefers a recognized request-level cause over the HTTP status label and omits the status description; unknown persisted causes are dropped and use the status fallback without raw attribution. Physical sends are unavailable for absent or invalid spend; retries appear only for one attempt with fully settled, consistent accounting and no flagged loss during attempt normalization, as sends after the first, floored at zero. Direct request-log ingress validates attempts with the persistence normalization rule, marks any loss, and retains the original live roster and its metadata. The ledger writer removes malformed attempts and persists the loss flag, so hydrated rosters can differ from live ones; both suppress retries when loss is marked. A loss detected while normalizing a legacy row is a non-enumerable in-memory flag, retained through re-normalization without changing JSON serialization; an explicitly persisted true flag stays enumerable. The persisted-to-request-log conversion and direct DTO projection preserve the flag. Other attempts and recovery reasons remain visible. Rows also carry the observed protocol path (`protocolTrace`), persisted in `usage.jsonl` and re-validated on read; the Logs list shows it as a text badge, the detail dialog as a section, and `src/server/request-log-filter.ts` owns the `/api/logs` query filters including `protocolMode`; its single-pass query applies provider, conversation, model, account, protocol mode and status before `tail`, then reports the pre-pagination count alongside the offset/limit page. `src/server/request-log-filter.ts` accepts the full provider/model label shown by `ocx logs` and bare model IDs, including IDs containing slashes. Qualified failover matches bind provider/model from the same attempt; matching occurs before the row cap and pagination. -[Protocol Paths](data-planes/protocol-paths.md) owns its derivation. +[Protocol Paths](data-planes/protocol-paths.md) owns its derivation. The upstream attempts table displays validated opaque account labels, and [native Gemini replays](data-planes/gemini-native.md) can show a cost subtotal. Conversation searches in the dashboard, `/api/logs` and `ocx logs filter --conversation` accept `codex://threads/` links up to 512 characters, including query/fragment metadata, trailing slashes and surrounding whitespace. The server matcher in `src/server/request-log-conversation.ts` and its browser mirror in `gui/src/log-conversation-id.ts` try both the extracted single-segment id and the original trimmed query, preserving raw-id and whole-literal-URI digest matching. The prefix is case-insensitive; the id retains its case. Malformed or longer links remain plain queries subject to the existing 4096-character digest-input bound. A pasted Claude Code `metadata.user_id` adds one more candidate, the JSON object without its per-turn `tk` (`claudeSessionUserId`), because the Messages inbound stores the session under that form; any turn's `user_id` therefore finds the whole session, and the raw candidate still matches rows logged before `tk` was stripped. A query over 4096 characters is not parsed. `conversationIdFromClaudeMetadata`, like the inbound cache key, drops `tk` at any length before applying that bound, so an oversized `tk` keeps the session id that also gates Claude routing identity. Persistence is unchanged. -Rows may also carry `genStartMs` and `lastOutputMs`, an observed request-relative pair recorded by `src/server/request-log-generation-window.ts` from the Responses and Anthropic SSE taps: the first output item or content block (reasoning included) to the last output delta. They are proxy observation times, not provider-internal token timing, and `src/usage/log.ts` keeps them only as a pair of nonnegative finite values with `lastOutputMs >= genStartMs`. `decodeTokPerSecondResult` in `src/server/management/shared.ts` prefers that window when the pair is valid and otherwise falls back to the post-TTFT window (`durationMs - firstOutputMs`); both keep the one-second minimum, the `ttft_missing` / `decode_window_too_short` unavailable reasons and `estimated: true`, so a short measured window is still an estimate rather than a provider decode benchmark. The end-to-end tok/s column is unchanged, attempts carry no generation window of their own, and the request-history view does not present one. Successful decode DTOs additionally expose `timingBasis: "generation-window" | "legacy-post-visible-output"`, derived at read time only. Logs labels the method “Generation window” or “After visible output” in the list and attempt table and uses “Output rate during generation (est.)” or “Output rate after first visible output (est.)” in request details. Missing or unfamiliar bases show “Timing unknown” and “Output rate (est.; timing method unknown)” in details rather than inferring a method. The detail grid shows a full-width muted caption explaining the method only when the decode rate is available. Both numerators include reported reasoning output tokens, so the two estimates are not directly comparable. Historical JSONL and end-to-end rates are unchanged. +Rows may also carry `genStartMs` and `lastOutputMs`, an observed request-relative pair recorded by `src/server/request-log-generation-window.ts` from Responses and Anthropic SSE taps and from native Gemini text and tool-call deltas. For Responses and Anthropic, the window starts at `response.output_item.added` or `content_block_start` respectively, even when that event carries no output. The first output delta starts the window if there is no preceding start event. For native Gemini, the first text or tool-call delta starts the window, including reasoning deltas. The last output delta closes the window for all three protocols. They are proxy observation times, not provider-internal token timing, and `src/usage/log.ts` keeps them only as a pair of nonnegative finite values with `lastOutputMs >= genStartMs`. `decodeTokPerSecondResult` in `src/server/management/shared.ts` prefers that window when the pair is valid. At stream completion, native Gemini discards the window if final usage reports thought tokens and the stream contained no thought delta. Native Gemini rows without a complete window return `decode_window_missing`. Other rows without the pair use the post-TTFT window (`durationMs - firstOutputMs`). Only that fallback returns `ttft_missing` when `firstOutputMs` is absent. Both methods return `decode_window_too_short` for positive windows shorter than one second and label calculated rates with `estimated: true`. The end-to-end tok/s column is unchanged, attempts carry no generation window of their own, and the request-history view does not present one. Successful decode DTOs additionally expose `timingBasis: "generation-window" | "legacy-post-visible-output"`, derived at read time only. Logs labels the method “Generation window” or “After visible output” in the list and attempt table and uses “Output rate during generation (est.)” or “Output rate after first visible output (est.)” in request details. Missing or unfamiliar bases show “Timing unknown” and “Output rate (est.; timing method unknown)” in details rather than inferring a method. The detail grid shows a full-width muted caption explaining the method only when the decode rate is available. Both numerators include reported reasoning output tokens, so the two estimates are not directly comparable. Historical JSONL and end-to-end rates are unchanged. Request-history selectors longer than 130 characters persist as a prefix plus a digest of the complete selector; exact-match filtering uses the same idempotent encoding. The derived index rebuilds when its diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 798dee0e524..79d81c45613 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -20,6 +20,13 @@ package-tree fence answers them in the Gemini error shape. The unauthenticated d allowlist admits each path with its own HTTP method only (a wrong method is a 404 there, not the 405), because `ocx connect agy` points the CLI at that socket; admission still comes from the receiving listener's policy, as for the chat wire. OPTIONS takes data-plane origin policy. +The gateway serves these routes by default. An explicit false or malformed Gemini surface setting +returns a Gemini-shaped 403 for supported methods before credential handling, turn admission or +body reads. `PATCH /api/protocols/settings` writes `apiSurfaces.gemini.enabled` from the boolean +`geminiEnabled`. `GET /api/protocols` reports `geminiSurface` alongside the three planning +surfaces. `GET /api/keys` returns `surfaces.gemini` and `geminiModelsEndpoint` for the +dashboard card and usage example. See [Protocol Paths](protocol-paths.md#settings) for save +and rollback behavior. Gemini clients authenticate with `x-goog-api-key` or a `?key=` query parameter. The dispatcher clones the request, moves that credential onto `x-opencodex-api-key` (an existing dedicated header @@ -30,10 +37,12 @@ the Chat admission (drain, key, origin, caller session, active turn, workflow, r model-discovery admission `/v1/models` uses. `embedContent` and `batchEmbedContents` answer 501 `UNIMPLEMENTED` after admission; `countTokens` is described below. -The catalog is the same eligible route set as Ollama's `/api/tags` (`src/server/ollama-route-policy.ts` +The catalog starts with the same eligible route set as Ollama's `/api/tags` (`src/server/ollama-route-policy.ts` and the key's model scope): `models//` with `generateContent` and `streamGenerateContent`. Unknown or ineligible models are 404 `NOT_FOUND`; synthetic, shadow, combo -and caller-credential selectors are refused as for Ollama. +and caller-credential selectors are refused as for Ollama. The [opt-in Antigravity catalog](gemini-native.md) +also exposes visible cached Gemini models and their routable wire aliases. Native generation +feeds its route decision, observed reasoning and streaming timing into the same Logs details. `src/protocols/codecs/gemini.ts` maps `contents`, `systemInstruction`, base64 image `inlineData`, `functionDeclarations` and `toolConfig`, `functionCall` and `functionResponse` (matched by id, then by diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index 02d90843f04..d4ed04205a2 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -5,21 +5,31 @@ admission check. In `src/server/index/gemini-routes.ts`, the native leg is avail `/v1beta` generation with `protocols.rollout.geminiNativeAntigravity: true` and a concrete Gemini route to the enabled, canonical `google-antigravity` OAuth provider in Cloud Code Assist mode. Requests outside those conditions use the Chat bridge. Advisor and sidecar capability requests -use the bridge for their inherited-policy checks. +use the bridge for their inherited-policy checks. The Google Antigravity Accounts tab edits the +existing rollout flag through the protocol settings PATCH. The native leg checks the captured admission model scope against the resolved destination. -`src/server/gemini-native-catalog.ts` also projects scoped native wire aliases from the configured -Gemini catalog. An alias is listed or served by point lookup only when routing the alias selects -the native leg and maps to that same wire ID. Discovery is configuration-only. Generation -resolves the Antigravity wire model from the route before accessing OAuth. +On admission it copies the router's decision into the shared request log. +`src/server/gemini-native-catalog.ts` extends the configured Gemini catalog with visible Gemini +models from the existing Antigravity discovery cache and the shared model visibility filter. +List, lookup and token counting apply the same route and key checks to the advertised +destination. A key can allow a concrete tier without allowing its source family. Wire aliases are published only when routing the alias selects +the native leg and maps to that same wire ID. These reads reuse the cached roster and start no +upstream discovery. Generation resolves the Antigravity wire model before accessing OAuth. -`src/server/gemini-native.ts` uses the active, usable OAuth account. The token and project come -from the same snapshot, including after one 401-triggered refresh. Each physical send uses -provider pacing and reserves one workflow send, including recovery. At the point of dispatch -both sends recheck the account for pause, reauthentication and removal. Applicable root, -identity, or pool token-spend ceilings refuse the request with 503 and -`gemini_native_spend_limits_unsupported`. The native leg does not settle token spend. The -destination policy checks the base URL and redirects remain manual. Only proxy-constructed +`src/server/gemini-native.ts` uses the shared Antigravity account preferences and per-account +discovery roster for the resolved wire model. Proactive selection follows OAuth account failover +settings. An account with a known omission cannot receive the request. The selected account's +token and project come from one snapshot, including after one 401-triggered refresh. Each +physical send uses provider pacing, reserves one workflow send and rechecks the account's model +support, pause, reauthentication and removal. The first send advances a configured round-robin +cursor. The native leg uses the [shared spend tracker](../transports/responses-spend.md) for +root, OAuth account and provider-pool token ceilings. It reserves an estimate of the original +JSON input and the supplied output ceiling per candidate. A 401 replay needs fresh capacity. +An applicable ceiling that cannot admit the reservation returns a Gemini-shaped 429 with +`workflow_spend_exhausted`. The final request log settles reported input and output usage, +including reasoning. Sends without final usage retain unresolved spend at the reservation size. +The destination policy checks the base URL and redirects remain manual. Only proxy-constructed headers and the bound OAuth credential go upstream. `src/server/gemini-native-wire.ts` validates the JSON object and embeds the original request @@ -44,8 +54,21 @@ default 300-second upload timeout in effect. A stalled upload returns 408. Cance shutdown, failure and EOF release the turn and transport. Native parsing owns no replay state. `src/server/gemini-native-log.ts` records final status, latency, client and admission identity. -Native errors fail the request-log row. Payloads, provider diagnostics and token usage are -omitted from the log. +Native errors fail the request-log row. A physical send marks the [protocol trace](protocol-paths.md) +as native Gemini, which the dashboard uses for its protocol badge, and records the wire model and +an opaque account label in the shared attempts. The log preserves the first 401 before refresh. +Only a physical replay records a second attempt with the OAuth recovery reason. Successful buffered responses +and complete streams supply normalized token counts through the shared Google usage parser. +For a stream, only its last valid cumulative snapshot is recorded. The dashboard derives its +end-to-end token rate from output tokens and request duration. When an API price matches, +the cost estimate accounts for reported cache hits at the read rate. Gemini generation usage +has no cache-write counter. For a credential replay with both priced and unpriced attempts, +`src/server/management/shared.ts` returns a display-only subtotal and the unpriced attempt count. +Request cost summaries still count such a request as unpriced. The attempts table displays each +valid opaque account label. Reasoning diagnostics use an explicit Gemini thinking control or the +selected wire model's effort suffix. Text and tool-call deltas supply the streaming output +window and first visible output time. Reported thought tokens require a thought delta before +estimating decode throughput. Payloads and provider diagnostics are omitted from the log. Coverage lives in `tests/server/gemini-native-routes.test.ts`, `tests/server/gemini-native-wire.test.ts` and `tests/server/gemini-native.test.ts`. diff --git a/structure/data-planes/protocol-paths.md b/structure/data-planes/protocol-paths.md index cb6dea2b04e..8a4f93b96ad 100644 --- a/structure/data-planes/protocol-paths.md +++ b/structure/data-planes/protocol-paths.md @@ -88,7 +88,7 @@ native lane, and the request's features; the Messages ingress (`src/server/claud marks caller-forward passthrough and the managed native lane as native, the translated path as the bridge, and a disabled surface or a compatibility reject as blocked. The Responses ingress needs no mark: its path follows the final adapter's wire. Marks live in WeakMaps keyed by the request log context -and the live attempt objects, and no mark function throws into the request. +and the live attempt objects. The native Gemini transport marks its same-wire path when it sends. `addFinalRequestLog` derives one `ProtocolTraceV1` through `path.ts`: a blocked mark wins with empty paths; otherwise each attempt gets the lane-derived path (or an explicit attempt mark), @@ -542,8 +542,8 @@ lane, the decline trace, the beta allowlist, opaque state and OAuth. ## Settings -`resolveApiSurfaceSettings` and `resolveProtocolSettings` in `src/protocols/settings.ts` are the -only readers of the `apiSurfaces` and `protocols` config keys. Responses and Chat Completions are +`src/protocols/settings.ts` resolves the `apiSurfaces` and `protocols` config keys through +`resolveApiSurfaceSettings`, `resolveGeminiApiSurface` and `resolveProtocolSettings`. Responses and Chat Completions are always served. The Messages surface uses an explicit `apiSurfaces.messages.enabled` boolean when present, closes when that value is present but malformed, and otherwise inherits `claudeCode.enabled !== false`. The unrepresentable policy defaults to `legacy` and every @@ -562,7 +562,7 @@ through `nativeMessagesDeclineReason` by the Messages ingress, `count_tokens` an closed surface answers 403 before the body is read. `buildApiAccessEndpoints` (`src/server/management/api-access.ts`) reports the resolved `surfaces` in the keys payload and keeps `claudeCodeEnabled` for older dashboards, set from the resolved Messages state rather than -from `claudeCode.enabled`. +from `claudeCode.enabled`. The [Gemini surface](gemini-inbound.md) defaults on and has its own setting. `PATCH /api/protocols/settings` is the one writer. `src/server/management/protocol-settings-patch.ts` validates the body strictly and applies it in memory; the route persists through diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 432b1b7ef19..bc457f4aec1 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -312,7 +312,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | | Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. GET reads the saved policy and returns `{ excludedProviders: string[], meteredComboIds: string[] }`. PUT accepts `{ provider: string, excluded: boolean }`, changes only that provider in the locked persisted configuration, and returns the resulting policy. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. These checks run only in the route, which is authoritative: the dashboard's gating is advisory and can briefly offer an action the route refuses, and the dashboard recovers from the 409 by re-reading the policy and combos. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | -| Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | +| Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved planning surfaces, the separate `geminiSurface` state, protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, geminiEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | | Low-quota history | `src/server/management/low-quota-routes.ts` lazily serves authenticated `GET /api/codex-auth/low-quota-events` from the bounded ledger owned by the server handling the request. The response includes only that server’s account ids and notice/pause-save status; logs omit identifiers. The default notice records `logged`; a notice records `delivered` only after the injected or opted-in OS notifier sink succeeds, `failed` when it fails, and `cancelled` when its episode ends first, while a pause-save records `succeeded` after persistence succeeds. A timed-out in-flight save remains `pending` until it settles. Invalid limits return 400. The route itself emits no OS notification. | diff --git a/structure/providers/google.md b/structure/providers/google.md index 3251ee3527f..4b49ec38002 100644 --- a/structure/providers/google.md +++ b/structure/providers/google.md @@ -10,6 +10,13 @@ UTF-8 encoding or rescanning of the growing prefix. The existing per-frame limit requirements and heartbeat batching remain in force. Replacement strings, including decoder EOF output, retain the [shared byte-accounting contract](../transports/byte-accounting.md#stream-buffer-accounting). +## Reported usage + +`src/adapters/google-usage.ts` normalizes `usageMetadata` for the Google adapter and the native +Gemini route. Prompt and tool-use prompt tokens count as input. Candidate and thought tokens +count as output, with cached input and thought tokens also available as separate counters. +The parser retains only valid numeric counters. + ## Vertex API-key endpoint selection Vertex requests may use host ADC without an API key. The ambient API key stays out of generic provider configuration: `src/providers/vertex-environment-authority.ts` keeps a keyed process-local digest and observed generation with the selected route, and only the Google adapter reads the key. For ADC, routed project and location are captured and rechecked before dispatch. `src/lib/gcp-adc.ts` identifies file and marker sources by keyed content digest and observed generation, checks the source before and after token exchange, and binds its identity to the built request. Shared token refresh has independently cancellable waiters. `src/server/responses/request-transport.ts` checks the provider and request binding after pacing, transfers it on rebuild, and checks the final selection, target and credential after plugin rewrites. The `project: "auto"` auxiliary probe checks the same selection before sending. Unreadable credentials fail closed. A service-account marker selects its named credential instead of the ambient key. Metadata identity changes and an external A→B→A change entirely between observations cannot be detected locally. `tests/adapters/google/gcp-adc.test.ts` covers synthetic key, ADC and physical-dispatch boundaries. diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md index 75106ba6094..d5549a00a27 100644 --- a/structure/usage-client-attribution.md +++ b/structure/usage-client-attribution.md @@ -223,8 +223,9 @@ permit is consumed. The import-free `src/lib/executor-physical-send-receipt.ts` final-admission receipt between the HTTP executor and adapter dispatch. Copilot continuation recovery checks the attempt identity and send count on the inference response, and pacing preserves that receipt when it wraps the body. -`src/server/responses/compact.ts` creates its native attempt on the first dispatch receipt and -seals a 401 before starting credential refresh. +Native compact and native Gemini create a shared attempt at the first physical dispatch and +seal a 401 before starting credential refresh. See `src/server/responses/compact.ts` and +`src/server/gemini-native.ts`. A Responses-to-Chat handoff carries this pending replay into translated dispatch and hosted sidecars. At replacement dispatch, `src/server/passive-route-linker.ts` resolves the passive Lab subject from the routed provider configuration, inbound wire and effective adapter. Matching diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 6f2c33e6cc3..49d463be590 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1593,7 +1593,7 @@ "upstream-retry-zero-output.test.ts": "lib", "upstream-transient-retry.test.ts": "providers", "url-normalization.test.ts": "config", "usage-aggregate-cache.test.ts": "usage", "usage-anthropic-fast-pricing.test.ts": "usage", "usage-cursor-fast-pricing.test.ts": "usage", - "usage-attempt-delivery.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", + "usage-attempt-delivery.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-cost-antigravity-gemini4.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", "usage-credit-ledger-regressions.test.ts": "usage", "usage-provider-credit-price.test.ts": "usage", "usage-debug.test.ts": "usage", "usage-failure-fingerprint.test.ts": "usage", diff --git a/tests/responses/protocol-dto.test.ts b/tests/responses/protocol-dto.test.ts index 9e2f3342f10..8fee85a8341 100644 --- a/tests/responses/protocol-dto.test.ts +++ b/tests/responses/protocol-dto.test.ts @@ -62,6 +62,23 @@ describe("trace validation", () => { expect(parsed.requestPath).not.toBe(trace.requestPath); }); + test("accepts a native Gemini trace and rejects mixed paths", () => { + const gemini: ProtocolTraceV1 = { + v: 1, + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + reasonCodes: ["same-wire-native"], + contractVersion: PROTOCOL_CONTRACT_VERSION, + }; + expect(parseProtocolTraceV1(gemini)).toEqual(gemini); + expect(parseProtocolTraceV1({ ...gemini, upstream: "chat" })).toBeUndefined(); + expect(parseProtocolTraceV1({ ...gemini, responsePath: ["gemini", "chat"] })).toBeUndefined(); + expect(parseProtocolTraceV1({ ...trace, upstream: "gemini" })).toBeUndefined(); + }); + test("a blocked trace has empty paths", () => { const blocked = { ...trace, mode: "blocked", upstream: undefined, requestPath: [], responsePath: [], attempts: undefined }; expect(isProtocolTraceV1(blocked)).toBe(true); diff --git a/tests/server/api-access-endpoints.test.ts b/tests/server/api-access-endpoints.test.ts index f5a87c6bca9..a9d41c79165 100644 --- a/tests/server/api-access-endpoints.test.ts +++ b/tests/server/api-access-endpoints.test.ts @@ -38,6 +38,8 @@ describe("buildApiAccessEndpoints", () => { chatCompletionsEndpoint: "http://[::1]:10100/v1/chat/completions", messagesEndpoint: "http://[::1]:10100/v1/messages", modelsEndpoint: "http://[::1]:10100/v1/models", + geminiModelsEndpoint: "http://[::1]:10100/v1beta/models", + surfaces: { gemini: { enabled: true, source: "default" } }, claudeCodeEnabled: true, }); }); @@ -121,6 +123,7 @@ describe("buildApiAccessEndpoints", () => { responses: { enabled: true, source: "fixed" }, chat: { enabled: true, source: "fixed" }, messages: { enabled: true, source: "claude-code-legacy" }, + gemini: { enabled: true, source: "default" }, }); // An explicit surface value wins over the Claude integration, and the back-compat flag // follows the resolved surface so an older dashboard shows the endpoint that is served. diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts index 5160831f8d4..b70f7f0067b 100644 --- a/tests/server/gemini-native-routes.test.ts +++ b/tests/server/gemini-native-routes.test.ts @@ -2,9 +2,17 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:te import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { fetchProviderModels } from "../../src/codex/catalog/provider-models"; +import { clearModelCache } from "../../src/codex/model-cache"; import { saveConfig } from "../../src/config"; -import { saveCredential } from "../../src/oauth/store"; +import { getAccountSet, removeAccount, saveCredential, setActiveAccount } from "../../src/oauth/store"; +import { oauthAccountLogLabel } from "../../src/codex/account-label"; +import { clearAntigravityAccountRosters, recordAntigravityAccountRoster } from "../../src/providers/antigravity-account-roster"; +import { sharedSpendLedger } from "../../src/lib/spend-reservation-ledger"; +import { estimateTokens } from "../../src/lib/token-estimate"; import { startServer } from "../../src/server"; +import { getRequestLogEntries } from "../../src/server/request-log"; +import { decodeTokPerSecondResult } from "../../src/server/management/shared"; import { nativeGeminiDestination } from "../../src/server/gemini-native-catalog"; import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -19,8 +27,18 @@ const GOOGLE_KEY = "fixture-local-ingress-key"; const OAUTH_TOKEN = "fixture-google-oauth-access"; const SCOPE_KEY = "ocx_data_" + "d".repeat(40); const MODEL_SCOPE_KEY = "ocx_data_" + "b".repeat(40); +const HYDROGEN = "gemini-4-hydrogen"; +const NEON = "gemini-4-neon"; +const NEW_GEMINI = "gemini-discovery-fixture"; +const TIER_SCOPE_KEY = "ocx_data_" + "f".repeat(40); +const DISCOVERED_WIRES = [ + ...["low", "medium", "high", "xhigh"].map(tier => `${HYDROGEN}-${tier}`), + ...["low", "medium", "high"].map(tier => `${NEON}-${tier}`), + NEW_GEMINI, +]; const RAW = '{"contents":[{"role":"user","parts":[{"text":"hello"}]}], "future":9007199254740993123}'; -const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"future":9007199254740993123}'; +const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":12,"toolUsePromptTokenCount":5,"candidatesTokenCount":7,"thoughtsTokenCount":3,"cachedContentTokenCount":4},"future":9007199254740993123}'; +const USAGE = { inputTokens: 17, outputTokens: 10, cachedInputTokens: 4, reasoningOutputTokens: 3 }; const originalFetch = globalThis.fetch; const previousEnv = { OPENCODEX_HOME: process.env.OPENCODEX_HOME, @@ -28,6 +46,8 @@ const previousEnv = { }; const seen: Array<{ url: URL; headers: Headers; body: string }> = []; let home: string; +let discoveryWires: string[]; +let nativeResponse: (() => Response) | undefined; beforeAll(async () => { home = mkdtempSync(join(tmpdir(), "ocx-native-gemini-routes-")); @@ -48,10 +68,18 @@ afterAll(() => { beforeEach(() => { seen.length = 0; + discoveryWires = []; + nativeResponse = undefined; const fixtureFetch: typeof fetch = Object.assign(async (input: RequestInfo | URL, init?: RequestInit) => { const url = new URL(input instanceof Request ? input.url : String(input)); if (url.hostname === "127.0.0.1" || url.hostname === "localhost") return originalFetch(input, init); if (url.origin !== CCA && url.origin !== CHAT) throw new Error("unexpected external fetch in Gemini fixture"); + if (url.origin === CCA && url.pathname === "/v1internal:fetchAvailableModels" && discoveryWires.length > 0) { + return Response.json({ + models: Object.fromEntries(discoveryWires.map(id => [id, {}])), + agentModelSorts: [{ groups: [{ modelIds: discoveryWires }] }], + }); + } if (init?.method !== "POST" || !url.pathname.includes("generateContent") && !url.pathname.includes("streamGenerateContent") && !url.pathname.endsWith("/chat/completions")) { return Response.json({ models: [], data: [] }); } @@ -62,6 +90,7 @@ beforeEach(() => { choices: [{ index: 0, message: { role: "assistant", content: "translated" }, finish_reason: "stop" }], }); } + if (nativeResponse) return nativeResponse(); const envelope = `{"project":"fixture-private-project","response":${PAYLOAD}}`; if (url.pathname.endsWith(":streamGenerateContent")) { return new Response(`data: ${envelope}\n\n`, { headers: { "content-type": "text/event-stream" } }); @@ -84,6 +113,8 @@ function config(flag?: boolean): OcxConfig { { id: "gemini-scope", name: "Gemini scope", key: SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: ["fx"] }, { id: "gemini-model-scope", name: "Gemini model scope", key: MODEL_SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: [PROVIDER], allowedModels: [`${PROVIDER}/gemini-4-argon`] }, + { id: "gemini-tier-scope", name: "Gemini tier scope", key: TIER_SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", + allowedProviders: [PROVIDER], allowedModels: [`${PROVIDER}/${HYDROGEN}-high`] }, ], }; } @@ -92,6 +123,10 @@ async function withServer(cfg: OcxConfig, run: (base: URL) => Promise) { const server = startServer(0); try { await run(server.url); } finally { await server.stop(true); } } +function discoverFixtureModels(cfg: OcxConfig) { + return fetchProviderModels(PROVIDER, { ...cfg.providers[PROVIDER]!, fetch: globalThis.fetch }, 60_000); +} + const key = { "x-goog-api-key": GOOGLE_KEY }; const generation = (model = TARGET, method = "generateContent", version = "v1beta") => `/${version}/models/${model}:${method}`; const post = (base: URL, path: string, headers: Record = key) => @@ -106,6 +141,19 @@ test("opted-in Gemini routes preserve native JSON and replace every ingress cred expect(response.headers.get("x-opencodex-request-id")).toBeTruthy(); expect(response.headers.has("set-cookie")).toBe(false); expect(await response.text()).toBe(PAYLOAD); + const log = getRequestLogEntries().find(row => row.requestId === response.headers.get("x-opencodex-request-id")); + expect(log).toMatchObject({ usageStatus: "reported", usage: USAGE, totalTokens: 27, effectiveEffort: "medium" }); + expect(log?.routeDecision).toMatchObject({ + routeKind: "explicit-provider", + selected: { provider: PROVIDER, model: MODEL, reason: "explicit-provider-namespace" }, + }); + expect(log?.protocolTrace).toMatchObject({ + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + }); expect(seen).toHaveLength(1); expect(seen[0]!.url.href).toBe(CCA + "/v1internal:generateContent"); expect(seen[0]!.headers.get("authorization")).toBe("Bearer " + OAUTH_TOKEN); @@ -116,6 +164,139 @@ test("opted-in Gemini routes preserve native JSON and replace every ingress cred }); }); +test.each(["root", "identity", "pool"] as const)("native Gemini settles the %s Token budget and refuses insufficient capacity", async scope => { + const cfg = config(true); + const limit = 10_000; + cfg.spend = { [scope]: { maxTokens: limit } }; + const rootId = `native-budget-${scope}-${crypto.randomUUID()}`; + const accountId = getAccountSet(PROVIDER)!.activeAccountId; + const scopeId = { root: rootId, identity: oauthAccountLogLabel(accountId, PROVIDER), pool: PROVIDER }[scope]; + const headers = { ...key, "content-type": "application/json", "x-codex-parent-thread-id": rootId, "thread-id": rootId }; + await withServer(cfg, async base => { + const ledger = sharedSpendLedger(); + const previous = ledger.snapshot(scope, scopeId)?.settled ?? 0; + const stream = scope === "root"; + const path = stream ? generation(TARGET, "streamGenerateContent") + "?alt=sse" : generation(); + const response = await post(base, path, headers); + expect(response.status).toBe(200); + expect(await response.text()).toBe(stream ? `data: ${PAYLOAD}\n\n` : PAYLOAD); + expect(ledger.snapshot(scope, scopeId)).toMatchObject({ settled: previous + 27, reserved: 0, unresolved: 0 }); + + const refused = await originalFetch(new URL(generation(), base), { + method: "POST", headers, + body: JSON.stringify({ contents: [], generationConfig: { maxOutputTokens: Math.floor(limit / 2), candidateCount: 2 } }), + }); + expect(refused.status).toBe(429); + expect(refused.headers.get("x-opencodex-local-refusal")).toBe("workflow_spend_exhausted"); + expect(await refused.json()).toMatchObject({ error: { status: "RESOURCE_EXHAUSTED" } }); + expect(seen).toHaveLength(1); + expect(ledger.snapshot(scope, scopeId)).toMatchObject({ settled: previous + 27, reserved: 0, unresolved: 0 }); + }); +}); + +test("native Gemini holds streaming spend until cancellation and keeps unknown usage unresolved", async () => { + const cfg = config(true); + const rootId = `native-budget-stream-${crypto.randomUUID()}`; + const headers = { ...key, "content-type": "application/json", "x-codex-parent-thread-id": rootId, "thread-id": rootId }; + const raw = '{"contents":[],"generation_config":{"max_output_tokens":32}}'; + const reservation = estimateTokens(raw, WIRE_MODEL) + 32; + cfg.spend = { root: { maxTokens: reservation } }; + const cancelled = Promise.withResolvers(); + nativeResponse = () => new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('data: {"response":{"candidates":[{"content":{"parts":[{"text":"partial"}]}}],"usageMetadata":{"promptTokenCount":1}}}\n\n')); + }, + cancel() { cancelled.resolve(); }, + }), { headers: { "content-type": "text/event-stream" } }); + + await withServer(cfg, async base => { + const ledger = sharedSpendLedger(); + const url = new URL(generation(TARGET, "streamGenerateContent") + "?alt=sse", base); + const abort = new AbortController(); + const response = await originalFetch(url, { method: "POST", headers, body: raw, signal: abort.signal }); + expect(response.status).toBe(200); + const reader = response.body!.getReader(); + try { + expect(new TextDecoder().decode((await reader.read()).value)).toContain("partial"); + expect(ledger.snapshot("root", rootId)).toMatchObject({ reserved: reservation, settled: 0 }); + const refused = await originalFetch(url, { method: "POST", headers, body: raw }); + expect(refused.status).toBe(429); + await refused.text(); + expect(seen).toHaveLength(1); + } finally { + abort.abort(); + await reader.cancel().catch(() => {}); + } + await cancelled.promise; + for (let wait = 0; wait < 40 && ledger.snapshot("root", rootId)?.reserved; wait++) await Bun.sleep(10); + expect(ledger.snapshot("root", rootId)).toMatchObject({ reserved: 0, settled: 0, unresolved: reservation }); + }); +}); + +test("native Gemini selects a listing sibling under the configured failover policy", async () => { + const active = getAccountSet(PROVIDER)!.activeAccountId; + const siblingToken = "fixture-sibling-gemini-access"; + const siblingProject = "fixture-sibling-gemini-project"; + const sibling = (await saveCredential(PROVIDER, { + access: siblingToken, refresh: "fixture-sibling-gemini-refresh", expires: Date.now() + 3_600_000, + accountId: "fixture-sibling-gemini-subject", projectId: siblingProject, source: "oauth", + }))!.accountId; + try { + expect(await setActiveAccount(PROVIDER, active)).toBe(true); + recordAntigravityAccountRoster(PROVIDER, active, [{ id: NEON, wireModelId: NEON }]); + recordAntigravityAccountRoster(PROVIDER, sibling, [{ id: MODEL, wireModelId: WIRE_MODEL }]); + const cfg = config(true); + delete cfg.providers[PROVIDER]!.authMode; + for (const enabled of [false, true]) { + cfg.providers[PROVIDER]!.oauthAccountFailover = { enabled }; + await withServer(cfg, async base => { + const response = await post(base, generation()); + if (!enabled) { + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { details: [{ reason: "gemini_native_model_unlisted" }] } }); + const log = getRequestLogEntries().find(row => row.requestId === response.headers.get("x-opencodex-request-id")); + expect(log).toMatchObject({ status: 403, terminalSource: "synthetic" }); + expect(log?.attempts).toBeUndefined(); + expect(log?.protocolTrace).toBeUndefined(); + expect(seen).toHaveLength(0); + return; + } + expect(response.status).toBe(200); + expect(await response.text()).toBe(PAYLOAD); + expect(seen).toHaveLength(1); + expect(seen[0]!.headers.get("authorization")).toBe(`Bearer ${siblingToken}`); + expect(seen[0]!.body).toContain(`"request":${RAW}`); + expect(JSON.parse(seen[0]!.body)).toMatchObject({ project: siblingProject, model: WIRE_MODEL }); + const recorded = getRequestLogEntries().find(row => row.requestId === response.headers.get("x-opencodex-request-id")); + expect(recorded?.attempts).toMatchObject([{ + status: 200, sendCount: 1, model: WIRE_MODEL, accountLogLabel: oauthAccountLogLabel(sibling, PROVIDER), + usageStatus: "reported", usage: USAGE, + }]); + expect(recorded?.spend).toMatchObject({ sends: 1, settled: 1, unresolved: 0 }); + expect(JSON.stringify(recorded)).not.toContain(siblingToken); + expect(JSON.stringify(recorded)).not.toContain(siblingProject); + expect(getAccountSet(PROVIDER)?.activeAccountId).toBe(active); + }); + } + seen.length = 0; + recordAntigravityAccountRoster(PROVIDER, active, [{ id: MODEL, wireModelId: WIRE_MODEL }]); + cfg.pool = { kernel: true }; + cfg.providers[PROVIDER]!.oauthAccountFailover = { enabled: true, strategy: "round-robin", stickyLimit: 1 }; + await withServer(cfg, async base => { + for (let index = 0; index < 2; index++) { + const response = await post(base, generation()); + expect(await response.text()).toBe(PAYLOAD); + } + }); + expect(seen.map(send => send.headers.get("authorization")).sort()) + .toEqual([`Bearer ${OAUTH_TOKEN}`, `Bearer ${siblingToken}`].sort()); + } finally { + clearAntigravityAccountRosters(PROVIDER, active); + clearAntigravityAccountRosters(PROVIDER, sibling); + await removeAccount(PROVIDER, sibling); + } +}); + test("flag off, v1, and a Gemini model on another provider use the Chat bridge", async () => { for (const flag of [undefined, false, true]) { await withServer(config(flag), async base => { @@ -123,6 +304,9 @@ test("flag off, v1, and a Gemini model on another provider use the Chat bridge", const translated = await post(base, path); expect(translated.status).toBe(200); expect(await translated.json()).not.toHaveProperty("future"); + const log = getRequestLogEntries().find(row => row.requestId === translated.headers.get("x-opencodex-request-id")); + expect(log).toBeDefined(); + expect(log?.protocolTrace?.inbound).not.toBe("gemini"); expect(seen.at(-1)?.body).not.toContain(RAW); const other = await post(base, generation(`fx/${MODEL}`)); expect(other.status).toBe(200); @@ -156,6 +340,15 @@ test("native streaming preserves records in both Gemini response formats", async const json = await post(base, path); expect(json.headers.get("content-type")).toContain("application/json"); expect(await json.text()).toBe(`[\n${PAYLOAD}\n]`); + for (const res of [sse, discoverySse, json]) { + const log = getRequestLogEntries().find(row => row.requestId === res.headers.get("x-opencodex-request-id")); + expect(log).toMatchObject({ + usageStatus: "reported", usage: USAGE, totalTokens: 27, + effectiveEffort: "medium", firstOutputMs: expect.any(Number), + }); + expect(log?.genStartMs).toBeUndefined(); + expect(decodeTokPerSecondResult(log!)).toEqual({ kind: "unavailable", reason: "decode_window_missing" }); + } expect(seen.map(call => call.url.href)).toEqual(Array(3).fill(CCA + "/v1internal:streamGenerateContent?alt=sse")); }); }); @@ -172,6 +365,13 @@ test("native selection shares key, origin, host, and model-scope refusals", asyn const response = await post(base, generation(), { ...headers }); expect(response.status).toBe(status); expect(await response.json()).toMatchObject({ error: { code: status, status: errorStatus } }); + const requestId = response.headers.get("x-opencodex-request-id"); + if (requestId) { + const log = getRequestLogEntries().find(row => row.requestId === requestId); + expect(log).toBeDefined(); + expect(log?.protocolTrace).toBeUndefined(); + expect(log?.routeDecision).toBeUndefined(); + } } expect(seen).toHaveLength(0); expect((await get(base, generation())).headers.get("allow")).toBe("POST"); @@ -221,3 +421,87 @@ test("model lookup and discovery expose only scoped, routable native wire aliase expect(seen).toHaveLength(0); }); }); + +test("Gemini discovery and lookup reuse live Antigravity models and exact wire tiers", async () => { + const cfg = config(true); + discoveryWires = DISCOVERED_WIRES; + try { + await withServer(cfg, async base => { + await discoverFixtureModels(cfg); + const openaiCatalog = await get(base, "/v1/models", { "x-opencodex-api-key": GOOGLE_KEY }); + expect(openaiCatalog.status).toBe(200); + expect(await openaiCatalog.json()).toMatchObject({ data: expect.arrayContaining([ + expect.objectContaining({ id: `${PROVIDER}/${HYDROGEN}` }), + expect.objectContaining({ id: `${PROVIDER}/${NEON}` }), + ]) }); + + const response = await get(base, "/v1beta/models"); + const { models } = await response.json() as { models: Array<{ name: string }> }; + for (const selector of [`${PROVIDER}/${HYDROGEN}`, `${PROVIDER}/${NEON}`, ...DISCOVERED_WIRES]) { + const listed = models.filter(model => model.name === `models/${selector}`); + expect(listed).toHaveLength(1); + const lookup = await get(base, `/v1beta/models/${selector}`); + expect(lookup.status).toBe(200); + expect(await lookup.json()).toEqual(listed[0]); + expect((await get(base, `/v1beta/models/${selector}`, { "x-goog-api-key": SCOPE_KEY })).status).toBe(404); + expect((await get(base, `/v1beta/models/${selector}`, { "x-goog-api-key": MODEL_SCOPE_KEY })).status).toBe(404); + } + expect(models.map(model => model.name)).not.toContain(`models/${NEON}-xhigh`); + expect((await get(base, `/v1beta/models/${NEON}-xhigh`)).status).toBe(404); + + const tierScope = { "x-goog-api-key": TIER_SCOPE_KEY }; + const high = `${HYDROGEN}-high`; + const scopedCatalog = await get(base, "/v1beta/models", tierScope); + const scopedModels = (await scopedCatalog.json() as { models: Array<{ name: string }> }).models; + expect(scopedModels.map(model => model.name)).toEqual([`models/${high}`]); + const scopedLookup = await get(base, `/v1beta/models/${high}`, tierScope); + expect(scopedLookup.status).toBe(200); + expect(await scopedLookup.json()).toEqual(scopedModels[0]); + expect((await get(base, `/v1beta/models/${PROVIDER}/${HYDROGEN}`, tierScope)).status).toBe(404); + expect((await get(base, `/v1beta/models/${HYDROGEN}-xhigh`, tierScope)).status).toBe(404); + const scopedSend = await post(base, generation(high), tierScope); + expect(scopedSend.status).toBe(200); + expect(await scopedSend.text()).toBe(PAYLOAD); + expect(JSON.parse(seen.at(-1)!.body).model).toBe(high); + expect((await post(base, generation(`${HYDROGEN}-xhigh`), tierScope)).status).toBe(403); + + const send = await post(base, generation(`${HYDROGEN}-xhigh`)); + expect(send.status).toBe(200); + expect(await send.text()).toBe(PAYLOAD); + expect(JSON.parse(seen.at(-1)!.body).model).toBe(`${HYDROGEN}-xhigh`); + }); + } finally { + clearModelCache(PROVIDER); + } +}); + +test("Gemini lists discovered families only when the rollout and model visibility allow them", async () => { + discoveryWires = DISCOVERED_WIRES; + for (const restriction of ["rollout", "disabled", "selection"] as const) { + const cfg = config(restriction !== "rollout"); + if (restriction === "disabled") cfg.disabledModels = [`${PROVIDER}/${HYDROGEN}`, `${PROVIDER}/${NEON}-medium`]; + if (restriction === "selection") cfg.providers[PROVIDER]!.selectedModels = [`${NEON}-high`]; + try { + await withServer(cfg, async base => { + const discovered = await discoverFixtureModels(cfg); + expect(discovered.map(model => model.id)).toContain(NEON); + const response = await get(base, "/v1beta/models"); + const { models } = await response.json() as { models: Array<{ name: string }> }; + const names = models.map(model => model.name); + const excluded = [`${PROVIDER}/${HYDROGEN}`, `${HYDROGEN}-high`]; + if (restriction !== "selection") excluded.push(`${NEON}-medium`); + for (const selector of excluded) { + expect(names).not.toContain(`models/${selector}`); + expect((await get(base, `/v1beta/models/${selector}`)).status).toBe(404); + } + if (restriction !== "rollout") { + expect(names).toContain(`models/${PROVIDER}/${NEON}`); + expect(names).toContain(`models/${NEON}-high`); + expect((await get(base, `/v1beta/models/${NEON}-high`)).status).toBe(200); + } + }); + } finally { + clearModelCache(PROVIDER); + } + } +}); diff --git a/tests/server/gemini-native-wire.test.ts b/tests/server/gemini-native-wire.test.ts index d71dda73d08..983355ac2c9 100644 --- a/tests/server/gemini-native-wire.test.ts +++ b/tests/server/gemini-native-wire.test.ts @@ -1,5 +1,5 @@ -import { expect, spyOn, test } from "bun:test"; -import { geminiSseTransform, rawJsonMember, unwrapGeminiResponse, wrapGeminiRequest } from "../../src/server/gemini-native-wire"; +import { expect, mock, spyOn, test } from "bun:test"; +import { geminiNativeReasoningFields, geminiSseTransform, rawJsonMember, unwrapGeminiResponse, wrapGeminiRequest } from "../../src/server/gemini-native-wire"; const response = '{"candidates":[{"finishReason":"STOP","content":{"parts":[{"thoughtSignature":"a+/=","functionCall":{"args":{"n":9007199254740993123}}}]}}],"future":1.000e+40,"promptFeedback":{"blockReason":"SAFETY"}}'; test("Gemini JSON retains integers, number spelling, unknown fields and signature bytes", () => { @@ -13,14 +13,16 @@ test("envelope extraction handles escaped keys, nesting, braces in strings and r expect(() => unwrapGeminiResponse(raw)).toThrow(); } }); -async function transform(text: string, chunk = 1, limit?: number): Promise { +async function transform( + text: string, chunk = 1, limit?: number, observers?: Parameters[1], +): Promise { const bytes = new TextEncoder().encode(text); let offset = 0; const body = new ReadableStream({ pull(c) { if (offset === bytes.length) { c.close(); return; } c.enqueue(bytes.slice(offset, offset + chunk)); offset = Math.min(bytes.length, offset + chunk); } }); - return new Response(body.pipeThrough(geminiSseTransform(limit))).text(); + return new Response(body.pipeThrough(geminiSseTransform(limit, observers))).text(); } test("SSE accepts byte-split UTF8, CRLF, comments and multiple events", async () => { const frame = `: ping\r\ndata: {"response":${response}}\r\n\r\n`; @@ -77,3 +79,58 @@ test("fragmented 1 MiB SSE lines perform only linear UTF-8 encoding work", async // Input plus output are about 2 MiB; re-encoding retained prefixes would exceed 500 MiB. expect(encodedBytes).toBeLessThan(frame.length * 3); }); + +test("native SSE reports the final cumulative usage once, retaining all original frames", async () => { + const frames = [ + '{"candidates":[{"index":0}],"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":2}}', + '{"candidates":[{"index":0,"finishReason":"STOP"}]}', + '{"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":6,"thoughtsTokenCount":9,"future":9007199254740993123}}', + '{"usageMetadata":{"candidatesTokenCount":"unreported"}}', + ]; + const upstream = frames.map(json => `data: {"response":${json}}\n\n`).join(""); + for (const terminator of ["", "data: [DONE]\n\n"]) { + const onUsage = mock(); + const result = await transform(upstream + terminator, 7, undefined, { onUsage }); + expect(result).toBe(frames.map(json => `data: ${json}\n\n`).join("")); + expect(onUsage).toHaveBeenCalledTimes(1); + expect(onUsage).toHaveBeenCalledWith({ inputTokens: 19, outputTokens: 15, reasoningOutputTokens: 9 }); + } +}); + +test("native SSE does not report partial usage when the response fails", async () => { + const frame = 'data: {"response":{"candidates":[{"index":0}],"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":2}}}\n\n'; + const onUsage = mock(); + await expect(transform(frame, 7, undefined, { onUsage })).rejects.toThrow("incomplete Gemini generation"); + const error = 'data: {"response":{"error":{"message":"rejected"}}}\n\n'; + await transform(frame + error, 7, undefined, { onUsage }); + expect(onUsage).not.toHaveBeenCalled(); +}); + +test("native reasoning diagnostics reflect the request controls and model wire tier", () => { + expect(geminiNativeReasoningFields({}, "gemini-4-neon-medium")).toEqual({ effectiveEffort: "medium" }); + const level = { generation_config: { thinking_config: { thinking_level: "HIGH" } } }; + expect(geminiNativeReasoningFields(level, "gemini-4-neon-medium")).toEqual({ + requestedEffort: "high", effectiveEffort: "medium", reasoningWireField: "thinkingLevel", reasoningWireValue: "HIGH", + }); + expect(geminiNativeReasoningFields(level, "gemini-3.7-flash-tiered").effectiveEffort).toBe("high"); + const budget = { generationConfig: { thinkingConfig: { thinkingBudget: -1 } } }; + expect(geminiNativeReasoningFields(budget, "gemini-3.7-flash-tiered")).toEqual({ + requestedEffort: "auto", effectiveEffort: undefined, reasoningWireField: "thinkingBudget", reasoningWireValue: "-1", + }); + const invalid = { generationConfig: { thinkingConfig: { thinkingLevel: "fixture-unrecognized" } } }; + expect(geminiNativeReasoningFields(invalid, "gemini-3.7-flash-tiered")).toEqual({ effectiveEffort: undefined }); +}); + +test("native output observation separates thoughts from visible content and ignores usage-only frames", async () => { + const frames = [ + '{"candidates":[{"content":{"parts":[{"text":"summary","thought":true}]}}]}', + '{"candidates":[{"content":{"parts":[{"thoughtSignature":"signature"},{"text":""}]}}]}', + '{"candidates":[{"content":{"parts":[{"text":"answer"}]}}]}', + '{"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"thoughtsTokenCount":12,"candidatesTokenCount":3}}', + ]; + const onOutput = mock(); + const upstream = frames.map(json => `data: {"response":${json}}\n\n`).join(""); + expect(await transform(upstream, 11, undefined, { onOutput })) + .toBe(frames.map(json => `data: ${json}\n\n`).join("")); + expect(onOutput.mock.calls).toEqual([[false, true], [true, false]]); +}); diff --git a/tests/server/gemini-native.test.ts b/tests/server/gemini-native.test.ts index 62e9815aeb3..717e23b39c6 100644 --- a/tests/server/gemini-native.test.ts +++ b/tests/server/gemini-native.test.ts @@ -1,10 +1,15 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import * as oauthStore from "../../src/oauth/store"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { configureSharedSpendLedger, sharedSpendLedger, spendPolicyFromConfig } from "../../src/lib/spend-reservation-ledger"; +import { estimateTokens } from "../../src/lib/token-estimate"; import type { OcxConfig } from "../../src/types"; import { handleGeminiNative, type GeminiNativeDeps } from "../../src/server/gemini-native"; import { getActiveTurnCount, tryAdmitTurn } from "../../src/server/lifecycle"; import { rawJsonMember } from "../../src/server/gemini-native-wire"; -import type { OAuthAccessSnapshot } from "../../src/oauth"; +import { OAuthLoginRequiredError, type OAuthAccessSnapshot } from "../../src/oauth"; +import { logGeminiNativeDelivery } from "../../src/server/gemini-native-log"; +import { getRequestLogEntries, nextRequestLogId } from "../../src/server/request-log"; const config = { providers: { "google-antigravity": { adapter: "google", baseUrl: "https://daily-cloudcode-pa.googleapis.com", authMode: "oauth" } } } as OcxConfig; const old: OAuthAccessSnapshot = { provider: "google-antigravity", accountId: "fixture-account", generation: "old", accessToken: "fixture-old-token", projectId: "fixture-project" }; @@ -18,8 +23,16 @@ const fixtureAccount = () => ({ }); let accountStatus: ReturnType; let accountStatusSpy: ReturnType>; -beforeEach(() => { accountStatus = fixtureAccount(); accountStatusSpy = spyOn(oauthStore, "getAccountCredentialWithStatus").mockImplementation(() => accountStatus); }); -afterEach(() => accountStatusSpy.mockRestore()); +let releaseSpendHome: () => void; +beforeEach(() => { + releaseSpendHome = acquireOwnedSpendHome(); + accountStatus = fixtureAccount(); + accountStatusSpy = spyOn(oauthStore, "getAccountCredentialWithStatus").mockImplementation(() => accountStatus); +}); +afterEach(() => { + accountStatusSpy.mockRestore(); + releaseSpendHome(); +}); function request(body = '{"contents":[],"future":9007199254740993123}', signal?: AbortSignal) { return new Request("http://localhost/v1beta/models/gemini-test:generateContent", { method: "POST", body, signal, headers: { Authorization: "Bearer fixture-client-key" } }); @@ -151,6 +164,45 @@ test("401 refreshes the rejected snapshot once and cancels its response", async expect(calls).toBe(2); expect(refreshes).toBe(1); expect(cancelled).toBe(true); }); +test("native logs distinguish a 401 replay from a refresh that never resends", async () => { + for (const refreshSucceeds of [true, false]) { + const req = request(); + const lease = tryAdmitTurn(undefined, req.signal)!; + const context = { model: "gemini-test", provider: old.provider }; + const start = Date.now(), id = nextRequestLogId(start); + let sends = 0; + try { + const response = await handleGeminiNative(req, config, "gemini-test", undefined, lease, { + access: async () => old, + refresh: async () => { + if (!refreshSucceeds) throw new OAuthLoginRequiredError(old.provider); + return fresh; + }, + fetch: transport(() => ++sends === 1 + ? new Response("private upstream rejection", { status: 401 }) + : new Response('{"response":{"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7}}}')), + }, context, start); + const delivery = logGeminiNativeDelivery(response, req, id, start, context); + expect(delivery.status).toBe(refreshSucceeds ? 200 : 503); + await delivery.text(); + const row = getRequestLogEntries().find(entry => entry.requestId === id); + expect(sends).toBe(refreshSucceeds ? 2 : 1); + expect(row?.spend).toMatchObject({ sends, settled: sends, unresolved: 0 }); + expect(row?.attempts?.map(attempt => [attempt.status, attempt.sendCount, attempt.recoveryKinds])) + .toEqual(refreshSucceeds ? [[401, 1, []], [200, 1, ["oauth-401"]]] : [[401, 1, []]]); + expect(row?.attempts?.[0]).toMatchObject({ failureCause: "credential-rejected", usageStatus: "unreported" }); + if (refreshSucceeds) { + expect(row?.attempts?.[1]).toMatchObject({ usageStatus: "reported", totalTokens: 18, + accountLogLabel: row?.attempts?.[0]?.accountLogLabel }); + expect(row?.totalTokens).toBe(18); + } + expect(JSON.stringify(row)).not.toContain("private upstream rejection"); + } finally { + lease.release(); + } + } +}); + for (const [name, echoed] of [["previous", old.accessToken], ["refreshed", fresh.accessToken]] as const) { test(`401 recovery still rejects the ${name} access token in a successful reply`, async () => { let calls = 0; @@ -320,34 +372,65 @@ test("native physical sends consume the workflow ceiling across requests and 401 } }); -test("native requests fail closed before OAuth when applicable token spend limits are configured", async () => { - let accessCalls = 0, sends = 0; - const deps = { access: async () => { accessCalls++; return old; }, refresh: async () => fresh, - fetch: transport(() => { sends++; return new Response('{"response":{}}'); }) }; - for (const scope of ["root", "identity", "pool"] as const) { - const req = request(); - req.headers.set("x-codex-parent-thread-id", "gemini-token-limit-fixture"); - const response = await run(req, deps, false, { ...config, spend: { [scope]: { maxTokens: 100 } } }); - expect(response.status).toBe(503); - expect(await response.json()).toMatchObject({ error: { details: [{ reason: "gemini_native_spend_limits_unsupported" }] } }); +test.each([true, false])("native Gemini admits each OAuth replay against its own reservation (funded: %s)", async funded => { + const raw = '{"contents":[],"generationConfig":{"maxOutputTokens":16}}'; + const reservation = estimateTokens(raw, "gemini-test") + 16; + const rootId = `native-replay-budget-${crypto.randomUUID()}`; + const cfg = { ...config, spend: { root: { maxTokens: reservation * (funded ? 2 : 1) } } }; + configureSharedSpendLedger(spendPolicyFromConfig(cfg.spend)); + const req = request(raw); + req.headers.set("x-codex-parent-thread-id", rootId); + const lease = tryAdmitTurn(undefined, req.signal)!; + const context = { model: "gemini-test", provider: old.provider }; + const start = Date.now(); + const id = nextRequestLogId(start); + let sends = 0; + try { + const response = await handleGeminiNative(req, cfg, "gemini-test", undefined, lease, { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => ++sends === 1 + ? new Response(null, { status: 401 }) + : new Response('{"response":{"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7}}}')), + }, context, start); + const delivery = logGeminiNativeDelivery(response, req, id, start, context); + expect(delivery.status).toBe(funded ? 200 : 429); + if (!funded) expect(delivery.headers.get("x-opencodex-local-refusal")).toBe("workflow_spend_exhausted"); + await delivery.text(); + expect(sends).toBe(funded ? 2 : 1); + const row = getRequestLogEntries().find(entry => entry.requestId === id); + expect(row?.attempts?.map(attempt => attempt.status)).toEqual(funded ? [401, 200] : [401]); + expect(sharedSpendLedger().snapshot("root", rootId)).toMatchObject({ + reserved: 0, settled: funded ? 18 : 0, unresolved: reservation, + }); + } finally { + lease.release(); } - expect(accessCalls).toBe(0); expect(sends).toBe(0); - // Without a workflow root the root-only ceiling does not apply to this request. - expect((await run(request(), deps, false, { ...config, spend: { root: { maxTokens: 100 } } })).status).toBe(200); - expect(sends).toBe(1); }); -test("a token spend ceiling enabled during setup is rechecked before physical dispatch", async () => { - const baseline = getActiveTurnCount(); - const liveConfig = { ...config }; +test("the live Token ceiling applies if it changes before the first physical send", async () => { + const req = request(); + const lease = tryAdmitTurn(undefined, req.signal)!; + const context = { model: "gemini-test", provider: old.provider }; + const start = Date.now(); + const id = nextRequestLogId(start); let sends = 0; - const response = await run(request(), { - access: async () => { liveConfig.spend = { pool: { maxTokens: 100 } }; return old; }, - refresh: async () => fresh, - fetch: transport(() => { sends++; return new Response('{"response":{}}'); }), - }, false, liveConfig); - expect(response.status).toBe(503); expect(sends).toBe(0); - expect(getActiveTurnCount()).toBe(baseline); + try { + const response = await handleGeminiNative(req, config, "gemini-test", undefined, lease, { + access: async () => { + configureSharedSpendLedger(spendPolicyFromConfig({ pool: { maxTokens: 1 } })); + return old; + }, + refresh: async () => fresh, + fetch: transport(() => { sends++; return new Response('{"response":{}}'); }), + }, context, start); + const delivery = logGeminiNativeDelivery(response, req, id, start, context); + expect(delivery.status).toBe(429); + expect(delivery.headers.get("x-opencodex-local-refusal")).toBe("workflow_spend_exhausted"); + await delivery.text(); + expect(sends).toBe(0); + } finally { + lease.release(); + } }); test("native SSE errors redact upstream diagnostics and delivery logs record failure", async () => { diff --git a/tests/server/management-api-logs-metrics.test.ts b/tests/server/management-api-logs-metrics.test.ts index d9bdcdacc0f..ae746fac26c 100644 --- a/tests/server/management-api-logs-metrics.test.ts +++ b/tests/server/management-api-logs-metrics.test.ts @@ -13,6 +13,7 @@ import { type RequestLogEntry, } from "../../src/server/request-log"; import type { OcxConfig } from "../../src/types"; +import { markNativeGeminiProtocol, protocolTraceForRequest } from "../../src/protocols/trace"; import { buildRouteDecisionTrace } from "../../src/routing/trace"; import { closeRequestHistoryIndex } from "../../src/routing/history/indexer"; import { summarizeUsage } from "../../src/usage/summary"; @@ -91,6 +92,31 @@ function baseEntry(overrides: Partial): RequestLogEntry { } describe("GET /api/logs display metrics", () => { + test("native Gemini OAuth replay reports only the subtotal of priced attempts", async () => { + const provider = "google-antigravity", model = "gemini-4-neon-medium"; + const usage = { inputTokens: 100, outputTokens: 10 }; + const attempt = { provider, model, adapter: "google", durationMs: 100, sendCount: 1, accountLogLabel: "o123abc" as const }; + const row = baseEntry({ + provider, model, usage, usageStatus: "unreported", + attempts: [ + { ...attempt, ordinal: 1, status: 401, recoveryKinds: [], usageStatus: "unreported" }, + { ...attempt, ordinal: 2, status: 200, recoveryKinds: ["oauth-401"], usageStatus: "reported", usage }, + ], + }); + markNativeGeminiProtocol(row); + row.protocolTrace = protocolTraceForRequest(row, undefined); + addRequestLog(row); + const ledgerBefore = readFileSync(usageLogPath(), "utf8"); + const [dto] = await readLogs(); + expect(dto!.attempts[0].displayMetrics.cost.kind).toBe("unavailable"); + expect(dto!.attempts[1].displayMetrics.cost.kind).toBe("value"); + const subtotalUsd = dto!.attempts[1].displayMetrics.cost.estimate.cost.total; + expect(subtotalUsd).toBeGreaterThan(0); + expect(dto!.displayMetrics.cost).toEqual({ kind: "partial", subtotalUsd, unpricedAttempts: 1 }); + expect(dto!.attempts.map((item: { accountLogLabel: string }) => item.accountLogLabel)).toEqual(["o123abc", "o123abc"]); + expect(readFileSync(usageLogPath(), "utf8")).toBe(ledgerBefore); + }); + test("parent, individual attempt DTO and summary agree on unresolved slash cost without rewriting history", async () => { const model = "anthropic/claude-3-haiku-20240307"; const row = baseEntry({ diff --git a/tests/server/protocol-settings-route.test.ts b/tests/server/protocol-settings-route.test.ts index 645384a938f..2f7c3acaffb 100644 --- a/tests/server/protocol-settings-route.test.ts +++ b/tests/server/protocol-settings-route.test.ts @@ -93,6 +93,26 @@ describe("PATCH /api/protocols/settings", () => { expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: true } }); }); + test("Gemini persists its own setting and keeps the planning surface shape compatible", async () => { + const h = harness({ apiSurfaces: { messages: { enabled: true } }, claudeCode: { enabled: true }, + protocols: { rollout: { geminiNativeAntigravity: true } } }); + const res = await patch(h, { geminiEnabled: false }); + expect(res.status).toBe(200); + expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: true }, gemini: { enabled: false } }); + expect(h.saves[0]!.claudeCode).toEqual({ enabled: true }); + expect(h.saves[0]!.protocols?.rollout?.geminiNativeAntigravity).toBe(true); + const body = await res.json(); + expect(Object.keys(body.surfaces)).toEqual(["responses", "chat", "messages"]); + expect(body.geminiSurface).toEqual({ enabled: false, source: "api-surfaces" }); + expect(h.syncs).toBe(0); + }); + + test("repairing malformed surface settings does not reopen the sibling", async () => { + const h = harness({ apiSurfaces: "off" }); + expect((await patch(h, { geminiEnabled: true })).status).toBe(200); + expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: false }, gemini: { enabled: true } }); + }); + test("policy and rollout switches merge into protocols", async () => { const h = harness({ protocols: { rollout: { directEncoders: true } } }); const res = await patch(h, { unrepresentable: "reject", rollout: { shadowPlan: true } }); @@ -147,6 +167,7 @@ describe("PATCH /api/protocols/settings", () => { ["a non-object body", [], "invalid_body"], ["an empty body", {}, "empty_body"], ["an unknown key", { messagesEnabled: true, claudeCode: { enabled: true } }, "unknown_field"], + ["a string geminiEnabled", { geminiEnabled: "false" }, "invalid_gemini_enabled"], ["a string messagesEnabled", { messagesEnabled: "false" }, "invalid_messages_enabled"], ["an unknown policy", { unrepresentable: "drop" }, "invalid_unrepresentable"], ["a non-object rollout", { rollout: true }, "invalid_rollout"], diff --git a/tests/server/server-gemini-inbound.test.ts b/tests/server/server-gemini-inbound.test.ts index 3689eec52ac..e7b7f13db48 100644 --- a/tests/server/server-gemini-inbound.test.ts +++ b/tests/server/server-gemini-inbound.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:tes import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { saveConfig } from "../../src/config"; +import { loadConfig, saveConfig } from "../../src/config"; import { startServer } from "../../src/server"; import { clearRequestLogsForTests, getRequestLogEntries } from "../../src/server/request-log"; import type { OcxConfig } from "../../src/types"; @@ -109,6 +109,49 @@ describe("Gemini-compatible inbound routes", () => { }); }); + test("the API switch closes and reopens Gemini on the running gateway", async () => { + await withServer(async base => { + const toggle = (geminiEnabled: boolean) => fetch(new URL("/api/protocols/settings", base), { + method: "PATCH", + headers: { "content-type": "application/json", "x-opencodex-api-key": ADMIN_TOKEN }, + body: JSON.stringify({ geminiEnabled }), + }); + const closed = await toggle(false); + expect(closed.status).toBe(200); + expect(await closed.json()).toMatchObject({ geminiSurface: { enabled: false, source: "api-surfaces" } }); + expect(loadConfig().apiSurfaces?.gemini?.enabled).toBe(false); + for (const [method, path] of [ + ["GET", "/v1beta/models"], + ["GET", "/v1beta/models/fx/m1"], + ["POST", "/v1beta/models/fx/m1:countTokens"], + ["POST", "/v1beta/models/fx/m1:streamGenerateContent?alt=sse"], + ["POST", "/v1/models/fx/m1:generateContent"], + ["POST", "/v1beta/interactions"], + ["DELETE", "/v1/interactions/example"], + ["POST", "/v1beta/interactions/example/cancel"], + ]) { + const response = await fetch(new URL(path!, base), { + method, headers: googKey, ...(method === "POST" ? { body: "not JSON" } : {}), + }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { message: "Gemini API is disabled", status: "PERMISSION_DENIED" } }); + } + expect(seen).toHaveLength(0); + const openAiModels = await fetch(new URL("/v1/models", base)); + expect(openAiModels.status).toBe(200); + await openAiModels.json(); + + const reopened = await toggle(true); + expect(reopened.status).toBe(200); + expect(await reopened.json()).toMatchObject({ geminiSurface: { enabled: true, source: "api-surfaces" } }); + expect(loadConfig().apiSurfaces?.gemini?.enabled).toBe(true); + const generated = await post(base, "/v1beta/models/fx/m1:generateContent", request()); + expect(generated.status).toBe(200); + expect(await generated.json()).toMatchObject({ candidates: [{ content: { parts: [{ text: "Hello" }] } }] }); + expect(seen).toHaveLength(1); + }); + }); + test("streamGenerateContent?alt=sse with x-goog-api-key streams Gemini SSE and reaches the provider as Chat", async () => { saveConfig(config(true)); await withServer(async base => { diff --git a/tests/usage/request-log-generation-window.test.ts b/tests/usage/request-log-generation-window.test.ts index 7cbdf7a7592..8b63007e805 100644 --- a/tests/usage/request-log-generation-window.test.ts +++ b/tests/usage/request-log-generation-window.test.ts @@ -2,6 +2,7 @@ import { expect, test } from "bun:test"; import { mkdtempSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { markNativeGeminiProtocol, protocolTraceForRequest } from "../../src/protocols/trace"; import { tapAnthropicSseForLog } from "../../src/server/claude-messages"; import { decodeTokPerSecondResult } from "../../src/server/management/shared"; import { @@ -50,6 +51,13 @@ test("the decode rate uses the generation window when the row carries one", () = expect(decodeTokPerSecondResult(row)).toEqual({ kind: "value", value: 200, estimated: true, timingBasis: "legacy-post-visible-output" }); expect(decodeTokPerSecondResult({ ...row, genStartMs: 1_000, lastOutputMs: 9_000 })) .toEqual({ kind: "value", value: 100, estimated: true, timingBasis: "generation-window" }); + const gemini = ctx(); + markNativeGeminiProtocol(gemini); + const protocolTrace = protocolTraceForRequest(gemini, undefined); + expect(decodeTokPerSecondResult({ ...row, protocolTrace })) + .toEqual({ kind: "unavailable", reason: "decode_window_missing" }); + expect(decodeTokPerSecondResult({ ...row, protocolTrace, genStartMs: 1_000, lastOutputMs: 9_000 })) + .toEqual({ kind: "value", value: 100, estimated: true, timingBasis: "generation-window" }); // The floor still applies, and a generation window never falls back to the TTFT window. expect(decodeTokPerSecondResult({ ...row, genStartMs: 8_500, lastOutputMs: 9_000 })) .toEqual({ kind: "unavailable", reason: "decode_window_too_short" }); diff --git a/tests/usage/usage-cost-antigravity-gemini4.test.ts b/tests/usage/usage-cost-antigravity-gemini4.test.ts new file mode 100644 index 00000000000..e1d9e448723 --- /dev/null +++ b/tests/usage/usage-cost-antigravity-gemini4.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { estimateRequestCost, resolveMatchedPrice } from "../../src/usage/cost"; + +test("Antigravity Gemini 4 prices exact effort IDs using reported input, output and cache hits", () => { + const usage = { inputTokens: 10_000, outputTokens: 1_000, cachedInputTokens: 4_000, reasoningOutputTokens: 800 }; + for (const [base, expected] of [ + ["gemini-4-neon", { input: 0.018, output: 0.015, cacheRead: 0.0006, total: 0.0336 }], + ["gemini-4-hydrogen", { input: 0.009, output: 0.0075, cacheRead: 0.0003, total: 0.0168 }], + ] as const) { + for (const suffix of ["", "-low", "-medium", "-high", "-xhigh"]) { + const estimate = estimateRequestCost({ + provider: "google-antigravity", model: base + suffix, usage, usageStatus: "reported", + }); + expect(estimate?.price).toMatchObject({ modelId: base + suffix, source: "expected", status: "verified-derived" }); + expect(estimate?.estimated).toBe(true); + expect(estimate?.tokens).toEqual({ input: 6_000, output: 1_000, cacheRead: 4_000, cacheWrite: 0 }); + expect(estimate?.cost.cacheWrite).toBe(0); + for (const component of ["input", "output", "cacheRead", "total"] as const) { + expect(estimate!.cost[component]).toBeCloseTo(expected[component], 12); + } + } + const direct = resolveMatchedPrice("google", base); + expect(direct?.status).toBe("verified"); + } + expect(resolveMatchedPrice("google-antigravity", "gemini-discovery-fixture")).toBeNull(); +});