@tangle-network/sandbox 1.0.231 → 1.0.232

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 (77) hide show
  1. package/README.md +22 -1
  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-DMaHbXAk.d.ts → agent-run-outcome-MsLkgPNu.d.ts} +2 -2
  7. package/dist/{api-request-_SFFNVqY.js → api-request-B0BPgzdp.js} +34 -9
  8. package/dist/auth/index.d.ts +2 -2
  9. package/dist/auth/index.js +2 -2
  10. package/dist/{browser-interactive-control-controller-BiP6TJFP.js → browser-interactive-control-controller-Bf-DbRCA.js} +14 -4
  11. package/dist/{browser-interactive-control-controller-qv26Bpfx.d.ts → browser-interactive-control-controller-D17JJ8B0.d.ts} +1 -1
  12. package/dist/{chunked-upload-BjkxykZD.js → chunked-upload-BGwaw5np.js} +4 -5
  13. package/dist/{chunked-upload-file-B2KFimpz.js → chunked-upload-file-BnV8qgwV.js} +2 -2
  14. package/dist/cli-auth-bundle-DvmJ71bO.js +2 -0
  15. package/dist/{client-DvvRMxKx.d.ts → client-BTpWpGs-.d.ts} +36 -30
  16. package/dist/{client-OlxlnLwV.js → client-CgZADtPk.js} +36 -46
  17. package/dist/collaboration/index.d.ts +1 -1
  18. package/dist/collaboration/index.js +1 -1
  19. package/dist/{collaboration-DZ8ptALs.js → collaboration-DneF_7bo.js} +20 -27
  20. package/dist/{core-D7czAW25.js → core-Cxww35JL.js} +5 -5
  21. package/dist/core.d.ts +6 -6
  22. package/dist/core.js +5 -5
  23. package/dist/{direct-http2-DU2SK2Wo.js → direct-http2-B5bdFrtg.js} +1 -1
  24. package/dist/{errors-A-bhwwsE.js → error-catalog-CGhVLVNq.js} +1 -382
  25. package/dist/errors-dK3-2RCh.js +382 -0
  26. package/dist/{file-download-UhMKbMbD.js → file-download-CUNdbymj.js} +1 -1
  27. package/dist/{index-Cip3q_xe.d.ts → index-CHP8U613.d.ts} +13 -23
  28. package/dist/index.d.ts +12 -12
  29. package/dist/index.js +28 -25
  30. package/dist/intelligence/index.js +3 -3
  31. package/dist/interactive-control.d.ts +1 -1
  32. package/dist/interactive-control.js +1 -1
  33. package/dist/{interactive-controller-D4gZ4f2I.js → interactive-controller-Bs7VQ04W.js} +17 -54
  34. package/dist/{interactive-controller-P0yy6sGl.d.ts → interactive-controller-DbNjY09X.d.ts} +3 -3
  35. package/dist/lib/prepared-evidence.js +1 -1
  36. package/dist/lib/prepared-process.js +1 -1
  37. package/dist/{lines-7VecgiGd.js → lines-DtssoioA.js} +1 -1
  38. package/dist/{lines-DNXdVbGO.d.ts → lines-n-mBURry.d.ts} +1 -1
  39. package/dist/lines.d.ts +1 -1
  40. package/dist/lines.js +1 -1
  41. package/dist/{local-cli-auth-CPS9yuTc.js → local-cli-auth-8Ndf1jRw.js} +1 -1
  42. package/dist/{mcp-local-CIXZFqF4.js → mcp-local-tA5cB3zq.js} +4 -4
  43. package/dist/{prepared-evidence-Byty5p51.js → prepared-evidence-DBE_xYjq.js} +2 -2
  44. package/dist/{prepared-process-u1B0b94R.js → prepared-process-B1kSkhn-.js} +2 -2
  45. package/dist/{preview-CNfYklE6.d.ts → preview-BHee3FzP.d.ts} +3 -3
  46. package/dist/{public-templates-CPvDf8CH.d.ts → public-templates-ZrUJ507X.d.ts} +2 -2
  47. package/dist/public-templates.d.ts +1 -1
  48. package/dist/public-templates.js +1 -1
  49. package/dist/{raw-evidence-archive-BgWqaQcM.js → raw-evidence-archive-Cfy_3_3y.js} +2 -2
  50. package/dist/{retry-policy-Dh-VezcE.js → retry-policy-CI5tyUGr.js} +2 -24
  51. package/dist/runtime.d.ts +7 -7
  52. package/dist/runtime.js +9 -9
  53. package/dist/{sandbox-Dvk2PYnL.js → sandbox-DOvm9OvM.js} +59 -74
  54. package/dist/{secp256k1-Cbp9tbkX.js → secp256k1-DZM5U2gv.js} +1 -1
  55. package/dist/select-seat-command.d.ts +1 -1
  56. package/dist/select-seat-command.js +1 -1
  57. package/dist/session-gateway/index.js +11 -20
  58. package/dist/sidecar-proxy-error-CeNM5eJj.js +4 -0
  59. package/dist/tangle/index.d.ts +1 -1
  60. package/dist/tangle/index.js +1 -1
  61. package/dist/{tangle-DWzUnb1Y.js → tangle-DFmy_0hM.js} +22 -17
  62. package/dist/{terminal-stream-types-DB8V0hiG.d.ts → terminal-stream-types-NBdVKKFu.d.ts} +0 -1
  63. package/dist/{types-Cmv31xBh.d.ts → types-CuMa305b.d.ts} +13 -57
  64. package/package.json +5 -5
  65. package/dist/cli-auth-bundle-CMJWI99l.js +0 -2
  66. package/dist/sidecar-proxy-error-DpBLxIof.js +0 -24
  67. /package/dist/{abort-signal-BbJTt2QJ.js → abort-signal-C0_9B1Hm.js} +0 -0
  68. /package/dist/{cli-auth-bundle-Wg3x2hd2.d.ts → cli-auth-bundle-BE_EfLUx.d.ts} +0 -0
  69. /package/dist/{cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js → cli-auth-bundle-C6DtK7GX-Cjs6D-9c.js} +0 -0
  70. /package/dist/{file-transfer-BSe4ayU9.js → file-transfer-CSL53pv9.js} +0 -0
  71. /package/dist/{index-YbAo-so_.d.ts → index-D0zHNMSe.d.ts} +0 -0
  72. /package/dist/{index-CDtEPygc.d.ts → index-DsX2pOIn.d.ts} +0 -0
  73. /package/dist/{keep-alive-fetch-BIaDMUtu.js → keep-alive-fetch-C2DX2_rG.js} +0 -0
  74. /package/dist/{preview-operations-B3TTvqlm.js → preview-operations-BBF0BNuZ.js} +0 -0
  75. /package/dist/{retry-after-header-DUdCC0KJ.js → retry-after-header-Bt-XvU-x.js} +0 -0
  76. /package/dist/{sse-parser-DOCszo1K.js → sse-parser-CBQzZvkZ.js} +0 -0
  77. /package/dist/{utils-CK-x8vXj.js → utils-DqiOGAK5.js} +0 -0
@@ -1,11 +1,5 @@
1
1
  //#region ../../../packages/runtime-contracts/dist/retry-policy.js
2
- /**
3
- * The one pacing every lifecycle hop re-sends with: the server's Retry-After,
4
- * else full-jitter exponential backoff, inside a retry budget per downstream
5
- * holding a storm near a tenth of the requests sent. Whether a failure reached
6
- * the server is read here; whether it may be re-sent stays with the catalog
7
- * and the verb. Imports nothing.
8
- */
2
+ /** Shared resend pacing and downstream budgets; the catalog and verb own eligibility. */
9
3
  /** Raised before a request byte left: a dial refused, unresolved, unroutable or timed out, or a refused certificate. */
