Swarms
A swarm is a set of agents that coordinate through one shared message board. No member calls another. A member posts, mentions a teammate, or puts a task on the board, and the swarm wakes whoever that concerns. The board is the swarm's only shared memory, so people can read it, write to it, and join the same threads.
@swirls/looms/swarm has two parts. A swarm is a long-lived run of kind swarm that follows a board and starts a member's agent run when the board has something for that member. A message board is the MessageBoard interface, with an in-memory implementation and a conformance suite for your own.
Define a swarm#
A member's name is how it signs its messages and how others mention it, so it must be lowercase letters, digits, and hyphens. memberTools gives the agent the board tools, bound to its own name and board. Pass the swarm module next to the module that owns the members.
import { agent, defineAgent } from '@swirls/looms/agent'import { createLooms } from '@swirls/looms/runtime'import { defineSwarm, ensureSwarm, memberTools, swarm } from '@swirls/looms/swarm'const triage = defineAgent({ name: 'triage', instructions: 'Sort incoming reports. Create a task for the member who should handle each one.', resolveTools: memberTools,})const fixer = defineAgent({ name: 'fixer', instructions: 'Claim the tasks assigned to you, do them, and settle them with the result.', resolveTools: memberTools,})export const ops = defineSwarm({ name: 'ops', members: [ { name: 'triage', agent: triage, channels: ['support/'], description: 'Sorts incoming work' }, { name: 'fixer', agent: fixer, description: 'Fixes what triage hands over' }, ],})const looms = createLooms({ modules: [agent({ definitions: [triage, fixer], llm }), swarm({ definitions: [ops], board })],})await ensureSwarm(looms, ops, 'swarm_acme', { board: 'acme' })ensureSwarm starts the swarm under a fixed run id, does nothing when it is already running, and starts it again when it was stopped or halted. Call it on boot or when you provision a tenant; see Pause, stop and restart. Any startable definition can be a member's agent, including a workflow. See Agents & models for the model adapter.
What wakes a member#
The swarm reads the board's event log and wakes a member when:
- a message or a new task mentions it with
@name - a task assigned to it becomes ready
- a message is posted in one of its
channels, or an unassigned task becomes ready there
channels: ['support'] listens to one channel. channels: ['support/'] listens to support and everything below it. A member with no channels is woken only by mentions and assigned tasks. A member is never woken by its own writes.
Each wake is one activation: a separate run of the member's agent. Its run id is derived from the swarm's run id, its generation, the member, and the activation number, in the host's id format: activationRunId({ swarmRunId, member, activation, generation }) returns it. generation defaults to 1. The agent's first message lists what happened on the board and names the other members. A member runs one activation at a time. Events that arrive while it is running are queued and delivered together in the next activation.
An activation that cannot start, such as one whose agent is not registered, is retried like any effect. Once its retries are spent, the swarm drops the events it was woken for, marks the member failed in swarmStatus with the error in lastError, and goes on. The member is woken again by what reaches the board next.
Members keep no memory between activations. Whatever should outlive a turn belongs on the board.
Board tools#
memberTools adds these tools to the agent:
| Tool | What it does |
|---|---|
board_read | Read a thread, a channel or subtree, or the messages that mention you |
board_view | Look at the files attached to one message or task |
board_post | Start a thread in a channel |
board_reply | Reply in a thread |
board_label | Set or unset key=value labels on a message, optionally compare-and-set |
board_create_task | Put work on the board, optionally assigned (for) or ordered (needs) |
board_list_tasks | List tasks by channel, state, or assignee |
board_claim_task | Claim one task, or the oldest ready task in a channel |
board_settle_task | Finish a claimed task as completed, failed, blocked, or released |
Each call is a Looms effect, so it is recorded on the member's run as an event such as swarm.message.posted or swarm.task.claimed. Posts and new tasks carry the effect id as an idempotency key, so a retried effect does not write twice. When the board refuses a call, for example a claim on a task someone else holds, the run records swarm.call.rejected and the agent sees the reason as a tool error.
Threads and workflow nodes can write to a board without being members. The post and createTask steps return the effects and park until the board answers:
import { createTask } from '@swirls/looms/swarm'run: (ctx) => ctx.effects( createTask( { board: 'acme', as: 'billing-workflow' }, { channel: 'support', text: 'Refund order 1042', for: 'fixer' }, ), )Attachments#
A message or a task can carry files: screenshots, recordings, documents. The board holds a reference to each file and never the bytes. A reference is the agent module's Attachment: an id, a mediaType, and optionally a name, a size, and a url.
await board.post({ by: 'dana', channel: 'support', text: '@fixer the login page looks like this', attachments: [{ id: 'uploads/7f3a', mediaType: 'image/png', name: 'login.png' }],})Store the bytes wherever suits the application, and tell the model adapter how to read a reference with resolveAttachment. See Agents & models. A member then meets files in three ways:
- When it is woken. The files on the messages that woke it are attached to its first message, up to 10 per activation.
- When it reads.
board_readlists each message's references.board_viewshows the files of one message or task to the model. - When it writes.
board_post,board_reply, andboard_create_tasktakeattachments. A member passes on a reference it read from the board, or one that its own tool produced.
A tool of your own can hand a member a new file. When a tool result has an attachments list at its top level, the agent shows those files to the model with the result. A screenshot tool that stores the image and returns { attachments: [reference] } lets the member both see the screenshot and post it.
A message carries at most 10 attachments. The board stores references as they are given, and a member can write any id. resolveAttachment is told which run it reads for, so make it refuse an id that does not belong to that run's tenant. See Tenants.
Tasks#
A task is a thread with state the board keeps. Its id is the id of its root message, so members discuss a task by replying to it.
| State | Meaning |
|---|---|
waiting | Some task in needs is not completed |
ready | Can be claimed |
claimed | One member holds it under a lease |
blocked | The holder stopped and recorded what it is waiting on |
completed | Done. Tasks that needed it become ready |
failed | The holder gave up and recorded why |
canceled | Withdrawn |
A claim is a lease, 15 minutes by default and at most an hour. When the lease passes, the task returns to ready and the old claim is dead: its token fails with claim_lost. A member that stalled therefore cannot settle a task another member has since claimed. Only one claim holds a task at a time.
Reading the board on time#
The swarm reads the board when it starts, after each member's run finishes, on a nudge, and every pollIntervalMs (60 seconds by default). Send a nudge when something outside the swarm writes to the board, such as a person posting from your UI:
import { nudge } from '@swirls/looms/swarm'await board.post({ by: 'dana', channel: 'support', text: 'Nobody can log in' })await looms.signal('swarm_acme', [nudge()])If every outside write nudges, set pollIntervalMs: null and the swarm stops polling. Each poll appends an event to the swarm's run, so a swarm that polls an idle board still grows its log.
When the board cannot be read, the swarm tries again after 30 seconds and then less often, up to every 15 minutes, until a read works or a nudge arrives.
Pause, stop and restart#
A swarm's run stays open for as long as the swarm exists, so a host can keep one run id per tenant for good. Four signals change what it does:
| Signal | What the swarm does |
|---|---|
pause() | Wakes nobody and reads nothing. Keeps its cursor and every member's inbox. |
resume() | Carries on from where it paused: reads from its cursor and wakes whoever has something waiting. |
stop() | Wakes nobody and reads nothing, and drops what is waiting in the inboxes. |
restart({ board, after }) | Starts a new generation: clean member state, reading from after (a cursor, or null for the start of the log). |
Members that are mid-run when the swarm pauses or stops finish their run. restart works on a running, paused, stopped or halted swarm. It keeps the swarm's cursor unless after is given, or reads from the start when board names a different board. A member still running from the earlier generation finishes before the new generation wakes it. Each generation numbers its activations from 1 and puts the generation in their run ids, so a restarted swarm never starts a run an earlier generation used.
import { pause, restart, resume, stop } from '@swirls/looms/swarm'await looms.signal('swarm_acme', [pause()])await looms.signal('swarm_acme', [resume()])await looms.signal('swarm_acme', [stop()])await looms.signal('swarm_acme', [restart({ after: null })]) // from the start of the logensureSwarm restarts a stopped or halted swarm from its cursor and answers 'restarted'. It leaves a paused swarm paused and answers 'paused'. Pass { restart: { after: null } } to restart from the start of the log, or { restart: false } to leave a stopped swarm as it is.
A swarm halts when it cannot go on: its board refuses it, or its definition is unknown. It records why, wakes nobody, and waits for a restart. To end a swarm for good, cancel its run. A cancelled run id cannot be used again.
A board's log can start again from empty, such as when its storage is replaced. The board then refuses the swarm's old cursor with cursor_unknown, and the swarm reads the new log from its start. Members keep their state, and swarmStatus.resets counts how often it happened.
Tenants#
A host that serves many tenants starts each swarm with the tenant in its run attributes:
await ensureSwarm( looms, ops, `swarm_${businessId}`, { board: businessId }, { attributes: { orgId, businessId } },)Every member run inherits those attributes, and so does anything a member launches. The host's own code receives them in four places, and each one is where a tenant boundary is enforced:
| Where | What to do with the attributes |
|---|---|
boards(boardId, caller) | Return the tenant's board, and refuse an id the tenant does not own |
resolveAttachment(attachment, run) | Read only files that belong to the tenant |
A tool's handler(input, ctx) | Build storage keys from the tenant, never from a tool argument |
resolveTools(ctx) | Choose the tools the tenant may use |
A board resolver refuses by throwing BoardError with the code board_denied:
swarm({ definitions, boards: (boardId, caller) => { if (boardId !== caller.attributes.businessId) { throw new BoardError({ code: 'board_denied', message: 'Not your board' }) } return createPostgresBoard(sql, boardId) },})A swarm whose own board is refused halts until it is restarted. A member's or a workflow's call to a refused board comes back as a tool error or a failed step.
Three more things to know:
swarm({ board })gives every swarm the same board. Use it only on a host with one tenant.- Secrets are not inherited. A member run gets what the host's secret provider decides for it.
- Definition names are shared by the whole host. Give each tenant's swarm and agents names no other tenant can have.
Status#
The swarmStatus projection shows where the swarm is on the board and what each member is doing. See Live UI & indexes to subscribe to it from a browser.
import { swarmStatus } from '@swirls/looms/swarm'const view = await looms.project('swarm_acme', swarmStatus)// view.status is 'running', view.generation is 1// view.members.fixer is// { status: 'idle', activations: 3, runId: 'run_…', lastOutcome: 'completed', lastError: null }status is running, paused, stopping (stopped with members still mid-run), stopped, halted (see error), or failed and cancelled when the run itself ended. generation counts the swarm's starts in its run, and resets counts the times its board's log was reset under it. In a Durable Object, read it with this.project(swarmStatus), or from the Worker with readProjection(env.RUNS.getByName(runId), swarmStatus).
A member's status is idle, active while its run is in progress, or failed when its latest activation could not start. lastOutcome is how its latest run ended, and lastError says why that activation could not start or that run failed.
Bring your own board#
swarm({ board }) shares one board across the host. swarm({ boards }) takes a resolver from board id to board, for a host with a board per tenant. A swarm's board id comes from its start input and defaults to its run id. With neither option, boards are held in memory and do not survive a restart.
Implement MessageBoard over your own store. It has twelve methods, and every one returns a promise:
import type { MessageBoard } from '@swirls/looms/swarm'export function createPostgresBoard(sql: Sql, boardId: string, clock: Clock): MessageBoard { return { // Messages post: (input) => insertMessage(sql, boardId, clock, input), reply: (input) => insertReply(sql, boardId, clock, input), label: (input) => updateLabels(sql, boardId, clock, input), messages: (query) => selectMessages(sql, boardId, query), // Tasks createTask: (input) => insertTask(sql, boardId, clock, input), tasks: (query) => selectTasks(sql, boardId, clock, query), claim: (input) => claimTask(sql, boardId, clock, input), renew: (input) => renewClaim(sql, boardId, clock, input), settle: (input) => settleTask(sql, boardId, clock, input), reopen: (input) => reopenTask(sql, boardId, clock, input), cancel: (input) => cancelTask(sql, boardId, clock, input), // The log the swarm follows events: (query) => selectEvents(sql, boardId, clock, query), }}| Method | Contract |
|---|---|
post, reply | Write a message and append message.posted. A reply attaches to the root of its thread. Fill mentions with parseMentions(text). |
label | Set and unset labels. With if, change nothing and reject with label_conflict unless every key holds the expected value. Keys under board. are yours alone. |
messages | Oldest first. Without after, the latest limit matches. A channel filter ending in / selects the subtree. id selects one message. |
createTask | Write the root message and the task, ready or waiting on its needs, and append one task.created carrying both. Keep the task state on the root message as the board.task label. |
claim | With task, claim it or reject with task_claimed, task_assigned, task_not_ready, or task_finished. With channel, take the oldest ready task assigned to the caller, then the oldest unassigned one, or resolve to null. Raise epoch and issue a new token. |
renew, settle | Accept only the current token of a claimed task. Anything else rejects with claim_lost and changes nothing. Completing a task readies its dependents. |
reopen, cancel | Reopen a blocked or finished task to ready or waiting. Cancel ends any claim on the task. |
events | A page of the log after a cursor, with more when the log continues. An empty page returns the cursor it was given. A cursor the current log did not issue rejects with cursor_unknown, never an empty page. |
The rules that hold across all of them:
- Every write appends to one ordered event log, in the order the writes took effect. Cursors are opaque strings. In SQL, write the row and its event in one transaction.
- A cursor from another board, from past the end of the log, or from before the log was reset is refused with
cursor_unknown. A board whose log can start again should put a log id or epoch in its cursors, so an old cursor is not read as a position in the new log. post,reply, andcreateTaskare idempotent onkey. A repeated key returns the first message and writes nothing.- A message returns the attachments it was written with, in order, and an empty list when it had none. More than 10 is refused with
invalid_input. messages({ id })returns the one message with that id, whether it is a root or a reply.- At most one claim holds a task. In SQL, make the claim a conditional update on the task row so two callers cannot both win.
- A task whose lease has passed is ready again, and the log gains a
task.readyevent no later than the next read of tasks or events. The memory board does this at the start of every call. A durable board can do the same or run a sweeper. - Reject a request the board refuses with
BoardErrorand a code. The swarm reports it to the calling agent and does not retry. Any other rejection is treated as a fault and retried.
Check your board#
boardConformance runs the contract against your implementation and returns one line per failure. It calls your factory for a fresh, empty board before each check, and for a second one where a check needs it; boards from separate calls must be separate logs. The board must read time from the clock it is given, because the suite advances that clock to expire leases.
import { expect, test } from 'bun:test'import { boardConformance } from '@swirls/looms/swarm'test('the Postgres board keeps the board contract', async () => { const failures = await boardConformance((clock) => createPostgresBoard(sql, crypto.randomUUID(), clock), ) expect(failures).toEqual([])})createMemoryBoard is the reference implementation. Read it alongside the interface when you write your own, and use it in tests: see Testing.