@twigpine/openclaude 0.0.0-stage → 0.32.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,621 @@
1
+ // Type declarations for @twigpine/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
@@ -0,0 +1,3 @@
1
+ /*! node-domexception shim. Re-exports the platform-native DOMException. */
2
+
3
+ module.exports = globalThis.DOMException
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "node-domexception",
3
+ "version": "1.0.0",
4
+ "description": "Stub shim: re-exports the platform-native DOMException. Replaces the deprecated node-domexception polyfill.",
5
+ "main": "index.js",
6
+ "type": "commonjs",
7
+ "license": "MIT"
8
+ }