@tangle-network/sandbox 1.0.231 → 1.0.233

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 (81) 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-execution-preparation-BJChICex.js +18 -0
  7. package/dist/agent-execution-preparation-receipt-BIFxqyr5.js +250 -0
  8. package/dist/{agent-run-outcome-DMaHbXAk.d.ts → agent-run-outcome-B0nURFpG.d.ts} +3 -2
  9. package/dist/{api-request-_SFFNVqY.js → api-request-dyabkosT.js} +34 -9
  10. package/dist/auth/index.d.ts +2 -2
  11. package/dist/auth/index.js +2 -2
  12. package/dist/{browser-interactive-control-controller-BiP6TJFP.js → browser-interactive-control-controller-BM2p1dBp.js} +16 -252
  13. package/dist/{browser-interactive-control-controller-qv26Bpfx.d.ts → browser-interactive-control-controller-CcUjQEfa.d.ts} +1 -1
  14. package/dist/{chunked-upload-BjkxykZD.js → chunked-upload-BlvgxPWx.js} +4 -5
  15. package/dist/{chunked-upload-file-B2KFimpz.js → chunked-upload-file-DOeLpMO0.js} +2 -2
  16. package/dist/cli-auth-bundle-BLAtE6Dc.js +2 -0
  17. package/dist/{client-OlxlnLwV.js → client-BS-PR_-j.js} +38 -47
  18. package/dist/{client-DvvRMxKx.d.ts → client-DlTDphmI.d.ts} +38 -32
  19. package/dist/collaboration/index.d.ts +1 -1
  20. package/dist/collaboration/index.js +1 -1
  21. package/dist/{collaboration-DZ8ptALs.js → collaboration-Dz20mN9a.js} +20 -27
  22. package/dist/core-CUZyz-U8.js +161 -0
  23. package/dist/core.d.ts +6 -6
  24. package/dist/core.js +6 -5
  25. package/dist/{direct-http2-DU2SK2Wo.js → direct-http2-Bgb2lHte.js} +1 -1
  26. package/dist/{errors-A-bhwwsE.js → error-catalog-CAbzw67O.js} +1 -382
  27. package/dist/errors-nXGKGVFe.js +382 -0
  28. package/dist/{file-download-UhMKbMbD.js → file-download-BjkrYzy_.js} +1 -1
  29. package/dist/{index-Cip3q_xe.d.ts → index-DE5n6mot.d.ts} +13 -23
  30. package/dist/index.d.ts +12 -12
  31. package/dist/index.js +29 -25
  32. package/dist/intelligence/index.d.ts +41 -109
  33. package/dist/intelligence/index.js +60 -73
  34. package/dist/interactive-control.d.ts +1 -1
  35. package/dist/interactive-control.js +1 -1
  36. package/dist/{interactive-controller-D4gZ4f2I.js → interactive-controller-DDPdZa2H.js} +20 -54
  37. package/dist/{interactive-controller-P0yy6sGl.d.ts → interactive-controller-sEU_J6Bc.d.ts} +3 -3
  38. package/dist/lib/prepared-evidence.js +1 -1
  39. package/dist/lib/prepared-process.js +1 -1
  40. package/dist/{lines-7VecgiGd.js → lines-CSGBHEjR.js} +1 -1
  41. package/dist/{lines-DNXdVbGO.d.ts → lines-qvpmwN_2.d.ts} +1 -1
  42. package/dist/lines.d.ts +1 -1
  43. package/dist/lines.js +1 -1
  44. package/dist/{local-cli-auth-CPS9yuTc.js → local-cli-auth-CO0byocv.js} +1 -1
  45. package/dist/{mcp-local-CIXZFqF4.js → mcp-local-Dz_Sehz0.js} +4 -4
  46. package/dist/{prepared-evidence-Byty5p51.js → prepared-evidence-ibAysmX8.js} +2 -2
  47. package/dist/{prepared-process-u1B0b94R.js → prepared-process-DQ_68Ofg.js} +2 -2
  48. package/dist/{preview-CNfYklE6.d.ts → preview-BC_wLaA2.d.ts} +3 -3
  49. package/dist/{public-templates-CPvDf8CH.d.ts → public-templates-WuvmbvzY.d.ts} +2 -2
  50. package/dist/public-templates.d.ts +1 -1
  51. package/dist/public-templates.js +1 -1
  52. package/dist/{raw-evidence-archive-BgWqaQcM.js → raw-evidence-archive-Cz4j8VMw.js} +2 -2
  53. package/dist/{retry-policy-Dh-VezcE.js → retry-policy-oW3_ljoc.js} +2 -24
  54. package/dist/runtime.d.ts +7 -7
  55. package/dist/runtime.js +9 -9
  56. package/dist/{sandbox-Dvk2PYnL.js → sandbox-OyCRplrI.js} +65 -91
  57. package/dist/{secp256k1-Cbp9tbkX.js → secp256k1-ZiYFbGjz.js} +1 -1
  58. package/dist/{core-D7czAW25.js → select-seat-B4Y-7vIq.js} +40 -171
  59. package/dist/select-seat-command.d.ts +9 -3
  60. package/dist/select-seat-command.js +69 -57
  61. package/dist/session-gateway/index.js +11 -20
  62. package/dist/sidecar-proxy-error-DTdbCbUM.js +4 -0
  63. package/dist/tangle/index.d.ts +1 -1
  64. package/dist/tangle/index.js +1 -1
  65. package/dist/{tangle-DWzUnb1Y.js → tangle-Crxw_6V-.js} +22 -17
  66. package/dist/{terminal-stream-types-DB8V0hiG.d.ts → terminal-stream-types-eE97lZ-5.d.ts} +0 -1
  67. package/dist/{types-Cmv31xBh.d.ts → types-Cs5eJzOK.d.ts} +17 -57
  68. package/package.json +5 -5
  69. package/dist/cli-auth-bundle-CMJWI99l.js +0 -2
  70. package/dist/sidecar-proxy-error-DpBLxIof.js +0 -24
  71. /package/dist/{abort-signal-BbJTt2QJ.js → abort-signal-CRxC2dlT.js} +0 -0
  72. /package/dist/{cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js → cli-auth-bundle-C6DtK7GX-mBUPER0R.js} +0 -0
  73. /package/dist/{cli-auth-bundle-Wg3x2hd2.d.ts → cli-auth-bundle-CjSu4D9W.d.ts} +0 -0
  74. /package/dist/{file-transfer-BSe4ayU9.js → file-transfer-DOSTbUSR.js} +0 -0
  75. /package/dist/{index-CDtEPygc.d.ts → index-C-_HY5NY.d.ts} +0 -0
  76. /package/dist/{index-YbAo-so_.d.ts → index-o31uwAkX.d.ts} +0 -0
  77. /package/dist/{keep-alive-fetch-BIaDMUtu.js → keep-alive-fetch-sGVP8skk.js} +0 -0
  78. /package/dist/{preview-operations-B3TTvqlm.js → preview-operations-DWL78boI.js} +0 -0
  79. /package/dist/{retry-after-header-DUdCC0KJ.js → retry-after-header-BZbs5rig.js} +0 -0
  80. /package/dist/{sse-parser-DOCszo1K.js → sse-parser-BCG3iL9j.js} +0 -0
  81. /package/dist/{utils-CK-x8vXj.js → utils-BT2q9nkO.js} +0 -0
