Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.UserMessage;
import io.agentscope.harness.agent.HarnessAgent;
import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse;
import io.agentscope.harness.agent.filesystem.model.FileUploadResponse;
import io.agentscope.harness.agent.filesystem.spec.LocalFilesystemSpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

Expand All @@ -36,6 +42,8 @@
* <li><b>Multi-user path isolation</b> — different {@code userId} values bucket runtime data
* into separate workspace sub-directories (e.g. {@code workspace/alice/} vs
* {@code workspace/bob/}).</li>
* <li><b>Streaming file transfers</b> — uploads and downloads use caller-owned streams
* through the configured {@link AbstractFilesystem}.</li>
* <li><b>Shell execution</b> — the agent can run host commands via {@code execute}.</li>
* </ol>
*
Expand Down Expand Up @@ -86,6 +94,27 @@ Keep answers concise (under two sentences).
RuntimeContext aliceCtx =
RuntimeContext.builder().userId("alice").sessionId("alice-s1").build();

// ── Upload and download through the filesystem API ──────────────────

AbstractFilesystem filesystem = agent.getWorkspaceManager().getFilesystem();
Path source = workspace.resolve("transfer-source.txt");
Files.writeString(source, "Hello from streamed file transfer");
try (InputStream content = Files.newInputStream(source)) {
FileUploadResponse upload =
filesystem.uploadFile(aliceCtx, "transfer.txt", content, Files.size(source));
if (!upload.isSuccess()) {
throw new IOException("Upload failed: " + upload.error());
}
}
Path downloaded = workspace.resolve("transfer-downloaded.txt");
try (OutputStream sink = Files.newOutputStream(downloaded)) {
FileDownloadResponse download = filesystem.downloadFile(aliceCtx, "transfer.txt", sink);
if (!download.isSuccess()) {
throw new IOException("Download failed: " + download.error());
}
}
System.out.println("Downloaded file: " + Files.readString(downloaded));

System.out.print("Agent: ");
agent.streamEvents(
new UserMessage("Run 'echo $EXAMPLE_VAR' and show the output."), aliceCtx)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
import com.google.protobuf.Descriptors;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import io.agentscope.harness.agent.filesystem.util.FilesystemUtils;
import io.agentscope.harness.agent.sandbox.ExecResult;
import io.agentscope.harness.agent.sandbox.SandboxErrorCode;
import io.agentscope.harness.agent.sandbox.SandboxException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
Expand All @@ -48,6 +50,7 @@
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -763,6 +766,65 @@ void uploadFile(E2bSandboxState state, String remotePath, byte[] data) throws Ex
}
}

/**
* Uploads a caller-owned stream once, without buffering the complete file. Network deadlines
* follow the configured HTTP client; caller stream operations must provide their own bounds.
*/
void uploadFile(E2bSandboxState state, String remotePath, InputStream data, long contentLength)
throws Exception {
FilesystemUtils.validateUpload(data, contentLength);
checkFileTransferInterrupted();
String filename = filenameFromPath(remotePath);
if (filename.isEmpty()) {
throw new IllegalArgumentException("remotePath must be a file path: " + remotePath);
}
AtomicBoolean uploadComplete = new AtomicBoolean();
RequestBody fileBody =
new RequestBody() {
@Override
public MediaType contentType() {
return APPLICATION_OCTET_STREAM;
}

@Override
public long contentLength() {
return contentLength;
}

@Override
public boolean isOneShot() {
return true;
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
FilesystemUtils.copyExactly(data, sink.outputStream(), contentLength);
uploadComplete.set(true);
}
};
MultipartBody multipart =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", filename, fileBody)
.build();
if (multipart.contentLength() < contentLength) {
throw new IllegalArgumentException("Content length is too large for multipart upload");
}
Request req =
baseRequest(envdHost(state) + filesUrl(remotePath), state).post(multipart).build();
OkHttpClient uploadClient =
http.newBuilder().retryOnConnectionFailure(false).followRedirects(false).build();
try (Response res = uploadClient.newCall(req).execute()) {
if (!res.isSuccessful()) {
throw streamingFileTransferError(
res, SandboxErrorCode.WORKSPACE_ARCHIVE_WRITE_ERROR, "upload");
}
if (!uploadComplete.get()) {
throw new IOException("envd upload completed before consuming the file content");
}
}
}

/**
* Download a file from the sandbox filesystem via the E2B Filesystem REST API.
*
Expand All @@ -783,6 +845,46 @@ byte[] downloadFile(E2bSandboxState state, String remotePath) throws Exception {
}
}

/** Writes a file to the caller's sink without closing or flushing that sink. */
void downloadFile(E2bSandboxState state, String remotePath, OutputStream sink)
throws Exception {
Objects.requireNonNull(sink, "sink");
checkFileTransferInterrupted();
Request req = baseRequest(envdHost(state) + filesUrl(remotePath), state).get().build();
OkHttpClient downloadClient = http.newBuilder().retryOnConnectionFailure(false).build();
try (Response res = downloadClient.newCall(req).execute()) {
if (!res.isSuccessful()) {
throw streamingFileTransferError(
res, SandboxErrorCode.WORKSPACE_ARCHIVE_READ_ERROR, "download");
}
InputStream input =
Objects.requireNonNull(res.body(), "envd response body").byteStream();
byte[] buffer = new byte[8192];
while (true) {
checkFileTransferInterrupted();
int read = input.read(buffer);
if (read < 0) {
return;
}
checkFileTransferInterrupted();
sink.write(buffer, 0, read);
}
}
}

private static void checkFileTransferInterrupted() throws InterruptedIOException {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedIOException("File transfer interrupted");
}
}

private static SandboxException.SandboxRuntimeException streamingFileTransferError(
Response res, SandboxErrorCode errorCode, String operation) throws IOException {
String err = res.body() != null ? res.peekBody(8192).string() : "";
return new SandboxException.SandboxRuntimeException(
errorCode, "envd " + operation + " file failed HTTP " + res.code() + ": " + err);
}

private static String filenameFromPath(String path) {
int idx = path.lastIndexOf('/');
return idx >= 0 ? path.substring(idx + 1) : path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -285,6 +286,16 @@ public void uploadFile(String absolutePath, byte[] content) throws Exception {
envd().uploadFile(e2bState, requireWorkspaceTransferPath(absolutePath), content);
}

@Override
public void uploadFile(String absolutePath, InputStream content, long contentLength)
throws Exception {
envd().uploadFile(
e2bState,
requireWorkspaceTransferPath(absolutePath),
content,
contentLength);
}

/**
* Download a file from the sandbox filesystem via the E2B Filesystem REST API.
*
Expand All @@ -296,6 +307,11 @@ public byte[] downloadFile(String absolutePath) throws Exception {
return envd().downloadFile(e2bState, requireWorkspaceTransferPath(absolutePath));
}

@Override
public void downloadFile(String absolutePath, OutputStream sink) throws Exception {
envd().downloadFile(e2bState, requireWorkspaceTransferPath(absolutePath), sink);
}

private void ensureSandbox() throws Exception {
JsonNode sandbox;
if (e2bState.getSandboxId() == null || e2bState.getSandboxId().isBlank()) {
Expand Down
Loading
Loading