@providerprotocol/ai 0.0.16 → 0.0.18

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.
Files changed (41) hide show
  1. package/README.md +111 -8
  2. package/dist/anthropic/index.d.ts +1 -1
  3. package/dist/anthropic/index.js +5 -3
  4. package/dist/anthropic/index.js.map +1 -1
  5. package/dist/{chunk-MOU4U3PO.js → chunk-5FEAOEXV.js} +4 -68
  6. package/dist/chunk-5FEAOEXV.js.map +1 -0
  7. package/dist/chunk-DZQHVGNV.js +71 -0
  8. package/dist/chunk-DZQHVGNV.js.map +1 -0
  9. package/dist/chunk-SKY2JLA7.js +59 -0
  10. package/dist/chunk-SKY2JLA7.js.map +1 -0
  11. package/dist/{chunk-SVYROCLD.js → chunk-UMKWXGO3.js} +1 -1
  12. package/dist/chunk-UMKWXGO3.js.map +1 -0
  13. package/dist/google/index.d.ts +29 -2
  14. package/dist/google/index.js +107 -4
  15. package/dist/google/index.js.map +1 -1
  16. package/dist/http/index.d.ts +2 -2
  17. package/dist/http/index.js +2 -1
  18. package/dist/index.d.ts +211 -1303
  19. package/dist/index.js +161 -58
  20. package/dist/index.js.map +1 -1
  21. package/dist/ollama/index.d.ts +26 -2
  22. package/dist/ollama/index.js +101 -4
  23. package/dist/ollama/index.js.map +1 -1
  24. package/dist/openai/index.d.ts +28 -3
  25. package/dist/openai/index.js +111 -4
  26. package/dist/openai/index.js.map +1 -1
  27. package/dist/openrouter/index.d.ts +29 -3
  28. package/dist/openrouter/index.js +118 -4
  29. package/dist/openrouter/index.js.map +1 -1
  30. package/dist/{provider-vTZ74u-w.d.ts → provider-D5MO3-pS.d.ts} +66 -1
  31. package/dist/proxy/index.d.ts +611 -0
  32. package/dist/proxy/index.js +565 -0
  33. package/dist/proxy/index.js.map +1 -0
  34. package/dist/{retry-CMdT0kD8.d.ts → retry-DZ4Sqmxp.d.ts} +1 -1
  35. package/dist/stream-BjyVzBxV.d.ts +1286 -0
  36. package/dist/xai/index.d.ts +1 -1
  37. package/dist/xai/index.js +5 -3
  38. package/dist/xai/index.js.map +1 -1
  39. package/package.json +6 -1
  40. package/dist/chunk-MOU4U3PO.js.map +0 -1
  41. package/dist/chunk-SVYROCLD.js.map +0 -1
