{"version":3,"sources":["../src/index.ts","../src/claude-code-provider.ts","../src/claude-code-language-model.ts","../src/convert-to-claude-code-messages.ts","../src/extract-json.ts","../src/errors.ts","../src/map-claude-code-finish-reason.ts","../src/validation.ts","../src/logger.ts","../src/mcp-helpers.ts"],"sourcesContent":["/**\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 LanguageModelV1 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 } 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 {\n  HookEvent,\n  HookCallback,\n  HookCallbackMatcher,\n  HookInput,\n  HookJSONOutput,\n  PreToolUseHookInput,\n  PostToolUseHookInput,\n  UserPromptSubmitHookInput,\n  SessionStartHookInput,\n  SessionEndHookInput,\n  CanUseTool,\n  PermissionResult,\n  PermissionUpdate,\n  PermissionBehavior,\n  PermissionRuleValue,\n  McpServerConfig,\n  McpSdkServerConfigWithInstance,\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 type { LanguageModelV2, ProviderV2 } 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 ProviderV1.\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 ProviderV2 {\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): LanguageModelV2;\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): LanguageModelV2;\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): LanguageModelV2;\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  ): LanguageModelV2 => {\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\n  // Add textEmbeddingModel method that throws NoSuchModelError\n  provider.textEmbeddingModel = (modelId: string) => {\n    throw new NoSuchModelError({\n      modelId,\n      modelType: 'textEmbeddingModel',\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  LanguageModelV2,\n  LanguageModelV2CallWarning,\n  LanguageModelV2FinishReason,\n  LanguageModelV2StreamPart,\n  LanguageModelV2Usage,\n  JSONValue,\n} from '@ai-sdk/provider';\nimport { NoSuchModelError, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\nimport { generateId } from '@ai-sdk/provider-utils';\nimport type { ClaudeCodeSettings, Logger } from './types.js';\nimport { convertToClaudeCodeMessages } from './convert-to-claude-code-messages.js';\nimport { extractJson } from './extract-json.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 } 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  // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 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\ntype ClaudeToolUse = {\n  id: string;\n  name: string;\n  input: unknown;\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 = LanguageModelV2StreamPart | ToolErrorPart;\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};\n\nfunction toAsyncIterablePrompt(\n  messagesPrompt: string,\n  outputStreamEnded: Promise<unknown>,\n  sessionId?: string,\n  contentParts?: SDKUserMessage['message']['content']\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 msg: SDKUserMessage = {\n    type: 'user',\n    message: {\n      role: 'user',\n      content,\n    },\n    parent_tool_use_id: null,\n    session_id: sessionId ?? '',\n  };\n  return {\n    async *[Symbol.asyncIterator]() {\n      yield msg;\n      await outputStreamEnded;\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 4.1 Opus model (most capable)\n * - 'sonnet': Claude 4.5 Sonnet model (balanced performance)\n * - 'haiku': Claude 4.5 Haiku model (fastest, most cost-effective) - Available in Claude Code v2.0.17+\n * - Custom string: Any other model identifier supported by the CLI\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-3-opus-20240229');\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 * Language model implementation for Claude Code SDK.\n * This class implements the AI SDK's LanguageModelV1 interface to provide\n * integration with Claude models through the Claude Code SDK.\n *\n * Features:\n * - Supports streaming and non-streaming generation\n * - Handles JSON object generation mode\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 * - Does not support structured outputs (tool 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 */\nexport class ClaudeCodeLanguageModel implements LanguageModelV2 {\n  readonly specificationVersion = 'v2' as const;\n  readonly defaultObjectGenerationMode = 'json' as const;\n  readonly supportsImageUrls = false;\n  readonly supportedUrls = {};\n  readonly supportsStructuredOutputs = false;\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 extractToolUses(content: unknown): ClaudeToolUse[] {\n    if (!Array.isArray(content)) {\n      return [];\n    }\n\n    return content\n      .filter(\n        (item): item is { type: string; id?: unknown; name?: unknown; input?: unknown } =>\n          typeof item === 'object' &&\n          item !== null &&\n          'type' in item &&\n          (item as { type: unknown }).type === 'tool_use'\n      )\n      .map((item) => {\n        const { id, name, input } = item as { id?: unknown; name?: unknown; input?: unknown };\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        } satisfies ClaudeToolUse;\n      });\n  }\n\n  private extractToolResults(content: unknown): ClaudeToolResult[] {\n    if (!Array.isArray(content)) {\n      return [];\n    }\n\n    return content\n      .filter(\n        (\n          item\n        ): item is {\n          type: string;\n          tool_use_id?: unknown;\n          content?: unknown;\n          is_error?: unknown;\n          name?: unknown;\n        } =>\n          typeof item === 'object' &&\n          item !== null &&\n          'type' in item &&\n          (item as { type: unknown }).type === 'tool_result'\n      )\n      .map((item) => {\n        const { tool_use_id, content, is_error, name } = item;\n        return {\n          id:\n            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    if (!Array.isArray(content)) {\n      return [];\n    }\n\n    return content\n      .filter(\n        (\n          item\n        ): item is {\n          type: string;\n          tool_use_id?: unknown;\n          error?: unknown;\n          name?: unknown;\n        } =>\n          typeof item === 'object' &&\n          item !== null &&\n          'type' in item &&\n          (item as { type: unknown }).type === 'tool_error'\n      )\n      .map((item) => {\n        const { tool_use_id, error, name } = item as {\n          tool_use_id?: unknown;\n          error?: unknown;\n          name?: unknown;\n        };\n        return {\n          id:\n            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\n    return result;\n  }\n\n  private generateAllWarnings(\n    options:\n      | Parameters<LanguageModelV2['doGenerate']>[0]\n      | Parameters<LanguageModelV2['doStream']>[0],\n    prompt: string\n  ): LanguageModelV2CallWarning[] {\n    const warnings: LanguageModelV2CallWarning[] = [];\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-setting',\n          setting: param as\n            | 'temperature'\n            | 'maxTokens'\n            | 'topP'\n            | 'topK'\n            | 'presencePenalty'\n            | 'frequencyPenalty'\n            | 'stopSequences'\n            | 'seed',\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    // 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 handleJsonExtraction(text: string, warnings: LanguageModelV2CallWarning[]): string {\n    const extracted = extractJson(text);\n    const validation = this.validateJsonExtraction(text, extracted);\n\n    if (!validation.valid && validation.warning) {\n      warnings.push(validation.warning);\n    }\n\n    return extracted;\n  }\n\n  private createQueryOptions(abortController: AbortController): Options {\n    const opts: Partial<Options> & Record<string, unknown> = {\n      model: this.getModel(),\n      abortController,\n      resume: this.settings.resume ?? this.sessionId,\n      pathToClaudeCodeExecutable: this.settings.pathToClaudeCodeExecutable,\n      maxTurns: this.settings.maxTurns,\n      maxThinkingTokens: this.settings.maxThinkingTokens,\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      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.stderr !== undefined) {\n      opts.stderr = this.settings.stderr;\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    // 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.env !== undefined) {\n      opts.env = { ...process.env, ...this.settings.env };\n    }\n    return opts as Options;\n  }\n\n  private handleClaudeCodeError(\n    error: unknown,\n    messagesPrompt: 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    ];\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    return createAPICallError({\n      message: isErrorWithMessage(error) && error.message ? error.message : 'Claude Code SDK error',\n      code: errorCode || undefined,\n      exitCode: exitCode,\n      stderr: isErrorWithCode(error) && typeof error.stderr === 'string' ? error.stderr : undefined,\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 validateJsonExtraction(\n    originalText: string,\n    extractedJson: string\n  ): { valid: boolean; warning?: LanguageModelV2CallWarning } {\n    // If the extracted JSON is the same as original, extraction likely failed\n    if (extractedJson === originalText) {\n      return {\n        valid: false,\n        warning: {\n          type: 'other',\n          message:\n            'JSON extraction from model response may be incomplete or modified. The model may not have returned valid JSON.',\n        },\n      };\n    }\n\n    // Try to parse the extracted JSON to validate it\n    try {\n      JSON.parse(extractedJson);\n      return { valid: true };\n    } catch {\n      return {\n        valid: false,\n        warning: {\n          type: 'other',\n          message: 'JSON extraction resulted in invalid JSON. The response may be malformed.',\n        },\n      };\n    }\n  }\n\n  async doGenerate(\n    options: Parameters<LanguageModelV2['doGenerate']>[0]\n  ): Promise<Awaited<ReturnType<LanguageModelV2['doGenerate']>>> {\n    this.logger.debug(`[claude-code] Starting doGenerate request with model: ${this.modelId}`);\n\n    // Determine mode based on responseFormat\n    const mode =\n      options.responseFormat?.type === 'json'\n        ? { type: 'object-json' as const }\n        : { type: 'regular' as const };\n\n    this.logger.debug(\n      `[claude-code] Request mode: ${mode.type}, response format: ${options.responseFormat?.type ?? 'none'}`\n    );\n\n    const {\n      messagesPrompt,\n      warnings: messageWarnings,\n      streamingContentParts,\n      hasImageParts,\n    } = convertToClaudeCodeMessages(\n      options.prompt,\n      mode,\n      options.responseFormat?.type === 'json' ? options.responseFormat.schema : undefined\n    );\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    const queryOptions = this.createQueryOptions(abortController);\n\n    let text = '';\n    let usage: LanguageModelV2Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n    let finishReason: LanguageModelV2FinishReason = 'stop';\n    let wasTruncated = false;\n    let costUsd: number | undefined;\n    let durationMs: number | undefined;\n    let rawUsage: unknown | undefined;\n    const warnings: LanguageModelV2CallWarning[] = this.generateAllWarnings(\n      options,\n      messagesPrompt\n    );\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 wantsStreamInput =\n      modeSetting === 'always' || (modeSetting === 'auto' && !!this.settings.canUseTool);\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 (this.settings.canUseTool && this.settings.permissionPromptToolName) {\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            this.settings.resume ?? this.sessionId,\n            streamingContentParts\n          )\n        : messagesPrompt;\n\n      this.logger.debug(\n        `[claude-code] Executing query with streamingInput: ${wantsStreamInput}, session: ${this.settings.resume ?? this.sessionId ?? 'new'}`\n      );\n\n      const response = query({\n        prompt: sdkPrompt,\n        options: queryOptions,\n      });\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          text += message.message.content\n            .map((c: { type: string; text?: string }) => (c.type === 'text' ? c.text : ''))\n            .join('');\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\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            rawUsage = message.usage;\n            usage = {\n              inputTokens:\n                (message.usage.cache_creation_input_tokens ?? 0) +\n                (message.usage.cache_read_input_tokens ?? 0) +\n                (message.usage.input_tokens ?? 0),\n              outputTokens: message.usage.output_tokens ?? 0,\n              totalTokens:\n                (message.usage.cache_creation_input_tokens ?? 0) +\n                (message.usage.cache_read_input_tokens ?? 0) +\n                (message.usage.input_tokens ?? 0) +\n                (message.usage.output_tokens ?? 0),\n            };\n\n            this.logger.debug(\n              `[claude-code] Token usage - Input: ${usage.inputTokens}, Output: ${usage.outputTokens}, Total: ${usage.totalTokens}`\n            );\n          }\n\n          finishReason = mapClaudeCodeFinishReason(message.subtype);\n          this.logger.debug(`[claude-code] Finish reason: ${finishReason}`);\n        } else if (message.type === 'system' && message.subtype === 'init') {\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 = 'length';\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);\n      }\n    } finally {\n      if (options.abortSignal && abortListener) {\n        options.abortSignal.removeEventListener('abort', abortListener);\n      }\n    }\n\n    // Extract JSON if responseFormat indicates JSON mode\n    if (options.responseFormat?.type === 'json' && text) {\n      text = this.handleJsonExtraction(text, warnings);\n    }\n\n    return {\n      content: [{ type: 'text', text }],\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          ...(rawUsage !== undefined && { rawUsage: rawUsage as JSONValue }),\n          ...(wasTruncated && { truncated: true }),\n        },\n      },\n    };\n  }\n\n  async doStream(\n    options: Parameters<LanguageModelV2['doStream']>[0]\n  ): Promise<Awaited<ReturnType<LanguageModelV2['doStream']>>> {\n    this.logger.debug(`[claude-code] Starting doStream request with model: ${this.modelId}`);\n\n    // Determine mode based on responseFormat\n    const mode =\n      options.responseFormat?.type === 'json'\n        ? { type: 'object-json' as const }\n        : { type: 'regular' as const };\n\n    this.logger.debug(\n      `[claude-code] Stream mode: ${mode.type}, response format: ${options.responseFormat?.type ?? 'none'}`\n    );\n\n    const {\n      messagesPrompt,\n      warnings: messageWarnings,\n      streamingContentParts,\n      hasImageParts,\n    } = convertToClaudeCodeMessages(\n      options.prompt,\n      mode,\n      options.responseFormat?.type === 'json' ? options.responseFormat.schema : undefined\n    );\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    const queryOptions = this.createQueryOptions(abortController);\n\n    const warnings: LanguageModelV2CallWarning[] = this.generateAllWarnings(\n      options,\n      messagesPrompt\n    );\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 wantsStreamInput =\n      modeSetting === 'always' || (modeSetting === 'auto' && !!this.settings.canUseTool);\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        const streamWarnings: LanguageModelV2CallWarning[] = [];\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              },\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: LanguageModelV2Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n        let accumulatedText = '';\n        let textPartId: string | undefined;\n\n        try {\n          // Emit stream-start with warnings\n          controller.enqueue({ type: 'stream-start', warnings });\n\n          if (this.settings.canUseTool && this.settings.permissionPromptToolName) {\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                this.settings.resume ?? this.sessionId,\n                streamingContentParts\n              )\n            : messagesPrompt;\n\n          this.logger.debug(\n            `[claude-code] Starting stream query with streamingInput: ${wantsStreamInput}, session: ${this.settings.resume ?? this.sessionId ?? 'new'}`\n          );\n\n          const response = query({\n            prompt: sdkPrompt,\n            options: queryOptions,\n          });\n\n          for await (const message of response) {\n            this.logger.debug(`[claude-code] Stream received message type: ${message.type}`);\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              const content = message.message.content;\n\n              for (const tool of this.extractToolUses(content)) {\n                const toolId = tool.id;\n                let state = toolStates.get(toolId);\n                if (!state) {\n                  state = {\n                    name: tool.name,\n                    inputStarted: false,\n                    inputClosed: false,\n                    callEmitted: false,\n                  };\n                  toolStates.set(toolId, state);\n                  this.logger.debug(\n                    `[claude-code] New tool use detected - Tool: ${tool.name}, ID: ${toolId}`\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                  } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\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                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            } 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              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                  state = {\n                    name: toolName,\n                    inputStarted: false,\n                    inputClosed: false,\n                    callEmitted: false,\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                    } 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\n                emitToolCall(result.id, state);\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: result.id,\n                  toolName,\n                  result: normalizedResult,\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,\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                  state = {\n                    name: toolName,\n                    inputStarted: true,\n                    inputClosed: true,\n                    callEmitted: false,\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                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                    },\n                  },\n                } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n              }\n            } else if (message.type === 'result') {\n              done();\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              let rawUsage: unknown | undefined;\n              if ('usage' in message) {\n                rawUsage = message.usage;\n                usage = {\n                  inputTokens:\n                    (message.usage.cache_creation_input_tokens ?? 0) +\n                    (message.usage.cache_read_input_tokens ?? 0) +\n                    (message.usage.input_tokens ?? 0),\n                  outputTokens: message.usage.output_tokens ?? 0,\n                  totalTokens:\n                    (message.usage.cache_creation_input_tokens ?? 0) +\n                    (message.usage.cache_read_input_tokens ?? 0) +\n                    (message.usage.input_tokens ?? 0) +\n                    (message.usage.output_tokens ?? 0),\n                };\n\n                this.logger.debug(\n                  `[claude-code] Stream token usage - Input: ${usage.inputTokens}, Output: ${usage.outputTokens}, Total: ${usage.totalTokens}`\n                );\n              }\n\n              const finishReason: LanguageModelV2FinishReason = mapClaudeCodeFinishReason(\n                message.subtype\n              );\n\n              this.logger.debug(`[claude-code] Stream finish reason: ${finishReason}`);\n\n              // Store session ID in the model instance\n              this.setSessionId(message.session_id);\n\n              // Check if we need to extract JSON based on responseFormat\n              if (options.responseFormat?.type === 'json' && accumulatedText) {\n                const extractedJson = this.handleJsonExtraction(accumulatedText, streamWarnings);\n\n                // Emit text-start/delta/end for JSON content\n                const jsonTextId = generateId();\n                controller.enqueue({\n                  type: 'text-start',\n                  id: jsonTextId,\n                });\n                controller.enqueue({\n                  type: 'text-delta',\n                  id: jsonTextId,\n                  delta: extractedJson,\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\n                controller.enqueue({\n                  type: 'text-end',\n                  id: textPartId,\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                    ...(rawUsage !== undefined && { rawUsage: rawUsage as JSONValue }),\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            } else if (message.type === 'system' && message.subtype === 'init') {\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: LanguageModelV2CallWarning = {\n              type: 'other',\n              message: CLAUDE_CODE_TRUNCATION_WARNING,\n            };\n            streamWarnings.push(truncationWarning);\n\n            const emitJsonText = () => {\n              const extractedJson = this.handleJsonExtraction(accumulatedText, streamWarnings);\n              const jsonTextId = generateId();\n              controller.enqueue({\n                type: 'text-start',\n                id: jsonTextId,\n              });\n              controller.enqueue({\n                type: 'text-delta',\n                id: jsonTextId,\n                delta: extractedJson,\n              });\n              controller.enqueue({\n                type: 'text-end',\n                id: jsonTextId,\n              });\n            };\n\n            if (options.responseFormat?.type === 'json') {\n              emitJsonText();\n            } else if (textPartId) {\n              controller.enqueue({\n                type: 'text-end',\n                id: textPartId,\n              });\n            } else if (accumulatedText) {\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: 'length',\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);\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<LanguageModelV2StreamPart>,\n      request: {\n        body: messagesPrompt,\n      },\n    };\n  }\n\n  private serializeWarningsForMetadata(warnings: LanguageModelV2CallWarning[]): 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-setting') {\n        const setting = (w as { setting: unknown }).setting;\n        if (setting !== undefined) base.setting = String(setting);\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 * @param mode - Optional mode for specialized output formats (e.g., JSON generation)\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 *   { type: 'regular' }\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 * - In 'object-json' mode, explicit JSON instructions are appended\n */\nexport function convertToClaudeCodeMessages(\n  prompt: readonly ModelMessage[],\n  mode: { type: 'regular' | 'object-json' | 'object-tool' } = { type: 'regular' },\n  jsonSchema?: unknown\n): {\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        for (const tool of message.content) {\n          const resultText =\n            tool.output.type === 'text' ? tool.output.value : JSON.stringify(tool.output.value);\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  // For JSON mode, add explicit instruction to ensure JSON output\n  let 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  if (mode?.type === 'object-json' && jsonSchema) {\n    // Prepend JSON instructions at the very beginning, before any messages\n    const schemaStr = JSON.stringify(jsonSchema, null, 2);\n\n    finalPrompt = `CRITICAL: You MUST respond with ONLY a JSON object. NO other text, NO explanations, NO questions.\n\nYour response MUST start with { and end with }\n\nThe JSON MUST match this EXACT schema:\n${schemaStr}\n\nNow, based on the following conversation, generate ONLY the JSON object with the exact fields specified above:\n\n${finalPrompt}\n\nRemember: Your ENTIRE response must be ONLY the JSON object, starting with { and ending with }`;\n\n    streamingParts = [{ type: 'text', text: finalPrompt }, ...imagePartsInOrder];\n  }\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","/**\n * Extract JSON from Claude's response using a tolerant parser.\n *\n * The function removes common wrappers such as markdown fences or variable\n * declarations and then attempts to parse the remaining text with\n * `jsonc-parser`.  If valid JSON (or JSONC) can be parsed, it is returned as a\n * string via `JSON.stringify`.  Otherwise the original text is returned.\n *\n * @param text - Raw text which may contain JSON\n * @returns A valid JSON string if extraction succeeds, otherwise the original text\n */\nimport { parse, type ParseError } from 'jsonc-parser';\n\nexport function extractJson(text: string): string {\n  let content = text.trim();\n\n  // Strip ```json or ``` fences\n  const fenceMatch = /```(?:json)?\\s*([\\s\\S]*?)\\s*```/i.exec(content);\n  if (fenceMatch) {\n    content = fenceMatch[1];\n  }\n\n  // Strip variable declarations like `const foo =` or `let foo =`\n  const varMatch = /^\\s*(?:const|let|var)\\s+\\w+\\s*=\\s*([\\s\\S]*)/i.exec(content);\n  if (varMatch) {\n    content = varMatch[1];\n    // Remove trailing semicolon if present\n    if (content.trim().endsWith(';')) {\n      content = content.trim().slice(0, -1);\n    }\n  }\n\n  // Find the first opening bracket\n  const firstObj = content.indexOf('{');\n  const firstArr = content.indexOf('[');\n  if (firstObj === -1 && firstArr === -1) {\n    return text;\n  }\n  const start =\n    firstArr === -1 ? firstObj : firstObj === -1 ? firstArr : Math.min(firstObj, firstArr);\n  content = content.slice(start);\n\n  // Try to parse the entire string with jsonc-parser\n  const tryParse = (value: string): string | undefined => {\n    const errors: ParseError[] = [];\n    try {\n      const result = parse(value, errors, { allowTrailingComma: true });\n      if (errors.length === 0) {\n        return JSON.stringify(result, null, 2);\n      }\n    } catch {\n      // ignore\n    }\n    return undefined;\n  };\n\n  const parsed = tryParse(content);\n  if (parsed !== undefined) {\n    return parsed;\n  }\n\n  // If parsing the full string failed, use a more efficient approach\n  // to find valid JSON boundaries\n  const openChar = content[0];\n  const closeChar = openChar === '{' ? '}' : ']';\n\n  // Find all potential closing positions by tracking nesting depth\n  const closingPositions: number[] = [];\n  let depth = 0;\n  let inString = false;\n  let escapeNext = false;\n\n  for (let i = 0; i < content.length; i++) {\n    const char = content[i];\n\n    if (escapeNext) {\n      escapeNext = false;\n      continue;\n    }\n\n    if (char === '\\\\') {\n      escapeNext = true;\n      continue;\n    }\n\n    if (char === '\"' && !inString) {\n      inString = true;\n      continue;\n    }\n\n    if (char === '\"' && inString) {\n      inString = false;\n      continue;\n    }\n\n    // Skip content inside strings\n    if (inString) continue;\n\n    if (char === openChar) {\n      depth++;\n    } else if (char === closeChar) {\n      depth--;\n      if (depth === 0) {\n        closingPositions.push(i + 1);\n      }\n    }\n  }\n\n  // Try parsing at each valid closing position, starting from the end\n  for (let i = closingPositions.length - 1; i >= 0; i--) {\n    const attempt = tryParse(content.slice(0, closingPositions[i]));\n    if (attempt !== undefined) {\n      return attempt;\n    }\n  }\n\n  // As a final fallback, try the original character-by-character approach\n  // but only for the last 1000 characters to limit performance impact\n  const searchStart = Math.max(0, content.length - 1000);\n  for (let end = content.length - 1; end > searchStart; end--) {\n    const attempt = tryParse(content.slice(0, end));\n    if (attempt !== undefined) {\n      return attempt;\n    }\n  }\n\n  return text;\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 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 { LanguageModelV2FinishReason } from '@ai-sdk/provider';\n\n/**\n * Maps Claude Code SDK result subtypes to AI SDK finish reasons.\n *\n * @param subtype - The result subtype from Claude Code SDK\n * @returns The corresponding AI SDK finish reason\n *\n * @example\n * ```typescript\n * const finishReason = mapClaudeCodeFinishReason('error_max_turns');\n * // Returns: 'length'\n * ```\n *\n * @remarks\n * Mappings:\n * - 'success' -> 'stop' (normal completion)\n * - 'error_max_turns' -> 'length' (hit turn limit)\n * - 'error_during_execution' -> 'error' (execution error)\n * - default -> 'stop' (unknown subtypes treated as normal completion)\n */\nexport function mapClaudeCodeFinishReason(subtype?: string): LanguageModelV2FinishReason {\n  switch (subtype) {\n    case 'success':\n      return 'stop';\n    case 'error_max_turns':\n      return 'length';\n    case 'error_during_execution':\n      return 'error';\n    default:\n      return 'stop';\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    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.enum(['default', 'acceptEdits', 'bypassPermissions', 'plan']).optional(),\n    permissionPromptToolName: z.string().optional(),\n    continue: z.boolean().optional(),\n    resume: z.string().optional(),\n    allowedTools: z.array(z.string()).optional(),\n    disallowedTools: z.array(z.string()).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    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.object({\n          description: z.string(),\n          tools: z.array(z.string()).optional(),\n          prompt: z.string(),\n          model: z.enum(['sonnet', 'opus', 'haiku', 'inherit']).optional(),\n        })\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  })\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    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  debug: (message: string) => console.debug(`[DEBUG] ${message}`),\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","import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport type { McpSdkServerConfigWithInstance } 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 * 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    }\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    )\n  );\n  return createSdkMcpServer({ name: config.name, version: config.version, tools: defs });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,mBAAiC;;;ACOjC,IAAAC,mBAAgE;AAChE,4BAA2B;;;ACA3B,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,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QAAQ,OAAO,KAAK,EAAE;AAAA,IAAI,CAAC,CAAC,MAAM,GAAG,UACvD;AAAA,MACE;AAAA,MACA,IAAI;AAAA,MACJ,IAAI,YAAY;AAAA,MAChB,CAAC,MAA+B,UAAmB,IAAI,QAAQ,MAAM,KAAK;AAAA,IAC5E;AAAA,EACF;AACA,aAAO,6CAAmB,EAAE,MAAM,OAAO,MAAM,SAAS,OAAO,SAAS,OAAO,KAAK,CAAC;AACvF;","names":["import_provider","import_provider","tool","tool","content","tool","import_claude_agent_sdk","import_claude_agent_sdk","import_zod"]}