diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index 9aa6e51e5..96c1f5122 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -236,6 +236,11 @@ const loadConfig = () => { routes: raw.experimental?.model_routes || raw.model_routes || {}, windows, disabled: new Set(raw.disabled_providers || []), + // Purpose/capability designations (code#13675 Part 1), read from + // the config FILE: the server's /api/config projection strips + // these fields (developing-today-forks/opencode#2782), so the + // proxy must never source them from the projection. + designations: raw.model_designations || {}, }; return cfgCache; }; @@ -1110,6 +1115,347 @@ const applyDemotion = (candidates, demoted) => { ]; }; +// --------------------------------------- purpose-aware dispatch (#13675 P2) +// +// The proxy is an OpenAI-compatible door for every pool purpose, not +// just chat. Each client endpoint requires the pool's declared +// purpose (absent = chat) to match, and each resolved leaf is +// checked against the model_designations registry at dispatch time +// (the checker guards the tracked file; the proxy guards what it +// actually serves, reading both from the config FILE per the +// opencode#2782 projection gap). +// +// Client endpoints and their required purposes: +// POST /v1/chat/completions chat OpenAI chat shape +// POST /v1/embeddings embed OpenAI embeddings shape +// POST /v1/decisions decision { model, input, questions } +// POST /v1/rerank rerank { model, query, documents } +// POST /v1/audio/transcriptions transcribe OpenAI multipart form +// POST /v1/audio/speech speak OpenAI speech JSON shape +// POST /v1/guard guard OpenAI chat shape +// The /v1/guard shape is deliberate: prompt-guard models are served +// through chat-shaped calls, so the guard endpoint reuses the chat +// core with the purpose fixed to guard. Audio endpoints are true +// passthroughs: the client's bytes are forwarded untouched, and the +// leaf's answer (plus status and content-type) is relayed back. +// +// Per-provider endpoint descriptors live in the provider block's +// options.endpoints, beside baseURL: +// "endpoints": { "": { "kind": ..., "path": ... } } +// Kinds: +// openai passthrough to the provider's OpenAI-style +// surface (default when no descriptor names the +// purpose). Default paths: /embeddings, /rerank, +// /audio/transcriptions, /audio/speech, +// /chat/completions (guard). Decisions have NO +// OpenAI-style default: a provider serves +// decisions only through an explicit descriptor — +// native wins over shim, and a blind /decisions +// POST to an OpenAI base is a guaranteed 404 that +// would only pollute the demotion ledger. +// google-decisions native POST {path} (default /decisions) on the +// v1beta base, x-goog-api-key auth, body +// { model, input, questions }. +// google-embed native embedContent / batchEmbedContent on the +// v1beta base, x-goog-api-key auth. Descriptor +// path names the single-item endpoint template +// (default /models/{model}:embedContent); arrays +// use the batch endpoint (descriptor batchPath, or +// the :embedContent -> :batchEmbedContent +// substitution, or sequential single calls). +// jev-systemone Zen's native decision shape: POST {path} +// (default /decisions), Bearer auth, body +// { model, input, questions }. Provisional until a +// live probe confirms the shape (no Zen key is +// fetchable by name, so no live seat exists yet). +// fireworks / native POST {path} (REQUIRED, no default), +// baseten / modal Bearer auth, client body with the model mapped +// to the leaf. Mechanism support only: fixtures + +// docs, no live seats (providers not configured). +// An unknown kind never invents a surface: the leaf is skipped for +// that endpoint. A leaf with no usable descriptor for the endpoint +// is skipped before the walk (like a credential-less leaf), so a +// route whose members cannot serve fails loud without spending +// attempts on guaranteed 404s. +// +// A2 embedding batch semantics: array inputs run natively where the +// provider supports them; an oversized batch splits at the +// provider's per-request limit (descriptor maxBatchItems; google +// default 100, provisional) and sub-batch results re-join in caller +// order with index-faithful mapping. A sub-batch that fails +// retryably (transport, 429, 5xx) fails the leaf over to the next +// candidate; a sub-batch that fails non-retryably (4xx) fails only +// its own items — the run answers 207 with per-item errors, never +// silently misaligning neighbours' positions. + +const GOOGLE_EMBED_DEFAULT_BATCH = 100; + +// Safe own-property read: pool/provider/model names ride in client +// request bodies, and a "__proto__"-shaped name must miss the +// tables rather than resolve through the prototype chain. +const ownEntry = (obj, key) => + obj && typeof obj === "object" && Object.hasOwn(obj, key) ? obj[key] : undefined; + +const routePurpose = (cfg, routeId) => + cfg.routes[routeId]?.purpose || "chat"; + +// A model's designated purposes, by bare model id (leaf.modelKey; +// e.g. "meta-llama/llama-prompt-guard-2-22m" splits provider-first +// so the key matches the designation registry), falling back to the +// provider catalog's resolved id. Absent = legacy unrestricted. +const designatedPurposes = (cfg, leaf) => { + const byKey = ownEntry(cfg.designations, leaf.modelKey); + if (byKey && Array.isArray(byKey.purposes)) return byKey.purposes; + const modelId = providerDef(cfg, leaf.providerId)?.models?.[leaf.modelKey]?.id; + if (typeof modelId === "string" && modelId !== leaf.modelKey) { + const byId = ownEntry(cfg.designations, modelId); + if (byId && Array.isArray(byId.purposes)) return byId.purposes; + } + return null; +}; + +// Pool-level purpose guard. Returns null when the route may serve +// the endpoint, else { status, message }. Unknown routes 404 here; +// the chat handler keeps its legacy 502 for unknown routes and uses +// this only for the mismatch refusal. +const checkEndpointAccess = (cfg, routeId, purpose) => { + if (!cfg.routes[routeId]) + return { status: 404, message: `unknown route: ${routeId}` }; + const pool = cfg.routes[routeId].purpose || "chat"; + if (pool !== purpose) + return { + status: 400, + message: `route ${routeId} has purpose "${pool}" and cannot serve ${purpose} requests`, + }; + return null; +}; + +// Shared candidate prep for every endpoint: unknown route, pool +// purpose, resolution, demotion, the known-exhausted gate, runtime +// designation enforcement, credential filter. Message-identical to +// the chat walk's former inline prep, with the designation refusal +// added between the gate and the credential filter. +const prepareCandidates = (cfg, routeId, variantIn, requiredPurpose = null) => { + if (!cfg.routes[routeId]) + throw new LeafError(`unknown route: ${routeId}`, { + tag: "InvalidRequest", + retryable: 0, + }); + const poolPurpose = cfg.routes[routeId].purpose || "chat"; + if (requiredPurpose && poolPurpose !== requiredPurpose) + throw new LeafError( + `route ${routeId} has purpose "${poolPurpose}" and cannot serve ${requiredPurpose} requests`, + { tag: "InvalidRequest", retryable: 0 }, + ); + let candidates = resolveRoute(cfg, routeId, variantIn); + candidates = applyDemotion(candidates, demotedPairs()); + candidates = applyKnownExhaustedGate(cfg, candidates); + if (!candidates.length) + throw new LeafError(`route ${routeId} has no available members`, { + tag: "UnknownProvider", + retryable: 0, + }); + candidates = candidates.filter((c) => { + const p = designatedPurposes(cfg, c); + return !p || p.includes(poolPurpose); + }); + if (!candidates.length) + throw new LeafError( + `route ${routeId} has no members designated for purpose "${poolPurpose}"`, + { tag: "UnknownProvider", retryable: 0 }, + ); + candidates = candidates.filter((c) => hasCredential(cfg, c.providerId)); + if (!candidates.length) + throw new LeafError(`route ${routeId} has no credentialed members`, { + tag: "UnknownProvider", + retryable: 0, + }); + return { candidates, poolPurpose }; +}; + +// A provider's descriptor for one endpoint purpose, following the +// instanceOf chain through the merged provider definition (a google.* +// alias carries its own endpoints; its google base carries none). +const endpointDescriptor = (cfg, providerId, purpose) => { + const eps = providerDef(cfg, providerId)?.options?.endpoints; + const ep = ownEntry(eps, purpose); + return ep && typeof ep === "object" ? ep : null; +}; + +const OPENAI_ENDPOINT_PATHS = { + embed: "/embeddings", + rerank: "/rerank", + transcribe: "/audio/transcriptions", + speak: "/audio/speech", + guard: "/chat/completions", +}; + +const NATIVE_PASSTHROUGH_KINDS = new Set(["fireworks", "baseten", "modal"]); + +// Build one leaf HTTP request for a purpose. `payload` is the client +// JSON body (model mapped to the leaf) or, for transcription +// passthrough, the raw multipart Buffer. Returns null when the leaf +// cannot serve the endpoint (no usable surface): the caller skips +// the leaf before spending an attempt on it. +const buildLeafRequest = (cfg, leaf, purpose, payload, sessionLabel) => { + const base = providerBaseURL(cfg, leaf.providerId); + if (!base) + throw new LeafError(`no endpoint configured for provider ${leaf.providerId}`, { + tag: "UnknownProvider", + retryable: 0, + }); + const apiKey = leafCredential(cfg, leaf.providerId); + if (!apiKey) + throw new LeafError(`no credential for provider ${leaf.providerId}`, { + tag: "Authentication", + retryable: 0, + }); + const desc = endpointDescriptor(cfg, leaf.providerId, purpose); + const kind = (desc && typeof desc.kind === "string" && desc.kind) || "openai"; + const leafModel = providerDef(cfg, leaf.providerId)?.models?.[leaf.modelKey]?.id || leaf.modelKey; + const google = kind === "google-decisions" || kind === "google-embed"; + const headers = { "user-agent": LEAF_UA }; + if (google) headers["x-goog-api-key"] = apiKey; + else headers.authorization = `Bearer ${apiKey}`; + // The OpenCode Go gateway attributes plan usage by this header; it + // is an attribution label minted per request, not a local session. + if (base.includes("opencode.ai")) headers["x-opencode-session"] = sessionLabel; + const descPath = + desc && typeof desc.path === "string" && desc.path ? desc.path : null; + const jsonHeaders = { ...headers, "content-type": "application/json" }; + const raw = Buffer.isBuffer(payload); + if (kind === "openai") { + const p = descPath || OPENAI_ENDPOINT_PATHS[purpose] || null; + if (!p) return null; + if (raw) return { url: base + p, headers, body: payload }; + return { + url: base + p, + headers: jsonHeaders, + body: JSON.stringify({ ...payload, model: leafModel }), + }; + } + if (raw) return null; // only the OpenAI audio surface takes multipart + if (kind === "google-embed") { + // Native embedContent / batchEmbedContent on the v1beta base. + // Descriptor path names the single-item endpoint template + // (default /models/{model}:embedContent); arrays use the batch + // endpoint (descriptor batchPath, or the :embedContent -> + // :batchEmbedContent substitution). {model} expands to the leaf + // model id; without it the template is used verbatim. + const singleTemplate = descPath || "/models/{model}:embedContent"; + const singlePath = singleTemplate.includes("{model}") + ? singleTemplate.replaceAll("{model}", leafModel) + : singleTemplate; + const batchPath = + desc && typeof desc.batchPath === "string" && desc.batchPath + ? desc.batchPath.includes("{model}") + ? desc.batchPath.replaceAll("{model}", leafModel) + : desc.batchPath + : singlePath.includes(":embedContent") + ? singlePath.replace(":embedContent", ":batchEmbedContent") + : null; + const toContent = (text) => ({ content: { parts: [{ text }] } }); + const input = payload?.input; + if (typeof input === "string") { + return { + url: base + singlePath, + headers: jsonHeaders, + body: JSON.stringify({ + model: `models/${leafModel}`, + ...toContent(input), + }), + embedBatch: false, + }; + } + if (Array.isArray(input)) { + if (!input.every((t) => typeof t === "string")) return null; + if (input.length <= 1) { + return { + url: base + singlePath, + headers: jsonHeaders, + body: JSON.stringify({ + model: `models/${leafModel}`, + ...toContent(input[0] ?? ""), + }), + embedBatch: false, + }; + } + if (!batchPath) return null; + return { + url: base + batchPath, + headers: jsonHeaders, + body: JSON.stringify({ + requests: input.map((text) => ({ + model: `models/${leafModel}`, + ...toContent(text), + })), + }), + embedBatch: true, + }; + } + return null; + } + if (kind === "google-decisions") { + if (!isPlainObj(payload.questions)) + throw new LeafError("questions must be an object", { + tag: "InvalidRequest", + retryable: 0, + }); + return { + url: base + (descPath || "/decisions"), + headers: jsonHeaders, + body: JSON.stringify({ + model: leafModel, + input: payload.input, + questions: payload.questions, + }), + }; + } + if (kind === "jev-systemone") { + if (!isPlainObj(payload.questions)) + throw new LeafError("questions must be an object", { + tag: "InvalidRequest", + retryable: 0, + }); + return { + url: base + (descPath || "/decisions"), + headers: jsonHeaders, + body: JSON.stringify({ + model: leafModel, + input: payload.input, + questions: payload.questions, + }), + }; + } + if (NATIVE_PASSTHROUGH_KINDS.has(kind)) { + if (!descPath) return null; + return { + url: base + descPath, + headers: jsonHeaders, + body: JSON.stringify({ ...payload, model: leafModel }), + }; + } + return null; // unknown kind: never invent a surface +}; + +const postLeaf = async (built, signal) => { + let res; + try { + res = await fetch(built.url, { + method: "POST", + headers: built.headers, + body: built.body, + signal, + }); + } catch (err) { + throw new LeafError(`leaf transport error: ${err?.message || err}`, { + tag: "Transport", + code: err?.cause?.code || null, + }); + } + return res; +}; + // ---------------------------------------------------------------- leaves class LeafError extends Error { @@ -1628,31 +1974,18 @@ const usageFields = (usage) => { // onStream takes over and returns the collected stream stats. const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { const cfg = loadConfig(); - if (!cfg.routes[routeId]) - throw new LeafError(`unknown route: ${routeId}`, { - tag: "InvalidRequest", - retryable: 0, - }); + // Resolution, demotion, the known-exhausted gate, runtime + // designation enforcement and the credential filter (#3228: a + // walk never spends an attempt on a credential-less leaf) all + // live in prepareCandidates; chat requires the chat purpose, so + // a chat call naming a decision pool (systemone) is refused here. + const { candidates } = prepareCandidates( + cfg, + routeId, + hooks.variantIn ?? null, + hooks.requiredPurpose ?? "chat", + ); const wantStream = Boolean(body.stream); - let candidates = resolveRoute(cfg, routeId, hooks.variantIn ?? null); - candidates = applyDemotion(candidates, demotedPairs()); - candidates = applyKnownExhaustedGate(cfg, candidates); - if (!candidates.length) - throw new LeafError(`route ${routeId} has no available members`, { - tag: "UnknownProvider", - retryable: 0, - }); - // Credential-less leaves are skipped like disabled providers (#3228): - // a walk never spends one of its MAX_ATTEMPTS on a provider whose - // credential lookup comes back empty (inactive or missing row), and - // such a leaf never surfaces its misleading Authentication error as - // the run's terminal failure. - candidates = candidates.filter((c) => hasCredential(cfg, c.providerId)); - if (!candidates.length) - throw new LeafError(`route ${routeId} has no credentialed members`, { - tag: "UnknownProvider", - retryable: 0, - }); const deadlineCtl = new AbortController(); const timer = setTimeout( () => deadlineCtl.abort(new Error("opencode-route-proxy deadline")), @@ -1844,48 +2177,597 @@ const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { } }; -// ---------------------------------------------------------------- http - -const sendJson = (res, status, obj) => { - if (res.destroyed || res.writableEnded) return; - const body = JSON.stringify(obj); - res.writeHead(status, { "content-type": "application/json" }); - res.end(body); +// ----------------------- purpose single-shot + A2 walks (#13675 P2) +// +// runSingleShotJson: one JSON body through the route's candidates. +// Leaves with no usable surface for the purpose (buildLeafRequest +// null: unknown kind, decisions without a descriptor, google-embed +// with an untranslatable input) are skipped before spending an +// attempt. Any leaf failure (transport, 429, 5xx, 4xx) fails over +// to the next candidate, mirroring the chat walk; the last error +// throws when every candidate fails. JSON purposes keep the +// per-leaf first-response timeout; audio passthroughs skip it +// (overall deadline still applies to all). +const runSingleShotJson = async ( + routeId, + purpose, + payload, + clientSignal, + variantIn = null, +) => { + const cfg = loadConfig(); + const { candidates } = prepareCandidates(cfg, routeId, variantIn, purpose); + const usable = candidates.filter( + (leaf) => buildLeafRequest(cfg, leaf, purpose, payload, "probe") !== null, + ); + if (!usable.length) + throw new LeafError(`route ${routeId} has no members serving ${purpose}`, { + tag: "UnknownProvider", + retryable: 0, + }); + const deadlineCtl = new AbortController(); + const timer = setTimeout( + () => deadlineCtl.abort(new Error("opencode-route-proxy deadline")), + TIMEOUT_MS, + ); + const signal = clientSignal + ? AbortSignal.any([deadlineCtl.signal, clientSignal]) + : deadlineCtl.signal; + const sessionLabel = `ses_${randomBytes(12).toString("hex")}`; + const attempts = usable.slice(0, MAX_ATTEMPTS); + let lastErr = null; + try { + for (let i = 0; i < attempts.length; i++) { + const leaf = attempts[i]; + const started = Date.now(); + const next = attempts[i + 1]; + const failedOverTo = next ? `${next.providerId}/${next.modelKey}` : null; + let built; + try { + built = buildLeafRequest(cfg, leaf, purpose, payload, sessionLabel); + } catch (err) { + // Validation errors (InvalidRequest, retryable 0) fail fast: + // a malformed client body is not a leaf failure. + if (err instanceof LeafError && err.retryable === 0) throw err; + lastErr = err; + continue; + } + if (!built) continue; + const leafDeadlineCtl = new AbortController(); + const leafTimer = setTimeout( + () => + leafDeadlineCtl.abort( + new Error("opencode-route-proxy leaf first-response timeout"), + ), + LEAF_TIMEOUT_MS, + ); + const leafSignal = AbortSignal.any([signal, leafDeadlineCtl.signal]); + try { + const res = await postLeaf(built, leafSignal); + const text = await res.text(); + const ended = Date.now(); + if (!res.ok) { + const err = classifyHttp(res.status, res.headers, text); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "failure", + errorTag: err.tag, + errorStatus: err.status, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota, + }); + lastErr = err; + if (signal.aborted) throw err; + continue; + } + let json = null; + try { + json = JSON.parse(text); + } catch {} + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "success", + outputStarted: true, + responseMs: ended - started, + ...(json?.usage ? usageFields(json.usage) : {}), + }); + return { json, text, leaf, embedBatch: built.embedBatch === true }; + } catch (err) { + const ended = Date.now(); + const leafTimedOut = !signal.aborted && leafDeadlineCtl.signal.aborted; + const leafErr = + err instanceof LeafError + ? err + : new LeafError(`leaf transport error: ${err?.message || err}`, { + tag: "Transport", + code: err?.cause?.code || null, + }); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: signal.aborted || leafTimedOut ? "timeout" : "failure", + errorTag: leafErr.tag || "Transport", + errorCode: leafErr.code ?? null, + errorStatus: leafErr.status ?? null, + errorMessage: String(leafErr.message || leafErr).slice(0, 500), + retryable: leafErr.retryable ?? 1, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: leafErr.quota ?? null, + }); + lastErr = leafErr; + if (signal.aborted) throw leafErr; + continue; + } finally { + clearTimeout(leafTimer); + } + } + throw lastErr || new Error(`route ${routeId}: all candidates failed`); + } finally { + clearTimeout(timer); + } }; -const sendError = (res, status, message) => - sendJson(res, status, { error: { message, type: "proxy_error" } }); -// A wall-paced answer (#13693 RC-4): 503 with Retry-After until the -// earliest known reset, and a JSON error body naming the wall — the -// same { error: { message, type } } shape as every other proxy -// error, plus the retry-after header sendJson does not carry. -const sendWallPaced = (res, err) => { - if (res.destroyed || res.writableEnded) return; - const secs = Math.max(1, Math.ceil((err.retryAfterMs ?? 0) / 1000)); - res.writeHead(503, { - "content-type": "application/json", - "retry-after": String(secs), +// Audio passthrough walk: the client's bytes forward untouched and +// the leaf's answer (status + content-type + bytes) relays back. +// No per-leaf first-response timeout: audio legs stream their +// answer late by nature; the overall deadline still bounds the run. +const runAudioPassthrough = async ( + routeId, + purpose, + rawBody, + contentType, + clientSignal, + variantIn = null, +) => { + const cfg = loadConfig(); + const { candidates } = prepareCandidates(cfg, routeId, variantIn, purpose); + const usable = candidates.filter((leaf) => { + try { + return buildLeafRequest(cfg, leaf, purpose, rawBody, "probe") !== null; + } catch { + return true; + } }); - res.end( - JSON.stringify({ - error: { message: String(err?.message || err), type: "proxy_error" }, - }), + if (!usable.length) + throw new LeafError(`route ${routeId} has no members serving ${purpose}`, { + tag: "UnknownProvider", + retryable: 0, + }); + const deadlineCtl = new AbortController(); + const timer = setTimeout( + () => deadlineCtl.abort(new Error("opencode-route-proxy deadline")), + TIMEOUT_MS, ); -}; - -const isPlainObject = (v) => - typeof v === "object" && v !== null && !Array.isArray(v); - -const parseRouteModel = (raw) => { - const model = typeof raw === "string" && raw ? raw : "workhorse"; - const id = model.startsWith("opencode-route/") - ? model.slice("opencode-route/".length) - : model; - const h = id.indexOf("#"); - return h > 0 - ? { routeId: id.slice(0, h), variant: id.slice(h + 1) } - : { routeId: id, variant: null }; -}; + const signal = clientSignal + ? AbortSignal.any([deadlineCtl.signal, clientSignal]) + : deadlineCtl.signal; + const sessionLabel = `ses_${randomBytes(12).toString("hex")}`; + const attempts = usable.slice(0, MAX_ATTEMPTS); + let lastErr = null; + try { + for (let i = 0; i < attempts.length; i++) { + const leaf = attempts[i]; + const started = Date.now(); + const next = attempts[i + 1]; + const failedOverTo = next ? `${next.providerId}/${next.modelKey}` : null; + let built; + try { + built = buildLeafRequest(cfg, leaf, purpose, rawBody, sessionLabel); + } catch (err) { + lastErr = err; + continue; + } + if (!built) continue; + built.headers = { ...built.headers }; + if (contentType) built.headers["content-type"] = contentType; + let res; + try { + res = await postLeaf(built, signal); + } catch (err) { + const ended = Date.now(); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: signal.aborted ? "timeout" : "failure", + errorTag: err.tag || "Transport", + errorCode: err.code ?? null, + errorStatus: err.status ?? null, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable ?? 1, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota ?? null, + }); + lastErr = err; + if (signal.aborted) throw err; + continue; + } + const buf = Buffer.from(await res.arrayBuffer()); + const ended = Date.now(); + if (!res.ok) { + const text = buf.toString("utf8"); + const err = classifyHttp(res.status, res.headers, text); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "failure", + errorTag: err.tag, + errorStatus: err.status, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota, + }); + lastErr = err; + if (signal.aborted) throw err; + continue; + } + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "success", + outputStarted: true, + responseMs: ended - started, + }); + return { + status: res.status, + contentType: res.headers.get("content-type") || "application/octet-stream", + body: buf, + }; + } + throw lastErr || new Error(`route ${routeId}: all candidates failed`); + } finally { + clearTimeout(timer); + } +}; + +// A3 autobatch (cross-request coalescing of concurrent single-item +// embeds behind a linger window) is POSTPONED, not attempted: probed +// 2026-11-23 — 6 concurrent single-item embeds issue 6 leaf calls +// (no merging). Correctness is unaffected (each request is answered +// exactly); only leaf-call efficiency is left on the table. A +// coalescer would need to hold client responses open across the +// route walk and re-map indices across requests — new failure +// surface for a follow-up slice, not this one. + +const embedMaxBatch = (cfg, leaf) => { + const desc = endpointDescriptor(cfg, leaf.providerId, "embed"); + const n = desc && Number(desc.maxBatchItems); + if (Number.isFinite(n) && n > 0) return Math.floor(n); + const kind = (desc && desc.kind) || "openai"; + if (kind === "google-embed") return GOOGLE_EMBED_DEFAULT_BATCH; + return Infinity; +}; + +// Extract embedding vectors from a leaf response, in request order. +// OpenAI shape: { data: [{ embedding }] }. Google single: +// { embedding: { values } }. Google batch: +// { embeddings: [{ values }] }. +const extractEmbedVectors = (json, batch, count) => { + if (!json || typeof json !== "object") return null; + if (batch) { + const arr = json.embeddings; + if (!Array.isArray(arr) || arr.length !== count) return null; + return arr.map((e) => e?.values ?? e?.embedding?.values ?? e); + } + if (Array.isArray(json.data) && json.data.length === count) + return json.data.map((d) => d?.embedding ?? d); + if (json.embedding && count === 1) + return [json.embedding?.values ?? json.embedding]; + return null; +}; + +const isRetryableLeafError = (err) => + !(err instanceof LeafError) || + (err.retryable !== 0 && !(err.status >= 400 && err.status < 500 && err.status !== 429 && err.status !== 402)); + +// A2 embedding walk: array inputs split at the provider's +// per-request limit and re-joined in caller order with +// index-faithful mapping. A sub-batch that fails retryably +// (transport, 429, 5xx) fails over to the next candidate; a +// sub-batch that fails non-retryably (4xx) fails only its own +// items — the run answers 207 with per-item errors, never +// silently misaligning neighbours' positions. +const runEmbeddingsA2 = async ( + routeId, + clientBody, + clientSignal, + variantIn = null, +) => { + const cfg = loadConfig(); + const inputs = clientBody.input; + const { candidates } = prepareCandidates(cfg, routeId, variantIn, "embed"); + const usable = candidates.filter((leaf) => { + try { + const probe = + inputs.length <= 1 + ? { model: "probe", input: inputs[0] ?? "" } + : { model: "probe", input: inputs.slice(0, 2) }; + return buildLeafRequest(cfg, leaf, "embed", probe, "probe") !== null; + } catch { + return false; + } + }); + if (!usable.length) + throw new LeafError(`route ${routeId} has no members serving embed`, { + tag: "UnknownProvider", + retryable: 0, + }); + let limit = Infinity; + for (const leaf of usable) { + const m = embedMaxBatch(cfg, leaf); + if (m < limit) limit = m; + } + if (!Number.isFinite(limit) || limit <= 0) limit = inputs.length || 1; + const chunks = []; + for (let i = 0; i < inputs.length; i += limit) + chunks.push({ start: i, texts: inputs.slice(i, i + limit) }); + return runEmbeddingsA2Direct(cfg, routeId, usable, chunks, clientBody, clientSignal); +}; + +// Direct per-leaf A2 implementation, factored for testability: each +// sub-batch walks the usable leaves in order without re-resolving. +const runEmbeddingsA2Direct = async ( + cfg, + routeId, + usable, + chunks, + clientBody, + clientSignal, +) => { + const deadlineCtl = new AbortController(); + const timer = setTimeout( + () => deadlineCtl.abort(new Error("opencode-route-proxy deadline")), + TIMEOUT_MS, + ); + const signal = clientSignal + ? AbortSignal.any([deadlineCtl.signal, clientSignal]) + : deadlineCtl.signal; + const sessionLabel = `ses_${randomBytes(12).toString("hex")}`; + const leaves = usable.slice(0, MAX_ATTEMPTS); + const vectors = new Array(clientBody.input.length).fill(null); + const itemErrors = new Array(clientBody.input.length).fill(null); + let lastErr = null; + try { + for (const chunk of chunks) { + let done = false; + for (let li = 0; li < leaves.length; li++) { + const leaf = leaves[li]; + const started = Date.now(); + const next = leaves[li + 1]; + const failedOverTo = next ? `${next.providerId}/${next.modelKey}` : null; + const payload = { + model: clientBody.model, + input: chunk.texts.length === 1 ? chunk.texts[0] : chunk.texts, + }; + let built; + try { + built = buildLeafRequest(cfg, leaf, "embed", payload, sessionLabel); + } catch (err) { + lastErr = err; + continue; + } + if (!built) continue; + const leafDeadlineCtl = new AbortController(); + const leafTimer = setTimeout( + () => + leafDeadlineCtl.abort( + new Error("opencode-route-proxy leaf first-response timeout"), + ), + LEAF_TIMEOUT_MS, + ); + const leafSignal = AbortSignal.any([signal, leafDeadlineCtl.signal]); + try { + const res = await postLeaf(built, leafSignal); + const text = await res.text(); + const ended = Date.now(); + if (!res.ok) { + const err = classifyHttp(res.status, res.headers, text); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "failure", + errorTag: err.tag, + errorStatus: err.status, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota, + }); + lastErr = err; + if (signal.aborted) throw err; + if (isRetryableLeafError(err)) continue; + for (let k = 0; k < chunk.texts.length; k++) + itemErrors[chunk.start + k] = String(err.message || err).slice(0, 300); + done = true; + break; + } + let json = null; + try { + json = JSON.parse(text); + } catch { + json = null; + } + const vecs = extractEmbedVectors(json, built.embedBatch === true, chunk.texts.length); + if (!vecs) { + const err = new LeafError("leaf embedding response unparseable", { + tag: "ProviderInternal", + }); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "failure", + errorTag: err.tag, + errorMessage: err.message, + retryable: err.retryable, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + }); + lastErr = err; + continue; + } + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: "success", + outputStarted: true, + responseMs: ended - started, + ...(json?.usage ? usageFields(json.usage) : {}), + }); + for (let k = 0; k < chunk.texts.length; k++) + vectors[chunk.start + k] = vecs[k]; + done = true; + break; + } catch (err) { + const ended = Date.now(); + const leafTimedOut = !signal.aborted && leafDeadlineCtl.signal.aborted; + const leafErr = + err instanceof LeafError + ? err + : new LeafError(`leaf transport error: ${err?.message || err}`, { + tag: "Transport", + code: err?.cause?.code || null, + }); + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: signal.aborted || leafTimedOut ? "timeout" : "failure", + errorTag: leafErr.tag || "Transport", + errorCode: leafErr.code ?? null, + errorStatus: leafErr.status ?? null, + errorMessage: String(leafErr.message || leafErr).slice(0, 500), + retryable: leafErr.retryable ?? 1, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: leafErr.quota ?? null, + }); + lastErr = leafErr; + if (signal.aborted) throw leafErr; + continue; + } finally { + clearTimeout(leafTimer); + } + } + if (!done && lastErr && isRetryableLeafError(lastErr)) { + // Every leaf failed retryably for this sub-batch: the whole + // run fails like a single-shot walk. + throw lastErr; + } + if (!done && lastErr) { + for (let k = 0; k < chunk.texts.length; k++) + if (itemErrors[chunk.start + k] === null) + itemErrors[chunk.start + k] = String(lastErr.message || lastErr).slice(0, 300); + } + } + const errors = []; + const data = []; + for (let i = 0; i < vectors.length; i++) { + if (itemErrors[i] !== null) errors.push({ index: i, message: itemErrors[i] }); + else data.push({ object: "embedding", index: i, embedding: vectors[i] }); + } + return { data, errors, model: clientBody.model }; + } finally { + clearTimeout(timer); + } +}; + +// ---------------------------------------------------------------- http + +const sendJson = (res, status, obj) => { + if (res.destroyed || res.writableEnded) return; + const body = JSON.stringify(obj); + res.writeHead(status, { "content-type": "application/json" }); + res.end(body); +}; +const sendError = (res, status, message) => + sendJson(res, status, { error: { message, type: "proxy_error" } }); + +// A wall-paced answer (#13693 RC-4): 503 with Retry-After until the +// earliest known reset, and a JSON error body naming the wall — the +// same { error: { message, type } } shape as every other proxy +// error, plus the retry-after header sendJson does not carry. +const sendWallPaced = (res, err) => { + if (res.destroyed || res.writableEnded) return; + const secs = Math.max(1, Math.ceil((err.retryAfterMs ?? 0) / 1000)); + res.writeHead(503, { + "content-type": "application/json", + "retry-after": String(secs), + }); + res.end( + JSON.stringify({ + error: { message: String(err?.message || err), type: "proxy_error" }, + }), + ); +}; + +const isPlainObject = (v) => + typeof v === "object" && v !== null && !Array.isArray(v); + +const parseRouteModel = (raw) => { + const model = typeof raw === "string" && raw ? raw : "workhorse"; + const id = model.startsWith("opencode-route/") + ? model.slice("opencode-route/".length) + : model; + const h = id.indexOf("#"); + return h > 0 + ? { routeId: id.slice(0, h), variant: id.slice(h + 1) } + : { routeId: id, variant: null }; +}; // Relay the already-inspected preface and the rest of the SSE stream. // A failure before a content delta is still a candidate failure; after a @@ -2002,8 +2884,7 @@ const handleChatCompletions = async (req, res, body) => { return sendError(res, 400, "messages must be an array"); if (body.messages.some((m) => !isPlainObject(m))) return sendError(res, 400, "each message must be an object"); - const { routeId, variant: reqVariant } = parseRouteModel(body.model); - const modelName = `opencode-route/${routeId}`; + const { routeId, variant: reqVariant } = parseRouteModel(body.model); const modelName = `opencode-route/${routeId}`; const clientCtl = new AbortController(); res.on("close", () => { if (!res.writableEnded) @@ -2059,6 +2940,285 @@ const handleChatCompletions = async (req, res, body) => { } }; +// New-endpoint error mapping: unknown routes 404 (the chat handler +// keeps its legacy 502 — an existing test asserts it), pool-purpose +// mismatches refuse 400, wall pacing answers 503, everything else +// 502. +const sendPurposeError = (res, err) => { + const msg = String(err?.message || err); + if (err?.wallPaced) return sendWallPaced(res, err); + if (msg.startsWith("unknown route:")) + return sendError(res, 404, msg); + if (msg.includes("cannot serve") || msg.includes("has no members")) + return sendError(res, 400, msg); + if (err instanceof LeafError && err.tag === "InvalidRequest" && err.retryable === 0) + return sendError(res, 400, msg); + return sendError(res, 502, msg); +}; + +const handleEmbeddings = async (req, res, body) => { + if (!isPlainObject(body)) + return sendError(res, 400, "request body must be a JSON object"); + const { routeId, variant: reqVariant } = parseRouteModel(body.model); + const input = body.input; + const validInput = + typeof input === "string" || + (Array.isArray(input) && + input.length > 0 && + input.every((t) => typeof t === "string")); + if (!validInput) + return sendError(res, 400, "input must be a string or a non-empty array of strings"); + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.writableEnded) clientCtl.abort(new Error("client disconnected")); + }); + const modelName = `opencode-route/${routeId}`; + try { + if (typeof input === "string") { + const { json, text } = await runSingleShotJson( + routeId, + "embed", + { model: body.model, input }, + clientCtl.signal, + reqVariant, + ); + if (json) { + // Normalize the Google single-item shape + // ({ embedding: { values } }) to the OpenAI embeddings + // shape so single and batch callers see one contract. + if (!Array.isArray(json.data) && json.embedding) { + const vec = json.embedding?.values ?? json.embedding; + return sendJson(res, 200, { + object: "list", + data: [{ object: "embedding", index: 0, embedding: vec }], + model: modelName, + }); + } + json.model = modelName; + return sendJson(res, 200, json); + } + if (!res.destroyed && !res.writableEnded) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(text); + } + return; + } + const { data, errors, model } = await runEmbeddingsA2( + routeId, + { model: body.model, input }, + clientCtl.signal, + reqVariant, + ); + void model; + const out = { object: "list", data, model: modelName }; + if (errors.length) { + out.errors = errors; + return sendJson(res, 207, out); + } + return sendJson(res, 200, out); + } catch (err) { + return sendPurposeError(res, err); + } +}; + +const handleDecisions = async (req, res, body) => { + if (!isPlainObject(body)) + return sendError(res, 400, "request body must be a JSON object"); + const { routeId, variant: reqVariant } = parseRouteModel(body.model); + if (!("input" in body)) + return sendError(res, 400, "input is required"); + if (!isPlainObject(body.questions)) + return sendError(res, 400, "questions must be an object"); + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.writableEnded) clientCtl.abort(new Error("client disconnected")); + }); + try { + const { json, text } = await runSingleShotJson( + routeId, + "decision", + { model: body.model, input: body.input, questions: body.questions }, + clientCtl.signal, + reqVariant, + ); + if (json) return sendJson(res, 200, json); + if (!res.destroyed && !res.writableEnded) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(text); + } + } catch (err) { + return sendPurposeError(res, err); + } +}; + +const handleRerank = async (req, res, body) => { + if (!isPlainObject(body)) + return sendError(res, 400, "request body must be a JSON object"); + const { routeId, variant: reqVariant } = parseRouteModel(body.model); + if (typeof body.query !== "string" || !body.query) + return sendError(res, 400, "query must be a non-empty string"); + if (!Array.isArray(body.documents) || !body.documents.length) + return sendError(res, 400, "documents must be a non-empty array"); + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.writableEnded) clientCtl.abort(new Error("client disconnected")); + }); + try { + const { json, text } = await runSingleShotJson( + routeId, + "rerank", + { model: body.model, query: body.query, documents: body.documents }, + clientCtl.signal, + reqVariant, + ); + if (json) return sendJson(res, 200, json); + if (!res.destroyed && !res.writableEnded) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(text); + } + } catch (err) { + return sendPurposeError(res, err); + } +}; + +// Extract the `model` form field from a multipart body without a +// dependency: enough to route the transcription request. +const multipartModelField = (buf, contentType) => { + const m = /boundary=([^;]+)/i.exec(contentType || ""); + if (!m) return null; + const boundary = m[1].trim().replace(/^"|"$/g, ""); + const text = buf.toString("latin1"); + const re = new RegExp( + `--${boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?name="model"[\\s\\S]*?\r\n\r\n([^\r\n]+)`, + ); + const hit = re.exec(text); + return hit ? hit[1].trim() : null; +}; + +const handleTranscriptions = async (req, res, raw, contentType) => { + const modelRaw = + multipartModelField(raw, contentType) || + new URL(req.url, `http://${HOST}:${PORT}`).searchParams.get("model"); + if (!modelRaw) return sendError(res, 400, "multipart model field is required"); + const { routeId, variant: reqVariant } = parseRouteModel(modelRaw); + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.destroyed && !res.writableEnded) clientCtl.abort(new Error("client disconnected")); + }); + try { + const out = await runAudioPassthrough( + routeId, + "transcribe", + raw, + contentType, + clientCtl.signal, + reqVariant, + ); + if (!res.destroyed && !res.writableEnded) { + res.writeHead(out.status, { "content-type": out.contentType }); + res.end(out.body); + } + } catch (err) { + return sendPurposeError(res, err); + } +}; + +const handleSpeech = async (req, res, body) => { + if (!isPlainObject(body)) + return sendError(res, 400, "request body must be a JSON object"); + const { routeId, variant: reqVariant } = parseRouteModel(body.model); + if (typeof body.input !== "string" || !body.input) + return sendError(res, 400, "input must be a non-empty string"); + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.destroyed && !res.writableEnded) clientCtl.abort(new Error("client disconnected")); + }); + try { + const out = await runAudioPassthrough( + routeId, + "speak", + Buffer.from(JSON.stringify({ ...body, model: body.model }), "utf8"), + "application/json", + clientCtl.signal, + reqVariant, + ); + if (!res.destroyed && !res.writableEnded) { + res.writeHead(out.status, { "content-type": out.contentType }); + res.end(out.body); + } + } catch (err) { + return sendPurposeError(res, err); + } +}; + +const handleGuard = async (req, res, body) => { + if (!isPlainObject(body)) + return sendError(res, 400, "request body must be a JSON object"); + if (!Array.isArray(body.messages)) + return sendError(res, 400, "messages must be an array"); + if (body.messages.some((m) => !isPlainObject(m))) + return sendError(res, 400, "each message must be an object"); + const { routeId, variant: reqVariant } = parseRouteModel(body.model); + const modelName = `opencode-route/${routeId}`; + const clientCtl = new AbortController(); + res.on("close", () => { + if (!res.writableEnded) + clientCtl.abort(new Error("client disconnected")); + }); + try { + const { json, text } = await runCompletion(routeId, body, clientCtl.signal, { + variantIn: reqVariant, + requiredPurpose: "guard", + }); + if (json) { + json.model = modelName; + return sendJson(res, 200, json); + } + if (!res.destroyed && !res.writableEnded) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(text); + } + } catch (err) { + return sendPurposeError(res, err); + } +}; + +const collectJsonBody = (req, res, onBody) => { + const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); + req.on("data", (chunk) => { + if (bodyCollector.tooLarge) return; + if (!bodyCollector.push(chunk)) { + sendError(res, 413, "request body too large"); + req.destroy(); + } + }); + req.on("end", async () => { + if (bodyCollector.tooLarge) return; + let body = {}; + try { + body = JSON.parse(bodyCollector.text() || "{}"); + } catch { + return sendError(res, 400, "invalid JSON body"); + } + await onBody(body); + }); +}; + +const collectRawBody = (req, res, limitBytes, onBody) => { + const bodyCollector = createRequestBodyCollector(limitBytes); + req.on("data", (chunk) => { + if (bodyCollector.tooLarge) return; + if (!bodyCollector.push(chunk)) { + sendError(res, 413, "request body too large"); + req.destroy(); + } + }); + req.on("end", async () => { + if (bodyCollector.tooLarge) return; + await onBody(bodyCollector.bytes()); + }); +}; + const server = createServer(async (req, res) => { res.on("error", () => {}); try { @@ -2082,24 +3242,33 @@ const server = createServer(async (req, res) => { // body arrives (#4335): per-chunk string coercion corrupts multibyte // characters split across TCP chunks. Cap 50 MB like the sibling // proxies (bin/request-body.mjs collector) with a 413 past the cap. - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on("data", (chunk) => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - sendError(res, 413, "request body too large"); - req.destroy(); - } - }); - req.on("end", async () => { - if (bodyCollector.tooLarge) return; - let body = {}; - try { - body = JSON.parse(bodyCollector.text() || "{}"); - } catch { - return sendError(res, 400, "invalid JSON body"); - } - await handleChatCompletions(req, res, body); - }); + collectJsonBody(req, res, (body) => handleChatCompletions(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/embeddings") { + collectJsonBody(req, res, (body) => handleEmbeddings(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/decisions") { + collectJsonBody(req, res, (body) => handleDecisions(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/rerank") { + collectJsonBody(req, res, (body) => handleRerank(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/guard") { + collectJsonBody(req, res, (body) => handleGuard(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/audio/speech") { + collectJsonBody(req, res, (body) => handleSpeech(req, res, body)); + return; + } + if (req.method === "POST" && url.pathname === "/v1/audio/transcriptions") { + collectRawBody(req, res, 50 * 1024 * 1024, (raw) => + handleTranscriptions(req, res, raw, req.headers["content-type"] || ""), + ); return; } return sendError(res, 404, `no route for ${req.method} ${url.pathname}`); diff --git a/bin/opencode-route-proxy.test.mjs b/bin/opencode-route-proxy.test.mjs index 2f27810a2..9570ccb0e 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -50,7 +50,9 @@ const makeLeaf = (name, expectedKey) => { } catch {} leaf.last = { headers: req.headers, body, url: req.url }; if (leaf.mode === "slow") return; - if (req.headers.authorization !== `Bearer ${expectedKey}`) { + const bearerOk = req.headers.authorization === `Bearer ${expectedKey}`; + const googOk = req.headers["x-goog-api-key"] === expectedKey; + if (!bearerOk && !googOk) { res.writeHead(401, { "content-type": "application/json" }); return res.end(JSON.stringify({ error: { message: "bad key" } })); } @@ -166,6 +168,112 @@ const makeLeaf = (name, expectedKey) => { res.write(": heartbeat\n\n"); return setTimeout(() => res.destroy(), 10); } + if (leaf.mode === "embed-400") { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad embedding request" } })); + } + if (req.url.includes(":batchEmbedContent")) { + // Google native batch shape. + const reqs = Array.isArray(body.requests) ? body.requests : []; + if (reqs.some((r) => typeof r?.content?.parts?.[0]?.text !== "string")) { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad batch request" } })); + } + if ( + leaf.mode === "embed-bad-item" && + reqs.some((r) => String(r.content.parts[0].text).includes("bad")) + ) { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad item" } })); + } + res.writeHead(200, { "content-type": "application/json" }); + return res.end( + JSON.stringify({ + embeddings: reqs.map((r) => ({ + values: [r.content.parts[0].text.length, 0.5], + })), + }), + ); + } + if (req.url.includes(":embedContent")) { + // Google native single shape. + const text = body?.content?.parts?.[0]?.text; + if (typeof text !== "string") { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad embed request" } })); + } + res.writeHead(200, { "content-type": "application/json" }); + return res.end( + JSON.stringify({ embedding: { values: [text.length, 0.5] } }), + ); + } + if (req.url.includes("/embeddings")) { + const input = body.input; + const texts = typeof input === "string" ? [input] : input; + if ( + leaf.mode === "embed-bad-item" && + Array.isArray(texts) && + texts.some((t) => typeof t === "string" && t.includes("bad")) + ) { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad item" } })); + } + if (typeof input === "string") { + res.writeHead(200, { "content-type": "application/json" }); + return res.end( + JSON.stringify({ + object: "list", + data: [{ object: "embedding", index: 0, embedding: [input.length, 0.5] }], + model: body.model, + }), + ); + } + if (Array.isArray(input) && input.every((t) => typeof t === "string")) { + res.writeHead(200, { "content-type": "application/json" }); + return res.end( + JSON.stringify({ + object: "list", + data: input.map((t, i) => ({ + object: "embedding", + index: i, + embedding: [t.length, 0.5], + })), + model: body.model, + }), + ); + } + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad embedding input" } })); + } + if (req.url.includes("/decisions")) { + if (leaf.mode === "dec-400") { + res.writeHead(400, { "content-type": "application/json" }); + return res.end(JSON.stringify({ error: { message: "bad decision" } })); + } + res.writeHead(200, { "content-type": "application/json" }); + return res.end( + JSON.stringify({ decision: "yes", model: body.model, echo: body.input ?? null }), + ); + } + if (req.url.includes("/rerank")) { + res.writeHead(200, { "content-type": "application/json" }); + const docs = Array.isArray(body.documents) ? body.documents : []; + return res.end( + JSON.stringify({ + results: docs.map((d, i) => ({ index: i, score: 1 - i * 0.1, document: d })), + model: body.model, + }), + ); + } + if (req.url.includes("/audio/transcriptions")) { + res.writeHead(200, { "content-type": "application/json" }); + return res.end(JSON.stringify({ text: `transcribed-by-${name}` })); + } + if (req.url.includes("/audio/speech")) { + const audio = Buffer.from(`audio-by-${name}`, "utf8"); + res.writeHead(200, { "content-type": "audio/mpeg", "content-length": audio.length }); + return res.end(audio); + } if (body.stream) { res.writeHead(200, { "content-type": "text/event-stream" }); const chunk = (delta, usage) => @@ -366,6 +474,66 @@ const startProxy = async (arg = {}) => { "options": { "baseURL": "http://127.0.0.1:${leafB.port}/v1", "apiKey": "key-b" }, "models": { "m-b": {} }, }, + "leafG": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://127.0.0.1:${leafA.port}/v1beta", + "apiKey": "key-a", + "endpoints": { + "embed": { "kind": "google-embed", "path": "/models/{model}:embedContent" }, + "decision": { "kind": "google-decisions", "path": "/decisions" } + } + }, + "models": { "m-ge": {}, "m-gd": {} }, + }, + "leafGsplit": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://127.0.0.1:${leafA.port}/v1beta", + "apiKey": "key-a", + "endpoints": { + "embed": { "kind": "google-embed", "path": "/models/{model}:embedContent", "maxBatchItems": 2 } + } + }, + "models": { "m-ge": {} }, + }, + "leafZ": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://127.0.0.1:${leafA.port}/v1", + "apiKey": "key-a", + "endpoints": { + "decision": { "kind": "jev-systemone", "path": "/decisions" } + } + }, + "models": { "m-zd": {} }, + }, + "leafF": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://127.0.0.1:${leafA.port}/v1", + "apiKey": "key-a", + "endpoints": { + "decision": { "kind": "fireworks", "path": "/decisions" } + } + }, + "models": { "m-fd": {} }, + }, + "leafWeird": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://127.0.0.1:${leafA.port}/v1", + "apiKey": "key-a", + "endpoints": { + "decision": { "kind": "not-a-real-kind", "path": "/decisions" } + } + }, + "models": { "m-wd": {} }, + }, + }, + "model_designations": { + "m-desig-dec": { "purposes": ["decision"] }, + "m-desig-chat": { "purposes": ["chat"] } }, "experimental": { "provider_routes": { @@ -419,6 +587,20 @@ const startProxy = async (arg = {}) => { "t-group-skip": { "selection": "ordered", "targets": ["grp-ordered/m-a"] }, "t-openai-default": { "selection": "ordered", "targets": ["openai/m-gpt"] }, "t-a-only": { "selection": "ordered", "targets": ["leafA/m-a"] }, + "t-decide": { "purpose": "decision", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-decide-goog": { "purpose": "decision", "selection": "ordered", "targets": ["leafG/m-gd"] }, + "t-decide-zen": { "purpose": "decision", "selection": "ordered", "targets": ["leafZ/m-zd"] }, + "t-decide-fw": { "purpose": "decision", "selection": "ordered", "targets": ["leafF/m-fd"] }, + "t-decide-weird": { "purpose": "decision", "selection": "ordered", "targets": ["leafWeird/m-wd"] }, + "t-decide-desig": { "purpose": "decision", "selection": "ordered", "targets": ["leafA/m-desig-dec", "leafB/m-desig-chat"] }, + "t-embed": { "purpose": "embed", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-embed-goog": { "purpose": "embed", "selection": "ordered", "targets": ["leafG/m-ge"] }, + "t-embed-split": { "purpose": "embed", "selection": "ordered", "targets": ["leafGsplit/m-ge"] }, + "t-rerank": { "purpose": "rerank", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-transcribe": { "purpose": "transcribe", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-speak": { "purpose": "speak", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-guard": { "purpose": "guard", "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, + "t-chat-desig": { "selection": "ordered", "targets": ["leafA/m-desig-dec", "leafB/m-b"] }, }, }, }`, @@ -2156,3 +2338,354 @@ test("429 with {\"retryDelay\": \"30s\"} JSON gates the pair (#13693)", async () await p.cleanup(); } }); + +// ---------------- Part 2: purpose-routed endpoints (#13675 P2) ---------------- +// +// Helpers for the non-chat doors. p.post only targets chat; these hit +// the purpose endpoints directly. +const postPurpose = (p, endpoint, payload, raw) => + fetch(`${p.base}${endpoint}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: raw !== undefined ? raw : JSON.stringify(payload), + }); + +const postTranscription = (p, model, fileBytes = "fake-audio-bytes") => { + const boundary = "----part2testboundary"; + const body = + `--${boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\n${model}\r\n` + + `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="a.wav"\r\n` + + `Content-Type: audio/wav\r\n\r\n${fileBytes}\r\n` + + `--${boundary}--\r\n`; + return fetch(`${p.base}/v1/audio/transcriptions`, { + method: "POST", + headers: { "content-type": `multipart/form-data; boundary=${boundary}` }, + body, + }); +}; + +test("decisions have no OpenAI default: plain leaves refuse with 400 (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide", + input: { state: 1 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 400); + assert.match(await res.text(), /no members serving decision/); + assert.equal(p.leafA.hits, 0); + assert.equal(p.leafB.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("decisions dispatch natively via google-decisions with x-goog-api-key (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide-goog", + input: { state: 1 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.decision, "yes"); + assert.ok(p.leafA.last.url.includes("/decisions")); + assert.equal(p.leafA.last.headers["x-goog-api-key"], "key-a"); + assert.ok(!("authorization" in p.leafA.last.headers)); + const rows = await waitForAttempts(p, 1); + assert.equal(rows[0].route_id, "t-decide-goog"); + assert.equal(rows[0].outcome, "success"); + assert.equal(rows[0].session_id, null); + } finally { + await p.cleanup(); + } +}); + +test("decisions dispatch via jev-systemone with Bearer auth (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide-zen", + input: { state: 2 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).decision, "yes"); + assert.ok(p.leafA.last.url.endsWith("/decisions")); + assert.equal(p.leafA.last.headers.authorization, "Bearer key-a"); + } finally { + await p.cleanup(); + } +}); + +test("decisions dispatch via fireworks passthrough with required path (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide-fw", + input: { state: 3 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).model, "m-fd"); + } finally { + await p.cleanup(); + } +}); + +test("unknown decision kinds never invent a surface (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide-weird", + input: { state: 1 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 400); + assert.match(await res.text(), /no members serving decision/); + assert.equal(p.leafA.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("new-endpoint unknown routes 404; pool-purpose mismatches refuse 400 (#13675 P2)", async () => { + const p = await startProxy(); + try { + const unknown = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/no-such-pool", + input: { state: 1 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(unknown.status, 404); + assert.match(await unknown.text(), /unknown route/); + const mismatch = await postPurpose(p, "/v1/embeddings", { + model: "opencode-route/t-decide-goog", + input: "hello", + }); + assert.equal(mismatch.status, 400); + assert.match(await mismatch.text(), /cannot serve embed/); + assert.equal(p.leafA.hits, 0); + assert.equal(p.leafB.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("chat calls naming a decision pool are refused, never forwarded (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await p.post({ + model: "opencode-route/t-decide-goog", + messages: MSGS, + }); + assert.equal(res.status, 502); + assert.match(await res.text(), /cannot serve chat/); + assert.equal(p.leafA.hits, 0); + assert.equal(p.leafB.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("runtime designations filter leaves at dispatch (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/decisions", { + model: "opencode-route/t-decide-desig", + input: { state: 1 }, + questions: { ok: { type: "noul" } }, + }); + assert.equal(res.status, 400); + const chat = await p.post({ + model: "opencode-route/t-chat-desig", + messages: MSGS, + }); + assert.equal(chat.status, 200); + assert.equal((await chat.json()).choices[0].message.content, "LEAF-B"); + const rows = await waitForAttempts(p, 1); + assert.equal(rows[0].provider_id, "leafB"); + } finally { + await p.cleanup(); + } +}); + +test("embeddings serve a single string via the OpenAI default (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/embeddings", { + model: "opencode-route/t-embed", + input: "hello", + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.object, "list"); + assert.equal(json.data.length, 1); + assert.equal(json.data[0].index, 0); + assert.deepEqual(json.data[0].embedding, [5, 0.5]); + assert.equal(json.model, "opencode-route/t-embed"); + } finally { + await p.cleanup(); + } +}); + +test("embeddings normalize the google single-item shape (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/embeddings", { + model: "opencode-route/t-embed-goog", + input: "hello", + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.object, "list"); + assert.equal(json.data.length, 1); + assert.deepEqual(json.data[0].embedding, [5, 0.5]); + assert.ok(p.leafA.last.url.includes(":embedContent")); + } finally { + await p.cleanup(); + } +}); + +test("A2 splits oversized batches and re-joins in caller order (#13675 P2)", async () => { + const p = await startProxy(); + try { + const input = ["a", "bb", "ccc", "dddd", "eeeee"]; + const res = await postPurpose(p, "/v1/embeddings", { + model: "opencode-route/t-embed-split", + input, + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.data.length, 5); + for (let i = 0; i < 5; i++) { + assert.equal(json.data[i].index, i); + assert.deepEqual(json.data[i].embedding, [input[i].length, 0.5]); + } + assert.ok(!("errors" in json)); + } finally { + await p.cleanup(); + } +}); + +test("A2 retryable sub-batch failure fails over to the next candidate (#13675 P2)", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "rate"; + const ok = await postPurpose(p, "/v1/embeddings", { + model: "opencode-route/t-embed", + input: ["aa", "bbb"], + }); + assert.equal(ok.status, 200); + const okJson = await ok.json(); + assert.equal(okJson.data.length, 2); + assert.deepEqual(okJson.data[0].embedding, [2, 0.5]); + assert.deepEqual(okJson.data[1].embedding, [3, 0.5]); + assert.equal(p.leafA.hits, 1); + assert.equal(p.leafB.hits, 1); + } finally { + await p.cleanup(); + } +}); + +test("A2 non-retryable sub-batch failure answers 207 with index-faithful errors (#13675 P2)", async () => { + const q = await startProxy(); + try { + q.leafA.mode = "embed-bad-item"; + const res = await postPurpose(q, "/v1/embeddings", { + model: "opencode-route/t-embed-split", + input: ["aa", "bb", "bad-1", "bad-2", "cc"], + }); + assert.equal(res.status, 207); + const json = await res.json(); + assert.deepEqual( + json.data.map((d) => d.index), + [0, 1, 4], + ); + assert.deepEqual( + json.errors.map((e) => e.index), + [2, 3], + ); + assert.deepEqual(json.data[0].embedding, [2, 0.5]); + assert.deepEqual(json.data[2].embedding, [2, 0.5]); + } finally { + await q.cleanup(); + } +}); + +test("rerank relays documents with scores (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/rerank", { + model: "opencode-route/t-rerank", + query: "what", + documents: ["doc-a", "doc-b"], + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.results.length, 2); + assert.equal(json.results[0].index, 0); + assert.ok(json.results[0].score > json.results[1].score); + const bad = await postPurpose(p, "/v1/rerank", { + model: "opencode-route/t-rerank", + query: "", + documents: [], + }); + assert.equal(bad.status, 400); + } finally { + await p.cleanup(); + } +}); + +test("transcription relays the leaf answer bytes untouched (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postTranscription(p, "opencode-route/t-transcribe"); + assert.equal(res.status, 200); + assert.equal((await res.json()).text, "transcribed-by-LEAF-A"); + const missing = await postPurpose(p, "/v1/audio/transcriptions", null, "--x\r\n"); + assert.equal(missing.status, 400); + } finally { + await p.cleanup(); + } +}); + +test("speech relays leaf audio bytes with the leaf content-type (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/audio/speech", { + model: "opencode-route/t-speak", + input: "say this", + voice: "alloy", + }); + assert.equal(res.status, 200); + assert.match(res.headers.get("content-type"), /audio\/mpeg/); + assert.equal(Buffer.from(await res.arrayBuffer()).toString("utf8"), "audio-by-LEAF-A"); + } finally { + await p.cleanup(); + } +}); + +test("guard serves chat-shaped calls through the guard pool only (#13675 P2)", async () => { + const p = await startProxy(); + try { + const res = await postPurpose(p, "/v1/guard", { + model: "opencode-route/t-guard", + messages: MSGS, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-A"); + assert.ok(p.leafA.last.url.endsWith("/chat/completions")); + const mismatch = await postPurpose(p, "/v1/guard", { + model: "opencode-route/t-ordered", + messages: MSGS, + }); + assert.equal(mismatch.status, 400); + assert.match(await mismatch.text(), /cannot serve guard/); + } finally { + await p.cleanup(); + } +}); diff --git a/bin/request-body.mjs b/bin/request-body.mjs index 30bc6ff22..df9ffab0d 100644 --- a/bin/request-body.mjs +++ b/bin/request-body.mjs @@ -22,5 +22,9 @@ export function createRequestBodyCollector(maxBytes) { if (tooLarge) throw new Error('Request body exceeds configured byte limit'); return Buffer.concat(chunks, byteLength).toString('utf8'); }, + bytes() { + if (tooLarge) throw new Error('Request body exceeds configured byte limit'); + return Buffer.concat(chunks, byteLength); + }, }; }