ai-sdk-provider-claude-code 3.4.4 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +312 -51
- package/dist/index.cjs +1589 -175
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +481 -31
- package/dist/index.d.ts +481 -31
- package/dist/index.js +1593 -177
- package/dist/index.js.map +1 -1
- package/docs/ai-sdk-v4/GUIDE.md +2 -0
- package/docs/ai-sdk-v4/README.md +7 -0
- package/docs/ai-sdk-v5/GUIDE.md +2 -0
- package/docs/ai-sdk-v5/README.md +10 -0
- package/docs/sessions.md +117 -0
- package/package.json +9 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/claude-code-provider.ts","../src/claude-code-language-model.ts","../src/convert-to-claude-code-messages.ts","../src/errors.ts","../src/map-claude-code-finish-reason.ts","../src/validation.ts","../src/logger.ts","../src/index.ts","../src/mcp-helpers.ts"],"sourcesContent":["import type { LanguageModelV3, ProviderV3 } from '@ai-sdk/provider';\nimport { NoSuchModelError } from '@ai-sdk/provider';\nimport { ClaudeCodeLanguageModel, type ClaudeCodeModelId } from './claude-code-language-model.js';\nimport type { ClaudeCodeSettings } from './types.js';\nimport { validateSettings } from './validation.js';\nimport { getLogger } from './logger.js';\n\n/**\n * Claude Code provider interface that extends the AI SDK's ProviderV3.\n * Provides methods to create language models for interacting with Claude via the CLI.\n *\n * @example\n * ```typescript\n * import { claudeCode } from 'ai-sdk-provider-claude-code';\n *\n * // Create a model instance\n * const model = claudeCode('opus');\n *\n * // Or use the explicit methods\n * const chatModel = claudeCode.chat('sonnet');\n * const languageModel = claudeCode.languageModel('opus', { maxTurns: 10 });\n * ```\n */\nexport interface ClaudeCodeProvider extends ProviderV3 {\n /**\n * Creates a language model instance for the specified model ID.\n * This is a shorthand for calling `languageModel()`.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n (modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n /**\n * Creates a language model instance for text generation.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n languageModel(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n /**\n * Alias for `languageModel()` to maintain compatibility with AI SDK patterns.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n chat(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n imageModel(modelId: string): never;\n}\n\n/**\n * Configuration options for creating a Claude Code provider instance.\n * These settings will be applied as defaults to all models created by the provider.\n *\n * @example\n * ```typescript\n * const provider = createClaudeCode({\n * defaultSettings: {\n * maxTurns: 5,\n * cwd: '/path/to/project'\n * }\n * });\n * ```\n */\nexport interface ClaudeCodeProviderSettings {\n /**\n * Default settings to use for all models created by this provider.\n * Individual model settings will override these defaults.\n */\n defaultSettings?: ClaudeCodeSettings;\n}\n\n/**\n * Creates a Claude Code provider instance with the specified configuration.\n * The provider can be used to create language models for interacting with Claude 4 models.\n *\n * @param options - Provider configuration options\n * @returns Claude Code provider instance\n *\n * @example\n * ```typescript\n * const provider = createClaudeCode({\n * defaultSettings: {\n * permissionMode: 'bypassPermissions',\n * maxTurns: 10\n * }\n * });\n *\n * const model = provider('opus');\n * ```\n */\nexport function createClaudeCode(options: ClaudeCodeProviderSettings = {}): ClaudeCodeProvider {\n // Get logger from default settings if provided\n const logger = getLogger(options.defaultSettings?.logger);\n\n // Validate default settings if provided\n if (options.defaultSettings) {\n const validation = validateSettings(options.defaultSettings);\n if (!validation.valid) {\n throw new Error(`Invalid default settings: ${validation.errors.join(', ')}`);\n }\n if (validation.warnings.length > 0) {\n validation.warnings.forEach((warning) => logger.warn(`Claude Code Provider: ${warning}`));\n }\n }\n\n const createModel = (\n modelId: ClaudeCodeModelId,\n settings: ClaudeCodeSettings = {}\n ): LanguageModelV3 => {\n const mergedSettings = {\n ...options.defaultSettings,\n ...settings,\n };\n\n // Validate merged settings\n const validation = validateSettings(mergedSettings);\n if (!validation.valid) {\n throw new Error(`Invalid settings: ${validation.errors.join(', ')}`);\n }\n\n return new ClaudeCodeLanguageModel({\n id: modelId,\n settings: mergedSettings,\n settingsValidationWarnings: validation.warnings,\n });\n };\n\n const provider = function (modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings) {\n if (new.target) {\n throw new Error('The Claude Code model function cannot be called with the new keyword.');\n }\n\n return createModel(modelId, settings);\n };\n\n provider.languageModel = createModel;\n provider.chat = createModel; // Alias for languageModel\n provider.specificationVersion = 'v3' as const;\n\n // Add embeddingModel method that throws NoSuchModelError\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'embeddingModel',\n });\n };\n\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'imageModel',\n });\n };\n\n return provider as ClaudeCodeProvider;\n}\n\n/**\n * Default Claude Code provider instance.\n * Pre-configured provider for quick usage without custom settings.\n *\n * @example\n * ```typescript\n * import { claudeCode } from 'ai-sdk-provider-claude-code';\n * import { generateText } from 'ai';\n *\n * const { text } = await generateText({\n * model: claudeCode('sonnet'),\n * prompt: 'Hello, Claude!'\n * });\n * ```\n */\nexport const claudeCode = createClaudeCode();\n","import type {\n LanguageModelV3,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3Warning,\n JSONValue,\n JSONObject,\n} from '@ai-sdk/provider';\nimport { NoSuchModelError, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\nimport { generateId } from '@ai-sdk/provider-utils';\nimport type { ClaudeCodeSettings, Logger, MessageInjector } from './types.js';\nimport { convertToClaudeCodeMessages } from './convert-to-claude-code-messages.js';\nimport { createAPICallError, createAuthenticationError, createTimeoutError } from './errors.js';\nimport { mapClaudeCodeFinishReason } from './map-claude-code-finish-reason.js';\nimport { validateModelId, validatePrompt, validateSessionId } from './validation.js';\nimport { getLogger, createVerboseLogger } from './logger.js';\n\nimport { query, type Options } from '@anthropic-ai/claude-agent-sdk';\nimport type { SDKUserMessage, SDKPartialAssistantMessage } from '@anthropic-ai/claude-agent-sdk';\n\nconst CLAUDE_CODE_TRUNCATION_WARNING =\n 'Claude Code SDK output ended unexpectedly; returning truncated response from buffered text. Await upstream fix to avoid data loss.';\n\nconst MIN_TRUNCATION_LENGTH = 512;\n\n/**\n * Detects if an error represents a truncated SDK JSON stream.\n *\n * The Claude Code SDK can truncate JSON responses mid-stream, producing a SyntaxError.\n * This function distinguishes genuine truncation from normal JSON syntax errors by:\n * 1. Verifying the error is a SyntaxError with truncation-specific messages\n * 2. Ensuring we received meaningful content (>= MIN_TRUNCATION_LENGTH characters)\n * 3. Avoiding false positives from unrelated parse errors\n *\n * Note: We compare against `bufferedText` (assistant text content) rather than the raw\n * JSON buffer length, since the SDK layer doesn't expose buffer positions. The position\n * reported in SyntaxError messages measures the full JSON payload (metadata + content),\n * which is typically much larger than extracted text. Therefore, we cannot reliably use\n * position proximity checks and instead rely on message patterns and content length.\n *\n * @param error - The caught error (expected to be SyntaxError for truncation)\n * @param bufferedText - Accumulated assistant text content (measured in UTF-16 code units)\n * @returns true if error indicates SDK truncation; false otherwise\n */\nfunction isClaudeCodeTruncationError(error: unknown, bufferedText: string): boolean {\n // Check for SyntaxError by instanceof or by name (for cross-realm errors)\n const isSyntaxError =\n error instanceof SyntaxError ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (typeof (error as any)?.name === 'string' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).name.toLowerCase() === 'syntaxerror');\n\n if (!isSyntaxError) {\n return false;\n }\n\n if (!bufferedText) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawMessage = typeof (error as any)?.message === 'string' ? (error as any).message : '';\n const message = rawMessage.toLowerCase();\n\n // Only match actual truncation patterns, not normal JSON parsing errors.\n // Real truncation: \"Unexpected end of JSON input\" or \"Unterminated string in JSON...\"\n // Normal errors: \"Unexpected token X in JSON at position N\" (should be surfaced as errors)\n const truncationIndicators = [\n 'unexpected end of json input',\n 'unexpected end of input',\n 'unexpected end of string',\n 'unexpected eof',\n 'end of file',\n 'unterminated string',\n 'unterminated string constant',\n ];\n\n if (!truncationIndicators.some((indicator) => message.includes(indicator))) {\n return false;\n }\n\n // Require meaningful content before treating as truncation.\n // Short responses with \"end of input\" errors are likely genuine syntax errors.\n // Note: bufferedText.length measures UTF-16 code units, not byte length.\n if (bufferedText.length < MIN_TRUNCATION_LENGTH) {\n return false;\n }\n\n // If we have a truncation indicator AND meaningful content, treat as truncation.\n return true;\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (err && typeof err === 'object') {\n const e = err as { name?: unknown; code?: unknown };\n if (typeof e.name === 'string' && e.name === 'AbortError') return true;\n if (typeof e.code === 'string' && e.code.toUpperCase() === 'ABORT_ERR') return true;\n }\n return false;\n}\n\nconst DEFAULT_INHERITED_ENV_VARS =\n process.platform === 'win32'\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PATHEXT',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'TMP',\n 'USERNAME',\n 'USERPROFILE',\n 'WINDIR',\n ]\n : ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER', 'LANG', 'LC_ALL', 'TMPDIR'];\n\nconst CLAUDE_ENV_VARS = ['CLAUDE_CONFIG_DIR'];\n\nfunction getBaseProcessEnv(): Record<string, string> {\n const env: Record<string, string> = {};\n const allowedKeys = new Set([...DEFAULT_INHERITED_ENV_VARS, ...CLAUDE_ENV_VARS]);\n\n for (const key of allowedKeys) {\n const value = process.env[key];\n if (typeof value !== 'string') {\n continue;\n }\n\n if (value.startsWith('()')) {\n continue;\n }\n\n env[key] = value;\n }\n\n return env;\n}\n\nconst STREAMING_FEATURE_WARNING =\n \"Claude Agent SDK features (hooks/MCP/images) require streaming input. Set `streamingInput: 'always'` or provide `canUseTool` (auto streams only when canUseTool is set).\";\n\nconst SDK_OPTIONS_BLOCKLIST = new Set(['model', 'abortController', 'prompt', 'outputFormat']);\n\ntype ClaudeToolUse = {\n id: string;\n name: string;\n input: unknown;\n parentToolUseId?: string | null;\n};\n\ntype ClaudeToolResult = {\n id: string;\n name?: string;\n result: unknown;\n isError: boolean;\n};\n\n// Provider extension for tool-error stream parts.\ntype ToolErrorPart = {\n type: 'tool-error';\n toolCallId: string;\n toolName: string;\n error: string;\n providerExecuted: true;\n providerMetadata?: Record<string, JSONValue>;\n};\n\n// Local extension of the AI SDK stream part union to include tool-error.\ntype ExtendedStreamPart = LanguageModelV3StreamPart | ToolErrorPart;\n\ntype ContentBlock = { type: string; [key: string]: unknown };\n\nfunction isContentBlock(item: unknown): item is ContentBlock {\n return typeof item === 'object' && item !== null && 'type' in item;\n}\n\nfunction filterContentBlocks(content: unknown, type: string): ContentBlock[] {\n if (!Array.isArray(content)) return [];\n const blocks = content.filter(\n (item): item is ContentBlock => isContentBlock(item) && item.type === type\n );\n const mismatch = blocks.find((b) => b.type !== type);\n if (mismatch) {\n throw new Error(\n `filterContentBlocks: block type '${mismatch.type}' passed filter for '${type}'`\n );\n }\n return blocks;\n}\n\n/**\n * Usage data from Claude Code SDK.\n */\ntype ClaudeCodeUsage = {\n input_tokens?: number | null;\n output_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n};\n\n/**\n * Creates a zero-initialized usage object for AI SDK v6 stable.\n */\nfunction createEmptyUsage(): LanguageModelV3Usage {\n return {\n inputTokens: {\n total: 0,\n noCache: 0,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 0,\n text: undefined,\n reasoning: undefined,\n },\n raw: undefined,\n };\n}\n\n/**\n * Converts Claude Code SDK usage to AI SDK v6 stable usage format.\n *\n * Maps Claude's flat token counts to the nested structure required by AI SDK v6:\n * - `cache_creation_input_tokens` → `inputTokens.cacheWrite`\n * - `cache_read_input_tokens` → `inputTokens.cacheRead`\n * - `input_tokens` → `inputTokens.noCache`\n * - `inputTokens.total` = sum of all input tokens\n * - `output_tokens` → `outputTokens.total`\n *\n * @param usage - Raw usage data from Claude Code SDK\n * @returns Formatted usage object for AI SDK v6\n */\nfunction convertClaudeCodeUsage(usage: ClaudeCodeUsage): LanguageModelV3Usage {\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const cacheWrite = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n\n return {\n inputTokens: {\n total: inputTokens + cacheWrite + cacheRead,\n noCache: inputTokens,\n cacheRead,\n cacheWrite,\n },\n outputTokens: {\n total: outputTokens,\n text: undefined,\n reasoning: undefined,\n },\n raw: usage as JSONObject,\n };\n}\n\n/**\n * Tracks the streaming lifecycle state for a single tool invocation.\n *\n * The tool streaming lifecycle follows this sequence:\n * 1. Tool use detected → state created with all flags false\n * 2. First input seen → `inputStarted` = true, emit `tool-input-start`\n * 3. Input deltas streamed → emit `tool-input-delta` (may be skipped for large/non-prefix updates)\n * 4. Input finalized → `inputClosed` = true, emit `tool-input-end`\n * 5. Tool call formed → `callEmitted` = true, emit `tool-call`\n * 6. Tool results/errors arrive → emit `tool-result` or `tool-error` (may occur multiple times)\n * 7. Stream ends → state cleaned up by `finalizeToolCalls()`\n *\n * @property name - Tool name from SDK (e.g., \"Bash\", \"Read\")\n * @property lastSerializedInput - Most recent serialized input, used for delta calculation\n * @property inputStarted - True after `tool-input-start` emitted; prevents duplicate start events\n * @property inputClosed - True after `tool-input-end` emitted; ensures proper event ordering\n * @property callEmitted - True after `tool-call` emitted; prevents duplicate call events when\n * multiple result/error chunks arrive for the same tool invocation\n */\ntype ToolStreamState = {\n name: string;\n lastSerializedInput?: string;\n inputStarted: boolean;\n inputClosed: boolean;\n callEmitted: boolean;\n parentToolCallId?: string | null;\n};\n\n/**\n * Queued injection item with content and optional delivery callback.\n */\ntype QueuedInjection = {\n content: string;\n onResult?: (delivered: boolean) => void;\n};\n\n/**\n * Creates a MessageInjector implementation that can queue messages for mid-session injection.\n * The injector uses a queue and signals to coordinate between the producer (user code)\n * and consumer (async generator).\n *\n * Note: getNextItem returns the full QueuedInjection so the consumer can call onResult\n * AFTER successfully yielding, avoiding a race condition with outputStreamEnded.\n */\nfunction createMessageInjector(): {\n injector: MessageInjector;\n getNextItem: () => Promise<QueuedInjection | null>;\n notifySessionEnded: () => void;\n} {\n const queue: QueuedInjection[] = [];\n let closed = false;\n let resolver: ((item: QueuedInjection | null) => void) | null = null;\n\n const injector: MessageInjector = {\n inject(content, onResult) {\n if (closed) {\n // Already closed - immediately notify not delivered\n onResult?.(false);\n return;\n }\n const item: QueuedInjection = { content, onResult };\n if (resolver) {\n // Consumer is waiting, resolve immediately\n const r = resolver;\n resolver = null;\n r(item);\n } else {\n // Queue for later consumption\n queue.push(item);\n }\n },\n close() {\n // Stop accepting new messages, but don't cancel pending ones\n // Pending messages can still be delivered until session ends\n closed = true;\n if (resolver && queue.length === 0) {\n // No pending messages and consumer is waiting - signal done\n resolver(null);\n resolver = null;\n }\n },\n };\n\n const getNextItem = (): Promise<QueuedInjection | null> => {\n if (queue.length > 0) {\n const item = queue.shift();\n if (!item) {\n return Promise.resolve(null);\n }\n // Return the full item - caller is responsible for calling onResult after yielding\n return Promise.resolve(item);\n }\n if (closed) {\n // Closed and queue is empty - no more messages\n return Promise.resolve(null);\n }\n return new Promise((resolve) => {\n resolver = (item) => {\n // Return the full item (or null) - caller handles onResult\n resolve(item);\n };\n });\n };\n\n const notifySessionEnded = () => {\n // Session ended - any remaining queued messages won't be delivered\n for (const item of queue) {\n item.onResult?.(false);\n }\n queue.length = 0;\n closed = true;\n if (resolver) {\n resolver(null);\n resolver = null;\n }\n };\n\n return { injector, getNextItem, notifySessionEnded };\n}\n\nfunction toAsyncIterablePrompt(\n messagesPrompt: string,\n outputStreamEnded: Promise<unknown>,\n sessionId?: string,\n contentParts?: SDKUserMessage['message']['content'],\n onStreamStart?: (injector: MessageInjector) => void\n): AsyncIterable<SDKUserMessage> {\n const content = (\n contentParts && contentParts.length > 0\n ? contentParts\n : [{ type: 'text', text: messagesPrompt }]\n ) as SDKUserMessage['message']['content'];\n\n const initialMsg: SDKUserMessage = {\n type: 'user',\n message: {\n role: 'user',\n content,\n },\n parent_tool_use_id: null,\n session_id: sessionId ?? '',\n };\n\n // If no callback, use simple behavior (backwards compatible)\n if (!onStreamStart) {\n return {\n async *[Symbol.asyncIterator]() {\n yield initialMsg;\n await outputStreamEnded;\n },\n };\n }\n\n // With injection support: create injector and yield messages as they arrive\n const { injector, getNextItem, notifySessionEnded } = createMessageInjector();\n\n return {\n async *[Symbol.asyncIterator]() {\n // Yield initial message\n yield initialMsg;\n\n // Notify consumer that streaming has started\n onStreamStart(injector);\n\n // Race between output ending and new messages arriving\n let streamEnded = false;\n void outputStreamEnded.then(() => {\n streamEnded = true;\n // Notify any pending injections that the session ended\n notifySessionEnded();\n });\n\n // Keep yielding injected messages until stream ends or injector closes\n while (!streamEnded) {\n // Race getNextItem against outputStreamEnded\n // We get the full item so we can call onResult AFTER yielding\n const item = await Promise.race([getNextItem(), outputStreamEnded.then(() => null)]);\n\n if (item === null) {\n // Ensure we don't close the input stream prematurely.\n // Wait for output to complete to avoid truncation issues.\n await outputStreamEnded;\n break;\n }\n\n const sdkMsg: SDKUserMessage = {\n type: 'user',\n message: {\n role: 'user',\n content: [{ type: 'text', text: item.content }],\n },\n parent_tool_use_id: null,\n session_id: sessionId ?? '',\n };\n yield sdkMsg;\n\n // Only report delivery AFTER successfully yielding\n item.onResult?.(true);\n }\n },\n };\n}\n\n/**\n * Options for creating a Claude Code language model instance.\n *\n * @example\n * ```typescript\n * const model = new ClaudeCodeLanguageModel({\n * id: 'opus',\n * settings: {\n * maxTurns: 10,\n * permissionMode: 'auto'\n * }\n * });\n * ```\n */\nexport interface ClaudeCodeLanguageModelOptions {\n /**\n * The model identifier to use.\n * Can be 'opus', 'sonnet', 'haiku', or a custom model string.\n */\n id: ClaudeCodeModelId;\n\n /**\n * Optional settings to configure the model behavior.\n */\n settings?: ClaudeCodeSettings;\n\n /**\n * Validation warnings from settings validation.\n * Used internally to pass warnings from provider.\n */\n settingsValidationWarnings?: string[];\n}\n\n/**\n * Supported Claude model identifiers.\n * - 'opus': Claude Opus (most capable)\n * - 'sonnet': Claude Sonnet (balanced performance)\n * - 'haiku': Claude Haiku (fastest, most cost-effective)\n * - Custom string: Any full model identifier (e.g., 'claude-opus-4-5', 'claude-sonnet-4-5-20250514')\n *\n * @example\n * ```typescript\n * const opusModel = claudeCode('opus');\n * const sonnetModel = claudeCode('sonnet');\n * const haikuModel = claudeCode('haiku');\n * const customModel = claudeCode('claude-opus-4-5');\n * ```\n */\nexport type ClaudeCodeModelId = 'opus' | 'sonnet' | 'haiku' | (string & {});\n\nconst modelMap: Record<string, string> = {\n opus: 'opus',\n sonnet: 'sonnet',\n haiku: 'haiku',\n};\n\n/**\n * Maximum size for tool results sent to the client stream.\n * Interior Claude Code process has full data; this only affects client stream.\n */\nconst MAX_TOOL_RESULT_SIZE = 10000;\n\n/**\n * Truncates large tool results to prevent stream bloat.\n * Only the largest string value in an object/array is truncated.\n * Preserves the original type (array stays array, object stays object).\n */\nfunction truncateToolResultForStream(\n result: unknown,\n maxSize: number = MAX_TOOL_RESULT_SIZE\n): unknown {\n if (typeof result === 'string') {\n if (result.length <= maxSize) return result;\n return result.slice(0, maxSize) + `\\n...[truncated ${result.length - maxSize} chars]`;\n }\n\n if (typeof result !== 'object' || result === null) return result;\n\n // Handle arrays separately to preserve array type\n if (Array.isArray(result)) {\n let largestIndex = -1;\n let largestSize = 0;\n\n for (let i = 0; i < result.length; i++) {\n const value = result[i];\n if (typeof value === 'string' && value.length > largestSize) {\n largestIndex = i;\n largestSize = value.length;\n }\n }\n\n if (largestIndex >= 0 && largestSize > maxSize) {\n const truncatedValue =\n (result[largestIndex] as string).slice(0, maxSize) +\n `\\n...[truncated ${largestSize - maxSize} chars]`;\n const cloned = [...result];\n cloned[largestIndex] = truncatedValue;\n return cloned;\n }\n\n return result;\n }\n\n // For objects, find and truncate only the largest string value\n const obj = result as Record<string, unknown>;\n let largestKey: string | null = null;\n let largestSize = 0;\n\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string' && value.length > largestSize) {\n largestKey = key;\n largestSize = value.length;\n }\n }\n\n if (largestKey && largestSize > maxSize) {\n const truncatedValue =\n (obj[largestKey] as string).slice(0, maxSize) +\n `\\n...[truncated ${largestSize - maxSize} chars]`;\n return { ...obj, [largestKey]: truncatedValue };\n }\n\n return result;\n}\n\n/**\n * Language model implementation for Claude Code SDK.\n * This class implements the AI SDK's LanguageModelV3 interface to provide\n * integration with Claude models through the Claude Agent SDK.\n *\n * Features:\n * - Supports streaming and non-streaming generation\n * - Native structured outputs via SDK's outputFormat (guaranteed schema compliance)\n * - Manages CLI sessions for conversation continuity\n * - Provides detailed error handling and retry logic\n *\n * Limitations:\n * - Image inputs require streaming mode\n * - Some parameters like temperature and max tokens are not supported by the CLI\n *\n * @example\n * ```typescript\n * const model = new ClaudeCodeLanguageModel({\n * id: 'opus',\n * settings: { maxTurns: 5 }\n * });\n *\n * const result = await model.doGenerate({\n * prompt: [{ role: 'user', content: 'Hello!' }],\n * mode: { type: 'regular' }\n * });\n * ```\n */\n\nexport class ClaudeCodeLanguageModel implements LanguageModelV3 {\n readonly specificationVersion = 'v3' as const;\n readonly defaultObjectGenerationMode = 'json' as const;\n readonly supportsImageUrls = false;\n readonly supportedUrls = {};\n readonly supportsStructuredOutputs = true;\n\n // Fallback/magic string constants\n static readonly UNKNOWN_TOOL_NAME = 'unknown-tool';\n\n // Tool input safety limits\n private static readonly MAX_TOOL_INPUT_SIZE = 1_048_576; // 1MB hard limit\n private static readonly MAX_TOOL_INPUT_WARN = 102_400; // 100KB warning threshold\n private static readonly MAX_DELTA_CALC_SIZE = 10_000; // 10KB delta computation threshold\n\n readonly modelId: ClaudeCodeModelId;\n readonly settings: ClaudeCodeSettings;\n\n private sessionId?: string;\n private modelValidationWarning?: string;\n private settingsValidationWarnings: string[];\n private logger: Logger;\n\n constructor(options: ClaudeCodeLanguageModelOptions) {\n this.modelId = options.id;\n this.settings = options.settings ?? {};\n this.settingsValidationWarnings = options.settingsValidationWarnings ?? [];\n\n // Create logger that respects verbose setting\n const baseLogger = getLogger(this.settings.logger);\n this.logger = createVerboseLogger(baseLogger, this.settings.verbose ?? false);\n\n // Validate model ID format\n if (!this.modelId || typeof this.modelId !== 'string' || this.modelId.trim() === '') {\n throw new NoSuchModelError({\n modelId: this.modelId,\n modelType: 'languageModel',\n });\n }\n\n // Additional model ID validation\n this.modelValidationWarning = validateModelId(this.modelId);\n if (this.modelValidationWarning) {\n this.logger.warn(`Claude Code Model: ${this.modelValidationWarning}`);\n }\n }\n\n get provider(): string {\n return 'claude-code';\n }\n\n private getModel(): string {\n const mapped = modelMap[this.modelId];\n return mapped ?? this.modelId;\n }\n\n private getSanitizedSdkOptions(): Partial<Options> | undefined {\n if (!this.settings.sdkOptions || typeof this.settings.sdkOptions !== 'object') {\n return undefined;\n }\n\n const sanitized = { ...(this.settings.sdkOptions as Record<string, unknown>) };\n const blockedKeys = Array.from(SDK_OPTIONS_BLOCKLIST).filter((key) => key in sanitized);\n\n if (blockedKeys.length > 0) {\n this.logger.warn(\n `[claude-code] sdkOptions includes provider-managed fields (${blockedKeys.join(\n ', '\n )}); these will be ignored.`\n );\n blockedKeys.forEach((key) => delete sanitized[key]);\n }\n\n return sanitized as Partial<Options>;\n }\n\n private getEffectiveResume(sdkOptions?: Partial<Options>): string | undefined {\n return sdkOptions?.resume ?? this.settings.resume ?? this.sessionId;\n }\n\n private extractTextAndThinking(content: unknown): { text: string; thinking: string[] } {\n if (!Array.isArray(content)) return { text: '', thinking: [] };\n\n let text = '';\n const thinking: string[] = [];\n\n for (const part of content) {\n if (!isContentBlock(part)) continue;\n if (part.type === 'text' && typeof part.text === 'string') {\n text += part.text;\n } else if (part.type === 'thinking' && typeof part.thinking === 'string') {\n thinking.push(part.thinking as string);\n }\n }\n\n if (text.length > 0 && typeof text !== 'string') {\n throw new Error('extractTextAndThinking: accumulated text must be a string');\n }\n if (thinking.some((t) => typeof t !== 'string')) {\n throw new Error('extractTextAndThinking: all thinking entries must be strings');\n }\n\n return { text, thinking };\n }\n\n private extractToolUses(content: unknown): ClaudeToolUse[] {\n return filterContentBlocks(content, 'tool_use').map((block) => {\n const { id, name, input, parent_tool_use_id } = block as {\n id?: unknown;\n name?: unknown;\n input?: unknown;\n parent_tool_use_id?: unknown;\n };\n return {\n id: typeof id === 'string' && id.length > 0 ? id : generateId(),\n name:\n typeof name === 'string' && name.length > 0\n ? name\n : ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME,\n input,\n parentToolUseId: typeof parent_tool_use_id === 'string' ? parent_tool_use_id : null,\n } satisfies ClaudeToolUse;\n });\n }\n\n private extractToolResults(content: unknown): ClaudeToolResult[] {\n return filterContentBlocks(content, 'tool_result').map((block) => {\n const { tool_use_id, content, is_error, name } = block as {\n tool_use_id?: unknown;\n content?: unknown;\n is_error?: unknown;\n name?: unknown;\n };\n return {\n id: typeof tool_use_id === 'string' && tool_use_id.length > 0 ? tool_use_id : generateId(),\n name: typeof name === 'string' && name.length > 0 ? name : undefined,\n result: content,\n isError: Boolean(is_error),\n } satisfies ClaudeToolResult;\n });\n }\n\n private extractToolErrors(content: unknown): Array<{\n id: string;\n name?: string;\n error: unknown;\n }> {\n return filterContentBlocks(content, 'tool_error').map((block) => {\n const { tool_use_id, error, name } = block as {\n tool_use_id?: unknown;\n error?: unknown;\n name?: unknown;\n };\n return {\n id: typeof tool_use_id === 'string' && tool_use_id.length > 0 ? tool_use_id : generateId(),\n name: typeof name === 'string' && name.length > 0 ? name : undefined,\n error,\n };\n });\n }\n\n private serializeToolInput(input: unknown): string {\n if (typeof input === 'string') {\n return this.checkInputSize(input);\n }\n\n if (input === undefined) {\n return '';\n }\n\n try {\n const serialized = JSON.stringify(input);\n return this.checkInputSize(serialized);\n } catch {\n const fallback = String(input);\n return this.checkInputSize(fallback);\n }\n }\n\n private checkInputSize(str: string): string {\n const length = str.length;\n\n if (length > ClaudeCodeLanguageModel.MAX_TOOL_INPUT_SIZE) {\n throw new Error(\n `Tool input exceeds maximum size of ${ClaudeCodeLanguageModel.MAX_TOOL_INPUT_SIZE} bytes (got ${length} bytes). This may indicate a malformed request or an attempt to process excessively large data.`\n );\n }\n\n if (length > ClaudeCodeLanguageModel.MAX_TOOL_INPUT_WARN) {\n this.logger.warn(\n `[claude-code] Large tool input detected: ${length} bytes. Performance may be impacted. Consider chunking or reducing input size.`\n );\n }\n\n return str;\n }\n\n private normalizeToolResult(result: unknown): unknown {\n if (typeof result === 'string') {\n try {\n return JSON.parse(result);\n } catch {\n return result;\n }\n }\n // Handle MCP content format: [{type: 'text', text: '...'}, ...]\n // MCP tools can return multiple content blocks; only normalize when all blocks are text.\n if (Array.isArray(result) && result.length > 0) {\n // Collect all text content from text blocks\n const textBlocks = result\n .filter(\n (block): block is { type: 'text'; text: string } =>\n block?.type === 'text' && typeof block.text === 'string'\n )\n .map((block) => block.text);\n\n if (textBlocks.length !== result.length) {\n return result;\n }\n\n // If single text block, try to parse as JSON\n if (textBlocks.length === 1) {\n try {\n return JSON.parse(textBlocks[0]);\n } catch {\n return textBlocks[0];\n }\n }\n\n // Multiple text blocks: join them and try to parse as JSON\n const combined = textBlocks.join('\\n');\n try {\n return JSON.parse(combined);\n } catch {\n return combined;\n }\n }\n\n return result;\n }\n\n private generateAllWarnings(\n options:\n | Parameters<LanguageModelV3['doGenerate']>[0]\n | Parameters<LanguageModelV3['doStream']>[0],\n prompt: string\n ): SharedV3Warning[] {\n const warnings: SharedV3Warning[] = [];\n const unsupportedParams: string[] = [];\n\n // Check for unsupported parameters\n if (options.temperature !== undefined) unsupportedParams.push('temperature');\n if (options.topP !== undefined) unsupportedParams.push('topP');\n if (options.topK !== undefined) unsupportedParams.push('topK');\n if (options.presencePenalty !== undefined) unsupportedParams.push('presencePenalty');\n if (options.frequencyPenalty !== undefined) unsupportedParams.push('frequencyPenalty');\n if (options.stopSequences !== undefined && options.stopSequences.length > 0)\n unsupportedParams.push('stopSequences');\n if (options.seed !== undefined) unsupportedParams.push('seed');\n\n if (unsupportedParams.length > 0) {\n // Add a warning for each unsupported parameter\n for (const param of unsupportedParams) {\n warnings.push({\n type: 'unsupported',\n feature: param,\n details: `Claude Code SDK does not support the ${param} parameter. It will be ignored.`,\n });\n }\n }\n\n // Add model validation warning if present\n if (this.modelValidationWarning) {\n warnings.push({\n type: 'other',\n message: this.modelValidationWarning,\n });\n }\n\n // Add settings validation warnings\n this.settingsValidationWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n\n // Warn if JSON response format is requested without a schema\n // Claude Code only supports structured outputs with schemas (like Anthropic's API)\n if (options.responseFormat?.type === 'json' && !options.responseFormat.schema) {\n warnings.push({\n type: 'unsupported',\n feature: 'responseFormat',\n details:\n 'JSON response format requires a schema for the Claude Code provider. The JSON responseFormat is ignored and the call is treated as plain text.',\n });\n }\n\n // Validate prompt\n const promptWarning = validatePrompt(prompt);\n if (promptWarning) {\n warnings.push({\n type: 'other',\n message: promptWarning,\n });\n }\n\n return warnings;\n }\n\n private createQueryOptions(\n abortController: AbortController,\n responseFormat?: Parameters<LanguageModelV3['doGenerate']>[0]['responseFormat'],\n stderrCollector?: (data: string) => void,\n sdkOptions?: Partial<Options>,\n effectiveResume?: string\n ): Options {\n const opts: Partial<Options> & Record<string, unknown> = {\n model: this.getModel(),\n abortController,\n resume: effectiveResume ?? this.settings.resume ?? this.sessionId,\n pathToClaudeCodeExecutable: this.settings.pathToClaudeCodeExecutable,\n maxTurns: this.settings.maxTurns,\n maxThinkingTokens: this.settings.maxThinkingTokens,\n thinking: this.settings.thinking,\n effort: this.settings.effort,\n promptSuggestions: this.settings.promptSuggestions,\n cwd: this.settings.cwd,\n executable: this.settings.executable,\n executableArgs: this.settings.executableArgs,\n permissionMode: this.settings.permissionMode,\n permissionPromptToolName: this.settings.permissionPromptToolName,\n continue: this.settings.continue,\n allowedTools: this.settings.allowedTools,\n disallowedTools: this.settings.disallowedTools,\n betas: this.settings.betas,\n allowDangerouslySkipPermissions: this.settings.allowDangerouslySkipPermissions,\n enableFileCheckpointing: this.settings.enableFileCheckpointing,\n maxBudgetUsd: this.settings.maxBudgetUsd,\n plugins: this.settings.plugins,\n resumeSessionAt: this.settings.resumeSessionAt,\n sandbox: this.settings.sandbox,\n tools: this.settings.tools,\n mcpServers: this.settings.mcpServers,\n canUseTool: this.settings.canUseTool,\n };\n // NEW: Agent SDK options with legacy mapping\n if (this.settings.systemPrompt !== undefined) {\n opts.systemPrompt = this.settings.systemPrompt;\n } else if (this.settings.customSystemPrompt !== undefined) {\n // Deprecation warning for legacy field\n this.logger.warn(\n \"[claude-code] 'customSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt' instead (string or { type: 'preset', preset: 'claude_code', append? }).\"\n );\n opts.systemPrompt = this.settings.customSystemPrompt;\n } else if (this.settings.appendSystemPrompt !== undefined) {\n // Deprecation warning for legacy field\n this.logger.warn(\n \"[claude-code] 'appendSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt: { type: 'preset', preset: 'claude_code', append: <text> }' instead.\"\n );\n opts.systemPrompt = {\n type: 'preset',\n preset: 'claude_code',\n append: this.settings.appendSystemPrompt,\n } as const;\n }\n if (this.settings.settingSources !== undefined) {\n opts.settingSources = this.settings.settingSources;\n }\n if (this.settings.additionalDirectories !== undefined) {\n opts.additionalDirectories = this.settings.additionalDirectories;\n }\n if (this.settings.agents !== undefined) {\n opts.agents = this.settings.agents;\n }\n if (this.settings.includePartialMessages !== undefined) {\n opts.includePartialMessages = this.settings.includePartialMessages;\n }\n if (this.settings.fallbackModel !== undefined) {\n opts.fallbackModel = this.settings.fallbackModel;\n }\n if (this.settings.forkSession !== undefined) {\n opts.forkSession = this.settings.forkSession;\n }\n if (this.settings.strictMcpConfig !== undefined) {\n opts.strictMcpConfig = this.settings.strictMcpConfig;\n }\n if (this.settings.extraArgs !== undefined) {\n opts.extraArgs = this.settings.extraArgs;\n }\n if (this.settings.persistSession !== undefined) {\n opts.persistSession = this.settings.persistSession;\n }\n if (this.settings.spawnClaudeCodeProcess !== undefined) {\n opts.spawnClaudeCodeProcess = this.settings.spawnClaudeCodeProcess;\n }\n // hooks is supported in newer SDKs; include it if provided\n if (this.settings.hooks) {\n opts.hooks = this.settings.hooks;\n }\n if (this.settings.sessionId !== undefined) {\n opts.sessionId = this.settings.sessionId;\n }\n if (this.settings.debug !== undefined) {\n opts.debug = this.settings.debug;\n }\n if (this.settings.debugFile !== undefined) {\n opts.debugFile = this.settings.debugFile;\n }\n\n const sdkOverrides = sdkOptions\n ? (sdkOptions as Partial<Options> & Record<string, unknown>)\n : undefined;\n const sdkEnv =\n sdkOverrides && typeof sdkOverrides.env === 'object' && sdkOverrides.env !== null\n ? (sdkOverrides.env as Record<string, string | undefined>)\n : undefined;\n const sdkStderr =\n sdkOverrides && typeof sdkOverrides.stderr === 'function'\n ? (sdkOverrides.stderr as (data: string) => void)\n : undefined;\n if (sdkOverrides) {\n const rest = { ...sdkOverrides };\n delete rest.env;\n delete rest.stderr;\n Object.assign(opts, rest);\n }\n\n // Wrap stderr callback to also collect data for error reporting\n const userStderrCallback = sdkStderr ?? this.settings.stderr;\n if (stderrCollector || userStderrCallback) {\n opts.stderr = (data: string) => {\n if (stderrCollector) stderrCollector(data);\n if (userStderrCallback) userStderrCallback(data);\n };\n }\n\n if (this.settings.env !== undefined || sdkEnv !== undefined) {\n const baseEnv = getBaseProcessEnv();\n opts.env = { ...baseEnv, ...this.settings.env, ...sdkEnv };\n }\n\n // Native structured outputs (SDK 0.1.45+)\n if (responseFormat?.type === 'json' && responseFormat.schema) {\n opts.outputFormat = {\n type: 'json_schema',\n schema: responseFormat.schema as Record<string, unknown>,\n };\n }\n\n return opts as Options;\n }\n\n private handleClaudeCodeError(\n error: unknown,\n messagesPrompt: string,\n collectedStderr?: string\n ): APICallError | LoadAPIKeyError {\n // Handle AbortError from the SDK\n if (isAbortError(error)) {\n // Return the abort reason if available, otherwise the error itself\n throw error;\n }\n\n // Type guard for error with properties\n const isErrorWithMessage = (err: unknown): err is { message?: string } => {\n return typeof err === 'object' && err !== null && 'message' in err;\n };\n\n const isErrorWithCode = (\n err: unknown\n ): err is { code?: string; exitCode?: number; stderr?: string } => {\n return typeof err === 'object' && err !== null;\n };\n\n // Check for authentication errors with improved detection\n const authErrorPatterns = [\n 'not logged in',\n 'authentication',\n 'unauthorized',\n 'auth failed',\n 'please login',\n 'claude login',\n 'claude auth login',\n '/login', // CLI returns \"Please run /login\"\n 'invalid api key',\n ];\n\n const errorMessage =\n isErrorWithMessage(error) && error.message ? error.message.toLowerCase() : '';\n\n const exitCode =\n isErrorWithCode(error) && typeof error.exitCode === 'number' ? error.exitCode : undefined;\n\n const isAuthError =\n authErrorPatterns.some((pattern) => errorMessage.includes(pattern)) || exitCode === 401;\n\n if (isAuthError) {\n return createAuthenticationError({\n message:\n isErrorWithMessage(error) && error.message\n ? error.message\n : 'Authentication failed. Please ensure Claude Code SDK is properly authenticated.',\n });\n }\n\n // Check for timeout errors\n const errorCode = isErrorWithCode(error) && typeof error.code === 'string' ? error.code : '';\n\n if (errorCode === 'ETIMEDOUT' || errorMessage.includes('timeout')) {\n return createTimeoutError({\n message: isErrorWithMessage(error) && error.message ? error.message : 'Request timed out',\n promptExcerpt: messagesPrompt.substring(0, 200),\n // Don't specify timeoutMs since we don't know the actual timeout value\n // It's controlled by the consumer via AbortSignal\n });\n }\n\n // Create general API call error with appropriate retry flag\n const isRetryable =\n errorCode === 'ENOENT' ||\n errorCode === 'ECONNREFUSED' ||\n errorCode === 'ETIMEDOUT' ||\n errorCode === 'ECONNRESET';\n\n // Use error.stderr if available from SDK, otherwise use collected stderr\n const stderrFromError =\n isErrorWithCode(error) && typeof error.stderr === 'string' ? error.stderr : undefined;\n const stderr = stderrFromError || collectedStderr || undefined;\n\n return createAPICallError({\n message: isErrorWithMessage(error) && error.message ? error.message : 'Claude Code SDK error',\n code: errorCode || undefined,\n exitCode: exitCode,\n stderr,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable,\n });\n }\n\n private setSessionId(sessionId: string): void {\n this.sessionId = sessionId;\n const warning = validateSessionId(sessionId);\n if (warning) {\n this.logger.warn(`Claude Code Session: ${warning}`);\n }\n }\n\n private logMcpConnectionIssues(\n mcpServers: Array<{ name?: string; status?: string; error?: string }> | undefined\n ): void {\n if (!Array.isArray(mcpServers) || mcpServers.length === 0) {\n return;\n }\n\n const serversNeedingAttention = mcpServers.filter((server) => {\n const status = typeof server.status === 'string' ? server.status.toLowerCase() : '';\n return status === 'failed' || status === 'needs-auth';\n });\n\n if (serversNeedingAttention.length === 0) {\n return;\n }\n\n const details = serversNeedingAttention\n .map((server) => {\n const name =\n typeof server.name === 'string' && server.name.trim().length > 0\n ? server.name\n : '<unknown>';\n const status =\n typeof server.status === 'string' && server.status.trim().length > 0\n ? server.status\n : 'unknown';\n const error =\n typeof server.error === 'string' && server.error.trim().length > 0\n ? ` (${server.error})`\n : '';\n return `${name}:${status}${error}`;\n })\n .join(', ');\n\n this.logger.warn(`[claude-code] MCP servers not connected: ${details}`);\n }\n\n async doGenerate(\n options: Parameters<LanguageModelV3['doGenerate']>[0]\n ): Promise<Awaited<ReturnType<LanguageModelV3['doGenerate']>>> {\n this.logger.debug(`[claude-code] Starting doGenerate request with model: ${this.modelId}`);\n this.logger.debug(`[claude-code] Response format: ${options.responseFormat?.type ?? 'none'}`);\n\n const {\n messagesPrompt,\n warnings: messageWarnings,\n streamingContentParts,\n hasImageParts,\n } = convertToClaudeCodeMessages(options.prompt);\n\n this.logger.debug(\n `[claude-code] Converted ${options.prompt.length} messages, hasImageParts: ${hasImageParts}`\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal?.aborted) {\n // Propagate already-aborted state immediately with original reason\n abortController.abort(options.abortSignal.reason);\n } else if (options.abortSignal) {\n abortListener = () => abortController.abort(options.abortSignal?.reason);\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n // Collect stderr for error reporting (SDK may not include it in errors)\n let collectedStderr = '';\n const stderrCollector = (data: string) => {\n collectedStderr += data;\n };\n\n const sdkOptions = this.getSanitizedSdkOptions();\n const effectiveResume = this.getEffectiveResume(sdkOptions);\n const queryOptions = this.createQueryOptions(\n abortController,\n options.responseFormat,\n stderrCollector,\n sdkOptions,\n effectiveResume\n );\n\n let text = '';\n const thinkingTraces: string[] = [];\n let structuredOutput: unknown | undefined;\n let usage: LanguageModelV3Usage = createEmptyUsage();\n let finishReason: LanguageModelV3FinishReason = { unified: 'stop', raw: undefined };\n let wasTruncated = false;\n let costUsd: number | undefined;\n let durationMs: number | undefined;\n let modelUsage: Record<string, unknown> | undefined;\n const warnings: SharedV3Warning[] = this.generateAllWarnings(options, messagesPrompt);\n\n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const modeSetting = this.settings.streamingInput ?? 'auto';\n const effectiveCanUseTool = sdkOptions?.canUseTool ?? this.settings.canUseTool;\n const effectivePermissionPromptToolName =\n sdkOptions?.permissionPromptToolName ?? this.settings.permissionPromptToolName;\n const wantsStreamInput =\n modeSetting === 'always' || (modeSetting === 'auto' && !!effectiveCanUseTool);\n\n if (!wantsStreamInput && hasImageParts) {\n warnings.push({\n type: 'other',\n message: STREAMING_FEATURE_WARNING,\n });\n }\n\n let done = () => {};\n const outputStreamEnded = new Promise((resolve) => {\n done = () => resolve(undefined);\n });\n try {\n if (effectiveCanUseTool && effectivePermissionPromptToolName) {\n throw new Error(\n \"canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.\"\n );\n }\n // hold input stream open until results\n // see: https://github.com/anthropics/claude-code/issues/4775\n const sdkPrompt = wantsStreamInput\n ? toAsyncIterablePrompt(\n messagesPrompt,\n outputStreamEnded,\n effectiveResume,\n streamingContentParts,\n this.settings.onStreamStart\n )\n : messagesPrompt;\n\n this.logger.debug(\n `[claude-code] Executing query with streamingInput: ${wantsStreamInput}, session: ${effectiveResume ?? 'new'}`\n );\n\n const response = query({\n prompt: sdkPrompt,\n options: queryOptions,\n });\n\n // Invoke onQueryCreated callback to expose Query object for advanced features\n // like mid-stream message injection via query.streamInput()\n this.settings.onQueryCreated?.(response);\n\n for await (const message of response) {\n this.logger.debug(`[claude-code] Received message type: ${message.type}`);\n if (message.type === 'assistant') {\n const { text: messageText, thinking: messageThinking } = this.extractTextAndThinking(\n message.message.content\n );\n text += messageText;\n thinkingTraces.push(...messageThinking);\n } else if (message.type === 'result') {\n done();\n this.setSessionId(message.session_id);\n costUsd = message.total_cost_usd;\n durationMs = message.duration_ms;\n modelUsage = message.modelUsage;\n\n // Handle is_error flag in result message (e.g., auth failures)\n // The CLI returns successful JSON with is_error: true and error message in result field\n if ('is_error' in message && message.is_error === true) {\n const errorMessage =\n 'result' in message && typeof message.result === 'string'\n ? message.result\n : 'Claude Code CLI returned an error';\n throw Object.assign(new Error(errorMessage), { exitCode: 1 });\n }\n\n // Handle structured output errors (SDK 0.1.45+)\n // Use string comparison to support new SDK subtypes not yet in TypeScript definitions\n if ((message.subtype as string) === 'error_max_structured_output_retries') {\n throw new Error(\n 'Failed to generate valid structured output after maximum retries. The model could not produce a response matching the required schema.'\n );\n }\n\n // Capture structured output if available (SDK 0.1.45+)\n if ('structured_output' in message && message.structured_output !== undefined) {\n structuredOutput = message.structured_output;\n this.logger.debug('[claude-code] Received structured output from SDK');\n }\n\n this.logger.info(\n `[claude-code] Request completed - Session: ${message.session_id}, Cost: $${costUsd?.toFixed(4) ?? 'N/A'}, Duration: ${durationMs ?? 'N/A'}ms`\n );\n\n if ('usage' in message) {\n usage = convertClaudeCodeUsage(message.usage);\n\n this.logger.debug(\n `[claude-code] Token usage - Input: ${usage.inputTokens.total}, Output: ${usage.outputTokens.total}`\n );\n }\n\n const stopReason =\n 'stop_reason' in message\n ? ((message as Record<string, unknown>).stop_reason as string | null | undefined)\n : undefined;\n finishReason = mapClaudeCodeFinishReason(message.subtype, stopReason);\n this.logger.debug(`[claude-code] Finish reason: ${finishReason.unified}`);\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.logMcpConnectionIssues(message.mcp_servers);\n this.setSessionId(message.session_id);\n this.logger.info(`[claude-code] Session initialized: ${message.session_id}`);\n }\n }\n } catch (error: unknown) {\n done();\n this.logger.debug(\n `[claude-code] Error during doGenerate: ${error instanceof Error ? error.message : String(error)}`\n );\n\n // Special handling for AbortError to preserve abort signal reason\n if (isAbortError(error)) {\n this.logger.debug('[claude-code] Request aborted by user');\n throw options.abortSignal?.aborted ? options.abortSignal.reason : error;\n }\n\n if (isClaudeCodeTruncationError(error, text)) {\n this.logger.warn(\n `[claude-code] Detected truncated response, returning ${text.length} characters of buffered text`\n );\n wasTruncated = true;\n finishReason = { unified: 'length', raw: 'truncation' };\n warnings.push({\n type: 'other',\n message: CLAUDE_CODE_TRUNCATION_WARNING,\n });\n } else {\n // Use unified error handler\n throw this.handleClaudeCodeError(error, messagesPrompt, collectedStderr);\n }\n } finally {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n }\n\n // Use structured output from SDK if available (native JSON schema support)\n // Otherwise fall back to accumulated text\n const finalText = structuredOutput !== undefined ? JSON.stringify(structuredOutput) : text;\n\n return {\n content: [\n ...thinkingTraces.map((trace) => ({\n type: 'reasoning' as const,\n text: trace,\n })),\n { type: 'text' as const, text: finalText },\n ],\n usage,\n finishReason,\n warnings,\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n request: {\n body: messagesPrompt,\n },\n providerMetadata: {\n 'claude-code': {\n ...(this.sessionId !== undefined && { sessionId: this.sessionId }),\n ...(costUsd !== undefined && { costUsd }),\n ...(durationMs !== undefined && { durationMs }),\n ...(modelUsage !== undefined && { modelUsage: modelUsage as unknown as JSONValue }),\n ...(wasTruncated && { truncated: true }),\n ...(thinkingTraces.length > 0 && { thinkingTraces }),\n },\n },\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV3['doStream']>[0]\n ): Promise<Awaited<ReturnType<LanguageModelV3['doStream']>>> {\n this.logger.debug(`[claude-code] Starting doStream request with model: ${this.modelId}`);\n this.logger.debug(`[claude-code] Response format: ${options.responseFormat?.type ?? 'none'}`);\n\n const {\n messagesPrompt,\n warnings: messageWarnings,\n streamingContentParts,\n hasImageParts,\n } = convertToClaudeCodeMessages(options.prompt);\n\n this.logger.debug(\n `[claude-code] Converted ${options.prompt.length} messages for streaming, hasImageParts: ${hasImageParts}`\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal?.aborted) {\n // Propagate already-aborted state immediately with original reason\n abortController.abort(options.abortSignal.reason);\n } else if (options.abortSignal) {\n abortListener = () => abortController.abort(options.abortSignal?.reason);\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n // Collect stderr for error reporting (SDK may not include it in errors)\n let collectedStderr = '';\n const stderrCollector = (data: string) => {\n collectedStderr += data;\n };\n\n const sdkOptions = this.getSanitizedSdkOptions();\n const effectiveResume = this.getEffectiveResume(sdkOptions);\n const queryOptions = this.createQueryOptions(\n abortController,\n options.responseFormat,\n stderrCollector,\n sdkOptions,\n effectiveResume\n );\n\n // Enable partial messages for true streaming (token-by-token delivery)\n // This can be overridden by user settings, but we default to true for doStream\n if (queryOptions.includePartialMessages === undefined) {\n queryOptions.includePartialMessages = true;\n }\n\n const warnings: SharedV3Warning[] = this.generateAllWarnings(options, messagesPrompt);\n\n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const modeSetting = this.settings.streamingInput ?? 'auto';\n const effectiveCanUseTool = sdkOptions?.canUseTool ?? this.settings.canUseTool;\n const effectivePermissionPromptToolName =\n sdkOptions?.permissionPromptToolName ?? this.settings.permissionPromptToolName;\n const wantsStreamInput =\n modeSetting === 'always' || (modeSetting === 'auto' && !!effectiveCanUseTool);\n\n if (!wantsStreamInput && hasImageParts) {\n warnings.push({\n type: 'other',\n message: STREAMING_FEATURE_WARNING,\n });\n }\n\n const stream = new ReadableStream<ExtendedStreamPart>({\n start: async (controller) => {\n let done = () => {};\n const outputStreamEnded = new Promise((resolve) => {\n done = () => resolve(undefined);\n });\n const toolStates = new Map<string, ToolStreamState>();\n // Track active Task tools for subagent hierarchy\n // Using a Map instead of stack to correctly handle parallel agents\n const activeTaskTools = new Map<string, { startTime: number }>();\n\n // Helper to get fallback parent - only returns a parent when exactly ONE Task is active\n // This prevents incorrect grouping when parallel agents run simultaneously\n const getFallbackParentId = (): string | null => {\n if (activeTaskTools.size === 1) {\n return activeTaskTools.keys().next().value ?? null;\n }\n return null;\n };\n\n const streamWarnings: SharedV3Warning[] = [];\n\n const closeToolInput = (toolId: string, state: ToolStreamState) => {\n if (!state.inputClosed && state.inputStarted) {\n controller.enqueue({\n type: 'tool-input-end',\n id: toolId,\n });\n state.inputClosed = true;\n }\n };\n\n const emitToolCall = (toolId: string, state: ToolStreamState) => {\n if (state.callEmitted) {\n return;\n }\n\n closeToolInput(toolId, state);\n\n controller.enqueue({\n type: 'tool-call',\n toolCallId: toolId,\n toolName: state.name,\n input: state.lastSerializedInput ?? '',\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined (not in user's tools map)\n providerMetadata: {\n 'claude-code': {\n // rawInput preserves the original serialized format before AI SDK normalization.\n // Use this if you need the exact string sent to the Claude CLI, which may differ\n // from the `input` field after AI SDK processing.\n rawInput: state.lastSerializedInput ?? '',\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n state.callEmitted = true;\n };\n\n const finalizeToolCalls = () => {\n for (const [toolId, state] of toolStates) {\n emitToolCall(toolId, state);\n }\n toolStates.clear();\n };\n\n let usage: LanguageModelV3Usage = createEmptyUsage();\n let accumulatedText = '';\n let textPartId: string | undefined;\n let streamedTextLength = 0; // Track text already emitted via stream_events to avoid duplication\n let hasReceivedStreamEvents = false; // Track if we've received any stream_events\n let hasStreamedJson = false; // Track if JSON has been streamed via input_json_delta\n\n // Content block streaming: Map block indices to tool IDs and accumulated JSON\n const toolBlocksByIndex = new Map<number, string>();\n const toolInputAccumulators = new Map<string, string>();\n\n // Track text content blocks by index for correlating text_delta with text parts\n const textBlocksByIndex = new Map<number, string>();\n\n // Track if text was streamed via content blocks to prevent double emission in result handler\n let textStreamedViaContentBlock = false;\n\n // Extended thinking: Map block indices to reasoning part IDs\n const reasoningBlocksByIndex = new Map<number, string>();\n let currentReasoningPartId: string | undefined;\n\n try {\n // Emit stream-start with warnings\n controller.enqueue({ type: 'stream-start', warnings });\n\n if (effectiveCanUseTool && effectivePermissionPromptToolName) {\n throw new Error(\n \"canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.\"\n );\n }\n // hold input stream open until results\n // see: https://github.com/anthropics/claude-code/issues/4775\n const sdkPrompt = wantsStreamInput\n ? toAsyncIterablePrompt(\n messagesPrompt,\n outputStreamEnded,\n effectiveResume,\n streamingContentParts,\n this.settings.onStreamStart\n )\n : messagesPrompt;\n\n this.logger.debug(\n `[claude-code] Starting stream query with streamingInput: ${wantsStreamInput}, session: ${effectiveResume ?? 'new'}`\n );\n\n const response = query({\n prompt: sdkPrompt,\n options: queryOptions,\n });\n\n // Invoke onQueryCreated callback to expose Query object for advanced features\n // like mid-stream message injection via query.streamInput()\n this.settings.onQueryCreated?.(response);\n\n for await (const message of response) {\n this.logger.debug(`[claude-code] Stream received message type: ${message.type}`);\n\n // Handle streaming events (token-by-token delivery via includePartialMessages)\n if (message.type === 'stream_event') {\n const streamEvent = message as SDKPartialAssistantMessage;\n const event = streamEvent.event;\n\n // Check for text_delta events within content_block_delta\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'text_delta' &&\n 'text' in event.delta &&\n event.delta.text\n ) {\n const deltaText = event.delta.text;\n hasReceivedStreamEvents = true;\n\n // Don't emit text deltas in JSON mode - accumulate instead\n if (options.responseFormat?.type === 'json') {\n accumulatedText += deltaText;\n streamedTextLength += deltaText.length;\n continue;\n }\n\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: deltaText,\n });\n accumulatedText += deltaText;\n streamedTextLength += deltaText.length;\n }\n // Handle input_json_delta events for structured output streaming\n // The SDK uses a StructuredOutput tool internally, and JSON is streamed via input_json_delta\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'input_json_delta' &&\n 'partial_json' in event.delta &&\n event.delta.partial_json\n ) {\n const jsonDelta = event.delta.partial_json;\n hasReceivedStreamEvents = true;\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n\n // In JSON mode, prioritize streaming to text-delta for streamObject() support\n // The SDK's internal StructuredOutput tool uses input_json_delta to stream JSON responses\n if (options.responseFormat?.type === 'json') {\n // Emit text-start if this is the first JSON delta\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: jsonDelta,\n });\n accumulatedText += jsonDelta;\n streamedTextLength += jsonDelta.length;\n hasStreamedJson = true;\n continue;\n }\n\n // In non-JSON mode, route to tool-input-delta if we have a tracked tool\n const toolId = toolBlocksByIndex.get(blockIndex);\n if (toolId) {\n // Accumulate and emit tool-input-delta\n const accumulated = (toolInputAccumulators.get(toolId) ?? '') + jsonDelta;\n toolInputAccumulators.set(toolId, accumulated);\n\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: jsonDelta,\n });\n continue;\n }\n // input_json_delta without tool context in non-JSON mode is ignored\n }\n\n // Handle content_block_start for tool_use - emit tool-input-start immediately\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'tool_use'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n const toolBlock = event.content_block as {\n type: string;\n id?: string;\n name?: string;\n };\n const toolId =\n typeof toolBlock.id === 'string' && toolBlock.id.length > 0\n ? toolBlock.id\n : generateId();\n const toolName =\n typeof toolBlock.name === 'string' && toolBlock.name.length > 0\n ? toolBlock.name\n : ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n hasReceivedStreamEvents = true;\n\n // Close any active text part before tool starts\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n // Track this block for later delta/stop events\n toolBlocksByIndex.set(blockIndex, toolId);\n toolInputAccumulators.set(toolId, '');\n\n // Create tool state if not exists\n let state = toolStates.get(toolId);\n if (!state) {\n // Use timing-based inference for parent (Task tools are top-level)\n const currentParentId = toolName === 'Task' ? null : getFallbackParentId();\n state = {\n name: toolName,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: currentParentId,\n };\n toolStates.set(toolId, state);\n }\n\n // Emit tool-input-start immediately with providerMetadata for parent context\n if (!state.inputStarted) {\n this.logger.debug(\n `[claude-code] Tool input started (content_block) - Tool: ${toolName}, ID: ${toolId}, parent: ${state.parentToolCallId}`\n );\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n\n // Track Task tools as active so nested tools can reference them as parent\n if (toolName === 'Task') {\n activeTaskTools.set(toolId, { startTime: Date.now() });\n }\n state.inputStarted = true;\n }\n continue;\n }\n\n // Handle content_block_start for text - emit text-start early\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'text'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Generate text part ID early and map to block index\n const partId = generateId();\n textBlocksByIndex.set(blockIndex, partId);\n textPartId = partId;\n\n this.logger.debug(\n `[claude-code] Text content block started - Index: ${blockIndex}, ID: ${partId}`\n );\n\n controller.enqueue({\n type: 'text-start',\n id: partId,\n });\n textStreamedViaContentBlock = true;\n continue;\n }\n\n // Handle content_block_start for thinking - emit reasoning-start immediately\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'thinking'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Close any active text part before reasoning starts\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n const reasoningPartId = generateId();\n reasoningBlocksByIndex.set(blockIndex, reasoningPartId);\n currentReasoningPartId = reasoningPartId;\n\n this.logger.debug(\n `[claude-code] Reasoning started (content_block) - ID: ${reasoningPartId}`\n );\n controller.enqueue({\n type: 'reasoning-start',\n id: reasoningPartId,\n });\n continue;\n }\n\n // Handle thinking_delta for extended thinking\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'thinking_delta' &&\n 'thinking' in event.delta &&\n event.delta.thinking\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n const reasoningPartId =\n reasoningBlocksByIndex.get(blockIndex) ?? currentReasoningPartId;\n hasReceivedStreamEvents = true;\n\n if (reasoningPartId) {\n controller.enqueue({\n type: 'reasoning-delta',\n id: reasoningPartId,\n delta: event.delta.thinking,\n });\n }\n continue;\n }\n\n // Handle content_block_stop - finalize tool input, text, or reasoning\n if (event.type === 'content_block_stop') {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Check if this is a tool block\n const toolId = toolBlocksByIndex.get(blockIndex);\n if (toolId) {\n const state = toolStates.get(toolId);\n if (state && !state.inputClosed) {\n const accumulatedInput = toolInputAccumulators.get(toolId) ?? '';\n this.logger.debug(\n `[claude-code] Tool content block stopped - Index: ${blockIndex}, Tool: ${state.name}, ID: ${toolId}`\n );\n controller.enqueue({\n type: 'tool-input-end',\n id: toolId,\n });\n state.inputClosed = true;\n const effectiveInput = accumulatedInput || state.lastSerializedInput || '';\n state.lastSerializedInput = effectiveInput;\n\n // Emit tool-call immediately when input is complete (don't wait for result)\n // This allows UI to show \"running\" state while tool executes\n if (!state.callEmitted) {\n controller.enqueue({\n type: 'tool-call',\n toolCallId: toolId,\n toolName: state.name,\n input: effectiveInput,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n 'claude-code': {\n rawInput: effectiveInput,\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n state.callEmitted = true;\n }\n }\n toolBlocksByIndex.delete(blockIndex);\n toolInputAccumulators.delete(toolId);\n continue;\n }\n\n // Check if this is a text block\n const textId = textBlocksByIndex.get(blockIndex);\n if (textId) {\n this.logger.debug(\n `[claude-code] Text content block stopped - Index: ${blockIndex}, ID: ${textId}`\n );\n controller.enqueue({\n type: 'text-end',\n id: textId,\n });\n textBlocksByIndex.delete(blockIndex);\n if (textPartId === textId) {\n textPartId = undefined;\n }\n continue;\n }\n\n // Check if this is a reasoning block\n const reasoningPartId = reasoningBlocksByIndex.get(blockIndex);\n if (reasoningPartId) {\n this.logger.debug(\n `[claude-code] Reasoning ended (content_block) - ID: ${reasoningPartId}`\n );\n controller.enqueue({\n type: 'reasoning-end',\n id: reasoningPartId,\n });\n reasoningBlocksByIndex.delete(blockIndex);\n if (currentReasoningPartId === reasoningPartId) {\n currentReasoningPartId = undefined;\n }\n continue;\n }\n }\n\n // Other stream_event types are informational\n continue;\n }\n\n if (message.type === 'assistant') {\n if (!message.message?.content) {\n this.logger.warn(\n `[claude-code] Unexpected assistant message structure: missing content field. Message type: ${message.type}. This may indicate an SDK protocol violation.`\n );\n continue;\n }\n\n // Extract parent_tool_use_id from SDK message - this is the authoritative source\n // SDK provides this field when tool is executed within a subagent context\n const sdkParentToolUseId = (message as { parent_tool_use_id?: string })\n .parent_tool_use_id;\n\n const content = message.message.content;\n const tools = this.extractToolUses(content);\n\n // Close any active text part before tool calls start.\n // This ensures tool calls split text into separate parts.\n // We only do this if there are actual tools to avoid unnecessary text-end events.\n if (textPartId && tools.length > 0) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined; // Reset so next text gets a new ID\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n for (const tool of tools) {\n const toolId = tool.id;\n let state = toolStates.get(toolId);\n if (!state) {\n // Prefer SDK message-level parent (works for parallel agents)\n // Fall back to content-level parent, then timing-based inference\n // Task tools never have a parent (they're top-level)\n const currentParentId =\n tool.name === 'Task'\n ? null\n : (sdkParentToolUseId ?? tool.parentToolUseId ?? getFallbackParentId());\n state = {\n name: tool.name,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: currentParentId,\n };\n toolStates.set(toolId, state);\n this.logger.debug(\n `[claude-code] New tool use detected - Tool: ${tool.name}, ID: ${toolId}, SDK parent: ${sdkParentToolUseId}, resolved parent: ${currentParentId}`\n );\n } else if (!state.parentToolCallId && sdkParentToolUseId && tool.name !== 'Task') {\n // RETROACTIVE PARENT CONTEXT: Tool state was created by streaming events\n // but we now have authoritative parent from SDK message - update state\n state.parentToolCallId = sdkParentToolUseId;\n this.logger.debug(\n `[claude-code] Retroactive parent context - Tool: ${tool.name}, ID: ${toolId}, parent: ${sdkParentToolUseId}`\n );\n }\n\n state.name = tool.name;\n\n if (!state.inputStarted) {\n this.logger.debug(\n `[claude-code] Tool input started - Tool: ${tool.name}, ID: ${toolId}`\n );\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName: tool.name,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n // Track Task tools as active so nested tools can reference them as parent\n if (tool.name === 'Task') {\n activeTaskTools.set(toolId, { startTime: Date.now() });\n }\n state.inputStarted = true;\n }\n\n const serializedInput = this.serializeToolInput(tool.input);\n if (serializedInput) {\n let deltaPayload = '';\n\n // First input: emit full delta only if small enough\n if (state.lastSerializedInput === undefined) {\n if (serializedInput.length <= ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE) {\n deltaPayload = serializedInput;\n }\n } else if (\n serializedInput.length <= ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE &&\n state.lastSerializedInput.length <=\n ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE &&\n serializedInput.startsWith(state.lastSerializedInput)\n ) {\n deltaPayload = serializedInput.slice(state.lastSerializedInput.length);\n } else if (serializedInput !== state.lastSerializedInput) {\n // Non-prefix updates or large inputs - defer to the final tool-call payload\n deltaPayload = '';\n }\n\n if (deltaPayload) {\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: deltaPayload,\n });\n }\n state.lastSerializedInput = serializedInput;\n }\n }\n\n const text = content\n .map((c: { type: string; text?: string }) => (c.type === 'text' ? c.text : ''))\n .join('');\n\n if (text) {\n // When we've received stream_events, assistant messages contain cumulative text\n // that we've already emitted via stream_event deltas - skip duplicates\n // When no stream_events received, assistant messages contain incremental text\n if (hasReceivedStreamEvents) {\n // Calculate delta: only emit text that wasn't already streamed via stream_events\n const newTextStart = streamedTextLength;\n const deltaText = text.length > newTextStart ? text.slice(newTextStart) : '';\n\n // Always accumulate for final result tracking\n accumulatedText = text; // Replace with full text (assistant msg contains full content)\n\n // In JSON mode, we accumulate the text and extract JSON at the end\n // Otherwise, stream any new text\n if (options.responseFormat?.type !== 'json' && deltaText) {\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: deltaText,\n });\n }\n\n // Update streamedTextLength to match what we now know is the full text\n streamedTextLength = text.length;\n } else {\n // No stream_events - assistant messages contain incremental text chunks\n accumulatedText += text;\n\n // In JSON mode, we accumulate the text and extract JSON at the end\n // Otherwise, stream the text as it comes\n if (options.responseFormat?.type !== 'json') {\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: text,\n });\n }\n }\n }\n } else if (message.type === 'user') {\n if (!message.message?.content) {\n this.logger.warn(\n `[claude-code] Unexpected user message structure: missing content field. Message type: ${message.type}. This may indicate an SDK protocol violation.`\n );\n continue;\n }\n\n // A user message signals the end of the current assistant message.\n // Reset text state to ensure the next assistant message starts with a new text part.\n // This prevents text from different assistant messages from being merged together.\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [blockIndex, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(blockIndex);\n break;\n }\n }\n accumulatedText = '';\n streamedTextLength = 0;\n this.logger.debug('[claude-code] Closed text part due to user message');\n }\n\n // Extract parent_tool_use_id from SDK message for late-arriving tool results\n const sdkParentToolUseIdForResults = (message as { parent_tool_use_id?: string })\n .parent_tool_use_id;\n\n const content = message.message.content;\n for (const result of this.extractToolResults(content)) {\n let state = toolStates.get(result.id);\n const toolName =\n result.name ?? state?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool result received - Tool: ${toolName}, ID: ${result.id}`\n );\n\n if (!state) {\n this.logger.warn(\n `[claude-code] Received tool result for unknown tool ID: ${result.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n const resolvedParentId =\n toolName === 'Task'\n ? null\n : (sdkParentToolUseIdForResults ?? getFallbackParentId());\n state = {\n name: toolName,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: resolvedParentId,\n };\n toolStates.set(result.id, state);\n // Synthesize input lifecycle to preserve ordering when no prior tool_use was seen\n if (!state.inputStarted) {\n controller.enqueue({\n type: 'tool-input-start',\n id: result.id,\n toolName,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n state.inputStarted = true;\n }\n if (!state.inputClosed) {\n controller.enqueue({\n type: 'tool-input-end',\n id: result.id,\n });\n state.inputClosed = true;\n }\n }\n state.name = toolName;\n const normalizedResult = this.normalizeToolResult(result.result);\n const rawResult =\n typeof result.result === 'string'\n ? result.result\n : (() => {\n try {\n return JSON.stringify(result.result);\n } catch {\n return String(result.result);\n }\n })();\n const maxToolResultSize = this.settings.maxToolResultSize;\n const truncatedResult = truncateToolResultForStream(\n normalizedResult,\n maxToolResultSize\n );\n const truncatedRawResult = truncateToolResultForStream(\n rawResult,\n maxToolResultSize\n ) as string;\n const rawResultTruncated = truncatedRawResult !== rawResult;\n\n emitToolCall(result.id, state);\n\n // Remove Task tools from active set when they complete\n if (toolName === 'Task') {\n activeTaskTools.delete(result.id);\n }\n\n controller.enqueue({\n type: 'tool-result',\n toolCallId: result.id,\n toolName,\n result: truncatedResult,\n isError: result.isError,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n // rawResult preserves the original CLI output string before JSON parsing.\n // Use this when you need the exact string returned by the tool, especially\n // if the `result` field has been parsed/normalized and you need the original format.\n rawResult: truncatedRawResult,\n rawResultTruncated,\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n // Handle tool errors\n for (const error of this.extractToolErrors(content)) {\n let state = toolStates.get(error.id);\n const toolName =\n error.name ?? state?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool error received - Tool: ${toolName}, ID: ${error.id}`\n );\n\n if (!state) {\n this.logger.warn(\n `[claude-code] Received tool error for unknown tool ID: ${error.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n const errorResolvedParentId =\n toolName === 'Task'\n ? null\n : (sdkParentToolUseIdForResults ?? getFallbackParentId());\n state = {\n name: toolName,\n inputStarted: true,\n inputClosed: true,\n callEmitted: false,\n parentToolCallId: errorResolvedParentId,\n };\n toolStates.set(error.id, state);\n }\n\n // Ensure tool-call is emitted before tool-error\n emitToolCall(error.id, state);\n\n // Remove Task tools from active set when they error\n if (toolName === 'Task') {\n activeTaskTools.delete(error.id);\n }\n\n const rawError =\n typeof error.error === 'string'\n ? error.error\n : typeof error.error === 'object' && error.error !== null\n ? (() => {\n try {\n return JSON.stringify(error.error);\n } catch {\n return String(error.error);\n }\n })()\n : String(error.error);\n\n controller.enqueue({\n type: 'tool-error',\n toolCallId: error.id,\n toolName,\n error: rawError,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n rawError,\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n } else if (message.type === 'result') {\n done();\n\n // Handle is_error flag in result message (e.g., auth failures)\n // The CLI returns successful JSON with is_error: true and error message in result field\n if ('is_error' in message && message.is_error === true) {\n const errorMessage =\n 'result' in message && typeof message.result === 'string'\n ? message.result\n : 'Claude Code CLI returned an error';\n throw Object.assign(new Error(errorMessage), { exitCode: 1 });\n }\n\n // Handle structured output errors (SDK 0.1.45+)\n // Use string comparison to support new SDK subtypes not yet in TypeScript definitions\n if ((message.subtype as string) === 'error_max_structured_output_retries') {\n throw new Error(\n 'Failed to generate valid structured output after maximum retries. The model could not produce a response matching the required schema.'\n );\n }\n\n this.logger.info(\n `[claude-code] Stream completed - Session: ${message.session_id}, Cost: $${message.total_cost_usd?.toFixed(4) ?? 'N/A'}, Duration: ${message.duration_ms ?? 'N/A'}ms`\n );\n\n if ('usage' in message) {\n usage = convertClaudeCodeUsage(message.usage);\n\n this.logger.debug(\n `[claude-code] Stream token usage - Input: ${usage.inputTokens.total}, Output: ${usage.outputTokens.total}`\n );\n }\n\n const stopReason =\n 'stop_reason' in message\n ? ((message as Record<string, unknown>).stop_reason as string | null | undefined)\n : undefined;\n const finishReason: LanguageModelV3FinishReason = mapClaudeCodeFinishReason(\n message.subtype,\n stopReason\n );\n\n this.logger.debug(`[claude-code] Stream finish reason: ${finishReason.unified}`);\n\n // Store session ID in the model instance\n this.setSessionId(message.session_id);\n\n // Use structured output from SDK if available (native JSON schema support)\n const structuredOutput =\n 'structured_output' in message ? message.structured_output : undefined;\n\n // Check if we've already streamed JSON via input_json_delta\n const alreadyStreamedJson =\n hasStreamedJson &&\n options.responseFormat?.type === 'json' &&\n hasReceivedStreamEvents;\n\n if (alreadyStreamedJson) {\n // We've already streamed JSON deltas; only close the text part if it's still open.\n if (textPartId) {\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n }\n } else if (structuredOutput !== undefined) {\n // Emit structured output as text (fallback when streaming didn't occur)\n const jsonTextId = generateId();\n const jsonText = JSON.stringify(structuredOutput);\n controller.enqueue({\n type: 'text-start',\n id: jsonTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: jsonTextId,\n delta: jsonText,\n });\n controller.enqueue({\n type: 'text-end',\n id: jsonTextId,\n });\n } else if (textPartId) {\n // Close the text part if it was opened (non-JSON mode)\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n } else if (accumulatedText && !textStreamedViaContentBlock) {\n // Fallback for JSON mode without schema: emit accumulated text\n // This handles the case where responseFormat.type === 'json' but no schema\n // was provided, so the SDK returns plain text instead of structured_output\n const fallbackTextId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: fallbackTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: fallbackTextId,\n delta: accumulatedText,\n });\n controller.enqueue({\n type: 'text-end',\n id: fallbackTextId,\n });\n }\n\n finalizeToolCalls();\n\n // Prepare JSON-safe warnings for provider metadata\n const warningsJson = this.serializeWarningsForMetadata(streamWarnings);\n\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage,\n providerMetadata: {\n 'claude-code': {\n sessionId: message.session_id,\n ...(message.total_cost_usd !== undefined && {\n costUsd: message.total_cost_usd,\n }),\n ...(message.duration_ms !== undefined && { durationMs: message.duration_ms }),\n ...(message.modelUsage !== undefined && {\n modelUsage: message.modelUsage as unknown as JSONValue,\n }),\n // JSON validation warnings are collected during streaming and included\n // in providerMetadata since the AI SDK's finish event doesn't support\n // a top-level warnings field (unlike stream-start which was already emitted)\n ...(streamWarnings.length > 0 && {\n warnings: warningsJson as unknown as JSONValue,\n }),\n },\n },\n });\n controller.close();\n return;\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.logMcpConnectionIssues(message.mcp_servers);\n\n // Store session ID for future use\n this.setSessionId(message.session_id);\n\n this.logger.info(`[claude-code] Stream session initialized: ${message.session_id}`);\n\n // Emit response metadata when session is initialized\n controller.enqueue({\n type: 'response-metadata',\n id: message.session_id,\n timestamp: new Date(),\n modelId: this.modelId,\n });\n }\n }\n\n finalizeToolCalls();\n this.logger.debug('[claude-code] Stream finalized, closing stream');\n controller.close();\n } catch (error: unknown) {\n done();\n\n this.logger.debug(\n `[claude-code] Error during doStream: ${error instanceof Error ? error.message : String(error)}`\n );\n\n if (isClaudeCodeTruncationError(error, accumulatedText)) {\n this.logger.warn(\n `[claude-code] Detected truncated stream response, returning ${accumulatedText.length} characters of buffered text`\n );\n const truncationWarning: SharedV3Warning = {\n type: 'other',\n message: CLAUDE_CODE_TRUNCATION_WARNING,\n };\n streamWarnings.push(truncationWarning);\n\n if (textPartId) {\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n } else if (accumulatedText && !textStreamedViaContentBlock) {\n const fallbackTextId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: fallbackTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: fallbackTextId,\n delta: accumulatedText,\n });\n controller.enqueue({\n type: 'text-end',\n id: fallbackTextId,\n });\n }\n\n finalizeToolCalls();\n\n const warningsJson = this.serializeWarningsForMetadata(streamWarnings);\n\n controller.enqueue({\n type: 'finish',\n finishReason: { unified: 'length', raw: 'truncation' },\n usage,\n providerMetadata: {\n 'claude-code': {\n ...(this.sessionId !== undefined && { sessionId: this.sessionId }),\n truncated: true,\n ...(streamWarnings.length > 0 && {\n warnings: warningsJson as unknown as JSONValue,\n }),\n },\n },\n });\n\n controller.close();\n return;\n }\n\n finalizeToolCalls();\n let errorToEmit: unknown;\n\n // Special handling for AbortError to preserve abort signal reason\n if (isAbortError(error)) {\n errorToEmit = options.abortSignal?.aborted ? options.abortSignal.reason : error;\n } else {\n // Use unified error handler\n errorToEmit = this.handleClaudeCodeError(error, messagesPrompt, collectedStderr);\n }\n\n // Emit error as a stream part\n controller.enqueue({\n type: 'error',\n error: errorToEmit,\n });\n\n controller.close();\n } finally {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n }\n },\n cancel: () => {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n },\n });\n\n return {\n stream: stream as unknown as ReadableStream<LanguageModelV3StreamPart>,\n request: {\n body: messagesPrompt,\n },\n };\n }\n\n private serializeWarningsForMetadata(warnings: SharedV3Warning[]): JSONValue {\n const result = warnings.map((w) => {\n const base: Record<string, string> = { type: w.type };\n if ('message' in w) {\n const m = (w as { message?: unknown }).message;\n if (m !== undefined) base.message = String(m);\n }\n if (w.type === 'unsupported' || w.type === 'compatibility') {\n const feature = (w as { feature: unknown }).feature;\n if (feature !== undefined) base.feature = String(feature);\n if ('details' in w) {\n const d = (w as { details?: unknown }).details;\n if (d !== undefined) base.details = String(d);\n }\n }\n return base;\n });\n return result as unknown as JSONValue;\n }\n}\n","import type { ModelMessage } from 'ai';\nimport type { SDKUserMessage } from '@anthropic-ai/claude-agent-sdk';\n\ntype SDKUserContentPart = SDKUserMessage['message']['content'][number];\n\ninterface StreamingSegment {\n formatted: string;\n}\n\nconst IMAGE_URL_WARNING = 'Image URLs are not supported by this provider; supply base64/data URLs.';\nconst IMAGE_CONVERSION_WARNING = 'Unable to convert image content; supply base64/data URLs.';\n\nfunction normalizeBase64(base64: string): string {\n return base64.replace(/\\s+/g, '');\n}\n\nfunction isImageMimeType(mimeType?: string): boolean {\n return typeof mimeType === 'string' && mimeType.trim().toLowerCase().startsWith('image/');\n}\n\nfunction createImageContent(mediaType: string, data: string): SDKUserContentPart | undefined {\n const trimmedType = mediaType.trim();\n const trimmedData = normalizeBase64(data.trim());\n\n if (!trimmedType || !trimmedData) {\n return undefined;\n }\n\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: trimmedType,\n data: trimmedData,\n },\n } as SDKUserContentPart;\n}\n\nfunction extractMimeType(candidate: unknown): string | undefined {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim();\n }\n return undefined;\n}\n\nfunction parseObjectImage(\n imageObj: Record<string, unknown>,\n fallbackMimeType?: string\n): SDKUserContentPart | undefined {\n const data = typeof imageObj.data === 'string' ? imageObj.data : undefined;\n const mimeType = extractMimeType(\n imageObj.mimeType ?? imageObj.mediaType ?? imageObj.media_type ?? fallbackMimeType\n );\n if (!data || !mimeType) {\n return undefined;\n }\n return createImageContent(mimeType, data);\n}\n\nfunction parseStringImage(\n value: string,\n fallbackMimeType?: string\n): { content?: SDKUserContentPart; warning?: string } {\n const trimmed = value.trim();\n\n if (/^https?:\\/\\//i.test(trimmed)) {\n return { warning: IMAGE_URL_WARNING };\n }\n\n const dataUrlMatch = trimmed.match(/^data:([^;]+);base64,(.+)$/i);\n if (dataUrlMatch) {\n const [, mediaType, data] = dataUrlMatch;\n const content = createImageContent(mediaType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n const base64Match = trimmed.match(/^base64:([^,]+),(.+)$/i);\n if (base64Match) {\n const [, explicitMimeType, data] = base64Match;\n const content = createImageContent(explicitMimeType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n if (fallbackMimeType) {\n const content = createImageContent(fallbackMimeType, trimmed);\n if (content) {\n return { content };\n }\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\nfunction parseImagePart(part: unknown): { content?: SDKUserContentPart; warning?: string } {\n if (!part || typeof part !== 'object') {\n return { warning: IMAGE_CONVERSION_WARNING };\n }\n\n const imageValue = (part as { image?: unknown }).image;\n const mimeType = extractMimeType((part as { mimeType?: unknown }).mimeType);\n\n if (typeof imageValue === 'string') {\n return parseStringImage(imageValue, mimeType);\n }\n\n if (imageValue && typeof imageValue === 'object') {\n const content = parseObjectImage(imageValue as Record<string, unknown>, mimeType);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\nfunction convertBinaryToBase64(data: Uint8Array | ArrayBuffer): string | undefined {\n if (typeof Buffer !== 'undefined') {\n const buffer =\n data instanceof Uint8Array ? Buffer.from(data) : Buffer.from(new Uint8Array(data));\n return buffer.toString('base64');\n }\n\n if (typeof btoa === 'function') {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n let binary = '';\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize);\n binary += String.fromCharCode(...chunk);\n }\n return btoa(binary);\n }\n\n return undefined;\n}\n\ntype FileLikePart = {\n mediaType?: unknown;\n mimeType?: unknown;\n data?: unknown;\n};\n\nfunction parseFilePart(part: FileLikePart): { content?: SDKUserContentPart; warning?: string } {\n const mimeType = extractMimeType(part.mediaType ?? part.mimeType);\n if (!mimeType || !isImageMimeType(mimeType)) {\n return {};\n }\n\n const data = part.data;\n if (typeof data === 'string') {\n const content = createImageContent(mimeType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n if (\n data instanceof Uint8Array ||\n (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n ) {\n const base64 = convertBinaryToBase64(data);\n if (!base64) {\n return { warning: IMAGE_CONVERSION_WARNING };\n }\n const content = createImageContent(mimeType, base64);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\n/**\n * Converts AI SDK prompt format to Claude Code SDK message format.\n * Handles system prompts, user messages, assistant responses, and tool interactions.\n *\n * @param prompt - The AI SDK prompt containing messages\n * @returns An object containing the formatted message prompt and optional system prompt\n *\n * @example\n * ```typescript\n * const { messagesPrompt } = convertToClaudeCodeMessages(\n * [{ role: 'user', content: 'Hello!' }]\n * );\n * ```\n *\n * @remarks\n * - Image parts are collected for streaming input; unsupported variants produce warnings\n * - Tool calls are simplified to \"[Tool calls made]\" notation\n * - JSON schema enforcement is handled natively by the SDK's outputFormat option (v0.1.45+)\n */\nexport function convertToClaudeCodeMessages(prompt: readonly ModelMessage[]): {\n messagesPrompt: string;\n systemPrompt?: string;\n warnings?: string[];\n streamingContentParts: SDKUserMessage['message']['content'];\n hasImageParts: boolean;\n} {\n const messages: string[] = [];\n const warnings: string[] = [];\n let systemPrompt: string | undefined;\n const streamingSegments: StreamingSegment[] = [];\n const imageMap = new Map<number, SDKUserContentPart[]>();\n let hasImageParts = false;\n\n const addSegment = (formatted: string): number => {\n streamingSegments.push({ formatted });\n return streamingSegments.length - 1;\n };\n\n const addImageForSegment = (segmentIndex: number, content: SDKUserContentPart): void => {\n hasImageParts = true;\n if (!imageMap.has(segmentIndex)) {\n imageMap.set(segmentIndex, []);\n }\n imageMap.get(segmentIndex)?.push(content);\n };\n\n for (const message of prompt) {\n switch (message.role) {\n case 'system':\n systemPrompt = message.content;\n if (typeof message.content === 'string' && message.content.trim().length > 0) {\n addSegment(message.content);\n } else {\n addSegment('');\n }\n break;\n\n case 'user':\n if (typeof message.content === 'string') {\n messages.push(message.content);\n addSegment(`Human: ${message.content}`);\n } else {\n // Handle multi-part content\n const textParts = message.content\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n\n const segmentIndex = addSegment(textParts ? `Human: ${textParts}` : '');\n\n if (textParts) {\n messages.push(textParts);\n }\n\n for (const part of message.content) {\n if (part.type === 'image') {\n const { content, warning } = parseImagePart(part);\n if (content) {\n addImageForSegment(segmentIndex, content);\n } else if (warning) {\n warnings.push(warning);\n }\n } else if (part.type === 'file') {\n const { content, warning } = parseFilePart(part);\n if (content) {\n addImageForSegment(segmentIndex, content);\n } else if (warning) {\n warnings.push(warning);\n }\n }\n }\n }\n break;\n\n case 'assistant': {\n let assistantContent = '';\n if (typeof message.content === 'string') {\n assistantContent = message.content;\n } else {\n const textParts = message.content\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n\n if (textParts) {\n assistantContent = textParts;\n }\n\n // Handle tool calls if present\n const toolCalls = message.content.filter((part) => part.type === 'tool-call');\n if (toolCalls.length > 0) {\n // For now, we'll just note that tool calls were made\n assistantContent += `\\n[Tool calls made]`;\n }\n }\n const formattedAssistant = `Assistant: ${assistantContent}`;\n messages.push(formattedAssistant);\n addSegment(formattedAssistant);\n break;\n }\n\n case 'tool':\n // Tool results could be included in the conversation\n // Filter out ToolApprovalResponse parts, only process ToolResultPart\n for (const tool of message.content) {\n if (tool.type === 'tool-approval-response') {\n continue; // Skip approval responses\n }\n // Handle different ToolResultOutput types\n let resultText: string;\n const output = tool.output;\n if (output.type === 'text' || output.type === 'error-text') {\n resultText = output.value;\n } else if (output.type === 'json' || output.type === 'error-json') {\n resultText = JSON.stringify(output.value);\n } else if (output.type === 'execution-denied') {\n resultText = `[Execution denied${output.reason ? `: ${output.reason}` : ''}]`;\n } else if (output.type === 'content') {\n // Handle content array - extract text parts\n resultText = output.value\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n } else {\n resultText = '[Unknown output type]';\n }\n const formattedToolResult = `Tool Result (${tool.toolName}): ${resultText}`;\n messages.push(formattedToolResult);\n addSegment(formattedToolResult);\n }\n break;\n }\n }\n\n // For the SDK, we need to provide a single prompt string\n // Format the conversation history properly\n\n // Combine system prompt with messages\n let finalPrompt = '';\n\n // Add system prompt at the beginning if present\n if (systemPrompt) {\n finalPrompt = systemPrompt;\n }\n\n if (messages.length > 0) {\n // Format messages\n const formattedMessages = [];\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Check if this is a user or assistant message based on content\n if (msg.startsWith('Assistant:') || msg.startsWith('Tool Result')) {\n formattedMessages.push(msg);\n } else {\n // User messages\n formattedMessages.push(`Human: ${msg}`);\n }\n }\n\n // Combine system prompt with messages\n if (finalPrompt) {\n const joinedMessages = formattedMessages.join('\\n\\n');\n finalPrompt = joinedMessages ? `${finalPrompt}\\n\\n${joinedMessages}` : finalPrompt;\n } else {\n finalPrompt = formattedMessages.join('\\n\\n');\n }\n }\n\n // Build streaming parts including text and images\n const streamingParts: SDKUserContentPart[] = [];\n const imagePartsInOrder: SDKUserContentPart[] = [];\n\n const appendImagesForIndex = (index: number) => {\n const images = imageMap.get(index);\n if (!images) {\n return;\n }\n images.forEach((image) => {\n streamingParts.push(image);\n imagePartsInOrder.push(image);\n });\n };\n\n if (streamingSegments.length > 0) {\n let accumulatedText = '';\n let emittedText = false;\n\n const flushText = () => {\n if (!accumulatedText) {\n return;\n }\n streamingParts.push({ type: 'text', text: accumulatedText });\n accumulatedText = '';\n emittedText = true;\n };\n\n streamingSegments.forEach((segment, index) => {\n const segmentText = segment.formatted;\n if (segmentText) {\n if (!accumulatedText) {\n accumulatedText = emittedText ? `\\n\\n${segmentText}` : segmentText;\n } else {\n accumulatedText += `\\n\\n${segmentText}`;\n }\n }\n\n if (imageMap.has(index)) {\n flushText();\n appendImagesForIndex(index);\n }\n });\n\n flushText();\n }\n\n // Note: JSON schema enforcement is now handled natively by the SDK's outputFormat option (v0.1.45+)\n // No prompt injection needed - structured outputs are guaranteed by the SDK\n\n return {\n messagesPrompt: finalPrompt,\n systemPrompt,\n ...(warnings.length > 0 && { warnings }),\n streamingContentParts:\n streamingParts.length > 0\n ? (streamingParts as SDKUserMessage['message']['content'])\n : ([\n { type: 'text', text: finalPrompt },\n ...imagePartsInOrder,\n ] as SDKUserMessage['message']['content']),\n hasImageParts,\n };\n}\n","import { APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\n\n/**\n * Metadata associated with Claude Code SDK errors.\n * Provides additional context about command execution failures.\n */\nexport interface ClaudeCodeErrorMetadata {\n /**\n * Error code from the CLI process (e.g., 'ENOENT', 'ETIMEDOUT').\n */\n code?: string;\n\n /**\n * Exit code from the Claude Code SDK process.\n * Common codes:\n * - 401: Authentication error\n * - 1: General error\n */\n exitCode?: number;\n\n /**\n * Standard error output from the CLI process.\n */\n stderr?: string;\n\n /**\n * Excerpt from the prompt that caused the error.\n * Limited to first 200 characters for debugging.\n */\n promptExcerpt?: string;\n}\n\n/**\n * Creates an APICallError with Claude Code specific metadata.\n * Used for general CLI execution errors.\n *\n * @param options - Error details and metadata\n * @param options.message - Human-readable error message\n * @param options.code - Error code from the CLI process\n * @param options.exitCode - Exit code from the CLI\n * @param options.stderr - Standard error output\n * @param options.promptExcerpt - Excerpt of the prompt that caused the error\n * @param options.isRetryable - Whether the error is potentially retryable\n * @returns An APICallError instance with Claude Code metadata\n *\n * @example\n * ```typescript\n * throw createAPICallError({\n * message: 'Claude Code SDK failed',\n * code: 'ENOENT',\n * isRetryable: true\n * });\n * ```\n */\nexport function createAPICallError({\n message,\n code,\n exitCode,\n stderr,\n promptExcerpt,\n isRetryable = false,\n}: ClaudeCodeErrorMetadata & {\n message: string;\n isRetryable?: boolean;\n}): APICallError {\n const metadata: ClaudeCodeErrorMetadata = {\n code,\n exitCode,\n stderr,\n promptExcerpt,\n };\n\n return new APICallError({\n message,\n isRetryable,\n url: 'claude-code-cli://command',\n requestBodyValues: promptExcerpt ? { prompt: promptExcerpt } : undefined,\n data: metadata,\n });\n}\n\n/**\n * Creates an authentication error for Claude Code SDK login failures.\n *\n * @param options - Error configuration\n * @param options.message - Error message describing the authentication failure\n * @returns A LoadAPIKeyError instance\n *\n * @example\n * ```typescript\n * throw createAuthenticationError({\n * message: 'Please run \"claude auth login\" to authenticate'\n * });\n * ```\n */\nexport function createAuthenticationError({ message }: { message: string }): LoadAPIKeyError {\n return new LoadAPIKeyError({\n message:\n message || 'Authentication failed. Please ensure Claude Code SDK is properly authenticated.',\n });\n}\n\n/**\n * Creates a timeout error for Claude Code SDK operations.\n *\n * @param options - Timeout error details\n * @param options.message - Error message describing the timeout\n * @param options.promptExcerpt - Excerpt of the prompt that timed out\n * @param options.timeoutMs - Timeout duration in milliseconds\n * @returns An APICallError instance configured as a timeout error\n *\n * @example\n * ```typescript\n * throw createTimeoutError({\n * message: 'Request timed out after 2 minutes',\n * timeoutMs: 120000\n * });\n * ```\n */\nexport function createTimeoutError({\n message,\n promptExcerpt,\n timeoutMs,\n}: {\n message: string;\n promptExcerpt?: string;\n timeoutMs?: number;\n}): APICallError {\n // Store timeoutMs in metadata for potential use by error handlers\n const metadata: ClaudeCodeErrorMetadata = {\n code: 'TIMEOUT',\n promptExcerpt,\n };\n\n return new APICallError({\n message,\n isRetryable: true,\n url: 'claude-code-cli://command',\n requestBodyValues: promptExcerpt ? { prompt: promptExcerpt } : undefined,\n data: timeoutMs !== undefined ? { ...metadata, timeoutMs } : metadata,\n });\n}\n\n/**\n * Checks if an error is an authentication error.\n * Returns true for LoadAPIKeyError instances or APICallError with exit code 401.\n *\n * @param error - The error to check\n * @returns True if the error is an authentication error\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * if (isAuthenticationError(error)) {\n * console.log('Please authenticate with Claude Code SDK');\n * }\n * }\n * ```\n */\nexport function isAuthenticationError(error: unknown): boolean {\n if (error instanceof LoadAPIKeyError) return true;\n if (error instanceof APICallError && (error.data as ClaudeCodeErrorMetadata)?.exitCode === 401)\n return true;\n return false;\n}\n\n/**\n * Checks if an error is a timeout error.\n * Returns true for APICallError instances with code 'TIMEOUT'.\n *\n * @param error - The error to check\n * @returns True if the error is a timeout error\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * if (isTimeoutError(error)) {\n * console.log('Request timed out, consider retrying');\n * }\n * }\n * ```\n */\nexport function isTimeoutError(error: unknown): boolean {\n if (error instanceof APICallError && (error.data as ClaudeCodeErrorMetadata)?.code === 'TIMEOUT')\n return true;\n return false;\n}\n\n/**\n * Extracts Claude Code error metadata from an error object.\n *\n * @param error - The error to extract metadata from\n * @returns The error metadata if available, undefined otherwise\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * const metadata = getErrorMetadata(error);\n * if (metadata?.exitCode === 401) {\n * console.log('Authentication required');\n * }\n * }\n * ```\n */\nexport function getErrorMetadata(error: unknown): ClaudeCodeErrorMetadata | undefined {\n if (error instanceof APICallError && error.data) {\n return error.data as ClaudeCodeErrorMetadata;\n }\n return undefined;\n}\n","import type { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\n/**\n * Maps Claude Code SDK result subtypes to AI SDK finish reasons.\n *\n * When `stopReason` is provided (from the SDK's `stop_reason` field), it takes\n * priority for mapping well-known Anthropic API stop reasons. Otherwise, falls\n * back to the existing subtype-based mapping.\n *\n * @param subtype - The result subtype from Claude Code SDK\n * @param stopReason - The optional stop_reason from SDKResultSuccess/SDKResultError (v0.2.31+)\n * @returns The corresponding AI SDK finish reason with unified and raw values\n *\n * @example\n * ```typescript\n * // With stop_reason (preferred when available)\n * mapClaudeCodeFinishReason('success', 'end_turn');\n * // Returns: { unified: 'stop', raw: 'end_turn' }\n *\n * // Without stop_reason (backward compatible)\n * mapClaudeCodeFinishReason('error_max_turns');\n * // Returns: { unified: 'length', raw: 'error_max_turns' }\n * ```\n */\nexport function mapClaudeCodeFinishReason(\n subtype?: string,\n stopReason?: string | null\n): LanguageModelV3FinishReason {\n // When stop_reason is present and non-null, map known Anthropic API stop reasons\n if (stopReason != null) {\n switch (stopReason) {\n case 'end_turn':\n return { unified: 'stop', raw: 'end_turn' };\n case 'max_tokens':\n return { unified: 'length', raw: 'max_tokens' };\n case 'stop_sequence':\n return { unified: 'stop', raw: 'stop_sequence' };\n case 'tool_use':\n return { unified: 'tool-calls', raw: 'tool_use' };\n default:\n // Unknown stop_reason: fall back to subtype mapping but preserve stop_reason as raw\n break;\n }\n }\n\n // Fall back to subtype-based mapping\n const raw = stopReason ?? subtype;\n switch (subtype) {\n case 'success':\n return { unified: 'stop', raw };\n case 'error_max_turns':\n return { unified: 'length', raw };\n case 'error_during_execution':\n return { unified: 'error', raw };\n case undefined:\n return { unified: 'stop', raw };\n default:\n return { unified: 'other', raw };\n }\n}\n","import { z } from 'zod';\nimport { existsSync } from 'fs';\n\n/**\n * Validation schemas and utilities for Claude Code provider inputs.\n * Uses Zod for type-safe validation following AI SDK patterns.\n */\n\n// Helper for Zod v3/v4 compatibility\n// Use a simple z.any() for functions to work with both versions\nconst loggerFunctionSchema = z.object({\n debug: z.any().refine((val) => typeof val === 'function', {\n message: 'debug must be a function',\n }),\n info: z.any().refine((val) => typeof val === 'function', {\n message: 'info must be a function',\n }),\n warn: z.any().refine((val) => typeof val === 'function', {\n message: 'warn must be a function',\n }),\n error: z.any().refine((val) => typeof val === 'function', {\n message: 'error must be a function',\n }),\n});\n\n/**\n * Schema for validating Claude Code settings.\n * Ensures all settings are within acceptable ranges and formats.\n */\nexport const claudeCodeSettingsSchema = z\n .object({\n pathToClaudeCodeExecutable: z.string().optional(),\n customSystemPrompt: z.string().optional(),\n appendSystemPrompt: z.string().optional(),\n systemPrompt: z\n .union([\n z.string(),\n z.object({\n type: z.literal('preset'),\n preset: z.literal('claude_code'),\n append: z.string().optional(),\n }),\n ])\n .optional(),\n maxTurns: z.number().int().min(1).max(100).optional(),\n maxThinkingTokens: z.number().int().positive().max(100000).optional(),\n thinking: z\n .union([\n z.object({ type: z.literal('adaptive') }).strict(),\n z\n .object({\n type: z.literal('enabled'),\n budgetTokens: z.number().int().positive().optional(),\n })\n .strict(),\n z.object({ type: z.literal('disabled') }).strict(),\n ])\n .optional(),\n effort: z.enum(['low', 'medium', 'high', 'max']).optional(),\n promptSuggestions: z.boolean().optional(),\n cwd: z\n .string()\n .refine(\n (val) => {\n // Skip directory validation in non-Node environments\n if (typeof process === 'undefined' || !process.versions?.node) {\n return true;\n }\n return !val || existsSync(val);\n },\n { message: 'Working directory must exist' }\n )\n .optional(),\n executable: z.enum(['bun', 'deno', 'node']).optional(),\n executableArgs: z.array(z.string()).optional(),\n permissionMode: z\n .enum(['default', 'acceptEdits', 'bypassPermissions', 'plan', 'delegate', 'dontAsk'])\n .optional(),\n permissionPromptToolName: z.string().optional(),\n continue: z.boolean().optional(),\n resume: z.string().optional(),\n sessionId: z.string().optional(),\n allowedTools: z.array(z.string()).optional(),\n disallowedTools: z.array(z.string()).optional(),\n betas: z.array(z.string()).optional(),\n allowDangerouslySkipPermissions: z.boolean().optional(),\n enableFileCheckpointing: z.boolean().optional(),\n maxBudgetUsd: z.number().min(0).optional(),\n plugins: z\n .array(\n z\n .object({\n type: z.string(),\n path: z.string(),\n })\n .passthrough()\n )\n .optional(),\n resumeSessionAt: z.string().optional(),\n sandbox: z\n .any()\n .refine((val) => val === undefined || typeof val === 'object', {\n message: 'sandbox must be an object',\n })\n .optional(),\n tools: z\n .union([\n z.array(z.string()),\n z.object({\n type: z.literal('preset'),\n preset: z.literal('claude_code'),\n }),\n ])\n .optional(),\n settingSources: z.array(z.enum(['user', 'project', 'local'])).optional(),\n streamingInput: z.enum(['auto', 'always', 'off']).optional(),\n // Hooks and tool-permission callback (permissive validation of shapes)\n canUseTool: z\n .any()\n .refine((v) => v === undefined || typeof v === 'function', {\n message: 'canUseTool must be a function',\n })\n .optional(),\n hooks: z\n .record(\n z.string(),\n z.array(\n z.object({\n matcher: z.string().optional(),\n hooks: z.array(z.any()).nonempty(),\n })\n )\n )\n .optional(),\n mcpServers: z\n .record(\n z.string(),\n z.union([\n // McpStdioServerConfig\n z.object({\n type: z.literal('stdio').optional(),\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n }),\n // McpSSEServerConfig\n z.object({\n type: z.literal('sse'),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n // McpHttpServerConfig\n z.object({\n type: z.literal('http'),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n // McpSdkServerConfig (in-process custom tools)\n z.object({\n type: z.literal('sdk'),\n name: z.string(),\n instance: z.any(),\n }),\n ])\n )\n .optional(),\n verbose: z.boolean().optional(),\n debug: z.boolean().optional(),\n debugFile: z.string().optional(),\n logger: z.union([z.literal(false), loggerFunctionSchema]).optional(),\n env: z.record(z.string(), z.string().optional()).optional(),\n additionalDirectories: z.array(z.string()).optional(),\n agents: z\n .record(\n z.string(),\n z\n .object({\n description: z.string(),\n tools: z.array(z.string()).optional(),\n disallowedTools: z.array(z.string()).optional(),\n prompt: z.string(),\n model: z.enum(['sonnet', 'opus', 'haiku', 'inherit']).optional(),\n mcpServers: z\n .array(\n z.union([\n z.string(),\n z.record(z.string(), z.any()), // McpServerConfigForProcessTransport\n ])\n )\n .optional(),\n criticalSystemReminder_EXPERIMENTAL: z.string().optional(),\n })\n .passthrough()\n )\n .optional(),\n includePartialMessages: z.boolean().optional(),\n fallbackModel: z.string().optional(),\n forkSession: z.boolean().optional(),\n stderr: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'stderr must be a function',\n })\n .optional(),\n strictMcpConfig: z.boolean().optional(),\n extraArgs: z.record(z.string(), z.union([z.string(), z.null()])).optional(),\n persistSession: z.boolean().optional(),\n spawnClaudeCodeProcess: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'spawnClaudeCodeProcess must be a function',\n })\n .optional(),\n sdkOptions: z.record(z.string(), z.any()).optional(),\n maxToolResultSize: z.number().int().min(100).max(1000000).optional(),\n // Callback invoked when Query object is created - for mid-stream injection via streamInput()\n onQueryCreated: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'onQueryCreated must be a function',\n })\n .optional(),\n onStreamStart: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'onStreamStart must be a function',\n })\n .optional(),\n })\n .strict();\n\n/**\n * Validates a model ID and returns warnings if needed.\n *\n * @param modelId - The model ID to validate\n * @returns Warning message if model is unknown, undefined otherwise\n */\nexport function validateModelId(modelId: string): string | undefined {\n const knownModels = ['opus', 'sonnet', 'haiku'];\n\n // Check for empty or whitespace-only\n if (!modelId || modelId.trim() === '') {\n throw new Error('Model ID cannot be empty');\n }\n\n // Warn about unknown models but allow them\n if (!knownModels.includes(modelId)) {\n return `Unknown model ID: '${modelId}'. Proceeding with custom model. Known models are: ${knownModels.join(', ')}`;\n }\n\n return undefined;\n}\n\n/**\n * Validates Claude Code settings and returns validation results.\n *\n * @param settings - The settings object to validate\n * @returns Object with validation results and any warnings\n */\nexport function validateSettings(settings: unknown): {\n valid: boolean;\n warnings: string[];\n errors: string[];\n} {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n try {\n // Parse with Zod schema\n const result = claudeCodeSettingsSchema.safeParse(settings);\n\n if (!result.success) {\n // Extract user-friendly error messages\n // Support both Zod v3 (errors) and v4 (issues)\n const errorObject = result.error as {\n errors?: Array<{ path: string[]; message: string }>;\n issues?: Array<{ path: string[]; message: string }>;\n };\n const issues = errorObject.errors || errorObject.issues || [];\n issues.forEach((err: { path: string[]; message: string }) => {\n const path = err.path.join('.');\n errors.push(`${path ? `${path}: ` : ''}${err.message}`);\n });\n return { valid: false, warnings, errors };\n }\n\n // Additional validation warnings\n const validSettings = result.data;\n\n // Warn about high turn limits\n if (validSettings.maxTurns && validSettings.maxTurns > 20) {\n warnings.push(\n `High maxTurns value (${validSettings.maxTurns}) may lead to long-running conversations`\n );\n }\n\n // Warn about very high thinking tokens\n if (validSettings.maxThinkingTokens && validSettings.maxThinkingTokens > 50000) {\n warnings.push(\n `Very high maxThinkingTokens (${validSettings.maxThinkingTokens}) may increase response time`\n );\n }\n\n // Check if both allowedTools and disallowedTools are specified\n if (validSettings.allowedTools && validSettings.disallowedTools) {\n warnings.push(\n 'Both allowedTools and disallowedTools are specified. Only allowedTools will be used.'\n );\n }\n\n // Validate tool name format\n const validateToolNames = (tools: string[], type: string) => {\n tools.forEach((tool) => {\n // Basic validation - tool names should be alphanumeric with optional specifiers\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*(\\([^)]*\\))?$/.test(tool) && !tool.startsWith('mcp__')) {\n warnings.push(`Unusual ${type} tool name format: '${tool}'`);\n }\n });\n };\n\n if (validSettings.allowedTools) {\n validateToolNames(validSettings.allowedTools, 'allowed');\n }\n\n if (validSettings.disallowedTools) {\n validateToolNames(validSettings.disallowedTools, 'disallowed');\n }\n\n // Warn about Skills configuration issues\n if (validSettings.allowedTools?.includes('Skill') && !validSettings.settingSources) {\n warnings.push(\n \"allowedTools includes 'Skill' but settingSources is not set. Skills require settingSources (e.g., ['user', 'project']) to load skill definitions.\"\n );\n }\n\n return { valid: true, warnings, errors };\n } catch (error) {\n errors.push(`Validation error: ${error instanceof Error ? error.message : String(error)}`);\n return { valid: false, warnings, errors };\n }\n}\n\n/**\n * Validates prompt length and format.\n *\n * @param prompt - The prompt to validate\n * @returns Warning message if prompt might cause issues\n */\nexport function validatePrompt(prompt: string): string | undefined {\n // Very long prompts might cause issues\n const MAX_PROMPT_LENGTH = 100000; // ~25k tokens\n\n if (prompt.length > MAX_PROMPT_LENGTH) {\n return `Very long prompt (${prompt.length} characters) may cause performance issues or timeouts`;\n }\n\n return undefined;\n}\n\n/**\n * Validates session ID format.\n *\n * @param sessionId - The session ID to validate\n * @returns Warning message if format is unusual\n */\nexport function validateSessionId(sessionId: string): string | undefined {\n // Session IDs from Claude Code are typically UUID-like\n // But we don't want to be too strict as format might change\n if (sessionId && !/^[a-zA-Z0-9-_]+$/.test(sessionId)) {\n return `Unusual session ID format. This may cause issues with session resumption.`;\n }\n\n return undefined;\n}\n","import type { Logger } from './types.js';\n\n/**\n * Default logger that uses console with level tags.\n */\nconst defaultLogger: Logger = {\n // eslint-disable-next-line no-console\n debug: (message: string) => console.debug(`[DEBUG] ${message}`),\n // eslint-disable-next-line no-console\n info: (message: string) => console.info(`[INFO] ${message}`),\n warn: (message: string) => console.warn(`[WARN] ${message}`),\n error: (message: string) => console.error(`[ERROR] ${message}`),\n};\n\n/**\n * No-op logger that discards all messages.\n */\nconst noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Gets the appropriate logger based on configuration.\n *\n * @param logger - Logger configuration from settings\n * @returns The logger to use\n */\nexport function getLogger(logger: Logger | false | undefined): Logger {\n if (logger === false) {\n return noopLogger;\n }\n\n if (logger === undefined) {\n return defaultLogger;\n }\n\n return logger;\n}\n\n/**\n * Creates a verbose-aware logger that only logs debug/info when verbose is enabled.\n * Warn and error are always logged regardless of verbose setting.\n *\n * @param logger - Base logger to wrap\n * @param verbose - Whether to enable verbose (debug/info) logging\n * @returns Logger with verbose-aware behavior\n */\nexport function createVerboseLogger(logger: Logger, verbose: boolean = false): Logger {\n if (verbose) {\n // When verbose is enabled, use all log levels\n return logger;\n }\n\n // When verbose is disabled, only allow warn/error\n // Bind methods to preserve 'this' context for custom loggers\n return {\n debug: () => {}, // No-op when not verbose\n info: () => {}, // No-op when not verbose\n warn: logger.warn.bind(logger),\n error: logger.error.bind(logger),\n };\n}\n","/**\n * Provider exports for creating and configuring Claude Code instances.\n * @module claude-code\n */\n\n/**\n * Creates a new Claude Code provider instance and the default provider instance.\n * @see {@link createClaudeCode} for creating custom provider instances\n * @see {@link claudeCode} for the default provider instance\n */\nexport { createClaudeCode, claudeCode } from './claude-code-provider.js';\n\n/**\n * Type definitions for the Claude Code provider.\n * @see {@link ClaudeCodeProvider} for the provider interface\n * @see {@link ClaudeCodeProviderSettings} for provider configuration options\n */\nexport type { ClaudeCodeProvider, ClaudeCodeProviderSettings } from './claude-code-provider.js';\n\n/**\n * Language model implementation for Claude Code.\n * This class implements the AI SDK's LanguageModelV3 interface.\n */\nexport { ClaudeCodeLanguageModel } from './claude-code-language-model.js';\n\n/**\n * Type definitions for Claude Code language models.\n * @see {@link ClaudeCodeModelId} for supported model identifiers\n * @see {@link ClaudeCodeLanguageModelOptions} for model configuration options\n */\nexport type {\n ClaudeCodeModelId,\n ClaudeCodeLanguageModelOptions,\n} from './claude-code-language-model.js';\n\n/**\n * Settings for configuring Claude Code behavior.\n * Includes options for customizing the CLI execution, permissions, and tool usage.\n */\nexport type { ClaudeCodeSettings, Logger, MessageInjector } from './types.js';\n\n// Convenience re-exports from the SDK for custom tools and hooks\nexport { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nexport { createCustomMcpServer } from './mcp-helpers.js';\nexport type { ToolAnnotations, MinimalCallToolResult } from './mcp-helpers.js';\nexport type {\n HookEvent,\n HookCallback,\n HookCallbackMatcher,\n HookInput,\n HookJSONOutput,\n PreToolUseHookInput,\n PostToolUseHookInput,\n UserPromptSubmitHookInput,\n SessionStartHookInput,\n SessionEndHookInput,\n TeammateIdleHookInput,\n TaskCompletedHookInput,\n CanUseTool,\n PermissionResult,\n PermissionUpdate,\n PermissionBehavior,\n PermissionRuleValue,\n McpServerConfig,\n McpSdkServerConfigWithInstance,\n OutputFormat,\n SpawnedProcess,\n SpawnOptions,\n AgentMcpServerSpec,\n // Query interface for mid-stream message injection via streamInput()\n Query,\n // Thinking configuration types\n ThinkingConfig,\n ThinkingAdaptive,\n ThinkingEnabled,\n ThinkingDisabled,\n} from '@anthropic-ai/claude-agent-sdk';\n\n/**\n * Error handling utilities for Claude Code.\n * These functions help create and identify specific error types.\n *\n * @see {@link isAuthenticationError} to check for authentication failures\n * @see {@link isTimeoutError} to check for timeout errors\n * @see {@link getErrorMetadata} to extract error metadata\n * @see {@link createAPICallError} to create general API errors\n * @see {@link createAuthenticationError} to create authentication errors\n * @see {@link createTimeoutError} to create timeout errors\n */\nexport {\n isAuthenticationError,\n isTimeoutError,\n getErrorMetadata,\n createAPICallError,\n createAuthenticationError,\n createTimeoutError,\n} from './errors.js';\n\n/**\n * Metadata associated with Claude Code errors.\n * Contains additional context about CLI execution failures.\n */\nexport type { ClaudeCodeErrorMetadata } from './errors.js';\n","import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport type {\n McpSdkServerConfigWithInstance,\n SdkMcpToolDefinition,\n} from '@anthropic-ai/claude-agent-sdk';\nimport { type ZodRawShape, type ZodObject } from 'zod';\n\n/**\n * Optional annotations for content items, per MCP specification.\n * Validated against MCP SDK schema version 2025-06-18.\n */\ntype ContentAnnotations = {\n /** Intended audience(s) for this content */\n audience?: ('user' | 'assistant')[];\n /** Priority hint (0 = least important, 1 = most important) */\n priority?: number;\n /** ISO 8601 timestamp of last modification */\n lastModified?: string;\n};\n\n/**\n * MCP tool annotations for hinting tool behavior to the model.\n * Derived from the SDK's SdkMcpToolDefinition type to stay in sync\n * with the upstream MCP ToolAnnotations definition.\n */\nexport type ToolAnnotations = NonNullable<SdkMcpToolDefinition['annotations']>;\n\n/**\n * Convenience helper to create an SDK MCP server from a simple tool map.\n * Each tool provides a description, a Zod object schema, and a handler.\n *\n * Type definition validated against MCP SDK specification version 2025-06-18.\n * See: https://modelcontextprotocol.io/specification/2025-06-18/server/tools\n */\nexport type MinimalCallToolResult = {\n content: Array<\n | {\n /** Text content */\n type: 'text';\n /** The text content (plain text or structured format like JSON) */\n text: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Image content (base64-encoded) */\n type: 'image';\n /** Base64-encoded image data */\n data: string;\n /** MIME type of the image (e.g., image/png, image/jpeg) */\n mimeType: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Audio content (base64-encoded) */\n type: 'audio';\n /** Base64-encoded audio data */\n data: string;\n /** MIME type of the audio (e.g., audio/wav, audio/mp3) */\n mimeType: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Embedded resource with full content (text or blob) */\n type: 'resource';\n /** Resource contents - either text or blob variant */\n resource: { uri: string; _meta?: Record<string, unknown>; [key: string]: unknown } & (\n | { text: string; mimeType?: string }\n | { blob: string; mimeType: string }\n );\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Resource link (reference only - no embedded content) */\n type: 'resource_link';\n /** URI of the resource */\n uri: string;\n /** Human-readable name (required per MCP spec) */\n name: string;\n /** Optional description of what this resource represents */\n description?: string;\n /** MIME type of the resource, if known */\n mimeType?: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n >;\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nexport function createCustomMcpServer<\n Tools extends Record<\n string,\n {\n description: string;\n inputSchema: ZodObject<ZodRawShape>;\n handler: (args: Record<string, unknown>, extra: unknown) => Promise<MinimalCallToolResult>;\n annotations?: ToolAnnotations;\n }\n >,\n>(config: { name: string; version?: string; tools: Tools }): McpSdkServerConfigWithInstance {\n const defs = Object.entries(config.tools).map(([name, def]) =>\n tool(\n name,\n def.description,\n def.inputSchema.shape as ZodRawShape,\n (args: Record<string, unknown>, extra: unknown) => def.handler(args, extra),\n def.annotations ? { annotations: def.annotations } : undefined\n )\n );\n return createSdkMcpServer({ name: config.name, version: config.version, tools: defs });\n}\n"],"mappings":";AACA,SAAS,oBAAAA,yBAAwB;;;ACQjC,SAAS,wBAAuD;AAChE,SAAS,kBAAkB;;;ACD3B,IAAM,oBAAoB;AAC1B,IAAM,2BAA2B;AAEjC,SAAS,gBAAgB,QAAwB;AAC/C,SAAO,OAAO,QAAQ,QAAQ,EAAE;AAClC;AAEA,SAAS,gBAAgB,UAA4B;AACnD,SAAO,OAAO,aAAa,YAAY,SAAS,KAAK,EAAE,YAAY,EAAE,WAAW,QAAQ;AAC1F;AAEA,SAAS,mBAAmB,WAAmB,MAA8C;AAC3F,QAAM,cAAc,UAAU,KAAK;AACnC,QAAM,cAAc,gBAAgB,KAAK,KAAK,CAAC;AAE/C,MAAI,CAAC,eAAe,CAAC,aAAa;AAChC,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,MAAM;AAAA,IACR;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,WAAwC;AAC/D,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,GAAG;AACrD,WAAO,U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M,KAAK;AAAA,MAC1E,IAAI,cAAc,EAAE,aAAa,IAAI,YAAY,IAAI;AAAA,IACvD;AAAA,EACF;AACA,SAAO,mBAAmB,EAAE,MAAM,OAAO,MAAM,SAAS,OAAO,SAAS,OAAO,KAAK,CAAC;AACvF;","names":["NoSuchModelError","tool","tool","largestSize","content","tool","NoSuchModelError","createSdkMcpServer","tool"]}
|
|
1
|
+
{"version":3,"sources":["../src/claude-code-provider.ts","../src/claude-code-language-model.ts","../src/convert-to-claude-code-messages.ts","../src/errors.ts","../src/map-claude-code-finish-reason.ts","../src/validation.ts","../src/sanitize-json-schema.ts","../src/logger.ts","../src/index.ts","../src/mcp-helpers.ts"],"sourcesContent":["import type { LanguageModelV3, ProviderV3 } from '@ai-sdk/provider';\nimport { NoSuchModelError } from '@ai-sdk/provider';\nimport { ClaudeCodeLanguageModel, type ClaudeCodeModelId } from './claude-code-language-model.js';\nimport type { ClaudeCodeSettings } from './types.js';\nimport { validateSettings } from './validation.js';\nimport { getLogger } from './logger.js';\n\n/**\n * Claude Code provider interface that extends the AI SDK's ProviderV3.\n * Provides methods to create language models for interacting with Claude via the CLI.\n *\n * @example\n * ```typescript\n * import { claudeCode } from 'ai-sdk-provider-claude-code';\n *\n * // Create a model instance\n * const model = claudeCode('opus');\n *\n * // Or use the explicit methods\n * const chatModel = claudeCode.chat('sonnet');\n * const languageModel = claudeCode.languageModel('opus', { maxTurns: 10 });\n * ```\n */\nexport interface ClaudeCodeProvider extends ProviderV3 {\n /**\n * Creates a language model instance for the specified model ID.\n * This is a shorthand for calling `languageModel()`.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n (modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n /**\n * Creates a language model instance for text generation.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n languageModel(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n /**\n * Alias for `languageModel()` to maintain compatibility with AI SDK patterns.\n *\n * @param modelId - The Claude model to use ('opus' or 'sonnet')\n * @param settings - Optional settings to configure the model\n * @returns A language model instance\n */\n chat(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;\n\n imageModel(modelId: string): never;\n}\n\n/**\n * Configuration options for creating a Claude Code provider instance.\n * These settings will be applied as defaults to all models created by the provider.\n *\n * @example\n * ```typescript\n * const provider = createClaudeCode({\n * defaultSettings: {\n * maxTurns: 5,\n * cwd: '/path/to/project'\n * }\n * });\n * ```\n */\nexport interface ClaudeCodeProviderSettings {\n /**\n * Default settings to use for all models created by this provider.\n * Individual model settings will override these defaults.\n */\n defaultSettings?: ClaudeCodeSettings;\n}\n\n/**\n * Creates a Claude Code provider instance with the specified configuration.\n * The provider can be used to create language models for interacting with Claude 4 models.\n *\n * @param options - Provider configuration options\n * @returns Claude Code provider instance\n *\n * @example\n * ```typescript\n * const provider = createClaudeCode({\n * defaultSettings: {\n * permissionMode: 'bypassPermissions',\n * maxTurns: 10\n * }\n * });\n *\n * const model = provider('opus');\n * ```\n */\nexport function createClaudeCode(options: ClaudeCodeProviderSettings = {}): ClaudeCodeProvider {\n // Get logger from default settings if provided\n const logger = getLogger(options.defaultSettings?.logger);\n\n // Validate default settings if provided\n if (options.defaultSettings) {\n const validation = validateSettings(options.defaultSettings);\n if (!validation.valid) {\n throw new Error(`Invalid default settings: ${validation.errors.join(', ')}`);\n }\n if (validation.warnings.length > 0) {\n validation.warnings.forEach((warning) => logger.warn(`Claude Code Provider: ${warning}`));\n }\n }\n\n const createModel = (\n modelId: ClaudeCodeModelId,\n settings: ClaudeCodeSettings = {}\n ): LanguageModelV3 => {\n const mergedSettings = {\n ...options.defaultSettings,\n ...settings,\n };\n\n // Validate merged settings\n const validation = validateSettings(mergedSettings);\n if (!validation.valid) {\n throw new Error(`Invalid settings: ${validation.errors.join(', ')}`);\n }\n\n return new ClaudeCodeLanguageModel({\n id: modelId,\n settings: mergedSettings,\n settingsValidationWarnings: validation.warnings,\n });\n };\n\n const provider = function (modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings) {\n if (new.target) {\n throw new Error('The Claude Code model function cannot be called with the new keyword.');\n }\n\n return createModel(modelId, settings);\n };\n\n provider.languageModel = createModel;\n provider.chat = createModel; // Alias for languageModel\n provider.specificationVersion = 'v3' as const;\n\n // Add embeddingModel method that throws NoSuchModelError\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'embeddingModel',\n });\n };\n\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'imageModel',\n });\n };\n\n return provider as ClaudeCodeProvider;\n}\n\n/**\n * Default Claude Code provider instance.\n * Pre-configured provider for quick usage without custom settings.\n *\n * @example\n * ```typescript\n * import { claudeCode } from 'ai-sdk-provider-claude-code';\n * import { generateText } from 'ai';\n *\n * const { text } = await generateText({\n * model: claudeCode('sonnet'),\n * prompt: 'Hello, Claude!'\n * });\n * ```\n */\nexport const claudeCode = createClaudeCode();\n","import type {\n LanguageModelV3,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3ToolCall,\n LanguageModelV3ToolResult,\n LanguageModelV3Usage,\n SharedV3Warning,\n JSONValue,\n JSONObject,\n} from '@ai-sdk/provider';\nimport { NoSuchModelError, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\nimport { generateId } from '@ai-sdk/provider-utils';\nimport type { ClaudeCodeSettings, Logger, MessageInjector } from './types.js';\nimport { convertToClaudeCodeMessages } from './convert-to-claude-code-messages.js';\nimport { createAPICallError, createAuthenticationError, createTimeoutError } from './errors.js';\nimport { mapClaudeCodeFinishReason } from './map-claude-code-finish-reason.js';\nimport { validateModelId, validatePrompt, validateSessionId, isBlankResume } from './validation.js';\nimport { sanitizeJsonSchemaForOutputFormat } from './sanitize-json-schema.js';\nimport { getLogger, createVerboseLogger } from './logger.js';\n\nimport { query, type Options } from '@anthropic-ai/claude-agent-sdk';\nimport type {\n SDKMessage,\n SDKUserMessage,\n SDKPartialAssistantMessage,\n} from '@anthropic-ai/claude-agent-sdk';\n\n/**\n * Provider version reported to the Agent SDK via CLAUDE_AGENT_SDK_CLIENT_APP.\n * Keep in sync with package.json (kept as a constant to avoid a build step).\n */\nconst PROVIDER_VERSION = '3.5.0';\nconst DEFAULT_CLIENT_APP = `ai-sdk-provider-claude-code/${PROVIDER_VERSION}`;\n\nconst CLAUDE_CODE_TRUNCATION_WARNING =\n 'Claude Code SDK output ended unexpectedly; returning truncated response from buffered text. Await upstream fix to avoid data loss.';\n\nconst MIN_TRUNCATION_LENGTH = 512;\n\n/**\n * Detects if an error represents a truncated SDK JSON stream.\n *\n * The Claude Code SDK can truncate JSON responses mid-stream, producing a SyntaxError.\n * This function distinguishes genuine truncation from normal JSON syntax errors by:\n * 1. Verifying the error is a SyntaxError with truncation-specific messages\n * 2. Ensuring we received meaningful content (>= MIN_TRUNCATION_LENGTH characters)\n * 3. Avoiding false positives from unrelated parse errors\n *\n * Note: We compare against `bufferedText` (assistant text content) rather than the raw\n * JSON buffer length, since the SDK layer doesn't expose buffer positions. The position\n * reported in SyntaxError messages measures the full JSON payload (metadata + content),\n * which is typically much larger than extracted text. Therefore, we cannot reliably use\n * position proximity checks and instead rely on message patterns and content length.\n *\n * @param error - The caught error (expected to be SyntaxError for truncation)\n * @param bufferedText - Accumulated assistant text content (measured in UTF-16 code units)\n * @returns true if error indicates SDK truncation; false otherwise\n */\n// Re-validated against SDK 0.3.170 on 2026-06-09: kept as defensive detection.\nfunction isClaudeCodeTruncationError(error: unknown, bufferedText: string): boolean {\n // Check for SyntaxError by instanceof or by name (for cross-realm errors)\n const isSyntaxError =\n error instanceof SyntaxError ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (typeof (error as any)?.name === 'string' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).name.toLowerCase() === 'syntaxerror');\n\n if (!isSyntaxError) {\n return false;\n }\n\n if (!bufferedText) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawMessage = typeof (error as any)?.message === 'string' ? (error as any).message : '';\n const message = rawMessage.toLowerCase();\n\n // Only match actual truncation patterns, not normal JSON parsing errors.\n // Real truncation: \"Unexpected end of JSON input\" or \"Unterminated string in JSON...\"\n // Normal errors: \"Unexpected token X in JSON at position N\" (should be surfaced as errors)\n const truncationIndicators = [\n 'unexpected end of json input',\n 'unexpected end of input',\n 'unexpected end of string',\n 'unexpected eof',\n 'end of file',\n 'unterminated string',\n 'unterminated string constant',\n ];\n\n if (!truncationIndicators.some((indicator) => message.includes(indicator))) {\n return false;\n }\n\n // Require meaningful content before treating as truncation.\n // Short responses with \"end of input\" errors are likely genuine syntax errors.\n // Note: bufferedText.length measures UTF-16 code units, not byte length.\n if (bufferedText.length < MIN_TRUNCATION_LENGTH) {\n return false;\n }\n\n // If we have a truncation indicator AND meaningful content, treat as truncation.\n return true;\n}\n\n/**\n * Error message thrown when structured output was requested but the CLI\n * returned neither `structured_output` nor parseable JSON prose. The usual\n * cause is a schema construct the CLI's constrained decoder cannot enforce\n * (the CLI then silently falls back to prose instead of erroring).\n */\nconst MISSING_STRUCTURED_OUTPUT_ERROR_MESSAGE =\n 'Structured output was requested (responseFormat with a JSON schema) but the Claude Code CLI returned no structured_output, and the prose response could not be parsed as JSON. ' +\n 'This usually means the schema contains constructs the CLI cannot enforce (e.g. complex regex patterns with lookaheads/backreferences), causing it to silently fall back to prose. ' +\n \"Simplify the generation schema and validate strictly client-side. See the 'Structured Outputs' section of the ai-sdk-provider-claude-code README for the list of known limitations.\";\n\n/**\n * Attempts to recover a JSON object/array from prose text returned when the\n * CLI silently skipped structured output. Tries the trimmed text first, then\n * the contents of fenced code blocks (```json ... ``` or ``` ... ```),\n * last-to-first — when several blocks are present, the final one is most\n * likely the model's actual answer.\n *\n * Only candidates that parse to a JSON object or array count: this recovery\n * path only runs when `responseFormat.schema` is present (always an\n * object/array schema in practice), and accepting scalars (prose that trims\n * to `null`, `true`, or a bare number) would bypass the loud failure only to\n * fail downstream with the opaque AI_NoObjectGeneratedError this path exists\n * to eliminate.\n *\n * @param text - Accumulated assistant prose text\n * @returns The valid JSON text (as emitted by the model) or undefined\n */\nfunction extractJsonObjectText(text: string): string | undefined {\n const trimmed = text.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const candidates: string[] = [trimmed];\n const fencedBlocks = Array.from(trimmed.matchAll(/```(?:json)?\\s*\\n?([\\s\\S]*?)```/gi))\n .map((match) => match[1]?.trim())\n .filter((block): block is string => block !== undefined && block.length > 0);\n candidates.push(...fencedBlocks.reverse());\n\n for (const candidate of candidates) {\n if (!candidate) continue;\n try {\n const parsed: unknown = JSON.parse(candidate);\n if (typeof parsed === 'object' && parsed !== null) {\n return candidate;\n }\n // Scalar JSON (null, booleans, numbers, bare strings) - not a valid\n // structured output; try the next candidate.\n } catch {\n // Try the next candidate\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts the structured error kind attached to errors thrown from result\n * handling. SDK 0.3.x delivers API failure kinds (SDKAssistantMessageError,\n * e.g. 'overloaded', 'model_not_found', 'oauth_org_not_allowed') as structured\n * fields on assistant messages rather than in thrown error text, so\n * classification must not rely on message substrings alone.\n */\nfunction getStructuredErrorKind(error: unknown): string | undefined {\n if (typeof error === 'object' && error !== null && 'errorKind' in error) {\n const kind = (error as { errorKind?: unknown }).errorKind;\n if (typeof kind === 'string') return kind;\n }\n return undefined;\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (err && typeof err === 'object') {\n const e = err as { name?: unknown; code?: unknown };\n if (typeof e.name === 'string' && e.name === 'AbortError') return true;\n if (typeof e.code === 'string' && e.code.toUpperCase() === 'ABORT_ERR') return true;\n }\n return false;\n}\n\nconst DEFAULT_INHERITED_ENV_VARS =\n process.platform === 'win32'\n ? [\n 'APPDATA',\n 'COMSPEC',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PATHEXT',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'TMP',\n 'USERNAME',\n 'USERPROFILE',\n 'WINDIR',\n ]\n : ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER', 'LANG', 'LC_ALL', 'TMPDIR'];\n\nconst CLAUDE_ENV_VARS = ['CLAUDE_CONFIG_DIR'];\n\n// Proxy and TLS configuration needed for the subprocess to reach the API.\nconst NETWORK_ENV_VARS = [\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'NO_PROXY',\n 'http_proxy',\n 'https_proxy',\n 'no_proxy',\n 'NODE_EXTRA_CA_CERTS',\n 'SSL_CERT_FILE',\n 'SSL_CERT_DIR',\n];\n\n// Bedrock/Vertex configuration not covered by the AWS_/GOOGLE_ prefixes.\nconst CLOUD_ENV_VARS = ['GCLOUD_PROJECT', 'CLOUD_ML_REGION'];\n\n// Prefix-matched inheritance for auth and cloud-provider configuration\n// (e.g. ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, AWS_PROFILE, GOOGLE_APPLICATION_CREDENTIALS).\nconst INHERITED_ENV_PREFIXES = ['ANTHROPIC_', 'CLAUDE_', 'AWS_', 'GOOGLE_'];\n\nfunction getBaseProcessEnv(): Record<string, string> {\n const env: Record<string, string> = {};\n const allowedKeys = new Set([\n ...DEFAULT_INHERITED_ENV_VARS,\n ...CLAUDE_ENV_VARS,\n ...NETWORK_ENV_VARS,\n ...CLOUD_ENV_VARS,\n ]);\n\n const addIfSafe = (key: string): void => {\n const value = process.env[key];\n if (typeof value !== 'string') {\n return;\n }\n\n // Skip exported shell functions (Shellshock-style values).\n if (value.startsWith('()')) {\n return;\n }\n\n env[key] = value;\n };\n\n for (const key of allowedKeys) {\n addIfSafe(key);\n }\n\n for (const key of Object.keys(process.env)) {\n if (INHERITED_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))) {\n addIfSafe(key);\n }\n }\n\n return env;\n}\n\nconst STREAMING_FEATURE_WARNING =\n \"Claude Agent SDK features (hooks/MCP/images) require streaming input. Set `streamingInput: 'always'` or provide `canUseTool` (auto streams only when canUseTool is set).\";\n\nconst SDK_OPTIONS_BLOCKLIST = new Set(['model', 'abortController', 'prompt', 'outputFormat']);\n\n/**\n * Tool names the CLI uses to launch subagents. The CLI bundled with the\n * pinned SDK (2.1.170) names the tool 'Task' (verified via the init tool\n * list), while current Agent SDK docs name it 'Agent' with 'Task' as a\n * backwards-compatible alias — recognize both so parent-hierarchy tracking\n * survives the upstream rename.\n */\nconst SUBAGENT_TOOL_NAMES = new Set(['Task', 'Agent']);\n\nfunction isSubagentToolName(name: string): boolean {\n return SUBAGENT_TOOL_NAMES.has(name);\n}\n\n/**\n * Resolve a tool's parentToolCallId. SDK 0.3 messages carry a REQUIRED\n * `parent_tool_use_id: string | null` (string = subagent parent, null =\n * top-level), so an explicit value — INCLUDING null — is authoritative and\n * wins over timing inference. The single-active-Task inference is only a\n * legacy fallback for older CLIs that omit the field (undefined). A `?? `\n * chain would wrongly treat an explicit null as \"missing\" and infer a parent,\n * nesting a top-level tool under an unrelated active Task.\n */\nfunction resolveToolParentId(\n messageLevel: string | null | undefined,\n blockLevel: string | null | undefined,\n inferFallback: () => string | null\n): string | null {\n if (messageLevel !== undefined) return messageLevel;\n if (typeof blockLevel === 'string') return blockLevel;\n return inferFallback();\n}\n\n/* ---------------------------------------------------------------------------\n * Refusal-fallback retraction policy (shared by doGenerate + doStream)\n *\n * SDK 0.3.x can RETRACT content the model already produced when a refusal\n * fallback swaps the answering model mid-turn. Two retraction signals feed the\n * SAME eviction routine, and the policy below is IDENTICAL in both loops:\n *\n * (P1) Two signals compose idempotently:\n * - an assistant message's `supersedes[]` (named on the replacement,\n * applied on arrival), and\n * - the end-of-turn `model_refusal_fallback` notice's\n * `retracted_message_uuids` (the SDK's complete, resolution-time\n * eviction record for the turn).\n * Re-evicting an already-removed uuid is a no-op, so replaying both is safe.\n * (P2) A retracted uuid evicts: text/reasoning segments tagged with it;\n * tool-CALL segments tagged with it (and TRANSITIVELY their\n * tool-result/tool-error); AND tool-result/tool-error frames tagged with\n * THEIR OWN frame uuid even when the originating tool_use was not retracted.\n * (P3) A retracted tool-call id becomes a TOMBSTONE so LATE tool_result/\n * tool_error frames for that id are DROPPED (not re-synthesized into an\n * orphan tool-call), preventing AI SDK asContent() 'Tool call not found.'\n * (P4) Retracted Task/subagent tools are removed from activeTaskTools so\n * fallback-parent inference is not polluted by a dangling parent.\n * (P5) Retraction must NOT depend on the superseding message carrying text of\n * its own.\n *\n * The MECHANISM differs and is intentionally NOT unified (see evictBuffered /\n * evictLive at the two call sites):\n * - doGenerate buffers a uniform, ordered `contentSegments` array and can\n * splice retracted entries out, restoring exact document order; its tool-id\n * set is derived from tool-CALL own-uuid AND tool-result/error own-uuid\n * membership (a result frame may be named directly).\n * - doStream operates on already-emitted wire parts + live toolStates + index\n * maps and can only DROP pending (not-yet-callEmitted) state; its tool-id set\n * is derived from toolState.messageUuid (results are not buffered as segments).\n *\n * The shareable unit is the POLICY (which uuids retract which tool ids), not the\n * mechanism. {@link computeRetractedToolCallIds} expresses that policy over a\n * uniform `{ toolCallId, uuid }` descriptor stream so BOTH call sites derive the\n * tombstone set identically while applying removal in their own structure.\n * ------------------------------------------------------------------------- */\n\n/** A retraction candidate: a tool id paired with the frame uuid that owns it. */\ntype RetractionToolDescriptor = { toolCallId: string; uuid: string | undefined };\n\n/**\n * Policy (P2/P3): given the retracted uuid set and the tool descriptors a path\n * exposes, return the set of tool-call ids that must be tombstoned. A descriptor\n * retracts its tool id iff its own uuid is in the retracted set. doGenerate feeds\n * tool-call AND tool-result/error descriptors (so a directly-named result frame\n * tombstones its call); doStream feeds one descriptor per live toolState keyed on\n * messageUuid. Callers then perform structure-specific removal + activeTaskTools\n * cleanup (P4).\n */\nfunction computeRetractedToolCallIds(\n retracted: Set<string>,\n descriptors: Iterable<RetractionToolDescriptor>\n): Set<string> {\n const ids = new Set<string>();\n for (const { toolCallId, uuid } of descriptors) {\n if (uuid !== undefined && retracted.has(uuid)) {\n ids.add(toolCallId);\n }\n }\n return ids;\n}\n\n/**\n * Policy (P1/P5): the supersede-on-arrival trigger, shared by both loops. When a\n * superseding assistant message names prior messages in `supersedes[]`, debug-log\n * and replay them through the path's eviction routine. Returns whether a\n * supersede was applied (the stream path branches its text-emission on this).\n * Deliberately does NOT inspect the message's own text — retraction must not\n * depend on the replacement carrying text (P5).\n */\nfunction applySupersede(\n message: { supersedes?: string[] },\n evict: (retracted: Set<string>) => void,\n logger: Logger,\n // The two loops historically guarded this branch differently for malformed\n // (out-of-contract) `supersedes` values, and that divergence is preserved\n // deliberately. doGenerate used a truthiness check\n // (`message.supersedes && message.supersedes.length > 0`); doStream used an\n // Array.isArray check. For well-formed `string[] | undefined` SDK values the\n // two modes are identical — they only diverge on non-array truthy inputs.\n guard: 'truthy' | 'array' = 'array'\n): boolean {\n const supersedes = message.supersedes;\n const triggered =\n guard === 'truthy'\n ? Boolean(supersedes && supersedes.length > 0)\n : Array.isArray(supersedes) && supersedes.length > 0;\n if (!triggered) {\n return false;\n }\n logger.debug(`[claude-code] Assistant message supersedes ${supersedes!.length} prior message(s)`);\n evict(new Set<string>(supersedes!));\n return true;\n}\n\n/**\n * Policy (P1): build the `onRetractedUuids` thunk handed to handleSystemMessage.\n * Both loops pass an identical `(uuids) => evict(new Set(uuids))`, replaying the\n * end-of-turn model_refusal_fallback notice's retracted_message_uuids through the\n * SAME eviction routine that supersedes uses. Defined once so the \"compose the\n * two retraction signals\" contract lives in one place.\n */\nfunction buildRetractionEvictor(\n evict: (retracted: Set<string>) => void\n): (uuids: string[]) => void {\n return (uuids) => evict(new Set(uuids));\n}\n\n/**\n * SDK 0.3.x system-message subtypes that are intentionally informational.\n * The provider debug-logs and ignores them: they carry host/UI telemetry\n * with no AI SDK stream-part equivalent.\n *\n * - 'notification' REPL-style text notifications (key/priority/timeout)\n * - 'status' spinner status ('requesting'/'compacting' and compact_result/compact_error)\n * - 'task_updated' background-task state patches\n * - 'session_state_changed' idle/running/requires_action transitions\n * - 'commands_changed' mid-session slash-command list refresh\n * - 'memory_recall' surfaced memory files/synthesis\n * - 'plugin_install' headless plugin installation progress\n */\nconst INFORMATIONAL_SYSTEM_SUBTYPES = new Set<string>([\n 'notification',\n 'status',\n 'task_updated',\n 'session_state_changed',\n 'commands_changed',\n 'memory_recall',\n 'plugin_install',\n]);\n\n/** Narrowed union of SDK system messages (init, api_retry, permission_denied, ...). */\ntype SDKSystemMessageVariant = Extract<SDKMessage, { type: 'system' }>;\n\n/**\n * A tool denial recorded from a `permission_denied` system message or from\n * the result message's `permission_denials` list (the latter is the only\n * place PreToolUse-hook denials appear — they bypass canUseTool and emit no\n * `permission_denied` system event).\n */\ntype PermissionDenialRecord = {\n toolName: string;\n toolUseId?: string;\n reason?: string;\n};\n\n/** Mutable per-request counters surfaced in providerMetadata at finish. */\ntype RequestMetadataTracking = {\n apiRetries: number;\n permissionDenials: PermissionDenialRecord[];\n /**\n * SessionStore transcript-mirror append failures (`mirror_error`). Each is a\n * DROPPED transcript batch after retries — surfaced (warn-logged + here) so\n * `sessionStore` consumers aren't told the mirror is intact when it lost\n * entries. `{ error, sessionId }` per occurrence.\n */\n mirrorErrors: Array<{ error: string; sessionId: string }>;\n /**\n * Accumulated `thinking_tokens` estimate. The SDK's `estimated_tokens` is a\n * per-thinking-block running total (not authoritative billed output tokens),\n * so the per-frame deltas are summed across blocks instead.\n */\n estimatedThinkingTokens: number;\n};\n\ntype ClaudeToolUse = {\n id: string;\n name: string;\n input: unknown;\n parentToolUseId?: string | null;\n};\n\ntype ClaudeToolResult = {\n id: string;\n name?: string;\n result: unknown;\n isError: boolean;\n};\n\n// Provider extension for tool-error stream parts.\ntype ToolErrorPart = {\n type: 'tool-error';\n toolCallId: string;\n toolName: string;\n error: string;\n providerExecuted: true;\n dynamic: true;\n providerMetadata?: Record<string, JSONValue>;\n};\n\n// Local extension of the AI SDK stream part union to include tool-error.\ntype ExtendedStreamPart = LanguageModelV3StreamPart | ToolErrorPart;\n\n/**\n * `tool-result` part shape shared by doGenerate content and doStream parts.\n * The V3 type does not declare `providerExecuted` on tool results, but this\n * provider has always emitted it on the stream path; keep both paths aligned.\n */\ntype ProviderToolResultPart = LanguageModelV3ToolResult & { providerExecuted: true };\n\n/**\n * Ordered content collected by doGenerate, tagged with the originating\n * assistant message uuid so refusal-fallback `supersedes` retractions can\n * drop already-collected parts (text, thinking, AND tool calls) instead of\n * duplicating or orphaning them.\n */\ntype GenerateContentSegment =\n | { kind: 'text'; uuid?: string; text: string }\n | { kind: 'reasoning'; uuid?: string; text: string }\n | { kind: 'tool-call'; uuid?: string; toolCallId: string; part: LanguageModelV3ToolCall }\n | { kind: 'tool-result'; uuid?: string; toolCallId: string; part: ProviderToolResultPart }\n // tool_error blocks carry a V3 `tool-result` part with `isError: true`:\n // the V3 CONTENT union has no `tool-error` member and AI SDK core's\n // asContent() silently drops unknown part types, whereas an isError\n // tool-result round-trips into a proper tool-error content part visible\n // in generateText steps content. (doStream keeps the provider-extension\n // tool-error STREAM part, which AI SDK core handles natively.)\n | { kind: 'tool-error'; uuid?: string; toolCallId: string; part: ProviderToolResultPart };\n\ntype ContentBlock = { type: string; [key: string]: unknown };\n\nfunction isContentBlock(item: unknown): item is ContentBlock {\n return typeof item === 'object' && item !== null && 'type' in item;\n}\n\nfunction filterContentBlocks(content: unknown, type: string): ContentBlock[] {\n if (!Array.isArray(content)) return [];\n const blocks = content.filter(\n (item): item is ContentBlock => isContentBlock(item) && item.type === type\n );\n const mismatch = blocks.find((b) => b.type !== type);\n if (mismatch) {\n throw new Error(\n `filterContentBlocks: block type '${mismatch.type}' passed filter for '${type}'`\n );\n }\n return blocks;\n}\n\n/**\n * Usage data from Claude Code SDK.\n */\ntype ClaudeCodeUsage = {\n input_tokens?: number | null;\n output_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n};\n\n/**\n * Creates a zero-initialized usage object for AI SDK v6 stable.\n */\nfunction createEmptyUsage(): LanguageModelV3Usage {\n return {\n inputTokens: {\n total: 0,\n noCache: 0,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 0,\n text: undefined,\n reasoning: undefined,\n },\n raw: undefined,\n };\n}\n\n/**\n * Converts Claude Code SDK usage to AI SDK v6 stable usage format.\n *\n * Maps Claude's flat token counts to the nested structure required by AI SDK v6:\n * - `cache_creation_input_tokens` → `inputTokens.cacheWrite`\n * - `cache_read_input_tokens` → `inputTokens.cacheRead`\n * - `input_tokens` → `inputTokens.noCache`\n * - `inputTokens.total` = sum of all input tokens\n * - `output_tokens` → `outputTokens.total`\n *\n * @param usage - Raw usage data from Claude Code SDK\n * @returns Formatted usage object for AI SDK v6\n */\nfunction convertClaudeCodeUsage(usage: ClaudeCodeUsage): LanguageModelV3Usage {\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const cacheWrite = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n\n return {\n inputTokens: {\n total: inputTokens + cacheWrite + cacheRead,\n noCache: inputTokens,\n cacheRead,\n cacheWrite,\n },\n outputTokens: {\n total: outputTokens,\n text: undefined,\n reasoning: undefined,\n },\n raw: usage as JSONObject,\n };\n}\n\n/**\n * Tracks the streaming lifecycle state for a single tool invocation.\n *\n * The tool streaming lifecycle follows this sequence:\n * 1. Tool use detected → state created with all flags false\n * 2. First input seen → `inputStarted` = true, emit `tool-input-start`\n * 3. Input deltas streamed → emit `tool-input-delta` (may be skipped for large/non-prefix updates)\n * 4. Input finalized → `inputClosed` = true, emit `tool-input-end`\n * 5. Tool call formed → `callEmitted` = true, emit `tool-call`\n * 6. Tool results/errors arrive → emit `tool-result` or `tool-error` (may occur multiple times)\n * 7. Stream ends → state cleaned up by `finalizeToolCalls()`\n *\n * @property name - Tool name from SDK (e.g., \"Bash\", \"Read\")\n * @property lastSerializedInput - Most recent serialized input, used for delta calculation\n * @property inputStarted - True after `tool-input-start` emitted; prevents duplicate start events\n * @property inputClosed - True after `tool-input-end` emitted; ensures proper event ordering\n * @property callEmitted - True after `tool-call` emitted; prevents duplicate call events when\n * multiple result/error chunks arrive for the same tool invocation\n */\ntype ToolStreamState = {\n name: string;\n lastSerializedInput?: string;\n inputStarted: boolean;\n inputClosed: boolean;\n callEmitted: boolean;\n parentToolCallId?: string | null;\n /** Uuid of the assistant message this tool belongs to (for supersede retraction). */\n messageUuid?: string;\n};\n\n/**\n * Queued injection item with content and optional delivery callback.\n */\ntype QueuedInjection = {\n content: string;\n onResult?: (delivered: boolean) => void;\n};\n\n/**\n * Creates a MessageInjector implementation that can queue messages for mid-session injection.\n * The injector uses a queue and signals to coordinate between the producer (user code)\n * and consumer (async generator).\n *\n * Note: getNextItem returns the full QueuedInjection so the consumer can call onResult\n * AFTER successfully yielding, avoiding a race condition with outputStreamEnded.\n */\nfunction createMessageInjector(): {\n injector: MessageInjector;\n getNextItem: () => Promise<QueuedInjection | null>;\n notifySessionEnded: () => void;\n} {\n const queue: QueuedInjection[] = [];\n let closed = false;\n let resolver: ((item: QueuedInjection | null) => void) | null = null;\n\n const injector: MessageInjector = {\n inject(content, onResult) {\n if (closed) {\n // Already closed - immediately notify not delivered\n onResult?.(false);\n return;\n }\n const item: QueuedInjection = { content, onResult };\n if (resolver) {\n // Consumer is waiting, resolve immediately\n const r = resolver;\n resolver = null;\n r(item);\n } else {\n // Queue for later consumption\n queue.push(item);\n }\n },\n close() {\n // Stop accepting new messages, but don't cancel pending ones\n // Pending messages can still be delivered until session ends\n closed = true;\n if (resolver && queue.length === 0) {\n // No pending messages and consumer is waiting - signal done\n resolver(null);\n resolver = null;\n }\n },\n };\n\n const getNextItem = (): Promise<QueuedInjection | null> => {\n if (queue.length > 0) {\n const item = queue.shift();\n if (!item) {\n return Promise.resolve(null);\n }\n // Return the full item - caller is responsible for calling onResult after yielding\n return Promise.resolve(item);\n }\n if (closed) {\n // Closed and queue is empty - no more messages\n return Promise.resolve(null);\n }\n return new Promise((resolve) => {\n resolver = (item) => {\n // Return the full item (or null) - caller handles onResult\n resolve(item);\n };\n });\n };\n\n const notifySessionEnded = () => {\n // Session ended - any remaining queued messages won't be delivered\n for (const item of queue) {\n item.onResult?.(false);\n }\n queue.length = 0;\n closed = true;\n if (resolver) {\n resolver(null);\n resolver = null;\n }\n };\n\n return { injector, getNextItem, notifySessionEnded };\n}\n\nfunction toAsyncIterablePrompt(\n messagesPrompt: string,\n outputStreamEnded: Promise<unknown>,\n sessionId?: string,\n contentParts?: SDKUserMessage['message']['content'],\n onStreamStart?: (injector: MessageInjector) => void\n): AsyncIterable<SDKUserMessage> {\n const content = (\n contentParts && contentParts.length > 0\n ? contentParts\n : [{ type: 'text', text: messagesPrompt }]\n ) as SDKUserMessage['message']['content'];\n\n const initialMsg: SDKUserMessage = {\n type: 'user',\n message: {\n role: 'user',\n content,\n },\n parent_tool_use_id: null,\n session_id: sessionId ?? '',\n };\n\n // If no callback, use simple behavior (backwards compatible)\n if (!onStreamStart) {\n return {\n async *[Symbol.asyncIterator]() {\n yield initialMsg;\n await outputStreamEnded;\n },\n };\n }\n\n // With injection support: create injector and yield messages as they arrive\n const { injector, getNextItem, notifySessionEnded } = createMessageInjector();\n\n return {\n async *[Symbol.asyncIterator]() {\n // Yield initial message\n yield initialMsg;\n\n // Notify consumer that streaming has started\n onStreamStart(injector);\n\n // Race between output ending and new messages arriving\n let streamEnded = false;\n void outputStreamEnded.then(() => {\n streamEnded = true;\n // Notify any pending injections that the session ended\n notifySessionEnded();\n });\n\n // Keep yielding injected messages until stream ends or injector closes\n while (!streamEnded) {\n // Race getNextItem against outputStreamEnded\n // We get the full item so we can call onResult AFTER yielding\n const item = await Promise.race([getNextItem(), outputStreamEnded.then(() => null)]);\n\n if (item === null) {\n // Ensure we don't close the input stream prematurely.\n // Wait for output to complete to avoid truncation issues.\n await outputStreamEnded;\n break;\n }\n\n const sdkMsg: SDKUserMessage = {\n type: 'user',\n message: {\n role: 'user',\n content: [{ type: 'text', text: item.content }],\n },\n parent_tool_use_id: null,\n session_id: sessionId ?? '',\n };\n yield sdkMsg;\n\n // Only report delivery AFTER successfully yielding\n item.onResult?.(true);\n }\n },\n };\n}\n\n/**\n * Options for creating a Claude Code language model instance.\n *\n * @example\n * ```typescript\n * const model = new ClaudeCodeLanguageModel({\n * id: 'opus',\n * settings: {\n * maxTurns: 10,\n * permissionMode: 'auto'\n * }\n * });\n * ```\n */\nexport interface ClaudeCodeLanguageModelOptions {\n /**\n * The model identifier to use.\n * Can be 'opus', 'sonnet', 'haiku', or a custom model string.\n */\n id: ClaudeCodeModelId;\n\n /**\n * Optional settings to configure the model behavior.\n */\n settings?: ClaudeCodeSettings;\n\n /**\n * Validation warnings from settings validation.\n * Used internally to pass warnings from provider.\n */\n settingsValidationWarnings?: string[];\n}\n\n/**\n * Supported Claude model identifiers.\n * - 'opus': Claude Opus (most capable)\n * - 'sonnet': Claude Sonnet (balanced performance)\n * - 'haiku': Claude Haiku (fastest, most cost-effective)\n * - Custom string: Any full model identifier (e.g., 'claude-opus-4-5', 'claude-sonnet-4-5-20250514')\n *\n * @example\n * ```typescript\n * const opusModel = claudeCode('opus');\n * const sonnetModel = claudeCode('sonnet');\n * const haikuModel = claudeCode('haiku');\n * const customModel = claudeCode('claude-opus-4-5');\n * ```\n */\nexport type ClaudeCodeModelId = 'opus' | 'sonnet' | 'haiku' | (string & {});\n\nconst modelMap: Record<string, string> = {\n opus: 'opus',\n sonnet: 'sonnet',\n haiku: 'haiku',\n};\n\n/**\n * Maximum size for tool results sent to the client stream.\n * Interior Claude Code process has full data; this only affects client stream.\n */\nconst MAX_TOOL_RESULT_SIZE = 10000;\n\n/**\n * Truncates large tool results to prevent stream bloat.\n * Only the largest string value in an object/array is truncated.\n * Preserves the original type (array stays array, object stays object).\n */\nfunction truncateToolResultForStream(\n result: unknown,\n maxSize: number = MAX_TOOL_RESULT_SIZE\n): unknown {\n if (typeof result === 'string') {\n if (result.length <= maxSize) return result;\n return result.slice(0, maxSize) + `\\n...[truncated ${result.length - maxSize} chars]`;\n }\n\n if (typeof result !== 'object' || result === null) return result;\n\n // Handle arrays separately to preserve array type\n if (Array.isArray(result)) {\n let largestIndex = -1;\n let largestSize = 0;\n\n for (let i = 0; i < result.length; i++) {\n const value = result[i];\n if (typeof value === 'string' && value.length > largestSize) {\n largestIndex = i;\n largestSize = value.length;\n }\n }\n\n if (largestIndex >= 0 && largestSize > maxSize) {\n const truncatedValue =\n (result[largestIndex] as string).slice(0, maxSize) +\n `\\n...[truncated ${largestSize - maxSize} chars]`;\n const cloned = [...result];\n cloned[largestIndex] = truncatedValue;\n return cloned;\n }\n\n return result;\n }\n\n // For objects, find and truncate only the largest string value\n const obj = result as Record<string, unknown>;\n let largestKey: string | null = null;\n let largestSize = 0;\n\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string' && value.length > largestSize) {\n largestKey = key;\n largestSize = value.length;\n }\n }\n\n if (largestKey && largestSize > maxSize) {\n const truncatedValue =\n (obj[largestKey] as string).slice(0, maxSize) +\n `\\n...[truncated ${largestSize - maxSize} chars]`;\n return { ...obj, [largestKey]: truncatedValue };\n }\n\n return result;\n}\n\n/**\n * Language model implementation for Claude Code SDK.\n * This class implements the AI SDK's LanguageModelV3 interface to provide\n * integration with Claude models through the Claude Agent SDK.\n *\n * Features:\n * - Supports streaming and non-streaming generation\n * - Native structured outputs via SDK's outputFormat (guaranteed schema compliance)\n * - Manages CLI sessions for conversation continuity\n * - Provides detailed error handling and retry logic\n *\n * Limitations:\n * - Image inputs require streaming mode\n * - Some parameters like temperature and max tokens are not supported by the CLI\n *\n * @example\n * ```typescript\n * const model = new ClaudeCodeLanguageModel({\n * id: 'opus',\n * settings: { maxTurns: 5 }\n * });\n *\n * const result = await model.doGenerate({\n * prompt: [{ role: 'user', content: 'Hello!' }],\n * mode: { type: 'regular' }\n * });\n * ```\n */\n\nexport class ClaudeCodeLanguageModel implements LanguageModelV3 {\n readonly specificationVersion = 'v3' as const;\n readonly defaultObjectGenerationMode = 'json' as const;\n readonly supportsImageUrls = false;\n readonly supportedUrls = {};\n readonly supportsStructuredOutputs = true;\n\n // Fallback/magic string constants\n static readonly UNKNOWN_TOOL_NAME = 'unknown-tool';\n\n // Tool input safety limits\n private static readonly MAX_TOOL_INPUT_SIZE = 1_048_576; // 1MB hard limit\n private static readonly MAX_TOOL_INPUT_WARN = 102_400; // 100KB warning threshold\n private static readonly MAX_DELTA_CALC_SIZE = 10_000; // 10KB delta computation threshold\n\n // Upper bound for draining post-result messages (prompt_suggestion) so a\n // lingering CLI subprocess cannot be held open indefinitely after finish.\n private static readonly PROMPT_SUGGESTION_DRAIN_TIMEOUT_MS = 10_000;\n\n readonly modelId: ClaudeCodeModelId;\n readonly settings: ClaudeCodeSettings;\n\n private sessionId?: string;\n private modelValidationWarning?: string;\n private settingsValidationWarnings: string[];\n private logger: Logger;\n\n constructor(options: ClaudeCodeLanguageModelOptions) {\n this.modelId = options.id;\n this.settings = options.settings ?? {};\n this.settingsValidationWarnings = options.settingsValidationWarnings ?? [];\n\n // Create logger that respects verbose setting\n const baseLogger = getLogger(this.settings.logger);\n this.logger = createVerboseLogger(baseLogger, this.settings.verbose ?? false);\n\n // Validate model ID format\n if (!this.modelId || typeof this.modelId !== 'string' || this.modelId.trim() === '') {\n throw new NoSuchModelError({\n modelId: this.modelId,\n modelType: 'languageModel',\n });\n }\n\n // Additional model ID validation\n this.modelValidationWarning = validateModelId(this.modelId);\n if (this.modelValidationWarning) {\n this.logger.warn(`Claude Code Model: ${this.modelValidationWarning}`);\n }\n }\n\n get provider(): string {\n return 'claude-code';\n }\n\n private getModel(): string {\n const mapped = modelMap[this.modelId];\n return mapped ?? this.modelId;\n }\n\n private getSanitizedSdkOptions(): Partial<Options> | undefined {\n if (!this.settings.sdkOptions || typeof this.settings.sdkOptions !== 'object') {\n return undefined;\n }\n\n const sanitized = { ...(this.settings.sdkOptions as Record<string, unknown>) };\n const blockedKeys = Array.from(SDK_OPTIONS_BLOCKLIST).filter((key) => key in sanitized);\n\n if (blockedKeys.length > 0) {\n this.logger.warn(\n `[claude-code] sdkOptions includes provider-managed fields (${blockedKeys.join(\n ', '\n )}); these will be ignored.`\n );\n blockedKeys.forEach((key) => delete sanitized[key]);\n }\n\n return sanitized as Partial<Options>;\n }\n\n private getEffectiveResume(sdkOptions?: Partial<Options>): string | undefined {\n // The SDK treats a blank/whitespace resume id as absent, so skip blanks\n // rather than letting one shadow a real later candidate or reach the CLI\n // as `--resume ''`.\n for (const candidate of [sdkOptions?.resume, this.settings.resume, this.sessionId]) {\n if (typeof candidate === 'string' && !isBlankResume(candidate)) {\n return candidate;\n }\n }\n return undefined;\n }\n\n /**\n * Single source of truth for the CLI's `--session-id` exclusivity rule.\n *\n * The CLI rejects `--session-id` together with `--resume`/`--continue`\n * unless `--fork-session` is also set (forkSession then names the forked\n * session's own ID). This predicate captures \"there IS a resume/continue\n * target AND we are not forking\", i.e. the case where a session id must NOT\n * coexist. It is referenced by both:\n * - the pre-merge forwarding guard (via its inverse), which decides whether\n * to forward `settings.sessionId` onto the base options, and\n * - the post-merge exclusivity drop, which removes any session id that the\n * generic sdkOptions overlay (or the auto-resume turn) re-introduced.\n *\n * Keeping one definition guarantees both sites agree on what \"conflicts with\n * a session id\" means. The mirror in validation.ts (construction-time)\n * intentionally stays separate: it reads settings+sdkOptions, not a built\n * opts object.\n */\n private static sessionIdConflictsWithResumeOrContinue(args: {\n resumePresent: boolean;\n continue: boolean;\n forkSession: boolean;\n }): boolean {\n return (args.resumePresent || args.continue) && !args.forkSession;\n }\n\n /**\n * Owns ALL session-id / resume cross-option resolution on the FINAL merged\n * options, in the single correct order. Called once, immediately after the\n * generic sdkOptions overlay in createQueryOptions.\n *\n * Two concerns, in this exact order (order matters: step 1 can change whether\n * step 2 sees a resume target):\n *\n * 1. Blank-resume restoration. The overlay copies the raw `sdkOptions.resume`\n * verbatim, which can re-introduce a blank/whitespace value over the\n * base `resume` that getEffectiveResume already normalized. The SDK treats\n * a blank resume as absent, so a blank must NOT clobber the computed\n * fallback — restore `effectiveResume` (already blank-stripped; may itself\n * be undefined for a genuinely new session) rather than leaving '' or\n * forcing undefined, which would erase a real settings.resume / captured\n * session id.\n *\n * 2. Session-id exclusivity. Drop `opts.sessionId` whenever it conflicts with\n * a resume/continue target (see sessionIdConflictsWithResumeOrContinue).\n * This runs on the merged opts so it catches a sessionId re-added by the\n * sdkOptions overlay AND the auto-resumed second turn (where resume was\n * populated from the captured session id). It complements — does not\n * replace — the pre-merge forwarding guard, which governs whether\n * settings.sessionId was forwarded BEFORE the overlay could mutate\n * forkSession/continue/resume.\n */\n private applySessionResolution(\n opts: Partial<Options> & Record<string, unknown>,\n effectiveResume?: string\n ): void {\n // Step 1: restore blank-stripped resume (see doc comment).\n if (isBlankResume(opts.resume)) {\n opts.resume = effectiveResume;\n }\n\n // Step 2: enforce --session-id exclusivity on the merged opts.\n if (\n opts.sessionId !== undefined &&\n ClaudeCodeLanguageModel.sessionIdConflictsWithResumeOrContinue({\n resumePresent: opts.resume !== undefined,\n continue: opts.continue === true,\n forkSession: opts.forkSession === true,\n })\n ) {\n opts.sessionId = undefined;\n }\n }\n\n private extractToolUses(content: unknown): ClaudeToolUse[] {\n return filterContentBlocks(content, 'tool_use').map((block) => {\n const { id, name, input, parent_tool_use_id } = block as {\n id?: unknown;\n name?: unknown;\n input?: unknown;\n parent_tool_use_id?: unknown;\n };\n return {\n id: typeof id === 'string' && id.length > 0 ? id : generateId(),\n name:\n typeof name === 'string' && name.length > 0\n ? name\n : ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME,\n input,\n parentToolUseId: typeof parent_tool_use_id === 'string' ? parent_tool_use_id : null,\n } satisfies ClaudeToolUse;\n });\n }\n\n private extractToolResults(content: unknown): ClaudeToolResult[] {\n return filterContentBlocks(content, 'tool_result').map((block) => {\n const { tool_use_id, content, is_error, name } = block as {\n tool_use_id?: unknown;\n content?: unknown;\n is_error?: unknown;\n name?: unknown;\n };\n return {\n id: typeof tool_use_id === 'string' && tool_use_id.length > 0 ? tool_use_id : generateId(),\n name: typeof name === 'string' && name.length > 0 ? name : undefined,\n result: content,\n isError: Boolean(is_error),\n } satisfies ClaudeToolResult;\n });\n }\n\n private extractToolErrors(content: unknown): Array<{\n id: string;\n name?: string;\n error: unknown;\n }> {\n return filterContentBlocks(content, 'tool_error').map((block) => {\n const { tool_use_id, error, name } = block as {\n tool_use_id?: unknown;\n error?: unknown;\n name?: unknown;\n };\n return {\n id: typeof tool_use_id === 'string' && tool_use_id.length > 0 ? tool_use_id : generateId(),\n name: typeof name === 'string' && name.length > 0 ? name : undefined,\n error,\n };\n });\n }\n\n private serializeToolInput(input: unknown): string {\n if (typeof input === 'string') {\n return this.checkInputSize(input);\n }\n\n if (input === undefined) {\n return '';\n }\n\n try {\n const serialized = JSON.stringify(input);\n return this.checkInputSize(serialized);\n } catch {\n const fallback = String(input);\n return this.checkInputSize(fallback);\n }\n }\n\n private checkInputSize(str: string): string {\n const length = str.length;\n\n if (length > ClaudeCodeLanguageModel.MAX_TOOL_INPUT_SIZE) {\n throw new Error(\n `Tool input exceeds maximum size of ${ClaudeCodeLanguageModel.MAX_TOOL_INPUT_SIZE} bytes (got ${length} bytes). This may indicate a malformed request or an attempt to process excessively large data.`\n );\n }\n\n if (length > ClaudeCodeLanguageModel.MAX_TOOL_INPUT_WARN) {\n this.logger.warn(\n `[claude-code] Large tool input detected: ${length} bytes. Performance may be impacted. Consider chunking or reducing input size.`\n );\n }\n\n return str;\n }\n\n private normalizeToolResult(result: unknown): unknown {\n if (typeof result === 'string') {\n try {\n return JSON.parse(result);\n } catch {\n return result;\n }\n }\n // Handle MCP content format: [{type: 'text', text: '...'}, ...]\n // MCP tools can return multiple content blocks; only normalize when all blocks are text.\n if (Array.isArray(result) && result.length > 0) {\n // Collect all text content from text blocks\n const textBlocks = result\n .filter(\n (block): block is { type: 'text'; text: string } =>\n block?.type === 'text' && typeof block.text === 'string'\n )\n .map((block) => block.text);\n\n if (textBlocks.length !== result.length) {\n return result;\n }\n\n // If single text block, try to parse as JSON\n if (textBlocks.length === 1) {\n try {\n return JSON.parse(textBlocks[0]);\n } catch {\n return textBlocks[0];\n }\n }\n\n // Multiple text blocks: join them and try to parse as JSON\n const combined = textBlocks.join('\\n');\n try {\n return JSON.parse(combined);\n } catch {\n return combined;\n }\n }\n\n return result;\n }\n\n /**\n * Builds a provider-executed `tool-call` part from an assistant `tool_use`\n * block. Shared by doGenerate (content part) and doStream (stream part) so\n * the two paths cannot drift in field shape.\n */\n private buildToolCallPart(\n toolCallId: string,\n toolName: string,\n input: string,\n parentToolCallId: string | null | undefined\n ): LanguageModelV3ToolCall {\n return {\n type: 'tool-call',\n toolCallId,\n toolName,\n input,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined (not in user's tools map)\n providerMetadata: {\n 'claude-code': {\n // rawInput preserves the original serialized format before AI SDK normalization.\n // Use this if you need the exact string sent to the Claude CLI, which may differ\n // from the `input` field after AI SDK processing.\n rawInput: input,\n parentToolCallId: parentToolCallId ?? null,\n },\n },\n };\n }\n\n /**\n * Builds a provider-executed `tool-result` part from a user-message\n * `tool_result` block, applying normalization and `maxToolResultSize`\n * truncation. Shared by doGenerate and doStream.\n */\n private buildToolResultPart(\n toolCallId: string,\n toolName: string,\n result: unknown,\n isError: boolean,\n parentToolCallId: string | null | undefined\n ): ProviderToolResultPart {\n const normalizedResult = this.normalizeToolResult(result);\n const rawResult =\n typeof result === 'string'\n ? result\n : result === undefined\n ? // tool_result blocks may omit `content` entirely; '' keeps both\n // `result` (NonNullable<JSONValue>) and rawResult (JSONValue) valid.\n ''\n : (() => {\n try {\n // JSON.stringify returns undefined (not a string) for\n // non-serializable values such as functions or symbols.\n return JSON.stringify(result) ?? String(result);\n } catch {\n return String(result);\n }\n })();\n const maxToolResultSize = this.settings.maxToolResultSize;\n const truncatedResult = truncateToolResultForStream(normalizedResult, maxToolResultSize);\n const truncatedRawResult = truncateToolResultForStream(rawResult, maxToolResultSize) as string;\n const rawResultTruncated = truncatedRawResult !== rawResult;\n\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n // `?? ''`: absent `content` (undefined) and string results that\n // normalize to JSON null (e.g. the string \"null\") must not violate the\n // NonNullable<JSONValue> contract of LanguageModelV3ToolResult.result.\n result: (truncatedResult ?? '') as NonNullable<JSONValue>,\n isError,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n // rawResult preserves the original CLI output string before JSON parsing.\n // Use this when you need the exact string returned by the tool, especially\n // if the `result` field has been parsed/normalized and you need the original format.\n rawResult: truncatedRawResult,\n rawResultTruncated,\n parentToolCallId: parentToolCallId ?? null,\n },\n },\n };\n }\n\n private serializeToolError(error: unknown): string {\n return typeof error === 'string'\n ? error\n : typeof error === 'object' && error !== null\n ? (() => {\n try {\n return JSON.stringify(error) ?? String(error);\n } catch {\n return String(error);\n }\n })()\n : String(error);\n }\n\n /**\n * Builds a provider-executed `tool-error` STREAM part from a user-message\n * `tool_error` block (doStream only; AI SDK core handles tool-error stream\n * parts natively).\n */\n private buildToolErrorPart(\n toolCallId: string,\n toolName: string,\n error: unknown,\n parentToolCallId: string | null | undefined\n ): ToolErrorPart {\n const rawError = this.serializeToolError(error);\n\n return {\n type: 'tool-error',\n toolCallId,\n toolName,\n error: rawError,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n rawError,\n parentToolCallId: parentToolCallId ?? null,\n },\n },\n };\n }\n\n /**\n * Builds a V3 `tool-result` CONTENT part with `isError: true` from a\n * user-message `tool_error` block (doGenerate only). The V3 content union\n * has no `tool-error` member and AI SDK core's asContent() silently drops\n * unknown content part types, so an extension tool-error part would never\n * reach `generateText` users — an isError tool-result, by contrast,\n * round-trips into a proper tool-error part in steps content.\n */\n private buildToolErrorResultPart(\n toolCallId: string,\n toolName: string,\n error: unknown,\n parentToolCallId: string | null | undefined\n ): ProviderToolResultPart {\n const rawError = this.serializeToolError(error);\n\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n result: rawError,\n isError: true,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n rawError,\n parentToolCallId: parentToolCallId ?? null,\n },\n },\n };\n }\n\n /**\n * Policy (P3): late-frame drop guard, shared by all four tool_result/tool_error\n * sites (doGenerate result+error, doStream result+error). When a frame's tool\n * id is tombstoned (its tool-call was retracted by a supersede/refusal-fallback\n * signal), the frame must be DROPPED rather than re-synthesized into an orphan\n * tool-call. Centralizing the predicate + debug message keeps the four sites in\n * lockstep so a future tombstone change can't be applied to only some of them.\n */\n private isRetractedToolFrame(\n id: string,\n tombstone: Set<string>,\n frameKind: 'result' | 'error'\n ): boolean {\n if (!tombstone.has(id)) {\n return false;\n }\n this.logger.debug(\n `[claude-code] Dropping tool ${frameKind} for retracted (superseded) tool ID: ${id}`\n );\n return true;\n }\n\n private generateAllWarnings(\n options:\n | Parameters<LanguageModelV3['doGenerate']>[0]\n | Parameters<LanguageModelV3['doStream']>[0],\n prompt: string\n ): SharedV3Warning[] {\n const warnings: SharedV3Warning[] = [];\n const unsupportedParams: string[] = [];\n\n // Check for unsupported parameters\n if (options.temperature !== undefined) unsupportedParams.push('temperature');\n if (options.topP !== undefined) unsupportedParams.push('topP');\n if (options.topK !== undefined) unsupportedParams.push('topK');\n if (options.presencePenalty !== undefined) unsupportedParams.push('presencePenalty');\n if (options.frequencyPenalty !== undefined) unsupportedParams.push('frequencyPenalty');\n if (options.stopSequences !== undefined && options.stopSequences.length > 0)\n unsupportedParams.push('stopSequences');\n if (options.seed !== undefined) unsupportedParams.push('seed');\n\n if (unsupportedParams.length > 0) {\n // Add a warning for each unsupported parameter\n for (const param of unsupportedParams) {\n warnings.push({\n type: 'unsupported',\n feature: param,\n details: `Claude Code SDK does not support the ${param} parameter. It will be ignored.`,\n });\n }\n }\n\n // AI SDK tool definitions cannot be auto-bridged: the Claude Code CLI\n // executes its own tools, and at the provider layer `options.tools` only\n // carries declarations (the execute functions never reach the provider).\n if (options.tools !== undefined && options.tools.length > 0) {\n warnings.push({\n type: 'unsupported',\n feature: 'tools',\n details:\n 'The Claude Code CLI executes its own tools; AI SDK tools cannot be auto-bridged at the provider layer and will be ignored. To expose custom tools to the CLI, build an in-process MCP server with the createAiSdkMcpServer helper (exported by this package) and pass it via the mcpServers setting (plus allowedTools).',\n });\n }\n\n if (options.toolChoice !== undefined && options.toolChoice.type !== 'auto') {\n warnings.push({\n type: 'unsupported',\n feature: 'toolChoice',\n details: `Claude Code CLI does not support toolChoice '${options.toolChoice.type}'. Only automatic tool selection is available; the toolChoice parameter will be ignored.`,\n });\n }\n\n if (options.maxOutputTokens !== undefined) {\n warnings.push({\n type: 'unsupported',\n feature: 'maxOutputTokens',\n details:\n 'Claude Code CLI does not accept an output token cap. The maxOutputTokens parameter will be ignored.',\n });\n }\n\n // Add model validation warning if present\n if (this.modelValidationWarning) {\n warnings.push({\n type: 'other',\n message: this.modelValidationWarning,\n });\n }\n\n // Add settings validation warnings\n this.settingsValidationWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n\n // Warn if JSON response format is requested without a schema\n // Claude Code only supports structured outputs with schemas (like Anthropic's API)\n if (options.responseFormat?.type === 'json' && !options.responseFormat.schema) {\n warnings.push({\n type: 'unsupported',\n feature: 'responseFormat',\n details:\n 'JSON response format requires a schema for the Claude Code provider. The JSON responseFormat is ignored and the call is treated as plain text.',\n });\n }\n\n // Validate prompt\n const promptWarning = validatePrompt(prompt);\n if (promptWarning) {\n warnings.push({\n type: 'other',\n message: promptWarning,\n });\n }\n\n return warnings;\n }\n\n private createQueryOptions(\n abortController: AbortController,\n responseFormat?: Parameters<LanguageModelV3['doGenerate']>[0]['responseFormat'],\n stderrCollector?: (data: string) => void,\n sdkOptions?: Partial<Options>,\n effectiveResume?: string\n ): Options {\n const opts: Partial<Options> & Record<string, unknown> = {\n model: this.getModel(),\n abortController,\n resume: effectiveResume,\n pathToClaudeCodeExecutable: this.settings.pathToClaudeCodeExecutable,\n maxTurns: this.settings.maxTurns,\n maxThinkingTokens: this.settings.maxThinkingTokens,\n thinking: this.settings.thinking,\n effort: this.settings.effort,\n promptSuggestions: this.settings.promptSuggestions,\n cwd: this.settings.cwd,\n executable: this.settings.executable,\n executableArgs: this.settings.executableArgs,\n permissionMode: this.settings.permissionMode,\n permissionPromptToolName: this.settings.permissionPromptToolName,\n continue: this.settings.continue,\n allowedTools: this.settings.allowedTools,\n disallowedTools: this.settings.disallowedTools,\n betas: this.settings.betas,\n allowDangerouslySkipPermissions: this.settings.allowDangerouslySkipPermissions,\n enableFileCheckpointing: this.settings.enableFileCheckpointing,\n maxBudgetUsd: this.settings.maxBudgetUsd,\n plugins: this.settings.plugins,\n resumeSessionAt: this.settings.resumeSessionAt,\n sandbox: this.settings.sandbox,\n tools: this.settings.tools,\n mcpServers: this.settings.mcpServers,\n canUseTool: this.settings.canUseTool,\n };\n // Blocking user-dialog handling (SDK fails closed without these: the CLI\n // never emits a dialog kind that is not declared in supportedDialogKinds,\n // and the dialog-gated flow degrades to its no-dialog behavior).\n if (this.settings.onUserDialog !== undefined) {\n opts.onUserDialog = this.settings.onUserDialog;\n }\n if (this.settings.supportedDialogKinds !== undefined) {\n opts.supportedDialogKinds = this.settings.supportedDialogKinds;\n }\n // NEW: Agent SDK options with legacy mapping\n if (this.settings.systemPrompt !== undefined) {\n opts.systemPrompt = this.settings.systemPrompt;\n } else if (this.settings.customSystemPrompt !== undefined) {\n // Deprecation warning for legacy field\n this.logger.warn(\n \"[claude-code] 'customSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt' instead (string or { type: 'preset', preset: 'claude_code', append? }).\"\n );\n opts.systemPrompt = this.settings.customSystemPrompt;\n } else if (this.settings.appendSystemPrompt !== undefined) {\n // Deprecation warning for legacy field\n this.logger.warn(\n \"[claude-code] 'appendSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt: { type: 'preset', preset: 'claude_code', append: <text> }' instead.\"\n );\n opts.systemPrompt = {\n type: 'preset',\n preset: 'claude_code',\n append: this.settings.appendSystemPrompt,\n } as const;\n }\n if (this.settings.settingSources !== undefined) {\n opts.settingSources = this.settings.settingSources;\n } else {\n // SDK 0.3.x flipped the default: omitting settingSources now loads ALL\n // filesystem settings (CLI behavior). Pin to [] to preserve the provider's\n // documented isolation default. Users can opt in via settings.settingSources\n // or override through sdkOptions (applied after this block).\n opts.settingSources = [];\n }\n if (this.settings.additionalDirectories !== undefined) {\n opts.additionalDirectories = this.settings.additionalDirectories;\n }\n if (this.settings.agents !== undefined) {\n opts.agents = this.settings.agents;\n }\n if (this.settings.skills !== undefined) {\n opts.skills = this.settings.skills;\n }\n if (this.settings.settings !== undefined) {\n opts.settings = this.settings.settings;\n }\n if (this.settings.managedSettings !== undefined) {\n opts.managedSettings = this.settings.managedSettings;\n }\n if (this.settings.toolAliases !== undefined) {\n opts.toolAliases = this.settings.toolAliases;\n }\n if (this.settings.toolConfig !== undefined) {\n opts.toolConfig = this.settings.toolConfig;\n }\n if (this.settings.planModeInstructions !== undefined) {\n opts.planModeInstructions = this.settings.planModeInstructions;\n }\n if (this.settings.title !== undefined) {\n opts.title = this.settings.title;\n }\n if (this.settings.forwardSubagentText !== undefined) {\n opts.forwardSubagentText = this.settings.forwardSubagentText;\n }\n if (this.settings.agentProgressSummaries !== undefined) {\n opts.agentProgressSummaries = this.settings.agentProgressSummaries;\n }\n if (this.settings.includeHookEvents !== undefined) {\n opts.includeHookEvents = this.settings.includeHookEvents;\n }\n // Alpha Agent SDK options (subject to upstream change)\n if (this.settings.taskBudget !== undefined) {\n opts.taskBudget = this.settings.taskBudget;\n }\n if (this.settings.sessionStore !== undefined) {\n opts.sessionStore = this.settings.sessionStore;\n }\n if (this.settings.sessionStoreFlush !== undefined) {\n opts.sessionStoreFlush = this.settings.sessionStoreFlush;\n }\n if (this.settings.loadTimeoutMs !== undefined) {\n opts.loadTimeoutMs = this.settings.loadTimeoutMs;\n }\n if (this.settings.includePartialMessages !== undefined) {\n opts.includePartialMessages = this.settings.includePartialMessages;\n }\n if (this.settings.fallbackModel !== undefined) {\n opts.fallbackModel = this.settings.fallbackModel;\n }\n if (this.settings.forkSession !== undefined) {\n opts.forkSession = this.settings.forkSession;\n }\n if (this.settings.strictMcpConfig !== undefined) {\n opts.strictMcpConfig = this.settings.strictMcpConfig;\n }\n if (this.settings.extraArgs !== undefined) {\n opts.extraArgs = this.settings.extraArgs;\n }\n if (this.settings.persistSession !== undefined) {\n opts.persistSession = this.settings.persistSession;\n }\n if (this.settings.spawnClaudeCodeProcess !== undefined) {\n opts.spawnClaudeCodeProcess = this.settings.spawnClaudeCodeProcess;\n }\n // hooks is supported in newer SDKs; include it if provided\n if (this.settings.hooks) {\n opts.hooks = this.settings.hooks;\n }\n // The CLI rejects --session-id combined with --resume/--continue unless\n // --fork-session is also set. On multi-turn conversations the provider\n // auto-resumes via the captured session ID (which already IS the custom\n // ID), so only forward sessionId while no resume/continue target exists —\n // or when the user opted into forking (sessionId then names the fork's\n // ID). forkSession and continue may arrive via the sdkOptions escape\n // hatch (merged below, after this decision), so honor the effective\n // values here. (opts.resume already reflects sdkOptions.resume via\n // effectiveResume.)\n // Read the EFFECTIVE fork/continue values (sdkOptions override settings via\n // `??`, so an explicit `sdkOptions.forkSession: false` correctly overrides\n // `settings.forkSession: true`). opts.resume already reflects sdkOptions via\n // effectiveResume. Forward settings.sessionId only when it would NOT conflict\n // with a resume/continue target — i.e. the inverse of the same exclusivity\n // predicate the post-merge drop uses, so the rule has one textual home.\n const effectiveForkSession = sdkOptions?.forkSession ?? this.settings.forkSession;\n const effectiveContinue = sdkOptions?.continue ?? this.settings.continue;\n if (\n this.settings.sessionId !== undefined &&\n !ClaudeCodeLanguageModel.sessionIdConflictsWithResumeOrContinue({\n resumePresent: opts.resume !== undefined,\n continue: effectiveContinue === true,\n forkSession: effectiveForkSession === true,\n })\n ) {\n opts.sessionId = this.settings.sessionId;\n }\n if (this.settings.debug !== undefined) {\n opts.debug = this.settings.debug;\n }\n if (this.settings.debugFile !== undefined) {\n opts.debugFile = this.settings.debugFile;\n }\n\n const sdkOverrides = sdkOptions\n ? (sdkOptions as Partial<Options> & Record<string, unknown>)\n : undefined;\n const sdkEnv =\n sdkOverrides && typeof sdkOverrides.env === 'object' && sdkOverrides.env !== null\n ? (sdkOverrides.env as Record<string, string | undefined>)\n : undefined;\n const sdkStderr =\n sdkOverrides && typeof sdkOverrides.stderr === 'function'\n ? (sdkOverrides.stderr as (data: string) => void)\n : undefined;\n if (sdkOverrides) {\n const rest = { ...sdkOverrides };\n delete rest.env;\n delete rest.stderr;\n // Skip undefined-valued keys: conditionally-built sdkOptions (e.g.\n // `{ settingSources: maybeSources }` with maybeSources === undefined) must\n // not clobber pinned defaults. On SDK 0.3.x an undefined settingSources\n // loads ALL filesystem settings, silently defeating the isolation default.\n for (const [key, value] of Object.entries(rest)) {\n if (value !== undefined) {\n opts[key] = value;\n }\n }\n }\n\n // Resolve all session-id / resume cross-option rules on the FINAL merged\n // options: blank-resume restoration then --session-id exclusivity, in that\n // order. See applySessionResolution for the full rationale.\n this.applySessionResolution(opts, effectiveResume);\n\n // SDK constraint: fallbackModel must differ from the main model (the SDK\n // throws while building CLI args at query time). Reject early with\n // guidance instead. Mirrors the SDK's naive string equality check.\n if (typeof opts.fallbackModel === 'string' && opts.fallbackModel === opts.model) {\n throw new Error(\n `fallbackModel cannot be the same as the model ('${String(opts.model)}'). Specify a different model for fallbackModel, or remove it.`\n );\n }\n\n // Wrap stderr callback to also collect data for error reporting\n const userStderrCallback = sdkStderr ?? this.settings.stderr;\n if (stderrCollector || userStderrCallback) {\n opts.stderr = (data: string) => {\n if (stderrCollector) stderrCollector(data);\n if (userStderrCallback) userStderrCallback(data);\n };\n }\n\n // SDK 0.3.x: Options.env REPLACES the subprocess environment entirely (0.2.x\n // effectively merged with process.env). The provider always constructs the full\n // environment from a sanitizing allowlist so behavior is deterministic.\n // Merge order: allowlisted process env, then settings.env, then sdkOptions.env\n // (user values win; explicit `undefined` removes a variable).\n const mergedEnv: Record<string, string | undefined> = {\n ...getBaseProcessEnv(),\n ...this.settings.env,\n ...sdkEnv,\n };\n // Identify this provider to the SDK (User-Agent) unless already set via\n // process env (inherited above), settings.env, or sdkOptions.env.\n if (!('CLAUDE_AGENT_SDK_CLIENT_APP' in mergedEnv)) {\n mergedEnv.CLAUDE_AGENT_SDK_CLIENT_APP = DEFAULT_CLIENT_APP;\n }\n opts.env = mergedEnv;\n\n // Native structured outputs (SDK 0.1.45+). The schema is sanitized first:\n // the CLI silently drops structured_output entirely when the schema\n // contains `format` keywords (date-time, email, uri, uuid, ...), so they\n // are stripped client-side with the hint folded into descriptions. This\n // loses nothing: generateObject/streamObject validate against the user's\n // original Zod schema client-side, so .email()/.datetime() enforcement is\n // preserved.\n if (responseFormat?.type === 'json' && responseFormat.schema) {\n const { schema: sanitizedSchema, strippedFormatPaths } = sanitizeJsonSchemaForOutputFormat(\n responseFormat.schema as Record<string, unknown>\n );\n if (strippedFormatPaths.length > 0) {\n this.logger.debug(\n `[claude-code] Stripped unsupported 'format' keywords from outputFormat schema (hints folded into descriptions; client-side Zod validation still enforces them) at: ${strippedFormatPaths.join(', ')}`\n );\n }\n opts.outputFormat = {\n type: 'json_schema',\n schema: sanitizedSchema,\n };\n }\n\n return opts as Options;\n }\n\n private handleClaudeCodeError(\n error: unknown,\n messagesPrompt: string,\n collectedStderr?: string\n ): APICallError | LoadAPIKeyError {\n // Handle AbortError from the SDK\n if (isAbortError(error)) {\n // Return the abort reason if available, otherwise the error itself\n throw error;\n }\n\n // Already-classified provider errors (e.g. the missing-structured-output\n // failure thrown from result handling) pass through unchanged instead of\n // being re-wrapped with their metadata dropped.\n if (error instanceof APICallError || error instanceof LoadAPIKeyError) {\n return error;\n }\n\n // Type guard for error with properties\n const isErrorWithMessage = (err: unknown): err is { message?: string } => {\n return typeof err === 'object' && err !== null && 'message' in err;\n };\n\n const isErrorWithCode = (\n err: unknown\n ): err is { code?: string; exitCode?: number; stderr?: string } => {\n return typeof err === 'object' && err !== null;\n };\n\n // Check for authentication errors with improved detection\n const authErrorPatterns = [\n 'not logged in',\n 'authentication',\n 'unauthorized',\n 'auth failed',\n 'please login',\n 'claude login',\n 'claude auth login',\n '/login', // CLI returns \"Please run /login\"\n 'invalid api key',\n 'oauth_org_not_allowed', // SDK 0.3.x assistant error kind: OAuth org not permitted\n ];\n\n const errorMessage =\n isErrorWithMessage(error) && error.message ? error.message.toLowerCase() : '';\n\n // Structured kind (SDKAssistantMessageError) propagated from result handling;\n // preferred over substring matching since SDK error text need not contain it.\n const errorKind = getStructuredErrorKind(error);\n\n const exitCode =\n isErrorWithCode(error) && typeof error.exitCode === 'number' ? error.exitCode : undefined;\n\n const isAuthError =\n errorKind === 'authentication_failed' ||\n errorKind === 'oauth_org_not_allowed' ||\n authErrorPatterns.some((pattern) => errorMessage.includes(pattern)) ||\n exitCode === 401;\n\n if (isAuthError) {\n return createAuthenticationError({\n message:\n isErrorWithMessage(error) && error.message\n ? error.message\n : 'Authentication failed. Please ensure Claude Code SDK is properly authenticated.',\n });\n }\n\n // Check for timeout errors\n const errorCode = isErrorWithCode(error) && typeof error.code === 'string' ? error.code : '';\n\n if (errorCode === 'ETIMEDOUT' || errorMessage.includes('timeout')) {\n return createTimeoutError({\n message: isErrorWithMessage(error) && error.message ? error.message : 'Request timed out',\n promptExcerpt: messagesPrompt.substring(0, 200),\n // Don't specify timeoutMs since we don't know the actual timeout value\n // It's controlled by the consumer via AbortSignal\n });\n }\n\n // Use error.stderr if available from SDK, otherwise use collected stderr\n const stderrFromError =\n isErrorWithCode(error) && typeof error.stderr === 'string' ? error.stderr : undefined;\n const stderr = stderrFromError || collectedStderr || undefined;\n\n // SDK 0.3.x assistant error kinds: API overload / rate limit — transient, safe to retry.\n if (\n errorKind === 'overloaded' ||\n errorKind === 'rate_limit' ||\n errorMessage.includes('overloaded')\n ) {\n return createAPICallError({\n message:\n isErrorWithMessage(error) && error.message\n ? error.message\n : 'Anthropic API is overloaded. Please retry.',\n code: errorCode || undefined,\n exitCode,\n stderr,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable: true,\n });\n }\n\n // SDK 0.3.x assistant error kind: requested model does not exist — not retryable.\n if (\n errorKind === 'model_not_found' ||\n errorMessage.includes('model_not_found') ||\n errorMessage.includes('no such model')\n ) {\n const originalMessage =\n isErrorWithMessage(error) && error.message ? error.message : 'Model not found';\n return createAPICallError({\n message: `${originalMessage}. The requested model was not found. Verify the model id passed to the provider (e.g. 'opus', 'sonnet', 'haiku', or a full model name) and that your account has access to it.`,\n code: errorCode || undefined,\n exitCode,\n stderr,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable: false,\n });\n }\n\n // Create general API call error with appropriate retry flag\n const isRetryable =\n errorCode === 'ENOENT' ||\n errorCode === 'ECONNREFUSED' ||\n errorCode === 'ETIMEDOUT' ||\n errorCode === 'ECONNRESET';\n\n return createAPICallError({\n message: isErrorWithMessage(error) && error.message ? error.message : 'Claude Code SDK error',\n code: errorCode || undefined,\n exitCode: exitCode,\n stderr,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable,\n });\n }\n\n private setSessionId(sessionId: string): void {\n this.sessionId = sessionId;\n const warning = validateSessionId(sessionId);\n if (warning) {\n this.logger.warn(`Claude Code Session: ${warning}`);\n }\n }\n\n private logMcpConnectionIssues(\n mcpServers: Array<{ name?: string; status?: string; error?: string }> | undefined\n ): void {\n if (!Array.isArray(mcpServers) || mcpServers.length === 0) {\n return;\n }\n\n const serversNeedingAttention = mcpServers.filter((server) => {\n const status = typeof server.status === 'string' ? server.status.toLowerCase() : '';\n return status === 'failed' || status === 'needs-auth';\n });\n\n if (serversNeedingAttention.length === 0) {\n return;\n }\n\n const details = serversNeedingAttention\n .map((server) => {\n const name =\n typeof server.name === 'string' && server.name.trim().length > 0\n ? server.name\n : '<unknown>';\n const status =\n typeof server.status === 'string' && server.status.trim().length > 0\n ? server.status\n : 'unknown';\n const error =\n typeof server.error === 'string' && server.error.trim().length > 0\n ? ` (${server.error})`\n : '';\n return `${name}:${status}${error}`;\n })\n .join(', ');\n\n this.logger.warn(`[claude-code] MCP servers not connected: ${details}`);\n }\n\n /**\n * Handles SDK 0.3.x system messages other than 'init', shared by doGenerate\n * and doStream:\n * - 'api_retry' is counted into providerMetadata (`apiRetries`) and debug-logged.\n * - 'permission_denied' is warn-logged and recorded into providerMetadata\n * (`permissionDenials`); without this a denial is invisible until the\n * model talks about it.\n * - 'model_refusal_fallback' is debug-logged (the superseding assistant\n * message is handled by the text-dedup guard in the message loops).\n * - 'thinking_tokens' deltas are accumulated into providerMetadata\n * (`estimatedThinkingTokens`); the estimate is explicitly not the\n * authoritative billed output tokens, so it is surfaced as metadata\n * instead of feeding `usage.outputTokens.reasoning`.\n * - The subtypes in {@link INFORMATIONAL_SYSTEM_SUBTYPES} are intentionally\n * informational and only debug-logged.\n */\n private handleSystemMessage(\n message: SDKSystemMessageVariant,\n tracking: RequestMetadataTracking,\n onRetractedUuids?: (uuids: string[]) => void\n ): void {\n switch (message.subtype) {\n case 'api_retry':\n tracking.apiRetries += 1;\n this.logger.debug(\n `[claude-code] API retry ${message.attempt}/${message.max_retries} in ${message.retry_delay_ms}ms - Status: ${message.error_status ?? 'unknown'}, Error: ${message.error}`\n );\n break;\n case 'permission_denied': {\n const reason = message.decision_reason ?? message.message;\n tracking.permissionDenials.push({\n toolName: message.tool_name,\n toolUseId: message.tool_use_id,\n ...(reason !== undefined && { reason }),\n });\n this.logger.warn(\n `[claude-code] Permission denied - Tool: ${message.tool_name}${reason ? `, Reason: ${reason}` : ''}`\n );\n break;\n }\n case 'mirror_error': {\n // SessionStore.append() failed after retries and the transcript batch\n // was DROPPED. Not informational: the response still succeeds, so warn\n // and record it in providerMetadata so sessionStore consumers can\n // detect the gap instead of trusting a silently-incomplete mirror.\n const mirrorError = (message as { error?: string }).error ?? 'unknown error';\n const mirrorSessionId =\n (message as { key?: { sessionId?: string } }).key?.sessionId ??\n (message as { session_id?: string }).session_id ??\n 'unknown';\n tracking.mirrorErrors.push({ error: mirrorError, sessionId: mirrorSessionId });\n this.logger.warn(\n `[claude-code] SessionStore mirror error (transcript batch dropped) - Session: ${mirrorSessionId}, Error: ${mirrorError}`\n );\n break;\n }\n case 'model_refusal_fallback': {\n this.logger.debug(\n `[claude-code] Model refusal fallback - ${message.original_model} -> ${message.fallback_model} (direction: ${message.direction})`\n );\n // The end-of-turn notice carries retracted_message_uuids - the\n // complete, resolution-time eviction record for the turn (including\n // tombstoned tool_result frames the per-message `supersedes` may not\n // have named). Replay it through the caller's eviction routine;\n // eviction is idempotent so already-retracted uuids are a no-op.\n const retractedUuids = (message as { retracted_message_uuids?: string[] })\n .retracted_message_uuids;\n if (onRetractedUuids && retractedUuids && retractedUuids.length > 0) {\n this.logger.debug(\n `[claude-code] Refusal fallback retracts ${retractedUuids.length} message uuid(s)`\n );\n onRetractedUuids(retractedUuids);\n }\n break;\n }\n case 'thinking_tokens':\n // `estimated_tokens` is a running total for the current thinking block\n // only, so accumulate the per-frame delta to cover multi-block requests.\n tracking.estimatedThinkingTokens += message.estimated_tokens_delta;\n this.logger.debug(\n `[claude-code] Thinking tokens estimate - block total: ${message.estimated_tokens}, delta: ${message.estimated_tokens_delta}, accumulated: ${tracking.estimatedThinkingTokens}`\n );\n break;\n default:\n if (INFORMATIONAL_SYSTEM_SUBTYPES.has(message.subtype)) {\n this.logger.debug(\n `[claude-code] Ignoring informational system message: ${message.subtype}`\n );\n } else {\n this.logger.debug(`[claude-code] Unhandled system message subtype: ${message.subtype}`);\n }\n break;\n }\n }\n\n /**\n * Merges the result message's `permission_denials` list into the tracked\n * denials. PreToolUse-hook denies bypass canUseTool and emit no\n * `permission_denied` system event (per the SDK docs on\n * SDKPermissionDeniedMessage), so the result list is the only place they\n * surface. Entries already recorded from stream-time events are deduped by\n * `tool_use_id`.\n */\n private mergeResultPermissionDenials(\n message: { permission_denials?: Array<{ tool_name: string; tool_use_id: string }> },\n tracking: RequestMetadataTracking\n ): void {\n for (const denial of message.permission_denials ?? []) {\n const alreadyTracked = tracking.permissionDenials.some(\n (d) => d.toolUseId !== undefined && d.toolUseId === denial.tool_use_id\n );\n if (!alreadyTracked) {\n tracking.permissionDenials.push({\n toolName: denial.tool_name,\n toolUseId: denial.tool_use_id,\n });\n }\n }\n }\n\n /**\n * Bounded post-result drain for the `prompt_suggestion` message\n * (promptSuggestions: true), shared by doGenerate and doStream. The\n * suggestion arrives AFTER the result message; the SDK emits at most one\n * per turn, so stop once it is delivered, and a timeout closes the\n * iterator (tearing down the subprocess) if the CLI lingers after the\n * result without emitting one. Advances the response's own generator, so\n * the caller's surrounding loop resumes to a finished iterator.\n */\n private async drainPromptSuggestion(\n response: AsyncIterable<SDKMessage>,\n onPromptSuggestion: (suggestion: string) => void\n ): Promise<void> {\n const iterator = response[Symbol.asyncIterator]();\n let drainTimer: ReturnType<typeof setTimeout> | undefined;\n const drainTimeout = new Promise<'timeout'>((resolve) => {\n drainTimer = setTimeout(\n () => resolve('timeout'),\n ClaudeCodeLanguageModel.PROMPT_SUGGESTION_DRAIN_TIMEOUT_MS\n );\n (drainTimer as { unref?: () => void }).unref?.();\n });\n try {\n while (true) {\n const winner = await Promise.race([iterator.next(), drainTimeout]);\n if (winner === 'timeout') {\n this.logger.debug('[claude-code] Post-result drain timed out; closing SDK iterator');\n // Fire-and-forget: return() may not settle while the subprocess is\n // wedged, and the response has already been produced.\n void iterator.return?.().catch(() => {});\n break;\n }\n if (winner.done) {\n break;\n }\n const trailingMessage = winner.value;\n this.logger.debug(`[claude-code] Post-result message type: ${trailingMessage.type}`);\n if (trailingMessage.type === 'prompt_suggestion') {\n onPromptSuggestion(trailingMessage.suggestion);\n // At most one prompt_suggestion per turn (SDK contract).\n void iterator.return?.().catch(() => {});\n break;\n }\n }\n } catch (drainError: unknown) {\n // Never fail the (already produced) response over post-result drain issues.\n this.logger.debug(\n `[claude-code] Error draining post-result messages: ${drainError instanceof Error ? drainError.message : String(drainError)}`\n );\n } finally {\n if (drainTimer !== undefined) {\n clearTimeout(drainTimer);\n }\n }\n }\n\n async doGenerate(\n options: Parameters<LanguageModelV3['doGenerate']>[0]\n ): Promise<Awaited<ReturnType<LanguageModelV3['doGenerate']>>> {\n this.logger.debug(`[claude-code] Starting doGenerate request with model: ${this.modelId}`);\n this.logger.debug(`[claude-code] Response format: ${options.responseFormat?.type ?? 'none'}`);\n\n const {\n messagesPrompt,\n warnings: messageWarnings,\n streamingContentParts,\n hasImageParts,\n } = convertToClaudeCodeMessages(options.prompt);\n\n this.logger.debug(\n `[claude-code] Converted ${options.prompt.length} messages, hasImageParts: ${hasImageParts}`\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal?.aborted) {\n // Propagate already-aborted state immediately with original reason\n abortController.abort(options.abortSignal.reason);\n }\n\n // Collect stderr for error reporting (SDK may not include it in errors)\n let collectedStderr = '';\n const stderrCollector = (data: string) => {\n collectedStderr += data;\n };\n\n const sdkOptions = this.getSanitizedSdkOptions();\n const effectiveResume = this.getEffectiveResume(sdkOptions);\n // createQueryOptions can throw (e.g. fallbackModel === model); attach the\n // abort listener only AFTER it succeeds so an early throw cannot leave a\n // listener on a long-lived caller AbortSignal.\n const queryOptions = this.createQueryOptions(\n abortController,\n options.responseFormat,\n stderrCollector,\n sdkOptions,\n effectiveResume\n );\n if (options.abortSignal && !options.abortSignal.aborted) {\n abortListener = () => abortController.abort(options.abortSignal?.reason);\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n let text = '';\n // Ordered, uuid-tagged content segments (text, thinking, tool parts) in\n // arrival order, so refusal-fallback `supersedes` retractions can drop\n // already-collected content instead of duplicating it, and so tool parts\n // interleave with text/reasoning in the final content array.\n const contentSegments: GenerateContentSegment[] = [];\n const joinTextSegments = () =>\n contentSegments\n .filter((segment) => segment.kind === 'text')\n .map((segment) => segment.text)\n .join('');\n // Text of the final assistant turn only: segments after the last\n // user-message-derived segment (tool-result/tool-error). Mirrors\n // doStream's accumulator reset on user messages, so JSON recovery in\n // multi-turn tool runs is not defeated by earlier-turn chatter.\n const joinFinalTurnTextSegments = () => {\n let start = 0;\n for (let i = 0; i < contentSegments.length; i++) {\n const kind = contentSegments[i]?.kind;\n if (kind === 'tool-result' || kind === 'tool-error') {\n start = i + 1;\n }\n }\n return contentSegments\n .slice(start)\n .filter((segment) => segment.kind === 'text')\n .map((segment) => segment.text)\n .join('');\n };\n // Known tools by ID so tool_result/tool_error blocks can resolve the tool\n // name and parent context (mirrors doStream's toolStates).\n const knownTools = new Map<string, { name: string; parentToolCallId: string | null }>();\n // Tool call IDs whose tool-call segment was retracted by a refusal-fallback\n // `supersedes` message. Late tool_result/tool_error frames for these IDs\n // are dropped: their call no longer exists in content, so emitting them\n // would create an orphan that makes AI SDK core's asContent() throw\n // ('Tool call ${id} not found.').\n const retractedToolIds = new Set<string>();\n // evictBuffered: the doGenerate half of the shared retraction policy (P1-P5,\n // see computeRetractedToolCallIds). MECHANISM = splice an ordered, uniform\n // contentSegments array, so retracted entries are removed entirely and the\n // surviving order is exact. Its parallel is doStream's evictLive, which can\n // only drop pending live state. Idempotent: re-evicting an already-removed\n // uuid is a no-op, so supersedes + model_refusal_fallback compose safely (P1).\n const evictBuffered = (retracted: Set<string>): void => {\n if (retracted.size === 0) return;\n // P2/P3 policy: derive tombstoned tool ids from tool-CALL own-uuid AND\n // tool-result/error OWN-uuid membership (a result frame may be named\n // directly even when its tool_use was not retracted).\n const retractedToolCallIds = computeRetractedToolCallIds(\n retracted,\n contentSegments\n .filter(\n (segment) =>\n segment.kind === 'tool-call' ||\n segment.kind === 'tool-result' ||\n segment.kind === 'tool-error'\n )\n .map((segment) => ({\n toolCallId: (segment as { toolCallId: string }).toolCallId,\n uuid: segment.uuid,\n }))\n );\n // P3/P4: a retracted Task must not remain \"active\" (it would pollute\n // getFallbackParentId with a dangling parent), and late results for\n // retracted IDs must be dropped (tombstone) rather than re-paired.\n for (const toolCallId of retractedToolCallIds) {\n retractedToolIds.add(toolCallId);\n knownTools.delete(toolCallId);\n activeTaskTools.delete(toolCallId);\n }\n for (let i = contentSegments.length - 1; i >= 0; i--) {\n const segment = contentSegments[i];\n if (segment === undefined) continue;\n const segmentUuid = 'uuid' in segment ? segment.uuid : undefined;\n const retractsSegment =\n (segmentUuid !== undefined && retracted.has(segmentUuid)) ||\n ((segment.kind === 'tool-result' || segment.kind === 'tool-error') &&\n retractedToolCallIds.has(segment.toolCallId));\n if (retractsSegment) {\n contentSegments.splice(i, 1);\n }\n }\n };\n // Track active Task tools for subagent hierarchy (mirrors doStream).\n // Using a Map instead of stack to correctly handle parallel agents\n const activeTaskTools = new Map<string, { startTime: number }>();\n\n // Helper to get fallback parent - only returns a parent when exactly ONE Task is active\n // This prevents incorrect grouping when parallel agents run simultaneously\n const getFallbackParentId = (): string | null => {\n if (activeTaskTools.size === 1) {\n return activeTaskTools.keys().next().value ?? null;\n }\n return null;\n };\n let structuredOutput: unknown | undefined;\n let receivedResultMessage = false;\n let usage: LanguageModelV3Usage = createEmptyUsage();\n let finishReason: LanguageModelV3FinishReason = { unified: 'stop', raw: undefined };\n let wasTruncated = false;\n let costUsd: number | undefined;\n let durationMs: number | undefined;\n let modelUsage: Record<string, unknown> | undefined;\n let ttftMs: number | undefined;\n let ttftStreamMs: number | undefined;\n let timeToRequestMs: number | undefined;\n let warmSpareClaimed: boolean | undefined;\n let terminalReason: string | undefined;\n // SDK 0.3.x informational counters surfaced in providerMetadata\n const metadataTracking: RequestMetadataTracking = {\n apiRetries: 0,\n permissionDenials: [],\n mirrorErrors: [],\n estimatedThinkingTokens: 0,\n };\n const warnings: SharedV3Warning[] = this.generateAllWarnings(options, messagesPrompt);\n\n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const modeSetting = this.settings.streamingInput ?? 'auto';\n const effectiveCanUseTool = sdkOptions?.canUseTool ?? this.settings.canUseTool;\n const effectivePermissionPromptToolName =\n sdkOptions?.permissionPromptToolName ?? this.settings.permissionPromptToolName;\n const wantsStreamInput =\n modeSetting === 'always' || (modeSetting === 'auto' && !!effectiveCanUseTool);\n\n if (!wantsStreamInput && hasImageParts) {\n warnings.push({\n type: 'other',\n message: STREAMING_FEATURE_WARNING,\n });\n }\n\n let done = () => {};\n const outputStreamEnded = new Promise((resolve) => {\n done = () => resolve(undefined);\n });\n try {\n if (effectiveCanUseTool && effectivePermissionPromptToolName) {\n throw new Error(\n \"canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.\"\n );\n }\n // hold input stream open until results\n // see: https://github.com/anthropics/claude-code/issues/4775\n // Re-validated against SDK 0.3.170 on 2026-06-09: kept as defensive workaround.\n const sdkPrompt = wantsStreamInput\n ? toAsyncIterablePrompt(\n messagesPrompt,\n outputStreamEnded,\n effectiveResume,\n streamingContentParts,\n this.settings.onStreamStart\n )\n : messagesPrompt;\n\n this.logger.debug(\n `[claude-code] Executing query with streamingInput: ${wantsStreamInput}, session: ${effectiveResume ?? 'new'}`\n );\n\n const response = query({\n prompt: sdkPrompt,\n options: queryOptions,\n });\n\n // Invoke onQueryCreated callback to expose Query object for advanced features\n // like mid-stream message injection via query.streamInput()\n this.settings.onQueryCreated?.(response);\n\n let lastAssistantErrorKind: string | undefined;\n // for-await's implicit cleanup AWAITS iterator.return(), which never\n // settles when the CLI is wedged mid-await after the result (the exact\n // case the bounded prompt-suggestion drain exists for). Iterate via a\n // wrapper whose return() detaches fire-and-forget so `break` can never\n // block generateText on a lingering subprocess.\n const sdkIterator = response[Symbol.asyncIterator]();\n const detachableResponse: AsyncIterable<SDKMessage> = {\n [Symbol.asyncIterator]: () => ({\n next: () => sdkIterator.next(),\n return: () => {\n void sdkIterator.return?.().catch(() => {});\n return Promise.resolve({ done: true as const, value: undefined });\n },\n }),\n };\n for await (const message of detachableResponse) {\n this.logger.debug(`[claude-code] Received message type: ${message.type}`);\n if (message.type === 'assistant') {\n // SDK 0.3.x delivers API error kinds (e.g. 'overloaded',\n // 'model_not_found') as a structured field on assistant messages.\n if (typeof message.error === 'string') {\n lastAssistantErrorKind = message.error;\n }\n // Refusal-fallback replacement (SDK 0.3.x): drop retracted segments\n // (text, thinking, AND tool calls) so superseded content is not\n // duplicated in the final output. Tool results/errors whose call was\n // retracted are dropped too so they don't survive as orphans. (P5: the\n // trigger ignores this message's own text — see applySupersede.)\n // doGenerate uses the 'truthy' guard to match af38c07's original\n // `message.supersedes && message.supersedes.length > 0` semantics.\n applySupersede(message, evictBuffered, this.logger, 'truthy');\n\n const messageUuid = typeof message.uuid === 'string' ? message.uuid : undefined;\n // Extract parent_tool_use_id from SDK message - this is the authoritative source\n // SDK provides this field when tool is executed within a subagent context\n const sdkParentToolUseId = (message as { parent_tool_use_id?: string | null })\n .parent_tool_use_id;\n const content = message.message.content;\n\n // Walk content blocks in document order so text, thinking, and\n // tool_use parts interleave in the final content array exactly as\n // the model produced them.\n if (Array.isArray(content)) {\n for (const block of content) {\n if (!isContentBlock(block)) continue;\n if (block.type === 'text' && typeof block.text === 'string') {\n if (block.text.length > 0) {\n contentSegments.push({\n kind: 'text',\n ...(messageUuid !== undefined && { uuid: messageUuid }),\n text: block.text,\n });\n }\n } else if (block.type === 'thinking' && typeof block.thinking === 'string') {\n contentSegments.push({\n kind: 'reasoning',\n ...(messageUuid !== undefined && { uuid: messageUuid }),\n text: block.thinking,\n });\n } else if (block.type === 'tool_use') {\n const [tool] = this.extractToolUses([block]);\n if (!tool) continue;\n // Prefer SDK message-level parent (works for parallel agents)\n // Fall back to content-level parent, then timing-based inference\n // Task tools never have a parent (they're top-level)\n const parentToolCallId = isSubagentToolName(tool.name)\n ? null\n : resolveToolParentId(\n sdkParentToolUseId,\n tool.parentToolUseId,\n getFallbackParentId\n );\n this.logger.debug(\n `[claude-code] Tool use detected - Tool: ${tool.name}, ID: ${tool.id}, SDK parent: ${sdkParentToolUseId}, resolved parent: ${parentToolCallId}`\n );\n knownTools.set(tool.id, { name: tool.name, parentToolCallId });\n // Track Task tools as active so nested tools can reference them as parent\n if (isSubagentToolName(tool.name)) {\n activeTaskTools.set(tool.id, { startTime: Date.now() });\n }\n contentSegments.push({\n kind: 'tool-call',\n ...(messageUuid !== undefined && { uuid: messageUuid }),\n toolCallId: tool.id,\n part: this.buildToolCallPart(\n tool.id,\n tool.name,\n this.serializeToolInput(tool.input),\n parentToolCallId\n ),\n });\n }\n }\n }\n text = joinTextSegments();\n } else if (message.type === 'user') {\n if (!message.message?.content) {\n this.logger.warn(\n `[claude-code] Unexpected user message structure: missing content field. Message type: ${message.type}. This may indicate an SDK protocol violation.`\n );\n continue;\n }\n\n // Extract parent_tool_use_id from SDK message for late-arriving tool results\n const sdkParentToolUseIdForResults = (message as { parent_tool_use_id?: string | null })\n .parent_tool_use_id;\n // tool_result/tool_error frames are their own normalized SDK messages\n // with their own uuid; tag segments with it so a refusal-fallback\n // retraction that names the tool_result uuid DIRECTLY (per the SDK,\n // retracted_message_uuids can include tombstoned tool_results) evicts\n // them even when the originating tool_use was not itself retracted.\n const resultMessageUuid =\n typeof (message as { uuid?: unknown }).uuid === 'string'\n ? (message as { uuid: string }).uuid\n : undefined;\n\n const content = message.message.content;\n for (const result of this.extractToolResults(content)) {\n if (this.isRetractedToolFrame(result.id, retractedToolIds, 'result')) {\n continue;\n }\n const known = knownTools.get(result.id);\n const toolName =\n result.name ?? known?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool result received - Tool: ${toolName}, ID: ${result.id}`\n );\n\n let parentToolCallId: string | null;\n if (known) {\n known.name = toolName;\n parentToolCallId = known.parentToolCallId;\n } else {\n this.logger.warn(\n `[claude-code] Received tool result for unknown tool ID: ${result.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n parentToolCallId = isSubagentToolName(toolName)\n ? null\n : resolveToolParentId(sdkParentToolUseIdForResults, undefined, getFallbackParentId);\n knownTools.set(result.id, { name: toolName, parentToolCallId });\n // Synthesize the tool-call part to preserve call/result pairing\n // when no prior tool_use block was seen (mirrors doStream).\n contentSegments.push({\n kind: 'tool-call',\n toolCallId: result.id,\n part: this.buildToolCallPart(result.id, toolName, '', parentToolCallId),\n });\n }\n\n // Remove Task tools from active set when they complete\n if (isSubagentToolName(toolName)) {\n activeTaskTools.delete(result.id);\n }\n\n contentSegments.push({\n kind: 'tool-result',\n ...(resultMessageUuid !== undefined && { uuid: resultMessageUuid }),\n toolCallId: result.id,\n part: this.buildToolResultPart(\n result.id,\n toolName,\n result.result,\n result.isError,\n parentToolCallId\n ),\n });\n }\n // Handle tool errors\n for (const error of this.extractToolErrors(content)) {\n if (this.isRetractedToolFrame(error.id, retractedToolIds, 'error')) {\n continue;\n }\n const known = knownTools.get(error.id);\n const toolName = error.name ?? known?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool error received - Tool: ${toolName}, ID: ${error.id}`\n );\n\n let parentToolCallId: string | null;\n if (known) {\n known.name = toolName;\n parentToolCallId = known.parentToolCallId;\n } else {\n this.logger.warn(\n `[claude-code] Received tool error for unknown tool ID: ${error.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n parentToolCallId = isSubagentToolName(toolName)\n ? null\n : resolveToolParentId(sdkParentToolUseIdForResults, undefined, getFallbackParentId);\n knownTools.set(error.id, { name: toolName, parentToolCallId });\n // Ensure a tool-call part precedes the tool-error (mirrors doStream)\n contentSegments.push({\n kind: 'tool-call',\n toolCallId: error.id,\n part: this.buildToolCallPart(error.id, toolName, '', parentToolCallId),\n });\n }\n\n // Remove Task tools from active set when they error\n if (isSubagentToolName(toolName)) {\n activeTaskTools.delete(error.id);\n }\n\n contentSegments.push({\n kind: 'tool-error',\n ...(resultMessageUuid !== undefined && { uuid: resultMessageUuid }),\n toolCallId: error.id,\n part: this.buildToolErrorResultPart(\n error.id,\n toolName,\n error.error,\n parentToolCallId\n ),\n });\n }\n } else if (message.type === 'result') {\n done();\n receivedResultMessage = true;\n this.setSessionId(message.session_id);\n costUsd = message.total_cost_usd;\n durationMs = message.duration_ms;\n modelUsage = message.modelUsage;\n // SDK 0.3.x timing metadata (only present on SDKResultSuccess)\n if ('ttft_ms' in message) {\n ttftMs = message.ttft_ms;\n }\n if ('ttft_stream_ms' in message) {\n ttftStreamMs = message.ttft_stream_ms;\n }\n if ('time_to_request_ms' in message) {\n timeToRequestMs = message.time_to_request_ms;\n }\n if ('warm_spare_claimed' in message) {\n warmSpareClaimed = message.warm_spare_claimed;\n }\n terminalReason = message.terminal_reason;\n this.mergeResultPermissionDenials(message, metadataTracking);\n\n // Handle is_error flag in result message (e.g., auth failures).\n // SDKResultSuccess carries the error text in `result`; SDKResultError\n // has no `result` field and carries details in `errors` instead.\n if ('is_error' in message && message.is_error === true) {\n const resultText =\n 'result' in message && typeof message.result === 'string'\n ? message.result\n : undefined;\n const errorsText =\n 'errors' in message && Array.isArray(message.errors)\n ? message.errors.filter((e): e is string => typeof e === 'string').join('; ')\n : '';\n const errorMessage = resultText ?? (errorsText || 'Claude Code CLI returned an error');\n throw Object.assign(new Error(errorMessage), {\n exitCode: 1,\n errorKind: lastAssistantErrorKind,\n });\n }\n\n // Handle structured output errors (SDK 0.1.45+)\n // Use string comparison to support new SDK subtypes not yet in TypeScript definitions\n if ((message.subtype as string) === 'error_max_structured_output_retries') {\n throw new Error(\n 'Failed to generate valid structured output after maximum retries. The model could not produce a response matching the required schema.'\n );\n }\n\n // Capture structured output if available (SDK 0.1.45+)\n if ('structured_output' in message && message.structured_output !== undefined) {\n structuredOutput = message.structured_output;\n this.logger.debug('[claude-code] Received structured output from SDK');\n }\n\n this.logger.info(\n `[claude-code] Request completed - Session: ${message.session_id}, Cost: $${costUsd?.toFixed(4) ?? 'N/A'}, Duration: ${durationMs ?? 'N/A'}ms`\n );\n\n if ('usage' in message) {\n usage = convertClaudeCodeUsage(message.usage);\n\n this.logger.debug(\n `[claude-code] Token usage - Input: ${usage.inputTokens.total}, Output: ${usage.outputTokens.total}`\n );\n }\n\n const stopReason =\n 'stop_reason' in message\n ? ((message as Record<string, unknown>).stop_reason as string | null | undefined)\n : undefined;\n finishReason = mapClaudeCodeFinishReason(message.subtype, stopReason);\n this.logger.debug(`[claude-code] Finish reason: ${finishReason.unified}`);\n\n // The result message is terminal. Mirror doStream: when a\n // prompt_suggestion callback is registered, drain for it with the\n // shared bounded drain (10s timeout, stops at the first suggestion);\n // otherwise stop iterating immediately so a lingering CLI cannot\n // block generateText after the result is already available.\n // Drain for the post-result prompt_suggestion only when suggestions\n // can actually be emitted. The SDK enables them when promptSuggestions\n // is absent OR true and disables them only when explicitly false, so\n // skip the (up to 10s) drain solely in the explicit-false case.\n const effectivePromptSuggestions =\n sdkOptions?.promptSuggestions ?? this.settings.promptSuggestions;\n if (this.settings.onPromptSuggestion && effectivePromptSuggestions !== false) {\n await this.drainPromptSuggestion(response, this.settings.onPromptSuggestion);\n }\n break;\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.logMcpConnectionIssues(message.mcp_servers);\n this.setSessionId(message.session_id);\n this.logger.info(`[claude-code] Session initialized: ${message.session_id}`);\n } else if (message.type === 'system') {\n this.handleSystemMessage(\n message,\n metadataTracking,\n buildRetractionEvictor(evictBuffered)\n );\n }\n }\n } catch (error: unknown) {\n done();\n this.logger.debug(\n `[claude-code] Error during doGenerate: ${error instanceof Error ? error.message : String(error)}`\n );\n\n // Special handling for AbortError to preserve abort signal reason\n if (isAbortError(error)) {\n this.logger.debug('[claude-code] Request aborted by user');\n throw options.abortSignal?.aborted ? options.abortSignal.reason : error;\n }\n\n if (isClaudeCodeTruncationError(error, text)) {\n this.logger.warn(\n `[claude-code] Detected truncated response, returning ${text.length} characters of buffered text`\n );\n wasTruncated = true;\n finishReason = { unified: 'length', raw: 'truncation' };\n warnings.push({\n type: 'other',\n message: CLAUDE_CODE_TRUNCATION_WARNING,\n });\n } else {\n // Use unified error handler\n throw this.handleClaudeCodeError(error, messagesPrompt, collectedStderr);\n }\n } finally {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n }\n\n // Loud failure / graceful recovery for native structured outputs: the CLI\n // can return a SUCCESSFUL result without structured_output when the schema\n // contains constructs it cannot enforce, silently falling back to prose.\n // Without this, the prose flows downstream and generateObject fails with an\n // opaque AI_NoObjectGeneratedError. Try to recover JSON from the prose\n // first; otherwise throw a descriptive, non-retryable error. Truncation\n // and error_max_structured_output_retries handling above are unaffected.\n if (\n options.responseFormat?.type === 'json' &&\n options.responseFormat.schema !== undefined &&\n receivedResultMessage &&\n structuredOutput === undefined &&\n !wasTruncated &&\n finishReason.unified === 'stop'\n ) {\n // Prefer the final assistant turn's prose (matches doStream, which\n // resets its accumulator on user messages), then fall back to all\n // turns joined (doGenerate never resets text segments).\n const recoveredJsonText =\n extractJsonObjectText(joinFinalTurnTextSegments()) ??\n extractJsonObjectText(joinTextSegments());\n if (recoveredJsonText !== undefined) {\n this.logger.warn(\n '[claude-code] outputFormat was requested but the CLI returned no structured_output; recovered JSON by parsing the prose response. The schema likely contains constructs the CLI cannot enforce - see the README structured-output limitations.'\n );\n structuredOutput = JSON.parse(recoveredJsonText);\n } else {\n throw createAPICallError({\n message: MISSING_STRUCTURED_OUTPUT_ERROR_MESSAGE,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable: false,\n });\n }\n }\n\n const thinkingTraces = contentSegments\n .filter((segment) => segment.kind === 'reasoning')\n .map((segment) => (segment as { text: string }).text);\n\n // Build the ordered content array. Adjacent text segments collapse into a\n // single text part (plain text responses keep their single-part shape),\n // while tool parts interleave with text/reasoning in arrival order.\n // When the SDK returned structured output (native JSON schema support),\n // it replaces the accumulated text as a single trailing text part.\n const contentParts: LanguageModelV3Content[] = [];\n for (const segment of contentSegments) {\n if (segment.kind === 'reasoning') {\n contentParts.push({ type: 'reasoning', text: segment.text });\n } else if (segment.kind === 'text') {\n if (structuredOutput !== undefined) continue;\n const last = contentParts[contentParts.length - 1];\n if (last !== undefined && last.type === 'text') {\n last.text += segment.text;\n } else {\n contentParts.push({ type: 'text', text: segment.text });\n }\n } else {\n // tool-call and tool-result parts are V3 content union members.\n // CLI tool_error blocks were mapped to tool-result parts with\n // isError: true (see buildToolErrorResultPart) so they survive AI\n // SDK core's asContent(), which drops unknown content part types.\n contentParts.push(segment.part);\n }\n }\n if (structuredOutput !== undefined) {\n contentParts.push({ type: 'text', text: JSON.stringify(structuredOutput) });\n } else if (!contentParts.some((part) => part.type === 'text')) {\n // Preserve the long-standing invariant that doGenerate always returns\n // a text part, even when the response produced no text.\n contentParts.push({ type: 'text', text: '' });\n }\n\n return {\n content: contentParts,\n usage,\n finishReason,\n warnings,\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n request: {\n body: messagesPrompt,\n },\n providerMetadata: {\n 'claude-code': {\n ...(this.sessionId !== undefined && { sessionId: this.sessionId }),\n ...(costUsd !== undefined && { costUsd }),\n ...(durationMs !== undefined && { durationMs }),\n ...(modelUsage !== undefined && { modelUsage: modelUsage as unknown as JSONValue }),\n ...(ttftMs !== undefined && { ttftMs }),\n ...(ttftStreamMs !== undefined && { ttftStreamMs }),\n ...(timeToRequestMs !== undefined && { timeToRequestMs }),\n ...(warmSpareClaimed !== undefined && { warmSpareClaimed }),\n ...(terminalReason !== undefined && { terminalReason }),\n ...(metadataTracking.apiRetries > 0 && { apiRetries: metadataTracking.apiRetries }),\n ...(metadataTracking.permissionDenials.length > 0 && {\n permissionDenials: metadataTracking.permissionDenials as unknown as JSONValue,\n }),\n ...(metadataTracking.mirrorErrors.length > 0 && {\n mirrorErrors: metadataTracking.mirrorErrors as unknown as JSONValue,\n }),\n ...(metadataTracking.estimatedThinkingTokens > 0 && {\n estimatedThinkingTokens: metadataTracking.estimatedThinkingTokens,\n }),\n ...(wasTruncated && { truncated: true }),\n ...(thinkingTraces.length > 0 && { thinkingTraces }),\n },\n },\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV3['doStream']>[0]\n ): Promise<Awaited<ReturnType<LanguageModelV3['doStream']>>> {\n this.logger.debug(`[claude-code] Starting doStream request with model: ${this.modelId}`);\n this.logger.debug(`[claude-code] Response format: ${options.responseFormat?.type ?? 'none'}`);\n\n const {\n messagesPrompt,\n warnings: messageWarnings,\n streamingContentParts,\n hasImageParts,\n } = convertToClaudeCodeMessages(options.prompt);\n\n this.logger.debug(\n `[claude-code] Converted ${options.prompt.length} messages for streaming, hasImageParts: ${hasImageParts}`\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal?.aborted) {\n // Propagate already-aborted state immediately with original reason\n abortController.abort(options.abortSignal.reason);\n }\n\n // Collect stderr for error reporting (SDK may not include it in errors)\n let collectedStderr = '';\n const stderrCollector = (data: string) => {\n collectedStderr += data;\n };\n\n const sdkOptions = this.getSanitizedSdkOptions();\n const effectiveResume = this.getEffectiveResume(sdkOptions);\n // createQueryOptions can throw (e.g. fallbackModel === model); attach the\n // abort listener only AFTER it succeeds so an early throw cannot leave a\n // listener on a long-lived caller AbortSignal.\n const queryOptions = this.createQueryOptions(\n abortController,\n options.responseFormat,\n stderrCollector,\n sdkOptions,\n effectiveResume\n );\n if (options.abortSignal && !options.abortSignal.aborted) {\n abortListener = () => abortController.abort(options.abortSignal?.reason);\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n // Enable partial messages for true streaming (token-by-token delivery)\n // This can be overridden by user settings, but we default to true for doStream\n if (queryOptions.includePartialMessages === undefined) {\n queryOptions.includePartialMessages = true;\n }\n\n const warnings: SharedV3Warning[] = this.generateAllWarnings(options, messagesPrompt);\n\n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach((warning) => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const modeSetting = this.settings.streamingInput ?? 'auto';\n const effectiveCanUseTool = sdkOptions?.canUseTool ?? this.settings.canUseTool;\n const effectivePermissionPromptToolName =\n sdkOptions?.permissionPromptToolName ?? this.settings.permissionPromptToolName;\n const wantsStreamInput =\n modeSetting === 'always' || (modeSetting === 'auto' && !!effectiveCanUseTool);\n\n if (!wantsStreamInput && hasImageParts) {\n warnings.push({\n type: 'other',\n message: STREAMING_FEATURE_WARNING,\n });\n }\n\n const stream = new ReadableStream<ExtendedStreamPart>({\n start: async (controller) => {\n let done = () => {};\n const outputStreamEnded = new Promise((resolve) => {\n done = () => resolve(undefined);\n });\n const toolStates = new Map<string, ToolStreamState>();\n // Tombstones for pending tool calls dropped by supersede retraction:\n // late tool_result/tool_error blocks for these IDs must be discarded,\n // not synthesized back into a tool-call via the unknown-tool path\n // (mirrors doGenerate's retractedToolIds).\n const retractedStreamToolIds = new Set<string>();\n // Track active Task tools for subagent hierarchy\n // Using a Map instead of stack to correctly handle parallel agents\n const activeTaskTools = new Map<string, { startTime: number }>();\n\n // Helper to get fallback parent - only returns a parent when exactly ONE Task is active\n // This prevents incorrect grouping when parallel agents run simultaneously\n const getFallbackParentId = (): string | null => {\n if (activeTaskTools.size === 1) {\n return activeTaskTools.keys().next().value ?? null;\n }\n return null;\n };\n\n const streamWarnings: SharedV3Warning[] = [];\n\n const closeToolInput = (toolId: string, state: ToolStreamState) => {\n if (!state.inputClosed && state.inputStarted) {\n controller.enqueue({\n type: 'tool-input-end',\n id: toolId,\n });\n state.inputClosed = true;\n }\n };\n\n const emitToolCall = (toolId: string, state: ToolStreamState) => {\n if (state.callEmitted) {\n return;\n }\n\n closeToolInput(toolId, state);\n\n controller.enqueue(\n this.buildToolCallPart(\n toolId,\n state.name,\n state.lastSerializedInput ?? '',\n state.parentToolCallId\n )\n );\n state.callEmitted = true;\n };\n\n const finalizeToolCalls = () => {\n for (const [toolId, state] of toolStates) {\n emitToolCall(toolId, state);\n }\n toolStates.clear();\n };\n\n let usage: LanguageModelV3Usage = createEmptyUsage();\n let accumulatedText = '';\n // Per-message text segments mirroring `accumulatedText` so refusal-fallback\n // `supersedes` retractions keep non-retracted text (matches doGenerate).\n const textSegments: Array<{ uuid?: string; text: string }> = [];\n let textPartId: string | undefined;\n let streamedTextLength = 0; // Track text already emitted via stream_events to avoid duplication\n // Model text delivered to the client as text-delta parts (non-JSON mode)\n // SINCE THE LAST ASSISTANT MESSAGE was processed. Each assistant message\n // \"claims\" the stream-event deltas that preceded it, so this window holds\n // exactly the deltas attributable to the upcoming assistant message. Used\n // to decide whether a superseding message's replacement text was already\n // streamed or must be emitted as a new part — scoping the check to this\n // window prevents false positives when the replacement happens to be a\n // substring of earlier (e.g. refused) output.\n let emittedTextSinceLastAssistant = '';\n let hasReceivedStreamEvents = false; // Track if we've received any stream_events\n let hasStreamedJson = false; // Track if JSON has been streamed via input_json_delta\n // SDK 0.3.x structured error kind from assistant messages (e.g. 'overloaded')\n let lastAssistantErrorKind: string | undefined;\n // SDK 0.3.x informational counters surfaced in providerMetadata at finish\n const metadataTracking: RequestMetadataTracking = {\n apiRetries: 0,\n permissionDenials: [],\n mirrorErrors: [],\n estimatedThinkingTokens: 0,\n };\n\n // Content block streaming: Map block indices to tool IDs and accumulated JSON\n const toolBlocksByIndex = new Map<number, string>();\n const toolInputAccumulators = new Map<string, string>();\n\n // Track text content blocks by index for correlating text_delta with text parts\n const textBlocksByIndex = new Map<number, string>();\n\n // Track if text was streamed via content blocks to prevent double emission in result handler\n let textStreamedViaContentBlock = false;\n\n // Extended thinking: Map block indices to reasoning part IDs\n const reasoningBlocksByIndex = new Map<number, string>();\n let currentReasoningPartId: string | undefined;\n\n // evictLive: the doStream half of the shared retraction policy (P1-P5,\n // see computeRetractedToolCallIds). MECHANISM = drop live state, since\n // already-emitted text/tool parts CANNOT be un-streamed. Its parallel is\n // doGenerate's evictBuffered, which splices ordered buffered segments.\n // Differences from evictBuffered (intentional, see policy block):\n // - text: surviving textSegments are kept and accumulatedText is\n // recomputed from them (P2 over text) so JSON-mode/final tracking\n // excludes retracted text — but the wire deltas already sent stay sent.\n // - tools: the tombstone set is derived from toolState.messageUuid (P2;\n // results aren't buffered as segments here, unlike evictBuffered), and\n // only PENDING (not-yet-callEmitted) calls can be dropped + tombstoned\n // (P3); activeTaskTools is always cleaned (P4).\n // Idempotent, so supersedes + model_refusal_fallback compose safely (P1).\n const evictLive = (retracted: Set<string>): void => {\n if (retracted.size === 0) return;\n for (let i = textSegments.length - 1; i >= 0; i--) {\n const segmentUuid = textSegments[i]?.uuid;\n if (segmentUuid !== undefined && retracted.has(segmentUuid)) {\n textSegments.splice(i, 1);\n }\n }\n // Recompute alongside every textSegments mutation so JSON-mode final\n // extraction never sees retracted text (kept in lockstep with the\n // other textSegments writers below).\n accumulatedText = textSegments.map((segment) => segment.text).join('');\n\n // P2/P3 policy: derive tombstoned tool ids from each live toolState's\n // owning messageUuid (the doStream descriptor shape).\n const retractedToolCallIds = computeRetractedToolCallIds(\n retracted,\n [...toolStates].map(([toolId, state]) => ({\n toolCallId: toolId,\n uuid: state.messageUuid,\n }))\n );\n for (const toolId of retractedToolCallIds) {\n const state = toolStates.get(toolId);\n if (!state) continue;\n activeTaskTools.delete(toolId); // P4\n if (!state.callEmitted) {\n // P3: only pending calls can be dropped + tombstoned; an\n // already-emitted tool-call is on the wire and cannot be retracted.\n closeToolInput(toolId, state);\n toolStates.delete(toolId);\n retractedStreamToolIds.add(toolId);\n toolInputAccumulators.delete(toolId);\n for (const [blockIndex, mappedId] of toolBlocksByIndex) {\n if (mappedId === toolId) {\n toolBlocksByIndex.delete(blockIndex);\n }\n }\n this.logger.debug(\n `[claude-code] Retracted pending tool call from superseded message - ID: ${toolId}`\n );\n }\n }\n };\n\n try {\n // Emit stream-start with warnings\n controller.enqueue({ type: 'stream-start', warnings });\n\n if (effectiveCanUseTool && effectivePermissionPromptToolName) {\n throw new Error(\n \"canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.\"\n );\n }\n // hold input stream open until results\n // see: https://github.com/anthropics/claude-code/issues/4775\n // Re-validated against SDK 0.3.170 on 2026-06-09: kept as defensive workaround.\n const sdkPrompt = wantsStreamInput\n ? toAsyncIterablePrompt(\n messagesPrompt,\n outputStreamEnded,\n effectiveResume,\n streamingContentParts,\n this.settings.onStreamStart\n )\n : messagesPrompt;\n\n this.logger.debug(\n `[claude-code] Starting stream query with streamingInput: ${wantsStreamInput}, session: ${effectiveResume ?? 'new'}`\n );\n\n const response = query({\n prompt: sdkPrompt,\n options: queryOptions,\n });\n\n // Invoke onQueryCreated callback to expose Query object for advanced features\n // like mid-stream message injection via query.streamInput()\n this.settings.onQueryCreated?.(response);\n\n for await (const message of response) {\n this.logger.debug(`[claude-code] Stream received message type: ${message.type}`);\n\n // Handle streaming events (token-by-token delivery via includePartialMessages)\n if (message.type === 'stream_event') {\n const streamEvent = message as SDKPartialAssistantMessage;\n const event = streamEvent.event;\n\n // Check for text_delta events within content_block_delta\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'text_delta' &&\n 'text' in event.delta &&\n event.delta.text\n ) {\n const deltaText = event.delta.text;\n hasReceivedStreamEvents = true;\n\n // Don't emit text deltas in JSON mode - accumulate instead\n if (options.responseFormat?.type === 'json') {\n accumulatedText += deltaText;\n streamedTextLength += deltaText.length;\n continue;\n }\n\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: deltaText,\n });\n accumulatedText += deltaText;\n streamedTextLength += deltaText.length;\n emittedTextSinceLastAssistant += deltaText;\n }\n // Handle input_json_delta events for structured output streaming\n // The SDK uses a StructuredOutput tool internally, and JSON is streamed via input_json_delta\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'input_json_delta' &&\n 'partial_json' in event.delta &&\n event.delta.partial_json\n ) {\n const jsonDelta = event.delta.partial_json;\n hasReceivedStreamEvents = true;\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n\n // In JSON mode, prioritize streaming to text-delta for streamObject() support\n // The SDK's internal StructuredOutput tool uses input_json_delta to stream JSON responses\n if (options.responseFormat?.type === 'json') {\n // Emit text-start if this is the first JSON delta\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: jsonDelta,\n });\n accumulatedText += jsonDelta;\n streamedTextLength += jsonDelta.length;\n hasStreamedJson = true;\n continue;\n }\n\n // In non-JSON mode, route to tool-input-delta if we have a tracked tool\n const toolId = toolBlocksByIndex.get(blockIndex);\n if (toolId) {\n // Accumulate and emit tool-input-delta\n const accumulated = (toolInputAccumulators.get(toolId) ?? '') + jsonDelta;\n toolInputAccumulators.set(toolId, accumulated);\n\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: jsonDelta,\n });\n continue;\n }\n // input_json_delta without tool context in non-JSON mode is ignored\n }\n\n // Handle content_block_start for tool_use - emit tool-input-start immediately\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'tool_use'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n const toolBlock = event.content_block as {\n type: string;\n id?: string;\n name?: string;\n };\n const toolId =\n typeof toolBlock.id === 'string' && toolBlock.id.length > 0\n ? toolBlock.id\n : generateId();\n const toolName =\n typeof toolBlock.name === 'string' && toolBlock.name.length > 0\n ? toolBlock.name\n : ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n hasReceivedStreamEvents = true;\n\n // Close any active text part before tool starts\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n // Track this block for later delta/stop events\n toolBlocksByIndex.set(blockIndex, toolId);\n toolInputAccumulators.set(toolId, '');\n\n // Create tool state if not exists\n let state = toolStates.get(toolId);\n if (!state) {\n // The partial-message envelope carries the authoritative\n // subagent parent (SDKPartialAssistantMessage.parent_tool_use_id).\n // These parts are emitted immediately - before the final\n // assistant message could retro-update state - so relying on\n // timing inference alone would permanently mis-parent (or\n // null-parent) nested subagent tools.\n const partialParentId = (message as { parent_tool_use_id?: string | null })\n .parent_tool_use_id;\n const currentParentId = isSubagentToolName(toolName)\n ? null\n : resolveToolParentId(partialParentId, undefined, getFallbackParentId);\n const envelopeUuid = (message as { uuid?: unknown }).uuid;\n state = {\n name: toolName,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: currentParentId,\n ...(typeof envelopeUuid === 'string' && { messageUuid: envelopeUuid }),\n };\n toolStates.set(toolId, state);\n }\n\n // Emit tool-input-start immediately with providerMetadata for parent context\n if (!state.inputStarted) {\n this.logger.debug(\n `[claude-code] Tool input started (content_block) - Tool: ${toolName}, ID: ${toolId}, parent: ${state.parentToolCallId}`\n );\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n\n // Track Task tools as active so nested tools can reference them as parent\n if (isSubagentToolName(toolName)) {\n activeTaskTools.set(toolId, { startTime: Date.now() });\n }\n state.inputStarted = true;\n }\n continue;\n }\n\n // Handle content_block_start for text - emit text-start early\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'text'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Generate text part ID early and map to block index\n const partId = generateId();\n textBlocksByIndex.set(blockIndex, partId);\n textPartId = partId;\n\n this.logger.debug(\n `[claude-code] Text content block started - Index: ${blockIndex}, ID: ${partId}`\n );\n\n controller.enqueue({\n type: 'text-start',\n id: partId,\n });\n textStreamedViaContentBlock = true;\n continue;\n }\n\n // Handle content_block_start for thinking - emit reasoning-start immediately\n if (\n event.type === 'content_block_start' &&\n 'content_block' in event &&\n event.content_block?.type === 'thinking'\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Close any active text part before reasoning starts\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n const reasoningPartId = generateId();\n reasoningBlocksByIndex.set(blockIndex, reasoningPartId);\n currentReasoningPartId = reasoningPartId;\n\n this.logger.debug(\n `[claude-code] Reasoning started (content_block) - ID: ${reasoningPartId}`\n );\n controller.enqueue({\n type: 'reasoning-start',\n id: reasoningPartId,\n });\n continue;\n }\n\n // Handle thinking_delta for extended thinking\n if (\n event.type === 'content_block_delta' &&\n event.delta.type === 'thinking_delta' &&\n 'thinking' in event.delta &&\n event.delta.thinking\n ) {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n const reasoningPartId =\n reasoningBlocksByIndex.get(blockIndex) ?? currentReasoningPartId;\n hasReceivedStreamEvents = true;\n\n if (reasoningPartId) {\n controller.enqueue({\n type: 'reasoning-delta',\n id: reasoningPartId,\n delta: event.delta.thinking,\n });\n }\n continue;\n }\n\n // Handle content_block_stop - finalize tool input, text, or reasoning\n if (event.type === 'content_block_stop') {\n const blockIndex = 'index' in event ? (event.index as number) : -1;\n hasReceivedStreamEvents = true;\n\n // Check if this is a tool block\n const toolId = toolBlocksByIndex.get(blockIndex);\n if (toolId) {\n const state = toolStates.get(toolId);\n if (state && !state.inputClosed) {\n const accumulatedInput = toolInputAccumulators.get(toolId) ?? '';\n this.logger.debug(\n `[claude-code] Tool content block stopped - Index: ${blockIndex}, Tool: ${state.name}, ID: ${toolId}`\n );\n controller.enqueue({\n type: 'tool-input-end',\n id: toolId,\n });\n state.inputClosed = true;\n const effectiveInput = accumulatedInput || state.lastSerializedInput || '';\n state.lastSerializedInput = effectiveInput;\n\n // Emit tool-call immediately when input is complete (don't wait for result)\n // This allows UI to show \"running\" state while tool executes\n if (!state.callEmitted) {\n controller.enqueue(\n this.buildToolCallPart(\n toolId,\n state.name,\n effectiveInput,\n state.parentToolCallId\n )\n );\n state.callEmitted = true;\n }\n }\n toolBlocksByIndex.delete(blockIndex);\n toolInputAccumulators.delete(toolId);\n continue;\n }\n\n // Check if this is a text block\n const textId = textBlocksByIndex.get(blockIndex);\n if (textId) {\n this.logger.debug(\n `[claude-code] Text content block stopped - Index: ${blockIndex}, ID: ${textId}`\n );\n controller.enqueue({\n type: 'text-end',\n id: textId,\n });\n textBlocksByIndex.delete(blockIndex);\n if (textPartId === textId) {\n textPartId = undefined;\n }\n continue;\n }\n\n // Check if this is a reasoning block\n const reasoningPartId = reasoningBlocksByIndex.get(blockIndex);\n if (reasoningPartId) {\n this.logger.debug(\n `[claude-code] Reasoning ended (content_block) - ID: ${reasoningPartId}`\n );\n controller.enqueue({\n type: 'reasoning-end',\n id: reasoningPartId,\n });\n reasoningBlocksByIndex.delete(blockIndex);\n if (currentReasoningPartId === reasoningPartId) {\n currentReasoningPartId = undefined;\n }\n continue;\n }\n }\n\n // Other stream_event types are informational\n continue;\n }\n\n if (message.type === 'assistant') {\n // SDK 0.3.x delivers API error kinds (e.g. 'overloaded',\n // 'model_not_found') as a structured field on assistant messages.\n if (typeof message.error === 'string') {\n lastAssistantErrorKind = message.error;\n }\n\n // Refusal-fallback replacement (SDK 0.3.x): this message replaces\n // previously-delivered messages whose text was already emitted and\n // cannot be retracted from the stream. Evict retracted segments on\n // arrival (matches doGenerate); the trigger does not depend on this\n // message carrying text of its own (P5). The boolean drives the\n // replacement-text emission sub-cases below.\n const supersedesPriorMessages = applySupersede(message, evictLive, this.logger);\n\n if (!message.message?.content) {\n this.logger.warn(\n `[claude-code] Unexpected assistant message structure: missing content field. Message type: ${message.type}. This may indicate an SDK protocol violation.`\n );\n continue;\n }\n\n // Extract parent_tool_use_id from SDK message - this is the authoritative source\n // SDK provides this field when tool is executed within a subagent context\n const sdkParentToolUseId = (message as { parent_tool_use_id?: string | null })\n .parent_tool_use_id;\n\n const content = message.message.content;\n const tools = this.extractToolUses(content);\n\n // Close any active text part before tool calls start.\n // This ensures tool calls split text into separate parts.\n // We only do this if there are actual tools to avoid unnecessary text-end events.\n if (textPartId && tools.length > 0) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined; // Reset so next text gets a new ID\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n\n for (const tool of tools) {\n const toolId = tool.id;\n let state = toolStates.get(toolId);\n if (!state) {\n // Prefer SDK message-level parent (works for parallel agents)\n // Fall back to content-level parent, then timing-based inference\n // Task tools never have a parent (they're top-level)\n const currentParentId = isSubagentToolName(tool.name)\n ? null\n : resolveToolParentId(\n sdkParentToolUseId,\n tool.parentToolUseId,\n getFallbackParentId\n );\n state = {\n name: tool.name,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: currentParentId,\n ...(typeof message.uuid === 'string' && { messageUuid: message.uuid }),\n };\n toolStates.set(toolId, state);\n this.logger.debug(\n `[claude-code] New tool use detected - Tool: ${tool.name}, ID: ${toolId}, SDK parent: ${sdkParentToolUseId}, resolved parent: ${currentParentId}`\n );\n } else if (\n !state.parentToolCallId &&\n sdkParentToolUseId &&\n !isSubagentToolName(tool.name)\n ) {\n // RETROACTIVE PARENT CONTEXT: Tool state was created by streaming events\n // but we now have authoritative parent from SDK message - update state\n state.parentToolCallId = sdkParentToolUseId;\n this.logger.debug(\n `[claude-code] Retroactive parent context - Tool: ${tool.name}, ID: ${toolId}, parent: ${sdkParentToolUseId}`\n );\n }\n\n state.name = tool.name;\n\n if (!state.inputStarted) {\n this.logger.debug(\n `[claude-code] Tool input started - Tool: ${tool.name}, ID: ${toolId}`\n );\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName: tool.name,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n // Track Task tools as active so nested tools can reference them as parent\n if (isSubagentToolName(tool.name)) {\n activeTaskTools.set(toolId, { startTime: Date.now() });\n }\n state.inputStarted = true;\n }\n\n const serializedInput = this.serializeToolInput(tool.input);\n if (serializedInput) {\n let deltaPayload = '';\n\n // First input: emit full delta only if small enough\n if (state.lastSerializedInput === undefined) {\n if (serializedInput.length <= ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE) {\n deltaPayload = serializedInput;\n }\n } else if (\n serializedInput.length <= ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE &&\n state.lastSerializedInput.length <=\n ClaudeCodeLanguageModel.MAX_DELTA_CALC_SIZE &&\n serializedInput.startsWith(state.lastSerializedInput)\n ) {\n deltaPayload = serializedInput.slice(state.lastSerializedInput.length);\n } else if (serializedInput !== state.lastSerializedInput) {\n // Non-prefix updates or large inputs - defer to the final tool-call payload\n deltaPayload = '';\n }\n\n if (deltaPayload) {\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: deltaPayload,\n });\n }\n state.lastSerializedInput = serializedInput;\n }\n }\n\n const text = content\n .map((c: { type: string; text?: string }) => (c.type === 'text' ? c.text : ''))\n .join('');\n\n if (text) {\n // When we've received stream_events, assistant messages contain cumulative text\n // that we've already emitted via stream_event deltas - skip duplicates\n // When no stream_events received, assistant messages contain incremental text\n if (supersedesPriorMessages) {\n // Refusal-fallback replacement: the superseded segments were\n // already retracted on arrival (above); record the\n // replacement text so kept text from earlier assistant\n // messages survives in the accumulators (matches doGenerate).\n textSegments.push({\n ...(typeof message.uuid === 'string' && { uuid: message.uuid }),\n text,\n });\n accumulatedText = textSegments.map((segment) => segment.text).join('');\n\n if (emittedTextSinceLastAssistant === text) {\n // The replacement text was fully streamed via stream_event\n // deltas attributable to THIS message (the window resets when\n // each assistant message is processed, so matches against\n // earlier/refused output cannot false-positive here); the\n // deltas were emitted and cannot be un-streamed, so\n // re-emitting the replacement here would duplicate output.\n streamedTextLength = Math.max(streamedTextLength, text.length);\n this.logger.debug(\n '[claude-code] Skipping text emission for superseding assistant message (replacement already streamed)'\n );\n } else if (\n emittedTextSinceLastAssistant.length > 0 &&\n text.startsWith(emittedTextSinceLastAssistant)\n ) {\n // A PREFIX of the replacement already streamed (e.g. deltas\n // emitted 'Replace' and the final message is 'Replacement\n // answer'). Emit only the unstreamed suffix on the SAME open\n // part - re-emitting the full text as a new part would\n // duplicate the prefix ('ReplaceReplacement answer').\n if (options.responseFormat?.type !== 'json') {\n const suffix = text.slice(emittedTextSinceLastAssistant.length);\n if (suffix) {\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({ type: 'text-start', id: textPartId });\n }\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: suffix,\n });\n emittedTextSinceLastAssistant = text;\n }\n }\n streamedTextLength = Math.max(streamedTextLength, text.length);\n this.logger.debug(\n '[claude-code] Emitted unstreamed suffix of superseding assistant message'\n );\n } else if (options.responseFormat?.type !== 'json') {\n // Without stream_events the canonical replacement was never\n // emitted. The retracted text cannot be un-streamed, so close\n // the open text part and deliver the replacement as a NEW\n // text part instead of dropping the model's actual answer.\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [idx, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(idx);\n break;\n }\n }\n }\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: text,\n });\n streamedTextLength = Math.max(streamedTextLength, text.length);\n this.logger.debug(\n '[claude-code] Emitted superseding assistant message as a new text part (canonical replacement)'\n );\n }\n } else if (hasReceivedStreamEvents) {\n // Calculate delta: only emit text that wasn't already streamed via stream_events\n const newTextStart = streamedTextLength;\n const deltaText = text.length > newTextStart ? text.slice(newTextStart) : '';\n\n // Always accumulate for final result tracking\n accumulatedText = text; // Replace with full text (assistant msg contains full content)\n textSegments.length = 0;\n textSegments.push({\n ...(typeof message.uuid === 'string' && { uuid: message.uuid }),\n text,\n });\n\n // In JSON mode, we accumulate the text and extract JSON at the end\n // Otherwise, stream any new text\n if (options.responseFormat?.type !== 'json' && deltaText) {\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: deltaText,\n });\n }\n\n // Update streamedTextLength to match what we now know is the full text\n streamedTextLength = text.length;\n } else {\n // No stream_events - assistant messages contain incremental text chunks\n accumulatedText += text;\n textSegments.push({\n ...(typeof message.uuid === 'string' && { uuid: message.uuid }),\n text,\n });\n\n // In JSON mode, we accumulate the text and extract JSON at the end\n // Otherwise, stream the text as it comes\n if (options.responseFormat?.type !== 'json') {\n // Emit text-start if this is the first text\n if (!textPartId) {\n textPartId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: textPartId,\n });\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: textPartId,\n delta: text,\n });\n }\n }\n }\n // This assistant message claims all stream-event deltas that\n // preceded it — reset the attribution window for the next one.\n emittedTextSinceLastAssistant = '';\n } else if (message.type === 'user') {\n if (!message.message?.content) {\n this.logger.warn(\n `[claude-code] Unexpected user message structure: missing content field. Message type: ${message.type}. This may indicate an SDK protocol violation.`\n );\n continue;\n }\n\n // A user message signals the end of the current assistant message.\n // Reset text state to ensure the next assistant message starts with a new text part.\n // This prevents text from different assistant messages from being merged together.\n if (textPartId) {\n const closedTextId = textPartId;\n controller.enqueue({\n type: 'text-end',\n id: closedTextId,\n });\n textPartId = undefined;\n // Prevent a later content_block_stop from closing the same text part twice.\n for (const [blockIndex, blockTextId] of textBlocksByIndex) {\n if (blockTextId === closedTextId) {\n textBlocksByIndex.delete(blockIndex);\n break;\n }\n }\n this.logger.debug('[claude-code] Closed text part due to user message');\n }\n // Reset the accumulators unconditionally: in JSON mode no text\n // part is ever opened (textPartId stays undefined), but prose\n // accumulated before a tool call must still be discarded so the\n // final-object extraction (and the missing-structured_output\n // recovery) parse only the last assistant turn's text.\n accumulatedText = '';\n textSegments.length = 0;\n streamedTextLength = 0;\n emittedTextSinceLastAssistant = '';\n\n // Extract parent_tool_use_id from SDK message for late-arriving tool results\n const sdkParentToolUseIdForResults = (\n message as { parent_tool_use_id?: string | null }\n ).parent_tool_use_id;\n\n const content = message.message.content;\n for (const result of this.extractToolResults(content)) {\n if (this.isRetractedToolFrame(result.id, retractedStreamToolIds, 'result')) {\n continue;\n }\n let state = toolStates.get(result.id);\n const toolName =\n result.name ?? state?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool result received - Tool: ${toolName}, ID: ${result.id}`\n );\n\n if (!state) {\n this.logger.warn(\n `[claude-code] Received tool result for unknown tool ID: ${result.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n const resolvedParentId = isSubagentToolName(toolName)\n ? null\n : resolveToolParentId(\n sdkParentToolUseIdForResults,\n undefined,\n getFallbackParentId\n );\n state = {\n name: toolName,\n inputStarted: false,\n inputClosed: false,\n callEmitted: false,\n parentToolCallId: resolvedParentId,\n };\n toolStates.set(result.id, state);\n // Synthesize input lifecycle to preserve ordering when no prior tool_use was seen\n if (!state.inputStarted) {\n controller.enqueue({\n type: 'tool-input-start',\n id: result.id,\n toolName,\n providerExecuted: true,\n dynamic: true, // V3 field: indicates tool is provider-defined\n providerMetadata: {\n 'claude-code': {\n parentToolCallId: state.parentToolCallId ?? null,\n },\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n state.inputStarted = true;\n }\n if (!state.inputClosed) {\n controller.enqueue({\n type: 'tool-input-end',\n id: result.id,\n });\n state.inputClosed = true;\n }\n }\n state.name = toolName;\n\n emitToolCall(result.id, state);\n\n // Remove Task tools from active set when they complete\n if (isSubagentToolName(toolName)) {\n activeTaskTools.delete(result.id);\n }\n\n controller.enqueue(\n this.buildToolResultPart(\n result.id,\n toolName,\n result.result,\n result.isError,\n state.parentToolCallId\n )\n );\n }\n // Handle tool errors\n for (const error of this.extractToolErrors(content)) {\n if (this.isRetractedToolFrame(error.id, retractedStreamToolIds, 'error')) {\n continue;\n }\n let state = toolStates.get(error.id);\n const toolName =\n error.name ?? state?.name ?? ClaudeCodeLanguageModel.UNKNOWN_TOOL_NAME;\n\n this.logger.debug(\n `[claude-code] Tool error received - Tool: ${toolName}, ID: ${error.id}`\n );\n\n if (!state) {\n this.logger.warn(\n `[claude-code] Received tool error for unknown tool ID: ${error.id}`\n );\n // Use SDK parent if available, otherwise fall back to timing-based inference\n const errorResolvedParentId = isSubagentToolName(toolName)\n ? null\n : resolveToolParentId(\n sdkParentToolUseIdForResults,\n undefined,\n getFallbackParentId\n );\n state = {\n name: toolName,\n inputStarted: true,\n inputClosed: true,\n callEmitted: false,\n parentToolCallId: errorResolvedParentId,\n };\n toolStates.set(error.id, state);\n }\n\n // Ensure tool-call is emitted before tool-error\n emitToolCall(error.id, state);\n\n // Remove Task tools from active set when they error\n if (isSubagentToolName(toolName)) {\n activeTaskTools.delete(error.id);\n }\n\n controller.enqueue(\n this.buildToolErrorPart(error.id, toolName, error.error, state.parentToolCallId)\n );\n }\n } else if (message.type === 'result') {\n done();\n this.mergeResultPermissionDenials(message, metadataTracking);\n\n // Handle is_error flag in result message (e.g., auth failures).\n // SDKResultSuccess carries the error text in `result`; SDKResultError\n // has no `result` field and carries details in `errors` instead.\n if ('is_error' in message && message.is_error === true) {\n const resultText =\n 'result' in message && typeof message.result === 'string'\n ? message.result\n : undefined;\n const errorsText =\n 'errors' in message && Array.isArray(message.errors)\n ? message.errors.filter((e): e is string => typeof e === 'string').join('; ')\n : '';\n const errorMessage =\n resultText ?? (errorsText || 'Claude Code CLI returned an error');\n throw Object.assign(new Error(errorMessage), {\n exitCode: 1,\n errorKind: lastAssistantErrorKind,\n });\n }\n\n // Handle structured output errors (SDK 0.1.45+)\n // Use string comparison to support new SDK subtypes not yet in TypeScript definitions\n if ((message.subtype as string) === 'error_max_structured_output_retries') {\n throw new Error(\n 'Failed to generate valid structured output after maximum retries. The model could not produce a response matching the required schema.'\n );\n }\n\n this.logger.info(\n `[claude-code] Stream completed - Session: ${message.session_id}, Cost: $${message.total_cost_usd?.toFixed(4) ?? 'N/A'}, Duration: ${message.duration_ms ?? 'N/A'}ms`\n );\n\n if ('usage' in message) {\n usage = convertClaudeCodeUsage(message.usage);\n\n this.logger.debug(\n `[claude-code] Stream token usage - Input: ${usage.inputTokens.total}, Output: ${usage.outputTokens.total}`\n );\n }\n\n const stopReason =\n 'stop_reason' in message\n ? ((message as Record<string, unknown>).stop_reason as string | null | undefined)\n : undefined;\n const finishReason: LanguageModelV3FinishReason = mapClaudeCodeFinishReason(\n message.subtype,\n stopReason\n );\n\n this.logger.debug(`[claude-code] Stream finish reason: ${finishReason.unified}`);\n\n // Store session ID in the model instance\n this.setSessionId(message.session_id);\n\n // Use structured output from SDK if available (native JSON schema support)\n const structuredOutput =\n 'structured_output' in message ? message.structured_output : undefined;\n\n // Check if we've already streamed JSON via input_json_delta\n const alreadyStreamedJson =\n hasStreamedJson &&\n options.responseFormat?.type === 'json' &&\n hasReceivedStreamEvents;\n\n if (alreadyStreamedJson) {\n // We've already streamed JSON deltas; only close the text part if it's still open.\n if (textPartId) {\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n }\n } else if (structuredOutput !== undefined) {\n // Emit structured output as text (fallback when streaming didn't occur)\n const jsonTextId = generateId();\n const jsonText = JSON.stringify(structuredOutput);\n controller.enqueue({\n type: 'text-start',\n id: jsonTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: jsonTextId,\n delta: jsonText,\n });\n controller.enqueue({\n type: 'text-end',\n id: jsonTextId,\n });\n } else if (\n options.responseFormat?.type === 'json' &&\n options.responseFormat.schema !== undefined &&\n finishReason.unified === 'stop'\n ) {\n // Loud failure / graceful recovery (mirrors doGenerate): the\n // CLI can return a SUCCESSFUL result without structured_output\n // when the schema contains constructs it cannot enforce,\n // silently falling back to prose. Try to recover JSON from the\n // accumulated prose; otherwise fail with a descriptive,\n // non-retryable error instead of streaming prose that ends in\n // an opaque AI_NoObjectGeneratedError downstream.\n const recoveredJsonText = extractJsonObjectText(accumulatedText);\n if (recoveredJsonText === undefined) {\n throw createAPICallError({\n message: MISSING_STRUCTURED_OUTPUT_ERROR_MESSAGE,\n promptExcerpt: messagesPrompt.substring(0, 200),\n isRetryable: false,\n });\n }\n this.logger.warn(\n '[claude-code] outputFormat was requested but the CLI returned no structured_output; recovered JSON by parsing the prose response. The schema likely contains constructs the CLI cannot enforce - see the README structured-output limitations.'\n );\n if (textPartId) {\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n }\n const recoveredTextId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: recoveredTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: recoveredTextId,\n delta: recoveredJsonText,\n });\n controller.enqueue({\n type: 'text-end',\n id: recoveredTextId,\n });\n } else if (textPartId) {\n // Close the text part if it was opened (non-JSON mode)\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n } else if (accumulatedText && !textStreamedViaContentBlock) {\n // Fallback for JSON mode without schema: emit accumulated text\n // This handles the case where responseFormat.type === 'json' but no schema\n // was provided, so the SDK returns plain text instead of structured_output\n const fallbackTextId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: fallbackTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: fallbackTextId,\n delta: accumulatedText,\n });\n controller.enqueue({\n type: 'text-end',\n id: fallbackTextId,\n });\n }\n\n finalizeToolCalls();\n\n // Prepare JSON-safe warnings for provider metadata\n const warningsJson = this.serializeWarningsForMetadata(streamWarnings);\n\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage,\n providerMetadata: {\n 'claude-code': {\n sessionId: message.session_id,\n ...(message.total_cost_usd !== undefined && {\n costUsd: message.total_cost_usd,\n }),\n ...(message.duration_ms !== undefined && { durationMs: message.duration_ms }),\n ...(message.modelUsage !== undefined && {\n modelUsage: message.modelUsage as unknown as JSONValue,\n }),\n // SDK 0.3.x timing metadata (ttft_* only present on SDKResultSuccess)\n ...('ttft_ms' in message &&\n message.ttft_ms !== undefined && { ttftMs: message.ttft_ms }),\n ...('ttft_stream_ms' in message &&\n message.ttft_stream_ms !== undefined && {\n ttftStreamMs: message.ttft_stream_ms,\n }),\n ...('time_to_request_ms' in message &&\n message.time_to_request_ms !== undefined && {\n timeToRequestMs: message.time_to_request_ms,\n }),\n ...('warm_spare_claimed' in message &&\n message.warm_spare_claimed !== undefined && {\n warmSpareClaimed: message.warm_spare_claimed,\n }),\n ...(message.terminal_reason !== undefined && {\n terminalReason: message.terminal_reason,\n }),\n ...(metadataTracking.apiRetries > 0 && {\n apiRetries: metadataTracking.apiRetries,\n }),\n ...(metadataTracking.permissionDenials.length > 0 && {\n permissionDenials: metadataTracking.permissionDenials as unknown as JSONValue,\n }),\n ...(metadataTracking.mirrorErrors.length > 0 && {\n mirrorErrors: metadataTracking.mirrorErrors as unknown as JSONValue,\n }),\n ...(metadataTracking.estimatedThinkingTokens > 0 && {\n estimatedThinkingTokens: metadataTracking.estimatedThinkingTokens,\n }),\n // JSON validation warnings are collected during streaming and included\n // in providerMetadata since the AI SDK's finish event doesn't support\n // a top-level warnings field (unlike stream-start which was already emitted)\n ...(streamWarnings.length > 0 && {\n warnings: warningsJson as unknown as JSONValue,\n }),\n },\n },\n });\n controller.close();\n\n // The prompt_suggestion message (promptSuggestions: true) arrives\n // AFTER the result message, so the AI SDK stream has already\n // finished above. Drain the remaining SDK messages to deliver it\n // via the callback; only done when a callback is registered so\n // everyone else keeps the immediate return-on-result behavior.\n // The drain is bounded: the SDK emits at most one prompt_suggestion\n // per turn, so stop once it is delivered, and a timeout closes the\n // iterator (tearing down the subprocess) if the CLI lingers after\n // the result without emitting one.\n // Drain for the post-result prompt_suggestion only when\n // suggestions can be emitted (promptSuggestions absent or true;\n // disabled only when explicitly false), skipping the up-to-10s\n // drain in the explicit-false case.\n const effectivePromptSuggestions =\n sdkOptions?.promptSuggestions ?? this.settings.promptSuggestions;\n if (this.settings.onPromptSuggestion && effectivePromptSuggestions !== false) {\n await this.drainPromptSuggestion(response, this.settings.onPromptSuggestion);\n }\n return;\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.logMcpConnectionIssues(message.mcp_servers);\n\n // Store session ID for future use\n this.setSessionId(message.session_id);\n\n this.logger.info(`[claude-code] Stream session initialized: ${message.session_id}`);\n\n // Emit response metadata when session is initialized\n controller.enqueue({\n type: 'response-metadata',\n id: message.session_id,\n timestamp: new Date(),\n modelId: this.modelId,\n });\n } else if (message.type === 'system') {\n this.handleSystemMessage(\n message,\n metadataTracking,\n buildRetractionEvictor(evictLive)\n );\n } else if (message.type === 'prompt_suggestion') {\n // Defensive: normally arrives after the result message (handled by\n // the post-finish drain above), but consume it here if it arrives early.\n this.logger.debug('[claude-code] Received prompt suggestion');\n this.settings.onPromptSuggestion?.(message.suggestion);\n }\n }\n\n finalizeToolCalls();\n this.logger.debug('[claude-code] Stream finalized, closing stream');\n controller.close();\n } catch (error: unknown) {\n done();\n\n this.logger.debug(\n `[claude-code] Error during doStream: ${error instanceof Error ? error.message : String(error)}`\n );\n\n if (isClaudeCodeTruncationError(error, accumulatedText)) {\n this.logger.warn(\n `[claude-code] Detected truncated stream response, returning ${accumulatedText.length} characters of buffered text`\n );\n const truncationWarning: SharedV3Warning = {\n type: 'other',\n message: CLAUDE_CODE_TRUNCATION_WARNING,\n };\n streamWarnings.push(truncationWarning);\n\n if (textPartId) {\n controller.enqueue({\n type: 'text-end',\n id: textPartId,\n });\n } else if (accumulatedText && !textStreamedViaContentBlock) {\n const fallbackTextId = generateId();\n controller.enqueue({\n type: 'text-start',\n id: fallbackTextId,\n });\n controller.enqueue({\n type: 'text-delta',\n id: fallbackTextId,\n delta: accumulatedText,\n });\n controller.enqueue({\n type: 'text-end',\n id: fallbackTextId,\n });\n }\n\n finalizeToolCalls();\n\n const warningsJson = this.serializeWarningsForMetadata(streamWarnings);\n\n controller.enqueue({\n type: 'finish',\n finishReason: { unified: 'length', raw: 'truncation' },\n usage,\n providerMetadata: {\n 'claude-code': {\n ...(this.sessionId !== undefined && { sessionId: this.sessionId }),\n truncated: true,\n ...(metadataTracking.apiRetries > 0 && {\n apiRetries: metadataTracking.apiRetries,\n }),\n ...(metadataTracking.permissionDenials.length > 0 && {\n permissionDenials: metadataTracking.permissionDenials as unknown as JSONValue,\n }),\n ...(metadataTracking.mirrorErrors.length > 0 && {\n mirrorErrors: metadataTracking.mirrorErrors as unknown as JSONValue,\n }),\n ...(metadataTracking.estimatedThinkingTokens > 0 && {\n estimatedThinkingTokens: metadataTracking.estimatedThinkingTokens,\n }),\n ...(streamWarnings.length > 0 && {\n warnings: warningsJson as unknown as JSONValue,\n }),\n },\n },\n });\n\n controller.close();\n return;\n }\n\n finalizeToolCalls();\n let errorToEmit: unknown;\n\n // Special handling for AbortError to preserve abort signal reason\n if (isAbortError(error)) {\n errorToEmit = options.abortSignal?.aborted ? options.abortSignal.reason : error;\n } else {\n // Use unified error handler\n errorToEmit = this.handleClaudeCodeError(error, messagesPrompt, collectedStderr);\n }\n\n // Emit error as a stream part\n controller.enqueue({\n type: 'error',\n error: errorToEmit,\n });\n\n controller.close();\n } finally {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n }\n },\n cancel: () => {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n },\n });\n\n return {\n stream: stream as unknown as ReadableStream<LanguageModelV3StreamPart>,\n request: {\n body: messagesPrompt,\n },\n };\n }\n\n private serializeWarningsForMetadata(warnings: SharedV3Warning[]): JSONValue {\n const result = warnings.map((w) => {\n const base: Record<string, string> = { type: w.type };\n if ('message' in w) {\n const m = (w as { message?: unknown }).message;\n if (m !== undefined) base.message = String(m);\n }\n if (w.type === 'unsupported' || w.type === 'compatibility') {\n const feature = (w as { feature: unknown }).feature;\n if (feature !== undefined) base.feature = String(feature);\n if ('details' in w) {\n const d = (w as { details?: unknown }).details;\n if (d !== undefined) base.details = String(d);\n }\n }\n return base;\n });\n return result as unknown as JSONValue;\n }\n}\n","import type { ModelMessage } from 'ai';\nimport type { SDKUserMessage } from '@anthropic-ai/claude-agent-sdk';\n\ntype SDKUserContentPart = SDKUserMessage['message']['content'][number];\n\ninterface StreamingSegment {\n formatted: string;\n}\n\nconst IMAGE_URL_WARNING = 'Image URLs are not supported by this provider; supply base64/data URLs.';\nconst IMAGE_CONVERSION_WARNING = 'Unable to convert image content; supply base64/data URLs.';\n\n/**\n * Maximum serialized length for a single tool-call input when replaying\n * conversation history. Mirrors the spirit of the model's tool-result\n * truncation (maxToolResultSize): the live turn saw the full data, history\n * replay only needs enough context to stay coherent. Inputs longer than this\n * are cut and suffixed with '...[truncated]'.\n */\nconst MAX_TOOL_CALL_INPUT_LENGTH = 1000;\n\n/**\n * Serializes a tool-call input to a bounded JSON string for history replay.\n * Non-JSON-serializable inputs fall back to String(); oversized payloads are\n * truncated at MAX_TOOL_CALL_INPUT_LENGTH with a '...[truncated]' suffix.\n */\nfunction serializeToolCallInput(input: unknown): string {\n let serialized: string;\n if (input === undefined) {\n serialized = '';\n } else {\n try {\n serialized = JSON.stringify(input) ?? String(input);\n } catch {\n serialized = String(input);\n }\n }\n\n if (serialized.length > MAX_TOOL_CALL_INPUT_LENGTH) {\n return `${serialized.slice(0, MAX_TOOL_CALL_INPUT_LENGTH)}...[truncated]`;\n }\n return serialized;\n}\n\nfunction normalizeBase64(base64: string): string {\n return base64.replace(/\\s+/g, '');\n}\n\nfunction isImageMimeType(mimeType?: string): boolean {\n return typeof mimeType === 'string' && mimeType.trim().toLowerCase().startsWith('image/');\n}\n\nfunction createImageContent(mediaType: string, data: string): SDKUserContentPart | undefined {\n const trimmedType = mediaType.trim();\n const trimmedData = normalizeBase64(data.trim());\n\n if (!trimmedType || !trimmedData) {\n return undefined;\n }\n\n return {\n type: 'image',\n source: {\n type: 'base64',\n media_type: trimmedType,\n data: trimmedData,\n },\n } as SDKUserContentPart;\n}\n\nfunction extractMimeType(candidate: unknown): string | undefined {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim();\n }\n return undefined;\n}\n\nfunction parseObjectImage(\n imageObj: Record<string, unknown>,\n fallbackMimeType?: string\n): SDKUserContentPart | undefined {\n const data = typeof imageObj.data === 'string' ? imageObj.data : undefined;\n const mimeType = extractMimeType(\n imageObj.mimeType ?? imageObj.mediaType ?? imageObj.media_type ?? fallbackMimeType\n );\n if (!data || !mimeType) {\n return undefined;\n }\n return createImageContent(mimeType, data);\n}\n\nfunction parseStringImage(\n value: string,\n fallbackMimeType?: string\n): { content?: SDKUserContentPart; warning?: string } {\n const trimmed = value.trim();\n\n if (/^https?:\\/\\//i.test(trimmed)) {\n return { warning: IMAGE_URL_WARNING };\n }\n\n const dataUrlMatch = trimmed.match(/^data:([^;]+);base64,(.+)$/i);\n if (dataUrlMatch) {\n const [, mediaType, data] = dataUrlMatch;\n const content = createImageContent(mediaType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n const base64Match = trimmed.match(/^base64:([^,]+),(.+)$/i);\n if (base64Match) {\n const [, explicitMimeType, data] = base64Match;\n const content = createImageContent(explicitMimeType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n if (fallbackMimeType) {\n const content = createImageContent(fallbackMimeType, trimmed);\n if (content) {\n return { content };\n }\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\nfunction parseImagePart(part: unknown): { content?: SDKUserContentPart; warning?: string } {\n if (!part || typeof part !== 'object') {\n return { warning: IMAGE_CONVERSION_WARNING };\n }\n\n const imageValue = (part as { image?: unknown }).image;\n const mimeType = extractMimeType((part as { mimeType?: unknown }).mimeType);\n\n if (typeof imageValue === 'string') {\n return parseStringImage(imageValue, mimeType);\n }\n\n if (imageValue && typeof imageValue === 'object') {\n const content = parseObjectImage(imageValue as Record<string, unknown>, mimeType);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\nfunction convertBinaryToBase64(data: Uint8Array | ArrayBuffer): string | undefined {\n if (typeof Buffer !== 'undefined') {\n const buffer =\n data instanceof Uint8Array ? Buffer.from(data) : Buffer.from(new Uint8Array(data));\n return buffer.toString('base64');\n }\n\n if (typeof btoa === 'function') {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n let binary = '';\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize);\n binary += String.fromCharCode(...chunk);\n }\n return btoa(binary);\n }\n\n return undefined;\n}\n\ntype FileLikePart = {\n mediaType?: unknown;\n mimeType?: unknown;\n data?: unknown;\n};\n\nfunction parseFilePart(part: FileLikePart): { content?: SDKUserContentPart; warning?: string } {\n const mimeType = extractMimeType(part.mediaType ?? part.mimeType);\n if (!mimeType || !isImageMimeType(mimeType)) {\n return {};\n }\n\n const data = part.data;\n if (typeof data === 'string') {\n const content = createImageContent(mimeType, data);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n if (\n data instanceof Uint8Array ||\n (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n ) {\n const base64 = convertBinaryToBase64(data);\n if (!base64) {\n return { warning: IMAGE_CONVERSION_WARNING };\n }\n const content = createImageContent(mimeType, base64);\n return content ? { content } : { warning: IMAGE_CONVERSION_WARNING };\n }\n\n return { warning: IMAGE_CONVERSION_WARNING };\n}\n\n/**\n * Converts AI SDK prompt format to Claude Code SDK message format.\n * Handles system prompts, user messages, assistant responses, and tool interactions.\n *\n * @param prompt - The AI SDK prompt containing messages\n * @returns An object containing the formatted message prompt and optional system prompt\n *\n * @example\n * ```typescript\n * const { messagesPrompt } = convertToClaudeCodeMessages(\n * [{ role: 'user', content: 'Hello!' }]\n * );\n * ```\n *\n * @remarks\n * - Image parts are collected for streaming input; unsupported variants produce warnings\n * - Tool calls are serialized one per line as `[Tool call: name({...input})]`\n * (inputs truncated at 1000 characters), pairing with `Tool Result (name): ...` lines\n * - JSON schema enforcement is handled natively by the SDK's outputFormat option (v0.1.45+)\n */\nexport function convertToClaudeCodeMessages(prompt: readonly ModelMessage[]): {\n messagesPrompt: string;\n systemPrompt?: string;\n warnings?: string[];\n streamingContentParts: SDKUserMessage['message']['content'];\n hasImageParts: boolean;\n} {\n const messages: string[] = [];\n const warnings: string[] = [];\n let systemPrompt: string | undefined;\n const streamingSegments: StreamingSegment[] = [];\n const imageMap = new Map<number, SDKUserContentPart[]>();\n let hasImageParts = false;\n\n const addSegment = (formatted: string): number => {\n streamingSegments.push({ formatted });\n return streamingSegments.length - 1;\n };\n\n const addImageForSegment = (segmentIndex: number, content: SDKUserContentPart): void => {\n hasImageParts = true;\n if (!imageMap.has(segmentIndex)) {\n imageMap.set(segmentIndex, []);\n }\n imageMap.get(segmentIndex)?.push(content);\n };\n\n for (const message of prompt) {\n switch (message.role) {\n case 'system':\n systemPrompt = message.content;\n if (typeof message.content === 'string' && message.content.trim().length > 0) {\n addSegment(message.content);\n } else {\n addSegment('');\n }\n break;\n\n case 'user':\n if (typeof message.content === 'string') {\n messages.push(message.content);\n addSegment(`Human: ${message.content}`);\n } else {\n // Handle multi-part content\n const textParts = message.content\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n\n const segmentIndex = addSegment(textParts ? `Human: ${textParts}` : '');\n\n if (textParts) {\n messages.push(textParts);\n }\n\n for (const part of message.content) {\n if (part.type === 'image') {\n const { content, warning } = parseImagePart(part);\n if (content) {\n addImageForSegment(segmentIndex, content);\n } else if (warning) {\n warnings.push(warning);\n }\n } else if (part.type === 'file') {\n const { content, warning } = parseFilePart(part);\n if (content) {\n addImageForSegment(segmentIndex, content);\n } else if (warning) {\n warnings.push(warning);\n }\n }\n }\n }\n break;\n\n case 'assistant': {\n let assistantContent = '';\n if (typeof message.content === 'string') {\n assistantContent = message.content;\n } else {\n const textParts = message.content\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n\n if (textParts) {\n assistantContent = textParts;\n }\n\n // Serialize tool calls so replayed history keeps tool context.\n // One line per call, pairing with the \"Tool Result (name): ...\" lines\n // emitted for tool messages below.\n const toolCalls = message.content.filter((part) => part.type === 'tool-call');\n if (toolCalls.length > 0) {\n const serializedCalls = toolCalls\n .map((call) => `[Tool call: ${call.toolName}(${serializeToolCallInput(call.input)})]`)\n .join('\\n');\n assistantContent += assistantContent ? `\\n${serializedCalls}` : serializedCalls;\n }\n }\n const formattedAssistant = `Assistant: ${assistantContent}`;\n messages.push(formattedAssistant);\n addSegment(formattedAssistant);\n break;\n }\n\n case 'tool':\n // Tool results could be included in the conversation\n // Filter out ToolApprovalResponse parts, only process ToolResultPart\n for (const tool of message.content) {\n if (tool.type === 'tool-approval-response') {\n continue; // Skip approval responses\n }\n // Handle different ToolResultOutput types\n let resultText: string;\n const output = tool.output;\n if (output.type === 'text' || output.type === 'error-text') {\n resultText = output.value;\n } else if (output.type === 'json' || output.type === 'error-json') {\n resultText = JSON.stringify(output.value);\n } else if (output.type === 'execution-denied') {\n resultText = `[Execution denied${output.reason ? `: ${output.reason}` : ''}]`;\n } else if (output.type === 'content') {\n // Handle content array - extract text parts\n resultText = output.value\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n } else {\n resultText = '[Unknown output type]';\n }\n const formattedToolResult = `Tool Result (${tool.toolName}): ${resultText}`;\n messages.push(formattedToolResult);\n addSegment(formattedToolResult);\n }\n break;\n }\n }\n\n // For the SDK, we need to provide a single prompt string\n // Format the conversation history properly\n\n // Combine system prompt with messages\n let finalPrompt = '';\n\n // Add system prompt at the beginning if present\n if (systemPrompt) {\n finalPrompt = systemPrompt;\n }\n\n if (messages.length > 0) {\n // Format messages\n const formattedMessages = [];\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Check if this is a user or assistant message based on content\n if (msg.startsWith('Assistant:') || msg.startsWith('Tool Result')) {\n formattedMessages.push(msg);\n } else {\n // User messages\n formattedMessages.push(`Human: ${msg}`);\n }\n }\n\n // Combine system prompt with messages\n if (finalPrompt) {\n const joinedMessages = formattedMessages.join('\\n\\n');\n finalPrompt = joinedMessages ? `${finalPrompt}\\n\\n${joinedMessages}` : finalPrompt;\n } else {\n finalPrompt = formattedMessages.join('\\n\\n');\n }\n }\n\n // Build streaming parts including text and images\n const streamingParts: SDKUserContentPart[] = [];\n const imagePartsInOrder: SDKUserContentPart[] = [];\n\n const appendImagesForIndex = (index: number) => {\n const images = imageMap.get(index);\n if (!images) {\n return;\n }\n images.forEach((image) => {\n streamingParts.push(image);\n imagePartsInOrder.push(image);\n });\n };\n\n if (streamingSegments.length > 0) {\n let accumulatedText = '';\n let emittedText = false;\n\n const flushText = () => {\n if (!accumulatedText) {\n return;\n }\n streamingParts.push({ type: 'text', text: accumulatedText });\n accumulatedText = '';\n emittedText = true;\n };\n\n streamingSegments.forEach((segment, index) => {\n const segmentText = segment.formatted;\n if (segmentText) {\n if (!accumulatedText) {\n accumulatedText = emittedText ? `\\n\\n${segmentText}` : segmentText;\n } else {\n accumulatedText += `\\n\\n${segmentText}`;\n }\n }\n\n if (imageMap.has(index)) {\n flushText();\n appendImagesForIndex(index);\n }\n });\n\n flushText();\n }\n\n // Note: JSON schema enforcement is now handled natively by the SDK's outputFormat option (v0.1.45+)\n // No prompt injection needed - structured outputs are guaranteed by the SDK\n\n return {\n messagesPrompt: finalPrompt,\n systemPrompt,\n ...(warnings.length > 0 && { warnings }),\n streamingContentParts:\n streamingParts.length > 0\n ? (streamingParts as SDKUserMessage['message']['content'])\n : ([\n { type: 'text', text: finalPrompt },\n ...imagePartsInOrder,\n ] as SDKUserMessage['message']['content']),\n hasImageParts,\n };\n}\n","import { APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\n\n/**\n * Metadata associated with Claude Code SDK errors.\n * Provides additional context about command execution failures.\n */\nexport interface ClaudeCodeErrorMetadata {\n /**\n * Error code from the CLI process (e.g., 'ENOENT', 'ETIMEDOUT').\n */\n code?: string;\n\n /**\n * Exit code from the Claude Code SDK process.\n * Common codes:\n * - 401: Authentication error\n * - 1: General error\n */\n exitCode?: number;\n\n /**\n * Standard error output from the CLI process.\n */\n stderr?: string;\n\n /**\n * Excerpt from the prompt that caused the error.\n * Limited to first 200 characters for debugging.\n */\n promptExcerpt?: string;\n}\n\n/**\n * Creates an APICallError with Claude Code specific metadata.\n * Used for general CLI execution errors.\n *\n * @param options - Error details and metadata\n * @param options.message - Human-readable error message\n * @param options.code - Error code from the CLI process\n * @param options.exitCode - Exit code from the CLI\n * @param options.stderr - Standard error output\n * @param options.promptExcerpt - Excerpt of the prompt that caused the error\n * @param options.isRetryable - Whether the error is potentially retryable\n * @returns An APICallError instance with Claude Code metadata\n *\n * @example\n * ```typescript\n * throw createAPICallError({\n * message: 'Claude Code SDK failed',\n * code: 'ENOENT',\n * isRetryable: true\n * });\n * ```\n */\nexport function createAPICallError({\n message,\n code,\n exitCode,\n stderr,\n promptExcerpt,\n isRetryable = false,\n}: ClaudeCodeErrorMetadata & {\n message: string;\n isRetryable?: boolean;\n}): APICallError {\n const metadata: ClaudeCodeErrorMetadata = {\n code,\n exitCode,\n stderr,\n promptExcerpt,\n };\n\n return new APICallError({\n message,\n isRetryable,\n url: 'claude-code-cli://command',\n requestBodyValues: promptExcerpt ? { prompt: promptExcerpt } : undefined,\n data: metadata,\n });\n}\n\n/**\n * Creates an authentication error for Claude Code SDK login failures.\n *\n * @param options - Error configuration\n * @param options.message - Error message describing the authentication failure\n * @returns A LoadAPIKeyError instance\n *\n * @example\n * ```typescript\n * throw createAuthenticationError({\n * message: 'Please run \"claude auth login\" to authenticate'\n * });\n * ```\n */\nexport function createAuthenticationError({ message }: { message: string }): LoadAPIKeyError {\n return new LoadAPIKeyError({\n message:\n message || 'Authentication failed. Please ensure Claude Code SDK is properly authenticated.',\n });\n}\n\n/**\n * Creates a timeout error for Claude Code SDK operations.\n *\n * @param options - Timeout error details\n * @param options.message - Error message describing the timeout\n * @param options.promptExcerpt - Excerpt of the prompt that timed out\n * @param options.timeoutMs - Timeout duration in milliseconds\n * @returns An APICallError instance configured as a timeout error\n *\n * @example\n * ```typescript\n * throw createTimeoutError({\n * message: 'Request timed out after 2 minutes',\n * timeoutMs: 120000\n * });\n * ```\n */\nexport function createTimeoutError({\n message,\n promptExcerpt,\n timeoutMs,\n}: {\n message: string;\n promptExcerpt?: string;\n timeoutMs?: number;\n}): APICallError {\n // Store timeoutMs in metadata for potential use by error handlers\n const metadata: ClaudeCodeErrorMetadata = {\n code: 'TIMEOUT',\n promptExcerpt,\n };\n\n return new APICallError({\n message,\n isRetryable: true,\n url: 'claude-code-cli://command',\n requestBodyValues: promptExcerpt ? { prompt: promptExcerpt } : undefined,\n data: timeoutMs !== undefined ? { ...metadata, timeoutMs } : metadata,\n });\n}\n\n/**\n * Checks if an error is an authentication error.\n * Returns true for LoadAPIKeyError instances or APICallError with exit code 401.\n *\n * @param error - The error to check\n * @returns True if the error is an authentication error\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * if (isAuthenticationError(error)) {\n * console.log('Please authenticate with Claude Code SDK');\n * }\n * }\n * ```\n */\nexport function isAuthenticationError(error: unknown): boolean {\n if (error instanceof LoadAPIKeyError) return true;\n if (error instanceof APICallError && (error.data as ClaudeCodeErrorMetadata)?.exitCode === 401)\n return true;\n return false;\n}\n\n/**\n * Checks if an error is a timeout error.\n * Returns true for APICallError instances with code 'TIMEOUT'.\n *\n * @param error - The error to check\n * @returns True if the error is a timeout error\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * if (isTimeoutError(error)) {\n * console.log('Request timed out, consider retrying');\n * }\n * }\n * ```\n */\nexport function isTimeoutError(error: unknown): boolean {\n if (error instanceof APICallError && (error.data as ClaudeCodeErrorMetadata)?.code === 'TIMEOUT')\n return true;\n return false;\n}\n\n/**\n * Extracts Claude Code error metadata from an error object.\n *\n * @param error - The error to extract metadata from\n * @returns The error metadata if available, undefined otherwise\n *\n * @example\n * ```typescript\n * try {\n * await model.generate(...);\n * } catch (error) {\n * const metadata = getErrorMetadata(error);\n * if (metadata?.exitCode === 401) {\n * console.log('Authentication required');\n * }\n * }\n * ```\n */\nexport function getErrorMetadata(error: unknown): ClaudeCodeErrorMetadata | undefined {\n if (error instanceof APICallError && error.data) {\n return error.data as ClaudeCodeErrorMetadata;\n }\n return undefined;\n}\n","import type { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\n/**\n * Maps Claude Code SDK result subtypes to AI SDK finish reasons.\n *\n * When `stopReason` is provided (from the SDK's `stop_reason` field), it takes\n * priority for mapping well-known Anthropic API stop reasons. Otherwise, falls\n * back to the existing subtype-based mapping.\n *\n * @param subtype - The result subtype from Claude Code SDK\n * @param stopReason - The optional stop_reason from SDKResultSuccess/SDKResultError (v0.2.31+)\n * @returns The corresponding AI SDK finish reason with unified and raw values\n *\n * @example\n * ```typescript\n * // With stop_reason (preferred when available)\n * mapClaudeCodeFinishReason('success', 'end_turn');\n * // Returns: { unified: 'stop', raw: 'end_turn' }\n *\n * // Without stop_reason (backward compatible)\n * mapClaudeCodeFinishReason('error_max_turns');\n * // Returns: { unified: 'length', raw: 'error_max_turns' }\n * ```\n */\nexport function mapClaudeCodeFinishReason(\n subtype?: string,\n stopReason?: string | null\n): LanguageModelV3FinishReason {\n // When stop_reason is present and non-null, map known Anthropic API stop reasons\n if (stopReason != null) {\n switch (stopReason) {\n case 'end_turn':\n return { unified: 'stop', raw: 'end_turn' };\n case 'max_tokens':\n return { unified: 'length', raw: 'max_tokens' };\n case 'stop_sequence':\n return { unified: 'stop', raw: 'stop_sequence' };\n case 'tool_use':\n return { unified: 'tool-calls', raw: 'tool_use' };\n default:\n // Unknown stop_reason: fall back to subtype mapping but preserve stop_reason as raw\n break;\n }\n }\n\n // Fall back to subtype-based mapping\n const raw = stopReason ?? subtype;\n switch (subtype) {\n case 'success':\n return { unified: 'stop', raw };\n case 'error_max_turns':\n return { unified: 'length', raw };\n case 'error_during_execution':\n return { unified: 'error', raw };\n case undefined:\n return { unified: 'stop', raw };\n default:\n return { unified: 'other', raw };\n }\n}\n","import { z } from 'zod';\nimport { existsSync } from 'fs';\n\n/**\n * Validation schemas and utilities for Claude Code provider inputs.\n * Uses Zod for type-safe validation following AI SDK patterns.\n */\n\n/**\n * The SDK/CLI treats a blank or whitespace-only resume id as absent (there is\n * no session to resume). This is the single source of truth for that rule so\n * the \"blank means no resume\" predicate lives in exactly one place, shared by\n * both query-time resolution (claude-code-language-model.ts) and\n * construction-time validation (effectiveResumeId below).\n */\nexport function isBlankResume(value: unknown): boolean {\n return typeof value === 'string' && value.trim() === '';\n}\n\n// Helper for Zod v3/v4 compatibility\n// Use a simple z.any() for functions to work with both versions\nconst loggerFunctionSchema = z.object({\n debug: z.any().refine((val) => typeof val === 'function', {\n message: 'debug must be a function',\n }),\n info: z.any().refine((val) => typeof val === 'function', {\n message: 'info must be a function',\n }),\n warn: z.any().refine((val) => typeof val === 'function', {\n message: 'warn must be a function',\n }),\n error: z.any().refine((val) => typeof val === 'function', {\n message: 'error must be a function',\n }),\n});\n\n/**\n * Schema for validating Claude Code settings.\n * Ensures all settings are within acceptable ranges and formats.\n */\nexport const claudeCodeSettingsSchema = z\n .object({\n pathToClaudeCodeExecutable: z.string().optional(),\n customSystemPrompt: z.string().optional(),\n appendSystemPrompt: z.string().optional(),\n systemPrompt: z\n .union([\n z.string(),\n z.array(z.string()),\n z.object({\n type: z.literal('preset'),\n preset: z.literal('claude_code'),\n append: z.string().optional(),\n excludeDynamicSections: z.boolean().optional(),\n }),\n ])\n .optional(),\n maxTurns: z.number().int().min(1).max(100).optional(),\n maxThinkingTokens: z.number().int().positive().max(100000).optional(),\n thinking: z\n .union([\n z\n .object({\n type: z.literal('adaptive'),\n display: z.enum(['summarized', 'omitted']).optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal('enabled'),\n budgetTokens: z.number().int().positive().optional(),\n display: z.enum(['summarized', 'omitted']).optional(),\n })\n .strict(),\n z.object({ type: z.literal('disabled') }).strict(),\n ])\n .optional(),\n effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).optional(),\n promptSuggestions: z.boolean().optional(),\n cwd: z\n .string()\n .refine(\n (val) => {\n // Skip directory validation in non-Node environments\n if (typeof process === 'undefined' || !process.versions?.node) {\n return true;\n }\n return !val || existsSync(val);\n },\n { message: 'Working directory must exist' }\n )\n .optional(),\n executable: z.enum(['bun', 'deno', 'node']).optional(),\n executableArgs: z.array(z.string()).optional(),\n // Mirrors the SDK 0.3.x PermissionMode union ('auto' and 'dontAsk' were\n // added in 0.3.x; 'delegate' was dropped AND is rejected by the CLI's\n // --permission-mode flag parser, so it is rejected here too).\n permissionMode: z\n .enum(['default', 'acceptEdits', 'bypassPermissions', 'plan', 'dontAsk', 'auto'])\n .optional(),\n permissionPromptToolName: z.string().optional(),\n continue: z.boolean().optional(),\n resume: z.string().optional(),\n // The CLI rejects --session-id values that are not valid UUIDs, so\n // enforce the UUID shape here instead of failing at query time.\n sessionId: z\n .string()\n .refine(\n (val) =>\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(val),\n { message: 'sessionId must be a valid UUID (the CLI rejects non-UUID session IDs)' }\n )\n .optional(),\n allowedTools: z.array(z.string()).optional(),\n disallowedTools: z.array(z.string()).optional(),\n betas: z.array(z.string()).optional(),\n allowDangerouslySkipPermissions: z.boolean().optional(),\n enableFileCheckpointing: z.boolean().optional(),\n maxBudgetUsd: z.number().min(0).optional(),\n plugins: z\n .array(\n z\n .object({\n // SDK SdkPluginConfig: only 'local' is supported; the SDK throws\n // 'Unsupported plugin type' at query time for anything else.\n type: z.literal('local'),\n path: z.string(),\n })\n .passthrough()\n )\n .optional(),\n resumeSessionAt: z.string().optional(),\n sandbox: z\n .any()\n .refine((val) => val === undefined || typeof val === 'object', {\n message: 'sandbox must be an object',\n })\n .optional(),\n tools: z\n .union([\n z.array(z.string()),\n z.object({\n type: z.literal('preset'),\n preset: z.literal('claude_code'),\n }),\n ])\n .optional(),\n skills: z.union([z.array(z.string()), z.literal('all')]).optional(),\n settings: z\n .union([\n z.string(),\n z.record(z.string(), z.any()), // inline Settings object\n ])\n .optional(),\n managedSettings: z.record(z.string(), z.any()).optional(),\n toolAliases: z.record(z.string(), z.string()).optional(),\n toolConfig: z\n .object({\n askUserQuestion: z\n .object({\n previewFormat: z.enum(['markdown', 'html']).optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough()\n .optional(),\n planModeInstructions: z.string().optional(),\n title: z.string().optional(),\n forwardSubagentText: z.boolean().optional(),\n agentProgressSummaries: z.boolean().optional(),\n includeHookEvents: z.boolean().optional(),\n taskBudget: z.object({ total: z.number().positive() }).strict().optional(),\n sessionStore: z\n .any()\n .refine(\n (val) =>\n val === undefined ||\n (typeof val === 'object' &&\n val !== null &&\n typeof (val as { append?: unknown }).append === 'function' &&\n typeof (val as { load?: unknown }).load === 'function'),\n { message: 'sessionStore must be an object with append() and load() functions' }\n )\n .optional(),\n sessionStoreFlush: z.enum(['batched', 'eager']).optional(),\n loadTimeoutMs: z.number().int().positive().optional(),\n settingSources: z.array(z.enum(['user', 'project', 'local'])).optional(),\n streamingInput: z.enum(['auto', 'always', 'off']).optional(),\n // Hooks and tool-permission callback (permissive validation of shapes)\n canUseTool: z\n .any()\n .refine((v) => v === undefined || typeof v === 'function', {\n message: 'canUseTool must be a function',\n })\n .optional(),\n onUserDialog: z\n .any()\n .refine((v) => v === undefined || typeof v === 'function', {\n message: 'onUserDialog must be a function',\n })\n .optional(),\n supportedDialogKinds: z.array(z.string()).optional(),\n hooks: z\n .record(\n z.string(),\n z.array(\n z.object({\n matcher: z.string().optional(),\n hooks: z.array(z.any()).nonempty(),\n })\n )\n )\n .optional(),\n mcpServers: z\n .record(\n z.string(),\n z.union([\n // McpStdioServerConfig\n z.object({\n type: z.literal('stdio').optional(),\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n }),\n // McpSSEServerConfig\n z.object({\n type: z.literal('sse'),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n // McpHttpServerConfig\n z.object({\n type: z.literal('http'),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n // McpSdkServerConfig (in-process custom tools)\n z.object({\n type: z.literal('sdk'),\n name: z.string(),\n instance: z.any(),\n }),\n ])\n )\n .optional(),\n verbose: z.boolean().optional(),\n debug: z.boolean().optional(),\n debugFile: z.string().optional(),\n logger: z.union([z.literal(false), loggerFunctionSchema]).optional(),\n env: z.record(z.string(), z.string().optional()).optional(),\n additionalDirectories: z.array(z.string()).optional(),\n agents: z\n .record(\n z.string(),\n z\n .object({\n description: z.string(),\n tools: z.array(z.string()).optional(),\n disallowedTools: z.array(z.string()).optional(),\n prompt: z.string(),\n // SDK 0.3.x AgentDefinition accepts any model alias or full model ID\n model: z.string().optional(),\n mcpServers: z\n .array(\n z.union([\n z.string(),\n z.record(z.string(), z.any()), // McpServerConfigForProcessTransport\n ])\n )\n .optional(),\n criticalSystemReminder_EXPERIMENTAL: z.string().optional(),\n })\n .passthrough()\n )\n .optional(),\n includePartialMessages: z.boolean().optional(),\n fallbackModel: z.string().optional(),\n forkSession: z.boolean().optional(),\n stderr: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'stderr must be a function',\n })\n .optional(),\n strictMcpConfig: z.boolean().optional(),\n extraArgs: z.record(z.string(), z.union([z.string(), z.null()])).optional(),\n persistSession: z.boolean().optional(),\n spawnClaudeCodeProcess: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'spawnClaudeCodeProcess must be a function',\n })\n .optional(),\n sdkOptions: z.record(z.string(), z.any()).optional(),\n maxToolResultSize: z.number().int().min(100).max(1000000).optional(),\n // Callback invoked when Query object is created - for mid-stream injection via streamInput()\n onQueryCreated: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'onQueryCreated must be a function',\n })\n .optional(),\n onStreamStart: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'onStreamStart must be a function',\n })\n .optional(),\n // Callback invoked with the predicted next user prompt (active unless promptSuggestions: false)\n onPromptSuggestion: z\n .any()\n .refine((val) => val === undefined || typeof val === 'function', {\n message: 'onPromptSuggestion must be a function',\n })\n .optional(),\n })\n .strict();\n\n/**\n * Validates a model ID and returns warnings if needed.\n *\n * @param modelId - The model ID to validate\n * @returns Warning message if model is unknown, undefined otherwise\n */\nexport function validateModelId(modelId: string): string | undefined {\n const knownModels = ['opus', 'sonnet', 'haiku', 'fable'];\n\n // Check for empty or whitespace-only\n if (!modelId || modelId.trim() === '') {\n throw new Error('Model ID cannot be empty');\n }\n\n // Warn about unknown models but allow them\n if (!knownModels.includes(modelId)) {\n return `Unknown model ID: '${modelId}'. Proceeding with custom model. Known models are: ${knownModels.join(', ')}`;\n }\n\n return undefined;\n}\n\n/**\n * Validates Claude Code settings and returns validation results.\n *\n * @param settings - The settings object to validate\n * @returns Object with validation results and any warnings\n */\nexport function validateSettings(settings: unknown): {\n valid: boolean;\n warnings: string[];\n errors: string[];\n} {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n try {\n // Parse with Zod schema\n const result = claudeCodeSettingsSchema.safeParse(settings);\n\n if (!result.success) {\n // Extract user-friendly error messages\n // Support both Zod v3 (errors) and v4 (issues)\n const errorObject = result.error as {\n errors?: Array<{ path: string[]; message: string }>;\n issues?: Array<{ path: string[]; message: string }>;\n };\n const issues = errorObject.errors || errorObject.issues || [];\n issues.forEach((err: { path: string[]; message: string }) => {\n const path = err.path.join('.');\n errors.push(`${path ? `${path}: ` : ''}${err.message}`);\n });\n return { valid: false, warnings, errors };\n }\n\n // Additional validation warnings\n const validSettings = result.data;\n\n // sdkOptions escape-hatch values are merged over explicit settings at\n // query time (undefined-valued keys are skipped by the merge), so every\n // cross-option SDK-constraint check below must inspect the EFFECTIVE\n // value - the sdkOptions override when defined, the first-class setting\n // otherwise - on BOTH sides of each constraint.\n const sdkOptionsRecord = validSettings.sdkOptions as Record<string, unknown> | undefined;\n const effective = (key: string): unknown => {\n const override = sdkOptionsRecord?.[key];\n return override !== undefined ? override : (validSettings as Record<string, unknown>)[key];\n };\n const effSessionStore = effective('sessionStore');\n // The SDK treats a blank/whitespace resume id as absent (no session to\n // resume), so normalize it for the cross-option checks below.\n const effectiveResumeId = (): string | undefined => {\n // Mirror the runtime's getEffectiveResume: pick the first NON-BLANK\n // candidate (sdkOptions overlay, then first-class setting). Using\n // effective('resume') alone would let a blank sdkOptions.resume shadow a\n // real settings.resume, wrongly rejecting a config the query accepts.\n for (const candidate of [sdkOptionsRecord?.resume, validSettings.resume]) {\n if (typeof candidate === 'string' && !isBlankResume(candidate)) {\n return candidate;\n }\n }\n return undefined;\n };\n\n // SDK constraint: sessionStore mirroring requires local session writes,\n // so it cannot be combined with persistSession: false.\n if (effSessionStore !== undefined && effective('persistSession') === false) {\n errors.push(\n 'sessionStore cannot be combined with persistSession: false. Transcript mirroring requires local session writes; remove persistSession: false or drop sessionStore.'\n );\n return { valid: false, warnings, errors };\n }\n\n // SDK constraint: checkpoint backup blobs are not mirrored to a sessionStore,\n // so rewindFiles() would fail after a store-backed resume. The SDK throws at\n // query time; reject early here instead.\n if (effSessionStore !== undefined && effective('enableFileCheckpointing') === true) {\n errors.push(\n 'sessionStore cannot be combined with enableFileCheckpointing: true. Checkpoint backup blobs are not mirrored to the store (rewindFiles() fails after a store-backed resume); remove enableFileCheckpointing or drop sessionStore.'\n );\n return { valid: false, warnings, errors };\n }\n\n // SDK constraint: continue with a sessionStore needs store.listSessions()\n // to discover the most recent session (unless a resume id is given).\n // The SDK throws at query time; reject early here instead.\n if (\n effective('continue') === true &&\n effSessionStore !== undefined &&\n effectiveResumeId() === undefined &&\n typeof (effSessionStore as { listSessions?: unknown }).listSessions !== 'function'\n ) {\n errors.push(\n 'continue: true with sessionStore requires the store to implement listSessions() (used to discover the most recent session). Implement listSessions(), pass resume with an explicit session ID, or drop continue.'\n );\n return { valid: false, warnings, errors };\n }\n\n // SDK constraint: the sandbox option cannot be combined with a settings\n // FILE PATH (inline Settings objects are fine - the SDK serializes them\n // to inline JSON). The SDK throws at query time; reject early here instead.\n const effSettingsOption = effective('settings');\n if (\n effective('sandbox') !== undefined &&\n typeof effSettingsOption === 'string' &&\n !(effSettingsOption.trim().startsWith('{') && effSettingsOption.trim().endsWith('}'))\n ) {\n errors.push(\n 'sandbox cannot be combined with a settings file path. Pass settings as an inline Settings object, or move the sandbox configuration into the settings file and drop the sandbox option.'\n );\n return { valid: false, warnings, errors };\n }\n\n // CLI constraint: --session-id cannot be combined with --continue or\n // --resume unless --fork-session is also set (to name the forked\n // session's ID). The CLI rejects the flags at argv parsing; reject early\n // here instead.\n if (\n effective('sessionId') !== undefined &&\n effective('forkSession') !== true &&\n (effective('continue') === true || effectiveResumeId() !== undefined)\n ) {\n errors.push(\n \"sessionId cannot be combined with continue or resume unless forkSession: true is also set (it then names the forked session's ID). Remove sessionId, remove continue/resume, or add forkSession: true.\"\n );\n return { valid: false, warnings, errors };\n }\n\n // Warn about high turn limits\n if (validSettings.maxTurns && validSettings.maxTurns > 20) {\n warnings.push(\n `High maxTurns value (${validSettings.maxTurns}) may lead to long-running conversations`\n );\n }\n\n // Warn about very high thinking tokens\n if (validSettings.maxThinkingTokens && validSettings.maxThinkingTokens > 50000) {\n warnings.push(\n `Very high maxThinkingTokens (${validSettings.maxThinkingTokens}) may increase response time`\n );\n }\n\n // Check if both allowedTools and disallowedTools are specified\n if (validSettings.allowedTools && validSettings.disallowedTools) {\n warnings.push(\n 'Both allowedTools and disallowedTools are specified. Only allowedTools will be used.'\n );\n }\n\n // Validate tool name format\n const validateToolNames = (tools: string[], type: string) => {\n tools.forEach((tool) => {\n // Basic validation - tool names should be alphanumeric with optional specifiers\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*(\\([^)]*\\))?$/.test(tool) && !tool.startsWith('mcp__')) {\n warnings.push(`Unusual ${type} tool name format: '${tool}'`);\n }\n });\n };\n\n if (validSettings.allowedTools) {\n validateToolNames(validSettings.allowedTools, 'allowed');\n }\n\n if (validSettings.disallowedTools) {\n validateToolNames(validSettings.disallowedTools, 'disallowed');\n }\n\n // SDK constraint: a non-empty supportedDialogKinds without an onUserDialog\n // handler throws at option intake (\"declaring dialog kinds without a\n // handler would park dialogs nothing can answer\"), so reject it instead\n // of warning - the query would fail at startup anyway. An empty list does\n // not throw, and onUserDialog may arrive via the sdkOptions escape hatch.\n const effDialogKinds = effective('supportedDialogKinds');\n if (\n Array.isArray(effDialogKinds) &&\n effDialogKinds.length > 0 &&\n effective('onUserDialog') == null\n ) {\n errors.push(\n 'supportedDialogKinds is set without onUserDialog. The SDK requires the onUserDialog callback to render declared dialog kinds and throws when a non-empty list is passed without it; provide onUserDialog or remove supportedDialogKinds.'\n );\n return { valid: false, warnings, errors };\n }\n\n // Warn about Skills configuration issues. Both allowedTools and\n // settingSources can arrive via the sdkOptions escape hatch, so inspect\n // the EFFECTIVE (sdkOptions-overlaid) values to avoid a spurious warning\n // when settingSources (or allowedTools) is supplied through sdkOptions.\n const effAllowedTools = effective('allowedTools');\n if (\n Array.isArray(effAllowedTools) &&\n effAllowedTools.includes('Skill') &&\n !effective('settingSources')\n ) {\n warnings.push(\n \"allowedTools includes 'Skill' but settingSources is not set. Skills require settingSources (e.g., ['user', 'project']) to load skill definitions.\"\n );\n }\n\n // SDK 0.3.x accepts any string for agents[].model (alias or full model ID),\n // so the schema no longer rejects typos. Warn (but allow) when a value looks\n // like neither a known alias nor a full model ID, to catch typo'd aliases\n // at validation time instead of failing later in the CLI.\n if (validSettings.agents) {\n const knownAgentModelAliases = ['sonnet', 'opus', 'haiku', 'fable', 'inherit'];\n for (const [agentName, agent] of Object.entries(validSettings.agents)) {\n const agentModel = agent.model;\n if (\n agentModel !== undefined &&\n !knownAgentModelAliases.includes(agentModel) &&\n !agentModel.includes('-')\n ) {\n warnings.push(\n `Unknown model alias '${agentModel}' for agent '${agentName}'. Known aliases are: ${knownAgentModelAliases.join(', ')}; full model IDs (e.g. 'claude-sonnet-4-5') are also accepted.`\n );\n }\n }\n }\n\n return { valid: true, warnings, errors };\n } catch (error) {\n errors.push(`Validation error: ${error instanceof Error ? error.message : String(error)}`);\n return { valid: false, warnings, errors };\n }\n}\n\n/**\n * Validates prompt length and format.\n *\n * @param prompt - The prompt to validate\n * @returns Warning message if prompt might cause issues\n */\nexport function validatePrompt(prompt: string): string | undefined {\n // Very long prompts might cause issues\n const MAX_PROMPT_LENGTH = 100000; // ~25k tokens\n\n if (prompt.length > MAX_PROMPT_LENGTH) {\n return `Very long prompt (${prompt.length} characters) may cause performance issues or timeouts`;\n }\n\n return undefined;\n}\n\n/**\n * Validates session ID format.\n *\n * @param sessionId - The session ID to validate\n * @returns Warning message if format is unusual\n */\nexport function validateSessionId(sessionId: string): string | undefined {\n // Session IDs from Claude Code are typically UUID-like\n // But we don't want to be too strict as format might change\n if (sessionId && !/^[a-zA-Z0-9-_]+$/.test(sessionId)) {\n return `Unusual session ID format. This may cause issues with session resumption.`;\n }\n\n return undefined;\n}\n","/**\n * JSON Schema sanitizer for the Claude Code CLI's native structured outputs.\n *\n * The CLI's constrained decoder does not support the JSON Schema `format`\n * keyword (`date-time`, `email`, `uri`, `uuid`, ...). Instead of enforcing or\n * ignoring it, the CLI silently returns a successful result WITHOUT\n * `structured_output`, which surfaces downstream as an opaque\n * `AI_NoObjectGeneratedError` (verified on SDK 0.2.63 and 0.3.170 — upstream\n * CLI limitation). Stripping `format` client-side keeps constrained decoding\n * active for the rest of the schema.\n *\n * Note: `pattern` is intentionally NOT touched. The CLI genuinely enforces\n * (simple) regex patterns, so removing it would drop real enforcement.\n * Complex patterns (lookaheads/backreferences) remain a documented limitation.\n */\n\n/** Keywords whose value is a map of property/definition name -> subschema. */\nconst SUBSCHEMA_MAP_KEYWORDS = [\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas',\n // draft-07 `dependencies` values are either subschemas (schema form) or\n // arrays of property-name strings (array form); sanitizeNode passes\n // string arrays through untouched, so walking both forms is safe.\n 'dependencies',\n] as const;\n\n/** Keywords whose value is a single subschema (or a boolean, which is skipped). */\nconst SUBSCHEMA_KEYWORDS = [\n 'items', // may also be an array of subschemas (draft-07 tuple form)\n 'additionalItems',\n 'additionalProperties',\n 'unevaluatedItems',\n 'unevaluatedProperties',\n 'not',\n 'contains',\n 'propertyNames',\n 'contentSchema',\n 'if',\n 'then',\n 'else',\n] as const;\n\n/** Keywords whose value is an array of subschemas. */\nconst SUBSCHEMA_LIST_KEYWORDS = ['prefixItems', 'anyOf', 'oneOf', 'allOf'] as const;\n\n/**\n * Result of sanitizing a JSON schema for the CLI's `outputFormat`.\n */\nexport interface SanitizedJsonSchema {\n /**\n * Schema safe to pass as `outputFormat.schema`. When no `format` keywords\n * were found, this is the input object itself (same reference); otherwise a\n * copy-on-write clone with every `format` keyword removed — modified nodes\n * are copied, while untouched subtrees are shared by reference with the\n * input (the input is never mutated).\n */\n schema: Record<string, unknown>;\n\n /**\n * JSON-pointer-style paths (`#`, `#/properties/email`, ...) of the schema\n * nodes whose `format` keyword was removed. Empty when nothing was stripped.\n */\n strippedFormatPaths: string[];\n}\n\n/**\n * Deep-walks a JSON schema and removes every `format` keyword, folding the\n * hint into the node's `description` (appending ` (expected format: <value>)`\n * to an existing description, or creating `Expected format: <value>`), so the\n * model still sees the intent in plain language.\n *\n * This is safe end-to-end: `generateObject`/`streamObject` validate the result\n * against the user's ORIGINAL Zod schema client-side, so `.email()` /\n * `.datetime()` / `.url()` / `.uuid()` enforcement is fully preserved — only\n * the CLI-side enforcement, which never existed for `format`, is dropped.\n *\n * Walked locations: `properties`, `patternProperties`, `$defs`/`definitions`,\n * `dependentSchemas`/`dependencies`, `items` (object and tuple forms),\n * `prefixItems`, `anyOf`/`oneOf`/`allOf`, `not`, `additionalProperties`,\n * `contentSchema`, and related applicator keywords. `$ref` values are strings\n * (no recursion risk), but object identity is still guarded so cyclic inputs\n * cannot cause infinite recursion.\n *\n * @param schema - JSON schema as provided by the AI SDK's `responseFormat`\n * @returns The (possibly unchanged) schema plus the list of stripped paths\n */\nexport function sanitizeJsonSchemaForOutputFormat(\n schema: Record<string, unknown>\n): SanitizedJsonSchema {\n const strippedFormatPaths: string[] = [];\n const sanitized = sanitizeNode(schema, '#', new WeakSet(), strippedFormatPaths);\n return {\n schema: (sanitized ?? schema) as Record<string, unknown>,\n strippedFormatPaths,\n };\n}\n\n/**\n * Copy-on-write recursive sanitizer. Returns the input value unchanged (same\n * reference) when neither the node nor any descendant contains a `format`\n * keyword.\n */\nfunction sanitizeNode(\n node: unknown,\n path: string,\n visiting: WeakSet<object>,\n strippedFormatPaths: string[]\n): unknown {\n if (typeof node !== 'object' || node === null) {\n return node;\n }\n\n // Cycle guard: $refs are strings so well-formed schemas cannot recurse, but\n // a cyclic object graph must not cause infinite recursion. On revisit the\n // node is returned as-is.\n if (visiting.has(node)) {\n return node;\n }\n visiting.add(node);\n\n try {\n if (Array.isArray(node)) {\n return sanitizeList(node, path, visiting, strippedFormatPaths);\n }\n\n const record = node as Record<string, unknown>;\n let result = record;\n const setKey = (key: string, value: unknown) => {\n if (result === record) {\n result = { ...record };\n }\n result[key] = value;\n };\n\n // Strip the `format` keyword, folding the hint into the description.\n if (typeof record.format === 'string') {\n const format = record.format;\n const existingDescription = record.description;\n result = { ...record };\n delete result.format;\n if (typeof existingDescription === 'string' && existingDescription.length > 0) {\n result.description = `${existingDescription} (expected format: ${format})`;\n } else if (existingDescription === undefined || existingDescription === '') {\n result.description = `Expected format: ${format}`;\n }\n // Non-string `description` values (spec-invalid, only possible in\n // hand-written schemas) are preserved untouched rather than overwritten.\n strippedFormatPaths.push(path);\n }\n\n // Maps of name -> subschema (properties, patternProperties, $defs, definitions).\n for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {\n const map = record[keyword];\n if (typeof map !== 'object' || map === null || Array.isArray(map)) continue;\n const mapRecord = map as Record<string, unknown>;\n let newMap = mapRecord;\n for (const [name, child] of Object.entries(mapRecord)) {\n const sanitizedChild = sanitizeNode(\n child,\n `${path}/${keyword}/${name}`,\n visiting,\n strippedFormatPaths\n );\n if (sanitizedChild !== child) {\n if (newMap === mapRecord) {\n newMap = { ...mapRecord };\n }\n newMap[name] = sanitizedChild;\n }\n }\n if (newMap !== mapRecord) {\n setKey(keyword, newMap);\n }\n }\n\n // Single subschemas (items, additionalProperties, not, ...). `items` may\n // also be a tuple array (handled transparently by sanitizeNode).\n for (const keyword of SUBSCHEMA_KEYWORDS) {\n const child = record[keyword];\n if (typeof child !== 'object' || child === null) continue;\n const sanitizedChild = sanitizeNode(\n child,\n `${path}/${keyword}`,\n visiting,\n strippedFormatPaths\n );\n if (sanitizedChild !== child) {\n setKey(keyword, sanitizedChild);\n }\n }\n\n // Arrays of subschemas (prefixItems, anyOf, oneOf, allOf).\n for (const keyword of SUBSCHEMA_LIST_KEYWORDS) {\n const list = record[keyword];\n if (!Array.isArray(list)) continue;\n const sanitizedList = sanitizeList(list, `${path}/${keyword}`, visiting, strippedFormatPaths);\n if (sanitizedList !== list) {\n setKey(keyword, sanitizedList);\n }\n }\n\n return result;\n } finally {\n // Visit-stack semantics: shared (DAG) subschemas reached via different\n // parents are each sanitized; only true cycles short-circuit above.\n visiting.delete(node);\n }\n}\n\n/** Copy-on-write sanitization of an array of subschemas. */\nfunction sanitizeList(\n list: unknown[],\n path: string,\n visiting: WeakSet<object>,\n strippedFormatPaths: string[]\n): unknown[] {\n let result = list;\n for (let i = 0; i < list.length; i++) {\n const sanitizedChild = sanitizeNode(list[i], `${path}/${i}`, visiting, strippedFormatPaths);\n if (sanitizedChild !== list[i]) {\n if (result === list) {\n result = [...list];\n }\n result[i] = sanitizedChild;\n }\n }\n return result;\n}\n","import type { Logger } from './types.js';\n\n/**\n * Default logger that uses console with level tags.\n */\nconst defaultLogger: Logger = {\n // eslint-disable-next-line no-console\n debug: (message: string) => console.debug(`[DEBUG] ${message}`),\n // eslint-disable-next-line no-console\n info: (message: string) => console.info(`[INFO] ${message}`),\n warn: (message: string) => console.warn(`[WARN] ${message}`),\n error: (message: string) => console.error(`[ERROR] ${message}`),\n};\n\n/**\n * No-op logger that discards all messages.\n */\nconst noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Gets the appropriate logger based on configuration.\n *\n * @param logger - Logger configuration from settings\n * @returns The logger to use\n */\nexport function getLogger(logger: Logger | false | undefined): Logger {\n if (logger === false) {\n return noopLogger;\n }\n\n if (logger === undefined) {\n return defaultLogger;\n }\n\n return logger;\n}\n\n/**\n * Creates a verbose-aware logger that only logs debug/info when verbose is enabled.\n * Warn and error are always logged regardless of verbose setting.\n *\n * @param logger - Base logger to wrap\n * @param verbose - Whether to enable verbose (debug/info) logging\n * @returns Logger with verbose-aware behavior\n */\nexport function createVerboseLogger(logger: Logger, verbose: boolean = false): Logger {\n if (verbose) {\n // When verbose is enabled, use all log levels\n return logger;\n }\n\n // When verbose is disabled, only allow warn/error\n // Bind methods to preserve 'this' context for custom loggers\n return {\n debug: () => {}, // No-op when not verbose\n info: () => {}, // No-op when not verbose\n warn: logger.warn.bind(logger),\n error: logger.error.bind(logger),\n };\n}\n","/**\n * Provider exports for creating and configuring Claude Code instances.\n * @module claude-code\n */\n\n/**\n * Creates a new Claude Code provider instance and the default provider instance.\n * @see {@link createClaudeCode} for creating custom provider instances\n * @see {@link claudeCode} for the default provider instance\n */\nexport { createClaudeCode, claudeCode } from './claude-code-provider.js';\n\n/**\n * Type definitions for the Claude Code provider.\n * @see {@link ClaudeCodeProvider} for the provider interface\n * @see {@link ClaudeCodeProviderSettings} for provider configuration options\n */\nexport type { ClaudeCodeProvider, ClaudeCodeProviderSettings } from './claude-code-provider.js';\n\n/**\n * Language model implementation for Claude Code.\n * This class implements the AI SDK's LanguageModelV3 interface.\n */\nexport { ClaudeCodeLanguageModel } from './claude-code-language-model.js';\n\n/**\n * Type definitions for Claude Code language models.\n * @see {@link ClaudeCodeModelId} for supported model identifiers\n * @see {@link ClaudeCodeLanguageModelOptions} for model configuration options\n */\nexport type {\n ClaudeCodeModelId,\n ClaudeCodeLanguageModelOptions,\n} from './claude-code-language-model.js';\n\n/**\n * Settings for configuring Claude Code behavior.\n * Includes options for customizing the CLI execution, permissions, and tool usage.\n */\nexport type { ClaudeCodeSettings, Logger, MessageInjector } from './types.js';\n\n// Convenience re-exports from the SDK for custom tools and hooks\nexport {\n createSdkMcpServer,\n tool,\n // Marker element for string[] systemPrompt cache splitting\n SYSTEM_PROMPT_DYNAMIC_BOUNDARY,\n // Reference SessionStore implementation (alpha)\n InMemorySessionStore,\n // Value-level companion to the HookEvent type (iterate/validate hook event names)\n HOOK_EVENTS,\n // Error class thrown by the SDK on abort (relevant on the standalone\n // startup()/WarmQuery path, where SDK errors propagate unwrapped)\n AbortError,\n} from '@anthropic-ai/claude-agent-sdk';\n\n/**\n * Session lifecycle helpers re-exported from the SDK.\n *\n * These operate on persisted session storage — the local\n * `~/.claude/projects/` JSONL files by default, or a custom `SessionStore`\n * when one is passed via each helper's `sessionStore` option (alpha).\n * See docs/sessions.md for a guide tying these together with the\n * session-related settings (`sessionId`, `resume`, `forkSession`, ...).\n */\nexport {\n listSessions,\n forkSession,\n getSessionInfo,\n getSessionMessages,\n deleteSession,\n renameSession,\n tagSession,\n listSubagents,\n getSubagentMessages,\n // Pure summary-folding utility for SessionStore implementers (alpha)\n foldSessionSummary,\n // Migrate a local JSONL session into a SessionStore (alpha)\n importSessionToStore,\n} from '@anthropic-ai/claude-agent-sdk';\n\n/**\n * Warm-start helper re-exported from the SDK.\n *\n * `startup()` pre-spawns the CLI subprocess and completes its initialize\n * handshake, returning a {@link WarmQuery} handle whose `query()` method\n * writes the prompt to the already-running process (no startup latency).\n *\n * Note: a `WarmQuery` is a standalone SDK query path — it cannot be handed\n * to this provider's `generateText`/`streamText` flow (the SDK exposes no\n * option for passing a pre-warmed handle to `query()`). See the README\n * section \"Reducing time-to-first-token (warm start)\" for the standalone\n * usage pattern and this limitation.\n */\nexport { startup } from '@anthropic-ai/claude-agent-sdk';\nexport { createCustomMcpServer, createAiSdkMcpServer } from './mcp-helpers.js';\nexport type {\n ToolAnnotations,\n MinimalCallToolResult,\n AiSdkLikeTool,\n AiSdkToolExecuteOptions,\n} from './mcp-helpers.js';\nexport type {\n HookEvent,\n HookCallback,\n HookCallbackMatcher,\n HookInput,\n HookJSONOutput,\n // HookJSONOutput union members\n AsyncHookJSONOutput,\n SyncHookJSONOutput,\n // Hook event inputs (every member of the SDK HookInput union)\n PreToolUseHookInput,\n PostToolUseHookInput,\n PostToolUseFailureHookInput,\n PostToolBatchHookInput,\n PermissionDeniedHookInput,\n NotificationHookInput,\n UserPromptSubmitHookInput,\n UserPromptExpansionHookInput,\n SessionStartHookInput,\n SessionEndHookInput,\n StopHookInput,\n StopFailureHookInput,\n SubagentStartHookInput,\n SubagentStopHookInput,\n PreCompactHookInput,\n PostCompactHookInput,\n PermissionRequestHookInput,\n SetupHookInput,\n TeammateIdleHookInput,\n TaskCreatedHookInput,\n TaskCompletedHookInput,\n ElicitationHookInput,\n ElicitationResultHookInput,\n ConfigChangeHookInput,\n InstructionsLoadedHookInput,\n WorktreeCreateHookInput,\n WorktreeRemoveHookInput,\n CwdChangedHookInput,\n FileChangedHookInput,\n MessageDisplayHookInput,\n // Hook-specific output payloads (SyncHookJSONOutput['hookSpecificOutput'] union members)\n PreToolUseHookSpecificOutput,\n UserPromptSubmitHookSpecificOutput,\n UserPromptExpansionHookSpecificOutput,\n SessionStartHookSpecificOutput,\n SetupHookSpecificOutput,\n SubagentStartHookSpecificOutput,\n PostToolUseHookSpecificOutput,\n PostToolUseFailureHookSpecificOutput,\n PostToolBatchHookSpecificOutput,\n StopHookSpecificOutput,\n SubagentStopHookSpecificOutput,\n PermissionDeniedHookSpecificOutput,\n NotificationHookSpecificOutput,\n PermissionRequestHookSpecificOutput,\n ElicitationHookSpecificOutput,\n ElicitationResultHookSpecificOutput,\n CwdChangedHookSpecificOutput,\n FileChangedHookSpecificOutput,\n WorktreeCreateHookSpecificOutput,\n MessageDisplayHookSpecificOutput,\n // Hook permission decision union (adds 'defer' in SDK 0.3.x)\n HookPermissionDecision,\n // Provenance of a user-role message (peer session, team lead, channel)\n SDKMessageOrigin,\n // Why the turn loop terminated (providerMetadata['claude-code'].terminalReason)\n TerminalReason,\n CanUseTool,\n PermissionResult,\n PermissionUpdate,\n PermissionBehavior,\n PermissionRuleValue,\n // Permission mode union referenced by ClaudeCodeSettings.permissionMode,\n // AgentDefinition.permissionMode, and Query.setPermissionMode()\n PermissionMode,\n // Destination carried by every PermissionUpdate variant\n PermissionUpdateDestination,\n // Provenance of a canUseTool decision (PermissionResult.decisionClassification)\n PermissionDecisionClassification,\n // Blocking user-dialog callback (`onUserDialog` setting) and its request/result shapes\n OnUserDialog,\n UserDialogRequest,\n UserDialogResult,\n // Pre-warmed query handle returned by startup()\n WarmQuery,\n // SDK query() options shape (also accepted by startup() and referenced by\n // ClaudeCodeSettings.systemPrompt/tools/sdkOptions)\n Options,\n McpServerConfig,\n // McpServerConfig union members\n McpStdioServerConfig,\n McpSSEServerConfig,\n McpHttpServerConfig,\n McpSdkServerConfig,\n McpSdkServerConfigWithInstance,\n // Per-agent MCP server map values (AgentMcpServerSpec record values)\n McpServerConfigForProcessTransport,\n OutputFormat,\n SpawnedProcess,\n SpawnOptions,\n AgentMcpServerSpec,\n // Subagent definitions (ClaudeCodeSettings['agents'] values)\n AgentDefinition,\n // Effort levels for the `effort` setting ('low' | 'medium' | 'high' | 'xhigh' | 'max')\n EffortLevel,\n // Settings object shape for the `settings`/`managedSettings` options\n Settings,\n // Per-tool configuration for built-in tools (`toolConfig` option)\n ToolConfig,\n // Session transcript mirroring (alpha `sessionStore` options)\n SessionStore,\n SessionStoreFlush,\n // Session lifecycle helper option/result types\n ListSessionsOptions,\n ForkSessionOptions,\n ForkSessionResult,\n GetSessionInfoOptions,\n GetSessionMessagesOptions,\n GetSubagentMessagesOptions,\n ListSubagentsOptions,\n SessionMutationOptions,\n ImportSessionToStoreOptions,\n // Session metadata returned by getSessionInfo()\n SDKSessionInfo,\n // Transcript message shape returned by getSubagentMessages()\n SessionMessage,\n // Building blocks for custom SessionStore implementations (alpha)\n SessionKey,\n SessionStoreEntry,\n SessionSummaryEntry,\n // Cron task summaries surfaced in session state (referenced by session metadata)\n SessionCronSummary,\n // Query interface for mid-stream message injection via streamInput()\n Query,\n // Messages yielded by Query (AsyncGenerator<SDKMessage>) and accepted by\n // Query.streamInput()/WarmQuery.query() (AsyncIterable<SDKUserMessage>)\n SDKMessage,\n SDKUserMessage,\n // Query method result shapes\n SlashCommand,\n ModelInfo,\n AgentInfo,\n AccountInfo,\n McpServerStatus,\n RewindFilesResult,\n McpSetServersResult,\n // Beta feature identifiers (`betas` setting values)\n SdkBeta,\n // Plugin configuration (`plugins` setting values)\n SdkPluginConfig,\n // Sandbox configuration (`sandbox` setting) and its nested shapes\n SandboxSettings,\n SandboxNetworkConfig,\n SandboxFilesystemConfig,\n SandboxIgnoreViolations,\n // Thinking configuration types\n ThinkingConfig,\n ThinkingAdaptive,\n ThinkingEnabled,\n ThinkingDisabled,\n} from '@anthropic-ai/claude-agent-sdk';\n\n/**\n * Error handling utilities for Claude Code.\n * These functions help create and identify specific error types.\n *\n * @see {@link isAuthenticationError} to check for authentication failures\n * @see {@link isTimeoutError} to check for timeout errors\n * @see {@link getErrorMetadata} to extract error metadata\n * @see {@link createAPICallError} to create general API errors\n * @see {@link createAuthenticationError} to create authentication errors\n * @see {@link createTimeoutError} to create timeout errors\n */\nexport {\n isAuthenticationError,\n isTimeoutError,\n getErrorMetadata,\n createAPICallError,\n createAuthenticationError,\n createTimeoutError,\n} from './errors.js';\n\n/**\n * Metadata associated with Claude Code errors.\n * Contains additional context about CLI execution failures.\n */\nexport type { ClaudeCodeErrorMetadata } from './errors.js';\n","import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport type {\n McpSdkServerConfigWithInstance,\n SdkMcpToolDefinition,\n} from '@anthropic-ai/claude-agent-sdk';\nimport { type ZodRawShape, type ZodObject } from 'zod';\n\n/**\n * Optional annotations for content items, per MCP specification.\n * Validated against MCP SDK schema version 2025-06-18.\n */\ntype ContentAnnotations = {\n /** Intended audience(s) for this content */\n audience?: ('user' | 'assistant')[];\n /** Priority hint (0 = least important, 1 = most important) */\n priority?: number;\n /** ISO 8601 timestamp of last modification */\n lastModified?: string;\n};\n\n/**\n * MCP tool annotations for hinting tool behavior to the model.\n * Derived from the SDK's SdkMcpToolDefinition type to stay in sync\n * with the upstream MCP ToolAnnotations definition.\n */\nexport type ToolAnnotations = NonNullable<SdkMcpToolDefinition['annotations']>;\n\n/**\n * Convenience helper to create an SDK MCP server from a simple tool map.\n * Each tool provides a description, a Zod object schema, and a handler.\n *\n * Type definition validated against MCP SDK specification version 2025-06-18.\n * See: https://modelcontextprotocol.io/specification/2025-06-18/server/tools\n */\nexport type MinimalCallToolResult = {\n content: Array<\n | {\n /** Text content */\n type: 'text';\n /** The text content (plain text or structured format like JSON) */\n text: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Image content (base64-encoded) */\n type: 'image';\n /** Base64-encoded image data */\n data: string;\n /** MIME type of the image (e.g., image/png, image/jpeg) */\n mimeType: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Audio content (base64-encoded) */\n type: 'audio';\n /** Base64-encoded audio data */\n data: string;\n /** MIME type of the audio (e.g., audio/wav, audio/mp3) */\n mimeType: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Embedded resource with full content (text or blob) */\n type: 'resource';\n /** Resource contents - either text or blob variant */\n resource: { uri: string; _meta?: Record<string, unknown>; [key: string]: unknown } & (\n | { text: string; mimeType?: string }\n | { blob: string; mimeType: string }\n );\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n | {\n /** Resource link (reference only - no embedded content) */\n type: 'resource_link';\n /** URI of the resource */\n uri: string;\n /** Human-readable name (required per MCP spec) */\n name: string;\n /** Optional description of what this resource represents */\n description?: string;\n /** MIME type of the resource, if known */\n mimeType?: string;\n annotations?: ContentAnnotations;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n }\n >;\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\n/**\n * Builds an `isError: true` MCP tool result carrying a single text content\n * item. Centralizes the {@link MinimalCallToolResult} error shape so the\n * handler's several error paths (invalid arguments, serialization failure,\n * thrown/rejected execute) all produce an identical structure.\n */\nfunction buildIsErrorResult(text: string): MinimalCallToolResult {\n return {\n isError: true,\n content: [{ type: 'text', text }],\n };\n}\n\n/**\n * Converts a value returned by an AI SDK tool's `execute` into MCP text.\n *\n * Owns the two accreted concerns of result handling:\n * 1. AsyncIterable draining: `execute` may return an async iterator that\n * yields partial outputs and a final value; the SDK uses the last *yielded*\n * value (a generator's `return` is not yielded). Drain it to that final\n * value instead of stringifying the iterator object to `{}`.\n * 2. Serialization: strings pass through unchanged; everything else is\n * `JSON.stringify`'d. `JSON.stringify(undefined)` returns `undefined`\n * (not a string), so the literal `'undefined'` fallback is preserved.\n * A serialization failure (e.g. circular reference) yields a descriptive\n * `isError` result rather than throwing.\n *\n * The drain runs OUTSIDE the serialization `try/catch` on purpose: a throw\n * while draining must propagate to the handler's outer `catch` (becoming a\n * generic `isError` from the error message), not be misreported as a\n * serialization failure.\n *\n * @returns `{ text }` on success, or `{ isError }` carrying a ready-made\n * serialization-failure result.\n */\nasync function normalizeToolResultToText(\n toolName: string,\n result: unknown\n): Promise<{ text: string } | { isError: MinimalCallToolResult }> {\n // Drain an AsyncIterable to its final yielded value (outside the\n // serialization try/catch — see doc comment).\n if (\n result != null &&\n typeof (result as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n ) {\n let last: unknown;\n for await (const chunk of result as AsyncIterable<unknown>) {\n last = chunk;\n }\n result = last;\n }\n\n if (typeof result === 'string') {\n return { text: result };\n }\n try {\n return { text: JSON.stringify(result) ?? 'undefined' };\n } catch (serializationError) {\n const reason =\n serializationError instanceof Error ? serializationError.message : String(serializationError);\n return {\n isError: buildIsErrorResult(\n `Tool \"${toolName}\" succeeded but its result could not be serialized to JSON: ${reason}`\n ),\n };\n }\n}\n\nexport function createCustomMcpServer<\n Tools extends Record<\n string,\n {\n description: string;\n inputSchema: ZodObject<ZodRawShape>;\n handler: (args: Record<string, unknown>, extra: unknown) => Promise<MinimalCallToolResult>;\n annotations?: ToolAnnotations;\n }\n >,\n>(config: { name: string; version?: string; tools: Tools }): McpSdkServerConfigWithInstance {\n const defs = Object.entries(config.tools).map(([name, def]) =>\n tool(\n name,\n def.description,\n def.inputSchema.shape as ZodRawShape,\n (args: Record<string, unknown>, extra: unknown) => def.handler(args, extra),\n def.annotations ? { annotations: def.annotations } : undefined\n )\n );\n return createSdkMcpServer({ name: config.name, version: config.version, tools: defs });\n}\n\n/**\n * Minimal per-call options passed to an AI SDK tool's `execute` function\n * when it is invoked through {@link createAiSdkMcpServer}.\n *\n * Note that the AI SDK's full `ToolCallOptions` (e.g. `messages`,\n * `experimental_context`) is not available here: the tool runs inside the\n * Claude Code CLI's MCP transport, outside the AI SDK call loop.\n */\nexport type AiSdkToolExecuteOptions = {\n /**\n * Identifier of the MCP request that triggered this call, when available.\n *\n * Note: this is the MCP JSON-RPC request id (often a small integer like\n * `'42'`), not the model's `toolu_...` tool_use id, so it will not match\n * the `toolCallId` on the AI SDK's `tool-call`/`tool-result` stream parts.\n */\n toolCallId?: string;\n /** Abort signal for the MCP request, when available. */\n abortSignal?: AbortSignal;\n};\n\n/**\n * Structural shape of an AI SDK tool (what the `ai` package's `tool()` helper\n * returns) as accepted by {@link createAiSdkMcpServer}. Deliberately\n * structurally typed so this package does not depend on the `ai` package.\n *\n * Constraints:\n * - `inputSchema` must be a Zod object schema (`z.object({...})`, Zod v3 or\n * v4) — the same schema you would pass to the `ai` package's `tool()`\n * helper. Schemas created with the AI SDK's `jsonSchema()` helper are not\n * supported because the Agent SDK's `tool()` requires a Zod shape.\n * - `execute` is required: only tools that execute locally can be bridged.\n */\nexport type AiSdkLikeTool = {\n description?: string;\n /** A Zod object schema (`z.object({...})`), Zod v3 or v4. */\n inputSchema: unknown;\n /**\n * Tool implementation. Receives the validated input and a minimal options\n * object ({@link AiSdkToolExecuteOptions}).\n *\n * Optional in the type only to stay assignment-compatible with the AI\n * SDK's `Tool` type — {@link createAiSdkMcpServer} throws at creation time\n * if it is missing.\n */\n execute?(input: never, options?: AiSdkToolExecuteOptions): PromiseLike<unknown> | unknown;\n};\n\n/** Symbol marker set by the AI SDK's `jsonSchema()`/`asSchema()` helpers. */\nconst AI_SDK_SCHEMA_SYMBOL = Symbol.for('vercel.ai.schema');\n\nfunction isAiSdkJsonSchema(schema: unknown): boolean {\n return typeof schema === 'object' && schema !== null && AI_SDK_SCHEMA_SYMBOL in schema;\n}\n\nfunction isZodObjectSchema(schema: unknown): schema is ZodObject<ZodRawShape> {\n if (typeof schema !== 'object' || schema === null) {\n return false;\n }\n const candidate = schema as {\n _zod?: { def?: { type?: string } };\n _def?: { typeName?: string };\n shape?: unknown;\n };\n // Zod v4 instances carry `_zod`; Zod v3 instances carry `_def`.\n if (!('_zod' in candidate) && !('_def' in candidate)) {\n return false;\n }\n const typeTag = candidate._zod?.def?.type ?? candidate._def?.typeName;\n if (typeTag !== 'object' && typeTag !== 'ZodObject') {\n return false;\n }\n return typeof candidate.shape === 'object' && candidate.shape !== null;\n}\n\n/**\n * Bridges AI SDK tool definitions (the `ai` package's `tool()` helper) into\n * an in-process SDK MCP server that the Claude Code CLI can execute.\n *\n * Why this helper exists: the Claude Code CLI executes its own tools, so AI\n * SDK tools passed to `generateText`/`streamText` via the `tools` option\n * cannot be auto-bridged by the provider — at the `LanguageModelV3` layer the\n * provider only receives tool *declarations* (name, description, JSON\n * schema); the `execute` functions live in the `ai` package layer and never\n * reach providers. This helper is the explicit alternative: pass your tools\n * here and wire the result into the `mcpServers` setting.\n *\n * Validation scope: the Agent SDK's `tool()` takes only the schema SHAPE and\n * validates incoming args against a default `z.object(shape)` — running\n * FIELD-LEVEL validation and transforms (the handler receives each field's\n * parsed `_output`) and STRIPPING unknown keys — before this handler runs. The\n * bridge does NOT re-parse on top of that: re-parsing the SDK's already-parsed\n * output against the original schema would re-run field transforms and would\n * outright reject any schema whose output type differs from its input (e.g.\n * `z.string().transform(v => v.length)`). Consequently OBJECT-LEVEL constructs\n * are NOT enforced by the bridge — `.refine()`/`.superRefine()` (cross-field\n * invariants) and `.strict()`/`.passthrough()`/`.catchall()` (unknown-key\n * modes) — so perform those checks inside `execute()`.\n *\n * Each tool's `execute` is called with the SDK-validated input and a minimal\n * options object ({@link AiSdkToolExecuteOptions}). String results pass\n * through as MCP text content; all other results are `JSON.stringify`'d.\n * Errors thrown (or rejections) become `isError: true` tool results instead\n * of crashing the CLI session. Results that cannot be serialized to JSON\n * (e.g. circular objects) also become `isError: true` results with a\n * serialization message, even though the tool itself succeeded.\n *\n * Tool results surface to the AI SDK as provider-executed dynamic tool parts\n * (`tool-call`/`tool-result` with `mcp__<serverName>__<toolName>` names), not\n * as executions of your local `tools` option.\n *\n * @param name - MCP server name. Tools are exposed to the CLI as\n * `mcp__<name>__<toolName>`.\n * @param tools - Map of tool name to AI SDK tool. Each tool must have an\n * `execute` function and a Zod object schema as its `inputSchema`\n * (`jsonSchema()`-based tools are rejected).\n * @returns An SDK MCP server config for the `mcpServers` setting.\n * @throws If a tool lacks an `execute` function or its `inputSchema` is not\n * a Zod object schema.\n *\n * @example\n * ```typescript\n * import { generateText, tool } from 'ai';\n * import { z } from 'zod';\n * import { claudeCode, createAiSdkMcpServer } from 'ai-sdk-provider-claude-code';\n *\n * const tools = {\n * add: tool({\n * description: 'Add two numbers',\n * inputSchema: z.object({ a: z.number(), b: z.number() }),\n * execute: async ({ a, b }) => ({ sum: a + b }),\n * }),\n * };\n *\n * const { text } = await generateText({\n * model: claudeCode('sonnet', {\n * mcpServers: { myTools: createAiSdkMcpServer('myTools', tools) },\n * // Tools are named mcp__<serverName>__<toolName>\n * allowedTools: ['mcp__myTools__add'],\n * }),\n * prompt: 'What is 2 + 3? Use the add tool.',\n * });\n * ```\n */\nexport function createAiSdkMcpServer(\n name: string,\n tools: Record<string, AiSdkLikeTool>\n): McpSdkServerConfigWithInstance {\n const defs = Object.entries(tools).map(([toolName, def]) => {\n const execute = def.execute;\n if (typeof execute !== 'function') {\n throw new Error(\n `createAiSdkMcpServer: tool \"${toolName}\" has no execute function. ` +\n 'Only tools that execute locally can be bridged to the Claude Code CLI.'\n );\n }\n if (isAiSdkJsonSchema(def.inputSchema)) {\n throw new Error(\n `createAiSdkMcpServer: tool \"${toolName}\" uses a JSON Schema-based inputSchema ` +\n \"(e.g. the AI SDK's jsonSchema() helper). Only Zod object schemas are supported \" +\n \"because the Agent SDK's tool() requires a Zod shape. \" +\n 'Define inputSchema with z.object({...}) instead.'\n );\n }\n if (!isZodObjectSchema(def.inputSchema)) {\n throw new Error(\n `createAiSdkMcpServer: tool \"${toolName}\" has an inputSchema that is not a Zod object ` +\n 'schema. Pass the same z.object({...}) schema you would give to the AI SDK tool() helper.'\n );\n }\n // Narrowed schema (captured so the async handler closure keeps the type).\n const zodSchema: ZodObject<ZodRawShape> = def.inputSchema;\n return tool(\n toolName,\n def.description ?? '',\n zodSchema.shape as ZodRawShape,\n async (args: Record<string, unknown>, extra: unknown): Promise<MinimalCallToolResult> => {\n try {\n const extraInfo = (extra ?? {}) as { signal?: AbortSignal; requestId?: string | number };\n // Pass the SDK's already-parsed `args` straight to execute. The Agent\n // SDK's tool() takes only the schema SHAPE and validates incoming args\n // against a default z.object(shape) — running field-level validation\n // AND transforms (InferShape = each field's `_output`) and stripping\n // unknown keys — BEFORE this handler runs. The bridge therefore does\n // NOT re-parse: re-parsing the SDK's output against the original\n // schema would re-run field transforms (and outright FAIL for any\n // schema whose output type differs from its input, e.g.\n // z.string().transform(v => v.length)). Object-level refinements\n // (.refine/.superRefine) and unknown-key modes (.strict/.passthrough/\n // .catchall) are consequently NOT enforced by the bridge — see the\n // helper's JSDoc; perform cross-field/unknown-key checks inside\n // execute(). `this === def` is preserved so tools can read off their\n // own object; the MCP request id is forwarded as `toolCallId` only\n // when present (never coerced to 'undefined').\n const result: unknown = await execute.call(def, args as never, {\n toolCallId: extraInfo.requestId !== undefined ? String(extraInfo.requestId) : undefined,\n abortSignal: extraInfo.signal,\n });\n const normalized = await normalizeToolResultToText(toolName, result);\n if ('isError' in normalized) {\n return normalized.isError;\n }\n return { content: [{ type: 'text', text: normalized.text }] };\n } catch (error) {\n return buildIsErrorResult(error instanceof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UAAmD;AACvF,YAAI;AACF,gBAAM,YAAa,SAAS,CAAC;AAgB7B,gBAAM,SAAkB,MAAM,QAAQ,KAAK,KAAK,MAAe;AAAA,YAC7D,YAAY,UAAU,cAAc,SAAY,OAAO,UAAU,SAAS,IAAI;AAAA,YAC9E,aAAa,UAAU;AAAA,UACzB,CAAC;AACD,gBAAM,aAAa,MAAM,0BAA0B,UAAU,MAAM;AACnE,cAAI,aAAa,YAAY;AAC3B,mBAAO,WAAW;AAAA,UACpB;AACA,iBAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,WAAW,KAAK,CAAC,EAAE;AAAA,QAC9D,SAAS,OAAO;AACd,iBAAO,mBAAmB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,QAClF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,mBAAmB,EAAE,MAAM,OAAO,KAAK,CAAC;AACjD;","names":["NoSuchModelError","APICallError","LoadAPIKeyError","tool","tool","largestSize","content","APICallError","LoadAPIKeyError","tool","NoSuchModelError","createSdkMcpServer","tool"]}
|