Swarms
Multi-agent coordination for complex tasks that require collaboration between specialized agents.
What Are Swarms?
A swarm is a group of agents working together under a coordination strategy. Instead of a single agent handling everything, swarms let you decompose complex tasks across multiple specialized agents that communicate, delegate, and synthesize results.
import { Cogitator, Agent } from '@cogitator-ai/core';
import { swarm } from '@cogitator-ai/swarms';
const cogitator = new Cogitator({/* ... */});
const devTeam = swarm('dev-team')
.strategy('hierarchical')
.supervisor(
new Agent({
name: 'tech-lead',
model: 'openai/gpt-6.1-sol',
instructions: 'You are a tech lead. Break down tasks and delegate to your team.',
})
)
.workers([
new Agent({
name: 'frontend-dev',
model: 'openai/gpt-6-luna',
instructions: 'Build React components.',
}),
new Agent({
name: 'backend-dev',
model: 'openai/gpt-6-luna',
instructions: 'Build APIs and services.',
}),
])
.build(cogitator);
const result = await devTeam.run({ input: 'Build a user authentication system' });
console.log(result.output);The supervisor automatically receives the delegation tools (delegate_task, check_progress, request_revision, list_workers), so it can hand subtasks to the workers. run() resolves to a StrategyResult: output, structured, agentResults (a Map of RunResults) and strategy-specific fields such as votes, bids, pipelineOutputs, debateTranscript or negotiationResult.
Core Concepts
Every swarm has three fundamental pieces:
| Concept | Description |
|---|---|
| Agents | The individual LLM agents that form the swarm. Each has a name, instructions, model, and optional tools. |
| Strategy | The coordination pattern that determines how agents interact: who runs when, how results flow, and how decisions are made. |
| Communication | The infrastructure for inter-agent messaging: blackboard (shared state), message bus (direct messaging), and event emitter (coordination signals). |
Available Strategies
Cogitator ships with 8 built-in coordination strategies:
| Strategy | Use Case |
|---|---|
hierarchical | Supervisor delegates to workers, coordinates results |
round-robin | Rotate tasks across agents for load balancing |
consensus | Agents vote and reach agreement on decisions |
auction | Agents bid on tasks based on capability |
pipeline | Sequential stages with optional quality gates |
debate | Agents argue opposing positions, moderator synthesizes |
negotiation | Multi-party negotiation with offers, counteroffers, and agreements |
team | A lead and members work through a shared task list with mailboxes |
Swarms can run in distributed mode (.distributed({ enabled: true, ... })) with Redis-backed state and worker nodes. Pipeline, round-robin, consensus, debate and auction work there (consensus voters vote with a VOTE: line), while hierarchical delegation, the voting, negotiation and team tools and agentTools exist only in-process - see Distributed Swarms.
Swarms vs Workflows
Both swarms and workflows coordinate multiple steps, but they solve different problems:
| Swarms | Workflows | |
|---|---|---|
| Coordination | Agent-to-agent, strategy-driven | DAG-based, node-to-node |
| Communication | Agents message each other via blackboard and message bus | Data flows through edges between nodes |
| Decision making | Dynamic: agents vote, bid, debate, negotiate | Static: predefined graph with conditional branches |
| Best for | Tasks requiring collaboration, deliberation, or emergent behavior | Tasks with clear sequential/parallel steps and deterministic flow |
Use swarms when agents need to discuss, delegate, or reach consensus. Use workflows when the execution path is well-defined upfront.
The Swarm Lifecycle
1. Build → Configure agents, strategy, communication
2. Assess → (Optional) Auto-assign optimal models via SwarmAssessor
3. Execute → Strategy coordinates agent runs
4. Observe → Events stream progress in real-time
5. Result → Aggregated output with per-agent resultsWhen a swarm runs, the coordinator manages agent execution, tracks resource usage per run, and handles errors according to your configuration (SwarmCoordinator in-process, DistributedSwarmCoordinator with Redis workers). Each strategy implements its own execution flow on top of the coordinator.
Resource Management
Swarms support built-in resource tracking and circuit breakers:
const team = swarm('team')
.strategy('hierarchical')
.supervisor(supervisor)
.workers(workers)
.resources({
maxConcurrency: 5,
tokenBudget: 100_000,
costLimit: 1.0,
timeout: 300_000,
})
.errorHandling({
onAgentFailure: 'retry',
retry: { maxRetries: 3, backoff: 'exponential' },
circuitBreaker: { enabled: true, threshold: 5, resetTimeout: 60_000 },
})
.build(cogitator);A swarm turn cannot wait for a person: when an agent calls a tool that needs approval (requiresApproval) and its run pauses, the turn fails with an AgentRunPausedError (from @cogitator-ai/core) that names the agent and the calls and carries the checkpoint, instead of passing the model's text before the tool call on as the agent's answer. It is not retried, skipped or failed over, since another attempt would only pause again, and it does not count against the circuit breaker. Give swarm agents an onApproval policy, or tools without approval, when the swarm must finish on its own. Distributed turns behave the same way.
Events
Every swarm emits structured events you can subscribe to:
const team = swarm('team')
.strategy('pipeline')
.pipeline({
stages: [/* ... */],
})
.build(cogitator);
team.on('agent:start', (event) => {
console.log(`Agent ${event.agentName} started`);
});
team.on('agent:complete', (event) => {
console.log(`Agent ${event.agentName} finished`);
});
team.on('swarm:complete', (event) => {
const { agentCount } = event.data as { agentCount: number };
console.log(`Swarm done, ${agentCount} agents ran`);
});Use the wildcard '*' to capture all events for logging or observability. event.data is unknown; the payload of each event is listed in Agent Communication.
Swarms Inside Workflows
swarmNode runs a swarm as a workflow node. It takes a built Swarm or a SwarmConfig (a config gets a fresh swarm per run that is closed afterwards) and uses the Cogitator of the workflow executor:
import { WorkflowBuilder } from '@cogitator-ai/workflows';
import { swarmNode, conditionalSwarmNode, parallelSwarmsNode } from '@cogitator-ai/swarms';
type ReviewState = { code: string; verdict?: string; risk?: string; notes?: unknown };
const workflow = new WorkflowBuilder<ReviewState>('review')
.initialState({ code: '' })
.addNode(
'board',
swarmNode<ReviewState>(reviewBoard, {
inputMapper: (state) => `Review this change:\n${state.code}`,
stateMapper: (result) => ({ verdict: String(result.output) }),
})
)
.addNode(
'risk',
conditionalSwarmNode<ReviewState>(
debateTeam,
(state) => state.verdict?.includes('MERGE') ?? false,
{ stateMapper: (result) => ({ risk: String(result.output) }) }
),
{ after: ['board'] }
)
.build();The swarm sees the node's step and the workflow state as workflowContext in its run context. The node passes the workflow run's abort signal to swarm.run(), so a node timeout, a pause or a cancel aborts the swarm and its agent turns in flight, and a retry of the node can run the same Swarm again. parallelSwarmsNode([{ swarm, key, options }, ...], merge) runs several swarms at once and fails only when all of them fail, its output maps each key to its StrategyResult.
Next Steps
- Coordination Strategies - detailed guide to all 8 strategies
- Agent Teams - a lead and members with a shared task list and mailboxes
- Swarm Builder — fluent API for configuring swarms
- Agent Communication — blackboard, message bus, events
- Swarm Assessment — auto-assign optimal models
- Distributed Swarms — scale across machines with Redis
Workflow Patterns
MapReduce, sub-workflows, parallel execution, conditional branching, loops, fan-out/fan-in, scatter-gather, race, and fallback patterns.
Coordination Strategies
All 8 built-in strategies for multi-agent coordination - hierarchical, round-robin, consensus, auction, pipeline, debate, negotiation and team.