@tangle-network/sandbox 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -160,14 +160,22 @@ The decision tree:
160
160
  ### Dispatch + reconnect (the "Worker restart" pattern)
161
161
 
162
162
  ```typescript
163
- import { Sandbox } from "@tangle-network/sandbox";
163
+ import { Sandbox } from "@tangle-network/sandbox/core";
164
164
 
165
165
  const client = new Sandbox({ apiKey: process.env.TANGLE_API_KEY! });
166
166
 
167
- // In your /chat handler:
168
- const sessionId = req.headers.get("x-turn-id") ?? crypto.randomUUID();
167
+ // In your /chat handler, authenticate first. Derive this stable runtime
168
+ // session ID from the authenticated user, conversation, and turn with a
169
+ // server-side HMAC; never accept a caller-selected runtime session ID.
170
+ const turnId = requireStableTurnId(req);
171
+ const sessionId = await deriveOwnedTurnSessionId(
172
+ user.id,
173
+ conversationId,
174
+ turnId,
175
+ );
169
176
  const { sessionId: id, alreadyExisted } = await box.dispatchPrompt(prompt, {
170
- sessionId, // idempotent: a retry with the same id is a lookup, not a re-execute
177
+ sessionId,
178
+ turnId,
171
179
  });
172
180
 
173
181
  // Stream to the browser; if the client comes back later with the same sessionId
@@ -179,32 +187,43 @@ for await (const event of box.session(id).events({
179
187
  }
180
188
  ```
181
189
 
182
- ### Browser-direct streaming (without proxying tokens through your server)
190
+ ### Browser-direct streaming (without proxying the stream through your server)
183
191
 
184
192
  ```typescript
185
193
  import { SessionGatewayClient } from "@tangle-network/sandbox/session-gateway";
186
194
 
187
- const client = new SessionGatewayClient({
195
+ const sessionId =
196
+ localStorage.getItem("sandbox-browser-session") ?? crypto.randomUUID();
197
+ localStorage.setItem("sandbox-browser-session", sessionId);
198
+
199
+ // The browser sends only sessionId. Your authenticated backend looks up the
200
+ // owned runtime session and mints with both sessionId and runtimeSessionId:
201
+ // box.mintScopedToken({ scope: "session", sessionId, runtimeSessionId })
202
+ const scoped = await fetchScopedToken({ sessionId });
203
+ let client: SessionGatewayClient;
204
+ client = new SessionGatewayClient({
188
205
  url: "wss://your-sandbox-api.example.com/session",
189
- token: await fetchScopedToken(), // mint via box.mintScopedToken({ scope: 'session', sessionId })
206
+ token: scoped.token,
190
207
  sessionId,
208
+ onTokenRefresh: () => fetchScopedToken({ sessionId }),
191
209
  autoReconnect: true,
192
- enableReplayPersistence: true, // remembers lastEventId across reloads
193
- replayStorage: { /* localStorage adapter, see session-gateway docs */ },
210
+ enableReplayPersistence: true,
211
+ replayStorage: window.localStorage,
194
212
  handlers: {
195
- onMessage: (event) => render(event),
196
- onReplayStart: ({ since }) => showSpinner(`replaying from ${since}`),
213
+ onAgentEvent: (_channel, event, seq) => render(event, seq),
214
+ onReplayStart: (total) => showSpinner(`replaying ${total} events`),
197
215
  onReplayComplete: () => hideSpinner(),
198
- onBackpressureWarning: ({ droppedCount, suggestReplay }) =>
199
- suggestReplay && client.replay(client.stats.replay.lastEventId),
216
+ onBackpressureWarning: (_droppedCount, since) => void client.replay(since),
200
217
  },
201
218
  });
202
219
  client.connect();
203
220
  ```
204
221
 
205
- `SessionGatewayClient` handles auto-reconnect with exponential backoff, sequence-gap
206
- detection, replay-on-reconnect, and `lastEventId` persistence. None of this requires a
207
- Durable Object.
222
+ `SessionGatewayClient` handles auto-reconnect with exponential backoff, event deduplication, replay-on-reconnect, and `lastEventId` persistence.
223
+ None of this requires a Durable Object.
224
+ The initial scoped token must be fetched before `connect()`; `onTokenRefresh` only handles later rotation.
225
+ Public operations reject if `connection.established` does not arrive within `connectionEstablishmentTimeoutMs` (10 seconds by default).
226
+ Use `handlers.onMessage` to observe every non-duplicate normalized frame after the client processes it; its `id` and canonical `seq` fields cover runtime, project, terminal, and control messages, while `onAgentEvent` is the agent-event convenience callback.
208
227
 
209
228
  Server-originated product events can arrive before the browser connects:
210
229
 
@@ -219,6 +238,10 @@ The public API binds that pending queue to the authenticated product and Sandbox
219
238
  A later connection by the same owner leases and acknowledges the ordered queue; another owner receives none of it.
