@agentuity/core 3.0.0-alpha.6 → 3.0.0-beta.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 (169) hide show
  1. package/AGENTS.md +0 -1
  2. package/dist/index.d.ts +0 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +0 -3
  5. package/dist/index.js.map +1 -1
  6. package/dist/services/coder/api-reference.d.ts.map +1 -1
  7. package/dist/services/coder/api-reference.js +30 -1
  8. package/dist/services/coder/api-reference.js.map +1 -1
  9. package/dist/services/coder/client.d.ts +17 -1
  10. package/dist/services/coder/client.d.ts.map +1 -1
  11. package/dist/services/coder/client.js +30 -2
  12. package/dist/services/coder/client.js.map +1 -1
  13. package/dist/services/coder/index.d.ts +2 -2
  14. package/dist/services/coder/index.d.ts.map +1 -1
  15. package/dist/services/coder/index.js +1 -1
  16. package/dist/services/coder/index.js.map +1 -1
  17. package/dist/services/coder/protocol.d.ts +186 -5
  18. package/dist/services/coder/protocol.d.ts.map +1 -1
  19. package/dist/services/coder/protocol.js +125 -0
  20. package/dist/services/coder/protocol.js.map +1 -1
  21. package/dist/services/coder/sessions.d.ts +22 -0
  22. package/dist/services/coder/sessions.d.ts.map +1 -1
  23. package/dist/services/coder/sessions.js +10 -1
  24. package/dist/services/coder/sessions.js.map +1 -1
  25. package/dist/services/coder/sse.d.ts +2 -2
  26. package/dist/services/coder/sse.d.ts.map +1 -1
  27. package/dist/services/coder/sse.js +290 -178
  28. package/dist/services/coder/sse.js.map +1 -1
  29. package/dist/services/coder/types.d.ts +627 -0
  30. package/dist/services/coder/types.d.ts.map +1 -1
  31. package/dist/services/coder/types.js +221 -1
  32. package/dist/services/coder/types.js.map +1 -1
  33. package/dist/services/coder/workspaces.d.ts +11 -1
  34. package/dist/services/coder/workspaces.d.ts.map +1 -1
  35. package/dist/services/coder/workspaces.js +34 -1
  36. package/dist/services/coder/workspaces.js.map +1 -1
  37. package/dist/services/index.d.ts +0 -2
  38. package/dist/services/index.d.ts.map +1 -1
  39. package/dist/services/index.js +0 -2
  40. package/dist/services/index.js.map +1 -1
  41. package/dist/services/keyvalue/service.d.ts +9 -3
  42. package/dist/services/keyvalue/service.d.ts.map +1 -1
  43. package/dist/services/keyvalue/service.js +6 -3
  44. package/dist/services/keyvalue/service.js.map +1 -1
  45. package/dist/services/sandbox/api-reference.js +8 -8
  46. package/dist/services/sandbox/api-reference.js.map +1 -1
  47. package/dist/services/sandbox/client.d.ts +3 -2
  48. package/dist/services/sandbox/client.d.ts.map +1 -1
  49. package/dist/services/sandbox/client.js.map +1 -1
  50. package/dist/services/sandbox/create.d.ts +5 -0
  51. package/dist/services/sandbox/create.d.ts.map +1 -1
  52. package/dist/services/sandbox/create.js +8 -0
  53. package/dist/services/sandbox/create.js.map +1 -1
  54. package/dist/services/sandbox/get.d.ts +8 -4
  55. package/dist/services/sandbox/get.d.ts.map +1 -1
  56. package/dist/services/sandbox/get.js +28 -3
  57. package/dist/services/sandbox/get.js.map +1 -1
  58. package/dist/services/sandbox/getStatus.d.ts +3 -0
  59. package/dist/services/sandbox/getStatus.d.ts.map +1 -1
  60. package/dist/services/sandbox/getStatus.js +19 -2
  61. package/dist/services/sandbox/getStatus.js.map +1 -1
  62. package/dist/services/sandbox/index.d.ts +1 -1
  63. package/dist/services/sandbox/index.d.ts.map +1 -1
  64. package/dist/services/sandbox/list.d.ts +3 -0
  65. package/dist/services/sandbox/list.d.ts.map +1 -1
  66. package/dist/services/sandbox/list.js +5 -0
  67. package/dist/services/sandbox/list.js.map +1 -1
  68. package/dist/services/sandbox/pause.d.ts +17 -1
  69. package/dist/services/sandbox/pause.d.ts.map +1 -1
  70. package/dist/services/sandbox/pause.js +21 -3
  71. package/dist/services/sandbox/pause.js.map +1 -1
  72. package/dist/services/sandbox/run.d.ts +3 -2
  73. package/dist/services/sandbox/run.d.ts.map +1 -1
  74. package/dist/services/sandbox/run.js +244 -84
  75. package/dist/services/sandbox/run.js.map +1 -1
  76. package/dist/services/sandbox/types.d.ts +11 -4
  77. package/dist/services/sandbox/types.d.ts.map +1 -1
  78. package/dist/services/sandbox/types.js +12 -0
  79. package/dist/services/sandbox/types.js.map +1 -1
  80. package/dist/services/stream/namespaces.d.ts +2 -2
  81. package/dist/services/stream/namespaces.js +2 -2
  82. package/dist/services/stream/namespaces.js.map +1 -1
  83. package/dist/services/vector/service.d.ts +11 -11
  84. package/dist/services/vector/service.d.ts.map +1 -1
  85. package/dist/services/vector/service.js.map +1 -1
  86. package/package.json +3 -17
  87. package/src/index.ts +0 -15
  88. package/src/services/coder/api-reference.ts +31 -0
  89. package/src/services/coder/client.ts +46 -0
  90. package/src/services/coder/index.ts +3 -0
  91. package/src/services/coder/protocol.ts +133 -0
  92. package/src/services/coder/sessions.ts +26 -0
  93. package/src/services/coder/sse.ts +343 -184
  94. package/src/services/coder/types.ts +273 -1
  95. package/src/services/coder/workspaces.ts +74 -0
  96. package/src/services/index.ts +0 -2
  97. package/src/services/keyvalue/service.ts +16 -7
  98. package/src/services/sandbox/api-reference.ts +8 -8
  99. package/src/services/sandbox/client.ts +4 -4
  100. package/src/services/sandbox/create.ts +10 -0
  101. package/src/services/sandbox/get.ts +32 -3
  102. package/src/services/sandbox/getStatus.ts +23 -2
  103. package/src/services/sandbox/index.ts +1 -1
  104. package/src/services/sandbox/list.ts +5 -0
  105. package/src/services/sandbox/pause.ts +38 -4
  106. package/src/services/sandbox/run.ts +352 -105
  107. package/src/services/sandbox/types.ts +17 -2
  108. package/src/services/stream/namespaces.ts +2 -2
  109. package/src/services/vector/service.ts +11 -21
  110. package/dist/services/auth/index.d.ts +0 -7
  111. package/dist/services/auth/index.d.ts.map +0 -1
  112. package/dist/services/auth/index.js +0 -7
  113. package/dist/services/auth/index.js.map +0 -1
  114. package/dist/services/auth/types.d.ts +0 -192
  115. package/dist/services/auth/types.d.ts.map +0 -1
  116. package/dist/services/auth/types.js +0 -11
  117. package/dist/services/auth/types.js.map +0 -1
  118. package/dist/services/eval/api-reference.d.ts +0 -4
  119. package/dist/services/eval/api-reference.d.ts.map +0 -1
  120. package/dist/services/eval/api-reference.js +0 -121
  121. package/dist/services/eval/api-reference.js.map +0 -1
  122. package/dist/services/eval/events.d.ts +0 -93
  123. package/dist/services/eval/events.d.ts.map +0 -1
  124. package/dist/services/eval/events.js +0 -24
  125. package/dist/services/eval/events.js.map +0 -1
  126. package/dist/services/eval/get.d.ts +0 -36
  127. package/dist/services/eval/get.d.ts.map +0 -1
  128. package/dist/services/eval/get.js +0 -23
  129. package/dist/services/eval/get.js.map +0 -1
  130. package/dist/services/eval/index.d.ts +0 -6
  131. package/dist/services/eval/index.d.ts.map +0 -1
  132. package/dist/services/eval/index.js +0 -6
  133. package/dist/services/eval/index.js.map +0 -1
  134. package/dist/services/eval/list.d.ts +0 -50
  135. package/dist/services/eval/list.d.ts.map +0 -1
  136. package/dist/services/eval/list.js +0 -32
  137. package/dist/services/eval/list.js.map +0 -1
  138. package/dist/services/eval/run-get.d.ts +0 -48
  139. package/dist/services/eval/run-get.d.ts.map +0 -1
  140. package/dist/services/eval/run-get.js +0 -29
  141. package/dist/services/eval/run-get.js.map +0 -1
  142. package/dist/services/eval/run-list.d.ts +0 -70
  143. package/dist/services/eval/run-list.d.ts.map +0 -1
  144. package/dist/services/eval/run-list.js +0 -42
  145. package/dist/services/eval/run-list.js.map +0 -1
  146. package/dist/webrtc.d.ts +0 -243
  147. package/dist/webrtc.d.ts.map +0 -1
  148. package/dist/webrtc.js +0 -5
  149. package/dist/webrtc.js.map +0 -1
  150. package/dist/workbench-config.d.ts +0 -62
  151. package/dist/workbench-config.d.ts.map +0 -1
  152. package/dist/workbench-config.js +0 -58
  153. package/dist/workbench-config.js.map +0 -1
  154. package/dist/workbench.d.ts +0 -2
  155. package/dist/workbench.d.ts.map +0 -1
  156. package/dist/workbench.js +0 -2
  157. package/dist/workbench.js.map +0 -1
  158. package/src/services/auth/index.ts +0 -19
  159. package/src/services/auth/types.ts +0 -223
  160. package/src/services/eval/api-reference.ts +0 -124
  161. package/src/services/eval/events.ts +0 -92
  162. package/src/services/eval/get.ts +0 -33
  163. package/src/services/eval/index.ts +0 -29
  164. package/src/services/eval/list.ts +0 -49
  165. package/src/services/eval/run-get.ts +0 -39
  166. package/src/services/eval/run-list.ts +0 -59
  167. package/src/webrtc.ts +0 -259
  168. package/src/workbench-config.ts +0 -79
  169. package/src/workbench.ts +0 -1
