@tangle-network/sandbox 0.11.1 → 0.12.0-develop.20260724231304.911a687

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.
@@ -1,40 +1,65 @@
1
- //#region src/session-gateway/types.ts
2
- /**
3
- * Default connection metrics.
4
- */
5
- const INITIAL_METRICS = {
6
- lastPingLatencyMs: null,
7
- avgPingLatencyMs: null,
8
- missedPongCount: 0,
9
- reconnectCount: 0,
10
- lastPongAt: null,
11
- lastReconnectAt: null,
12
- quality: "disconnected"
13
- };
14
- /**
15
- * Calculate connection quality from metrics.
16
- */
17
- function calculateConnectionQuality(metrics, isConnected) {
18
- if (!isConnected) return "disconnected";
19
- const { avgPingLatencyMs, missedPongCount, reconnectCount, lastReconnectAt } = metrics;
20
- const recentReconnect = lastReconnectAt && Date.now() - lastReconnectAt < 300 * 1e3;
21
- if (missedPongCount >= 2 || recentReconnect && reconnectCount > 1) return "poor";
22
- if (missedPongCount >= 1 || avgPingLatencyMs !== null && avgPingLatencyMs > 1e3 || recentReconnect) return "degraded";
23
- if (avgPingLatencyMs !== null && avgPingLatencyMs < 100 && reconnectCount === 0) return "excellent";
24
- if (avgPingLatencyMs !== null && avgPingLatencyMs <= 300) return "good";
25
- return "good";
1
+ //#region src/session-gateway/callback.ts
2
+ function invokeClientCallback(name, callback, onError) {
3
+ try {
4
+ callback();
5
+ } catch (error) {
6
+ if (name === "onError") return;
7
+ try {
8
+ onError?.(`${name} callback failed: ${error instanceof Error ? error.message : String(error)}`, "CALLBACK_ERROR");
9
+ } catch {}
10
+ }
26
11
  }
27
12
  //#endregion
28
- //#region src/session-gateway/client.ts
29
- /**
30
- * SessionGatewayClient
31
- *
32
- * WebSocket client for Sandbox API session streaming.
33
- * Browser-safe: no Node.js APIs.
34
- */
13
+ //#region src/session-gateway/connection-waiters.ts
14
+ var ConnectionWaiters = class {
15
+ waiters = /* @__PURE__ */ new Set();
16
+ establishmentTimeout = null;
17
+ constructor(timeoutMs) {
18
+ this.timeoutMs = timeoutMs;
19
+ }
20
+ start(onTimeout) {
21
+ this.clear();
22
+ this.establishmentTimeout = setTimeout(() => {
23
+ this.establishmentTimeout = null;
24
+ const error = /* @__PURE__ */ new Error(`Connection establishment timed out after ${this.timeoutMs}ms`);
25
+ this.rejectAll(error);
26
+ onTimeout(error);
27
+ }, this.timeoutMs);
28
+ }
29
+ clear() {
30
+ if (this.establishmentTimeout !== null) {
31
+ clearTimeout(this.establishmentTimeout);
32
+ this.establishmentTimeout = null;
33
+ }
34
+ }
35
+ wait() {
36
+ return new Promise((resolve, reject) => {
37
+ this.waiters.add({
38
+ resolve: () => {
39
+ resolve();
40
+ },
41
+ reject: (error) => {
42
+ reject(error);
43
+ }
44
+ });
45
+ });
46
+ }
47
+ resolveAll() {
48
+ this.clear();
49
+ for (const waiter of this.waiters) waiter.resolve();
50
+ this.waiters.clear();
51
+ }
52
+ rejectAll(error) {
53
+ this.clear();
54
+ for (const waiter of this.waiters) waiter.reject(error);
55
+ this.waiters.clear();
56
+ }
57
+ };
58
+ //#endregion
59
+ //#region src/session-gateway/protocol.ts
35
60
  const DEFAULT_CONFIG = {
36
61
  transport: "websocket",
37
- channels: ["*"],
62
+ channels: [],
38
63
  autoReconnect: true,
39
64
  maxReconnectAttempts: 10,
40
65
  initialReconnectDelayMs: 1e3,
@@ -46,29 +71,39 @@ const DEFAULT_CONFIG = {
46
71
  maxDeduplicationSize: 1e3,
47
72
  enableReplayPersistence: false,
48
73
  replayStorageKeyPrefix: "session_gateway_",
49
- latencyHistorySize: 10
74
+ latencyHistorySize: 10,
75
+ connectionEstablishmentTimeoutMs: 1e4
50
76
  };
77
+ const CONTROL_MESSAGE_TYPES = new Set([
78
+ "connection.established",
79
+ "subscribed",
80
+ "unsubscribed",
81
+ "pong",
82
+ "replay.start",
83
+ "replay.progress",
84
+ "replay.complete",
85
+ "error",
86
+ "token.expiring",
87
+ "token.expired",
88
+ "backpressure.warning",
89
+ "terminal.input.error",
90
+ "heartbeat"
91
+ ]);
92
+ function acceptedSubscriptionChannels(acknowledgement) {
93
+ if (acknowledgement.denied?.length) {
94
+ const reasons = acknowledgement.denied.map(({ channel, reason }) => `${channel}: ${reason}`).join(", ");
95
+ throw new Error(`Subscription denied (${reasons})`);
96
+ }
97
+ return acknowledgement.channels;
98
+ }
99
+ //#endregion
100
+ //#region src/session-gateway/replay-storage.ts
51
101
  const STORAGE_KEYS = {
52
102
  lastEventId: "last_event_id",
53
103
  executionId: "execution_id",
54
104
  sessionId: "session_id"
55
105
  };
56
- /**
57
- * Legacy wire-protocol message type map. The current server emits the
58
- * `sidecar.*` message types; the SDK surfaces the canonical `runtime.*`
59
- * names. Kept at module scope so it isn't re-allocated per inbound
60
- * WebSocket message.
61
- */
62
- const WIRE_TYPE_MAP = {
63
- "sidecar.connected": "runtime.connected",
64
- "sidecar.disconnected": "runtime.disconnected",
65
- "sidecar.not_found": "runtime.not_found",
66
- "sidecar.ready": "runtime.ready"
67
- };
68
- /**
69
- * Memory-based storage fallback when localStorage is not available.
70
- */
71
- var MemoryStorage = class {
106
+ var MemoryReplayStorage = class {
72
107
  store = /* @__PURE__ */ new Map();
73
108
  getItem(key) {
74
109
  return this.store.get(key) ?? null;
@@ -80,15 +115,141 @@ var MemoryStorage = class {
80
115
  this.store.delete(key);
81
116
  }
82
117
  };
118
+ function resolveReplayStorage(configured) {
119
+ if (configured) return configured;
120
+ if (typeof globalThis !== "undefined" && "localStorage" in globalThis) try {
121
+ const testKey = "__session_gateway_storage_test__";
122
+ const previous = localStorage.getItem(testKey);
123
+ try {
124
+ localStorage.setItem(testKey, testKey);
125
+ localStorage.removeItem(testKey);
126
+ } finally {
127
+ if (previous !== null) localStorage.setItem(testKey, previous);
128
+ }
129
+ return localStorage;
130
+ } catch {
131
+ return new MemoryReplayStorage();
132
+ }
133
+ return new MemoryReplayStorage();
134
+ }
135
+ function endpointIdentity(rawUrl) {
136
+ const url = new URL(rawUrl);
137
+ url.username = "";
138
+ url.password = "";
139
+ url.hash = "";
140
+ for (const key of [...url.searchParams.keys()]) if (/(^|[-_])(api[-_]?key|auth|authorization|credential|key|password|secret|sig|signature|token)($|[-_])/i.test(key)) url.searchParams.delete(key);
141
+ url.searchParams.sort();
142
+ return url.toString();
143
+ }
144
+ var ReplayStateStore = class {
145
+ prefix;
146
+ constructor(enabled, storage, keyPrefix, endpointUrl, sessionId) {
147
+ this.enabled = enabled;
148
+ this.storage = storage;
149
+ this.prefix = `${keyPrefix}${encodeURIComponent(endpointIdentity(endpointUrl))}:${encodeURIComponent(sessionId)}:`;
150
+ }
151
+ load() {
152
+ if (!this.enabled) return this.emptyState();
153
+ try {
154
+ return {
155
+ lastEventId: this.storage.getItem(this.prefix + STORAGE_KEYS.lastEventId),
156
+ executionId: this.storage.getItem(this.prefix + STORAGE_KEYS.executionId),
157
+ sessionId: this.storage.getItem(this.prefix + STORAGE_KEYS.sessionId)
158
+ };
159
+ } catch {
160
+ return this.emptyState();
161
+ }
162
+ }
163
+ save(state) {
164
+ if (!this.enabled) return;
165
+ try {
166
+ if (state.lastEventId) this.storage.setItem(this.prefix + STORAGE_KEYS.lastEventId, state.lastEventId);
167
+ if (state.executionId) this.storage.setItem(this.prefix + STORAGE_KEYS.executionId, state.executionId);
168
+ if (state.sessionId) this.storage.setItem(this.prefix + STORAGE_KEYS.sessionId, state.sessionId);
169
+ } catch {}
170
+ }
171
+ clear() {
172
+ if (!this.enabled) return;
173
+ try {
174
+ this.storage.removeItem(this.prefix + STORAGE_KEYS.lastEventId);
175
+ this.storage.removeItem(this.prefix + STORAGE_KEYS.executionId);
176
+ this.storage.removeItem(this.prefix + STORAGE_KEYS.sessionId);
177
+ } catch {}
178
+ }
179
+ emptyState() {
180
+ return {
181
+ lastEventId: null,
182
+ executionId: null,
183
+ sessionId: null
184
+ };
185
+ }
186
+ };
187
+ //#endregion
188
+ //#region src/session-gateway/token-refresh.ts
189
+ var TokenRefresher = class {
190
+ refreshing = false;
191
+ constructor(refreshToken, applyToken, onError) {
192
+ this.refreshToken = refreshToken;
193
+ this.applyToken = applyToken;
194
+ this.onError = onError;
195
+ }
196
+ async refresh() {
197
+ if (!this.refreshToken || this.refreshing) return;
198
+ this.refreshing = true;
199
+ try {
200
+ const result = await this.refreshToken();
201
+ if (!result.token.trim()) throw new Error("token refresh returned an empty token");
202
+ this.applyToken(result.token);
203
+ } catch (error) {
204
+ invokeClientCallback("onError", () => this.onError?.(`Token refresh failed: ${error instanceof Error ? error.message : String(error)}`, "TOKEN_REFRESH_FAILED"), this.onError);
205
+ } finally {
206
+ this.refreshing = false;
207
+ }
208
+ }
209
+ };
210
+ //#endregion
211
+ //#region src/session-gateway/types.ts
212
+ /**
213
+ * Default connection metrics.
214
+ */
215
+ const INITIAL_METRICS = {
216
+ lastPingLatencyMs: null,
217
+ avgPingLatencyMs: null,
218
+ missedPongCount: 0,
219
+ reconnectCount: 0,
220
+ lastPongAt: null,
221
+ lastReconnectAt: null,
222
+ quality: "disconnected"
223
+ };
224
+ /**
225
+ * Calculate connection quality from metrics.
226
+ */
227
+ function calculateConnectionQuality(metrics, isConnected) {
228
+ if (!isConnected) return "disconnected";
229
+ const { avgPingLatencyMs, missedPongCount, reconnectCount, lastReconnectAt } = metrics;
230
+ const recentReconnect = lastReconnectAt && Date.now() - lastReconnectAt < 300 * 1e3;
231
+ if (missedPongCount >= 2 || recentReconnect && reconnectCount > 1) return "poor";
232
+ if (missedPongCount >= 1 || avgPingLatencyMs !== null && avgPingLatencyMs > 1e3 || recentReconnect) return "degraded";
233
+ if (avgPingLatencyMs !== null && avgPingLatencyMs < 100 && reconnectCount === 0) return "excellent";
234
+ if (avgPingLatencyMs !== null && avgPingLatencyMs <= 300) return "good";
235
+ return "good";
236
+ }
237
+ //#endregion
238
+ //#region src/session-gateway/client.ts
239
+ const CONNECTION_ESTABLISHMENT_TIMEOUT_CODE = 4008;
240
+ const CONNECTION_ERROR_CODE = 4009;
241
+ const CONNECTION_ERROR_REASON = "WebSocket connection error";
83
242
  var SessionGatewayClient = class {
84
243
  ws = null;
85
244
  config;
86
245
  handlers;
246
+ replayStateStore;
247
+ tokenRefresher;
87
248
  currentToken;
88
- isRefreshingToken = false;
89
249
  state = "disconnected";
90
250
  connectedAt = null;
91
251
  hasConnectedBefore = false;
252
+ connectionEstablishedForSocket = false;
92
253
  lastPingAt = null;
93
254
  lastPongAt = null;
94
255
  lastPingSentAt = null;
@@ -102,6 +263,7 @@ var SessionGatewayClient = class {
102
263
  pingInterval = null;
103
264
  pongTimeout = null;
104
265
  pendingCallbacks = /* @__PURE__ */ new Map();
266
+ connectionWaiters;
105
267
  messageIdCounter = 0;
106
268
  processedEventIds = /* @__PURE__ */ new Set();
107
269
  pingLatencyHistory = [];
@@ -115,22 +277,12 @@ var SessionGatewayClient = class {
115
277
  received: 0
116
278
  };
117
279
  constructor(config) {
118
- let storage;
119
- if (config.replayStorage) storage = config.replayStorage;
120
- else if (typeof globalThis !== "undefined" && "localStorage" in globalThis) try {
121
- const testKey = "__test__";
122
- localStorage.setItem(testKey, testKey);
123
- localStorage.removeItem(testKey);
124
- storage = localStorage;
125
- } catch {
126
- storage = new MemoryStorage();
127
- }
128
- else storage = new MemoryStorage();
280
+ if (!config.token.trim()) throw new Error("Session gateway token must not be empty");
281
+ const replayStorage = resolveReplayStorage(config.replayStorage);
129
282
  this.config = {
130
283
  url: config.url,
131
284
  sessionId: config.sessionId,
132
285
  token: config.token,
133
- onTokenRefresh: config.onTokenRefresh,
134
286
  transport: config.transport ?? DEFAULT_CONFIG.transport,
135
287
  channels: config.channels ?? DEFAULT_CONFIG.channels,
136
288
  autoReconnect: config.autoReconnect ?? DEFAULT_CONFIG.autoReconnect,
@@ -143,11 +295,14 @@ var SessionGatewayClient = class {
143
295
  enableDeduplication: config.enableDeduplication ?? DEFAULT_CONFIG.enableDeduplication,
144
296
  maxDeduplicationSize: config.maxDeduplicationSize ?? DEFAULT_CONFIG.maxDeduplicationSize,
145
297
  enableReplayPersistence: config.enableReplayPersistence ?? DEFAULT_CONFIG.enableReplayPersistence,
146
- replayStorage: storage,
147
298
  replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? DEFAULT_CONFIG.replayStorageKeyPrefix,
148
- latencyHistorySize: config.latencyHistorySize ?? DEFAULT_CONFIG.latencyHistorySize
299
+ latencyHistorySize: config.latencyHistorySize ?? DEFAULT_CONFIG.latencyHistorySize,
300
+ connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? DEFAULT_CONFIG.connectionEstablishmentTimeoutMs
149
301
  };
150
302
  this.handlers = config.handlers ?? {};
303
+ this.connectionWaiters = new ConnectionWaiters(this.config.connectionEstablishmentTimeoutMs);
304
+ this.replayStateStore = new ReplayStateStore(this.config.enableReplayPersistence, replayStorage, this.config.replayStorageKeyPrefix, this.config.url, this.config.sessionId);
305
+ this.tokenRefresher = new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError);
151
306
  this.currentToken = config.token;
152
307
  if (this.config.enableReplayPersistence) this.loadReplayState();
153
308
  }
@@ -155,30 +310,37 @@ var SessionGatewayClient = class {
155
310
  * Connect to the session gateway.
156
311
  */
157
312
  connect() {
158
- if (this.state === "connected" || this.state === "connecting") return;
159
- const isReconnect = this.hasConnectedBefore;
160
- this.setState(isReconnect ? "reconnecting" : "connecting");
313
+ if (this.state === "connected" || this.state === "connecting" || this.state === "reconnecting") return;
314
+ const nextState = this.hasConnectedBefore ? "reconnecting" : "connecting";
315
+ this.setState(nextState);
316
+ if (this.getState() !== nextState) return;
161
317
  this.connectWebSocket();
162
318
  }
163
319
  connectWebSocket() {
164
320
  const url = new URL(this.config.url);
165
321
  url.searchParams.set("token", this.currentToken);
322
+ this.connectionEstablishedForSocket = false;
166
323
  const socket = new WebSocket(url.toString());
167
324
  this.ws = socket;
168
325
  socket.onopen = () => {
169
326
  if (this.ws === socket) this.handleOpen();
170
327
  };
171
328
  socket.onclose = (event) => this.handleClose(socket, event.code, event.reason);
172
- socket.onerror = (_event) => {};
329
+ socket.onerror = () => this.handleError(socket);
173
330
  socket.onmessage = (event) => {
174
331
  if (this.ws === socket) this.handleMessage(event.data);
175
332
  };
333
+ this.connectionWaiters.start((error) => {
334
+ this.closeBeforeEstablishment(socket, CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
335
+ });
176
336
  }
177
337
  /**
178
338
  * Disconnect from the session gateway.
179
339
  */
180
340
  disconnect() {
341
+ this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Client disconnected"));
181
342
  this.cleanup();
343
+ this.connectionEstablishedForSocket = false;
182
344
  const socket = this.ws;
183
345
  this.ws = null;
184
346
  if (socket) socket.close(1e3, "Client disconnect");
@@ -188,10 +350,10 @@ var SessionGatewayClient = class {
188
350
  * Subscribe to additional channels.
189
351
  */
190
352
  async subscribe(channels) {
191
- return (await this.sendWithResponse({
353
+ return acceptedSubscriptionChannels(await this.sendWithResponse({
192
354
  type: "subscribe",
193
355
  channels
194
- })).channels;
356
+ }));
195
357
  }
196
358
  /**
197
359
  * Unsubscribe from channels.
@@ -213,7 +375,9 @@ var SessionGatewayClient = class {
213
375
  /**
214
376
  * Request replay of events since a timestamp.
215
377
  */
216
- replay(since) {
378
+ async replay(since) {
379
+ if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
380
+ if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before replay could be requested");
217
381
  this.send({
218
382
  type: "replay",
219
383
  since
@@ -255,14 +419,7 @@ var SessionGatewayClient = class {
255
419
  };
256
420
  this.processedEventIds.clear();
257
421
  this.duplicatesSkipped = 0;
258
- if (this.config.enableReplayPersistence) {
259
- const prefix = this.config.replayStorageKeyPrefix;
260
- try {
261
- this.config.replayStorage.removeItem(prefix + STORAGE_KEYS.lastEventId);
262
- this.config.replayStorage.removeItem(prefix + STORAGE_KEYS.executionId);
263
- this.config.replayStorage.removeItem(prefix + STORAGE_KEYS.sessionId);
264
- } catch {}
265
- }
422
+ this.replayStateStore.clear();
266
423
  }
267
424
  /**
268
425
  * Get current replay state for UI indicators.
@@ -306,12 +463,13 @@ var SessionGatewayClient = class {
306
463
  resetMetrics() {
307
464
  this.pingLatencyHistory = [];
308
465
  this.connectionMetrics = { ...INITIAL_METRICS };
309
- this.handlers.onMetricsChange?.(this.connectionMetrics);
466
+ invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
310
467
  }
311
468
  /**
312
469
  * Update the auth token and reconnect with the new token.
313
470
  */
314
471
  updateToken(token) {
472
+ if (!token.trim()) throw new Error("Session gateway token must not be empty");
315
473
  this.currentToken = token;
316
474
  if (this.state === "connected" && this.ws) this.ws.close(1e3, "Token refreshed");
317
475
  }
@@ -325,73 +483,102 @@ var SessionGatewayClient = class {
325
483
  if (this.state !== state) {
326
484
  this.state = state;
327
485
  this.updateConnectionQuality();
328
- this.handlers.onStateChange?.(state);
486
+ invokeClientCallback("onStateChange", () => this.handlers.onStateChange?.(state), this.handlers.onError);
329
487
  }
330
488
  }
331
489
  handleOpen() {
490
+ this.missedPongCount = 0;
491
+ }
492
+ handleConnectionEstablished(sessionId) {
493
+ if (this.connectionEstablishedForSocket) return;
494
+ this.connectionWaiters.clear();
332
495
  const isReconnect = this.hasConnectedBefore;
496
+ this.connectionEstablishedForSocket = true;
333
497
  this.hasConnectedBefore = true;
334
- this.setState("connected");
335
498
  this.connectedAt = Date.now();
336
499
  this.reconnectAttempts = 0;
337
- this.missedPongCount = 0;
338
500
  this.startPingInterval();
339
501
  this.restoreSubscriptions();
340
- if (isReconnect) {
502
+ this.setState("connected");
503
+ if (!this.connectionEstablishedForSocket || !this.isConnected()) return;
504
+ this.connectionWaiters.resolveAll();
505
+ invokeClientCallback("onConnect", () => this.handlers.onConnect?.(sessionId), this.handlers.onError);
506
+ if (isReconnect && this.connectionEstablishedForSocket && this.isConnected()) {
341
507
  this.trackReconnection();
342
- this.handlers.onReconnect?.();
508
+ invokeClientCallback("onReconnect", () => this.handlers.onReconnect?.(), this.handlers.onError);
343
509
  }
344
510
  }
345
511
  handleClose(socket, code, reason) {
346
512
  if (this.ws !== socket) return;
513
+ this.connectionWaiters.clear();
347
514
  this.ws = null;
515
+ this.connectionEstablishedForSocket = false;
348
516
  this.cleanup();
349
- this.handlers.onDisconnect?.(code, reason);
350
517
  if (this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts) {
351
518
  this.setState("reconnecting");
352
- this.scheduleReconnect();
353
- } else this.setState("disconnected");
519
+ if (this.state === "reconnecting") this.scheduleReconnect();
520
+ } else {
521
+ this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Connection closed"));
522
+ this.setState("disconnected");
523
+ }
524
+ invokeClientCallback("onDisconnect", () => this.handlers.onDisconnect?.(code, reason), this.handlers.onError);
525
+ }
526
+ handleError(socket) {
527
+ if (this.ws !== socket) return;
528
+ this.connectionWaiters.clear();
529
+ this.closeBeforeEstablishment(socket, CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
530
+ }
531
+ closeBeforeEstablishment(socket, code, reason) {
532
+ if (this.ws !== socket || this.connectionEstablishedForSocket) return;
533
+ try {
534
+ socket.close(code, reason);
535
+ } finally {
536
+ this.handleClose(socket, code, reason);
537
+ }
354
538
  }
355
539
  handleMessage(data) {
356
540
  this.messagesReceived++;
357
541
  try {
358
542
  const raw = JSON.parse(data);
359
- if (!raw.type && raw.messageType) raw.type = raw.messageType;
360
- if (typeof raw.type === "string" && WIRE_TYPE_MAP[raw.type] !== void 0) raw.type = WIRE_TYPE_MAP[raw.type];
543
+ if (typeof raw.type !== "string") {
544
+ invokeClientCallback("onError", () => this.handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
545
+ return;
546
+ }
361
547
  if (raw.data && typeof raw.data === "object") {
362
548
  const d = raw.data;
363
- if (d.sidecarId !== void 0 && d.sandboxId === void 0) d.sandboxId = d.sidecarId;
364
- }
365
- if (raw.type === "agent.event" && !raw.data && raw.channel) {
366
- const { type, messageType, channel, id, sequenceId, timestamp, ...rest } = raw;
367
- raw.data = rest;
549
+ if (raw.type === "error") {
550
+ if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
551
+ if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
552
+ }
368
553
  }
369
554
  const message = raw;
370
- if (message.type === "pong") {
371
- this.handlePong(message.timestamp);
372
- this.dispatchMessage(message);
555
+ if (CONTROL_MESSAGE_TYPES.has(message.type)) {
556
+ if (message.type === "pong") this.handlePong(message.timestamp);
557
+ this.deliverMessage(message);
373
558
  return;
374
559
  }
375
- if ("id" in message && message.id && this.config.enableDeduplication) {
560
+ if ("id" in message && message.id) {
376
561
  const eventId = message.id;
377
- if (this.processedEventIds.has(eventId)) {
378
- this.duplicatesSkipped++;
379
- return;
380
- }
381
- this.processedEventIds.add(eventId);
382
- if (this.processedEventIds.size > this.config.maxDeduplicationSize) {
383
- const entriesToRemove = Math.floor(this.config.maxDeduplicationSize * .1);
384
- let removed = 0;
385
- for (const oldId of this.processedEventIds) {
386
- if (removed >= entriesToRemove) break;
387
- this.processedEventIds.delete(oldId);
388
- removed++;
562
+ if (this.config.enableDeduplication) {
563
+ if (this.processedEventIds.has(eventId)) {
564
+ this.duplicatesSkipped++;
565
+ return;
566
+ }
567
+ this.processedEventIds.add(eventId);
568
+ if (this.processedEventIds.size > this.config.maxDeduplicationSize) {
569
+ const entriesToRemove = Math.floor(this.config.maxDeduplicationSize * .1);
570
+ let removed = 0;
571
+ for (const oldId of this.processedEventIds) {
572
+ if (removed >= entriesToRemove) break;
573
+ this.processedEventIds.delete(oldId);
574
+ removed++;
575
+ }
389
576
  }
390
577
  }
391
578
  this.lastEventId = eventId;
392
579
  this.saveReplayState();
393
580
  }
394
- this.dispatchMessage(message);
581
+ this.deliverMessage(message);
395
582
  } catch {}
396
583
  }
397
584
  handlePong(timestamp) {
@@ -407,6 +594,7 @@ var SessionGatewayClient = class {
407
594
  }
408
595
  }
409
596
  dispatchMessage(message) {
597
+ if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") this.clearReplayState();
410
598
  if ("id" in message && message.id) {
411
599
  const callback = this.pendingCallbacks.get(message.id);
412
600
  if (callback) {
@@ -418,7 +606,7 @@ var SessionGatewayClient = class {
418
606
  }
419
607
  switch (message.type) {
420
608
  case "connection.established":
421
- this.handlers.onConnect?.(message.data.sessionId);
609
+ this.handleConnectionEstablished(message.data.sessionId);
422
610
  break;
423
611
  case "runtime.connected":
424
612
  this.handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
@@ -429,13 +617,6 @@ var SessionGatewayClient = class {
429
617
  case "runtime.not_found":
430
618
  this.handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
431
619
  break;
432
- case "container.ready": {
433
- const data = message.data;
434
- const id = data.sandboxId ?? data.sidecarId;
435
- if (id) this.handlers.onContainerReady?.(id);
436
- else this.handlers.onError?.("container.ready event received without sandboxId", "invalid_payload");
437
- break;
438
- }
439
620
  case "runtime.ready":
440
621
  this.handlers.onRuntimeReady?.(message.data);
441
622
  break;
@@ -448,7 +629,7 @@ var SessionGatewayClient = class {
448
629
  case "agent.event":
449
630
  this.eventsReceived++;
450
631
  this.trackExecutionContext(message.data);
451
- this.handlers.onAgentEvent?.(message.channel, message.data, message.sequenceId);
632
+ this.handlers.onAgentEvent?.(message.channel, message.data, message.seq);
452
633
  break;
453
634
  case "replay.start":
454
635
  this.isReplaying = true;
@@ -470,8 +651,8 @@ var SessionGatewayClient = class {
470
651
  this.handlers.onError?.(message.message, message.code);
471
652
  break;
472
653
  case "token.expiring":
473
- this.handlers.onTokenExpiring?.(message.data.secondsRemaining);
474
- this.handleTokenExpiring();
654
+ invokeClientCallback("onTokenExpiring", () => this.handlers.onTokenExpiring?.(message.data.secondsRemaining), this.handlers.onError);
655
+ this.tokenRefresher.refresh();
475
656
  break;
476
657
  case "token.expired":
477
658
  this.handlers.onTokenExpired?.();
@@ -481,6 +662,10 @@ var SessionGatewayClient = class {
481
662
  break;
482
663
  }
483
664
  }
665
+ deliverMessage(message) {
666
+ invokeClientCallback("message dispatch", () => this.dispatchMessage(message), this.handlers.onError);
667
+ invokeClientCallback("onMessage", () => this.handlers.onMessage?.(message), this.handlers.onError);
668
+ }
484
669
  trackExecutionContext(data) {
485
670
  if (typeof data !== "object" || data === null) return;
486
671
  const eventData = data;
@@ -493,25 +678,15 @@ var SessionGatewayClient = class {
493
678
  this.saveReplayState();
494
679
  }
495
680
  }
496
- async handleTokenExpiring() {
497
- if (!this.config.onTokenRefresh || this.isRefreshingToken) return;
498
- this.isRefreshingToken = true;
499
- try {
500
- const result = await this.config.onTokenRefresh();
501
- this.updateToken(result.token);
502
- } catch (error) {
503
- this.handlers.onError?.(`Token refresh failed: ${error instanceof Error ? error.message : String(error)}`, "TOKEN_REFRESH_FAILED");
504
- } finally {
505
- this.isRefreshingToken = false;
506
- }
507
- }
508
681
  send(message) {
509
682
  if (this.ws?.readyState === WebSocket.OPEN) {
510
683
  this.ws.send(JSON.stringify(message));
511
684
  this.messagesSent++;
512
685
  }
513
686
  }
514
- sendWithResponse(message) {
687
+ async sendWithResponse(message) {
688
+ if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
689
+ if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before request could be sent");
515
690
  return new Promise((resolve, reject) => {
516
691
  const id = `msg_${++this.messageIdCounter}`;
517
692
  this.pendingCallbacks.set(id, {
@@ -530,14 +705,20 @@ var SessionGatewayClient = class {
530
705
  });
531
706
  });
532
707
  }
708
+ waitForConnectionEstablished() {
709
+ if (this.connectionEstablishedForSocket && this.isConnected()) return Promise.resolve();
710
+ if (this.state === "disconnected") return Promise.reject(/* @__PURE__ */ new Error("Client is not connected"));
711
+ return this.connectionWaiters.wait();
712
+ }
533
713
  restoreSubscriptions() {
534
714
  const channels = this.config.channels;
535
715
  const replayOptions = {};
536
716
  if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
537
717
  if (this.currentExecutionId) replayOptions.executionId = this.currentExecutionId;
538
718
  if (this.currentSessionId) replayOptions.sessionId = this.currentSessionId;
539
- const hasReplayState = Object.keys(replayOptions).length > 0;
540
- if (hasReplayState) {
719
+ const hasReplayCursor = this.lastEventId !== null;
720
+ if (channels.length === 0 && !hasReplayCursor) return;
721
+ if (hasReplayCursor) {
541
722
  this.isReplaying = true;
542
723
  this.replayProgress = {
543
724
  total: 0,
@@ -547,7 +728,7 @@ var SessionGatewayClient = class {
547
728
  this.send({
548
729
  type: "subscribe",
549
730
  channels,
550
- ...hasReplayState ? { replayOptions } : {}
731
+ ...hasReplayCursor ? { replayOptions } : {}
551
732
  });
552
733
  }
553
734
  startPingInterval() {
@@ -603,7 +784,7 @@ var SessionGatewayClient = class {
603
784
  const jitter = delay * .3 * (Math.random() * 2 - 1);
604
785
  this.reconnectTimer = setTimeout(() => {
605
786
  this.reconnectTimer = null;
606
- this.connect();
787
+ if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
607
788
  }, delay + jitter);
608
789
  }
609
790
  cleanup() {
@@ -637,7 +818,7 @@ var SessionGatewayClient = class {
637
818
  ...this.connectionMetrics,
638
819
  quality
639
820
  };
640
- this.handlers.onMetricsChange?.(this.connectionMetrics);
821
+ invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
641
822
  }
642
823
  }
643
824
  trackReconnection() {
@@ -651,22 +832,17 @@ var SessionGatewayClient = class {
651
832
  this.updateConnectionQuality();
652
833
  }
653
834
  loadReplayState() {
654
- if (!this.config.enableReplayPersistence) return;
655
- const prefix = this.config.replayStorageKeyPrefix;
656
- try {
657
- this.lastEventId = this.config.replayStorage.getItem(prefix + STORAGE_KEYS.lastEventId);
658
- this.currentExecutionId = this.config.replayStorage.getItem(prefix + STORAGE_KEYS.executionId);
659
- this.currentSessionId = this.config.replayStorage.getItem(prefix + STORAGE_KEYS.sessionId);
660
- } catch {}
835
+ const state = this.replayStateStore.load();
836
+ this.lastEventId = state.lastEventId;
837
+ this.currentExecutionId = state.executionId;
838
+ this.currentSessionId = state.sessionId;
661
839
  }
662
840
  saveReplayState() {
663
- if (!this.config.enableReplayPersistence) return;
664
- const prefix = this.config.replayStorageKeyPrefix;
665
- try {
666
- if (this.lastEventId) this.config.replayStorage.setItem(prefix + STORAGE_KEYS.lastEventId, this.lastEventId);
667
- if (this.currentExecutionId) this.config.replayStorage.setItem(prefix + STORAGE_KEYS.executionId, this.currentExecutionId);
668
- if (this.currentSessionId) this.config.replayStorage.setItem(prefix + STORAGE_KEYS.sessionId, this.currentSessionId);
669
- } catch {}
841
+ this.replayStateStore.save({
842
+ lastEventId: this.lastEventId,
843
+ executionId: this.currentExecutionId,
844
+ sessionId: this.currentSessionId
845
+ });
670
846
  }
671
847
  };
672
848
  //#endregion