Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(ai): GOOGLE_GENERATIVE_AI_BASE_URL override for native Gemini chat, expansion and embedding
garrytan53035aaafe8c
diff --git a/docs/ai-providers/google.md b/docs/ai-providers/google.mdnew file mode 100644index 0000000000..e5923e4b56--- /dev/null+++ b/docs/ai-providers/google.md@@ -0,0 +1,43 @@+# Google Gemini++GBrain calls Gemini natively for chat, query expansion and embeddings: model+strings `google:<model>`, such as `google:gemini-2.5-flash` for chat and+`google:gemini-embedding-2` for embeddings. Embedding models, dimensions and+pricing are in [embedding providers](../integrations/embedding-providers.md#google-gemini).++## Key setup++Set `GOOGLE_GENERATIVE_AI_API_KEY`, an AI Studio API key. `GEMINI_API_KEY` works as an alias+when the first variable is unset. You can also set `google_api_key` in `~/.gbrain/config.json`; a+real value in the environment wins over the config file.++## Base URL override++`GOOGLE_GENERATIVE_AI_BASE_URL` sends every native Gemini request to another+endpoint: chat, query expansion and embeddings. Use it for a metering or+logging proxy, such as an eval harness's spend proxy, or for a regional gateway.++```bash+export GOOGLE_GENERATIVE_AI_BASE_URL=http://127.0.0.1:8787+```++- **A URL with no version segment** gets `/v1beta` appended, matching the+ default `https://generativelanguage.googleapis.com/v1beta`. Requests then go+ to `<base>/v1beta/models/<model>:generateContent` (chat and expansion) and+ `:embedContent` / `:batchEmbedContents` (embeddings). A proxy that forwards+ the path upstream works unchanged.+- **A URL that already ends in a version** (`/v1`, `/v1beta`, `/v1alpha`) is+ used as written. Trailing slashes are trimmed.+- **The API key** still goes in the `x-goog-api-key` header, so the endpoint+ receives your key. Point it only at a proxy you control.+- **Unset or blank:** the SDK default is used, so nothing changes.++The file-plane equivalent is `provider_base_urls.google` in+`~/.gbrain/config.json`. The environment variable wins over it. A value merged+from a mounted brain's database never sets this URL, so a shared brain cannot+redirect your key; the same rule covers `ANTHROPIC_BASE_URL` and+`OPENAI_BASE_URL`.++Verify the override with one short request through the proxy, for example+`gbrain think "ping" --model google:gemini-2.5-flash`, and check that the proxy+logged a `/v1beta/models/gemini-2.5-flash:generateContent` call.diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex a1e4928a08..7d6cb66c73 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved. `GOOGLE_GENERATIVE_AI_BASE_URL` does the same for every native `createGoogleGenerativeAI` site (chat, expansion, embedding), appending `/v1beta` only when the URL names no version (`docs/ai-providers/google.md`; test `test/ai/google-base-url.test.ts` against a local fake Gemini server). `build-gateway-config.ts` folds file-plane `provider_base_urls.google` into that variable (env wins). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`) or the caller's own abort stops the chain; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts`.- `src/core/ai/sdk-warnings.ts` — AI SDK provider warnings to stderr (#5892). The gateway calls `installAiSdkWarningWriter()` when it loads, which sets `globalThis.AI_SDK_LOG_WARNINGS` to a writer with the `ai` logger signature (`{ warnings, provider, model }`) that prints each warning in the SDK's own wording to stderr and never the SDK's `console.info` banner, which landed on stdout and broke `--json` output (the claude-cli model's v2-compat notice fires on every process's first call). A user-set value (`false` or a function) is kept. Tests: `ai-sdk-warnings.test.ts`, `json-stdout-ai-warnings.serial.test.ts`.diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.mdindex e7a5c8535f..9caf513d1c 100644--- a/docs/integrations/embedding-providers.md+++ b/docs/integrations/embedding-providers.md@@ -81,7 +81,7 @@ The doctor distinguishes two repair paths:The main alternative to the Voyage default (its flexible-dim `text-embedding-3` models can keep an existing column width during a provider migration). Set `OPENAI_API_KEY`. Models: `text-embedding-3-large` (3072 max, 1536 default), `text-embedding-3-small` (1536). Matryoshka via the `dimensions` field — gbrain pins it from `embedding_dimensions` config so existing 1536-dim brains stay aligned across SDK upgrades.-Optional `OPENAI_BASE_URL` — point the native OpenAI provider at an OpenAI-compatible gateway. A bare host is normalized to carry the `/v1` suffix automatically (so `https://gw.example.com` and `https://gw.example.com/v1` both work); when unset, the SDK's default endpoint is untouched. With `OPENAI_BASE_URL` set, embedding does not require `OPENAI_API_KEY` — the override targets local OpenAI-compatible servers (LM Studio, vLLM) that ignore auth, so gbrain sends a placeholder key instead of refusing. `ANTHROPIC_BASE_URL` gets the same normalization for Anthropic chat/expansion calls.+Optional `OPENAI_BASE_URL` — point the native OpenAI provider at an OpenAI-compatible gateway. A bare host is normalized to carry the `/v1` suffix automatically (so `https://gw.example.com` and `https://gw.example.com/v1` both work); when unset, the SDK's default endpoint is untouched. With `OPENAI_BASE_URL` set, embedding does not require `OPENAI_API_KEY` — the override targets local OpenAI-compatible servers (LM Studio, vLLM) that ignore auth, so gbrain sends a placeholder key instead of refusing. `ANTHROPIC_BASE_URL` gets the same normalization for Anthropic chat/expansion calls; `GOOGLE_GENERATIVE_AI_BASE_URL` does the same for Gemini with `/v1beta` ([Google Gemini](../ai-providers/google.md)).### Voyage AI@@ -112,7 +112,7 @@ To switch an existing brain, run `gbrain migrate embeddings --to voyage:voyage-c### Google Gemini-Set `GOOGLE_GENERATIVE_AI_API_KEY` (the AI Studio public API key). Models: `gemini-embedding-2` (current, GA 2026-04-22) and `gemini-embedding-001`. Default 768 dims; Matryoshka up to 3072 (`--embedding-dimensions 1536` / `3072`). Cheap. The two models' vector spaces are not interchangeable — to move an existing brain from `-001` to `-2`, use `gbrain migrate embeddings --to google:gemini-embedding-2 --dim <N>`, not `config set`.+Set `GOOGLE_GENERATIVE_AI_API_KEY` (the AI Studio public API key). Models: `gemini-embedding-2` (current, GA 2026-04-22) and `gemini-embedding-001`. Default 768 dims; Matryoshka up to 3072 (`--embedding-dimensions 1536` / `3072`). Cheap. The two models' vector spaces are not interchangeable — to move an existing brain from `-001` to `-2`, use `gbrain migrate embeddings --to google:gemini-embedding-2 --dim <N>`, not `config set`. Optional `GOOGLE_GENERATIVE_AI_BASE_URL` points native Gemini chat, expansion and embedding requests at a proxy or gateway; a URL without a version segment gets `/v1beta`. See [Google Gemini](../ai-providers/google.md).GCP service-account / Vertex AI auth (Vertex ADC) is not supported; only the AI Studio API key path is wired.diff --git a/llms.txt b/llms.txtindex 32447f3102..344203305c 100644--- a/llms.txt+++ b/llms.txt@@ -48,6 +48,7 @@ Repo: https://github.com/garrytan/gbrain## AI providers+- [docs/ai-providers/google.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/google.md): Google Gemini: GOOGLE_GENERATIVE_AI_API_KEY (GEMINI_API_KEY alias), GOOGLE_GENERATIVE_AI_BASE_URL override for chat, expansion and embeddings (metering proxies, regional gateways), provider_base_urls.google.- [docs/ai-providers/llama-server-reranker.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/llama-server-reranker.md): Local reranker via llama.cpp --reranking: Qwen3-Reranker, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.- [docs/ai-providers/typesafe.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/typesafe.md): TypeSafe Jev: TYPESAFE_API_KEY (JEV_TYPESAFE_API_KEY alias), pinned vs alias models, Jev search reranker setup (#5178), pricing, limits, data handling and what never leaves the machine.diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex 5de99f1198..2c39e5cea8 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -217,6 +217,13 @@ export const SECTIONS: DocSection[] = [{heading: "AI providers",entries: [+ {+ title: "docs/ai-providers/google.md",+ description:+ "Google Gemini: GOOGLE_GENERATIVE_AI_API_KEY (GEMINI_API_KEY alias), GOOGLE_GENERATIVE_AI_BASE_URL override for chat, expansion and embeddings (metering proxies, regional gateways), provider_base_urls.google.",+ path: "docs/ai-providers/google.md",+ includeInFull: false,+ },{title: "docs/ai-providers/llama-server-reranker.md",description:diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.tsindex 278596b0c4..cc47b0afba 100644--- a/src/core/ai/build-gateway-config.ts+++ b/src/core/ai/build-gateway-config.ts@@ -4,8 +4,9 @@ import type { AIGatewayConfig } from './types.ts';import { mergedProviderEnv } from './provider-env.ts';/**- * #3350: fold FILE-plane `provider_base_urls.{anthropic,openai}` into the- * gateway env as `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL`, same shape as the+ * #3350: fold FILE-plane `provider_base_urls.{anthropic,openai,google}` into the+ * gateway env as `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` /+ * `GOOGLE_GENERATIVE_AI_BASE_URL`, same shape as the* credential folds (env wins for keys carrying a real value). Native* providers read their base URL exclusively from env via* `resolveNativeBaseUrl` (which also normalizes the `/v1` suffix), so before@@ -31,6 +32,7 @@ export function foldNativeBaseUrlsFromFilePlane(for (const [provider, envKey] of [['anthropic', 'ANTHROPIC_BASE_URL'],['openai', 'OPENAI_BASE_URL'],+ ['google', 'GOOGLE_GENERATIVE_AI_BASE_URL'],] as const) {const fileUrl = urls[provider];// Env wins: only fold when the env carries no real value.diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 247e3948d1..f2ef8604c3 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -400,20 +400,26 @@ export function applyOpenAICompatConfig(** Returns undefined when the env provides no base URL, so the SDK's own default* (which already includes `/v1`) is preserved untouched — the happy path is not- * altered. Google is intentionally NOT handled here: its native suffix is- * unproven (Gemini's OpenAI-compat route is `/v1beta/openai`), so it's deferred- * to a follow-up rather than risk a regression on a wrong assumption.+ * altered.+ *+ * Google (`GOOGLE_GENERATIVE_AI_BASE_URL`, used by native-google chat,+ * expansion and embedding): the SDK's default root is+ * `https://generativelanguage.googleapis.com/v1beta` and it appends+ * `/models/<id>:<method>`, so a URL with no version segment gets `/v1beta`+ * (a pass-through proxy then forwards the real path); a URL that already+ * names a version (`/v1`, `/v1beta`, `/v1alpha`) is kept as written.** @internal exported for tests.*/export function resolveNativeBaseUrl(- provider: 'anthropic' | 'openai',+ provider: 'anthropic' | 'openai' | 'google',cfg: AIGatewayConfig,): string | undefined {- const envKey = provider === 'anthropic' ? 'ANTHROPIC_BASE_URL' : 'OPENAI_BASE_URL';+ const envKey = provider === 'anthropic' ? 'ANTHROPIC_BASE_URL' : provider === 'openai' ? 'OPENAI_BASE_URL' : 'GOOGLE_GENERATIVE_AI_BASE_URL';const raw = cfg.env[envKey];if (!raw || !raw.trim()) return undefined;const trimmed = raw.trim().replace(/\/+$/, '');+ if (provider === 'google') return /\/v\d+[a-z]*$/i.test(trimmed) ? trimmed : `${trimmed}/v1beta`;return /\/v1$/.test(trimmed) ? trimmed : `${trimmed}/v1`;}@@ -1412,7 +1418,8 @@ function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayCon`Google embedding requires GOOGLE_GENERATIVE_AI_API_KEY.`,recipe.setup_hint,);- const client = createGoogleGenerativeAI({ apiKey });+ const baseURL = resolveNativeBaseUrl('google', cfg);+ const client = createGoogleGenerativeAI({ apiKey, ...(baseURL ? { baseURL } : {}) });return (client as any).textEmbeddingModel? (client as any).textEmbeddingModel(modelId): (client as any).embedding(modelId);@@ -2302,7 +2309,8 @@ function instantiateExpansion(recipe: Recipe, modelId: string, cfg: AIGatewayConcase 'native-google': {const apiKey = cfg.env.GOOGLE_GENERATIVE_AI_API_KEY;if (!apiKey) throw new AIConfigError(`Google expansion requires GOOGLE_GENERATIVE_AI_API_KEY.`, recipe.setup_hint);- return createGoogleGenerativeAI({ apiKey }).languageModel(modelId);+ const baseURL = resolveNativeBaseUrl('google', cfg);+ return createGoogleGenerativeAI({ apiKey, ...(baseURL ? { baseURL } : {}) }).languageModel(modelId);}case 'native-anthropic': {const apiKey = cfg.env.ANTHROPIC_API_KEY;@@ -3203,7 +3211,8 @@ function instantiateChat(recipe: Recipe, modelId: string, cfg: AIGatewayConfig):case 'native-google': {const apiKey = cfg.env.GOOGLE_GENERATIVE_AI_API_KEY;if (!apiKey) throw new AIConfigError(`Google chat requires GOOGLE_GENERATIVE_AI_API_KEY.`, recipe.setup_hint);- return createGoogleGenerativeAI({ apiKey }).languageModel(modelId);+ const baseURL = resolveNativeBaseUrl('google', cfg);+ return createGoogleGenerativeAI({ apiKey, ...(baseURL ? { baseURL } : {}) }).languageModel(modelId);}case 'native-anthropic': {const apiKey = cfg.env.ANTHROPIC_API_KEY;diff --git a/test/ai/google-base-url.test.ts b/test/ai/google-base-url.test.tsnew file mode 100644index 0000000000..657c1a40c6--- /dev/null+++ b/test/ai/google-base-url.test.ts@@ -0,0 +1,83 @@+/**+ * GOOGLE_GENERATIVE_AI_BASE_URL: native-google chat and embedding requests go+ * to the configured base URL (an eval metering proxy, a regional gateway)+ * with the real path and key header, and nothing changes when it is unset.+ * A local HTTP server stands in for the Gemini API, so the real AI SDK+ * request is exercised (no transport stub, no network).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { chat, configureGateway, embed, resetGateway, resolveNativeBaseUrl } from '../../src/core/ai/gateway.ts';+import type { AIGatewayConfig } from '../../src/core/ai/types.ts';++const seen: Array<{ path: string; key: string | null }> = [];+let server: ReturnType<typeof Bun.serve>;++beforeAll(() => {+ server = Bun.serve({+ port: 0,+ async fetch(req) {+ const url = new URL(req.url);+ seen.push({ path: url.pathname, key: req.headers.get('x-goog-api-key') });+ if (url.pathname.endsWith(':generateContent')) {+ return Response.json({+ candidates: [{ content: { role: 'model', parts: [{ text: 'proxied' }] }, finishReason: 'STOP' }],+ usageMetadata: { promptTokenCount: 3, candidatesTokenCount: 1, totalTokenCount: 4 },+ });+ }+ if (url.pathname.endsWith(':embedContent')) return Response.json({ embedding: { values: [0.6, 0.8, 0] } });+ if (url.pathname.endsWith(':batchEmbedContents')) {+ const body = await req.json() as { requests: unknown[] };+ return Response.json({ embeddings: body.requests.map(() => ({ values: [0.6, 0.8, 0] })) });+ }+ return new Response('not found', { status: 404 });+ },+ });+});++afterAll(() => { server.stop(true); });+afterEach(() => { seen.length = 0; resetGateway(); });++const cfgWith = (env: Record<string, string | undefined>) => ({ env }) as unknown as AIGatewayConfig;++describe('resolveNativeBaseUrl google', () => {+ test('a bare host gets /v1beta; a versioned URL is kept; trailing slashes are trimmed', () => {+ expect(resolveNativeBaseUrl('google', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: 'http://127.0.0.1:8787' }))).toBe('http://127.0.0.1:8787/v1beta');+ expect(resolveNativeBaseUrl('google', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: 'https://proxy.example/google/' }))).toBe('https://proxy.example/google/v1beta');+ expect(resolveNativeBaseUrl('google', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: 'https://proxy.example/v1beta/' }))).toBe('https://proxy.example/v1beta');+ expect(resolveNativeBaseUrl('google', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: 'https://proxy.example/v1' }))).toBe('https://proxy.example/v1');+ });++ test('unset or blank leaves the SDK default; providers read only their own variable', () => {+ expect(resolveNativeBaseUrl('google', cfgWith({}))).toBeUndefined();+ expect(resolveNativeBaseUrl('google', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: ' ' }))).toBeUndefined();+ expect(resolveNativeBaseUrl('google', cfgWith({ OPENAI_BASE_URL: 'https://x' }))).toBeUndefined();+ expect(resolveNativeBaseUrl('openai', cfgWith({ GOOGLE_GENERATIVE_AI_BASE_URL: 'https://x' }))).toBeUndefined();+ });+});++describe('native-google requests honor the override', () => {+ test('chat posts generateContent under the configured base URL with the key header', async () => {+ configureGateway({+ chat_model: 'google:gemini-2.5-flash',+ env: { GOOGLE_GENERATIVE_AI_API_KEY: 'test-google-key', GOOGLE_GENERATIVE_AI_BASE_URL: `http://127.0.0.1:${server.port}` },+ });+ const result = await chat({ model: 'google:gemini-2.5-flash', messages: [{ role: 'user', content: 'ping' }], maxTokens: 16 });+ expect(result.text).toBe('proxied');+ expect(seen).toEqual([{ path: '/v1beta/models/gemini-2.5-flash:generateContent', key: 'test-google-key' }]);+ });++ test('embedding posts under the configured base URL', async () => {+ configureGateway({+ embedding_model: 'google:gemini-embedding-001',+ embedding_dimensions: 3,+ env: { GOOGLE_GENERATIVE_AI_API_KEY: 'test-google-key', GOOGLE_GENERATIVE_AI_BASE_URL: `http://127.0.0.1:${server.port}/v1beta` },+ });+ const [one] = await embed(['hello'], { inputType: 'document' });+ const two = await embed(['hello', 'world'], { inputType: 'document' });+ for (const v of [one, ...two]) expect(Array.from(v).map(x => Math.round(x * 10) / 10)).toEqual([0.6, 0.8, 0]);+ expect(seen).toEqual([+ { path: '/v1beta/models/gemini-embedding-001:embedContent', key: 'test-google-key' },+ { path: '/v1beta/models/gemini-embedding-001:batchEmbedContents', key: 'test-google-key' },+ ]);+ });+});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex ae892ff2a8..315fd24299 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -2206,7 +2206,7 @@"kind": "function","name": "resolveNativeBaseUrl","signature": [- "(provider: \"anthropic\" | \"openai\", cfg: AIGatewayConfig) => string | undefined"+ "(provider: \"anthropic\" | \"openai\" | \"google\", cfg: AIGatewayConfig) => string | undefined"]},{diff --git a/test/native-base-url-fold.serial.test.ts b/test/native-base-url-fold.serial.test.tsindex fca8ac670d..4cb5b634d4 100644--- a/test/native-base-url-fold.serial.test.ts+++ b/test/native-base-url-fold.serial.test.ts@@ -91,6 +91,13 @@ describe('foldNativeBaseUrlsFromFilePlane (unit)', () => {expect(env.OPENAI_BASE_URL).toBe('https://file.example');});+ test('folds google as GOOGLE_GENERATIVE_AI_BASE_URL; env still wins', () => {+ expect(foldNativeBaseUrlsFromFilePlane({ provider_base_urls: { google: 'http://127.0.0.1:8787' } }, {}).GOOGLE_GENERATIVE_AI_BASE_URL)+ .toBe('http://127.0.0.1:8787');+ expect(foldNativeBaseUrlsFromFilePlane({ provider_base_urls: { google: 'http://file.example' } }, { GOOGLE_GENERATIVE_AI_BASE_URL: 'http://env.example' })+ .GOOGLE_GENERATIVE_AI_BASE_URL).toBe('http://env.example');+ });+test('non-native providers are ignored; null config is a no-op', () => {const env1 = foldNativeBaseUrlsFromFilePlane({ provider_base_urls: { ollama: 'http://localhost:11434' } },@@ -98,6 +105,7 @@ describe('foldNativeBaseUrlsFromFilePlane (unit)', () => {);expect(env1.ANTHROPIC_BASE_URL).toBeUndefined();expect(env1.OPENAI_BASE_URL).toBeUndefined();+ expect(env1.GOOGLE_GENERATIVE_AI_BASE_URL).toBeUndefined();const base = { OPENAI_API_KEY: 'sk-x' };expect(foldNativeBaseUrlsFromFilePlane(null, base)).toEqual(base);});