Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs-site/src/content/docs/es/guides/integrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
6 changes: 6 additions & 0 deletions docs-site/src/content/docs/es/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
44 changes: 43 additions & 1 deletion docs-site/src/content/docs/es/reference/proxy-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<provider>/<model>` 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.
Expand Down Expand Up @@ -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.

<a id="native-gemini-with-antigravity"></a>

## 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.
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/guides/integrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
41 changes: 40 additions & 1 deletion docs-site/src/content/docs/reference/proxy-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 `</function></tool_call>` 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.
3 changes: 3 additions & 0 deletions scripts/test-layout/layout-server-inbound.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 2 additions & 0 deletions src/config/schema/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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,
},
};
Expand Down
3 changes: 3 additions & 0 deletions src/protocols/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export interface ProtocolRolloutSettings {
managedMessagesNativeOAuth: boolean;
directEncoders: boolean;
antigravityDirect: boolean;
geminiNativeAntigravity: boolean;
shadowPlan: boolean;
}

Expand Down Expand Up @@ -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"),
}),
});
Expand Down Expand Up @@ -153,6 +155,7 @@ export function protocolPolicyRevision(config: ProtocolConfig & Pick<OcxConfig,
secondarySettings.rollout.managedMessagesNativeOAuth,
settings.rollout.directEncoders,
settings.rollout.antigravityDirect,
settings.rollout.geminiNativeAntigravity,
settings.rollout.shadowPlan,
],
});
Expand Down
21 changes: 14 additions & 7 deletions src/server/gemini-inbound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { estimateInputTokens } from "./responses/input-admission";
import type { DataPlaneAdmission } from "./auth-cors";
import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope";
import type { GeminiMethod } from "./gemini-native-paths";
import { geminiNativeCatalogAliases, geminiNativeCatalogLookup } from "./gemini-native-catalog";
import {
applyLocalRefusalCode,
commitCancelled,
Expand Down Expand Up @@ -95,24 +96,30 @@ const modelResource = (config: OcxConfig, row: { selector: string; route: RouteR
});

export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response {
return Response.json({ models: eligibleRoutes(config, req, admission).map(row => 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");
}

/**
* `:countTokens`: a local estimate over the same Chat projection generation uses, for the routes the
* 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<Response> {
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 {
Expand Down
Loading
Loading