ai-sdk-provider-claude-code 0.2.1 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/claude-code-provider.ts","../src/claude-code-language-model.ts","../src/convert-to-claude-code-messages.ts","../src/extract-json.ts","../src/errors.ts","../src/map-claude-code-finish-reason.ts","../src/validation.ts","../src/logger.ts"],"sourcesContent":["import type { LanguageModelV1, ProviderV1 } 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 ProviderV1 {\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): LanguageModelV1;\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(\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ): LanguageModelV1;\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(\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ): LanguageModelV1;\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(\n options: ClaudeCodeProviderSettings = {},\n): 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 ): LanguageModelV1 => {\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 (\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ) {\n if (new.target) {\n throw new Error(\n 'The Claude Code model function cannot be called with the new keyword.',\n );\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 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();","import type {\n LanguageModelV1,\n LanguageModelV1CallWarning,\n LanguageModelV1FinishReason,\n LanguageModelV1StreamPart,\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 } from './logger.js';\n\nimport { query, AbortError, type Options } from '@anthropic-ai/claude-code';\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', 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 Opus model (most capable)\n * - 'sonnet': Claude 4 Sonnet model (balanced performance)\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 customModel = claudeCode('claude-3-opus-20240229');\n * ```\n */\nexport type ClaudeCodeModelId = 'opus' | 'sonnet' | (string & {});\n\nconst modelMap: Record<string, string> = {\n 'opus': 'opus',\n 'sonnet': 'sonnet',\n};\n\n/**\n * Language model implementation for Claude Code CLI.\n * This class implements the AI SDK's LanguageModelV1 interface to provide\n * integration with Claude models through the Claude Code CLI.\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 * - Does not support image inputs\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 LanguageModelV1 {\n readonly specificationVersion = 'v1' as const;\n readonly defaultObjectGenerationMode = 'json' as const;\n readonly supportsImageUrls = false;\n readonly supportsStructuredOutputs = false;\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 this.logger = getLogger(this.settings.logger);\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 generateAllWarnings(\n options: Parameters<LanguageModelV1['doGenerate']>[0] | Parameters<LanguageModelV1['doStream']>[0],\n prompt: string\n ): LanguageModelV1CallWarning[] {\n const warnings: LanguageModelV1CallWarning[] = [];\n const unsupportedParams: string[] = [];\n \n // Check for unsupported parameters\n if (options.temperature !== undefined) unsupportedParams.push('temperature');\n if (options.maxTokens !== undefined) unsupportedParams.push('maxTokens');\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) 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 'temperature' | 'maxTokens' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed',\n details: `Claude Code CLI 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 createQueryOptions(abortController: AbortController): Options {\n return {\n model: this.getModel(),\n abortController,\n resume: this.settings.resume ?? this.sessionId,\n pathToClaudeCodeExecutable: this.settings.pathToClaudeCodeExecutable,\n customSystemPrompt: this.settings.customSystemPrompt,\n appendSystemPrompt: this.settings.appendSystemPrompt,\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 };\n }\n\n private handleClaudeCodeError(\n error: unknown,\n messagesPrompt: string\n ): APICallError | LoadAPIKeyError {\n // Handle AbortError from the SDK\n if (error instanceof AbortError) {\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 = (err: unknown): 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 = isErrorWithMessage(error) && error.message \n ? error.message.toLowerCase() \n : '';\n \n const exitCode = isErrorWithCode(error) && typeof error.exitCode === 'number' \n ? error.exitCode \n : undefined;\n \n const isAuthError = authErrorPatterns.some(pattern => errorMessage.includes(pattern)) ||\n exitCode === 401;\n\n if (isAuthError) {\n return createAuthenticationError({\n message: isErrorWithMessage(error) && error.message \n ? error.message \n : 'Authentication failed. Please ensure Claude Code CLI is properly authenticated.',\n });\n }\n\n // Check for timeout errors\n const errorCode = isErrorWithCode(error) && typeof error.code === 'string' \n ? error.code \n : '';\n \n if (errorCode === 'ETIMEDOUT' || errorMessage.includes('timeout')) {\n return createTimeoutError({\n message: isErrorWithMessage(error) && error.message \n ? error.message \n : '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 = errorCode === 'ENOENT' || \n errorCode === 'ECONNREFUSED' ||\n errorCode === 'ETIMEDOUT' ||\n errorCode === 'ECONNRESET';\n\n return createAPICallError({\n message: isErrorWithMessage(error) && error.message \n ? error.message \n : 'Claude Code CLI error',\n code: errorCode || undefined,\n exitCode: exitCode,\n stderr: isErrorWithCode(error) && typeof error.stderr === 'string' \n ? error.stderr \n : 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?: LanguageModelV1CallWarning } {\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: '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<LanguageModelV1['doGenerate']>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>> {\n const { messagesPrompt, warnings: messageWarnings } = convertToClaudeCodeMessages(options.prompt, options.mode);\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal) {\n abortListener = () => abortController.abort();\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n const queryOptions = this.createQueryOptions(abortController);\n\n let text = '';\n let usage = { promptTokens: 0, completionTokens: 0 };\n let finishReason: LanguageModelV1FinishReason = 'stop';\n let costUsd: number | undefined;\n let durationMs: number | undefined;\n let rawUsage: unknown | undefined;\n const warnings: LanguageModelV1CallWarning[] = this.generateAllWarnings(options, messagesPrompt);\n \n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach(warning => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n try {\n const response = query({\n prompt: messagesPrompt,\n options: queryOptions,\n });\n\n for await (const message of response) {\n if (message.type === 'assistant') {\n text += message.message.content.map((c: { type: string; text?: string }) => \n c.type === 'text' ? c.text : ''\n ).join('');\n } else if (message.type === 'result') {\n this.setSessionId(message.session_id);\n costUsd = message.total_cost_usd;\n durationMs = message.duration_ms;\n \n if ('usage' in message) {\n rawUsage = message.usage;\n usage = {\n promptTokens: (message.usage.cache_creation_input_tokens ?? 0) + \n (message.usage.cache_read_input_tokens ?? 0) +\n (message.usage.input_tokens ?? 0),\n completionTokens: message.usage.output_tokens ?? 0,\n };\n }\n\n finishReason = mapClaudeCodeFinishReason(message.subtype);\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.setSessionId(message.session_id);\n }\n }\n } catch (error: unknown) {\n // Special handling for AbortError to preserve abort signal reason\n if (error instanceof AbortError) {\n throw options.abortSignal?.aborted ? options.abortSignal.reason : error;\n }\n \n // Use unified error handler\n throw this.handleClaudeCodeError(error, messagesPrompt);\n } finally {\n if (options.abortSignal && abortListener) {\n options.abortSignal.removeEventListener('abort', abortListener);\n }\n }\n\n // Extract JSON if in object-json mode\n if (options.mode?.type === 'object-json' && text) {\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 text = extracted;\n }\n\n return {\n text: text || undefined,\n usage,\n finishReason,\n rawCall: {\n rawPrompt: messagesPrompt,\n rawSettings: queryOptions,\n },\n warnings: warnings.length > 0 ? warnings : undefined,\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 },\n },\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV1['doStream']>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>> {\n const { messagesPrompt, warnings: messageWarnings } = convertToClaudeCodeMessages(options.prompt, options.mode);\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal) {\n abortListener = () => abortController.abort();\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n const queryOptions = this.createQueryOptions(abortController);\n\n const warnings: LanguageModelV1CallWarning[] = this.generateAllWarnings(options, messagesPrompt);\n \n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach(warning => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const stream = new ReadableStream<LanguageModelV1StreamPart>({\n start: async (controller) => {\n try {\n const response = query({\n prompt: messagesPrompt,\n options: queryOptions,\n });\n\n let usage = { promptTokens: 0, completionTokens: 0 };\n let accumulatedText = '';\n\n for await (const message of response) {\n if (message.type === 'assistant') {\n const text = message.message.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 object-json mode, we need to accumulate the full text\n // and extract JSON at the end, so don't stream individual deltas\n if (options.mode?.type !== 'object-json') {\n controller.enqueue({\n type: 'text-delta',\n textDelta: text,\n });\n }\n }\n } else if (message.type === 'result') {\n let rawUsage: unknown | undefined;\n if ('usage' in message) {\n rawUsage = message.usage;\n usage = {\n promptTokens: (message.usage.cache_creation_input_tokens ?? 0) + \n (message.usage.cache_read_input_tokens ?? 0) +\n (message.usage.input_tokens ?? 0),\n completionTokens: message.usage.output_tokens ?? 0,\n };\n }\n\n const finishReason: LanguageModelV1FinishReason = mapClaudeCodeFinishReason(message.subtype);\n\n // Store session ID in the model instance\n this.setSessionId(message.session_id);\n \n // In object-json mode, extract JSON and send the full text at once\n if (options.mode?.type === 'object-json' && accumulatedText) {\n const extractedJson = extractJson(accumulatedText);\n this.validateJsonExtraction(accumulatedText, extractedJson);\n \n // If validation failed, we should add a warning but we can't modify warnings array in stream\n // So we'll just send the extracted JSON anyway\n // In the future, we could emit a warning stream part if the SDK supports it\n \n controller.enqueue({\n type: 'text-delta',\n textDelta: extractedJson,\n });\n }\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 && { costUsd: message.total_cost_usd }),\n ...(message.duration_ms !== undefined && { durationMs: message.duration_ms }),\n ...(rawUsage !== undefined && { rawUsage: rawUsage as JSONValue }),\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 // 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 controller.close();\n } catch (error: unknown) {\n let errorToEmit: unknown;\n \n // Special handling for AbortError to preserve abort signal reason\n if (error instanceof AbortError) {\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,\n rawCall: {\n rawPrompt: messagesPrompt,\n rawSettings: queryOptions,\n },\n warnings: warnings.length > 0 ? warnings : undefined,\n request: {\n body: messagesPrompt,\n },\n };\n }\n}","import type { LanguageModelV1Prompt } from '@ai-sdk/provider';\n\n/**\n * Converts AI SDK prompt format to Claude Code CLI 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 inputs are not supported and will be ignored with a warning\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: LanguageModelV1Prompt,\n mode?: { type: 'regular' | 'object-json' | 'object-tool' }\n): {\n messagesPrompt: string;\n systemPrompt?: string;\n warnings?: string[];\n} {\n const messages: string[] = [];\n const warnings: string[] = [];\n let systemPrompt: string | undefined;\n\n for (const message of prompt) {\n switch (message.role) {\n case 'system':\n systemPrompt = message.content;\n break;\n \n case 'user':\n if (typeof message.content === 'string') {\n messages.push(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 if (textParts) {\n messages.push(textParts);\n }\n \n // Note: Image parts are not supported by Claude Code CLI\n const imageParts = message.content.filter(part => part.type === 'image');\n if (imageParts.length > 0) {\n warnings.push('Claude Code CLI does not support image inputs. Images will be ignored.');\n }\n }\n break;\n \n case 'assistant':\n if (typeof message.content === 'string') {\n messages.push(`Assistant: ${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 messages.push(`Assistant: ${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 messages.push(`Assistant: [Tool calls made]`);\n }\n }\n break;\n \n case 'tool':\n // Tool results could be included in the conversation\n messages.push(`Tool Result (${message.content[0].toolName}): ${JSON.stringify(message.content[0].result)}`);\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 return { messagesPrompt: finalPrompt, systemPrompt };\n }\n \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 finalPrompt = finalPrompt + '\\n\\n' + formattedMessages.join('\\n\\n');\n } else {\n finalPrompt = formattedMessages.join('\\n\\n');\n }\n \n // For JSON mode, add explicit instruction to ensure JSON output\n if (mode?.type === 'object-json') {\n // Make the JSON instruction even more explicit\n finalPrompt = `${finalPrompt}\n\nCRITICAL INSTRUCTION: You MUST respond with ONLY valid JSON. Follow these rules EXACTLY:\n1. Start your response with an opening brace {\n2. End your response with a closing brace }\n3. Do NOT include any text before the opening brace\n4. Do NOT include any text after the closing brace\n5. Do NOT use markdown code blocks or backticks\n6. Do NOT include explanations or commentary\n7. The ENTIRE response must be valid JSON that can be parsed with JSON.parse()\n\nBegin your response with { and end with }`;\n }\n \n return {\n messagesPrompt: finalPrompt,\n systemPrompt,\n ...(warnings.length > 0 && { warnings }),\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 = 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}","import { APICallError, LoadAPIKeyError } from '@ai-sdk/provider';\n\n/**\n * Metadata associated with Claude Code CLI 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 CLI 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 CLI 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 CLI 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({\n message,\n}: {\n message: string;\n}): LoadAPIKeyError {\n return new LoadAPIKeyError({\n message: message || 'Authentication failed. Please ensure Claude Code CLI is properly authenticated.',\n });\n}\n\n/**\n * Creates a timeout error for Claude Code CLI 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 CLI');\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) 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') 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}","import type { LanguageModelV1FinishReason } from '@ai-sdk/provider';\n\n/**\n * Maps Claude Code CLI result subtypes to AI SDK finish reasons.\n * \n * @param subtype - The result subtype from Claude Code CLI\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(\n subtype?: string\n): LanguageModelV1FinishReason {\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}","import { z } from 'zod';\nimport { existsSync } from 'fs';\n\n/**\n * Validation schemas and utilities for Claude Code provider inputs.\n * Uses Zod for type-safe validation following AI SDK patterns.\n */\n\n/**\n * Schema for validating Claude Code settings.\n * Ensures all settings are within acceptable ranges and formats.\n */\nexport const claudeCodeSettingsSchema = z.object({\n pathToClaudeCodeExecutable: z.string().optional(),\n customSystemPrompt: z.string().optional(),\n appendSystemPrompt: z.string().optional(),\n maxTurns: z.number().int().min(1).max(100).optional(),\n maxThinkingTokens: z.number().int().positive().max(100000).optional(),\n cwd: z.string().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 ).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 mcpServers: z.record(z.string(), 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()).optional()\n }),\n // McpSSEServerConfig\n z.object({\n type: z.literal('sse'),\n url: z.string(),\n headers: z.record(z.string()).optional()\n })\n ])).optional(),\n verbose: z.boolean().optional(),\n logger: z.union([\n z.literal(false),\n z.object({\n warn: z.function().args(z.string()).returns(z.void()),\n error: z.function().args(z.string()).returns(z.void())\n })\n ]).optional(),\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'];\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 result.error.errors.forEach(err => {\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(`High maxTurns value (${validSettings.maxTurns}) may lead to long-running conversations`);\n }\n \n // Warn about very high thinking tokens\n if (validSettings.maxThinkingTokens && validSettings.maxThinkingTokens > 50000) {\n warnings.push(`Very high maxThinkingTokens (${validSettings.maxThinkingTokens}) may increase response time`);\n }\n \n // Check if both allowedTools and disallowedTools are specified\n if (validSettings.allowedTools && validSettings.disallowedTools) {\n warnings.push('Both allowedTools and disallowedTools are specified. Only allowedTools will be used.');\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}","import type { Logger } from './types.js';\n\n/**\n * Default logger that uses console.\n */\nconst defaultLogger: Logger = {\n warn: (message: string) => console.warn(message),\n error: (message: string) => console.error(message),\n};\n\n/**\n * No-op logger that discards all messages.\n */\nconst noopLogger: Logger = {\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}"],"mappings":";AACA,SAAS,oBAAAA,yBAAwB;;;ACMjC,SAAS,wBAAuD;AAChE,S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AAEpB,QAAM,SAAS,UAAU,QAAQ,iBAAiB,MAAM;AAGxD,MAAI,QAAQ,iBAAiB;AAC3B,UAAM,aAAa,iBAAiB,QAAQ,eAAe;AAC3D,QAAI,CAAC,WAAW,OAAO;AACrB,YAAM,IAAI,MAAM,6BAA6B,WAAW,OAAO,KAAK,IAAI,CAAC,EAAE;AAAA,IAC7E;AACA,QAAI,WAAW,SAAS,SAAS,GAAG;AAClC,iBAAW,SAAS,QAAQ,aAAW,OAAO,KAAK,yBAAyB,OAAO,EAAE,CAAC;AAAA,IACxF;AAAA,EACF;AAEA,QAAM,cAAc,CAClB,SACA,WAA+B,CAAC,MACZ;AACpB,UAAM,iBAAiB;AAAA,MACrB,GAAG,QAAQ;AAAA,MACX,GAAG;AAAA,IACL;AAGA,UAAM,aAAa,iBAAiB,cAAc;AAClD,QAAI,CAAC,WAAW,OAAO;AACrB,YAAM,IAAI,MAAM,qBAAqB,WAAW,OAAO,KAAK,IAAI,CAAC,EAAE;AAAA,IACrE;AAEA,WAAO,IAAI,wBAAwB;AAAA,MACjC,IAAI;AAAA,MACJ,UAAU;AAAA,MACV,4BAA4B,WAAW;AAAA,IACzC,CAAC;AAAA,EACH;AAEA,QAAM,WAAW,SACf,SACA,UACA;AACA,QAAI,YAAY;AACd,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO,YAAY,SAAS,QAAQ;AAAA,EACtC;AAEA,WAAS,gBAAgB;AACzB,WAAS,OAAO;AAGhB,WAAS,qBAAqB,CAAC,YAAoB;AACjD,UAAM,IAAIC,kBAAiB;AAAA,MACzB;AAAA,MACA,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAiBO,IAAM,aAAa,iBAAiB;","names":["NoSuchModelError","NoSuchModelError"]}
1
+ {"version":3,"sources":["../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"],"sourcesContent":["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(\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ): 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(\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ): 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(\n options: ClaudeCodeProviderSettings = {},\n): 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 (\n modelId: ClaudeCodeModelId,\n settings?: ClaudeCodeSettings,\n ) {\n if (new.target) {\n throw new Error(\n 'The Claude Code model function cannot be called with the new keyword.',\n );\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();","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 } from './logger.js';\n\nimport { query, AbortError, type Options } from '@anthropic-ai/claude-code';\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', 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 Opus model (most capable)\n * - 'sonnet': Claude 4 Sonnet model (balanced performance)\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 customModel = claudeCode('claude-3-opus-20240229');\n * ```\n */\nexport type ClaudeCodeModelId = 'opus' | 'sonnet' | (string & {});\n\nconst modelMap: Record<string, string> = {\n 'opus': 'opus',\n 'sonnet': 'sonnet',\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 * - Does not support image inputs\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 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 this.logger = getLogger(this.settings.logger);\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 generateAllWarnings(\n options: Parameters<LanguageModelV2['doGenerate']>[0] | 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) 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 'temperature' | 'maxTokens' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | '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 createQueryOptions(abortController: AbortController): Options {\n return {\n model: this.getModel(),\n abortController,\n resume: this.settings.resume ?? this.sessionId,\n pathToClaudeCodeExecutable: this.settings.pathToClaudeCodeExecutable,\n customSystemPrompt: this.settings.customSystemPrompt,\n appendSystemPrompt: this.settings.appendSystemPrompt,\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 };\n }\n\n private handleClaudeCodeError(\n error: unknown,\n messagesPrompt: string\n ): APICallError | LoadAPIKeyError {\n // Handle AbortError from the SDK\n if (error instanceof AbortError) {\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 = (err: unknown): 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 = isErrorWithMessage(error) && error.message \n ? error.message.toLowerCase() \n : '';\n \n const exitCode = isErrorWithCode(error) && typeof error.exitCode === 'number' \n ? error.exitCode \n : undefined;\n \n const isAuthError = authErrorPatterns.some(pattern => errorMessage.includes(pattern)) ||\n exitCode === 401;\n\n if (isAuthError) {\n return createAuthenticationError({\n message: 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' \n ? error.code \n : '';\n \n if (errorCode === 'ETIMEDOUT' || errorMessage.includes('timeout')) {\n return createTimeoutError({\n message: isErrorWithMessage(error) && error.message \n ? error.message \n : '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 = errorCode === 'ENOENT' || \n errorCode === 'ECONNREFUSED' ||\n errorCode === 'ETIMEDOUT' ||\n errorCode === 'ECONNRESET';\n\n return createAPICallError({\n message: isErrorWithMessage(error) && error.message \n ? error.message \n : 'Claude Code SDK error',\n code: errorCode || undefined,\n exitCode: exitCode,\n stderr: isErrorWithCode(error) && typeof error.stderr === 'string' \n ? error.stderr \n : 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: '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 // Determine mode based on responseFormat\n const mode = options.responseFormat?.type === 'json' \n ? { type: 'object-json' as const } \n : { type: 'regular' as const };\n \n const { messagesPrompt, warnings: messageWarnings } = convertToClaudeCodeMessages(\n options.prompt, \n mode,\n options.responseFormat?.type === 'json' ? options.responseFormat.schema : undefined\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal) {\n abortListener = () => abortController.abort();\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 costUsd: number | undefined;\n let durationMs: number | undefined;\n let rawUsage: unknown | undefined;\n const warnings: LanguageModelV2CallWarning[] = this.generateAllWarnings(options, messagesPrompt);\n \n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach(warning => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n try {\n const response = query({\n prompt: messagesPrompt,\n options: queryOptions,\n });\n\n for await (const message of response) {\n if (message.type === 'assistant') {\n text += message.message.content.map((c: { type: string; text?: string }) => \n c.type === 'text' ? c.text : ''\n ).join('');\n } else if (message.type === 'result') {\n this.setSessionId(message.session_id);\n costUsd = message.total_cost_usd;\n durationMs = message.duration_ms;\n \n if ('usage' in message) {\n rawUsage = message.usage;\n usage = {\n inputTokens: (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: (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\n finishReason = mapClaudeCodeFinishReason(message.subtype);\n } else if (message.type === 'system' && message.subtype === 'init') {\n this.setSessionId(message.session_id);\n }\n }\n } catch (error: unknown) {\n // Special handling for AbortError to preserve abort signal reason\n if (error instanceof AbortError) {\n throw options.abortSignal?.aborted ? options.abortSignal.reason : error;\n }\n \n // Use unified error handler\n throw this.handleClaudeCodeError(error, messagesPrompt);\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 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 text = extracted;\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 },\n },\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV2['doStream']>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV2['doStream']>>> {\n // Determine mode based on responseFormat\n const mode = options.responseFormat?.type === 'json' \n ? { type: 'object-json' as const } \n : { type: 'regular' as const };\n \n const { messagesPrompt, warnings: messageWarnings } = convertToClaudeCodeMessages(\n options.prompt, \n mode,\n options.responseFormat?.type === 'json' ? options.responseFormat.schema : undefined\n );\n\n const abortController = new AbortController();\n let abortListener: (() => void) | undefined;\n if (options.abortSignal) {\n abortListener = () => abortController.abort();\n options.abortSignal.addEventListener('abort', abortListener, { once: true });\n }\n\n const queryOptions = this.createQueryOptions(abortController);\n\n const warnings: LanguageModelV2CallWarning[] = this.generateAllWarnings(options, messagesPrompt);\n \n // Add warnings from message conversion\n if (messageWarnings) {\n messageWarnings.forEach(warning => {\n warnings.push({\n type: 'other',\n message: warning,\n });\n });\n }\n\n const stream = new ReadableStream<LanguageModelV2StreamPart>({\n start: async (controller) => {\n try {\n // Emit stream-start with warnings\n controller.enqueue({ type: 'stream-start', warnings });\n \n const response = query({\n prompt: messagesPrompt,\n options: queryOptions,\n });\n\n let usage: LanguageModelV2Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n let accumulatedText = '';\n let textPartId: string | undefined;\n\n for await (const message of response) {\n if (message.type === 'assistant') {\n const text = message.message.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 === 'result') {\n let rawUsage: unknown | undefined;\n if ('usage' in message) {\n rawUsage = message.usage;\n usage = {\n inputTokens: (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: (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\n const finishReason: LanguageModelV2FinishReason = mapClaudeCodeFinishReason(message.subtype);\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 = extractJson(accumulatedText);\n this.validateJsonExtraction(accumulatedText, extractedJson);\n \n // If validation failed, we should add a warning but we can't modify warnings array in stream\n // So we'll just send the extracted JSON anyway\n // In the future, we could emit a warning stream part if the SDK supports it\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 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 && { costUsd: message.total_cost_usd }),\n ...(message.duration_ms !== undefined && { durationMs: message.duration_ms }),\n ...(rawUsage !== undefined && { rawUsage: rawUsage as JSONValue }),\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 // 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 controller.close();\n } catch (error: unknown) {\n let errorToEmit: unknown;\n \n // Special handling for AbortError to preserve abort signal reason\n if (error instanceof AbortError) {\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,\n request: {\n body: messagesPrompt,\n },\n };\n }\n}","import type { ModelMessage } from 'ai';\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 inputs are not supported and will be ignored with a warning\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} {\n const messages: string[] = [];\n const warnings: string[] = [];\n let systemPrompt: string | undefined;\n\n for (const message of prompt) {\n switch (message.role) {\n case 'system':\n systemPrompt = message.content;\n break;\n \n case 'user':\n if (typeof message.content === 'string') {\n messages.push(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 if (textParts) {\n messages.push(textParts);\n }\n \n // Note: Image parts are not supported by Claude Code SDK\n const imageParts = message.content.filter(part => part.type === 'image');\n if (imageParts.length > 0) {\n warnings.push('Claude Code SDK does not support image inputs. Images will be ignored.');\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 messages.push(`Assistant: ${assistantContent}`);\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 = tool.output.type === 'text' \n ? tool.output.value \n : JSON.stringify(tool.output.value);\n messages.push(`Tool Result (${tool.toolName}): ${resultText}`);\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 return { messagesPrompt: finalPrompt, systemPrompt };\n }\n \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 finalPrompt = finalPrompt + '\\n\\n' + formattedMessages.join('\\n\\n');\n } else {\n finalPrompt = formattedMessages.join('\\n\\n');\n }\n \n // For JSON mode, add explicit instruction to ensure JSON output\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 \n return {\n messagesPrompt: finalPrompt,\n systemPrompt,\n ...(warnings.length > 0 && { warnings }),\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 = 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}","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({\n message,\n}: {\n message: string;\n}): LoadAPIKeyError {\n return new LoadAPIKeyError({\n message: 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) 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') 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}","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(\n subtype?: string\n): 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}","import { z } from 'zod';\nimport { existsSync } from 'fs';\n\n/**\n * Validation schemas and utilities for Claude Code provider inputs.\n * Uses Zod for type-safe validation following AI SDK patterns.\n */\n\n/**\n * Schema for validating Claude Code settings.\n * Ensures all settings are within acceptable ranges and formats.\n */\nexport const claudeCodeSettingsSchema = z.object({\n pathToClaudeCodeExecutable: z.string().optional(),\n customSystemPrompt: z.string().optional(),\n appendSystemPrompt: z.string().optional(),\n maxTurns: z.number().int().min(1).max(100).optional(),\n maxThinkingTokens: z.number().int().positive().max(100000).optional(),\n cwd: z.string().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 ).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 mcpServers: z.record(z.string(), 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()).optional()\n }),\n // McpSSEServerConfig\n z.object({\n type: z.literal('sse'),\n url: z.string(),\n headers: z.record(z.string()).optional()\n })\n ])).optional(),\n verbose: z.boolean().optional(),\n logger: z.union([\n z.literal(false),\n z.object({\n warn: z.function().args(z.string()).returns(z.void()),\n error: z.function().args(z.string()).returns(z.void())\n })\n ]).optional(),\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'];\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 result.error.errors.forEach(err => {\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(`High maxTurns value (${validSettings.maxTurns}) may lead to long-running conversations`);\n }\n \n // Warn about very high thinking tokens\n if (validSettings.maxThinkingTokens && validSettings.maxThinkingTokens > 50000) {\n warnings.push(`Very high maxThinkingTokens (${validSettings.maxThinkingTokens}) may increase response time`);\n }\n \n // Check if both allowedTools and disallowedTools are specified\n if (validSettings.allowedTools && validSettings.disallowedTools) {\n warnings.push('Both allowedTools and disallowedTools are specified. Only allowedTools will be used.');\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}","import type { Logger } from './types.js';\n\n/**\n * Default logger that uses console.\n */\nconst defaultLogger: Logger = {\n warn: (message: string) => console.warn(message),\n error: (message: string) => console.error(message),\n};\n\n/**\n * No-op logger that discards all messages.\n */\nconst noopLogger: Logger = {\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}"],"mappings":";AACA,SAAS,oBAAAA,yBAAwB;;;ACOjC,SAAS,wBAAuD;AAChE,SAAS,kBAAkB;;;ACcpB,SAAS,4BACd,QACA,OAA4D,EAAE,MAAM,UAAU,GAC9E,YAKA;AACA,QAAM,WAAqB,CAAC;AAC5B,QAAM,WAAqB,CAAC;AAC5B,MAAI;AAEJ,aAAW,WAAW,QAAQ;AAC5B,YAAQ,QAAQ,MAAM;AAAA,MACpB,KAAK;AACH,uBAAe,QAAQ;AACvB;AAAA,MAEF,KAAK;AACH,YAAI,OAAO,QAAQ,YAAY,UAAU;AACvC,mBAAS,KAAK,QAAQ,OAAO;AAAA,QAC/B,OAAO;AAEL,gBAAM,YAAY,QAAQ,QACvB,OAAO,UAAQ,KAAK,SAAS,MAAM,EACnC,IAAI,UAAQ,KAAK,IAAI,EACrB,KAAK,IAAI;AAEZ,cAAI,WAAW;AACb,qBAAS,KAAK,SAAS;AAAA,UACzB;AAGA,gBAAM,aAAa,QAAQ,QAAQ,OAAO,UA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AAU;AAAA,MACV,4BAA4B,WAAW;AAAA,IACzC,CAAC;AAAA,EACH;AAEA,QAAM,WAAW,SACf,SACA,UACA;AACA,QAAI,YAAY;AACd,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO,YAAY,SAAS,QAAQ;AAAA,EACtC;AAEA,WAAS,gBAAgB;AACzB,WAAS,OAAO;AAGhB,WAAS,qBAAqB,CAAC,YAAoB;AACjD,UAAM,IAAIC,kBAAiB;AAAA,MACzB;AAAA,MACA,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,WAAS,aAAa,CAAC,YAAoB;AACzC,UAAM,IAAIA,kBAAiB;AAAA,MACzB;AAAA,MACA,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAiBO,IAAM,aAAa,iBAAiB;","names":["NoSuchModelError","NoSuchModelError"]}
@@ -174,7 +174,7 @@ The Claude Code provider is available in the `ai-sdk-provider-claude-code` modul
174
174
 
175
175
  ### Prerequisites
176
176
 
177
- Install and authenticate the Claude Code CLI:
177
+ Install and authenticate the Claude Code SDK:
178
178
 
179
179
  ```bash
180
180
  npm install -g @anthropic-ai/claude-code
@@ -217,5 +217,5 @@ const { text } = await generateText({
217
217
  The provider uses the official Claude Code SDK. While the models support tool use, this provider
218
218
  doesn't implement the AI SDK's tool calling interface. However, you can configure MCP servers
219
219
  for tool functionality, and Claude can use built-in tools (Bash, Read, Write, etc.) through
220
- the Claude Code CLI.
220
+ the Claude Code SDK.
221
221
  </Note>
@@ -708,13 +708,13 @@ Review our examples for implementation patterns
708
708
 
709
709
  ## Limitations
710
710
 
711
- - **No image support**: The Claude Code CLI doesn't support image inputs (provider sets `supportsImageUrls = false`)
711
+ - **No image support**: The Claude Code SDK doesn't support image inputs (provider sets `supportsImageUrls = false`)
712
712
  - **No embedding support**: Text embeddings are not available through this provider
713
713
  - **Object-tool mode not supported**: Only `object-json` mode works via `generateObject`/`streamObject`. The AI SDK's tool calling interface is not implemented
714
714
  - **Text-only responses**: No support for file generation or other modalities
715
715
  - **Session management**: While sessions are supported, message history is the recommended approach
716
716
  - **Unsupported generation settings**: The following AI SDK settings are ignored and will generate warnings:
717
- - `temperature` - Claude Code CLI doesn't expose temperature control
717
+ - `temperature` - Claude Code SDK doesn't expose temperature control
718
718
  - `maxTokens` - Token limits aren't configurable via CLI
719
719
  - `topP`, `topK` - Sampling parameters aren't available
720
720
  - `presencePenalty`, `frequencyPenalty` - Penalty parameters aren't supported
@@ -831,7 +831,7 @@ ai-sdk-provider-claude-code/
831
831
  ## Known Limitations
832
832
 
833
833
  1. **No image support**: The CLI doesn't accept image inputs
834
- 2. **Authentication required**: Requires separate Claude Code CLI authentication (`claude login`)
834
+ 2. **Authentication required**: Requires separate Claude Code SDK authentication (`claude login`)
835
835
  3. **Session IDs change**: Each request gets a new session ID, even when using `--resume`
836
836
  4. **No AI SDK tool calling interface**: The AI SDK's function/tool calling interface is not implemented, but Claude can use tools via MCP servers and built-in CLI tools
837
837
 
@@ -862,4 +862,4 @@ MIT - see [LICENSE](../LICENSE) for details.
862
862
 
863
863
  ## Acknowledgments
864
864
 
865
- This provider is built for the [Vercel AI SDK](https://sdk.vercel.ai/) and uses the [Claude Code CLI](https://docs.anthropic.com/claude-code/cli) by Anthropic.
865
+ This provider is built for the [Vercel AI SDK](https://sdk.vercel.ai/) and uses the [Claude Code SDK](https://docs.anthropic.com/claude-code/cli) by Anthropic.
@@ -10,7 +10,7 @@ This guide documents common issues and solutions for the Claude Code AI SDK Prov
10
10
 
11
11
  **Solution**:
12
12
  ```bash
13
- # Install Claude Code CLI globally
13
+ # Install Claude Code SDK globally
14
14
  npm install -g @anthropic-ai/claude-code
15
15
 
16
16
  # Authenticate with your Claude account