@tangle-network/sandbox 0.60.78-develop.20261017134105.a6b32a2 → 0.60.78-develop.20261021201434.3bcd5ef

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 (66) hide show
  1. package/README.md +61 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-CTEpjCEZ.d.ts → agent-run-outcome-brwJbH5S.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +5 -5
  9. package/dist/{backend-types-D6bYbvMB.js → backend-types-CLvdSX8V.js} +41 -1
  10. package/dist/{browser-interactive-control-controller-rpTbyvAS.d.ts → browser-interactive-control-controller-CvObO_Kf.d.ts} +1 -1
  11. package/dist/{browser-interactive-control-controller-BJf0P_J4.js → browser-interactive-control-controller-DHx53yre.js} +16 -1
  12. package/dist/{chunked-upload-DtIvkKNo.js → chunked-upload-DN2twsUu.js} +2 -59
  13. package/dist/{chunked-upload-file-DnsHEjg0.js → chunked-upload-file-Dpv1YsoA.js} +2 -1
  14. package/dist/{cli-auth-bundle-cSJjPeFF.js → cli-auth-bundle-CFeHsq-5.js} +23 -11
  15. package/dist/{client-R1tw-4Px.js → client-CgtR203z.js} +3349 -3341
  16. package/dist/client-Dr8qasCR.d.ts +6076 -0
  17. package/dist/collaboration/index.d.ts +1 -1
  18. package/dist/collaboration/index.js +1 -1
  19. package/dist/{collaboration-DaJU5O0E.js → collaboration-g_HzXa6f.js} +5 -5
  20. package/dist/core.d.ts +7 -7
  21. package/dist/core.js +7 -6
  22. package/dist/direct-http2-Dar5erTH.js +99 -0
  23. package/dist/{errors-DSJBKmGZ.js → errors-BfbOP_rx.js} +171 -22
  24. package/dist/{index-DO7GVpk_.d.ts → index-C8VSFtWl.d.ts} +1 -1
  25. package/dist/{index-DZ27pdB8.d.ts → index-CVjTnRWP.d.ts} +1 -1
  26. package/dist/{sandbox-CoIGxzm_.d.ts → index-D5dVNm76.d.ts} +2117 -1519
  27. package/dist/index.d.ts +12 -4704
  28. package/dist/index.js +40 -15
  29. package/dist/intelligence/index.js +1 -1
  30. package/dist/interactive-control.d.ts +1 -1
  31. package/dist/interactive-control.js +1 -1
  32. package/dist/{interactive-controller-CJ24g8Va.js → interactive-controller-OAsASPd_.js} +662 -620
  33. package/dist/interactive-controller-nMhGqXxq.d.ts +41 -0
  34. package/dist/keep-alive-fetch-BBzJDWyt.js +247 -0
  35. package/dist/{lines-DodQslsf.d.ts → lines-C5CPSg8n.d.ts} +21 -17
  36. package/dist/lines-C5ER4aN_.js +298 -0
  37. package/dist/lines.d.ts +1 -1
  38. package/dist/lines.js +1 -295
  39. package/dist/{local-cli-auth-CBV7Vjk5.js → local-cli-auth-D-CQ0-ub.js} +1 -1
  40. package/dist/{mcp-local-DjryqUiY.js → mcp-local-BjLG7VHY.js} +1 -1
  41. package/dist/{preview-wpGGk0bu.d.ts → preview-COO7TSBk.d.ts} +3 -3
  42. package/dist/public-templates-BDrchm0J.d.ts +80 -0
  43. package/dist/public-templates.d.ts +2 -0
  44. package/dist/public-templates.js +173 -0
  45. package/dist/{raw-evidence-archive-Br5a3xZ_.js → raw-evidence-archive-CDYDqHNv.js} +161 -69
  46. package/dist/runtime.d.ts +49 -41
  47. package/dist/runtime.js +8 -8
  48. package/dist/{sandbox-C7Tk62qn.js → sandbox-BrZxAq11.js} +9048 -8939
  49. package/dist/{secp256k1-Dx2XABHz.js → secp256k1-CmLpsmWl.js} +1 -1
  50. package/dist/session-gateway/index.d.ts +23 -67
  51. package/dist/session-gateway/index.js +578 -451
  52. package/dist/tangle/index.d.ts +1 -1
  53. package/dist/tangle/index.js +1 -1
  54. package/dist/{tangle-Ba4Kz5zT.js → tangle-GiPBak5X.js} +176 -169
  55. package/dist/terminal-stream-types-ClZCArRg.d.ts +662 -0
  56. package/dist/{types-B_QF-iHm.d.ts → types-CtH0GRql.d.ts} +6161 -5812
  57. package/package.json +11 -6
  58. package/dist/client-Lhxo82x1.d.ts +0 -1261
  59. package/dist/errors-mPL-qvgF.d.ts +0 -347
  60. package/dist/index-DRto9Ijb.d.ts +0 -579
  61. package/dist/managed-process-B7WfqKmi.d.ts +0 -15
  62. package/dist/terminal-stream-jdYomM1m.d.ts +0 -389
  63. /package/dist/{cli-auth-bundle-ODe06Ts7.d.ts → cli-auth-bundle-Dyw3hCGx.d.ts} +0 -0
  64. /package/dist/{line-application-Cq6dJLBD.js → line-application-DY9ZTdgF.js} +0 -0
  65. /package/dist/{preview-operations-DqSo-IBm.js → preview-operations-Ca02vPDJ.js} +0 -0
  66. /package/dist/{utils-B7_9Hl_z.js → utils-BGvM02yJ.js} +0 -0
@@ -33,7 +33,7 @@ function calculateConnectionQuality(metrics, isConnected) {
33
33
  return "good";
34
34
  }
35
35
  //#endregion
36
- //#region ../../../packages/sdk/dist/client-Bnu3TXji.js
36
+ //#region ../../../packages/sdk/dist/types-BpG4d3NG.js
37
37
  function invokeClientCallback(name, callback, onError) {
38
38
  try {
39
39
  callback();
@@ -44,7 +44,74 @@ function invokeClientCallback(name, callback, onError) {
44
44
  } catch {}
45
45
  }
46
46
  }