@@ -1,16 +1,21 @@
1
1
  import type { Logger } from '../../logger.ts';
2
2
  import type { Readable, Writable } from 'node:stream';
3
3
  import { PassThrough } from 'node:stream';
4
+ import { finished } from 'node:stream/promises';
4
5
  import { z } from 'zod';
5
6
  import { APIClient, PaymentRequiredError } from '../api.ts';
6
7
  import { sandboxCreate } from './create.ts';
7
8
  import { sandboxDestroy } from './destroy.ts';
9
+ import { executionGet } from './execution.ts';
8
10
  import { sandboxGetStatus } from './getStatus.ts';
9
11
  import { ExecutionCancelledError, writeAndDrain } from './util.ts';
10
12
  import { SandboxRunOptionsSchema, type SandboxRunResult } from './types.ts';
11
13
  import { getServiceUrls } from '../config.ts';
12
14
 
13
15
  const timingLogsEnabled = false;
16
+ const EXECUTION_WAIT_DURATION = '5m';
17
+ const EXIT_CODE_FAST_WAIT_DURATION = '250ms';
18
+ const TERMINAL_EXECUTION_STATUSES = new Set(['completed', 'failed', 'timeout', 'cancelled']);
14
19
 
15
20
  /**
16
21
  * Creates a Writable stream that captures all chunks to a buffer array
@@ -73,8 +78,19 @@ export async function sandboxRun(
73
78
  let stdinStreamId: string | undefined;
74
79
  let stdinStreamUrl: string | undefined;
75
80
 
76
- // If stdin is provided and has data, create a stream for it
77
- if (stdin && region && apiKey) {
81
+ // Handle stdin stream configuration:
82
+ // - If stdin is "ignore", pass it through to skip stdin handling on server
83
+ // - If stdin is an explicit stream ID, use it directly
84
+ // - If stdin readable is provided, create a stream for it
85
+ const stdinConfig = options.stream?.stdin;
86
+ if (stdinConfig === 'ignore') {
87
+ stdinStreamId = 'ignore';
88
+ logger?.debug('stdin explicitly ignored');
89
+ } else if (stdinConfig && stdinConfig !== 'ignore') {
90
+ // User provided an explicit stream ID
91
+ stdinStreamId = stdinConfig;
92
+ logger?.debug('using provided stdin stream ID: %s', stdinStreamId);
93
+ } else if (stdin && region && apiKey) {
78
94
  const streamResult = await createStdinStream(region, apiKey, orgId, logger);
79
95
  stdinStreamId = streamResult.id;
80
96
  stdinStreamUrl = streamResult.url;
@@ -176,52 +192,46 @@ export async function sandboxRun(
176
192
  }
177
193
  }
178
194
 
179
- // Wait for streams to complete Pulse closes streams on sandbox termination (EOF).
180
- // This is our primary completion signal; no polling needed.
181
- logger?.debug('waiting for streams to complete...');
195
+ // Wait for execution completion in parallel with stream consumption. The old
196
+ // flow waited for stream EOF first and only then started polling for the
197
+ // final exit code, which adds avoidable tail latency now that create returns
198
+ // an execution ID immediately for oneshot sandboxes.
199
+ let finalExecution:
200
+ | {
201
+ exitCode?: number;
202
+ status: string;
203
+ }
204
+ | undefined;
205
+ if (createResponse.executionId) {
206
+ logger?.debug(
207
+ 'waiting for execution %s and %d stream(s) in parallel',
208
+ createResponse.executionId,
209
+ streamPromises.length
210
+ );
211
+ const completionPromise = waitForRunCompletion(
212
+ client,
213
+ sandboxId,
214
+ createResponse.executionId,
215
+ orgId,
216
+ signal,
217
+ logger,
218
+ started
219
+ );
182
220
 
183
- if (streamPromises.length > 0) {
184
- if (signal) {
185
- // Race streams against abort signal, cleaning up the listener
186
- // in all cases so an orphaned reject cannot fire after settlement.
187
- let onAbort: (() => void) | undefined;
188
- try {
189
- await Promise.race([
190
- Promise.allSettled(streamPromises),
191
- new Promise<never>((_, reject) => {
192
- onAbort = () => {
193
- abortController.abort();
194
- reject(
195
- new ExecutionCancelledError({
196
- message: 'Sandbox execution cancelled',
197
- sandboxId,
198
- })
199
- );
200
- };
201
- if (signal.aborted) {
202
- onAbort();
203
- } else {
204
- signal.addEventListener('abort', onAbort, { once: true });
205
- }
206
- }),
207
- ]);
208
- } finally {
209
- if (onAbort && signal) {
210
- signal.removeEventListener('abort', onAbort);
211
- }
212
- }
213
- } else {
214
- await Promise.allSettled(streamPromises);
215
- }
221
+ finalExecution = signal
222
+ ? await raceWithAbort(completionPromise, signal, abortController, sandboxId)
223
+ : await completionPromise;
224
+ await waitForStreamsToDrain(streamPromises, signal, abortController, sandboxId);
216
225
  } else {
217
- // No streams available (shouldn't happen for oneshot, but handle defensively).
218
- // Fall back to a single wait then check.
219
- logger?.debug('no streams to wait on, checking sandbox status directly');
226
+ logger?.debug(
227
+ 'missing executionId on create response, falling back to stream-first completion'
228
+ );
229
+ await waitForStreamsToDrain(streamPromises, signal, abortController, sandboxId);
220
230
  }
221
231
 
222
232
  if (timingLogsEnabled)
223
- console.error(`[TIMING] +${Date.now() - started}ms: all streams done, fetching exit code`);
224
- logger?.debug('streams completed, fetching final status');
233
+ console.error(`[TIMING] +${Date.now() - started}ms: completion wait finished`);
234
+ logger?.debug('completion wait finished, resolving final exit code');
225
235
 
226
236
  // Stream EOF means the sandbox is done — hadron only closes streams after the
227
237
  // container exits. Poll for the exit code with retries because the lifecycle
@@ -234,94 +244,108 @@ export async function sandboxRun(
234
244
  // linear 1s polling interval (not exponential backoff) so we don't overshoot
235
245
  // the window — 15 attempts × 1s = 15s total, which comfortably covers the
236
246
  // drain + lifecycle propagation delay.
237
- // Abort-aware sleep that rejects when the caller's signal fires.
238
- const abortAwareSleep = (ms: number): Promise<void> =>
239
- new Promise((resolve, reject) => {
240
- if (signal?.aborted) {
241
- reject(new DOMException('Aborted', 'AbortError'));
242
- return;
243
- }
244
- const timer = setTimeout(resolve, ms);
245
- signal?.addEventListener(
246
- 'abort',
247
- () => {
248
- clearTimeout(timer);
249
- reject(new DOMException('Aborted', 'AbortError'));
250
- },
251
- { once: true }
252
- );
253
- });
254
-
255
- let exitCode = 0;
256
- const maxStatusRetries = 15;
257
- const statusPollInterval = 1000;
247
+ let exitCode = finalExecution?.exitCode ?? 0;
258
248
  const statusPollStart = Date.now();
259
- for (let attempt = 0; attempt < maxStatusRetries; attempt++) {
260
- if (signal?.aborted) {
261
- break;
249
+ let shouldWaitForSandboxStatus = finalExecution?.exitCode == null;
250
+ let sandboxStatusReconciled = false;
251
+ if (finalExecution?.exitCode == null) {
252
+ if (createResponse.executionId && finalExecution?.status === 'completed') {
253
+ try {
254
+ const execution = await executionGet(client, {
255
+ executionId: createResponse.executionId,
256
+ orgId,
257
+ wait: EXIT_CODE_FAST_WAIT_DURATION,
258
+ signal,
259
+ });
260
+ if (execution.exitCode != null) {
261
+ exitCode = execution.exitCode;
262
+ finalExecution.exitCode = execution.exitCode;
263
+ shouldWaitForSandboxStatus = false;
264
+ logger?.debug(
265
+ '[run] exit code %d found from fast execution retry (+%dms)',
266
+ exitCode,
267
+ Date.now() - statusPollStart
268
+ );
269
+ }
270
+ } catch (err) {
271
+ if (!(err instanceof DOMException && err.name === 'AbortError')) {
272
+ logger?.debug(
273
+ '[run] fast execution exit code retry failed (+%dms): %s',
274
+ Date.now() - statusPollStart,
275
+ err
276
+ );
277
+ }
278
+ }
262
279
  }
280
+ }
281
+ if (shouldWaitForSandboxStatus) {
263
282
  try {
264
- const sandboxStatus = await sandboxGetStatus(client, { sandboxId, orgId });
283
+ const sandboxStatus = await sandboxGetStatus(client, {
284
+ sandboxId,
285
+ orgId,
286
+ waitForStatus: ['terminated', 'failed'],
287
+ waitMs: 15000,
288
+ });
265
289
  if (sandboxStatus.exitCode != null) {
266
290
  exitCode = sandboxStatus.exitCode;
291
+ sandboxStatusReconciled = true;
267
292
  logger?.debug(
268
- '[run] exit code %d found on attempt %d/%d (+%dms)',
293
+ '[run] exit code %d found after server-side wait (+%dms)',
269
294
  exitCode,
270
- attempt + 1,
271
- maxStatusRetries,
272
295
  Date.now() - statusPollStart
273
296
  );
274
- break;
275
297
  } else if (sandboxStatus.status === 'failed') {
276
298
  exitCode = 1;
299
+ sandboxStatusReconciled = true;
277
300
  logger?.debug(
278
- '[run] sandbox failed on attempt %d/%d (+%dms)',
279
- attempt + 1,
280
- maxStatusRetries,
301
+ '[run] sandbox failed after server-side wait (+%dms)',
281
302
  Date.now() - statusPollStart
282
303
  );
283
- break;
284
304
  } else if (sandboxStatus.status === 'terminated') {
285
- // Sandbox was destroyed. If exit code is missing, the
286
- // terminated event may have overwritten it. Stop polling —
287
- // no further updates will come.
305
+ sandboxStatusReconciled = true;
288
306
  logger?.debug(
289
- '[run] sandbox terminated without exit code on attempt %d/%d (+%dms)',
290
- attempt + 1,
291
- maxStatusRetries,
307
+ '[run] sandbox terminated without exit code after server-side wait (+%dms)',
308
+ Date.now() - statusPollStart
309
+ );
310
+ } else {
311
+ logger?.debug(
312
+ '[run] sandbox status wait expired with status=%s (+%dms)',
313
+ sandboxStatus.status,
292
314
  Date.now() - statusPollStart
293
315
  );
294
- break;
295
- }
296
- // Exit code not yet propagated — wait before next poll.
297
- if (attempt < maxStatusRetries - 1) {
298
- await abortAwareSleep(statusPollInterval);
299
316
  }
300
317
  } catch (err) {
301
- if (err instanceof DOMException && err.name === 'AbortError') {
302
- break;
303
- }
304
- // Transient failure (sandbox briefly unavailable, network error).
305
- // Retry instead of giving up — the lifecycle event may still arrive.
306
- logger?.debug(
307
- '[run] sandboxGetStatus attempt %d/%d failed (+%dms): %s',
308
- attempt + 1,
309
- maxStatusRetries,
310
- Date.now() - statusPollStart,
311
- err
312
- );
313
- if (attempt < maxStatusRetries - 1) {
314
- await abortAwareSleep(statusPollInterval);
318
+ if (!(err instanceof DOMException && err.name === 'AbortError')) {
319
+ logger?.debug(
320
+ '[run] sandboxGetStatus server-side wait failed (+%dms): %s',
321
+ Date.now() - statusPollStart,
322
+ err
323
+ );
315
324
  }
316
325
  }
317
326
  }
318
- if (exitCode === 0) {
327
+ if (
328
+ finalExecution &&
329
+ finalExecution?.exitCode == null &&
330
+ finalExecution?.status !== 'completed' &&
331
+ !sandboxStatusReconciled
332
+ ) {
333
+ exitCode = 1;
319
334
  logger?.debug(
320
- '[run] exit code polling finished with default 0 after %d attempts (+%dms)',
321
- maxStatusRetries,
322
- Date.now() - statusPollStart
335
+ '[run] using fallback exit code 1 for terminal status=%s after sandbox status reconciliation failed',
336
+ finalExecution?.status
323
337
  );
324
338
  }
339
+ if (exitCode === 0) {
340
+ if (finalExecution?.exitCode != null) {
341
+ logger?.debug('[run] using execution exit code 0 from long-poll result');
342
+ } else {
343
+ logger?.debug(
344
+ '[run] exit code wait finished with default 0 (+%dms)',
345
+ Date.now() - statusPollStart
346
+ );
347
+ }
348
+ }
325
349
 
326
350
  if (timingLogsEnabled)
327
351
  console.error(
@@ -352,6 +376,223 @@ export async function sandboxRun(
352
376
  }
353
377
  }
354
378
 
379
+ async function waitForRunCompletion(
380
+ client: APIClient,
381
+ sandboxId: string,
382
+ executionId: string,
383
+ orgId: string | undefined,
384
+ signal: AbortSignal | undefined,
385
+ logger: Logger | undefined,
386
+ started: number
387
+ ): Promise<{ exitCode?: number; status: string }> {
388
+ const completionAbortController = new AbortController();
389
+ let onAbort: (() => void) | undefined;
390
+ if (signal) {
391
+ onAbort = () => completionAbortController.abort(signal.reason);
392
+ if (signal.aborted) {
393
+ onAbort();
394
+ } else {
395
+ signal.addEventListener('abort', onAbort, { once: true });
396
+ }
397
+ }
398
+
399
+ try {
400
+ const completionSignal = completionAbortController.signal;
401
+ const executionPromise = waitForExecutionCompletion(
402
+ client,
403
+ executionId,
404
+ orgId,
405
+ completionSignal,
406
+ logger,
407
+ started
408
+ );
409
+ const statusPromise = waitForSandboxStatusCompletion(
410
+ client,
411
+ sandboxId,
412
+ orgId,
413
+ completionSignal,
414
+ logger,
415
+ started
416
+ ).catch((err) => {
417
+ if (completionSignal.aborted) {
418
+ throw err;
419
+ }
420
+ logger?.debug('[run] sandbox status completion wait failed: %s', err);
421
+ return new Promise<never>(() => {});
422
+ });
423
+
424
+ const result = await Promise.race([executionPromise, statusPromise]);
425
+ return result;
426
+ } finally {
427
+ if (onAbort && signal) {
428
+ signal.removeEventListener('abort', onAbort);
429
+ }
430
+ }
431
+ }
432
+
433
+ async function waitForExecutionCompletion(
434
+ client: APIClient,
435
+ executionId: string,
436
+ orgId: string | undefined,
437
+ signal: AbortSignal | undefined,
438
+ logger: Logger | undefined,
439
+ started: number
440
+ ): Promise<{ exitCode?: number; status: string }> {
441
+ while (true) {
442
+ if (signal?.aborted) {
443
+ throw new DOMException('Aborted', 'AbortError');
444
+ }
445
+
446
+ const result = await executionGet(client, {
447
+ executionId,
448
+ orgId,
449
+ wait: EXECUTION_WAIT_DURATION,
450
+ signal,
451
+ });
452
+ logger?.debug(
453
+ '[run] execution wait: id=%s status=%s exit=%s +%dms',
454
+ executionId,
455
+ result.status,
456
+ result.exitCode ?? 'undefined',
457
+ Date.now() - started
458
+ );
459
+
460
+ if (TERMINAL_EXECUTION_STATUSES.has(result.status)) {
461
+ return {
462
+ exitCode: result.exitCode,
463
+ status: result.status,
464
+ };
465
+ }
466
+ }
467
+ }
468
+
469
+ async function waitForSandboxStatusCompletion(
470
+ client: APIClient,
471
+ sandboxId: string,
472
+ orgId: string | undefined,
473
+ signal: AbortSignal | undefined,
474
+ logger: Logger | undefined,
475
+ started: number
476
+ ): Promise<{ exitCode?: number; status: string }> {
477
+ while (true) {
478
+ if (signal?.aborted) {
479
+ throw new DOMException('Aborted', 'AbortError');
480
+ }
481
+
482
+ const result = await sandboxGetStatus(client, {
483
+ sandboxId,
484
+ orgId,
485
+ waitForStatus: ['idle', 'terminated', 'failed'],
486
+ waitMs: 300000,
487
+ signal,
488
+ });
489
+ logger?.debug(
490
+ '[run] sandbox status wait: sandbox=%s status=%s exit=%s +%dms',
491
+ sandboxId,
492
+ result.status,
493
+ result.exitCode ?? 'undefined',
494
+ Date.now() - started
495
+ );
496
+
497
+ if (result.exitCode != null) {
498
+ return {
499
+ exitCode: result.exitCode,
500
+ status: 'completed',
501
+ };
502
+ }
503
+ if (result.status === 'failed') {
504
+ return {
505
+ exitCode: 1,
506
+ status: 'failed',
507
+ };
508
+ }
509
+ if (result.status === 'terminated') {
510
+ return {
511
+ status: 'completed',
512
+ };
513
+ }
514
+
515
+ await new Promise((resolve) => setTimeout(resolve, 25));
516
+ }
517
+ }
518
+
519
+ async function waitForStreamsToDrain(
520
+ streamPromises: Promise<void>[],
521
+ signal: AbortSignal | undefined,
522
+ abortController: AbortController,
523
+ sandboxId: string
524
+ ): Promise<void> {
525
+ if (streamPromises.length === 0) {
526
+ return;
527
+ }
528
+
529
+ if (signal) {
530
+ let onAbort: (() => void) | undefined;
531
+ try {
532
+ await Promise.race([
533
+ Promise.allSettled(streamPromises).then(() => undefined),
534
+ new Promise<never>((_, reject) => {
535
+ onAbort = () => {
536
+ abortController.abort();
537
+ reject(
538
+ new ExecutionCancelledError({
539
+ message: 'Sandbox execution cancelled',
540
+ sandboxId,
541
+ })
542
+ );
543
+ };
544
+ if (signal.aborted) {
545
+ onAbort();
546
+ } else {
547
+ signal.addEventListener('abort', onAbort, { once: true });
548
+ }
549
+ }),
550
+ ]);
551
+ } finally {
552
+ if (onAbort) {
553
+ signal.removeEventListener('abort', onAbort);
554
+ }
555
+ }
556
+ return;
557
+ }
558
+
559
+ await Promise.allSettled(streamPromises);
560
+ }
561
+
562
+ async function raceWithAbort<T>(
563
+ promise: Promise<T>,
564
+ signal: AbortSignal,
565
+ abortController: AbortController,
566
+ sandboxId: string
567
+ ): Promise<T> {
568
+ let onAbort: (() => void) | undefined;
569
+ try {
570
+ return await Promise.race([
571
+ promise,
572
+ new Promise<never>((_, reject) => {
573
+ onAbort = () => {
574
+ abortController.abort();
575
+ reject(
576
+ new ExecutionCancelledError({
577
+ message: 'Sandbox execution cancelled',
578
+ sandboxId,
579
+ })
580
+ );
581
+ };
582
+ if (signal.aborted) {
583
+ onAbort();
584
+ } else {
585
+ signal.addEventListener('abort', onAbort, { once: true });
586
+ }
587
+ }),
588
+ ]);
589
+ } finally {
590
+ if (onAbort) {
591
+ signal.removeEventListener('abort', onAbort);
592
+ }
593
+ }
594
+ }
595
+
355
596
  async function createStdinStream(
356
597
  region: string,
357
598
  apiKey: string,
@@ -526,6 +767,12 @@ async function streamUrlToWritable(
526
767
  // Signal end-of-stream to the tee/pipe chain so downstream
527
768
  // consumers (e.g. process.stdout pipe) know no more data is coming.
528
769
  writable.end();
770
+ if ('once' in writable) {
771
+ await finished(writable as NodeJS.WritableStream).catch(() => {
772
+ // Ignore finish errors here; the main read/write path already
773
+ // reported meaningful stream errors.
774
+ });
775
+ }
529
776
  } catch (err) {
530
777
  if (err instanceof Error && err.name === 'AbortError') {
531
778
  logger?.debug('[stream] aborted after %dms', Date.now() - streamStart);
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { StructuredError } from '../../error.ts';
3
3
  import { SortDirectionSchema } from '../pagination.ts';
4
+ import type { SandboxPauseResult } from './pause.ts';
4
5
 
5
6
  /**
6
7
  * Resource limits for a sandbox using Kubernetes-style units
@@ -274,6 +275,13 @@ export const SandboxTimeoutConfigSchema = z.object({
274
275
  .string()
275
276
  .optional()
276
277
  .describe('Maximum execution time per command (e.g., "5m", "1h")'),
278
+ /** Maximum duration a sandbox can remain paused before termination (e.g., "24h", "0" for infinite) */
279
+ paused: z
280
+ .string()
281
+ .optional()
282
+ .describe(
283
+ 'Maximum duration a sandbox can remain paused before termination (e.g., "24h", "0" for infinite)'
284
+ ),
277
285
  });
