@tangle-network/sandbox 0.60.2 → 0.60.6

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 (52) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-BDxby7zK.d.ts → agent-run-outcome-B7w8HpoL.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{browser-interactive-control-controller-C2qVGzQz.d.ts → browser-interactive-control-controller-C-3MDol8.d.ts} +1 -1
  10. package/dist/{client-BFilDKO8.d.ts → client-AXO7ykS7.d.ts} +5 -5
  11. package/dist/{client-p2T45dAv.js → client-qSyPPokh.js} +84 -355
  12. package/dist/collaboration/index.d.ts +1 -1
  13. package/dist/collaboration/index.js +1 -1
  14. package/dist/{collaboration-C1JAl5kE.js → collaboration-B7QeBrFQ.js} +1 -1
  15. package/dist/core.d.ts +6 -6
  16. package/dist/core.js +4 -4
  17. package/dist/{errors-CKl_BSlD.js → errors-D1JIX7Jm.js} +13 -1
  18. package/dist/{index-DGuTeptP.d.ts → index-BPt77jdR.d.ts} +88 -3
  19. package/dist/index.d.ts +13 -13
  20. package/dist/index.js +7 -7
  21. package/dist/intelligence/index.js +1 -1
  22. package/dist/interactive-control.d.ts +1 -1
  23. package/dist/{interactive-controller-DV1HT3NR.js → interactive-controller-f_ePJqoh.js} +14 -8
  24. package/dist/{interactive-controller-Dghv9yMk.d.ts → interactive-controller-iYddZt8b.d.ts} +2 -2
  25. package/dist/{line-application-DJYY1v8U.js → line-application-C2SuT1zK.js} +24 -0
  26. package/dist/{lines-T2D6xHHx.d.ts → lines-ggdLY7xy.d.ts} +37 -12
  27. package/dist/lines.d.ts +2 -2
  28. package/dist/lines.js +4 -5
  29. package/dist/{local-cli-auth-CdIM0B6p.js → local-cli-auth-D4T4wi9r.js} +1 -1
  30. package/dist/{mcp-local-BSvH4yAU.js → mcp-local-DjryqUiY.js} +1 -1
  31. package/dist/{preview-ZaYvOOXz.d.ts → preview-CAiSrOuZ.d.ts} +3 -3
  32. package/dist/runtime.d.ts +6 -6
  33. package/dist/runtime.js +2 -2
  34. package/dist/{sandbox-DeE2MDx9.js → sandbox-DF2Z1lqW.js} +128 -558
  35. package/dist/{sandbox-LRvBzGGm.d.ts → sandbox-DsJ3ZJdA.d.ts} +5 -5
  36. package/dist/secp256k1-CyKOxB5J.js +2619 -0
  37. package/dist/session-gateway/index.d.ts +31 -25
  38. package/dist/session-gateway/index.js +75 -79
  39. package/dist/tangle/index.d.ts +2 -2
  40. package/dist/tangle/index.js +2 -2
  41. package/dist/tangle-CDtwGZtf.js +2847 -0
  42. package/dist/{types-C9w6MdZB.d.ts → types-BbgO-4f8.d.ts} +6 -2
  43. package/dist/utils-ChcSLv53.js +170 -0
  44. package/package.json +8 -7
  45. package/dist/tangle-SNShua9T.js +0 -1146
  46. /package/dist/{cli-auth-bundle-gs7xEnA1.d.ts → cli-auth-bundle-CTia4WWs.d.ts} +0 -0
  47. /package/dist/{cli-auth-bundle-ChOdvrjd.js → cli-auth-bundle-DzbqR2nA.js} +0 -0
  48. /package/dist/{errors-C6dll8Qf.d.ts → errors-DS32ViPj.d.ts} +0 -0
  49. /package/dist/{index-BKhRnV0i.d.ts → index-BXcL8P-U.d.ts} +0 -0
  50. /package/dist/{index-BSCz2Q0v.d.ts → index-BoQeoNOD.d.ts} +0 -0
  51. /package/dist/{preview-operations-BLsclF88.js → preview-operations-DqSo-IBm.js} +0 -0
  52. /package/dist/{terminal-stream-C9jxoB07.d.ts → terminal-stream-BUMu8Oae.d.ts} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
2
- import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, l as SandboxRuntimeApi, m as TRACE_ID_HEADER, n as InteractiveSessionController, o as assertScopedTokenActive, p as waitForRetryAfter, r as TerminalStream, u as isRetryableCredentialRefusal, v as appendSessionIdQuery, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-DV1HT3NR.js";
3
- import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-CKl_BSlD.js";
2
+ import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, l as SandboxRuntimeApi, m as TRACE_ID_HEADER, n as InteractiveSessionController, o as assertScopedTokenActive, p as waitForRetryAfter, r as TerminalStream, u as isRetryableCredentialRefusal, v as appendSessionIdQuery, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-f_ePJqoh.js";
3
+ import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError, v as parseResponseError, y as readResponseJson } from "./errors-D1JIX7Jm.js";
4
4
  import { d as awaitWithAbort, f as combineAbortSignals, g as interactiveSessionStatusResponseSchema, h as interactiveSessionControlValidationResponseSchema, l as createInteractiveControlHolderId, m as interactiveSessionControlReleaseResponseSchema, p as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-BJf0P_J4.js";
5
5
  import { SandboxLines } from "./lines.js";
6
6
  import "./specs-CnqSWFNT-i2wJxPoD.js";
@@ -1334,10 +1334,7 @@ var SandboxInteractiveOperations = class {
1334
1334
  body: JSON.stringify(exactStart),
1335
1335
  ...requestOptions?.signal === void 0 ? {} : { signal: requestOptions.signal }
1336
1336
  });
1337
- if (!response.ok) {
1338
- const body = await response.text();
1339
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1340
- }
1337
+ if (!response.ok) throw await parseResponseError(response);
1341
1338
  const endpoint = `/agents/sessions/${encodeURIComponent(id)}/interactive`;
1342
1339
  const parsed = interactiveSessionStartResponseSchema.safeParse(await response.json());
1343
1340
  if (!parsed.success) throw new ServerError("Interactive session response has an invalid exact identity", 502, {
@@ -1369,11 +1366,7 @@ var SandboxInteractiveOperations = class {
1369
1366
  body: JSON.stringify(exactCommand),
1370
1367
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1371
1368
  });
1372
- if (!response.ok) {
1373
- const body = await response.text();
1374
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1375
- }
1376
- const parsed = interactiveSessionPromptResponseSchema.safeParse(await response.json());
1369
+ const parsed = interactiveSessionPromptResponseSchema.safeParse(await readResponseJson(response));
1377
1370
  if (!parsed.success) throw new ServerError("Interactive prompt acknowledgement is invalid", 502, {
1378
1371
  endpoint,
1379
1372
  origin: "runtime"
@@ -1399,11 +1392,7 @@ var SandboxInteractiveOperations = class {
1399
1392
  body: JSON.stringify(exactRequest),
1400
1393
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1401
1394
  });
1402
- if (!response.ok) {
1403
- const body = await response.text();
1404
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1405
- }
1406
- const parsed = interactiveSessionControlClaimResponseSchema.safeParse(await response.json());
1395
+ const parsed = interactiveSessionControlClaimResponseSchema.safeParse(await readResponseJson(response));
1407
1396
  if (!parsed.success) throw new ServerError("Interactive control claim acknowledgement is invalid", 502, {
1408
1397
  endpoint,
1409
1398
  origin: "runtime"
@@ -1432,11 +1421,7 @@ var SandboxInteractiveOperations = class {
1432
1421
  }),
1433
1422
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1434
1423
  });
1435
- if (!response.ok) {
1436
- const body = await response.text();
1437
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1438
- }
1439
- if (!interactiveSessionControlReleaseResponseSchema.safeParse(await response.json()).success) throw new ServerError("Interactive control release response is invalid", 502, {
1424
+ if (!interactiveSessionControlReleaseResponseSchema.safeParse(await readResponseJson(response)).success) throw new ServerError("Interactive control release response is invalid", 502, {
1440
1425
  endpoint,
1441
1426
  origin: "runtime"
1442
1427
  });
@@ -1460,11 +1445,7 @@ var SandboxInteractiveOperations = class {
1460
1445
  }),
1461
1446
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1462
1447
  });
