@mastra/cloudflare-sandbox 0.2.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # @mastra/cloudflare-sandbox
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Honor the sandbox runtime environment (`setEnv()`/`getEnv()` from `@mastra/core`) in every workspace sandbox provider. Environment variables set after construction now reach subsequent commands on all providers: ([#22250](https://github.com/mastra-ai/mastra/pull/22250))
8
+
9
+ - Process-manager-routed providers (E2B, Blaxel, Cloudflare, Daytona, Docker, Modal, Vercel microVM spawns) inherit the merge from the core spawn wrapper; their duplicated per-manager env plumbing is removed.
10
+ - Providers with their own exec transports (AgentCore, Apple Container, Railway, Vercel microVM and serverless `executeCommand`, Platform's private-network, WebSocket lease, and E2B lease paths) now merge `getEnv()` under per-call env.
11
+
12
+ Constructor `env` continues to behave as before: it seeds the sandbox runtime environment, and providers that bake env into the VM or container at creation time (Docker, Modal, Railway, Apple Container, Vercel, Platform) still do so. Per-call `env` on `executeCommand` still takes precedence for that command only.
13
+
14
+ Removed exported types (minor bump for these two packages): `BlaxelProcessManagerOptions` from `@mastra/blaxel` and `RailwayProcessManagerOptions` from `@mastra/railway`. Both existed only to pass `env` into a process manager constructed by hand; the core spawn wrapper now owns that merge, so the option and its type are gone.
15
+
16
+ - Updated dependencies [[`79f04a7`](https://github.com/mastra-ai/mastra/commit/79f04a7f6c6829da541139f638f2f1d267916e08), [`65edab1`](https://github.com/mastra-ai/mastra/commit/65edab1c233d17b8f163bad12fca410d0e6f16b1), [`1e47b75`](https://github.com/mastra-ai/mastra/commit/1e47b7520cab4cfaa8daed52f17e2e6d14ff7539), [`ab20a38`](https://github.com/mastra-ai/mastra/commit/ab20a38d0275f8d85e0f3833bd87ef487bcc609f), [`fd4d5fe`](https://github.com/mastra-ai/mastra/commit/fd4d5fe4f943699b85db5e74404f190d5a6b8c2a), [`ae8790c`](https://github.com/mastra-ai/mastra/commit/ae8790c4bfaa088d2ab279d1dcc06f326b9fd109), [`2c85f42`](https://github.com/mastra-ai/mastra/commit/2c85f428e04ccd63ea31a7ec80b5b327afdad555), [`11bbeb9`](https://github.com/mastra-ai/mastra/commit/11bbeb9b108ef2264e05acefc6dafb9cbb342921), [`48ef1f1`](https://github.com/mastra-ai/mastra/commit/48ef1f1d24eedafbb07f64e659a81b52b67b8bf6), [`aa3a85d`](https://github.com/mastra-ai/mastra/commit/aa3a85daf094c683bb97efdf4b6a696d2e474af5), [`d29d06f`](https://github.com/mastra-ai/mastra/commit/d29d06fe00bbd35b4571150ea04c59d2ed783c71), [`e6516df`](https://github.com/mastra-ai/mastra/commit/e6516dfcdae4f4ac0e7971d84359a81385ee602f), [`1a485f3`](https://github.com/mastra-ai/mastra/commit/1a485f3538f5ec64d58bd8b5e1e99de0c695c87b), [`0d37487`](https://github.com/mastra-ai/mastra/commit/0d37487d9f349388a3f1cef6a536cf9dcc4b6273), [`8661d7d`](https://github.com/mastra-ai/mastra/commit/8661d7d7179f0a024456aabdd8679bcecd09ac28), [`dbbfeb8`](https://github.com/mastra-ai/mastra/commit/dbbfeb85ec949dc9ebc0755e1ad262e4f5eba8db), [`575e343`](https://github.com/mastra-ai/mastra/commit/575e343900451021d96110916497d334af7bc252), [`0b2a3d1`](https://github.com/mastra-ai/mastra/commit/0b2a3d1783875c5b97b7b36ab3d03d7360e0dde7), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`3cc9d00`](https://github.com/mastra-ai/mastra/commit/3cc9d00b2b4333e0377a5e9df5eff92c17ce7630), [`cacb839`](https://github.com/mastra-ai/mastra/commit/cacb8392d9e74189b56d857290b0615f98a2683d), [`57de7d6`](https://github.com/mastra-ai/mastra/commit/57de7d644ba7146edb4e9e6111ec4fa98c3a59e9), [`c8e4cea`](https://github.com/mastra-ai/mastra/commit/c8e4ceac9a390d78c8327dff3cdb2861dd71957f), [`ed01e9a`](https://github.com/mastra-ai/mastra/commit/ed01e9a807514a904374bf687a7b8f18750f6f78), [`b47b26e`](https://github.com/mastra-ai/mastra/commit/b47b26e6fe95cb8a3482be2c5e52de157fe59d0b), [`0d37487`](https://github.com/mastra-ai/mastra/commit/0d37487d9f349388a3f1cef6a536cf9dcc4b6273), [`733a537`](https://github.com/mastra-ai/mastra/commit/733a537489a858b5880b2e98809334fba895a221), [`e8e299c`](https://github.com/mastra-ai/mastra/commit/e8e299cc6abdfc39947e2fec25803493015d3882), [`edfc548`](https://github.com/mastra-ai/mastra/commit/edfc548886bc7bae17b681f8b6b41a47eb32bcd2), [`b05f486`](https://github.com/mastra-ai/mastra/commit/b05f48612984d5fe2447ea2d6cdd5c604d285b97), [`a8a4871`](https://github.com/mastra-ai/mastra/commit/a8a4871215f51da95c47129602157ce5372f634a), [`eb9ecaa`](https://github.com/mastra-ai/mastra/commit/eb9ecaa89c36e889749e3b825cfc507ce7f7980b), [`4ff3ee2`](https://github.com/mastra-ai/mastra/commit/4ff3ee2bff7ed07528b4817f8f49639031c72a4d), [`9207dfa`](https://github.com/mastra-ai/mastra/commit/9207dfab8062e5fc68b751684797ff86fe0b4e70), [`5165cdc`](https://github.com/mastra-ai/mastra/commit/5165cdcdcf50e144bb8113278535196cc9b07065), [`e737014`](https://github.com/mastra-ai/mastra/commit/e737014e0fc7035759762bb5b48baef1d6c0f6a7), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`f591643`](https://github.com/mastra-ai/mastra/commit/f591643becdf0be9bddce6ba1748e64bc30d77f1), [`63796ba`](https://github.com/mastra-ai/mastra/commit/63796ba0fda60253be17535e68f6bbbf1e6ffa09), [`b1ad324`](https://github.com/mastra-ai/mastra/commit/b1ad324d657f3544b0701332aef7eb10e9a36258), [`61c566d`](https://github.com/mastra-ai/mastra/commit/61c566dd2f2cde2b23ed8f139924e530d4202214), [`c24754c`](https://github.com/mastra-ai/mastra/commit/c24754c1fb6fe144e5051e536e98c8a18b0214ac), [`12c61d2`](https://github.com/mastra-ai/mastra/commit/12c61d280c8cb208bc3c8dbcbe5dcc60cf9d1cd0), [`c46eb09`](https://github.com/mastra-ai/mastra/commit/c46eb09ce4987509af57a0ac582c61241a6dd2f1), [`9ee8120`](https://github.com/mastra-ai/mastra/commit/9ee8120ce17f76b9f617489e05a283353742690a), [`d975e92`](https://github.com/mastra-ai/mastra/commit/d975e924d4936f46c386bd3dee39c671720289f6), [`45dd6ee`](https://github.com/mastra-ai/mastra/commit/45dd6ee089bd7df0d0c98a10098e483fd388e04a), [`4e9a228`](https://github.com/mastra-ai/mastra/commit/4e9a2283d5fd6ed1b70a2751eb3dc2cbf82ada20), [`d6ce34a`](https://github.com/mastra-ai/mastra/commit/d6ce34aeceb06ddf3d595a1eed5cc74f481a46a1), [`f95f468`](https://github.com/mastra-ai/mastra/commit/f95f468cf1e7c2b924a13826494f98b8f2ccd581), [`30ed33e`](https://github.com/mastra-ai/mastra/commit/30ed33ee14084a26019aba15fceadda6d6ddefaf), [`04a815f`](https://github.com/mastra-ai/mastra/commit/04a815fc8971d29e97fcdcc5008a1eb472fc00ff), [`1cfa878`](https://github.com/mastra-ai/mastra/commit/1cfa8784d8da0dfaa0317e5048bc48b6084a5ea5), [`9a12ef3`](https://github.com/mastra-ai/mastra/commit/9a12ef3fccf3f4186db0f294f4ee1f02cf4d8db2), [`32d3583`](https://github.com/mastra-ai/mastra/commit/32d358332cb8ac2306b83b73cf3536e74dbd435e), [`7960688`](https://github.com/mastra-ai/mastra/commit/7960688828e04eaf3106e34f7758fa580257eef6), [`91ad69d`](https://github.com/mastra-ai/mastra/commit/91ad69d64994c89199b0c55399e64ed91c61df2f), [`8dc408d`](https://github.com/mastra-ai/mastra/commit/8dc408d34438f9e13297f792c11a5cfd6cf952e1), [`c92def1`](https://github.com/mastra-ai/mastra/commit/c92def10a13c822972c96f0a4ca6ffc1f4258aed), [`63041eb`](https://github.com/mastra-ai/mastra/commit/63041eb4c50b520a0a80e03d4cd6ea99f67715a0), [`c118318`](https://github.com/mastra-ai/mastra/commit/c1183181c9804303db4b511c2e2648f8b714712b), [`c5eaec5`](https://github.com/mastra-ai/mastra/commit/c5eaec5a860d80d0e3805e67db0414b87ac8cbed), [`fc07c64`](https://github.com/mastra-ai/mastra/commit/fc07c6465043e08e99193a6751a01c56ffc2e7a1), [`cced745`](https://github.com/mastra-ai/mastra/commit/cced745a056ec2225c5bc702e32d848847aa8b65), [`542dee2`](https://github.com/mastra-ai/mastra/commit/542dee254167f974ff8cbbbfc0ce10f9a2616a7b), [`3c19dce`](https://github.com/mastra-ai/mastra/commit/3c19dcef8e73062a80627a4927eae3ec11145afd), [`aca2869`](https://github.com/mastra-ai/mastra/commit/aca2869b2031982f3c4a2f52525c9be7cf123ef8), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`e6f8450`](https://github.com/mastra-ai/mastra/commit/e6f845074d478527026b18d85031b23353e1d0a4), [`895e9df`](https://github.com/mastra-ai/mastra/commit/895e9dfc17d6f34299eca64e317ded9e5f5e5ef8), [`e66b2ba`](https://github.com/mastra-ai/mastra/commit/e66b2ba100db63eaeab6e21e1ea34b113f2ec781), [`3e8727e`](https://github.com/mastra-ai/mastra/commit/3e8727e11ec1a5d733acedb5c872896394be18c1)]:
17
+ - @mastra/core@1.62.0
18
+
19
+ ## 0.2.1-alpha.0
20
+
21
+ ### Patch Changes
22
+
23
+ - Honor the sandbox runtime environment (`setEnv()`/`getEnv()` from `@mastra/core`) in every workspace sandbox provider. Environment variables set after construction now reach subsequent commands on all providers: ([#22250](https://github.com/mastra-ai/mastra/pull/22250))
24
+
25
+ - Process-manager-routed providers (E2B, Blaxel, Cloudflare, Daytona, Docker, Modal, Vercel microVM spawns) inherit the merge from the core spawn wrapper; their duplicated per-manager env plumbing is removed.
26
+ - Providers with their own exec transports (AgentCore, Apple Container, Railway, Vercel microVM and serverless `executeCommand`, Platform's private-network, WebSocket lease, and E2B lease paths) now merge `getEnv()` under per-call env.
27
+
28
+ Constructor `env` continues to behave as before: it seeds the sandbox runtime environment, and providers that bake env into the VM or container at creation time (Docker, Modal, Railway, Apple Container, Vercel, Platform) still do so. Per-call `env` on `executeCommand` still takes precedence for that command only.
29
+
30
+ Removed exported types (minor bump for these two packages): `BlaxelProcessManagerOptions` from `@mastra/blaxel` and `RailwayProcessManagerOptions` from `@mastra/railway`. Both existed only to pass `env` into a process manager constructed by hand; the core spawn wrapper now owns that merge, so the option and its type are gone.
31
+
32
+ - Updated dependencies [[`aa3a85d`](https://github.com/mastra-ai/mastra/commit/aa3a85daf094c683bb97efdf4b6a696d2e474af5), [`d29d06f`](https://github.com/mastra-ai/mastra/commit/d29d06fe00bbd35b4571150ea04c59d2ed783c71), [`e6516df`](https://github.com/mastra-ai/mastra/commit/e6516dfcdae4f4ac0e7971d84359a81385ee602f), [`0b2a3d1`](https://github.com/mastra-ai/mastra/commit/0b2a3d1783875c5b97b7b36ab3d03d7360e0dde7), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`57de7d6`](https://github.com/mastra-ai/mastra/commit/57de7d644ba7146edb4e9e6111ec4fa98c3a59e9), [`e8e299c`](https://github.com/mastra-ai/mastra/commit/e8e299cc6abdfc39947e2fec25803493015d3882), [`edfc548`](https://github.com/mastra-ai/mastra/commit/edfc548886bc7bae17b681f8b6b41a47eb32bcd2), [`a8a4871`](https://github.com/mastra-ai/mastra/commit/a8a4871215f51da95c47129602157ce5372f634a), [`5165cdc`](https://github.com/mastra-ai/mastra/commit/5165cdcdcf50e144bb8113278535196cc9b07065), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`9ee8120`](https://github.com/mastra-ai/mastra/commit/9ee8120ce17f76b9f617489e05a283353742690a), [`d975e92`](https://github.com/mastra-ai/mastra/commit/d975e924d4936f46c386bd3dee39c671720289f6), [`1cfa878`](https://github.com/mastra-ai/mastra/commit/1cfa8784d8da0dfaa0317e5048bc48b6084a5ea5), [`c118318`](https://github.com/mastra-ai/mastra/commit/c1183181c9804303db4b511c2e2648f8b714712b), [`fc07c64`](https://github.com/mastra-ai/mastra/commit/fc07c6465043e08e99193a6751a01c56ffc2e7a1), [`542dee2`](https://github.com/mastra-ai/mastra/commit/542dee254167f974ff8cbbbfc0ce10f9a2616a7b), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`895e9df`](https://github.com/mastra-ai/mastra/commit/895e9dfc17d6f34299eca64e317ded9e5f5e5ef8)]:
33
+ - @mastra/core@1.62.0-alpha.8
34
+
3
35
  ## 0.2.0
4
36
 
5
37
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -186,7 +186,6 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
186
186
  provider = "cloudflare-sandbox";
187
187
  status = "pending";
188
188
  client;
189
- env;
190
189
  workingDirectory;
191
190
  commandTimeout;
192
191
  instructions;
@@ -202,7 +201,6 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
202
201
  this.id = options.id ?? `cloudflare-sandbox-${(0, crypto.randomUUID)()}`;
203
202
  this.name = name;
204
203
  this.sandboxId = options.sandboxId;
205
- this.env = { ...options.env };
206
204
  this.workingDirectory = options.workingDirectory;
207
205
  this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;
208
206
  this.instructions = options.instructions;
@@ -244,7 +242,7 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
244
242
  let stderr = "";
245
243
  let exitCode = 1;
246
244
  const env = Object.fromEntries(Object.entries({
247
- ...this.env,
245
+ ...this.getEnv(),
248
246
  ...options?.env
249
247
  }).filter((entry) => entry[1] !== void 0));
250
248
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["posix","path","MastraSandbox"],"sources":["../src/bridge-client.ts","../src/sandbox.ts"],"sourcesContent":["export interface CloudflareSandboxBridgeClientOptions {\n baseUrl: string;\n apiToken?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/** Terminal and streaming events emitted by `POST /v1/sandbox/:id/exec`. */\nexport type CloudflareCommandEvent =\n | { type: 'stdout'; data: Uint8Array }\n | { type: 'stderr'; data: Uint8Array }\n | { type: 'exit'; exitCode: number }\n | { type: 'error'; message: string; code?: string };\n\nexport interface CloudflareExecRequest {\n /** Command and arguments. The bridge applies ANSI-C quoting to each element. */\n argv: string[];\n timeoutMs?: number;\n cwd?: string;\n}\n\nexport class CloudflareSandboxBridgeError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Cloudflare Sandbox Bridge request failed (${status}): ${body || 'empty response'}`);\n this.name = 'CloudflareSandboxBridgeError';\n this.status = status;\n this.body = body;\n }\n}\n\nfunction stripTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** Encodes an absolute sandbox path for the `/file/*` route, which omits the leading slash. */\nfunction encodeFilePath(absolutePath: string): string {\n let start = 0;\n while (start < absolutePath.length && absolutePath[start] === '/') start++;\n return absolutePath\n .slice(start)\n .split('/')\n .map(segment => encodeURIComponent(segment))\n .join('/');\n}\n\n/**\n * Client for the Cloudflare Sandbox Bridge Worker.\n *\n * @see https://developers.cloudflare.com/sandbox/bridge/http-api/\n */\nexport class CloudflareSandboxBridgeClient {\n readonly baseUrl: string;\n private readonly apiToken?: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: CloudflareSandboxBridgeClientOptions) {\n this.baseUrl = stripTrailingSlashes(options.baseUrl);\n this.apiToken = options.apiToken;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n }\n\n /** `POST /v1/sandbox` */\n async createSandbox(): Promise<string> {\n const created = await this.request<{ id: string }>('/v1/sandbox', { method: 'POST' });\n return created.id;\n }\n\n /** `GET /v1/sandbox/:id/running` */\n async isRunning(id: string): Promise<boolean> {\n const status = await this.request<{ running: boolean }>(`/v1/sandbox/${encodeURIComponent(id)}/running`, {});\n return status.running === true;\n }\n\n /** `DELETE /v1/sandbox/:id` */\n async deleteSandbox(id: string): Promise<void> {\n await this.request(`/v1/sandbox/${encodeURIComponent(id)}`, { method: 'DELETE' }, true);\n }\n\n /** `PUT /v1/sandbox/:id/file/*` — one file per request, raw bytes as the body. */\n async writeFile(id: string, absolutePath: string, content: Uint8Array | string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`,\n {\n method: 'PUT',\n body: content as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/exec` — streams SSE events until `exit` or `error`. */\n async exec(\n id: string,\n request: CloudflareExecRequest,\n options: {\n signal?: AbortSignal;\n onEvent: (event: CloudflareCommandEvent) => void;\n },\n ): Promise<void> {\n const response = await this.fetchImpl(`${this.baseUrl}/v1/sandbox/${encodeURIComponent(id)}/exec`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json', accept: 'text/event-stream' },\n body: JSON.stringify({\n argv: request.argv,\n ...(request.timeoutMs === undefined ? {} : { timeout_ms: request.timeoutMs }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n }),\n signal: options.signal,\n });\n\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (!response.body) {\n throw new Error('Cloudflare Sandbox Bridge returned an empty command stream');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done }).replace(/\\r\\n/g, '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n this.emitBlock(buffer.slice(0, boundary), options.onEvent);\n buffer = buffer.slice(boundary + 2);\n boundary = buffer.indexOf('\\n\\n');\n }\n if (done) break;\n }\n if (buffer.trim()) this.emitBlock(buffer, options.onEvent);\n }\n\n private emitBlock(block: string, onEvent: (event: CloudflareCommandEvent) => void): void {\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) eventName = line.slice(6).trim();\n else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));\n }\n const data = dataLines.join('\\n');\n if (!eventName || !data) return;\n\n switch (eventName) {\n case 'stdout':\n case 'stderr':\n onEvent({ type: eventName, data: base64ToBytes(data) });\n return;\n case 'exit': {\n const parsed = safeJsonParse(data);\n onEvent({ type: 'exit', exitCode: typeof parsed?.exit_code === 'number' ? parsed.exit_code : 0 });\n return;\n }\n case 'error': {\n const parsed = safeJsonParse(data);\n onEvent({\n type: 'error',\n message: typeof parsed?.error === 'string' ? parsed.error : data,\n code: typeof parsed?.code === 'string' ? parsed.code : undefined,\n });\n return;\n }\n default:\n return;\n }\n }\n\n private headers(): Record<string, string> {\n return this.apiToken ? { authorization: `Bearer ${this.apiToken}` } : {};\n }\n\n private async request<T>(path: string, init: RequestInit, allowEmpty = false): Promise<T> {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: { ...this.headers(), ...init.headers },\n });\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (allowEmpty || response.status === 204) return undefined as T;\n return response.json() as Promise<T>;\n }\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, 'base64'));\n}\n\nfunction safeJsonParse(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n} from '@mastra/core/workspace';\nimport { MastraSandbox } from '@mastra/core/workspace';\nimport { CloudflareSandboxBridgeClient, type CloudflareSandboxBridgeClientOptions } from './bridge-client';\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 300_000;\nconst WORKSPACE_ROOT = '/workspace';\n\ntype InstructionsOption = string | ((options: { defaultInstructions: string }) => string);\ntype BridgeClient = Pick<\n CloudflareSandboxBridgeClient,\n 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'exec'\n>;\n\nexport interface CloudflareSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** URL of a deployed Cloudflare Sandbox Bridge Worker. */\n baseUrl: string;\n /** Bearer token matching the Worker's `SANDBOX_API_KEY` secret, when authentication is enabled. */\n apiToken?: string;\n /** Stable Mastra identifier for this sandbox instance. */\n id?: string;\n /** Existing Cloudflare sandbox ID to reconnect to instead of creating a sandbox. */\n sandboxId?: string;\n /** Human-readable name shown in Mastra sandbox metadata. */\n name?: string;\n /** Environment variables applied to every command. */\n env?: Record<string, string>;\n /** Working directory applied to every command. Must be under /workspace. */\n workingDirectory?: string;\n /** Default command timeout in milliseconds. */\n commandTimeout?: number;\n /** Custom instructions returned by getInstructions(). */\n instructions?: InstructionsOption;\n /** Custom fetch implementation, primarily for advanced networking setup and tests. */\n fetch?: CloudflareSandboxBridgeClientOptions['fetch'];\n /** Preconfigured Bridge client, primarily for tests. */\n client?: BridgeClient;\n}\n\n/**\n * Builds the argv array sent to the bridge. The bridge applies ANSI-C quoting to\n * every element, so no local escaping is needed. Environment variables are applied\n * with `env`, which keeps each assignment a separate argv element.\n */\nfunction buildArgv(command: string, args: string[] | undefined, env: Record<string, string>): string[] {\n const assignments = Object.entries(env).map(([key, value]) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n return `${key}=${value}`;\n });\n const invocation = [command, ...(args ?? [])];\n return assignments.length ? ['env', ...assignments, ...invocation] : invocation;\n}\n\n/** Resolves a path inside /workspace, rejecting anything that escapes the workspace root. */\nfunction resolveWorkspacePath(path: string): string {\n const resolved = posix.resolve(WORKSPACE_ROOT, path);\n if (resolved !== WORKSPACE_ROOT && !resolved.startsWith(`${WORKSPACE_ROOT}/`)) {\n throw new Error(`Cloudflare Sandbox files must be written under ${WORKSPACE_ROOT}: ${path}`);\n }\n return resolved;\n}\n\nexport class CloudflareSandbox extends MastraSandbox {\n readonly id: string;\n readonly name: string;\n readonly provider = 'cloudflare-sandbox';\n status: ProviderStatus = 'pending';\n\n private readonly client: BridgeClient;\n private readonly env: Record<string, string>;\n private readonly workingDirectory?: string;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n\n constructor(options: CloudflareSandboxOptions) {\n const name = options.name ?? 'Cloudflare Sandbox';\n super({ ...options, name });\n this.id = options.id ?? `cloudflare-sandbox-${randomUUID()}`;\n this.name = name;\n this.sandboxId = options.sandboxId;\n this.env = { ...options.env };\n this.workingDirectory = options.workingDirectory;\n this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;\n this.instructions = options.instructions;\n this.client =\n options.client ??\n new CloudflareSandboxBridgeClient({ baseUrl: options.baseUrl, apiToken: options.apiToken, fetch: options.fetch });\n }\n\n async start(): Promise<void> {\n if (this.sandboxId) {\n // The bridge boots the container on demand, so a stopped container is not fatal.\n const running = await this.client.isRunning(this.sandboxId);\n if (!running) {\n this.logger?.debug(`Cloudflare sandbox ${this.sandboxId} is not running yet; it starts on first use`);\n }\n return;\n }\n this.sandboxId = await this.client.createSandbox();\n this.createdAt = new Date();\n }\n\n async stop(): Promise<void> {\n // The bridge exposes create/delete but no suspend operation. Stop detaches this\n // Mastra lifecycle while preserving the remote sandbox for later reconnection.\n }\n\n async destroy(): Promise<void> {\n if (!this.sandboxId) return;\n await this.client.deleteSandbox(this.sandboxId);\n this.sandboxId = undefined;\n }\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n const sandboxId = this.requireSandboxId();\n\n const startedAt = Date.now();\n const timeout = options?.timeout ?? this.commandTimeout;\n if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError('Command timeout must be positive');\n\n const controller = new AbortController();\n let didTimeout = false;\n const timer = setTimeout(() => {\n didTimeout = true;\n controller.abort();\n }, timeout);\n const signal = options?.abortSignal ? AbortSignal.any([controller.signal, options.abortSignal]) : controller.signal;\n\n // stdout and stderr are separate byte streams, so each needs its own streaming decoder.\n const stdoutDecoder = new TextDecoder();\n const stderrDecoder = new TextDecoder();\n let stdout = '';\n let stderr = '';\n let exitCode = 1;\n\n const env = Object.fromEntries(\n Object.entries({ ...this.env, ...options?.env }).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\n try {\n await this.client.exec(\n sandboxId,\n {\n argv: buildArgv(command, args, env),\n timeoutMs: timeout,\n cwd: options?.cwd ?? this.workingDirectory,\n },\n {\n signal,\n onEvent: event => {\n switch (event.type) {\n case 'stdout': {\n const chunk = stdoutDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stdout += chunk;\n options?.onStdout?.(chunk);\n return;\n }\n case 'stderr': {\n const chunk = stderrDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stderr += chunk;\n options?.onStderr?.(chunk);\n return;\n }\n case 'exit':\n exitCode = event.exitCode;\n return;\n case 'error':\n stderr += event.message;\n options?.onStderr?.(event.message);\n return;\n }\n },\n },\n );\n } catch (error) {\n if (!signal.aborted) throw error;\n } finally {\n clearTimeout(timer);\n }\n\n // Flush each decoder so a trailing truncated multi-byte sequence isn't dropped.\n const stdoutTail = stdoutDecoder.decode();\n if (stdoutTail) {\n stdout += stdoutTail;\n options?.onStdout?.(stdoutTail);\n }\n const stderrTail = stderrDecoder.decode();\n if (stderrTail) {\n stderr += stderrTail;\n options?.onStderr?.(stderrTail);\n }\n\n this.lastUsedAt = new Date();\n return {\n command,\n args,\n success: exitCode === 0 && !signal.aborted,\n exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startedAt,\n timedOut: didTimeout,\n killed: signal.aborted && !didTimeout,\n };\n }\n\n async writeFiles(files: SandboxFileInput[]): Promise<void> {\n const sandboxId = this.requireSandboxId();\n // The bridge writes one file per request.\n for (const file of files) {\n await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);\n }\n this.lastUsedAt = new Date();\n }\n\n getInfo(): SandboxInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this.createdAt,\n lastUsedAt: this.lastUsedAt,\n metadata: {\n sandboxId: this.sandboxId,\n bridgeBaseUrl: this.client instanceof CloudflareSandboxBridgeClient ? this.client.baseUrl : undefined,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions =\n 'Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n private requireSandboxId(): string {\n if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);\n return this.sandboxId;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,+BAAb,cAAkD,MAAM;CACtD;CACA;CAEA,YAAY,QAAgB,MAAc;EACxC,MAAM,6CAA6C,OAAO,KAAK,QAAQ,kBAAkB;EACzF,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;AAEA,SAAS,qBAAqB,KAAqB;CACjD,IAAI,MAAM,IAAI;CACd,OAAO,MAAM,KAAK,IAAI,MAAM,OAAO,KAAK;CACxC,OAAO,IAAI,MAAM,GAAG,GAAG;AACzB;;AAGA,SAAS,e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,KAAK,iBAAiB,aAChC,KAAK,aAAa,EAAE,oBAAoB,CAAC,IACxC,KAAK,gBAAgB;CAC5B;CAEA,mBAAmC;EACjC,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,sBAAsB,KAAK,GAAG,sBAAsB;EACzF,OAAO,KAAK;CACd;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["posix","path","MastraSandbox"],"sources":["../src/bridge-client.ts","../src/sandbox.ts"],"sourcesContent":["export interface CloudflareSandboxBridgeClientOptions {\n baseUrl: string;\n apiToken?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/** Terminal and streaming events emitted by `POST /v1/sandbox/:id/exec`. */\nexport type CloudflareCommandEvent =\n | { type: 'stdout'; data: Uint8Array }\n | { type: 'stderr'; data: Uint8Array }\n | { type: 'exit'; exitCode: number }\n | { type: 'error'; message: string; code?: string };\n\nexport interface CloudflareExecRequest {\n /** Command and arguments. The bridge applies ANSI-C quoting to each element. */\n argv: string[];\n timeoutMs?: number;\n cwd?: string;\n}\n\nexport class CloudflareSandboxBridgeError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Cloudflare Sandbox Bridge request failed (${status}): ${body || 'empty response'}`);\n this.name = 'CloudflareSandboxBridgeError';\n this.status = status;\n this.body = body;\n }\n}\n\nfunction stripTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** Encodes an absolute sandbox path for the `/file/*` route, which omits the leading slash. */\nfunction encodeFilePath(absolutePath: string): string {\n let start = 0;\n while (start < absolutePath.length && absolutePath[start] === '/') start++;\n return absolutePath\n .slice(start)\n .split('/')\n .map(segment => encodeURIComponent(segment))\n .join('/');\n}\n\n/**\n * Client for the Cloudflare Sandbox Bridge Worker.\n *\n * @see https://developers.cloudflare.com/sandbox/bridge/http-api/\n */\nexport class CloudflareSandboxBridgeClient {\n readonly baseUrl: string;\n private readonly apiToken?: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: CloudflareSandboxBridgeClientOptions) {\n this.baseUrl = stripTrailingSlashes(options.baseUrl);\n this.apiToken = options.apiToken;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n }\n\n /** `POST /v1/sandbox` */\n async createSandbox(): Promise<string> {\n const created = await this.request<{ id: string }>('/v1/sandbox', { method: 'POST' });\n return created.id;\n }\n\n /** `GET /v1/sandbox/:id/running` */\n async isRunning(id: string): Promise<boolean> {\n const status = await this.request<{ running: boolean }>(`/v1/sandbox/${encodeURIComponent(id)}/running`, {});\n return status.running === true;\n }\n\n /** `DELETE /v1/sandbox/:id` */\n async deleteSandbox(id: string): Promise<void> {\n await this.request(`/v1/sandbox/${encodeURIComponent(id)}`, { method: 'DELETE' }, true);\n }\n\n /** `PUT /v1/sandbox/:id/file/*` — one file per request, raw bytes as the body. */\n async writeFile(id: string, absolutePath: string, content: Uint8Array | string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`,\n {\n method: 'PUT',\n body: content as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/exec` — streams SSE events until `exit` or `error`. */\n async exec(\n id: string,\n request: CloudflareExecRequest,\n options: {\n signal?: AbortSignal;\n onEvent: (event: CloudflareCommandEvent) => void;\n },\n ): Promise<void> {\n const response = await this.fetchImpl(`${this.baseUrl}/v1/sandbox/${encodeURIComponent(id)}/exec`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json', accept: 'text/event-stream' },\n body: JSON.stringify({\n argv: request.argv,\n ...(request.timeoutMs === undefined ? {} : { timeout_ms: request.timeoutMs }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n }),\n signal: options.signal,\n });\n\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (!response.body) {\n throw new Error('Cloudflare Sandbox Bridge returned an empty command stream');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done }).replace(/\\r\\n/g, '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n this.emitBlock(buffer.slice(0, boundary), options.onEvent);\n buffer = buffer.slice(boundary + 2);\n boundary = buffer.indexOf('\\n\\n');\n }\n if (done) break;\n }\n if (buffer.trim()) this.emitBlock(buffer, options.onEvent);\n }\n\n private emitBlock(block: string, onEvent: (event: CloudflareCommandEvent) => void): void {\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) eventName = line.slice(6).trim();\n else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));\n }\n const data = dataLines.join('\\n');\n if (!eventName || !data) return;\n\n switch (eventName) {\n case 'stdout':\n case 'stderr':\n onEvent({ type: eventName, data: base64ToBytes(data) });\n return;\n case 'exit': {\n const parsed = safeJsonParse(data);\n onEvent({ type: 'exit', exitCode: typeof parsed?.exit_code === 'number' ? parsed.exit_code : 0 });\n return;\n }\n case 'error': {\n const parsed = safeJsonParse(data);\n onEvent({\n type: 'error',\n message: typeof parsed?.error === 'string' ? parsed.error : data,\n code: typeof parsed?.code === 'string' ? parsed.code : undefined,\n });\n return;\n }\n default:\n return;\n }\n }\n\n private headers(): Record<string, string> {\n return this.apiToken ? { authorization: `Bearer ${this.apiToken}` } : {};\n }\n\n private async request<T>(path: string, init: RequestInit, allowEmpty = false): Promise<T> {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: { ...this.headers(), ...init.headers },\n });\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (allowEmpty || response.status === 204) return undefined as T;\n return response.json() as Promise<T>;\n }\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, 'base64'));\n}\n\nfunction safeJsonParse(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n} from '@mastra/core/workspace';\nimport { MastraSandbox } from '@mastra/core/workspace';\nimport { CloudflareSandboxBridgeClient, type CloudflareSandboxBridgeClientOptions } from './bridge-client';\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 300_000;\nconst WORKSPACE_ROOT = '/workspace';\n\ntype InstructionsOption = string | ((options: { defaultInstructions: string }) => string);\ntype BridgeClient = Pick<\n CloudflareSandboxBridgeClient,\n 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'exec'\n>;\n\nexport interface CloudflareSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** URL of a deployed Cloudflare Sandbox Bridge Worker. */\n baseUrl: string;\n /** Bearer token matching the Worker's `SANDBOX_API_KEY` secret, when authentication is enabled. */\n apiToken?: string;\n /** Stable Mastra identifier for this sandbox instance. */\n id?: string;\n /** Existing Cloudflare sandbox ID to reconnect to instead of creating a sandbox. */\n sandboxId?: string;\n /** Human-readable name shown in Mastra sandbox metadata. */\n name?: string;\n /** Environment variables applied to every command. */\n env?: Record<string, string>;\n /** Working directory applied to every command. Must be under /workspace. */\n workingDirectory?: string;\n /** Default command timeout in milliseconds. */\n commandTimeout?: number;\n /** Custom instructions returned by getInstructions(). */\n instructions?: InstructionsOption;\n /** Custom fetch implementation, primarily for advanced networking setup and tests. */\n fetch?: CloudflareSandboxBridgeClientOptions['fetch'];\n /** Preconfigured Bridge client, primarily for tests. */\n client?: BridgeClient;\n}\n\n/**\n * Builds the argv array sent to the bridge. The bridge applies ANSI-C quoting to\n * every element, so no local escaping is needed. Environment variables are applied\n * with `env`, which keeps each assignment a separate argv element.\n */\nfunction buildArgv(command: string, args: string[] | undefined, env: Record<string, string>): string[] {\n const assignments = Object.entries(env).map(([key, value]) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n return `${key}=${value}`;\n });\n const invocation = [command, ...(args ?? [])];\n return assignments.length ? ['env', ...assignments, ...invocation] : invocation;\n}\n\n/** Resolves a path inside /workspace, rejecting anything that escapes the workspace root. */\nfunction resolveWorkspacePath(path: string): string {\n const resolved = posix.resolve(WORKSPACE_ROOT, path);\n if (resolved !== WORKSPACE_ROOT && !resolved.startsWith(`${WORKSPACE_ROOT}/`)) {\n throw new Error(`Cloudflare Sandbox files must be written under ${WORKSPACE_ROOT}: ${path}`);\n }\n return resolved;\n}\n\nexport class CloudflareSandbox extends MastraSandbox {\n readonly id: string;\n readonly name: string;\n readonly provider = 'cloudflare-sandbox';\n status: ProviderStatus = 'pending';\n\n private readonly client: BridgeClient;\n private readonly workingDirectory?: string;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n\n constructor(options: CloudflareSandboxOptions) {\n const name = options.name ?? 'Cloudflare Sandbox';\n super({ ...options, name });\n this.id = options.id ?? `cloudflare-sandbox-${randomUUID()}`;\n this.name = name;\n this.sandboxId = options.sandboxId;\n this.workingDirectory = options.workingDirectory;\n this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;\n this.instructions = options.instructions;\n this.client =\n options.client ??\n new CloudflareSandboxBridgeClient({ baseUrl: options.baseUrl, apiToken: options.apiToken, fetch: options.fetch });\n }\n\n async start(): Promise<void> {\n if (this.sandboxId) {\n // The bridge boots the container on demand, so a stopped container is not fatal.\n const running = await this.client.isRunning(this.sandboxId);\n if (!running) {\n this.logger?.debug(`Cloudflare sandbox ${this.sandboxId} is not running yet; it starts on first use`);\n }\n return;\n }\n this.sandboxId = await this.client.createSandbox();\n this.createdAt = new Date();\n }\n\n async stop(): Promise<void> {\n // The bridge exposes create/delete but no suspend operation. Stop detaches this\n // Mastra lifecycle while preserving the remote sandbox for later reconnection.\n }\n\n async destroy(): Promise<void> {\n if (!this.sandboxId) return;\n await this.client.deleteSandbox(this.sandboxId);\n this.sandboxId = undefined;\n }\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n const sandboxId = this.requireSandboxId();\n\n const startedAt = Date.now();\n const timeout = options?.timeout ?? this.commandTimeout;\n if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError('Command timeout must be positive');\n\n const controller = new AbortController();\n let didTimeout = false;\n const timer = setTimeout(() => {\n didTimeout = true;\n controller.abort();\n }, timeout);\n const signal = options?.abortSignal ? AbortSignal.any([controller.signal, options.abortSignal]) : controller.signal;\n\n // stdout and stderr are separate byte streams, so each needs its own streaming decoder.\n const stdoutDecoder = new TextDecoder();\n const stderrDecoder = new TextDecoder();\n let stdout = '';\n let stderr = '';\n let exitCode = 1;\n\n const env = Object.fromEntries(\n Object.entries({ ...this.getEnv(), ...options?.env }).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\n try {\n await this.client.exec(\n sandboxId,\n {\n argv: buildArgv(command, args, env),\n timeoutMs: timeout,\n cwd: options?.cwd ?? this.workingDirectory,\n },\n {\n signal,\n onEvent: event => {\n switch (event.type) {\n case 'stdout': {\n const chunk = stdoutDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stdout += chunk;\n options?.onStdout?.(chunk);\n return;\n }\n case 'stderr': {\n const chunk = stderrDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stderr += chunk;\n options?.onStderr?.(chunk);\n return;\n }\n case 'exit':\n exitCode = event.exitCode;\n return;\n case 'error':\n stderr += event.message;\n options?.onStderr?.(event.message);\n return;\n }\n },\n },\n );\n } catch (error) {\n if (!signal.aborted) throw error;\n } finally {\n clearTimeout(timer);\n }\n\n // Flush each decoder so a trailing truncated multi-byte sequence isn't dropped.\n const stdoutTail = stdoutDecoder.decode();\n if (stdoutTail) {\n stdout += stdoutTail;\n options?.onStdout?.(stdoutTail);\n }\n const stderrTail = stderrDecoder.decode();\n if (stderrTail) {\n stderr += stderrTail;\n options?.onStderr?.(stderrTail);\n }\n\n this.lastUsedAt = new Date();\n return {\n command,\n args,\n success: exitCode === 0 && !signal.aborted,\n exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startedAt,\n timedOut: didTimeout,\n killed: signal.aborted && !didTimeout,\n };\n }\n\n async writeFiles(files: SandboxFileInput[]): Promise<void> {\n const sandboxId = this.requireSandboxId();\n // The bridge writes one file per request.\n for (const file of files) {\n await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);\n }\n this.lastUsedAt = new Date();\n }\n\n getInfo(): SandboxInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this.createdAt,\n lastUsedAt: this.lastUsedAt,\n metadata: {\n sandboxId: this.sandboxId,\n bridgeBaseUrl: this.client instanceof CloudflareSandboxBridgeClient ? this.client.baseUrl : undefined,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions =\n 'Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n private requireSandboxId(): string {\n if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);\n return this.sandboxId;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,+BAAb,cAAkD,MAAM;CACtD;CACA;CAEA,YAAY,QAAgB,MAAc;EACxC,MAAM,6CAA6C,OAAO,KAAK,QAAQ,kBAAkB;EACzF,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;AAEA,SAAS,qBAAqB,KAAqB;CACjD,IAAI,MAAM,IAAI;CACd,OAAO,MAAM,KAAK,IAAI,MAAM,OAAO,KAAK;CACxC,OA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AAO,KAAK,iBAAiB,aAChC,KAAK,aAAa,EAAE,oBAAoB,CAAC,IACxC,KAAK,gBAAgB;CAC5B;CAEA,mBAAmC;EACjC,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,sBAAsB,KAAK,GAAG,sBAAsB;EACzF,OAAO,KAAK;CACd;AACF"}
package/dist/index.js CHANGED
@@ -185,7 +185,6 @@ var CloudflareSandbox = class extends MastraSandbox {
185
185
  provider = "cloudflare-sandbox";
186
186
  status = "pending";
187
187
  client;
188
- env;
189
188
  workingDirectory;
190
189
  commandTimeout;
191
190
  instructions;
@@ -201,7 +200,6 @@ var CloudflareSandbox = class extends MastraSandbox {
201
200
  this.id = options.id ?? `cloudflare-sandbox-${randomUUID()}`;
202
201
  this.name = name;
203
202
  this.sandboxId = options.sandboxId;
204
- this.env = { ...options.env };
205
203
  this.workingDirectory = options.workingDirectory;
206
204
  this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;
207
205
  this.instructions = options.instructions;
@@ -243,7 +241,7 @@ var CloudflareSandbox = class extends MastraSandbox {
243
241
  let stderr = "";
244
242
  let exitCode = 1;
245
243
  const env = Object.fromEntries(Object.entries({
246
- ...this.env,
244
+ ...this.getEnv(),
247
245
  ...options?.env
248
246
  }).filter((entry) => entry[1] !== void 0));
249
247
  try {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/bridge-client.ts","../src/sandbox.ts"],"sourcesContent":["export interface CloudflareSandboxBridgeClientOptions {\n baseUrl: string;\n apiToken?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/** Terminal and streaming events emitted by `POST /v1/sandbox/:id/exec`. */\nexport type CloudflareCommandEvent =\n | { type: 'stdout'; data: Uint8Array }\n | { type: 'stderr'; data: Uint8Array }\n | { type: 'exit'; exitCode: number }\n | { type: 'error'; message: string; code?: string };\n\nexport interface CloudflareExecRequest {\n /** Command and arguments. The bridge applies ANSI-C quoting to each element. */\n argv: string[];\n timeoutMs?: number;\n cwd?: string;\n}\n\nexport class CloudflareSandboxBridgeError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Cloudflare Sandbox Bridge request failed (${status}): ${body || 'empty response'}`);\n this.name = 'CloudflareSandboxBridgeError';\n this.status = status;\n this.body = body;\n }\n}\n\nfunction stripTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** Encodes an absolute sandbox path for the `/file/*` route, which omits the leading slash. */\nfunction encodeFilePath(absolutePath: string): string {\n let start = 0;\n while (start < absolutePath.length && absolutePath[start] === '/') start++;\n return absolutePath\n .slice(start)\n .split('/')\n .map(segment => encodeURIComponent(segment))\n .join('/');\n}\n\n/**\n * Client for the Cloudflare Sandbox Bridge Worker.\n *\n * @see https://developers.cloudflare.com/sandbox/bridge/http-api/\n */\nexport class CloudflareSandboxBridgeClient {\n readonly baseUrl: string;\n private readonly apiToken?: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: CloudflareSandboxBridgeClientOptions) {\n this.baseUrl = stripTrailingSlashes(options.baseUrl);\n this.apiToken = options.apiToken;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n }\n\n /** `POST /v1/sandbox` */\n async createSandbox(): Promise<string> {\n const created = await this.request<{ id: string }>('/v1/sandbox', { method: 'POST' });\n return created.id;\n }\n\n /** `GET /v1/sandbox/:id/running` */\n async isRunning(id: string): Promise<boolean> {\n const status = await this.request<{ running: boolean }>(`/v1/sandbox/${encodeURIComponent(id)}/running`, {});\n return status.running === true;\n }\n\n /** `DELETE /v1/sandbox/:id` */\n async deleteSandbox(id: string): Promise<void> {\n await this.request(`/v1/sandbox/${encodeURIComponent(id)}`, { method: 'DELETE' }, true);\n }\n\n /** `PUT /v1/sandbox/:id/file/*` — one file per request, raw bytes as the body. */\n async writeFile(id: string, absolutePath: string, content: Uint8Array | string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`,\n {\n method: 'PUT',\n body: content as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/exec` — streams SSE events until `exit` or `error`. */\n async exec(\n id: string,\n request: CloudflareExecRequest,\n options: {\n signal?: AbortSignal;\n onEvent: (event: CloudflareCommandEvent) => void;\n },\n ): Promise<void> {\n const response = await this.fetchImpl(`${this.baseUrl}/v1/sandbox/${encodeURIComponent(id)}/exec`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json', accept: 'text/event-stream' },\n body: JSON.stringify({\n argv: request.argv,\n ...(request.timeoutMs === undefined ? {} : { timeout_ms: request.timeoutMs }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n }),\n signal: options.signal,\n });\n\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (!response.body) {\n throw new Error('Cloudflare Sandbox Bridge returned an empty command stream');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done }).replace(/\\r\\n/g, '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n this.emitBlock(buffer.slice(0, boundary), options.onEvent);\n buffer = buffer.slice(boundary + 2);\n boundary = buffer.indexOf('\\n\\n');\n }\n if (done) break;\n }\n if (buffer.trim()) this.emitBlock(buffer, options.onEvent);\n }\n\n private emitBlock(block: string, onEvent: (event: CloudflareCommandEvent) => void): void {\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) eventName = line.slice(6).trim();\n else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));\n }\n const data = dataLines.join('\\n');\n if (!eventName || !data) return;\n\n switch (eventName) {\n case 'stdout':\n case 'stderr':\n onEvent({ type: eventName, data: base64ToBytes(data) });\n return;\n case 'exit': {\n const parsed = safeJsonParse(data);\n onEvent({ type: 'exit', exitCode: typeof parsed?.exit_code === 'number' ? parsed.exit_code : 0 });\n return;\n }\n case 'error': {\n const parsed = safeJsonParse(data);\n onEvent({\n type: 'error',\n message: typeof parsed?.error === 'string' ? parsed.error : data,\n code: typeof parsed?.code === 'string' ? parsed.code : undefined,\n });\n return;\n }\n default:\n return;\n }\n }\n\n private headers(): Record<string, string> {\n return this.apiToken ? { authorization: `Bearer ${this.apiToken}` } : {};\n }\n\n private async request<T>(path: string, init: RequestInit, allowEmpty = false): Promise<T> {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: { ...this.headers(), ...init.headers },\n });\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (allowEmpty || response.status === 204) return undefined as T;\n return response.json() as Promise<T>;\n }\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, 'base64'));\n}\n\nfunction safeJsonParse(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n} from '@mastra/core/workspace';\nimport { MastraSandbox } from '@mastra/core/workspace';\nimport { CloudflareSandboxBridgeClient, type CloudflareSandboxBridgeClientOptions } from './bridge-client';\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 300_000;\nconst WORKSPACE_ROOT = '/workspace';\n\ntype InstructionsOption = string | ((options: { defaultInstructions: string }) => string);\ntype BridgeClient = Pick<\n CloudflareSandboxBridgeClient,\n 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'exec'\n>;\n\nexport interface CloudflareSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** URL of a deployed Cloudflare Sandbox Bridge Worker. */\n baseUrl: string;\n /** Bearer token matching the Worker's `SANDBOX_API_KEY` secret, when authentication is enabled. */\n apiToken?: string;\n /** Stable Mastra identifier for this sandbox instance. */\n id?: string;\n /** Existing Cloudflare sandbox ID to reconnect to instead of creating a sandbox. */\n sandboxId?: string;\n /** Human-readable name shown in Mastra sandbox metadata. */\n name?: string;\n /** Environment variables applied to every command. */\n env?: Record<string, string>;\n /** Working directory applied to every command. Must be under /workspace. */\n workingDirectory?: string;\n /** Default command timeout in milliseconds. */\n commandTimeout?: number;\n /** Custom instructions returned by getInstructions(). */\n instructions?: InstructionsOption;\n /** Custom fetch implementation, primarily for advanced networking setup and tests. */\n fetch?: CloudflareSandboxBridgeClientOptions['fetch'];\n /** Preconfigured Bridge client, primarily for tests. */\n client?: BridgeClient;\n}\n\n/**\n * Builds the argv array sent to the bridge. The bridge applies ANSI-C quoting to\n * every element, so no local escaping is needed. Environment variables are applied\n * with `env`, which keeps each assignment a separate argv element.\n */\nfunction buildArgv(command: string, args: string[] | undefined, env: Record<string, string>): string[] {\n const assignments = Object.entries(env).map(([key, value]) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n return `${key}=${value}`;\n });\n const invocation = [command, ...(args ?? [])];\n return assignments.length ? ['env', ...assignments, ...invocation] : invocation;\n}\n\n/** Resolves a path inside /workspace, rejecting anything that escapes the workspace root. */\nfunction resolveWorkspacePath(path: string): string {\n const resolved = posix.resolve(WORKSPACE_ROOT, path);\n if (resolved !== WORKSPACE_ROOT && !resolved.startsWith(`${WORKSPACE_ROOT}/`)) {\n throw new Error(`Cloudflare Sandbox files must be written under ${WORKSPACE_ROOT}: ${path}`);\n }\n return resolved;\n}\n\nexport class CloudflareSandbox extends MastraSandbox {\n readonly id: string;\n readonly name: string;\n readonly provider = 'cloudflare-sandbox';\n status: ProviderStatus = 'pending';\n\n private readonly client: BridgeClient;\n private readonly env: Record<string, string>;\n private readonly workingDirectory?: string;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n\n constructor(options: CloudflareSandboxOptions) {\n const name = options.name ?? 'Cloudflare Sandbox';\n super({ ...options, name });\n this.id = options.id ?? `cloudflare-sandbox-${randomUUID()}`;\n this.name = name;\n this.sandboxId = options.sandboxId;\n this.env = { ...options.env };\n this.workingDirectory = options.workingDirectory;\n this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;\n this.instructions = options.instructions;\n this.client =\n options.client ??\n new CloudflareSandboxBridgeClient({ baseUrl: options.baseUrl, apiToken: options.apiToken, fetch: options.fetch });\n }\n\n async start(): Promise<void> {\n if (this.sandboxId) {\n // The bridge boots the container on demand, so a stopped container is not fatal.\n const running = await this.client.isRunning(this.sandboxId);\n if (!running) {\n this.logger?.debug(`Cloudflare sandbox ${this.sandboxId} is not running yet; it starts on first use`);\n }\n return;\n }\n this.sandboxId = await this.client.createSandbox();\n this.createdAt = new Date();\n }\n\n async stop(): Promise<void> {\n // The bridge exposes create/delete but no suspend operation. Stop detaches this\n // Mastra lifecycle while preserving the remote sandbox for later reconnection.\n }\n\n async destroy(): Promise<void> {\n if (!this.sandboxId) return;\n await this.client.deleteSandbox(this.sandboxId);\n this.sandboxId = undefined;\n }\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n const sandboxId = this.requireSandboxId();\n\n const startedAt = Date.now();\n const timeout = options?.timeout ?? this.commandTimeout;\n if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError('Command timeout must be positive');\n\n const controller = new AbortController();\n let didTimeout = false;\n const timer = setTimeout(() => {\n didTimeout = true;\n controller.abort();\n }, timeout);\n const signal = options?.abortSignal ? AbortSignal.any([controller.signal, options.abortSignal]) : controller.signal;\n\n // stdout and stderr are separate byte streams, so each needs its own streaming decoder.\n const stdoutDecoder = new TextDecoder();\n const stderrDecoder = new TextDecoder();\n let stdout = '';\n let stderr = '';\n let exitCode = 1;\n\n const env = Object.fromEntries(\n Object.entries({ ...this.env, ...options?.env }).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\n try {\n await this.client.exec(\n sandboxId,\n {\n argv: buildArgv(command, args, env),\n timeoutMs: timeout,\n cwd: options?.cwd ?? this.workingDirectory,\n },\n {\n signal,\n onEvent: event => {\n switch (event.type) {\n case 'stdout': {\n const chunk = stdoutDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stdout += chunk;\n options?.onStdout?.(chunk);\n return;\n }\n case 'stderr': {\n const chunk = stderrDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stderr += chunk;\n options?.onStderr?.(chunk);\n return;\n }\n case 'exit':\n exitCode = event.exitCode;\n return;\n case 'error':\n stderr += event.message;\n options?.onStderr?.(event.message);\n return;\n }\n },\n },\n );\n } catch (error) {\n if (!signal.aborted) throw error;\n } finally {\n clearTimeout(timer);\n }\n\n // Flush each decoder so a trailing truncated multi-byte sequence isn't dropped.\n const stdoutTail = stdoutDecoder.decode();\n if (stdoutTail) {\n stdout += stdoutTail;\n options?.onStdout?.(stdoutTail);\n }\n const stderrTail = stderrDecoder.decode();\n if (stderrTail) {\n stderr += stderrTail;\n options?.onStderr?.(stderrTail);\n }\n\n this.lastUsedAt = new Date();\n return {\n command,\n args,\n success: exitCode === 0 && !signal.aborted,\n exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startedAt,\n timedOut: didTimeout,\n killed: signal.aborted && !didTimeout,\n };\n }\n\n async writeFiles(files: SandboxFileInput[]): Promise<void> {\n const sandboxId = this.requireSandboxId();\n // The bridge writes one file per request.\n for (const file of files) {\n await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);\n }\n this.lastUsedAt = new Date();\n }\n\n getInfo(): SandboxInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this.createdAt,\n lastUsedAt: this.lastUsedAt,\n metadata: {\n sandboxId: this.sandboxId,\n bridgeBaseUrl: this.client instanceof CloudflareSandboxBridgeClient ? this.client.baseUrl : undefined,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions =\n 'Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n private requireSandboxId(): string {\n if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);\n return this.sandboxId;\n }\n}\n"],"mappings":";;;;AAoBA,IAAa,+BAAb,cAAkD,MAAM;CACtD;CACA;CAEA,YAAY,QAAgB,MAAc;EACxC,MAAM,6CAA6C,OAAO,KAAK,QAAQ,kBAAkB;EACzF,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;AAEA,SAAS,qBAAqB,KAAqB;CACjD,IAAI,MAAM,IAAI;CACd,OAAO,MAAM,KAAK,IAAI,MAAM,OAAO,KAAK;CACxC,OAAO,IAAI,MAAM,GAAG,GAAG;AACzB;;AAGA,SAAS,eAAe,cAA8B;CACpD,IAAI,QAAQ;CACZ,OAAO,QAAQ,aAAa,UAAU,aAAa,WAAW,KAAK;CACnE,OAAO,aACJ,MAAM,KAAK,CAAC,CACZ,MAAM,GAAG,CAAC,CACV,KAAI,YAAW,mBAAmB,OAAO,CAAC,CAAC,CAC3C,KAAK,GAAG;AACb;;;;;;AAOA,IAAa,gCAAb,MAA2C;CACzC;CACA;CACA;CAEA,YAAY,SAA+C;EACzD,KAAK,UAAU,qBAAqB,QAAQ,OAAO;EACnD,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAAQ,SAAS,WAAW;CAC/C;;CAGA,MAAM,gBAAiC;EAErC,QAAO,MADe,KAAK,QAAwB,eAAe,EAAE,QAAQ,OAAO,CAAC,EAAA,CACrE;CACjB;;CAGA,MAAM,UAAU,IAA8B;EAE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EAChC;EAEA,KAAK,6BAAa,IAAI,KAAK;EAC3B,OAAO;GACL;GACA;GACA,SAAS,aAAa,KAAK,CAAC,OAAO;GACnC;GACA;GACA;GACA,iBAAiB,KAAK,IAAI,IAAI;GAC9B,UAAU;GACV,QAAQ,OAAO,WAAW,CAAC;EAC7B;CACF;CAEA,MAAM,WAAW,OAA0C;EACzD,MAAM,YAAY,KAAK,iBAAiB;EAExC,KAAK,MAAM,QAAQ,OACjB,MAAM,KAAK,OAAO,UAAU,WAAW,qBAAqB,KAAK,IAAI,GAAG,KAAK,OAAO;EAEtF,KAAK,6BAAa,IAAI,KAAK;CAC7B;CAEA,UAAuB;EACrB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,UAAU;IACR,WAAW,KAAK;IAChB,eAAe,KAAK,kBAAkB,gCAAgC,KAAK,OAAO,UAAU,KAAA;GAC9F;EACF;CACF;CAEA,kBAA0B;EACxB,MAAM,sBACJ;EACF,OAAO,OAAO,KAAK,iBAAiB,aAChC,KAAK,aAAa,EAAE,oBAAoB,CAAC,IACxC,KAAK,gBAAgB;CAC5B;CAEA,mBAAmC;EACjC,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,sBAAsB,KAAK,GAAG,sBAAsB;EACzF,OAAO,KAAK;CACd;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/bridge-client.ts","../src/sandbox.ts"],"sourcesContent":["export interface CloudflareSandboxBridgeClientOptions {\n baseUrl: string;\n apiToken?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/** Terminal and streaming events emitted by `POST /v1/sandbox/:id/exec`. */\nexport type CloudflareCommandEvent =\n | { type: 'stdout'; data: Uint8Array }\n | { type: 'stderr'; data: Uint8Array }\n | { type: 'exit'; exitCode: number }\n | { type: 'error'; message: string; code?: string };\n\nexport interface CloudflareExecRequest {\n /** Command and arguments. The bridge applies ANSI-C quoting to each element. */\n argv: string[];\n timeoutMs?: number;\n cwd?: string;\n}\n\nexport class CloudflareSandboxBridgeError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Cloudflare Sandbox Bridge request failed (${status}): ${body || 'empty response'}`);\n this.name = 'CloudflareSandboxBridgeError';\n this.status = status;\n this.body = body;\n }\n}\n\nfunction stripTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** Encodes an absolute sandbox path for the `/file/*` route, which omits the leading slash. */\nfunction encodeFilePath(absolutePath: string): string {\n let start = 0;\n while (start < absolutePath.length && absolutePath[start] === '/') start++;\n return absolutePath\n .slice(start)\n .split('/')\n .map(segment => encodeURIComponent(segment))\n .join('/');\n}\n\n/**\n * Client for the Cloudflare Sandbox Bridge Worker.\n *\n * @see https://developers.cloudflare.com/sandbox/bridge/http-api/\n */\nexport class CloudflareSandboxBridgeClient {\n readonly baseUrl: string;\n private readonly apiToken?: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: CloudflareSandboxBridgeClientOptions) {\n this.baseUrl = stripTrailingSlashes(options.baseUrl);\n this.apiToken = options.apiToken;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n }\n\n /** `POST /v1/sandbox` */\n async createSandbox(): Promise<string> {\n const created = await this.request<{ id: string }>('/v1/sandbox', { method: 'POST' });\n return created.id;\n }\n\n /** `GET /v1/sandbox/:id/running` */\n async isRunning(id: string): Promise<boolean> {\n const status = await this.request<{ running: boolean }>(`/v1/sandbox/${encodeURIComponent(id)}/running`, {});\n return status.running === true;\n }\n\n /** `DELETE /v1/sandbox/:id` */\n async deleteSandbox(id: string): Promise<void> {\n await this.request(`/v1/sandbox/${encodeURIComponent(id)}`, { method: 'DELETE' }, true);\n }\n\n /** `PUT /v1/sandbox/:id/file/*` — one file per request, raw bytes as the body. */\n async writeFile(id: string, absolutePath: string, content: Uint8Array | string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`,\n {\n method: 'PUT',\n body: content as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/exec` — streams SSE events until `exit` or `error`. */\n async exec(\n id: string,\n request: CloudflareExecRequest,\n options: {\n signal?: AbortSignal;\n onEvent: (event: CloudflareCommandEvent) => void;\n },\n ): Promise<void> {\n const response = await this.fetchImpl(`${this.baseUrl}/v1/sandbox/${encodeURIComponent(id)}/exec`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json', accept: 'text/event-stream' },\n body: JSON.stringify({\n argv: request.argv,\n ...(request.timeoutMs === undefined ? {} : { timeout_ms: request.timeoutMs }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n }),\n signal: options.signal,\n });\n\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (!response.body) {\n throw new Error('Cloudflare Sandbox Bridge returned an empty command stream');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done }).replace(/\\r\\n/g, '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n this.emitBlock(buffer.slice(0, boundary), options.onEvent);\n buffer = buffer.slice(boundary + 2);\n boundary = buffer.indexOf('\\n\\n');\n }\n if (done) break;\n }\n if (buffer.trim()) this.emitBlock(buffer, options.onEvent);\n }\n\n private emitBlock(block: string, onEvent: (event: CloudflareCommandEvent) => void): void {\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) eventName = line.slice(6).trim();\n else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));\n }\n const data = dataLines.join('\\n');\n if (!eventName || !data) return;\n\n switch (eventName) {\n case 'stdout':\n case 'stderr':\n onEvent({ type: eventName, data: base64ToBytes(data) });\n return;\n case 'exit': {\n const parsed = safeJsonParse(data);\n onEvent({ type: 'exit', exitCode: typeof parsed?.exit_code === 'number' ? parsed.exit_code : 0 });\n return;\n }\n case 'error': {\n const parsed = safeJsonParse(data);\n onEvent({\n type: 'error',\n message: typeof parsed?.error === 'string' ? parsed.error : data,\n code: typeof parsed?.code === 'string' ? parsed.code : undefined,\n });\n return;\n }\n default:\n return;\n }\n }\n\n private headers(): Record<string, string> {\n return this.apiToken ? { authorization: `Bearer ${this.apiToken}` } : {};\n }\n\n private async request<T>(path: string, init: RequestInit, allowEmpty = false): Promise<T> {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: { ...this.headers(), ...init.headers },\n });\n if (!response.ok) {\n throw new CloudflareSandboxBridgeError(response.status, await response.text());\n }\n if (allowEmpty || response.status === 204) return undefined as T;\n return response.json() as Promise<T>;\n }\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, 'base64'));\n}\n\nfunction safeJsonParse(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n} from '@mastra/core/workspace';\nimport { MastraSandbox } from '@mastra/core/workspace';\nimport { CloudflareSandboxBridgeClient, type CloudflareSandboxBridgeClientOptions } from './bridge-client';\n\nconst DEFAULT_COMMAND_TIMEOUT_MS = 300_000;\nconst WORKSPACE_ROOT = '/workspace';\n\ntype InstructionsOption = string | ((options: { defaultInstructions: string }) => string);\ntype BridgeClient = Pick<\n CloudflareSandboxBridgeClient,\n 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'exec'\n>;\n\nexport interface CloudflareSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** URL of a deployed Cloudflare Sandbox Bridge Worker. */\n baseUrl: string;\n /** Bearer token matching the Worker's `SANDBOX_API_KEY` secret, when authentication is enabled. */\n apiToken?: string;\n /** Stable Mastra identifier for this sandbox instance. */\n id?: string;\n /** Existing Cloudflare sandbox ID to reconnect to instead of creating a sandbox. */\n sandboxId?: string;\n /** Human-readable name shown in Mastra sandbox metadata. */\n name?: string;\n /** Environment variables applied to every command. */\n env?: Record<string, string>;\n /** Working directory applied to every command. Must be under /workspace. */\n workingDirectory?: string;\n /** Default command timeout in milliseconds. */\n commandTimeout?: number;\n /** Custom instructions returned by getInstructions(). */\n instructions?: InstructionsOption;\n /** Custom fetch implementation, primarily for advanced networking setup and tests. */\n fetch?: CloudflareSandboxBridgeClientOptions['fetch'];\n /** Preconfigured Bridge client, primarily for tests. */\n client?: BridgeClient;\n}\n\n/**\n * Builds the argv array sent to the bridge. The bridge applies ANSI-C quoting to\n * every element, so no local escaping is needed. Environment variables are applied\n * with `env`, which keeps each assignment a separate argv element.\n */\nfunction buildArgv(command: string, args: string[] | undefined, env: Record<string, string>): string[] {\n const assignments = Object.entries(env).map(([key, value]) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n return `${key}=${value}`;\n });\n const invocation = [command, ...(args ?? [])];\n return assignments.length ? ['env', ...assignments, ...invocation] : invocation;\n}\n\n/** Resolves a path inside /workspace, rejecting anything that escapes the workspace root. */\nfunction resolveWorkspacePath(path: string): string {\n const resolved = posix.resolve(WORKSPACE_ROOT, path);\n if (resolved !== WORKSPACE_ROOT && !resolved.startsWith(`${WORKSPACE_ROOT}/`)) {\n throw new Error(`Cloudflare Sandbox files must be written under ${WORKSPACE_ROOT}: ${path}`);\n }\n return resolved;\n}\n\nexport class CloudflareSandbox extends MastraSandbox {\n readonly id: string;\n readonly name: string;\n readonly provider = 'cloudflare-sandbox';\n status: ProviderStatus = 'pending';\n\n private readonly client: BridgeClient;\n private readonly workingDirectory?: string;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n\n constructor(options: CloudflareSandboxOptions) {\n const name = options.name ?? 'Cloudflare Sandbox';\n super({ ...options, name });\n this.id = options.id ?? `cloudflare-sandbox-${randomUUID()}`;\n this.name = name;\n this.sandboxId = options.sandboxId;\n this.workingDirectory = options.workingDirectory;\n this.commandTimeout = options.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT_MS;\n this.instructions = options.instructions;\n this.client =\n options.client ??\n new CloudflareSandboxBridgeClient({ baseUrl: options.baseUrl, apiToken: options.apiToken, fetch: options.fetch });\n }\n\n async start(): Promise<void> {\n if (this.sandboxId) {\n // The bridge boots the container on demand, so a stopped container is not fatal.\n const running = await this.client.isRunning(this.sandboxId);\n if (!running) {\n this.logger?.debug(`Cloudflare sandbox ${this.sandboxId} is not running yet; it starts on first use`);\n }\n return;\n }\n this.sandboxId = await this.client.createSandbox();\n this.createdAt = new Date();\n }\n\n async stop(): Promise<void> {\n // The bridge exposes create/delete but no suspend operation. Stop detaches this\n // Mastra lifecycle while preserving the remote sandbox for later reconnection.\n }\n\n async destroy(): Promise<void> {\n if (!this.sandboxId) return;\n await this.client.deleteSandbox(this.sandboxId);\n this.sandboxId = undefined;\n }\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n const sandboxId = this.requireSandboxId();\n\n const startedAt = Date.now();\n const timeout = options?.timeout ?? this.commandTimeout;\n if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError('Command timeout must be positive');\n\n const controller = new AbortController();\n let didTimeout = false;\n const timer = setTimeout(() => {\n didTimeout = true;\n controller.abort();\n }, timeout);\n const signal = options?.abortSignal ? AbortSignal.any([controller.signal, options.abortSignal]) : controller.signal;\n\n // stdout and stderr are separate byte streams, so each needs its own streaming decoder.\n const stdoutDecoder = new TextDecoder();\n const stderrDecoder = new TextDecoder();\n let stdout = '';\n let stderr = '';\n let exitCode = 1;\n\n const env = Object.fromEntries(\n Object.entries({ ...this.getEnv(), ...options?.env }).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\n try {\n await this.client.exec(\n sandboxId,\n {\n argv: buildArgv(command, args, env),\n timeoutMs: timeout,\n cwd: options?.cwd ?? this.workingDirectory,\n },\n {\n signal,\n onEvent: event => {\n switch (event.type) {\n case 'stdout': {\n const chunk = stdoutDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stdout += chunk;\n options?.onStdout?.(chunk);\n return;\n }\n case 'stderr': {\n const chunk = stderrDecoder.decode(event.data, { stream: true });\n if (!chunk) return;\n stderr += chunk;\n options?.onStderr?.(chunk);\n return;\n }\n case 'exit':\n exitCode = event.exitCode;\n return;\n case 'error':\n stderr += event.message;\n options?.onStderr?.(event.message);\n return;\n }\n },\n },\n );\n } catch (error) {\n if (!signal.aborted) throw error;\n } finally {\n clearTimeout(timer);\n }\n\n // Flush each decoder so a trailing truncated multi-byte sequence isn't dropped.\n const stdoutTail = stdoutDecoder.decode();\n if (stdoutTail) {\n stdout += stdoutTail;\n options?.onStdout?.(stdoutTail);\n }\n const stderrTail = stderrDecoder.decode();\n if (stderrTail) {\n stderr += stderrTail;\n options?.onStderr?.(stderrTail);\n }\n\n this.lastUsedAt = new Date();\n return {\n command,\n args,\n success: exitCode === 0 && !signal.aborted,\n exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startedAt,\n timedOut: didTimeout,\n killed: signal.aborted && !didTimeout,\n };\n }\n\n async writeFiles(files: SandboxFileInput[]): Promise<void> {\n const sandboxId = this.requireSandboxId();\n // The bridge writes one file per request.\n for (const file of files) {\n await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);\n }\n this.lastUsedAt = new Date();\n }\n\n getInfo(): SandboxInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this.createdAt,\n lastUsedAt: this.lastUsedAt,\n metadata: {\n sandboxId: this.sandboxId,\n bridgeBaseUrl: this.client instanceof CloudflareSandboxBridgeClient ? this.client.baseUrl : undefined,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions =\n 'Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n private requireSandboxId(): string {\n if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);\n return this.sandboxId;\n }\n}\n"],"mappings":";;;;AAoBA,IAAa,+BAAb,cAAkD,MAAM;CACtD;CACA;CAEA,YAAY,QAAgB,MAAc;EACxC,MAAM,6CAA6C,OAAO,KAAK,QAAQ,kBAAkB;EACzF,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;AAEA,SAAS,qBAAqB,KAAqB;CACjD,IAAI,MAAM,IAAI;CACd,OAAO,MAAM,KAAK,IAAI,MAAM,OAAO,KAAK;CACxC,OAAO,IAAI,MAAM,GAAG,GAAG;AACzB;;AAGA,SAAS,eAAe,cAA8B;CACpD,IAAI,QAAQ;CACZ,OAAO,QAAQ,aAAa,UAAU,aAAa,WAAW,KAAK;CACnE,OAAO,aACJ,MAAM,KAAK,CAAC,CACZ,MAAM,GAAG,CAAC,CACV,KAAI,YAAW,mBAAmB,OAAO,CAAC,CAAC,CAC3C,KAAK,GAAG;AACb;;;;;;AAOA,IAAa,gCAAb,MAA2C;CACzC;CACA;CACA;CAEA,YAAY,SAA+C;EACzD,KAAK,UAAU,qBAAqB,QAAQ,OAAO;EACnD,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAAQ,SAAS,WAAW;CAC/C;;CAGA,MAAM,gBAAiC;EAErC,QAAO,MADe,KAAK,QAAwB,eAAe,EAAE,QAAQ,OAAO,CAAC,EAAA,CACrE;CACjB;;CAGA,MAAM,UAAU,IAA8B;EAE5C,QAAO,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;GACA;GACA,SAAS,aAAa,KAAK,CAAC,OAAO;GACnC;GACA;GACA;GACA,iBAAiB,KAAK,IAAI,IAAI;GAC9B,UAAU;GACV,QAAQ,OAAO,WAAW,CAAC;EAC7B;CACF;CAEA,MAAM,WAAW,OAA0C;EACzD,MAAM,YAAY,KAAK,iBAAiB;EAExC,KAAK,MAAM,QAAQ,OACjB,MAAM,KAAK,OAAO,UAAU,WAAW,qBAAqB,KAAK,IAAI,GAAG,KAAK,OAAO;EAEtF,KAAK,6BAAa,IAAI,KAAK;CAC7B;CAEA,UAAuB;EACrB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,UAAU;IACR,WAAW,KAAK;IAChB,eAAe,KAAK,kBAAkB,gCAAgC,KAAK,OAAO,UAAU,KAAA;GAC9F;EACF;CACF;CAEA,kBAA0B;EACxB,MAAM,sBACJ;EACF,OAAO,OAAO,KAAK,iBAAiB,aAChC,KAAK,aAAa,EAAE,oBAAoB,CAAC,IACxC,KAAK,gBAAgB;CAC5B;CAEA,mBAAmC;EACjC,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,sBAAsB,KAAK,GAAG,sBAAsB;EACzF,OAAO,KAAK;CACd;AACF"}
package/dist/sandbox.d.ts CHANGED
@@ -35,7 +35,6 @@ export declare class CloudflareSandbox extends MastraSandbox {
35
35
  readonly provider = "cloudflare-sandbox";
36
36
  status: ProviderStatus;
37
37
  private readonly client;
38
- private readonly env;
39
38
  private readonly workingDirectory?;
40
39
  private readonly commandTimeout;
41
40
  private readonly instructions?;
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,aAAa,EACb,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,EAChB,WAAW,EACZ,MAAM,wBAAwB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,CAAC,SAAS,CAAC,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,UAAU,CAAC,CAAO;gBAEd,OAAO,EAAE,wBAAwB;IAcvC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAatB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAKrB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,qBAAqB,GAAG,OAAO,CAAC,aAAa,CAAC;IAiGzG,UAAU,CAAC,KAAK,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAS1D,OAAO,IAAI,WAAW;IAetB,eAAe,IAAI,MAAM;IAQzB,OAAO,CAAC,gBAAgB;CAIzB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/cloudflare-sandbox",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Cloudflare Sandbox provider for Mastra workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -28,10 +28,10 @@
28
28
  "tsdown": "0.22.9",
29
29
  "typescript": "^6.0.3",
30
30
  "vitest": "4.1.10",
31
- "@internal/lint": "0.0.124",
32
- "@internal/types-builder": "0.0.99",
33
- "@internal/workspace-test-utils": "0.0.68",
34
- "@mastra/core": "1.60.0"
31
+ "@internal/lint": "0.0.126",
32
+ "@internal/types-builder": "0.0.101",
33
+ "@mastra/core": "1.62.0",
34
+ "@internal/workspace-test-utils": "0.0.70"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@mastra/core": ">=1.12.0-0 <2.0.0-0"