@chucky.cloud/sdk 0.2.7 → 0.3.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.
Files changed (94) hide show
  1. package/dist/browser.cjs +1361 -0
  2. package/dist/browser.cjs.map +1 -0
  3. package/dist/browser.d.cts +1 -0
  4. package/dist/browser.d.ts +1 -8
  5. package/dist/browser.js +1278 -11
  6. package/dist/browser.js.map +1 -1
  7. package/dist/index.cjs +1361 -0
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.cts +1973 -0
  10. package/dist/index.d.ts +1953 -48
  11. package/dist/index.js +1278 -72
  12. package/dist/index.js.map +1 -1
  13. package/dist/node.cjs +1361 -0
  14. package/dist/node.cjs.map +1 -0
  15. package/dist/node.d.cts +1 -0
  16. package/dist/node.d.ts +1 -8
  17. package/dist/node.js +1278 -10
  18. package/dist/node.js.map +1 -1
  19. package/package.json +13 -7
  20. package/dist/browser.d.ts.map +0 -1
  21. package/dist/client/ChuckyClient.d.ts +0 -141
  22. package/dist/client/ChuckyClient.d.ts.map +0 -1
  23. package/dist/client/ChuckyClient.js +0 -209
  24. package/dist/client/ChuckyClient.js.map +0 -1
  25. package/dist/client/Session.d.ts +0 -167
  26. package/dist/client/Session.d.ts.map +0 -1
  27. package/dist/client/Session.js +0 -392
  28. package/dist/client/Session.js.map +0 -1
  29. package/dist/client/index.d.ts +0 -10
  30. package/dist/client/index.d.ts.map +0 -1
  31. package/dist/client/index.js +0 -9
  32. package/dist/client/index.js.map +0 -1
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/node.d.ts.map +0 -1
  35. package/dist/tools/McpServer.d.ts +0 -117
  36. package/dist/tools/McpServer.d.ts.map +0 -1
  37. package/dist/tools/McpServer.js +0 -142
  38. package/dist/tools/McpServer.js.map +0 -1
  39. package/dist/tools/index.d.ts +0 -9
  40. package/dist/tools/index.d.ts.map +0 -1
  41. package/dist/tools/index.js +0 -8
  42. package/dist/tools/index.js.map +0 -1
  43. package/dist/tools/tool.d.ts +0 -146
  44. package/dist/tools/tool.d.ts.map +0 -1
  45. package/dist/tools/tool.js +0 -232
  46. package/dist/tools/tool.js.map +0 -1
  47. package/dist/transport/Transport.d.ts +0 -82
  48. package/dist/transport/Transport.d.ts.map +0 -1
  49. package/dist/transport/Transport.js +0 -47
  50. package/dist/transport/Transport.js.map +0 -1
  51. package/dist/transport/WebSocketTransport.d.ts +0 -78
  52. package/dist/transport/WebSocketTransport.d.ts.map +0 -1
  53. package/dist/transport/WebSocketTransport.js +0 -258
  54. package/dist/transport/WebSocketTransport.js.map +0 -1
  55. package/dist/transport/index.d.ts +0 -10
  56. package/dist/transport/index.d.ts.map +0 -1
  57. package/dist/transport/index.js +0 -8
  58. package/dist/transport/index.js.map +0 -1
  59. package/dist/types/index.d.ts +0 -12
  60. package/dist/types/index.d.ts.map +0 -1
  61. package/dist/types/index.js +0 -8
  62. package/dist/types/index.js.map +0 -1
  63. package/dist/types/messages.d.ts +0 -327
  64. package/dist/types/messages.d.ts.map +0 -1
  65. package/dist/types/messages.js +0 -133
  66. package/dist/types/messages.js.map +0 -1
  67. package/dist/types/options.d.ts +0 -212
  68. package/dist/types/options.d.ts.map +0 -1
  69. package/dist/types/options.js +0 -8
  70. package/dist/types/options.js.map +0 -1
  71. package/dist/types/results.d.ts +0 -186
  72. package/dist/types/results.d.ts.map +0 -1
  73. package/dist/types/results.js +0 -7
  74. package/dist/types/results.js.map +0 -1
  75. package/dist/types/token.d.ts +0 -124
  76. package/dist/types/token.d.ts.map +0 -1
  77. package/dist/types/token.js +0 -7
  78. package/dist/types/token.js.map +0 -1
  79. package/dist/types/tools.d.ts +0 -234
  80. package/dist/types/tools.d.ts.map +0 -1
  81. package/dist/types/tools.js +0 -31
  82. package/dist/types/tools.js.map +0 -1
  83. package/dist/utils/errors.d.ts +0 -80
  84. package/dist/utils/errors.d.ts.map +0 -1
  85. package/dist/utils/errors.js +0 -158
  86. package/dist/utils/errors.js.map +0 -1
  87. package/dist/utils/index.d.ts +0 -8
  88. package/dist/utils/index.d.ts.map +0 -1
  89. package/dist/utils/index.js +0 -8
  90. package/dist/utils/index.js.map +0 -1
  91. package/dist/utils/token.d.ts +0 -104
  92. package/dist/utils/token.d.ts.map +0 -1
  93. package/dist/utils/token.js +0 -209
  94. package/dist/utils/token.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,68 +1,1973 @@
