@vite-hub/sandbox 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -446,6 +446,7 @@ The Definition entrypoint does not import `@vite-hub/sandbox/task`. ViteHub call
446
446
  - Set `cpu` (vCPUs) and `memory` (MiB) next to `driver`, such as `hubSandboxTask({ driver: "cloudflare", cpu: 1, memory: 4096 })`. They are minimums, and ViteHub picks the smallest driver size that fits both. Vercel gets `resources.vcpus`: 1 or an even number up to 32, with 2048 MiB for each vCPU. Cloudflare gets the smallest instance type from `lite` to `standard-4`, and the default is `standard-1` (1/2 vCPU, 4096 MiB). On Cloudflare the size belongs to the Container class, so it applies to every task of the app. ViteHub keeps the `instance_type` of your own `containers` entry and fails the build when it is smaller than `cpu` or `memory`. `maxInstances` sets the Cloudflare Container limit (default 12).
447
447
  - Driver selection belongs to application or host configuration, not to a Definition. `hubSandboxTask({ driver: "vercel" })` and `hubSandboxTask({ driver: "cloudflare" })` are the direct-package forms. The `vite-hub` distribution infers the driver from its Vercel and Cloudflare hosts, and takes the same options in `vitehub({ sandboxTask: { ... } })`.
448
448
  - `vitehub.sandboxTask.timeout` must be a positive integer no greater than `2_147_483_647`. Without it, a run stops after 5 minutes on every driver. It bounds one execution attempt after driver startup, including package preparation, staging, and execution. Queueing, Sandbox startup, and retry delays can make the complete `runSandboxTask()` call take longer. An elapsed attempt timeout sends an internal abort signal to cancellable driver operations and returns `SANDBOX_TASK_RUN_FAILED` with `error.data.code` set to `SANDBOX_TASK_TIMEOUT` and status 504. On Vercel, the Sandbox session gets the task timeout plus 30 seconds, because its clock starts before Sandbox setup. ViteHub then ends the run at the task timeout, not the VM.
449
+ - `vitehub.sandboxTask.transfer` accepts the same transfer limits as `defineSandboxTask()`.
449
450
  - Pass `signal` to `runSandboxTask()` when it belongs to a request or Agent Invocation. ViteHub forwards it to Sandbox startup and execution, cancels queued Cloudflare runs and retry backoff, and preserves the caller's abort reason. A Definition timeout remains the independent bound for each execution attempt.
450
451
  - A failed run returns `SANDBOX_TASK_RUN_FAILED`. `error.cause` keeps the failure's code, message, and every detail for server logs. `toResponse(error)` from `@vite-hub/runtime` sends only `code`, `why`, and `fix`, so no stack or process output reaches the client. `resolveSandboxTaskRunner(name).run()` throws the same failure.
451
452
  - Vercel Sandbox sessions are closed in a `finally` block after success or failure. Cloudflare also creates and closes a unique Sandbox for each run unless you configure `sandboxId` or pass one to `runSandboxTask()`. Session cleanup failures return an error, even after a successful handler. So do Cloudflare invocation-file cleanup failures in a Sandbox that stays open after the run. A Sandbox that ViteHub closes after the run loses its files when it closes, so ViteHub does not delete them separately.
@@ -471,6 +472,25 @@ The descriptor reports the provider's complete `ExecutionAuthority`, including d
471
472
 
472
473
  Payloads, context, and results must be JSON-serializable. Nested `Blob` and `Uint8Array` values cross the Sandbox boundary through invocation-local binary files, and Node.js `Buffer` values retain their type.
473
474
 
475
+ ViteHub limits what one run can send across the Sandbox boundary. The payload and context JSON can have at most 4 MiB of UTF-8 text, and so can the result JSON. Each direction can also have at most 64 binary files, 64 MiB of binary data, and 32 levels of nested arrays and objects. Set `transfer` on a Definition to change these limits:
476
+
477
+ ```ts
478
+ import { defineSandboxTask } from "@vite-hub/sandbox/task";
479
+
480
+ export default defineSandboxTask({
481
+ transfer: {
482
+ maxInputBytes: 2_097_152,
483
+ maxOutputBytes: 8_388_608,
484
+ maxDepth: 24,
485
+ maxSidecars: 16,
486
+ maxSidecarBytes: 16_777_216,
487
+ },
488
+ handler: async (payload: { image: Blob }) => payload,
489
+ });
490
+ ```
491
+
492
+ Each limit is a whole number from 1 to 1073741824. A run that exceeds a limit fails with `SANDBOX_TASK_TRANSFER_LIMIT`. For input, the run fails before the handler starts and before ViteHub writes a binary file. For output, the run fails before ViteHub parses the result or reads a binary file. The byte limits count the UTF-8 JSON and the bytes of the binary values. The provider still sets its own execution and timeout limits.
493
+
474
494
  ### Package projects
475
495
 
