Skip to content

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

fix(sdks): preserve custom filesystem adapter compatibility

wenmouc0ac5f5928d6
diff --git a/docs/sdks/csharp.md b/docs/sdks/csharp.md
index cf926e523..08483bc44 100644
--- a/docs/sdks/csharp.md
+++ b/docs/sdks/csharp.md
@@ -369,7 +369,7 @@ await sandbox.Files.DeleteDirectoriesAsync(new[] { "/tmp/demo" });
For binary data, use `byte[]` or `Stream` in `WriteEntry.Data`, and download with `ReadBytesAsync()` or `ReadBytesStreamAsync()`. Read options support partial downloads.
-Use `ReadBytesDetailedAsync` or `ReadBytesStreamDetailedAsync` when Range response metadata is required. Dispose a detailed stream body if it is not fully consumed.
+Use `ReadBytesDetailedAsync` or `ReadBytesStreamDetailedAsync` for the body together with HTTP status and range metadata; unknown sizes use `-1`. Check `IsPartial` before appending a resumed download, and dispose a detailed stream body with `await using`. These extension methods are in `OpenSandbox`; custom adapters must implement `IDownloadSandboxFiles` or the methods throw `NotSupportedException`.
#### File operations with an explicit identity
diff --git a/docs/sdks/go.md b/docs/sdks/go.md
index d2003cc76..e59a61648 100644
--- a/docs/sdks/go.md
+++ b/docs/sdks/go.md
@@ -272,6 +272,17 @@ if err := sandbox.DeleteFiles(ctx, []string{"/tmp/demo.txt"}); err != nil {
The same upload/download methods support binary files. Pass a Range header such as `"bytes=0-1023"` to `DownloadFile` for a partial download.
+Use `DownloadFileResponse` for the body together with HTTP status and range metadata; unknown sizes use `-1`. Check `IsPartial()` before appending a resumed download, and close `Body` after use:
+
+```go
+download, err := sandbox.DownloadFileResponse(ctx, "/tmp/data.bin", "bytes=5-")
+if err != nil {
+ return err
+}
+defer download.Body.Close()
+fmt.Println(download.IsPartial(), download.TotalSize, download.ContentRange)
+```
+
#### File operations with an explicit identity
Bind a filesystem client to a Linux UID and GID:
@@ -287,6 +298,8 @@ The bound client exposes the usual file operations and shares the sandbox connec
This requires Linux and an Execd version that supports filesystem execution identity. Unsupported servers return an error; requests never fall back to the default filesystem routes. Keep sandbox credentials and identity selection in the trusted backend. Linux filesystem permissions apply; this feature does not create a tenant isolation boundary. See [Execd](/architecture/data-plane/execd) for permission and workspace provisioning details.
+For download metadata on this client, check the optional capability with `downloads, ok := files.(opensandbox.DownloadFilesystem)`, then call `downloads.DownloadFileResponse` when `ok` is true.
+
### Pause and reconnect
Pause is asynchronous and runtime-dependent. Use a deadline before resuming:
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.md
index d4b0caea2..53a9c7234 100644
--- a/docs/sdks/javascript.md
+++ b/docs/sdks/javascript.md
@@ -341,7 +341,16 @@ 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.
+Use `readBytesDetailed` or `readBytesStreamDetailed` for the body together with HTTP status and range metadata; unknown sizes use `-1`. Both methods are optional on `SandboxFiles`; check for support before calling them. Close a detailed stream body with `await download.body.close()` if it is not fully consumed.
+
+```ts
+if (sandbox.files.readBytesDetailed) {
+ const download = await sandbox.files.readBytesDetailed("/tmp/data.bin", { range: "bytes=5-" });
+ console.log(download.isPartial, download.totalSize, download.contentRange);
+}
+```
+
+Check `isPartial` before appending a resumed download: a `200` response means the server ignored Range and returned the whole file.
#### File operations with an explicit identity
diff --git a/docs/sdks/kotlin.md b/docs/sdks/kotlin.md
index 5c16c4f45..c873e719d 100644
--- a/docs/sdks/kotlin.md
+++ b/docs/sdks/kotlin.md
@@ -391,7 +391,7 @@ files.forEach(f -> System.out.println("Found: " + f.getPath()));
sandbox.files().deleteFiles(List.of("/tmp/hello.txt"));
```
-Use `readByteArrayDetailed` or `readStreamDetailed` when Range response metadata is required.
+Use `readByteArrayDetailed` or `readStreamDetailed` for the body together with HTTP status and range metadata; unknown sizes use `-1`. Check `isPartial` before appending a resumed download, and close a detailed stream body with try-with-resources or Kotlin's `use`. Custom adapters that do not override these methods throw `UnsupportedOperationException`.
#### File operations with an explicit identity
diff --git a/docs/sdks/python.md b/docs/sdks/python.md
index 0ae3cfe80..2783e6188 100644
--- a/docs/sdks/python.md
+++ b/docs/sdks/python.md
@@ -428,7 +428,18 @@ async with aclosing(await sandbox.files.read_bytes_stream("/tmp/large.bin")) as
break
```
-Use `read_bytes_detailed` or `read_bytes_stream_detailed` when Range response metadata is required. Close a detailed stream body if it is not fully consumed.
+Use `read_bytes_detailed` or `read_bytes_stream_detailed` for the body together with HTTP status and range metadata; unknown sizes use `-1`. Check the optional `DownloadFilesystem` capability before calling them:
+
+```python
+from opensandbox.services import DownloadFilesystem
+
+files = sandbox.files
+if isinstance(files, DownloadFilesystem):
+ download = await files.read_bytes_detailed("/tmp/data.bin", range_header="bytes=5-")
+ print(download.is_partial, download.total_size, download.content_range)
+```
+
+Check `is_partial` before appending a resumed download. Use `async with download.body` for a detailed stream so it closes even on early exit. The synchronous equivalent uses `DownloadFilesystemSync` from `opensandbox.sync.services` and `with download.body`.
#### File operations with an explicit identity
diff --git a/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs b/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs
index fd25d5412..2541b3d65 100644
--- a/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs
+++ b/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs
@@ -27,7 +27,7 @@ namespace OpenSandbox.Adapters;
/// <summary>
/// Adapter for the execd filesystem service.
/// </summary>
-internal sealed class FilesystemAdapter : IIdentitySandboxFiles
+internal sealed class FilesystemAdapter : IIdentitySandboxFiles, IDownloadSandboxFiles
{
internal const uint MaxIdentityId = uint.MaxValue - 1;
private readonly HttpClientWrapper _client;
diff --git a/sdks/sandbox/csharp/src/OpenSandbox/SandboxFilesExtensions.cs b/sdks/sandbox/csharp/src/OpenSandbox/SandboxFilesExtensions.cs
new file mode 100644
index 000000000..b9d14787c
--- /dev/null
+++ b/sdks/sandbox/csharp/src/OpenSandbox/SandboxFilesExtensions.cs
@@ -0,0 +1,48 @@
+// 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.
+
+using OpenSandbox.Models;
+using OpenSandbox.Services;
+
+namespace OpenSandbox;
+
+/// <summary>Optional download metadata operations on filesystem adapters.</summary>
+public static class SandboxFilesExtensions
+{
+ /// <summary>Reads file bytes and HTTP response metadata.</summary>
+ /// <exception cref="NotSupportedException">The adapter does not support download metadata.</exception>
+ public static Task<ReadBytesResponse<byte[]>> ReadBytesDetailedAsync(
+ this ISandboxFiles files,
+ string path,
+ ReadBytesOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (files is not IDownloadSandboxFiles downloads)
+ throw new NotSupportedException("The selected filesystem adapter does not support download metadata.");
+ return downloads.ReadBytesDetailedAsync(path, options, cancellationToken);
+ }
+
+ /// <summary>Opens a byte stream with HTTP response metadata; dispose the body after use.</summary>
+ /// <exception cref="NotSupportedException">The adapter does not support download metadata.</exception>
+ public static Task<ReadBytesResponse<IAsyncReadBytesStream>> ReadBytesStreamDetailedAsync(
+ this ISandboxFiles files,
+ string path,
+ ReadBytesOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (files is not IDownloadSandboxFiles downloads)
+ throw new NotSupportedException("The selected filesystem adapter does not support download metadata.");
+ return downloads.ReadBytesStreamDetailedAsync(path, options, cancellationToken);
+ }
+}
diff --git a/sdks/sandbox/csharp/src/OpenSandbox/Services/ISandboxFiles.cs b/sdks/sandbox/csharp/src/OpenSandbox/Services/ISandboxFiles.cs
index d3bc6dfe1..80c4a61a3 100644
--- a/sdks/sandbox/csharp/src/OpenSandbox/Services/ISandboxFiles.cs
+++ b/sdks/sandbox/csharp/src/OpenSandbox/Services/ISandboxFiles.cs
@@ -121,20 +121,6 @@ public interface ISandboxFiles
ReadBytesOptions? options = null,
CancellationToken cancellationToken = default);
- /// <summary>
- /// Reads a file as bytes together with HTTP response metadata.
- /// </summary>
- /// <param name="path">The file path.</param>
- /// <param name="options">Optional read options.</param>
- /// <param name="cancellationToken">Cancellation token.</param>
- /// <returns>The file content and HTTP response metadata.</returns>
- /// <exception cref="InvalidArgumentException">Thrown when request values are invalid.</exception>
- /// <exception cref="SandboxException">Thrown when the execd service request fails.</exception>
- Task<ReadBytesResponse<byte[]>> ReadBytesDetailedAsync(
- string path,
- ReadBytesOptions? options = null,
- CancellationToken cancellationToken = default);
-
/// <summary>
/// Reads a file as a stream of byte chunks.
/// </summary>
@@ -149,20 +135,6 @@ public interface ISandboxFiles
ReadBytesOptions? options = null,
CancellationToken cancellationToken = default);
- /// <summary>
- /// Reads a file as a byte stream together with HTTP response metadata.
- /// </summary>
- /// <param name="path">The file path.</param>
- /// <param name="options">Optional read options.</param>
- /// <param name="cancellationToken">Cancellation token.</param>
- /// <returns>The byte stream and HTTP response metadata.</returns>
- /// <exception cref="InvalidArgumentException">Thrown when request values are invalid.</exception>
- /// <exception cref="SandboxException">Thrown when the execd service request fails.</exception>
- Task<ReadBytesResponse<IAsyncReadBytesStream>> ReadBytesStreamDetailedAsync(
- string path,
- ReadBytesOptions? options = null,
- CancellationToken cancellationToken = default);
-
/// <summary>
/// Deletes files at the specified paths.
/// </summary>
@@ -220,6 +192,22 @@ public interface ISandboxFiles
CancellationToken cancellationToken = default);
}
+/// <summary>Optional filesystem capability for HTTP download response metadata.</summary>
+public interface IDownloadSandboxFiles : ISandboxFiles
+{
+ /// <summary>Reads a file as bytes together with HTTP response metadata.</summary>
+ Task<ReadBytesResponse<byte[]>> ReadBytesDetailedAsync(
+ string path,
+ ReadBytesOptions? options = null,
+ CancellationToken cancellationToken = default);
+
+ /// <summary>Reads a file as a byte stream together with HTTP response metadata.</summary>
+ Task<ReadBytesResponse<IAsyncReadBytesStream>> ReadBytesStreamDetailedAsync(
+ string path,
+ ReadBytesOptions? options = null,
+ CancellationToken cancellationToken = default);
+}
+
/// <summary>Filesystem capability for explicit execution identities.</summary>
public interface IIdentitySandboxFiles : ISandboxFiles
{
diff --git a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs
index e8400cbf5..0127abd29 100644
--- a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs
+++ b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs
@@ -19,6 +19,7 @@ using OpenSandbox.Adapters;
using OpenSandbox.Core;
using OpenSandbox.Internal;
using OpenSandbox.Models;
+using OpenSandbox.Services;
using Xunit;
namespace OpenSandbox.Tests;
@@ -345,7 +346,7 @@ public class FilesystemAdapterTests
errorContent.Disposed.Should().BeTrue();
}
- private static FilesystemAdapter CreateAdapter(HttpClient client)
+ private static ISandboxFiles CreateAdapter(HttpClient client)
{
var wrapper = new HttpClientWrapper(client, "http://localhost:8080");
return new FilesystemAdapter(wrapper, "http://localhost:8080", new Dictionary<string, string>());
diff --git a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/SandboxEgressLifecycleTests.cs b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/SandboxEgressLifecycleTests.cs
index 5132244b6..51aa22709 100644
--- a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/SandboxEgressLifecycleTests.cs
+++ b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/SandboxEgressLifecycleTests.cs
@@ -26,6 +26,17 @@ namespace OpenSandbox.Tests;
public class SandboxEgressLifecycleTests
{
+ [Fact]
+ public async Task LegacyFilesystem_ShouldRejectUnsupportedDownloadMetadata()
+ {
+ ISandboxFiles files = new StubFiles();
+ Func<Task> bytes = () => files.ReadBytesDetailedAsync("/data.bin");
+ Func<Task> stream = () => files.ReadBytesStreamDetailedAsync("/data.bin");
+
+ await bytes.Should().ThrowAsync<NotSupportedException>().WithMessage("*download metadata*");
+ await stream.Should().ThrowAsync<NotSupportedException>().WithMessage("*download metadata*");
+ }
+
[Fact]
public async Task CreateAsync_ShouldBuildEgressStackOnce_AndReuseItForOperations()
{
@@ -929,15 +940,9 @@ public class SandboxEgressLifecycleTests
public Task<byte[]> ReadBytesAsync(string path, ReadBytesOptions? options = null, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
- public Task<ReadBytesResponse<byte[]>> ReadBytesDetailedAsync(string path, ReadBytesOptions? options = null, CancellationToken cancellationToken = default) =>
- throw new NotImplementedException();
-
public IAsyncEnumerable<byte[]> ReadBytesStreamAsync(string path, ReadBytesOptions? options = null, CancellationToken cancellationToken = default) =>
AsyncEnumerable.Empty<byte[]>();
- public Task<ReadBytesResponse<IAsyncReadBytesStream>> ReadBytesStreamDetailedAsync(string path, ReadBytesOptions? options = null, CancellationToken cancellationToken = default) =>
- throw new NotImplementedException();
-
public Task DeleteFilesAsync(IEnumerable<string> paths, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
diff --git a/sdks/sandbox/go/execd.go b/sdks/sandbox/go/execd.go
index a638d9324..d0bc4e467 100644
--- a/sdks/sandbox/go/execd.go
+++ b/sdks/sandbox/go/execd.go
@@ -459,6 +459,13 @@ type ByteRange struct {
Raw string
}
+// DownloadFilesystem is the optional capability for HTTP download metadata.
+// ExecdClient implements it, including clients returned by FilesWithIdentity.
+// Callers must close the returned response body.
+type DownloadFilesystem interface {
+ DownloadFileResponse(context.Context, string, string, ...DownloadFileOptions) (*DownloadFileResponse, error)
+}
+
// DownloadFileResponse contains a download body and its HTTP response
// metadata. The caller must close Body.
type DownloadFileResponse struct {
diff --git a/sdks/sandbox/go/filesystem_identity.go b/sdks/sandbox/go/filesystem_identity.go
index be43a756f..ead84a941 100644
--- a/sdks/sandbox/go/filesystem_identity.go
+++ b/sdks/sandbox/go/filesystem_identity.go
@@ -23,6 +23,7 @@ import (
// IdentityFilesystem exposes file operations bound to explicit Linux credentials.
// It shares the sandbox transport without changing its default filesystem client.
+// For download metadata, use the optional DownloadFilesystem capability.
type IdentityFilesystem interface {
GetFileInfo(context.Context, string) (map[string]FileInfo, error)
DeleteFiles(context.Context, []string) error
diff --git a/sdks/sandbox/go/filesystem_identity_test.go b/sdks/sandbox/go/filesystem_identity_test.go
index 9f783143b..385d2c29a 100644
--- a/sdks/sandbox/go/filesystem_identity_test.go
+++ b/sdks/sandbox/go/filesystem_identity_test.go
@@ -66,15 +66,22 @@ func TestFilesWithIdentityPreservesTransportAndDefaultClient(t *testing.T) {
t.Errorf("missing request for %s", path)
}
}
- body, err := a.DownloadFile(context.Background(), "/file", "")
+ downloads, ok := a.(DownloadFilesystem)
+ if !ok {
+ t.Fatal("identity filesystem does not expose download metadata")
+ }
+ download, err := downloads.DownloadFileResponse(context.Background(), "/file", "")
if err != nil {
t.Fatal(err)
}
- _, err = io.ReadAll(body)
- _ = body.Close()
+ _, err = io.ReadAll(download.Body)
+ _ = download.Body.Close()
if err != nil {
t.Fatal(err)
}
+ if download.StatusCode != http.StatusOK || download.ContentLength != 2 || download.TotalSize != 2 {
+ t.Fatalf("unexpected download metadata: %+v", download)
+ }
if path := <-paths; path != prefix+"/v1/filesystem/1001/2000/files/download" {
t.Errorf("download path = %s", path)
}
diff --git a/sdks/sandbox/javascript/src/services/filesystem.ts b/sdks/sandbox/javascript/src/services/filesystem.ts
index a2819004a..551c30bec 100644
--- a/sdks/sandbox/javascript/src/services/filesystem.ts
+++ b/sdks/sandbox/javascript/src/services/filesystem.ts
@@ -44,9 +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>>;
+ 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>>;
+ 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/public-exports.test.mjs b/sdks/sandbox/javascript/tests/public-exports.test.mjs
index d2712e8f8..b12a52349 100644
--- a/sdks/sandbox/javascript/tests/public-exports.test.mjs
+++ b/sdks/sandbox/javascript/tests/public-exports.test.mjs
@@ -15,6 +15,8 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
+import { fileURLToPath } from "node:url";
+import ts from "typescript";
function exportedDeclarationNames(declarations) {
const names = new Set(
@@ -38,9 +40,41 @@ test("public type declarations export stable models", async () => {
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("legacy filesystem adapters remain assignable to the public filesystem interface", () => {
+ const filename = fileURLToPath(new URL("./filesystem-compatibility.mts", import.meta.url));
+ const source = `
+ import type { ByteRange, ReadBytesResponse, ReadBytesStream, Sandbox, SandboxFiles } from "../dist/index.js";
+ type LegacyFiles = Omit<SandboxFiles, "readBytesDetailed" | "readBytesStreamDetailed">;
+ function configure(files: LegacyFiles): Sandbox["files"] { return files; }
+ async function download(files: SandboxFiles) {
+ if (files.readBytesDetailed && files.readBytesStreamDetailed) {
+ await files.readBytesDetailed("/data.bin");
+ const response: ReadBytesResponse<ReadBytesStream> = await files.readBytesStreamDetailed("/data.bin");
+ const range: ByteRange | undefined = response.contentRange;
+ await response.body.close();
+ }
+ }
+ `;
+ const options = {
+ strict: true,
+ noEmit: true,
+ skipLibCheck: true,
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.NodeNext,
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
+ };
+ const host = ts.createCompilerHost(options);
+ const getSourceFile = host.getSourceFile;
+ host.getSourceFile = (path, ...args) => path === filename
+ ? ts.createSourceFile(path, source, options.target, true)
+ : getSourceFile(path, ...args);
+ const program = ts.createProgram([filename], options, host);
+ const errors = ts.getPreEmitDiagnostics(program).map(
+ (diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
+ );
+ assert.deepEqual(errors, []);
});
test("public type declarations export lifecycle models", async () => {
diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/domain/services/Filesystem.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/domain/services/Filesystem.kt
index 93a154e26..604379fe4 100644
--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/domain/services/Filesystem.kt
+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/domain/services/Filesystem.kt
@@ -124,7 +124,9 @@ interface Filesystem {
range: String? = null,
offset: Int? = null,
limit: Int? = null,
- ): ReadBytesResponse<ByteArray>
+ ): ReadBytesResponse<ByteArray> {
+ throw UnsupportedOperationException("The filesystem adapter does not support download metadata")
+ }
/**
* Opens a file for reading as an InputStream.
@@ -173,7 +175,9 @@ interface Filesystem {
range: String? = null,
offset: Int? = null,
limit: Int? = null,
- ): ReadBytesResponse<InputStream>
+ ): ReadBytesResponse<InputStream> {
+ throw UnsupportedOperationException("The filesystem adapter does not support download metadata")
+ }
/**
* Writes content to files based on the provided write entries.
diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/DownloadResponseMapper.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/DownloadResponseMapper.kt
index 9a98915d0..48804db2d 100644
--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/DownloadResponseMapper.kt
+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/DownloadResponseMapper.kt
@@ -39,7 +39,10 @@ private fun parseContentRange(raw: String?): ByteRange? {
return ByteRange(start = start, end = end, total = total, raw = raw)
}
-internal fun <T> Response.toReadBytesResponse(body: T, lineBased: Boolean): ReadBytesResponse<T> {
+internal fun <T> Response.toReadBytesResponse(
+ body: T,
+ lineBased: Boolean,
+): ReadBytesResponse<T> {
val isPartial = code == 206
val contentLength = header("Content-Length")?.toLongOrNull()?.takeIf { it >= 0 } ?: -1
val contentRange = if (isPartial) parseContentRange(header("Content-Range")) else null
@@ -49,7 +52,14 @@ internal fun <T> Response.toReadBytesResponse(body: T, lineBased: Boolean): Read
contentType = header("Content-Type"),
contentDisposition = header("Content-Disposition"),
contentLength = contentLength,
- totalSize = if (isPartial) contentRange?.total ?: -1 else if (lineBased) -1 else contentLength,
+ totalSize =
+ if (isPartial) {
+ contentRange?.total ?: -1
+ } else if (lineBased) {
+ -1
+ } else {
+ contentLength
+ },
contentRange = contentRange,
)
}
diff --git a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/domain/services/FilesystemCompatibilityTest.kt b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/domain/services/FilesystemCompatibilityTest.kt
new file mode 100644
index 000000000..ff38a448f
--- /dev/null
+++ b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/domain/services/FilesystemCompatibilityTest.kt
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+package com.alibaba.opensandbox.sandbox.domain.services
+
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.ContentReplaceEntry
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.ContentReplaceResult
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.EntryInfo
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.MoveEntry
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.SearchEntry
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.SetPermissionEntry
+import com.alibaba.opensandbox.sandbox.domain.models.execd.filesystem.WriteEntry
+import org.junit.jupiter.api.Assertions.assertArrayEquals
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.assertThrows
+import java.io.InputStream
+
+class FilesystemCompatibilityTest {
+ @Test
+ fun `legacy adapters work without implementing download metadata`() {
+ val files: Filesystem = LegacyFilesystem()
+
+ assertArrayEquals(byteArrayOf(1, 2), files.readByteArray("/data.bin"))
+ assertThrows<UnsupportedOperationException> { files.readByteArrayDetailed("/data.bin") }
+ assertThrows<UnsupportedOperationException> { files.readStreamDetailed("/data.bin") }
+ }
+
+ private class LegacyFilesystem : Filesystem {
+ override fun readFile(
+ path: String,
+ encoding: String,
+ range: String?,
+ offset: Int?,
+ limit: Int?,
+ ): String = unsupported()
+
+ override fun readByteArray(
+ path: String,
+ range: String?,
+ offset: Int?,
+ limit: Int?,
+ ): ByteArray = byteArrayOf(1, 2)
+
+ override fun readStream(
+ path: String,
+ range: String?,
+ offset: Int?,
+ limit: Int?,
+ ): InputStream = unsupported()
+
+ override fun write(entries: List<WriteEntry>) = unsupported()
+
+ override fun createDirectories(entries: List<WriteEntry>) = unsupported()
+
+ override fun deleteFiles(paths: List<String>) = unsupported()
+
+ override fun deleteDirectories(paths: List<String>) = unsupported()
+
+ override fun listDirectory(
+ path: String,
+ depth: Int?,
+ ): List<EntryInfo> = unsupported()
+
+ override fun moveFiles(entries: List<MoveEntry>) = unsupported()
+
+ override fun setPermissions(entries: List<SetPermissionEntry>) = unsupported()
+
+ override fun replaceContents(entries: List<ContentReplaceEntry>) = unsupported()
+
+ override fun replaceContentsDetailed(entries: List<ContentReplaceEntry>): List<ContentReplaceResult> = unsupported()
+
+ override fun search(entry: SearchEntry): List<EntryInfo> = unsupported()
+
+ override fun readFileInfo(paths: List<String>): Map<String, EntryInfo> = unsupported()
+
+ private fun unsupported(): Nothing = throw UnsupportedOperationException("not used")
+ }
+}
diff --git a/sdks/sandbox/python/src/opensandbox/services/__init__.py b/sdks/sandbox/python/src/opensandbox/services/__init__.py
index 59d4ca77e..aaee4068d 100644
--- a/sdks/sandbox/python/src/opensandbox/services/__init__.py
+++ b/sdks/sandbox/python/src/opensandbox/services/__init__.py
@@ -22,7 +22,7 @@ Protocol definitions for sandbox services.
from opensandbox.services.command import Commands
from opensandbox.services.diagnostics import Diagnostics
from opensandbox.services.egress import CredentialVault, Egress
-from opensandbox.services.filesystem import Filesystem
+from opensandbox.services.filesystem import DownloadFilesystem, Filesystem
from opensandbox.services.health import Health
from opensandbox.services.isolated import IsolationService, IsolationSession
from opensandbox.services.metrics import Metrics
@@ -32,6 +32,7 @@ __all__ = [
"Commands",
"CredentialVault",
"Diagnostics",
+ "DownloadFilesystem",
"Egress",
"Filesystem",
"Health",
diff --git a/sdks/sandbox/python/src/opensandbox/services/filesystem.py b/sdks/sandbox/python/src/opensandbox/services/filesystem.py
index 82fedb4fe..402ea6dc3 100644
--- a/sdks/sandbox/python/src/opensandbox/services/filesystem.py
+++ b/sdks/sandbox/python/src/opensandbox/services/filesystem.py
@@ -20,7 +20,7 @@ Protocol for sandbox filesystem operations.
"""
from collections.abc import AsyncGenerator
from io import IOBase
-from typing import Protocol
+from typing import Protocol, runtime_checkable
from opensandbox.models.filesystem import (
AsyncReadBytesStream,
@@ -103,15 +103,6 @@ class Filesystem(Protocol):
"""
...
- async def read_bytes_detailed(
- self,
- path: str,
- *,
- range_header: str | None = None,
- offset: int | None = None,
- limit: int | None = None,
- ) -> ReadBytesResponse[bytes]: ...
-
async def read_bytes_stream(
self,
path: str,
@@ -126,16 +117,6 @@ class Filesystem(Protocol):
"""
...
- async def read_bytes_stream_detailed(
- self,
- path: str,
- *,
- chunk_size: int = 64 * 1024,
- range_header: str | None = None,
- offset: int | None = None,
- limit: int | None = None,
- ) -> ReadBytesResponse[AsyncReadBytesStream]: ...
-
async def write_files(self, entries: list[WriteEntry]) -> None:
"""
Write content to files based on the provided write entries.
@@ -305,3 +286,27 @@ class Filesystem(Protocol):
SandboxException: if the operation fails
"""
...
+
+
+@runtime_checkable
+class DownloadFilesystem(Filesystem, Protocol):
+ """Optional filesystem capability for HTTP download response metadata."""
+
+ async def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]: ...
+
+ async def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[AsyncReadBytesStream]: ...
diff --git a/sdks/sandbox/python/src/opensandbox/sync/services/__init__.py b/sdks/sandbox/python/src/opensandbox/sync/services/__init__.py
index dca7eb070..5a61f5545 100644
--- a/sdks/sandbox/python/src/opensandbox/sync/services/__init__.py
+++ b/sdks/sandbox/python/src/opensandbox/sync/services/__init__.py
@@ -20,7 +20,7 @@ Synchronous service interfaces (Protocols) for the sync SDK.
from opensandbox.sync.services.command import CommandsSync
from opensandbox.sync.services.diagnostics import DiagnosticsSync
from opensandbox.sync.services.egress import CredentialVaultSync, EgressSync
-from opensandbox.sync.services.filesystem import FilesystemSync
+from opensandbox.sync.services.filesystem import DownloadFilesystemSync, FilesystemSync
from opensandbox.sync.services.health import HealthSync
from opensandbox.sync.services.isolated import (
IsolationServiceSync,
@@ -33,6 +33,7 @@ __all__ = [
"CommandsSync",
"CredentialVaultSync",
"DiagnosticsSync",
+ "DownloadFilesystemSync",
"EgressSync",
"FilesystemSync",
"HealthSync",
diff --git a/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py b/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
index 7a919e9ed..cdf2fe6ea 100644
--- a/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
+++ b/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
@@ -22,7 +22,7 @@ This is the sync counterpart of :mod:`opensandbox.services.filesystem`.
from collections.abc import Iterator
from io import IOBase
-from typing import Protocol
+from typing import Protocol, runtime_checkable
from opensandbox.models.filesystem import (
ContentReplaceEntry,
@@ -108,15 +108,6 @@ class FilesystemSync(Protocol):
"""
...
- def read_bytes_detailed(
- self,
- path: str,
- *,
- range_header: str | None = None,
- offset: int | None = None,
- limit: int | None = None,
- ) -> ReadBytesResponse[bytes]: ...
-
def read_bytes_stream(
self,
path: str,
@@ -142,16 +133,6 @@ class FilesystemSync(Protocol):
"""
...
- def read_bytes_stream_detailed(
- self,
- path: str,
- *,
- chunk_size: int = 64 * 1024,
- range_header: str | None = None,
- offset: int | None = None,
- limit: int | None = None,
- ) -> ReadBytesResponse[ReadBytesStream]: ...
-
def write_files(self, entries: list[WriteEntry]) -> None:
"""
Write content to files based on the provided write entries.
@@ -321,3 +302,27 @@ class FilesystemSync(Protocol):
SandboxException: If the operation fails.
"""
...
+
+
+@runtime_checkable
+class DownloadFilesystemSync(FilesystemSync, Protocol):
+ """Optional filesystem capability for HTTP download response metadata."""
+
+ def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]: ...
+
+ def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[ReadBytesStream]: ...
diff --git a/sdks/sandbox/python/tests/typecheck/filesystem_download.py b/sdks/sandbox/python/tests/typecheck/filesystem_download.py
index 37f749d54..f40f02a19 100644
--- a/sdks/sandbox/python/tests/typecheck/filesystem_download.py
+++ b/sdks/sandbox/python/tests/typecheck/filesystem_download.py
@@ -14,11 +14,25 @@
"""Type-check the public download cleanup examples without a live sandbox."""
+from collections.abc import AsyncGenerator, Iterator
from contextlib import aclosing
+from io import IOBase
+from typing import Protocol
from opensandbox.adapters.filesystem_adapter import FilesystemAdapter
from opensandbox.adapters.isolated_filesystem_adapter import IsolatedFilesystemAdapter
-from opensandbox.services.filesystem import Filesystem
+from opensandbox.models.filesystem import (
+ ContentReplaceEntry,
+ ContentReplaceResult,
+ DirectoryListEntry,
+ EntryInfo,
+ MoveEntry,
+ SearchEntry,
+ SetPermissionEntry,
+ WriteEntry,
+)
+from opensandbox.services import DownloadFilesystem, Filesystem
+from opensandbox.sync.services import DownloadFilesystemSync, FilesystemSync
async def close_download(
@@ -30,3 +44,158 @@ async def close_download(
async with aclosing(await files.read_bytes_stream("/tmp/large.bin")) as chunks:
async for _chunk in chunks:
break
+
+
+async def close_detailed_download(files: Filesystem) -> None:
+ if isinstance(files, DownloadFilesystem):
+ download = await files.read_bytes_stream_detailed("/tmp/large.bin")
+ async with download.body:
+ async for _chunk in download.body:
+ break
+
+
+def close_detailed_download_sync(files: FilesystemSync) -> None:
+ if isinstance(files, DownloadFilesystemSync):
+ with files.read_bytes_stream_detailed("/tmp/large.bin").body as chunks:
+ for _chunk in chunks:
+ break
+
+
+# Preserve the pre-metadata structural contracts to catch required-method regressions.
+class _LegacyAsyncFilesystem(Protocol):
+ async def read_file(
+ self,
+ path: str,
+ *,
+ encoding: str = "utf-8",
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> str: ...
+
+ async def read_bytes(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> bytes: ...
+
+ async def read_bytes_stream(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> AsyncGenerator[bytes, None]: ...
+
+ async def write_files(self, entries: list[WriteEntry]) -> None: ...
+
+ async def write_file(
+ self,
+ path: str,
+ data: str | bytes | IOBase,
+ *,
+ encoding: str = "utf-8",
+ mode: int = 755,
+ owner: str | None = None,
+ group: str | None = None,
+ ) -> None: ...
+
+ async def create_directories(self, entries: list[WriteEntry]) -> None: ...
+
+ async def delete_files(self, paths: list[str]) -> None: ...
+
+ async def delete_directories(self, paths: list[str]) -> None: ...
+
+ async def move_files(self, entries: list[MoveEntry]) -> None: ...
+
+ async def set_permissions(self, entries: list[SetPermissionEntry]) -> None: ...
+
+ async def replace_contents(self, entries: list[ContentReplaceEntry]) -> None: ...
+
+ async def replace_contents_detailed(
+ self, entries: list[ContentReplaceEntry]
+ ) -> list[ContentReplaceResult]: ...
+
+ async def search(self, entry: SearchEntry) -> list[EntryInfo]: ...
+
+ async def list_directory(self, entry: DirectoryListEntry) -> list[EntryInfo]: ...
+
+ async def get_file_info(self, paths: list[str]) -> dict[str, EntryInfo]: ...
+
+
+class _LegacySyncFilesystem(Protocol):
+ def read_file(
+ self,
+ path: str,
+ *,
+ encoding: str = "utf-8",
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> str: ...
+
+ def read_bytes(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> bytes: ...
+
+ def read_bytes_stream(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> Iterator[bytes]: ...
+
+ def write_files(self, entries: list[WriteEntry]) -> None: ...
+
+ def write_file(
+ self,
+ path: str,
+ data: str | bytes | IOBase,
+ *,
+ encoding: str = "utf-8",
+ mode: int = 755,
+ owner: str | None = None,
+ group: str | None = None,
+ ) -> None: ...
+
+ def create_directories(self, entries: list[WriteEntry]) -> None: ...
+
+ def delete_files(self, paths: list[str]) -> None: ...
+
+ def delete_directories(self, paths: list[str]) -> None: ...
+
+ def move_files(self, entries: list[MoveEntry]) -> None: ...
+
+ def set_permissions(self, entries: list[SetPermissionEntry]) -> None: ...
+
+ def replace_contents(self, entries: list[ContentReplaceEntry]) -> None: ...
+
+ def replace_contents_detailed(
+ self, entries: list[ContentReplaceEntry]
+ ) -> list[ContentReplaceResult]: ...
+
+ def search(self, entry: SearchEntry) -> list[EntryInfo]: ...
+
+ def list_directory(self, entry: DirectoryListEntry) -> list[EntryInfo]: ...
+
+ def get_file_info(self, paths: list[str]) -> dict[str, EntryInfo]: ...
+
+
+def accept_legacy_adapters(
+ async_files: _LegacyAsyncFilesystem,
+ sync_files: _LegacySyncFilesystem,
+) -> tuple[Filesystem, FilesystemSync]:
+ return async_files, sync_files