Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(sdk/js): expose download response metadata

wenmou949d14d3696a
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.md
index e85b04229..d4b0caea2 100644
--- a/docs/sdks/javascript.md
+++ b/docs/sdks/javascript.md
@@ -341,6 +341,8 @@ await sandbox.files.deleteDirectories(["/tmp/demo"]);
For binary files, pass a `Uint8Array` to `writeFiles()` and read with `readBytes()` or `readBytesStream()`. Read options support `offset` and `limit` for partial downloads.
+Use `readBytesDetailed` or `readBytesStreamDetailed` when Range response metadata is required. Close a detailed stream body if it is not fully consumed.
+
#### File operations with an explicit identity
Bind a filesystem client to a Linux UID and GID:
diff --git a/sdks/sandbox/javascript/src/adapters/downloadResponse.ts b/sdks/sandbox/javascript/src/adapters/downloadResponse.ts
new file mode 100644
index 000000000..5b537ffb6
--- /dev/null
+++ b/sdks/sandbox/javascript/src/adapters/downloadResponse.ts
@@ -0,0 +1,113 @@
+// Copyright 2026 Alibaba Group Holding Ltd.
+//
+// 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 type {
+ ByteRange,
+ ReadBytesResponse,
+ ReadBytesStream,
+} from "../models/filesystem.js";
+
+function parseHeaderInteger(raw: string | null): number {
+ if (raw === null || !/^\d+$/.test(raw)) return -1;
+ const value = Number(raw);
+ return Number.isSafeInteger(value) ? value : -1;
+}
+
+function parseContentRange(raw: string | null): ByteRange | undefined {
+ if (raw === null || raw === "") return undefined;
+
+ const invalid: ByteRange = { start: -1, end: -1, total: -1, raw };
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(raw);
+ if (!match) return invalid;
+
+ const start = parseHeaderInteger(match[1]);
+ const end = parseHeaderInteger(match[2]);
+ const total = match[3] === "*" ? -1 : parseHeaderInteger(match[3]);
+ if (start < 0 || end < start || (total !== -1 && total <= end)) {
+ return invalid;
+ }
+ return { start, end, total, raw };
+}
+
+export function createReadBytesResponse<TBody>(
+ response: Response,
+ body: TBody,
+): ReadBytesResponse<TBody> {
+ const isPartial = response.status === 206;
+ const contentRange = isPartial
+ ? parseContentRange(response.headers.get("content-range"))
+ : undefined;
+ const contentLength = parseHeaderInteger(response.headers.get("content-length"));
+
+ return {
+ body,
+ statusCode: response.status,
+ contentType: response.headers.get("content-type") ?? undefined,
+ contentDisposition: response.headers.get("content-disposition") ?? undefined,
+ contentLength,
+ totalSize: isPartial ? (contentRange?.total ?? -1) : contentLength,
+ contentRange,
+ isPartial,
+ };
+}
+
+class ResponseByteStream implements ReadBytesStream {
+ private reader?: ReadableStreamDefaultReader<Uint8Array>;
+ private started = false;
+ private closed = false;
+
+ constructor(private readonly response: Response) {}
+
+ async close(): Promise<void> {
+ if (this.closed) return;
+ this.closed = true;
+
+ if (this.reader) {
+ await this.reader.cancel().catch(() => undefined);
+ this.reader.releaseLock();
+ this.reader = undefined;
+ return;
+ }
+ await this.response.body?.cancel().catch(() => undefined);
+ }
+
+ async *[Symbol.asyncIterator](): AsyncIterator<Uint8Array> {
+ if (this.started) {
+ throw new Error("Download body can only be read once");
+ }
+ this.started = true;
+ if (this.closed) return;
+
+ const body = this.response.body as ReadableStream<Uint8Array> | null;
+ if (!body) {
+ this.closed = true;
+ return;
+ }
+
+ this.reader = body.getReader();
+ try {
+ while (true) {
+ const { done, value } = await this.reader.read();
+ if (done) return;
+ if (value) yield value;
+ }
+ } finally {
+ await this.close();
+ }
+ }
+}
+
+export function readResponseBody(response: Response): ReadBytesStream {
+ return new ResponseByteStream(response);
+}
diff --git a/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts b/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts
index 18ad2025f..7833be84b 100644
--- a/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts
+++ b/sdks/sandbox/javascript/src/adapters/filesystemAdapter.ts
@@ -27,14 +27,16 @@ import type {
Permission,
RenameFileItem,
ReplaceFileContentItem,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SearchFilesResponse,
SetPermissionEntry,
WriteEntry,
} from "../models/filesystem.js";
import { SandboxApiException, SandboxError } from "../core/exceptions.js";
-import { iterateBodyStream } from "../core/streams.js";
import { throwOnUploadFailure } from "./uploadFailure.js";
+import { createReadBytesResponse, readResponseBody } from "./downloadResponse.js";
function joinUrl(baseUrl: string, pathname: string): string {
const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
@@ -579,34 +581,16 @@ export class FilesystemAdapter implements SandboxFiles {
path: string,
opts?: { range?: string; offset?: number; limit?: number }
): Promise<Uint8Array> {
- let url =
- joinUrl(this.opts.baseUrl, "/files/download") +
- `?path=${encodeURIComponent(path)}`;
- if (opts?.offset != null) url += `&offset=${opts.offset}`;
- if (opts?.limit != null) url += `&limit=${opts.limit}`;
- const res = await this.fetch(url, {
- method: "GET",
- headers: {
- ...(this.opts.headers ?? {}),
- ...(opts?.range ? { Range: opts.range } : {}),
- },
- });
- if (!res.ok) {
- const requestId = res.headers.get("x-request-id") ?? undefined;
- const rawBody = await res.text().catch(() => undefined);
- throw new SandboxApiException({
- message: "Download failed",
- statusCode: res.status,
- requestId,
- error: new SandboxError(
- SandboxError.UNEXPECTED_RESPONSE,
- "Download failed"
- ),
- rawBody,
- });
- }
+ return (await this.readBytesDetailed(path, opts)).body;
+ }
+
+ async readBytesDetailed(
+ path: string,
+ opts?: { range?: string; offset?: number; limit?: number }
+ ): Promise<ReadBytesResponse<Uint8Array>> {
+ const res = await this.fetchDownload(path, opts, "Download failed");
const ab = await res.arrayBuffer();
- return new Uint8Array(ab);
+ return createReadBytesResponse(res, new Uint8Array(ab));
}
readBytesStream(
@@ -616,10 +600,19 @@ export class FilesystemAdapter implements SandboxFiles {
return this.downloadStream(path, opts);
}
- private async *downloadStream(
+ async readBytesStreamDetailed(
path: string,
opts?: { range?: string; offset?: number; limit?: number }
- ): AsyncIterable<Uint8Array> {
+ ): Promise<ReadBytesResponse<ReadBytesStream>> {
+ const res = await this.fetchDownload(path, opts, "Download stream failed");
+ return createReadBytesResponse(res, readResponseBody(res));
+ }
+
+ private async fetchDownload(
+ path: string,
+ opts: { range?: string; offset?: number; limit?: number } | undefined,
+ errorMessage: string,
+ ): Promise<Response> {
let url =
joinUrl(this.opts.baseUrl, "/files/download") +
`?path=${encodeURIComponent(path)}`;
@@ -636,20 +629,25 @@ export class FilesystemAdapter implements SandboxFiles {
const requestId = res.headers.get("x-request-id") ?? undefined;
const rawBody = await res.text().catch(() => undefined);
throw new SandboxApiException({
- message: "Download stream failed",
+ message: errorMessage,
statusCode: res.status,
requestId,
error: new SandboxError(
SandboxError.UNEXPECTED_RESPONSE,
- "Download stream failed"
+ errorMessage
),
rawBody,
});
}
+ return res;
+ }
- const body = res.body as ReadableStream<Uint8Array> | null;
- if (!body) return;
- yield* iterateBodyStream(body);
+ private async *downloadStream(
+ path: string,
+ opts?: { range?: string; offset?: number; limit?: number }
+ ): AsyncIterable<Uint8Array> {
+ const response = await this.readBytesStreamDetailed(path, opts);
+ yield* response.body;
}
async readFile(
diff --git a/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts b/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts
index ad84e7215..a38a10852 100644
--- a/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts
+++ b/sdks/sandbox/javascript/src/adapters/isolatedFilesystemAdapter.ts
@@ -34,14 +34,16 @@ import type {
Permission,
RenameFileItem,
ReplaceFileContentItem,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SearchFilesResponse,
SetPermissionEntry,
WriteEntry,
} from "../models/filesystem.js";
import { SandboxApiException, SandboxError } from "../core/exceptions.js";
-import { iterateBodyStream } from "../core/streams.js";
import { throwOnUploadFailure } from "./uploadFailure.js";
+import { createReadBytesResponse, readResponseBody } from "./downloadResponse.js";
function joinUrl(baseUrl: string, pathname: string): string {
const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
@@ -364,33 +366,16 @@ export class IsolatedFilesystemAdapter implements SandboxFiles {
path: string,
opts?: { range?: string; offset?: number; limit?: number },
): Promise<Uint8Array> {
- let url =
- joinUrl(
- this.opts.baseUrl,
- `/v1/isolated/session/${encodeURIComponent(this.sessionId)}/files/download`,
- ) + `?path=${encodeURIComponent(path)}`;
- if (opts?.offset != null) url += `&offset=${opts.offset}`;
- if (opts?.limit != null) url += `&limit=${opts.limit}`;
- const res = await this.fetch(url, {
- method: "GET",
- headers: {
- ...(this.opts.headers ?? {}),
- ...(opts?.range ? { Range: opts.range } : {}),
- },
- });
- if (!res.ok) {
- const requestId = res.headers.get("x-request-id") ?? undefined;
- const rawBody = await res.text().catch(() => undefined);
- throw new SandboxApiException({
- message: "Download failed",
- statusCode: res.status,
- requestId,
- error: new SandboxError(SandboxError.UNEXPECTED_RESPONSE, "Download failed"),
- rawBody,
- });
- }
+ return (await this.readBytesDetailed(path, opts)).body;
+ }
+
+ async readBytesDetailed(
+ path: string,
+ opts?: { range?: string; offset?: number; limit?: number },
+ ): Promise<ReadBytesResponse<Uint8Array>> {
+ const res = await this.fetchDownload(path, opts, "Download failed");
const ab = await res.arrayBuffer();
- return new Uint8Array(ab);
+ return createReadBytesResponse(res, new Uint8Array(ab));
}
readBytesStream(
@@ -400,10 +385,19 @@ export class IsolatedFilesystemAdapter implements SandboxFiles {
return this.downloadStream(path, opts);
}
- private async *downloadStream(
+ async readBytesStreamDetailed(
path: string,
opts?: { range?: string; offset?: number; limit?: number },
- ): AsyncIterable<Uint8Array> {
+ ): Promise<ReadBytesResponse<ReadBytesStream>> {
+ const res = await this.fetchDownload(path, opts, "Download stream failed");
+ return createReadBytesResponse(res, readResponseBody(res));
+ }
+
+ private async fetchDownload(
+ path: string,
+ opts: { range?: string; offset?: number; limit?: number } | undefined,
+ errorMessage: string,
+ ): Promise<Response> {
let url =
joinUrl(
this.opts.baseUrl,
@@ -422,16 +416,22 @@ export class IsolatedFilesystemAdapter implements SandboxFiles {
const requestId = res.headers.get("x-request-id") ?? undefined;
const rawBody = await res.text().catch(() => undefined);
throw new SandboxApiException({
- message: "Download stream failed",
+ message: errorMessage,
statusCode: res.status,
requestId,
- error: new SandboxError(SandboxError.UNEXPECTED_RESPONSE, "Download stream failed"),
+ error: new SandboxError(SandboxError.UNEXPECTED_RESPONSE, errorMessage),
rawBody,
});
}
- const body = res.body as ReadableStream<Uint8Array> | null;
- if (!body) return;
- yield* iterateBodyStream(body);
+ return res;
+ }
+
+ private async *downloadStream(
+ path: string,
+ opts?: { range?: string; offset?: number; limit?: number },
+ ): AsyncIterable<Uint8Array> {
+ const response = await this.readBytesStreamDetailed(path, opts);
+ yield* response.body;
}
async readFile(
diff --git a/sdks/sandbox/javascript/src/index.ts b/sdks/sandbox/javascript/src/index.ts
index b57c60579..297a824b7 100644
--- a/sdks/sandbox/javascript/src/index.ts
+++ b/sdks/sandbox/javascript/src/index.ts
@@ -114,12 +114,15 @@ export type { SandboxFilter, SandboxManagerOptions } from "./manager.js";
export type { ExecdHealth } from "./services/execdHealth.js";
export type { ExecdMetrics } from "./services/execdMetrics.js";
export type {
+ ByteRange,
FileEntryType,
FileInfo,
FileMetadata,
Permission,
RenameFileItem,
ReplaceFileContentItem,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchFilesResponse,
FilesInfoResponse,
} from "./models/filesystem.js";
diff --git a/sdks/sandbox/javascript/src/models/filesystem.ts b/sdks/sandbox/javascript/src/models/filesystem.ts
index 602b73bb6..9379673b5 100644
--- a/sdks/sandbox/javascript/src/models/filesystem.ts
+++ b/sdks/sandbox/javascript/src/models/filesystem.ts
@@ -66,6 +66,36 @@ export type FilesInfoResponse = Record<string, FileInfo>;
export type SearchFilesResponse = FileInfo[];
+export interface ByteRange {
+ /** Inclusive first byte offset, or -1 if parsing failed. */
+ start: number;
+ /** Inclusive last byte offset, or -1 if parsing failed. */
+ end: number;
+ /** Complete file size, or -1 if unknown or parsing failed. */
+ total: number;
+ /** Original Content-Range header value. */
+ raw: string;
+}
+
+export interface ReadBytesResponse<TBody> {
+ body: TBody;
+ statusCode: number;
+ contentType?: string;
+ contentDisposition?: string;
+ /** Response body size, or -1 if the Content-Length header is unavailable. */
+ contentLength: number;
+ /** Complete file size, or -1 if unknown. */
+ totalSize: number;
+ contentRange?: ByteRange;
+ /** Whether the server returned 206 Partial Content. */
+ isPartial: boolean;
+}
+
+/** A single-use download body that can be closed without consuming it. */
+export interface ReadBytesStream extends AsyncIterable<Uint8Array> {
+ close(): Promise<void>;
+}
+
// High-level filesystem facade models used by `sandbox.files`.
export interface WriteEntry {
path: string;
@@ -113,4 +143,4 @@ export interface SetPermissionEntry {
mode: number;
owner?: string;
group?: string;
-}
\ No newline at end of file
+}
diff --git a/sdks/sandbox/javascript/src/services/filesystem.ts b/sdks/sandbox/javascript/src/services/filesystem.ts
index b80c38c02..a2819004a 100644
--- a/sdks/sandbox/javascript/src/services/filesystem.ts
+++ b/sdks/sandbox/javascript/src/services/filesystem.ts
@@ -19,6 +19,8 @@ import type {
DirectoryListEntry,
FileInfo,
MoveEntry,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -42,7 +44,9 @@ export interface SandboxFiles {
writeFiles(entries: WriteEntry[]): Promise<void>;
readFile(path: string, opts?: { encoding?: string; range?: string; offset?: number; limit?: number }): Promise<string>;
readBytes(path: string, opts?: { range?: string; offset?: number; limit?: number }): Promise<Uint8Array>;
+ readBytesDetailed(path: string, opts?: { range?: string; offset?: number; limit?: number }): Promise<ReadBytesResponse<Uint8Array>>;
readBytesStream(path: string, opts?: { range?: string; offset?: number; limit?: number }): AsyncIterable<Uint8Array>;
+ readBytesStreamDetailed(path: string, opts?: { range?: string; offset?: number; limit?: number }): Promise<ReadBytesResponse<ReadBytesStream>>;
deleteFiles(paths: string[]): Promise<void>;
moveFiles(entries: MoveEntry[]): Promise<void>;
diff --git a/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs b/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs
new file mode 100644
index 000000000..ea90148d8
--- /dev/null
+++ b/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs
@@ -0,0 +1,168 @@
+// Copyright 2026 Alibaba Group Holding Ltd.
+//
+// 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 test from "node:test";
+
+import { FilesystemAdapter, createExecdClient } from "../dist/internal.js";
+
+const baseUrl = "http://execd.test";
+
+function createAdapter(fetch) {
+ const client = createExecdClient({ baseUrl, fetch });
+ return new FilesystemAdapter(client, { baseUrl, fetch });
+}
+
+async function collect(stream) {
+ const chunks = [];
+ for await (const chunk of stream) chunks.push(...chunk);
+ return new Uint8Array(chunks);
+}
+
+test("readBytesDetailed exposes partial response metadata", async () => {
+ const adapter = createAdapter(async (input, init) => {
+ assert.equal(new URL(input).pathname, "/files/download");
+ assert.equal(new Headers(init.headers).get("range"), "bytes=0-4");
+ return new Response("hello", {
+ status: 206,
+ headers: {
+ "Content-Type": "application/octet-stream",
+ "Content-Disposition": 'attachment; filename="data.bin"',
+ "Content-Length": "5",
+ "Content-Range": "bytes 0-4/10",
+ },
+ });
+ });
+
+ const response = await adapter.readBytesDetailed("/data.bin", {
+ range: "bytes=0-4",
+ });
+
+ assert.deepEqual(response.body, new TextEncoder().encode("hello"));
+ assert.equal(response.statusCode, 206);
+ assert.equal(response.isPartial, true);
+ assert.equal(response.contentType, "application/octet-stream");
+ assert.equal(response.contentDisposition, 'attachment; filename="data.bin"');
+ assert.equal(response.contentLength, 5);
+ assert.equal(response.totalSize, 10);
+ assert.deepEqual(response.contentRange, {
+ start: 0,
+ end: 4,
+ total: 10,
+ raw: "bytes 0-4/10",
+ });
+});
+
+test("readBytesDetailed identifies an ignored Range request", async () => {
+ const adapter = createAdapter(async () =>
+ new Response("whole file", {
+ status: 200,
+ headers: { "Content-Length": "10" },
+ }),
+ );
+
+ const response = await adapter.readBytesDetailed("/data.bin", {
+ range: "bytes=5-",
+ });
+
+ assert.equal(response.statusCode, 200);
+ assert.equal(response.isPartial, false);
+ assert.equal(response.contentRange, undefined);
+ assert.equal(response.contentLength, 10);
+ assert.equal(response.totalSize, 10);
+});
+
+test("readBytesDetailed preserves malformed and unknown Content-Range values", async () => {
+ const ranges = ["garbage", "bytes 5-9/*"];
+ const adapter = createAdapter(async () =>
+ new Response("hello", {
+ status: 206,
+ headers: { "Content-Range": ranges.shift() },
+ }),
+ );
+
+ const malformed = await adapter.readBytesDetailed("/data.bin");
+ assert.deepEqual(malformed.contentRange, {
+ start: -1,
+ end: -1,
+ total: -1,
+ raw: "garbage",
+ });
+ assert.equal(malformed.totalSize, -1);
+
+ const unknown = await adapter.readBytesDetailed("/data.bin");
+ assert.deepEqual(unknown.contentRange, {
+ start: 5,
+ end: 9,
+ total: -1,
+ raw: "bytes 5-9/*",
+ });
+ assert.equal(unknown.totalSize, -1);
+});
+
+test("detailed and legacy streaming reads return the response body", async () => {
+ const adapter = createAdapter(async () =>
+ new Response("hello", {
+ status: 206,
+ headers: {
+ "Content-Length": "5",
+ "Content-Range": "bytes 0-4/10",
+ },
+ }),
+ );
+
+ const detailed = await adapter.readBytesStreamDetailed("/data.bin", {
+ range: "bytes=0-4",
+ });
+ assert.equal(detailed.isPartial, true);
+ assert.deepEqual(await collect(detailed.body), new TextEncoder().encode("hello"));
+
+ assert.deepEqual(
+ await adapter.readBytes("/data.bin"),
+ new TextEncoder().encode("hello"),
+ );
+ assert.deepEqual(
+ await collect(adapter.readBytesStream("/data.bin")),
+ new TextEncoder().encode("hello"),
+ );
+});
+
+test("detailed streams cancel unconsumed and partially consumed bodies", async () => {
+ const cancelled = [];
+ const adapter = createAdapter(async () => {
+ const index = cancelled.length;
+ cancelled.push(false);
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode("hello"));
+ },
+ cancel() {
+ cancelled[index] = true;
+ },
+ }),
+ { status: 206, headers: { "Content-Range": "bytes 0-4/10" } },
+ );
+ });
+
+ const unconsumed = await adapter.readBytesStreamDetailed("/data.bin");
+ await unconsumed.body.close();
+ assert.equal(cancelled[0], true);
+
+ const partial = await adapter.readBytesStreamDetailed("/data.bin");
+ for await (const _chunk of partial.body) {
+ break;
+ }
+ assert.equal(cancelled[1], true);
+});
diff --git a/sdks/sandbox/javascript/tests/public-exports.test.mjs b/sdks/sandbox/javascript/tests/public-exports.test.mjs
index 719c4348d..d2712e8f8 100644
--- a/sdks/sandbox/javascript/tests/public-exports.test.mjs
+++ b/sdks/sandbox/javascript/tests/public-exports.test.mjs
@@ -33,11 +33,14 @@ function exportedDeclarationNames(declarations) {
return names;
}
-test("public type declarations export credential substitution models", async () => {
+test("public type declarations export stable models", async () => {
const declarations = await readFile(new URL("../dist/index.d.ts", import.meta.url), "utf8");
assert.match(declarations, /\bCredentialSubstitution\b/);
assert.match(declarations, /\bCredentialSubstitutionSurface\b/);
+ assert.match(declarations, /\bByteRange\b/);
+ assert.match(declarations, /\bReadBytesResponse\b/);
+ assert.match(declarations, /\bReadBytesStream\b/);
});
test("public type declarations export lifecycle models", async () => {