import { randomUUID } from 'node:crypto' import { createAnthropic } from '@ai-sdk/anthropic' import { createGoogleGenerativeAI } from '@ai-sdk/google' import { createOpenAI } from '@ai-sdk/openai' import { createOpenAICompatible } from '@ai-sdk/openai-compatible' import { APICallError, type LanguageModelV3, type LanguageModelV3Content, type LanguageModelV3Prompt, type LanguageModelV3StreamPart, type LanguageModelV3Usage, type SharedV3ProviderMetadata, } from '@ai-sdk/provider' import { type ChatCompletionParams, type LLMProvider, type ModelInfo, type ProviderCapabilities, ProviderRequestError, type ReasoningEffort, type StreamChunk, type ThinkingConfig, type TokenUsage, attributionHeaders, isProviderRequestError, providerHttpError, providerVendorError, } from '@namzu/sdk' import { type ZenCatalogue, findZenCatalogueModel, isUnroutedZenModel, } from './catalogue/catalogue.js' import { isExperimentalFreeZenModel } from './catalogue/experimental-free.js' import { experimentalOpenCodeRequestId, experimentalOpenCodeSessionId, experimentalOpenCodeUserAgent, } from './experimental-identity.js' import type { ZenModel, ZenService } from './models.js' import { createCallOptions, goRejectsToolChoice, withZenFreeTierTools } from './options.js' import { createReplayState, isGoDeepSeekV4ResponsesModel, isMuseSparkResponsesModel, toReasoningBlocks, } from './prompt.js' import type { ZenConfig, ZenGoConfig } from './types.js' export const ZEN_CAPABILITIES: ProviderCapabilities = { supportsTools: true, supportsStreaming: true, supportsFunctionCalling: true, supportsNativeStructuredOutput: true, supportsVision: true, supportsDocuments: true, supportsToolResultImages: true, supportsToolResultDocuments: true, } export const ZEN_BASE_URL = 'https://opencode.ai/zen/v1' export const ZEN_GO_BASE_URL = 'https://opencode.ai/zen/go/v1' /** * The host the anonymous free tier is served from. * * `ZEN_BASE_URL` remains the route for every keyed request, but the free-tier * gateway refuses anonymous traffic on it: `POST /zen/v1/chat/completions` * answers `403 FreeTierError` ("can only be used from within OpenCode") no * matter how faithfully the request is shaped. The same request against * `/inference/v1/chat/completions` is admitted, and that is the path OpenCode * itself now speaks. Only the chat route is reachable anonymously — `/models` * answers on both, and the Anthropic and Responses routes answer `401 Missing * API key` on either, which is why the gate never offered them free access to * begin with. */ export const ZEN_FREE_TIER_BASE_URL = 'https://opencode.ai/inference/v1' function withoutMuseSparkEncryptedReasoning(init?: RequestInit): RequestInit { // The pinned OpenAI adapter adds this include automatically whenever a // reasoning model uses store:false, even if providerOptions omits it. // Muse Spark cannot round-trip that gateway-issued ciphertext. Keep the // request stateless and preserve every other include the adapter may add. if (typeof init?.body !== 'string') throw new Error('Zen Muse Spark adapter emitted a request body that cannot be checked.') const body: unknown = JSON.parse(init.body) if (typeof body !== 'object' || body === null || Array.isArray(body)) throw new Error('Zen Muse Spark adapter emitted an invalid request body.') const request = body as Record if (request.include !== undefined) { if ( !Array.isArray(request.include) || !request.include.every((item) => typeof item === 'string') ) throw new Error('Zen Muse Spark adapter emitted an invalid include list.') const include = request.include.filter((item) => item !== 'reasoning.encrypted_content') if (include.length > 0) request.include = include else request.include = undefined } return { ...init, body: JSON.stringify(request) } } function isGoDeepSeekV4ChatModel(service: ZenService, model: string, protocol: string): boolean { return ( service === 'go' && protocol === 'chat' && (model === 'deepseek-v4-pro' || model === 'deepseek-v4.1-flash' || model === 'deepseek-v4-flash') ) } function adapterBody(init: RequestInit | undefined, model: string): Record { if (typeof init?.body !== 'string') throw new Error(`Zen adapter emitted a non-JSON request body for ${model}.`) const body: unknown = JSON.parse(init.body) if (typeof body !== 'object' || body === null || Array.isArray(body)) throw new Error(`Zen adapter emitted an invalid request body for ${model}.`) return body as Record } function withGoDeepSeekV4ChatHistory(init: RequestInit | undefined, model: string): RequestInit { const body = adapterBody(init, model) if (!Array.isArray(body.messages)) throw new Error('Go DeepSeek chat request has no messages.') for (const value of body.messages) { if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('Go DeepSeek chat request has an invalid message.') const message = value as Record if (message.role !== 'assistant') continue if (message.content === null) message.content = '' if (message.reasoning_content === undefined || message.reasoning_content === null) message.reasoning_content = '' else if (typeof message.reasoning_content !== 'string') throw new Error('Go DeepSeek chat request has invalid reasoning content.') } return { ...init, body: JSON.stringify(body) } } function withGoDeepSeekV4ResponsesHistory( init: RequestInit | undefined, model: string, prompt: LanguageModelV3Prompt, ): RequestInit { const body = adapterBody(init, model) if (!Array.isArray(body.input)) throw new Error('Go DeepSeek Responses request has no input.') const input: Record[] = [] let turn: Record[] = [] const sourceTurns = prompt.filter((message) => message.role === 'assistant') let sourceIndex = 0 const refuse = (): never => { throw new ProviderRequestError({ providerId: 'zen-go', kind: 'bad_request', detail: `Go DeepSeek ${model} requires captured, nonempty reasoning_text for each previous assistant turn. This history cannot be replayed safely.`, }) } const flushTurn = () => { if (turn.length === 0) return const source = sourceTurns[sourceIndex++] if (source?.role !== 'assistant') return refuse() const messages = turn.filter((item) => item.role === 'assistant') const calls = turn.filter((item) => item.type === 'function_call') const sourceText = source.content .filter((part) => part.type === 'text') .map((part) => part.text) const wireText = messages.flatMap((message) => Array.isArray(message.content) ? message.content .filter( (part) => typeof part === 'object' && part !== null && part.type === 'output_text', ) .map((part) => part.text) : [], ) const sourceCalls = source.content .filter((part) => part.type === 'tool-call') .map((part) => part.toolCallId) const wireCalls = calls.map((call) => call.call_id) if ( JSON.stringify(sourceText) !== JSON.stringify(wireText) || JSON.stringify(sourceCalls) !== JSON.stringify(wireCalls) ) refuse() const captured = source.content .filter((part) => part.type === 'reasoning') .map((part) => part.text) .filter((text) => text.trim().length > 0) .join('\n') if (!captured) refuse() const reasoning = { type: 'reasoning', summary: [], content: [{ type: 'reasoning_text', text: captured }], } // The adapter can replay a native [tool-call, text] turn as a call then // an assistant message. Go rejects a message between calls and outputs. input.push(reasoning, ...messages, ...calls) turn = [] } for (const value of body.input) { if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('Go DeepSeek Responses request has an invalid input item.') const item = value as Record if (item.type === 'reasoning' || item.type === 'function_call' || item.role === 'assistant') { turn.push(item) } else { flushTurn() input.push(item) } } flushTurn() if (sourceIndex !== sourceTurns.length) refuse() body.input = input return { ...init, body: JSON.stringify(body) } } function withGoDeepSeekReasoningTextEvents(response: Response): Response { if ( !response.ok || !response.body || !response.headers.get('content-type')?.includes('text/event-stream') ) return response // @ai-sdk/openai 3.0.109 understands reasoning summary deltas but not the // reasoning_text delta that Go DeepSeek streams. Translate that one event // before the adapter parses SSE; the original text then enters durable replay. const decoder = new TextDecoder() const encoder = new TextEncoder() let pending = '' const rewrite = (event: string): string => { const lines = event.split(/\r\n|\n|\r/) const dataLines = lines.filter((line) => line.startsWith('data:')) if (dataLines.length !== 1) return event let value: unknown try { value = JSON.parse(dataLines[0]?.slice(5).trimStart() ?? '') } catch { return event } if ( typeof value !== 'object' || value === null || !('type' in value) || value.type !== 'response.reasoning_text.delta' || !('item_id' in value) || typeof value.item_id !== 'string' || !('delta' in value) || typeof value.delta !== 'string' ) return event const translated = { ...value, type: 'response.reasoning_summary_text.delta', summary_index: 0, } return lines .map((line) => { if (line.startsWith('data:')) return `data: ${JSON.stringify(translated)}` if (line.startsWith('event:')) return 'event: response.reasoning_summary_text.delta' return line }) .join('\n') } const body = response.body.pipeThrough( new TransformStream({ transform(chunk, controller) { pending += decoder.decode(chunk, { stream: true }) while (true) { const boundary = /\r\n\r\n|\n\n|\r\r/.exec(pending) if (!boundary) break const event = pending.slice(0, boundary.index) pending = pending.slice(boundary.index + boundary[0].length) controller.enqueue(encoder.encode(`${rewrite(event)}\n\n`)) } }, flush(controller) { pending += decoder.decode() if (pending) controller.enqueue(encoder.encode(pending)) }, }), ) const headers = new Headers(response.headers) headers.delete('content-length') headers.delete('content-encoding') return new Response(body, { status: response.status, statusText: response.statusText, headers, }) } /** * The words a backend's own finish reason uses, in `LanguageModelV3FinishReason.raw`, * for "the model's context window, not its output-token budget, is what ran * out" — Anthropic's `model_context_window_exceeded` (folded, with * `max_tokens`, into `unified: 'length'` by `@ai-sdk/anthropic`'s * `mapAnthropicStopReason`) and the words other OpenAI-compatible backends * use (see `@namzu/http`'s `mapOpenAIFinish`), since Zen also routes through * `@ai-sdk/openai-compatible`. */ const CONTEXT_WINDOW_RAW_FINISH_REASONS = new Set([ 'model_context_window_exceeded', 'model_length', 'context_length', 'context_length_exceeded', ]) /** A provider instance belongs to one conversation; it never owns an agent loop. */ export class ZenProvider implements LLMProvider { readonly id: 'zen' | 'zen-go' readonly name: string readonly capabilities = ZEN_CAPABILITIES readonly sessionId: string private readonly baseURL: string private readonly timeout: number private readonly requestFetch: ( input: Parameters[0], init?: RequestInit, overrides?: Readonly>, ) => ReturnType private readonly apiKey: string private readonly anonymous: boolean constructor( private readonly config: ZenConfig = {}, readonly service: ZenService = 'zen', ) { if (service !== 'zen' && service !== 'go') throw new Error('Unknown service.') if (config.protocol && !['chat', 'responses', 'messages', 'google'].includes(config.protocol)) throw new Error('Unknown model protocol.') if ( config.catalogue !== undefined && typeof config.catalogue !== 'function' && (typeof config.catalogue !== 'object' || config.catalogue === null) ) throw new Error('catalogue must be a Zen catalogue or a function returning one.') this.id = service === 'go' ? 'zen-go' : 'zen' this.name = service === 'go' ? 'Zen Go' : 'Zen' if (config.apiKey !== undefined && typeof config.apiKey !== 'string') throw new Error('apiKey must be a string.') const apiKey = config.apiKey?.trim() this.anonymous = !apiKey || apiKey === 'public' if (service === 'go' && this.anonymous) throw new Error('Zen Go requires an API key.') // OpenCode uses this non-secret sentinel for its documented anonymous models. this.apiKey = apiKey || 'public' this.sessionId = config.sessionId ?? randomUUID() if ( !this.sessionId.trim() || /[\r\n]/.test(this.sessionId) || Buffer.byteLength(this.sessionId) > 512 ) throw new Error('A nonempty, single-line conversation sessionId is required.') this.baseURL = (config.baseURL ?? (service === 'go' ? ZEN_GO_BASE_URL : ZEN_BASE_URL)).replace( /\/+$/, '', ) const url = new URL(this.baseURL) if ( !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash ) throw new Error( 'baseURL must be an HTTP(S) service URL without credentials, query or fragment.', ) this.timeout = config.timeout ?? 120_000 if (!Number.isSafeInteger(this.timeout) || this.timeout <= 0) throw new Error('timeout must be a positive integer in milliseconds.') this.requestFetch = (input, init, overrides) => { const headers = new Headers(init?.headers) for (const [key, value] of Object.entries(attributionHeaders())) headers.set(key, value) headers.set('x-opencode-session', this.sessionId) if (overrides) for (const [key, value] of Object.entries(overrides)) headers.set(key, value) return fetch(input, { ...init, headers, redirect: 'error' }) } } async *chatStream(params: ChatCompletionParams): AsyncIterable { const model = params.model || this.config.model || (this.anonymous ? 'space-bunny-free' : 'glm-5.3-flash') const catalogue = this.runtimeCatalogue() const info = findZenCatalogueModel(catalogue, this.service, model) // Every zero-price Zen model is admitted anonymously; the free-tier // gateway then decides per request. `supportsAnonymousAccess` still // marks the one model whose keyless path was verified directly. if (this.anonymous && !isExperimentalFreeZenModel(this.service, info)) throw new ProviderRequestError({ providerId: this.id, kind: 'auth', detail: 'Anonymous Zen access requires a listed free model with a known route. Configure an API key for other models.', }) const protocol = this.config.protocol ?? info?.protocol if (!protocol) throw new ProviderRequestError({ providerId: this.id, kind: 'bad_request', detail: isUnroutedZenModel(catalogue, this.service, model) ? 'The service serves this model, but no source states its wire format. Configure protocol explicitly.' : 'This model has no known wire format. Update the provider or configure protocol explicitly.', }) const route = params.providerRoute ?? { providerId: this.id, model, chainIndex: 0, } const controller = new AbortController() const signal = AbortSignal.any([ controller.signal, AbortSignal.timeout(this.timeout), ...(params.signal ? [params.signal] : []), ]) let reader: ReadableStreamDefaultReader | undefined // The free-tier gateway admits an anonymous request only when it is // shaped as the OpenCode client shapes it: an OpenCode User-Agent, a // descending `ses_` session id, and the four tool names the client // always registers. A caller-owned base URL is not the gateway, so the // identity stays off it. const freeTierGate = this.anonymous && this.baseURL === ZEN_BASE_URL // Shape alone is not enough on `ZEN_BASE_URL`: the gateway turned the // anonymous route away there and answers `403 FreeTierError`. Serve the // gated request from the host that still admits it, and leave every // keyed request on `this.baseURL`. const requestBaseURL = freeTierGate ? ZEN_FREE_TIER_BASE_URL : this.baseURL const gateSession = freeTierGate ? experimentalOpenCodeSessionId(this.sessionId) : this.sessionId const gateHeaders = freeTierGate ? { 'User-Agent': experimentalOpenCodeUserAgent(), 'x-opencode-client': 'cli', 'x-opencode-project': 'global', 'x-opencode-session': gateSession, 'x-opencode-session-id': gateSession, } : undefined const modelFetch: typeof fetch = (input, init) => this.requestFetch( input, init, gateHeaders ? { ...gateHeaders, 'x-opencode-request': experimentalOpenCodeRequestId() } : undefined, ) try { signal.throwIfAborted() let options: ReturnType try { options = createCallOptions({ ...params, model }, route, this.service, protocol, info) } catch (error) { if (isProviderRequestError(error)) throw error throw new ProviderRequestError({ providerId: this.id, kind: 'bad_request', detail: 'The message history contains content this model protocol cannot encode.', }) } options = withZenFreeTierTools(options, freeTierGate, protocol !== 'responses') options.abortSignal = signal const settings = { apiKey: this.apiKey, baseURL: requestBaseURL, fetch: ((input, init) => { // The pinned Google adapter converts JSON Schema into an OpenAPI subset, // dropping constraints. Use the endpoint's JSON Schema field instead. if ( protocol === 'google' && params.responseFormat?.type === 'json_schema' && typeof init?.body === 'string' ) { const body = JSON.parse(init.body) body.generationConfig ??= {} delete body.generationConfig.responseSchema body.generationConfig.responseJsonSchema = params.responseFormat.json_schema.schema return modelFetch(input, { ...init, body: JSON.stringify(body), }) } if (isMuseSparkResponsesModel(model, protocol)) return modelFetch(input, withoutMuseSparkEncryptedReasoning(init)) if (isGoDeepSeekV4ChatModel(this.service, model, protocol)) return modelFetch(input, withGoDeepSeekV4ChatHistory(init, model)) if (isGoDeepSeekV4ResponsesModel(this.service, model, protocol)) return modelFetch( input, withGoDeepSeekV4ResponsesHistory(init, model, options.prompt), ).then(withGoDeepSeekReasoningTextEvents) return modelFetch(input, init) }) as typeof fetch, } let native: LanguageModelV3 switch (protocol) { case 'chat': native = createOpenAICompatible({ ...settings, name: 'opencode', includeUsage: true, supportsStructuredOutputs: true, })(model) break case 'responses': native = createOpenAI(settings).responses(model) break case 'messages': native = createAnthropic(settings)(model) break case 'google': native = createGoogleGenerativeAI(settings)(model) break } const result = await native.doStream(options) reader = result.stream.getReader() let id = randomUUID() as string const content: LanguageModelV3Content[] = [] const texts = new Map>() const thoughts = new Map< string, { index: number value: Extract } >() const tools = new Map< string, { index: number input: string ended: boolean value: Extract } >() let finish: Extract | undefined while (true) { const next = await reader.read() if (next.done) break const part = next.value signal.throwIfAborted() switch (part.type) { case 'stream-start': { const unsupported = part.warnings.filter((warning) => warning.type === 'unsupported') if (unsupported.length) throw new ProviderRequestError({ providerId: this.id, kind: 'bad_request', detail: 'The selected model protocol cannot honor one or more requested settings or content parts.', }) break } case 'response-metadata': if (part.id) id = part.id break case 'text-start': { const value = { type: 'text' as const, text: '', providerMetadata: part.providerMetadata, } texts.set(part.id, value) content.push(value) break } case 'text-delta': { const value = texts.get(part.id) if (!value) throw new Error('Text delta has no open block.') value.text += part.delta value.providerMetadata = mergeMetadata(value.providerMetadata, part.providerMetadata) yield { id, delta: { content: part.delta } } break } case 'text-end': { const value = texts.get(part.id) if (value) value.providerMetadata = mergeMetadata(value.providerMetadata, part.providerMetadata) break } case 'reasoning-start': { const value = { type: 'reasoning' as const, text: '', providerMetadata: part.providerMetadata, } const index = thoughts.size thoughts.set(part.id, { index, value }) content.push(value) yield { id, delta: { reasoning: { index, type: 'thinking', text: '' } }, } break } case 'reasoning-delta': case 'reasoning-end': { const thought = thoughts.get(part.id) if (!thought) throw new Error('Reasoning delta has no open block.') thought.value.providerMetadata = mergeMetadata( thought.value.providerMetadata, part.providerMetadata, ) if (part.type === 'reasoning-delta') thought.value.text += part.delta yield { id, delta: { reasoning: { index: thought.index, ...(part.type === 'reasoning-delta' ? { text: part.delta } : { ...toReasoningBlocks([thought.value])[0], text: undefined, done: true, }), }, }, } break } case 'tool-input-start': { if (part.providerExecuted) throw new Error('Provider-executed tools are not configured.') const index = tools.size const value = { type: 'tool-call' as const, toolCallId: part.id, toolName: part.toolName, input: '', providerMetadata: part.providerMetadata, } tools.set(part.id, { index, input: '', ended: false, value }) content.push(value) yield { id, delta: { toolCalls: [ { index, id: part.id, type: 'function', function: { name: part.toolName, arguments: '' }, }, ], }, } break } case 'tool-input-delta': { const tool = tools.get(part.id) if (!tool) throw new Error('Tool delta has no open call.') tool.input += part.delta tool.value.input = tool.input tool.value.providerMetadata = mergeMetadata( tool.value.providerMetadata, part.providerMetadata, ) yield { id, delta: { toolCalls: [{ index: tool.index, function: { arguments: part.delta } }], }, } break } case 'tool-input-end': { const tool = tools.get(part.id) if (tool) tool.value.providerMetadata = mergeMetadata( tool.value.providerMetadata, part.providerMetadata, ) // The final tool-call includes signatures and the authoritative arguments. break } case 'tool-call': { if (part.providerExecuted) throw new Error('Provider-executed tools are not configured.') let tool = tools.get(part.toolCallId) if (!tool) { tool = { index: tools.size, input: '', ended: false, value: { ...part }, } tools.set(part.toolCallId, tool) content.push(tool.value) yield { id, delta: { toolCalls: [ { index: tool.index, id: part.toolCallId, type: 'function', function: { name: part.toolName, arguments: '' }, }, ], }, } } if (tool.ended) throw new Error('Duplicate completed tool call.') if (!part.input.startsWith(tool.input)) throw new Error('Final tool arguments do not match the stream.') const suffix = part.input.slice(tool.input.length) if (suffix) yield { id, delta: { toolCalls: [{ index: tool.index, function: { arguments: suffix } }], }, } tool.value.input = part.input tool.value.providerMetadata = mergeMetadata( tool.value.providerMetadata, part.providerMetadata, ) tool.ended = true yield { id, delta: { toolCallEnd: { index: tool.index, id: part.toolCallId }, }, } break } case 'finish': finish = part break case 'error': throw part.error case 'raw': case 'source': break default: throw new Error('Unsupported model output part.') } } // A stream that closes without its final outcome, or whose outcome names no // finish reason at all, was cut by the connection. It is a lost // connection to try again, not an answer to accept as complete. if (!finish || (finish.finishReason.unified === 'other' && !finish.finishReason.raw)) throw new ProviderRequestError({ kind: 'network', providerId: this.id, detail: `model "${model}": the connection closed before the response finished`, }) if (finish.finishReason.unified === 'error' || finish.finishReason.unified === 'other') throw new Error('The model did not report a successful finish reason.') const finishReason = finish.finishReason.unified === 'length' ? 'length' : finish.finishReason.unified === 'content-filter' ? 'content_filter' : tools.size > 0 ? 'tool_calls' : 'stop' yield { id, delta: {}, finishReason, ...(finishReason === 'content_filter' ? { refusal: {} } : {}), ...(finishReason === 'length' && finish.finishReason.raw && CONTEXT_WINDOW_RAW_FINISH_REASONS.has(finish.finishReason.raw) ? { finishDetail: 'context_window' as const } : {}), usage: mapUsage(finish.usage), replayState: createReplayState( { ...params, model }, route, this.service, protocol, content, ), } } catch (error) { if (params.signal?.aborted) throw params.signal.reason if (isProviderRequestError(error)) throw error throw this.failure(error, model) } finally { controller.abort() if (reader) { await reader.cancel().catch(() => {}) reader.releaseLock() } } } async listModels(signal?: AbortSignal): Promise { try { const response = await this.requestFetch(`${this.baseURL}/models`, { headers: { Authorization: `Bearer ${this.apiKey}` }, signal: AbortSignal.any([AbortSignal.timeout(this.timeout), ...(signal ? [signal] : [])]), }) if (!response.ok) { await response.body?.cancel() throw providerHttpError({ providerId: this.id, status: response.status, body: undefined, retryAfter: response.headers.get('retry-after'), }) } const body: unknown = await readCatalogue(response) if (!body || typeof body !== 'object' || !('data' in body) || !Array.isArray(body.data)) throw new Error('The model catalogue returned an invalid response.') const result: ModelInfo[] = [] const seen = new Set() const catalogue = this.runtimeCatalogue() for (const item of body.data) { if (!item || typeof item !== 'object' || typeof item.id !== 'string' || seen.has(item.id)) continue seen.add(item.id) const model = findZenCatalogueModel(catalogue, this.service, item.id) if (model) { if (!this.anonymous || isExperimentalFreeZenModel(this.service, model)) result.push({ ...model }) continue } // Served, and named by the runtime catalogue as having no known wire: // listed as exactly that, so an operator can see it exists, and // callable only with an explicit protocol. Never anonymous, and // nothing about it — price, limits, tools — is invented. if (!this.anonymous && isUnroutedZenModel(catalogue, this.service, item.id)) result.push({ id: item.id, name: `${item.id} (no known wire format)`, supportsToolUse: false, supportsStreaming: true, }) } return result } catch (error) { if (signal?.aborted) throw signal.reason if (isProviderRequestError(error)) throw error throw this.failure(error) } } reasoningEffortLevelsFor( model: string, _thinking?: ThinkingConfig, ): readonly ReasoningEffort[] | undefined { return this.model(model)?.effortLevels } async resolveContextWindow(model: string, signal?: AbortSignal): Promise { signal?.throwIfAborted() return this.model(model)?.contextWindow } /** * Whether `model` reads images. One Zen account serves vision and text-only * models side by side, and a text-only one refuses the whole request when the * conversation holds an image; the catalogue says which is which. A model the * catalogue does not know is assumed to read them. */ supportsImageInputFor(model: string): boolean { const modalities = this.model(model)?.inputModalities return modalities === undefined || modalities.includes('image') } /** * Whether `model` takes a forced tool choice. The Go models that refuse * `required` or a named function (the DeepSeek V4 ones among them) are * refused before transport by the same rule, so the kernel asks first and * puts the instruction in words instead of failing the step. */ acceptsForcedToolChoiceFor(model: string): boolean { return !goRejectsToolChoice(this.service, model) } /** The injected runtime catalogue as it stands now, or undefined for the bundled one alone. */ private runtimeCatalogue(): ZenCatalogue | undefined { const source = this.config.catalogue return typeof source === 'function' ? source() : source } /** Exact lookup: the runtime catalogue first, then the bundled snapshot. */ private model(id: string): ZenModel | undefined { return findZenCatalogueModel(this.runtimeCatalogue(), this.service, id) } /** * Classify a caught throwable into a `ProviderRequestError`. * * `model`, when given, names the request that failed: a driver-level * detail like "the operation was aborted due to timeout" says nothing * about WHICH model was unreachable, and an operator watching a run that * spans several models (a fallback chain, `resolveContextWindow`, a * chat vs. a catalogue call) needs that in the one sentence the error * carries, not just in a status line above it that a log line will not * repeat. `listModels()` has no single model to name and omits it. */ private failure(error: unknown, model?: string): ProviderRequestError { const scrub = (text: string) => this.anonymous ? text : text.split(this.apiKey).join('[REDACTED:api-key]') // Fold the model into `detail` — never into `providerId`, which pricing, // telemetry and route-equality checks key on as an exact 'zen'/'zen-go' // literal — by rebuilding the classified error with the same kind, // status and code, so `.message` and `.detail` both name the model // alongside whatever the provider (or the transport) said. const named = (err: ProviderRequestError): ProviderRequestError => { if (!model) return err return new ProviderRequestError({ kind: err.kind, providerId: err.providerId, ...(err.providerCode !== undefined ? { providerCode: err.providerCode } : {}), ...(err.status !== undefined ? { status: err.status } : {}), ...(err.retryAfterMs !== undefined ? { retryAfterMs: err.retryAfterMs } : {}), detail: err.detail ? `model "${model}": ${err.detail}` : `model "${model}"`, }) } // `APICallError` also wraps a TRANSPORT failure — a connection the // vendor SDK never got a response on at all, e.g. `ECONNREFUSED` — and // on those `error.statusCode` is `undefined`. The `?? 502` that used to // sit here manufactured an HTTP 502 for a request that never reached // the wire: `classifyProviderHttpStatus` reads that as a genuine // upstream 5xx and reports `kind: 'server'` — "the provider is failing // on its own side, resume once it recovers" — when what actually // happened is this host could not open the connection at all, which is // `kind: 'network'`'s story ("check network reachability … "), not the // server's. A real status is still handled exactly as before. if (APICallError.isInstance(error) && error.statusCode !== undefined) return named( providerHttpError({ providerId: this.id, status: error.statusCode, body: scrub(error.responseBody ?? error.message), retryAfter: error.responseHeaders?.['retry-after'], shouldRetry: error.responseHeaders?.['x-should-retry'], }), ) if (APICallError.isInstance(error)) return named( providerVendorError({ providerId: this.id, // A fresh Error, not the `APICallError` itself: only the // scrubbed message crosses this boundary, never its // `responseBody`/`responseHeaders`/`cause`. error: new Error(scrub(error.message)), }), ) // Native streaming adapters can emit plain error envelopes after HTTP 200. // Keep only classification fields; never attach the original error/cause. const envelope = safeErrorEnvelope(error) const body = scrub(JSON.stringify(envelope)) if (envelope.status !== undefined) return named( providerHttpError({ providerId: this.id, status: envelope.status, body, }), ) return named( providerVendorError({ providerId: this.id, error: Object.assign(new Error(body), { ...(envelope.code !== undefined ? { code: scrub(envelope.code) } : {}), }), }), ) } } export class ZenGoProvider extends ZenProvider { constructor(config: ZenGoConfig) { super(config, 'go') } } function safeErrorEnvelope(error: unknown): { type?: string code?: string message: string status?: number } { // Plain property access, not `Object.getOwnPropertyDescriptor`: `message` // and `name` are defined on the PROTOTYPE for platform error classes like // `DOMException` (what `fetch`'s own `AbortSignal.timeout` rejects with), // so an own-property-only read silently came back `undefined` for every // field on exactly the errors this branch exists to describe — a client // timeout or an aborted connection — and fell through to the hardcoded // "The model stream failed." This does not touch the safety property: the // five fields read here (type/code/message/status/statusCode) are the // same ones a JSON vendor envelope would carry as OWN properties, and // normal property access reads a vendor object's own fields exactly as // `own` did — it only additionally reaches a HOST class's prototype // accessors, never anything nested or secret-shaped that the type/length // guards below would not already exclude. const own = (value: unknown, key: string): unknown => typeof value === 'object' && value !== null ? (value as Record)[key] : undefined const nested = own(error, 'error') const source = typeof nested === 'object' && nested !== null ? nested : error const type = own(source, 'type') const code = own(source, 'code') const message = typeof source === 'string' ? source : own(source, 'message') const status = own(source, 'status') ?? own(source, 'statusCode') ?? own(error, 'status') return { ...(typeof type === 'string' && type.length <= 80 ? { type } : {}), ...(typeof code === 'string' && code.length <= 80 ? { code } : {}), message: typeof message === 'string' ? message.slice(0, 8192) : 'The model stream failed.', ...(typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? { status } : {}), } } function mergeMetadata( left?: SharedV3ProviderMetadata, right?: SharedV3ProviderMetadata, ): SharedV3ProviderMetadata | undefined { if (!right) return left const result = { ...left } for (const [key, value] of Object.entries(right)) result[key] = { ...result[key], ...value } return result } function mapUsage(usage: LanguageModelV3Usage): TokenUsage { const promptTokens = usage.inputTokens.total ?? 0 const completionTokens = usage.outputTokens.total ?? 0 return { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens, cachedTokens: usage.inputTokens.cacheRead ?? 0, cacheWriteTokens: usage.inputTokens.cacheWrite ?? 0, ...(usage.outputTokens.reasoning !== undefined ? { reasoningTokens: usage.outputTokens.reasoning } : {}), } } async function readCatalogue(response: Response): Promise { const reader = response.body?.getReader() if (!reader) throw new Error('Empty model catalogue.') const chunks: Uint8Array[] = [] let bytes = 0 try { while (true) { const next = await reader.read() if (next.done) break bytes += next.value.byteLength if (bytes > 1_048_576) throw new Error('The model catalogue exceeds 1 MiB.') chunks.push(next.value) } return JSON.parse( new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, bytes)), ) } finally { await reader.cancel().catch(() => {}) reader.releaseLock() } }