# TypeScript SDK Reference

Complete reference documentation for the microsandbox TypeScript SDK.


# Installation

npm install microsandbox

# Quick Start

import { PythonSandbox } from "microsandbox";

async function main() {
  const sb = await PythonSandbox.create({ name: "my-sandbox" });

  try {
    const exec = await sb.run("print('Hello, World!')");
    console.log(await exec.output());
  } finally {
    await sb.stop();
  }
}

main().catch(console.error);

# PythonSandbox

The main class for creating and managing Python execution environments.

constructor(options?: SandboxOptions)
Parameter Type Description
options.serverUrl string URL of the microsandbox server (defaults to MSB_SERVER_URL env var or "http://127.0.0.1:5555")
options.namespace string Namespace for the sandbox (default: "default")
options.name string Sandbox identifier (auto-generated if undefined)
options.apiKey string Authentication key (or set MSB_API_KEY env var)

# Class Methods

Creates and automatically starts a new sandbox instance.

static async create(options?: SandboxOptions): Promise<PythonSandbox>
Parameter Type Description
options.serverUrl string URL of the microsandbox server
options.namespace string Namespace for the sandbox
options.name string Name for the sandbox
options.apiKey string API key for authentication
options.image string Docker image to use
options.memory number Memory limit in MB
options.cpus number CPU cores
options.timeout number Startup timeout in seconds

Returns: A started PythonSandbox instance

const sb = await PythonSandbox.create({ name: "my-sandbox" });
try {
  const exec = await sb.run("print('Hello!')");
  console.log(await exec.output());
} finally {
  await sb.stop();
}

# Instance Methods

Starts the sandbox with optional resource constraints.

async start(
  image?: string,
  memory?: number,
  cpus?: number,
  timeout?: number
): Promise<void>
Parameter Type Description
image string Docker image to use (defaults to language-specific image)
memory number Memory limit in MB (default: 512)
cpus number CPU cores (will be rounded to nearest integer, default: 1.0)
timeout number Startup timeout in seconds (default: 180.0)
const sandbox = new PythonSandbox({ name: "resource-limited" });
await sandbox.start("microsandbox/python", 1024, 2.0);

Stops and cleans up the sandbox.

async stop(): Promise<void>

Executes Python code in the sandbox environment.

async run(code: string, options?: { timeout?: number }): Promise<Execution>
Parameter Type Description
code string Python code to execute
options.timeout number Execution timeout in seconds (optional)

Returns: Execution object with results

const exec = await sb.run("print('Hello, World!')");
console.log(await exec.output());
const code = `
import math
result = math.sqrt(16)
print(f"Square root of 16 is: {result}")
`;
const exec = await sb.run(code);

# Properties

Access to shell command execution interface.

get command(): Command
const result = await sb.command.run("ls", ["-la", "/"]);
console.log(await result.output());

Access to resource monitoring interface.

get metrics(): Metrics
const cpu = await sb.metrics.cpu();
const memory = await sb.metrics.memory();
console.log(`CPU: ${cpu}%, Memory: ${memory} MiB`);

Returns sandbox running status.

get isStarted(): boolean

Returns the sandbox identifier.

get name(): string

Returns the server URL.

get serverUrl(): string

Returns the namespace.

get namespace(): string

Returns the API key.

get apiKey(): string | undefined

# NodeSandbox

JavaScript/Node.js execution environment with identical API to PythonSandbox.

constructor(options?: SandboxOptions)
Parameter Type Description
options.serverUrl string URL of the microsandbox server
options.namespace string Namespace for the sandbox
options.name string Sandbox identifier (auto-generated if undefined)
options.apiKey string Authentication key (or set MSB_API_KEY env var)

All methods are identical to PythonSandbox but execute JavaScript code.

import { NodeSandbox } from "microsandbox";

const sb = await NodeSandbox.create({ name: "js-sandbox" });
try {
  const exec = await sb.run("console.log('Hello from Node.js!');");
  console.log(await exec.output());
} finally {
  await sb.stop();
}

# Execution

Represents the result of code execution from sandbox.run().

# Methods

Returns standard output from execution.

async output(): Promise<string>

Returns standard error from execution.

async error(): Promise<string>

Checks if execution produced errors.

hasError(): boolean

# Properties

Execution status.

get status(): string

Language used for execution.

get language(): string

# CommandExecution

Represents the result of command execution from sandbox.command.run().

# Methods

Returns standard output from command execution.

async output(): Promise<string>

Returns standard error from command execution.

async error(): Promise<string>

