@daytona/sdk 0.199.0-alpha.1 → 0.200.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.
@@ -0,0 +1,398 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.EventDispatcher = void 0;
8
+ const socket_io_client_1 = require("socket.io-client");
9
+ /**
10
+ * Extracts the resource ID from an event payload.
11
+ *
12
+ * Handles two payload shapes:
13
+ * - Wrapper: {sandbox: {id: ...}, ...} -> nested resource ID
14
+ * - Direct: {id: ...} -> top-level ID
15
+ */
16
+ function extractIdFromEvent(data) {
17
+ if (!data || typeof data !== 'object')
18
+ return undefined;
19
+ for (const key of ['sandbox', 'volume', 'snapshot', 'runner']) {
20
+ const nested = data[key];
21
+ if (nested && typeof nested === 'object' && typeof nested.id === 'string') {
22
+ return nested.id;
23
+ }
24
+ }
25
+ if (typeof data.id === 'string') {
26
+ return data.id;
27
+ }
28
+ return undefined;
29
+ }
30
+ /**
31
+ * Manages a Socket.IO connection to the Daytona notification gateway
32
+ * and dispatches resource events to per-resource handlers.
33
+ */
34
+ class EventDispatcher {
35
+ apiUrl;
36
+ token;
37
+ organizationId;
38
+ source;
39
+ sdkVersion;
40
+ socket;
41
+ _connected = false;
42
+ _closed = false;
43
+ _failed = false;
44
+ _failError = null;
45
+ listeners = new Map();
46
+ registeredEvents = new Set();
47
+ connectPromise = null;
48
+ ensureConnectPromise = null;
49
+ reconnectAttempts = 0;
50
+ maxReconnectAttempts = 10;
51
+ // Cleared on connect/error/disconnect to prevent late state mutation.
52
+ _connectTimer = null;
53
+ disconnectTimer = null;
54
+ disconnectGeneration = 0;
55
+ static DISCONNECT_DELAY_MS = 30_000;
56
+ // Set once on the first Manager 'open' by capability probe, not runtime name.
57
+ // `undefined` (pre-connect) is treated as `false` → ephemeral disconnect.
58
+ supportsBackgroundUnref = undefined;
59
+ constructor(apiUrl, token, organizationId, source, sdkVersion) {
60
+ this.apiUrl = apiUrl;
61
+ this.token = token;
62
+ this.organizationId = organizationId;
63
+ this.source = source;
64
+ this.sdkVersion = sdkVersion;
65
+ }
66
+ /**
67
+ * Idempotent: ensure a connection attempt is in progress or already established.
68
+ *
69
+ * Non-blocking. Fires-and-forgets a connect() call via a stored promise if not
70
+ * already connected and no attempt is currently running.
71
+ */
72
+ ensureConnected() {
73
+ // No-op after disconnect — prevents socket resurrection.
74
+ if (this._closed)
75
+ return;
76
+ if (this._connected)
77
+ return;
78
+ if (this.connectPromise)
79
+ return;
80
+ if (this.ensureConnectPromise)
81
+ return;
82
+ this.ensureConnectPromise = this.connect()
83
+ .catch(() => {
84
+ // Callers check isConnected when they need it
85
+ })
86
+ .finally(() => {
87
+ this.ensureConnectPromise = null;
88
+ });
89
+ }
90
+ /**
91
+ * Establishes the Socket.IO connection. Resolves when connected.
92
+ * Throws if the connection fails within the timeout.
93
+ */
94
+ async connect(timeoutMs = 5000) {
95
+ if (this._closed) {
96
+ return;
97
+ }
98
+ if (this._connected && this.socket) {
99
+ return;
100
+ }
101
+ if (this.connectPromise) {
102
+ return this.connectPromise;
103
+ }
104
+ this.connectPromise = this.doConnect(timeoutMs);
105
+ try {
106
+ await this.connectPromise;
107
+ if (this.listeners.size === 0) {
108
+ this.scheduleDelayedDisconnect();
109
+ }
110
+ }
111
+ catch (error) {
112
+ if (this.listeners.size === 0) {
113
+ // Stop retries if nobody is listening.
114
+ this.socket?.disconnect();
115
+ }
116
+ throw error;
117
+ }
118
+ finally {
119
+ this.connectPromise = null;
120
+ }
121
+ }
122
+ doConnect(timeoutMs) {
123
+ return new Promise((resolve, reject) => {
124
+ if (this.socket) {
125
+ this.socket.removeAllListeners();
126
+ this.socket.disconnect();
127
+ this.socket = undefined;
128
+ }
129
+ // Derive path from the API URL so reverse-proxy prefixes are preserved (not hardcoded /api).
130
+ const url = new URL(this.apiUrl);
131
+ const origin = url.origin;
132
+ const socketPath = `${url.pathname.replace(/\/$/, '')}/socket.io/`;
133
+ const query = {};
134
+ if (this.organizationId) {
135
+ query.organizationId = this.organizationId;
136
+ }
137
+ if (this.source) {
138
+ query.source = this.source;
139
+ }
140
+ if (this.sdkVersion) {
141
+ query.sdkVersion = this.sdkVersion;
142
+ }
143
+ this.socket = (0, socket_io_client_1.io)(origin, {
144
+ path: socketPath,
145
+ autoConnect: false,
146
+ transports: ['websocket'],
147
+ query,
148
+ reconnection: true,
149
+ reconnectionAttempts: this.maxReconnectAttempts,
150
+ reconnectionDelay: 1000,
151
+ reconnectionDelayMax: 30000,
152
+ });
153
+ this.socket.auth = { token: this.token };
154
+ this.clearConnectTimer();
155
+ this._connectTimer = setTimeout(() => {
156
+ if (!this._connected) {
157
+ this.socket?.disconnect();
158
+ this.clearConnectTimer();
159
+ this._failed = true;
160
+ this._failError = 'WebSocket connection timed out';
161
+ reject(new Error(this._failError));
162
+ }
163
+ }, timeoutMs);
164
+ if (typeof this._connectTimer.unref === 'function') {
165
+ this._connectTimer.unref();
166
+ }
167
+ this.socket.on('connect', () => {
168
+ this.clearConnectTimer();
169
+ this._connected = true;
170
+ this._failed = false;
171
+ this._failError = null;
172
+ this.reconnectAttempts = 0;
173
+ resolve();
174
+ });
175
+ this.socket.on('connect_error', (err) => {
176
+ if (!this._connected) {
177
+ this.clearConnectTimer();
178
+ this._failed = true;
179
+ this._failError = `WebSocket connection failed: ${err.message}`;
180
+ reject(new Error(this._failError));
181
+ }
182
+ });
183
+ this.socket.on('disconnect', (reason) => {
184
+ this._connected = false;
185
+ if (reason === 'io server disconnect') {
186
+ // Server initiated disconnect - try to reconnect
187
+ this.socket?.connect();
188
+ }
189
+ });
190
+ this.socket.io.on('reconnect', () => {
191
+ this._connected = true;
192
+ this._failed = false;
193
+ this._failError = null;
194
+ this.reconnectAttempts = 0;
195
+ });
196
+ this.socket.io.on('reconnect_attempt', () => {
197
+ this.reconnectAttempts++;
198
+ });
199
+ this.socket.io.on('reconnect_failed', () => {
200
+ this._connected = false;
201
+ this._failed = true;
202
+ this._failError = `WebSocket reconnection failed after ${this.maxReconnectAttempts} attempts`;
203
+ });
204
+ // Fires before engine.io's first _resetPingTimeout(), so enabling autoUnref here
205
+ // also covers the initial + recurring ping timers and reconnect timers.
206
+ this.socket.io.on('open', () => {
207
+ this.applyUnrefCapability();
208
+ });
209
+ // Re-register any events that were added before the socket was created
210
+ const pendingEvents = [...this.registeredEvents];
211
+ this.registeredEvents.clear();
212
+ this.registerEvents(pendingEvents);
213
+ this.socket.connect();
214
+ });
215
+ }
216
+ /**
217
+ * Registers Socket.IO event handlers (idempotent -- each event is registered once).
218
+ */
219
+ registerEvents(events) {
220
+ for (const eventName of events) {
221
+ if (this.registeredEvents.has(eventName)) {
222
+ continue;
223
+ }
224
+ this.registeredEvents.add(eventName);
225
+ // If socket isn't created yet, the event will be registered when connect() runs
226
+ if (!this.socket)
227
+ continue;
228
+ const handler = (data) => {
229
+ const resourceId = extractIdFromEvent(data);
230
+ if (resourceId) {
231
+ this.dispatch(resourceId, eventName, data);
232
+ }
233
+ };
234
+ this.socket.on(eventName, handler);
235
+ }
236
+ }
237
+ /**
238
+ * Registers a handler for events targeting a specific resource.
239
+ * Returns an unsubscribe function.
240
+ *
241
+ * @param resourceId - The ID of the resource (e.g. sandbox ID).
242
+ * @param handler - Callback receiving (eventName, rawData).
243
+ * @param events - List of Socket.IO event names to listen for.
244
+ */
245
+ subscribe(resourceId, handler, events) {
246
+ // No-op after disconnect — prevents socket resurrection.
247
+ if (this._closed) {
248
+ return () => {
249
+ return;
250
+ };
251
+ }
252
+ this.cancelDelayedDisconnect();
253
+ this.disconnectGeneration++;
254
+ this.ensureConnected();
255
+ if (!this.listeners.has(resourceId)) {
256
+ this.listeners.set(resourceId, new Set());
257
+ }
258
+ this.listeners.get(resourceId).add(handler);
259
+ // Register any new events with the Socket.IO client
260
+ this.registerEvents(events);
261
+ return () => {
262
+ const handlers = this.listeners.get(resourceId);
263
+ if (handlers) {
264
+ handlers.delete(handler);
265
+ if (handlers.size === 0) {
266
+ this.listeners.delete(resourceId);
267
+ }
268
+ }
269
+ // Schedule delayed disconnect when no resources are listening anymore
270
+ if (this.listeners.size === 0) {
271
+ this.scheduleDelayedDisconnect();
272
+ }
273
+ };
274
+ }
275
+ /** Whether the WebSocket is currently connected */
276
+ get isConnected() {
277
+ return this._connected;
278
+ }
279
+ /** Whether the WebSocket has permanently failed (exhausted reconnection attempts) */
280
+ get isFailed() {
281
+ return this._failed;
282
+ }
283
+ /** The error message if the connection has failed */
284
+ get failError() {
285
+ return this._failError;
286
+ }
287
+ /** Disconnects and cleans up all resources */
288
+ disconnect() {
289
+ this._closed = true;
290
+ this.cancelDelayedDisconnect();
291
+ this.clearConnectTimer();
292
+ this.connectPromise = null;
293
+ this.ensureConnectPromise = null;
294
+ this.disconnectSocket();
295
+ }
296
+ disconnectSocket() {
297
+ if (this.socket) {
298
+ this.socket.removeAllListeners();
299
+ this.socket.disconnect();
300
+ this.socket = undefined;
301
+ }
302
+ this._connected = false;
303
+ this.listeners.clear();
304
+ this.registeredEvents.clear();
305
+ }
306
+ /**
307
+ * Decides, by capability rather than runtime name, whether this runtime can keep a
308
+ * background socket open without blocking process exit.
309
+ *
310
+ * A runtime qualifies only if it can unref BOTH the transport's raw socket AND timers:
311
+ * Node/Deno (ws package exposes `_socket`, timers are objects) qualify; Bun (native
312
+ * WebSocket has no `_socket`) and browsers (timers are numbers, no `_socket`) do not.
313
+ *
314
+ * When it qualifies, this unrefs the current connection's socket (engine.io skipped it —
315
+ * autoUnref was off during the transport's onopen) and enables engine.io's own autoUnref
316
+ * so it keeps every later ping-timeout and reconnect timer unref'd. When it does not,
317
+ * autoUnref stays off (avoiding the `ws._socket.unref()` and number-timer crashes) and
318
+ * the socket is dropped the instant it goes idle (see scheduleDelayedDisconnect).
319
+ */
320
+ applyUnrefCapability() {
321
+ const manager = this.socket?.io;
322
+ // Known-unsupported runtime: nothing to unref; ephemeral disconnect handles exit.
323
+ if (this.supportsBackgroundUnref === false)
324
+ return;
325
+ // Re-apply per Manager: an idle disconnect replaces the socket with a fresh manager
326
+ // whose autoUnref is off, so skip only when this manager already has it applied.
327
+ if (this.supportsBackgroundUnref === true && manager?.opts?.autoUnref === true)
328
+ return;
329
+ try {
330
+ const engine = manager?.engine;
331
+ const rawSocket = engine?.transport?.ws?._socket;
332
+ const socketUnrefable = !!rawSocket && typeof rawSocket.unref === 'function';
333
+ const probe = setTimeout(() => undefined, 0);
334
+ const timerUnrefable = typeof probe?.unref === 'function';
335
+ clearTimeout(probe);
336
+ if (socketUnrefable && timerUnrefable) {
337
+ rawSocket.unref();
338
+ engine.opts.autoUnref = true;
339
+ manager.opts.autoUnref = true;
340
+ this.supportsBackgroundUnref = true;
341
+ }
342
+ else if (this.supportsBackgroundUnref === undefined) {
343
+ this.supportsBackgroundUnref = false;
344
+ }
345
+ }
346
+ catch {
347
+ if (this.supportsBackgroundUnref === undefined)
348
+ this.supportsBackgroundUnref = false;
349
+ }
350
+ }
351
+ dispatch(resourceId, eventName, data) {
352
+ if (!resourceId)
353
+ return;
354
+ const handlers = this.listeners.get(resourceId);
355
+ if (handlers) {
356
+ for (const handler of handlers) {
357
+ try {
358
+ handler(eventName, data);
359
+ }
360
+ catch {
361
+ // Don't let a handler error break other handlers
362
+ }
363
+ }
364
+ }
365
+ }
366
+ cancelDelayedDisconnect() {
367
+ if (this.disconnectTimer) {
368
+ clearTimeout(this.disconnectTimer);
369
+ this.disconnectTimer = null;
370
+ }
371
+ }
372
+ clearConnectTimer() {
373
+ if (this._connectTimer) {
374
+ clearTimeout(this._connectTimer);
375
+ this._connectTimer = null;
376
+ }
377
+ }
378
+ scheduleDelayedDisconnect() {
379
+ this.cancelDelayedDisconnect();
380
+ const generation = this.disconnectGeneration;
381
+ // Where the socket can't be unref'd (Bun/browser), an open idle socket keeps the
382
+ // event loop alive, so drop it immediately; elsewhere keep it warm for reuse.
383
+ const delay = this.supportsBackgroundUnref === true ? EventDispatcher.DISCONNECT_DELAY_MS : 0;
384
+ this.disconnectTimer = setTimeout(() => {
385
+ if (generation !== this.disconnectGeneration) {
386
+ return;
387
+ }
388
+ if (this.listeners.size === 0) {
389
+ this.disconnectSocket();
390
+ }
391
+ }, delay);
392
+ if (typeof this.disconnectTimer.unref === 'function') {
393
+ this.disconnectTimer.unref();
394
+ }
395
+ }
396
+ }
397
+ exports.EventDispatcher = EventDispatcher;
398
+ //# sourceMappingURL=EventDispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EventDispatcher.js","sourceRoot":"","sources":["../../../../../sdk-typescript/src/utils/EventDispatcher.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uDAA6C;AAK7C;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,IAAS;IACnC,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAA;IACvD,KAAK,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,CAAC;QAC9D,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAA;QACxB,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;YAC1E,OAAO,MAAM,CAAC,EAAE,CAAA;QAClB,CAAC;IACH,CAAC;IACD,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC,EAAE,CAAA;IAChB,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED;;;GAGG;AACH,MAAa,eAAe;IAsBP;IACA;IACA;IACA;IACA;IAzBX,MAAM,CAAoB;IAC1B,UAAU,GAAG,KAAK,CAAA;IAClB,OAAO,GAAG,KAAK,CAAA;IACf,OAAO,GAAG,KAAK,CAAA;IACf,UAA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C,gBAAgB,EAAE,CAAA;YACzB,CAAC;QACH,CAAC,EAAE,KAAK,CAAC,CAAA;QAET,IAAI,OAAO,IAAI,CAAC,eAAe,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;YACrD,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAA;QAC9B,CAAC;IACH,CAAC;;AAzYH,0CA0YC"}
@@ -0,0 +1,14 @@
1
+ import { EventDispatcher, type EventHandler } from './EventDispatcher';
2
+ export declare class EventSubscriptionManager {
3
+ private readonly dispatcher;
4
+ private static readonly SUBSCRIPTION_TTL;
5
+ private readonly subscriptions;
6
+ private _closed;
7
+ constructor(dispatcher: EventDispatcher | null);
8
+ subscribe(resourceId: string, handler: EventHandler, events: string[]): string;
9
+ refresh(subId: string): boolean;
10
+ unsubscribe(subId: string): void;
11
+ shutdown(): void;
12
+ private createTimer;
13
+ }
14
+ //# sourceMappingURL=EventSubscriptionManager.d.ts.map
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.EventSubscriptionManager = void 0;
8
+ function createSubscriptionId() {
9
+ // Browser-safe UUID generation.
10
+ if (typeof globalThis.crypto?.randomUUID === 'function') {
11
+ return globalThis.crypto.randomUUID();
12
+ }
13
+ const randomHex = () => Math.floor(Math.random() * 0xffffffff)
14
+ .toString(16)
15
+ .padStart(8, '0');
16
+ return `${randomHex()}${randomHex()}${randomHex()}${randomHex()}`;
17
+ }
18
+ class EventSubscriptionManager {
19
+ dispatcher;
20
+ static SUBSCRIPTION_TTL = 300;
21
+ subscriptions = new Map();
22
+ _closed = false;
23
+ constructor(dispatcher) {
24
+ this.dispatcher = dispatcher;
25
+ }
26
+ subscribe(resourceId, handler, events) {
27
+ // No-op when shut down or when streaming is disabled (no dispatcher) — callers poll.
28
+ if (this._closed || !this.dispatcher) {
29
+ return '';
30
+ }
31
+ const subId = createSubscriptionId();
32
+ const unsubscribe = this.dispatcher.subscribe(resourceId, handler, events);
33
+ try {
34
+ if (this._closed) {
35
+ throw new Error('EventSubscriptionManager is closed');
36
+ }
37
+ this.subscriptions.set(subId, {
38
+ unsubscribe,
39
+ timer: this.createTimer(subId),
40
+ });
41
+ return subId;
42
+ }
43
+ catch (error) {
44
+ // Rollback dispatcher subscription on failure.
45
+ unsubscribe();
46
+ if (this._closed) {
47
+ return '';
48
+ }
49
+ throw error;
50
+ }
51
+ }
52
+ refresh(subId) {
53
+ // Reject operations after shutdown to prevent use-after-close.
54
+ if (this._closed) {
55
+ return false;
56
+ }
57
+ const subscription = this.subscriptions.get(subId);
58
+ if (!subscription) {
59
+ return false;
60
+ }
61
+ clearTimeout(subscription.timer);
62
+ subscription.timer = this.createTimer(subId);
63
+ return true;
64
+ }
65
+ unsubscribe(subId) {
66
+ const subscription = this.subscriptions.get(subId);
67
+ if (!subscription) {
68
+ return;
69
+ }
70
+ clearTimeout(subscription.timer);
71
+ this.subscriptions.delete(subId);
72
+ subscription.unsubscribe();
73
+ }
74
+ shutdown() {
75
+ this._closed = true;
76
+ for (const [subId, subscription] of this.subscriptions) {
77
+ clearTimeout(subscription.timer);
78
+ this.subscriptions.delete(subId);
79
+ subscription.unsubscribe();
80
+ }
81
+ }
82
+ createTimer(subId) {
83
+ const timer = setTimeout(() => {
84
+ const subscription = this.subscriptions.get(subId);
85
+ if (!subscription || subscription.timer !== timer) {
86
+ return;
87
+ }
88
+ this.subscriptions.delete(subId);
89
+ subscription.unsubscribe();
90
+ }, EventSubscriptionManager.SUBSCRIPTION_TTL * 1000);
91
+ if (typeof timer.unref === 'function') {
92
+ timer.unref();
93
+ }
94
+ return timer;
95
+ }
96
+ }
97
+ exports.EventSubscriptionManager = EventSubscriptionManager;
98
+ //# sourceMappingURL=EventSubscriptionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EventSubscriptionManager.js","sourceRoot":"","sources":["../../../../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,CAAC,CAAA;YAChC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAChC,YAAY,CAAC,WAAW,EAAE,CAAA;QAC5B,CAAC;IACH,CAAC;IAEO,WAAW,CAAC,KAAa;QAC/B,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAClD,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;gBAClD,OAAM;YACR,CAAC;YAED,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAChC,YAAY,CAAC,WAAW,EAAE,CAAA;QAC5B,CAAC,EAAE,wBAAwB,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAA;QAEpD,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;YACtC,KAAK,CAAC,KAAK,EAAE,CAAA;QACf,CAAC;QAED,OAAO,KAAK,CAAA;IACd,CAAC;;AAzFH,4DA0FC"}
package/esm/Daytona.d.ts CHANGED
@@ -59,6 +59,16 @@ export interface DaytonaConfig {
59
59
  target?: string;
60
60
  /** Enable OpenTelemetry tracing for SDK operations. */
61
61
  otelEnabled?: boolean;
62
+ /**
63
+ * Observe sandbox state by legacy polling instead of WebSocket event streaming.
64
+ * Defaults to `false`, where state changes are streamed over WebSocket. Can also
65
+ * be enabled via the `DAYTONA_USE_DEPRECATED_POLLING` environment variable.
66
+ *
67
+ * @deprecated Polling-only mode will be removed in a future release. Event
68
+ * streaming is the default and falls back to polling automatically when
69
+ * WebSockets are unavailable.
70
+ */
71
+ useDeprecatedPolling?: boolean;
62
72
  /** Configuration for experimental features */
63
73
  _experimental?: Record<string, any>;
64
74
  }