220
239
  A gateway crash before acknowledgement redelivers the same event IDs, which the default `SessionGatewayClient` deduplicates before invoking handlers.
221
240
 
241
+ The Worker example authenticates before touching the account-key-backed Sandbox client and derives a user-owned runtime session ID from the user, conversation, and turn.
242
+ A retry with the same `x-conversation-id` and `x-turn-id` reuses one execution; a distinct turn gets a distinct execution.
243
+ The detached run survives a Worker or browser response ending; reconnect with the same conversation ID, turn ID, and `Last-Event-ID` to resume.
244
+
222
245
  See `examples/cf-worker-chat.ts`, `examples/browser-streaming-resume.ts`, and
223
246
  `examples/reconnect-from-last-event-id.ts` for end-to-end patterns.
224
247
 
@@ -543,6 +566,39 @@ console.log(result.stdout);
543
566
  console.log(result.stderr);
544
567
  ```
545
568
 
569
+ #### `box.images.publish(input, options?)`
570
+
571
+ Build a Dockerfile from the sandbox workspace and publish the resulting image through the public Sandbox API.
572
+ Registry credentials are sent to the trusted publisher and are not exposed to sandbox processes.
573
+ Use the top-level `ImageBuilder` for an image specification needed before sandbox creation; use `box.images.publish()` for files already built or edited inside a live sandbox.
574
+
575
+ ```typescript
576
+ const published = await box.images.publish(
577
+ {
578
+ contextPath: "apps/web",
579
+ dockerfilePath: "Dockerfile",
580
+ repository: "ghcr.io/acme/web",
581
+ auth: {
582
+ username: process.env.REGISTRY_USERNAME!,
583
+ password: process.env.REGISTRY_PASSWORD!,
584
+ },
585
+ platform: "linux/amd64",
586
+ },
587
+ {
588
+ idempotencyKey: "deploy-request-0184",
589
+ timeoutMs: 15 * 60 * 1000,
590
+ },
591
+ );
592
+
593
+ console.log(published.image); // ghcr.io/acme/web@sha256:...
594
+ console.log(published.taggedImage); // deterministic operation tag
595
+ ```
596
+
597
+ Reuse the same `idempotencyKey` only when retrying the same logical publication.
598
+ The returned `image` is immutable and digest-addressed.
599
+ Operation tags are create-only: replaying identical content succeeds, while attempting to reuse a tag for different content fails.
600
+ The repository must omit the scheme, tag, and digest.
601
+
546
602
  #### `box.prompt(message, options?)`
547
603
 
548
604
  Send a single prompt to the AI agent.
@@ -654,9 +710,26 @@ await box.prompt("Analyze this", {
654
710
  },
655
711
  },
656
712
  });
713
+
714
+ // Attach non-secret product labels to this run's platform-managed trace.
715
+ await box.prompt("Build the project", {
716
+ backend: {
717
+ type: "opencode",
718
+ metadata: {
719
+ traceAttributes: {
720
+ "tangle.product": "blueprint-agent",
721
+ "tangle.partner": "acme",
722
+ "tangle.projectId": "project-42",
723
+ "tangle.domain": "web",
724
+ },
725
+ },
726
+ },
727
+ });
657
728
  ```
658
729
 
659
730
  The SDK serializes `backend.profile` into the required wire format automatically.
731
+ Trace attributes are labels only; supported backend metadata is limited to `containerType` and `traceAttributes`.
732
+ Sandbox configures the trace exporter; do not put collector endpoints, authorization headers, API keys, or user content in `traceAttributes`.
660
733
 
661
734
  Cursor profiles map portable MCP, resources, skills, subagents, hooks, permissions,
662
735
  and Cursor-native `extensions.cursor` fields into the Cursor Agent SDK. Local
