> files);
+ /**
+ * Uploads a single file from a caller-owned stream, replacing existing content according to
+ * the backend's upload semantics. The default implementation buffers the file and delegates
+ * to {@link #uploadFiles}; native streaming implementations avoid this full-file buffer.
+ *
+ * This blocking method consumes {@code content} through EOF without closing it. The input
+ * must contain exactly {@code contentLength} bytes. The operation is not guaranteed to be
+ * atomic: an I/O or length error may leave a partially written destination.
+ *
+ * @param runtimeContext per-call agent runtime; {@link RuntimeContext#empty()} when none
+ * @param path destination file path
+ * @param content file content
+ * @param contentLength exact number of bytes, must be nonnegative
+ * @return upload result; length mismatches and I/O failures are reported in {@code error}
+ */
+ default FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ validatePath(path);
+ try {
+ byte[] bytes = FilesystemUtils.readUpload(content, contentLength);
+ return uploadFiles(runtimeContext, List.of(Map.entry(path, bytes))).get(0);
+ } catch (IOException e) {
+ return FileUploadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ }
+ }
+
/**
* Download multiple files.
*
@@ -145,6 +176,37 @@ List uploadFiles(
*/
List downloadFiles(RuntimeContext runtimeContext, List paths);
+ /**
+ * Downloads a single file to a caller-owned stream. The default implementation delegates
+ * to {@link #downloadFiles} and buffers the file; native streaming implementations avoid
+ * this full-file buffer.
+ *
+ * This blocking method does not close or flush {@code sink}. A failed download may have
+ * already written partial content, so callers must not automatically retry into the same
+ * stream.
+ *
+ * @param runtimeContext per-call agent runtime; {@link RuntimeContext#empty()} when none
+ * @param path source file path
+ * @param sink destination for file bytes
+ * @return download result; bytes are written to {@code sink}, so {@code content} is
+ * {@code null} even on success; I/O failures are reported in {@code error}
+ */
+ default FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ validatePath(path);
+ Objects.requireNonNull(sink, "sink");
+ FileDownloadResponse response = downloadFiles(runtimeContext, List.of(path)).get(0);
+ if (!response.isSuccess()) {
+ return response;
+ }
+ try {
+ sink.write(response.content());
+ return FileDownloadResponse.success(path);
+ } catch (IOException e) {
+ return FileDownloadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ }
+ }
+
/**
* Delete a file or directory (recursive for directories).
*
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/BakedContextFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/BakedContextFilesystem.java
index 067cc01370..2577f82d48 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/BakedContextFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/BakedContextFilesystem.java
@@ -25,6 +25,8 @@
import io.agentscope.harness.agent.filesystem.model.LsResult;
import io.agentscope.harness.agent.filesystem.model.ReadResult;
import io.agentscope.harness.agent.filesystem.model.WriteResult;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -96,12 +98,24 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
return delegate.glob(bakedRc, pattern, path);
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ return delegate.uploadFile(bakedRc, path, content, contentLength);
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
return delegate.uploadFiles(bakedRc, files);
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ return delegate.downloadFile(bakedRc, path, sink);
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java
index 3a35772020..d43e45140f 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java
@@ -28,6 +28,8 @@
import io.agentscope.harness.agent.filesystem.model.ReadResult;
import io.agentscope.harness.agent.filesystem.model.WriteResult;
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
@@ -436,6 +438,18 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
return GlobResult.success(results);
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ RouteResult route = routeForPath(path);
+ FileUploadResponse response =
+ route.backend()
+ .uploadFile(runtimeContext, route.backendPath(), content, contentLength);
+ return response.isSuccess()
+ ? FileUploadResponse.success(path)
+ : FileUploadResponse.fail(path, response.error());
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
@@ -470,6 +484,17 @@ public List uploadFiles(
return List.of(results);
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ RouteResult route = routeForPath(path);
+ FileDownloadResponse response =
+ route.backend().downloadFile(runtimeContext, route.backendPath(), sink);
+ return response.isSuccess()
+ ? FileDownloadResponse.success(path)
+ : FileDownloadResponse.fail(path, response.error());
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java
index 2968e5580a..464cba4702 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java
@@ -29,6 +29,8 @@
import io.agentscope.harness.agent.filesystem.model.WriteResult;
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -295,12 +297,28 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
return GlobResult.success(new ArrayList<>(merged.values()));
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ return upper.uploadFile(runtimeContext, path, content, contentLength);
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
return upper.uploadFiles(runtimeContext, files);
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ if (upper.exists(runtimeContext, path)) {
+ return upper.downloadFile(runtimeContext, path, sink);
+ } else {
+ return lower.downloadFile(runtimeContext, path, sink);
+ }
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java
index 56b868be52..e71184935d 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java
@@ -29,6 +29,8 @@
import io.agentscope.harness.agent.filesystem.remote.store.NamespaceFactory;
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -227,6 +229,25 @@ public WriteResult delete(RuntimeContext runtimeContext, String path) {
return super.delete(runtimeContext, target);
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ String target = toWorkspaceRelativePath(runtimeContext, path);
+ FileUploadResponse response;
+ if (isWorkspacePath(runtimeContext, path)) {
+ response = upper().uploadFile(runtimeContext, target, content, contentLength);
+ } else {
+ WriteResult shadowed = shadowedByWorkspaceCopy(runtimeContext, target);
+ if (shadowed != null) {
+ return FileUploadResponse.fail(path, shadowed.error());
+ }
+ response = projectFs.uploadFile(runtimeContext, target, content, contentLength);
+ }
+ return response.isSuccess()
+ ? FileUploadResponse.success(path)
+ : FileUploadResponse.fail(path, response.error());
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
@@ -283,6 +304,17 @@ public boolean exists(RuntimeContext runtimeContext, String path) {
return viewFor(runtimeContext, target).exists(runtimeContext, target);
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ String target = toWorkspaceRelativePath(runtimeContext, path);
+ FileDownloadResponse response =
+ viewFor(runtimeContext, target).downloadFile(runtimeContext, target, sink);
+ return response.isSuccess()
+ ? FileDownloadResponse.success(path)
+ : FileDownloadResponse.fail(path, response.error());
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java
index cde7e6ebd5..6f05dbb200 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java
@@ -27,6 +27,8 @@
import io.agentscope.harness.agent.filesystem.model.ReadResult;
import io.agentscope.harness.agent.filesystem.model.WriteResult;
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -115,12 +117,24 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
return composite.glob(runtimeContext, pattern, path);
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ return composite.uploadFile(runtimeContext, path, content, contentLength);
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
return composite.uploadFiles(runtimeContext, files);
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ return composite.downloadFile(runtimeContext, path, sink);
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystem.java
index da0b9822fa..ac73b2f446 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystem.java
@@ -34,7 +34,9 @@
import io.agentscope.harness.agent.workspace.PathPolicy;
import java.io.BufferedReader;
import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
@@ -56,6 +58,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -636,6 +639,34 @@ public FileVisitResult visitFileFailed(Path file, IOException exc) {
return GlobResult.success(results);
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ Path resolved;
+ try {
+ resolved = resolvePath(runtimeContext, path);
+ if (isHiddenFromCaller(resolved)) {
+ return FileUploadResponse.fail(path, "path not found");
+ }
+ } catch (SecurityException | IllegalArgumentException e) {
+ return FileUploadResponse.fail(path, "permission_denied");
+ }
+ FilesystemUtils.validateUpload(content, contentLength);
+ try {
+ if (resolved.getParent() != null) {
+ Files.createDirectories(resolved.getParent());
+ }
+ try (OutputStream output = Files.newOutputStream(resolved)) {
+ FilesystemUtils.copyExactly(content, output, contentLength);
+ }
+ return FileUploadResponse.success(path);
+ } catch (IOException e) {
+ return FileUploadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ } catch (SecurityException e) {
+ return FileUploadResponse.fail(path, "permission_denied");
+ }
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
@@ -663,6 +694,34 @@ public List uploadFiles(
return responses;
}
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ Path resolved;
+ try {
+ resolved = resolvePath(runtimeContext, path);
+ } catch (SecurityException e) {
+ return FileDownloadResponse.fail(path, "permission_denied");
+ }
+ Objects.requireNonNull(sink, "File output stream must not be null");
+ try {
+ if (isHiddenFromCaller(resolved) || !Files.exists(resolved)) {
+ return FileDownloadResponse.fail(path, "file_not_found");
+ }
+ if (Files.isDirectory(resolved)) {
+ return FileDownloadResponse.fail(path, "is_directory");
+ }
+ try (InputStream input = Files.newInputStream(resolved)) {
+ input.transferTo(sink);
+ }
+ return FileDownloadResponse.success(path);
+ } catch (IOException e) {
+ return FileDownloadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ } catch (SecurityException e) {
+ return FileDownloadResponse.fail(path, "permission_denied");
+ }
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/model/FileDownloadResponse.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/model/FileDownloadResponse.java
index 16caab0e3b..7b714ce640 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/model/FileDownloadResponse.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/model/FileDownloadResponse.java
@@ -19,11 +19,17 @@
* Result of a single file download operation.
*
* @param path the file path that was requested
- * @param content file contents as bytes on success, {@code null} on failure
+ * @param content file contents for a successful byte-array download; {@code null} for a streamed
+ * download or on failure
* @param error error description on failure, {@code null} on success
*/
public record FileDownloadResponse(String path, byte[] content, String error) {
+ /** Creates a successful streamed download whose bytes were written to the caller's sink. */
+ public static FileDownloadResponse success(String path) {
+ return new FileDownloadResponse(path, null, null);
+ }
+
public static FileDownloadResponse success(String path, byte[] content) {
return new FileDownloadResponse(path, content, null);
}
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystem.java
index aec05aa0a9..17a24773d8 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystem.java
@@ -18,6 +18,7 @@
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
import io.agentscope.harness.agent.sandbox.Sandbox;
+import java.io.InputStream;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@@ -127,6 +128,20 @@ public boolean isSandboxReleased() {
return mirrorGate.released;
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ mirrorGate.lock.readLock().lock();
+ try {
+ if (mirrorGate.released || !pinnedSandbox.isRunning()) {
+ return FileUploadResponse.fail(path, "Sandbox has been released");
+ }
+ return super.uploadFile(runtimeContext, path, content, contentLength);
+ } finally {
+ mirrorGate.lock.readLock().unlock();
+ }
+ }
+
@Override
public List uploadFiles(
RuntimeContext runtimeContext, List> files) {
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java
index 95d7ba635a..f153abaa52 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java
@@ -20,6 +20,7 @@
import io.agentscope.harness.agent.filesystem.model.ExecuteResponse;
import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
import io.agentscope.harness.agent.sandbox.ExecResult;
import io.agentscope.harness.agent.sandbox.Sandbox;
import io.agentscope.harness.agent.sandbox.SandboxAcquireResult;
@@ -32,11 +33,13 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.UUID;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@@ -177,6 +180,71 @@ public List uploadFiles(
return results;
}
+ @Override
+ public FileUploadResponse uploadFile(
+ RuntimeContext runtimeContext, String path, InputStream content, long contentLength) {
+ AbstractFilesystem.validatePath(path);
+ FilesystemUtils.validateUpload(content, contentLength);
+ Sandbox active = requireSandbox(runtimeContext);
+ if (active instanceof SandboxFileTransfer transfer) {
+ String transferPath = null;
+ try {
+ transferPath = resolveTransferPath(active, path);
+ } catch (IllegalArgumentException e) {
+ return FileUploadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ } catch (IOException e) {
+ log.debug(
+ "[sandbox-fs] Workspace root unavailable, keeping archive fallback: {}",
+ path);
+ }
+ if (transferPath != null && transfer.supportsFileTransfer(transferPath)) {
+ try {
+ transfer.uploadFile(transferPath, content, contentLength);
+ return FileUploadResponse.success(path);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return FileUploadResponse.fail(path, "Sandbox upload interrupted");
+ } catch (Exception e) {
+ log.warn("[sandbox-fs] native upload failed for path: {}", path, e);
+ return FileUploadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ }
+ }
+ }
+ return super.uploadFile(runtimeContext, path, content, contentLength);
+ }
+
+ @Override
+ public FileDownloadResponse downloadFile(
+ RuntimeContext runtimeContext, String path, OutputStream sink) {
+ AbstractFilesystem.validatePath(path);
+ Objects.requireNonNull(sink, "sink");
+ Sandbox active = requireSandbox(runtimeContext);
+ if (active instanceof SandboxFileTransfer transfer) {
+ String transferPath = null;
+ try {
+ transferPath = resolveTransferPath(active, path);
+ } catch (IllegalArgumentException e) {
+ return FileDownloadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ } catch (IOException e) {
+ log.debug(
+ "[sandbox-fs] Workspace root unavailable, keeping exec fallback: {}", path);
+ }
+ if (transferPath != null && transfer.supportsFileTransfer(transferPath)) {
+ try {
+ transfer.downloadFile(transferPath, sink);
+ return FileDownloadResponse.success(path);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return FileDownloadResponse.fail(path, "Sandbox download interrupted");
+ } catch (Exception e) {
+ log.warn("[sandbox-fs] native download failed for path: {}", path, e);
+ return FileDownloadResponse.fail(path, FilesystemUtils.transferErrorMessage(e));
+ }
+ }
+ }
+ return super.downloadFile(runtimeContext, path, sink);
+ }
+
@Override
public List downloadFiles(
RuntimeContext runtimeContext, List paths) {
@@ -311,9 +379,9 @@ private String resolveArchivePath(Sandbox active, String path) throws IOExceptio
}
/**
- * Normalizes an upload path and resolves it to its sandbox-absolute form so
+ * Normalizes a transfer path and resolves it to its sandbox-absolute form so
* workspace-relative paths can ride the native single-file transfer
- * ({@link SandboxFileTransfer#uploadFile}) instead of the archive-hydrate fallback. Throws
+ * ({@link SandboxFileTransfer}) instead of the buffered fallback. Throws
* {@link IllegalArgumentException} for invalid paths — the caller fails just that file,
* matching the archive fallback's validation contract.
*/
@@ -323,7 +391,8 @@ private String resolveTransferPath(Sandbox active, String path) throws IOExcepti
if (normalized.startsWith("/")) {
return normalized;
}
- return resolveWorkspaceRoot(active) + "/" + normalized;
+ String root = resolveWorkspaceRoot(active);
+ return ("/".equals(root) ? root : root + "/") + normalized;
}
/** Normalizes separators and strips leading {@code ./} segments. */
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/util/FilesystemUtils.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/util/FilesystemUtils.java
index 9ddfd03434..a06e398661 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/util/FilesystemUtils.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/util/FilesystemUtils.java
@@ -19,6 +19,12 @@
import io.agentscope.harness.agent.filesystem.CompositeFilesystem;
import io.agentscope.harness.agent.filesystem.RoutedSandboxFilesystem;
import io.agentscope.harness.agent.filesystem.model.EditResult;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
@@ -27,6 +33,7 @@
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
+import java.util.Objects;
import java.util.Set;
/**
@@ -87,6 +94,57 @@ public static String decodeUtf8Strict(byte[] bytes) throws CharacterCodingExcept
return decoder.decode(ByteBuffer.wrap(bytes)).toString();
}
+ /** Validates upload arguments without consuming the input stream. */
+ public static void validateUpload(InputStream content, long contentLength) {
+ Objects.requireNonNull(content, "File content must not be null");
+ if (contentLength < 0) {
+ throw new IllegalArgumentException("Content length must not be negative");
+ }
+ }
+
+ /**
+ * Copies the declared number of bytes and verifies EOF without closing or flushing either
+ * stream. A failed copy may have already written partial content.
+ */
+ public static void copyExactly(InputStream content, OutputStream sink, long contentLength)
+ throws IOException {
+ validateUpload(content, contentLength);
+ Objects.requireNonNull(sink, "File output stream must not be null");
+ byte[] buffer = new byte[8192];
+ long remaining = contentLength;
+ while (remaining > 0) {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new InterruptedIOException("File upload interrupted");
+ }
+ int read = content.read(buffer, 0, (int) Math.min(buffer.length, remaining));
+ if (read < 0) {
+ throw new EOFException("File content is shorter than the declared length");
+ }
+ sink.write(buffer, 0, read);
+ remaining -= read;
+ }
+ if (content.read() != -1) {
+ throw new IOException("File content exceeds the declared length");
+ }
+ }
+
+ /** Buffers an upload for a backend that only supports byte-array transfers. */
+ public static byte[] readUpload(InputStream content, long contentLength) throws IOException {
+ validateUpload(content, contentLength);
+ if (contentLength > Integer.MAX_VALUE) {
+ throw new IOException("File is too large for the backend's byte-array transfer API");
+ }
+ ByteArrayOutputStream buffer =
+ new ByteArrayOutputStream((int) Math.min(contentLength, 8192));
+ copyExactly(content, buffer, contentLength);
+ return buffer.toByteArray();
+ }
+
+ /** Keeps a failed transfer distinguishable from success when an exception has no message. */
+ public static String transferErrorMessage(Exception exception) {
+ return exception.getMessage() != null ? exception.getMessage() : exception.toString();
+ }
+
private static final Set BINARY_EXTENSIONS =
Set.of(
".png", ".jpg", ".jpeg", ".gif", ".webp", ".heic", ".heif", ".bmp", ".ico",
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxFileTransfer.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxFileTransfer.java
index e21d725862..c4b84c2ee2 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxFileTransfer.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxFileTransfer.java
@@ -15,6 +15,11 @@
*/
package io.agentscope.harness.agent.sandbox;
+import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Objects;
+
/**
* Optional capability for {@link Sandbox} backends that support native (non-exec) file
* transfer, e.g. a dedicated HTTP upload/download API exposed by the sandbox runtime.
@@ -52,6 +57,24 @@ public interface SandboxFileTransfer {
*/
void uploadFile(String path, byte[] content) throws Exception;
+ /**
+ * Uploads a file from a caller-owned stream. The default implementation buffers the file and
+ * delegates to the legacy byte-array method. Backends can override it for bounded-memory
+ * transfer.
+ *
+ * The method completes synchronously and does not close {@code content}. Its length must
+ * match {@code contentLength} exactly. Failure may leave a partially written destination;
+ * uploads are not guaranteed to be atomic.
+ *
+ * @param path destination path accepted by {@link #supportsFileTransfer}
+ * @param content file content, consumed through EOF
+ * @param contentLength exact number of bytes, must be nonnegative
+ * @throws Exception when length validation or the transfer fails
+ */
+ default void uploadFile(String path, InputStream content, long contentLength) throws Exception {
+ uploadFile(path, FilesystemUtils.readUpload(content, contentLength));
+ }
+
/**
* Reads a file from the sandbox.
*
@@ -61,4 +84,22 @@ public interface SandboxFileTransfer {
* is not retried through the exec strategy
*/
byte[] downloadFile(String path) throws Exception;
+
+ /**
+ * Downloads a file to a caller-owned stream. The default implementation delegates to the
+ * legacy byte-array method and buffers the entire file. Backends can override it for
+ * bounded-memory transfer.
+ *
+ *
The method completes synchronously and does not close or flush {@code sink}. Failure
+ * may leave partial content in the sink; callers must not automatically retry into the same
+ * stream.
+ *
+ * @param path source path accepted by {@link #supportsFileTransfer}
+ * @param sink destination for file bytes
+ * @throws Exception when reading the file or writing the sink fails
+ */
+ default void downloadFile(String path, OutputStream sink) throws Exception {
+ Objects.requireNonNull(sink, "sink");
+ sink.write(downloadFile(path));
+ }
}
diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java
index 8c81b837ec..93653a8f0f 100644
--- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java
+++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java
@@ -16,6 +16,7 @@
package io.agentscope.harness.agent.sandbox.impl.docker;
import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
import io.agentscope.harness.agent.sandbox.AbstractBaseSandbox;
import io.agentscope.harness.agent.sandbox.ExecResult;
import io.agentscope.harness.agent.sandbox.SandboxErrorCode;
@@ -26,6 +27,7 @@
import io.agentscope.harness.agent.sandbox.layout.WorkspaceEntry;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -36,10 +38,15 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,11 +71,12 @@
*
Exec: {@code docker exec -w sh -c }
* PersistWorkspace: {@code docker exec tar -cf - -C .}
* HydrateWorkspace: {@code docker exec -i tar -xpf - -C }
- * UploadFile / DownloadFile ({@link SandboxFileTransfer}): a host temp file round-tripped
- * through {@code docker cp}, so file bytes never pass through exec argv or the stdout
- * capture cap. Scoped to the workspace subtree by lexical validation; uploads land with
- * mode 0644, matching the archive-hydrate fallback. Symlinks inside the sandbox are not
- * resolved — the isolation boundary is the container, not the subtree.
+ * Byte-array file transfer ({@link SandboxFileTransfer}): a host temporary file is
+ * round-tripped through {@code docker cp}.
+ * Stream file transfer: a single-file tar archive is piped through {@code docker cp}
+ * without buffering the full file. Both transfer forms use lexical workspace path
+ * validation and upload with mode 0644. Symlinks inside the sandbox are not resolved.
+ * The container is the isolation boundary.
*
*/
public class DockerSandbox extends AbstractBaseSandbox implements SandboxFileTransfer {
@@ -400,6 +408,38 @@ public void uploadFile(String path, byte[] content) throws Exception {
}
}
+ @Override
+ public void uploadFile(String path, InputStream content, long contentLength) throws Exception {
+ FilesystemUtils.validateUpload(content, contentLength);
+ String containerPath = requireTransferPath(path);
+ int slash = containerPath.lastIndexOf('/');
+ String parent = slash > 0 ? containerPath.substring(0, slash) : "/";
+ String filename = containerPath.substring(slash + 1);
+ runDockerCliBlocking(
+ 30, "docker", "exec", dockerState.getContainerId(), "mkdir", "-p", parent);
+ runFileTransfer(
+ process -> {
+ try (TarArchiveOutputStream tar =
+ new TarArchiveOutputStream(
+ process.getOutputStream(), StandardCharsets.UTF_8.name())) {
+ tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+ tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
+ TarArchiveEntry entry = new TarArchiveEntry(filename);
+ entry.setSize(contentLength);
+ entry.setMode(0644);
+ tar.putArchiveEntry(entry);
+ FilesystemUtils.copyExactly(content, tar, contentLength);
+ tar.closeArchiveEntry();
+ tar.finish();
+ }
+ },
+ true,
+ "docker",
+ "cp",
+ "-",
+ dockerState.getContainerId() + ":" + parent);
+ }
+
@Override
public byte[] downloadFile(String path) throws Exception {
String containerPath = requireTransferPath(path);
@@ -417,6 +457,155 @@ public byte[] downloadFile(String path) throws Exception {
}
}
+ @Override
+ public void downloadFile(String path, OutputStream sink) throws Exception {
+ if (sink == null) {
+ throw new IllegalArgumentException("File output stream must not be null");
+ }
+ String containerPath = requireTransferPath(path);
+ runFileTransfer(
+ process -> {
+ InputStream stdout = process.getInputStream();
+ try (TarArchiveInputStream tar =
+ new TarArchiveInputStream(stdout, StandardCharsets.UTF_8.name())) {
+ TarArchiveEntry entry = tar.getNextEntry();
+ if (entry == null || !entry.isFile()) {
+ throw new IOException("Docker file transfer did not contain a file");
+ }
+ tar.transferTo(sink);
+ if (tar.getNextEntry() != null) {
+ throw new IOException("Docker file transfer contained multiple files");
+ }
+ // Consume Docker's archive padding before waiting for its process to exit.
+ stdout.transferTo(OutputStream.nullOutputStream());
+ }
+ },
+ false,
+ "docker",
+ "cp",
+ dockerState.getContainerId() + ":" + containerPath,
+ "-");
+ }
+
+ @FunctionalInterface
+ private interface FileTransfer {
+ void run(Process process) throws Exception;
+ }
+
+ private void runFileTransfer(FileTransfer transfer, boolean drainStdout, String... command)
+ throws Exception {
+ Process process = startFileTransferProcess(command);
+ ExecutorService ioExecutor =
+ Executors.newFixedThreadPool(
+ drainStdout ? 3 : 2,
+ task -> {
+ Thread thread = new Thread(task, "sandbox-docker-file-transfer");
+ thread.setDaemon(true);
+ return thread;
+ });
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(fileTransferTimeoutSeconds());
+ Future stderrFuture =
+ ioExecutor.submit(() -> readStream(process.getErrorStream(), 64 * 1024));
+ Future> stdoutFuture =
+ drainStdout
+ ? ioExecutor.submit(() -> readStream(process.getInputStream(), 64 * 1024))
+ : null;
+ Future> transferFuture =
+ ioExecutor.submit(
+ () -> {
+ transfer.run(process);
+ return null;
+ });
+ try {
+ // Notice a failed pipe while Docker is still waiting for its other endpoint.
+ while (!transferFuture.isDone() && process.isAlive()) {
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ throw new TimeoutException();
+ }
+ process.waitFor(
+ Math.min(remaining, TimeUnit.MILLISECONDS.toNanos(100)),
+ TimeUnit.NANOSECONDS);
+ }
+ if (transferFuture.isDone()) {
+ awaitFileTransferTask(transferFuture, deadline);
+ }
+ if (!process.waitFor(
+ Math.max(0L, deadline - System.nanoTime()), TimeUnit.NANOSECONDS)) {
+ throw new TimeoutException();
+ }
+ if (process.exitValue() != 0) {
+ throw new SandboxException.SandboxRuntimeException(
+ SandboxErrorCode.WORKSPACE_START_ERROR,
+ "Docker file transfer failed (exit="
+ + process.exitValue()
+ + "): "
+ + awaitFileTransferTask(stderrFuture, deadline));
+ }
+ awaitFileTransferTask(transferFuture, deadline);
+ awaitFileTransferTask(stderrFuture, deadline);
+ if (stdoutFuture != null) {
+ awaitFileTransferTask(stdoutFuture, deadline);
+ }
+ } catch (TimeoutException e) {
+ throw new SandboxException.SandboxRuntimeException(
+ SandboxErrorCode.WORKSPACE_START_ERROR, "Docker file transfer timed out", e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw e;
+ } finally {
+ transferFuture.cancel(true);
+ stderrFuture.cancel(true);
+ if (stdoutFuture != null) {
+ stdoutFuture.cancel(true);
+ }
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ closeTransferPipe(process.getOutputStream());
+ closeTransferPipe(process.getInputStream());
+ closeTransferPipe(process.getErrorStream());
+ ioExecutor.shutdownNow();
+ try {
+ process.waitFor(1, TimeUnit.SECONDS);
+ ioExecutor.awaitTermination(1, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ private static T awaitFileTransferTask(Future future, long deadline) throws Exception {
+ try {
+ return future.get(Math.max(0L, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
+ } catch (ExecutionException e) {
+ if (e.getCause() instanceof Exception exception) {
+ throw exception;
+ }
+ if (e.getCause() instanceof Error error) {
+ throw error;
+ }
+ throw new IllegalStateException(e.getCause());
+ }
+ }
+
+ private static void closeTransferPipe(Closeable pipe) {
+ try {
+ pipe.close();
+ } catch (IOException e) {
+ log.debug("[sandbox-docker] Failed to close file-transfer pipe", e);
+ }
+ }
+
+ // Package-private process and deadline seams keep streaming tests independent of Docker.
+ Process startFileTransferProcess(String... command) throws IOException {
+ return new ProcessBuilder(command).start();
+ }
+
+ int fileTransferTimeoutSeconds() {
+ return TAR_TIMEOUT_SECONDS;
+ }
+
private String requireTransferPath(String path) {
if (dockerState.getContainerId() == null || dockerState.getContainerId().isBlank()) {
throw new IllegalArgumentException("Docker container is unavailable");
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/CompositeFilesystemTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/CompositeFilesystemTest.java
index 4cf2b85326..bdeb1d53a5 100644
--- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/CompositeFilesystemTest.java
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/CompositeFilesystemTest.java
@@ -23,16 +23,22 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.journal.AtomicJournalStorage;
import io.agentscope.harness.agent.filesystem.local.LocalFilesystem;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
import io.agentscope.harness.agent.filesystem.model.FileInfo;
import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
import io.agentscope.harness.agent.filesystem.model.GlobResult;
import io.agentscope.harness.agent.filesystem.model.ReadResult;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -53,6 +59,45 @@ class CompositeFilesystemTest {
@TempDir Path tmp;
+ @Test
+ void streamingTransfersRouteDirectlyWithTheCallerContextAndStreams() {
+ RuntimeContext context = RuntimeContext.builder().userId("alice").sessionId("s1").build();
+ AbstractFilesystem local = mock(AbstractFilesystem.class);
+ AbstractFilesystem memories = mock(AbstractFilesystem.class);
+ CompositeFilesystem composite =
+ new CompositeFilesystem(local, Map.of("memories/", memories));
+ InputStream source = mock(InputStream.class);
+ OutputStream sink = mock(OutputStream.class);
+ when(memories.uploadFile(context, "/note.bin", source, 8))
+ .thenReturn(
+ FileUploadResponse.success("/note.bin"),
+ FileUploadResponse.fail("/note.bin", "upload failed"));
+ when(memories.downloadFile(context, "/note.bin", sink))
+ .thenReturn(
+ FileDownloadResponse.success("/note.bin"),
+ FileDownloadResponse.fail("/note.bin", "download failed"));
+
+ FileUploadResponse upload = composite.uploadFile(context, "memories/note.bin", source, 8);
+ FileDownloadResponse download = composite.downloadFile(context, "/memories/note.bin", sink);
+ assertTrue(upload.isSuccess());
+ assertEquals("memories/note.bin", upload.path());
+ assertTrue(download.isSuccess());
+ assertEquals("/memories/note.bin", download.path());
+ FileUploadResponse failedUpload =
+ composite.uploadFile(context, "memories/note.bin", source, 8);
+ FileDownloadResponse failedDownload =
+ composite.downloadFile(context, "/memories/note.bin", sink);
+ assertEquals("memories/note.bin", failedUpload.path());
+ assertEquals("upload failed", failedUpload.error());
+ assertEquals("/memories/note.bin", failedDownload.path());
+ assertEquals("download failed", failedDownload.error());
+
+ verify(memories, times(2)).uploadFile(context, "/note.bin", source, 8);
+ verify(memories, times(2)).downloadFile(context, "/note.bin", sink);
+ verifyNoMoreInteractions(memories);
+ verifyNoInteractions(local, source, sink);
+ }
+
@Test
void explicitJournalBackendDoesNotChangeFileRouting() {
var local = mock(AbstractFilesystem.class);
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/FilesystemStreamingDelegationTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/FilesystemStreamingDelegationTest.java
new file mode 100644
index 0000000000..865d5b566f
--- /dev/null
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/FilesystemStreamingDelegationTest.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2024-2026 the original author or 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 io.agentscope.harness.agent.filesystem;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+
+class FilesystemStreamingDelegationTest {
+
+ private final RuntimeContext context =
+ RuntimeContext.builder().userId("alice").sessionId("s1").build();
+
+ @Test
+ void overlayUploadsOnlyToUpperAndReadsTheFirstExistingLayer() {
+ AbstractFilesystem upper = mock(AbstractFilesystem.class);
+ AbstractFilesystem lower = mock(AbstractFilesystem.class);
+ OverlayFilesystem overlay = new OverlayFilesystem(upper, lower);
+ InputStream source = mock(InputStream.class);
+ OutputStream sink = mock(OutputStream.class);
+ FileUploadResponse upload = FileUploadResponse.success("/shared.bin");
+ FileDownloadResponse ownDownload = FileDownloadResponse.success("/own.bin");
+ FileDownloadResponse sharedDownload = FileDownloadResponse.success("/shared.bin");
+ when(upper.uploadFile(context, "/shared.bin", source, 4)).thenReturn(upload);
+ when(upper.exists(context, "/own.bin")).thenReturn(true);
+ when(upper.downloadFile(context, "/own.bin", sink)).thenReturn(ownDownload);
+ when(lower.downloadFile(context, "/shared.bin", sink)).thenReturn(sharedDownload);
+
+ assertSame(upload, overlay.uploadFile(context, "/shared.bin", source, 4));
+ assertSame(ownDownload, overlay.downloadFile(context, "/own.bin", sink));
+ assertSame(sharedDownload, overlay.downloadFile(context, "/shared.bin", sink));
+
+ verify(upper).uploadFile(context, "/shared.bin", source, 4);
+ verify(upper).exists(context, "/own.bin");
+ verify(upper).downloadFile(context, "/own.bin", sink);
+ verify(upper).exists(context, "/shared.bin");
+ verify(lower).downloadFile(context, "/shared.bin", sink);
+ verifyNoMoreInteractions(upper, lower);
+ verifyNoInteractions(source, sink);
+ }
+
+ @Test
+ void overlayPropagatesAnUpperReadFailureWithoutReadingLower() {
+ AbstractFilesystem upper = mock(AbstractFilesystem.class);
+ AbstractFilesystem lower = mock(AbstractFilesystem.class);
+ OverlayFilesystem overlay = new OverlayFilesystem(upper, lower);
+ OutputStream sink = mock(OutputStream.class);
+ FileDownloadResponse failure = FileDownloadResponse.fail("/shared.bin", "read failed");
+ when(upper.exists(context, "/shared.bin")).thenReturn(true);
+ when(upper.downloadFile(context, "/shared.bin", sink)).thenReturn(failure);
+
+ assertSame(failure, overlay.downloadFile(context, "/shared.bin", sink));
+
+ verifyNoInteractions(lower, sink);
+ }
+
+ @Test
+ void bakedContextReplacesTheCallerIdentityForStreamingTransfers() {
+ AbstractFilesystem delegate = mock(AbstractFilesystem.class);
+ RuntimeContext baked = RuntimeContext.builder().userId("bob").sessionId("s2").build();
+ BakedContextFilesystem filesystem = new BakedContextFilesystem(delegate, baked);
+ InputStream source = mock(InputStream.class);
+ OutputStream sink = mock(OutputStream.class);
+ FileUploadResponse upload = FileUploadResponse.fail("/note.bin", "permission_denied");
+ FileDownloadResponse download = FileDownloadResponse.success("/note.bin");
+ when(delegate.uploadFile(baked, "/note.bin", source, 4)).thenReturn(upload);
+ when(delegate.downloadFile(baked, "/note.bin", sink)).thenReturn(download);
+
+ assertSame(upload, filesystem.uploadFile(context, "/note.bin", source, 4));
+ assertSame(download, filesystem.downloadFile(context, "/note.bin", sink));
+
+ verify(delegate).uploadFile(baked, "/note.bin", source, 4);
+ verify(delegate).downloadFile(baked, "/note.bin", sink);
+ verifyNoMoreInteractions(delegate);
+ verifyNoInteractions(source, sink);
+ }
+
+ @Test
+ void routedSandboxPreservesTheSelectedStreamingBackend() {
+ AbstractSandboxFilesystem primary = mock(AbstractSandboxFilesystem.class);
+ AbstractFilesystem memories = mock(AbstractFilesystem.class);
+ RoutedSandboxFilesystem filesystem =
+ new RoutedSandboxFilesystem(primary, Map.of("memory/", memories));
+ InputStream source = mock(InputStream.class);
+ OutputStream sink = mock(OutputStream.class);
+ when(memories.uploadFile(context, "/note.bin", source, 4))
+ .thenReturn(FileUploadResponse.fail("/note.bin", "permission_denied"));
+ when(memories.downloadFile(context, "/note.bin", sink))
+ .thenReturn(FileDownloadResponse.success("/note.bin"));
+
+ FileUploadResponse upload = filesystem.uploadFile(context, "memory/note.bin", source, 4);
+ FileDownloadResponse download = filesystem.downloadFile(context, "/memory/note.bin", sink);
+
+ assertEquals("memory/note.bin", upload.path());
+ assertEquals("permission_denied", upload.error());
+ assertEquals("/memory/note.bin", download.path());
+ assertTrue(download.isSuccess());
+
+ verify(memories).uploadFile(context, "/note.bin", source, 4);
+ verify(memories).downloadFile(context, "/note.bin", sink);
+ verifyNoMoreInteractions(memories);
+ verifyNoInteractions(primary, source, sink);
+ }
+}
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlayTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlayTest.java
index 59aa7cc043..0a592a9522 100644
--- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlayTest.java
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlayTest.java
@@ -34,7 +34,11 @@
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
import io.agentscope.harness.agent.workspace.LocalFsMode;
import io.agentscope.harness.agent.workspace.PathPolicy;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -329,6 +333,82 @@ void delete_workspacePath_deletesFromWorkspace() throws IOException {
// ==================== uploadFiles routing ====================
+ @Test
+ void uploadFile_streamingRoutesProjectAndWorkspaceFiles() {
+ byte[] projectContent = "class App {}".getBytes(StandardCharsets.UTF_8);
+ byte[] memoryContent = "# Memory".getBytes(StandardCharsets.UTF_8);
+ String projectPath = workspace.resolve("src/App.java").toAbsolutePath().toString();
+ String memoryPath = workspace.resolve("MEMORY.md").toAbsolutePath().toString();
+
+ FileUploadResponse projectUpload =
+ overlay.uploadFile(
+ rc,
+ projectPath,
+ new ByteArrayInputStream(projectContent),
+ projectContent.length);
+ FileUploadResponse memoryUpload =
+ overlay.uploadFile(
+ rc,
+ memoryPath,
+ new ByteArrayInputStream(memoryContent),
+ memoryContent.length);
+
+ assertTrue(projectUpload.isSuccess());
+ assertEquals(projectPath, projectUpload.path());
+ assertTrue(memoryUpload.isSuccess());
+ assertEquals(memoryPath, memoryUpload.path());
+ assertTrue(Files.exists(project.resolve("src/App.java")));
+ assertFalse(Files.exists(workspace.resolve("src/App.java")));
+ assertTrue(Files.exists(workspace.resolve("MEMORY.md")));
+ assertFalse(Files.exists(project.resolve("MEMORY.md")));
+
+ ByteArrayOutputStream projectDownload = new ByteArrayOutputStream();
+ ByteArrayOutputStream memoryDownload = new ByteArrayOutputStream();
+ FileDownloadResponse projectResult = overlay.downloadFile(rc, projectPath, projectDownload);
+ FileDownloadResponse memoryResult = overlay.downloadFile(rc, memoryPath, memoryDownload);
+ assertTrue(projectResult.isSuccess());
+ assertEquals(projectPath, projectResult.path());
+ assertTrue(memoryResult.isSuccess());
+ assertEquals(memoryPath, memoryResult.path());
+ assertEquals("class App {}", projectDownload.toString(StandardCharsets.UTF_8));
+ assertEquals("# Memory", memoryDownload.toString(StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void streamingTransfers_preserveRequestedPathsOnFailure() {
+ InputStream input =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw new IOException("input failed");
+ }
+ };
+ OutputStream output =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw new IOException("output failed");
+ }
+ };
+
+ for (String relative : List.of("src/App.java", "MEMORY.md")) {
+ String path = workspace.resolve(relative).toAbsolutePath().toString();
+ assertTrue(
+ overlay.uploadFile(rc, path, new ByteArrayInputStream(new byte[] {1}), 1)
+ .isSuccess());
+
+ FileDownloadResponse download = overlay.downloadFile(rc, path, output);
+ assertFalse(download.isSuccess());
+ assertEquals(path, download.path());
+ assertEquals("output failed", download.error());
+
+ FileUploadResponse upload = overlay.uploadFile(rc, path, input, 1);
+ assertFalse(upload.isSuccess());
+ assertEquals(path, upload.path());
+ assertEquals("input failed", upload.error());
+ }
+ }
+
@Test
void uploadFiles_splitsByTarget() {
List> files =
@@ -440,6 +520,43 @@ void projectWrite_isReadableBackAtTheKeyItUsed() throws IOException {
assertTrue(shared.isSuccess(), () -> "shared read failed: " + shared.error());
}
+ @Test
+ void streamingDownload_readsNamespacedUploadBeforeSharedProject() throws IOException {
+ String key = "report.txt";
+ Files.writeString(project.resolve(key), "shared");
+ byte[] data = "user copy".getBytes(StandardCharsets.UTF_8);
+ FileUploadResponse upload =
+ nsOverlay.uploadFile(nsRc, key, new ByteArrayInputStream(data), data.length);
+ assertTrue(upload.isSuccess(), upload::error);
+
+ ByteArrayOutputStream sink = new ByteArrayOutputStream();
+ FileDownloadResponse download = nsOverlay.downloadFile(nsRc, key, sink);
+ assertTrue(download.isSuccess(), download::error);
+ assertEquals("user copy", sink.toString(StandardCharsets.UTF_8));
+ assertEquals("shared", Files.readString(project.resolve(key)));
+ }
+
+ @Test
+ void streamingUpload_rejectsShadowedProjectFileBeforeReadingInput() throws IOException {
+ Path workspaceFile = workspace.resolve("u1/report.txt");
+ Path projectFile = project.resolve("u1/report.txt");
+ Files.createDirectories(workspaceFile.getParent());
+ Files.createDirectories(projectFile.getParent());
+ Files.writeString(workspaceFile, "workspace");
+ Files.writeString(projectFile, "project");
+ ByteArrayInputStream input = new ByteArrayInputStream(new byte[] {42});
+ String requestedPath = workspaceFile.toString();
+
+ FileUploadResponse response = nsOverlay.uploadFile(nsRc, requestedPath, input, 1);
+
+ assertFalse(response.isSuccess());
+ assertEquals(requestedPath, response.path());
+ assertTrue(response.error().contains("workspace copy"), response::error);
+ assertEquals(42, input.read());
+ assertEquals("workspace", Files.readString(workspaceFile));
+ assertEquals("project", Files.readString(projectFile));
+ }
+
@Test
void edit_absolutePath_copiesProjectOriginalToWorkspace() throws IOException {
Files.createDirectories(project.resolve("src"));
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/StreamingFileTransferCompatibilityTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/StreamingFileTransferCompatibilityTest.java
new file mode 100644
index 0000000000..3efb9b7614
--- /dev/null
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/StreamingFileTransferCompatibilityTest.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright 2024-2026 the original author or 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 io.agentscope.harness.agent.filesystem;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import io.agentscope.harness.agent.sandbox.SandboxFileTransfer;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+class StreamingFileTransferCompatibilityTest {
+
+ private static final RuntimeContext RT = RuntimeContext.empty();
+ private static final String PATH = "/data.bin";
+
+ @Test
+ void filesystemDefaults_delegateToLegacyBatchApi() throws Exception {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+ byte[] content = new byte[] {0, 1, -1, 10};
+ doReturn(List.of(FileUploadResponse.success(PATH)))
+ .when(filesystem)
+ .uploadFiles(same(RT), anyList());
+ doReturn(List.of(FileDownloadResponse.success(PATH, content)))
+ .when(filesystem)
+ .downloadFiles(RT, List.of(PATH));
+ TrackingInput input = new TrackingInput(content);
+ TrackingOutput output = new TrackingOutput();
+
+ FileUploadResponse upload = filesystem.uploadFile(RT, PATH, input, content.length);
+ FileDownloadResponse download = filesystem.downloadFile(RT, PATH, output);
+
+ verify(filesystem)
+ .uploadFiles(
+ same(RT),
+ argThat(
+ files ->
+ files.size() == 1
+ && PATH.equals(files.get(0).getKey())
+ && Arrays.equals(
+ content, files.get(0).getValue())));
+ assertArrayEquals(content, output.toByteArray());
+ assertTrue(upload.isSuccess());
+ assertTrue(download.isSuccess());
+ assertEquals(PATH, upload.path());
+ assertEquals(PATH, download.path());
+ assertNull(download.content());
+ assertArrayEquals(content, filesystem.downloadFiles(RT, List.of(PATH)).get(0).content());
+ assertFalse(input.closed);
+ assertFalse(output.closed);
+ assertFalse(output.flushed);
+ }
+
+ @Test
+ void filesystemDefaults_reportLegacyBackendErrors() {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+ doReturn(List.of(FileUploadResponse.fail(PATH, "upload failed")))
+ .when(filesystem)
+ .uploadFiles(same(RT), anyList());
+ doReturn(List.of(FileDownloadResponse.fail(PATH, "download failed")))
+ .when(filesystem)
+ .downloadFiles(RT, List.of(PATH));
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(RT, PATH, new ByteArrayInputStream(new byte[0]), 0);
+ FileDownloadResponse download =
+ filesystem.downloadFile(RT, PATH, new ByteArrayOutputStream());
+
+ assertFalse(upload.isSuccess());
+ assertFalse(download.isSuccess());
+ assertEquals("upload failed", upload.error());
+ assertEquals("download failed", download.error());
+ }
+
+ @Test
+ void uploadFile_rejectsLengthMismatchBeforeCallingLegacyBackend() {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+ TrackingInput shortInput = new TrackingInput(new byte[] {1});
+ TrackingInput longInput = new TrackingInput(new byte[] {1, 2, 3});
+
+ assertFalse(filesystem.uploadFile(RT, PATH, shortInput, 2).isSuccess());
+ assertFalse(filesystem.uploadFile(RT, PATH, longInput, 2).isSuccess());
+
+ verify(filesystem, never()).uploadFiles(any(), anyList());
+ assertFalse(shortInput.closed);
+ assertFalse(longInput.closed);
+ }
+
+ @Test
+ void downloadFile_reportsCallerOutputFailure() {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+ doReturn(List.of(FileDownloadResponse.success(PATH, new byte[] {1})))
+ .when(filesystem)
+ .downloadFiles(RT, List.of(PATH));
+ IOException failure = new IOException("output failed");
+ OutputStream output =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw failure;
+ }
+ };
+
+ FileDownloadResponse result = filesystem.downloadFile(RT, PATH, output);
+
+ assertFalse(result.isSuccess());
+ assertEquals("output failed", result.error());
+ }
+
+ @Test
+ void filesystemDefaults_reportStreamFailuresWithoutMessages() {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+ doReturn(List.of(FileDownloadResponse.success(PATH, new byte[] {1})))
+ .when(filesystem)
+ .downloadFiles(RT, List.of(PATH));
+ InputStream input =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw new IOException();
+ }
+ };
+ OutputStream output =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw new IOException();
+ }
+ };
+
+ FileUploadResponse upload = filesystem.uploadFile(RT, PATH, input, 1);
+ FileDownloadResponse download = filesystem.downloadFile(RT, PATH, output);
+
+ assertFalse(upload.isSuccess());
+ assertFalse(download.isSuccess());
+ assertNotNull(upload.error());
+ assertNotNull(download.error());
+ verify(filesystem, never()).uploadFiles(any(), anyList());
+ }
+
+ @Test
+ void uploadFile_rejectsInvalidArgumentsBeforeCallingLegacyBackend() {
+ AbstractFilesystem filesystem = mock(AbstractFilesystem.class, CALLS_REAL_METHODS);
+
+ assertThrows(NullPointerException.class, () -> filesystem.uploadFile(RT, PATH, null, 0));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> filesystem.uploadFile(RT, PATH, new ByteArrayInputStream(new byte[0]), -1));
+
+ verify(filesystem, never()).uploadFiles(any(), anyList());
+ }
+
+ @Test
+ void sandboxDefaults_delegateToLegacyFileTransferApi() throws Exception {
+ SandboxFileTransfer transfer = mock(SandboxFileTransfer.class, CALLS_REAL_METHODS);
+ byte[] content = new byte[] {1, 2, 3};
+ doReturn(content).when(transfer).downloadFile(PATH);
+ TrackingInput input = new TrackingInput(content);
+ TrackingOutput output = new TrackingOutput();
+
+ transfer.uploadFile(PATH, input, content.length);
+ transfer.downloadFile(PATH, output);
+
+ verify(transfer).uploadFile(PATH, content);
+ assertArrayEquals(content, output.toByteArray());
+ assertFalse(input.closed);
+ assertFalse(output.closed);
+ assertFalse(output.flushed);
+ }
+
+ private static final class TrackingInput extends ByteArrayInputStream {
+ private boolean closed;
+
+ private TrackingInput(byte[] content) {
+ super(content);
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+ }
+
+ private static final class TrackingOutput extends ByteArrayOutputStream {
+ private boolean closed;
+ private boolean flushed;
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+
+ @Override
+ public void flush() {
+ flushed = true;
+ }
+ }
+}
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemStreamingTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemStreamingTest.java
new file mode 100644
index 0000000000..fce870a89f
--- /dev/null
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemStreamingTest.java
@@ -0,0 +1,282 @@
+/*
+ * Copyright 2024-2026 the original author or 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 io.agentscope.harness.agent.filesystem.local;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import io.agentscope.harness.agent.workspace.LocalFsMode;
+import io.agentscope.harness.agent.workspace.PathPolicy;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Random;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+class LocalFilesystemStreamingTest {
+
+ @TempDir Path workspace;
+
+ @Test
+ void streamingTransfers_preserveBinaryContentAndCallerStreams() throws Exception {
+ LocalFilesystem filesystem = new LocalFilesystem(workspace);
+ byte[] content = new byte[65_537];
+ new Random(1).nextBytes(content);
+ TrackingInput input = new TrackingInput(content);
+ TrackingOutput output = new TrackingOutput();
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(
+ RuntimeContext.empty(), "nested/data.bin", input, content.length);
+ FileDownloadResponse download =
+ filesystem.downloadFile(RuntimeContext.empty(), "nested/data.bin", output);
+
+ assertTrue(upload.isSuccess());
+ assertEquals("nested/data.bin", upload.path());
+ assertTrue(download.isSuccess());
+ assertEquals("nested/data.bin", download.path());
+ assertNull(download.content());
+ assertArrayEquals(content, Files.readAllBytes(workspace.resolve("nested/data.bin")));
+ assertArrayEquals(content, output.toByteArray());
+ assertFalse(input.closed);
+ assertFalse(output.closed);
+ assertFalse(output.flushed);
+ }
+
+ @Test
+ void streamingTransfers_respectExcludedSubtree() throws IOException {
+ Path excluded = Files.createDirectory(workspace.resolve("excluded"));
+ Files.writeString(excluded.resolve("file.txt"), "original");
+ LocalFilesystem filesystem = new LocalFilesystem(workspace).excludeSubtree(excluded);
+ String key = "excluded/file.txt";
+ ByteArrayInputStream input = new ByteArrayInputStream(new byte[] {1});
+ ByteArrayOutputStream sink = new ByteArrayOutputStream();
+
+ assertFalse(filesystem.uploadFile(RuntimeContext.empty(), key, input, 1).isSuccess());
+ assertFalse(filesystem.downloadFile(RuntimeContext.empty(), key, sink).isSuccess());
+ assertEquals(1, input.available());
+ assertEquals(0, sink.size());
+ assertEquals("original", Files.readString(excluded.resolve("file.txt")));
+ }
+
+ @Test
+ void uploadFile_rejectsShortAndLongContentWithoutClosingInput() {
+ LocalFilesystem filesystem = new LocalFilesystem(workspace);
+ TrackingInput shortInput = new TrackingInput(new byte[] {1});
+ TrackingInput longInput = new TrackingInput(new byte[] {1, 2, 3});
+
+ FileUploadResponse shortResult =
+ filesystem.uploadFile(RuntimeContext.empty(), "short.bin", shortInput, 2);
+ FileUploadResponse longResult =
+ filesystem.uploadFile(RuntimeContext.empty(), "long.bin", longInput, 2);
+
+ assertFalse(shortResult.isSuccess());
+ assertEquals("short.bin", shortResult.path());
+ assertEquals("File content is shorter than the declared length", shortResult.error());
+ assertFalse(longResult.isSuccess());
+ assertEquals("long.bin", longResult.path());
+ assertEquals("File content exceeds the declared length", longResult.error());
+ assertFalse(shortInput.closed);
+ assertFalse(longInput.closed);
+ }
+
+ @Test
+ void streamingTransfers_checkPathPolicyBeforeConsumingCallerData(@TempDir Path outside)
+ throws Exception {
+ Path privateFile = outside.resolve("private.bin");
+ Files.write(privateFile, new byte[] {7});
+ LocalFilesystem filesystem =
+ new LocalFilesystem(workspace, LocalFsMode.ROOTED, PathPolicy.empty(), 10, null);
+ TrackingInput input = new TrackingInput(new byte[] {1, 2});
+ TrackingOutput output = new TrackingOutput();
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(RuntimeContext.empty(), privateFile.toString(), input, 2);
+ FileDownloadResponse download =
+ filesystem.downloadFile(RuntimeContext.empty(), privateFile.toString(), output);
+
+ assertEquals(privateFile.toString(), upload.path());
+ assertEquals("permission_denied", upload.error());
+ assertEquals(privateFile.toString(), download.path());
+ assertEquals("permission_denied", download.error());
+ assertEquals(2, input.available());
+ assertEquals(0, output.size());
+ assertArrayEquals(new byte[] {7}, Files.readAllBytes(privateFile));
+ }
+
+ @Test
+ void streamingTransfers_preserveRuntimeNamespaceAndBlockSiblingAccess() throws Exception {
+ LocalFilesystem filesystem =
+ new LocalFilesystem(
+ workspace,
+ LocalFsMode.ROOTED,
+ PathPolicy.empty(),
+ 10,
+ context -> List.of(context.getUserId()))
+ .namespaceBoundary(true);
+ RuntimeContext alice = RuntimeContext.builder().userId("alice").build();
+ RuntimeContext bob = RuntimeContext.builder().userId("bob").build();
+ assertTrue(
+ filesystem
+ .uploadFile(alice, "file.bin", new ByteArrayInputStream(new byte[] {1}), 1)
+ .isSuccess());
+ assertTrue(
+ filesystem
+ .uploadFile(bob, "file.bin", new ByteArrayInputStream(new byte[] {2}), 1)
+ .isSuccess());
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ assertTrue(filesystem.downloadFile(alice, "file.bin", output).isSuccess());
+
+ assertArrayEquals(new byte[] {1}, output.toByteArray());
+ assertArrayEquals(new byte[] {2}, Files.readAllBytes(workspace.resolve("bob/file.bin")));
+ FileDownloadResponse denied =
+ filesystem.downloadFile(
+ alice,
+ workspace.resolve("bob/file.bin").toString(),
+ new ByteArrayOutputStream());
+ assertEquals("permission_denied", denied.error());
+ }
+
+ @Test
+ void streamingTransfers_reportCallerStreamFailures() throws Exception {
+ LocalFilesystem filesystem = new LocalFilesystem(workspace);
+ IOException inputFailure = new IOException("source failed");
+ InputStream failingInput =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw inputFailure;
+ }
+ };
+ FileUploadResponse upload =
+ filesystem.uploadFile(RuntimeContext.empty(), "input.bin", failingInput, 1);
+ assertEquals("input.bin", upload.path());
+ assertEquals(inputFailure.getMessage(), upload.error());
+ Files.write(workspace.resolve("output.bin"), new byte[] {1});
+ IOException outputFailure = new IOException("destination failed");
+ OutputStream failingOutput =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw outputFailure;
+ }
+ };
+ FileDownloadResponse download =
+ filesystem.downloadFile(RuntimeContext.empty(), "output.bin", failingOutput);
+ assertEquals("output.bin", download.path());
+ assertEquals(outputFailure.getMessage(), download.error());
+ }
+
+ @Test
+ void streamingTransfers_reportFileErrorsAndKeepInvalidArgumentsAsExceptions() {
+ LocalFilesystem filesystem = new LocalFilesystem(workspace);
+ assertEquals(
+ "file_not_found",
+ filesystem
+ .downloadFile(
+ RuntimeContext.empty(), "missing.bin", new ByteArrayOutputStream())
+ .error());
+ assertEquals(
+ "is_directory",
+ filesystem
+ .downloadFile(RuntimeContext.empty(), "/", new ByteArrayOutputStream())
+ .error());
+ assertThrows(
+ NullPointerException.class,
+ () -> filesystem.uploadFile(RuntimeContext.empty(), "file.bin", null, 0));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ filesystem.uploadFile(
+ RuntimeContext.empty(),
+ "file.bin",
+ InputStream.nullInputStream(),
+ -1));
+ assertThrows(
+ NullPointerException.class,
+ () -> filesystem.downloadFile(RuntimeContext.empty(), "file.bin", null));
+ }
+
+ @Test
+ void streamingTransfers_reportIoFailuresWithoutMessages() throws Exception {
+ LocalFilesystem filesystem = new LocalFilesystem(workspace);
+ InputStream input =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw new IOException();
+ }
+ };
+ FileUploadResponse upload =
+ filesystem.uploadFile(RuntimeContext.empty(), "input.bin", input, 1);
+ assertFalse(upload.isSuccess());
+ assertEquals("java.io.IOException", upload.error());
+ Files.write(workspace.resolve("output.bin"), new byte[] {1});
+ OutputStream output =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw new IOException();
+ }
+ };
+ FileDownloadResponse download =
+ filesystem.downloadFile(RuntimeContext.empty(), "output.bin", output);
+ assertFalse(download.isSuccess());
+ assertEquals("java.io.IOException", download.error());
+ }
+
+ private static final class TrackingInput extends ByteArrayInputStream {
+ private boolean closed;
+
+ private TrackingInput(byte[] content) {
+ super(content);
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+ }
+
+ private static final class TrackingOutput extends ByteArrayOutputStream {
+ private boolean closed;
+ private boolean flushed;
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+
+ @Override
+ public void flush() {
+ flushed = true;
+ }
+ }
+}
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystemTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystemTest.java
index f1fa950463..845225aecb 100644
--- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystemTest.java
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/PinnedSandboxFilesystemTest.java
@@ -18,10 +18,14 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
import io.agentscope.harness.agent.sandbox.ExecResult;
import io.agentscope.harness.agent.sandbox.Sandbox;
+import io.agentscope.harness.agent.sandbox.SandboxFileTransfer;
import io.agentscope.harness.agent.sandbox.SandboxState;
import java.io.InputStream;
import java.util.List;
@@ -40,6 +44,55 @@
@ResourceLock(Resources.SYSTEM_PROPERTIES)
class PinnedSandboxFilesystemTest {
+ @Test
+ void releaseWaitsForStreamingUploadThenRejectsLaterUploads() throws Exception {
+ String previous = System.getProperty(PinnedSandboxFilesystem.RELEASE_GATE_TIMEOUT_PROPERTY);
+ System.setProperty(PinnedSandboxFilesystem.RELEASE_GATE_TIMEOUT_PROPERTY, "5000");
+ BlockingSandbox sandbox = new StreamingSandbox();
+ PinnedSandboxFilesystem.markSandboxAcquired(sandbox);
+ PinnedSandboxFilesystem filesystem = new PinnedSandboxFilesystem(sandbox);
+ InputStream source = mock(InputStream.class);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future upload =
+ executor.submit(
+ () ->
+ filesystem.uploadFile(
+ RuntimeContext.empty(),
+ "/workspace/session.jsonl",
+ source,
+ 1));
+ assertTrue(sandbox.uploadStarted.await(2, TimeUnit.SECONDS));
+ Future> release =
+ executor.submit(() -> PinnedSandboxFilesystem.markSandboxReleased(sandbox));
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
+ while (!filesystem.isSandboxReleased() && System.nanoTime() < deadline) {
+ Thread.onSpinWait();
+ }
+ assertTrue(filesystem.isSandboxReleased());
+ assertFalse(release.isDone(), "release must wait for the active streamed upload");
+
+ sandbox.allowUploadToFinish.countDown();
+ FileUploadResponse completed = upload.get(2, TimeUnit.SECONDS);
+ assertTrue(completed.isSuccess());
+ assertEquals("/workspace/session.jsonl", completed.path());
+ release.get(2, TimeUnit.SECONDS);
+
+ InputStream nextSource = mock(InputStream.class);
+ FileUploadResponse rejected =
+ filesystem.uploadFile(
+ RuntimeContext.empty(), "/workspace/later.jsonl", nextSource, 1);
+ assertFalse(rejected.isSuccess());
+ assertEquals("/workspace/later.jsonl", rejected.path());
+ assertEquals("Sandbox has been released", rejected.error());
+ verifyNoInteractions(source, nextSource);
+ } finally {
+ sandbox.allowUploadToFinish.countDown();
+ executor.shutdownNow();
+ restoreTimeoutProperty(previous);
+ }
+ }
+
@Test
void releaseWaitsForActiveUploadThenRejectsLaterUploads() throws Exception {
String previous = System.getProperty(PinnedSandboxFilesystem.RELEASE_GATE_TIMEOUT_PROPERTY);
@@ -230,4 +283,28 @@ public int hashCode() {
return 1;
}
}
+
+ private static final class StreamingSandbox extends BlockingSandbox
+ implements SandboxFileTransfer {
+ @Override
+ public boolean supportsFileTransfer(String path) {
+ return true;
+ }
+
+ @Override
+ public void uploadFile(String path, byte[] content) {
+ throw new AssertionError("The streaming API must not fall back to byte arrays");
+ }
+
+ @Override
+ public void uploadFile(String path, InputStream content, long contentLength)
+ throws InterruptedException {
+ hydrateWorkspace(content);
+ }
+
+ @Override
+ public byte[] downloadFile(String path) {
+ throw new UnsupportedOperationException();
+ }
+ }
}
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystemTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystemTest.java
index bfc2c48b75..be4af73811 100644
--- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystemTest.java
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystemTest.java
@@ -17,6 +17,7 @@
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -24,6 +25,7 @@
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
import io.agentscope.harness.agent.sandbox.ExecResult;
import io.agentscope.harness.agent.sandbox.Sandbox;
import io.agentscope.harness.agent.sandbox.SandboxAcquireResult;
@@ -32,8 +34,10 @@
import io.agentscope.harness.agent.sandbox.SandboxState;
import io.agentscope.harness.agent.sandbox.WorkspaceSpec;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.HashMap;
@@ -379,6 +383,199 @@ void uploadFiles_reportsNativeTransferFailure() {
assertEquals("transfer down", responses.get(0).error());
}
+ @Test
+ void streamingTransfers_useThePerCallSandbox() throws Exception {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox fallback = new FakeTransferSandbox("/workspace");
+ FakeTransferSandbox selected = new FakeTransferSandbox("/workspace");
+ filesystem.setSandbox(fallback);
+ RuntimeContext context =
+ RuntimeContext.builder()
+ .put(SandboxAcquireResult.class, SandboxAcquireResult.userManaged(selected))
+ .build();
+ byte[] content = new byte[] {1, 2, 3};
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(context, "./结果.bin", new ByteArrayInputStream(content), 3);
+ FileDownloadResponse download = filesystem.downloadFile(context, "./结果.bin", output);
+
+ assertTrue(upload.isSuccess());
+ assertTrue(download.isSuccess());
+ assertEquals("./结果.bin", upload.path());
+ assertEquals("./结果.bin", download.path());
+ assertNull(download.content());
+ assertArrayEquals(content, output.toByteArray());
+ assertEquals(1, selected.streamUploads);
+ assertEquals(1, selected.streamDownloads);
+ assertTrue(fallback.uploaded.isEmpty());
+ assertNull(selected.lastCommand);
+ assertEquals(0, selected.hydrateCalls);
+ }
+
+ @Test
+ void streamingTransfers_doNotRetryFailedNativeTransfers() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/workspace");
+ sandbox.failTransfers = true;
+ filesystem.setSandbox(sandbox);
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(RT, "data.bin", new ByteArrayInputStream(new byte[] {1}), 1);
+ FileDownloadResponse download =
+ filesystem.downloadFile(RT, "/workspace/data.bin", new ByteArrayOutputStream());
+
+ assertTrue(!upload.isSuccess());
+ assertTrue(!download.isSuccess());
+ assertEquals("transfer down", upload.error());
+ assertEquals("transfer down", download.error());
+
+ assertEquals(1, sandbox.streamUploads);
+ assertEquals(1, sandbox.streamDownloads);
+ assertEquals(0, sandbox.hydrateCalls);
+ assertNull(sandbox.lastCommand);
+ }
+
+ @Test
+ void streamingTransfers_resolveRelativePathsAtFilesystemRoot() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/");
+ sandbox.workspaceSpec.setRoot("/");
+ filesystem.setSandbox(sandbox);
+ byte[] content = new byte[] {4, 5};
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ FileUploadResponse upload =
+ filesystem.uploadFile(
+ RT, "data.bin", new ByteArrayInputStream(content), content.length);
+ FileDownloadResponse download = filesystem.downloadFile(RT, "data.bin", output);
+
+ assertTrue(upload.isSuccess());
+ assertTrue(download.isSuccess());
+ assertArrayEquals(content, sandbox.uploaded.get("/data.bin"));
+ assertArrayEquals(content, output.toByteArray());
+ assertEquals(1, sandbox.streamUploads);
+ assertEquals(1, sandbox.streamDownloads);
+ assertEquals(0, sandbox.hydrateCalls);
+ assertNull(sandbox.lastCommand);
+ }
+
+ @Test
+ void uploadFile_keepsArchiveFallbackForUnsupportedNativePaths() throws Exception {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/other");
+ filesystem.setSandbox(sandbox);
+ byte[] content = new byte[] {4, 5};
+
+ FileUploadResponse result =
+ filesystem.uploadFile(
+ RT, "data.bin", new ByteArrayInputStream(content), content.length);
+
+ assertTrue(result.isSuccess());
+ assertEquals(0, sandbox.streamUploads);
+ assertEquals(1, sandbox.hydrateCalls);
+ assertArchive(sandbox.hydratedArchive, "data.bin", content);
+ }
+
+ @Test
+ void downloadFile_keepsExecFallbackForUnsupportedNativePaths() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/other");
+ filesystem.setSandbox(sandbox);
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ FileDownloadResponse result = filesystem.downloadFile(RT, "data.bin", output);
+
+ assertTrue(result.isSuccess());
+ assertEquals("data.bin", result.path());
+ assertNull(result.content());
+ assertEquals(0, output.size());
+ assertEquals(0, sandbox.streamDownloads);
+ assertEquals("base64 'data.bin'", sandbox.lastCommand);
+ }
+
+ @Test
+ void uploadFile_reportsInputFailureWithoutRetry() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/workspace");
+ filesystem.setSandbox(sandbox);
+ IOException failure = new IOException("input failed");
+ InputStream input =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw failure;
+ }
+ };
+
+ FileUploadResponse result = filesystem.uploadFile(RT, "data.bin", input, 1);
+
+ assertTrue(!result.isSuccess());
+ assertEquals("input failed", result.error());
+ assertEquals(1, sandbox.streamUploads);
+ assertEquals(0, sandbox.hydrateCalls);
+ }
+
+ @Test
+ void streamingTransfers_reportFailuresWithoutMessages() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/workspace");
+ filesystem.setSandbox(sandbox);
+ InputStream input =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw new IOException();
+ }
+ };
+ OutputStream output =
+ new OutputStream() {
+ @Override
+ public void write(int value) throws IOException {
+ throw new IOException();
+ }
+ };
+
+ FileUploadResponse upload = filesystem.uploadFile(RT, "data.bin", input, 1);
+ assertTrue(
+ filesystem
+ .uploadFile(RT, "data.bin", new ByteArrayInputStream(new byte[] {1}), 1)
+ .isSuccess());
+ FileDownloadResponse download = filesystem.downloadFile(RT, "/workspace/data.bin", output);
+
+ assertTrue(!upload.isSuccess());
+ assertTrue(!download.isSuccess());
+ assertNotNull(upload.error());
+ assertNotNull(download.error());
+ assertEquals(0, sandbox.hydrateCalls);
+ assertNull(sandbox.lastCommand);
+ }
+
+ @Test
+ void streamingTransfers_preserveInterruptFlagWhenReportingFailure() {
+ SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
+ FakeTransferSandbox sandbox = new FakeTransferSandbox("/workspace");
+ sandbox.interruptTransfers = true;
+ filesystem.setSandbox(sandbox);
+ try {
+ FileUploadResponse upload =
+ filesystem.uploadFile(
+ RT, "data.bin", new ByteArrayInputStream(new byte[] {1}), 1);
+ assertTrue(!upload.isSuccess());
+ assertTrue(Thread.currentThread().isInterrupted());
+ Thread.interrupted();
+
+ FileDownloadResponse download =
+ filesystem.downloadFile(RT, "/workspace/data.bin", new ByteArrayOutputStream());
+ assertTrue(!download.isSuccess());
+ assertTrue(Thread.currentThread().isInterrupted());
+ assertEquals(0, sandbox.hydrateCalls);
+ assertNull(sandbox.lastCommand);
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
private static void assertArchive(byte[] archive, String expectedPath, byte[] expectedContent)
throws IOException {
try (TarArchiveInputStream tar =
@@ -396,10 +593,13 @@ private static final class FakeTransferSandbox extends BaseFakeSandbox
private final String rootPrefix;
private final Map uploaded = new HashMap<>();
private boolean failTransfers;
+ private boolean interruptTransfers;
+ private int streamUploads;
+ private int streamDownloads;
private FakeTransferSandbox(String root) {
super(new ExecResult(0, "", "", false));
- this.rootPrefix = root + "/";
+ this.rootPrefix = "/".equals(root) ? root : root + "/";
}
@Override
@@ -422,6 +622,31 @@ public byte[] downloadFile(String absolutePath) throws Exception {
}
return uploaded.get(absolutePath);
}
+
+ @Override
+ public void uploadFile(String absolutePath, InputStream content, long contentLength)
+ throws Exception {
+ streamUploads++;
+ if (interruptTransfers) {
+ throw new InterruptedException("upload interrupted");
+ }
+ if (failTransfers) {
+ throw new IllegalStateException("transfer down");
+ }
+ uploaded.put(absolutePath, FilesystemUtils.readUpload(content, contentLength));
+ }
+
+ @Override
+ public void downloadFile(String absolutePath, OutputStream sink) throws Exception {
+ streamDownloads++;
+ if (interruptTransfers) {
+ throw new InterruptedException("download interrupted");
+ }
+ if (failTransfers) {
+ throw new IllegalStateException("transfer down");
+ }
+ sink.write(uploaded.get(absolutePath));
+ }
}
private static final class FakeSandbox extends BaseFakeSandbox {
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxFileTransferIntegrationTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxFileTransferIntegrationTest.java
index 3f778d7f70..58f25ac54e 100644
--- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxFileTransferIntegrationTest.java
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxFileTransferIntegrationTest.java
@@ -27,16 +27,26 @@
import io.agentscope.harness.agent.filesystem.model.WriteResult;
import io.agentscope.harness.agent.filesystem.sandbox.SandboxBackedFilesystem;
import io.agentscope.harness.agent.sandbox.WorkspaceSpec;
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.security.DigestInputStream;
+import java.security.DigestOutputStream;
+import java.security.MessageDigest;
import java.util.Random;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.api.io.TempDir;
/**
* Real end-to-end round-trip of {@code docker cp} based file transfer against a live Docker
@@ -61,6 +71,8 @@ class DockerSandboxFileTransferIntegrationTest {
private DockerSandbox sandbox;
+ @TempDir Path hostDirectory;
+
@BeforeEach
void setUp() throws Exception {
Assumptions.assumeTrue(dockerDaemonReachable(), "Docker daemon is not reachable");
@@ -99,6 +111,72 @@ void uploadsAndDownloadsBinaryLargerThanOneMegabyteBitForBit() throws Exception
assertArrayEquals(payload, downloaded, "uploaded and downloaded bytes must be identical");
}
+ @Test
+ void streamsLargeBinaryFileWithoutClosingCallerStreamsAndKeepsUploadMode() throws Exception {
+ Path source = hostDirectory.resolve("large.bin");
+ Random random = new Random(42L);
+ byte[] buffer = new byte[64 * 1024];
+ try (OutputStream output = Files.newOutputStream(source)) {
+ for (int block = 0; block < 256; block++) {
+ random.nextBytes(buffer);
+ output.write(buffer);
+ }
+ }
+ MessageDigest expected = MessageDigest.getInstance("SHA-256");
+ try (InputStream input = new DigestInputStream(Files.newInputStream(source), expected)) {
+ input.transferTo(OutputStream.nullOutputStream());
+ }
+ AtomicBoolean inputClosed = new AtomicBoolean();
+ String path = "/workspace/streaming/large \"file\".bin";
+ try (InputStream input =
+ new FilterInputStream(Files.newInputStream(source)) {
+ @Override
+ public void close() throws IOException {
+ inputClosed.set(true);
+ super.close();
+ }
+ }) {
+ sandbox.uploadFile(path, input, Files.size(source));
+ assertFalse(inputClosed.get());
+ }
+ MessageDigest actual = MessageDigest.getInstance("SHA-256");
+ AtomicBoolean outputClosed = new AtomicBoolean();
+ int[] flushes = {0};
+ try (OutputStream output =
+ new FilterOutputStream(
+ new DigestOutputStream(OutputStream.nullOutputStream(), actual)) {
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ out.write(bytes, offset, length);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ flushes[0]++;
+ super.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ outputClosed.set(true);
+ super.close();
+ }
+ }) {
+ sandbox.downloadFile(path, output);
+ assertFalse(outputClosed.get());
+ assertEquals(0, flushes[0]);
+ }
+ assertArrayEquals(expected.digest(), actual.digest());
+ assertEquals(
+ "644",
+ sandbox.exec(
+ RuntimeContext.empty(),
+ "stat -c '%a' '/workspace/streaming/large \"file\".bin'",
+ 10)
+ .stdout()
+ .trim());
+ }
+
@Test
void filesystemWriteUploadsOverExclusivePlaceholder() {
SandboxBackedFilesystem filesystem = new SandboxBackedFilesystem();
diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxStreamingFileTransferTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxStreamingFileTransferTest.java
new file mode 100644
index 0000000000..590b9d81ae
--- /dev/null
+++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxStreamingFileTransferTest.java
@@ -0,0 +1,624 @@
+/*
+ * Copyright 2024-2026 the original author or 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 io.agentscope.harness.agent.sandbox.impl.docker;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import io.agentscope.harness.agent.sandbox.SandboxErrorCode;
+import io.agentscope.harness.agent.sandbox.SandboxException;
+import io.agentscope.harness.agent.sandbox.WorkspaceSpec;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.zip.CRC32;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
+import org.junit.jupiter.api.Test;
+
+class DockerSandboxStreamingFileTransferTest {
+
+ private static final int CONTENT_SIZE = 8 * 1024 * 1024;
+
+ @Test
+ void uploadStreamsBeforeReadingWholeInputAndPreservesMode() throws Exception {
+ PipedInputStream archiveInput = new PipedInputStream(32 * 1024);
+ PipedOutputStream archiveOutput = new PipedOutputStream(archiveInput);
+ FakeProcess process = new FakeProcess(InputStream.nullInputStream(), archiveOutput);
+ CountDownLatch firstPayload = new CountDownLatch(1);
+ GeneratedInput content = new GeneratedInput(CONTENT_SIZE, firstPayload);
+ CountingSink received = new CountingSink();
+ AtomicReference uploadedEntry = new AtomicReference<>();
+ AtomicReference readerFailure = new AtomicReference<>();
+ Thread reader =
+ daemon(
+ () -> {
+ try (TarArchiveInputStream tar =
+ new TarArchiveInputStream(archiveInput)) {
+ uploadedEntry.set(tar.getNextEntry());
+ byte[] buffer = new byte[8192];
+ int read;
+ while ((read = tar.read(buffer)) != -1) {
+ received.write(buffer, 0, read);
+ firstPayload.countDown();
+ }
+ assertNull(tar.getNextEntry());
+ archiveInput.transferTo(OutputStream.nullOutputStream());
+ process.finish(0);
+ } catch (Throwable error) {
+ readerFailure.set(error);
+ process.finish(1);
+ }
+ });
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+
+ sandbox.uploadFile("reports/with \"quotes\".bin", content, CONTENT_SIZE);
+ reader.join(3000);
+
+ assertNull(readerFailure.get());
+ assertFalse(reader.isAlive());
+ assertEquals(CONTENT_SIZE, received.count);
+ assertEquals(content.checksum.getValue(), received.checksum.getValue());
+ assertEquals("with \"quotes\".bin", uploadedEntry.get().getName());
+ assertEquals(0644, uploadedEntry.get().getMode());
+ assertEquals(CONTENT_SIZE, uploadedEntry.get().getSize());
+ assertEquals(
+ List.of("docker", "cp", "-", "container-1:/workspace/reports"),
+ sandbox.transferCommand);
+ assertTrue(
+ sandbox.commands.contains(
+ List.of(
+ "docker",
+ "exec",
+ "container-1",
+ "mkdir",
+ "-p",
+ "/workspace/reports")));
+ assertFalse(content.closed);
+ assertTrue(process.stdin.closed);
+ assertTrue(process.stdout.closed);
+ assertTrue(process.stderr.closed);
+ }
+
+ @Test
+ void downloadWritesBeforeEntireArchiveArrivesAndDoesNotCloseOrFlushSink() throws Exception {
+ PipedInputStream archiveInput = new PipedInputStream(32 * 1024);
+ PipedOutputStream archiveOutput = new PipedOutputStream(archiveInput);
+ FakeProcess process = new FakeProcess(archiveInput, OutputStream.nullOutputStream());
+ CountDownLatch firstWrite = new CountDownLatch(1);
+ CountingSink sink = new CountingSink(firstWrite);
+ GeneratedInput content = new GeneratedInput(CONTENT_SIZE, firstWrite);
+ AtomicReference writerFailure = new AtomicReference<>();
+ Thread writer =
+ daemon(
+ () -> {
+ try (TarArchiveOutputStream tar =
+ new TarArchiveOutputStream(archiveOutput)) {
+ TarArchiveEntry entry = new TarArchiveEntry("result.bin");
+ entry.setSize(CONTENT_SIZE);
+ tar.putArchiveEntry(entry);
+ content.transferTo(tar);
+ tar.closeArchiveEntry();
+ tar.finish();
+ } catch (Throwable error) {
+ writerFailure.set(error);
+ } finally {
+ process.finish(writerFailure.get() == null ? 0 : 1);
+ }
+ });
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+
+ sandbox.downloadFile("/workspace/result.bin", sink);
+ writer.join(3000);
+
+ assertNull(writerFailure.get());
+ assertFalse(writer.isAlive());
+ assertEquals(CONTENT_SIZE, sink.count);
+ assertEquals(content.checksum.getValue(), sink.checksum.getValue());
+ assertFalse(sink.closed);
+ assertEquals(0, sink.flushes);
+ assertEquals(
+ List.of("docker", "cp", "container-1:/workspace/result.bin", "-"),
+ sandbox.transferCommand);
+ assertTrue(process.stdout.closed);
+ assertTrue(process.stdin.closed);
+ assertTrue(process.stderr.closed);
+ }
+
+ @Test
+ void uploadPropagatesSourceFailureAndClosesOnlyProcessPipes() {
+ IOException failure = new IOException("source failed");
+ TrackingInput content =
+ new TrackingInput(
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw failure;
+ }
+ });
+ FakeProcess process =
+ new FakeProcess(InputStream.nullInputStream(), OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+
+ assertSame(
+ failure,
+ assertThrows(IOException.class, () -> sandbox.uploadFile("a.bin", content, 1)));
+
+ assertFalse(content.closed);
+ assertTrue(process.destroyed);
+ assertTrue(process.stdin.closed);
+ assertTrue(process.stdout.closed);
+ assertTrue(process.stderr.closed);
+ }
+
+ @Test
+ void uploadAcceptsTarHeadersLargerThanEightGiB() throws Exception {
+ long contentLength = 8L * 1024 * 1024 * 1024;
+ IOException failure = new IOException("source failed");
+ InputStream content =
+ new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw failure;
+ }
+ };
+ ByteArrayOutputStream archive = new ByteArrayOutputStream();
+ FakeProcess process = new FakeProcess(InputStream.nullInputStream(), archive);
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+
+ assertSame(
+ failure,
+ assertThrows(
+ IOException.class,
+ () -> sandbox.uploadFile("large.bin", content, contentLength)));
+
+ try (TarArchiveInputStream tar =
+ new TarArchiveInputStream(new ByteArrayInputStream(archive.toByteArray()))) {
+ assertEquals(contentLength, tar.getNextEntry().getSize());
+ }
+ }
+
+ @Test
+ void downloadPropagatesSinkFailureAndDoesNotCloseOrFlushSink() throws Exception {
+ IOException failure = new IOException("sink failed");
+ CountingSink sink =
+ new CountingSink() {
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ throw failure;
+ }
+ };
+ FakeProcess process =
+ new FakeProcess(
+ new ByteArrayInputStream(archive("file.bin", new byte[] {1})),
+ OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+
+ assertSame(
+ failure,
+ assertThrows(IOException.class, () -> sandbox.downloadFile("file.bin", sink)));
+
+ assertFalse(sink.closed);
+ assertEquals(0, sink.flushes);
+ assertTrue(process.destroyed);
+ assertTrue(process.stdout.closed);
+ }
+
+ @Test
+ void uploadRejectsIncorrectLengthWithoutClosingInput() {
+ for (long length : new long[] {0, 2}) {
+ FakeProcess process =
+ new FakeProcess(InputStream.nullInputStream(), OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+ TrackingInput content = new TrackingInput(new ByteArrayInputStream(new byte[] {1}));
+
+ assertThrows(IOException.class, () -> sandbox.uploadFile("file.bin", content, length));
+
+ assertFalse(content.closed);
+ assertTrue(process.destroyed);
+ }
+ }
+
+ @Test
+ void invalidArgumentsAndPathsDoNotReadInputOrStartDocker() {
+ FakeProcess process =
+ new FakeProcess(InputStream.nullInputStream(), OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+ GeneratedInput content = new GeneratedInput(16, null);
+ CountingSink sink = new CountingSink();
+
+ assertThrows(NullPointerException.class, () -> sandbox.uploadFile("file", null, 0));
+ assertThrows(IllegalArgumentException.class, () -> sandbox.uploadFile("file", content, -1));
+ assertThrows(
+ IllegalArgumentException.class, () -> sandbox.uploadFile("../escape", content, 16));
+ assertThrows(
+ IllegalArgumentException.class, () -> sandbox.downloadFile("/etc/passwd", sink));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> sandbox.downloadFile("file", (OutputStream) null));
+
+ assertEquals(0, content.position);
+ assertEquals(0, sink.count);
+ assertNull(sandbox.transferCommand);
+ assertTrue(sandbox.commands.isEmpty());
+ }
+
+ @Test
+ void missingFileOrMultipleArchiveEntriesAreRejected() throws Exception {
+ for (byte[] archive :
+ List.of(new byte[0], archive("directory/", new byte[0]), multipleFiles())) {
+ FakeProcess process =
+ new FakeProcess(
+ new ByteArrayInputStream(archive), OutputStream.nullOutputStream());
+ process.finish(0);
+ CountingSink sink = new CountingSink();
+
+ assertThrows(
+ IOException.class,
+ () -> new StreamingSandbox(process).downloadFile("file.bin", sink));
+
+ assertFalse(sink.closed);
+ assertEquals(0, sink.flushes);
+ assertTrue(process.stdout.closed);
+ }
+ }
+
+ @Test
+ void timeoutDestroysProcessAndReleasesPipesWithoutClosingSink() {
+ PipedInputStream stalled = new PipedInputStream();
+ try (PipedOutputStream writer = new PipedOutputStream(stalled)) {
+ FakeProcess process = new FakeProcess(stalled, OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+ sandbox.timeoutSeconds = 1;
+ CountingSink sink = new CountingSink();
+ long start = System.nanoTime();
+
+ SandboxException.SandboxRuntimeException failure =
+ assertThrows(
+ SandboxException.SandboxRuntimeException.class,
+ () -> sandbox.downloadFile("file.bin", sink));
+
+ assertEquals(SandboxErrorCode.WORKSPACE_START_ERROR, failure.getErrorCode());
+ assertTrue(
+ Duration.ofNanos(System.nanoTime() - start).compareTo(Duration.ofSeconds(4))
+ < 0);
+ assertTrue(process.destroyed);
+ assertTrue(process.stdout.closed);
+ assertTrue(process.stdin.closed);
+ assertTrue(process.stderr.closed);
+ assertFalse(sink.closed);
+ } catch (IOException failure) {
+ throw new AssertionError(failure);
+ }
+ }
+
+ @Test
+ void interruptionPreservesInterruptFlagAndStopsTransfer() throws Exception {
+ PipedInputStream stalled = new PipedInputStream();
+ try (PipedOutputStream writer = new PipedOutputStream(stalled)) {
+ FakeProcess process = new FakeProcess(stalled, OutputStream.nullOutputStream());
+ StreamingSandbox sandbox = new StreamingSandbox(process);
+ CountingSink sink = new CountingSink();
+ AtomicReference failure = new AtomicReference<>();
+ AtomicBoolean interrupted = new AtomicBoolean();
+ Thread caller =
+ new Thread(
+ () -> {
+ try {
+ sandbox.downloadFile("file.bin", sink);
+ } catch (Throwable error) {
+ failure.set(error);
+ interrupted.set(Thread.currentThread().isInterrupted());
+ }
+ });
+ caller.start();
+ assertTrue(sandbox.started.await(3, TimeUnit.SECONDS));
+ caller.interrupt();
+ caller.join(3000);
+
+ assertFalse(caller.isAlive());
+ assertInstanceOf(InterruptedException.class, failure.get());
+ assertTrue(interrupted.get());
+ assertTrue(process.destroyed);
+ assertTrue(process.stdout.closed);
+ assertFalse(sink.closed);
+ }
+ }
+
+ private static byte[] archive(String name, byte[] content) throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bytes)) {
+ TarArchiveEntry entry = new TarArchiveEntry(name);
+ entry.setSize(content.length);
+ tar.putArchiveEntry(entry);
+ tar.write(content);
+ tar.closeArchiveEntry();
+ tar.finish();
+ }
+ return bytes.toByteArray();
+ }
+
+ private static byte[] multipleFiles() throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bytes)) {
+ for (String name : List.of("first", "second")) {
+ TarArchiveEntry entry = new TarArchiveEntry(name);
+ entry.setSize(0);
+ tar.putArchiveEntry(entry);
+ tar.closeArchiveEntry();
+ }
+ tar.finish();
+ }
+ return bytes.toByteArray();
+ }
+
+ private static Thread daemon(Runnable action) {
+ Thread thread = new Thread(action, "docker-streaming-test-peer");
+ thread.setDaemon(true);
+ thread.start();
+ return thread;
+ }
+
+ private static final class StreamingSandbox extends DockerSandbox {
+ final List> commands = new ArrayList<>();
+ final CountDownLatch started = new CountDownLatch(1);
+ final FakeProcess process;
+ List transferCommand;
+ int timeoutSeconds = 5;
+
+ StreamingSandbox(FakeProcess process) {
+ super(state());
+ this.process = process;
+ }
+
+ private static DockerSandboxState state() {
+ DockerSandboxState state = new DockerSandboxState();
+ state.setContainerId("container-1");
+ state.setWorkspaceRoot("/workspace");
+ state.setWorkspaceSpec(new WorkspaceSpec());
+ return state;
+ }
+
+ @Override
+ void runDockerCliBlocking(int timeoutSeconds, String... command) {
+ commands.add(List.of(command));
+ }
+
+ @Override
+ Process startFileTransferProcess(String... command) {
+ transferCommand = List.of(command);
+ started.countDown();
+ return process;
+ }
+
+ @Override
+ int fileTransferTimeoutSeconds() {
+ return timeoutSeconds;
+ }
+ }
+
+ private static final class FakeProcess extends Process {
+ final TrackingInput stdout;
+ final TrackingInput stderr = new TrackingInput(InputStream.nullInputStream());
+ final TrackingOutput stdin;
+ final CountDownLatch finished = new CountDownLatch(1);
+ volatile boolean destroyed;
+ volatile int exitCode;
+
+ FakeProcess(InputStream stdout, OutputStream stdin) {
+ this.stdout = new TrackingInput(stdout);
+ this.stdin = new TrackingOutput(stdin);
+ }
+
+ void finish(int exitCode) {
+ this.exitCode = exitCode;
+ finished.countDown();
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ return stdin;
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return stdout;
+ }
+
+ @Override
+ public InputStream getErrorStream() {
+ return stderr;
+ }
+
+ @Override
+ public int waitFor() throws InterruptedException {
+ finished.await();
+ return exitCode;
+ }
+
+ @Override
+ public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException {
+ return finished.await(timeout, unit);
+ }
+
+ @Override
+ public int exitValue() {
+ if (isAlive()) throw new IllegalThreadStateException();
+ return exitCode;
+ }
+
+ @Override
+ public boolean isAlive() {
+ return finished.getCount() != 0;
+ }
+
+ @Override
+ public void destroy() {
+ destroyed = true;
+ finish(137);
+ }
+
+ @Override
+ public Process destroyForcibly() {
+ destroy();
+ return this;
+ }
+ }
+
+ private static final class TrackingInput extends FilterInputStream {
+ boolean closed;
+
+ TrackingInput(InputStream input) {
+ super(input);
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed = true;
+ super.close();
+ }
+ }
+
+ private static final class TrackingOutput extends FilterOutputStream {
+ boolean closed;
+
+ TrackingOutput(OutputStream output) {
+ super(output);
+ }
+
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ out.write(bytes, offset, length);
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed = true;
+ super.close();
+ }
+ }
+
+ private static class CountingSink extends OutputStream {
+ final CRC32 checksum = new CRC32();
+ final CountDownLatch firstWrite;
+ long count;
+ boolean closed;
+ int flushes;
+
+ CountingSink() {
+ this(null);
+ }
+
+ CountingSink(CountDownLatch firstWrite) {
+ this.firstWrite = firstWrite;
+ }
+
+ @Override
+ public void write(int value) {
+ checksum.update(value);
+ count++;
+ if (firstWrite != null) firstWrite.countDown();
+ }
+
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ checksum.update(bytes, offset, length);
+ count += length;
+ if (firstWrite != null) firstWrite.countDown();
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+
+ @Override
+ public void flush() {
+ flushes++;
+ }
+ }
+
+ private static final class GeneratedInput extends InputStream {
+ final CRC32 checksum = new CRC32();
+ final int length;
+ final CountDownLatch firstPayload;
+ int position;
+ boolean closed;
+
+ GeneratedInput(int length, CountDownLatch firstPayload) {
+ this.length = length;
+ this.firstPayload = firstPayload;
+ }
+
+ @Override
+ public int read(byte[] bytes, int offset, int requested) throws IOException {
+ if (position == length) return -1;
+ if (position >= 8192 && firstPayload != null) {
+ try {
+ if (!firstPayload.await(3, TimeUnit.SECONDS))
+ throw new IOException(
+ "Transfer buffered the input before forwarding its first bytes");
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ throw new IOException(error);
+ }
+ }
+ int read = Math.min(requested, length - position);
+ for (int index = 0; index < read; index++)
+ bytes[offset + index] = (byte) ((position + index) % 251);
+ checksum.update(bytes, offset, read);
+ position += read;
+ return read;
+ }
+
+ @Override
+ public int read() {
+ if (position == length) return -1;
+ int value = position++ % 251;
+ checksum.update(value);
+ return value;
+ }
+
+ @Override
+ public byte[] readAllBytes() {
+ throw new AssertionError("Streaming must not call readAllBytes");
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+ }
+}
diff --git a/docs/dev/en/docs/harness/filesystem.md b/docs/dev/en/docs/harness/filesystem.md
index 0b91fd93b5..a28fd49dbb 100644
--- a/docs/dev/en/docs/harness/filesystem.md
+++ b/docs/dev/en/docs/harness/filesystem.md
@@ -489,6 +489,49 @@ All file tools call through the `AbstractFilesystem` interface, passing the curr
| Shared store | `CompositeFilesystem`: routed paths go through KV overlay (remote upper + local template lower); others go local |
| Sandbox | All file operations forwarded into the sandbox container |
+### Streaming file transfers
+
+Use `AbstractFilesystem.uploadFile(runtimeContext, path, content, contentLength)` and `downloadFile(runtimeContext, path, sink)` to transfer a single file through Java streams. They follow the configured filesystem's path rules, routing, and runtime isolation. For a local-mode agent, obtain its filesystem and pass the same `RuntimeContext` used for agent calls.
+
+The methods return `FileUploadResponse` and `FileDownloadResponse`. Check `isSuccess()` after each transfer and inspect `error()` on failure. A successful streaming download has `content() == null` because the bytes are written to the supplied sink.
+
+```java
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+RuntimeContext context = RuntimeContext.builder()
+ .userId("alice").sessionId("alice-s1").build();
+AbstractFilesystem filesystem = agent.getWorkspaceManager().getFilesystem();
+Path source = Path.of("input.bin");
+
+try (InputStream content = Files.newInputStream(source)) {
+ FileUploadResponse upload =
+ filesystem.uploadFile(context, "input.bin", content, Files.size(source));
+ if (!upload.isSuccess()) {
+ throw new IOException("Upload failed: " + upload.error());
+ }
+}
+try (OutputStream sink = Files.newOutputStream(Path.of("downloaded.bin"))) {
+ FileDownloadResponse download = filesystem.downloadFile(context, "input.bin", sink);
+ if (!download.isSuccess()) {
+ throw new IOException("Download failed: " + download.error());
+ }
+}
+```
+
+Both methods are synchronous and blocking, so run them outside reactive event-loop threads. The caller owns the streams and must close them, as the example does with try-with-resources. A download does not flush its output stream. If you keep that stream open, flush it when your application needs the bytes to reach its destination. Network timeouts cannot forcibly stop a blocking read or write in a caller-provided stream; configure those streams to complete promptly or enforce their own timeouts.
+
+An upload requires a nonnegative `contentLength` that exactly matches the bytes available through EOF. Keep the source unchanged during the transfer. Transfer failures and length mismatches are reported by failed result objects. An upload can update its destination incrementally, and either operation can leave partial content. Reset or replace the destination before retrying a failed download. The example converts failed results into exceptions to stop its execution.
+
+`LocalFilesystem` and the Docker, E2B, and Kubernetes sandboxes transfer files with bounded client-side buffers on paths supported by their native file APIs. For Kubernetes, configure `fileApiBaseDir` to match the runtime's file API base directory. Unsupported paths and backends can still use the default implementation, which buffers the complete file through the existing `byte[]` APIs. Provider and gateway request size limits still apply. The remote runtime may buffer data independently of the client. These stream methods do not change bulk `uploadFiles` / `downloadFiles` calls, workspace archive transfers, or snapshots.
+
### Shell execution (execute)
| Mode | Shell available? | Where it runs |
diff --git a/docs/dev/zh/docs/harness/filesystem.md b/docs/dev/zh/docs/harness/filesystem.md
index 8e869fb244..f03443abf7 100644
--- a/docs/dev/zh/docs/harness/filesystem.md
+++ b/docs/dev/zh/docs/harness/filesystem.md
@@ -488,6 +488,49 @@ Harness 把仓库中当前可见的技能渲染成仅供本轮请求使用的 `<
| 共享存储 | `CompositeFilesystem`:命中路由的路径走 KV overlay(远端上层 + 本地模板下层),其余走本地 |
| 沙箱 | 所有文件操作转发到沙箱容器内 |
+### 流式文件传输
+
+通过 `AbstractFilesystem.uploadFile(runtimeContext, path, content, contentLength)` 和 `downloadFile(runtimeContext, path, sink)`,可以使用 Java 流传输单个文件。这两个方法遵循已配置文件系统的路径规则、路由和运行时隔离。对于本机模式的 agent,获取它的文件系统,并传入调用 agent 时使用的同一个 `RuntimeContext`。
+
+两个方法分别返回 `FileUploadResponse` 和 `FileDownloadResponse`。每次传输后都应检查 `isSuccess()`,失败时通过 `error()` 获取错误。流式下载成功时 `content() == null`,文件字节已写入调用方提供的 sink。
+
+```java
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
+import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
+import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+RuntimeContext context = RuntimeContext.builder()
+ .userId("alice").sessionId("alice-s1").build();
+AbstractFilesystem filesystem = agent.getWorkspaceManager().getFilesystem();
+Path source = Path.of("input.bin");
+
+try (InputStream content = Files.newInputStream(source)) {
+ FileUploadResponse upload =
+ filesystem.uploadFile(context, "input.bin", content, Files.size(source));
+ if (!upload.isSuccess()) {
+ throw new IOException("Upload failed: " + upload.error());
+ }
+}
+try (OutputStream sink = Files.newOutputStream(Path.of("downloaded.bin"))) {
+ FileDownloadResponse download = filesystem.downloadFile(context, "input.bin", sink);
+ if (!download.isSuccess()) {
+ throw new IOException("Download failed: " + download.error());
+ }
+}
+```
+
+两个方法都是同步阻塞调用,应在响应式事件循环线程之外执行。流由调用方管理,需要像示例一样通过 try-with-resources 关闭。下载方法不会 flush 输出流。如果需要保持流打开,应由应用在需要将字节送达目标时主动 flush。网络超时无法强制停止调用方流中的阻塞读写;这些流应能及时完成操作,或设置自身的超时。
+
+上传的 `contentLength` 必须非负,并且与输入流直到 EOF 的实际字节数完全一致。传输期间应保持源文件不变。传输失败和长度不匹配通过失败结果对象报告。上传过程中目标内容可能逐步更新,两种操作都可能留下部分内容。重试失败的下载前,应重置或替换目标。示例将失败结果转换为异常,以便停止执行。
+
+`LocalFilesystem` 以及 Docker、E2B 和 Kubernetes 沙箱,对原生文件 API 支持的路径使用有界的客户端缓冲区传输文件。使用 Kubernetes 时,应将 `fileApiBaseDir` 配置为与 runtime 的文件 API 基础目录一致。不受支持的路径和后端仍可能使用默认实现,通过已有的 `byte[]` API 缓冲整个文件。服务提供方和网关的请求大小限制仍然生效。远端 runtime 可能独立缓存数据。这两个流式方法不会改变批量 `uploadFiles` / `downloadFiles` 调用、工作区归档传输或快照的行为。
+
### Shell 执行(execute)
| 模式 | Shell 可用? | 执行位置 |