diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index ef134650e85..49a07c3f84f 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -778,3 +778,9 @@ variables `AGY_LLM_GATEWAY_*` y después la configuración del usuario. El estad configuración de la organización y las variables de entorno que puede ver. Solo consulta el entorno del proceso de OpenCodex. Si la variable se fija únicamente en el proceso de Antigravity, el estado 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 +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/adapters.md b/docs-site/src/content/docs/es/reference/adapters.md index 2e323d6e91a..22b8d55dac8 100644 --- a/docs-site/src/content/docs/es/reference/adapters.md +++ b/docs-site/src/content/docs/es/reference/adapters.md @@ -197,6 +197,12 @@ El proveedor con clave API `commandcode` usa Chat Completions para la mayoría d ## `google` +La entrada compatible con Gemini en `/v1beta` puede conservar el JSON original al generar +contenido mediante el proveedor OAuth canónico `google-antigravity`. Activa +`protocols.rollout.geminiNativeAntigravity: true` para que se aplique después del enrutamiento y +la admisión. La opción está desactivada por defecto. +Consulta [Gemini nativo con Antigravity](/es/reference/proxy-formats/#native-gemini-with-antigravity). + **Objetivos:** Google **Gemini**, **Vertex AI**, y la Antigravity **Asistencia de código en la nube**. AI Studio utiliza `/v1beta/models/{model}:streamGenerateContent`; los otros modos usan sus puntos finales nativos Google. **Auth:** clave API, Vertex ADC o Google Antigravity OAuth, seleccionado por `googleMode`. 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 936b2fc2d82..70340d9c8d9 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -461,7 +461,7 @@ La instantánea sigue siendo un contrato de lista de modelos de solo lectura; no ## API de Gemini: `/v1beta/models` y `/v1beta/interactions` -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 traduce cada solicitud a su ruta de Chat Completions, así que detrás puede haber cualquier proveedor. 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" } }`. +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. - `:generateContent` y `:streamGenerateContent`, bajo `/v1beta/models/` o `/v1/models/`, traducen `contents`, `systemInstruction`, imágenes en línea, declaraciones y llamadas de funciones, y `generationConfig`. Las firmas de pensamiento de las partes `functionCall` viajan en ambos sentidos. Con `alt=sse` el flujo es SSE; sin él la respuesta es un único array JSON, como lo envía la API REST de Google. Las herramientas alojadas de Gemini se ignoran. Un `candidateCount` distinto de 1, datos en línea que no son imágenes y partes de archivo se rechazan con 400. @@ -629,3 +629,45 @@ Las solicitudes enrutadas toleran los argumentos de función serializados mal fo Al traducir Chat Completions a Responses de OpenAI o al backend ChatGPT, las herramientas de función mantienen el valor no estricto de Chat: si se omite `strict`, se envía false; los booleanos explícitos se conservan. Las `functions` heredadas tampoco se vuelven estrictas. Los argumentos opcionales —incluidos los selectores alternativos de índice y coordenadas de `computer_use`— siguen siendo opcionales. No se reescribe el esquema ni cambian los predeterminados de Responses nativo, destinos Chat o proveedores Responses externos. Una entrada de compactación retenida de OpenCodex mal formada (`ocx2:`) devuelve HTTP 400 con `error.type: "invalid_request_error"` antes de enrutar, elegir cuenta, refrescar credenciales o enviar al proveedor. No provoca reintentos ni registra un fallo contra una cuenta Codex del pool. + + + +## Gemini nativo con Antigravity + +Habilita el proveedor canónico `google-antigravity`, inicia sesión con +`ocx login google-antigravity` y añade esta opción a la configuración JSON de OpenCodex: + +```json +{ + "protocols": { + "rollout": { + "geminiNativeAntigravity": true + } + } +} +``` + +La opción está desactivada por defecto. Usa la API compatible con Gemini en `/v1beta` y +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. + +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 +razonamiento. La transmisión usa SSE con `alt=sse` y una matriz JSON en los demás casos. +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. + +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. + +Envía JSON con codificación `identity`. El cuerpo de la solicitud, la respuesta almacenada +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. diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index abdcdeefe61..ca562c0c91c 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1264,3 +1264,8 @@ an organization `admin_settings.json` first, then the `AGY_LLM_GATEWAY_*` variab status warns about organization settings and environment overrides it can see. It checks the 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 +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/adapters.md b/docs-site/src/content/docs/reference/adapters.md index d8b35c3d230..3382f5033d0 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -495,6 +495,11 @@ MiMo model Command Code serves. ## `google` +The Gemini-compatible `/v1beta` inbound can opt in to source-preserving generation over the +canonical `google-antigravity` OAuth provider with `protocols.rollout.geminiNativeAntigravity: true`. +The default is off. This applies to Gemini inbound requests after routing and admission. See +[Native Gemini with Antigravity](/reference/proxy-formats/#native-gemini-with-antigravity). + **Targets:** Google **Gemini**, **Vertex AI**, and Antigravity **Cloud Code Assist**. AI Studio uses `/v1beta/models/{model}:streamGenerateContent`; the other modes use their native Google endpoints. **Auth:** API key, Vertex ADC, or Google Antigravity OAuth, selected by `googleMode`. diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index d29396c268f..a9ca2869fea 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -828,7 +828,8 @@ Thinking replay and prompt-cache work remain separate in [#3719](https://github. 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 -translates each request onto its Chat Completions path, so the route behind it can be any provider. +normally translates generation onto its Chat Completions path, so the route behind it can be any +provider. Eligible Antigravity generation can use [native passthrough](#native-gemini-with-antigravity) when enabled. Authenticate with a proxy API key in `x-goog-api-key` or a `?key=` query parameter; the key is removed from the URL and headers before the request is logged or forwarded. Errors use Google's `{ "error": { "code", "message", "status" } }` shape. @@ -1120,3 +1121,41 @@ Routed requests tolerate malformed serialized function arguments as an empty obj Two bounded history repairs preserve usable arguments: a missing JSON object prefix, and MiMo's trailing `` envelope with a missing closing quote or brace. A repair must decode to a JSON object. Valid JSON values containing those tags are preserved. + +## 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: + +```json +{ + "protocols": { + "rollout": { + "geminiNativeAntigravity": true + } + } +} +``` + +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. + +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. + +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. + +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. diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index cf257ff5f81..55e5756d102 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,7 @@ { + "gemini-native.test.ts": "server", + "gemini-native-wire.test.ts": "server", + "gemini-native-routes.test.ts": "server", "claude-translated-advisor-tool.test.ts": "claude-integration", "claude-translated-hosted-advisor-choice.test.ts": "claude-integration", "management-provider-forward-advisor-tool.test.ts": "server", diff --git a/src/config/schema/config-schema.ts b/src/config/schema/config-schema.ts index 1ff92dcb99c..4fc23938db7 100644 --- a/src/config/schema/config-schema.ts +++ b/src/config/schema/config-schema.ts @@ -108,6 +108,7 @@ export const protocolConfigSchema = z.object({ managedMessagesNativeOAuth: z.boolean().optional(), directEncoders: z.boolean().optional(), antigravityDirect: z.boolean().optional(), + geminiNativeAntigravity: z.boolean().optional(), shadowPlan: z.boolean().optional(), }).strict().optional(), }).strict(); @@ -156,6 +157,7 @@ export const configSchema = z.object({ managedMessagesNativeOAuth: false, directEncoders: fields.directEncoders === true, antigravityDirect: fields.antigravityDirect === true, + geminiNativeAntigravity: false, shadowPlan: fields.shadowPlan === true, }, }; diff --git a/src/protocols/settings.ts b/src/protocols/settings.ts index 139b00eca5c..670a5b7b55b 100644 --- a/src/protocols/settings.ts +++ b/src/protocols/settings.ts @@ -65,6 +65,7 @@ export interface ProtocolRolloutSettings { managedMessagesNativeOAuth: boolean; directEncoders: boolean; antigravityDirect: boolean; + geminiNativeAntigravity: boolean; shadowPlan: boolean; } @@ -108,6 +109,7 @@ export function resolveProtocolSettings(config: ProtocolConfig, providerName?: s antigravityDirect: validContainers && (Object.hasOwn(rollout, "antigravityDirect") ? rollout.antigravityDirect === true : true), + geminiNativeAntigravity: on("geminiNativeAntigravity"), shadowPlan: on("shadowPlan"), }), }); @@ -153,6 +155,7 @@ export function protocolPolicyRevision(config: ProtocolConfig & Pick modelResource(config, row)) }); + const rows = eligibleRoutes(config, req, admission); + const aliases = geminiNativeCatalogAliases(config, req, rows, resolveAdmissionModelScope(config, admission)); + return Response.json({ models: [...rows, ...aliases].map(row => modelResource(config, row)) }); } -export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { +function findGeminiCatalogRow(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string) { const row = findOllamaRoute(config, model, req); const scope = resolveAdmissionModelScope(config, admission); - if (!row || !routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })) return geminiError(404, "model not found"); - return Response.json(modelResource(config, row)); + if (row && routeAllowedByScope(scope, row.route)) return row; + return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, admission), scope); +} + +export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { + const row = findGeminiCatalogRow(config, req, admission, model); + return row ? Response.json(modelResource(config, row)) : geminiError(404, "model not found"); } /** @@ -110,9 +118,8 @@ export function handleGeminiModel(config: OcxConfig, req: Request, admission: Da * key may reach. No upstream call. Body: `{contents, systemInstruction, tools}` or `{generateContentRequest}`. */ export async function handleGeminiCountTokens(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Promise { - const row = findOllamaRoute(config, model, req); - const scope = resolveAdmissionModelScope(config, admission); - if (!row || !routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })) return geminiError(404, "model not found"); + const row = findGeminiCatalogRow(config, req, admission, model); + if (!row) return geminiError(404, "model not found"); const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes); const budget = createTranslatorBudget(); try { diff --git a/src/server/gemini-native-catalog.ts b/src/server/gemini-native-catalog.ts new file mode 100644 index 00000000000..70813403c54 --- /dev/null +++ b/src/server/gemini-native-catalog.ts @@ -0,0 +1,64 @@ +import { resolveProtocolSettings } from "../protocols/settings"; +import { resolveAntigravityEffortWireModel } from "../providers/antigravity-models"; +import { effectiveGoogleMode } from "../providers/registry"; +import type { RouteResult } from "../router"; +import type { OcxConfig } from "../types"; +import { routeAllowedByScope, type AdmissionModelScope } from "./admission-model-scope"; +import { preflightOllamaRoute } from "./ollama-route-policy"; + +const PROVIDER = "google-antigravity"; +const GEMINI_MODEL = /^gemini-[A-Za-z0-9._-]{1,120}$/; + +function nativeWireModel(config: OcxConfig, route: RouteResult, effort?: string): string | undefined { + const configured = config.providers[PROVIDER]; + const { providerName, provider, modelId } = route; + if (providerName !== PROVIDER || route.routeReason === "blocked-model-redirect" + || !configured || configured.disabled === true + || (configured.authMode !== undefined && configured.authMode !== "oauth") + || provider.authMode !== "oauth" || effectiveGoogleMode(providerName, provider) !== "cloud-code-assist" + || !GEMINI_MODEL.test(modelId)) return undefined; + const { wireModelId } = resolveAntigravityEffortWireModel(modelId, effort, provider.baseUrl); + return GEMINI_MODEL.test(wireModelId) ? wireModelId : undefined; +} + +function resolveNativeDestination(config: OcxConfig, req: Request, selector: string) { + const preflight = preflightOllamaRoute(config, selector, req); + if (!preflight.ok) return undefined; + const wireModel = nativeWireModel(config, preflight.route); + return wireModel ? { route: preflight.route, wireModel } : undefined; +} + +export function nativeGeminiDestination(config: OcxConfig, req: Request, selector: string) { + if (!resolveProtocolSettings(config).rollout.geminiNativeAntigravity) return undefined; + return resolveNativeDestination(config, req, selector); +} + +/** 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; + const destination = resolveNativeDestination(config, req, alias); + if (destination?.wireModel !== alias || !routeAllowedByScope(scope, destination.route)) return undefined; + return { selector: alias, route: destination.route }; +} + +type CatalogRow = { selector: string; route: RouteResult }; + +export function geminiNativeCatalogLookup( + config: OcxConfig, req: Request, alias: string, rows: () => readonly CatalogRow[], scope?: AdmissionModelScope, +): CatalogRow | undefined { + if (!resolveProtocolSettings(config).rollout.geminiNativeAntigravity) return undefined; + const row = allowedWireAlias(config, req, alias, scope); + return row && rows().some(({ route }) => advertisedWireModels(config, route).includes(alias)) ? row : undefined; +} + +function advertisedWireModels(config: OcxConfig, route: RouteResult): string[] { + return [undefined, "low", "medium", "high"].flatMap(effort => nativeWireModel(config, route, effort) ?? []); +} + +export function geminiNativeCatalogAliases( + config: OcxConfig, req: Request, rows: readonly CatalogRow[], scope?: AdmissionModelScope, +): CatalogRow[] { + if (!resolveProtocolSettings(config).rollout.geminiNativeAntigravity) return []; + const aliases = new Set(rows.flatMap(({ route }) => advertisedWireModels(config, route))); + return [...aliases].sort().flatMap(alias => allowedWireAlias(config, req, alias, scope) ?? []); +} diff --git a/src/server/gemini-native-log.ts b/src/server/gemini-native-log.ts new file mode 100644 index 00000000000..02944fbbd50 --- /dev/null +++ b/src/server/gemini-native-log.ts @@ -0,0 +1,33 @@ +import { addFinalRequestLog, type RequestLogContext } from "./request-log"; +import { GEMINI_NATIVE_ERROR_CODE } from "./gemini-native-wire"; + +/** Observe delivery lifetime without parsing, retaining or rewriting Gemini payloads. */ +export function logGeminiNativeDelivery(response: Response, req: Request, requestId: string, start: number, context: RequestLogContext): Response { + let settled = false; + const finish = (status: number) => { + if (settled) return; + settled = true; + if (status < 400 && context.errorCode === GEMINI_NATIVE_ERROR_CODE) status = 502; + req.signal.removeEventListener("abort", onAbort); + addFinalRequestLog(requestId, start, context, status, { + terminalStatus: status < 400 ? "completed" : "failed", + closeReason: status === 499 ? "client_cancel" : "terminal", + }); + }; + const onAbort = () => finish(499); + req.signal.addEventListener("abort", onAbort, { once: true }); + if (req.signal.aborted) onAbort(); + if (!response.body) { finish(response.status); return response; } + const reader = response.body.getReader(); + const body = new ReadableStream({ + async pull(controller) { + try { + const next = await reader.read(); + if (next.done) { finish(response.status); controller.close(); } + else controller.enqueue(next.value); + } catch (error) { finish(req.signal.aborted ? 499 : 502); controller.error(error); } + }, + cancel(reason) { finish(499); return reader.cancel(reason); }, + }); + return new Response(body, { status: response.status, headers: response.headers }); +} diff --git a/src/server/gemini-native-wire.ts b/src/server/gemini-native-wire.ts new file mode 100644 index 00000000000..e195b8eca38 --- /dev/null +++ b/src/server/gemini-native-wire.ts @@ -0,0 +1,201 @@ +/** 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"); +} + +/** Find a top-level member's original value, including exact numeric/string spelling. */ +export function rawJsonMember(raw: string, member: string): string { + validateGeminiObject(raw); + let depth = 0, start = -1, key: string | undefined, found: string | undefined; + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + if (ch === '"') { + const begin = i++; + for (; i < raw.length; i++) { + if (raw[i] === "\\") i++; + else if (raw[i] === '"') break; + } + if (depth === 1 && start < 0) key = JSON.parse(raw.slice(begin, i + 1)) as string; + continue; + } + if (ch === ":" && depth === 1 && start < 0) { start = i + 1; continue; } + if ((ch === "," && depth === 1) || (ch === "}" && depth === 1)) { + if (key === member) { + if (found !== undefined) throw new Error("duplicate envelope member"); + found = raw.slice(start, i).trim(); + } + key = undefined; start = -1; + } + if (ch === "{" || ch === "[") depth++; + else if (ch === "}" || ch === "]") depth--; + } + if (found === undefined) throw new Error("missing envelope member"); + return found; +} + +export function unwrapGeminiResponse(raw: string): string { + const response = rawJsonMember(raw, "response"); + validateGeminiObject(response); + return response; +} + +/** Check validated JSON source, including escaped strings and duplicate members. */ +export function containsGeminiCredential(raw: string, credentials: readonly string[]): boolean { + if (!credentials.length) return false; + const contains = (text: string) => credentials.some(value => text.includes(value)); + if (contains(raw)) return true; + if (!raw.includes("\\")) return false; + + const delimiters = /["\\]/g; + let start = -1, escaped = false; + for (let match = delimiters.exec(raw); match; match = delimiters.exec(raw)) { + if (match[0] === "\\") { + escaped = true; + delimiters.lastIndex++; + } else if (start < 0) { + start = match.index; + } else { + if (escaped && contains(JSON.parse(raw.slice(start, delimiters.lastIndex)))) return true; + start = -1; + escaped = false; + } + } + return false; +} + +export function wrapGeminiRequest(raw: string, model: string, project: string): string { + validateGeminiObject(raw); + const envelope = JSON.stringify({ model, project, userAgent: "antigravity", requestType: "agent", requestId: `agent-${crypto.randomUUID()}` }); + return `${envelope.slice(0, -1)},"request":${raw}}`; +} + +/** Decode bounded upstream SSE events and frame the unwrapped JSON for the client. */ +export function geminiSseTransform( + maxBytes = GEMINI_NATIVE_MAX_BYTES, + onNativeError?: () => void, + format: "sse" | "array" = "sse", + credentials: readonly string[] = [], +): TransformStream { + const decoder = new TextDecoder("utf-8", { fatal: true }); + const encoder = new TextEncoder(); + let lineParts: string[] = [], data: string[] = [], eventBytes = 0, afterCR = false; + const candidates = new Map(); + let terminal = false, blocked = false, arrayOpened = false; + 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 } }; + if (Object.hasOwn(value, "error") || containsGeminiCredential(raw, credentials)) { + terminal = true; + try { 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"); + 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); + } + return raw; + } + function emit(controller: TransformStreamDefaultController) { + if (data.length) { + const payload = data.join("\n"); + if (payload.trim() === "[DONE]") { + if (!complete()) throw new Error("premature Gemini stream terminator"); + terminal = true; + } else { + const response = observe(unwrapGeminiResponse(payload)); + if (format === "sse") { + controller.enqueue(encoder.encode(`data: ${response.replaceAll("\n", "\ndata: ")}\n\n`)); + } else { + controller.enqueue(encoder.encode((arrayOpened ? ",\n" : "[\n") + response)); + arrayOpened = true; + } + } + } + data = []; eventBytes = 0; + if (terminal) { + closeArray(controller); + controller.terminate(); + } + } + function appendLineBytes(bytes: Uint8Array) { + if (!bytes.byteLength) return; + eventBytes += bytes.byteLength; + if (eventBytes > maxBytes) throw new Error("Gemini SSE event too large"); + const text = decoder.decode(bytes, { stream: true }); + if (text) lineParts.push(text); + } + function endLine(controller: TransformStreamDefaultController) { + const tail = decoder.decode(); + if (tail) lineParts.push(tail); + const line = lineParts.join(""); + lineParts = []; + if (!line) emit(controller); + else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, "")); + } + return new TransformStream({ + transform(chunk, controller) { + let start = 0; + // Scan only new bytes; CR/LF cannot occur inside a UTF-8 continuation sequence. + for (let i = 0; i < chunk.byteLength; i++) { + const byte = chunk[i]; + if (afterCR) { + afterCR = false; + if (byte === 10) { start = i + 1; continue; } + } + if (byte !== 10 && byte !== 13) continue; + appendLineBytes(chunk.subarray(start, i)); + endLine(controller); + if (terminal) return; + afterCR = byte === 13; + start = i + 1; + } + appendLineBytes(chunk.subarray(start)); + }, + flush(controller) { + const tail = decoder.decode(); + 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"); + closeArray(controller); + }, + }); +} + +/** Read source text with a byte cap and cancellation, without parsing or re-encoding it. */ +export async function readGeminiText(body: ReadableStream | null, limit: number, signal: AbortSignal): Promise { + signal.throwIfAborted(); + if (!body) return ""; + const reader = body.getReader(); + const onAbort = () => { void reader.cancel(signal.reason).catch(() => {}); }; + signal.addEventListener("abort", onAbort, { once: true }); + const decoder = new TextDecoder("utf-8", { fatal: true }); + let total = 0; + const parts: string[] = []; + try { + for (;;) { + const next = await reader.read(); + signal.throwIfAborted(); + if (next.done) break; + total += next.value.byteLength; + if (total > limit) return null; + parts.push(decoder.decode(next.value, { stream: true })); + } + parts.push(decoder.decode()); + return parts.join(""); + } finally { + signal.removeEventListener("abort", onAbort); + void reader.cancel().catch(() => {}); + } +} diff --git a/src/server/gemini-native.ts b/src/server/gemini-native.ts new file mode 100644 index 00000000000..f34511bc358 --- /dev/null +++ b/src/server/gemini-native.ts @@ -0,0 +1,218 @@ +import type { OcxConfig } from "../types"; +import { getValidAccessSnapshotForAccount, forceRefreshOAuthAccessSnapshot, OAuthLoginRequiredError, OAuthAccountPausedError, OAuthTokenRefreshBusyError, OAuthTokenRefreshStaleError, type OAuthAccessSnapshot } from "../oauth"; +import { getAccountSet, getAccountCredentialWithStatus } from "../oauth/store"; +import { getProviderRegistryEntry } from "../providers/registry"; +import { sendTrackingRequestSlot, waitForProviderRequestSlot, RequestPacingQueueOverloadError, RequestPacingProviderRemovedError } from "../providers/request-pacing"; +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 { DEFAULT_STALL_TIMEOUT_SEC, resolveStallTimeoutMs } from "../stall-timeout"; +import { isLocalUpstream } from "../lib/local-upstream"; +import { assertProviderDestinationAllowed } from "../lib/destination-policy"; +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"; + +export const GEMINI_NATIVE_PROVIDER = "google-antigravity"; +class NativeWorkflowSendDenied extends Error {} +class NativeSpendLimitsUnsupported extends Error {} +class NativeRequestBodyTimeout extends Error {} +class NativeConfigurationInvalid 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; + refresh: (snapshot: OAuthAccessSnapshot) => Promise; + fetch: typeof globalThis.fetch; +} +const defaults: Omit = { + access: async () => { + const set = getAccountSet(GEMINI_NATIVE_PROVIDER); + if (!set) throw new OAuthLoginRequiredError(GEMINI_NATIVE_PROVIDER); + return getValidAccessSnapshotForAccount(GEMINI_NATIVE_PROVIDER, set.activeAccountId, { requireUsableAccount: true }); + }, refresh: forceRefreshOAuthAccessSnapshot, +}; + +/** Active-account native leg; no internal messages, tool-schema repair or model rewriting. */ +export async function handleGeminiNative( + req: Request, config: OcxConfig, model: string, streamFormat: "sse" | "array" | undefined, + lease: ActiveTurnLease, deps: GeminiNativeDeps = { ...defaults, fetch: globalThis.fetch }, logCtx?: RequestLogContext, +): 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 = () => { + 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(); + 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"); + const ac = new AbortController(); + const onAbort = () => ac.abort(req.signal.reason); + req.signal.addEventListener("abort", onAbort, { once: true }); + if (req.signal.aborted) onAbort(); + registerTurn(ac, lease); + const baseUrl = provider.baseUrl || getProviderRegistryEntry(GEMINI_NATIVE_PROVIDER)!.baseUrl; + let timer: ReturnType | undefined; + let bodyReadTimer: ReturnType | undefined; + let finished = false; + let onUpstreamAbort: (() => void) | undefined; + const finish = () => { + if (finished) return; + finished = true; + clearTimeout(timer); clearTimeout(bodyReadTimer); + if (onUpstreamAbort) ac.signal.removeEventListener("abort", onUpstreamAbort); + req.signal.removeEventListener("abort", onAbort); + unregisterTurn(ac); + }; + const armStall = () => { + clearTimeout(timer); + const stallMs = resolveStallTimeoutMs(config.stallTimeoutSec, { localUpstream: isLocalUpstream(baseUrl) }); + if (stallMs > 0) timer = setTimeout(() => ac.abort(new Error("Gemini upstream stalled")), stallMs); + }; + const noteNativeError = () => { + if (logCtx) { logCtx.errorCode = GEMINI_NATIVE_ERROR_CODE; logCtx.terminalSource = "upstream"; } + }; + let upstream: Response | undefined; + try { + const maxBytes = Math.min(GEMINI_NATIVE_MAX_BYTES, config.maxInboundBodyBytes ?? GEMINI_NATIVE_MAX_BYTES); + // Upload protection is independent of upstream silence: disabling model stalls must not + // let an authenticated client hold an admission lease with an unfinished JSON upload. + const bodyIdleMs = resolveStallTimeoutMs(config.stallTimeoutSec) || DEFAULT_STALL_TIMEOUT_SEC * 1000; + const armBodyRead = () => { + clearTimeout(bodyReadTimer); + bodyReadTimer = setTimeout(() => ac.abort(new NativeRequestBodyTimeout()), bodyIdleMs); + }; + const input = req.body?.pipeThrough(new TransformStream({ + transform(chunk, controller) { if (chunk.byteLength) armBodyRead(); controller.enqueue(chunk); }, + })) ?? null; + let raw: string | null; + armBodyRead(); + try { raw = await readGeminiText(input, maxBytes, ac.signal); } + catch (error) { + if (ac.signal.aborted) throw error; + 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(); + const boundCredentials = new Set(); + for (let attempt = 0; attempt < 2; attempt++) { + ac.signal.throwIfAborted(); + if (!access.projectId) { finish(); return geminiNativeError(503, "Antigravity project missing; sign in again"); } + try { + assertProviderDestinationAllowed(GEMINI_NATIVE_PROVIDER, { ...provider, baseUrl }); + const base = new URL(baseUrl); + if (base.username || base.password || base.search || base.hash) throw new NativeConfigurationInvalid(); + } 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, () => { + 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 { 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); + }); + if (upstream.status !== 401 || attempt === 1) break; + 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) { + void upstream.body?.cancel().catch(() => {}); + finish(); + const response = geminiNativeError(upstream.status >= 400 ? upstream.status : 502, "Antigravity upstream rejected the request"); + const retryAfter = upstream.headers.get("retry-after"); + if (retryAfter && /^\d{1,6}$/.test(retryAfter)) response.headers.set("Retry-After", retryAfter); + return response; + } + if (!upstream.body) throw new Error("missing upstream response body"); + const reader = upstream.body.getReader(); + const cancel = onUpstreamAbort = () => { void reader.cancel(ac.signal.reason).catch(() => {}); }; + ac.signal.addEventListener("abort", cancel, { once: true }); + armStall(); + const body = new ReadableStream({ + async pull(controller) { + try { + ac.signal.throwIfAborted(); armStall(); + const next = await reader.read(); + ac.signal.throwIfAborted(); armStall(); + if (next.done) { controller.close(); finish(); ac.signal.removeEventListener("abort", cancel); } + else controller.enqueue(next.value); + } catch (error) { controller.error(error); ac.abort(error); finish(); } + }, + cancel(reason) { ac.abort(reason); finish(); return reader.cancel(reason); }, + }); + 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 }); + } + 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)) { + noteNativeError(); + return geminiNativeError(502, "Antigravity upstream rejected the request"); + } + return new Response(response, { headers: { "Content-Type": "application/json" } }); + } catch (error) { + ac.abort(); finish(); + void upstream?.body?.cancel().catch(() => {}); + if (req.signal.aborted) return geminiNativeError(499, "Request cancelled"); + if (error instanceof NativeRequestBodyTimeout) return geminiNativeError(408, "Gemini request body upload stalled; send a complete JSON body and retry"); + if (error instanceof OAuthLoginRequiredError) return geminiNativeError(503, "Antigravity sign-in required; run ocx login google-antigravity"); + if (error instanceof OAuthAccountPausedError) return geminiNativeError(503, "Antigravity account is paused; resume it in OC account settings and retry"); + if (error instanceof OAuthTokenRefreshBusyError || error instanceof OAuthTokenRefreshStaleError) { + const response = geminiNativeError(503, "Antigravity credential refresh is temporarily busy; retry shortly"); + response.headers.set("Retry-After", "1"); return response; + } + if (error instanceof RequestPacingQueueOverloadError) { + const response = geminiNativeError(429, "Antigravity request queue is temporarily full; retry after the indicated delay"); + const seconds = Number.isFinite(error.retryAfterSeconds) ? Math.max(1, Math.ceil(error.retryAfterSeconds)) : 5; + response.headers.set("Retry-After", String(seconds)); return response; + } + 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 NativeWorkflowSendDenied) { + const refusal = workflowRefusalResponse("workflow-sends-exhausted", logCtx, undefined, rootId); + return carryWorkflowRefusal(refusal, geminiNativeError(429, "OpenCodex workflow physical-send budget exhausted")); + } + return geminiNativeError(req.signal.aborted ? 499 : 502, req.signal.aborted ? "Request cancelled" : "Gemini native upstream request failed"); + } +} diff --git a/src/server/index/gemini-routes.ts b/src/server/index/gemini-routes.ts index 2217489c315..0d3c62780ed 100644 --- a/src/server/index/gemini-routes.ts +++ b/src/server/index/gemini-routes.ts @@ -6,14 +6,22 @@ * `?key=` query parameter, so the request is cloned with that credential moved onto * `x-opencodex-api-key` and the query key dropped; the key is never logged or forwarded. */ +import { ADVISOR_INTERNAL_CAPABILITY_HEADER } from "../../lib/local-internal-call-capability"; +import { clientFacingModelLabel, clientFacingModelText } from "../../lib/error-destination"; import { classifyUsageClient } from "../../usage/client"; -import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors, type RequestPolicyView } from "../auth-cors"; +import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors } from "../auth-cors"; +import { AdmissionModelDeniedError, projectAdmissionModelDeniedLog, routeAllowedByScope } from "../admission-model-scope"; +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 { 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"; +import { nativeGeminiDestination } from "../gemini-native-catalog"; +import { handleGeminiNative } from "../gemini-native"; +import { logGeminiNativeDelivery } from "../gemini-native-log"; +import { nativeInnerErrorMessage } from "../native-chat-bridge"; import { nextRequestLogId, type RequestLogContext } from "../request-log"; import { runAdmittedBodyWork } from "../inbound-body-admission"; import { disableResponsesRequestTimeout } from "../responses"; @@ -104,6 +112,25 @@ async function handleGeminiRoute(route: GeminiNativeRoute, original: Request, ur const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission); const response = await deps.runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => { ownsRequestLog = true; + // Internal Advisor and sidecar hops keep the Chat bridge's capability and inherited-policy checks. + const native = route.kind === "method" && url.pathname.startsWith("/v1beta/") && !sessionReq.headers.has(ADVISOR_INTERNAL_CAPABILITY_HEADER) + && !sessionReq.headers.has(SIDECAR_INTERNAL_CAPABILITY_HEADER) + ? nativeGeminiDestination(config, sessionReq, route.model) : undefined; + if (native && route.kind === "method") { + const modelLabel = clientFacingModelLabel(route.model); + logCtx.requestedModel = clientFacingModelText(modelLabel); + let result: Response; + if (!routeAllowedByScope(advisorAdmissionPolicy.modelScope, native.route)) { + projectAdmissionModelDeniedLog(new AdmissionModelDeniedError(modelLabel, native.route), logCtx); + result = geminiError(403, nativeInnerErrorMessage(403)); + } else { + logCtx.model = native.route.modelId; + logCtx.provider = native.route.providerName; + const delivery = route.method === "streamGenerateContent" ? (sse ? "sse" : "array") : undefined; + result = await handleGeminiNative(sessionReq, config, native.wireModel, delivery, turnAdmissionLease, undefined, logCtx); + } + return withCors(logGeminiNativeDelivery(result, sessionReq, requestId, start, logCtx), original, policy); + } const ids = { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }; return withCors( route.kind === "method" diff --git a/src/server/management/protocol-settings-patch.ts b/src/server/management/protocol-settings-patch.ts index 0dd2a82efe5..05188aefa5e 100644 --- a/src/server/management/protocol-settings-patch.ts +++ b/src/server/management/protocol-settings-patch.ts @@ -32,6 +32,7 @@ export const PROTOCOL_ROLLOUT_KEYS = [ "managedMessagesNativeOAuth", "directEncoders", "antigravityDirect", + "geminiNativeAntigravity", "shadowPlan", ] as const satisfies readonly (keyof ProtocolRolloutSettings)[]; const ROLLOUT_KEYS = new Set(PROTOCOL_ROLLOUT_KEYS); diff --git a/src/types/config.ts b/src/types/config.ts index 9f264655cde..ab68af04707 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -48,6 +48,8 @@ export interface OcxProtocolsConfig { * answered through the direct encoders, with no internal Responses body in either direction. */ antigravityDirect?: boolean; + /** Preserve native Gemini payloads for concrete Antigravity OAuth routes on /v1beta. Default off. */ + geminiNativeAntigravity?: boolean; /** Compare the dispatch plan with the observed path; never sends a second request. */ shadowPlan?: boolean; }; diff --git a/structure/INDEX.md b/structure/INDEX.md index f1915071b7b..640e91197b3 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -68,6 +68,7 @@ The wire surfaces a client actually talks to. | [`data-planes/search.md`](data-planes/search.md) | Hosted search relay and exact account selectors. | | [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md) | Chat Completions inbound, Anthropic-shaped clients, and JSON-upstream streaming clients. | | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | Physical-adapter tool-loading projections (Responses additional_tools and the Chat use_loaded_tool dispatcher with its response rewrite), preserved catalogs, fallback exclusions and opt-in prerequisites. | +| [`data-planes/gemini-native.md`](data-planes/gemini-native.md) | Opt-in source-preserving Gemini requests over Antigravity OAuth within the shared Gemini ingress. | | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | Ollama-shaped version/tags/show/chat/generate routes translated onto Chat Completions, their admission, native error shape and final request-log ownership. | | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | Gemini-shaped models/generateContent/streamGenerateContent and Interactions API routes translated onto Chat Completions, the x-goog-api-key and ?key= credential move, the native error shape, SSE and JSON-array streaming, the Interactions SSE vocabulary, and the Chat bridge shared with the Ollama inbound. | | [`data-planes/error-detail.md`](data-planes/error-detail.md) | Closed error codes, upstream condition classification, numeric quota reset, closed failure detail, service tier and model identity bounds on request-log rows; response metadata header normalization and the client Retry-After format. Chat client error envelopes, literal tables, proxy-authored message provenance, collector verdicts and internal evidence channels; fixed undeclared-tool refusals, producer-owned incomplete-event origins and constructor-bounded destination labels, branded original client selectors, bounded combo exclusions and fixed retry-evidence diagnostics. Original model labels on synthetic terminal envelopes and compact/Messages ingress handoffs. Messages error envelopes, construction-registered fixed local-refusal guidance, sliced outcome comparisons and baseline client recovery outcomes across special codes and catch returns, non-2xx passthrough envelopes and unchanged 2xx passthrough bodies and original collector evidence and error-event identity, overflow/native-stream golden parity and normalized Anthropic response headers with full-fraction reset dates and success media types. | @@ -493,14 +494,18 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/gemini-inbound.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/gemini-interactions-inbound.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/gemini-interactions-store.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | +| `src/server/gemini-native-catalog.ts` | [`data-planes/gemini-native.md`](data-planes/gemini-native.md) | +| `src/server/gemini-native-log.ts` | [`data-planes/gemini-native.md`](data-planes/gemini-native.md) | | `src/server/gemini-native-paths.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | +| `src/server/gemini-native-wire.ts` | [`data-planes/gemini-native.md`](data-planes/gemini-native.md) | +| `src/server/gemini-native.ts` | [`data-planes/gemini-native.md`](data-planes/gemini-native.md) | | `src/server/gui-pair-delivery.ts` | [`remote-link.md`](remote-link.md) | | `src/server/hub-relay-auth.ts` | [`remote-link.md`](remote-link.md) | | `src/server/hub-usage.ts` | [`usage-client-attribution.md`](usage-client-attribution.md) | | `src/server/images.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/index.ts` | [`adapters/compatibility-lab.md`](adapters/compatibility-lab.md) | | `src/server/index/` | [`usage-client-attribution.md`](usage-client-attribution.md) | -| `src/server/index/gemini-routes.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | +| `src/server/index/gemini-routes.ts` | [`data-planes/gemini-native.md`](data-planes/gemini-native.md)
[`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/index/link-management.ts` | [`remote-link.md`](remote-link.md) | | `src/server/index/link-websocket-limits.ts` | [`remote-link.md`](remote-link.md) | | `src/server/index/link-websocket.ts` | [`remote-link.md`](remote-link.md) | diff --git a/structure/clients/antigravity-gateway.md b/structure/clients/antigravity-gateway.md index f7f61c90ba0..8eef4425e74 100644 --- a/structure/clients/antigravity-gateway.md +++ b/structure/clients/antigravity-gateway.md @@ -105,3 +105,7 @@ instance refuses the mutations. `ocx connect|disconnect antigravity|agy` and `ocx connect antigravity|agy status` in `src/cli/gateway-client-command.ts` call those routes through the running proxy and run the same connectors in-process when the proxy is not running. The dispatch branch sits before the hub `connect` logic and the disconnect restart flow, which are about a remote hub and do not apply. + +The Gemini-compatible gateway surface uses the [Gemini inbound dispatcher](../data-planes/gemini-inbound.md). +The optional [Antigravity OAuth native leg](../data-planes/gemini-native.md) is configured in +OpenCodex and selected for an eligible route after admission. diff --git a/structure/config.md b/structure/config.md index b6d5e973120..2868b014795 100644 --- a/structure/config.md +++ b/structure/config.md @@ -593,7 +593,7 @@ to absence so an optional monitoring typo cannot discard providers or credential boundary runs `metricsExportConfigError` in `src/config/diagnostics.ts` before the degrading schema, so wrong types and unknown nested fields are rejected rather than silently saved. Activation is read when the server process creates its serve options and therefore requires restart; it adds no setting to the live `/api/settings` mutation surface. -`apiSurfaces` and `protocols` on `src/types/config.ts` are parsed by `src/protocols/settings.ts` only; [Protocol Paths](data-planes/protocol-paths.md#settings) owns their schema handling, meaning and the one writer (`PATCH /api/protocols/settings`), including why closing Messages also writes `claudeCode.enabled` through `commitClaudeCodeBlock` (`src/claude/claude-code-block.ts`, the sentinel-stamping block writer every management route uses). +`apiSurfaces` and `protocols` on `src/types/config.ts` are parsed by `src/protocols/settings.ts` only; [Protocol Paths](data-planes/protocol-paths.md#settings) owns their schema handling, meaning and the one writer (`PATCH /api/protocols/settings`), including why closing Messages also writes `claudeCode.enabled` through `commitClaudeCodeBlock` (`src/claude/claude-code-block.ts`, the sentinel-stamping block writer every management route uses). The optional boolean `protocols.rollout.geminiNativeAntigravity` defaults off and malformed file policy cannot enable it. See [Native Gemini Inbound](data-planes/gemini-native.md). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. Proxy activation and credential-safe CLI output follow [Proxy Configuration](config-proxy.md). The experimental `chatgptDesktop` leaf accepts only optional boolean `appServerShim`, default off. Malformed reads disable this leaf; live writes reject malformed values and unknown keys. `src/config/diagnostics.ts` reports the reason a whole `chatgptDesktop` block is dropped on both normal and salvaged reads; salvage retains its fallback source and schema error. Its activation and local executable boundary follow [ChatGPT Desktop](clients/chatgpt-desktop.md). `claudeCode.subagentModelForce` is an optional safe roster-style id. Invalid hand edits degrade with a warning without losing other config; stale but syntactically valid targets remain stored for repair and are skipped at launch. Management force updates are field-scoped against current disk state, preserving concurrent Claude sibling edits. A config absent at request start uses canonical create-only initialization; a racing file or invalid initial state refuses the save, and an existing-file mutation never recreates deleted config. Clearing removes only that leaf. A malformed `asideProfileSync` still loads as `{ allProfiles: false }`, which turns every Aside profile off, so `warnDegradedTopLevelOptIns` in `src/config/load-degrade.ts` now reports it once per load without echoing a key or value. diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 4f8c0fad2bf..798dee0e524 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -3,7 +3,9 @@ Gemini clients (the google-genai SDK with a custom base URL, `agy` with its `genai` gateway wire protocol, `GOOGLE_GEMINI_BASE_URL`) can use configured provider routes through the Gemini REST shape. Like the [Ollama inbound](ollama-inbound.md) it is a translation onto the -[Chat Completions inbound](inbound-compat.md) path and never talks to Google itself. +[Chat Completions inbound](inbound-compat.md) path by default. The default-off +[Antigravity OAuth passthrough](gemini-native.md) runs after the same admission for eligible +`/v1beta` generation. Eligible native wire aliases augment the model catalog when enabled. `src/server/gemini-native-paths.ts` classifies a path: `GET /v1beta/models`, `GET /v1beta/models/{model}`, and `POST /v1beta/models/{model}:{method}` or @@ -43,7 +45,7 @@ more than 1,024 function calls) is a 400. Responses map Chat finish `stop` and ` error, never a success. A streamed tool call is accumulated and emitted as one whole `functionCall` part. Usage becomes `usageMetadata`, with reasoning tokens reported as `thoughtsTokenCount`. -`src/server/gemini-inbound.ts` owns delivery. With `alt=sse` a stream is `data: \r\n\r\n` +`src/server/gemini-inbound.ts` owns translated delivery. With `alt=sse` a stream is `data: \r\n\r\n` frames; without it, one streamed JSON array. The closing chunk (finish reason and usage) is emitted only after the Chat stream reached EOF and the inner path settled, through the shared pump in `src/server/native-chat-bridge.ts` that Ollama also uses: identity-only internal Chat request, diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md new file mode 100644 index 00000000000..02d90843f04 --- /dev/null +++ b/structure/data-planes/gemini-native.md @@ -0,0 +1,51 @@ +# Native Gemini Inbound + +The [Gemini-compatible dispatcher](gemini-inbound.md) owns every path, listener decision and +admission check. In `src/server/index/gemini-routes.ts`, the native leg is available only for +`/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. + +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. + +`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 +headers and the bound OAuth credential go upstream. + +`src/server/gemini-native-wire.ts` validates the JSON object and embeds the original request +under the CCA `request` member. It extracts successful `response` members by source offsets +so unknown fields, integer precision, number spelling, tool arguments and thought signatures +survive. CCA SSE is reframed as Gemini SSE with `alt=sse` and as a streamed JSON array otherwise. +Malformed or oversized events, missing or duplicate envelopes, incomplete final events and +EOF before all observed candidates finish terminate delivery without a replay. A blocked prompt +also counts as completion when no candidates were observed. A valid `[DONE]` or a sanitized +in-band error ends delivery and cancels the upstream body. Before sending buffered JSON or a +complete stream frame, the native leg checks the original JSON and its decoded strings for +bound OAuth tokens, project IDs and private account identifiers from both sends. A match returns +the same fixed Gemini error as an in-band upstream error. HTTP failures retain only bounded +numeric retry advice. + +Request and buffered response bodies and each SSE event have a 16 MiB ceiling. A lower +`maxInboundBodyBytes` narrows the request limit. Compressed requests are refused with 415. +Headers use `connectTimeoutMs` and upstream body inactivity uses `stallTimeoutSec`, with +non-positive values disabling that upstream timer. Upload inactivity has an independent timer +that resets per chunk and clears before OAuth and pacing. Disabling upstream stalls leaves the +default 300-second upload timeout in effect. A stalled upload returns 408. Cancellation, +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. + +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/inbound-compat.md b/structure/data-planes/inbound-compat.md index 7a1515dba7b..cc58d5cbc4b 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -3,7 +3,7 @@ Native Chat/Messages and Claude passthrough use the [local timeout contract](../transports/timeouts.md): local JSON inactivity is independent of header arrival and total generation; public JSON defaults -retain their previous allowance. No disabled header clock detaches client cancellation. +retain their previous allowance. No disabled header clock detaches client cancellation. Gemini `/v1beta` uses the shared dispatcher with an [optional source-preserving Antigravity leg](gemini-native.md). Thinking enablement is separate from strength: `src/responses/schema.ts` accepts the OCX `reasoning.enabled` boolean and `src/responses/parser.ts` retains it as `options.thinkingEnabled`, independently of `options.reasoning`. Chat `thinking.type` and Anthropic `thinking.type` preserve this choice through their inbound translators; the existing Anthropic disabled-effort sentinel remains for legacy destinations. `src/clients/reasoning-controls.ts` decodes effort-only client aliases for declared toggle-only models before strength caps run. Route fallback restores the original choice alongside effort in `src/server/effort-policy.ts`; a cleared strength list does not clear a thinking switch. Regression coverage lives in `tests/responses/responses-parser.test.ts`, `tests/responses/chat-inbound-reasoning-none.test.ts`, `tests/claude-integration/claude-inbound.test.ts`, and `tests/codex-integration/effort-policy.test.ts`. diff --git a/structure/data-planes/protocol-paths.md b/structure/data-planes/protocol-paths.md index 31c328904dc..cb6dea2b04e 100644 --- a/structure/data-planes/protocol-paths.md +++ b/structure/data-planes/protocol-paths.md @@ -554,8 +554,8 @@ the key-auth one. The Chat and Messages ingresses read the unrepresentable polic the Messages ingress and the planner; the Chat ingress reads `nativeChatCombos` for combo routes (above); `managedMessagesNative` and `managedMessagesNativeOAuth` are read through `nativeMessagesDeclineReason` by the Messages ingress, `count_tokens` and the planner -(above); `shadowPlan` is read by `recordProtocolShadowPlan` ([Shadow plan](#shadow-plan)). Every -rollout switch now has a reader. +(above). `geminiNativeAntigravity` enables the [native Gemini leg](gemini-native.md) for eligible +`/v1beta` requests. `recordProtocolShadowPlan` reads `shadowPlan` ([Shadow plan](#shadow-plan)). `claudeInboundDisabled` in `src/server/claude-messages.ts` is the Messages ingress reader: both `/v1/messages` and `/v1/messages/count_tokens` call it, so the two routes cannot disagree, and a diff --git a/structure/manifest.json b/structure/manifest.json index ec9ab6663c7..e17bd25fa01 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -548,6 +548,19 @@ "scope": "Physical-adapter tool-loading projections (Responses additional_tools and the Chat use_loaded_tool dispatcher with its response rewrite), preserved catalogs, fallback exclusions and opt-in prerequisites.", "documents": ["src/claude/", "src/server/responses/", "src/types/claude-tool-loading.ts"] }, + { + "path": "data-planes/gemini-native.md", + "tier": 3, + "title": "Native Gemini Inbound", + "scope": "Opt-in source-preserving Gemini requests over Antigravity OAuth within the shared Gemini ingress.", + "documents": [ + "src/server/gemini-native.ts", + "src/server/gemini-native-wire.ts", + "src/server/gemini-native-catalog.ts", + "src/server/gemini-native-log.ts", + "src/server/index/gemini-routes.ts" + ] + }, { "path": "data-planes/ollama-inbound.md", "tier": 3, diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md index ace50c17c31..fe68870ea02 100644 --- a/structure/usage-client-attribution.md +++ b/structure/usage-client-attribution.md @@ -243,3 +243,7 @@ and the request-log hydration keep only `p` plus six lowercase hex digits and dr Per-account summaries still key on `accountLogLabel` and ignore the tag (`tests/usage/request-log-anthropic-account-tag.test.ts`). Remote Link rows may carry an optional `link` object (transport, continuation, hashed thread and turn refs) while the link WebSocket feature is on; it is validated in `src/usage/link-log-fields.ts` and spread into the row, the persisted entry and hydration, and described in `structure/remote-link.md`. + +Opted-in native Gemini delivery uses `src/server/gemini-native-log.ts` for client and admission attribution, +status and latency. It does not inspect source payloads or report token usage; see +[Native Gemini Inbound](data-planes/gemini-native.md). diff --git a/tests/adapters/anthropic/anthropic-fast-opt-in.test.ts b/tests/adapters/anthropic/anthropic-fast-opt-in.test.ts index 524a4ddc3cd..70fa86e0242 100644 --- a/tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +++ b/tests/adapters/anthropic/anthropic-fast-opt-in.test.ts @@ -1,4 +1,4 @@ -import { afterAll, describe, expect, setDefaultTimeout, test } from "bun:test"; +import { afterAll, describe, expect, setDefaultTimeout, spyOn, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -13,6 +13,7 @@ import { startServer } from "../../../src/server"; import { catalogFastRowEligible } from "../../../src/server/fast-row"; import type { OcxConfig, OcxProviderConfig } from "../../../src/types"; import { managementFetch as fetch } from "../../helpers/management-auth"; +import * as destinationPolicy from "../../../src/lib/destination-policy"; import { removeTreeWithRetry } from "../../helpers/remove-tree"; /** @@ -124,6 +125,8 @@ describe("Anthropic Fast switch over the management API", () => { }, } as OcxConfig); const server = startServer(0); + // Configuration persistence is independent of the host DNS resolver. + const resolvedDestination = spyOn(destinationPolicy, "providerDestinationResolvedError").mockResolvedValue(null); const patch = (body: unknown) => fetch(new URL("/api/providers?name=anthropic-apikey", server.url), { method: "PATCH", headers: { "content-type": "application/json" }, @@ -162,6 +165,7 @@ describe("Anthropic Fast switch over the management API", () => { expect(loadConfig().providers["anthropic-apikey"]).not.toHaveProperty("fastEnabled"); expect((await summary("anthropic-apikey"))?.fastOptIn).toEqual({ enabled: false }); } finally { + resolvedDestination.mockRestore(); await server.stop(true); } }); diff --git a/tests/claude-integration/claude-messages-endpoint.test.ts b/tests/claude-integration/claude-messages-endpoint.test.ts index 6a8eae60eef..d31fa6fbd5b 100644 --- a/tests/claude-integration/claude-messages-endpoint.test.ts +++ b/tests/claude-integration/claude-messages-endpoint.test.ts @@ -1,5 +1,6 @@ import { expect } from "bun:test"; import { installEndpointHooks, test, fetch, startServer, serveUpstream, ownCleanup, caseSignal, testDir, isolatedCodexHome, originalFetch } from "../helpers/claude-endpoint-lifetime"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { logsFromApiBody } from "../helpers/logs-api"; import { rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -644,6 +645,10 @@ test("native openai-responses route carries prompt_cache_key + synthesized sessi return new Response(frames.join(""), { headers: { "Content-Type": "text/event-stream" } }); }, }); + // This fixture serves HTTP/SSE only: refuse native WSS instead of reaching chatgpt.com. + const originalWebSocket = globalThis.WebSocket; + ownCleanup(() => { globalThis.WebSocket = originalWebSocket; }); + redirectCanonicalCodexTo(upstream.url.toString()); globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; const url = new URL(requestUrl); diff --git a/tests/claude-integration/claude-outbound.test.ts b/tests/claude-integration/claude-outbound.test.ts index 163d7d5e27f..f7c3bc8a8e3 100644 --- a/tests/claude-integration/claude-outbound.test.ts +++ b/tests/claude-integration/claude-outbound.test.ts @@ -6,6 +6,7 @@ import { startServer } from "../../src/server"; import type { OcxConfig } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { anthropicErrorBody, @@ -1821,6 +1822,7 @@ describe("Messages ingress context errors", () => { let previousHome: string | undefined; let isolated: IsolatedCodexHome; const originalFetch = globalThis.fetch; + const originalWebSocket = globalThis.WebSocket; beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; @@ -1830,6 +1832,7 @@ describe("Messages ingress context errors", () => { }); afterEach(() => { globalThis.fetch = originalFetch; + globalThis.WebSocket = originalWebSocket; isolated.restore(); if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; @@ -1857,6 +1860,8 @@ describe("Messages ingress context errors", () => { } } as OcxConfig; if (canonical) { config.providers.native!.baseUrl = "https://chatgpt.com/backend-api/codex"; + // This fixture owns HTTP/SSE only; keep native WSS off the real service. + redirectCanonicalCodexTo(upstream.url.toString()); globalThis.fetch = ((input, init) => { const url = input instanceof Request ? input.url : String(input); if (url === "https://chatgpt.com/backend-api/codex/responses") { diff --git a/tests/codex-integration/catalog-omit-disabled-native.test.ts b/tests/codex-integration/catalog-omit-disabled-native.test.ts index 8980d518bf9..346c10d5725 100644 --- a/tests/codex-integration/catalog-omit-disabled-native.test.ts +++ b/tests/codex-integration/catalog-omit-disabled-native.test.ts @@ -10,6 +10,7 @@ import { getConfigPath, loadConfig, saveConfig } from "../../src/config"; import type { OcxConfig } from "../../src/types"; import { CODEX_FORWARD_BASE_URL } from "../../src/providers/openai-tiers"; import { startServer } from "../../src/server"; +import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; import { buildCodexModelList } from "../../src/server/codex-model-list"; import { desktopAllowlistSuppressedNativeSlugs } from "../../src/codex/catalog/metadata"; import { NATIVE_OPENAI_MODELS } from "../../src/codex/catalog/native-models"; @@ -195,7 +196,7 @@ test("retained sync and serve-options omit the same rows without changing routed const next = config(true); saveConfig(next); expect((await syncCatalogModels(next, { allowWhenDesiredDisabled: true })).refreshOutcome).toBe("committed"); - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); try { const response = await fetch(new URL("/v1/models?client_version=0.160.0", server.url)); expect(response.status).toBe(200); @@ -255,7 +256,7 @@ async function upgradedOutputs(flag: boolean, model: string, method: "convergenc } const cache = JSON.parse(readFileSync(join(home.codexHome, "models_cache.json"), "utf8")) as RawCatalog; const live = liveList(next); - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); let http: RawCatalog; try { const response = await fetch(new URL("/v1/models?client_version=0.160.0", server.url)); diff --git a/tests/codex-integration/issue-452-empty-503.test.ts b/tests/codex-integration/issue-452-empty-503.test.ts index d8aa8049535..63e964a13d4 100644 --- a/tests/codex-integration/issue-452-empty-503.test.ts +++ b/tests/codex-integration/issue-452-empty-503.test.ts @@ -11,11 +11,13 @@ import { getDebugLogEntries, resetDebugLogBufferForTests } from "../../src/lib/d import { resetDebugSettingsForTests } from "../../src/lib/debug-settings"; import { setDraining } from "../../src/server/lifecycle"; import { startServer } from "../../src/server"; +import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; import { findAvailablePort } from "../../src/server/ports"; import { readDisplaySafeErrorText } from "../../src/server/responses/core"; import { formatPassthroughUpstreamError } from "../../src/server/responses/passthrough-error"; import type { OcxConfig, OcxParsedRequest } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { SERVER_BUDGET_MS } from "../helpers/test-budget"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -23,21 +25,10 @@ const previousApiToken = process.env.OPENCODEX_API_AUTH_TOKEN; const previousOpencodexHome = process.env.OPENCODEX_HOME; const previousOcxDebug = process.env.OCX_DEBUG; const originalGlobalFetch = globalThis.fetch; +const originalWebSocket = globalThis.WebSocket; const TEST_DIR = join(import.meta.dir, ".tmp-issue-452-empty-503"); let isolatedCodexHome: IsolatedCodexHome | null = null; -function redirectCanonicalCodexTo(baseUrl: string): void { - globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { - const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; - const url = new URL(requestUrl); - const prefix = "/backend-api/codex"; - if (url.hostname === "chatgpt.com" && url.pathname.startsWith(prefix)) { - const target = new URL(`${url.pathname.slice(prefix.length)}${url.search}`, baseUrl); - return originalGlobalFetch(target, init); - } - return originalGlobalFetch(input, init); - }) as typeof fetch; -} beforeEach(() => { isolatedCodexHome = installIsolatedCodexHome("ocx-issue-452-"); @@ -48,6 +39,7 @@ beforeEach(() => { afterEach(() => { globalThis.fetch = originalGlobalFetch; + globalThis.WebSocket = originalWebSocket; setDraining(false); if (previousApiToken === undefined) delete process.env.OPENCODEX_API_AUTH_TOKEN; else process.env.OPENCODEX_API_AUTH_TOKEN = previousApiToken; @@ -234,7 +226,7 @@ async function withPoolPassthrough( }); updateAccountQuota("pool-a", 10); - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); try { await run(server.url.toString()); } finally { diff --git a/tests/codex-integration/issue-702-expired-replay-state.test.ts b/tests/codex-integration/issue-702-expired-replay-state.test.ts index 2beed684681..0006f1304c8 100644 --- a/tests/codex-integration/issue-702-expired-replay-state.test.ts +++ b/tests/codex-integration/issue-702-expired-replay-state.test.ts @@ -21,18 +21,21 @@ import { responseSpillDirectory } from "../../src/responses/spill-store"; import { PLAINTEXT_V2_COLLABORATION_NAMESPACE } from "../../src/responses/plaintext-v2-agent-messages"; import { startServer } from "../../src/server"; import { aggregateTelemetryForDay } from "../../src/telemetry/aggregate"; +import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; import type { OcxConfig } from "../../src/types"; import { readRecentUsageEntries } from "../../src/usage/log"; import { computeEntryCost, summarizeUsage } from "../../src/usage/summary"; import { codexHeaders, encryptedInput } from "../helpers/agent-task-recovery"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { INTERNAL_DEADLINE_MS, SERVER_BUDGET_MS } from "../helpers/test-budget"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { rememberOwnedResponseState as rememberResponseState, responseReplayFixtureApiKeys, responseReplayFixtureHeaders } from "../helpers/response-replay-owner"; const originalFetch = globalThis.fetch; +const originalWebSocket = globalThis.WebSocket; const previousOpencodexHome = process.env.OPENCODEX_HOME; const previousApiToken = process.env.OPENCODEX_API_AUTH_TOKEN; const REPLAY_TTL_MS = RESPONSE_TTL_MS; @@ -214,7 +217,7 @@ async function runForwardScenario( }) as typeof fetch; saveConfig(forwardConfig()); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const token = fakeChatGptJwt({ chatgpt_account_id: "acct-issue-702" }); const requestHeaders = { ...(mode === "ordinary" ? {} : responseReplayFixtureHeaders()), @@ -286,6 +289,8 @@ async function runForwardScenario( } beforeEach(() => { + // Native WSS must fall back to each test's HTTP fetch stub, never the network. + redirectCanonicalCodexTo("http://127.0.0.1"); testHome = mkdtempSync(join(tmpdir(), "ocx-issue-702-")); process.env.OPENCODEX_HOME = testHome; delete process.env.OPENCODEX_API_AUTH_TOKEN; @@ -296,6 +301,7 @@ beforeEach(() => { afterEach(() => { globalThis.fetch = originalFetch; + globalThis.WebSocket = originalWebSocket; clearResponseStateForTests(); setResponseStateByteCapForTests(null); resetSubagentModelFallbackStateForTests(); @@ -373,7 +379,7 @@ describe("routed replay recovery", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const deltaRequest = { model: "routed-test/test-model", previous_response_id: FIRST_RESPONSE_ID, input: [toolResult], tools, store: false, @@ -488,7 +494,7 @@ describe("routed replay recovery", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const refused = await originalFetch(new URL("/v1/responses", server.url), { method: "POST", @@ -568,7 +574,7 @@ describe("routed replay recovery", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const response = await originalFetch(new URL("/v1/responses", server.url), { method: "POST", headers: { "content-type": "application/json", ...responseReplayFixtureHeaders() }, @@ -662,7 +668,7 @@ describe("Issue #702 expired forward replay state", () => { try { for (const routeClass of routeClasses) { saveConfig(routeClass.config); - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); try { const response = await originalFetch(new URL("/v1/responses", server.url), { method: "POST", @@ -746,7 +752,7 @@ describe("Issue #702 expired forward replay state", () => { return originalFetch(input, init); }) as typeof fetch; saveConfig({ ...forwardConfig(), websockets: true }); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const headers = { ...responseReplayFixtureHeaders(), authorization: `Bearer ${fakeChatGptJwt({ chatgpt_account_id: "acct-issue-702" })}`, @@ -1017,7 +1023,7 @@ describe("Issue #702 expired forward replay state", () => { throw new Error("upstream must not be called"); }) as typeof fetch; saveConfig(forwardConfig()); - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const token = fakeChatGptJwt({ chatgpt_account_id: "acct-issue-702" }); const ask = async (previousResponseId: string, threadId: string): Promise<{ status: number; body: string }> => { const response = await originalFetch(new URL("/v1/responses", server.url), { @@ -1089,7 +1095,7 @@ describe("Issue #702 expired forward replay state", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); socket = await openResponseSocket(server.url, responseReplayFixtureHeaders("task-b")); const refused = await sendSocketTurn(socket, { model: "routed-test/test-model", previous_response_id: FIRST_RESPONSE_ID, @@ -1160,7 +1166,7 @@ describe("Issue #702 expired forward replay state", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); rememberResponseState( { input: [inputMessage(HISTORICAL_USER_SENTINEL)], store: false }, { id: FIRST_RESPONSE_ID, status: "completed", output: [] }, @@ -1230,7 +1236,7 @@ describe("Issue #702 expired forward replay state", () => { }, }, } as OcxConfig); - server = startServer(0); + server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("isolated HTTP fixture") }); const response = await originalFetch(new URL("/v1/responses", server.url), { method: "POST", diff --git a/tests/codex-integration/native-profile-drain-server.test.ts b/tests/codex-integration/native-profile-drain-server.test.ts index 34fc9f71c5f..bba5e706222 100644 --- a/tests/codex-integration/native-profile-drain-server.test.ts +++ b/tests/codex-integration/native-profile-drain-server.test.ts @@ -24,12 +24,14 @@ import type { OcxConfig } from "../../src/types"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { watchdogMs } from "../helpers/ci-watchdog"; import { removeTreeWithRetry } from "../helpers/remove-tree"; /** These cases sandbox CODEX_HOME/OPENCODEX_HOME, so the installed service is not their evidence. */ const inspectNativeCodexOwnership = ownedServiceHomeInspection("native-profile drain server test"); const originalFetch = globalThis.fetch; +const originalWebSocket = globalThis.WebSocket; const previousOpencodexHome = process.env.OPENCODEX_HOME; const previousCodexHome = process.env.CODEX_HOME; let opencodexHome = ""; @@ -53,6 +55,7 @@ beforeEach(() => { afterEach(() => { globalThis.fetch = originalFetch; + globalThis.WebSocket = originalWebSocket; resetLifecycleDrainStateForTests(); clearAccountQuota(); clearThreadAccountMap(); @@ -69,6 +72,8 @@ afterEach(() => { describe("native main profile scoped server admission", () => { test("HTTP and Responses WebSocket keep Direct live while main Pool frames are rejected", async () => { let upstreamRequests = 0; + // The HTTP mock below owns inference; native WSS must not contact the real service. + redirectCanonicalCodexTo("http://127.0.0.1"); globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; if (url.includes("chatgpt.com/backend-api/codex/responses")) { diff --git a/tests/config/protocol-settings.test.ts b/tests/config/protocol-settings.test.ts index 32ca462c438..ed2cdba8854 100644 --- a/tests/config/protocol-settings.test.ts +++ b/tests/config/protocol-settings.test.ts @@ -59,6 +59,7 @@ describe("protocol settings resolution", () => { managedMessagesNativeOAuth: false, directEncoders: false, antigravityDirect: true, + geminiNativeAntigravity: false, shadowPlan: false, }, }); @@ -89,6 +90,7 @@ describe("protocol settings resolution", () => { expect(protocolPolicyRevision(cfg({ port: 1234 }))).toBe(base); expect(protocolPolicyRevision(cfg({ protocols: { unrepresentable: "reject" } }))).not.toBe(base); expect(protocolPolicyRevision(cfg({ claudeCode: { enabled: false } }))).not.toBe(base); + expect(protocolPolicyRevision(cfg({ protocols: { rollout: { geminiNativeAntigravity: true } } }))).not.toBe(base); expect(base).toMatch(/^p1-[0-9a-f]{8}$/); }); }); @@ -176,3 +178,26 @@ test("raw pool DTOs resolve absent to true, malformed to false and unsupported t } expect(unifiedPoolSettingsDto(cfg({ providers: {} }), "anthropic", "anthropic").nativeMessages).toBe(true); }); + +test("Gemini Antigravity native passthrough accepts only a boolean rollout opt-in", () => { + for (const value of [true, false]) { + const protocols = { rollout: { geminiNativeAntigravity: value } }; + const candidate = validateConfigCandidate({ + defaultProvider: "fixture", + providers: { fixture: { adapter: "openai-chat", baseUrl: "https://provider.invalid/v1", apiKey: "fixture-key" } }, + protocols, + }); + if (!candidate.ok) throw new Error(candidate.error); + expect(candidate.config.protocols?.rollout?.geminiNativeAntigravity).toBe(value); + expect(configSchema.shape.protocols.parse(protocols)).toEqual(protocols); + } + for (const value of ["true", null, 1, {}]) { + const protocols = { rollout: { geminiNativeAntigravity: value } }; + const candidate = validateConfigCandidate({ protocols }); + expect(candidate).toMatchObject({ ok: false, error: expect.stringContaining("schema_invalid: protocols") }); + expect(configSchema.shape.protocols.parse(protocols)?.rollout?.geminiNativeAntigravity).toBe(false); + } + expect(configSchema.shape.protocols.parse(undefined)).toBeUndefined(); + expect(configSchema.shape.protocols.parse({ rollout: { geminiNativeAntigravity: true, shadowPlan: "invalid" } }) + ?.rollout?.geminiNativeAntigravity).toBe(false); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 975df6054fd..664db54bea7 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", +{ "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", "codex-ws-recovery-budget.test.ts": "responses", "codex-ws-cache-miss.test.ts": "responses", "codex-ws-incremental.test.ts": "responses", diff --git a/tests/oauth/oauth-code-login.test.ts b/tests/oauth/oauth-code-login.test.ts index 3ff9ccd7d55..29b9c2cc2ae 100644 --- a/tests/oauth/oauth-code-login.test.ts +++ b/tests/oauth/oauth-code-login.test.ts @@ -60,6 +60,8 @@ function installTokenMock(reply: (request: TokenRequest) => TokenReply): { const originalFetch = globalThis.fetch; const requests: TokenRequest[] = []; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + // Token-exchange assertions do not depend on optional live profile enrichment. + if (String(input).startsWith("https://api.anthropic.com/api/oauth/profile")) return new Response("{}", { status: 401 }); if (!String(input).startsWith(TOKEN_URL)) return originalFetch(input, init); const request = JSON.parse(String(init?.body ?? "{}")) as TokenRequest; requests.push(request); diff --git a/tests/responses/chat-completions-pool-mode.test.ts b/tests/responses/chat-completions-pool-mode.test.ts index f03b31fbe62..40596161c2d 100644 --- a/tests/responses/chat-completions-pool-mode.test.ts +++ b/tests/responses/chat-completions-pool-mode.test.ts @@ -8,6 +8,7 @@ import { startServer } from "../../src/server"; import type { OcxConfig } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; const inspectNativeCodexOwnership = ownedServiceHomeInspection("chat completions pool-mode test"); @@ -17,6 +18,7 @@ describe("chat-completions pool vs direct credential injection", () => { let previousHome: string | undefined; let isolatedCodexHome: IsolatedCodexHome | null = null; const originalFetch = globalThis.fetch; + const originalWebSocket = globalThis.WebSocket; beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; @@ -30,6 +32,7 @@ describe("chat-completions pool vs direct credential injection", () => { if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; globalThis.fetch = originalFetch; + globalThis.WebSocket = originalWebSocket; if (isolatedCodexHome) { isolatedCodexHome.restore(); isolatedCodexHome = null; @@ -65,13 +68,16 @@ describe("chat-completions pool vs direct credential injection", () => { }, }); + // This upstream fixture serves HTTP only; native WSS must fall back locally too. + redirectCanonicalCodexTo(upstream.url.toString()); + const redirectedFetch = globalThis.fetch; globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { - const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; - const url = new URL(requestUrl); - if (url.hostname === "chatgpt.com" && url.pathname.startsWith("/backend-api/codex")) { - return originalFetch(new URL(`${url.pathname.slice("/backend-api/codex".length)}${url.search}`, upstream.url), init); + const url = new URL(input instanceof Request ? input.url : String(input)); + // Optional quota priming is unrelated to credential injection and must stay offline. + if (url.origin === "https://chatgpt.com" && url.pathname === "/backend-api/wham/usage") { + return Promise.resolve(Response.json({ rate_limit: { primary_window: { used_percent: 10 } } })); } - return originalFetch(input, init); + return redirectedFetch(input, init); }) as typeof fetch; let server: ReturnType | undefined; diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts new file mode 100644 index 00000000000..5160831f8d4 --- /dev/null +++ b/tests/server/gemini-native-routes.test.ts @@ -0,0 +1,223 @@ +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { saveCredential } from "../../src/oauth/store"; +import { startServer } from "../../src/server"; +import { nativeGeminiDestination } from "../../src/server/gemini-native-catalog"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const MODEL = "gemini-3.8-flash"; +const WIRE_MODEL = "gemini-3.8-flash-medium"; +const PROVIDER = "google-antigravity"; +const TARGET = `${PROVIDER}/${MODEL}`; +const CCA = "https://daily-cloudcode-pa.googleapis.com"; +const CHAT = "https://chat-fixture.invalid"; +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 RAW = '{"contents":[{"role":"user","parts":[{"text":"hello"}]}], "future":9007199254740993123}'; +const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"future":9007199254740993123}'; +const originalFetch = globalThis.fetch; +const previousEnv = { + OPENCODEX_HOME: process.env.OPENCODEX_HOME, + OPENCODEX_API_AUTH_TOKEN: process.env.OPENCODEX_API_AUTH_TOKEN, +}; +const seen: Array<{ url: URL; headers: Headers; body: string }> = []; +let home: string; + +beforeAll(async () => { + home = mkdtempSync(join(tmpdir(), "ocx-native-gemini-routes-")); + process.env.OPENCODEX_HOME = home; + process.env.OPENCODEX_API_AUTH_TOKEN = GOOGLE_KEY; + await saveCredential(PROVIDER, { + access: OAUTH_TOKEN, refresh: "fixture-google-oauth-refresh", + expires: Date.now() + 3_600_000, accountId: "fixture-google-account", + projectId: "fixture-google-project", source: "oauth", + }); +}); +afterAll(() => { + for (const [key, value] of Object.entries(previousEnv)) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + if (home) removeTreeWithRetry(home); +}); + +beforeEach(() => { + seen.length = 0; + 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 (init?.method !== "POST" || !url.pathname.includes("generateContent") && !url.pathname.includes("streamGenerateContent") && !url.pathname.endsWith("/chat/completions")) { + return Response.json({ models: [], data: [] }); + } + seen.push({ url, headers: new Headers(init.headers), body: String(init.body) }); + if (url.origin === CHAT) { + return Response.json({ + id: "chatcmpl-gemini-route-fixture", object: "chat.completion", created: 1, model: MODEL, + choices: [{ index: 0, message: { role: "assistant", content: "translated" }, finish_reason: "stop" }], + }); + } + 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" } }); + } + return new Response(envelope, { headers: { "content-type": "application/json", "set-cookie": "fixture-private" } }); + }, { preconnect: originalFetch.preconnect }); + globalThis.fetch = fixtureFetch; +}); +afterEach(() => { globalThis.fetch = originalFetch; }); + +function config(flag?: boolean): OcxConfig { + return { + port: 0, hostname: "0.0.0.0", defaultProvider: PROVIDER, + providers: { + [PROVIDER]: { adapter: "google", authMode: "oauth", baseUrl: CCA, googleMode: "cloud-code-assist", models: [MODEL, WIRE_MODEL] }, + fx: { adapter: "openai-chat", authMode: "key", baseUrl: CHAT + "/v1", apiKey: "fixture-chat-access", models: [MODEL] }, + }, + ...(flag === undefined ? {} : { protocols: { rollout: { geminiNativeAntigravity: flag } } }), + apiKeys: [ + { 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`] }, + ], + }; +} +async function withServer(cfg: OcxConfig, run: (base: URL) => Promise) { + saveConfig(cfg); + const server = startServer(0); + try { await run(server.url); } finally { await server.stop(true); } +} +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) => + originalFetch(new URL(path, base), { method: "POST", headers: { "content-type": "application/json", ...headers }, body: RAW }); +const get = (base: URL, path: string, headers: Record = key) => + originalFetch(new URL(path, base), { headers }); + +test("opted-in Gemini routes preserve native JSON and replace every ingress credential", async () => { + await withServer(config(true), async base => { + const response = await post(base, generation() + `?key=${GOOGLE_KEY}`, {}); + expect(response.status).toBe(200); + expect(response.headers.get("x-opencodex-request-id")).toBeTruthy(); + expect(response.headers.has("set-cookie")).toBe(false); + expect(await response.text()).toBe(PAYLOAD); + expect(seen).toHaveLength(1); + expect(seen[0]!.url.href).toBe(CCA + "/v1internal:generateContent"); + expect(seen[0]!.headers.get("authorization")).toBe("Bearer " + OAUTH_TOKEN); + expect(seen[0]!.headers.has("x-goog-api-key")).toBe(false); + expect(seen[0]!.headers.has("x-opencodex-api-key")).toBe(false); + expect(seen[0]!.body).toContain(`"request":${RAW}`); + expect(JSON.parse(seen[0]!.body)).toMatchObject({ model: WIRE_MODEL, project: "fixture-google-project" }); + }); +}); + +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 => { + const path = flag === true ? generation(TARGET, "generateContent", "v1") : generation() + "?ocx_native=true"; + const translated = await post(base, path); + expect(translated.status).toBe(200); + expect(await translated.json()).not.toHaveProperty("future"); + expect(seen.at(-1)?.body).not.toContain(RAW); + const other = await post(base, generation(`fx/${MODEL}`)); + expect(other.status).toBe(200); + expect(await other.text()).toContain("translated"); + expect(seen.at(-1)?.url.origin).toBe(CHAT); + expect(JSON.parse(seen.at(-1)!.body)).toMatchObject({ model: MODEL, messages: [{ role: "user", content: "hello" }] }); + }); + } +}); + +test("a Google OAuth clone and an overridden wire cannot take the canonical native leg", () => { + const cfg = config(true); + const canonical = cfg.providers[PROVIDER]!; + const req = new Request("http://localhost/v1beta/models"); + expect(nativeGeminiDestination(cfg, req, TARGET)?.wireModel).toBe(WIRE_MODEL); + cfg.providers.mirror = { ...canonical }; + expect(nativeGeminiDestination(cfg, req, `mirror/${MODEL}`)).toBeUndefined(); + canonical.modelAdapters = { [MODEL]: "openai-responses" }; + expect(nativeGeminiDestination(cfg, req, TARGET)).toBeUndefined(); +}); + +test("native streaming preserves records in both Gemini response formats", async () => { + await withServer(config(true), async base => { + const path = generation(TARGET, "streamGenerateContent"); + const sse = await post(base, path + "?alt=sse"); + expect(sse.headers.get("content-type")).toContain("text/event-stream"); + expect(await sse.text()).toBe(`data: ${PAYLOAD}\n\n`); + const discoverySse = await post(base, path + "?$alt=sse"); + expect(discoverySse.headers.get("content-type")).toContain("text/event-stream"); + expect(await discoverySse.text()).toBe(`data: ${PAYLOAD}\n\n`); + const json = await post(base, path); + expect(json.headers.get("content-type")).toContain("application/json"); + expect(await json.text()).toBe(`[\n${PAYLOAD}\n]`); + expect(seen.map(call => call.url.href)).toEqual(Array(3).fill(CCA + "/v1internal:streamGenerateContent?alt=sse")); + }); +}); + +test("native selection shares key, origin, host, and model-scope refusals", async () => { + await withServer(config(true), async base => { + for (const [headers, status, errorStatus] of [ + [{}, 401, "UNAUTHENTICATED"], + [{ "x-goog-api-key": "wrong" }, 401, "UNAUTHENTICATED"], + [{ ...key, origin: "https://foreign.example" }, 403, "PERMISSION_DENIED"], + [{ "x-goog-api-key": SCOPE_KEY }, 403, "PERMISSION_DENIED"], + [{ "x-goog-api-key": MODEL_SCOPE_KEY }, 403, "PERMISSION_DENIED"], + ] as const) { + const response = await post(base, generation(), { ...headers }); + expect(response.status).toBe(status); + expect(await response.json()).toMatchObject({ error: { code: status, status: errorStatus } }); + } + expect(seen).toHaveLength(0); + expect((await get(base, generation())).headers.get("allow")).toBe("POST"); + const interactions = await get(base, "/v1beta/interactions"); + expect(interactions.status).toBe(405); + expect(interactions.headers.get("allow")).toBe("POST"); + expect(await interactions.json()).toMatchObject({ error: { code: 405, status: "UNIMPLEMENTED" } }); + }); + await withServer({ ...config(true), hostname: "127.0.0.1" }, async base => { + const headers = { ...key, host: "rebind.example" }; + const response = await post(base, generation(), headers); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { code: 403, status: "PERMISSION_DENIED" } }); + expect((await get(base, "/v1beta/models", headers)).status).toBe(403); + expect(seen).toHaveLength(0); + }); +}); + +test("model lookup and discovery expose only scoped, routable native wire aliases", async () => { + const cfg = config(true); + cfg.providers[PROVIDER]!.defaultMaxOutputTokens = 4096; + await withServer(cfg, async base => { + const response = await get(base, "/v1beta/models"); + const payload = await response.json() as { models: Array<{ name: string }> }; + const names = payload.models.map(model => model.name); + expect(names).toContain(`models/${WIRE_MODEL}`); + expect(names).toContain(`models/${TARGET}`); + expect(names).toContain(`models/fx/${MODEL}`); + const one = await get(base, `/v1beta/models/${WIRE_MODEL}`); + expect(one.status).toBe(200); + const alias = { + name: `models/${WIRE_MODEL}`, + outputTokenLimit: 4096, + supportedGenerationMethods: ["generateContent", "streamGenerateContent", "countTokens"], + }; + expect(await one.json()).toMatchObject(alias); + expect(payload.models.find(model => model.name === alias.name)).toMatchObject(alias); + const count = await post(base, generation(WIRE_MODEL, "countTokens")); + expect(count.status).toBe(200); + expect((await count.json() as { totalTokens: number }).totalTokens).toBeGreaterThan(0); + const scoped = { "x-goog-api-key": SCOPE_KEY }; + const filtered = await get(base, "/v1beta/models", scoped); + expect(await filtered.json()).toMatchObject({ models: [{ name: `models/fx/${MODEL}` }] }); + expect((await get(base, `/v1beta/models/${WIRE_MODEL}`, scoped)).status).toBe(404); + expect((await post(base, generation(WIRE_MODEL, "countTokens"), scoped)).status).toBe(404); + expect((await get(base, "/v1beta/models/gemini-no-such-model")).status).toBe(404); + expect(seen).toHaveLength(0); + }); +}); diff --git a/tests/server/gemini-native-wire.test.ts b/tests/server/gemini-native-wire.test.ts new file mode 100644 index 00000000000..d71dda73d08 --- /dev/null +++ b/tests/server/gemini-native-wire.test.ts @@ -0,0 +1,79 @@ +import { expect, spyOn, test } from "bun:test"; +import { 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", () => { + const raw = '{ "contents": [], "future":9007199254740993123, "s":"\\u0061" }'; + expect(rawJsonMember(wrapGeminiRequest(raw, "gemini-test", "project"), "request")).toBe(raw.trim()); + expect(unwrapGeminiResponse(`{"response":${response},"other":{"response":null}}`)).toBe(response); +}); +test("envelope extraction handles escaped keys, nesting, braces in strings and rejects ambiguity", () => { + expect(unwrapGeminiResponse('{"respon\\u0073e":{"s":"},\\\"","a":[{}]}}')).toBe('{"s":"},\\\"","a":[{}]}'); + for (const raw of ['[]', '{}', '{"response":null}', '{"response":{},"response":{}}', '{"response":{']) { + expect(() => unwrapGeminiResponse(raw)).toThrow(); + } +}); +async function transform(text: string, chunk = 1, limit?: number): 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(); +} +test("SSE accepts byte-split UTF8, CRLF, comments and multiple events", async () => { + const frame = `: ping\r\ndata: {"response":${response}}\r\n\r\n`; + const unicode = 'data: {"response":{"text":"中文😀","promptFeedback":{"blockReason":"SAFETY"}}}\n\n'; + expect(await transform(frame + unicode)).toBe(`data: ${response}\n\ndata: {"text":"中文😀","promptFeedback":{"blockReason":"SAFETY"}}\n\n`); +}); +test("SSE supports multiline data and lone CR framing", async () => { + expect(await transform('data: {"response":\rdata: {"promptFeedback":{"blockReason":"SAFETY"}}}\r\r')).toBe('data: {"promptFeedback":{"blockReason":"SAFETY"}}\n\n'); +}); +test("SSE rejects truncation, oversized frames and missing wrappers", async () => { + for (const raw of ['data: {"response":{}}', 'data: {}\n\n', 'data: [DONE]\n\n']) { + await expect(transform(raw)).rejects.toThrow(); + } + await expect(transform('data: {"response":{"text":"too long"}}\n\n', 1, 20)).rejects.toThrow(); +}); + +test("SSE requires every observed candidate to finish; DONE alone is insufficient", async () => { + const frame = (response: string) => `data: {"response":${response}}\n\n`; + const first = frame('{"candidates":[{"index":0},{"index":1}]}'); + const one = frame('{"candidates":[{"index":0,"finishReason":"STOP"}]}'); + const two = frame('{"candidates":[{"index":1,"finishReason":"STOP"}]}'); + await expect(transform(first + one)).rejects.toThrow("incomplete"); + await expect(transform(first + "data: [DONE]\n\n")).rejects.toThrow(); + expect(await transform(first + one + two + "data: [DONE]\n\n")).toBe([first, one, two].map(text => `data: ${unwrapGeminiResponse(text.slice(6).trim())}\n\n`).join('')); +}); + +test("SSE prefixes each preserved JSON line inside an extracted multiline response", async () => { + const raw = '{\n "candidates": [{"finishReason":"STOP"}],\n "future":9007199254740993123,\n "signature":"a+/="\n}'; + const frame = `data: {"response":${raw.replaceAll("\n", "\ndata: ")}}\n\n`; + const result = await transform(frame, 3); + expect(result).toBe(`data: ${raw.replaceAll("\n", "\ndata: ")}\n\n`); + // A standard SSE consumer must recover the complete original JSON, including its newlines. + const data = result.trimEnd().split("\n").map(line => { + expect(line.startsWith("data: ")).toBe(true); + return line.slice(6); + }).join("\n"); + expect(data).toBe(raw); +}); + +test("fragmented 1 MiB SSE lines perform only linear UTF-8 encoding work", async () => { + const raw = `{"candidates":[{"finishReason":"STOP"}],"padding":"${"x".repeat(1024 * 1024)}"}`; + const frame = `data: {"response":${raw}}\n\n`; + const originalEncode = TextEncoder.prototype.encode; + let encodedBytes = 0; + const encoder = spyOn(TextEncoder.prototype, "encode").mockImplementation(function(this: TextEncoder, text?: string) { + const bytes = originalEncode.call(this, text); + encodedBytes += bytes.byteLength; + return bytes; + }); + let result: string; + try { result = await transform(frame, 1024); } + finally { encoder.mockRestore(); } + expect(result!).toBe(`data: ${raw}\n\n`); + // Input plus output are about 2 MiB; re-encoding retained prefixes would exceed 500 MiB. + expect(encodedBytes).toBeLessThan(frame.length * 3); +}); diff --git a/tests/server/gemini-native.test.ts b/tests/server/gemini-native.test.ts new file mode 100644 index 00000000000..62e9815aeb3 --- /dev/null +++ b/tests/server/gemini-native.test.ts @@ -0,0 +1,528 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import * as oauthStore from "../../src/oauth/store"; +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"; + +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" }; +const fresh = { ...old, generation: "new", accessToken: "fixture-new-token" }; +const fixtureAccount = () => ({ + credential: { + access: old.accessToken, refresh: "fixture-refresh", expires: Date.now() + 3600_000, + projectId: old.projectId, accountId: "fixture-google-subject", + }, + paused: false, needsReauth: false, +}); +let accountStatus: ReturnType; +let accountStatusSpy: ReturnType>; +beforeEach(() => { accountStatus = fixtureAccount(); accountStatusSpy = spyOn(oauthStore, "getAccountCredentialWithStatus").mockImplementation(() => accountStatus); }); +afterEach(() => accountStatusSpy.mockRestore()); + +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" } }); +} +function transport(fn: (url: string, init: RequestInit) => Response | Promise): typeof fetch { + return Object.assign((url: RequestInfo | URL, init?: RequestInit) => Promise.resolve(fn(String(url), init!)), { preconnect: fetch.preconnect }) as typeof fetch; +} +async function run(req: Request, deps: GeminiNativeDeps, stream: boolean | "array" = false, cfg = config) { + const lease = tryAdmitTurn(undefined, req.signal)!; + try { return await handleGeminiNative(req, cfg, "gemini-test", stream === "array" ? stream : stream ? "sse" : undefined, lease, deps); } + finally { if (!lease.isTransferred()) lease.release(); } +} +test("native generation preserves source JSON, binds project and replaces ingress credentials", async () => { + const baseline = getActiveTurnCount(); + const raw = '{"contents":[],"future":9007199254740993123}'; + const response = await run(request(raw), { + access: async () => old, refresh: async () => { throw new Error("unexpected refresh"); }, + fetch: transport((url, init) => { + expect(url).toEndWith("/v1internal:generateContent"); + expect(init.redirect).toBe("manual"); + expect(new Headers(init.headers).get("authorization")).toBe("Bearer fixture-old-token"); + expect(rawJsonMember(String(init.body), "request")).toBe(raw); + expect(JSON.parse(String(init.body)).project).toBe("fixture-project"); + return new Response('{"response":{"future":9007199254740993123}}'); + }), + }); + expect(response.status).toBe(200); + expect(await response.text()).toBe('{"future":9007199254740993123}'); + expect(getActiveTurnCount()).toBe(baseline); +}); + +const fixtureCredentials = [ + { name: "access token", wire: old.accessToken }, + { name: "project ID", wire: old.projectId! }, + { name: "refresh token", wire: fixtureAccount().credential.refresh }, + { name: "account identity", wire: fixtureAccount().credential.accountId }, + { name: "JSON-escaped project ID", wire: "\\u0066ixture-project" }, +]; +const finishedPayload = '{ "candidates": [{"finishReason":"STOP"}], "future":9007199254740993123 }'; +const safeUpstreamError = { error: { code: 502, message: "Antigravity upstream rejected the request", status: "UNAVAILABLE" } }; +const safeInBandUpstreamError = { error: { ...safeUpstreamError.error, status: "INTERNAL" } }; +const event = (response: string) => `data: {"response":${response}}\n\n`; +const fixtureChunk = (text: string) => new TextEncoder().encode(text); + +for (const { name, wire } of fixtureCredentials) { + const payload = `{"future":[{"text":"prefix ${wire} suffix","text":"replacement"}]}`; + test(`buffered native success rejects an echoed ${name}`, async () => { + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(`{"response":${payload}}`)), + }); + expect(response.status).toBe(502); + expect(await response.json()).toEqual(safeUpstreamError); + }); + + for (const format of ["sse", "array"] as const) { + test(`native ${format} rejects an echoed ${name} split across transport chunks`, async () => { + const frame = event(payload); + const split = frame.indexOf(wire) + Math.floor(wire.length / 2); + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(new ReadableStream({ + start(controller) { + for (const chunk of [event(finishedPayload), frame.slice(0, split), frame.slice(split)]) { + controller.enqueue(fixtureChunk(chunk)); + } + controller.close(); + }, + }))), + }, format === "array" ? format : true); + const prefix = format === "sse" ? `data: ${finishedPayload}\n\n` : `[\n${finishedPayload},\n`; + const error = JSON.stringify(safeInBandUpstreamError); + expect(await response.text()).toBe(prefix + (format === "sse" ? `data: ${error}\n\n` : `${error}\n]`)); + }); + } +} + +for (const format of ["sse", "array"] as const) { + for (const terminal of ["DONE", "in-band error"] as const) { + test(`native ${format} stops at ${terminal} and cancels the open upstream`, async () => { + const baseline = getActiveTurnCount(); + let cancelled = false; + const terminalEvent = terminal === "DONE" ? "data: [DONE]\n\n" : event('{"error":{"message":"private upstream diagnostic"}}'); + const late = event('{"candidates":[{"finishReason":"STOP"}],"text":"late success"}'); + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(new ReadableStream({ + start(controller) { + controller.enqueue(fixtureChunk(event(finishedPayload) + terminalEvent + late)); + controller.enqueue(fixtureChunk(late)); + }, + cancel() { cancelled = true; }, + }))), + }, format === "array" ? format : true); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + const read = async () => decoder.decode((await reader.read()).value); + try { + expect(await read()).toBe(format === "sse" ? `data: ${finishedPayload}\n\n` : `[\n${finishedPayload}`); + if (terminal === "in-band error") { + const error = JSON.stringify(safeInBandUpstreamError); + expect(await read()).toBe(format === "sse" ? `data: ${error}\n\n` : `,\n${error}`); + } + if (format === "array") expect(await read()).toBe("\n]"); + expect((await reader.read()).done).toBe(true); + await Bun.sleep(0); + expect(cancelled).toBe(true); + expect(getActiveTurnCount()).toBe(baseline); + } finally { + await reader.cancel(); + } + }); + } +} + +test("401 refreshes the rejected snapshot once and cancels its response", async () => { + let calls = 0, refreshes = 0, cancelled = false; + const response = await run(request(), { + access: async () => old, + refresh: async rejected => { expect(rejected).toBe(old); refreshes++; return fresh; }, + fetch: transport((_url, init) => { + calls++; + if (calls === 1) return new Response(new ReadableStream({ cancel() { cancelled = true; } }), { status: 401 }); + expect(new Headers(init.headers).get("authorization")).toBe("Bearer fixture-new-token"); + return new Response('{"response":{}}'); + }), + }); + expect(response.status).toBe(200); + expect(calls).toBe(2); expect(refreshes).toBe(1); expect(cancelled).toBe(true); +}); + +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; + const response = await run(request(), { + access: async () => old, + refresh: async () => { + accountStatus = { ...fixtureAccount(), credential: { ...fixtureAccount().credential, access: fresh.accessToken } }; + return fresh; + }, + fetch: transport(() => ++calls === 1 + ? new Response(null, { status: 401 }) + : new Response(`{"response":{"text":"${echoed}"}}`)), + }); + expect(calls).toBe(2); + expect(response.status).toBe(502); + expect(await response.json()).toEqual(safeUpstreamError); + }); +} +test("cancellation while discarding a 401 detaches a stalled body without refreshing", async () => { + const ac = new AbortController(); + const cancel = Promise.withResolvers(); + let refreshes = 0; + const pending = run(request(undefined, ac.signal), { + access: async () => old, + refresh: async () => { refreshes++; return fresh; }, + fetch: transport(() => new Response(new ReadableStream({ + cancel() { queueMicrotask(() => ac.abort()); return cancel.promise; }, + }), { status: 401 })), + }); + try { + const status = await Promise.race([pending.then(response => response.status), Bun.sleep(200).then(() => 0)]); + expect(status).toBe(499); + expect(refreshes).toBe(0); + } finally { + cancel.resolve(); + await pending; + } +}); + +test("persistent 401 is terminal and safe error headers retain numeric Retry-After", async () => { + let calls = 0, refreshes = 0; + const response = await run(request(), { + access: async () => old, refresh: async () => { refreshes++; return fresh; }, + fetch: transport(() => { calls++; return new Response("private upstream diagnostics", { status: 401, headers: { "Retry-After": "5", "Set-Cookie": "private" } }); }), + }); + expect(response.status).toBe(401); expect(calls).toBe(2); expect(refreshes).toBe(1); + expect(response.headers.get("retry-after")).toBe("5"); expect(response.headers.has("set-cookie")).toBe(false); + expect(await response.text()).not.toContain("private"); +}); +test("invalid input, configured byte cap and disabled provider never acquire OAuth", async () => { + let accessCalls = 0; + const deps = { access: async () => { accessCalls++; return old; }, refresh: async () => fresh, fetch: transport(() => { throw new Error("unexpected send"); }) }; + expect((await run(request("[]"), deps)).status).toBe(400); + expect((await run(request(), deps, false, { ...config, maxInboundBodyBytes: 2 })).status).toBe(413); + expect((await run(request(), deps, false, { ...config, providers: { "google-antigravity": { ...config.providers["google-antigravity"], disabled: true } } })).status).toBe(503); + expect(accessCalls).toBe(0); +}); +test("stream cancellation releases upstream and active turn without a resend", async () => { + const baseline = getActiveTurnCount(); + let calls = 0, cancelled = false; + const response = await run(request(), { + access: async () => old, refresh: async () => { throw new Error("unexpected refresh"); }, + fetch: transport(() => { + calls++; + return new Response(new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode('data: {"response":{"text":"hello"}}\n\n')); }, cancel() { cancelled = true; } })); + }), + }, true); + const reader = response.body!.getReader(); + expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello"); + await reader.cancel(); + await Bun.sleep(0); + expect(cancelled).toBe(true); expect(calls).toBe(1); expect(getActiveTurnCount()).toBe(baseline); +}); +test("client cancellation during headers reaches the physical fetch", async () => { + const baseline = getActiveTurnCount(); + const ac = new AbortController(); + const result = run(request(undefined, ac.signal), { + access: async () => old, refresh: async () => fresh, + fetch: transport((_url, init) => new Promise((_resolve, reject) => { + init.signal!.addEventListener("abort", () => reject(init.signal!.reason), { once: true }); + ac.abort(); + })), + }); + expect((await result).status).toBe(499); expect(getActiveTurnCount()).toBe(baseline); +}); +test("malformed stream terminates delivery and never retries after output", async () => { + let calls = 0; + const response = await run(request(), { + access: async () => old, refresh: async () => { throw new Error("unexpected refresh"); }, + fetch: transport(() => { calls++; return new Response('data: {"response":{"text":"first"}}\n\ndata: {}\n\n'); }), + }, true); + await expect(response.text()).rejects.toThrow(); expect(calls).toBe(1); +}); + +test("refresh failure returns a terminal error and releases the turn", async () => { + const baseline = getActiveTurnCount(); + let calls = 0; + const response = await run(request(), { access: async () => old, refresh: async () => { throw new Error("fixture-refresh-failure"); }, fetch: transport(() => { calls++; return new Response("{}", { status: 401 }); }) }); + expect(response.status).toBe(502); expect(calls).toBe(1); expect(getActiveTurnCount()).toBe(baseline); +}); +test("header deadline aborts fetch and body stall aborts stream without replay", async () => { + const baseline = getActiveTurnCount(); + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport((_url, init) => new Promise((_resolve, reject) => init.signal!.addEventListener("abort", () => reject(init.signal!.reason), { once: true }))), + }, false, { ...config, connectTimeoutMs: 10 }); + expect(response.status).toBe(502); + let cancelled = false; + const stream = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(new ReadableStream({ cancel() { cancelled = true; } }))), + }, true, { ...config, stallTimeoutSec: 1 }); + await expect(stream.text()).rejects.toThrow(); + expect(cancelled).toBe(true); expect(getActiveTurnCount()).toBe(baseline); +}); + +test("native delivery logging observes EOF, failure and cancellation without changing bytes", async () => { + const { logGeminiNativeDelivery } = await import("../../src/server/gemini-native-log"); + const { getRequestLogEntries } = await import("../../src/server/request-log"); + const context = () => ({ model: "gemini-test", provider: "google-antigravity" }); + const id = `gemini-native-fixture-${crypto.randomUUID()}`; + const raw = '{"unknown":9007199254740993123}'; + const delivered = logGeminiNativeDelivery(new Response(raw), request(), id, Date.now(), context()); + expect(await delivered.text()).toBe(raw); + expect(getRequestLogEntries().find(row => row.requestId === id)?.status).toBe(200); + const failedId = `${id}-failure`; + const failed = logGeminiNativeDelivery(new Response(new ReadableStream({ pull(c) { c.error(new Error("fixture failure")); } })), request(), failedId, Date.now(), context()); + await expect(failed.text()).rejects.toThrow(); + expect(getRequestLogEntries().find(row => row.requestId === failedId)?.status).toBe(502); + const cancelledId = `${id}-cancel`; + const cancelled = logGeminiNativeDelivery(new Response(new ReadableStream({})), request(), cancelledId, Date.now(), context()); + await cancelled.body!.cancel(); + expect(getRequestLogEntries().find(row => row.requestId === cancelledId)?.status).toBe(499); +}); + +test("native physical sends consume the workflow ceiling across requests and 401 recovery", async () => { + const { createAdmittedHttpTurn } = await import("../../src/server/admitted-http-turn"); + const { bindWorkflowBudgetConfig, currentWorkflowBudgetPolicy } = await import("../../src/lib/workflow-budget-config"); + const { workflowBudgetSnapshot, clearWorkflowBudgetForRoot } = await import("../../src/lib/workflow-budget"); + const rootId = `gemini-workflow-fixture-${crypto.randomUUID()}`; + bindWorkflowBudgetConfig({ workflowBudget: { maxPhysicalSends: 1 } }); + const guarded = createAdmittedHttpTurn(() => undefined, () => new Response(null, { status: 503 })); + const call = (deps: GeminiNativeDeps) => { + const req = request(); + req.headers.set("x-codex-parent-thread-id", rootId); + req.headers.set("thread-id", rootId); + return guarded(req, config, lease => handleGeminiNative(req, config, "gemini-test", undefined, lease, deps)); + }; + let sends = 0; + try { + const deps = { access: async () => old, refresh: async () => fresh, + fetch: transport(() => { sends++; return new Response('{"response":{}}'); }) }; + const first = await call(deps); + expect(first.status).toBe(200); await first.text(); + expect(workflowBudgetSnapshot(rootId, currentWorkflowBudgetPolicy())?.sends).toBe(1); + expect((await call(deps)).status).toBe(429); + expect(sends).toBe(1); + clearWorkflowBudgetForRoot(rootId); + sends = 0; + const recovered = await call({ ...deps, fetch: transport(() => { sends++; return new Response("{}", { status: 401 }); }) }); + expect(recovered.status).toBe(429); + expect(recovered.headers.get("x-opencodex-local-refusal")).toBe("workflow_sends_exhausted"); + expect(sends).toBe(1); + } finally { + clearWorkflowBudgetForRoot(rootId); + bindWorkflowBudgetConfig(null); + } +}); + +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" }] } }); + } + 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 }; + 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); +}); + +test("native SSE errors redact upstream diagnostics and delivery logs record failure", async () => { + const { logGeminiNativeDelivery } = await import("../../src/server/gemini-native-log"); + const { getRequestLogEntries } = await import("../../src/server/request-log"); + const req = request(); + const lease = tryAdmitTurn(undefined, req.signal)!; + const context = { model: "gemini-test", provider: "google-antigravity" }; + const id = `gemini-native-error-fixture-${crypto.randomUUID()}`; + const payload = '{"error":{"code":500,"message":"opaque upstream diagnostic","future":9007199254740993123}}'; + try { + const response = await handleGeminiNative(req, config, "gemini-test", "sse", lease, { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(`data: {"response":${payload}}\n\n`)), + }, context); + const delivery = logGeminiNativeDelivery(response, req, id, Date.now(), context); + expect(delivery.status).toBe(200); + const delivered = await delivery.text(); + expect(delivered).not.toContain("opaque upstream diagnostic"); + expect(JSON.parse(delivered.slice("data: ".length))).toEqual({ + error: { code: 502, message: "Antigravity upstream rejected the request", status: "INTERNAL" }, + }); + const row = getRequestLogEntries().find(entry => entry.requestId === id); + expect(context).toMatchObject({ errorCode: "gemini_native_upstream_error" }); + expect(row).toMatchObject({ status: 502, terminalStatus: "failed", errorCode: "upstream_server_error", terminalSource: "upstream" }); + expect(JSON.stringify(row)).not.toContain("opaque upstream diagnostic"); + } finally { lease.release(); } +}); + +test("non-positive upstream stall settings stay disabled while delayed bodies complete", async () => { + for (const stallTimeoutSec of [0, -1]) { + let cancelled = false; + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(new ReadableStream({ + async start(controller) { + await Bun.sleep(1100); + if (!cancelled) { controller.enqueue(new TextEncoder().encode('{"response":{}}')); controller.close(); } + }, + cancel() { cancelled = true; }, + }))), + }, false, { ...config, stallTimeoutSec }); + expect(response.status).toBe(200); expect(cancelled).toBe(false); + } +}); + +test("an idle partial upload times out locally and releases admission before OAuth", async () => { + const baseline = getActiveTurnCount(); + let cancelled = false, accessCalls = 0; + const req = new Request("http://localhost/v1beta/models/gemini-test:generateContent", { + method: "POST", body: new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode('{"contents":')); }, + cancel() { cancelled = true; }, + }), + }); + const response = await run(req, { + access: async () => { accessCalls++; return old; }, refresh: async () => fresh, + fetch: transport(() => { throw new Error("unexpected send"); }), + }, false, { ...config, stallTimeoutSec: 1 }); + expect(response.status).toBe(408); expect(cancelled).toBe(true); expect(accessCalls).toBe(0); + expect(getActiveTurnCount()).toBe(baseline); +}); + +test("upload idle protection resets for each chunk and ends before slow OAuth setup", async () => { + let cancelled = false; + const req = new Request("http://localhost/v1beta/models/gemini-test:generateContent", { + method: "POST", body: new ReadableStream({ + async start(controller) { + controller.enqueue(new TextEncoder().encode('{"con')); + await Bun.sleep(600); if (cancelled) return; + controller.enqueue(new TextEncoder().encode('tents":')); + await Bun.sleep(600); if (cancelled) return; + controller.enqueue(new TextEncoder().encode('[]}')); controller.close(); + }, + cancel() { cancelled = true; }, + }), + }); + const response = await run(req, { + access: async () => { await Bun.sleep(1100); return old; }, refresh: async () => fresh, + fetch: transport(() => new Response('{"response":{}}')), + }, false, { ...config, stallTimeoutSec: 1 }); + expect(response.status).toBe(200); +}); + +test("error responses retain status and Retry-After without decoding or waiting for their body", async () => { + const baseline = getActiveTurnCount(); + for (const payload of [new Uint8Array([255]), new Uint8Array(16 * 1024 * 1024 + 1), undefined]) { + let cancelled = false; + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(new ReadableStream({ + start(controller) { if (payload) controller.enqueue(payload); }, + cancel() { cancelled = true; }, + }), { status: 429, headers: { "Retry-After": "7" } })), + }); + expect(response.status).toBe(429); expect(response.headers.get("retry-after")).toBe("7"); + expect(cancelled).toBe(true); + } + expect(getActiveTurnCount()).toBe(baseline); +}); + +test("known setup errors retain actionable auth, pacing and configuration responses", async () => { + const { OAuthLoginRequiredError, OAuthAccountPausedError, OAuthTokenRefreshBusyError } = await import("../../src/oauth"); + const { RequestPacingQueueOverloadError } = await import("../../src/providers/request-pacing"); + for (const [error, status, retryAfter, message] of [ + [new OAuthLoginRequiredError("google-antigravity"), 503, null, "ocx login google-antigravity"], + [new OAuthAccountPausedError(), 503, null, "resume"], + [new OAuthTokenRefreshBusyError(), 503, "1", "refresh"], + [new RequestPacingQueueOverloadError("google-antigravity", "queue_full", 7), 429, "7", "queue"], + ] as const) { + const response = await run(request(), { + access: async () => { throw error; }, refresh: async () => fresh, + fetch: transport(() => { throw new Error("unexpected send"); }), + }); + expect(response.status).toBe(status); expect(response.headers.get("retry-after")).toBe(retryAfter); + expect(await response.text()).toContain(message); + } + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => { throw new Error("unexpected send"); }), + }, false, { ...config, providers: { "google-antigravity": { ...config.providers["google-antigravity"], baseUrl: "http://169.254.169.254" } } }); + expect(response.status).toBe(503); + const message = await response.text(); + expect(message).toContain("baseUrl"); expect(message).not.toContain("169.254.169.254"); +}); + +test("queued native sends recheck paused, reauth and removed accounts before initial and 401 dispatch", async () => { + const { waitForProviderRequestSlot, providerRequestPacingStatus } = await import("../../src/providers/request-pacing"); + const provider = { ...config.providers["google-antigravity"], requestPacing: { enabled: true, maxConcurrentRequests: 1 } }; + const cfg = { ...config, providers: { "google-antigravity": provider } }; + const baseline = getActiveTurnCount(); + for (const retry of [false, true]) for (const state of ["paused", "needsReauth", "removed"] as const) { + accountStatus = fixtureAccount(); + let sends = 0; + let blocker: Awaited> | undefined; + if (!retry) blocker = await waitForProviderRequestSlot("google-antigravity", provider, "gemini-test"); + const ac = new AbortController(); + const pending = run(request(undefined, ac.signal), { + access: async () => old, + refresh: async () => { blocker = await waitForProviderRequestSlot("google-antigravity", provider, "gemini-test"); return fresh; }, + fetch: transport(() => { sends++; return new Response('{"response":{}}', { status: retry ? 401 : 200 }); }), + }, false, cfg); + try { + const deadline = Date.now() + 1000; + while (providerRequestPacingStatus("google-antigravity", provider).queued !== 1 && Date.now() < deadline) await Bun.sleep(0); + expect(providerRequestPacingStatus("google-antigravity", provider).queued).toBe(1); + accountStatus = state === "removed" ? null : { ...fixtureAccount(), [state]: true }; + blocker!.release(); + expect((await pending).status).toBe(503); + expect(sends).toBe(retry ? 1 : 0); + expect(accountStatusSpy).toHaveBeenLastCalledWith("google-antigravity", old.accountId); + } finally { blocker?.release(); ac.abort(); await pending; } + } + expect(getActiveTurnCount()).toBe(baseline); +}); + +test("buffered native errors redact upstream diagnostics and log failure", async () => { + const { logGeminiNativeDelivery } = await import("../../src/server/gemini-native-log"); + const { getRequestLogEntries } = await import("../../src/server/request-log"); + const req = request(), lease = tryAdmitTurn(undefined, req.signal)!; + const context = { model: "gemini-test", provider: "google-antigravity" }; + const id = `gemini-buffered-error-fixture-${crypto.randomUUID()}`; + const payload = '{"error":{"code":500,"message":"private buffered diagnostic","future":9007199254740993123}}'; + try { + const response = await handleGeminiNative(req, config, "gemini-test", undefined, lease, { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => new Response(`{"response":${payload}}`)), + }, context); + const delivery = logGeminiNativeDelivery(response, req, id, Date.now(), context); + expect(delivery.status).toBe(502); + expect(await delivery.json()).toEqual({ + error: { code: 502, message: "Antigravity upstream rejected the request", status: "UNAVAILABLE" }, + }); + const row = getRequestLogEntries().find(entry => entry.requestId === id); + expect(row).toMatchObject({ status: 502, terminalStatus: "failed", errorCode: "upstream_server_error", terminalSource: "upstream" }); + expect(JSON.stringify(row)).not.toContain("private buffered diagnostic"); + } finally { lease.release(); } +}); diff --git a/tests/server/management-provider-validation.test.ts b/tests/server/management-provider-validation.test.ts index 470ceb309bf..f8f74cf6926 100644 --- a/tests/server/management-provider-validation.test.ts +++ b/tests/server/management-provider-validation.test.ts @@ -1884,6 +1884,10 @@ describe("provider management validation", () => { // opencode-go the seed is exactly {"kimi-k3": 262144}, which is what the reporter found in // place of their deepseek-v4-flash override. describe("provider POST overwrite preserves hand-edited context windows (#1409)", () => { + // These save/merge assertions do not depend on live DNS destination discovery. + let resolvedDestination: ReturnType>; + beforeEach(() => { resolvedDestination = spyOn(destinationPolicy, "providerDestinationResolvedError").mockResolvedValue(null); }); + afterEach(() => resolvedDestination.mockRestore()); async function seedProvider(url: URL, extra: Record): Promise { return fetch(new URL("/api/providers", url), { method: "POST", @@ -2316,6 +2320,7 @@ describe("provider management validation", () => { saveConfig(config("127.0.0.1")); const server = startServer(0); + const resolvedDestination = spyOn(destinationPolicy, "providerDestinationResolvedError").mockResolvedValue(null); try { const response = await fetch(new URL("/api/providers", server.url), { method: "POST", @@ -2336,6 +2341,7 @@ describe("provider management validation", () => { expect(saved.providers["meta-muse"]?.headers).toBeUndefined(); expect(saved.providers["meta-muse"]?.keyOptional).toBeUndefined(); } finally { + resolvedDestination.mockRestore(); await server.stop(true); } }); diff --git a/tests/server/protocol-settings-route.test.ts b/tests/server/protocol-settings-route.test.ts index 050b3360cdb..645384a938f 100644 --- a/tests/server/protocol-settings-route.test.ts +++ b/tests/server/protocol-settings-route.test.ts @@ -103,6 +103,16 @@ describe("PATCH /api/protocols/settings", () => { expect(body.settings.rollout).toMatchObject({ directEncoders: true, shadowPlan: true, nativeChatCombos: false }); }); + test("the Gemini rollout switch persists and is returned by management settings", async () => { + const h = harness(); + for (const geminiNativeAntigravity of [true, false]) { + const res = await patch(h, { rollout: { geminiNativeAntigravity } }); + expect(res.status).toBe(200); + expect(h.saves.at(-1)?.protocols?.rollout?.geminiNativeAntigravity).toBe(geminiNativeAntigravity); + expect(await res.json()).toMatchObject({ settings: { rollout: { geminiNativeAntigravity } } }); + } + }); + test("the OAuth native-Messages switch cannot be turned on without the key-auth one", async () => { const h = harness(); const res = await patch(h, { rollout: { managedMessagesNativeOAuth: true } }); diff --git a/tests/server/server-auth.test.ts b/tests/server/server-auth.test.ts index 1f349d9da29..f36e8ebe0ef 100644 --- a/tests/server/server-auth.test.ts +++ b/tests/server/server-auth.test.ts @@ -1477,8 +1477,9 @@ describe("server local API auth", () => { } return originalGlobalFetch(input, init); }) as typeof fetch; + // Keep native WSS inside this HTTP fixture instead of contacting chatgpt.com. + redirectCanonicalCodexTo(upstream.url.toString()); globalThis.fetch = matrixFetch; - const request = (server: ReturnType, headers?: HeadersInit, model = "gpt-test") => { const requestHeaders = new Headers(headers); requestHeaders.set("content-type", "application/json"); @@ -1517,7 +1518,6 @@ describe("server local API auth", () => { ws.addEventListener("error", () => reject(new Error("tier websocket failed")), { once: true }); }); }; - try { const directConfig = { port: 0, diff --git a/tests/server/turn-state-handles.test.ts b/tests/server/turn-state-handles.test.ts index c3b922e6a7b..b6392985939 100644 --- a/tests/server/turn-state-handles.test.ts +++ b/tests/server/turn-state-handles.test.ts @@ -9,6 +9,8 @@ import { resolveTurnStateHandle, runTurnStateCallerScope, TURN_STATE_MISMATCH_NOTICE, turnStateBinding, } from "../../src/server/turn-state-handles"; import type { OcxConfig } from "../../src/types"; +import { ownedServiceHomeInspection } from "../helpers/owned-service-home-inspection"; +import { redirectCanonicalCodexTo } from "../helpers/pool-retry-harness"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -87,6 +89,7 @@ describe("turn-state handles", () => { describe("the server redeems a handle only for the same caller, provider and account", () => { const originalFetch = globalThis.fetch; + const originalWebSocket = globalThis.WebSocket; const previousHome = process.env.OPENCODEX_HOME; let home = ""; let forwarded: Array<{ headers: Headers; body?: Record }> = []; @@ -103,6 +106,7 @@ describe("the server redeems a handle only for the same caller, provider and acc }); afterEach(() => { globalThis.fetch = originalFetch; + globalThis.WebSocket = originalWebSocket; if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; removeTreeWithRetry(home); }); @@ -110,6 +114,8 @@ describe("the server redeems a handle only for the same caller, provider and acc const bearer = `Bearer ${fakeChatGptJwt({ chatgpt_account_id: "turn-state-fixture", exp: Math.floor(Date.now() / 1000) + 3600 })}`; function captureUpstream(server: { url: URL }): void { const local = new URL(server.url).origin; + // Keep speculative native WSS on the same synthetic HTTP/SSE upstream. + redirectCanonicalCodexTo(local); globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = input instanceof Request ? input.url : String(input); if (url.startsWith(local)) return originalFetch(input, init); @@ -159,7 +165,7 @@ describe("the server redeems a handle only for the same caller, provider and acc for (const transport of ["HTTP", "WebSocket"] as const) { for (const [name, binding, expected] of CASES) { test(`${transport}: ${name}`, async () => { - const server = startServer(0); + const server = startServer(0, { inspectNativeCodexOwnership: ownedServiceHomeInspection("turn-state fixture") }); captureUpstream(server); const warn = spyOn(console, "warn"); try {