@@ -770,6 +843,7 @@ for await (const event of box.events({ signal: controller.signal })) {
770
843
  | `fs.download(remotePath, localPath, options?)` | Node only | — | Writes to a local path with `node:fs` |
771
844
  | `fs.uploadDir` / `fs.downloadDir` | Node only | Local directory path | tar-based directory transfer |
772
845
  | `fs.list` / `fs.stat` / `fs.mkdir` / `fs.delete` / `fs.rename` / `fs.exists` | Node + browser | — | Directory listing and file metadata operations |
846
+ | `fs.tree(path, options?)` / `fs.usage(path, options?)` | Node + browser | — | Filtered file browsing versus complete aggregate storage accounting |
773
847
 
774
848
  ```typescript
775
849
  // Text write/read (UTF-8 by default)
@@ -796,6 +870,10 @@ await box.fs.uploadData("/workspace/models/model.bin", blob, {
796
870
  });
797
871
 
798
872
  await box.fs.download("/workspace/results.zip", "./results.zip");
873
+
874
+ // Complete storage usage, including .git, dependencies, caches, and build output
875
+ const usage = await box.fs.usage("/workspace");
876
+ if (!usage.complete) throw new Error("Workspace usage scan was incomplete");
799
877
  ```
800
878
 
801
879
  `fs.uploadData` is the sanctioned path once a payload clears the single-shot
@@ -1,6 +1,6 @@
1
- import { D as CodeExecutionOptions, O as CodeExecutionResult, j as CodeResultPart, k as CodeLanguage } from "../types-D2C72ySk.js";
2
- import { n as SandboxInstance } from "../sandbox-BRoxCvpS.js";
3
- import { i as SandboxClient } from "../client-DBioX_CL.js";
1
+ import { C as CodeExecutionResult, E as CodeResultPart, S as CodeExecutionOptions, w as CodeLanguage } from "../types-C67osezQ.js";
2
+ import { n as SandboxInstance } from "../sandbox-hbYwu_Ot.js";
3
+ import { i as SandboxClient } from "../client-iZbD-9Ks.js";
4
4
  import * as _$_modelcontextprotocol_sdk_server_index_js0 from "@modelcontextprotocol/sdk/server/index.js";
5
5
 
6
6
  //#region src/agent/tools/_specs.d.ts
@@ -1,6 +1,6 @@
1
- import { c as encodeTextForWire, i as SANDBOX_PROXY_REQUEST_MAX_BYTES, o as combineAbortSignals, s as encodePromptForWire } from "./runtime-api-kukaWPtF.js";
2
- import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, o as PartialFailureError, p as parseErrorResponse, t as AuthError } from "./errors-Cbs78OlF.js";
3
- import { d as exportTraceBundle, l as normalizeConnection, m as parseSSEStream, n as normalizeStartupDiagnostics, t as SandboxInstance } from "./sandbox-DaLPTCRA.js";
1
+ import { c as encodeTextForWire, i as SANDBOX_PROXY_REQUEST_MAX_BYTES, o as combineAbortSignals, s as encodePromptForWire } from "./runtime-api-XhAv6YiH.js";
2
+ import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, o as PartialFailureError, p as parseErrorResponse, t as AuthError } from "./errors-D9fFOWX9.js";
3
+ import { g as exportTraceBundle, m as normalizeConnection, n as createSandboxInstanceFromResponse, r as normalizeStartupDiagnostics, y as parseSSEStream } from "./sandbox-CWeFm9Hj.js";
4
4
  //#region src/resources.ts
