ai-sdk-provider-claude-code 3.4.3 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { LanguageModelV3, ProviderV3, APICallError, LoadAPIKeyError } from '@ai-sdk/provider';
2
- import { ThinkingConfig, PermissionMode, SdkBeta, SdkPluginConfig, SandboxSettings, Options, McpServerConfig, CanUseTool, AgentMcpServerSpec, SpawnOptions, SpawnedProcess, Query, SdkMcpToolDefinition, McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk';
3
- export { AgentMcpServerSpec, CanUseTool, HookCallback, HookCallbackMatcher, HookEvent, HookInput, HookJSONOutput, McpSdkServerConfigWithInstance, McpServerConfig, OutputFormat, PermissionBehavior, PermissionResult, PermissionRuleValue, PermissionUpdate, PostToolUseHookInput, PreToolUseHookInput, Query, SessionEndHookInput, SessionStartHookInput, SpawnOptions, SpawnedProcess, TaskCompletedHookInput, TeammateIdleHookInput, ThinkingAdaptive, ThinkingConfig, ThinkingDisabled, ThinkingEnabled, UserPromptSubmitHookInput, createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
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
4
  import { ZodObject, ZodRawShape } from 'zod';
5
5
 
6
6
  type StreamingInputMode = 'auto' | 'always' | 'off';
@@ -72,13 +72,15 @@ interface ClaudeCodeSettings {
72
72
  /**
73
73
  * Agent SDK system prompt configuration. Preferred over legacy fields.
74
74
  * - string: custom system prompt
75
- * - preset object: Claude Code preset, with optional append
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)
76
82
  */
77
- systemPrompt?: string | {
78
- type: 'preset';
79
- preset: 'claude_code';
80
- append?: string;
81
- };
83
+ systemPrompt?: Options['systemPrompt'];
82
84
  /**
83
85
  * Maximum number of turns for the conversation
84
86
  */
@@ -106,11 +108,12 @@ interface ClaudeCodeSettings {
106
108
  * - `'low'` — Minimal thinking, fastest responses
107
109
  * - `'medium'` — Moderate thinking
108
110
  * - `'high'` — Deep reasoning (default)
111
+ * - `'xhigh'` — Extra-high effort
109
112
  * - `'max'` — Maximum effort (Opus 4.6 only)
110
113
  *
111
114
  * @see https://docs.anthropic.com/en/docs/build-with-claude/effort
112
115
  */
113
- effort?: 'low' | 'medium' | 'high' | 'max';
116
+ effort?: EffortLevel;
114
117
  /**
115
118
  * Enable prompt suggestions. When true, the agent emits a predicted
116
119
  * next user prompt after each turn (arrives after the result message).
@@ -130,7 +133,11 @@ interface ClaudeCodeSettings {
130
133
  */
131
134
  executableArgs?: string[];
132
135
  /**
133
- * Permission mode for tool usage
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.
134
141
  * @default 'default'
135
142
  */
136
143
  permissionMode?: PermissionMode;
@@ -149,6 +156,13 @@ interface ClaudeCodeSettings {
149
156
  /**
150
157
  * Use a specific session ID for this query.
151
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).
152
166
  */
153
167
  sessionId?: string;
154
168
  /**
@@ -187,19 +201,103 @@ interface ClaudeCodeSettings {
187
201
  resumeSessionAt?: string;
188
202
  /**
189
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.
190
209
  */
191
210
  sandbox?: SandboxSettings;
192
211
  /**
193
212
  * Tool configuration (array of tool names or Claude Code preset).
194
213
  */
195
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;
196
288
  /**
197
289
  * MCP server configuration
198
290
  */
199
291
  mcpServers?: Record<string, McpServerConfig>;
200
292
  /**
201
293
  * Filesystem settings sources to load (CLAUDE.md, settings.json, etc.)
202
- * When omitted, the Agent SDK loads no filesystem settings.
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).
203
301
  *
204
302
  * Required for Skills support - skills are loaded from these sources.
205
303
  * @example ['user', 'project']
@@ -208,6 +306,17 @@ interface ClaudeCodeSettings {
208
306
  /**
209
307
  * Hook callbacks for lifecycle events (e.g., PreToolUse, PostToolUse).
210
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`.
211
320
  */
212
321
  hooks?: Partial<Record<string, Array<{
213
322
  matcher?: string;
@@ -216,8 +325,45 @@ interface ClaudeCodeSettings {
216
325
  /**
217
326
  * Dynamic permission callback invoked before a tool is executed.
218
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.
219
336
  */
220
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[];
221
367
  /**
222
368
  * Controls whether to send streaming input to the SDK (enables canUseTool).
223
369
  * - 'auto' (default): stream when canUseTool is provided
@@ -260,7 +406,14 @@ interface ClaudeCodeSettings {
260
406
  */
261
407
  logger?: Logger | false;
262
408
  /**
263
- * Environment variables to set
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.
264
417
  */
265
418
  env?: Record<string, string | undefined>;
266
419
  /**
@@ -269,29 +422,24 @@ interface ClaudeCodeSettings {
269
422
  additionalDirectories?: string[];
270
423
  /**
271
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.
272
430
  */
273
- agents?: Record<string, {
274
- /** Natural language description of when to use this agent */
275
- description: string;
276
- /** Array of allowed tool names. If omitted, inherits all tools from parent */
277
- tools?: string[];
278
- /** Array of tool names to explicitly disallow for this agent */
279
- disallowedTools?: string[];
280
- /** The agent's system prompt */
281
- prompt: string;
282
- /** Model to use for this agent. If omitted or 'inherit', uses the main model */
283
- model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
284
- /** MCP servers available to this agent (server names or inline configs) */
285
- mcpServers?: AgentMcpServerSpec[];
286
- /** Experimental: Critical reminder added to system prompt */
287
- criticalSystemReminder_EXPERIMENTAL?: string;
288
- }>;
431
+ agents?: Record<string, AgentDefinition>;
289
432
  /**
290
433
  * Include partial message events from the SDK stream.
291
434
  */
292
435
  includePartialMessages?: boolean;
293
436
  /**
294
- * Model to use if primary fails.
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.
295
443
  */
296
444
  fallbackModel?: string;
297
445
  /**
@@ -317,6 +465,45 @@ interface ClaudeCodeSettings {
317
465
  * @default true
318
466
  */
319
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;
320
507
  /**
321
508
  * Custom function to spawn the Claude Code process.
322
509
  * Use this to run Claude Code in VMs, containers, or remote environments.
@@ -373,6 +560,34 @@ interface ClaudeCodeSettings {
373
560
  * ```
374
561
  */
375
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;
376
591
  }
377
592
  /**
378
593
  * Controller for injecting messages into an active Claude Code session.
@@ -494,6 +709,7 @@ declare class ClaudeCodeLanguageModel implements LanguageModelV3 {
494
709
  private static readonly MAX_TOOL_INPUT_SIZE;
495
710
  private static readonly MAX_TOOL_INPUT_WARN;
496
711
  private static readonly MAX_DELTA_CALC_SIZE;
712
+ private static readonly PROMPT_SUGGESTION_DRAIN_TIMEOUT_MS;
497
713
  readonly modelId: ClaudeCodeModelId;
498
714
  readonly settings: ClaudeCodeSettings;
499
715
  private sessionId?;
@@ -505,18 +721,136 @@ declare class ClaudeCodeLanguageModel implements LanguageModelV3 {
505
721
  private getModel;
506
722
  private getSanitizedSdkOptions;
507
723
  private getEffectiveResume;
508
- private extractTextAndThinking;
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;
509
770
  private extractToolUses;
510
771
  private extractToolResults;
511
772
  private extractToolErrors;
512
773
  private serializeToolInput;
513
774
  private checkInputSize;
514
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;
515
813
  private generateAllWarnings;
516
814
  private createQueryOptions;
517
815
  private handleClaudeCodeError;
518
816
  private setSessionId;
519
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;
520
854
  doGenerate(options: Parameters<LanguageModelV3['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV3['doGenerate']>>>;
521
855
  doStream(options: Parameters<LanguageModelV3['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV3['doStream']>>>;
522
856
  private serializeWarningsForMetadata;
@@ -726,6 +1060,122 @@ declare function createCustomMcpServer<Tools extends Record<string, {
726
1060
  version?: string;
727
1061
  tools: Tools;
728
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;
729
1179
 
730
1180
  /**
731
1181
  * Metadata associated with Claude Code SDK errors.
@@ -876,4 +1326,4 @@ declare function isTimeoutError(error: unknown): boolean;
876
1326
  */
877
1327
  declare function getErrorMetadata(error: unknown): ClaudeCodeErrorMetadata | undefined;
878
1328
 
879
- export { type ClaudeCodeErrorMetadata, ClaudeCodeLanguageModel, type ClaudeCodeLanguageModelOptions, type ClaudeCodeModelId, type ClaudeCodeProvider, type ClaudeCodeProviderSettings, type ClaudeCodeSettings, type Logger, type MessageInjector, type MinimalCallToolResult, type ToolAnnotations, claudeCode, createAPICallError, createAuthenticationError, createClaudeCode, createCustomMcpServer, createTimeoutError, getErrorMetadata, isAuthenticationError, isTimeoutError };
1329
+ 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 };