Sandboxed Execution

medium10 minsandbox-execution.ts

You need to run commands with limits — memory, CPU, no network, a timeout — in Docker when it is available.

What it shows

  • Run a command with NativeSandboxExecutor
  • Use SandboxManager with resource defaults and fall back from Docker to native
  • Kill long runs with a timeout

The code

sandbox-execution.ts
import { NativeSandboxExecutor, SandboxManager } from '@cogitator-ai/sandbox';

const native = new NativeSandboxExecutor();
await native.connect();
const hello = await native.execute(
  { command: ['echo', 'Hello from the native sandbox'] },
  { type: 'native', timeout: 5000 }
);
if (hello.success) console.log(hello.data.stdout.trim());

const manager = new SandboxManager({
  defaults: {
    timeout: 10_000,
    resources: { memory: '256MB', cpus: 0.5 },
    network: { mode: 'none' },
  },
  pool: { maxSize: 3, idleTimeoutMs: 30_000 },
});
await manager.initialize();

const dockerAvailable = await manager.isDockerAvailable();
console.log('Docker available:', dockerAvailable);

const result = await manager.execute(
  { command: ['node', '-e', 'console.log(JSON.stringify({ sum: 2 + 2 }))'] },
  { type: dockerAvailable ? 'docker' : 'native', image: 'node:20-alpine' }
);
console.log(result.success ? result.data.stdout.trim() : result.error);

const slow = await manager.execute({ command: ['sleep', '30'], timeout: 500 }, { type: 'native' });
if (slow.success) console.log('timed out:', slow.data.timedOut);

await manager.shutdown();

Run it

install · bash
pnpm add @cogitator-ai/sandbox
run · bash
npx tsx sandbox-execution.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/infrastructure/05-sandbox-execution.ts

Learn more