@anthropic-ai/claude-agent-sdk 0.1.75 → 0.1.77

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.
@@ -1,668 +1,19 @@
1
- import type { MessageParam as APIUserMessage } from '@anthropic-ai/sdk/resources';
2
- import type { BetaMessage as APIAssistantMessage, BetaUsage as Usage, BetaRawMessageStreamEvent as RawMessageStreamEvent } from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs';
3
- import type { UUID } from 'crypto';
4
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
5
- import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
- import { type z, type ZodRawShape, type ZodObject } from 'zod';
7
- import type { SandboxSettings, SandboxNetworkConfig, SandboxIgnoreViolations } from './sandboxTypes.js';
8
- import type { SpawnedProcess, SpawnOptions } from '../transport/processTransportTypes.js';
9
- import type { Transport } from '../transport/transport.js';
10
- export type { SandboxSettings, SandboxNetworkConfig, SandboxIgnoreViolations };
11
- export type NonNullableUsage = {
12
- [K in keyof Usage]: NonNullable<Usage[K]>;
13
- };
14
- export type ModelUsage = {
15
- inputTokens: number;
16
- outputTokens: number;
17
- cacheReadInputTokens: number;
18
- cacheCreationInputTokens: number;
19
- webSearchRequests: number;
20
- costUSD: number;
21
- contextWindow: number;
22
- };
23
- export type OutputFormatType = 'json_schema';
24
- export type BaseOutputFormat = {
25
- type: OutputFormatType;
26
- };
27
- export type JsonSchemaOutputFormat = BaseOutputFormat & {
28
- type: 'json_schema';
29
- schema: Record<string, unknown>;
30
- };
31
- export type OutputFormat = JsonSchemaOutputFormat;
32
- export type ApiKeySource = 'user' | 'project' | 'org' | 'temporary';
33
- export type ConfigScope = 'local' | 'user' | 'project';
34
- /**
35
- * Allowed beta headers that can be passed via SDK options.
36
- */
37
- export type SdkBeta = 'context-1m-2025-08-07';
38
- export type McpStdioServerConfig = {
39
- type?: 'stdio';
40
- command: string;
41
- args?: string[];
42
- env?: Record<string, string>;
43
- };
44
- export type McpSSEServerConfig = {
45
- type: 'sse';
46
- url: string;
47
- headers?: Record<string, string>;
48
- };
49
- export type McpHttpServerConfig = {
50
- type: 'http';
51
- url: string;
52
- headers?: Record<string, string>;
53
- };
54
- export type McpSdkServerConfig = {
55
- type: 'sdk';
56
- name: string;
57
- };
58
- export type McpSdkServerConfigWithInstance = McpSdkServerConfig & {
59
- instance: McpServer;
60
- };
61
- export type McpServerConfig = McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfigWithInstance;
62
- export type McpServerConfigForProcessTransport = McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig;
63
- type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
64
- export type PermissionBehavior = 'allow' | 'deny' | 'ask';
65
- export type PermissionUpdate = {
66
- type: 'addRules';
67
- rules: PermissionRuleValue[];
68
- behavior: PermissionBehavior;
69
- destination: PermissionUpdateDestination;
70
- } | {
71
- type: 'replaceRules';
72
- rules: PermissionRuleValue[];
73
- behavior: PermissionBehavior;
74
- destination: PermissionUpdateDestination;
75
- } | {
76
- type: 'removeRules';
77
- rules: PermissionRuleValue[];
78
- behavior: PermissionBehavior;
79
- destination: PermissionUpdateDestination;
80
- } | {
81
- type: 'setMode';
82
- mode: PermissionMode;
83
- destination: PermissionUpdateDestination;
84
- } | {
85
- type: 'addDirectories';
86
- directories: string[];
87
- destination: PermissionUpdateDestination;
88
- } | {
89
- type: 'removeDirectories';
90
- directories: string[];
91
- destination: PermissionUpdateDestination;
92
- };
93
- export type PermissionResult = {
94
- behavior: 'allow';
95
- /**
96
- * Updated tool input to use, if any changes are needed.
97
- *
98
- * For example if the user was given the option to update the tool use
99
- * input before approving, then this would be the updated input which
100
- * would be executed by the tool.
101
- */
102
- updatedInput: Record<string, unknown>;
103
- /**
104
- * Permissions updates to be applied as part of accepting this tool use.
105
- *
106
- * Typically this is used as part of the 'always allow' flow and these
107
- * permission updates are from the `suggestions` field from the
108
- * CanUseTool callback.
109
- *
110
- * It is recommended that you use these suggestions rather than
111
- * attempting to re-derive them from the tool use input, as the
112
- * suggestions may include other permission changes such as adding
113
- * directories or incorporate complex tool-use logic such as bash
114
- * commands.
115
- */
116
- updatedPermissions?: PermissionUpdate[];
117
- /**
118
- * The tool use ID. Supplied and used internally.
119
- */
120
- toolUseID?: string;
121
- } | {
122
- behavior: 'deny';
123
- /**
124
- * Message indicating the reason for denial, or guidance of what the
125
- * model should do instead.
126
- */
127
- message: string;
128
- /**
129
- * If true, interrupt execution and do not continue.
130
- *
131
- * Typically this should be set to true when the user says 'no' with no
132
- * further guidance. Leave unset or false if the user provides guidance
133
- * which the model should incorporate and continue.
134
- */
135
- interrupt?: boolean;
136
- /**
137
- * The tool use ID. Supplied and used internally.
138
- */
139
- toolUseID?: string;
140
- };
141
- export type PermissionRuleValue = {
142
- toolName: string;
143
- ruleContent?: string;
144
- };
145
- export type CanUseTool = (toolName: string, input: Record<string, unknown>, options: {
146
- /** Signaled if the operation should be aborted. */
147
- signal: AbortSignal;
148
- /**
149
- * Suggestions for updating permissions so that the user will not be
150
- * prompted again for this tool during this session.
151
- *
152
- * Typically if presenting the user an option 'always allow' or similar,
153
- * then this full set of suggestions should be returned as the
154
- * `updatedPermissions` in the PermissionResult.
155
- */
156
- suggestions?: PermissionUpdate[];
157
- /**
158
- * The file path that triggered the permission request, if applicable.
159
- * For example, when a Bash command tries to access a path outside allowed directories.
160
- */
161
- blockedPath?: string;
162
- /** Explains why this permission request was triggered. */
163
- decisionReason?: string;
164
- /**
165
- * Unique identifier for this specific tool call within the assistant message.
166
- * Multiple tool calls in the same assistant message will have different toolUseIDs.
167
- */
168
- toolUseID: string;
169
- /** If running within the context of a sub-agent, the sub-agent's ID. */
170
- agentID?: string;
171
- }) => Promise<PermissionResult>;
172
- export declare const HOOK_EVENTS: readonly ["PreToolUse", "PostToolUse", "PostToolUseFailure", "Notification", "UserPromptSubmit", "SessionStart", "SessionEnd", "Stop", "SubagentStart", "SubagentStop", "PreCompact", "PermissionRequest"];
173
- export type HookEvent = (typeof HOOK_EVENTS)[number];
174
- export type HookCallback = (input: HookInput, toolUseID: string | undefined, options: {
175
- signal: AbortSignal;
176
- }) => Promise<HookJSONOutput>;
177
- export interface HookCallbackMatcher {
178
- matcher?: string;
179
- hooks: HookCallback[];
180
- /** Timeout in seconds for all hooks in this matcher */
181
- timeout?: number;
182
- }
183
- export type BaseHookInput = {
184
- session_id: string;
185
- transcript_path: string;
186
- cwd: string;
187
- permission_mode?: string;
188
- };
189
- export type PreToolUseHookInput = BaseHookInput & {
190
- hook_event_name: 'PreToolUse';
191
- tool_name: string;
192
- tool_input: unknown;
193
- tool_use_id: string;
194
- };
195
- export type PermissionRequestHookInput = BaseHookInput & {
196
- hook_event_name: 'PermissionRequest';
197
- tool_name: string;
198
- tool_input: unknown;
199
- permission_suggestions?: PermissionUpdate[];
200
- };
201
- export type PostToolUseHookInput = BaseHookInput & {
202
- hook_event_name: 'PostToolUse';
203
- tool_name: string;
204
- tool_input: unknown;
205
- tool_response: unknown;
206
- tool_use_id: string;
207
- };
208
- export type PostToolUseFailureHookInput = BaseHookInput & {
209
- hook_event_name: 'PostToolUseFailure';
210
- tool_name: string;
211
- tool_input: unknown;
212
- tool_use_id: string;
213
- error: string;
214
- is_interrupt?: boolean;
215
- };
216
- export type NotificationHookInput = BaseHookInput & {
217
- hook_event_name: 'Notification';
218
- message: string;
219
- title?: string;
220
- notification_type: string;
221
- };
222
- export type UserPromptSubmitHookInput = BaseHookInput & {
223
- hook_event_name: 'UserPromptSubmit';
224
- prompt: string;
225
- };
226
- export type SessionStartHookInput = BaseHookInput & {
227
- hook_event_name: 'SessionStart';
228
- source: 'startup' | 'resume' | 'clear' | 'compact';
229
- };
230
- export type StopHookInput = BaseHookInput & {
231
- hook_event_name: 'Stop';
232
- stop_hook_active: boolean;
233
- };
234
- export type SubagentStartHookInput = BaseHookInput & {
235
- hook_event_name: 'SubagentStart';
236
- agent_id: string;
237
- agent_type: string;
238
- };
239
- export type SubagentStopHookInput = BaseHookInput & {
240
- hook_event_name: 'SubagentStop';
241
- stop_hook_active: boolean;
242
- agent_id: string;
243
- agent_transcript_path: string;
244
- };
245
- export type PreCompactHookInput = BaseHookInput & {
246
- hook_event_name: 'PreCompact';
247
- trigger: 'manual' | 'auto';
248
- custom_instructions: string | null;
249
- };
250
- export declare const EXIT_REASONS: string[];
251
- export type ExitReason = (typeof EXIT_REASONS)[number];
252
- export type SessionEndHookInput = BaseHookInput & {
253
- hook_event_name: 'SessionEnd';
254
- reason: ExitReason;
255
- };
256
- export type HookInput = PreToolUseHookInput | PostToolUseHookInput | PostToolUseFailureHookInput | NotificationHookInput | UserPromptSubmitHookInput | SessionStartHookInput | SessionEndHookInput | StopHookInput | SubagentStartHookInput | SubagentStopHookInput | PreCompactHookInput | PermissionRequestHookInput;
257
- export type AsyncHookJSONOutput = {
258
- async: true;
259
- asyncTimeout?: number;
260
- };
261
- export type SyncHookJSONOutput = {
262
- continue?: boolean;
263
- suppressOutput?: boolean;
264
- stopReason?: string;
265
- decision?: 'approve' | 'block';
266
- systemMessage?: string;
267
- reason?: string;
268
- hookSpecificOutput?: {
269
- hookEventName: 'PreToolUse';
270
- permissionDecision?: 'allow' | 'deny' | 'ask';
271
- permissionDecisionReason?: string;
272
- updatedInput?: Record<string, unknown>;
273
- } | {
274
- hookEventName: 'UserPromptSubmit';
275
- additionalContext?: string;
276
- } | {
277
- hookEventName: 'SessionStart';
278
- additionalContext?: string;
279
- } | {
280
- hookEventName: 'SubagentStart';
281
- additionalContext?: string;
282
- } | {
283
- hookEventName: 'PostToolUse';
284
- additionalContext?: string;
285
- updatedMCPToolOutput?: unknown;
286
- } | {
287
- hookEventName: 'PostToolUseFailure';
288
- additionalContext?: string;
289
- } | {
290
- hookEventName: 'PermissionRequest';
291
- decision: {
292
- behavior: 'allow';
293
- updatedInput?: Record<string, unknown>;
294
- updatedPermissions?: PermissionUpdate[];
295
- } | {
296
- behavior: 'deny';
297
- message?: string;
298
- interrupt?: boolean;
299
- };
300
- };
301
- };
302
- export type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;
303
- /**
304
- * Permission mode for controlling how tool executions are handled.
305
- * - `'default'` - Standard behavior, prompts for dangerous operations
306
- * - `'acceptEdits'` - Auto-accept file edit operations
307
- * - `'bypassPermissions'` - Bypass all permission checks (requires `allowDangerouslySkipPermissions`)
308
- * - `'plan'` - Planning mode, no actual tool execution
309
- * - `'delegate'` - Delegate mode, restricts team leader to only Teammate and Task tools
310
- * - `'dontAsk'` - Don't prompt for permissions, deny if not pre-approved
311
- */
312
- export type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'delegate' | 'dontAsk';
313
- /**
314
- * Information about an available skill (invoked via /command syntax).
315
- */
316
- export type SlashCommand = {
317
- /** Skill name (without the leading slash) */
318
- name: string;
319
- /** Description of what the skill does */
320
- description: string;
321
- /** Hint for skill arguments (e.g., "<file>") */
322
- argumentHint: string;
323
- };
324
- /**
325
- * Information about an available model.
326
- */
327
- export type ModelInfo = {
328
- /** Model identifier to use in API calls */
329
- value: string;
330
- /** Human-readable display name */
331
- displayName: string;
332
- /** Description of the model's capabilities */
333
- description: string;
334
- };
335
- /** Information about the logged in user's account. */
336
- export type AccountInfo = {
337
- email?: string;
338
- organization?: string;
339
- subscriptionType?: string;
340
- tokenSource?: string;
341
- apiKeySource?: string;
342
- };
343
1
  /**
344
- * Status information for an MCP server connection.
345
- */
346
- export type McpServerStatus = {
347
- /** Server name as configured */
348
- name: string;
349
- /** Current connection status */
350
- status: 'connected' | 'failed' | 'needs-auth' | 'pending';
351
- /** Server information (available when connected) */
352
- serverInfo?: {
353
- name: string;
354
- version: string;
355
- };
356
- };
357
- /**
358
- * Result of a setMcpServers operation.
359
- */
360
- export type McpSetServersResult = {
361
- /** Names of servers that were added */
362
- added: string[];
363
- /** Names of servers that were removed */
364
- removed: string[];
365
- /** Map of server names to error messages for servers that failed to connect */
366
- errors: Record<string, string>;
367
- };
368
- type SDKUserMessageContent = {
369
- type: 'user';
370
- message: APIUserMessage;
371
- parent_tool_use_id: string | null;
372
- /**
373
- * True if this is a 'synthetic' user message which did not originate from
374
- * the user directly, but instead was generated by the system.
375
- */
376
- isSynthetic?: boolean;
377
- /**
378
- * If present, the JSON result of a tool use that this user message is
379
- * responding to. This is provided to make it easier for applications to
380
- * present the tool result in a formatted way. The model only receives
381
- * the content within the user message.
382
- * The specific format is tool-dependent.
383
- */
384
- tool_use_result?: unknown;
385
- };
386
- export type SDKUserMessage = SDKUserMessageContent & {
387
- uuid?: UUID;
388
- session_id: string;
389
- };
390
- export type SDKUserMessageReplay = SDKUserMessageContent & {
391
- uuid: UUID;
392
- session_id: string;
393
- /**
394
- * True if this is a replay/acknowledgment of a user message that was already
395
- * added to the messages array. Used internally to prevent duplicate messages.
396
- */
397
- isReplay: true;
398
- };
399
- export type SDKAssistantMessageError = 'authentication_failed' | 'billing_error' | 'rate_limit' | 'invalid_request' | 'server_error' | 'unknown';
400
- export type SDKAssistantMessage = {
401
- type: 'assistant';
402
- message: APIAssistantMessage;
403
- parent_tool_use_id: string | null;
404
- error?: SDKAssistantMessageError;
405
- uuid: UUID;
406
- session_id: string;
407
- };
408
- export type SDKPermissionDenial = {
409
- tool_name: string;
410
- tool_use_id: string;
411
- tool_input: Record<string, unknown>;
412
- };
413
- export type SDKResultMessage = {
414
- type: 'result';
415
- subtype: 'success';
416
- duration_ms: number;
417
- duration_api_ms: number;
418
- is_error: boolean;
419
- num_turns: number;
420
- result: string;
421
- total_cost_usd: number;
422
- usage: NonNullableUsage;
423
- modelUsage: {
424
- [modelName: string]: ModelUsage;
425
- };
426
- permission_denials: SDKPermissionDenial[];
427
- structured_output?: unknown;
428
- uuid: UUID;
429
- session_id: string;
430
- } | {
431
- type: 'result';
432
- subtype: 'error_during_execution' | 'error_max_turns' | 'error_max_budget_usd' | 'error_max_structured_output_retries';
433
- duration_ms: number;
434
- duration_api_ms: number;
435
- is_error: boolean;
436
- num_turns: number;
437
- total_cost_usd: number;
438
- usage: NonNullableUsage;
439
- modelUsage: {
440
- [modelName: string]: ModelUsage;
441
- };
442
- permission_denials: SDKPermissionDenial[];
443
- errors: string[];
444
- uuid: UUID;
445
- session_id: string;
446
- };
447
- export type SDKSystemMessage = {
448
- type: 'system';
449
- subtype: 'init';
450
- agents?: string[];
451
- apiKeySource: ApiKeySource;
452
- betas?: string[];
453
- claude_code_version: string;
454
- cwd: string;
455
- tools: string[];
456
- mcp_servers: {
457
- name: string;
458
- status: string;
459
- }[];
460
- model: string;
461
- permissionMode: PermissionMode;
462
- slash_commands: string[];
463
- output_style: string;
464
- skills: string[];
465
- plugins: {
466
- name: string;
467
- path: string;
468
- }[];
469
- uuid: UUID;
470
- session_id: string;
471
- };
472
- export type SDKPartialAssistantMessage = {
473
- type: 'stream_event';
474
- event: RawMessageStreamEvent;
475
- parent_tool_use_id: string | null;
476
- uuid: UUID;
477
- session_id: string;
478
- };
479
- export type SDKCompactBoundaryMessage = {
480
- type: 'system';
481
- subtype: 'compact_boundary';
482
- compact_metadata: {
483
- trigger: 'manual' | 'auto';
484
- pre_tokens: number;
485
- };
486
- uuid: UUID;
487
- session_id: string;
488
- };
489
- export type SDKStatus = 'compacting' | null;
490
- export type SDKStatusMessage = {
491
- type: 'system';
492
- subtype: 'status';
493
- status: SDKStatus;
494
- uuid: UUID;
495
- session_id: string;
496
- };
497
- export type SDKHookResponseMessage = {
498
- type: 'system';
499
- subtype: 'hook_response';
500
- hook_name: string;
501
- hook_event: string;
502
- stdout: string;
503
- stderr: string;
504
- exit_code?: number;
505
- uuid: UUID;
506
- session_id: string;
507
- };
508
- export type SDKToolProgressMessage = {
509
- type: 'tool_progress';
510
- tool_use_id: string;
511
- tool_name: string;
512
- parent_tool_use_id: string | null;
513
- elapsed_time_seconds: number;
514
- uuid: UUID;
515
- session_id: string;
516
- };
517
- export type SDKAuthStatusMessage = {
518
- type: 'auth_status';
519
- isAuthenticating: boolean;
520
- output: string[];
521
- error?: string;
522
- uuid: UUID;
523
- session_id: string;
524
- };
525
- export type SDKMessage = SDKAssistantMessage | SDKUserMessage | SDKUserMessageReplay | SDKResultMessage | SDKSystemMessage | SDKPartialAssistantMessage | SDKCompactBoundaryMessage | SDKStatusMessage | SDKHookResponseMessage | SDKToolProgressMessage | SDKAuthStatusMessage;
526
- export interface Query extends AsyncGenerator<SDKMessage, void> {
527
- /**
528
- * Control Requests
529
- * The following methods are control requests, and are only supported when
530
- * streaming input/output is used.
531
- */
532
- /**
533
- * Interrupt the current query execution. The query will stop processing
534
- * and return control to the caller.
535
- */
536
- interrupt(): Promise<void>;
537
- /**
538
- * Change the permission mode for the current session.
539
- * Only available in streaming input mode.
540
- *
541
- * @param mode - The new permission mode to set
542
- */
543
- setPermissionMode(mode: PermissionMode): Promise<void>;
544
- /**
545
- * Change the model used for subsequent responses.
546
- * Only available in streaming input mode.
547
- *
548
- * @param model - The model identifier to use, or undefined to use the default
549
- */
550
- setModel(model?: string): Promise<void>;
551
- /**
552
- * Set the maximum number of thinking tokens the model is allowed to use
553
- * when generating its response. This can be used to limit the amount of
554
- * tokens the model uses for its response, which can help control cost and
555
- * latency.
556
- *
557
- * Use `null` to clear any previously set limit and allow the model to
558
- * use the default maximum thinking tokens.
559
- *
560
- * @param maxThinkingTokens - Maximum tokens for thinking, or null to clear the limit
561
- */
562
- setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
563
- /**
564
- * Get the list of available skills for the current session.
565
- *
566
- * @returns Array of available skills with their names and descriptions
567
- */
568
- supportedCommands(): Promise<SlashCommand[]>;
569
- /**
570
- * Get the list of available models.
571
- *
572
- * @returns Array of model information including display names and descriptions
573
- */
574
- supportedModels(): Promise<ModelInfo[]>;
575
- /**
576
- * Get the current status of all configured MCP servers.
577
- *
578
- * @returns Array of MCP server statuses (connected, failed, needs-auth, pending)
579
- */
580
- mcpServerStatus(): Promise<McpServerStatus[]>;
581
- /**
582
- * Get information about the authenticated account.
583
- *
584
- * @returns Account information including email, organization, and subscription type
585
- */
586
- accountInfo(): Promise<AccountInfo>;
587
- /**
588
- * Rewind tracked files to their state at a specific user message.
589
- * Requires file checkpointing to be enabled via the `enableFileCheckpointing` option.
590
- *
591
- * @param userMessageId - UUID of the user message to rewind to
592
- */
593
- rewindFiles(userMessageId: string): Promise<void>;
594
- /**
595
- * Dynamically set the MCP servers for this session.
596
- * This replaces the current set of dynamically-added MCP servers with the provided set.
597
- * Servers that are removed will be disconnected, and new servers will be connected.
598
- *
599
- * Supports both process-based servers (stdio, sse, http) and SDK servers (in-process).
600
- * SDK servers are handled locally in the SDK process, while process-based servers
601
- * are managed by the CLI subprocess.
602
- *
603
- * Note: This only affects servers added dynamically via this method or the SDK.
604
- * Servers configured via settings files are not affected.
605
- *
606
- * @param servers - Record of server name to configuration. Pass an empty object to remove all dynamic servers.
607
- * @returns Information about which servers were added, removed, and any connection errors
608
- */
609
- setMcpServers(servers: Record<string, McpServerConfig>): Promise<McpSetServersResult>;
610
- /**
611
- * Stream input messages to the query.
612
- * Used internally for multi-turn conversations.
613
- *
614
- * @param stream - Async iterable of user messages to send
615
- */
616
- streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void>;
617
- }
618
- /**
619
- * V2 API - UNSTABLE
620
- * Options for creating a session
621
- */
622
- export type SDKSessionOptions = {
623
- /** Model to use */
624
- model: string;
625
- /** Path to Claude Code executable */
626
- pathToClaudeCodeExecutable?: string;
627
- /** Executable to use (node, bun) */
628
- executable?: 'node' | 'bun';
629
- /** Arguments to pass to executable */
630
- executableArgs?: string[];
631
- /**
632
- * Environment variables to pass to the Claude Code process.
633
- * Defaults to `process.env`.
634
- */
635
- env?: {
636
- [envVar: string]: string | undefined;
637
- };
638
- };
639
- /**
640
- * V2 API - UNSTABLE
641
- * Session interface for multi-turn conversations
2
+ * Main entrypoint for Claude Code Agent SDK types.
3
+ *
4
+ * This file re-exports the public SDK API from:
5
+ * - sdk/coreTypes.ts - Common serializable types (messages, configs)
6
+ * - sdk/runtimeTypes.ts - Non-serializable types (callbacks, interfaces)
7
+ *
8
+ * SDK builders who need control protocol types should import from
9
+ * sdk/controlTypes.ts directly.
642
10
  */
