Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): send Voyage width to the Vercel AI Gateway only (#6061)

garrytan2c3321e592b8
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 9c2ddb60e7..1ab4567fe9 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -58,3 +58,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/reranker-readiness.ts` — pure leaf answering "is the reranker actually going to run?" for `gbrain search modes` (`buildModesReport.reranker_readiness`), doctor's `reranker_health`, and init's reranker-default write. `rerankerReadiness(model, env, { baseUrlOverrides? })` → `{model, provider, modelId (alias-canonical), recipeKnown, hasTouchpoint, modelListed, requiredKey (the first MISSING key, else the first required key — this is how `Reranker: … VOYAGE_API_KEY present` renders; null only for keyless recipes), keyPresent, selfHosted, ready}`; the env snapshot comes from the CALLER — the leaf never reads `process.env` and never imports the gateway (init runs before `configureGateway` and passes `mergedProviderEnv(cfg, process.env)` where `cfg` is `loadConfigFileOnly()` merged with the brain's DB-plane provider keys via `loadConfigWithEngine` — file plane alone if that read fails — so a `--force` re-init sees a Voyage key that lives only in the config table). A recipe with a custom `resolveAuth` needs no env key (mirrors the gateway); a `provider_base_urls` override marks the provider self-hosted. `describeRerankerFix(r)` renders the paste-ready one-liner (unknown-model > missing key + disable command). `src/core/ai/reranker-readiness-engine.ts` is the engine-plane wrapper doctor and `gbrain search modes` share: `rerankerReadinessForEngine(engine, model)` reads the LIVE gateway snapshot (env + base_urls — exactly what `rerank()` consults, so the verdict cannot disagree with search and a mounted brain's DB plane cannot steer it) and falls back to env > file > DB-plane provider keys + `provider_base_urls` via `loadConfigWithEngine` only when no gateway is configured; `redactReadinessForRemote` (modes-report.ts) strips `required_key`/`key_present`/`fix` from the `search_modes` op for untrusted callers. `test/ai/reranker-readiness.test.ts` pins agreement with `isAvailable('reranker', m)` on an env × model matrix (`recipeKnown && hasTouchpoint && keyPresent`) so the two predicates cannot drift.
- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling: `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
+
+- `src/core/ai/voyage-gateway.ts` — Voyage width plumbing for `voyageCompatFetch` (#6061). `applyVoyageOutputDimension(body, input, dims)` always sets root `output_dimension` and adds `providerOptions.voyage.outputDimension` only when the request URL's hostname is exactly `ai-gateway.vercel.sh` (the Vercel AI Gateway reads only that; Voyage's own API answers 400 on `providerOptions`; look-alike hosts, suffixes and path mentions never match). `embeddingDimMismatchError(...)` builds the dim-mismatch `AIConfigError`: with a non-default `provider_base_urls.<provider>` it names that host as the likely cause (a proxy dropping the width), says nothing was written and points at fixing the proxy plus `gbrain doctor --only embedding_provider --probe --json` before a migration; the default route keeps the `gbrain migrate --embedding-model … --embedding-dimensions …` hint. Pinned in `test/ai/gateway.test.ts` (Voyage shim describe).
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index b0fa9afdec..5cc054581c 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -89,6 +89,8 @@ Optional `OPENAI_BASE_URL` — point the native OpenAI provider at an OpenAI-com
Voyage 4 family shares an embedding space across all variants, so you can index with `voyage-4` and later point the query model at `voyage-4-large` or `voyage-4-lite` without reindexing. Dims: 256, 512, 1024, 2048. **2048 exceeds pgvector's HNSW cap of 2000** — those brains fall back to exact vector scans (still correct, just slower).
+Routed through the Vercel AI Gateway (`provider_base_urls.voyage` = `https://ai-gateway.vercel.sh/v1`), the embedding request also carries the width as `providerOptions.voyage.outputDimension`, which the gateway reads instead of Voyage's root `output_dimension`; that field is sent only when the hostname is exactly `ai-gateway.vercel.sh`, because Voyage's own API rejects it with HTTP 400. If a proxy returns a different width than `embedding_dimensions`, the embed fails before anything is written and the error names the proxy as the likely cause; fix the proxy's width parameter before considering a migration.
+
Voyage also serves four hosted rerankers at `POST /v1/rerank` — `rerank-2.5` ($0.05/M) and `rerank-2.5-lite` ($0.02/M), plus the preview `rerank-3` ($0.05/M) and `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06). All four share one request/response wire, so switching is a config change and nothing else.
`rerank-2.5` is the mode-bundle reranker default, so no config row is needed for it (an explicit `search.reranker.model` equal to it is exactly what `gbrain doctor`'s `search_mode` check calls redundant). Moving to the preview generation is one command:
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 90a43c8067..91a52978a1 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -68,6 +68,7 @@ import { loadConfig } from '../config.ts';
import type { GBrainConfig } from '../config.ts';
import { mergedProviderEnv } from './provider-env.ts';
import { redactProviderKeys } from './key-redact.ts';
+import { applyVoyageOutputDimension, embeddingDimMismatchError } from './voyage-gateway.ts';
import { reportEmbeddingAuthFailure } from './key-warnings.ts';
import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';
import { invokeAI, sdkInvocationUsage, responseInvocationUsage, hasAIInvocationGuard, isAIInvocationPolicyError } from './invocation-guard.ts';
@@ -1083,7 +1084,7 @@ const voyageCompatFetch = (async (input: RequestInfo | URL, init?: RequestInit)
if ('dimensions' in parsed) {
const dims = parsed.dimensions;
delete parsed.dimensions;
- if (typeof dims === 'number') parsed.output_dimension = dims;
+ if (typeof dims === 'number') applyVoyageOutputDimension(parsed, input, dims);
mutated = true;
}
// Recover the SDK-stripped input_type (#1400) — opt-in, mirroring
@@ -1748,10 +1749,8 @@ async function embedSubBatch(
for (const embedding of result.embeddings) {
if (Array.isArray(embedding) && embedding.length !== expectedDims) {
- throw new AIConfigError(
- `Embedding dim mismatch: model ${modelId} returned ${embedding.length} but schema expects ${expectedDims}.`,
- `Run \`gbrain migrate --embedding-model ${getEmbeddingModel()} --embedding-dimensions ${embedding.length}\` or change models.`,
- );
+ throw embeddingDimMismatchError(modelId, embedding.length, expectedDims, getEmbeddingModel(),
+ { provider: recipe.id, baseUrl: _config?.base_urls?.[recipe.id], defaultBaseUrl: recipe.base_url_default });
}
}
diff --git a/src/core/ai/voyage-gateway.ts b/src/core/ai/voyage-gateway.ts
new file mode 100644
index 0000000000..08590f260d
--- /dev/null
+++ b/src/core/ai/voyage-gateway.ts
@@ -0,0 +1,51 @@
+/**
+ * Voyage embeddings routed through the Vercel AI Gateway (#6061). The gateway
+ * ignores Voyage's root `output_dimension` and reads the width from
+ * `providerOptions.voyage.outputDimension`, so a Matryoshka width other than
+ * the model default came back at the default width. Voyage's own API rejects
+ * `providerOptions` with HTTP 400, so the field is added only when the
+ * request URL's hostname is exactly the gateway host: never a substring or
+ * suffix match, never for api.voyageai.com or another proxy.
+ */
+import { AIConfigError } from './errors.ts';
+
+export const VERCEL_AI_GATEWAY_HOST = 'ai-gateway.vercel.sh';
+
+function requestHostname(input: RequestInfo | URL): string | null {
+ try {
+ const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url);
+ return url.hostname.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+/** Set the Voyage width on an outbound body: root `output_dimension` always, the gateway field only for the gateway host. */
+export function applyVoyageOutputDimension(body: Record<string, unknown>, input: RequestInfo | URL, dims: number): void {
+ body.output_dimension = dims;
+ if (requestHostname(input) !== VERCEL_AI_GATEWAY_HOST) return;
+ const options = (body.providerOptions && typeof body.providerOptions === 'object' ? body.providerOptions : {}) as Record<string, unknown>;
+ const voyage = (options.voyage && typeof options.voyage === 'object' ? options.voyage : {}) as Record<string, unknown>;
+ body.providerOptions = { ...options, voyage: { ...voyage, outputDimension: dims } };
+}
+
+/**
+ * The response carried a width other than the one requested. With a custom
+ * base URL the likely cause is the proxy dropping the width parameter, not
+ * the stored vectors, so the message says so before suggesting a migration.
+ */
+export function embeddingDimMismatchError(
+ modelId: string, returned: number, expected: number, embeddingModel: string,
+ route: { provider: string; baseUrl?: string; defaultBaseUrl?: string },
+): AIConfigError {
+ const migrate = `\`gbrain migrate --embedding-model ${embeddingModel} --embedding-dimensions ${returned}\``;
+ const proxied = route.baseUrl !== undefined && route.baseUrl !== route.defaultBaseUrl;
+ if (!proxied) {
+ return new AIConfigError(`Embedding dim mismatch: model ${modelId} returned ${returned} but schema expects ${expected}.`, `Run ${migrate} or change models.`);
+ }
+ const host = requestHostname(route.baseUrl!) ?? route.baseUrl!;
+ return new AIConfigError(
+ `Embedding dim mismatch: model ${modelId} returned ${returned} but schema expects ${expected}. Requests go through ${host} (provider_base_urls.${route.provider}), not the provider's own API; a proxy that drops the requested width returns the model default. Nothing was written.`,
+ `Check that the proxy forwards the requested embedding width (then \`gbrain doctor --only embedding_provider --probe --json\`); only if ${returned} dimensions is what you want, run ${migrate}.`,
+ );
+}
diff --git a/test/ai/gateway.test.ts b/test/ai/gateway.test.ts
index 9c75d107ee..299bad58b4 100644
--- a/test/ai/gateway.test.ts
+++ b/test/ai/gateway.test.ts
@@ -304,6 +304,63 @@ describe('Voyage openai-compatible request shim', () => {
globalThis.fetch = originalFetch;
}
});
+
+ // #6061: the Vercel AI Gateway reads the width from providerOptions.voyage;
+ // Voyage's own API rejects providerOptions with HTTP 400.
+ async function captureVoyageRequest(baseUrl: string | undefined, returnedDims = 2048) {
+ const originalFetch = globalThis.fetch;
+ let requestBody: Record<string, unknown> | undefined;
+ let requestUrl = '';
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ requestUrl = String(url instanceof Request ? url.url : url);
+ requestBody = JSON.parse(String(init?.body ?? '{}'));
+ return new Response(JSON.stringify({
+ object: 'list',
+ data: [{ object: 'embedding', index: 0, embedding: new Array(returnedDims).fill(0.01) }],
+ model: 'voyage-4-large',
+ usage: { total_tokens: 3 },
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }) as unknown as typeof fetch;
+ try {
+ configureGateway({
+ embedding_model: 'voyage:voyage-4-large',
+ embedding_dimensions: 2048,
+ env: { VOYAGE_API_KEY: 'voyage-fake' },
+ ...(baseUrl ? { base_urls: { voyage: baseUrl } } : {}),
+ });
+ const result = await embed(['dimension probe']).then((v) => ({ vectors: v, error: null }), (error: unknown) => ({ vectors: null, error }));
+ return { requestBody, requestUrl, ...result };
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ }
+
+ test('through the Vercel AI Gateway the width also rides providerOptions.voyage.outputDimension', async () => {
+ const { requestBody, requestUrl } = await captureVoyageRequest('https://ai-gateway.vercel.sh/v1');
+ expect(new URL(requestUrl).hostname).toBe('ai-gateway.vercel.sh');
+ expect(requestBody?.output_dimension).toBe(2048);
+ expect(requestBody?.providerOptions).toEqual({ voyage: { outputDimension: 2048 } });
+ });
+
+ test('the direct Voyage API and look-alike hosts never get providerOptions (Voyage answers 400 on it)', async () => {
+ for (const baseUrl of [undefined, 'https://api.voyageai.com/v1', 'https://ai-gateway.vercel.sh.attacker.example/v1', 'https://my-ai-gateway.vercel.sh/v1', 'https://proxy.example/ai-gateway.vercel.sh/v1']) {
+ const { requestBody } = await captureVoyageRequest(baseUrl);
+ expect(requestBody?.output_dimension).toBe(2048);
+ expect(requestBody && 'providerOptions' in requestBody).toBe(false);
+ }
+ });
+
+ test('a width mismatch through a custom base URL names the proxy as the likely cause; the default route keeps the migrate hint', async () => {
+ const proxied = await captureVoyageRequest('https://ai-gateway.vercel.sh/v1', 1024);
+ const err = proxied.error as { message: string; fix?: string };
+ expect(err.message).toContain('returned 1024 but schema expects 2048');
+ expect(err.message).toContain('ai-gateway.vercel.sh (provider_base_urls.voyage)');
+ expect(err.fix).toContain('gbrain doctor --only embedding_provider --probe --json');
+ const direct = await captureVoyageRequest(undefined, 1024);
+ const directErr = direct.error as { message: string; fix?: string };
+ expect(directErr.message).not.toContain('base_urls');
+ expect(directErr.fix).toContain('gbrain migrate --embedding-model');
+ });
});
// ─────────────────────────────────────────────────────────────────────