@@ -0,0 +1,382 @@
1
+ import { n as HOST_AGENT_RESTART_KINDS, r as catalogEntry, t as ERROR_CATALOG } from "./error-catalog-CAbzw67O.js";
2
+ import { t as parseSandboxRetryAfterHeader } from "./retry-after-header-BZbs5rig.js";
3
+ //#region src/error-classes.ts
4
+ const STATUS_CODE = {
5
+ 400: "VALIDATION_ERROR",
6
+ 401: "UNAUTHORIZED",
7
+ 402: "PAYMENT_REQUIRED",
8
+ 403: "FORBIDDEN",
9
+ 404: "NOT_FOUND",
10
+ 408: "TIMEOUT",
11
+ 409: "INVALID_STATE",
12
+ 410: "EXPIRED",
13
+ 413: "PAYLOAD_TOO_LARGE",
14
+ 422: "VALIDATION_ERROR",
15
+ 424: "NOT_CONNECTED",
16
+ 425: "NOT_READY",
17
+ 429: "RATE_LIMITED",
18
+ 501: "UNSUPPORTED",
19
+ 502: "UPSTREAM_ERROR",
20
+ 503: "UNAVAILABLE",
21
+ 504: "TIMEOUT",
22
+ 524: "TIMEOUT"
23
+ };
24
+ /** Cluster of a wire code the catalog does not list yet, by its name (design note, section 2). */
25
+ const NAME_CODE = [
26
+ [/QUOTA_EXCEEDED$|CREDIT_EXHAUSTED$/, "QUOTA_EXCEEDED"],
27
+ [/RATE_LIMIT/, "RATE_LIMITED"],
28
+ [/_IN_PROGRESS$|_BUSY$|_PENDING$|_RECONCILING$|_CONTENDED$/, "IN_PROGRESS"],
29
+ [/_NOT_READY$|_RESTARTING$|_STARTING$/, "NOT_READY"],
30
+ [/_DISABLED$|_NOT_ENABLED$/, "FEATURE_DISABLED"],
31
+ [/_NOT_CONFIGURED$|CONFIGURATION/, "CONFIGURATION_ERROR"],
32
+ [/_NOT_FOUND$/, "NOT_FOUND"],
33
+ [/_CONFLICT$/, "CONFLICT"],
34
+ [/PARTIAL_FAILURE$/, "OPERATION_FAILED"],
35
+ [/_TIMEOUT$|_TIMED_OUT$/, "TIMEOUT"],
36
+ [/^TRANSPORT$/, "NETWORK_ERROR"],
37
+ [/UNSUPPORTED$|NOT_IMPLEMENTED$/, "UNSUPPORTED"]
38
+ ];
39
+ /** Resolve a wire code by catalog, name cluster, HTTP status, then fallback. */
40
+ function catalogCode(wireCode, status, fallback = "INTERNAL_ERROR") {
41
+ if (Object.hasOwn(ERROR_CATALOG, wireCode)) return wireCode;
42
+ return NAME_CODE.find(([pattern]) => pattern.test(wireCode))?.[1] ?? (status === void 0 ? void 0 : STATUS_CODE[status]) ?? fallback;
43
+ }
44
+ var SandboxError = class extends Error {
45
+ code;
46
+ catalogCode;
47
+ /** HTTP status the server answered, else the catalog status of `catalogCode`. */
48
+ status;
49
+ retryable;
50
+ nextStep;
51
+ docs;
52
+ constructor(message, metadata = {}) {
53
+ const { code, status, cause, ...fields } = metadata;
54
+ super(message, cause === void 0 ? void 0 : { cause });
55
+ const fallback = ALIAS_CODE.get(new.target) ?? "INTERNAL_ERROR";
56
+ this.code = code ?? (status === void 0 ? void 0 : STATUS_CODE[status]) ?? fallback;
57
+ this.catalogCode = catalogCode(this.code, status, fallback);
58
+ const entry = catalogEntry(this.catalogCode);
59
+ this.status = status ?? entry.status;
60
+ this.retryable = entry.retryable;
61
+ this.nextStep = entry.nextStep;
62
+ this.docs = entry.docs;
63
+ Object.assign(this, fields);
64
+ this.name = new.target.name;
65
+ }
66
+ /** @deprecated Shipped in 1.0.191–1.0.195; removed in 2.0.0. Read `code`. */
67
+ get wireCode() {
68
+ return this.code;
69
+ }
70
+ };
71
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "UNAUTHORIZED"`. */
72
+ var AuthError = class extends SandboxError {};
73
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "NOT_FOUND"`. */
74
+ var NotFoundError = class extends SandboxError {};
75
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "QUOTA_EXCEEDED"` or `"RATE_LIMITED"`. */
76
+ var QuotaError = class extends SandboxError {};
77
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "UNSUPPORTED"` or `"FEATURE_DISABLED"`. */
78
+ var CapabilityError = class extends SandboxError {};
79
+ /** @deprecated Removed in 2.0.0; check `code === "GPU_PROVIDER_NOT_CONFIGURED"`. */
80
+ var GpuProviderNotConfiguredError = class extends CapabilityError {};
81
+ /** @deprecated Removed in 2.0.0; check `code` for `COMPLIANCE_NOT_ENTITLED` or `COMPLIANCE_CELL_UNAVAILABLE`. */
82
+ var CompliancePlacementError = class extends SandboxError {};
83
+ /** @deprecated Removed in 2.0.0; read `failures`. */
84
+ var PartialFailureError = class extends SandboxError {};
85
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "VALIDATION_ERROR"`. */
86
+ var ValidationError = class extends SandboxError {};
87
+ /** @deprecated Removed in 2.0.0; check `code` and read `path`. */
88
+ var ProfileFileMountPathError = class extends SandboxError {};
89
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "INVALID_STATE"`. */
90
+ var StateError = class extends SandboxError {};
91
+ /** @deprecated Removed in 2.0.0; check `code === "EDGE_NOT_READY"`. */
92
+ var EdgeNotReadyError = class extends SandboxError {};
93
+ /** @deprecated Removed in 2.0.0; check `code === "FILE_WRITE_CONFLICT"`. */
94
+ var FileWriteConflictError = class extends SandboxError {};
95
+ /** @deprecated Removed in 2.0.0; check `code === "KEY_BUDGET_EXHAUSTED"`. */
96
+ var KeyBudgetExhaustedError = class extends SandboxError {};
97
+ /** @deprecated Removed in 2.0.0; check `code === "EGRESS_PROXY_RECOVERY_REQUIRED"`. */
98
+ var EgressProxyRecoveryError = class extends SandboxError {};
99
+ /** @deprecated Removed in 2.0.0; check `code === "RESUME_ENV_REQUIRED"` and read `missingEnvKeys`. */
100
+ var ResumeEnvRequiredError = class extends SandboxError {};
101
+ /** @deprecated Removed in 2.0.0; check `code === "BRANCH_FANOUT_EXCEEDS_HOST"` and read `maxChildren`. */
102
+ var BranchFanoutExceedsHostError = class extends SandboxError {};
103
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "TIMEOUT"`. */
104
+ var TimeoutError = class extends SandboxError {};
105
+ /** @deprecated Removed in 2.0.0; check `catalogCode === "NETWORK_ERROR"`. */
106
+ var NetworkError = class extends SandboxError {};
107
+ /**
108
+ * The stream of an admitted execution ended without its terminal event and
109
+ * the SDK could not rejoin it. The outcome is UNKNOWN, never a failure
110
+ * verdict: rejoin with `streamPrompt(message, { executionId, lastEventId,
111
+ * sessionId })`, or read the session status.
112
+ * @deprecated Removed in 2.0.0; check `code === "STREAM_INTERRUPTED"`.
113
+ */
114
+ var StreamInterruptedError = class extends SandboxError {};
115
+ /** @deprecated Removed in 2.0.0; check `status >= 500`. */
116
+ var ServerError = class extends SandboxError {};
117
+ /** Each alias, its default code, and the wire codes the parse point builds it for. */
118
+ const ALIASES = [
119
+ [AuthError, "UNAUTHORIZED"],
120
+ [NotFoundError, "NOT_FOUND"],
121
+ [QuotaError, "QUOTA_EXCEEDED"],
122
+ [
123
+ CapabilityError,
124
+ "UNSUPPORTED",
125
+ "CAPABILITY_NOT_ENABLED",
126
+ "CAPABILITY_UNSUPPORTED",
127
+ "UNSUPPORTED_CAPABILITY",
128
+ "FLEET_SHARED_WORKSPACE_UNSUPPORTED",
129
+ "SHARED_WORKSPACE_UNSUPPORTED"
130
+ ],
131
+ [
132
+ GpuProviderNotConfiguredError,
133
+ "CONFIGURATION_ERROR",
134
+ "GPU_PROVIDER_NOT_CONFIGURED",
135
+ "GPU_PROVIDERS_NOT_CONFIGURED"
136
+ ],
137
+ [
138
+ CompliancePlacementError,
139
+ "FORBIDDEN",
140
+ "COMPLIANCE_NOT_ENTITLED",
141
+ "COMPLIANCE_CELL_UNAVAILABLE"
142
+ ],
143
+ [
144
+ PartialFailureError,
145
+ "OPERATION_FAILED",
146
+ "PARTIAL_FAILURE",
147
+ "FLEET_PARTIAL_FAILURE",
148
+ "FLEET_DISPATCH_PARTIAL_FAILURE",
149
+ "FLEET_DEPROVISION_FAILED"
150
+ ],
151
+ [ValidationError, "VALIDATION_ERROR"],
152
+ [
153
+ ProfileFileMountPathError,
154
+ "VALIDATION_ERROR",
155
+ "PROFILE_FILE_MOUNT_OUTSIDE_ROOTS"
156
+ ],
157
+ [StateError, "INVALID_STATE"],
158
+ [
159
+ EdgeNotReadyError,
160
+ "NOT_READY",
161
+ "EDGE_NOT_READY"
162
+ ],
163
+ [
164
+ FileWriteConflictError,
165
+ "CONFLICT",
166
+ "FILE_WRITE_CONFLICT"
167
+ ],
168
+ [
169
+ KeyBudgetExhaustedError,
170
+ "PAYMENT_REQUIRED",
171
+ "KEY_BUDGET_EXHAUSTED"
172
+ ],
173
+ [
174
+ EgressProxyRecoveryError,
175
+ "EGRESS_PROXY_RECOVERY_REQUIRED",
176
+ "EGRESS_PROXY_RECOVERY_REQUIRED"
177
+ ],
178
+ [
179
+ ResumeEnvRequiredError,
180
+ "INVALID_STATE",
181
+ "RESUME_ENV_REQUIRED"
182
+ ],
183
+ [
184
+ BranchFanoutExceedsHostError,
185
+ "QUOTA_EXCEEDED",
186
+ "BRANCH_FANOUT_EXCEEDS_HOST"
187
+ ],
188
+ [TimeoutError, "TIMEOUT"],
189
+ [NetworkError, "NETWORK_ERROR"],
190
+ [StreamInterruptedError, "STREAM_INTERRUPTED"],
191
+ [ServerError, "INTERNAL_ERROR"]
192
+ ];
193
+ const ALIAS_CODE = new Map(ALIASES.map(([alias, code]) => [alias, code]));
194
+ //#endregion
195
+ //#region src/errors.ts
196
+ /**
197
+ * Sandbox SDK Errors
198
+ *
199
+ * The one parse point from an error response to a `SandboxError`.
200
+ */
201
+ /**
202
+ * The one retry rule: retry a failure when the catalog marks its code
203
+ * retryable. A loop adds only its own deliberate exception.
204
+ */
205
+ function retryWhen(error) {
206
+ return error instanceof SandboxError && error.retryable;
207
+ }
208
+ /** A file write or part PUT to resend: retryable, and answered 429 or 5xx, or timed out. */
209
+ function isTransientWrite(error) {
210
+ return retryWhen(error) && (error.status >= 500 || error.status === 429 || error instanceof TimeoutError);
211
+ }
212
+ const ALIAS_BY_WIRE_CODE = new Map(ALIASES.flatMap(([alias, , ...wireCodes]) => wireCodes.map((code) => [code, alias])));
213
+ const ALIAS_BY_STATUS = {
214
+ 400: ValidationError,
215
+ 401: AuthError,
216
+ 404: NotFoundError,
217
+ 408: TimeoutError,
218
+ 409: StateError,
219
+ 429: QuotaError
220
+ };
221
+ /** Detail fields a refusal body may carry at its top level, in `error`, or in `details`. */
222
+ const WIRE_FIELDS = [
223
+ "restartKind",
224
+ "resourceType",
225
+ "resourceId",
226
+ "quotaType",
227
+ "current",
228
+ "limit",
229
+ "capability",
230
+ "providers",
231
+ "fields",
232
+ "path",
233
+ "currentState",
234
+ "requiredState",
235
+ "expectedHash",
236
+ "currentHash",
237
+ "currentMtime",
238
+ "keyId",
239
+ "budgetUsd",
240
+ "spentUsd",
241
+ "reservedUsd",
242
+ "missingEnvKeys",
243
+ "maxChildren",
244
+ "requestedChildren",
245
+ "timeoutMs"
246
+ ];
247
+ function wireFields(...sources) {
248
+ const fields = {};
249
+ for (const source of sources) {
250
+ if (!isFailureDetail(source)) continue;
251
+ for (const key of WIRE_FIELDS) fields[key] ??= source[key];
252
+ }
253
+ if (!HOST_AGENT_RESTART_KINDS.some((kind) => kind === fields.restartKind)) delete fields.restartKind;
254
+ return fields;
255
+ }
256
+ function parseRetryAfterMs(rawValue, data) {
257
+ if (typeof data.retryAfterMs === "number" && Number.isFinite(data.retryAfterMs)) return Math.max(0, data.retryAfterMs);
258
+ return parseSandboxRetryAfterHeader(rawValue);
259
+ }
260
+ /**
261
+ * The server's published wait, in seconds. Only a positive finite number is
262
+ * a wait; anything else is absent. Never derived from `Retry-After` — that
263
+ * header is a pacing hint every refusal carries, while `etaSeconds` is a
264
+ * measurement the cell only publishes when it has one.
265
+ */
266
+ function parseEtaSeconds(data) {
267
+ const raw = data.etaSeconds;
268
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return;
269
+ return raw;
270
+ }
271
+ /**
272
+ * What a capacity refusal publishes: the cell's measured wait, and whether its
273
+ * customer floor refused an internal create (SandboxError.capacityHold).
274
+ */
275
+ function capacityRefusalMetadata(data) {
276
+ return {
277
+ etaSeconds: parseEtaSeconds(data),
278
+ capacityHold: data.code === "CAPACITY_EXHAUSTED" && data.reason === "customer_floor" ? "customer_floor" : void 0
279
+ };
280
+ }
281
+ function inferOrigin(headers, context) {
282
+ const derivedPath = context?.path ?? headers?.get("x-tangle-request-path") ?? void 0;
283
+ if (!headers) return context?.path ? "sandbox-api" : void 0;
284
+ if (headers.has("x-sidecar-version") || headers.has("x-sidecar-image") || headers.has("x-sidecar-image-tag")) return "sidecar";
285
+ if (headers.has("x-orchestrator-version")) return "control-plane";
286
+ if (derivedPath?.startsWith("/v1/")) return "sandbox-api";
287
+ if (derivedPath) {
288
+ if (derivedPath.startsWith("/projects") || derivedPath.startsWith("/sidecars") || derivedPath.startsWith("/instances")) return "control-plane";
289
+ return "runtime";
290
+ }
291
+ return "unknown";
292
+ }
293
+ const ERROR_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;
294
+ function asErrorCode(value) {
295
+ return typeof value === "string" && ERROR_CODE_PATTERN.test(value) ? value : void 0;
296
+ }
297
+ function isFailureDetail(value) {
298
+ return typeof value === "object" && value !== null && !Array.isArray(value);
299
+ }
300
+ function readFailures(data, errorObj) {
301
+ if (Array.isArray(data.failures)) return data.failures.filter(isFailureDetail);
302
+ if (Array.isArray(data.results)) {
303
+ const failures = data.results.filter((result) => typeof result === "object" && result !== null && result.ok === false);
304
+ if (failures.length > 0) return failures.filter(isFailureDetail);
305
+ }
306
+ if (typeof errorObj === "object" && errorObj !== null && Array.isArray(errorObj.failures)) return errorObj.failures.filter(isFailureDetail);
307
+ }
308
+ /**
309
+ * Parse an error response from the API.
310
+ * @param status - HTTP status code
311
+ * @param body - Response body text
312
+ * @param context - Optional request context for better error messages
313
+ */
314
+ function parseErrorResponse(status, body, context, headers) {
315
+ let data;
316
+ try {
317
+ data = JSON.parse(body);
318
+ } catch {
319
+ data = { message: body };
320
+ }
321
+ const nested = data.error?.details;
322
+ if (isFailureDetail(nested)) data = {
323
+ ...nested,
324
+ ...data
325
+ };
326
+ const errorObj = data.error;
327
+ const nestedMessage = typeof errorObj === "object" && errorObj !== null ? errorObj.message : void 0;
328
+ const nestedCode = typeof errorObj === "object" && errorObj !== null ? typeof errorObj.code === "string" ? asErrorCode(errorObj.code) : void 0 : void 0;
329
+ const baseMessage = data.message || nestedMessage || (typeof errorObj === "string" ? errorObj : void 0) || body || "Unknown error";
330
+ const details = typeof data.details === "string" && data.details.trim().length > 0 ? data.details.trim() : void 0;
331
+ const shouldAppendDetails = !!details && details !== baseMessage && (baseMessage === "Unknown error" || /^failed\b/i.test(baseMessage) || /^provision failed\b/i.test(baseMessage) || /^deprovision failed\b/i.test(baseMessage));
332
+ const rawReason = typeof data.reason === "string" ? data.reason : typeof errorObj === "object" && errorObj !== null ? errorObj.reason : void 0;
333
+ const reason = typeof rawReason === "string" && rawReason.trim().length > 0 ? rawReason.trim() : void 0;
334
+ const code = (typeof data.code === "string" ? asErrorCode(data.code) : void 0) ?? nestedCode;
335
+ const rawLog = typeof errorObj === "object" && errorObj !== null ? errorObj.log : void 0;
336
+ const logTail = typeof rawLog === "string" && rawLog.trim().length > 0 ? rawLog.trim() : void 0;
337
+ const prefix = context?.method || context?.path ? `${context.method ?? "REQUEST"} ${context.path ?? ""}: ` : "";
338
+ const composedMessage = shouldAppendDetails ? `${baseMessage}: ${details}` : baseMessage;
339
+ const messageWithReason = `${prefix}${reason && !composedMessage.includes(reason) ? `${composedMessage}: ${reason}` : composedMessage}`;
340
+ const message = logTail && !messageWithReason.includes(logTail) ? `${messageWithReason}\n${logTail}` : messageWithReason;
341
+ const metadata = {
342
+ origin: inferOrigin(headers, context),
343
+ endpoint: context?.path ?? headers?.get("x-tangle-request-path") ?? void 0,
344
+ retryAfterMs: parseRetryAfterMs(headers?.get("retry-after") ?? void 0, data),
345
+ ...capacityRefusalMetadata(data),
346
+ sidecarVersion: headers?.get("x-sidecar-version") ?? void 0,
347
+ containerImage: headers?.get("x-sidecar-image") ?? headers?.get("x-sidecar-image-tag") ?? void 0,
348
+ createFailureDisposition: context?.allPreviousCreateAttemptsRefused === true && (context.method ?? headers?.get("x-tangle-request-method")) === "POST" && (context.path ?? headers?.get("x-tangle-request-path")) === "/v1/sandboxes" && status === 429 && (code === "RATE_LIMIT_EXCEEDED" || code === "QUOTA_EXCEEDED" || code === "PLATFORM_RATE_LIMITED") ? "not-admitted" : void 0
349
+ };
350
+ const source = wireFields(data, errorObj, data.details);
351
+ const Alias = ALIAS_BY_WIRE_CODE.get(code ?? "") ?? (code && catalogCode(code) === "QUOTA_EXCEEDED" ? QuotaError : void 0) ?? ALIAS_BY_STATUS[status] ?? (status >= 500 && status !== 501 ? ServerError : SandboxError);
352
+ return new Alias(message, {
353
+ ...source,
354
+ ...metadata,
355
+ code,
356
+ status,
357
+ failures: readFailures(data, errorObj),
358
+ quotaType: Alias === QuotaError ? asErrorCode(reason) ?? source.quotaType ?? "rate_limit" : void 0,
359
+ currentState: source.currentState ?? (Alias === StateError ? "unknown" : void 0)
360
+ });
361
+ }
362
+ /** Read a failed HTTP response without changing its typed error or retry metadata. */
363
+ async function parseResponseError(response) {
364
+ const body = await response.text();
365
+ return parseErrorResponse(response.status, body, void 0, response.headers);
366
+ }
367
+ /** Read a checked response once; callers interpret its JSON wire value. */
368
+ function readResponseJson(response) {
369
+ if (response.ok) return response.json();
370
+ return parseResponseError(response).then((error) => {
371
+ throw error;
372
+ });
373
+ }
374
+ /**
375
+ * A terminal protocol `error` frame (`code` is its protocol code, e.g.
376
+ * `INIT_FAILED`) or a socket fault (`TRANSPORT`). `beforeOpen` is true when
377
+ * the socket never reached OPEN, so no PTY work started on this dial.
378
+ * @deprecated Removed in 2.0.0; check `code`.
379
+ */
380
+ var TerminalStreamError = class extends SandboxError {};
381
+ //#endregion
382
+ export { ServerError as C, ValidationError as D, TimeoutError as E, SandboxError as S, StreamInterruptedError as T, NotFoundError as _, readResponseJson as a, QuotaError as b, BranchFanoutExceedsHostError as c, EdgeNotReadyError as d, EgressProxyRecoveryError as f, NetworkError as g, KeyBudgetExhaustedError as h, parseResponseError as i, CapabilityError as l, GpuProviderNotConfiguredError as m, isTransientWrite as n, retryWhen as o, FileWriteConflictError as p, parseErrorResponse as r, AuthError as s, TerminalStreamError as t, CompliancePlacementError as u, PartialFailureError as v, StateError as w, ResumeEnvRequiredError as x, ProfileFileMountPathError as y };
@@ -1,5 +1,5 @@
1
1
  import { n as bytesToHex, t as sha256 } from "./sha2-vu4U-x2L.js";
2
- import { D as ValidationError } from "./errors-A-bhwwsE.js";
2
+ import { D as ValidationError } from "./errors-nXGKGVFe.js";
3
3
  //#region src/lib/file-download.ts
4
4
  function downloadBounds(options) {
5
5
  for (const [name, value] of Object.entries({
@@ -1,9 +1,9 @@
1
- import { Ct as InteractionRequest, It as ProxySecretReceipt, L as SandboxError, Lt as InteractionData, St as InteractionAcknowledgement, Tt as AgentProfile, _t as TerminalOutputEvent, at as AgentInteractiveSessionAttach, bt as AgentRunCancellationAcknowledgement, ct as AgentInteractiveSessionControlClaimRequest, dt as AgentInteractiveSessionRef, g as TerminalReadyInfo, ht as AgentInteractiveTerminalSession, i as TerminalStreamHandlers, it as AgentInteractiveSessionStart, kt as AgentProfileFileMount, l as MintScopedTokenOptions, lt as AgentInteractiveSessionPromptAcknowledgement, mt as AgentInteractiveSessionStopCommand, o as TerminalStreamReconnectAuthority, ot as AgentInteractiveSessionControlClaim, pt as AgentInteractiveSessionStopAcknowledgement, q as SandboxCreateReceipt, st as AgentInteractiveSessionControlClaimAcknowledgement, u as ScopedToken, ut as AgentInteractiveSessionPromptCommand, vt as TerminalReplayWindow, wt as InteractionResponseCommand, xt as AgentRunCancellationRequest } from "./terminal-stream-types-DB8V0hiG.js";
2
- import { $a as RawEvidenceBoxDirectoryExport, $r as ForkCounts, An as SandboxShape, Ar as DriverInfo, Bi as CreateSessionOptions, C as WorkspaceOperationLookup, Ci as IntelligenceReportWindow, Cn as TerminalStream, D as ProvisionResult, Di as SandboxEvent, E as ProvisionEvent, Ei as PromptResult, Fi as CommitTaskSessionOptions, Fn as EgressManager, G as GitBranch, Ga as ExecResult, Gi as ListMessagesOptions, Ha as CodeExecutionResult, Hi as DispatchPromptOptions, Ia as WorkspaceImagePublishInput, J as GitStatus, Ja as SandboxEnvRecoveryView, Ji as SendSessionMessageRequest, K as GitCommit, Ka as WriteFileRequest, Ki as PublicProfileConflict, Kt as SandboxFleetTraceBundle, La as WorkspaceImagePublishResult, Li as CompletedTurnResult, Ln as NetworkManager, Lr as GpuLeaseManager, Mi as SandboxTraceOptions, Mn as SandboxResourceUsage, Mr as GpuLease, N as WaitForOptions, Nn as SandboxRuntimeCapabilities, Pi as TurnBackendConfig, Qi as SessionExecutionInfo, Qr as BranchOptions, Ri as ConversationTurnOptions, S as StopOptions, Sn as TeePublicKeyResponse, Ti as PromptOptions, Tn as CreateSandboxOptions, U as PreviewLinkManager, Ua as CodeLanguage, Ui as DispatchedSession, Ur as CodeExecutionOptions, Vi as CreateTaskSessionOptions, Wi as DriveTurnOptions, Xa as RawEvidenceArchiveManifest, Xr as HttpClient, Yi as SentSessionMessage, Zi as SessionEventStreamOptions, _ as SnapshotInfo, _r as SearchMatch, aa as SessionMessage, ai as WaitForRolloutOptions, an as SandboxInfo, bi as IntelligenceReportBudget, bn as TeeAttestationResponse, c as SandboxDeleteOptions, ca as SessionResultOptions, co as InteractionResolutionAcknowledgement, cr as FileWriteResult, d as SandboxOperationKind, ei as ForkIdempotency, eo as RawEvidenceBoxExportOptions, f as SandboxOperationState, fa as TaskSessionInfo, ga as BackendConfig, gn as StartupDiagnostics, gr as WriteManyOptions, hi as DurablePlanDecisionResult, hn as SandboxTerminals, hr as WriteManyFile, ia as SessionListOptions, ii as RolloutStartResult, in as SandboxConnection, k as ResumeOptions, ki as SandboxTraceBundle, kn as SandboxStatus, la as TaskSessionChanges, ln as SandboxRuntimeHealth, m as SnapshotDeleteAcknowledgement, ma as TurnDriveResult, mi as DurablePlanDecisionOptions, mr as WriteFileOptions, na as SessionInfo, ni as Rollout, nn as SSHCommandDescriptor, no as RawEvidenceExportOptions, nr as FileSystem, o as RestoreSnapshotOptions, oa as SessionMessageAdmission, on as SandboxPortBinding, oo as RawEvidenceUnavailable, pi as DurablePlan, q as GitDiff, qa as SandboxEnvRecovery, qi as SendSessionMessageOptions, ra as SessionInterruptOptions, ri as RolloutOptions, rn as SSHCredentials, s as SandboxDeleteAcknowledgement, ta as SessionForkOptions, ti as ForkLookupOptions, to as RawEvidenceDirectoryExport, u as SandboxOperationInfo, ua as TaskSessionCommitResult, un as SandboxTerminalAttachOptions, v as SnapshotOptions, va as BackendManager, vi as EventStreamOptions, vn as TeeAttestationOptions, vr as SearchOptions, wi as PromptInputPart, x as SnapshotResult, xi as IntelligenceReportCompareTo, y as SnapshotProvenance, yi as IntelligenceReport, yr as ExecOptions, z as ProcessManager, zi as ConversationTurnResult } from "./types-Cmv31xBh.js";
3
- import { t as CliAuthReference } from "./cli-auth-bundle-Wg3x2hd2.js";
4
- import { n as SandboxLines } from "./lines-DNXdVbGO.js";
5
- import { _ as InteractiveSessionStatus, f as InteractiveAttachOptions, g as InteractiveRequestOptions, h as InteractiveObserveOptions, m as InteractiveControlClaimOptions, p as InteractiveControlClaimAcknowledgement } from "./browser-interactive-control-controller-qv26Bpfx.js";
6
- import { r as InteractiveAttachRequest } from "./interactive-controller-P0yy6sGl.js";
1
+ import { Ct as InteractionRequest, It as ProxySecretReceipt, L as SandboxError, Lt as InteractionData, St as InteractionAcknowledgement, Tt as AgentProfile, _t as TerminalOutputEvent, at as AgentInteractiveSessionAttach, bt as AgentRunCancellationAcknowledgement, ct as AgentInteractiveSessionControlClaimRequest, dt as AgentInteractiveSessionRef, g as TerminalReadyInfo, ht as AgentInteractiveTerminalSession, i as TerminalStreamHandlers, it as AgentInteractiveSessionStart, kt as AgentProfileFileMount, l as MintScopedTokenOptions, lt as AgentInteractiveSessionPromptAcknowledgement, mt as AgentInteractiveSessionStopCommand, o as TerminalStreamReconnectAuthority, ot as AgentInteractiveSessionControlClaim, pt as AgentInteractiveSessionStopAcknowledgement, q as SandboxCreateReceipt, st as AgentInteractiveSessionControlClaimAcknowledgement, u as ScopedToken, ut as AgentInteractiveSessionPromptCommand, vt as TerminalReplayWindow, wt as InteractionResponseCommand, xt as AgentRunCancellationRequest } from "./terminal-stream-types-eE97lZ-5.js";
2
+ import { $a as RawEvidenceBoxDirectoryExport, $r as ForkCounts, An as SandboxShape, Ar as DriverInfo, Bi as CreateSessionOptions, C as WorkspaceOperationLookup, Ci as IntelligenceReportWindow, Cn as TerminalStream, D as ProvisionResult, Di as SandboxEvent, E as ProvisionEvent, Ei as PromptResult, Fi as CommitTaskSessionOptions, Fn as EgressManager, G as GitBranch, Ga as ExecResult, Gi as ListMessagesOptions, Ha as CodeExecutionResult, Hi as DispatchPromptOptions, Ia as WorkspaceImagePublishInput, J as GitStatus, Ja as SandboxEnvRecoveryView, Ji as SendSessionMessageRequest, K as GitCommit, Ka as WriteFileRequest, Ki as PublicProfileConflict, Kt as SandboxFleetTraceBundle, La as WorkspaceImagePublishResult, Li as CompletedTurnResult, Ln as NetworkManager, Lr as GpuLeaseManager, Mi as SandboxTraceOptions, Mn as SandboxResourceUsage, Mr as GpuLease, N as WaitForOptions, Nn as SandboxRuntimeCapabilities, Pi as TurnBackendConfig, Qi as SessionExecutionInfo, Qr as BranchOptions, Ri as ConversationTurnOptions, S as StopOptions, Sn as TeePublicKeyResponse, Ti as PromptOptions, Tn as CreateSandboxOptions, U as PreviewLinkManager, Ua as CodeLanguage, Ui as DispatchedSession, Ur as CodeExecutionOptions, Vi as CreateTaskSessionOptions, Wi as DriveTurnOptions, Xa as RawEvidenceArchiveManifest, Xr as HttpClient, Yi as SentSessionMessage, Zi as SessionEventStreamOptions, _ as SnapshotInfo, _r as SearchMatch, aa as SessionMessage, ai as WaitForRolloutOptions, an as SandboxInfo, bi as IntelligenceReportBudget, bn as TeeAttestationResponse, c as SandboxDeleteOptions, ca as SessionResultOptions, co as InteractionResolutionAcknowledgement, cr as FileWriteResult, d as SandboxOperationKind, ei as ForkIdempotency, eo as RawEvidenceBoxExportOptions, f as SandboxOperationState, fa as TaskSessionInfo, ga as BackendConfig, gn as StartupDiagnostics, gr as WriteManyOptions, hi as DurablePlanDecisionResult, hn as SandboxTerminals, hr as WriteManyFile, ia as SessionListOptions, ii as RolloutStartResult, in as SandboxConnection, k as ResumeOptions, ki as SandboxTraceBundle, kn as SandboxStatus, la as TaskSessionChanges, ln as SandboxRuntimeHealth, m as SnapshotDeleteAcknowledgement, ma as TurnDriveResult, mi as DurablePlanDecisionOptions, mr as WriteFileOptions, na as SessionInfo, ni as Rollout, nn as SSHCommandDescriptor, no as RawEvidenceExportOptions, nr as FileSystem, o as RestoreSnapshotOptions, oa as SessionMessageAdmission, on as SandboxPortBinding, oo as RawEvidenceUnavailable, pi as DurablePlan, q as GitDiff, qa as SandboxEnvRecovery, qi as SendSessionMessageOptions, ra as SessionInterruptOptions, ri as RolloutOptions, rn as SSHCredentials, s as SandboxDeleteAcknowledgement, ta as SessionForkOptions, ti as ForkLookupOptions, to as RawEvidenceDirectoryExport, u as SandboxOperationInfo, ua as TaskSessionCommitResult, un as SandboxTerminalAttachOptions, v as SnapshotOptions, va as BackendManager, vi as EventStreamOptions, vn as TeeAttestationOptions, vr as SearchOptions, wi as PromptInputPart, x as SnapshotResult, xi as IntelligenceReportCompareTo, y as SnapshotProvenance, yi as IntelligenceReport, yr as ExecOptions, z as ProcessManager, zi as ConversationTurnResult } from "./types-Cs5eJzOK.js";
3
+ import { t as CliAuthReference } from "./cli-auth-bundle-CjSu4D9W.js";
4
+ import { n as SandboxLines } from "./lines-qvpmwN_2.js";
5
+ import { _ as InteractiveSessionStatus, f as InteractiveAttachOptions, g as InteractiveRequestOptions, h as InteractiveObserveOptions, m as InteractiveControlClaimOptions, p as InteractiveControlClaimAcknowledgement } from "./browser-interactive-control-controller-CcUjQEfa.js";
6
+ import { r as InteractiveAttachRequest } from "./interactive-controller-sEU_J6Bc.js";
7
7
  import { z } from "zod";
8
8
  import { OtlpTraceExport } from "@tangle-network/agent-trace-contract/otlp";
9
9
 
@@ -998,6 +998,7 @@ declare abstract class SandboxRuntimeOperations extends SandboxLifecycleCapabili
998
998
  //#region src/generated/sandbox-code-operations.d.ts
999
999
  declare abstract class SandboxCodeOperations extends SandboxRuntimeOperations {
1000
1000
  runCode(language: CodeLanguage, source: string, options?: CodeExecutionOptions): Promise<CodeExecutionResult>;
1001
+ /** Timeout: `options.timeoutMs` (default 30000 ms) plus `SDK_TIMEOUTS.margin`. */
1001
1002
  exec(command: string, options?: ExecOptions): Promise<ExecResult>;
1002
1003
  }
1003
1004
  //#endregion
@@ -2576,7 +2577,9 @@ declare class BlueprintSandboxClient implements HttpClient {
2576
2577
  * - POST /v1/sandboxes/:id/resume → unsupported until blueprint exposes resume
2577
2578
  * - DELETE /v1/sandboxes/:id → on-chain JOB_SANDBOX_DELETE
2578
2579
  */
2579
- fetch(path: string, options?: RequestInit): Promise<Response>;
2580
+ fetch(path: string, options?: RequestInit, fetchOptions?: {
2581
+ timeoutMs?: number;
2582
+ }): Promise<Response>;
2580
2583
  private fetchRuntime;
2581
2584
  /**
2582
2585
  * Get available capacity from the blueprint contract.
@@ -2625,22 +2628,9 @@ declare class BlueprintSandboxClient implements HttpClient {
2625
2628
  //#endregion
2626
2629
  //#region src/tangle/operator-auth.d.ts
2627
2630
  /**
2628
- * Operator API session auth — the client half of the operator's EIP-191
2629
- * challenge-response flow (`sandbox-runtime/src/session_auth`).
2630
- *
2631
- * Flow (matches the operator exactly):
2632
- * 1. `POST /api/auth/challenge` → `{ nonce, message, expires_at }`
2633
- * 2. Sign `message` with the job submitter's key (EIP-191 personal_sign,
2634
- * 65-byte `r ‖ s ‖ v`)
2635
- * 3. `POST /api/auth/session` `{ nonce, signature }` →
2636
- * `{ token, address, expires_at }` (PASETO bearer, 1h)
2637
- * 4. `Authorization: Bearer <token>`
2638
- *
2639
- * The operator recovers the signer address from the signature and binds every
2640
- * sandbox operation to it: `require_sandbox_owner` rejects any session whose
2641
- * address is not the sandbox's on-chain creator. So a session minted from the
2642
- * same key that submitted the create job can read/inject that sandbox's
2643
- * secrets — and nothing else.
2631
+ * EIP-191 operator auth: fetch challenge, sign message, exchange for bearer.
2632
+ * The signer must be the sandbox's on-chain creator; the operator enforces
2633
+ * sandbox ownership. Expiry comes from the challenge/session response.
2644
2634
  */
2645
2635
  /** Challenge payload served by `POST /api/auth/challenge`. */
2646
2636
  interface OperatorChallenge {