import { getModelCapabilities as getMessagesCapabilities } from '@ai-sdk/anthropic/internal' import type { LanguageModelV3CallOptions, SharedV3ProviderOptions } from '@ai-sdk/provider' import { type ChatCompletionParams, ProviderRequestError, type ProviderRoute, acceptsStrictSchema, } from '@namzu/sdk' import { ZEN_FREE_TIER_TOOL_NAMES } from './experimental-identity.js' import type { ZenModel, ZenProtocol, ZenService } from './models.js' import { isMuseSparkResponsesModel, toModelPrompt } from './prompt.js' export function goRejectsToolChoice(service: ZenService, model: string): boolean { if (service !== 'go') return false if (model.startsWith('mimo-')) return true if (model === 'deepseek-flash') return true return ( /^deepseek-v4(?:\.\d+)?-(?:flash|pro)(?:$|-)/.test(model) && model !== 'deepseek-v4-flash-vision-exp' ) } export function createCallOptions( params: ChatCompletionParams, route: ProviderRoute, service: ZenService, protocol: ZenProtocol, known: ZenModel | undefined, ): LanguageModelV3CallOptions { const refuse = (detail: string): never => { throw new ProviderRequestError({ providerId: route.providerId, kind: 'bad_request', detail, }) } // Optional wire fields can still select a small upstream default when // absent. Request the advertised model ceiling when known; do not invent // a ceiling for an unknown model. Messages also checks its native ceiling. let maxOutputTokens = params.maxTokens ?? (protocol === 'messages' ? undefined : known?.maxOutputTokens) if ( maxOutputTokens !== undefined && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) ) refuse('maxTokens must be a positive integer.') if ( params.effort !== undefined && known?.effortLevels && !known.effortLevels.includes(params.effort) ) refuse('The selected model does not advertise this reasoning effort level.') if (params.repetitionPenalty !== undefined) refuse('repetitionPenalty is not supported by this driver.') if (params.topK !== undefined && protocol !== 'google' && protocol !== 'messages') refuse('topK is not supported by this model protocol.') if ( protocol === 'messages' && (params.frequencyPenalty !== undefined || params.presencePenalty !== undefined) ) refuse('Frequency and presence penalties are not supported by the messages protocol.') if (params.cacheControl?.type === 'ephemeral' && protocol !== 'messages') refuse('Explicit ephemeral cache control requires the messages protocol.') const options: SharedV3ProviderOptions = {} switch (protocol) { case 'chat': { if (params.thinking?.budgetTokens !== undefined || params.thinking?.display !== undefined) refuse('This chat protocol cannot honor a thinking budget or display setting.') options.opencode = { ...(params.effort !== undefined ? { reasoningEffort: params.effort } : {}), ...(params.parallelToolCalls !== undefined ? { parallel_tool_calls: params.parallelToolCalls } : {}), ...(params.thinking ? { thinking: { type: params.thinking.type } } : {}), ...(params.responseFormat?.type === 'json_schema' ? { strictJsonSchema: params.responseFormat.json_schema.strict ?? true, } : {}), } break } case 'responses': { if (params.stop !== undefined) refuse('Stop sequences are not supported by the responses protocol.') if (params.frequencyPenalty !== undefined || params.presencePenalty !== undefined) refuse('Frequency and presence penalties are not supported by the responses protocol.') if (params.thinking?.type === 'enabled' || params.thinking?.budgetTokens !== undefined) refuse('The responses protocol uses adaptive effort, not a fixed thinking budget.') if ( params.thinking?.type === 'disabled' && params.effort !== undefined && params.effort !== 'none' ) refuse('Disabled thinking conflicts with a non-none reasoning effort.') if ( params.thinking?.type === 'disabled' && known?.effortLevels && !known.effortLevels.includes('none') ) refuse('This model does not advertise disabled reasoning.') // The pinned native adapter removes sampling parameters from reasoning // requests. Its warning arrives after the POST, so reject that loss here. const gpt = /^gpt-(\d+)(?:\.(\d+))?(?:-(.+))?$/.exec(params.model) const isReasoning = Boolean(known?.effortLevels?.length) || /^o\d+(?:-|$)/.test(params.model) || (gpt !== null && Number(gpt[1]) >= 5 && !(gpt[2] === undefined && gpt[3]?.startsWith('chat'))) const effort = params.thinking?.type === 'disabled' ? 'none' : params.effort const allowsSampling = effort === 'none' && gpt !== null && Number(gpt[1]) === 5 && Number(gpt[2]) >= 1 if ( isReasoning && !allowsSampling && (params.temperature !== undefined || params.topP !== undefined) ) refuse('Sampling parameters are not supported with this model’s reasoning configuration.') if ( !isReasoning && (params.effort !== undefined || params.thinking?.display === 'summarized') ) refuse('This responses model does not support reasoning controls.') options.openai = { store: false, // Muse Spark's gateway cannot replay caller-bound encrypted reasoning. ...(isMuseSparkResponsesModel(params.model, protocol) ? {} : { include: ['reasoning.encrypted_content'] }), ...(known?.effortLevels?.length ? { forceReasoning: true } : {}), ...(params.effort !== undefined ? { reasoningEffort: params.effort } : {}), ...(params.thinking?.type === 'disabled' ? { reasoningEffort: 'none' } : {}), ...(params.thinking?.display === 'summarized' ? { reasoningSummary: 'auto' } : {}), ...(params.parallelToolCalls !== undefined ? { parallelToolCalls: params.parallelToolCalls } : {}), ...(params.responseFormat?.type === 'json_schema' ? { strictJsonSchema: params.responseFormat.json_schema.strict ?? true, } : {}), } break } case 'messages': { const thinking = params.thinking const capabilities = getMessagesCapabilities(params.model) // Messages requires max_tokens. Use the actual model ceiling, not // the native adapter's conservative fallback for unknown models. if (maxOutputTokens === undefined) { const modelCeiling = known?.maxOutputTokens ?? (capabilities.isKnownModel ? capabilities.maxOutputTokens : undefined) if (modelCeiling === undefined) return refuse('This messages model has no known output limit; set maxTokens explicitly.') maxOutputTokens = capabilities.isKnownModel ? Math.min(modelCeiling, capabilities.maxOutputTokens) : modelCeiling } const isThinking = thinking?.type === 'enabled' || thinking?.type === 'adaptive' if ( (isThinking || capabilities.rejectsSamplingParameters) && (params.temperature !== undefined || params.topP !== undefined || params.topK !== undefined) ) refuse('Sampling parameters are not supported with this model’s thinking configuration.') if ( params.temperature !== undefined && (!Number.isFinite(params.temperature) || params.temperature < 0 || params.temperature > 1) ) refuse('The messages protocol requires temperature between 0 and 1.') if ( params.model.includes('claude-') && params.temperature !== undefined && params.topP !== undefined ) refuse('This model cannot honor temperature and topP together.') if ( params.responseFormat?.type === 'json_schema' && params.responseFormat.json_schema.strict === false ) refuse('The messages protocol cannot disable schema enforcement.') if (params.responseFormat?.type === 'json_object') refuse('The messages protocol requires a schema for JSON output.') if ( capabilities.rejectsThinkingDisabledAboveHighEffort && thinking?.type === 'disabled' && (params.effort === 'xhigh' || params.effort === 'max') ) refuse('This model cannot disable thinking at the requested effort level.') if (thinking?.budgetTokens !== undefined && thinking.type !== 'enabled') refuse('A thinking budget requires manual enabled thinking.') if (thinking?.display !== undefined && thinking.type !== 'adaptive') refuse('Thinking display selection requires adaptive thinking.') if (capabilities.isKnownModel && maxOutputTokens > capabilities.maxOutputTokens) refuse('maxTokens exceeds the selected model’s output limit.') if (thinking?.type === 'enabled') { // Namzu's cap includes thinking; the native adapter adds its budget // to maxOutputTokens, including a default 1024 when omitted. const budget = thinking.budgetTokens ?? 1024 if (!Number.isSafeInteger(budget) || budget < 1024 || budget >= maxOutputTokens) refuse('Manual thinking requires a budget of at least 1024 below maxTokens.') maxOutputTokens -= budget } if ( !capabilities.supportsStructuredOutput && params.responseFormat?.type === 'json_schema' && params.parallelToolCalls === true ) refuse('This model cannot combine schema output with parallel tool calls.') if ( !capabilities.supportsStructuredOutput && params.tools?.some((tool) => params.enforceToolInputSchema?.includes(tool.function.name)) ) refuse('This model protocol cannot enforce strict tool input schemas.') options.anthropic = { ...(params.responseFormat?.type === 'json_schema' ? { structuredOutputMode: 'outputFormat' } : {}), sendReasoning: true, ...(thinking ? { thinking: { ...thinking } } : {}), ...(params.effort !== undefined ? { effort: params.effort } : {}), ...(params.parallelToolCalls !== undefined ? { disableParallelToolUse: !params.parallelToolCalls } : {}), // Cache breakpoints are block-level, placed by `toModelPrompt`: // a request-level `cacheControl` would become Anthropic's // automatic caching, whose breakpoint lands on the request-only // context at the tail. } break } case 'google': { if (params.parallelToolCalls !== undefined) refuse('The google protocol has no parallelToolCalls switch.') if (params.thinking?.budgetTokens !== undefined && params.thinking.type !== 'enabled') refuse('A thinking budget requires manual enabled thinking.') if ( params.thinking?.type === 'disabled' && params.effort !== undefined && params.effort !== 'none' ) refuse('Disabled thinking conflicts with a reasoning effort level.') options.google = { thinkingConfig: { includeThoughts: params.thinking?.display !== 'omitted', ...(params.effort !== undefined ? { thinkingLevel: params.effort } : {}), ...(params.thinking?.type === 'disabled' ? { thinkingBudget: 0 } : {}), ...(params.thinking?.budgetTokens !== undefined ? { thinkingBudget: params.thinking.budgetTokens } : {}), }, } break } } // Some Responses upstreams accept only auto tool choice (observed on Muse). // A no-tools turn can preserve its meaning by exposing no tools at all. // Keep required/named choices explicit; never silently weaken them to auto. const rejectsToolChoice = goRejectsToolChoice(service, params.model) if ( rejectsToolChoice && params.toolChoice !== undefined && params.toolChoice !== 'auto' && params.toolChoice !== 'none' ) refuse('This Zen Go model does not support required or named tool choice.') const withoutTools = (protocol === 'responses' || rejectsToolChoice) && params.toolChoice === 'none' const enforced = new Set(params.enforceToolInputSchema) return { prompt: toModelPrompt(params, route, service, protocol), ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}), ...(params.temperature !== undefined ? { temperature: params.temperature } : {}), ...(params.topP !== undefined ? { topP: params.topP } : {}), ...(params.topK !== undefined ? { topK: params.topK } : {}), ...(params.frequencyPenalty !== undefined ? { frequencyPenalty: params.frequencyPenalty } : {}), ...(params.presencePenalty !== undefined ? { presencePenalty: params.presencePenalty } : {}), ...(params.stop ? { stopSequences: params.stop } : {}), ...(params.tools && !withoutTools ? { tools: params.tools.map((tool) => ({ type: 'function' as const, name: tool.function.name, description: tool.function.description, inputSchema: tool.function.parameters, // Neither wire here can carry Namzu's general tool // contract. Responses cannot express it at all, so it // is always `strict: false`. The chat wire accepts the // FLAG but applies the subset's structural rules // itself, so claim it only for a schema that would // survive them — the free-tier gateway refuses the // whole request otherwise, taking every other tool in // the call down with it. `edit` carries optional // fields on purpose, so it gets the same answer as // Responses; `write` requires both of its fields and // keeps the guarantee. Like the Codex driver and // OpenCode itself (`strict: false` on every tool), the // schema is retained either way and inputs are // validated at execution; enforcement is a // capability-dependent hint. ...(protocol === 'responses' ? { strict: false } : enforced.has(tool.function.name) ? { strict: acceptsStrictSchema(tool.function.parameters) } : {}), })), } : {}), ...(params.toolChoice && !withoutTools && !rejectsToolChoice ? { toolChoice: typeof params.toolChoice === 'string' ? { type: params.toolChoice } : { type: 'tool', toolName: params.toolChoice.function.name }, } : {}), ...(params.responseFormat ? { responseFormat: params.responseFormat.type === 'json_object' ? { type: 'json' as const } : { type: 'json' as const, schema: params.responseFormat.json_schema.schema, name: params.responseFormat.json_schema.name, }, } : {}), providerOptions: options, } } /** * The tool definitions the Zen free-tier gate requires on the wire. * * The gate admits a request only when its `tools` carry all four of `bash`, * `glob`, `grep` and `read`, so a caller that registers none of them — a text * turn, or an agent whose tools happen to use other names — would be refused * before the model ever saw the prompt. These are the gap-fillers, and only * the gaps: a name the caller already registered keeps its own definition, * description and schema untouched. */ function zenFreeTierTools(): readonly NonNullable[number][] { return ZEN_FREE_TIER_TOOL_NAMES.map((name) => ({ type: 'function' as const, name, description: name === 'bash' ? 'Execute a shell command and return its standard output and error.' : name === 'glob' ? 'List filesystem paths matching a glob pattern.' : name === 'grep' ? 'Search file contents for a regular expression and return the matches.' : 'Read a UTF-8 text file and return its contents.', inputSchema: { type: 'object' as const, properties: name === 'bash' ? { command: { type: 'string' as const, description: 'The shell command to run.' } } : name === 'glob' ? { pattern: { type: 'string' as const, description: 'The glob pattern to match.' } } : name === 'grep' ? { pattern: { type: 'string' as const, description: 'The regular expression to search for.', }, } : { path: { type: 'string' as const, description: 'The file to read.' } }, required: [ name === 'bash' ? 'command' : name === 'glob' ? 'pattern' : name === 'grep' ? 'pattern' : 'path', ], }, })) } /** * Admit an anonymous Zen request through the free-tier gate. * * `enabled` is the gate path — anonymous access on the official host. When a * caller registered no tool at all, the injected names also pin tool choice to * `none`: the four names are present because the gate reads them, and the * model is still told not to call any of them, so a turn that never asked for * tools never receives one it cannot execute. `honoursNone` is false on a wire * that rejects the choice — Muse Spark's Answers endpoint accepts only * `auto` — where the tools travel without a choice and the kernel's ordinary * unknown-tool answer covers a call to a name it does not hold. * A caller that did register tools keeps its own choice. */ export function withZenFreeTierTools( options: LanguageModelV3CallOptions, enabled: boolean, honoursNone = true, ): LanguageModelV3CallOptions { if (!enabled) return options const existing = options.tools ?? [] const held = new Set(existing.flatMap((tool) => (tool.type === 'function' ? [tool.name] : []))) const missing = zenFreeTierTools().filter((tool) => !held.has(tool.name)) if (missing.length === 0) return options return { ...options, tools: [...existing, ...missing], ...(existing.length === 0 && honoursNone ? { toolChoice: { type: 'none' as const } } : {}), } }