@mastra/cloudflare-sandbox 0.4.0 → 0.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -217,6 +217,37 @@ function safeJsonParse(value) {
217
217
  //#region src/sandbox.ts
218
218
  const DEFAULT_COMMAND_TIMEOUT_MS = 3e5;
219
219
  const WORKSPACE_ROOT = "/workspace";
220
+ /** Allowlist pattern for mount paths, matching the other remote sandbox providers. */
221
+ const SAFE_MOUNT_PATH = /^\/[a-zA-Z0-9_.\-/]+$/;
222
+ function validateMountPath(mountPath) {
223
+ if (!SAFE_MOUNT_PATH.test(mountPath)) throw new Error(`Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`);
224
+ }
225
+ /**
226
+ * Translates a Workspace mount config into the bridge's mount request, or
227
+ * explains why the bridge cannot serve it. The bridge mounts S3-compatible
228
+ * buckets with s3fs; GCS and Azure mount configs have no equivalent route.
229
+ */
230
+ function toMountRequest(config, mountPath) {
231
+ if (config.type !== "s3") return { error: `Cloudflare Sandbox can only mount S3-compatible buckets; got mount type "${config.type}"` };
232
+ const s3 = config;
233
+ if (s3.sessionToken) return { error: "Cloudflare Sandbox bucket mounts do not support temporary credentials (sessionToken)" };
234
+ if (Boolean(s3.accessKeyId) !== Boolean(s3.secretAccessKey)) return { error: "Cloudflare Sandbox bucket mounts need both accessKeyId and secretAccessKey, or neither" };
235
+ const endpoint = s3.endpoint ?? (s3.region ? `https://s3.${s3.region}.amazonaws.com` : void 0);
236
+ const prefix = s3.prefix ? s3.prefix.startsWith("/") ? s3.prefix : `/${s3.prefix}` : void 0;
237
+ return { request: {
238
+ bucket: s3.bucket,
239
+ mountPath,
240
+ options: {
241
+ endpoint,
242
+ prefix,
243
+ readOnly: s3.readOnly,
244
+ credentials: s3.accessKeyId && s3.secretAccessKey ? {
245
+ accessKeyId: s3.accessKeyId,
246
+ secretAccessKey: s3.secretAccessKey
247
+ } : void 0
248
+ }
249
+ } };
250
+ }
220
251
  /**
221
252
  * Absolute path to the shell used to interpret bare command strings. Absolute so it
222
253
  * resolves even when a custom PATH excludes the standard system directories.
@@ -266,6 +297,8 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
266
297
  sandboxId;
267
298
  createdAt = /* @__PURE__ */ new Date();
268
299
  lastUsedAt;
300
+ /** Shared across concurrent callers so a wake triggers a single re-mount pass. */
301
+ ensureMountsPromise;
269
302
  constructor(options) {
270
303
  const name = options.name ?? "Cloudflare Sandbox";
271
304
  super({
@@ -299,6 +332,7 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
299
332
  }
300
333
  async executeCommand(command, args, options) {
301
334
  const sandboxId = this.requireSandboxId();
335
+ await this.ensureMountsActive(sandboxId);
302
336
  const startedAt = Date.now();
303
337
  const timeout = options?.timeout ?? this.commandTimeout;
304
338
  if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError("Command timeout must be positive");
@@ -382,12 +416,14 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
382
416
  async writeFiles(files) {
383
417
  (0, _mastra_core_workspace.assertModesUnsupported)(files, "Cloudflare");
384
418
  const sandboxId = this.requireSandboxId();
419
+ await this.ensureMountsActive(sandboxId);
385
420
  for (const file of files) await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);
386
421
  this.lastUsedAt = /* @__PURE__ */ new Date();
387
422
  }
388
423
  /** Reads a single file under /workspace, returning its raw bytes. */
389
424
  async readFile(path$2) {
390
425
  const sandboxId = this.requireSandboxId();
426
+ await this.ensureMountsActive(sandboxId);
391
427
  const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path$2));
392
428
  this.lastUsedAt = /* @__PURE__ */ new Date();
393
429
  return bytes;
@@ -395,6 +431,7 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
395
431
  /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */
396
432
  async persistWorkspace(options) {
397
433
  const sandboxId = this.requireSandboxId();
434
+ await this.ensureMountsActive(sandboxId);
398
435
  const archive = await this.client.persistWorkspace(sandboxId, options);
399
436
  this.lastUsedAt = /* @__PURE__ */ new Date();
400
437
  return archive;
@@ -402,6 +439,7 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
402
439
  /** Restores /workspace from a raw tar payload produced by persistWorkspace. */
403
440
  async hydrateWorkspace(tar) {
404
441
  const sandboxId = this.requireSandboxId();
442
+ await this.ensureMountsActive(sandboxId);
405
443
  await this.client.hydrateWorkspace(sandboxId, tar);
406
444
  this.lastUsedAt = /* @__PURE__ */ new Date();
407
445
  }
@@ -419,10 +457,135 @@ var CloudflareSandbox = class extends _mastra_core_workspace.MastraSandbox {
419
457
  }
420
458
  };
421
459
  }
460
+ /**
461
+ * Mounts an S3-compatible bucket (R2, S3, MinIO, ...) at `mountPath` through
462
+ * the bridge's mount route. Called by MountManager for each Workspace `mounts`
463
+ * entry after start(). The Cloudflare Sandbox SDK forgets mounts when an idle
464
+ * container is stopped and does not restore them on wake, so
465
+ * {@link ensureMountsActive} re-mounts stale paths before each operation; that
466
+ * makes mounted paths the durable part of the filesystem.
467
+ */
468
+ async mount(filesystem, mountPath) {
469
+ validateMountPath(mountPath);
470
+ const sandboxId = this.requireSandboxId();
471
+ const config = filesystem.getMountConfig?.();
472
+ if (!config) {
473
+ const error = `Filesystem "${filesystem.id}" does not provide a mount config`;
474
+ this.mounts.set(mountPath, {
475
+ filesystem,
476
+ state: "error",
477
+ error
478
+ });
479
+ return {
480
+ success: false,
481
+ mountPath,
482
+ error
483
+ };
484
+ }
485
+ const translated = toMountRequest(config, mountPath);
486
+ if ("error" in translated) {
487
+ this.mounts.set(mountPath, {
488
+ filesystem,
489
+ state: "error",
490
+ config,
491
+ error: translated.error
492
+ });
493
+ return {
494
+ success: false,
495
+ mountPath,
496
+ error: translated.error
497
+ };
498
+ }
499
+ this.mounts.set(mountPath, {
500
+ filesystem,
501
+ state: "mounting",
502
+ config
503
+ });
504
+ try {
505
+ await this.client.mountBucket(sandboxId, translated.request);
506
+ } catch (cause) {
507
+ const error = cause instanceof Error ? cause.message : String(cause);
508
+ this.mounts.set(mountPath, {
509
+ filesystem,
510
+ state: "error",
511
+ config,
512
+ error
513
+ });
514
+ return {
515
+ success: false,
516
+ mountPath,
517
+ error
518
+ };
519
+ }
520
+ this.mounts.set(mountPath, {
521
+ filesystem,
522
+ state: "mounted",
523
+ config
524
+ });
525
+ this.lastUsedAt = /* @__PURE__ */ new Date();
526
+ return {
527
+ success: true,
528
+ mountPath
529
+ };
530
+ }
531
+ /** Unmounts a bucket previously mounted with {@link mount}. */
532
+ async unmount(mountPath) {
533
+ validateMountPath(mountPath);
534
+ const sandboxId = this.requireSandboxId();
535
+ await this.client.unmountBucket(sandboxId, mountPath);
536
+ this.mounts.delete(mountPath);
537
+ this.lastUsedAt = /* @__PURE__ */ new Date();
538
+ }
422
539
  getInstructions() {
423
- const defaultInstructions = "Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.";
540
+ const mounted = [...this.mounts.entries].filter(([, entry]) => entry.state === "mounted").map(([path$3]) => path$3);
541
+ const defaultInstructions = mounted.length > 0 ? `Commands execute in a remote Cloudflare Sandbox. The container sleeps when idle and files under /workspace do NOT survive between commands, except under the mounted paths: ${mounted.join(", ")}. Keep anything that must persist under a mounted path.` : "Commands execute in a remote Cloudflare Sandbox. Use /workspace as scratch space only: the container sleeps when idle and files under /workspace do NOT survive between commands. Do not assume earlier files still exist.";
424
542
  return typeof this.instructions === "function" ? this.instructions({ defaultInstructions }) : this.instructions ?? defaultInstructions;
425
543
  }
544
+ /**
545
+ * A slept container boots fresh without its mounts: `@cloudflare/sandbox` keeps
546
+ * `activeMounts` in memory and clears it on stop, so it never re-mounts on wake,
547
+ * and `GET /running` still reports `true` until the DO next talks to the
548
+ * container. Before any operation that reads or writes the filesystem, probe the
549
+ * mounted paths with `mountpoint` and re-mount the ones that are gone. The pass
550
+ * is shared across concurrent callers, and there is no probe when nothing is
551
+ * mounted.
552
+ */
553
+ ensureMountsActive(sandboxId) {
554
+ const mountedPaths = [...this.mounts.entries].filter(([, entry]) => entry.state === "mounted").map(([mountPath]) => mountPath);
555
+ if (mountedPaths.length === 0) return Promise.resolve();
556
+ if (!this.ensureMountsPromise) this.ensureMountsPromise = this.remountStalePaths(sandboxId, mountedPaths).finally(() => {
557
+ this.ensureMountsPromise = void 0;
558
+ });
559
+ return this.ensureMountsPromise;
560
+ }
561
+ async remountStalePaths(sandboxId, mountedPaths) {
562
+ const script = `for p in ${mountedPaths.join(" ")}; do mountpoint -q "$p" || echo "$p"; done`;
563
+ const decoder = new TextDecoder();
564
+ let stdout = "";
565
+ await this.client.exec(sandboxId, {
566
+ argv: [
567
+ SHELL_PATH,
568
+ "-c",
569
+ script
570
+ ],
571
+ timeoutMs: this.commandTimeout
572
+ }, { onEvent: (event) => {
573
+ if (event.type === "stdout") stdout += decoder.decode(event.data, { stream: true });
574
+ } });
575
+ stdout += decoder.decode();
576
+ const stalePaths = stdout.split("\n").map((line) => line.trim()).filter(Boolean);
577
+ for (const mountPath of stalePaths) {
578
+ const entry = this.mounts.get(mountPath);
579
+ if (!entry?.config) continue;
580
+ const translated = toMountRequest(entry.config, mountPath);
581
+ if ("error" in translated) continue;
582
+ try {
583
+ await this.client.mountBucket(sandboxId, translated.request);
584
+ } catch (cause) {
585
+ this.logger?.warn(`Failed to re-mount ${mountPath} after container wake`, { error: cause });
586
+ }
587
+ }
588
+ }
426
589
  requireSandboxId() {
427
590
  if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);
428
591
  return this.sandboxId;
@@ -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 interface CloudflarePersistWorkspaceOptions {\n /** Relative paths (under /workspace) to exclude from the archive. */\n excludes?: string[];\n}\n\nexport interface CloudflareMountBucketCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n}\n\nexport interface CloudflareMountBucketOptions {\n /** S3-compatible endpoint, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n endpoint?: string;\n /** Mount the bucket read-only. */\n readOnly?: boolean;\n /** Only expose objects under this bucket prefix at the mount point. */\n prefix?: string;\n /** Storage provider hint, e.g. `r2`. */\n provider?: string;\n /** Explicit credentials; omitted when the Worker resolves them from secrets. */\n credentials?: CloudflareMountBucketCredentials;\n}\n\nexport interface CloudflareMountBucketRequest {\n /** Bucket name, e.g. `my-r2-bucket`. */\n bucket: string;\n /** Local filesystem path to mount at, e.g. `/mnt/data`. */\n mountPath: string;\n options?: CloudflareMountBucketOptions;\n}\n\nexport interface CloudflareCreateSessionRequest {\n /** Working directory the session starts in. */\n cwd?: string;\n /** Environment variables seeded into the session. */\n env?: Record<string, string>;\n /** Caller-chosen session id; must match `^[a-zA-Z0-9._-]{1,128}$`. Generated when omitted. */\n sessionId?: string;\n}\n\nexport interface CloudflareSession {\n id: 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 /** `GET /v1/sandbox/:id/file/*` — reads one file, returning its raw bytes. */\n async readFile(id: string, absolutePath: string): Promise<Uint8Array> {\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`, {});\n }\n\n /** `GET /v1/sandbox/:id/persist` — archives `/workspace`, returning raw tar bytes. */\n async persistWorkspace(id: string, options: CloudflarePersistWorkspaceOptions = {}): Promise<Uint8Array> {\n const query = options.excludes?.length ? `?excludes=${encodeURIComponent(options.excludes.join(','))}` : '';\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/persist${query}`, {});\n }\n\n /** `POST /v1/sandbox/:id/hydrate` — restores `/workspace` from a raw tar payload. */\n async hydrateWorkspace(id: string, tar: Uint8Array): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/hydrate`,\n {\n method: 'POST',\n body: tar as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/mount` — mounts an S3-compatible bucket as a local directory. */\n async mountBucket(id: string, request: CloudflareMountBucketRequest): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/mount`,\n {\n method: 'POST',\n body: JSON.stringify(request),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/unmount` — unmounts a previously mounted bucket. */\n async unmountBucket(id: string, mountPath: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/unmount`,\n {\n method: 'POST',\n body: JSON.stringify({ mountPath }),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/session` — creates an execution session, returning its id. */\n async createSession(id: string, request: CloudflareCreateSessionRequest = {}): Promise<CloudflareSession> {\n const body: Record<string, unknown> = {};\n if (request.cwd !== undefined) body.cwd = request.cwd;\n if (request.env !== undefined) body.env = request.env;\n if (request.sessionId !== undefined) body.id = request.sessionId;\n return this.request<CloudflareSession>(`/v1/sandbox/${encodeURIComponent(id)}/session`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'content-type': 'application/json' },\n });\n }\n\n /** `DELETE /v1/sandbox/:id/session/:sessionId` — tears down an execution session. */\n async deleteSession(id: string, sessionId: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/session/${encodeURIComponent(sessionId)}`,\n { method: 'DELETE' },\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 private async requestBytes(path: string, init: RequestInit): Promise<Uint8Array> {\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 return new Uint8Array(await response.arrayBuffer());\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, assertModesUnsupported } from '@mastra/core/workspace';\nimport {\n CloudflareSandboxBridgeClient,\n type CloudflarePersistWorkspaceOptions,\n type CloudflareSandboxBridgeClientOptions,\n} 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'\n | 'isRunning'\n | 'deleteSandbox'\n | 'writeFile'\n | 'readFile'\n | 'persistWorkspace'\n | 'hydrateWorkspace'\n | '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 * Absolute path to the shell used to interpret bare command strings. Absolute so it\n * resolves even when a custom PATH excludes the standard system directories.\n */\nconst SHELL_PATH = '/bin/bash';\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 *\n * When no separate arguments are supplied (the shape the built-in Workspace\n * `execute_command` tool uses), `command` is a shell command string — pipes,\n * chaining, quoting, redirection — so it is run through a non-login shell rather\n * than treated as a single executable name. When explicit arguments are given,\n * each element stays a literal argv token.\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 = args && args.length > 0 ? [command, ...args] : [SHELL_PATH, '-c', command];\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 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.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 assertModesUnsupported(files, 'Cloudflare');\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 /** Reads a single file under /workspace, returning its raw bytes. */\n async readFile(path: string): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path));\n this.lastUsedAt = new Date();\n return bytes;\n }\n\n /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */\n async persistWorkspace(options?: CloudflarePersistWorkspaceOptions): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n const archive = await this.client.persistWorkspace(sandboxId, options);\n this.lastUsedAt = new Date();\n return archive;\n }\n\n /** Restores /workspace from a raw tar payload produced by persistWorkspace. */\n async hydrateWorkspace(tar: Uint8Array): Promise<void> {\n const sandboxId = this.requireSandboxId();\n await this.client.hydrateWorkspace(sandboxId, tar);\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":";;;;;AAgEA,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,MADc,KAAK,QAA8B,eAAe,mBAAmB,EAAE,EAAE,WAAW,CAAC,CAAC,EAAA,CAC7F,YAAY;CAC5B;;CAGA,MAAM,cAAc,IAA2B;EAC7C,MAAM,KAAK,QAAQ,eAAe,mBAAmB,EAAE,KAAK,EAAE,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ACxC,MAAM,KAAK,OAAO,iBAAiB,WAAW,GAAG;EACjD,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.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 interface CloudflarePersistWorkspaceOptions {\n /** Relative paths (under /workspace) to exclude from the archive. */\n excludes?: string[];\n}\n\nexport interface CloudflareMountBucketCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n}\n\nexport interface CloudflareMountBucketOptions {\n /** S3-compatible endpoint, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n endpoint?: string;\n /** Mount the bucket read-only. */\n readOnly?: boolean;\n /** Only expose objects under this bucket prefix at the mount point. */\n prefix?: string;\n /** Storage provider hint, e.g. `r2`. */\n provider?: string;\n /** Explicit credentials; omitted when the Worker resolves them from secrets. */\n credentials?: CloudflareMountBucketCredentials;\n}\n\nexport interface CloudflareMountBucketRequest {\n /** Bucket name, e.g. `my-r2-bucket`. */\n bucket: string;\n /** Local filesystem path to mount at, e.g. `/mnt/data`. */\n mountPath: string;\n options?: CloudflareMountBucketOptions;\n}\n\nexport interface CloudflareCreateSessionRequest {\n /** Working directory the session starts in. */\n cwd?: string;\n /** Environment variables seeded into the session. */\n env?: Record<string, string>;\n /** Caller-chosen session id; must match `^[a-zA-Z0-9._-]{1,128}$`. Generated when omitted. */\n sessionId?: string;\n}\n\nexport interface CloudflareSession {\n id: 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 /** `GET /v1/sandbox/:id/file/*` — reads one file, returning its raw bytes. */\n async readFile(id: string, absolutePath: string): Promise<Uint8Array> {\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`, {});\n }\n\n /** `GET /v1/sandbox/:id/persist` — archives `/workspace`, returning raw tar bytes. */\n async persistWorkspace(id: string, options: CloudflarePersistWorkspaceOptions = {}): Promise<Uint8Array> {\n const query = options.excludes?.length ? `?excludes=${encodeURIComponent(options.excludes.join(','))}` : '';\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/persist${query}`, {});\n }\n\n /** `POST /v1/sandbox/:id/hydrate` — restores `/workspace` from a raw tar payload. */\n async hydrateWorkspace(id: string, tar: Uint8Array): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/hydrate`,\n {\n method: 'POST',\n body: tar as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/mount` — mounts an S3-compatible bucket as a local directory. */\n async mountBucket(id: string, request: CloudflareMountBucketRequest): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/mount`,\n {\n method: 'POST',\n body: JSON.stringify(request),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/unmount` — unmounts a previously mounted bucket. */\n async unmountBucket(id: string, mountPath: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/unmount`,\n {\n method: 'POST',\n body: JSON.stringify({ mountPath }),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/session` — creates an execution session, returning its id. */\n async createSession(id: string, request: CloudflareCreateSessionRequest = {}): Promise<CloudflareSession> {\n const body: Record<string, unknown> = {};\n if (request.cwd !== undefined) body.cwd = request.cwd;\n if (request.env !== undefined) body.env = request.env;\n if (request.sessionId !== undefined) body.id = request.sessionId;\n return this.request<CloudflareSession>(`/v1/sandbox/${encodeURIComponent(id)}/session`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'content-type': 'application/json' },\n });\n }\n\n /** `DELETE /v1/sandbox/:id/session/:sessionId` — tears down an execution session. */\n async deleteSession(id: string, sessionId: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/session/${encodeURIComponent(sessionId)}`,\n { method: 'DELETE' },\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 private async requestBytes(path: string, init: RequestInit): Promise<Uint8Array> {\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 return new Uint8Array(await response.arrayBuffer());\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 FilesystemMountConfig,\n MastraSandboxOptions,\n MountManager,\n MountResult,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n WorkspaceFilesystem,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, assertModesUnsupported } from '@mastra/core/workspace';\nimport {\n CloudflareSandboxBridgeClient,\n type CloudflareMountBucketRequest,\n type CloudflarePersistWorkspaceOptions,\n type CloudflareSandboxBridgeClientOptions,\n} 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'\n | 'isRunning'\n | 'deleteSandbox'\n | 'writeFile'\n | 'readFile'\n | 'persistWorkspace'\n | 'hydrateWorkspace'\n | 'mountBucket'\n | 'unmountBucket'\n | 'exec'\n>;\n\n/**\n * Mount config accepted by the Cloudflare bridge: any S3-compatible bucket\n * (R2, S3, MinIO, ...) as produced by `S3Filesystem.getMountConfig()`.\n * Declared structurally so this package does not depend on `@mastra/s3`.\n */\ninterface S3CompatibleMountConfig extends FilesystemMountConfig {\n type: 's3';\n bucket: string;\n region?: string;\n endpoint?: string;\n accessKeyId?: string;\n secretAccessKey?: string;\n sessionToken?: string;\n prefix?: string;\n readOnly?: boolean;\n}\n\n/** Allowlist pattern for mount paths, matching the other remote sandbox providers. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\n\nfunction validateMountPath(mountPath: string): void {\n if (!SAFE_MOUNT_PATH.test(mountPath)) {\n throw new Error(\n `Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`,\n );\n }\n}\n\n/**\n * Translates a Workspace mount config into the bridge's mount request, or\n * explains why the bridge cannot serve it. The bridge mounts S3-compatible\n * buckets with s3fs; GCS and Azure mount configs have no equivalent route.\n */\nfunction toMountRequest(\n config: FilesystemMountConfig,\n mountPath: string,\n): { request: CloudflareMountBucketRequest } | { error: string } {\n if (config.type !== 's3') {\n return { error: `Cloudflare Sandbox can only mount S3-compatible buckets; got mount type \"${config.type}\"` };\n }\n const s3 = config as S3CompatibleMountConfig;\n if (s3.sessionToken) {\n return { error: 'Cloudflare Sandbox bucket mounts do not support temporary credentials (sessionToken)' };\n }\n if (Boolean(s3.accessKeyId) !== Boolean(s3.secretAccessKey)) {\n return { error: 'Cloudflare Sandbox bucket mounts need both accessKeyId and secretAccessKey, or neither' };\n }\n // The bridge treats a request with no endpoint as an R2 binding mount, so a\n // region-only AWS filesystem must resolve to an explicit S3 endpoint.\n const endpoint = s3.endpoint ?? (s3.region ? `https://s3.${s3.region}.amazonaws.com` : undefined);\n // The bridge requires the prefix to start with `/`; S3Filesystem emits `dir/`.\n const prefix = s3.prefix ? (s3.prefix.startsWith('/') ? s3.prefix : `/${s3.prefix}`) : undefined;\n return {\n request: {\n bucket: s3.bucket,\n mountPath,\n options: {\n endpoint,\n prefix,\n readOnly: s3.readOnly,\n credentials:\n s3.accessKeyId && s3.secretAccessKey\n ? { accessKeyId: s3.accessKeyId, secretAccessKey: s3.secretAccessKey }\n : undefined,\n },\n },\n };\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 * Absolute path to the shell used to interpret bare command strings. Absolute so it\n * resolves even when a custom PATH excludes the standard system directories.\n */\nconst SHELL_PATH = '/bin/bash';\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 *\n * When no separate arguments are supplied (the shape the built-in Workspace\n * `execute_command` tool uses), `command` is a shell command string — pipes,\n * chaining, quoting, redirection — so it is run through a non-login shell rather\n * than treated as a single executable name. When explicit arguments are given,\n * each element stays a literal argv token.\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 = args && args.length > 0 ? [command, ...args] : [SHELL_PATH, '-c', command];\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 /** Created by MastraSandbox because this class implements mount(). */\n declare readonly mounts: MountManager;\n\n private readonly client: BridgeClient;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n /** Shared across concurrent callers so a wake triggers a single re-mount pass. */\n private ensureMountsPromise?: Promise<void>;\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.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 await this.ensureMountsActive(sandboxId);\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 assertModesUnsupported(files, 'Cloudflare');\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\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 /** Reads a single file under /workspace, returning its raw bytes. */\n async readFile(path: string): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path));\n this.lastUsedAt = new Date();\n return bytes;\n }\n\n /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */\n async persistWorkspace(options?: CloudflarePersistWorkspaceOptions): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n const archive = await this.client.persistWorkspace(sandboxId, options);\n this.lastUsedAt = new Date();\n return archive;\n }\n\n /** Restores /workspace from a raw tar payload produced by persistWorkspace. */\n async hydrateWorkspace(tar: Uint8Array): Promise<void> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n await this.client.hydrateWorkspace(sandboxId, tar);\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 /**\n * Mounts an S3-compatible bucket (R2, S3, MinIO, ...) at `mountPath` through\n * the bridge's mount route. Called by MountManager for each Workspace `mounts`\n * entry after start(). The Cloudflare Sandbox SDK forgets mounts when an idle\n * container is stopped and does not restore them on wake, so\n * {@link ensureMountsActive} re-mounts stale paths before each operation; that\n * makes mounted paths the durable part of the filesystem.\n */\n async mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult> {\n validateMountPath(mountPath);\n const sandboxId = this.requireSandboxId();\n\n const config = filesystem.getMountConfig?.();\n if (!config) {\n const error = `Filesystem \"${filesystem.id}\" does not provide a mount config`;\n this.mounts.set(mountPath, { filesystem, state: 'error', error });\n return { success: false, mountPath, error };\n }\n\n const translated = toMountRequest(config, mountPath);\n if ('error' in translated) {\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: translated.error });\n return { success: false, mountPath, error: translated.error };\n }\n\n this.mounts.set(mountPath, { filesystem, state: 'mounting', config });\n try {\n await this.client.mountBucket(sandboxId, translated.request);\n } catch (cause) {\n const error = cause instanceof Error ? cause.message : String(cause);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n this.mounts.set(mountPath, { filesystem, state: 'mounted', config });\n this.lastUsedAt = new Date();\n return { success: true, mountPath };\n }\n\n /** Unmounts a bucket previously mounted with {@link mount}. */\n async unmount(mountPath: string): Promise<void> {\n validateMountPath(mountPath);\n const sandboxId = this.requireSandboxId();\n await this.client.unmountBucket(sandboxId, mountPath);\n this.mounts.delete(mountPath);\n this.lastUsedAt = new Date();\n }\n\n getInstructions(): string {\n const mounted = [...this.mounts.entries].filter(([, entry]) => entry.state === 'mounted').map(([path]) => path);\n const defaultInstructions =\n mounted.length > 0\n ? `Commands execute in a remote Cloudflare Sandbox. The container sleeps when idle and files under /workspace do NOT survive between commands, except under the mounted paths: ${mounted.join(', ')}. Keep anything that must persist under a mounted path.`\n : 'Commands execute in a remote Cloudflare Sandbox. Use /workspace as scratch space only: the container sleeps when idle and files under /workspace do NOT survive between commands. Do not assume earlier files still exist.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n /**\n * A slept container boots fresh without its mounts: `@cloudflare/sandbox` keeps\n * `activeMounts` in memory and clears it on stop, so it never re-mounts on wake,\n * and `GET /running` still reports `true` until the DO next talks to the\n * container. Before any operation that reads or writes the filesystem, probe the\n * mounted paths with `mountpoint` and re-mount the ones that are gone. The pass\n * is shared across concurrent callers, and there is no probe when nothing is\n * mounted.\n */\n private ensureMountsActive(sandboxId: string): Promise<void> {\n const mountedPaths = [...this.mounts.entries]\n .filter(([, entry]) => entry.state === 'mounted')\n .map(([mountPath]) => mountPath);\n if (mountedPaths.length === 0) return Promise.resolve();\n if (!this.ensureMountsPromise) {\n this.ensureMountsPromise = this.remountStalePaths(sandboxId, mountedPaths).finally(() => {\n this.ensureMountsPromise = undefined;\n });\n }\n return this.ensureMountsPromise;\n }\n\n private async remountStalePaths(sandboxId: string, mountedPaths: string[]): Promise<void> {\n // Mount paths are validated against SAFE_MOUNT_PATH, so they are safe to embed\n // directly. `mountpoint -q` exits non-zero for a path that is no longer a mount,\n // and that path is echoed so a single exec reports every stale mount at once.\n const script = `for p in ${mountedPaths.join(' ')}; do mountpoint -q \"$p\" || echo \"$p\"; done`;\n const decoder = new TextDecoder();\n let stdout = '';\n await this.client.exec(\n sandboxId,\n { argv: [SHELL_PATH, '-c', script], timeoutMs: this.commandTimeout },\n {\n onEvent: event => {\n if (event.type === 'stdout') stdout += decoder.decode(event.data, { stream: true });\n },\n },\n );\n stdout += decoder.decode();\n\n const stalePaths = stdout\n .split('\\n')\n .map(line => line.trim())\n .filter(Boolean);\n for (const mountPath of stalePaths) {\n const entry = this.mounts.get(mountPath);\n if (!entry?.config) continue;\n const translated = toMountRequest(entry.config, mountPath);\n if ('error' in translated) continue;\n try {\n await this.client.mountBucket(sandboxId, translated.request);\n } catch (cause) {\n this.logger?.warn(`Failed to re-mount ${mountPath} after container wake`, { error: cause });\n }\n }\n }\n\n private requireSandbox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AI;IACF,MAAM,KAAK,OAAO,YAAY,WAAW,WAAW,OAAO;GAC7D,SAAS,OAAO;IACd,KAAK,QAAQ,KAAK,sBAAsB,UAAU,wBAAwB,EAAE,OAAO,MAAM,CAAC;GAC5F;EACF;CACF;CAEA,mBAAmC;EACjC,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,sBAAsB,KAAK,GAAG,sBAAsB;EACzF,OAAO,KAAK;CACd;AACF"}
package/dist/index.js CHANGED
@@ -216,6 +216,37 @@ function safeJsonParse(value) {
216
216
  //#region src/sandbox.ts
217
217
  const DEFAULT_COMMAND_TIMEOUT_MS = 3e5;
218
218
  const WORKSPACE_ROOT = "/workspace";
219
+ /** Allowlist pattern for mount paths, matching the other remote sandbox providers. */
220
+ const SAFE_MOUNT_PATH = /^\/[a-zA-Z0-9_.\-/]+$/;
221
+ function validateMountPath(mountPath) {
222
+ if (!SAFE_MOUNT_PATH.test(mountPath)) throw new Error(`Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`);
223
+ }
224
+ /**
225
+ * Translates a Workspace mount config into the bridge's mount request, or
226
+ * explains why the bridge cannot serve it. The bridge mounts S3-compatible
227
+ * buckets with s3fs; GCS and Azure mount configs have no equivalent route.
228
+ */
229
+ function toMountRequest(config, mountPath) {
230
+ if (config.type !== "s3") return { error: `Cloudflare Sandbox can only mount S3-compatible buckets; got mount type "${config.type}"` };
231
+ const s3 = config;
232
+ if (s3.sessionToken) return { error: "Cloudflare Sandbox bucket mounts do not support temporary credentials (sessionToken)" };
233
+ if (Boolean(s3.accessKeyId) !== Boolean(s3.secretAccessKey)) return { error: "Cloudflare Sandbox bucket mounts need both accessKeyId and secretAccessKey, or neither" };
234
+ const endpoint = s3.endpoint ?? (s3.region ? `https://s3.${s3.region}.amazonaws.com` : void 0);
235
+ const prefix = s3.prefix ? s3.prefix.startsWith("/") ? s3.prefix : `/${s3.prefix}` : void 0;
236
+ return { request: {
237
+ bucket: s3.bucket,
238
+ mountPath,
239
+ options: {
240
+ endpoint,
241
+ prefix,
242
+ readOnly: s3.readOnly,
243
+ credentials: s3.accessKeyId && s3.secretAccessKey ? {
244
+ accessKeyId: s3.accessKeyId,
245
+ secretAccessKey: s3.secretAccessKey
246
+ } : void 0
247
+ }
248
+ } };
249
+ }
219
250
  /**
220
251
  * Absolute path to the shell used to interpret bare command strings. Absolute so it
221
252
  * resolves even when a custom PATH excludes the standard system directories.
@@ -265,6 +296,8 @@ var CloudflareSandbox = class extends MastraSandbox {
265
296
  sandboxId;
266
297
  createdAt = /* @__PURE__ */ new Date();
267
298
  lastUsedAt;
299
+ /** Shared across concurrent callers so a wake triggers a single re-mount pass. */
300
+ ensureMountsPromise;
268
301
  constructor(options) {
269
302
  const name = options.name ?? "Cloudflare Sandbox";
270
303
  super({
@@ -298,6 +331,7 @@ var CloudflareSandbox = class extends MastraSandbox {
298
331
  }
299
332
  async executeCommand(command, args, options) {
300
333
  const sandboxId = this.requireSandboxId();
334
+ await this.ensureMountsActive(sandboxId);
301
335
  const startedAt = Date.now();
302
336
  const timeout = options?.timeout ?? this.commandTimeout;
303
337
  if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError("Command timeout must be positive");
@@ -381,12 +415,14 @@ var CloudflareSandbox = class extends MastraSandbox {
381
415
  async writeFiles(files) {
382
416
  assertModesUnsupported(files, "Cloudflare");
383
417
  const sandboxId = this.requireSandboxId();
418
+ await this.ensureMountsActive(sandboxId);
384
419
  for (const file of files) await this.client.writeFile(sandboxId, resolveWorkspacePath(file.path), file.content);
385
420
  this.lastUsedAt = /* @__PURE__ */ new Date();
386
421
  }
387
422
  /** Reads a single file under /workspace, returning its raw bytes. */
388
423
  async readFile(path) {
389
424
  const sandboxId = this.requireSandboxId();
425
+ await this.ensureMountsActive(sandboxId);
390
426
  const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path));
391
427
  this.lastUsedAt = /* @__PURE__ */ new Date();
392
428
  return bytes;
@@ -394,6 +430,7 @@ var CloudflareSandbox = class extends MastraSandbox {
394
430
  /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */
395
431
  async persistWorkspace(options) {
396
432
  const sandboxId = this.requireSandboxId();
433
+ await this.ensureMountsActive(sandboxId);
397
434
  const archive = await this.client.persistWorkspace(sandboxId, options);
398
435
  this.lastUsedAt = /* @__PURE__ */ new Date();
399
436
  return archive;
@@ -401,6 +438,7 @@ var CloudflareSandbox = class extends MastraSandbox {
401
438
  /** Restores /workspace from a raw tar payload produced by persistWorkspace. */
402
439
  async hydrateWorkspace(tar) {
403
440
  const sandboxId = this.requireSandboxId();
441
+ await this.ensureMountsActive(sandboxId);
404
442
  await this.client.hydrateWorkspace(sandboxId, tar);
405
443
  this.lastUsedAt = /* @__PURE__ */ new Date();
406
444
  }
@@ -418,10 +456,135 @@ var CloudflareSandbox = class extends MastraSandbox {
418
456
  }
419
457
  };
420
458
  }
459
+ /**
460
+ * Mounts an S3-compatible bucket (R2, S3, MinIO, ...) at `mountPath` through
461
+ * the bridge's mount route. Called by MountManager for each Workspace `mounts`
462
+ * entry after start(). The Cloudflare Sandbox SDK forgets mounts when an idle
463
+ * container is stopped and does not restore them on wake, so
464
+ * {@link ensureMountsActive} re-mounts stale paths before each operation; that
465
+ * makes mounted paths the durable part of the filesystem.
466
+ */
467
+ async mount(filesystem, mountPath) {
468
+ validateMountPath(mountPath);
469
+ const sandboxId = this.requireSandboxId();
470
+ const config = filesystem.getMountConfig?.();
471
+ if (!config) {
472
+ const error = `Filesystem "${filesystem.id}" does not provide a mount config`;
473
+ this.mounts.set(mountPath, {
474
+ filesystem,
475
+ state: "error",
476
+ error
477
+ });
478
+ return {
479
+ success: false,
480
+ mountPath,
481
+ error
482
+ };
483
+ }
484
+ const translated = toMountRequest(config, mountPath);
485
+ if ("error" in translated) {
486
+ this.mounts.set(mountPath, {
487
+ filesystem,
488
+ state: "error",
489
+ config,
490
+ error: translated.error
491
+ });
492
+ return {
493
+ success: false,
494
+ mountPath,
495
+ error: translated.error
496
+ };
497
+ }
498
+ this.mounts.set(mountPath, {
499
+ filesystem,
500
+ state: "mounting",
501
+ config
502
+ });
503
+ try {
504
+ await this.client.mountBucket(sandboxId, translated.request);
505
+ } catch (cause) {
506
+ const error = cause instanceof Error ? cause.message : String(cause);
507
+ this.mounts.set(mountPath, {
508
+ filesystem,
509
+ state: "error",
510
+ config,
511
+ error
512
+ });
513
+ return {
514
+ success: false,
515
+ mountPath,
516
+ error
517
+ };
518
+ }
519
+ this.mounts.set(mountPath, {
520
+ filesystem,
521
+ state: "mounted",
522
+ config
523
+ });
524
+ this.lastUsedAt = /* @__PURE__ */ new Date();
525
+ return {
526
+ success: true,
527
+ mountPath
528
+ };
529
+ }
530
+ /** Unmounts a bucket previously mounted with {@link mount}. */
531
+ async unmount(mountPath) {
532
+ validateMountPath(mountPath);
533
+ const sandboxId = this.requireSandboxId();
534
+ await this.client.unmountBucket(sandboxId, mountPath);
535
+ this.mounts.delete(mountPath);
536
+ this.lastUsedAt = /* @__PURE__ */ new Date();
537
+ }
421
538
  getInstructions() {
422
- const defaultInstructions = "Commands execute in a remote Cloudflare Sandbox. Read and write persistent project files under /workspace.";
539
+ const mounted = [...this.mounts.entries].filter(([, entry]) => entry.state === "mounted").map(([path]) => path);
540
+ const defaultInstructions = mounted.length > 0 ? `Commands execute in a remote Cloudflare Sandbox. The container sleeps when idle and files under /workspace do NOT survive between commands, except under the mounted paths: ${mounted.join(", ")}. Keep anything that must persist under a mounted path.` : "Commands execute in a remote Cloudflare Sandbox. Use /workspace as scratch space only: the container sleeps when idle and files under /workspace do NOT survive between commands. Do not assume earlier files still exist.";
423
541
  return typeof this.instructions === "function" ? this.instructions({ defaultInstructions }) : this.instructions ?? defaultInstructions;
424
542
  }
543
+ /**
544
+ * A slept container boots fresh without its mounts: `@cloudflare/sandbox` keeps
545
+ * `activeMounts` in memory and clears it on stop, so it never re-mounts on wake,
546
+ * and `GET /running` still reports `true` until the DO next talks to the
547
+ * container. Before any operation that reads or writes the filesystem, probe the
548
+ * mounted paths with `mountpoint` and re-mount the ones that are gone. The pass
549
+ * is shared across concurrent callers, and there is no probe when nothing is
550
+ * mounted.
551
+ */
552
+ ensureMountsActive(sandboxId) {
553
+ const mountedPaths = [...this.mounts.entries].filter(([, entry]) => entry.state === "mounted").map(([mountPath]) => mountPath);
554
+ if (mountedPaths.length === 0) return Promise.resolve();
555
+ if (!this.ensureMountsPromise) this.ensureMountsPromise = this.remountStalePaths(sandboxId, mountedPaths).finally(() => {
556
+ this.ensureMountsPromise = void 0;
557
+ });
558
+ return this.ensureMountsPromise;
559
+ }
560
+ async remountStalePaths(sandboxId, mountedPaths) {
561
+ const script = `for p in ${mountedPaths.join(" ")}; do mountpoint -q "$p" || echo "$p"; done`;
562
+ const decoder = new TextDecoder();
563
+ let stdout = "";
564
+ await this.client.exec(sandboxId, {
565
+ argv: [
566
+ SHELL_PATH,
567
+ "-c",
568
+ script
569
+ ],
570
+ timeoutMs: this.commandTimeout
571
+ }, { onEvent: (event) => {
572
+ if (event.type === "stdout") stdout += decoder.decode(event.data, { stream: true });
573
+ } });
574
+ stdout += decoder.decode();
575
+ const stalePaths = stdout.split("\n").map((line) => line.trim()).filter(Boolean);
576
+ for (const mountPath of stalePaths) {
577
+ const entry = this.mounts.get(mountPath);
578
+ if (!entry?.config) continue;
579
+ const translated = toMountRequest(entry.config, mountPath);
580
+ if ("error" in translated) continue;
581
+ try {
582
+ await this.client.mountBucket(sandboxId, translated.request);
583
+ } catch (cause) {
584
+ this.logger?.warn(`Failed to re-mount ${mountPath} after container wake`, { error: cause });
585
+ }
586
+ }
587
+ }
425
588
  requireSandboxId() {
426
589
  if (!this.sandboxId) throw new Error(`Cloudflare Sandbox ${this.id} has not been started`);
427
590
  return this.sandboxId;
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 interface CloudflarePersistWorkspaceOptions {\n /** Relative paths (under /workspace) to exclude from the archive. */\n excludes?: string[];\n}\n\nexport interface CloudflareMountBucketCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n}\n\nexport interface CloudflareMountBucketOptions {\n /** S3-compatible endpoint, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n endpoint?: string;\n /** Mount the bucket read-only. */\n readOnly?: boolean;\n /** Only expose objects under this bucket prefix at the mount point. */\n prefix?: string;\n /** Storage provider hint, e.g. `r2`. */\n provider?: string;\n /** Explicit credentials; omitted when the Worker resolves them from secrets. */\n credentials?: CloudflareMountBucketCredentials;\n}\n\nexport interface CloudflareMountBucketRequest {\n /** Bucket name, e.g. `my-r2-bucket`. */\n bucket: string;\n /** Local filesystem path to mount at, e.g. `/mnt/data`. */\n mountPath: string;\n options?: CloudflareMountBucketOptions;\n}\n\nexport interface CloudflareCreateSessionRequest {\n /** Working directory the session starts in. */\n cwd?: string;\n /** Environment variables seeded into the session. */\n env?: Record<string, string>;\n /** Caller-chosen session id; must match `^[a-zA-Z0-9._-]{1,128}$`. Generated when omitted. */\n sessionId?: string;\n}\n\nexport interface CloudflareSession {\n id: 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 /** `GET /v1/sandbox/:id/file/*` — reads one file, returning its raw bytes. */\n async readFile(id: string, absolutePath: string): Promise<Uint8Array> {\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`, {});\n }\n\n /** `GET /v1/sandbox/:id/persist` — archives `/workspace`, returning raw tar bytes. */\n async persistWorkspace(id: string, options: CloudflarePersistWorkspaceOptions = {}): Promise<Uint8Array> {\n const query = options.excludes?.length ? `?excludes=${encodeURIComponent(options.excludes.join(','))}` : '';\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/persist${query}`, {});\n }\n\n /** `POST /v1/sandbox/:id/hydrate` — restores `/workspace` from a raw tar payload. */\n async hydrateWorkspace(id: string, tar: Uint8Array): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/hydrate`,\n {\n method: 'POST',\n body: tar as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/mount` — mounts an S3-compatible bucket as a local directory. */\n async mountBucket(id: string, request: CloudflareMountBucketRequest): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/mount`,\n {\n method: 'POST',\n body: JSON.stringify(request),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/unmount` — unmounts a previously mounted bucket. */\n async unmountBucket(id: string, mountPath: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/unmount`,\n {\n method: 'POST',\n body: JSON.stringify({ mountPath }),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/session` — creates an execution session, returning its id. */\n async createSession(id: string, request: CloudflareCreateSessionRequest = {}): Promise<CloudflareSession> {\n const body: Record<string, unknown> = {};\n if (request.cwd !== undefined) body.cwd = request.cwd;\n if (request.env !== undefined) body.env = request.env;\n if (request.sessionId !== undefined) body.id = request.sessionId;\n return this.request<CloudflareSession>(`/v1/sandbox/${encodeURIComponent(id)}/session`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'content-type': 'application/json' },\n });\n }\n\n /** `DELETE /v1/sandbox/:id/session/:sessionId` — tears down an execution session. */\n async deleteSession(id: string, sessionId: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/session/${encodeURIComponent(sessionId)}`,\n { method: 'DELETE' },\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 private async requestBytes(path: string, init: RequestInit): Promise<Uint8Array> {\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 return new Uint8Array(await response.arrayBuffer());\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, assertModesUnsupported } from '@mastra/core/workspace';\nimport {\n CloudflareSandboxBridgeClient,\n type CloudflarePersistWorkspaceOptions,\n type CloudflareSandboxBridgeClientOptions,\n} 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'\n | 'isRunning'\n | 'deleteSandbox'\n | 'writeFile'\n | 'readFile'\n | 'persistWorkspace'\n | 'hydrateWorkspace'\n | '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 * Absolute path to the shell used to interpret bare command strings. Absolute so it\n * resolves even when a custom PATH excludes the standard system directories.\n */\nconst SHELL_PATH = '/bin/bash';\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 *\n * When no separate arguments are supplied (the shape the built-in Workspace\n * `execute_command` tool uses), `command` is a shell command string — pipes,\n * chaining, quoting, redirection — so it is run through a non-login shell rather\n * than treated as a single executable name. When explicit arguments are given,\n * each element stays a literal argv token.\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 = args && args.length > 0 ? [command, ...args] : [SHELL_PATH, '-c', command];\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 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.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 assertModesUnsupported(files, 'Cloudflare');\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 /** Reads a single file under /workspace, returning its raw bytes. */\n async readFile(path: string): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path));\n this.lastUsedAt = new Date();\n return bytes;\n }\n\n /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */\n async persistWorkspace(options?: CloudflarePersistWorkspaceOptions): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n const archive = await this.client.persistWorkspace(sandboxId, options);\n this.lastUsedAt = new Date();\n return archive;\n }\n\n /** Restores /workspace from a raw tar payload produced by persistWorkspace. */\n async hydrateWorkspace(tar: Uint8Array): Promise<void> {\n const sandboxId = this.requireSandboxId();\n await this.client.hydrateWorkspace(sandboxId, tar);\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":";;;;AAgEA,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,MADc,KAAK,QAA8B,eAAe,mBAAmB,EAAE,EAAE,WAAW,CAAC,CAAC,EAAA,CAC7F,YAAY;CAC5B;;CAGA,MAAM,cAAc,IAA2B;EAC7C,MAAM,KA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,iBAAiB,WAAW,GAAG;EACjD,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 interface CloudflarePersistWorkspaceOptions {\n /** Relative paths (under /workspace) to exclude from the archive. */\n excludes?: string[];\n}\n\nexport interface CloudflareMountBucketCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n}\n\nexport interface CloudflareMountBucketOptions {\n /** S3-compatible endpoint, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n endpoint?: string;\n /** Mount the bucket read-only. */\n readOnly?: boolean;\n /** Only expose objects under this bucket prefix at the mount point. */\n prefix?: string;\n /** Storage provider hint, e.g. `r2`. */\n provider?: string;\n /** Explicit credentials; omitted when the Worker resolves them from secrets. */\n credentials?: CloudflareMountBucketCredentials;\n}\n\nexport interface CloudflareMountBucketRequest {\n /** Bucket name, e.g. `my-r2-bucket`. */\n bucket: string;\n /** Local filesystem path to mount at, e.g. `/mnt/data`. */\n mountPath: string;\n options?: CloudflareMountBucketOptions;\n}\n\nexport interface CloudflareCreateSessionRequest {\n /** Working directory the session starts in. */\n cwd?: string;\n /** Environment variables seeded into the session. */\n env?: Record<string, string>;\n /** Caller-chosen session id; must match `^[a-zA-Z0-9._-]{1,128}$`. Generated when omitted. */\n sessionId?: string;\n}\n\nexport interface CloudflareSession {\n id: 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 /** `GET /v1/sandbox/:id/file/*` — reads one file, returning its raw bytes. */\n async readFile(id: string, absolutePath: string): Promise<Uint8Array> {\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/file/${encodeFilePath(absolutePath)}`, {});\n }\n\n /** `GET /v1/sandbox/:id/persist` — archives `/workspace`, returning raw tar bytes. */\n async persistWorkspace(id: string, options: CloudflarePersistWorkspaceOptions = {}): Promise<Uint8Array> {\n const query = options.excludes?.length ? `?excludes=${encodeURIComponent(options.excludes.join(','))}` : '';\n return this.requestBytes(`/v1/sandbox/${encodeURIComponent(id)}/persist${query}`, {});\n }\n\n /** `POST /v1/sandbox/:id/hydrate` — restores `/workspace` from a raw tar payload. */\n async hydrateWorkspace(id: string, tar: Uint8Array): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/hydrate`,\n {\n method: 'POST',\n body: tar as RequestInit['body'],\n headers: { 'content-type': 'application/octet-stream' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/mount` — mounts an S3-compatible bucket as a local directory. */\n async mountBucket(id: string, request: CloudflareMountBucketRequest): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/mount`,\n {\n method: 'POST',\n body: JSON.stringify(request),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/unmount` — unmounts a previously mounted bucket. */\n async unmountBucket(id: string, mountPath: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/unmount`,\n {\n method: 'POST',\n body: JSON.stringify({ mountPath }),\n headers: { 'content-type': 'application/json' },\n },\n true,\n );\n }\n\n /** `POST /v1/sandbox/:id/session` — creates an execution session, returning its id. */\n async createSession(id: string, request: CloudflareCreateSessionRequest = {}): Promise<CloudflareSession> {\n const body: Record<string, unknown> = {};\n if (request.cwd !== undefined) body.cwd = request.cwd;\n if (request.env !== undefined) body.env = request.env;\n if (request.sessionId !== undefined) body.id = request.sessionId;\n return this.request<CloudflareSession>(`/v1/sandbox/${encodeURIComponent(id)}/session`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'content-type': 'application/json' },\n });\n }\n\n /** `DELETE /v1/sandbox/:id/session/:sessionId` — tears down an execution session. */\n async deleteSession(id: string, sessionId: string): Promise<void> {\n await this.request(\n `/v1/sandbox/${encodeURIComponent(id)}/session/${encodeURIComponent(sessionId)}`,\n { method: 'DELETE' },\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 private async requestBytes(path: string, init: RequestInit): Promise<Uint8Array> {\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 return new Uint8Array(await response.arrayBuffer());\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 FilesystemMountConfig,\n MastraSandboxOptions,\n MountManager,\n MountResult,\n ProviderStatus,\n SandboxFileInput,\n SandboxInfo,\n WorkspaceFilesystem,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, assertModesUnsupported } from '@mastra/core/workspace';\nimport {\n CloudflareSandboxBridgeClient,\n type CloudflareMountBucketRequest,\n type CloudflarePersistWorkspaceOptions,\n type CloudflareSandboxBridgeClientOptions,\n} 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'\n | 'isRunning'\n | 'deleteSandbox'\n | 'writeFile'\n | 'readFile'\n | 'persistWorkspace'\n | 'hydrateWorkspace'\n | 'mountBucket'\n | 'unmountBucket'\n | 'exec'\n>;\n\n/**\n * Mount config accepted by the Cloudflare bridge: any S3-compatible bucket\n * (R2, S3, MinIO, ...) as produced by `S3Filesystem.getMountConfig()`.\n * Declared structurally so this package does not depend on `@mastra/s3`.\n */\ninterface S3CompatibleMountConfig extends FilesystemMountConfig {\n type: 's3';\n bucket: string;\n region?: string;\n endpoint?: string;\n accessKeyId?: string;\n secretAccessKey?: string;\n sessionToken?: string;\n prefix?: string;\n readOnly?: boolean;\n}\n\n/** Allowlist pattern for mount paths, matching the other remote sandbox providers. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\n\nfunction validateMountPath(mountPath: string): void {\n if (!SAFE_MOUNT_PATH.test(mountPath)) {\n throw new Error(\n `Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`,\n );\n }\n}\n\n/**\n * Translates a Workspace mount config into the bridge's mount request, or\n * explains why the bridge cannot serve it. The bridge mounts S3-compatible\n * buckets with s3fs; GCS and Azure mount configs have no equivalent route.\n */\nfunction toMountRequest(\n config: FilesystemMountConfig,\n mountPath: string,\n): { request: CloudflareMountBucketRequest } | { error: string } {\n if (config.type !== 's3') {\n return { error: `Cloudflare Sandbox can only mount S3-compatible buckets; got mount type \"${config.type}\"` };\n }\n const s3 = config as S3CompatibleMountConfig;\n if (s3.sessionToken) {\n return { error: 'Cloudflare Sandbox bucket mounts do not support temporary credentials (sessionToken)' };\n }\n if (Boolean(s3.accessKeyId) !== Boolean(s3.secretAccessKey)) {\n return { error: 'Cloudflare Sandbox bucket mounts need both accessKeyId and secretAccessKey, or neither' };\n }\n // The bridge treats a request with no endpoint as an R2 binding mount, so a\n // region-only AWS filesystem must resolve to an explicit S3 endpoint.\n const endpoint = s3.endpoint ?? (s3.region ? `https://s3.${s3.region}.amazonaws.com` : undefined);\n // The bridge requires the prefix to start with `/`; S3Filesystem emits `dir/`.\n const prefix = s3.prefix ? (s3.prefix.startsWith('/') ? s3.prefix : `/${s3.prefix}`) : undefined;\n return {\n request: {\n bucket: s3.bucket,\n mountPath,\n options: {\n endpoint,\n prefix,\n readOnly: s3.readOnly,\n credentials:\n s3.accessKeyId && s3.secretAccessKey\n ? { accessKeyId: s3.accessKeyId, secretAccessKey: s3.secretAccessKey }\n : undefined,\n },\n },\n };\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 * Absolute path to the shell used to interpret bare command strings. Absolute so it\n * resolves even when a custom PATH excludes the standard system directories.\n */\nconst SHELL_PATH = '/bin/bash';\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 *\n * When no separate arguments are supplied (the shape the built-in Workspace\n * `execute_command` tool uses), `command` is a shell command string — pipes,\n * chaining, quoting, redirection — so it is run through a non-login shell rather\n * than treated as a single executable name. When explicit arguments are given,\n * each element stays a literal argv token.\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 = args && args.length > 0 ? [command, ...args] : [SHELL_PATH, '-c', command];\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 /** Created by MastraSandbox because this class implements mount(). */\n declare readonly mounts: MountManager;\n\n private readonly client: BridgeClient;\n private readonly commandTimeout: number;\n private readonly instructions?: InstructionsOption;\n private sandboxId?: string;\n private createdAt = new Date();\n private lastUsedAt?: Date;\n /** Shared across concurrent callers so a wake triggers a single re-mount pass. */\n private ensureMountsPromise?: Promise<void>;\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.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 await this.ensureMountsActive(sandboxId);\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 assertModesUnsupported(files, 'Cloudflare');\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\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 /** Reads a single file under /workspace, returning its raw bytes. */\n async readFile(path: string): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n const bytes = await this.client.readFile(sandboxId, resolveWorkspacePath(path));\n this.lastUsedAt = new Date();\n return bytes;\n }\n\n /** Archives /workspace, returning raw tar bytes that can later restore it via hydrateWorkspace. */\n async persistWorkspace(options?: CloudflarePersistWorkspaceOptions): Promise<Uint8Array> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n const archive = await this.client.persistWorkspace(sandboxId, options);\n this.lastUsedAt = new Date();\n return archive;\n }\n\n /** Restores /workspace from a raw tar payload produced by persistWorkspace. */\n async hydrateWorkspace(tar: Uint8Array): Promise<void> {\n const sandboxId = this.requireSandboxId();\n await this.ensureMountsActive(sandboxId);\n await this.client.hydrateWorkspace(sandboxId, tar);\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 /**\n * Mounts an S3-compatible bucket (R2, S3, MinIO, ...) at `mountPath` through\n * the bridge's mount route. Called by MountManager for each Workspace `mounts`\n * entry after start(). The Cloudflare Sandbox SDK forgets mounts when an idle\n * container is stopped and does not restore them on wake, so\n * {@link ensureMountsActive} re-mounts stale paths before each operation; that\n * makes mounted paths the durable part of the filesystem.\n */\n async mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult> {\n validateMountPath(mountPath);\n const sandboxId = this.requireSandboxId();\n\n const config = filesystem.getMountConfig?.();\n if (!config) {\n const error = `Filesystem \"${filesystem.id}\" does not provide a mount config`;\n this.mounts.set(mountPath, { filesystem, state: 'error', error });\n return { success: false, mountPath, error };\n }\n\n const translated = toMountRequest(config, mountPath);\n if ('error' in translated) {\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: translated.error });\n return { success: false, mountPath, error: translated.error };\n }\n\n this.mounts.set(mountPath, { filesystem, state: 'mounting', config });\n try {\n await this.client.mountBucket(sandboxId, translated.request);\n } catch (cause) {\n const error = cause instanceof Error ? cause.message : String(cause);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n this.mounts.set(mountPath, { filesystem, state: 'mounted', config });\n this.lastUsedAt = new Date();\n return { success: true, mountPath };\n }\n\n /** Unmounts a bucket previously mounted with {@link mount}. */\n async unmount(mountPath: string): Promise<void> {\n validateMountPath(mountPath);\n const sandboxId = this.requireSandboxId();\n await this.client.unmountBucket(sandboxId, mountPath);\n this.mounts.delete(mountPath);\n this.lastUsedAt = new Date();\n }\n\n getInstructions(): string {\n const mounted = [...this.mounts.entries].filter(([, entry]) => entry.state === 'mounted').map(([path]) => path);\n const defaultInstructions =\n mounted.length > 0\n ? `Commands execute in a remote Cloudflare Sandbox. The container sleeps when idle and files under /workspace do NOT survive between commands, except under the mounted paths: ${mounted.join(', ')}. Keep anything that must persist under a mounted path.`\n : 'Commands execute in a remote Cloudflare Sandbox. Use /workspace as scratch space only: the container sleeps when idle and files under /workspace do NOT survive between commands. Do not assume earlier files still exist.';\n return typeof this.instructions === 'function'\n ? this.instructions({ defaultInstructions })\n : (this.instructions ?? defaultInstructions);\n }\n\n /**\n * A slept container boots fresh without its mounts: `@cloudflare/sandbox` keeps\n * `activeMounts` in memory and clears it on stop, so it never re-mounts on wake,\n * and `GET /running` still reports `true` until the DO next talks to the\n * container. Before any operation that reads or writes the filesystem, probe the\n * mounted paths with `mountpoint` and re-mount the ones that are gone. The pass\n * is shared across concurrent callers, and there is no probe when nothing is\n * mounted.\n */\n private ensureMountsActive(sandboxId: string): Promise<void> {\n const mountedPaths = [...this.mounts.entries]\n .filter(([, entry]) => entry.state === 'mounted')\n .map(([mountPath]) => mountPath);\n if (mountedPaths.length === 0) return Promise.resolve();\n if (!this.ensureMountsPromise) {\n this.ensureMountsPromise = this.remountStalePaths(sandboxId, mountedPaths).finally(() => {\n this.ensureMountsPromise = undefined;\n });\n }\n return this.ensureMountsPromise;\n }\n\n private async remountStalePaths(sandboxId: string, mountedPaths: string[]): Promise<void> {\n // Mount paths are validated against SAFE_MOUNT_PATH, so they are safe to embed\n // directly. `mountpoint -q` exits non-zero for a path that is no longer a mount,\n // and that path is echoed so a single exec reports every stale mount at once.\n const script = `for p in ${mountedPaths.join(' ')}; do mountpoint -q \"$p\" || echo \"$p\"; done`;\n const decoder = new TextDecoder();\n let stdout = '';\n await this.client.exec(\n sandboxId,\n { argv: [SHELL_PATH, '-c', script], timeoutMs: this.commandTimeout },\n {\n onEvent: event => {\n if (event.type === 'stdout') stdout += decoder.decode(event.data, { stream: true });\n },\n },\n );\n stdout += decoder.decode();\n\n const stalePaths = stdout\n .split('\\n')\n .map(line => line.trim())\n .filter(Boolean);\n for (const mountPath of stalePaths) {\n const entry = this.mounts.get(mountPath);\n if (!entry?.config) continue;\n const translated = toMountRequest(entry.config, mountPath);\n if ('error' in translated) continue;\n try {\n await this.client.mountBucket(sandboxId, translated.request);\n } catch (cause) {\n this.logger?.warn(`Failed to re-mount ${mountPath} after container wake`, { error: cause });\n }\n }\n }\n\n private requireSandboxId(): string {\n if (!this.sandboxId) throw new Error(`Cloudflare S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,wBAAwB,EAAE,OAAO,MAAM,CAAC;GAC5F;EACF;CACF;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
@@ -1,10 +1,10 @@
1
- import type { CommandResult, ExecuteCommandOptions, MastraSandboxOptions, ProviderStatus, SandboxFileInput, SandboxInfo } from '@mastra/core/workspace';
1
+ import type { CommandResult, ExecuteCommandOptions, MastraSandboxOptions, MountManager, MountResult, ProviderStatus, SandboxFileInput, SandboxInfo, WorkspaceFilesystem } from '@mastra/core/workspace';
2
2
  import { MastraSandbox } from '@mastra/core/workspace';
3
3
  import { CloudflareSandboxBridgeClient, type CloudflarePersistWorkspaceOptions, type CloudflareSandboxBridgeClientOptions } from './bridge-client.js';
4
4
  type InstructionsOption = string | ((options: {
5
5
  defaultInstructions: string;
6
6
  }) => string);
7
- type BridgeClient = Pick<CloudflareSandboxBridgeClient, 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'readFile' | 'persistWorkspace' | 'hydrateWorkspace' | 'exec'>;
7
+ type BridgeClient = Pick<CloudflareSandboxBridgeClient, 'createSandbox' | 'isRunning' | 'deleteSandbox' | 'writeFile' | 'readFile' | 'persistWorkspace' | 'hydrateWorkspace' | 'mountBucket' | 'unmountBucket' | 'exec'>;
8
8
  export interface CloudflareSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {
9
9
  /** URL of a deployed Cloudflare Sandbox Bridge Worker. */
10
10
  baseUrl: string;
@@ -34,12 +34,16 @@ export declare class CloudflareSandbox extends MastraSandbox {
34
34
  readonly name: string;
35
35
  readonly provider = "cloudflare-sandbox";
36
36
  status: ProviderStatus;
37
+ /** Created by MastraSandbox because this class implements mount(). */
38
+ readonly mounts: MountManager;
37
39
  private readonly client;
38
40
  private readonly commandTimeout;
39
41
  private readonly instructions?;
40
42
  private sandboxId?;
41
43
  private createdAt;
42
44
  private lastUsedAt?;
45
+ /** Shared across concurrent callers so a wake triggers a single re-mount pass. */
46
+ private ensureMountsPromise?;
43
47
  constructor(options: CloudflareSandboxOptions);
44
48
  start(): Promise<void>;
45
49
  stop(): Promise<void>;
@@ -53,7 +57,29 @@ export declare class CloudflareSandbox extends MastraSandbox {
53
57
  /** Restores /workspace from a raw tar payload produced by persistWorkspace. */
54
58
  hydrateWorkspace(tar: Uint8Array): Promise<void>;
55
59
  getInfo(): SandboxInfo;
60
+ /**
61
+ * Mounts an S3-compatible bucket (R2, S3, MinIO, ...) at `mountPath` through
62
+ * the bridge's mount route. Called by MountManager for each Workspace `mounts`
63
+ * entry after start(). The Cloudflare Sandbox SDK forgets mounts when an idle
64
+ * container is stopped and does not restore them on wake, so
65
+ * {@link ensureMountsActive} re-mounts stale paths before each operation; that
66
+ * makes mounted paths the durable part of the filesystem.
67
+ */
68
+ mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult>;
69
+ /** Unmounts a bucket previously mounted with {@link mount}. */
70
+ unmount(mountPath: string): Promise<void>;
56
71
  getInstructions(): string;
72
+ /**
73
+ * A slept container boots fresh without its mounts: `@cloudflare/sandbox` keeps
74
+ * `activeMounts` in memory and clears it on stop, so it never re-mounts on wake,
75
+ * and `GET /running` still reports `true` until the DO next talks to the
76
+ * container. Before any operation that reads or writes the filesystem, probe the
77
+ * mounted paths with `mountpoint` and re-mount the ones that are gone. The pass
78
+ * is shared across concurrent callers, and there is no probe when nothing is
79
+ * mounted.
80
+ */
81
+ private ensureMountsActive;
82
+ private remountStalePaths;
57
83
  private requireSandboxId;
58
84
  }
59
85
  export {};
@@ -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,CAAC;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rD;IAED,OAAO,IAAI,WAAW,CAarB;IAED;;;;;;;OAOG;IACG,KAAK,CAAC,UAAU,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CA4BpF;IAED,+DAA+D;IACzD,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM9C;IAED,eAAe,IAAI,MAAM,CASxB;IAED;;;;;;;;OAQG;IACH,OAAO,CAAC,kBAAkB;YAaZ,iBAAiB;IAmC/B,OAAO,CAAC,gBAAgB;CAIzB"}
@@ -42,8 +42,16 @@ export interface FakeBridge {
42
42
  mounts: unknown[];
43
43
  /** Bodies received by `POST /unmount`. */
44
44
  unmounts: unknown[];
45
+ /** Mount paths the SDK currently considers active (cleared by {@link FakeBridge.sleep}). */
46
+ activeMounts: Set<string>;
45
47
  /** Live session ids created via `POST /session`. */
46
48
  sessions: Set<string>;
49
+ /**
50
+ * Models `@cloudflare/sandbox` stopping an idle container: scratch files and the
51
+ * in-memory `activeMounts` are dropped, but the sandbox id survives and boots a
52
+ * fresh container on next use.
53
+ */
54
+ sleep: () => void;
47
55
  /** Overrides the default `echo`-only behaviour. */
48
56
  onExec?: (request: FakeExecRequest) => FakeExecResult;
49
57
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fake-bridge.d.ts","sourceRoot":"","sources":["../../src/testing/fake-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+CAA+C;IAC/C,KAAK,CAAC,EAAE;QAAE,KAAK,EAAE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AM,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,cAAc,CAAC;CACvD;AA6BD,wBAAgB,gBAAgB,CAAC,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,UAAU,CAgJlG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/cloudflare-sandbox",
3
- "version": "0.4.0",
3
+ "version": "0.5.0-alpha.0",
4
4
  "description": "Cloudflare Sandbox provider for Mastra workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,17 +21,17 @@
21
21
  "license": "Apache-2.0",
22
22
  "devDependencies": {
23
23
  "@types/node": "22.19.15",
24
- "@vitest/coverage-v8": "4.1.10",
25
- "@vitest/ui": "4.1.10",
24
+ "@vitest/coverage-v8": "4.1.11",
25
+ "@vitest/ui": "4.1.11",
26
26
  "dotenv": "^17.4.2",
27
27
  "eslint": "^10.7.0",
28
28
  "tsdown": "0.22.9",
29
29
  "typescript": "^7.0.2",
30
- "vitest": "4.1.10",
30
+ "vitest": "4.1.11",
31
31
  "@internal/lint": "0.0.133",
32
- "@internal/types-builder": "0.0.108",
33
32
  "@internal/workspace-test-utils": "0.0.77",
34
- "@mastra/core": "1.67.0"
33
+ "@internal/types-builder": "0.0.108",
34
+ "@mastra/core": "1.68.0-alpha.5"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@mastra/core": ">=1.67.0-0 <2.0.0-0"