# Properties

Command exit code.

get exitCode(): number

True if command was successful (exit code 0).

get success(): boolean

The command that was executed.

get command(): string

Arguments used for the command.

get args(): string[]

# Command

Interface for executing shell commands within sandboxes.

Executes shell commands with arguments.

async run(
  command: string,
  args?: string[],
  timeout?: number
): Promise<CommandExecution>
Parameter Type Description
command string Command to execute
args string[] Command arguments (optional)
timeout number Execution timeout in seconds (optional)

Returns: CommandExecution object with results

const result = await sb.command.run("ls");
const result = await sb.command.run("ls", ["-la", "/tmp"]);
const result = await sb.command.run("sleep", ["10"], 5);
const result = await sb.command.run("ls", ["/nonexistent"]);
if (result.success) {
  console.log("Output:", await result.output());
} else {
  console.log("Error:", await result.error());
  console.log("Exit code:", result.exitCode);
}

# Metrics

Interface for monitoring sandbox resource usage and performance.

# Methods

Current CPU usage percentage.

async cpu(): Promise<number | undefined>

Current memory usage in MiB.

async memory(): Promise<number | undefined>

Current disk usage in bytes.

async disk(): Promise<number | undefined>

Sandbox running status.

async isRunning(): Promise<boolean>

All metrics as a dictionary.

async all(): Promise<any>

Returns: Object with keys: name, namespace, running, cpu_usage, memory_usage, disk_usage

// Individual metrics
const cpu = await sb.metrics.cpu();
const memory = await sb.metrics.memory();
const disk = await sb.metrics.disk();
const running = await sb.metrics.isRunning();

console.log(`CPU: ${cpu !== undefined ? cpu + '%' : 'Not available'}`);
console.log(`Memory: ${memory || 'Not available'} MiB`);
console.log(`Disk: ${disk || 'Not available'} bytes`);
console.log(`Running: ${running}`);

// All metrics at once
const metrics = await sb.metrics.all();
console.log(`All metrics:`, metrics);

# Usage Patterns

# Automatic Cleanup (Recommended)

Manual resource management with proper cleanup.

const sb = await PythonSandbox.create({ name: "my-sandbox" });

try {
  const exec = await sb.run("print('Hello, World!')");
  console.log(await exec.output());
} finally {
  await sb.stop(); // Always cleanup
}

# Manual Lifecycle Management

Manual control over sandbox lifecycle.

const sandbox = new PythonSandbox({ name: "my-sandbox" });

try {
  await sandbox.start(undefined, 1024, 2.0);
  const exec = await sandbox.run("print('Hello, World!')");
  console.log(await exec.output());
} finally {
  await sandbox.stop();
}

# State Persistence

Variables and imports persist between executions.

const sb = await PythonSandbox.create({ name: "stateful" });

try {
  await sb.run("x = 42");
  await sb.run("y = x * 2");
  const exec = await sb.run("print(f'Result: {y}')");
  console.log(await exec.output()); // Output: Result: 84
} finally {
  await sb.stop();
}

# Error Handling

Comprehensive error handling patterns.

const sb = await PythonSandbox.create({ name: "error-handling" });

try {
  const exec = await sb.run("1/0"); // Division by zero
  if (exec.hasError()) {
    console.log("Error occurred:", await exec.error());
  }
} catch (error) {
  console.log("Runtime error:", error);
} finally {
  await sb.stop();
}

# File Operations

Creating and manipulating files within sandboxes.

const sb = await PythonSandbox.create({ name: "files" });

try {
  // Create a file using Python
  await sb.run(`
with open('/tmp/test.txt', 'w') as f:
    f.write('Hello from sandbox!')
  `);

  // Read the file using shell command
  const result = await sb.command.run("cat", ["/tmp/test.txt"]);
  console.log("File content:", await result.output());
} finally {
  await sb.stop();
}

# Configuration

# Environment Variables

Variable Description
MSB_API_KEY API key for authentication
MSB_SERVER_URL Default server URL (overrides default)

# Server Configuration

Default server URL: http://127.0.0.1:5555


# Error Handling

# Best Practices

try {
  const sb = await PythonSandbox.create({ name: "error-test" });

  try {
    const exec = await sb.run("potentially_failing_code()");

    if (exec.hasError()) {
      console.log("Execution error:", await exec.error());
    } else {
      console.log("Success:", await exec.output());
    }
  } finally {
    await sb.stop();
  }
} catch (error) {
  console.log(`SDK error: ${error}`);
}

# Best Practices