47
+ /** Browser-safe session gateway contracts for both SDK clients. */
48
+ const INITIAL_METRICS = createConnectionMetrics();
49
+ /** Connection quality metrics derived from ping latency and missed pongs. */
50
+ var ConnectionMetricsTracker = class {
51
+ metrics;
52
+ latencyHistory = [];
53
+ constructor(initialMetrics, latencyHistorySize, isConnected, onChange) {
54
+ this.initialMetrics = initialMetrics;
55
+ this.latencyHistorySize = latencyHistorySize;
56
+ this.isConnected = isConnected;
57
+ this.onChange = onChange;
58
+ this.metrics = { ...initialMetrics };
59
+ }
60
+ get quality() {
61
+ return this.metrics.quality;
62
+ }
63
+ snapshot() {
64
+ return { ...this.metrics };
65
+ }
66
+ reset() {
67
+ this.latencyHistory = [];
68
+ this.metrics = { ...this.initialMetrics };
69
+ this.onChange(this.metrics);
70
+ }
71
+ recordMissedPongs(missedPongCount) {
72
+ this.metrics = {
73
+ ...this.metrics,
74
+ missedPongCount
75
+ };
76
+ this.refreshQuality();
77
+ }
78
+ recordLatency(latency, pongTime, missedPongCount) {
79
+ this.latencyHistory.push(latency);
80
+ if (this.latencyHistory.length > this.latencyHistorySize) this.latencyHistory.shift();
81
+ const avgLatency = this.latencyHistory.length > 0 ? this.latencyHistory.reduce((a, b) => a + b, 0) / this.latencyHistory.length : null;
82
+ this.metrics = {
83
+ ...this.metrics,
84
+ lastPingLatencyMs: latency,
85
+ avgPingLatencyMs: avgLatency,
86
+ missedPongCount,
87
+ lastPongAt: pongTime
88
+ };
89
+ this.refreshQuality();
90
+ }
91
+ trackReconnection() {
92
+ const now = Date.now();
93
+ this.metrics = {
94
+ ...this.metrics,
95
+ reconnectCount: this.metrics.reconnectCount + 1,
96
+ lastReconnectAt: now
97
+ };
98
+ this.latencyHistory = [];
99
+ this.refreshQuality();
100
+ }
101
+ refreshQuality() {
102
+ const quality = calculateConnectionQuality(this.metrics, this.isConnected());
103
+ if (this.metrics.quality !== quality) {
104
+ this.metrics = {
105
+ ...this.metrics,
106
+ quality
107
+ };
108
+ this.onChange(this.metrics);
109
+ }
110
+ }
111
+ };
47
112
  var ConnectionWaiters = class {
113
+ /** True once the current socket has reported `connection.established`. */
114
+ established = false;
48
115
  waiters = /* @__PURE__ */ new Set();
49
116
  establishmentTimeout = null;
50
117
  constructor(timeoutMs) {
@@ -73,6 +140,15 @@ var ConnectionWaiters = class {
73
140
  });
74
141
  });
75
142
  }
143
+ /** Wait for the socket to be established, or fail with `closedMessage`. */
144
+ async awaitEstablished(getState, closedMessage) {
145
+ const ready = () => this.established && getState() === "connected";
146
+ if (!ready()) {
147
+ if (getState() === "disconnected") throw new Error("Client is not connected");
148
+ await this.wait();
149
+ }
150
+ if (!ready()) throw new Error(closedMessage);
151
+ }
76
152
  resolveAll() {
77
153
  this.clear();
78
154
  for (const waiter of this.waiters) waiter.resolve();
@@ -84,7 +160,212 @@ var ConnectionWaiters = class {
84
160
  this.waiters.clear();
85
161
  }
86
162
  };
