ai-sdk-provider-claude-code 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/claude-code-provider.ts","../src/claude-code-language-model.ts","../src/convert-to-claude-code-messages.ts","../src/extract-json.ts","../src/errors.ts","../src/map-claude-code-finish-reason.ts","../src/validation.ts","../src/logger.ts"],"sourcesContent":["/**\n * Provider exports for creating and configuring Claude Code instances.\n * @module claude-code\n */\n\n/**\n * Creates a new Claude Code provider instance and the default provider instance.\n * @see {@link createClaudeCode} for creating custom provider instances\n * @see {@link claudeCode} for the default provider instance\n */\nexport { createClaudeCode, claudeCode } from './claude-code-provider.js';\n\n/**\n * Type definitions for the Claude Code provider.\n * @see {@link ClaudeCodeProvider} for the provider interface\n * @see {@link ClaudeCodeProviderSettings} for provider configuration options\n */\nexport type { ClaudeCodeProvider, ClaudeCodeProviderSettings } from './claude-code-provider.js';\n\n/**\n * Language model implementation for Claude Code.\n * This class implements the AI SDK's LanguageModelV1 interface.\n */\nexport { ClaudeCodeLanguageModel } from './claude-code-language-model.js';\n\n/**\n * Type definitions for Claude Code language models.\n * @see {@link ClaudeCodeModelId} for supported model identifiers\n * @see {@link ClaudeCodeLanguageModelOptions} for model configuration options\n */\nexport type { ClaudeCodeModelId, ClaudeCodeLanguageModelOptions } from './claude-code-language-model.js';\n\n/**\n * Settings for configuring Claude Code behavior.\n * Includes options for customizing the CLI execution, permissions, and tool usage.\n */\nexport type { ClaudeCodeSettings, Logger } from './types.js';\n\n/**\n * Error handling utilities for Claude Code.\n * These functions help create and identify specific error types.\n * \n * @see {@link isAuthenticationError} to check for authentication failures\n * @see {@link isTimeoutError} to check for timeout errors\n * @see {@link getErrorMetadata} to extract error metadata\n * @see {@link createAPICallError} to create general API errors\n * @see {@link createAuthenticationError} to create authentication errors\n * @see {@link createTimeoutError} to create timeout errors\n */\nexport { \n isAuthenticationError, \n isTimeoutError, \n getErrorMetadata,\n createAPICallError,\n createAuthenticationError,\n createTimeoutError\n} from './errors.js';\n\n/**\n * Metadata associated with Claude Code errors.\n * Contains additional context about CLI execution failures.\n */\nexport type { ClaudeCodeErrorMetadata } from './errors.js';","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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,mBAAiC;;;ACMjC,IAAAC,mBAAgE;AAChE,4BAA2B;;;ACepB,SAAS,4BACd,QACA,MAKA;AACA,QAAM,WAA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AM,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,IAAI,kCAAiB;AAAA,MACzB;AAAA,MACA,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAiBO,IAAM,aAAa,iBAAiB;","names":["import_provider","import_provider"]}
@@ -0,0 +1,483 @@
1
+ import { LanguageModelV1, ProviderV1, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';
2
+ import { PermissionMode, McpServerConfig } from '@anthropic-ai/claude-code';
3
+
4
+ /**
5
+ * Logger interface for custom logging.
6
+ * Allows consumers to provide their own logging implementation
7
+ * or disable logging entirely.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const customLogger: Logger = {
12
+ * warn: (message) => myLoggingService.warn(message),
13
+ * error: (message) => myLoggingService.error(message),
14
+ * };
15
+ * ```
16
+ */
17
+ interface Logger {
18
+ /**
19
+ * Log a warning message.
20
+ */
21
+ warn: (message: string) => void;
22
+ /**
23
+ * Log an error message.
24
+ */
25
+ error: (message: string) => void;
26
+ }
27
+ /**
28
+ * Configuration settings for Claude Code CLI behavior.
29
+ * These settings control how the CLI executes, what permissions it has,
30
+ * and which tools are available during conversations.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const settings: ClaudeCodeSettings = {
35
+ * maxTurns: 10,
36
+ * permissionMode: 'auto',
37
+ * cwd: '/path/to/project',
38
+ * allowedTools: ['Read', 'LS'],
39
+ * disallowedTools: ['Bash(rm:*)']
40
+ * };
41
+ * ```
42
+ */
43
+ interface ClaudeCodeSettings {
44
+ /**
45
+ * Custom path to Claude Code CLI executable
46
+ * @default 'claude' (uses system PATH)
47
+ */
48
+ pathToClaudeCodeExecutable?: string;
49
+ /**
50
+ * Custom system prompt to use
51
+ */
52
+ customSystemPrompt?: string;
53
+ /**
54
+ * Append additional content to the system prompt
55
+ */
56
+ appendSystemPrompt?: string;
57
+ /**
58
+ * Maximum number of turns for the conversation
59
+ */
60
+ maxTurns?: number;
61
+ /**
62
+ * Maximum thinking tokens for the model
63
+ */
64
+ maxThinkingTokens?: number;
65
+ /**
66
+ * Working directory for CLI operations
67
+ */
68
+ cwd?: string;
69
+ /**
70
+ * JavaScript runtime to use
71
+ * @default 'node' (or 'bun' if Bun is detected)
72
+ */
73
+ executable?: 'bun' | 'deno' | 'node';
74
+ /**
75
+ * Additional arguments for the JavaScript runtime
76
+ */
77
+ executableArgs?: string[];
78
+ /**
79
+ * Permission mode for tool usage
80
+ * @default 'default'
81
+ */
82
+ permissionMode?: PermissionMode;
83
+ /**
84
+ * Custom tool name for permission prompts
85
+ */
86
+ permissionPromptToolName?: string;
87
+ /**
88
+ * Continue the most recent conversation
89
+ */
90
+ continue?: boolean;
91
+ /**
92
+ * Resume a specific session by ID
93
+ */
94
+ resume?: string;
95
+ /**
96
+ * Tools to explicitly allow during execution
97
+ * Examples: ['Read', 'LS', 'Bash(git log:*)']
98
+ */
99
+ allowedTools?: string[];
100
+ /**
101
+ * Tools to disallow during execution
102
+ * Examples: ['Write', 'Edit', 'Bash(rm:*)']
103
+ */
104
+ disallowedTools?: string[];
105
+ /**
106
+ * MCP server configuration
107
+ */
108
+ mcpServers?: Record<string, McpServerConfig>;
109
+ /**
110
+ * Enable verbose logging for debugging
111
+ */
112
+ verbose?: boolean;
113
+ /**
114
+ * Custom logger for handling warnings and errors.
115
+ * - Set to `false` to disable all logging
116
+ * - Provide a Logger object to use custom logging
117
+ * - Leave undefined to use console (default)
118
+ *
119
+ * @default console
120
+ * @example
121
+ * ```typescript
122
+ * // Disable logging
123
+ * const settings = { logger: false };
124
+ *
125
+ * // Custom logger
126
+ * const settings = {
127
+ * logger: {
128
+ * warn: (msg) => myLogger.warn(msg),
129
+ * error: (msg) => myLogger.error(msg),
130
+ * }
131
+ * };
132
+ * ```
133
+ */
134
+ logger?: Logger | false;
135
+ }
136
+
137
+ /**
138
+ * Options for creating a Claude Code language model instance.
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * const model = new ClaudeCodeLanguageModel({
143
+ * id: 'opus',
144
+ * settings: {
145
+ * maxTurns: 10,
146
+ * permissionMode: 'auto'
147
+ * }
148
+ * });
149
+ * ```
150
+ */
151
+ interface ClaudeCodeLanguageModelOptions {
152
+ /**
153
+ * The model identifier to use.
154
+ * Can be 'opus', 'sonnet', or a custom model string.
155
+ */
156
+ id: ClaudeCodeModelId;
157
+ /**
158
+ * Optional settings to configure the model behavior.
159
+ */
160
+ settings?: ClaudeCodeSettings;
161
+ /**
162
+ * Validation warnings from settings validation.
163
+ * Used internally to pass warnings from provider.
164
+ */
165
+ settingsValidationWarnings?: string[];
166
+ }
167
+ /**
168
+ * Supported Claude model identifiers.
169
+ * - 'opus': Claude 4 Opus model (most capable)
170
+ * - 'sonnet': Claude 4 Sonnet model (balanced performance)
171
+ * - Custom string: Any other model identifier supported by the CLI
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const opusModel = claudeCode('opus');
176
+ * const sonnetModel = claudeCode('sonnet');
177
+ * const customModel = claudeCode('claude-3-opus-20240229');
178
+ * ```
179
+ */
180
+ type ClaudeCodeModelId = 'opus' | 'sonnet' | (string & {});
181
+ /**
182
+ * Language model implementation for Claude Code CLI.
183
+ * This class implements the AI SDK's LanguageModelV1 interface to provide
184
+ * integration with Claude models through the Claude Code CLI.
185
+ *
186
+ * Features:
187
+ * - Supports streaming and non-streaming generation
188
+ * - Handles JSON object generation mode
189
+ * - Manages CLI sessions for conversation continuity
190
+ * - Provides detailed error handling and retry logic
191
+ *
192
+ * Limitations:
193
+ * - Does not support image inputs
194
+ * - Does not support structured outputs (tool mode)
195
+ * - Some parameters like temperature and max tokens are not supported by the CLI
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const model = new ClaudeCodeLanguageModel({
200
+ * id: 'opus',
201
+ * settings: { maxTurns: 5 }
202
+ * });
203
+ *
204
+ * const result = await model.doGenerate({
205
+ * prompt: [{ role: 'user', content: 'Hello!' }],
206
+ * mode: { type: 'regular' }
207
+ * });
208
+ * ```
209
+ */
210
+ declare class ClaudeCodeLanguageModel implements LanguageModelV1 {
211
+ readonly specificationVersion: "v1";
212
+ readonly defaultObjectGenerationMode: "json";
213
+ readonly supportsImageUrls = false;
214
+ readonly supportsStructuredOutputs = false;
215
+ readonly modelId: ClaudeCodeModelId;
216
+ readonly settings: ClaudeCodeSettings;
217
+ private sessionId?;
218
+ private modelValidationWarning?;
219
+ private settingsValidationWarnings;
220
+ private logger;
221
+ constructor(options: ClaudeCodeLanguageModelOptions);
222
+ get provider(): string;
223
+ private getModel;
224
+ private generateAllWarnings;
225
+ private createQueryOptions;
226
+ private handleClaudeCodeError;
227
+ private setSessionId;
228
+ private validateJsonExtraction;
229
+ doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
230
+ doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
231
+ }
232
+
233
+ /**
234
+ * Claude Code provider interface that extends the AI SDK's ProviderV1.
235
+ * Provides methods to create language models for interacting with Claude via the CLI.
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * import { claudeCode } from 'ai-sdk-provider-claude-code';
240
+ *
241
+ * // Create a model instance
242
+ * const model = claudeCode('opus');
243
+ *
244
+ * // Or use the explicit methods
245
+ * const chatModel = claudeCode.chat('sonnet');
246
+ * const languageModel = claudeCode.languageModel('opus', { maxTurns: 10 });
247
+ * ```
248
+ */
249
+ interface ClaudeCodeProvider extends ProviderV1 {
250
+ /**
251
+ * Creates a language model instance for the specified model ID.
252
+ * This is a shorthand for calling `languageModel()`.
253
+ *
254
+ * @param modelId - The Claude model to use ('opus' or 'sonnet')
255
+ * @param settings - Optional settings to configure the model
256
+ * @returns A language model instance
257
+ */
258
+ (modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV1;
259
+ /**
260
+ * Creates a language model instance for text generation.
261
+ *
262
+ * @param modelId - The Claude model to use ('opus' or 'sonnet')
263
+ * @param settings - Optional settings to configure the model
264
+ * @returns A language model instance
265
+ */
266
+ languageModel(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV1;
267
+ /**
268
+ * Alias for `languageModel()` to maintain compatibility with AI SDK patterns.
269
+ *
270
+ * @param modelId - The Claude model to use ('opus' or 'sonnet')
271
+ * @param settings - Optional settings to configure the model
272
+ * @returns A language model instance
273
+ */
274
+ chat(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV1;
275
+ }
276
+ /**
277
+ * Configuration options for creating a Claude Code provider instance.
278
+ * These settings will be applied as defaults to all models created by the provider.
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * const provider = createClaudeCode({
283
+ * defaultSettings: {
284
+ * maxTurns: 5,
285
+ * cwd: '/path/to/project'
286
+ * }
287
+ * });
288
+ * ```
289
+ */
290
+ interface ClaudeCodeProviderSettings {
291
+ /**
292
+ * Default settings to use for all models created by this provider.
293
+ * Individual model settings will override these defaults.
294
+ */
295
+ defaultSettings?: ClaudeCodeSettings;
296
+ }
297
+ /**
298
+ * Creates a Claude Code provider instance with the specified configuration.
299
+ * The provider can be used to create language models for interacting with Claude 4 models.
300
+ *
301
+ * @param options - Provider configuration options
302
+ * @returns Claude Code provider instance
303
+ *
304
+ * @example
305
+ * ```typescript
306
+ * const provider = createClaudeCode({
307
+ * defaultSettings: {
308
+ * permissionMode: 'bypassPermissions',
309
+ * maxTurns: 10
310
+ * }
311
+ * });
312
+ *
313
+ * const model = provider('opus');
314
+ * ```
315
+ */
316
+ declare function createClaudeCode(options?: ClaudeCodeProviderSettings): ClaudeCodeProvider;
317
+ /**
318
+ * Default Claude Code provider instance.
319
+ * Pre-configured provider for quick usage without custom settings.
320
+ *
321
+ * @example
322
+ * ```typescript
323
+ * import { claudeCode } from 'ai-sdk-provider-claude-code';
324
+ * import { generateText } from 'ai';
325
+ *
326
+ * const { text } = await generateText({
327
+ * model: claudeCode('sonnet'),
328
+ * prompt: 'Hello, Claude!'
329
+ * });
330
+ * ```
331
+ */
332
+ declare const claudeCode: ClaudeCodeProvider;
333
+
334
+ /**
335
+ * Metadata associated with Claude Code CLI errors.
336
+ * Provides additional context about command execution failures.
337
+ */
338
+ interface ClaudeCodeErrorMetadata {
339
+ /**
340
+ * Error code from the CLI process (e.g., 'ENOENT', 'ETIMEDOUT').
341
+ */
342
+ code?: string;
343
+ /**
344
+ * Exit code from the Claude Code CLI process.
345
+ * Common codes:
346
+ * - 401: Authentication error
347
+ * - 1: General error
348
+ */
349
+ exitCode?: number;
350
+ /**
351
+ * Standard error output from the CLI process.
352
+ */
353
+ stderr?: string;
354
+ /**
355
+ * Excerpt from the prompt that caused the error.
356
+ * Limited to first 200 characters for debugging.
357
+ */
358
+ promptExcerpt?: string;
359
+ }
360
+ /**
361
+ * Creates an APICallError with Claude Code specific metadata.
362
+ * Used for general CLI execution errors.
363
+ *
364
+ * @param options - Error details and metadata
365
+ * @param options.message - Human-readable error message
366
+ * @param options.code - Error code from the CLI process
367
+ * @param options.exitCode - Exit code from the CLI
368
+ * @param options.stderr - Standard error output
369
+ * @param options.promptExcerpt - Excerpt of the prompt that caused the error
370
+ * @param options.isRetryable - Whether the error is potentially retryable
371
+ * @returns An APICallError instance with Claude Code metadata
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * throw createAPICallError({
376
+ * message: 'Claude Code CLI failed',
377
+ * code: 'ENOENT',
378
+ * isRetryable: true
379
+ * });
380
+ * ```
381
+ */
382
+ declare function createAPICallError({ message, code, exitCode, stderr, promptExcerpt, isRetryable, }: ClaudeCodeErrorMetadata & {
383
+ message: string;
384
+ isRetryable?: boolean;
385
+ }): APICallError;
386
+ /**
387
+ * Creates an authentication error for Claude Code CLI login failures.
388
+ *
389
+ * @param options - Error configuration
390
+ * @param options.message - Error message describing the authentication failure
391
+ * @returns A LoadAPIKeyError instance
392
+ *
393
+ * @example
394
+ * ```typescript
395
+ * throw createAuthenticationError({
396
+ * message: 'Please run "claude login" to authenticate'
397
+ * });
398
+ * ```
399
+ */
400
+ declare function createAuthenticationError({ message, }: {
401
+ message: string;
402
+ }): LoadAPIKeyError;
403
+ /**
404
+ * Creates a timeout error for Claude Code CLI operations.
405
+ *
406
+ * @param options - Timeout error details
407
+ * @param options.message - Error message describing the timeout
408
+ * @param options.promptExcerpt - Excerpt of the prompt that timed out
409
+ * @param options.timeoutMs - Timeout duration in milliseconds
410
+ * @returns An APICallError instance configured as a timeout error
411
+ *
412
+ * @example
413
+ * ```typescript
414
+ * throw createTimeoutError({
415
+ * message: 'Request timed out after 2 minutes',
416
+ * timeoutMs: 120000
417
+ * });
418
+ * ```
419
+ */
420
+ declare function createTimeoutError({ message, promptExcerpt, timeoutMs, }: {
421
+ message: string;
422
+ promptExcerpt?: string;
423
+ timeoutMs?: number;
424
+ }): APICallError;
425
+ /**
426
+ * Checks if an error is an authentication error.
427
+ * Returns true for LoadAPIKeyError instances or APICallError with exit code 401.
428
+ *
429
+ * @param error - The error to check
430
+ * @returns True if the error is an authentication error
431
+ *
432
+ * @example
433
+ * ```typescript
434
+ * try {
435
+ * await model.generate(...);
436
+ * } catch (error) {
437
+ * if (isAuthenticationError(error)) {
438
+ * console.log('Please authenticate with Claude Code CLI');
439
+ * }
440
+ * }
441
+ * ```
442
+ */
443
+ declare function isAuthenticationError(error: unknown): boolean;
444
+ /**
445
+ * Checks if an error is a timeout error.
446
+ * Returns true for APICallError instances with code 'TIMEOUT'.
447
+ *
448
+ * @param error - The error to check
449
+ * @returns True if the error is a timeout error
450
+ *
451
+ * @example
452
+ * ```typescript
453
+ * try {
454
+ * await model.generate(...);
455
+ * } catch (error) {
456
+ * if (isTimeoutError(error)) {
457
+ * console.log('Request timed out, consider retrying');
458
+ * }
459
+ * }
460
+ * ```
461
+ */
462
+ declare function isTimeoutError(error: unknown): boolean;
463
+ /**
464
+ * Extracts Claude Code error metadata from an error object.
465
+ *
466
+ * @param error - The error to extract metadata from
467
+ * @returns The error metadata if available, undefined otherwise
468
+ *
469
+ * @example
470
+ * ```typescript
471
+ * try {
472
+ * await model.generate(...);
473
+ * } catch (error) {
474
+ * const metadata = getErrorMetadata(error);
475
+ * if (metadata?.exitCode === 401) {
476
+ * console.log('Authentication required');
477
+ * }
478
+ * }
479
+ * ```
480
+ */
481
+ declare function getErrorMetadata(error: unknown): ClaudeCodeErrorMetadata | undefined;
482
+
483
+ export { type ClaudeCodeErrorMetadata, ClaudeCodeLanguageModel, type ClaudeCodeLanguageModelOptions, type ClaudeCodeModelId, type ClaudeCodeProvider, type ClaudeCodeProviderSettings, type ClaudeCodeSettings, type Logger, claudeCode, createAPICallError, createAuthenticationError, createClaudeCode, createTimeoutError, getErrorMetadata, isAuthenticationError, isTimeoutError };