@tangle-network/sandbox 0.68.6 → 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-cOkMrS6h.d.ts → client-BG1kKuT7.d.ts} +15 -15
  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-BBpr9Ogx.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 +6 -6
  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,37 +1,8 @@
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
- }
11
- }
12
- //#endregion
1
+ import { n as combineAbortSignals } from "../abort-signal-BKVZNJul.js";
2
+ import "../sidecar-proxy-error-B2Hxt41g.js";
3
+ import { t as parseSSEStream } from "../sse-parser-CUfurwcm.js";
13
4
  //#region ../../../packages/runtime-contracts/dist/session-gateway.js
14
5
  /**
15
- * Shared session-gateway protocol and connection metrics
16
- *
17
- * Browser-safe wire contracts. SDK-specific extensions and connection defaults
18
- * remain with their clients; this module imports no runtime or Node services.
19
- */
20
- /**
21
- * Default connection metrics.
22
- */
23
- function createConnectionMetrics() {
24
- return {
25
- lastPingLatencyMs: null,
26
- avgPingLatencyMs: null,
27
- missedPongCount: 0,
28
- reconnectCount: 0,
29
- lastPongAt: null,
30
- lastReconnectAt: null,
31
- quality: "disconnected"
32
- };
33
- }
34
- /**
35
6
  * Calculate connection quality from metrics.
36
7
  */