476
496
  ViteHub uses the package manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` moves preparation to the pnpm Workspace root and carries the transitive `workspace:*` dependency closure into the Sandbox while the entrypoint still runs from its package directory.
@@ -58,7 +58,7 @@ const sandboxTaskErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
58
58
  },
59
59
  SANDBOX_TASK_C0007: {
60
60
  ...dynamicError,
61
- fix: "Write `timeout`, `env`, and `project` in `defineSandboxTask()` as `key: value` with a literal value. Only `handler` can be a method."
61
+ fix: "Write `timeout`, `env`, `transfer`, and `project` in `defineSandboxTask()` as `key: value` with a literal value. Only `handler` can be a method."
62
62
  },
63
63
  SANDBOX_TASK_C0008: {
64
64
  ...dynamicError,
@@ -214,7 +214,7 @@ const sandboxTaskErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
214
214
  },
215
215
  SANDBOX_TASK_C0012: {
216
216
  ...dynamicError,
217
- fix: "Use only the `handler`, `timeout`, `env`, and `project` options in `defineSandboxTask()`. Remove the other keys that the message lists."
217
+ fix: "Use only the `handler`, `timeout`, `env`, `transfer`, and `project` options in `defineSandboxTask()`. Remove the other keys that the message lists."
218
218
  },
219
219
  SANDBOX_TASK_C0013: {
220
220
  ...dynamicError,
@@ -294,7 +294,7 @@ const sandboxTaskErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
294
294
  },
295
295
  SANDBOX_TASK_R0069: {
296
296
  ...dynamicError,
297
- fix: "Remove the options that the message names from `defineSandboxTask()`. A Definition supports only `handler`, `timeout`, `env`, and `project`."
297
+ fix: "Remove the options that the message names from `defineSandboxTask()`. A Definition supports only `handler`, `timeout`, `env`, `transfer`, and `project`."
298
298
  },
299
299
  SANDBOX_TASK_R0070: {
300
300
  ...dynamicError,
@@ -356,6 +356,10 @@ const sandboxTaskErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
356
356
  why: ({ max, provider, size }) => `[vitehub] ${provider} has no Sandbox size for ${size}. The largest size is ${max}.`,
357
357
  fix: "Lower `cpu` or `memory` in the Sandbox Task options. On Cloudflare the largest Container has 4 vCPU and 12288 MiB memory. On Vercel the largest Sandbox has 32 vCPU and 65536 MiB memory, and your plan can allow fewer."
358
358
  },
359
+ SANDBOX_TASK_TRANSFER_INVALID: {
360
+ why: ({ problem }) => `[vitehub] The \`transfer\` option of the Sandbox Task Definition ${problem}.`,
361
+ fix: "Set `transfer` in `defineSandboxTask()` or `vitehub.sandboxTask.transfer` in `package.json` to an object that uses only `maxInputBytes`, `maxOutputBytes`, `maxDepth`, `maxSidecars`, and `maxSidecarBytes`. Set each one to a whole number from 1 to 1073741824, or remove it."
362
+ },
359
363
  SANDBOX_TASK_VERCEL_TIMEOUT_LIMIT: {
360
364
  why: ({ limit, timeout }) => `Vercel rejected the Sandbox session timeout of ${timeout}ms: ${limit}.`,
361
365
  fix: "Set a lower Sandbox Task `timeout`. Vercel allows up to 45 minutes on Hobby and 24 hours on Pro. The Vercel session gets the task timeout plus 30 seconds."
@@ -102,13 +102,26 @@ type SandboxTaskRunArguments<TPayload> = undefined extends TPayload ? [payload?:
102
102
  type SandboxTaskDefinitionHandler<TPayload = unknown, TResult = unknown> = (payload: TPayload, context: Record<string, unknown>) => TResult | Promise<TResult>;
103
103
  type SandboxTaskDefinitionPayload<THandler extends (...args: any[]) => any> = Parameters<THandler> extends [infer TPayload, ...unknown[]] ? TPayload : unknown;
104
104
  type SandboxTaskDefinitionResult<THandler extends (...args: any[]) => any> = Awaited<ReturnType<THandler>>;
105
+ /** The limits on the values that cross the Sandbox boundary. Each limit is a whole number from 1 to 1073741824. */
106
+ interface SandboxTaskTransferOptions {
107
+ /** The largest payload and context JSON, in UTF-8 bytes. Default: 4194304 (4 MiB). */
108
+ maxInputBytes?: number;
109
+ /** The largest result JSON, in UTF-8 bytes. Default: 4194304 (4 MiB). */
110
+ maxOutputBytes?: number;
111
+ /** The deepest nesting of arrays and objects in one direction. Default: 32. */
112
+ maxDepth?: number;
113
+ /** The largest number of `Blob`, `Uint8Array`, and `Buffer` values in one direction. Default: 64. */
114
+ maxSidecars?: number;
115
+ /** The largest total size of the binary values in one direction, in bytes. Default: 67108864 (64 MiB). */
116
+ maxSidecarBytes?: number;
117
+ }
105
118
  interface SandboxTaskDefinitionOptions {
106
119
  timeout?: number;
107
120
  env?: Record<string, string>;
121
+ /** The limits on the payload, the context, and the result of a run. */
122
+ transfer?: SandboxTaskTransferOptions;
108
123
  }
109
- interface SandboxTaskProjectOptions {
110
- timeout?: number;
111
- }
124
+ type SandboxTaskProjectOptions = Pick<SandboxTaskDefinitionOptions, 'timeout' | 'transfer'>;
112
125
  interface SandboxTaskDefinitionInput<TPayload = unknown, TResult = unknown> extends SandboxTaskDefinitionOptions {
113
126
  /** Force project packaging on or off. Omit to detect project use automatically. */
114
127
  project?: boolean;
@@ -127,4 +140,4 @@ type SandboxTaskDefinitionFromHandler<THandler extends (...args: any[]) => any>
127
140
  */
128
141
  type SandboxTaskRunResult<TResult = unknown> = [error: ReturnType<typeof sandboxTaskRunErrors.SANDBOX_TASK_RUN_FAILED>, data: undefined] | [error: undefined, data: TResult];
129
142
  declare function getSandboxTaskFeatureDriver(config?: AgentSandboxTaskConfig | false): SandboxTaskDefinitionDriverOptions | undefined;
130
- export { VercelSandboxTaskDriverOptions as _, SandboxTaskDefinitionBundle as a, SandboxTaskDefinitionHandler as c, SandboxTaskDevOptions as d, SandboxTaskDriver as f, SandboxTaskRunResult as g, SandboxTaskRunArguments as h, SandboxTaskDefinition as i, SandboxTaskDefinitionInput as l, SandboxTaskProjectOptions as m, CloudflareSandboxTaskDefinitionDriverOptions as n, SandboxTaskDefinitionDriverOptions as o, SandboxTaskExecutionOptions as p, CloudflareSandboxTaskOptions as r, SandboxTaskDefinitionFromHandler as s, AgentSandboxTaskConfig as t, SandboxTaskDefinitionOptions as u, getSandboxTaskFeatureDriver as v, SandboxTaskSizeOptions as y };
143
+ export { SandboxTaskTransferOptions as _, SandboxTaskDefinitionBundle as a, SandboxTaskSizeOptions as b, SandboxTaskDefinitionHandler as c, SandboxTaskDevOptions as d, SandboxTaskDriver as f, SandboxTaskRunResult as g, SandboxTaskRunArguments as h, SandboxTaskDefinition as i, SandboxTaskDefinitionInput as l, SandboxTaskProjectOptions as m, CloudflareSandboxTaskDefinitionDriverOptions as n, SandboxTaskDefinitionDriverOptions as o, SandboxTaskExecutionOptions as p, CloudflareSandboxTaskOptions as r, SandboxTaskDefinitionFromHandler as s, AgentSandboxTaskConfig as t, SandboxTaskDefinitionOptions as u, VercelSandboxTaskDriverOptions as v, getSandboxTaskFeatureDriver as y };
@@ -1,5 +1,5 @@
1
1
  import { l as Sandbox } from "./index-D9DogaoF.js";
2
- import { f as SandboxTaskDriver, o as SandboxTaskDefinitionDriverOptions, u as SandboxTaskDefinitionOptions } from "./module-types-B3uJG1po.js";
2
+ import { f as SandboxTaskDriver, o as SandboxTaskDefinitionDriverOptions, u as SandboxTaskDefinitionOptions } from "./module-types-DHr6oC3h.js";
3
3
  import { ExecutionAuthority } from "@vite-hub/runtime";
4
4
  /** `local` runs a Sandbox Task as a process on this machine, which only `vite dev` does. */
5
5
  type SandboxTaskExecutionProvider = 'cloudflare' | 'vercel' | 'local';
@@ -1,5 +1,6 @@
1
1
  import { t as getActiveCloudflareEnv } from "./cloudflare-env-lookup-BNbNil7g.js";
2
- import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-ClSiUwCm.js";
2
+ import { t as assertSandboxTaskTransferOptions } from "./transfer-options-LTUzbHDw.js";
3
+ import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-D9n0ZmdN.js";
3
4
  import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
4
5
  // src/task/sandbox-task/errors.ts
5
6
  function sanitizeSandboxTaskDetail(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
@@ -63,7 +64,11 @@ const isVercel = () => {
63
64
  return !!(env.VERCEL || env.VERCEL_ENV);
64
65
  };
65
66
  // src/task/runtime/provider-resolution.ts
66
- const allowedDefinitionKeys = /* @__PURE__ */ new Set(["timeout", "env"]);
67
+ const allowedDefinitionKeys = /* @__PURE__ */ new Set([
68
+ "timeout",
69
+ "env",
70
+ "transfer"
71
+ ]);
67
72
  const maxTimeout = 2147483647;
68
73
  /** The timeout of a Sandbox Task run that sets no `timeout`, on every provider. */
69
74
  const DEFAULT_SANDBOX_TASK_TIMEOUT_MS = 3e5;
@@ -112,8 +117,9 @@ function unsupportedHostedSandboxTaskProviderError(provider) {
112
117
  }
113
118
  function assertSandboxTaskDefinitionOptions(local) {
114
119
  const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
115
- if (invalidKeys.length > 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0069({ message: `[vitehub] Sandbox Task Definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}` });
120
+ if (invalidKeys.length > 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0069({ message: `[vitehub] Sandbox Task Definition options only support timeout, env, and transfer. Unsupported: ${invalidKeys.join(", ")}` });
116
121
  if (local.timeout !== void 0 && (!Number.isInteger(local.timeout) || local.timeout <= 0 || local.timeout > maxTimeout)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0070({ message: `[vitehub] Sandbox Task Definition timeout must be a positive integer no greater than ${maxTimeout}.` });
122
+ assertSandboxTaskTransferOptions(local.transfer);
117
123
  }
118
124
  async function resolveTaskSandbox(provider, providerOptions, local) {
119
125
  return await (await (await import("#vitehub-sandbox-task-provider-loader")).loadSandboxTaskRuntimeProvider(provider)).resolveTaskSandbox({
@@ -1,4 +1,4 @@
1
- import { _ as VercelSandboxTaskDriverOptions, a as SandboxTaskDefinitionBundle, c as SandboxTaskDefinitionHandler, d as SandboxTaskDevOptions, f as SandboxTaskDriver, g as SandboxTaskRunResult, h as SandboxTaskRunArguments, i as SandboxTaskDefinition, l as SandboxTaskDefinitionInput, m as SandboxTaskProjectOptions, n as CloudflareSandboxTaskDefinitionDriverOptions, o as SandboxTaskDefinitionDriverOptions, p as SandboxTaskExecutionOptions, r as CloudflareSandboxTaskOptions, s as SandboxTaskDefinitionFromHandler, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionOptions, v as getSandboxTaskFeatureDriver, y as SandboxTaskSizeOptions } from "../module-types-B3uJG1po.js";
1
+ import { _ as SandboxTaskTransferOptions, a as SandboxTaskDefinitionBundle, b as SandboxTaskSizeOptions, c as SandboxTaskDefinitionHandler, d as SandboxTaskDevOptions, f as SandboxTaskDriver, g as SandboxTaskRunResult, h as SandboxTaskRunArguments, i as SandboxTaskDefinition, l as SandboxTaskDefinitionInput, m as SandboxTaskProjectOptions, n as CloudflareSandboxTaskDefinitionDriverOptions, o as SandboxTaskDefinitionDriverOptions, p as SandboxTaskExecutionOptions, r as CloudflareSandboxTaskOptions, s as SandboxTaskDefinitionFromHandler, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionOptions, v as VercelSandboxTaskDriverOptions, y as getSandboxTaskFeatureDriver } from "../module-types-DHr6oC3h.js";
2
2
  import { ExecutionAuthority, ViteHubContext } from "@vite-hub/runtime";
3
3
  import { Buffer } from "node:buffer";
4
4
  import { SandboxTaskDefinitionModules } from "#vitehub-sandbox-task-registry";
@@ -61,4 +61,4 @@ type ResolvedSandboxTaskRunner<TPayload, TResult> = Omit<SandboxTaskRunner, 'run
61
61
  };
62
62
  export declare function resolveSandboxTaskRunner<const TName extends SandboxTaskDefinitionName>(name: TName): Promise<ResolvedSandboxTaskRunner<SandboxTaskPayload<SandboxTaskRegistryDefinition<TName>>, SandboxTaskResult<SandboxTaskRegistryDefinition<TName>>>>;
63
63
  export declare function resolveSandboxTaskRunner<TPayload = unknown, TResult = unknown>(name?: string): Promise<ResolvedSandboxTaskRunner<TPayload, TResult>>;
64
- export type { AgentSandboxTaskConfig, CloudflareSandboxTaskDefinitionDriverOptions, CloudflareSandboxTaskOptions, SandboxTaskDefinition, SandboxTaskDefinitionBundle, SandboxTaskDefinitionDriverOptions, SandboxTaskDefinitionFromHandler, SandboxTaskDefinitionHandler, SandboxTaskDefinitionInput, SandboxTaskDefinitionOptions, SandboxTaskDevOptions, SandboxTaskDriver, SandboxTaskExecutionOptions, SandboxTaskProjectOptions, SandboxTaskRunArguments, SandboxTaskRunResult, SandboxTaskRunner, SandboxTaskSizeOptions, VercelSandboxTaskDriverOptions, getSandboxTaskFeatureDriver };
64
+ export type { AgentSandboxTaskConfig, CloudflareSandboxTaskDefinitionDriverOptions, CloudflareSandboxTaskOptions, SandboxTaskDefinition, SandboxTaskDefinitionBundle, SandboxTaskDefinitionDriverOptions, SandboxTaskDefinitionFromHandler, SandboxTaskDefinitionHandler, SandboxTaskDefinitionInput, SandboxTaskDefinitionOptions, SandboxTaskDevOptions, SandboxTaskDriver, SandboxTaskExecutionOptions, SandboxTaskProjectOptions, SandboxTaskRunArguments, SandboxTaskRunResult, SandboxTaskRunner, SandboxTaskSizeOptions, SandboxTaskTransferOptions, VercelSandboxTaskDriverOptions, getSandboxTaskFeatureDriver };
@@ -1,5 +1,5 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-ClSiUwCm.js";
2
- import { a as resolveTaskSandbox, c as isSandboxTaskError, i as resolveRuntimeProvider, l as sandboxTaskError, n as assertSandboxTaskDefinitionOptions, o as unsupportedHostedSandboxTaskProviderError, r as createCloudflareExecutionSandboxId, s as withSandboxTaskProvider } from "../provider-resolution-Cl2NKhRP.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-D9n0ZmdN.js";
2
+ import { a as resolveTaskSandbox, c as isSandboxTaskError, i as resolveRuntimeProvider, l as sandboxTaskError, n as assertSandboxTaskDefinitionOptions, o as unsupportedHostedSandboxTaskProviderError, r as createCloudflareExecutionSandboxId, s as withSandboxTaskProvider } from "../provider-resolution-qvRcW1PC.js";
3
3
  import { n as cloudflareRetryDelays, r as readCloudflareFailure, t as canRetryCloudflareRequest } from "../cloudflare-failure-f-3P3ul-.js";
4
4
  import { t as isTrustedHostReservedCommandEnvironmentKey } from "../trusted-host-environment-BJE5hGtQ.js";
5
5
  import { getSandboxTaskRuntimeConfig, getSandboxTaskRuntimeLocalProvider, getSandboxTaskRuntimeRegistry } from "./runtime/state.js";
@@ -31,9 +31,10 @@ function createSandboxTaskDefinition(functionName, input) {
31
31
  "handler",
32
32
  "timeout",
33
33
  "env",
34
+ "transfer",
34
35
  "project"
35
36
  ],
36
- invalidKeysMessage: "supports only portable Sandbox options (handler, timeout, env, project)"
37
+ invalidKeysMessage: "supports only portable Sandbox options (handler, timeout, env, transfer, project)"
37
38
  });
38
39
  if (!validated) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0072({ message: `[vitehub] \`${functionName}()\` requires an options object.` });
39
40
  if (typeof validated.project !== "undefined" && typeof validated.project !== "boolean") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0073({ message: `[vitehub] \`${functionName}()\` project must be a boolean.` });
@@ -172,6 +173,14 @@ function isObjectRecord(value) {
172
173
  return !!value && typeof value === "object";
173
174
  }
174
175
  const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
176
+ const blobSizeGetter = typeof Blob === "undefined" ? void 0 : Object.getOwnPropertyDescriptor(Blob.prototype, "size")?.get;
177
+ const blobArrayBuffer = typeof Blob === "undefined" ? void 0 : Blob.prototype.arrayBuffer;
178
+ function readBlobSize(blob) {
179
+ return blobSizeGetter ? Reflect.apply(blobSizeGetter, blob, []) : blob.size;
180
+ }
181
+ async function readBlobBytes(blob) {
182
+ return new Uint8Array(await (blobArrayBuffer ? Reflect.apply(blobArrayBuffer, blob, []) : blob.arrayBuffer()));
183
+ }
175
184
  function isUint8Array(value) {
176
185
  if (!ArrayBuffer.isView(value) || !typedArrayTag) return false;
177
186
  try {
@@ -208,8 +217,38 @@ function serializationError(message, details, cause) {
208
217
  details
209
218
  });
210
219
  }
211
- async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
212
- const state = { nextId: 0 };
220
+ const DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS = {
221
+ maxDepth: 32,
222
+ maxSidecars: 64,
223
+ maxSidecarBytes: 67108864
224
+ };
225
+ const DEFAULT_SANDBOX_TASK_TRANSFER_BYTES = 4194304;
226
+ function transferLimitError(label, limit, value, maximum) {
227
+ return sandboxTaskError(`Sandbox ${label} exceeds its ${limit} limit (${value} > ${maximum}).`, {
228
+ code: "SANDBOX_TASK_TRANSFER_LIMIT",
229
+ details: {
230
+ label,
231
+ limit,
232
+ value,
233
+ maximum
234
+ }
235
+ });
236
+ }
237
+ function isSandboxTaskTransferLimitError(error) {
238
+ return isSandboxTaskError(error) && error.code === "SANDBOX_TASK_TRANSFER_LIMIT";
239
+ }
240
+ /** Rejects a JSON envelope whose UTF-8 size is above `maximum` bytes. */
241
+ function assertSandboxTaskTransferBytes(json, label, limit, maximum) {
242
+ const bytes = new TextEncoder().encode(json).byteLength;
243
+ if (bytes > maximum) throw transferLimitError(label, limit, bytes, maximum);
244
+ }
245
+ /** Encodes a value and holds its binary sidecars in memory. `writeSidecars()` writes them to the Sandbox. */
246
+ async function encodeSandboxTaskValueStaged(sandbox, value, assetsDir, label, signal, limits = DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS, rootDepth = 0) {
247
+ const state = {
248
+ nextId: 0,
249
+ sidecarBytes: 0,
250
+ pendingWrites: []
251
+ };
213
252
  const throwIfAborted = () => signal?.throwIfAborted();
214
253
  const abortable = async (operation) => {
215
254
  try {
@@ -219,38 +258,51 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
219
258
  throw error;
220
259
  }
221
260
  };
222
- async function encode(entry, ancestors, key = "", applyToJSON = true) {
223
- const blob = typeof Blob !== "undefined" && entry instanceof Blob;
224
- const buffer = typeof Buffer !== "undefined" && Buffer.isBuffer(entry);
225
- if (blob || isUint8Array(entry)) {
226
- throwIfAborted();
227
- const id = state.nextId++;
228
- state.directory ||= abortable(sandbox.files.mkdir(assetsDir, {
229
- recursive: true,
230
- signal
231
- }));
232
- await state.directory;
233
- const bytes = blob ? new Uint8Array(await entry.arrayBuffer()) : entry;
234
- throwIfAborted();
235
- await abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }));
236
- return tagged({
237
- id,
238
- kind: blob ? "blob" : buffer ? "buffer" : "uint8array",
239
- ...blob && entry.type ? { type: entry.type } : {},
240
- tag: "binary"
241
- });
261
+ async function stage(descriptor, byteLength, read) {
262
+ throwIfAborted();
263
+ if (state.nextId + 1 > limits.maxSidecars) throw transferLimitError(label, "maxSidecars", state.nextId + 1, limits.maxSidecars);
264
+ if (state.sidecarBytes + byteLength > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", state.sidecarBytes + byteLength, limits.maxSidecarBytes);
265
+ const bytes = await read();
266
+ throwIfAborted();
267
+ const sidecarBytes = state.sidecarBytes + bytes.byteLength;
268
+ if (sidecarBytes > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", sidecarBytes, limits.maxSidecarBytes);
269
+ state.sidecarBytes = sidecarBytes;
270
+ const id = state.nextId++;
271
+ state.pendingWrites.push({
272
+ id,
273
+ bytes
274
+ });
275
+ return tagged({
276
+ id,
277
+ ...descriptor,
278
+ tag: "binary"
279
+ });
280
+ }
281
+ async function encode(entry, ancestors, key = "", applyToJSON = true, depth = 0) {
282
+ if (typeof Blob !== "undefined" && entry instanceof Blob) {
283
+ const prototype = Object.getPrototypeOf(entry);
284
+ if (prototype !== Blob.prototype && (typeof File === "undefined" || prototype !== File.prototype)) throw serializationError(`Sandbox ${label} Blob subclasses are not supported.`, { label });
285
+ if (Object.hasOwn(entry, "arrayBuffer")) throw serializationError(`Sandbox ${label} Blob arrayBuffer overrides are not supported.`, { label });
286
+ return await stage({
287
+ kind: "blob",
288
+ ...entry.type ? { type: entry.type } : {}
289
+ }, readBlobSize(entry), () => readBlobBytes(entry));
242
290
  }
291
+ if (isUint8Array(entry)) return await stage({ kind: typeof Buffer !== "undefined" && Buffer.isBuffer(entry) ? "buffer" : "uint8array" }, entry.byteLength, () => entry);
243
292
  if (isObjectRecord(entry) && applyToJSON) try {
244
293
  const toJSON = entry.toJSON;
245
- if (typeof toJSON === "function") return await encode(Reflect.apply(toJSON, entry, [key]), ancestors, key, false);
294
+ if (typeof toJSON === "function") return await encode(Reflect.apply(toJSON, entry, [key]), ancestors, key, false, depth);
246
295
  } catch (error) {
247
296
  if (isSandboxTaskError(error)) throw error;
248
297
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
249
298
  }
250
299
  if (Array.isArray(entry)) {
300
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
251
301
  if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
252
302
  const nextAncestors = new Set(ancestors).add(entry);
253
- return await Promise.all(entry.map((item, index) => encode(item, nextAncestors, String(index))));
303
+ const items = [];
304
+ for (const [index, item] of entry.entries()) items.push(await encode(item, nextAncestors, String(index), true, depth + 1));
305
+ return items;
254
306
  }
255
307
  if (!isObjectRecord(entry)) return entry;
256
308
  let boxed;
@@ -259,7 +311,8 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
259
311
  } catch (error) {
260
312
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
261
313
  }
262
- if (boxed) return await encode(boxed.value, ancestors, key, false);
314
+ if (boxed) return await encode(boxed.value, ancestors, key, false, depth);
315
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
263
316
  if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
264
317
  const nextAncestors = new Set(ancestors).add(entry);
265
318
  let sourceEntries;
@@ -268,35 +321,81 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
268
321
  } catch (error) {
269
322
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
270
323
  }
271
- const entries = await Promise.all(sourceEntries.map(async ([entryKey, item]) => [entryKey, await encode(item, nextAncestors, entryKey)]));
324
+ const entries = [];
325
+ for (const [entryKey, item] of sourceEntries) entries.push([entryKey, await encode(item, nextAncestors, entryKey, true, depth + 1)]);
272
326
  return hasMarker(entry) ? tagged({
273
327
  entries,
274
328
  tag: "object"
275
329
  }) : Object.fromEntries(entries);
276
330
  }
277
- return await encode(value, /* @__PURE__ */ new Set());
278
- }
279
- async function decodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
280
- if (Array.isArray(value)) return await Promise.all(value.map((entry) => decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)));
281
- if (!isPlainObject(value)) return value;
282
- if (!hasMarker(value)) return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
283
- const descriptor = value[SANDBOX_VALUE_MARKER];
284
- if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
285
- if (descriptor.tag === "response") {
286
- if (!isSerializedResponse(descriptor.value)) throw serializationError(`Sandbox ${label} contains an invalid response descriptor.`, { label });
287
- return deserializeResponse(descriptor.value);
288
- }
289
- if (descriptor.tag === "object") {
290
- if (!Array.isArray(descriptor.entries) || !descriptor.entries.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string")) throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
291
- return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
331
+ return {
332
+ value: await encode(value, /* @__PURE__ */ new Set(), "", true, rootDepth),
333
+ async writeSidecars() {
334
+ if (!state.pendingWrites.length) return;
335
+ await abortable(sandbox.files.mkdir(assetsDir, {
336
+ recursive: true,
337
+ signal
338
+ }));
339
+ await Promise.all(state.pendingWrites.map(({ id, bytes }) => abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }))));
340
+ }
341
+ };
342
+ }
343
+ async function decodeSandboxTaskValue(sandbox, value, assetsDir, label, signal, limits = DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS) {
344
+ const state = {
345
+ sidecars: 0,
346
+ sidecarBytes: 0
347
+ };
348
+ const readSidecar = async (path) => {
349
+ try {
350
+ return await sandbox.files.read(path, { signal });
351
+ } catch (error) {
352
+ signal?.throwIfAborted();
353
+ throw error;
354
+ }
355
+ };
356
+ async function decode(entry, depth) {
357
+ const assertContainerDepth = () => {
358
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
359
+ };
360
+ if (Array.isArray(entry)) {
361
+ assertContainerDepth();
362
+ const items = [];
363
+ for (const item of entry) items.push(await decode(item, depth + 1));
364
+ return items;
365
+ }
366
+ if (!isPlainObject(entry)) return entry;
367
+ if (!hasMarker(entry)) {
368
+ assertContainerDepth();
369
+ const entries = [];
370
+ for (const [key, item] of Object.entries(entry)) entries.push([key, await decode(item, depth + 1)]);
371
+ return Object.fromEntries(entries);
372
+ }
373
+ const descriptor = entry[SANDBOX_VALUE_MARKER];
374
+ if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
375
+ if (descriptor.tag === "response") {
376
+ if (!isSerializedResponse(descriptor.value)) throw serializationError(`Sandbox ${label} contains an invalid response descriptor.`, { label });
377
+ return deserializeResponse(descriptor.value);
378
+ }
379
+ if (descriptor.tag === "object") {
380
+ assertContainerDepth();
381
+ if (!Array.isArray(descriptor.entries) || !descriptor.entries.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string")) throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
382
+ const entries = [];
383
+ for (const [key, item] of descriptor.entries) entries.push([key, await decode(item, depth + 1)]);
384
+ return Object.fromEntries(entries);
385
+ }
386
+ if (descriptor.tag !== "binary" || !Number.isSafeInteger(descriptor.id) || Object.is(descriptor.id, -0) || descriptor.id < 0 || descriptor.kind !== "blob" && descriptor.kind !== "buffer" && descriptor.kind !== "uint8array" || typeof descriptor.type !== "undefined" && typeof descriptor.type !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
387
+ if (state.sidecars + 1 > limits.maxSidecars) throw transferLimitError(label, "maxSidecars", state.sidecars + 1, limits.maxSidecars);
388
+ const bytes = await readSidecar(`${assetsDir}/${descriptor.id}`);
389
+ if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
390
+ id: descriptor.id,
391
+ label
392
+ });
393
+ if (state.sidecarBytes + bytes.byteLength > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", state.sidecarBytes + bytes.byteLength, limits.maxSidecarBytes);
394
+ state.sidecars++;
395
+ state.sidecarBytes += bytes.byteLength;
396
+ return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
292
397
  }
293
- if (descriptor.tag !== "binary" || !Number.isSafeInteger(descriptor.id) || Object.is(descriptor.id, -0) || descriptor.id < 0 || descriptor.kind !== "blob" && descriptor.kind !== "buffer" && descriptor.kind !== "uint8array" || typeof descriptor.type !== "undefined" && typeof descriptor.type !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
294
- const bytes = await sandbox.files.read(`${assetsDir}/${descriptor.id}`, { signal });
295
- if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
296
- id: descriptor.id,
297
- label
298
- });
299
- return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
398
+ return await decode(value, 0);
300
399
  }
301
400
  // src/task/runtime/error-normalization.ts
302
401
  function readSandboxTaskErrorMetadata(error) {
@@ -358,7 +457,12 @@ function sandboxTaskCode(code) {
358
457
  }
359
458
  // src/task/runtime/entry-script.injected.ts
360
459
  const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
361
- function createEntrySource(definitionPath, execution = "definition", env) {
460
+ const EXEC_DIAGNOSTIC_PREFIX = "{\"ok\":false,\"error\":";
461
+ const MAX_EXEC_DIAGNOSTIC_BYTES = 131072;
462
+ function createEntrySource(definitionPath, execution = "definition", env, transferLimits = {
463
+ ...DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS,
464
+ maxOutputBytes: DEFAULT_SANDBOX_TASK_TRANSFER_BYTES
465
+ }) {
362
466
  const invocation = execution === "module" ? [
363
467
  ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
364
468
  ` const exported = await mod.default`,
@@ -377,6 +481,8 @@ function createEntrySource(definitionPath, execution = "definition", env) {
377
481
  `import { Buffer } from 'node:buffer'`,
378
482
  `import { pathToFileURL } from 'node:url'`,
379
483
  `const serializationErrors = new WeakSet()`,
484
+ `const transferLimitErrors = new WeakSet()`,
485
+ `const transferLimits = ${JSON.stringify(transferLimits)}`,
380
486
  ``,
381
487
  `function serializationError(message, cause) {`,
382
488
  ` const error = new TypeError(message, { cause })`,
@@ -384,10 +490,16 @@ function createEntrySource(definitionPath, execution = "definition", env) {
384
490
  ` return error`,
385
491
  `}`,
386
492
  ``,
493
+ `function transferLimitError(limit, value) {`,
494
+ ` const error = new Error('Sandbox result exceeds its ' + limit + ' limit (' + value + ' > ' + transferLimits[limit] + ').')`,
495
+ ` transferLimitErrors.add(error)`,
496
+ ` return error`,
497
+ `}`,
498
+ ``,
387
499
  `function normalizeError(error) {`,
388
500
  ` if (error instanceof Error) {`,
389
501
  ` return {`,
390
- ` code: serializationErrors.has(error) ? 'SANDBOX_TASK_SERIALIZATION_ERROR' : undefined,`,
502
+ ` code: serializationErrors.has(error) ? 'SANDBOX_TASK_SERIALIZATION_ERROR' : transferLimitErrors.has(error) ? 'SANDBOX_TASK_TRANSFER_LIMIT' : undefined,`,
391
503
  ` name: error.name,`,
392
504
  ` message: error.message,`,
393
505
  ` stack: error.stack,`,
@@ -401,8 +513,21 @@ function createEntrySource(definitionPath, execution = "definition", env) {
401
513
  ` }`,
402
514
  `}`,
403
515
  ``,
516
+ `function serializeFailure(error) {`,
517
+ ` const diagnostic = normalizeError(error)`,
518
+ ` const maximum = ${MAX_EXEC_DIAGNOSTIC_BYTES}`,
519
+ ` const envelope = value => ${JSON.stringify(EXEC_DIAGNOSTIC_PREFIX)} + JSON.stringify(value) + '}'`,
520
+ ` const output = envelope(Object.fromEntries(Object.entries(diagnostic).map(([key, value]) => [key, typeof value === 'string' ? value.slice(0, maximum) : value])))`,
521
+ ` if (Buffer.byteLength(output) <= maximum) return output`,
522
+ ` const fallback = { code: diagnostic.code, message: '' }`,
523
+ ` const message = String(diagnostic.message).slice(0, maximum)`,
524
+ ` const withMessage = envelope({ ...fallback, message })`,
525
+ ` if (Buffer.byteLength(withMessage) <= maximum) return withMessage`,
526
+ ` const messageBudget = maximum - Buffer.byteLength(envelope(fallback))`,
527
+ ` return envelope({ ...fallback, message: message.slice(0, Math.floor(messageBudget / 6)) })`,
528
+ `}`,
529
+ ``,
404
530
  `const valueMarker = ${JSON.stringify("vitehub:sandbox-task:value")}`,
405
- `const nativeResponseClone = typeof Response !== 'undefined' ? Response.prototype.clone : undefined`,
406
531
  `const nativeResponseBody = typeof Response !== 'undefined' ? Object.getOwnPropertyDescriptor(Response.prototype, 'body')?.get : undefined`,
407
532
  ``,
408
533
  `function isPlainObject(value) {`,
@@ -416,6 +541,8 @@ function createEntrySource(definitionPath, execution = "definition", env) {
416
541
  `}`,
417
542
  ``,
418
543
  `const typedArrayTagGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get`,
544
+ `const blobSizeGetter = typeof Blob !== 'undefined' ? Object.getOwnPropertyDescriptor(Blob.prototype, 'size')?.get : undefined`,
545
+ `const blobArrayBuffer = typeof Blob !== 'undefined' ? Blob.prototype.arrayBuffer : undefined`,
419
546
  ``,
420
547
  `function isUint8Array(value) {`,
421
548
  ` return ArrayBuffer.isView(value) && typedArrayTagGetter?.call(value) === 'Uint8Array'`,
@@ -440,20 +567,17 @@ function createEntrySource(definitionPath, execution = "definition", env) {
440
567
  `function isResponse(value) {`,
441
568
  ` if (!value || typeof value !== 'object') return false`,
442
569
  ` try {`,
443
- ` let clone = nativeResponseClone`,
444
- ` let cloneSucceeded = false`,
445
- ` let cloneResult`,
446
570
  ` let bodySucceeded = false`,
447
- ` if (typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
448
- ` if (!cloneSucceeded && typeof nativeResponseBody === 'function') { try { nativeResponseBody.call(value); bodySucceeded = true } catch {} }`,
449
- ` if (cloneSucceeded || bodySucceeded) {`,
571
+ ` if (typeof nativeResponseBody === 'function') { try { nativeResponseBody.call(value); bodySucceeded = true } catch {} }`,
572
+ ` if (bodySucceeded) {`,
450
573
  ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
451
574
  ` && typeof value.statusText === 'string'`,
452
575
  ` && typeof value.arrayBuffer === 'function'`,
453
576
  ` && value.headers && typeof value.headers.get === 'function'`,
454
577
  ` && typeof value.headers[Symbol.iterator] === 'function'`,
455
578
  ` }`,
456
- ` clone = undefined`,
579
+ ` let clone`,
580
+ ` let cloneResult`,
457
581
  ` let foreignCloneDescriptor`,
458
582
  ` let foreignBodyDescriptor`,
459
583
  ` let foreignConstructorDescriptor`,
@@ -484,7 +608,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
484
608
  ` }`,
485
609
  ` prototype = Object.getPrototypeOf(prototype)`,
486
610
  ` }`,
487
- ` if (!cloneSucceeded && typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
611
+ ` if (typeof clone === 'function') { try { cloneResult = clone.call(value) } catch {} }`,
488
612
  ` // Consumed or locked foreign Responses reject clone(), but their branded body getter still succeeds.`,
489
613
  ` if (!bodySucceeded || typeof clone !== 'function') return false`,
490
614
  ` let cloneResultBodySucceeded = false`,
@@ -522,6 +646,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
522
646
  ` const undiciInternals = enumerableSymbols.length === 2 && undiciState && typeof undiciState === 'object' && Number.isInteger(undiciState.status) && 'body' in undiciState && 'headersList' in undiciState && undiciHeaders && typeof undiciHeaders === 'object' && undiciHeaders === value.headers && typeof undiciHeaders.get === 'function' && cloneSymbols?.length === 2 && cloneState && typeof cloneState === 'object' && 'headersList' in cloneState && cloneHeaders && typeof cloneHeaders === 'object' && cloneHeaders === cloneResult.headers && typeof cloneHeaders.get === 'function'`,
523
647
  ` if (Object.keys(value).length > 0) return false`,
524
648
  ` if (hasEnumerableProperties(value) && !undiciInternals) return false`,
649
+ ` if (cloneResultBodySucceeded && cloneResult.body) void cloneResult.body.cancel().catch(() => {})`,
525
650
  ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
526
651
  ` && typeof value.statusText === 'string'`,
527
652
  ` && typeof value.arrayBuffer === 'function'`,
@@ -567,25 +692,70 @@ function createEntrySource(definitionPath, execution = "definition", env) {
567
692
  ` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
568
693
  `}`,
569
694
  ``,
570
- `async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
695
+ `async function readResponseBody(response, state, descriptorBytes) {`,
696
+ ` const baseBytes = state.responseBytes + descriptorBytes`,
697
+ ` const assertBytes = bodyBytes => {`,
698
+ ` const outputBytes = baseBytes + 4 * Math.ceil(bodyBytes / 3)`,
699
+ ` if (outputBytes > transferLimits.maxOutputBytes) throw transferLimitError('maxOutputBytes', outputBytes)`,
700
+ ` return outputBytes`,
701
+ ` }`,
702
+ ` if (!response.body) {`,
703
+ ` state.responseBytes = assertBytes(0)`,
704
+ ` return ''`,
705
+ ` }`,
706
+ ` if (response.bodyUsed) throw new TypeError('Response body has already been consumed.')`,
707
+ ` const reader = response.body.getReader()`,
708
+ ` const chunks = []`,
709
+ ` let bytes = 0`,
710
+ ` try {`,
711
+ ` assertBytes(0)`,
712
+ ` for (;;) {`,
713
+ ` const { done, value } = await reader.read()`,
714
+ ` if (done) break`,
715
+ ` if (!(value instanceof Uint8Array) && !isUint8Array(value)) throw new TypeError('Response body must contain bytes.')`,
716
+ ` bytes += value.byteLength`,
717
+ ` assertBytes(bytes)`,
718
+ ` if (value.byteLength) chunks.push(value)`,
719
+ ` }`,
720
+ ` state.responseBytes = assertBytes(bytes)`,
721
+ ` return Buffer.concat(chunks, bytes).toString('base64')`,
722
+ ` }`,
723
+ ` catch (error) {`,
724
+ ` void reader.cancel().catch(() => {})`,
725
+ ` throw error`,
726
+ ` }`,
727
+ ` finally { reader.releaseLock() }`,
728
+ `}`,
729
+ ``,
730
+ `async function extractValue(value, assetsDir, state, ancestors = new Set(), key = '', applyToJSON = true, depth = 0) {`,
571
731
  ` if (isResponse(value)) {`,
572
- ` return { [valueMarker]: { tag: 'response', value: {`,
573
- ` body: { isNull: value.body === null, data: Buffer.from(await value.arrayBuffer()).toString('base64'), encoding: 'base64', mediaType: value.headers.get('content-type') || 'application/octet-stream' },`,
732
+ ` const response = {`,
733
+ ` body: { isNull: value.body === null, data: '', encoding: 'base64', mediaType: value.headers.get('content-type') || 'application/octet-stream' },`,
574
734
  ` headers: Array.from(value.headers),`,
575
735
  ` status: value.status,`,
576
736
  ` statusText: value.statusText,`,
577
737
  ` ...(value.type === 'opaqueredirect' ? { url: value.url } : {}),`,
578
738
  ` ...(['error', 'opaque', 'opaqueredirect'].includes(value.type) ? { type: value.type } : {}),`,
579
- ` } } }`,
739
+ ` }`,
740
+ ` const descriptor = { [valueMarker]: { tag: 'response', value: response } }`,
741
+ ` response.body.data = await readResponseBody(value, state, Buffer.byteLength(JSON.stringify(descriptor)))`,
742
+ ` return descriptor`,
580
743
  ` }`,
581
744
  ` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
745
+ ` if (blob && Object.getPrototypeOf(value) !== Blob.prototype && (typeof File === 'undefined' || Object.getPrototypeOf(value) !== File.prototype))`,
746
+ ` throw serializationError('Sandbox result must be JSON-serializable; Blob subclasses are not supported.')`,
747
+ ` if (blob && Object.hasOwn(value, 'arrayBuffer'))`,
748
+ ` throw serializationError('Sandbox result must be JSON-serializable; Blob arrayBuffer overrides are not supported.')`,
582
749
  ` const buffer = Buffer.isBuffer(value)`,
583
750
  ` if (blob || isUint8Array(value)) {`,
751
+ ` if (state.nextId + 1 > transferLimits.maxSidecars) throw transferLimitError('maxSidecars', state.nextId + 1)`,
752
+ ` const byteLength = blob ? Reflect.apply(blobSizeGetter, value, []) : value.byteLength`,
753
+ ` if (state.sidecarBytes + byteLength > transferLimits.maxSidecarBytes) throw transferLimitError('maxSidecarBytes', state.sidecarBytes + byteLength)`,
754
+ ` const bytes = blob ? new Uint8Array(await Reflect.apply(blobArrayBuffer, value, [])) : value`,
755
+ ` if (state.sidecarBytes + bytes.byteLength > transferLimits.maxSidecarBytes) throw transferLimitError('maxSidecarBytes', state.sidecarBytes + bytes.byteLength)`,
756
+ ` state.sidecarBytes += bytes.byteLength`,
584
757
  ` const id = state.nextId++`,
585
- ` state.directory ||= mkdir(assetsDir, { recursive: true })`,
586
- ` await state.directory`,
587
- ` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
588
- ` await writeFile(assetsDir + '/' + id, bytes)`,
758
+ ` state.pendingWrites.push({ id, bytes })`,
589
759
  ` return { [valueMarker]: {`,
590
760
  ` id,`,
591
761
  ` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
@@ -595,33 +765,40 @@ function createEntrySource(definitionPath, execution = "definition", env) {
595
765
  ` }`,
596
766
  ` if (value && typeof value === 'object' && applyToJSON) {`,
597
767
  ` const toJSON = value.toJSON`,
598
- ` if (typeof toJSON === 'function')`,
599
- ` return await extractValue(Reflect.apply(toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
768
+ ` if (typeof toJSON === 'function') {`,
769
+ ` const replacement = Reflect.apply(toJSON, value, [key])`,
770
+ ` return await extractValue(replacement, assetsDir, state, ancestors, key, false, depth)`,
771
+ ` }`,
600
772
  ` }`,
601
773
  ` if (Array.isArray(value)) {`,
774
+ ` if (depth >= transferLimits.maxDepth) throw transferLimitError('maxDepth', depth + 1)`,
602
775
  ` if (ancestors.has(value))`,
603
776
  ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
604
777
  ` const nextAncestors = new Set(ancestors).add(value)`,
605
- ` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
778
+ ` const items = []`,
779
+ ` for (const [index, entry] of value.entries())`,
780
+ ` items.push(await extractValue(entry, assetsDir, state, nextAncestors, String(index), true, depth + 1))`,
781
+ ` return items`,
606
782
  ` }`,
607
783
  ` if (!value || typeof value !== 'object') return value`,
608
784
  ` const boxed = unboxJsonPrimitive(value)`,
609
- ` if (boxed) return await extractValue(boxed.value, assetsDir, state, ancestors, key, false)`,
785
+ ` if (boxed) return await extractValue(boxed.value, assetsDir, state, ancestors, key, false, depth)`,
786
+ ` if (depth >= transferLimits.maxDepth) throw transferLimitError('maxDepth', depth + 1)`,
610
787
  ` if (ancestors.has(value))`,
611
788
  ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
612
789
  ` const nextAncestors = new Set(ancestors).add(value)`,
613
790
  ` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
614
- ` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
615
- ` entryKey,`,
616
- ` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
617
- ` ]))`,
791
+ ` const entries = []`,
792
+ ` for (const [entryKey, entry] of sourceEntries)`,
793
+ ` entries.push([entryKey, await extractValue(entry, assetsDir, state, nextAncestors, entryKey, true, depth + 1)])`,
618
794
  ` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
619
795
  `}`,
620
796
  ``,
621
797
  `async function serializeSuccess(result, assetsDir) {`,
622
798
  ` try {`,
623
- ` const encoded = await extractValue(result, assetsDir)`,
624
- ` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
799
+ ` const state = { nextId: 0, sidecarBytes: 0, pendingWrites: [], responseBytes: '{"ok":true,"result":}'.length }`,
800
+ ` const encoded = await extractValue(result, assetsDir, state)`,
801
+ ` const output = JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
625
802
  ` const type = typeof value`,
626
803
  ` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
627
804
  ` throw serializationError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
@@ -629,9 +806,16 @@ function createEntrySource(definitionPath, execution = "definition", env) {
629
806
  ` throw serializationError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
630
807
  ` return value`,
631
808
  ` })`,
809
+ ` const outputBytes = Buffer.byteLength(output, 'utf8')`,
810
+ ` if (outputBytes > transferLimits.maxOutputBytes) throw transferLimitError('maxOutputBytes', outputBytes)`,
811
+ ` if (state.pendingWrites.length) {`,
812
+ ` await mkdir(assetsDir, { recursive: true })`,
813
+ ` await Promise.all(state.pendingWrites.map(({ id, bytes }) => writeFile(assetsDir + '/' + id, bytes)))`,
814
+ ` }`,
815
+ ` return output`,
632
816
  ` }`,
633
817
  ` catch (error) {`,
634
- ` if (serializationErrors.has(error))`,
818
+ ` if (serializationErrors.has(error) || transferLimitErrors.has(error))`,
635
819
  ` throw error`,
636
820
  ` throw serializationError('Sandbox result must be JSON-serializable.', error)`,
637
821
  ` }`,
@@ -650,7 +834,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
650
834
  ` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
651
835
  ` }`,
652
836
  ` catch (error) {`,
653
- ` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
837
+ ` const output = serializeFailure(error)`,
654
838
  ` await writeFile(outputPath, output)`,
655
839
  ` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
656
840
  ` process.exitCode = 1`,
@@ -832,6 +1016,13 @@ const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
832
1016
  const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
833
1017
  const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
834
1018
  const HANDLER_DIAGNOSTIC_LENGTH = 16384;
1019
+ function assertOutputBytes(output, maxOutputBytes) {
1020
+ if (output.startsWith("{\"ok\":false,\"error\":") || "{\"ok\":false,\"error\":".startsWith(output)) {
1021
+ assertSandboxTaskTransferBytes(output, "diagnostic", "maxDiagnosticBytes", MAX_EXEC_DIAGNOSTIC_BYTES);
1022
+ if (tryParseSandboxTaskOutput(output)?.ok !== true) return;
1023
+ }
1024
+ if (maxOutputBytes !== void 0) assertSandboxTaskTransferBytes(output, "result", "maxOutputBytes", maxOutputBytes);
1025
+ }
835
1026
  function getErrorMessage(error) {
836
1027
  if (error instanceof Error) return error.message;
837
1028
  if (error && typeof error === "object") {
@@ -942,7 +1133,7 @@ function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, ex
942
1133
  ...getExecutionDiagnostics(execution)
943
1134
  });
944
1135
  }
945
- async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1136
+ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
946
1137
  const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
947
1138
  const deadline = Date.now() + recoveryTimeout;
948
1139
  let lastError = error;
@@ -951,10 +1142,12 @@ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution,
951
1142
  signal?.throwIfAborted();
952
1143
  try {
953
1144
  const output = await sandbox.readFile(outputPath, { signal });
1145
+ assertOutputBytes(output, maxOutputBytes);
954
1146
  lastOutput = output;
955
1147
  if (isCompleteSandboxTaskOutput(output)) return output;
956
1148
  } catch (readError) {
957
1149
  if (signal?.aborted) throw signal.reason;
1150
+ if (isSandboxTaskTransferLimitError(readError)) throw readError;
958
1151
  lastError = readError;
959
1152
  }
960
1153
  const remaining = deadline - Date.now();
@@ -966,34 +1159,42 @@ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution,
966
1159
  outputPreview: lastOutput.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH) || void 0
967
1160
  });
968
1161
  }
969
- async function recoverExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1162
+ async function recoverExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
970
1163
  if (sandbox.provider !== "cloudflare" || !mayHaveRunCloudflareExec(error)) return null;
971
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1164
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
972
1165
  }
973
- async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal) {
1166
+ async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
974
1167
  const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
975
1168
  signal?.throwIfAborted();
976
1169
  if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
977
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1170
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
978
1171
  }
979
- async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution, signal) {
1172
+ async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
980
1173
  const executionOutput = extractSandboxTaskOutputFromExecution(execution) || extractSandboxTaskOutputFromExecution(error);
981
- if (executionOutput) return executionOutput;
1174
+ if (executionOutput) {
1175
+ assertOutputBytes(executionOutput, maxOutputBytes);
1176
+ return executionOutput;
1177
+ }
982
1178
  try {
983
1179
  const output = await sandbox.readFile(outputPath, { signal });
1180
+ assertOutputBytes(output, maxOutputBytes);
984
1181
  if (isCompleteSandboxTaskOutput(output)) return output;
985
- } catch {
1182
+ } catch (readError) {
1183
+ if (isSandboxTaskTransferLimitError(readError)) throw readError;
986
1184
  signal?.throwIfAborted();
987
- return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1185
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
988
1186
  }
989
- return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1187
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
990
1188
  }
991
1189
  // src/task/runtime/execute.ts
992
1190
  const SANDBOX_CLEANUP_GRACE_MS = 1e3;
993
- function toJson(value, label) {
1191
+ function toJson(value, label, maxInputBytes) {
994
1192
  try {
995
- return JSON.stringify(value);
1193
+ const json = JSON.stringify(value);
1194
+ assertSandboxTaskTransferBytes(json, label, "maxInputBytes", maxInputBytes);
1195
+ return json;
996
1196
  } catch (error) {
1197
+ if (isSandboxTaskError(error)) throw error;
997
1198
  throw sandboxTaskError(`Sandbox ${label} must be JSON-serializable.`, {
998
1199
  code: "SANDBOX_TASK_SERIALIZATION_ERROR",
999
1200
  details: { label },
@@ -1004,29 +1205,40 @@ function toJson(value, label) {
1004
1205
  async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, lifecycle, deadline) {
1005
1206
  const bundle = normalizeSandboxTaskDefinitionBundle(source);
1006
1207
  const files = createExecutionFiles(definitionName, sandbox.tempDir);
1208
+ const transfer = definitionOptions?.transfer;
1209
+ const transferLimits = {
1210
+ maxDepth: transfer?.maxDepth ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxDepth,
1211
+ maxSidecars: transfer?.maxSidecars ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxSidecars,
1212
+ maxSidecarBytes: transfer?.maxSidecarBytes ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxSidecarBytes
1213
+ };
1214
+ const maxInputBytes = transfer?.maxInputBytes ?? 4194304;
1215
+ const maxOutputBytes = transfer?.maxOutputBytes ?? 4194304;
1007
1216
  let failure;
1008
1217
  const throwIfAborted = () => {
1009
1218
  if (signal?.aborted) throw signal.reason ?? new DOMException("The Sandbox invocation was aborted.", "AbortError");
1010
1219
  };
1220
+ const encodeInput = async () => {
1221
+ const encoded = await encodeSandboxTaskValueStaged(sandbox, {
1222
+ payload,
1223
+ context
1224
+ }, files.inputAssetsDir, "payload/context", signal, transferLimits, -1);
1225
+ const json = toJson(encoded.value, "payload/context", maxInputBytes);
1226
+ await encoded.writeSidecars();
1227
+ return json;
1228
+ };
1011
1229
  try {
1012
1230
  await sandbox.mkdir(files.baseDir, {
1013
1231
  recursive: true,
1014
1232
  signal
1015
1233
  });
1016
1234
  throwIfAborted();
1017
- let inputJson = bundle.project ? toJson(await encodeSandboxTaskValue(sandbox, {
1018
- payload,
1019
- context
1020
- }, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
1235
+ let inputJson = bundle.project ? await encodeInput() : void 0;
1021
1236
  const prepared = await prepareSandboxTaskDefinition(sandbox, bundle, files.baseDir, {
1022
1237
  onCommandStart: lifecycle?.onCommandStart,
1023
1238
  signal,
1024
1239
  timeout: definitionOptions?.timeout
1025
1240
  });
1026
- inputJson ||= toJson(await encodeSandboxTaskValue(sandbox, {
1027
- payload,
1028
- context
1029
- }, files.inputAssetsDir, "payload/context", signal), "payload/context");
1241
+ inputJson ||= await encodeInput();
1030
1242
  const definitionPath = resolveSandboxTaskModulePath(prepared.directory, bundle.entry);
1031
1243
  const local = sandbox.provider === "local";
1032
1244
  let env = definitionOptions?.env;
@@ -1037,7 +1249,10 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1037
1249
  env = Object.fromEntries(entries.filter(([name]) => !isTrustedHostReservedCommandEnvironmentKey(name)));
1038
1250
  }
1039
1251
  throwIfAborted();
1040
- await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution, entryEnvironment), { signal }), sandbox.writeFile(files.inputPath, inputJson, { signal })]);
1252
+ await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution, entryEnvironment, {
1253
+ ...transferLimits,
1254
+ maxOutputBytes
1255
+ }), { signal }), sandbox.writeFile(files.inputPath, inputJson, { signal })]);
1041
1256
  throwIfAborted();
1042
1257
  const execArgs = local ? [
1043
1258
  files.entryPath,
@@ -1060,13 +1275,13 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1060
1275
  signal,
1061
1276
  timeout: definitionOptions?.timeout
1062
1277
  });
1063
- outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution, signal);
1278
+ outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1064
1279
  } catch (error) {
1065
1280
  throwIfAborted();
1066
1281
  if (readSandboxTaskErrorMetadata(error)?.details?.operation === "createSession") throw error;
1067
- if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1282
+ if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1068
1283
  else {
1069
- const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1284
+ const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1070
1285
  if (recoveredOutput == null) throw error;
1071
1286
  outputRaw = recoveredOutput;
1072
1287
  }
@@ -1076,7 +1291,11 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1076
1291
  output: outputRaw,
1077
1292
  cause: "Output file was empty or contained incomplete JSON."
1078
1293
  });
1079
- if (output.ok) return await decodeSandboxTaskValue(sandbox, output.result, files.outputAssetsDir, "result", signal);
1294
+ if (output.ok) return await decodeSandboxTaskValue(sandbox, output.result, files.outputAssetsDir, "result", signal, transferLimits);
1295
+ if (output.error?.code === "SANDBOX_TASK_TRANSFER_LIMIT") throw sandboxTaskError(output.error.message || "Sandbox result exceeds its transfer limit.", {
1296
+ code: "SANDBOX_TASK_TRANSFER_LIMIT",
1297
+ provider: sandbox.provider
1298
+ });
1080
1299
  if (output.error?.code === "SANDBOX_TASK_SERIALIZATION_ERROR") throw sandboxTaskError(output.error.message || "Sandbox result must be JSON-serializable.", {
1081
1300
  code: "SANDBOX_TASK_SERIALIZATION_ERROR",
1082
1301
  provider: sandbox.provider,
@@ -1,2 +1,2 @@
1
- import { n as SandboxTaskRuntimeProvider, r as loadSandboxTaskRuntimeProvider, t as ResolvedTaskSandbox } from "../../provider-loader-CNKHrWXG.js";
1
+ import { n as SandboxTaskRuntimeProvider, r as loadSandboxTaskRuntimeProvider, t as ResolvedTaskSandbox } from "../../provider-loader-CLIIEEmR.js";
2
2
  export { ResolvedTaskSandbox, SandboxTaskRuntimeProvider, loadSandboxTaskRuntimeProvider };
@@ -1,4 +1,4 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "../../error-diagnostics-ClSiUwCm.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "../../error-diagnostics-D9n0ZmdN.js";
2
2
  // src/task/runtime/provider-loader.ts
3
3
  const dynamicImport = new Function("specifier", "return import(specifier)");
4
4
  async function loadSandboxTaskRuntimeProvider(provider) {
@@ -1,5 +1,5 @@
1
1
  import { l as Sandbox } from "../../../index-D9DogaoF.js";
2
- import { n as CloudflareSandboxTaskDefinitionDriverOptions, u as SandboxTaskDefinitionOptions } from "../../../module-types-B3uJG1po.js";
2
+ import { n as CloudflareSandboxTaskDefinitionDriverOptions, u as SandboxTaskDefinitionOptions } from "../../../module-types-DHr6oC3h.js";
3
3
  type SandboxTaskOptions = {
4
4
  local: SandboxTaskDefinitionOptions;
5
5
  provider: CloudflareSandboxTaskDefinitionDriverOptions;
@@ -1,6 +1,6 @@
1
1
  import { resolveCloudflareSandbox } from "../../../internal/cloudflare.js";
2
2
  import { t as getActiveCloudflareEnv } from "../../../cloudflare-env-lookup-BNbNil7g.js";
3
- import { t as sandboxTaskErrorDiagnostics } from "../../../error-diagnostics-ClSiUwCm.js";
3
+ import { t as sandboxTaskErrorDiagnostics } from "../../../error-diagnostics-D9n0ZmdN.js";
4
4
  // src/task/runtime/providers/cloudflare.ts
5
5
  /** Resolve the Sandbox namespace from the bindings of the active Cloudflare request. */
6
6
  async function resolveCloudflareTaskSandbox(options) {
@@ -1,4 +1,4 @@
1
- import { t as ResolvedTaskSandbox } from "../../../provider-loader-CNKHrWXG.js";
1
+ import { t as ResolvedTaskSandbox } from "../../../provider-loader-CLIIEEmR.js";
2
2
  /**
3
3
  * `vite dev` runs each Sandbox Task as a Node process on this machine, in a temporary directory that the run removes.
4
4
  * The process is not isolated: the Sandbox `executionAuthority` says `isolation: "none"`.
@@ -1,5 +1,5 @@
1
1
  import { l as Sandbox } from "../../../index-D9DogaoF.js";
2
- import { _ as VercelSandboxTaskDriverOptions, u as SandboxTaskDefinitionOptions } from "../../../module-types-B3uJG1po.js";
2
+ import { u as SandboxTaskDefinitionOptions, v as VercelSandboxTaskDriverOptions } from "../../../module-types-DHr6oC3h.js";
3
3
  type SandboxTaskOptions = {
4
4
  local: SandboxTaskDefinitionOptions;
5
5
  provider: VercelSandboxTaskDriverOptions;
@@ -1,8 +1,8 @@
1
1
  import { resolveVercelSandbox } from "../../../internal/vercel.js";
2
2
  import { n as loadVercelSandbox } from "../../../vercel-DT74kDyI.js";
3
- import { o as resolveVercelSandboxTaskVcpus, t as vercelCredentialEnv } from "../../../vercel-credentials-BGuXoKxG.js";
4
- import { t as sandboxTaskErrorDiagnostics } from "../../../error-diagnostics-ClSiUwCm.js";
5
- import "../../../provider-resolution-Cl2NKhRP.js";
3
+ import { o as resolveVercelSandboxTaskVcpus, t as vercelCredentialEnv } from "../../../vercel-credentials-BH5lPJxs.js";
4
+ import { t as sandboxTaskErrorDiagnostics } from "../../../error-diagnostics-D9n0ZmdN.js";
5
+ import "../../../provider-resolution-qvRcW1PC.js";
6
6
  // ../internal/src/env.ts
7
7
  function trimmed(value) {
8
8
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
@@ -1,5 +1,5 @@
1
- import { a as SandboxTaskDefinitionBundle, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionOptions } from "../../module-types-B3uJG1po.js";
2
- import { t as ResolvedTaskSandbox } from "../../provider-loader-CNKHrWXG.js";
1
+ import { a as SandboxTaskDefinitionBundle, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionOptions } from "../../module-types-DHr6oC3h.js";
2
+ import { t as ResolvedTaskSandbox } from "../../provider-loader-CLIIEEmR.js";
3
3
  export type SandboxTaskRegistryEntry = {
4
4
  bundle: SandboxTaskDefinitionBundle;
5
5
  options?: SandboxTaskDefinitionOptions;
@@ -1,4 +1,4 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "../../error-diagnostics-ClSiUwCm.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "../../error-diagnostics-D9n0ZmdN.js";
2
2
  import { pathToFileURL } from "node:url";
3
3
  // src/task/runtime/state.ts
4
4
  let sandboxTaskConfig;
@@ -1,4 +1,4 @@
1
- import { t as AgentSandboxTaskConfig } from "../module-types-B3uJG1po.js";
1
+ import { t as AgentSandboxTaskConfig } from "../module-types-DHr6oC3h.js";
2
2
  import { Plugin } from "vite";
3
3
  /** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
4
4
  type ViteHubHost = "cloudflare" | "deno" | "netlify" | "node" | "vercel";
@@ -180,7 +180,7 @@ interface ViteHubConsoleOperationAction {
180
180
  operation: string;
181
181
  input: Readonly<Record<string, string>>;
182
182
  /**
183
- * The result is `{ url }`, such as a one-time link or a provider sign-in: the Console opens it in a new tab, and loads
183
+ * The result is `{ url }`, such as a provider sign-in: the Console opens it in a new tab, and loads
184
184
  * the list again when the person comes back. The URL must be `https:`, or `http:` on a loopback host.
185
185
  */
186
186
  tab?: true;
package/dist/task/vite.js CHANGED
@@ -1,6 +1,7 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-ClSiUwCm.js";
2
- import { a as resolveCloudflareSandboxTaskInstanceType, i as readSandboxTaskSize, n as assertCloudflareInstanceTypeFits, o as resolveVercelSandboxTaskVcpus, r as describeCloudflareInstanceType, t as vercelCredentialEnv } from "../vercel-credentials-BGuXoKxG.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-D9n0ZmdN.js";
2
+ import { a as resolveCloudflareSandboxTaskInstanceType, i as readSandboxTaskSize, n as assertCloudflareInstanceTypeFits, o as resolveVercelSandboxTaskVcpus, r as describeCloudflareInstanceType, t as vercelCredentialEnv } from "../vercel-credentials-BH5lPJxs.js";
3
3
  import { n as invariantError, t as invariant } from "../invariant-Dj2R1eMr.js";
4
+ import { t as assertSandboxTaskTransferOptions } from "../transfer-options-LTUzbHDw.js";
4
5
  import { t as getSandboxTaskFeatureDriver } from "../module-types-CWcBHyEs.js";
5
6
  import { builtinModules, createRequire, isBuiltin } from "node:module";
6
7
  import { createHash, randomUUID } from "node:crypto";
@@ -1740,13 +1741,16 @@ function parseSandboxTaskProjectOptions(manifest, path) {
1740
1741
  const sandbox = manifest.vitehub.sandboxTask;
1741
1742
  if (typeof sandbox === "undefined") return void 0;
1742
1743
  if (!isRecord(sandbox)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0058({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" must be an object: ${path}` });
1743
- const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
1744
+ const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout" && key !== "transfer");
1744
1745
  if (unsupported.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0059({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" has unsupported keys: ${unsupported.join(", ")}.` });
1745
- const timeout = sandbox.timeout;
1746
- if (timeout === void 0) return void 0;
1747
- const numericTimeout = Number(timeout);
1748
- if (numericTimeout !== timeout || !Number.isInteger(numericTimeout) || numericTimeout <= 0 || numericTimeout > maxTimeout) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0060({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask.timeout" must be a positive integer no greater than ${maxTimeout}.` });
1749
- return { timeout: numericTimeout };
1746
+ const { timeout, transfer } = sandbox;
1747
+ if (timeout !== void 0 && (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout <= 0 || timeout > maxTimeout)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0060({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask.timeout" must be a positive integer no greater than ${maxTimeout}.` });
1748
+ assertSandboxTaskTransferOptions(transfer);
1749
+ if (timeout === void 0 && transfer === void 0) return void 0;
1750
+ return {
1751
+ ...timeout === void 0 ? {} : { timeout },
1752
+ ...transfer === void 0 ? {} : { transfer }
1753
+ };
1750
1754
  }
1751
1755
  function pnpmPatchPaths(manifest) {
1752
1756
  if (!isRecord(manifest.pnpm) || !isRecord(manifest.pnpm.patchedDependencies)) return [];
@@ -0,0 +1,18 @@
1
+ import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-D9n0ZmdN.js";
2
+ // src/task/transfer-options.ts
3
+ const transferKeys = /* @__PURE__ */ new Set([
4
+ "maxInputBytes",
5
+ "maxOutputBytes",
6
+ "maxDepth",
7
+ "maxSidecars",
8
+ "maxSidecarBytes"
9
+ ]);
10
+ const maxTransferLimit = 1073741824;
11
+ function assertSandboxTaskTransferOptions(transfer) {
12
+ if (transfer === void 0) return;
13
+ if (typeof transfer !== "object" || transfer === null || Array.isArray(transfer)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_TRANSFER_INVALID({ problem: "must be an object" });
14
+ const invalidKeys = Object.keys(transfer).filter((key) => !transferKeys.has(key));
15
+ if (invalidKeys.length > 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_TRANSFER_INVALID({ problem: `supports only ${[...transferKeys].join(", ")}. Unsupported: ${invalidKeys.join(", ")}` });
16
+ for (const [key, value] of Object.entries(transfer)) if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0 || value > maxTransferLimit)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_TRANSFER_INVALID({ problem: `sets ${key} to ${String(value)}. Each limit must be a whole number from 1 to ${maxTransferLimit}` });
17
+ }
18
+ export { assertSandboxTaskTransferOptions as t };
@@ -1,4 +1,4 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-ClSiUwCm.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-D9n0ZmdN.js";
2
2
  // src/task/size.ts
3
3
  const cloudflareInstanceTypes = [
4
4
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/sandbox",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Portable, isolated Sandboxes for ViteHub Agents, and Sandbox Tasks that run named package projects in them.",
5
5
  "keywords": [
6
6
  "agent",
@@ -114,7 +114,7 @@
114
114
  }
115
115
  },
116
116
  "dependencies": {
117
- "@vite-hub/runtime": "0.5.1",
117
+ "@vite-hub/runtime": "0.6.0",
118
118
  "local-pkg": "^2.0.0",
119
119
  "mlly": "^1.8.2",
120
120
  "nostics": "1.4.0",