Skip to content
Open
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
3 changes: 3 additions & 0 deletions docs-site/src/content/docs/reference/proxy-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 18 additions & 5 deletions src/server/gemini-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -43,9 +45,10 @@ export function geminiNativeError(status: number, message: string, reason?: stri
export interface GeminiNativeDeps {
access: (config: OcxConfig, model: string, clientModel: ClientFacingModelLabel) => Promise<OAuthAccessSnapshot>;
refresh: (snapshot: OAuthAccessSnapshot) => Promise<OAuthAccessSnapshot>;
fetch: typeof globalThis.fetch;
fetch?: typeof globalThis.fetch;
}
const defaults: Omit<GeminiNativeDeps, "fetch"> = {
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);
Expand All @@ -61,7 +64,7 @@ const defaults: Omit<GeminiNativeDeps, "fetch"> = {
/** 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<Response> {
const rootId = req.headers.get("x-codex-parent-thread-id")?.trim() || undefined;
if (!logCtx) {
Expand All @@ -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<typeof setTimeout> | undefined;
let bodyReadTimer: ReturnType<typeof setTimeout> | undefined;
let finished = false;
Expand Down Expand Up @@ -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();
Expand All @@ -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, () => ({
Expand All @@ -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?.(); }
Expand Down Expand Up @@ -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");
}
Expand Down
7 changes: 5 additions & 2 deletions structure/data-planes/gemini-native.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
78 changes: 78 additions & 0 deletions tests/server/gemini-native.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<string | false | undefined> = [];
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 () => {
Expand Down
Loading