Skip to content

Swarm on Google Cloud

The agent swarm of examples/swarm - the same HTTP API, the same session semantics - built on Google Cloud’s own primitives instead of Temporal + Postgres: Firestore (Native mode) holds every session’s state, event log, runs, call journal, leases, parked items, children and an outbox of effects; Cloud Tasks drives the work - one task per turn attempt, per child attempt, per pipeline step and per timer; the Node core @dudko.dev/agent runs in containers on Cloud Run (a gateway service and a worker service, one image) or, from the same code, in Firebase Functions (2nd gen).

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 and the Cloudflare one run.

Nothing in this repository deploys it or talks to Google Cloud. Everything here was built and tested on the Firestore emulator and a stand-in for Cloud Tasks (what that leaves unproven); deploying is the owner’s, by hand (Deploying).

HTTPS, bearer token
clients ──────────────────────► gateway (Cloud Run; swarm-shared's createGatewayHandler)
▲ │ a call = ONE Firestore transaction on the session
│ SSE: replay = a query, │ (the reducer applied; its effects into the outbox),
│ live = a Firestore listener │ then the outbox is drained: tasks are enqueued
└───────────────────────────────┤
▼
Firestore (Native) swarm_sessions/<session> the session: small, the hot doc
a database of its own blobs/ the reducer's state, a phase's input, a child's input
rules: deny every client runs/<run> binding, attempt, fence, snapshot + journal/<entry>
leases/<run> runLease: a TTL by the database's clock
streams/<stream>/events/<cursor> the event log, per stream
parked/ children/ (settled/) phases/ outbox/
swarm_limiter/<bucket> sharedLimits
▲
│ every hook of the agent: persistence + journal,
│ runLease, onEvent (batches), sharedLimits
Cloud Tasks ── OIDC ─────► worker (Cloud Run, internal ingress; the tasks' account only)
swarm-turns POST /tasks/turn one attempt of a turn's phase = one agent.run
(rate, cap) POST /tasks/child one attempt of a subagent call / a pipeline node visit
swarm-control POST /tasks/pipeline one replay of a pipeline (the core's graph engine)
POST /tasks/timer a session's timer: idle end, watchdog, retention
Cloud Scheduler POST /tasks/sweep every minute: the net under all of the above

The single writer is a transaction. There is no process that owns a session (a Temporal workflow, a Durable Object). Every transition - a message, an answer, a stop, a turn’s or a child’s outcome, a timer - is ONE Firestore transaction that reads the session’s document and its state, applies swarm-shared’s reducer, and writes - together or not at all - the state it leaves, the turn.ended and child markers, the parked items, the children, and the effects on Cloud Tasks as documents of an outbox. Two transitions of one session that meet are serialized by Firestore: the later one runs again on what the earlier one left (tests/session.test.ts runs six at once). After the commit the same process makes the effects, in the order they were decided; an effect is a task with a name that is a function of what it runs, and Cloud Tasks refuses a second task of a name - so an effect made twice is one task.

A turn’s attempt is one task, one request. Cloud Tasks POSTs /tasks/turn to the worker; the worker counts the attempt, runs ONE agent.run with every scale-out hook of the agent pointed at Firestore, and reports the outcome to the session (applied once per phase). A run that parks ends its request - nothing runs and nothing is billed while a person decides - and the answer’s transition enqueues the task of the next phase, which resumes the SAME run (resumeFromRunId + answers). A request that dies (the instance went away, the deadline passed) is delivered again by Cloud Tasks, and the next attempt finds the 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 gateway from Firestore. Replay is a query; live is a Firestore listener on the stream’s newest event (see why).

examples/swarm (Temporal + Postgres) Here (Firestore + Cloud Tasks + Cloud Run) Where
the session workflow (signals, query, the loop) a transaction per call on swarm_sessions/<id>: the reducer applied, its state stored (blobs/state), view() for the query src/session.ts
deterministic replay of the session none needed: the state is stored, not replayed (no patched(), no continue-as-new)
Temporal’s “one workflow task at a time” Firestore’s serializable transactions on the session’s document (and, inside one process, a queue per session) src/firestore.ts transact
commands a workflow task emits (start an activity, a child, a timer) the outbox: documents written in the transition’s transaction, made into Cloud Tasks after it; the sweep makes what a dead process left src/host.ts drain, sweep
the runTurn activity, its retries a Cloud Task per phase → POST /tasks/turn; a failed attempt answers 500 and is delivered again; the attempts of a phase are the SESSION’s count (TURN_MAX_ATTEMPTS) src/worker.ts, src/steps.ts
TURN_REFUSED (non-retryable) the worker fails the phase at once and answers 2xx (a refusal, refused credentials, a misconfiguration) src/worker.ts
startToCloseTimeout TURN_TIMEOUT_MS, at most 29 min: a task’s request may take 30. The attempt gives its run up at the limit and the next one resumes it src/worker.ts, src/config.ts
the activity heartbeat = the lease runLease in leases/<run>: a TTL by the database’s clock (LEASE_TTL_MS) from its last write, renewed every TTL/3; a holder that renews is never replaced - a second delivery of its task is answered 503 busy, uncounted - and the run is taken only once the holder’s lease has run out (it is gone). A healthy holder writes its lease at least every TTL/2 (an event batch stands for a renew only if it wrote the lease less than TTL/6 ago), so it survives a stall of half a TTL; a renew Firestore does not answer (busy) stands on the last write it confirmed while the next renew still comes inside that write’s TTL - one bad second does not cost a healthy run its attempt src/store.ts leaseAcquire, leaseSkipMs; src/steps.ts createLeaseRenewer
a user’s stop = activity cancellation the answer of the lease’s renew (and of every event batch): stop → the attempt aborts the run, which records cancelled src/steps.ts
heartbeat timeout → retried elsewhere the watchdog: a phase nobody heard of for 3 TTLs whose task is gone, or handed to a silent worker, is enqueued again under a new name, which carries its generation (r): the task it replaced is answered and dropped if it shows up after all, and a phase enqueued again 10 times fails src/host.ts watchdog, src/session.ts beginAttempt
worker shutdown (revokedReason) SIGTERM: attempts give their runs up, answer 503 (not counted), let their leases go; the next delivery resumes src/worker.ts
swarm_runs (snapshots, fence, supersedeRun) runs/<run>, the same fences, each check and its write in one transaction src/store.ts
swarm_journal (FOR SHARE against the fence) runs/<run>/journal/<entry>; the append reads the run’s fence in the transaction that writes the entry src/store.ts appendJournal
swarm_events + NOTIFY streams/<stream>/events/<cursor> + a Firestore listener per stream per gateway instance src/store.ts, src/feed.ts
swarm_parked parked/<item> (the same rows, the same states) src/store.ts
swarm_sessions the session’s document exists
swarm_limiter (row lock, the database’s clock) swarm_limiter/<bucket>: a transaction, the database’s clock; the bucket math is the same src/limiter.ts
child workflows (startChild, child.result()) tasks the session enqueues from its outbox (/tasks/child); a child reports its outcome to the session src/session.ts, src/worker.ts
a child’s wait (signals into child-state.ts) the same child-state.ts, applied in the session’s transaction; the answer’s transition enqueues the child’s next phase src/session.ts
the pipeline workflow (the engine, replayed by Temporal) a replay per settled visit: the session appends each visit’s outcome to the pipeline’s log in ONE order and enqueues /tasks/pipeline, which runs the engine from the start over that log src/pipeline-run.ts
the workflow’s timer (condition(ready, idleTimeoutMs)) one scheduled Cloud Task per session at its earliest deadline (/tasks/timer) src/session.ts save, timer
workflow / child ids as dedup a task’s name, a digest of turn-<session>-<turn>-<phase> and the like src/tasks.ts
the gateway on node:http the same adapter, on Cloud Run src/http-adapter.ts
.env, *_FILE secrets the services’ env, Secret Manager references (or volumes: *_FILE) deploy/
compose.yaml, the Helm chart Terraform, Cloud Run manifests, firebase.json deploy/, firebase.json
  • Cloud Tasks, not Pub/Sub. A task has a name a second task cannot take (dedup with no store of ours), a schedule time (the idle timer, the watchdog and retention are tasks, not a scheduler of ours), one HTTP request with a deadline and retries with backoff (an attempt that dies is delivered again - the retry the journal was made for), an OIDC identity the worker can check, and a queue has a rate and a concurrency cap (back-pressure, and a spending cap). Pub/Sub offers ordering keys and fan-out, which nothing here needs, and none of those five.
  • A Firestore listener for live events, not polling. An open stream that says nothing costs nothing with a listener; a poll is a billed read every interval, idle or not, and delivers up to an interval late. A listener is billed one document read per commit that moved the stream’s head
    • one per event batch (EVENT_FLUSH_MS), not per event - plus the replay’s reads. One listener per stream per gateway instance, shared by that stream’s readers; SSE_MAX_CONNECTIONS bounds the open streams of an instance and with them its listeners. The handler’s contract holds: a subscription starts “notified” and stays so until its listener’s first snapshot, so what was stored between the replay and the listener coming up is found by one more read (tests/feed.test.ts). An instance that goes away (a scale-in, a new revision) ends its streams; clients reconnect to another with Last-Event-ID and miss nothing.
  • A pipeline is replayed, not kept alive. The core’s graph engine is deterministic by contract; a process that lives as long as a pipeline would be a request held open for nothing. So the pipeline’s log of settled visits is written in the session’s transaction (one order, whatever order the visits’ tasks finished in) and each entry enqueues a replay: the engine runs from the start, is handed the log one entry at a time (waiting between two until it has done all it can), starts the visits it asks for (each once) and writes its events (each once).
  • A sweep under everything. Firestore and Cloud Tasks have no transaction together, so a process can die between its commit and its enqueue. The session’s document says when its outbox is due (outboxAt), and a Cloud Scheduler job (every minute) drains what is overdue - and runs the timers whose task was lost, and deletes the ended sessions past their retention.
  • An agent per attempt (as on Cloudflare): made in the task’s request with its hooks closed over that attempt, closed with it. Simple and stateless; the price is an MCP connection per attempt.

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. The platform’s differences:

  • A 503 says firestore: the store cannot be reached (one fixed sentence; the Temporal swarm’s names no store at all). /readyz (unauthenticated, as there) reads nothing - a Firestore read is billed, and anyone can call /readyz: it says the process is up, its configuration was read, and whether a listener is failing right now.
  • POST /sessions may answer 429 too_many_sessions with Retry-After: at most SESSION_CREATE_PER_MINUTE sessions are started per minute over the whole deployment (60 by default; 0 turns it off). See Security.
  • SSE_MAX_CONNECTIONS counts the open streams of one gateway instance, as in the Temporal swarm. A stream is one request and Cloud Run ends a request after an hour at most: clients reconnect with Last-Event-ID (an EventSource does it by itself).
  • An ended session answers 404 on every route once its retention has passed, whether its documents have been deleted yet or not.

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

  • A turn - phases 0, 1, ... (one per park and resume), each a task named turn-<session>-<turn>-<phase>. A stop while an attempt runs reaches it at its next lease renew or event batch (within half a TTL, 7.5 s by default; at once while it streams events); a stop while it is parked ends the turn at once (its items closed; no task of it exists). A stop between attempts is read by the next attempt before it runs anything.
  • Parking - the attempt reports parked and its request ends; the session records the items (what the gateway checks an answer against), the reducer takes the answers (the authority), and the transition that takes the last one enqueues the next phase. A session that goes idle while its turn is parked ends as a stop with end would end it (as on Cloudflare).
  • Static subagents - SUBAGENTS, as in the Temporal swarm: the tool defers, the session enqueues a /tasks/child 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 session routes the answer to that child’s wait, which is checked again there.
  • Pipelines - PIPELINES: the session enqueues /tasks/pipeline; every node visit is a /tasks/child of its own (its agent.run, then the route call where it ran), a wave started together. A visit’s outcome is appended to the pipeline’s log by the transition that takes it, which enqueues the next replay. The pipeline runs the definition it started with (kept at its first replay), whatever a later deploy sets PIPELINES to.
  • An attempt fails (the provider fails past the agent’s retries, a journal append is refused, a limiter bucket Firestore could not serve - not a refusal: it says nothing of the limit): the worker answers 500, Cloud Tasks delivers the task again with backoff, and the next attempt resumes the run from its last snapshot. Once the phase’s attempts ran out (TURN_MAX_ATTEMPTS, counted in Firestore, not by the queue) the turn fails and the task is done - unless its run is over on record (the last attempt finished it and died before it could say so): then that outcome is reported, not a failure (tests/worker.test.ts). What is guaranteed today: 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)). What is not, until the core’s fix lands (@dudko.dev/agent, PR #90): a run that fails inside a step, after a tool call of that step ran, is resumed under the next iteration’s journal positions - that step’s tool calls run again (at least once, not exactly once). The Temporal and Cloudflare swarms have the same limit; nothing here works around it, and nothing here needs to change when it is fixed.
  • The worker dies mid-attempt (an instance evicted, a new revision, a machine; in the tests: SIGKILL): the request’s connection breaks, Cloud Tasks delivers the task again; the dead attempt’s lease runs out (it renews no more), the next attempt takes the run, raises its fence and resumes it - the write the dead attempt made is answered from the journal (e2e/crash.test.ts (b)).
  • The worker is told to stop (SIGTERM: a scale-in, a new revision): its attempts give their runs up as a lost lease (the core writes nothing more), let the leases go and answer 503; the attempt is not counted, and the next delivery resumes at once (e2e/platform.test.ts).
  • An attempt over its time (TURN_TIMEOUT_MS): the same, counted as an attempt. A turn longer than one request may take is therefore not lost - it goes on in the next attempt, from the journal - but each such cut spends one of TURN_MAX_ATTEMPTS.
  • An attempt Cloud Tasks still waits for, that says nothing (a paused or partitioned instance): it renews its lease no more, the watchdog finds its phase silent and enqueues the task again under a new name. The next attempt waits for the lease to run out, then: before the first snapshot it supersedes the run - the old attempt’s next journal append is refused and the core stops it before any tool call it makes runs; after its plan, it raises the run’s fence and resumes: nothing of the old attempt is written again - no snapshot, no journal entry, no event (e2e/zombie.test.ts, tests/steps.test.ts). What no fence undoes is a tool call the old attempt had already started.
  • A task is delivered twice while its attempt is alive (Cloud Tasks delivers at least once; the watchdog enqueued a task again whose attempt was only slow to get as far as its lease): the second delivery finds the run’s lease held and renewed, waits one TTL to be sure, and answers 503 busy - not counted, nothing run, the attempt untouched. Cloud Tasks brings it back with backoff; by then the phase has its outcome (2xx, done) or its attempt died (resumed). A duplicate never stops a healthy attempt and never re-runs its tool call (tests/steps.test.ts, tests/worker.test.ts). The cost: a duplicate holds one of the worker’s attempt slots for about 1.25 lease TTLs each time it comes.
  • The worker dies in the middle of a Firestore transaction: Firestore keeps the locks of a transaction nobody will finish for up to a minute (the emulator does the same: measured, 60 s). Until then a delivery that needs one of those documents cannot take the run: it waits out the transaction’s own retries and answers 503 busy - not an attempt (isStoreBusy: gRPC ABORTED, UNAVAILABLE, DEADLINE_EXCEEDED before the run was taken). The watchdog may enqueue the phase again meanwhile; none of that spends the phase’s attempts, because the count is of attempts that are over: one whose task a worker still holds is under way, for the watchdog (spent) and for the worker (othersUnderWay) alike. A phase fails for its attempts only when that many really ended in failure - or when it was enqueued again ten times (e2e/crash.test.ts (b) meets this now and then; tests/worker.test.ts).
  • The result was lost (the run ended, the report did not arrive): the next attempt finds the snapshot complete (or waiting) and reports it without running anything. That holds for a delivery that comes after the attempts ran out too, and a delivery that finds the count over the limit while an attempt is alive (it holds the run’s lease) is told busy: it fails nothing.
  • A task is lost (the queue dropped it after its own attempts, somebody purged the queue): the watchdog enqueues it again (e2e/platform.test.ts); out of attempts, the turn fails.
  • An effect cannot be made (Cloud Tasks is briefly unavailable): retried with backoff, in order. A task that starts a turn or a child is given up after 12 tries and what it would have run fails, so the session goes on; any other task (a resume, a pipeline’s next step, a timer) is never given up - dropping one would leave the session “running” for something nobody will finish.
  • A process dies between its commit and its enqueue: the effects are in Firestore; the sweep (every minute) makes them.

Firestore’s limits, and what is done about each

Section titled “Firestore’s limits, and what is done about each”

Each limit, then what is done about it.

  • A document holds 1 MiB. Values that may be larger - the reducer’s state, a run’s snapshot, a journal entry, a phase’s input, a child’s input - are blobs: JSON text in parts of 230,000 characters (under 700 kB each). One part lives in its owner’s document; several are written before the transaction that names them, under a fresh version, and the transaction writes only the pointer - a reader never sees half a value. Parts nothing names any more (the value before, a write that was refused or never committed) are not deleted at once: a reader may still hold the pointer of the value before, and a commit can go through without the writer learning it (the SDK then runs the transaction again). They are collected by age - ten minutes, more than a transaction lives - after later writes of the same owner (at most once a minute per owner and process); a reader that still loses a part reads the pointer again once. What is left when the writes stop (at most the last ten minutes’ superseded values of a run) goes with the session at its retention. A stored event is capped by EVENT_MAX_BYTES (a stub beyond); a turn.ended marker over the cap keeps its fields with the long texts cut (truncated); a parked item’s question over a part’s size is stored as a stub.
  • A transaction’s request holds 10 MiB (and, formerly, 500 writes). Big values go in by pointer (above), so a transition’s transaction is small whatever the state’s size. Event batches are cut by bytes (4 MB) and by count; a transaction of more than 400 writes is refused before it is sent.
  • A document should not be written more than about once a second for long. The session’s document - the hot one - is written once per transition (a message, an answer, an outcome) and once more when its outbox is drained; never per event, never per heartbeat. Events are documents of their own. A lease is written at most every sixth of its TTL however often event batches ask (leaseSkipMs; the core’s own renew, every third, writes it when no batch did lately). A limiter bucket is written once per model call: at more than about a call a second for long, use LIMITER_SCOPE=model to spread it. The creation limit’s bucket is written once per POST /sessions.
  • Ids in sequence slow a range down (about 500 writes/s). An event’s id is its cursor, so a stream’s events are in sequence - within one stream. One attempt writes at most a few hundred events a second in bursts (batched by EVENT_FLUSH_MS); raise it for chattier models. Task ids are digests (no common prefix), as Cloud Tasks asks.
  • Transactions that meet. Firestore runs the later one again (up to 10 times here, with its own backoff). Inside one process the transitions of a session are queued instead, so a pipeline’s wave of starts does not fight itself. A transition that still cannot commit answers 503 to the client (a retry is safe: every call is idempotent).
  • Reads before writes in a transaction. The session’s logic reads what it wrote a moment ago; a transaction here buffers its writes and reads them back from the buffer (Uow).
  • Index entries are written with every document. The large, never-queried fields are exempt from indexing (deploy/firestore.indexes.json, Terraform’s google_firestore_field). There is ONE composite index (parked: answeredBy + ord); everything else is a get, a single-field order, or equalities.
  • A Cloud Task holds 1 MB, a schedule time at most 30 days ahead, a request at most 30 min. A task carries ids only (the worker reads its input from Firestore). A later deadline is scheduled for the last day it may be; that task finds nothing due and arms the next. TURN_TIMEOUT_MS is at most 29 min.

Nothing here was measured on Google Cloud; these are the things that grow.

  • Firestore writes: one document per stored event (a streaming model emits many text.delta events: this is the largest number by far), two journal entries per model or tool call, a snapshot per planned step, a lease write every LEASE_TTL_MS / 3 per running attempt (every sixth while it streams events), about five documents per transition. Reads: one per event replayed to each stream reader, one per event batch per open stream (the listener), a handful per transition, three per event batch (the run’s fence, the stop flag, the lease).
  • Storage: every model response and tool result is stored twice (the journal and the snapshot) and once more as events. SESSION_RETENTION_DAYS deletes an ended session whole; a session that never ends is never deleted - set SESSION_IDLE_TIMEOUT_MS.
  • Cloud Run: the worker is billed for every second an attempt’s request is open - including the seconds it waits for the model. WORKER_MAX_CONCURRENT_TURNS (attempts per instance) is the lever: attempts are mostly waiting, so many fit one CPU. The gateway is billed while any stream is open on an instance.
  • Cloud Tasks / Scheduler: a task per attempt, per pipeline step, per timer; a sweep a minute (43,200 invocations a month, each three small queries).
  • What bounds a runaway: the turns queue’s max_dispatches_per_second and max_concurrent_dispatches (Terraform: turns_per_second, the workers’ capacity), SESSION_CREATE_PER_MINUTE, SESSION_MAX_QUEUED_MESSAGES, the agent’s own AGENT_MAX_TOTAL_TOKENS / AGENT_MAX_TOOL_CALLS, LIMITER_*, and Cloud Run’s max_instances.

One codebase, two ways to run it. Both handlers are (request: Request) => Promise<Response> behind the same node:http adapter.

Cloud Run (recommended) Firebase Functions, 2nd gen
What runs the image (Dockerfile): gateway and worker services src/functions.ts: gateway and worker HTTP functions, bundled by build into dist/functions
The core it runs the one in this tree (the image builds it) the one published on npm at the version of packages/agent - Firebase installs dependencies from npm; a change to the core that is not released is not in a deployed function
What it installs pnpm-lock.yaml’s (pnpm install --frozen-lockfile, then pnpm deploy --prod) pnpm-lock.yaml’s too: dist/functions/package.json names every dependency at one exact version, and dist/functions/package-lock.json (made from pnpm-lock.yaml by build) pins everything under them - Google’s build runs npm ci when the source has one
Event streams yes, up to 60 min per request yes (a 2nd gen function streams its response), up to 60 min per request (timeoutSeconds: 3600)
An attempt’s time 30 min (Cloud Tasks’ deadline) the same
Concurrency per service (containerConcurrency: 250 / 20 - the worker’s is its 10 attempts plus 10 slots for control tasks and the sweep) per function (concurrency: 250 / 20, the same)
The worker is not public ingress: internal + roles/run.invoker for the tasks’ account only + the OIDC check in code invoker: 'private' (then grant the tasks’ account) + the OIDC check in code; no internal-only ingress from firebase.json - set it on the underlying Cloud Run service if you want it
The runtime distroless, uid 1000, nothing writable but /tmp, no shell Google’s Node.js buildpack image
stdio MCP servers the command must be in the image (the distroless one has only node) only what npm ci brings
Secrets Secret Manager references in the service secrets: [...] on the function (firebase functions:secrets:set)
Cold starts min_instances (Terraform) minInstances (add it in src/functions.ts)

Both the gateway and the worker make sense as functions: a 2nd gen function is a Cloud Run service. What you give up is the hardened image and the build from this tree. The OIDC audience of a function is its https://<region>-<project>.cloudfunctions.net/worker (or run.app) URL: set WORKER_URL to exactly what Cloud Tasks is told to call. Not supported on Functions here: the Cloud Run manifests’ internal ingress, and a core newer than the published one.

Everything comes from the environment. The names are examples/swarm’s wherever the meaning is the same; a bad value stops the process at start with the variable’s name in the log. A secret may also be given as a file (<NAME>_FILE: a Secret Manager secret mounted as a volume).

The platform (both roles)

Variable Default
GOOGLE_CLOUD_PROJECT - (required) The project id (GCLOUD_PROJECT / GCP_PROJECT are read too)
FIRESTORE_DATABASE (default) The Firestore database (Terraform makes swarm)
FIRESTORE_PREFIX swarm The collections’ prefix: <prefix>_sessions, <prefix>_limiter
CLOUD_TASKS_LOCATION - (required) The queues’ region
CLOUD_TASKS_QUEUE_TURNS / _CONTROL swarm-turns / swarm-control The queue of attempts; the queue of pipeline steps and timers
WORKER_URL - (required) The worker’s base URL: where tasks POST, and (by default) the audience of their OIDC tokens. https://
WORKER_AUTH oidc How the worker knows a task: oidc (Cloud Tasks’ identity token), or local-secret - local only
TASKS_SERVICE_ACCOUNT - (required with oidc) The service account Cloud Tasks and Cloud Scheduler sign their requests as
WORKER_OIDC_AUDIENCE WORKER_URL The audience a task’s token must carry
LEASE_TTL_MS 15000 The run lease’s TTL (renewed every third of it, written at least every half while the holder is healthy - its margin for a stall; a stop reaches an attempt within half of it); what TURN_HEARTBEAT_TIMEOUT_MS is to the Temporal swarm. The watchdog looks every four TTLs and is patient for three
EVENT_MAX_BYTES 262144 One stored event’s cap (at most 900000)
LOG_LEVEL info One JSON line per entry (Cloud Logging), redacted

Local only - refused unless SWARM_LOCAL=true, and SWARM_LOCAL=true is refused on Google Cloud (K_SERVICE, FUNCTION_TARGET, … set):

Variable
SWARM_LOCAL The one switch for everything below
FIRESTORE_EMULATOR_HOST The Firestore emulator (the SDK reads it; without SWARM_LOCAL the process refuses to start)
CLOUD_TASKS_ENDPOINT A stand-in for the Cloud Tasks API (no access token is sent to it)
WORKER_AUTH=local-secret, WORKER_LOCAL_SECRET A shared secret (16+ characters) in a header instead of the OIDC token
GATEWAY_AUTH=none No bearer token

The gateway

Variable Default
GATEWAY_AUTH bearer
GATEWAY_TOKENS - (required; a secret) Bearer tokens, comma separated, 16+ characters each; a placeholder (change-me...) is refused
GATEWAY_HOST / GATEWAY_PORT 0.0.0.0 / 8080 Cloud Run’s PORT wins over GATEWAY_PORT
CORS_ORIGINS none Allowed browser origins (exact), or *
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 200 Open event streams per instance (more: 503); keep it under the service’s concurrency
SSE_KEEPALIVE_MS / SSE_BATCH 15000 / 500
SESSION_CREATE_PER_MINUTE 60 Sessions the whole deployment may start in a minute (429 beyond); 0: no limit
SESSION_RETENTION_DAYS 30 An ended session’s documents are deleted this long after it ended; 0 keeps them. Fixed when the session starts

A session’s options - fixed when it starts (its document keeps them); read by the gateway:

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 1740000 One attempt of a turn; at most 1740000 (a task’s request may take 30 min). The Temporal swarm’s default, 1800000, is refused here
TURN_MAX_ATTEMPTS 5 Attempts of one phase
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 worker

Variable Default
WORKER_HOST / WORKER_PORT 0.0.0.0 / 8081 Cloud Run’s PORT wins
WORKER_MAX_CONCURRENT_TURNS 10 Attempts one instance runs at once (more: 429, the task comes back later). Set the service’s request concurrency above it (the manifests and Terraform add 10): the control queue’s tasks and the sweep come to the same service and must not wait behind attempts
WORKER_SHUTDOWN_GRACE_MS 8000 How long a worker told to stop waits for its attempts to give their runs up (Cloud Run gives ten seconds)
EVENT_FLUSH_MS 500 How long an attempt buffers its run’s events before one write sends them
LIMITER_REFILL_PER_SECOND, LIMITER_CAPACITY, LIMITER_MAX_WAIT_MS, LIMITER_SCOPE off sharedLimits, as in the Temporal swarm (a Firestore document per bucket)
CHILD_ASK park park / deny

The agent (the worker) - 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 example installs), 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 {"url": ..., "headers": {...}} and stdio {"command": ..., "args": [...]}, as in the Temporal swarm - 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.

Everything else of the Node core works here as in the Temporal swarm - web_fetch / egress, the run_js sandbox, worker-thread subagents - and, as there, none of it has a variable: build the config in code (agentSetupFromEnv(env, extra)).

Not read here (no meaning on this platform): DATABASE_URL, PG_POOL_MAX, MIGRATE_DATABASE_URL, TEMPORAL_*, WORKER_IDENTITY, WORKER_HEALTH_PORT, WORKER_HEARTBEAT_THROTTLE_MS, WORKFLOW_BUNDLE_PATH, TURN_HEARTBEAT_TIMEOUT_MS (the lease TTL is it), SESSION_MAX_TURNS_PER_RUN (no continue-as-new).

Emulators only: the Firestore emulator (a Java program - Java 21) and a stand-in for Cloud Tasks that this example brings. No Google account, no credentials, nothing deployed.

Terminal window
pnpm install && pnpm nx run-many -t build -p @dudko.dev/agent,swarm-shared
cd examples/swarm-gcp
pnpm emulator:install # once: the Firestore emulator's jar (137 MB, checksum pinned)
cp .env.example .env # set GATEWAY_TOKENS and AGENT_API_KEY; never commit it
pnpm dev # the emulator, the tasks stand-in, the gateway (:8080), the worker (:8081)

Talk to it exactly as to the Temporal swarm:

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

Nothing is kept when it stops (the emulator holds its data in memory).

The owner’s steps. This repository never runs any of them, and its CI holds no Google credentials. Terraform makes everything but the secrets’ values and the image.

Terminal window
cd examples/swarm-gcp/deploy/terraform
cp terraform.tfvars.example terraform.tfvars # project_id, region, firestore_location, worker_env
gcloud auth application-default login # the owner's own credentials
terraform init # the provider is pinned (.terraform.lock.hcl)
# 1. Everything but the services: the APIs, the database with its indexes, TTL policies and
# rules, the queues, the service accounts and their roles, the (empty) secrets, the registry.
terraform apply
# 2. The secrets' values - never in Terraform (they would be in its state), never in a file here.
printf '%s' "$(openssl rand -hex 32)" | gcloud secrets versions add swarm-gateway-tokens --data-file=-
printf '%s' "$PROVIDER_API_KEY" | gcloud secrets versions add swarm-agent-api-key --data-file=-
# 3. The image, from the repository's root, pushed by digest.
cd ../../../..
REPO=$(terraform -chdir=examples/swarm-gcp/deploy/terraform output -raw image_repository)
gcloud auth configure-docker "${REPO%%/*}"
docker build -f examples/swarm-gcp/Dockerfile -t "$REPO/agent-swarm-gcp:v1" .
docker push "$REPO/agent-swarm-gcp:v1"
DIGEST=$(docker inspect --format '{{index .RepoDigests 0}}' "$REPO/agent-swarm-gcp:v1")
# 4. The services and the sweep's job.
cd examples/swarm-gcp/deploy/terraform
terraform apply -var deploy_services=true -var "image=$DIGEST"
terraform output gateway_url
# Check: the URL the worker was told (the deterministic form; an OIDC audience must match it) is
# one Cloud Run serves it at. Not verified against a real project here - if it prints false, set
# WORKER_URL and WORKER_OIDC_AUDIENCE from `terraform output worker_service_urls`.
terraform output worker_url_served

Instead of step 4, the services can be deployed from the manifests (fill in the UPPER_CASE values from Terraform’s outputs), and the sweep’s job by hand:

Terminal window
gcloud run services replace deploy/cloudrun/worker.service.yaml --region "$REGION"
gcloud run services replace deploy/cloudrun/gateway.service.yaml --region "$REGION"
gcloud run services add-iam-policy-binding swarm-worker --region "$REGION" \
--member "serviceAccount:swarm-tasks@$PROJECT.iam.gserviceaccount.com" --role roles/run.invoker
gcloud run services add-iam-policy-binding swarm-gateway --region "$REGION" \
--member allUsers --role roles/run.invoker # only if the API is to be public
gcloud scheduler jobs create http swarm-sweep --location "$REGION" --schedule '* * * * *' \
--uri "$WORKER_URL/tasks/sweep" --http-method POST \
--oidc-service-account-email "swarm-tasks@$PROJECT.iam.gserviceaccount.com" \
--oidc-token-audience "$WORKER_URL"

Firebase Functions instead of Cloud Run (keep Terraform’s first apply for the database, the queues, the accounts and the secrets):

Terminal window
pnpm nx build swarm-gcp # dist/functions: the bundle, its package.json (exact
# versions) and package-lock.json (all of it pinned)
cd examples/swarm-gcp
firebase login # the owner's account
firebase use "$PROJECT"
firebase functions:secrets:set GATEWAY_TOKENS
firebase functions:secrets:set AGENT_API_KEY
# The plain variables: dist/functions/.env (GOOGLE_CLOUD_PROJECT is set by the platform;
# FIRESTORE_DATABASE, CLOUD_TASKS_LOCATION, WORKER_URL = the worker function's URL,
# TASKS_SERVICE_ACCOUNT, AGENT_PROVIDER_TYPE, AGENT_MODEL, ...). It is rebuilt with dist: keep
# your copy elsewhere and copy it in after each build.
firebase deploy --only functions:swarm,firestore # Google's build: `npm ci` from the lockfile
# Then let the tasks' account - and nobody else - invoke the worker function:
gcloud functions add-invoker-policy-binding worker --region "$REGION" \
--member "serviceAccount:swarm-tasks@$PROJECT.iam.gserviceaccount.com"

firebase deploy --only firestore also publishes deploy/firestore.rules and deploy/firestore.indexes.json - the same rules and indexes Terraform sets (a test keeps the two in step); use one of them for those.

  • The API’s bearer token is checked in constant time (swarm-shared) before anything else: an unauthenticated request reads nothing from Firestore (tests/gateway.test.ts runs every route against a store that fails the test if it is touched). It is one shared secret for the whole API - whoever holds it can start, steer and read any session: put your own authentication in front before serving several users.
  • The worker is not a public endpoint. It runs turns, ends sessions and deletes them, so every /tasks/* request must be Cloud Tasks’ (or the sweep’s): the worker verifies the request’s OIDC identity token itself - RS256 only, a key Google publishes, the issuer, the audience (this worker: a token minted for any other service is refused), the tasks’ service account’s verified email, the expiry - before it reads the body and before anything touches Firestore (src/task-auth.ts; every guard has its token in tests/task-auth.test.ts). In front of that, Cloud Run’s own locks: internal ingress, and roles/run.invoker for the tasks’ account only - an account whose one permission is that. Its surface is five routes; there is no other way into the session logic through it. The local stand-in for all this is a shared secret in a header, refused unless SWARM_LOCAL=true, which is itself refused on Google Cloud.
  • A task carries ids, and a child only of its own session: a session id is checked against the API’s id pattern, a child’s workflow id must be one the session’s id names (subagent-<session>-...), numbers are numbers. A task for a session nobody created does nothing and writes nothing.
  • Tenant isolation is the path. Everything of a session is under swarm_sessions/<id>, and every reference is built from the id by one module (src/firestore.ts), which refuses an id that is not an id (a / would name another path). A parked item is looked up under its session and checked against it; a child’s answer goes only to the child the session named (childOwnerOf, swarm-shared).
  • Nothing reaches Firestore but the services. The security rules deny every client everything (deploy/firestore.rules); the two service accounts get roles/datastore.user on the swarm’s database only (an IAM condition), the right to create tasks on the swarm’s two queues only, and their own secrets.
  • Secrets are Secret Manager’s: referenced by the services, never in a manifest, a variable file or Terraform’s state (it makes the secret, the owner adds the version). The provider key reaches the provider through the model object built in the attempt; it is in no snapshot, event or log.
  • The fences keep an attempt that lost its run from writing: a snapshot below the attempt on record or below the run’s fence is refused, so is a journal entry, and so is an event; a lease is taken from its holder only once it ran out, never while the holder renews; a heartbeat of a phase that is not the current one answers stop. Each check and the write it guards are one transaction.
  • Logs: every line 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 a field, never the line. A task request that is refused logs why (audience, signature, …) and answers nothing. The Cloud Tasks client never quotes the API’s answer (it can echo the request, and with it the local secret).
  • What a client is told of a failure: the model’s or a tool’s error as it is - never what Google Cloud said. A Firestore, Cloud Tasks or auth-library error (an IAM denial names the project and the service account; others the database or the queue), anywhere in an error’s chain, fails a turn with one fixed sentence (worker.ts failureText); the hooks the core calls (snapshots, the journal, the lease, the limiter) throw a PlatformError with a fixed message in its place, so the core’s own errors and log events - which reach the stream - quote nothing of it. The worker’s log has the text (redacted). tests/worker.test.ts pins it with an IAM denial.
  • /healthz and /readyz (both services, unauthenticated) read nothing from Firestore and call nothing: a wrong worker configuration answers one word, the log has the reason.
  • Denial of wallet. The shared API has no per-user quota (it has one token): what bounds the spend of a leaked token or a loop is the deployment’s - SESSION_CREATE_PER_MINUTE (a global bucket; 429 beyond), SESSION_MAX_QUEUED_MESSAGES per session, the turns queue’s rate and concurrency caps (attempts started per second and running at once, whatever is asked for), the agent’s own token and tool-call budgets, the workers’ max_instances. A per-user or per-token quota belongs in the authentication you put in front.
  • The data at rest is the conversation: each session’s documents hold its events (tool inputs and outputs), snapshots, journal (every model response and tool result) and parked items; Cloud Tasks holds only ids.

SESSION_RETENTION_DAYS (30 by default) after a session ended - a stop with end, or the idle timer - its documents are deleted: every subcollection under it, to any depth, then its own document. From its deadline on its id answers 404 on every route, whether the deletion has run yet or not. The deadline is the session’s timer task; the sweep deletes what a lost task left. A session that has not ended is never deleted: end the ones you are done with, or set SESSION_IDLE_TIMEOUT_MS.

Why not a Firestore TTL policy on the sessions: a TTL deletes one document and never what is under it - a TTL on the session’s document would remove the one handle to its events, journal and snapshots and leave them behind, unreachable. TTL policies are used where a document stands alone: a lease nobody released (its worker died) and a limiter bucket nobody draws from (deploy/terraform/firestore.tf). An operator who must delete one session’s data sooner ends it with a short retention, or deletes it by hand: firebase firestore:delete --database swarm -r swarm_sessions/<id>.

  • Interactive MCP OAuth, MCP elicitation, remember on an approval, steering inside a turn: as in examples/swarm.
  • A run that fails in the middle of a step re-runs that step’s tool calls (the core’s limit, PR #90; see What happens on a crash).
  • One attempt is one request of at most 29 minutes. A longer turn continues in the next attempt (from the journal), spending one of TURN_MAX_ATTEMPTS each time; a single model call or tool call longer than that can never finish.
  • A stopped or failed attempt’s in-flight tool call is not undone: the journal closes every window but the one between a tool’s side effect and its result being on record.
  • An agent per attempt: MCP servers are connected to at every attempt (a stdio server is started at every attempt).
  • The watchdog’s patience is three lease TTLs: an attempt that needs longer than that to get as far as its lease (a very slow MCP server start) is enqueued a second time. The redrive then IS the phase’s task: the first delivery goes on if it is alive (the redrive is told busy and comes back), but should it fail, its own retry is answered and dropped and the redrive resumes the run. Nothing runs twice; it costs a worker slot for a lease’s wait.
  • No per-session cap on open streams (Cloudflare’s port has one): the cap is per gateway instance.
  • Firestore’s own limits as handled above: one stored event at most 900 kB, a parked item’s question at most a part, about a write a second per bucket for the limiter.

What was only tested on emulators and fakes

Section titled “What was only tested on emulators and fakes”

Everything. Nothing here has run on Google Cloud. What that means, concretely:

  • Firestore: the emulator enforces the 1 MiB document size (seen), serializes transactions and delivers listeners - but it does not enforce the 10 MiB transaction size, it needs no indexes (a missing composite index, or an index exemption that breaks a query, shows only on the real service: there is one composite index and the queries are few - check the first GET /sessions/:id/subagents), its contention behaviour and latency are not the service’s (real lock waits, real ABORTED rates under load, the 270 s transaction limit), and TTL policies do nothing in it.
  • Cloud Tasks: a fake of its REST contract (tests/helpers/tasks-fake.ts, whose header lists it): the real rate limiting and the queue-wide slow-down a 429 / 503 from the worker starts, how long a name stays taken, task size limits, real OIDC tokens and Google’s key rotation, IAM (cloudtasks.enqueuer, acting as the tasks’ account), what exactly tasks.get reports while a request is in flight and after one nobody answered (the watchdog reads “the last attempt has a dispatch time and no response time, and the task is not scheduled for later” as handed out - from the documentation of Task.lastAttempt, never seen on the service), and how often Cloud Tasks really delivers a task twice (the code assumes it may, at any moment).
  • Cloud Run: that Cloud Tasks and Cloud Scheduler of the same project pass ingress: internal; the deterministic service URL Terraform computes (step 4 of Deploying checks it); how a request open for 29 minutes and an SSE stream behave behind Google’s front end (buffering, idle timeouts); CPU throttling between requests; the ten seconds after SIGTERM; the image itself on Cloud Run’s sandbox (it was built and started locally: read-only root, uid 1000).
  • Firebase Functions: src/functions.ts is typechecked and bundled, and the bundle’s dependency list is tested: exact versions, and a lockfile in which every dependency of every package resolves, where npm looks, to the version pnpm-lock.yaml resolved, with its integrity (tests/deploy.test.ts). It was never loaded by the Functions runtime or deployed. That Google’s build installs it with npm ci is the Node.js buildpack’s documented rule, not seen; npm ci of it warns that @firebase/database (under firebase-admin 14) asks for Node 24.12 while the functions run on nodejs22. Streaming through a function, invoker: 'private' with Cloud Tasks, and the installed @dudko.dev/agent from npm matching this tree are all unproven.
  • Terraform: fmt and validate pass (the configuration is well-formed against the provider’s schema). No plan was ever made: IAM conditions on roles/datastore.user, the Firestore rules release’s name for a named database, and API enablement order are the places a first apply is most likely to object.
  • Costs and performance: not measured at all.

The workspace project swarm-gcp (examples/swarm-gcp): typecheck, format:check, build (the Firebase Functions bundle, offline), test and test:e2e.

Terminal window
pnpm --filter swarm-gcp emulator:install # once
pnpm nx run-many -t typecheck format:check build test -p swarm-gcp
pnpm nx run swarm-gcp:test:e2e # a few minutes

test and test:e2e start the Firestore emulator themselves (scripts/with-emulator.mjs) and stop it. Without the emulator (no Java, or the jar not installed) the unit tests that need Firestore skip, saying why - the others run - and the script says so in a banner before and after the run (and as a warning annotation on GitHub Actions: the repository’s ci.yml has no Java set up for it, so most of this suite skips there). REQUIRE_FIRESTORE_EMULATOR=1 makes that a failure (swarm-gcp.yml sets it: that workflow is where they run), and the end-to-end tests always require it.

  • Unit tests (tests/*.test.ts, node --test, in pnpm check): the store on the emulator (store.test.ts: the transaction wrapper, blobs larger than a document, every fence, the journal’s order and its race against a fence, the lease by a test clock and by the database’s, events, parked items, the limiter); the session with the tasks played by the test (session.test.ts: every transition, six at once, children and their waits, the outbox and a process that dies before its drain, the timer, the watchdog, retention, no document for a made-up id); the attempts with the real core against the scripted model (steps.test.ts: a phase, a lost result, parking, a stop, a refusal, an attempt over its time, both fences against an attempt that lost its run, and - on the core’s lease clock, moved by the test - a renew Firestore does not answer); how an attempt keeps its lease (lease.test.ts: what a renew is answered, a batch’s write, a healthy holder’s margin at the worst moments for a batch); a pipeline’s replay (pipeline.test.ts); the task driver against the Cloud Tasks stand-in (tasks.test.ts); the worker’s auth (task-auth.test.ts) and its handler (worker.test.ts); the gateway over Firestore (gateway.test.ts); the listener feed (feed.test.ts); the configuration, the limiter’s math, the log filter; and what is deployed, as text (deploy.test.ts: also the functions’ exact versions and their lockfile).
  • End to end (e2e/*.test.ts): the gateway and the worker as real processes (node src/main.ts ...), the emulator, the Cloud Tasks stand-in delivering over real HTTP, the scripted OpenAI-compatible model of packages/agent/tests/helpers/openai-server.ts, the MCP server of @dudko.dev/test-servers. Mirrored from examples/swarm’s integration tests (and the Cloudflare port’s e2e): session (a turn end to end, replay from a cursor, Last-Event-ID, live, the refusals, the stream cap), parking (park, answer, the write once; a partial answer; stop during a park), crash (a failure between steps; the worker killed mid-step), zombie (a worker paused with SIGSTOP before its first snapshot and woken after the turn ended elsewhere), stop, subagents (two children side by side, the per-round cap, stop while they run), child-parking ((a), (d), (e)), pipelines (a wave, a routed node, the streams; stop while a node runs), limits (the shared bucket refuses a call: the turn fails, not retried), mcp, and platform (the worker refuses what is not a task; SIGTERM hands a turn over; a lost task; the sweep; the idle timer). Not mirrored: what is Postgres’ or Temporal’s own (postgres.test.ts’s races - their counterparts are in store.test.ts -, continue-as-new), subagents-crash and pipelines-crash (a child’s attempt is the same code path as a turn’s, covered by crash; a pipeline’s replay killed half way is pipeline.test.ts‘s), the pipelines’ caps, child parking’s (b), (c), (f), (g) (the shared reducer’s unit tests and session.test.ts).
  • CI: .github/workflows/swarm-gcp.yml - the checks and every test with the emulator, the image built (never pushed) and started read-only, Terraform’s fmt and validate. No Google credentials.