1463
- if (!response.ok) {
1464
- const body = await response.text();
1465
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1466
- }
1467
- if (!interactiveSessionControlValidationResponseSchema.safeParse(await response.json()).success) throw new ServerError("Interactive control validation response is invalid", 502, {
1448
+ if (!interactiveSessionControlValidationResponseSchema.safeParse(await readResponseJson(response)).success) throw new ServerError("Interactive control validation response is invalid", 502, {
1468
1449
  endpoint,
1469
1450
  origin: "runtime"
1470
1451
  });
@@ -1479,11 +1460,7 @@ var SandboxInteractiveOperations = class {
1479
1460
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1480
1461
  });
1481
1462
  if (response.status === 404) return null;
1482
- if (!response.ok) {
1483
- const body = await response.text();
1484
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1485
- }
1486
- const parsed = interactiveSessionStatusResponseSchema.safeParse(await response.json());
1463
+ const parsed = interactiveSessionStatusResponseSchema.safeParse(await readResponseJson(response));
1487
1464
  if (!parsed.success) throw new ServerError("Interactive status response has an invalid exact identity", 502, {
1488
1465
  endpoint,
1489
1466
  origin: "runtime"
@@ -1509,11 +1486,7 @@ var SandboxInteractiveOperations = class {
1509
1486
  body: JSON.stringify(exactCommand),
1510
1487
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1511
1488
  });
1512
- if (!response.ok) {
1513
- const body = await response.text();
1514
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1515
- }
1516
- const parsed = interactiveSessionStopResponseSchema.safeParse(await response.json());
1489
+ const parsed = interactiveSessionStopResponseSchema.safeParse(await readResponseJson(response));
1517
1490
  if (!parsed.success) throw new ServerError("Interactive stop acknowledgement is invalid", 502, {
1518
1491
  endpoint,
1519
1492
  origin: "runtime"
@@ -1538,11 +1511,7 @@ var SandboxInteractiveOperations = class {
1538
1511
  body: JSON.stringify({ ref: exactRef }),
1539
1512
  ...options?.signal === void 0 ? {} : { signal: options.signal }
1540
1513
  });
1541
- if (!response.ok) {
1542
- const body = await response.text();
1543
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1544
- }
1545
- const parsed = interactiveSessionStopResponseSchema.safeParse(await response.json());
1514
+ const parsed = interactiveSessionStopResponseSchema.safeParse(await readResponseJson(response));
1546
1515
  if (!parsed.success) throw new ServerError("Interactive lifecycle stop acknowledgement is invalid", 502, {
1547
1516
  endpoint,
1548
1517
  origin: "runtime"
@@ -3496,12 +3465,7 @@ var SandboxInstance = class SandboxInstance {
3496
3465
  if (options?.ttlMinutes) params.set("ttlMinutes", String(options.ttlMinutes));
3497
3466
  const qs = params.toString();
3498
3467
  const path = `/v1/sandboxes/${this.id}/mcp${qs ? `?${qs}` : ""}`;
3499
- const response = await this.client.fetch(path);
3500
- if (!response.ok) {
3501
- const body = await response.text();
3502
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3503
- }
3504
- return await response.json();
3468
+ return await readResponseJson(await this.client.fetch(path));
3505
3469
  }
3506
3470
  /**
3507
3471
  * Refresh sandbox information from the server.
@@ -3526,12 +3490,7 @@ var SandboxInstance = class SandboxInstance {
3526
3490
  sandboxStatusObservedAt.set(this, Date.now());
3527
3491
  return;
3528
3492
  }
3529
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}`, ...direct?.kind === "fallback" ? [{ headers: this.directRead.fallbackHeaders(direct.reason) }] : []);
3530
- if (!response.ok) {
3531
- const body = await response.text();
3532
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3533
- }
3534
- const data = await response.json();
3493
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}`, ...direct?.kind === "fallback" ? [{ headers: this.directRead.fallbackHeaders(direct.reason) }] : []));
3535
3494
  this.directRead.adopt(data);
3536
3495
  this.info = this.parseInfo(data, this.info);
3537
3496
  sandboxStatusObservedAt.set(this, Date.now());
@@ -3619,7 +3578,7 @@ var SandboxInstance = class SandboxInstance {
3619
3578
  * ```
3620
3579
  */
3621
3580
  async collaborate(path, options) {
3622
- const response = await this.client.fetch("/v1/collaboration/bootstrap", {
3581
+ return await readResponseJson(await this.client.fetch("/v1/collaboration/bootstrap", {
3623
3582
  method: "POST",
3624
3583
  headers: { "Content-Type": "application/json" },
3625
3584
  body: JSON.stringify({
@@ -3627,12 +3586,7 @@ var SandboxInstance = class SandboxInstance {
3627
3586
  path,
3628
3587
  access: options?.access ?? "write"
3629
3588
  })
3630
- });
3631
- if (!response.ok) {
3632
- const body = await response.text();
3633
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3634
- }
3635
- return await response.json();
3589
+ }));
3636
3590
  }
3637
3591
  /**
3638
3592
  * Refresh a collaboration token for an existing document session.
@@ -3642,7 +3596,7 @@ var SandboxInstance = class SandboxInstance {
3642
3596
  * token — cannot be escalated (read stays read, write stays write).
3643
3597
  */
3644
3598
  async refreshCollaborationToken(documentId, currentToken) {
3645
- const response = await this.client.fetch("/v1/collaboration/token", {
3599
+ return await readResponseJson(await this.client.fetch("/v1/collaboration/token", {
3646
3600
  method: "POST",
3647
3601
  headers: { "Content-Type": "application/json" },
3648
3602
  body: JSON.stringify({
@@ -3650,12 +3604,7 @@ var SandboxInstance = class SandboxInstance {
3650
3604
  documentId,
3651
3605
  currentToken
3652
3606
  })
3653
- });
3654
- if (!response.ok) {
3655
- const body = await response.text();
3656
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3657
- }
3658
- return await response.json();
3607
+ }));
3659
3608
  }
3660
3609
  /**
3661
3610
  * Get SSH credentials for connecting to the sandbox.
@@ -3685,7 +3634,7 @@ var SandboxInstance = class SandboxInstance {
3685
3634
  await this.ensureRunning(options?.signal);
3686
3635
  const timeoutMs = options?.timeoutMs ?? EXEC_DEFAULT_TIMEOUT_MS;
3687
3636
  if (!Number.isInteger(timeoutMs) || timeoutMs < EXEC_MIN_TIMEOUT_MS || timeoutMs > EXEC_MAX_TIMEOUT_MS) throw new ValidationError(`exec timeoutMs must be an integer between ${EXEC_MIN_TIMEOUT_MS} and ${EXEC_MAX_TIMEOUT_MS}`);
3688
- const response = await this.runtimeFetch("/process/spawn", {
3637
+ const result = (await readResponseJson(await this.runtimeFetch("/process/spawn", {
3689
3638
  method: "POST",
3690
3639
  headers,
3691
3640
  ...options?.signal ? { signal: options.signal } : {},
@@ -3697,12 +3646,7 @@ var SandboxInstance = class SandboxInstance {
3697
3646
  timeoutMs,
3698
3647
  blocking: true
3699
3648
  })
3700
- }, { timeoutMs: timeoutMs + EXEC_TRANSPORT_MARGIN_MS });
3701
- if (!response.ok) {
3702
- const body = await response.text();
3703
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3704
- }
3705
- const result = (await response.json()).data;
3649
+ }, { timeoutMs: timeoutMs + EXEC_TRANSPORT_MARGIN_MS }))).data;
3706
3650
  if (!result || typeof result.exitCode !== "number" || typeof result.stdout !== "string" || typeof result.stderr !== "string") throw new ServerError("Sandbox process response was malformed", 502);
3707
3651
  return {
3708
3652
  exitCode: result.exitCode,
@@ -3741,7 +3685,7 @@ var SandboxInstance = class SandboxInstance {
3741
3685
  const headers = sessionHeaders(options?.sessionId) ?? {};
3742
3686
  await this.ensureRunning();
3743
3687
  if (options?.idempotencyKey) headers["X-Idempotency-Key"] = options.idempotencyKey;
3744
- const response = await this.runtimeFetch("/code/exec", {
3688
+ const payload = await readResponseJson(await this.runtimeFetch("/code/exec", {
3745
3689
  method: "POST",
3746
3690
  headers,
3747
3691
  body: JSON.stringify({
@@ -3751,12 +3695,7 @@ var SandboxInstance = class SandboxInstance {
3751
3695
  env: options?.env,
3752
3696
  cwd: options?.cwd
3753
3697
  })
3754
- });
3755
- if (!response.ok) {
3756
- const body = await response.text();
3757
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3758
- }
3759
- const payload = await response.json();
3698
+ }));
3760
3699
  if (!payload.success || !payload.data) throw new Error(payload.error?.message ?? "runCode failed without a typed error");
3761
3700
  return payload.data;
3762
3701
  }
@@ -3784,10 +3723,7 @@ var SandboxInstance = class SandboxInstance {
3784
3723
  encoding: "utf8"
3785
3724
  })
3786
3725
  });
3787
- if (!response.ok) {
3788
- const body = await response.text();
3789
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3790
- }
3726
+ if (!response.ok) throw await parseResponseError(response);
3791
3727
  return parseTextFileReadResponse(await response.text());
3792
3728
  }
3793
3729
  /**
@@ -3811,7 +3747,7 @@ var SandboxInstance = class SandboxInstance {
3811
3747
  const params = new URLSearchParams();
3812
3748
  appendSessionIdQuery(params, options?.sessionId);
3813
3749
  const query = params.toString();
3814
- const response = await this.runtimeFetch(`/files/write${query ? `?${query}` : ""}`, {
3750
+ const data = await readResponseJson(await this.runtimeFetch(`/files/write${query ? `?${query}` : ""}`, {
3815
3751
  method: "POST",
3816
3752
  body: JSON.stringify({
3817
3753
  path,
@@ -3821,12 +3757,7 @@ var SandboxInstance = class SandboxInstance {
3821
3757
  expectedHash: options?.ifHash,
3822
3758
  ifAbsent: options?.ifAbsent
3823
3759
  })
3824
- });
3825
- if (!response.ok) {
3826
- const body = await response.text();
3827
- throw parseErrorResponse(response.status, body, void 0, response.headers);
3828
- }
3829
- const data = await response.json();
3760
+ }));
3830
3761
  if (!data.data) throw new ServerError("Invalid file write response: missing data", 502);
3831
3762
  this.assertWritePreconditions(data.data, {
3832
3763
  expectedHash: options?.ifHash,
@@ -4429,10 +4360,7 @@ var SandboxInstance = class SandboxInstance {
4429
4360
  */
4430
4361
  async *events(options) {
4431
4362
  const response = await this.client.fetch(`/v1/sandboxes/${this.id}/events`, { signal: options?.signal });
4432
- if (!response.ok) {
4433
- const body = await response.text();
4434
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4435
- }
4363
+ if (!response.ok) throw await parseResponseError(response);
4436
4364
  for await (const event of this.parseSSEStream(response, options?.signal)) {
4437
4365
  if (options?.eventTypes && !options.eventTypes.includes(event.type)) continue;
4438
4366
  yield event;
@@ -4441,12 +4369,7 @@ var SandboxInstance = class SandboxInstance {
4441
4369
  async trace(options = {}) {
4442
4370
  const query = new URLSearchParams();
4443
4371
  if (options.includeIntelligence === true) query.set("includeIntelligence", "true");
4444
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/trace${query.size ? `?${query}` : ""}`);
4445
- if (!response.ok) {
4446
- const body = await response.text();
4447
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4448
- }
4449
- return await response.json();
4372
+ return await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/trace${query.size ? `?${query}` : ""}`));
4450
4373
  }
4451
4374
  async intelligence() {
4452
4375
  const intelligence = (await this.trace({ includeIntelligence: true })).intelligence;
@@ -4578,7 +4501,7 @@ var SandboxInstance = class SandboxInstance {
4578
4501
  */
4579
4502
  async *search(pattern, options) {
4580
4503
  await this.ensureRunning();
4581
- const response = await this.runtimeFetch("/search", {
4504
+ const matches = (await readResponseJson(await this.runtimeFetch("/search", {
4582
4505
  method: "POST",
4583
4506
  body: JSON.stringify({
4584
4507
  pattern,
@@ -4588,12 +4511,7 @@ var SandboxInstance = class SandboxInstance {
4588
4511
  ignoreCase: options?.ignoreCase,
4589
4512
  context: options?.context
4590
4513
  })
4591
- });
4592
- if (!response.ok) {
4593
- const body = await response.text();
4594
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4595
- }
4596
- const matches = (await response.json()).matches ?? [];
4514
+ }))).matches ?? [];
4597
4515
  for (const match of matches) yield {
4598
4516
  path: match.path,
4599
4517
  line: match.line,
@@ -4741,12 +4659,7 @@ var SandboxInstance = class SandboxInstance {
4741
4659
  }
4742
4660
  async gitStatus() {
4743
4661
  await this.ensureRunning();
4744
- const response = await this.runtimeFetch("/git/status", { method: "GET" });
4745
- if (!response.ok) {
4746
- const body = await response.text();
4747
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4748
- }
4749
- const data = await response.json();
4662
+ const data = await readResponseJson(await this.runtimeFetch("/git/status", { method: "GET" }));
4750
4663
  const isRepo = data.isRepo ?? true;
4751
4664
  return {
4752
4665
  isRepo,
@@ -4762,12 +4675,7 @@ var SandboxInstance = class SandboxInstance {
4762
4675
  }
4763
4676
  async gitLog(limit = 10) {
4764
4677
  await this.ensureRunning();
4765
- const response = await this.runtimeFetch(`/git/log?limit=${limit}`, { method: "GET" });
4766
- if (!response.ok) {
4767
- const body = await response.text();
4768
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4769
- }
4770
- return ((await response.json()).commits ?? []).map((c) => ({
4678
+ return ((await readResponseJson(await this.runtimeFetch(`/git/log?limit=${limit}`, { method: "GET" }))).commits ?? []).map((c) => ({
4771
4679
  sha: c.sha,
4772
4680
  shortSha: c.sha.slice(0, 7),
4773
4681
  message: c.message,
@@ -4779,12 +4687,7 @@ var SandboxInstance = class SandboxInstance {
4779
4687
  async gitDiff(ref) {
4780
4688
  await this.ensureRunning();
4781
4689
  const url = ref ? `/git/diff?ref=${encodeURIComponent(ref)}` : "/git/diff";
4782
- const response = await this.runtimeFetch(url, { method: "GET" });
4783
- if (!response.ok) {
4784
- const body = await response.text();
4785
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4786
- }
4787
- const data = await response.json();
4690
+ const data = await readResponseJson(await this.runtimeFetch(url, { method: "GET" }));
4788
4691
  return {
4789
4692
  files: data.files ?? [],
4790
4693
  additions: data.additions ?? 0,
@@ -4798,25 +4701,17 @@ var SandboxInstance = class SandboxInstance {
4798
4701
  method: "POST",
4799
4702
  body: JSON.stringify({ paths })
4800
4703
  });
4801
- if (!response.ok) {
4802
- const body = await response.text();
4803
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4804
- }
4704
+ if (!response.ok) throw await parseResponseError(response);
4805
4705
  }
4806
4706
  async gitCommit(message, options) {
4807
4707
  await this.ensureRunning();
4808
- const response = await this.runtimeFetch("/git/commit", {
4708
+ const data = await readResponseJson(await this.runtimeFetch("/git/commit", {
4809
4709
  method: "POST",
4810
4710
  body: JSON.stringify({
4811
4711
  message,
4812
4712
  amend: options?.amend
4813
4713
  })
4814
- });
4815
- if (!response.ok) {
4816
- const body = await response.text();
4817
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4818
- }
4819
- const data = await response.json();
4714
+ }));
4820
4715
  return {
4821
4716
  sha: data.sha,
4822
4717
  shortSha: data.sha.slice(0, 7),
@@ -4832,10 +4727,7 @@ var SandboxInstance = class SandboxInstance {
4832
4727
  method: "POST",
4833
4728
  body: JSON.stringify({ force: options?.force })
4834
4729
  });
4835
- if (!response.ok) {
4836
- const body = await response.text();
4837
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4838
- }
4730
+ if (!response.ok) throw await parseResponseError(response);
4839
4731
  }
4840
4732
  async gitPull(options) {
4841
4733
  await this.ensureRunning();
@@ -4843,19 +4735,11 @@ var SandboxInstance = class SandboxInstance {
4843
4735
  method: "POST",
4844
4736
  body: JSON.stringify({ rebase: options?.rebase })
4845
4737
  });
4846
- if (!response.ok) {
4847
- const body = await response.text();
4848
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4849
- }
4738
+ if (!response.ok) throw await parseResponseError(response);
4850
4739
  }
4851
4740
  async gitBranches() {
4852
4741
  await this.ensureRunning();
4853
- const response = await this.runtimeFetch("/git/branches", { method: "GET" });
4854
- if (!response.ok) {
4855
- const body = await response.text();
4856
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4857
- }
4858
- return (await response.json()).branches ?? [];
4742
+ return (await readResponseJson(await this.runtimeFetch("/git/branches", { method: "GET" }))).branches ?? [];
4859
4743
  }
4860
4744
  async gitCheckout(ref, options) {
4861
4745
  await this.ensureRunning();
@@ -4866,10 +4750,7 @@ var SandboxInstance = class SandboxInstance {
4866
4750
  create: options?.create
4867
4751
  })
4868
4752
  });
4869
- if (!response.ok) {
4870
- const body = await response.text();
4871
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4872
- }
4753
+ if (!response.ok) throw await parseResponseError(response);
4873
4754
  }
4874
4755
  /**
4875
4756
  * Tools capability object for managing language runtimes.
@@ -4988,10 +4869,7 @@ var SandboxInstance = class SandboxInstance {
4988
4869
  method: "GET",
4989
4870
  signal
4990
4871
  });
4991
- if (!response.ok) {
4992
- const body = await response.text();
4993
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4994
- }
4872
+ if (!response.ok) throw await parseResponseError(response);
4995
4873
  return response;
4996
4874
  }, localPath, options);
4997
4875
  }
@@ -5012,10 +4890,7 @@ var SandboxInstance = class SandboxInstance {
5012
4890
  body: formData,
5013
4891
  headers: {}
5014
4892
  });
5015
- if (!response.ok) {
5016
- const body = await response.text();
5017
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5018
- }
4893
+ if (!response.ok) throw await parseResponseError(response);
5019
4894
  } finally {
5020
4895
  await fs.unlink(tempTarPath).catch(() => {});
5021
4896
  }
@@ -5026,10 +4901,7 @@ var SandboxInstance = class SandboxInstance {
5026
4901
  const path = await import("node:path");
5027
4902
  const { execSync } = await import("node:child_process");
5028
4903
  const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/download-dir", remoteDir), { method: "GET" });
5029
- if (!response.ok) {
5030
- const body = await response.text();
5031
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5032
- }
4904
+ if (!response.ok) throw await parseResponseError(response);
5033
4905
  const tempDir = await fs.mkdtemp(path.join((await import("node:os")).tmpdir(), "download-"));
5034
4906
  const tempTarPath = path.join(tempDir, "archive.tar.gz");
5035
4907
  try {
@@ -5055,12 +4927,7 @@ var SandboxInstance = class SandboxInstance {
5055
4927
  const query = params.toString();
5056
4928
  const basePath = runtimeFilesystemPath("/fs/list", path);
5057
4929
  const url = query ? `${basePath}?${query}` : basePath;
5058
- const response = await this.runtimeFetch(url, { method: "GET" });
5059
- if (!response.ok) {
5060
- const body = await response.text();
5061
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5062
- }
5063
- return ((await response.json()).data?.entries ?? []).map((e) => ({
4930
+ return ((await readResponseJson(await this.runtimeFetch(url, { method: "GET" }))).data?.entries ?? []).map((e) => ({
5064
4931
  name: e.name,
5065
4932
  path: e.path,
5066
4933
  size: e.size,
@@ -5076,12 +4943,7 @@ var SandboxInstance = class SandboxInstance {
5076
4943
  }
5077
4944
  async fsStat(path) {
5078
4945
  await this.ensureRunning();
5079
- const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/stat", path), { method: "GET" });
5080
- if (!response.ok) {
5081
- const body = await response.text();
5082
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5083
- }
5084
- const e = (await response.json()).data;
4946
+ const e = (await readResponseJson(await this.runtimeFetch(runtimeFilesystemPath("/fs/stat", path), { method: "GET" }))).data;
5085
4947
  return {
5086
4948
  name: e.name,
5087
4949
  path: e.path,
@@ -5106,20 +4968,14 @@ var SandboxInstance = class SandboxInstance {
5106
4968
  method: "POST",
5107
4969
  body: JSON.stringify({ path })
5108
4970
  });
5109
- if (!response.ok) {
5110
- const body = await response.text();
5111
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5112
- }
4971
+ if (!response.ok) throw await parseResponseError(response);
5113
4972
  return;
5114
4973
  }
5115
4974
  const query = params.toString();
5116
4975
  const basePath = runtimeFilesystemPath("/fs", path);
5117
4976
  const url = query ? `${basePath}?${query}` : basePath;
5118
4977
  const response = await this.runtimeFetch(url, { method: "DELETE" });
5119
- if (!response.ok) {
5120
- const body = await response.text();
5121
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5122
- }
4978
+ if (!response.ok) throw await parseResponseError(response);
5123
4979
  }
5124
4980
  async fsRename(sourcePath, destinationPath, options) {
5125
4981
  return this.runtime.renameFile(sourcePath, destinationPath, options);
@@ -5132,19 +4988,11 @@ var SandboxInstance = class SandboxInstance {
5132
4988
  const basePath = runtimeFilesystemPath("/fs/mkdir", path);
5133
4989
  const url = query ? `${basePath}?${query}` : basePath;
5134
4990
  const response = await this.runtimeFetch(url, { method: "POST" });
5135
- if (!response.ok) {
5136
- const body = await response.text();
5137
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5138
- }
4991
+ if (!response.ok) throw await parseResponseError(response);
5139
4992
  }
5140
4993
  async fsExists(path) {
5141
4994
  await this.ensureRunning();
5142
- const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/exists", path), { method: "GET" });
5143
- if (!response.ok) {
5144
- const body = await response.text();
5145
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5146
- }
5147
- return (await response.json()).data?.exists === true;
4995
+ return (await readResponseJson(await this.runtimeFetch(runtimeFilesystemPath("/fs/exists", path), { method: "GET" }))).data?.exists === true;
5148
4996
  }
5149
4997
  /**
5150
4998
  * Permissions manager for multi-user access control.
@@ -5180,12 +5028,7 @@ var SandboxInstance = class SandboxInstance {
5180
5028
  }
5181
5029
  async permissionsList() {
5182
5030
  await this.ensureRunning();
5183
- const response = await this.runtimeFetch("/permissions/users", { method: "GET" });
5184
- if (!response.ok) {
5185
- const body = await response.text();
5186
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5187
- }
5188
- return ((await response.json()).users ?? []).map((u) => ({
5031
+ return ((await readResponseJson(await this.runtimeFetch("/permissions/users", { method: "GET" }))).users ?? []).map((u) => ({
5189
5032
  userId: u.userId,
5190
5033
  username: u.username,
5191
5034
  homeDir: u.homeDir,
@@ -5200,11 +5043,7 @@ var SandboxInstance = class SandboxInstance {
5200
5043
  await this.ensureRunning();
5201
5044
  const response = await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}`, { method: "GET" });
5202
5045
  if (response.status === 404) return null;
5203
- if (!response.ok) {
5204
- const body = await response.text();
5205
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5206
- }
5207
- const u = await response.json();
5046
+ const u = await readResponseJson(response);
5208
5047
  return {
5209
5048
  userId: u.userId,
5210
5049
  username: u.username,
@@ -5218,15 +5057,10 @@ var SandboxInstance = class SandboxInstance {
5218
5057
  }
5219
5058
  async permissionsAdd(options) {
5220
5059
  await this.ensureRunning();
5221
- const response = await this.runtimeFetch("/permissions/users", {
5060
+ const u = await readResponseJson(await this.runtimeFetch("/permissions/users", {
5222
5061
  method: "POST",
5223
5062
  body: JSON.stringify(options)
5224
- });
5225
- if (!response.ok) {
5226
- const body = await response.text();
5227
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5228
- }
5229
- const u = await response.json();
5063
+ }));
5230
5064
  return {
5231
5065
  userId: u.userId,
5232
5066
  username: u.username,
@@ -5240,15 +5074,10 @@ var SandboxInstance = class SandboxInstance {
5240
5074
  }
5241
5075
  async permissionsUpdate(userId, options) {
5242
5076
  await this.ensureRunning();
5243
- const response = await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}`, {
5077
+ const u = await readResponseJson(await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}`, {
5244
5078
  method: "PATCH",
5245
5079
  body: JSON.stringify(options)
5246
- });
5247
- if (!response.ok) {
5248
- const body = await response.text();
5249
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5250
- }
5251
- const u = await response.json();
5080
+ }));
5252
5081
  return {
5253
5082
  userId: u.userId,
5254
5083
  username: u.username,
@@ -5267,10 +5096,7 @@ var SandboxInstance = class SandboxInstance {
5267
5096
  const query = params.toString();
5268
5097
  const path = query ? `/permissions/users/${encodeURIComponent(userId)}?${query}` : `/permissions/users/${encodeURIComponent(userId)}`;
5269
5098
  const response = await this.runtimeFetch(path, { method: "DELETE" });
5270
- if (!response.ok) {
5271
- const body = await response.text();
5272
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5273
- }
5099
+ if (!response.ok) throw await parseResponseError(response);
5274
5100
  }
5275
5101
  async permissionsSetAccessPolicies(userId, rules) {
5276
5102
  await this.ensureRunning();
@@ -5278,34 +5104,21 @@ var SandboxInstance = class SandboxInstance {
5278
5104
  method: "PUT",
5279
5105
  body: JSON.stringify({ rules })
5280
5106
  });
5281
- if (!response.ok) {
5282
- const body = await response.text();
5283
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5284
- }
5107
+ if (!response.ok) throw await parseResponseError(response);
5285
5108
  }
5286
5109
  async permissionsGetAccessPolicies(userId) {
5287
5110
  await this.ensureRunning();
5288
- const response = await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}/policies`, { method: "GET" });
5289
- if (!response.ok) {
5290
- const body = await response.text();
5291
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5292
- }
5293
- return (await response.json()).rules ?? [];
5111
+ return (await readResponseJson(await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}/policies`, { method: "GET" }))).rules ?? [];
5294
5112
  }
5295
5113
  async permissionsCheckAccess(userId, path, action) {
5296
5114
  await this.ensureRunning();
5297
- const response = await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}/check`, {
5115
+ return (await readResponseJson(await this.runtimeFetch(`/permissions/users/${encodeURIComponent(userId)}/check`, {
5298
5116
  method: "POST",
5299
5117
  body: JSON.stringify({
5300
5118
  path,
5301
5119
  action
5302
5120
  })
5303
- });
5304
- if (!response.ok) {
5305
- const body = await response.text();
5306
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5307
- }
5308
- return (await response.json()).allowed === true;
5121
+ }))).allowed === true;
5309
5122
  }
5310
5123
  /**
5311
5124
  * Backend manager for runtime agent configuration.
@@ -5351,21 +5164,11 @@ var SandboxInstance = class SandboxInstance {
5351
5164
  }
5352
5165
  async backendStatus() {
5353
5166
  await this.ensureRunning();
5354
- const response = await this.runtimeFetch("/backend", { method: "GET" });
5355
- if (!response.ok) {
5356
- const body = await response.text();
5357
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5358
- }
5359
- return await response.json();
5167
+ return await readResponseJson(await this.runtimeFetch("/backend", { method: "GET" }));
5360
5168
  }
5361
5169
  async backendGetMcpStatus() {
5362
5170
  await this.ensureRunning();
5363
- const response = await this.runtimeFetch("/backend/mcp", { method: "GET" });
5364
- if (!response.ok) {
5365
- const body = await response.text();
5366
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5367
- }
5368
- return (await response.json()).servers ?? {};
5171
+ return (await readResponseJson(await this.runtimeFetch("/backend/mcp", { method: "GET" }))).servers ?? {};
5369
5172
  }
5370
5173
  async backendUpdateConfig(config) {
5371
5174
  await this.ensureRunning();
@@ -5373,19 +5176,11 @@ var SandboxInstance = class SandboxInstance {
5373
5176
  method: "POST",
5374
5177
  body: JSON.stringify(config)
5375
5178
  });
5376
- if (!response.ok) {
5377
- const body = await response.text();
5378
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5379
- }
5179
+ if (!response.ok) throw await parseResponseError(response);
5380
5180
  }
5381
5181
  async backendControlData(path) {
5382
5182
  await this.ensureRunning();
5383
- const response = await this.runtimeFetch(path, { method: "GET" });
5384
- if (!response.ok) {
5385
- const body = await response.text();
5386
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5387
- }
5388
- const payload = await response.json();
5183
+ const payload = await readResponseJson(await this.runtimeFetch(path, { method: "GET" }));
5389
5184
  if (!payload || typeof payload !== "object" || !("data" in payload)) throw new ServerError("Backend control response missing data", 502, {
5390
5185
  endpoint: path,
5391
5186
  origin: "runtime"
@@ -5395,10 +5190,7 @@ var SandboxInstance = class SandboxInstance {
5395
5190
  async backendControlAction(path, method) {
5396
5191
  await this.ensureRunning();
5397
5192
  const response = await this.runtimeFetch(path, { method });
5398
- if (!response.ok) {
5399
- const body = await response.text();
5400
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5401
- }
5193
+ if (!response.ok) throw await parseResponseError(response);
5402
5194
  }
5403
5195
  backendListSearch(options) {
5404
5196
  const search = new URLSearchParams();
@@ -5449,12 +5241,7 @@ var SandboxInstance = class SandboxInstance {
5449
5241
  async backendDownloadArtifact(sessionId, path) {
5450
5242
  await this.ensureRunning();
5451
5243
  const search = new URLSearchParams({ path });
5452
- const response = await this.runtimeFetch(`/config/artifacts/${encodeURIComponent(sessionId)}/download?${search.toString()}`, { method: "GET" });
5453
- if (!response.ok) {
5454
- const body = await response.text();
5455
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5456
- }
5457
- const payload = await response.json();
5244
+ const payload = await readResponseJson(await this.runtimeFetch(`/config/artifacts/${encodeURIComponent(sessionId)}/download?${search.toString()}`, { method: "GET" }));
5458
5245
  if (!payload || typeof payload.base64 !== "string") throw new ServerError("Backend artifact download response missing base64", 502, {
5459
5246
  endpoint: `/config/artifacts/${encodeURIComponent(sessionId)}/download`,
5460
5247
  origin: "runtime"
@@ -5464,10 +5251,7 @@ var SandboxInstance = class SandboxInstance {
5464
5251
  async backendRestart() {
5465
5252
  await this.ensureRunning();
5466
5253
  const response = await this.runtimeFetch("/backend/restart", { method: "POST" });
5467
- if (!response.ok) {
5468
- const body = await response.text();
5469
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5470
- }
5254
+ if (!response.ok) throw await parseResponseError(response);
5471
5255
  }
5472
5256
  /**
5473
5257
  * Process manager for spawning and controlling processes.
@@ -5513,16 +5297,11 @@ var SandboxInstance = class SandboxInstance {
5513
5297
  const headers = sessionHeaders(options?.sessionId);
5514
5298
  if (options?.cwd !== void 0 && (typeof options.cwd !== "string" || options.cwd.trim().length === 0)) throw new ValidationError("Dev server cwd must be a non-empty string");
5515
5299
  await this.ensureRunning();
5516
- const response = await this.runtimeFetch("/process/ensure-dev-server", {
5300
+ const payload = await readResponseJson(await this.runtimeFetch("/process/ensure-dev-server", {
5517
5301
  method: "POST",
5518
5302
  headers,
5519
5303
  body: JSON.stringify(options?.cwd ? { cwd: options.cwd } : {})
5520
- });
5521
- if (!response.ok) {
5522
- const body = await response.text();
5523
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5524
- }
5525
- const payload = await response.json();
5304
+ }));
5526
5305
  return {
5527
5306
  ...payload.data,
5528
5307
  startedAt: new Date(payload.data.startedAt)
@@ -5531,7 +5310,7 @@ var SandboxInstance = class SandboxInstance {
5531
5310
  async processSpawn(command, options) {
5532
5311
  const headers = sessionHeaders(options?.sessionId);
5533
5312
  await this.ensureRunning();
5534
- const response = await this.runtimeFetch("/process/spawn", {
5313
+ const data = await readResponseJson(await this.runtimeFetch("/process/spawn", {
5535
5314
  method: "POST",
5536
5315
  headers,
5537
5316
  body: JSON.stringify({
@@ -5542,18 +5321,13 @@ var SandboxInstance = class SandboxInstance {
5542
5321
  timeoutMs: options?.timeoutMs,
5543
5322
  blocking: false
5544
5323
  })
5545
- });
5546
- if (!response.ok) {
5547
- const body = await response.text();
5548
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5549
- }
5550
- const data = await response.json();
5324
+ }));
5551
5325
  return this.createProcessHandle(data.data.pid, command);
5552
5326
  }
5553
5327
  async processSpawnExact(executable, args, options) {
5554
5328
  const headers = sessionHeaders(options?.sessionId);
5555
5329
  await this.ensureRunning();
5556
- const response = await this.runtimeFetch("/process/spawn", {
5330
+ const data = await readResponseJson(await this.runtimeFetch("/process/spawn", {
5557
5331
  method: "POST",
5558
5332
  headers,
5559
5333
  body: JSON.stringify({
@@ -5568,24 +5342,14 @@ var SandboxInstance = class SandboxInstance {
5568
5342
  retentionMs: options?.retentionMs,
5569
5343
  blocking: false
5570
5344
  })
5571
- });
5572
- if (!response.ok) {
5573
- const body = await response.text();
5574
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5575
- }
5576
- const data = await response.json();
5345
+ }));
5577
5346
  return this.createProcessHandle(data.data.pid, JSON.stringify([executable, ...args]));
5578
5347
  }
5579
5348
  async processList(options) {
5580
5349
  await this.ensureRunning();
5581
5350
  const query = new URLSearchParams();
5582
5351
  if (options?.idempotencyKey !== void 0) query.set("idempotencyKey", options.idempotencyKey);
5583
- const response = await this.runtimeFetch(query.size === 0 ? "/process" : `/process?${query.toString()}`, { method: "GET" });
5584
- if (!response.ok) {
5585
- const body = await response.text();
5586
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5587
- }
5588
- return ((await response.json()).data ?? []).map((p) => ({
5352
+ return ((await readResponseJson(await this.runtimeFetch(query.size === 0 ? "/process" : `/process?${query.toString()}`, { method: "GET" }))).data ?? []).map((p) => ({
5589
5353
  pid: p.pid,
5590
5354
  ...p.idempotencyKey === void 0 ? {} : { idempotencyKey: p.idempotencyKey },
5591
5355
  command: p.command,
@@ -5601,21 +5365,12 @@ var SandboxInstance = class SandboxInstance {
5601
5365
  await this.ensureRunning();
5602
5366
  const response = await this.runtimeFetch(`/process/${pid}`, { method: "GET" });
5603
5367
  if (response.status === 404) return null;
5604
- if (!response.ok) {
5605
- const body = await response.text();
5606
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5607
- }
5608
- const data = await response.json();
5368
+ const data = await readResponseJson(response);
5609
5369
  return this.createProcessHandle(pid, data.data.command);
5610
5370
  }
5611
5371
  createProcessHandle(pid, command) {
5612
5372
  const status = async () => {
5613
- const response = await this.runtimeFetch(`/process/${pid}`, { method: "GET" });
5614
- if (!response.ok) {
5615
- const body = await response.text();
5616
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5617
- }
5618
- const process = (await response.json()).data;
5373
+ const process = (await readResponseJson(await this.runtimeFetch(`/process/${pid}`, { method: "GET" }))).data;
5619
5374
  return {
5620
5375
  pid: process.pid,
5621
5376
  ...process.idempotencyKey === void 0 ? {} : { idempotencyKey: process.idempotencyKey },
@@ -5643,10 +5398,7 @@ var SandboxInstance = class SandboxInstance {
5643
5398
  };
5644
5399
  const logs = async function* (runtimeFetch, parseProcessLogStream) {
5645
5400
  const response = await runtimeFetch(`/process/${pid}/logs`, { method: "GET" });
5646
- if (!response.ok) {
5647
- const body = await response.text();
5648
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5649
- }
5401
+ if (!response.ok) throw await parseResponseError(response);
5650
5402
  yield* parseProcessLogStream(response);
5651
5403
  }.bind(void 0, this.runtimeFetch.bind(this), this.parseProcessLogStream.bind(this));
5652
5404
  return {
@@ -5758,61 +5510,33 @@ var SandboxInstance = class SandboxInstance {
5758
5510
  method: "PATCH",
5759
5511
  body: JSON.stringify(config)
5760
5512
  });
5761
- if (!response.ok) {
5762
- const body = await response.text();
5763
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5764
- }
5513
+ if (!response.ok) throw await parseResponseError(response);
5765
5514
  }
5766
5515
  async networkExposePort(port) {
5767
5516
  if (port < 1 || port > 65535) throw new Error("Port must be between 1 and 65535");
5768
- const response = await this.runtimeFetch("/network/expose", {
5517
+ return (await readResponseJson(await this.runtimeFetch("/network/expose", {
5769
5518
  method: "POST",
5770
5519
  body: JSON.stringify({ port })
5771
- });
5772
- if (!response.ok) {
5773
- const body = await response.text();
5774
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5775
- }
5776
- return (await response.json()).url;
5520
+ }))).url;
5777
5521
  }
5778
5522
  async networkListUrls() {
5779
- const response = await this.runtimeFetch("/network/urls");
5780
- if (!response.ok) {
5781
- const body = await response.text();
5782
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5783
- }
5784
- return (await response.json()).urls ?? {};
5523
+ return (await readResponseJson(await this.runtimeFetch("/network/urls"))).urls ?? {};
5785
5524
  }
5786
5525
  async networkGetConfig() {
5787
- const response = await this.runtimeFetch("/network");
5788
- if (!response.ok) {
5789
- const body = await response.text();
5790
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5791
- }
5792
- return await response.json();
5526
+ return await readResponseJson(await this.runtimeFetch("/network"));
5793
5527
  }
5794
5528
  async egressGet() {
5795
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}`);
5796
- if (!response.ok) {
5797
- const body = await response.text();
5798
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5799
- }
5800
- const data = await response.json();
5529
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}`));
5801
5530
  return {
5802
5531
  policy: data.egressPolicy ?? { mode: "open" },
5803
5532
  source: data.egressPolicySource ?? "platform"
5804
5533
  };
5805
5534
  }
5806
5535
  async egressUpdate(policy) {
5807
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/egress`, {
5536
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/egress`, {
5808
5537
  method: "PATCH",
5809
5538
  body: JSON.stringify(policy)
5810
- });
5811
- if (!response.ok) {
5812
- const body = await response.text();
5813
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5814
- }
5815
- const data = await response.json();
5539
+ }));
5816
5540
  this.info = {
5817
5541
  ...this.info,
5818
5542
  egressPolicy: data.egressPolicy,
@@ -5831,10 +5555,7 @@ var SandboxInstance = class SandboxInstance {
5831
5555
  }
5832
5556
  const query = limit === void 0 ? "" : `?limit=${encodeURIComponent(limit)}`;
5833
5557
  const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/egress/denials${query}`);
5834
- if (!response.ok) {
5835
- const body = await response.text();
5836
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5837
- }
5558
+ if (!response.ok) throw await parseResponseError(response);
5838
5559
  let body;
5839
5560
  try {
5840
5561
  body = await response.json();
@@ -5880,10 +5601,7 @@ var SandboxInstance = class SandboxInstance {
5880
5601
  }
5881
5602
  const query = limit === void 0 ? "" : `?limit=${encodeURIComponent(limit)}`;
5882
5603
  const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/egress/activity${query}`);
5883
- if (!response.ok) {
5884
- const body = await response.text();
5885
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5886
- }
5604
+ if (!response.ok) throw await parseResponseError(response);
5887
5605
  let body;
5888
5606
  try {
5889
5607
  body = await response.json();
@@ -5926,42 +5644,22 @@ var SandboxInstance = class SandboxInstance {
5926
5644
  };
5927
5645
  }
5928
5646
  async gpuAttach(options) {
5929
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases`, {
5647
+ return (await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases`, {
5930
5648
  method: "POST",
5931
5649
  body: JSON.stringify(options)
5932
- });
5933
- if (!response.ok) {
5934
- const body = await response.text();
5935
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5936
- }
5937
- return (await response.json()).lease;
5650
+ }))).lease;
5938
5651
  }
5939
5652
  async gpuList() {
5940
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases`);
5941
- if (!response.ok) {
5942
- const body = await response.text();
5943
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5944
- }
5945
- return (await response.json()).leases ?? [];
5653
+ return (await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases`))).leases ?? [];
5946
5654
  }
5947
5655
  async gpuExec(leaseId, options) {
5948
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases/${encodeURIComponent(leaseId)}/exec`, {
5656
+ return await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases/${encodeURIComponent(leaseId)}/exec`, {
5949
5657
  method: "POST",
5950
5658
  body: JSON.stringify(options)
5951
- });
5952
- if (!response.ok) {
5953
- const body = await response.text();
5954
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5955
- }
5956
- return await response.json();
5659
+ }));
5957
5660
  }
5958
5661
  async gpuDetach(leaseId) {
5959
- const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases/${encodeURIComponent(leaseId)}`, { method: "DELETE" });
5960
- if (!response.ok) {
5961
- const body = await response.text();
5962
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5963
- }
5964
- return (await response.json()).lease;
5662
+ return (await readResponseJson(await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/gpu/leases/${encodeURIComponent(leaseId)}`, { method: "DELETE" }))).lease;
5965
5663
  }
5966
5664
  /**
5967
5665
  * Validate CIDR notation (IPv4 and IPv6)
@@ -6016,11 +5714,7 @@ var SandboxInstance = class SandboxInstance {
6016
5714
  metadata: options?.metadata
6017
5715
  })
6018
5716
  });
6019
- if (!response.ok) {
6020
- const body = await response.text();
6021
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6022
- }
6023
- const data = await response.json();
5717
+ const data = await readResponseJson(response);
6024
5718
  if (response.status !== 200 && response.status !== 201) throw new Error("Preview creation returned an unexpected success status");
6025
5719
  return {
6026
5720
  ...normalizePreviewLink(data.previewLink),
@@ -6028,20 +5722,10 @@ var SandboxInstance = class SandboxInstance {
6028
5722
  };
6029
5723
  }
6030
5724
  async previewLinkList() {
6031
- const response = await this.runtimeFetch("/preview-links");
6032
- if (!response.ok) {
6033
- const body = await response.text();
6034
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6035
- }
6036
- return ((await response.json()).previewLinks ?? []).map(normalizePreviewLink);
5725
+ return ((await readResponseJson(await this.runtimeFetch("/preview-links"))).previewLinks ?? []).map(normalizePreviewLink);
6037
5726
  }
6038
5727
  async previewLinkGet(previewId, signal) {
6039
- const response = await this.runtimeFetch(`/preview-links/${encodeURIComponent(previewId)}`, signal ? { signal } : void 0);
6040
- if (!response.ok) {
6041
- const body = await response.text();
6042
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6043
- }
6044
- return normalizePreviewLink((await response.json()).previewLink);
5728
+ return normalizePreviewLink((await readResponseJson(await this.runtimeFetch(`/preview-links/${encodeURIComponent(previewId)}`, signal ? { signal } : void 0))).previewLink);
6045
5729
  }
6046
5730
  async previewLinkWaitUntilReady(previewId, options) {
6047
5731
  const timeoutMs = options?.timeoutMs ?? PREVIEW_LINK_READY_TIMEOUT_MS;
@@ -6103,10 +5787,7 @@ var SandboxInstance = class SandboxInstance {
6103
5787
  }
6104
5788
  async previewLinkRemove(previewId) {
6105
5789
  const response = await this.runtimeFetch(`/preview-links/${encodeURIComponent(previewId)}`, { method: "DELETE" });
6106
- if (!response.ok) {
6107
- const body = await response.text();
6108
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6109
- }
5790
+ if (!response.ok) throw await parseResponseError(response);
6110
5791
  }
6111
5792
  /**
6112
5793
  * Get information about the infrastructure driver for this sandbox.
@@ -6118,12 +5799,7 @@ var SandboxInstance = class SandboxInstance {
6118
5799
  * ```
6119
5800
  */
6120
5801
  async getDriverInfo() {
6121
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/driver`);
6122
- if (!response.ok) {
6123
- const body = await response.text();
6124
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6125
- }
6126
- return await response.json();
5802
+ return await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/driver`));
6127
5803
  }
6128
5804
  async toolsInstall(tool, version) {
6129
5805
  await this.ensureRunning();
@@ -6134,10 +5810,7 @@ var SandboxInstance = class SandboxInstance {
6134
5810
  version
6135
5811
  })
6136
5812
  });
6137
- if (!response.ok) {
6138
- const body = await response.text();
6139
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6140
- }
5813
+ if (!response.ok) throw await parseResponseError(response);
6141
5814
  }
6142
5815
  async toolsUse(tool, version) {
6143
5816
  await this.ensureRunning();
@@ -6148,34 +5821,21 @@ var SandboxInstance = class SandboxInstance {
6148
5821
  version
6149
5822
  })
6150
5823
  });
6151
- if (!response.ok) {
6152
- const body = await response.text();
6153
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6154
- }
5824
+ if (!response.ok) throw await parseResponseError(response);
6155
5825
  }
6156
5826
  async toolsList() {
6157
5827
  await this.ensureRunning();
6158
- const response = await this.runtimeFetch("/tools", { method: "GET" });
6159
- if (!response.ok) {
6160
- const body = await response.text();
6161
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6162
- }
6163
- return (await response.json()).tools ?? [];
5828
+ return (await readResponseJson(await this.runtimeFetch("/tools", { method: "GET" }))).tools ?? [];
6164
5829
  }
6165
5830
  async toolsRun(tool, args) {
6166
5831
  await this.ensureRunning();
6167
- const response = await this.runtimeFetch("/tools/run", {
5832
+ const data = await readResponseJson(await this.runtimeFetch("/tools/run", {
6168
5833
  method: "POST",
6169
5834
  body: JSON.stringify({
6170
5835
  tool,
6171
5836
  args
6172
5837
  })
6173
- });
6174
- if (!response.ok) {
6175
- const body = await response.text();
6176
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6177
- }
6178
- const data = await response.json();
5838
+ }));
6179
5839
  return {
6180
5840
  exitCode: data.exitCode ?? 0,
6181
5841
  stdout: data.stdout ?? "",
@@ -6217,19 +5877,14 @@ var SandboxInstance = class SandboxInstance {
6217
5877
  if (options?.idempotencyKey && options.storage) throw new Error("idempotencyKey is not supported with customer-provided storage; the BYOS3 snapshot path keeps no operation ledger");
6218
5878
  await this.ensureRunning();
6219
5879
  if (options?.storage) {
6220
- const response = await this.runtimeFetch("/snapshots", {
5880
+ const data = await readResponseJson(await this.runtimeFetch("/snapshots", {
6221
5881
  method: "POST",
6222
5882
  body: JSON.stringify({
6223
5883
  projectId: this.id,
6224
5884
  storage: options.storage,
6225
5885
  tags: options.tags
6226
5886
  })
6227
- });
6228
- if (!response.ok) {
6229
- const body = await response.text();
6230
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6231
- }
6232
- const data = await response.json();
5887
+ }));
6233
5888
  return {
6234
5889
  snapshotId: data.snapshot?.id ?? data.snapshotId,
6235
5890
  createdAt: new Date(data.snapshot?.createdAt ?? data.createdAt ?? Date.now()),
@@ -6242,11 +5897,7 @@ var SandboxInstance = class SandboxInstance {
6242
5897
  ...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
6243
5898
  body: JSON.stringify({ tags: options?.tags })
6244
5899
  }, { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS });
6245
- if (!response.ok) {
6246
- const body = await response.text();
6247
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6248
- }
6249
- const data = await response.json();
5900
+ const data = await readResponseJson(response);
6250
5901
  const snapshotId = data.snapshotId ?? data.id;
6251
5902
  if (typeof snapshotId !== "string" || snapshotId.length === 0) throw new ServerError(`Snapshot create returned 200 but body had no snapshot ID: ${JSON.stringify(data).slice(0, 200)}`, response.status);
6252
5903
  const reportedOutcome = data.idempotency?.outcome;
@@ -6298,18 +5949,13 @@ var SandboxInstance = class SandboxInstance {
6298
5949
  async listSnapshots(storage) {
6299
5950
  if (storage) {
6300
5951
  await this.ensureRunning();
6301
- const response = await this.runtimeFetch("/snapshots/list", {
5952
+ return ((await readResponseJson(await this.runtimeFetch("/snapshots/list", {
6302
5953
  method: "POST",
6303
5954
  body: JSON.stringify({
6304
5955
  projectId: this.id,
6305
5956
  storage
6306
5957
  })
6307
- });
6308
- if (!response.ok) {
6309
- const body = await response.text();
6310
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6311
- }
6312
- return ((await response.json()).snapshots ?? []).map((s) => ({
5958
+ }))).snapshots ?? []).map((s) => ({
6313
5959
  snapshotId: s.id ?? s.snapshotId,
6314
5960
  sandboxId: this.id,
6315
5961
  createdAt: new Date(s.createdAt),
@@ -6318,12 +5964,7 @@ var SandboxInstance = class SandboxInstance {
6318
5964
  sizeBytes: s.sizeBytes
6319
5965
  }));
6320
5966
  }
6321
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots`);
6322
- if (!response.ok) {
6323
- const body = await response.text();
6324
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6325
- }
6326
- const data = await response.json();
5967
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots`));
6327
5968
  return (Array.isArray(data) ? data : data.snapshots ?? []).map((s) => ({
6328
5969
  snapshotId: s.snapshotId ?? s.id,
6329
5970
  sandboxId: s.sandboxId ?? s.projectRef ?? this.id,
@@ -6335,11 +5976,7 @@ var SandboxInstance = class SandboxInstance {
6335
5976
  }
6336
5977
  async revertToSnapshot(snapshotId) {
6337
5978
  const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots/${encodeURIComponent(snapshotId)}/restore`, { method: "POST" }, { timeoutMs: SNAPSHOT_RESTORE_TIMEOUT_MS });
6338
- if (!response.ok) {
6339
- const body = await response.text();
6340
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6341
- }
6342
- const data = await response.json();
5979
+ const data = await readResponseJson(response);
6343
5980
  if (response.status === 202) return this.waitForSnapshotRestore(snapshotId, data);
6344
5981
  return toSnapshotResult(data);
6345
5982
  }
@@ -6352,11 +5989,7 @@ var SandboxInstance = class SandboxInstance {
6352
5989
  method: "POST",
6353
5990
  body: JSON.stringify({ paths })
6354
5991
  }, { timeoutMs: SNAPSHOT_RESTORE_TIMEOUT_MS });
6355
- if (!response.ok) {
6356
- const body = await response.text();
6357
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6358
- }
6359
- const data = await response.json();
5992
+ const data = await readResponseJson(response);
6360
5993
  if (response.status === 202) return this.waitForSnapshotRestore(snapshotId, data);
6361
5994
  return toSnapshotResult(data);
6362
5995
  }
@@ -6364,12 +5997,7 @@ var SandboxInstance = class SandboxInstance {
6364
5997
  const deadline = Date.now() + SNAPSHOT_RESTORE_TIMEOUT_MS;
6365
5998
  let polls = 0;
6366
5999
  while (Date.now() < deadline) {
6367
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots/jobs/${encodeURIComponent(accepted.jobId)}`);
6368
- if (!response.ok) {
6369
- const body = await response.text();
6370
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6371
- }
6372
- const status = await response.json();
6000
+ const status = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots/jobs/${encodeURIComponent(accepted.jobId)}`));
6373
6001
  if (status.status === "failed" || status.result?.success === false) throw new ServerError(status.result?.error ?? `Snapshot restore job ${accepted.jobId} failed`);
6374
6002
  if (status.status === "completed") {
6375
6003
  this.applyLifecycleResponse(status.sandbox ?? null);
@@ -6422,10 +6050,7 @@ var SandboxInstance = class SandboxInstance {
6422
6050
  */
6423
6051
  async deleteSnapshot(snapshotId, options) {
6424
6052
  const response = await this.client.fetch(`/v1/sandboxes/${this.id}/snapshots/${encodeURIComponent(snapshotId)}`, { method: "DELETE" }, usableTimeoutMs(options?.timeoutMs));
6425
- if (!response.ok) {
6426
- const body = await response.text();
6427
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6428
- }
6053
+ if (!response.ok) throw await parseResponseError(response);
6429
6054
  const body = await response.json().catch(() => ({}));
6430
6055
  return {
6431
6056
  snapshotId,
@@ -6493,11 +6118,7 @@ var SandboxInstance = class SandboxInstance {
6493
6118
  })
6494
6119
  });
6495
6120
  if (response.status === 404) return null;
6496
- if (!response.ok) {
6497
- const body = await response.text();
6498
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6499
- }
6500
- const data = await response.json();
6121
+ const data = await readResponseJson(response);
6501
6122
  if (!data.snapshot) return null;
6502
6123
  return {
6503
6124
  snapshotId: data.snapshot.id,
@@ -6548,7 +6169,7 @@ var SandboxInstance = class SandboxInstance {
6548
6169
  */
6549
6170
  async fork(count, options) {
6550
6171
  if (!Number.isInteger(count) || count < 1) throw new ValidationError(`branch count must be an integer >= 1 (got ${count})`);
6551
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/branch`, {
6172
+ const data = await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/branch`, {
6552
6173
  method: "POST",
6553
6174
  ...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
6554
6175
  body: JSON.stringify({
@@ -6556,12 +6177,7 @@ var SandboxInstance = class SandboxInstance {
6556
6177
  env: options?.env,
6557
6178
  metadata: options?.metadata
6558
6179
  })
6559
- });
6560
- if (!response.ok) {
6561
- const body = await response.text();
6562
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6563
- }
6564
- const data = await response.json();
6180
+ }));
6565
6181
  const children = (data.children ?? []).map((child) => createSandboxInstanceFromResponse(this.client, this.parseInfo(child), this.defaultRuntimeBackend));
6566
6182
  const materializedCount = children.length;
6567
6183
  const requestedCount = typeof data.fork?.requestedCount === "number" ? data.fork.requestedCount : count;
@@ -6642,11 +6258,7 @@ var SandboxInstance = class SandboxInstance {
6642
6258
  ...options.scorer ? { scorer: options.scorer } : {}
6643
6259
  })
6644
6260
  });
6645
- if (!response.ok) {
6646
- const body = await response.text();
6647
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6648
- }
6649
- const data = await response.json();
6261
+ const data = await readResponseJson(response);
6650
6262
  if (typeof data.rolloutId !== "string" || data.rolloutId.length === 0) throw new ServerError(`Rollout create returned ${response.status} but body had no rolloutId: ${JSON.stringify(data).slice(0, 200)}`, response.status);
6651
6263
  return data;
6652
6264
  }
@@ -6660,12 +6272,7 @@ var SandboxInstance = class SandboxInstance {
6660
6272
  */
6661
6273
  async getRollout(rolloutId) {
6662
6274
  if (!rolloutId) throw new ValidationError("rolloutId is required");
6663
- const response = await this.client.fetch(`/v1/sandboxes/${this.id}/rollouts/${encodeURIComponent(rolloutId)}`, { method: "GET" });
6664
- if (!response.ok) {
6665
- const body = await response.text();
6666
- throw parseErrorResponse(response.status, body, void 0, response.headers);
6667
- }
6668
- return await response.json();
6275
+ return await readResponseJson(await this.client.fetch(`/v1/sandboxes/${this.id}/rollouts/${encodeURIComponent(rolloutId)}`, { method: "GET" }));
6669
6276
  }
6670
6277
  /**
6671
6278
  * Poll {@link getRollout} until the rollout leaves `running`, then return
@@ -7123,10 +6730,7 @@ var SandboxInstance = class SandboxInstance {
7123
6730
  reprovisionRequired: true,
7124
6731
  code: "STALE_SIDECAR"
7125
6732
  };
7126
- if (!response.ok) {
7127
- const body = await response.text();
7128
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7129
- }
6733
+ if (!response.ok) throw await parseResponseError(response);
7130
6734
  const data = await response.json().catch(() => ({}));
7131
6735
  return {
7132
6736
  success: data.success ?? true,
@@ -7143,10 +6747,7 @@ var SandboxInstance = class SandboxInstance {
7143
6747
  */
7144
6748
  async unregisterSessionMapping(opts) {
7145
6749
  const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, { method: "DELETE" });
7146
- if (!response.ok) {
7147
- const body = await response.text();
7148
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7149
- }
6750
+ if (!response.ok) throw await parseResponseError(response);
7150
6751
  const data = await response.json().catch(() => ({}));
7151
6752
  return {
7152
6753
  success: data.success ?? true,
@@ -7247,12 +6848,7 @@ var SandboxInstance = class SandboxInstance {
7247
6848
  search.set("backend", opts.backend);
7248
6849
  }
7249
6850
  const qs = search.toString();
7250
- const response = await this.runtimeFetch(`/agents/sessions${qs ? `?${qs}` : ""}`);
7251
- if (!response.ok) {
7252
- const body = await response.text();
7253
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7254
- }
7255
- const list = await response.json();
6851
+ const list = await readResponseJson(await this.runtimeFetch(`/agents/sessions${qs ? `?${qs}` : ""}`));
7256
6852
  const out = [];
7257
6853
  for (const raw of list) {
7258
6854
  const info = normalizeSessionInfo(raw);
@@ -7454,11 +7050,7 @@ var SandboxInstance = class SandboxInstance {
7454
7050
  });
7455
7051
  const response = await this.runtimeFetch(`/messages/turns?${query.toString()}`, { method: "GET" });
7456
7052
  if (response.status === 204) return null;
7457
- if (!response.ok) {
7458
- const body = await response.text();
7459
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7460
- }
7461
- return parseCompletedTurnResult(await response.json(), {
7053
+ return parseCompletedTurnResult(await readResponseJson(response), {
7462
7054
  turnId,
7463
7055
  sessionId: opts.sessionId
7464
7056
  });
@@ -7574,7 +7166,8 @@ var SandboxInstance = class SandboxInstance {
7574
7166
  ...opts.managedQuoteVersion !== void 0 ? { managedQuoteVersion: opts.managedQuoteVersion } : {},
7575
7167
  ...opts.managedModelCredential === true ? { managedModelCredential: true } : {},
7576
7168
  ...backend !== void 0 ? { backend } : {},
7577
- ...opts.runControlRef !== void 0 ? { runControlRef: opts.runControlRef } : {}
7169
+ ...opts.runControlRef !== void 0 ? { runControlRef: opts.runControlRef } : {},
7170
+ ...opts.admissionDeadline !== void 0 ? { admissionDeadline: opts.admissionDeadline } : {}
7578
7171
  };
7579
7172
  const wireRequest = sessionMessageRequestBody(request);
7580
7173
  if (opts.runControlRef && (opts.runControlRef.sessionId !== opts.sessionId || opts.runControlRef.environmentId !== this.id)) throw new ValidationError("runControlRef does not belong to this sandbox conversation");
@@ -7690,11 +7283,7 @@ var SandboxInstance = class SandboxInstance {
7690
7283
  await this.ensureRunning();
7691
7284
  const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}`);
7692
7285
  if (response.status === 404) return null;
7693
- if (!response.ok) {
7694
- const body = await response.text();
7695
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7696
- }
7697
- return normalizeSessionInfo(await response.json());
7286
+ return normalizeSessionInfo(await readResponseJson(response));
7698
7287
  }
7699
7288
  /** @internal — invoked before the sandbox is deleted. */
7700
7289
  async _sessionRawEvidence(id) {
@@ -7770,10 +7359,7 @@ var SandboxInstance = class SandboxInstance {
7770
7359
  if (opts?.since) search.set("since", opts.since);
7771
7360
  if (opts?.executionId) search.set("executionId", opts.executionId);
7772
7361
  const response = await this.runtimeFetch(`/agents/events?${search.toString()}`, { signal: opts?.signal });
7773
- if (!response.ok) {
7774
- const body = await response.text();
7775
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7776
- }
7362
+ if (!response.ok) throw await parseResponseError(response);
7777
7363
  for await (const event of this.parseSSEStream(response, opts?.signal)) {
7778
7364
  yield event;
7779
7365
  const turnTerminal = event.type === "done" || event.type === "error";
@@ -7789,10 +7375,7 @@ var SandboxInstance = class SandboxInstance {
7789
7375
  sessionId
7790
7376
  });
7791
7377
  const response = await this.runtimeFetch(`/agents/run/${encodeURIComponent(executionId)}/events?${search.toString()}`);
7792
- if (!response.ok) {
7793
- const body = await response.text();
7794
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7795
- }
7378
+ if (!response.ok) throw await parseResponseError(response);
7796
7379
  for await (const event of this.parseSSEStream(response)) {
7797
7380
  yield event;
7798
7381
  if (event.type === "done" || event.type === "error") return;
@@ -7942,11 +7525,7 @@ var SandboxInstance = class SandboxInstance {
7942
7525
  })
7943
7526
  }) : await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/abort`, { method: "POST" });
7944
7527
  if (response.status === 404) return { cancelled: false };
7945
- if (!response.ok) {
7946
- const body = await response.text();
7947
- throw parseErrorResponse(response.status, body, void 0, response.headers);
7948
- }
7949
- const json = await response.json();
7528
+ const json = await readResponseJson(response);
7950
7529
  return { cancelled: options?.executionId ? json.success === true : json.data?.cancelled === true };
7951
7530
  }
7952
7531
  /** @internal — invoked by SandboxSession.cancelRun(). */
@@ -8001,11 +7580,7 @@ var SandboxInstance = class SandboxInstance {
8001
7580
  const path = `/v1/sandboxes/${encodeURIComponent(this.id)}/agent-sessions/${encodeURIComponent(sessionId)}/plans/current`;
8002
7581
  const response = await this.client.fetch(path);
8003
7582
  if (response.status === 404) return null;
8004
- if (!response.ok) {
8005
- const body = await response.text();
8006
- throw parseErrorResponse(response.status, body, void 0, response.headers);
8007
- }
8008
- const decoded = await response.json();
7583
+ const decoded = await readResponseJson(response);
8009
7584
  if (!decoded.plan) throw new ServerError("Durable plan response is missing plan", 502, {
8010
7585
  endpoint: path,
8011
7586
  origin: "control-plane"
@@ -8015,15 +7590,10 @@ var SandboxInstance = class SandboxInstance {
8015
7590
  /** @internal — invoked by SandboxSession.approvePlan()/rejectPlan(). */
8016
7591
  async _decidePlan(sessionId, planId, decision) {
8017
7592
  const path = `/v1/sandboxes/${encodeURIComponent(this.id)}/agent-sessions/${encodeURIComponent(sessionId)}/plans/${encodeURIComponent(planId)}/decision`;
8018
- const response = await this.client.fetch(path, {
7593
+ const decoded = await readResponseJson(await this.client.fetch(path, {
8019
7594
  method: "POST",
8020
7595
  body: JSON.stringify(decision)
8021
- });
8022
- if (!response.ok) {
8023
- const body = await response.text();
8024
- throw parseErrorResponse(response.status, body, void 0, response.headers);
8025
- }
8026
- const decoded = await response.json();
7596
+ }));
8027
7597
  const followUpState = decoded.followUp?.state;
8028
7598
  if (!decoded.plan || typeof decoded.followUp?.turnId !== "string" || ![
8029
7599
  "queued",