@opencoredev/sandbox-sdk 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +74 -11
  2. package/README.md +357 -25
  3. package/dist/ai.d.ts +5 -0
  4. package/dist/ai.js +1 -0
  5. package/dist/chunk-23tjmd39.js +8 -0
  6. package/dist/chunk-2ts3evzh.js +2 -0
  7. package/dist/chunk-83avbjns.js +2 -0
  8. package/dist/chunk-8786zrns.js +2 -0
  9. package/dist/chunk-8wq767xb.js +17 -0
  10. package/dist/chunk-9w9rddra.js +2 -0
  11. package/dist/chunk-bd481sb7.js +2 -0
  12. package/dist/chunk-ckym4cht.js +23 -0
  13. package/dist/chunk-gw3n7sx7.js +5 -0
  14. package/dist/chunk-hgrwyjrb.js +2 -0
  15. package/dist/chunk-hzbssbep.js +31 -0
  16. package/dist/chunk-k60b4r27.js +2 -0
  17. package/dist/chunk-kk1hw8wa.js +1 -0
  18. package/dist/chunk-nw845a93.js +27 -0
  19. package/dist/chunk-q5vqajhg.js +2 -0
  20. package/dist/chunk-vy1j4r8f.js +2 -0
  21. package/dist/chunk-x681p5d2.js +68 -0
  22. package/dist/chunk-xgxfy2n8.js +4 -0
  23. package/dist/core/process-records.d.ts +25 -0
  24. package/dist/errors.d.ts +126 -0
  25. package/dist/files.d.ts +64 -0
  26. package/dist/git.d.ts +28 -0
  27. package/dist/handle.d.ts +4 -0
  28. package/dist/http.d.ts +225 -0
  29. package/dist/index.d.ts +19 -0
  30. package/dist/index.js +1 -0
  31. package/dist/keys.d.ts +10 -0
  32. package/dist/logs.d.ts +8 -0
  33. package/dist/mastra.d.ts +43 -0
  34. package/dist/mastra.js +1 -0
  35. package/dist/memory.d.ts +37 -0
  36. package/dist/memory.js +13 -0
  37. package/dist/native.d.ts +127 -0
  38. package/dist/openai.d.ts +39 -0
  39. package/dist/openai.js +1 -0
  40. package/dist/peer.d.ts +14 -0
  41. package/dist/processes.d.ts +71 -0
  42. package/dist/provider.d.ts +171 -0
  43. package/dist/provider.js +1 -0
  44. package/dist/providers/agentos/errors.d.ts +5 -0
  45. package/dist/providers/agentos/index.d.ts +4 -0
  46. package/dist/providers/agentos/index.js +2 -0
  47. package/dist/providers/agentos/provider.d.ts +50 -0
  48. package/dist/providers/boat/index.d.ts +66 -0
  49. package/dist/providers/boat/index.js +1 -0
  50. package/dist/providers/boat-api/errors.d.ts +6 -0
  51. package/dist/providers/boat-api/exec.d.ts +24 -0
  52. package/dist/providers/boat-api/follow.d.ts +24 -0
  53. package/dist/providers/boat-api/index.d.ts +60 -0
  54. package/dist/providers/boat-api/transport.d.ts +77 -0
  55. package/dist/providers/boxd/errors.d.ts +3 -0
  56. package/dist/providers/boxd/execute.d.ts +3 -0
  57. package/dist/providers/boxd/index.d.ts +3 -0
  58. package/dist/providers/boxd/index.js +105 -0
  59. package/dist/providers/boxd/provider.d.ts +74 -0
  60. package/dist/providers/boxd/transfers.d.ts +28 -0
  61. package/dist/providers/daytona/api.d.ts +124 -0
  62. package/dist/providers/daytona/buffered.d.ts +3 -0
  63. package/dist/providers/daytona/errors.d.ts +19 -0
  64. package/dist/providers/daytona/exec.d.ts +14 -0
  65. package/dist/providers/daytona/index.d.ts +73 -0
  66. package/dist/providers/daytona/index.js +96 -0
  67. package/dist/providers/daytona/multipart.d.ts +25 -0
  68. package/dist/providers/e2b/envd.d.ts +113 -0
  69. package/dist/providers/e2b/errors.d.ts +20 -0
  70. package/dist/providers/e2b/index.d.ts +53 -0
  71. package/dist/providers/e2b/index.js +1 -0
  72. package/dist/providers/freestyle/client.d.ts +87 -0
  73. package/dist/providers/freestyle/deadline.d.ts +5 -0
  74. package/dist/providers/freestyle/errors.d.ts +29 -0
  75. package/dist/providers/freestyle/execute.d.ts +8 -0
  76. package/dist/providers/freestyle/index.d.ts +40 -0
  77. package/dist/providers/freestyle/index.js +105 -0
  78. package/dist/providers/local/docker.d.ts +36 -0
  79. package/dist/providers/local/index.d.ts +46 -0
  80. package/dist/providers/local/index.js +2 -0
  81. package/dist/providers/railway/errors.d.ts +10 -0
  82. package/dist/providers/railway/index.d.ts +3 -0
  83. package/dist/providers/railway/index.js +1 -0
  84. package/dist/providers/railway/provider.d.ts +53 -0
  85. package/dist/providers/sandboxer/index.d.ts +40 -0
  86. package/dist/providers/sandboxer/index.js +1 -0
  87. package/dist/providers/superserve/bootstrap.d.ts +11 -0
  88. package/dist/providers/superserve/errors.d.ts +3 -0
  89. package/dist/providers/superserve/execute.d.ts +8 -0
  90. package/dist/providers/superserve/index.d.ts +52 -0
  91. package/dist/providers/superserve/index.js +94 -0
  92. package/dist/providers/superserve/routes.d.ts +80 -0
  93. package/dist/providers/superserve/session.d.ts +33 -0
  94. package/dist/providers/tenki/deadline.d.ts +2 -0
  95. package/dist/providers/tenki/errors.d.ts +10 -0
  96. package/dist/providers/tenki/exec.d.ts +4 -0
  97. package/dist/providers/tenki/files.d.ts +3 -0
  98. package/dist/providers/tenki/index.d.ts +3 -0
  99. package/dist/providers/tenki/index.js +175 -0
  100. package/dist/providers/tenki/provider.d.ts +95 -0
  101. package/dist/providers/tenki/ready.d.ts +7 -0
  102. package/dist/providers/tenki/records.d.ts +16 -0
  103. package/dist/providers/tenki/stream.d.ts +3 -0
  104. package/dist/providers/upstash/buffered.d.ts +3 -0
  105. package/dist/providers/upstash/errors.d.ts +3 -0
  106. package/dist/providers/upstash/exec.d.ts +18 -0
  107. package/dist/providers/upstash/files.d.ts +15 -0
  108. package/dist/providers/upstash/index.d.ts +6 -0
  109. package/dist/providers/upstash/index.js +105 -0
  110. package/dist/providers/upstash/provider.d.ts +81 -0
  111. package/dist/providers/vercel/errors.d.ts +5 -0
  112. package/dist/providers/vercel/index.d.ts +22 -0
  113. package/dist/providers/vercel/index.js +1 -0
  114. package/dist/providers/vercel/provider.d.ts +58 -0
  115. package/dist/providers/vercel/transport.d.ts +43 -0
  116. package/dist/run.d.ts +43 -0
  117. package/dist/shared/deadline.d.ts +12 -0
  118. package/dist/shared/guest.d.ts +18 -0
  119. package/dist/shared/json.d.ts +11 -0
  120. package/dist/shared/metadata.d.ts +19 -0
  121. package/dist/shared/narrow.d.ts +8 -0
  122. package/dist/shared/native-error.d.ts +42 -0
  123. package/dist/shared/paged-exec.d.ts +22 -0
  124. package/dist/shared/shell.d.ts +2 -0
  125. package/dist/shared/wire.d.ts +10 -0
  126. package/dist/shell/process-records.d.ts +44 -0
  127. package/dist/streams.d.ts +72 -0
  128. package/dist/testing.d.ts +27 -0
  129. package/dist/testing.js +9 -0
  130. package/dist/tool-security.d.ts +9 -0
  131. package/dist/tools.d.ts +118 -0
  132. package/dist/tools.js +1 -0
  133. package/dist/types.d.ts +197 -0
  134. package/package.json +143 -102
  135. package/dist/agentos-CbrZW7R0.mjs +0 -390
  136. package/dist/agentos-CbrZW7R0.mjs.map +0 -1
  137. package/dist/ai/harness.d.mts +0 -16
  138. package/dist/ai/harness.mjs +0 -69
  139. package/dist/ai/harness.mjs.map +0 -1
  140. package/dist/ai/index.d.mts +0 -54
  141. package/dist/ai/index.mjs +0 -4
  142. package/dist/ai-DeFa8yPk.mjs +0 -243
  143. package/dist/ai-DeFa8yPk.mjs.map +0 -1
  144. package/dist/capabilities-BWvOVFbH.d.mts +0 -15
  145. package/dist/capabilities-CaSNd6J1.mjs +0 -125
  146. package/dist/capabilities-CaSNd6J1.mjs.map +0 -1
  147. package/dist/capabilities-xs9kaHrK.mjs +0 -28
  148. package/dist/capabilities-xs9kaHrK.mjs.map +0 -1
  149. package/dist/errors-BuF9bYOQ.mjs +0 -68
  150. package/dist/errors-BuF9bYOQ.mjs.map +0 -1
  151. package/dist/eve/index.d.mts +0 -19
  152. package/dist/eve/index.mjs +0 -155
  153. package/dist/eve/index.mjs.map +0 -1
  154. package/dist/index-CkTwqD0X.d.mts +0 -25
  155. package/dist/index-Dh9xob2s.d.mts +0 -31
  156. package/dist/index.d.mts +0 -5
  157. package/dist/index.mjs +0 -40
  158. package/dist/index.mjs.map +0 -1
  159. package/dist/managed-provider-BsZGVQ4I.mjs +0 -148
  160. package/dist/managed-provider-BsZGVQ4I.mjs.map +0 -1
  161. package/dist/mastra/index.d.mts +0 -118
  162. package/dist/mastra/index.mjs +0 -662
  163. package/dist/mastra/index.mjs.map +0 -1
  164. package/dist/metadata.d.mts +0 -34
  165. package/dist/metadata.mjs +0 -135
  166. package/dist/metadata.mjs.map +0 -1
  167. package/dist/provider-DOBErkBO.d.mts +0 -91
  168. package/dist/provider-utils-CfB9nvJx.mjs +0 -57
  169. package/dist/provider-utils-CfB9nvJx.mjs.map +0 -1
  170. package/dist/providers/agentos/index.d.mts +0 -7
  171. package/dist/providers/agentos/index.mjs +0 -9
  172. package/dist/providers/box/index.d.mts +0 -34
  173. package/dist/providers/box/index.mjs +0 -348
  174. package/dist/providers/box/index.mjs.map +0 -1
  175. package/dist/providers/daytona/index.d.mts +0 -21
  176. package/dist/providers/daytona/index.mjs +0 -206
  177. package/dist/providers/daytona/index.mjs.map +0 -1
  178. package/dist/providers/e2b/index.d.mts +0 -17
  179. package/dist/providers/e2b/index.mjs +0 -169
  180. package/dist/providers/e2b/index.mjs.map +0 -1
  181. package/dist/providers/local/index.d.mts +0 -22
  182. package/dist/providers/local/index.mjs +0 -22
  183. package/dist/providers/local/index.mjs.map +0 -1
  184. package/dist/providers/railway/index.d.mts +0 -29
  185. package/dist/providers/railway/index.mjs +0 -211
  186. package/dist/providers/railway/index.mjs.map +0 -1
  187. package/dist/providers/upstash/index.d.mts +0 -17
  188. package/dist/providers/upstash/index.mjs +0 -211
  189. package/dist/providers/upstash/index.mjs.map +0 -1
  190. package/dist/providers/vercel/index.d.mts +0 -28
  191. package/dist/providers/vercel/index.mjs +0 -186
  192. package/dist/providers/vercel/index.mjs.map +0 -1
  193. package/dist/sandbox-DdEqoXJF.d.mts +0 -26
  194. package/dist/sandbox-DgtY5hvt.mjs +0 -112
  195. package/dist/sandbox-DgtY5hvt.mjs.map +0 -1
  196. package/dist/testing/index.d.mts +0 -27
  197. package/dist/testing/index.mjs +0 -173
  198. package/dist/testing/index.mjs.map +0 -1
  199. package/dist/types-Bv6I2U1c.d.mts +0 -103
