From fcb8f9a1c0aa91a57c9fa713a9cdefb01520906d Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:38:30 -0500 Subject: [PATCH 1/5] refactor(server): share native Chat-bridge plumbing between native ingresses Move the identity-only internal Chat request, Retry-After and refusal vocabulary, fixed inner error text and the SSE stream pump out of the Ollama inbound into native-chat-bridge.ts so a second native ingress can reuse them. The Ollama surface keeps its exports and behavior. --- src/server/native-chat-bridge.ts | 225 +++++++++++++++++++++++++++++++ src/server/ollama-inbound.ts | 201 +++++---------------------- 2 files changed, 255 insertions(+), 171 deletions(-) create mode 100644 src/server/native-chat-bridge.ts diff --git a/src/server/native-chat-bridge.ts b/src/server/native-chat-bridge.ts new file mode 100644 index 00000000000..4f2a2645fb0 --- /dev/null +++ b/src/server/native-chat-bridge.ts @@ -0,0 +1,225 @@ +/** + * Shared plumbing for native ingresses that translate onto the internal Chat Completions path + * (the Ollama-compatible and Gemini-compatible routes). It holds what is identical across them: + * the identity-only internal request, Retry-After and refusal vocabulary, fixed error text by + * status, and the SSE-to-native stream pump with its settlement and cancellation rules. The + * protocol-specific parts (frame shapes, error bodies) stay in each ingress. + */ +import { parseRetryAfterMs } from "../combos"; +import { WORKFLOW_LOCAL_REFUSAL_HEADER } from "../lib/workflow-budget"; +import type { NativeFinalLog } from "./native-final-log"; +import { linkRequestSessionLane } from "./request-log-conversation"; + +// Session and workflow identity only: lineage, session lanes and the workflow root's spend +// ceiling read these from the request Chat sees. Never authorization, cookies or admission keys. +const IDENTITY_HEADERS = ["session_id", "session-id", "thread-id", "x-session-id", "x-codex-parent-thread-id"] as const; + +/** The synthesized Chat request: JSON content type, identity headers, the client signal and its session lane. */ +export function internalChatRequest(req: Request, chatJson: string): Request { + const headers = new Headers({ "content-type": "application/json" }); + for (const name of IDENTITY_HEADERS) { + const value = req.headers.get(name); + if (value !== null) headers.set(name, value); + } + const internal = new Request(new URL("/v1/chat/completions", req.url), { method: "POST", headers, body: chatJson, signal: req.signal }); + linkRequestSessionLane(req, internal); + return internal; +} + +/** Upper bound for the retry advice a native surface passes on. */ +export const NATIVE_MAX_RETRY_AFTER_SECONDS = 3600; + +/** + * Retry-After as an integer we format ourselves. The incoming value may come from an upstream, + * so only the parsed delay crosses this boundary, never its bytes; unparseable values are dropped. + */ +export function nativeRetryAfter(value: string | null | undefined, now = Date.now()): string | undefined { + if (value?.trim() === "0") return "0"; + const ms = parseRetryAfterMs(value, now); + if (ms === undefined) return undefined; + return String(Math.min(NATIVE_MAX_RETRY_AFTER_SECONDS, Math.max(0, Math.ceil(ms / 1000)))); +} + +/** + * The local refusal codes native surfaces pass on, each mapped to a constant defined here. The + * emitted header value is always the constant; an incoming value only selects it, and any value + * not in this table is dropped. + */ +const LOCAL_REFUSAL_CODES: ReadonlyMap = new Map([ + ["workflow_sends_exhausted", "workflow_sends_exhausted"], + ["workflow_children_exhausted", "workflow_children_exhausted"], + ["workflow_concurrency_exhausted", "workflow_concurrency_exhausted"], + ["workflow_spend_exhausted", "workflow_spend_exhausted"], + ["workflow_tracking_exhausted", "workflow_tracking_exhausted"], + ["workflow_send_replayed", "workflow_send_replayed"], + ["workflow_pool_history_unresolved", "workflow_pool_history_unresolved"], + ["workflow_spend_undurable", "workflow_spend_undurable"], +]); + +export interface NativeRefusalParts { + status: number; + message: string; + retryAfter: string | null; + /** A constant from the known workflow refusal codes, never the incoming header value. */ + localRefusalCode?: string; +} + +/** Reduce an existing proxy refusal (capacity, workflow, drain) to its status, fixed text and retry advice. */ +export function nativeRefusalParts(response: Response): NativeRefusalParts { + try { void response.body?.cancel().catch(() => {}); } catch { /* already consumed */ } + const message = response.status === 429 ? "request budget exhausted; retry later" + : response.status === 499 ? "request cancelled" + : response.status === 503 ? "server temporarily unavailable; retry later" : "request refused"; + const code = LOCAL_REFUSAL_CODES.get(response.headers.get(WORKFLOW_LOCAL_REFUSAL_HEADER) ?? ""); + return { status: response.status, message, retryAfter: response.headers.get("retry-after"), ...(code !== undefined ? { localRefusalCode: code } : {}) }; +} + +/** Put the workflow refusal constant on a native refusal and expose it to browsers. */ +export function applyLocalRefusalCode(native: Response, code: string | undefined): Response { + if (code === undefined) return native; + native.headers.set(WORKFLOW_LOCAL_REFUSAL_HEADER, code); + native.headers.set("Access-Control-Expose-Headers", WORKFLOW_LOCAL_REFUSAL_HEADER); + return native; +} + +/** + * Native error text is chosen by status only. The inner body can carry upstream-authored text, + * which may echo a credential no pattern recognizes, so it is drained and never forwarded. + */ +const INNER_ERROR_MESSAGES: Readonly> = { + 400: "request rejected", + 401: "upstream authentication failed", + 402: "upstream payment required", + 403: "request not permitted", + 404: "model not found", + 408: "upstream request timed out", + 409: "request conflict", + 413: "request too large", + 422: "request rejected", + 429: "rate limited; retry later", + 499: "request cancelled", + 500: "upstream request failed", + 502: "upstream request failed", + 503: "upstream unavailable; retry later", + 504: "upstream request timed out", +}; + +export function nativeInnerErrorMessage(status: number): string { + return INNER_ERROR_MESSAGES[status] ?? (status >= 500 ? "upstream request failed" : "request failed"); +} + +export async function drainedInnerErrorMessage(response: Response): Promise { + await response.body?.cancel().catch(() => {}); + return nativeInnerErrorMessage(response.ok ? 502 : response.status); +} + +/** A client that left before the outer outcome was committed owns a 499 row, whatever the inner path reported. */ +export function commitCancelled(finalLog: NativeFinalLog): void { + finalLog.commit({ status: 499, closeReason: "client_cancel" }); +} + +export type NativeStreamTerminal = { ok: true; frames(): Uint8Array[] } | { ok: false; error: string }; + +/** The protocol-specific half of a native stream: how Chat chunks become frames. */ +export interface NativeStreamTranslator { + contentType: string; + /** One parsed Chat chunk to zero or more encoded frames. Throwing marks the stream failed. */ + chunk(parsed: unknown): Uint8Array[]; + /** Evaluated once at end of stream, before settlement is known; frames are produced only on success. */ + terminal(): NativeStreamTerminal; + /** Encoded frames that end a stream that failed or did not settle. */ + failure(message: string): Uint8Array[]; +} + +/** + * Pump an inner Chat SSE body through a translator. A stream's terminal frames are emitted only + * after the Chat stream reached EOF and the inner path settled, so trailing usage is included and + * a later error never follows a success terminal. The row is committed exactly once through + * the final log; a client that cancels, even while settlement is pending, owns a 499 row. + */ +export function streamNativeFromChat(translator: NativeStreamTranslator, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { + const reader = body.getReader(); + const decoder = new TextDecoder(); + let pending = ""; + // ended: no further reads or frames. cancelled: the client went away, possibly while end() waits. + let ended = false; + let cancelled = false; + // The inner Chat path can finalize on EOF after [DONE], so keep draining to EOF before ending. + let sawDone = false; + const cancelInner = () => { try { void reader.cancel().catch(() => {}); } catch { /* released */ } }; + const end = async (controller: ReadableStreamDefaultController, failure?: string) => { + if (ended) return; + ended = true; + if (failure !== undefined) cancelInner(); + const terminal = failure === undefined ? translator.terminal() : undefined; + const settled = await finalLog.waitForInner(); + if (cancelled || signal.aborted) { + commitCancelled(finalLog); + try { controller.close(); } catch { /* already cancelled by the client */ } + return; + } + try { + if (terminal?.ok === true && settled) { + for (const frame of terminal.frames()) controller.enqueue(frame); + finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "terminal" }); + } else { + const message = failure ?? (terminal?.ok === false ? terminal.error : "request did not complete"); + for (const frame of translator.failure(message)) controller.enqueue(frame); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "terminal" }); + } + controller.close(); + } catch { + // The client cancelled between settlement and the terminal frames; the row still lands once. + commitCancelled(finalLog); + } + }; + // Returns how many frames were enqueued. Finish and usage chunks may enqueue nothing. + const consume = (controller: ReadableStreamDefaultController, block: string): number => { + let emitted = 0; + for (const raw of block.split("\n")) { + const text = raw.trimEnd(); + if (!text.startsWith("data:")) continue; + // Chat ends at [DONE]; any later data (an error frame, say) means the stream did not settle cleanly. + if (sawDone) throw new Error("data after the Chat stream terminator"); + const payload = text.slice(5).trim(); + if (payload === "[DONE]") { sawDone = true; continue; } + for (const frame of translator.chunk(JSON.parse(payload))) { controller.enqueue(frame); emitted++; } + } + return emitted; + }; + return new Response(new ReadableStream({ + // A pull that resolves without enqueueing is not called again, so keep reading until this + // pull has produced a frame or ended the stream. + async pull(controller) { + try { + while (!ended) { + const { done, value } = await reader.read(); + if (done) { + pending += decoder.decode(); + if (pending) consume(controller, pending); + pending = ""; + await end(controller); + return; + } + pending += decoder.decode(value, { stream: true }); + const boundary = pending.lastIndexOf("\n"); + if (boundary < 0) continue; + const complete = pending.slice(0, boundary); + pending = pending.slice(boundary + 1); + if (consume(controller, complete) > 0) return; + } + } catch { + await end(controller, signal.aborted ? "request cancelled" : "upstream stream failed"); + } + }, + async cancel() { + cancelled = true; + // When end() is already waiting for settlement it sees the flag and writes the 499 row. + if (ended) return; + ended = true; + cancelInner(); + await finalLog.waitForInner(); + commitCancelled(finalLog); + }, + }, { highWaterMark: 0 }), { status: 200, headers: { "content-type": translator.contentType } }); +} diff --git a/src/server/ollama-inbound.ts b/src/server/ollama-inbound.ts index 06762a9ff67..c454cbb3bda 100644 --- a/src/server/ollama-inbound.ts +++ b/src/server/ollama-inbound.ts @@ -9,8 +9,6 @@ */ import { OllamaCodecError, consumeOllamaChatChunk, createOllamaStreamState, ollamaBufferedResponse, ollamaStreamTerminal, ollamaToChat, type OllamaKind } from "../protocols/codecs/ollama"; import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; -import { parseRetryAfterMs } from "../combos"; -import { WORKFLOW_LOCAL_REFUSAL_HEADER } from "../lib/workflow-budget"; import type { OcxConfig } from "../types"; import type { DataPlaneAdmission } from "./auth-cors"; import type { CapturedAdmissionPolicy } from "../types/admission-policy"; @@ -18,29 +16,29 @@ import type { AdmissionLease } from "../lib/admission"; import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; import { handleChatCompletions } from "./chat-completions"; import { VERSION } from "./management-api"; +import { + NATIVE_MAX_RETRY_AFTER_SECONDS, + applyLocalRefusalCode, + commitCancelled, + drainedInnerErrorMessage, + internalChatRequest, + nativeInnerErrorMessage, + nativeRefusalParts, + nativeRetryAfter, + streamNativeFromChat, +} from "./native-chat-bridge"; import { createNativeFinalLog, type NativeFinalLog } from "./native-final-log"; -import { findOllamaRoute, linkRequestSessionLane, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy"; +import { findOllamaRoute, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy"; import { DecompressedBodyTooLargeError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; import { addFinalRequestLog, type RequestLogContext } from "./request-log"; const SHOW_BODY_LIMIT_BYTES = 64 * 1024; -// Session and workflow identity only: lineage, session lanes and the workflow root's spend -// ceiling read these from the request Chat sees. Never authorization, cookies or admission keys. -const IDENTITY_HEADERS = ["session_id", "session-id", "thread-id", "x-session-id", "x-codex-parent-thread-id"] as const; /** Upper bound for the retry advice this surface passes on. */ -export const OLLAMA_MAX_RETRY_AFTER_SECONDS = 3600; +export const OLLAMA_MAX_RETRY_AFTER_SECONDS = NATIVE_MAX_RETRY_AFTER_SECONDS; -/** - * Retry-After as an integer we format ourselves. The incoming value may come from an upstream, - * so only the parsed delay crosses this boundary, never its bytes; unparseable values are dropped. - */ -export function ollamaRetryAfter(value: string | null | undefined, now = Date.now()): string | undefined { - if (value?.trim() === "0") return "0"; - const ms = parseRetryAfterMs(value, now); - if (ms === undefined) return undefined; - return String(Math.min(OLLAMA_MAX_RETRY_AFTER_SECONDS, Math.max(0, Math.ceil(ms / 1000)))); -} +/** Retry-After as an integer we format ourselves; see nativeRetryAfter. */ +export const ollamaRetryAfter = nativeRetryAfter; /** * Every Ollama error response is built from scratch: content type, our own error text, and @@ -54,36 +52,10 @@ export function ollamaError(status: number, message: string, retryAfter?: string return new Response(JSON.stringify({ error: message }), { status, headers }); } -/** - * The local refusal codes this surface passes on, each mapped to a constant defined here. The - * emitted header value is always the constant; an incoming value only selects it, and any value - * not in this table is dropped. - */ -const LOCAL_REFUSAL_CODES: ReadonlyMap = new Map([ - ["workflow_sends_exhausted", "workflow_sends_exhausted"], - ["workflow_children_exhausted", "workflow_children_exhausted"], - ["workflow_concurrency_exhausted", "workflow_concurrency_exhausted"], - ["workflow_spend_exhausted", "workflow_spend_exhausted"], - ["workflow_tracking_exhausted", "workflow_tracking_exhausted"], - ["workflow_send_replayed", "workflow_send_replayed"], - ["workflow_pool_history_unresolved", "workflow_pool_history_unresolved"], - ["workflow_spend_undurable", "workflow_spend_undurable"], -]); - /** Reshape an existing proxy refusal (capacity, workflow, drain) keeping its status and retry advice. */ export function toOllamaRefusal(response: Response): Response { - try { void response.body?.cancel().catch(() => {}); } catch { /* already consumed */ } - const message = response.status === 429 ? "request budget exhausted; retry later" - : response.status === 499 ? "request cancelled" - : response.status === 503 ? "server temporarily unavailable; retry later" : "request refused"; - const native = ollamaError(response.status, message, response.headers.get("retry-after")); - // The workflow refusal names its local reason; only a recognized code selects our constant. - const code = LOCAL_REFUSAL_CODES.get(response.headers.get(WORKFLOW_LOCAL_REFUSAL_HEADER) ?? ""); - if (code !== undefined) { - native.headers.set(WORKFLOW_LOCAL_REFUSAL_HEADER, code); - native.headers.set("Access-Control-Expose-Headers", WORKFLOW_LOCAL_REFUSAL_HEADER); - } - return native; + const parts = nativeRefusalParts(response); + return applyLocalRefusalCode(ollamaError(parts.status, parts.message, parts.retryAfter), parts.localRefusalCode); } export function handleOllamaVersion(): Response { @@ -131,47 +103,7 @@ function failBeforeInner(ids: OllamaLogIds, logCtx: RequestLogContext, status: n return ollamaError(status, message); } -function internalChatRequest(req: Request, chatJson: string): Request { - const headers = new Headers({ "content-type": "application/json" }); - for (const name of IDENTITY_HEADERS) { - const value = req.headers.get(name); - if (value !== null) headers.set(name, value); - } - const internal = new Request(new URL("/v1/chat/completions", req.url), { method: "POST", headers, body: chatJson, signal: req.signal }); - linkRequestSessionLane(req, internal); - return internal; -} - -/** - * Native error text is chosen by status only. The inner body can carry upstream-authored text, - * which may echo a credential no pattern recognizes, so it is drained and never forwarded. - */ -const INNER_ERROR_MESSAGES: Readonly> = { - 400: "request rejected", - 401: "upstream authentication failed", - 402: "upstream payment required", - 403: "request not permitted", - 404: "model not found", - 408: "upstream request timed out", - 409: "request conflict", - 413: "request too large", - 422: "request rejected", - 429: "rate limited; retry later", - 499: "request cancelled", - 500: "upstream request failed", - 502: "upstream request failed", - 503: "upstream unavailable; retry later", - 504: "upstream request timed out", -}; - -export function ollamaInnerErrorMessage(status: number): string { - return INNER_ERROR_MESSAGES[status] ?? (status >= 500 ? "upstream request failed" : "request failed"); -} - -async function innerErrorMessage(response: Response): Promise { - await response.body?.cancel().catch(() => {}); - return ollamaInnerErrorMessage(response.ok ? 502 : response.status); -} +export const ollamaInnerErrorMessage = nativeInnerErrorMessage; /** /api/chat and /api/generate. `req` is the admitted, session-promoted request. */ export async function handleOllamaGeneration( @@ -218,7 +150,7 @@ export async function handleOllamaGeneration( return ollamaError(502, "request failed"); } if (!inner.ok || !inner.body) { - const message = await innerErrorMessage(inner); + const message = await drainedInnerErrorMessage(inner); await finalLog.waitForInner(); if (req.signal.aborted) return cancelledNonStream(finalLog); finalLog.commit({ status: inner.ok ? 502 : inner.status, terminalStatus: "failed", closeReason: "non_stream" }); @@ -231,7 +163,7 @@ export async function handleOllamaGeneration( /** A client that left before the outer outcome was committed owns a 499 row, whatever the inner path reported. */ function cancelledNonStream(finalLog: NativeFinalLog): Response { - finalLog.commit({ status: 499, closeReason: "client_cancel" }); + commitCancelled(finalLog); return ollamaError(499, "request cancelled"); } @@ -261,89 +193,16 @@ const line = (record: unknown) => encoder.encode(`${JSON.stringify(record)}\n`); /** Exported for the settlement-window cancellation test; production callers go through handleOllamaGeneration. */ export function streamOllama(kind: OllamaKind, model: string, createdAt: string, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { - const reader = body.getReader(); - const decoder = new TextDecoder(); const state = createOllamaStreamState(kind, model, createdAt); - let pending = ""; - // ended: no further reads or records. cancelled: the client went away, possibly while end() waits. - let ended = false; - let cancelled = false; - // The inner Chat path can finalize on EOF after [DONE], so keep draining to EOF before ending. - let sawDone = false; - const cancelInner = () => { try { void reader.cancel().catch(() => {}); } catch { /* released */ } }; - const commitCancelled = () => finalLog.commit({ status: 499, closeReason: "client_cancel" }); - const end = async (controller: ReadableStreamDefaultController, failure?: string) => { - if (ended) return; - ended = true; - if (failure !== undefined) cancelInner(); - const terminal = failure === undefined ? ollamaStreamTerminal(state) : undefined; - const settled = await finalLog.waitForInner(); - if (cancelled || signal.aborted) { - commitCancelled(); - try { controller.close(); } catch { /* already cancelled by the client */ } - return; - } - try { - if (terminal?.done === true && settled) { - controller.enqueue(line(terminal)); - finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "terminal" }); - } else { - controller.enqueue(line({ error: failure ?? (typeof terminal?.error === "string" ? terminal.error : "request did not complete") })); - finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "terminal" }); - } - controller.close(); - } catch { - // The client cancelled between settlement and the terminal record; the row still lands once. - commitCancelled(); - } - }; - // Returns how many native records were enqueued. Finish and usage frames enqueue nothing. - const consume = (controller: ReadableStreamDefaultController, block: string): number => { - let emitted = 0; - for (const raw of block.split("\n")) { - const text = raw.trimEnd(); - if (!text.startsWith("data:")) continue; - // Chat ends at [DONE]; any later data (an error frame, say) means the stream did not settle cleanly. - if (sawDone) throw new Error("data after the Chat stream terminator"); - const payload = text.slice(5).trim(); - if (payload === "[DONE]") { sawDone = true; continue; } - for (const record of consumeOllamaChatChunk(state, JSON.parse(payload))) { controller.enqueue(line(record)); emitted++; } - } - return emitted; - }; - return new Response(new ReadableStream({ - // A pull that resolves without enqueueing is not called again, so keep reading until this - // pull has produced a record or ended the stream. - async pull(controller) { - try { - while (!ended) { - const { done, value } = await reader.read(); - if (done) { - pending += decoder.decode(); - if (pending) consume(controller, pending); - pending = ""; - await end(controller); - return; - } - pending += decoder.decode(value, { stream: true }); - const boundary = pending.lastIndexOf("\n"); - if (boundary < 0) continue; - const complete = pending.slice(0, boundary); - pending = pending.slice(boundary + 1); - if (consume(controller, complete) > 0) return; - } - } catch { - await end(controller, signal.aborted ? "request cancelled" : "upstream stream failed"); - } - }, - async cancel() { - cancelled = true; - // When end() is already waiting for settlement it sees the flag and writes the 499 row. - if (ended) return; - ended = true; - cancelInner(); - await finalLog.waitForInner(); - commitCancelled(); + return streamNativeFromChat({ + contentType: "application/x-ndjson", + chunk: parsed => consumeOllamaChatChunk(state, parsed).map(line), + terminal() { + const record = ollamaStreamTerminal(state); + return record.done === true + ? { ok: true, frames: () => [line(record)] } + : { ok: false, error: typeof record.error === "string" ? record.error : "request did not complete" }; }, - }, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "application/x-ndjson" } }); + failure: message => [line({ error: message })], + }, body, finalLog, signal); } From d085e0617bb952004a0103bcd71e4e4a7be7007c Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:38:37 -0500 Subject: [PATCH 2/5] feat(protocols): add Gemini generateContent codec Pure request projection (contents, systemInstruction, tools, toolConfig, generationConfig, thinkingConfig) onto Chat Completions, buffered response projection, and the Chat-chunk to Gemini stream state machine. --- src/protocols/codecs/gemini.ts | 426 +++++++++++++++++++++++++++++++++ 1 file changed, 426 insertions(+) create mode 100644 src/protocols/codecs/gemini.ts diff --git a/src/protocols/codecs/gemini.ts b/src/protocols/codecs/gemini.ts new file mode 100644 index 00000000000..af2db7f71f3 --- /dev/null +++ b/src/protocols/codecs/gemini.ts @@ -0,0 +1,426 @@ +/** + * Pure Gemini generateContent request and Chat Completions response projections. + * + * Request side: a Gemini body becomes one Chat Completions body. Unknown fields are ignored (the + * Gemini API grows them often); a field this proxy cannot honor and that would change the answer + * (a second candidate, a non-image inline part) is a typed 400 instead of a silent drop. + * Response side: a buffered Chat completion or a Chat SSE chunk sequence becomes Gemini + * GenerateContentResponse objects. A streamed tool call is accumulated and emitted as one + * complete functionCall part, because Gemini clients expect whole calls. + */ +type Obj = Record; + +export const MAX_GEMINI_TOOL_CALLS = 1_024; +export const MAX_GEMINI_SCHEMA_DEPTH = 64; + +export class GeminiCodecError extends Error { + readonly status = 400; + readonly code = "invalid_gemini_request"; + constructor(message: string) { super(message); this.name = "GeminiCodecError"; } +} + +function fail(message: string): never { throw new GeminiCodecError(message); } +const isObj = (value: unknown): value is Obj => !!value && typeof value === "object" && !Array.isArray(value); +function object(value: unknown, label: string): Obj { + if (!isObj(value)) fail(`Invalid ${label}`); + return value; +} +function array(value: unknown, label: string): unknown[] { + if (!Array.isArray(value)) fail(`Invalid ${label}`); + return value; +} +function text(value: unknown, label: string, nonempty = false): string { + if (typeof value !== "string" || (nonempty && !value.trim())) fail(`Invalid ${label}`); + return value; +} +function finiteNumber(value: unknown, label: string): number { + if (typeof value !== "number" || !Number.isFinite(value)) fail(`Invalid ${label}`); + return value; +} +const snake = (key: string) => key.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`); +/** Gemini JSON is camelCase, but the REST surface also accepts snake_case; read either. */ +function field(source: Obj, key: string): unknown { + return source[key] !== undefined ? source[key] : source[snake(key)]; +} + +/** Gemini declares schema types in upper case ("OBJECT"); Chat tools want JSON Schema's lower case. */ +function normalizeSchema(value: unknown, depth = 0): unknown { + if (depth > MAX_GEMINI_SCHEMA_DEPTH) fail("Schema nesting too deep"); + if (Array.isArray(value)) return value.map(item => normalizeSchema(item, depth + 1)); + if (!isObj(value)) return value; + const out: Obj = {}; + for (const [key, item] of Object.entries(value)) { + out[key] = key === "type" && typeof item === "string" ? item.toLowerCase() : normalizeSchema(item, depth + 1); + } + return out; +} + +function chatTools(value: unknown): Obj[] { + const tools: Obj[] = []; + for (const raw of array(value, "tools")) { + const declarations = field(object(raw, "tool"), "functionDeclarations"); + // Hosted Gemini tools (search, code execution) have no Chat equivalent and are not declarations. + if (declarations === undefined) continue; + for (const rawDeclaration of array(declarations, "functionDeclarations")) { + const declaration = object(rawDeclaration, "function declaration"); + const name = text(declaration.name, "function name", true); + if (declaration.description !== undefined) text(declaration.description, "function description"); + const schema = field(declaration, "parametersJsonSchema") ?? declaration.parameters ?? { type: "object", properties: {} }; + object(schema, "function parameters"); + tools.push({ + type: "function", + function: { + name, + ...(typeof declaration.description === "string" ? { description: declaration.description } : {}), + parameters: normalizeSchema(schema), + }, + }); + } + } + return tools; +} + +function toolChoice(toolConfig: unknown): unknown { + if (toolConfig === undefined) return undefined; + const config = field(object(toolConfig, "toolConfig"), "functionCallingConfig"); + if (config === undefined) return undefined; + const calling = object(config, "functionCallingConfig"); + const mode = calling.mode === undefined ? "AUTO" : text(calling.mode, "function calling mode").toUpperCase(); + const namesRaw = field(calling, "allowedFunctionNames"); + const names = namesRaw === undefined ? [] : array(namesRaw, "allowedFunctionNames").map(name => text(name, "allowed function name", true)); + const entries = names.map(name => ({ type: "function", function: { name } })); + if (mode === "NONE") return "none"; + if (mode === "AUTO" || mode === "MODE_UNSPECIFIED") return entries.length ? { type: "allowed_tools", allowed_tools: { mode: "auto", tools: entries } } : undefined; + if (mode === "ANY" || mode === "VALIDATED") { + if (entries.length === 1) return entries[0]; + return entries.length ? { type: "allowed_tools", allowed_tools: { mode: "required", tools: entries } } : "required"; + } + return fail("Unsupported function calling mode"); +} + +function responseFormat(config: Obj): Obj | undefined { + const mime = config.responseMimeType === undefined && config.response_mime_type === undefined ? undefined : text(field(config, "responseMimeType"), "responseMimeType"); + const schema = field(config, "responseJsonSchema") ?? field(config, "responseSchema"); + if (mime !== undefined && mime !== "application/json" && mime !== "text/plain") fail("Unsupported responseMimeType"); + if (mime === "text/plain" || (mime === undefined && schema === undefined)) return undefined; + if (schema === undefined) return { type: "json_object" }; + object(schema, "response schema"); + return { type: "json_schema", json_schema: { name: "response", schema: normalizeSchema(schema) } }; +} + +const REASONING_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh"]); +function reasoning(config: unknown): Obj { + if (config === undefined) return {}; + const thinking = object(config, "thinkingConfig"); + const out: Obj = {}; + const level = field(thinking, "thinkingLevel"); + const budget = field(thinking, "thinkingBudget"); + if (level !== undefined) { + const effort = text(level, "thinkingLevel").toLowerCase(); + if (REASONING_EFFORTS.has(effort)) out.reasoning_effort = effort; + } else if (budget !== undefined) { + const tokens = finiteNumber(budget, "thinkingBudget"); + // -1 asks the model to decide, which is the upstream default. + if (tokens === 0) out.reasoning_effort = "none"; + else if (tokens > 0) out.reasoning_effort = tokens <= 2_048 ? "low" : tokens <= 12_288 ? "medium" : "high"; + } + if (field(thinking, "includeThoughts") === true) out.include_reasoning = true; + return out; +} + +function generationSettings(raw: unknown, result: Obj): void { + if (raw === undefined) return; + const config = object(raw, "generationConfig"); + const numeric: ReadonlyArray = [ + ["temperature", "temperature"], ["topP", "top_p"], ["presencePenalty", "presence_penalty"], ["frequencyPenalty", "frequency_penalty"], + ]; + for (const [key, chatKey] of numeric) { + const value = field(config, key); + if (value !== undefined) result[chatKey] = finiteNumber(value, key); + } + const maxTokens = field(config, "maxOutputTokens"); + if (maxTokens !== undefined) { + if (typeof maxTokens !== "number" || !Number.isSafeInteger(maxTokens) || maxTokens < 1) fail("Invalid maxOutputTokens"); + result.max_tokens = maxTokens; + } + const seed = field(config, "seed"); + if (seed !== undefined) { + if (typeof seed !== "number" || !Number.isSafeInteger(seed)) fail("Invalid seed"); + result.seed = seed; + } + const stops = field(config, "stopSequences"); + if (stops !== undefined) result.stop = array(stops, "stopSequences").map(stop => text(stop, "stop sequence")); + const candidates = field(config, "candidateCount"); + if (candidates !== undefined && candidates !== 1) fail("candidateCount other than 1 is unsupported"); + const format = responseFormat(config); + if (format) result.response_format = format; + Object.assign(result, reasoning(field(config, "thinkingConfig"))); +} + +function partsOf(content: Obj): Obj[] { + return array(field(content, "parts"), "parts").map(part => object(part, "part")); +} + +function systemText(value: unknown): string { + if (typeof value === "string") return value; + return partsOf(object(value, "systemInstruction")).map(part => (part.text === undefined ? "" : text(part.text, "system text"))).join("\n"); +} + +const BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/; +function inlineImage(raw: unknown): Obj { + const data = object(raw, "inlineData"); + const mime = text(field(data, "mimeType"), "inline data media type", true).toLowerCase(); + if (!/^image\/[a-z0-9.+-]+$/.test(mime)) fail("Unsupported inline data media type"); + const bytes = text(data.data, "inline data", true); + if (!BASE64.test(bytes)) fail("Invalid inline data encoding"); + return { type: "image_url", image_url: { url: `data:${mime};base64,${bytes}` } }; +} + +interface PendingCall { id: string; name: string; matched: boolean } + +/** Convert Gemini contents to Chat messages, matching each functionResponse to a prior functionCall. */ +function chatMessages(contents: unknown, system: unknown): Obj[] { + const messages: Obj[] = []; + if (system !== undefined) { + const instruction = systemText(system); + if (instruction) messages.push({ role: "system", content: instruction }); + } + const byId = new Map(); + const byName = new Map(); + let callCount = 0; + array(contents, "contents").forEach((rawContent, ci) => { + const content = object(rawContent, "content"); + const role = content.role === undefined ? "user" : text(content.role, "role"); + if (role !== "user" && role !== "model" && role !== "function" && role !== "tool") fail("Unsupported role"); + const parts = partsOf(content); + for (const part of parts) { + if (field(part, "fileData") !== undefined || field(part, "executableCode") !== undefined || field(part, "codeExecutionResult") !== undefined) fail("Unsupported part"); + } + if (role === "model") { + const texts: string[] = []; + const calls: Obj[] = []; + parts.forEach((part, pi) => { + if (typeof part.text === "string") { + // Replayed thought summaries are not conversation content. + if (part.thought !== true) texts.push(part.text); + return; + } + const rawCall = field(part, "functionCall"); + if (rawCall === undefined) { + if (field(part, "inlineData") !== undefined || field(part, "functionResponse") !== undefined) fail("Unsupported model part"); + return; + } + if (++callCount > MAX_GEMINI_TOOL_CALLS) fail("Too many function calls"); + const call = object(rawCall, "functionCall"); + const name = text(call.name, "function name", true); + const args = call.args === undefined ? {} : object(call.args, "function arguments"); + const id = call.id === undefined ? `call_gemini_${ci}_${pi}` : text(call.id, "function call id", true); + if (byId.has(id)) fail("Duplicate function call id"); + const pending: PendingCall = { id, name, matched: false }; + byId.set(id, pending); + byName.set(name, [...(byName.get(name) ?? []), pending]); + calls.push({ id, type: "function", function: { name, arguments: JSON.stringify(args) } }); + }); + const body = texts.join(""); + if (body || calls.length) messages.push({ role: "assistant", content: body || null, ...(calls.length ? { tool_calls: calls } : {}) }); + return; + } + const tools: Obj[] = []; + const user: Obj[] = []; + let hasImage = false; + for (const part of parts) { + const rawResponse = field(part, "functionResponse"); + if (rawResponse !== undefined) { + const response = object(rawResponse, "functionResponse"); + const name = text(response.name, "function name", true); + const id = response.id === undefined ? undefined : text(response.id, "function response id", true); + let target = id === undefined ? undefined : byId.get(id); + if (!target || target.matched || target.name !== name) target = byName.get(name)?.find(candidate => !candidate.matched); + if (!target) fail("Unmatched function response"); + target.matched = true; + tools.push({ role: "tool", tool_call_id: target.id, content: JSON.stringify(response.response ?? {}) }); + } else if (typeof part.text === "string") { + if (part.thought !== true) user.push({ type: "text", text: part.text }); + } else if (field(part, "inlineData") !== undefined) { + user.push(inlineImage(field(part, "inlineData"))); + hasImage = true; + } + } + // Tool results must directly follow the assistant turn that asked for them. + messages.push(...tools); + if (user.length) messages.push({ role: "user", content: hasImage ? user : user.map(item => item.text as string).join("\n") }); + }); + return messages; +} + +/** Project a generateContent body for `model` onto a Chat Completions body. */ +export function geminiToChat(model: string, input: unknown, stream: boolean): Obj { + const body = object(input, "request"); + const result: Obj = { model: text(model, "model", true), stream, messages: chatMessages(body.contents, field(body, "systemInstruction")) }; + if (body.tools !== undefined) { + const tools = chatTools(body.tools); + if (tools.length) { + result.tools = tools; + const choice = toolChoice(field(body, "toolConfig")); + if (choice !== undefined) result.tool_choice = choice; + } + } + generationSettings(field(body, "generationConfig"), result); + return result; +} + +function nonNegativeInt(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +function usageMetadata(value: unknown): Obj | undefined { + if (!isObj(value)) return undefined; + const prompt = nonNegativeInt(value.prompt_tokens); + const completion = nonNegativeInt(value.completion_tokens); + if (prompt === undefined && completion === undefined) return undefined; + const details = isObj(value.completion_tokens_details) ? value.completion_tokens_details : {}; + const promptDetails = isObj(value.prompt_tokens_details) ? value.prompt_tokens_details : {}; + const thoughts = nonNegativeInt(details.reasoning_tokens) ?? 0; + const cached = nonNegativeInt(promptDetails.cached_tokens) ?? 0; + const out: Obj = { + promptTokenCount: prompt ?? 0, + // Chat counts reasoning inside completion tokens; Gemini reports it separately. + candidatesTokenCount: Math.max(0, (completion ?? 0) - thoughts), + totalTokenCount: (prompt ?? 0) + (completion ?? 0), + }; + if (thoughts > 0) out.thoughtsTokenCount = thoughts; + if (cached > 0) out.cachedContentTokenCount = cached; + return out; +} + +const FINISH_REASONS: Readonly> = { + stop: "STOP", + tool_calls: "STOP", + function_call: "STOP", + length: "MAX_TOKENS", + content_filter: "SAFETY", +}; +function finishReason(value: unknown): string | undefined { + return typeof value === "string" && Object.hasOwn(FINISH_REASONS, value) ? FINISH_REASONS[value] : undefined; +} + +function candidate(parts: Obj[], reason?: string): Obj { + return { content: { role: "model", parts }, ...(reason ? { finishReason: reason } : {}), index: 0 }; +} + +function functionCallPart(id: unknown, name: string, argumentsJson: unknown, index: number): Obj { + let args: unknown = {}; + if (typeof argumentsJson === "string") { + if (argumentsJson.trim()) { try { args = JSON.parse(argumentsJson); } catch { throw new Error("Invalid Chat tool arguments"); } } + } else if (argumentsJson !== undefined && argumentsJson !== null) args = argumentsJson; + if (!isObj(args)) throw new Error("Invalid Chat tool arguments"); + return { functionCall: { id: typeof id === "string" && id ? id : `call_gemini_response_${index}`, name, args } }; +} + +/** A complete Chat completion as a GenerateContentResponse. Throws when the completion did not finish cleanly. */ +export function chatToGeminiResponse(model: string, input: unknown): Obj { + const body = object(input, "Chat response"); + if (!Array.isArray(body.choices) || body.choices.length !== 1) throw new Error("Invalid Chat choices"); + const choice = object(body.choices[0], "Chat choice"); + const reason = finishReason(choice.finish_reason); + if (!reason) throw new Error("Chat completion did not finish successfully"); + const message = object(choice.message, "Chat message"); + const parts: Obj[] = []; + const thought = message.reasoning_content ?? message.reasoning; + if (typeof thought === "string" && thought) parts.push({ text: thought, thought: true }); + if (message.content != null) { + if (typeof message.content !== "string") throw new Error("Invalid Chat content"); + if (message.content) parts.push({ text: message.content }); + } + if (message.tool_calls !== undefined) { + if (!Array.isArray(message.tool_calls)) throw new Error("Invalid Chat tool calls"); + message.tool_calls.forEach((raw, i) => { + const call = object(raw, "Chat tool call"); + const fn = object(call.function, "Chat tool function"); + parts.push(functionCallPart(call.id, text(fn.name, "tool name", true), fn.arguments, i)); + }); + } + if (!parts.length) parts.push({ text: "" }); + const usage = usageMetadata(body.usage); + return { candidates: [candidate(parts, reason)], ...(usage ? { usageMetadata: usage } : {}), modelVersion: model }; +} + +type StreamTool = { id?: string; name: string; arguments: string }; +export interface GeminiStreamState { + model: string; + finishReason?: unknown; + usage?: Obj; + tools: Map; + toolsEmitted: boolean; +} +export function createGeminiStreamState(model: string): GeminiStreamState { + return { model, tools: new Map(), toolsEmitted: false }; +} + +function streamChunk(state: GeminiStreamState, parts: Obj[]): Obj { + return { candidates: [candidate(parts)], modelVersion: state.model }; +} + +/** Consume one parsed Chat chunk. The caller owns settlement and may discard these records on failure. */ +export function consumeGeminiChatChunk(state: GeminiStreamState, input: unknown): Obj[] { + const body = object(input, "Chat chunk"); + if (body.error !== undefined) throw new Error("Chat stream error"); + if (body.usage != null) state.usage = usageMetadata(body.usage); + if (!Array.isArray(body.choices) || body.choices.length > 1) throw new Error("Invalid Chat chunk choices"); + if (!body.choices.length) return []; + const choice = object(body.choices[0], "Chat choice"); + const delta = object(choice.delta, "Chat delta"); + if (state.finishReason !== undefined) throw new Error("Chat chunk after finish"); + const records: Obj[] = []; + const thought = delta.reasoning_content ?? delta.reasoning; + if (thought != null) { + const value = text(thought, "Chat reasoning"); + if (value) records.push(streamChunk(state, [{ text: value, thought: true }])); + } + if (delta.content != null) { + const value = text(delta.content, "Chat content"); + if (value) records.push(streamChunk(state, [{ text: value }])); + } + if (delta.tool_calls !== undefined) { + if (!Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta"); + for (const raw of delta.tool_calls) { + const call = object(raw, "tool delta"); + if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index"); + const index = call.index as number; + if (!state.tools.has(index) && state.tools.size >= MAX_GEMINI_TOOL_CALLS) throw new Error("Too many tool calls"); + const current = state.tools.get(index) ?? { name: "", arguments: "" }; + if (call.id !== undefined) { + const id = text(call.id, "tool id", true); + if (current.id && current.id !== id) throw new Error("Conflicting tool id"); + current.id = id; + } + if (call.function !== undefined) { + const fn = object(call.function, "tool function"); + if (fn.name !== undefined) current.name += text(fn.name, "tool name"); + if (fn.arguments !== undefined) current.arguments += text(fn.arguments, "tool arguments"); + } + state.tools.set(index, current); + } + } + if (choice.finish_reason != null) { + state.finishReason = choice.finish_reason; + if (state.tools.size) { + const parts = [...state.tools.entries()].sort((a, b) => a[0] - b[0]) + .map(([index, tool]) => functionCallPart(tool.id, text(tool.name, "tool name", true), tool.arguments, index)); + records.push(streamChunk(state, parts)); + state.toolsEmitted = true; + } + } + return records; +} + +/** The closing chunk with the finish reason and usage. Call only after the outer handler confirms settlement. */ +export function geminiStreamTerminal(state: GeminiStreamState): Obj | undefined { + const reason = finishReason(state.finishReason); + if (!reason || (state.tools.size > 0 && !state.toolsEmitted)) return undefined; + return { + candidates: [candidate([{ text: "" }], reason)], + ...(state.usage ? { usageMetadata: state.usage } : {}), + modelVersion: state.model, + }; +} From 15e6e5bb82ac1acb8312439839d19d82c2355b5f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:43:18 -0500 Subject: [PATCH 3/5] feat(server): serve Gemini-compatible generateContent and models routes Gemini clients (the google-genai SDK with a custom base URL, agy with the genai wire protocol) can now reach configured provider routes through /v1beta/models and /v1beta|v1/models/{model}:generateContent|streamGenerateContent. The x-goog-api-key header or ?key= query parameter is moved onto the dedicated proxy header before admission, and the request translates onto the shared internal Chat path like the Ollama inbound. --- src/server/gemini-inbound.ts | 203 +++++++++++++++++++++++++++ src/server/gemini-native-paths.ts | 50 +++++++ src/server/inbound-body-admission.ts | 3 +- src/server/index.ts | 3 + src/server/index/gemini-routes.ts | 90 ++++++++++++ src/server/index/serve-options.ts | 13 +- src/server/native-chat-bridge.ts | 12 ++ src/server/ollama-inbound.ts | 11 +- 8 files changed, 374 insertions(+), 11 deletions(-) create mode 100644 src/server/gemini-inbound.ts create mode 100644 src/server/gemini-native-paths.ts create mode 100644 src/server/index/gemini-routes.ts diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts new file mode 100644 index 00000000000..349777454e3 --- /dev/null +++ b/src/server/gemini-inbound.ts @@ -0,0 +1,203 @@ +/** + * Gemini-compatible inbound API: GET /v1beta/models[/{model}] and POST + * /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 + * 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. + */ +import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini"; +import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; +import type { OcxConfig } from "../types"; +import type { DataPlaneAdmission } from "./auth-cors"; +import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; +import { handleChatCompletions } from "./chat-completions"; +import type { GeminiMethod } from "./gemini-native-paths"; +import { + applyLocalRefusalCode, + commitCancelled, + drainedInnerErrorMessage, + internalChatRequest, + nativeRefusalParts, + nativeRetryAfter, + streamNativeFromChat, + type NativeLogIds, +} from "./native-chat-bridge"; +import { createNativeFinalLog, type NativeFinalLog } from "./native-final-log"; +import { findOllamaRoute, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy"; +import { DecompressedBodyTooLargeError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; +import { addFinalRequestLog, type RequestLogContext } from "./request-log"; + +const STATUS_NAMES: Readonly> = { + 400: "INVALID_ARGUMENT", 401: "UNAUTHENTICATED", 403: "PERMISSION_DENIED", 404: "NOT_FOUND", 413: "INVALID_ARGUMENT", + 429: "RESOURCE_EXHAUSTED", 499: "CANCELLED", 501: "UNIMPLEMENTED", 503: "UNAVAILABLE", 504: "DEADLINE_EXCEEDED", +}; + +export function geminiErrorBody(status: number, message: string): { error: { code: number; message: string; status: string } } { + return { error: { code: status, message, status: STATUS_NAMES[status] ?? "INTERNAL" } }; +} + +/** + * Every Gemini error response is built from scratch: content type, our own error text, and + * optionally a reformatted Retry-After. Callers add CORS and the request-log id. + */ +export function geminiError(status: number, message: string, retryAfter?: string | null): Response { + const headers = new Headers({ "content-type": "application/json" }); + const advice = nativeRetryAfter(retryAfter); + if (advice !== undefined) headers.set("Retry-After", advice); + return new Response(JSON.stringify(geminiErrorBody(status, message)), { status, headers }); +} + +/** Reshape an existing proxy refusal (capacity, workflow, drain) keeping its status and retry advice. */ +export function toGeminiRefusal(response: Response): Response { + const parts = nativeRefusalParts(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 })); +} + +const modelResource = (selector: string) => ({ + name: `models/${selector}`, + displayName: selector, + supportedGenerationMethods: ["generateContent", "streamGenerateContent"], +}); + +export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response { + return Response.json({ models: eligibleRoutes(config, req, admission).map(row => modelResource(row.selector)) }); +} + +export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response { + const row = findOllamaRoute(config, model, req); + const scope = resolveAdmissionModelScope(config, admission); + if (!row || !routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })) return geminiError(404, "model not found"); + return Response.json(modelResource(row.selector)); +} + +function failBeforeInner(ids: NativeLogIds, logCtx: RequestLogContext, status: number, message: string): Response { + addFinalRequestLog(ids.requestId, ids.start, logCtx, status, { closeReason: "non_stream" }); + return geminiError(status, message); +} + +function cancelledNonStream(finalLog: NativeFinalLog): Response { + commitCancelled(finalLog); + return geminiError(499, "request cancelled"); +} + +/** generateContent and streamGenerateContent. `req` is the admitted, session-promoted request. */ +export async function handleGeminiGeneration( + method: Extract, + model: string, + sse: boolean, + req: Request, + config: OcxConfig, + logCtx: RequestLogContext, + ids: NativeLogIds, +): Promise { + const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes); + const stream = method === "streamGenerateContent"; + const budget = createTranslatorBudget(); + let chat: Record; + try { + chat = geminiToChat(model, await readJsonRequestBody(req, budget, limit), stream); + } catch (error) { + if (req.signal.aborted) return failBeforeInner(ids, logCtx, 499, "request cancelled"); + if (error instanceof DecompressedBodyTooLargeError) return failBeforeInner(ids, logCtx, 413, "request body too large"); + if (isTranslatorBudgetExceededError(error)) return failBeforeInner(ids, logCtx, 502, "request translation buffer exceeded the safe limit"); + return failBeforeInner(ids, logCtx, 400, error instanceof GeminiCodecError ? error.message : "invalid JSON body"); + } finally { + budget.dispose(); + } + logCtx.requestedModel = model; + const preflight = preflightOllamaRoute(config, model, req); + if (!preflight.ok) { + logCtx.errorCode = preflight.error.code; + return failBeforeInner(ids, logCtx, preflight.error.status, preflight.error.message); + } + const chatJson = JSON.stringify(chat); + if (Buffer.byteLength(chatJson) > limit) return failBeforeInner(ids, logCtx, 413, "request body too large"); + const internal = internalChatRequest(req, chatJson); + const finalLog = createNativeFinalLog(ids.requestId, ids.start, logCtx); + let inner: Response; + try { + inner = await handleChatCompletions(internal, config, logCtx, { ...ids, suppressProtocolTrace: true }); + } catch { + await finalLog.waitForInner(); + if (req.signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return geminiError(502, "request failed"); + } + if (!inner.ok || !inner.body) { + const message = await drainedInnerErrorMessage(inner); + await finalLog.waitForInner(); + if (req.signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: inner.ok ? 502 : inner.status, terminalStatus: "failed", closeReason: "non_stream" }); + return geminiError(inner.ok ? 502 : inner.status, message, inner.headers.get("retry-after")); + } + return stream + ? streamGemini(model, sse, inner.body, finalLog, req.signal) + : bufferedGemini(model, inner, finalLog, req.signal); +} + +async function bufferedGemini(model: string, inner: Response, finalLog: NativeFinalLog, signal: AbortSignal): Promise { + let native: Record; + try { + native = chatToGeminiResponse(model, JSON.parse(await inner.text())); + } catch { + await finalLog.waitForInner(); + if (signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return geminiError(502, "invalid upstream response"); + } + const settled = await finalLog.waitForInner(); + if (signal.aborted) return cancelledNonStream(finalLog); + if (!settled) { + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return geminiError(502, "request did not complete"); + } + finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "non_stream" }); + return Response.json(native); +} + +const encoder = new TextEncoder(); + +/** How records become bytes: SSE data frames, or the elements of one JSON array. */ +interface GeminiFraming { + contentType: string; + frames(records: unknown[]): Uint8Array[]; + end(records: unknown[]): Uint8Array[]; +} + +const sseFraming = (): GeminiFraming => { + const frames = (records: unknown[]) => records.map(record => encoder.encode(`data: ${JSON.stringify(record)}\r\n\r\n`)); + return { contentType: "text/event-stream", frames, end: frames }; +}; + +const arrayFraming = (): GeminiFraming => { + let opened = false; + const frames = (records: unknown[]) => records.map(record => { + const prefix = opened ? ",\n" : "[\n"; + opened = true; + return encoder.encode(prefix + JSON.stringify(record)); + }); + return { contentType: "application/json", frames, end: records => [...frames(records), encoder.encode("\n]")] }; +}; + +function streamGemini(model: string, sse: boolean, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { + const state = createGeminiStreamState(model); + const framing = sse ? sseFraming() : arrayFraming(); + return streamNativeFromChat({ + contentType: framing.contentType, + chunk: parsed => framing.frames(consumeGeminiChatChunk(state, parsed)), + terminal() { + const record = geminiStreamTerminal(state); + return record ? { ok: true, frames: () => framing.end([record]) } : { ok: false, error: "request did not complete" }; + }, + failure: message => framing.end([geminiErrorBody(502, message)]), + }, body, finalLog, signal); +} diff --git a/src/server/gemini-native-paths.ts b/src/server/gemini-native-paths.ts new file mode 100644 index 00000000000..0116b739f9c --- /dev/null +++ b/src/server/gemini-native-paths.ts @@ -0,0 +1,50 @@ +/** + * Gemini-compatible paths served on the authenticated data-plane listener. Kept free of handler + * imports so listener allowlists and the package-tree fence can classify a path cheaply. + * `GET /v1/models` and every other /v1/ path belong to OpenCodex itself: `/v1/` counts here only + * for `POST /v1/models/{model}:{method}` with a method this surface knows. + */ +export type GeminiMethod = "generateContent" | "streamGenerateContent" | "countTokens" | "embedContent" | "batchEmbedContents"; + +export type GeminiNativeRoute = + | { kind: "models"; httpMethod: "GET" } + | { kind: "model"; httpMethod: "GET"; model: string } + | { kind: "method"; httpMethod: "POST"; model: string; method: GeminiMethod }; + +const METHODS: ReadonlySet = new Set(["generateContent", "streamGenerateContent", "countTokens", "embedContent", "batchEmbedContents"]); + +/** A model reference as clients write it: URL-encoded or not, with or without a leading `models/`. */ +function modelName(raw: string): string | undefined { + let decoded: string; + try { decoded = decodeURIComponent(raw); } catch { return undefined; } + const name = decoded.startsWith("models/") ? decoded.slice("models/".length) : decoded; + return name.trim() ? name : undefined; +} + +/** The Gemini route a path names, or undefined when the path is not one this surface serves. */ +export function parseGeminiNativePath(pathname: string): GeminiNativeRoute | undefined { + const beta = pathname.startsWith("/v1beta/models"); + if (!beta && !pathname.startsWith("/v1/models/")) return undefined; + const rest = pathname.slice(beta ? "/v1beta/models".length : "/v1/models".length); + if (beta && (rest === "" || rest === "/")) return { kind: "models", httpMethod: "GET" }; + if (!rest.startsWith("/")) return undefined; + const target = rest.slice(1); + const colon = target.lastIndexOf(":"); + if (colon >= 0 && METHODS.has(target.slice(colon + 1))) { + const model = modelName(target.slice(0, colon)); + return model ? { kind: "method", httpMethod: "POST", model, method: target.slice(colon + 1) as GeminiMethod } : undefined; + } + if (!beta) return undefined; + const model = modelName(target); + return model ? { kind: "model", httpMethod: "GET", model } : undefined; +} + +export function isGeminiNativePath(pathname: string): boolean { + return parseGeminiNativePath(pathname) !== undefined; +} + +/** Generation routes read a JSON body under maxInboundBodyBytes and take the raised-body admission. */ +export function isGeminiGenerationPath(pathname: string): boolean { + const route = parseGeminiNativePath(pathname); + return route?.kind === "method" && (route.method === "generateContent" || route.method === "streamGenerateContent"); +} diff --git a/src/server/inbound-body-admission.ts b/src/server/inbound-body-admission.ts index bd2c5c7b9f5..a4f521dc183 100644 --- a/src/server/inbound-body-admission.ts +++ b/src/server/inbound-body-admission.ts @@ -8,6 +8,7 @@ import { codexCompatibleUrl } from "../codex/context-compat"; import { addFinalRequestLog, markLocalRequestLogRefusal } from "./request-log"; import type { WorkflowRefusalLog } from "./workflow-refusal"; import { inboundBodyBudget, bindInboundBodyLease, type InboundBodyBudget } from "./inbound-body-budget"; +import { isGeminiGenerationPath } from "./gemini-native-paths"; import { OLLAMA_JSON_BODY_ROUTES } from "./ollama-native-paths"; export { configureInboundBodyBudget, MAX_CONCURRENT_INBOUND_BODY_BYTES } from "./inbound-body-budget"; @@ -163,7 +164,7 @@ export async function withRaisedInboundBodyAdmission( // Native Ollama generation routes are served only on the authenticated listener, so they sit in // their own set: the loopback oracle checks CONFIGURABLE_JSON_BODY_ROUTES against that allowlist. const raised = maxBytes > MAX_DECOMPRESSED_BODY_BYTES; - if (req.method !== "POST" || !(CONFIGURABLE_JSON_BODY_ROUTES.has(pathname) || OLLAMA_JSON_BODY_ROUTES.has(pathname)) + if (req.method !== "POST" || !(CONFIGURABLE_JSON_BODY_ROUTES.has(pathname) || OLLAMA_JSON_BODY_ROUTES.has(pathname) || isGeminiGenerationPath(pathname)) || !(raised || encodedBody(req)) || req.signal.aborted) { return work(); } diff --git a/src/server/index.ts b/src/server/index.ts index 6d2f25b2ee4..4ea4157b390 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -5,6 +5,7 @@ import { normalizeBindHostname } from "./bind-host"; import { configureInboundBodyBudget } from "./inbound-body-admission"; import { createAdmittedHttpTurn } from "./admitted-http-turn"; import { isOllamaNativePath } from "./ollama-native-paths"; +import { isGeminiNativePath } from "./gemini-native-paths"; import { buildWarmupCompletionFrames, buildWsErrorFrame, @@ -451,6 +452,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe if (rawPath === "/opencodex-session") return req.method === "GET" || req.method === "POST"; // Ollama-compatible inference paths are data plane, not management: never via Tailscale Serve. if (isOllamaNativePath(rawPath)) return false; + // Gemini-compatible inference paths are data plane too, and /v1beta/ is never a management route. + if (isGeminiNativePath(rawPath) || rawPath.startsWith("/v1beta/")) return false; if (rawPath.startsWith("/api/")) return true; if (req.method !== "GET" && req.method !== "HEAD") return false; let decodedPath: string; diff --git a/src/server/index/gemini-routes.ts b/src/server/index/gemini-routes.ts new file mode 100644 index 00000000000..81e683c7b83 --- /dev/null +++ b/src/server/index/gemini-routes.ts @@ -0,0 +1,90 @@ +/** + * Dispatcher arm for the Gemini-compatible inbound API (the google-genai SDK with a custom base + * URL, `agy` with the genai wire protocol). Like the Ollama arm it runs only for the exact native + * paths and reuses the data-plane gates; refusals keep their status and retry advice and are + * reshaped into the Gemini error body. Gemini clients authenticate with `x-goog-api-key` or a + * `?key=` query parameter, so the request is cloned with that credential moved onto + * `x-opencodex-api-key` and the query key dropped; the key is never logged or forwarded. + */ +import { classifyUsageClient } from "../../usage/client"; +import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors, type RequestPolicyView } from "../auth-cors"; +import { withCallerSessionIdentity } from "../caller-session-identity"; +import { captureAdmissionPolicy } from "../capture-admission-policy"; +import { isDraining } from "../lifecycle"; +import { parseGeminiNativePath } from "../gemini-native-paths"; +import { geminiError, handleGeminiGeneration, handleGeminiModel, handleGeminiModels, toGeminiRefusal } from "../gemini-inbound"; +import { nextRequestLogId, type RequestLogContext } from "../request-log"; +import { disableResponsesRequestTimeout } from "../responses"; +import { withRequestLogId } from "./startup-warnings"; +import type { OllamaRouteDeps } from "./ollama-routes"; + +export type GeminiRouteDeps = OllamaRouteDeps; + +/** Move the Gemini credential onto the proxy's dedicated header and drop it from the URL. */ +function withProxyCredential(req: Request, url: URL): Request { + const headers = new Headers(req.headers); + const key = headers.get("x-goog-api-key")?.trim() || url.searchParams.get("key")?.trim(); + headers.delete("x-goog-api-key"); + if (key && !headers.get("x-opencodex-api-key")?.trim()) headers.set("x-opencodex-api-key", key); + const clean = new URL(url); + clean.searchParams.delete("key"); + const init: RequestInit & { duplex?: "half" } = { method: req.method, headers, signal: req.signal }; + if (req.body) { init.body = req.body; init.duplex = "half"; } + return new Request(clean, init); +} + +/** Returns undefined when the path is not one of the native routes. */ +export async function dispatchGeminiRoute(original: Request, url: URL, deps: GeminiRouteDeps): Promise { + const route = parseGeminiNativePath(url.pathname); + if (!route) return undefined; + const { config, policy } = deps; + if (original.method !== route.httpMethod) { + const refused = geminiError(405, `method ${original.method} not allowed`); + refused.headers.set("Allow", route.httpMethod); + return withCors(refused, original, policy); + } + const generation = route.kind === "method" && (route.method === "generateContent" || route.method === "streamGenerateContent"); + if (generation) disableResponsesRequestTimeout(original, deps.requestServer); + const req = withProxyCredential(original, url); + if (!generation) { + // Model discovery never forwards Authorization upstream, so the broader admission set is safe. + const admission = resolveApiAuth(req, policy); + if (!admission) return withCors(geminiError(401, "opencodex API key required"), original, policy); + if (!isAllowedRequestOrigin(req, policy)) return withCors(geminiError(403, "cross-origin data-plane request blocked"), original, policy); + const response = route.kind === "models" ? handleGeminiModels(config, req, admission) + : route.kind === "model" ? handleGeminiModel(config, req, admission, route.model) + : geminiError(501, `${route.method} is not supported`); + return withCors(response, original, policy); + } + if (isDraining()) return withCors(toGeminiRefusal(deps.drainingResponse(req, policy)), original, policy); + const admission = resolveResponsesApiAuth(req, policy); + if (!admission) return withCors(geminiError(401, "opencodex API key required"), original, policy); + if (!isAllowedRequestOrigin(req, policy)) return withCors(geminiError(403, "cross-origin data-plane request blocked"), original, policy); + const start = Date.now(); + const requestId = nextRequestLogId(start); + const logCtx: RequestLogContext = { + model: "unknown", + provider: "unknown", + ...deps.requestMetricsLogContext, + client: classifyUsageClient(req.headers), + ...admissionFields(admission), + }; + const sessionReq = withCallerSessionIdentity(req, admission); + const sse = url.searchParams.get("alt") === "sse"; + // Expose an id only when the handler or a logged refusal owns the history row. + let ownsRequestLog = false; + const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission); + const method = route.method as "generateContent" | "streamGenerateContent"; + const response = await deps.runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => { + ownsRequestLog = true; + return withCors( + await handleGeminiGeneration(method, route.model, sse, sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }), + original, + policy, + ); + }, { requestId, start, logCtx, onLogged: () => { ownsRequestLog = true; } }, { + mapRefusal: toGeminiRefusal, + onAdmissionError: () => geminiError(499, "request cancelled"), + }); + return ownsRequestLog ? withRequestLogId(response, requestId) : response; +} diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index b943aab586d..dc4a254f0bc 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -208,6 +208,9 @@ import { classifyUsageClient } from "../../usage/client"; import { isOllamaNativePath } from "../ollama-native-paths"; import { ollamaError } from "../ollama-inbound"; import { dispatchOllamaRoute } from "./ollama-routes"; +import { isGeminiNativePath } from "../gemini-native-paths"; +import { geminiError } from "../gemini-inbound"; +import { dispatchGeminiRoute } from "./gemini-routes"; import { readyProtocolMetadata } from "../../remote/protocol"; import { homeInstanceId, stampServedBy } from "../../remote/served-by"; @@ -364,6 +367,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { || readyzPath !== undefined || url.pathname.startsWith("/v1/") || isOllamaNativePath(url.pathname) + || isGeminiNativePath(url.pathname) )) { const message = "OpenCodex package files changed while this proxy was running; it restarts on its own, or run 'ocx restart' ('ocx service restart' for a background service)."; const fencedPort = ctx.boundPort ?? requestServer.port ?? listenPort; @@ -389,7 +393,9 @@ export function createServeOptions(ctx: ServeOptionsContext) { }, 503, req, policy) : isOllamaNativePath(url.pathname) ? withCors(ollamaError(503, message), req, policy) - : packageTreeChangedResponse(req, policy, message); + : isGeminiNativePath(url.pathname) + ? withCors(geminiError(503, message), req, policy) + : packageTreeChangedResponse(req, policy, message); const headers = new Headers(response.headers); headers.set("Retry-After", "5"); const challenge = fencedHealth ? req.headers.get(LOCAL_ATTESTATION_CHALLENGE_HEADER) : null; @@ -407,6 +413,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { } // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS. const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname); + // Gemini routes are data-plane paths too (never under /api/), so they take the data-plane branch. const allowed = managementPreflight ? isAllowedManagementOrigin(req, config) : isAllowedRequestOrigin(req, policy); @@ -656,6 +663,10 @@ export function createServeOptions(ctx: ServeOptionsContext) { const native = await dispatchOllamaRoute(req, url, { config, policy, requestServer, requestMetricsLogContext, drainingResponse, runAdmittedHttpTurn }); if (native) return native; } + if (isGeminiNativePath(url.pathname)) { + const native = await dispatchGeminiRoute(req, url, { config, policy, requestServer, requestMetricsLogContext, drainingResponse, runAdmittedHttpTurn }); + if (native) return native; + } if (url.pathname.startsWith("/api/")) { const localManagementAuth = { diff --git a/src/server/native-chat-bridge.ts b/src/server/native-chat-bridge.ts index 4f2a2645fb0..0b6a60e504f 100644 --- a/src/server/native-chat-bridge.ts +++ b/src/server/native-chat-bridge.ts @@ -6,7 +6,10 @@ * protocol-specific parts (frame shapes, error bodies) stay in each ingress. */ import { parseRetryAfterMs } from "../combos"; +import type { AdmissionLease } from "../lib/admission"; import { WORKFLOW_LOCAL_REFUSAL_HEADER } from "../lib/workflow-budget"; +import type { CapturedAdmissionPolicy } from "../types/admission-policy"; +import type { DataPlaneAdmission } from "./auth-cors"; import type { NativeFinalLog } from "./native-final-log"; import { linkRequestSessionLane } from "./request-log-conversation"; @@ -26,6 +29,15 @@ export function internalChatRequest(req: Request, chatJson: string): Request { return internal; } +/** The request-log and admission identity a native handler passes to the inner Chat path. */ +export interface NativeLogIds { + requestId: string; + start: number; + turnAdmissionLease?: AdmissionLease; + admission?: DataPlaneAdmission; + advisorAdmissionPolicy?: CapturedAdmissionPolicy; +} + /** Upper bound for the retry advice a native surface passes on. */ export const NATIVE_MAX_RETRY_AFTER_SECONDS = 3600; diff --git a/src/server/ollama-inbound.ts b/src/server/ollama-inbound.ts index c454cbb3bda..c3358789b2d 100644 --- a/src/server/ollama-inbound.ts +++ b/src/server/ollama-inbound.ts @@ -11,8 +11,6 @@ import { OllamaCodecError, consumeOllamaChatChunk, createOllamaStreamState, olla import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; import type { OcxConfig } from "../types"; import type { DataPlaneAdmission } from "./auth-cors"; -import type { CapturedAdmissionPolicy } from "../types/admission-policy"; -import type { AdmissionLease } from "../lib/admission"; import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; import { handleChatCompletions } from "./chat-completions"; import { VERSION } from "./management-api"; @@ -26,6 +24,7 @@ import { nativeRefusalParts, nativeRetryAfter, streamNativeFromChat, + type NativeLogIds, } from "./native-chat-bridge"; import { createNativeFinalLog, type NativeFinalLog } from "./native-final-log"; import { findOllamaRoute, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy"; @@ -90,13 +89,7 @@ export async function handleOllamaShow(config: OcxConfig, req: Request, admissio return Response.json({ details: {}, model_info: {}, capabilities: ["completion"] }); } -export interface OllamaLogIds { - requestId: string; - start: number; - turnAdmissionLease?: AdmissionLease; - admission?: DataPlaneAdmission; - advisorAdmissionPolicy?: CapturedAdmissionPolicy; -} +export type OllamaLogIds = NativeLogIds; function failBeforeInner(ids: OllamaLogIds, logCtx: RequestLogContext, status: number, message: string): Response { addFinalRequestLog(ids.requestId, ids.start, logCtx, status, { closeReason: "non_stream" }); From c870f33522fb77eaedce8309930b7b840ad078ca Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:16:44 -0500 Subject: [PATCH 4/5] test(server): cover Gemini-compatible inbound routes and codec Pins list and lookup, SSE and JSON-array streaming, buffered answers on /v1beta and /v1, x-goog-api-key and ?key= admission, tool calls, Gemini error bodies, 501/405 and an unchanged GET /v1/models. --- .../test-layout/layout-server-inbound.json | 2 + structure/INDEX.md | 6 + structure/data-planes/gemini-inbound.md | 59 +++++ structure/manifest.json | 13 + tests/fixtures/test-layout-expected.json | 3 +- .../responses/responses-gemini-codec.test.ts | 120 +++++++++ tests/server/server-gemini-inbound.test.ts | 237 ++++++++++++++++++ 7 files changed, 439 insertions(+), 1 deletion(-) create mode 100644 structure/data-planes/gemini-inbound.md create mode 100644 tests/responses/responses-gemini-codec.test.ts create mode 100644 tests/server/server-gemini-inbound.test.ts diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index ea06db0ab22..e3e83d8221e 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -13,8 +13,10 @@ "server-ollama-inbound.test.ts": "server", "server-ollama-inbound-lifecycle.test.ts": "server", "server-ollama-inbound-errors.test.ts": "server", + "server-gemini-inbound.test.ts": "server", "protocol-trace-suppression.test.ts": "server", "responses-ollama-codec.test.ts": "responses", + "responses-gemini-codec.test.ts": "responses", "messages-error-normalization.test.ts": "claude-integration", "messages-header-normalization.test.ts": "claude-integration", "messages-lane-errors.test.ts": "claude-integration", diff --git a/structure/INDEX.md b/structure/INDEX.md index 2bea8d6e528..32f217efe64 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -68,6 +68,7 @@ The wire surfaces a client actually talks to. | [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md) | Chat Completions inbound, Anthropic-shaped clients, and JSON-upstream streaming clients. | | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | Physical-adapter tool-loading projections (Responses additional_tools and the Chat use_loaded_tool dispatcher with its response rewrite), preserved catalogs, fallback exclusions and opt-in prerequisites. | | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | Ollama-shaped version/tags/show/chat/generate routes translated onto Chat Completions, their admission, native error shape and final request-log ownership. | +| [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | Gemini-shaped models/generateContent/streamGenerateContent routes translated onto Chat Completions, the x-goog-api-key and ?key= credential move, the native error shape, SSE and JSON-array streaming, and the Chat bridge shared with the Ollama inbound. | | [`data-planes/error-detail.md`](data-planes/error-detail.md) | Closed error codes, upstream condition classification, numeric quota reset, closed failure detail, service tier and model identity bounds on request-log rows; response metadata header normalization and the client Retry-After format. Chat client error envelopes, literal tables, proxy-authored message provenance, collector verdicts and internal evidence channels; fixed undeclared-tool refusals, producer-owned incomplete-event origins and constructor-bounded destination labels, branded original client selectors, bounded combo exclusions and fixed retry-evidence diagnostics. Original model labels on synthetic terminal envelopes and compact/Messages ingress handoffs. Messages error envelopes, construction-registered fixed local-refusal guidance, sliced outcome comparisons and baseline client recovery outcomes across special codes and catch returns, non-2xx passthrough envelopes and unchanged 2xx passthrough bodies and original collector evidence and error-event identity, overflow/native-stream golden parity and normalized Anthropic response headers with full-fraction reset dates and success media types. | | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | The reasoning_details carrier that lets Chat Completions clients round-trip signed Anthropic thinking across tool steps (#7429). | | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | Shared protocol vocabulary, declared feature dispositions, the ingress-by-upstream baseline, plan/trace shapes, and protocol settings. | @@ -397,6 +398,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/oauth/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/plugins/` | [`ops/plugins.md`](ops/plugins.md) | | `src/protocols/` | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | +| `src/protocols/codecs/gemini.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/protocols/codecs/ollama.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/protocols/encoders/adapter-events.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/protocols/encoders/messages.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | @@ -450,11 +452,14 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/capture-admission-policy.ts` | [`advisor.md`](advisor.md) | | `src/server/claude-messages.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md)
[`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/context-history.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/server/gemini-inbound.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | +| `src/server/gemini-native-paths.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/gui-pair-delivery.ts` | [`remote-link.md`](remote-link.md) | | `src/server/hub-usage.ts` | [`usage-client-attribution.md`](usage-client-attribution.md) | | `src/server/images.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/index.ts` | [`adapters/compatibility-lab.md`](adapters/compatibility-lab.md) | | `src/server/index/` | [`usage-client-attribution.md`](usage-client-attribution.md) | +| `src/server/index/gemini-routes.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/index/link-management.ts` | [`remote-link.md`](remote-link.md) | | `src/server/index/link-websocket-limits.ts` | [`remote-link.md`](remote-link.md) | | `src/server/index/link-websocket.ts` | [`remote-link.md`](remote-link.md) | @@ -488,6 +493,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/messages-response-headers.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/server/messages-shared.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/server/messages-sse-error-filter.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | +| `src/server/native-chat-bridge.ts` | [`data-planes/gemini-inbound.md`](data-planes/gemini-inbound.md) | | `src/server/native-final-log.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/ollama-inbound.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/ollama-native-paths.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md new file mode 100644 index 00000000000..5c51e25b022 --- /dev/null +++ b/structure/data-planes/gemini-inbound.md @@ -0,0 +1,59 @@ +# Gemini-Compatible Inbound + +Gemini clients (the google-genai SDK with a custom base URL, `agy` with its `genai` gateway wire +protocol, `GOOGLE_GEMINI_BASE_URL`) can use configured provider routes through the Gemini REST +shape. Like the [Ollama inbound](ollama-inbound.md) it is a translation onto the +[Chat Completions inbound](inbound-compat.md) path and never talks to Google itself. + +`src/server/gemini-native-paths.ts` classifies a path: `GET /v1beta/models`, +`GET /v1beta/models/{model}`, and `POST /v1beta/models/{model}:{method}` or +`POST /v1/models/{model}:{method}` for `generateContent`, `streamGenerateContent`, `countTokens`, +`embedContent` and `batchEmbedContents`. The model may contain `/` (a `provider/model` selector), +may be URL-encoded, and may carry a doubled `models/` prefix. `/v1/` counts only with a known +`:method`, so OpenCodex's own `GET /v1/models` and every other `/v1/*` route are untouched. A wrong +HTTP method on a recognised path is a native 405 with `Allow`. `src/server/index/gemini-routes.ts` +matches in `serve-options.ts` next to the Ollama arm. The routes are data plane only: +`managementIngressRouteAllowed` in `src/server/index.ts` denies them and all of `/v1beta/`, the +unauthenticated listener allowlists do not list them, and the package-tree fence answers them in +the Gemini error shape. OPTIONS takes data-plane origin policy. + +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 +wins), and drops it from the URL and headers, so admission sees the usual proxy key and the key is +never logged or forwarded. The idle-timeout override receives the original request. Generation takes +the Chat admission (drain, key, origin, caller session, active turn, workflow, raised body via +`isGeminiGenerationPath` in `inbound-body-admission.ts`); the list and lookup routes take the +model-discovery admission `/v1/models` uses. `countTokens`, `embedContent` and +`batchEmbedContents` answer 501 `UNIMPLEMENTED` after admission. + +The catalog is 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. + +`src/protocols/codecs/gemini.ts` maps `contents`, `systemInstruction`, base64 image `inlineData`, +`functionDeclarations` and `toolConfig`, `functionCall` and `functionResponse` (matched by id, then by +name), and `generationConfig` (including `thinkingConfig` as reasoning effort and a JSON response +schema) onto one Chat body, reading camelCase or snake_case. Hosted Gemini tools are ignored. A field +that would change the answer (`candidateCount` other than 1, non-image inline data, file parts, +more than 1,024 function calls) is a 400. Responses map Chat finish `stop` and `tool_calls` to +`STOP`, `length` to `MAX_TOKENS` and `content_filter` to `SAFETY`; an unknown or missing finish is an +error, never a success. A streamed tool call is accumulated and emitted as one whole `functionCall` +part. Usage becomes `usageMetadata`, with reasoning tokens reported as `thoughtsTokenCount`. + +`src/server/gemini-inbound.ts` owns delivery. With `alt=sse` a stream is `data: \r\n\r\n` +frames; without it, one streamed JSON array. The closing chunk (finish reason and usage) is emitted +only after the Chat stream reached EOF and the inner path settled, through the shared pump in +`src/server/native-chat-bridge.ts` that Ollama also uses: identity-only internal Chat request, +Retry-After and refusal vocabulary, fixed error text by status, one request-log row committed exactly +once through [`native-final-log`](ollama-inbound.md#final-request-log), a 499 row for a client that +leaves. Errors are `{ "error": { "code", "message", "status" } }` with `status` chosen by HTTP code; +the message is fixed by code and upstream-authored text is never forwarded. Inner Chat runs with +`suppressProtocolTrace`, so no Chat protocol identity is persisted for these rows. + +## Coverage + +`tests/server/server-gemini-inbound.test.ts` (list and lookup, SSE and JSON-array streams, buffered +answers on `/v1beta` and `/v1`, `x-goog-api-key` and `?key=` admission, tool calls, errors, 501 and +405, `/v1/models` unchanged), `tests/responses/responses-gemini-codec.test.ts` (request and +response mapping, streaming translation), plus the Ollama tests that pin the shared bridge. diff --git a/structure/manifest.json b/structure/manifest.json index efe4a5bbca4..d4bb0c74da2 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -541,6 +541,19 @@ "src/protocols/codecs/ollama.ts" ] }, + { + "path": "data-planes/gemini-inbound.md", + "tier": 3, + "title": "Gemini-Compatible Inbound", + "scope": "Gemini-shaped models/generateContent/streamGenerateContent routes translated onto Chat Completions, the x-goog-api-key and ?key= credential move, the native error shape, SSE and JSON-array streaming, and the Chat bridge shared with the Ollama inbound.", + "documents": [ + "src/server/gemini-inbound.ts", + "src/server/gemini-native-paths.ts", + "src/server/native-chat-bridge.ts", + "src/server/index/gemini-routes.ts", + "src/protocols/codecs/gemini.ts" + ] + }, { "path": "data-planes/error-detail.md", "tier": 3, diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ebfabf37355..fa313fc0890 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -963,7 +963,8 @@ "inbound-body-budget.test.ts": "server", "admitted-http-turn.test.ts": "server", "server-native-final-log.test.ts": "server", "server-ollama-route-policy.test.ts": "server", "server-ollama-inbound.test.ts": "server", "server-ollama-inbound-lifecycle.test.ts": "server", "server-ollama-inbound-errors.test.ts": "server", - "protocol-trace-suppression.test.ts": "server", "responses-ollama-codec.test.ts": "responses", + "server-gemini-inbound.test.ts": "server", + "protocol-trace-suppression.test.ts": "server", "responses-ollama-codec.test.ts": "responses", "responses-gemini-codec.test.ts": "responses", "config-concurrent-inbound-body.test.ts": "config", "inline-think-boundaries.test.ts": "adapters/openai", "input-admission.test.ts": "server", "install-scripts.test.ts": "ci-workflows", "installed-gate-drivers.test.ts": "ci-workflows", diff --git a/tests/responses/responses-gemini-codec.test.ts b/tests/responses/responses-gemini-codec.test.ts new file mode 100644 index 00000000000..48296631791 --- /dev/null +++ b/tests/responses/responses-gemini-codec.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, test } from "bun:test"; +import { + GeminiCodecError, + MAX_GEMINI_TOOL_CALLS, + chatToGeminiResponse, + consumeGeminiChatChunk, + createGeminiStreamState, + geminiStreamTerminal, + geminiToChat, +} from "../../src/protocols/codecs/gemini"; + +const png = "iVBORw0KGgo="; +const declaration = { name: "find", description: "Find", parameters: { type: "OBJECT", properties: { q: { type: "STRING" } }, required: ["q"] } }; + +describe("Gemini codec request mapping", () => { + test("projects system, text, image, tools, function call and response onto Chat", () => { + const result = geminiToChat("fx/m1", { + systemInstruction: { parts: [{ text: "rules" }] }, + contents: [ + { role: "user", parts: [{ text: "look" }, { inlineData: { mimeType: "image/png", data: png } }] }, + { role: "model", parts: [{ text: "checking" }, { functionCall: { name: "find", args: { q: "a" } } }] }, + { role: "user", parts: [{ functionResponse: { name: "find", response: { hit: true } } }] }, + ], + tools: [{ functionDeclarations: [declaration] }], + toolConfig: { functionCallingConfig: { mode: "ANY", allowedFunctionNames: ["find"] } }, + generationConfig: { temperature: 0.2, topP: 0.9, maxOutputTokens: 50, stopSequences: ["end"], thinkingConfig: { thinkingLevel: "HIGH" } }, + }, true); + expect(result).toEqual({ + model: "fx/m1", + stream: true, + messages: [ + { role: "system", content: "rules" }, + { role: "user", content: [{ type: "text", text: "look" }, { type: "image_url", image_url: { url: `data:image/png;base64,${png}` } }] }, + { role: "assistant", content: "checking", tool_calls: [{ id: "call_gemini_1_1", type: "function", function: { name: "find", arguments: '{"q":"a"}' } }] }, + { role: "tool", tool_call_id: "call_gemini_1_1", content: '{"hit":true}' }, + ], + tools: [{ type: "function", function: { name: "find", description: "Find", parameters: { type: "object", properties: { q: { type: "string" } }, required: ["q"] } } }], + tool_choice: { type: "function", function: { name: "find" } }, + temperature: 0.2, + top_p: 0.9, + max_tokens: 50, + stop: ["end"], + reasoning_effort: "high", + }); + }); + + test("accepts snake_case fields and a plain system string", () => { + const result = geminiToChat("m", { system_instruction: "be brief", contents: [{ role: "user", parts: [{ text: "hi" }] }], generation_config: { max_output_tokens: 5 } }, false); + expect(result).toEqual({ model: "m", stream: false, messages: [{ role: "system", content: "be brief" }, { role: "user", content: "hi" }], max_tokens: 5 }); + }); + + test("rejects requests that would silently change the answer", () => { + const user = [{ role: "user", parts: [{ text: "hi" }] }]; + expect(() => geminiToChat("m", { contents: user, generationConfig: { candidateCount: 2 } }, false)).toThrow(GeminiCodecError); + expect(() => geminiToChat("m", { contents: [{ role: "user", parts: [{ inlineData: { mimeType: "audio/wav", data: png } }] }] }, false)).toThrow(GeminiCodecError); + expect(() => geminiToChat("m", { contents: [{ role: "user", parts: [{ functionResponse: { name: "ghost", response: {} } }] }] }, false)).toThrow("Unmatched function response"); + expect(() => geminiToChat("m", { contents: "hi" }, false)).toThrow(GeminiCodecError); + }); + + test("bounds function calls in one request", () => { + const parts = Array.from({ length: MAX_GEMINI_TOOL_CALLS + 1 }, (_, i) => ({ functionCall: { id: `c${i}`, name: "f", args: {} } })); + expect(() => geminiToChat("m", { contents: [{ role: "model", parts }] }, false)).toThrow("Too many function calls"); + }); +}); + +const usage = { prompt_tokens: 5, completion_tokens: 4, total_tokens: 9, completion_tokens_details: { reasoning_tokens: 1 } }; + +describe("Gemini codec response mapping", () => { + test("buffered completion carries text, thought, tool call, finish and usage", () => { + const body = chatToGeminiResponse("fx/m1", { + choices: [{ index: 0, finish_reason: "tool_calls", message: { role: "assistant", content: "Hi", reasoning_content: "hmm", tool_calls: [{ id: "call_1", type: "function", function: { name: "find", arguments: '{"q":"a"}' } }] } }], + usage, + }); + expect(body).toEqual({ + candidates: [{ content: { role: "model", parts: [{ text: "hmm", thought: true }, { text: "Hi" }, { functionCall: { id: "call_1", name: "find", args: { q: "a" } } }] }, finishReason: "STOP", index: 0 }], + usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 3, totalTokenCount: 9, thoughtsTokenCount: 1 }, + modelVersion: "fx/m1", + }); + }); + + test("length maps to MAX_TOKENS and an unfinished completion is an error", () => { + const choice = (finish: unknown) => ({ choices: [{ index: 0, finish_reason: finish, message: { role: "assistant", content: "x" } }] }); + expect((chatToGeminiResponse("m", choice("length")).candidates as any[])[0].finishReason).toBe("MAX_TOKENS"); + expect((chatToGeminiResponse("m", choice("content_filter")).candidates as any[])[0].finishReason).toBe("SAFETY"); + expect(() => chatToGeminiResponse("m", choice("mystery"))).toThrow(); + expect(() => chatToGeminiResponse("m", choice(null))).toThrow(); + }); + + test("a stream emits text and thought deltas, then one complete tool call, then the terminal with usage", () => { + const state = createGeminiStreamState("fx/m1"); + const chunk = (delta: Record, finish: unknown = null, extra: Record = {}) => ({ choices: [{ index: 0, delta, finish_reason: finish }], ...extra }); + const records = [ + ...consumeGeminiChatChunk(state, chunk({ role: "assistant", reasoning_content: "think" })), + ...consumeGeminiChatChunk(state, chunk({ content: "Hel" })), + ...consumeGeminiChatChunk(state, chunk({ content: "lo" })), + ...consumeGeminiChatChunk(state, chunk({ tool_calls: [{ index: 0, id: "call_9", function: { name: "find", arguments: '{"q"' } }] })), + ...consumeGeminiChatChunk(state, chunk({ tool_calls: [{ index: 0, function: { arguments: ':"a"}' } }] })), + ]; + expect(geminiStreamTerminal(state)).toBeUndefined(); + records.push(...consumeGeminiChatChunk(state, chunk({}, "tool_calls"))); + expect(consumeGeminiChatChunk(state, { choices: [], usage })).toEqual([]); + const parts = records.map(record => (record.candidates as any[])[0].content.parts[0]); + expect(parts).toEqual([ + { text: "think", thought: true }, { text: "Hel" }, { text: "lo" }, + { functionCall: { id: "call_9", name: "find", args: { q: "a" } } }, + ]); + expect(geminiStreamTerminal(state)).toEqual({ + candidates: [{ content: { role: "model", parts: [{ text: "" }] }, finishReason: "STOP", index: 0 }], + usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 3, totalTokenCount: 9, thoughtsTokenCount: 1 }, + modelVersion: "fx/m1", + }); + }); + + test("a stream error chunk or chunk after finish fails the stream", () => { + const state = createGeminiStreamState("m"); + expect(() => consumeGeminiChatChunk(state, { error: { message: "x" } })).toThrow(); + consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "a" }, finish_reason: "stop" }] }); + expect(() => consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "b" } }] })).toThrow(); + }); +}); diff --git a/tests/server/server-gemini-inbound.test.ts b/tests/server/server-gemini-inbound.test.ts new file mode 100644 index 00000000000..8c4e2a97b74 --- /dev/null +++ b/tests/server/server-gemini-inbound.test.ts @@ -0,0 +1,237 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { clearRequestLogsForTests, getRequestLogEntries } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const DATA_TOKEN = "ocx_data_geminifixture"; +const ADMIN_TOKEN = "admin-secret-for-gemini"; +const PROVIDER_KEY = "provider-fixture-key"; +const saved = { home: process.env.OPENCODEX_HOME, data: process.env.OPENCODEX_API_AUTH_TOKEN, admin: process.env.OPENCODEX_ADMIN_AUTH_TOKEN }; +let home = ""; +let mode: "text" | "tools" | "error400" = "text"; +let seen: { auth: string | null; url: string; body: Record }[] = []; +let upstream: ReturnType; + +const chunk = (choices: unknown[], extra: Record = {}) => + "data: " + JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 1, model: "m1", choices, ...extra }) + "\n\n"; + +beforeAll(() => { + upstream = Bun.serve({ port: 0, async fetch(req) { + if (req.method === "GET") return Response.json({ object: "list", data: [{ id: "m1", object: "model" }] }); + const body = await req.json() as Record; + seen.push({ auth: req.headers.get("authorization"), url: req.url, body }); + if (mode === "error400") return Response.json({ error: { message: "fixture upstream rejected the request", type: "invalid_request_error" } }, { status: 400 }); + const usage = { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }; + const toolCall = { id: "call_fixture", type: "function", function: { name: "lookup", arguments: "{\"q\":\"x\"}" } }; + const finish = mode === "tools" ? "tool_calls" : "stop"; + if (body.stream !== true) { + const message = mode === "tools" ? { role: "assistant", content: null, tool_calls: [toolCall] } : { role: "assistant", content: "Hello" }; + return Response.json({ id: "chatcmpl-fixture", object: "chat.completion", created: 1, model: "m1", choices: [{ index: 0, message, finish_reason: finish }], usage }); + } + const frames = mode === "tools" + ? [chunk([{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, ...toolCall }] } }])] + : [chunk([{ index: 0, delta: { role: "assistant", content: "Hel" } }]), chunk([{ index: 0, delta: { content: "lo" } }])]; + frames.push(chunk([{ index: 0, delta: {}, finish_reason: finish }]), chunk([], { usage }), "data: [DONE]\n\n"); + return new Response(frames.join(""), { headers: { "content-type": "text/event-stream" } }); + } }); +}); +afterAll(() => { upstream.stop(true); }); + +function config(remote = false): OcxConfig { + return { + port: 0, + // A public bind is what makes the data-plane key mandatory. + ...(remote ? { hostname: "0.0.0.0" } : {}), + defaultProvider: "fx", + providers: { fx: { adapter: "openai-chat", baseUrl: upstream.url.origin + "/v1", authMode: "key", apiKey: PROVIDER_KEY, allowPrivateNetwork: true, models: ["m1"] }, off: { adapter: "openai-chat", baseUrl: "https://off.example/v1", authMode: "key", apiKey: "fixture", models: ["m1"], disabled: true } }, + } as OcxConfig; +} + +// The spend ledger binds one state directory per process, so the whole file shares one home. +beforeAll(() => { + home = mkdtempSync(join(tmpdir(), "ocx-gemini-inbound-")); + process.env.OPENCODEX_HOME = home; + process.env.OPENCODEX_API_AUTH_TOKEN = DATA_TOKEN; + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = ADMIN_TOKEN; +}); +beforeEach(() => { + mode = "text"; + seen = []; + clearRequestLogsForTests(); + saveConfig(config()); +}); +afterAll(() => { + for (const [key, value] of [["OPENCODEX_HOME", saved.home], ["OPENCODEX_API_AUTH_TOKEN", saved.data], ["OPENCODEX_ADMIN_AUTH_TOKEN", saved.admin]] as const) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + if (home) removeTreeWithRetry(home); + home = ""; +}); + +// startServer hydrates earlier rows from disk, so a test counts only the rows it wrote. +let earlierRows = new Set(); +const newRows = () => getRequestLogEntries().filter(entry => !earlierRows.has(entry.requestId)); +async function withServer(run: (base: URL) => Promise): Promise { + const server = startServer(0); + earlierRows = new Set(getRequestLogEntries().map(entry => entry.requestId)); + try { await run(server.url); } finally { await server.stop(true); } +} + +const googKey = { "x-goog-api-key": DATA_TOKEN }; +const post = (base: URL, path: string, body: unknown, headers: Record = googKey) => + fetch(new URL(path, base), { method: "POST", headers: { "content-type": "application/json", ...headers }, body: typeof body === "string" ? body : JSON.stringify(body) }); +const request = (extra: Record = {}) => ({ contents: [{ role: "user", parts: [{ text: "hi" }] }], ...extra }); +const sseRecords = async (res: Response) => (await res.text()).split("\r\n\r\n").filter(Boolean).map(frame => { + expect(frame.startsWith("data: ")).toBe(true); + return JSON.parse(frame.slice("data: ".length)) as Record; +}); +const textOf = (records: Record[]) => records.flatMap(record => record.candidates?.[0]?.content?.parts ?? []).map((part: { text?: string }) => part.text ?? "").join(""); + +describe("Gemini-compatible inbound routes", () => { + test("model list and point lookup describe configured routes only", async () => { + await withServer(async base => { + const list = await fetch(new URL("/v1beta/models", base), { headers: googKey }); + expect(list.status).toBe(200); + expect(await list.json()).toEqual({ models: [{ name: "models/fx/m1", displayName: "fx/m1", supportedGenerationMethods: ["generateContent", "streamGenerateContent"] }] }); + for (const path of ["/v1beta/models/fx/m1", "/v1beta/models/models/fx/m1", "/v1beta/models/fx%2Fm1"]) { + const one = await fetch(new URL(path, base), { headers: googKey }); + expect(one.status).toBe(200); + expect(await one.json()).toMatchObject({ name: "models/fx/m1" }); + } + const missing = await fetch(new URL("/v1beta/models/fx/absent", base), { headers: googKey }); + expect(missing.status).toBe(404); + expect(await missing.json()).toEqual({ error: { code: 404, message: "model not found", status: "NOT_FOUND" } }); + }); + }); + + 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 => { + const res = await post(base, "/v1beta/models/fx/m1:streamGenerateContent?alt=sse", request({ systemInstruction: { parts: [{ text: "rules" }] } })); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/event-stream"); + const records = await sseRecords(res); + expect(textOf(records)).toBe("Hello"); + expect(records.at(-1)).toMatchObject({ candidates: [{ finishReason: "STOP" }], usageMetadata: { promptTokenCount: 5, totalTokenCount: 7 } }); + expect(records.filter(record => record.candidates?.[0]?.finishReason)).toHaveLength(1); + expect(seen).toHaveLength(1); + expect(seen[0]!.auth).toBe("Bearer " + PROVIDER_KEY); + expect(seen[0]!.body).toMatchObject({ model: "m1", stream: true, messages: [{ role: "system", content: "rules" }, { role: "user", content: "hi" }] }); + await Bun.sleep(20); + expect(newRows()).toHaveLength(1); + expect(newRows()[0]!.status).toBe(200); + }); + }); + + test("the ?key= query credential admits the request and is never forwarded", async () => { + saveConfig(config(true)); + await withServer(async base => { + const res = await post(base, `/v1beta/models/fx/m1:generateContent?key=${DATA_TOKEN}`, request(), {}); + expect(res.status).toBe(200); + await res.text(); + expect(seen).toHaveLength(1); + expect(seen[0]!.url).not.toContain(DATA_TOKEN); + expect(seen[0]!.auth).toBe("Bearer " + PROVIDER_KEY); + for (const headers of [{}, { "x-goog-api-key": "wrong-key" }]) { + const refused = await post(base, "/v1beta/models/fx/m1:generateContent", request(), headers); + expect(refused.status).toBe(401); + expect(await refused.json()).toEqual({ error: { code: 401, message: "opencodex API key required", status: "UNAUTHENTICATED" } }); + } + const list = await fetch(new URL("/v1beta/models", base)); + expect(list.status).toBe(401); + expect(seen).toHaveLength(1); + }); + }); + + test("streaming without alt=sse is one streamed JSON array", async () => { + await withServer(async base => { + const res = await post(base, "/v1beta/models/fx/m1:streamGenerateContent", request()); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("application/json"); + const array = JSON.parse(await res.text()) as Record[]; + expect(Array.isArray(array)).toBe(true); + expect(textOf(array)).toBe("Hello"); + expect(array.at(-1)).toMatchObject({ candidates: [{ finishReason: "STOP" }], usageMetadata: { promptTokenCount: 5 } }); + }); + }); + + test("buffered generateContent answers on /v1beta and on /v1 with an encoded model", async () => { + await withServer(async base => { + for (const path of ["/v1beta/models/fx/m1:generateContent", "/v1/models/fx%2Fm1:generateContent"]) { + const res = await post(base, path, request()); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + candidates: [{ content: { role: "model", parts: [{ text: "Hello" }] }, finishReason: "STOP", index: 0 }], + usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 2, totalTokenCount: 7 }, + modelVersion: "fx/m1", + }); + } + expect(seen.map(call => call.body.stream)).toEqual([false, false]); + await Bun.sleep(20); + expect(newRows()).toHaveLength(2); + }); + }); + + test("a streamed tool call arrives as one complete functionCall part", async () => { + mode = "tools"; + await withServer(async base => { + const tools = [{ functionDeclarations: [{ name: "lookup", description: "find", parameters: { type: "OBJECT", properties: { q: { type: "STRING" } } } }] }]; + const records = await sseRecords(await post(base, "/v1beta/models/fx/m1:streamGenerateContent?alt=sse", request({ tools }))); + const calls = records.flatMap(record => record.candidates?.[0]?.content?.parts ?? []).filter((part: Record) => part.functionCall); + expect(calls).toEqual([{ functionCall: { id: "call_fixture", name: "lookup", args: { q: "x" } } }]); + expect(records.at(-1)).toMatchObject({ candidates: [{ finishReason: "STOP" }] }); + expect(seen[0]!.body.tools).toEqual([{ type: "function", function: { name: "lookup", description: "find", parameters: { type: "object", properties: { q: { type: "string" } } } } }]); + }); + }); + + test("bad input and unknown models are Gemini errors before any send", async () => { + await withServer(async base => { + const badJson = await post(base, "/v1beta/models/fx/m1:generateContent", "{not json"); + expect(badJson.status).toBe(400); + expect(await badJson.json()).toMatchObject({ error: { code: 400, status: "INVALID_ARGUMENT" } }); + const badShape = await post(base, "/v1beta/models/fx/m1:generateContent", { contents: "hi" }); + expect(badShape.status).toBe(400); + const unknown = await post(base, "/v1beta/models/off/m1:generateContent", request()); + expect(unknown.status).toBe(404); + expect(await unknown.json()).toMatchObject({ error: { code: 404, status: "NOT_FOUND" } }); + expect(seen).toHaveLength(0); + expect(newRows()).toHaveLength(3); + }); + }); + + test("an upstream refusal keeps its status with a fixed message", async () => { + mode = "error400"; + await withServer(async base => { + const res = await post(base, "/v1beta/models/fx/m1:generateContent", request()); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ error: { code: 400, message: "request rejected", status: "INVALID_ARGUMENT" } }); + }); + }); + + test("unsupported methods answer 501 and wrong HTTP methods 405", async () => { + await withServer(async base => { + for (const method of ["countTokens", "embedContent", "batchEmbedContents"]) { + const res = await post(base, `/v1beta/models/fx/m1:${method}`, {}); + expect(res.status).toBe(501); + expect(await res.json()).toMatchObject({ error: { code: 501, status: "UNIMPLEMENTED" } }); + } + const wrong = await fetch(new URL("/v1beta/models/fx/m1:generateContent", base), { headers: googKey }); + expect(wrong.status).toBe(405); + expect(wrong.headers.get("allow")).toBe("POST"); + expect(seen).toHaveLength(0); + }); + }); + + test("OpenCodex's own /v1/models is untouched", async () => { + await withServer(async base => { + const res = await fetch(new URL("/v1/models", base), { headers: { authorization: "Bearer " + DATA_TOKEN } }); + expect(res.status).toBe(200); + expect(await res.json()).not.toHaveProperty("models"); + }); + }); +}); From e02c54b6ab2a052a99419cd582f79be57c40773f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:02:57 -0500 Subject: [PATCH 5/5] fix(gemini-inbound): admit the Gemini wire on the unauthenticated loopback listener --- src/server/index.ts | 6 +++++- structure/data-planes/gemini-inbound.md | 8 +++++--- structure/runtime.md | 2 +- tests/server/loopback-listener-admission.test.ts | 8 ++++++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/server/index.ts b/src/server/index.ts index 4ea4157b390..ea60fb98011 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -5,7 +5,7 @@ import { normalizeBindHostname } from "./bind-host"; import { configureInboundBodyBudget } from "./inbound-body-admission"; import { createAdmittedHttpTurn } from "./admitted-http-turn"; import { isOllamaNativePath } from "./ollama-native-paths"; -import { isGeminiNativePath } from "./gemini-native-paths"; +import { isGeminiNativePath, parseGeminiNativePath } from "./gemini-native-paths"; import { buildWarmupCompletionFrames, buildWsErrorFrame, @@ -419,6 +419,10 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe return req.method === "POST"; } if (path === "/v1/models") return req.method === "GET"; + // Gemini wire (#8732): `ocx connect agy` points the CLI at this socket. Same admission as the + // chat wire it is translated into; each Gemini path admits only its own HTTP method. + const gemini = parseGeminiNativePath(path); + if (gemini) return req.method === gemini.httpMethod; // Realtime voice — a directly-spawned `codex app-server` needs these for desktop voice // the same way it needs /v1/responses. Two shapes, same trust model as /v1/responses: // - standalone sessions (codex-rs thread/realtime/start, WebSocket transport): diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 5c51e25b022..0fadb4cff0c 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -13,9 +13,11 @@ may be URL-encoded, and may carry a doubled `models/` prefix. `/v1/` counts only `:method`, so OpenCodex's own `GET /v1/models` and every other `/v1/*` route are untouched. A wrong HTTP method on a recognised path is a native 405 with `Allow`. `src/server/index/gemini-routes.ts` matches in `serve-options.ts` next to the Ollama arm. The routes are data plane only: -`managementIngressRouteAllowed` in `src/server/index.ts` denies them and all of `/v1beta/`, the -unauthenticated listener allowlists do not list them, and the package-tree fence answers them in -the Gemini error shape. OPTIONS takes data-plane origin policy. +`managementIngressRouteAllowed` in `src/server/index.ts` denies them and all of `/v1beta/`, and the +package-tree fence answers them in the Gemini error shape. The unauthenticated data-loopback +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. 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/runtime.md b/structure/runtime.md index 6598dab83f1..d0874942567 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -215,7 +215,7 @@ Enabled startup retains separate fresh ownership decisions. Explicit `sync` and The data-loopback socket serves a fixed data-plane allowlist: Responses and its compact sibling, the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, the realtime voice shapes, and the Anthropic and OpenAI chat wires the host's own local clients speak — `POST /v1/messages`, -`POST /v1/messages/count_tokens`, and `POST /v1/chat/completions`. It never serves `/api/*`, +`POST /v1/messages/count_tokens`, and `POST /v1/chat/completions` — plus the Gemini wire, each path with its own method. It never serves `/api/*`, `/healthz`, `/readyz`, or GUI routes, so local management discovery has to use an authenticated surface with a management credential. The hub-management socket is enabled only by `runtimeRole: "hub"` plus diff --git a/tests/server/loopback-listener-admission.test.ts b/tests/server/loopback-listener-admission.test.ts index ea3075085f7..ce073936dbc 100644 --- a/tests/server/loopback-listener-admission.test.ts +++ b/tests/server/loopback-listener-admission.test.ts @@ -118,6 +118,14 @@ describe("local client inference wires on the loopback listener (#4236)", () => ); }); + test("the Gemini wire is admitted per path with its own HTTP method", () => { + // `ocx connect agy` writes the loopback port, so without this entry every agy call 404s on a + // hub whose public listener binds a tailnet address. The handlers resolve admission from the + // receiving listener's policy, so this adds a wire, not a trust level. + expect(source).toContain("const gemini = parseGeminiNativePath(path);"); + expect(source).toContain("if (gemini) return req.method === gemini.httpMethod;"); + }); + test("no /api route joins the allowlist", () => { // Management discovery is the other destination contract (authenticated ingress). A // reviewer condition on #4236: `/api/*` must never appear on this listener.