@tanstack/ai-anthropic 0.15.13 → 0.16.1

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.
@@ -13,7 +13,7 @@ export type AnthropicSummarizeModel = (typeof ANTHROPIC_MODELS)[number];
13
13
  * Creates an Anthropic summarize adapter with explicit API key.
14
14
  * Type resolution happens here at the call site.
15
15
  *
16
- * @param model - The model name (e.g., 'claude-sonnet-4-5', 'claude-3-5-haiku-latest')
16
+ * @param model - The model name (e.g., 'claude-sonnet-5', 'claude-haiku-4-5')
17
17
  * @param apiKey - Your Anthropic API key
18
18
  * @param config - Optional additional configuration
19
19
  * @returns Configured Anthropic summarize adapter instance with resolved types
@@ -28,7 +28,7 @@ export declare function createAnthropicSummarize<TModel extends AnthropicSummari
28
28
  * Creates an Anthropic summarize adapter with automatic API key detection.
29
29
  * Type resolution happens here at the call site.
30
30
  *
31
- * @param model - The model name (e.g., 'claude-sonnet-4-5', 'claude-3-5-haiku-latest')
31
+ * @param model - The model name (e.g., 'claude-sonnet-5', 'claude-haiku-4-5')
32
32
  * @param config - Optional configuration (excluding apiKey which is auto-detected)
33
33
  * @returns Configured Anthropic summarize adapter instance with resolved types
34
34
  *
@@ -1 +1 @@
1
- {"version":3,"file":"summarize.js","sources":["../../../src/adapters/summarize.ts"],"sourcesContent":["import { ChatStreamSummarizeAdapter } from '@tanstack/ai/adapters'\nimport { getAnthropicApiKeyFromEnv } from '../utils'\nimport { AnthropicTextAdapter } from './text'\nimport type { InferTextProviderOptions } from '@tanstack/ai/adapters'\nimport type { ANTHROPIC_MODELS } from '../model-meta'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * Configuration for Anthropic summarize adapter\n */\nexport interface AnthropicSummarizeConfig extends AnthropicClientConfig {}\n\n/** Model type for Anthropic summarization */\nexport type AnthropicSummarizeModel = (typeof ANTHROPIC_MODELS)[number]\n\n/**\n * Creates an Anthropic summarize adapter with explicit API key.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'claude-sonnet-4-5', 'claude-3-5-haiku-latest')\n * @param apiKey - Your Anthropic API key\n * @param config - Optional additional configuration\n * @returns Configured Anthropic summarize adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = createAnthropicSummarize('claude-sonnet-4-5', 'sk-ant-...');\n * ```\n */\nexport function createAnthropicSummarize<\n TModel extends AnthropicSummarizeModel,\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<AnthropicTextAdapter<TModel>>\n> {\n return new ChatStreamSummarizeAdapter(\n new AnthropicTextAdapter({ apiKey, ...config }, model),\n model,\n 'anthropic',\n )\n}\n\n/**\n * Creates an Anthropic summarize adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'claude-sonnet-4-5', 'claude-3-5-haiku-latest')\n * @param config - Optional configuration (excluding apiKey which is auto-detected)\n * @returns Configured Anthropic summarize adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = anthropicSummarize('claude-sonnet-4-5');\n * await summarize({ adapter, text: 'Long article text...' });\n * ```\n */\nexport function anthropicSummarize<TModel extends AnthropicSummarizeModel>(\n model: TModel,\n config?: Omit<AnthropicSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<AnthropicTextAdapter<TModel>>\n> {\n return createAnthropicSummarize(model, getAnthropicApiKeyFromEnv(), config)\n}\n"],"names":[],"mappings":";;;AA6BO,SAAS,yBAGd,OACA,QACA,QAIA;AACA,SAAO,IAAI;AAAA,IACT,IAAI,qBAAqB,EAAE,QAAQ,GAAG,OAAA,GAAU,KAAK;AAAA,IACrD;AAAA,IACA;AAAA,EAAA;AAEJ;AAgBO,SAAS,mBACd,OACA,QAIA;AACA,SAAO,yBAAyB,OAAO,0BAAA,GAA6B,MAAM;AAC5E;"}
1
+ {"version":3,"file":"summarize.js","sources":["../../../src/adapters/summarize.ts"],"sourcesContent":["import { ChatStreamSummarizeAdapter } from '@tanstack/ai/adapters'\nimport { getAnthropicApiKeyFromEnv } from '../utils'\nimport { AnthropicTextAdapter } from './text'\nimport type { InferTextProviderOptions } from '@tanstack/ai/adapters'\nimport type { ANTHROPIC_MODELS } from '../model-meta'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * Configuration for Anthropic summarize adapter\n */\nexport interface AnthropicSummarizeConfig extends AnthropicClientConfig {}\n\n/** Model type for Anthropic summarization */\nexport type AnthropicSummarizeModel = (typeof ANTHROPIC_MODELS)[number]\n\n/**\n * Creates an Anthropic summarize adapter with explicit API key.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'claude-sonnet-5', 'claude-haiku-4-5')\n * @param apiKey - Your Anthropic API key\n * @param config - Optional additional configuration\n * @returns Configured Anthropic summarize adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = createAnthropicSummarize('claude-sonnet-4-5', 'sk-ant-...');\n * ```\n */\nexport function createAnthropicSummarize<\n TModel extends AnthropicSummarizeModel,\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<AnthropicTextAdapter<TModel>>\n> {\n return new ChatStreamSummarizeAdapter(\n new AnthropicTextAdapter({ apiKey, ...config }, model),\n model,\n 'anthropic',\n )\n}\n\n/**\n * Creates an Anthropic summarize adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'claude-sonnet-5', 'claude-haiku-4-5')\n * @param config - Optional configuration (excluding apiKey which is auto-detected)\n * @returns Configured Anthropic summarize adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = anthropicSummarize('claude-sonnet-4-5');\n * await summarize({ adapter, text: 'Long article text...' });\n * ```\n */\nexport function anthropicSummarize<TModel extends AnthropicSummarizeModel>(\n model: TModel,\n config?: Omit<AnthropicSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<AnthropicTextAdapter<TModel>>\n> {\n return createAnthropicSummarize(model, getAnthropicApiKeyFromEnv(), config)\n}\n"],"names":[],"mappings":";;;AA6BO,SAAS,yBAGd,OACA,QACA,QAIA;AACA,SAAO,IAAI;AAAA,IACT,IAAI,qBAAqB,EAAE,QAAQ,GAAG,OAAA,GAAU,KAAK;AAAA,IACrD;AAAA,IACA;AAAA,EAAA;AAEJ;AAgBO,SAAS,mBACd,OACA,QAIA;AACA,SAAO,yBAAyB,OAAO,0BAAA,GAA6B,MAAM;AAC5E;"}
@@ -6,7 +6,38 @@ import { readCodeExecutionSkills, readCodeExecutionConfig } from "../tools/code-
6
6
  import { validateTextProviderOptions } from "../text/text-provider-options.js";
