@tangle-network/sandbox 0.68.7 → 0.69.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 (68) hide show
  1. package/README.md +5 -4
  2. package/dist/abort-signal-BKVZNJul.js +46 -0
  3. package/dist/agent/index.d.ts +4 -4
  4. package/dist/agent/index.js +4 -4
  5. package/dist/agent/preview.d.ts +1 -1
  6. package/dist/agent/preview.js +2 -2
  7. package/dist/{agent-run-outcome-Cp8hzV98.d.ts → agent-run-outcome-z5-7NA1x.d.ts} +1 -1
  8. package/dist/{api-request-D8Mni27A.js → api-request-D1UVNo16.js} +1 -1
  9. package/dist/auth/index.d.ts +2 -2
  10. package/dist/auth/index.js +1 -1
  11. package/dist/{browser-interactive-control-controller-CH7CLpmc.d.ts → browser-interactive-control-controller-CAmOZ9Sw.d.ts} +1 -1
  12. package/dist/{browser-interactive-control-controller-k1KkqDGF.js → browser-interactive-control-controller-CLHNi8rG.js} +2 -46
  13. package/dist/{chunked-upload-file-CbbWlCFt.js → chunked-upload-file-CLwAeLrM.js} +1 -1
  14. package/dist/{client-aBXGR6bc.d.ts → client-BG1kKuT7.d.ts} +5 -5
  15. package/dist/{client-D5GLp93x.js → client-DP5TOkG6.js} +9 -8
  16. package/dist/collaboration/index.d.ts +1 -1
  17. package/dist/collaboration/index.js +1 -1
  18. package/dist/{core-VOzQz1mc.js → core-CO7om2qW.js} +2 -2
  19. package/dist/core.d.ts +6 -6
  20. package/dist/core.js +4 -4
  21. package/dist/{direct-http2--35cHOv5.js → direct-http2-Pyj3Rvr1.js} +1 -1
  22. package/dist/{index-EebEqYqj.d.ts → index-DQpx4M1t.d.ts} +8 -8
  23. package/dist/index.d.ts +11 -11
  24. package/dist/index.js +9 -8
  25. package/dist/intelligence/index.js +1 -1
  26. package/dist/interactive-control.d.ts +1 -1
  27. package/dist/interactive-control.js +1 -1
  28. package/dist/{interactive-controller-ThIeP_oZ.js → interactive-controller-DIlzqR9a.js} +15 -234
  29. package/dist/{interactive-controller-Mh7Ud5DQ.d.ts → interactive-controller-qsiVS3gd.d.ts} +3 -3
  30. package/dist/lib/prepared-evidence.js +1 -1
  31. package/dist/lib/prepared-process.js +1 -1
  32. package/dist/{lines-BTIFNxRO.d.ts → lines-B9f2EKS6.d.ts} +1 -1
  33. package/dist/lines.d.ts +1 -1
  34. package/dist/lines.js +1 -1
  35. package/dist/{local-cli-auth-Dxti_D10.js → local-cli-auth-B5lzT8mt.js} +1 -1
  36. package/dist/{mcp-local-ClJ5TD-m.js → mcp-local-Gz1Uygqk.js} +1 -1
  37. package/dist/{preview-D6tTCcmv.d.ts → preview-II4uNVbG.d.ts} +3 -3
  38. package/dist/{public-templates-sZe-0Qvi.d.ts → public-templates-CkHcnhWA.d.ts} +2 -2
  39. package/dist/public-templates.d.ts +1 -1
  40. package/dist/{raw-evidence-archive-iDPF8eF_.js → raw-evidence-archive-D60Yg1-5.js} +1 -1
  41. package/dist/runtime.d.ts +5 -5
  42. package/dist/runtime.js +4 -4
  43. package/dist/{sandbox-Ksajmtq4.js → sandbox-CVieDtU6.js} +31 -39
  44. package/dist/{secp256k1-CoRKQn1k.js → secp256k1-DxHlUI6v.js} +1 -1
  45. package/dist/select-seat-command.d.ts +1 -1
  46. package/dist/session-gateway/index.d.ts +132 -508
  47. package/dist/session-gateway/index.js +694 -946
  48. package/dist/sidecar-proxy-error-B2Hxt41g.js +24 -0
  49. package/dist/sse-parser-CUfurwcm.js +227 -0
  50. package/dist/tangle/index.d.ts +1 -1
  51. package/dist/tangle/index.js +1 -1
  52. package/dist/{tangle-Cmr8JcO3.js → tangle-B4k-BjIh.js} +3 -3
  53. package/dist/{terminal-stream-types-yAt76vk7.d.ts → terminal-stream-types-Bgy8iSFg.d.ts} +8 -5
  54. package/dist/{types-DUNlmyED.d.ts → types-D6n5ohlx.d.ts} +2 -2
  55. package/package.json +7 -7
  56. /package/dist/{chunked-upload-CbtLVV6-.js → chunked-upload-l6b9AWFA.js} +0 -0
  57. /package/dist/{cli-auth-bundle-Can3oLKY.d.ts → cli-auth-bundle-CeNOYFje.d.ts} +0 -0
  58. /package/dist/{cli-auth-bundle-DlQs_26j.js → cli-auth-bundle-CrO4F3Ru.js} +0 -0
  59. /package/dist/{collaboration-Ox7K-TN6.js → collaboration-BwLNv6sy.js} +0 -0
  60. /package/dist/{index-B8xo7y26.d.ts → index-C0RkLba5.d.ts} +0 -0
  61. /package/dist/{index-mz8_2rr2.d.ts → index-DaIF4c9p.d.ts} +0 -0
  62. /package/dist/{keep-alive-fetch-C92u8Kce.js → keep-alive-fetch-Bi-zvHpN.js} +0 -0
  63. /package/dist/{lines-DgRXUg5y.js → lines-D_HDAcVt.js} +0 -0
  64. /package/dist/{prepared-evidence-Di89Tatw.js → prepared-evidence-DUmJSegi.js} +0 -0
  65. /package/dist/{prepared-process-DKgEUodb.js → prepared-process-Dlk_9JVJ.js} +0 -0
  66. /package/dist/{preview-operations-BL7YCkes.js → preview-operations-eTUlPen5.js} +0 -0
  67. /package/dist/{response-rewrap-Bsj87BIq.js → response-rewrap-BKkJ5hnn.js} +0 -0
  68. /package/dist/{utils-C86i6t3C.js → utils-DB8DnUCU.js} +0 -0
