diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index def6d1b613e..39bad03e470 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1180,6 +1180,9 @@ is known to lack the model and no replacement is allowed, the proxy returns 403. and project always come from the same account. Other providers and `/v1` requests use the Chat bridge. +Native generation uses the Antigravity provider's [outbound proxy settings](/reference/configuration/providers/#what-the-route-covers). +OAuth token exchange and refresh use the process-wide route. + 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 include diff --git a/src/server/gemini-native.ts b/src/server/gemini-native.ts index 8468c8a906b..7713e0da484 100644 --- a/src/server/gemini-native.ts +++ b/src/server/gemini-native.ts @@ -26,6 +26,8 @@ import { noteCredentialAttemptSend, sealCredentialRefusal } from "./credential-r import { DEFAULT_STALL_TIMEOUT_SEC, resolveStallTimeoutMs } from "../stall-timeout"; import { isLocalUpstream } from "../lib/local-upstream"; import { assertProviderDestinationAllowed } from "../lib/destination-policy"; +import { InvalidProviderEgressError, markEgressTransparentExecutor, providerEgressSendInit } from "../lib/provider-egress"; +import { configuredOutboundFetch, ExplicitProxyExemptedError } from "../lib/proxy-env"; import { clientFacingModelLabel, type ClientFacingModelLabel } from "../lib/error-destination"; import { registerTurn, unregisterTurn, type ActiveTurnLease } from "./lifecycle"; import { containsGeminiCredential, geminiNativeReasoningFields, geminiSseTransform, readGeminiText, validateGeminiObject, GEMINI_NATIVE_MAX_BYTES, GEMINI_NATIVE_ERROR_CODE, unwrapGeminiResponse, wrapGeminiRequest } from "./gemini-native-wire"; @@ -43,9 +45,10 @@ export function geminiNativeError(status: number, message: string, reason?: stri export interface GeminiNativeDeps { access: (config: OcxConfig, model: string, clientModel: ClientFacingModelLabel) => Promise; refresh: (snapshot: OAuthAccessSnapshot) => Promise; - fetch: typeof globalThis.fetch; + fetch?: typeof globalThis.fetch; } -const defaults: Omit = { +const nativeOutboundFetch = markEgressTransparentExecutor(((input, init) => configuredOutboundFetch(input, init)) as typeof fetch); +const defaults: GeminiNativeDeps = { access: async (config, model, clientModel) => { const set = getAccountSet(GEMINI_NATIVE_PROVIDER); if (!set) throw new OAuthLoginRequiredError(GEMINI_NATIVE_PROVIDER); @@ -61,7 +64,7 @@ const defaults: Omit = { /** Native leg using an account-scoped Antigravity token and project. */ export async function handleGeminiNative( req: Request, config: OcxConfig, model: string, streamFormat: "sse" | "array" | undefined, - lease: ActiveTurnLease, deps: GeminiNativeDeps = { ...defaults, fetch: globalThis.fetch }, logCtx?: RequestLogContext, start?: number, + lease: ActiveTurnLease, deps: GeminiNativeDeps = defaults, logCtx?: RequestLogContext, start?: number, ): Promise { const rootId = req.headers.get("x-codex-parent-thread-id")?.trim() || undefined; if (!logCtx) { @@ -88,6 +91,7 @@ export async function handleGeminiNative( if (req.signal.aborted) onAbort(); registerTurn(ac, lease); const baseUrl = provider.baseUrl || getProviderRegistryEntry(GEMINI_NATIVE_PROVIDER)!.baseUrl; + const executor = deps.fetch ?? nativeOutboundFetch; let timer: ReturnType | undefined; let bodyReadTimer: ReturnType | undefined; let finished = false; @@ -175,6 +179,7 @@ export async function handleGeminiNative( if (base.username || base.password || base.search || base.hash) throw new NativeConfigurationInvalid(); } catch { throw new NativeConfigurationInvalid(); } const method = streamFormat ? "streamGenerateContent?alt=sse" : "generateContent"; + const url = `${baseUrl.replace(/\/$/, "")}/v1internal:${method}`; const slot = await waitForProviderRequestSlot(GEMINI_NATIVE_PROVIDER, provider, model, ac.signal); upstream = await sendTrackingRequestSlot(slot, async () => { ac.signal.throwIfAborted(); @@ -191,6 +196,7 @@ export async function handleGeminiNative( credential.refresh, credential.projectId, credential.accountId, credential.email]) { if (value) boundCredentials.add(value); } + const egress = providerEgressSendInit({ providerName: GEMINI_NATIVE_PROVIDER, provider }, executor, url); const body = wrapGeminiRequest(raw, model, access.projectId!); if (logCtx) stampOAuthAccountLabel(logCtx, GEMINI_NATIVE_PROVIDER, { authMode: "oauth" }, access.accountId); const report = physicalBudget && createPhysicalSendReporter(physicalBudget, () => ({ @@ -212,11 +218,12 @@ export async function handleGeminiNative( Object.assign(logCtx.activeAttempt!, reasoning); } dispatched = true; - return await fetchWithAttemptDeadline(`${baseUrl.replace(/\/$/, "")}/v1internal:${method}`, { + return await fetchWithAttemptDeadline(url, { + ...egress, method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${access.accessToken}`, "User-Agent": antigravityUserAgentForWireModel(model) }, body, - }, config.connectTimeoutMs ?? 200_000, ac.signal, true, deps.fetch); + }, config.connectTimeoutMs ?? 200_000, ac.signal, true, executor); } finally { try { if (dispatched) report?.(1); } finally { report?.close?.(); } @@ -289,6 +296,12 @@ export async function handleGeminiNative( 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 ExplicitProxyExemptedError) { + return geminiNativeError(503, "Antigravity provider proxy conflicts with process NO_PROXY. Remove the destination from NO_PROXY to use the proxy, or add it to the provider's noProxy to connect directly."); + } + if (error instanceof InvalidProviderEgressError) { + return geminiNativeError(503, "Antigravity provider egress configuration is unavailable or invalid; check proxy and noProxy in OC settings"); + } 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"); } diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index d4ed04205a2..c527d85f533 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -29,8 +29,11 @@ JSON input and the supplied output ceiling per candidate. A 401 replay needs fre An applicable ceiling that cannot admit the reservation returns a Gemini-shaped 429 with `workflow_spend_exhausted`. The final request log settles reported input and output usage, including reasoning. Sends without final usage retain unresolved spend at the reservation size. -The destination policy checks the base URL and redirects remain manual. Only proxy-constructed -headers and the bound OAuth credential go upstream. +The destination policy checks the base URL and redirects remain manual. Before reserving each +physical send, the native leg applies the provider's `proxy` and `noProxy` policy to the final +URL and executor. When an explicit HTTP(S) proxy conflicts with a process `NO_PROXY` exemption, +the client receives a fixed 503 configuration error before the generation request is sent. +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 diff --git a/tests/server/gemini-native.test.ts b/tests/server/gemini-native.test.ts index 717e23b39c6..5a514c9b00a 100644 --- a/tests/server/gemini-native.test.ts +++ b/tests/server/gemini-native.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import * as oauthStore from "../../src/oauth/store"; +import * as proxyEnv from "../../src/lib/proxy-env"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { configureSharedSpendLedger, sharedSpendLedger, spendPolicyFromConfig } from "../../src/lib/spend-reservation-ledger"; import { estimateTokens } from "../../src/lib/token-estimate"; @@ -77,6 +78,83 @@ const safeInBandUpstreamError = { error: { ...safeUpstreamError.error, status: " const event = (response: string) => `data: {"response":${response}}\n\n`; const fixtureChunk = (text: string) => new TextEncoder().encode(text); +const fixtureProxy = "http://proxy.example.test:8080/"; +const relayBaseUrl = "https://relay.example.test/cca"; +// Both spellings can affect a provider route on a developer or CI host. +function setFixtureNoProxy(value: string): () => void { + const keys = ["NO_PROXY", "no_proxy"] as const; + const saved = keys.map(key => process.env[key]); + for (const key of keys) process.env[key] = value; + return () => keys.forEach((key, i) => { + if (saved[i] === undefined) delete process.env[key]; + else process.env[key] = saved[i]; + }); +} + +for (const { name, providerRoute, expected } of [ + { name: "inherits", providerRoute: {}, expected: undefined }, + { name: "uses its proxy", providerRoute: { proxy: fixtureProxy }, expected: fixtureProxy }, + { name: "goes direct", providerRoute: { proxy: "direct" }, expected: false }, + { name: "matches noProxy on the configured relay", providerRoute: { proxy: fixtureProxy, noProxy: ["relay.example.test"] }, expected: false }, +]) { + test(`native streaming ${name} on both sends across a credential refresh`, async () => { + const provider = { ...config.providers[old.provider]!, ...providerRoute, baseUrl: relayBaseUrl }; + const routes: Array = []; + const outbound = spyOn(proxyEnv, "configuredOutboundFetch").mockImplementation(async (url, init) => { + expect(String(url)).toBe(relayBaseUrl + "/v1internal:streamGenerateContent?alt=sse"); + expect(init?.redirect).toBe("manual"); + routes.push((init as proxyEnv.ProxyCapableRequestInit).proxy); + return routes.length === 1 + ? new Response(null, { status: 401 }) + : new Response(event(finishedPayload)); + }); + const restoreNoProxy = setFixtureNoProxy(""); + try { + const response = await run(request(), { access: async () => old, refresh: async () => fresh }, + true, { ...config, providers: { [old.provider]: provider } }); + expect(response.status).toBe(200); + expect(await response.text()).toContain(finishedPayload); + expect(routes).toEqual([expected, expected]); + } finally { + restoreNoProxy(); + outbound.mockRestore(); + } + }); +} + +test("native generation reports an explicit proxy conflict with process NO_PROXY before dispatch", async () => { + const provider = { ...config.providers[old.provider]!, baseUrl: relayBaseUrl, proxy: fixtureProxy }; + const outbound = spyOn(proxyEnv, "configuredOutboundFetch").mockResolvedValue(new Response()); + const restoreNoProxy = setFixtureNoProxy("relay.example.test"); + try { + const response = await run(request(), { access: async () => old, refresh: async () => fresh }, + false, { ...config, providers: { [old.provider]: provider } }); + expect(response.status).toBe(503); + expect((await response.json()).error.message).toBe("Antigravity provider proxy conflicts with process NO_PROXY. Remove the destination from NO_PROXY to use the proxy, or add it to the provider's noProxy to connect directly."); + expect(outbound).not.toHaveBeenCalled(); + } finally { + restoreNoProxy(); + outbound.mockRestore(); + } +}); + +test("native generation refuses a configured proxy on an opaque executor before dispatch", async () => { + const provider = { ...config.providers[old.provider]!, proxy: fixtureProxy }; + let sends = 0; + const restoreNoProxy = setFixtureNoProxy(""); + try { + const response = await run(request(), { + access: async () => old, refresh: async () => fresh, + fetch: transport(() => { sends++; return new Response('{"response":{}}'); }), + }, false, { ...config, providers: { [old.provider]: provider } }); + expect(response.status).toBe(503); + expect(await response.text()).toContain("egress configuration"); + expect(sends).toBe(0); + } finally { + restoreNoProxy(); + } +}); + for (const { name, wire } of fixtureCredentials) { const payload = `{"future":[{"text":"prefix ${wire} suffix","text":"replacement"}]}`; test(`buffered native success rejects an echoed ${name}`, async () => {