@providerprotocol/ai 0.0.27 → 0.0.29
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 +38 -1
- package/dist/anthropic/index.js.map +1 -1
- package/dist/{chunk-6AZVUI6H.js → chunk-ILR2D5PN.js} +7 -1
- package/dist/chunk-ILR2D5PN.js.map +1 -0
- package/dist/{chunk-MKDLXV4O.js → chunk-NSE7QN3P.js} +1 -1
- package/dist/chunk-NSE7QN3P.js.map +1 -0
- package/dist/embedding-DtyOFIsS.d.ts +158 -0
- package/dist/google/index.d.ts +1 -1
- package/dist/google/index.js +41 -4
- package/dist/google/index.js.map +1 -1
- package/dist/http/index.d.ts +2 -2
- package/dist/index.d.ts +430 -514
- package/dist/index.js +627 -3
- package/dist/index.js.map +1 -1
- package/dist/llm-DgDEy9il.d.ts +3118 -0
- package/dist/ollama/index.d.ts +1 -1
- package/dist/ollama/index.js +2 -1
- package/dist/ollama/index.js.map +1 -1
- package/dist/openai/index.d.ts +1 -1
- package/dist/openai/index.js +70 -3
- package/dist/openai/index.js.map +1 -1
- package/dist/openrouter/index.d.ts +20 -2
- package/dist/openrouter/index.js +134 -13
- package/dist/openrouter/index.js.map +1 -1
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +3 -2
- package/dist/proxy/index.js.map +1 -1
- package/dist/{retry-BhX8mIrL.d.ts → retry-DXLQnTuU.d.ts} +1 -1
- package/dist/xai/index.d.ts +1 -1
- package/dist/xai/index.js +7 -3
- package/dist/xai/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-6AZVUI6H.js.map +0 -1
- package/dist/chunk-MKDLXV4O.js.map +0 -1
- package/dist/embedding-CK5oa38O.d.ts +0 -1235
- package/dist/provider-6-mJYOOl.d.ts +0 -1474
package/dist/anthropic/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
isAssistantMessage,
|
|
12
12
|
isToolResultMessage,
|
|
13
13
|
isUserMessage
|
|
14
|
-
} from "../chunk-
|
|
14
|
+
} from "../chunk-ILR2D5PN.js";
|
|
15
15
|
import {
|
|
16
16
|
parseSSEStream
|
|
17
17
|
} from "../chunk-TOJCZMVU.js";
|
|
@@ -376,6 +376,42 @@ function transformContentBlock(block, cacheControl) {
|
|
|
376
376
|
}
|
|
377
377
|
throw new Error(`Unknown image source type`);
|
|
378
378
|
}
|
|
379
|
+
case "document": {
|
|
380
|
+
const documentBlock = block;
|
|
381
|
+
if (documentBlock.source.type === "base64") {
|
|
382
|
+
return {
|
|
383
|
+
type: "document",
|
|
384
|
+
source: {
|
|
385
|
+
type: "base64",
|
|
386
|
+
media_type: documentBlock.mimeType,
|
|
387
|
+
data: documentBlock.source.data
|
|
388
|
+
},
|
|
389
|
+
...cacheControl ? { cache_control: cacheControl } : {}
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (documentBlock.source.type === "url") {
|
|
393
|
+
return {
|
|
394
|
+
type: "document",
|
|
395
|
+
source: {
|
|
396
|
+
type: "url",
|
|
397
|
+
url: documentBlock.source.url
|
|
398
|
+
},
|
|
399
|
+
...cacheControl ? { cache_control: cacheControl } : {}
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
if (documentBlock.source.type === "text") {
|
|
403
|
+
return {
|
|
404
|
+
type: "document",
|
|
405
|
+
source: {
|
|
406
|
+
type: "text",
|
|
407
|
+
media_type: documentBlock.mimeType,
|
|
408
|
+
data: documentBlock.source.data
|
|
409
|
+
},
|
|
410
|
+
...cacheControl ? { cache_control: cacheControl } : {}
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
throw new Error(`Unknown document source type`);
|
|
414
|
+
}
|
|
379
415
|
default:
|
|
380
416
|
throw new Error(`Unsupported content type: ${block.type}`);
|
|
381
417
|
}
|
|
@@ -703,6 +739,7 @@ var ANTHROPIC_CAPABILITIES = {
|
|
|
703
739
|
tools: true,
|
|
704
740
|
structuredOutput: true,
|
|
705
741
|
imageInput: true,
|
|
742
|
+
documentInput: true,
|
|
706
743
|
videoInput: false,
|
|
707
744
|
audioInput: false
|
|
708
745
|
};
|
|
@@ -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 | 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 AnthropicCodeExecutionTool,\n AnthropicTool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AAA,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 | AnthropicDocumentContent\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 * Document content block for PDF and text document support.\n *\n * Documents can be provided as base64-encoded PDFs, PDF URLs, or plain text.\n *\n * @example\n * ```typescript\n * // Base64 PDF\n * const pdfContent: AnthropicDocumentContent = {\n * type: 'document',\n * source: {\n * type: 'base64',\n * media_type: 'application/pdf',\n * data: 'JVBERi0xLjQK...',\n * },\n * };\n *\n * // URL PDF\n * const urlContent: AnthropicDocumentContent = {\n * type: 'document',\n * source: {\n * type: 'url',\n * url: 'https://example.com/document.pdf',\n * },\n * };\n *\n * // Plain text document\n * const textContent: AnthropicDocumentContent = {\n * type: 'document',\n * source: {\n * type: 'text',\n * media_type: 'text/plain',\n * data: 'Document content here...',\n * },\n * };\n * ```\n */\nexport interface AnthropicDocumentContent {\n /** Content type discriminator. */\n type: 'document';\n /** Document source configuration. */\n source:\n | {\n /** Base64-encoded document (PDF). */\n type: 'base64';\n /** MIME type ('application/pdf'). */\n media_type: string;\n /** Base64-encoded document data. */\n data: string;\n }\n | {\n /** URL to PDF document. */\n type: 'url';\n /** URL of the PDF. */\n url: string;\n }\n | {\n /** Plain text document. */\n type: 'text';\n /** MIME type ('text/plain'). */\n media_type: string;\n /** Plain text content. */\n data: string;\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n /** Enable citations from document content. */\n citations?: { enabled: boolean };\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, DocumentBlock, 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 case 'document': {\n const documentBlock = block as DocumentBlock;\n if (documentBlock.source.type === 'base64') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n media_type: documentBlock.mimeType,\n data: documentBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (documentBlock.source.type === 'url') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: documentBlock.source.url,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (documentBlock.source.type === 'text') {\n return {\n type: 'document',\n source: {\n type: 'text',\n media_type: documentBlock.mimeType,\n data: documentBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n throw new Error(`Unknown document 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 { BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';\nimport type { LLMHandler } from '../../types/provider.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 * - documentInput: PDF and text document analysis\n */\nconst ANTHROPIC_CAPABILITIES: LLMCapabilities = {\n streaming: true,\n tools: true,\n structuredOutput: true,\n imageInput: true,\n documentInput: 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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YAAY,WAAW;AAChC,0BAAM;AAAA,kBACR;AAAA,gBACF;AAAA,cACF;AAEA,8BAAgB,uBAAuB,OAAO,yBAAyB,CAAC;AAAA,YAC1E,SAAS,OAAO;AACd,oBAAM,MAAM,QAAQ,KAAK;AACzB,6BAAe,GAAG;AAClB,oBAAM;AAAA,YACR;AAAA,UACF;AAEA,iBAAO;AAAA,YACL,CAAC,OAAO,aAAa,IAAI;AACvB,qBAAO,eAAe;AAAA,YACxB;AAAA,YACA,UAAU;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACtPA,SAAS,qBAAqB,SAAsE;AAClG,MAAI,CAAC,SAAS,SAAS,QAAQ,MAAM,WAAW,GAAG;AACjD,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,QAAQ,MAAM,KAAK,GAAG;AAEzC,SAAO;AAAA,IACL,SAAS;AAAA,MACP,kBAAkB;AAAA,IACpB;AAAA,EACF;AACF;AAwCO,IAAM,YAAY,eAAsC;AAAA,EAC7D,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,IACR,KAAK,iBAAiB;AAAA,EACxB;AAAA,EACA,sBAAsB,CAAC,SAAS,SAAS,aAAa;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":[]}
|
|
@@ -49,6 +49,12 @@ var Message = class {
|
|
|
49
49
|
get images() {
|
|
50
50
|
return this.getContent().filter((block) => block.type === "image");
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* All document content blocks in this message.
|
|
54
|
+
*/
|
|
55
|
+
get documents() {
|
|
56
|
+
return this.getContent().filter((block) => block.type === "document");
|
|
57
|
+
}
|
|
52
58
|
/**
|
|
53
59
|
* All audio content blocks in this message.
|
|
54
60
|
*/
|
|
@@ -252,4 +258,4 @@ export {
|
|
|
252
258
|
isToolResultMessage,
|
|
253
259
|
createProvider
|
|
254
260
|
};
|
|
255
|
-
//# sourceMappingURL=chunk-
|
|
261
|
+
//# sourceMappingURL=chunk-ILR2D5PN.js.map
|