10
4
  const UNDELIVERED_CODES = new Set([
11
5
  "ECONNREFUSED",
@@ -21,15 +15,8 @@ const UNDELIVERED_CODES = new Set([
21
15
  "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
22
16
  "CERT_HAS_EXPIRED"
23
17
  ]);
24
- /** A Worker's fetch names the failure only in its message. */
25
18
  const UNDELIVERED_MESSAGE = /\b(?:connection refused|DNS lookup failed|TLS handshake failed|before secure TLS connection was established)\b/i;
26
- /**
27
- * Whether a thrown failure proves no request reached the peer, so any verb may
28
- * dial again: a code above or a `syscall: "connect"` failure under it (fetch
29
- * nests the socket error in `cause`, a dual-stack dial in `errors`), or a
30
- * Worker's message for one. A reset or timeout off the connect syscall may
31
- * follow a request sent on a reused socket, so it proves nothing.
32
- */
19
+ /** Connect failures prove no delivery, even nested under cause/errors; later resets do not. */
33
20
  function isUndelivered(cause) {
34
21
  const pending = [cause];
35
22
  for (let read = 0; pending.length > 0 && read < 16; read++) {
@@ -44,23 +31,17 @@ function isUndelivered(cause) {
44
31
  return false;
45
32
  }
46
33
  const RETRY_POLICY = {
47
- /** The first re-send waits up to baseMs; each later one doubles it, up to capMs. */
48
34
  baseMs: 250,
49
35
  capMs: 8e3,
50
- /** Re-sends one request earns. */
51
36
  budgetRatio: .1,
52
- /** Re-sends an idle downstream may spend at once: 10 s of the floor. */
53
37
  budgetCapacity: 100,
54
- /** Re-sends earned each second however quiet the caller (Finagle's default). */
55
38
  budgetFloorPerSecond: 10
56
39
  };
57
- /** Re-send `resend` (1 = first) waits the server's `retryAfterMs` (its pushback, as in gRPC), else U[0, min(cap, base * 2^(resend-1))). */
58
40
  function backoffDelayMs(resend, retryAfterMs, capMs = RETRY_POLICY.capMs) {
59
41
  const ceilingMs = Math.min(capMs, RETRY_POLICY.baseMs * 2 ** (resend - 1));
60
42
  return retryAfterMs ?? Math.random() * ceilingMs;
61
43
  }
62
44
  const budgets = /* @__PURE__ */ new Map();
63
- /** The re-send budget for `scope`, one per downstream in this isolate or process. */
64
45
  function retryBudget(scope) {
65
46
  const { budgetCapacity, budgetFloorPerSecond, budgetRatio } = RETRY_POLICY;
66
47
  let budget = budgets.get(scope);
@@ -87,7 +68,6 @@ function retryBudget(scope) {
87
68
  budgets.set(scope, budget);
88
69
  return budget;
89
70
  }
90
- /** Resolve after `ms`; reject with the signal's reason the moment it aborts. */
91
71
  function abortableSleep(ms, signal) {
92
72
  if (signal?.aborted) return Promise.reject(signal.reason);
93
73
  if (ms <= 0) return Promise.resolve();
@@ -103,7 +83,6 @@ function abortableSleep(ms, signal) {
103
83
  signal?.addEventListener("abort", onAbort, { once: true });
104
84
  });
105
85
  }
106
- /** The Sandbox API downstream: every SDK request earns its budget and every SDK re-send spends it. */
107
86
  const SANDBOX_API_RETRY_SCOPE = "sandbox-api";
108
87
  /** Re-send `resend`'s wait: its backoff and, unless the server paced it, its budget turn (taken now); `undefined`, spending nothing, past `deadlineAt` (default: one cap past the backoff). */
109
88
  function planResend(scope, resend, o = {}) {
@@ -114,7 +93,6 @@ function planResend(scope, resend, o = {}) {
114
93
  const turnMs = retryBudget(scope).take(remainingMs);
115
94
  return turnMs === void 0 ? void 0 : Math.max(backoffMs, turnMs);
116
95
  }
117
- /** Wait out {@link planResend}; `false` when it could not go. `spent` hears the wait first, for a loop whose window counts only waits. */
118
96
  async function awaitResend(scope, resend, o = {}) {
119
97
  const waitMs = planResend(scope, resend, o);
120
98
  if (waitMs === void 0) return false;
package/dist/runtime.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { B as ServerError, C as CapabilityError, D as FileWriteConflictError, F as QuotaError, G as ValidationError, L as SandboxError, M as NotFoundError, N as PartialFailureError, P as ProfileFileMountPathError, R as SandboxErrorJson, V as StateError, W as TimeoutError, j as NetworkError, u as ScopedToken, x as AuthError, z as SandboxFailureDetail } from "./terminal-stream-types-DB8V0hiG.js";
2
- import { $i as SessionExecutionStatus, Bi as CreateSessionOptions, Cn as TerminalStream, Di as SandboxEvent, Fi as CommitTaskSessionOptions, Gi as ListMessagesOptions, Gn as ChunkedUploadResult, Ji as SendSessionMessageRequest, Qi as SessionExecutionInfo, Qn as FileReadBatchResult, Vi as CreateTaskSessionOptions, Wn as ChunkedUploadOptions, Yi as SentSessionMessage, Zi as SessionEventStreamOptions, Zn as FileReadBatchOptions, aa as SessionMessage, ar as FileTreeResult, cr as FileWriteResult, dn as SandboxTerminalCreateOptions, dr as RenameOptions, fa as TaskSessionInfo, fn as SandboxTerminalInfo, ir as FileTreeOptions, la as TaskSessionChanges, ln as SandboxRuntimeHealth, mn as SandboxTerminalRequestOptions, mr as WriteFileOptions, na as SessionInfo, oa as SessionMessageAdmission, on as SandboxPortBinding, or as FileUsageOptions, pn as SandboxTerminalManager, pr as UploadProgress, qi as SendSessionMessageOptions, sr as FileUsageResult, tr as FileRenameResult, ua as TaskSessionCommitResult } from "./types-Cmv31xBh.js";
3
- import { c as InteractiveSessionIdentity, l as InteractiveSessionNotRunningError, r as browserInteractiveControlHolderId } from "./browser-interactive-control-controller-qv26Bpfx.js";
4
- import { t as BrowserInteractiveSessionController } from "./interactive-controller-P0yy6sGl.js";
5
- import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, o as projectAgentTerminalRecord, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-DMaHbXAk.js";
1
+ import { B as ServerError, C as CapabilityError, D as FileWriteConflictError, F as QuotaError, G as ValidationError, L as SandboxError, M as NotFoundError, N as PartialFailureError, P as ProfileFileMountPathError, R as SandboxErrorJson, V as StateError, W as TimeoutError, j as NetworkError, u as ScopedToken, x as AuthError, z as SandboxFailureDetail } from "./terminal-stream-types-NBdVKKFu.js";
2
+ import { $i as SessionExecutionStatus, Bi as CreateSessionOptions, Cn as TerminalStream, Di as SandboxEvent, Fi as CommitTaskSessionOptions, Gi as ListMessagesOptions, Gn as ChunkedUploadResult, Ji as SendSessionMessageRequest, Qi as SessionExecutionInfo, Qn as FileReadBatchResult, Vi as CreateTaskSessionOptions, Wn as ChunkedUploadOptions, Xr as HttpClient, Yi as SentSessionMessage, Zi as SessionEventStreamOptions, Zn as FileReadBatchOptions, aa as SessionMessage, ar as FileTreeResult, cr as FileWriteResult, dn as SandboxTerminalCreateOptions, dr as RenameOptions, fa as TaskSessionInfo, fn as SandboxTerminalInfo, ir as FileTreeOptions, la as TaskSessionChanges, ln as SandboxRuntimeHealth, mn as SandboxTerminalRequestOptions, mr as WriteFileOptions, na as SessionInfo, oa as SessionMessageAdmission, on as SandboxPortBinding, or as FileUsageOptions, pn as SandboxTerminalManager, pr as UploadProgress, qi as SendSessionMessageOptions, sr as FileUsageResult, tr as FileRenameResult, ua as TaskSessionCommitResult } from "./types-CuMa305b.js";
3
+ import { c as InteractiveSessionIdentity, l as InteractiveSessionNotRunningError, r as browserInteractiveControlHolderId } from "./browser-interactive-control-controller-D17JJ8B0.js";
4
+ import { t as BrowserInteractiveSessionController } from "./interactive-controller-DbNjY09X.js";
5
+ import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, o as projectAgentTerminalRecord, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-MsLkgPNu.js";
6
6
 
7
7
  //#region src/lib/chunked-upload.d.ts
8
8
  /** The transport a caller wires this module to — {@link SandboxInstance.runtimeFetch}
@@ -32,7 +32,7 @@ declare function uploadChunked(transport: ChunkedUploadTransport, remotePath: st
32
32
  //#region src/runtime-transport.d.ts
33
33
  interface RuntimeTransport {
34
34
  ensureRunning(): Promise<void>;
35
- fetch(path: string, init?: RequestInit): Promise<Response>;
35
+ fetch: HttpClient["fetch"];
36
36
  }
37
37
  declare class RuntimeApiTransport {
38
38
  protected readonly transport: RuntimeTransport;
@@ -121,7 +121,7 @@ interface SandboxRuntimeClientConfig {
121
121
  baseUrl: string;
122
122
  /** Short-lived `session-runtime` or `read-only` token. */
123
123
  token: string;
124
- /** Request timeout in milliseconds. Defaults to 30 seconds. */
124
+ /** Request timeout in milliseconds. Defaults to `SDK_TIMEOUTS.default`. */
125
125
  timeoutMs?: number;
126
126
  /** Fetch implementation override for Workers, tests, or custom runtimes. */
127
127
  fetch?: typeof globalThis.fetch;
package/dist/runtime.js CHANGED
@@ -1,10 +1,9 @@
1
- import { F as createAgentRunOutcomeTracker, I as deriveAgentResultOutcome, L as deriveAgentRunOutcome, R as projectAgentTerminalRecord, c as SandboxRuntimeApi, t as BrowserInteractiveSessionController } from "./interactive-controller-D4gZ4f2I.js";
2
- import { n as browserInteractiveControlHolderId, s as InteractiveSessionNotRunningError } from "./browser-interactive-control-controller-BiP6TJFP.js";
3
- import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, _ as NotFoundError, b as QuotaError, g as NetworkError, l as CapabilityError, p as FileWriteConflictError, s as AuthError, v as PartialFailureError, w as StateError, y as ProfileFileMountPathError } from "./errors-A-bhwwsE.js";
4
- import { s as uploadChunked } from "./chunked-upload-BjkxykZD.js";
5
- import { r as fetchSandboxApi } from "./api-request-_SFFNVqY.js";
1
+ import { F as createAgentRunOutcomeTracker, I as deriveAgentResultOutcome, L as deriveAgentRunOutcome, R as projectAgentTerminalRecord, c as SandboxRuntimeApi, t as BrowserInteractiveSessionController } from "./interactive-controller-Bs7VQ04W.js";
2
+ import { n as browserInteractiveControlHolderId, s as InteractiveSessionNotRunningError } from "./browser-interactive-control-controller-Bf-DbRCA.js";
3
+ import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, _ as NotFoundError, b as QuotaError, g as NetworkError, l as CapabilityError, p as FileWriteConflictError, s as AuthError, v as PartialFailureError, w as StateError, y as ProfileFileMountPathError } from "./errors-dK3-2RCh.js";
4
+ import { i as fetchSandboxApi, n as SDK_TIMEOUTS } from "./api-request-B0BPgzdp.js";
5
+ import { s as uploadChunked } from "./chunked-upload-BGwaw5np.js";
6
6
  //#region src/runtime-client.ts
7
- const DEFAULT_RUNTIME_TIMEOUT_MS = 3e4;
8
7
  function requireToken(token) {
9
8
  const value = token.trim();
10
9
  if (!value) throw new ValidationError("Scoped runtime token is required");
@@ -23,7 +22,7 @@ function requireBaseUrl(baseUrl) {
23
22
  return url.toString().replace(/\/+$/, "");
24
23
  }
25
24
  function requireTimeout(timeoutMs) {
26
- const value = timeoutMs ?? DEFAULT_RUNTIME_TIMEOUT_MS;
25
+ const value = timeoutMs ?? SDK_TIMEOUTS.default;
27
26
  if (!Number.isFinite(value) || value <= 0) throw new ValidationError("Scoped runtime timeout must be positive");
28
27
  return value;
29
28
  }
@@ -45,7 +44,8 @@ var SandboxRuntimeClient = class extends SandboxRuntimeApi {
45
44
  if (typeof fetchImpl !== "function") throw new ValidationError("Scoped runtime client requires a fetch implementation");
46
45
  super({
47
46
  ensureRunning: async () => void 0,
48
- fetch: async (path, init = {}) => {
47
+ fetch: async (path, requestInit, fetchOptions) => {
48
+ const init = requestInit ?? {};
49
49
  if (!path.startsWith("/") || path.startsWith("//")) throw new ValidationError("Scoped runtime request paths must start with one slash");
50
50
  return fetchSandboxApi({
51
51
  baseUrl,
@@ -62,7 +62,7 @@ var SandboxRuntimeClient = class extends SandboxRuntimeApi {
62
62
  origin: "runtime",
63
63
  endpoint: path
64
64
  })
65
- }, path, init, { bodyDeadline: false });
65
+ }, path, init, fetchOptions);
66
66
  }
67
67
  });
68
68
  this.#auth = auth;
@@ -1,22 +1,22 @@
1
- import { A as requestedPublicProfileDigest, C as runtimeFilesystemPath, D as assertCurrentBackendType, E as applyRequestedModel, F as createAgentRunOutcomeTracker, I as deriveAgentResultOutcome, O as mergeRuntimeBackendConfig, P as withoutRuntimeSecrets, S as encodeTextForWire, U as normalizeEffectiveBackend, _ as mintTraceId, a as assertScopedTokenActive, b as validateAcceptedDispatchRunRef, c as SandboxRuntimeApi, d as appendSessionIdQuery, f as callHeaders, g as isTraceId, h as TRACE_ID_HEADER, i as terminalUpgradeHeadersSupported, j as requestedSecretProfilePublicDigest, k as normalizeRuntimeBackendConfig, l as normalizeSessionInfo, m as assertFileWritePreconditions, n as InteractiveSessionController, p as sessionHeaders, r as TerminalStream, s as requestScopedToken, u as sessionMessageRequestBody, v as resolveTraceId, w as canUseNodeHttp2, x as encodePromptForWire, y as resolveDispatchRunIdentity } from "./interactive-controller-D4gZ4f2I.js";
1
+ import { A as requestedPublicProfileDigest, C as runtimeFilesystemPath, D as assertCurrentBackendType, E as applyRequestedModel, F as createAgentRunOutcomeTracker, I as deriveAgentResultOutcome, O as mergeRuntimeBackendConfig, P as withoutRuntimeSecrets, S as encodeTextForWire, U as normalizeEffectiveBackend, _ as mintTraceId, a as assertScopedTokenActive, b as validateAcceptedDispatchRunRef, c as SandboxRuntimeApi, d as appendSessionIdQuery, f as callHeaders, g as isTraceId, h as TRACE_ID_HEADER, i as terminalUpgradeHeadersSupported, j as requestedSecretProfilePublicDigest, k as normalizeRuntimeBackendConfig, l as normalizeSessionInfo, m as assertFileWritePreconditions, n as InteractiveSessionController, p as sessionHeaders, r as TerminalStream, s as requestScopedToken, u as sessionMessageRequestBody, v as resolveTraceId, w as canUseNodeHttp2, x as encodePromptForWire, y as resolveDispatchRunIdentity } from "./interactive-controller-Bs7VQ04W.js";
2
2
  import { C as boundedIdentifierSchema$1, E as boundedStringSchema$1, g as sha256DigestSchema$1, o as canonicalCandidateDigest$1, s as canonicalCandidateJson$1, u as isCanonicalJsonValue$1 } from "./harness-DMaNgn0S.js";
3
3
  import { t as sha256$1 } from "./sha2-vu4U-x2L.js";
4
- import { A as agentInteractiveSessionStatusMatchesRef, B as PlanContinuationSchema, C as AgentInteractiveSessionStopAcknowledgementSchema, D as agentInteractiveSessionControlClaimMatchesRef, E as agentInteractiveSessionControlClaimIsNewer, F as AgentRunCancellationAcknowledgementSchema, G as InteractionResponseSchema, H as InteractionBindingSchema, I as AgentRunCancellationRequestSchema, L as agentRunCancellationAcknowledgementMatchesRequest, M as agentInteractiveDimensionSchema, N as sameAgentExactRun, O as agentInteractiveSessionPromptAcknowledgementMatchesCommand, P as AgentExactRunControlRefSchema, S as AgentInteractiveSessionStatusSchema, T as agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, U as InteractionRequestSchema, V as InteractionAcknowledgementSchema, W as InteractionResponseCommandSchema, _ as AgentInteractiveSessionControlClaimRequestSchema, b as AgentInteractiveSessionPromptCommandSchema, d as interactiveSessionControlClaimResponseSchema, f as interactiveSessionControlReleaseResponseSchema, g as AgentInteractiveSessionControlClaimAcknowledgementSchema, h as AgentInteractiveSessionAttachSchema, j as agentInteractiveSessionStopAcknowledgementMatchesCommand, l as createInteractiveControlHolderId, m as interactiveSessionStatusResponseSchema, p as interactiveSessionControlValidationResponseSchema, v as AgentInteractiveSessionControlClaimSchema, w as AgentInteractiveSessionStopCommandSchema, x as AgentInteractiveSessionRefSchema, y as AgentInteractiveSessionPromptAcknowledgementSchema } from "./browser-interactive-control-controller-BiP6TJFP.js";
4
+ import { A as agentInteractiveSessionStatusMatchesRef, B as PlanContinuationSchema, C as AgentInteractiveSessionStopAcknowledgementSchema, D as agentInteractiveSessionControlClaimMatchesRef, E as agentInteractiveSessionControlClaimIsNewer, F as AgentRunCancellationAcknowledgementSchema, G as InteractionResponseSchema, H as InteractionBindingSchema, I as AgentRunCancellationRequestSchema, L as agentRunCancellationAcknowledgementMatchesRequest, M as agentInteractiveDimensionSchema, N as sameAgentExactRun, O as agentInteractiveSessionPromptAcknowledgementMatchesCommand, P as AgentExactRunControlRefSchema, S as AgentInteractiveSessionStatusSchema, T as agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, U as InteractionRequestSchema, V as InteractionAcknowledgementSchema, W as InteractionResponseCommandSchema, _ as AgentInteractiveSessionControlClaimRequestSchema, b as AgentInteractiveSessionPromptCommandSchema, d as interactiveSessionControlClaimResponseSchema, f as interactiveSessionControlReleaseResponseSchema, g as AgentInteractiveSessionControlClaimAcknowledgementSchema, h as AgentInteractiveSessionAttachSchema, j as agentInteractiveSessionStopAcknowledgementMatchesCommand, l as createInteractiveControlHolderId, m as interactiveSessionStatusResponseSchema, p as interactiveSessionControlValidationResponseSchema, v as AgentInteractiveSessionControlClaimSchema, w as AgentInteractiveSessionStopCommandSchema, x as AgentInteractiveSessionRefSchema, y as AgentInteractiveSessionPromptAcknowledgementSchema } from "./browser-interactive-control-controller-Bf-DbRCA.js";
5
5
  import { a as ProxySecretReceiptSchema$1, o as canonicalAgentProfileValue$1, r as agentProfileSchema$1 } from "./profile-schema-C1KpT-wS.js";
6
- import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, T as StreamInterruptedError, _ as NotFoundError, a as readResponseJson, d as EdgeNotReadyError, g as NetworkError, i as parseResponseError, l as CapabilityError, n as isTransientWrite, o as retryWhen, r as parseErrorResponse, s as AuthError, t as TerminalStreamError, w as StateError, y as ProfileFileMountPathError } from "./errors-A-bhwwsE.js";
7
- import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-BbJTt2QJ.js";
8
- import { a as backoffDelayMs, o as isUndelivered, r as abortableSleep } from "./retry-policy-Dh-VezcE.js";
9
- import { a as SANDBOX_PROXY_REQUEST_MAX_BYTES, c as PROFILE_FILE_MOUNT_OUTSIDE_ROOTS_CODE, d as isProfileFileMountOutsideRoots, f as profileFileMountOutsideRootsMessage, l as SANDBOX_AGENT_HOME, o as FILE_OPERATION_LIMITS, u as SANDBOX_FILE_API_ABSOLUTE_ROOTS } from "./file-transfer-BSe4ayU9.js";
10
- import { c as awaitSdkResend, l as countSdkRequest, s as uploadChunked, u as takeSdkTurn } from "./chunked-upload-BjkxykZD.js";
11
- import { a as rewrapResponse, i as isReplayableBody, t as IDEMPOTENT_METHODS } from "./api-request-_SFFNVqY.js";
12
- import { n as fetchWithKeepAlive, t as emitTiming } from "./keep-alive-fetch-BIaDMUtu.js";
13
- import { t as SIDECAR_PROXY_ERROR_HEADER } from "./sidecar-proxy-error-DpBLxIof.js";
14
- import { t as parseSSEStream } from "./sse-parser-DOCszo1K.js";
15
- import { t as runPreparedProcess } from "./prepared-process-u1B0b94R.js";
16
- import { a as isBackendType, r as cliAuthReferenceSchema } from "./cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js";
17
- import "./cli-auth-bundle-CMJWI99l.js";
18
- import { n as SandboxLines } from "./lines-7VecgiGd.js";
19
- import { t as downloadFile } from "./file-download-UhMKbMbD.js";
6
+ import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, T as StreamInterruptedError, _ as NotFoundError, a as readResponseJson, d as EdgeNotReadyError, g as NetworkError, i as parseResponseError, l as CapabilityError, n as isTransientWrite, o as retryWhen, r as parseErrorResponse, s as AuthError, t as TerminalStreamError, w as StateError, y as ProfileFileMountPathError } from "./errors-dK3-2RCh.js";
7
+ import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-C0_9B1Hm.js";
8
+ import { a as backoffDelayMs, o as isUndelivered, r as abortableSleep } from "./retry-policy-CI5tyUGr.js";
9
+ import { a as isReplayableBody, i as fetchSandboxApi, n as SDK_TIMEOUTS, o as rewrapResponse, t as IDEMPOTENT_METHODS } from "./api-request-B0BPgzdp.js";
10
+ import { a as SANDBOX_PROXY_REQUEST_MAX_BYTES, c as PROFILE_FILE_MOUNT_OUTSIDE_ROOTS_CODE, d as isProfileFileMountOutsideRoots, f as profileFileMountOutsideRootsMessage, l as SANDBOX_AGENT_HOME, o as FILE_OPERATION_LIMITS, u as SANDBOX_FILE_API_ABSOLUTE_ROOTS } from "./file-transfer-CSL53pv9.js";
11
+ import { c as awaitSdkResend, l as takeSdkTurn, s as uploadChunked } from "./chunked-upload-BGwaw5np.js";
12
+ import { n as fetchWithKeepAlive, t as emitTiming } from "./keep-alive-fetch-C2DX2_rG.js";
13
+ import { t as SIDECAR_PROXY_ERROR_HEADER } from "./sidecar-proxy-error-CeNM5eJj.js";
14
+ import { t as parseSSEStream } from "./sse-parser-CBQzZvkZ.js";
15
+ import { t as runPreparedProcess } from "./prepared-process-B1kSkhn-.js";
16
+ import { a as isBackendType, r as cliAuthReferenceSchema } from "./cli-auth-bundle-C6DtK7GX-Cjs6D-9c.js";
17
+ import "./cli-auth-bundle-DvmJ71bO.js";
18
+ import { n as SandboxLines } from "./lines-DtssoioA.js";
19
+ import { t as downloadFile } from "./file-download-CUNdbymj.js";
20
20
  import { z } from "zod";
21
21
  import { createHash } from "node:crypto";
22
22
  import { constants } from "node:fs";
@@ -258,8 +258,6 @@ const TerminalReplayWindowSchema = z.strictObject({
258
258
  });
259
259
  //#endregion
260
260
  //#region src/client-create-retry.ts
261
- const DEFAULT_CREATE_TIMEOUT_MS = 12e4;
262
- const DEFAULT_GPU_CREATE_TIMEOUT_MS = 900 * 1e3;
263
261
  const CREATE_RETRY_MAX_DELAY_MS = 4e3;
264
262
  /** 503s meaning "cannot place now, ask again"; the key joins any provision that started. `SANDBOX_CREATE_RECONCILING` is absent: it outlasts any budget. */
265
263
  const DEPLOY_WINDOW_RETRY_CODES = new Set([
@@ -292,7 +290,7 @@ function extendableDeadline(atMs) {
292
290
  };
293
291
  }
294
292
  function isDeployWindowCreateError(cause) {
295
- return cause instanceof SandboxError && cause.status === 503 && DEPLOY_WINDOW_RETRY_CODES.has(cause.code);
293
+ return retryWhen(cause) && cause.status === 503 && DEPLOY_WINDOW_RETRY_CODES.has(cause.code);
296
294
  }
297
295
  /** A no-room refusal allocated nothing, so a create giving up on one reports this typed 503. */
298
296
  const isCapacityShortageCreateError = (cause) => isDeployWindowCreateError(cause) && (cause.code === "CAPACITY_EXHAUSTED" || cause.code === "HOST_PRESSURE");
@@ -1161,7 +1159,7 @@ var SandboxInfoCapabilities = class {
1161
1159
  return response;
1162
1160
  } catch (err) {
1163
1161
  options?.signal?.throwIfAborted();
1164
- if (err instanceof StateError) throw err;
1162
+ if (err instanceof StateError || err instanceof TimeoutError) throw err;
1165
1163
  throw new NetworkError(`Failed to connect to sandbox: ${err instanceof Error ? err.message : String(err)}`, {
1166
1164
  cause: err instanceof Error ? err : void 0,
1167
1165
  endpoint: path,
@@ -2829,15 +2827,8 @@ async function edgeVerdict(response) {
2829
2827
  //#endregion
2830
2828
  //#region src/direct-runtime-client.ts
2831
2829
  /**
2832
- * The SDK's direct runtime transport. Every default handle uses it edge
2833
- * first (`SandboxConfig.directExec`). When the connection names the owning
2834
- * host (`connection.hostUrl`), every runtime call goes straight to that host's
2835
- * runtime door at the API's own path on the runtime bearer, over one HTTP/2
2836
- * connection per host. Otherwise exec-family calls go to the cell exec host on
2837
- * the short exec grant and the rest to the cell edge at `connection.runtimeUrl`.
2838
- * A call the host or edge does not serve is sent through the API
2839
- * (runtime-route-policy.ts). `SandboxInstance.direct()` uses it for every
2840
- * runtime call, with no API fallback.
2830
+ * Direct runtime bearer transport: owning host, else cell exec/edge routes.
2831
+ * Edge-first mode falls back to the API by route policy; direct() never does.
2841
2832
  */
2842
2833
  /** Renew a bearer this close to its expiry before sending it. */
2843
2834
  const BEARER_RENEW_BEFORE_MS = 5e3;
@@ -2946,7 +2937,8 @@ var DirectRuntimeHttpClient = class {
2946
2937
  if (connection?.hostUrl && connection.authToken) return {
2947
2938
  useExec: false,
2948
2939
  useHost: true,
2949
- url: `${connection.hostUrl.replace(/\/$/, "")}${path}`,
2940
+ origin: connection.hostUrl,
2941
+ path,
2950
2942
  bearer: connection.authToken,
2951
2943
  expiresAt: connection.authTokenExpiresAt
2952
2944
  };
@@ -2958,7 +2950,8 @@ var DirectRuntimeHttpClient = class {
2958
2950
  return {
2959
2951
  useExec,
2960
2952
  useHost: false,
2961
- url: `${origin.replace(/\/$/, "")}${runtimePath}`,
2953
+ origin,
2954
+ path: runtimePath,
2962
2955
  bearer,
2963
2956
  expiresAt: useExec ? connection?.execTokenExpiresAt : connection?.authTokenExpiresAt
2964
2957
  };
@@ -2989,15 +2982,11 @@ var DirectRuntimeHttpClient = class {
2989
2982
  this.edgeCooldownUntil = Date.now() + EDGE_COOLDOWN_MS;
2990
2983
  return throughApi();
2991
2984
  };
2992
- const isFormDataBody = typeof FormData !== "undefined" && options?.body instanceof FormData;
2993
- if (!headers.has("Content-Type") && !isFormDataBody) headers.set("Content-Type", "application/json");
2994
2985
  const init = {
2995
2986
  ...options,
2996
2987
  headers
2997
2988
  };
2998
- if (options?.body && typeof options.body === "object" && !isFormDataBody) init.duplex = "half";
2999
- const directTimeoutMs = fetchOptions?.timeoutMs;
3000
- if (!init.signal && typeof directTimeoutMs === "number" && directTimeoutMs > 0) init.signal = AbortSignal.timeout(directTimeoutMs);
2989
+ if (options?.body && typeof options.body === "object" && !(typeof FormData !== "undefined" && options.body instanceof FormData)) init.duplex = "half";
3001
2990
  if (this.signal) {
3002
2991
  this.signal.throwIfAborted();
3003
2992
  init.signal = init.signal ? combineAbortSignals([init.signal, this.signal]) : this.signal;
@@ -3008,18 +2997,23 @@ var DirectRuntimeHttpClient = class {
3008
2997
  path
3009
2998
  };
3010
2999
  if (!route) throw new NetworkError("Direct runtime route was withdrawn");
3011
- countSdkRequest();
3012
- if ((route.useHost || route.useExec) && canUseNodeHttp2()) {
3013
- const { fetchDirectHttp2 } = await import("./direct-http2-DU2SK2Wo.js");
3014
- return fetchDirectHttp2(route.url, request, timing);
3015
- }
3016
- return fetchWithKeepAlive(route.url, request, timing);
3000
+ const { fetchDirectHttp2: transport } = (route.useHost || route.useExec) && canUseNodeHttp2() ? await import("./direct-http2-B5bdFrtg.js") : { fetchDirectHttp2: fetchWithKeepAlive };
3001
+ return fetchSandboxApi({
3002
+ baseUrl: route.origin,
3003
+ timeoutMs: this.baseClient.timeoutMs,
3004
+ timeoutError: (ms) => new TimeoutError(`Request timed out after ${ms}ms`, {
3005
+ timeoutMs: ms,
3006
+ origin: "runtime",
3007
+ endpoint: path
3008
+ }),
3009
+ fetchImpl: (url, init) => transport(url, init, timing)
3010
+ }, route.path, request, fetchOptions);
3017
3011
  };
3018
3012
  const sendOrResend = async (request) => {
3019
3013
  try {
3020
3014
  return { sent: await send(request) };
3021
3015
  } catch (error) {
3022
- if (canResendThroughApi && !init.signal?.aborted && !headers.has("x-no-retry") && (replaySafe || isUndelivered(error))) return { resent: await resendThroughApi() };
3016
+ if (canResendThroughApi && !init.signal?.aborted && !(error instanceof TimeoutError) && !headers.has("x-no-retry") && (replaySafe || isUndelivered(error))) return { resent: await resendThroughApi() };
3023
3017
  throw error;
3024
3018
  }
3025
3019
  };
@@ -3051,7 +3045,7 @@ var DirectRuntimeHttpClient = class {
3051
3045
  }
3052
3046
  if (canResendThroughApi && !headers.has("x-no-retry")) {
3053
3047
  const verdict = await edgeVerdict(response);
3054
- if (verdict === "undelivered" || verdict === "unknown" && replaySafe) return resendThroughApi(response);
3048
+ if (verdict === "undelivered" || verdict === "unknown" && replaySafe && (await parseResponseError(response.clone())).retryable) return resendThroughApi(response);
3055
3049
  }
3056
3050
  if (this.onUnreachable && await isRuntimeUnreachable(response)) await this.onUnreachable();
3057
3051
  const responseHeaders = new Headers(response.headers);
@@ -5168,10 +5162,6 @@ function catalogEntry(code) {
5168
5162
  docs: `https://sandbox.tangle.tools/docs/errors#${code.toLowerCase()}`
5169
5163
  };
5170
5164
  }
5171
- /**
5172
- * The one error class. The catalog gives the status, retryability and next
5173
- * step; the message names this occurrence's cause.
5174
- */
5175
5165
  var CatalogError = class extends Error {
5176
5166
  code;
5177
5167
  details;
@@ -5188,7 +5178,6 @@ var CatalogError = class extends Error {
5188
5178
  this.nextStep = entry.nextStep;
5189
5179
  this.name = this.constructor.name;
5190
5180
  }
5191
- /** The `{ success: false, error }` response envelope. */
5192
5181
  toJSON() {
5193
5182
  return {
5194
5183
  success: false,
@@ -6691,6 +6680,7 @@ function isTransientExecError(err, seen = /* @__PURE__ */ new Set()) {
6691
6680
  if (!err || typeof err !== "object") return false;
6692
6681
  if (seen.has(err)) return false;
6693
6682
  seen.add(err);
6683
+ if (err instanceof SandboxError && !err.retryable) return false;
6694
6684
  const e = err;
6695
6685
  const status = errorStatus(e);
6696
6686
  if (status !== void 0 && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true;
@@ -7452,7 +7442,6 @@ var ProfileFileDelivery = class {
7452
7442
  */
7453
7443
  const FIRST_POLL_MS = 250;
7454
7444
  const MAX_POLL_MS = 2e3;
7455
- const DEFAULT_WAIT_TIMEOUT_MS = 10 * 6e4;
7456
7445
  /** An accepted operation ended in failure. `code` names why. */
7457
7446
  var SandboxOperationFailedError = class extends SandboxError {
7458
7447
  operation;
@@ -7603,7 +7592,7 @@ var SandboxOperation = class SandboxOperation {
7603
7592
  * (the server's Retry-After, else full jitter, and the client's retry budget).
7604
7593
  */
7605
7594
  async wait(options = {}) {
7606
- const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
7595
+ const timeoutMs = options.timeoutMs ?? SDK_TIMEOUTS.operationWait;
7607
7596
  const startedAt = Date.now();
7608
7597
  const { signal } = options;
7609
7598
  let [delayMs, capMs, failedReads] = [
@@ -8330,7 +8319,6 @@ function normalizePreviewLink(raw) {
8330
8319
  metadata: raw.metadata
8331
8320
  };
8332
8321
  }
8333
- const PREVIEW_LINK_READY_TIMEOUT_MS = 12e4;
8334
8322
  const PREVIEW_LINK_READY_POLL_INTERVAL_MS = 2e3;
8335
8323
  var SandboxPreviewCapabilities = class extends SandboxGpuCapabilities {
8336
8324
  /**
@@ -8380,7 +8368,7 @@ var SandboxPreviewCapabilities = class extends SandboxGpuCapabilities {
8380
8368
  return normalizePreviewLink((await readResponseJson(await this.runtimeFetch(`/preview-links/${encodeURIComponent(previewId)}`, signal ? { signal } : void 0))).previewLink);
8381
8369
  }
8382
8370
  async previewLinkWaitUntilReady(previewId, options) {
8383
- const timeoutMs = options?.timeoutMs ?? PREVIEW_LINK_READY_TIMEOUT_MS;
8371
+ const timeoutMs = options?.timeoutMs ?? SDK_TIMEOUTS.previewReady;
8384
8372
  const pollIntervalMs = options?.pollIntervalMs ?? PREVIEW_LINK_READY_POLL_INTERVAL_MS;
8385
8373
  if (!Number.isFinite(timeoutMs) || timeoutMs < 1) throw new ValidationError("timeoutMs must be at least 1");
8386
8374
  if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 1) throw new ValidationError("pollIntervalMs must be at least 1");
@@ -8702,8 +8690,6 @@ var SandboxLifecycleEventsCapabilities = class extends SandboxPreviewCapabilitie
8702
8690
  };
8703
8691
  //#endregion
8704
8692
  //#region src/sandbox-lifecycle.ts
8705
- /** Snapshot and retained-stop requests wait for the same bounded source capture. */
8706
- const SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS = 600 * 1e3;
8707
8693
  var SandboxLifecycleCapabilities = class extends SandboxLifecycleEventsCapabilities {
8708
8694
  async stop(options) {
8709
8695
  options?.signal?.throwIfAborted();
@@ -8715,7 +8701,7 @@ var SandboxLifecycleCapabilities = class extends SandboxLifecycleEventsCapabilit
8715
8701
  method: "POST",
8716
8702
  ...options?.retain ? { body: JSON.stringify({ retain: options.retain }) } : {},
8717
8703
  ...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {}
8718
- }, options?.retain ? { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS } : void 0), options?.signal ? { signal: options.signal } : {});
8704
+ }, options?.retain ? { timeoutMs: SDK_TIMEOUTS.snapshot } : void 0), options?.signal ? { signal: options.signal } : {});
8719
8705
  if (noWait && response.status === 202) return new SandboxOperation(parseSandboxOperation((await readResponseJson(response)).operation, {
8720
8706
  kind: "stop",
8721
8707
  sandboxId: this.id
@@ -8841,11 +8827,11 @@ const LIFECYCLE_CONFLICT_WINDOW_MS = 15e3;
8841
8827
  /** A lease-store or storage outage the API answers 503 before or after its effect: a retry is safe. */
8842
8828
  const LIFECYCLE_OUTAGE_CODES = new Set(["SANDBOX_LIFECYCLE_COORDINATION_UNAVAILABLE", "STORAGE_UNAVAILABLE"]);
8843
8829
  function isLifecycleConflict(cause) {
8844
- return cause instanceof SandboxError && (cause.status === 409 && cause.code === "SANDBOX_LIFECYCLE_IN_PROGRESS" || cause.status === 503 && LIFECYCLE_OUTAGE_CODES.has(cause.code));
8830
+ return retryWhen(cause) && (cause.status === 409 && cause.code === "SANDBOX_LIFECYCLE_IN_PROGRESS" || cause.status === 503 && LIFECYCLE_OUTAGE_CODES.has(cause.code));
8845
8831
  }
8846
8832
  /** A DELETE a gateway or release roll dropped (502, 503, no response) is safe to resend. */
8847
8833
  function isDeleteRetry(cause) {
8848
- return isLifecycleConflict(cause) || cause instanceof NetworkError || cause instanceof SandboxError && [502, 503].includes(cause.status);
8834
+ return isLifecycleConflict(cause) || cause instanceof NetworkError || retryWhen(cause) && [502, 503].includes(cause.status);
8849
8835
  }
8850
8836
  /**
8851
8837
  * Run one lifecycle mutation, re-attempting only the failures `retry` names
@@ -10047,10 +10033,11 @@ var SandboxCodeOperations = class extends SandboxRuntimeOperations {
10047
10033
  env: options?.env,
10048
10034
  cwd: options?.cwd
10049
10035
  })
10050
- }));
10036
+ }, { timeoutMs: (options?.timeoutMs || SDK_TIMEOUTS.runCode) + SDK_TIMEOUTS.margin }));
10051
10037
  if (!payload.success || !payload.data) throw new Error(payload.error?.message ?? "runCode failed without a typed error");
10052
10038
  return payload.data;
10053
10039
  }
10040
+ /** Timeout: `options.timeoutMs` (default 30000 ms) plus `SDK_TIMEOUTS.margin`. */
10054
10041
  async exec(command, options) {
10055
10042
  const headers = callHeaders(options);
10056
10043
  await this.ensureRunning(options?.signal);
@@ -10068,7 +10055,7 @@ var SandboxCodeOperations = class extends SandboxRuntimeOperations {
10068
10055
  timeoutMs,
10069
10056
  blocking: true
10070
10057
  })
10071
- }, timeoutMs + 15e3))).data;
10058
+ }, timeoutMs + SDK_TIMEOUTS.margin))).data;
10072
10059
  if (!result || typeof result.exitCode !== "number" || typeof result.stdout !== "string" || typeof result.stderr !== "string") throw new ServerError("Sandbox process response was malformed", { status: 502 });
10073
10060
  return {
10074
10061
  exitCode: result.exitCode,
@@ -12027,7 +12014,7 @@ var SandboxInteractiveCapabilities = class extends SandboxPromptCapabilities {
12027
12014
  var SandboxSessionEvidenceCapabilities = class extends SandboxInteractiveCapabilities {
12028
12015
  /** @internal — invoked before the sandbox is deleted. */
12029
12016
  async _sessionExportRawEvidence(id, destination, options) {
12030
- const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-BgWqaQcM.js");
12017
+ const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-Cfy_3_3y.js");
12031
12018
  await this.ensureRunning();
12032
12019
  await this.refresh();
12033
12020
  return exportRawEvidenceDirectory((signal, archiveId, cancel) => this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/raw-evidence/archive?${new URLSearchParams([
@@ -12058,7 +12045,7 @@ var SandboxSessionEvidenceCapabilities = class extends SandboxInteractiveCapabil
12058
12045
  * and the byte and file bounds are verified before the directory appears.
12059
12046
  */
12060
12047
  async exportRawEvidence(destination, options) {
12061
- const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-BgWqaQcM.js");
12048
+ const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-Cfy_3_3y.js");
12062
12049
  await this.ensureRunning();
12063
12050
  await this.refresh();
12064
12051
  return exportRawEvidenceDirectory((signal, archiveId, cancel) => this.runtimeFetch(`/agents/raw-evidence/archive?${new URLSearchParams({
@@ -13054,7 +13041,6 @@ function interpretWorkspaceOperationLookup(body, kind) {
13054
13041
  }
13055
13042
  const SNAPSHOT_RESTORE_HOLD_MS = 1e4;
13056
13043
  const SNAPSHOT_RESTORE_POLL_FLOOR_MS = 500;
13057
- const SNAPSHOT_RESTORE_TIMEOUT_MS = 600 * 1e3;
13058
13044
  const SNAPSHOT_VISIBILITY_POLL_INTERVAL_MS = 1e3;
13059
13045
  const SNAPSHOT_VISIBILITY_TIMEOUT_MS = 120 * 1e3;
13060
13046
  function toSnapshotResult(data, provenance) {
@@ -13099,7 +13085,7 @@ var SandboxSnapshotCapabilities = class extends SandboxTurnCapabilities {
13099
13085
  method: "POST",
13100
13086
  ...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
13101
13087
  body: JSON.stringify({ tags: options?.tags })
13102
- }, { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS });
13088
+ }, { timeoutMs: SDK_TIMEOUTS.snapshot });
13103
13089
  const data = await readResponseJson(response);
13104
13090
  const snapshotId = data.snapshotId ?? data.id;
13105
13091
  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)}`, { status: response.status });
@@ -13132,7 +13118,7 @@ var SandboxSnapshotCapabilities = class extends SandboxTurnCapabilities {
13132
13118
  method: "POST",
13133
13119
  ...options.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {},
13134
13120
  body: JSON.stringify({ tags: options.tags })
13135
- }, { timeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS });
13121
+ }, { timeoutMs: SDK_TIMEOUTS.snapshot });
13136
13122
  const body = await readResponseJson(response);
13137
13123
  if (response.status === 202) return new SandboxOperation(parseSandboxOperation(body.operation, {
13138
13124
  kind: "snapshot",
@@ -13275,7 +13261,7 @@ var SandboxSnapshotCapabilities = class extends SandboxTurnCapabilities {
13275
13261
  method: "POST",
13276
13262
  headers,
13277
13263
  ...init
13278
- }, { timeoutMs: SNAPSHOT_RESTORE_TIMEOUT_MS });
13264
+ }, { timeoutMs: SDK_TIMEOUTS.snapshot });
13279
13265
  const data = await readResponseJson(response);
13280
13266
  if (response.status === 202) return this.waitForSnapshotRestore(snapshotId, data);
13281
13267
  return toSnapshotResult(data, state(this).profileProvenance);
@@ -13285,7 +13271,7 @@ var SandboxSnapshotCapabilities = class extends SandboxTurnCapabilities {
13285
13271
  * the job's end, is the first status read; only an unfinished one polls.
13286
13272
  */
13287
13273
  async waitForSnapshotRestore(snapshotId, accepted) {
13288
- const deadline = Date.now() + SNAPSHOT_RESTORE_TIMEOUT_MS;
13274
+ const deadline = Date.now() + SDK_TIMEOUTS.snapshot;
13289
13275
  let status = accepted;
13290
13276
  let polledAt = 0;
13291
13277
  while (Date.now() < deadline) {
@@ -13306,7 +13292,7 @@ var SandboxSnapshotCapabilities = class extends SandboxTurnCapabilities {
13306
13292
  polledAt = Date.now();
13307
13293
  status = await readResponseJson(await state(this).client.fetch(`/v1/sandboxes/${this.id}/snapshots/jobs/${encodeURIComponent(accepted.jobId)}?waitMs=${SNAPSHOT_RESTORE_HOLD_MS}`));
13308
13294
  }
13309
- throw new TimeoutError(`Request timed out after ${SNAPSHOT_RESTORE_TIMEOUT_MS}ms`, { timeoutMs: SNAPSHOT_RESTORE_TIMEOUT_MS });
13295
+ throw new TimeoutError(`Request timed out after ${SDK_TIMEOUTS.snapshot}ms`, { timeoutMs: SDK_TIMEOUTS.snapshot });
13310
13296
  }
13311
13297
  async waitForSnapshotVisible(snapshotId, fallback) {
13312
13298
  const deadline = Date.now() + SNAPSHOT_VISIBILITY_TIMEOUT_MS;
@@ -13680,7 +13666,7 @@ async function exportTraceBundle(bundle, sink) {
13680
13666
  const fetchImpl = sink.fetch ?? globalThis.fetch;
13681
13667
  if (!fetchImpl) throw new Error("Trace export requires fetch");
13682
13668
  const controller = new AbortController();
13683
- const timeout = setTimeout(() => controller.abort(), sink.timeoutMs ?? 3e4);
13669
+ const timeout = setTimeout(() => controller.abort(), sink.timeoutMs ?? SDK_TIMEOUTS.default);
13684
13670
  try {
13685
13671
  const response = await fetchImpl(sink.url, {
13686
13672
  method: "POST",
@@ -14192,7 +14178,7 @@ var SandboxFilesystemOperations = class extends DeclaredFilesystemOperations {
14192
14178
  totalBytes: size,
14193
14179
  percentage: 0
14194
14180
  });
14195
- const { uploadChunkedFromFile } = await import("./chunked-upload-file-B2KFimpz.js");
14181
+ const { uploadChunkedFromFile } = await import("./chunked-upload-file-BnV8qgwV.js");
14196
14182
  await uploadChunkedFromFile({ fetch: (path, init) => this.host.runtimeFetch(path, init) }, remotePath, localPath, {
14197
14183
  mode: options?.permissions,
14198
14184
  onProgress: options?.onProgress ? (progress) => {
@@ -14735,7 +14721,6 @@ function parseWorkspaceImagePublishResultForRepository(value, repository) {
14735
14721
  }
14736
14722
  //#endregion
14737
14723
  //#region src/workspace-images.ts
14738
- const DEFAULT_WORKSPACE_IMAGE_CLIENT_TIMEOUT_MS = 99e4;
14739
14724
  const WORKSPACE_IMAGE_REQUEST_ATTEMPTS = 2;
14740
14725
  const MAX_WORKSPACE_IMAGE_RESPONSE_BYTES = 64 * 1024;
14741
14726
  const MAX_TIMER_DELAY_MS = 2147483647;
@@ -14819,7 +14804,7 @@ var WorkspaceImages = class {
14819
14804
  if (options.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > MAX_TIMER_DELAY_MS)) throw new TypeError(`workspace image timeoutMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}`);
14820
14805
  if (options.idempotencyKey !== void 0 && !IDEMPOTENCY_KEY_PATTERN.test(options.idempotencyKey)) throw new TypeError("workspace image idempotencyKey must be 16-128 letters, numbers, underscores, or dashes");
14821
14806
  const path = `/v1/sandboxes/${encodeURIComponent(this.sandboxId)}/images`;
14822
- const timeoutMs = options.timeoutMs ?? DEFAULT_WORKSPACE_IMAGE_CLIENT_TIMEOUT_MS;
14807
+ const timeoutMs = options.timeoutMs ?? SDK_TIMEOUTS.workspaceImage;
14823
14808
  const deadline = Date.now() + timeoutMs;
14824
14809
  const timeoutSignal = AbortSignal.timeout(timeoutMs);
14825
14810
  const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
@@ -14887,7 +14872,7 @@ var WorkspaceImages = class {
14887
14872
  method: "POST",
14888
14873
  path
14889
14874
  }, response.headers);
14890
- if (error.code === "IMAGE_PUBLISH_OUTCOME_UNKNOWN" && attempt < WORKSPACE_IMAGE_REQUEST_ATTEMPTS && Date.now() < deadline) continue;
14875
+ if (error.retryable && error.code === "IMAGE_PUBLISH_OUTCOME_UNKNOWN" && attempt < WORKSPACE_IMAGE_REQUEST_ATTEMPTS && Date.now() < deadline) continue;
14891
14876
  throw error;
14892
14877
  }
14893
14878
  const parsed = parseWorkspaceImagePublishResultForRepository((() => {
@@ -15100,4 +15085,4 @@ var SandboxInstance = class SandboxInstance extends SandboxEgressCapabilities {
15100
15085
  }
15101
15086
  };
15102
15087
  //#endregion
15103
- export { isCapacityShortageCreateError as $, ProfileUnsupportedError as A, normalizeConnection as B, SandboxOperationFailedError as C, validateDeferredProfileFileMounts as D, splitInlineProfileSkills as E, normalizeSandboxCreateReceipt as F, CAPACITY_ETA_WAIT_MAX_MS as G, normalizeProxySecretReceipt as H, normalizeStartupDiagnostics as I, DEPLOY_WINDOW_RETRY_MS as J, DEFAULT_CREATE_TIMEOUT_MS as K, readFilesystemIncarnationTuple as L, isMaterializerHarness as M, materializeProfile as N, isRetryableProfileFileMaterializeFailure as O, normalizeCaptureProof as P, generateIdempotencyKey as Q, dateOf as R, SandboxOperation as S, splitInlineProfileFileMounts as T, normalizeSandboxShape as U, normalizeEgressPolicyFields as V, CAPACITY_ETA_MARGIN_MS as W, createRetryDelayMs as X, awaitCreateResend as Y, extendableDeadline as Z, collectAgentFinalMessageText as _, buildTraceExportPayload as a, isToolBearingEvent as b, toOtelJson as c, sandboxLedgerUsd as d, isDeployWindowCreateError as et, InteractiveSessionHandle as f, applySandboxEventText as g, createInteractiveTerminalSession as h, MAX_EGRESS_DENIALS_LIMIT as i, enforceWorkspacePlanSupport as j, HARNESS_LAUNCH_MATERIALIZE_OPTIONS as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, isRetryableCreateError as nt, exportTraceBundle as o, InteractiveTerminalFrameLog as p, DEFAULT_GPU_CREATE_TIMEOUT_MS as q, WorkspaceImages as r, canonicalAgentProfileDigest as rt, otelTraceIdForTangleTrace as s, SandboxInstance as t, isRateLimitCreateError as tt, SandboxSession as u, collectAgentResponseText as v, materializeProfileFileMounts as w, ManagedProcessClient as x, getSandboxEventText as y, parseLifecycleTimes as z };
15088
+ export { isRateLimitCreateError as $, ProfileUnsupportedError as A, normalizeConnection as B, SandboxOperationFailedError as C, validateDeferredProfileFileMounts as D, splitInlineProfileSkills as E, normalizeSandboxCreateReceipt as F, CAPACITY_ETA_WAIT_MAX_MS as G, normalizeProxySecretReceipt as H, normalizeStartupDiagnostics as I, createRetryDelayMs as J, DEPLOY_WINDOW_RETRY_MS as K, readFilesystemIncarnationTuple as L, isMaterializerHarness as M, materializeProfile as N, isRetryableProfileFileMaterializeFailure as O, normalizeCaptureProof as P, isDeployWindowCreateError as Q, dateOf as R, SandboxOperation as S, splitInlineProfileFileMounts as T, normalizeSandboxShape as U, normalizeEgressPolicyFields as V, CAPACITY_ETA_MARGIN_MS as W, generateIdempotencyKey as X, extendableDeadline as Y, isCapacityShortageCreateError as Z, collectAgentFinalMessageText as _, buildTraceExportPayload as a, isToolBearingEvent as b, toOtelJson as c, sandboxLedgerUsd as d, isRetryableCreateError as et, InteractiveSessionHandle as f, applySandboxEventText as g, createInteractiveTerminalSession as h, MAX_EGRESS_DENIALS_LIMIT as i, enforceWorkspacePlanSupport as j, HARNESS_LAUNCH_MATERIALIZE_OPTIONS as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, exportTraceBundle as o, InteractiveTerminalFrameLog as p, awaitCreateResend as q, WorkspaceImages as r, otelTraceIdForTangleTrace as s, SandboxInstance as t, canonicalAgentProfileDigest as tt, SandboxSession as u, collectAgentResponseText as v, materializeProfileFileMounts as w, ManagedProcessClient as x, getSandboxEventText as y, parseLifecycleTimes as z };
@@ -1,4 +1,4 @@
1
- import { a as anumber, c as concatBytes$1, f as randomBytes, h as toBytes, i as ahash, l as createHasher$1, n as abytes$1, o as aoutput, p as rotr, r as aexists, s as clean, t as Hash, u as createView, x as split } from "./utils-CK-x8vXj.js";
1
+ import { a as anumber, c as concatBytes$1, f as randomBytes, h as toBytes, i as ahash, l as createHasher$1, n as abytes$1, o as aoutput, p as rotr, r as aexists, s as clean, t as Hash, u as createView, x as split } from "./utils-DqiOGAK5.js";
2
2
  //#region ../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
3
3
  /**
4
4
  * Internal Merkle-Damgard hash utils.
@@ -1,4 +1,4 @@
1
- import { mt as SeatOwnerTransport } from "./client-DvvRMxKx.js";
1
+ import { ht as SeatOwnerTransport } from "./client-BTpWpGs-.js";
2
2
 
3
3
  //#region src/select-seat-command.d.ts
4
4
  /** Public reply bound; the owner prints one metadata object. */
@@ -1,4 +1,4 @@
1
- import { D as ValidationError, S as SandboxError } from "./errors-A-bhwwsE.js";
1
+ import { D as ValidationError, S as SandboxError } from "./errors-dK3-2RCh.js";
2
2
  import { spawn } from "node:child_process";
3
3
  //#region src/select-seat-command.ts
4
4
  /**
@@ -1,6 +1,7 @@
1
- import { n as combineAbortSignals } from "../abort-signal-BbJTt2QJ.js";
2
- import "../sidecar-proxy-error-DpBLxIof.js";
3
- import { t as parseSSEStream } from "../sse-parser-DOCszo1K.js";
1
+ import { n as combineAbortSignals } from "../abort-signal-C0_9B1Hm.js";
2
+ import { i as fetchSandboxApi } from "../api-request-B0BPgzdp.js";
3
+ import "../sidecar-proxy-error-CeNM5eJj.js";
4
+ import { t as parseSSEStream } from "../sse-parser-CBQzZvkZ.js";
4
5
  import { PART_TEXT, PART_TEXT_SUFFIX } from "@tangle-network/agent-core/sse";
5
6
  //#region ../../../packages/runtime-contracts/dist/session-gateway.js
6
7
  /**
@@ -60,22 +61,9 @@ function calculateSessionStreamConnectionQuality(metrics, isConnected) {
60
61
  //#endregion
61
62
  //#region src/session-gateway/client.ts
62
63
  /**
63
- * SessionGatewayClient: one agent session's events, read from the sandbox's
64
- * cell edge, so no control-plane process holds a socket for them.
65
- *
66
- * The client reads `GET {url}/agents/events`, where a browser's `url` is the
67
- * Sandbox API proxy (`ScopedToken.sidecarProxyUrl`) because the box host
68
- * is server-facing; a server may read the box host. While the session runs a
69
- * turn, it reads that turn's execution stream (`executionId`): every frame
70
- * comes from the sidecar's event store with its store id, and an attach
71
- * resumes after the last delivered id (`since`), so a drop loses nothing and
72
- * repeats nothing. Between turns it reads the session stream, which carries
73
- * the session's container events (ports, sidecar, Hub); a turn frame there
74
- * makes the client move to that turn's execution stream from its first
75
- * event. Each attach first asks the runtime which turn is running
76
- * (`GET /agents/sessions/{id}`).
77
- *
78
- * Browser-safe: global `fetch` and streams only.
64
+ * Browser-safe session events from the API proxy or owning host.
65
+ * Execution-store ids resume without gaps/duplicates; a session turn frame
66
+ * switches to that execution's stream, then returns to session events.
79
67
  */
80
68
  const DEFAULTS = {
81
69
  autoReconnect: true,
@@ -180,7 +168,10 @@ var SessionGatewayClient = class {
180
168
  const url = runtimeBaseUrl(config.url);
181
169
  const fetchImpl = config.fetch ?? globalThis.fetch;
182
170
  if (typeof fetchImpl !== "function") throw new Error("SessionGatewayClient requires a fetch implementation");
183
- this.#fetch = (input, init) => fetchImpl(input, init);
171
+ this.#fetch = (input, init) => fetchSandboxApi({
172
+ baseUrl: "",
173
+ fetchImpl
174
+ }, String(input), init);
184
175
  this.#config = {
185
176
  url,
186
177
  sessionId,