278
286
  export type SandboxTimeoutConfig = z.infer<typeof SandboxTimeoutConfigSchema>;
279
287
 
@@ -399,7 +407,7 @@ export const SandboxSchema = z.object({
399
407
  .describe('Set environment variables on the sandbox. Pass null to delete a variable.'),
400
408
  /** Pause the sandbox, creating a checkpoint of its current state. */
401
409
  pause: z
402
- .custom<() => Promise<void>>()
410
+ .custom<() => Promise<SandboxPauseResult>>()
403
411
  .describe('Pause the sandbox, creating a checkpoint of its current state.'),
404
412
  /** Resume the sandbox from a paused or evacuated state. */
405
413
  resume: z
@@ -592,6 +600,11 @@ export const SandboxInfoSchema = z.object({
592
600
  idle: z.string().optional().describe('Idle timeout duration (e.g., "10m0s")'),
593
601
  /** Execution timeout duration (e.g., "5m0s") */
594
602
  execution: z.string().optional().describe('Execution timeout duration (e.g., "5m0s")'),
603
+ /** Paused timeout duration (e.g., "24h0s", "0s" for infinite) */
604
+ paused: z
605
+ .string()
606
+ .optional()
607
+ .describe('Paused timeout duration (e.g., "24h0s", "0s" for infinite)'),
595
608
  })
596
609
  .optional()
597
610
  .describe('Timeout configuration for this sandbox'),
@@ -830,6 +843,8 @@ export const SnapshotCreateOptionsSchema = z.object({
830
843
  tag: z.string().optional().describe('Tag for the snapshot (defaults to "latest")'),
831
844
  /** Make the snapshot publicly accessible */
832
845
  public: z.boolean().optional().describe('Make the snapshot publicly accessible'),
846
+ /** Organization ID to use for CLI-authenticated requests */
847
+ orgId: z.string().optional().describe('Organization ID for CLI-authenticated requests'),
833
848
  });
834
849
  export type SnapshotCreateOptions = z.infer<typeof SnapshotCreateOptionsSchema>;
835
850
 
@@ -905,7 +920,7 @@ export interface SandboxService {
905
920
  list(params?: ListSandboxesParams): Promise<ListSandboxesResponse>;
906
921
  destroy(sandboxId: string): Promise<void>;
907
922
  /** Pause a running sandbox, creating a checkpoint of its current state. */
908
- pause(sandboxId: string): Promise<void>;
923
+ pause(sandboxId: string): Promise<SandboxPauseResult>;
909
924
  /** Resume a paused or evacuated sandbox from its checkpoint. */
910
925
  resume(sandboxId: string): Promise<void>;
911
926
  snapshot: SnapshotService;
@@ -40,11 +40,11 @@ export const StreamNamespaceEntrySchema = z.object({
40
40
  chunks: z.number().describe('number of chunks'),
41
41
  completed: z.boolean().describe('whether the stream upload is completed'),
42
42
  size_bytes: z.number().describe('size in bytes'),
43
- started_at: z.string().nullable().describe('ISO 8601 stream start timestamp'),
43
+ started_at: z.string().nullable().optional().describe('ISO 8601 stream start timestamp'),
44
44
  ended_at: z.string().nullable().describe('ISO 8601 stream end timestamp'),
45
45
  headers: z.record(z.string(), z.string()).nullable().optional().describe('stream headers'),
46
46
  metadata: z.record(z.string(), z.string()).nullable().optional().describe('stream metadata'),
47
- expires_at: z.string().nullable().describe('ISO 8601 expiration timestamp or null'),
47
+ expires_at: z.string().nullable().optional().describe('ISO 8601 expiration timestamp or null'),
48
48
  url: z.string().describe('public URL to access the stream'),
49
49
  });
50
50