@@ -109,9 +119,11 @@ export interface Resources {
109
119
  * @property {Record<string, string>} [envVars] - Optional environment variables to set in the Sandbox
110
120
  * @property {Record<string, string>} [labels] - Sandbox labels
111
121
  * @property {boolean} [public] - Is the Sandbox port preview public
112
- * @property {number} [autoStopInterval] - Auto-stop interval in minutes (0 means disabled). Default is 15 minutes.
122
+ * @property {number} [autoStopInterval] - Auto-stop interval in minutes (0 means disabled). Default is 15 minutes (for sandbox classes that support pausing, auto-pause defaults to 60 minutes instead and auto-stop is disabled).
123
+ * @property {number} [autoPauseInterval] - Auto-pause interval in minutes (0 means disabled). Only supported for sandbox classes that support pausing. Not allowed for ephemeral sandboxes. At most one of autoStopInterval and autoPauseInterval may be non-zero. For non-ephemeral sandbox classes that support pausing, defaults to 60 minutes (with auto-stop disabled) when neither interval is provided.
113
124
  * @property {number} [autoArchiveInterval] - Auto-archive interval in minutes (0 means the maximum interval will be used). Default is 7 days.
114
125
  * @property {number} [autoDeleteInterval] - Auto-delete interval in minutes (negative value means disabled, 0 means delete immediately upon stopping). By default, auto-delete is disabled.
126
+ * @property {number} [ttlMinutes] - Maximum time to live in minutes, counted as wall-clock time since creation regardless of sandbox state (0 means disabled). When it elapses the Sandbox is destroyed, even if it is stopped, paused, or archived.
115
127
  * @property {VolumeMount[]} [volumes] - Optional array of volumes to mount to the Sandbox
116
128
  * @property {boolean} [networkBlockAll] - Whether to block all network access for the Sandbox
117
129
  * @property {string} [networkAllowList] - Comma-separated list of allowed CIDR network addresses for the Sandbox
@@ -128,8 +140,10 @@ export type CreateSandboxBaseParams = {
128
140
  labels?: Record<string, string>;
129
141
  public?: boolean;
130
142
  autoStopInterval?: number;
143
+ autoPauseInterval?: number;
131
144
  autoArchiveInterval?: number;
132
145
  autoDeleteInterval?: number;
146
+ ttlMinutes?: number;
133
147
  volumes?: VolumeMount[];
134
148
  networkBlockAll?: boolean;
135
149
  networkAllowList?: string;
@@ -196,12 +210,21 @@ export declare class Daytona implements AsyncDisposable {
196
210
  private readonly sandboxApi;
197
211
  private readonly objectStorageApi;
198
212
  private readonly configApi;
213
+ private analyticsApiUrlPromise?;
214
+ /**
215
+ * Resolves the deployment's Analytics API URL via `/config`, cached for the client's
216
+ * lifetime. The in-flight promise is shared by concurrent callers; a rejected lookup
217
+ * is evicted so the next call retries.
218
+ */
219
+ private readonly getAnalyticsApiUrl;
199
220
  private readonly target?;
200
221
  private readonly apiKey?;
201
222
  private readonly jwtToken?;
202
223
  private readonly organizationId?;
203
224
  private readonly apiUrl;
204
225
  private otelSdk?;
226
+ private eventDispatcher?;
227
+ private eventSubscriptionManager;
205
228
  readonly volume: VolumeService;
206
229
  readonly snapshot: SnapshotService;
207
230
  readonly secret: SecretService;
@@ -305,6 +328,7 @@ export declare class Daytona implements AsyncDisposable {
305
328
  * }
306
329
  */
307
330
  list(query?: ListSandboxesQuery): AsyncIterableIterator<Sandbox>;
331
+ private ensureToolboxProxyUrl;
308
332
  /**
309
333
  * Starts a Sandbox and waits for it to be ready.
310
334
  *
@@ -351,13 +375,14 @@ export declare class Daytona implements AsyncDisposable {
351
375
  *
352
376
  * @param {Sandbox} sandbox - The Sandbox to delete
353
377
  * @param {number} timeout - Timeout in seconds (0 means no timeout, default is 60)
378
+ * @param {boolean} wait - If true, wait until the Sandbox is destroyed (default is false)
354
379
  * @returns {Promise<void>}
355
380
  *
356
381
  * @example
357
382
  * const sandbox = await daytona.get('my-sandbox-id');
358
383
  * await daytona.delete(sandbox);
359
384
  */
360
- delete(sandbox: Sandbox, timeout?: number): Promise<void>;
385
+ delete(sandbox: Sandbox, timeout?: number, wait?: boolean): Promise<void>;
361
386
  /**
362
387
  * @hidden
363
388
  */