Local Commands in the OS Sandbox

medium10 minos-sandbox.ts

An agent runs shell commands on your machine, and they should not write outside the project, read your keys or reach hosts you did not list.

What it shows

  • Read the sandbox section of .claude/settings.json with loadSandboxPolicy
  • Run a LocalWorkspace under OsSandbox: Seatbelt on macOS, bubblewrap on Linux
  • Read what the sandbox refused from result.sandbox.violations
  • Delete into the trash with delete_file and restore

The code

os-sandbox.ts
import { LocalWorkspace, loadSandboxPolicy, workspaceTools } from '@cogitator-ai/core';
import { OsSandbox } from '@cogitator-ai/sandbox';
import type { WorkspaceExecResult } from '@cogitator-ai/types';

const availability = await OsSandbox.probe();
if (!availability.available) throw new Error(`No OS sandbox here: ${availability.reason}`);

const root = './project';
const { policy } = await loadSandboxPolicy(root);
const sandbox = new OsSandbox({
  policy: policy.enabled ? policy : { network: { allowedDomains: ['registry.npmjs.org'] } },
});
const workspace = new LocalWorkspace({ root, exec: { sandbox } });
await workspace.start();

const [runCommand, deleteFile] = workspaceTools(workspace, {
  tools: ['run_command', 'delete_file'],
});
const context = { agentId: 'demo', runId: 'demo', signal: new AbortController().signal };

for (const command of ['echo ok > ok.txt', 'echo no > ~/escape.txt', 'curl -s https://example.com']) {
  const result = (await runCommand.execute({ command }, context)) as WorkspaceExecResult;
  console.log(command, '->', result.exitCode, result.sandbox?.violations);
}

await deleteFile.execute({ path: 'ok.txt' }, context);
const [entry] = await workspace.listTrash();
await workspace.restoreFromTrash(entry.id);

await workspace.dispose();
await sandbox.dispose();

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/sandbox
Linux only: apt-get install bubblewrap socat
run · bash
npx tsx os-sandbox.ts

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

repository · bash
npx tsx examples/infrastructure/08-os-sandbox.ts

Learn more