@rayss-dev/openclaude 0.30.3-by-rayss → 0.31.0-by-rayss

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,601 +1,621 @@
1
- // Type declarations for @rayss-dev/openclaude SDK
2
- // Manually maintained — keep in sync with src/entrypoints/sdk/index.ts
3
- // Drift is caught by validate-externals.ts (runs in CI)
4
-
5
- // ============================================================================
6
- // Error
7
- // ============================================================================
8
-
9
- export class AbortError extends Error {
10
- override readonly name: 'AbortError'
11
- }
12
-
13
- export class ClaudeError extends Error {
14
- constructor(message: string)
15
- }
16
-
17
- export class SDKError extends ClaudeError {
18
- constructor(message: string)
19
- }
20
-
21
- export class SDKAuthenticationError extends SDKError {
22
- constructor(message?: string)
23
- }
24
-
25
- export class SDKBillingError extends SDKError {
26
- constructor(message?: string)
27
- }
28
-
29
- export class SDKRateLimitError extends SDKError {
30
- readonly resetsAt?: number
31
- readonly rateLimitType?: string
32
- constructor(message?: string, resetsAt?: number, rateLimitType?: string)
33
- }
34
-
35
- export class SDKInvalidRequestError extends SDKError {
36
- constructor(message?: string)
37
- }
38
-
39
- export class SDKServerError extends SDKError {
40
- constructor(message?: string)
41
- }
42
-
43
- export class SDKMaxOutputTokensError extends SDKError {
44
- constructor(message?: string)
45
- }
46
-
47
- export type SDKAssistantMessageError =
48
- | 'authentication_failed'
49
- | 'billing_error'
50
- | 'rate_limit'
51
- | 'invalid_request'
52
- | 'server_error'
53
- | 'unknown'
54
- | 'max_output_tokens'
55
-
56
- export function sdkErrorFromType(
57
- errorType: SDKAssistantMessageError,
58
- message?: string,
59
- ): SDKError | ClaudeError
60
-
61
- // ============================================================================
62
- // Types
63
- // ============================================================================
64
-
65
- export type ApiKeySource = 'user' | 'project' | 'org' | 'temporary' | 'oauth' | 'none'
66
-
67
- export type RewindFilesResult = {
68
- canRewind: boolean
69
- error?: string
70
- filesChanged?: string[]
71
- insertions?: number
72
- deletions?: number
73
- }
74
-
75
- export type McpServerStatus = {
76
- name: string
77
- status: 'connected' | 'failed' | 'needs-auth' | 'pending' | 'disabled'
78
- serverInfo?: { name: string; version: string }
79
- error?: string
80
- scope?: string
81
- tools?: {
82
- name: string
83
- description?: string
84
- annotations?: {
85
- readOnly?: boolean
86
- destructive?: boolean
87
- openWorld?: boolean
88
- }
89
- }[]
90
- }
91
-
92
- export type PermissionResult = ({
93
- behavior: 'allow'
94
- updatedInput?: Record<string, unknown>
95
- updatedPermissions?: ({
96
- type: 'addRules'
97
- rules: { toolName: string; ruleContent?: string }[]
98
- behavior: 'allow' | 'deny' | 'ask'
99
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
100
- }) | ({
101
- type: 'replaceRules'
102
- rules: { toolName: string; ruleContent?: string }[]
103
- behavior: 'allow' | 'deny' | 'ask'
104
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
105
- }) | ({
106
- type: 'removeRules'
107
- rules: { toolName: string; ruleContent?: string }[]
108
- behavior: 'allow' | 'deny' | 'ask'
109
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
110
- }) | ({
111
- type: 'setMode'
112
- mode: 'default' | 'acceptEdits' | 'bypassPermissions' | 'fullAccess' | 'plan' | 'dontAsk'
113
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
114
- }) | ({
115
- type: 'addDirectories'
116
- directories: string[]
117
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
118
- }) | ({
119
- type: 'removeDirectories'
120
- directories: string[]
121
- destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
122
- })[]
123
- toolUseID?: string
124
- decisionClassification?: 'user_temporary' | 'user_permanent' | 'user_reject'
125
- }) | ({
126
- behavior: 'deny'
127
- message: string
128
- interrupt?: boolean
129
- toolUseID?: string
130
- decisionClassification?: 'user_temporary' | 'user_permanent' | 'user_reject'
131
- })
132
-
133
- export type SDKSessionInfo = {
134
- sessionId: string
135
- summary: string
136
- lastModified: number
137
- fileSize?: number
138
- customTitle?: string
139
- firstPrompt?: string
140
- gitBranch?: string
141
- cwd?: string
142
- tag?: string
143
- createdAt?: number
144
- }
145
-
146
- export type ListSessionsOptions = {
147
- dir?: string
148
- limit?: number
149
- offset?: number
150
- includeWorktrees?: boolean
151
- }
152
-
153
- export type GetSessionInfoOptions = {
154
- dir?: string
155
- }
156
-
157
- export type GetSessionMessagesOptions = {
158
- dir?: string
159
- limit?: number
160
- offset?: number
161
- includeSystemMessages?: boolean
162
- }
163
-
164
- export type SessionMutationOptions = {
165
- dir?: string
166
- }
167
-
168
- export type ForkSessionOptions = {
169
- dir?: string
170
- upToMessageId?: string
171
- title?: string
172
- }
173
-
174
- export type ForkSessionResult = {
175
- sessionId: string
176
- }
177
-
178
- export type SessionMessage = {
179
- role: 'user' | 'assistant' | 'system'
180
- content: unknown
181
- timestamp?: string
182
- uuid?: string
183
- parentUuid?: string | null
184
- [key: string]: unknown
185
- }
186
-
187
- // Re-export precise SDK message types from generated types
188
- // These use camelCase field names and discriminated unions for full IntelliSense
189
- import type {
190
- AccountInfo,
191
- AgentInfo,
192
- FastModeState,
193
- ModelInfo,
194
- SlashCommand,
195
- SDKMessage,
196
- SDKUserMessage,
197
- SDKResultMessage,
198
- } from './sdk/coreTypes.generated.js'
199
-
200
- export type {
201
- AccountInfo,
202
- AgentInfo,
203
- FastModeState,
204
- ModelInfo,
205
- SlashCommand,
206
- SDKMessage,
207
- SDKUserMessage,
208
- SDKResultMessage,
209
- } from './sdk/coreTypes.generated.js'
210
-
211
- export type SDKControlInitializeResponse = {
212
- commands: SlashCommand[]
213
- agents: AgentInfo[]
214
- output_style: string
215
- available_output_styles: string[]
216
- models: ModelInfo[]
217
- account: AccountInfo
218
- /** @internal CLI process PID for tmux socket isolation. */
219
- pid?: number
220
- fast_mode_state?: FastModeState
221
- }
222
-
223
- // ============================================================================
224
- // Query types
225
- // ============================================================================
226
-
227
- export type QueryPermissionMode =
228
- | 'default'
229
- | 'plan'
230
- | 'auto-accept'
231
- | 'bypass-permissions'
232
- | 'bypassPermissions'
233
- | 'full-access'
234
- | 'fullAccess'
235
- | 'acceptEdits'
236
-
237
- export type QueryOptions = {
238
- cwd: string
239
- additionalDirectories?: string[]
240
- model?: string
241
- sessionId?: string
242
- /** Fork the session before resuming (requires sessionId). */
243
- fork?: boolean
244
- /** Alias for fork. When true, resumed session forks to a new session ID. */
245
- forkSession?: boolean
246
- /** Resume the most recent session for this cwd (no sessionId needed). */
247
- continue?: boolean
248
- resume?: string
249
- /** When resuming, resume messages up to and including this message UUID. */
250
- resumeSessionAt?: string
251
- permissionMode?: QueryPermissionMode
252
- abortController?: AbortController
253
- executable?: string
254
- allowDangerouslySkipPermissions?: boolean
255
- disallowedTools?: string[]
256
- hooks?: Record<string, unknown[]>
257
- mcpServers?: Record<string, unknown>
258
- settings?: {
259
- env?: Record<string, string>
260
- attribution?: { commit: string; pr: string }
261
- }
262
- /** Environment variables to apply during query execution. Overrides process.env. Takes precedence over settings.env. */
263
- env?: Record<string, string | undefined>
264
- /**
265
- * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
266
- * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
267
- *
268
- * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
269
- * is provided, ALL tool uses are denied. You MUST provide at least one of
270
- * these callbacks to allow tool execution.
271
- */
272
- canUseTool?: (
273
- name: string,
274
- input: unknown,
275
- options?: { toolUseID?: string },
276
- ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
277
- /**
278
- * Callback invoked when a tool needs permission approval. The host receives
279
- * the request immediately and can resolve it by calling
280
- * `query.respondToPermission(toolUseId, decision)` before the timeout.
281
- * If omitted, tools that require permission fall through to the default
282
- * permission logic immediately (no timeout).
283
- */
284
- onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
285
- systemPrompt?:
286
- | string
287
- | { type: 'preset'; preset: string; append?: string }
288
- | { type: 'custom'; content: string }
289
- /** Agent definitions to register with the query engine. */
290
- agents?: Record<string, {
291
- description?: string
292
- prompt: string
293
- /**
294
- * Tool allowlist for this agent. If omitted or set to ['*'], the agent can use
295
- * all tools available to subagents after disallowedTools is applied.
296
- */
297
- tools?: string[]
298
- /** Tool denylist for this agent. Deny entries always override tools entries. */
299
- disallowedTools?: string[]
300
- model?: string
301
- maxTurns?: number
302
- maxSteps?: number
303
- }>
304
- settingSources?: string[]
305
- /** When true, yields stream_event messages for token-by-token streaming. */
306
- includePartialMessages?: boolean
307
- /** @internal Timeout in ms for permission request resolution. Default 30000. */
308
- _permissionTimeoutMs?: number
309
- stderr?: (data: string) => void
310
- }
311
-
312
- export interface Query {
313
- readonly sessionId: string
314
- [Symbol.asyncIterator](): AsyncIterator<SDKMessage>
315
- setModel(model: string): Promise<void>
316
- setPermissionMode(mode: QueryPermissionMode): Promise<void>
317
- close(): void
318
- interrupt(): void
319
- respondToPermission(toolUseId: string, decision: PermissionResult): void
320
- /** Check if file rewind is possible. */
321
- rewindFiles(): RewindFilesResult
322
- /** Actually perform the file rewind. Returns files changed and diff stats. */
323
- rewindFilesAsync(): Promise<RewindFilesResult>
324
- supportedCommands(): string[]
325
- supportedModels(): string[]
326
- supportedAgents(): string[]
327
- mcpServerStatus(): McpServerStatus[]
328
- accountInfo(): Promise<{ apiKeySource: ApiKeySource; [key: string]: unknown }>
329
- setMaxThinkingTokens(tokens: number): void
330
- }
331
-
332
- /**
333
- * Permission request message emitted when a tool needs permission approval.
334
- * Hosts can respond via respondToPermission() using the request_id.
335
- */
336
- export type SDKPermissionRequestMessage = {
337
- type: 'permission_request'
338
- request_id: string
339
- tool_name: string
340
- tool_use_id: string
341
- input: Record<string, unknown>
342
- uuid: string
343
- session_id: string
344
- }
345
-
346
- export type SDKPermissionTimeoutMessage = {
347
- type: 'permission_timeout'
348
- tool_name: string
349
- tool_use_id: string
350
- timed_out_after_ms: number
351
- uuid: string
352
- session_id: string
353
- }
354
-
355
- /**
356
- * A message emitted when agent definitions fail to load.
357
- * This allows hosts to detect configuration issues that would otherwise
358
- * be silently logged to console.warn.
359
- *
360
- * Note: Agent load failures are non-fatal — the query continues without agents.
361
- */
362
- export type SDKAgentLoadFailureMessage = {
363
- type: 'agent_load_failure'
364
- stage: 'definitions' | 'injection'
365
- error_message: string
366
- }
367
-
368
- // ============================================================================
369
- // Permission resolve decision (SDK-specific)
370
- // ============================================================================
371
-
372
- /**
373
- * Decision returned by permission resolution.
374
- * Used by respondToPermission() and internal permission handling.
375
- */
376
- export type PermissionResolveDecision =
377
- | { behavior: 'allow'; updatedInput?: Record<string, unknown> }
378
- | { behavior: 'deny'; message: string; decisionReason: { type: 'mode'; mode: string } }
379
-
380
- // ============================================================================
381
- // V2 API types
382
- // ============================================================================
383
-
384
- export type SDKSessionOptions = {
385
- cwd: string
386
- model?: string
387
- permissionMode?: QueryPermissionMode
388
- allowDangerouslySkipPermissions?: boolean
389
- abortController?: AbortController
390
- /**
391
- * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
392
- * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
393
- *
394
- * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
395
- * is provided, ALL tool uses are denied. You MUST provide at least one of
396
- * these callbacks to allow tool execution.
397
- */
398
- canUseTool?: (
399
- name: string,
400
- input: unknown,
401
- options?: { toolUseID?: string },
402
- ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
403
- /** MCP server configurations for this session. */
404
- mcpServers?: Record<string, unknown>
405
- /**
406
- * Callback invoked when a tool needs permission approval. The host receives
407
- * the request immediately and can resolve it via respondToPermission().
408
- */
409
- onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
410
- /** Tools to disallow (blanket deny by tool name). */
411
- disallowedTools?: string[]
412
- /** Agent definitions to register with the session engine. */
413
- agents?: Record<string, {
414
- description?: string
415
- prompt: string
416
- /**
417
- * Tool allowlist for this agent. If omitted or set to ['*'], the agent can use
418
- * all tools available to subagents after disallowedTools is applied.
419
- */
420
- tools?: string[]
421
- /** Tool denylist for this agent. Deny entries always override tools entries. */
422
- disallowedTools?: string[]
423
- model?: string
424
- maxTurns?: number
425
- maxSteps?: number
426
- }>
427
- }
428
-
429
- export interface SDKSession {
430
- sessionId: string
431
- sendMessage(content: string): AsyncIterable<SDKMessage>
432
- getMessages(): SDKMessage[]
433
- interrupt(): void
434
- /** Close the session and release resources (MCP connections, etc.). */
435
- close(): void
436
- /** Respond to a pending permission prompt. */
437
- respondToPermission(toolUseId: string, decision: PermissionResult): void
438
- }
439
-
440
- // ============================================================================
441
- // MCP tool types
442
- // ============================================================================
443
-
444
- export interface SdkMcpToolDefinition<Schema = any> {
445
- name: string
446
- description: string
447
- inputSchema: Schema
448
- handler: (args: any, extra: unknown) => Promise<any>
449
- annotations?: any
450
- searchHint?: string
451
- alwaysLoad?: boolean
452
- }
453
-
454
- // ============================================================================
455
- // Session functions
456
- // ============================================================================
457
-
458
- export function listSessions(
459
- options?: ListSessionsOptions,
460
- ): Promise<SDKSessionInfo[]>
461
-
462
- export function getSessionInfo(
463
- sessionId: string,
464
- options?: GetSessionInfoOptions,
465
- ): Promise<SDKSessionInfo | undefined>
466
-
467
- export function getSessionMessages(
468
- sessionId: string,
469
- options?: GetSessionMessagesOptions,
470
- ): Promise<SessionMessage[]>
471
-
472
- export function renameSession(
473
- sessionId: string,
474
- title: string,
475
- options?: SessionMutationOptions,
476
- ): Promise<void>
477
-
478
- export function tagSession(
479
- sessionId: string,
480
- tag: string | null,
481
- options?: SessionMutationOptions,
482
- ): Promise<void>
483
-
484
- export function forkSession(
485
- sessionId: string,
486
- options?: ForkSessionOptions,
487
- ): Promise<ForkSessionResult>
488
-
489
- export function deleteSession(
490
- sessionId: string,
491
- options?: SessionMutationOptions,
492
- ): Promise<void>
493
-
494
- // ============================================================================
495
- // Query functions
496
- // ============================================================================
497
-
498
- export function query(params: {
499
- prompt: string | AsyncIterable<SDKUserMessage>
500
- options?: QueryOptions
501
- }): Query
502
-
503
- export function queryAsync(params: {
504
- prompt: string | AsyncIterable<SDKUserMessage>
505
- options?: QueryOptions
506
- }): Promise<Query>
507
-
508
- // ============================================================================
509
- // V2 API functions
510
- // ============================================================================
511
-
512
- export function unstable_v2_createSession(options: SDKSessionOptions): SDKSession
513
-
514
- export function unstable_v2_resumeSession(
515
- sessionId: string,
516
- options: SDKSessionOptions,
517
- ): Promise<SDKSession>
518
-
519
- export function unstable_v2_prompt(
520
- message: string,
521
- options: SDKSessionOptions,
522
- ): Promise<SDKResultMessage>
523
-
524
- // ============================================================================
525
- // MCP tool functions
526
- // ============================================================================
527
-
528
- export function tool<Schema = any>(
529
- name: string,
530
- description: string,
531
- inputSchema: Schema,
532
- handler: (args: any, extra: unknown) => Promise<any>,
533
- extras?: {
534
- annotations?: any
535
- searchHint?: string
536
- alwaysLoad?: boolean
537
- },
538
- ): SdkMcpToolDefinition<Schema>
539
-
540
- /**
541
- * MCP server transport configuration types.
542
- * Matches McpServerConfigForProcessTransport from coreTypes.generated.ts.
543
- */
544
- export type SdkMcpStdioConfig = {
545
- type?: "stdio"
546
- command: string
547
- args?: string[]
548
- env?: Record<string, string>
549
- }
550
-
551
- export type SdkMcpSSEConfig = {
552
- type: "sse"
553
- url: string
554
- headers?: Record<string, string>
555
- }
556
-
557
- export type SdkMcpHttpConfig = {
558
- type: "http"
559
- url: string
560
- headers?: Record<string, string>
561
- }
562
-
563
- export type SdkMcpSdkConfig = {
564
- type: "sdk"
565
- name: string
566
- /** In-process tool definitions created via the tool() helper. */
567
- tools?: SdkMcpToolDefinition[]
568
- }
569
-
570
- export type SdkMcpServerConfig = SdkMcpStdioConfig | SdkMcpSSEConfig | SdkMcpHttpConfig | SdkMcpSdkConfig
571
-
572
- /**
573
- * Scoped MCP server config with session scope.
574
- * Returned by createSdkMcpServer() for use with mcpServers option.
575
- */
576
- export type SdkScopedMcpServerConfig = SdkMcpServerConfig & {
577
- scope: "session"
578
- }
579
-
580
- /**
581
- * Wraps an MCP server configuration for use with the SDK.
582
- * Adds the 'session' scope marker so the SDK knows this server
583
- * should be connected per-session (not globally).
584
- *
585
- * @param config - MCP server config (stdio, sse, http, or sdk type)
586
- * @returns Scoped config with scope: 'session' added
587
- *
588
- * @example
589
- * ```typescript
590
- * const server = createSdkMcpServer({
591
- * type: 'stdio',
592
- * command: 'npx',
593
- * args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
594
- * })
595
- * const session = unstable_v2_createSession({
596
- * cwd: '/my/project',
597
- * mcpServers: { 'fs': server },
598
- * })
599
- * ```
600
- */
601
- export function createSdkMcpServer(config: SdkMcpServerConfig): SdkScopedMcpServerConfig
1
+ // Type declarations for @rayss-dev/openclaude SDK
2
+ // Manually maintained — keep in sync with src/entrypoints/sdk/index.ts
3
+ // Drift is caught by validate-externals.ts (runs in CI)
4
+
5
+ // ============================================================================
6
+ // Error
7
+ // ============================================================================
8
+
9
+ export class AbortError extends Error {
10
+ override readonly name: 'AbortError'
11
+ }
12
+
13
+ export class ClaudeError extends Error {
14
+ constructor(message: string)
15
+ }
16
+
17
+ export class SDKError extends ClaudeError {
18
+ constructor(message: string)
19
+ }
20
+
21
+ export class SDKAuthenticationError extends SDKError {
22
+ constructor(message?: string)
23
+ }
24
+
25
+ export class SDKBillingError extends SDKError {
26
+ constructor(message?: string)
27
+ }
28
+
29
+ export class SDKRateLimitError extends SDKError {
30
+ readonly resetsAt?: number
31
+ readonly rateLimitType?: string
32
+ constructor(message?: string, resetsAt?: number, rateLimitType?: string)
33
+ }
34
+
35
+ export class SDKInvalidRequestError extends SDKError {
36
+ constructor(message?: string)
37
+ }
38
+
39
+ export class SDKServerError extends SDKError {
40
+ constructor(message?: string)
41
+ }
42
+
43
+ export class SDKMaxOutputTokensError extends SDKError {
44
+ constructor(message?: string)
45
+ }
46
+
47
+ export type SDKAssistantMessageError =
48
+ | 'authentication_failed'
49
+ | 'billing_error'
50
+ | 'rate_limit'
51
+ | 'invalid_request'
52
+ | 'server_error'
53
+ | 'unknown'
54
+ | 'max_output_tokens'
55
+
56
+ export function sdkErrorFromType(
57
+ errorType: SDKAssistantMessageError,
58
+ message?: string,
59
+ ): SDKError | ClaudeError
60
+
61
+ // ============================================================================
62
+ // Types
63
+ // ============================================================================
64
+
65
+ export type ApiKeySource = 'user' | 'project' | 'org' | 'temporary' | 'oauth' | 'none'
66
+
67
+ export type RewindFilesResult = {
68
+ canRewind: boolean
69
+ error?: string
70
+ filesChanged?: string[]
71
+ insertions?: number
72
+ deletions?: number
73
+ }
74
+
75
+ export type McpServerStatus = {
76
+ name: string
77
+ status: 'connected' | 'failed' | 'needs-auth' | 'pending' | 'disabled'
78
+ serverInfo?: { name: string; version: string }
79
+ error?: string
80
+ scope?: string
81
+ tools?: {
82
+ name: string
83
+ description?: string
84
+ annotations?: {
85
+ readOnly?: boolean
86
+ destructive?: boolean
87
+ openWorld?: boolean
88
+ }
89
+ }[]
90
+ }
91
+
92
+ export type PermissionResult = ({
93
+ behavior: 'allow'
94
+ updatedInput?: Record<string, unknown>
95
+ updatedPermissions?: ({
96
+ type: 'addRules'
97
+ rules: { toolName: string; ruleContent?: string }[]
98
+ behavior: 'allow' | 'deny' | 'ask'
99
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
100
+ }) | ({
101
+ type: 'replaceRules'
102
+ rules: { toolName: string; ruleContent?: string }[]
103
+ behavior: 'allow' | 'deny' | 'ask'
104
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
105
+ }) | ({
106
+ type: 'removeRules'
107
+ rules: { toolName: string; ruleContent?: string }[]
108
+ behavior: 'allow' | 'deny' | 'ask'
109
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
110
+ }) | ({
111
+ type: 'setMode'
112
+ mode: 'default' | 'acceptEdits' | 'bypassPermissions' | 'fullAccess' | 'plan' | 'dontAsk'
113
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
114
+ }) | ({
115
+ type: 'addDirectories'
116
+ directories: string[]
117
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
118
+ }) | ({
119
+ type: 'removeDirectories'
120
+ directories: string[]
121
+ destination: 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'
122
+ })[]
123
+ toolUseID?: string
124
+ decisionClassification?: 'user_temporary' | 'user_permanent' | 'user_reject'
125
+ }) | ({
126
+ behavior: 'deny'
127
+ message: string
128
+ interrupt?: boolean
129
+ toolUseID?: string
130
+ decisionClassification?: 'user_temporary' | 'user_permanent' | 'user_reject'
131
+ })
132
+
133
+ export type SDKSessionInfo = {
134
+ sessionId: string
135
+ summary: string
136
+ lastModified: number
137
+ fileSize?: number
138
+ customTitle?: string
139
+ firstPrompt?: string
140
+ gitBranch?: string
141
+ cwd?: string
142
+ tag?: string
143
+ createdAt?: number
144
+ }
145
+
146
+ export type ListSessionsOptions = {
147
+ dir?: string
148
+ limit?: number
149
+ offset?: number
150
+ includeWorktrees?: boolean
151
+ }
152
+
153
+ export type GetSessionInfoOptions = {
154
+ dir?: string
155
+ }
156
+
157
+ export type GetSessionMessagesOptions = {
158
+ dir?: string
159
+ limit?: number
160
+ offset?: number
161
+ includeSystemMessages?: boolean
162
+ }
163
+
164
+ export type SessionMutationOptions = {
165
+ dir?: string
166
+ }
167
+
168
+ export type ForkSessionOptions = {
169
+ dir?: string
170
+ upToMessageId?: string
171
+ title?: string
172
+ }
173
+
174
+ export type ForkSessionResult = {
175
+ sessionId: string
176
+ }
177
+
178
+ export type SessionMessage = {
179
+ role: 'user' | 'assistant' | 'system'
180
+ content: unknown
181
+ timestamp?: string
182
+ uuid?: string
183
+ parentUuid?: string | null
184
+ [key: string]: unknown
185
+ }
186
+
187
+ // Re-export precise SDK message types from generated types
188
+ // These use camelCase field names and discriminated unions for full IntelliSense
189
+ // Note: ToolAnnotations and CallToolResult shapes mirror the MCP SDK but are
190
+ // declared locally to keep the public SDK declarations free of the optional
191
+ // `@modelcontextprotocol/sdk` peer dependency. They are stable SDK shapes.
192
+ type ToolAnnotations = {
193
+ title?: string
194
+ readOnlyHint?: boolean
195
+ destructiveHint?: boolean
196
+ idempotentHint?: boolean
197
+ openWorldHint?: boolean
198
+ }
199
+ type CallToolResult = {
200
+ content?: Array<
201
+ | { type: 'text'; text: string }
202
+ | { type: 'image'; data: string; mimeType: string }
203
+ | { type: 'resource'; resource: { uri: string; text?: string; mimeType?: string } }
204
+ | { type: string; [key: string]: unknown }
205
+ >
206
+ isError?: boolean
207
+ [key: string]: unknown
208
+ }
209
+ import type {
210
+ AccountInfo,
211
+ AgentInfo,
212
+ FastModeState,
213
+ ModelInfo,
214
+ SlashCommand,
215
+ SDKMessage,
216
+ SDKUserMessage,
217
+ SDKResultMessage,
218
+ } from './sdk/coreTypes.generated.js'
219
+
220
+ export type {
221
+ AccountInfo,
222
+ AgentInfo,
223
+ FastModeState,
224
+ ModelInfo,
225
+ SlashCommand,
226
+ SDKMessage,
227
+ SDKUserMessage,
228
+ SDKResultMessage,
229
+ } from './sdk/coreTypes.generated.js'
230
+
231
+ export type SDKControlInitializeResponse = {
232
+ commands: SlashCommand[]
233
+ agents: AgentInfo[]
234
+ output_style: string
235
+ available_output_styles: string[]
236
+ models: ModelInfo[]
237
+ account: AccountInfo
238
+ /** @internal CLI process PID for tmux socket isolation. */
239
+ pid?: number
240
+ fast_mode_state?: FastModeState
241
+ }
242
+
243
+ // ============================================================================
244
+ // Query types
245
+ // ============================================================================
246
+
247
+ export type QueryPermissionMode =
248
+ | 'default'
249
+ | 'plan'
250
+ | 'auto-accept'
251
+ | 'bypass-permissions'
252
+ | 'bypassPermissions'
253
+ | 'full-access'
254
+ | 'fullAccess'
255
+ | 'acceptEdits'
256
+
257
+ export type QueryOptions = {
258
+ cwd: string
259
+ additionalDirectories?: string[]
260
+ model?: string
261
+ sessionId?: string
262
+ /** Fork the session before resuming (requires sessionId). */
263
+ fork?: boolean
264
+ /** Alias for fork. When true, resumed session forks to a new session ID. */
265
+ forkSession?: boolean
266
+ /** Resume the most recent session for this cwd (no sessionId needed). */
267
+ continue?: boolean
268
+ resume?: string
269
+ /** When resuming, resume messages up to and including this message UUID. */
270
+ resumeSessionAt?: string
271
+ permissionMode?: QueryPermissionMode
272
+ abortController?: AbortController
273
+ executable?: string
274
+ allowDangerouslySkipPermissions?: boolean
275
+ disallowedTools?: string[]
276
+ hooks?: Record<string, unknown[]>
277
+ mcpServers?: Record<string, unknown>
278
+ settings?: {
279
+ env?: Record<string, string>
280
+ attribution?: { commit: string; pr: string }
281
+ }
282
+ /** Environment variables to apply during query execution. Overrides process.env. Takes precedence over settings.env. */
283
+ env?: Record<string, string | undefined>
284
+ /**
285
+ * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
286
+ * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
287
+ *
288
+ * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
289
+ * is provided, ALL tool uses are denied. You MUST provide at least one of
290
+ * these callbacks to allow tool execution.
291
+ */
292
+ canUseTool?: (
293
+ name: string,
294
+ input: unknown,
295
+ options?: { toolUseID?: string },
296
+ ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
297
+ /**
298
+ * Callback invoked when a tool needs permission approval. The host receives
299
+ * the request immediately and can resolve it by calling
300
+ * `query.respondToPermission(toolUseId, decision)` before the timeout.
301
+ * If omitted, tools that require permission fall through to the default
302
+ * permission logic immediately (no timeout).
303
+ */
304
+ onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
305
+ systemPrompt?:
306
+ | string
307
+ | { type: 'preset'; preset: string; append?: string }
308
+ | { type: 'custom'; content: string }
309
+ /** Agent definitions to register with the query engine. */
310
+ agents?: Record<string, {
311
+ description?: string
312
+ prompt: string
313
+ /**
314
+ * Tool allowlist for this agent. If omitted or set to ['*'], the agent can use
315
+ * all tools available to subagents after disallowedTools is applied.
316
+ */
317
+ tools?: string[]
318
+ /** Tool denylist for this agent. Deny entries always override tools entries. */
319
+ disallowedTools?: string[]
320
+ model?: string
321
+ maxTurns?: number
322
+ maxSteps?: number
323
+ }>
324
+ settingSources?: string[]
325
+ /** When true, yields stream_event messages for token-by-token streaming. */
326
+ includePartialMessages?: boolean
327
+ /** @internal Timeout in ms for permission request resolution. Default 30000. */
328
+ _permissionTimeoutMs?: number
329
+ stderr?: (data: string) => void
330
+ }
331
+
332
+ export interface Query {
333
+ readonly sessionId: string
334
+ [Symbol.asyncIterator](): AsyncIterator<SDKMessage>
335
+ setModel(model: string): Promise<void>
336
+ setPermissionMode(mode: QueryPermissionMode): Promise<void>
337
+ close(): void
338
+ interrupt(): void
339
+ respondToPermission(toolUseId: string, decision: PermissionResult): void
340
+ /** Check if file rewind is possible. */
341
+ rewindFiles(): RewindFilesResult
342
+ /** Actually perform the file rewind. Returns files changed and diff stats. */
343
+ rewindFilesAsync(): Promise<RewindFilesResult>
344
+ supportedCommands(): string[]
345
+ supportedModels(): string[]
346
+ supportedAgents(): string[]
347
+ mcpServerStatus(): McpServerStatus[]
348
+ accountInfo(): Promise<{ apiKeySource: ApiKeySource; [key: string]: unknown }>
349
+ setMaxThinkingTokens(tokens: number): void
350
+ }
351
+
352
+ /**
353
+ * Permission request message emitted when a tool needs permission approval.
354
+ * Hosts can respond via respondToPermission() using the request_id.
355
+ */
356
+ export type SDKPermissionRequestMessage = {
357
+ type: 'permission_request'
358
+ request_id: string
359
+ tool_name: string
360
+ tool_use_id: string
361
+ input: Record<string, unknown>
362
+ uuid: string
363
+ session_id: string
364
+ }
365
+
366
+ export type SDKPermissionTimeoutMessage = {
367
+ type: 'permission_timeout'
368
+ tool_name: string
369
+ tool_use_id: string
370
+ timed_out_after_ms: number
371
+ uuid: string
372
+ session_id: string
373
+ }
374
+
375
+ /**
376
+ * A message emitted when agent definitions fail to load.
377
+ * This allows hosts to detect configuration issues that would otherwise
378
+ * be silently logged to console.warn.
379
+ *
380
+ * Note: Agent load failures are non-fatal — the query continues without agents.
381
+ */
382
+ export type SDKAgentLoadFailureMessage = {
383
+ type: 'agent_load_failure'
384
+ stage: 'definitions' | 'injection'
385
+ error_message: string
386
+ }
387
+
388
+ // ============================================================================
389
+ // Permission resolve decision (SDK-specific)
390
+ // ============================================================================
391
+
392
+ /**
393
+ * Decision returned by permission resolution.
394
+ * Used by respondToPermission() and internal permission handling.
395
+ */
396
+ export type PermissionResolveDecision =
397
+ | { behavior: 'allow'; updatedInput?: Record<string, unknown> }
398
+ | { behavior: 'deny'; message: string; decisionReason: { type: 'mode'; mode: string } }
399
+
400
+ // ============================================================================
401
+ // V2 API types
402
+ // ============================================================================
403
+
404
+ export type SDKSessionOptions = {
405
+ cwd: string
406
+ model?: string
407
+ permissionMode?: QueryPermissionMode
408
+ allowDangerouslySkipPermissions?: boolean
409
+ abortController?: AbortController
410
+ /**
411
+ * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
412
+ * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
413
+ *
414
+ * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
415
+ * is provided, ALL tool uses are denied. You MUST provide at least one of
416
+ * these callbacks to allow tool execution.
417
+ */
418
+ canUseTool?: (
419
+ name: string,
420
+ input: unknown,
421
+ options?: { toolUseID?: string },
422
+ ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
423
+ /** MCP server configurations for this session. */
424
+ mcpServers?: Record<string, unknown>
425
+ /**
426
+ * Callback invoked when a tool needs permission approval. The host receives
427
+ * the request immediately and can resolve it via respondToPermission().
428
+ */
429
+ onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
430
+ /** Tools to disallow (blanket deny by tool name). */
431
+ disallowedTools?: string[]
432
+ /** Agent definitions to register with the session engine. */
433
+ agents?: Record<string, {
434
+ description?: string
435
+ prompt: string
436
+ /**
437
+ * Tool allowlist for this agent. If omitted or set to ['*'], the agent can use
438
+ * all tools available to subagents after disallowedTools is applied.
439
+ */
440
+ tools?: string[]
441
+ /** Tool denylist for this agent. Deny entries always override tools entries. */
442
+ disallowedTools?: string[]
443
+ model?: string
444
+ maxTurns?: number
445
+ maxSteps?: number
446
+ }>
447
+ }
448
+
449
+ export interface SDKSession {
450
+ sessionId: string
451
+ sendMessage(content: string): AsyncIterable<SDKMessage>
452
+ getMessages(): SDKMessage[]
453
+ interrupt(): void
454
+ /** Close the session and release resources (MCP connections, etc.). */
455
+ close(): void
456
+ /** Respond to a pending permission prompt. */
457
+ respondToPermission(toolUseId: string, decision: PermissionResult): void
458
+ }
459
+
460
+ // ============================================================================
461
+ // MCP tool types
462
+ // ============================================================================
463
+
464
+ export interface SdkMcpToolDefinition<Schema = unknown> {
465
+ name: string
466
+ description: string
467
+ inputSchema: Schema
468
+ handler: (args: any, extra: unknown) => Promise<CallToolResult>
469
+ annotations?: ToolAnnotations
470
+ searchHint?: string
471
+ alwaysLoad?: boolean
472
+ }
473
+
474
+ // ============================================================================
475
+ // Session functions
476
+ // ============================================================================
477
+
478
+ export function listSessions(
479
+ options?: ListSessionsOptions,
480
+ ): Promise<SDKSessionInfo[]>
481
+
482
+ export function getSessionInfo(
483
+ sessionId: string,
484
+ options?: GetSessionInfoOptions,
485
+ ): Promise<SDKSessionInfo | undefined>
486
+
487
+ export function getSessionMessages(
488
+ sessionId: string,
489
+ options?: GetSessionMessagesOptions,
490
+ ): Promise<SessionMessage[]>
491
+
492
+ export function renameSession(
493
+ sessionId: string,
494
+ title: string,
495
+ options?: SessionMutationOptions,
496
+ ): Promise<void>
497
+
498
+ export function tagSession(
499
+ sessionId: string,
500
+ tag: string | null,
501
+ options?: SessionMutationOptions,
502
+ ): Promise<void>
503
+
504
+ export function forkSession(
505
+ sessionId: string,
506
+ options?: ForkSessionOptions,
507
+ ): Promise<ForkSessionResult>
508
+
509
+ export function deleteSession(
510
+ sessionId: string,
511
+ options?: SessionMutationOptions,
512
+ ): Promise<void>
513
+
514
+ // ============================================================================
515
+ // Query functions
516
+ // ============================================================================
517
+
518
+ export function query(params: {
519
+ prompt: string | AsyncIterable<SDKUserMessage>
520
+ options?: QueryOptions
521
+ }): Query
522
+
523
+ export function queryAsync(params: {
524
+ prompt: string | AsyncIterable<SDKUserMessage>
525
+ options?: QueryOptions
526
+ }): Promise<Query>
527
+
528
+ // ============================================================================
529
+ // V2 API functions
530
+ // ============================================================================
531
+
532
+ export function unstable_v2_createSession(options: SDKSessionOptions): SDKSession
533
+
534
+ export function unstable_v2_resumeSession(
535
+ sessionId: string,
536
+ options: SDKSessionOptions,
537
+ ): Promise<SDKSession>
538
+
539
+ export function unstable_v2_prompt(
540
+ message: string,
541
+ options: SDKSessionOptions,
542
+ ): Promise<SDKResultMessage>
543
+
544
+ // ============================================================================
545
+ // MCP tool functions
546
+ // ============================================================================
547
+
548
+ export function tool<Schema = unknown>(
549
+ name: string,
550
+ description: string,
551
+ inputSchema: Schema,
552
+ handler: (args: any, extra: unknown) => Promise<CallToolResult>,
553
+ extras?: {
554
+ annotations?: ToolAnnotations
555
+ searchHint?: string
556
+ alwaysLoad?: boolean
557
+ },
558
+ ): SdkMcpToolDefinition<Schema>
559
+
560
+ /**
561
+ * MCP server transport configuration types.
562
+ * Matches McpServerConfigForProcessTransport from coreTypes.generated.ts.
563
+ */
564
+ export type SdkMcpStdioConfig = {
565
+ type?: "stdio"
566
+ command: string
567
+ args?: string[]
568
+ env?: Record<string, string>
569
+ }
570
+
571
+ export type SdkMcpSSEConfig = {
572
+ type: "sse"
573
+ url: string
574
+ headers?: Record<string, string>
575
+ }
576
+
577
+ export type SdkMcpHttpConfig = {
578
+ type: "http"
579
+ url: string
580
+ headers?: Record<string, string>
581
+ }
582
+
583
+ export type SdkMcpSdkConfig = {
584
+ type: "sdk"
585
+ name: string
586
+ /** In-process tool definitions created via the tool() helper. */
587
+ tools?: SdkMcpToolDefinition[]
588
+ }
589
+
590
+ export type SdkMcpServerConfig = SdkMcpStdioConfig | SdkMcpSSEConfig | SdkMcpHttpConfig | SdkMcpSdkConfig
591
+
592
+ /**
593
+ * Scoped MCP server config with session scope.
594
+ * Returned by createSdkMcpServer() for use with mcpServers option.
595
+ */
596
+ export type SdkScopedMcpServerConfig = SdkMcpServerConfig & {
597
+ scope: "session"
598
+ }
599
+
600
+ /**
601
+ * Wraps an MCP server configuration for use with the SDK.
602
+ * Adds the 'session' scope marker so the SDK knows this server
603
+ * should be connected per-session (not globally).
604
+ *
605
+ * @param config - MCP server config (stdio, sse, http, or sdk type)
606
+ * @returns Scoped config with scope: 'session' added
607
+ *
608
+ * @example
609
+ * ```typescript
610
+ * const server = createSdkMcpServer({
611
+ * type: 'stdio',
612
+ * command: 'npx',
613
+ * args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
614
+ * })
615
+ * const session = unstable_v2_createSession({
616
+ * cwd: '/my/project',
617
+ * mcpServers: { 'fs': server },
618
+ * })
619
+ * ```
620
+ */
621
+ export function createSdkMcpServer(config: SdkMcpServerConfig): SdkScopedMcpServerConfig