@@ -1,208 +1,4 @@
1
1
  //#region ../../../packages/runtime-contracts/dist/session-gateway.d.ts
2
- /**
3
- * Shared session-gateway protocol and connection metrics
4
- *
5
- * Browser-safe wire contracts. SDK-specific extensions and connection defaults
6
- * remain with their clients; this module imports no runtime or Node services.
7
- */
8
- /**
9
- * Message types sent by the client.
10
- */
11
- type ClientMessage = {
12
- type: "subscribe";
13
- id?: string;
14
- channels: string[];
15
- replayOptions?: ReplayOptions;
16
- } | {
17
- type: "unsubscribe";
18
- id?: string;
19
- channels: string[];
20
- } | {
21
- type: "ping";
22
- id?: string;
23
- } | {
24
- type: "replay";
25
- id?: string;
26
- /**
27
- * Timestamp to replay from.
28
- * @deprecated Timestamps are not a stable cursor. Use `sinceSeq`.
29
- */
30
- since?: number; /** Replay events with a per-session seq above this value. */
31
- sinceSeq?: number;
32
- } | {
33
- type: "terminal.input";
34
- id?: string;
35
- data: {
36
- terminalId: string;
37
- input: string;
38
- };
39
- };
40
- /**
41
- * Replay options for reconnection event recovery.
42
- */
43
- interface ReplayOptions {
44
- /** Last received event ID for replay continuation */
45
- lastEventId?: string;
46
- /** Execution ID to replay events for */
47
- executionId?: string;
48
- /** Session ID context for replay */
49
- sessionId?: string;
50
- }
51
- /**
52
- * Base fields present on all server messages.
53
- */
54
- interface ServerMessageBase {
55
- id?: string;
56
- timestamp?: number;
57
- /** Monotonic sequence number for gap detection (per session) */
58
- seq?: number;
59
- }
60
- type RuntimeUnavailableReason = "container_mismatch" | "incarnation_transitioning" | "project_provisioning" | "project_degraded" | "project_suspended" | "project_failed" | "project_deprovisioning" | "project_restarting" | "sidecar_starting" | "sidecar_stopped" | "sidecar_suspended";
61
- interface RuntimeUnavailableData {
62
- sandboxId: string;
63
- sessionId: string;
64
- reason: RuntimeUnavailableReason;
65
- }
66
- /**
67
- * Message types sent by the server.
68
- */
69
- type GatewayServerMessage = (ServerMessageBase & {
70
- type: "connection.established";
71
- data: {
72
- sessionId: string;
73
- };
74
- }) | (ServerMessageBase & {
75
- type: "subscribed";
76
- data: {
77
- channels: string[];
78
- };
79
- }) | (ServerMessageBase & {
80
- type: "unsubscribed";
81
- data: {
82
- channels: string[];
83
- };
84
- }) | (ServerMessageBase & {
85
- type: "pong";
86
- timestamp: number;
87
- }) | (ServerMessageBase & {
88
- type: "runtime.connected";
89
- data: {
90
- sandboxId: string;
91
- baseUrl: string;
92
- };
93
- }) | (ServerMessageBase & {
94
- type: "runtime.disconnected";
95
- data: {
96
- sandboxId: string;
97
- error?: string;
98
- reason?: string;
99
- };
100
- }) | (ServerMessageBase & {
101
- type: "runtime.unavailable";
102
- data: RuntimeUnavailableData;
103
- }) | (ServerMessageBase & {
104
- type: "runtime.reconnecting";
105
- data: {
106
- sandboxId: string;
107
- attempt: number;
108
- delayMs: number;
109
- };
110
- }) | (ServerMessageBase & {
111
- type: "runtime.removed";
112
- data: {
113
- sandboxId: string;
114
- reason: string;
115
- };
116
- }) | (ServerMessageBase & {
117
- type: "runtime.not_found";
118
- data: {
119
- sessionId: string;
120
- containerId?: string;
121
- reason: string;
122
- };
123
- }) | (ServerMessageBase & {
124
- type: "runtime.ready";
125
- data: {
126
- sandboxId: string;
127
- sessionId: string;
128
- port: number;
129
- host: string;
130
- status: string;
131
- image?: string;
132
- backend?: {
133
- type: string;
134
- provider?: string;
135
- model?: string;
136
- };
137
- };
138
- }) | (ServerMessageBase & {
139
- type: "port.opened";
140
- data: PortEventData;
141
- }) | (ServerMessageBase & {
142
- type: "port.closed";
143
- data: PortEventData;
144
- }) | (ServerMessageBase & {
145
- type: "agent.event";
146
- channel: string;
147
- data: unknown;
148
- }) | (ServerMessageBase & {
149
- type: "replay.start";
150
- total: number;
151
- }) | (ServerMessageBase & {
152
- type: "replay.progress";
153
- received: number;
154
- }) | (ServerMessageBase & {
155
- type: "replay.complete";
156
- total: number;
157
- }) | (ServerMessageBase & {
158
- type: "replay.truncated";
159
- data: {
160
- /** Why the replay is incomplete (e.g. "cursor_evicted") */reason: string; /** Seq cursor the client requested */
161
- requestedSeq?: number; /** Oldest seq still retained by the gateway buffer */
162
- firstAvailableSeq?: number;
163
- };
164
- }) | (ServerMessageBase & {
165
- type: "stream.gap";
166
- data: {
167
- sandboxId?: string; /** Events the sidecar dropped before the gateway saw them */
168
- droppedCount?: number;
169
- };
170
- }) | (ServerMessageBase & {
171
- type: "stream.dead";
172
- data: {
173
- sandboxId?: string; /** Why the upstream subscription stopped */
174
- error?: string;
175
- };
176
- }) | (ServerMessageBase & {
177
- type: "error";
178
- message: string;
179
- code?: string;
180
- }) | (ServerMessageBase & {
181
- type: "token.expiring";
182
- data: {
183
- secondsRemaining: number;
184
- message: string;
185
- };
186
- }) | (ServerMessageBase & {
187
- type: "token.expired";
188
- data: {
189
- message: string;
190
- };
191
- }) | (ServerMessageBase & {
192
- type: "backpressure.warning";
193
- data: {
194
- /** Number of events dropped since last notification */droppedCount: number; /** Timestamp when the notification window started */
195
- since: number; /** Total events dropped in this session */
196
- totalDropped: number; /** Hint that client should request a replay */
197
- suggestReplay: boolean;
198
- };
199
- });
200
- interface PortEventData {
201
- type: "opened" | "closed";
202
- port: number;
203
- protocol: string;
204
- processName?: string;
205
- }
206
2
  /**
207
3
  * Connection state for the WebSocket client.
208
4
  */
