Multi-Agent Orchestration: Subagents, /swarm & Python Workflows
A single coding agent handles most everyday tasks well, but once task scope scales up, the bottlenecks show up fast:
- Context pollution: Scanning the whole repository just to modify two call sites floods the main thread with a dozen
grepoutputs and raw source dumps, making the model progressively forget your original constraints. - Serial latency: Drafting several independent docs or patching unrelated modules one after another leaves obvious parallelism on the table.
- Self-review blind spots: Asking an agent to review code it just wrote in the same context usually rubber-stamps its own reasoning.
- Loop drift: Asking an LLM to make 20–30 repetitive tool calls in natural language burns tokens and quietly drops items halfway through.
I hit every one of these while writing this Antigravity series: polishing a single post works smoothly in one main session, but writing multiple posts in parallel, generating illustrations concurrently, and cross-checking them on a single thread drags throughput down sharply.
Google Antigravity provides three progressive multi-agent orchestration mechanisms tailored to different task scales: Subagents, /swarm, and run_workflow Python dynamic workflows. Rather than replacing one another, they map cleanly to lightweight delegation, multi-role collaboration, and code-driven pipelines.

1. Comparing the Three Multi-Agent Orchestration Patterns
Start with a side-by-side breakdown of where each mechanism sits, how agents communicate, and when to reach for it:
| Dimension | Subagents | /swarm |
run_workflow |
|---|---|---|---|
| Core Tools | define_subagent / invoke_subagent / send_message / manage_subagents |
swarm / post_message / read_board / swarm_wait |
run_workflow (async Python script) |
| Collaboration Model | Main agent dispatches async background runs and wakes on callback | Coordinator + named Workers + Verifiers communicating over a shared message board | Script explicitly controls parallel / pipeline execution and structured data flow |
| Best For | 1–4 cleanly scoped independent subtasks (research, parallel edits to separate files, image generation) | Large tasks split across multiple coding roles with handoffs and adversarial code review | Code-shaped orchestration: discover N targets, fan out, pipeline stages, aggregate JSON |
| Cost & Constraints | Lightweight and flexible; per-task model tiering | Preview & Quota Heavy; message board broadcasts add context overhead | Deterministic, saves orchestration tokens, enforces JSON Schema validation on outputs |
Lightweight Default: Subagents & Built-in Types
Whenever you want to offload 1–4 cleanly bounded subtasks in parallel, Subagents are the fastest entry point. The main agent launches a subagent via invoke_subagent, the subagent executes asynchronously in its own isolated conversation, and the runtime wakes the main agent automatically once it finishes—never write a polling loop; continue other work or end your turn and wait for the callback.
Antigravity ships with three ready-to-use built-in types and lets you register custom session-scoped subagents via define_subagent (with independent toggles for EnableWriteTools, EnableMCPTools, and EnableSubagentTools):
self: Inherits the parent agent’s full toolset, system prompt, and model configuration; ideal for editing separate files in parallel or running independent tasks.research: Runs inside a read-only, network-disabled sandbox built for broad codebase exploration and doc reading—keeping noisy search traces out of the main context and returning only clean findings.image-generator: Generates or edits images from a brief and returns the saved local file paths directly.
Use the Model parameter to match cost and speed to task difficulty across four tiers: inherit (default, uses the parent model), flash_lite, flash, and pro. One easily overlooked habit: if a follow-up builds on an existing subagent’s work, continue that conversation via send_message using its conversationId instead of cold-starting a fresh subagent. Use manage_subagents (list / kill / kill_all) to inspect or clean up finished or stuck subagents.
2. Shared Workspace Isolation: inherit / share / branch
Whether you use Subagents, /swarm, or run_workflow, having multiple agents touch the same repository always comes down to one critical parameter: workspace. It controls the filesystem view each child agent operates in:
| Mode | Underlying Behavior | Best Suited For | Teardown & Cleanup Notes |
|---|---|---|---|
inherit (default) |
Shares the parent agent’s live working directory directly | Read-only research, verifier reviews, or write tasks guaranteed never to touch overlapping files |
No extra directory created; no cleanup needed |
share |
Like git worktree / hg share—an isolated working copy sharing the underlying repo storage |
Multiple writers editing code, building, and running unit tests in parallel | kill permanently deletes this working copy; merge changes before cleanup |
branch |
Full independent repository clone with complete physical isolation | High-risk refactors or experiments that alter repo-wide config or dependency trees | Uses the most disk space; kill also deletes the entire clone |
The engineering rule of thumb is straightforward: keep read-only researchers and reviewers on inherit, and switch to share whenever two or more agents will edit code or run builds concurrently. Running concurrent writers under inherit—even on disjoint source files—routinely collides on package-lock.json, build output directories, or .git/index.lock.
Land changes before killing: Calling kill on a Subagent or Swarm Worker running in share or branch mode permanently deletes its isolated workspace (for Subagents, it also terminates all descendants, preserving only logs and artifacts). Always have writers commit inside their own workspace first, then merge or cherry-pick those commits back into your main workspace (or upload them for code review) before tearing down the worker.
3. /swarm Shared Message Board: Roles, States & Pitfalls
Once a task requires five or more specialized roles with upstream/downstream dependencies and dedicated reviewers guarding quality, routing every message through the main agent via send_message turns into a bottleneck fast.
/swarm (currently marked Preview & Quota Heavy) solves this by putting all Workers onto a shared message board: you talk only to the Coordinator, while Workers hand off work, report bugs, and signal completion directly on the board without the main agent copy-pasting messages between them.
The Coordinator’s Iron Rule: Split, Monitor, Decide—Never Code
When you start /swarm, your current session becomes the Coordinator. The first rule for a Coordinator is absolute: never jump in and write code yourself—nor should you run investigations, builds, tests, or review fixes directly. Delegate all execution to Workers.
The reason is practical: the moment the Coordinator gets bogged down in a long execution task, nobody is watching the message board or responding to the user, and the whole swarm quietly stalls at handoffs. Keep Coordinator turns short—scope tasks cleanly, read board updates, make tradeoff calls, dispatch, and step back.
The Four Core Tools & the “Next-Turn” Gotcha
A Coordinator works with four orchestration tools:
| Tool | Core Actions & Purpose |
|---|---|
swarm |
Manage swarm lifecycle: add, status, models, model, kill, title, channel |
post_message |
Post to the board using @name to assign tasks or trigger peer handoffs |
read_board |
Fetch board history by since sequence number or channel (persisted; since: 0 replays from the start) |
swarm_wait |
Block and sleep until new board messages arrive—zero token cost while sleeping (never poll read_board) |
Watch out for one classic first-timer gotcha: post_message, read_board, and swarm_wait do not appear until the turn after you add your first Worker (i.e., after your first swarm{action:"add"} call). On your setup turn, set the swarm title, add all initial Workers in one go, and end your turn—don’t go looking for the board tools in that same turn.
The Four Worker States: Never Use kill as a Pause Button
Running swarm{action:"status"} shows each Worker’s live state. There are only four:
| State | Meaning & Runtime Behavior | How to Handle |
|---|---|---|
waiting |
Asleep on the message board, consuming zero tokens | Wakes only when mentioned via @name, @<prefix>, or @all; post a message to assign work |
working |
Actively thinking, calling tools, or waiting on a model response | Safe to message ahead; it will read your post when its current turn wraps up |
stopped |
Not currently loaded in memory (e.g., after a service restart) | Mentioning @name on the board revives it automatically—assign work just like waiting |
killed |
Permanently terminated; its share / branch workspace is deleted |
Cannot be revived and the name cannot be reused; add a new Worker to take over unfinished work |
Remember this: waiting is already a free pause. An idle Worker sitting on the board costs nothing. Only call kill when you are completely done with a Worker or it is stuck in a runaway loop.
Six Advanced Habits That Keep Swarms Fast and Safe
Running /swarm smoothly in production usually comes down to six small operational habits that are documented in detail but easy to overlook:
- Reference earlier posts by
#seq, never copy-paste summaries: Every message on the board gets an incrementing#seqID. When assigning review or downstream work, write@verifier check #4 and #6or@parser match the signature in #8instead of paraphrasing previous reports—saving context tokens and preventing telephone-game drift. - Treat
@mentionsas wake-up doorbells, not email CCs: Every extra@wakes another agent and spends a full model turn. For peer handoffs (author <-> verifier), instruct Workers to@only the next peer who needs to act. Reserve@coordinatorfor final delivery (e.g.,@coordinator [done] <summary>) or real blockers that need a decision, and reserve@allstrictly for swarm-wide rules or interface changes. - Introduce Channels past 8 Workers or across domains: Where
swarmsupportschannel, partition domains withswarm{action:"channel", op:"create", channel:"parser", topic:"lexer and parser"}and attach Workers withchannels:["parser"]. Every member joinsmainby default, so Channels only pay off if domain chatter stays inside its own channel (#parser,#ui), keepingmainquiet for cross-domain decisions and final handoffs. Ping another domain via@#parserrather than@all, and archive completed areas withop:"archive". - Inherit warm context with
fork: Newlyadded Workers start cold—they have no access to the main conversation or prior research. When you need to branch an active investigation or replace a Worker that has already mapped out the core codebase, passfork:"<member>"(or"coordinator") so the new Worker starts with that warm context intact. - Switch models in place when quota runs dry—never kill and rebuild: On large runs, a Worker will occasionally hit quota exhaustion (it reports the error and returns to
waitingwithout restarting on its own). Callswarm{action:"models"}to check livequota_remainingandquota_resets, then once the Worker iswaiting, runswarm{action:"model", name:"parser", model:"<new-model>"}(the Coordinator can omitnameor pass"coordinator"to switch itself). The Worker keeps its full conversation history and picks up seamlessly on the new model. - Pair adversarial Verifiers at 1:2–4, and keep them strictly read-only: Assign one
verifierfor every 2–4 authors to inspect diffs, run tests, probe edge cases, and report findings directly to@author. Enforce one hard rule: Verifiers report defects and never edit source files—the instant a reviewer starts editing, it collides with the author on the same files.
When you need a homogeneous pool or sharded batch of Workers in one shot, pass n or a tasks list to swarm{action:"add"} to spawn <name>-1 through <name>-<k> (@<name> addresses the whole group; @<name>-1 addresses an individual). Workers can also add their own helper sub-workers and are responsible for integrating their output and killing them when done.
4. run_workflow Python Dynamic Workflows: Orchestration as Code
Both Subagents and /swarm rely on the LLM deciding whom to call next inside a conversation loop. Some workflows, however, are deterministic control flow at heart: scan 15 changed files, fan out 15 lightweight models to review them against a fixed checklist, filter structured JSON results for high-severity findings, and feed only those into a lead reviewer.
Asking an LLM to issue 15 sequential tool calls in natural language is slow, expensive, and prone to skipping files. Antigravity’s third mechanism is run_workflow: write a short async Python script that expresses orchestration directly in code (requires Python 3.8+ on PATH and supports top-level await).
You can pass code inline via Script, though in practice writing the file to your scratch directory and passing an absolute ScriptPath is much cleaner—tracebacks report exact line numbers, and editing and rerunning takes seconds. External parameters enter through Args as the args dict, and the script defaults to WORKSPACES[0] as its working directory. For fast workflows (such as pure tool fan-outs), set WaitMsBeforeAsync (up to 10000 ms) to collect results in the same turn; longer scripts run asynchronously in the background and notify you on completion.
The 6 Core Primitives & call_tool
Workflow scripts run with 6 built-in orchestration primitives plus direct tool invocation via call_tool:
| Primitive | Behavior & Key Details |
|---|---|
phase(name) |
Starts a named stage; subsequent logs and agent cards are grouped under this phase in the UI |
log(*args) |
Writes to the workflow result’s Logs: section and streams to the UI (print() goes to Output:) |
agent(...) |
Declares a workflow agent (prompt, schema, role, type_name, workspace, model); lazy—nothing executes until awaited or called |
parallel(items, fn) |
Runs fn(item) concurrently and returns results in original input order; if any item fails, all remaining tasks in the batch are cancelled immediately |
pipeline(items, fn) |
Executes fn(item) sequentially and returns results in order |
trajectory(...) |
Reads main-session steps recorded before run_workflow started, filterable by tools, types, last, min_index, and max_index; steps evicted from memory have status CLEARED and output None, requiring fallback to transcript.jsonl / transcript_full.jsonl |
call_tool(name, **args) |
Invokes an available tool directly and returns str; workflows cannot prompt the user for interactive approval, so unapproved or Hook-blocked calls raise ToolError (.denied == True) |
Strict Structured Outputs & Two Calling Modes
What sets run_workflow apart from standard Subagents is contract-enforced return values:
- Every
agent(...)call requires aschema(a JSON Schema dict or string; pass{"type": "string"}for plain text). The workflow sub-agent must explicitly call its built-infinishtool to submit its result, which is validated against the schema before being parsed and returned to Python. If the agent exits without callingfinish, the workflow treats that step as failed. agent(...)supports two distinct calling styles (pick one per object; do not mix both on the same instance):- One-shot call: Run
res = await agent(prompt, schema=...)directly; the agent finishes immediately (awaiting the same object twice executes once and returns the cached result). - Stateful multi-turn: Declare
reviewer = agent("persistent instructions", role="Reviewer"), then invokeawait reviewer(prompt, schema)multiple times sequentially inside the same conversation context; release it explicitly withdel reviewer(all agents are also automatically cleaned up when the workflow exits).
- One-shot call: Run
Production Template: Discover → Fan-Out Review → Stateful Aggregation
Here is a drop-in Python workflow template. It mines recent failed command logs from the main session trajectory, discovers the core changed files, fans out parallel flash reviews with enforced JSON output, and hands high-severity hits to a stateful reviewer for deduplication and prioritized remediation:
1 | import json |

5. Choosing the Right Pattern & 4 Common Pitfalls
If you are unsure which orchestration pattern fits your current task, walk through this decision tree:
flowchart TD
S["Single Agent hits context, latency, or review limits"] --> Q1{"4 or fewer independent tasks?"}
Q1 -->|Yes| A1["invoke_subagent: pick research / self / image-generator"]
Q1 -->|No| Q2{"Can orchestration be written as deterministic code (loops/fan-out/pipelines/JSON aggregation)?"}
Q2 -->|Yes| A2["run_workflow: async Python script + parallel/pipeline + schema"]
Q2 -->|No| A3["/swarm: Coordinator + named Workers (workspace: share) + Verifier"]
A2 --> N2["Set workspace: share for code-writing agents"]
A3 --> N3["Use Channels above 8 workers; switch models in place via action: model when quota runs out"]
Finally, here are the four most expensive pitfalls I run into when orchestrating multiple agents:
Pitfall 1: Launching /swarm for a Single-File Task
/swarm is explicitly labeled Quota Heavy. Beyond each Worker maintaining its own context window, public briefs and main-channel broadcasts are read into every relevant member’s context. If you are only editing one module, drafting one article, or running a targeted investigation, stick to the main agent or spin up 1–2 invoke_subagent calls—don’t bring an entire swarm to a single-file job.
Pitfall 2: Writing Briefs as If the New Agent Read Your Main Session
Whether you use invoke_subagent, swarm add, or agent() inside run_workflow, every newly spawned agent starts completely cold—it has not seen the user’s opening prompt, your earlier findings, or any peer agent’s transcript. A vague brief like “update the parser based on what we just discussed” forces the child agent to guess.
Spelling out three things eliminates most rework: which files it owns, what it must not touch, and what “done” looks like. When you genuinely need to pass down deep accumulated context in /swarm, use fork:"<member>".
Pitfall 3: Treating parallel in run_workflow as a Fault-Tolerant Pool
parallel(items, fn) is strictly fail-fast: if a single sub-agent throws an exception or forgets to call finish, every other in-flight agent in that batch is immediately cancelled, wasting all tokens spent so far. If your workflow can tolerate individual failures and needs partial results, wrap the call in an async def helper with try / except that returns an error sentinel dict, or switch to pipeline for sequential execution.
Pitfall 4: Editing the Same Repo in Parallel Without workspace: "share"
workspace defaults to inherit. The moment two writers edit files, run npm run build, or execute git commands in the same working copy, you get silent last-write-wins overwrites at best and lockfile crashes at worst. Make it muscle memory: parallel writers get share, read-only researchers and verifiers stay on inherit, and always merge changes back into the main workspace before cleanup.


















