Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk-js): preserve reused byte chunks in file uploads
Qiu34bb2b4883de
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.mdindex 2e38c6c9e..92abc08d9 100644--- a/docs/sdks/javascript.md+++ b/docs/sdks/javascript.md@@ -99,11 +99,11 @@ const sandbox = await Sandbox.create({});```-The Server validates `timeoutSeconds`; `preStart` accepts 1–10800 seconds, while `periodic` accepts 1–300 seconds. Both default to 60 seconds when omitted. See [Lifecycle Hooks](/guides/lifecycle-hooks) for timing, failure behavior, and provider limitations.+The Server validates `timeoutSeconds`; `preStart` accepts 1�C10800 seconds, while `periodic` accepts 1�C300 seconds. Both default to 60 seconds when omitted. See [Lifecycle Hooks](/guides/lifecycle-hooks) for timing, failure behavior, and provider limitations.### Idle policy (auto-pause and wake-on-access)-`lifecycle.idlePolicy` (OSEP-0024, fast-sandbox only) tells the control plane to auto-pause the sandbox after `idleTimeoutSeconds` (30–86400) of continuously idle ingress-observed traffic, and to wake it on the next request. It is control-plane state: it never reaches the guest, is allowed in template mode (`Sandbox.createFromTemplate({ idlePolicy })`), and is rejected by non-fast-sandbox backends. Omitting it preserves non-automated behavior exactly.+`lifecycle.idlePolicy` (OSEP-0024, fast-sandbox only) tells the control plane to auto-pause the sandbox after `idleTimeoutSeconds` (30�C86400) of continuously idle ingress-observed traffic, and to wake it on the next request. It is control-plane state: it never reaches the guest, is allowed in template mode (`Sandbox.createFromTemplate({ idlePolicy })`), and is rejected by non-fast-sandbox backends. Omitting it preserves non-automated behavior exactly.```tsconst sandbox = await Sandbox.create({@@ -124,7 +124,7 @@ const sandbox = await Sandbox.create({### Renewal policy (renew-on-access)-`lifecycle.renewalPolicy.extendSeconds` (OSEP-0009) opts the sandbox into automatic expiration extension on observed access: each proxied or gateway-observed request moves the expiration to `max(now + extendSeconds, current expiresAt)`. It is control-plane state and never reaches the guest. Requires the server operator to enable `[renew_intent]` — see [Renew-on-Access](/guides/renew-on-access). The deprecated `extensions["access.renew.extend.seconds"]` key remains supported through 1.x and is removed in 2.0.+`lifecycle.renewalPolicy.extendSeconds` (OSEP-0009) opts the sandbox into automatic expiration extension on observed access: each proxied or gateway-observed request moves the expiration to `max(now + extendSeconds, current expiresAt)`. It is control-plane state and never reaches the guest. Requires the server operator to enable `[renew_intent]` �� see [Renew-on-Access](/guides/renew-on-access). The deprecated `extensions["access.renew.extend.seconds"]` key remains supported through 1.x and is removed in 2.0.```tsconst sandbox = await Sandbox.create({@@ -139,7 +139,7 @@ const sandbox = await Sandbox.create({### Wake retry-A request to a paused sandbox may arrive while its restore is still in progress. The gateway answers `503` with the `OpenSandbox-Wake: expired` header; the transport recognizes it and resends the original request after the `Retry-After` delay (safe for any method — the marker proves the request was never forwarded). The wake budget defaults to 5 attempts / 60 seconds across all wake cycles; when it is exhausted the SDK throws `SandboxWakeTimeoutException` (carrying `attempts` and `waitedMs`) while the server-side resume continues in the background. Bare `503` responses follow the existing rules untouched. Tune it on the connection config: `wakeRetryEnabled` (default true), `wakeMaxAttempts` (5), `wakeOverallDeadlineSeconds` (60, `null` for unbounded). The SSE transport is wrapped too, so `commands.run()` wakes a paused sandbox like any other request (an established stream is never re-dispatched — only the marked 503 connect replays); the upload transport stays bare because upload bodies are streams and cannot be replayed.+A request to a paused sandbox may arrive while its restore is still in progress. The gateway answers `503` with the `OpenSandbox-Wake: expired` header; the transport recognizes it and resends the original request after the `Retry-After` delay (safe for any method �� the marker proves the request was never forwarded). The wake budget defaults to 5 attempts / 60 seconds across all wake cycles; when it is exhausted the SDK throws `SandboxWakeTimeoutException` (carrying `attempts` and `waitedMs`) while the server-side resume continues in the background. Bare `503` responses follow the existing rules untouched. Tune it on the connection config: `wakeRetryEnabled` (default true), `wakeMaxAttempts` (5), `wakeOverallDeadlineSeconds` (60, `null` for unbounded). The SSE transport is wrapped too, so `commands.run()` wakes a paused sandbox like any other request (an established stream is never re-dispatched �� only the marked 503 connect replays); the upload transport stays bare because upload bodies are streams and cannot be replayed.## Client Pool and observability@@ -303,7 +303,7 @@ try {#### Persistent environment variables-Set environment variables that the runtime injects into every subsequent command and session — without hand-writing shell escaping against the sandbox env file.+Set environment variables that the runtime injects into every subsequent command and session �� without hand-writing shell escaping against the sandbox env file.```tsawait sandbox.commands.setEnv("MY_TOKEN", "it's a safe value");@@ -614,6 +614,8 @@ Both `Sandbox` and `SandboxManager` own a scoped HTTP agent when running on Node## Browser Notes+Uploads copy each consumed byte chunk before requesting the next one, so producers can reuse a `Uint8Array` or Node.js `Buffer` between chunks. A `ReadableStream` producer must still keep a chunk unchanged while it is queued and has not yet been consumed.+::: warning- The SDK can run in browsers, but **streaming file uploads are Node-only**.- If you pass `ReadableStream` or `AsyncIterable` for `writeFiles`, the browser will fall back to **buffering in memory** before upload.diff --git a/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts b/sdks/sandbox/javascript/src/adapters/filesystemAdapter.tsindex 8a3a50480..426990be1 100644--- a/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts+++ b/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts@@ -76,7 +76,7 @@ async function collectBytes(const { done, value } = await reader.read();if (done) break;if (value) {- chunks.push(value);+ chunks.push(Uint8Array.from(value));total += value.length;}}@@ -85,7 +85,7 @@ async function collectBytes(}} else {for await (const chunk of source) {- chunks.push(chunk);+ chunks.push(Uint8Array.from(chunk));total += chunk.length;}}@@ -178,14 +178,14 @@ async function* multipartUploadBody(opts: {while (true) {const { done, value } = await reader.read();if (done) break;- if (value) yield value;+ if (value) yield Uint8Array.from(value);}} finally {reader.releaseLock();}} else {for await (const chunk of opts.file) {- yield chunk;+ yield Uint8Array.from(chunk);}}diff --git a/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts b/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.tsindex ac5202c1a..12589863f 100644--- a/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts+++ b/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts@@ -75,12 +75,12 @@ async function collectBytes(while (true) {const { done, value } = await reader.read();if (done) break;- if (value) { chunks.push(value); total += value.length; }+ if (value) { chunks.push(Uint8Array.from(value)); total += value.length; }}} finally { reader.releaseLock(); }} else {for await (const chunk of source) {- chunks.push(chunk);+ chunks.push(Uint8Array.from(chunk));total += chunk.length;}}diff --git a/sdks/sandbox/javascript/tests/filesystem.upload-chunks.test.mjs b/sdks/sandbox/javascript/tests/filesystem.upload-chunks.test.mjsnew file mode 100644index 000000000..30f65b6c3--- /dev/null+++ b/sdks/sandbox/javascript/tests/filesystem.upload-chunks.test.mjs@@ -0,0 +1,151 @@+// Copyright 2026 The OpenSandbox Authors+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++import assert from "node:assert/strict";+import { Buffer } from "node:buffer";+import test from "node:test";++import {+ FilesystemAdapter,+ IsolatedSessionsAdapter,+ createExecdClient,+} from "../dist/internal.js";++const BASE_URL = "http://127.0.0.1:8080";++async function withBrowserRuntime(run) {+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "process");+ Object.defineProperty(globalThis, "process", { configurable: true, value: undefined });+ try {+ return await run();+ } finally {+ Object.defineProperty(globalThis, "process", descriptor);+ }+}++async function createUploader(kind) {+ const uploads = [];+ const fetchImpl = async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init);+ if (request.method === "GET") {+ return Response.json({ created_at: "2026-01-01T00:00:00Z" });+ }+ const form = await request.formData();+ uploads.push({+ path: new URL(request.url).pathname,+ metadata: JSON.parse(await form.get("metadata").text()),+ bytes: new Uint8Array(await form.get("file").arrayBuffer()),+ });+ return Response.json({});+ };+ const opts = { baseUrl: BASE_URL, fetch: fetchImpl };+ const files = kind === "isolated"+ ? (await new IsolatedSessionsAdapter(opts).attach("session-1")).files+ : new FilesystemAdapter(createExecdClient(opts), opts);+ return {+ uploads,+ upload(data) {+ const run = () => files.writeFiles([{ path: "/tmp/chunks.bin", data }]);+ return kind === "browser" ? withBrowserRuntime(run) : run();+ },+ };+}++async function* reuseBuffer(view) {+ view.fill(65);+ yield view;+ view.fill(66);+ yield view;+}++function reusedReadableStream() {+ const view = new Uint8Array(4).subarray(1, 3);+ let count = 0;+ return new ReadableStream({+ pull(controller) {+ view.fill(count++ === 0 ? 65 : 66);+ controller.enqueue(view);+ if (count === 2) controller.close();+ },+ }, { highWaterMark: 0 });+}++// Node's test runner isolates files in separate processes and runs these tests+// serially. Only "browser" hides process to select the non-Node fallback; it+// exercises the real adapter and multipart body, not an actual browser engine.+for (const kind of ["browser", "isolated", "node"]) {+ for (const [name, source] of [+ ["Uint8Array subview", () => reuseBuffer(new Uint8Array(4).subarray(1, 3))],+ ["Buffer subview", () => reuseBuffer(Buffer.alloc(4).subarray(1, 3))],+ ["ReadableStream", reusedReadableStream],+ ]) {+ test(`${kind} upload snapshots a reused ${name}`, async () => {+ const { upload, uploads } = await createUploader(kind);+ await upload(source());+ assert.equal(uploads.length, 1);+ assert.equal(uploads[0].path, kind === "isolated"+ ? "/v1/isolated/session/session-1/files/upload" : "/files/upload");+ assert.equal(uploads[0].metadata.path, "/tmp/chunks.bin");+ assert.deepEqual(uploads[0].bytes, new Uint8Array([65, 65, 66, 66]));+ });+ }++ test(`${kind} upload preserves independent binary chunks and empty input`, async () => {+ const { upload, uploads } = await createUploader(kind);+ async function* independentChunks() {+ yield new Uint8Array([0, 255]);+ yield new Uint8Array([128, 1]);+ }+ await upload(independentChunks());+ async function* empty() { /* No data. */ }+ await upload(empty());+ assert.deepEqual(uploads.map(({ bytes }) => Array.from(bytes)), [[0, 255, 128, 1], []]);+ });++ // The Node path starts sending before the producer is exhausted; only+ // buffering guarantees producer errors occur before an upload request.+ if (kind === "node") continue;++ test(`${kind} buffered upload propagates producer errors before sending`, async () => {+ const { upload, uploads } = await createUploader(kind);+ const failure = new Error("producer failed");+ let finalized = false;+ async function* source() {+ try {+ yield new Uint8Array([1]);+ throw failure;+ } finally {+ finalized = true;+ }+ }+ await assert.rejects(() => upload(source()), (error) => error === failure);+ assert.equal(finalized, true);+ assert.deepEqual(uploads, []);+ });++ test(`${kind} buffered upload releases an errored stream reader`, async () => {+ const { upload, uploads } = await createUploader(kind);+ const failure = new Error("stream failed");+ let count = 0;+ const source = new ReadableStream({+ pull(controller) {+ if (count++ === 0) controller.enqueue(new Uint8Array([1]));+ else controller.error(failure);+ },+ }, { highWaterMark: 0 });+ await assert.rejects(() => upload(source), (error) => error === failure);+ assert.equal(source.locked, false);+ assert.deepEqual(uploads, []);+ });+}