From 03fae10ecfda021816e6e1d2b5d41c07a8b4e897 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:49:58 +0800 Subject: [PATCH 01/19] fix(logs): show native Gemini protocol traces --- .../content/docs/reference/proxy-formats.md | 3 +- .../protocols/ProtocolTracePanel.tsx | 19 ++++++---- .../components/protocols/protocol-labels.ts | 8 ++--- gui/tests/logs-protocol-trace.test.tsx | 17 +++++++++ src/protocols/dto.ts | 36 ++++++++++++------- src/protocols/shadow.ts | 5 ++- src/protocols/trace.ts | 26 ++++++++++++-- src/server/gemini-native.ts | 5 ++- structure/data-planes/gemini-native.md | 5 +-- structure/data-planes/protocol-paths.md | 2 +- tests/responses/protocol-dto.test.ts | 17 +++++++++ tests/server/gemini-native-routes.test.ts | 15 ++++++++ 12 files changed, 125 insertions(+), 33 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 174a5cb7746..b91a9d1996c 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1157,7 +1157,8 @@ The proxy preserves successful request and response JSON source, including unkno 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. +to their Antigravity model. Requests sent through the native path show **Gemini → Gemini · Native** +in the dashboard's request logs. 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. diff --git a/gui/src/components/protocols/ProtocolTracePanel.tsx b/gui/src/components/protocols/ProtocolTracePanel.tsx index 80c336c8ab5..0b332d3371e 100644 --- a/gui/src/components/protocols/ProtocolTracePanel.tsx +++ b/gui/src/components/protocols/ProtocolTracePanel.tsx @@ -1,3 +1,4 @@ +import { isProtocol } from "../../../../src/protocols/contract"; import { parseProtocolTraceV1 } from "../../../../src/protocols/dto"; import type { TFn } from "../../i18n/shared"; import { openCompatibilityPair, protocolPairUpstream } from "../../protocol-deep-links"; @@ -12,6 +13,8 @@ import { FEATURE_DISPOSITION_KEYS, PROTOCOL_MODE_KEYS, protocolHopLabel, protoco */ export function ProtocolTracePanel({ trace, t }: { trace: unknown; t: TFn }) { const parsed = parseProtocolTraceV1(trace); + const inbound = parsed?.inbound; + const upstream = parsed?.upstream; return (

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

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

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