7
7
  import { buildAnthropicUsage } from "../usage.js";
8
8
  import { createAnthropicClient, generateId, getAnthropicApiKeyFromEnv } from "../utils/client.js";
9
- import { ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "../model-meta.js";
9
+ import { getAnthropicDefaultMaxTokens, ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "../model-meta.js";
10
+ function readAnthropicServerToolMetadata(metadata) {
11
+ if (typeof metadata !== "object" || metadata === null) return null;
12
+ const outer = metadata;
13
+ if (outer.providerExecuted !== true) return null;
14
+ const inner = outer.anthropic;
15
+ if (typeof inner !== "object" || inner === null) return null;
16
+ const { serverToolType, resultBlockType, result } = inner;
17
+ if (typeof serverToolType !== "string" || resultBlockType !== "web_search_tool_result" && resultBlockType !== "web_fetch_tool_result") {
18
+ return null;
19
+ }
20
+ return {
21
+ // Validated as a string above; widen back to the SDK's tool-name union.
22
+ serverToolType,
23
+ resultBlockType,
24
+ result
25
+ };
26
+ }
27
+ function buildServerToolResultBlock(toolUseId, meta) {
28
+ if (meta.resultBlockType === "web_search_tool_result") {
29
+ return {
30
+ type: "web_search_tool_result",
31
+ tool_use_id: toolUseId,
32
+ content: meta.result
33
+ };
34
+ }
35
+ return {
36
+ type: "web_fetch_tool_result",
37
+ tool_use_id: toolUseId,
38
+ content: meta.result
39
+ };
40
+ }
10
41
  function computeAnthropicBetas(tools, modelOptions) {
11
42
  const betas = /* @__PURE__ */ new Set();
12
43
  const useInterleavedThinking = modelOptions?.thinking?.type === "enabled" && typeof modelOptions.thinking.budget_tokens === "number" && modelOptions.thinking.budget_tokens > 0;
@@ -90,7 +121,9 @@ class AnthropicTextAdapter extends BaseTextAdapter {
90
121
  async structuredOutput(options) {
91
122
  const { chatOptions, outputSchema } = options;
92
123
  const { logger } = chatOptions;
93
- const requestParams = this.mapCommonOptionsToAnthropic(chatOptions);
124
+ const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {
125
+ stream: false
126
+ });
94
127
  const structuredOutputTool = {
95
128
  name: "structured_output",
96
129
  description: "Use this tool to provide your response in the required structured format.",
@@ -162,7 +195,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
162
195
  );
163
196
  }
164
197
  }
165
- mapCommonOptionsToAnthropic(options) {
198
+ mapCommonOptionsToAnthropic(options, { stream = true } = {}) {
166
199
  const modelOptions = options.modelOptions;
167
200
  const formattedMessages = this.formatMessages(options.messages);
168
201
  const tools = options.tools ? convertToolsToProviderFormat(options.tools) : void 0;
@@ -210,7 +243,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
210
243
  }
211
244
  }
212
245
  const thinkingBudget = validProviderOptions.thinking?.type === "enabled" ? validProviderOptions.thinking.budget_tokens : void 0;
213
- const defaultMaxTokens = modelOptions?.max_tokens ?? 1024;
246
+ const defaultMaxTokens = modelOptions?.max_tokens ?? getAnthropicDefaultMaxTokens(this.model, { stream });
214
247
  const maxTokens = thinkingBudget && thinkingBudget >= defaultMaxTokens ? thinkingBudget + 1 : defaultMaxTokens;
215
248
  const systemBlocks = (() => {
216
249
  const normalized = normalizeSystemPrompts(
@@ -362,6 +395,20 @@ class AnthropicTextAdapter extends BaseTextAdapter {
362
395
  } catch {
363
396
  parsedInput = toolCall.function.arguments;
364
397
  }
398
+ const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata);
399
+ if (serverMeta) {
400
+ const serverToolUseBlock = {
401
+ type: "server_tool_use",
402
+ id: toolCall.id,
403
+ name: serverMeta.serverToolType,
404
+ input: parsedInput
405
+ };
406
+ contentBlocks.push(serverToolUseBlock);
407
+ contentBlocks.push(
408
+ buildServerToolResultBlock(toolCall.id, serverMeta)
409
+ );
410
+ continue;
411
+ }
365
412
  const toolUseBlock = {
366
413
  type: "tool_use",
367
414
  id: toolCall.id,
@@ -476,6 +523,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
476
523
  const toolCallsMap = /* @__PURE__ */ new Map();
477
524
  let currentToolIndex = -1;
478
525
  let currentServerTool = null;
526
+ const completedServerTools = /* @__PURE__ */ new Map();
479
527
  const runId = options.runId ?? genId();
480
528
  const threadId = options.threadId ?? genId();
481
529
  const messageId = genId();
@@ -532,6 +580,49 @@ class AnthropicTextAdapter extends BaseTextAdapter {
532
580
  }
533
581
  );
534
582
  }
583
+ const serverTool = completedServerTools.get(
584
+ event.content_block.tool_use_id
585
+ );
586
+ if (serverTool) {
587
+ completedServerTools.delete(serverTool.id);
588
+ let parsedInput = {};
589
+ try {
590
+ const parsed = serverTool.input ? JSON.parse(serverTool.input) : {};
591
+ parsedInput = parsed && typeof parsed === "object" ? parsed : {};
592
+ } catch {
593
+ parsedInput = {};
594
+ }
595
+ const serverToolMetadata = {
596
+ providerExecuted: true,
597
+ anthropic: {
598
+ serverToolType: serverTool.name,
599
+ resultBlockType: event.content_block.type,
600
+ result: content
601
+ }
602
+ };
603
+ currentToolIndex++;
604
+ yield {
605
+ type: EventType.TOOL_CALL_START,
606
+ toolCallId: serverTool.id,
607
+ toolCallName: serverTool.name,
608
+ toolName: serverTool.name,
609
+ parentMessageId: messageId,
610
+ model,
611
+ timestamp: Date.now(),
612
+ index: currentToolIndex,
613
+ metadata: serverToolMetadata
614
+ };
615
+ yield {
616
+ type: EventType.TOOL_CALL_END,
617
+ toolCallId: serverTool.id,
618
+ toolCallName: serverTool.name,
619
+ toolName: serverTool.name,
620
+ model,
621
+ timestamp: Date.now(),
622
+ input: parsedInput
623
+ };
624
+ hasEmittedTextMessageStart = false;
625
+ }
535
626
  } else if (event.content_block.type === "thinking") {
536
627
  accumulatedThinking = "";
537
628
  accumulatedSignature = "";
@@ -706,6 +797,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
706
797
  input: currentServerTool.input
707
798
  }
708
799
  );
800
+ completedServerTools.set(currentServerTool.id, currentServerTool);
709
801
  }
