Skip to main content
The OpenSandbox Kotlin SDK provides secure, isolated execution environments with comprehensive file system access, command execution, and resource management capabilities.

Installation

dependencies {
    implementation("com.alibaba.opensandbox:sandbox:{latest_version}")
}

Core Classes

Sandbox

Main class for creating and managing sandbox instances.

Builder Methods

build()
Create a new sandbox instance using the builder pattern.
import com.alibaba.opensandbox.sandbox.Sandbox;
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import java.time.Duration;

ConnectionConfig config = ConnectionConfig.builder()
    .domain("api.opensandbox.io")
    .apiKey("your-api-key")
    .build();

try (Sandbox sandbox = Sandbox.builder()
        .connectionConfig(config)
        .image("python:3.11")
        .timeout(Duration.ofMinutes(30))
        .resource(map -> {
            map.put("cpu", "2");
            map.put("memory", "4Gi");
        })
        .env("PYTHONPATH", "/workspace")
        .build()) {

    // Use sandbox
    sandbox.commands().run("python script.py");
}
connectionConfig
ConnectionConfig
required
Connection configuration for API server.
image
String
required
Docker image to use.
timeout
Duration
default:"Duration.ofMinutes(10)"
Automatic termination timeout.
entrypoint
List<String>
default:"[\"tail\", \"-f\", \"/dev/null\"]"
Container entrypoint command.
resource
Map<String, String>
default:"{\"cpu\": \"1\", \"memory\": \"2Gi\"}"
CPU and memory limits.
env
Map<String, String>
Environment variables.
metadata
Map<String, String>
Custom metadata tags.
networkPolicy
NetworkPolicy
Optional outbound network policy (egress).
readyTimeout
Duration
default:"Duration.ofSeconds(30)"
Maximum time to wait for sandbox to be ready.
healthCheck
Function<Sandbox, Boolean>
Custom health check function.
return
Sandbox
Fully configured and ready Sandbox instance.

Instance Methods

getInfo()
Get the current status of the sandbox.
SandboxInfo info = sandbox.getInfo();
System.out.println("State: " + info.getStatus().getState());
return
SandboxInfo
Current sandbox status including state and metadata.
getEndpoint()
Get a specific network endpoint for the sandbox.
SandboxEndpoint endpoint = sandbox.getEndpoint(80);
System.out.println("Endpoint: " + endpoint.getEndpoint());
port
int
required
The port number to get the endpoint for.
return
SandboxEndpoint
Endpoint information including connection details.
renew()
Renew the sandbox expiration time.
sandbox.renew(Duration.ofMinutes(30));
timeout
Duration
required
Duration to add to the current time to set the new expiration.
return
void
Method completes when renewal is successful.
pause()
Pause the sandbox while preserving its state.
sandbox.pause();
return
void
Method completes when sandbox is paused.
resume()
Resume a previously paused sandbox.
sandbox.resume();
return
void
Method completes when sandbox is resumed.
kill()
Terminate the remote sandbox instance.
sandbox.kill();
return
void
Method completes when sandbox is terminated.
close()
Close local resources associated with the sandbox.
sandbox.close();
return
void
Method completes when resources are closed.

Properties

commands()
Provides access to command execution operations.
Execution execution = sandbox.commands().run("echo 'Hello World'");
System.out.println(execution.getLogs().getStdout().get(0).getText());
return
Commands
Command execution interface.
files()
Provides access to file system operations.
sandbox.files().write(List.of(
    WriteEntry.builder()
        .path("/tmp/hello.txt")
        .data("Hello World")
        .mode(644)
        .build()
));
String content = sandbox.files().readFile("/tmp/hello.txt", "UTF-8", null);
return
Filesystem
File system operations interface.

SandboxManager

Administrative interface for managing multiple sandbox instances.

Builder Methods

build()
Create a SandboxManager instance.
import com.alibaba.opensandbox.sandbox.SandboxManager;

SandboxManager manager = SandboxManager.builder()
    .connectionConfig(config)
    .build();
connectionConfig
ConnectionConfig
required
Connection configuration.
return
SandboxManager
Configured sandbox manager instance.

Instance Methods

listSandboxInfos()
List sandboxes with filtering options.
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.SandboxState;

PagedSandboxInfos sandboxes = manager.listSandboxInfos(
    SandboxFilter.builder()
        .states(SandboxState.RUNNING)
        .pageSize(10)
        .page(1)
        .build()
);

sandboxes.getSandboxInfos().forEach(info ->
    System.out.println("Found sandbox: " + info.getId())
);
filter
SandboxFilter
required
Filter criteria for sandbox listing.
return
PagedSandboxInfos
Paged sandbox information matching the filter criteria.
killSandbox()
Terminate a single sandbox.
manager.killSandbox("sandbox-id");
sandboxId
String
required
Sandbox ID to terminate.
return
void
Method completes when sandbox is terminated.
close()
Close local resources associated with the manager.
manager.close();
return
void
Method completes when resources are closed.

Service Interfaces

Commands

Command execution service for sandbox environments.

run()

Execute a shell command in the sandbox.
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;
import com.alibaba.opensandbox.sandbox.domain.models.execd.ExecutionHandlers;

