The OpenSandbox JavaScript/TypeScript SDK provides secure, isolated execution environments with comprehensive file system access, command execution, and resource management capabilities.
Installation
npm install @alibaba-group/opensandbox
Core Classes
Sandbox
Main class for creating and managing sandbox instances.
Static Methods
create()
Create a new sandbox instance with the specified configuration.
import { Sandbox , ConnectionConfig } from "@alibaba-group/opensandbox" ;
const config = new ConnectionConfig ({
domain: "api.opensandbox.io" ,
apiKey: "your-api-key" ,
});
const sandbox = await Sandbox . create ({
connectionConfig: config ,
image: "python:3.11" ,
timeoutSeconds: 30 * 60 ,
env: { PYTHONPATH: "/workspace" },
resource: { cpu: "2" , memory: "4Gi" },
});
Configuration options for sandbox creation. Connection configuration for API server.
Automatic termination timeout (server-side TTL).
entrypoint
string[]
default: "[\"tail\", \"-f\", \"/dev/null\"]"
Container entrypoint command.
resource
Record<string, string>
default: "{\"cpu\": \"1\", \"memory\": \"2Gi\"}"
CPU and memory limits.
Optional outbound network policy (egress).
Extra server-defined fields.
Skip readiness checks (Running + health check).
healthCheck
(sandbox: Sandbox) => Promise<boolean>
Custom readiness check function.
Maximum time to wait for readiness.
healthCheckPollingInterval
Poll interval while waiting (milliseconds).
Fully configured and ready Sandbox instance.
Instance Methods
getInfo()
Get the current status of the sandbox.
const info = await sandbox . getInfo ();
console . log ( "State:" , info . status . state );
console . log ( "Created:" , info . createdAt );
console . log ( "Expires:" , info . expiresAt );
Current sandbox status including state and metadata.
getEndpoint()
Get a specific network endpoint for the sandbox.
const { endpoint } = await sandbox . getEndpoint ( 80 );
console . log ( "Endpoint:" , endpoint );
The port number to get the endpoint for.
return
Promise<{ endpoint: string }>
Endpoint information (without scheme, e.g., “localhost:44772”).
getEndpointUrl()
Get a ready-to-use absolute URL for a port.
const url = await sandbox . getEndpointUrl ( 80 );
console . log ( "URL:" , url ); // e.g., "http://localhost:44772"
The port number to get the URL for.
Absolute URL with scheme.
renew()
Renew the sandbox expiration time.
await sandbox . renew ( 30 * 60 ); // 30 minutes
Duration in seconds to extend the expiration.
Promise that resolves when renewal is complete.
pause()
Pause the sandbox while preserving its state.
Promise that resolves when sandbox is paused.
resume()
Resume a previously paused sandbox.
const resumed = await sandbox . resume ();
Fresh, connected Sandbox instance.
kill()
Terminate the remote sandbox instance.
Promise that resolves when sandbox is terminated.
close()
Close local resources (HTTP agent) associated with the sandbox.
Promise that resolves when resources are closed.
Properties
commands
Provides access to command execution operations.
const execution = await sandbox . commands . run ( "echo 'Hello World'" );
console . log ( execution . logs . stdout [ 0 ]?. text );
Command execution interface.
files
Provides access to file system operations.
await sandbox . files . writeFiles ([
{ path: "/tmp/hello.txt" , data: "Hello World" , mode: 644 },
]);
const content = await sandbox . files . readFile ( "/tmp/hello.txt" );
File system operations interface.
SandboxManager
Administrative interface for managing multiple sandbox instances.
Static Methods
create()
Create a SandboxManager instance.
import { SandboxManager , ConnectionConfig } from "@alibaba-group/opensandbox" ;
const config = new ConnectionConfig ({
domain: "api.opensandbox.io" ,
apiKey: "your-api-key" ,
});
const manager = SandboxManager . create ({ connectionConfig: config });
Connection configuration.
Configured sandbox manager instance.
Instance Methods
listSandboxInfos()
List sandboxes with filtering options.
const list = await manager . listSandboxInfos ({
states: [ "Running" ],
pageSize: 10 ,
});
console . log ( list . items . map (( s ) => s . id ));
Filter by sandbox states.
Number of results per page.
return
Promise<PagedSandboxInfos>
Paged sandbox information matching the filter criteria.
close()
Close local resources associated with the manager.
Promise that resolves when resources are closed.
Service Interfaces
Commands
Command execution service for sandbox environments.
run()
Execute a shell command in the sandbox.
import type { ExecutionHandlers } from "@alibaba-group/opensandbox" ;
// Simple execution
const execution = await sandbox . commands . run ( "echo 'Hello World'" );
console . log ( execution . logs . stdout [ 0 ]?. text );
// With streaming handlers
const handlers : ExecutionHandlers = {
onStdout : ( m ) => console . log ( "STDOUT:" , m . text ),
onStderr : ( m ) => console . error ( "STDERR:" , m . text ),
onExecutionComplete : ( c ) => console . log ( "Finished in" , c . executionTimeMs , "ms" ),
};
await sandbox . commands . run (
'for i in 1 2 3; do echo "Count $i"; sleep 0.2; done' ,
undefined ,
handlers
);
Shell command text to execute.
Run command in background mode.
Working directory for command execution.
Command execution timeout.
Optional handlers for streaming events.
Execution handle representing the running command.
Filesystem
Filesystem operations service for sandbox environments.
readFile()
Read the content of a file as a string.
const content = await sandbox . files . readFile ( "/tmp/hello.txt" );
console . log ( "Content:" , content );
The absolute or relative path to the file to read.
The file content as a string.
writeFiles()
Write content to files.
await sandbox . files . writeFiles ([
{ path: "/tmp/hello.txt" , data: "Hello World" , mode: 644 },
]);
List of write entries specifying files and their content.
Promise that resolves when files are written.
createDirectories()
Create directories.
await sandbox . files . createDirectories ([{ path: "/tmp/demo" , mode: 755 }]);
entries
CreateDirectoryEntry[]
required
List of directory entries.
Promise that resolves when directories are created.
deleteFiles()
Delete the specified files.
await sandbox . files . deleteFiles ([ "/tmp/hello.txt" ]);
List of file paths to delete.
Promise that resolves when files are deleted.
deleteDirectories()
Delete the specified directories.
await sandbox . files . deleteDirectories ([ "/tmp/demo" ]);
List of directory paths to delete.
Promise that resolves when directories are deleted.
search()
Search for files and directories.
const files = await sandbox . files . search ({
path: "/tmp/demo" ,
pattern: "*.txt" ,
});
console . log ( files . map (( f ) => f . path ));
Glob pattern for matching.
List of matching file/directory information.
Configuration
ConnectionConfig
Connection configuration for API server communication.
import { ConnectionConfig } from "@alibaba-group/opensandbox" ;
const config = new ConnectionConfig ({
domain: "api.opensandbox.io" ,
apiKey: "your-api-key" ,
protocol: "https" ,
requestTimeoutSeconds: 60 ,
headers: { "X-Custom-Header" : "value" },
});
API key for authentication (can also be set via OPEN_SANDBOX_API_KEY environment variable).
domain
string
default: "localhost:8080"
Sandbox service domain (can also be set via OPEN_SANDBOX_DOMAIN environment variable).
protocol
'http' | 'https'
default: "http"
HTTP protocol.
Request timeout applied to SDK HTTP calls.
Enable basic HTTP debug logging.
Extra headers applied to every request.
Use sandbox server as proxy for execd/endpoint requests.
Browser Support
The SDK can run in browsers with the following limitations:
Streaming file uploads are Node-only
In browsers, writeFiles with ReadableStream or AsyncIterable will buffer in memory before upload
This is due to browser limitations with streaming multipart/form-data bodies
Complete Example
import { ConnectionConfig , Sandbox , SandboxException } from "@alibaba-group/opensandbox" ;
const config = new ConnectionConfig ({
domain: "api.opensandbox.io" ,
apiKey: "your-api-key" ,
});
try {
const sandbox = await Sandbox . create ({
connectionConfig: config ,
image: "python:3.11" ,
timeoutSeconds: 30 * 60 ,
});
// Write a file
await sandbox . files . writeFiles ([
{ path: "/tmp/script.py" , data: "print('Hello World')" , mode: 644 },
]);
// Execute command with streaming
const handlers = {
onStdout : ( m ) => console . log ( "Output:" , m . text ),
};
await sandbox . commands . run ( "python /tmp/script.py" , undefined , handlers );
// Get info
const info = await sandbox . getInfo ();
console . log ( "State:" , info . status . state );
// Cleanup
await sandbox . kill ();
await sandbox . close ();
} catch ( err ) {
if ( err instanceof SandboxException ) {
console . error ( `Sandbox Error: [ ${ err . error . code } ] ${ err . error . message ?? "" } ` );
} else {
console . error ( err );
}
}