@makerbi/openclaude 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,555 @@
1
+ // Type declarations for @gitlawb/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' | '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
+ SDKMessage,
191
+ SDKUserMessage,
192
+ SDKResultMessage,
193
+ } from './sdk/coreTypes.generated.js'
194
+
195
+ export type {
196
+ SDKMessage,
197
+ SDKUserMessage,
198
+ SDKResultMessage,
199
+ } from './sdk/coreTypes.generated.js'
200
+
201
+ // ============================================================================
202
+ // Query types
203
+ // ============================================================================
204
+
205
+ export type QueryPermissionMode =
206
+ | 'default'
207
+ | 'plan'
208
+ | 'auto-accept'
209
+ | 'bypass-permissions'
210
+ | 'bypassPermissions'
211
+ | 'acceptEdits'
212
+
213
+ export type QueryOptions = {
214
+ cwd: string
215
+ additionalDirectories?: string[]
216
+ model?: string
217
+ sessionId?: string
218
+ /** Fork the session before resuming (requires sessionId). */
219
+ fork?: boolean
220
+ /** Alias for fork. When true, resumed session forks to a new session ID. */
221
+ forkSession?: boolean
222
+ /** Resume the most recent session for this cwd (no sessionId needed). */
223
+ continue?: boolean
224
+ resume?: string
225
+ /** When resuming, resume messages up to and including this message UUID. */
226
+ resumeSessionAt?: string
227
+ permissionMode?: QueryPermissionMode
228
+ abortController?: AbortController
229
+ executable?: string
230
+ allowDangerouslySkipPermissions?: boolean
231
+ disallowedTools?: string[]
232
+ hooks?: Record<string, unknown[]>
233
+ mcpServers?: Record<string, unknown>
234
+ settings?: {
235
+ env?: Record<string, string>
236
+ attribution?: { commit: string; pr: string }
237
+ }
238
+ /** Environment variables to apply during query execution. Overrides process.env. Takes precedence over settings.env. */
239
+ env?: Record<string, string | undefined>
240
+ /**
241
+ * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
242
+ * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
243
+ *
244
+ * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
245
+ * is provided, ALL tool uses are denied. You MUST provide at least one of
246
+ * these callbacks to allow tool execution.
247
+ */
248
+ canUseTool?: (
249
+ name: string,
250
+ input: unknown,
251
+ options?: { toolUseID?: string },
252
+ ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
253
+ /**
254
+ * Callback invoked when a tool needs permission approval. The host receives
255
+ * the request immediately and can resolve it by calling
256
+ * `query.respondToPermission(toolUseId, decision)` before the timeout.
257
+ * If omitted, tools that require permission fall through to the default
258
+ * permission logic immediately (no timeout).
259
+ */
260
+ onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
261
+ systemPrompt?:
262
+ | string
263
+ | { type: 'preset'; preset: string; append?: string }
264
+ | { type: 'custom'; content: string }
265
+ /** Agent definitions to register with the query engine. */
266
+ agents?: Record<string, {
267
+ description: string
268
+ prompt: string
269
+ tools?: string[]
270
+ disallowedTools?: string[]
271
+ model?: string
272
+ maxTurns?: number
273
+ }>
274
+ settingSources?: string[]
275
+ /** When true, yields stream_event messages for token-by-token streaming. */
276
+ includePartialMessages?: boolean
277
+ /** @internal Timeout in ms for permission request resolution. Default 30000. */
278
+ _permissionTimeoutMs?: number
279
+ stderr?: (data: string) => void
280
+ }
281
+
282
+ export interface Query {
283
+ readonly sessionId: string
284
+ [Symbol.asyncIterator](): AsyncIterator<SDKMessage>
285
+ setModel(model: string): Promise<void>
286
+ setPermissionMode(mode: QueryPermissionMode): Promise<void>
287
+ close(): void
288
+ interrupt(): void
289
+ respondToPermission(toolUseId: string, decision: PermissionResult): void
290
+ /** Check if file rewind is possible. */
291
+ rewindFiles(): RewindFilesResult
292
+ /** Actually perform the file rewind. Returns files changed and diff stats. */
293
+ rewindFilesAsync(): Promise<RewindFilesResult>
294
+ supportedCommands(): string[]
295
+ supportedModels(): string[]
296
+ supportedAgents(): string[]
297
+ mcpServerStatus(): McpServerStatus[]
298
+ accountInfo(): Promise<{ apiKeySource: ApiKeySource; [key: string]: unknown }>
299
+ setMaxThinkingTokens(tokens: number): void
300
+ }
301
+
302
+ /**
303
+ * Permission request message emitted when a tool needs permission approval.
304
+ * Hosts can respond via respondToPermission() using the request_id.
305
+ */
306
+ export type SDKPermissionRequestMessage = {
307
+ type: 'permission_request'
308
+ request_id: string
309
+ tool_name: string
310
+ tool_use_id: string
311
+ input: Record<string, unknown>
312
+ uuid: string
313
+ session_id: string
314
+ }
315
+
316
+ export type SDKPermissionTimeoutMessage = {
317
+ type: 'permission_timeout'
318
+ tool_name: string
319
+ tool_use_id: string
320
+ timed_out_after_ms: number
321
+ uuid: string
322
+ session_id: string
323
+ }
324
+
325
+ /**
326
+ * A message emitted when agent definitions fail to load.
327
+ * This allows hosts to detect configuration issues that would otherwise
328
+ * be silently logged to console.warn.
329
+ *
330
+ * Note: Agent load failures are non-fatal — the query continues without agents.
331
+ */
332
+ export type SDKAgentLoadFailureMessage = {
333
+ type: 'agent_load_failure'
334
+ stage: 'definitions' | 'injection'
335
+ error_message: string
336
+ }
337
+
338
+ // ============================================================================
339
+ // Permission resolve decision (SDK-specific)
340
+ // ============================================================================
341
+
342
+ /**
343
+ * Decision returned by permission resolution.
344
+ * Used by respondToPermission() and internal permission handling.
345
+ */
346
+ export type PermissionResolveDecision =
347
+ | { behavior: 'allow'; updatedInput?: Record<string, unknown> }
348
+ | { behavior: 'deny'; message: string; decisionReason: { type: 'mode'; mode: string } }
349
+
350
+ // ============================================================================
351
+ // V2 API types
352
+ // ============================================================================
353
+
354
+ export type SDKSessionOptions = {
355
+ cwd: string
356
+ model?: string
357
+ permissionMode?: QueryPermissionMode
358
+ abortController?: AbortController
359
+ /**
360
+ * Callback invoked before each tool use. Return `{ behavior: 'allow' }` to
361
+ * permit the call or `{ behavior: 'deny', message?: string }` to reject it.
362
+ *
363
+ * **Secure-by-default**: If neither `canUseTool` nor `onPermissionRequest`
364
+ * is provided, ALL tool uses are denied. You MUST provide at least one of
365
+ * these callbacks to allow tool execution.
366
+ */
367
+ canUseTool?: (
368
+ name: string,
369
+ input: unknown,
370
+ options?: { toolUseID?: string },
371
+ ) => Promise<{ behavior: 'allow' | 'deny'; message?: string; updatedInput?: unknown }>
372
+ /** MCP server configurations for this session. */
373
+ mcpServers?: Record<string, unknown>
374
+ /**
375
+ * Callback invoked when a tool needs permission approval. The host receives
376
+ * the request immediately and can resolve it via respondToPermission().
377
+ */
378
+ onPermissionRequest?: (message: SDKPermissionRequestMessage) => void
379
+ /** Tools to disallow (blanket deny by tool name). */
380
+ disallowedTools?: string[]
381
+ }
382
+
383
+ export interface SDKSession {
384
+ sessionId: string
385
+ sendMessage(content: string): AsyncIterable<SDKMessage>
386
+ getMessages(): SDKMessage[]
387
+ interrupt(): void
388
+ /** Close the session and release resources (MCP connections, etc.). */
389
+ close(): void
390
+ /** Respond to a pending permission prompt. */
391
+ respondToPermission(toolUseId: string, decision: PermissionResult): void
392
+ }
393
+
394
+ // ============================================================================
395
+ // MCP tool types
396
+ // ============================================================================
397
+
398
+ export interface SdkMcpToolDefinition<Schema = any> {
399
+ name: string
400
+ description: string
401
+ inputSchema: Schema
402
+ handler: (args: any, extra: unknown) => Promise<any>
403
+ annotations?: any
404
+ searchHint?: string
405
+ alwaysLoad?: boolean
406
+ }
407
+
408
+ // ============================================================================
409
+ // Session functions
410
+ // ============================================================================
411
+
412
+ export function listSessions(
413
+ options?: ListSessionsOptions,
414
+ ): Promise<SDKSessionInfo[]>
415
+
416
+ export function getSessionInfo(
417
+ sessionId: string,
418
+ options?: GetSessionInfoOptions,
419
+ ): Promise<SDKSessionInfo | undefined>
420
+
421
+ export function getSessionMessages(
422
+ sessionId: string,
423
+ options?: GetSessionMessagesOptions,
424
+ ): Promise<SessionMessage[]>
425
+
426
+ export function renameSession(
427
+ sessionId: string,
428
+ title: string,
429
+ options?: SessionMutationOptions,
430
+ ): Promise<void>
431
+
432
+ export function tagSession(
433
+ sessionId: string,
434
+ tag: string | null,
435
+ options?: SessionMutationOptions,
436
+ ): Promise<void>
437
+
438
+ export function forkSession(
439
+ sessionId: string,
440
+ options?: ForkSessionOptions,
441
+ ): Promise<ForkSessionResult>
442
+
443
+ export function deleteSession(
444
+ sessionId: string,
445
+ options?: SessionMutationOptions,
446
+ ): Promise<void>
447
+
448
+ // ============================================================================
449
+ // Query functions
450
+ // ============================================================================
451
+
452
+ export function query(params: {
453
+ prompt: string | AsyncIterable<SDKUserMessage>
454
+ options?: QueryOptions
455
+ }): Query
456
+
457
+ export function queryAsync(params: {
458
+ prompt: string | AsyncIterable<SDKUserMessage>
459
+ options?: QueryOptions
460
+ }): Promise<Query>
461
+
462
+ // ============================================================================
463
+ // V2 API functions
464
+ // ============================================================================
465
+
466
+ export function unstable_v2_createSession(options: SDKSessionOptions): SDKSession
467
+
468
+ export function unstable_v2_resumeSession(
469
+ sessionId: string,
470
+ options: SDKSessionOptions,
471
+ ): Promise<SDKSession>
472
+
473
+ export function unstable_v2_prompt(
474
+ message: string,
475
+ options: SDKSessionOptions,
476
+ ): Promise<SDKResultMessage>
477
+
478
+ // ============================================================================
479
+ // MCP tool functions
480
+ // ============================================================================
481
+
482
+ export function tool<Schema = any>(
483
+ name: string,
484
+ description: string,
485
+ inputSchema: Schema,
486
+ handler: (args: any, extra: unknown) => Promise<any>,
487
+ extras?: {
488
+ annotations?: any
489
+ searchHint?: string
490
+ alwaysLoad?: boolean
491
+ },
492
+ ): SdkMcpToolDefinition<Schema>
493
+
494
+ /**
495
+ * MCP server transport configuration types.
496
+ * Matches McpServerConfigForProcessTransport from coreTypes.generated.ts.
497
+ */
498
+ export type SdkMcpStdioConfig = {
499
+ type?: "stdio"
500
+ command: string
501
+ args?: string[]
502
+ env?: Record<string, string>
503
+ }
504
+
505
+ export type SdkMcpSSEConfig = {
506
+ type: "sse"
507
+ url: string
508
+ headers?: Record<string, string>
509
+ }
510
+
511
+ export type SdkMcpHttpConfig = {
512
+ type: "http"
513
+ url: string
514
+ headers?: Record<string, string>
515
+ }
516
+
517
+ export type SdkMcpSdkConfig = {
518
+ type: "sdk"
519
+ name: string
520
+ /** In-process tool definitions created via the tool() helper. */
521
+ tools?: SdkMcpToolDefinition[]
522
+ }
523
+
524
+ export type SdkMcpServerConfig = SdkMcpStdioConfig | SdkMcpSSEConfig | SdkMcpHttpConfig | SdkMcpSdkConfig
525
+
526
+ /**
527
+ * Scoped MCP server config with session scope.
528
+ * Returned by createSdkMcpServer() for use with mcpServers option.
529
+ */
530
+ export type SdkScopedMcpServerConfig = SdkMcpServerConfig & {
531
+ scope: "session"
532
+ }
533
+
534
+ /**
535
+ * Wraps an MCP server configuration for use with the SDK.
536
+ * Adds the 'session' scope marker so the SDK knows this server
537
+ * should be connected per-session (not globally).
538
+ *
539
+ * @param config - MCP server config (stdio, sse, http, or sdk type)
540
+ * @returns Scoped config with scope: 'session' added
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * const server = createSdkMcpServer({
545
+ * type: 'stdio',
546
+ * command: 'npx',
547
+ * args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
548
+ * })
549
+ * const session = unstable_v2_createSession({
550
+ * cwd: '/my/project',
551
+ * mcpServers: { 'fs': server },
552
+ * })
553
+ * ```
554
+ */
555
+ export function createSdkMcpServer(config: SdkMcpServerConfig): SdkScopedMcpServerConfig