|
| 1 | +# Swarms — agent fan-out and orchestration in code mode |
| 2 | + |
| 3 | +Status: implementation spec (v1 in progress). This document is the frozen build |
| 4 | +spec. It will be rewritten as user-facing docs (`docs/tools/swarm.md`) once the |
| 5 | +feature lands and is tested. Feature-gated behind `tools.swarm` (default off); |
| 6 | +`main` remains shippable at every point. |
| 7 | + |
| 8 | +## 1. What and why |
| 9 | + |
| 10 | +A **swarm** is many subagents orchestrated deterministically from a code-mode |
| 11 | +script: fan out N readers, verify findings adversarially, synthesize through a |
| 12 | +stateful prioritizer, loop on decision gates. Control flow (`Promise.all`, |
| 13 | +`while`, `if`) _is_ the orchestration — there is deliberately **no graph DSL, |
| 14 | +no new mode, no new top-level tool surface**. |
| 15 | + |
| 16 | +OpenClaw code mode (QuickJS-WASI, snapshot/resume, bridge requests) is the |
| 17 | +substrate. A parked bridge call survives VM snapshot, gateway restart, and |
| 18 | +resumes exactly where it stopped — stronger than journal-replay designs, with |
| 19 | +no determinism constraints on scripts. |
| 20 | + |
| 21 | +Naming: product/docs name is **Swarm**. Code identifiers stay literal: |
| 22 | +`agents.*` guest API, `tools.swarm` config, `swarm` group columns. |
| 23 | + |
| 24 | +## 2. Decisions (maintainer, 2026-07-17) |
| 25 | + |
| 26 | +- Cost: enforced config caps; per-swarm token budget optional. No mandatory budget. |
| 27 | +- Approvals: children run **fail-closed / non-interactive**. Approval-requiring |
| 28 | + actions are denied; the denial is reported in the child result; the script |
| 29 | + decides. No operator prompt spam from fan-out. |
| 30 | +- v1 is model-written ad-hoc scripts only. Saved/named workflows, CLI/cron |
| 31 | + entry: later (headless code mode already exists for cron). |
| 32 | +- Child identity: dedicated worker agent by default via `tools.swarm.defaultAgentId` |
| 33 | + config (validated against existing subagent target allowlist); per-spawn |
| 34 | + `agentId` override. Core ships no bundled agent id; docs recommend a lean |
| 35 | + `worker` agent config. |
| 36 | +- No Codex source changes. Codex harness uses the spawn/wait idiom (§8). |
| 37 | + |
| 38 | +## 3. Architecture overview |
| 39 | + |
| 40 | +``` |
| 41 | +code-mode script (QuickJS VM, gateway) Codex V8 script (codex process) |
| 42 | + agents.run(...) ── parked bridge call tools.sessions_spawn / tools.agents_wait |
| 43 | + │ │ item/tool/call RPC (≤600s each) |
| 44 | + ▼ ▼ |
| 45 | + CORE (harness-agnostic, this repo) |
| 46 | + sessions_spawn {collect:true, outputSchema, fastMode, groupId} |
| 47 | + agents_wait {ids, timeoutSeconds} |
| 48 | + │ |
| 49 | + subagent registry (SQLite): collector completion records, swarm group id |
| 50 | + │ |
| 51 | + children = ordinary subagent sessions (lane-capped, fail-closed approvals) |
| 52 | + │ |
| 53 | + sessions.changed SSE ──► Control UI dots / sidebar / channel status message |
| 54 | +``` |
| 55 | + |
| 56 | +One canonical owner of spawn/complete/settle semantics (core tools + registry). |
| 57 | +Two await transports: QuickJS parks a bridge call indefinitely (snapshot); |
| 58 | +Codex polls `agents_wait` in bounded RPCs. |
| 59 | + |
| 60 | +## 4. Config gate (v1) |
| 61 | + |
| 62 | +New `tools.swarm` (global + per-agent override, same merge pattern as |
| 63 | +`tools.codeMode`): |
| 64 | + |
| 65 | +```jsonc |
| 66 | +"tools": { |
| 67 | + "swarm": { |
| 68 | + "enabled": false, // master gate, default OFF |
| 69 | + "maxConcurrent": 8, // children running at once (swarm lane cap) |
| 70 | + "maxChildrenPerGroup": 50, // live children per swarm group |
| 71 | + "maxTotalPerGroup": 200, // lifetime spawn count per group (runaway backstop) |
| 72 | + "waitTimeoutSecondsMax": 600, |
| 73 | + "defaultAgentId": "" // optional; child agent id when spawn omits agentId |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
| 77 | + |
| 78 | +- Zod: union `boolean | strict object` like `CodeModeSchema` |
| 79 | + (`src/config/zod-schema.agent-runtime.ts`); `swarm: true` → `{enabled: true}`. |
| 80 | +- Types in `src/config/types.tools.ts` (both per-agent and top-level `tools`), |
| 81 | + labels in `schema.labels.ts`, help in `schema.help.runtime.ts`. |
| 82 | +- Resolution helper `resolveSwarmConfig(cfg, agentId)` mirroring |
| 83 | + `resolveCodeModeConfig` (`src/agents/code-mode.ts:215`), clamping all numbers. |
| 84 | +- Gate effects when disabled: `agents_wait` tool absent from catalogs; |
| 85 | + `collect`/`outputSchema`/`fastMode`/`groupId` params on `sessions_spawn` |
| 86 | + rejected with a clear error naming the config key. No other behavior change. |
| 87 | +- `defaultAgentId` is validated through `resolveSubagentAllowedTargetIds` |
| 88 | + (`src/agents/subagent-target-policy.ts`); unknown id → spawn error, not fallback. |
| 89 | + |
| 90 | +## 5. Core: collector-mode spawn + `agents_wait` (v1) |
| 91 | + |
| 92 | +### 5.1 `sessions_spawn` additions (all gated on swarm enabled) |
| 93 | + |
| 94 | +- `collect: boolean` — when true, the child run is registered with |
| 95 | + `expectsCompletionMessage: false` and a **collector completion record** |
| 96 | + instead of announce/steering delivery. Tool returns `{ runId, sessionKey }` |
| 97 | + immediately. No channel/thread binding. |
| 98 | +- `outputSchema: object` — JSON Schema. Child gets a synthetic |
| 99 | + `structured_output` tool appended to its tool surface; system-prompt addendum |
| 100 | + instructs it to call it exactly once with its final result. On validation |
| 101 | + failure the child gets one nudge retry; after that the completion record |
| 102 | + carries `structured: undefined` plus the raw text and a `schemaError`. |
| 103 | +- `fastMode: true | "auto" | false` — threaded into the child session patch |
| 104 | + alongside model/thinking via `resolveSubagentModelAndThinkingPlan` |
| 105 | + (`src/agents/subagent-spawn-plan.ts`), using the existing `FastMode` axis |
| 106 | + (`src/shared/fast-mode.ts`). Omitted = inherit. |
| 107 | +- `groupId: string` — swarm group stamp. Defaults to |
| 108 | + `swarm:<requesterSessionKey>:<runId-of-requesting-run>`. Persisted on the |
| 109 | + registry record and the child session row. Used for caps, listing, batch |
| 110 | + archive, and the dots. |
| 111 | +- `label: string` already exists — surfaces in dots and `subagents list`. |
| 112 | +- Child agent id: `params.agentId` → else `tools.swarm.defaultAgentId` → else |
| 113 | + requester agent (existing behavior). |
| 114 | + |
| 115 | +### 5.2 Approvals fail-closed |
| 116 | + |
| 117 | +Collector children run with a non-interactive approval context: any tool call |
| 118 | +that would require operator approval resolves as a structured denial |
| 119 | +(`approval_required`) visible to the child, which is expected to report the |
| 120 | +blockage in its result. Implementation: reuse the existing exec/tool approval |
| 121 | +policy plumbing with a forced `deny` resolver for collector-mode child runs. |
| 122 | +No approval events are emitted to operator surfaces from collector children. |
| 123 | + |
| 124 | +### 5.3 `agents_wait` tool (new, gated) |
| 125 | + |
| 126 | +``` |
| 127 | +agents_wait({ ids: string[], timeoutSeconds?: number }) |
| 128 | +→ { |
| 129 | + completed: [{ runId, status: "done"|"failed"|"killed"|"timeout", |
| 130 | + result: string, structured?: unknown, schemaError?: string, |
| 131 | + sessionKey, label?, usage?: {inputTokens, outputTokens} }], |
| 132 | + pending: string[] |
| 133 | + } |
| 134 | +``` |
| 135 | + |
| 136 | +- Returns as soon as **at least one** id completes (first-completion / race |
| 137 | + semantics, enables pipelines), or on timeout with `completed: []`. |
| 138 | +- `timeoutSeconds` default 30, clamped to `waitTimeoutSecondsMax`. |
| 139 | +- Idempotent: already-completed ids return their records again (records are |
| 140 | + kept until group archive). Unknown id → per-id error entry, not a throw. |
| 141 | +- Ownership: only the session that spawned a run (or its parent chain) may wait |
| 142 | + on it — same ownership rule as `wait` in code mode (`code-mode.ts:1684`). |
| 143 | +- Registry: completion records live in the existing subagent registry SQLite |
| 144 | + store (`subagent-registry.store.sqlite.ts`) — new fields, no new store, no |
| 145 | + schema-version bump (additive columns only; see §9 constraint). |
| 146 | + |
| 147 | +### 5.4 Caps enforcement |
| 148 | + |
| 149 | +- `maxConcurrent`: collector children run on the existing subagent lane but |
| 150 | + counted per swarm group; spawns beyond the cap queue FIFO (host-side, in the |
| 151 | + spawn path — return runId immediately, run starts when a slot frees). |
| 152 | +- `maxChildrenPerGroup` / `maxTotalPerGroup`: spawn rejects with a typed error |
| 153 | + once exceeded; the error text names the config key. |
| 154 | +- Depth: collector children keep `DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH` semantics |
| 155 | + (children are leaves unless nesting explicitly configured). |
| 156 | + |
| 157 | +## 6. Testing contract (v1, lane A) |
| 158 | + |
| 159 | +- Unit: config resolution/clamping; gate rejections when disabled; groupId |
| 160 | + defaulting; cap enforcement (queue + reject); wait race semantics; wait |
| 161 | + idempotency; ownership denial; structured-output validation + nudge retry + |
| 162 | + schemaError path; fastMode plumbing into session patch; defaultAgentId |
| 163 | + validation. |
| 164 | +- Integration (vitest, mock model runtime): spawn 3 collector children, wait |
| 165 | + in a loop, assert first-completion ordering and final drain; gateway-restart |
| 166 | + simulation: registry reload → wait resolves from persisted completion. |
| 167 | +- All tests colocated `*.test.ts`; no live model calls. |
| 168 | + |
| 169 | +## 7. QuickJS guest surface (lane B, after core) |
| 170 | + |
| 171 | +- Guest globals installed in `CONTROLLER_SOURCE` |
| 172 | + (`src/agents/code-mode.worker.ts:190-374`), reserved names added in |
| 173 | + `code-mode-namespaces.ts`: |
| 174 | + - `agents.run(prompt, opts) → Promise<result|structured>` — sugar: |
| 175 | + collector spawn + parked await on a dedicated bridge method (`agentWait`) |
| 176 | + that the host settles on completion (no polling; snapshot-safe). |
| 177 | + - `agents.session(system, opts) → Promise<handle>`; |
| 178 | + `handle.send(input, opts) → Promise<...>`; `handle.close()`. (v1.1 — |
| 179 | + ships after run(); uses `mode:"session"` + per-turn collector records.) |
| 180 | + - `phase(title)`, `log(message)` — fire-and-forget bridge notifications → |
| 181 | + swarm progress events. |
| 182 | +- Bridge methods added to `CodeModeBridgeMethod` (`code-mode.ts:91`): |
| 183 | + `agentSpawn`, `agentWait`, `swarmNote`. `agentSpawn`/`agentWait` are |
| 184 | + replay-safe **by construction**: idempotency key `(codeModeRunId, bridgeId)` |
| 185 | + stored on the registry record; restart re-settles from persisted completions |
| 186 | + and never double-spawns. |
| 187 | +- Pending `agentWait` bridge calls extend the run's snapshot TTL (pending |
| 188 | + agent set is the signal; no flag). |
| 189 | +- `API.read("agents.d.ts")` virtual file documents the typed surface + the |
| 190 | + fan-out / gate / cycle idioms (`createCodeModeApiVirtualFiles`, |
| 191 | + `code-mode-namespaces.ts:876`). |
| 192 | + |
| 193 | +## 8. Codex harness projection (later lane) |
| 194 | + |
| 195 | +- `sessions_spawn` (with new params) and `agents_wait` flow through the |
| 196 | + existing dynamic-tool bridge; inside Codex code-mode scripts they appear as |
| 197 | + `tools.*` automatically (verified: `codex-rs/code-mode/src/runtime/globals.rs:14-65`, |
| 198 | + `codex-rs/core/src/tools/spec_plan.rs:448-507`). |
| 199 | +- `agents_wait` gets the long dynamic-tool timeout class (600s cap; |
| 200 | + `extensions/codex/src/app-server/dynamic-tool-execution.ts:37-39`) and is |
| 201 | + marked timeout/replay-safe. |
| 202 | +- Group key for Codex parents: `swarm:<parentSessionKey>:<turnId>`. |
| 203 | +- Codex-native `spawn_agent` subagents coexist; their task-mirror rows feed |
| 204 | + the same progress surface. |
| 205 | + |
| 206 | +## 9. Persistence and retention |
| 207 | + |
| 208 | +- No new stores. Registry records extend the existing subagent registry |
| 209 | + SQLite tables; children are ordinary `sessions` rows. Additive columns only |
| 210 | + — **any change requiring a SQLite schema-version bump needs explicit |
| 211 | + maintainer sign-off first** (repo policy). |
| 212 | +- Swarm group id on registry record + child session metadata. |
| 213 | +- Retention: completed collector records survive until **group archive**: |
| 214 | + when the parent run finishes (or TTL expires), the group's children archive |
| 215 | + as a batch (extend the existing `DEFAULT_SUBAGENT_ARCHIVE_AFTER_MINUTES` |
| 216 | + sweep to operate per group). |
| 217 | + |
| 218 | +## 10. Progress surface ("the dots") — later lane |
| 219 | + |
| 220 | +- Implicit, harness-driven. Derived from existing `sessions.changed` SSE + |
| 221 | + registry; `phase`/`log` notes add semantics. No agent-driven rendering. |
| 222 | +- Control UI: `swarm` renderer in the workspace widget family |
| 223 | + (`ui/src/lib/workspace/widgets/`) — dot grid grouped by phase, narrator |
| 224 | + line, per-dot status/label/model; sidebar child-tree unchanged. |
| 225 | +- Channels: one throttled edited status message per group (follow |
| 226 | + `docs/concepts/streaming.md`; never per-child messages). |
| 227 | + |
| 228 | +## 11. Labs page (Control UI, independent lane) |
| 229 | + |
| 230 | +Settings → **Labs**: experimental feature toggles, first entries **Code Mode** |
| 231 | +and **Swarm**. Each row: name, one-line description, docs link, toggle wired |
| 232 | +via the existing `config.patch` RPC (RFC 7396 merge-patch — set |
| 233 | +`tools.codeMode.enabled` / `tools.swarm.enabled`), plus a "restart required" |
| 234 | +hint when applicable. Discoverable, but copy makes the experimental status |
| 235 | +clear. i18n: all strings through the normal `en.ts` + sync pipeline. |
| 236 | + |
| 237 | +## 12. Placement (later) |
| 238 | + |
| 239 | +- `placement` opt on spawn: `"local"` (default) | `"cloud:<profile>"` via |
| 240 | + existing worker-environment dispatch (`sessions.dispatch`); pooled placement |
| 241 | + later if shared-box SSH-sandbox children prove insufficient. |
| 242 | +- Orchestrator VM always stays on the gateway; settle/dots/budget are |
| 243 | + placement-blind. |
| 244 | + |
| 245 | +## 13. Non-goals |
| 246 | + |
| 247 | +- No graph DSL — control flow is the graph (deliberate, documented). |
| 248 | +- No Codex source changes; no reuse of Codex Code Mode internals. |
| 249 | +- No saved/named workflows in v1; no CLI entry point. |
| 250 | +- No per-child operator approval bubbling. |
| 251 | +- No 1:1 cloud provisioning at fan-out scale. |
| 252 | +- No steady-state runtime compat shims; swarm is new surface, gated. |
| 253 | + |
| 254 | +## 14. Build phases / PR slicing |
| 255 | + |
| 256 | +1. **Lane A (core)**: §4 config + §5 spawn/wait/caps/approvals + §6 tests. |
| 257 | +2. **Lane C (Labs page)**: §11 — independent, can land first. |
| 258 | +3. **Lane B (QuickJS surface)**: §7 — after A contracts land. |
| 259 | +4. Dots renderer (§10), Codex projection (§8), `agents.session` (§7 v1.1), |
| 260 | + placement (§12), user docs rewrite — follow-up PRs in that order. |
| 261 | + |
| 262 | +Each PR: green CI, `$autoreview` clean, gated off by default, main shippable. |
0 commit comments