ai-sdk-provider-claude-code 3.5.3 → 4.0.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/README.md +228 -124
- package/dist/index.d.ts +236 -51
- package/dist/index.js +951 -223
- package/dist/index.js.map +1 -1
- package/docs/sessions.md +4 -4
- package/package.json +12 -14
- package/dist/index.cjs +0 -4085
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -1331
package/dist/index.d.cts
DELETED
|
@@ -1,1331 +0,0 @@
|
|
|
1
|
-
import { LanguageModelV3, ProviderV3, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';
|
|
2
|
-
import { Options, ThinkingConfig, EffortLevel, PermissionMode, SdkBeta, SdkPluginConfig, SandboxSettings, Settings, ToolConfig, McpServerConfig, CanUseTool, OnUserDialog, AgentDefinition, SessionStore, SessionStoreFlush, SpawnOptions, SpawnedProcess, Query, SdkMcpToolDefinition, McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk';
|
|
3
|
-
export { AbortError, AccountInfo, AgentDefinition, AgentInfo, AgentMcpServerSpec, AsyncHookJSONOutput, CanUseTool, ConfigChangeHookInput, CwdChangedHookInput, CwdChangedHookSpecificOutput, EffortLevel, ElicitationHookInput, ElicitationHookSpecificOutput, ElicitationResultHookInput, ElicitationResultHookSpecificOutput, FileChangedHookInput, FileChangedHookSpecificOutput, ForkSessionOptions, ForkSessionResult, GetSessionInfoOptions, GetSessionMessagesOptions, GetSubagentMessagesOptions, HOOK_EVENTS, HookCallback, HookCallbackMatcher, HookEvent, HookInput, HookJSONOutput, HookPermissionDecision, ImportSessionToStoreOptions, InMemorySessionStore, InstructionsLoadedHookInput, ListSessionsOptions, ListSubagentsOptions, McpHttpServerConfig, McpSSEServerConfig, McpSdkServerConfig, McpSdkServerConfigWithInstance, McpServerConfig, McpServerConfigForProcessTransport, McpServerStatus, McpSetServersResult, McpStdioServerConfig, MessageDisplayHookInput, MessageDisplayHookSpecificOutput, ModelInfo, NotificationHookInput, NotificationHookSpecificOutput, OnUserDialog, Options, OutputFormat, PermissionBehavior, PermissionDecisionClassification, PermissionDeniedHookInput, PermissionDeniedHookSpecificOutput, PermissionMode, PermissionRequestHookInput, PermissionRequestHookSpecificOutput, PermissionResult, PermissionRuleValue, PermissionUpdate, PermissionUpdateDestination, PostCompactHookInput, PostToolBatchHookInput, PostToolBatchHookSpecificOutput, PostToolUseFailureHookInput, PostToolUseFailureHookSpecificOutput, PostToolUseHookInput, PostToolUseHookSpecificOutput, PreCompactHookInput, PreToolUseHookInput, PreToolUseHookSpecificOutput, Query, RewindFilesResult, SDKMessage, SDKMessageOrigin, SDKSessionInfo, SDKUserMessage, SYSTEM_PROMPT_DYNAMIC_BOUNDARY, SandboxFilesystemConfig, SandboxIgnoreViolations, SandboxNetworkConfig, SandboxSettings, SdkBeta, SdkPluginConfig, SessionCronSummary, SessionEndHookInput, SessionKey, SessionMessage, SessionMutationOptions, SessionStartHookInput, SessionStartHookSpecificOutput, SessionStore, SessionStoreEntry, SessionStoreFlush, SessionSummaryEntry, Settings, SetupHookInput, SetupHookSpecificOutput, SlashCommand, SpawnOptions, SpawnedProcess, StopFailureHookInput, StopHookInput, StopHookSpecificOutput, SubagentStartHookInput, SubagentStartHookSpecificOutput, SubagentStopHookInput, SubagentStopHookSpecificOutput, SyncHookJSONOutput, TaskCompletedHookInput, TaskCreatedHookInput, TeammateIdleHookInput, TerminalReason, ThinkingAdaptive, ThinkingConfig, ThinkingDisabled, ThinkingEnabled, ToolConfig, UserDialogRequest, UserDialogResult, UserPromptExpansionHookInput, UserPromptExpansionHookSpecificOutput, UserPromptSubmitHookInput, UserPromptSubmitHookSpecificOutput, WarmQuery, WorktreeCreateHookInput, WorktreeCreateHookSpecificOutput, WorktreeRemoveHookInput, createSdkMcpServer, deleteSession, foldSessionSummary, forkSession, getSessionInfo, getSessionMessages, getSubagentMessages, importSessionToStore, listSessions, listSubagents, renameSession, startup, tagSession, tool } from '@anthropic-ai/claude-agent-sdk';
|
|
4
|
-
import { ZodObject, ZodRawShape } from 'zod';
|
|
5
|
-
|
|
6
|
-
type StreamingInputMode = 'auto' | 'always' | 'off';
|
|
7
|
-
/**
|
|
8
|
-
* Logger interface for custom logging.
|
|
9
|
-
* Allows consumers to provide their own logging implementation
|
|
10
|
-
* or disable logging entirely.
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```typescript
|
|
14
|
-
* const customLogger: Logger = {
|
|
15
|
-
* debug: (message) => myLoggingService.debug(message),
|
|
16
|
-
* info: (message) => myLoggingService.info(message),
|
|
17
|
-
* warn: (message) => myLoggingService.warn(message),
|
|
18
|
-
* error: (message) => myLoggingService.error(message),
|
|
19
|
-
* };
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
interface Logger {
|
|
23
|
-
/**
|
|
24
|
-
* Log a debug message. Only logged when verbose mode is enabled.
|
|
25
|
-
* Used for detailed execution tracing and troubleshooting.
|
|
26
|
-
*/
|
|
27
|
-
debug: (message: string) => void;
|
|
28
|
-
/**
|
|
29
|
-
* Log an informational message. Only logged when verbose mode is enabled.
|
|
30
|
-
* Used for general execution flow information.
|
|
31
|
-
*/
|
|
32
|
-
info: (message: string) => void;
|
|
33
|
-
/**
|
|
34
|
-
* Log a warning message.
|
|
35
|
-
*/
|
|
36
|
-
warn: (message: string) => void;
|
|
37
|
-
/**
|
|
38
|
-
* Log an error message.
|
|
39
|
-
*/
|
|
40
|
-
error: (message: string) => void;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Configuration settings for Claude Code SDK behavior.
|
|
44
|
-
* These settings control how the CLI executes, what permissions it has,
|
|
45
|
-
* and which tools are available during conversations.
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```typescript
|
|
49
|
-
* const settings: ClaudeCodeSettings = {
|
|
50
|
-
* maxTurns: 10,
|
|
51
|
-
* permissionMode: 'auto',
|
|
52
|
-
* cwd: '/path/to/project',
|
|
53
|
-
* allowedTools: ['Read', 'LS'],
|
|
54
|
-
* disallowedTools: ['Bash(rm:*)']
|
|
55
|
-
* };
|
|
56
|
-
* ```
|
|
57
|
-
*/
|
|
58
|
-
interface ClaudeCodeSettings {
|
|
59
|
-
/**
|
|
60
|
-
* Custom path to Claude Code SDK executable
|
|
61
|
-
* @default 'claude' (uses system PATH)
|
|
62
|
-
*/
|
|
63
|
-
pathToClaudeCodeExecutable?: string;
|
|
64
|
-
/**
|
|
65
|
-
* Custom system prompt to use
|
|
66
|
-
*/
|
|
67
|
-
customSystemPrompt?: string;
|
|
68
|
-
/**
|
|
69
|
-
* Append additional content to the system prompt
|
|
70
|
-
*/
|
|
71
|
-
appendSystemPrompt?: string;
|
|
72
|
-
/**
|
|
73
|
-
* Agent SDK system prompt configuration. Preferred over legacy fields.
|
|
74
|
-
* - string: custom system prompt
|
|
75
|
-
* - string[]: custom system prompt blocks; include the
|
|
76
|
-
* `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` marker (re-exported by this package)
|
|
77
|
-
* as a standalone element to split the static (cross-session cacheable)
|
|
78
|
-
* prefix from the dynamic (session-specific) suffix
|
|
79
|
-
* - preset object: Claude Code preset, with optional `append` and
|
|
80
|
-
* `excludeDynamicSections` (strips per-user dynamic sections such as
|
|
81
|
-
* working directory and git status so the prompt caches across users)
|
|
82
|
-
*/
|
|
83
|
-
systemPrompt?: Options['systemPrompt'];
|
|
84
|
-
/**
|
|
85
|
-
* Maximum number of turns for the conversation
|
|
86
|
-
*/
|
|
87
|
-
maxTurns?: number;
|
|
88
|
-
/**
|
|
89
|
-
* Maximum thinking tokens for the model
|
|
90
|
-
*
|
|
91
|
-
* @deprecated Use `thinking` instead.
|
|
92
|
-
*/
|
|
93
|
-
maxThinkingTokens?: number;
|
|
94
|
-
/**
|
|
95
|
-
* Controls Claude's thinking/reasoning behavior.
|
|
96
|
-
* Takes precedence over the deprecated `maxThinkingTokens`.
|
|
97
|
-
*
|
|
98
|
-
* - `{ type: 'adaptive' }` — Claude decides when and how much to think (Opus 4.6+, default)
|
|
99
|
-
* - `{ type: 'enabled', budgetTokens?: number }` — Fixed thinking token budget
|
|
100
|
-
* - `{ type: 'disabled' }` — No extended thinking
|
|
101
|
-
*
|
|
102
|
-
* @see https://docs.anthropic.com/en/docs/build-with-claude/adaptive-thinking
|
|
103
|
-
*/
|
|
104
|
-
thinking?: ThinkingConfig;
|
|
105
|
-
/**
|
|
106
|
-
* Controls how much effort Claude puts into its response.
|
|
107
|
-
*
|
|
108
|
-
* - `'low'` — Minimal thinking, fastest responses
|
|
109
|
-
* - `'medium'` — Moderate thinking
|
|
110
|
-
* - `'high'` — Deep reasoning (default)
|
|
111
|
-
* - `'xhigh'` — Extra-high effort
|
|
112
|
-
* - `'max'` — Maximum effort (Opus 4.6 only)
|
|
113
|
-
*
|
|
114
|
-
* @see https://docs.anthropic.com/en/docs/build-with-claude/effort
|
|
115
|
-
*/
|
|
116
|
-
effort?: EffortLevel;
|
|
117
|
-
/**
|
|
118
|
-
* Enable prompt suggestions. When true, the agent emits a predicted
|
|
119
|
-
* next user prompt after each turn (arrives after the result message).
|
|
120
|
-
*/
|
|
121
|
-
promptSuggestions?: boolean;
|
|
122
|
-
/**
|
|
123
|
-
* Working directory for CLI operations
|
|
124
|
-
*/
|
|
125
|
-
cwd?: string;
|
|
126
|
-
/**
|
|
127
|
-
* JavaScript runtime to use
|
|
128
|
-
* @default 'node' (or 'bun' if Bun is detected)
|
|
129
|
-
*/
|
|
130
|
-
executable?: 'bun' | 'deno' | 'node';
|
|
131
|
-
/**
|
|
132
|
-
* Additional arguments for the JavaScript runtime
|
|
133
|
-
*/
|
|
134
|
-
executableArgs?: string[];
|
|
135
|
-
/**
|
|
136
|
-
* Permission mode for tool usage.
|
|
137
|
-
*
|
|
138
|
-
* Note: `'delegate'` was removed in Agent SDK 0.3.x — the CLI rejects
|
|
139
|
-
* `--permission-mode delegate` at argv parsing — so it is no longer
|
|
140
|
-
* accepted here either.
|
|
141
|
-
* @default 'default'
|
|
142
|
-
*/
|
|
143
|
-
permissionMode?: PermissionMode;
|
|
144
|
-
/**
|
|
145
|
-
* Custom tool name for permission prompts
|
|
146
|
-
*/
|
|
147
|
-
permissionPromptToolName?: string;
|
|
148
|
-
/**
|
|
149
|
-
* Continue the most recent conversation
|
|
150
|
-
*/
|
|
151
|
-
continue?: boolean;
|
|
152
|
-
/**
|
|
153
|
-
* Resume a specific session by ID
|
|
154
|
-
*/
|
|
155
|
-
resume?: string;
|
|
156
|
-
/**
|
|
157
|
-
* Use a specific session ID for this query.
|
|
158
|
-
* Allows deterministic session identifiers for tracking and correlation.
|
|
159
|
-
*
|
|
160
|
-
* Must be a valid UUID (the CLI rejects other formats). Cannot be combined
|
|
161
|
-
* with `continue` or `resume` unless `forkSession` is also set (it then
|
|
162
|
-
* names the forked session's ID); the provider rejects those combinations
|
|
163
|
-
* at validation time. On multi-turn conversations the provider forwards
|
|
164
|
-
* `sessionId` only on the first turn — subsequent turns resume the captured
|
|
165
|
-
* session (which already carries the custom ID).
|
|
166
|
-
*/
|
|
167
|
-
sessionId?: string;
|
|
168
|
-
/**
|
|
169
|
-
* Tools to explicitly allow during execution
|
|
170
|
-
* Examples: ['Read', 'LS', 'Bash(git log:*)']
|
|
171
|
-
*/
|
|
172
|
-
allowedTools?: string[];
|
|
173
|
-
/**
|
|
174
|
-
* Tools to disallow during execution
|
|
175
|
-
* Examples: ['Write', 'Edit', 'Bash(rm:*)']
|
|
176
|
-
*/
|
|
177
|
-
disallowedTools?: string[];
|
|
178
|
-
/**
|
|
179
|
-
* Enable Agent SDK beta features.
|
|
180
|
-
*/
|
|
181
|
-
betas?: SdkBeta[];
|
|
182
|
-
/**
|
|
183
|
-
* Allow bypassing permissions when using permissionMode: 'bypassPermissions'.
|
|
184
|
-
*/
|
|
185
|
-
allowDangerouslySkipPermissions?: boolean;
|
|
186
|
-
/**
|
|
187
|
-
* Enable file checkpointing for rewind support.
|
|
188
|
-
*/
|
|
189
|
-
enableFileCheckpointing?: boolean;
|
|
190
|
-
/**
|
|
191
|
-
* Maximum budget in USD for the query.
|
|
192
|
-
*/
|
|
193
|
-
maxBudgetUsd?: number;
|
|
194
|
-
/**
|
|
195
|
-
* Load custom plugins from local paths.
|
|
196
|
-
*/
|
|
197
|
-
plugins?: SdkPluginConfig[];
|
|
198
|
-
/**
|
|
199
|
-
* Resume session at a specific message UUID.
|
|
200
|
-
*/
|
|
201
|
-
resumeSessionAt?: string;
|
|
202
|
-
/**
|
|
203
|
-
* Configure sandbox behavior programmatically.
|
|
204
|
-
*
|
|
205
|
-
* Cannot be combined with a `settings` FILE PATH (the SDK throws at query
|
|
206
|
-
* time); pass `settings` as an inline object instead, or move the sandbox
|
|
207
|
-
* configuration into the settings file. The provider rejects the
|
|
208
|
-
* combination at validation time.
|
|
209
|
-
*/
|
|
210
|
-
sandbox?: SandboxSettings;
|
|
211
|
-
/**
|
|
212
|
-
* Tool configuration (array of tool names or Claude Code preset).
|
|
213
|
-
*/
|
|
214
|
-
tools?: Options['tools'];
|
|
215
|
-
/**
|
|
216
|
-
* Skills to enable for the main session. This is the single place to turn
|
|
217
|
-
* skills on; you do not need to add `'Skill'` to `allowedTools` yourself
|
|
218
|
-
* when using this option.
|
|
219
|
-
*
|
|
220
|
-
* - `'all'`: enable every discovered skill
|
|
221
|
-
* - `string[]`: enable only the listed skills (SKILL.md `name`/directory
|
|
222
|
-
* name, or `plugin:skill` for plugin-qualified skills)
|
|
223
|
-
* - omitted (default): no SDK auto-configuration
|
|
224
|
-
*
|
|
225
|
-
* Note: filesystem skills are discovered via `settingSources` — set it
|
|
226
|
-
* (e.g. `['user', 'project']`) so skill definitions can be loaded.
|
|
227
|
-
*/
|
|
228
|
-
skills?: string[] | 'all';
|
|
229
|
-
/**
|
|
230
|
-
* Inline settings object or path to a settings JSON file.
|
|
231
|
-
* Applied as an additional settings layer for the session.
|
|
232
|
-
*
|
|
233
|
-
* A settings file path cannot be combined with the `sandbox` option (the
|
|
234
|
-
* SDK throws at query time; inline objects are fine). The provider rejects
|
|
235
|
-
* the combination at validation time.
|
|
236
|
-
*/
|
|
237
|
-
settings?: string | Settings;
|
|
238
|
-
/**
|
|
239
|
-
* Policy-tier settings supplied by the spawning parent process.
|
|
240
|
-
* Filtered restrictive-only by the SDK; intended for embedding
|
|
241
|
-
* applications that need to enforce lockdown settings on the
|
|
242
|
-
* subprocess without writing root-owned files.
|
|
243
|
-
*/
|
|
244
|
-
managedSettings?: Settings;
|
|
245
|
-
/**
|
|
246
|
-
* Map built-in tool names to replacement tools (e.g. MCP tools).
|
|
247
|
-
*
|
|
248
|
-
* @example
|
|
249
|
-
* ```typescript
|
|
250
|
-
* toolAliases: { Bash: 'mcp__workspace__bash' }
|
|
251
|
-
* ```
|
|
252
|
-
*/
|
|
253
|
-
toolAliases?: Record<string, string>;
|
|
254
|
-
/**
|
|
255
|
-
* Per-tool configuration for built-in tools
|
|
256
|
-
* (e.g. `{ askUserQuestion: { previewFormat: 'html' } }`).
|
|
257
|
-
*/
|
|
258
|
-
toolConfig?: ToolConfig;
|
|
259
|
-
/**
|
|
260
|
-
* Custom workflow instructions for plan mode. When `permissionMode` is
|
|
261
|
-
* `'plan'`, this string replaces the default code-implementation workflow
|
|
262
|
-
* body in the plan-mode system reminder.
|
|
263
|
-
*/
|
|
264
|
-
planModeInstructions?: string;
|
|
265
|
-
/**
|
|
266
|
-
* Custom title for a new session. When provided, the session uses this
|
|
267
|
-
* title instead of auto-generating one from the first user message.
|
|
268
|
-
* When resuming, the resumed session's persisted title takes precedence.
|
|
269
|
-
*/
|
|
270
|
-
title?: string;
|
|
271
|
-
/**
|
|
272
|
-
* Forward subagent text and thinking blocks as messages with
|
|
273
|
-
* `parent_tool_use_id` set so consumers can render a nested transcript.
|
|
274
|
-
* By default only tool_use/tool_result blocks from subagents are emitted.
|
|
275
|
-
*/
|
|
276
|
-
forwardSubagentText?: boolean;
|
|
277
|
-
/**
|
|
278
|
-
* Enable periodic AI-generated progress summaries for running subagents,
|
|
279
|
-
* emitted on `task_progress` events via the `summary` field.
|
|
280
|
-
*/
|
|
281
|
-
agentProgressSummaries?: boolean;
|
|
282
|
-
/**
|
|
283
|
-
* Include hook lifecycle events (`hook_started`, `hook_progress`,
|
|
284
|
-
* `hook_response`) in the output stream for all hook event types.
|
|
285
|
-
* @default false
|
|
286
|
-
*/
|
|
287
|
-
includeHookEvents?: boolean;
|
|
288
|
-
/**
|
|
289
|
-
* MCP server configuration
|
|
290
|
-
*/
|
|
291
|
-
mcpServers?: Record<string, McpServerConfig>;
|
|
292
|
-
/**
|
|
293
|
-
* Filesystem settings sources to load (CLAUDE.md, settings.json, etc.)
|
|
294
|
-
* When omitted, the provider explicitly passes `[]` to the Agent SDK so that
|
|
295
|
-
* no filesystem settings are loaded (isolation mode).
|
|
296
|
-
*
|
|
297
|
-
* Note: Agent SDK 0.3.x changed the SDK-level default — omitting
|
|
298
|
-
* `settingSources` now loads ALL filesystem settings (matching CLI behavior).
|
|
299
|
-
* The provider pins isolation mode unless you set this option (or override
|
|
300
|
-
* `settingSources` via the `sdkOptions` escape hatch).
|
|
301
|
-
*
|
|
302
|
-
* Required for Skills support - skills are loaded from these sources.
|
|
303
|
-
* @example ['user', 'project']
|
|
304
|
-
*/
|
|
305
|
-
settingSources?: Array<'user' | 'project' | 'local'>;
|
|
306
|
-
/**
|
|
307
|
-
* Hook callbacks for lifecycle events (e.g., PreToolUse, PostToolUse).
|
|
308
|
-
* Note: typed loosely to support multiple SDK versions.
|
|
309
|
-
*
|
|
310
|
-
* Two verified upstream CLI behaviors to be aware of (CLI 2.1.172):
|
|
311
|
-
* - A `PreToolUse` hook returning `permissionDecision: 'defer'` combined
|
|
312
|
-
* with a {@link canUseTool} callback fails the tool call before
|
|
313
|
-
* `canUseTool` is ever consulted. Return no decision (or `'allow'`)
|
|
314
|
-
* instead of `'defer'` when `canUseTool` should handle the call.
|
|
315
|
-
* - The `PermissionDenied` hook only fires for CLI-internal auto-mode
|
|
316
|
-
* classifier denials (e.g. `permissionMode: 'auto'`). Denials issued by
|
|
317
|
-
* `canUseTool` do NOT trigger it; they surface via the result message's
|
|
318
|
-
* `permission_denials`, exposed as
|
|
319
|
-
* `providerMetadata['claude-code'].permissionDenials`.
|
|
320
|
-
*/
|
|
321
|
-
hooks?: Partial<Record<string, Array<{
|
|
322
|
-
matcher?: string;
|
|
323
|
-
hooks: Array<(...args: unknown[]) => Promise<unknown>>;
|
|
324
|
-
}>>>;
|
|
325
|
-
/**
|
|
326
|
-
* Dynamic permission callback invoked before a tool is executed.
|
|
327
|
-
* Allows runtime approval/denial and optional input mutation.
|
|
328
|
-
*
|
|
329
|
-
* Upstream CLI caveats (verified on CLI 2.1.172):
|
|
330
|
-
* - Do not combine with a `PreToolUse` hook that returns
|
|
331
|
-
* `permissionDecision: 'defer'` — the CLI fails the tool call before
|
|
332
|
-
* this callback is consulted.
|
|
333
|
-
* - Denials returned here do not fire the `PermissionDenied` hook (it only
|
|
334
|
-
* fires for auto-mode classifier denials); they surface in
|
|
335
|
-
* `providerMetadata['claude-code'].permissionDenials` instead.
|
|
336
|
-
*/
|
|
337
|
-
canUseTool?: CanUseTool;
|
|
338
|
-
/**
|
|
339
|
-
* Callback for handling `request_user_dialog` control requests — blocking
|
|
340
|
-
* dialogs the CLI asks the host to render (e.g. the refusal-fallback
|
|
341
|
-
* prompt). Each `dialogKind` defines its own payload and result shape;
|
|
342
|
-
* answer unrecognized kinds with `{ behavior: 'cancelled' }` so the CLI
|
|
343
|
-
* applies the dialog's default behavior.
|
|
344
|
-
*
|
|
345
|
-
* The SDK fails closed around dialogs: when the CLI requests a dialog and
|
|
346
|
-
* no handler/declared kind exists, the dialog-gated flow degrades to its
|
|
347
|
-
* no-dialog behavior (for `'refusal_fallback_prompt'`, the classic refusal
|
|
348
|
-
* error ends the turn). Wire this callback together with
|
|
349
|
-
* `supportedDialogKinds` to opt in — providing the callback alone does NOT
|
|
350
|
-
* make the CLI emit dialogs.
|
|
351
|
-
*/
|
|
352
|
-
onUserDialog?: OnUserDialog;
|
|
353
|
-
/**
|
|
354
|
-
* Dialog kinds (`request_user_dialog` `dialog_kind` values, e.g.
|
|
355
|
-
* `'refusal_fallback_prompt'`) that your `onUserDialog` callback can
|
|
356
|
-
* actually render. The CLI only emits dialog kinds declared here and
|
|
357
|
-
* fails closed on absence: an undeclared kind is never emitted and the
|
|
358
|
-
* flow behind it degrades to its no-dialog behavior instead. Omitting the
|
|
359
|
-
* option entirely means no dialogs are emitted, even with `onUserDialog`
|
|
360
|
-
* wired.
|
|
361
|
-
*
|
|
362
|
-
* Requires `onUserDialog` — the SDK throws at option intake when a
|
|
363
|
-
* non-empty list is passed without the callback (the provider also warns
|
|
364
|
-
* at validation time).
|
|
365
|
-
*/
|
|
366
|
-
supportedDialogKinds?: string[];
|
|
367
|
-
/**
|
|
368
|
-
* Controls whether to send streaming input to the SDK (enables canUseTool).
|
|
369
|
-
* - 'auto' (default): stream when canUseTool is provided
|
|
370
|
-
* - 'always': always stream
|
|
371
|
-
* - 'off': never stream (legacy behavior)
|
|
372
|
-
*/
|
|
373
|
-
streamingInput?: StreamingInputMode;
|
|
374
|
-
/**
|
|
375
|
-
* Enable verbose logging for debugging
|
|
376
|
-
*/
|
|
377
|
-
verbose?: boolean;
|
|
378
|
-
/**
|
|
379
|
-
* Enable programmatic debug logging from the SDK.
|
|
380
|
-
*/
|
|
381
|
-
debug?: boolean;
|
|
382
|
-
/**
|
|
383
|
-
* Path to a file for SDK debug log output.
|
|
384
|
-
*/
|
|
385
|
-
debugFile?: string;
|
|
386
|
-
/**
|
|
387
|
-
* Custom logger for handling warnings and errors.
|
|
388
|
-
* - Set to `false` to disable all logging
|
|
389
|
-
* - Provide a Logger object to use custom logging
|
|
390
|
-
* - Leave undefined to use console (default)
|
|
391
|
-
*
|
|
392
|
-
* @default console
|
|
393
|
-
* @example
|
|
394
|
-
* ```typescript
|
|
395
|
-
* // Disable logging
|
|
396
|
-
* const settings = { logger: false };
|
|
397
|
-
*
|
|
398
|
-
* // Custom logger
|
|
399
|
-
* const settings = {
|
|
400
|
-
* logger: {
|
|
401
|
-
* warn: (msg) => myLogger.warn(msg),
|
|
402
|
-
* error: (msg) => myLogger.error(msg),
|
|
403
|
-
* }
|
|
404
|
-
* };
|
|
405
|
-
* ```
|
|
406
|
-
*/
|
|
407
|
-
logger?: Logger | false;
|
|
408
|
-
/**
|
|
409
|
-
* Environment variables to set for the Claude Code subprocess.
|
|
410
|
-
*
|
|
411
|
-
* The provider always constructs the subprocess environment from a sanitizing
|
|
412
|
-
* allowlist of `process.env` (HOME, PATH, proxy/TLS vars, `ANTHROPIC_*`,
|
|
413
|
-
* `CLAUDE_*`, `AWS_*`, `GOOGLE_*`, etc.), then merges these values over it
|
|
414
|
-
* (set a key to `undefined` to remove it). Agent SDK 0.3.x treats
|
|
415
|
-
* `Options.env` as a full replacement for the subprocess environment, so
|
|
416
|
-
* variables outside the allowlist are not inherited unless set here.
|
|
417
|
-
*/
|
|
418
|
-
env?: Record<string, string | undefined>;
|
|
419
|
-
/**
|
|
420
|
-
* Additional directories Claude can access.
|
|
421
|
-
*/
|
|
422
|
-
additionalDirectories?: string[];
|
|
423
|
-
/**
|
|
424
|
-
* Programmatically defined subagents.
|
|
425
|
-
*
|
|
426
|
-
* Uses the Agent SDK's `AgentDefinition` directly, which includes
|
|
427
|
-
* `effort`, `permissionMode`, `background`, `memory`, `initialPrompt`,
|
|
428
|
-
* `skills`, `maxTurns`, and full model ID strings in addition to the
|
|
429
|
-
* core `description`/`prompt`/`tools` fields.
|
|
430
|
-
*/
|
|
431
|
-
agents?: Record<string, AgentDefinition>;
|
|
432
|
-
/**
|
|
433
|
-
* Include partial message events from the SDK stream.
|
|
434
|
-
*/
|
|
435
|
-
includePartialMessages?: boolean;
|
|
436
|
-
/**
|
|
437
|
-
* Model(s) to use if the primary model is overloaded or unavailable.
|
|
438
|
-
* Accepts a comma-separated list to try each in order; the primary model
|
|
439
|
-
* is re-tried at the start of each user turn.
|
|
440
|
-
*
|
|
441
|
-
* Must differ from the main model (the SDK throws when they are equal);
|
|
442
|
-
* the provider rejects the combination before invoking the SDK.
|
|
443
|
-
*/
|
|
444
|
-
fallbackModel?: string;
|
|
445
|
-
/**
|
|
446
|
-
* When resuming, fork to a new session ID instead of continuing the original.
|
|
447
|
-
*/
|
|
448
|
-
forkSession?: boolean;
|
|
449
|
-
/**
|
|
450
|
-
* Callback for stderr output from the underlying process.
|
|
451
|
-
*/
|
|
452
|
-
stderr?: (data: string) => void;
|
|
453
|
-
/**
|
|
454
|
-
* Enforce strict MCP validation.
|
|
455
|
-
*/
|
|
456
|
-
strictMcpConfig?: boolean;
|
|
457
|
-
/**
|
|
458
|
-
* Additional CLI arguments.
|
|
459
|
-
*/
|
|
460
|
-
extraArgs?: Record<string, string | null>;
|
|
461
|
-
/**
|
|
462
|
-
* When false, disables session persistence to disk.
|
|
463
|
-
* Sessions will not be saved to ~/.claude/projects/ and cannot be resumed later.
|
|
464
|
-
* Useful for ephemeral or automated workflows where session history is not needed.
|
|
465
|
-
* @default true
|
|
466
|
-
*/
|
|
467
|
-
persistSession?: boolean;
|
|
468
|
-
/**
|
|
469
|
-
* API-side task budget in tokens. When set, the model is made aware of
|
|
470
|
-
* its remaining token budget so it can pace tool use and wrap up before
|
|
471
|
-
* the limit.
|
|
472
|
-
*
|
|
473
|
-
* @alpha Subject to change in upstream Agent SDK releases.
|
|
474
|
-
*/
|
|
475
|
-
taskBudget?: {
|
|
476
|
-
total: number;
|
|
477
|
-
};
|
|
478
|
-
/**
|
|
479
|
-
* Mirror session transcripts to a custom storage adapter (e.g. Postgres,
|
|
480
|
-
* S3, Redis) in addition to local JSONL files. Cannot be combined with
|
|
481
|
-
* `persistSession: false` — local writes are required for the mirror to
|
|
482
|
-
* function — or with `enableFileCheckpointing: true` — checkpoint backup
|
|
483
|
-
* blobs are not mirrored, so `rewindFiles()` fails after a store-backed
|
|
484
|
-
* resume. Combining it with `continue: true` (without a `resume` ID)
|
|
485
|
-
* additionally requires the store to implement `listSessions()`, which the
|
|
486
|
-
* SDK uses to discover the most recent session. The provider rejects all
|
|
487
|
-
* three invalid combinations at validation time.
|
|
488
|
-
*
|
|
489
|
-
* @alpha Subject to change in upstream Agent SDK releases.
|
|
490
|
-
*/
|
|
491
|
-
sessionStore?: SessionStore;
|
|
492
|
-
/**
|
|
493
|
-
* Flush strategy for `sessionStore` transcript mirroring:
|
|
494
|
-
* `'batched'` (default) or `'eager'`. Ignored when `sessionStore` is unset.
|
|
495
|
-
*
|
|
496
|
-
* @alpha Subject to change in upstream Agent SDK releases.
|
|
497
|
-
*/
|
|
498
|
-
sessionStoreFlush?: SessionStoreFlush;
|
|
499
|
-
/**
|
|
500
|
-
* Timeout in milliseconds for each `sessionStore.load()` /
|
|
501
|
-
* `sessionStore.listSubkeys()` call during resume materialization.
|
|
502
|
-
*
|
|
503
|
-
* @default 60000
|
|
504
|
-
* @alpha Subject to change in upstream Agent SDK releases.
|
|
505
|
-
*/
|
|
506
|
-
loadTimeoutMs?: number;
|
|
507
|
-
/**
|
|
508
|
-
* Custom function to spawn the Claude Code process.
|
|
509
|
-
* Use this to run Claude Code in VMs, containers, or remote environments.
|
|
510
|
-
*/
|
|
511
|
-
spawnClaudeCodeProcess?: (options: SpawnOptions) => SpawnedProcess;
|
|
512
|
-
/**
|
|
513
|
-
* Escape hatch for Agent SDK options. Overrides explicit settings.
|
|
514
|
-
* Provider-managed fields (e.g. model, abortController, prompt, outputFormat)
|
|
515
|
-
* are ignored if supplied here.
|
|
516
|
-
*/
|
|
517
|
-
sdkOptions?: Partial<Options>;
|
|
518
|
-
/**
|
|
519
|
-
* Maximum size (in characters) for tool results sent to the client stream.
|
|
520
|
-
* The interior Claude Code process retains full data; this only affects client stream.
|
|
521
|
-
* Tool results exceeding this size will be truncated with a `...[truncated N chars]` suffix.
|
|
522
|
-
* @default 10000
|
|
523
|
-
*/
|
|
524
|
-
maxToolResultSize?: number;
|
|
525
|
-
/**
|
|
526
|
-
* Callback invoked when the Query object is created.
|
|
527
|
-
* Use this to access the Query for advanced features like mid-stream
|
|
528
|
-
* message injection via `query.streamInput()`.
|
|
529
|
-
*
|
|
530
|
-
* @example
|
|
531
|
-
* ```typescript
|
|
532
|
-
* const model = claudeCode('sonnet', {
|
|
533
|
-
* onQueryCreated: (query) => {
|
|
534
|
-
* // Store query for later injection
|
|
535
|
-
* myQueryStore.set(sessionId, query);
|
|
536
|
-
* }
|
|
537
|
-
* });
|
|
538
|
-
* ```
|
|
539
|
-
*/
|
|
540
|
-
onQueryCreated?: (query: Query) => void;
|
|
541
|
-
/**
|
|
542
|
-
* Callback invoked when streaming input mode starts.
|
|
543
|
-
* Provides a MessageInjector that can be used to inject messages mid-session.
|
|
544
|
-
*
|
|
545
|
-
* This enables supervisor patterns where you can redirect or interrupt
|
|
546
|
-
* the agent during execution.
|
|
547
|
-
*
|
|
548
|
-
* @example
|
|
549
|
-
* ```typescript
|
|
550
|
-
* const model = claudeCode("haiku", {
|
|
551
|
-
* streamingInput: "always",
|
|
552
|
-
* onStreamStart: (injector) => {
|
|
553
|
-
* // Store the injector for later use
|
|
554
|
-
* supervisorInjector = injector;
|
|
555
|
-
* }
|
|
556
|
-
* });
|
|
557
|
-
*
|
|
558
|
-
* // Later, inject a message mid-session:
|
|
559
|
-
* supervisorInjector.inject("STOP! Change of plans...");
|
|
560
|
-
* ```
|
|
561
|
-
*/
|
|
562
|
-
onStreamStart?: (injector: MessageInjector) => void;
|
|
563
|
-
/**
|
|
564
|
-
* Callback invoked when the agent emits a prompt suggestion (a predicted
|
|
565
|
-
* next user prompt). Suggestions are enabled when `promptSuggestions` is
|
|
566
|
-
* `true` OR left unset (the SDK enables them when the option is absent or
|
|
567
|
-
* true and disables them only when explicitly `false`). When the callback
|
|
568
|
-
* is set and `promptSuggestions !== false`, the provider drains post-result
|
|
569
|
-
* messages to deliver the suggestion. Delivery is still subject to CLI
|
|
570
|
-
* heuristics — suppressed on the first turn, after API errors, in plan
|
|
571
|
-
* mode, and by `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false` — so it may not
|
|
572
|
-
* fire on every turn.
|
|
573
|
-
*
|
|
574
|
-
* The SDK emits at most one `prompt_suggestion` message per turn, and it
|
|
575
|
-
* arrives AFTER the `result` message — i.e. after the AI SDK response has
|
|
576
|
-
* already finished. That is why suggestions are delivered through this
|
|
577
|
-
* callback instead of `providerMetadata` (which is finalized with the
|
|
578
|
-
* finish event/result).
|
|
579
|
-
*
|
|
580
|
-
* @example
|
|
581
|
-
* ```typescript
|
|
582
|
-
* const model = claudeCode('sonnet', {
|
|
583
|
-
* promptSuggestions: true,
|
|
584
|
-
* onPromptSuggestion: (suggestion) => {
|
|
585
|
-
* console.log('Suggested next prompt:', suggestion);
|
|
586
|
-
* }
|
|
587
|
-
* });
|
|
588
|
-
* ```
|
|
589
|
-
*/
|
|
590
|
-
onPromptSuggestion?: (suggestion: string) => void;
|
|
591
|
-
}
|
|
592
|
-
/**
|
|
593
|
-
* Controller for injecting messages into an active Claude Code session.
|
|
594
|
-
* Obtained via the onStreamStart callback.
|
|
595
|
-
*/
|
|
596
|
-
interface MessageInjector {
|
|
597
|
-
/**
|
|
598
|
-
* Inject a user message into the current session.
|
|
599
|
-
* The message will be queued and sent to the agent mid-turn.
|
|
600
|
-
*
|
|
601
|
-
* @param content - The message content to inject
|
|
602
|
-
* @param onResult - Optional callback invoked when delivery status is known:
|
|
603
|
-
* - `delivered: true` if the message was sent to the agent
|
|
604
|
-
* - `delivered: false` if the session ended before the message could be delivered
|
|
605
|
-
*
|
|
606
|
-
* @example
|
|
607
|
-
* ```typescript
|
|
608
|
-
* // Fire-and-forget
|
|
609
|
-
* injector.inject("STOP! Cancel the current task.");
|
|
610
|
-
*
|
|
611
|
-
* // With delivery tracking
|
|
612
|
-
* injector.inject("Change of plans!", (delivered) => {
|
|
613
|
-
* if (!delivered) {
|
|
614
|
-
* console.log("Message not delivered - session ended first");
|
|
615
|
-
* // Handle retry via session resume, etc.
|
|
616
|
-
* }
|
|
617
|
-
* });
|
|
618
|
-
* ```
|
|
619
|
-
*/
|
|
620
|
-
inject(content: string, onResult?: (delivered: boolean) => void): void;
|
|
621
|
-
/**
|
|
622
|
-
* Signal that no more messages will be injected.
|
|
623
|
-
* Call this when the session should be allowed to complete normally.
|
|
624
|
-
*/
|
|
625
|
-
close(): void;
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
/**
|
|
629
|
-
* Options for creating a Claude Code language model instance.
|
|
630
|
-
*
|
|
631
|
-
* @example
|
|
632
|
-
* ```typescript
|
|
633
|
-
* const model = new ClaudeCodeLanguageModel({
|
|
634
|
-
* id: 'opus',
|
|
635
|
-
* settings: {
|
|
636
|
-
* maxTurns: 10,
|
|
637
|
-
* permissionMode: 'auto'
|
|
638
|
-
* }
|
|
639
|
-
* });
|
|
640
|
-
* ```
|
|
641
|
-
*/
|
|
642
|
-
interface ClaudeCodeLanguageModelOptions {
|
|
643
|
-
/**
|
|
644
|
-
* The model identifier to use.
|
|
645
|
-
* Can be 'opus', 'sonnet', 'haiku', or a custom model string.
|
|
646
|
-
*/
|
|
647
|
-
id: ClaudeCodeModelId;
|
|
648
|
-
/**
|
|
649
|
-
* Optional settings to configure the model behavior.
|
|
650
|
-
*/
|
|
651
|
-
settings?: ClaudeCodeSettings;
|
|
652
|
-
/**
|
|
653
|
-
* Validation warnings from settings validation.
|
|
654
|
-
* Used internally to pass warnings from provider.
|
|
655
|
-
*/
|
|
656
|
-
settingsValidationWarnings?: string[];
|
|
657
|
-
}
|
|
658
|
-
/**
|
|
659
|
-
* Supported Claude model identifiers.
|
|
660
|
-
* - 'opus': Claude Opus (most capable)
|
|
661
|
-
* - 'sonnet': Claude Sonnet (balanced performance)
|
|
662
|
-
* - 'haiku': Claude Haiku (fastest, most cost-effective)
|
|
663
|
-
* - Custom string: Any full model identifier (e.g., 'claude-opus-4-5', 'claude-sonnet-4-5-20250514')
|
|
664
|
-
*
|
|
665
|
-
* @example
|
|
666
|
-
* ```typescript
|
|
667
|
-
* const opusModel = claudeCode('opus');
|
|
668
|
-
* const sonnetModel = claudeCode('sonnet');
|
|
669
|
-
* const haikuModel = claudeCode('haiku');
|
|
670
|
-
* const customModel = claudeCode('claude-opus-4-5');
|
|
671
|
-
* ```
|
|
672
|
-
*/
|
|
673
|
-
type ClaudeCodeModelId = 'opus' | 'sonnet' | 'haiku' | (string & {});
|
|
674
|
-
/**
|
|
675
|
-
* Language model implementation for Claude Code SDK.
|
|
676
|
-
* This class implements the AI SDK's LanguageModelV3 interface to provide
|
|
677
|
-
* integration with Claude models through the Claude Agent SDK.
|
|
678
|
-
*
|
|
679
|
-
* Features:
|
|
680
|
-
* - Supports streaming and non-streaming generation
|
|
681
|
-
* - Native structured outputs via SDK's outputFormat (guaranteed schema compliance)
|
|
682
|
-
* - Manages CLI sessions for conversation continuity
|
|
683
|
-
* - Provides detailed error handling and retry logic
|
|
684
|
-
*
|
|
685
|
-
* Limitations:
|
|
686
|
-
* - Image inputs require streaming mode
|
|
687
|
-
* - Some parameters like temperature and max tokens are not supported by the CLI
|
|
688
|
-
*
|
|
689
|
-
* @example
|
|
690
|
-
* ```typescript
|
|
691
|
-
* const model = new ClaudeCodeLanguageModel({
|
|
692
|
-
* id: 'opus',
|
|
693
|
-
* settings: { maxTurns: 5 }
|
|
694
|
-
* });
|
|
695
|
-
*
|
|
696
|
-
* const result = await model.doGenerate({
|
|
697
|
-
* prompt: [{ role: 'user', content: 'Hello!' }],
|
|
698
|
-
* mode: { type: 'regular' }
|
|
699
|
-
* });
|
|
700
|
-
* ```
|
|
701
|
-
*/
|
|
702
|
-
declare class ClaudeCodeLanguageModel implements LanguageModelV3 {
|
|
703
|
-
readonly specificationVersion: "v3";
|
|
704
|
-
readonly defaultObjectGenerationMode: "json";
|
|
705
|
-
readonly supportsImageUrls = false;
|
|
706
|
-
readonly supportedUrls: {};
|
|
707
|
-
readonly supportsStructuredOutputs = true;
|
|
708
|
-
static readonly UNKNOWN_TOOL_NAME = "unknown-tool";
|
|
709
|
-
private static readonly MAX_TOOL_INPUT_SIZE;
|
|
710
|
-
private static readonly MAX_TOOL_INPUT_WARN;
|
|
711
|
-
private static readonly MAX_DELTA_CALC_SIZE;
|
|
712
|
-
private static readonly PROMPT_SUGGESTION_DRAIN_TIMEOUT_MS;
|
|
713
|
-
readonly modelId: ClaudeCodeModelId;
|
|
714
|
-
readonly settings: ClaudeCodeSettings;
|
|
715
|
-
private sessionId?;
|
|
716
|
-
private modelValidationWarning?;
|
|
717
|
-
private settingsValidationWarnings;
|
|
718
|
-
private logger;
|
|
719
|
-
constructor(options: ClaudeCodeLanguageModelOptions);
|
|
720
|
-
get provider(): string;
|
|
721
|
-
private getModel;
|
|
722
|
-
private getSanitizedSdkOptions;
|
|
723
|
-
private getEffectiveResume;
|
|
724
|
-
/**
|
|
725
|
-
* Single source of truth for the CLI's `--session-id` exclusivity rule.
|
|
726
|
-
*
|
|
727
|
-
* The CLI rejects `--session-id` together with `--resume`/`--continue`
|
|
728
|
-
* unless `--fork-session` is also set (forkSession then names the forked
|
|
729
|
-
* session's own ID). This predicate captures "there IS a resume/continue
|
|
730
|
-
* target AND we are not forking", i.e. the case where a session id must NOT
|
|
731
|
-
* coexist. It is referenced by both:
|
|
732
|
-
* - the pre-merge forwarding guard (via its inverse), which decides whether
|
|
733
|
-
* to forward `settings.sessionId` onto the base options, and
|
|
734
|
-
* - the post-merge exclusivity drop, which removes any session id that the
|
|
735
|
-
* generic sdkOptions overlay (or the auto-resume turn) re-introduced.
|
|
736
|
-
*
|
|
737
|
-
* Keeping one definition guarantees both sites agree on what "conflicts with
|
|
738
|
-
* a session id" means. The mirror in validation.ts (construction-time)
|
|
739
|
-
* intentionally stays separate: it reads settings+sdkOptions, not a built
|
|
740
|
-
* opts object.
|
|
741
|
-
*/
|
|
742
|
-
private static sessionIdConflictsWithResumeOrContinue;
|
|
743
|
-
/**
|
|
744
|
-
* Owns ALL session-id / resume cross-option resolution on the FINAL merged
|
|
745
|
-
* options, in the single correct order. Called once, immediately after the
|
|
746
|
-
* generic sdkOptions overlay in createQueryOptions.
|
|
747
|
-
*
|
|
748
|
-
* Two concerns, in this exact order (order matters: step 1 can change whether
|
|
749
|
-
* step 2 sees a resume target):
|
|
750
|
-
*
|
|
751
|
-
* 1. Blank-resume restoration. The overlay copies the raw `sdkOptions.resume`
|
|
752
|
-
* verbatim, which can re-introduce a blank/whitespace value over the
|
|
753
|
-
* base `resume` that getEffectiveResume already normalized. The SDK treats
|
|
754
|
-
* a blank resume as absent, so a blank must NOT clobber the computed
|
|
755
|
-
* fallback — restore `effectiveResume` (already blank-stripped; may itself
|
|
756
|
-
* be undefined for a genuinely new session) rather than leaving '' or
|
|
757
|
-
* forcing undefined, which would erase a real settings.resume / captured
|
|
758
|
-
* session id.
|
|
759
|
-
*
|
|
760
|
-
* 2. Session-id exclusivity. Drop `opts.sessionId` whenever it conflicts with
|
|
761
|
-
* a resume/continue target (see sessionIdConflictsWithResumeOrContinue).
|
|
762
|
-
* This runs on the merged opts so it catches a sessionId re-added by the
|
|
763
|
-
* sdkOptions overlay AND the auto-resumed second turn (where resume was
|
|
764
|
-
* populated from the captured session id). It complements — does not
|
|
765
|
-
* replace — the pre-merge forwarding guard, which governs whether
|
|
766
|
-
* settings.sessionId was forwarded BEFORE the overlay could mutate
|
|
767
|
-
* forkSession/continue/resume.
|
|
768
|
-
*/
|
|
769
|
-
private applySessionResolution;
|
|
770
|
-
private extractToolUses;
|
|
771
|
-
private extractToolResults;
|
|
772
|
-
private extractToolErrors;
|
|
773
|
-
private serializeToolInput;
|
|
774
|
-
private checkInputSize;
|
|
775
|
-
private normalizeToolResult;
|
|
776
|
-
/**
|
|
777
|
-
* Builds a provider-executed `tool-call` part from an assistant `tool_use`
|
|
778
|
-
* block. Shared by doGenerate (content part) and doStream (stream part) so
|
|
779
|
-
* the two paths cannot drift in field shape.
|
|
780
|
-
*/
|
|
781
|
-
private buildToolCallPart;
|
|
782
|
-
/**
|
|
783
|
-
* Builds a provider-executed `tool-result` part from a user-message
|
|
784
|
-
* `tool_result` block, applying normalization and `maxToolResultSize`
|
|
785
|
-
* truncation. Shared by doGenerate and doStream.
|
|
786
|
-
*/
|
|
787
|
-
private buildToolResultPart;
|
|
788
|
-
private serializeToolError;
|
|
789
|
-
/**
|
|
790
|
-
* Builds a provider-executed `tool-error` STREAM part from a user-message
|
|
791
|
-
* `tool_error` block (doStream only; AI SDK core handles tool-error stream
|
|
792
|
-
* parts natively).
|
|
793
|
-
*/
|
|
794
|
-
private buildToolErrorPart;
|
|
795
|
-
/**
|
|
796
|
-
* Builds a V3 `tool-result` CONTENT part with `isError: true` from a
|
|
797
|
-
* user-message `tool_error` block (doGenerate only). The V3 content union
|
|
798
|
-
* has no `tool-error` member and AI SDK core's asContent() silently drops
|
|
799
|
-
* unknown content part types, so an extension tool-error part would never
|
|
800
|
-
* reach `generateText` users — an isError tool-result, by contrast,
|
|
801
|
-
* round-trips into a proper tool-error part in steps content.
|
|
802
|
-
*/
|
|
803
|
-
private buildToolErrorResultPart;
|
|
804
|
-
/**
|
|
805
|
-
* Policy (P3): late-frame drop guard, shared by all four tool_result/tool_error
|
|
806
|
-
* sites (doGenerate result+error, doStream result+error). When a frame's tool
|
|
807
|
-
* id is tombstoned (its tool-call was retracted by a supersede/refusal-fallback
|
|
808
|
-
* signal), the frame must be DROPPED rather than re-synthesized into an orphan
|
|
809
|
-
* tool-call. Centralizing the predicate + debug message keeps the four sites in
|
|
810
|
-
* lockstep so a future tombstone change can't be applied to only some of them.
|
|
811
|
-
*/
|
|
812
|
-
private isRetractedToolFrame;
|
|
813
|
-
private generateAllWarnings;
|
|
814
|
-
private createQueryOptions;
|
|
815
|
-
private handleClaudeCodeError;
|
|
816
|
-
private setSessionId;
|
|
817
|
-
private logMcpConnectionIssues;
|
|
818
|
-
/**
|
|
819
|
-
* Handles SDK 0.3.x system messages other than 'init', shared by doGenerate
|
|
820
|
-
* and doStream:
|
|
821
|
-
* - 'api_retry' is counted into providerMetadata (`apiRetries`) and debug-logged.
|
|
822
|
-
* - 'permission_denied' is warn-logged and recorded into providerMetadata
|
|
823
|
-
* (`permissionDenials`); without this a denial is invisible until the
|
|
824
|
-
* model talks about it.
|
|
825
|
-
* - 'model_refusal_fallback' is debug-logged (the superseding assistant
|
|
826
|
-
* message is handled by the text-dedup guard in the message loops).
|
|
827
|
-
* - 'thinking_tokens' deltas are accumulated into providerMetadata
|
|
828
|
-
* (`estimatedThinkingTokens`); the estimate is explicitly not the
|
|
829
|
-
* authoritative billed output tokens, so it is surfaced as metadata
|
|
830
|
-
* instead of feeding `usage.outputTokens.reasoning`.
|
|
831
|
-
* - The subtypes in {@link INFORMATIONAL_SYSTEM_SUBTYPES} are intentionally
|
|
832
|
-
* informational and only debug-logged.
|
|
833
|
-
*/
|
|
834
|
-
private handleSystemMessage;
|
|
835
|
-
/**
|
|
836
|
-
* Merges the result message's `permission_denials` list into the tracked
|
|
837
|
-
* denials. PreToolUse-hook denies bypass canUseTool and emit no
|
|
838
|
-
* `permission_denied` system event (per the SDK docs on
|
|
839
|
-
* SDKPermissionDeniedMessage), so the result list is the only place they
|
|
840
|
-
* surface. Entries already recorded from stream-time events are deduped by
|
|
841
|
-
* `tool_use_id`.
|
|
842
|
-
*/
|
|
843
|
-
private mergeResultPermissionDenials;
|
|
844
|
-
/**
|
|
845
|
-
* Bounded post-result drain for the `prompt_suggestion` message
|
|
846
|
-
* (promptSuggestions: true), shared by doGenerate and doStream. The
|
|
847
|
-
* suggestion arrives AFTER the result message; the SDK emits at most one
|
|
848
|
-
* per turn, so stop once it is delivered, and a timeout closes the
|
|
849
|
-
* iterator (tearing down the subprocess) if the CLI lingers after the
|
|
850
|
-
* result without emitting one. Advances the response's own generator, so
|
|
851
|
-
* the caller's surrounding loop resumes to a finished iterator.
|
|
852
|
-
*/
|
|
853
|
-
private drainPromptSuggestion;
|
|
854
|
-
doGenerate(options: Parameters<LanguageModelV3['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV3['doGenerate']>>>;
|
|
855
|
-
doStream(options: Parameters<LanguageModelV3['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV3['doStream']>>>;
|
|
856
|
-
private serializeWarningsForMetadata;
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
/**
|
|
860
|
-
* Claude Code provider interface that extends the AI SDK's ProviderV3.
|
|
861
|
-
* Provides methods to create language models for interacting with Claude via the CLI.
|
|
862
|
-
*
|
|
863
|
-
* @example
|
|
864
|
-
* ```typescript
|
|
865
|
-
* import { claudeCode } from 'ai-sdk-provider-claude-code';
|
|
866
|
-
*
|
|
867
|
-
* // Create a model instance
|
|
868
|
-
* const model = claudeCode('opus');
|
|
869
|
-
*
|
|
870
|
-
* // Or use the explicit methods
|
|
871
|
-
* const chatModel = claudeCode.chat('sonnet');
|
|
872
|
-
* const languageModel = claudeCode.languageModel('opus', { maxTurns: 10 });
|
|
873
|
-
* ```
|
|
874
|
-
*/
|
|
875
|
-
interface ClaudeCodeProvider extends ProviderV3 {
|
|
876
|
-
/**
|
|
877
|
-
* Creates a language model instance for the specified model ID.
|
|
878
|
-
* This is a shorthand for calling `languageModel()`.
|
|
879
|
-
*
|
|
880
|
-
* @param modelId - The Claude model to use ('opus' or 'sonnet')
|
|
881
|
-
* @param settings - Optional settings to configure the model
|
|
882
|
-
* @returns A language model instance
|
|
883
|
-
*/
|
|
884
|
-
(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;
|
|
885
|
-
/**
|
|
886
|
-
* Creates a language model instance for text generation.
|
|
887
|
-
*
|
|
888
|
-
* @param modelId - The Claude model to use ('opus' or 'sonnet')
|
|
889
|
-
* @param settings - Optional settings to configure the model
|
|
890
|
-
* @returns A language model instance
|
|
891
|
-
*/
|
|
892
|
-
languageModel(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;
|
|
893
|
-
/**
|
|
894
|
-
* Alias for `languageModel()` to maintain compatibility with AI SDK patterns.
|
|
895
|
-
*
|
|
896
|
-
* @param modelId - The Claude model to use ('opus' or 'sonnet')
|
|
897
|
-
* @param settings - Optional settings to configure the model
|
|
898
|
-
* @returns A language model instance
|
|
899
|
-
*/
|
|
900
|
-
chat(modelId: ClaudeCodeModelId, settings?: ClaudeCodeSettings): LanguageModelV3;
|
|
901
|
-
imageModel(modelId: string): never;
|
|
902
|
-
}
|
|
903
|
-
/**
|
|
904
|
-
* Configuration options for creating a Claude Code provider instance.
|
|
905
|
-
* These settings will be applied as defaults to all models created by the provider.
|
|
906
|
-
*
|
|
907
|
-
* @example
|
|
908
|
-
* ```typescript
|
|
909
|
-
* const provider = createClaudeCode({
|
|
910
|
-
* defaultSettings: {
|
|
911
|
-
* maxTurns: 5,
|
|
912
|
-
* cwd: '/path/to/project'
|
|
913
|
-
* }
|
|
914
|
-
* });
|
|
915
|
-
* ```
|
|
916
|
-
*/
|
|
917
|
-
interface ClaudeCodeProviderSettings {
|
|
918
|
-
/**
|
|
919
|
-
* Default settings to use for all models created by this provider.
|
|
920
|
-
* Individual model settings will override these defaults.
|
|
921
|
-
*/
|
|
922
|
-
defaultSettings?: ClaudeCodeSettings;
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Creates a Claude Code provider instance with the specified configuration.
|
|
926
|
-
* The provider can be used to create language models for interacting with Claude 4 models.
|
|
927
|
-
*
|
|
928
|
-
* @param options - Provider configuration options
|
|
929
|
-
* @returns Claude Code provider instance
|
|
930
|
-
*
|
|
931
|
-
* @example
|
|
932
|
-
* ```typescript
|
|
933
|
-
* const provider = createClaudeCode({
|
|
934
|
-
* defaultSettings: {
|
|
935
|
-
* permissionMode: 'bypassPermissions',
|
|
936
|
-
* maxTurns: 10
|
|
937
|
-
* }
|
|
938
|
-
* });
|
|
939
|
-
*
|
|
940
|
-
* const model = provider('opus');
|
|
941
|
-
* ```
|
|
942
|
-
*/
|
|
943
|
-
declare function createClaudeCode(options?: ClaudeCodeProviderSettings): ClaudeCodeProvider;
|
|
944
|
-
/**
|
|
945
|
-
* Default Claude Code provider instance.
|
|
946
|
-
* Pre-configured provider for quick usage without custom settings.
|
|
947
|
-
*
|
|
948
|
-
* @example
|
|
949
|
-
* ```typescript
|
|
950
|
-
* import { claudeCode } from 'ai-sdk-provider-claude-code';
|
|
951
|
-
* import { generateText } from 'ai';
|
|
952
|
-
*
|
|
953
|
-
* const { text } = await generateText({
|
|
954
|
-
* model: claudeCode('sonnet'),
|
|
955
|
-
* prompt: 'Hello, Claude!'
|
|
956
|
-
* });
|
|
957
|
-
* ```
|
|
958
|
-
*/
|
|
959
|
-
declare const claudeCode: ClaudeCodeProvider;
|
|
960
|
-
|
|
961
|
-
/**
|
|
962
|
-
* Optional annotations for content items, per MCP specification.
|
|
963
|
-
* Validated against MCP SDK schema version 2025-06-18.
|
|
964
|
-
*/
|
|
965
|
-
type ContentAnnotations = {
|
|
966
|
-
/** Intended audience(s) for this content */
|
|
967
|
-
audience?: ('user' | 'assistant')[];
|
|
968
|
-
/** Priority hint (0 = least important, 1 = most important) */
|
|
969
|
-
priority?: number;
|
|
970
|
-
/** ISO 8601 timestamp of last modification */
|
|
971
|
-
lastModified?: string;
|
|
972
|
-
};
|
|
973
|
-
/**
|
|
974
|
-
* MCP tool annotations for hinting tool behavior to the model.
|
|
975
|
-
* Derived from the SDK's SdkMcpToolDefinition type to stay in sync
|
|
976
|
-
* with the upstream MCP ToolAnnotations definition.
|
|
977
|
-
*/
|
|
978
|
-
type ToolAnnotations = NonNullable<SdkMcpToolDefinition['annotations']>;
|
|
979
|
-
/**
|
|
980
|
-
* Convenience helper to create an SDK MCP server from a simple tool map.
|
|
981
|
-
* Each tool provides a description, a Zod object schema, and a handler.
|
|
982
|
-
*
|
|
983
|
-
* Type definition validated against MCP SDK specification version 2025-06-18.
|
|
984
|
-
* See: https://modelcontextprotocol.io/specification/2025-06-18/server/tools
|
|
985
|
-
*/
|
|
986
|
-
type MinimalCallToolResult = {
|
|
987
|
-
content: Array<{
|
|
988
|
-
/** Text content */
|
|
989
|
-
type: 'text';
|
|
990
|
-
/** The text content (plain text or structured format like JSON) */
|
|
991
|
-
text: string;
|
|
992
|
-
annotations?: ContentAnnotations;
|
|
993
|
-
_meta?: Record<string, unknown>;
|
|
994
|
-
[key: string]: unknown;
|
|
995
|
-
} | {
|
|
996
|
-
/** Image content (base64-encoded) */
|
|
997
|
-
type: 'image';
|
|
998
|
-
/** Base64-encoded image data */
|
|
999
|
-
data: string;
|
|
1000
|
-
/** MIME type of the image (e.g., image/png, image/jpeg) */
|
|
1001
|
-
mimeType: string;
|
|
1002
|
-
annotations?: ContentAnnotations;
|
|
1003
|
-
_meta?: Record<string, unknown>;
|
|
1004
|
-
[key: string]: unknown;
|
|
1005
|
-
} | {
|
|
1006
|
-
/** Audio content (base64-encoded) */
|
|
1007
|
-
type: 'audio';
|
|
1008
|
-
/** Base64-encoded audio data */
|
|
1009
|
-
data: string;
|
|
1010
|
-
/** MIME type of the audio (e.g., audio/wav, audio/mp3) */
|
|
1011
|
-
mimeType: string;
|
|
1012
|
-
annotations?: ContentAnnotations;
|
|
1013
|
-
_meta?: Record<string, unknown>;
|
|
1014
|
-
[key: string]: unknown;
|
|
1015
|
-
} | {
|
|
1016
|
-
/** Embedded resource with full content (text or blob) */
|
|
1017
|
-
type: 'resource';
|
|
1018
|
-
/** Resource contents - either text or blob variant */
|
|
1019
|
-
resource: {
|
|
1020
|
-
uri: string;
|
|
1021
|
-
_meta?: Record<string, unknown>;
|
|
1022
|
-
[key: string]: unknown;
|
|
1023
|
-
} & ({
|
|
1024
|
-
text: string;
|
|
1025
|
-
mimeType?: string;
|
|
1026
|
-
} | {
|
|
1027
|
-
blob: string;
|
|
1028
|
-
mimeType: string;
|
|
1029
|
-
});
|
|
1030
|
-
annotations?: ContentAnnotations;
|
|
1031
|
-
_meta?: Record<string, unknown>;
|
|
1032
|
-
[key: string]: unknown;
|
|
1033
|
-
} | {
|
|
1034
|
-
/** Resource link (reference only - no embedded content) */
|
|
1035
|
-
type: 'resource_link';
|
|
1036
|
-
/** URI of the resource */
|
|
1037
|
-
uri: string;
|
|
1038
|
-
/** Human-readable name (required per MCP spec) */
|
|
1039
|
-
name: string;
|
|
1040
|
-
/** Optional description of what this resource represents */
|
|
1041
|
-
description?: string;
|
|
1042
|
-
/** MIME type of the resource, if known */
|
|
1043
|
-
mimeType?: string;
|
|
1044
|
-
annotations?: ContentAnnotations;
|
|
1045
|
-
_meta?: Record<string, unknown>;
|
|
1046
|
-
[key: string]: unknown;
|
|
1047
|
-
}>;
|
|
1048
|
-
isError?: boolean;
|
|
1049
|
-
structuredContent?: Record<string, unknown>;
|
|
1050
|
-
_meta?: Record<string, unknown>;
|
|
1051
|
-
[key: string]: unknown;
|
|
1052
|
-
};
|
|
1053
|
-
declare function createCustomMcpServer<Tools extends Record<string, {
|
|
1054
|
-
description: string;
|
|
1055
|
-
inputSchema: ZodObject<ZodRawShape>;
|
|
1056
|
-
handler: (args: Record<string, unknown>, extra: unknown) => Promise<MinimalCallToolResult>;
|
|
1057
|
-
annotations?: ToolAnnotations;
|
|
1058
|
-
}>>(config: {
|
|
1059
|
-
name: string;
|
|
1060
|
-
version?: string;
|
|
1061
|
-
tools: Tools;
|
|
1062
|
-
}): McpSdkServerConfigWithInstance;
|
|
1063
|
-
/**
|
|
1064
|
-
* Minimal per-call options passed to an AI SDK tool's `execute` function
|
|
1065
|
-
* when it is invoked through {@link createAiSdkMcpServer}.
|
|
1066
|
-
*
|
|
1067
|
-
* Note that the AI SDK's full `ToolCallOptions` (e.g. `messages`,
|
|
1068
|
-
* `experimental_context`) is not available here: the tool runs inside the
|
|
1069
|
-
* Claude Code CLI's MCP transport, outside the AI SDK call loop.
|
|
1070
|
-
*/
|
|
1071
|
-
type AiSdkToolExecuteOptions = {
|
|
1072
|
-
/**
|
|
1073
|
-
* Identifier of the MCP request that triggered this call, when available.
|
|
1074
|
-
*
|
|
1075
|
-
* Note: this is the MCP JSON-RPC request id (often a small integer like
|
|
1076
|
-
* `'42'`), not the model's `toolu_...` tool_use id, so it will not match
|
|
1077
|
-
* the `toolCallId` on the AI SDK's `tool-call`/`tool-result` stream parts.
|
|
1078
|
-
*/
|
|
1079
|
-
toolCallId?: string;
|
|
1080
|
-
/** Abort signal for the MCP request, when available. */
|
|
1081
|
-
abortSignal?: AbortSignal;
|
|
1082
|
-
};
|
|
1083
|
-
/**
|
|
1084
|
-
* Structural shape of an AI SDK tool (what the `ai` package's `tool()` helper
|
|
1085
|
-
* returns) as accepted by {@link createAiSdkMcpServer}. Deliberately
|
|
1086
|
-
* structurally typed so this package does not depend on the `ai` package.
|
|
1087
|
-
*
|
|
1088
|
-
* Constraints:
|
|
1089
|
-
* - `inputSchema` must be a Zod object schema (`z.object({...})`, Zod v3 or
|
|
1090
|
-
* v4) — the same schema you would pass to the `ai` package's `tool()`
|
|
1091
|
-
* helper. Schemas created with the AI SDK's `jsonSchema()` helper are not
|
|
1092
|
-
* supported because the Agent SDK's `tool()` requires a Zod shape.
|
|
1093
|
-
* - `execute` is required: only tools that execute locally can be bridged.
|
|
1094
|
-
*/
|
|
1095
|
-
type AiSdkLikeTool = {
|
|
1096
|
-
description?: string;
|
|
1097
|
-
/** A Zod object schema (`z.object({...})`), Zod v3 or v4. */
|
|
1098
|
-
inputSchema: unknown;
|
|
1099
|
-
/**
|
|
1100
|
-
* Tool implementation. Receives the validated input and a minimal options
|
|
1101
|
-
* object ({@link AiSdkToolExecuteOptions}).
|
|
1102
|
-
*
|
|
1103
|
-
* Optional in the type only to stay assignment-compatible with the AI
|
|
1104
|
-
* SDK's `Tool` type — {@link createAiSdkMcpServer} throws at creation time
|
|
1105
|
-
* if it is missing.
|
|
1106
|
-
*/
|
|
1107
|
-
execute?(input: never, options?: AiSdkToolExecuteOptions): PromiseLike<unknown> | unknown;
|
|
1108
|
-
};
|
|
1109
|
-
/**
|
|
1110
|
-
* Bridges AI SDK tool definitions (the `ai` package's `tool()` helper) into
|
|
1111
|
-
* an in-process SDK MCP server that the Claude Code CLI can execute.
|
|
1112
|
-
*
|
|
1113
|
-
* Why this helper exists: the Claude Code CLI executes its own tools, so AI
|
|
1114
|
-
* SDK tools passed to `generateText`/`streamText` via the `tools` option
|
|
1115
|
-
* cannot be auto-bridged by the provider — at the `LanguageModelV3` layer the
|
|
1116
|
-
* provider only receives tool *declarations* (name, description, JSON
|
|
1117
|
-
* schema); the `execute` functions live in the `ai` package layer and never
|
|
1118
|
-
* reach providers. This helper is the explicit alternative: pass your tools
|
|
1119
|
-
* here and wire the result into the `mcpServers` setting.
|
|
1120
|
-
*
|
|
1121
|
-
* Validation scope: the Agent SDK's `tool()` takes only the schema SHAPE and
|
|
1122
|
-
* validates incoming args against a default `z.object(shape)` — running
|
|
1123
|
-
* FIELD-LEVEL validation and transforms (the handler receives each field's
|
|
1124
|
-
* parsed `_output`) and STRIPPING unknown keys — before this handler runs. The
|
|
1125
|
-
* bridge does NOT re-parse on top of that: re-parsing the SDK's already-parsed
|
|
1126
|
-
* output against the original schema would re-run field transforms and would
|
|
1127
|
-
* outright reject any schema whose output type differs from its input (e.g.
|
|
1128
|
-
* `z.string().transform(v => v.length)`). Consequently OBJECT-LEVEL constructs
|
|
1129
|
-
* are NOT enforced by the bridge — `.refine()`/`.superRefine()` (cross-field
|
|
1130
|
-
* invariants) and `.strict()`/`.passthrough()`/`.catchall()` (unknown-key
|
|
1131
|
-
* modes) — so perform those checks inside `execute()`.
|
|
1132
|
-
*
|
|
1133
|
-
* Each tool's `execute` is called with the SDK-validated input and a minimal
|
|
1134
|
-
* options object ({@link AiSdkToolExecuteOptions}). String results pass
|
|
1135
|
-
* through as MCP text content; all other results are `JSON.stringify`'d.
|
|
1136
|
-
* Errors thrown (or rejections) become `isError: true` tool results instead
|
|
1137
|
-
* of crashing the CLI session. Results that cannot be serialized to JSON
|
|
1138
|
-
* (e.g. circular objects) also become `isError: true` results with a
|
|
1139
|
-
* serialization message, even though the tool itself succeeded.
|
|
1140
|
-
*
|
|
1141
|
-
* Tool results surface to the AI SDK as provider-executed dynamic tool parts
|
|
1142
|
-
* (`tool-call`/`tool-result` with `mcp__<serverName>__<toolName>` names), not
|
|
1143
|
-
* as executions of your local `tools` option.
|
|
1144
|
-
*
|
|
1145
|
-
* @param name - MCP server name. Tools are exposed to the CLI as
|
|
1146
|
-
* `mcp__<name>__<toolName>`.
|
|
1147
|
-
* @param tools - Map of tool name to AI SDK tool. Each tool must have an
|
|
1148
|
-
* `execute` function and a Zod object schema as its `inputSchema`
|
|
1149
|
-
* (`jsonSchema()`-based tools are rejected).
|
|
1150
|
-
* @returns An SDK MCP server config for the `mcpServers` setting.
|
|
1151
|
-
* @throws If a tool lacks an `execute` function or its `inputSchema` is not
|
|
1152
|
-
* a Zod object schema.
|
|
1153
|
-
*
|
|
1154
|
-
* @example
|
|
1155
|
-
* ```typescript
|
|
1156
|
-
* import { generateText, tool } from 'ai';
|
|
1157
|
-
* import { z } from 'zod';
|
|
1158
|
-
* import { claudeCode, createAiSdkMcpServer } from 'ai-sdk-provider-claude-code';
|
|
1159
|
-
*
|
|
1160
|
-
* const tools = {
|
|
1161
|
-
* add: tool({
|
|
1162
|
-
* description: 'Add two numbers',
|
|
1163
|
-
* inputSchema: z.object({ a: z.number(), b: z.number() }),
|
|
1164
|
-
* execute: async ({ a, b }) => ({ sum: a + b }),
|
|
1165
|
-
* }),
|
|
1166
|
-
* };
|
|
1167
|
-
*
|
|
1168
|
-
* const { text } = await generateText({
|
|
1169
|
-
* model: claudeCode('sonnet', {
|
|
1170
|
-
* mcpServers: { myTools: createAiSdkMcpServer('myTools', tools) },
|
|
1171
|
-
* // Tools are named mcp__<serverName>__<toolName>
|
|
1172
|
-
* allowedTools: ['mcp__myTools__add'],
|
|
1173
|
-
* }),
|
|
1174
|
-
* prompt: 'What is 2 + 3? Use the add tool.',
|
|
1175
|
-
* });
|
|
1176
|
-
* ```
|
|
1177
|
-
*/
|
|
1178
|
-
declare function createAiSdkMcpServer(name: string, tools: Record<string, AiSdkLikeTool>): McpSdkServerConfigWithInstance;
|
|
1179
|
-
|
|
1180
|
-
/**
|
|
1181
|
-
* Metadata associated with Claude Code SDK errors.
|
|
1182
|
-
* Provides additional context about command execution failures.
|
|
1183
|
-
*/
|
|
1184
|
-
interface ClaudeCodeErrorMetadata {
|
|
1185
|
-
/**
|
|
1186
|
-
* Error code from the CLI process (e.g., 'ENOENT', 'ETIMEDOUT').
|
|
1187
|
-
*/
|
|
1188
|
-
code?: string;
|
|
1189
|
-
/**
|
|
1190
|
-
* Exit code from the Claude Code SDK process.
|
|
1191
|
-
* Common codes:
|
|
1192
|
-
* - 401: Authentication error
|
|
1193
|
-
* - 1: General error
|
|
1194
|
-
*/
|
|
1195
|
-
exitCode?: number;
|
|
1196
|
-
/**
|
|
1197
|
-
* Standard error output from the CLI process.
|
|
1198
|
-
*/
|
|
1199
|
-
stderr?: string;
|
|
1200
|
-
/**
|
|
1201
|
-
* Excerpt from the prompt that caused the error.
|
|
1202
|
-
* Limited to first 200 characters for debugging.
|
|
1203
|
-
*/
|
|
1204
|
-
promptExcerpt?: string;
|
|
1205
|
-
}
|
|
1206
|
-
/**
|
|
1207
|
-
* Creates an APICallError with Claude Code specific metadata.
|
|
1208
|
-
* Used for general CLI execution errors.
|
|
1209
|
-
*
|
|
1210
|
-
* @param options - Error details and metadata
|
|
1211
|
-
* @param options.message - Human-readable error message
|
|
1212
|
-
* @param options.code - Error code from the CLI process
|
|
1213
|
-
* @param options.exitCode - Exit code from the CLI
|
|
1214
|
-
* @param options.stderr - Standard error output
|
|
1215
|
-
* @param options.promptExcerpt - Excerpt of the prompt that caused the error
|
|
1216
|
-
* @param options.isRetryable - Whether the error is potentially retryable
|
|
1217
|
-
* @returns An APICallError instance with Claude Code metadata
|
|
1218
|
-
*
|
|
1219
|
-
* @example
|
|
1220
|
-
* ```typescript
|
|
1221
|
-
* throw createAPICallError({
|
|
1222
|
-
* message: 'Claude Code SDK failed',
|
|
1223
|
-
* code: 'ENOENT',
|
|
1224
|
-
* isRetryable: true
|
|
1225
|
-
* });
|
|
1226
|
-
* ```
|
|
1227
|
-
*/
|
|
1228
|
-
declare function createAPICallError({ message, code, exitCode, stderr, promptExcerpt, isRetryable, }: ClaudeCodeErrorMetadata & {
|
|
1229
|
-
message: string;
|
|
1230
|
-
isRetryable?: boolean;
|
|
1231
|
-
}): APICallError;
|
|
1232
|
-
/**
|
|
1233
|
-
* Creates an authentication error for Claude Code SDK login failures.
|
|
1234
|
-
*
|
|
1235
|
-
* @param options - Error configuration
|
|
1236
|
-
* @param options.message - Error message describing the authentication failure
|
|
1237
|
-
* @returns A LoadAPIKeyError instance
|
|
1238
|
-
*
|
|
1239
|
-
* @example
|
|
1240
|
-
* ```typescript
|
|
1241
|
-
* throw createAuthenticationError({
|
|
1242
|
-
* message: 'Please run "claude auth login" to authenticate'
|
|
1243
|
-
* });
|
|
1244
|
-
* ```
|
|
1245
|
-
*/
|
|
1246
|
-
declare function createAuthenticationError({ message, stderr, }: {
|
|
1247
|
-
message: string;
|
|
1248
|
-
stderr?: string;
|
|
1249
|
-
}): LoadAPIKeyError;
|
|
1250
|
-
/**
|
|
1251
|
-
* Creates a timeout error for Claude Code SDK operations.
|
|
1252
|
-
*
|
|
1253
|
-
* @param options - Timeout error details
|
|
1254
|
-
* @param options.message - Error message describing the timeout
|
|
1255
|
-
* @param options.promptExcerpt - Excerpt of the prompt that timed out
|
|
1256
|
-
* @param options.timeoutMs - Timeout duration in milliseconds
|
|
1257
|
-
* @returns An APICallError instance configured as a timeout error
|
|
1258
|
-
*
|
|
1259
|
-
* @example
|
|
1260
|
-
* ```typescript
|
|
1261
|
-
* throw createTimeoutError({
|
|
1262
|
-
* message: 'Request timed out after 2 minutes',
|
|
1263
|
-
* timeoutMs: 120000
|
|
1264
|
-
* });
|
|
1265
|
-
* ```
|
|
1266
|
-
*/
|
|
1267
|
-
declare function createTimeoutError({ message, stderr, promptExcerpt, timeoutMs, }: {
|
|
1268
|
-
message: string;
|
|
1269
|
-
stderr?: string;
|
|
1270
|
-
promptExcerpt?: string;
|
|
1271
|
-
timeoutMs?: number;
|
|
1272
|
-
}): APICallError;
|
|
1273
|
-
/**
|
|
1274
|
-
* Checks if an error is an authentication error.
|
|
1275
|
-
* Returns true for LoadAPIKeyError instances or APICallError with exit code 401.
|
|
1276
|
-
*
|
|
1277
|
-
* @param error - The error to check
|
|
1278
|
-
* @returns True if the error is an authentication error
|
|
1279
|
-
*
|
|
1280
|
-
* @example
|
|
1281
|
-
* ```typescript
|
|
1282
|
-
* try {
|
|
1283
|
-
* await model.generate(...);
|
|
1284
|
-
* } catch (error) {
|
|
1285
|
-
* if (isAuthenticationError(error)) {
|
|
1286
|
-
* console.log('Please authenticate with Claude Code SDK');
|
|
1287
|
-
* }
|
|
1288
|
-
* }
|
|
1289
|
-
* ```
|
|
1290
|
-
*/
|
|
1291
|
-
declare function isAuthenticationError(error: unknown): boolean;
|
|
1292
|
-
/**
|
|
1293
|
-
* Checks if an error is a timeout error.
|
|
1294
|
-
* Returns true for APICallError instances with code 'TIMEOUT'.
|
|
1295
|
-
*
|
|
1296
|
-
* @param error - The error to check
|
|
1297
|
-
* @returns True if the error is a timeout error
|
|
1298
|
-
*
|
|
1299
|
-
* @example
|
|
1300
|
-
* ```typescript
|
|
1301
|
-
* try {
|
|
1302
|
-
* await model.generate(...);
|
|
1303
|
-
* } catch (error) {
|
|
1304
|
-
* if (isTimeoutError(error)) {
|
|
1305
|
-
* console.log('Request timed out, consider retrying');
|
|
1306
|
-
* }
|
|
1307
|
-
* }
|
|
1308
|
-
* ```
|
|
1309
|
-
*/
|
|
1310
|
-
declare function isTimeoutError(error: unknown): boolean;
|
|
1311
|
-
/**
|
|
1312
|
-
* Extracts Claude Code error metadata from an error object.
|
|
1313
|
-
*
|
|
1314
|
-
* @param error - The error to extract metadata from
|
|
1315
|
-
* @returns The error metadata if available, undefined otherwise
|
|
1316
|
-
*
|
|
1317
|
-
* @example
|
|
1318
|
-
* ```typescript
|
|
1319
|
-
* try {
|
|
1320
|
-
* await model.generate(...);
|
|
1321
|
-
* } catch (error) {
|
|
1322
|
-
* const metadata = getErrorMetadata(error);
|
|
1323
|
-
* if (metadata?.exitCode === 401) {
|
|
1324
|
-
* console.log('Authentication required');
|
|
1325
|
-
* }
|
|
1326
|
-
* }
|
|
1327
|
-
* ```
|
|
1328
|
-
*/
|
|
1329
|
-
declare function getErrorMetadata(error: unknown): ClaudeCodeErrorMetadata | undefined;
|
|
1330
|
-
|
|
1331
|
-
export { type AiSdkLikeTool, type AiSdkToolExecuteOptions, type ClaudeCodeErrorMetadata, ClaudeCodeLanguageModel, type ClaudeCodeLanguageModelOptions, type ClaudeCodeModelId, type ClaudeCodeProvider, type ClaudeCodeProviderSettings, type ClaudeCodeSettings, type Logger, type MessageInjector, type MinimalCallToolResult, type ToolAnnotations, claudeCode, createAPICallError, createAiSdkMcpServer, createAuthenticationError, createClaudeCode, createCustomMcpServer, createTimeoutError, getErrorMetadata, isAuthenticationError, isTimeoutError };
|