Skip to main content
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" },
});
options
object
required
Configuration options for sandbox creation.
return
Promise<Sandbox>
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);
return
Promise<SandboxInfo>
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);
port
number
required
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"
port
number
required
The port number to get the URL for.
return
Promise<string>
Absolute URL with scheme.
renew()
Renew the sandbox expiration time.
await sandbox.renew(30 * 60); // 30 minutes
timeoutSeconds
number
required
Duration in seconds to extend the expiration.
return
Promise<void>
Promise that resolves when renewal is complete.
pause()
Pause the sandbox while preserving its state.
await sandbox.pause();
return
Promise<void>
Promise that resolves when sandbox is paused.
resume()
Resume a previously paused sandbox.
const resumed = await sandbox.resume();
return
Promise<Sandbox>
Fresh, connected Sandbox instance.
kill()
Terminate the remote sandbox instance.
await sandbox.kill();
return
Promise<void>
Promise that resolves when sandbox is terminated.
close()
Close local resources (HTTP agent) associated with the sandbox.
await sandbox.close();
return
Promise<void>
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);
type
Commands
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");
type
Filesystem
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 });
options
object
required
return
SandboxManager
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
object
required
return
Promise<PagedSandboxInfos>
Paged sandbox information matching the filter criteria.
close()
Close local resources associated with the manager.
await manager.close();
return
Promise<void>
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
);
command
string
required
Shell command text to execute.
options
object
handlers
ExecutionHandlers
Optional handlers for streaming events.
return
Promise<Execution>
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);
path
string
required
The absolute or relative path to the file to read.
return
Promise<string>
The file content as a string.

writeFiles()

Write content to files.
await sandbox.files.writeFiles([
  { path: "/tmp/hello.txt", data: "Hello World", mode: 644 },
]);
entries
WriteEntry[]
required
List of write entries specifying files and their content.
return
Promise<void>
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.
return
Promise<void>
Promise that resolves when directories are created.

deleteFiles()

Delete the specified files.
await sandbox.files.deleteFiles(["/tmp/hello.txt"]);
paths
string[]
required
List of file paths to delete.
return
Promise<void>
Promise that resolves when files are deleted.

deleteDirectories()

Delete the specified directories.
await sandbox.files.deleteDirectories(["/tmp/demo"]);
paths
string[]
required
List of directory paths to delete.
return
Promise<void>
Promise that resolves when directories are deleted.
Search for files and directories.
const files = await sandbox.files.search({
  path: "/tmp/demo",
  pattern: "*.txt",
});
console.log(files.map((f) => f.path));
entry
object
required
return
Promise<EntryInfo[]>
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" },
});
options
object
required

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);
  }
}

Build docs developers (and LLMs) love