@tanstack/ai-anthropic 0.16.5 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n readCodeExecutionConfig,\n readCodeExecutionSkills,\n} from '../tools/code-execution-tool'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils/client'\nimport {\n ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,\n getAnthropicDefaultMaxTokens,\n} from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n ServerToolUseBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n WebFetchToolResultBlockParam,\n WebSearchToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils/client'\n\n/**\n * The block type carried by an Anthropic provider-executed (server) tool's\n * stored result. Mirrors the `*_tool_result` block emitted by the streaming\n * API so it can be replayed verbatim into a later turn.\n */\ntype AnthropicServerToolResultBlockType =\n | 'web_search_tool_result'\n | 'web_fetch_tool_result'\n\n/**\n * Anthropic payload stashed on a provider-executed tool call's `metadata`\n * (under the `anthropic` key, alongside `providerExecuted: true`). Holds enough\n * to reconstruct the original `server_tool_use` + `*_tool_result` blocks so the\n * model still sees prior `web_search` / `web_fetch` evidence on the next turn.\n */\ninterface AnthropicServerToolMetadata {\n serverToolType: ServerToolUseBlockParam['name']\n resultBlockType: AnthropicServerToolResultBlockType\n /** Raw result block content, preserved verbatim from the stream. */\n result: unknown\n}\n\n/**\n * Narrow an opaque tool-call `metadata` to {@link AnthropicServerToolMetadata}\n * when it follows the provider-executed convention, else `null`.\n */\nfunction readAnthropicServerToolMetadata(\n metadata: unknown,\n): AnthropicServerToolMetadata | null {\n if (typeof metadata !== 'object' || metadata === null) return null\n const outer = metadata as { providerExecuted?: unknown; anthropic?: unknown }\n if (outer.providerExecuted !== true) return null\n const inner = outer.anthropic\n if (typeof inner !== 'object' || inner === null) return null\n const { serverToolType, resultBlockType, result } = inner as {\n serverToolType?: unknown\n resultBlockType?: unknown\n result?: unknown\n }\n if (\n typeof serverToolType !== 'string' ||\n (resultBlockType !== 'web_search_tool_result' &&\n resultBlockType !== 'web_fetch_tool_result')\n ) {\n return null\n }\n return {\n // Validated as a string above; widen back to the SDK's tool-name union.\n serverToolType: serverToolType as ServerToolUseBlockParam['name'],\n resultBlockType,\n result,\n }\n}\n\n/**\n * Reconstruct the `*_tool_result` block param from stored server-tool metadata.\n * The `result` content is opaque round-trip data, asserted to the SDK's param\n * content type at this single boundary.\n */\nfunction buildServerToolResultBlock(\n toolUseId: string,\n meta: AnthropicServerToolMetadata,\n): WebSearchToolResultBlockParam | WebFetchToolResultBlockParam {\n if (meta.resultBlockType === 'web_search_tool_result') {\n return {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebSearchToolResultBlockParam['content'],\n }\n }\n return {\n type: 'web_fetch_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebFetchToolResultBlockParam['content'],\n }\n}\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n // `structuredOutput()` issues a non-streaming `messages.create({ stream:\n // false })` below, so the defaulted `max_tokens` must stay under the SDK's\n // non-streaming 10-minute guard (issue #849) — pass `stream: false`.\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {\n stream: false,\n })\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n { stream = true }: { stream?: boolean } = {},\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'cache_control',\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n // Anthropic's Messages API *requires* `max_tokens`, so we must always send a\n // value. When the caller doesn't specify one, default to the resolved\n // model's real output ceiling (from model-meta) rather than a low constant\n // that silently truncates long responses with `stop_reason: \"max_tokens\"`\n // (issue #849). `max_tokens` is a ceiling, not a reservation — billing is on\n // tokens actually generated, so a higher default costs nothing extra.\n // For non-streaming requests (the `structuredOutput()` path) the default is\n // clamped to the SDK's non-streaming-safe limit so it doesn't trip the\n // \"streaming required\" 10-minute guard — see getAnthropicDefaultMaxTokens.\n const defaultMaxTokens =\n modelOptions?.max_tokens ??\n getAnthropicDefaultMaxTokens(this.model, { stream })\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n // Provider-executed server tools (e.g. web_search) replay as the\n // original `server_tool_use` + result blocks so the model still sees\n // the prior evidence. Their result was captured verbatim during\n // streaming (see processAnthropicStream).\n const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata)\n if (serverMeta) {\n const serverToolUseBlock: ServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: toolCall.id,\n name: serverMeta.serverToolType,\n input: parsedInput,\n }\n contentBlocks.push(serverToolUseBlock)\n contentBlocks.push(\n buildServerToolResultBlock(toolCall.id, serverMeta),\n )\n continue\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n // Completed server tools awaiting their matching result block. Anthropic\n // emits `server_tool_use` then a separate `*_tool_result` block; we hold\n // the call here (keyed by id) until the result arrives so we can emit a\n // single provider-executed tool call carrying the raw result for round-trip.\n const completedServerTools = new Map<\n string,\n { id: string; name: string; input: string }\n >()\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n\n // Emit the server tool as a single provider-executed tool call,\n // carrying its raw result so the evidence (e.g. web_search sources)\n // round-trips into the next turn's request. The agent loop skips\n // provider-executed calls, so this never triggers client execution.\n const serverTool = completedServerTools.get(\n event.content_block.tool_use_id,\n )\n if (serverTool) {\n completedServerTools.delete(serverTool.id)\n\n let parsedInput: unknown = {}\n try {\n const parsed = serverTool.input\n ? JSON.parse(serverTool.input)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n const serverToolMetadata = {\n providerExecuted: true,\n anthropic: {\n serverToolType: serverTool.name,\n resultBlockType: event.content_block.type,\n result: content,\n },\n }\n\n currentToolIndex++\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n metadata: serverToolMetadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Text after the server tool starts a fresh message segment.\n hasEmittedTextMessageStart = false\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n // Hold the call until its result block arrives so we can emit\n // both together as one provider-executed tool call.\n completedServerTools.set(currentServerTool.id, currentServerTool)\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n // Surface a warning when the truncating cap was the\n // adapter-supplied default (caller didn't pass `max_tokens`), so\n // the truncation isn't silently attributed to the model \"doing\n // nothing\" (issue #849). When the caller set `max_tokens`\n // themselves, hitting it is their own deliberate ceiling.\n if (options.modelOptions?.max_tokens == null) {\n const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model)\n logger.warn(\n `anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,\n {\n source: 'anthropic.processAnthropicStream',\n model,\n defaultedMaxTokens,\n },\n )\n }\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"mappings":";;;;;;;;;;;;;;AA8FA,SAAS,gCACP,UACoC;CACpC,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM,OAAO;CAC9D,MAAM,QAAQ;CACd,IAAI,MAAM,qBAAqB,MAAM,OAAO;CAC5C,MAAM,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GACZ,MAAM,WAAW,mBAAmB,KAAK;GAEzC,OAAO,OAAO,0CAA0C;IACtD;IACA,QAAQ;GACV,CAAC;GACD,MAAM;IACJ,MAAM,UAAU;IAChB;IACA,WAAW,KAAK,IAAI;IACpB,SAAS,IAAI,WAAW;IACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;IAEnC,GAAI,aAAa,KAAA,KAAa,EAAE,SAAS;IACzC,OAAO;KACL,SAAS,IAAI,WAAW;KACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;IACrC;GACF;EACF;CACF;AACF;;;;;AAMA,SAAgB,oBAGd,OACA,QACA,QAKA;CACA,OAAO,IAAI,qBAAqB;EAAE;EAAQ,GAAG;CAAO,GAAG,KAAK;AAC9D;;;;;AAMA,SAAgB,cACd,OACA,QAKA;CAEA,OAAO,oBAAoB,OADZ,0BACmB,GAAQ,MAAM;AAClD"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n readCodeExecutionConfig,\n readCodeExecutionSkills,\n} from '../tools/code-execution-tool'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils/client'\nimport {\n ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,\n getAnthropicDefaultMaxTokens,\n} from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n ServerToolUseBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n WebFetchToolResultBlockParam,\n WebSearchToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils/client'\n\n/**\n * The block type carried by an Anthropic provider-executed (server) tool's\n * stored result. Mirrors the `*_tool_result` block emitted by the streaming\n * API so it can be replayed verbatim into a later turn.\n */\ntype AnthropicServerToolResultBlockType =\n | 'web_search_tool_result'\n | 'web_fetch_tool_result'\n\n/**\n * Anthropic payload stashed on a provider-executed tool call's `metadata`\n * (under the `anthropic` key, alongside `providerExecuted: true`). Holds enough\n * to reconstruct the original `server_tool_use` + `*_tool_result` blocks so the\n * model still sees prior `web_search` / `web_fetch` evidence on the next turn.\n */\ninterface AnthropicServerToolMetadata {\n serverToolType: ServerToolUseBlockParam['name']\n resultBlockType: AnthropicServerToolResultBlockType\n /** Raw result block content, preserved verbatim from the stream. */\n result: unknown\n}\n\n/**\n * Narrow an opaque tool-call `metadata` to {@link AnthropicServerToolMetadata}\n * when it follows the provider-executed convention, else `null`.\n */\nfunction readAnthropicServerToolMetadata(\n metadata: unknown,\n): AnthropicServerToolMetadata | null {\n if (typeof metadata !== 'object' || metadata === null) return null\n const outer = metadata as { providerExecuted?: unknown; anthropic?: unknown }\n if (outer.providerExecuted !== true) return null\n const inner = outer.anthropic\n if (typeof inner !== 'object' || inner === null) return null\n const { serverToolType, resultBlockType, result } = inner as {\n serverToolType?: unknown\n resultBlockType?: unknown\n result?: unknown\n }\n if (\n typeof serverToolType !== 'string' ||\n (resultBlockType !== 'web_search_tool_result' &&\n resultBlockType !== 'web_fetch_tool_result')\n ) {\n return null\n }\n return {\n // Validated as a string above; widen back to the SDK's tool-name union.\n serverToolType: serverToolType as ServerToolUseBlockParam['name'],\n resultBlockType,\n result,\n }\n}\n\n/**\n * Reconstruct the `*_tool_result` block param from stored server-tool metadata.\n * The `result` content is opaque round-trip data, asserted to the SDK's param\n * content type at this single boundary.\n */\nfunction buildServerToolResultBlock(\n toolUseId: string,\n meta: AnthropicServerToolMetadata,\n): WebSearchToolResultBlockParam | WebFetchToolResultBlockParam {\n if (meta.resultBlockType === 'web_search_tool_result') {\n return {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebSearchToolResultBlockParam['content'],\n }\n }\n return {\n type: 'web_fetch_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebFetchToolResultBlockParam['content'],\n }\n}\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n // `structuredOutput()` issues a non-streaming `messages.create({ stream:\n // false })` below, so the defaulted `max_tokens` must stay under the SDK's\n // non-streaming 10-minute guard (issue #849) — pass `stream: false`.\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {\n stream: false,\n })\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n { stream = true }: { stream?: boolean } = {},\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'cache_control',\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n // Anthropic's Messages API *requires* `max_tokens`, so we must always send a\n // value. When the caller doesn't specify one, default to the resolved\n // model's real output ceiling (from model-meta) rather than a low constant\n // that silently truncates long responses with `stop_reason: \"max_tokens\"`\n // (issue #849). `max_tokens` is a ceiling, not a reservation — billing is on\n // tokens actually generated, so a higher default costs nothing extra.\n // For non-streaming requests (the `structuredOutput()` path) the default is\n // clamped to the SDK's non-streaming-safe limit so it doesn't trip the\n // \"streaming required\" 10-minute guard — see getAnthropicDefaultMaxTokens.\n const defaultMaxTokens =\n modelOptions?.max_tokens ??\n getAnthropicDefaultMaxTokens(this.model, { stream })\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n // Provider-executed server tools (e.g. web_search) replay as the\n // original `server_tool_use` + result blocks so the model still sees\n // the prior evidence. Their result was captured verbatim during\n // streaming (see processAnthropicStream).\n const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata)\n if (serverMeta) {\n const serverToolUseBlock: ServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: toolCall.id,\n name: serverMeta.serverToolType,\n input: parsedInput,\n }\n contentBlocks.push(serverToolUseBlock)\n contentBlocks.push(\n buildServerToolResultBlock(toolCall.id, serverMeta),\n )\n continue\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n // Completed server tools awaiting their matching result block. Anthropic\n // emits `server_tool_use` then a separate `*_tool_result` block; we hold\n // the call here (keyed by id) until the result arrives so we can emit a\n // single provider-executed tool call carrying the raw result for round-trip.\n const completedServerTools = new Map<\n string,\n { id: string; name: string; input: string }\n >()\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n\n // Emit the server tool as a single provider-executed tool call,\n // carrying its raw result so the evidence (e.g. web_search sources)\n // round-trips into the next turn's request. The agent loop skips\n // provider-executed calls, so this never triggers client execution.\n const serverTool = completedServerTools.get(\n event.content_block.tool_use_id,\n )\n if (serverTool) {\n completedServerTools.delete(serverTool.id)\n\n let parsedInput: unknown = {}\n try {\n const parsed = serverTool.input\n ? JSON.parse(serverTool.input)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n const serverToolMetadata = {\n providerExecuted: true,\n anthropic: {\n serverToolType: serverTool.name,\n resultBlockType: event.content_block.type,\n result: content,\n },\n }\n\n currentToolIndex++\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n metadata: serverToolMetadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Text after the server tool starts a fresh message segment.\n hasEmittedTextMessageStart = false\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n // Hold the call until its result block arrives so we can emit\n // both together as one provider-executed tool call.\n completedServerTools.set(currentServerTool.id, currentServerTool)\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n // Surface a warning when the truncating cap was the\n // adapter-supplied default (caller didn't pass `max_tokens`), so\n // the truncation isn't silently attributed to the model \"doing\n // nothing\" (issue #849). When the caller set `max_tokens`\n // themselves, hitting it is their own deliberate ceiling.\n if (options.modelOptions?.max_tokens == null) {\n const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model)\n logger.warn(\n `anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,\n {\n source: 'anthropic.processAnthropicStream',\n model,\n defaultedMaxTokens,\n },\n )\n }\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"mappings":";;;;;;;;;;;;;;AA8FA,SAAS,gCACP,UACoC;CACpC,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM,OAAO;CAC9D,MAAM,QAAQ;CACd,IAAI,MAAM,qBAAqB,MAAM,OAAO;CAC5C,MAAM,QAAQ,MAAM;CACpB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,gBAAgB,iBAAiB,WAAW;CAKpD,IACE,OAAO,mBAAmB,YACzB,oBAAoB,4BACnB,oBAAoB,yBAEtB,OAAO;CAET,OAAO;EAEW;EAChB;EACA;CACF;AACF;;;;;;AAOA,SAAS,2BACP,WACA,MAC8D;CAC9D,IAAI,KAAK,oBAAoB,0BAC3B,OAAO;EACL,MAAM;EACN,aAAa;EACb,SAAS,KAAK;CAChB;CAEF,OAAO;EACL,MAAM;EACN,aAAa;EACb,SAAS,KAAK;CAChB;AACF;;;;;;;;AASA,SAAgB,sBACd,OACA,cAQkC;CAClC,MAAM,wBAAQ,IAAI,IAAmB;CAMrC,IAHE,cAAc,UAAU,SAAS,aACjC,OAAO,aAAa,SAAS,kBAAkB,YAC/C,aAAa,SAAS,gBAAgB,GACZ,MAAM,IAAI,iCAAiC;CAIvE,MAAM,eAAe,OAAO,MAAM,MAAM,EAAE,SAAS,gBAAgB;CACnE,IAAI,cAAc;EAChB,MAAM,UAAU,wBAAwB,YAAY,CAAC,EAAE;EAIvD,MAAM,IACJ,YAAY,4BACR,8BACA,2BACN;CACF;CAUA,IALkB,OAAO,MACtB,MACC,EAAE,SAAS,qBACV,w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AEF,KAAK;QAMH,IAAI,QAAQ,cAAc,cAAc,MAAM;SAC5C,MAAM,qBAAqB,6BAA6B,KAAK;SAC7D,OAAO,KACL,2DAA2D,mBAAmB,cAAc,MAAM,4EAClG;UACE,QAAQ;UACR;UACA;SACF,CACF;QACF;QACA,MAAM;SACJ,MAAM,UAAU;SAChB;SACA,WAAW,KAAK,IAAI;SACpB,SACE;SACF,MAAM;SACN,OAAO;UACL,SACE;UACF,MAAM;SACR;QACF;QACA;OAQF,SAKE,MAAM;QACJ,MAAM,UAAU;QAChB;QACA;QACA;QACA,WAAW,KAAK,IAAI;QACpB,cAAc;QACd,OAAO,oBAAoB,MAAM,KAAK;OACxC;MAEJ;KACF;;GAEJ;EACF,SAAS,OAAgB;GACvB,MAAM,MAAM;GACZ,MAAM,WAAW,mBAAmB,KAAK;GAEzC,OAAO,OAAO,0CAA0C;IACtD;IACA,QAAQ;GACV,CAAC;GACD,MAAM;IACJ,MAAM,UAAU;IAChB;IACA,WAAW,KAAK,IAAI;IACpB,SAAS,IAAI,WAAW;IACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;IAEnC,GAAI,aAAa,KAAA,KAAa,EAAE,SAAS;IACzC,OAAO;KACL,SAAS,IAAI,WAAW;KACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;IACrC;GACF;EACF;CACF;AACF;;;;;AAMA,SAAgB,oBAGd,OACA,QACA,QAKA;CACA,OAAO,IAAI,qBAAqB;EAAE;EAAQ,GAAG;CAAO,GAAG,KAAK;AAC9D;;;;;AAMA,SAAgB,cACd,OACA,QAKA;CAEA,OAAO,oBAAoB,OADZ,0BACmB,GAAQ,MAAM;AAClD"}
@@ -224,7 +224,45 @@ declare const CLAUDE_SONNET_5: {
224
224
  * via the `speed` parameter, not a model id) were removed after Anthropic
225
225
  * turned them off.
226
226
  */
227
- export declare const ANTHROPIC_MODELS: readonly ["claude-opus-4-6", "claude-opus-4-5", "claude-sonnet-4-6", "claude-sonnet-4-5", "claude-haiku-4-5", "claude-opus-4-1", "claude-opus-4-7", "claude-opus-4-8", "claude-fable-5", "claude-sonnet-5"];
227
+ declare const CLAUDE_OPUS_5: {
228
+ readonly name: "claude-opus-5";
229
+ readonly id: "claude-opus-5";
230
+ readonly context_window: 1000000;
231
+ readonly max_output_tokens: 128000;
232
+ readonly supports: {
233
+ readonly input: ["text", "image", "document"];
234
+ readonly tools: [];
235
+ };
236
+ readonly pricing: {
237
+ readonly input: {
238
+ readonly normal: 5;
239
+ readonly cached: 0.5;
240
+ };
241
+ readonly output: {
242
+ readonly normal: 25;
243
+ };
244
+ };
245
+ };
246
+ declare const CLAUDE_OPUS_5_FAST: {
247
+ readonly name: "claude-opus-5-fast";
248
+ readonly id: "claude-opus-5-fast";
249
+ readonly context_window: 1000000;
250
+ readonly max_output_tokens: 128000;
251
+ readonly supports: {
252
+ readonly input: ["text", "image", "document"];
253
+ readonly tools: [];
254
+ };
255
+ readonly pricing: {
256
+ readonly input: {
257
+ readonly normal: 10;
258
+ readonly cached: 1;
259
+ };
260
+ readonly output: {
261
+ readonly normal: 50;
262
+ };
263
+ };
264
+ };
265
+ export declare const ANTHROPIC_MODELS: readonly ["claude-opus-5", "claude-opus-5-fast", "claude-opus-4-6", "claude-opus-4-5", "claude-sonnet-4-6", "claude-sonnet-4-5", "claude-haiku-4-5", "claude-opus-4-1", "claude-opus-4-7", "claude-opus-4-8", "claude-fable-5", "claude-sonnet-5"];
228
266
  /**
229
267
  * Fallback `max_tokens` ceiling for a model whose metadata carries no
230
268
  * `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages
@@ -287,6 +325,8 @@ export type AnthropicChatModelProviderOptionsByName = {
287
325
  [CLAUDE_OPUS_4_8.id]: AnthropicCacheControlOptions & AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicAdaptiveOrDisabledThinkingOptions & AnthropicToolChoiceOptions & AnthropicMaxTokensOptions & AnthropicOutputConfigOptions;
288
326
  [CLAUDE_FABLE_5.id]: AnthropicCacheControlOptions & AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicAdaptiveOnlyThinkingOptions & AnthropicToolChoiceOptions & AnthropicMaxTokensOptions & AnthropicOutputConfigOptions;
289
327
  [CLAUDE_SONNET_5.id]: AnthropicCacheControlOptions & AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicAdaptiveOrDisabledThinkingOptions & AnthropicToolChoiceOptions & AnthropicMaxTokensOptions & AnthropicOutputConfigOptions;
328
+ [CLAUDE_OPUS_5.id]: AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicThinkingOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions;
329
+ [CLAUDE_OPUS_5_FAST.id]: AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicThinkingOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions;
290
330
  };
291
331
  export type AnthropicChatModelToolCapabilitiesByName = {
292
332
  [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.tools;
@@ -299,6 +339,8 @@ export type AnthropicChatModelToolCapabilitiesByName = {
299
339
  [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools;
300
340
  [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools;
301
341
  [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools;
342
+ [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.tools;
343
+ [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.tools;
302
344
  };
303
345
  /**
304
346
  * Type-only map from chat model name to its supported input modalities.
@@ -322,5 +364,7 @@ export type AnthropicModelInputModalitiesByName = {
322
364
  [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input;
323
365
  [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input;
324
366
  [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input;
367
+ [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.input;
368
+ [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.input;
325
369
  };
326
370
  export {};
@@ -312,7 +312,51 @@ var CLAUDE_SONNET_5 = {
312
312
  * via the `speed` parameter, not a model id) were removed after Anthropic
313
313
  * turned them off.
314
314
  */
315
+ var CLAUDE_OPUS_5 = {
316
+ name: "claude-opus-5",
317
+ id: "claude-opus-5",
318
+ context_window: 1e6,
319
+ max_output_tokens: 128e3,
320
+ supports: {
321
+ input: [
322
+ "text",
323
+ "image",
324
+ "document"
325
+ ],
326
+ tools: []
327
+ },
328
+ pricing: {
329
+ input: {
330
+ normal: 5,
331
+ cached: .5
332
+ },
333
+ output: { normal: 25 }
334
+ }
335
+ };
336
+ var CLAUDE_OPUS_5_FAST = {
337
+ name: "claude-opus-5-fast",
338
+ id: "claude-opus-5-fast",
339
+ context_window: 1e6,
340
+ max_output_tokens: 128e3,
341
+ supports: {
342
+ input: [
343
+ "text",
344
+ "image",
345
+ "document"
346
+ ],
347
+ tools: []
348
+ },
349
+ pricing: {
350
+ input: {
351
+ normal: 10,
352
+ cached: 1
353
+ },
354
+ output: { normal: 50 }
355
+ }
356
+ };
315
357
  var ANTHROPIC_MODELS = [
358
+ CLAUDE_OPUS_5.id,
359
+ CLAUDE_OPUS_5_FAST.id,
316
360
  CLAUDE_OPUS_4_6.id,
317
361
  CLAUDE_OPUS_4_5.id,
318
362
  CLAUDE_SONNET_4_6.id,
@@ -357,7 +401,9 @@ var ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS = {
357
401
  [CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,
358
402
  [CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,
359
403
  [CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,
360
- [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens
404
+ [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,
405
+ [CLAUDE_OPUS_5.id]: CLAUDE_OPUS_5.max_output_tokens,
406
+ [CLAUDE_OPUS_5_FAST.id]: CLAUDE_OPUS_5_FAST.max_output_tokens
361
407
  };
362
408
  /**
363
409
  * Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**
@@ -1 +1 @@
1
- {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type {\n AnthropicAdaptiveOnlyThinkingOptions,\n AnthropicAdaptiveOrDisabledThinkingOptions,\n AnthropicAdaptiveThinkingOptions,\n AnthropicCacheControlOptions,\n AnthropicContainerOptions,\n AnthropicContextManagementOptions,\n AnthropicMCPOptions,\n AnthropicMaxTokensOptions,\n AnthropicOutputConfigOptions,\n AnthropicSamplingOptions,\n AnthropicServiceTierOptions,\n AnthropicStopSequencesOptions,\n AnthropicThinkingOptions,\n AnthropicToolChoiceOptions,\n} from './text/text-provider-options'\n\ninterface ModelMeta<\n TProviderOptions = unknown,\n TToolCapabilities = unknown,\n TMessageCapabilities = unknown,\n> {\n name: string\n id: string\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'video' | 'document'>\n extended_thinking?: boolean\n adaptive_thinking?: boolean\n priority_tier?: boolean\n tools?: Array<\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'computer_use'\n | 'bash'\n | 'text_editor'\n | 'memory'\n >\n }\n context_window?: number\n max_output_tokens?: number\n knowledge_cutoff?: string\n pricing: {\n input: {\n normal: number\n cached?: number\n }\n output: {\n normal: number\n }\n }\n /**\n * Type-level description of which provider options this model supports.\n */\n providerOptions?: TProviderOptions\n /**\n * Type-level description of which tool capabilities this model supports.\n */\n toolCapabilities?: TToolCapabilities\n /**\n * Type-level description of which message/input capabilities this model supports.\n */\n messageCapabilities?: TMessageCapabilities\n}\n\n// Claude Opus 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_OPUS_4_6 = {\n name: 'claude-opus-4-6',\n id: 'claude-opus-4-6',\n context_window: 200_000,\n max_output_tokens: 128_000,\n knowledge_cutoff: '2025-05-01',\n pricing: {\n input: {\n normal: 5,\n },\n output: {\n normal: 25,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_5 = {\n name: 'claude-opus-4-5',\n id: 'claude-opus-4-5',\n context_window: 200_000,\n max_output_tokens: 32_000,\n knowledge_cutoff: '2025-11-01',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Sonnet 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_SONNET_4_6 = {\n name: 'claude-sonnet-4-6',\n id: 'claude-sonnet-4-6',\n context_window: 1_000_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-01',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_SONNET_4_5 = {\n name: 'claude-sonnet-4-5',\n id: 'claude-sonnet-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-09-29',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_HAIKU_4_5 = {\n name: 'claude-haiku-4-5',\n id: 'claude-haiku-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-10-01',\n pricing: {\n input: {\n normal: 1,\n },\n output: {\n normal: 5,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_1 = {\n name: 'claude-opus-4-1',\n id: 'claude-opus-4-1',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-05',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Opus 4.7 removed budget-based extended thinking and the sampling\n// parameters (`temperature`, `top_p`, `top_k`) — sending either returns a\n// 400. Use adaptive thinking with `output_config.effort` instead.\nconst CLAUDE_OPUS_4_7 = {\n name: 'claude-opus-4-7',\n id: 'claude-opus-4-7',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Opus 4.8 keeps the same request surface as Opus 4.7: adaptive\n// thinking only (budget_tokens 400s), no sampling parameters.\nconst CLAUDE_OPUS_4_8 = {\n name: 'claude-opus-4-8',\n id: 'claude-opus-4-8',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Fable 5: thinking is always on — the only accepted explicit\n// `thinking` config is `{type: 'adaptive'}` (disabled/budget_tokens 400),\n// and the sampling parameters (`temperature`, `top_p`, `top_k`) are\n// rejected. Its provider options therefore use the adaptive-only thinking\n// shape and `max_tokens` without the sampling knobs.\nconst CLAUDE_FABLE_5 = {\n name: 'claude-fable-5',\n id: 'claude-fable-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 10,\n cached: 1,\n },\n output: {\n normal: 50,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Sonnet 5: adaptive thinking is the default (omitting `thinking`\n// runs adaptive); `{type: 'disabled'}` opts out, but the manual\n// `{type: 'enabled', budget_tokens}` shape and non-default sampling\n// parameters (`temperature`, `top_p`, `top_k`) are rejected with a 400.\n// Pricing below is the sticker $3/$15 per MTok (an introductory $2/$10\n// applies through 2026-08-31).\nconst CLAUDE_SONNET_5 = {\n name: 'claude-sonnet-5',\n id: 'claude-sonnet-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 3,\n cached: 0.3,\n },\n output: {\n normal: 15,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n/**\n * Model ids accepted by the Anthropic text adapter.\n *\n * Every id here resolves against the first-party Anthropic API\n * (`GET /v1/models/{id}`). Retired models (Claude 3.x, Sonnet 3.7,\n * Opus 4 / Sonnet 4) and the `-fast` variant ids (fast mode is requested\n * via the `speed` parameter, not a model id) were removed after Anthropic\n * turned them off.\n */\nexport const ANTHROPIC_MODELS = [\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_HAIKU_4_5.id,\n CLAUDE_OPUS_4_1.id,\n\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n] as const\n\n/**\n * Fallback `max_tokens` ceiling for a model whose metadata carries no\n * `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages\n * API *requires* `max_tokens`, so the adapter must always send a value. 64K is\n * the output ceiling of the current mainstream Claude tier (Sonnet/Haiku 4.5),\n * so it's a sane default for an unknown — almost certainly modern — model and\n * avoids silently truncating long generations (issue #849). Recognized models\n * use their exact `max_output_tokens` from {@link ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS}\n * (e.g. 128K for Opus), so this fallback only ever applies to ids not in the\n * map.\n */\nexport const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64_000\n\n/**\n * Runtime lookup of each model's maximum output-token ceiling, keyed by model\n * id. Lets the text adapter default the required `max_tokens` request field to\n * the model's real ceiling when the caller doesn't specify one, rather than a\n * low constant that truncates responses mid-stream (issue #849).\n *\n * Kept in sync with {@link ANTHROPIC_MODELS} by `scripts/sync-provider-models.ts`\n * — when that script adds a model it also inserts the model's `max_output_tokens`\n * here, so a freshly-synced model resolves to its real ceiling rather than the\n * fallback above.\n */\nconst ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {\n [CLAUDE_OPUS_4_6.id]: CLAUDE_OPUS_4_6.max_output_tokens,\n [CLAUDE_OPUS_4_5.id]: CLAUDE_OPUS_4_5.max_output_tokens,\n [CLAUDE_SONNET_4_6.id]: CLAUDE_SONNET_4_6.max_output_tokens,\n [CLAUDE_SONNET_4_5.id]: CLAUDE_SONNET_4_5.max_output_tokens,\n [CLAUDE_HAIKU_4_5.id]: CLAUDE_HAIKU_4_5.max_output_tokens,\n [CLAUDE_OPUS_4_1.id]: CLAUDE_OPUS_4_1.max_output_tokens,\n [CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,\n [CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,\n [CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,\n [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,\n}\n\n/**\n * Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**\n * request. The SDK refuses to make a non-streaming call it estimates could\n * exceed its 10-minute timeout, computed as\n * `(60min * max_tokens) / 128_000 > 10min` — i.e. it throws\n * `\"Streaming is required for operations that may take longer than 10 minutes\"`\n * once `max_tokens > 128_000 * 10 / 60 ≈ 21_333`\n * (`@anthropic-ai/sdk`'s `calculateNonstreamingTimeout`). The text adapter's\n * only non-streaming call is the forced-tool `structuredOutput()` request, so\n * its defaulted ceiling must stay at or below this; the streaming chat path\n * keeps the model's full {@link getAnthropicDefaultMaxTokens} ceiling. We sit\n * just under the boundary (`21_333` would round-trip to exactly 10min). This\n * caps only the *default* — an explicit oversized `max_tokens` from the caller\n * still surfaces the SDK's \"use streaming\" error, which is the correct signal.\n */\nexport const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21_000\n\n/**\n * Resolve the default `max_tokens` for a model: its known `max_output_tokens`\n * ceiling, or {@link ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS} for unknown models.\n * Callers that pass an explicit `max_tokens` bypass this entirely.\n *\n * Pass `stream: false` for non-streaming requests (the `structuredOutput()`\n * path): the result is then clamped to {@link ANTHROPIC_MAX_NONSTREAMING_TOKENS}\n * so the defaulted ceiling doesn't trip the SDK's non-streaming 10-minute guard\n * (issue #849). Streaming requests (the default) are unaffected and get the\n * model's full ceiling.\n */\nexport function getAnthropicDefaultMaxTokens(\n model: string,\n { stream = true }: { stream?: boolean } = {},\n): number {\n const ceiling =\n ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS[model] ??\n ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS\n return stream ? ceiling : Math.min(ceiling, ANTHROPIC_MAX_NONSTREAMING_TOKENS)\n}\n\n/**\n * Anthropic models that support combining `tools` + JSON-Schema-constrained\n * output in a single streaming Messages request (per issue #605). GA'd\n * 2026-01-29 for Claude 4.5+ via `output_format` on the beta messages\n * endpoint. Older Claude models still need the forced-tool-use workaround\n * in `structuredOutput`.\n */\nexport const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = new Set<string>([\n CLAUDE_OPUS_4_5.id,\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_HAIKU_4_5.id,\n])\n\n// const ANTHROPIC_IMAGE_MODELS = [] as const\n// const ANTHROPIC_EMBEDDING_MODELS = [] as const\n// const ANTHROPIC_AUDIO_MODELS = [] as const\n// const ANTHROPIC_VIDEO_MODELS = [] as const\n\nexport type AnthropicChatModel = (typeof ANTHROPIC_MODELS)[number]\n// Manual type map for per-model provider options\n// Models are differentiated by which thinking shapes and sampling\n// parameters the API accepts.\nexport type AnthropicChatModelProviderOptionsByName = {\n // 4.6 generation: adaptive thinking plus the deprecated budget-based\n // shape; sampling parameters still accepted.\n [CLAUDE_OPUS_4_6.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_6.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Pre-4.6 models: budget-based extended thinking and sampling parameters.\n [CLAUDE_OPUS_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_HAIKU_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_OPUS_4_1.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Opus 4.7/4.8: adaptive thinking (or explicit disable), no\n // budget_tokens, no sampling parameters — see the constants above.\n [CLAUDE_OPUS_4_7.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n [CLAUDE_OPUS_4_8.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n\n // Claude Fable 5: thinking always on (adaptive-only config); sampling\n // parameters removed — see the CLAUDE_FABLE_5 constant above.\n [CLAUDE_FABLE_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n // Claude Sonnet 5: adaptive thinking by default, explicit disable\n // allowed; no budget_tokens, no sampling parameters — see the\n // CLAUDE_SONNET_5 constant above.\n [CLAUDE_SONNET_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n}\n\nexport type AnthropicChatModelToolCapabilitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.tools\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.tools\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.tools\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.tools\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.tools\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.tools\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.tools\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools\n}\n\n/**\n * Type-only map from chat model name to its supported input modalities.\n * All Anthropic Claude models support text, image, and document (PDF) input.\n * Used by the core AI types to constrain ContentPart types based on the selected model.\n * Note: These must be inlined as readonly arrays (not typeof) because the model\n * constants are not exported and typeof references don't work in .d.ts files\n * when consumed by external packages.\n *\n * @see https://docs.anthropic.com/claude/docs/vision\n * @see https://docs.anthropic.com/claude/docs/pdf-support\n */\nexport type AnthropicModelInputModalitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.input\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.input\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.input\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.input\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.input\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.input\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.input\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input\n}\n"],"mappings":";AAmEA,IAAM,kBAAkB;CACtB,MAAM;CACN,IAAI;CACJ,gBAAgB;CAChB,mBAAmB;CACnB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AI,IAAY;CACxE,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,gBAAgB;CAChB,kBAAkB;CAClB,kBAAkB;CAClB,iBAAiB;AACnB,CAAC"}
1
+ {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type {\n AnthropicAdaptiveOnlyThinkingOptions,\n AnthropicAdaptiveOrDisabledThinkingOptions,\n AnthropicAdaptiveThinkingOptions,\n AnthropicCacheControlOptions,\n AnthropicContainerOptions,\n AnthropicContextManagementOptions,\n AnthropicMCPOptions,\n AnthropicMaxTokensOptions,\n AnthropicOutputConfigOptions,\n AnthropicSamplingOptions,\n AnthropicServiceTierOptions,\n AnthropicStopSequencesOptions,\n AnthropicThinkingOptions,\n AnthropicToolChoiceOptions,\n} from './text/text-provider-options'\n\ninterface ModelMeta<\n TProviderOptions = unknown,\n TToolCapabilities = unknown,\n TMessageCapabilities = unknown,\n> {\n name: string\n id: string\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'video' | 'document'>\n extended_thinking?: boolean\n adaptive_thinking?: boolean\n priority_tier?: boolean\n tools?: Array<\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'computer_use'\n | 'bash'\n | 'text_editor'\n | 'memory'\n >\n }\n context_window?: number\n max_output_tokens?: number\n knowledge_cutoff?: string\n pricing: {\n input: {\n normal: number\n cached?: number\n }\n output: {\n normal: number\n }\n }\n /**\n * Type-level description of which provider options this model supports.\n */\n providerOptions?: TProviderOptions\n /**\n * Type-level description of which tool capabilities this model supports.\n */\n toolCapabilities?: TToolCapabilities\n /**\n * Type-level description of which message/input capabilities this model supports.\n */\n messageCapabilities?: TMessageCapabilities\n}\n\n// Claude Opus 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_OPUS_4_6 = {\n name: 'claude-opus-4-6',\n id: 'claude-opus-4-6',\n context_window: 200_000,\n max_output_tokens: 128_000,\n knowledge_cutoff: '2025-05-01',\n pricing: {\n input: {\n normal: 5,\n },\n output: {\n normal: 25,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_5 = {\n name: 'claude-opus-4-5',\n id: 'claude-opus-4-5',\n context_window: 200_000,\n max_output_tokens: 32_000,\n knowledge_cutoff: '2025-11-01',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Sonnet 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_SONNET_4_6 = {\n name: 'claude-sonnet-4-6',\n id: 'claude-sonnet-4-6',\n context_window: 1_000_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-01',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_SONNET_4_5 = {\n name: 'claude-sonnet-4-5',\n id: 'claude-sonnet-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-09-29',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_HAIKU_4_5 = {\n name: 'claude-haiku-4-5',\n id: 'claude-haiku-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-10-01',\n pricing: {\n input: {\n normal: 1,\n },\n output: {\n normal: 5,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_1 = {\n name: 'claude-opus-4-1',\n id: 'claude-opus-4-1',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-05',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Opus 4.7 removed budget-based extended thinking and the sampling\n// parameters (`temperature`, `top_p`, `top_k`) — sending either returns a\n// 400. Use adaptive thinking with `output_config.effort` instead.\nconst CLAUDE_OPUS_4_7 = {\n name: 'claude-opus-4-7',\n id: 'claude-opus-4-7',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Opus 4.8 keeps the same request surface as Opus 4.7: adaptive\n// thinking only (budget_tokens 400s), no sampling parameters.\nconst CLAUDE_OPUS_4_8 = {\n name: 'claude-opus-4-8',\n id: 'claude-opus-4-8',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Fable 5: thinking is always on — the only accepted explicit\n// `thinking` config is `{type: 'adaptive'}` (disabled/budget_tokens 400),\n// and the sampling parameters (`temperature`, `top_p`, `top_k`) are\n// rejected. Its provider options therefore use the adaptive-only thinking\n// shape and `max_tokens` without the sampling knobs.\nconst CLAUDE_FABLE_5 = {\n name: 'claude-fable-5',\n id: 'claude-fable-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 10,\n cached: 1,\n },\n output: {\n normal: 50,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Sonnet 5: adaptive thinking is the default (omitting `thinking`\n// runs adaptive); `{type: 'disabled'}` opts out, but the manual\n// `{type: 'enabled', budget_tokens}` shape and non-default sampling\n// parameters (`temperature`, `top_p`, `top_k`) are rejected with a 400.\n// Pricing below is the sticker $3/$15 per MTok (an introductory $2/$10\n// applies through 2026-08-31).\nconst CLAUDE_SONNET_5 = {\n name: 'claude-sonnet-5',\n id: 'claude-sonnet-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 3,\n cached: 0.3,\n },\n output: {\n normal: 15,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n/**\n * Model ids accepted by the Anthropic text adapter.\n *\n * Every id here resolves against the first-party Anthropic API\n * (`GET /v1/models/{id}`). Retired models (Claude 3.x, Sonnet 3.7,\n * Opus 4 / Sonnet 4) and the `-fast` variant ids (fast mode is requested\n * via the `speed` parameter, not a model id) were removed after Anthropic\n * turned them off.\n */\nconst CLAUDE_OPUS_5 = {\n name: 'claude-opus-5',\n id: 'claude-opus-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n tools: [],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_5_FAST = {\n name: 'claude-opus-5-fast',\n id: 'claude-opus-5-fast',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n tools: [],\n },\n pricing: {\n input: {\n normal: 10,\n cached: 1,\n },\n output: {\n normal: 50,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nexport const ANTHROPIC_MODELS = [\n CLAUDE_OPUS_5.id,\n CLAUDE_OPUS_5_FAST.id,\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_HAIKU_4_5.id,\n CLAUDE_OPUS_4_1.id,\n\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n] as const\n\n/**\n * Fallback `max_tokens` ceiling for a model whose metadata carries no\n * `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages\n * API *requires* `max_tokens`, so the adapter must always send a value. 64K is\n * the output ceiling of the current mainstream Claude tier (Sonnet/Haiku 4.5),\n * so it's a sane default for an unknown — almost certainly modern — model and\n * avoids silently truncating long generations (issue #849). Recognized models\n * use their exact `max_output_tokens` from {@link ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS}\n * (e.g. 128K for Opus), so this fallback only ever applies to ids not in the\n * map.\n */\nexport const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64_000\n\n/**\n * Runtime lookup of each model's maximum output-token ceiling, keyed by model\n * id. Lets the text adapter default the required `max_tokens` request field to\n * the model's real ceiling when the caller doesn't specify one, rather than a\n * low constant that truncates responses mid-stream (issue #849).\n *\n * Kept in sync with {@link ANTHROPIC_MODELS} by `scripts/sync-provider-models.ts`\n * — when that script adds a model it also inserts the model's `max_output_tokens`\n * here, so a freshly-synced model resolves to its real ceiling rather than the\n * fallback above.\n */\nconst ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {\n [CLAUDE_OPUS_4_6.id]: CLAUDE_OPUS_4_6.max_output_tokens,\n [CLAUDE_OPUS_4_5.id]: CLAUDE_OPUS_4_5.max_output_tokens,\n [CLAUDE_SONNET_4_6.id]: CLAUDE_SONNET_4_6.max_output_tokens,\n [CLAUDE_SONNET_4_5.id]: CLAUDE_SONNET_4_5.max_output_tokens,\n [CLAUDE_HAIKU_4_5.id]: CLAUDE_HAIKU_4_5.max_output_tokens,\n [CLAUDE_OPUS_4_1.id]: CLAUDE_OPUS_4_1.max_output_tokens,\n [CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,\n [CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,\n [CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,\n [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,\n [CLAUDE_OPUS_5.id]: CLAUDE_OPUS_5.max_output_tokens,\n [CLAUDE_OPUS_5_FAST.id]: CLAUDE_OPUS_5_FAST.max_output_tokens,\n}\n\n/**\n * Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**\n * request. The SDK refuses to make a non-streaming call it estimates could\n * exceed its 10-minute timeout, computed as\n * `(60min * max_tokens) / 128_000 > 10min` — i.e. it throws\n * `\"Streaming is required for operations that may take longer than 10 minutes\"`\n * once `max_tokens > 128_000 * 10 / 60 ≈ 21_333`\n * (`@anthropic-ai/sdk`'s `calculateNonstreamingTimeout`). The text adapter's\n * only non-streaming call is the forced-tool `structuredOutput()` request, so\n * its defaulted ceiling must stay at or below this; the streaming chat path\n * keeps the model's full {@link getAnthropicDefaultMaxTokens} ceiling. We sit\n * just under the boundary (`21_333` would round-trip to exactly 10min). This\n * caps only the *default* — an explicit oversized `max_tokens` from the caller\n * still surfaces the SDK's \"use streaming\" error, which is the correct signal.\n */\nexport const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21_000\n\n/**\n * Resolve the default `max_tokens` for a model: its known `max_output_tokens`\n * ceiling, or {@link ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS} for unknown models.\n * Callers that pass an explicit `max_tokens` bypass this entirely.\n *\n * Pass `stream: false` for non-streaming requests (the `structuredOutput()`\n * path): the result is then clamped to {@link ANTHROPIC_MAX_NONSTREAMING_TOKENS}\n * so the defaulted ceiling doesn't trip the SDK's non-streaming 10-minute guard\n * (issue #849). Streaming requests (the default) are unaffected and get the\n * model's full ceiling.\n */\nexport function getAnthropicDefaultMaxTokens(\n model: string,\n { stream = true }: { stream?: boolean } = {},\n): number {\n const ceiling =\n ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS[model] ??\n ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS\n return stream ? ceiling : Math.min(ceiling, ANTHROPIC_MAX_NONSTREAMING_TOKENS)\n}\n\n/**\n * Anthropic models that support combining `tools` + JSON-Schema-constrained\n * output in a single streaming Messages request (per issue #605). GA'd\n * 2026-01-29 for Claude 4.5+ via `output_format` on the beta messages\n * endpoint. Older Claude models still need the forced-tool-use workaround\n * in `structuredOutput`.\n */\nexport const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = new Set<string>([\n CLAUDE_OPUS_4_5.id,\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_HAIKU_4_5.id,\n])\n\n// const ANTHROPIC_IMAGE_MODELS = [] as const\n// const ANTHROPIC_EMBEDDING_MODELS = [] as const\n// const ANTHROPIC_AUDIO_MODELS = [] as const\n// const ANTHROPIC_VIDEO_MODELS = [] as const\n\nexport type AnthropicChatModel = (typeof ANTHROPIC_MODELS)[number]\n// Manual type map for per-model provider options\n// Models are differentiated by which thinking shapes and sampling\n// parameters the API accepts.\nexport type AnthropicChatModelProviderOptionsByName = {\n // 4.6 generation: adaptive thinking plus the deprecated budget-based\n // shape; sampling parameters still accepted.\n [CLAUDE_OPUS_4_6.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_6.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Pre-4.6 models: budget-based extended thinking and sampling parameters.\n [CLAUDE_OPUS_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_HAIKU_4_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_OPUS_4_1.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Opus 4.7/4.8: adaptive thinking (or explicit disable), no\n // budget_tokens, no sampling parameters — see the constants above.\n [CLAUDE_OPUS_4_7.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n [CLAUDE_OPUS_4_8.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n\n // Claude Fable 5: thinking always on (adaptive-only config); sampling\n // parameters removed — see the CLAUDE_FABLE_5 constant above.\n [CLAUDE_FABLE_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n // Claude Sonnet 5: adaptive thinking by default, explicit disable\n // allowed; no budget_tokens, no sampling parameters — see the\n // CLAUDE_SONNET_5 constant above.\n [CLAUDE_SONNET_5.id]: AnthropicCacheControlOptions &\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n [CLAUDE_OPUS_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_OPUS_5_FAST.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n}\n\nexport type AnthropicChatModelToolCapabilitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.tools\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.tools\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.tools\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.tools\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.tools\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.tools\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.tools\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools\n [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.tools\n [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.tools\n}\n\n/**\n * Type-only map from chat model name to its supported input modalities.\n * All Anthropic Claude models support text, image, and document (PDF) input.\n * Used by the core AI types to constrain ContentPart types based on the selected model.\n * Note: These must be inlined as readonly arrays (not typeof) because the model\n * constants are not exported and typeof references don't work in .d.ts files\n * when consumed by external packages.\n *\n * @see https://docs.anthropic.com/claude/docs/vision\n * @see https://docs.anthropic.com/claude/docs/pdf-support\n */\nexport type AnthropicModelInputModalitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.input\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.input\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.input\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.input\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.input\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.input\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.input\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input\n [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.input\n [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.input\n}\n"],"mappings":";AAmEA,IAAM,kBAAkB;CACtB,MAAM;CACN,IAAI;CACJ,gBAAgB;CAChB,mBAAmB;CACnB,kBAAkB;CAClB,SAAS;EACP,OAAO,EACL,QAAQ,EACV;EACA,QAAQ,EACN,QAAQ,GACV;CACF;CACA,UAAU;EACR,OAAO;GA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iBAAiB;EACvC,gBAAgB,KAAK,gBAAgB;EACrC,gBAAgB,KAAK,gBAAgB;EACrC,gBAAgB,KAAK,gBAAgB;EACrC,eAAe,KAAK,eAAe;EACnC,gBAAgB,KAAK,gBAAgB;EACrC,cAAc,KAAK,cAAc;EACjC,mBAAmB,KAAK,mBAAmB;AAC9C;;;;;;;;;;;;;;;;AAiBA,IAAa,oCAAoC;;;;;;;;;;;;AAajD,SAAgB,6BACd,OACA,EAAE,SAAS,SAA+B,CAAC,GACnC;CACR,MAAM,UACJ,kCAAkC,UAAA;CAEpC,OAAO,SAAS,UAAU,KAAK,IAAI,SAAS,iCAAiC;AAC/E;;;;;;;;AASA,IAAa,6DAA6C,IAAI,IAAY;CACxE,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,gBAAgB;CAChB,kBAAkB;CAClB,kBAAkB;CAClB,iBAAiB;AACnB,CAAC"}
@@ -23,13 +23,14 @@ function codeExecutionTool(config, options = {}) {
23
23
  if (skills.length > 8) throw new Error("code_execution supports at most 8 skills per request.");
24
24
  for (const skill of skills) if (skill.skill_id.length < 1 || skill.skill_id.length > 64) throw new Error("skill_id must be between 1 and 64 characters.");
25
25
  }
26
+ const metadata = {
27
+ config,
28
+ ...skills && { skills }
29
+ };
26
30
  return brandProviderTool({
27
31
  name: "code_execution",
28
32
  description: "",
29
- metadata: {
30
- config,
31
- ...skills && { skills }
32
- }
33
+ metadata
33
34
  });
34
35
  }
35
36
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"code-execution-tool.js","names":[],"sources":["../../../src/tools/code-execution-tool.ts"],"sourcesContent":["import { brandProviderTool } from '@tanstack/ai'\nimport type {\n BetaCodeExecutionTool20250522,\n BetaCodeExecutionTool20250825,\n} from '@anthropic-ai/sdk/resources/beta'\nimport type { ProviderTool, Tool } from '@tanstack/ai'\n\nexport type CodeExecutionToolConfig =\n | BetaCodeExecutionTool20250522\n | BetaCodeExecutionTool20250825\n\n/** @deprecated Renamed to `CodeExecutionToolConfig`. Will be removed in a future release. */\nexport type CodeExecutionTool = CodeExecutionToolConfig\n\n/**\n * A hosted/managed Anthropic Skill reference. Lifted by the text adapter into\n * the top-level `container.skills` request param (NOT serialized into the\n * `tools[]` entry). Requires the `code_execution` tool to be enabled.\n */\nexport interface AnthropicContainerSkill {\n /** 1–64 characters. */\n skill_id: string\n type: 'anthropic' | 'custom'\n /** Skill version, or `'latest'` (default) when omitted. */\n version?: string\n}\n\nexport interface CodeExecutionToolOptions {\n /** Hosted skills to load into the code-execution container (max 8). */\n skills?: Array<AnthropicContainerSkill>\n}\n\ninterface CodeExecutionToolMetadata {\n config: CodeExecutionToolConfig\n skills?: Array<AnthropicContainerSkill>\n}\n\nexport type AnthropicCodeExecutionTool = ProviderTool<\n 'anthropic',\n 'code_execution'\n>\n\nexport function convertCodeExecutionToolToAdapterFormat(\n tool: Tool,\n): CodeExecutionToolConfig {\n // The converter is only called for real `code_execution` tools, so a\n // non-undefined config is expected — but read via optional chaining so an\n // absent metadata object doesn't throw.\n return readCodeExecutionConfig(tool) as CodeExecutionToolConfig\n}\n\n/**\n * Reads the SDK tool config attached to a `code_execution` tool, if any.\n * Used by the text adapter to select the version-aware code-execution beta.\n */\nexport function readCodeExecutionConfig(\n tool: Tool,\n): CodeExecutionToolConfig | undefined {\n return (tool.metadata as CodeExecutionToolMetadata | undefined)?.config\n}\n\n/**\n * Reads the hosted skills attached to a `code_execution` tool, if any.\n * Used by the text adapter to build the top-level `container.skills` param.\n */\nexport function readCodeExecutionSkills(\n tool: Tool,\n): Array<AnthropicContainerSkill> | undefined {\n return (tool.metadata as CodeExecutionToolMetadata | undefined)?.skills\n}\n\nexport function codeExecutionTool(\n config: CodeExecutionToolConfig,\n options: CodeExecutionToolOptions = {},\n): AnthropicCodeExecutionTool {\n const { skills } = options\n if (skills) {\n if (skills.length > 8) {\n throw new Error('code_execution supports at most 8 skills per request.')\n }\n for (const skill of skills) {\n if (skill.skill_id.length < 1 || skill.skill_id.length > 64) {\n throw new Error('skill_id must be between 1 and 64 characters.')\n }\n }\n }\n const metadata: CodeExecutionToolMetadata = {\n config,\n ...(skills && { skills }),\n }\n return brandProviderTool<AnthropicCodeExecutionTool>({\n name: 'code_execution',\n description: '',\n metadata,\n })\n}\n"],"mappings":";;AA0CA,SAAgB,wCACd,MACyB;CAIzB,OAAO,wBAAwB,IAAI;AACrC;;;;;AAMA,SAAgB,wBACd,MACqC;CACrC,OAAQ,KAAK,UAAoD;AACnE;;;;;AAMA,SAAgB,wBACd,MAC4C;CAC5C,OAAQ,KAAK,UAAoD;AACnE;AAEA,SAAgB,kBACd,QACA,UAAoC,CAAC,GACT;CAC5B,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ;EACV,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MAAM,uDAAuD;EAEzE,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,SAAS,SAAS,KAAK,MAAM,SAAS,SAAS,IACvD,MAAM,IAAI,MAAM,+CAA+C;CAGrE;CAKA,OAAO,kBAA8C;EACnD,MAAM;EACN,aAAa;EACb,UAAA;GANA;GACA,GAAI,UAAU,EAAE,OAAO;EAKvB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"code-execution-tool.js","names":[],"sources":["../../../src/tools/code-execution-tool.ts"],"sourcesContent":["import { brandProviderTool } from '@tanstack/ai'\nimport type {\n BetaCodeExecutionTool20250522,\n BetaCodeExecutionTool20250825,\n} from '@anthropic-ai/sdk/resources/beta'\nimport type { ProviderTool, Tool } from '@tanstack/ai'\n\nexport type CodeExecutionToolConfig =\n | BetaCodeExecutionTool20250522\n | BetaCodeExecutionTool20250825\n\n/** @deprecated Renamed to `CodeExecutionToolConfig`. Will be removed in a future release. */\nexport type CodeExecutionTool = CodeExecutionToolConfig\n\n/**\n * A hosted/managed Anthropic Skill reference. Lifted by the text adapter into\n * the top-level `container.skills` request param (NOT serialized into the\n * `tools[]` entry). Requires the `code_execution` tool to be enabled.\n */\nexport interface AnthropicContainerSkill {\n /** 1–64 characters. */\n skill_id: string\n type: 'anthropic' | 'custom'\n /** Skill version, or `'latest'` (default) when omitted. */\n version?: string\n}\n\nexport interface CodeExecutionToolOptions {\n /** Hosted skills to load into the code-execution container (max 8). */\n skills?: Array<AnthropicContainerSkill>\n}\n\ninterface CodeExecutionToolMetadata {\n config: CodeExecutionToolConfig\n skills?: Array<AnthropicContainerSkill>\n}\n\nexport type AnthropicCodeExecutionTool = ProviderTool<\n 'anthropic',\n 'code_execution'\n>\n\nexport function convertCodeExecutionToolToAdapterFormat(\n tool: Tool,\n): CodeExecutionToolConfig {\n // The converter is only called for real `code_execution` tools, so a\n // non-undefined config is expected — but read via optional chaining so an\n // absent metadata object doesn't throw.\n return readCodeExecutionConfig(tool) as CodeExecutionToolConfig\n}\n\n/**\n * Reads the SDK tool config attached to a `code_execution` tool, if any.\n * Used by the text adapter to select the version-aware code-execution beta.\n */\nexport function readCodeExecutionConfig(\n tool: Tool,\n): CodeExecutionToolConfig | undefined {\n return (tool.metadata as CodeExecutionToolMetadata | undefined)?.config\n}\n\n/**\n * Reads the hosted skills attached to a `code_execution` tool, if any.\n * Used by the text adapter to build the top-level `container.skills` param.\n */\nexport function readCodeExecutionSkills(\n tool: Tool,\n): Array<AnthropicContainerSkill> | undefined {\n return (tool.metadata as CodeExecutionToolMetadata | undefined)?.skills\n}\n\nexport function codeExecutionTool(\n config: CodeExecutionToolConfig,\n options: CodeExecutionToolOptions = {},\n): AnthropicCodeExecutionTool {\n const { skills } = options\n if (skills) {\n if (skills.length > 8) {\n throw new Error('code_execution supports at most 8 skills per request.')\n }\n for (const skill of skills) {\n if (skill.skill_id.length < 1 || skill.skill_id.length > 64) {\n throw new Error('skill_id must be between 1 and 64 characters.')\n }\n }\n }\n const metadata: CodeExecutionToolMetadata = {\n config,\n ...(skills && { skills }),\n }\n return brandProviderTool<AnthropicCodeExecutionTool>({\n name: 'code_execution',\n description: '',\n metadata,\n })\n}\n"],"mappings":";;AA0CA,SAAgB,wCACd,MACyB;CAIzB,OAAO,wBAAwB,IAAI;AACrC;;;;;AAMA,SAAgB,wBACd,MACqC;CACrC,OAAQ,KAAK,UAAoD;AACnE;;;;;AAMA,SAAgB,wBACd,MAC4C;CAC5C,OAAQ,KAAK,UAAoD;AACnE;AAEA,SAAgB,kBACd,QACA,UAAoC,CAAC,GACT;CAC5B,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ;EACV,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MAAM,uDAAuD;EAEzE,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,SAAS,SAAS,KAAK,MAAM,SAAS,SAAS,IACvD,MAAM,IAAI,MAAM,+CAA+C;CAGrE;CACA,MAAM,WAAsC;EAC1C;EACA,GAAI,UAAU,EAAE,OAAO;CACzB;CACA,OAAO,kBAA8C;EACnD,MAAM;EACN,aAAa;EACb;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-anthropic",
3
- "version": "0.16.5",
3
+ "version": "0.16.6",
4
4
  "description": "Anthropic Claude adapter for TanStack AI chat, tool calling, thinking, and structured outputs.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -53,12 +53,12 @@
53
53
  },
54
54
  "peerDependencies": {
55
55
  "zod": "^4.0.0",
56
- "@tanstack/ai": "^0.44.0"
56
+ "@tanstack/ai": "^0.45.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@vitest/coverage-v8": "4.0.14",
59
+ "@vitest/coverage-v8": "4.1.10",
60
60
  "zod": "^4.2.0",
61
- "@tanstack/ai": "0.44.0"
61
+ "@tanstack/ai": "0.45.0"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vite build",
package/src/model-meta.ts CHANGED
@@ -502,7 +502,67 @@ const CLAUDE_SONNET_5 = {
502
502
  * via the `speed` parameter, not a model id) were removed after Anthropic
503
503
  * turned them off.
504
504
  */
505
+ const CLAUDE_OPUS_5 = {
506
+ name: 'claude-opus-5',
507
+ id: 'claude-opus-5',
508
+ context_window: 1_000_000,
509
+ max_output_tokens: 128_000,
510
+ supports: {
511
+ input: ['text', 'image', 'document'],
512
+ tools: [],
513
+ },
514
+ pricing: {
515
+ input: {
516
+ normal: 5,
517
+ cached: 0.5,
518
+ },
519
+ output: {
520
+ normal: 25,
521
+ },
522
+ },
523
+ } as const satisfies ModelMeta<
524
+ AnthropicContainerOptions &
525
+ AnthropicContextManagementOptions &
526
+ AnthropicMCPOptions &
527
+ AnthropicServiceTierOptions &
528
+ AnthropicStopSequencesOptions &
529
+ AnthropicThinkingOptions &
530
+ AnthropicToolChoiceOptions &
531
+ AnthropicSamplingOptions
532
+ >
533
+
534
+ const CLAUDE_OPUS_5_FAST = {
535
+ name: 'claude-opus-5-fast',
536
+ id: 'claude-opus-5-fast',
537
+ context_window: 1_000_000,
538
+ max_output_tokens: 128_000,
539
+ supports: {
540
+ input: ['text', 'image', 'document'],
541
+ tools: [],
542
+ },
543
+ pricing: {
544
+ input: {
545
+ normal: 10,
546
+ cached: 1,
547
+ },
548
+ output: {
549
+ normal: 50,
550
+ },
551
+ },
552
+ } as const satisfies ModelMeta<
553
+ AnthropicContainerOptions &
554
+ AnthropicContextManagementOptions &
555
+ AnthropicMCPOptions &
556
+ AnthropicServiceTierOptions &
557
+ AnthropicStopSequencesOptions &
558
+ AnthropicThinkingOptions &
559
+ AnthropicToolChoiceOptions &
560
+ AnthropicSamplingOptions
561
+ >
562
+
505
563
  export const ANTHROPIC_MODELS = [
564
+ CLAUDE_OPUS_5.id,
565
+ CLAUDE_OPUS_5_FAST.id,
506
566
  CLAUDE_OPUS_4_6.id,
507
567
  CLAUDE_OPUS_4_5.id,
508
568
  CLAUDE_SONNET_4_6.id,
@@ -552,6 +612,8 @@ const ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {
552
612
  [CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,
553
613
  [CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,
554
614
  [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,
615
+ [CLAUDE_OPUS_5.id]: CLAUDE_OPUS_5.max_output_tokens,
616
+ [CLAUDE_OPUS_5_FAST.id]: CLAUDE_OPUS_5_FAST.max_output_tokens,
555
617
  }
556
618
 
557
619
  /**
@@ -728,6 +790,22 @@ export type AnthropicChatModelProviderOptionsByName = {
728
790
  AnthropicToolChoiceOptions &
729
791
  AnthropicMaxTokensOptions &
730
792
  AnthropicOutputConfigOptions
793
+ [CLAUDE_OPUS_5.id]: AnthropicContainerOptions &
794
+ AnthropicContextManagementOptions &
795
+ AnthropicMCPOptions &
796
+ AnthropicServiceTierOptions &
797
+ AnthropicStopSequencesOptions &
798
+ AnthropicThinkingOptions &
799
+ AnthropicToolChoiceOptions &
800
+ AnthropicSamplingOptions
801
+ [CLAUDE_OPUS_5_FAST.id]: AnthropicContainerOptions &
802
+ AnthropicContextManagementOptions &
803
+ AnthropicMCPOptions &
804
+ AnthropicServiceTierOptions &
805
+ AnthropicStopSequencesOptions &
806
+ AnthropicThinkingOptions &
807
+ AnthropicToolChoiceOptions &
808
+ AnthropicSamplingOptions
731
809
  }
732
810
 
733
811
  export type AnthropicChatModelToolCapabilitiesByName = {
@@ -741,6 +819,8 @@ export type AnthropicChatModelToolCapabilitiesByName = {
741
819
  [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools
742
820
  [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools
743
821
  [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools
822
+ [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.tools
823
+ [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.tools
744
824
  }
745
825
 
746
826
  /**
@@ -765,4 +845,6 @@ export type AnthropicModelInputModalitiesByName = {
765
845
  [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input
766
846
  [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input
767
847
  [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input
848
+ [CLAUDE_OPUS_5.id]: typeof CLAUDE_OPUS_5.supports.input
849
+ [CLAUDE_OPUS_5_FAST.id]: typeof CLAUDE_OPUS_5_FAST.supports.input
768
850
  }