> ## Documentation Index
> Fetch the complete documentation index at: https://docs.boxd.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent swarm intelligence

> Fan a problem out to many agents, each on its own machine, and synthesize one answer.

A swarm splits a problem across many worker agents and merges their findings into one answer. On boxd, each worker gets a full machine of its own, with Claude Code, Codex, and OpenCode already installed and logged in, so a worker is one `exec` away from doing real work. Machines boot in about 30ms and cost near zero when idle, which makes spawning a machine per worker feel like calling a function.

<Frame caption="Three scouts research in parallel, one machine each, then a lead agent reads all three reports and writes the recommendation.">
  <video autoPlay muted loop playsInline src="https://mintcdn.com/azin/psRZbQh2QwMUVL3U/videos/agent-swarm.mp4?fit=max&auto=format&n=psRZbQh2QwMUVL3U&q=85&s=bf4fb6d89613ca5288a4b1bd739abbd5" data-path="videos/agent-swarm.mp4" />
</Frame>

## How it works

1. The coordinator (your script, or an agent on a boxd machine) defines the sub-tasks.
2. It creates one machine per worker, fresh or [forked](/guides/fork) from a warm baseline.
3. Each worker runs a coding agent headless inside its machine, and the output comes back through `exec`.
4. A lead step reads every report and writes the synthesis.
5. Workers are destroyed, and the fleet goes back to zero.

## Full example

Three scouts research the same question through different lenses, then a lead agent reads all three reports and produces one recommendation:

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":"github-dark"}
    from concurrent.futures import ThreadPoolExecutor
    from boxd import Boxd

    LENSES = {
        "market": "Size the market for on-device speech models. Write a compact report.",
        "tech":   "Survey the strongest open-source on-device speech models. Write a compact report.",
        "risks":  "List the main risks of betting on on-device speech models. Write a compact report.",
    }

    boxd = Boxd()   # reads BOXD_API_KEY; authenticates automatically inside a VM

    def scout(name: str, prompt: str) -> str:
        machine = boxd.machines.create(name)
        boxd.machines.wait_until_ready(machine.id)
        result = boxd.machines.exec(
            machine.id,
            f'claude -p "{prompt}" --dangerously-skip-permissions',
            timeout=600,
        )
        boxd.machines.delete(machine.id)
        return result.stdout

    with ThreadPoolExecutor() as pool:
        reports = list(pool.map(
            lambda kv: scout(f"scout-{kv[0]}", kv[1]), LENSES.items()
        ))

    # Lead agent: one more machine reads every report and merges them
    lead = boxd.machines.create("lead")
    boxd.machines.wait_until_ready(lead.id)
    boxd.machines.files.upload(lead.id, "/home/boxd/reports.md", "\n\n---\n\n".join(reports))
    final = boxd.machines.exec(
        lead.id,
        'claude -p "Read /home/boxd/reports.md and write one recommendation." '
        "--dangerously-skip-permissions",
        timeout=600,
    )
    print(final.stdout)
    boxd.machines.delete(lead.id)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={"theme":"github-dark"}
    import { Boxd } from "@boxd-sh/sdk";

    const LENSES: Record<string, string> = {
      market: "Size the market for on-device speech models. Write a compact report.",
      tech:   "Survey the strongest open-source on-device speech models. Write a compact report.",
      risks:  "List the main risks of betting on on-device speech models. Write a compact report.",
    };

    const boxd = new Boxd();   // reads BOXD_API_KEY; authenticates automatically inside a VM

    async function scout(name: string, prompt: string): Promise<string> {
      const machine = await boxd.machines.create({ name });
      await boxd.machines.waitUntilReady(machine.id);
      const result = await boxd.machines.exec(machine.id, {
        command: `claude -p "${prompt}" --dangerously-skip-permissions`,
        timeout: 600_000,
      });
      await boxd.machines.delete(machine.id);
      return result.stdout;
    }

    const reports = await Promise.all(
      Object.entries(LENSES).map(([lens, prompt]) => scout(`scout-${lens}`, prompt))
    );

    // Lead agent: one more machine reads every report and merges them
    const lead = await boxd.machines.create({ name: "lead" });
    await boxd.machines.waitUntilReady(lead.id);
    await boxd.machines.files.upload(lead.id, "/home/boxd/reports.md", reports.join("\n\n---\n\n"));
    const final = await boxd.machines.exec(lead.id, {
      command: `claude -p "Read /home/boxd/reports.md and write one recommendation." --dangerously-skip-permissions`,
      timeout: 600_000,
    });
    console.log(final.stdout);
    await boxd.machines.delete(lead.id);
    await boxd.close();
    ```
  </Tab>
</Tabs>

The workers need nothing installed first, because the agents ship in the image and Claude Code is already logged in on every machine you own. See [Coding agents](/use-cases/coding-agents).

| Stage      | What happens                                           |
| ---------- | ------------------------------------------------------ |
| Fan out    | The coordinator creates one machine per lens           |
| Work       | A coding agent runs headless inside each worker        |
| Collect    | Each report comes back as the `exec` result            |
| Synthesize | A lead machine reads all reports and writes one answer |
| Teardown   | Workers are destroyed, and the fleet is gone           |

## Share state over the private network

Workers can do more than report back at the end. Inside any of your machines, `<vmname>.boxd` resolves to that machine's private IP, so a swarm can share a queue, a database, or a scoreboard by running it on one machine and letting the others connect by name:

```bash theme={"theme":"github-dark"}
curl http://coordinator.boxd:8000/next-task
psql -h shared-db.boxd -U postgres
```

Name resolution is private to your account, and only machines you own resolve. See [VM to VM](/guides/vm-to-vm).

## Let the swarm run itself

The coordinator can be a machine too. Every boxd VM carries the in-VM `boxd` CLI and the SDKs, pre-authenticated as your account, so an agent inside one machine can spawn siblings, hand them work, and clean up. The example above runs unchanged on a boxd machine, where `Boxd()` needs neither a key nor configuration.

## Production tips

### Warm-start workers with a fork

A fresh machine is generic, and a worker that needs your repo, dependencies, or a loaded model should start from a prepared baseline instead. Set the baseline up once, then `boxd.machines.fork("baseline", name)` per worker. Each fork lands in about 160ms with the baseline's disk and memory intact. For a baseline that outlives the machine and stays versioned, use a [golden image](/guides/golden-image), and for identical starting states at scale see [Reproducible RL environments](/use-cases/reproducible-rl-environments).

### Keep workers apart

Independent attempts should stay independent, and workers running generated code shouldn't reach their siblings. [Networks](/guides/vm-to-vm#tag-based-networks) partition the swarm, and each worker then reaches the coordinator and nothing else:

```bash theme={"theme":"github-dark"}
boxd machine new coordinator --networks=job-1,job-2,job-3
boxd machine new worker-1 --networks=job-1
boxd machine new worker-2 --networks=job-2
boxd machine new worker-3 --networks=job-3
```

For untrusted work, create workers with `--isolated` and they reach nothing of yours beyond networks you grant explicitly. See [Sandboxes](/use-cases/sandboxes).

### Mind the cost and the cap

Destroy workers when their task ends, since a removed machine costs nothing. Workers you keep for the next batch [suspend and hibernate](/guides/suspend-resume) on their own and wake on the next request. Accounts start at 50 concurrent machines, extendable on request, and the coordinator counts too. See [Resources and limits](/guides/resources).
