@steventsao/agent-session-core 0.1.12 → 0.1.13

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.
package/dist/index.d.ts CHANGED
@@ -1,10 +1,732 @@
1
+ import { z } from 'zod';
2
+
1
3
  /**
2
- * @agent-session/core
4
+ * Centralized WebSocket Events
3
5
  *
4
- * Shared types and protocol for agent-session.
5
- * Used by both client and server packages.
6
+ * Single source of truth for all socket event types used across:
7
+ * - SessionSocket Durable Object (Cloudflare Worker)
8
+ * - Client applications (React, etc.)
9
+ * - E2B sandbox communication
6
10
  */
7
- export * from './socket-events';
8
- export * from './types';
9
- export * from './session-config';
10
- //# sourceMappingURL=index.d.ts.map
11
+
12
+ declare const ClientEventType: {
13
+ readonly INIT: "INIT";
14
+ readonly PING: "PING";
15
+ readonly JOIN_SESSION: "JOIN_SESSION";
16
+ readonly START_SANDBOX: "START_SANDBOX";
17
+ readonly STOP_SANDBOX: "STOP_SANDBOX";
18
+ readonly EXEC: "EXEC";
19
+ readonly AGENT_MESSAGE: "AGENT_MESSAGE";
20
+ readonly AGENT_STOP: "AGENT_STOP";
21
+ readonly AGENT_RESET: "AGENT_RESET";
22
+ };
23
+ type ClientEventType = (typeof ClientEventType)[keyof typeof ClientEventType];
24
+ declare const ServerEventType: {
25
+ readonly CONNECTED: "CONNECTED";
26
+ readonly READY: "READY";
27
+ readonly PONG: "PONG";
28
+ readonly MESSAGE_ACK: "MESSAGE_ACK";
29
+ readonly MESSAGE_ERROR: "MESSAGE_ERROR";
30
+ readonly EVENTS_BATCH: "EVENTS_BATCH";
31
+ readonly SANDBOX_STATUS: "SANDBOX_STATUS";
32
+ readonly LIFECYCLE: "LIFECYCLE";
33
+ readonly TERM_DATA: "TERM_DATA";
34
+ readonly EXEC_COMPLETE: "EXEC_COMPLETE";
35
+ readonly SYSTEM: "SYSTEM";
36
+ readonly ERROR: "ERROR";
37
+ readonly AGENT_STARTED: "AGENT_STARTED";
38
+ readonly AGENT_MESSAGE: "AGENT_MESSAGE";
39
+ readonly AGENT_ACTION: "AGENT_ACTION";
40
+ readonly AGENT_STEP_COMPLETE: "AGENT_STEP_COMPLETE";
41
+ readonly AGENT_DONE: "AGENT_DONE";
42
+ readonly AGENT_ERROR: "AGENT_ERROR";
43
+ readonly AGENT_EVENT: "AGENT_EVENT";
44
+ readonly FILE_UPLOADED: "FILE_UPLOADED";
45
+ readonly FILES_SYNC: "FILES_SYNC";
46
+ readonly TOC_REQUEST_RECEIVED: "TOC_REQUEST_RECEIVED";
47
+ readonly TOC_AUTH_COMPLETED: "TOC_AUTH_COMPLETED";
48
+ readonly TOC_DB_QUERY_STARTED: "TOC_DB_QUERY_STARTED";
49
+ readonly TOC_DB_QUERY_COMPLETED: "TOC_DB_QUERY_COMPLETED";
50
+ readonly TOC_GCS_DOWNLOAD_STARTED: "TOC_GCS_DOWNLOAD_STARTED";
51
+ readonly TOC_GCS_DOWNLOAD_COMPLETED: "TOC_GCS_DOWNLOAD_COMPLETED";
52
+ readonly TOC_SANDBOX_CREATED: "TOC_SANDBOX_CREATED";
53
+ readonly TOC_EXTRACTION_STARTED: "TOC_EXTRACTION_STARTED";
54
+ readonly TOC_EXTRACTION_COMPLETED: "TOC_EXTRACTION_COMPLETED";
55
+ readonly TOC_RESPONSE_READY: "TOC_RESPONSE_READY";
56
+ };
57
+ type ServerEventType = (typeof ServerEventType)[keyof typeof ServerEventType];
58
+ declare const SandboxStatus: {
59
+ readonly IDLE: "idle";
60
+ readonly BOOTING: "booting";
61
+ readonly READY: "ready";
62
+ readonly ERROR: "error";
63
+ };
64
+ type SandboxStatus = (typeof SandboxStatus)[keyof typeof SandboxStatus];
65
+ /**
66
+ * Granular lifecycle phases for UI loading states
67
+ * Common lifecycle events across different app types:
68
+ * - idle: No sandbox running
69
+ * - booting: Creating sandbox instance
70
+ * - environment_ready: Sandbox created, basic environment up
71
+ * - files_ready: App files synced/loaded (for app builders)
72
+ * - installing: Installing dependencies
73
+ * - starting: Starting services (dev server, etc.)
74
+ * - interaction_ready: Ready for user interaction (agent can respond)
75
+ * - ready: Fully ready (deprecated alias for interaction_ready)
76
+ * - error: Something went wrong
77
+ */
78
+ declare const SandboxLifecycle: {
79
+ readonly IDLE: "idle";
80
+ readonly BOOTING: "booting";
81
+ readonly ENVIRONMENT_READY: "environment_ready";
82
+ readonly FILES_READY: "files_ready";
83
+ readonly INSTALLING: "installing";
84
+ readonly STARTING: "starting";
85
+ readonly INTERACTION_READY: "interaction_ready";
86
+ readonly READY: "ready";
87
+ readonly ERROR: "error";
88
+ };
89
+ type SandboxLifecycle = (typeof SandboxLifecycle)[keyof typeof SandboxLifecycle];
90
+ /**
91
+ * Parse SYSTEM message to SandboxLifecycle phase
92
+ */
93
+ declare function parseSystemMessageToLifecycle(msg: string): SandboxLifecycle | null;
94
+ interface InitEvent {
95
+ type: 'INIT';
96
+ userId?: string;
97
+ metadata?: Record<string, unknown>;
98
+ }
99
+ interface PingEvent {
100
+ type: 'PING';
101
+ }
102
+ /**
103
+ * Join session with optional cursor for event resumption (Manus pattern)
104
+ * On reconnect, client sends lastEventId to receive missed events
105
+ */
106
+ interface JoinSessionEvent {
107
+ type: 'JOIN_SESSION';
108
+ /** Last event ID received - server will send events after this cursor */
109
+ lastEventId?: string;
110
+ }
111
+ /**
112
+ * Bootstrap options for sandbox file pre-population
113
+ *
114
+ * Supports three strategies (in order of preference):
115
+ * 1. archiveUrl: Single tar.gz archive - fastest for many files
116
+ * 2. bootstrapUrl: Fetch file manifest with individual URLs
117
+ * 3. files: Inline files (legacy, causes WebSocket bloat)
118
+ */
119
+ interface SandboxBootstrapOptions {
120
+ /** URL to tar.gz archive containing all workspace files (preferred) */
121
+ archiveUrl?: string;
122
+ /** URL to fetch file manifest (returns SandboxFile[]) */
123
+ bootstrapUrl?: string;
124
+ /** Inline files to write directly */
125
+ files?: SandboxFile[];
126
+ /** Headers to include when fetching bootstrapUrl or archiveUrl */
127
+ headers?: Record<string, string>;
128
+ }
129
+ interface StartSandboxEvent {
130
+ type: 'START_SANDBOX';
131
+ template?: string;
132
+ /** Bootstrap options for file pre-population before agent starts */
133
+ bootstrap?: SandboxBootstrapOptions;
134
+ }
135
+ interface StopSandboxEvent {
136
+ type: 'STOP_SANDBOX';
137
+ }
138
+ interface ExecEvent {
139
+ type: 'EXEC';
140
+ cmd: string;
141
+ cwd?: string;
142
+ }
143
+ /**
144
+ * Identity of the message sender — enables multi-client attribution
145
+ * in shared WebSocket sessions (web + CLI + API).
146
+ */
147
+ interface MessageAuthor {
148
+ name: string;
149
+ clientType?: 'web' | 'cli' | 'api';
150
+ clientId?: string;
151
+ }
152
+ interface AgentMessageClientEvent {
153
+ type: 'AGENT_MESSAGE';
154
+ /** Client-generated message ID for deterministic ack handling */
155
+ clientMessageId?: string;
156
+ content: string;
157
+ /** Who sent this message — for multi-client attribution */
158
+ author?: MessageAuthor;
159
+ model?: {
160
+ id: string;
161
+ provider?: string;
162
+ };
163
+ config?: {
164
+ temperature?: number;
165
+ maxTokens?: number;
166
+ };
167
+ /** Direct system prompt text */
168
+ systemPrompt?: string;
169
+ /** Named prompt template (e.g., "claude-code") */
170
+ systemPromptName?: string;
171
+ /** Variables to compile into the prompt template */
172
+ systemPromptVariables?: Record<string, string>;
173
+ agentType?: string;
174
+ }
175
+ interface AgentStopEvent {
176
+ type: 'AGENT_STOP';
177
+ }
178
+ interface AgentResetEvent {
179
+ type: 'AGENT_RESET';
180
+ }
181
+ type ClientEvent = InitEvent | PingEvent | JoinSessionEvent | StartSandboxEvent | StopSandboxEvent | ExecEvent | AgentMessageClientEvent | AgentStopEvent | AgentResetEvent;
182
+ /**
183
+ * Optional metadata added to persistable server events
184
+ * Events with eventId can be replayed on reconnection
185
+ */
186
+ interface ServerEventMeta {
187
+ /** Unique event identifier for cursor-based resumption */
188
+ eventId?: string;
189
+ /** Monotonic event sequence for deterministic replay */
190
+ eventSequence?: number;
191
+ /** Server timestamp when event was created */
192
+ eventTimestamp?: number;
193
+ }
194
+ interface ConnectedServerEvent {
195
+ type: 'CONNECTED';
196
+ clientId: string;
197
+ sessionId: string;
198
+ }
199
+ interface ReadyServerEvent {
200
+ type: 'READY';
201
+ sandboxId: string | null;
202
+ sandboxUrl: string | null;
203
+ }
204
+ /**
205
+ * Batch of events sent on reconnection (Manus eventsNotifyEventsAfter pattern)
206
+ * Contains all events since the client's lastEventId cursor
207
+ */
208
+ interface EventsBatchServerEvent {
209
+ type: 'EVENTS_BATCH';
210
+ /** Events since last cursor, in chronological order */
211
+ events: PersistableServerEvent[];
212
+ /** Latest event ID - client should use this as next cursor */
213
+ lastEventId: string;
214
+ /** Total events in batch */
215
+ count: number;
216
+ }
217
+ interface PongServerEvent {
218
+ type: 'PONG';
219
+ timestamp: number;
220
+ }
221
+ interface SandboxStatusServerEvent {
222
+ type: 'SANDBOX_STATUS';
223
+ status: 'idle' | 'booting' | 'ready' | 'error';
224
+ sandboxId?: string;
225
+ sandboxUrl?: string;
226
+ error?: string;
227
+ }
228
+ /**
229
+ * Lifecycle event - granular phase transitions
230
+ * Use for loading UI states and progress indicators
231
+ */
232
+ interface LifecycleServerEvent {
233
+ type: 'LIFECYCLE';
234
+ phase: SandboxLifecycle;
235
+ message?: string;
236
+ progress?: number;
237
+ metadata?: Record<string, unknown>;
238
+ }
239
+ interface TermDataServerEvent {
240
+ type: 'TERM_DATA';
241
+ data: string;
242
+ stream: 'stdout' | 'stderr';
243
+ }
244
+ interface ExecCompleteServerEvent {
245
+ type: 'EXEC_COMPLETE';
246
+ exitCode: number;
247
+ }
248
+ interface SystemServerEvent {
249
+ type: 'SYSTEM';
250
+ msg: string;
251
+ }
252
+ interface ErrorServerEvent {
253
+ type: 'ERROR';
254
+ msg: string;
255
+ code?: string;
256
+ }
257
+ interface MessageAckServerEvent {
258
+ type: 'MESSAGE_ACK';
259
+ clientMessageId: string;
260
+ receivedAt: number;
261
+ }
262
+ interface MessageErrorServerEvent {
263
+ type: 'MESSAGE_ERROR';
264
+ clientMessageId: string;
265
+ error: string;
266
+ }
267
+ interface FileUploadedServerEvent {
268
+ type: 'FILE_UPLOADED';
269
+ path: string;
270
+ filename: string;
271
+ url: string;
272
+ mimeType: string;
273
+ description?: string;
274
+ sizeBytes?: number;
275
+ }
276
+ /**
277
+ * File to write to sandbox during bootstrap
278
+ */
279
+ interface SandboxFile {
280
+ path: string;
281
+ content?: string;
282
+ url?: string;
283
+ encoding?: 'utf-8' | 'base64';
284
+ }
285
+ interface SandboxFile {
286
+ path: string;
287
+ name: string;
288
+ isDir: boolean;
289
+ size?: number;
290
+ }
291
+ interface FilesSyncServerEvent {
292
+ type: 'FILES_SYNC';
293
+ files: SandboxFile[];
294
+ dirs: string[];
295
+ }
296
+ interface AgentStartedServerEvent {
297
+ type: 'AGENT_STARTED';
298
+ prompt?: string;
299
+ clientMessageId?: string;
300
+ /** Who triggered this agent run — copied from client event */
301
+ author?: MessageAuthor;
302
+ }
303
+ interface TextContentBlock {
304
+ type: 'text';
305
+ text: string;
306
+ }
307
+ interface ToolUseContentBlock {
308
+ type: 'tool_use';
309
+ id: string;
310
+ name: string;
311
+ input: Record<string, unknown>;
312
+ }
313
+ interface ToolResultContentBlock {
314
+ type: 'tool_result';
315
+ tool_use_id: string;
316
+ content: string | null;
317
+ is_error?: boolean;
318
+ }
319
+ type ContentBlock = TextContentBlock | ToolUseContentBlock | ToolResultContentBlock;
320
+ interface AgentMessageServerEvent {
321
+ type: 'AGENT_MESSAGE';
322
+ message?: {
323
+ content: ContentBlock[];
324
+ };
325
+ subtype?: string;
326
+ total_cost_usd?: number | null;
327
+ duration_ms?: number | null;
328
+ result?: string | null;
329
+ clientMessageId?: string;
330
+ }
331
+ interface AgentActionServerEvent {
332
+ type: 'AGENT_ACTION';
333
+ action: string;
334
+ id?: string;
335
+ input?: unknown;
336
+ status: 'executing' | 'complete' | 'error';
337
+ result?: string;
338
+ error?: string;
339
+ }
340
+ interface AgentStepCompleteServerEvent {
341
+ type: 'AGENT_STEP_COMPLETE';
342
+ success?: boolean;
343
+ cost?: number;
344
+ duration?: number;
345
+ }
346
+ interface AgentDoneServerEvent {
347
+ type: 'AGENT_DONE';
348
+ exitCode?: number;
349
+ sessionId?: string;
350
+ clientMessageId?: string;
351
+ }
352
+ interface AgentErrorServerEvent {
353
+ type: 'AGENT_ERROR';
354
+ error: string;
355
+ clientMessageId?: string;
356
+ }
357
+ interface AgentGenericServerEvent {
358
+ type: 'AGENT_EVENT';
359
+ [key: string]: unknown;
360
+ }
361
+ interface TocEventServerEvent {
362
+ type: 'TOC_REQUEST_RECEIVED' | 'TOC_AUTH_COMPLETED' | 'TOC_DB_QUERY_STARTED' | 'TOC_DB_QUERY_COMPLETED' | 'TOC_GCS_DOWNLOAD_STARTED' | 'TOC_GCS_DOWNLOAD_COMPLETED' | 'TOC_SANDBOX_CREATED' | 'TOC_EXTRACTION_STARTED' | 'TOC_EXTRACTION_COMPLETED' | 'TOC_RESPONSE_READY';
363
+ data?: Record<string, unknown>;
364
+ cost?: {
365
+ duration_ms?: number;
366
+ total_usd?: number;
367
+ input_tokens?: number;
368
+ output_tokens?: number;
369
+ };
370
+ }
371
+ /**
372
+ * Events that should be persisted and replayed on reconnection
373
+ * These events have state significance (not ephemeral like PONG)
374
+ */
375
+ type PersistableServerEvent = (SandboxStatusServerEvent | LifecycleServerEvent | AgentStartedServerEvent | AgentMessageServerEvent | AgentActionServerEvent | AgentDoneServerEvent | AgentErrorServerEvent | SystemServerEvent | TocEventServerEvent) & ServerEventMeta;
376
+ /**
377
+ * Event types that should NOT be persisted (ephemeral)
378
+ */
379
+ declare const EPHEMERAL_EVENT_TYPES: Set<string>;
380
+ /**
381
+ * Check if a server event should be persisted for replay
382
+ */
383
+ declare function isPersistableEvent(event: ServerEvent): boolean;
384
+ type ServerEvent = ConnectedServerEvent | ReadyServerEvent | EventsBatchServerEvent | PongServerEvent | MessageAckServerEvent | MessageErrorServerEvent | SandboxStatusServerEvent | LifecycleServerEvent | TermDataServerEvent | ExecCompleteServerEvent | SystemServerEvent | ErrorServerEvent | FileUploadedServerEvent | FilesSyncServerEvent | AgentStartedServerEvent | AgentMessageServerEvent | AgentActionServerEvent | AgentStepCompleteServerEvent | AgentDoneServerEvent | AgentErrorServerEvent | AgentGenericServerEvent | TocEventServerEvent;
385
+ declare const ToolUseBlockSchema: z.ZodObject<{
386
+ type: z.ZodLiteral<"tool_use">;
387
+ name: z.ZodString;
388
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
389
+ }, "strip", z.ZodTypeAny, {
390
+ type: "tool_use";
391
+ name: string;
392
+ input?: Record<string, unknown> | undefined;
393
+ }, {
394
+ type: "tool_use";
395
+ name: string;
396
+ input?: Record<string, unknown> | undefined;
397
+ }>;
398
+ declare const TextBlockSchema: z.ZodObject<{
399
+ type: z.ZodLiteral<"text">;
400
+ text: z.ZodString;
401
+ }, "strip", z.ZodTypeAny, {
402
+ text: string;
403
+ type: "text";
404
+ }, {
405
+ text: string;
406
+ type: "text";
407
+ }>;
408
+ declare const ContentBlockSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
409
+ type: z.ZodLiteral<"tool_use">;
410
+ name: z.ZodString;
411
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
412
+ }, "strip", z.ZodTypeAny, {
413
+ type: "tool_use";
414
+ name: string;
415
+ input?: Record<string, unknown> | undefined;
416
+ }, {
417
+ type: "tool_use";
418
+ name: string;
419
+ input?: Record<string, unknown> | undefined;
420
+ }>, z.ZodObject<{
421
+ type: z.ZodLiteral<"text">;
422
+ text: z.ZodString;
423
+ }, "strip", z.ZodTypeAny, {
424
+ text: string;
425
+ type: "text";
426
+ }, {
427
+ text: string;
428
+ type: "text";
429
+ }>]>;
430
+ declare const AssistantMessageSchema: z.ZodObject<{
431
+ type: z.ZodLiteral<"assistant">;
432
+ message: z.ZodObject<{
433
+ content: z.ZodArray<z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
434
+ type: z.ZodLiteral<"tool_use">;
435
+ name: z.ZodString;
436
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
437
+ }, "strip", z.ZodTypeAny, {
438
+ type: "tool_use";
439
+ name: string;
440
+ input?: Record<string, unknown> | undefined;
441
+ }, {
442
+ type: "tool_use";
443
+ name: string;
444
+ input?: Record<string, unknown> | undefined;
445
+ }>, z.ZodObject<{
446
+ type: z.ZodLiteral<"text">;
447
+ text: z.ZodString;
448
+ }, "strip", z.ZodTypeAny, {
449
+ text: string;
450
+ type: "text";
451
+ }, {
452
+ text: string;
453
+ type: "text";
454
+ }>]>, "many">;
455
+ }, "strip", z.ZodTypeAny, {
456
+ content: ({
457
+ type: "tool_use";
458
+ name: string;
459
+ input?: Record<string, unknown> | undefined;
460
+ } | {
461
+ text: string;
462
+ type: "text";
463
+ })[];
464
+ }, {
465
+ content: ({
466
+ type: "tool_use";
467
+ name: string;
468
+ input?: Record<string, unknown> | undefined;
469
+ } | {
470
+ text: string;
471
+ type: "text";
472
+ })[];
473
+ }>;
474
+ }, "strip", z.ZodTypeAny, {
475
+ type: "assistant";
476
+ message: {
477
+ content: ({
478
+ type: "tool_use";
479
+ name: string;
480
+ input?: Record<string, unknown> | undefined;
481
+ } | {
482
+ text: string;
483
+ type: "text";
484
+ })[];
485
+ };
486
+ }, {
487
+ type: "assistant";
488
+ message: {
489
+ content: ({
490
+ type: "tool_use";
491
+ name: string;
492
+ input?: Record<string, unknown> | undefined;
493
+ } | {
494
+ text: string;
495
+ type: "text";
496
+ })[];
497
+ };
498
+ }>;
499
+ declare const ResultMessageSchema: z.ZodObject<{
500
+ type: z.ZodLiteral<"result">;
501
+ session_id: z.ZodOptional<z.ZodString>;
502
+ total_cost_usd: z.ZodOptional<z.ZodNumber>;
503
+ duration_ms: z.ZodOptional<z.ZodNumber>;
504
+ }, "strip", z.ZodTypeAny, {
505
+ type: "result";
506
+ session_id?: string | undefined;
507
+ total_cost_usd?: number | undefined;
508
+ duration_ms?: number | undefined;
509
+ }, {
510
+ type: "result";
511
+ session_id?: string | undefined;
512
+ total_cost_usd?: number | undefined;
513
+ duration_ms?: number | undefined;
514
+ }>;
515
+ declare const ErrorMessageSchema: z.ZodObject<{
516
+ type: z.ZodLiteral<"error">;
517
+ error: z.ZodString;
518
+ }, "strip", z.ZodTypeAny, {
519
+ error: string;
520
+ type: "error";
521
+ }, {
522
+ error: string;
523
+ type: "error";
524
+ }>;
525
+ declare const SystemMessageSchema: z.ZodObject<{
526
+ type: z.ZodLiteral<"system">;
527
+ message: z.ZodString;
528
+ }, "strip", z.ZodTypeAny, {
529
+ type: "system";
530
+ message: string;
531
+ }, {
532
+ type: "system";
533
+ message: string;
534
+ }>;
535
+ declare const AgentOutputMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
536
+ type: z.ZodLiteral<"assistant">;
537
+ message: z.ZodObject<{
538
+ content: z.ZodArray<z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
539
+ type: z.ZodLiteral<"tool_use">;
540
+ name: z.ZodString;
541
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
542
+ }, "strip", z.ZodTypeAny, {
543
+ type: "tool_use";
544
+ name: string;
545
+ input?: Record<string, unknown> | undefined;
546
+ }, {
547
+ type: "tool_use";
548
+ name: string;
549
+ input?: Record<string, unknown> | undefined;
550
+ }>, z.ZodObject<{
551
+ type: z.ZodLiteral<"text">;
552
+ text: z.ZodString;
553
+ }, "strip", z.ZodTypeAny, {
554
+ text: string;
555
+ type: "text";
556
+ }, {
557
+ text: string;
558
+ type: "text";
559
+ }>]>, "many">;
560
+ }, "strip", z.ZodTypeAny, {
561
+ content: ({
562
+ type: "tool_use";
563
+ name: string;
564
+ input?: Record<string, unknown> | undefined;
565
+ } | {
566
+ text: string;
567
+ type: "text";
568
+ })[];
569
+ }, {
570
+ content: ({
571
+ type: "tool_use";
572
+ name: string;
573
+ input?: Record<string, unknown> | undefined;
574
+ } | {
575
+ text: string;
576
+ type: "text";
577
+ })[];
578
+ }>;
579
+ }, "strip", z.ZodTypeAny, {
580
+ type: "assistant";
581
+ message: {
582
+ content: ({
583
+ type: "tool_use";
584
+ name: string;
585
+ input?: Record<string, unknown> | undefined;
586
+ } | {
587
+ text: string;
588
+ type: "text";
589
+ })[];
590
+ };
591
+ }, {
592
+ type: "assistant";
593
+ message: {
594
+ content: ({
595
+ type: "tool_use";
596
+ name: string;
597
+ input?: Record<string, unknown> | undefined;
598
+ } | {
599
+ text: string;
600
+ type: "text";
601
+ })[];
602
+ };
603
+ }>, z.ZodObject<{
604
+ type: z.ZodLiteral<"result">;
605
+ session_id: z.ZodOptional<z.ZodString>;
606
+ total_cost_usd: z.ZodOptional<z.ZodNumber>;
607
+ duration_ms: z.ZodOptional<z.ZodNumber>;
608
+ }, "strip", z.ZodTypeAny, {
609
+ type: "result";
610
+ session_id?: string | undefined;
611
+ total_cost_usd?: number | undefined;
612
+ duration_ms?: number | undefined;
613
+ }, {
614
+ type: "result";
615
+ session_id?: string | undefined;
616
+ total_cost_usd?: number | undefined;
617
+ duration_ms?: number | undefined;
618
+ }>, z.ZodObject<{
619
+ type: z.ZodLiteral<"error">;
620
+ error: z.ZodString;
621
+ }, "strip", z.ZodTypeAny, {
622
+ error: string;
623
+ type: "error";
624
+ }, {
625
+ error: string;
626
+ type: "error";
627
+ }>, z.ZodObject<{
628
+ type: z.ZodLiteral<"system">;
629
+ message: z.ZodString;
630
+ }, "strip", z.ZodTypeAny, {
631
+ type: "system";
632
+ message: string;
633
+ }, {
634
+ type: "system";
635
+ message: string;
636
+ }>]>;
637
+ type ToolUseBlock = z.infer<typeof ToolUseBlockSchema>;
638
+ type TextBlock = z.infer<typeof TextBlockSchema>;
639
+ type AgentContentBlock = z.infer<typeof ContentBlockSchema>;
640
+ type AssistantMessage = z.infer<typeof AssistantMessageSchema>;
641
+ type ResultMessage = z.infer<typeof ResultMessageSchema>;
642
+ type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
643
+ type SystemMessage = z.infer<typeof SystemMessageSchema>;
644
+ type AgentOutputMessage = z.infer<typeof AgentOutputMessageSchema>;
645
+ declare function parseAgentOutputMessage(line: string): AgentOutputMessage | null;
646
+ declare function isClientEvent(data: unknown): data is ClientEvent;
647
+ declare function isServerEvent(data: unknown): data is ServerEvent;
648
+ declare function parseServerEvent(json: string): ServerEvent | null;
649
+ declare function parseClientEvent(json: string): ClientEvent | null;
650
+ type ClientMessage = ClientEvent;
651
+
652
+ /**
653
+ * Shared types for agent-session
654
+ */
655
+ interface SocketAttachment {
656
+ clientId: string;
657
+ userId?: string;
658
+ connectedAt: number;
659
+ }
660
+ interface SessionState {
661
+ sessionId: string;
662
+ sandboxId?: string;
663
+ metadata?: Record<string, unknown>;
664
+ }
665
+ /**
666
+ * Configuration for connecting to agent-session
667
+ */
668
+ interface AgentSessionConfig {
669
+ /** WebSocket URL of the deployed worker */
670
+ url: string;
671
+ /** Session ID for this connection */
672
+ sessionId: string;
673
+ /** Optional user ID for tracking */
674
+ userId?: string;
675
+ }
676
+
677
+ /**
678
+ * Session Refresh Configuration
679
+ *
680
+ * Defines how the client should behave when the sessionId changes.
681
+ * This is critical for document isolation in multi-document applications.
682
+ */
683
+ /**
684
+ * Refresh strategies for session changes
685
+ *
686
+ * - 'reset': Clear all client state and connect fresh (recommended for document isolation)
687
+ * - 'preserve': Attempt to reconnect to existing sandbox (for tab persistence scenarios)
688
+ */
689
+ type SessionRefreshStrategy = 'reset' | 'preserve';
690
+ interface SessionRefreshConfig {
691
+ /**
692
+ * What to do when sessionId changes:
693
+ *
694
+ * 'reset' (default, recommended):
695
+ * - Clear sandboxId, sandboxUrl, messages, agentSessionId
696
+ * - Disconnect from old socket
697
+ * - Connect to new session with clean slate
698
+ * - Use this when sessionId represents a document UUID
699
+ *
700
+ * 'preserve':
701
+ * - Keep existing state during reconnection
702
+ * - Useful for browser tab persistence where same user returns
703
+ * - NOT recommended when switching between documents
704
+ */
705
+ onSessionChange: SessionRefreshStrategy;
706
+ /**
707
+ * Whether to clear chat messages when session changes (only applies to 'reset' strategy)
708
+ * Default: true
709
+ */
710
+ clearMessagesOnReset?: boolean;
711
+ /**
712
+ * Whether to clear agent session ID when session changes (only applies to 'reset' strategy)
713
+ * Default: true
714
+ */
715
+ clearAgentSessionOnReset?: boolean;
716
+ }
717
+ /**
718
+ * Default configuration - full reset on session change
719
+ * This is the safest option for document isolation
720
+ */
721
+ declare const DEFAULT_SESSION_REFRESH_CONFIG: SessionRefreshConfig;
722
+ /**
723
+ * Preserve configuration - for tab persistence scenarios
724
+ * Use with caution - only when you know the user is returning to the same document
725
+ */
726
+ declare const PRESERVE_SESSION_CONFIG: SessionRefreshConfig;
727
+ /**
728
+ * Helper to determine if state should be reset based on config
729
+ */
730
+ declare function shouldResetOnSessionChange(config: SessionRefreshConfig, oldSessionId: string | null, newSessionId: string | null): boolean;
731
+
732
+ export { type AgentActionServerEvent, type AgentContentBlock, type AgentDoneServerEvent, type AgentErrorServerEvent, type AgentGenericServerEvent, type AgentMessageClientEvent, type AgentMessageServerEvent, type AgentOutputMessage, AgentOutputMessageSchema, type AgentResetEvent, type AgentSessionConfig, type AgentStartedServerEvent, type AgentStepCompleteServerEvent, type AgentStopEvent, type AssistantMessage, AssistantMessageSchema, type ClientEvent, ClientEventType, type ClientMessage, type ConnectedServerEvent, type ContentBlock, ContentBlockSchema, DEFAULT_SESSION_REFRESH_CONFIG, EPHEMERAL_EVENT_TYPES, type ErrorMessage, ErrorMessageSchema, type ErrorServerEvent, type EventsBatchServerEvent, type ExecCompleteServerEvent, type ExecEvent, type FileUploadedServerEvent, type FilesSyncServerEvent, type InitEvent, type JoinSessionEvent, type LifecycleServerEvent, type MessageAckServerEvent, type MessageAuthor, type MessageErrorServerEvent, PRESERVE_SESSION_CONFIG, type PersistableServerEvent, type PingEvent, type PongServerEvent, type ReadyServerEvent, type ResultMessage, ResultMessageSchema, type SandboxBootstrapOptions, type SandboxFile, SandboxLifecycle, SandboxStatus, type SandboxStatusServerEvent, type ServerEvent, type ServerEventMeta, ServerEventType, type SessionRefreshConfig, type SessionRefreshStrategy, type SessionState, type SocketAttachment, type StartSandboxEvent, type StopSandboxEvent, type SystemMessage, SystemMessageSchema, type SystemServerEvent, type TermDataServerEvent, type TextBlock, TextBlockSchema, type TextContentBlock, type TocEventServerEvent, type ToolResultContentBlock, type ToolUseBlock, ToolUseBlockSchema, type ToolUseContentBlock, isClientEvent, isPersistableEvent, isServerEvent, parseAgentOutputMessage, parseClientEvent, parseServerEvent, parseSystemMessageToLifecycle, shouldResetOnSessionChange };