@@ -216,370 +12,198 @@ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecti
216
12
  */
217
13
  type ConnectionQuality = "excellent" | "good" | "degraded" | "poor" | "disconnected";
218
14
  /**
219
- * Metrics tracked for connection quality assessment.
15
+ * Token refresh result from the product backend.
220
16
  */
221
- interface ConnectionMetrics {
222
- /** Last measured ping latency in milliseconds */
223
- lastPingLatencyMs: number | null;
224
- /** Average ping latency over the last N samples */
225
- avgPingLatencyMs: number | null;
226
- /** Number of consecutive missed pongs */
227
- missedPongCount: number;
228
- /** Number of reconnections in the current session */
17
+ interface TokenRefreshResult {
18
+ /** New read token */
19
+ token: string;
20
+ /** Token expiry timestamp (Unix seconds) */
21
+ expiresAt: number;
22
+ }
23
+ //#endregion
24
+ //#region src/session-gateway/types.d.ts
25
+ interface SessionStreamConnectionMetrics {
26
+ /** Milliseconds from dial to the first frame, on the latest attach. */
27
+ lastAttachLatencyMs: number | null;
28
+ /** Mean attach latency over the last `latencyHistorySize` attaches. */
29
+ avgAttachLatencyMs: number | null;
30
+ /**
31
+ * Consecutive attaches that ended because the stream sent nothing for
32
+ * `idleTimeoutMs`. The sidecar writes a heartbeat every 30 s, so a silent
33
+ * stream is a dead one.
34
+ */
35
+ silentDropCount: number;
36
+ /** Reconnections since the client was created. */
229
37
  reconnectCount: number;
230
- /** Timestamp of last successful pong */
231
- lastPongAt: number | null;
232
- /** Timestamp of last reconnection */
38
+ /** When the stream last delivered a frame, heartbeats included. */
39
+ lastFrameAt: number | null;
233
40
  lastReconnectAt: number | null;
234
- /** Current calculated quality level */
235
41
  quality: ConnectionQuality;
236
42
  }
237
- /**
238
- * Replay state for UI display during event replay.
239
- */
240
- interface ReplayState {
241
- /** Whether currently replaying events */
43
+ /** Replay of the session's running turn from the sidecar event store. */
44
+ interface SessionStreamReplayState {
242
45
  isReplaying: boolean;
243
- /** Progress tracking */
244
- progress: {
245
- total: number;
246
- received: number;
46
+ /** Frames the current or last replay delivered. */
47
+ received: number;
48
+ }
49
+ /** Why the edge could not reach the session's runtime this attempt. */
50
+ type SessionStreamRuntimeUnavailableReason = /** The host is restarting the sidecar. */"sidecar_restarting" /** The edge or host could not reach the sidecar. */ | "sidecar_unreachable";
51
+ interface SessionStreamRuntimeUnavailableData {
52
+ sandboxId: string;
53
+ sessionId: string;
54
+ reason: SessionStreamRuntimeUnavailableReason;
55
+ }
56
+ /** Announced on every attach: the runtime answered and is streaming. */
57
+ interface SessionStreamRuntimeReadyData {
58
+ sandboxId: string;
59
+ sessionId: string;
60
+ /** The runtime URL's host and port. */
61
+ host: string;
62
+ port: number;
63
+ status: "running";
64
+ /** The backend the runtime session ran on, when it has run. */
65
+ backend?: {
66
+ type: string;
67
+ provider?: string;
68
+ model?: string;
247
69
  };
248
70
  }
249
- /**
250
- * Token refresh result from the product backend.
251
- */
252
- interface TokenRefreshResult {
253
- /** New read token */
254
- token: string;
255
- /** Token expiry timestamp (Unix seconds) */
256
- expiresAt: number;
71
+ /** One frame as the client delivers it to `onMessage`. */
72
+ interface SessionStreamMessage {
73
+ type: "agent.event";
74
+ /** `session:<sessionId>` */
75
+ channel: string;
76
+ /** The sidecar event-store id, on frames replayed from the store. */
77
+ id?: string;
78
+ /** The sidecar frame, its `type` set and its session id translated. */
79
+ data: unknown;
80
+ timestamp: number;
81
+ /** Delivery order within this client. */
82
+ seq: number;
257
83
  }
258
- /**
259
- * Event handlers for session gateway events.
260
- */
261
- interface GatewayEventHandlers {
84
+ interface SessionStreamEventHandlers {
85
+ /** The stream is open; fires once per attach. */
262
86
  onConnect?: (sessionId: string) => void;
87
+ /** An open stream ended or an attach failed. Not called on `disconnect()`. */
263
88
  onDisconnect?: (code: number, reason: string) => void;
89
+ /** A later attach succeeded after a drop. */
264
90
  onReconnect?: () => void;
265
91
  onRuntimeConnected?: (sandboxId: string, baseUrl: string) => void;
266
92
  onRuntimeDisconnected?: (sandboxId: string, error?: string) => void;
267
- onRuntimeUnavailable?: (data: RuntimeUnavailableData) => void;
93
+ onRuntimeUnavailable?: (data: SessionStreamRuntimeUnavailableData) => void;
268
94
  /**
269
- * Called when no running container is found for the session.
270
- * This typically happens when a user returns after their container has expired.
271
- * The client should trigger reprovisioning or prompt the user.
95
+ * The edge holds no route to this sandbox: it is stopped, suspended or
96
+ * deleted. The client stops; reprovision or resume, then connect again.
272
97
  */
273
- onRuntimeNotFound?: (sessionId: string, containerId: string | undefined, reason: string) => void;
274
- /**
275
- * Called when a runtime is fully ready with rich metadata.
276
- */
277
- onRuntimeReady?: (data: {
278
- sandboxId: string;
279
- sessionId: string;
280
- port: number;
281
- host: string;
282
- status: string;
283
- image?: string;
284
- backend?: {
285
- type: string;
286
- provider?: string;
287
- model?: string;
288
- };
289
- }) => void;
290
- onPortOpened?: (port: number, protocol: string, processName?: string) => void;
291
- onPortClosed?: (port: number) => void;
292
- onAgentEvent?: (channel: string, raw: unknown, seq?: number) => void;
98
+ onRuntimeNotFound?: (sessionId: string, sandboxId: string | undefined, reason: string) => void;
99
+ onRuntimeReady?: (data: SessionStreamRuntimeReadyData) => void;
100
+ /** Every sidecar frame of the session, on channel `session:<sessionId>`. */
101
+ onAgentEvent?: (channel: string, data: unknown, seq?: number) => void;
102
+ /** Every delivered frame, whatever the channel subscriptions. */
103
+ onMessage?: (message: SessionStreamMessage) => void;
293
104
  onError?: (message: string, code?: string) => void;
294
105
  onStateChange?: (state: ConnectionState) => void;
295
- onMetricsChange?: (metrics: ConnectionMetrics) => void;
296
- onReplayStart?: (total: number) => void;
297
- onReplayProgress?: (received: number, total: number) => void;
298
- onReplayComplete?: (total: number) => void;
299
- /**
300
- * Called when the gateway buffer evicted events the client requested.
301
- * The replay that follows starts at firstAvailableSeq.
302
- */
303
- onReplayTruncated?: (data: {
304
- reason: string;
305
- requestedSeq?: number;
306
- firstAvailableSeq?: number;
307
- }) => void;
308
- /**
309
- * Called when the sidecar dropped events upstream of the gateway.
310
- * The live stream has a gap; request a replay to recover.
311
- */
106
+ onMetricsChange?: (metrics: SessionStreamConnectionMetrics) => void;
107
+ /** The sidecar began replaying the running turn from its event store. */
108
+ onReplayStart?: () => void;
109
+ onReplayProgress?: (received: number) => void;
110
+ onReplayComplete?: (received: number) => void;
111
+ /** The sidecar dropped frames for this stream (`buffer.overflow`). */
312
112
  onStreamGap?: (data: {
313
113
  sandboxId?: string;
314
114
  droppedCount?: number;
315
115
  }) => void;
316
- /**
317
- * Called when the gateway gave up reconnecting to the sidecar.
318
- * No further events arrive on this stream.
319
- */
320
- onStreamDead?: (data: {
321
- sandboxId?: string;
322
- error?: string;
323
- }) => void;
324
- /**
325
- * Called when the token is about to expire.
326
- * The client should call refreshToken() or disconnect.
327
- * @param secondsRemaining - Seconds until token expires
328
- */
116
+ /** About a minute before the token's `exp`; `onTokenRefresh` runs next. */
329
117
  onTokenExpiring?: (secondsRemaining: number) => void;
330
- /**
331
- * Called when the token has expired.
332
- * The client will be disconnected shortly after this event.
333
- */
118
+ /** The token expired with no replacement; the next attach will fail. */
334
119
  onTokenExpired?: () => void;
335
- /**
336
- * Called when events have been dropped due to WebSocket backpressure.
337
- * The client should consider requesting a replay to catch up on missed events.
338
- * @param droppedCount - Number of events dropped since last notification
339
- * @param since - Timestamp when the notification window started
340
- * @param totalDropped - Total events dropped in this session
341
- */
342
- onBackpressureWarning?: (droppedCount: number, since: number, totalDropped: number) => void;
343
120
  }
344
- /**
345
- * Storage interface for replay state persistence.
346
- * Allows custom storage implementations (localStorage, sessionStorage, memory, etc.)
347
- */
348
- interface ReplayStateStorage {
349
- getItem(key: string): string | null;
350
- setItem(key: string, value: string): void;
351
- removeItem(key: string): void;
352
- }
353
- /**
354
- * Transport mode for event delivery.
355
- *
356
- * - "websocket": WebSocket mode - all events via WebSocket (default)
357
- */
358
- type TransportMode = "websocket";
359
- /**
360
- * Configuration for SessionGatewayClient.
361
- */
362
- interface GatewayClientConfig {
363
- /** WebSocket URL for the session gateway */
121
+ interface SessionStreamClientConfig {
122
+ /** The sandbox runtime URL: `ScopedToken.runtimeUrl`. */
364
123
  url: string;
365
124
  /**
366
- * JWT read token for authentication (required).
367
- * Obtain from product backend's session creation endpoint.
125
+ * A token the runtime accepts for this session's events: the result of
126
+ * `box.mintScopedToken({ scope: "session-runtime", sessionId: runtimeSessionId, access: "read-only" })`.
368
127
  */
369
128
  token: string;
370
- /**
371
- * Callback to refresh the token when it's about to expire.
372
- * Called when server sends token.expiring event.
373
- * Return new token and expiry, or throw to disconnect.
374
- */
129
+ /** Called about a minute before the token expires, and on a 401. */
375
130
  onTokenRefresh?: () => Promise<TokenRefreshResult>;
376
- /** Session ID to connect to */
377
- sessionId: string;
378
131
  /**
379
- * Transport mode for event delivery (default: "websocket").
132
+ * The session id the caller uses. Frames name it in place of
133
+ * `runtimeSessionId`, and arrive on channel `session:<sessionId>`.
380
134
  */
381
- transport?: TransportMode;
382
- /** Channels to subscribe to (default: ["*"]) */
135
+ sessionId: string;
136
+ /** The runtime session whose events stream (default: `sessionId`). */
137
+ runtimeSessionId?: string;
138
+ /** Reported to lifecycle handlers (default: the runtime URL's first host label). */
139
+ sandboxId?: string;
140
+ /** Channel patterns delivered to `onAgentEvent` (default: all). */
383
141
  channels?: string[];
384
- /** Auto-reconnect on disconnect (default: true) */
142
+ /** Reattach after a drop (default: true). */
385
143
  autoReconnect?: boolean;
386
- /** Maximum reconnection attempts (default: 10) */
144
+ /** Consecutive failed attaches before the client stops (default: 10). */
387
145
  maxReconnectAttempts?: number;
388
- /** Initial reconnection delay in ms (default: 1000) */
146
+ /** First reattach delay; each failure doubles it (default: 1000 ms). */
389
147
  initialReconnectDelayMs?: number;
390
- /** Maximum reconnection delay in ms (default: 30000) */
148
+ /** Longest reattach delay (default: 30000 ms). */
391
149
  maxReconnectDelayMs?: number;
392
- /** Ping interval in ms (default: 30000) */
393
- pingIntervalMs?: number;
394
- /** Pong timeout in ms (default: 10000) */
395
- pongTimeoutMs?: number;
396
- /** Maximum missed pongs before forcing reconnection (default: 2) */
397
- maxMissedPongs?: number;
398
- /** Enable event deduplication (default: true) */
150
+ /** Reattach when the stream sends nothing this long (default: 75000 ms). */
151
+ idleTimeoutMs?: number;
152
+ /** Deliver each event-store frame once across replays (default: true). */
399
153
  enableDeduplication?: boolean;
400
- /** Maximum number of event IDs to track for deduplication (default: 1000) */
154
+ /** Event-store ids remembered for deduplication (default: 1000). */
401
155
  maxDeduplicationSize?: number;
402
- /** Enable replay state persistence (default: false) */
403
- enableReplayPersistence?: boolean;
404
- /** Storage for replay state persistence (default: localStorage if available) */
405
- replayStorage?: ReplayStateStorage;
406
- /** Storage key prefix for replay state (default: "session_gateway_") */
407
- replayStorageKeyPrefix?: string;
408
- /** Number of latency samples to track for averaging (default: 10) */
156
+ /** Attach latencies averaged into the metrics (default: 10). */
409
157
  latencyHistorySize?: number;
410
- /** Event handlers */
411
- handlers?: GatewayEventHandlers;
158
+ /** Longest wait for the stream's first frame (default: 10000 ms). */
159
+ connectionEstablishmentTimeoutMs?: number;
160
+ /** Fetch implementation for Workers, tests or custom runtimes. */
161
+ fetch?: typeof globalThis.fetch;
162
+ handlers?: SessionStreamEventHandlers;
412
163
  }
413
- /**
414
- * Statistics for the session gateway connection.
415
- */
416
- interface SessionGatewayStats {
164
+ interface SessionStreamStats {
417
165
  state: ConnectionState;
418
166
  connectedAt: number | null;
419
- lastPingAt: number | null;
420
- lastPongAt: number | null;
421
167
  reconnectAttempts: number;
422
- messagesReceived: number;
423
- messagesSent: number;
424
- eventsReceived: number;
168
+ framesReceived: number;
169
+ eventsDelivered: number;
425
170
  duplicatesSkipped: number;
426
- metrics: ConnectionMetrics;
427
- replay: ReplayState;
428
- }
429
- /**
430
- * Calculate connection quality from metrics.
431
- */
432
- declare function calculateConnectionQuality(metrics: ConnectionMetrics, isConnected: boolean): ConnectionQuality;
433
- //#endregion
434
- //#region src/session-gateway/core-types.d.ts
435
- interface SubscriptionDenial {
436
- channel: string;
437
- reason: string;
438
- }
439
- interface SubscriptionAcknowledgement {
440
- channels: string[];
441
- denied?: SubscriptionDenial[];
442
- }
443
- type ServerMessage = Exclude<GatewayServerMessage, {
444
- type: "connection.established" | "subscribed";
445
- }> | (ServerMessageBase & {
446
- type: "connection.established";
447
- data: {
448
- sessionId: string;
449
- hydratedCount?: number;
450
- };
451
- }) | (ServerMessageBase & {
452
- type: "subscribed";
453
- data: SubscriptionAcknowledgement;
454
- }) | (ServerMessageBase & {
455
- type: "terminal.input.error";
456
- data: {
457
- terminalId: string;
458
- code: string;
459
- message: string;
460
- };
461
- }) | (ServerMessageBase & {
462
- type: `project.${string}`;
463
- channel?: string;
464
- data: unknown;
465
- }) | (ServerMessageBase & {
466
- type: "heartbeat";
467
- data?: unknown;
468
- });
469
- /** Untrusted inbound frame; the client validates its type before dispatch. */
470
- interface RawWireMessage {
471
- type?: string;
472
- channel?: string;
473
- data?: unknown;
474
- id?: string;
475
- message?: string;
476
- code?: string;
477
- timestamp?: number;
478
- seq?: number;
479
- [key: string]: unknown;
480
- }
481
- /** Every inbound frame after its message type has been validated. */
482
- interface NormalizedServerMessage extends RawWireMessage {
483
- type: string;
484
- }
485
- interface SessionGatewayEventHandlers extends GatewayEventHandlers {
486
- /** Called after internal processing for every non-duplicate normalized frame. */
487
- onMessage?: (message: NormalizedServerMessage) => void;
488
- }
489
- interface SessionGatewayClientConfig extends Omit<GatewayClientConfig, "handlers"> {
490
- /** Browser session ID embedded in the session-scoped read token. */
491
- sessionId: string;
492
- /** Additional subscriptions; server-authorized channels are used by default. */
493
- channels?: string[];
494
- /** Maximum wait for `connection.established` (default: 10000 ms). */
495
- connectionEstablishmentTimeoutMs?: number;
496
- handlers?: SessionGatewayEventHandlers;
171
+ metrics: SessionStreamConnectionMetrics;
172
+ replay: SessionStreamReplayState;
497
173
  }
498
- declare const INITIAL_METRICS: ConnectionMetrics;
174
+ /** A fresh metrics object; never shared between clients. */
175
+ declare const INITIAL_METRICS: SessionStreamConnectionMetrics;
176
+ /** Adapt stream measurements to the shared connection-quality policy. */
177
+ declare function calculateSessionStreamConnectionQuality(metrics: SessionStreamConnectionMetrics, isConnected: boolean): ConnectionQuality;
499
178
  //#endregion
500
- //#region src/session-gateway/core.d.ts
501
- declare class SessionGatewayClientCore {
179
+ //#region src/session-gateway/client.d.ts
180
+ declare class SessionGatewayClient {
502
181
  #private;
503
- private ws;
504
- private readonly handlers;
505
- private state;
506
- private readonly counters;
507
- private readonly connectionWaiters;
508
- private readonly metrics;
509
- private readonly replayCursor;
510
- private readonly inbound;
511
- constructor(config: SessionGatewayClientConfig, initialMetrics?: ConnectionMetrics);
512
- /**
513
- * Connect to the session gateway.
514
- */
182
+ constructor(config: SessionStreamClientConfig);
183
+ /** Open the stream; reattaches after drops until `disconnect()`. */
515
184
  connect(): void;
516
- private connectWebSocket;
517
- /**
518
- * Disconnect from the session gateway.
519
- */
185
+ /** Close the stream and stop reattaching. */
520
186
  disconnect(): void;
521
- /**
522
- * Subscribe to additional channels.
523
- */
187
+ /** Deliver frames on these channel patterns (`*`, `session:*`, exact). */
524
188
  subscribe(channels: string[]): Promise<string[]>;
525
- /**
526
- * Unsubscribe from channels.
527
- */
528
189
  unsubscribe(channels: string[]): Promise<string[]>;
529
190
  /**
530
- * Send a ping and wait for pong.
531
- */
532
- ping(): Promise<number>;
533
- protected replayImmediately(message: ClientMessage): void;
534
- protected replayAfterConnection(message: ClientMessage): Promise<void>;
535
- /**
536
- * Send terminal input via WebSocket.
537
- */
538
- sendTerminalInput(terminalId: string, input: string): boolean;
539
- /**
540
- * Set the current session/execution context for event tracking.
541
- */
542
- setSessionContext(sessionId: string, executionId?: string): void;
543
- /**
544
- * Clear replay state (call when session ends).
191
+ * Reattach now and re-read the running turn from its first event. With
192
+ * deduplication on, only frames this client has not delivered arrive.
545
193
  */
194
+ replay(): Promise<void>;
195
+ /** Forget delivered event-store ids, so a replay delivers them again. */
546
196
  clearReplayState(): void;
547
- /**
548
- * Get current replay state for UI indicators.
549
- */
550
- getReplayState(): ReplayState;
551
- /**
552
- * Get connection statistics.
553
- */
554
- getStats(): SessionGatewayStats;
197
+ getReplayState(): SessionStreamReplayState;
198
+ getStats(): SessionStreamStats;
555
199
  getState(): ConnectionState;
556
200
  isConnected(): boolean;
557
201
  getConnectionQuality(): ConnectionQuality;
558
- getConnectionMetrics(): ConnectionMetrics;
202
+ getConnectionMetrics(): SessionStreamConnectionMetrics;
559
203
  resetMetrics(): void;
560
- /**
561
- * Update the auth token and reconnect with the new token.
562
- */
204
+ /** Use this token from the next attach on; the open stream stays. */
563
205
  updateToken(token: string): void;
564
- /**
565
- * Get the current auth token.
566
- */
567
206
  getToken(): string;
568
- private setState;
569
- private handleConnectionEstablished;
570
- private handleClose;
571
- private handleMessage;
572
- private send;
573
- private sendWithResponse;
574
- }
575
- //#endregion
576
- //#region src/session-gateway/client.d.ts
577
- /** Sandbox replay waits for the server's authenticated connection receipt. */
578
- declare class SessionGatewayClient extends SessionGatewayClientCore {
579
- constructor(config: SessionGatewayClientConfig);
580
- /** @deprecated Timestamps are not a stable cursor. Use replaySinceSeq(). */
581
- replay(since: number): Promise<void>;
582
- replaySinceSeq(sinceSeq: number): Promise<void>;
583
207
  }
584
208
  //#endregion
585
- export { type ClientMessage, type ConnectionMetrics, type ConnectionQuality, type ConnectionState, INITIAL_METRICS, type NormalizedServerMessage, type PortEventData, type ReplayOptions, type ReplayState, type ReplayStateStorage, type RuntimeUnavailableData, type RuntimeUnavailableReason, type ServerMessage, SessionGatewayClient, type SessionGatewayClientConfig, type SessionGatewayEventHandlers, type SessionGatewayStats, type SubscriptionAcknowledgement, type SubscriptionDenial, type TokenRefreshResult, type TransportMode, calculateConnectionQuality };
209
+ export { type SessionStreamConnectionMetrics as ConnectionMetrics, type ConnectionQuality, type ConnectionState, INITIAL_METRICS, type SessionStreamReplayState as ReplayState, type SessionStreamRuntimeReadyData as RuntimeReadyData, type SessionStreamRuntimeUnavailableData as RuntimeUnavailableData, type SessionStreamRuntimeUnavailableReason as RuntimeUnavailableReason, SessionGatewayClient, type SessionStreamClientConfig as SessionGatewayClientConfig, type SessionStreamEventHandlers as SessionGatewayEventHandlers, type SessionStreamStats as SessionGatewayStats, type SessionStreamMessage, type TokenRefreshResult, calculateSessionStreamConnectionQuality as calculateConnectionQuality };