87
- const DEFAULT_CONFIG = {
163
+ const PONG_TIMEOUT_CLOSE_CODE = 4e3;
164
+ const PONG_TIMEOUT_CLOSE_REASON = "Pong timeout - connection unresponsive";
165
+ /** Sends pings on an interval and closes a socket that stops answering. */
166
+ var Heartbeat = class {
167
+ lastPingAt = null;
168
+ lastPongAt = null;
169
+ lastPingSentAt = null;
170
+ missedPongCount = 0;
171
+ pingInterval = null;
172
+ pongTimeout = null;
173
+ constructor(policy, metrics, socket, send) {
174
+ this.policy = policy;
175
+ this.metrics = metrics;
176
+ this.socket = socket;
177
+ this.send = send;
178
+ }
179
+ start() {
180
+ this.stopInterval();
181
+ this.pingInterval = setInterval(() => {
182
+ this.sendPing();
183
+ }, this.policy.pingIntervalMs);
184
+ }
185
+ stop() {
186
+ this.stopInterval();
187
+ this.clearPongTimeout();
188
+ }
189
+ resetMissedPongs() {
190
+ this.missedPongCount = 0;
191
+ }
192
+ handlePong(timestamp) {
193
+ const now = Date.now();
194
+ this.lastPongAt = timestamp;
195
+ this.missedPongCount = 0;
196
+ this.clearPongTimeout();
197
+ if (this.lastPingSentAt) this.metrics.recordLatency(now - this.lastPingSentAt, now, this.missedPongCount);
198
+ }
199
+ stopInterval() {
200
+ if (this.pingInterval) {
201
+ clearInterval(this.pingInterval);
202
+ this.pingInterval = null;
203
+ }
204
+ }
205
+ clearPongTimeout() {
206
+ if (this.pongTimeout) {
207
+ clearTimeout(this.pongTimeout);
208
+ this.pongTimeout = null;
209
+ }
210
+ }
211
+ /** Count a missed pong. Returns true when the socket was closed for it. */
212
+ recordMissedPong() {
213
+ this.missedPongCount++;
214
+ this.metrics.recordMissedPongs(this.missedPongCount);
215
+ if (this.missedPongCount >= this.policy.maxMissedPongs) {
216
+ this.socket()?.close(PONG_TIMEOUT_CLOSE_CODE, PONG_TIMEOUT_CLOSE_REASON);
217
+ return true;
218
+ }
219
+ return false;
220
+ }
221
+ sendPing() {
222
+ if (this.socket()?.readyState !== WebSocket.OPEN) return;
223
+ const timeSinceLastPong = this.lastPongAt ? Date.now() - this.lastPongAt : 0;
224
+ if (this.lastPongAt && timeSinceLastPong > this.policy.pongTimeoutMs && this.recordMissedPong()) return;
225
+ this.lastPingAt = Date.now();
226
+ this.lastPingSentAt = Date.now();
227
+ this.send({ type: "ping" });
228
+ this.pongTimeout = setTimeout(() => {
229
+ this.recordMissedPong();
230
+ }, this.policy.pongTimeoutMs);
231
+ }
232
+ };
233
+ /**
234
+ * Parse a wire frame into a server message. Reports a frame with no message
235
+ * type through `onError` and returns null; throws on invalid JSON.
236
+ */
237
+ function parseServerFrame(data, handlers) {
238
+ const raw = JSON.parse(data);
239
+ if (typeof raw.type !== "string") {
240
+ invokeClientCallback("onError", () => handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
241
+ return null;
242
+ }
243
+ if (raw.data && typeof raw.data === "object") {
244
+ const d = raw.data;
245
+ if (raw.type === "error") {
246
+ if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
247
+ if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
248
+ }
249
+ }
250
+ return raw;
251
+ }
252
+ /** Dispatch a message to client state, then to the catch-all `onMessage`. */
253
+ function deliverServerMessage(message, targets) {
254
+ const { handlers } = targets;
255
+ invokeClientCallback("message dispatch", () => dispatchServerMessage(message, targets), handlers.onError);
256
+ invokeClientCallback("onMessage", () => handlers.onMessage?.(message), handlers.onError);
257
+ }
258
+ /** Apply one validated server message to client state and its handlers. */
259
+ function dispatchServerMessage(message, targets) {
260
+ const { handlers, replay } = targets;
261
+ if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") replay.clear();
262
+ if (targets.requests.settle(message)) return;
263
+ switch (message.type) {
264
+ case "connection.established":
265
+ targets.onConnectionEstablished(message.data.sessionId);
266
+ break;
267
+ case "runtime.connected":
268
+ handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
269
+ break;
270
+ case "runtime.disconnected":
271
+ handlers.onRuntimeDisconnected?.(message.data.sandboxId, message.data.error);
272
+ break;
273
+ case "runtime.unavailable":
274
+ handlers.onRuntimeUnavailable?.(message.data);
275
+ break;
276
+ case "runtime.not_found":
277
+ handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
278
+ break;
279
+ case "runtime.ready":
280
+ handlers.onRuntimeReady?.(message.data);
281
+ break;
282
+ case "port.opened":
283
+ handlers.onPortOpened?.(message.data.port, message.data.protocol, message.data.processName);
284
+ break;
285
+ case "port.closed":
286
+ handlers.onPortClosed?.(message.data.port);
287
+ break;
288
+ case "agent.event":
289
+ targets.onAgentEvent(message.data);
290
+ handlers.onAgentEvent?.(message.channel, message.data, message.seq);
291
+ break;
292
+ case "replay.start":
293
+ replay.start(message.total);
294
+ handlers.onReplayStart?.(message.total);
295
+ break;
296
+ case "replay.progress": {
297
+ const total = replay.advance(message.received);
298
+ handlers.onReplayProgress?.(message.received, total);
299
+ break;
300
+ }
301
+ case "replay.complete":
302
+ replay.complete();
303
+ handlers.onReplayComplete?.(message.total);
304
+ break;
305
+ case "replay.truncated":
306
+ handlers.onReplayTruncated?.(message.data);
307
+ break;
308
+ case "stream.gap":
309
+ handlers.onStreamGap?.(message.data);
310
+ break;
311
+ case "stream.dead":
312
+ handlers.onStreamDead?.(message.data);
313
+ break;
314
+ case "error":
315
+ handlers.onError?.(message.message, message.code);
316
+ break;
317
+ case "token.expiring":
318
+ invokeClientCallback("onTokenExpiring", () => handlers.onTokenExpiring?.(message.data.secondsRemaining), handlers.onError);
319
+ targets.tokenRefresher.refresh();
320
+ break;
321
+ case "token.expired":
322
+ handlers.onTokenExpired?.();
323
+ break;
324
+ case "backpressure.warning":
325
+ handlers.onBackpressureWarning?.(message.data.droppedCount, message.data.since, message.data.totalDropped);
326
+ break;
327
+ }
328
+ }
329
+ const REQUEST_TIMEOUT_MS = 1e4;
330
+ /** Correlates request messages with the server replies that carry their id. */
331
+ var PendingRequests = class {
332
+ callbacks = /* @__PURE__ */ new Map();
333
+ idCounter = 0;
334
+ /** Assign a correlation id, send via `send`, and await the reply. */
335
+ request(send) {
336
+ return new Promise((resolve, reject) => {
337
+ const id = `msg_${++this.idCounter}`;
338
+ this.callbacks.set(id, {
339
+ resolve,
340
+ reject
341
+ });
342
+ setTimeout(() => {
343
+ if (this.callbacks.has(id)) {
344
+ this.callbacks.delete(id);
345
+ reject(/* @__PURE__ */ new Error("Request timeout"));
346
+ }
347
+ }, REQUEST_TIMEOUT_MS);
348
+ send(id);
349
+ });
350
+ }
351
+ /** Settle the request a reply answers. Returns false when none is waiting. */
352
+ settle(message) {
353
+ if (!("id" in message && message.id)) return false;
354
+ const callback = this.callbacks.get(message.id);
355
+ if (!callback) return false;
356
+ this.callbacks.delete(message.id);
357
+ if (message.type === "error") callback.reject(new Error(message.message));
358
+ else callback.resolve("data" in message ? message.data : void 0);
359
+ return true;
360
+ }
361
+ rejectAll(reason) {
362
+ for (const [id, callback] of this.callbacks) {
363
+ callback.reject(new Error(reason));
364
+ this.callbacks.delete(id);
365
+ }
366
+ }
367
+ };
368
+ const DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG = {
88
369
  transport: "websocket",
89
370
  channels: [],
90
371
  autoReconnect: true,
@@ -124,6 +405,191 @@ function acceptedSubscriptionChannels(acknowledgement) {
124
405
  }
125
406
  return acknowledgement.channels;
126
407
  }
408
+ /** Fill every option the caller left unset with its documented default. */
409
+ function resolveClientConfig(config) {
410
+ const defaults = DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG;
411
+ return {
412
+ url: config.url,
413
+ sessionId: config.sessionId,
414
+ token: config.token,
415
+ transport: config.transport ?? defaults.transport,
416
+ channels: config.channels ?? defaults.channels,
417
+ autoReconnect: config.autoReconnect ?? defaults.autoReconnect,
418
+ maxReconnectAttempts: config.maxReconnectAttempts ?? defaults.maxReconnectAttempts,
419
+ initialReconnectDelayMs: config.initialReconnectDelayMs ?? defaults.initialReconnectDelayMs,
420
+ maxReconnectDelayMs: config.maxReconnectDelayMs ?? defaults.maxReconnectDelayMs,
421
+ pingIntervalMs: config.pingIntervalMs ?? defaults.pingIntervalMs,
422
+ pongTimeoutMs: config.pongTimeoutMs ?? defaults.pongTimeoutMs,
423
+ maxMissedPongs: config.maxMissedPongs ?? defaults.maxMissedPongs,
424
+ enableDeduplication: config.enableDeduplication ?? defaults.enableDeduplication,
425
+ maxDeduplicationSize: config.maxDeduplicationSize ?? defaults.maxDeduplicationSize,
426
+ enableReplayPersistence: config.enableReplayPersistence ?? defaults.enableReplayPersistence,
427
+ replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? defaults.replayStorageKeyPrefix,
428
+ latencyHistorySize: config.latencyHistorySize ?? defaults.latencyHistorySize,
429
+ connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? defaults.connectionEstablishmentTimeoutMs
430
+ };
431
+ }
432
+ /** Decides whether to reconnect and schedules attempts with jittered backoff. */
433
+ var ReconnectScheduler = class {
434
+ hasConnectedBefore = false;
435
+ attempts = 0;
436
+ timer = null;
437
+ constructor(policy) {
438
+ this.policy = policy;
439
+ }
440
+ canRetry() {
441
+ return this.policy.autoReconnect && this.attempts < this.policy.maxReconnectAttempts;
442
+ }
443
+ schedule(reconnect) {
444
+ if (this.timer) return;
445
+ this.attempts++;
446
+ const delay = Math.min(this.policy.initialReconnectDelayMs * 2 ** (this.attempts - 1), this.policy.maxReconnectDelayMs);
447
+ const jitter = delay * .3 * (Math.random() * 2 - 1);
448
+ this.timer = setTimeout(() => {
449
+ this.timer = null;
450
+ reconnect();
451
+ }, delay + jitter);
452
+ }
453
+ cancel() {
454
+ if (this.timer) {
455
+ clearTimeout(this.timer);
456
+ this.timer = null;
457
+ }
458
+ }
459
+ };
460
+ /**
461
+ * Replay position of one gateway session: the last delivered event, the
462
+ * execution and session being followed, replay progress, and the set of event
463
+ * IDs already delivered. Position changes are persisted through the store.
464
+ */
465
+ var ReplayCursor = class {
466
+ lastEventId = null;
467
+ duplicatesSkipped = 0;
468
+ executionId = null;
469
+ sessionId = null;
470
+ isReplaying = false;
471
+ progress = {
472
+ total: 0,
473
+ received: 0
474
+ };
475
+ processedEventIds = /* @__PURE__ */ new Set();
476
+ constructor(store, dedup) {
477
+ this.store = store;
478
+ this.dedup = dedup;
479
+ const state = this.store.load();
480
+ this.lastEventId = state.lastEventId;
481
+ this.executionId = state.executionId;
482
+ this.sessionId = state.sessionId;
483
+ }
484
+ setContext(sessionId, executionId) {
485
+ this.sessionId = sessionId;
486
+ if (executionId) this.executionId = executionId;
487
+ this.save();
488
+ }
489
+ clear() {
490
+ this.lastEventId = null;
491
+ this.executionId = null;
492
+ this.sessionId = null;
493
+ this.isReplaying = false;
494
+ this.progress = {
495
+ total: 0,
496
+ received: 0
497
+ };
498
+ this.processedEventIds.clear();
499
+ this.duplicatesSkipped = 0;
500
+ this.store.clear();
501
+ }
502
+ state() {
503
+ return {
504
+ isReplaying: this.isReplaying,
505
+ progress: { ...this.progress }
506
+ };
507
+ }
508
+ /** Follow the execution and session named by an agent event payload. */
509
+ trackExecution(raw) {
510
+ if (typeof raw !== "object" || raw === null) return;
511
+ const eventData = raw;
512
+ if (eventData.executionId) {
513
+ this.executionId = eventData.executionId;
514
+ this.save();
515
+ }
516
+ if (eventData.type === "execution.started" && eventData.sessionId) {
517
+ this.sessionId = eventData.sessionId;
518
+ this.save();
519
+ }
520
+ }
521
+ /**
522
+ * Record a delivered event ID as the new cursor. Returns false when
523
+ * deduplication is on and the event was already delivered.
524
+ */
525
+ accept(eventId) {
526
+ if (this.dedup.enabled) {
527
+ if (this.processedEventIds.has(eventId)) {
528
+ this.duplicatesSkipped++;
529
+ return false;
530
+ }
531
+ this.processedEventIds.add(eventId);
532
+ if (this.processedEventIds.size > this.dedup.maxSize) {
533
+ const entriesToRemove = Math.floor(this.dedup.maxSize * .1);
534
+ let removed = 0;
535
+ for (const oldId of this.processedEventIds) {
536
+ if (removed >= entriesToRemove) break;
537
+ this.processedEventIds.delete(oldId);
538
+ removed++;
539
+ }
540
+ }
541
+ }
542
+ this.lastEventId = eventId;
543
+ this.save();
544
+ return true;
545
+ }
546
+ /**
547
+ * The subscribe frame sent after a connection is established, asking the
548
+ * server to resume from this cursor when there is one. Null when there is
549
+ * nothing to subscribe to.
550
+ */
551
+ subscribeMessage(channels) {
552
+ const replayOptions = {};
553
+ if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
554
+ if (this.executionId) replayOptions.executionId = this.executionId;
555
+ if (this.sessionId) replayOptions.sessionId = this.sessionId;
556
+ const hasReplayCursor = this.lastEventId !== null;
557
+ if (channels.length === 0 && !hasReplayCursor) return null;
558
+ if (hasReplayCursor) {
559
+ this.isReplaying = true;
560
+ this.progress = {
561
+ total: 0,
562
+ received: 0
563
+ };
564
+ }
565
+ return {
566
+ type: "subscribe",
567
+ channels,
568
+ ...hasReplayCursor ? { replayOptions } : {}
569
+ };
570
+ }
571
+ start(total) {
572
+ this.isReplaying = true;
573
+ this.progress = {
574
+ total,
575
+ received: 0
576
+ };
577
+ }
578
+ advance(received) {
579
+ this.progress.received = received;
580
+ return this.progress.total;
581
+ }
582
+ complete() {
583
+ this.isReplaying = false;
584
+ }
585
+ save() {
586
+ this.store.save({
587
+ lastEventId: this.lastEventId,
588
+ executionId: this.executionId,
589
+ sessionId: this.sessionId
590
+ });
591
+ }
592
+ };
127
593
  const STORAGE_KEYS = {
128
594
  lastEventId: "last_event_id",
129
595
  executionId: "execution_id",
@@ -231,106 +697,91 @@ var TokenRefresher = class {
231
697
  }
232
698
  }
233
699
  };
234
- /** Browser-safe session gateway contracts for both SDK clients. */
235
- const INITIAL_METRICS$1 = createConnectionMetrics();
236
700
  const CONNECTION_ESTABLISHMENT_TIMEOUT_CODE = 4008;
237
701
  const CONNECTION_ERROR_CODE = 4009;
238
702
  const CONNECTION_ERROR_REASON = "WebSocket connection error";
239
703
  var SessionGatewayClientCore = class {
240
704
  ws = null;
241
- config;
705
+ #config;
706
+ #currentToken;
242
707
  handlers;
243
- replayStateStore;
244
- tokenRefresher;
245
- currentToken;
246
708
  state = "disconnected";
247
- connectedAt = null;
248
- hasConnectedBefore = false;
249
- connectionEstablishedForSocket = false;
250
- lastPingAt = null;
251
- lastPongAt = null;
252
- lastPingSentAt = null;
253
- missedPongCount = 0;
254
- reconnectAttempts = 0;
255
- messagesReceived = 0;
256
- messagesSent = 0;
257
- eventsReceived = 0;
258
- duplicatesSkipped = 0;
259
- reconnectTimer = null;
260
- pingInterval = null;
261
- pongTimeout = null;
262
- pendingCallbacks = /* @__PURE__ */ new Map();
263
- connectionWaiters;
264
- messageIdCounter = 0;
265
- processedEventIds = /* @__PURE__ */ new Set();
266
- pingLatencyHistory = [];
267
- connectionMetrics;
268
- lastEventId = null;
269
- currentExecutionId = null;
270
- currentSessionId = null;
271
- isReplaying = false;
272
- replayProgress = {
273
- total: 0,
274
- received: 0
709
+ counters = {
710
+ connectedAt: null,
711
+ messagesReceived: 0,
712
+ messagesSent: 0,
713
+ eventsReceived: 0
275
714
  };
276
- constructor(config, initialMetrics = INITIAL_METRICS$1) {
277
- this.initialMetrics = initialMetrics;
278
- this.connectionMetrics = { ...initialMetrics };
715
+ connectionWaiters;
716
+ reconnects;
717
+ heartbeat;
718
+ metrics;
719
+ replayCursor;
720
+ inbound;
721
+ constructor(config, initialMetrics = INITIAL_METRICS) {
279
722
  if (!config.token.trim()) throw new Error("Session gateway token must not be empty");
280
723
  const replayStorage = resolveReplayStorage(config.replayStorage);
281
- this.config = {
282
- url: config.url,
283
- sessionId: config.sessionId,
284
- token: config.token,
285
- transport: config.transport ?? DEFAULT_CONFIG.transport,
286
- channels: config.channels ?? DEFAULT_CONFIG.channels,
287
- autoReconnect: config.autoReconnect ?? DEFAULT_CONFIG.autoReconnect,
288
- maxReconnectAttempts: config.maxReconnectAttempts ?? DEFAULT_CONFIG.maxReconnectAttempts,
289
- initialReconnectDelayMs: config.initialReconnectDelayMs ?? DEFAULT_CONFIG.initialReconnectDelayMs,
290
- maxReconnectDelayMs: config.maxReconnectDelayMs ?? DEFAULT_CONFIG.maxReconnectDelayMs,
291
- pingIntervalMs: config.pingIntervalMs ?? DEFAULT_CONFIG.pingIntervalMs,
292
- pongTimeoutMs: config.pongTimeoutMs ?? DEFAULT_CONFIG.pongTimeoutMs,
293
- maxMissedPongs: config.maxMissedPongs ?? DEFAULT_CONFIG.maxMissedPongs,
294
- enableDeduplication: config.enableDeduplication ?? DEFAULT_CONFIG.enableDeduplication,
295
- maxDeduplicationSize: config.maxDeduplicationSize ?? DEFAULT_CONFIG.maxDeduplicationSize,
296
- enableReplayPersistence: config.enableReplayPersistence ?? DEFAULT_CONFIG.enableReplayPersistence,
297
- replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? DEFAULT_CONFIG.replayStorageKeyPrefix,
298
- latencyHistorySize: config.latencyHistorySize ?? DEFAULT_CONFIG.latencyHistorySize,
299
- connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? DEFAULT_CONFIG.connectionEstablishmentTimeoutMs
300
- };
724
+ this.#config = resolveClientConfig(config);
301
725
  this.handlers = config.handlers ?? {};
302
- this.connectionWaiters = new ConnectionWaiters(this.config.connectionEstablishmentTimeoutMs);
303
- this.replayStateStore = new ReplayStateStore(this.config.enableReplayPersistence, replayStorage, this.config.replayStorageKeyPrefix, this.config.url, this.config.sessionId);
304
- this.tokenRefresher = new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError);
305
- this.currentToken = config.token;
306
- if (this.config.enableReplayPersistence) this.loadReplayState();
726
+ this.connectionWaiters = new ConnectionWaiters(this.#config.connectionEstablishmentTimeoutMs);
727
+ this.reconnects = new ReconnectScheduler(this.#config);
728
+ this.metrics = new ConnectionMetricsTracker(initialMetrics, this.#config.latencyHistorySize, () => this.state === "connected", (metrics) => invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(metrics), this.handlers.onError));
729
+ this.heartbeat = new Heartbeat(this.#config, this.metrics, () => this.ws, (message) => this.send(message));
730
+ this.replayCursor = new ReplayCursor(new ReplayStateStore(this.#config.enableReplayPersistence, replayStorage, this.#config.replayStorageKeyPrefix, this.#config.url, this.#config.sessionId), {
731
+ enabled: this.#config.enableDeduplication,
732
+ maxSize: this.#config.maxDeduplicationSize
733
+ });
734
+ this.inbound = {
735
+ handlers: this.handlers,
736
+ replay: this.replayCursor,
737
+ requests: new PendingRequests(),
738
+ tokenRefresher: new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError),
739
+ onConnectionEstablished: (sessionId) => this.handleConnectionEstablished(sessionId),
740
+ onAgentEvent: (data) => {
741
+ this.counters.eventsReceived++;
742
+ this.replayCursor.trackExecution(data);
743
+ }
744
+ };
745
+ this.#currentToken = config.token;
307
746
  }
308
747
  /**
309
748
  * Connect to the session gateway.
310
749
  */
311
750
  connect() {
312
751
  if (this.state === "connected" || this.state === "connecting" || this.state === "reconnecting") return;
313
- const nextState = this.hasConnectedBefore ? "reconnecting" : "connecting";
752
+ const nextState = this.reconnects.hasConnectedBefore ? "reconnecting" : "connecting";
314
753
  this.setState(nextState);
315
754
  if (this.getState() !== nextState) return;
316
755
  this.connectWebSocket();
317
756
  }
318
757
  connectWebSocket() {
319
- const url = new URL(this.config.url);
320
- url.searchParams.set("token", this.currentToken);
321
- this.connectionEstablishedForSocket = false;
758
+ const url = new URL(this.#config.url);
759
+ url.searchParams.set("token", this.#currentToken);
760
+ this.connectionWaiters.established = false;
322
761
  const socket = new WebSocket(url.toString());
323
762
  this.ws = socket;
763
+ const closeBeforeEstablishment = (code, reason) => {
764
+ if (this.ws !== socket || this.connectionWaiters.established) return;
765
+ try {
766
+ socket.close(code, reason);
767
+ } finally {
768
+ this.handleClose(socket, code, reason);
769
+ }
770
+ };
324
771
  socket.onopen = () => {
325
- if (this.ws === socket) this.handleOpen();
772
+ if (this.ws === socket) this.heartbeat.resetMissedPongs();
326
773
  };
327
774
  socket.onclose = (event) => this.handleClose(socket, event.code, event.reason);
328
- socket.onerror = () => this.handleError(socket);
775
+ socket.onerror = () => {
776
+ if (this.ws !== socket) return;
777
+ this.connectionWaiters.clear();
778
+ closeBeforeEstablishment(CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
779
+ };
329
780
  socket.onmessage = (event) => {
330
781
  if (this.ws === socket) this.handleMessage(event.data);
331
782
  };
332
783
  this.connectionWaiters.start((error) => {
333
- this.closeBeforeEstablishment(socket, CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
784
+ closeBeforeEstablishment(CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
334
785
  });
335
786
  }
336
787
  /**
@@ -338,8 +789,10 @@ var SessionGatewayClientCore = class {
338
789
  */
339
790
  disconnect() {
340
791
  this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Client disconnected"));
341
- this.cleanup();
342
- this.connectionEstablishedForSocket = false;
792
+ this.heartbeat.stop();
793
+ this.reconnects.cancel();
794
+ this.inbound.requests.rejectAll("Connection closed");
795
+ this.connectionWaiters.established = false;
343
796
  const socket = this.ws;
344
797
  this.ws = null;
345
798
  if (socket) socket.close(1e3, "Client disconnect");
@@ -375,8 +828,7 @@ var SessionGatewayClientCore = class {
375
828
  this.send(message);
376
829
  }
377
830
  async replayAfterConnection(message) {
378
- if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
379
- if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before replay could be requested");
831
+ await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before replay could be requested");
380
832
  this.send(message);
381
833
  }
382
834
  /**
@@ -397,34 +849,19 @@ var SessionGatewayClientCore = class {
397
849
  * Set the current session/execution context for event tracking.
398
850
  */
399
851
  setSessionContext(sessionId, executionId) {
400
- this.currentSessionId = sessionId;
401
- if (executionId) this.currentExecutionId = executionId;
402
- this.saveReplayState();
852
+ this.replayCursor.setContext(sessionId, executionId);
403
853
  }
404
854
  /**
405
855
  * Clear replay state (call when session ends).
406
856
  */
407
857
  clearReplayState() {
408
- this.lastEventId = null;
409
- this.currentExecutionId = null;
410
- this.currentSessionId = null;
411
- this.isReplaying = false;
412
- this.replayProgress = {
413
- total: 0,
414
- received: 0
415
- };
416
- this.processedEventIds.clear();
417
- this.duplicatesSkipped = 0;
418
- this.replayStateStore.clear();
858
+ this.replayCursor.clear();
419
859
  }
420
860
  /**
421
861
  * Get current replay state for UI indicators.
422
862
  */
423
863
  getReplayState() {
424
- return {
425
- isReplaying: this.isReplaying,
426
- progress: { ...this.replayProgress }
427
- };
864
+ return this.replayCursor.state();
428
865
  }
429
866
  /**
430
867
  * Get connection statistics.
@@ -432,15 +869,15 @@ var SessionGatewayClientCore = class {
432
869
  getStats() {
433
870
  return {
434
871
  state: this.state,
435
- connectedAt: this.connectedAt,
436
- lastPingAt: this.lastPingAt,
437
- lastPongAt: this.lastPongAt,
438
- reconnectAttempts: this.reconnectAttempts,
439
- messagesReceived: this.messagesReceived,
440
- messagesSent: this.messagesSent,
441
- eventsReceived: this.eventsReceived,
442
- duplicatesSkipped: this.duplicatesSkipped,
443
- metrics: { ...this.connectionMetrics },
872
+ connectedAt: this.counters.connectedAt,
873
+ lastPingAt: this.heartbeat.lastPingAt,
874
+ lastPongAt: this.heartbeat.lastPongAt,
875
+ reconnectAttempts: this.reconnects.attempts,
876
+ messagesReceived: this.counters.messagesReceived,
877
+ messagesSent: this.counters.messagesSent,
878
+ eventsReceived: this.counters.eventsReceived,
879
+ duplicatesSkipped: this.replayCursor.duplicatesSkipped,
880
+ metrics: this.metrics.snapshot(),
444
881
  replay: this.getReplayState()
445
882
  };
446
883
  }
@@ -451,56 +888,52 @@ var SessionGatewayClientCore = class {
451
888
  return this.state === "connected";
452
889
  }
453
890
  getConnectionQuality() {
454
- return this.connectionMetrics.quality;
891
+ return this.metrics.quality;
455
892
  }
456
893
  getConnectionMetrics() {
457
- return { ...this.connectionMetrics };
894
+ return this.metrics.snapshot();
458
895
  }
459
896
  resetMetrics() {
460
- this.pingLatencyHistory = [];
461
- this.connectionMetrics = { ...this.initialMetrics };
462
- invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
897
+ this.metrics.reset();
463
898
  }
464
899
  /**
465
900
  * Update the auth token and reconnect with the new token.
466
901
  */
467
902
  updateToken(token) {
468
903
  if (!token.trim()) throw new Error("Session gateway token must not be empty");
469
- this.currentToken = token;
904
+ this.#currentToken = token;
470
905
  if (this.state === "connected" && this.ws) this.ws.close(1e3, "Token refreshed");
471
906
  }
472
907
  /**
473
908
  * Get the current auth token.
474
909
  */
475
910
  getToken() {
476
- return this.currentToken;
911
+ return this.#currentToken;
477
912
  }
478
913
  setState(state) {
479
914
  if (this.state !== state) {
480
915
  this.state = state;
481
- this.updateConnectionQuality();
916
+ this.metrics.refreshQuality();
482
917
  invokeClientCallback("onStateChange", () => this.handlers.onStateChange?.(state), this.handlers.onError);
483
918
  }
484
919
  }
485
- handleOpen() {
486
- this.missedPongCount = 0;
487
- }
488
920
  handleConnectionEstablished(sessionId) {
489
- if (this.connectionEstablishedForSocket) return;
921
+ if (this.connectionWaiters.established) return;
490
922
  this.connectionWaiters.clear();
491
- const isReconnect = this.hasConnectedBefore;
492
- this.connectionEstablishedForSocket = true;
493
- this.hasConnectedBefore = true;
494
- this.connectedAt = Date.now();
495
- this.reconnectAttempts = 0;
496
- this.startPingInterval();
497
- this.restoreSubscriptions();
923
+ const isReconnect = this.reconnects.hasConnectedBefore;
924
+ this.connectionWaiters.established = true;
925
+ this.reconnects.hasConnectedBefore = true;
926
+ this.counters.connectedAt = Date.now();
927
+ this.reconnects.attempts = 0;
928
+ this.heartbeat.start();
929
+ const subscribe = this.replayCursor.subscribeMessage(this.#config.channels);
930
+ if (subscribe) this.send(subscribe);
498
931
  this.setState("connected");
499
- if (!this.connectionEstablishedForSocket || !this.isConnected()) return;
932
+ if (!this.connectionWaiters.established || !this.isConnected()) return;
500
933
  this.connectionWaiters.resolveAll();
501
934
  invokeClientCallback("onConnect", () => this.handlers.onConnect?.(sessionId), this.handlers.onError);
502
- if (isReconnect && this.connectionEstablishedForSocket && this.isConnected()) {
503
- this.trackReconnection();
935
+ if (isReconnect && this.connectionWaiters.established && this.isConnected()) {
936
+ this.metrics.trackReconnection();
504
937
  invokeClientCallback("onReconnect", () => this.handlers.onReconnect?.(), this.handlers.onError);
505
938
  }
506
939
  }
@@ -508,355 +941,49 @@ var SessionGatewayClientCore = class {
508
941
  if (this.ws !== socket) return;
509
942
  this.connectionWaiters.clear();
510
943
  this.ws = null;
511
- this.connectionEstablishedForSocket = false;
512
- this.cleanup();
513
- if (this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts) {
944
+ this.connectionWaiters.established = false;
945
+ this.heartbeat.stop();
946
+ this.reconnects.cancel();
947
+ this.inbound.requests.rejectAll("Connection closed");
948
+ if (this.reconnects.canRetry()) {
514
949
  this.setState("reconnecting");
515
- if (this.state === "reconnecting") this.scheduleReconnect();
950
+ if (this.state === "reconnecting") this.reconnects.schedule(() => {
951
+ if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
952
+ });
516
953
  } else {
517
954
  this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Connection closed"));
518
955
  this.setState("disconnected");
519
956
  }
520
957
  invokeClientCallback("onDisconnect", () => this.handlers.onDisconnect?.(code, reason), this.handlers.onError);
521
958
  }
522
- handleError(socket) {
523
- if (this.ws !== socket) return;
524
- this.connectionWaiters.clear();
525
- this.closeBeforeEstablishment(socket, CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
526
- }
527
- closeBeforeEstablishment(socket, code, reason) {
528
- if (this.ws !== socket || this.connectionEstablishedForSocket) return;
529
- try {
530
- socket.close(code, reason);
531
- } finally {
532
- this.handleClose(socket, code, reason);
533
- }
534
- }
535
959
  handleMessage(data) {
536
- this.messagesReceived++;
960
+ this.counters.messagesReceived++;
537
961
  try {
538
- const raw = JSON.parse(data);
539
- if (typeof raw.type !== "string") {
540
- invokeClientCallback("onError", () => this.handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
541
- return;
542
- }
543
- if (raw.data && typeof raw.data === "object") {
544
- const d = raw.data;
545
- if (raw.type === "error") {
546
- if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
547
- if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
548
- }
549
- }
550
- const message = raw;
962
+ const message = parseServerFrame(data, this.handlers);
963
+ if (!message) return;
551
964
  if (CONTROL_MESSAGE_TYPES.has(message.type)) {
552
- if (message.type === "pong") this.handlePong(message.timestamp);
553
- this.deliverMessage(message);
965
+ if (message.type === "pong") this.heartbeat.handlePong(message.timestamp);
966
+ deliverServerMessage(message, this.inbound);
554
967
  return;
555
968
  }
556
- if ("id" in message && message.id) {
557
- const eventId = message.id;
558
- if (this.config.enableDeduplication) {
559
- if (this.processedEventIds.has(eventId)) {
560
- this.duplicatesSkipped++;
561
- return;
562
- }
563
- this.processedEventIds.add(eventId);
564
- if (this.processedEventIds.size > this.config.maxDeduplicationSize) {
565
- const entriesToRemove = Math.floor(this.config.maxDeduplicationSize * .1);
566
- let removed = 0;
567
- for (const oldId of this.processedEventIds) {
568
- if (removed >= entriesToRemove) break;
569
- this.processedEventIds.delete(oldId);
570
- removed++;
571
- }
572
- }
573
- }
574
- this.lastEventId = eventId;
575
- this.saveReplayState();
576
- }
577
- this.deliverMessage(message);
969
+ if ("id" in message && message.id && !this.replayCursor.accept(message.id)) return;
970
+ deliverServerMessage(message, this.inbound);
578
971
  } catch {}
579
972
  }
580
- handlePong(timestamp) {
581
- const now = Date.now();
582
- this.lastPongAt = timestamp;
583
- this.missedPongCount = 0;
584
- this.clearPongTimeout();
585
- if (this.lastPingSentAt) {
586
- const latency = now - this.lastPingSentAt;
587
- this.pingLatencyHistory.push(latency);
588
- if (this.pingLatencyHistory.length > this.config.latencyHistorySize) this.pingLatencyHistory.shift();
589
- this.updateConnectionMetrics(latency, now);
590
- }
591
- }
592
- dispatchMessage(message) {
593
- if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") this.clearReplayState();
594
- if ("id" in message && message.id) {
595
- const callback = this.pendingCallbacks.get(message.id);
596
- if (callback) {
597
- this.pendingCallbacks.delete(message.id);
598
- if (message.type === "error") callback.reject(new Error(message.message));
599
- else callback.resolve("data" in message ? message.data : void 0);
600
- return;
601
- }
602
- }
603
- switch (message.type) {
604
- case "connection.established":
605
- this.handleConnectionEstablished(message.data.sessionId);
606
- break;
607
- case "runtime.connected":
608
- this.handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
609
- break;
610
- case "runtime.disconnected":
611
- this.handlers.onRuntimeDisconnected?.(message.data.sandboxId, message.data.error);
612
- break;
613
- case "runtime.unavailable":
614
- this.handlers.onRuntimeUnavailable?.(message.data);
615
- break;
616
- case "runtime.not_found":
617
- this.handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
618
- break;
619
- case "runtime.ready":
620
- this.handlers.onRuntimeReady?.(message.data);
621
- break;
622
- case "port.opened":
623
- this.handlers.onPortOpened?.(message.data.port, message.data.protocol, message.data.processName);
624
- break;
625
- case "port.closed":
626
- this.handlers.onPortClosed?.(message.data.port);
627
- break;
628
- case "agent.event":
629
- this.eventsReceived++;
630
- this.trackExecutionContext(message.data);
631
- this.handlers.onAgentEvent?.(message.channel, message.data, message.seq);
632
- break;
633
- case "replay.start":
634
- this.isReplaying = true;
635
- this.replayProgress = {
636
- total: message.total,
637
- received: 0
638
- };
639
- this.handlers.onReplayStart?.(message.total);
640
- break;
641
- case "replay.progress":
642
- this.replayProgress.received = message.received;
643
- this.handlers.onReplayProgress?.(message.received, this.replayProgress.total);
644
- break;
645
- case "replay.complete":
646
- this.isReplaying = false;
647
- this.handlers.onReplayComplete?.(message.total);
648
- break;
649
- case "replay.truncated":
650
- this.handlers.onReplayTruncated?.(message.data);
651
- break;
652
- case "stream.gap":
653
- this.handlers.onStreamGap?.(message.data);
654
- break;
655
- case "stream.dead":
656
- this.handlers.onStreamDead?.(message.data);
657
- break;
658
- case "error":
659
- this.handlers.onError?.(message.message, message.code);
660
- break;
661
- case "token.expiring":
662
- invokeClientCallback("onTokenExpiring", () => this.handlers.onTokenExpiring?.(message.data.secondsRemaining), this.handlers.onError);
663
- this.tokenRefresher.refresh();
664
- break;
665
- case "token.expired":
666
- this.handlers.onTokenExpired?.();
667
- break;
668
- case "backpressure.warning":
669
- this.handlers.onBackpressureWarning?.(message.data.droppedCount, message.data.since, message.data.totalDropped);
670
- break;
671
- }
672
- }
673
- deliverMessage(message) {
674
- invokeClientCallback("message dispatch", () => this.dispatchMessage(message), this.handlers.onError);
675
- invokeClientCallback("onMessage", () => this.handlers.onMessage?.(message), this.handlers.onError);
676
- }
677
- trackExecutionContext(raw) {
678
- if (typeof raw !== "object" || raw === null) return;
679
- const eventData = raw;
680
- if (eventData.executionId) {
681
- this.currentExecutionId = eventData.executionId;
682
- this.saveReplayState();
683
- }
684
- if (eventData.type === "execution.started" && eventData.sessionId) {
685
- this.currentSessionId = eventData.sessionId;
686
- this.saveReplayState();
687
- }
688
- }
689
973
  send(message) {
690
974
  if (this.ws?.readyState === WebSocket.OPEN) {
691
975
  this.ws.send(JSON.stringify(message));
692
- this.messagesSent++;
976
+ this.counters.messagesSent++;
693
977
  }
694
978
  }
695
979
  async sendWithResponse(message) {
696
- if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
697
- if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before request could be sent");
698
- return new Promise((resolve, reject) => {
699
- const id = `msg_${++this.messageIdCounter}`;
700
- this.pendingCallbacks.set(id, {
701
- resolve,
702
- reject
703
- });
704
- setTimeout(() => {
705
- if (this.pendingCallbacks.has(id)) {
706
- this.pendingCallbacks.delete(id);
707
- reject(/* @__PURE__ */ new Error("Request timeout"));
708
- }
709
- }, 1e4);
710
- this.send({
711
- ...message,
712
- id
713
- });
714
- });
715
- }
716
- waitForConnectionEstablished() {
717
- if (this.connectionEstablishedForSocket && this.isConnected()) return Promise.resolve();
718
- if (this.state === "disconnected") return Promise.reject(/* @__PURE__ */ new Error("Client is not connected"));
719
- return this.connectionWaiters.wait();
720
- }
721
- restoreSubscriptions() {
722
- const channels = this.config.channels;
723
- const replayOptions = {};
724
- if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
725
- if (this.currentExecutionId) replayOptions.executionId = this.currentExecutionId;
726
- if (this.currentSessionId) replayOptions.sessionId = this.currentSessionId;
727
- const hasReplayCursor = this.lastEventId !== null;
728
- if (channels.length === 0 && !hasReplayCursor) return;
729
- if (hasReplayCursor) {
730
- this.isReplaying = true;
731
- this.replayProgress = {
732
- total: 0,
733
- received: 0
734
- };
735
- }
736
- this.send({
737
- type: "subscribe",
738
- channels,
739
- ...hasReplayCursor ? { replayOptions } : {}
740
- });
741
- }
742
- startPingInterval() {
743
- this.stopPingInterval();
744
- this.pingInterval = setInterval(() => {
745
- this.sendPing();
746
- }, this.config.pingIntervalMs);
747
- }
748
- stopPingInterval() {
749
- if (this.pingInterval) {
750
- clearInterval(this.pingInterval);
751
- this.pingInterval = null;
752
- }
753
- }
754
- sendPing() {
755
- if (this.ws?.readyState !== WebSocket.OPEN) return;
756
- const timeSinceLastPong = this.lastPongAt ? Date.now() - this.lastPongAt : 0;
757
- if (this.lastPongAt && timeSinceLastPong > this.config.pongTimeoutMs) {
758
- this.missedPongCount++;
759
- this.connectionMetrics = {
760
- ...this.connectionMetrics,
761
- missedPongCount: this.missedPongCount
762
- };
763
- this.updateConnectionQuality();
764
- if (this.missedPongCount >= this.config.maxMissedPongs) {
765
- this.ws?.close(4e3, "Pong timeout - connection unresponsive");
766
- return;
767
- }
768
- }
769
- this.lastPingAt = Date.now();
770
- this.lastPingSentAt = Date.now();
771
- this.send({ type: "ping" });
772
- this.pongTimeout = setTimeout(() => {
773
- this.missedPongCount++;
774
- this.connectionMetrics = {
775
- ...this.connectionMetrics,
776
- missedPongCount: this.missedPongCount
777
- };
778
- this.updateConnectionQuality();
779
- if (this.missedPongCount >= this.config.maxMissedPongs) this.ws?.close(4e3, "Pong timeout - connection unresponsive");
780
- }, this.config.pongTimeoutMs);
781
- }
782
- clearPongTimeout() {
783
- if (this.pongTimeout) {
784
- clearTimeout(this.pongTimeout);
785
- this.pongTimeout = null;
786
- }
787
- }
788
- scheduleReconnect() {
789
- if (this.reconnectTimer) return;
790
- this.reconnectAttempts++;
791
- const delay = Math.min(this.config.initialReconnectDelayMs * 2 ** (this.reconnectAttempts - 1), this.config.maxReconnectDelayMs);
792
- const jitter = delay * .3 * (Math.random() * 2 - 1);
793
- this.reconnectTimer = setTimeout(() => {
794
- this.reconnectTimer = null;
795
- if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
796
- }, delay + jitter);
797
- }
798
- cleanup() {
799
- this.stopPingInterval();
800
- this.clearPongTimeout();
801
- if (this.reconnectTimer) {
802
- clearTimeout(this.reconnectTimer);
803
- this.reconnectTimer = null;
804
- }
805
- for (const [id, callback] of this.pendingCallbacks) {
806
- callback.reject(/* @__PURE__ */ new Error("Connection closed"));
807
- this.pendingCallbacks.delete(id);
808
- }
809
- }
810
- updateConnectionMetrics(latency, pongTime) {
811
- const avgLatency = this.pingLatencyHistory.length > 0 ? this.pingLatencyHistory.reduce((a, b) => a + b, 0) / this.pingLatencyHistory.length : null;
812
- this.connectionMetrics = {
813
- ...this.connectionMetrics,
814
- lastPingLatencyMs: latency,
815
- avgPingLatencyMs: avgLatency,
816
- missedPongCount: this.missedPongCount,
817
- lastPongAt: pongTime
818
- };
819
- this.updateConnectionQuality();
820
- }
821
- updateConnectionQuality() {
822
- const isConnected = this.state === "connected";
823
- const quality = calculateConnectionQuality(this.connectionMetrics, isConnected);
824
- if (this.connectionMetrics.quality !== quality) {
825
- this.connectionMetrics = {
826
- ...this.connectionMetrics,
827
- quality
828
- };
829
- invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
830
- }
831
- }
832
- trackReconnection() {
833
- const now = Date.now();
834
- this.connectionMetrics = {
835
- ...this.connectionMetrics,
836
- reconnectCount: this.connectionMetrics.reconnectCount + 1,
837
- lastReconnectAt: now
838
- };
839
- this.pingLatencyHistory = [];
840
- this.updateConnectionQuality();
841
- }
842
- loadReplayState() {
843
- const state = this.replayStateStore.load();
844
- this.lastEventId = state.lastEventId;
845
- this.currentExecutionId = state.executionId;
846
- this.currentSessionId = state.sessionId;
847
- }
848
- saveReplayState() {
849
- this.replayStateStore.save({
850
- lastEventId: this.lastEventId,
851
- executionId: this.currentExecutionId,
852
- sessionId: this.currentSessionId
853
- });
980
+ await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before request could be sent");
981
+ return this.inbound.requests.request((id) => this.send({
982
+ ...message,
983
+ id
984
+ }));
854
985
  }
855
986
  };
856
- createConnectionMetrics();
857
- //#endregion
858
- //#region src/session-gateway/types.ts
859
- const INITIAL_METRICS = createConnectionMetrics();
860
987
  //#endregion
861
988
  //#region src/session-gateway/client.ts
862
989
  /** Sandbox replay waits for the server's authenticated connection receipt. */