package/CHANGELOG.md CHANGED
@@ -1,17 +1,80 @@
1
- ## @opencoredev/sandbox-sdk@0.2.0
1
+ # Changelog
2
2
 
3
- - Add Ascii Box and Railway Sandbox provider adapters, package exports, capabilities, examples,
4
- live-test entry points, and provider documentation.
5
- - Normalize HTTP response status codes from provider SDK errors.
3
+ ## 1.0.0
6
4
 
7
- ## @opencoredev/sandbox-sdk@0.1.1
5
+ ### Major Changes
8
6
 
9
- - Add `Symbol.asyncDispose` to `Sandbox` so `await using` provides automatic cleanup.
7
+ - 8b7214a: Sandbox SDK 1.0: one TypeScript API for 14 sandbox providers (E2B, Daytona, Vercel Sandbox, Upstash Box, Railway, Boat, Sandboxer, Tenki, boxd, Freestyle, Superserve, local Docker, agentOS, and an in-memory fake), with typed capabilities, background processes, previews, files, git, and agent tools for the AI SDK, Mastra, and OpenAI Agents. 1.0 is a rewrite; see the upgrade guide at https://sandbox-sdk.app/docs/upgrade-from-0-2 when coming from 0.2.
10
8
 
11
- ## @opencoredev/sandbox-sdk@0.1.0
9
+ Since 1.0.0-beta.1:
12
10
 
13
- ### Initial release
11
+ E2B, Daytona, Freestyle, Superserve, Boat, and Sandboxer now call their provider's HTTP API directly, so `npm i @opencoredev/sandbox-sdk` is the whole install for them. `e2b`, `@daytonaio/sdk`, `freestyle`, `@superserve/sdk`, and `@boatdev/sdk` are no longer peer dependencies. On these providers `box.native` is a `NativeApi` (`request`, `fetch`, `sdk`), and `box.native.sdk(() => import("<package>"))` still gives you the official SDK's object if you install it yourself. Vercel, Upstash Box, Railway, Tenki, boxd, and agentOS still need their SDK. The bullets below cover each provider's migration.
14
12
 