5
5
  /**
6
6
  * Compute tiers, ordered smallest → largest. Defined HERE (not imported from
@@ -326,10 +326,18 @@ var SandboxFleet = class {
326
326
  return this.requireSandbox(machineId);
327
327
  }
328
328
  async collectArtifacts(artifacts) {
329
+ const sandboxes = /* @__PURE__ */ new Map();
330
+ const sandboxFor = (machineId) => {
331
+ const existing = sandboxes.get(machineId);
332
+ if (existing) return existing;
333
+ const pending = this.requireSandbox(machineId);
334
+ sandboxes.set(machineId, pending);
335
+ return pending;
336
+ };
329
337
  return mapConcurrent(artifacts, Math.min(MAX_CONCURRENT_ARTIFACT_READS, artifacts.length || 1), async (artifact) => {
330
338
  assertArtifactPath(artifact.path);
331
339
  const machine = this.get(artifact.machineId);
332
- const content = await (await this.requireSandbox(artifact.machineId)).read(artifact.path);
340
+ const content = await (await sandboxFor(artifact.machineId)).read(artifact.path);
333
341
  assertArtifactSize(content, artifact);
334
342
  return {
335
343
  ...artifact,
@@ -999,6 +1007,34 @@ function validateDeferredProfileFileMounts(files) {
999
1007
  validateProfileFilePath(mount.path);
1000
1008
  }
1001
1009
  }
1010
+ /**
1011
+ * Split inline `resources.skills` out of a profile the way
1012
+ * {@link splitInlineProfileFileMounts} splits inline files: the returned
1013
+ * `leanProfile` drops them so the create POST fits its wire cap. Unlike file
1014
+ * mounts, skills are NOT materialized to disk here — they are harness-specific
1015
+ * (each turn's harness needs them in its own dir), so they must ride the
1016
+ * per-turn profile. The full profile is delivered once (create-time priming)
1017
+ * and referenced by hash thereafter.
1018
+ */
1019
+ function splitInlineProfileSkills(profile) {
1020
+ const skills = profile.resources?.skills ?? [];
1021
+ const kept = skills.filter((ref) => ref.kind !== "inline");
1022
+ const deferredSkillCount = skills.length - kept.length;
1023
+ if (deferredSkillCount === 0) return {
1024
+ leanProfile: profile,
1025
+ deferredSkillCount: 0
1026
+ };
1027
+ return {
1028
+ leanProfile: {
1029
+ ...profile,
1030
+ resources: {
1031
+ ...profile.resources ?? {},
1032
+ skills: kept
1033
+ }
1034
+ },
1035
+ deferredSkillCount
1036
+ };
1037
+ }
1002
1038
  function splitInlineProfileFileMounts(profile) {
1003
1039
  const files = profile.resources?.files ?? [];
1004
1040
  const deferredFiles = [];
@@ -1655,19 +1691,38 @@ var SandboxClient = class {
1655
1691
  type: backend.type ?? "opencode"
1656
1692
  } : void 0;
1657
1693
  const autoMaterializeProfileFiles = options?.autoMaterializeProfileFiles ?? true;
1694
+ const autoDeferProfile = options?.autoDeferProfile ?? true;
1658
1695
  let deferredProfileFiles = [];
1659
1696
  let profileFilesFailOnError = true;
1660
1697
  let requestBackend = resolvedBackend;
1661
- if (autoMaterializeProfileFiles && resolvedBackend?.profile && typeof resolvedBackend.profile === "object") {
1662
- const split = splitInlineProfileFileMounts(resolvedBackend.profile);
1663
- deferredProfileFiles = split.deferredFiles;
1664
- if (deferredProfileFiles.length > 0) {
1665
- requestBackend = {
1666
- ...resolvedBackend,
1667
- profile: split.leanProfile
1668
- };
1669
- profileFilesFailOnError = resolvedBackend.profile.resources?.failOnError !== false;
1670
- if (profileFilesFailOnError) validateDeferredProfileFileMounts(deferredProfileFiles);
1698
+ let handleBackend = resolvedBackend;
1699
+ let deferredProfileForPriming;
1700
+ if (resolvedBackend?.profile && typeof resolvedBackend.profile === "object") {
1701
+ const inlineProfile = resolvedBackend.profile;
1702
+ let handleProfile = inlineProfile;
1703
+ if (autoMaterializeProfileFiles) {
1704
+ const split = splitInlineProfileFileMounts(inlineProfile);
1705
+ deferredProfileFiles = split.deferredFiles;
1706
+ handleProfile = split.leanProfile;
1707
+ if (deferredProfileFiles.length > 0) {
1708
+ profileFilesFailOnError = inlineProfile.resources?.failOnError !== false;
1709
+ if (profileFilesFailOnError) validateDeferredProfileFileMounts(deferredProfileFiles);
1710
+ }
1711
+ }
1712
+ handleBackend = {
1713
+ ...resolvedBackend,
1714
+ profile: handleProfile
1715
+ };
1716
+ requestBackend = handleBackend;
1717
+ if (autoDeferProfile) {
1718
+ const skillSplit = splitInlineProfileSkills(handleProfile);
1719
+ if (skillSplit.deferredSkillCount > 0) {
1720
+ requestBackend = {
1721
+ ...resolvedBackend,
1722
+ profile: skillSplit.leanProfile
1723
+ };
1724
+ deferredProfileForPriming = handleProfile;
1725
+ }
1671
1726
  }
1672
1727
  }
1673
1728
  const resources = normalizeSandboxResources(options?.resources, options?.driver);
@@ -1682,6 +1737,7 @@ var SandboxClient = class {
1682
1737
  git,
1683
1738
  tools: options?.tools,
1684
1739
  bare: options?.bare,
1740
+ agent: options?.agent,
1685
1741
  ...options?.publicEdge === false ? { publicEdge: false } : {},
1686
1742
  driver: options?.driver,
1687
1743
  backend: requestBackend,
@@ -1745,7 +1801,7 @@ var SandboxClient = class {
1745
1801
  }
1746
1802
  if (!response) throw createTimeoutError();
1747
1803
  const data = await response.json();
1748
- const instance = new SandboxInstance(this, this.parseInfo(data), requestBackend);
1804
+ const instance = createSandboxInstanceFromResponse(this, this.parseInfo(data), handleBackend);
1749
1805
  if (instance.status === "provisioning" || instance.status === "pending") {
1750
1806
  const remainingMs = Math.max(0, deadline - Date.now());
1751
1807
  await instance.waitFor("running", {
@@ -1775,6 +1831,11 @@ var SandboxClient = class {
1775
1831
  throw new PartialFailureError(message, "PROFILE_FILES_MATERIALIZE_FAILED", 502, void 0, paths.map((path) => ({ path })));
1776
1832
  }
1777
1833
  }
1834
+ if (deferredProfileForPriming !== void 0) try {
1835
+ await instance._primeDeferredProfile(deferredProfileForPriming);
1836
+ } catch (err) {
1837
+ console.warn(`[sandbox.create] Profile priming failed for ${instance.id}; turns will send the full profile inline. Cause: ${err instanceof Error ? err.message : String(err)}`);
1838
+ }
1778
1839
  return instance;
1779
1840
  }
1780
1841
  /**
@@ -1828,7 +1889,7 @@ var SandboxClient = class {
1828
1889
  throw parseErrorResponse(response.status, body, void 0, response.headers);
1829
1890
  }
1830
1891
  const data = await response.json();
1831
- return (Array.isArray(data) ? data : data.sandboxes ?? []).map((item) => new SandboxInstance(this, this.parseInfo(item)));
1892
+ return (Array.isArray(data) ? data : data.sandboxes ?? []).map((item) => createSandboxInstanceFromResponse(this, this.parseInfo(item)));
1832
1893
  }
1833
1894
  /**
1834
1895
  * Get a sandbox by ID.
@@ -1852,7 +1913,7 @@ var SandboxClient = class {
1852
1913
  throw parseErrorResponse(response.status, body, void 0, response.headers);
1853
1914
  }
1854
1915
  const data = await response.json();
1855
- return new SandboxInstance(this, this.parseInfo(data));
1916
+ return createSandboxInstanceFromResponse(this, this.parseInfo(data));
1856
1917
  }
1857
1918
  /**
1858
1919
  * Get usage information for the account.
@@ -2104,6 +2165,9 @@ var SandboxClient = class {
2104
2165
  return {
2105
2166
  id: data.id ?? "",
2106
2167
  name: data.name,
2168
+ filesystemIncarnationId: data.filesystemIncarnationId,
2169
+ filesystemIncarnationProvenance: data.filesystemIncarnationProvenance,
2170
+ filesystemIncarnationReadiness: data.filesystemIncarnationReadiness,
2107
2171
  status: data.status ?? "pending",
2108
2172
  connection: normalizeConnection(data.connection),
2109
2173
  metadata: data.metadata,
@@ -2664,4 +2728,4 @@ var TeamsClient = class {
2664
2728
  }
2665
2729
  };
2666
2730
  //#endregion
2667
- export { validateDeferredProfileFileMounts as a, DEFAULT_SANDBOX_SIZE as c, resolveSandboxResources as d, sandboxResourcesForSize as f, splitInlineProfileFileMounts as i, SANDBOX_SIZE_PRESETS as l, SandboxClient as n, SandboxFleet as o, materializeProfileFileMounts as r, SandboxFleetClient as s, IntelligenceClient as t, SANDBOX_SIZE_PRESET_NAMES as u };
2731
+ export { splitInlineProfileSkills as a, SandboxFleetClient as c, SANDBOX_SIZE_PRESET_NAMES as d, resolveSandboxResources as f, splitInlineProfileFileMounts as i, DEFAULT_SANDBOX_SIZE as l, SandboxClient as n, validateDeferredProfileFileMounts as o, sandboxResourcesForSize as p, materializeProfileFileMounts as r, SandboxFleet as s, IntelligenceClient as t, SANDBOX_SIZE_PRESETS as u };
@@ -1,5 +1,5 @@
1
- import { $t as ListSandboxFleetOptions, An as ReapExpiredSandboxFleetsResult, B as CreateSandboxOptions, Cr as SandboxInfo, Ct as FleetMachineId, Di as TokenRefreshHandler, Dn as PublishPublicTemplateOptions, En as PublicTemplateVersionInfo, F as CreateIntelligenceReportOptions, Gt as IntelligenceReport, I as CreateRequestOptions, Jn as SandboxEnvironment, Kn as SandboxClientConfig, Kt as IntelligenceReportBudget, L as CreateSandboxFleetOptions, Mn as ReconcileSandboxFleetsResult, Ni as UsageInfo, On as PublishPublicTemplateVersionOptions, Or as SandboxProfileSummary, Qn as SandboxFleetCostEstimate, R as CreateSandboxFleetTokenOptions, Sr as SandboxFleetWorkspaceSnapshotResult, St as FleetExecDispatchResult, Tn as PublicTemplateInfo, Tt as FleetPromptDispatchResult, Xn as SandboxFleetArtifact, Yr as SecretsManager, Yt as IntelligenceReportWindow, Zn as SandboxFleetArtifactSpec, _ as BatchResult, _r as SandboxFleetTraceOptions, _t as FleetDispatchCancelResult, a as AttachSandboxFleetMachineOptions, at as ExecResult, bn as PromptResult, br as SandboxFleetWorkspaceReconcileResult, bt as FleetDispatchStreamOptions, dr as SandboxFleetOperationsSummary, en as ListSandboxOptions, er as SandboxFleetDispatchResponse, g as BatchOptions, it as ExecOptions, jn as ReconcileSandboxFleetsOptions, kn as ReapExpiredSandboxFleetsOptions, lr as SandboxFleetManifest, m as BatchEvent, mi as SubscriptionInfo, mr as SandboxFleetTraceBundle, pr as SandboxFleetToken, qt as IntelligenceReportCompareTo, rr as SandboxFleetInfo, sr as SandboxFleetMachineRecord, tr as SandboxFleetDriverCapability, ui as SshKeysManager, v as BatchRunOptions, vn as PromptInputPart, vr as SandboxFleetUsage, vt as FleetDispatchResultBuffer, wt as FleetPromptDispatchOptions, x as BatchTask, xr as SandboxFleetWorkspaceRestoreResult, xt as FleetExecDispatchOptions, y as BatchRunRequest, yn as PromptOptions, yt as FleetDispatchResultBufferOptions, z as CreateSandboxFleetWithCoordinatorOptions } from "./types-D2C72ySk.js";
2
- import { a as TraceExportSink, i as TraceExportResult, n as SandboxInstance, t as HttpClient } from "./sandbox-BRoxCvpS.js";
1
+ import { $t as ListSandboxOptions, A as CreateIntelligenceReportOptions, An as ReapExpiredSandboxFleetsResult, Cr as SandboxInfo, Ct as FleetPromptDispatchOptions, Dn as PublishPublicTemplateOptions, En as PublicTemplateVersionInfo, F as CreateSandboxOptions, Fi as UsageInfo, Gt as IntelligenceReportBudget, Hi as BatchEvent, Jn as SandboxEnvironment, Jt as IntelligenceReportWindow, Kn as SandboxClientConfig, Kt as IntelligenceReportCompareTo, M as CreateSandboxFleetOptions, Mn as ReconcileSandboxFleetsResult, N as CreateSandboxFleetTokenOptions, On as PublishPublicTemplateVersionOptions, Or as SandboxProfileSummary, P as CreateSandboxFleetWithCoordinatorOptions, Qn as SandboxFleetCostEstimate, Qt as ListSandboxFleetOptions, Sr as SandboxFleetWorkspaceSnapshotResult, St as FleetMachineId, Tn as PublicTemplateInfo, Wt as IntelligenceReport, Xn as SandboxFleetArtifact, Zn as SandboxFleetArtifactSpec, Zr as SecretsManager, _ as BatchTask, _r as SandboxFleetTraceOptions, _t as FleetDispatchResultBuffer, a as AttachSandboxFleetMachineOptions, bn as PromptResult, br as SandboxFleetWorkspaceReconcileResult, bt as FleetExecDispatchOptions, dr as SandboxFleetOperationsSummary, er as SandboxFleetDispatchResponse, fi as SshKeysManager, g as BatchRunRequest, gi as SubscriptionInfo, gt as FleetDispatchCancelResult, h as BatchRunOptions, j as CreateRequestOptions, jn as ReconcileSandboxFleetsOptions, ki as TokenRefreshHandler, kn as ReapExpiredSandboxFleetsOptions, lr as SandboxFleetManifest, m as BatchResult, mr as SandboxFleetTraceBundle, nt as ExecResult, p as BatchOptions, pr as SandboxFleetToken, rr as SandboxFleetInfo, sr as SandboxFleetMachineRecord, tr as SandboxFleetDriverCapability, tt as ExecOptions, vn as PromptInputPart, vr as SandboxFleetUsage, vt as FleetDispatchResultBufferOptions, wt as FleetPromptDispatchResult, xr as SandboxFleetWorkspaceRestoreResult, xt as FleetExecDispatchResult, yn as PromptOptions, yt as FleetDispatchStreamOptions } from "./types-C67osezQ.js";
2
+ import { c as TraceExportResult, l as TraceExportSink, n as SandboxInstance, t as HttpClient } from "./sandbox-hbYwu_Ot.js";
3
3
 
4
4
  //#region src/lib/sse-parser.d.ts
5
5
  /**
@@ -1,2 +1,2 @@
1
- import { a as CollaborationClient, i as parseCollaborationDocumentId, n as buildCollaborationDocumentId, r as normalizeCollaborationPath, t as CollaborationFileBridge } from "../collaboration-DDnuTcZd.js";
1
+ import { a as CollaborationClient, i as parseCollaborationDocumentId, n as buildCollaborationDocumentId, r as normalizeCollaborationPath, t as CollaborationFileBridge } from "../collaboration-DdD_rFZQ.js";
2
2
  export { CollaborationClient, CollaborationFileBridge, buildCollaborationDocumentId, normalizeCollaborationPath, parseCollaborationDocumentId };
@@ -1,4 +1,4 @@
1
- import { d as TimeoutError, i as NetworkError, p as parseErrorResponse } from "./errors-Cbs78OlF.js";
1
+ import { d as TimeoutError, i as NetworkError, p as parseErrorResponse } from "./errors-D9fFOWX9.js";
2
2
  //#region src/collaboration/client.ts
3
3
  const DEFAULT_TIMEOUT_MS = 3e4;
4
4
  function normalizeBaseUrl(url) {
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as CreateSandboxOptions, Cr as SandboxInfo, Kn as SandboxClientConfig, Pr as SandboxStatus, at as ExecResult, in as NetworkConfig, it as ExecOptions, ln as PreviewLinkInfo, un as PreviewLinkManager } from "./types-D2C72ySk.js";
2
- import { n as SandboxInstance } from "./sandbox-BRoxCvpS.js";
3
- import { i as SandboxClient } from "./client-DBioX_CL.js";
4
- import { a as NotFoundError, c as SandboxError, d as ServerError, f as StateError, i as NetworkError, l as SandboxErrorJson, m as ValidationError, n as CapabilityError, o as PartialFailureError, p as TimeoutError, s as QuotaError, t as AuthError, u as SandboxFailureDetail } from "./errors-ntvaf0_F.js";
5
- export { AuthError, CapabilityError, type CreateSandboxOptions, type ExecOptions, type ExecResult, type NetworkConfig, NetworkError, NotFoundError, PartialFailureError, type PreviewLinkInfo, type PreviewLinkManager, QuotaError, SandboxClient as Sandbox, SandboxClient, type SandboxClientConfig, SandboxError, type SandboxErrorJson, type SandboxFailureDetail, type SandboxInfo, SandboxInstance, type SandboxStatus, ServerError, StateError, TimeoutError, ValidationError };
1
+ import { Cr as SandboxInfo, F as CreateSandboxOptions, Kn as SandboxClientConfig, Pr as SandboxStatus, cn as PreviewLinkInfo, ln as PreviewLinkManager, nt as ExecResult, rn as NetworkConfig, tt as ExecOptions } from "./types-C67osezQ.js";
2
+ import { a as WorkspaceImagePublishResult, i as WorkspaceImagePublishRequestOptions, n as SandboxInstance, o as WorkspaceImages, r as WorkspaceImagePublishInput } from "./sandbox-hbYwu_Ot.js";
3
+ import { i as SandboxClient } from "./client-iZbD-9Ks.js";
4
+ import { a as NotFoundError, c as SandboxError, d as ServerError, f as StateError, i as NetworkError, l as SandboxErrorJson, m as ValidationError, n as CapabilityError, o as PartialFailureError, p as TimeoutError, s as QuotaError, t as AuthError, u as SandboxFailureDetail } from "./errors-C8HMx78o.js";
5
+ export { AuthError, CapabilityError, type CreateSandboxOptions, type ExecOptions, type ExecResult, type NetworkConfig, NetworkError, NotFoundError, PartialFailureError, type PreviewLinkInfo, type PreviewLinkManager, QuotaError, SandboxClient as Sandbox, SandboxClient, type SandboxClientConfig, SandboxError, type SandboxErrorJson, type SandboxFailureDetail, type SandboxInfo, SandboxInstance, type SandboxStatus, ServerError, StateError, TimeoutError, ValidationError, type WorkspaceImagePublishInput, type WorkspaceImagePublishRequestOptions, type WorkspaceImagePublishResult, WorkspaceImages };
package/dist/core.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, l as ServerError, n as CapabilityError, o as PartialFailureError, s as QuotaError, t as AuthError, u as StateError } from "./errors-Cbs78OlF.js";
2
- import { t as SandboxInstance } from "./sandbox-DaLPTCRA.js";
3
- import { n as SandboxClient } from "./client-D_67csnK.js";
4
- export { AuthError, CapabilityError, NetworkError, NotFoundError, PartialFailureError, QuotaError, SandboxClient as Sandbox, SandboxClient, SandboxError, SandboxInstance, ServerError, StateError, TimeoutError, ValidationError };
1
+ import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, l as ServerError, n as CapabilityError, o as PartialFailureError, s as QuotaError, t as AuthError, u as StateError } from "./errors-D9fFOWX9.js";
2
+ import { i as WorkspaceImages, t as SandboxInstance } from "./sandbox-CWeFm9Hj.js";
3
+ import { n as SandboxClient } from "./client-BCNrDjvA.js";
4
+ export { AuthError, CapabilityError, NetworkError, NotFoundError, PartialFailureError, QuotaError, SandboxClient as Sandbox, SandboxClient, SandboxError, SandboxInstance, ServerError, StateError, TimeoutError, ValidationError, WorkspaceImages };
@@ -52,7 +52,7 @@ declare class NotFoundError extends SandboxError {
52
52
  readonly resourceType: string;
53
53
  /** The resource ID that was not found */
54
54
  readonly resourceId: string;
55
- constructor(resourceType: string, resourceId: string, metadata?: SandboxErrorMetadata);
55
+ constructor(resourceType: string, resourceId: string, metadata?: SandboxErrorMetadata, message?: string, code?: string);
56
56
  }
57
57
  /**
58
58
  * Account quota or rate limit exceeded.
@@ -126,7 +126,7 @@ declare class NetworkError extends SandboxError {
126
126
  * The server returned an unexpected error.
127
127
  */
128
128
  declare class ServerError extends SandboxError {
129
- constructor(message: string, status?: number, metadata?: SandboxErrorMetadata);
129
+ constructor(message: string, status?: number, metadata?: SandboxErrorMetadata, code?: string);
130
130
  }
131
131
  //#endregion
132
132
  export { NotFoundError as a, SandboxError as c, ServerError as d, StateError as f, NetworkError as i, SandboxErrorJson as l, ValidationError as m, CapabilityError as n, PartialFailureError as o, TimeoutError as p, EgressProxyRecoveryError as r, QuotaError as s, AuthError as t, SandboxFailureDetail as u };
@@ -51,8 +51,8 @@ var NotFoundError = class extends SandboxError {
51
51
  resourceType;
52
52
  /** The resource ID that was not found */
53
53
  resourceId;
54
- constructor(resourceType, resourceId, metadata) {
55
- super(`${resourceType} not found: ${resourceId}`, "NOT_FOUND", 404, metadata);
54
+ constructor(resourceType, resourceId, metadata, message = `${resourceType} not found: ${resourceId}`, code = "NOT_FOUND") {
55
+ super(message, code, 404, metadata);
56
56
  this.name = "NotFoundError";
57
57
  this.resourceType = resourceType;
58
58
  this.resourceId = resourceId;
@@ -168,8 +168,8 @@ var NetworkError = class extends SandboxError {
168
168
  * The server returned an unexpected error.
169
169
  */
170
170
  var ServerError = class extends SandboxError {
171
- constructor(message, status = 500, metadata) {
172
- super(message, "SERVER_ERROR", status, metadata);
171
+ constructor(message, status = 500, metadata, code = "SERVER_ERROR") {
172
+ super(message, code, status, metadata);
173
173
  this.name = "ServerError";
174
174
  }
175
175
  };
@@ -207,6 +207,10 @@ function isPartialFailureCode(code) {
207
207
  function asString(value) {
208
208
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
209
209
  }
210
+ const ERROR_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;
211
+ function asErrorCode(value) {
212
+ return typeof value === "string" && ERROR_CODE_PATTERN.test(value) ? value : void 0;
213
+ }
210
214
  function isFailureDetail(value) {
211
215
  return typeof value === "object" && value !== null && !Array.isArray(value);
212
216
  }
@@ -237,11 +241,11 @@ function parseErrorResponse(status, body, context, headers) {
237
241
  }
238
242
  const errorObj = data.error;
239
243
  const nestedMessage = typeof errorObj === "object" && errorObj !== null ? errorObj.message : void 0;
240
- const nestedCode = typeof errorObj === "object" && errorObj !== null ? errorObj.code : void 0;
244
+ const nestedCode = typeof errorObj === "object" && errorObj !== null ? asErrorCode(errorObj.code) : void 0;
241
245
  const baseMessage = data.message || nestedMessage || (typeof errorObj === "string" ? errorObj : void 0) || body || "Unknown error";
242
246
  const details = typeof data.details === "string" && data.details.trim().length > 0 ? data.details.trim() : void 0;
243
247
  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));
244
- const code = data.code || nestedCode;
248
+ const code = asErrorCode(data.code) ?? nestedCode;
245
249
  const message = `${context ? `${context.method ?? "REQUEST"} ${context.path ?? ""}: ` : ""}${shouldAppendDetails ? `${baseMessage}: ${details}` : baseMessage}`;
246
250
  const metadata = {
247
251
  origin: inferOrigin(headers, context),
@@ -257,13 +261,13 @@ function parseErrorResponse(status, body, context, headers) {
257
261
  switch (status) {
258
262
  case 400: return new ValidationError(message, data.fields, metadata, code);
259
263
  case 401: return new AuthError(message, metadata);
260
- case 404: return new NotFoundError(data.resourceType || "Resource", data.resourceId || "unknown", metadata);
264
+ case 404: return new NotFoundError(data.resourceType || "Resource", data.resourceId || "unknown", metadata, message, code);
261
265
  case 408: return new TimeoutError(data.timeoutMs || 3e4, message, metadata);
262
266
  case 409: return new StateError(message, data.currentState || "unknown", data.requiredState, metadata, code);
263
267
  case 429: return new QuotaError(data.quotaType || "rate_limit", message, data.current, data.limit, metadata);
264
268
  case 501: return new SandboxError(message, code || "NOT_IMPLEMENTED", status, metadata);
265
269
  default:
266
- if (status >= 500) return new ServerError(message, status, metadata);
270
+ if (status >= 500) return new ServerError(message, status, metadata, code);
267
271
  return new SandboxError(message, code || "UNKNOWN_ERROR", status, metadata);
268
272
  }
269
273
  }
@@ -1,5 +1,5 @@
1
- import { B as CreateSandboxOptions } from "./types-D2C72ySk.js";
2
- import { n as SandboxInstance, t as HttpClient } from "./sandbox-BRoxCvpS.js";
1
+ import { F as CreateSandboxOptions } from "./types-C67osezQ.js";
2
+ import { n as SandboxInstance, t as HttpClient } from "./sandbox-hbYwu_Ot.js";
3
3
 
4
4
  //#region src/tangle/abi.d.ts
5
5
  /**