package/README.md CHANGED
@@ -57,16 +57,119 @@ const turn = await llm({
57
57
  console.log(turn.data); // { name: 'John', age: 30 }
58
58
  ```
59
59
 
60
+ ## Embeddings
61
+
62
+ Generate vector embeddings from text using the unified `embedding()` interface.
63
+
64
+ ```typescript
65
+ import { embedding } from '@providerprotocol/ai';
66
+ import { openai } from '@providerprotocol/ai/openai';
67
+ import { google } from '@providerprotocol/ai/google';
68
+ import { ollama } from '@providerprotocol/ai/ollama';
69
+ import { openrouter } from '@providerprotocol/ai/openrouter';
70
+
71
+ // Single text embedding
72
+ const embedder = embedding({ model: openai('text-embedding-3-small') });
73
+ const result = await embedder.embed('Hello world');
74
+ console.log(result.embeddings[0].vector); // [0.123, -0.456, ...]
75
+ console.log(result.embeddings[0].dimensions); // 1536
76
+
77
+ // Batch embedding
78
+ const batch = await embedder.embed(['doc1', 'doc2', 'doc3']);
79
+ console.log(batch.embeddings.length); // 3
80
+
81
+ // Custom dimensions (OpenAI text-embedding-3 models)
82
+ const smallEmbed = embedding({
83
+ model: openai('text-embedding-3-small'),
84
+ params: { dimensions: 256 },
85
+ });
86
+
87
+ // Google with task type optimization
88
+ const googleEmbed = embedding({
89
+ model: google('text-embedding-004'),
90
+ params: {
91
+ taskType: 'RETRIEVAL_DOCUMENT',
92
+ title: 'Important Document',
93
+ },
94
+ });
95
+
96
+ // Ollama local embeddings
97
+ const localEmbed = embedding({
98
+ model: ollama('qwen3-embedding:4b'),
99
+ });
100
+
101
+ // OpenRouter (access multiple providers)
102
+ const routerEmbed = embedding({
103
+ model: openrouter('openai/text-embedding-3-small'),
104
+ });
105
+ ```
106
+
107
+ ### Chunked Streaming
108
+
109
+ For large document sets, use chunked mode for progress tracking:
110
+
111
+ ```typescript
112
+ const embedder = embedding({ model: openai('text-embedding-3-small') });
113
+ const documents = Array.from({ length: 1000 }, (_, i) => `Document ${i}`);
114
+
115
+ const stream = embedder.embed(documents, {
116
+ chunked: true,
117
+ batchSize: 100,
118
+ concurrency: 2,
119
+ });
120
+
121
+ for await (const progress of stream) {
122
+ console.log(`${progress.percent.toFixed(1)}% complete`);
123
+ console.log(`Processed ${progress.completed} of ${progress.total}`);
124
+ }
125
+
126
+ const finalResult = await stream.result;
127
+ console.log(`Total embeddings: ${finalResult.embeddings.length}`);
128
+ ```
129
+
130
+ ### Provider-Specific Parameters
131
+
132
+ Each provider supports its native parameters passed through unchanged:
133
+
134
+ ```typescript
135
+ // OpenAI: dimensions, encoding_format, user
136
+ embedding({
137
+ model: openai('text-embedding-3-large'),
138
+ params: { dimensions: 1024, encoding_format: 'float' },
139
+ });
140
+
141
+ // Google: taskType, title, outputDimensionality
142
+ embedding({
143
+ model: google('text-embedding-004'),
144
+ params: {
145
+ taskType: 'SEMANTIC_SIMILARITY',
146
+ outputDimensionality: 256,
147
+ },
148
+ });
149
+
150
+ // Ollama: truncate, keep_alive, options
151
+ embedding({
152
+ model: ollama('nomic-embed-text'),
153
+ params: { truncate: true, keep_alive: '5m' },
154
+ });
155
+
156
+ // OpenRouter: dimensions, encoding_format, input_type
157
+ embedding({
158
+ model: openrouter('openai/text-embedding-3-small'),
159
+ params: { dimensions: 512 },
160
+ });
161
+ ```
162
+
60
163
  ## Providers
61
164
 
62
- | Provider | Import |
63
- |----------|--------|
64
- | Anthropic | `@providerprotocol/ai/anthropic` |
65
- | OpenAI | `@providerprotocol/ai/openai` |
66
- | Google | `@providerprotocol/ai/google` |
67
- | Ollama | `@providerprotocol/ai/ollama` |
68
- | OpenRouter | `@providerprotocol/ai/openrouter` |
69
- | xAI (Grok) | `@providerprotocol/ai/xai` |
165
+ | Provider | Import | LLM | Embedding |
166
+ |----------|--------|-----|-----------|
167
+ | Anthropic | `@providerprotocol/ai/anthropic` | Yes | - |
168
+ | OpenAI | `@providerprotocol/ai/openai` | Yes | Yes |
169
+ | Google | `@providerprotocol/ai/google` | Yes | Yes |
170
+ | Ollama | `@providerprotocol/ai/ollama` | Yes | Yes |
171
+ | OpenRouter | `@providerprotocol/ai/openrouter` | Yes | Yes |
172
+ | xAI (Grok) | `@providerprotocol/ai/xai` | Yes | - |
70
173
 
71
174
  ### xAI API Modes
72
175
 
@@ -1,4 +1,4 @@
1
- import { b as Provider } from '../provider-vTZ74u-w.js';
1
+ import { d as Provider } from '../provider-D5MO3-pS.js';
2
2
 
3
3
  /**
4
4
  * @fileoverview Anthropic API type definitions.
@@ -6,17 +6,19 @@ import {
6
6
  isAssistantMessage,
7
7
  isToolResultMessage,
8
8
  isUserMessage
9
- } from "../chunk-SVYROCLD.js";
9
+ } from "../chunk-UMKWXGO3.js";
10
10
  import {
11
11
  parseSSEStream
12
12
  } from "../chunk-Z7RBRCRN.js";
13
13
  import {
14
- UPPError,
15
14
  doFetch,
16
15
  doStreamFetch,
17
16
  normalizeHttpError,
18
17
  resolveApiKey
19
- } from "../chunk-MOU4U3PO.js";
18
+ } from "../chunk-5FEAOEXV.js";
19
+ import {
20
+ UPPError
21
+ } from "../chunk-DZQHVGNV.js";
20
22
 
21
23
  // src/providers/anthropic/transform.ts
22
24
  function transformRequest(request, modelId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/providers/anthropic/transform.ts","../../src/providers/anthropic/llm.ts","../../src/providers/anthropic/types.ts","../../src/providers/anthropic/index.ts"],"sourcesContent":["/**\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 type { StreamEvent } from '../../types/stream.ts';\nimport type { Tool, ToolCall } from '../../types/tool.ts';\nimport type { TokenUsage } from '../../types/turn.ts';\nimport type { ContentBlock, TextBlock, ImageBlock } from '../../types/content.ts';\nimport {\n AssistantMessage,\n isUserMessage,\n isAssistantMessage,\n isToolResultMessage,\n} from '../../types/messages.ts';\nimport type {\n AnthropicLLMParams,\n AnthropicRequest,\n AnthropicMessage,\n AnthropicContent,\n AnthropicTool,\n AnthropicResponse,\n AnthropicStreamEvent,\n AnthropicCacheControl,\n AnthropicSystemContent,\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 * @returns An AnthropicRequest ready for the Messages API\n *\n * @example\n * ```typescript\n * const anthropicRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * params: { max_tokens: 1024, temperature: 0.7 },\n * }, 'claude-sonnet-4-20250514');\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): AnthropicRequest {\n const params = (request.params ?? {}) as AnthropicLLMParams;\n const { builtInTools, ...restParams } = params;\n\n const anthropicRequest: AnthropicRequest = {\n ...restParams,\n model: modelId,\n messages: request.messages.map(transformMessage),\n };\n\n if (request.system) {\n // Pass through directly - accepts string or array of AnthropicSystemContent\n // Array format enables cache_control: [{type: 'text', text: '...', cache_control: {...}}]\n anthropicRequest.system = request.system as string | AnthropicSystemContent[];\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 // For tool caching, use params.tools directly with native 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 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 },\n };\n\n anthropicRequest.tools = [...(anthropicRequest.tools ?? []), structuredTool];\n anthropicRequest.tool_choice = { type: 'tool', name: 'json_response' };\n }\n\n return anthropicRequest;\n}\n\n/**\n * Filters content blocks to include only those with a valid type property.\n *\n * @param content - Array of content blocks to filter\n * @returns Filtered array containing only blocks with a string type property\n */\nfunction filterValidContent<T extends { type?: string }>(content: T[]): T[] {\n return content.filter((c) => c && typeof c.type === 'string');\n}\n\n/**\n * Extracts cache control configuration from message metadata.\n *\n * @param message - The message to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractCacheControl(message: Message): AnthropicCacheControl | undefined {\n const anthropicMeta = message.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Message to Anthropic's message format.\n *\n * Handles three message types:\n * - UserMessage: Converted with content blocks\n * - AssistantMessage: Includes text and tool_use blocks\n * - ToolResultMessage: Converted to user role with tool_result content\n *\n * Cache control can be specified via message metadata:\n * ```typescript\n * new UserMessage(content, {\n * metadata: { anthropic: { cache_control: { type: \"ephemeral\" } } }\n * })\n * ```\n *\n * @param message - The UPP message to transform\n * @returns An AnthropicMessage with the appropriate role and content\n * @throws Error if the message type is unknown\n */\nfunction transformMessage(message: Message): AnthropicMessage {\n const cacheControl = extractCacheControl(message);\n\n if (isUserMessage(message)) {\n const validContent = filterValidContent(message.content);\n const contentBlocks = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 ? cacheControl : undefined)\n );\n return {\n role: 'user',\n content: contentBlocks,\n };\n }\n\n if (isAssistantMessage(message)) {\n const validContent = filterValidContent(message.content);\n const content: AnthropicContent[] = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 && !message.toolCalls?.length ? cacheControl : undefined)\n );\n\n if (message.toolCalls) {\n for (let i = 0; i < message.toolCalls.length; i++) {\n const call = message.toolCalls[i]!;\n const isLast = i === message.toolCalls.length - 1;\n content.push({\n type: 'tool_use',\n id: call.toolCallId,\n name: call.toolName,\n input: call.arguments,\n ...(isLast && cacheControl ? { cache_control: cacheControl } : {}),\n });\n }\n }\n\n return {\n role: 'assistant',\n content,\n };\n }\n\n if (isToolResultMessage(message)) {\n return {\n role: 'user',\n content: message.results.map((result, index, arr) => ({\n type: 'tool_result' as const,\n tool_use_id: result.toolCallId,\n content:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n is_error: result.isError,\n ...(index === arr.length - 1 && cacheControl ? { cache_control: cacheControl } : {}),\n })),\n };\n }\n\n throw new Error(`Unknown message type: ${message.type}`);\n}\n\n/**\n * Transforms a UPP ContentBlock to Anthropic's content format.\n *\n * Supports text and image content types. Image blocks can be provided\n * as base64, URL, or raw bytes (which are converted to base64).\n *\n * @param block - The UPP content block to transform\n * @param cacheControl - Optional cache control to apply to the block\n * @returns An AnthropicContent object\n * @throws Error if the content type or image source type is unsupported\n */\nfunction transformContentBlock(\n block: ContentBlock,\n cacheControl?: AnthropicCacheControl\n): AnthropicContent {\n switch (block.type) {\n case 'text':\n return {\n type: 'text',\n text: block.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n\n case 'image': {\n const imageBlock = block as ImageBlock;\n if (imageBlock.source.type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: imageBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'url') {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: imageBlock.source.url,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'bytes') {\n const base64 = btoa(\n Array.from(imageBlock.source.data)\n .map((b) => String.fromCharCode(b))\n .join('')\n );\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: base64,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n throw new Error(`Unknown image source type`);\n }\n\n default:\n throw new Error(`Unsupported content type: ${block.type}`);\n }\n}\n\n/**\n * Extracts cache control configuration from tool metadata.\n *\n * @param tool - The tool to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractToolCacheControl(tool: Tool): AnthropicCacheControl | undefined {\n const anthropicMeta = tool.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Tool definition to Anthropic's tool format.\n *\n * Cache control can be specified via tool metadata:\n * ```typescript\n * const tool: Tool = {\n * name: 'search_docs',\n * description: 'Search documentation',\n * parameters: {...},\n * metadata: { anthropic: { cache_control: { type: 'ephemeral' } } },\n * run: async (params) => {...}\n * };\n * ```\n *\n * @param tool - The UPP tool definition\n * @returns An AnthropicTool with the appropriate input schema\n */\nfunction transformTool(tool: Tool): AnthropicTool {\n const cacheControl = extractToolCacheControl(tool);\n\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: 'object',\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n },\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. The json_response tool is treated\n * specially for structured output extraction. Code execution results (stdout)\n * are appended to the text content.\n *\n * @param data - The raw Anthropic API response\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(data: AnthropicResponse): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of data.content) {\n if (block.type === 'text') {\n textContent.push({ type: 'text', text: block.text });\n } else if (block.type === 'tool_use') {\n if (block.name === 'json_response') {\n structuredData = block.input;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: block.input,\n });\n } else if (block.type === 'bash_code_execution_tool_result') {\n // Extract stdout from code execution results and append to text\n if (block.content.type === 'bash_code_execution_result' && block.content.stdout) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.stdout}\\`\\`\\`\\n` });\n }\n } else if (block.type === 'text_editor_code_execution_tool_result') {\n // Extract file content from text editor results\n if (block.content.type === 'text_editor_code_execution_result' && block.content.content) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.content}\\`\\`\\`\\n` });\n }\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: data.id,\n metadata: {\n anthropic: {\n stop_reason: data.stop_reason,\n stop_sequence: data.stop_sequence,\n model: data.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n cacheReadTokens: data.usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: data.usage.cache_creation_input_tokens ?? 0,\n };\n\n return {\n message,\n usage,\n stopReason: data.stop_reason ?? 'end_turn',\n data: structuredData,\n };\n}\n\n/**\n * Mutable state object for accumulating streamed response data.\n *\n * Used during streaming to collect content blocks, token counts, and\n * metadata as events arrive from the Anthropic API.\n */\nexport interface StreamState {\n /** Unique identifier for the message being streamed. */\n messageId: string;\n /** The model that generated this response. */\n model: string;\n /** Accumulated content blocks indexed by their stream position. */\n content: Array<{\n type: string;\n text?: string;\n id?: string;\n name?: string;\n input?: string;\n /** Code execution stdout (for bash_code_execution_tool_result). */\n stdout?: string;\n /** Code execution tool use ID (for result blocks). */\n tool_use_id?: string;\n /** File content (for text_editor_code_execution_tool_result). */\n fileContent?: string;\n }>;\n /** The reason the response ended, if completed. */\n stopReason: string | null;\n /** Number of input tokens consumed. */\n inputTokens: number;\n /** Number of output tokens generated. */\n outputTokens: number;\n /** Number of tokens read from cache (cache hits). */\n cacheReadTokens: number;\n /** Number of tokens written to cache. */\n cacheWriteTokens: number;\n}\n\n/**\n * Creates an initialized StreamState for accumulating streaming responses.\n *\n * @returns A fresh StreamState with empty/default values\n */\nexport function createStreamState(): StreamState {\n return {\n messageId: '',\n model: '',\n content: [],\n stopReason: null,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n}\n\n/**\n * Transforms an Anthropic streaming event to a UPP StreamEvent.\n *\n * Updates the provided state object as a side effect to accumulate\n * response data across multiple events. Returns null for events that\n * don't produce corresponding UPP events (e.g., ping, message_delta).\n *\n * @param event - The Anthropic SSE event to transform\n * @param state - Mutable state object to update with accumulated data\n * @returns A UPP StreamEvent, or null if no event should be emitted\n *\n * @example\n * ```typescript\n * const state = createStreamState();\n * for await (const event of parseSSEStream(response.body)) {\n * const uppEvent = transformStreamEvent(event, state);\n * if (uppEvent) {\n * yield uppEvent;\n * }\n * }\n * const finalResponse = buildResponseFromState(state);\n * ```\n */\nexport function transformStreamEvent(\n event: AnthropicStreamEvent,\n state: StreamState\n): StreamEvent | null {\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 return { type: 'message_start', index: 0, delta: {} };\n\n case 'content_block_start':\n if (event.content_block.type === 'text') {\n state.content[event.index] = { type: 'text', text: '' };\n } else if (event.content_block.type === 'tool_use') {\n state.content[event.index] = {\n type: 'tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'server_tool_use') {\n state.content[event.index] = {\n type: 'server_tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'bash_code_execution_tool_result') {\n // Handle code execution results - extract stdout for text\n const resultBlock = event.content_block as {\n type: 'bash_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; stdout?: string };\n };\n state.content[event.index] = {\n type: 'bash_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n stdout: resultBlock.content?.stdout ?? '',\n };\n } else if (event.content_block.type === 'text_editor_code_execution_tool_result') {\n // Handle text editor results - extract file content\n const resultBlock = event.content_block as {\n type: 'text_editor_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; content?: string };\n };\n state.content[event.index] = {\n type: 'text_editor_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n fileContent: resultBlock.content?.content ?? '',\n };\n }\n return { type: 'content_block_start', index: event.index, delta: {} };\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 return {\n type: 'text_delta',\n index: event.index,\n delta: { text: delta.text },\n };\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 return {\n type: 'tool_call_delta',\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 }\n if (delta.type === 'thinking_delta') {\n return {\n type: 'reasoning_delta',\n index: event.index,\n delta: { text: delta.thinking },\n };\n }\n return null;\n }\n\n case 'content_block_stop':\n return { type: 'content_block_stop', index: event.index, delta: {} };\n\n case 'message_delta':\n state.stopReason = event.delta.stop_reason;\n state.outputTokens = event.usage.output_tokens;\n return null;\n\n case 'message_stop':\n return { type: 'message_stop', index: 0, delta: {} };\n\n case 'ping':\n case 'error':\n return null;\n\n default:\n return null;\n }\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 * @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(state: StreamState): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of state.content) {\n // Skip undefined blocks (can happen with built-in tool results that aren't tracked)\n if (!block) continue;\n\n if (block.type === 'text' && block.text) {\n textContent.push({ type: 'text', text: block.text });\n } else if (block.type === 'tool_use' && block.id && block.name) {\n let args: Record<string, unknown> = {};\n if (block.input) {\n try {\n args = JSON.parse(block.input);\n } catch {\n // Invalid JSON - use empty object\n }\n }\n if (block.name === 'json_response') {\n structuredData = args;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: args,\n });\n } else if (block.type === 'bash_code_execution_tool_result' && block.stdout) {\n // Append code execution stdout to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.stdout}\\`\\`\\`\\n` });\n } else if (block.type === 'text_editor_code_execution_tool_result' && block.fileContent) {\n // Append file content to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.fileContent}\\`\\`\\`\\n` });\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: state.messageId,\n metadata: {\n anthropic: {\n stop_reason: state.stopReason,\n model: state.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.inputTokens + state.outputTokens,\n cacheReadTokens: state.cacheReadTokens,\n cacheWriteTokens: state.cacheWriteTokens,\n };\n\n return {\n message,\n usage,\n stopReason: state.stopReason ?? 'end_turn',\n data: structuredData,\n };\n}\n","/**\n * @fileoverview Anthropic LLM handler implementation.\n *\n * This module provides the core LLM handler for Anthropic's Claude models,\n * implementing both synchronous completion and streaming capabilities.\n */\n\nimport type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';\nimport type { StreamEvent } from '../../types/stream.ts';\nimport type { LLMProvider } from '../../types/provider.ts';\nimport { UPPError } 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 type { AnthropicLLMParams, AnthropicResponse, AnthropicStreamEvent } from './types.ts';\nimport {\n transformRequest,\n transformResponse,\n transformStreamEvent,\n createStreamState,\n buildResponseFromState,\n} from './transform.ts';\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 'INVALID_REQUEST',\n 'anthropic',\n '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 baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId);\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 response.json()) as AnthropicResponse;\n return transformResponse(data);\n },\n\n stream(request: LLMRequest<AnthropicLLMParams>): LLMStreamResult {\n const state = createStreamState();\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);\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 };\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 'PROVIDER_ERROR',\n 'anthropic',\n '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 'PROVIDER_ERROR',\n 'anthropic',\n 'llm'\n );\n responseReject(error);\n throw error;\n }\n\n const uppEvent = transformStreamEvent(event, state);\n if (uppEvent) {\n yield uppEvent;\n }\n }\n }\n\n responseResolve(buildResponseFromState(state));\n } catch (error) {\n responseReject(error as Error);\n throw error;\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","/**\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 * 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 * builtInTools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\n builtInTools?: 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 */\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\n/**\n * A single message in an Anthropic conversation.\n *\n * Messages alternate between 'user' and 'assistant' roles. Content can be\n * a simple string or an array of typed content blocks.\n */\nexport interface AnthropicMessage {\n /** The role of the message sender. */\n role: 'user' | 'assistant';\n /** Message content as string or structured content blocks. */\n content: AnthropicContent[] | string;\n}\n\n/**\n * Union type for all Anthropic content block types.\n *\n * Used in both request messages and response content arrays.\n */\nexport type AnthropicContent =\n | AnthropicTextContent\n | AnthropicImageContent\n | AnthropicToolUseContent\n | AnthropicToolResultContent;\n\n/**\n * Cache control configuration for prompt caching.\n *\n * Marks content blocks for caching to reduce costs and latency\n * on subsequent requests with the same prefix.\n *\n * @example\n * ```typescript\n * const cacheControl: AnthropicCacheControl = {\n * type: 'ephemeral',\n * ttl: '1h' // Optional: extend to 1-hour cache\n * };\n * ```\n */\nexport interface AnthropicCacheControl {\n /** Cache type - only 'ephemeral' is supported */\n type: 'ephemeral';\n /** Optional TTL: '5m' (default) or '1h' for extended caching */\n ttl?: '5m' | '1h';\n}\n\n/**\n * Plain text content block.\n */\nexport interface AnthropicTextContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Image content block for vision capabilities.\n *\n * Images can be provided as base64-encoded data or via URL.\n */\nexport interface AnthropicImageContent {\n /** Content type discriminator. */\n type: 'image';\n /** Image source configuration. */\n source: {\n /** How the image data is provided. */\n type: 'base64' | 'url';\n /** MIME type of the image (required for base64). */\n media_type?: string;\n /** Base64-encoded image data. */\n data?: string;\n /** URL to fetch the image from. */\n url?: string;\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool use content block representing a function call by the assistant.\n *\n * Appears in assistant messages when the model invokes a tool.\n */\nexport interface AnthropicToolUseContent {\n /** Content type discriminator. */\n type: 'tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the tool being called. */\n name: string;\n /** Arguments passed to the tool as a JSON object. */\n input: Record<string, unknown>;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool result content block providing the output of a tool call.\n *\n * Sent in user messages to provide results for previous tool_use blocks.\n */\nexport interface AnthropicToolResultContent {\n /** Content type discriminator. */\n type: 'tool_result';\n /** ID of the tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The result content (string or structured blocks). */\n content: string | AnthropicContent[];\n /** Whether the tool execution resulted in an error. */\n is_error?: boolean;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool definition for Anthropic's function calling feature.\n *\n * Defines a callable function that the model can invoke during generation.\n */\nexport interface AnthropicTool {\n /** Unique name for the tool. */\n name: string;\n /** Description of what the tool does and when to use it. */\n description: string;\n /** JSON Schema defining the expected input parameters. */\n input_schema: {\n /** Schema type (always 'object' for tool inputs). */\n type: 'object';\n /** Property definitions for each parameter. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Complete response from the Anthropic Messages API.\n *\n * Returned from non-streaming requests and contains the full\n * generated content along with usage statistics.\n */\nexport interface AnthropicResponse {\n /** Unique identifier for this response. */\n id: string;\n /** Response type (always 'message'). */\n type: 'message';\n /** Role of the responder (always 'assistant'). */\n role: 'assistant';\n /** Generated content blocks. */\n content: AnthropicResponseContent[];\n /** Model that generated this response. */\n model: string;\n /**\n * Reason the model stopped generating.\n * - `end_turn`: Natural completion\n * - `max_tokens`: Hit token limit\n * - `stop_sequence`: Hit a stop sequence\n * - `tool_use`: Model wants to use a tool\n * - `pause_turn`: Paused for extended thinking\n * - `refusal`: Model refused to respond\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal' | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n /** Token usage statistics. */\n usage: {\n /** Tokens consumed by the input. */\n input_tokens: number;\n /** Tokens generated in the output. */\n output_tokens: number;\n /** Tokens used to create cache entries. */\n cache_creation_input_tokens?: number;\n /** Tokens read from cache. */\n cache_read_input_tokens?: number;\n };\n}\n\n/**\n * Union type for content blocks that can appear in API responses.\n *\n * Includes text, tool use, thinking blocks, and code execution results.\n */\nexport type AnthropicResponseContent =\n | AnthropicTextContent\n | AnthropicToolUseContent\n | AnthropicThinkingContent\n | AnthropicServerToolUseContent\n | AnthropicBashCodeExecutionToolResultContent\n | AnthropicTextEditorCodeExecutionToolResultContent;\n\n/**\n * Thinking content block from extended thinking feature.\n *\n * Contains the model's internal reasoning process when thinking is enabled.\n */\nexport interface AnthropicThinkingContent {\n /** Content type discriminator. */\n type: 'thinking';\n /** The model's thinking/reasoning text. */\n thinking: string;\n /** Cryptographic signature for thinking verification. */\n signature?: string;\n}\n\n/**\n * Server tool use content block for built-in tools like code execution.\n *\n * Appears when Claude invokes a server-side tool.\n */\nexport interface AnthropicServerToolUseContent {\n /** Content type discriminator. */\n type: 'server_tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the server tool being called (e.g., 'bash_code_execution', 'text_editor_code_execution'). */\n name: string;\n /** Arguments passed to the tool. */\n input: Record<string, unknown>;\n}\n\n/**\n * Result from bash code execution tool.\n *\n * Contains stdout, stderr, and return code from command execution.\n */\nexport interface AnthropicBashCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'bash_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The execution result. */\n content: {\n /** Result type discriminator. */\n type: 'bash_code_execution_result';\n /** Standard output from the command. */\n stdout: string;\n /** Standard error from the command. */\n stderr: string;\n /** Exit code (0 for success). */\n return_code: number;\n /** File IDs for any files created during execution. */\n content?: Array<{ file_id: string }>;\n } | {\n /** Error result type. */\n type: 'bash_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Result from text editor code execution tool.\n *\n * Contains file operation results.\n */\nexport interface AnthropicTextEditorCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'text_editor_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The operation result. */\n content: {\n /** Result type discriminator. */\n type: 'text_editor_code_execution_result';\n /** File type (for view operations). */\n file_type?: string;\n /** File content (for view operations). */\n content?: string;\n /** Number of lines returned (for view operations). */\n numLines?: number;\n /** Starting line number (for view operations). */\n startLine?: number;\n /** Total lines in file (for view operations). */\n totalLines?: number;\n /** Whether this was a file update (for create operations). */\n is_file_update?: boolean;\n /** Old start line (for edit operations). */\n oldStart?: number;\n /** Old line count (for edit operations). */\n oldLines?: number;\n /** New start line (for edit operations). */\n newStart?: number;\n /** New line count (for edit operations). */\n newLines?: number;\n /** Diff lines (for edit operations). */\n lines?: string[];\n } | {\n /** Error result type. */\n type: 'text_editor_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Union type for all Server-Sent Events from Anthropic's streaming API.\n *\n * Events are received in a specific order:\n * 1. message_start - Initial message metadata\n * 2. content_block_start - Beginning of each content block\n * 3. content_block_delta - Incremental content updates (multiple)\n * 4. content_block_stop - End of each content block\n * 5. message_delta - Final usage and stop reason\n * 6. message_stop - Stream complete\n */\nexport type AnthropicStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent;\n\n/**\n * Initial event containing message metadata and partial response.\n */\nexport interface AnthropicMessageStartEvent {\n /** Event type discriminator. */\n type: 'message_start';\n /** Partial response with id, model, and input token count. */\n message: AnthropicResponse;\n}\n\n/**\n * Signals the start of a new content block.\n */\nexport interface AnthropicContentBlockStartEvent {\n /** Event type discriminator. */\n type: 'content_block_start';\n /** Zero-based index of this content block. */\n index: number;\n /** Initial content block data (may be empty for streaming). */\n content_block: AnthropicResponseContent;\n}\n\n/**\n * Incremental update to a content block's content.\n *\n * Multiple delta events are sent as content is generated.\n */\nexport interface AnthropicContentBlockDeltaEvent {\n /** Event type discriminator. */\n type: 'content_block_delta';\n /** Index of the content block being updated. */\n index: number;\n /** The incremental content update. */\n delta:\n | { type: 'text_delta'; text: string }\n | { type: 'thinking_delta'; thinking: string }\n | { type: 'signature_delta'; signature: string }\n | { type: 'input_json_delta'; partial_json: string };\n}\n\n/**\n * Signals the end of a content block.\n */\nexport interface AnthropicContentBlockStopEvent {\n /** Event type discriminator. */\n type: 'content_block_stop';\n /** Index of the completed content block. */\n index: number;\n}\n\n/**\n * Final message update with stop reason and output token count.\n */\nexport interface AnthropicMessageDeltaEvent {\n /** Event type discriminator. */\n type: 'message_delta';\n /** Final message metadata. */\n delta: {\n /** Why the model stopped generating. */\n stop_reason: string | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n };\n /** Final usage statistics. */\n usage: {\n /** Total output tokens generated. */\n output_tokens: number;\n };\n}\n\n/**\n * Terminal event indicating the stream is complete.\n */\nexport interface AnthropicMessageStopEvent {\n /** Event type discriminator. */\n type: 'message_stop';\n}\n\n/**\n * Keep-alive event sent periodically during long operations.\n */\nexport interface AnthropicPingEvent {\n /** Event type discriminator. */\n type: 'ping';\n}\n\n/**\n * Error event indicating a problem during streaming.\n */\nexport interface AnthropicErrorEvent {\n /** Event type discriminator. */\n type: 'error';\n /** Error details. */\n error: {\n /** Error type identifier. */\n type: string;\n /** Human-readable error message. */\n message: string;\n };\n}\n\n/**\n * Anthropic-specific HTTP headers for API requests.\n *\n * @example\n * ```typescript\n * const headers: AnthropicHeaders = {\n * 'anthropic-beta': 'extended-cache-ttl-2025-04-11',\n * };\n * ```\n */\nexport interface AnthropicHeaders {\n /**\n * Beta features header.\n *\n * Comma-separated list of beta feature flags:\n * - `extended-cache-ttl-2025-04-11` - Enable 1-hour cache TTL\n * - `token-efficient-tools-2025-02-19` - Token-efficient tool encoding\n * - `computer-use-2025-01-24` - Computer use tool (Claude 4 models)\n * - `computer-use-2025-11-24` - Computer use tool (Claude Opus 4.5)\n * - `code-execution-2025-08-25` - Code execution tool\n * - `advanced-tool-use-2025-11-20` - Tool search tool\n */\n 'anthropic-beta'?: string;\n [key: string]: string | undefined;\n}\n\n// ============================================\n// Built-in Tools\n// ============================================\n\n/**\n * User location for web search context.\n *\n * Used to localize web search results based on the user's approximate location.\n */\nexport interface AnthropicUserLocation {\n /** Location type - must be 'approximate' */\n type: 'approximate';\n /** City name */\n city?: string;\n /** Region/state name */\n region?: string;\n /** ISO 3166-1 alpha-2 country code (e.g., \"US\") */\n country?: string;\n /** IANA timezone (e.g., \"America/New_York\") */\n timezone?: string;\n}\n\n/**\n * Web search tool for real-time web information retrieval.\n *\n * Enables Claude to search the web for up-to-date information.\n * No beta header required - this is a GA feature.\n *\n * @example\n * ```typescript\n * const tool: AnthropicWebSearchTool = {\n * type: 'web_search_20250305',\n * name: 'web_search',\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * };\n * ```\n */\nexport interface AnthropicWebSearchTool {\n /** Tool type identifier */\n type: 'web_search_20250305';\n /** Tool name - must be 'web_search' */\n name: 'web_search';\n /** Maximum searches per request (default: unlimited) */\n max_uses?: number;\n /** Whitelist domains (mutually exclusive with blocked_domains) */\n allowed_domains?: string[];\n /** Blacklist domains (mutually exclusive with allowed_domains) */\n blocked_domains?: string[];\n /** User location for localized results */\n user_location?: AnthropicUserLocation;\n}\n\n/**\n * Computer use tool for desktop automation.\n *\n * Enables Claude to interact with computer interfaces through\n * mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header:\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other Claude 4 models\n *\n * @example\n * ```typescript\n * const tool: AnthropicComputerTool = {\n * type: 'computer_20250124',\n * name: 'computer',\n * display_width_px: 1920,\n * display_height_px: 1080,\n * };\n * ```\n */\nexport interface AnthropicComputerTool {\n /** Tool type identifier (version-specific) */\n type: 'computer_20251124' | 'computer_20250124';\n /** Tool name - must be 'computer' */\n name: 'computer';\n /** Display width in pixels */\n display_width_px: number;\n /** Display height in pixels */\n display_height_px: number;\n /** X11 display number (optional) */\n display_number?: number;\n /** Enable zoom action (Opus 4.5 only with 20251124 version) */\n enable_zoom?: boolean;\n}\n\n/**\n * Text editor tool for file viewing and editing.\n *\n * Enables Claude to view, create, and edit files with\n * commands like view, str_replace, create, and insert.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicTextEditorTool = {\n * type: 'text_editor_20250728',\n * name: 'str_replace_based_edit_tool',\n * max_characters: 10000,\n * };\n * ```\n */\nexport interface AnthropicTextEditorTool {\n /** Tool type identifier (version-specific) */\n type: 'text_editor_20250728' | 'text_editor_20250124';\n /** Tool name (version-specific) */\n name: 'str_replace_based_edit_tool' | 'str_replace_editor';\n /** Max characters for view truncation (20250728+ only) */\n max_characters?: number;\n}\n\n/**\n * Bash tool for shell command execution.\n *\n * Enables Claude to execute bash commands in a shell session.\n * The session persists within the conversation.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicBashTool = {\n * type: 'bash_20250124',\n * name: 'bash',\n * };\n * ```\n */\nexport interface AnthropicBashTool {\n /** Tool type identifier */\n type: 'bash_20250124';\n /** Tool name - must be 'bash' */\n name: 'bash';\n}\n\n/**\n * Code execution tool for sandboxed Python/Bash execution.\n *\n * Enables Claude to write and execute code in a secure container\n * with pre-installed data science libraries.\n *\n * Requires beta header: `code-execution-2025-08-25`\n *\n * @example\n * ```typescript\n * const tool: AnthropicCodeExecutionTool = {\n * type: 'code_execution_20250825',\n * name: 'code_execution',\n * };\n * ```\n */\nexport interface AnthropicCodeExecutionTool {\n /** Tool type identifier */\n type: 'code_execution_20250825';\n /** Tool name - must be 'code_execution' */\n name: 'code_execution';\n}\n\n/**\n * Tool search tool for dynamic tool discovery.\n *\n * Enables Claude to search through large tool catalogs\n * using regex or natural language (BM25) queries.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20`\n *\n * @example\n * ```typescript\n * const tool: AnthropicToolSearchTool = {\n * type: 'tool_search_tool_regex_20251119',\n * name: 'tool_search_tool_regex',\n * };\n * ```\n */\nexport interface AnthropicToolSearchTool {\n /** Tool type identifier (regex or BM25 variant) */\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_bm25_20251119';\n /** Tool name (must match type variant) */\n name: 'tool_search_tool_regex' | 'tool_search_tool_bm25';\n}\n\n/**\n * Union type for all Anthropic built-in tools.\n *\n * Built-in tools run server-side and have special handling\n * different from user-defined function tools.\n */\nexport type AnthropicBuiltInTool =\n | AnthropicWebSearchTool\n | AnthropicComputerTool\n | AnthropicTextEditorTool\n | AnthropicBashTool\n | AnthropicCodeExecutionTool\n | AnthropicToolSearchTool;\n\n/**\n * Combined tool type for API requests (user-defined or built-in).\n */\nexport type AnthropicToolUnion = AnthropicTool | AnthropicBuiltInTool;\n\n// ============================================\n// Tool Helper Constructors\n// ============================================\n\n/**\n * Creates a web search tool configuration.\n *\n * The web search tool enables Claude to search the web for up-to-date information.\n * Pricing: $10 per 1,000 searches plus standard token costs.\n *\n * @param options - Optional configuration for search behavior\n * @returns A web search tool configuration object\n *\n * @example\n * ```typescript\n * // Basic web search\n * const search = webSearchTool();\n *\n * // With configuration\n * const searchWithOptions = webSearchTool({\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * user_location: {\n * type: 'approximate',\n * city: 'San Francisco',\n * country: 'US',\n * },\n * });\n * ```\n */\nexport function webSearchTool(options?: {\n max_uses?: number;\n allowed_domains?: string[];\n blocked_domains?: string[];\n user_location?: AnthropicUserLocation;\n}): AnthropicWebSearchTool {\n return {\n type: 'web_search_20250305',\n name: 'web_search',\n ...options,\n };\n}\n\n/**\n * Creates a computer use tool configuration.\n *\n * The computer tool enables Claude to interact with computer interfaces\n * through mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header (automatically injected when using this tool):\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other models\n *\n * @param options - Display configuration and optional settings\n * @returns A computer tool configuration object\n *\n * @example\n * ```typescript\n * const computer = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * });\n *\n * // For Opus 4.5 with zoom support\n * const computerOpus = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * version: '20251124',\n * enable_zoom: true,\n * });\n * ```\n */\nexport function computerTool(options: {\n display_width_px: number;\n display_height_px: number;\n display_number?: number;\n enable_zoom?: boolean;\n /** Use '20251124' for Claude Opus 4.5, '20250124' for other models */\n version?: '20251124' | '20250124';\n}): AnthropicComputerTool {\n const { version = '20250124', ...rest } = options;\n return {\n type: version === '20251124' ? 'computer_20251124' : 'computer_20250124',\n name: 'computer',\n ...rest,\n };\n}\n\n/**\n * Creates a text editor tool configuration.\n *\n * The text editor tool enables Claude to view, create, and edit files\n * using commands like view, str_replace, create, and insert.\n *\n * Token overhead: ~700 tokens per tool definition.\n *\n * @param options - Optional configuration\n * @returns A text editor tool configuration object\n *\n * @example\n * ```typescript\n * const editor = textEditorTool();\n *\n * // With max characters for view truncation\n * const editorWithLimit = textEditorTool({\n * max_characters: 10000,\n * });\n * ```\n */\nexport function textEditorTool(options?: {\n max_characters?: number;\n /** Use '20250728' for Claude 4, '20250124' for Claude 3.7 */\n version?: '20250728' | '20250124';\n}): AnthropicTextEditorTool {\n const version = options?.version ?? '20250728';\n return {\n type: version === '20250728' ? 'text_editor_20250728' : 'text_editor_20250124',\n name: version === '20250728' ? 'str_replace_based_edit_tool' : 'str_replace_editor',\n ...(options?.max_characters !== undefined && { max_characters: options.max_characters }),\n };\n}\n\n/**\n * Creates a bash tool configuration.\n *\n * The bash tool enables Claude to execute shell commands.\n * Sessions persist within the conversation.\n *\n * Token overhead: ~245 tokens per tool definition.\n *\n * @returns A bash tool configuration object\n *\n * @example\n * ```typescript\n * const bash = bashTool();\n * ```\n */\nexport function bashTool(): AnthropicBashTool {\n return {\n type: 'bash_20250124',\n name: 'bash',\n };\n}\n\n/**\n * Creates a code execution tool configuration.\n *\n * The code execution tool enables Claude to write and execute\n * Python/Bash code in a secure sandboxed container.\n *\n * Requires beta header: `code-execution-2025-08-25` (automatically injected).\n *\n * Pricing:\n * - Free tier: 1,550 hours/month per organization\n * - Additional: $0.05 per hour, per container\n *\n * @returns A code execution tool configuration object\n *\n * @example\n * ```typescript\n * const codeExec = codeExecutionTool();\n * ```\n */\nexport function codeExecutionTool(): AnthropicCodeExecutionTool {\n return {\n type: 'code_execution_20250825',\n name: 'code_execution',\n };\n}\n\n/**\n * Creates a tool search tool configuration.\n *\n * The tool search tool enables Claude to search through large\n * tool catalogs (up to 10,000 tools) using regex or natural language.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20` (automatically injected).\n *\n * @param options - Optional mode selection\n * @returns A tool search tool configuration object\n *\n * @example\n * ```typescript\n * // Regex-based search (default)\n * const search = toolSearchTool();\n *\n * // Natural language (BM25) search\n * const nlSearch = toolSearchTool({ mode: 'bm25' });\n * ```\n */\nexport function toolSearchTool(options?: {\n /** Search mode: 'regex' for pattern matching, 'bm25' for natural language */\n mode?: 'regex' | 'bm25';\n}): AnthropicToolSearchTool {\n const mode = options?.mode ?? 'regex';\n return {\n type: mode === 'regex' ? 'tool_search_tool_regex_20251119' : 'tool_search_tool_bm25_20251119',\n name: mode === 'regex' ? 'tool_search_tool_regex' : 'tool_search_tool_bm25',\n };\n}\n\n/**\n * Namespace object containing all Anthropic tool helper constructors.\n *\n * Provides a convenient way to create built-in tool configurations.\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * builtInTools: [\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","import { createProvider } from '../../core/provider.ts';\nimport { createLLMHandler } from './llm.ts';\n\n/**\n * Anthropic provider instance for the Universal Provider Protocol.\n *\n * Provides access to Claude language models through a unified interface.\n * Currently supports the LLM modality with full streaming, tool use,\n * structured output, and image input capabilities.\n *\n * @example\n * ```typescript\n * import { anthropic } from './providers/anthropic';\n *\n * const claude = anthropic.llm.bind('claude-sonnet-4-20250514');\n * const response = await claude.complete({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * });\n * ```\n *\n * @see {@link AnthropicLLMParams} for provider-specific parameters\n */\nexport const anthropic = createProvider({\n name: 'anthropic',\n version: '1.0.0',\n modalities: {\n llm: createLLMHandler(),\n },\n});\n\nexport { tools } from './types.ts';\nexport type {\n AnthropicLLMParams,\n AnthropicHeaders,\n AnthropicBuiltInTool,\n AnthropicWebSearchTool,\n AnthropicComputerTool,\n AnthropicTextEditorTool,\n AnthropicBashTool,\n AnthropicCodeExecutionTool,\n AnthropicToolSearchTool,\n AnthropicUserLocation,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0DO,SAAS,iBACd,SACA,SACkB;AAClB,QAAM,SAAU,QAAQ,UAAU,CAAC;AACnC,QAAM,EAAE,cAAc,GAAG,WAAW,IAAI;AAExC,QAAM,mBAAqC;AAAA,IACzC,GAAG;AAAA,IACH,OAAO;AAAA,IACP,UAAU,QAAQ,SAAS,IAAI,gBAAgB;AAAA,EACjD;AAEA,MAAI,QAAQ,QAAQ;AAGlB,qBAAiB,SAAS,QAAQ;AAAA,EACpC;AAGA,QAAM,WAAmD,CAAC;AAE1D,MAAI,QAAQ,SAAS,QAAQ,MAAM,SAAS,GAAG;AAE7C,aAAS,KAAK,GAAG,QAAQ,MAAM,IAAI,aAAa,CAAC;AAAA,EACnD;AAGA,MAAI,gBAAgB,aAAa,SAAS,GAAG;AAC3C,aAAS,KAAK,GAAG,YAAY;AAAA,EAC/B;AAEA,MAAI,SAAS,SAAS,GAAG;AACvB,qBAAiB,QAAQ;AACzB,qBAAiB,cAAc,EAAE,MAAM,OAAO;AAAA,EAChD;AAEA,MAAI,QAAQ,WAAW;AACrB,U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;AAAA,EACF;AACF;;;ACmkBO,SAAS,cAAc,SAKH;AACzB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,GAAG;AAAA,EACL;AACF;AA+BO,SAAS,aAAa,SAOH;AACxB,QAAM,EAAE,UAAU,YAAY,GAAG,KAAK,IAAI;AAC1C,SAAO;AAAA,IACL,MAAM,YAAY,aAAa,sBAAsB;AAAA,IACrD,MAAM;AAAA,IACN,GAAG;AAAA,EACL;AACF;AAuBO,SAAS,eAAe,SAIH;AAC1B,QAAM,UAAU,SAAS,WAAW;AACpC,SAAO;AAAA,IACL,MAAM,YAAY,aAAa,yBAAyB;AAAA,IACxD,MAAM,YAAY,aAAa,gCAAgC;AAAA,IAC/D,GAAI,SAAS,mBAAmB,UAAa,EAAE,gBAAgB,QAAQ,eAAe;AAAA,EACxF;AACF;AAiBO,SAAS,WAA8B;AAC5C,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AACF;AAqBO,SAAS,oBAAgD;AAC9D,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AACF;AAsBO,SAAS,eAAe,SAGH;AAC1B,QAAM,OAAO,SAAS,QAAQ;AAC9B,SAAO;AAAA,IACL,MAAM,SAAS,UAAU,oCAAoC;AAAA,IAC7D,MAAM,SAAS,UAAU,2BAA2B;AAAA,EACtD;AACF;AAsBO,IAAM,QAAQ;AAAA;AAAA,EAEnB,WAAW;AAAA;AAAA,EAEX,UAAU;AAAA;AAAA,EAEV,YAAY;AAAA;AAAA,EAEZ,MAAM;AAAA;AAAA,EAEN,eAAe;AAAA;AAAA,EAEf,YAAY;AACd;;;AC5+BO,IAAM,YAAY,eAAe;AAAA,EACtC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,YAAY;AAAA,IACV,KAAK,iBAAiB;AAAA,EACxB;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../src/providers/anthropic/transform.ts","../../src/providers/anthropic/llm.ts","../../src/providers/anthropic/types.ts","../../src/providers/anthropic/index.ts"],"sourcesContent":["/**\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 type { StreamEvent } from '../../types/stream.ts';\nimport type { Tool, ToolCall } from '../../types/tool.ts';\nimport type { TokenUsage } from '../../types/turn.ts';\nimport type { ContentBlock, TextBlock, ImageBlock } from '../../types/content.ts';\nimport {\n AssistantMessage,\n isUserMessage,\n isAssistantMessage,\n isToolResultMessage,\n} from '../../types/messages.ts';\nimport type {\n AnthropicLLMParams,\n AnthropicRequest,\n AnthropicMessage,\n AnthropicContent,\n AnthropicTool,\n AnthropicResponse,\n AnthropicStreamEvent,\n AnthropicCacheControl,\n AnthropicSystemContent,\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 * @returns An AnthropicRequest ready for the Messages API\n *\n * @example\n * ```typescript\n * const anthropicRequest = transformRequest({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * params: { max_tokens: 1024, temperature: 0.7 },\n * }, 'claude-sonnet-4-20250514');\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): AnthropicRequest {\n const params = (request.params ?? {}) as AnthropicLLMParams;\n const { builtInTools, ...restParams } = params;\n\n const anthropicRequest: AnthropicRequest = {\n ...restParams,\n model: modelId,\n messages: request.messages.map(transformMessage),\n };\n\n if (request.system) {\n // Pass through directly - accepts string or array of AnthropicSystemContent\n // Array format enables cache_control: [{type: 'text', text: '...', cache_control: {...}}]\n anthropicRequest.system = request.system as string | AnthropicSystemContent[];\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 // For tool caching, use params.tools directly with native 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 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 },\n };\n\n anthropicRequest.tools = [...(anthropicRequest.tools ?? []), structuredTool];\n anthropicRequest.tool_choice = { type: 'tool', name: 'json_response' };\n }\n\n return anthropicRequest;\n}\n\n/**\n * Filters content blocks to include only those with a valid type property.\n *\n * @param content - Array of content blocks to filter\n * @returns Filtered array containing only blocks with a string type property\n */\nfunction filterValidContent<T extends { type?: string }>(content: T[]): T[] {\n return content.filter((c) => c && typeof c.type === 'string');\n}\n\n/**\n * Extracts cache control configuration from message metadata.\n *\n * @param message - The message to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractCacheControl(message: Message): AnthropicCacheControl | undefined {\n const anthropicMeta = message.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Message to Anthropic's message format.\n *\n * Handles three message types:\n * - UserMessage: Converted with content blocks\n * - AssistantMessage: Includes text and tool_use blocks\n * - ToolResultMessage: Converted to user role with tool_result content\n *\n * Cache control can be specified via message metadata:\n * ```typescript\n * new UserMessage(content, {\n * metadata: { anthropic: { cache_control: { type: \"ephemeral\" } } }\n * })\n * ```\n *\n * @param message - The UPP message to transform\n * @returns An AnthropicMessage with the appropriate role and content\n * @throws Error if the message type is unknown\n */\nfunction transformMessage(message: Message): AnthropicMessage {\n const cacheControl = extractCacheControl(message);\n\n if (isUserMessage(message)) {\n const validContent = filterValidContent(message.content);\n const contentBlocks = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 ? cacheControl : undefined)\n );\n return {\n role: 'user',\n content: contentBlocks,\n };\n }\n\n if (isAssistantMessage(message)) {\n const validContent = filterValidContent(message.content);\n const content: AnthropicContent[] = validContent.map((block, index, arr) =>\n transformContentBlock(block, index === arr.length - 1 && !message.toolCalls?.length ? cacheControl : undefined)\n );\n\n if (message.toolCalls) {\n for (let i = 0; i < message.toolCalls.length; i++) {\n const call = message.toolCalls[i]!;\n const isLast = i === message.toolCalls.length - 1;\n content.push({\n type: 'tool_use',\n id: call.toolCallId,\n name: call.toolName,\n input: call.arguments,\n ...(isLast && cacheControl ? { cache_control: cacheControl } : {}),\n });\n }\n }\n\n return {\n role: 'assistant',\n content,\n };\n }\n\n if (isToolResultMessage(message)) {\n return {\n role: 'user',\n content: message.results.map((result, index, arr) => ({\n type: 'tool_result' as const,\n tool_use_id: result.toolCallId,\n content:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n is_error: result.isError,\n ...(index === arr.length - 1 && cacheControl ? { cache_control: cacheControl } : {}),\n })),\n };\n }\n\n throw new Error(`Unknown message type: ${message.type}`);\n}\n\n/**\n * Transforms a UPP ContentBlock to Anthropic's content format.\n *\n * Supports text and image content types. Image blocks can be provided\n * as base64, URL, or raw bytes (which are converted to base64).\n *\n * @param block - The UPP content block to transform\n * @param cacheControl - Optional cache control to apply to the block\n * @returns An AnthropicContent object\n * @throws Error if the content type or image source type is unsupported\n */\nfunction transformContentBlock(\n block: ContentBlock,\n cacheControl?: AnthropicCacheControl\n): AnthropicContent {\n switch (block.type) {\n case 'text':\n return {\n type: 'text',\n text: block.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n\n case 'image': {\n const imageBlock = block as ImageBlock;\n if (imageBlock.source.type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: imageBlock.source.data,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'url') {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: imageBlock.source.url,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n if (imageBlock.source.type === 'bytes') {\n const base64 = btoa(\n Array.from(imageBlock.source.data)\n .map((b) => String.fromCharCode(b))\n .join('')\n );\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: imageBlock.mimeType,\n data: base64,\n },\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n }\n throw new Error(`Unknown image source type`);\n }\n\n default:\n throw new Error(`Unsupported content type: ${block.type}`);\n }\n}\n\n/**\n * Extracts cache control configuration from tool metadata.\n *\n * @param tool - The tool to extract cache control from\n * @returns The cache control configuration if present, undefined otherwise\n */\nfunction extractToolCacheControl(tool: Tool): AnthropicCacheControl | undefined {\n const anthropicMeta = tool.metadata?.anthropic as\n | { cache_control?: AnthropicCacheControl }\n | undefined;\n return anthropicMeta?.cache_control;\n}\n\n/**\n * Transforms a UPP Tool definition to Anthropic's tool format.\n *\n * Cache control can be specified via tool metadata:\n * ```typescript\n * const tool: Tool = {\n * name: 'search_docs',\n * description: 'Search documentation',\n * parameters: {...},\n * metadata: { anthropic: { cache_control: { type: 'ephemeral' } } },\n * run: async (params) => {...}\n * };\n * ```\n *\n * @param tool - The UPP tool definition\n * @returns An AnthropicTool with the appropriate input schema\n */\nfunction transformTool(tool: Tool): AnthropicTool {\n const cacheControl = extractToolCacheControl(tool);\n\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: 'object',\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n },\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. The json_response tool is treated\n * specially for structured output extraction. Code execution results (stdout)\n * are appended to the text content.\n *\n * @param data - The raw Anthropic API response\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(data: AnthropicResponse): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of data.content) {\n if (block.type === 'text') {\n textContent.push({ type: 'text', text: block.text });\n } else if (block.type === 'tool_use') {\n if (block.name === 'json_response') {\n structuredData = block.input;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: block.input,\n });\n } else if (block.type === 'bash_code_execution_tool_result') {\n // Extract stdout from code execution results and append to text\n if (block.content.type === 'bash_code_execution_result' && block.content.stdout) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.stdout}\\`\\`\\`\\n` });\n }\n } else if (block.type === 'text_editor_code_execution_tool_result') {\n // Extract file content from text editor results\n if (block.content.type === 'text_editor_code_execution_result' && block.content.content) {\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.content.content}\\`\\`\\`\\n` });\n }\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: data.id,\n metadata: {\n anthropic: {\n stop_reason: data.stop_reason,\n stop_sequence: data.stop_sequence,\n model: data.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n cacheReadTokens: data.usage.cache_read_input_tokens ?? 0,\n cacheWriteTokens: data.usage.cache_creation_input_tokens ?? 0,\n };\n\n return {\n message,\n usage,\n stopReason: data.stop_reason ?? 'end_turn',\n data: structuredData,\n };\n}\n\n/**\n * Mutable state object for accumulating streamed response data.\n *\n * Used during streaming to collect content blocks, token counts, and\n * metadata as events arrive from the Anthropic API.\n */\nexport interface StreamState {\n /** Unique identifier for the message being streamed. */\n messageId: string;\n /** The model that generated this response. */\n model: string;\n /** Accumulated content blocks indexed by their stream position. */\n content: Array<{\n type: string;\n text?: string;\n id?: string;\n name?: string;\n input?: string;\n /** Code execution stdout (for bash_code_execution_tool_result). */\n stdout?: string;\n /** Code execution tool use ID (for result blocks). */\n tool_use_id?: string;\n /** File content (for text_editor_code_execution_tool_result). */\n fileContent?: string;\n }>;\n /** The reason the response ended, if completed. */\n stopReason: string | null;\n /** Number of input tokens consumed. */\n inputTokens: number;\n /** Number of output tokens generated. */\n outputTokens: number;\n /** Number of tokens read from cache (cache hits). */\n cacheReadTokens: number;\n /** Number of tokens written to cache. */\n cacheWriteTokens: number;\n}\n\n/**\n * Creates an initialized StreamState for accumulating streaming responses.\n *\n * @returns A fresh StreamState with empty/default values\n */\nexport function createStreamState(): StreamState {\n return {\n messageId: '',\n model: '',\n content: [],\n stopReason: null,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n };\n}\n\n/**\n * Transforms an Anthropic streaming event to a UPP StreamEvent.\n *\n * Updates the provided state object as a side effect to accumulate\n * response data across multiple events. Returns null for events that\n * don't produce corresponding UPP events (e.g., ping, message_delta).\n *\n * @param event - The Anthropic SSE event to transform\n * @param state - Mutable state object to update with accumulated data\n * @returns A UPP StreamEvent, or null if no event should be emitted\n *\n * @example\n * ```typescript\n * const state = createStreamState();\n * for await (const event of parseSSEStream(response.body)) {\n * const uppEvent = transformStreamEvent(event, state);\n * if (uppEvent) {\n * yield uppEvent;\n * }\n * }\n * const finalResponse = buildResponseFromState(state);\n * ```\n */\nexport function transformStreamEvent(\n event: AnthropicStreamEvent,\n state: StreamState\n): StreamEvent | null {\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 return { type: 'message_start', index: 0, delta: {} };\n\n case 'content_block_start':\n if (event.content_block.type === 'text') {\n state.content[event.index] = { type: 'text', text: '' };\n } else if (event.content_block.type === 'tool_use') {\n state.content[event.index] = {\n type: 'tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'server_tool_use') {\n state.content[event.index] = {\n type: 'server_tool_use',\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n };\n } else if (event.content_block.type === 'bash_code_execution_tool_result') {\n // Handle code execution results - extract stdout for text\n const resultBlock = event.content_block as {\n type: 'bash_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; stdout?: string };\n };\n state.content[event.index] = {\n type: 'bash_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n stdout: resultBlock.content?.stdout ?? '',\n };\n } else if (event.content_block.type === 'text_editor_code_execution_tool_result') {\n // Handle text editor results - extract file content\n const resultBlock = event.content_block as {\n type: 'text_editor_code_execution_tool_result';\n tool_use_id: string;\n content?: { type: string; content?: string };\n };\n state.content[event.index] = {\n type: 'text_editor_code_execution_tool_result',\n tool_use_id: resultBlock.tool_use_id,\n fileContent: resultBlock.content?.content ?? '',\n };\n }\n return { type: 'content_block_start', index: event.index, delta: {} };\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 return {\n type: 'text_delta',\n index: event.index,\n delta: { text: delta.text },\n };\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 return {\n type: 'tool_call_delta',\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 }\n if (delta.type === 'thinking_delta') {\n return {\n type: 'reasoning_delta',\n index: event.index,\n delta: { text: delta.thinking },\n };\n }\n return null;\n }\n\n case 'content_block_stop':\n return { type: 'content_block_stop', index: event.index, delta: {} };\n\n case 'message_delta':\n state.stopReason = event.delta.stop_reason;\n state.outputTokens = event.usage.output_tokens;\n return null;\n\n case 'message_stop':\n return { type: 'message_stop', index: 0, delta: {} };\n\n case 'ping':\n case 'error':\n return null;\n\n default:\n return null;\n }\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 * @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(state: StreamState): LLMResponse {\n const textContent: TextBlock[] = [];\n const toolCalls: ToolCall[] = [];\n let structuredData: unknown;\n\n for (const block of state.content) {\n // Skip undefined blocks (can happen with built-in tool results that aren't tracked)\n if (!block) continue;\n\n if (block.type === 'text' && block.text) {\n textContent.push({ type: 'text', text: block.text });\n } else if (block.type === 'tool_use' && block.id && block.name) {\n let args: Record<string, unknown> = {};\n if (block.input) {\n try {\n args = JSON.parse(block.input);\n } catch {\n // Invalid JSON - use empty object\n }\n }\n if (block.name === 'json_response') {\n structuredData = args;\n }\n toolCalls.push({\n toolCallId: block.id,\n toolName: block.name,\n arguments: args,\n });\n } else if (block.type === 'bash_code_execution_tool_result' && block.stdout) {\n // Append code execution stdout to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.stdout}\\`\\`\\`\\n` });\n } else if (block.type === 'text_editor_code_execution_tool_result' && block.fileContent) {\n // Append file content to text content\n textContent.push({ type: 'text', text: `\\n\\`\\`\\`\\n${block.fileContent}\\`\\`\\`\\n` });\n }\n // server_tool_use blocks are tracked for context but don't produce output\n }\n\n const message = new AssistantMessage(\n textContent,\n toolCalls.length > 0 ? toolCalls : undefined,\n {\n id: state.messageId,\n metadata: {\n anthropic: {\n stop_reason: state.stopReason,\n model: state.model,\n },\n },\n }\n );\n\n const usage: TokenUsage = {\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.inputTokens + state.outputTokens,\n cacheReadTokens: state.cacheReadTokens,\n cacheWriteTokens: state.cacheWriteTokens,\n };\n\n return {\n message,\n usage,\n stopReason: state.stopReason ?? 'end_turn',\n data: structuredData,\n };\n}\n","/**\n * @fileoverview Anthropic LLM handler implementation.\n *\n * This module provides the core LLM handler for Anthropic's Claude models,\n * implementing both synchronous completion and streaming capabilities.\n */\n\nimport type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';\nimport type { StreamEvent } from '../../types/stream.ts';\nimport type { LLMProvider } from '../../types/provider.ts';\nimport { UPPError } 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 type { AnthropicLLMParams, AnthropicResponse, AnthropicStreamEvent } from './types.ts';\nimport {\n transformRequest,\n transformResponse,\n transformStreamEvent,\n createStreamState,\n buildResponseFromState,\n} from './transform.ts';\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 'INVALID_REQUEST',\n 'anthropic',\n '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 baseUrl = request.config.baseUrl ?? ANTHROPIC_API_URL;\n const body = transformRequest(request, modelId);\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 response.json()) as AnthropicResponse;\n return transformResponse(data);\n },\n\n stream(request: LLMRequest<AnthropicLLMParams>): LLMStreamResult {\n const state = createStreamState();\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);\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 };\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 'PROVIDER_ERROR',\n 'anthropic',\n '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 'PROVIDER_ERROR',\n 'anthropic',\n 'llm'\n );\n responseReject(error);\n throw error;\n }\n\n const uppEvent = transformStreamEvent(event, state);\n if (uppEvent) {\n yield uppEvent;\n }\n }\n }\n\n responseResolve(buildResponseFromState(state));\n } catch (error) {\n responseReject(error as Error);\n throw error;\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","/**\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 * 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 * builtInTools: [\n * tools.webSearch({ max_uses: 5 }),\n * tools.codeExecution(),\n * ],\n * },\n * });\n * ```\n */\n builtInTools?: 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 */\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\n/**\n * A single message in an Anthropic conversation.\n *\n * Messages alternate between 'user' and 'assistant' roles. Content can be\n * a simple string or an array of typed content blocks.\n */\nexport interface AnthropicMessage {\n /** The role of the message sender. */\n role: 'user' | 'assistant';\n /** Message content as string or structured content blocks. */\n content: AnthropicContent[] | string;\n}\n\n/**\n * Union type for all Anthropic content block types.\n *\n * Used in both request messages and response content arrays.\n */\nexport type AnthropicContent =\n | AnthropicTextContent\n | AnthropicImageContent\n | AnthropicToolUseContent\n | AnthropicToolResultContent;\n\n/**\n * Cache control configuration for prompt caching.\n *\n * Marks content blocks for caching to reduce costs and latency\n * on subsequent requests with the same prefix.\n *\n * @example\n * ```typescript\n * const cacheControl: AnthropicCacheControl = {\n * type: 'ephemeral',\n * ttl: '1h' // Optional: extend to 1-hour cache\n * };\n * ```\n */\nexport interface AnthropicCacheControl {\n /** Cache type - only 'ephemeral' is supported */\n type: 'ephemeral';\n /** Optional TTL: '5m' (default) or '1h' for extended caching */\n ttl?: '5m' | '1h';\n}\n\n/**\n * Plain text content block.\n */\nexport interface AnthropicTextContent {\n /** Content type discriminator. */\n type: 'text';\n /** The text content. */\n text: string;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Image content block for vision capabilities.\n *\n * Images can be provided as base64-encoded data or via URL.\n */\nexport interface AnthropicImageContent {\n /** Content type discriminator. */\n type: 'image';\n /** Image source configuration. */\n source: {\n /** How the image data is provided. */\n type: 'base64' | 'url';\n /** MIME type of the image (required for base64). */\n media_type?: string;\n /** Base64-encoded image data. */\n data?: string;\n /** URL to fetch the image from. */\n url?: string;\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool use content block representing a function call by the assistant.\n *\n * Appears in assistant messages when the model invokes a tool.\n */\nexport interface AnthropicToolUseContent {\n /** Content type discriminator. */\n type: 'tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the tool being called. */\n name: string;\n /** Arguments passed to the tool as a JSON object. */\n input: Record<string, unknown>;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool result content block providing the output of a tool call.\n *\n * Sent in user messages to provide results for previous tool_use blocks.\n */\nexport interface AnthropicToolResultContent {\n /** Content type discriminator. */\n type: 'tool_result';\n /** ID of the tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The result content (string or structured blocks). */\n content: string | AnthropicContent[];\n /** Whether the tool execution resulted in an error. */\n is_error?: boolean;\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Tool definition for Anthropic's function calling feature.\n *\n * Defines a callable function that the model can invoke during generation.\n */\nexport interface AnthropicTool {\n /** Unique name for the tool. */\n name: string;\n /** Description of what the tool does and when to use it. */\n description: string;\n /** JSON Schema defining the expected input parameters. */\n input_schema: {\n /** Schema type (always 'object' for tool inputs). */\n type: 'object';\n /** Property definitions for each parameter. */\n properties: Record<string, unknown>;\n /** List of required property names. */\n required?: string[];\n };\n /** Cache control for prompt caching. */\n cache_control?: AnthropicCacheControl;\n}\n\n/**\n * Complete response from the Anthropic Messages API.\n *\n * Returned from non-streaming requests and contains the full\n * generated content along with usage statistics.\n */\nexport interface AnthropicResponse {\n /** Unique identifier for this response. */\n id: string;\n /** Response type (always 'message'). */\n type: 'message';\n /** Role of the responder (always 'assistant'). */\n role: 'assistant';\n /** Generated content blocks. */\n content: AnthropicResponseContent[];\n /** Model that generated this response. */\n model: string;\n /**\n * Reason the model stopped generating.\n * - `end_turn`: Natural completion\n * - `max_tokens`: Hit token limit\n * - `stop_sequence`: Hit a stop sequence\n * - `tool_use`: Model wants to use a tool\n * - `pause_turn`: Paused for extended thinking\n * - `refusal`: Model refused to respond\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal' | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n /** Token usage statistics. */\n usage: {\n /** Tokens consumed by the input. */\n input_tokens: number;\n /** Tokens generated in the output. */\n output_tokens: number;\n /** Tokens used to create cache entries. */\n cache_creation_input_tokens?: number;\n /** Tokens read from cache. */\n cache_read_input_tokens?: number;\n };\n}\n\n/**\n * Union type for content blocks that can appear in API responses.\n *\n * Includes text, tool use, thinking blocks, and code execution results.\n */\nexport type AnthropicResponseContent =\n | AnthropicTextContent\n | AnthropicToolUseContent\n | AnthropicThinkingContent\n | AnthropicServerToolUseContent\n | AnthropicBashCodeExecutionToolResultContent\n | AnthropicTextEditorCodeExecutionToolResultContent;\n\n/**\n * Thinking content block from extended thinking feature.\n *\n * Contains the model's internal reasoning process when thinking is enabled.\n */\nexport interface AnthropicThinkingContent {\n /** Content type discriminator. */\n type: 'thinking';\n /** The model's thinking/reasoning text. */\n thinking: string;\n /** Cryptographic signature for thinking verification. */\n signature?: string;\n}\n\n/**\n * Server tool use content block for built-in tools like code execution.\n *\n * Appears when Claude invokes a server-side tool.\n */\nexport interface AnthropicServerToolUseContent {\n /** Content type discriminator. */\n type: 'server_tool_use';\n /** Unique identifier for this tool invocation. */\n id: string;\n /** Name of the server tool being called (e.g., 'bash_code_execution', 'text_editor_code_execution'). */\n name: string;\n /** Arguments passed to the tool. */\n input: Record<string, unknown>;\n}\n\n/**\n * Result from bash code execution tool.\n *\n * Contains stdout, stderr, and return code from command execution.\n */\nexport interface AnthropicBashCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'bash_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The execution result. */\n content: {\n /** Result type discriminator. */\n type: 'bash_code_execution_result';\n /** Standard output from the command. */\n stdout: string;\n /** Standard error from the command. */\n stderr: string;\n /** Exit code (0 for success). */\n return_code: number;\n /** File IDs for any files created during execution. */\n content?: Array<{ file_id: string }>;\n } | {\n /** Error result type. */\n type: 'bash_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Result from text editor code execution tool.\n *\n * Contains file operation results.\n */\nexport interface AnthropicTextEditorCodeExecutionToolResultContent {\n /** Content type discriminator. */\n type: 'text_editor_code_execution_tool_result';\n /** ID of the server_tool_use block this result corresponds to. */\n tool_use_id: string;\n /** The operation result. */\n content: {\n /** Result type discriminator. */\n type: 'text_editor_code_execution_result';\n /** File type (for view operations). */\n file_type?: string;\n /** File content (for view operations). */\n content?: string;\n /** Number of lines returned (for view operations). */\n numLines?: number;\n /** Starting line number (for view operations). */\n startLine?: number;\n /** Total lines in file (for view operations). */\n totalLines?: number;\n /** Whether this was a file update (for create operations). */\n is_file_update?: boolean;\n /** Old start line (for edit operations). */\n oldStart?: number;\n /** Old line count (for edit operations). */\n oldLines?: number;\n /** New start line (for edit operations). */\n newStart?: number;\n /** New line count (for edit operations). */\n newLines?: number;\n /** Diff lines (for edit operations). */\n lines?: string[];\n } | {\n /** Error result type. */\n type: 'text_editor_code_execution_tool_result_error';\n /** Error code. */\n error_code: string;\n };\n}\n\n/**\n * Union type for all Server-Sent Events from Anthropic's streaming API.\n *\n * Events are received in a specific order:\n * 1. message_start - Initial message metadata\n * 2. content_block_start - Beginning of each content block\n * 3. content_block_delta - Incremental content updates (multiple)\n * 4. content_block_stop - End of each content block\n * 5. message_delta - Final usage and stop reason\n * 6. message_stop - Stream complete\n */\nexport type AnthropicStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent;\n\n/**\n * Initial event containing message metadata and partial response.\n */\nexport interface AnthropicMessageStartEvent {\n /** Event type discriminator. */\n type: 'message_start';\n /** Partial response with id, model, and input token count. */\n message: AnthropicResponse;\n}\n\n/**\n * Signals the start of a new content block.\n */\nexport interface AnthropicContentBlockStartEvent {\n /** Event type discriminator. */\n type: 'content_block_start';\n /** Zero-based index of this content block. */\n index: number;\n /** Initial content block data (may be empty for streaming). */\n content_block: AnthropicResponseContent;\n}\n\n/**\n * Incremental update to a content block's content.\n *\n * Multiple delta events are sent as content is generated.\n */\nexport interface AnthropicContentBlockDeltaEvent {\n /** Event type discriminator. */\n type: 'content_block_delta';\n /** Index of the content block being updated. */\n index: number;\n /** The incremental content update. */\n delta:\n | { type: 'text_delta'; text: string }\n | { type: 'thinking_delta'; thinking: string }\n | { type: 'signature_delta'; signature: string }\n | { type: 'input_json_delta'; partial_json: string };\n}\n\n/**\n * Signals the end of a content block.\n */\nexport interface AnthropicContentBlockStopEvent {\n /** Event type discriminator. */\n type: 'content_block_stop';\n /** Index of the completed content block. */\n index: number;\n}\n\n/**\n * Final message update with stop reason and output token count.\n */\nexport interface AnthropicMessageDeltaEvent {\n /** Event type discriminator. */\n type: 'message_delta';\n /** Final message metadata. */\n delta: {\n /** Why the model stopped generating. */\n stop_reason: string | null;\n /** The stop sequence that was matched, if any. */\n stop_sequence: string | null;\n };\n /** Final usage statistics. */\n usage: {\n /** Total output tokens generated. */\n output_tokens: number;\n };\n}\n\n/**\n * Terminal event indicating the stream is complete.\n */\nexport interface AnthropicMessageStopEvent {\n /** Event type discriminator. */\n type: 'message_stop';\n}\n\n/**\n * Keep-alive event sent periodically during long operations.\n */\nexport interface AnthropicPingEvent {\n /** Event type discriminator. */\n type: 'ping';\n}\n\n/**\n * Error event indicating a problem during streaming.\n */\nexport interface AnthropicErrorEvent {\n /** Event type discriminator. */\n type: 'error';\n /** Error details. */\n error: {\n /** Error type identifier. */\n type: string;\n /** Human-readable error message. */\n message: string;\n };\n}\n\n/**\n * Anthropic-specific HTTP headers for API requests.\n *\n * @example\n * ```typescript\n * const headers: AnthropicHeaders = {\n * 'anthropic-beta': 'extended-cache-ttl-2025-04-11',\n * };\n * ```\n */\nexport interface AnthropicHeaders {\n /**\n * Beta features header.\n *\n * Comma-separated list of beta feature flags:\n * - `extended-cache-ttl-2025-04-11` - Enable 1-hour cache TTL\n * - `token-efficient-tools-2025-02-19` - Token-efficient tool encoding\n * - `computer-use-2025-01-24` - Computer use tool (Claude 4 models)\n * - `computer-use-2025-11-24` - Computer use tool (Claude Opus 4.5)\n * - `code-execution-2025-08-25` - Code execution tool\n * - `advanced-tool-use-2025-11-20` - Tool search tool\n */\n 'anthropic-beta'?: string;\n [key: string]: string | undefined;\n}\n\n// ============================================\n// Built-in Tools\n// ============================================\n\n/**\n * User location for web search context.\n *\n * Used to localize web search results based on the user's approximate location.\n */\nexport interface AnthropicUserLocation {\n /** Location type - must be 'approximate' */\n type: 'approximate';\n /** City name */\n city?: string;\n /** Region/state name */\n region?: string;\n /** ISO 3166-1 alpha-2 country code (e.g., \"US\") */\n country?: string;\n /** IANA timezone (e.g., \"America/New_York\") */\n timezone?: string;\n}\n\n/**\n * Web search tool for real-time web information retrieval.\n *\n * Enables Claude to search the web for up-to-date information.\n * No beta header required - this is a GA feature.\n *\n * @example\n * ```typescript\n * const tool: AnthropicWebSearchTool = {\n * type: 'web_search_20250305',\n * name: 'web_search',\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * };\n * ```\n */\nexport interface AnthropicWebSearchTool {\n /** Tool type identifier */\n type: 'web_search_20250305';\n /** Tool name - must be 'web_search' */\n name: 'web_search';\n /** Maximum searches per request (default: unlimited) */\n max_uses?: number;\n /** Whitelist domains (mutually exclusive with blocked_domains) */\n allowed_domains?: string[];\n /** Blacklist domains (mutually exclusive with allowed_domains) */\n blocked_domains?: string[];\n /** User location for localized results */\n user_location?: AnthropicUserLocation;\n}\n\n/**\n * Computer use tool for desktop automation.\n *\n * Enables Claude to interact with computer interfaces through\n * mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header:\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other Claude 4 models\n *\n * @example\n * ```typescript\n * const tool: AnthropicComputerTool = {\n * type: 'computer_20250124',\n * name: 'computer',\n * display_width_px: 1920,\n * display_height_px: 1080,\n * };\n * ```\n */\nexport interface AnthropicComputerTool {\n /** Tool type identifier (version-specific) */\n type: 'computer_20251124' | 'computer_20250124';\n /** Tool name - must be 'computer' */\n name: 'computer';\n /** Display width in pixels */\n display_width_px: number;\n /** Display height in pixels */\n display_height_px: number;\n /** X11 display number (optional) */\n display_number?: number;\n /** Enable zoom action (Opus 4.5 only with 20251124 version) */\n enable_zoom?: boolean;\n}\n\n/**\n * Text editor tool for file viewing and editing.\n *\n * Enables Claude to view, create, and edit files with\n * commands like view, str_replace, create, and insert.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicTextEditorTool = {\n * type: 'text_editor_20250728',\n * name: 'str_replace_based_edit_tool',\n * max_characters: 10000,\n * };\n * ```\n */\nexport interface AnthropicTextEditorTool {\n /** Tool type identifier (version-specific) */\n type: 'text_editor_20250728' | 'text_editor_20250124';\n /** Tool name (version-specific) */\n name: 'str_replace_based_edit_tool' | 'str_replace_editor';\n /** Max characters for view truncation (20250728+ only) */\n max_characters?: number;\n}\n\n/**\n * Bash tool for shell command execution.\n *\n * Enables Claude to execute bash commands in a shell session.\n * The session persists within the conversation.\n *\n * No beta header required.\n *\n * @example\n * ```typescript\n * const tool: AnthropicBashTool = {\n * type: 'bash_20250124',\n * name: 'bash',\n * };\n * ```\n */\nexport interface AnthropicBashTool {\n /** Tool type identifier */\n type: 'bash_20250124';\n /** Tool name - must be 'bash' */\n name: 'bash';\n}\n\n/**\n * Code execution tool for sandboxed Python/Bash execution.\n *\n * Enables Claude to write and execute code in a secure container\n * with pre-installed data science libraries.\n *\n * Requires beta header: `code-execution-2025-08-25`\n *\n * @example\n * ```typescript\n * const tool: AnthropicCodeExecutionTool = {\n * type: 'code_execution_20250825',\n * name: 'code_execution',\n * };\n * ```\n */\nexport interface AnthropicCodeExecutionTool {\n /** Tool type identifier */\n type: 'code_execution_20250825';\n /** Tool name - must be 'code_execution' */\n name: 'code_execution';\n}\n\n/**\n * Tool search tool for dynamic tool discovery.\n *\n * Enables Claude to search through large tool catalogs\n * using regex or natural language (BM25) queries.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20`\n *\n * @example\n * ```typescript\n * const tool: AnthropicToolSearchTool = {\n * type: 'tool_search_tool_regex_20251119',\n * name: 'tool_search_tool_regex',\n * };\n * ```\n */\nexport interface AnthropicToolSearchTool {\n /** Tool type identifier (regex or BM25 variant) */\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_bm25_20251119';\n /** Tool name (must match type variant) */\n name: 'tool_search_tool_regex' | 'tool_search_tool_bm25';\n}\n\n/**\n * Union type for all Anthropic built-in tools.\n *\n * Built-in tools run server-side and have special handling\n * different from user-defined function tools.\n */\nexport type AnthropicBuiltInTool =\n | AnthropicWebSearchTool\n | AnthropicComputerTool\n | AnthropicTextEditorTool\n | AnthropicBashTool\n | AnthropicCodeExecutionTool\n | AnthropicToolSearchTool;\n\n/**\n * Combined tool type for API requests (user-defined or built-in).\n */\nexport type AnthropicToolUnion = AnthropicTool | AnthropicBuiltInTool;\n\n// ============================================\n// Tool Helper Constructors\n// ============================================\n\n/**\n * Creates a web search tool configuration.\n *\n * The web search tool enables Claude to search the web for up-to-date information.\n * Pricing: $10 per 1,000 searches plus standard token costs.\n *\n * @param options - Optional configuration for search behavior\n * @returns A web search tool configuration object\n *\n * @example\n * ```typescript\n * // Basic web search\n * const search = webSearchTool();\n *\n * // With configuration\n * const searchWithOptions = webSearchTool({\n * max_uses: 5,\n * allowed_domains: ['wikipedia.org', 'github.com'],\n * user_location: {\n * type: 'approximate',\n * city: 'San Francisco',\n * country: 'US',\n * },\n * });\n * ```\n */\nexport function webSearchTool(options?: {\n max_uses?: number;\n allowed_domains?: string[];\n blocked_domains?: string[];\n user_location?: AnthropicUserLocation;\n}): AnthropicWebSearchTool {\n return {\n type: 'web_search_20250305',\n name: 'web_search',\n ...options,\n };\n}\n\n/**\n * Creates a computer use tool configuration.\n *\n * The computer tool enables Claude to interact with computer interfaces\n * through mouse clicks, keyboard input, and screenshots.\n *\n * Requires beta header (automatically injected when using this tool):\n * - `computer-use-2025-11-24` for Claude Opus 4.5\n * - `computer-use-2025-01-24` for other models\n *\n * @param options - Display configuration and optional settings\n * @returns A computer tool configuration object\n *\n * @example\n * ```typescript\n * const computer = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * });\n *\n * // For Opus 4.5 with zoom support\n * const computerOpus = computerTool({\n * display_width_px: 1920,\n * display_height_px: 1080,\n * version: '20251124',\n * enable_zoom: true,\n * });\n * ```\n */\nexport function computerTool(options: {\n display_width_px: number;\n display_height_px: number;\n display_number?: number;\n enable_zoom?: boolean;\n /** Use '20251124' for Claude Opus 4.5, '20250124' for other models */\n version?: '20251124' | '20250124';\n}): AnthropicComputerTool {\n const { version = '20250124', ...rest } = options;\n return {\n type: version === '20251124' ? 'computer_20251124' : 'computer_20250124',\n name: 'computer',\n ...rest,\n };\n}\n\n/**\n * Creates a text editor tool configuration.\n *\n * The text editor tool enables Claude to view, create, and edit files\n * using commands like view, str_replace, create, and insert.\n *\n * Token overhead: ~700 tokens per tool definition.\n *\n * @param options - Optional configuration\n * @returns A text editor tool configuration object\n *\n * @example\n * ```typescript\n * const editor = textEditorTool();\n *\n * // With max characters for view truncation\n * const editorWithLimit = textEditorTool({\n * max_characters: 10000,\n * });\n * ```\n */\nexport function textEditorTool(options?: {\n max_characters?: number;\n /** Use '20250728' for Claude 4, '20250124' for Claude 3.7 */\n version?: '20250728' | '20250124';\n}): AnthropicTextEditorTool {\n const version = options?.version ?? '20250728';\n return {\n type: version === '20250728' ? 'text_editor_20250728' : 'text_editor_20250124',\n name: version === '20250728' ? 'str_replace_based_edit_tool' : 'str_replace_editor',\n ...(options?.max_characters !== undefined && { max_characters: options.max_characters }),\n };\n}\n\n/**\n * Creates a bash tool configuration.\n *\n * The bash tool enables Claude to execute shell commands.\n * Sessions persist within the conversation.\n *\n * Token overhead: ~245 tokens per tool definition.\n *\n * @returns A bash tool configuration object\n *\n * @example\n * ```typescript\n * const bash = bashTool();\n * ```\n */\nexport function bashTool(): AnthropicBashTool {\n return {\n type: 'bash_20250124',\n name: 'bash',\n };\n}\n\n/**\n * Creates a code execution tool configuration.\n *\n * The code execution tool enables Claude to write and execute\n * Python/Bash code in a secure sandboxed container.\n *\n * Requires beta header: `code-execution-2025-08-25` (automatically injected).\n *\n * Pricing:\n * - Free tier: 1,550 hours/month per organization\n * - Additional: $0.05 per hour, per container\n *\n * @returns A code execution tool configuration object\n *\n * @example\n * ```typescript\n * const codeExec = codeExecutionTool();\n * ```\n */\nexport function codeExecutionTool(): AnthropicCodeExecutionTool {\n return {\n type: 'code_execution_20250825',\n name: 'code_execution',\n };\n}\n\n/**\n * Creates a tool search tool configuration.\n *\n * The tool search tool enables Claude to search through large\n * tool catalogs (up to 10,000 tools) using regex or natural language.\n *\n * Requires beta header: `advanced-tool-use-2025-11-20` (automatically injected).\n *\n * @param options - Optional mode selection\n * @returns A tool search tool configuration object\n *\n * @example\n * ```typescript\n * // Regex-based search (default)\n * const search = toolSearchTool();\n *\n * // Natural language (BM25) search\n * const nlSearch = toolSearchTool({ mode: 'bm25' });\n * ```\n */\nexport function toolSearchTool(options?: {\n /** Search mode: 'regex' for pattern matching, 'bm25' for natural language */\n mode?: 'regex' | 'bm25';\n}): AnthropicToolSearchTool {\n const mode = options?.mode ?? 'regex';\n return {\n type: mode === 'regex' ? 'tool_search_tool_regex_20251119' : 'tool_search_tool_bm25_20251119',\n name: mode === 'regex' ? 'tool_search_tool_regex' : 'tool_search_tool_bm25',\n };\n}\n\n/**\n * Namespace object containing all Anthropic tool helper constructors.\n *\n * Provides a convenient way to create built-in tool configurations.\n *\n * @example\n * ```typescript\n * import { anthropic, tools } from 'provider-protocol/anthropic';\n *\n * const model = llm({\n * model: anthropic('claude-sonnet-4-20250514'),\n * params: {\n * builtInTools: [\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","import { createProvider } from '../../core/provider.ts';\nimport { createLLMHandler } from './llm.ts';\n\n/**\n * Anthropic provider instance for the Universal Provider Protocol.\n *\n * Provides access to Claude language models through a unified interface.\n * Currently supports the LLM modality with full streaming, tool use,\n * structured output, and image input capabilities.\n *\n * @example\n * ```typescript\n * import { anthropic } from './providers/anthropic';\n *\n * const claude = anthropic.llm.bind('claude-sonnet-4-20250514');\n * const response = await claude.complete({\n * messages: [new UserMessage([{ type: 'text', text: 'Hello!' }])],\n * config: { apiKey: 'sk-...' },\n * });\n * ```\n *\n * @see {@link AnthropicLLMParams} for provider-specific parameters\n */\nexport const anthropic = createProvider({\n name: 'anthropic',\n version: '1.0.0',\n modalities: {\n llm: createLLMHandler(),\n },\n});\n\nexport { tools } from './types.ts';\nexport type {\n AnthropicLLMParams,\n AnthropicHeaders,\n AnthropicBuiltInTool,\n AnthropicWebSearchTool,\n AnthropicComputerTool,\n AnthropicTextEditorTool,\n AnthropicBashTool,\n AnthropicCodeExecutionTool,\n AnthropicToolSearchTool,\n AnthropicUserLocation,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DO,SAAS,iBACd,SACA,SACkB;AAClB,QAAM,SAAU,QAAQ,UAAU,CAAC;AACnC,QAAM,EAAE,cAAc,GAAG,WAAW,IAAI;AAExC,QAAM,mBAAqC;AAAA,IACzC,GAAG;AAAA,IACH,OAAO;AAAA,IACP,UAAU,QAAQ,SAAS,IAAI,gBAAgB;AAAA,EACjD;AAEA,MAAI,QAAQ,QAAQ;AAGlB,qBAAiB,SAAS,QAAQ;AAAA,EACpC;AAGA,QAAM,WAA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;AAAA,EAEnB,WAAW;AAAA;AAAA,EAEX,UAAU;AAAA;AAAA,EAEV,YAAY;AAAA;AAAA,EAEZ,MAAM;AAAA;AAAA,EAEN,eAAe;AAAA;AAAA,EAEf,YAAY;AACd;;;AC5+BO,IAAM,YAAY,eAAe;AAAA,EACtC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,YAAY;AAAA,IACV,KAAK,iBAAiB;AAAA,EACxB;AACF,CAAC;","names":[]}
@@ -1,69 +1,6 @@
1
- // src/types/errors.ts
2
- var UPPError = class _UPPError extends Error {
3
- /** Normalized error code for programmatic handling */
4
- code;
5
- /** Name of the provider that generated the error */
6
- provider;
7
- /** The modality that was being used when the error occurred */
8
- modality;
9
- /** HTTP status code from the provider's response, if available */
10
- statusCode;
11
- /** The original error that caused this UPPError, if wrapping another error */
12
- cause;
13
- /** Error class name, always 'UPPError' */
14
- name = "UPPError";
15
- /**
16
- * Creates a new UPPError instance.
17
- *
18
- * @param message - Human-readable error description
19
- * @param code - Normalized error code for programmatic handling
20
- * @param provider - Name of the provider that generated the error
21
- * @param modality - The modality that was being used
22
- * @param statusCode - HTTP status code from the provider's response
23
- * @param cause - The original error being wrapped
24
- */
25
- constructor(message, code, provider, modality, statusCode, cause) {
26
- super(message);
27
- this.code = code;
28
- this.provider = provider;
29
- this.modality = modality;
30
- this.statusCode = statusCode;
31
- this.cause = cause;
32
- if (Error.captureStackTrace) {
33
- Error.captureStackTrace(this, _UPPError);
34
- }
35
- }
36
- /**
37
- * Creates a string representation of the error.
38
- *
39
- * @returns Formatted error string including code, message, provider, and modality
40
- */
41
- toString() {
42
- let str = `UPPError [${this.code}]: ${this.message}`;
43
- str += ` (provider: ${this.provider}, modality: ${this.modality}`;
44
- if (this.statusCode) {
45
- str += `, status: ${this.statusCode}`;
46
- }
47
- str += ")";
48
- return str;
49
- }
50
- /**
51
- * Converts the error to a JSON-serializable object.
52
- *
53
- * @returns Plain object representation suitable for logging or transmission
54
- */
55
- toJSON() {
56
- return {
57
- name: this.name,
58
- message: this.message,
59
- code: this.code,
60
- provider: this.provider,
61
- modality: this.modality,
62
- statusCode: this.statusCode,
63
- cause: this.cause?.message
64
- };
65
- }
66
- };
1
+ import {
2
+ UPPError
3
+ } from "./chunk-DZQHVGNV.js";
67
4
 
68
5
  // src/http/keys.ts
69
6
  var RoundRobinKeys = class {
@@ -373,7 +310,6 @@ async function doStreamFetch(url, init, config, provider, modality) {
373
310
  }
374
311
 
375
312
  export {
376
- UPPError,
377
313
  RoundRobinKeys,
378
314
  WeightedKeys,
379
315
  DynamicKey,
@@ -386,4 +322,4 @@ export {
386
322
  doFetch,
387
323
  doStreamFetch
388
324
  };
389
- //# sourceMappingURL=chunk-MOU4U3PO.js.map
325
+ //# sourceMappingURL=chunk-5FEAOEXV.js.map