37
8
  function calculateConnectionQuality(metrics, isConnected) {
@@ -45,989 +16,766 @@ function calculateConnectionQuality(metrics, isConnected) {
45
16
  return "good";
46
17
  }
47
18
  //#endregion
48
- //#region src/session-gateway/core-types.ts
49
- /** Browser-safe session gateway contracts for both SDK clients. */
50
- const INITIAL_METRICS = createConnectionMetrics();
51
- //#endregion
52
- //#region src/session-gateway/connection-metrics.ts
53
- /** Connection quality metrics derived from ping latency and missed pongs. */
54
- var ConnectionMetricsTracker = class {
55
- metrics;
56
- latencyHistory = [];
57
- constructor(initialMetrics, latencyHistorySize, isConnected, onChange) {
58
- this.initialMetrics = initialMetrics;
59
- this.latencyHistorySize = latencyHistorySize;
60
- this.isConnected = isConnected;
61
- this.onChange = onChange;
62
- this.metrics = { ...initialMetrics };
63
- }
64
- get quality() {
65
- return this.metrics.quality;
66
- }
67
- snapshot() {
68
- return { ...this.metrics };
69
- }
70
- reset() {
71
- this.latencyHistory = [];
72
- this.metrics = { ...this.initialMetrics };
73
- this.onChange(this.metrics);
74
- }
75
- recordMissedPongs(missedPongCount) {
76
- this.metrics = {
77
- ...this.metrics,
78
- missedPongCount
79
- };
80
- this.refreshQuality();
81
- }
82
- recordLatency(latency, pongTime, missedPongCount) {
83
- this.latencyHistory.push(latency);
84
- if (this.latencyHistory.length > this.latencyHistorySize) this.latencyHistory.shift();
85
- const avgLatency = this.latencyHistory.length > 0 ? this.latencyHistory.reduce((a, b) => a + b, 0) / this.latencyHistory.length : null;
86
- this.metrics = {
87
- ...this.metrics,
88
- lastPingLatencyMs: latency,
89
- avgPingLatencyMs: avgLatency,
90
- missedPongCount,
91
- lastPongAt: pongTime
92
- };
93
- this.refreshQuality();
94
- }
95
- trackReconnection() {
96
- const now = Date.now();
97
- this.metrics = {
98
- ...this.metrics,
99
- reconnectCount: this.metrics.reconnectCount + 1,
100
- lastReconnectAt: now
101
- };
102
- this.latencyHistory = [];
103
- this.refreshQuality();
104
- }
105
- refreshQuality() {
106
- const quality = calculateConnectionQuality(this.metrics, this.isConnected());
107
- if (this.metrics.quality !== quality) {
108
- this.metrics = {
109
- ...this.metrics,
110
- quality
111
- };
112
- this.onChange(this.metrics);
113
- }
114
- }
115
- };
116
- //#endregion
117
- //#region src/session-gateway/connection-waiters.ts
118
- var ConnectionWaiters = class {
119
- /** True once the current socket has reported `connection.established`. */
120
- established = false;
121
- waiters = /* @__PURE__ */ new Set();
122
- establishmentTimeout = null;
123
- constructor(timeoutMs) {
124
- this.timeoutMs = timeoutMs;
125
- }
126
- start(onTimeout) {
127
- this.clear();
128
- this.establishmentTimeout = setTimeout(() => {
129
- this.establishmentTimeout = null;
130
- const error = /* @__PURE__ */ new Error(`Connection establishment timed out after ${this.timeoutMs}ms`);
131
- this.rejectAll(error);
132
- onTimeout(error);
133
- }, this.timeoutMs);
134
- }
135
- clear() {
136
- if (this.establishmentTimeout !== null) {
137
- clearTimeout(this.establishmentTimeout);
138
- this.establishmentTimeout = null;
139
- }
140
- }
141
- wait() {
142
- return new Promise((resolve, reject) => {
143
- this.waiters.add({
144
- resolve,
145
- reject
146
- });
147
- });
148
- }
149
- /** Wait for the socket to be established, or fail with `closedMessage`. */
150
- async awaitEstablished(getState, closedMessage) {
151
- const ready = () => this.established && getState() === "connected";
152
- if (!ready()) {
153
- if (getState() === "disconnected") throw new Error("Client is not connected");
154
- await this.wait();
155
- }
156
- if (!ready()) throw new Error(closedMessage);
157
- }
158
- resolveAll() {
159
- this.clear();
160
- for (const waiter of this.waiters) waiter.resolve();
161
- this.waiters.clear();
162
- }
163
- rejectAll(error) {
164
- this.clear();
165
- for (const waiter of this.waiters) waiter.reject(error);
166
- this.waiters.clear();
167
- }
168
- };
169
- //#endregion
170
- //#region src/session-gateway/heartbeat.ts
171
- const PONG_TIMEOUT_CLOSE_CODE = 4e3;
172
- const PONG_TIMEOUT_CLOSE_REASON = "Pong timeout - connection unresponsive";
173
- /** Sends pings on an interval and closes a socket that stops answering. */
174
- var Heartbeat = class {
175
- lastPingAt = null;
176
- lastPongAt = null;
177
- lastPingSentAt = null;
178
- missedPongCount = 0;
179
- pingInterval = null;
180
- pongTimeout = null;
181
- constructor(policy, metrics, socket, send) {
182
- this.policy = policy;
183
- this.metrics = metrics;
184
- this.socket = socket;
185
- this.send = send;
186
- }
187
- start() {
188
- this.stopInterval();
189
- this.pingInterval = setInterval(() => {
190
- this.sendPing();
191
- }, this.policy.pingIntervalMs);
192
- }
193
- stop() {
194
- this.stopInterval();
195
- this.clearPongTimeout();
196
- }
197
- resetMissedPongs() {
198
- this.missedPongCount = 0;
199
- }
200
- handlePong(timestamp) {
201
- const now = Date.now();
202
- this.lastPongAt = timestamp;
203
- this.missedPongCount = 0;
204
- this.clearPongTimeout();
205
- if (this.lastPingSentAt) this.metrics.recordLatency(now - this.lastPingSentAt, now, this.missedPongCount);
206
- }
207
- stopInterval() {
208
- if (this.pingInterval) {
209
- clearInterval(this.pingInterval);
210
- this.pingInterval = null;
211
- }
212
- }
213
- clearPongTimeout() {
214
- if (this.pongTimeout) {
215
- clearTimeout(this.pongTimeout);
216
- this.pongTimeout = null;
217
- }
218
- }
219
- /** Count a missed pong. Returns true when the socket was closed for it. */
220
- recordMissedPong() {
221
- this.missedPongCount++;
222
- this.metrics.recordMissedPongs(this.missedPongCount);
223
- if (this.missedPongCount >= this.policy.maxMissedPongs) {
224
- this.socket()?.close(PONG_TIMEOUT_CLOSE_CODE, PONG_TIMEOUT_CLOSE_REASON);
225
- return true;
226
- }
227
- return false;
228
- }
229
- sendPing() {
230
- if (this.socket()?.readyState !== WebSocket.OPEN) return;
231
- const timeSinceLastPong = this.lastPongAt ? Date.now() - this.lastPongAt : 0;
232
- if (this.lastPongAt && timeSinceLastPong > this.policy.pongTimeoutMs && this.recordMissedPong()) return;
233
- this.lastPingAt = Date.now();
234
- this.lastPingSentAt = Date.now();
235
- this.send({ type: "ping" });
236
- this.pongTimeout = setTimeout(() => {
237
- this.recordMissedPong();
238
- }, this.policy.pongTimeoutMs);
239
- }
240
- };
241
- //#endregion
242
- //#region src/session-gateway/message-dispatch.ts
19
+ //#region src/session-gateway/types.ts
243
20
  /**
244
- * Parse a wire frame into a server message. Reports a frame with no message
245
- * type through `onError` and returns null; throws on invalid JSON.
21
+ * The contract of `SessionGatewayClient`, the browser-safe client for one
22
+ * agent session's event stream.
23
+ *
24
+ * The client reads `GET {runtimeUrl}/agents/events?sessionId=…` on the
25
+ * sandbox's cell edge. Connection state and quality policy come from
26
+ * runtime-contracts; stream-specific contracts live here.
246
27
  */
247
- function parseServerFrame(data, handlers) {
248
- const raw = JSON.parse(data);
249
- if (typeof raw.type !== "string") {
250
- invokeClientCallback("onError", () => handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
251
- return null;
252
- }
253
- if (raw.data && typeof raw.data === "object") {
254
- const d = raw.data;
255
- if (raw.type === "error") {
256
- if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
257
- if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
258
- }
259
- }
260
- return raw;
261
- }
262
- /** Dispatch a message to client state, then to the catch-all `onMessage`. */
263
- function deliverServerMessage(message, targets) {
264
- const { handlers } = targets;
265
- invokeClientCallback("message dispatch", () => dispatchServerMessage(message, targets), handlers.onError);
266
- invokeClientCallback("onMessage", () => handlers.onMessage?.(message), handlers.onError);
28
+ function createSessionStreamConnectionMetrics() {
29
+ return {
30
+ lastAttachLatencyMs: null,
31
+ avgAttachLatencyMs: null,
32
+ silentDropCount: 0,
33
+ reconnectCount: 0,
34
+ lastFrameAt: null,
35
+ lastReconnectAt: null,
36
+ quality: "disconnected"
37
+ };
267
38
  }
268
- /** Apply one validated server message to client state and its handlers. */
269
- function dispatchServerMessage(message, targets) {
270
- const { handlers, replay } = targets;
271
- if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") replay.clear();
272
- if (targets.requests.settle(message)) return;
273
- switch (message.type) {
274
- case "connection.established":
275
- targets.onConnectionEstablished(message.data.sessionId);
276
- break;
277
- case "runtime.connected":
278
- handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
279
- break;
280
- case "runtime.disconnected":
281
- handlers.onRuntimeDisconnected?.(message.data.sandboxId, message.data.error);
282
- break;
283
- case "runtime.unavailable":
284
- handlers.onRuntimeUnavailable?.(message.data);
285
- break;
286
- case "runtime.not_found":
287
- handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
288
- break;
289
- case "runtime.ready":
290
- handlers.onRuntimeReady?.(message.data);
291
- break;
292
- case "port.opened":
293
- handlers.onPortOpened?.(message.data.port, message.data.protocol, message.data.processName);
294
- break;
295
- case "port.closed":
296
- handlers.onPortClosed?.(message.data.port);
297
- break;
298
- case "agent.event":
299
- targets.onAgentEvent(message.data);
300
- handlers.onAgentEvent?.(message.channel, message.data, message.seq);
301
- break;
302
- case "replay.start":
303
- replay.start(message.total);
304
- handlers.onReplayStart?.(message.total);
305
- break;
306
- case "replay.progress": {
307
- const total = replay.advance(message.received);
308
- handlers.onReplayProgress?.(message.received, total);
309
- break;
310
- }
311
- case "replay.complete":
312
- replay.complete();
313
- handlers.onReplayComplete?.(message.total);
314
- break;
315
- case "replay.truncated":
316
- handlers.onReplayTruncated?.(message.data);
317
- break;
318
- case "stream.gap":
319
- handlers.onStreamGap?.(message.data);
320
- break;
321
- case "stream.dead":
322
- handlers.onStreamDead?.(message.data);
323
- break;
324
- case "error":
325
- handlers.onError?.(message.message, message.code);
326
- break;
327
- case "token.expiring":
328
- invokeClientCallback("onTokenExpiring", () => handlers.onTokenExpiring?.(message.data.secondsRemaining), handlers.onError);
329
- targets.tokenRefresher.refresh();
330
- break;
331
- case "token.expired":
332
- handlers.onTokenExpired?.();
333
- break;
334
- case "backpressure.warning":
335
- handlers.onBackpressureWarning?.(message.data.droppedCount, message.data.since, message.data.totalDropped);
336
- break;
337
- }
39
+ /** A fresh metrics object; never shared between clients. */
40
+ const INITIAL_METRICS = createSessionStreamConnectionMetrics();
41
+ /** Adapt stream measurements to the shared connection-quality policy. */
42
+ function calculateSessionStreamConnectionQuality(metrics, isConnected) {
43
+ return calculateConnectionQuality({
44
+ lastPingLatencyMs: metrics.lastAttachLatencyMs,
45
+ avgPingLatencyMs: metrics.avgAttachLatencyMs,
46
+ missedPongCount: metrics.silentDropCount,
47
+ lastPongAt: metrics.lastFrameAt,
48
+ reconnectCount: metrics.reconnectCount,
49
+ lastReconnectAt: metrics.lastReconnectAt,
50
+ quality: metrics.quality
51
+ }, isConnected);
338
52
  }
339
53
  //#endregion
340
- //#region src/session-gateway/pending-requests.ts
341
- const REQUEST_TIMEOUT_MS = 1e4;
342
- /** Correlates request messages with the server replies that carry their id. */
343
- var PendingRequests = class {
344
- callbacks = /* @__PURE__ */ new Map();
345
- idCounter = 0;
346
- /** Assign a correlation id, send via `send`, and await the reply. */
347
- request(send) {
348
- return new Promise((resolve, reject) => {
349
- const id = `msg_${++this.idCounter}`;
350
- this.callbacks.set(id, {
351
- resolve,
352
- reject
353
- });
354
- setTimeout(() => {
355
- if (this.callbacks.has(id)) {
356
- this.callbacks.delete(id);
357
- reject(/* @__PURE__ */ new Error("Request timeout"));
358
- }
359
- }, REQUEST_TIMEOUT_MS);
360
- send(id);
361
- });
362
- }
363
- /** Settle the request a reply answers. Returns false when none is waiting. */
364
- settle(message) {
365
- if (!("id" in message && message.id)) return false;
366
- const callback = this.callbacks.get(message.id);
367
- if (!callback) return false;
368
- this.callbacks.delete(message.id);
369
- if (message.type === "error") callback.reject(new Error(message.message));
370
- else callback.resolve("data" in message ? message.data : void 0);
371
- return true;
372
- }
373
- rejectAll(reason) {
374
- for (const [id, callback] of this.callbacks) {
375
- callback.reject(new Error(reason));
376
- this.callbacks.delete(id);
377
- }
378
- }
379
- };
380
- //#endregion
381
- //#region src/session-gateway/protocol.ts
382
- const DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG = {
383
- transport: "websocket",
384
- channels: [],
54
+ //#region src/session-gateway/client.ts
55
+ /**
56
+ * SessionGatewayClient: one agent session's events, read from the sandbox's
57
+ * cell edge, so no control-plane process holds a socket for them.
58
+ *
59
+ * The client reads `GET {runtimeUrl}/agents/events`. While the session runs a
60
+ * turn, it reads that turn's execution stream (`executionId`): every frame
61
+ * comes from the sidecar's event store with its store id, and an attach
62
+ * resumes after the last delivered id (`since`), so a drop loses nothing and
63
+ * repeats nothing. Between turns it reads the session stream, which carries
64
+ * the session's container events (ports, sidecar, Hub); a turn frame there
65
+ * makes the client move to that turn's execution stream from its first
66
+ * event. Each attach first asks the runtime which turn is running
67
+ * (`GET /agents/sessions/{id}`).
68
+ *
69
+ * Browser-safe: global `fetch` and streams only.
70
+ */
71
+ const DEFAULTS = {
385
72
  autoReconnect: true,
386
73
  maxReconnectAttempts: 10,
387
74
  initialReconnectDelayMs: 1e3,
388
75
  maxReconnectDelayMs: 3e4,
389
- pingIntervalMs: 3e4,
390
- pongTimeoutMs: 1e4,
391
- maxMissedPongs: 2,
76
+ idleTimeoutMs: 75e3,
392
77
  enableDeduplication: true,
393
78
  maxDeduplicationSize: 1e3,
394
- enableReplayPersistence: false,
395
- replayStorageKeyPrefix: "session_gateway_",
396
79
  latencyHistorySize: 10,
397
80
  connectionEstablishmentTimeoutMs: 1e4
398
81
  };
399
- const CONTROL_MESSAGE_TYPES = new Set([
400
- "connection.established",
401
- "subscribed",
402
- "unsubscribed",
403
- "pong",
404
- "replay.start",
405
- "replay.progress",
406
- "replay.complete",
407
- "replay.truncated",
408
- "error",
409
- "token.expiring",
410
- "token.expired",
411
- "backpressure.warning",
412
- "terminal.input.error",
413
- "heartbeat"
414
- ]);
415
- function acceptedSubscriptionChannels(acknowledgement) {
416
- if (acknowledgement.denied?.length) {
417
- const reasons = acknowledgement.denied.map(({ channel, reason }) => `${channel}: ${reason}`).join(", ");
418
- throw new Error(`Subscription denied (${reasons})`);
419
- }
420
- return acknowledgement.channels;
421
- }
422
- /** Fill every option the caller left unset with its documented default. */
423
- function resolveClientConfig(config) {
424
- const defaults = DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG;
425
- return {
426
- url: config.url,
427
- sessionId: config.sessionId,
428
- token: config.token,
429
- transport: config.transport ?? defaults.transport,
430
- channels: config.channels ?? defaults.channels,
431
- autoReconnect: config.autoReconnect ?? defaults.autoReconnect,
432
- maxReconnectAttempts: config.maxReconnectAttempts ?? defaults.maxReconnectAttempts,
433
- initialReconnectDelayMs: config.initialReconnectDelayMs ?? defaults.initialReconnectDelayMs,
434
- maxReconnectDelayMs: config.maxReconnectDelayMs ?? defaults.maxReconnectDelayMs,
435
- pingIntervalMs: config.pingIntervalMs ?? defaults.pingIntervalMs,
436
- pongTimeoutMs: config.pongTimeoutMs ?? defaults.pongTimeoutMs,
437
- maxMissedPongs: config.maxMissedPongs ?? defaults.maxMissedPongs,
438
- enableDeduplication: config.enableDeduplication ?? defaults.enableDeduplication,
439
- maxDeduplicationSize: config.maxDeduplicationSize ?? defaults.maxDeduplicationSize,
440
- enableReplayPersistence: config.enableReplayPersistence ?? defaults.enableReplayPersistence,
441
- replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? defaults.replayStorageKeyPrefix,
442
- latencyHistorySize: config.latencyHistorySize ?? defaults.latencyHistorySize,
443
- connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? defaults.connectionEstablishmentTimeoutMs
444
- };
445
- }
446
- //#endregion
447
- //#region src/session-gateway/reconnect-scheduler.ts
448
- /** Decides whether to reconnect and schedules attempts with jittered backoff. */
449
- var ReconnectScheduler = class {
450
- hasConnectedBefore = false;
451
- attempts = 0;
452
- timer = null;
453
- constructor(policy) {
454
- this.policy = policy;
455
- }
456
- canRetry() {
457
- return this.policy.autoReconnect && this.attempts < this.policy.maxReconnectAttempts;
458
- }
459
- schedule(reconnect) {
460
- if (this.timer) return;
461
- this.attempts++;
462
- const delay = Math.min(this.policy.initialReconnectDelayMs * 2 ** (this.attempts - 1), this.policy.maxReconnectDelayMs);
463
- const jitter = delay * .3 * (Math.random() * 2 - 1);
464
- this.timer = setTimeout(() => {
465
- this.timer = null;
466
- reconnect();
467
- }, delay + jitter);
468
- }
469
- cancel() {
470
- if (this.timer) {
471
- clearTimeout(this.timer);
472
- this.timer = null;
473
- }
474
- }
475
- };
476
- //#endregion
477
- //#region src/session-gateway/replay-cursor.ts
82
+ /** How long the attach waits for the runtime to name its running turn. */
83
+ const SESSION_READ_TIMEOUT_MS = 1e4;
84
+ /** How long before `exp` the client asks for a new token. */
85
+ const TOKEN_REFRESH_LEAD_MS = 6e4;
478
86
  /**
479
- * Replay position of one gateway session: the last delivered event, the
480
- * execution and session being followed, replay progress, and the set of event
481
- * IDs already delivered. Position changes are persisted through the store.
87
+ * After a check finds no running turn, session frames pass without another
88
+ * check for this long, so a quiet session cannot make the client re-attach
89
+ * on every frame.
482
90
  */
483
- var ReplayCursor = class {
484
- lastEventId = null;
485
- duplicatesSkipped = 0;
486
- executionId = null;
487
- sessionId = null;
488
- isReplaying = false;
489
- progress = {
490
- total: 0,
491
- received: 0
492
- };
493
- processedEventIds = /* @__PURE__ */ new Set();
494
- constructor(store, dedup) {
495
- this.store = store;
496
- this.dedup = dedup;
497
- const state = this.store.load();
498
- this.lastEventId = state.lastEventId;
499
- this.executionId = state.executionId;
500
- this.sessionId = state.sessionId;
501
- }
502
- setContext(sessionId, executionId) {
503
- this.sessionId = sessionId;
504
- if (executionId) this.executionId = executionId;
505
- this.save();
506
- }
507
- clear() {
508
- this.lastEventId = null;
509
- this.executionId = null;
510
- this.sessionId = null;
511
- this.isReplaying = false;
512
- this.progress = {
513
- total: 0,
514
- received: 0
515
- };
516
- this.processedEventIds.clear();
517
- this.duplicatesSkipped = 0;
518
- this.store.clear();
519
- }
520
- state() {
521
- return {
522
- isReplaying: this.isReplaying,
523
- progress: { ...this.progress }
524
- };
525
- }
526
- /** Follow the execution and session named by an agent event payload. */
527
- trackExecution(raw) {
528
- if (typeof raw !== "object" || raw === null) return;
529
- const eventData = raw;
530
- if (eventData.executionId) {
531
- this.executionId = eventData.executionId;
532
- this.save();
533
- }
534
- if (eventData.type === "execution.started" && eventData.sessionId) {
535
- this.sessionId = eventData.sessionId;
536
- this.save();
537
- }
538
- }
539
- /**
540
- * Record a delivered event ID as the new cursor. Returns false when
541
- * deduplication is on and the event was already delivered.
542
- */
543
- accept(eventId) {
544
- if (this.dedup.enabled) {
545
- if (this.processedEventIds.has(eventId)) {
546
- this.duplicatesSkipped++;
547
- return false;
548
- }
549
- this.processedEventIds.add(eventId);
550
- if (this.processedEventIds.size > this.dedup.maxSize) {
551
- const entriesToRemove = Math.floor(this.dedup.maxSize * .1);
552
- let removed = 0;
553
- for (const oldId of this.processedEventIds) {
554
- if (removed >= entriesToRemove) break;
555
- this.processedEventIds.delete(oldId);
556
- removed++;
557
- }
558
- }
559
- }
560
- this.lastEventId = eventId;
561
- this.save();
562
- return true;
563
- }
564
- /**
565
- * The subscribe frame sent after a connection is established, asking the
566
- * server to resume from this cursor when there is one. Null when there is
567
- * nothing to subscribe to.
568
- */
569
- subscribeMessage(channels) {
570
- const replayOptions = {};
571
- if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
572
- if (this.executionId) replayOptions.executionId = this.executionId;
573
- if (this.sessionId) replayOptions.sessionId = this.sessionId;
574
- const hasReplayCursor = this.lastEventId !== null;
575
- if (channels.length === 0 && !hasReplayCursor) return null;
576
- if (hasReplayCursor) {
577
- this.isReplaying = true;
578
- this.progress = {
579
- total: 0,
580
- received: 0
581
- };
582
- }
583
- return {
584
- type: "subscribe",
585
- channels,
586
- ...hasReplayCursor ? { replayOptions } : {}
587
- };
588
- }
589
- start(total) {
590
- this.isReplaying = true;
591
- this.progress = {
592
- total,
593
- received: 0
594
- };
595
- }
596
- advance(received) {
597
- this.progress.received = received;
598
- return this.progress.total;
599
- }
600
- complete() {
601
- this.isReplaying = false;
602
- }
603
- save() {
604
- this.store.save({
605
- lastEventId: this.lastEventId,
606
- executionId: this.executionId,
607
- sessionId: this.sessionId
608
- });
609
- }
91
+ const NO_TURN_QUIET_MS = 2e3;
92
+ /** `onDisconnect` codes. HTTP refusals report `4000 + status`. */
93
+ const CLOSE = {
94
+ ENDED: 1e3,
95
+ NETWORK: 1006,
96
+ SILENT: 4002,
97
+ ESTABLISH_TIMEOUT: 4008
610
98
  };
611
- //#endregion
612
- //#region src/session-gateway/replay-storage.ts
613
- const STORAGE_KEYS = {
614
- lastEventId: "last_event_id",
615
- executionId: "execution_id",
616
- sessionId: "session_id"
617
- };
618
- var MemoryReplayStorage = class {
619
- store = /* @__PURE__ */ new Map();
620
- getItem(key) {
621
- return this.store.get(key) ?? null;
622
- }
623
- setItem(key, value) {
624
- this.store.set(key, value);
625
- }
626
- removeItem(key) {
627
- this.store.delete(key);
628
- }
629
- };
630
- function resolveReplayStorage(configured) {
631
- if (configured) return configured;
632
- if (typeof globalThis !== "undefined" && "localStorage" in globalThis) try {
633
- const testKey = "__session_gateway_storage_test__";
634
- const previous = localStorage.getItem(testKey);
635
- try {
636
- localStorage.setItem(testKey, testKey);
637
- localStorage.removeItem(testKey);
638
- } finally {
639
- if (previous !== null) localStorage.setItem(testKey, previous);
640
- }
641
- return localStorage;
642
- } catch {
643
- return new MemoryReplayStorage();
644
- }
645
- return new MemoryReplayStorage();
646
- }
647
- function endpointIdentity(rawUrl) {
648
- const url = new URL(rawUrl);
649
- url.username = "";
650
- url.password = "";
651
- url.hash = "";
652
- 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);
653
- url.searchParams.sort();
654
- return url.toString();
99
+ /** Edge route misses (apps/edge-router/src/server.ts): no route to the box. */
100
+ const EDGE_ROUTE_MISSES = new Set([
101
+ "unknown_host",
102
+ "outside_zone",
103
+ "invalid_host",
104
+ "no_host_header"
105
+ ]);
106
+ /** Host-agent refusals for a box that is not on its host. */
107
+ const HOST_ABSENT = new Set(["NOT_MANAGED", "NO_IP"]);
108
+ const REPLAY_START = "history.replay.start";
109
+ const REPLAY_END = "history.replay.end";
110
+ /** Transport terminals. An execution's store can hold more than one: a
111
+ * run-lane `done`, then the session message's `message.complete`,
112
+ * `session.idle` and its own `done`. */
113
+ const TURN_TERMINALS = new Set(["done", "error"]);
114
+ /** After a terminal, the turn has ended once its store stays quiet this long. */
115
+ const TURN_END_QUIET_MS = 1500;
116
+ /**
117
+ * Session-stream frames that belong to no turn: the stream's own frames and
118
+ * the container events the sidecar forwards to every session stream
119
+ * (apps/sidecar/src/routes/agents-events-frames.ts `isSystemEvent`).
120
+ */
121
+ function isSessionFrame(type) {
122
+ return type === "heartbeat" || type === "connection.established" || type.startsWith("port.") || type.startsWith("sidecar.") || type.startsWith("hub.") || type.startsWith("file.watcher.");
655
123
  }
656
- var ReplayStateStore = class {
657
- prefix;
658
- constructor(enabled, storage, keyPrefix, endpointUrl, sessionId) {
659
- this.enabled = enabled;
660
- this.storage = storage;
661
- this.prefix = `${keyPrefix}${encodeURIComponent(endpointIdentity(endpointUrl))}:${encodeURIComponent(sessionId)}:`;
662
- }
663
- load() {
664
- if (!this.enabled) return this.emptyState();
665
- try {
666
- return {
667
- lastEventId: this.storage.getItem(this.prefix + STORAGE_KEYS.lastEventId),
668
- executionId: this.storage.getItem(this.prefix + STORAGE_KEYS.executionId),
669
- sessionId: this.storage.getItem(this.prefix + STORAGE_KEYS.sessionId)
670
- };
671
- } catch {
672
- return this.emptyState();
673
- }
674
- }
675
- save(state) {
676
- if (!this.enabled) return;
677
- try {
678
- if (state.lastEventId) this.storage.setItem(this.prefix + STORAGE_KEYS.lastEventId, state.lastEventId);
679
- if (state.executionId) this.storage.setItem(this.prefix + STORAGE_KEYS.executionId, state.executionId);
680
- if (state.sessionId) this.storage.setItem(this.prefix + STORAGE_KEYS.sessionId, state.sessionId);
681
- } catch {}
682
- }
683
- clear() {
684
- if (!this.enabled) return;
685
- try {
686
- this.storage.removeItem(this.prefix + STORAGE_KEYS.lastEventId);
687
- this.storage.removeItem(this.prefix + STORAGE_KEYS.executionId);
688
- this.storage.removeItem(this.prefix + STORAGE_KEYS.sessionId);
689
- } catch {}
690
- }
691
- emptyState() {
692
- return {
693
- lastEventId: null,
694
- executionId: null,
695
- sessionId: null
696
- };
697
- }
698
- };
699
- //#endregion
700
- //#region src/session-gateway/token-refresh.ts
701
- var TokenRefresher = class {
702
- refreshing = false;
703
- constructor(refreshToken, applyToken, onError) {
704
- this.refreshToken = refreshToken;
705
- this.applyToken = applyToken;
706
- this.onError = onError;
707
- }
708
- async refresh() {
709
- if (!this.refreshToken || this.refreshing) return;
710
- this.refreshing = true;
711
- try {
712
- const result = await this.refreshToken();
713
- if (!result.token.trim()) throw new Error("token refresh returned an empty token");
714
- this.applyToken(result.token);
715
- } catch (error) {
716
- invokeClientCallback("onError", () => this.onError?.(`Token refresh failed: ${error instanceof Error ? error.message : String(error)}`, "TOKEN_REFRESH_FAILED"), this.onError);
717
- } finally {
718
- this.refreshing = false;
719
- }
720
- }
721
- };
722
- //#endregion
723
- //#region src/session-gateway/core.ts
724
- const CONNECTION_ESTABLISHMENT_TIMEOUT_CODE = 4008;
725
- const CONNECTION_ERROR_CODE = 4009;
726
- const CONNECTION_ERROR_REASON = "WebSocket connection error";
727
- var SessionGatewayClientCore = class {
728
- ws = null;
124
+ var EstablishTimeout = class extends Error {};
125
+ var SessionGatewayClient = class {
126
+ #token;
729
127
  #config;
730
- #currentToken;
731
- handlers;
732
- state = "disconnected";
733
- counters = {
734
- connectedAt: null,
735
- messagesReceived: 0,
736
- messagesSent: 0,
737
- eventsReceived: 0
128
+ #handlers;
129
+ #fetch;
130
+ #refreshToken;
131
+ #channel;
132
+ #channels;
133
+ #state = "disconnected";
134
+ /** Bumped by every new attach and by `disconnect()`; stale work checks it. */
135
+ #generation = 0;
136
+ #stream = null;
137
+ #reconnectTimer;
138
+ #tokenTimer;
139
+ #refreshing = null;
140
+ #reconnectAttempts = 0;
141
+ #hasConnectedBefore = false;
142
+ /** The client is attached; switching streams keeps it attached. */
143
+ #open = false;
144
+ /** The client ended the current stream itself, to switch or replay. */
145
+ #reattachNow = false;
146
+ /** The followed turn and its last delivered store id. */
147
+ #cursor = {};
148
+ /** The last turn the client followed to its terminal; never followed again. */
149
+ #finished;
150
+ /** A session-stream frame held while the client checks for a running turn. */
151
+ #held = null;
152
+ #quietUntil = 0;
153
+ /** Ends the followed turn once its store goes quiet after a terminal. */
154
+ #turnEndTimer;
155
+ #backend;
156
+ #replay = {
157
+ isReplaying: false,
158
+ received: 0
738
159
  };
739
- connectionWaiters;
740
- #reconnects;
741
- #heartbeat;
742
- metrics;
743
- replayCursor;
744
- inbound;
745
- constructor(config, initialMetrics = INITIAL_METRICS) {
746
- if (!config.token.trim()) throw new Error("Session gateway token must not be empty");
747
- const replayStorage = resolveReplayStorage(config.replayStorage);
748
- this.#config = resolveClientConfig(config);
749
- this.handlers = config.handlers ?? {};
750
- this.connectionWaiters = new ConnectionWaiters(this.#config.connectionEstablishmentTimeoutMs);
751
- this.#reconnects = new ReconnectScheduler(this.#config);
752
- this.metrics = new ConnectionMetricsTracker(initialMetrics, this.#config.latencyHistorySize, () => this.state === "connected", (metrics) => invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(metrics), this.handlers.onError));
753
- this.#heartbeat = new Heartbeat(this.#config, this.metrics, () => this.ws, (message) => this.send(message));
754
- this.replayCursor = new ReplayCursor(new ReplayStateStore(this.#config.enableReplayPersistence, replayStorage, this.#config.replayStorageKeyPrefix, this.#config.url, this.#config.sessionId), {
755
- enabled: this.#config.enableDeduplication,
756
- maxSize: this.#config.maxDeduplicationSize
757
- });
758
- this.inbound = {
759
- handlers: this.handlers,
760
- replay: this.replayCursor,
761
- requests: new PendingRequests(),
762
- tokenRefresher: new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError),
763
- onConnectionEstablished: (sessionId) => this.handleConnectionEstablished(sessionId),
764
- onAgentEvent: (data) => {
765
- this.counters.eventsReceived++;
766
- this.replayCursor.trackExecution(data);
767
- }
160
+ #delivered = /* @__PURE__ */ new Set();
161
+ #duplicatesSkipped = 0;
162
+ #seq = 0;
163
+ #framesReceived = 0;
164
+ #eventsDelivered = 0;
165
+ #connectedAt = null;
166
+ #metrics = createSessionStreamConnectionMetrics();
167
+ #latencies = [];
168
+ constructor(config) {
169
+ this.#token = requireText(config.token, "token");
170
+ const sessionId = requireText(config.sessionId, "sessionId");
171
+ const url = runtimeBaseUrl(config.url);
172
+ const fetchImpl = config.fetch ?? globalThis.fetch;
173
+ if (typeof fetchImpl !== "function") throw new Error("SessionGatewayClient requires a fetch implementation");
174
+ this.#fetch = (input, init) => fetchImpl(input, init);
175
+ this.#config = {
176
+ url,
177
+ sessionId,
178
+ runtimeSessionId: config.runtimeSessionId?.trim() || sessionId,
179
+ sandboxId: config.sandboxId?.trim() || new URL(url).hostname.split(".")[0] || url,
180
+ autoReconnect: config.autoReconnect ?? DEFAULTS.autoReconnect,
181
+ maxReconnectAttempts: config.maxReconnectAttempts ?? DEFAULTS.maxReconnectAttempts,
182
+ initialReconnectDelayMs: config.initialReconnectDelayMs ?? DEFAULTS.initialReconnectDelayMs,
183
+ maxReconnectDelayMs: config.maxReconnectDelayMs ?? DEFAULTS.maxReconnectDelayMs,
184
+ idleTimeoutMs: config.idleTimeoutMs ?? DEFAULTS.idleTimeoutMs,
185
+ enableDeduplication: config.enableDeduplication ?? DEFAULTS.enableDeduplication,
186
+ maxDeduplicationSize: config.maxDeduplicationSize ?? DEFAULTS.maxDeduplicationSize,
187
+ latencyHistorySize: config.latencyHistorySize ?? DEFAULTS.latencyHistorySize,
188
+ connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? DEFAULTS.connectionEstablishmentTimeoutMs
768
189
  };
769
- this.#currentToken = config.token;
190
+ this.#handlers = config.handlers ?? {};
191
+ this.#refreshToken = config.onTokenRefresh;
192
+ this.#channel = `session:${sessionId}`;
193
+ this.#channels = new Set(config.channels ?? []);
770
194
  }
771
- /**
772
- * Connect to the session gateway.
773
- */
195
+ /** Open the stream; reattaches after drops until `disconnect()`. */
774
196
  connect() {
775
- if (this.state === "connected" || this.state === "connecting" || this.state === "reconnecting") return;
776
- const nextState = this.#reconnects.hasConnectedBefore ? "reconnecting" : "connecting";
777
- this.setState(nextState);
778
- if (this.getState() !== nextState) return;
779
- this.connectWebSocket();
780
- }
781
- connectWebSocket() {
782
- const url = new URL(this.#config.url);
783
- url.searchParams.set("token", this.#currentToken);
784
- this.connectionWaiters.established = false;
785
- const socket = new WebSocket(url.toString());
786
- this.ws = socket;
787
- const closeBeforeEstablishment = (code, reason) => {
788
- if (this.ws !== socket || this.connectionWaiters.established) return;
789
- try {
790
- socket.close(code, reason);
791
- } finally {
792
- this.handleClose(socket, code, reason);
793
- }
794
- };
795
- socket.onopen = () => {
796
- if (this.ws === socket) this.#heartbeat.resetMissedPongs();
797
- };
798
- socket.onclose = (event) => this.handleClose(socket, event.code, event.reason);
799
- socket.onerror = () => {
800
- if (this.ws !== socket) return;
801
- this.connectionWaiters.clear();
802
- closeBeforeEstablishment(CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
803
- };
804
- socket.onmessage = (event) => {
805
- if (this.ws === socket) this.handleMessage(event.data);
806
- };
807
- this.connectionWaiters.start((error) => {
808
- closeBeforeEstablishment(CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
809
- });
810
- }
811
- /**
812
- * Disconnect from the session gateway.
813
- */
197
+ if (this.#state !== "disconnected") return;
198
+ const next = this.#hasConnectedBefore ? "reconnecting" : "connecting";
199
+ this.#setState(next);
200
+ if (this.getState() !== next) return;
201
+ this.#scheduleTokenRefresh();
202
+ this.#attach(++this.#generation);
203
+ }
204
+ /** Close the stream and stop reattaching. */
814
205
  disconnect() {
815
- this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Client disconnected"));
816
- this.#heartbeat.stop();
817
- this.#reconnects.cancel();
818
- this.inbound.requests.rejectAll("Connection closed");
819
- this.connectionWaiters.established = false;
820
- const socket = this.ws;
821
- this.ws = null;
822
- if (socket) socket.close(1e3, "Client disconnect");
823
- this.setState("disconnected");
206
+ this.#generation++;
207
+ this.#stream?.abort();
208
+ this.#stream = null;
209
+ clearTimeout(this.#reconnectTimer);
210
+ clearTimeout(this.#tokenTimer);
211
+ clearTimeout(this.#turnEndTimer);
212
+ this.#reconnectTimer = void 0;
213
+ this.#tokenTimer = void 0;
214
+ this.#open = false;
215
+ this.#reattachNow = false;
216
+ this.#held = null;
217
+ this.#replay = {
218
+ isReplaying: false,
219
+ received: this.#replay.received
220
+ };
221
+ this.#setState("disconnected");
824
222
  }
825
- /**
826
- * Subscribe to additional channels.
827
- */
223
+ /** Deliver frames on these channel patterns (`*`, `session:*`, exact). */
828
224
  async subscribe(channels) {
829
- return acceptedSubscriptionChannels(await this.sendWithResponse({
830
- type: "subscribe",
831
- channels
832
- }));
225
+ for (const channel of channels) this.#channels.add(channel);
226
+ return channels;
833
227
  }
834
- /**
835
- * Unsubscribe from channels.
836
- */
837
228
  async unsubscribe(channels) {
838
- return (await this.sendWithResponse({
839
- type: "unsubscribe",
840
- channels
841
- })).channels;
842
- }
843
- /**
844
- * Send a ping and wait for pong.
845
- */
846
- async ping() {
847
- const start = Date.now();
848
- await this.sendWithResponse({ type: "ping" });
849
- return Date.now() - start;
850
- }
851
- replayImmediately(message) {
852
- this.send(message);
853
- }
854
- async replayAfterConnection(message) {
855
- await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before replay could be requested");
856
- this.send(message);
857
- }
858
- /**
859
- * Send terminal input via WebSocket.
860
- */
861
- sendTerminalInput(terminalId, input) {
862
- if (!this.isConnected()) return false;
863
- this.send({
864
- type: "terminal.input",
865
- data: {
866
- terminalId,
867
- input
868
- }
869
- });
870
- return true;
229
+ for (const channel of channels) this.#channels.delete(channel);
230
+ return channels;
871
231
  }
872
232
  /**
873
- * Set the current session/execution context for event tracking.
233
+ * Reattach now and re-read the running turn from its first event. With
234
+ * deduplication on, only frames this client has not delivered arrive.
874
235
  */
875
- setSessionContext(sessionId, executionId) {
876
- this.replayCursor.setContext(sessionId, executionId);
236
+ async replay() {
237
+ if (!this.#open || !this.#stream) return;
238
+ this.#cursor = { executionId: this.#cursor.executionId };
239
+ this.#reattachNow = true;
240
+ this.#stream.abort();
877
241
  }
878
- /**
879
- * Clear replay state (call when session ends).
880
- */
242
+ /** Forget delivered event-store ids, so a replay delivers them again. */
881
243
  clearReplayState() {
882
- this.replayCursor.clear();
244
+ this.#delivered.clear();
245
+ this.#duplicatesSkipped = 0;
246
+ this.#replay = {
247
+ isReplaying: false,
248
+ received: 0
249
+ };
883
250
  }
884
- /**
885
- * Get current replay state for UI indicators.
886
- */
887
251
  getReplayState() {
888
- return this.replayCursor.state();
252
+ return { ...this.#replay };
889
253
  }
890
- /**
891
- * Get connection statistics.
892
- */
893
254
  getStats() {
894
255
  return {
895
- state: this.state,
896
- connectedAt: this.counters.connectedAt,
897
- lastPingAt: this.#heartbeat.lastPingAt,
898
- lastPongAt: this.#heartbeat.lastPongAt,
899
- reconnectAttempts: this.#reconnects.attempts,
900
- messagesReceived: this.counters.messagesReceived,
901
- messagesSent: this.counters.messagesSent,
902
- eventsReceived: this.counters.eventsReceived,
903
- duplicatesSkipped: this.replayCursor.duplicatesSkipped,
904
- metrics: this.metrics.snapshot(),
256
+ state: this.#state,
257
+ connectedAt: this.#connectedAt,
258
+ reconnectAttempts: this.#reconnectAttempts,
259
+ framesReceived: this.#framesReceived,
260
+ eventsDelivered: this.#eventsDelivered,
261
+ duplicatesSkipped: this.#duplicatesSkipped,
262
+ metrics: this.getConnectionMetrics(),
905
263
  replay: this.getReplayState()
906
264
  };
907
265
  }
908
266
  getState() {
909
- return this.state;
267
+ return this.#state;
910
268
  }
911
269
  isConnected() {
912
- return this.state === "connected";
270
+ return this.#state === "connected";
913
271
  }
914
272
  getConnectionQuality() {
915
- return this.metrics.quality;
273
+ return this.#metrics.quality;
916
274
  }
917
275
  getConnectionMetrics() {
918
- return this.metrics.snapshot();
276
+ return { ...this.#metrics };
919
277
  }
920
278
  resetMetrics() {
921
- this.metrics.reset();
279
+ this.#metrics = createSessionStreamConnectionMetrics();
280
+ this.#latencies.length = 0;
281
+ this.#metricsChanged();
922
282
  }
923
- /**
924
- * Update the auth token and reconnect with the new token.
925
- */
283
+ /** Use this token from the next attach on; the open stream stays. */
926
284
  updateToken(token) {
927
- if (!token.trim()) throw new Error("Session gateway token must not be empty");
928
- this.#currentToken = token;
929
- if (this.state === "connected" && this.ws) this.ws.close(1e3, "Token refreshed");
285
+ this.#token = requireText(token, "token");
286
+ if (this.#state !== "disconnected") this.#scheduleTokenRefresh();
930
287
  }
931
- /**
932
- * Get the current auth token.
933
- */
934
288
  getToken() {
935
- return this.#currentToken;
936
- }
937
- setState(state) {
938
- if (this.state !== state) {
939
- this.state = state;
940
- this.metrics.refreshQuality();
941
- invokeClientCallback("onStateChange", () => this.handlers.onStateChange?.(state), this.handlers.onError);
289
+ return this.#token;
290
+ }
291
+ async #attach(generation) {
292
+ const controller = new AbortController();
293
+ this.#stream = controller;
294
+ const dialedAt = Date.now();
295
+ const session = this.#cursor.executionId !== void 0 && this.#cursor.executionId !== this.#finished ? {} : await this.#readSession(controller.signal);
296
+ if (generation !== this.#generation) return;
297
+ if (session.backend) this.#backend = session.backend;
298
+ const turn = this.#follow(session.activeExecutionId);
299
+ this.#releaseHeld(turn);
300
+ const query = new URLSearchParams({ sessionId: this.#config.runtimeSessionId });
301
+ if (turn) {
302
+ query.set("executionId", turn.executionId);
303
+ query.set("since", turn.since);
304
+ }
305
+ let response;
306
+ try {
307
+ response = await this.#fetch(`${this.#config.url}/agents/events?${query}`, {
308
+ headers: this.#headers("text/event-stream"),
309
+ signal: controller.signal
310
+ });
311
+ } catch (error) {
312
+ if (generation === this.#generation) this.#dropped(CLOSE.NETWORK, describe(error));
313
+ return;
942
314
  }
315
+ if (generation !== this.#generation) {
316
+ await response.body?.cancel().catch(() => void 0);
317
+ return;
318
+ }
319
+ if (!response.ok || !response.body) {
320
+ await this.#refused(generation, response, turn);
321
+ return;
322
+ }
323
+ await this.#read(generation, controller, response.body, dialedAt, turn);
943
324
  }
944
- handleConnectionEstablished(sessionId) {
945
- if (this.connectionWaiters.established) return;
946
- this.connectionWaiters.clear();
947
- const isReconnect = this.#reconnects.hasConnectedBefore;
948
- this.connectionWaiters.established = true;
949
- this.#reconnects.hasConnectedBefore = true;
950
- this.counters.connectedAt = Date.now();
951
- this.#reconnects.attempts = 0;
952
- this.#heartbeat.start();
953
- const subscribe = this.replayCursor.subscribeMessage(this.#config.channels);
954
- if (subscribe) this.send(subscribe);
955
- this.setState("connected");
956
- if (!this.connectionWaiters.established || !this.isConnected()) return;
957
- this.connectionWaiters.resolveAll();
958
- invokeClientCallback("onConnect", () => this.handlers.onConnect?.(sessionId), this.handlers.onError);
959
- if (isReconnect && this.connectionWaiters.established && this.isConnected()) {
960
- this.metrics.trackReconnection();
961
- invokeClientCallback("onReconnect", () => this.handlers.onReconnect?.(), this.handlers.onError);
325
+ /**
326
+ * The turn to read: the followed turn until its terminal arrives, else the
327
+ * session's running turn from its first event, else none.
328
+ */
329
+ #follow(activeExecutionId) {
330
+ const followed = this.#cursor.executionId;
331
+ if (followed && followed !== this.#finished) return {
332
+ executionId: followed,
333
+ since: this.#cursor.lastId ?? "0"
334
+ };
335
+ if (activeExecutionId && activeExecutionId !== this.#finished) {
336
+ this.#cursor = { executionId: activeExecutionId };
337
+ return {
338
+ executionId: activeExecutionId,
339
+ since: "0"
340
+ };
962
341
  }
342
+ this.#cursor = {};
343
+ }
344
+ /** A held session frame: the turn's replay carries it, or it passes now. */
345
+ #releaseHeld(turn) {
346
+ const held = this.#held;
347
+ this.#held = null;
348
+ if (turn || !held) return;
349
+ this.#quietUntil = Date.now() + NO_TURN_QUIET_MS;
350
+ this.#deliver(held.type, held.data, held.id);
351
+ }
352
+ async #read(generation, controller, body, dialedAt, turn) {
353
+ const establishTimer = setTimeout(() => controller.abort(new EstablishTimeout()), this.#config.connectionEstablishmentTimeoutMs);
354
+ let code = CLOSE.ENDED;
355
+ let reason = "Event stream ended";
356
+ let first = true;
357
+ try {
358
+ for await (const frame of parseSSEStream(body, {
359
+ signal: controller.signal,
360
+ invalidEvent: "warn-and-skip",
361
+ idleMs: () => this.#config.idleTimeoutMs
362
+ })) {
363
+ if (generation !== this.#generation) return;
364
+ if (first) {
365
+ first = false;
366
+ clearTimeout(establishTimer);
367
+ if (!this.#open) this.#established(dialedAt);
368
+ if (generation !== this.#generation) return;
369
+ }
370
+ const switchStream = this.#frame(frame, turn?.executionId, controller);
371
+ if (generation !== this.#generation) return;
372
+ if (switchStream) {
373
+ this.#reattachNow = true;
374
+ break;
375
+ }
376
+ }
377
+ } catch (error) {
378
+ if (generation !== this.#generation) return;
379
+ if (controller.signal.reason instanceof EstablishTimeout) {
380
+ code = CLOSE.ESTABLISH_TIMEOUT;
381
+ reason = `No frame within ${this.#config.connectionEstablishmentTimeoutMs} ms`;
382
+ } else if (error instanceof Error && error.name === "SSEStreamSilentError") {
383
+ code = CLOSE.SILENT;
384
+ reason = error.message;
385
+ this.#metrics.silentDropCount++;
386
+ } else {
387
+ code = CLOSE.NETWORK;
388
+ reason = describe(error);
389
+ }
390
+ } finally {
391
+ clearTimeout(establishTimer);
392
+ clearTimeout(this.#turnEndTimer);
393
+ this.#turnEndTimer = void 0;
394
+ controller.abort();
395
+ }
396
+ if (generation !== this.#generation) return;
397
+ if (this.#reattachNow && this.#open) {
398
+ this.#reattachNow = false;
399
+ this.#attach(++this.#generation);
400
+ return;
401
+ }
402
+ this.#dropped(code, reason);
963
403
  }
964
- handleClose(socket, code, reason) {
965
- if (this.ws !== socket) return;
966
- this.connectionWaiters.clear();
967
- this.ws = null;
968
- this.connectionWaiters.established = false;
969
- this.#heartbeat.stop();
970
- this.#reconnects.cancel();
971
- this.inbound.requests.rejectAll("Connection closed");
972
- if (this.#reconnects.canRetry()) {
973
- this.setState("reconnecting");
974
- if (this.state === "reconnecting") this.#reconnects.schedule(() => {
975
- if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
404
+ /** The runtime's running turn for this session, and its backend. */
405
+ async #readSession(signal) {
406
+ const path = `/agents/sessions/${encodeURIComponent(this.#config.runtimeSessionId)}`;
407
+ try {
408
+ const response = await this.#fetch(`${this.#config.url}${path}`, {
409
+ headers: this.#headers("application/json"),
410
+ signal: combineAbortSignals([signal, AbortSignal.timeout(SESSION_READ_TIMEOUT_MS)])
976
411
  });
977
- } else {
978
- this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Connection closed"));
979
- this.setState("disconnected");
412
+ if (!response.ok) {
413
+ await response.body?.cancel().catch(() => void 0);
414
+ return {};
415
+ }
416
+ const body = await response.json();
417
+ const info = isRecord(body.data) ? body.data : body;
418
+ const effective = isRecord(info.effectiveBackend) ? info.effectiveBackend : {};
419
+ return {
420
+ activeExecutionId: text(info.activeExecutionId),
421
+ backend: typeof info.backendType === "string" ? {
422
+ type: info.backendType,
423
+ ...text(effective.provider) ? { provider: text(effective.provider) } : {},
424
+ ...text(effective.model) ? { model: text(effective.model) } : {}
425
+ } : void 0
426
+ };
427
+ } catch {
428
+ return {};
980
429
  }
981
- invokeClientCallback("onDisconnect", () => this.handlers.onDisconnect?.(code, reason), this.handlers.onError);
982
430
  }
983
- handleMessage(data) {
984
- this.counters.messagesReceived++;
985
- try {
986
- const message = parseServerFrame(data, this.handlers);
987
- if (!message) return;
988
- if (CONTROL_MESSAGE_TYPES.has(message.type)) {
989
- if (message.type === "pong") this.#heartbeat.handlePong(message.timestamp);
990
- deliverServerMessage(message, this.inbound);
991
- return;
431
+ #established(dialedAt) {
432
+ this.#open = true;
433
+ const now = Date.now();
434
+ this.#recordLatency(now - dialedAt);
435
+ const isReconnect = this.#hasConnectedBefore;
436
+ this.#hasConnectedBefore = true;
437
+ this.#reconnectAttempts = 0;
438
+ this.#connectedAt = now;
439
+ if (isReconnect) {
440
+ this.#metrics.reconnectCount++;
441
+ this.#metrics.lastReconnectAt = now;
442
+ }
443
+ this.#setState("connected");
444
+ if (this.#state !== "connected") return;
445
+ const { sessionId, sandboxId, url } = this.#config;
446
+ const runtime = new URL(url);
447
+ this.#call("onConnect", (h) => h.onConnect(sessionId));
448
+ this.#call("onRuntimeConnected", (h) => h.onRuntimeConnected(sandboxId, url));
449
+ this.#call("onRuntimeReady", (h) => h.onRuntimeReady({
450
+ sandboxId,
451
+ sessionId,
452
+ host: runtime.hostname,
453
+ port: runtime.port ? Number(runtime.port) : runtime.protocol === "https:" ? 443 : 80,
454
+ status: "running",
455
+ ...this.#backend ? { backend: this.#backend } : {}
456
+ }));
457
+ if (isReconnect) this.#call("onReconnect", (h) => h.onReconnect());
458
+ this.#metricsChanged();
459
+ }
460
+ /** Handle one frame; true ends the stream so the client can switch. */
461
+ #frame(frame, executionId, stream) {
462
+ this.#framesReceived++;
463
+ this.#metrics.lastFrameAt = Date.now();
464
+ this.#metrics.silentDropCount = 0;
465
+ const { type, data, id } = frame;
466
+ if (type === REPLAY_START) {
467
+ this.#replay = {
468
+ isReplaying: true,
469
+ received: 0
470
+ };
471
+ this.#call("onReplayStart", (h) => h.onReplayStart());
472
+ return false;
473
+ }
474
+ if (type === REPLAY_END) {
475
+ const { received } = this.#replay;
476
+ this.#replay = {
477
+ isReplaying: false,
478
+ received
479
+ };
480
+ this.#call("onReplayComplete", (h) => h.onReplayComplete(received));
481
+ return false;
482
+ }
483
+ if (type === "buffer.overflow") {
484
+ const properties = isRecord(data.properties) ? data.properties : {};
485
+ const droppedCount = typeof properties.droppedCount === "number" ? properties.droppedCount : void 0;
486
+ this.#call("onStreamGap", (h) => h.onStreamGap({
487
+ sandboxId: this.#config.sandboxId,
488
+ droppedCount
489
+ }));
490
+ }
491
+ if (isSessionFrame(type) || !executionId && Date.now() < this.#quietUntil) {
492
+ this.#deliver(type, data, id);
493
+ return false;
494
+ }
495
+ if (!executionId) {
496
+ this.#held = frame;
497
+ return true;
498
+ }
499
+ if (id !== void 0 && type !== "heartbeat" && /^\d+$/.test(id)) {
500
+ if (this.#config.enableDeduplication && this.#delivered.has(id)) {
501
+ this.#duplicatesSkipped++;
502
+ this.#cursor.lastId = id;
503
+ return false;
992
504
  }
993
- if ("id" in message && message.id && !this.replayCursor.accept(message.id)) return;
994
- deliverServerMessage(message, this.inbound);
995
- } catch {}
505
+ this.#remember(id);
506
+ this.#cursor.lastId = id;
507
+ }
508
+ if (this.#replay.isReplaying) {
509
+ const received = ++this.#replay.received;
510
+ this.#call("onReplayProgress", (h) => h.onReplayProgress(received));
511
+ }
512
+ this.#deliver(type, data, id);
513
+ if (TURN_TERMINALS.has(type) || this.#turnEndTimer !== void 0) this.#awaitTurnEnd(executionId, stream);
514
+ return false;
996
515
  }
997
- send(message) {
998
- if (this.ws?.readyState === WebSocket.OPEN) {
999
- this.ws.send(JSON.stringify(message));
1000
- this.counters.messagesSent++;
516
+ /**
517
+ * After a terminal, keep reading until the turn's store stays quiet, then
518
+ * leave the turn: its store may append a session message's tail after the
519
+ * run's own terminal.
520
+ */
521
+ #awaitTurnEnd(executionId, stream) {
522
+ clearTimeout(this.#turnEndTimer);
523
+ this.#turnEndTimer = setTimeout(() => {
524
+ this.#turnEndTimer = void 0;
525
+ if (this.#stream !== stream || stream.signal.aborted) return;
526
+ this.#finished = executionId;
527
+ this.#cursor = {};
528
+ this.#reattachNow = true;
529
+ stream.abort();
530
+ }, TURN_END_QUIET_MS);
531
+ }
532
+ #deliver(type, data, id) {
533
+ const payload = this.#translate(typeof data.type === "string" ? data : {
534
+ ...data,
535
+ type
536
+ });
537
+ const message = {
538
+ type: "agent.event",
539
+ channel: this.#channel,
540
+ ...id !== void 0 ? { id } : {},
541
+ data: payload,
542
+ timestamp: Date.now(),
543
+ seq: ++this.#seq
544
+ };
545
+ this.#eventsDelivered++;
546
+ if (this.#subscribed()) this.#call("onAgentEvent", (h) => h.onAgentEvent(message.channel, payload, message.seq));
547
+ this.#call("onMessage", (h) => h.onMessage(message));
548
+ }
549
+ /** Frames name the runtime session; callers know theirs. */
550
+ #translate(payload) {
551
+ const { runtimeSessionId, sessionId } = this.#config;
552
+ if (runtimeSessionId === sessionId) return payload;
553
+ const json = JSON.stringify(payload);
554
+ return json.includes(runtimeSessionId) ? JSON.parse(json.split(runtimeSessionId).join(sessionId)) : payload;
555
+ }
556
+ #subscribed() {
557
+ if (this.#channels.size === 0) return true;
558
+ for (const pattern of this.#channels) if (pattern === "*" || pattern === this.#channel || pattern.endsWith("*") && this.#channel.startsWith(pattern.slice(0, -1))) return true;
559
+ return false;
560
+ }
561
+ #remember(id) {
562
+ this.#delivered.add(id);
563
+ if (this.#delivered.size <= this.#config.maxDeduplicationSize) return;
564
+ const excess = this.#delivered.size - this.#config.maxDeduplicationSize;
565
+ let removed = 0;
566
+ for (const oldest of this.#delivered) {
567
+ if (removed++ >= excess) break;
568
+ this.#delivered.delete(oldest);
1001
569
  }
1002
570
  }
1003
- async sendWithResponse(message) {
1004
- await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before request could be sent");
1005
- return this.inbound.requests.request((id) => this.send({
1006
- ...message,
1007
- id
571
+ async #refused(generation, response, turn) {
572
+ const { status } = response;
573
+ const hostCode = response.headers.get("X-Tangle-Sidecar-Proxy-Error") ?? void 0;
574
+ const refusal = await readRefusal(response);
575
+ if (generation !== this.#generation) return;
576
+ const { sessionId, sandboxId } = this.#config;
577
+ if (status === 401) {
578
+ if (this.#reconnectAttempts < this.#config.maxReconnectAttempts && await this.#refresh()) {
579
+ if (generation !== this.#generation) return;
580
+ this.#reconnectAttempts++;
581
+ this.#attach(++this.#generation);
582
+ return;
583
+ }
584
+ if (generation !== this.#generation) return;
585
+ this.#call("onTokenExpired", (h) => h.onTokenExpired());
586
+ this.#stop(4e3 + status, "The runtime refused the token");
587
+ return;
588
+ }
589
+ const routeMiss = refusal.reason && EDGE_ROUTE_MISSES.has(refusal.reason) || hostCode && HOST_ABSENT.has(hostCode);
590
+ if (status === 404 && routeMiss) {
591
+ const reason = refusal.reason ?? hostCode ?? "not_found";
592
+ this.#stop(4e3 + status, `No runtime serves this sandbox (${reason})`);
593
+ this.#call("onRuntimeNotFound", (h) => h.onRuntimeNotFound(sessionId, sandboxId, reason));
594
+ return;
595
+ }
596
+ if (status === 404 && refusal.code === "EXECUTION_NOT_FOUND" && turn) {
597
+ this.#finished = turn.executionId;
598
+ this.#cursor = {};
599
+ this.#attach(++this.#generation);
600
+ return;
601
+ }
602
+ if (status === 400 || status === 403 || status === 404) {
603
+ const message = refusal.message ?? `Event stream refused (HTTP ${status})`;
604
+ this.#call("onError", (h) => h.onError(message, refusal.code ?? hostCode ?? "STREAM_REFUSED"));
605
+ this.#stop(4e3 + status, message);
606
+ return;
607
+ }
608
+ if (hostCode === "SIDECAR_RESTARTING" || status >= 502) this.#call("onRuntimeUnavailable", (h) => h.onRuntimeUnavailable({
609
+ sandboxId,
610
+ sessionId,
611
+ reason: hostCode === "SIDECAR_RESTARTING" ? "sidecar_restarting" : "sidecar_unreachable"
1008
612
  }));
613
+ this.#dropped(4e3 + status, `Event stream refused (HTTP ${status})`);
614
+ }
615
+ /** The attach failed or the stream ended: reattach with backoff, or stop. */
616
+ #dropped(code, reason) {
617
+ const wasOpen = this.#open;
618
+ this.#open = false;
619
+ this.#stream = null;
620
+ this.#reattachNow = false;
621
+ this.#replay = {
622
+ isReplaying: false,
623
+ received: this.#replay.received
624
+ };
625
+ if (wasOpen) this.#call("onRuntimeDisconnected", (h) => h.onRuntimeDisconnected(this.#config.sandboxId, reason));
626
+ const { autoReconnect, maxReconnectAttempts } = this.#config;
627
+ if (autoReconnect && this.#reconnectAttempts < maxReconnectAttempts) {
628
+ this.#setState("reconnecting");
629
+ if (this.#state === "reconnecting") {
630
+ const generation = ++this.#generation;
631
+ const delay = this.#backoff(this.#reconnectAttempts++);
632
+ this.#reconnectTimer = setTimeout(() => {
633
+ if (generation === this.#generation) this.#attach(generation);
634
+ }, delay);
635
+ }
636
+ } else {
637
+ this.#generation++;
638
+ clearTimeout(this.#tokenTimer);
639
+ this.#setState("disconnected");
640
+ }
641
+ this.#metricsChanged();
642
+ this.#call("onDisconnect", (h) => h.onDisconnect(code, reason));
643
+ }
644
+ /** A refusal no retry can change: stop and report it. */
645
+ #stop(code, reason) {
646
+ this.#generation++;
647
+ this.#open = false;
648
+ this.#stream = null;
649
+ clearTimeout(this.#reconnectTimer);
650
+ clearTimeout(this.#tokenTimer);
651
+ this.#setState("disconnected");
652
+ this.#metricsChanged();
653
+ this.#call("onDisconnect", (h) => h.onDisconnect(code, reason));
654
+ }
655
+ #backoff(attempt) {
656
+ const { initialReconnectDelayMs, maxReconnectDelayMs } = this.#config;
657
+ const base = Math.min(maxReconnectDelayMs, initialReconnectDelayMs * 2 ** Math.min(attempt, 16));
658
+ return Math.round(base * (.8 + .4 * Math.random()));
659
+ }
660
+ #scheduleTokenRefresh() {
661
+ clearTimeout(this.#tokenTimer);
662
+ this.#tokenTimer = void 0;
663
+ const expiresAt = jwtExpiryMs(this.#token);
664
+ if (expiresAt === void 0) return;
665
+ this.#tokenTimer = setTimeout(() => void this.#tokenExpiring(expiresAt), Math.max(0, expiresAt - Date.now() - TOKEN_REFRESH_LEAD_MS));
666
+ }
667
+ async #tokenExpiring(expiresAt) {
668
+ const secondsRemaining = Math.max(0, Math.round((expiresAt - Date.now()) / 1e3));
669
+ this.#call("onTokenExpiring", (h) => h.onTokenExpiring(secondsRemaining));
670
+ if (await this.#refresh()) return;
671
+ if (this.#state === "disconnected") return;
672
+ this.#tokenTimer = setTimeout(() => {
673
+ if (this.#state !== "disconnected") this.#call("onTokenExpired", (h) => h.onTokenExpired());
674
+ }, Math.max(0, expiresAt - Date.now()));
675
+ }
676
+ #refresh() {
677
+ const refreshToken = this.#refreshToken;
678
+ if (!refreshToken) return Promise.resolve(false);
679
+ this.#refreshing ??= (async () => {
680
+ try {
681
+ const result = await refreshToken();
682
+ this.updateToken(result?.token ?? "");
683
+ return true;
684
+ } catch (error) {
685
+ this.#call("onError", (h) => h.onError(`Token refresh failed: ${describe(error)}`, "TOKEN_REFRESH_FAILED"));
686
+ return false;
687
+ } finally {
688
+ this.#refreshing = null;
689
+ }
690
+ })();
691
+ return this.#refreshing;
692
+ }
693
+ #headers(accept) {
694
+ return {
695
+ Authorization: `Bearer ${this.#token}`,
696
+ Accept: accept
697
+ };
698
+ }
699
+ #recordLatency(ms) {
700
+ this.#latencies.push(ms);
701
+ while (this.#latencies.length > this.#config.latencyHistorySize) this.#latencies.shift();
702
+ this.#metrics.lastAttachLatencyMs = ms;
703
+ this.#metrics.avgAttachLatencyMs = Math.round(this.#latencies.reduce((sum, value) => sum + value, 0) / this.#latencies.length);
704
+ }
705
+ #setState(state) {
706
+ if (this.#state === state) return;
707
+ this.#state = state;
708
+ this.#metrics.quality = calculateSessionStreamConnectionQuality(this.#metrics, state === "connected");
709
+ this.#call("onStateChange", (h) => h.onStateChange(state));
710
+ }
711
+ #metricsChanged() {
712
+ this.#metrics.quality = calculateSessionStreamConnectionQuality(this.#metrics, this.#state === "connected");
713
+ const metrics = this.getConnectionMetrics();
714
+ this.#call("onMetricsChange", (h) => h.onMetricsChange(metrics));
715
+ }
716
+ /** Run a handler; a throw reaches `onError` and never the client's state. */
717
+ #call(name, invoke) {
718
+ if (!this.#handlers[name]) return;
719
+ try {
720
+ invoke(this.#handlers);
721
+ } catch (error) {
722
+ if (name === "onError") return;
723
+ try {
724
+ this.#handlers.onError?.(`${name} callback failed: ${describe(error)}`, "CALLBACK_ERROR");
725
+ } catch {}
726
+ }
1009
727
  }
1010
728
  };
1011
- //#endregion
1012
- //#region src/session-gateway/client.ts
1013
- /** Sandbox replay waits for the server's authenticated connection receipt. */
1014
- var SessionGatewayClient = class extends SessionGatewayClientCore {
1015
- constructor(config) {
1016
- super(config, INITIAL_METRICS);
729
+ function requireText(value, name) {
730
+ if (typeof value !== "string" || !value.trim()) throw new Error(`SessionGatewayClient ${name} must not be empty`);
731
+ return value;
732
+ }
733
+ /** The runtime base URL: absolute HTTP(S), no credentials, query or fragment. */
734
+ function runtimeBaseUrl(raw) {
735
+ let url;
736
+ try {
737
+ url = new URL(raw);
738
+ } catch {
739
+ throw new Error("SessionGatewayClient url must be an absolute runtime URL");
1017
740
  }
1018
- /** @deprecated Timestamps are not a stable cursor. Use replaySinceSeq(). */
1019
- replay(since) {
1020
- return this.replayAfterConnection({
1021
- type: "replay",
1022
- since
1023
- });
741
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("SessionGatewayClient url must be the runtime's HTTP(S) URL (ScopedToken.runtimeUrl)");
742
+ if (url.username || url.password || url.search || url.hash) throw new Error("SessionGatewayClient url must not carry credentials, a query or a fragment");
743
+ return url.toString().replace(/\/+$/, "");
744
+ }
745
+ function isRecord(value) {
746
+ return typeof value === "object" && value !== null && !Array.isArray(value);
747
+ }
748
+ function text(value) {
749
+ return typeof value === "string" && value.length > 0 ? value : void 0;
750
+ }
751
+ function describe(error) {
752
+ return error instanceof Error ? error.message : String(error);
753
+ }
754
+ /** The refusal's route-miss reason, error code and message, when it has them. */
755
+ async function readRefusal(response) {
756
+ try {
757
+ const body = await response.json();
758
+ const error = isRecord(body.error) ? body.error : {};
759
+ return {
760
+ reason: text(body.reason),
761
+ code: text(body.code) ?? text(error.code),
762
+ message: text(body.message) ?? text(error.message) ?? (typeof body.error === "string" ? body.error : void 0)
763
+ };
764
+ } catch {
765
+ return {};
1024
766
  }
1025
- replaySinceSeq(sinceSeq) {
1026
- return this.replayAfterConnection({
1027
- type: "replay",
1028
- sinceSeq
1029
- });
767
+ }
768
+ /** The token's `exp` in milliseconds, read without verifying it. */
769
+ function jwtExpiryMs(token) {
770
+ const payload = token.split(".")[1];
771
+ if (!payload) return void 0;
772
+ try {
773
+ const padded = payload.replace(/-/g, "+").replace(/_/g, "/");
774
+ const claims = JSON.parse(atob(padded));
775
+ return typeof claims.exp === "number" ? claims.exp * 1e3 : void 0;
776
+ } catch {
777
+ return;
1030
778
  }
1031
- };
779
+ }
1032
780
  //#endregion
1033
- export { INITIAL_METRICS, SessionGatewayClient, calculateConnectionQuality };
781
+ export { INITIAL_METRICS, SessionGatewayClient, calculateSessionStreamConnectionQuality as calculateConnectionQuality };