@providerprotocol/ai 0.0.23 → 0.0.24
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.
- package/dist/anthropic/index.d.ts +1 -1
- package/dist/anthropic/index.js +66 -12
- package/dist/anthropic/index.js.map +1 -1
- package/dist/{chunk-MF5ETY5O.js → chunk-6AZVUI6H.js} +8 -1
- package/dist/chunk-6AZVUI6H.js.map +1 -0
- package/dist/{chunk-NWS5IKNR.js → chunk-TOJCZMVU.js} +3 -12
- package/dist/chunk-TOJCZMVU.js.map +1 -0
- package/dist/google/index.d.ts +34 -3
- package/dist/google/index.js +62 -22
- package/dist/google/index.js.map +1 -1
- package/dist/http/index.d.ts +2 -2
- package/dist/http/index.js +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/ollama/index.d.ts +1 -1
- package/dist/ollama/index.js +14 -8
- package/dist/ollama/index.js.map +1 -1
- package/dist/openai/index.d.ts +1 -1
- package/dist/openai/index.js +60 -4
- package/dist/openai/index.js.map +1 -1
- package/dist/openrouter/index.d.ts +1 -1
- package/dist/openrouter/index.js +2 -2
- package/dist/{provider-DR1yins0.d.ts → provider-x4RocsnK.d.ts} +52 -3
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/dist/{retry-DJiqAslw.d.ts → retry-DTfjXXPh.d.ts} +1 -1
- package/dist/{stream-BuTrqt_j.d.ts → stream-ITNFNnO4.d.ts} +6 -1
- package/dist/xai/index.d.ts +1 -1
- package/dist/xai/index.js +151 -32
- package/dist/xai/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-MF5ETY5O.js.map +0 -1
- package/dist/chunk-NWS5IKNR.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/providers/anthropic/types.ts","../../src/providers/anthropic/transform.ts","../../src/providers/anthropic/llm.ts","../../src/providers/anthropic/index.ts"],"sourcesContent":["/**\n * @fileoverview Anthropic API type definitions.\n *\n * Contains TypeScript interfaces for Anthropic's Messages API request/response\n * structures, streaming events, and provider-specific parameters.\n */\n\n// ============================================\n// Beta Headers\n// ============================================\n\n/**\n * Known Anthropic beta header values.\n *\n * Beta features are enabled by passing these values in the `betas` config option\n * or via the `anthropic-beta` HTTP header. Multiple betas can be enabled simultaneously.\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n *\n * // Using the betas config option (recommended)\n * const provider = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.interleavedThinking],\n * });\n *\n * // Or use string values directly for new/unlisted betas\n * const provider = anthropic('claude-sonnet-4-20250514', {\n * betas: ['new-beta-2025-12-01'],\n * });\n * ```\n */\nexport const betas = {\n // Structured Outputs\n /** Guaranteed JSON schema conformance for responses. Available for Claude Sonnet 4.5+. */\n structuredOutputs: 'structured-outputs-2025-11-13',\n\n // Extended Thinking / Reasoning\n /** Enables Claude to think between tool calls in Claude 4 models. */\n interleavedThinking: 'interleaved-thinking-2025-05-14',\n /** Developer mode for full thinking output visibility. */\n devFullThinking: 'dev-full-thinking-2025-05-14',\n /** Effort parameter for Claude Opus 4.5 - controls response thoroughness vs efficiency. */\n effort: 'effort-2025-11-24',\n\n // Computer Use\n /** Legacy computer use tool (Claude 3.x models). */\n computerUseLegacy: 'computer-use-2024-10-22',\n /** Computer use tool for Claude 4 models (mouse, keyboard, screenshots). */\n computerUse: 'computer-use-2025-01-24',\n /** Computer use tool for Claude Opus 4.5 with additional commands. */\n computerUseOpus: 'computer-use-2025-11-24',\n\n // Extended Output / Context\n /** Enables up to 8,192 output tokens from Claude Sonnet 3.5. */\n maxTokens35Sonnet: 'max-tokens-3-5-sonnet-2024-07-15',\n /** Enables 128K token output length. */\n output128k: 'output-128k-2025-02-19',\n /** Enables 1 million token context window for Claude Sonnet 4. */\n context1m: 'context-1m-2025-08-07',\n\n // Token Efficiency\n /** Reduces output token consumption by up to 70% for tool calls. */\n tokenEfficientTools: 'token-efficient-tools-2025-02-19',\n /** Streams tool use parameters without buffering/JSON validation. */\n fineGrainedToolStreaming: 'fine-grained-tool-streaming-2025-05-14',\n\n // Code Execution\n /** Code execution tool for running Python/Bash in secure sandbox. */\n codeExecution: 'code-execution-2025-08-25',\n\n // Advanced Tool Use\n /** Advanced tool use: Tool Search, Programmatic Tool Calling, Tool Use Examples. */\n advancedToolUse: 'advanced-tool-use-2025-11-20',\n\n // Files & Documents\n /** Files API for uploading and managing files. */\n filesApi: 'files-api-2025-04-14',\n /** PDF document support. */\n pdfs: 'pdfs-2024-09-25',\n\n // MCP (Model Context Protocol)\n /** MCP connector to connect to remote MCP servers. */\n mcpClient: 'mcp-client-2025-04-04',\n /** Updated MCP client. */\n mcpClientLatest: 'mcp-client-2025-11-20',\n\n // Caching\n /** Prompt caching for reduced latency and costs. Now works automatically with cache_control. */\n promptCaching: 'prompt-caching-2024-07-31',\n /** Enables 1-hour cache TTL (vs default 5-minute). */\n extendedCacheTtl: 'extended-cache-ttl-2025-04-11',\n\n // Context Management\n /** Automatic tool call clearing for context management. */\n contextManagement: 'context-management-2025-06-27',\n /** Handling for when model context window is exceeded. */\n modelContextWindowExceeded: 'model-context-window-exceeded-2025-08-26',\n\n // Message Batches (generally available but may still need header)\n /** Message Batches API for async processing at 50% cost. */\n messageBatches: 'message-batches-2024-09-24',\n\n // Token Counting (generally available)\n /** Token counting endpoint. */\n tokenCounting: 'token-counting-2024-11-01',\n\n // Skills\n /** Agent Skills for specialized tasks (PowerPoint, Excel, Word, PDF). */\n skills: 'skills-2025-10-02',\n} as const;\n\n/** Type representing any valid beta key from the betas object. */\nexport type BetaKey = keyof typeof betas;\n\n/** Type representing a beta value (either a known constant or arbitrary string). */\nexport type BetaValue = (typeof betas)[BetaKey] | string;\n\n/**\n * Provider-specific parameters for Anthropic Claude models.\n *\n * These parameters are passed through to the Anthropic Messages API and\n * control model behavior such as sampling, token limits, and extended thinking.\n *\n * @example\n * ```typescript\n * const params: AnthropicLLMParams = {\n * max_tokens: 4096,\n * temperature: 0.7,\n * thinking: { type: 'enabled', budget_tokens: 10000 },\n * };\n * ```\n */\nexport interface AnthropicLLMParams {\n /** Maximum number of tokens to generate. Defaults to model maximum if not specified. */\n max_tokens?: number;\n\n /** Sampling temperature from 0.0 (deterministic) to 1.0 (maximum randomness). */\n temperature?: number;\n\n /** Nucleus sampling threshold. Only tokens with cumulative probability <= top_p are considered. */\n top_p?: number;\n\n /** Top-k sampling. Only the k most likely tokens are considered at each step. */\n top_k?: number;\n\n /** Custom sequences that will cause the model to stop generating. */\n stop_sequences?: string[];\n\n /** Request metadata for tracking and analytics. */\n metadata?: {\n /** Unique identifier for the end user making the request. */\n user_id?: string;\n };\n\n /** Extended thinking configuration for complex reasoning tasks. */\n thinking?: {\n /** Must be 'enabled' to activate extended thinking. */\n type: 'enabled';\n /** Token budget for the thinking process. */\n budget_tokens: number;\n };\n\n /**\n * Service tier selection for capacity routing.\n * - `auto`: Automatically select based on availability (default)\n * - `standard_only`: Only use standard capacity, never priority\n */\n service_tier?: 'auto' | 'standard_only';\n\n /**\n * Built-in tools for server-side execution.\n *\n * Use the tool helper constructors from the `tools` namespace:\n * - `tools.webSearch()` - Web search capability\n * - `tools.computer()` - Computer use (mouse, keyboard, screenshots)\n * - `tools.textEditor()` - File viewing and editing\n * - `tools.bash()` - Shell command execution\n * - `tools.codeExecution()` - Sandboxed Python/Bash execution\n * - `tools.toolSearch()` - Dynamic tool catalog search\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * tools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\n tools?: AnthropicBuiltInTool[];\n\n /**\n * Container ID for code execution tool reuse.\n * Pass the container ID from a previous response to reuse the same environment.\n */\n container?: string;\n}\n\n/**\n * System content block for structured system prompts with caching support.\n *\n * When system is provided as an array, each block can have cache_control.\n */\nexport interface AnthropicSystemContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Request body structure for Anthropic's Messages API.\n *\n * This interface represents the full request payload sent to the\n * `/v1/messages` endpoint.\n */\n/**\n * Native structured output format configuration.\n *\n * When provided, Claude's response will be constrained to match the\n * specified JSON schema. Requires the beta header `structured-outputs-2025-11-13`.\n *\n * @example\n * ```typescript\n * const outputFormat: AnthropicOutputFormat = {\n * type: 'json_schema',\n * schema: {\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'integer' },\n * },\n * required: ['name', 'age'],\n * additionalProperties: false,\n * },\n * };\n * ```\n */\nexport interface AnthropicOutputFormat {\n /** Output format type - currently only 'json_schema' is supported. */\n type: 'json_schema';\n /** JSON Schema defining the expected response structure. */\n schema: {\n /** Schema type (always 'object' for structured outputs). */\n type: 'object';\n /** Property definitions for each field. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n /** Must be false for structured outputs. */\n additionalProperties?: false;\n };\n}\n\nexport interface AnthropicRequest {\n /** The model identifier (e.g., 'claude-sonnet-4-20250514'). */\n model: string;\n /** Maximum tokens to generate in the response. */\n max_tokens?: number;\n /** Conversation messages in Anthropic's format. */\n messages: AnthropicMessage[];\n /** System prompt - string for simple prompts, array for caching support. */\n system?: string | AnthropicSystemContent[];\n /** Sampling temperature. */\n temperature?: number;\n /** Nucleus sampling threshold. */\n top_p?: number;\n /** Top-k sampling value. */\n top_k?: number;\n /** Stop sequences to halt generation. */\n stop_sequences?: string[];\n /** Enable Server-Sent Events streaming. */\n stream?: boolean;\n /** Available tools for function calling and built-in tools. */\n tools?: (AnthropicTool | AnthropicBuiltInTool)[];\n /** Tool selection strategy. */\n tool_choice?: { type: 'auto' | 'any' | 'tool'; name?: string };\n /** Request metadata for tracking. */\n metadata?: { user_id?: string };\n /** Extended thinking configuration. */\n thinking?: { type: 'enabled'; budget_tokens: number };\n /** Capacity tier selection. */\n service_tier?: 'auto' | 'standard_only';\n /**\n * Native structured output format.\n *\n * Constrains Claude's response to match the specified JSON schema.\n * Requires the beta header `structured-outputs-2025-11-13`.\n *\n * @see {@link AnthropicOutputFormat}\n */\n output_format?: AnthropicOutputFormat;\n}\n\n/**\n * A single message in an Anthropic conversation.\n *\n * Messages alternate between 'user' and 'assistant' roles. Content can be\n * a simple string or an array of typed content blocks.\n */\nexport interface AnthropicMessage {\n /** The role of the message sender. */\n role: 'user' | 'assistant';\n /** Message content as string or structured content blocks. */\n content: AnthropicContent[] | string;\n}\n\n/**\n * Union type for all Anthropic content block types.\n *\n * Used in both request messages and response content arrays.\n */\nexport type AnthropicContent =\n | AnthropicTextContent\n | AnthropicImageContent\n | AnthropicToolUseContent\n | AnthropicToolResultContent;\n\n/**\n * Cache control configuration for prompt caching.\n *\n * Marks content blocks for caching to reduce costs and latency\n * on subsequent requests with the same prefix.\n *\n * @example\n * ```typescript\n * const cacheControl: AnthropicCacheControl = {\n * type: 'ephemeral',\n * ttl: '1h' // Optional: extend to 1-hour cache\n * };\n * ```\n */\nexport interface AnthropicCacheControl {\n /** Cache type - only 'ephemeral' is supported */\n type: 'ephemeral';\n /** Optional TTL: '5m' (default) or '1h' for extended caching */\n ttl?: '5m' | '1h';\n}\n\n/**\n * Plain text content block.\n */\nexport interface AnthropicTextContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Image content block for vision capabilities.\n *\n * Images can be provided as base64-encoded data or via URL.\n */\nexport interface AnthropicImageContent {\n /** Content type discriminator. */\n type: 'image';\n /** Image source configuration. */\n source: {\n /** How the image data is provided. */\n type: 'base64' | 'url';\n /** MIME type of the image (required for base64). */\n media_type?: string;\n /** Base64-encoded image data. */\n data?: string;\n /** URL to fetch the image from. */\n url?: string;\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool use content block representing a function call by the assistant.\n *\n * Appears in assistant messages when the model invokes a tool.\n */\nexport interface AnthropicToolUseContent {\n /** Content type discriminator. */\n type: 'tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the tool being called. */\n name: string;\n /** Arguments passed to the tool as a JSON object. */\n input: Record<string, unknown>;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool result content block providing the output of a tool call.\n *\n * Sent in user messages to provide results for previous tool_use blocks.\n */\nexport interface AnthropicToolResultContent {\n /** Content type discriminator. */\n type: 'tool_result';\n /** ID of the tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The result content (string or structured blocks). */\n content: string | AnthropicContent[];\n /** Whether the tool execution resulted in an error. */\n is_error?: boolean;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool definition for Anthropic's function calling feature.\n *\n * Defines a callable function that the model can invoke during generation.\n */\nexport interface AnthropicTool {\n /** Unique name for the tool. */\n name: string;\n /** Description of what the tool does and when to use it. */\n description: string;\n /** JSON Schema defining the expected input parameters. */\n input_schema: {\n /** Schema type (always 'object' for tool inputs). */\n type: 'object';\n /** Property definitions for each parameter. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Complete response from the Anthropic Messages API.\n *\n * Returned from non-streaming requests and contains the full\n * generated content along with usage statistics.\n */\nexport interface AnthropicResponse {\n /** Unique identifier for this response. */\n id: string;\n /** Response type (always 'message'). */\n type: 'message';\n /** Role of the responder (always 'assistant'). */\n role: 'assistant';\n /** Generated content blocks. */\n content: AnthropicResponseContent[];\n /** Model that generated this response. */\n model: string;\n /**\n * Reason the model stopped generating.\n * - `end_turn`: Natural completion\n * - `max_tokens`: Hit token limit\n * - `stop_sequence`: Hit a stop sequence\n * - `tool_use`: Model wants to use a tool\n * - `pause_turn`: Paused for extended thinking\n * - `refusal`: Model refused to respond\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal' | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n /** Token usage statistics. */\n usage: {\n /** Tokens consumed by the input. */\n input_tokens: number;\n /** Tokens generated in the output. */\n output_tokens: number;\n /** Tokens used to create cache entries. */\n cache_creation_input_tokens?: number;\n /** Tokens read from cache. */\n cache_read_input_tokens?: number;\n };\n}\n\n/**\n * Union type for content blocks that can appear in API responses.\n *\n * Includes text, tool use, thinking blocks, and code execution results.\n */\nexport type AnthropicResponseContent =\n | AnthropicTextContent\n | AnthropicToolUseContent\n | AnthropicThinkingContent\n | AnthropicServerToolUseContent\n | AnthropicBashCodeExecutionToolResultContent\n | AnthropicTextEditorCodeExecutionToolResultContent;\n\n/**\n * Thinking content block from extended thinking feature.\n *\n * Contains the model's internal reasoning process when thinking is enabled.\n */\nexport interface AnthropicThinkingContent {\n /** Content type discriminator. */\n type: 'thinking';\n /** The model's thinking/reasoning text. */\n thinking: string;\n /** Cryptographic signature for thinking verification. */\n signature?: string;\n}\n\n/**\n * Server tool use content block for built-in tools like code execution.\n *\n * Appears when Claude invokes a server-side tool.\n */\nexport interface AnthropicServerToolUseContent {\n /** Content type discriminator. */\n type: 'server_tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the server tool being called (e.g., 'bash_code_execution', 'text_editor_code_execution'). */\n name: string;\n /** Arguments passed to the tool. */\n input: Record<string, unknown>;\n}\n\n/**\n * Result from bash code execution tool.\n *\n * Contains stdout, stderr, and return code from command execution.\n */\nexport interface AnthropicBashCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'bash_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The execution result. */\n content: {\n /** Result type discriminator. */\n type: 'bash_code_execution_result';\n /** Standard output from the command. */\n stdout: string;\n /** Standard error from the command. */\n stderr: string;\n /** Exit code (0 for success). */\n return_code: number;\n /** File IDs for any files created during execution. */\n content?: Array<{ file_id: string }>;\n } | {\n /** Error result type. */\n type: 'bash_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Result from text editor code execution tool.\n *\n * Contains file operation results.\n */\nexport interface AnthropicTextEditorCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'text_editor_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The operation result. */\n content: {\n /** Result type discriminator. */\n type: 'text_editor_code_execution_result';\n /** File type (for view operations). */\n file_type?: string;\n /** File content (for view operations). */\n content?: string;\n /** Number of lines returned (for view operations). */\n numLines?: number;\n /** Starting line number (for view operations). */\n startLine?: number;\n /** Total lines in file (for view operations). */\n totalLines?: number;\n /** Whether this was a file update (for create operations). */\n is_file_update?: boolean;\n /** Old start line (for edit operations). */\n oldStart?: number;\n /** Old line count (for edit operations). */\n oldLines?: number;\n /** New start line (for edit operations). */\n newStart?: number;\n /** New line count (for edit operations). */\n newLines?: number;\n /** Diff lines (for edit operations). */\n lines?: string[];\n } | {\n /** Error result type. */\n type: 'text_editor_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Union type for all Server-Sent Events from Anthropic's streaming API.\n *\n * Events are received in a specific order:\n * 1. message_start - Initial message metadata\n * 2. content_block_start - Beginning of each content block\n * 3. content_block_delta - Incremental content updates (multiple)\n * 4. content_block_stop - End of each content block\n * 5. message_delta - Final usage and stop reason\n * 6. message_stop - Stream complete\n */\nexport type AnthropicStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent;\n\n/**\n * Initial event containing message metadata and partial response.\n */\nexport interface AnthropicMessageStartEvent {\n /** Event type discriminator. */\n type: 'message_start';\n /** Partial response with id, model, and input token count. */\n message: AnthropicResponse;\n}\n\n/**\n * Signals the start of a new content block.\n */\nexport interface AnthropicContentBlockStartEvent {\n /** Event type discriminator. */\n type: 'content_block_start';\n /** Zero-based index of this content block. */\n index: number;\n /** Initial content block data (may be empty for streaming). */\n content_block: AnthropicResponseContent;\n}\n\n/**\n * Incremental update to a content block's content.\n *\n * Multiple delta events are sent as content is generated.\n */\nexport interface AnthropicContentBlockDeltaEvent {\n /** Event type discriminator. */\n type: 'content_block_delta';\n /** Index of the content block being updated. */\n index: number;\n /** The incremental content update. */\n delta:\n | { type: 'text_delta'; text: string }\n | { type: 'thinking_delta'; thinking: string }\n | { type: 'signature_delta'; signature: string }\n | { type: 'input_json_delta'; partial_json: string };\n}\n\n/**\n * Signals the end of a content block.\n */\nexport interface AnthropicContentBlockStopEvent {\n /** Event type discriminator. */\n type: 'content_block_stop';\n /** Index of the completed content block. */\n index: number;\n}\n\n/**\n * Final message update with stop reason and output token count.\n */\nexport interface AnthropicMessageDeltaEvent {\n /** Event type discriminator. */\n type: 'message_delta';\n /** Final message metadata. */\n delta: {\n /** Why the model stopped generating. */\n stop_reason: string | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n };\n /** Final usage statistics. */\n usage: {\n /** Total output tokens generated. */\n output_tokens: number;\n };\n}\n\n/**\n * Terminal event indicating the stream is complete.\n */\nexport interface AnthropicMessageStopEvent {\n /** Event type discriminator. */\n type: 'message_stop';\n}\n\n/**\n * Keep-alive event sent periodically during long operations.\n */\nexport interface AnthropicPingEvent {\n /** Event type discriminator. */\n type: 'ping';\n}\n\n/**\n * Error event indicating a problem during streaming.\n */\nexport interface AnthropicErrorEvent {\n /** Event type discriminator. */\n type: 'error';\n /** Error details. */\n error: {\n /** Error type identifier. */\n type: string;\n /** Human-readable error message. */\n message: string;\n };\n}\n\n/**\n * Anthropic-specific HTTP headers for API requests.\n *\n * @example\n * ```typescript\n * const headers: AnthropicHeaders = {\n * 'anthropic-beta': 'extended-cache-ttl-2025-04-11',\n * };\n * ```\n */\nexport interface AnthropicHeaders {\n /**\n * Beta features header.\n *\n * Comma-separated list of beta feature flags:\n * - `extended-cache-ttl-2025-04-11` - Enable 1-hour cache TTL\n * - `token-efficient-tools-2025-02-19` - Token-efficient tool encoding\n * - `computer-use-2025-01-24` - Computer use tool (Claude 4 models)\n * - `computer-use-2025-11-24` - Computer use tool (Claude Opus 4.5)\n * - `code-execution-2025-08-25` - Code execution tool\n * - `advanced-tool-use-2025-11-20` - Tool search tool\n */\n 'anthropic-beta'?: string;\n [key: string]: string | undefined;\n}\n\n// ============================================\n// Built-in Tools\n// ============================================\n\n/**\n * User location for web search context.\n *\n * Used to localize web search results based on the user's approximate location.\n */\nexport interface AnthropicUserLocation {\n /** Location type - must be 'approximate' */\n type: 'approximate';\n /** City name */\n city?: string;\n /** Region/state name */\n region?: string;\n /** ISO 3166-1 alpha-2 country code (e.g., \"US\") */\n country?: string;\n /** IANA timezone (e.g., \"America/New_York\") */\n timezone?: string;\n}\n\n/**\n * Web search tool for real-time web information retrieval.\n *\n * Enables Claude to search the web for up-to-date information.\n * No beta header required - this is a GA feature.\n *\n * @example\n * ```typescript\n * const tool: AnthropicWebSearchTool = {\n * type: 'web_search_20250305',\n * name: 'web_search',\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * };\n * ```\n */\nexport interface AnthropicWebSearchTool {\n /** Tool type identifier */\n type: 'web_search_20250305';\n /** Tool name - must be 'web_search' */\n name: 'web_search';\n /** Maximum searches per request (default: unlimited) */\n max_uses?: number;\n /** Whitelist domains (mutually exclusive with blocked_domains) */\n allowed_domains?: string[];\n /** Blacklist domains (mutually exclusive with allowed_domains) */\n blocked_domains?: string[];\n /** User location for localized results */\n user_location?: AnthropicUserLocation;\n}\n\n/**\n * Computer use tool for desktop automation.\n *\n * Enables Claude to interact with computer interfaces through\n * mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header:\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other Claude 4 models\n *\n * @example\n * ```typescript\n * const tool: AnthropicComputerTool = {\n * type: 'computer_20250124',\n * name: 'computer',\n * display_width_px: 1920,\n * display_height_px: 1080,\n * };\n * ```\n */\nexport interface AnthropicComputerTool {\n /** Tool type identifier (version-specific) */\n type: 'computer_20251124' | 'computer_20250124';\n /** Tool name - must be 'computer' */\n name: 'computer';\n /** Display width in pixels */\n display_width_px: number;\n /** Display height in pixels */\n display_height_px: number;\n /** X11 display number (optional) */\n display_number?: number;\n /** Enable zoom action (Opus 4.5 only with 20251124 version) */\n enable_zoom?: boolean;\n}\n\n/**\n * Text editor tool for file viewing and editing.\n *\n * Enables Claude to view, create, and edit files with\n * commands like view, str_replace, create, and insert.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicTextEditorTool = {\n * type: 'text_editor_20250728',\n * name: 'str_replace_based_edit_tool',\n * max_characters: 10000,\n * };\n * ```\n */\nexport interface AnthropicTextEditorTool {\n /** Tool type identifier (version-specific) */\n type: 'text_editor_20250728' | 'text_editor_20250124';\n /** Tool name (version-specific) */\n name: 'str_replace_based_edit_tool' | 'str_replace_editor';\n /** Max characters for view truncation (20250728+ only) */\n max_characters?: number;\n}\n\n/**\n * Bash tool for shell command execution.\n *\n * Enables Claude to execute bash commands in a shell session.\n * The session persists within the conversation.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicBashTool = {\n * type: 'bash_20250124',\n * name: 'bash',\n * };\n * ```\n */\nexport interface AnthropicBashTool {\n /** Tool type identifier */\n type: 'bash_20250124';\n /** Tool name - must be 'bash' */\n name: 'bash';\n}\n\n/**\n * Code execution tool for sandboxed Python/Bash execution.\n *\n * Enables Claude to write and execute code in a secure container\n * with pre-installed data science libraries.\n *\n * Requires beta header: `code-execution-2025-08-25`\n *\n * @example\n * ```typescript\n * const tool: AnthropicCodeExecutionTool = {\n * type: 'code_execution_20250825',\n * name: 'code_execution',\n * };\n * ```\n */\nexport interface AnthropicCodeExecutionTool {\n /** Tool type identifier */\n type: 'code_execution_20250825';\n /** Tool name - must be 'code_execution' */\n name: 'code_execution';\n}\n\n/**\n * Tool search tool for dynamic tool discovery.\n *\n * Enables Claude to search through large tool catalogs\n * using regex or natural language (BM25) queries.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20`\n *\n * @example\n * ```typescript\n * const tool: AnthropicToolSearchTool = {\n * type: 'tool_search_tool_regex_20251119',\n * name: 'tool_search_tool_regex',\n * };\n * ```\n */\nexport interface AnthropicToolSearchTool {\n /** Tool type identifier (regex or BM25 variant) */\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_bm25_20251119';\n /** Tool name (must match type variant) */\n name: 'tool_search_tool_regex' | 'tool_search_tool_bm25';\n}\n\n/**\n * Union type for all Anthropic built-in tools.\n *\n * Built-in tools run server-side and have special handling\n * different from user-defined function tools.\n */\nexport type AnthropicBuiltInTool =\n | AnthropicWebSearchTool\n | AnthropicComputerTool\n | AnthropicTextEditorTool\n | AnthropicBashTool\n | AnthropicCodeExecutionTool\n | AnthropicToolSearchTool;\n\n/**\n * Combined tool type for API requests (user-defined or built-in).\n */\nexport type AnthropicToolUnion = AnthropicTool | AnthropicBuiltInTool;\n\n// ============================================\n// Tool Helper Constructors\n// ============================================\n\n/**\n * Creates a web search tool configuration.\n *\n * The web search tool enables Claude to search the web for up-to-date information.\n * Pricing: $10 per 1,000 searches plus standard token costs.\n *\n * @param options - Optional configuration for search behavior\n * @returns A web search tool configuration object\n *\n * @example\n * ```typescript\n * // Basic web search\n * const search = webSearchTool();\n *\n * // With configuration\n * const searchWithOptions = webSearchTool({\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * user_location: {\n * type: 'approximate',\n * city: 'San Francisco',\n * country: 'US',\n * },\n * });\n * ```\n */\nexport function webSearchTool(options?: {\n max_uses?: number;\n allowed_domains?: string[];\n blocked_domains?: string[];\n user_location?: AnthropicUserLocation;\n}): AnthropicWebSearchTool {\n return {\n type: 'web_search_20250305',\n name: 'web_search',\n ...options,\n };\n}\n\n/**\n * Creates a computer use tool configuration.\n *\n * The computer tool enables Claude to interact with computer interfaces\n * through mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header (automatically injected when using this tool):\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other models\n *\n * @param options - Display configuration and optional settings\n * @returns A computer tool configuration object\n *\n * @example\n * ```typescript\n * const computer = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * });\n *\n * // For Opus 4.5 with zoom support\n * const computerOpus = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * version: '20251124',\n * enable_zoom: true,\n * });\n * ```\n */\nexport function computerTool(options: {\n display_width_px: number;\n display_height_px: number;\n display_number?: number;\n enable_zoom?: boolean;\n /** Use '20251124' for Claude Opus 4.5, '20250124' for other models */\n version?: '20251124' | '20250124';\n}): AnthropicComputerTool {\n const { version = '20250124', ...rest } = options;\n return {\n type: version === '20251124' ? 'computer_20251124' : 'computer_20250124',\n name: 'computer',\n ...rest,\n };\n}\n\n/**\n * Creates a text editor tool configuration.\n *\n * The text editor tool enables Claude to view, create, and edit files\n * using commands like view, str_replace, create, and insert.\n *\n * Token overhead: ~700 tokens per tool definition.\n *\n * @param options - Optional configuration\n * @returns A text editor tool configuration object\n *\n * @example\n * ```typescript\n * const editor = textEditorTool();\n *\n * // With max characters for view truncation\n * const editorWithLimit = textEditorTool({\n * max_characters: 10000,\n * });\n * ```\n */\nexport function textEditorTool(options?: {\n max_characters?: number;\n /** Use '20250728' for Claude 4, '20250124' for Claude 3.7 */\n version?: '20250728' | '20250124';\n}): AnthropicTextEditorTool {\n const version = options?.version ?? '20250728';\n return {\n type: version === '20250728' ? 'text_editor_20250728' : 'text_editor_20250124',\n name: version === '20250728' ? 'str_replace_based_edit_tool' : 'str_replace_editor',\n ...(options?.max_characters !== undefined && { max_characters: options.max_characters }),\n };\n}\n\n/**\n * Creates a bash tool configuration.\n *\n * The bash tool enables Claude to execute shell commands.\n * Sessions persist within the conversation.\n *\n * Token overhead: ~245 tokens per tool definition.\n *\n * @returns A bash tool configuration object\n *\n * @example\n * ```typescript\n * const bash = bashTool();\n * ```\n */\nexport function bashTool(): AnthropicBashTool {\n return {\n type: 'bash_20250124',\n name: 'bash',\n };\n}\n\n/**\n * Creates a code execution tool configuration.\n *\n * The code execution tool enables Claude to write and execute\n * Python/Bash code in a secure sandboxed container.\n *\n * Requires beta header: `code-execution-2025-08-25` (automatically injected).\n *\n * Pricing:\n * - Free tier: 1,550 hours/month per organization\n * - Additional: $0.05 per hour, per container\n *\n * @returns A code execution tool configuration object\n *\n * @example\n * ```typescript\n * const codeExec = codeExecutionTool();\n * ```\n */\nexport function codeExecutionTool(): AnthropicCodeExecutionTool {\n return {\n type: 'code_execution_20250825',\n name: 'code_execution',\n };\n}\n\n/**\n * Creates a tool search tool configuration.\n *\n * The tool search tool enables Claude to search through large\n * tool catalogs (up to 10,000 tools) using regex or natural language.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20` (automatically injected).\n *\n * @param options - Optional mode selection\n * @returns A tool search tool configuration object\n *\n * @example\n * ```typescript\n * // Regex-based search (default)\n * const search = toolSearchTool();\n *\n * // Natural language (BM25) search\n * const nlSearch = toolSearchTool({ mode: 'bm25' });\n * ```\n */\nexport function toolSearchTool(options?: {\n /** Search mode: 'regex' for pattern matching, 'bm25' for natural language */\n mode?: 'regex' | 'bm25';\n}): AnthropicToolSearchTool {\n const mode = options?.mode ?? 'regex';\n return {\n type: mode === 'regex' ? 'tool_search_tool_regex_20251119' : 'tool_search_tool_bm25_20251119',\n name: mode === 'regex' ? 'tool_search_tool_regex' : 'tool_search_tool_bm25',\n };\n}\n\n/**\n * Namespace object containing all Anthropic tool helper constructors.\n *\n * Provides a convenient way to create built-in tool configurations.\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * tools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\nexport const tools = {\n /** Creates a web search tool configuration */\n webSearch: webSearchTool,\n /** Creates a computer use tool configuration */\n computer: computerTool,\n /** Creates a text editor tool configuration */\n textEditor: textEditorTool,\n /** Creates a bash tool configuration */\n bash: bashTool,\n /** Creates a code execution tool configuration */\n codeExecution: codeExecutionTool,\n /** Creates a tool search tool configuration */\n toolSearch: toolSearchTool,\n};\n","/**\n * @fileoverview UPP to Anthropic message transformation utilities.\n *\n * This module handles bidirectional conversion between Universal Provider Protocol\n * message formats and Anthropic's native API structures. It supports:\n * - Request transformation (UPP -> Anthropic)\n * - Response transformation (Anthropic -> UPP)\n * - Stream event transformation for real-time responses\n * - Tool call and structured output handling\n */\n\nimport type { LLMRequest, LLMResponse } from '../../types/llm.ts';\nimport type { Message } from '../../types/messages.ts';\nimport { StreamEventType, type StreamEvent } from '../../types/stream.ts';\nimport type { Tool, ToolCall } from '../../types/tool.ts';\nimport type { TokenUsage } from '../../types/turn.ts';\nimport type { ContentBlock, TextBlock, ImageBlock } from '../../types/content.ts';\nimport {\n AssistantMessage,\n isUserMessage,\n isAssistantMessage,\n isToolResultMessage,\n} from '../../types/messages.ts';\nimport { UPPError, ErrorCode, ModalityType } from '../../types/errors.ts';\nimport { generateId } from '../../utils/id.ts';\nimport type {\n AnthropicLLMParams,\n AnthropicRequest,\n AnthropicMessage,\n AnthropicContent,\n AnthropicTool,\n AnthropicResponse,\n AnthropicStreamEvent,\n AnthropicCacheControl,\n AnthropicSystemContent,\n AnthropicOutputFormat,\n} from './types.ts';\n\n/**\n * Transforms a UPP LLM request to Anthropic's native API format.\n *\n * Handles conversion of messages, system prompts, tools, and structured output\n * configuration. Parameters are spread directly to enable pass-through of any\n * Anthropic API fields, even those not explicitly defined in our types.\n *\n * @typeParam TParams - Anthropic-specific parameters extending AnthropicLLMParams\n * @param request - The UPP-formatted LLM request\n * @param modelId - The Anthropic model identifier (e.g., 'claude-sonnet-4-20250514')\n * @param useNativeStructuredOutput - When true, use native `output_format` instead of\n * tool-based fallback for structured outputs. Should be true when the request includes\n * the `structured-outputs-2025-11-13` beta header.\n * @returns An AnthropicRequest ready for the Messages API\n *\n * @example\n * ```typescript\n * // Without native structured outputs (tool fallback)\n * const anthropicRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * params: { max_tokens: 1024 },\n * }, 'claude-sonnet-4-20250514', false);\n *\n * // With native structured outputs (requires beta header)\n * const nativeRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Extract data' }])],\n * config: { apiKey: 'sk-...', headers: { 'anthropic-beta': 'structured-outputs-2025-11-13' } },\n * params: { max_tokens: 1024 },\n * structure: { properties: { name: { type: 'string' } }, required: ['name'] },\n * }, 'claude-sonnet-4-20250514', true);\n * ```\n *\n * @see {@link transformResponse} for the reverse transformation\n */\nexport function transformRequest<TParams extends AnthropicLLMParams>(\n request: LLMRequest<TParams>,\n modelId: string,\n useNativeStructuredOutput = false\n): AnthropicRequest {\n const params = (request.params ?? {}) as AnthropicLLMParams;\n const { tools: builtInTools, ...restParams } = params;\n\n const anthropicRequest: AnthropicRequest = {\n ...restParams,\n model: modelId,\n messages: request.messages.map(transformMessage),\n };\n\n const normalizedSystem = normalizeSystem(request.system);\n if (normalizedSystem !== undefined) {\n anthropicRequest.system = normalizedSystem;\n }\n\n // Collect all tools: user-defined tools + built-in tools\n const allTools: NonNullable<AnthropicRequest['tools']> = [];\n\n if (request.tools && request.tools.length > 0) {\n // Transform function tools into Anthropic format\n allTools.push(...request.tools.map(transformTool));\n }\n\n // Add built-in tools (web_search, computer, text_editor, bash, code_execution, etc.)\n if (builtInTools && builtInTools.length > 0) {\n allTools.push(...builtInTools);\n }\n\n if (allTools.length > 0) {\n anthropicRequest.tools = allTools;\n anthropicRequest.tool_choice = { type: 'auto' };\n }\n\n if (request.structure) {\n if (useNativeStructuredOutput) {\n // Use native structured outputs with output_format parameter\n const outputFormat: AnthropicOutputFormat = {\n type: 'json_schema',\n schema: {\n type: 'object',\n properties: request.structure.properties,\n required: request.structure.required,\n additionalProperties: false,\n },\n };\n anthropicRequest.output_format = outputFormat;\n } else {\n // Fall back to tool-based structured output\n const structuredTool: AnthropicTool = {\n name: 'json_response',\n description: 'Return the response in the specified JSON format. You MUST use this tool to provide your response.',\n input_schema: {\n type: 'object',\n properties: request.structure.properties,\n required: request.structure.required,\n ...(request.structure.additionalProperties !== undefined\n ? { additionalProperties: request.structure.additionalProperties }\n : {}),\n },\n };\n\n anthropicRequest.tools = [...(anthropicRequest.tools ?? []), structuredTool];\n anthropicRequest.tool_choice = { type: 'tool', name: 'json_response' };\n }\n }\n\n return anthropicRequest;\n}\n\n/**\n * Validates and normalizes system prompt input for Anthropic.\n */\nfunction normalizeSystem(\n system: string | unknown[] | undefined\n): string | AnthropicSystemContent[] | undefined {\n if (system === undefined || system === null) return undefined;\n if (typeof system === 'string') return system;\n if (!Array.isArray(system)) {\n throw new UPPError(\n 'System prompt must be a string or an array of text blocks',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n\n const blocks: AnthropicSystemContent[] = [];\n for (const block of system) {\n if (!block || typeof block !== 'object') {\n throw new UPPError(\n 'System prompt array must contain objects with type \"text\"',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n const candidate = block as { type?: unknown; text?: unknown; cache_control?: unknown };\n if (candidate.type !== 'text' || typeof candidate.text !== 'string') {\n throw new UPPError(\n 'Anthropic system blocks must be of type \"text\" with a string text field',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n if (candidate.cache_control !== undefined && !isValidCacheControl(candidate.cache_control)) {\n throw new UPPError(\n 'Invalid cache_control for Anthropic system prompt',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n blocks.push(block as AnthropicSystemContent);\n }\n\n return blocks.length > 0 ? blocks : undefined;\n}\n\nfunction isValidCacheControl(value: unknown): value is AnthropicCacheControl {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as { type?: unknown; ttl?: unknown };\n if (candidate.type !== 'ephemeral') return false;\n if (candidate.ttl !== undefined && candidate.ttl !== '5m' && candidate.ttl !== '1h') {\n return false;\n }\n return true;\n}\n\n/**\n * Filters content blocks to include only those with a valid type property.\n *\n * @param content - Array of content blocks to filter\n * @returns Filtered array containing only blocks with a string type property\n */\nfunction filterValidContent<T extends { type?: string }>(content: T[]): T[] {\n return content.filter((c) => c && typeof c.type === 'string');\n}\n\n/**\n * Extracts cache control configuration from message metadata.\n *\n * @param message - The message to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractCacheControl(message: Message): AnthropicCacheControl | undefined {\n const anthropicMeta = message.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Message to Anthropic's message format.\n *\n * Handles three message types:\n * - UserMessage: Converted with content blocks\n * - AssistantMessage: Includes text and tool_use blocks\n * - ToolResultMessage: Converted to user role with tool_result content\n *\n * Cache control can be specified via message metadata:\n * ```typescript\n * new UserMessage(content, {\n * metadata: { anthropic: { cache_control: { type: \"ephemeral\" } } }\n * })\n * ```\n *\n * @param message - The UPP message to transform\n * @returns An AnthropicMessage with the appropriate role and content\n * @throws Error if the message type is unknown\n */\nfunction transformMessage(message: Message): AnthropicMessage {\n const cacheControl = extractCacheControl(message);\n\n if (isUserMessage(message)) {\n const validContent = filterValidContent(message.content);\n const contentBlocks = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 ? cacheControl : undefined)\n );\n return {\n role: 'user',\n content: contentBlocks,\n };\n }\n\n if (isAssistantMessage(message)) {\n const validContent = filterValidContent(message.content);\n const content: AnthropicContent[] = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 && !message.toolCalls?.length ? cacheControl : undefined)\n );\n\n if (message.toolCalls) {\n for (let i = 0; i < message.toolCalls.length; i++) {\n const call = message.toolCalls[i]!;\n const isLast = i === message.toolCalls.length - 1;\n content.push({\n type: 'tool_use',\n id: call.toolCallId,\n name: call.toolName,\n input: call.arguments,\n ...(isLast && cacheControl ? { cache_control: cacheControl } : {}),\n });\n }\n }\n\n return {\n role: 'assistant',\n content,\n };\n }\n\n if (isToolResultMessage(message)) {\n return {\n role: 'user',\n content: message.results.map((result, index, arr) => ({\n type: 'tool_result' as const,\n tool_use_id: result.toolCallId,\n content:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n is_error: result.isError,\n ...(index === arr.length - 1 && cacheControl ? { cache_control: cacheControl } : {}),\n })),\n };\n }\n\n throw new Error(`Unknown message type: ${message.type}`);\n}\n\n/**\n * Transforms a UPP ContentBlock to Anthropic's content format.\n *\n * Supports text and image content types. Image blocks can be provided\n * as base64, URL, or raw bytes (which are converted to base64).\n *\n * @param block - The UPP content block to transform\n * @param cacheControl - Optional cache control to apply to the block\n * @returns An AnthropicContent object\n * @throws Error if the content type or image source type is unsupported\n */\nfunction transformContentBlock(\n block: ContentBlock,\n cacheControl?: AnthropicCacheControl\n): AnthropicContent {\n switch (block.type) {\n case 'text':\n return {\n type: 'text',\n text: block.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n\n case 'image': {\n const imageBlock = block as ImageBlock;\n if (imageBlock.source.type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: imageBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'url') {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: imageBlock.source.url,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'bytes') {\n const base64 = btoa(\n Array.from(imageBlock.source.data)\n .map((b) => String.fromCharCode(b))\n .join('')\n );\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: base64,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n throw new Error(`Unknown image source type`);\n }\n\n default:\n throw new Error(`Unsupported content type: ${block.type}`);\n }\n}\n\n/**\n * Extracts cache control configuration from tool metadata.\n *\n * @param tool - The tool to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractToolCacheControl(tool: Tool): AnthropicCacheControl | undefined {\n const anthropicMeta = tool.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Tool definition to Anthropic's tool format.\n *\n * Cache control can be specified via tool metadata:\n * ```typescript\n * const tool: Tool = {\n * name: 'search_docs',\n * description: 'Search documentation',\n * parameters: {...},\n * metadata: { anthropic: { cache_control: { type: 'ephemeral' } } },\n * run: async (params) => {...}\n * };\n * ```\n *\n * @param tool - The UPP tool definition\n * @returns An AnthropicTool with the appropriate input schema\n */\nfunction transformTool(tool: Tool): AnthropicTool {\n const cacheControl = extractToolCacheControl(tool);\n\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: 'object',\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n ...(tool.parameters.additionalProperties !== undefined\n ? { additionalProperties: tool.parameters.additionalProperties }\n : {}),\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n}\n\n/**\n * Transforms an Anthropic API response to UPP's LLMResponse format.\n *\n * Extracts text content, tool calls, code execution results, and structured\n * output data from Anthropic's response. Handles both native structured outputs\n * (JSON in text content) and tool-based fallback (json_response tool).\n * Code execution results (stdout) are appended to the text content.\n *\n * @param data - The raw Anthropic API response\n * @param useNativeStructuredOutput - When true, parse text content as JSON for structured\n * data instead of looking for a json_response tool call.\n * @returns A UPP LLMResponse with message, usage, and optional structured data\n *\n * @see {@link transformRequest} for the request transformation\n */\nexport function transformResponse(\n data: AnthropicResponse,\n useNativeStructuredOutput = false\n): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of data.content) {\n if (block.type === 'text') {\n textContent.push({ type: 'text', text: block.text });\n\n // For native structured outputs, parse the text as JSON\n if (useNativeStructuredOutput && structuredData === undefined) {\n try {\n structuredData = JSON.parse(block.text);\n } catch {\n // Not valid JSON - this shouldn't happen with native structured outputs\n // but we handle it gracefully by leaving structuredData undefined\n }\n }\n } else if (block.type === 'tool_use') {\n if (block.name === 'json_response') {\n structuredData = block.input;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: block.input,\n });\n } else if (block.type === 'bash_code_execution_tool_result') {\n // Extract stdout from code execution results and append to text\n if (block.content.type === 'bash_code_execution_result' && block.content.stdout) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.stdout}\\`\\`\\`\\n` });\n }\n } else if (block.type === 'text_editor_code_execution_tool_result') {\n // Extract file content from text editor results\n if (block.content.type === 'text_editor_code_execution_result' && block.content.content) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.content}\\`\\`\\`\\n` });\n }\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: data.id,\n metadata: {\n anthropic: {\n stop_reason: data.stop_reason,\n stop_sequence: data.stop_sequence,\n model: data.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n cacheReadTokens: data.usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: data.usage.cache_creation_input_tokens ?? 0,\n };\n\n return {\n message,\n usage,\n stopReason: data.stop_reason ?? 'end_turn',\n data: structuredData,\n };\n}\n\n/**\n * Mutable state object for accumulating streamed response data.\n *\n * Used during streaming to collect content blocks, token counts, and\n * metadata as events arrive from the Anthropic API.\n */\nexport interface StreamState {\n /** Unique identifier for the message being streamed. */\n messageId: string;\n /** The model that generated this response. */\n model: string;\n /** Accumulated content blocks indexed by their stream position. */\n content: Array<{\n type: string;\n text?: string;\n id?: string;\n name?: string;\n input?: string;\n /** Code execution stdout (for bash_code_execution_tool_result). */\n stdout?: string;\n /** Code execution tool use ID (for result blocks). */\n tool_use_id?: string;\n /** File content (for text_editor_code_execution_tool_result). */\n fileContent?: string;\n }>;\n /** The reason the response ended, if completed. */\n stopReason: string | null;\n /** Number of input tokens consumed. */\n inputTokens: number;\n /** Number of output tokens generated. */\n outputTokens: number;\n /** Number of tokens read from cache (cache hits). */\n cacheReadTokens: number;\n /** Number of tokens written to cache. */\n cacheWriteTokens: number;\n}\n\n/**\n * Creates an initialized StreamState for accumulating streaming responses.\n *\n * @returns A fresh StreamState with empty/default values\n */\nexport function createStreamState(): StreamState {\n return {\n messageId: '',\n model: '',\n content: [],\n stopReason: null,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n}\n\n/**\n * Transforms an Anthropic streaming event to a UPP StreamEvent.\n *\n * Updates the provided state object as a side effect to accumulate\n * response data across multiple events. Returns null for events that\n * don't produce corresponding UPP events (e.g., ping, message_delta).\n *\n * @param event - The Anthropic SSE event to transform\n * @param state - Mutable state object to update with accumulated data\n * @returns A UPP StreamEvent, or null if no event should be emitted\n *\n * @example\n * ```typescript\n * const state = createStreamState();\n * for await (const event of parseSSEStream(response.body)) {\n * const uppEvents = transformStreamEvent(event, state);\n * for (const uppEvent of uppEvents) {\n * yield uppEvent;\n * }\n * }\n * const finalResponse = buildResponseFromState(state);\n * ```\n */\nexport function transformStreamEvent(\n event: AnthropicStreamEvent,\n state: StreamState\n): StreamEvent[] {\n const events: StreamEvent[] = [];\n switch (event.type) {\n case 'message_start':\n state.messageId = event.message.id;\n state.model = event.message.model;\n state.inputTokens = event.message.usage.input_tokens;\n state.cacheReadTokens = event.message.usage.cache_read_input_tokens ?? 0;\n state.cacheWriteTokens = event.message.usage.cache_creation_input_tokens ?? 0;\n events.push({ type: StreamEventType.MessageStart, index: 0, delta: {} });\n break;\n\n case 'content_block_start':\n if (event.content_block.type === 'text') {\n state.content[event.index] = { type: 'text', text: '' };\n } else if (event.content_block.type === 'tool_use') {\n state.content[event.index] = {\n type: 'tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'server_tool_use') {\n state.content[event.index] = {\n type: 'server_tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'bash_code_execution_tool_result') {\n // Handle code execution results - extract stdout for text\n const resultBlock = event.content_block as {\n type: 'bash_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; stdout?: string };\n };\n state.content[event.index] = {\n type: 'bash_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n stdout: resultBlock.content?.stdout ?? '',\n };\n } else if (event.content_block.type === 'text_editor_code_execution_tool_result') {\n // Handle text editor results - extract file content\n const resultBlock = event.content_block as {\n type: 'text_editor_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; content?: string };\n };\n state.content[event.index] = {\n type: 'text_editor_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n fileContent: resultBlock.content?.content ?? '',\n };\n }\n events.push({ type: StreamEventType.ContentBlockStart, index: event.index, delta: {} });\n break;\n\n case 'content_block_delta': {\n const delta = event.delta;\n if (delta.type === 'text_delta') {\n if (state.content[event.index]) {\n state.content[event.index]!.text =\n (state.content[event.index]!.text ?? '') + delta.text;\n }\n events.push({\n type: StreamEventType.TextDelta,\n index: event.index,\n delta: { text: delta.text },\n });\n break;\n }\n if (delta.type === 'input_json_delta') {\n if (state.content[event.index]) {\n state.content[event.index]!.input =\n (state.content[event.index]!.input ?? '') + delta.partial_json;\n }\n events.push({\n type: StreamEventType.ToolCallDelta,\n index: event.index,\n delta: {\n argumentsJson: delta.partial_json,\n toolCallId: state.content[event.index]?.id,\n toolName: state.content[event.index]?.name,\n },\n });\n break;\n }\n if (delta.type === 'thinking_delta') {\n events.push({\n type: StreamEventType.ReasoningDelta,\n index: event.index,\n delta: { text: delta.thinking },\n });\n break;\n }\n break;\n }\n\n case 'content_block_stop':\n events.push({ type: StreamEventType.ContentBlockStop, index: event.index, delta: {} });\n break;\n\n case 'message_delta':\n state.stopReason = event.delta.stop_reason;\n state.outputTokens = event.usage.output_tokens;\n return [];\n\n case 'message_stop':\n events.push({ type: StreamEventType.MessageStop, index: 0, delta: {} });\n break;\n\n case 'ping':\n case 'error':\n return [];\n\n default:\n break;\n }\n\n return events;\n}\n\n/**\n * Builds a complete LLMResponse from accumulated stream state.\n *\n * Call this after all stream events have been processed to construct\n * the final response. Parses accumulated JSON for tool call arguments\n * and extracts structured output data.\n *\n * @param state - The accumulated stream state\n * @param useNativeStructuredOutput - When true, parse text content as JSON for structured\n * data instead of looking for a json_response tool call.\n * @returns A complete UPP LLMResponse\n *\n * @see {@link createStreamState} for initializing state\n * @see {@link transformStreamEvent} for populating state from events\n */\nexport function buildResponseFromState(\n state: StreamState,\n useNativeStructuredOutput = false\n): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of state.content) {\n // Skip undefined blocks (can happen with built-in tool results that aren't tracked)\n if (!block) continue;\n\n if (block.type === 'text' && block.text) {\n textContent.push({ type: 'text', text: block.text });\n\n // For native structured outputs, parse the text as JSON\n if (useNativeStructuredOutput && structuredData === undefined) {\n try {\n structuredData = JSON.parse(block.text);\n } catch {\n // Not valid JSON - this shouldn't happen with native structured outputs\n // but we handle it gracefully by leaving structuredData undefined\n }\n }\n } else if (block.type === 'tool_use' && block.id && block.name) {\n let args: Record<string, unknown> = {};\n if (block.input) {\n try {\n args = JSON.parse(block.input);\n } catch {\n // Invalid JSON - use empty object\n }\n }\n if (block.name === 'json_response') {\n structuredData = args;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: args,\n });\n } else if (block.type === 'bash_code_execution_tool_result' && block.stdout) {\n // Append code execution stdout to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.stdout}\\`\\`\\`\\n` });\n } else if (block.type === 'text_editor_code_execution_tool_result' && block.fileContent) {\n // Append file content to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.fileContent}\\`\\`\\`\\n` });\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const messageId = state.messageId || generateId();\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: messageId,\n metadata: {\n anthropic: {\n stop_reason: state.stopReason,\n model: state.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.inputTokens + state.outputTokens,\n cacheReadTokens: state.cacheReadTokens,\n cacheWriteTokens: state.cacheWriteTokens,\n };\n\n return {\n message,\n usage,\n stopReason: state.stopReason ?? 'end_turn',\n data: structuredData,\n };\n}\n","/**\n * @fileoverview Anthropic LLM handler implementation.\n *\n * This module provides the core LLM handler for Anthropic's Claude models,\n * implementing both synchronous completion and streaming capabilities.\n */\n\nimport type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';\nimport type { StreamEvent } from '../../types/stream.ts';\nimport type { LLMProvider } from '../../types/provider.ts';\nimport { UPPError, ErrorCode, ModalityType } from '../../types/errors.ts';\nimport { resolveApiKey } from '../../http/keys.ts';\nimport { doFetch, doStreamFetch } from '../../http/fetch.ts';\nimport { parseSSEStream } from '../../http/sse.ts';\nimport { normalizeHttpError } from '../../http/errors.ts';\nimport { parseJsonResponse } from '../../http/json.ts';\nimport { toError } from '../../utils/error.ts';\nimport type { AnthropicLLMParams, AnthropicResponse, AnthropicStreamEvent } from './types.ts';\nimport { betas } from './types.ts';\nimport {\n transformRequest,\n transformResponse,\n transformStreamEvent,\n createStreamState,\n buildResponseFromState,\n} from './transform.ts';\nimport type { ProviderConfig } from '../../types/provider.ts';\nimport type { JSONSchema } from '../../types/schema.ts';\n\n/**\n * Checks if native structured outputs should be used.\n *\n * Native structured outputs are enabled when:\n * 1. The request includes a structure schema\n * 2. The beta header 'structured-outputs-2025-11-13' is present\n *\n * @param config - The provider configuration containing headers\n * @param structure - The structured output schema (if any)\n * @returns True if native structured outputs should be used\n */\nfunction shouldUseNativeStructuredOutput(\n config: ProviderConfig,\n structure: JSONSchema | undefined\n): boolean {\n if (!structure) {\n return false;\n }\n\n const betaHeader = config.headers?.['anthropic-beta'];\n if (!betaHeader) {\n return false;\n }\n\n // Beta header can contain multiple comma-separated values\n return betaHeader.includes(betas.structuredOutputs);\n}\n\n/** Base URL for the Anthropic Messages API. */\nconst ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';\n\n/** Default Anthropic API version header value. */\nconst ANTHROPIC_VERSION = '2023-06-01';\n\n/**\n * Capability flags for Anthropic Claude models.\n *\n * Defines what features are supported by the Anthropic provider:\n * - streaming: Real-time token generation via SSE\n * - tools: Function calling / tool use\n * - structuredOutput: JSON schema-constrained responses (via tool forcing)\n * - imageInput: Vision capabilities for image analysis\n */\nconst ANTHROPIC_CAPABILITIES: LLMCapabilities = {\n streaming: true,\n tools: true,\n structuredOutput: true,\n imageInput: true,\n videoInput: false,\n audioInput: false,\n};\n\n/**\n * Creates an Anthropic LLM handler for the Universal Provider Protocol.\n *\n * The handler provides methods to bind specific Claude models and make\n * completion requests. It handles API authentication, request transformation,\n * and response parsing.\n *\n * @returns An LLMHandler configured for Anthropic's Messages API\n *\n * @example\n * ```typescript\n * const handler = createLLMHandler();\n * const model = handler.bind('claude-sonnet-4-20250514');\n *\n * const response = await model.complete({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: process.env.ANTHROPIC_API_KEY },\n * });\n * ```\n */\nexport function createLLMHandler(): LLMHandler<AnthropicLLMParams> {\n let providerRef: LLMProvider<AnthropicLLMParams> | null = null;\n\n return {\n _setProvider(provider: LLMProvider<AnthropicLLMParams>) {\n providerRef = provider;\n },\n\n bind(modelId: string): BoundLLMModel<AnthropicLLMParams> {\n if (!providerRef) {\n throw new UPPError(\n 'Provider reference not set. Handler must be used with createProvider().',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n\n const model: BoundLLMModel<AnthropicLLMParams> = {\n modelId,\n capabilities: ANTHROPIC_CAPABILITIES,\n\n get provider(): LLMProvider<AnthropicLLMParams> {\n return providerRef!;\n },\n\n async complete(request: LLMRequest<AnthropicLLMParams>): Promise<LLMResponse> {\n const apiKey = await resolveApiKey(\n request.config,\n 'ANTHROPIC_API_KEY',\n 'anthropic',\n 'llm'\n );\n\n const useNativeStructuredOutput = shouldUseNativeStructuredOutput(\n request.config,\n request.structure\n );\n const baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId, useNativeStructuredOutput);\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': request.config.apiVersion ?? ANTHROPIC_VERSION,\n };\n\n if (request.config.headers) {\n for (const [key, value] of Object.entries(request.config.headers)) {\n if (value !== undefined) {\n headers[key] = value;\n }\n }\n }\n\n const response = await doFetch(\n baseUrl,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: request.signal,\n },\n request.config,\n 'anthropic',\n 'llm'\n );\n\n const data = await parseJsonResponse<AnthropicResponse>(response, 'anthropic', 'llm');\n return transformResponse(data, useNativeStructuredOutput);\n },\n\n stream(request: LLMRequest<AnthropicLLMParams>): LLMStreamResult {\n const state = createStreamState();\n const useNativeStructuredOutput = shouldUseNativeStructuredOutput(\n request.config,\n request.structure\n );\n let responseResolve: (value: LLMResponse) => void;\n let responseReject: (error: Error) => void;\n\n const responsePromise = new Promise<LLMResponse>((resolve, reject) => {\n responseResolve = resolve;\n responseReject = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<StreamEvent, void, unknown> {\n try {\n const apiKey = await resolveApiKey(\n request.config,\n 'ANTHROPIC_API_KEY',\n 'anthropic',\n 'llm'\n );\n\n const baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId, useNativeStructuredOutput);\n body.stream = true;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': request.config.apiVersion ?? ANTHROPIC_VERSION,\n Accept: 'text/event-stream',\n };\n\n if (request.config.headers) {\n for (const [key, value] of Object.entries(request.config.headers)) {\n if (value !== undefined) {\n headers[key] = value;\n }\n }\n }\n\n const response = await doStreamFetch(\n baseUrl,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: request.signal,\n },\n request.config,\n 'anthropic',\n 'llm'\n );\n\n if (!response.ok) {\n const error = await normalizeHttpError(response, 'anthropic', 'llm');\n responseReject(error);\n throw error;\n }\n\n if (!response.body) {\n const error = new UPPError(\n 'No response body for streaming request',\n ErrorCode.ProviderError,\n 'anthropic',\n ModalityType.LLM\n );\n responseReject(error);\n throw error;\n }\n\n for await (const data of parseSSEStream(response.body)) {\n if (typeof data === 'object' && data !== null && 'type' in data) {\n const event = data as AnthropicStreamEvent;\n\n if (event.type === 'error') {\n const error = new UPPError(\n event.error.message,\n ErrorCode.ProviderError,\n 'anthropic',\n ModalityType.LLM\n );\n responseReject(error);\n throw error;\n }\n\n const uppEvents = transformStreamEvent(event, state);\n for (const uppEvent of uppEvents) {\n yield uppEvent;\n }\n }\n }\n\n responseResolve(buildResponseFromState(state, useNativeStructuredOutput));\n } catch (error) {\n const err = toError(error);\n responseReject(err);\n throw err;\n }\n }\n\n return {\n [Symbol.asyncIterator]() {\n return generateEvents();\n },\n response: responsePromise,\n };\n },\n };\n\n return model;\n },\n };\n}\n","import { createProvider } from '../../core/provider.ts';\nimport { createLLMHandler } from './llm.ts';\nimport type { ProviderConfig } from '../../types/provider.ts';\nimport type { BetaValue } from './types.ts';\n\n/**\n * Options for configuring an Anthropic model reference.\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n *\n * // Enable structured outputs beta\n * const model = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs],\n * });\n *\n * // Enable multiple betas\n * const modelWithBetas = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.interleavedThinking],\n * });\n *\n * // Use string values for new/unlisted betas\n * const modelWithCustomBeta = anthropic('claude-sonnet-4-20250514', {\n * betas: ['new-beta-2025-12-01'],\n * });\n * ```\n */\nexport interface AnthropicModelOptions {\n /**\n * Beta features to enable for this model.\n *\n * Use values from the `betas` export or pass arbitrary strings for new betas.\n * Multiple betas are combined into a comma-separated `anthropic-beta` header.\n */\n betas?: BetaValue[];\n}\n\n/**\n * Creates provider config from Anthropic model options.\n *\n * @param options - The model options containing betas\n * @returns Partial provider config with anthropic-beta header if betas provided\n */\nfunction createProviderConfig(options?: AnthropicModelOptions): Partial<ProviderConfig> | undefined {\n if (!options?.betas || options.betas.length === 0) {\n return undefined;\n }\n\n const betaHeader = options.betas.join(',');\n\n return {\n headers: {\n 'anthropic-beta': betaHeader,\n },\n };\n}\n\n/**\n * Anthropic provider for the Universal Provider Protocol.\n *\n * Provides access to Claude language models through a unified interface.\n * Supports LLM modality with streaming, tool use, structured output,\n * and image input capabilities.\n *\n * @param modelId - The model identifier (e.g., 'claude-sonnet-4-20250514')\n * @param options - Optional configuration including beta features\n * @returns A model reference for use with `llm()`\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n * import { llm } from 'provider-protocol';\n *\n * // Basic usage\n * const model = llm({ model: anthropic('claude-sonnet-4-20250514') });\n *\n * // With structured outputs beta\n * const modelWithBetas = llm({\n * model: anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs],\n * }),\n * structure: { properties: { name: { type: 'string' } } },\n * });\n *\n * // With multiple betas\n * const advancedModel = llm({\n * model: anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.tokenEfficientTools],\n * }),\n * });\n * ```\n *\n * @see {@link betas} for available beta features\n * @see {@link AnthropicLLMParams} for provider-specific parameters\n */\nexport const anthropic = createProvider<AnthropicModelOptions>({\n name: 'anthropic',\n version: '1.0.0',\n handlers: {\n llm: createLLMHandler(),\n },\n createModelReference: (modelId, options, provider) => {\n const providerConfig = createProviderConfig(options);\n return {\n modelId,\n provider,\n options,\n ...(providerConfig && { providerConfig }),\n };\n },\n});\n\nexport { tools, betas } from './types.ts';\nexport type { BetaKey, BetaValue } from './types.ts';\nexport type {\n AnthropicLLMParams,\n AnthropicHeaders,\n AnthropicBuiltInTool,\n AnthropicWebSearchTool,\n AnthropicComputerTool,\n AnthropicTextEditorTool,\n AnthropicBashTool,\n AnthropicCodeExecutionTool,\n AnthropicToolSearchTool,\n AnthropicUserLocation,\n AnthropicOutputFormat,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCO,IAAM,QAAQ;AAAA;AAAA;AAAA,EAGnB,mBAAmB;AAAA;AAAA;AAAA,EAInB,qBAAqB;AAAA;AAAA,EAErB,iBAAiB;AAAA;AAAA,EAEjB,QAAQ;AAAA;AAAA;AAAA,EAIR,mBAAmB;AAAA;AAAA,EAEnB,aAAa;AAAA;AAAA,EAEb,iBAAiB;AAAA;AAAA;AAAA,EAIjB,mBAAmB;AAAA;AAAA,EAEnB,YAAY;AAAA;AAAA,EAEZ,WAAW;AAAA;AAAA;AAAA,EAIX,qBAAqB;AAAA;AAAA,EAErB,0BAA0B;AAAA;AAAA;AAAA,EAI1B,eAAe;AAAA;AAAA;AAAA,EAIf,iBAAiB;AAAA;AAAA;AAAA,EAIjB,UAAU;AAAA;AAAA,EA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AAa;AACpD,UAAM,iBAAiB,qBAAqB,OAAO;AACnD,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAI,kBAAkB,EAAE,eAAe;AAAA,IACzC;AAAA,EACF;AACF,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/providers/anthropic/types.ts","../../src/providers/anthropic/transform.ts","../../src/providers/anthropic/llm.ts","../../src/providers/anthropic/index.ts"],"sourcesContent":["/**\n * @fileoverview Anthropic API type definitions.\n *\n * Contains TypeScript interfaces for Anthropic's Messages API request/response\n * structures, streaming events, and provider-specific parameters.\n */\n\n// ============================================\n// Beta Headers\n// ============================================\n\n/**\n * Known Anthropic beta header values.\n *\n * Beta features are enabled by passing these values in the `betas` config option\n * or via the `anthropic-beta` HTTP header. Multiple betas can be enabled simultaneously.\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n *\n * // Using the betas config option (recommended)\n * const provider = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.interleavedThinking],\n * });\n *\n * // Or use string values directly for new/unlisted betas\n * const provider = anthropic('claude-sonnet-4-20250514', {\n * betas: ['new-beta-2025-12-01'],\n * });\n * ```\n */\nexport const betas = {\n // Structured Outputs\n /** Guaranteed JSON schema conformance for responses. Available for Claude Sonnet 4.5+. */\n structuredOutputs: 'structured-outputs-2025-11-13',\n\n // Extended Thinking / Reasoning\n /** Enables Claude to think between tool calls in Claude 4 models. */\n interleavedThinking: 'interleaved-thinking-2025-05-14',\n /** Developer mode for full thinking output visibility. */\n devFullThinking: 'dev-full-thinking-2025-05-14',\n /** Effort parameter for Claude Opus 4.5 - controls response thoroughness vs efficiency. */\n effort: 'effort-2025-11-24',\n\n // Computer Use\n /** Legacy computer use tool (Claude 3.x models). */\n computerUseLegacy: 'computer-use-2024-10-22',\n /** Computer use tool for Claude 4 models (mouse, keyboard, screenshots). */\n computerUse: 'computer-use-2025-01-24',\n /** Computer use tool for Claude Opus 4.5 with additional commands. */\n computerUseOpus: 'computer-use-2025-11-24',\n\n // Extended Output / Context\n /** Enables up to 8,192 output tokens from Claude Sonnet 3.5. */\n maxTokens35Sonnet: 'max-tokens-3-5-sonnet-2024-07-15',\n /** Enables 128K token output length. */\n output128k: 'output-128k-2025-02-19',\n /** Enables 1 million token context window for Claude Sonnet 4. */\n context1m: 'context-1m-2025-08-07',\n\n // Token Efficiency\n /** Reduces output token consumption by up to 70% for tool calls. */\n tokenEfficientTools: 'token-efficient-tools-2025-02-19',\n /** Streams tool use parameters without buffering/JSON validation. */\n fineGrainedToolStreaming: 'fine-grained-tool-streaming-2025-05-14',\n\n // Code Execution\n /** Code execution tool for running Python/Bash in secure sandbox. */\n codeExecution: 'code-execution-2025-08-25',\n\n // Advanced Tool Use\n /** Advanced tool use: Tool Search, Programmatic Tool Calling, Tool Use Examples. */\n advancedToolUse: 'advanced-tool-use-2025-11-20',\n\n // Files & Documents\n /** Files API for uploading and managing files. */\n filesApi: 'files-api-2025-04-14',\n /** PDF document support. */\n pdfs: 'pdfs-2024-09-25',\n\n // MCP (Model Context Protocol)\n /** MCP connector to connect to remote MCP servers. */\n mcpClient: 'mcp-client-2025-04-04',\n /** Updated MCP client. */\n mcpClientLatest: 'mcp-client-2025-11-20',\n\n // Caching\n /** Prompt caching for reduced latency and costs. Now works automatically with cache_control. */\n promptCaching: 'prompt-caching-2024-07-31',\n /** Enables 1-hour cache TTL (vs default 5-minute). */\n extendedCacheTtl: 'extended-cache-ttl-2025-04-11',\n\n // Context Management\n /** Automatic tool call clearing for context management. */\n contextManagement: 'context-management-2025-06-27',\n /** Handling for when model context window is exceeded. */\n modelContextWindowExceeded: 'model-context-window-exceeded-2025-08-26',\n\n // Message Batches (generally available but may still need header)\n /** Message Batches API for async processing at 50% cost. */\n messageBatches: 'message-batches-2024-09-24',\n\n // Token Counting (generally available)\n /** Token counting endpoint. */\n tokenCounting: 'token-counting-2024-11-01',\n\n // Skills\n /** Agent Skills for specialized tasks (PowerPoint, Excel, Word, PDF). */\n skills: 'skills-2025-10-02',\n} as const;\n\n/** Type representing any valid beta key from the betas object. */\nexport type BetaKey = keyof typeof betas;\n\n/** Type representing a beta value (either a known constant or arbitrary string). */\nexport type BetaValue = (typeof betas)[BetaKey] | string;\n\n/**\n * Provider-specific parameters for Anthropic Claude models.\n *\n * These parameters are passed through to the Anthropic Messages API and\n * control model behavior such as sampling, token limits, and extended thinking.\n *\n * @example\n * ```typescript\n * const params: AnthropicLLMParams = {\n * max_tokens: 4096,\n * temperature: 0.7,\n * thinking: { type: 'enabled', budget_tokens: 10000 },\n * };\n * ```\n */\nexport interface AnthropicLLMParams {\n /** Maximum number of tokens to generate. Defaults to model maximum if not specified. */\n max_tokens?: number;\n\n /** Sampling temperature from 0.0 (deterministic) to 1.0 (maximum randomness). */\n temperature?: number;\n\n /** Nucleus sampling threshold. Only tokens with cumulative probability <= top_p are considered. */\n top_p?: number;\n\n /** Top-k sampling. Only the k most likely tokens are considered at each step. */\n top_k?: number;\n\n /** Custom sequences that will cause the model to stop generating. */\n stop_sequences?: string[];\n\n /** Request metadata for tracking and analytics. */\n metadata?: {\n /** Unique identifier for the end user making the request. */\n user_id?: string;\n };\n\n /** Extended thinking configuration for complex reasoning tasks. */\n thinking?: {\n /** Must be 'enabled' to activate extended thinking. */\n type: 'enabled';\n /** Token budget for the thinking process. */\n budget_tokens: number;\n };\n\n /**\n * Service tier selection for capacity routing.\n * - `auto`: Automatically select based on availability (default)\n * - `standard_only`: Only use standard capacity, never priority\n */\n service_tier?: 'auto' | 'standard_only';\n\n /**\n * Built-in tools for server-side execution.\n *\n * Use the tool helper constructors from the `tools` namespace:\n * - `tools.webSearch()` - Web search capability\n * - `tools.computer()` - Computer use (mouse, keyboard, screenshots)\n * - `tools.textEditor()` - File viewing and editing\n * - `tools.bash()` - Shell command execution\n * - `tools.codeExecution()` - Sandboxed Python/Bash execution\n * - `tools.toolSearch()` - Dynamic tool catalog search\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * tools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\n tools?: AnthropicBuiltInTool[];\n\n /**\n * Container ID for code execution tool reuse.\n * Pass the container ID from a previous response to reuse the same environment.\n */\n container?: string;\n}\n\n/**\n * System content block for structured system prompts with caching support.\n *\n * When system is provided as an array, each block can have cache_control.\n */\nexport interface AnthropicSystemContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Request body structure for Anthropic's Messages API.\n *\n * This interface represents the full request payload sent to the\n * `/v1/messages` endpoint.\n */\n/**\n * Native structured output format configuration.\n *\n * When provided, Claude's response will be constrained to match the\n * specified JSON schema. Requires the beta header `structured-outputs-2025-11-13`.\n *\n * @example\n * ```typescript\n * const outputFormat: AnthropicOutputFormat = {\n * type: 'json_schema',\n * schema: {\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'integer' },\n * },\n * required: ['name', 'age'],\n * additionalProperties: false,\n * },\n * };\n * ```\n */\nexport interface AnthropicOutputFormat {\n /** Output format type - currently only 'json_schema' is supported. */\n type: 'json_schema';\n /** JSON Schema defining the expected response structure. */\n schema: {\n /** Schema type (always 'object' for structured outputs). */\n type: 'object';\n /** Property definitions for each field. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n /** Must be false for structured outputs. */\n additionalProperties?: false;\n };\n}\n\nexport interface AnthropicRequest {\n /** The model identifier (e.g., 'claude-sonnet-4-20250514'). */\n model: string;\n /** Maximum tokens to generate in the response. */\n max_tokens?: number;\n /** Conversation messages in Anthropic's format. */\n messages: AnthropicMessage[];\n /** System prompt - string for simple prompts, array for caching support. */\n system?: string | AnthropicSystemContent[];\n /** Sampling temperature. */\n temperature?: number;\n /** Nucleus sampling threshold. */\n top_p?: number;\n /** Top-k sampling value. */\n top_k?: number;\n /** Stop sequences to halt generation. */\n stop_sequences?: string[];\n /** Enable Server-Sent Events streaming. */\n stream?: boolean;\n /** Available tools for function calling and built-in tools. */\n tools?: (AnthropicTool | AnthropicBuiltInTool)[];\n /** Tool selection strategy. */\n tool_choice?: { type: 'auto' | 'any' | 'tool'; name?: string };\n /** Request metadata for tracking. */\n metadata?: { user_id?: string };\n /** Extended thinking configuration. */\n thinking?: { type: 'enabled'; budget_tokens: number };\n /** Capacity tier selection. */\n service_tier?: 'auto' | 'standard_only';\n /**\n * Native structured output format.\n *\n * Constrains Claude's response to match the specified JSON schema.\n * Requires the beta header `structured-outputs-2025-11-13`.\n *\n * @see {@link AnthropicOutputFormat}\n */\n output_format?: AnthropicOutputFormat;\n}\n\n/**\n * A single message in an Anthropic conversation.\n *\n * Messages alternate between 'user' and 'assistant' roles. Content can be\n * a simple string or an array of typed content blocks.\n */\nexport interface AnthropicMessage {\n /** The role of the message sender. */\n role: 'user' | 'assistant';\n /** Message content as string or structured content blocks. */\n content: AnthropicContent[] | string;\n}\n\n/**\n * Union type for all Anthropic content block types.\n *\n * Used in both request messages and response content arrays.\n */\nexport type AnthropicContent =\n | AnthropicTextContent\n | AnthropicImageContent\n | AnthropicToolUseContent\n | AnthropicToolResultContent\n | AnthropicThinkingContent;\n\n/**\n * Cache control configuration for prompt caching.\n *\n * Marks content blocks for caching to reduce costs and latency\n * on subsequent requests with the same prefix.\n *\n * @example\n * ```typescript\n * const cacheControl: AnthropicCacheControl = {\n * type: 'ephemeral',\n * ttl: '1h' // Optional: extend to 1-hour cache\n * };\n * ```\n */\nexport interface AnthropicCacheControl {\n /** Cache type - only 'ephemeral' is supported */\n type: 'ephemeral';\n /** Optional TTL: '5m' (default) or '1h' for extended caching */\n ttl?: '5m' | '1h';\n}\n\n/**\n * Plain text content block.\n */\nexport interface AnthropicTextContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Image content block for vision capabilities.\n *\n * Images can be provided as base64-encoded data or via URL.\n */\nexport interface AnthropicImageContent {\n /** Content type discriminator. */\n type: 'image';\n /** Image source configuration. */\n source: {\n /** How the image data is provided. */\n type: 'base64' | 'url';\n /** MIME type of the image (required for base64). */\n media_type?: string;\n /** Base64-encoded image data. */\n data?: string;\n /** URL to fetch the image from. */\n url?: string;\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool use content block representing a function call by the assistant.\n *\n * Appears in assistant messages when the model invokes a tool.\n */\nexport interface AnthropicToolUseContent {\n /** Content type discriminator. */\n type: 'tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the tool being called. */\n name: string;\n /** Arguments passed to the tool as a JSON object. */\n input: Record<string, unknown>;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool result content block providing the output of a tool call.\n *\n * Sent in user messages to provide results for previous tool_use blocks.\n */\nexport interface AnthropicToolResultContent {\n /** Content type discriminator. */\n type: 'tool_result';\n /** ID of the tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The result content (string or structured blocks). */\n content: string | AnthropicContent[];\n /** Whether the tool execution resulted in an error. */\n is_error?: boolean;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool definition for Anthropic's function calling feature.\n *\n * Defines a callable function that the model can invoke during generation.\n */\nexport interface AnthropicTool {\n /** Unique name for the tool. */\n name: string;\n /** Description of what the tool does and when to use it. */\n description: string;\n /** JSON Schema defining the expected input parameters. */\n input_schema: {\n /** Schema type (always 'object' for tool inputs). */\n type: 'object';\n /** Property definitions for each parameter. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Complete response from the Anthropic Messages API.\n *\n * Returned from non-streaming requests and contains the full\n * generated content along with usage statistics.\n */\nexport interface AnthropicResponse {\n /** Unique identifier for this response. */\n id: string;\n /** Response type (always 'message'). */\n type: 'message';\n /** Role of the responder (always 'assistant'). */\n role: 'assistant';\n /** Generated content blocks. */\n content: AnthropicResponseContent[];\n /** Model that generated this response. */\n model: string;\n /**\n * Reason the model stopped generating.\n * - `end_turn`: Natural completion\n * - `max_tokens`: Hit token limit\n * - `stop_sequence`: Hit a stop sequence\n * - `tool_use`: Model wants to use a tool\n * - `pause_turn`: Paused for extended thinking\n * - `refusal`: Model refused to respond\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal' | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n /** Token usage statistics. */\n usage: {\n /** Tokens consumed by the input. */\n input_tokens: number;\n /** Tokens generated in the output. */\n output_tokens: number;\n /** Tokens used to create cache entries. */\n cache_creation_input_tokens?: number;\n /** Tokens read from cache. */\n cache_read_input_tokens?: number;\n };\n}\n\n/**\n * Union type for content blocks that can appear in API responses.\n *\n * Includes text, tool use, thinking blocks, and code execution results.\n */\nexport type AnthropicResponseContent =\n | AnthropicTextContent\n | AnthropicToolUseContent\n | AnthropicThinkingContent\n | AnthropicServerToolUseContent\n | AnthropicBashCodeExecutionToolResultContent\n | AnthropicTextEditorCodeExecutionToolResultContent;\n\n/**\n * Thinking content block from extended thinking feature.\n *\n * Contains the model's internal reasoning process when thinking is enabled.\n */\nexport interface AnthropicThinkingContent {\n /** Content type discriminator. */\n type: 'thinking';\n /** The model's thinking/reasoning text. */\n thinking: string;\n /** Cryptographic signature for thinking verification. */\n signature?: string;\n}\n\n/**\n * Server tool use content block for built-in tools like code execution.\n *\n * Appears when Claude invokes a server-side tool.\n */\nexport interface AnthropicServerToolUseContent {\n /** Content type discriminator. */\n type: 'server_tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the server tool being called (e.g., 'bash_code_execution', 'text_editor_code_execution'). */\n name: string;\n /** Arguments passed to the tool. */\n input: Record<string, unknown>;\n}\n\n/**\n * Result from bash code execution tool.\n *\n * Contains stdout, stderr, and return code from command execution.\n */\nexport interface AnthropicBashCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'bash_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The execution result. */\n content: {\n /** Result type discriminator. */\n type: 'bash_code_execution_result';\n /** Standard output from the command. */\n stdout: string;\n /** Standard error from the command. */\n stderr: string;\n /** Exit code (0 for success). */\n return_code: number;\n /** File IDs for any files created during execution. */\n content?: Array<{ file_id: string }>;\n } | {\n /** Error result type. */\n type: 'bash_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Result from text editor code execution tool.\n *\n * Contains file operation results.\n */\nexport interface AnthropicTextEditorCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'text_editor_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The operation result. */\n content: {\n /** Result type discriminator. */\n type: 'text_editor_code_execution_result';\n /** File type (for view operations). */\n file_type?: string;\n /** File content (for view operations). */\n content?: string;\n /** Number of lines returned (for view operations). */\n numLines?: number;\n /** Starting line number (for view operations). */\n startLine?: number;\n /** Total lines in file (for view operations). */\n totalLines?: number;\n /** Whether this was a file update (for create operations). */\n is_file_update?: boolean;\n /** Old start line (for edit operations). */\n oldStart?: number;\n /** Old line count (for edit operations). */\n oldLines?: number;\n /** New start line (for edit operations). */\n newStart?: number;\n /** New line count (for edit operations). */\n newLines?: number;\n /** Diff lines (for edit operations). */\n lines?: string[];\n } | {\n /** Error result type. */\n type: 'text_editor_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Union type for all Server-Sent Events from Anthropic's streaming API.\n *\n * Events are received in a specific order:\n * 1. message_start - Initial message metadata\n * 2. content_block_start - Beginning of each content block\n * 3. content_block_delta - Incremental content updates (multiple)\n * 4. content_block_stop - End of each content block\n * 5. message_delta - Final usage and stop reason\n * 6. message_stop - Stream complete\n */\nexport type AnthropicStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent;\n\n/**\n * Initial event containing message metadata and partial response.\n */\nexport interface AnthropicMessageStartEvent {\n /** Event type discriminator. */\n type: 'message_start';\n /** Partial response with id, model, and input token count. */\n message: AnthropicResponse;\n}\n\n/**\n * Signals the start of a new content block.\n */\nexport interface AnthropicContentBlockStartEvent {\n /** Event type discriminator. */\n type: 'content_block_start';\n /** Zero-based index of this content block. */\n index: number;\n /** Initial content block data (may be empty for streaming). */\n content_block: AnthropicResponseContent;\n}\n\n/**\n * Incremental update to a content block's content.\n *\n * Multiple delta events are sent as content is generated.\n */\nexport interface AnthropicContentBlockDeltaEvent {\n /** Event type discriminator. */\n type: 'content_block_delta';\n /** Index of the content block being updated. */\n index: number;\n /** The incremental content update. */\n delta:\n | { type: 'text_delta'; text: string }\n | { type: 'thinking_delta'; thinking: string }\n | { type: 'signature_delta'; signature: string }\n | { type: 'input_json_delta'; partial_json: string };\n}\n\n/**\n * Signals the end of a content block.\n */\nexport interface AnthropicContentBlockStopEvent {\n /** Event type discriminator. */\n type: 'content_block_stop';\n /** Index of the completed content block. */\n index: number;\n}\n\n/**\n * Final message update with stop reason and output token count.\n */\nexport interface AnthropicMessageDeltaEvent {\n /** Event type discriminator. */\n type: 'message_delta';\n /** Final message metadata. */\n delta: {\n /** Why the model stopped generating. */\n stop_reason: string | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n };\n /** Final usage statistics. */\n usage: {\n /** Total output tokens generated. */\n output_tokens: number;\n };\n}\n\n/**\n * Terminal event indicating the stream is complete.\n */\nexport interface AnthropicMessageStopEvent {\n /** Event type discriminator. */\n type: 'message_stop';\n}\n\n/**\n * Keep-alive event sent periodically during long operations.\n */\nexport interface AnthropicPingEvent {\n /** Event type discriminator. */\n type: 'ping';\n}\n\n/**\n * Error event indicating a problem during streaming.\n */\nexport interface AnthropicErrorEvent {\n /** Event type discriminator. */\n type: 'error';\n /** Error details. */\n error: {\n /** Error type identifier. */\n type: string;\n /** Human-readable error message. */\n message: string;\n };\n}\n\n/**\n * Anthropic-specific HTTP headers for API requests.\n *\n * @example\n * ```typescript\n * const headers: AnthropicHeaders = {\n * 'anthropic-beta': 'extended-cache-ttl-2025-04-11',\n * };\n * ```\n */\nexport interface AnthropicHeaders {\n /**\n * Beta features header.\n *\n * Comma-separated list of beta feature flags:\n * - `extended-cache-ttl-2025-04-11` - Enable 1-hour cache TTL\n * - `token-efficient-tools-2025-02-19` - Token-efficient tool encoding\n * - `computer-use-2025-01-24` - Computer use tool (Claude 4 models)\n * - `computer-use-2025-11-24` - Computer use tool (Claude Opus 4.5)\n * - `code-execution-2025-08-25` - Code execution tool\n * - `advanced-tool-use-2025-11-20` - Tool search tool\n */\n 'anthropic-beta'?: string;\n [key: string]: string | undefined;\n}\n\n// ============================================\n// Built-in Tools\n// ============================================\n\n/**\n * User location for web search context.\n *\n * Used to localize web search results based on the user's approximate location.\n */\nexport interface AnthropicUserLocation {\n /** Location type - must be 'approximate' */\n type: 'approximate';\n /** City name */\n city?: string;\n /** Region/state name */\n region?: string;\n /** ISO 3166-1 alpha-2 country code (e.g., \"US\") */\n country?: string;\n /** IANA timezone (e.g., \"America/New_York\") */\n timezone?: string;\n}\n\n/**\n * Web search tool for real-time web information retrieval.\n *\n * Enables Claude to search the web for up-to-date information.\n * No beta header required - this is a GA feature.\n *\n * @example\n * ```typescript\n * const tool: AnthropicWebSearchTool = {\n * type: 'web_search_20250305',\n * name: 'web_search',\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * };\n * ```\n */\nexport interface AnthropicWebSearchTool {\n /** Tool type identifier */\n type: 'web_search_20250305';\n /** Tool name - must be 'web_search' */\n name: 'web_search';\n /** Maximum searches per request (default: unlimited) */\n max_uses?: number;\n /** Whitelist domains (mutually exclusive with blocked_domains) */\n allowed_domains?: string[];\n /** Blacklist domains (mutually exclusive with allowed_domains) */\n blocked_domains?: string[];\n /** User location for localized results */\n user_location?: AnthropicUserLocation;\n}\n\n/**\n * Computer use tool for desktop automation.\n *\n * Enables Claude to interact with computer interfaces through\n * mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header:\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other Claude 4 models\n *\n * @example\n * ```typescript\n * const tool: AnthropicComputerTool = {\n * type: 'computer_20250124',\n * name: 'computer',\n * display_width_px: 1920,\n * display_height_px: 1080,\n * };\n * ```\n */\nexport interface AnthropicComputerTool {\n /** Tool type identifier (version-specific) */\n type: 'computer_20251124' | 'computer_20250124';\n /** Tool name - must be 'computer' */\n name: 'computer';\n /** Display width in pixels */\n display_width_px: number;\n /** Display height in pixels */\n display_height_px: number;\n /** X11 display number (optional) */\n display_number?: number;\n /** Enable zoom action (Opus 4.5 only with 20251124 version) */\n enable_zoom?: boolean;\n}\n\n/**\n * Text editor tool for file viewing and editing.\n *\n * Enables Claude to view, create, and edit files with\n * commands like view, str_replace, create, and insert.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicTextEditorTool = {\n * type: 'text_editor_20250728',\n * name: 'str_replace_based_edit_tool',\n * max_characters: 10000,\n * };\n * ```\n */\nexport interface AnthropicTextEditorTool {\n /** Tool type identifier (version-specific) */\n type: 'text_editor_20250728' | 'text_editor_20250124';\n /** Tool name (version-specific) */\n name: 'str_replace_based_edit_tool' | 'str_replace_editor';\n /** Max characters for view truncation (20250728+ only) */\n max_characters?: number;\n}\n\n/**\n * Bash tool for shell command execution.\n *\n * Enables Claude to execute bash commands in a shell session.\n * The session persists within the conversation.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicBashTool = {\n * type: 'bash_20250124',\n * name: 'bash',\n * };\n * ```\n */\nexport interface AnthropicBashTool {\n /** Tool type identifier */\n type: 'bash_20250124';\n /** Tool name - must be 'bash' */\n name: 'bash';\n}\n\n/**\n * Code execution tool for sandboxed Python/Bash execution.\n *\n * Enables Claude to write and execute code in a secure container\n * with pre-installed data science libraries.\n *\n * Requires beta header: `code-execution-2025-08-25`\n *\n * @example\n * ```typescript\n * const tool: AnthropicCodeExecutionTool = {\n * type: 'code_execution_20250825',\n * name: 'code_execution',\n * };\n * ```\n */\nexport interface AnthropicCodeExecutionTool {\n /** Tool type identifier */\n type: 'code_execution_20250825';\n /** Tool name - must be 'code_execution' */\n name: 'code_execution';\n}\n\n/**\n * Tool search tool for dynamic tool discovery.\n *\n * Enables Claude to search through large tool catalogs\n * using regex or natural language (BM25) queries.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20`\n *\n * @example\n * ```typescript\n * const tool: AnthropicToolSearchTool = {\n * type: 'tool_search_tool_regex_20251119',\n * name: 'tool_search_tool_regex',\n * };\n * ```\n */\nexport interface AnthropicToolSearchTool {\n /** Tool type identifier (regex or BM25 variant) */\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_bm25_20251119';\n /** Tool name (must match type variant) */\n name: 'tool_search_tool_regex' | 'tool_search_tool_bm25';\n}\n\n/**\n * Union type for all Anthropic built-in tools.\n *\n * Built-in tools run server-side and have special handling\n * different from user-defined function tools.\n */\nexport type AnthropicBuiltInTool =\n | AnthropicWebSearchTool\n | AnthropicComputerTool\n | AnthropicTextEditorTool\n | AnthropicBashTool\n | AnthropicCodeExecutionTool\n | AnthropicToolSearchTool;\n\n/**\n * Combined tool type for API requests (user-defined or built-in).\n */\nexport type AnthropicToolUnion = AnthropicTool | AnthropicBuiltInTool;\n\n// ============================================\n// Tool Helper Constructors\n// ============================================\n\n/**\n * Creates a web search tool configuration.\n *\n * The web search tool enables Claude to search the web for up-to-date information.\n * Pricing: $10 per 1,000 searches plus standard token costs.\n *\n * @param options - Optional configuration for search behavior\n * @returns A web search tool configuration object\n *\n * @example\n * ```typescript\n * // Basic web search\n * const search = webSearchTool();\n *\n * // With configuration\n * const searchWithOptions = webSearchTool({\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * user_location: {\n * type: 'approximate',\n * city: 'San Francisco',\n * country: 'US',\n * },\n * });\n * ```\n */\nexport function webSearchTool(options?: {\n max_uses?: number;\n allowed_domains?: string[];\n blocked_domains?: string[];\n user_location?: AnthropicUserLocation;\n}): AnthropicWebSearchTool {\n return {\n type: 'web_search_20250305',\n name: 'web_search',\n ...options,\n };\n}\n\n/**\n * Creates a computer use tool configuration.\n *\n * The computer tool enables Claude to interact with computer interfaces\n * through mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header (automatically injected when using this tool):\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other models\n *\n * @param options - Display configuration and optional settings\n * @returns A computer tool configuration object\n *\n * @example\n * ```typescript\n * const computer = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * });\n *\n * // For Opus 4.5 with zoom support\n * const computerOpus = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * version: '20251124',\n * enable_zoom: true,\n * });\n * ```\n */\nexport function computerTool(options: {\n display_width_px: number;\n display_height_px: number;\n display_number?: number;\n enable_zoom?: boolean;\n /** Use '20251124' for Claude Opus 4.5, '20250124' for other models */\n version?: '20251124' | '20250124';\n}): AnthropicComputerTool {\n const { version = '20250124', ...rest } = options;\n return {\n type: version === '20251124' ? 'computer_20251124' : 'computer_20250124',\n name: 'computer',\n ...rest,\n };\n}\n\n/**\n * Creates a text editor tool configuration.\n *\n * The text editor tool enables Claude to view, create, and edit files\n * using commands like view, str_replace, create, and insert.\n *\n * Token overhead: ~700 tokens per tool definition.\n *\n * @param options - Optional configuration\n * @returns A text editor tool configuration object\n *\n * @example\n * ```typescript\n * const editor = textEditorTool();\n *\n * // With max characters for view truncation\n * const editorWithLimit = textEditorTool({\n * max_characters: 10000,\n * });\n * ```\n */\nexport function textEditorTool(options?: {\n max_characters?: number;\n /** Use '20250728' for Claude 4, '20250124' for Claude 3.7 */\n version?: '20250728' | '20250124';\n}): AnthropicTextEditorTool {\n const version = options?.version ?? '20250728';\n return {\n type: version === '20250728' ? 'text_editor_20250728' : 'text_editor_20250124',\n name: version === '20250728' ? 'str_replace_based_edit_tool' : 'str_replace_editor',\n ...(options?.max_characters !== undefined && { max_characters: options.max_characters }),\n };\n}\n\n/**\n * Creates a bash tool configuration.\n *\n * The bash tool enables Claude to execute shell commands.\n * Sessions persist within the conversation.\n *\n * Token overhead: ~245 tokens per tool definition.\n *\n * @returns A bash tool configuration object\n *\n * @example\n * ```typescript\n * const bash = bashTool();\n * ```\n */\nexport function bashTool(): AnthropicBashTool {\n return {\n type: 'bash_20250124',\n name: 'bash',\n };\n}\n\n/**\n * Creates a code execution tool configuration.\n *\n * The code execution tool enables Claude to write and execute\n * Python/Bash code in a secure sandboxed container.\n *\n * Requires beta header: `code-execution-2025-08-25` (automatically injected).\n *\n * Pricing:\n * - Free tier: 1,550 hours/month per organization\n * - Additional: $0.05 per hour, per container\n *\n * @returns A code execution tool configuration object\n *\n * @example\n * ```typescript\n * const codeExec = codeExecutionTool();\n * ```\n */\nexport function codeExecutionTool(): AnthropicCodeExecutionTool {\n return {\n type: 'code_execution_20250825',\n name: 'code_execution',\n };\n}\n\n/**\n * Creates a tool search tool configuration.\n *\n * The tool search tool enables Claude to search through large\n * tool catalogs (up to 10,000 tools) using regex or natural language.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20` (automatically injected).\n *\n * @param options - Optional mode selection\n * @returns A tool search tool configuration object\n *\n * @example\n * ```typescript\n * // Regex-based search (default)\n * const search = toolSearchTool();\n *\n * // Natural language (BM25) search\n * const nlSearch = toolSearchTool({ mode: 'bm25' });\n * ```\n */\nexport function toolSearchTool(options?: {\n /** Search mode: 'regex' for pattern matching, 'bm25' for natural language */\n mode?: 'regex' | 'bm25';\n}): AnthropicToolSearchTool {\n const mode = options?.mode ?? 'regex';\n return {\n type: mode === 'regex' ? 'tool_search_tool_regex_20251119' : 'tool_search_tool_bm25_20251119',\n name: mode === 'regex' ? 'tool_search_tool_regex' : 'tool_search_tool_bm25',\n };\n}\n\n/**\n * Namespace object containing all Anthropic tool helper constructors.\n *\n * Provides a convenient way to create built-in tool configurations.\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * tools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\nexport const tools = {\n /** Creates a web search tool configuration */\n webSearch: webSearchTool,\n /** Creates a computer use tool configuration */\n computer: computerTool,\n /** Creates a text editor tool configuration */\n textEditor: textEditorTool,\n /** Creates a bash tool configuration */\n bash: bashTool,\n /** Creates a code execution tool configuration */\n codeExecution: codeExecutionTool,\n /** Creates a tool search tool configuration */\n toolSearch: toolSearchTool,\n};\n","/**\n * @fileoverview UPP to Anthropic message transformation utilities.\n *\n * This module handles bidirectional conversion between Universal Provider Protocol\n * message formats and Anthropic's native API structures. It supports:\n * - Request transformation (UPP -> Anthropic)\n * - Response transformation (Anthropic -> UPP)\n * - Stream event transformation for real-time responses\n * - Tool call and structured output handling\n */\n\nimport type { LLMRequest, LLMResponse } from '../../types/llm.ts';\nimport type { Message } from '../../types/messages.ts';\nimport { StreamEventType, type StreamEvent } from '../../types/stream.ts';\nimport type { Tool, ToolCall } from '../../types/tool.ts';\nimport type { TokenUsage } from '../../types/turn.ts';\nimport type { ContentBlock, TextBlock, ImageBlock, ReasoningBlock, AssistantContent } from '../../types/content.ts';\nimport {\n AssistantMessage,\n isUserMessage,\n isAssistantMessage,\n isToolResultMessage,\n} from '../../types/messages.ts';\nimport { UPPError, ErrorCode, ModalityType } from '../../types/errors.ts';\nimport { generateId } from '../../utils/id.ts';\nimport type {\n AnthropicLLMParams,\n AnthropicRequest,\n AnthropicMessage,\n AnthropicContent,\n AnthropicTool,\n AnthropicResponse,\n AnthropicStreamEvent,\n AnthropicCacheControl,\n AnthropicSystemContent,\n AnthropicOutputFormat,\n} from './types.ts';\n\n/**\n * Transforms a UPP LLM request to Anthropic's native API format.\n *\n * Handles conversion of messages, system prompts, tools, and structured output\n * configuration. Parameters are spread directly to enable pass-through of any\n * Anthropic API fields, even those not explicitly defined in our types.\n *\n * @typeParam TParams - Anthropic-specific parameters extending AnthropicLLMParams\n * @param request - The UPP-formatted LLM request\n * @param modelId - The Anthropic model identifier (e.g., 'claude-sonnet-4-20250514')\n * @param useNativeStructuredOutput - When true, use native `output_format` instead of\n * tool-based fallback for structured outputs. Should be true when the request includes\n * the `structured-outputs-2025-11-13` beta header.\n * @returns An AnthropicRequest ready for the Messages API\n *\n * @example\n * ```typescript\n * // Without native structured outputs (tool fallback)\n * const anthropicRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * params: { max_tokens: 1024 },\n * }, 'claude-sonnet-4-20250514', false);\n *\n * // With native structured outputs (requires beta header)\n * const nativeRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Extract data' }])],\n * config: { apiKey: 'sk-...', headers: { 'anthropic-beta': 'structured-outputs-2025-11-13' } },\n * params: { max_tokens: 1024 },\n * structure: { properties: { name: { type: 'string' } }, required: ['name'] },\n * }, 'claude-sonnet-4-20250514', true);\n * ```\n *\n * @see {@link transformResponse} for the reverse transformation\n */\nexport function transformRequest<TParams extends AnthropicLLMParams>(\n request: LLMRequest<TParams>,\n modelId: string,\n useNativeStructuredOutput = false\n): AnthropicRequest {\n const params = (request.params ?? {}) as AnthropicLLMParams;\n const { tools: builtInTools, ...restParams } = params;\n\n const anthropicRequest: AnthropicRequest = {\n ...restParams,\n model: modelId,\n messages: request.messages.map(transformMessage),\n };\n\n const normalizedSystem = normalizeSystem(request.system);\n if (normalizedSystem !== undefined) {\n anthropicRequest.system = normalizedSystem;\n }\n\n // Collect all tools: user-defined tools + built-in tools\n const allTools: NonNullable<AnthropicRequest['tools']> = [];\n\n if (request.tools && request.tools.length > 0) {\n // Transform function tools into Anthropic format\n allTools.push(...request.tools.map(transformTool));\n }\n\n // Add built-in tools (web_search, computer, text_editor, bash, code_execution, etc.)\n if (builtInTools && builtInTools.length > 0) {\n allTools.push(...builtInTools);\n }\n\n if (allTools.length > 0) {\n anthropicRequest.tools = allTools;\n anthropicRequest.tool_choice = { type: 'auto' };\n }\n\n if (request.structure) {\n if (useNativeStructuredOutput) {\n // Use native structured outputs with output_format parameter\n const outputFormat: AnthropicOutputFormat = {\n type: 'json_schema',\n schema: {\n type: 'object',\n properties: request.structure.properties,\n required: request.structure.required,\n additionalProperties: false,\n },\n };\n anthropicRequest.output_format = outputFormat;\n } else {\n // Fall back to tool-based structured output\n const structuredTool: AnthropicTool = {\n name: 'json_response',\n description: 'Return the response in the specified JSON format. You MUST use this tool to provide your response.',\n input_schema: {\n type: 'object',\n properties: request.structure.properties,\n required: request.structure.required,\n ...(request.structure.additionalProperties !== undefined\n ? { additionalProperties: request.structure.additionalProperties }\n : {}),\n },\n };\n\n anthropicRequest.tools = [...(anthropicRequest.tools ?? []), structuredTool];\n anthropicRequest.tool_choice = { type: 'tool', name: 'json_response' };\n }\n }\n\n return anthropicRequest;\n}\n\n/**\n * Validates and normalizes system prompt input for Anthropic.\n */\nfunction normalizeSystem(\n system: string | unknown[] | undefined\n): string | AnthropicSystemContent[] | undefined {\n if (system === undefined || system === null) return undefined;\n if (typeof system === 'string') return system;\n if (!Array.isArray(system)) {\n throw new UPPError(\n 'System prompt must be a string or an array of text blocks',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n\n const blocks: AnthropicSystemContent[] = [];\n for (const block of system) {\n if (!block || typeof block !== 'object') {\n throw new UPPError(\n 'System prompt array must contain objects with type \"text\"',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n const candidate = block as { type?: unknown; text?: unknown; cache_control?: unknown };\n if (candidate.type !== 'text' || typeof candidate.text !== 'string') {\n throw new UPPError(\n 'Anthropic system blocks must be of type \"text\" with a string text field',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n if (candidate.cache_control !== undefined && !isValidCacheControl(candidate.cache_control)) {\n throw new UPPError(\n 'Invalid cache_control for Anthropic system prompt',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n blocks.push(block as AnthropicSystemContent);\n }\n\n return blocks.length > 0 ? blocks : undefined;\n}\n\nfunction isValidCacheControl(value: unknown): value is AnthropicCacheControl {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as { type?: unknown; ttl?: unknown };\n if (candidate.type !== 'ephemeral') return false;\n if (candidate.ttl !== undefined && candidate.ttl !== '5m' && candidate.ttl !== '1h') {\n return false;\n }\n return true;\n}\n\n/**\n * Filters content blocks to include only those with a valid type property.\n *\n * @param content - Array of content blocks to filter\n * @returns Filtered array containing only blocks with a string type property\n */\nfunction filterValidContent<T extends { type?: string }>(content: T[]): T[] {\n return content.filter((c) => c && typeof c.type === 'string');\n}\n\n/**\n * Extracts cache control configuration from message metadata.\n *\n * @param message - The message to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractCacheControl(message: Message): AnthropicCacheControl | undefined {\n const anthropicMeta = message.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Message to Anthropic's message format.\n *\n * Handles three message types:\n * - UserMessage: Converted with content blocks\n * - AssistantMessage: Includes text and tool_use blocks\n * - ToolResultMessage: Converted to user role with tool_result content\n *\n * Cache control can be specified via message metadata:\n * ```typescript\n * new UserMessage(content, {\n * metadata: { anthropic: { cache_control: { type: \"ephemeral\" } } }\n * })\n * ```\n *\n * @param message - The UPP message to transform\n * @returns An AnthropicMessage with the appropriate role and content\n * @throws Error if the message type is unknown\n */\nfunction transformMessage(message: Message): AnthropicMessage {\n const cacheControl = extractCacheControl(message);\n\n if (isUserMessage(message)) {\n const validContent = filterValidContent(message.content);\n const contentBlocks = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 ? cacheControl : undefined)\n );\n return {\n role: 'user',\n content: contentBlocks,\n };\n }\n\n if (isAssistantMessage(message)) {\n const validContent = filterValidContent(message.content);\n const content: AnthropicContent[] = [];\n\n // Get thinking signatures from metadata if present\n const anthropicMeta = message.metadata?.anthropic as\n | { thinkingSignature?: string; thinkingSignatures?: Array<string | null> }\n | undefined;\n const thinkingSignatures = anthropicMeta?.thinkingSignatures;\n let reasoningIndex = 0;\n\n for (let i = 0; i < validContent.length; i++) {\n const block = validContent[i]!;\n const isLastNonToolBlock = i === validContent.length - 1 && !message.toolCalls?.length;\n\n if (block.type === 'reasoning') {\n // Convert reasoning blocks to thinking blocks for Anthropic\n const signatureFromArray = thinkingSignatures?.[reasoningIndex];\n const signature = Array.isArray(thinkingSignatures)\n ? (typeof signatureFromArray === 'string' ? signatureFromArray : undefined)\n : anthropicMeta?.thinkingSignature;\n reasoningIndex += 1;\n content.push({\n type: 'thinking',\n thinking: (block as ReasoningBlock).text,\n ...(signature ? { signature } : {}),\n });\n } else {\n content.push(transformContentBlock(block, isLastNonToolBlock ? cacheControl : undefined));\n }\n }\n\n if (message.toolCalls) {\n for (let i = 0; i < message.toolCalls.length; i++) {\n const call = message.toolCalls[i]!;\n const isLast = i === message.toolCalls.length - 1;\n content.push({\n type: 'tool_use',\n id: call.toolCallId,\n name: call.toolName,\n input: call.arguments,\n ...(isLast && cacheControl ? { cache_control: cacheControl } : {}),\n });\n }\n }\n\n return {\n role: 'assistant',\n content,\n };\n }\n\n if (isToolResultMessage(message)) {\n return {\n role: 'user',\n content: message.results.map((result, index, arr) => ({\n type: 'tool_result' as const,\n tool_use_id: result.toolCallId,\n content:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n is_error: result.isError,\n ...(index === arr.length - 1 && cacheControl ? { cache_control: cacheControl } : {}),\n })),\n };\n }\n\n throw new Error(`Unknown message type: ${message.type}`);\n}\n\n/**\n * Transforms a UPP ContentBlock to Anthropic's content format.\n *\n * Supports text and image content types. Image blocks can be provided\n * as base64, URL, or raw bytes (which are converted to base64).\n *\n * @param block - The UPP content block to transform\n * @param cacheControl - Optional cache control to apply to the block\n * @returns An AnthropicContent object\n * @throws Error if the content type or image source type is unsupported\n */\nfunction transformContentBlock(\n block: ContentBlock,\n cacheControl?: AnthropicCacheControl\n): AnthropicContent {\n switch (block.type) {\n case 'text':\n return {\n type: 'text',\n text: block.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n\n case 'image': {\n const imageBlock = block as ImageBlock;\n if (imageBlock.source.type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: imageBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'url') {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: imageBlock.source.url,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'bytes') {\n const base64 = btoa(\n Array.from(imageBlock.source.data)\n .map((b) => String.fromCharCode(b))\n .join('')\n );\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: base64,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n throw new Error(`Unknown image source type`);\n }\n\n default:\n throw new Error(`Unsupported content type: ${block.type}`);\n }\n}\n\n/**\n * Extracts cache control configuration from tool metadata.\n *\n * @param tool - The tool to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractToolCacheControl(tool: Tool): AnthropicCacheControl | undefined {\n const anthropicMeta = tool.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Tool definition to Anthropic's tool format.\n *\n * Cache control can be specified via tool metadata:\n * ```typescript\n * const tool: Tool = {\n * name: 'search_docs',\n * description: 'Search documentation',\n * parameters: {...},\n * metadata: { anthropic: { cache_control: { type: 'ephemeral' } } },\n * run: async (params) => {...}\n * };\n * ```\n *\n * @param tool - The UPP tool definition\n * @returns An AnthropicTool with the appropriate input schema\n */\nfunction transformTool(tool: Tool): AnthropicTool {\n const cacheControl = extractToolCacheControl(tool);\n\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: 'object',\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n ...(tool.parameters.additionalProperties !== undefined\n ? { additionalProperties: tool.parameters.additionalProperties }\n : {}),\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n}\n\n/**\n * Transforms an Anthropic API response to UPP's LLMResponse format.\n *\n * Extracts text content, tool calls, code execution results, and structured\n * output data from Anthropic's response. Handles both native structured outputs\n * (JSON in text content) and tool-based fallback (json_response tool).\n * Code execution results (stdout) are appended to the text content.\n *\n * @param data - The raw Anthropic API response\n * @param useNativeStructuredOutput - When true, parse text content as JSON for structured\n * data instead of looking for a json_response tool call.\n * @returns A UPP LLMResponse with message, usage, and optional structured data\n *\n * @see {@link transformRequest} for the request transformation\n */\nexport function transformResponse(\n data: AnthropicResponse,\n useNativeStructuredOutput = false\n): LLMResponse {\n const reasoningContent: ReasoningBlock[] = [];\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n let thinkingSignature: string | undefined;\n const thinkingSignatures: Array<string | null> = [];\n\n for (const block of data.content) {\n if (block.type === 'thinking') {\n reasoningContent.push({ type: 'reasoning', text: block.thinking });\n // Capture signature for multi-turn context\n if (block.signature) {\n thinkingSignature = block.signature;\n }\n thinkingSignatures.push(block.signature ?? null);\n } else if (block.type === 'text') {\n textContent.push({ type: 'text', text: block.text });\n\n // For native structured outputs, parse the text as JSON\n if (useNativeStructuredOutput && structuredData === undefined) {\n try {\n structuredData = JSON.parse(block.text);\n } catch {\n // Not valid JSON - this shouldn't happen with native structured outputs\n // but we handle it gracefully by leaving structuredData undefined\n }\n }\n } else if (block.type === 'tool_use') {\n if (block.name === 'json_response') {\n structuredData = block.input;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: block.input,\n });\n } else if (block.type === 'bash_code_execution_tool_result') {\n // Extract stdout from code execution results and append to text\n if (block.content.type === 'bash_code_execution_result' && block.content.stdout) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.stdout}\\`\\`\\`\\n` });\n }\n } else if (block.type === 'text_editor_code_execution_tool_result') {\n // Extract file content from text editor results\n if (block.content.type === 'text_editor_code_execution_result' && block.content.content) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.content}\\`\\`\\`\\n` });\n }\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n // Combine reasoning before text content\n const allContent: AssistantContent[] = [...reasoningContent, ...textContent];\n\n const hasThinkingSignatures = thinkingSignatures.some((signature) => signature);\n\n const message = new AssistantMessage(\n allContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: data.id,\n metadata: {\n anthropic: {\n stop_reason: data.stop_reason,\n stop_sequence: data.stop_sequence,\n model: data.model,\n thinkingSignature,\n ...(hasThinkingSignatures ? { thinkingSignatures } : {}),\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n cacheReadTokens: data.usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: data.usage.cache_creation_input_tokens ?? 0,\n };\n\n return {\n message,\n usage,\n stopReason: data.stop_reason ?? 'end_turn',\n data: structuredData,\n };\n}\n\n/**\n * Mutable state object for accumulating streamed response data.\n *\n * Used during streaming to collect content blocks, token counts, and\n * metadata as events arrive from the Anthropic API.\n */\nexport interface StreamState {\n /** Unique identifier for the message being streamed. */\n messageId: string;\n /** The model that generated this response. */\n model: string;\n /** Accumulated content blocks indexed by their stream position. */\n content: Array<{\n type: string;\n text?: string;\n thinking?: string;\n /** Cryptographic signature for thinking blocks (required for multi-turn with tools). */\n signature?: string;\n id?: string;\n name?: string;\n input?: string;\n /** Code execution stdout (for bash_code_execution_tool_result). */\n stdout?: string;\n /** Code execution tool use ID (for result blocks). */\n tool_use_id?: string;\n /** File content (for text_editor_code_execution_tool_result). */\n fileContent?: string;\n }>;\n /** The reason the response ended, if completed. */\n stopReason: string | null;\n /** Number of input tokens consumed. */\n inputTokens: number;\n /** Number of output tokens generated. */\n outputTokens: number;\n /** Number of tokens read from cache (cache hits). */\n cacheReadTokens: number;\n /** Number of tokens written to cache. */\n cacheWriteTokens: number;\n}\n\n/**\n * Creates an initialized StreamState for accumulating streaming responses.\n *\n * @returns A fresh StreamState with empty/default values\n */\nexport function createStreamState(): StreamState {\n return {\n messageId: '',\n model: '',\n content: [],\n stopReason: null,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n}\n\n/**\n * Transforms an Anthropic streaming event to a UPP StreamEvent.\n *\n * Updates the provided state object as a side effect to accumulate\n * response data across multiple events. Returns null for events that\n * don't produce corresponding UPP events (e.g., ping, message_delta).\n *\n * @param event - The Anthropic SSE event to transform\n * @param state - Mutable state object to update with accumulated data\n * @returns A UPP StreamEvent, or null if no event should be emitted\n *\n * @example\n * ```typescript\n * const state = createStreamState();\n * for await (const event of parseSSEStream(response.body)) {\n * const uppEvents = transformStreamEvent(event, state);\n * for (const uppEvent of uppEvents) {\n * yield uppEvent;\n * }\n * }\n * const finalResponse = buildResponseFromState(state);\n * ```\n */\nexport function transformStreamEvent(\n event: AnthropicStreamEvent,\n state: StreamState\n): StreamEvent[] {\n const events: StreamEvent[] = [];\n switch (event.type) {\n case 'message_start':\n state.messageId = event.message.id;\n state.model = event.message.model;\n state.inputTokens = event.message.usage.input_tokens;\n state.cacheReadTokens = event.message.usage.cache_read_input_tokens ?? 0;\n state.cacheWriteTokens = event.message.usage.cache_creation_input_tokens ?? 0;\n events.push({ type: StreamEventType.MessageStart, index: 0, delta: {} });\n break;\n\n case 'content_block_start':\n if (event.content_block.type === 'thinking') {\n state.content[event.index] = { type: 'thinking', thinking: '' };\n } else if (event.content_block.type === 'text') {\n state.content[event.index] = { type: 'text', text: '' };\n } else if (event.content_block.type === 'tool_use') {\n state.content[event.index] = {\n type: 'tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'server_tool_use') {\n state.content[event.index] = {\n type: 'server_tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'bash_code_execution_tool_result') {\n // Handle code execution results - extract stdout for text\n const resultBlock = event.content_block as {\n type: 'bash_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; stdout?: string };\n };\n state.content[event.index] = {\n type: 'bash_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n stdout: resultBlock.content?.stdout ?? '',\n };\n } else if (event.content_block.type === 'text_editor_code_execution_tool_result') {\n // Handle text editor results - extract file content\n const resultBlock = event.content_block as {\n type: 'text_editor_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; content?: string };\n };\n state.content[event.index] = {\n type: 'text_editor_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n fileContent: resultBlock.content?.content ?? '',\n };\n }\n events.push({ type: StreamEventType.ContentBlockStart, index: event.index, delta: {} });\n break;\n\n case 'content_block_delta': {\n const delta = event.delta;\n if (delta.type === 'text_delta') {\n if (state.content[event.index]) {\n state.content[event.index]!.text =\n (state.content[event.index]!.text ?? '') + delta.text;\n }\n events.push({\n type: StreamEventType.TextDelta,\n index: event.index,\n delta: { text: delta.text },\n });\n break;\n }\n if (delta.type === 'input_json_delta') {\n if (state.content[event.index]) {\n state.content[event.index]!.input =\n (state.content[event.index]!.input ?? '') + delta.partial_json;\n }\n events.push({\n type: StreamEventType.ToolCallDelta,\n index: event.index,\n delta: {\n argumentsJson: delta.partial_json,\n toolCallId: state.content[event.index]?.id,\n toolName: state.content[event.index]?.name,\n },\n });\n break;\n }\n if (delta.type === 'thinking_delta') {\n if (state.content[event.index]) {\n state.content[event.index]!.thinking =\n (state.content[event.index]!.thinking ?? '') + delta.thinking;\n }\n events.push({\n type: StreamEventType.ReasoningDelta,\n index: event.index,\n delta: { text: delta.thinking },\n });\n break;\n }\n if (delta.type === 'signature_delta') {\n // Capture thinking block signature for multi-turn context verification\n if (state.content[event.index]) {\n state.content[event.index]!.signature = delta.signature;\n }\n break;\n }\n break;\n }\n\n case 'content_block_stop':\n events.push({ type: StreamEventType.ContentBlockStop, index: event.index, delta: {} });\n break;\n\n case 'message_delta':\n state.stopReason = event.delta.stop_reason;\n state.outputTokens = event.usage.output_tokens;\n return [];\n\n case 'message_stop':\n events.push({ type: StreamEventType.MessageStop, index: 0, delta: {} });\n break;\n\n case 'ping':\n case 'error':\n return [];\n\n default:\n break;\n }\n\n return events;\n}\n\n/**\n * Builds a complete LLMResponse from accumulated stream state.\n *\n * Call this after all stream events have been processed to construct\n * the final response. Parses accumulated JSON for tool call arguments\n * and extracts structured output data.\n *\n * @param state - The accumulated stream state\n * @param useNativeStructuredOutput - When true, parse text content as JSON for structured\n * data instead of looking for a json_response tool call.\n * @returns A complete UPP LLMResponse\n *\n * @see {@link createStreamState} for initializing state\n * @see {@link transformStreamEvent} for populating state from events\n */\nexport function buildResponseFromState(\n state: StreamState,\n useNativeStructuredOutput = false\n): LLMResponse {\n const reasoningContent: ReasoningBlock[] = [];\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n let thinkingSignature: string | undefined;\n const thinkingSignatures: Array<string | null> = [];\n\n for (const block of state.content) {\n // Skip undefined blocks (can happen with built-in tool results that aren't tracked)\n if (!block) continue;\n\n if (block.type === 'thinking' && block.thinking) {\n reasoningContent.push({ type: 'reasoning', text: block.thinking });\n // Capture signature for multi-turn context (last signature wins for interleaved thinking)\n if (block.signature) {\n thinkingSignature = block.signature;\n }\n thinkingSignatures.push(block.signature ?? null);\n } else if (block.type === 'text' && block.text) {\n textContent.push({ type: 'text', text: block.text });\n\n // For native structured outputs, parse the text as JSON\n if (useNativeStructuredOutput && structuredData === undefined) {\n try {\n structuredData = JSON.parse(block.text);\n } catch {\n // Not valid JSON - this shouldn't happen with native structured outputs\n // but we handle it gracefully by leaving structuredData undefined\n }\n }\n } else if (block.type === 'tool_use' && block.id && block.name) {\n let args: Record<string, unknown> = {};\n if (block.input) {\n try {\n args = JSON.parse(block.input);\n } catch {\n // Invalid JSON - use empty object\n }\n }\n if (block.name === 'json_response') {\n structuredData = args;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: args,\n });\n } else if (block.type === 'bash_code_execution_tool_result' && block.stdout) {\n // Append code execution stdout to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.stdout}\\`\\`\\`\\n` });\n } else if (block.type === 'text_editor_code_execution_tool_result' && block.fileContent) {\n // Append file content to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.fileContent}\\`\\`\\`\\n` });\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n // Combine reasoning before text content\n const allContent: AssistantContent[] = [...reasoningContent, ...textContent];\n\n const hasThinkingSignatures = thinkingSignatures.some((signature) => signature);\n const messageId = state.messageId || generateId();\n const message = new AssistantMessage(\n allContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: messageId,\n metadata: {\n anthropic: {\n stop_reason: state.stopReason,\n model: state.model,\n thinkingSignature,\n ...(hasThinkingSignatures ? { thinkingSignatures } : {}),\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.inputTokens + state.outputTokens,\n cacheReadTokens: state.cacheReadTokens,\n cacheWriteTokens: state.cacheWriteTokens,\n };\n\n return {\n message,\n usage,\n stopReason: state.stopReason ?? 'end_turn',\n data: structuredData,\n };\n}\n","/**\n * @fileoverview Anthropic LLM handler implementation.\n *\n * This module provides the core LLM handler for Anthropic's Claude models,\n * implementing both synchronous completion and streaming capabilities.\n */\n\nimport type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';\nimport type { StreamEvent } from '../../types/stream.ts';\nimport type { LLMProvider } from '../../types/provider.ts';\nimport { UPPError, ErrorCode, ModalityType } from '../../types/errors.ts';\nimport { resolveApiKey } from '../../http/keys.ts';\nimport { doFetch, doStreamFetch } from '../../http/fetch.ts';\nimport { parseSSEStream } from '../../http/sse.ts';\nimport { normalizeHttpError } from '../../http/errors.ts';\nimport { parseJsonResponse } from '../../http/json.ts';\nimport { toError } from '../../utils/error.ts';\nimport type { AnthropicLLMParams, AnthropicResponse, AnthropicStreamEvent } from './types.ts';\nimport { betas } from './types.ts';\nimport {\n transformRequest,\n transformResponse,\n transformStreamEvent,\n createStreamState,\n buildResponseFromState,\n} from './transform.ts';\nimport type { ProviderConfig } from '../../types/provider.ts';\nimport type { JSONSchema } from '../../types/schema.ts';\n\n/**\n * Checks if native structured outputs should be used.\n *\n * Native structured outputs are enabled when:\n * 1. The request includes a structure schema\n * 2. The beta header 'structured-outputs-2025-11-13' is present\n *\n * @param config - The provider configuration containing headers\n * @param structure - The structured output schema (if any)\n * @returns True if native structured outputs should be used\n */\nfunction shouldUseNativeStructuredOutput(\n config: ProviderConfig,\n structure: JSONSchema | undefined\n): boolean {\n if (!structure) {\n return false;\n }\n\n const betaHeader = config.headers?.['anthropic-beta'];\n if (!betaHeader) {\n return false;\n }\n\n // Beta header can contain multiple comma-separated values\n return betaHeader.includes(betas.structuredOutputs);\n}\n\n/** Base URL for the Anthropic Messages API. */\nconst ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';\n\n/** Default Anthropic API version header value. */\nconst ANTHROPIC_VERSION = '2023-06-01';\n\n/**\n * Capability flags for Anthropic Claude models.\n *\n * Defines what features are supported by the Anthropic provider:\n * - streaming: Real-time token generation via SSE\n * - tools: Function calling / tool use\n * - structuredOutput: JSON schema-constrained responses (via tool forcing)\n * - imageInput: Vision capabilities for image analysis\n */\nconst ANTHROPIC_CAPABILITIES: LLMCapabilities = {\n streaming: true,\n tools: true,\n structuredOutput: true,\n imageInput: true,\n videoInput: false,\n audioInput: false,\n};\n\n/**\n * Creates an Anthropic LLM handler for the Universal Provider Protocol.\n *\n * The handler provides methods to bind specific Claude models and make\n * completion requests. It handles API authentication, request transformation,\n * and response parsing.\n *\n * @returns An LLMHandler configured for Anthropic's Messages API\n *\n * @example\n * ```typescript\n * const handler = createLLMHandler();\n * const model = handler.bind('claude-sonnet-4-20250514');\n *\n * const response = await model.complete({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: process.env.ANTHROPIC_API_KEY },\n * });\n * ```\n */\nexport function createLLMHandler(): LLMHandler<AnthropicLLMParams> {\n let providerRef: LLMProvider<AnthropicLLMParams> | null = null;\n\n return {\n _setProvider(provider: LLMProvider<AnthropicLLMParams>) {\n providerRef = provider;\n },\n\n bind(modelId: string): BoundLLMModel<AnthropicLLMParams> {\n if (!providerRef) {\n throw new UPPError(\n 'Provider reference not set. Handler must be used with createProvider().',\n ErrorCode.InvalidRequest,\n 'anthropic',\n ModalityType.LLM\n );\n }\n\n const model: BoundLLMModel<AnthropicLLMParams> = {\n modelId,\n capabilities: ANTHROPIC_CAPABILITIES,\n\n get provider(): LLMProvider<AnthropicLLMParams> {\n return providerRef!;\n },\n\n async complete(request: LLMRequest<AnthropicLLMParams>): Promise<LLMResponse> {\n const apiKey = await resolveApiKey(\n request.config,\n 'ANTHROPIC_API_KEY',\n 'anthropic',\n 'llm'\n );\n\n const useNativeStructuredOutput = shouldUseNativeStructuredOutput(\n request.config,\n request.structure\n );\n const baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId, useNativeStructuredOutput);\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': request.config.apiVersion ?? ANTHROPIC_VERSION,\n };\n\n if (request.config.headers) {\n for (const [key, value] of Object.entries(request.config.headers)) {\n if (value !== undefined) {\n headers[key] = value;\n }\n }\n }\n\n const response = await doFetch(\n baseUrl,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: request.signal,\n },\n request.config,\n 'anthropic',\n 'llm'\n );\n\n const data = await parseJsonResponse<AnthropicResponse>(response, 'anthropic', 'llm');\n return transformResponse(data, useNativeStructuredOutput);\n },\n\n stream(request: LLMRequest<AnthropicLLMParams>): LLMStreamResult {\n const state = createStreamState();\n const useNativeStructuredOutput = shouldUseNativeStructuredOutput(\n request.config,\n request.structure\n );\n let responseResolve: (value: LLMResponse) => void;\n let responseReject: (error: Error) => void;\n\n const responsePromise = new Promise<LLMResponse>((resolve, reject) => {\n responseResolve = resolve;\n responseReject = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<StreamEvent, void, unknown> {\n try {\n const apiKey = await resolveApiKey(\n request.config,\n 'ANTHROPIC_API_KEY',\n 'anthropic',\n 'llm'\n );\n\n const baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId, useNativeStructuredOutput);\n body.stream = true;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': request.config.apiVersion ?? ANTHROPIC_VERSION,\n Accept: 'text/event-stream',\n };\n\n if (request.config.headers) {\n for (const [key, value] of Object.entries(request.config.headers)) {\n if (value !== undefined) {\n headers[key] = value;\n }\n }\n }\n\n const response = await doStreamFetch(\n baseUrl,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: request.signal,\n },\n request.config,\n 'anthropic',\n 'llm'\n );\n\n if (!response.ok) {\n const error = await normalizeHttpError(response, 'anthropic', 'llm');\n responseReject(error);\n throw error;\n }\n\n if (!response.body) {\n const error = new UPPError(\n 'No response body for streaming request',\n ErrorCode.ProviderError,\n 'anthropic',\n ModalityType.LLM\n );\n responseReject(error);\n throw error;\n }\n\n for await (const data of parseSSEStream(response.body)) {\n if (typeof data === 'object' && data !== null && 'type' in data) {\n const event = data as AnthropicStreamEvent;\n\n if (event.type === 'error') {\n const error = new UPPError(\n event.error.message,\n ErrorCode.ProviderError,\n 'anthropic',\n ModalityType.LLM\n );\n responseReject(error);\n throw error;\n }\n\n const uppEvents = transformStreamEvent(event, state);\n for (const uppEvent of uppEvents) {\n yield uppEvent;\n }\n }\n }\n\n responseResolve(buildResponseFromState(state, useNativeStructuredOutput));\n } catch (error) {\n const err = toError(error);\n responseReject(err);\n throw err;\n }\n }\n\n return {\n [Symbol.asyncIterator]() {\n return generateEvents();\n },\n response: responsePromise,\n };\n },\n };\n\n return model;\n },\n };\n}\n","import { createProvider } from '../../core/provider.ts';\nimport { createLLMHandler } from './llm.ts';\nimport type { ProviderConfig } from '../../types/provider.ts';\nimport type { BetaValue } from './types.ts';\n\n/**\n * Options for configuring an Anthropic model reference.\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n *\n * // Enable structured outputs beta\n * const model = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs],\n * });\n *\n * // Enable multiple betas\n * const modelWithBetas = anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.interleavedThinking],\n * });\n *\n * // Use string values for new/unlisted betas\n * const modelWithCustomBeta = anthropic('claude-sonnet-4-20250514', {\n * betas: ['new-beta-2025-12-01'],\n * });\n * ```\n */\nexport interface AnthropicModelOptions {\n /**\n * Beta features to enable for this model.\n *\n * Use values from the `betas` export or pass arbitrary strings for new betas.\n * Multiple betas are combined into a comma-separated `anthropic-beta` header.\n */\n betas?: BetaValue[];\n}\n\n/**\n * Creates provider config from Anthropic model options.\n *\n * @param options - The model options containing betas\n * @returns Partial provider config with anthropic-beta header if betas provided\n */\nfunction createProviderConfig(options?: AnthropicModelOptions): Partial<ProviderConfig> | undefined {\n if (!options?.betas || options.betas.length === 0) {\n return undefined;\n }\n\n const betaHeader = options.betas.join(',');\n\n return {\n headers: {\n 'anthropic-beta': betaHeader,\n },\n };\n}\n\n/**\n * Anthropic provider for the Universal Provider Protocol.\n *\n * Provides access to Claude language models through a unified interface.\n * Supports LLM modality with streaming, tool use, structured output,\n * and image input capabilities.\n *\n * @param modelId - The model identifier (e.g., 'claude-sonnet-4-20250514')\n * @param options - Optional configuration including beta features\n * @returns A model reference for use with `llm()`\n *\n * @example\n * ```typescript\n * import { anthropic, betas } from 'provider-protocol/anthropic';\n * import { llm } from 'provider-protocol';\n *\n * // Basic usage\n * const model = llm({ model: anthropic('claude-sonnet-4-20250514') });\n *\n * // With structured outputs beta\n * const modelWithBetas = llm({\n * model: anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs],\n * }),\n * structure: { properties: { name: { type: 'string' } } },\n * });\n *\n * // With multiple betas\n * const advancedModel = llm({\n * model: anthropic('claude-sonnet-4-20250514', {\n * betas: [betas.structuredOutputs, betas.tokenEfficientTools],\n * }),\n * });\n * ```\n *\n * @see {@link betas} for available beta features\n * @see {@link AnthropicLLMParams} for provider-specific parameters\n */\nexport const anthropic = createProvider<AnthropicModelOptions>({\n name: 'anthropic',\n version: '1.0.0',\n handlers: {\n llm: createLLMHandler(),\n },\n createModelReference: (modelId, options, provider) => {\n const providerConfig = createProviderConfig(options);\n return {\n modelId,\n provider,\n options,\n ...(providerConfig && { providerConfig }),\n };\n },\n});\n\nexport { tools, betas } from './types.ts';\nexport type { BetaKey, BetaValue } from './types.ts';\nexport type {\n AnthropicLLMParams,\n AnthropicHeaders,\n AnthropicBuiltInTool,\n AnthropicWebSearchTool,\n AnthropicComputerTool,\n AnthropicTextEditorTool,\n AnthropicBashTool,\n AnthropicCode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A,MACA;AAAA,MACA;AAAA,MACA,GAAI,kBAAkB,EAAE,eAAe;AAAA,IACzC;AAAA,EACF;AACF,CAAC;","names":[]}
|
|
@@ -61,6 +61,13 @@ var Message = class {
|
|
|
61
61
|
get video() {
|
|
62
62
|
return this.getContent().filter((block) => block.type === "video");
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* All reasoning/thinking content blocks in this message.
|
|
66
|
+
* Available when using extended thinking models.
|
|
67
|
+
*/
|
|
68
|
+
get reasoning() {
|
|
69
|
+
return this.getContent().filter((block) => block.type === "reasoning");
|
|
70
|
+
}
|
|
64
71
|
};
|
|
65
72
|
var UserMessage = class extends Message {
|
|
66
73
|
/** Message type discriminator */
|
|
@@ -245,4 +252,4 @@ export {
|
|
|
245
252
|
isToolResultMessage,
|
|
246
253
|
createProvider
|
|
247
254
|
};
|
|
248
|
-
//# sourceMappingURL=chunk-
|
|
255
|
+
//# sourceMappingURL=chunk-6AZVUI6H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/id.ts","../src/types/messages.ts","../src/core/provider-handlers.ts","../src/core/provider.ts"],"sourcesContent":["/**\n * @fileoverview ID generation utilities for the Universal Provider Protocol.\n *\n * Provides functions for generating unique identifiers used throughout UPP,\n * including message IDs, tool call IDs, and other internal references.\n *\n * @module utils/id\n */\n\n/**\n * Generates a unique UUID v4 identifier.\n *\n * Uses the native `crypto.randomUUID()` when available for cryptographically\n * secure randomness. Falls back to a Math.random-based implementation for\n * environments without Web Crypto API support.\n *\n * @returns A UUID v4 string in the format `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`\n *\n * @example\n * ```typescript\n * const messageId = generateId();\n * // => \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"\n * ```\n */\nexport function generateId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generates a short alphanumeric identifier.\n *\n * Creates a 12-character random string using alphanumeric characters (a-z, A-Z, 0-9).\n * Useful for tool call IDs and other cases where a full UUID is not required.\n *\n * @param prefix - Optional prefix to prepend to the generated ID\n * @returns A string containing the prefix followed by 12 random alphanumeric characters\n *\n * @example\n * ```typescript\n * const toolCallId = generateShortId('call_');\n * // => \"call_aB3xY9mK2pQr\"\n *\n * const simpleId = generateShortId();\n * // => \"Tz4wN8vL1sHj\"\n * ```\n */\nexport function generateShortId(prefix = ''): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let result = prefix;\n for (let i = 0; i < 12; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n}\n","/**\n * @fileoverview Message types for conversation history.\n *\n * Defines the message classes used to represent conversation turns\n * between users and assistants, including support for multimodal\n * content and tool calls.\n *\n * @module types/messages\n */\n\nimport { generateId } from '../utils/id.ts';\nimport type {\n ContentBlock,\n TextBlock,\n ReasoningBlock,\n ImageBlock,\n AudioBlock,\n VideoBlock,\n UserContent,\n AssistantContent,\n} from './content.ts';\nimport type { ToolCall, ToolResult } from './tool.ts';\n\n/**\n * Message serialized to JSON format.\n * Picks common fields from Message, converts timestamp to string.\n */\nexport type MessageJSON = Pick<Message, 'id' | 'type' | 'metadata'> & {\n timestamp: string;\n content: ContentBlock[];\n toolCalls?: ToolCall[];\n results?: ToolResult[];\n};\n\n/**\n * Message role/type constants.\n *\n * Use these constants instead of raw strings for type-safe message handling:\n *\n * @example\n * ```typescript\n * import { MessageRole, isUserMessage } from 'upp';\n *\n * if (message.type === MessageRole.User) {\n * console.log('User said:', message.text);\n * } else if (message.type === MessageRole.Assistant) {\n * console.log('Assistant replied:', message.text);\n * }\n * ```\n */\nexport const MessageRole = {\n /** User message */\n User: 'user',\n /** Assistant/model response */\n Assistant: 'assistant',\n /** Tool execution result */\n ToolResult: 'tool_result',\n} as const;\n\n/**\n * Message type discriminator union.\n *\n * This type is derived from {@link MessageRole} constants. The name `MessageType`\n * is kept for backward compatibility; `MessageRole` works as both the const\n * object and this type.\n */\nexport type MessageType = (typeof MessageRole)[keyof typeof MessageRole];\n\n/**\n * Type alias for MessageType, allowing `MessageRole` to work as both const and type.\n */\nexport type MessageRole = MessageType;\n\n/**\n * Provider-namespaced metadata for messages.\n *\n * Each provider can attach its own metadata under its namespace,\n * preventing conflicts between different providers.\n *\n * @example\n * ```typescript\n * const metadata: MessageMetadata = {\n * openai: { model: 'gpt-4', finishReason: 'stop' },\n * anthropic: { model: 'claude-3', stopReason: 'end_turn' }\n * };\n * ```\n */\nexport interface MessageMetadata {\n [provider: string]: Record<string, unknown> | undefined;\n}\n\n/**\n * Options for constructing messages.\n */\nexport interface MessageOptions {\n /** Custom message ID (auto-generated if not provided) */\n id?: string;\n\n /** Provider-specific metadata */\n metadata?: MessageMetadata;\n}\n\n/**\n * Abstract base class for all message types.\n *\n * Provides common functionality for user, assistant, and tool result\n * messages, including content accessors and metadata handling.\n *\n * @example\n * ```typescript\n * // Access text content from any message\n * const text = message.text;\n *\n * // Access images\n * const images = message.images;\n * ```\n */\nexport abstract class Message {\n /** Unique message identifier */\n readonly id: string;\n\n /** Timestamp when the message was created */\n readonly timestamp: Date;\n\n /** Provider-specific metadata, namespaced by provider name */\n readonly metadata?: MessageMetadata;\n\n /** Message type discriminator (implemented by subclasses) */\n abstract readonly type: MessageType;\n\n /**\n * Returns the content blocks for this message.\n * Implemented by subclasses to provide type-specific content.\n */\n protected abstract getContent(): ContentBlock[];\n\n /**\n * Creates a new message instance.\n *\n * @param options - Optional message ID and metadata\n */\n constructor(options?: MessageOptions) {\n this.id = options?.id ?? generateId();\n this.timestamp = new Date();\n this.metadata = options?.metadata;\n }\n\n /**\n * Concatenated text content from all text blocks.\n * Blocks are joined with double newlines.\n */\n get text(): string {\n return this.getContent()\n .filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('\\n\\n');\n }\n\n /**\n * All image content blocks in this message.\n */\n get images(): ImageBlock[] {\n return this.getContent().filter((block): block is ImageBlock => block.type === 'image');\n }\n\n /**\n * All audio content blocks in this message.\n */\n get audio(): AudioBlock[] {\n return this.getContent().filter((block): block is AudioBlock => block.type === 'audio');\n }\n\n /**\n * All video content blocks in this message.\n */\n get video(): VideoBlock[] {\n return this.getContent().filter((block): block is VideoBlock => block.type === 'video');\n }\n\n /**\n * All reasoning/thinking content blocks in this message.\n * Available when using extended thinking models.\n */\n get reasoning(): ReasoningBlock[] {\n return this.getContent().filter((block): block is ReasoningBlock => block.type === 'reasoning');\n }\n}\n\n/**\n * User input message.\n *\n * Represents a message from the user, which can contain text and/or\n * multimodal content like images, audio, or video.\n *\n * @example\n * ```typescript\n * // Simple text message\n * const msg = new UserMessage('Hello, world!');\n *\n * // Multimodal message\n * const msg = new UserMessage([\n * { type: 'text', text: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', url: '...' }, mimeType: 'image/png' }\n * ]);\n * ```\n */\nexport class UserMessage extends Message {\n /** Message type discriminator */\n readonly type = 'user' as const;\n\n /** Content blocks in this message */\n readonly content: UserContent[];\n\n /**\n * Creates a new user message.\n *\n * @param content - String (converted to TextBlock) or array of content blocks\n * @param options - Optional message ID and metadata\n */\n constructor(content: string | UserContent[], options?: MessageOptions) {\n super(options);\n if (typeof content === 'string') {\n this.content = [{ type: 'text', text: content }];\n } else {\n this.content = content;\n }\n }\n\n protected getContent(): ContentBlock[] {\n return this.content;\n }\n}\n\n/**\n * Assistant response message.\n *\n * Represents a response from the AI assistant, which may contain\n * text, media content, and/or tool call requests.\n *\n * @example\n * ```typescript\n * // Simple text response\n * const msg = new AssistantMessage('Hello! How can I help?');\n *\n * // Response with tool calls\n * const msg = new AssistantMessage(\n * 'Let me check the weather...',\n * [{ toolCallId: 'call_1', toolName: 'get_weather', arguments: { location: 'NYC' } }]\n * );\n * ```\n */\nexport class AssistantMessage extends Message {\n /** Message type discriminator */\n readonly type = 'assistant' as const;\n\n /** Content blocks in this message */\n readonly content: AssistantContent[];\n\n /** Tool calls requested by the model (if any) */\n readonly toolCalls?: ToolCall[];\n\n /**\n * Creates a new assistant message.\n *\n * @param content - String (converted to TextBlock) or array of content blocks\n * @param toolCalls - Tool calls requested by the model\n * @param options - Optional message ID and metadata\n */\n constructor(\n content: string | AssistantContent[],\n toolCalls?: ToolCall[],\n options?: MessageOptions\n ) {\n super(options);\n if (typeof content === 'string') {\n this.content = [{ type: 'text', text: content }];\n } else {\n this.content = content;\n }\n this.toolCalls = toolCalls;\n }\n\n protected getContent(): ContentBlock[] {\n return this.content;\n }\n\n /**\n * Whether this message contains tool call requests.\n */\n get hasToolCalls(): boolean {\n return this.toolCalls !== undefined && this.toolCalls.length > 0;\n }\n}\n\n/**\n * Tool execution result message.\n *\n * Contains the results of executing one or more tool calls,\n * sent back to the model for further processing.\n *\n * @example\n * ```typescript\n * const msg = new ToolResultMessage([\n * { toolCallId: 'call_1', result: { temperature: 72, conditions: 'sunny' } },\n * { toolCallId: 'call_2', result: 'File not found', isError: true }\n * ]);\n * ```\n */\nexport class ToolResultMessage extends Message {\n /** Message type discriminator */\n readonly type = 'tool_result' as const;\n\n /** Results from tool executions */\n readonly results: ToolResult[];\n\n /**\n * Creates a new tool result message.\n *\n * @param results - Array of tool execution results\n * @param options - Optional message ID and metadata\n */\n constructor(results: ToolResult[], options?: MessageOptions) {\n super(options);\n this.results = results;\n }\n\n protected getContent(): ContentBlock[] {\n return this.results.map((result) => ({\n type: 'text' as const,\n text:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n }));\n }\n}\n\n/**\n * Type guard for UserMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is a UserMessage\n *\n * @example\n * ```typescript\n * if (isUserMessage(msg)) {\n * console.log('User said:', msg.text);\n * }\n * ```\n */\nexport function isUserMessage(msg: Message): msg is UserMessage {\n return msg.type === MessageRole.User;\n}\n\n/**\n * Type guard for AssistantMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is an AssistantMessage\n *\n * @example\n * ```typescript\n * if (isAssistantMessage(msg)) {\n * console.log('Assistant said:', msg.text);\n * if (msg.hasToolCalls) {\n * console.log('Tool calls:', msg.toolCalls);\n * }\n * }\n * ```\n */\nexport function isAssistantMessage(msg: Message): msg is AssistantMessage {\n return msg.type === MessageRole.Assistant;\n}\n\n/**\n * Type guard for ToolResultMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is a ToolResultMessage\n *\n * @example\n * ```typescript\n * if (isToolResultMessage(msg)) {\n * for (const result of msg.results) {\n * console.log(`Tool ${result.toolCallId}:`, result.result);\n * }\n * }\n * ```\n */\nexport function isToolResultMessage(msg: Message): msg is ToolResultMessage {\n return msg.type === MessageRole.ToolResult;\n}\n","/**\n * @fileoverview Internal handler registry and resolver utilities.\n *\n * @module core/provider-handlers\n */\n\nimport type {\n ProviderIdentity,\n LLMHandler,\n EmbeddingHandler,\n ImageHandler,\n} from '../types/provider.ts';\n\n/**\n * Resolver for dynamically selecting LLM handlers based on model options.\n *\n * Used by providers that support multiple API modes (e.g., OpenAI with responses/completions).\n * The resolver eliminates shared mutable state by storing the mode on the ModelReference\n * and resolving the correct handler at request time.\n *\n * @typeParam TOptions - Provider-specific options type\n */\nexport interface LLMHandlerResolver<TOptions = unknown> {\n /** Map of mode identifiers to their corresponding LLM handlers */\n handlers: Record<string, LLMHandler>;\n /** The default mode when options don't specify one */\n defaultMode: string;\n /** Function to extract the mode from provider options */\n getMode: (options: TOptions | undefined) => string;\n}\n\n/**\n * Type guard to check if a value is an LLMHandlerResolver.\n */\nexport function isHandlerResolver<TOptions>(\n value: LLMHandler | LLMHandlerResolver<TOptions> | undefined\n): value is LLMHandlerResolver<TOptions> {\n return value !== undefined && 'handlers' in value && 'getMode' in value;\n}\n\ntype ProviderHandlers<TOptions = unknown> = {\n llm?: LLMHandler;\n embedding?: EmbeddingHandler;\n image?: ImageHandler;\n llmResolver?: LLMHandlerResolver<TOptions>;\n};\n\nconst providerHandlers = new WeakMap<object, ProviderHandlers<unknown>>();\n\n/**\n * Registers handler implementations for a provider.\n */\nexport function registerProviderHandlers<TOptions>(\n provider: ProviderIdentity,\n handlers: ProviderHandlers<TOptions>\n): void {\n providerHandlers.set(provider as object, handlers as ProviderHandlers<unknown>);\n}\n\nfunction getProviderHandlers<TOptions>(\n provider: ProviderIdentity\n): ProviderHandlers<TOptions> | undefined {\n return providerHandlers.get(provider as object) as ProviderHandlers<TOptions> | undefined;\n}\n\n/**\n * Resolves the correct LLM handler based on model reference options.\n *\n * For providers with multiple LLM handlers (e.g., OpenAI with responses/completions APIs),\n * this function determines which handler to use based on the options stored on the\n * ModelReference. This eliminates race conditions from shared mutable state.\n *\n * For providers with a single LLM handler, this simply returns that handler.\n *\n * @typeParam TOptions - Provider-specific options type\n * @param provider - The provider to resolve the handler from\n * @param options - The options from the ModelReference\n * @returns The resolved LLM handler, or undefined if LLM is not supported\n *\n * @internal\n */\nexport function resolveLLMHandler<TOptions = unknown>(\n provider: ProviderIdentity,\n options: TOptions | undefined\n): LLMHandler | undefined {\n const handlers = getProviderHandlers(provider);\n const resolver = handlers?.llmResolver;\n\n if (resolver) {\n const mode = resolver.getMode(options);\n return resolver.handlers[mode] ?? handlers?.llm;\n }\n\n return handlers?.llm;\n}\n\n/**\n * Resolves the embedding handler for a provider, if supported.\n *\n * @internal\n */\nexport function resolveEmbeddingHandler<TParams = unknown>(\n provider: ProviderIdentity\n): EmbeddingHandler<TParams> | undefined {\n const handlers = getProviderHandlers(provider);\n return handlers?.embedding as EmbeddingHandler<TParams> | undefined;\n}\n\n/**\n * Resolves the image handler for a provider, if supported.\n *\n * @internal\n */\nexport function resolveImageHandler<TParams = unknown>(\n provider: ProviderIdentity\n): ImageHandler<TParams> | undefined {\n const handlers = getProviderHandlers(provider);\n return handlers?.image as ImageHandler<TParams> | undefined;\n}\n","/**\n * @fileoverview Base provider interface and factory for the Universal Provider Protocol.\n *\n * This module provides the foundation for creating AI providers that conform to the\n * UPP specification. Providers are callable functions that create model references\n * and register internal handlers for LLM, embedding, and image modalities.\n *\n * @module core/provider\n */\n\nimport type {\n Provider,\n ModelReference,\n LLMHandler,\n EmbeddingHandler,\n ImageHandler,\n LLMProvider,\n EmbeddingProvider,\n ImageProvider,\n} from '../types/provider.ts';\nimport type { LLMHandlerResolver } from './provider-handlers.ts';\nimport { isHandlerResolver, registerProviderHandlers } from './provider-handlers.ts';\n\n\n/**\n * Configuration options for creating a new provider.\n *\n * @typeParam TOptions - Provider-specific options type\n *\n * @example\n * ```typescript\n * // Simple provider with single handler\n * const options: CreateProviderOptions = {\n * name: 'my-provider',\n * version: '1.0.0',\n * handlers: {\n * llm: createLLMHandler(),\n * embedding: createEmbeddingHandler(),\n * },\n * };\n *\n * // Provider with multiple LLM handlers (API modes)\n * const options: CreateProviderOptions<OpenAIOptions> = {\n * name: 'openai',\n * version: '1.0.0',\n * handlers: {\n * llm: {\n * handlers: { responses: handler1, completions: handler2 },\n * defaultMode: 'responses',\n * getMode: (opts) => opts?.api ?? 'responses',\n * },\n * },\n * };\n * ```\n */\nexport interface CreateProviderOptions<TOptions = unknown> {\n /** Unique identifier for the provider */\n name: string;\n /** Semantic version string for the provider implementation */\n version: string;\n /** Handlers for supported modalities (LLM, embedding, image generation) */\n handlers: {\n /** Handler for language model completions, or resolver for multi-handler providers */\n llm?: LLMHandler | LLMHandlerResolver<TOptions>;\n /** Handler for text embeddings */\n embedding?: EmbeddingHandler;\n /** Handler for image generation */\n image?: ImageHandler;\n };\n /**\n * Custom function to create model references from options.\n * Use this to map provider options to providerConfig (e.g., betas to headers).\n */\n createModelReference?: (\n modelId: string,\n options: TOptions | undefined,\n provider: Provider<TOptions>\n ) => ModelReference<TOptions>;\n}\n\n\n/**\n * Creates a provider factory function with registered modality handlers.\n *\n * The returned provider is a callable function that creates model references\n * when invoked with a model ID. It exposes `name` and `version` metadata.\n *\n * @typeParam TOptions - Provider-specific options type (defaults to unknown)\n * @param options - Provider configuration including name, version, and handlers\n * @returns A callable Provider with handlers registered internally\n *\n * @example\n * ```typescript\n * // Create a basic provider\n * const anthropic = createProvider({\n * name: 'anthropic',\n * version: '1.0.0',\n * handlers: { llm: createLLMHandler() },\n * });\n *\n * // Use the provider to create a model reference\n * const model = anthropic('claude-sonnet-4-20250514');\n *\n * // Provider with custom options type\n * interface MyOptions { apiVersion?: 'v1' | 'v2' }\n * const myProvider = createProvider<MyOptions>({\n * name: 'my-provider',\n * version: '1.0.0',\n * handlers: { llm: handler },\n * });\n *\n * // Provider with multiple LLM handlers (API modes)\n * const openai = createProvider<OpenAIOptions>({\n * name: 'openai',\n * version: '1.0.0',\n * handlers: {\n * llm: {\n * handlers: { responses: responsesHandler, completions: completionsHandler },\n * defaultMode: 'responses',\n * getMode: (opts) => opts?.api ?? 'responses',\n * },\n * },\n * });\n * ```\n */\nexport function createProvider<TOptions = unknown>(\n options: CreateProviderOptions<TOptions>\n): Provider<TOptions> {\n // Resolve the default LLM handler for capabilities/bind\n const llmInput = options.handlers.llm;\n const hasResolver = isHandlerResolver<TOptions>(llmInput);\n const defaultLLMHandler = hasResolver ? llmInput.handlers[llmInput.defaultMode] : llmInput;\n\n if (hasResolver && !defaultLLMHandler) {\n throw new Error(\n `Provider '${options.name}' LLM resolver defaultMode '${llmInput.defaultMode}' has no handler`\n );\n }\n\n // Create the factory function\n const fn = function (modelId: string, modelOptions?: TOptions): ModelReference<TOptions> {\n if (options.createModelReference) {\n return options.createModelReference(modelId, modelOptions, provider);\n }\n // Default: store options on the reference for handler resolution\n return { modelId, provider, options: modelOptions };\n };\n\n Object.defineProperties(fn, {\n name: {\n value: options.name,\n writable: false,\n configurable: true,\n },\n version: {\n value: options.version,\n writable: false,\n configurable: true,\n },\n });\n\n const provider = fn as Provider<TOptions>;\n\n // If there's a resolver, set provider on all handlers\n if (hasResolver) {\n for (const handler of Object.values(llmInput.handlers)) {\n handler._setProvider?.(provider as unknown as LLMProvider);\n }\n } else if (defaultLLMHandler?._setProvider) {\n defaultLLMHandler._setProvider(provider as unknown as LLMProvider);\n }\n\n if (options.handlers.embedding?._setProvider) {\n options.handlers.embedding._setProvider(provider as unknown as EmbeddingProvider);\n }\n if (options.handlers.image?._setProvider) {\n options.handlers.image._setProvider(provider as unknown as ImageProvider);\n }\n\n registerProviderHandlers(provider, {\n llm: defaultLLMHandler,\n embedding: options.handlers.embedding,\n image: options.handlers.image,\n ...(hasResolver ? { llmResolver: llmInput } : {}),\n });\n\n return provider;\n}\n"],"mappings":";AAwBO,SAAS,aAAqB;AACnC,MAAI,OAAO,WAAW,eAAe,OAAO,YAAY;AACtD,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO,uCAAuC,QAAQ,SAAS,CAAC,MAAM;AACpE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,MAAM,MAAM,IAAK,IAAI,IAAO;AACtC,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB,CAAC;AACH;;;ACgBO,IAAM,cAAc;AAAA;AAAA,EAEzB,MAAM;AAAA;AAAA,EAEN,WAAW;AAAA;AAAA,EAEX,YAAY;AACd;AA4DO,IAAe,UAAf,MAAuB;AAAA;AAAA,EAEnB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBT,YAAY,SAA0B;AACpC,SAAK,KAAK,SAAS,MAAM,WAAW;AACpC,SAAK,YAAY,oBAAI,KAAK;AAC1B,SAAK,WAAW,SAAS;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,OAAe;AACjB,WAAO,KAAK,WAAW,EACpB,OAAO,CAAC,UAA8B,MAAM,SAAS,MAAM,EAC3D,IAAI,CAAC,UAAU,MAAM,IAAI,EACzB,KAAK,MAAM;AAAA,EAChB;AAAA;AAAA;AAAA;A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