643
- export interface SDKSession {
644
- /**
645
- * The session ID. Available after receiving the first message.
646
- * For resumed sessions, available immediately.
647
- * Throws if accessed before the session is initialized.
648
- */
649
- readonly sessionId: string;
650
- /** Send a message to the agent */
651
- send(message: string | SDKUserMessage): Promise<void>;
652
- /** Stream messages from the agent */
653
- stream(): AsyncGenerator<SDKMessage, void>;
654
- /** Close the session */
655
- close(): void;
656
- /** Async disposal support (calls close if not already closed) */
657
- [Symbol.asyncDispose](): Promise<void>;
658
- }
659
- type SdkMcpToolDefinition<Schema extends ZodRawShape = ZodRawShape> = {
660
- name: string;
661
- description: string;
662
- inputSchema: Schema;
663
- handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>;
664
- };
665
- export declare function tool<Schema extends ZodRawShape>(_name: string, _description: string, _inputSchema: Schema, _handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>): SdkMcpToolDefinition<Schema>;
11
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
12
+ export * from './sdk/coreTypes.js';
13
+ export * from './sdk/runtimeTypes.js';
14
+ import type { Query, Options, SDKSessionOptions, SDKSession, SdkMcpToolDefinition, McpSdkServerConfigWithInstance, AnyZodRawShape, InferShape } from './sdk/runtimeTypes.js';
15
+ import type { SDKUserMessage, SDKResultMessage } from './sdk/coreTypes.js';
16
+ export declare function tool<Schema extends AnyZodRawShape>(_name: string, _description: string, _inputSchema: Schema, _handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>): SdkMcpToolDefinition<Schema>;
666
17
  type CreateSdkMcpServerOptions = {
667
18
  name: string;
668
19
  version?: string;
@@ -677,388 +28,23 @@ type CreateSdkMcpServerOptions = {
677
28
  export declare function createSdkMcpServer(_options: CreateSdkMcpServerOptions): McpSdkServerConfigWithInstance;
678
29
  export declare class AbortError extends Error {
679
30
  }
680
- /**
681
- * Definition for a custom subagent that can be invoked via the Task tool.
682
- */
683
- export type AgentDefinition = {
684
- /** Natural language description of when to use this agent */
685
- description: string;
686
- /** Array of allowed tool names. If omitted, inherits all tools from parent */
687
- tools?: string[];
688
- /** Array of tool names to explicitly disallow for this agent */
689
- disallowedTools?: string[];
690
- /** The agent's system prompt */
691
- prompt: string;
692
- /** Model to use for this agent. If omitted or 'inherit', uses the main model */
693
- model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
694
- /** Experimental: Critical reminder added to system prompt */
695
- criticalSystemReminder_EXPERIMENTAL?: string;
696
- };
697
- /**
698
- * Source for loading filesystem-based settings.
699
- * - `'user'` - Global user settings (`~/.claude/settings.json`)
700
- * - `'project'` - Project settings (`.claude/settings.json`)
701
- * - `'local'` - Local settings (`.claude/settings.local.json`)
702
- */
703
- export type SettingSource = 'user' | 'project' | 'local';
704
- /**
705
- * Configuration for loading a plugin.
706
- */
707
- export type SdkPluginConfig = {
708
- /** Plugin type. Currently only 'local' is supported */
709
- type: 'local';
710
- /** Absolute or relative path to the plugin directory */
711
- path: string;
712
- };
713
- export type Options = {
714
- /**
715
- * Controller for cancelling the query. When aborted, the query will stop
716
- * and clean up resources.
717
- */
718
- abortController?: AbortController;
719
- /**
720
- * Additional directories Claude can access beyond the current working directory.
721
- * Paths should be absolute.
722
- */
723
- additionalDirectories?: string[];
724
- /**
725
- * Programmatically define custom subagents that can be invoked via the Task tool.
726
- * Keys are agent names, values are agent definitions.
727
- *
728
- * @example
729
- * ```typescript
730
- * agents: {
731
- * 'code-reviewer': {
732
- * description: 'Reviews code for bugs and style issues',
733
- * prompt: 'You are a code reviewer...',
734
- * tools: ['Read', 'Grep', 'Glob']
735
- * }
736
- * }
737
- * ```
738
- */
739
- agents?: Record<string, AgentDefinition>;
740
- /**
741
- * List of tool names that are auto-allowed without prompting for permission.
742
- * These tools will execute automatically without asking the user for approval.
743
- * To restrict which tools are available, use the `tools` option instead.
744
- */
745
- allowedTools?: string[];
746
- /**
747
- * Custom permission handler for controlling tool usage. Called before each
748
- * tool execution to determine if it should be allowed, denied, or prompt the user.
749
- */
750
- canUseTool?: CanUseTool;
751
- /**
752
- * Continue the most recent conversation instead of starting a new one.
753
- * Mutually exclusive with `resume`.
754
- */
755
- continue?: boolean;
756
- /**
757
- * Current working directory for the session. Defaults to `process.cwd()`.
758
- */
759
- cwd?: string;
760
- /**
761
- * List of tool names that are disallowed. These tools will be removed
762
- * from the model's context and cannot be used, even if they would
763
- * otherwise be allowed.
764
- */
765
- disallowedTools?: string[];
766
- /**
767
- * Specify the base set of available built-in tools.
768
- * - `string[]` - Array of specific tool names (e.g., `['Bash', 'Read', 'Edit']`)
769
- * - `[]` (empty array) - Disable all built-in tools
770
- * - `{ type: 'preset'; preset: 'claude_code' }` - Use all default Claude Code tools
771
- */
772
- tools?: string[] | {
773
- type: 'preset';
774
- preset: 'claude_code';
775
- };
776
- /**
777
- * Environment variables to pass to the Claude Code process.
778
- * Defaults to `process.env`.
779
- */
780
- env?: {
781
- [envVar: string]: string | undefined;
782
- };
783
- /**
784
- * JavaScript runtime to use for executing Claude Code.
785
- * Auto-detected if not specified.
786
- */
787
- executable?: 'bun' | 'deno' | 'node';
788
- /**
789
- * Additional arguments to pass to the JavaScript runtime executable.
790
- */
791
- executableArgs?: string[];
792
- /**
793
- * Additional CLI arguments to pass to Claude Code.
794
- * Keys are argument names (without --), values are argument values.
795
- * Use `null` for boolean flags.
796
- */
797
- extraArgs?: Record<string, string | null>;
798
- /**
799
- * Fallback model to use if the primary model fails or is unavailable.
800
- */
801
- fallbackModel?: string;
802
- /**
803
- * Enable file checkpointing to track file changes during the session.
804
- * When enabled, files can be rewound to their state at any user message
805
- * using `Query.rewindFiles()`.
806
- *
807
- * File checkpointing creates backups of files before they are modified,
808
- * allowing you to restore them to previous states.
809
- */
810
- enableFileCheckpointing?: boolean;
811
- /**
812
- * When true, resumed sessions will fork to a new session ID rather than
813
- * continuing the previous session. Use with `resume`.
814
- */
815
- forkSession?: boolean;
816
- /**
817
- * Enable beta features. Currently supported:
818
- * - `'context-1m-2025-08-07'` - Enable 1M token context window (Sonnet 4/4.5 only)
819
- *
820
- * @see https://docs.anthropic.com/en/api/beta-headers
821
- */
822
- betas?: SdkBeta[];
823
- /**
824
- * Hook callbacks for responding to various events during execution.
825
- * Hooks can modify behavior, add context, or implement custom logic.
826
- *
827
- * @example
828
- * ```typescript
829
- * hooks: {
830
- * PreToolUse: [{
831
- * hooks: [async (input) => ({ continue: true })]
832
- * }]
833
- * }
834
- * ```
835
- */
836
- hooks?: Partial<Record<HookEvent, HookCallbackMatcher[]>>;
837
- /**
838
- * When false, disables session persistence to disk. Sessions will not be
839
- * saved to ~/.claude/projects/ and cannot be resumed later. Useful for
840
- * ephemeral or automated workflows where session history is not needed.
841
- *
842
- * @default true
843
- */
844
- persistSession?: boolean;
845
- /**
846
- * Include partial/streaming message events in the output.
847
- * When true, `SDKPartialAssistantMessage` events will be emitted during streaming.
848
- */
849
- includePartialMessages?: boolean;
850
- /**
851
- * Maximum number of tokens the model can use for its thinking/reasoning process.
852
- * Helps control cost and latency for complex tasks.
853
- */
854
- maxThinkingTokens?: number;
855
- /**
856
- * Maximum number of conversation turns before the query stops.
857
- * A turn consists of a user message and assistant response.
858
- */
859
- maxTurns?: number;
860
- /**
861
- * Maximum budget in USD for the query. The query will stop if this
862
- * budget is exceeded, returning an `error_max_budget_usd` result.
863
- */
864
- maxBudgetUsd?: number;
865
- /**
866
- * MCP (Model Context Protocol) server configurations.
867
- * Keys are server names, values are server configurations.
868
- *
869
- * @example
870
- * ```typescript
871
- * mcpServers: {
872
- * 'my-server': {
873
- * command: 'node',
874
- * args: ['./my-mcp-server.js']
875
- * }
876
- * }
877
- * ```
878
- */
879
- mcpServers?: Record<string, McpServerConfig>;
880
- /**
881
- * Claude model to use. Defaults to the CLI default model.
882
- * Examples: 'claude-sonnet-4-5-20250929', 'claude-opus-4-20250514'
883
- */
884
- model?: string;
885
- /**
886
- * Output format configuration for structured responses.
887
- * When specified, the agent will return structured data matching the schema.
888
- *
889
- * @example
890
- * ```typescript
891
- * outputFormat: {
892
- * type: 'json_schema',
893
- * schema: { type: 'object', properties: { result: { type: 'string' } } }
894
- * }
895
- * ```
896
- */
897
- outputFormat?: OutputFormat;
898
- /**
899
- * Path to the Claude Code executable. Uses the built-in executable if not specified.
900
- */
901
- pathToClaudeCodeExecutable?: string;
902
- /**
903
- * Permission mode for the session.
904
- * - `'default'` - Standard permission behavior, prompts for dangerous operations
905
- * - `'acceptEdits'` - Auto-accept file edit operations
906
- * - `'bypassPermissions'` - Bypass all permission checks (requires `allowDangerouslySkipPermissions`)
907
- * - `'plan'` - Planning mode, no execution of tools
908
- * - `'dontAsk'` - Don't prompt for permissions, deny if not pre-approved
909
- */
910
- permissionMode?: PermissionMode;
911
- /**
912
- * Must be set to `true` when using `permissionMode: 'bypassPermissions'`.
913
- * This is a safety measure to ensure intentional bypassing of permissions.
914
- */
915
- allowDangerouslySkipPermissions?: boolean;
916
- /**
917
- * MCP tool name to use for permission prompts. When set, permission requests
918
- * will be routed through this MCP tool instead of the default handler.
919
- */
920
- permissionPromptToolName?: string;
921
- /**
922
- * Load plugins for this session. Plugins provide custom commands, agents,
923
- * skills, and hooks that extend Claude Code's capabilities.
924
- *
925
- * Currently only local plugins are supported via the 'local' type.
926
- *
927
- * @example
928
- * ```typescript
929
- * plugins: [
930
- * { type: 'local', path: './my-plugin' },
931
- * { type: 'local', path: '/absolute/path/to/plugin' }
932
- * ]
933
- * ```
934
- */
935
- plugins?: SdkPluginConfig[];
936
- /**
937
- * Session ID to resume. Loads the conversation history from the specified session.
938
- */
939
- resume?: string;
940
- /**
941
- * When resuming, only resume messages up to and including the message with this UUID.
942
- * Use with `resume`. This allows you to resume from a specific point in the conversation.
943
- * The message ID should be from `SDKAssistantMessage.uuid`.
944
- */
945
- resumeSessionAt?: string;
946
- /**
947
- * Sandbox settings for command execution isolation.
948
- *
949
- * When enabled, commands are executed in a sandboxed environment that restricts
950
- * filesystem and network access. This provides an additional security layer.
951
- *
952
- * **Important:** Filesystem and network restrictions are configured via permission
953
- * rules, not via these sandbox settings:
954
- * - Filesystem access: Use `Read` and `Edit` permission rules
955
- * - Network access: Use `WebFetch` permission rules
956
- *
957
- * These sandbox settings control sandbox behavior (enabled, auto-allow, etc.),
958
- * while the actual access restrictions come from your permission configuration.
959
- *
960
- * @example Enable sandboxing with auto-allow
961
- * ```typescript
962
- * sandbox: {
963
- * enabled: true,
964
- * autoAllowBashIfSandboxed: true
965
- * }
966
- * ```
967
- *
968
- * @example Configure network options (not restrictions)
969
- * ```typescript
970
- * sandbox: {
971
- * enabled: true,
972
- * network: {
973
- * allowLocalBinding: true,
974
- * allowUnixSockets: ['/var/run/docker.sock']
975
- * }
976
- * }
977
- * ```
978
- *
979
- * @see https://docs.anthropic.com/en/docs/claude-code/settings#sandbox-settings
980
- */
981
- sandbox?: SandboxSettings;
982
- /**
983
- * Control which filesystem settings to load.
984
- * - `'user'` - Global user settings (`~/.claude/settings.json`)
985
- * - `'project'` - Project settings (`.claude/settings.json`)
986
- * - `'local'` - Local settings (`.claude/settings.local.json`)
987
- *
988
- * When omitted or empty, no filesystem settings are loaded (SDK isolation mode).
989
- * Must include `'project'` to load CLAUDE.md files.
990
- */
991
- settingSources?: SettingSource[];
992
- /**
993
- * Callback for stderr output from the Claude Code process.
994
- * Useful for debugging and logging.
995
- */
996
- stderr?: (data: string) => void;
997
- /**
998
- * Enforce strict validation of MCP server configurations.
999
- * When true, invalid configurations will cause errors instead of warnings.
1000
- */
1001
- strictMcpConfig?: boolean;
1002
- /**
1003
- * System prompt configuration.
1004
- * - `string` - Use a custom system prompt
1005
- * - `{ type: 'preset', preset: 'claude_code' }` - Use Claude Code's default system prompt
1006
- * - `{ type: 'preset', preset: 'claude_code', append: '...' }` - Use default prompt with appended instructions
1007
- *
1008
- * @example Custom prompt
1009
- * ```typescript
1010
- * systemPrompt: 'You are a helpful coding assistant.'
1011
- * ```
1012
- *
1013
- * @example Default with additions
1014
- * ```typescript
1015
- * systemPrompt: {
1016
- * type: 'preset',
1017
- * preset: 'claude_code',
1018
- * append: 'Always explain your reasoning.'
1019
- * }
1020
- * ```
1021
- */
1022
- systemPrompt?: string | {
1023
- type: 'preset';
1024
- preset: 'claude_code';
1025
- append?: string;
1026
- };
1027
- /**
1028
- * Custom function to spawn the Claude Code process.
1029
- * Use this to run Claude Code in VMs, containers, or remote environments.
1030
- *
1031
- * When provided, this function is called instead of the default local spawn.
1032
- * The default behavior checks if the executable exists before spawning.
1033
- *
1034
- * @example
1035
- * ```typescript
1036
- * spawnClaudeCodeProcess: (options) => {
1037
- * // Custom spawn logic for VM execution
1038
- * // options contains: command, args, cwd, env, signal
1039
- * return myVMProcess; // Must satisfy SpawnedProcess interface
1040
- * }
1041
- * ```
1042
- */
1043
- spawnClaudeCodeProcess?: (options: SpawnOptions) => SpawnedProcess;
1044
- };
1045
31
  export declare function query(_params: {
1046
32
  prompt: string | AsyncIterable<SDKUserMessage>;
1047
33
  options?: Options;
1048
34
  }): Query;
1049
35
  /**
1050
36
  * V2 API - UNSTABLE
1051
- * Create a persistent session for multi-turn conversations
37
+ * Create a persistent session for multi-turn conversations.
1052
38
  */
1053
39
  export declare function unstable_v2_createSession(_options: SDKSessionOptions): SDKSession;
1054
40
  /**
1055
41
  * V2 API - UNSTABLE
1056
- * Resume an existing session by ID
42
+ * Resume an existing session by ID.
1057
43
  */
1058
44
  export declare function unstable_v2_resumeSession(_sessionId: string, _options: SDKSessionOptions): SDKSession;
1059
45
  /**
1060
46
  * V2 API - UNSTABLE
1061
- * One-shot convenience function for single prompts
47
+ * One-shot convenience function for single prompts.
1062
48
  *
1063
49
  * @example
1064
50
  * ```typescript
@@ -1068,4 +54,3 @@ export declare function unstable_v2_resumeSession(_sessionId: string, _options:
1068
54
  * ```
1069
55
  */
1070
56
  export declare function unstable_v2_prompt(_message: string, _options: SDKSessionOptions): Promise<SDKResultMessage>;
1071
- export { SpawnOptions, SpawnedProcess, Transport };