Skip to content

Swarm on Cloudflare

The agent swarm of examples/swarm - the same HTTP API, the same session semantics - built on Cloudflare’s own primitives instead of Temporal + Postgres: a Durable Object per session (its state, its event log, its runs, its call journal, its parked items and children) and a Workflow instance per turn and per child (a static subagent call, a pipeline call, a pipeline node visit), with the Node core @dudko.dev/agent running in workerd under nodejs_compat. One Worker; nothing else to run.

This is an example, not a package: private in the workspace, never published. Its platform-independent part - the session reducer, the answer checks, the ids, the cursor and the HTTP API itself - is swarm-shared, the same code the Temporal swarm runs.

HTTPS
clients ──────────────► Worker (fetch: swarm-shared's createGatewayHandler)
▲ │ │ every route but the streams: RPC to the session's object
│ SSE (forwarded to │ │ a stream: the bearer token checked, then forwarded
│ the object, served ▼ ▼
│ by it) SessionDO (one per session: idFromName(sessionId), SQLite)
└────────────────── │ the reducer's state (swarm-shared/workflow), its single writer
│ the event log (every stream of the session) + the live readers
│ runs (snapshots, fences), the call journal, the lease
│ parked items, children, the outbox of effects, the alarm
│
│ outbox: create an instance / send it an event
▼
TurnWorkflow (one per turn: turn-<session>-<turn>)
│ step `phase k` = one agent.run attempt, every hook on the object:
│ persistence + journal → RPC; runLease → RPC; onEvent → RPC (batched)
│ sharedLimits → LimiterDO (one per bucket)
│ parked → waitForEvent(`resume-k`) → step `phase k+1` (the same run)
│
├─ SubagentWorkflow (one per static subagent call)
└─ PipelineWorkflow (one per pipeline call: the graph engine)
└─ PipelineNodeWorkflow (one per node visit, a wave in parallel)

The session’s object is its single writer. Every transition - a message, an answer, a stop, a turn’s or a child’s outcome, the idle timer - is one call into it, and everything the transition produces is written in the same storage transaction as the state it leaves: the reducer’s state (swarm-shared’s ISessionState, as JSON), the turn.ended and child markers (the event log is in the same object, so they need no activity of their own), the parked items, the children, and the effects on other services, as rows of an outbox. After the transaction the object makes the effects - start a Workflow instance, send one an event - in the order they were decided, one at a time, retrying a failed one from its alarm with backoff (a later one never overtakes it). Every effect is idempotent: instance ids are functions of what they run (a retried create finds the instance there), and an event a waiter already took is never waited for again.

A turn is a Workflow instance; an attempt is a step. The instance’s phase 0 step asks the object for the turn’s input, runs ONE agent.run with every scale-out hook of the agent pointed at the object, and reports the outcome (the object applies it once per phase: a retried report is a no-op). A run that parks reports parked; the instance waits for resume-1 (no step holds anything while a person decides), which the object sends once every item has its answer; phase 1 resumes the SAME run (resumeFromRunId + answers). A step the engine retries (it threw, its isolate died) finds its run on record and resumes it from its last snapshot, replaying its call journal: a recorded model call is not sent again, a recorded tool call does not run again.

The streams are served by the session’s object. The Worker checks the bearer token of a stream request and forwards it (stub.fetch) to the object, which serves it with the same createGatewayHandler, its own event log as the feed. A reader’s subscription is a waiter in the memory of the one object that writes the stream, taken synchronously before the replay reads (the object runs one thing at a time), and woken by the write itself: LISTEN / NOTIFY without the network hop, nothing polled, nothing missed between the replay and the live part. The alternative - the Worker long-polling the object by RPC - would add a hop per wake and a window between the replay read and the subscription to close by hand. An unauthenticated request never reaches an object (an id names an object: any id would wake one).

examples/swarm (Temporal + Postgres) Here (Durable Objects + Workflows) Where
the session workflow (signals, query, the loop) SessionDO: one call per signal, the reducer applied in the object, view() for the query src/session.ts, src/host.ts
deterministic replay of the session none needed: the object’s state is stored, not replayed (no patched(), no continue-as-new)
the runTurn activity, its retries a TurnWorkflow step per attempt (retries.limit = TURN_MAX_ATTEMPTS - 1, timeout = TURN_TIMEOUT_MS) src/workflows.ts, src/steps.ts
TURN_REFUSED (non-retryable) NonRetryableError (a refusal, refused credentials, a misconfiguration) src/workflows.ts
endTurn / writeMarkers activities written by the object in the transition’s own transaction src/session.ts
the session’s timer (condition(ready, idleTimeoutMs)) the object’s alarm (with the outbox’s retries and the watchdog) src/host.ts
the activity heartbeat = the lease runLease on the object: a TTL by the object’s clock (LEASE_TTL_MS) from its last write, renewed every TTL/3; a newer attempt revokes the holder (its next renew says lost) and takes the run once the holder’s lease has run out. Every answer of the object that says held is a write of the lease - an event batch’s too - so a renew may stand on a batch’s answer for a third of the TTL and a healthy holder writes its lease at least every 2·TTL/3; a renew the object did not answer (the stub’s error is retryable or overloaded) stands on the last write it confirmed while the next renew still comes inside that write’s TTL - one lost RPC does not cost a healthy run its attempt src/store.ts leaseAcquire; src/steps.ts createLeaseRenewer
a user’s stop = activity cancellation the answer of the lease’s renew (and of every event batch): stop → the step aborts the run, which records cancelled src/steps.ts
revokedReason (heartbeat timeout, shutdown, …) the revoke above; the watchdog for an instance that errored or went silent src/host.ts
swarm_runs (snapshots, fence, supersedeRun) the object’s runs table, the same fences: checkpoint >=, resume >, nothing below the fence, supersede only without a plan src/store.ts
swarm_journal (FOR SHARE against the fence) the object’s journal table; the check and the insert are one synchronous block of a single-threaded object - nothing can come between them src/store.ts
swarm_events + NOTIFY the object’s events table + its in-memory waiters src/store.ts, src/feed.ts
swarm_parked the object’s parked table (the same rows, the same states) src/store.ts
swarm_sessions the object’s existence (state on record)
swarm_limiter (row lock, the database’s clock) LimiterDO per bucket (one call at a time, the object’s clock); the bucket math is the same src/limiter.ts
child workflows (startChild, child.result()) Workflow instances the object starts from its outbox; a child reports its outcome to the object src/workflows.ts, src/session.ts
a child’s wait (signals into child-state.ts) the same child-state.ts, applied in the object; the object sends the child resume-k src/session.ts
subagentWorkflowIdOf etc. as workflow ids the same names (swarm-shared) for everything the API shows; the instance id is a SHA-256 of the name (Workflow ids are ≤ 100 chars of [A-Za-z0-9_-]) src/ids.ts
the pipeline workflow (the engine, replayed by Temporal) PipelineWorkflow: the engine between named steps; the visits’ outcomes arrive as settled <n> events one at a time, so a replay applies them in the same order src/workflows.ts
the gateway on node:http the Worker (fetch); the streams in the session’s object src/gateway.ts
.env, *_FILE secrets wrangler.jsonc vars, Worker secrets (.dev.vars locally) wrangler.jsonc
compose.yaml, the Helm chart, the image wrangler.jsonc

Why this way, where there was a choice:

  • The state machine stays in the object, the waiting in the Workflows. A Workflow has no query and holds no state anyone else can read cheaply; an object has both and is a natural single writer. Workflows are what survives a dying isolate - so every run (and every wait for a resume) is in one, and nothing long-running is in the object.
  • Big data stays in the object; ids cross. A step result and an event payload are at most 1 MiB: an instance is started with { sessionId, turn }, a step reads its input from the object and reports its outcome to it by RPC (a compacted history, a pipeline’s node texts), and returns only a status. Values that may outgrow a SQLite row (2 MB) - the state, a snapshot, a journal entry, a turn’s input - are stored in parts.
  • An agent per step. workerd keeps no I/O across requests, so the agent (and its MCP connections) is made in the step and closed in it; a subagent’s or pipeline’s call budget is the step’s own object, closed over by its tool - no AsyncLocalStorage.
  • The lease revokes. On Temporal the server tells a worker it lost the activity; nothing tells a Workflow step that the engine gave up on it. So a retried attempt that finds the run held revokes the holder (its next renew answers false: the core aborts it and writes nothing more) and waits for the holder’s lease to run out before it takes the run and raises its fence. A step that went silent - gone with its isolate - is the same: its lease runs out.

The same as examples/swarm’s, served by the same code: routes, bodies, answers, status codes, the event stream’s frames and cursor (<turn>:<attempt>:<seq>, ?after= and Last-Event-ID), parking and its answer checks, the children’s streams and listings. Two differences of the platform:

  • SSE_MAX_CONNECTIONS caps the open streams of one session (its object serves them), not of a gateway instance - a Worker has no instance to protect; the object is the resource a crowd of readers could wear out. Default 100.
  • A 503 names durable object: ... (the session’s object could not be reached) where the Temporal swarm names Postgres or Temporal. /readyz (unauthenticated, as there) touches no Durable Object - a request to an object is billed, and anyone can call /readyz - so it checks only the configuration the steps need: a wrong one answers 503 with "backend": "misconfigured", one word (the detail - which can quote a value, a secret’s included - is in the log).

GATEWAY_AUTH=bearer is one shared operator token: whoever holds it reaches every session, so it belongs on a server, never in a page. GATEWAY_AUTH=visitor lets the end users of one website talk to the gateway straight from their browsers, each reaching only the sessions they started (swarm-shared’s src/visitor.ts; the same code would serve the other swarms, which keep bearer only for now).

Who a visitor is. Either the website says so - its backend signs a short-lived token for the person - or, for a site with no backend, the gateway names anonymous visitors itself in a cookie (VISITOR_ANONYMOUS=true). Both can be on at once. Operator tokens (GATEWAY_TOKENS, optional here) still reach every session.

The token (format v1), sent as Authorization: Bearer <token>:

v1.<userId>.<sessionId>.<expiresAt>.<mac>
Field
userId the site’s id of the person, [A-Za-z0-9_-]{1,64} - map an e-mail or a database id to that alphabet (an opaque id, a hash); a random one for an anonymous visitor
sessionId empty, or [A-Za-z0-9_-]{1,64}: the token then reaches that session only, and POST /sessions with it starts the session under that id (once: then 409 session_exists)
expiresAt seconds since the epoch, decimal
mac base64url without padding (43 characters) of HMAC-SHA256(VISITOR_SECRET, v1.<userId>.<sessionId>.<expiresAt>) - the token up to its last dot, as ASCII; the canonical encoding only (any standard base64url encoder’s output: the last character’s two unused bits are zero)

The gateway refuses it (401) when a field is malformed, the mac is not VISITOR_SECRET’s (or a VISITOR_PREVIOUS_SECRETS entry’s, during a rotation; compared in constant time), it expired more than VISITOR_CLOCK_SKEW_SECONDS ago, or it expires further ahead than VISITOR_TOKEN_MAX_LIFETIME_SECONDS (plus the skew) - so a site cannot hand out a token that lives for ever by mistake. Hand out short tokens (minutes) and fetch a new one when it runs out. In Node (any language does the same):

import { createHmac } from 'node:crypto'
const visitorToken = (secret: string, userId: string, sessionId = '', ttlSeconds = 600) => {
const body = `v1.${userId}.${sessionId}.${Math.floor(Date.now() / 1000) + ttlSeconds}`
return `${body}.${createHmac('sha256', secret).update(body).digest('base64url')}`
}

(signVisitorToken in swarm-shared is the same, over WebCrypto.)

The anonymous cookie. POST /sessions without a credential names a new visitor (anon-<uuid>) and sets __Host-swarm-visitor (VISITOR_COOKIE_NAME, which must keep the __Host- prefix - without it a sibling host such as evil.example.com could plant the cookie for chat.example.com and fix a visitor’s identity; the Worker does not start with another name unless VISITOR_COOKIE_ALLOW_NO_HOST_PREFIX=true): HttpOnly; Secure; Path=/; SameSite=Strict (VISITOR_COOKIE_SAMESITE), valid VISITOR_COOKIE_TTL_SECONDS and renewed past half its life. Its value has the token’s shape with the tag v1a and no session (v1a.<userId>..<expiresAt>.<mac>, signed with VISITOR_SECRET), so a cookie is never taken as a token or a token as a cookie. A cookie that fails any check - changed, expired, sent twice - counts as none: every route but POST /sessions answers 401, and POST /sessions names a NEW visitor. A request that the cookie authenticates from an Origin that is neither in CORS_ORIGINS nor the gateway’s own is refused (403 origin_not_allowed): the browser sends the cookie with any request to the gateway’s host. Serve the gateway on a subdomain of the site (chat.example.com for www.example.com): the cookie is then first-party and SameSite=Strict works; a gateway on another site needs SameSite=None, which browsers that block third-party cookies refuse - use tokens there.

Ownership. POST /sessions records the visitor as the session’s owner, in the session’s object in the same write. Every route that names a session - its state, messages, answers, stop, events, and the subagent and pipeline listings and streams - checks that the caller owns it before anything else of the session is read, and answers a session of someone else (or one an operator started) exactly as one that does not exist: the same 404 with the same body. A session-bound token naming another session gets that 404 too, from the Worker, before any object is woken. The session’s object checks the owner again for a stream (the Worker forwards it there).

From the browser. CORS_ORIGINS must name the site’s origins exactly (* is refused in this mode); the answers allow credentials for those origins, and the preflight allows the request headers authorization, content-type and last-event-id (a Worker built on this one adds the ones its own checks read with corsAllowHeaders - below). A fetch sends the token in its Authorization header (or credentials: 'include' for the cookie). An EventSource sends no header: open the stream with new EventSource(url, { withCredentials: true }) (the cookie), or put a token in the URL - .../events?access_token=<token> - or read the stream with fetch. A URL ends up in logs (Workers Logs record every request’s URL when observability is on, and so do proxies), so a token in ?access_token= is taken on the event streams only, and only when it is bound to that session and expires within 300 seconds - whatever VISITOR_TOKEN_MAX_LIFETIME_SECONDS allows in a header; anything else there (a token without a session, a longer one, an operator token) is 401 with a message saying so. A header, when sent, is the credential: ?access_token= is not looked at, and a bad header is never rescued by the URL or the cookie. An EventSource reconnects with the same URL, so a site that streams by token hands the page a fresh short token for each (re)connection - or uses the cookie.

What a visitor sees. The event stream is the session’s raw event stream: everything the agent emits, including the tool calls it makes with their inputs and their outputs, the planner’s steps and the subagents’ and pipelines’ own streams. Do not give a visitor’s agent a tool whose input or output the visitor must not read (another customer’s record, an internal note, a secret from a tool’s result) - the visitor reads it in the stream even when the answer they are shown is polite about it.

Who answers what. A parked item - an approval (a person’s decision on a tool call) or a tool (the output of a tool whose result comes from outside, deferResult) - is answered by an operator (GATEWAY_TOKENS). A visitor answers no parked item by default (403 answer_not_allowed, before the item is read): an approval gates a tool call the visitor’s own message asked for, so letting the visitor approve it is no gate, and a tool answer IS the tool’s output, so letting the visitor give it lets them say what the tool returned (a refund granted, a check passed). VISITOR_ANSWER_KINDS lists the kinds visitors may answer - approval for a confirmation the visitor is meant to give themself (“send this e-mail to you?”), tool only when the tool’s output is the visitor’s own input by design. Operators answer every kind.

Abuse limits. A visitor’s message (POST /sessions with one, /messages) is at most VISITOR_MESSAGE_MAX_CHARS (413 message_too_long). The visitors’ writes that can make the model work - POST /sessions, messages, answers - are rate limited in token buckets held by LimiterDO objects (one per bucket, shared by every isolate), all of them on by default:

Bucket Variables Default Key
per visitor VISITOR_USER_MESSAGES_PER_MINUTE / _BURST 10 / min, burst 5 the visitor’s id
per address VISITOR_IP_MESSAGES_PER_MINUTE / _BURST 30 / min, burst 10 cf-connecting-ip: IPv4 as is, IPv6 by its /64
per network VISITOR_NET_MESSAGES_PER_MINUTE / _BURST 120 / min, burst 40 IPv6 by its /48 (an IPv4 address is its own network: only its address bucket applies)
every visitor VISITOR_ALL_MESSAGES_PER_MINUTE / _BURST 600 / min, burst 200 one bucket for all visitors
every visitor, per day VISITOR_ALL_MESSAGES_PER_DAY 20 000 one bucket for all visitors that refills over a day

An anonymous visitor gets a new id with every new cookie, so the per-visitor bucket alone caps nothing for a script; the address, the network and the all-visitors buckets do - the last two are what bound the spend on the model whatever the attacker’s addresses. Set them to what the model’s budget allows (0 turns one off). Over a limit: 429 rate_limited with Retry-After, and the request goes no further - it never reaches the session’s object or the model. A limiter object that cannot be reached refuses the request (503, never let through). A visitor’s bucket object forgets its state once the bucket is full again (an alarm a minute after that, moved on by every take): visitors who come once leave nothing behind. Operators are not limited; reading is not limited (streams have SSE_MAX_CONNECTIONS).

Errors. A 503 says only the service is unavailable: try again shortly, and /readyz (unauthenticated) one word per check (ok | down); what the store or an object said is in the log.

Building on it: another Worker on this runtime

Section titled “Building on it: another Worker on this runtime”

A Worker with its own agent and its own checks can take this runtime as it is - no fork. The package’s ./worker entry (src/worker.ts) has what it needs:

  • useAgentSetup((env) => setup) - the agent the steps build, instead of the one AGENT_* and MCP_SERVERS describe: its config, and two optional hooks of IAgentSetup - turnConfig(sessionId, config) (a turn’s config: tools that act for that session) and createAgent (a wrap around the core’s, e.g. a gate that decides before the agent runs). Called at the top of the Worker’s module, before any request.
  • createSwarmFetch({ backend?, admit?, corsAllowHeaders? }) - this Worker’s fetch as a factory: backend wraps the gateway’s backend (a check that needs the session - its turns so far - runs there), admit is swarm-shared’s admission hook (IGatewayDeps.admit: run after the credential, the session’s owner and the visitors’ buckets, before the backend - a captcha, a daily budget, a cap per session; a thrown HttpError answers, any other error is a 503), and corsAllowHeaders (IGatewayDeps.corsAllowHeaders) lists the request headers those checks read (e.g. a captcha token in cf-turnstile-response), allowed by CORS’s preflight besides the API’s own (authorization, content-type, last-event-id): without it a browser on a listed origin refuses to send such a header cross-origin and the request never reaches the Worker. Lowercase header names; anything else refuses to start.
  • The classes are the package’s own: export { SessionDO, LimiterDO, TurnWorkflow } from 'swarm-cloudflare' in the Worker’s entry, bound in its wrangler.jsonc as here.
  • For a Worker that runs agents without a session: agentSetupFromEnv (the agent’s setup from AGENT_* and MCP_SERVERS), pipelineNodeConfig / needsCatalog (a pipeline node’s agent config) and safeLogger / redact (the log filter).

examples/support-cloudflare is one: the support chat of agent.dudko.dev. examples/pipelines takes the agent’s setup and the node config from here to run pipelines drawn in Pipeline Studio.

The semantics are examples/swarm’s; how they run here:

  • A turn - TurnWorkflow turn-<session>-<turn>, steps phase 0, phase 1, … (one per park and resume). A stop while a step runs reaches it with its next event batch or the next lease renew that asks the object (within 2·TTL/3, 10 s by default: a renew may stand on a batch answered just before the stop, and the one after it asks); a stop while it is parked ends the turn at once (its items closed, its instance told to end). A stop between attempts (a retry’s backoff) is read by the next attempt before it runs anything.
  • Parking - the step reports parked; the object records the items (what the gateway checks an answer against), the reducer takes the answers (the authority), and the object sends resume-k once every item has one. The parked items are marked answered when the resume is decided. A session that goes idle while its turn is parked (no answer within SESSION_IDLE_TIMEOUT_MS, and no child working) ends as a stop with end would end it: the turn is recorded stopped, its turn.ended is written, its items are closed and its instance is told to end. (The Temporal swarm ends such a session without ending the parked turn - no turn.ended there.)
  • Static subagents - SUBAGENTS, as in the Temporal swarm: the tool defers, the object starts a SubagentWorkflow per call (within SUBAGENT_MAX_PER_ROUND / _PER_SESSION), the child runs its profile’s agent in its own stream <session>/<item>, its outcome answers the item. A child parks like a turn (CHILD_ASK=park): its items are the session’s, owned by it; the gateway recomputes the owner (childOwnerOf) and the object routes the answer to that child’s wait, which is checked again there.
  • Pipelines - PIPELINES: a PipelineWorkflow per call runs the core’s graph engine (@dudko.dev/agent/pipeline-engine) between named steps; every node visit is a PipelineNodeWorkflow (its agent.run, then the route call where it ran), a wave started together. The engine’s events go to the pipeline’s own stream in order; a visit’s outcome comes back through the object as a settled event, taken one at a time in a named wait - so a replay of the pipeline’s instance makes the same calls and starts the same visits.
  • A step throws (the provider fails past the agent’s retries, a journal append is refused): the engine retries it with backoff and the retry resumes the run from its last snapshot, as the Temporal swarm’s retried activity does. A failure between two planned steps resumes at the next step, and nothing the run did before is done again (e2e/crash.test.ts (a)). A run that fails inside a step is recorded by the core as it stood when that step started, so the step is replayed from the journal and only the call that failed, and what follows it, is live (the core’s resume; the end-to-end tests here cover the failure between steps and the killed runtime, not this case).
  • The isolate dies mid-step (on Cloudflare: an eviction, a deploy, a machine; locally: wrangler dev killed): the engine runs the step again; the old attempt’s lease runs out (it renews no more), the retry takes the run, raises its fence and resumes it - the write the dead attempt made is answered from the journal. Locally, Miniflare resumes an instance only when something sends it an event: the object’s watchdog nudges an instance whose step went silent (no heartbeat, no event for three lease TTLs) with an event nothing waits for; on Cloudflare the engine restarts the step itself and the nudge is a no-op. e2e/crash.test.ts (b).
  • An attempt the engine gave up on, still running (a step timeout while it is alive, a partition): before its first snapshot, the retry supersedes its run - its next journal append is refused and the core stops it before any tool call it makes runs; after its plan, the retry revokes its lease and raises the run’s fence: it is aborted, and nothing of it is written again. tests/steps.test.ts (both, with the real core).
  • The result was lost (the run ended, the report did not arrive): the retry finds the snapshot complete (or waiting) and reports it without running anything.
  • A Workflow instance errors outside a step, or is terminated: the watchdog (every four lease TTLs) fails the turn or the child, as Temporal fails an activity it gave up on.
  • An effect fails (the Workflows API is briefly unavailable): retried from the alarm with backoff (at most a minute apart), in order. An event - a resume, a pipeline’s settled, a stop - is never given up: dropping one would leave its instance waiting and the session “running” forever, so it is retried until it is delivered, or until its instance is over (complete, errored, terminated or gone: nothing waits for it then, and the watchdog settles what that instance left). A start that keeps failing is given up after 12 tries and its turn (or child) fails, so the session goes on. The alarm is set in the same turn as the transaction that decided the effect, so an object that dies before it made one still wakes to make it; and a resumed instance the watchdog finds still waiting for its resume is sent it again.
  • The session’s object restarts: nothing is lost - the state, the outbox and the alarm are stored; readers reconnect with Last-Event-ID.
  • Not on workerd: stdio MCP servers (no processes: MCP_SERVERS refuses a command), the run_js sandbox and worker-thread subagents (no worker_threads), web_fetch / egress (the core’s safe fetch does its own DNS lookup, which workerd does not offer: it fails closed - keep egress off), enterprise-managed MCP authorization with private_key_jwt (KeyObject), and interactive MCP OAuth (as in the Temporal swarm). Static headers on HTTP MCP servers work.
  • MCP tools with an outputSchema need @dudko.dev/agent with newOutputSchemaValidator (Ajv compiles schemas to code, which workerd forbids; the core now picks the MCP SDK’s code-free validator there). e2e/mcp.test.ts.
  • Workflows’ own limits: a step result and an event payload ≤ 1 MiB (only ids and statuses cross here); a wait (a resume, a pipeline’s settled) is taken again every 30 days, up to 1000 times. See Long turns: the limits to raise.
  • A SQLite row holds 2 MB: the state, snapshots, journal entries and inputs are stored in parts; one stored event is capped by EVENT_MAX_BYTES (at most 1 MiB, a stub beyond); a parked item’s question (a tool’s input) must fit a row.
  • One object per session: every write of a session - its turns and all its children’s runs and events - goes through one single-threaded object. That is the point (one writer, no fences across machines), and it bounds a session’s throughput, not the swarm’s.
  • No continue-as-new and no SESSION_MAX_TURNS_PER_RUN: the object stores its state; nothing grows a history.
  • Everything examples/swarm lists that is not about Temporal or Postgres: remember refused on an approval, no steering inside a turn, MCP elicitation not answered, at-least-once tool calls in the one window the journal cannot close.

A turn’s step is one Worker invocation that lasts as long as the turn’s attempt (up to TURN_TIMEOUT_MS), and every hook of the agent is an RPC to the session’s object - a subrequest. What one attempt makes, roughly: one event batch every EVENT_FLUSH_MS while the run streams (500 ms by default; each batch also renews the lease), a lease renew every LEASE_TTL_MS / 3 while it does not, two journal appends per model or tool call, a snapshot per planned step, one call per shared-limit bucket per model call. A ten-minute attempt that streams throughout is about 1200 batches. So, on Cloudflare:

  • the Worker’s subrequests per invocation (limits.subrequests in wrangler.jsonc, on the paid plan; the free plan’s small fixed number is far too low for a real turn) - raise it, or raise EVENT_FLUSH_MS;
  • the CPU per invocation (limits.cpu_ms, up to 300000 on the paid plan): the agent’s own CPU is small (its time is I/O), but a large history’s compaction and JSON are not free;
  • the steps per Workflow instance (limits.steps of a workflows entry): a turn uses a few per park; a pipeline about four per node visit (its start, its settled wait, its stream writes) - a long graph with many visits may need more than the default.

wrangler.jsonc lists them, commented out; check the current numbers in Cloudflare’s limits pages before you raise them.

Everything comes from the Worker’s environment: vars in wrangler.jsonc and Worker secrets (wrangler secret put; locally .dev.vars, from .dev.vars.example - never committed). The names are examples/swarm’s wherever the meaning is the same; a bad value fails the request with the variable’s name in the log (/readyz answers down).

The API (the Worker)

Variable Default
GATEWAY_AUTH bearer visitor: the end users of one website (Visitors). none turns auth off - for a local try only, and only with GATEWAY_ALLOW_NO_AUTH=true as well (a Worker cannot tell where it runs; never on a deployed one)
GATEWAY_TOKENS - (required with bearer, optional operator tokens with visitor; a secret) Bearer tokens, comma separated, 16+ characters each, never v1.-prefixed; the placeholder of .dev.vars.example (and any change-me...) is refused
CORS_ORIGINS none Allowed browser origins (exact), or * (not with visitor)
GATEWAY_MAX_BODY_BYTES 65536
MESSAGE_MAX_CHARS 32000
CONTEXT_KEYS (none) The page-context keys a message may carry (context of POST /sessions/:id/messages), comma-separated, exact names; every other key is dropped, and with none the context is ignored. Untrusted: shown to the model as data, never a policy input
SSE_MAX_CONNECTIONS 100 Open event streams per session (more: 503)
SSE_KEEPALIVE_MS 15000
SSE_BATCH 500 Rows per replay read
LOG_LEVEL info One JSON line per entry (Workers Logs)

Visitors (GATEWAY_AUTH=visitor)

Variable Default
VISITOR_SECRET - (required; a secret) The HMAC key the website shares, 32+ characters (openssl rand -hex 32); signs the anonymous cookies; the placeholder of .dev.vars.example is refused
VISITOR_PREVIOUS_SECRETS none (a secret) Still accepted, never used to sign - a rotation: move the old secret here, deploy, then let the site sign with the new one
VISITOR_TOKEN_MAX_LIFETIME_SECONDS 3600 A token expiring further ahead is refused (60 to 604800)
VISITOR_CLOCK_SKEW_SECONDS 60 How far the site’s clock and the gateway’s may differ (0 to 300)
VISITOR_ANONYMOUS false The gateway names visitors in a cookie (a site with no backend)
VISITOR_COOKIE_NAME __Host-swarm-visitor Must start with __Host-
VISITOR_COOKIE_ALLOW_NO_HOST_PREFIX false Allows a VISITOR_COOKIE_NAME without __Host- - a cookie a sibling host can plant; only when no other host can set cookies for the domain
VISITOR_COOKIE_TTL_SECONDS 2592000 (30 days) Renewed past half of it
VISITOR_COOKIE_SAMESITE Strict Strict | Lax | None (a gateway on another site than the page)
VISITOR_MESSAGE_MAX_CHARS 4000 A visitor’s message (and never more than MESSAGE_MAX_CHARS)
VISITOR_USER_MESSAGES_PER_MINUTE 10 Per visitor: sessions started, messages, answers (0: no limit)
VISITOR_USER_MESSAGES_BURST 5
VISITOR_IP_MESSAGES_PER_MINUTE 30 The same per client address (0: no limit)
VISITOR_IP_MESSAGES_BURST 10
VISITOR_NET_MESSAGES_PER_MINUTE 120 The same per network: an IPv6 address by its /48 (0: no limit)
VISITOR_NET_MESSAGES_BURST 40
VISITOR_ALL_MESSAGES_PER_MINUTE 600 Every visitor together (0: no limit)
VISITOR_ALL_MESSAGES_BURST 200
VISITOR_ALL_MESSAGES_PER_DAY 20000 Every visitor together, a day’s budget (0: no limit)
VISITOR_ANSWER_KINDS none The parked items visitors may answer: approval, tool, comma separated; none by default (operators answer them)

A session’s options - fixed when it starts (the object keeps them):

Variable Default
SESSION_IDLE_TIMEOUT_MS 86400000 No work for this long ends the session (a parked turn ends stopped); 0 never
TURN_TIMEOUT_MS 1800000 One attempt of a turn: the step’s timeout
TURN_MAX_ATTEMPTS 5 Attempts of one step (the engine’s retries + 1)
SESSION_HISTORY_MAX_CHARS 200000
SESSION_MAX_QUEUED_MESSAGES 50
SUBAGENT_MAX_PER_ROUND / SUBAGENT_MAX_PER_SESSION 4 / 50
PIPELINE_MAX_PER_ROUND / PIPELINE_MAX_PER_SESSION 2 / 20

The steps

Variable Default
LEASE_TTL_MS 15000 The run lease’s TTL (renewed every third of it, written at least every two thirds while the holder is healthy; a stop reaches a step that streams nothing within two thirds of it); what TURN_HEARTBEAT_TIMEOUT_MS is to the Temporal swarm. The watchdog looks every four TTLs and nudges a step silent for three
EVENT_MAX_BYTES 262144 One stored event’s cap (at most 1 MiB)
EVENT_FLUSH_MS 500 How long a step buffers its run’s events before one RPC (a subrequest) sends them; each batch renews the run’s lease too, so a streaming run makes no renews of its own
SESSION_RETENTION_DAYS 30 An ended session’s storage is deleted this long after it ended; 0 keeps it
LIMITER_REFILL_PER_SECOND, LIMITER_CAPACITY, LIMITER_MAX_WAIT_MS, LIMITER_SCOPE off sharedLimits, as in the Temporal swarm (one LimiterDO per bucket)
CHILD_ASK park park / deny

The agent - the Temporal swarm’s variables, with the model built in code (src/agent-config.ts): AGENT_PROVIDER_TYPE (openai default, anthropic, google, openai-compatible - the providers this Worker bundles), AGENT_API_KEY (a secret, required), AGENT_MODEL (required), AGENT_BASE_URL (required for openai-compatible), AGENT_PROVIDER_OPTIONS, AGENT_PLANNER_MODEL, AGENT_SYNTHESIZER_MODEL, MCP_SERVERS (HTTP only: {"name": {"url": "...", "headers": {...}}} - a secret when its headers carry a token), AGENT_TOOL_APPROVAL, AGENT_TOOL_RULES, SUBAGENTS, PIPELINES (a profile’s or a node’s model is a model id on the same provider), AGENT_MAX_ITERATIONS, AGENT_MAX_STEPS_PER_TASK, AGENT_MAX_REVISIONS, AGENT_MAX_TOOL_CALLS, AGENT_MAX_TOTAL_TOKENS, AGENT_LLM_TIMEOUT_MS, AGENT_LLM_MAX_RETRIES, AGENT_COMPACTION, AGENT_CONTEXT_WINDOW_TOKENS, AGENT_SYSTEM_PROMPT, AGENT_CLIENT_NAME, AGENT_LOG_LEVEL.

Not read here (no meaning on this platform): DATABASE_URL, PG_POOL_MAX, MIGRATE_DATABASE_URL, TEMPORAL_*, GATEWAY_HOST / GATEWAY_PORT, WORKER_*, WORKFLOW_BUNDLE_PATH, TURN_HEARTBEAT_TIMEOUT_MS (the lease TTL is it), SESSION_MAX_TURNS_PER_RUN (no continue-as-new), and every <NAME>_FILE.

Local only - wrangler dev runs the Worker in workerd with Miniflare’s Durable Objects and Workflows; nothing is deployed and no account is needed.

Terminal window
pnpm install && pnpm nx run-many -t build -p @dudko.dev/agent,swarm-shared
cd examples/swarm-cloudflare
cp .dev.vars.example .dev.vars # set GATEWAY_TOKENS and AGENT_API_KEY; never commit it
npx wrangler dev # http://localhost:8787, state in .wrangler/

Talk to it exactly as to the Temporal swarm:

Terminal window
TOKEN=... # one of GATEWAY_TOKENS
S=$(curl -s -X POST localhost:8787/sessions -H "authorization: Bearer $TOKEN" \
-H 'content-type: application/json' -d '{"message":"What is 2+2?"}' | jq -r .sessionId)
curl -N localhost:8787/sessions/$S/events -H "authorization: Bearer $TOKEN"

The local explorer (/cdn-cgi/local/explorer/api/workflows/agent-swarm-turn/instances, printed by wrangler dev) shows every Workflow instance and its steps.

The owner’s steps (this repository never deploys it; there is no Workers Builds project for it):

Terminal window
cd examples/swarm-cloudflare
pnpm nx run-many -t build -p @dudko.dev/agent,swarm-shared # the bundle imports their dist
npx wrangler login # once, the owner's account
npx wrangler secret put GATEWAY_TOKENS # 16+ characters, comma separated
npx wrangler secret put VISITOR_SECRET # GATEWAY_AUTH=visitor only: 32+ characters
npx wrangler secret put AGENT_API_KEY
npx wrangler secret put MCP_SERVERS # when its headers carry a token
# Edit the non-secret vars in wrangler.jsonc (AGENT_PROVIDER_TYPE, AGENT_MODEL, ...), then:
npx wrangler deploy

wrangler.jsonc publishes no workers.dev route and no preview URLs (workers_dev: false, preview_urls: false): add a route or a Custom Domain on purpose (routes), or set workers_dev: true to try it. The first deploy creates the Durable Object classes (migration v1, SQLite) and the four Workflows. A step’s CPU limit is 30 s on the free plan; on the paid plan limits.cpu_ms raises it (up to 300000).

  • The bearer token is checked in constant time (swarm-shared), on the Worker for every route and again in the session’s object for a stream; an unauthenticated stream never reaches (or wakes) an object. It is one shared secret for the whole API - whoever holds it can start, steer and read any session: to serve many users, use GATEWAY_AUTH=visitor (Visitors) or put your own authentication in front.
  • Visitors reach only the sessions they started: the owner is checked first on every route that names a session, and someone else’s session answers exactly as a missing one. A visitor token or cookie is checked (HMAC-SHA256, constant time, expiry with a bounded skew, a maximum lifetime) on the Worker and again in the session’s object for a stream; one in a URL only when bound to its session and expiring within 5 minutes. A visitor answers no parked item unless VISITOR_ANSWER_KINDS says so, and sees the raw event stream (tool inputs and outputs included). The visitors’ writes are rate limited per visitor, address, network and across all visitors (a day’s budget too) before they reach an object.
  • Errors reach a client as one fixed sentence (503) or one word (/readyz); the detail is in the log only.
  • Secrets are Worker secrets, never in wrangler.jsonc and never committed (.dev.vars is gitignored). The key reaches the provider through the model object built in the step; it is in no snapshot, event or log.
  • The data at rest is the conversation: each session’s object holds its events (tool inputs and outputs), snapshots, journal (every model response and tool result) and parked items, in Cloudflare’s storage; Workflow instances hold only ids and statuses (and a pipeline’s definition). Retention: SESSION_RETENTION_DAYS (30 by default) after a session ended (a stop with end, or the idle timer), its object deletes its own storage (deleteAll); from then on its id answers exactly as an id never used - 404 session_not_found on every route, a 404 for its streams. A session that has not ended is never deleted: end the ones you are done with (POST /sessions/:id/stop {"end": true}). An operator who must delete one session’s data sooner sets a shorter retention and ends it - the shared API has no delete route, and Cloudflare offers no command that empties one object; deleting every session at once is a migration that deletes the SessionDO class (deleted_classes). An id nobody created leaves nothing behind: an object’s tables are made only when a session is.
  • Logs: every line the Worker writes (Workers Logs) goes through one filter (src/redact.ts): the message and the fields that carry outside text (error, reason, message, …) have bearer tokens, API keys and key=value secrets redacted and are clipped to 300 characters; the core’s own warnings are logged as such a field, never as the line. Ids and numbers pass as they are. (The Temporal swarm logs these texts verbatim.)
  • Answers are untrusted: checked by the gateway (shape, size, the item’s session, the child’s recomputed id), then by the object’s reducer or the child’s wait, then by the core.
  • The objects are reachable only through this Worker’s bindings: their RPC surface is not public, and it is an allowlist (RPC_METHODS in src/host.ts) - the object’s drain, watchdog and internals are not callable through a stub. A step of a turn (or child) that is over, or of another phase than the one that runs, is told to stop by its next heartbeat or event batch, and its events below its run’s fence are not written.

The workspace project swarm-cloudflare (examples/swarm-cloudflare): typecheck (the Worker against @cloudflare/workers-types, tests and e2e against Node’s), format:check, build (wrangler deploy --dry-run --outdir dist: the bundle exactly as a deploy would upload it - it needs no network at all, checked in an empty network namespace), test, and test:e2e.

Terminal window
pnpm nx run-many -t typecheck format:check build test -p swarm-cloudflare
pnpm nx run swarm-cloudflare:test:e2e # wrangler dev, a few minutes
  • Unit tests (tests/*.test.ts, node --test, in pnpm check): the object’s tables over node:sqlite behind the shape of a Durable Object’s ctx.storage.sql (the fences, the journal, the supersede, the lease, the events, the parked items, the blobs); the session’s object (SessionHost) with the Workflow instances played by the test (every transition, the children, a child’s wait, stop, the idle timer, the outbox, the watchdog); the steps with the real core against the scripted model (a phase, a lost result, parking, a stop, a refusal, both fences against an attempt the engine gave up on, and a renew the object did not answer); the lease as a step keeps it (tests/lease.test.ts: every batch answer that says held is a write, a renew the object did not answer stands only while the lease’s last write holds, never turns “not held” into “held”); the Worker’s gateway and backend and the object’s streams; the configuration, the ids, the limiter; what keeps a session from getting stuck (tests/durability.test.ts: an event never dropped, a start given up failing its turn, the alarm set with the transaction, a crash between the commit and the drain, the watchdog’s own deadline and each of its branches, a zombie step told to stop and its events refused, the idle end of a parked turn, retention, no tables for a made-up id, the RPC allowlist); the Workflow classes themselves with cloudflare:* stubbed and a small engine playing the runtime (tests/workflows.test.ts: a PipelineWorkflow killed in the middle of its graph replays the same steps in the same order, makes none of them again and starts each visit once; a settled wait that timed out is taken again); the log filter (tests/redact.test.ts). The tests that run the real core move their own time (tests/helpers/time.ts: the core’s lease timers, the object’s clock, a step’s clock and its wait for a lease) and hold a slow model at a gate: nothing in them waits on, or races, the clock. Why node --test and not @cloudflare/vitest-pool-workers: the code is written so that everything but the thin cloudflare:* classes runs in Node, so the state transitions and the guards are tested fast and without workerd (and mutation-checked in seconds), with the repository’s one test runner; the platform glue - the bindings, the events between the object and the instances, retries, a killed runtime - is what the e2e run in a real workerd, the bundle that deploys.
  • End to end (e2e/*.test.ts): wrangler dev on a temporary --persist-to, the scripted OpenAI-compatible model of packages/agent/tests/helpers/openai-server.ts, the MCP server of @dudko.dev/test-servers, the HTTP API. Mirrored from examples/swarm’s integration tests: session (a turn end to end, replay from a cursor, Last-Event-ID, live, the refusals - plus the per-session stream cap), parking (park, answer, the write once; a partial answer; stop during a park), crash (a step that throws; the dev server killed mid-step and started again), stop (stop, the next message, end), subagents (two children side by side, the per-round cap, stop while they run), child-parking ((a), (d), (e) - and an answer in another session’s URL), pipelines (a wave, a routed node, the streams; stop while a node runs), and mcp (a structured MCP tool from workerd). Not mirrored: what is Postgres’ or Temporal’s own (postgres.test.ts’s races, continue-as-new, zombie.test.ts’s SIGSTOP - its guarantee is tests/steps.test.ts‘s, with the real core), limits.test.ts (the limiter is unit-tested), the pipelines’ caps and crash test, child parking’s (b), (c), (f), (g) (covered by the unit tests of the shared reducer and of the object).
  • CI: .github/workflows/swarm-cloudflare.yml runs the e2e (ci.yml already runs the four checks with every other project).