710
802
  currentServerTool = null;
711
803
  } else if (currentBlockType === "web_fetch_tool_result" || currentBlockType === "web_search_tool_result") {
@@ -778,6 +870,17 @@ class AnthropicTextAdapter extends BaseTextAdapter {
778
870
  break;
779
871
  }
780
872
  case "max_tokens": {
873
+ if (options.modelOptions?.max_tokens == null) {
874
+ const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model);
875
+ logger.warn(
876
+ `anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,
877
+ {
878
+ source: "anthropic.processAnthropicStream",
879
+ model,
880
+ defaultedMaxTokens
881
+ }
882
+ );
883
+ }
781
884
  yield {
782
885
  type: EventType.RUN_ERROR,
783
886
  model,
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport { readCodeExecutionConfig, readCodeExecutionSkills } from '../tools'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils'\nimport { ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions)\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n const defaultMaxTokens = modelOptions?.max_tokens ?? 1024\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;;;;;;;AAkEO,SAAS,sBACd,OACA,cAQkC;AAClC,QAAM,4BAAY,IAAA;AAElB,QAAM,yBACJ,cAAc,UAAU,SAAS,aACjC,OAAO,aAAa,SAAS,kBAAkB,YAC/C,aAAa,SAAS,gBAAgB;AACxC,MAAI,uBAAwB,OAAM,IAAI,iCAAiC;AAIvE,QAAM,eAAe,OAAO,KAAK,CAAC,MAAM,EAAE,SAAS,gBAAgB;AACnE,MAAI,cAAc;AAChB,UAAM,UAAU,wBAAwB,YAAY,GAAG;AAIvD,UAAM;AAAA,MACJ,YAAY,4BACR,8BACA;AAAA,IAAA;AAAA,EAER;AAKA,QAAM,YAAY,OAAO;AAAA,IACvB,CAAC,MACC,EAAE,SAAS,qBACV,wBAAwB,CAAC,GAAG,UAAU,KAAK;AAAA,EAAA;AAEhD,MAAI,UAAW,OAAM,IAAI,mBAAmB;AAE5C,SAAO,MAAM,OAAO,IAAI,MAAM,KAAK,KAAK,IAAI;AAC9C;AAiDO,MAAM,6BAOH,gBAWR;AAAA,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oBACF,MAAM;AAAA,kBAAA;AAAA,gBACR;AAEF;AAAA,cACF;AAAA,cACA,KAAK;AAAA,cACL,KAAK;AAAA,cACL,KAAK;AAAA,cACL,KAAK;AAAA,cACL,KAAK;AAAA,cACL,KAAK;AAAA,cACL,SAAS;AAKP,sBAAM;AAAA,kBACJ,MAAM,UAAU;AAAA,kBAChB;AAAA,kBACA;AAAA,kBACA;AAAA,kBACA,WAAW,KAAK,IAAA;AAAA,kBAChB,cAAc;AAAA,kBACd,OAAO,oBAAoB,MAAM,KAAK;AAAA,gBAAA;AAAA,cAE1C;AAAA,YAAA;AAAA,UAEJ;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,OAAgB;AACvB,YAAM,MAAM;AACZ,YAAM,WAAW,mBAAmB,KAAK;AAEzC,aAAO,OAAO,0CAA0C;AAAA,QACtD;AAAA,QACA,QAAQ;AAAA,MAAA,CACT;AACD,YAAM;AAAA,QACJ,MAAM,UAAU;AAAA,QAChB;AAAA,QACA,WAAW,KAAK,IAAA;AAAA,QAChB,SAAS,IAAI,WAAW;AAAA,QACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;AAAA;AAAA,QAEnC,GAAI,aAAa,UAAa,EAAE,SAAA;AAAA,QAChC,OAAO;AAAA,UACL,SAAS,IAAI,WAAW;AAAA,UACxB,MAAM,IAAI,QAAQ,OAAO,IAAI,MAAM;AAAA,QAAA;AAAA,MACrC;AAAA,IAEJ;AAAA,EACF;AACF;AAMO,SAAS,oBAGd,OACA,QACA,QAKA;AACA,SAAO,IAAI,qBAAqB,EAAE,QAAQ,GAAG,OAAA,GAAU,KAAK;AAC9D;AAMO,SAAS,cACd,OACA,QAKA;AACA,QAAM,SAAS,0BAAA;AACf,SAAO,oBAAoB,OAAO,QAAQ,MAAM;AAClD;"}
1
+ {"version":3,"file":"text.js","sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport { readCodeExecutionConfig, readCodeExecutionSkills } from '../tools'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils'\nimport {\n ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,\n getAnthropicDefaultMaxTokens,\n} from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n ServerToolUseBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n WebFetchToolResultBlockParam,\n WebSearchToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * The block type carried by an Anthropic provider-executed (server) tool's\n * stored result. Mirrors the `*_tool_result` block emitted by the streaming\n * API so it can be replayed verbatim into a later turn.\n */\ntype AnthropicServerToolResultBlockType =\n | 'web_search_tool_result'\n | 'web_fetch_tool_result'\n\n/**\n * Anthropic payload stashed on a provider-executed tool call's `metadata`\n * (under the `anthropic` key, alongside `providerExecuted: true`). Holds enough\n * to reconstruct the original `server_tool_use` + `*_tool_result` blocks so the\n * model still sees prior `web_search` / `web_fetch` evidence on the next turn.\n */\ninterface AnthropicServerToolMetadata {\n serverToolType: ServerToolUseBlockParam['name']\n resultBlockType: AnthropicServerToolResultBlockType\n /** Raw result block content, preserved verbatim from the stream. */\n result: unknown\n}\n\n/**\n * Narrow an opaque tool-call `metadata` to {@link AnthropicServerToolMetadata}\n * when it follows the provider-executed convention, else `null`.\n */\nfunction readAnthropicServerToolMetadata(\n metadata: unknown,\n): AnthropicServerToolMetadata | null {\n if (typeof metadata !== 'object' || metadata === null) return null\n const outer = metadata as { providerExecuted?: unknown; anthropic?: unknown }\n if (outer.providerExecuted !== true) return null\n const inner = outer.anthropic\n if (typeof inner !== 'object' || inner === null) return null\n const { serverToolType, resultBlockType, result } = inner as {\n serverToolType?: unknown\n resultBlockType?: unknown\n result?: unknown\n }\n if (\n typeof serverToolType !== 'string' ||\n (resultBlockType !== 'web_search_tool_result' &&\n resultBlockType !== 'web_fetch_tool_result')\n ) {\n return null\n }\n return {\n // Validated as a string above; widen back to the SDK's tool-name union.\n serverToolType: serverToolType as ServerToolUseBlockParam['name'],\n resultBlockType,\n result,\n }\n}\n\n/**\n * Reconstruct the `*_tool_result` block param from stored server-tool metadata.\n * The `result` content is opaque round-trip data, asserted to the SDK's param\n * content type at this single boundary.\n */\nfunction buildServerToolResultBlock(\n toolUseId: string,\n meta: AnthropicServerToolMetadata,\n): WebSearchToolResultBlockParam | WebFetchToolResultBlockParam {\n if (meta.resultBlockType === 'web_search_tool_result') {\n return {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebSearchToolResultBlockParam['content'],\n }\n }\n return {\n type: 'web_fetch_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebFetchToolResultBlockParam['content'],\n }\n}\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n // `structuredOutput()` issues a non-streaming `messages.create({ stream:\n // false })` below, so the defaulted `max_tokens` must stay under the SDK's\n // non-streaming 10-minute guard (issue #849) — pass `stream: false`.\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {\n stream: false,\n })\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n { stream = true }: { stream?: boolean } = {},\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n // Anthropic's Messages API *requires* `max_tokens`, so we must always send a\n // value. When the caller doesn't specify one, default to the resolved\n // model's real output ceiling (from model-meta) rather than a low constant\n // that silently truncates long responses with `stop_reason: \"max_tokens\"`\n // (issue #849). `max_tokens` is a ceiling, not a reservation — billing is on\n // tokens actually generated, so a higher default costs nothing extra.\n // For non-streaming requests (the `structuredOutput()` path) the default is\n // clamped to the SDK's non-streaming-safe limit so it doesn't trip the\n // \"streaming required\" 10-minute guard — see getAnthropicDefaultMaxTokens.\n const defaultMaxTokens =\n modelOptions?.max_tokens ??\n getAnthropicDefaultMaxTokens(this.model, { stream })\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n // Provider-executed server tools (e.g. web_search) replay as the\n // original `server_tool_use` + result blocks so the model still sees\n // the prior evidence. Their result was captured verbatim during\n // streaming (see processAnthropicStream).\n const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata)\n if (serverMeta) {\n const serverToolUseBlock: ServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: toolCall.id,\n name: serverMeta.serverToolType,\n input: parsedInput,\n }\n contentBlocks.push(serverToolUseBlock)\n contentBlocks.push(\n buildServerToolResultBlock(toolCall.id, serverMeta),\n )\n continue\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n // Completed server tools awaiting their matching result block. Anthropic\n // emits `server_tool_use` then a separate `*_tool_result` block; we hold\n // the call here (keyed by id) until the result arrives so we can emit a\n // single provider-executed tool call carrying the raw result for round-trip.\n const completedServerTools = new Map<\n string,\n { id: string; name: string; input: string }\n >()\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n\n // Emit the server tool as a single provider-executed tool call,\n // carrying its raw result so the evidence (e.g. web_search sources)\n // round-trips into the next turn's request. The agent loop skips\n // provider-executed calls, so this never triggers client execution.\n const serverTool = completedServerTools.get(\n event.content_block.tool_use_id,\n )\n if (serverTool) {\n completedServerTools.delete(serverTool.id)\n\n let parsedInput: unknown = {}\n try {\n const parsed = serverTool.input\n ? JSON.parse(serverTool.input)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n const serverToolMetadata = {\n providerExecuted: true,\n anthropic: {\n serverToolType: serverTool.name,\n resultBlockType: event.content_block.type,\n result: content,\n },\n }\n\n currentToolIndex++\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n metadata: serverToolMetadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Text after the server tool starts a fresh message segment.\n hasEmittedTextMessageStart = false\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n // Hold the call until its result block arrives so we can emit\n // both together as one provider-executed tool call.\n completedServerTools.set(currentServerTool.id, currentServerTool)\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n // Surface a warning when the truncating cap was the\n // adapter-supplied default (caller didn't pass `max_tokens`), so\n // the truncation isn't silently attributed to the model \"doing\n // nothing\" (issue #849). When the caller set `max_tokens`\n // themselves, hitting it is their own deliberate ceiling.\n if (options.modelOptions?.max_tokens == null) {\n const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model)\n logger.warn(\n `anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,\n {\n source: 'anthropic.processAnthropicStream',\n model,\n defaultedMaxTokens,\n },\n )\n }\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;;;;;;;AA2FA,SAAS,gCACP,UACoC;AACpC,MAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;AAC9D,QAAM,QAAQ;AACd,MAAI,MAAM,qBAAqB,KAAM,QAAO;AAC5C,QAAM,QAAQ,MAAM;AACpB,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,EAAE,gBAAgB,iBAAiB,OAAA,IAAW;AAKpD,MACE,OAAO,mBAAmB,YACzB,oBAAoB,4BACnB,oBAAoB,yBACtB;AACA,WAAO;AAAA,EACT;AACA,SAAO;AAAA;AAAA,IAEL;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;AAOA,SAAS,2BACP,WACA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