15
- - Run one TypeScript sandbox API across Local, E2B, Daytona, Vercel Sandbox, and Upstash Box.
16
- - Use normalized files, commands, processes, ports, snapshots, and provider capabilities.
17
- - Integrate sandbox sessions with AI SDK, Harness, Eve, and Mastra.
13
+ - **Breaking for Daytona:** `daytona()` calls Daytona's HTTP API directly, and `@daytonaio/sdk` is no longer a peer dependency, so `npm i @opencoredev/sandbox-sdk` is the whole install. File transfers use Web `FormData` and a built-in multipart reader, so bundled apps no longer need `form-data` or `busboy`, and the `codeRun` transfer fallback is gone. `box.native` is now a `NativeApi` with `"api"` and `"toolbox"` planes instead of the SDK's `Sandbox`: call `box.native.request(...)`, or `await box.native.sdk(() => import("@daytonaio/sdk"))` to keep using the SDK. `daytona().api` makes account-level calls. A create that fails after Daytona made the sandbox now always deletes it, including one whose create request got no answer.
14
+ - `superserve()` calls Superserve's HTTP API directly, so `@superserve/sdk` is no longer a peer: `npm i @opencoredev/sandbox-sdk` is the whole install. Breaking for beta users: `box.native` is now a `NativeApi` (`request`, `fetch`, `sdk`) instead of the SDK's `Sandbox`. Get the old object with `await box.native.sdk(() => import("@superserve/sdk"))`. A stdin-free run whose connection drops after the command started now rejects with `outcome_unknown` instead of `provider`.
15
+
16
+ - `e2b()` calls E2B's API and each sandbox's envd daemon over HTTP, so `e2b` is no longer a peer dependency: `npm i @opencoredev/sandbox-sdk` is the whole install. Options, defaults and behaviour are unchanged. Control-plane reads and the idempotent `connect`, `timeout` and `pause` calls retry on 429, 502, 503 and 504; a create whose response is lost is `outcome_unknown`. Every command start carries a tag, so a cancelled start, or one whose response was lost, is found and stopped. **Breaking for beta users:** `box.native` is now a `NativeApi` with the `"api"` and `"envd"` planes and the `{sandboxId}` placeholder, and `e2b().api` makes account calls. For the official SDK's `Sandbox`, install `e2b` and call `await box.native.sdk(() => import("e2b"))`.
17
+ - **Breaking for Freestyle:** `freestyle()` calls Freestyle's API directly, so `npm i @opencoredev/sandbox-sdk` is the whole install and the `freestyle` package is no longer a peer. `box.native` is now a `NativeApi` (`request`, `fetch`, `sdk`) instead of the SDK's `Vm`. Replace `box.native.exec(...)` with `(await box.native.sdk(() => import("freestyle"))).exec(...)` after installing `freestyle` yourself, or call the endpoint with `box.native.request("POST", "/v5/vms/{vmId}/exec-await", { body })`. `freestyle().api` makes account-level calls. Background requests (HTTP 202 polling), ranged reads and chunked uploads over 8 MiB work as they did with the SDK. A create aborted by its signal no longer cuts the request, so a VM Freestyle allocates anyway is deleted instead of left running.
18
+ - `boat()` and `sandboxer()` call their API over plain HTTP. `@boatdev/sdk` is no longer a peer: `npm i @opencoredev/sandbox-sdk` is the whole install. Breaking for beta users: `box.native` is now a native API (`request`, `fetch`, `sdk`) instead of `{ sandbox, client }`. Get the old pair with `await box.native.sdk(() => import("@boatdev/sdk"))` after installing `@boatdev/sdk` yourself, and the account client with `boat().api.sdk(...)`. Sandboxer keeps `box.native.region`, `regionSource` and `createSnapshot(name)`.
19
+ - On these six providers, credential headers you pass to `box.native` (`authorization`, `cookie`, `*-token`, `*-key`) are never sent to another origin or followed through a redirect, and an error that echoes one shows it redacted. A command whose output stream breaks after it started rejects with `outcome_unknown`, and a write is never sent twice after a credential refresh unless the server refused it first. A Boat or Sandboxer create stays within `requestTimeoutMs` across its retries.
20
+
21
+ ## 1.0.0-beta.1
22
+
23
+ Fixes from early-adopter reports, provider options that were missing, and bundler support. Published under the `next` tag.
24
+
25
+ ### Fixed
26
+
27
+ - Provider SDKs load inside bundles. CommonJS peers imported from an esbuild, webpack or Next.js bundle no longer fail with `X is not a constructor`, and error mapping no longer depends on class names that minifiers rename. boxd transfers and Daytona file operations work in bundles too. An ESM bundle without a `require` shim fails with an `unavailable` error that says how to fix it.
28
+ - Errors keep a redacted `cause`, and messages say what went wrong instead of "The provider reported provider". URLs, auth headers and credential-like values are scrubbed from every message and cause.
29
+ - `boat()` and `sandboxer()` no longer put stdin or file contents in command strings. Both travel through the file API into a private `0600` staging file.
30
+ - `connectSandbox()` no longer runs secret recovery on connect. It runs before the first command, so connecting to a stopped sandbox to destroy it works. Pass `recoverSecrets: false` to skip it.
31
+ - `start()` reports a command that exits at once, or a missing `cwd`, as `failed` instead of `running`. A missing `cwd` is a normal failed run (exit 2) on every provider.
32
+ - Railway command timeouts kill only the command instead of deleting the sandbox. Railway `list()` includes owned sandboxes that aren't running yet.
33
+ - Tenki reports `/workspace` as a directory on a fresh sandbox. boxd and Freestyle report missing files as `file_not_found`. e2b reports exit 143 after `stop()`.
34
+ - A local Docker sandbox restored from a snapshot no longer inherits the source's deadlines.
35
+ - A Daytona create that times out deletes the half-created sandbox (with `@daytonaio/sdk` 0.227 or later). The Daytona peer range now accepts any 0.x from 0.225.
36
+ - A thrown `SandboxError` prints as `SandboxError [code]: message`. `box.run()` returns a real `Promise` with `catch` and `finally`.
37
+
38
+ ### Added
39
+
40
+ - `files.write(path, data, { mode })` and `files.write(record, { mode })` set POSIX permissions. Providers apply the mode natively where they can; the rest run `chmod` right after the write.
41
+ - `box.snapshot({ expiresInMs })`. Providers that can't expire snapshots reject a nonzero value with `unsupported`.
42
+ - `vercel()`: `persistent`, `timeoutMs` (per session), `image`, `runtime`, `source` (git or tarball), exact vCPU sizes, `networkPolicy`, `region`, `failoverRegions`, `networkId`, `mounts`, `snapshotExpiresInMs`, `keepLastSnapshots`, `deleteOrphanSnapshots` and `fetch`.
43
+ - Native options for the other providers, including e2b `public`, `autoPause`, `autoResume`, `volumes`; Daytona `public`, `autoArchiveMs`, `autoDeleteMs`, `volumes`, `createTimeoutMs`; Upstash `keepAlive`, `browser`, `attachHeaders`; Tenki `pauseRetentionMs`, `volumes`, `workspaceId`, `previewTtlMs`; Railway `resources`; Boat and Sandboxer `ttlSeconds`, `snapshots`, `monitoring`, `org`, and Sandboxer `idleTimeoutMs`; local `platform`, `user`, `runtime`, `networkMode`, `mounts`, `pidsLimit`, `shmSizeMb`, capabilities, `securityOpt` and custom sizes; Superserve network policies, `secretBindings`, `previewAccess`, `autoPauseMs`, `autoDeleteMs`; boxd allow lists, `volumes`, `timeoutMs`, `idleTimeoutMs`; Freestyle `autoDeleteMs` and snapshot expiry; agentOS `software`, `mounts`, `limits`. Each provider page lists them.
44
+
45
+ ## 1.0.0-beta.0
46
+
47
+ First preview of the 1.0 rewrite, published under the `next` tag. The SDK was rewritten from scratch; most of the 0.2 surface changed. The API may still change before 1.0.0. The [upgrade guide](https://github.com/opencoredev/sandbox-sdk/blob/main/apps/docs/content/upgrade-from-0-2.mdx) maps every 0.2 call to its 1.0 form.
48
+
49
+ ### Unreleased
50
+
51
+ - Provider options now use `baseUrl` instead of `boxd.baseURL`, `daytona.apiUrl`, and `boat.apiUrl`; `tenki.apiKey` replaces `authToken`, and `boat.machine` replaces `type`. Old names remain deprecated aliases until 1.0.0. When both are supplied, the new name wins.
52
+ - Added the Sandboxer provider at `@opencoredev/sandbox-sdk/sandboxer`. It shares Boat's API transport, including deferred workspace setup, and adds pause and resume, named snapshots, cookie-authenticated previews, and a `region` option (`us-east` or `eu-central`, default `SANDBOXER_REGION`, else nearest).
53
+ - Provider option hovers document defaults and environment variables. All provider subpaths export a named provider type. Missing-credential errors explain the next step; E2B checks its key on first use and reads environment values set after factory construction.
54
+
55
+ ### Breaking changes since 0.2.0
56
+
57
+ - `createSandbox(provider, options?)` takes the provider as its first argument instead of `createSandbox({ provider })`. The `cwd` option is gone; every sandbox starts in `/workspace`.
58
+ - `stop()` is split into `destroy()`, which deletes the sandbox, and `close()`, which detaches and leaves it running. `await using` calls `close()` for keyed sandboxes and `destroy()` otherwise.
59
+ - `run` results: `success` is now `ok`, `timeout` is `timeoutMs` (default 120 s), and a timeout resolves with `timedOut: true` instead of throwing. The `{ command, args }` form is replaced by the `` box.$`...` `` tag.
60
+ - `files.text(path)` is now `files.read(path)`; bytes come from `files.read(path, { as: "bytes" })`. `files.mkdir` is gone (`write` creates parents). `write` accepts only strings and `Uint8Array`.
61
+ - `processes.start` is now `box.start(command, { name })`. `output()` is replaced by `lines()` and `logs()`, `kill()` by `stop()`, and process stdin writes are removed.
62
+ - `ports.expose` is now `box.preview(port)`, which returns `url` plus any required `headers`.
63
+ - `snapshots.*` is now `box.snapshot()` and `createSandbox(provider, { from: id })`.
64
+ - `local()` runs a Docker container from `node:22-bookworm` instead of a bundled AgentOS VM. AgentOS moved to the optional `/agentos` entry.
65
+ - `sandbox.raw` is now `box.native`.
66
+ - Removed: the Ascii Box provider, the `/eve` integration, and the helpers `withSandbox`, `supports`, `requireCapability`, `capabilityMode`, `isSandboxError`, and `redactSensitive`. Use `await using`, `box.capabilities.has(...)`, and `error instanceof SandboxError`.
67
+ - Node.js 22+ or Bun 1.3+ is required. The package is ESM only.
68
+
69
+ ### Highlights
70
+
71
+ - Thirteen providers behind one API: E2B, Daytona, Vercel, Upstash Box (durable and ephemeral), Railway, Tenki, boxd, Freestyle, Superserve, Boat, Local (Docker), agentOS, and an in-memory fake for tests.
72
+ - Typed capabilities: `pause`, `snapshot`, and `terminal` exist on the sandbox type only when the provider supports them. Options a provider cannot enforce fail with `unsupported` instead of being dropped.
73
+ - Keys: `createSandbox(provider, { key })` returns the same sandbox on every call, with an optional `locator` for your own store.
74
+ - Secrets passed as `secrets` are redacted from command output, logs, errors, and agent tool results, including after reconnecting.
75
+ - Durable named background processes with readiness checks (`port`, `http`, or `log`) and resumable log cursors that survive a server restart.
76
+ - Files: `edit`, `search`, `watch`, `upload`/`download`, and `mark`/`changes` diffs, plus `box.git` with token-safe `clone` and `push`.
77
+ - Agent tools for AI SDK (`/ai`), Mastra (`/mastra`), and OpenAI Agents (`/openai`), with output budgets, a `root` path guard, and a `beforeRun` command hook.
78
+ - `SandboxError` with 15 stable codes, a `retryable` flag, and a `hint` for every code.
79
+ - Zero runtime dependencies. The root entry is under 8 KB minified, and provider SDKs load only on first use.
80
+ - A shared conformance suite (`/testing`) that every adapter, including third-party ones, can run.
package/README.md CHANGED
@@ -1,49 +1,381 @@
1
- <p align="center">
2
- <img alt="Sandbox SDK with supported provider logos" src="https://raw.githubusercontent.com/opencoredev/sandbox-sdk/main/Background-with-text.png" width="820" />
3
- </p>
1
+ # Sandbox SDK
4
2
 
5
- Run the same TypeScript sandbox code on Local, E2B, Daytona, Vercel Sandbox, Upstash Box, Ascii Box, or Railway Sandboxes.
3
+ One TypeScript API for running code in a sandbox. The same `createSandbox`, `run`, `files`, `start`, and `preview` calls work on E2B, Daytona, Vercel, Upstash Box, Railway, Tenki, boxd, Freestyle, Superserve, Boat, Sandboxer, Docker on your machine, and an in-process fake for tests. Changing provider means changing one import.
4
+
5
+ > **Coming from 0.2?** 1.0 changes the API. [Upgrade from 0.2](https://sandbox-sdk.app/docs/upgrade-from-0-2) walks through each change.
6
6
 
7
7
  ## Install
8
8
 
9
- ```bash
10
- bun add @opencoredev/sandbox-sdk
9
+ ```sh
10
+ npm install @opencoredev/sandbox-sdk
11
11
  ```
12
12
 
13
- Node.js 22 or 24 is supported. Bun 1.3 or newer is also supported.
13
+ That is the whole install for E2B, Daytona, Freestyle, Superserve, Boat, and Sandboxer, which call the provider's HTTP API directly. Vercel, Upstash Box, Railway, Tenki, boxd, and agentOS also need the provider's package, for example `npm install @vercel/sandbox`. The [peer packages table](https://sandbox-sdk.app/docs/reference/capabilities#peer-packages) lists every one. Those packages are optional peers, so you only download the ones you need. The core has no runtime dependencies.
14
+
15
+ Requires Node.js 22+ or Bun 1.3+, ESM only. The examples use `await using`, which runs natively on Node.js 24 and Bun. On Node.js 22, compile with TypeScript (target ES2022 or lower) or call `box.destroy()` yourself.
14
16
 
15
17
  ## Quickstart
16
18
 
19
+ This runs with no account and no Docker. The `memory` provider is an in-process fake with a small shell (`echo`, `cat`, `printf`, `sleep`, `ls`, `printenv`):
20
+
17
21
  ```ts
18
22
  import { createSandbox } from "@opencoredev/sandbox-sdk";
19
- import { local } from "@opencoredev/sandbox-sdk/local";
23
+ import { memory } from "@opencoredev/sandbox-sdk/memory";
24
+
25
+ await using box = await createSandbox(memory());
26
+
27
+ await box.files.write("hello.txt", "hello from the sandbox\n");
28
+ const result = await box.run("cat hello.txt");
29
+ console.log(result.ok, result.stdout); // true "hello from the sandbox\n"
30
+ ```
31
+
32
+ For a real Linux sandbox, swap the provider. Nothing else changes:
20
33
 
21
- await using sandbox = await createSandbox({ provider: local() });
22
- console.log((await sandbox.run("node --version")).stdout);
34
+ ```ts
35
+ import { createSandbox } from "@opencoredev/sandbox-sdk";
36
+ import { e2b } from "@opencoredev/sandbox-sdk/e2b";
37
+
38
+ // Reads E2B_API_KEY from the environment. No other package needed.
39
+ await using box = await createSandbox(e2b());
40
+
41
+ await box.files.write("hello.py", "print('hello from the sandbox')");
42
+ const result = await box.run("python3 hello.py");
43
+ console.log(result.ok, result.stdout);
23
44
  ```
24
45
 
25
- `await using` stops the sandbox automatically when its scope exits, including when an operation throws.
46
+ `await using` deletes the sandbox when the scope ends, even if your code throws. A command that exits non-zero resolves with `ok: false`; it never throws.
47
+
48
+ ## Switch providers with one variable
49
+
50
+ Pick the provider from an environment variable and keep the sandbox code identical. Each adapter loads through a dynamic `import()`, so only the provider you pick needs its peer package installed, if it has one. At runtime that holds as written. For the TypeScript compiler, the switch still reaches every listed adapter's declarations, and those reference their peer's types. Set `"skipLibCheck": true` in `tsconfig.json` (most templates already do), or install the peers you list as devDependencies, otherwise `tsc` reports TS2307 for the ones you left out.
51
+
52
+ ```ts
53
+ import { createSandbox, type Sandbox } from "@opencoredev/sandbox-sdk";
54
+ import type { Provider } from "@opencoredev/sandbox-sdk/provider";
26
55
 
27
- Node.js 24 and Bun run this syntax directly. On Node.js 22, compile TypeScript to ES2022 or use the callback-style `withSandbox()` helper.
56
+ async function loadProvider(name: string): Promise<Provider> {
57
+ switch (name) {
58
+ case "memory":
59
+ return (await import("@opencoredev/sandbox-sdk/memory")).memory();
60
+ case "local":
61
+ return (await import("@opencoredev/sandbox-sdk/local")).local();
62
+ case "e2b":
63
+ return (await import("@opencoredev/sandbox-sdk/e2b")).e2b();
64
+ case "daytona":
65
+ return (await import("@opencoredev/sandbox-sdk/daytona")).daytona();
66
+ case "vercel":
67
+ return (await import("@opencoredev/sandbox-sdk/vercel")).vercel();
68
+ case "upstash":
69
+ return (await import("@opencoredev/sandbox-sdk/upstash")).upstash();
70
+ default:
71
+ throw new Error(`Unknown SANDBOX_PROVIDER "${name}"`);
72
+ }
73
+ }
74
+
75
+ // Portable code takes the base `Sandbox` type: only the methods every provider has.
76
+ async function greet(box: Sandbox): Promise<string> {
77
+ await box.files.write("greeting.txt", `hello from ${box.provider}\n`);
78
+ return (await box.run("cat greeting.txt")).stdout.trim();
79
+ }
80
+
81
+ await using box = await createSandbox(await loadProvider(process.env.SANDBOX_PROVIDER ?? "memory"));
82
+ console.log(await greet(box));
83
+ ```
84
+
85
+ `SANDBOX_PROVIDER=local` runs it in Docker; `SANDBOX_PROVIDER=e2b` runs it on E2B. The repository has a runnable version with every provider and an exhaustive switch in `examples/getting-started`.
86
+
87
+ Two things differ between providers and are worth checking before you go multi-provider:
88
+
89
+ - **Optional methods.** `pause`/`resume` and `snapshot` exist only on providers that support them. See [Pause, resume, and snapshots](#pause-resume-and-snapshots) for how this works with a runtime-selected provider.
90
+ - **Create options.** `size`, `network`, `from`, `timeoutMs`, and `idleTimeoutMs` fail with `unsupported` on providers that cannot enforce them. Provider-agnostic code should leave them out or catch that code.
28
91
 
29
92
  ## Providers
30
93
 
31
- | Provider | Runtime | Best for |
32
- | --------------------------------------------------------------- | ----------------------- | --------------------------------------- |
33
- | [Local](https://sandbox-sdk.app/docs/providers/local) | AgentOS VM | Development, CI, and self-hosting |
34
- | [E2B](https://sandbox-sdk.app/docs/providers/e2b) | Hosted Linux sandbox | Coding agents and isolated jobs |
35
- | [Daytona](https://sandbox-sdk.app/docs/providers/daytona) | Cloud workspace | Persistent projects and GPUs |
36
- | [Vercel Sandbox](https://sandbox-sdk.app/docs/providers/vercel) | Hosted Linux sandbox | Coding agents and persistent workspaces |
37
- | [Upstash Box](https://sandbox-sdk.app/docs/providers/upstash) | Durable cloud container | Serverless agents and long-lived state |
38
- | [Ascii Box](https://sandbox-sdk.app/docs/providers/box) | Persistent cloud VM | Full VMs and protected app previews |
39
- | [Railway](https://sandbox-sdk.app/docs/providers/railway) | Ephemeral cloud VM | Durable jobs and private networking |
94
+ Import each provider from its own subpath. The root entry never loads a provider SDK, and constructing a factory performs no I/O. The [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) lists each provider's peer package, capabilities, limits, and preview behavior, and a script checks it against this package's source.
95
+
96
+ | Provider | Import from | Factory | Credentials (env) |
97
+ | -------------------------------------------------------------- | ------------- | ----------------------- | ------------------------------------------------------------------------------- |
98
+ | [E2B](https://sandbox-sdk.app/docs/providers/e2b) | `/e2b` | `e2b()` | `E2B_API_KEY` |
99
+ | [Daytona](https://sandbox-sdk.app/docs/providers/daytona) | `/daytona` | `daytona()` | `DAYTONA_API_KEY` (optional `DAYTONA_API_URL`, `DAYTONA_TARGET`) |
100
+ | [Vercel](https://sandbox-sdk.app/docs/providers/vercel) | `/vercel` | `vercel()` | `VERCEL_OIDC_TOKEN`, or `VERCEL_TOKEN` + `VERCEL_TEAM_ID` + `VERCEL_PROJECT_ID` |
101
+ | [Upstash Box](https://sandbox-sdk.app/docs/providers/upstash) | `/upstash` | `upstash()` | `UPSTASH_BOX_API_KEY` (optional `UPSTASH_BOX_BASE_URL`) |
102
+ | [Railway](https://sandbox-sdk.app/docs/providers/railway) | `/railway` | `railway()` | `RAILWAY_API_TOKEN`, `RAILWAY_ENVIRONMENT_ID` |
103
+ | [Tenki](https://sandbox-sdk.app/docs/providers/tenki) | `/tenki` | `tenki()` | `TENKI_AUTH_TOKEN` or `TENKI_API_KEY` |
104
+ | boxd | `/boxd` | `boxd()` | `BOXD_API_KEY` (optional `BOXD_BASE_URL`) |
105
+ | Freestyle | `/freestyle` | `freestyle()` | `FREESTYLE_API_KEY` |
106
+ | Superserve | `/superserve` | `superserve()` | `SUPERSERVE_API_KEY` |
107
+ | Boat | `/boat` | `boat()` | `BOAT_API_KEY` (optional `BOAT_API_BASE`) |
108
+ | Sandboxer | `/sandboxer` | `sandboxer({ region })` | `SANDBOXER_API_KEY` (optional `SANDBOXER_REGION`: `us-east`, `eu-central`) |
109
+ | [Local (Docker)](https://sandbox-sdk.app/docs/providers/local) | `/local` | `local()` | none; needs a running Docker Engine (`DOCKER_HOST` or `/var/run/docker.sock`) |
110
+ | [agentOS](https://sandbox-sdk.app/docs/providers/agentos) | `/agentos` | `agentos()` | none |
111
+ | Memory | `/memory` | `memory()` | none |
112
+
113
+ Capability meanings: `pause` adds `box.pause()` and `box.resume()`, `snapshot` adds `box.snapshot()` and `createSandbox(provider, { from })`, `size` allows the `size` option, and `network-policy` allows `network: "none"` or `{ allow: [...] }`. The SDK also defines `terminal` (`box.terminal()`, an interactive PTY), but no built-in provider supports it yet.
114
+
115
+ Every factory also accepts its credential as an option, such as `e2b({ apiKey })` or `railway({ token, environmentId })`. Endpoints use `baseUrl` (boxd, Daytona, Tenki, Upstash, Boat), and Boat's default machine size uses `machine`:
116
+
117
+ ```ts
118
+ import { boat } from "@opencoredev/sandbox-sdk/boat";
119
+ import { boxd } from "@opencoredev/sandbox-sdk/boxd";
120
+ import { daytona } from "@opencoredev/sandbox-sdk/daytona";
121
+ import { tenki } from "@opencoredev/sandbox-sdk/tenki";
122
+
123
+ const providers = [
124
+ boxd({ baseUrl: "https://boxd.sh:9443" }),
125
+ daytona({ baseUrl: "https://app.daytona.io/api" }),
126
+ boat({ baseUrl: "https://boat.dev/api/v1", machine: "small" }),
127
+ tenki({ apiKey: process.env.TENKI_API_KEY }),
128
+ ];
129
+ ```
130
+
131
+ The old names (`boxd.baseURL`, `daytona.apiUrl`, `boat.apiUrl`, `tenki.authToken`, and `boat.type`) still work as deprecated aliases until 1.0.0. When both names are set, the new name wins.
132
+
133
+ ## Core API
134
+
135
+ ### Create, reconnect, clean up
136
+
137
+ ```ts
138
+ import { connectSandbox, createSandbox } from "@opencoredev/sandbox-sdk";
139
+ import { e2b } from "@opencoredev/sandbox-sdk/e2b";
140
+
141
+ const box = await createSandbox(e2b(), {
142
+ key: "user:123", // the same key returns the same sandbox
143
+ env: { NODE_ENV: "development" },
144
+ secrets: { GITHUB_TOKEN: "ghp_example" }, // redacted from all output and errors
145
+ network: { allow: ["registry.npmjs.org"] },
146
+ timeoutMs: 30 * 60_000, // hard lifetime, where the provider supports it
147
+ });
148
+
149
+ await box.close(); // detach; the sandbox keeps running
150
+ const again = await connectSandbox(e2b(), box.id);
151
+ await again.destroy(); // delete it
152
+ ```
153
+
154
+ `await using box = await createSandbox(...)` disposes the handle when the scope ends:
155
+
156
+ - Without a `key`, it calls `destroy()` and the sandbox is deleted.
157
+ - With a `key`, it calls `close()`, so the sandbox survives for the next request with that key.
158
+
159
+ Use `listSandboxes(provider)` and `reapSandboxes(provider, { olderThanMs })` to find and delete sandboxes this SDK created, such as ones a crashed process never cleaned up.
160
+
161
+ ### Run commands and stream output
162
+
163
+ ```ts
164
+ const result = await box.run("npm test", { cwd: "app" });
165
+ if (!result.ok) console.log(result.exitCode, result.output);
166
+
167
+ const branch = "feature/login";
168
+ await box.$`git checkout ${branch}`; // interpolated values are shell-quoted
169
+
170
+ const install = box.run("npm install");
171
+ for await (const chunk of install) process.stdout.write(chunk.text); // chunk.stream is "stdout" or "stderr"
172
+ const { ok, durationMs } = await install; // the same handle, now finished
173
+ ```
174
+
175
+ `run` returns a lazy handle: nothing starts until you `await` it or iterate it. Commands start in `/workspace` and keep up to 1 MB per stream (`maxOutputBytes`); older output is dropped and `truncated` is set. `stdout` and `stderr` are separate strings, and `output` interleaves them in arrival order.
176
+
177
+ ### Timeouts and cancellation
178
+
179
+ ```ts
180
+ const slow = await box.run("sleep 600", { timeoutMs: 5_000 });
181
+ console.log(slow.ok, slow.timedOut, slow.exitCode); // false true null
182
+
183
+ const chained = await box.run("npm test").cwd("app").timeout(60_000);
184
+
185
+ const controller = new AbortController();
186
+ const pending = box.run("npm run build", { signal: controller.signal });
187
+ controller.abort();
188
+ console.log((await pending).ok); // false; an aborted run also reports timedOut: true
189
+ ```
190
+
191
+ - Commands time out after 120 seconds unless you pass `timeoutMs` or chain `.timeout(ms)`. A timeout or an abort kills the command's process group and resolves with `ok: false`, `exitCode: null`, and `timedOut: true`. It does not throw.
192
+ - `createSandbox(provider, { signal })` rejects with `SandboxError` code `aborted`. A sandbox that arrives after the abort is destroyed for you.
193
+ - `start(..., { readyTimeoutMs })` bounds readiness (default 60 seconds), and `preview(port, { waitMs })` waits for a 2xx.
194
+ - `timeoutMs` and `idleTimeoutMs` on `createSandbox` set the sandbox's own lifetime, not a command timeout. A provider that can't enforce one rejects it with `unsupported`. The `timeoutMs` and `idleTimeoutMs` rows of the [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) say which providers support each, and in what units.
195
+
196
+ ### Files
197
+
198
+ ```ts
199
+ await box.files.write({ "app/package.json": "{}", "app/index.js": "console.log(1)" });
200
+ const text = await box.files.read("app/index.js");
201
+ const bytes = await box.files.read("app/index.js", { as: "bytes" });
202
+ await box.files.edit("app/index.js", { find: "console.log(1)", replace: "console.log(2)" });
203
+ const matches = await box.files.search("console.log", { path: "app" });
204
+ const entries = await box.files.list("app", { recursive: true });
205
+ await box.files.upload("./local-project", "app", { ignore: ["node_modules"] });
206
+ const diff = await box.files.changes({ since: await box.files.mark() });
207
+ ```
208
+
209
+ Relative paths resolve against `/workspace`. `read` returns a string unless you pass `{ as: "bytes" }`. A missing path fails with `file_not_found`. `edit` fails with `edit_not_found` or `edit_not_unique` unless the text matches exactly once.
210
+
211
+ ### Background processes
212
+
213
+ ```ts
214
+ const dev = await box.start("npm run dev", { name: "dev", ready: { port: 3000 } });
215
+ console.log(dev.ready, dev.status); // true "running"
216
+
217
+ const { text } = await box.process("dev").logs();
218
+ await dev.stop();
219
+ ```
220
+
221
+ `start` returns once the process is ready. Readiness is one of:
222
+
223
+ - `{ port: 3000 }`: the port's preview URL answers with a 2xx.
224
+ - `{ http: { port: 3000, path: "/health" } }`: that path answers with a 2xx.
225
+ - `{ log: /listening/ }`: a log line matches.
226
+
227
+ Without `ready`, `start` returns as soon as the process launches. If the process exits first, `start` fails with `process_exited` and includes the exit code and log tail. Readiness gives up after `readyTimeoutMs` (default 60 seconds) with `timeout`.
228
+
229
+ The name is the process's durable ID (1 to 128 letters, digits, `-`, `_`). It is optional: without one, `start` derives a stable name from the command, such as `npm-1a2b3c4d`, and returns it as `dev.name`. Any client can find it again with `box.process("dev")`, even after your server restarts. `box.processes()` lists them, and a handle has `logs()`, `lines()`, `stop()`, `restart()`, and `wait()`.
230
+
231
+ ### Previews
232
+
233
+ ```ts
234
+ import { createSandbox } from "@opencoredev/sandbox-sdk";
235
+ import { local } from "@opencoredev/sandbox-sdk/local";
236
+
237
+ await using box = await createSandbox(local(), { ports: [3000] });
238
+ await box.start("python3 -m http.server 3000", { name: "web", ready: { port: 3000 } });
239
+
240
+ const preview = await box.preview(3000);
241
+ const response = await fetch(preview.url, { headers: preview.headers });
242
+ console.log(preview.url, response.status); // http://127.0.0.1:<port>/ 200
243
+ ```
244
+
245
+ Always send `preview.headers`. Several providers put the access token there and reject requests without it. Some providers only route ports you declared with `createSandbox(provider, { ports })`, so pass `ports` in provider-agnostic code; the other providers ignore it. The `ports` and Preview URL rows of the [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) say which. Servers must listen on `0.0.0.0`, not `localhost`.
246
+
247
+ ### Pause, resume, and snapshots
248
+
249
+ ```ts
250
+ import { createSandbox } from "@opencoredev/sandbox-sdk";
251
+ import { e2b } from "@opencoredev/sandbox-sdk/e2b";
252
+
253
+ await using box = await createSandbox(e2b());
254
+ const snap = await box.snapshot();
255
+ await using copy = await createSandbox(e2b(), { from: snap.id });
256
+
257
+ await box.pause();
258
+ await box.resume();
259
+ ```
260
+
261
+ These methods are gated in the types by the provider's capability union. With a concrete provider, a missing method is a compile error:
262
+
263
+ ```ts
264
+ import { createSandbox } from "@opencoredev/sandbox-sdk";
265
+ import { boat } from "@opencoredev/sandbox-sdk/boat";
266
+
267
+ await using box = await createSandbox(boat());
268
+ // @ts-expect-error Boat has no snapshot capability, so the method does not exist.
269
+ await box.snapshot();
270
+ ```
271
+
272
+ When you pick the provider at runtime, as in [Switch providers](#switch-providers-with-one-variable), the provider's type is the wide `Provider`, so the SDK cannot know which methods exist. `pause`, `resume`, `snapshot`, and `terminal` are then optional on the sandbox, and calling one directly is a compile error. `hasCapability` checks at runtime and narrows the type:
273
+
274
+ ```ts
275
+ import { hasCapability } from "@opencoredev/sandbox-sdk";
276
+
277
+ if (hasCapability(box, "snapshot")) {
278
+ const { id } = await box.snapshot();
279
+ console.log(`saved ${id}`);
280
+ }
281
+ ```
282
+
283
+ `box.capabilities.has("snapshot")` gives the same answer as a boolean, but it cannot narrow `box`, so use `hasCapability` before calling the method.
284
+
285
+ ### Git
286
+
287
+ ```ts
288
+ await box.git.clone("https://github.com/opencoredev/sandbox-sdk", { dir: "repo", depth: 1 });
289
+ await box.git.commit("repo", { message: "Update docs", all: true });
290
+ await box.git.push("repo", { token: process.env.GITHUB_TOKEN });
291
+ ```
292
+
293
+ Tokens reach git through a temporary credential helper, never argv, env, or shell history, and are redacted from output. Git must be installed in the sandbox image; the memory provider has no git.
294
+
295
+ ### Errors
296
+
297
+ ```ts
298
+ import { SandboxError } from "@opencoredev/sandbox-sdk";
299
+
300
+ try {
301
+ await box.files.read("missing.txt");
302
+ } catch (error) {
303
+ if (!(error instanceof SandboxError)) throw error;
304
+ console.error(error.code, error.message, error.hint, error.retryable);
305
+ }
306
+ ```
307
+
308
+ The SDK only throws `SandboxError`. A non-zero exit, a command timeout, or an aborted `run` is a result, not an error. `hint` is the next step on its own, `retryable` says whether the same call can succeed again, and `provider` and `sandboxId` say where it happened. Secrets are redacted from every field.
309
+
310
+ | `code` | Meaning |
311
+ | ----------------------------------- | -------------------------------------------------------------------------------------------------------- |
312
+ | `auth` | Credentials are missing or rejected. |
313
+ | `not_found` | The sandbox no longer exists, or this handle was closed. |
314
+ | `quota` | A provider limit or billing stopped the request. Usually retryable. |
315
+ | `unavailable` | The provider is down or unreachable. Usually retryable. |
316
+ | `unsupported` | The provider cannot do what was asked: `size`, `network`, a lifetime option, an undeclared preview port. |
317
+ | `timeout` | A provider operation or a readiness check took too long. |
318
+ | `aborted` | Your `AbortSignal` fired during `createSandbox`. |
319
+ | `outcome_unknown` | The request may or may not have happened. Check state before retrying. |
320
+ | `process_exited` | A background process exited before it was ready. |
321
+ | `port_not_ready` | A preview did not answer with a 2xx before `waitMs` ran out. |
322
+ | `edit_not_found`, `edit_not_unique` | `files.edit` matched zero times or more than once. |
323
+ | `file_not_found` | The path does not exist. |
324
+ | `invalid_argument` | The input is invalid. Retrying will not help. |
325
+ | `provider` | Any other provider or adapter failure. Read `message` and `cause`. |
326
+
327
+ ## Give an agent a sandbox
328
+
329
+ Install `zod` and your agent framework, then pass the tools to your agent:
330
+
331
+ ```ts
332
+ import { generateText, stepCountIs } from "ai";
333
+ import { sandboxTools } from "@opencoredev/sandbox-sdk/ai";
334
+
335
+ const { text } = await generateText({
336
+ model: "anthropic/claude-opus-5-5",
337
+ tools: sandboxTools(box, { root: "/workspace/app" }),
338
+ stopWhen: stepCountIs(20),
339
+ prompt: "Add a /health route to the Express app and run its tests.",
340
+ });
341
+ ```
342
+
343
+ | Framework | Import | Returns |
344
+ | ------------------- | --------------------------------- | ------------------------------------------ |
345
+ | AI SDK 7 | `@opencoredev/sandbox-sdk/ai` | tool map for `generateText` / `streamText` |
346
+ | Mastra 1.78+ | `@opencoredev/sandbox-sdk/mastra` | tool map for `new Agent({ tools })` |
347
+ | OpenAI Agents 0.20+ | `@opencoredev/sandbox-sdk/openai` | tool array for `new Agent({ tools })` |
348
+ | Anything else | `@opencoredev/sandbox-sdk/tools` | `createSandboxTools` and Zod `toolSchemas` |
349
+
350
+ The default tools are `run`, `read_file`, `write_file`, `edit_file`, `start_process`, `process_logs`, and `stop_process`. Opt into `search`, `list_files`, `changes`, or `preview` with `allow`. Results are compact and capped for model context, and registered secrets never reach the model. Use `beforeRun` to deny or rewrite commands. `root` limits file paths, but it is not a security boundary; the sandbox is.
351
+
352
+ ## Performance
353
+
354
+ The SDK aims for near-zero overhead on top of each provider's own API. The root entry is under 8 KB minified, providers load on first use, and `createSandbox` adds no provider calls beyond the create itself unless you pass `secrets`, `from`, or `trackChanges: true` (one exec each).
355
+
356
+ Time the SDK adds on top of each provider's own SDK, as median milliseconds. "Cold" is `createSandbox` plus the first `box.run("true")`, compared with the provider SDK's create plus its own exec. "Run" is a warm `run("true")` on an existing sandbox. Negative numbers and small differences are within provider noise.
357
+
358
+ | Provider | Create | Cold: create to first command | Warm `run` |
359
+ | ----------- | -----: | ----------------------------: | ---------: |
360
+ | E2B | +24 | +52 | +8 |
361
+ | Daytona | ±0 | ±0 | +38 |
362
+ | Upstash Box | +27 | +69 | +15 |
363
+ | Freestyle | ±0 | +51 | +23 |
364
+ | Tenki | ±0 | +119 | +15 |
365
+ | Superserve | ±0 | +73 | +9 |
366
+ | boxd | +272 | +370 | +52 |
367
+
368
+ boxd has no native metadata field, so a sandbox created with labels or a `key` writes its ownership record with one extra request before `createSandbox` returns. The other providers send labels with the create call itself and run any guest setup inside your first command.
40
369
 
41
- Local is included. Cloud providers use their official SDKs and credentials.
370
+ Measured on 2026-10-22 from one Linux host with `bench/scripts/sdk-overhead.ts`, 5 to 8 cold samples and 10 warm samples per provider. See the `bench/` directory in the repository to reproduce.
42
371
 
43
- ## Documentation
372
+ ## More
44
373
 
45
- Setup, usage, integrations, and API reference are available at [sandbox-sdk.app/docs](https://sandbox-sdk.app/docs).
374
+ - [Documentation](https://sandbox-sdk.app/docs): guides, provider pages, and the [error reference](https://sandbox-sdk.app/docs/reference/errors).
375
+ - Write your own provider: implement `Provider` from `@opencoredev/sandbox-sdk/provider` and test it with `runConformance` from `@opencoredev/sandbox-sdk/testing`.
376
+ - [Report an issue](https://github.com/opencoredev/sandbox-sdk/issues).
377
+ - [Changelog](./CHANGELOG.md).
46
378
 
47
379
  ## License
48
380
 
49
- [MIT](./LICENSE) © OpenCore
381
+ MIT
package/dist/ai.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { type Tool } from "ai";
2
+ import type { Sandbox } from "./types.js";
3
+ import { type SandboxToolsOptions, type ToolResult, type ToolParameters } from "./tools.js";
4
+ export type { SandboxToolsOptions } from "./tools.js";
5
+ export declare function sandboxTools(box: Sandbox, options?: SandboxToolsOptions): Record<string, Tool<ToolParameters, ToolResult, Record<string, never>>>;
package/dist/ai.js ADDED
@@ -0,0 +1 @@
1
+ import{J}from"./chunk-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{tool as u}from"ai";function b(p,m){return Object.fromEntries(M(p,m).map((o)=>[o.name,u({description:o.description,inputSchema:o.inputSchema,async*execute(e,s){let r=new AbortController,c=s.abortSignal?AbortSignal.any([r.signal,s.abortSignal]):r.signal,n=new J,a=n.stream(),l=a.next(),i=o.execute(e,(t)=>n.emit({stream:t.stream,text:t.text}),c).finally(()=>n.end());try{while(!0){let t=await l;if(t.done)break;yield{text:t.value.text},l=a.next()}yield await i}finally{r.abort(),await i,await a.return(void 0)}},toModelOutput:({output:e})=>({type:"text",value:e.text})})]))}export{b as sandboxTools};
@@ -0,0 +1,8 @@
1
+ import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-xgxfy2n8.js";import{posix as q}from"node:path";var l={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1"},u=(t=".")=>q.resolve("/workspace",t),re="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",G=`trap 'rm -rf -- "$2"' EXIT
2
+ (umask 077; mkdir -p "$2") || exit 1
3
+ { { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2/status"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
4
+ read -r code < "$2/status"
5
+ exit "$code"`,z=(t,e,o="sh")=>`sh -c ${n(G)} sh ${n(t)} ${n(e)} ${n(o)}`,B=new Map,me=(t,e)=>(B.get(t)?.get(e)??0)>0;function F(t,e){let o=B.get(t);if(!o)o=new Map,B.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let h=(a.get(e)??1)-1;if(h)a.set(e,h);else a.delete(e);if(!a.size)B.delete(t)}}class A{limit;head=Buffer.alloc(0);tail=Buffer.alloc(0);total=0;constructor(t){this.limit=t}add(t){let e=Buffer.from(t);this.total+=e.length;let o=Math.ceil(this.limit/2),a=Math.min(e.length,o-this.head.length);if(a>0)this.head=Buffer.concat([this.head,e.subarray(0,a)]);if(this.tail=Buffer.concat([this.tail,e.subarray(Math.max(0,a))]),this.tail.length>this.limit-o)this.tail=this.tail.subarray(this.tail.length-(this.limit-o))}get truncated(){return this.total>this.limit}text(){if(!this.truncated)return Buffer.concat([this.head,this.tail]).toString();let t=new TextDecoder().decode(this.head,{stream:!0}),e=0;while(e<this.tail.length&&((this.tail[e]??0)&192)===128)e++;let o=this.tail.subarray(e).toString();return t+`
6
+ [${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
7
+ `+o}}class J{listeners=new Set;ended=!1;failure;emit(t){for(let e of this.listeners)e(t)}fail(t){this.failure=t,this.end()}end(){this.ended=!0;for(let t of this.listeners)t()}async*stream(){let t=[],e=0,o=()=>{},a=(h)=>{if(h){let d=Buffer.byteLength(h.text)>1048576?Buffer.from(h.text).subarray(-1048576).toString():h.text;t.push({...h,text:d}),e+=Buffer.byteLength(d);while(e>1048576&&t.length>1)e-=Buffer.byteLength(t.shift()?.text??"")}o()};this.listeners.add(a);try{while(!this.ended||t.length){let h=t.shift();if(h)e-=Buffer.byteLength(h.text),yield h;else await new Promise((d)=>{o=d})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function E(t,e,o=!1){let a=[];function h(d=!1){let b=t.secrets,w=new Set(b.map((i)=>i[0]));while(a.length){let i=a[0];if(!i)break;if(!w.has(i.text[0])){let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;if(e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r),!i.text)a.shift();continue}let v=a.flatMap((r)=>o||r.stream===i.stream?[r.text]:[]).join(""),y=b.find((r)=>v.startsWith(r));if(y){e({stream:i.stream,text:"[REDACTED]"});let r=y.length;for(let x of a)if((o||x.stream===i.stream)&&r){let g=Math.min(r,x.text.length);x.text=x.text.slice(g),r-=g}}else{if(!d&&b.some((x)=>x.startsWith(v))){if(a.reduce((x,g)=>x+Buffer.byteLength(g.text),0)<=1048576)break;e({stream:i.stream,text:"[REDACTED]"}),a.shift();continue}let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r)}for(let r=a.length-1;r>=0;r--)if(!a[r]?.text)a.splice(r,1)}}return{push(d){if(!t.secrets.length){e(d);return}a.push({...d}),h()},flush(){h(!0)}}}function oe(t,e,o,a,h,d=()=>{}){return(b,w={})=>{let i={...w},v,y=new J,r=(c=!1)=>v??=x(c).catch((p)=>{let m=o.error(p,t.name,e);throw y.fail(m),m});async function x(c){await d();let p=i.timeoutMs??120000,m=i.maxOutputBytes??1048576;if(!Number.isFinite(p)||p<=0||!Number.isSafeInteger(m)||m<1)s("timeoutMs and maxOutputBytes must be positive");let D=u(i.cwd),N=Date.now(),O=new A(m),C=new A(m),S=new A(m*2),k=new AbortController,R=i.signal?.aborted??!1,_=()=>{R=!0,k.abort()};i.signal?.addEventListener("abort",_,{once:!0});let j=setTimeout(_,p),P=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,I=!1,H=F(t.name,e),T=E(o,(f)=>{S.add(f.text),y.emit(f)},!0),L=E(o,(f)=>{(f.stream==="stdout"?O:C).add(f.text),T.push(f)});try{if(R)k.abort();let f=R?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?b:z(b,P,t.commandShell),cwd:D,env:{...a,...i.env,...l},stdin:i.stdin,timeoutMs:p,signal:k.signal,streaming:c,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?P:void 0,onChunk:(M)=>L.push(M)});return I=f.exitCode!==null&&f.exitCode>=0&&f.exitCode<128&&!f.timedOut&&!k.signal.aborted,R||=f.timedOut,L.flush(),T.flush(),h(O.total+C.total),{ok:!R&&f.exitCode===0,exitCode:R?null:f.exitCode,stdout:O.text(),stderr:C.text(),output:S.text(),durationMs:Date.now()-N,truncated:O.truncated||C.truncated||S.truncated,timedOut:R,cwd:D,command:o.text(b)}}catch(f){L.flush(),T.flush();let M=o.error(f,t.name,e);throw y.fail(M),M}finally{if(clearTimeout(j),i.signal?.removeEventListener("abort",_),!I&&!t.inlineActivity)await Promise.resolve().then(()=>t.files.remove(e,P,{recursive:!0})).catch(()=>{});H(),y.end()}}let g={[Symbol.toStringTag]:"RunHandle",then(c,p){return r().then(c,p)},catch(c){return r().catch(c)},finally(c){return r().finally(c)},[Symbol.asyncIterator](){let c=y.stream(),p=c.next();r(!0).catch(()=>{});let m=!0;return{next:()=>{if(m)return m=!1,p;return c.next()},return:()=>c.return(void 0)}},cwd(c){if(v)s("Run already started");return i.cwd=c,g},env(c){if(v)s("Run already started");return i.env={...i.env,...c},g},timeout(c){if(v)s("Run already started");return i.timeoutMs=c,g}};return g}}
8
+ export{l,u,re,me,A,J,E,oe};
@@ -0,0 +1,2 @@
1
+ function n(r){return`'${r.replaceAll("'","'\\''")}'`}
2
+ export{n};
@@ -0,0 +1,2 @@
1
+ import{t,r,e,w}from"./chunk-xgxfy2n8.js";var A=new WeakMap;function z(s){return s instanceof e?A.get(s):void 0}var C={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function h(s,a,d,n){let i=new e(`${a}. The stream from ${d.provider} cannot be read further.`,{code:C[s],provider:d.provider,sandboxId:d.sandboxId,retryable:s==="disconnected"||s==="truncated",...n===void 0?void 0:{cause:w(n)??s}});return A.set(i,s),i}class S{chunks=[];head=0;length=0;push(s){if(s.byteLength)this.chunks.push(s),this.length+=s.byteLength}find(s,a=0){let d=0;for(let n=0;n<this.chunks.length;n++){let i=this.chunks[n],l=n===0?this.head:0,u=i.byteLength-l;if(a<d+u){for(let o=Math.max(l,l+a-d);o<i.byteLength;o++)if(s(i[o]))return d+o-l}d+=u}return-1}at(s){let a=s;for(let d=0;d<this.chunks.length;d++){let n=this.chunks[d],i=d===0?this.head:0;if(a<n.byteLength-i)return n[i+a];a-=n.byteLength-i}return}take(s){let a=new Uint8Array(s),d=0;while(d<s){let n=this.chunks[0],i=Math.min(s-d,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+i),d),d+=i,this.head+=i,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=s,a}}async function*k(s,a){let d=s.getReader(),{signal:n}=a,i=!1,l=()=>{d.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw v(a);for(;;){let u;try{u=await d.read()}catch(o){if(i=!0,n?.aborted)throw v(a);if(o instanceof e){if(o.code==="unavailable"||o.code==="outcome_unknown")A.set(o,"disconnected");throw o}throw h("disconnected","The connection dropped mid-stream",a,o)}if(n?.aborted)throw i=!0,v(a);if(u.done){i=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!i)await d.cancel().catch(()=>{});d.releaseLock()}}function v(s){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:s.provider,sandboxId:s.sandboxId})}var p=new TextDecoder;var O=16777216;async function*ie(s,a){let d=a.maxFrameBytes??O,n=new S,i=(l,u)=>{let o=p.decode(l).replace(/\r$/,"");try{return JSON.parse(o)}catch{throw u?h("truncated","The stream ended inside a JSON line",a):h("malformed","A line is not valid JSON",a)}};for await(let l of k(s,a)){let u=n.length;n.push(l);for(let o=n.find((f)=>f===10,u);o>=0;o=n.find((f)=>f===10)){if(o>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a);let f=n.take(o+1).subarray(0,o);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield i(f,!1)}if(n.length>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield i(l,!0)}}async function*ae(s,a){let d=a.maxFrameBytes??O,n=new S,i=k(s,a),l=async(f)=>{while(n.length<f){let c=await i.next();if(c.done)return!1;n.push(c.value)}return!0};try{for(let f=!1;;){if(!await l(5)){if(n.length)throw h("truncated","The stream ended inside a Connect frame header",a);if(!f)throw h("truncated","The stream ended before the Connect end-of-stream frame",a);return}if(f)throw h("malformed","A Connect frame followed the end-of-stream frame",a);let c=n.take(5),b=c[0],m=new DataView(c.buffer,c.byteOffset,5).getUint32(1);if(b&1)throw h("malformed","A Connect frame is compressed, but no compression was negotiated",a);if(b&-4)throw h("malformed","A Connect frame has unknown flags",a);if(m>d)throw h("frame_too_large",`A Connect frame exceeds ${d} bytes`,a);if(!await l(m))throw h("truncated","The stream ended inside a Connect frame",a);let g=u(n.take(m));if(b&2)f=!0,yield o(g);else yield{kind:"message",message:g}}}finally{await i.return()}function u(f){try{return JSON.parse(p.decode(f))}catch{throw h("malformed","A Connect frame is not valid JSON",a)}}function o(f){if(!r(f)||f===null)throw h("malformed","The Connect end-of-stream frame is not an object",a);let c="error"in f?f.error:void 0,b="metadata"in f?f.metadata:void 0,m={kind:"end"};if(c!==void 0){if(!r(c)||c===null)throw h("malformed","The Connect end-of-stream error is not an object",a);let g="code"in c?c.code:void 0,y="message"in c?c.message:void 0,x="details"in c?c.details:void 0;if(!t(g))throw h("malformed","The Connect end-of-stream error has no code",a);m.error={code:g,...t(y)?{message:y}:void 0,...Array.isArray(x)?{details:x}:void 0}}if(r(b)){let g=Object.entries(b).filter((y)=>Array.isArray(y[1])&&y[1].every((x)=>t(x)));m.metadata=Object.fromEntries(g)}return m}}function de(s,a=!1){let d=new TextEncoder().encode(JSON.stringify(s)),n=new Uint8Array(5+d.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,d.byteLength),n.set(d,5),n}
2
+ export{z,ie,ae,de};
@@ -0,0 +1,2 @@
1
+ import{t,o}from"./chunk-xgxfy2n8.js";function T(s){let i=[];function f(r){if(t(r)){let e=Buffer.from(r),n=Buffer.alloc(5);n[0]=117,n.writeUInt32LE(e.length,1),i.push(n,e)}else if(o(r)){let e=Buffer.alloc(9);e[0]=103,e.writeDoubleLE(r,1),i.push(e)}else if(Array.isArray(r)){let e=Buffer.alloc(5);e[0]=91,e.writeUInt32LE(r.length,1),i.push(e);for(let n of r)f(n)}else if(r!==void 0){i.push(Buffer.from("{"));for(let[e,n]of Object.entries(r))if(n!==void 0)f(e),f(n);i.push(Buffer.from("0"))}}return f(s),Buffer.concat(i)}
2
+ export{T};