Skip to main content

Installation

npm install @alibaba-group/opensandbox

Quick Start

import { ConnectionConfig, Sandbox, SandboxException } from "@alibaba-group/opensandbox";

const config = new ConnectionConfig({
  domain: "api.opensandbox.io",
  apiKey: "your-api-key",
  // protocol: "https",
  // requestTimeoutSeconds: 60,
});

try {
  const sandbox = await Sandbox.create({
    connectionConfig: config,
    image: "ubuntu",
    timeoutSeconds: 10 * 60,
  });

  const execution = await sandbox.commands.run("echo 'Hello Sandbox!'");
  console.log(execution.logs.stdout[0]?.text);

  // Optional but recommended: terminate the remote instance when you are done.
  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);
  }
}

Core Features

Lifecycle Management

Manage the sandbox lifecycle, including renewal, pausing, and resuming.
const info = await sandbox.getInfo();
console.log("State:", info.status.state);
console.log("Created:", info.createdAt);
console.log("Expires:", info.expiresAt);

await sandbox.pause();

// Resume returns a fresh, connected Sandbox instance.
const resumed = await sandbox.resume();

// Renew: expiresAt = now + timeoutSeconds
await resumed.renew(30 * 60);

Custom Health Check

Define custom logic to determine whether the sandbox is ready/healthy. This overrides the default ping check used during readiness checks.
const sandbox = await Sandbox.create({
  connectionConfig: config,
  image: "nginx:latest",
  healthCheck: async (sbx) => {
    // Example: consider the sandbox healthy when port 80 endpoint becomes available
    const ep = await sbx.getEndpoint(80);
    return !!ep.endpoint;
  },
});

Command Execution & Streaming

Execute commands and handle output streams in real-time.
import type { ExecutionHandlers } from "@alibaba-group/opensandbox";

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

File Operations

Manage files and directories, including read, write, list/search, and delete.
await sandbox.files.createDirectories([{ path: "/tmp/demo", mode: 755 }]);

await sandbox.files.writeFiles([
  { path: "/tmp/demo/hello.txt", data: "Hello World", mode: 644 },
]);

const content = await sandbox.files.readFile("/tmp/demo/hello.txt");
console.log("Content:", content);

const files = await sandbox.files.search({
  path: "/tmp/demo",
  pattern: "*.txt",
});
console.log(files.map((f) => f.path));

await sandbox.files.deleteDirectories(["/tmp/demo"]);

Endpoints

getEndpoint() returns an endpoint without a scheme (for example "localhost:44772"). Use getEndpointUrl() if you want a ready-to-use absolute URL (for example "http://localhost:44772").
const { endpoint } = await sandbox.getEndpoint(44772);
const url = await sandbox.getEndpointUrl(44772);

Sandbox Management (Admin)

Use SandboxManager for administrative tasks and finding existing sandboxes.
import { SandboxManager } from "@alibaba-group/opensandbox";

const manager = SandboxManager.create({ connectionConfig: config });
const list = await manager.listSandboxInfos({
  states: ["Running"],
  pageSize: 10,
});
console.log(list.items.map((s) => s.id));
await manager.close();

Configuration

Connection Configuration

The ConnectionConfig class manages API server connection settings. Runtime notes:
  • In browsers, the SDK uses the global fetch implementation.
  • In Node.js, every Sandbox and SandboxManager clones the base ConnectionConfig via withTransportIfMissing(), so each instance gets an isolated undici keep-alive pool. Call sandbox.close() or manager.close() when you are done so the SDK can release the associated agent.
ParameterDescriptionDefaultEnvironment Variable
apiKeyAPI key for authenticationOptionalOPEN_SANDBOX_API_KEY
domainSandbox service domain (host[:port])localhost:8080OPEN_SANDBOX_DOMAIN
protocolHTTP protocol (http/https)http-
requestTimeoutSecondsRequest timeout applied to SDK HTTP calls30-
debugEnable basic HTTP debug loggingfalse-
headersExtra headers applied to every request{}-
useServerProxyUse sandbox server as proxy for execd/endpoint requestsfalse-
import { ConnectionConfig } from "@alibaba-group/opensandbox";

const config = new ConnectionConfig({
  domain: "api.opensandbox.io",
  apiKey: "your-key",
  requestTimeoutSeconds: 60,
});

Sandbox Creation Configuration