1
1
  /**
2
- * @chucky.cloud/sdk
2
+ * Tool Definition Types
3
3
  *
4
- * SDK for interacting with Chucky sandbox - supports both browser and Node.js.
4
+ * Types for defining tools that can be executed by Claude.
5
+ * Supports both server-side and browser-side execution.
6
+ */
7
+ /**
8
+ * JSON Schema property types
9
+ */
10
+ type JsonSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
11
+ /**
12
+ * JSON Schema property definition
13
+ */
14
+ interface JsonSchemaProperty {
15
+ /** Property type */
16
+ type: JsonSchemaType;
17
+ /** Human-readable description */
18
+ description?: string;
19
+ /** Enumeration of allowed values */
20
+ enum?: string[];
21
+ /** Default value */
22
+ default?: unknown;
23
+ /** For arrays: schema of array items */
24
+ items?: JsonSchemaProperty;
25
+ /** For objects: nested properties */
26
+ properties?: Record<string, JsonSchemaProperty>;
27
+ /** For objects: required property names */
28
+ required?: string[];
29
+ /** Minimum value (for numbers) */
30
+ minimum?: number;
31
+ /** Maximum value (for numbers) */
32
+ maximum?: number;
33
+ /** Minimum length (for strings/arrays) */
34
+ minLength?: number;
35
+ /** Maximum length (for strings/arrays) */
36
+ maxLength?: number;
37
+ /** Pattern (for strings) */
38
+ pattern?: string;
39
+ }
40
+ /**
41
+ * JSON Schema for tool input
42
+ */
43
+ interface ToolInputSchema {
44
+ /** Always 'object' for tool inputs */
45
+ type: 'object';
46
+ /** Property definitions */
47
+ properties: Record<string, JsonSchemaProperty>;
48
+ /** Required property names */
49
+ required?: string[];
50
+ /** Allow additional properties */
51
+ additionalProperties?: boolean;
52
+ }
53
+ /**
54
+ * Tool content types for results
55
+ */
56
+ type ToolContentType = 'text' | 'image' | 'resource';
57
+ /**
58
+ * Text content in tool result (MCP format)
59
+ */
60
+ interface ToolTextContent {
61
+ type: 'text';
62
+ text: string;
63
+ }
64
+ /**
65
+ * Image content in tool result (MCP format)
66
+ */
67
+ interface ToolImageContent {
68
+ type: 'image';
69
+ /** Base64-encoded image data */
70
+ data: string;
71
+ /** MIME type (e.g., 'image/png') */
72
+ mimeType: string;
73
+ }
74
+ /**
75
+ * Resource content in tool result
76
+ */
77
+ interface ResourceContent {
78
+ type: 'resource';
79
+ /** Resource URI */
80
+ uri: string;
81
+ /** MIME type */
82
+ mimeType?: string;
83
+ /** Resource text content */
84
+ text?: string;
85
+ /** Resource binary data (base64) */
86
+ blob?: string;
87
+ }
88
+ /**
89
+ * Union type for all tool content
90
+ */
91
+ type ToolContent = ToolTextContent | ToolImageContent | ResourceContent;
92
+ /**
93
+ * Tool execution result
94
+ */
95
+ interface ToolResult {
96
+ /** Result content */
97
+ content: ToolContent[];
98
+ /** Whether this is an error result */
99
+ isError?: boolean;
100
+ }
101
+ /**
102
+ * Where the tool should be executed
103
+ */
104
+ type ToolExecutionLocation = 'server' | 'browser';
105
+ /**
106
+ * Tool handler function type
107
+ */
108
+ type ToolHandler<TInput = Record<string, unknown>> = (input: TInput) => ToolResult | Promise<ToolResult>;
109
+ /**
110
+ * Tool definition
111
+ */
112
+ interface ToolDefinition<TInput = Record<string, unknown>> {
113
+ /** Unique tool name */
114
+ name: string;
115
+ /** Human-readable description of what the tool does */
116
+ description: string;
117
+ /** JSON Schema defining the input parameters */
118
+ inputSchema: ToolInputSchema;
119
+ /**
120
+ * Where the tool should be executed
121
+ * @default 'server'
122
+ */
123
+ executeIn?: ToolExecutionLocation;
124
+ /**
125
+ * Handler function (required for browser tools, optional for server tools)
126
+ */
127
+ handler?: ToolHandler<TInput>;
128
+ }
129
+ /**
130
+ * MCP Server with client-side tools (handlers run in your app)
131
+ * This is our custom format - bridge converts to SDK format
132
+ */
133
+ interface McpClientToolsServer {
134
+ /** Server name */
135
+ name: string;
136
+ /** Server version */
137
+ version?: string;
138
+ /** Tools with handlers that execute client-side */
139
+ tools: ToolDefinition[];
140
+ }
141
+ /**
142
+ * MCP Stdio server configuration
143
+ */
144
+ interface McpStdioServerConfig {
145
+ /** Server name */
146
+ name: string;
147
+ /** Server type */
148
+ type?: 'stdio';
149
+ /** Command to run */
150
+ command: string;
151
+ /** Command arguments */
152
+ args?: string[];
153
+ /** Environment variables */
154
+ env?: Record<string, string>;
155
+ }
156
+ /**
157
+ * MCP SSE server configuration
158
+ */
159
+ interface McpSSEServerConfig {
160
+ /** Server name */
161
+ name: string;
162
+ /** Server type */
163
+ type: 'sse';
164
+ /** SSE endpoint URL */
165
+ url: string;
166
+ /** Request headers */
167
+ headers?: Record<string, string>;
168
+ }
169
+ /**
170
+ * MCP HTTP server configuration
171
+ */
172
+ interface McpHttpServerConfig {
173
+ /** Server name */
174
+ name: string;
175
+ /** Server type */
176
+ type: 'http';
177
+ /** HTTP endpoint URL */
178
+ url: string;
179
+ /** Request headers */
180
+ headers?: Record<string, string>;
181
+ }
182
+ /**
183
+ * MCP Server definition - all supported server types
184
+ * Array format - bridge converts to Record<string, config> for official SDK
185
+ */
186
+ type McpServerDefinition = McpClientToolsServer | McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig;
187
+ /**
188
+ * Tool preset configuration
189
+ */
190
+ interface ToolPreset {
191
+ type: 'preset';
192
+ preset: 'claude_code';
193
+ }
194
+ /**
195
+ * Tools configuration - either allowlist of names or preset
196
+ */
197
+ type ToolsConfig = string[] | ToolPreset;
198
+ /**
199
+ * Tool call from the model
200
+ */
201
+ interface ToolCall {
202
+ /** Unique call ID */
203
+ callId: string;
204
+ /** Tool name */
205
+ toolName: string;
206
+ /** Input arguments */
207
+ input: Record<string, unknown>;
208
+ }
209
+ /**
210
+ * Tool call response
211
+ */
212
+ interface ToolCallResponse {
213
+ /** Call ID (must match the tool call) */
214
+ callId: string;
215
+ /** Tool execution result */
216
+ result: ToolResult;
217
+ }
218
+
219
+ /**
220
+ * SDK Options Types
221
+ *
222
+ * These types define all configuration options for sessions and prompts.
223
+ * Designed for both browser and Node.js environments.
224
+ */
225
+
226
+ /**
227
+ * Available Claude models
228
+ */
229
+ type Model = 'claude-sonnet-4-5-20250929' | 'claude-opus-4-5-20251101' | 'claude-3-5-sonnet-20241022' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-20240229' | (string & {});
230
+ /**
231
+ * System prompt configuration
232
+ */
233
+ type SystemPrompt = string | {
234
+ /** Use a preset system prompt */
235
+ type: 'preset';
236
+ /** The preset name */
237
+ preset: 'claude_code';
238
+ /** Additional text to append to the preset */
239
+ append?: string;
240
+ };
241
+ /**
242
+ * Output format configuration for structured outputs
243
+ */
244
+ interface OutputFormat {
245
+ /** Output format type */
246
+ type: 'json_schema';
247
+ /** JSON Schema definition for the expected output */
248
+ schema: Record<string, unknown>;
249
+ }
250
+ /**
251
+ * Agent definition for sub-agents
252
+ */
253
+ interface AgentDefinition {
254
+ /** Agent name */
255
+ name: string;
256
+ /** Agent description */
257
+ description?: string;
258
+ /** Model to use for this agent */
259
+ model?: Model;
260
+ /** System prompt for this agent */
261
+ systemPrompt?: SystemPrompt;
262
+ /** Tools available to this agent */
263
+ tools?: string[];
264
+ /** Maximum turns for this agent */
265
+ maxTurns?: number;
266
+ }
267
+ /**
268
+ * Base options shared between sessions and prompts
269
+ */
270
+ interface BaseOptions {
271
+ /**
272
+ * The model to use for generation
273
+ * @default 'claude-sonnet-4-5-20250929'
274
+ */
275
+ model?: Model;
276
+ /**
277
+ * Fallback model if primary model is unavailable
278
+ */
279
+ fallbackModel?: Model;
280
+ /**
281
+ * Maximum number of conversation turns
282
+ */
283
+ maxTurns?: number;
284
+ /**
285
+ * Maximum budget in USD for this session/prompt
286
+ */
287
+ maxBudgetUsd?: number;
288
+ /**
289
+ * Maximum thinking tokens (for extended thinking)
290
+ */
291
+ maxThinkingTokens?: number;
292
+ /**
293
+ * System prompt or preset configuration
294
+ */
295
+ systemPrompt?: SystemPrompt;
296
+ /**
297
+ * Tool configuration - allowlist of tool names or preset
298
+ * Pass an array of tool names or use the preset to get Claude Code's default tools
299
+ */
300
+ tools?: ToolsConfig;
301
+ /**
302
+ * List of tool names that are allowed
303
+ */
304
+ allowedTools?: string[];
305
+ /**
306
+ * List of tool names that are blocked
307
+ */
308
+ disallowedTools?: string[];
309
+ /**
310
+ * MCP server definitions (array format)
311
+ * Bridge translates to Record format for official SDK
312
+ */
313
+ mcpServers?: McpServerDefinition[];
314
+ /**
315
+ * Sub-agent definitions
316
+ */
317
+ agents?: Record<string, AgentDefinition>;
318
+ /**
319
+ * Beta features to enable
320
+ */
321
+ betas?: string[];
322
+ /**
323
+ * Permission mode for sandbox operations
324
+ */
325
+ permissionMode?: 'default' | 'plan' | 'bypassPermissions';
326
+ /**
327
+ * Allow dangerous operations (use with caution)
328
+ */
329
+ allowDangerouslySkipPermissions?: boolean;
330
+ /**
331
+ * Custom environment variables
332
+ */
333
+ env?: Record<string, string>;
334
+ /**
335
+ * Output format for structured responses
336
+ */
337
+ outputFormat?: OutputFormat;
338
+ /**
339
+ * Include partial messages in the stream
340
+ */
341
+ includePartialMessages?: boolean;
342
+ }
343
+ /**
344
+ * Session-specific options
345
+ */
346
+ interface SessionOptions extends BaseOptions {
347
+ /**
348
+ * Session ID for resuming an existing session
349
+ */
350
+ sessionId?: string;
351
+ /**
352
+ * Fork from an existing session instead of resuming
353
+ */
354
+ forkSession?: boolean;
355
+ /**
356
+ * Resume session at a specific conversation ID
357
+ */
358
+ resumeSessionAt?: string;
359
+ /**
360
+ * Continue from where the session left off
361
+ */
362
+ continue?: boolean;
363
+ /**
364
+ * Settings sources for configuration
365
+ */
366
+ settingSources?: Array<'user' | 'project' | 'local'>;
367
+ /**
368
+ * Job ID for tracking background/deferred executions
369
+ */
370
+ jobId?: string;
371
+ }
372
+ /**
373
+ * Prompt-specific options (stateless, one-shot)
374
+ */
375
+ interface PromptOptions extends BaseOptions {
376
+ /**
377
+ * The prompt message to send
378
+ */
379
+ message: string;
380
+ }
381
+ /**
382
+ * Client configuration options
383
+ */
384
+ interface ClientOptions {
385
+ /**
386
+ * Base URL for the Chucky service
387
+ * @default 'wss://box.chucky.cloud'
388
+ */
389
+ baseUrl?: string;
390
+ /**
391
+ * Authentication token (JWT)
392
+ */
393
+ token: string;
394
+ /**
395
+ * Enable debug logging
396
+ */
397
+ debug?: boolean;
398
+ /**
399
+ * Connection timeout in milliseconds
400
+ * @default 30000
401
+ */
402
+ timeout?: number;
403
+ /**
404
+ * Keep-alive interval in milliseconds
405
+ * @default 300000 (5 minutes)
406
+ */
407
+ keepAliveInterval?: number;
408
+ /**
409
+ * Auto-reconnect on disconnect
410
+ * @default true
411
+ */
412
+ autoReconnect?: boolean;
413
+ /**
414
+ * Maximum reconnect attempts
415
+ * @default 5
416
+ */
417
+ maxReconnectAttempts?: number;
418
+ }
419
+ /**
420
+ * Connection status
421
+ */
422
+ type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'error';
423
+ /**
424
+ * Event handlers for client events
425
+ */
426
+ interface ClientEventHandlers {
427
+ /** Called when connection status changes */
428
+ onStatusChange?: (status: ConnectionStatus) => void;
429
+ /** Called when a raw message is sent or received (for debugging) */
430
+ onRawMessage?: (direction: 'in' | 'out', message: unknown) => void;
431
+ /** Called when an error occurs */
432
+ onError?: (error: Error) => void;
433
+ }
434
+
435
+ /**
436
+ * WebSocket Message Types
437
+ *
438
+ * Matches the official Claude Agent SDK message format.
439
+ * See: https://platform.claude.com/docs/en/agent-sdk/typescript
440
+ */
441
+
442
+ type UUID = string;
443
+ /**
444
+ * Anthropic API message content types
445
+ */
446
+ type TextContent = {
447
+ type: 'text';
448
+ text: string;
449
+ };
450
+ type ImageContent = {
451
+ type: 'image';
452
+ source: {
453
+ type: 'base64';
454
+ media_type: string;
455
+ data: string;
456
+ };
457
+ };
458
+ type ToolUseContent = {
459
+ type: 'tool_use';
460
+ id: string;
461
+ name: string;
462
+ input: Record<string, unknown>;
463
+ };
464
+ type ToolResultContent = {
465
+ type: 'tool_result';
466
+ tool_use_id: string;
467
+ content: string | Array<TextContent | ImageContent>;
468
+ is_error?: boolean;
469
+ };
470
+ type ContentBlock$1 = TextContent | ImageContent | ToolUseContent | ToolResultContent;
471
+ /**
472
+ * Anthropic API User Message
473
+ */
474
+ interface APIUserMessage {
475
+ role: 'user';
476
+ content: string | ContentBlock$1[];
477
+ }
478
+ /**
479
+ * Anthropic API Assistant Message
480
+ */
481
+ interface APIAssistantMessage {
482
+ role: 'assistant';
483
+ content: ContentBlock$1[];
484
+ }
485
+ /**
486
+ * User message - sent by the client
487
+ */
488
+ interface SDKUserMessage {
489
+ type: 'user';
490
+ uuid?: UUID;
491
+ session_id: string;
492
+ message: APIUserMessage;
493
+ parent_tool_use_id: string | null;
494
+ }
495
+ /**
496
+ * Assistant message - response from Claude
497
+ */
498
+ interface SDKAssistantMessage {
499
+ type: 'assistant';
500
+ uuid: UUID;
501
+ session_id: string;
502
+ message: APIAssistantMessage;
503
+ parent_tool_use_id: string | null;
504
+ }
505
+ /**
506
+ * Result message subtypes
507
+ */
508
+ type ResultSubtype = 'success' | 'error_max_turns' | 'error_during_execution' | 'error_max_budget_usd' | 'error_max_structured_output_retries';
509
+ /**
510
+ * Success result message
511
+ */
512
+ interface SDKResultMessageSuccess {
513
+ type: 'result';
514
+ subtype: 'success';
515
+ uuid: UUID;
516
+ session_id: string;
517
+ duration_ms: number;
518
+ duration_api_ms: number;
519
+ is_error: boolean;
520
+ num_turns: number;
521
+ result: string;
522
+ total_cost_usd: number;
523
+ usage: {
524
+ input_tokens: number;
525
+ output_tokens: number;
526
+ cache_creation_input_tokens: number;
527
+ cache_read_input_tokens: number;
528
+ };
529
+ structured_output?: unknown;
530
+ }
531
+ /**
532
+ * Error result message
533
+ */
534
+ interface SDKResultMessageError {
535
+ type: 'result';
536
+ subtype: Exclude<ResultSubtype, 'success'>;
537
+ uuid: UUID;
538
+ session_id: string;
539
+ duration_ms: number;
540
+ duration_api_ms: number;
541
+ is_error: boolean;
542
+ num_turns: number;
543
+ total_cost_usd: number;
544
+ usage: {
545
+ input_tokens: number;
546
+ output_tokens: number;
547
+ cache_creation_input_tokens: number;
548
+ cache_read_input_tokens: number;
549
+ };
550
+ errors: string[];
551
+ }
552
+ type SDKResultMessage = SDKResultMessageSuccess | SDKResultMessageError;
553
+ /**
554
+ * System message subtypes
555
+ */
556
+ type SystemSubtype = 'init' | 'compact_boundary';
557
+ /**
558
+ * System init message
559
+ */
560
+ interface SDKSystemMessageInit {
561
+ type: 'system';
562
+ subtype: 'init';
563
+ uuid: UUID;
564
+ session_id: string;
565
+ cwd: string;
566
+ tools: string[];
567
+ mcp_servers: Array<{
568
+ name: string;
569
+ status: string;
570
+ }>;
571
+ model: string;
572
+ permissionMode: string;
573
+ }
574
+ /**
575
+ * System compact boundary message
576
+ */
577
+ interface SDKSystemMessageCompact {
578
+ type: 'system';
579
+ subtype: 'compact_boundary';
580
+ uuid: UUID;
581
+ session_id: string;
582
+ compact_metadata: {
583
+ trigger: 'manual' | 'auto';
584
+ pre_tokens: number;
585
+ };
586
+ }
587
+ type SDKSystemMessage = SDKSystemMessageInit | SDKSystemMessageCompact;
588
+ /**
589
+ * Partial assistant message (streaming)
590
+ */
591
+ interface SDKPartialAssistantMessage {
592
+ type: 'stream_event';
593
+ event: unknown;
594
+ parent_tool_use_id: string | null;
595
+ uuid: UUID;
596
+ session_id: string;
597
+ }
598
+ /**
599
+ * All SDK message types (matching official SDK)
600
+ */
601
+ type SDKMessage = SDKUserMessage | SDKAssistantMessage | SDKResultMessage | SDKSystemMessage | SDKPartialAssistantMessage;
602
+ /**
603
+ * WebSocket envelope types for our transport
604
+ */
605
+ type WsEnvelopeType = 'init' | 'user' | 'assistant' | 'result' | 'system' | 'stream_event' | 'control' | 'error' | 'ping' | 'pong' | 'tool_call' | 'tool_result';
606
+ /**
607
+ * Init message payload (session initialization)
608
+ */
609
+ interface InitPayload extends Omit<SessionOptions, 'mcpServers'> {
610
+ mcpServers?: unknown[];
611
+ }
612
+ /**
613
+ * Control message actions
614
+ */
615
+ type ControlAction = 'ready' | 'session_info' | 'end_input' | 'close';
616
+ /**
617
+ * Control message payload
618
+ */
619
+ interface ControlPayload {
620
+ action: ControlAction;
621
+ data?: Record<string, unknown>;
622
+ }
623
+ /**
624
+ * Error message payload
625
+ */
626
+ interface ErrorPayload {
627
+ message: string;
628
+ code?: string;
629
+ details?: Record<string, unknown>;
630
+ }
631
+ /**
632
+ * Ping/Pong payload
633
+ */
634
+ interface PingPongPayload {
635
+ timestamp: number;
636
+ }
637
+ /**
638
+ * Tool call payload (server -> client)
639
+ */
640
+ interface ToolCallPayload extends ToolCall {
641
+ }
642
+ /**
643
+ * Tool result payload (client -> server)
644
+ */
645
+ interface ToolResultPayload {
646
+ callId: string;
647
+ result: ToolResult;
648
+ }
649
+ interface InitEnvelope {
650
+ type: 'init';
651
+ payload: InitPayload;
652
+ }
653
+ interface ControlEnvelope {
654
+ type: 'control';
655
+ payload: ControlPayload;
656
+ }
657
+ interface ErrorEnvelope {
658
+ type: 'error';
659
+ payload: ErrorPayload;
660
+ }
661
+ interface PingEnvelope {
662
+ type: 'ping';
663
+ payload: PingPongPayload;
664
+ }
665
+ interface PongEnvelope {
666
+ type: 'pong';
667
+ payload: PingPongPayload;
668
+ }
669
+ interface ToolCallEnvelope {
670
+ type: 'tool_call';
671
+ payload: ToolCallPayload;
672
+ }
673
+ interface ToolResultEnvelope {
674
+ type: 'tool_result';
675
+ payload: ToolResultPayload;
676
+ }
677
+ /**
678
+ * Outgoing messages (client -> server)
679
+ */
680
+ type OutgoingMessage = InitEnvelope | SDKUserMessage | ControlEnvelope | PingEnvelope | ToolResultEnvelope;
681
+ /**
682
+ * Incoming messages (server -> client)
683
+ */
684
+ type IncomingMessage = SDKAssistantMessage | SDKResultMessage | SDKSystemMessage | SDKPartialAssistantMessage | ControlEnvelope | ErrorEnvelope | PongEnvelope | ToolCallEnvelope;
685
+ /**
686
+ * All messages
687
+ */
688
+ type AnyMessage = OutgoingMessage | IncomingMessage;
689
+ /**
690
+ * Create an init message
691
+ */
692
+ declare function createInitMessage(payload: InitPayload): InitEnvelope;
693
+ /**
694
+ * Create a user message (official SDK format)
695
+ */
696
+ declare function createUserMessage(content: string | ContentBlock$1[], sessionId: string, options?: {
697
+ uuid?: UUID;
698
+ parentToolUseId?: string | null;
699
+ }): SDKUserMessage;
700
+ /**
701
+ * Create a control message
702
+ */
703
+ declare function createControlMessage(action: ControlAction, data?: Record<string, unknown>): ControlEnvelope;
704
+ /**
705
+ * Create a ping message
706
+ */
707
+ declare function createPingMessage(): PingEnvelope;
708
+ /**
709
+ * Create a tool result message
710
+ */
711
+ declare function createToolResultMessage(callId: string, result: ToolResult): ToolResultEnvelope;
712
+ /**
713
+ * Check if message is a user message
714
+ */
715
+ declare function isUserMessage(message: AnyMessage): message is SDKUserMessage;
716
+ /**
717
+ * Check if message is an assistant message
718
+ */
719
+ declare function isAssistantMessage(message: AnyMessage): message is SDKAssistantMessage;
720
+ /**
721
+ * Check if message is a result message
722
+ */
723
+ declare function isResultMessage(message: AnyMessage): message is SDKResultMessage;
724
+ /**
725
+ * Check if message is a success result
726
+ */
727
+ declare function isSuccessResult(message: AnyMessage): message is SDKResultMessageSuccess;
728
+ /**
729
+ * Check if message is an error result
730
+ */
731
+ declare function isErrorResult(message: AnyMessage): message is SDKResultMessageError;
732
+ /**
733
+ * Check if message is a system message
734
+ */
735
+ declare function isSystemMessage(message: AnyMessage): message is SDKSystemMessage;
736
+ /**
737
+ * Check if message is a stream event
738
+ */
739
+ declare function isStreamEvent(message: AnyMessage): message is SDKPartialAssistantMessage;
740
+ /**
741
+ * Check if message is a tool call
742
+ */
743
+ declare function isToolCallMessage(message: AnyMessage): message is ToolCallEnvelope;
744
+ /**
745
+ * Check if message is a control message
746
+ */
747
+ declare function isControlMessage(message: AnyMessage): message is ControlEnvelope;
748
+ /**
749
+ * Check if message is an error message
750
+ */
751
+ declare function isErrorMessage(message: AnyMessage): message is ErrorEnvelope;
752
+
753
+ /**
754
+ * Result Types
755
+ *
756
+ * Types for responses from sessions and prompts.
757
+ */
758
+ /**
759
+ * Message role
760
+ */
761
+ type MessageRole = 'user' | 'assistant' | 'system';
762
+ /**
763
+ * Content block types
764
+ */
765
+ type ContentBlockType = 'text' | 'tool_use' | 'tool_result' | 'thinking' | 'image';
766
+ /**
767
+ * Text content block
768
+ */
769
+ interface TextBlock {
770
+ type: 'text';
771
+ text: string;
772
+ }
773
+ /**
774
+ * Tool use content block
775
+ */
776
+ interface ToolUseBlock {
777
+ type: 'tool_use';
778
+ id: string;
779
+ name: string;
780
+ input: Record<string, unknown>;
781
+ }
782
+ /**
783
+ * Tool result content block
784
+ */
785
+ interface ToolResultBlock {
786
+ type: 'tool_result';
787
+ tool_use_id: string;
788
+ content: string | Array<{
789
+ type: 'text';
790
+ text: string;
791
+ }>;
792
+ is_error?: boolean;
793
+ }
794
+ /**
795
+ * Thinking content block (extended thinking)
796
+ */
797
+ interface ThinkingBlock {
798
+ type: 'thinking';
799
+ thinking: string;
800
+ }
801
+ /**
802
+ * Image content block
803
+ */
804
+ interface ImageBlock {
805
+ type: 'image';
806
+ source: {
807
+ type: 'base64';
808
+ media_type: string;
809
+ data: string;
810
+ };
811
+ }
812
+ /**
813
+ * Union type for all content blocks
814
+ */
815
+ type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ThinkingBlock | ImageBlock;
816
+ /**
817
+ * A message in the conversation
818
+ */
819
+ interface Message {
820
+ /** Message role */
821
+ role: MessageRole;
822
+ /** Message content */
823
+ content: ContentBlock[] | string;
824
+ }
825
+ /**
826
+ * Usage statistics
827
+ */
828
+ interface Usage {
829
+ /** Input tokens used */
830
+ input_tokens: number;
831
+ /** Output tokens generated */
832
+ output_tokens: number;
833
+ /** Cache creation input tokens */
834
+ cache_creation_input_tokens?: number;
835
+ /** Cache read input tokens */
836
+ cache_read_input_tokens?: number;
837
+ }
838
+ /**
839
+ * Cost breakdown
840
+ */
841
+ interface CostBreakdown {
842
+ /** Input cost in USD */
843
+ input_cost_usd: number;
844
+ /** Output cost in USD */
845
+ output_cost_usd: number;
846
+ /** Total cost in USD */
847
+ total_cost_usd: number;
848
+ }
849
+ /**
850
+ * Session result (returned when session completes)
851
+ */
852
+ interface SessionResult {
853
+ /** Result type */
854
+ type: 'result';
855
+ /** Result subtype */
856
+ subtype?: 'success' | 'error' | 'interrupted';
857
+ /** Final response text */
858
+ text?: string;
859
+ /** Conversation messages */
860
+ messages?: Message[];
861
+ /** Total cost in USD */
862
+ total_cost_usd?: number;
863
+ /** Session duration in seconds */
864
+ duration_secs?: number;
865
+ /** Number of conversation turns */
866
+ turn_count?: number;
867
+ /** Usage statistics */
868
+ usage?: Usage;
869
+ /** Session ID (for resuming) */
870
+ session_id?: string;
871
+ /** Error message (if subtype is 'error') */
872
+ error?: string;
873
+ }
874
+ /**
875
+ * Prompt result (returned from one-shot prompts)
876
+ */
877
+ interface PromptResult {
878
+ /** Result type */
879
+ type: 'result';
880
+ /** Result subtype */
881
+ subtype?: 'success' | 'error';
882
+ /** Response text */
883
+ text?: string;
884
+ /** Structured output (if outputFormat was specified) */
885
+ output?: unknown;
886
+ /** Total cost in USD */
887
+ total_cost_usd?: number;
888
+ /** Duration in seconds */
889
+ duration_secs?: number;
890
+ /** Usage statistics */
891
+ usage?: Usage;
892
+ /** Error message (if subtype is 'error') */
893
+ error?: string;
894
+ }
895
+ /**
896
+ * Streaming message event
897
+ */
898
+ interface StreamEvent {
899
+ /** Event type */
900
+ type: 'message_start' | 'content_block_start' | 'content_block_delta' | 'content_block_stop' | 'message_delta' | 'message_stop' | 'tool_use' | 'tool_result' | 'error';
901
+ /** Event data */
902
+ data: unknown;
903
+ }
904
+ /**
905
+ * Partial message (during streaming)
906
+ */
907
+ interface PartialMessage {
908
+ /** Message role */
909
+ role: MessageRole;
910
+ /** Partial content accumulated so far */
911
+ content: ContentBlock[];
912
+ /** Whether the message is complete */
913
+ complete: boolean;
914
+ }
915
+ /**
916
+ * Session state
917
+ */
918
+ type SessionState = 'idle' | 'initializing' | 'ready' | 'processing' | 'waiting_tool' | 'completed' | 'error';
919
+ /**
920
+ * Session info (returned when connecting/resuming)
921
+ */
922
+ interface SessionInfo {
923
+ /** Session ID */
924
+ sessionId?: string;
925
+ /** Current state */
926
+ state?: SessionState;
927
+ /** Number of messages in conversation */
928
+ messageCount?: number;
929
+ /** Session creation time (ISO 8601) */
930
+ createdAt?: string;
931
+ /** Last activity time (ISO 8601) */
932
+ lastActivityAt?: string;
933
+ /** Model being used */
934
+ model?: string;
935
+ /** Available tools */
936
+ tools?: string[];
937
+ }
938
+
939
+ /**
940
+ * Transport Interface
941
+ *
942
+ * Abstract interface for communication between the SDK and Chucky server.
943
+ * Implementations can use WebSocket (browser/Node.js) or other protocols.
944
+ */
945
+
946
+ /**
947
+ * Transport event types
948
+ */
949
+ interface TransportEvents extends ClientEventHandlers {
950
+ /** Called when a message is received */
951
+ onMessage?: (message: IncomingMessage) => void;
952
+ /** Called when the transport is closed */
953
+ onClose?: (code?: number, reason?: string) => void;
954
+ }
955
+ /**
956
+ * Transport configuration
957
+ */
958
+ interface TransportConfig {
959
+ /** Server URL */
960
+ url: string;
961
+ /** Authentication token */
962
+ token: string;
963
+ /** Connection timeout in milliseconds */
964
+ timeout?: number;
965
+ /** Keep-alive interval in milliseconds */
966
+ keepAliveInterval?: number;
967
+ /** Auto-reconnect on disconnect */
968
+ autoReconnect?: boolean;
969
+ /** Maximum reconnect attempts */
970
+ maxReconnectAttempts?: number;
971
+ /** Debug mode */
972
+ debug?: boolean;
973
+ }
974
+ /**
975
+ * Abstract transport interface
976
+ */
977
+ interface Transport {
978
+ /** Current connection status */
979
+ readonly status: ConnectionStatus;
980
+ /**
981
+ * Connect to the server
982
+ */
983
+ connect(): Promise<void>;
984
+ /**
985
+ * Disconnect from the server
986
+ */
987
+ disconnect(): Promise<void>;
988
+ /**
989
+ * Send a message to the server
990
+ */
991
+ send(message: OutgoingMessage): Promise<void>;
992
+ /**
993
+ * Set event handlers
994
+ */
995
+ setEventHandlers(handlers: TransportEvents): void;
996
+ /**
997
+ * Wait for connection to be ready
998
+ */
999
+ waitForReady(): Promise<void>;
1000
+ }
1001
+ /**
1002
+ * Base transport class with common functionality
1003
+ */
1004
+ declare abstract class BaseTransport implements Transport {
1005
+ protected _status: ConnectionStatus;
1006
+ protected handlers: TransportEvents;
1007
+ protected config: TransportConfig;
1008
+ constructor(config: TransportConfig);
1009
+ get status(): ConnectionStatus;
1010
+ protected setStatus(status: ConnectionStatus): void;
1011
+ protected log(...args: unknown[]): void;
1012
+ protected logError(...args: unknown[]): void;
1013
+ setEventHandlers(handlers: TransportEvents): void;
1014
+ abstract connect(): Promise<void>;
1015
+ abstract disconnect(): Promise<void>;
1016
+ abstract send(message: OutgoingMessage): Promise<void>;
1017
+ abstract waitForReady(): Promise<void>;
1018
+ }
1019
+
1020
+ /**
1021
+ * Session
1022
+ *
1023
+ * Represents a conversation session with the Chucky sandbox.
1024
+ * Matches the official Claude Agent SDK V2 interface.
5
1025
  *
6
1026
  * @example
7
1027
  * ```typescript
8
- * import { ChuckyClient, tool, createBudget, createToken } from '@chucky.cloud/sdk';
1028
+ * const session = createSession({ token, model: 'claude-sonnet-4-5-20250929' });
9
1029
  *
10
- * // Server-side: Create a token for your user
11
- * const token = await createToken({
12
- * userId: 'user-123',
13
- * projectId: 'your-project-uuid',
14
- * secret: 'your-hmac-secret',
15
- * budget: createBudget({
16
- * aiDollars: 1.00,
17
- * computeHours: 1,
18
- * window: 'day',
1030
+ * await session.send('Hello!');
1031
+ * for await (const msg of session.stream()) {
1032
+ * if (msg.type === 'assistant') {
1033
+ * console.log(getAssistantText(msg));
1034
+ * }
1035
+ * }
1036
+ * ```
1037
+ */
1038
+
1039
+ /**
1040
+ * Session event handlers
1041
+ */
1042
+ interface SessionEventHandlers {
1043
+ onSessionInfo?: (info: SessionInfo) => void;
1044
+ onError?: (error: Error) => void;
1045
+ }
1046
+ /**
1047
+ * Internal session configuration
1048
+ */
1049
+ interface SessionConfig {
1050
+ debug?: boolean;
1051
+ }
1052
+ /**
1053
+ * Session class - matches official V2 SDK interface
1054
+ *
1055
+ * Usage:
1056
+ * ```typescript
1057
+ * const session = createSession({ token, model: 'claude-sonnet-4-5-20250929' });
1058
+ *
1059
+ * // Multi-turn conversation
1060
+ * await session.send('What is 5 + 3?');
1061
+ * for await (const msg of session.stream()) {
1062
+ * if (msg.type === 'result') console.log(msg.result);
1063
+ * }
1064
+ *
1065
+ * await session.send('Multiply that by 2');
1066
+ * for await (const msg of session.stream()) {
1067
+ * if (msg.type === 'result') console.log(msg.result);
1068
+ * }
1069
+ *
1070
+ * session.close();
1071
+ * ```
1072
+ */
1073
+ declare class Session {
1074
+ private transport;
1075
+ private options;
1076
+ private config;
1077
+ private eventHandlers;
1078
+ private toolHandlers;
1079
+ private messageBuffer;
1080
+ private _state;
1081
+ private _sessionId;
1082
+ private messageResolvers;
1083
+ private connected;
1084
+ private connectPromise;
1085
+ constructor(transport: Transport, options: SessionOptions, config?: SessionConfig);
1086
+ /**
1087
+ * Get the session ID
1088
+ */
1089
+ get sessionId(): string;
1090
+ /**
1091
+ * Set event handlers
1092
+ */
1093
+ on(handlers: SessionEventHandlers): this;
1094
+ /**
1095
+ * Connect and initialize the session (called automatically on first send)
1096
+ */
1097
+ private ensureConnected;
1098
+ private connect;
1099
+ /**
1100
+ * Send a message to the session
1101
+ *
1102
+ * Matches V2 SDK: send() returns Promise<void>
1103
+ * Use stream() to get the response.
1104
+ *
1105
+ * @example
1106
+ * ```typescript
1107
+ * await session.send('Hello!');
1108
+ * for await (const msg of session.stream()) {
1109
+ * // Handle messages
1110
+ * }
1111
+ * ```
1112
+ */
1113
+ send(message: string): Promise<void>;
1114
+ /**
1115
+ * Stream the response after sending a message
1116
+ *
1117
+ * Matches V2 SDK: Returns AsyncGenerator<SDKMessage>
1118
+ *
1119
+ * @example
1120
+ * ```typescript
1121
+ * await session.send('Hello!');
1122
+ * for await (const msg of session.stream()) {
1123
+ * if (msg.type === 'assistant') {
1124
+ * const text = msg.message.content
1125
+ * .filter(b => b.type === 'text')
1126
+ * .map(b => b.text)
1127
+ * .join('');
1128
+ * console.log(text);
1129
+ * }
1130
+ * if (msg.type === 'result') {
1131
+ * console.log('Done:', msg.result);
1132
+ * }
1133
+ * }
1134
+ * ```
1135
+ */
1136
+ stream(): AsyncGenerator<SDKMessage, void, unknown>;
1137
+ /**
1138
+ * Receive messages (alias for stream for V2 compatibility)
1139
+ */
1140
+ receive(): AsyncGenerator<SDKMessage, void, unknown>;
1141
+ /**
1142
+ * Close the session
1143
+ */
1144
+ close(): void;
1145
+ /**
1146
+ * Support for `await using` (TypeScript 5.2+)
1147
+ */
1148
+ [Symbol.asyncDispose](): Promise<void>;
1149
+ /**
1150
+ * Build init payload from options
1151
+ */
1152
+ private buildInitPayload;
1153
+ /**
1154
+ * Handle incoming message
1155
+ */
1156
+ private handleMessage;
1157
+ /**
1158
+ * Wait for session to be ready
1159
+ */
1160
+ private waitForReady;
1161
+ /**
1162
+ * Wait for next message
1163
+ */
1164
+ private waitForNextMessage;
1165
+ /**
1166
+ * Handle a tool call
1167
+ */
1168
+ private handleToolCall;
1169
+ /**
1170
+ * Log debug messages
1171
+ */
1172
+ private log;
1173
+ }
1174
+ /**
1175
+ * Extract text from an assistant message
1176
+ */
1177
+ declare function getAssistantText(msg: SDKMessage): string | null;
1178
+ /**
1179
+ * Extract result from a result message
1180
+ */
1181
+ declare function getResultText(msg: SDKMessage): string | null;
1182
+
1183
+ /**
1184
+ * Chucky Client
1185
+ *
1186
+ * Main entry point for the Chucky SDK.
1187
+ * Provides methods to create sessions and execute prompts.
1188
+ * Matches the official Claude Agent SDK V2 interface.
1189
+ */
1190
+
1191
+ /**
1192
+ * Chucky client for interacting with the sandbox service
1193
+ *
1194
+ * Matches the official Claude Agent SDK V2 interface.
1195
+ *
1196
+ * @example
1197
+ * ```typescript
1198
+ * import { ChuckyClient } from '@chucky.cloud/sdk';
1199
+ *
1200
+ * const client = new ChuckyClient({
1201
+ * token: 'your-jwt-token',
1202
+ * });
1203
+ *
1204
+ * // Create a session (V2 style)
1205
+ * const session = client.createSession({
1206
+ * model: 'claude-sonnet-4-5-20250929',
1207
+ * systemPrompt: 'You are a helpful assistant.',
1208
+ * });
1209
+ *
1210
+ * // Send messages and stream responses
1211
+ * await session.send('Hello, world!');
1212
+ * for await (const msg of session.stream()) {
1213
+ * if (msg.type === 'assistant') {
1214
+ * const text = getAssistantText(msg);
1215
+ * console.log(text);
1216
+ * }
1217
+ * if (msg.type === 'result') {
1218
+ * console.log('Done:', msg);
1219
+ * }
1220
+ * }
1221
+ *
1222
+ * session.close();
1223
+ * ```
1224
+ */
1225
+ declare class ChuckyClient {
1226
+ private readonly options;
1227
+ private eventHandlers;
1228
+ private activeSessions;
1229
+ /**
1230
+ * Create a new Chucky client
1231
+ */
1232
+ constructor(options: ClientOptions);
1233
+ /**
1234
+ * Set event handlers
1235
+ */
1236
+ on(handlers: ClientEventHandlers): this;
1237
+ /**
1238
+ * Create a new session
1239
+ *
1240
+ * Matches V2 SDK: createSession() returns a Session immediately.
1241
+ * Connection happens automatically on first send().
1242
+ *
1243
+ * @param options - Session configuration options
1244
+ * @returns A new session instance
1245
+ *
1246
+ * @example
1247
+ * ```typescript
1248
+ * const session = client.createSession({
1249
+ * model: 'claude-sonnet-4-5-20250929',
1250
+ * systemPrompt: 'You are a helpful coding assistant.',
1251
+ * });
1252
+ *
1253
+ * await session.send('Hello!');
1254
+ * for await (const msg of session.stream()) {
1255
+ * // Handle messages
1256
+ * }
1257
+ * ```
1258
+ */
1259
+ createSession(options?: SessionOptions): Session;
1260
+ /**
1261
+ * Resume an existing session
1262
+ *
1263
+ * @param sessionId - The session ID to resume
1264
+ * @param options - Additional session options
1265
+ * @returns The resumed session
1266
+ *
1267
+ * @example
1268
+ * ```typescript
1269
+ * const session = client.resumeSession('session-123');
1270
+ * await session.send('Continue our conversation');
1271
+ * ```
1272
+ */
1273
+ resumeSession(sessionId: string, options?: Omit<SessionOptions, 'sessionId'>): Session;
1274
+ /**
1275
+ * Execute a one-shot prompt (stateless)
1276
+ *
1277
+ * Supports two call signatures:
1278
+ * - `prompt('message', { model: '...' })` - positional style
1279
+ * - `prompt({ message: '...', model: '...' })` - object style
1280
+ *
1281
+ * @param messageOrOptions - The message string OR an options object with message
1282
+ * @param options - Prompt configuration (only used with positional style)
1283
+ * @returns The result message
1284
+ *
1285
+ * @example
1286
+ * ```typescript
1287
+ * // Positional style
1288
+ * const result = await client.prompt(
1289
+ * 'Explain quantum computing in simple terms',
1290
+ * { model: 'claude-sonnet-4-5-20250929' }
1291
+ * );
1292
+ *
1293
+ * // Object style
1294
+ * const result = await client.prompt({
1295
+ * message: 'Explain quantum computing in simple terms',
1296
+ * model: 'claude-sonnet-4-5-20250929',
1297
+ * });
1298
+ *
1299
+ * if (result.subtype === 'success') {
1300
+ * console.log(result.result);
1301
+ * }
1302
+ * ```
1303
+ */
1304
+ prompt(messageOrOptions: string | PromptOptions, options?: SessionOptions): Promise<SDKResultMessage>;
1305
+ /**
1306
+ * Close all active sessions and disconnect
1307
+ */
1308
+ close(): void;
1309
+ /**
1310
+ * Create a new transport instance
1311
+ */
1312
+ private createTransport;
1313
+ }
1314
+ /**
1315
+ * Create a Chucky client
1316
+ *
1317
+ * @param options - Client configuration
1318
+ * @returns A new ChuckyClient instance
1319
+ *
1320
+ * @example
1321
+ * ```typescript
1322
+ * import { createClient } from '@chucky.cloud/sdk';
1323
+ *
1324
+ * const client = createClient({
1325
+ * token: 'your-jwt-token',
1326
+ * });
1327
+ * ```
1328
+ */
1329
+ declare function createClient(options: ClientOptions): ChuckyClient;
1330
+
1331
+ /**
1332
+ * Tool Helper
1333
+ *
1334
+ * Helper functions for defining tools with type safety.
1335
+ * Supports both JSON Schema and Zod for input validation.
1336
+ */
1337
+
1338
+ /**
1339
+ * Options for creating a tool
1340
+ */
1341
+ interface CreateToolOptions<TInput = Record<string, unknown>> {
1342
+ /** Tool name (must be unique) */
1343
+ name: string;
1344
+ /** Human-readable description */
1345
+ description: string;
1346
+ /** Input schema (JSON Schema or Zod schema) */
1347
+ inputSchema: ToolInputSchema | ZodLikeSchema;
1348
+ /** Where to execute the tool */
1349
+ executeIn?: ToolExecutionLocation;
1350
+ /** Handler function */
1351
+ handler?: ToolHandler<TInput>;
1352
+ }
1353
+ /**
1354
+ * Zod-like schema interface for compatibility
1355
+ */
1356
+ interface ZodLikeSchema {
1357
+ _def?: unknown;
1358
+ shape?: unknown;
1359
+ safeParse?: (data: unknown) => {
1360
+ success: boolean;
1361
+ data?: unknown;
1362
+ error?: unknown;
1363
+ };
1364
+ }
1365
+ /**
1366
+ * Create a tool definition
1367
+ *
1368
+ * @param options - Tool configuration
1369
+ * @returns Tool definition ready to use
1370
+ *
1371
+ * @example
1372
+ * ```typescript
1373
+ * // With JSON Schema
1374
+ * const weatherTool = createTool({
1375
+ * name: 'get_weather',
1376
+ * description: 'Get current weather for a city',
1377
+ * inputSchema: {
1378
+ * type: 'object',
1379
+ * properties: {
1380
+ * city: { type: 'string', description: 'City name' },
1381
+ * unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
1382
+ * },
1383
+ * required: ['city'],
1384
+ * },
1385
+ * handler: async ({ city, unit }) => ({
1386
+ * content: [{ type: 'text', text: `Weather in ${city}: Sunny, 72°${unit === 'celsius' ? 'C' : 'F'}` }],
19
1387
  * }),
20
1388
  * });
21
1389
  *
22
- * // Create client with the token
23
- * const client = new ChuckyClient({ token });
1390
+ * // With Zod (optional peer dependency)
1391
+ * import { z } from 'zod';
24
1392
  *
25
- * // Create a session with tools
26
- * const session = await client.createSession({
27
- * model: 'claude-sonnet-4-5-20250929',
28
- * tools: [
29
- * tool('greet', 'Greet someone', {
1393
+ * const calculatorTool = createTool({
1394
+ * name: 'calculate',
1395
+ * description: 'Perform a calculation',
1396
+ * inputSchema: z.object({
1397
+ * expression: z.string().describe('Math expression to evaluate'),
1398
+ * }),
1399
+ * handler: async ({ expression }) => ({
1400
+ * content: [{ type: 'text', text: `Result: ${eval(expression)}` }],
1401
+ * }),
1402
+ * });
1403
+ * ```
1404
+ */
1405
+ declare function createTool<TInput = Record<string, unknown>>(options: CreateToolOptions<TInput>): ToolDefinition<TInput>;
1406
+ /**
1407
+ * Shorthand for creating a tool
1408
+ *
1409
+ * @param name - Tool name
1410
+ * @param description - Tool description
1411
+ * @param inputSchema - Input schema
1412
+ * @param handler - Handler function
1413
+ * @returns Tool definition
1414
+ *
1415
+ * @example
1416
+ * ```typescript
1417
+ * const greetTool = tool(
1418
+ * 'greet',
1419
+ * 'Greet a person by name',
1420
+ * {
1421
+ * type: 'object',
1422
+ * properties: { name: { type: 'string' } },
1423
+ * required: ['name'],
1424
+ * },
1425
+ * async ({ name }) => ({
1426
+ * content: [{ type: 'text', text: `Hello, ${name}!` }],
1427
+ * })
1428
+ * );
1429
+ * ```
1430
+ */
1431
+ declare function tool<TInput = Record<string, unknown>>(name: string, description: string, inputSchema: ToolInputSchema | ZodLikeSchema, handler?: ToolHandler<TInput>): ToolDefinition<TInput>;
1432
+ /**
1433
+ * Create a browser-executed tool
1434
+ *
1435
+ * @param options - Tool configuration
1436
+ * @returns Tool definition that executes in the browser
1437
+ *
1438
+ * @example
1439
+ * ```typescript
1440
+ * const alertTool = browserTool({
1441
+ * name: 'show_alert',
1442
+ * description: 'Show an alert dialog',
1443
+ * inputSchema: {
1444
+ * type: 'object',
1445
+ * properties: { message: { type: 'string' } },
1446
+ * required: ['message'],
1447
+ * },
1448
+ * handler: async ({ message }) => {
1449
+ * alert(message);
1450
+ * return { content: [{ type: 'text', text: 'Alert shown' }] };
1451
+ * },
1452
+ * });
1453
+ * ```
1454
+ */
1455
+ declare function browserTool<TInput = Record<string, unknown>>(options: Omit<CreateToolOptions<TInput>, 'executeIn'>): ToolDefinition<TInput>;
1456
+ /**
1457
+ * Create a server-executed tool
1458
+ *
1459
+ * @param options - Tool configuration (handler is optional for server tools)
1460
+ * @returns Tool definition that executes on the server
1461
+ */
1462
+ declare function serverTool<TInput = Record<string, unknown>>(options: Omit<CreateToolOptions<TInput>, 'executeIn' | 'handler'>): ToolDefinition<TInput>;
1463
+ /**
1464
+ * Helper to create text content for tool results
1465
+ */
1466
+ declare function textResult(text: string): ToolResult;
1467
+ /**
1468
+ * Helper to create error result for tools
1469
+ */
1470
+ declare function errorResult(message: string): ToolResult;
1471
+ /**
1472
+ * Helper to create image content for tool results
1473
+ */
1474
+ declare function imageResult(data: string, mimeType: string): ToolResult;
1475
+
1476
+ /**
1477
+ * MCP Server Builder
1478
+ *
1479
+ * Builder pattern for creating MCP server definitions with multiple tools.
1480
+ */
1481
+
1482
+ /**
1483
+ * MCP Server builder for creating server definitions
1484
+ *
1485
+ * @example
1486
+ * ```typescript
1487
+ * const myServer = new McpServerBuilder('my-tools', '1.0.0')
1488
+ * .addTool({
1489
+ * name: 'greet',
1490
+ * description: 'Greet someone',
1491
+ * inputSchema: {
30
1492
  * type: 'object',
31
1493
  * properties: { name: { type: 'string' } },
32
1494
  * required: ['name'],
33
- * }, async ({ name }) => ({
1495
+ * },
1496
+ * handler: async ({ name }) => ({
34
1497
  * content: [{ type: 'text', text: `Hello, ${name}!` }],
35
- * })),
36
- * ],
1498
+ * }),
1499
+ * })
1500
+ * .addTool({
1501
+ * name: 'farewell',
1502
+ * description: 'Say goodbye',
1503
+ * inputSchema: {
1504
+ * type: 'object',
1505
+ * properties: { name: { type: 'string' } },
1506
+ * required: ['name'],
1507
+ * },
1508
+ * handler: async ({ name }) => ({
1509
+ * content: [{ type: 'text', text: `Goodbye, ${name}!` }],
1510
+ * }),
1511
+ * })
1512
+ * .build();
1513
+ * ```
1514
+ */
1515
+ declare class McpServerBuilder {
1516
+ private name;
1517
+ private version;
1518
+ private tools;
1519
+ /**
1520
+ * Create a new MCP server builder
1521
+ *
1522
+ * @param name - Server name
1523
+ * @param version - Server version (default: '1.0.0')
1524
+ */
1525
+ constructor(name: string, version?: string);
1526
+ /**
1527
+ * Add a tool to the server
1528
+ *
1529
+ * @param options - Tool configuration
1530
+ * @returns This builder for chaining
1531
+ */
1532
+ addTool<TInput = Record<string, unknown>>(options: CreateToolOptions<TInput>): this;
1533
+ /**
1534
+ * Add an existing tool definition
1535
+ *
1536
+ * @param tool - Tool definition
1537
+ * @returns This builder for chaining
1538
+ */
1539
+ add(tool: ToolDefinition): this;
1540
+ /**
1541
+ * Add multiple tools at once
1542
+ *
1543
+ * @param tools - Array of tool definitions
1544
+ * @returns This builder for chaining
1545
+ */
1546
+ addTools(tools: ToolDefinition[]): this;
1547
+ /**
1548
+ * Build the MCP server definition
1549
+ *
1550
+ * @returns Complete MCP server definition
1551
+ */
1552
+ build(): McpServerDefinition;
1553
+ }
1554
+ /**
1555
+ * Create an MCP server definition
1556
+ *
1557
+ * @param name - Server name
1558
+ * @param tools - Array of tool definitions
1559
+ * @param version - Server version
1560
+ * @returns MCP server definition
1561
+ *
1562
+ * @example
1563
+ * ```typescript
1564
+ * const server = createMcpServer('my-server', [
1565
+ * tool('greet', 'Greet someone', { type: 'object', properties: { name: { type: 'string' } } }),
1566
+ * tool('farewell', 'Say goodbye', { type: 'object', properties: { name: { type: 'string' } } }),
1567
+ * ]);
1568
+ * ```
1569
+ */
1570
+ declare function createMcpServer(name: string, tools: ToolDefinition[], version?: string): McpServerDefinition;
1571
+ /**
1572
+ * Create an MCP server using the builder pattern
1573
+ *
1574
+ * @param name - Server name
1575
+ * @param version - Server version
1576
+ * @returns MCP server builder
1577
+ *
1578
+ * @example
1579
+ * ```typescript
1580
+ * const server = mcpServer('my-tools')
1581
+ * .addTool({
1582
+ * name: 'hello',
1583
+ * description: 'Say hello',
1584
+ * inputSchema: { type: 'object', properties: {} },
1585
+ * handler: async () => ({ content: [{ type: 'text', text: 'Hello!' }] }),
1586
+ * })
1587
+ * .build();
1588
+ * ```
1589
+ */
1590
+ declare function mcpServer(name: string, version?: string): McpServerBuilder;
1591
+
1592
+ /**
1593
+ * Budget Token Types
1594
+ *
1595
+ * Types for JWT tokens used for authentication and budget control.
1596
+ */
1597
+ /**
1598
+ * Budget window types
1599
+ */
1600
+ type BudgetWindow = 'hour' | 'day' | 'week' | 'month';
1601
+ /**
1602
+ * Budget configuration in a token
1603
+ */
1604
+ interface TokenBudget {
1605
+ /** AI budget in microdollars (1 USD = 1,000,000 microdollars) */
1606
+ ai: number;
1607
+ /** Compute budget in seconds */
1608
+ compute: number;
1609
+ /** Budget window period */
1610
+ window: BudgetWindow;
1611
+ /** When current period started (ISO 8601) */
1612
+ windowStart: string;
1613
+ }
1614
+ /**
1615
+ * Permission configuration in a token
1616
+ */
1617
+ interface TokenPermissions {
1618
+ /** Allowed tool names */
1619
+ tools?: string[];
1620
+ /** Blocked tool names */
1621
+ blockedTools?: string[];
1622
+ /** Maximum turns per conversation */
1623
+ maxTurns?: number;
1624
+ /** Model restriction */
1625
+ model?: string;
1626
+ }
1627
+ /**
1628
+ * SDK configuration overrides in a token
1629
+ * When present, these values SUPERSEDE options provided by the SDK client
1630
+ */
1631
+ interface TokenSdkConfig {
1632
+ /** Model to use */
1633
+ model?: string;
1634
+ /** System prompt */
1635
+ systemPrompt?: string;
1636
+ /** Tools configuration */
1637
+ tools?: unknown;
1638
+ /** Allowed tools */
1639
+ allowedTools?: string[];
1640
+ /** Disallowed tools */
1641
+ disallowedTools?: string[];
1642
+ /** Maximum turns */
1643
+ maxTurns?: number;
1644
+ /** Maximum budget in USD */
1645
+ maxBudgetUsd?: number;
1646
+ /** Maximum thinking tokens */
1647
+ maxThinkingTokens?: number;
1648
+ /** Permission mode */
1649
+ permissionMode?: string;
1650
+ /** Allow dangerous skip permissions */
1651
+ allowDangerouslySkipPermissions?: boolean;
1652
+ /** MCP servers configuration */
1653
+ mcpServers?: unknown[];
1654
+ /** Agents configuration */
1655
+ agents?: unknown;
1656
+ /** Betas configuration */
1657
+ betas?: string[];
1658
+ /** Output format */
1659
+ outputFormat?: string;
1660
+ /** Environment variables */
1661
+ env?: Record<string, string>;
1662
+ }
1663
+ /**
1664
+ * Budget token payload (JWT claims)
1665
+ */
1666
+ interface BudgetTokenPayload {
1667
+ /** User ID - unique identifier for the end user */
1668
+ sub: string;
1669
+ /** Project/Issuer ID - identifies which project */
1670
+ iss: string;
1671
+ /** Token expiry timestamp (Unix seconds) */
1672
+ exp: number;
1673
+ /** Issued at timestamp (Unix seconds) */
1674
+ iat?: number;
1675
+ /** Budget declaration */
1676
+ budget: TokenBudget;
1677
+ /** Permission configuration (optional) */
1678
+ permissions?: TokenPermissions;
1679
+ /** SDK config overrides (optional) */
1680
+ sdkConfig?: TokenSdkConfig;
1681
+ }
1682
+ /**
1683
+ * Options for creating a budget token
1684
+ */
1685
+ interface CreateTokenOptions {
1686
+ /** User ID */
1687
+ userId: string;
1688
+ /** Project/Issuer ID (UUID) */
1689
+ projectId: string;
1690
+ /** HMAC secret key for signing */
1691
+ secret: string;
1692
+ /** Token expiry duration in seconds (default: 3600 = 1 hour) */
1693
+ expiresIn?: number;
1694
+ /** Budget configuration */
1695
+ budget: TokenBudget;
1696
+ /** Permission configuration */
1697
+ permissions?: TokenPermissions;
1698
+ /** SDK config overrides */
1699
+ sdkConfig?: TokenSdkConfig;
1700
+ }
1701
+ /**
1702
+ * Decoded token result
1703
+ */
1704
+ interface DecodedToken {
1705
+ /** Token header */
1706
+ header: {
1707
+ alg: string;
1708
+ typ: string;
1709
+ };
1710
+ /** Token payload */
1711
+ payload: BudgetTokenPayload;
1712
+ /** Token signature (base64url) */
1713
+ signature: string;
1714
+ }
1715
+
1716
+ /**
1717
+ * Token Utilities
1718
+ *
1719
+ * Helpers for creating and decoding JWT tokens for authentication.
1720
+ * These are primarily for server-side use (Node.js).
1721
+ */
1722
+
1723
+ /**
1724
+ * Create a budget token (JWT) for authenticating with Chucky
1725
+ *
1726
+ * @param options - Token creation options
1727
+ * @returns Signed JWT token
1728
+ *
1729
+ * @example
1730
+ * ```typescript
1731
+ * // Server-side token creation
1732
+ * const token = await createToken({
1733
+ * userId: 'user-123',
1734
+ * projectId: '550e8400-e29b-41d4-a716-446655440000',
1735
+ * secret: 'your-hmac-secret',
1736
+ * budget: {
1737
+ * ai: 1_000_000, // $1 in microdollars
1738
+ * compute: 3600, // 1 hour
1739
+ * window: 'day',
1740
+ * windowStart: new Date().toISOString(),
1741
+ * },
37
1742
  * });
1743
+ * ```
1744
+ */
1745
+ declare function createToken(options: CreateTokenOptions): Promise<string>;
1746
+ /**
1747
+ * Decode a token without verification
38
1748
  *
39
- * // Send a message
40
- * const result = await session.send('Greet the world!');
41
- * console.log(result.text);
1749
+ * @param token - JWT token to decode
1750
+ * @returns Decoded token parts
42
1751
  *
43
- * // Or stream the response
44
- * for await (const event of session.sendStream('Tell me a story')) {
45
- * if (event.type === 'text') {
46
- * process.stdout.write(event.text);
47
- * }
1752
+ * @example
1753
+ * ```typescript
1754
+ * const decoded = decodeToken(token);
1755
+ * console.log(decoded.payload.sub); // User ID
1756
+ * console.log(decoded.payload.budget); // Budget limits
1757
+ * ```
1758
+ */
1759
+ declare function decodeToken(token: string): DecodedToken;
1760
+ /**
1761
+ * Verify a token signature
1762
+ *
1763
+ * @param token - JWT token to verify
1764
+ * @param secret - HMAC secret for verification
1765
+ * @returns True if signature is valid
1766
+ *
1767
+ * @example
1768
+ * ```typescript
1769
+ * const isValid = await verifyToken(token, 'your-hmac-secret');
1770
+ * if (!isValid) {
1771
+ * throw new Error('Invalid token');
48
1772
  * }
49
1773
  * ```
1774
+ */
1775
+ declare function verifyToken(token: string, secret: string): Promise<boolean>;
1776
+ /**
1777
+ * Check if a token is expired
1778
+ *
1779
+ * @param token - JWT token to check
1780
+ * @returns True if token is expired
1781
+ */
1782
+ declare function isTokenExpired(token: string): boolean;
1783
+ /**
1784
+ * @deprecated The project ID is now separate from the HMAC key for security reasons.
1785
+ * Get your project ID from the Chucky portal (app.chucky.cloud) instead.
1786
+ *
1787
+ * Previously, the HMAC key embedded the project ID, but this exposed the secret
1788
+ * in JWT tokens. Project IDs are now Convex document IDs visible in the portal.
1789
+ *
1790
+ * @param _hmacKey - Ignored (previously used to extract project ID)
1791
+ * @throws Always throws an error directing users to get project ID from portal
1792
+ */
1793
+ declare function extractProjectId(_hmacKey: string): never;
1794
+ /**
1795
+ * Create a simple budget configuration
1796
+ *
1797
+ * @param options - Budget options
1798
+ * @returns Budget configuration
1799
+ *
1800
+ * @example
1801
+ * ```typescript
1802
+ * const budget = createBudget({
1803
+ * aiDollars: 1.00, // $1 AI budget
1804
+ * computeHours: 1, // 1 hour compute
1805
+ * window: 'day',
1806
+ * });
1807
+ * ```
1808
+ */
1809
+ declare function createBudget(options: {
1810
+ /** AI budget in dollars */
1811
+ aiDollars: number;
1812
+ /** Compute budget in hours */
1813
+ computeHours: number;
1814
+ /** Budget window */
1815
+ window: 'hour' | 'day' | 'week' | 'month';
1816
+ /** Window start (default: now) */
1817
+ windowStart?: Date;
1818
+ }): TokenBudget;
1819
+
1820
+ /**
1821
+ * Error Classes
50
1822
  *
51
- * @packageDocumentation
52
- */
53
- export { ChuckyClient, createClient, getAssistantText, getResultText } from './client/index.js';
54
- export { Session } from './client/index.js';
55
- export type { SessionEventHandlers } from './client/index.js';
56
- export { createTool, tool, browserTool, serverTool, textResult, errorResult, imageResult, McpServerBuilder, createMcpServer, mcpServer, } from './tools/index.js';
57
- export type { CreateToolOptions } from './tools/index.js';
58
- export { createToken, decodeToken, verifyToken, isTokenExpired, extractProjectId, createBudget, } from './utils/index.js';
59
- export { ChuckyError, ConnectionError, AuthenticationError, BudgetExceededError, ConcurrencyLimitError, RateLimitError, SessionError, ToolExecutionError, TimeoutError, ValidationError, createError, } from './utils/index.js';
60
- export { WebSocketTransport } from './transport/index.js';
61
- export type { Transport, TransportConfig, TransportEvents } from './transport/index.js';
62
- export type { Model, SystemPrompt, OutputFormat, AgentDefinition, BaseOptions, SessionOptions, PromptOptions, ClientOptions, ConnectionStatus, ClientEventHandlers, } from './types/index.js';
63
- export type { JsonSchemaType, JsonSchemaProperty, ToolInputSchema, ToolContentType, ToolTextContent, ToolImageContent, ResourceContent, ToolContent, ToolResult, ToolExecutionLocation, ToolHandler, ToolDefinition, McpServerDefinition, ToolCall, ToolCallResponse, } from './types/index.js';
64
- export type { UUID, SDKTextContent, SDKImageContent, ToolUseContent, ToolResultContent, SDKContentBlock, APIUserMessage, APIAssistantMessage, SDKUserMessage, SDKAssistantMessage, SDKResultMessage, SDKResultMessageSuccess, SDKResultMessageError, ResultSubtype, SDKSystemMessage, SDKSystemMessageInit, SDKSystemMessageCompact, SystemSubtype, SDKPartialAssistantMessage, SDKMessage, WsEnvelopeType, InitPayload, ControlAction, ControlPayload, ErrorPayload, OutgoingMessage, IncomingMessage, } from './types/index.js';
65
- export type { BudgetWindow, TokenBudget, TokenPermissions, TokenSdkConfig, BudgetTokenPayload, CreateTokenOptions, DecodedToken, } from './types/index.js';
66
- export type { MessageRole, ContentBlockType, TextBlock, ToolUseBlock, ToolResultBlock, ThinkingBlock, ImageBlock, Message, Usage, CostBreakdown, SessionResult, PromptResult, StreamEvent, PartialMessage, SessionState, SessionInfo, } from './types/index.js';
67
- export { createInitMessage, createUserMessage, createControlMessage, createPingMessage, createToolResultMessage, isUserMessage, isAssistantMessage, isResultMessage, isSuccessResult, isErrorResult, isSystemMessage, isStreamEvent, isToolCallMessage, isControlMessage, isErrorMessage, } from './types/index.js';
68
- //# sourceMappingURL=index.d.ts.map
1823
+ * Custom error types for the Chucky SDK.
1824
+ */
1825
+ /**
1826
+ * Base error class for Chucky SDK errors
1827
+ */
1828
+ declare class ChuckyError extends Error {
1829
+ /** Error code */
1830
+ readonly code: string;
1831
+ /** Additional error details */
1832
+ readonly details?: Record<string, unknown>;
1833
+ constructor(message: string, code: string, details?: Record<string, unknown>);
1834
+ }
1835
+ /**
1836
+ * Connection error
1837
+ */
1838
+ declare class ConnectionError extends ChuckyError {
1839
+ constructor(message: string, details?: Record<string, unknown>);
1840
+ }
1841
+ /**
1842
+ * Authentication error
1843
+ */
1844
+ declare class AuthenticationError extends ChuckyError {
1845
+ constructor(message: string, details?: Record<string, unknown>);
1846
+ }
1847
+ /**
1848
+ * Budget exceeded error
1849
+ */
1850
+ declare class BudgetExceededError extends ChuckyError {
1851
+ constructor(message: string, details?: Record<string, unknown>);
1852
+ }
1853
+ /**
1854
+ * Concurrency limit error
1855
+ */
1856
+ declare class ConcurrencyLimitError extends ChuckyError {
1857
+ constructor(message: string, details?: Record<string, unknown>);
1858
+ }
1859
+ /**
1860
+ * Rate limit error
1861
+ */
1862
+ declare class RateLimitError extends ChuckyError {
1863
+ constructor(message: string, details?: Record<string, unknown>);
1864
+ }
1865
+ /**
1866
+ * Session error
1867
+ */
1868
+ declare class SessionError extends ChuckyError {
1869
+ constructor(message: string, details?: Record<string, unknown>);
1870
+ }
1871
+ /**
1872
+ * Tool execution error
1873
+ */
1874
+ declare class ToolExecutionError extends ChuckyError {
1875
+ /** Tool name */
1876
+ readonly toolName: string;
1877
+ constructor(message: string, toolName: string, details?: Record<string, unknown>);
1878
+ }
1879
+ /**
1880
+ * Timeout error
1881
+ */
1882
+ declare class TimeoutError extends ChuckyError {
1883
+ constructor(message: string, details?: Record<string, unknown>);
1884
+ }
1885
+ /**
1886
+ * Validation error
1887
+ */
1888
+ declare class ValidationError extends ChuckyError {
1889
+ constructor(message: string, details?: Record<string, unknown>);
1890
+ }
1891
+ /**
1892
+ * Create appropriate error from message and optional code
1893
+ */
1894
+ declare function createError(message: string, code?: string): ChuckyError;
1895
+
1896
+ /**
1897
+ * WebSocket Transport
1898
+ *
1899
+ * WebSocket-based transport that works in both browser and Node.js.
1900
+ * Handles connection management, keep-alive, and reconnection.
1901
+ */
1902
+
1903
+ /**
1904
+ * WebSocket transport configuration
1905
+ */
1906
+ interface WebSocketTransportConfig extends TransportConfig {
1907
+ /** Protocol to use (default: determined from URL) */
1908
+ protocol?: 'ws' | 'wss';
1909
+ }
1910
+ /**
1911
+ * WebSocket transport implementation
1912
+ */
1913
+ declare class WebSocketTransport extends BaseTransport {
1914
+ private ws;
1915
+ private keepAliveTimer;
1916
+ private reconnectAttempts;
1917
+ private reconnectTimer;
1918
+ private readyPromise;
1919
+ private readyResolve;
1920
+ private readyReject;
1921
+ private messageQueue;
1922
+ constructor(config: WebSocketTransportConfig);
1923
+ /**
1924
+ * Build the WebSocket URL with token
1925
+ */
1926
+ private buildUrl;
1927
+ /**
1928
+ * Connect to the WebSocket server
1929
+ */
1930
+ connect(): Promise<void>;
1931
+ /**
1932
+ * Disconnect from the server
1933
+ */
1934
+ disconnect(): Promise<void>;
1935
+ /**
1936
+ * Send a message to the server
1937
+ */
1938
+ send(message: OutgoingMessage): Promise<void>;
1939
+ /**
1940
+ * Send a message immediately
1941
+ */
1942
+ private sendImmediate;
1943
+ /**
1944
+ * Wait for the connection to be ready
1945
+ */
1946
+ waitForReady(): Promise<void>;
1947
+ /**
1948
+ * Handle incoming message
1949
+ */
1950
+ private handleMessage;
1951
+ /**
1952
+ * Start keep-alive ping
1953
+ */
1954
+ private startKeepAlive;
1955
+ /**
1956
+ * Stop keep-alive ping
1957
+ */
1958
+ private stopKeepAlive;
1959
+ /**
1960
+ * Schedule a reconnection attempt
1961
+ */
1962
+ private scheduleReconnect;
1963
+ /**
1964
+ * Clear reconnect timer
1965
+ */
1966
+ private clearReconnectTimer;
1967
+ /**
1968
+ * Flush queued messages
1969
+ */
1970
+ private flushMessageQueue;
1971
+ }
1972
+
1973
+ export { type APIAssistantMessage, type APIUserMessage, type AgentDefinition, AuthenticationError, type BaseOptions, BudgetExceededError, type BudgetTokenPayload, type BudgetWindow, ChuckyClient, ChuckyError, type ClientEventHandlers, type ClientOptions, ConcurrencyLimitError, ConnectionError, type ConnectionStatus, type ContentBlockType, type ControlAction, type ControlPayload, type CostBreakdown, type CreateTokenOptions, type CreateToolOptions, type DecodedToken, type ErrorPayload, type ImageBlock, type IncomingMessage, type InitPayload, type JsonSchemaProperty, type JsonSchemaType, McpServerBuilder, type McpServerDefinition, type Message, type MessageRole, type Model, type OutgoingMessage, type OutputFormat, type PartialMessage, type PromptOptions, type PromptResult, RateLimitError, type ResourceContent, type ResultSubtype, type SDKAssistantMessage, type ContentBlock$1 as SDKContentBlock, type ImageContent as SDKImageContent, type SDKMessage, type SDKPartialAssistantMessage, type SDKResultMessage, type SDKResultMessageError, type SDKResultMessageSuccess, type SDKSystemMessage, type SDKSystemMessageCompact, type SDKSystemMessageInit, type TextContent as SDKTextContent, type SDKUserMessage, Session, SessionError, type SessionEventHandlers, type SessionInfo, type SessionOptions, type SessionResult, type SessionState, type StreamEvent, type SystemPrompt, type SystemSubtype, type TextBlock, type ThinkingBlock, TimeoutError, type TokenBudget, type TokenPermissions, type TokenSdkConfig, type ToolCall, type ToolCallResponse, type ToolContent, type ToolContentType, type ToolDefinition, ToolExecutionError, type ToolExecutionLocation, type ToolHandler, type ToolImageContent, type ToolInputSchema, type ToolResult, type ToolResultBlock, type ToolResultContent, type ToolTextContent, type ToolUseBlock, type ToolUseContent, type Transport, type TransportConfig, type TransportEvents, type UUID, type Usage, ValidationError, WebSocketTransport, type WsEnvelopeType, browserTool, createBudget, createClient, createControlMessage, createError, createInitMessage, createMcpServer, createPingMessage, createToken, createTool, createToolResultMessage, createUserMessage, decodeToken, errorResult, extractProjectId, getAssistantText, getResultText, imageResult, isAssistantMessage, isControlMessage, isErrorMessage, isErrorResult, isResultMessage, isStreamEvent, isSuccessResult, isSystemMessage, isTokenExpired, isToolCallMessage, isUserMessage, mcpServer, serverTool, textResult, tool, verifyToken };