// Simple execution
Execution execution = sandbox.commands().run("echo 'Hello World'");
System.out.println(execution.getLogs().getStdout().get(0).getText());

// With handlers
ExecutionHandlers handlers = ExecutionHandlers.builder()
    .onStdout(msg -> System.out.println("STDOUT: " + msg.getText()))
    .onStderr(msg -> System.err.println("STDERR: " + msg.getText()))
    .onExecutionComplete(complete ->
        System.out.println("Command finished in " + complete.getExecutionTimeInMillis() + "ms")
    )
    .build();

RunCommandRequest request = RunCommandRequest.builder()
    .command("for i in {1..5}; do echo \"Count $i\"; sleep 0.5; done")
    .handlers(handlers)
    .build();

sandbox.commands().run(request);
command
String
required
Shell command text to execute.
request
RunCommandRequest
Command request with options and handlers.
return
Execution
Execution handle representing the running command.

Filesystem

Filesystem operations service for sandbox environments.

readFile()

Read the content of a file as a string.
String content = sandbox.files().readFile("/tmp/hello.txt", "UTF-8", null);
System.out.println("Content: " + content);
path
String
required
The absolute or relative path to the file to read.
encoding
String
default:"UTF-8"
Character encoding for the file content.
rangeHeader
String
HTTP byte range to read (e.g., “bytes=0-1023”).
return
String
The file content as a string.

write()

Write content to files.
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;

sandbox.files().write(List.of(
    WriteEntry.builder()
        .path("/tmp/hello.txt")
        .data("Hello World")
        .mode(644)
        .build()
));
entries
List<WriteEntry>
required
List of write entries specifying files and their content.
return
void
Method completes when files are written.

deleteFiles()

Delete the specified files.
sandbox.files().deleteFiles(List.of("/tmp/hello.txt"));
paths
List<String>
required
List of file paths to delete.
return
void
Method completes when files are deleted.
Search for files and directories.
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.SearchEntry;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.EntryInfo;

List<EntryInfo> files = sandbox.files().search(
    SearchEntry.builder()
        .path("/tmp")
        .pattern("*.txt")
        .build()
);
files.forEach(f -> System.out.println("Found: " + f.getPath()));
entry
SearchEntry
required
Search entry containing search parameters and criteria.
return
List<EntryInfo>
List of matching file/directory information.

Configuration

ConnectionConfig

Connection configuration for API server communication.
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import okhttp3.ConnectionPool;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

// Basic configuration
ConnectionConfig config = ConnectionConfig.builder()
    .apiKey("your-key")
    .domain("api.opensandbox.io")
    .requestTimeout(Duration.ofSeconds(60))
    .build();

// Advanced: Shared Connection Pool
ConnectionPool sharedPool = new ConnectionPool(50, 30, TimeUnit.SECONDS);

ConnectionConfig sharedConfig = ConnectionConfig.builder()
    .apiKey("your-key")
    .domain("api.opensandbox.io")
    .connectionPool(sharedPool)
    .build();
apiKey
String
required
API Key for authentication (can also be set via OPEN_SANDBOX_API_KEY environment variable).
domain
String
required
The endpoint domain of the sandbox service (can also be set via OPEN_SANDBOX_DOMAIN environment variable).
protocol
String
default:"http"
HTTP protocol (http/https).
requestTimeout
Duration
default:"Duration.ofSeconds(30)"
Timeout for API requests.
debug
boolean
default:"false"
Enable debug logging for HTTP requests.
headers
Map<String, String>
Custom HTTP headers.
connectionPool
ConnectionPool
Shared OKHttp ConnectionPool.
useServerProxy
boolean
default:"false"
Use sandbox server as proxy for execd/endpoint requests.

Network Policy

import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkPolicy;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkRule;

Sandbox sandbox = Sandbox.builder()
    .connectionConfig(config)
    .image("python:3.11")
    .networkPolicy(
        NetworkPolicy.builder()
            .defaultAction(NetworkPolicy.DefaultAction.DENY)
            .addEgress(
                NetworkRule.builder()
                    .action(NetworkRule.Action.ALLOW)
                    .target("pypi.org")
                    .build()
            )
            .build()
    )
    .build();

Complete Example

import com.alibaba.opensandbox.sandbox.Sandbox;
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxException;
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;
import java.time.Duration;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        ConnectionConfig config = ConnectionConfig.builder()
            .domain("api.opensandbox.io")
            .apiKey("your-api-key")
            .build();

        try (Sandbox sandbox = Sandbox.builder()
                .connectionConfig(config)
                .image("python:3.11")
                .timeout(Duration.ofMinutes(30))
                .build()) {

            // Write a file
            sandbox.files().write(List.of(
                WriteEntry.builder()
                    .path("/tmp/script.py")
                    .data("print('Hello World')")
                    .mode(644)
                    .build()
            ));

            // Execute command
            Execution execution = sandbox.commands().run("python /tmp/script.py");
            System.out.println(execution.getLogs().getStdout().get(0).getText());

            // Get info
            SandboxInfo info = sandbox.getInfo();
            System.out.println("State: " + info.getStatus().getState());

            // Cleanup
            sandbox.kill();
        } catch (SandboxException e) {
            System.err.println("Sandbox Error: [" + e.getError().getCode() + "] " + e.getError().getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Build docs developers (and LLMs) love