Sandbox.create() allows configuring the sandbox environment.
ParameterDescriptionDefault
imageDocker image to useRequired
timeoutSecondsAutomatic termination timeout (server-side TTL)10 minutes
entrypointContainer entrypoint command["tail","-f","/dev/null"]
resourceCPU and memory limits (string map){"cpu":"1","memory":"2Gi"}
envEnvironment variables{}
metadataCustom metadata tags{}
networkPolicyOptional outbound network policy (egress)-
extensionsExtra server-defined fields{}
skipHealthCheckSkip readiness checks (Running + health check)false
healthCheckCustom readiness check-
readyTimeoutSecondsMax time to wait for readiness30 seconds
healthCheckPollingIntervalPoll interval while waiting (milliseconds)200 ms
const sandbox = await Sandbox.create({
  connectionConfig: config,
  image: "python:3.11",
  networkPolicy: {
    defaultAction: "deny",
    egress: [{ action: "allow", target: "pypi.org" }],
  },
});

Resource Cleanup

Both Sandbox and SandboxManager own a scoped HTTP agent when running on Node.js so you can safely reuse the same ConnectionConfig. Once you are finished interacting with the sandbox or administration APIs, call sandbox.close() / manager.close() to release the underlying agent.
const sandbox = await Sandbox.create({ ... });
// ... use sandbox ...
await sandbox.close();

Browser Notes

  • The SDK can run in browsers, but streaming file uploads are Node-only.
  • If you pass ReadableStream or AsyncIterable for writeFiles, the browser will fall back to buffering in memory before upload.
  • Reason: browsers do not support streaming multipart/form-data bodies with custom boundaries (required by the execd upload API).

API Reference

Sandbox

Main class for interacting with sandboxes.

Methods

create
static method
Creates and initializes a new sandbox instance.Parameters:
  • connectionConfig (ConnectionConfig): Connection configuration
  • image (string): Docker image to use
  • timeoutSeconds (number, optional): Sandbox lifetime in seconds
  • entrypoint (string[], optional): Custom entrypoint
  • resource (object, optional): CPU/memory limits
  • env (object, optional): Environment variables
  • metadata (object, optional): Custom metadata
  • networkPolicy (NetworkPolicy, optional): Network egress rules
  • healthCheck (function, optional): Custom health check function
  • readyTimeoutSeconds (number, optional): Readiness timeout
Returns: Promise<Sandbox>
commands
property
Access to command execution operations.Returns: CommandsClient
files
property
Access to file system operations.Returns: FilesClient
renew
method
Extends the sandbox expiration time.Parameters:
  • timeoutSeconds (number): Extension duration in seconds
Returns: Promise<void>
pause
method
Pauses the sandbox (suspends all processes).Returns: Promise<void>
resume
method
Resumes this paused sandbox.Returns: Promise<Sandbox>
kill
method
Terminates the sandbox immediately.Returns: Promise<void>
getInfo
method
Retrieves current sandbox information.Returns: Promise<SandboxInfo>
getEndpoint
method
Gets the external endpoint for a port (without scheme).Parameters:
  • port (number): Internal port number
Returns: Promise<SandboxEndpoint>
getEndpointUrl
method
Gets the full URL for a port (with scheme).Parameters:
  • port (number): Internal port number
Returns: Promise<string>
close
method
Releases the underlying HTTP agent (Node.js only).Returns: Promise<void>

Examples

Running a Node.js Script

await sandbox.files.writeFiles([
  {
    path: "/app/script.js",
    data: `
console.log('Node version:', process.version);
console.log('Hello from OpenSandbox!');
    `,
    mode: 755,
  },
]);

const execution = await sandbox.commands.run("node /app/script.js");
execution.logs.stdout.forEach((line) => console.log(line.text));

Network Policy Example

const sandbox = await Sandbox.create({
  connectionConfig: config,
  image: "node:20",
  networkPolicy: {
    defaultAction: "deny",
    egress: [
      { action: "allow", target: "npmjs.org" },
      { action: "allow", target: "registry.npmjs.org" },
    ],
  },
});

Port Forwarding

// Start a web server in the sandbox
await sandbox.commands.run(
  "node -e 'require(\"http\").createServer((req,res)=>res.end(\"Hello\")).listen(8000)'",
  { background: true },
);

// Get the external URL
const url = await sandbox.getEndpointUrl(8000);
console.log(`Access your server at: ${url}`);

Error Handling

import { SandboxException } from "@alibaba-group/opensandbox";

try {
  const sandbox = await Sandbox.create({
    connectionConfig: config,
    image: "ubuntu",
  });
  const execution = await sandbox.commands.run("ls -la");
} catch (err) {
  if (err instanceof SandboxException) {
    console.error(`Error [${err.error.code}]: ${err.error.message}`);
  } else {
    throw err;
  }
}

TypeScript Support

The SDK is written in TypeScript and provides full type definitions.
import type {
  Sandbox,
  SandboxInfo,
  Execution,
  ExecutionHandlers,
  WriteEntry,
  SearchEntry,
  NetworkPolicy,
} from "@alibaba-group/opensandbox";

Next Steps

Python SDK

Explore the Python SDK

API Reference

Detailed API documentation

Examples

Browse more code examples

Configuration

Advanced configuration options

Build docs developers (and LLMs) love