import type * as plugins from './plugins.js'; import { invalidRequest } from './errors.js'; import type { IAnthropicMessagesControls, IAnthropicMessagesModel, TAnthropicMessagesEffort, } from './interfaces.js'; import type { ThinkingSignatures } from './signature.js'; /* * Request policy. A field that changes what the model does and has a faithful translation is translated. * A field that is only a hint to Anthropic's own service (prompt cache markers, citations, metadata, the * service tier, eager tool input streaming) is accepted without effect. Every other field is refused with a * 400 that names it, so a capability this service cannot provide never silently disappears. */ type TParsedFile = { kind: 'file'; mediaType: string; data: { type: 'data'; data: string } | { type: 'url'; url: URL }; }; type TParsedText = { kind: 'text'; text: string }; type TParsedToolResult = { kind: 'tool_result'; toolUseId: string; isError: boolean; content: string | Array; }; type TParsedUserBlock = TParsedText | TParsedFile | TParsedToolResult; type TParsedAssistantBlock = | TParsedText | { kind: 'thinking'; thinking: string; signature: string } | { kind: 'redacted_thinking' } | { kind: 'tool_use'; id: string; name: string; input: unknown }; type TParsedMessage = | { role: 'system'; text: string } | { role: 'user'; blocks: TParsedUserBlock[] } | { role: 'assistant'; blocks: TParsedAssistantBlock[] }; interface IParsedTool { name: string; description?: string; inputSchema: plugins.LanguageModelV4FunctionTool['inputSchema']; strict?: boolean; inputExamples?: Array<{ input: plugins.JSONObject }>; } type TParsedToolChoice = | { type: 'auto' } | { type: 'any' } | { type: 'none' } | { type: 'tool'; name: string }; /** A request of the Messages API, checked and reduced to what this service translates. */ export interface IAnthropicMessagesParsedRequest { modelId: string; stream: boolean; maxTokens: number; system: string[]; messages: TParsedMessage[]; tools: IParsedTool[]; toolChoice?: TParsedToolChoice; parallelToolCalls: boolean; thinking: false | { display: 'summarized' | 'omitted' }; effort?: TAnthropicMessagesEffort; responseFormat?: { type: 'json'; schema: plugins.LanguageModelV4FunctionTool['inputSchema'] }; temperature?: number; topP?: number; topK?: number; stopSequences?: string[]; } const efforts: readonly TAnthropicMessagesEffort[] = ['low', 'medium', 'high', 'xhigh', 'max']; /** Every effort name either side uses, in ascending order, for fitting one to a model's list. */ const isEffort = (valueArg: unknown): valueArg is TAnthropicMessagesEffort => efforts.some((effort) => effort === valueArg); const effortRanks: readonly string[] = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']; const toolNamePattern = /^[a-zA-Z0-9_-]{1,128}$/u; const imageMediaTypes: ReadonlySet = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']); const isPlainObject = (valueArg: unknown): valueArg is Record => typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg); const describePath = (pathArg: string, keyArg: string): string => (pathArg ? `${pathArg}.${keyArg}` : keyArg); /** Refuses any key that is neither translated nor a known hint, naming it. */ const checkKeys = ( valueArg: Record, pathArg: string, translatedArg: readonly string[], hintsArg: readonly string[] = [], ): void => { for (const key of Object.keys(valueArg)) { if (!translatedArg.includes(key) && !hintsArg.includes(key)) { throw invalidRequest(`${describePath(pathArg, key)}: this field is not supported by this service.`); } } }; const requireObject = (valueArg: unknown, pathArg: string): Record => { if (!isPlainObject(valueArg)) throw invalidRequest(`${pathArg}: must be an object.`); return valueArg; }; const requireString = (valueArg: unknown, pathArg: string, allowEmptyArg = true): string => { if (typeof valueArg !== 'string' || (!allowEmptyArg && valueArg.length === 0)) { throw invalidRequest(`${pathArg}: must be a${allowEmptyArg ? '' : ' non-empty'} string.`); } return valueArg; }; const requireArray = (valueArg: unknown, pathArg: string): unknown[] => { if (!Array.isArray(valueArg)) throw invalidRequest(`${pathArg}: must be an array.`); return valueArg; }; const optionalNumber = (valueArg: unknown, pathArg: string): number | undefined => { if (valueArg === undefined) return undefined; if (typeof valueArg !== 'number' || !Number.isFinite(valueArg)) throw invalidRequest(`${pathArg}: must be a number.`); return valueArg; }; const blockHints = ['cache_control', 'citations']; const parseText = (blockArg: Record, pathArg: string): TParsedText => { checkKeys(blockArg, pathArg, ['type', 'text'], blockHints); return { kind: 'text', text: requireString(blockArg.text, `${pathArg}.text`) }; }; const parseSource = ( sourceArg: unknown, pathArg: string, mediaTypeCheckArg: (mediaTypeArg: string) => boolean, ): TParsedFile['data'] & { mediaType?: string } => { const source = requireObject(sourceArg, pathArg); if (source.type === 'base64') { checkKeys(source, pathArg, ['type', 'media_type', 'data']); const mediaType = requireString(source.media_type, `${pathArg}.media_type`, false); if (!mediaTypeCheckArg(mediaType)) throw invalidRequest(`${pathArg}.media_type: "${mediaType}" is not supported.`); return { type: 'data', data: requireString(source.data, `${pathArg}.data`, false), mediaType }; } if (source.type === 'url') { checkKeys(source, pathArg, ['type', 'url']); let url: URL; try { url = new URL(requireString(source.url, `${pathArg}.url`, false)); } catch { throw invalidRequest(`${pathArg}.url: must be an absolute URL.`); } return { type: 'url', url }; } throw invalidRequest(`${pathArg}.type: source type "${String(source.type)}" is not supported.`); }; const parseImage = (blockArg: Record, pathArg: string): TParsedFile => { checkKeys(blockArg, pathArg, ['type', 'source'], blockHints); const { mediaType, ...data } = parseSource(blockArg.source, `${pathArg}.source`, (typeArg) => imageMediaTypes.has(typeArg)); return { kind: 'file', mediaType: mediaType ?? 'image', data }; }; const parseDocument = (blockArg: Record, pathArg: string): TParsedFile | TParsedText => { checkKeys(blockArg, pathArg, ['type', 'source', 'title', 'context'], blockHints); const title = blockArg.title === undefined || blockArg.title === null ? undefined : requireString(blockArg.title, `${pathArg}.title`); const context = blockArg.context === undefined || blockArg.context === null ? undefined : requireString(blockArg.context, `${pathArg}.context`); const source = requireObject(blockArg.source, `${pathArg}.source`); if (source.type === 'text') { checkKeys(source, `${pathArg}.source`, ['type', 'media_type', 'data']); if (source.media_type !== 'text/plain') { throw invalidRequest(`${pathArg}.source.media_type: a text document must be "text/plain".`); } const text = requireString(source.data, `${pathArg}.source.data`); return { kind: 'text', text: [title, context, text].filter((entry) => entry !== undefined).join('\n\n') }; } if (title !== undefined || context !== undefined) { throw invalidRequest(`${pathArg}: a title or context is supported on text documents only.`); } const { mediaType, ...data } = parseSource(source, `${pathArg}.source`, (typeArg) => typeArg === 'application/pdf'); return { kind: 'file', mediaType: mediaType ?? 'application/pdf', data }; }; const parseToolResultContent = (valueArg: unknown, pathArg: string): TParsedToolResult['content'] => { if (valueArg === undefined) return ''; if (typeof valueArg === 'string') return valueArg; return requireArray(valueArg, pathArg).map((entry, index) => { const path = `${pathArg}[${index}]`; const block = requireObject(entry, path); switch (block.type) { case 'text': return parseText(block, path); case 'image': return parseImage(block, path); case 'document': return parseDocument(block, path); default: throw invalidRequest(`${path}.type: "${String(block.type)}" is not supported in a tool result.`); } }); }; const parseUserBlock = (valueArg: unknown, pathArg: string): TParsedUserBlock => { const block = requireObject(valueArg, pathArg); switch (block.type) { case 'text': return parseText(block, pathArg); case 'image': return parseImage(block, pathArg); case 'document': return parseDocument(block, pathArg); case 'tool_result': { checkKeys(block, pathArg, ['type', 'tool_use_id', 'content', 'is_error'], blockHints); if (block.is_error !== undefined && typeof block.is_error !== 'boolean') { throw invalidRequest(`${pathArg}.is_error: must be a boolean.`); } return { kind: 'tool_result', toolUseId: requireString(block.tool_use_id, `${pathArg}.tool_use_id`, false), isError: block.is_error === true, content: parseToolResultContent(block.content, `${pathArg}.content`), }; } default: throw invalidRequest(`${pathArg}.type: "${String(block.type)}" is not supported in a user message.`); } }; const parseAssistantBlock = (valueArg: unknown, pathArg: string): TParsedAssistantBlock => { const block = requireObject(valueArg, pathArg); switch (block.type) { case 'text': return parseText(block, pathArg); case 'thinking': checkKeys(block, pathArg, ['type', 'thinking', 'signature'], blockHints); return { kind: 'thinking', thinking: requireString(block.thinking, `${pathArg}.thinking`), signature: requireString(block.signature, `${pathArg}.signature`), }; case 'redacted_thinking': checkKeys(block, pathArg, ['type', 'data'], blockHints); return { kind: 'redacted_thinking' }; case 'tool_use': { checkKeys(block, pathArg, ['type', 'id', 'name', 'input'], [...blockHints, 'caller']); const name = requireString(block.name, `${pathArg}.name`, false); if (!toolNamePattern.test(name)) throw invalidRequest(`${pathArg}.name: "${name}" is not a valid tool name.`); return { kind: 'tool_use', id: requireString(block.id, `${pathArg}.id`, false), name, input: block.input ?? {}, }; } default: throw invalidRequest(`${pathArg}.type: "${String(block.type)}" is not supported in an assistant message.`); } }; const parseSystemText = (valueArg: unknown, pathArg: string): string[] => { if (typeof valueArg === 'string') return [valueArg]; return requireArray(valueArg, pathArg).map((entry, index) => { const path = `${pathArg}[${index}]`; const block = requireObject(entry, path); if (block.type !== 'text') throw invalidRequest(`${path}.type: system content must be text.`); return parseText(block, path).text; }); }; const parseMessage = (valueArg: unknown, pathArg: string): TParsedMessage => { const message = requireObject(valueArg, pathArg); checkKeys(message, pathArg, ['role', 'content']); const content = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : requireArray(message.content, `${pathArg}.content`); switch (message.role) { case 'system': return { role: 'system', text: parseSystemText(message.content, `${pathArg}.content`).join('\n') }; case 'user': return { role: 'user', blocks: content.map((entry, index) => parseUserBlock(entry, `${pathArg}.content[${index}]`)) }; case 'assistant': return { role: 'assistant', blocks: content.map((entry, index) => parseAssistantBlock(entry, `${pathArg}.content[${index}]`)), }; default: throw invalidRequest(`${pathArg}.role: "${String(message.role)}" is not a message role.`); } }; const isJsonSchemaObject = ( valueArg: unknown, ): valueArg is plugins.LanguageModelV4FunctionTool['inputSchema'] => isPlainObject(valueArg); const parseTool = (valueArg: unknown, pathArg: string): IParsedTool => { const tool = requireObject(valueArg, pathArg); if (tool.type !== undefined && tool.type !== 'custom') { // The wording names the tool type after `Input tag`, which is how an Anthropic client recognizes a // server tool the endpoint does not offer and continues without it. throw invalidRequest(`${pathArg}: Input tag '${String(tool.type)}' found using 'type' does not match any of the expected tags: 'custom'`); } if (tool.defer_loading === true) { throw invalidRequest(`${pathArg}.defer_loading: deferred tool loading (tool search) is not supported by this service.`); } checkKeys(tool, pathArg, ['type', 'name', 'description', 'input_schema', 'strict', 'input_examples', 'defer_loading'], [ 'cache_control', 'eager_input_streaming', ]); const name = requireString(tool.name, `${pathArg}.name`, false); if (!toolNamePattern.test(name)) throw invalidRequest(`${pathArg}.name: "${name}" is not a valid tool name.`); if (!isJsonSchemaObject(tool.input_schema)) throw invalidRequest(`${pathArg}.input_schema: must be a JSON schema object.`); if (tool.strict !== undefined && typeof tool.strict !== 'boolean') throw invalidRequest(`${pathArg}.strict: must be a boolean.`); const inputExamples = tool.input_examples === undefined ? undefined : requireArray(tool.input_examples, `${pathArg}.input_examples`).map((example, index) => { if (!isPlainObject(example)) throw invalidRequest(`${pathArg}.input_examples[${index}]: must be an object.`); return { input: example as plugins.JSONObject }; }); return { name, ...(tool.description === undefined ? {} : { description: requireString(tool.description, `${pathArg}.description`) }), inputSchema: tool.input_schema, ...(tool.strict === undefined ? {} : { strict: tool.strict }), ...(inputExamples === undefined ? {} : { inputExamples }), }; }; const parseToolChoice = (valueArg: unknown): { choice?: TParsedToolChoice; parallelToolCalls: boolean } => { if (valueArg === undefined) return { parallelToolCalls: true }; const choice = requireObject(valueArg, 'tool_choice'); checkKeys(choice, 'tool_choice', ['type', 'name', 'disable_parallel_tool_use']); if (choice.disable_parallel_tool_use !== undefined && typeof choice.disable_parallel_tool_use !== 'boolean') { throw invalidRequest('tool_choice.disable_parallel_tool_use: must be a boolean.'); } const parallelToolCalls = choice.disable_parallel_tool_use !== true; switch (choice.type) { case 'auto': case 'any': case 'none': if (choice.name !== undefined) throw invalidRequest(`tool_choice.name: only a "tool" choice names a tool.`); return { choice: { type: choice.type }, parallelToolCalls }; case 'tool': return { choice: { type: 'tool', name: requireString(choice.name, 'tool_choice.name', false) }, parallelToolCalls }; default: throw invalidRequest(`tool_choice.type: "${String(choice.type)}" is not a tool choice.`); } }; const parseThinking = (valueArg: unknown): IAnthropicMessagesParsedRequest['thinking'] => { if (valueArg === undefined) return false; const thinking = requireObject(valueArg, 'thinking'); const display = thinking.display ?? 'summarized'; if (display !== 'summarized' && display !== 'omitted') { throw invalidRequest(`thinking.display: "${String(display)}" is not supported.`); } switch (thinking.type) { case 'disabled': checkKeys(thinking, 'thinking', ['type']); return false; case 'adaptive': checkKeys(thinking, 'thinking', ['type', 'display']); return { display }; case 'enabled': // The reasoning depth of the model is set by effort; a token budget has no equivalent to translate to. checkKeys(thinking, 'thinking', ['type', 'display'], ['budget_tokens']); return { display }; default: throw invalidRequest(`thinking.type: "${String(thinking.type)}" is not supported.`); } }; const parseOutputConfig = (valueArg: unknown): Pick => { if (valueArg === undefined) return {}; const config = requireObject(valueArg, 'output_config'); checkKeys(config, 'output_config', ['effort', 'format']); const effort = config.effort; if (effort !== undefined && !isEffort(effort)) { throw invalidRequest(`output_config.effort: "${String(effort)}" is not an effort level.`); } let responseFormat: IAnthropicMessagesParsedRequest['responseFormat']; if (config.format !== undefined && config.format !== null) { const format = requireObject(config.format, 'output_config.format'); checkKeys(format, 'output_config.format', ['type', 'schema']); if (format.type !== 'json_schema' || !isJsonSchemaObject(format.schema)) { throw invalidRequest('output_config.format: only a "json_schema" format with a schema is supported.'); } responseFormat = { type: 'json', schema: format.schema }; } return { ...(isEffort(effort) ? { effort } : {}), ...(responseFormat ? { responseFormat } : {}), }; }; const refusedFeatures: Readonly> = { context_management: 'server-side context management', container: 'code execution containers', mcp_servers: 'remote MCP servers', }; /** Checks a Messages API request body and reduces it to what this service translates. */ export const parseAnthropicMessagesRequest = (bodyArg: unknown): IAnthropicMessagesParsedRequest => { const body = requireObject(bodyArg, 'body'); for (const [key, feature] of Object.entries(refusedFeatures)) { if (body[key] !== undefined) throw invalidRequest(`${key}: ${feature} is not supported by this service.`); } checkKeys(body, '', [ 'model', 'messages', 'max_tokens', 'system', 'stream', 'tools', 'tool_choice', 'thinking', 'output_config', 'temperature', 'top_p', 'top_k', 'stop_sequences', ], ['metadata', 'service_tier', 'cache_control']); const maxTokens = body.max_tokens; if (typeof maxTokens !== 'number' || !Number.isSafeInteger(maxTokens) || maxTokens < 1) { throw invalidRequest('max_tokens: must be a positive integer.'); } if (body.stream !== undefined && typeof body.stream !== 'boolean') throw invalidRequest('stream: must be a boolean.'); const messages = requireArray(body.messages, 'messages').map((entry, index) => parseMessage(entry, `messages[${index}]`)); if (messages.length === 0) throw invalidRequest('messages: at least one message is required.'); const tools = body.tools === undefined ? [] : requireArray(body.tools, 'tools').map((entry, index) => parseTool(entry, `tools[${index}]`)); if (new Set(tools.map((tool) => tool.name)).size !== tools.length) throw invalidRequest('tools: tool names must be unique.'); const { choice, parallelToolCalls } = parseToolChoice(body.tool_choice); if (choice?.type === 'tool' && !tools.some((tool) => tool.name === choice.name)) { throw invalidRequest(`tool_choice.name: no tool is named "${choice.name}".`); } const stopSequences = body.stop_sequences === undefined ? undefined : requireArray(body.stop_sequences, 'stop_sequences').map((entry, index) => requireString(entry, `stop_sequences[${index}]`, false)); const topK = optionalNumber(body.top_k, 'top_k'); return { modelId: requireString(body.model, 'model', false), stream: body.stream === true, maxTokens, system: body.system === undefined ? [] : parseSystemText(body.system, 'system'), messages, tools, ...(choice ? { toolChoice: choice } : {}), parallelToolCalls, thinking: parseThinking(body.thinking), ...parseOutputConfig(body.output_config), ...(body.temperature === undefined ? {} : { temperature: optionalNumber(body.temperature, 'temperature') }), ...(body.top_p === undefined ? {} : { topP: optionalNumber(body.top_p, 'top_p') }), ...(topK === undefined ? {} : { topK }), ...(stopSequences === undefined || stopSequences.length === 0 ? {} : { stopSequences }), }; }; /** Maps tool names to the names the model is sent, for a model with a shorter tool name limit. */ export class ToolNames { private readonly toModel = new Map(); private readonly fromModel = new Map(); public static async create(namesArg: Iterable, limitArg: number | undefined): Promise { const names = new ToolNames(); const unique = [...new Set(namesArg)]; for (const name of unique) { let sent = name; if (limitArg !== undefined && name.length > limitArg) { if (limitArg < 16) throw invalidRequest(`tools: the model's tool name limit of ${limitArg} is too short to alias "${name}".`); const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(name))); const suffix = [...digest.subarray(0, 4)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); sent = `${name.slice(0, limitArg - suffix.length - 1)}_${suffix}`; } if (names.fromModel.has(sent)) { throw invalidRequest(`tools: "${name}" and "${names.fromModel.get(sent)}" share the name the model is sent.`); } names.toModel.set(name, sent); names.fromModel.set(sent, name); } return names; } public sent(nameArg: string): string { const sent = this.toModel.get(nameArg); if (sent === undefined) throw new Error(`Tool name "${nameArg}" was not registered.`); return sent; } /** The client's name for a tool the model called, or `undefined` for a name the request never offered. */ public received(nameArg: string): string | undefined { return this.fromModel.get(nameArg); } } /** Fits a requested effort to the efforts a model accepts, preferring the nearest lower one. */ const fitEffort = ( requestedArg: string, acceptedArg: readonly string[] | undefined, ): string | undefined => { if (!acceptedArg || acceptedArg.includes(requestedArg)) return requestedArg; const requestedRank = effortRanks.indexOf(requestedArg); const ranked = acceptedArg .map((effort) => ({ effort, rank: effortRanks.indexOf(effort) })) .filter((entry) => entry.rank !== -1) .sort((left, right) => left.rank - right.rank); const lower = ranked.filter((entry) => entry.rank <= requestedRank); return (lower.at(-1) ?? ranked[0])?.effort; }; export interface IAnthropicMessagesModelCall { options: Omit; toolNames: ToolNames; /** Response headers that name what this request received differently from what it asked for. */ notices: Record; } const toFilePart = (fileArg: TParsedFile): plugins.LanguageModelV4FilePart => ({ type: 'file', mediaType: fileArg.mediaType, data: fileArg.data, }); const toToolResultOutput = ( resultArg: TParsedToolResult, pathArg: string, ): plugins.LanguageModelV4ToolResultOutput => { if (typeof resultArg.content === 'string') { return resultArg.isError ? { type: 'error-text', value: resultArg.content } : { type: 'text', value: resultArg.content }; } if (resultArg.isError) { const texts = resultArg.content.filter((entry): entry is TParsedText => entry.kind === 'text'); if (texts.length !== resultArg.content.length) { throw invalidRequest(`${pathArg}: a tool result marked as an error can carry text only.`); } return { type: 'error-text', value: texts.map((entry) => entry.text).join('\n') }; } return { type: 'content', value: resultArg.content.map((entry) => entry.kind === 'text' ? { type: 'text' as const, text: entry.text } : { type: 'file' as const, mediaType: entry.mediaType, data: entry.data }), }; }; /** Translates a parsed request into the call of one model. */ export const createAnthropicMessagesModelCall = async ( requestArg: IAnthropicMessagesParsedRequest, modelArg: IAnthropicMessagesModel, signaturesArg: ThinkingSignatures, sessionIdArg: string | undefined, ): Promise => { const notices: Record = {}; const toolNamesInUse: string[] = requestArg.tools.map((tool) => tool.name); const toolUseNames = new Map(); for (const message of requestArg.messages) { if (message.role !== 'assistant') continue; for (const block of message.blocks) { if (block.kind !== 'tool_use') continue; toolNamesInUse.push(block.name); toolUseNames.set(block.id, block.name); } } const toolNames = await ToolNames.create(toolNamesInUse, modelArg.toolNameLimit); const prompt: plugins.LanguageModelV4Prompt = requestArg.system.map((text) => ({ role: 'system', content: text })); let droppedThinking = 0; for (const [messageIndex, message] of requestArg.messages.entries()) { if (message.role === 'system') { prompt.push({ role: 'system', content: message.text }); continue; } if (message.role === 'assistant') { const content: Extract['content'] = []; for (const block of message.blocks) { if (block.kind === 'text') { if (block.text.length > 0) content.push({ type: 'text', text: block.text }); } else if (block.kind === 'thinking') { const providerOptions = await signaturesArg.verify(block.signature, modelArg.signatureScope); if (providerOptions) content.push({ type: 'reasoning', text: block.thinking, providerOptions }); else droppedThinking++; } else if (block.kind === 'redacted_thinking') { droppedThinking++; } else { content.push({ type: 'tool-call', toolCallId: block.id, toolName: toolNames.sent(block.name), input: block.input }); } } if (content.length > 0) prompt.push({ role: 'assistant', content }); continue; } // A user message's tool results answer the preceding tool calls, so each run of them becomes a tool // message and every other run of content a user message, in the order the client wrote them. let toolParts: plugins.LanguageModelV4ToolResultPart[] = []; let userParts: Array = []; const flushTool = (): void => { if (toolParts.length > 0) prompt.push({ role: 'tool', content: toolParts }); toolParts = []; }; const flushUser = (): void => { if (userParts.length > 0) prompt.push({ role: 'user', content: userParts }); userParts = []; }; for (const [blockIndex, block] of message.blocks.entries()) { if (block.kind === 'tool_result') { flushUser(); const name = toolUseNames.get(block.toolUseId); const path = `messages[${messageIndex}].content[${blockIndex}]`; if (name === undefined) throw invalidRequest(`${path}.tool_use_id: no tool_use block has the id "${block.toolUseId}".`); toolParts.push({ type: 'tool-result', toolCallId: block.toolUseId, toolName: toolNames.sent(name), output: toToolResultOutput(block, path), }); continue; } flushTool(); userParts.push(block.kind === 'text' ? { type: 'text', text: block.text } : toFilePart(block)); } flushTool(); flushUser(); } if (droppedThinking > 0) notices['x-flexharness-thinking-dropped'] = String(droppedThinking); let reasoningEffort: string | undefined; if (requestArg.effort !== undefined) { reasoningEffort = fitEffort(requestArg.effort, modelArg.reasoningEfforts); if (reasoningEffort !== requestArg.effort) { notices['x-flexharness-effort-fitted'] = `${requestArg.effort}=>${reasoningEffort ?? 'model-default'}`; } } if (!modelArg.sendsMaxTokens) notices['x-flexharness-max-tokens'] = 'not-sent'; const controls: IAnthropicMessagesControls = { ...(reasoningEffort === undefined ? {} : { reasoningEffort }), thinking: requestArg.thinking !== false, parallelToolCalls: requestArg.parallelToolCalls, ...(sessionIdArg ? { sessionId: sessionIdArg } : {}), }; const toolChoice: plugins.LanguageModelV4ToolChoice | undefined = requestArg.toolChoice === undefined ? undefined : requestArg.toolChoice.type === 'tool' ? { type: 'tool', toolName: toolNames.sent(requestArg.toolChoice.name) } : { type: requestArg.toolChoice.type === 'any' ? 'required' : requestArg.toolChoice.type }; return { toolNames, notices, options: { prompt, ...(modelArg.sendsMaxTokens ? { maxOutputTokens: requestArg.maxTokens } : {}), ...(requestArg.temperature === undefined ? {} : { temperature: requestArg.temperature }), ...(requestArg.topP === undefined ? {} : { topP: requestArg.topP }), ...(requestArg.topK === undefined ? {} : { topK: requestArg.topK }), ...(requestArg.stopSequences === undefined ? {} : { stopSequences: requestArg.stopSequences }), ...(requestArg.responseFormat === undefined ? {} : { responseFormat: requestArg.responseFormat }), ...(requestArg.tools.length === 0 ? {} : { tools: requestArg.tools.map((tool) => ({ type: 'function' as const, name: toolNames.sent(tool.name), ...(tool.description === undefined ? {} : { description: tool.description }), inputSchema: tool.inputSchema, ...(tool.strict === undefined ? {} : { strict: tool.strict }), ...(tool.inputExamples === undefined ? {} : { inputExamples: tool.inputExamples }), })), }), ...(toolChoice === undefined ? {} : { toolChoice }), providerOptions: modelArg.providerOptions(controls), }, }; };