Skip to content

Fork a sandbox

Forking captures a running sandbox once and immediately starts one or more independent copies. Each copy has its own ID and timeout. Files, processes, and memory initially match the source and diverge after the fork.

mjs
import { Sandbox } from "@abox-dev/sdk";

const sandbox = await Sandbox.create();
const forks = [];

try {
  await sandbox.files.write("/tmp/shared.txt", "state copied to each fork");

  const results = await sandbox.fork({ count: 2 });
  for (const result of results) {
    if (result instanceof Sandbox) {
      forks.push(result);
      console.log(await result.files.read("/tmp/shared.txt"));
    } else {
      console.error(`Fork failed: ${result.message}`);
    }
  }
} finally {
  await Promise.all(forks.map((fork) => fork.kill()));
  await sandbox.kill();
}

The result contains one item per requested copy. A successful item is a connected Sandbox; a failed item is an error. Handle every item so a partial failure does not hide the copies that did start.

The source sandbox is briefly paused while its state is captured. Active streams and external connections must reconnect afterwards. Use snapshots when the captured state should be kept and reused later.