diff --git a/gui/src/components/protocols/protocol-labels.ts b/gui/src/components/protocols/protocol-labels.ts index 4c73f03e561..9b248e01184 100644 --- a/gui/src/components/protocols/protocol-labels.ts +++ b/gui/src/components/protocols/protocol-labels.ts @@ -1,5 +1,5 @@ import type { DeliveryMode, ProtocolHop } from "../../../../src/protocols/contract"; -import type { ProtocolTraceV1 } from "../../../../src/protocols/dto"; +import type { ProtocolTraceHop, ProtocolTraceV1 } from "../../../../src/protocols/dto"; import type { FeatureDisposition } from "../../../../src/protocols/features"; import type { TFn, TKey } from "../../i18n/shared"; @@ -33,11 +33,11 @@ const HOP_KEYS: Record = { const ARROW = " → "; -export function protocolHopLabel(hop: ProtocolHop, t: TFn): string { - return t(HOP_KEYS[hop]); +export function protocolHopLabel(hop: ProtocolTraceHop, t: TFn): string { + return hop === "gemini" ? "Gemini" : t(HOP_KEYS[hop]); } -export function protocolPathLabel(path: readonly ProtocolHop[], t: TFn): string { +export function protocolPathLabel(path: readonly ProtocolTraceHop[], t: TFn): string { return path.map(hop => protocolHopLabel(hop, t)).join(ARROW); } diff --git a/gui/tests/logs-protocol-trace.test.tsx b/gui/tests/logs-protocol-trace.test.tsx index 9b942b63c56..4d146bf176f 100644 --- a/gui/tests/logs-protocol-trace.test.tsx +++ b/gui/tests/logs-protocol-trace.test.tsx @@ -31,6 +31,14 @@ const native: ProtocolTraceV1 = { attempts: undefined, }; +const gemini: ProtocolTraceV1 = { + ...native, + inbound: "gemini", + upstream: "gemini", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], +}; + describe("ProtocolBadge", () => { test("writes the path and the mode as text", () => { const html = renderToStaticMarkup(); @@ -38,6 +46,15 @@ describe("ProtocolBadge", () => { expect(html).toContain('data-protocol-mode="native"'); }); + test("labels native Gemini in both the list and the detail", () => { + const translate: TFn = (key, vars) => interpolate(DICTS.zh[key], vars); + const badge = renderToStaticMarkup(); + const panel = renderToStaticMarkup(); + expect(badge).toContain("Gemini → Gemini · 原生"); + expect(panel).toContain("Gemini → Gemini"); + expect(panel).not.toContain("protocol-deep-link"); + }); + test("renders nothing for a row without a valid trace", () => { expect(renderToStaticMarkup()).toBe(""); expect(renderToStaticMarkup()).toBe(""); diff --git a/src/protocols/dto.ts b/src/protocols/dto.ts index 3d96365879d..17181a0bb6f 100644 --- a/src/protocols/dto.ts +++ b/src/protocols/dto.ts @@ -87,15 +87,18 @@ export interface ProtocolAttemptTraceV1 { responsePath?: ProtocolHop[]; } +/** A hop in an observed trace. Gemini native delivery does not go through the protocol planner. */ +export type ProtocolTraceHop = ProtocolHop | "gemini"; + /** What one request actually did, recorded at the send boundary and persisted with the log row. */ export interface ProtocolTraceV1 { v: typeof PROTOCOL_TRACE_SCHEMA_VERSION; - inbound: Protocol; + inbound: Protocol | "gemini"; /** Final attempt's mode, or `blocked` when refused before any send. */ mode: DeliveryMode; - upstream?: UpstreamWire; - requestPath: ProtocolHop[]; - responsePath: ProtocolHop[]; + upstream?: UpstreamWire | "gemini"; + requestPath: ProtocolTraceHop[]; + responsePath: ProtocolTraceHop[]; reasonCodes: ProtocolReasonCode[]; featureEffects?: ProtocolFeatureEffectV1[]; attempts?: ProtocolAttemptTraceV1[]; @@ -202,15 +205,24 @@ function isAttemptTrace(value: unknown): value is ProtocolAttemptTraceV1 { && (value.responsePath === undefined || isPath(value.responsePath)); } +function isNativeGeminiPath(value: unknown): boolean { + return Array.isArray(value) && value.length === 2 && value[0] === "gemini" && value[1] === "gemini"; +} + export function isProtocolTraceV1(value: unknown): value is ProtocolTraceV1 { - if (!isRec(value) || value.v !== PROTOCOL_TRACE_SCHEMA_VERSION) return false; - if (!isProtocol(value.inbound) || !isDeliveryMode(value.mode)) return false; - if (value.upstream !== undefined && !isUpstreamWire(value.upstream)) return false; - const pathsOk = value.mode === "blocked" - ? Array.isArray(value.requestPath) && value.requestPath.length === 0 - && Array.isArray(value.responsePath) && value.responsePath.length === 0 - : isPath(value.requestPath) && isPath(value.responsePath); - if (!pathsOk || !isReasonCodes(value.reasonCodes) || typeof value.contractVersion !== "string") return false; + if (!isRec(value) || value.v !== PROTOCOL_TRACE_SCHEMA_VERSION || !isDeliveryMode(value.mode)) return false; + if (value.inbound === "gemini") { + if (value.mode !== "native" || value.upstream !== "gemini" || value.attempts !== undefined + || !isNativeGeminiPath(value.requestPath) || !isNativeGeminiPath(value.responsePath)) return false; + } else { + if (!isProtocol(value.inbound) || (value.upstream !== undefined && !isUpstreamWire(value.upstream))) return false; + const pathsOk = value.mode === "blocked" + ? Array.isArray(value.requestPath) && value.requestPath.length === 0 + && Array.isArray(value.responsePath) && value.responsePath.length === 0 + : isPath(value.requestPath) && isPath(value.responsePath); + if (!pathsOk) return false; + } + if (!isReasonCodes(value.reasonCodes) || typeof value.contractVersion !== "string") return false; if (value.featureEffects !== undefined && !boundedArray(value.featureEffects, PROTOCOL_DTO_LIMITS.featureEffects, isFeatureEffect)) return false; if (value.attempts !== undefined && !boundedArray(value.attempts, PROTOCOL_DTO_LIMITS.attempts, isAttemptTrace)) return false; diff --git a/src/protocols/shadow.ts b/src/protocols/shadow.ts index fbe147d0a31..ff5c388eb40 100644 --- a/src/protocols/shadow.ts +++ b/src/protocols/shadow.ts @@ -18,8 +18,7 @@ * - A blocked trace agrees with a blocked plan. A compatibility reject is Claude-integration * policy the planner does not model, so it is not compared. */ -import type { ProtocolHop } from "./contract"; -import type { ProtocolPlanCandidateV1, ProtocolPlanV1, ProtocolTraceV1 } from "./dto"; +import type { ProtocolPlanCandidateV1, ProtocolPlanV1, ProtocolTraceHop, ProtocolTraceV1 } from "./dto"; /** The route the request settled on, as the request log context records it. */ export interface ShadowSettledRoute { @@ -27,7 +26,7 @@ export interface ShadowSettledRoute { model?: string; } -function samePath(a: readonly ProtocolHop[], b: readonly ProtocolHop[]): boolean { +function samePath(a: readonly ProtocolTraceHop[], b: readonly ProtocolTraceHop[]): boolean { return a.length === b.length && a.every((hop, index) => hop === b[index]); } diff --git a/src/protocols/trace.ts b/src/protocols/trace.ts index d0c1994d23d..723b16e5495 100644 --- a/src/protocols/trace.ts +++ b/src/protocols/trace.ts @@ -62,7 +62,7 @@ export interface ProtocolTraceAttempt { adapter: string; } -const requestMarks = new WeakMap(); +const requestMarks = new WeakMap(); const attemptMarks = new WeakMap(); const shadowInputs = new WeakMap(); const suppressedContexts = new WeakSet(); @@ -121,12 +121,22 @@ export function markProtocolEntry( } } +/** Record an actual native Gemini send without inspecting the payload. */ +export function markNativeGeminiProtocol(logCtx: object): void { + if (protocolTraceSuppressed(logCtx)) return; + try { + requestMarks.set(logCtx, { kind: "gemini-native" }); + } catch { + /* a trace must never fail the request it describes */ + } +} + /** Features the request's entry or blocked mark recorded, for the shadow plan input. */ export function protocolMarkFeatures(logCtx: object): readonly ProtocolFeature[] | undefined { if (protocolTraceSuppressed(logCtx)) return undefined; try { const mark = requestMarks.get(logCtx); - return mark ? [...mark.features] : undefined; + return mark && mark.kind !== "gemini-native" ? [...mark.features] : undefined; } catch { return undefined; } @@ -292,6 +302,18 @@ function observedTrace( ): ProtocolTraceV1 | undefined { try { const mark = requestMarks.get(logCtx); + if (mark?.kind === "gemini-native") { + return { + v: PROTOCOL_TRACE_SCHEMA_VERSION, + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + reasonCodes: ["same-wire-native"], + contractVersion: PROTOCOL_CONTRACT_VERSION, + }; + } if (mark?.kind === "blocked") { return { v: PROTOCOL_TRACE_SCHEMA_VERSION, diff --git a/src/server/gemini-native.ts b/src/server/gemini-native.ts index f34511bc358..93ff850a54c 100644 --- a/src/server/gemini-native.ts +++ b/src/server/gemini-native.ts @@ -1,4 +1,5 @@ import type { OcxConfig } from "../types"; +import { markNativeGeminiProtocol } from "../protocols/trace"; import { getValidAccessSnapshotForAccount, forceRefreshOAuthAccessSnapshot, OAuthLoginRequiredError, OAuthAccountPausedError, OAuthTokenRefreshBusyError, OAuthTokenRefreshStaleError, type OAuthAccessSnapshot } from "../oauth"; import { getAccountSet, getAccountCredentialWithStatus } from "../oauth/store"; import { getProviderRegistryEntry } from "../providers/registry"; @@ -139,10 +140,12 @@ export async function handleGeminiNative( credential.refresh, credential.projectId, credential.accountId, credential.email]) { if (value) boundCredentials.add(value); } + const body = wrapGeminiRequest(raw, model, access.projectId!); + if (logCtx) markNativeGeminiProtocol(logCtx); 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!), + body, }, config.connectTimeoutMs ?? 200_000, ac.signal, true, deps.fetch); }); if (upstream.status !== 401 || attempt === 1) break; diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index 02d90843f04..0b07e76420d 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -44,8 +44,9 @@ default 300-second upload timeout in effect. A stalled upload returns 408. Cance shutdown, failure and EOF release the turn and transport. Native parsing owns no replay state. `src/server/gemini-native-log.ts` records final status, latency, client and admission identity. -Native errors fail the request-log row. Payloads, provider diagnostics and token usage are -omitted from the log. +Native errors fail the request-log row. A physical send marks the [protocol trace](protocol-paths.md) +as native Gemini, which the dashboard uses for its protocol badge. 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/protocol-paths.md b/structure/data-planes/protocol-paths.md index cb6dea2b04e..1458e846ead 100644 --- a/structure/data-planes/protocol-paths.md +++ b/structure/data-planes/protocol-paths.md @@ -88,7 +88,7 @@ native lane, and the request's features; the Messages ingress (`src/server/claud marks caller-forward passthrough and the managed native lane as native, the translated path as the bridge, and a disabled surface or a compatibility reject as blocked. The Responses ingress needs no mark: its path follows the final adapter's wire. Marks live in WeakMaps keyed by the request log context -and the live attempt objects, and no mark function throws into the request. +and the live attempt objects. The native Gemini transport marks its same-wire path when it sends. `addFinalRequestLog` derives one `ProtocolTraceV1` through `path.ts`: a blocked mark wins with empty paths; otherwise each attempt gets the lane-derived path (or an explicit attempt mark), diff --git a/tests/responses/protocol-dto.test.ts b/tests/responses/protocol-dto.test.ts index 9e2f3342f10..8fee85a8341 100644 --- a/tests/responses/protocol-dto.test.ts +++ b/tests/responses/protocol-dto.test.ts @@ -62,6 +62,23 @@ describe("trace validation", () => { expect(parsed.requestPath).not.toBe(trace.requestPath); }); + test("accepts a native Gemini trace and rejects mixed paths", () => { + const gemini: ProtocolTraceV1 = { + v: 1, + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + reasonCodes: ["same-wire-native"], + contractVersion: PROTOCOL_CONTRACT_VERSION, + }; + expect(parseProtocolTraceV1(gemini)).toEqual(gemini); + expect(parseProtocolTraceV1({ ...gemini, upstream: "chat" })).toBeUndefined(); + expect(parseProtocolTraceV1({ ...gemini, responsePath: ["gemini", "chat"] })).toBeUndefined(); + expect(parseProtocolTraceV1({ ...trace, upstream: "gemini" })).toBeUndefined(); + }); + test("a blocked trace has empty paths", () => { const blocked = { ...trace, mode: "blocked", upstream: undefined, requestPath: [], responsePath: [], attempts: undefined }; expect(isProtocolTraceV1(blocked)).toBe(true); diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts index 5160831f8d4..6c94a1e0f9e 100644 --- a/tests/server/gemini-native-routes.test.ts +++ b/tests/server/gemini-native-routes.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { saveConfig } from "../../src/config"; import { saveCredential } from "../../src/oauth/store"; import { startServer } from "../../src/server"; +import { getRequestLogEntries } from "../../src/server/request-log"; import { nativeGeminiDestination } from "../../src/server/gemini-native-catalog"; import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -106,6 +107,14 @@ test("opted-in Gemini routes preserve native JSON and replace every ingress cred expect(response.headers.get("x-opencodex-request-id")).toBeTruthy(); expect(response.headers.has("set-cookie")).toBe(false); expect(await response.text()).toBe(PAYLOAD); + const log = getRequestLogEntries().find(row => row.requestId === response.headers.get("x-opencodex-request-id")); + expect(log?.protocolTrace).toMatchObject({ + inbound: "gemini", + upstream: "gemini", + mode: "native", + requestPath: ["gemini", "gemini"], + responsePath: ["gemini", "gemini"], + }); expect(seen).toHaveLength(1); expect(seen[0]!.url.href).toBe(CCA + "/v1internal:generateContent"); expect(seen[0]!.headers.get("authorization")).toBe("Bearer " + OAUTH_TOKEN); @@ -172,6 +181,12 @@ test("native selection shares key, origin, host, and model-scope refusals", asyn const response = await post(base, generation(), { ...headers }); expect(response.status).toBe(status); expect(await response.json()).toMatchObject({ error: { code: status, status: errorStatus } }); + const requestId = response.headers.get("x-opencodex-request-id"); + if (requestId) { + const log = getRequestLogEntries().find(row => row.requestId === requestId); + expect(log).toBeDefined(); + expect(log?.protocolTrace).toBeUndefined(); + } } expect(seen).toHaveLength(0); expect((await get(base, generation())).headers.get("allow")).toBe("POST"); From 43e6a5a7e6759196b8f6c83b281a4293a1e7d2a3 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:59:00 +0800 Subject: [PATCH 02/19] fix(gemini): expose live-discovered Antigravity models --- .../content/docs/reference/proxy-formats.md | 10 +- src/server/gemini-inbound.ts | 26 +++--- src/server/gemini-native-catalog.ts | 29 +++++- structure/data-planes/gemini-inbound.md | 5 +- structure/data-planes/gemini-native.md | 9 +- tests/server/gemini-native-routes.test.ts | 91 +++++++++++++++++++ 6 files changed, 146 insertions(+), 24 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index b91a9d1996c..e7033c6f4cd 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1155,10 +1155,12 @@ 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. Requests sent through the native path show **Gemini → Gemini · Native** -in the dashboard's request logs. +`alt=sse` or a streamed JSON array otherwise. `GET /v1beta/models` and model lookup include +eligible, live-discovered Gemini models from the Antigravity discovery cache alongside configured +models. Refresh the Antigravity model list in OpenCodex to populate the cache. Native wire aliases +are available when the exact selector routes to that Antigravity model and the admission key +allows it. Requests sent through the native path show **Gemini → Gemini · Native** in the +dashboard's request logs. 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. diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts index 2b298779bdf..619c2388d7b 100644 --- a/src/server/gemini-inbound.ts +++ b/src/server/gemini-inbound.ts @@ -3,8 +3,8 @@ * /v1beta|v1/models/{model}:generateContent|streamGenerateContent (countTokens and the embed * methods answer 501). * - * Same shape as the Ollama inbound (./ollama-inbound): the model list describes configured - * provider routes, generation is translated into an internal Chat Completions request handled by + * Like the Ollama inbound (./ollama-inbound), the catalog starts with configured + * provider routes. Unless the native leg applies, generation is translated into an internal Chat Completions request handled by * the ordinary Chat path, and this handler owns the final request-log row. Errors use the Gemini * `{ error: { code, message, status } }` body with a fixed message chosen by HTTP status. */ @@ -19,9 +19,9 @@ import { chatConversationToIr } from "../protocols/codecs/chat-ir"; import { ChatCompletionsRequestError } from "../chat/inbound"; import { estimateInputTokens } from "./responses/input-admission"; import type { DataPlaneAdmission } from "./auth-cors"; -import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; +import { resolveAdmissionModelScope, routeAllowedByScope, type AdmissionModelScope } from "./admission-model-scope"; import type { GeminiMethod } from "./gemini-native-paths"; -import { geminiNativeCatalogAliases, geminiNativeCatalogLookup } from "./gemini-native-catalog"; +import { geminiNativeCatalogAliases, geminiNativeCatalogLookup, geminiNativeDiscoveredRoutes } from "./gemini-native-catalog"; import { applyLocalRefusalCode, commitCancelled, @@ -66,10 +66,11 @@ export function toGeminiRefusal(response: Response): Response { return applyLocalRefusalCode(geminiError(parts.status, parts.message, parts.retryAfter), parts.localRefusalCode); } -function eligibleRoutes(config: OcxConfig, req: Request, admission: DataPlaneAdmission) { - const scope = resolveAdmissionModelScope(config, admission); - return listOllamaRoutes(config, req) - .filter(row => routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })); +function eligibleRoutes(config: OcxConfig, req: Request, scope: AdmissionModelScope | undefined) { + const configured = listOllamaRoutes(config, req); + const selectors = new Set(configured.map(row => row.selector)); + const discovered = geminiNativeDiscoveredRoutes(config, req).filter(row => !selectors.has(row.selector)); + return [...configured, ...discovered].filter(row => routeAllowedByScope(scope, row.route)); } /** Token limits from configuration first, then generated model metadata; omitted when unknown. */ @@ -96,16 +97,17 @@ const modelResource = (config: OcxConfig, row: { selector: string; route: RouteR }); export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response { - const rows = eligibleRoutes(config, req, admission); - const aliases = geminiNativeCatalogAliases(config, req, rows, resolveAdmissionModelScope(config, admission)); + const scope = resolveAdmissionModelScope(config, admission); + const rows = eligibleRoutes(config, req, scope); + const aliases = geminiNativeCatalogAliases(config, req, rows, scope); return Response.json({ models: [...rows, ...aliases].map(row => modelResource(config, row)) }); } function findGeminiCatalogRow(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string) { - const row = findOllamaRoute(config, model, req); + const row = findOllamaRoute(config, model, req) ?? geminiNativeDiscoveredRoutes(config, req, model)[0]; const scope = resolveAdmissionModelScope(config, admission); if (row && routeAllowedByScope(scope, row.route)) return row; - return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, admission), scope); + return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, scope), scope); } export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { diff --git a/src/server/gemini-native-catalog.ts b/src/server/gemini-native-catalog.ts index 70813403c54..d87619cd7c2 100644 --- a/src/server/gemini-native-catalog.ts +++ b/src/server/gemini-native-catalog.ts @@ -1,5 +1,8 @@ +import { getStaleCached } from "../codex/model-cache"; +import { filterCatalogVisibleModels } from "../codex/catalog/model-visibility"; import { resolveProtocolSettings } from "../protocols/settings"; import { resolveAntigravityEffortWireModel } from "../providers/antigravity-models"; +import { slugEquals } from "../providers/slug-codec"; import { effectiveGoogleMode } from "../providers/registry"; import type { RouteResult } from "../router"; import type { OcxConfig } from "../types"; @@ -35,7 +38,7 @@ export function nativeGeminiDestination(config: OcxConfig, req: Request, selecto /** A native alias must route to the same wire ID and pass scope under its own resolved destination. */ function allowedWireAlias(config: OcxConfig, req: Request, alias: string, scope?: AdmissionModelScope): CatalogRow | undefined { - if (!GEMINI_MODEL.test(alias)) return undefined; + if (!GEMINI_MODEL.test(alias) || nativeModelDisabled(config, alias)) return undefined; const destination = resolveNativeDestination(config, req, alias); if (destination?.wireModel !== alias || !routeAllowedByScope(scope, destination.route)) return undefined; return { selector: alias, route: destination.route }; @@ -43,6 +46,27 @@ function allowedWireAlias(config: OcxConfig, req: Request, alias: string, scope? type CatalogRow = { selector: string; route: RouteResult }; +/** Read the same accepted provider roster as the other catalogs; do not start discovery here. */ +export function geminiNativeDiscoveredRoutes(config: OcxConfig, req: Request, selector?: string): CatalogRow[] { + const provider = config.providers[PROVIDER]; + if (!resolveProtocolSettings(config).rollout.geminiNativeAntigravity + || !provider || provider.disabled === true || provider.liveModels === false + || (selector !== undefined && !selector.startsWith(`${PROVIDER}/`))) return []; + const cached = getStaleCached(PROVIDER) ?? []; + const models = filterCatalogVisibleModels(cached.filter(model => + model.provider === PROVIDER && GEMINI_MODEL.test(model.id)), config); + return models.flatMap(({ id }) => { + const qualified = `${PROVIDER}/${id}`; + if (selector !== undefined && selector !== qualified) return []; + const destination = resolveNativeDestination(config, req, qualified); + return destination?.route.modelId === id ? [{ selector: qualified, route: destination.route }] : []; + }); +} + +function nativeModelDisabled(config: OcxConfig, modelId: string): boolean { + return config.disabledModels?.some(slug => slugEquals(slug, PROVIDER, modelId)) ?? false; +} + export function geminiNativeCatalogLookup( config: OcxConfig, req: Request, alias: string, rows: () => readonly CatalogRow[], scope?: AdmissionModelScope, ): CatalogRow | undefined { @@ -52,7 +76,8 @@ export function geminiNativeCatalogLookup( } function advertisedWireModels(config: OcxConfig, route: RouteResult): string[] { - return [undefined, "low", "medium", "high"].flatMap(effort => nativeWireModel(config, route, effort) ?? []); + if (route.providerName !== PROVIDER || nativeModelDisabled(config, route.modelId)) return []; + return [undefined, "low", "medium", "high", "xhigh"].flatMap(effort => nativeWireModel(config, route, effort) ?? []); } export function geminiNativeCatalogAliases( diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 798dee0e524..dc9032c98af 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -30,10 +30,11 @@ the Chat admission (drain, key, origin, caller session, active turn, workflow, r model-discovery admission `/v1/models` uses. `embedContent` and `batchEmbedContents` answer 501 `UNIMPLEMENTED` after admission; `countTokens` is described below. -The catalog is the same eligible route set as Ollama's `/api/tags` (`src/server/ollama-route-policy.ts` +The catalog starts with the same eligible route set as Ollama's `/api/tags` (`src/server/ollama-route-policy.ts` and the key's model scope): `models//` with `generateContent` and `streamGenerateContent`. Unknown or ineligible models are 404 `NOT_FOUND`; synthetic, shadow, combo -and caller-credential selectors are refused as for Ollama. +and caller-credential selectors are refused as for Ollama. The [opt-in Antigravity catalog](gemini-native.md) +also exposes visible cached Gemini models and their routable wire aliases. `src/protocols/codecs/gemini.ts` maps `contents`, `systemInstruction`, base64 image `inlineData`, `functionDeclarations` and `toolConfig`, `functionCall` and `functionResponse` (matched by id, then by diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index 0b07e76420d..c1c84ae720c 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -8,10 +8,11 @@ Requests outside those conditions use the Chat bridge. Advisor and sidecar capab 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-catalog.ts` extends the configured Gemini catalog with visible Gemini +models from the existing Antigravity discovery cache. List, lookup and token counting apply +the same route and key checks. Wire aliases are published only when routing the alias selects +the native leg and maps to that same wire ID. These reads reuse the cached roster and start no +upstream discovery. Generation resolves the Antigravity wire model before accessing OAuth. `src/server/gemini-native.ts` uses the active, usable OAuth account. The token and project come from the same snapshot, including after one 401-triggered refresh. Each physical send uses diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts index 6c94a1e0f9e..d1b1ba705a1 100644 --- a/tests/server/gemini-native-routes.test.ts +++ b/tests/server/gemini-native-routes.test.ts @@ -2,6 +2,8 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:te import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { fetchProviderModels } from "../../src/codex/catalog/provider-models"; +import { clearModelCache } from "../../src/codex/model-cache"; import { saveConfig } from "../../src/config"; import { saveCredential } from "../../src/oauth/store"; import { startServer } from "../../src/server"; @@ -20,6 +22,12 @@ const GOOGLE_KEY = "fixture-local-ingress-key"; const OAUTH_TOKEN = "fixture-google-oauth-access"; const SCOPE_KEY = "ocx_data_" + "d".repeat(40); const MODEL_SCOPE_KEY = "ocx_data_" + "b".repeat(40); +const HYDROGEN = "gemini-4-hydrogen"; +const NEON = "gemini-4-neon"; +const DISCOVERED_WIRES = [ + ...["low", "medium", "high", "xhigh"].map(tier => `${HYDROGEN}-${tier}`), + ...["low", "medium", "high"].map(tier => `${NEON}-${tier}`), +]; 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; @@ -29,6 +37,7 @@ const previousEnv = { }; const seen: Array<{ url: URL; headers: Headers; body: string }> = []; let home: string; +let discoveryWires: string[]; beforeAll(async () => { home = mkdtempSync(join(tmpdir(), "ocx-native-gemini-routes-")); @@ -49,10 +58,17 @@ afterAll(() => { beforeEach(() => { seen.length = 0; + discoveryWires = []; const fixtureFetch: typeof fetch = Object.assign(async (input: RequestInfo | URL, init?: RequestInit) => { const url = new URL(input instanceof Request ? input.url : String(input)); if (url.hostname === "127.0.0.1" || url.hostname === "localhost") return originalFetch(input, init); if (url.origin !== CCA && url.origin !== CHAT) throw new Error("unexpected external fetch in Gemini fixture"); + if (url.origin === CCA && url.pathname === "/v1internal:fetchAvailableModels" && discoveryWires.length > 0) { + return Response.json({ + models: Object.fromEntries(discoveryWires.map(id => [id, {}])), + agentModelSorts: [{ groups: [{ modelIds: discoveryWires }] }], + }); + } if (init?.method !== "POST" || !url.pathname.includes("generateContent") && !url.pathname.includes("streamGenerateContent") && !url.pathname.endsWith("/chat/completions")) { return Response.json({ models: [], data: [] }); } @@ -93,6 +109,10 @@ async function withServer(cfg: OcxConfig, run: (base: URL) => Promise) { const server = startServer(0); try { await run(server.url); } finally { await server.stop(true); } } +function discoverFixtureModels(cfg: OcxConfig) { + return fetchProviderModels(PROVIDER, { ...cfg.providers[PROVIDER]!, fetch: globalThis.fetch }, 60_000); +} + const key = { "x-goog-api-key": GOOGLE_KEY }; const generation = (model = TARGET, method = "generateContent", version = "v1beta") => `/${version}/models/${model}:${method}`; const post = (base: URL, path: string, headers: Record = key) => @@ -132,6 +152,9 @@ test("flag off, v1, and a Gemini model on another provider use the Chat bridge", const translated = await post(base, path); expect(translated.status).toBe(200); expect(await translated.json()).not.toHaveProperty("future"); + const log = getRequestLogEntries().find(row => row.requestId === translated.headers.get("x-opencodex-request-id")); + expect(log).toBeDefined(); + expect(log?.protocolTrace?.inbound).not.toBe("gemini"); expect(seen.at(-1)?.body).not.toContain(RAW); const other = await post(base, generation(`fx/${MODEL}`)); expect(other.status).toBe(200); @@ -236,3 +259,71 @@ test("model lookup and discovery expose only scoped, routable native wire aliase expect(seen).toHaveLength(0); }); }); + +test("Gemini discovery and lookup reuse live Antigravity models and exact wire tiers", async () => { + const cfg = config(true); + discoveryWires = DISCOVERED_WIRES; + try { + await withServer(cfg, async base => { + await discoverFixtureModels(cfg); + const openaiCatalog = await get(base, "/v1/models", { "x-opencodex-api-key": GOOGLE_KEY }); + expect(openaiCatalog.status).toBe(200); + expect(await openaiCatalog.json()).toMatchObject({ data: expect.arrayContaining([ + expect.objectContaining({ id: `${PROVIDER}/${HYDROGEN}` }), + expect.objectContaining({ id: `${PROVIDER}/${NEON}` }), + ]) }); + + const response = await get(base, "/v1beta/models"); + const { models } = await response.json() as { models: Array<{ name: string }> }; + for (const selector of [`${PROVIDER}/${HYDROGEN}`, `${PROVIDER}/${NEON}`, ...DISCOVERED_WIRES]) { + const listed = models.filter(model => model.name === `models/${selector}`); + expect(listed).toHaveLength(1); + const lookup = await get(base, `/v1beta/models/${selector}`); + expect(lookup.status).toBe(200); + expect(await lookup.json()).toEqual(listed[0]); + expect((await get(base, `/v1beta/models/${selector}`, { "x-goog-api-key": SCOPE_KEY })).status).toBe(404); + expect((await get(base, `/v1beta/models/${selector}`, { "x-goog-api-key": MODEL_SCOPE_KEY })).status).toBe(404); + } + expect(models.map(model => model.name)).not.toContain(`models/${NEON}-xhigh`); + expect((await get(base, `/v1beta/models/${NEON}-xhigh`)).status).toBe(404); + + const send = await post(base, generation(`${HYDROGEN}-xhigh`)); + expect(send.status).toBe(200); + expect(await send.text()).toBe(PAYLOAD); + expect(JSON.parse(seen.at(-1)!.body).model).toBe(`${HYDROGEN}-xhigh`); + }); + } finally { + clearModelCache(PROVIDER); + } +}); + +test("Gemini lists discovered families only when the rollout and model visibility allow them", async () => { + discoveryWires = DISCOVERED_WIRES; + for (const restriction of ["rollout", "disabled", "selection"] as const) { + const cfg = config(restriction !== "rollout"); + if (restriction === "disabled") cfg.disabledModels = [`${PROVIDER}/${HYDROGEN}`, `${PROVIDER}/${NEON}-medium`]; + if (restriction === "selection") cfg.providers[PROVIDER]!.selectedModels = [`${NEON}-high`]; + try { + await withServer(cfg, async base => { + const discovered = await discoverFixtureModels(cfg); + expect(discovered.map(model => model.id)).toContain(NEON); + const response = await get(base, "/v1beta/models"); + const { models } = await response.json() as { models: Array<{ name: string }> }; + const names = models.map(model => model.name); + const excluded = [`${PROVIDER}/${HYDROGEN}`, `${HYDROGEN}-high`]; + if (restriction !== "selection") excluded.push(`${NEON}-medium`); + for (const selector of excluded) { + expect(names).not.toContain(`models/${selector}`); + expect((await get(base, `/v1beta/models/${selector}`)).status).toBe(404); + } + if (restriction !== "rollout") { + expect(names).toContain(`models/${PROVIDER}/${NEON}`); + expect(names).toContain(`models/${NEON}-high`); + expect((await get(base, `/v1beta/models/${NEON}-high`)).status).toBe(200); + } + }); + } finally { + clearModelCache(PROVIDER); + } + } +}); From a133c2543da8bf2cb5075cb1a6e537cf1df6a952 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:08:11 +0800 Subject: [PATCH 03/19] fix(gemini): report native token usage in request logs --- .../content/docs/reference/proxy-formats.md | 3 +- src/adapters/google-usage.ts | 28 +++++++++++++++ src/adapters/google.ts | 27 ++++----------- src/server/gemini-native-wire.ts | 26 ++++++++++++-- src/server/gemini-native.ts | 13 +++++-- structure/data-planes/gemini-native.md | 7 ++-- structure/providers/google.md | 7 ++++ tests/server/gemini-native-routes.test.ts | 8 ++++- tests/server/gemini-native-wire.test.ts | 34 +++++++++++++++++-- 9 files changed, 120 insertions(+), 33 deletions(-) create mode 100644 src/adapters/google-usage.ts diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index e7033c6f4cd..02097d2eb45 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1160,7 +1160,8 @@ eligible, live-discovered Gemini models from the Antigravity discovery cache alo models. Refresh the Antigravity model list in OpenCodex to populate the cache. Native wire aliases are available when the exact selector routes to that Antigravity model and the admission key allows it. Requests sent through the native path show **Gemini → Gemini · Native** in the -dashboard's request logs. +dashboard's request logs. When a completed response reports token counts, the log displays +them and computes the end-to-end output rate. 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. diff --git a/src/adapters/google-usage.ts b/src/adapters/google-usage.ts new file mode 100644 index 00000000000..6b039c30a73 --- /dev/null +++ b/src/adapters/google-usage.ts @@ -0,0 +1,28 @@ +import type { OcxUsage } from "../types"; + +function tokenCount(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +/** Translate Gemini usageMetadata without retaining provider payload fields. */ +export function usageFromGemini(usage: unknown): OcxUsage | undefined { + if (!usage || typeof usage !== "object" || Array.isArray(usage)) return undefined; + const counters = usage as Record; + const prompt = tokenCount(counters.promptTokenCount); + const toolPrompt = tokenCount(counters.toolUsePromptTokenCount); + const candidates = tokenCount(counters.candidatesTokenCount); + const thoughts = tokenCount(counters.thoughtsTokenCount); + const cached = tokenCount(counters.cachedContentTokenCount); + if ([prompt, toolPrompt, candidates, thoughts, cached].every(count => count === undefined)) return undefined; + + // Tool-use prompts are billed as input and thinking tokens are billed as output. + const inputTokens = (prompt ?? 0) + (toolPrompt ?? 0); + const outputTokens = (candidates ?? 0) + (thoughts ?? 0); + if (!Number.isSafeInteger(inputTokens + outputTokens)) return undefined; + return { + inputTokens, + outputTokens, + ...(cached !== undefined ? { cachedInputTokens: cached } : {}), + ...(thoughts !== undefined ? { reasoningOutputTokens: thoughts } : {}), + }; +} diff --git a/src/adapters/google.ts b/src/adapters/google.ts index fe17b39aea4..5f4f10661be 100644 --- a/src/adapters/google.ts +++ b/src/adapters/google.ts @@ -28,6 +28,7 @@ import { readDisplaySafeErrorPayloadText } from "./upstream-http-error"; import { googleModeLabel, googlePromptBlockedEvent, googleStopReason, isGoogleTruncatedTurn, vertexTruncationErrorEvent } from "./google-truncation"; import { antigravitySessionAnchor, antigravityUserAgentForWireModel, antigravitySessionId, isLikelyRealThoughtSignature, sanitizeAntigravityClaudeSignatures } from "./google-antigravity-wire"; import { summarizeGoogleWireShape } from "./google-wire-shape"; +import { usageFromGemini } from "./google-usage"; import { compileGoogleWireBody } from "./google-wire-compiler"; import type { GoogleToolSchemaLossReport, GoogleToolSchemaProfile } from "./google-tool-schema"; import { identifyRoutedModel } from "./identity"; @@ -685,19 +686,6 @@ function toolChoiceToGeminiToolConfig(parsed: OcxParsedRequest): Record | undefined): OcxUsage | undefined { - if (!usage) return undefined; - return { - // Google reports tool-use prompt tokens (search grounding, URL context) beside the prompt. - inputTokens: (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0), - // Google reports thinking beside candidates. Every other adapter's output includes reasoning - // (telemetry clamps reasoning to output, src/telemetry/aggregate.ts), and Google bills it as output. - outputTokens: (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0), - ...(usage.cachedContentTokenCount !== undefined ? { cachedInputTokens: usage.cachedContentTokenCount } : {}), - ...(usage.thoughtsTokenCount !== undefined ? { reasoningOutputTokens: usage.thoughtsTokenCount } : {}), - }; -} - /** * Cap on the buffered non-streaming response body (100 MiB), matching * IMAGES_RESPONSE_MAX_BYTES in src/server/images.ts. Enforced by streaming the @@ -1438,11 +1426,10 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte } // usageMetadata is a top-level field independent of candidates; read it BEFORE the // candidates guard so a usage-only final chunk is not dropped. - const usageMeta = root.usageMetadata as Record | undefined; - if (usageMeta) { + if (root.usageMetadata) { // Accumulate usage; emit a single terminal `done` post-loop so usage is never // dropped on EOF and the stream never yields two `done` events. - pendingUsage = usageFromGemini(usageMeta); + pendingUsage = usageFromGemini(root.usageMetadata) ?? pendingUsage; sawTerminalSignal = true; } const rawCandidates = root.candidates; @@ -1771,7 +1758,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte const feedback = (json as { promptFeedback?: unknown }).promptFeedback; if (isGoogleRecord(feedback) && typeof feedback.blockReason === "string" && feedback.blockReason) { return finish([googlePromptBlockedEvent(googleModeLabel(provider.googleMode), feedback.blockReason, - usageFromGemini(json.usageMetadata as Record | undefined))]); + usageFromGemini(json.usageMetadata))]); } return finish([{ type: "error", message: "google response contained no candidates" }]); } @@ -1855,12 +1842,12 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte return finish([vertexTruncationErrorEvent( candidate.finishReason, toolCallsStarted, - usageFromGemini(json.usageMetadata as Record | undefined), + usageFromGemini(json.usageMetadata), googleModeLabel(provider.googleMode), )]); } - const usage = json.usageMetadata as Record | undefined; + const usage = usageFromGemini(json.usageMetadata); // Mirror the streaming path: a buffered turn cut off by the token limit or a content filter // must carry its stop reason, or the bridge sees a clean `done` and reports the truncated // turn as completed — and, on a compaction turn, installs the half-written summary as @@ -1869,7 +1856,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte const stopReason = googleStopReason(finishReason); events.push({ type: "done", - usage: usageFromGemini(usage), + usage, ...(stopReason ? { stopReason } : {}), }); return finish(events); diff --git a/src/server/gemini-native-wire.ts b/src/server/gemini-native-wire.ts index e195b8eca38..932f7031aa2 100644 --- a/src/server/gemini-native-wire.ts +++ b/src/server/gemini-native-wire.ts @@ -1,3 +1,6 @@ +import { usageFromGemini } from "../adapters/google-usage"; +import type { OcxUsage } from "../types"; + /** Gemini payloads remain source text: parsing is validation, never serialization. */ export const GEMINI_NATIVE_MAX_BYTES = 16 * 1024 * 1024; export const GEMINI_NATIVE_ERROR_CODE = "gemini_native_upstream_error"; @@ -74,10 +77,15 @@ export function wrapGeminiRequest(raw: string, model: string, project: string): return `${envelope.slice(0, -1)},"request":${raw}}`; } +interface GeminiStreamObservers { + onNativeError?: () => void; + onUsage?: (usage: OcxUsage) => void; +} + /** Decode bounded upstream SSE events and frame the unwrapped JSON for the client. */ export function geminiSseTransform( maxBytes = GEMINI_NATIVE_MAX_BYTES, - onNativeError?: () => void, + observers?: GeminiStreamObservers, format: "sse" | "array" = "sse", credentials: readonly string[] = [], ): TransformStream { @@ -86,15 +94,24 @@ export function geminiSseTransform( let lineParts: string[] = [], data: string[] = [], eventBytes = 0, afterCR = false; const candidates = new Map(); let terminal = false, blocked = false, arrayOpened = false; + let usage: OcxUsage | undefined; + const reportUsage = () => { + if (!usage) return; + try { observers?.onUsage?.(usage); } catch { /* Observational callbacks never change delivery. */ } + }; const complete = () => candidates.size ? [...candidates.values()].every(Boolean) : blocked; const closeArray = (controller: TransformStreamDefaultController) => { if (format === "array") controller.enqueue(encoder.encode("\n]")); }; function observe(raw: string) { - const value = JSON.parse(raw) as { candidates?: Array<{ index?: number; finishReason?: string }>; error?: unknown; promptFeedback?: { blockReason?: string } }; + const value = JSON.parse(raw) as { + candidates?: Array<{ index?: number; finishReason?: string }>; + promptFeedback?: { blockReason?: string }; + usageMetadata?: unknown; + }; if (Object.hasOwn(value, "error") || containsGeminiCredential(raw, credentials)) { terminal = true; - try { onNativeError?.(); } catch { /* Observational callbacks never change delivery. */ } + try { observers?.onNativeError?.(); } catch { /* Observational callbacks never change delivery. */ } return SAFE_UPSTREAM_ERROR; } blocked ||= !!value.promptFeedback?.blockReason; @@ -105,6 +122,7 @@ export function geminiSseTransform( if (!Number.isSafeInteger(index) || index < 0 || candidates.size >= 1024 && !candidates.has(index)) throw new Error("invalid Gemini candidate index"); candidates.set(index, candidates.get(index) === true || typeof candidate.finishReason === "string" && candidate.finishReason.length > 0); } + if (observers?.onUsage) usage = usageFromGemini(value.usageMetadata) ?? usage; return raw; } function emit(controller: TransformStreamDefaultController) { @@ -112,6 +130,7 @@ export function geminiSseTransform( const payload = data.join("\n"); if (payload.trim() === "[DONE]") { if (!complete()) throw new Error("premature Gemini stream terminator"); + reportUsage(); terminal = true; } else { const response = observe(unwrapGeminiResponse(payload)); @@ -168,6 +187,7 @@ export function geminiSseTransform( if (tail) lineParts.push(tail); if (lineParts.join("").trim() || data.length) throw new Error("truncated Gemini SSE event"); if (!complete()) throw new Error("incomplete Gemini generation"); + reportUsage(); closeArray(controller); }, }); diff --git a/src/server/gemini-native.ts b/src/server/gemini-native.ts index 93ff850a54c..bc99c956851 100644 --- a/src/server/gemini-native.ts +++ b/src/server/gemini-native.ts @@ -1,9 +1,10 @@ -import type { OcxConfig } from "../types"; +import type { OcxConfig, OcxUsage } from "../types"; import { markNativeGeminiProtocol } from "../protocols/trace"; import { getValidAccessSnapshotForAccount, forceRefreshOAuthAccessSnapshot, OAuthLoginRequiredError, OAuthAccountPausedError, OAuthTokenRefreshBusyError, OAuthTokenRefreshStaleError, type OAuthAccessSnapshot } from "../oauth"; import { getAccountSet, getAccountCredentialWithStatus } from "../oauth/store"; import { getProviderRegistryEntry } from "../providers/registry"; import { sendTrackingRequestSlot, waitForProviderRequestSlot, RequestPacingQueueOverloadError, RequestPacingProviderRemovedError } from "../providers/request-pacing"; +import { usageFromGemini } from "../adapters/google-usage"; import { antigravityUserAgentForWireModel } from "../adapters/google-antigravity-wire"; import { fetchWithAttemptDeadline, releaseResponseBodyBestEffort } from "../lib/upstream-retry"; import { reserveWorkflowSend } from "../lib/workflow-budget"; @@ -90,6 +91,7 @@ export async function handleGeminiNative( const noteNativeError = () => { if (logCtx) { logCtx.errorCode = GEMINI_NATIVE_ERROR_CODE; logCtx.terminalSource = "upstream"; } }; + const noteUsage = logCtx ? (usage: OcxUsage) => { logCtx.usage = usage; } : undefined; let upstream: Response | undefined; try { const maxBytes = Math.min(GEMINI_NATIVE_MAX_BYTES, config.maxInboundBodyBytes ?? GEMINI_NATIVE_MAX_BYTES); @@ -182,15 +184,20 @@ export async function handleGeminiNative( const credentials = [...boundCredentials]; if (streamFormat) { const headers = { "Content-Type": streamFormat === "sse" ? "text/event-stream" : "application/json", "Cache-Control": "no-cache" }; - return new Response(body.pipeThrough(geminiSseTransform(GEMINI_NATIVE_MAX_BYTES, noteNativeError, streamFormat, credentials)), { headers }); + return new Response(body.pipeThrough(geminiSseTransform( + GEMINI_NATIVE_MAX_BYTES, { onNativeError: noteNativeError, onUsage: noteUsage }, streamFormat, credentials, + )), { headers }); } const text = await readGeminiText(body, GEMINI_NATIVE_MAX_BYTES, ac.signal); if (text === null) return geminiNativeError(502, "Gemini upstream response exceeds the body limit"); const response = unwrapGeminiResponse(text); - if (Object.hasOwn(JSON.parse(response), "error") || containsGeminiCredential(response, credentials)) { + const payload = JSON.parse(response) as { usageMetadata?: unknown }; + if (Object.hasOwn(payload, "error") || containsGeminiCredential(response, credentials)) { noteNativeError(); return geminiNativeError(502, "Antigravity upstream rejected the request"); } + const usage = usageFromGemini(payload.usageMetadata); + if (usage) noteUsage?.(usage); return new Response(response, { headers: { "Content-Type": "application/json" } }); } catch (error) { ac.abort(); finish(); diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index c1c84ae720c..f229771655f 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -46,8 +46,11 @@ shutdown, failure and EOF release the turn and transport. Native parsing owns no `src/server/gemini-native-log.ts` records final status, latency, client and admission identity. Native errors fail the request-log row. A physical send marks the [protocol trace](protocol-paths.md) -as native Gemini, which the dashboard uses for its protocol badge. Payloads, provider diagnostics -and token usage are omitted from the log. +as native Gemini, which the dashboard uses for its protocol badge. Successful buffered responses +and complete streams supply normalized token counts through the shared Google usage parser. +For a stream, only its last valid cumulative snapshot is recorded. The dashboard derives its +end-to-end token rate from output tokens and request duration. Payloads and provider diagnostics +are omitted from the log. Coverage lives in `tests/server/gemini-native-routes.test.ts`, `tests/server/gemini-native-wire.test.ts` and `tests/server/gemini-native.test.ts`. diff --git a/structure/providers/google.md b/structure/providers/google.md index 09433046dd6..5d105c55fa9 100644 --- a/structure/providers/google.md +++ b/structure/providers/google.md @@ -10,6 +10,13 @@ UTF-8 encoding or rescanning of the growing prefix. The existing per-frame limit requirements and heartbeat batching remain in force. Replacement strings, including decoder EOF output, retain the [shared byte-accounting contract](../transports/byte-accounting.md#stream-buffer-accounting). +## Reported usage + +`src/adapters/google-usage.ts` normalizes `usageMetadata` for the Google adapter and the native +Gemini route. Prompt and tool-use prompt tokens count as input. Candidate and thought tokens +count as output, with cached input and thought tokens also available as separate counters. +The parser retains only valid numeric counters. + ## Vertex API-key endpoint selection Vertex requests may use host ADC without an API key. The ambient API key stays out of generic provider configuration: `src/providers/vertex-environment-authority.ts` keeps a keyed process-local digest and observed generation with the selected route, and only the Google adapter reads the key. For ADC, routed project and location are captured and rechecked before dispatch. `src/lib/gcp-adc.ts` identifies file and marker sources by keyed content digest and observed generation, checks the source before and after token exchange, and binds its identity to the built request. Shared token refresh has independently cancellable waiters. `src/server/responses/request-transport.ts` checks the provider and request binding after pacing, transfers it on rebuild, and checks the final selection, target and credential after plugin rewrites. The `project: "auto"` auxiliary probe checks the same selection before sending. Unreadable credentials fail closed. A service-account marker selects its named credential instead of the ambient key. Metadata identity changes and an external A→B→A change entirely between observations cannot be detected locally. `tests/adapters/google/gcp-adc.test.ts` covers synthetic key, ADC and physical-dispatch boundaries. diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts index d1b1ba705a1..3bba76b6cdf 100644 --- a/tests/server/gemini-native-routes.test.ts +++ b/tests/server/gemini-native-routes.test.ts @@ -29,7 +29,8 @@ const DISCOVERED_WIRES = [ ...["low", "medium", "high"].map(tier => `${NEON}-${tier}`), ]; const RAW = '{"contents":[{"role":"user","parts":[{"text":"hello"}]}], "future":9007199254740993123}'; -const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"future":9007199254740993123}'; +const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":12,"toolUsePromptTokenCount":5,"candidatesTokenCount":7,"thoughtsTokenCount":3,"cachedContentTokenCount":4},"future":9007199254740993123}'; +const USAGE = { inputTokens: 17, outputTokens: 10, cachedInputTokens: 4, reasoningOutputTokens: 3 }; const originalFetch = globalThis.fetch; const previousEnv = { OPENCODEX_HOME: process.env.OPENCODEX_HOME, @@ -128,6 +129,7 @@ test("opted-in Gemini routes preserve native JSON and replace every ingress cred expect(response.headers.has("set-cookie")).toBe(false); expect(await response.text()).toBe(PAYLOAD); const log = getRequestLogEntries().find(row => row.requestId === response.headers.get("x-opencodex-request-id")); + expect(log).toMatchObject({ usageStatus: "reported", usage: USAGE, totalTokens: 27 }); expect(log?.protocolTrace).toMatchObject({ inbound: "gemini", upstream: "gemini", @@ -188,6 +190,10 @@ test("native streaming preserves records in both Gemini response formats", async const json = await post(base, path); expect(json.headers.get("content-type")).toContain("application/json"); expect(await json.text()).toBe(`[\n${PAYLOAD}\n]`); + for (const res of [sse, discoverySse, json]) { + const log = getRequestLogEntries().find(row => row.requestId === res.headers.get("x-opencodex-request-id")); + expect(log).toMatchObject({ usageStatus: "reported", usage: USAGE, totalTokens: 27 }); + } expect(seen.map(call => call.url.href)).toEqual(Array(3).fill(CCA + "/v1internal:streamGenerateContent?alt=sse")); }); }); diff --git a/tests/server/gemini-native-wire.test.ts b/tests/server/gemini-native-wire.test.ts index d71dda73d08..87cacbeee5b 100644 --- a/tests/server/gemini-native-wire.test.ts +++ b/tests/server/gemini-native-wire.test.ts @@ -1,4 +1,4 @@ -import { expect, spyOn, test } from "bun:test"; +import { expect, mock, 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"}}'; @@ -13,14 +13,16 @@ test("envelope extraction handles escaped keys, nesting, braces in strings and r expect(() => unwrapGeminiResponse(raw)).toThrow(); } }); -async function transform(text: string, chunk = 1, limit?: number): Promise { +async function transform( + text: string, chunk = 1, limit?: number, observers?: Parameters[1], +): Promise { const bytes = new TextEncoder().encode(text); let offset = 0; const body = new ReadableStream({ pull(c) { if (offset === bytes.length) { c.close(); return; } c.enqueue(bytes.slice(offset, offset + chunk)); offset = Math.min(bytes.length, offset + chunk); } }); - return new Response(body.pipeThrough(geminiSseTransform(limit))).text(); + return new Response(body.pipeThrough(geminiSseTransform(limit, observers))).text(); } test("SSE accepts byte-split UTF8, CRLF, comments and multiple events", async () => { const frame = `: ping\r\ndata: {"response":${response}}\r\n\r\n`; @@ -77,3 +79,29 @@ test("fragmented 1 MiB SSE lines perform only linear UTF-8 encoding work", async // Input plus output are about 2 MiB; re-encoding retained prefixes would exceed 500 MiB. expect(encodedBytes).toBeLessThan(frame.length * 3); }); + +test("native SSE reports the final cumulative usage once, retaining all original frames", async () => { + const frames = [ + '{"candidates":[{"index":0}],"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":2}}', + '{"candidates":[{"index":0,"finishReason":"STOP"}]}', + '{"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":6,"thoughtsTokenCount":9,"future":9007199254740993123}}', + '{"usageMetadata":{"candidatesTokenCount":"unreported"}}', + ]; + const upstream = frames.map(json => `data: {"response":${json}}\n\n`).join(""); + for (const terminator of ["", "data: [DONE]\n\n"]) { + const onUsage = mock(); + const result = await transform(upstream + terminator, 7, undefined, { onUsage }); + expect(result).toBe(frames.map(json => `data: ${json}\n\n`).join("")); + expect(onUsage).toHaveBeenCalledTimes(1); + expect(onUsage).toHaveBeenCalledWith({ inputTokens: 19, outputTokens: 15, reasoningOutputTokens: 9 }); + } +}); + +test("native SSE does not report partial usage when the response fails", async () => { + const frame = 'data: {"response":{"candidates":[{"index":0}],"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":2}}}\n\n'; + const onUsage = mock(); + await expect(transform(frame, 7, undefined, { onUsage })).rejects.toThrow("incomplete Gemini generation"); + const error = 'data: {"response":{"error":{"message":"rejected"}}}\n\n'; + await transform(frame + error, 7, undefined, { onUsage }); + expect(onUsage).not.toHaveBeenCalled(); +}); From d4c52d40e25aeee10f2df889514f6f59ec9b47d4 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:50:23 +0800 Subject: [PATCH 04/19] fix(gemini): scope listed tiers and add official rate estimates --- .../content/docs/reference/proxy-formats.md | 4 +++- src/server/gemini-inbound.ts | 14 ++++++----- src/usage/expected-prices.ts | 17 +++++++++++++ structure/dashboard-and-usage.md | 2 +- structure/data-planes/gemini-native.md | 10 ++++---- tests/server/gemini-native-routes.test.ts | 21 ++++++++++++++++ tests/usage/usage-cost.test.ts | 24 +++++++++++++++++++ 7 files changed, 80 insertions(+), 12 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 02097d2eb45..89325cee438 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1161,7 +1161,9 @@ models. Refresh the Antigravity model list in OpenCodex to populate the cache. N are available when the exact selector routes to that Antigravity model and the admission key allows it. Requests sent through the native path show **Gemini → Gemini · Native** in the dashboard's request logs. When a completed response reports token counts, the log displays -them and computes the end-to-end output rate. +them and computes the end-to-end output rate. For models with a matched official rate, the +`~$` column estimates the equivalent Gemini API cost from reported input, output and cache-hit +tokens. The amount is an API price reference for Antigravity OAuth sessions. 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. diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts index 619c2388d7b..6ff831de6ad 100644 --- a/src/server/gemini-inbound.ts +++ b/src/server/gemini-inbound.ts @@ -19,7 +19,7 @@ import { chatConversationToIr } from "../protocols/codecs/chat-ir"; import { ChatCompletionsRequestError } from "../chat/inbound"; import { estimateInputTokens } from "./responses/input-admission"; import type { DataPlaneAdmission } from "./auth-cors"; -import { resolveAdmissionModelScope, routeAllowedByScope, type AdmissionModelScope } from "./admission-model-scope"; +import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; import type { GeminiMethod } from "./gemini-native-paths"; import { geminiNativeCatalogAliases, geminiNativeCatalogLookup, geminiNativeDiscoveredRoutes } from "./gemini-native-catalog"; import { @@ -66,11 +66,11 @@ export function toGeminiRefusal(response: Response): Response { return applyLocalRefusalCode(geminiError(parts.status, parts.message, parts.retryAfter), parts.localRefusalCode); } -function eligibleRoutes(config: OcxConfig, req: Request, scope: AdmissionModelScope | undefined) { +function geminiCatalogRoutes(config: OcxConfig, req: Request) { const configured = listOllamaRoutes(config, req); const selectors = new Set(configured.map(row => row.selector)); const discovered = geminiNativeDiscoveredRoutes(config, req).filter(row => !selectors.has(row.selector)); - return [...configured, ...discovered].filter(row => routeAllowedByScope(scope, row.route)); + return [...configured, ...discovered]; } /** Token limits from configuration first, then generated model metadata; omitted when unknown. */ @@ -98,8 +98,10 @@ const modelResource = (config: OcxConfig, row: { selector: string; route: RouteR export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response { const scope = resolveAdmissionModelScope(config, admission); - const rows = eligibleRoutes(config, req, scope); - const aliases = geminiNativeCatalogAliases(config, req, rows, scope); + const candidates = geminiCatalogRoutes(config, req); + const rows = candidates.filter(row => routeAllowedByScope(scope, row.route)); + // A key can allow a concrete effort tier while excluding its source family. + const aliases = geminiNativeCatalogAliases(config, req, candidates, scope); return Response.json({ models: [...rows, ...aliases].map(row => modelResource(config, row)) }); } @@ -107,7 +109,7 @@ function findGeminiCatalogRow(config: OcxConfig, req: Request, admission: DataPl const row = findOllamaRoute(config, model, req) ?? geminiNativeDiscoveredRoutes(config, req, model)[0]; const scope = resolveAdmissionModelScope(config, admission); if (row && routeAllowedByScope(scope, row.route)) return row; - return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, scope), scope); + return geminiNativeCatalogLookup(config, req, model, () => geminiCatalogRoutes(config, req), scope); } export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { diff --git a/src/usage/expected-prices.ts b/src/usage/expected-prices.ts index 74c224af113..a4cca5d3dac 100644 --- a/src/usage/expected-prices.ts +++ b/src/usage/expected-prices.ts @@ -98,6 +98,16 @@ const GEMINI_38_FLASH: Cost4 = { input: 0.75, output: 3.75, cacheRead: 0.075, ca // per 1M through 2026-11-30, stepping up to $4 / $20 / $0.20 on 2026-12-01. Revisit this row // then. No free tier. Implicit caching only, so there is no per-token cache-write price. const GEMINI_4_ARGON: Cost4 = { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 }; +// Standard paid Gemini API rates. Antigravity uses the same token rates as an +// estimated reference. Its generation usage reports cache hits but no cache-write count. +const GEMINI_4_API_RATES = [ + { modelId: "gemini-4-hydrogen", cost4: { input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 0 } }, + { modelId: "gemini-4-neon", cost4: { input: 3, output: 15, cacheRead: 0.15, cacheWrite: 0 } }, +].map(row => ({ + ...row, + source: `https://ai.google.dev/gemini-api/docs/pricing#${row.modelId} (Standard paid tier)`, + verifiedAt: "2026-11-19", +})); const MINIMAX_M21_HIGHSPEED: Cost4 = { input: 0.6, output: 2.4, cacheRead: 0.03, cacheWrite: 0.375 }; const KIMI_K3: Cost4 = { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3 }; // K3.1 Pro and its highspeed variant: flat 1M-context pricing (no context tiering). Like K3, @@ -412,6 +422,12 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ // 3.7 Flash rides CCA, whose billing equivalence to the Developer API list price is // not published, so this is `verified-derived` rather than `verified`: the number is // proven, the claim that Antigravity charges it is inferred. + ...GEMINI_4_API_RATES.flatMap(row => [ + row.modelId, ...["low", "medium", "high", "xhigh"].map(effort => `${row.modelId}-${effort}`), + ].map(modelId => ({ + ...row, provider: "google-antigravity", modelId, + source: `derived: Gemini API reference price ${row.source}`, status: "verified-derived" as const, + }))), // Gemini 4 Argon on Antigravity (AI Ultra / Enterprise only): the picker id plus its three // verified CCA wire ids. Billing equivalence to the API price is inferred. { provider: "google-antigravity", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: `derived: Gemini 4 Argon introductory rate through 2026-11-30 ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, @@ -471,6 +487,7 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ { provider: "google-antigravity", modelId: "gemini-3.5-flash-high", cost4: GEMINI_36_FLASH, source: `compat alias -> gemini-3.6-flash-high ${GEMINI_PRICING}`, verifiedAt: "2026-07-22", status: "verified-derived" }, { provider: "google-antigravity", modelId: "gemini-3-flash-agent", cost4: GEMINI_36_FLASH, source: `compat alias -> gemini-3.6-flash-high ${GEMINI_PRICING}`, verifiedAt: "2026-07-22", status: "verified-derived" }, // Direct Google Gemini API current model (verified — published table). + ...GEMINI_4_API_RATES.map(row => ({ ...row, provider: "google", status: "verified" as const })), { provider: "google", modelId: "gemini-3.6-flash", cost4: GEMINI_36_FLASH, source: GEMINI_PRICING, verifiedAt: "2026-07-22", status: "verified" }, // Developer API row: the price IS published for this surface, so `verified`. { provider: "google", modelId: "gemini-3.7-flash", cost4: GEMINI_37_FLASH, source: GEMINI_37_PRICING, verifiedAt: "2026-08-14", status: "verified" }, diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 01a766602da..95ba1b8cb40 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -331,7 +331,7 @@ selectors, a vendor-only inferred price is unavailable; exact provider and user eligible. Missing trace evidence is not reconstructed from today's configuration. Provider-detail model shares use that provider's token total, not the global total. Unknown reserved `policy/` selectors are rejected before upstream dispatch; historical rows remain unchanged. -Haiku 5.5 in `src/usage/expected-prices.ts` uses 0.10/0.50/0.01/0.125 USD per MTok (input/output/cache read/5m write), with all four rates multiplied by five above 100,000 raw prompt tokens; exactly 100,000 stays base. Exact provider/id bands include Cursor regular effort spellings and reference-priced preemptive surfaces; Kilo stays untiered. Sonnet 5.5 cache read is 0.10 (0.05x input), except Bedrock retains partner rates and Venice has its 1.25x exact overlay. Expected-price overlays are estimates, not billing reproductions: the Z.AI GLM rows (`zai`, `zhipu-bigmodel`, `zhipu-bigmodel-coding`, `zhipu-bigmodel-responses`) display the published z.ai USD list price on surfaces that actually bill by Coding Plan subscription or CNY-tiered domestic PAYG, and every such row is marked `verified-derived` so the estimate flag reaches the UI. Antigravity Claude Sonnet and Opus 5.5 base/tier overlays in `src/usage/expected-prices.ts` likewise use Anthropic reference prices with `verified-derived`, so even reported tokens retain an estimated-cost flag. +Haiku 5.5 in `src/usage/expected-prices.ts` uses 0.10/0.50/0.01/0.125 USD per MTok (input/output/cache read/5m write), with all four rates multiplied by five above 100,000 raw prompt tokens; exactly 100,000 stays base. Exact provider/id bands include Cursor regular effort spellings and reference-priced preemptive surfaces; Kilo stays untiered. Sonnet 5.5 cache read is 0.10 (0.05x input), except Bedrock retains partner rates and Venice has its 1.25x exact overlay. Expected-price overlays are estimates, not billing reproductions: the Z.AI GLM rows (`zai`, `zhipu-bigmodel`, `zhipu-bigmodel-coding`, `zhipu-bigmodel-responses`) display the published z.ai USD list price on surfaces that actually bill by Coding Plan subscription or CNY-tiered domestic PAYG, and every such row is marked `verified-derived` so the estimate flag reaches the UI. Antigravity base and effort overlays in `src/usage/expected-prices.ts` use Anthropic API reference prices for Claude Sonnet and Opus 5.5 and standard Gemini API rates for Gemini 4 Neon and Hydrogen. These rows carry `verified-derived`, so reported tokens still produce an estimated cost. The management API retains the compact accumulator plus bounded query summaries; it never retains normalized per-request rows after a response. File identity changes, shrinkage, same-size metadata diff --git a/structure/data-planes/gemini-native.md b/structure/data-planes/gemini-native.md index f229771655f..e3fa1a10e9d 100644 --- a/structure/data-planes/gemini-native.md +++ b/structure/data-planes/gemini-native.md @@ -9,8 +9,9 @@ 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` extends the configured Gemini catalog with visible Gemini -models from the existing Antigravity discovery cache. List, lookup and token counting apply -the same route and key checks. Wire aliases are published only when routing the alias selects +models from the existing Antigravity discovery cache and the shared model visibility filter. +List, lookup and token counting apply the same route and key checks to the advertised +destination. A key can allow a concrete tier without allowing its source family. Wire aliases are published only when routing the alias selects the native leg and maps to that same wire ID. These reads reuse the cached roster and start no upstream discovery. Generation resolves the Antigravity wire model before accessing OAuth. @@ -49,8 +50,9 @@ Native errors fail the request-log row. A physical send marks the [protocol trac as native Gemini, which the dashboard uses for its protocol badge. Successful buffered responses and complete streams supply normalized token counts through the shared Google usage parser. For a stream, only its last valid cumulative snapshot is recorded. The dashboard derives its -end-to-end token rate from output tokens and request duration. Payloads and provider diagnostics -are omitted from the log. +end-to-end token rate from output tokens and request duration. When an API price matches, +the cost estimate accounts for reported cache hits at the read rate. Gemini generation usage +has no cache-write counter. Payloads and provider diagnostics are omitted from the log. Coverage lives in `tests/server/gemini-native-routes.test.ts`, `tests/server/gemini-native-wire.test.ts` and `tests/server/gemini-native.test.ts`. diff --git a/tests/server/gemini-native-routes.test.ts b/tests/server/gemini-native-routes.test.ts index 3bba76b6cdf..210b5039036 100644 --- a/tests/server/gemini-native-routes.test.ts +++ b/tests/server/gemini-native-routes.test.ts @@ -24,9 +24,12 @@ const SCOPE_KEY = "ocx_data_" + "d".repeat(40); const MODEL_SCOPE_KEY = "ocx_data_" + "b".repeat(40); const HYDROGEN = "gemini-4-hydrogen"; const NEON = "gemini-4-neon"; +const NEW_GEMINI = "gemini-discovery-fixture"; +const TIER_SCOPE_KEY = "ocx_data_" + "f".repeat(40); const DISCOVERED_WIRES = [ ...["low", "medium", "high", "xhigh"].map(tier => `${HYDROGEN}-${tier}`), ...["low", "medium", "high"].map(tier => `${NEON}-${tier}`), + NEW_GEMINI, ]; const RAW = '{"contents":[{"role":"user","parts":[{"text":"hello"}]}], "future":9007199254740993123}'; const PAYLOAD = '{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":12,"toolUsePromptTokenCount":5,"candidatesTokenCount":7,"thoughtsTokenCount":3,"cachedContentTokenCount":4},"future":9007199254740993123}'; @@ -102,6 +105,8 @@ function config(flag?: boolean): OcxConfig { { id: "gemini-scope", name: "Gemini scope", key: SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: ["fx"] }, { id: "gemini-model-scope", name: "Gemini model scope", key: MODEL_SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: [PROVIDER], allowedModels: [`${PROVIDER}/gemini-4-argon`] }, + { id: "gemini-tier-scope", name: "Gemini tier scope", key: TIER_SCOPE_KEY, createdAt: "2026-01-01T00:00:00.000Z", + allowedProviders: [PROVIDER], allowedModels: [`${PROVIDER}/${HYDROGEN}-high`] }, ], }; } @@ -293,6 +298,22 @@ test("Gemini discovery and lookup reuse live Antigravity models and exact wire t expect(models.map(model => model.name)).not.toContain(`models/${NEON}-xhigh`); expect((await get(base, `/v1beta/models/${NEON}-xhigh`)).status).toBe(404); + const tierScope = { "x-goog-api-key": TIER_SCOPE_KEY }; + const high = `${HYDROGEN}-high`; + const scopedCatalog = await get(base, "/v1beta/models", tierScope); + const scopedModels = (await scopedCatalog.json() as { models: Array<{ name: string }> }).models; + expect(scopedModels.map(model => model.name)).toEqual([`models/${high}`]); + const scopedLookup = await get(base, `/v1beta/models/${high}`, tierScope); + expect(scopedLookup.status).toBe(200); + expect(await scopedLookup.json()).toEqual(scopedModels[0]); + expect((await get(base, `/v1beta/models/${PROVIDER}/${HYDROGEN}`, tierScope)).status).toBe(404); + expect((await get(base, `/v1beta/models/${HYDROGEN}-xhigh`, tierScope)).status).toBe(404); + const scopedSend = await post(base, generation(high), tierScope); + expect(scopedSend.status).toBe(200); + expect(await scopedSend.text()).toBe(PAYLOAD); + expect(JSON.parse(seen.at(-1)!.body).model).toBe(high); + expect((await post(base, generation(`${HYDROGEN}-xhigh`), tierScope)).status).toBe(403); + const send = await post(base, generation(`${HYDROGEN}-xhigh`)); expect(send.status).toBe(200); expect(await send.text()).toBe(PAYLOAD); diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index 0ecf16758f2..5f3b62c671e 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1978,3 +1978,27 @@ describe("aggregator vendor-prefixed model ids (#3136)", () => { expect(resolveMatchedPrice("openrouter", "a/deepseek/deepseek-v4-flash")).toBeNull(); }); }); + +test("Antigravity Gemini 4 prices exact effort IDs using reported input, output and cache hits", () => { + const usage = { inputTokens: 10_000, outputTokens: 1_000, cachedInputTokens: 4_000, reasoningOutputTokens: 800 }; + for (const [base, expected] of [ + ["gemini-4-neon", { input: 0.018, output: 0.015, cacheRead: 0.0006, total: 0.0336 }], + ["gemini-4-hydrogen", { input: 0.009, output: 0.0075, cacheRead: 0.0003, total: 0.0168 }], + ] as const) { + for (const suffix of ["", "-low", "-medium", "-high", "-xhigh"]) { + const estimate = estimateRequestCost({ + provider: "google-antigravity", model: base + suffix, usage, usageStatus: "reported", + }); + expect(estimate?.price).toMatchObject({ modelId: base + suffix, source: "expected", status: "verified-derived" }); + expect(estimate?.estimated).toBe(true); + expect(estimate?.tokens).toEqual({ input: 6_000, output: 1_000, cacheRead: 4_000, cacheWrite: 0 }); + expect(estimate?.cost.cacheWrite).toBe(0); + for (const component of ["input", "output", "cacheRead", "total"] as const) { + expect(estimate!.cost[component]).toBeCloseTo(expected[component], 12); + } + } + const direct = resolveMatchedPrice("google", base); + expect(direct?.status).toBe("verified"); + } + expect(resolveMatchedPrice("google-antigravity", "gemini-discovery-fixture")).toBeNull(); +}); From c4c386abc2691e6c0c3cf7b9db63ac10bccb1901 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:04:01 +0800 Subject: [PATCH 05/19] feat(gemini): expose native switch and report reasoning and timing --- .../content/docs/es/guides/integrations.md | 2 +- .../src/content/docs/guides/integrations.md | 5 +- .../content/docs/reference/proxy-formats.md | 6 +- ...tting.tsx => NativePassthroughSetting.tsx} | 63 ++++++++++++------- .../provider-workspace/ProviderAuthPanel.tsx | 9 ++- gui/src/i18n/de.ts | 4 ++ gui/src/i18n/en.ts | 4 ++ gui/src/i18n/fr.ts | 4 ++ gui/src/i18n/ja.ts | 4 ++ gui/src/i18n/ko.ts | 4 ++ gui/src/i18n/pt.ts | 4 ++ gui/src/i18n/ru.ts | 4 ++ gui/src/i18n/tr.ts | 4 ++ gui/src/i18n/vi.ts | 4 ++ gui/src/i18n/zh-TW.ts | 4 ++ gui/src/i18n/zh.ts | 4 ++ gui/src/pages/Logs.tsx | 3 +- ...claude-native-passthrough-setting.test.tsx | 44 ++++++++++++- src/server/gemini-native-wire.ts | 53 ++++++++++++++-- src/server/gemini-native.ts | 35 ++++++++--- src/server/index/gemini-routes.ts | 2 +- src/server/management/shared.ts | 7 ++- src/server/request-log-generation-window.ts | 9 ++- structure/data-planes/gemini-inbound.md | 3 +- structure/data-planes/gemini-native.md | 8 ++- tests/server/gemini-native-routes.test.ts | 10 ++- tests/server/gemini-native-wire.test.ts | 31 ++++++++- .../request-log-generation-window.test.ts | 8 +++ 28 files changed, 284 insertions(+), 58 deletions(-) rename gui/src/components/provider-workspace/{ClaudeNativePassthroughSetting.tsx => NativePassthroughSetting.tsx} (58%) diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index 49a07c3f84f..8823ada7e33 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -780,7 +780,7 @@ del proceso de OpenCodex. Si la variable se fija únicamente en el proceso de An no la detecta. En Windows `agy` no está probado, porque Google lo publica solo para macOS y Linux. Para conservar el JSON de Gemini, inicia sesión con `ocx login google-antigravity` y configura -`protocols.rollout.geminiNativeAntigravity` como `true` en el JSON de OpenCodex. Esta opción se +`protocols.rollout.geminiNativeAntigravity` como `true` en el JSON de OpenCodex. También puedes activar la transmisión nativa de Gemini en la pestaña **Cuentas** de Google Antigravity. Esta opción se aplica a las solicitudes de generación Gemini de `/v1beta` que se enrutan al proveedor OAuth canónico `google-antigravity`. Las demás rutas usan el puente de Chat. Consulta [Gemini nativo con Antigravity](/es/reference/proxy-formats/#native-gemini-with-antigravity). diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index ca562c0c91c..ee2ab5c3b83 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1265,7 +1265,8 @@ status warns about organization settings and environment overrides it can see. I OpenCodex process environment. An override set only in the Antigravity process will not appear. On Windows `agy` is untested because Google lists it for macOS and Linux only. -To preserve Gemini JSON, sign in with `ocx login google-antigravity` and set -`protocols.rollout.geminiNativeAntigravity` to `true` in OpenCodex's JSON config. This opt-in +To preserve Gemini JSON, sign in with `ocx login google-antigravity` and turn on **Native Gemini +passthrough** in the Google Antigravity **Accounts** tab. The JSON setting is +`protocols.rollout.geminiNativeAntigravity`. This opt-in applies to `/v1beta` Gemini generation routed to the canonical `google-antigravity` OAuth provider. Other routes use the Chat bridge. See [Native Gemini with Antigravity](/reference/proxy-formats/#native-gemini-with-antigravity). diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 89325cee438..f295441a943 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -1134,7 +1134,8 @@ A repair must decode to a JSON object. Valid JSON values containing those tags a ## Native Gemini with Antigravity Enable the canonical `google-antigravity` provider, sign in with `ocx login google-antigravity`, -and add this optional setting to OpenCodex's JSON config: +then open the Google Antigravity **Accounts** tab and turn on **Native Gemini passthrough**. +The dashboard and JSON config use the same setting: ```json { @@ -1164,6 +1165,9 @@ dashboard's request logs. When a completed response reports token counts, the lo them and computes the end-to-end output rate. For models with a matched official rate, the `~$` column estimates the equivalent Gemini API cost from reported input, output and cache-hit tokens. The amount is an API price reference for Antigravity OAuth sessions. +The log details show the named reasoning tier or explicit thinking control and the first +visible output time for a stream. Decode throughput is estimated from the observed output +window when it includes the reported reasoning output. If an upstream payload contains bound account credentials, the proxy returns a generic Gemini error. A valid upstream `[DONE]` or a Gemini error ends stream delivery. diff --git a/gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx b/gui/src/components/provider-workspace/NativePassthroughSetting.tsx similarity index 58% rename from gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx rename to gui/src/components/provider-workspace/NativePassthroughSetting.tsx index 83f4005c101..c17128e2d08 100644 --- a/gui/src/components/provider-workspace/ClaudeNativePassthroughSetting.tsx +++ b/gui/src/components/provider-workspace/NativePassthroughSetting.tsx @@ -1,23 +1,32 @@ -/** - * Claude Code's native passthrough (`claudeCode.nativePassthrough`, default on), shown under the - * Claude account pool because it decides whether Claude Code's own traffic can reach the pool at - * all: while it is on, a bare Claude id unclaimed by an alias or model map goes straight to - * Anthropic when Claude Code sends its own login. It is one global setting, saved immediately through - * the Claude Code settings patch, which changes only the field it is sent. - */ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { useT } from "../../i18n/shared"; import { isApiTargetCaptureCurrent, targetFetch } from "../../api"; import { useRenderTargetCapture } from "../../use-render-target-capture"; -export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { apiBase: string; targetKey?: string }) { +type NativeProtocol = "claude" | "gemini"; + +function readPassthrough(payload: unknown, protocol: NativeProtocol): boolean | null { + const info = payload as { + nativePassthrough?: unknown; + settings?: { rollout?: { geminiNativeAntigravity?: unknown } }; + } | null; + const value = protocol === "gemini" ? info?.settings?.rollout?.geminiNativeAntigravity : info?.nativePassthrough; + return typeof value === "boolean" ? value : null; +} + +/** A provider account card that saves just its protocol's native passthrough setting. */ +export default function NativePassthroughSetting({ + apiBase, targetKey, protocol, +}: { apiBase: string; targetKey?: string; protocol: NativeProtocol }) { const t = useT(); + const gemini = protocol === "gemini"; + const readPath = gemini ? "/api/protocols" : "/api/claude-code"; + const title = t(gemini ? "pws.geminiNativePassthrough" : "claude.nativePassthrough"); const capture = useRenderTargetCapture(apiBase, targetKey); const [enabled, setEnabled] = useState(null); const [loadFailed, setLoadFailed] = useState(false); const [saving, setSaving] = useState(false); const [saveFailed, setSaveFailed] = useState(false); - // GET /api/claude-code gathers the catalog and can answer 503 while it is busy; Retry reloads. const [reloadVersion, setReloadVersion] = useState(0); const mountedRef = useRef(true); @@ -29,15 +38,16 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { useEffect(() => { let cancelled = false; const ac = new AbortController(); - void targetFetch(capture, `${apiBase}/api/claude-code`, { signal: ac.signal, cache: "no-store" }) + void targetFetch(capture, `${apiBase}${readPath}`, { signal: ac.signal, cache: "no-store" }) .then(response => { if (!response.ok) throw new Error("load"); - return response.json() as Promise<{ nativePassthrough?: unknown }>; + return response.json() as Promise; }) .then(json => { if (cancelled || !isApiTargetCaptureCurrent(capture)) return; - if (typeof json?.nativePassthrough !== "boolean") throw new Error("load"); - setEnabled(json.nativePassthrough); + const saved = readPassthrough(json, protocol); + if (saved === null) throw new Error("load"); + setEnabled(saved); setLoadFailed(false); }) .catch(() => { @@ -49,7 +59,7 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { cancelled = true; ac.abort(); }; - }, [apiBase, capture, reloadVersion]); + }, [apiBase, capture, protocol, readPath, reloadVersion]); const toggle = async () => { if (enabled === null || saving) return; @@ -57,17 +67,20 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { setSaving(true); setSaveFailed(false); try { - const response = await targetFetch(capture, `${apiBase}/api/claude-code`, { - method: "PUT", + const response = await targetFetch(capture, `${apiBase}${gemini ? "/api/protocols/settings" : readPath}`, { + method: gemini ? "PATCH" : "PUT", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ nativePassthrough: requested }), + body: JSON.stringify(gemini + ? { rollout: { geminiNativeAntigravity: requested } } + : { nativePassthrough: requested }), }); if (!mountedRef.current || !isApiTargetCaptureCurrent(capture)) return; if (!response.ok) throw new Error("save"); - const json = await response.json() as { nativePassthrough?: unknown } | null; + const json: unknown = await response.json(); if (!mountedRef.current || !isApiTargetCaptureCurrent(capture)) return; - if (json?.nativePassthrough !== requested) throw new Error("save"); - setEnabled(json.nativePassthrough); + const saved = readPassthrough(json, protocol); + if (saved !== requested) throw new Error("save"); + setEnabled(saved); } catch { if (mountedRef.current && isApiTargetCaptureCurrent(capture)) { setEnabled(null); @@ -81,12 +94,14 @@ export default function ClaudeNativePassthroughSetting({ apiBase, targetKey }: { const loading = enabled === null && !loadFailed; return ( -
+
- {t("claude.nativePassthrough")} + {title}
- {loadFailed ? t("claude.nativePassthroughLoadFailed") : loading ? t("common.loading") : t("claude.nativePassthroughDesc")} + {loadFailed + ? t(gemini ? "pws.geminiNativePassthroughLoadFailed" : "claude.nativePassthroughLoadFailed") + : loading ? t("common.loading") : t(gemini ? "pws.geminiNativePassthroughDesc" : "claude.nativePassthroughDesc")}
diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index b8da7161d05..f4c212d8ef7 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2577,18 +2577,23 @@ export const de: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini-API", "api.modelsEndpoint": "Models API", "api.surface.on": "An", "api.surface.off": "Aus", "api.surface.source.fixed": "Immer bereitgestellt", + "api.surface.source.default": "Standardmäßig aktiv", "api.surface.source.explicit": "Explizite Einstellung", "api.surface.source.inherited": "Von den Claude-Einstellungen übernommen", "api.surface.source.invalid": "Ungültiger Wert — geschlossen", "api.surface.messagesToggle": "Messages API bereitstellen", + "api.surface.geminiToggle": "Gemini-API bereitstellen", "api.surface.messagesCloseNote": "Wenn Messages ausgeschaltet wird, wird auch die Claude-Integration ausgeschaltet, damit eine ältere opencodex-Version den Endpunkt ebenfalls geschlossen hält.", "api.surface.openClaude": "Claude-Einstellungen", "api.surface.toggleFailed": "Die Messages-Einstellung konnte nicht gespeichert werden.", "api.surface.toggleUnavailable": "Diese Proxy-Version kann die Messages API hier nicht ändern. Nutze stattdessen die Claude-Seite.", + "api.surface.geminiToggleFailed": "Die Einstellung für die Gemini-API konnte nicht gespeichert werden.", + "api.surface.geminiToggleUnavailable": "Diese Proxy-Version kann die Gemini-API hier nicht umschalten.", "api.surface.closedNote": "Anfragen an diesen Endpunkt werden mit 403 abgelehnt.", "api.endpointNote": "Nutze die Basis-URL für OpenAI-kompatible Clients. Responses und Chat Completions liegen unter /v1.", "api.endpointsTitle": "Gateway-Endpunkte", @@ -2620,6 +2625,7 @@ export const de: Record = { "api.usageResponsesTitle": "Responses-Beispiel", "api.usageChatTitle": "Chat-Completions-Beispiel", "api.usageMessagesTitle": "Messages-Beispiel", + "api.usageGeminiTitle": "Gemini-Beispiel", "api.testSucceeded": "OK", "api.newKeyTitle": "Neuer Schlüssel erstellt", "api.newKeyNote": "Kopiere diesen Schlüssel jetzt. Später kannst du ihn in der Schlüsselliste per Klick erneut anzeigen.", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index f5bb2b82d99..9b8eec78616 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -3246,18 +3246,23 @@ export const en = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "On", "api.surface.off": "Off", "api.surface.source.fixed": "Always served", + "api.surface.source.default": "On by default", "api.surface.source.explicit": "Explicit setting", "api.surface.source.inherited": "Inherited from Claude settings", "api.surface.source.invalid": "Invalid value — closed", "api.surface.messagesToggle": "Serve the Messages API", + "api.surface.geminiToggle": "Serve the Gemini API", "api.surface.messagesCloseNote": "Turning Messages off also turns off the Claude integration, so an older opencodex version keeps the endpoint closed too.", "api.surface.openClaude": "Claude settings", "api.surface.toggleFailed": "The Messages setting could not be saved.", "api.surface.toggleUnavailable": "This proxy version cannot change the Messages API here. Use the Claude page instead.", + "api.surface.geminiToggleFailed": "The Gemini API setting could not be saved.", + "api.surface.geminiToggleUnavailable": "This proxy version cannot change the Gemini API here.", "api.surface.closedNote": "Requests to this endpoint are refused with 403.", "api.endpointNote": "Use the base URL with OpenAI-compatible clients. Responses and Chat Completions are exposed under /v1.", "api.endpointsTitle": "Endpoints", @@ -3376,6 +3381,7 @@ export const en = { "api.usageChatTitle": "Chat Completions example", "api.usageResponsesTitle": "Responses example", "api.usageMessagesTitle": "Messages example", + "api.usageGeminiTitle": "Gemini example", "api.usageSampleInput": "Hello, world!", "api.clientConfig.title": "Client config", "api.clientConfig.rowsLabel": "Connect a client", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index eca34fd4a05..1a482c16abb 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -3162,18 +3162,23 @@ export const fr: Record = { "api.responsesEndpoint": "API Responses", "api.chatCompletionsEndpoint": "API Chat Completions", "api.messagesEndpoint": "API Messages", + "api.geminiEndpoint": "API Gemini", "api.modelsEndpoint": "API des modèles", "api.surface.on": "Activé", "api.surface.off": "Désactivé", "api.surface.source.fixed": "Toujours servi", + "api.surface.source.default": "Activée par défaut", "api.surface.source.explicit": "Réglage explicite", "api.surface.source.inherited": "Hérité des réglages Claude", "api.surface.source.invalid": "Valeur invalide — fermé", "api.surface.messagesToggle": "Servir l’API Messages", + "api.surface.geminiToggle": "Activer l’API Gemini", "api.surface.messagesCloseNote": "Désactiver Messages désactive aussi l’intégration Claude, afin qu’une version plus ancienne d’opencodex garde également le point de terminaison fermé.", "api.surface.openClaude": "Réglages Claude", "api.surface.toggleFailed": "Le réglage Messages n’a pas pu être enregistré.", "api.surface.toggleUnavailable": "Cette version du proxy ne peut pas modifier l’API Messages ici. Utilisez plutôt la page Claude.", + "api.surface.geminiToggleFailed": "Le réglage de l’API Gemini n’a pas pu être enregistré.", + "api.surface.geminiToggleUnavailable": "Cette version du proxy ne permet pas de modifier l’API Gemini ici.", "api.surface.closedNote": "Les requêtes vers ce point de terminaison sont refusées avec 403.", "api.endpointNote": "Utilisez l’URL de base avec les clients compatibles avec OpenAI. Responses et Chat Completions sont accessibles sous /v1.", "api.endpointsTitle": "Points de terminaison", @@ -3292,6 +3297,7 @@ export const fr: Record = { "api.usageChatTitle": "Exemple Chat Completions", "api.usageResponsesTitle": "Exemple Responses", "api.usageMessagesTitle": "Exemple Messages", + "api.usageGeminiTitle": "Exemple Gemini", "api.usageSampleInput": "Bonjour tout le monde!", "api.clientConfig.title": "Configuration du client", "api.clientConfig.rowsLabel": "Connecter un client", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 91098e01e41..9cacc05f7fc 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -3064,18 +3064,23 @@ export const ja: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "オン", "api.surface.off": "オフ", "api.surface.source.fixed": "常に提供", + "api.surface.source.default": "既定で有効", "api.surface.source.explicit": "明示的な設定", "api.surface.source.inherited": "Claude 設定から継承", "api.surface.source.invalid": "無効な値 — 閉鎖", "api.surface.messagesToggle": "Messages API を提供する", + "api.surface.geminiToggle": "Gemini API を提供", "api.surface.messagesCloseNote": "Messages をオフにすると Claude 連携もオフになるため、古い opencodex バージョンでもエンドポイントは閉じたままになります。", "api.surface.openClaude": "Claude 設定", "api.surface.toggleFailed": "Messages の設定を保存できませんでした。", "api.surface.toggleUnavailable": "このプロキシのバージョンではここで Messages API を変更できません。Claude ページを使ってください。", + "api.surface.geminiToggleFailed": "Gemini API の設定を保存できませんでした。", + "api.surface.geminiToggleUnavailable": "このバージョンのプロキシではここから Gemini API を切り替えられません。", "api.surface.closedNote": "このエンドポイントへのリクエストは 403 で拒否されます。", "api.authTitle": "認証", "api.authBaseUrlNote": "クライアントにはベース URL を設定し、下のプロトコル別エンドポイントを選んでください。", @@ -3106,6 +3111,7 @@ export const ja: Record = { "api.usageResponsesTitle": "Responses の例", "api.usageChatTitle": "Chat Completions の例", "api.usageMessagesTitle": "Messages の例", + "api.usageGeminiTitle": "Gemini の例", "api.newKeyTitle": "新しいキーを作成しました", "api.newKeyNote": "今すぐこのキーをコピーしてください。後からでもキー一覧でキーをクリックすると再表示できます。", "api.copy": "コピー", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 6ac168528b8..4da14c7291a 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -2625,18 +2625,23 @@ export const ko: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "켜짐", "api.surface.off": "꺼짐", "api.surface.source.fixed": "항상 제공", + "api.surface.source.default": "기본적으로 켜짐", "api.surface.source.explicit": "명시적 설정", "api.surface.source.inherited": "Claude 설정에서 상속", "api.surface.source.invalid": "잘못된 값 — 닫힘", "api.surface.messagesToggle": "Messages API 제공", + "api.surface.geminiToggle": "Gemini API 제공", "api.surface.messagesCloseNote": "Messages를 끄면 Claude 연동도 함께 꺼지므로, 이전 opencodex 버전에서도 엔드포인트가 닫힌 채로 유지됩니다.", "api.surface.openClaude": "Claude 설정", "api.surface.toggleFailed": "Messages 설정을 저장하지 못했습니다.", "api.surface.toggleUnavailable": "이 프록시 버전에서는 여기서 Messages API를 바꿀 수 없습니다. Claude 페이지를 사용하세요.", + "api.surface.geminiToggleFailed": "Gemini API 설정을 저장하지 못했습니다.", + "api.surface.geminiToggleUnavailable": "이 프록시 버전에서는 여기서 Gemini API를 변경할 수 없습니다.", "api.surface.closedNote": "이 엔드포인트로 오는 요청은 403으로 거부됩니다.", "api.endpointsTitle": "게이트웨이 엔드포인트", "api.authBaseUrlNote": "클라이언트에는 기본 URL을 설정한 뒤 아래에서 프로토콜별 엔드포인트를 선택하세요.", @@ -2668,6 +2673,7 @@ export const ko: Record = { "api.usageResponsesTitle": "Responses 예시", "api.usageChatTitle": "Chat Completions 예시", "api.usageMessagesTitle": "Messages 예시", + "api.usageGeminiTitle": "Gemini 예제", "api.newKeyTitle": "새 키 생성됨", "api.newKeyNote": "지금 키를 복사하세요. 나중에도 키 목록에서 키를 클릭하면 다시 볼 수 있습니다.", "api.copy": "복사", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 0aded6b5acc..d9f9cd08761 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -3203,18 +3203,23 @@ export const pt: Record = { "api.responsesEndpoint": "API Responses", "api.chatCompletionsEndpoint": "API Chat Completions", "api.messagesEndpoint": "API Messages", + "api.geminiEndpoint": "API Gemini", "api.modelsEndpoint": "API Models", "api.surface.on": "Ativado", "api.surface.off": "Desativado", "api.surface.source.fixed": "Sempre disponível", + "api.surface.source.default": "Ativada por padrão", "api.surface.source.explicit": "Configuração explícita", "api.surface.source.inherited": "Herdado das configurações do Claude", "api.surface.source.invalid": "Valor inválido — fechado", "api.surface.messagesToggle": "Disponibilizar a API Messages", + "api.surface.geminiToggle": "Disponibilizar a API Gemini", "api.surface.messagesCloseNote": "Desativar o Messages também desativa a integração com o Claude, para que uma versão mais antiga do opencodex mantenha o endpoint fechado também.", "api.surface.openClaude": "Configurações do Claude", "api.surface.toggleFailed": "Não foi possível salvar a configuração do Messages.", "api.surface.toggleUnavailable": "Esta versão do proxy não permite alterar a API Messages aqui. Use a página do Claude.", + "api.surface.geminiToggleFailed": "Não foi possível salvar a configuração da API Gemini.", + "api.surface.geminiToggleUnavailable": "Esta versão do proxy não permite alterar a API Gemini aqui.", "api.surface.closedNote": "As requisições a este endpoint são recusadas com 403.", "api.endpointNote": "Use a URL base com clientes compatíveis com OpenAI. Responses e Chat Completions são expostos em /v1.", "api.endpointsTitle": "Endpoints", @@ -3333,6 +3338,7 @@ export const pt: Record = { "api.usageChatTitle": "Exemplo de Chat Completions", "api.usageResponsesTitle": "Exemplo de Responses", "api.usageMessagesTitle": "Exemplo de Messages", + "api.usageGeminiTitle": "Exemplo do Gemini", "api.usageSampleInput": "Olá, mundo!", "api.clientConfig.title": "Configuração do cliente", "api.clientConfig.rowsLabel": "Conectar um cliente", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index a87610e9216..1bf83b84cd6 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -3154,18 +3154,23 @@ export const ru: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "API Gemini", "api.modelsEndpoint": "Models API", "api.surface.on": "Вкл.", "api.surface.off": "Выкл.", "api.surface.source.fixed": "Доступен всегда", + "api.surface.source.default": "Включено по умолчанию", "api.surface.source.explicit": "Явная настройка", "api.surface.source.inherited": "Унаследовано из настроек Claude", "api.surface.source.invalid": "Недопустимое значение — закрыто", "api.surface.messagesToggle": "Предоставлять Messages API", + "api.surface.geminiToggle": "Предоставлять API Gemini", "api.surface.messagesCloseNote": "Отключение Messages также отключает интеграцию Claude, чтобы более старая версия opencodex тоже держала эту конечную точку закрытой.", "api.surface.openClaude": "Настройки Claude", "api.surface.toggleFailed": "Не удалось сохранить настройку Messages.", "api.surface.toggleUnavailable": "Эта версия прокси не может изменить Messages API здесь. Используйте страницу Claude.", + "api.surface.geminiToggleFailed": "Не удалось сохранить настройку API Gemini.", + "api.surface.geminiToggleUnavailable": "В этой версии прокси настройка API Gemini здесь недоступна.", "api.surface.closedNote": "Запросы к этой конечной точке отклоняются с кодом 403.", "api.endpointsTitle": "Конечные точки", "api.authTitle": "Аутентификация", @@ -3197,6 +3202,7 @@ export const ru: Record = { "api.usageResponsesTitle": "Пример Responses", "api.usageChatTitle": "Пример Chat Completions", "api.usageMessagesTitle": "Пример Messages", + "api.usageGeminiTitle": "Пример Gemini", "api.newKeyTitle": "Создан новый ключ", "api.newKeyNote": "Скопируйте ключ сейчас. Позже его можно снова показать, нажав на него в списке ключей.", "api.copy": "Копировать", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 7a60e333f17..63b5094bfaf 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -3181,18 +3181,23 @@ export const tr: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "Açık", "api.surface.off": "Kapalı", "api.surface.source.fixed": "Her zaman sunulur", + "api.surface.source.default": "Varsayılan olarak açık", "api.surface.source.explicit": "Açık ayar", "api.surface.source.inherited": "Claude ayarlarından devralındı", "api.surface.source.invalid": "Geçersiz değer — kapalı", "api.surface.messagesToggle": "Messages API'yi sun", + "api.surface.geminiToggle": "Gemini API’yi sun", "api.surface.messagesCloseNote": "Messages kapatıldığında Claude entegrasyonu da kapanır; böylece eski bir opencodex sürümü de uç noktayı kapalı tutar.", "api.surface.openClaude": "Claude ayarları", "api.surface.toggleFailed": "Messages ayarı kaydedilemedi.", "api.surface.toggleUnavailable": "Bu proxy sürümü Messages API'yi burada değiştiremez. Bunun yerine Claude sayfasını kullanın.", + "api.surface.geminiToggleFailed": "Gemini API ayarı kaydedilemedi.", + "api.surface.geminiToggleUnavailable": "Bu proxy sürümü Gemini API ayarını buradan değiştiremez.", "api.surface.closedNote": "Bu uç noktaya gelen istekler 403 ile reddedilir.", "api.endpointNote": "OpenAI uyumlu istemcilerle taban URL'yi kullanın.", "api.endpointsTitle": "Uç noktalar", @@ -3311,6 +3316,7 @@ export const tr: Record = { "api.usageChatTitle": "Chat Completions örneği", "api.usageResponsesTitle": "Responses örneği", "api.usageMessagesTitle": "Messages örneği", + "api.usageGeminiTitle": "Gemini örneği", "api.usageSampleInput": "Merhaba dünya!", "api.clientConfig.title": "İstemci konfigürasyonu", "api.clientConfig.rowsLabel": "Bir istemci bağlayın", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 5980f0dd541..6288c9731cb 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -3173,18 +3173,23 @@ export const vi: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "API Gemini", "api.modelsEndpoint": "Models API", "api.surface.on": "Bật", "api.surface.off": "Tắt", "api.surface.source.fixed": "Luôn phục vụ", + "api.surface.source.default": "Bật theo mặc định", "api.surface.source.explicit": "Thiết lập tường minh", "api.surface.source.inherited": "Kế thừa từ cài đặt Claude", "api.surface.source.invalid": "Giá trị không hợp lệ — đã đóng", "api.surface.messagesToggle": "Phục vụ Messages API", + "api.surface.geminiToggle": "Cung cấp API Gemini", "api.surface.messagesCloseNote": "Tắt Messages cũng tắt tích hợp Claude, để phiên bản opencodex cũ hơn cũng giữ endpoint này đóng.", "api.surface.openClaude": "Cài đặt Claude", "api.surface.toggleFailed": "Không lưu được thiết lập Messages.", "api.surface.toggleUnavailable": "Phiên bản proxy này không thể đổi Messages API tại đây. Hãy dùng trang Claude.", + "api.surface.geminiToggleFailed": "Không thể lưu cài đặt API Gemini.", + "api.surface.geminiToggleUnavailable": "Phiên bản proxy này không thể thay đổi API Gemini tại đây.", "api.surface.closedNote": "Yêu cầu tới endpoint này bị từ chối với mã 403.", "api.endpointNote": "Dùng URL cơ sở cho các ứng dụng hỗ trợ OpenAI tương thích. Responses và Chat Completions được đặt ở /v1.", "api.endpointsTitle": "Endpoints", @@ -3303,6 +3308,7 @@ export const vi: Record = { "api.usageChatTitle": "Ví dụ Chat Completions", "api.usageResponsesTitle": "Ví dụ Responses", "api.usageMessagesTitle": "Ví dụ Messages", + "api.usageGeminiTitle": "Ví dụ Gemini", "api.usageSampleInput": "Xin chào, thế giới!", "api.clientConfig.title": "Cấu hình Client", "api.clientConfig.rowsLabel": "Kết nối một client", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 5772753f4aa..9bd31621879 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2439,18 +2439,23 @@ export const zhTW: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "開啟", "api.surface.off": "關閉", "api.surface.source.fixed": "一律提供", + "api.surface.source.default": "預設開啟", "api.surface.source.explicit": "明確設定", "api.surface.source.inherited": "繼承自 Claude 設定", "api.surface.source.invalid": "無效值 — 已關閉", "api.surface.messagesToggle": "提供 Messages API", + "api.surface.geminiToggle": "提供 Gemini API", "api.surface.messagesCloseNote": "關閉 Messages 也會關閉 Claude 整合,讓舊版 opencodex 也保持此端點關閉。", "api.surface.openClaude": "Claude 設定", "api.surface.toggleFailed": "無法儲存 Messages 設定。", "api.surface.toggleUnavailable": "此代理版本無法在這裡變更 Messages API,請改用 Claude 頁面。", + "api.surface.geminiToggleFailed": "無法儲存 Gemini API 設定。", + "api.surface.geminiToggleUnavailable": "此代理版本無法在此切換 Gemini API。", "api.surface.closedNote": "對此端點的請求會以 403 拒絕。", "api.endpointNote": "請將基礎 URL 用於 OpenAI 相容客戶端。Responses 與 Chat Completions 在 /v1 下提供。", "api.endpointsTitle": "閘道器端點", @@ -2510,6 +2515,7 @@ export const zhTW: Record = { "api.usageChatTitle": "Chat Completions 範例", "api.usageResponsesTitle": "Responses 範例", "api.usageMessagesTitle": "Messages 範例", + "api.usageGeminiTitle": "Gemini 範例", "api.usageSampleInput": "你好,世界!", "api.keysLoadFailed": "無法載入 API 金鑰。", "api.createFailed": "無法建立 API 金鑰。", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 5885bc91897..3f4fec050b6 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2598,18 +2598,23 @@ export const zh: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "Gemini API", "api.modelsEndpoint": "Models API", "api.surface.on": "开启", "api.surface.off": "关闭", "api.surface.source.fixed": "始终提供", + "api.surface.source.default": "默认开启", "api.surface.source.explicit": "显式设置", "api.surface.source.inherited": "继承自 Claude 设置", "api.surface.source.invalid": "无效值 — 已关闭", "api.surface.messagesToggle": "提供 Messages API", + "api.surface.geminiToggle": "提供 Gemini API", "api.surface.messagesCloseNote": "关闭 Messages 也会关闭 Claude 集成,这样旧版 opencodex 也会保持该端点关闭。", "api.surface.openClaude": "Claude 设置", "api.surface.toggleFailed": "无法保存 Messages 设置。", "api.surface.toggleUnavailable": "此代理版本无法在这里更改 Messages API,请改用 Claude 页面。", + "api.surface.geminiToggleFailed": "无法保存 Gemini API 设置。", + "api.surface.geminiToggleUnavailable": "此代理版本无法在此切换 Gemini API。", "api.surface.closedNote": "对该端点的请求会以 403 拒绝。", "api.endpointsTitle": "网关端点", "api.authBaseUrlNote": "客户端应使用基础 URL,然后选择下面的协议端点。", @@ -2641,6 +2646,7 @@ export const zh: Record = { "api.usageResponsesTitle": "Responses 示例", "api.usageChatTitle": "Chat Completions 示例", "api.usageMessagesTitle": "Messages 示例", + "api.usageGeminiTitle": "Gemini 示例", "api.newKeyTitle": "已创建新密钥", "api.newKeyNote": "请立即复制此密钥。之后也可以在密钥列表中点击它再次显示。", "api.copy": "复制", diff --git a/gui/src/pages/ApiKeys.tsx b/gui/src/pages/ApiKeys.tsx index d7496433ebd..1fd13f7d695 100644 --- a/gui/src/pages/ApiKeys.tsx +++ b/gui/src/pages/ApiKeys.tsx @@ -49,6 +49,7 @@ interface KeysResponse extends UsageReadMetadata { chatCompletionsEndpoint?: string; messagesEndpoint?: string; modelsEndpoint?: string; + geminiModelsEndpoint?: string; claudeCodeEnabled?: boolean; surfaces?: unknown; audio?: unknown; @@ -188,6 +189,8 @@ export default function ApiKeys({ apiBase, active = true }: { apiBase: string; a chatCompletions: data.chatCompletionsEndpoint ?? derived.chatCompletions, messages: data.messagesEndpoint ?? derived.messages, models: data.modelsEndpoint ?? derived.models, + ...(typeof data.geminiModelsEndpoint === "string" && data.geminiModelsEndpoint + ? { geminiModels: data.geminiModelsEndpoint } : {}), ...(isAudioApiInfo(data.audio, data.baseUrl ?? derived.baseUrl) ? { audio: data.audio } : {}), }, claudeCodeEnabled: data.claudeCodeEnabled !== false, diff --git a/gui/src/pages/api-keys-endpoints-panel.tsx b/gui/src/pages/api-keys-endpoints-panel.tsx index d065f8d568a..4e998691651 100644 --- a/gui/src/pages/api-keys-endpoints-panel.tsx +++ b/gui/src/pages/api-keys-endpoints-panel.tsx @@ -30,7 +30,7 @@ export function ApiKeysEndpointsPanel({ authMatrix: ApiAuthMatrixRow[]; /** Absent from a server that predates API surface settings; the flat list is kept then. */ surfaces?: ApiSurfacesInfo; - /** Management origin the Messages toggle writes to (this machine or the shared hub). */ + /** Management origin the surface toggles write to (this machine or the shared hub). */ apiBase?: string; onSurfacesChanged?: () => void; }) { diff --git a/gui/src/pages/api-keys-panels.tsx b/gui/src/pages/api-keys-panels.tsx index 661dd006e4c..8ef2e6411a6 100644 --- a/gui/src/pages/api-keys-panels.tsx +++ b/gui/src/pages/api-keys-panels.tsx @@ -308,9 +308,11 @@ export function ApiKeysModelsPanel({ export function ApiKeysUsagePanel({ endpoints, claudeCodeEnabled, + geminiEnabled = false, }: { endpoints: ApiEndpointInfo; claudeCodeEnabled: boolean; + geminiEnabled?: boolean; }) { const { t } = useI18n(); const sampleInput = JSON.stringify(t("api.usageSampleInput")); @@ -340,6 +342,14 @@ export function ApiKeysUsagePanel({ "messages": [{"role": "user", "content": ${sampleInput}}] }'`; + const geminiModelAction = "google-antigravity/gemini-3.8-flash:generateContent"; + const geminiExample = `curl ${endpoints.geminiModels}/${geminiModelAction} \\ + -H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\ + -H "Content-Type: application/json" \\ + -d '{ + "contents": [{"role": "user", "parts": [{"text": ${sampleInput}}]}] + }'`; + return ( // Not a disclosure. These are the answer to "how do I call this?", and a // closed
answered it only for someone who already suspected the @@ -363,6 +373,12 @@ export function ApiKeysUsagePanel({
)} + {geminiEnabled && endpoints.geminiModels && ( +
+

{t("api.usageGeminiTitle")}

+ +
+ )}
); diff --git a/gui/src/pages/api-keys-utils.ts b/gui/src/pages/api-keys-utils.ts index 3a5fe54f044..e0d30fbde35 100644 --- a/gui/src/pages/api-keys-utils.ts +++ b/gui/src/pages/api-keys-utils.ts @@ -75,14 +75,14 @@ export function isApiAuthMatrix(value: unknown): value is ApiAuthMatrixRow[] { export const API_KEY_NAME_MAX_LENGTH = 64; /** Who decided a surface's state; mirrors `ApiSurfaceSource` in src/protocols/settings.ts. */ -export type ApiSurfaceSource = "fixed" | "api-surfaces" | "claude-code-legacy" | "invalid"; +export type ApiSurfaceSource = "fixed" | "default" | "api-surfaces" | "claude-code-legacy" | "invalid"; export interface ApiSurfaceInfo { enabled: boolean; source: ApiSurfaceSource; } -export type ApiSurfacesInfo = Record; +export type ApiSurfacesInfo = Record & { gemini?: ApiSurfaceInfo }; -const SURFACE_SOURCES = new Set(["fixed", "api-surfaces", "claude-code-legacy", "invalid"]); +const SURFACE_SOURCES = new Set(["fixed", "default", "api-surfaces", "claude-code-legacy", "invalid"]); const SURFACE_NAMES = ["responses", "chat", "messages"] as const satisfies readonly GatewayInboundProtocol[]; /** @@ -93,8 +93,9 @@ export function parseApiSurfaces(value: unknown): ApiSurfacesInfo | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; const record = value as Record; const surfaces = {} as ApiSurfacesInfo; - for (const name of SURFACE_NAMES) { + for (const name of [...SURFACE_NAMES, "gemini"] as const) { const surface = record[name]; + if (name === "gemini" && surface === undefined) continue; if (!surface || typeof surface !== "object" || Array.isArray(surface)) return undefined; const { enabled, source } = surface as Record; if (typeof enabled !== "boolean" || !SURFACE_SOURCES.has(source as ApiSurfaceSource)) return undefined; @@ -109,6 +110,7 @@ export interface ApiEndpointInfo { chatCompletions: string; messages: string; models: string; + geminiModels?: string; audio?: AudioApiInfo; } diff --git a/gui/src/pages/api-surface-cards.tsx b/gui/src/pages/api-surface-cards.tsx index 430791aacd8..a4eb4a7d611 100644 --- a/gui/src/pages/api-surface-cards.tsx +++ b/gui/src/pages/api-surface-cards.tsx @@ -1,19 +1,13 @@ /** - * One card per public API (Responses, Chat Completions, Messages): whether it is served, where - * it lives, and who decided that. The server resolves every state - * (`resolveApiSurfaceSettings`); this component only names it. - * - * Messages is the one switchable surface. Its card stays visible while closed, so the operator - * can see the endpoint that is being refused and reopen it. The toggle writes through - * `PATCH /api/protocols/settings` on the target `apiBase` names, then asks the page to reload - * the keys payload rather than predicting the new state. + * Gateway endpoint cards show the state reported by the server. Closed APIs stay visible so + * the operator can reopen them. Toggles patch protocol settings on the selected target and + * reload the keys payload. */ import { useState } from "react"; import { Notice, Switch } from "../ui"; import { useI18n, type TKey } from "../i18n/shared"; import { navigateHash } from "../hash-routing"; import { patchProtocolSettings } from "../protocol-api"; -import type { GatewayInboundProtocol } from "../api-access-models"; import type { ApiEndpointInfo, ApiSurfaceInfo, ApiSurfaceSource, ApiSurfacesInfo } from "./api-keys-utils"; import { EndpointUrl } from "./api-keys-copy"; @@ -21,18 +15,26 @@ const CLAUDE_HASH = "claude/code"; const SOURCE_KEYS: Record = { fixed: "api.surface.source.fixed", + default: "api.surface.source.default", "api-surfaces": "api.surface.source.explicit", "claude-code-legacy": "api.surface.source.inherited", invalid: "api.surface.source.invalid", }; -const CARDS: ReadonlyArray<{ id: GatewayInboundProtocol; titleKey: TKey; url: (endpoints: ApiEndpointInfo) => string }> = [ +const CARDS: ReadonlyArray<{ id: keyof ApiSurfacesInfo; titleKey: TKey; url: (endpoints: ApiEndpointInfo) => string | undefined }> = [ { id: "responses", titleKey: "api.responsesEndpoint", url: endpoints => endpoints.responses }, { id: "chat", titleKey: "api.chatCompletionsEndpoint", url: endpoints => endpoints.chatCompletions }, { id: "messages", titleKey: "api.messagesEndpoint", url: endpoints => endpoints.messages }, + { id: "gemini", titleKey: "api.geminiEndpoint", url: endpoints => endpoints.geminiModels }, ]; -type ToggleError = "failed" | "unavailable" | null; +const TOGGLES = { + messages: { label: "api.surface.messagesToggle", failed: "api.surface.toggleFailed", unavailable: "api.surface.toggleUnavailable" }, + gemini: { label: "api.surface.geminiToggle", failed: "api.surface.geminiToggleFailed", unavailable: "api.surface.geminiToggleUnavailable" }, +} as const satisfies Record; + +type SwitchableSurface = keyof typeof TOGGLES; +type ToggleError = { surface: SwitchableSurface; kind: "failed" | "unavailable" }; export function ApiSurfaceCards({ apiBase, @@ -47,16 +49,18 @@ export function ApiSurfaceCards({ }) { const { t } = useI18n(); const [pending, setPending] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); - const toggleMessages = async (messages: ApiSurfaceInfo) => { + const toggleSurface = async (id: SwitchableSurface, surface: ApiSurfaceInfo) => { if (pending) return; setPending(true); setError(null); try { - const result = await patchProtocolSettings(apiBase, { messagesEnabled: !messages.enabled }); + const result = await patchProtocolSettings(apiBase, id === "messages" + ? { messagesEnabled: !surface.enabled } + : { geminiEnabled: !surface.enabled }); if (result.kind === "ok") onChanged(); - else setError(result.kind === "unavailable" ? "unavailable" : "failed"); + else setError({ surface: id, kind: result.kind === "unavailable" ? "unavailable" : "failed" }); } finally { setPending(false); } @@ -66,6 +70,10 @@ export function ApiSurfaceCards({
{CARDS.map(card => { const surface = surfaces[card.id]; + const url = card.url(endpoints); + if (!surface || !url) return null; + const switchable = card.id === "messages" || card.id === "gemini" ? card.id : undefined; + const toggle = switchable && TOGGLES[switchable]; const stateLabel = surface.enabled ? t("api.surface.on") : t("api.surface.off"); return (
{t(card.titleKey)} - {card.id === "messages" ? ( + {switchable && toggle ? ( { void toggleMessages(surface); }} - label={`${t("api.surface.messagesToggle")}: ${stateLabel}`} + onClick={() => { void toggleSurface(switchable, surface); }} + label={`${t(toggle.label)}: ${stateLabel}`} /> ) : null} {stateLabel}
- + {t(SOURCE_KEYS[surface.source])} + {toggle && !surface.enabled ? {t("api.surface.closedNote")} : null} {card.id === "messages" ? ( <> - {!surface.enabled ? {t("api.surface.closedNote")} : null} {surface.enabled ? {t("api.surface.messagesCloseNote")} : null} - {error ? ( - {t(error === "unavailable" ? "api.surface.toggleUnavailable" : "api.surface.toggleFailed")} - ) : null} ) : null} + {toggle && error?.surface === card.id ? {t(toggle[error.kind])} : null}
); })} diff --git a/gui/src/protocol-api.ts b/gui/src/protocol-api.ts index 0e906520741..81f971bd7b3 100644 --- a/gui/src/protocol-api.ts +++ b/gui/src/protocol-api.ts @@ -119,6 +119,7 @@ export async function fetchProtocolPlan( export interface ProtocolSettingsPatchBody { messagesEnabled?: boolean; + geminiEnabled?: boolean; } export type ProtocolSettingsPatchResult = diff --git a/gui/src/styles-apikeys-workspace.css b/gui/src/styles-apikeys-workspace.css index 9a36acfb2b5..7c67ff70a09 100644 --- a/gui/src/styles-apikeys-workspace.css +++ b/gui/src/styles-apikeys-workspace.css @@ -1003,7 +1003,7 @@ /* API surface cards (PF-04): one card per public API. Inherits the endpoint URL styling from .api-endpoints; a closed surface stays visible, dimmed rather than hidden. */ .api-endpoints.api-surface-cards { - grid-template-columns: repeat(3, minmax(0, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); } .api-surface-card { padding: var(--space-3); diff --git a/gui/tests/api-surface-cards.test.tsx b/gui/tests/api-surface-cards.test.tsx index 0ea6bc19849..3ba3d004d7d 100644 --- a/gui/tests/api-surface-cards.test.tsx +++ b/gui/tests/api-surface-cards.test.tsx @@ -4,6 +4,7 @@ import { act } from "react"; import type { Root } from "react-dom/client"; import { LanguageProvider } from "../src/i18n/provider"; import { DICTS } from "../src/i18n/shared"; +import { ApiKeysUsagePanel } from "../src/pages/api-keys-panels"; import { ApiKeysEndpointsPanel } from "../src/pages/api-keys-endpoints-panel"; import { parseApiSurfaces, type ApiSurfacesInfo } from "../src/pages/api-keys-utils"; import { patchProtocolSettings } from "../src/protocol-api"; @@ -20,6 +21,7 @@ const endpoints = { chatCompletions: "http://127.0.0.1:10100/v1/chat/completions", messages: "http://127.0.0.1:10100/v1/messages", models: "http://127.0.0.1:10100/v1/models", + geminiModels: "http://127.0.0.1:10100/v1beta/models", }; const authMatrix = [{ endpoint: "/v1/responses", bearer: "rejected" as const, dedicated: "required" as const, xApiKey: "rejected" as const }]; @@ -150,6 +152,28 @@ describe("API surface cards", () => { await act(async () => root.unmount()); }); + test("Gemini keeps its own card and patches only its setting on the selected gateway", async () => { + const calls: Array<{ url: string; method?: string; body: string }> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + calls.push({ url: String(input), method: init?.method, body: String(init?.body) }); + return Response.json({ ...INFO, geminiSurface: { enabled: true, source: "api-surfaces" } }); + }) as typeof fetch; + const remote = parseApiSurfaces({ ...INFO.surfaces, gemini: { enabled: false, source: "api-surfaces" } }); + let changed = 0; + const { root, container } = await mount({ + surfaces: remote, + apiBase: "http://hub.example:10100", + onSurfacesChanged: () => { changed++; }, + }); + const card = container.querySelector('[data-surface="gemini"]')!; + expect(card.textContent).toContain(endpoints.geminiModels); + expect(card.textContent).toContain(en["api.surface.closedNote"]); + await act(async () => { card.querySelector(".switch")!.click(); }); + expect(calls).toEqual([{ url: "http://hub.example:10100/api/protocols/settings", method: "PATCH", body: JSON.stringify({ geminiEnabled: true }) }]); + expect(changed).toBe(1); + await act(async () => root.unmount()); + }); + test("a failed toggle says so and does not reload", async () => { globalThis.fetch = (async () => new Response(JSON.stringify({ error: { code: "write_failed" } }), { status: 500 })) as unknown as typeof fetch; let changed = 0; @@ -165,6 +189,25 @@ describe("API surface cards", () => { }); }); +test("the Gemini example follows the API switch and uses the advertised models URL", async () => { + const { root, container } = await mount({}); + const render = (geminiEnabled: boolean) => act(async () => { + root.render( + + + , + ); + }); + await render(true); + expect(container.textContent).toContain(en["api.usageGeminiTitle"]); + expect(container.textContent).toContain(`${endpoints.geminiModels}/google-antigravity/gemini-3.8-flash:generateContent`); + expect(container.textContent).toContain('"parts": [{"text":'); + await render(false); + expect(container.textContent).not.toContain(en["api.usageGeminiTitle"]); + expect(container.textContent).toContain(en["api.usageMessagesTitle"]); + await act(async () => root.unmount()); +}); + describe("patchProtocolSettings", () => { test("an older server without the route reads as unavailable", async () => { globalThis.fetch = (async () => new Response("{}", { status: 404 })) as unknown as typeof fetch; diff --git a/src/protocols/settings.ts b/src/protocols/settings.ts index 670a5b7b55b..b963912649d 100644 --- a/src/protocols/settings.ts +++ b/src/protocols/settings.ts @@ -13,6 +13,8 @@ import type { Protocol } from "./contract"; export type ApiSurfaceSource = /** Responses and Chat Completions: always served. */ | "fixed" + /** Gemini: open when no setting is supplied. */ + | "default" /** An explicit boolean in `apiSurfaces`. */ | "api-surfaces" /** No explicit value; inherited from `claudeCode.enabled`. */ @@ -32,28 +34,30 @@ function isRec(value: unknown): value is Rec { return !!value && typeof value === "object" && !Array.isArray(value); } -function resolveMessagesSurface(config: Pick): ApiSurfaceSetting { - const raw: unknown = config.apiSurfaces; - if (raw !== undefined) { - if (!isRec(raw)) return { enabled: false, source: "invalid" }; - const messages = raw.messages; - if (messages !== undefined) { - if (!isRec(messages)) return { enabled: false, source: "invalid" }; - if (Object.hasOwn(messages, "enabled")) { - return typeof messages.enabled === "boolean" - ? { enabled: messages.enabled, source: "api-surfaces" } - : { enabled: false, source: "invalid" }; - } - } - } - return { enabled: config.claudeCode?.enabled !== false, source: "claude-code-legacy" }; +function resolveOptionalSurface(raw: unknown, name: "messages" | "gemini", fallback: ApiSurfaceSetting): ApiSurfaceSetting { + if (raw === undefined) return fallback; + if (!isRec(raw)) return { enabled: false, source: "invalid" }; + const surface = raw[name]; + if (surface === undefined) return fallback; + if (!isRec(surface)) return { enabled: false, source: "invalid" }; + if (!Object.hasOwn(surface, "enabled")) return fallback; + return typeof surface.enabled === "boolean" + ? { enabled: surface.enabled, source: "api-surfaces" } + : { enabled: false, source: "invalid" }; +} + +export function resolveGeminiApiSurface(config: Pick): ApiSurfaceSetting { + return resolveOptionalSurface(config.apiSurfaces, "gemini", { enabled: true, source: "default" }); } export function resolveApiSurfaceSettings(config: Pick): ApiSurfaceSettings { return Object.freeze({ responses: Object.freeze({ enabled: true, source: "fixed" as const }), chat: Object.freeze({ enabled: true, source: "fixed" as const }), - messages: Object.freeze(resolveMessagesSurface(config)), + messages: Object.freeze(resolveOptionalSurface(config.apiSurfaces, "messages", { + enabled: config.claudeCode?.enabled !== false, + source: "claude-code-legacy", + })), }); } diff --git a/src/server/index/gemini-routes.ts b/src/server/index/gemini-routes.ts index d840502e6e6..357fa2b536f 100644 --- a/src/server/index/gemini-routes.ts +++ b/src/server/index/gemini-routes.ts @@ -15,6 +15,7 @@ import { SIDECAR_INTERNAL_CAPABILITY_HEADER } from "../advisor-admission-scope"; import { withCallerSessionIdentity } from "../caller-session-identity"; import { captureAdmissionPolicy } from "../capture-admission-policy"; import { isDraining } from "../lifecycle"; +import { resolveGeminiApiSurface } from "../../protocols/settings"; import { geminiRouteAllowHeader, geminiRouteAllows, parseGeminiNativePath, type GeminiNativeRoute } from "../gemini-native-paths"; import { geminiError, handleGeminiCountTokens, handleGeminiGeneration, handleGeminiModel, handleGeminiModels, toGeminiRefusal } from "../gemini-inbound"; import { handleGeminiInteraction, handleGeminiInteractionResource } from "../gemini-interactions-inbound"; @@ -62,6 +63,9 @@ async function handleGeminiRoute(route: GeminiNativeRoute, original: Request, ur refused.headers.set("Allow", geminiRouteAllowHeader(route)); return withCors(refused, original, policy); } + if (!resolveGeminiApiSurface(config).enabled) { + return withCors(geminiError(403, "Gemini API is disabled"), original, policy); + } const generation = route.kind === "interactions" || (route.kind === "method" && (route.method === "generateContent" || route.method === "streamGenerateContent")); if (generation) disableResponsesRequestTimeout(original, deps.requestServer); diff --git a/src/server/management/api-access.ts b/src/server/management/api-access.ts index b840430d875..a4740cd801f 100644 --- a/src/server/management/api-access.ts +++ b/src/server/management/api-access.ts @@ -3,7 +3,7 @@ import { isWildcardHostname } from "../../codex/loopback-target"; import { localCredentialDestinationHostname, localInferenceDestination } from "../../lib/local-destinations"; import { isCanonicalOpenAiForwardProvider, OPENAI_API_PROVIDER_ID, OPENAI_CODEX_PROVIDER_ID } from "../../providers/openai-tiers-destination"; import { LIVE_AUDIO_MODEL, TRANSCRIPTION_MODEL } from "../audio-upstream"; -import { resolveApiSurfaceSettings, type ApiSurfaceSettings } from "../../protocols/settings"; +import { resolveApiSurfaceSettings, resolveGeminiApiSurface, type ApiSurfaceSetting, type ApiSurfaceSettings } from "../../protocols/settings"; export interface AudioApiAccess { transcriptionEndpoint: string; @@ -24,8 +24,9 @@ export interface ApiAccessEndpoints { chatCompletionsEndpoint: string; messagesEndpoint: string; modelsEndpoint: string; + geminiModelsEndpoint: string; /** Which public APIs are served and who decided it, from `resolveApiSurfaceSettings`. */ - surfaces: ApiSurfaceSettings; + surfaces: ApiSurfaceSettings & { gemini: ApiSurfaceSetting }; /** * Back-compat for dashboards that predate `surfaces`: they hide the Messages endpoint when * this is false. It mirrors `surfaces.messages.enabled`, not `claudeCode.enabled`, so an @@ -180,7 +181,8 @@ export function buildApiAccessEndpoints( chatCompletionsEndpoint: `${baseUrl}/chat/completions`, messagesEndpoint: `${baseUrl}/messages`, modelsEndpoint: `${baseUrl}/models`, - surfaces, + geminiModelsEndpoint: baseUrl.replace(/\/v1$/, "/v1beta/models"), + surfaces: { ...surfaces, gemini: resolveGeminiApiSurface(config) }, claudeCodeEnabled: surfaces.messages.enabled, audio: { transcriptionEndpoint: `${baseUrl}/audio/transcriptions`, diff --git a/src/server/management/protocol-routes.ts b/src/server/management/protocol-routes.ts index 2eca1eea959..73a5072c6f0 100644 --- a/src/server/management/protocol-routes.ts +++ b/src/server/management/protocol-routes.ts @@ -18,7 +18,7 @@ import { isProtocol, PROTOCOL_CONTRACT_VERSION } from "../../protocols/contract" import { isProtocolFeature, PROTOCOL_FEATURES, type ProtocolFeature } from "../../protocols/features"; import { previewProtocolPlan, type ProtocolPlanRequest } from "../../protocols/plan-snapshot"; import { buildProtocolProviderSummary } from "../../protocols/provider-summary"; -import { protocolPolicyRevision, resolveApiSurfaceSettings, resolveProtocolSettings } from "../../protocols/settings"; +import { protocolPolicyRevision, resolveApiSurfaceSettings, resolveGeminiApiSurface, resolveProtocolSettings } from "../../protocols/settings"; import type { OcxConfig } from "../../types"; import type { ManagementContext } from "./context"; import { readManagementJsonBodyOr } from "./body"; @@ -71,6 +71,8 @@ function protocolInfo(config: OcxConfig) { contractVersion: PROTOCOL_CONTRACT_VERSION, policyRevision: protocolPolicyRevision(config), surfaces: resolveApiSurfaceSettings(config), + // Older dashboards require exactly the three planning protocols inside surfaces. + geminiSurface: resolveGeminiApiSurface(config), settings: resolveProtocolSettings(config), features: PROTOCOL_FEATURES, }; diff --git a/src/server/management/protocol-settings-patch.ts b/src/server/management/protocol-settings-patch.ts index 05188aefa5e..f44ed43de44 100644 --- a/src/server/management/protocol-settings-patch.ts +++ b/src/server/management/protocol-settings-patch.ts @@ -17,6 +17,7 @@ import type { OcxConfig } from "../../types"; export interface ProtocolSettingsPatch { messagesEnabled?: boolean; + geminiEnabled?: boolean; unrepresentable?: UnrepresentablePolicy; rollout?: Partial; } @@ -25,7 +26,7 @@ export type ParsedProtocolSettingsPatch = | { ok: true; patch: ProtocolSettingsPatch } | { ok: false; code: string; message: string }; -const PATCH_KEYS = new Set(["messagesEnabled", "unrepresentable", "rollout"]); +const PATCH_KEYS = new Set(["messagesEnabled", "geminiEnabled", "unrepresentable", "rollout"]); export const PROTOCOL_ROLLOUT_KEYS = [ "nativeChatCombos", "managedMessagesNative", @@ -50,15 +51,19 @@ function invalid(code: string, message: string): ParsedProtocolSettingsPatch { export function parseProtocolSettingsPatch(body: unknown): ParsedProtocolSettingsPatch { if (!isRec(body)) return invalid("invalid_body", "body must be a JSON object"); const keys = Object.keys(body); - if (keys.length === 0) return invalid("empty_body", "body must set messagesEnabled, unrepresentable or rollout"); + if (keys.length === 0) return invalid("empty_body", "body must set messagesEnabled, geminiEnabled, unrepresentable or rollout"); for (const key of keys) { - if (!PATCH_KEYS.has(key)) return invalid("unknown_field", "body accepts only messagesEnabled, unrepresentable and rollout"); + if (!PATCH_KEYS.has(key)) return invalid("unknown_field", "body accepts only messagesEnabled, geminiEnabled, unrepresentable and rollout"); } const patch: ProtocolSettingsPatch = {}; if (body.messagesEnabled !== undefined) { if (typeof body.messagesEnabled !== "boolean") return invalid("invalid_messages_enabled", "messagesEnabled must be a boolean"); patch.messagesEnabled = body.messagesEnabled; } + if (body.geminiEnabled !== undefined) { + if (typeof body.geminiEnabled !== "boolean") return invalid("invalid_gemini_enabled", "geminiEnabled must be a boolean"); + patch.geminiEnabled = body.geminiEnabled; + } if (body.unrepresentable !== undefined) { if (body.unrepresentable !== "legacy" && body.unrepresentable !== "reject") { return invalid("invalid_unrepresentable", "unrepresentable must be \"legacy\" or \"reject\""); @@ -131,14 +136,24 @@ export function applyProtocolSettingsPatch(config: OcxConfig, patch: ProtocolSet } let claudeCodeChanged = false; - if (patch.messagesEnabled !== undefined) { - // A malformed block is replaced, not merged: the explicit value is what the operator asked for. - const surfaces: Rec = isRec(config.apiSurfaces) ? { ...config.apiSurfaces } : {}; - const messages: Rec = isRec(surfaces.messages) ? { ...surfaces.messages } : {}; - messages.enabled = patch.messagesEnabled; - surfaces.messages = messages; + if (patch.messagesEnabled !== undefined || patch.geminiEnabled !== undefined) { + const current = config.apiSurfaces; + const surfaces: Rec = isRec(current) ? { ...current } : {}; + for (const [name, enabled] of [ + ["messages", patch.messagesEnabled], + ["gemini", patch.geminiEnabled], + ] as const) { + if (enabled === undefined) continue; + const surface = surfaces[name]; + surfaces[name] = { ...(isRec(surface) ? surface : {}), enabled }; + } + if (current !== undefined && !isRec(current)) { + // Repairing the malformed parent must preserve closed sibling surfaces. + if (patch.messagesEnabled === undefined) surfaces.messages = { enabled: false }; + if (patch.geminiEnabled === undefined) surfaces.gemini = { enabled: false }; + } config.apiSurfaces = surfaces as OcxConfig["apiSurfaces"]; - if (!patch.messagesEnabled && config.claudeCode?.enabled !== false) { + if (patch.messagesEnabled === false && config.claudeCode?.enabled !== false) { commitClaudeCodeBlock(config, { ...(config.claudeCode ?? {}), enabled: false }); claudeCodeChanged = true; } diff --git a/src/types/config.ts b/src/types/config.ts index 1c2d01c51f3..e760899f19a 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -24,6 +24,8 @@ export interface OcxApiSurfacesConfig { * `claudeCode.enabled !== false`"; a present non-boolean value disables the surface. */ messages?: { enabled?: boolean }; + /** Gemini-compatible routes. The surface is open by default. */ + gemini?: { enabled?: boolean }; } /** Protocol delivery policy (devlog/_plan/260924_protocol_first_class). */ diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 184b88ec023..79d81c45613 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -20,6 +20,13 @@ package-tree fence answers them in the Gemini error shape. The unauthenticated d allowlist admits each path with its own HTTP method only (a wrong method is a 404 there, not the 405), because `ocx connect agy` points the CLI at that socket; admission still comes from the receiving listener's policy, as for the chat wire. OPTIONS takes data-plane origin policy. +The gateway serves these routes by default. An explicit false or malformed Gemini surface setting +returns a Gemini-shaped 403 for supported methods before credential handling, turn admission or +body reads. `PATCH /api/protocols/settings` writes `apiSurfaces.gemini.enabled` from the boolean +`geminiEnabled`. `GET /api/protocols` reports `geminiSurface` alongside the three planning +surfaces. `GET /api/keys` returns `surfaces.gemini` and `geminiModelsEndpoint` for the +dashboard card and usage example. See [Protocol Paths](protocol-paths.md#settings) for save +and rollback behavior. Gemini clients authenticate with `x-goog-api-key` or a `?key=` query parameter. The dispatcher clones the request, moves that credential onto `x-opencodex-api-key` (an existing dedicated header diff --git a/structure/data-planes/protocol-paths.md b/structure/data-planes/protocol-paths.md index 1458e846ead..8a4f93b96ad 100644 --- a/structure/data-planes/protocol-paths.md +++ b/structure/data-planes/protocol-paths.md @@ -542,8 +542,8 @@ lane, the decline trace, the beta allowlist, opaque state and OAuth. ## Settings -`resolveApiSurfaceSettings` and `resolveProtocolSettings` in `src/protocols/settings.ts` are the -only readers of the `apiSurfaces` and `protocols` config keys. Responses and Chat Completions are +`src/protocols/settings.ts` resolves the `apiSurfaces` and `protocols` config keys through +`resolveApiSurfaceSettings`, `resolveGeminiApiSurface` and `resolveProtocolSettings`. Responses and Chat Completions are always served. The Messages surface uses an explicit `apiSurfaces.messages.enabled` boolean when present, closes when that value is present but malformed, and otherwise inherits `claudeCode.enabled !== false`. The unrepresentable policy defaults to `legacy` and every @@ -562,7 +562,7 @@ through `nativeMessagesDeclineReason` by the Messages ingress, `count_tokens` an closed surface answers 403 before the body is read. `buildApiAccessEndpoints` (`src/server/management/api-access.ts`) reports the resolved `surfaces` in the keys payload and keeps `claudeCodeEnabled` for older dashboards, set from the resolved Messages state rather than -from `claudeCode.enabled`. +from `claudeCode.enabled`. The [Gemini surface](gemini-inbound.md) defaults on and has its own setting. `PATCH /api/protocols/settings` is the one writer. `src/server/management/protocol-settings-patch.ts` validates the body strictly and applies it in memory; the route persists through diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index a72be4519c5..8ccefae9339 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -312,7 +312,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | | Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. GET reads the saved policy and returns `{ excludedProviders: string[], meteredComboIds: string[] }`. PUT accepts `{ provider: string, excluded: boolean }`, changes only that provider in the locked persisted configuration, and returns the resulting policy. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. These checks run only in the route, which is authoritative: the dashboard's gating is advisory and can briefly offer an action the route refuses, and the dashboard recovers from the 409 by re-reading the policy and combos. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | -| Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | +| Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved planning surfaces, the separate `geminiSurface` state, protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, geminiEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | | Low-quota history | `src/server/management/low-quota-routes.ts` lazily serves authenticated `GET /api/codex-auth/low-quota-events` from the bounded ledger owned by the server handling the request. The response includes only that server’s account ids and notice/pause-save status; logs omit identifiers. The default notice records `logged`; a notice records `delivered` only after the injected or opted-in OS notifier sink succeeds, `failed` when it fails, and `cancelled` when its episode ends first, while a pause-save records `succeeded` after persistence succeeds. A timed-out in-flight save remains `pending` until it settles. Invalid limits return 400. The route itself emits no OS notification. | diff --git a/tests/server/api-access-endpoints.test.ts b/tests/server/api-access-endpoints.test.ts index f5a87c6bca9..a9d41c79165 100644 --- a/tests/server/api-access-endpoints.test.ts +++ b/tests/server/api-access-endpoints.test.ts @@ -38,6 +38,8 @@ describe("buildApiAccessEndpoints", () => { chatCompletionsEndpoint: "http://[::1]:10100/v1/chat/completions", messagesEndpoint: "http://[::1]:10100/v1/messages", modelsEndpoint: "http://[::1]:10100/v1/models", + geminiModelsEndpoint: "http://[::1]:10100/v1beta/models", + surfaces: { gemini: { enabled: true, source: "default" } }, claudeCodeEnabled: true, }); }); @@ -121,6 +123,7 @@ describe("buildApiAccessEndpoints", () => { responses: { enabled: true, source: "fixed" }, chat: { enabled: true, source: "fixed" }, messages: { enabled: true, source: "claude-code-legacy" }, + gemini: { enabled: true, source: "default" }, }); // An explicit surface value wins over the Claude integration, and the back-compat flag // follows the resolved surface so an older dashboard shows the endpoint that is served. diff --git a/tests/server/protocol-settings-route.test.ts b/tests/server/protocol-settings-route.test.ts index 645384a938f..2f7c3acaffb 100644 --- a/tests/server/protocol-settings-route.test.ts +++ b/tests/server/protocol-settings-route.test.ts @@ -93,6 +93,26 @@ describe("PATCH /api/protocols/settings", () => { expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: true } }); }); + test("Gemini persists its own setting and keeps the planning surface shape compatible", async () => { + const h = harness({ apiSurfaces: { messages: { enabled: true } }, claudeCode: { enabled: true }, + protocols: { rollout: { geminiNativeAntigravity: true } } }); + const res = await patch(h, { geminiEnabled: false }); + expect(res.status).toBe(200); + expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: true }, gemini: { enabled: false } }); + expect(h.saves[0]!.claudeCode).toEqual({ enabled: true }); + expect(h.saves[0]!.protocols?.rollout?.geminiNativeAntigravity).toBe(true); + const body = await res.json(); + expect(Object.keys(body.surfaces)).toEqual(["responses", "chat", "messages"]); + expect(body.geminiSurface).toEqual({ enabled: false, source: "api-surfaces" }); + expect(h.syncs).toBe(0); + }); + + test("repairing malformed surface settings does not reopen the sibling", async () => { + const h = harness({ apiSurfaces: "off" }); + expect((await patch(h, { geminiEnabled: true })).status).toBe(200); + expect(h.saves[0]!.apiSurfaces).toEqual({ messages: { enabled: false }, gemini: { enabled: true } }); + }); + test("policy and rollout switches merge into protocols", async () => { const h = harness({ protocols: { rollout: { directEncoders: true } } }); const res = await patch(h, { unrepresentable: "reject", rollout: { shadowPlan: true } }); @@ -147,6 +167,7 @@ describe("PATCH /api/protocols/settings", () => { ["a non-object body", [], "invalid_body"], ["an empty body", {}, "empty_body"], ["an unknown key", { messagesEnabled: true, claudeCode: { enabled: true } }, "unknown_field"], + ["a string geminiEnabled", { geminiEnabled: "false" }, "invalid_gemini_enabled"], ["a string messagesEnabled", { messagesEnabled: "false" }, "invalid_messages_enabled"], ["an unknown policy", { unrepresentable: "drop" }, "invalid_unrepresentable"], ["a non-object rollout", { rollout: true }, "invalid_rollout"], diff --git a/tests/server/server-gemini-inbound.test.ts b/tests/server/server-gemini-inbound.test.ts index 3689eec52ac..e7b7f13db48 100644 --- a/tests/server/server-gemini-inbound.test.ts +++ b/tests/server/server-gemini-inbound.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:tes import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { saveConfig } from "../../src/config"; +import { loadConfig, saveConfig } from "../../src/config"; import { startServer } from "../../src/server"; import { clearRequestLogsForTests, getRequestLogEntries } from "../../src/server/request-log"; import type { OcxConfig } from "../../src/types"; @@ -109,6 +109,49 @@ describe("Gemini-compatible inbound routes", () => { }); }); + test("the API switch closes and reopens Gemini on the running gateway", async () => { + await withServer(async base => { + const toggle = (geminiEnabled: boolean) => fetch(new URL("/api/protocols/settings", base), { + method: "PATCH", + headers: { "content-type": "application/json", "x-opencodex-api-key": ADMIN_TOKEN }, + body: JSON.stringify({ geminiEnabled }), + }); + const closed = await toggle(false); + expect(closed.status).toBe(200); + expect(await closed.json()).toMatchObject({ geminiSurface: { enabled: false, source: "api-surfaces" } }); + expect(loadConfig().apiSurfaces?.gemini?.enabled).toBe(false); + for (const [method, path] of [ + ["GET", "/v1beta/models"], + ["GET", "/v1beta/models/fx/m1"], + ["POST", "/v1beta/models/fx/m1:countTokens"], + ["POST", "/v1beta/models/fx/m1:streamGenerateContent?alt=sse"], + ["POST", "/v1/models/fx/m1:generateContent"], + ["POST", "/v1beta/interactions"], + ["DELETE", "/v1/interactions/example"], + ["POST", "/v1beta/interactions/example/cancel"], + ]) { + const response = await fetch(new URL(path!, base), { + method, headers: googKey, ...(method === "POST" ? { body: "not JSON" } : {}), + }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { message: "Gemini API is disabled", status: "PERMISSION_DENIED" } }); + } + expect(seen).toHaveLength(0); + const openAiModels = await fetch(new URL("/v1/models", base)); + expect(openAiModels.status).toBe(200); + await openAiModels.json(); + + const reopened = await toggle(true); + expect(reopened.status).toBe(200); + expect(await reopened.json()).toMatchObject({ geminiSurface: { enabled: true, source: "api-surfaces" } }); + expect(loadConfig().apiSurfaces?.gemini?.enabled).toBe(true); + const generated = await post(base, "/v1beta/models/fx/m1:generateContent", request()); + expect(generated.status).toBe(200); + expect(await generated.json()).toMatchObject({ candidates: [{ content: { parts: [{ text: "Hello" }] } }] }); + expect(seen).toHaveLength(1); + }); + }); + test("streamGenerateContent?alt=sse with x-goog-api-key streams Gemini SSE and reaches the provider as Chat", async () => { saveConfig(config(true)); await withServer(async base => { From 876f9efc971f407c4e1aec67d32bad17c5589204 Mon Sep 17 00:00:00 2001 From: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:33:36 +0800 Subject: [PATCH 17/19] fix(gui): localize the Gemini endpoint label in Traditional Chinese --- gui/src/i18n/zh-TW.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 9bd31621879..f3f027e4a93 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2439,7 +2439,7 @@ export const zhTW: Record = { "api.responsesEndpoint": "Responses API", "api.chatCompletionsEndpoint": "Chat Completions API", "api.messagesEndpoint": "Messages API", - "api.geminiEndpoint": "Gemini API", + "api.geminiEndpoint": "Gemini API 端點", "api.modelsEndpoint": "Models API", "api.surface.on": "開啟", "api.surface.off": "關閉", From dd80f2dbe7422051bd5932048d7991e224b8c96a Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 03:37:54 +0900 Subject: [PATCH 18/19] test(usage): move the Antigravity Gemini 4 price case to a sibling file; sync Spanish docs usage-cost.test.ts grew past the 2,000-line ratchet threshold; the case moves byte for byte into usage-cost-antigravity-gemini4.test.ts (registered in the usage shard). The Spanish server reference now names apiSurfaces.gemini.enabled as the English page does. --- .../docs/es/reference/configuration/server.md | 2 +- scripts/test-layout/layout-usage.json | 1 + tests/fixtures/test-layout-expected.json | 2 +- .../usage-cost-antigravity-gemini4.test.ts | 26 +++++++++++++++++++ tests/usage/usage-cost.test.ts | 24 ----------------- 5 files changed, 29 insertions(+), 26 deletions(-) create mode 100644 tests/usage/usage-cost-antigravity-gemini4.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index 871a8908f6f..a4fd7616b9b 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -526,7 +526,7 @@ Responses (`/v1/responses`) y Chat Completions (`/v1/chat/completions`) siempre | `apiSurfaces.messages.enabled?` | `boolean` | herede | `true` sirve el Messages API, `false` rechaza ambas rutas con 403. Unset hereda `claudeCode.enabled`, por lo que una integración Claude que está desactivada también cierra Messages. | | `apiSurfaces.gemini.enabled?` | `boolean` | `true` | `false` devuelve 403 para el catálogo, las operaciones de modelos y las interacciones de Gemini, incluidas las rutas compatibles bajo `/v1beta` y `/v1`. | -La tarjeta **API de Gemini** del panel controla este ajuste. El acceso nativo a Antigravity se configura por separado. +La tarjeta **API de Gemini** del panel controla este ajuste y su interruptor guarda solo `apiSurfaces.gemini.enabled`. El acceso nativo a Antigravity se configura por separado. Un valor presente pero mal formado (un no objeto `apiSurfaces` o `messages`, o un no booleano `enabled`) cierra el Messages API en lugar de volver al valor heredado. Ambas rutas siempre están de acuerdo. diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index 245e242e4e5..05ce1c30f46 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -1,4 +1,5 @@ { + "usage-cost-antigravity-gemini4.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-credit-ledger-regressions.test.ts": "usage", "usage-provider-credit-price.test.ts": "usage", diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f007d908cc7..028c93868c0 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1584,7 +1584,7 @@ "upstream-retry-zero-output.test.ts": "lib", "upstream-transient-retry.test.ts": "providers", "url-normalization.test.ts": "config", "usage-aggregate-cache.test.ts": "usage", "usage-anthropic-fast-pricing.test.ts": "usage", "usage-cursor-fast-pricing.test.ts": "usage", - "usage-attempt-delivery.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", + "usage-attempt-delivery.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-cost-antigravity-gemini4.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", "usage-credit-ledger-regressions.test.ts": "usage", "usage-provider-credit-price.test.ts": "usage", "usage-debug.test.ts": "usage", "usage-failure-fingerprint.test.ts": "usage", diff --git a/tests/usage/usage-cost-antigravity-gemini4.test.ts b/tests/usage/usage-cost-antigravity-gemini4.test.ts new file mode 100644 index 00000000000..e1d9e448723 --- /dev/null +++ b/tests/usage/usage-cost-antigravity-gemini4.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { estimateRequestCost, resolveMatchedPrice } from "../../src/usage/cost"; + +test("Antigravity Gemini 4 prices exact effort IDs using reported input, output and cache hits", () => { + const usage = { inputTokens: 10_000, outputTokens: 1_000, cachedInputTokens: 4_000, reasoningOutputTokens: 800 }; + for (const [base, expected] of [ + ["gemini-4-neon", { input: 0.018, output: 0.015, cacheRead: 0.0006, total: 0.0336 }], + ["gemini-4-hydrogen", { input: 0.009, output: 0.0075, cacheRead: 0.0003, total: 0.0168 }], + ] as const) { + for (const suffix of ["", "-low", "-medium", "-high", "-xhigh"]) { + const estimate = estimateRequestCost({ + provider: "google-antigravity", model: base + suffix, usage, usageStatus: "reported", + }); + expect(estimate?.price).toMatchObject({ modelId: base + suffix, source: "expected", status: "verified-derived" }); + expect(estimate?.estimated).toBe(true); + expect(estimate?.tokens).toEqual({ input: 6_000, output: 1_000, cacheRead: 4_000, cacheWrite: 0 }); + expect(estimate?.cost.cacheWrite).toBe(0); + for (const component of ["input", "output", "cacheRead", "total"] as const) { + expect(estimate!.cost[component]).toBeCloseTo(expected[component], 12); + } + } + const direct = resolveMatchedPrice("google", base); + expect(direct?.status).toBe("verified"); + } + expect(resolveMatchedPrice("google-antigravity", "gemini-discovery-fixture")).toBeNull(); +}); diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index 5f3b62c671e..0ecf16758f2 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1978,27 +1978,3 @@ describe("aggregator vendor-prefixed model ids (#3136)", () => { expect(resolveMatchedPrice("openrouter", "a/deepseek/deepseek-v4-flash")).toBeNull(); }); }); - -test("Antigravity Gemini 4 prices exact effort IDs using reported input, output and cache hits", () => { - const usage = { inputTokens: 10_000, outputTokens: 1_000, cachedInputTokens: 4_000, reasoningOutputTokens: 800 }; - for (const [base, expected] of [ - ["gemini-4-neon", { input: 0.018, output: 0.015, cacheRead: 0.0006, total: 0.0336 }], - ["gemini-4-hydrogen", { input: 0.009, output: 0.0075, cacheRead: 0.0003, total: 0.0168 }], - ] as const) { - for (const suffix of ["", "-low", "-medium", "-high", "-xhigh"]) { - const estimate = estimateRequestCost({ - provider: "google-antigravity", model: base + suffix, usage, usageStatus: "reported", - }); - expect(estimate?.price).toMatchObject({ modelId: base + suffix, source: "expected", status: "verified-derived" }); - expect(estimate?.estimated).toBe(true); - expect(estimate?.tokens).toEqual({ input: 6_000, output: 1_000, cacheRead: 4_000, cacheWrite: 0 }); - expect(estimate?.cost.cacheWrite).toBe(0); - for (const component of ["input", "output", "cacheRead", "total"] as const) { - expect(estimate!.cost[component]).toBeCloseTo(expected[component], 12); - } - } - const direct = resolveMatchedPrice("google", base); - expect(direct?.status).toBe("verified"); - } - expect(resolveMatchedPrice("google-antigravity", "gemini-discovery-fixture")).toBeNull(); -}); From 377cf7b9d09b828802e79e0f2dc478b01e46c0c3 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 04:26:52 +0900 Subject: [PATCH 19/19] fix(gui): keep the telemetry-contract types in a type-only import request-outcome-agreement requires Logs.tsx to import AttemptRecoveryKind via import type from the contract leaf. Split the value import of ACCOUNT_LOG_LABEL_RE into its own statement. --- gui/src/pages/Logs.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/gui/src/pages/Logs.tsx b/gui/src/pages/Logs.tsx index 7d390dcfe73..5c1ac40f4bd 100644 --- a/gui/src/pages/Logs.tsx +++ b/gui/src/pages/Logs.tsx @@ -39,14 +39,14 @@ import { validCachedRouteDecision, } from "./log-route-decision"; import { mergeLogDelta, parseLogPollResponse } from "./log-poll"; -import { - ACCOUNT_LOG_LABEL_RE, - type AttemptRecoveryKind, - type RequestFailureCause, - type RequestFailureStage, - type RequestSpendTotals, - type ResendPermission, +import type { + AttemptRecoveryKind, + RequestFailureCause, + RequestFailureStage, + RequestSpendTotals, + ResendPermission, } from "../../../src/usage/telemetry-contract"; +import { ACCOUNT_LOG_LABEL_RE } from "../../../src/usage/telemetry-contract"; import { classifyRequestOutcome, type RequestOutcomeClass,