Skip to the page

Guides · Agents & copilots

Durable loops and swarms

Checkpoint long-running agent loops so they pause at zero idle compute, and coordinate multi-agent swarms on one database record with atomic task claims and caller-tree budgets.

API
—
In the schema
—

What you’ll build#

You will build a two-part agent workflow: first, a refund agent that checkpoints every turn in Napalm and pauses for hours awaiting human approval with zero idle compute, and second, a three-agent swarm (triage lead, researcher and writer) collaborating on one customer ticket with atomic exclusive task claims and strict caller-tree budgets.

Sleep-to-zero loops
Persist turn state inside Napalm, exit your worker process completely during long waits and resume hours later with exact checkpoint state.
Policy-bound blackboards
Attach a shared blackboard directly to any record in your schema so only callers who can access that record can read or claim swarm work.
Hierarchical budgets
Cap total calls and tokens at the orchestrator level and carve attenuated sub-budgets for each specialist worker.

What sleep-to-zero loops unlock#

Real-world agents rarely finish in one HTTP request. A refund agent waits six hours for a finance manager to click approve. A vendor-onboarding agent waits two days for a webhook callback. Holding worker processes open in memory across those waits wastes compute and loses progress whenever a container restarts. Running a separate workflow cluster such as Temporal or a LangGraph server solves persistence, yet leaves you managing another stateful service that knows nothing about your database’s access policies or caller credentials.

Napalm’s durable loops (client.agentLoops and napalm loops) store every turn checkpoint right inside your branch as ext::napalm::AgentLoopCheckpoint records under the caller’s identity, so your app can query and live-subscribe to loop progress directly with EdgeQL.

ConcernLong-lived workers or external workflow serverNapalm sleep-to-zero loops
Idle compute and wakeupsWorker processes sit blocked in memory, poll on a timer or require a separate workflow engine cluster.Napalm sleep-to-zero loopsThe worker checkpoints state and exits immediately. Set optional wakeupAction and wakeupPayload on POST /agent-loops or pause requests so the engine automatically resumes the paused loop and invokes wakeupAction when a referenced require approval decision commits or a scheduled timer expires without external polling.
Duplicate step retriesProcess restarts re-run model calls or tool writes unless you build your own idempotency table.Napalm sleep-to-zero loopscheckpoint() keys every step by (turnIndex, stepKey) across turn_start, model_call, tool_call, tool_result and state_snapshot, deduplicating retries automatically.
Concurrent resumesTwo webhook retries or workers can race and execute the next turn twice.Napalm sleep-to-zero loopsResuming requires a matching constant-time token (approvalId, callbackKey or toolCallId) plus optimistic version checks (409 loop_version_conflict) so a paused turn wakes once.
EdgeQL visibility and credentialsExternal workflow engines hide step history behind custom APIs and replay jobs as a single privileged service account.Napalm sleep-to-zero loopsEach session preserves its original caller identity and traceId, and every checkpoint lives in ext::napalm::AgentLoopCheckpoint for direct EdgeQL queries and live subscriptions.

Checkpointing and resuming a refund agent#

In this scenario, a refund agent starts a durable loop for ticket #4812 with wakeupAction: 'billing.resume_refund' and wakeupPayload, verifies invoice inv_981 in turn 1 and submits a $1,200 refund mutation. Your schema’s escalating approval policy holds refunds over $500 and answers 202 approval_required with an approvalId. The loop enters a zero-compute paused state tagged awaiting_approval, and the worker process shuts down cleanly.

Hours later, a finance reviewer approves the held write. Because wakeupAction is registered on the session (or supplied on the pause request), Napalm automatically resumes the paused loop when that approval commits and invokes billing.resume_refund with wakeupPayload and zero external polling. The same automatic wakeup fires when a scheduled_wakeup timer expires. External webhook handlers or operators can still call client.agentLoops.resume explicitly with the matching approvalId.

agents/refundLoop.ts
// agents/refundLoop.tsimport { NapalmClient, isAgentLoopError } from 'napalm-client' const client = new NapalmClient('https://s4p8m2k9vr.napalmcloud.com', {  token: process.env.REFUND_AGENT_TOKEN,}) // 1. Start a durable session bound to the caller's identity, trace ID and wakeup action.const session = await client.agentLoops.start({  name: 'refund-review',  initialStateJson: { ticketId, amountCents: 120_000, stage: 'verify-invoice' },  traceId: 'refund-4812',  wakeupAction: 'billing.resume_refund',  wakeupPayload: { ticketId },}) // 2. Checkpoint turn 1 idempotently by (turnIndex, stepKey).//    Retrying the same step returns deduplicated: true instead of re-running it.await client.agentLoops.checkpoint(session.id, {  turnIndex: 1,  stepKey: 'verify-invoice',  kind: 'tool_result',  inputJson: { ticketId },  outputJson: { invoiceId: 'inv_981', eligible: true },  stateJson: { ticketId, invoiceId: 'inv_981', stage: 'awaiting-finance' },}) // 3. Submit the refund mutation. Because the schema has a `require approval`//    policy above $500, Napalm returns HTTP 202 with approvalId instead of committing.//    Pause the loop with that approvalId (optionally overriding wakeupAction and//    wakeupPayload) and let the worker process exit completely with zero idle compute. // 4. Hours later, once finance approves (or when a scheduled timer expires),//    Napalm automatically resumes the paused loop and invokes `billing.resume_refund`//    with zero external polling. Manual or webhook-driven callers can also call resume():export async function continueAfterApproval(sessionId: string, approvalId: string) {  try {    const resumed = await client.agentLoops.resume(sessionId, {      approvalId,      payloadJson: { approvedBy: 'finance@acme.example.com' },    })     // Pick up cleanly at resumed.checkpointCursor using resumed.stateJson.    await client.agentLoops.checkpoint(resumed.sessionId, {      turnIndex: resumed.currentTurn + 1,      stepKey: 'notify-customer',      kind: 'tool_result',      outputJson: { emailSent: true },      stateJson: { ...(resumed.stateJson as object), stage: 'done' },    })     return await client.agentLoops.complete(resumed.sessionId, {      resultJson: { status: 'refunded', approvalId },    })  } catch (error) {    if (isAgentLoopError(error) && error.code === 'loop_version_conflict') {      // Another worker already resumed this session; exit without double-running.      return null    }    throw error  }}

Because turn checkpoints are stored as ext::napalm::AgentLoopCheckpoint objects rather than opaque blobs, dashboards can query and live-subscribe to step history directly with EdgeQL:

dbschema/queries/loopCheckpoints.edgeql
# Query or live-subscribe to turn checkpoints directly with EdgeQLselect ext::napalm::AgentLoopCheckpoint {  turn_index,  step_key,  kind,  output_json,  created_at,}filter .session.id = <uuid>$session_idorder by .turn_index asc;

Operators can also inspect active loops, verify waiting triggers, wake paused sessions or cancel stuck runs directly from the terminal:

Terminal
# List active durable loops on the branchnapalm loops list support --status running # Inspect checkpoints, waiting trigger and turn limits for one sessionnapalm loops inspect support <session-id> # Approve the held refund write from the approval queuenapalm approvals approve support <approval-id> --note "Verified invoice inv_981" # Wake the paused loop with the matching approval tokennapalm loops resume support <session-id> --approval-id <approval-id> # Cancel a loop permanently if the customer withdraws the requestnapalm loops cancel support <session-id> --reason "Customer withdrew refund" --yes

What swarm blackboards unlock#

Once an agent workflow splits into specialists (a triage lead, a billing researcher and a reply writer), teams often glue together Redis queues, JSON pub-sub channels and custom lock rows. That extra plumbing creates four recurring failure modes: unauthorized workers reading tenant data off a shared queue, concurrent writers clobbering each other’s drafts, crashed workers holding locks forever or waking up late to overwrite a peer’s result, and runaway sub-agents burning unlimited tokens.

Napalm’s swarm blackboards (client.swarmBlackboard) bind directly to any record in your database as an Object Home, inheriting that record’s compiled select and update access policies. Across multi-engine clusters, both Agent Channels and Swarm Blackboards route through Object Homes so concurrent requests landing on any engine serialize cleanly and stream to every connected client.

CapabilityRedis queues and ad-hoc JSON busesNapalm swarm blackboards
Record-level securityShared queues rely on hand-written prefix checks outside the database.Napalm swarm blackboardsBound to (objectType, objectId) such as default::Ticket. Callers who fail the record’s access policies receive 403 swarm_access_denied.
Shared versioned stateLast-write-wins JSON keys silently drop parallel findings.Napalm swarm blackboardsputEntry() and listEntries() version every entry and enforce optional expectedVersion compare-and-swap (409 board_revision_conflict).
Exclusive task claimsStalled workers can wake up after timeout and overwrite the new owner’s output.Napalm swarm blackboardsclaimTask() grants one exclusive, time-bounded claim with a monotonically increasing claim token. reclaimExpired() reopens timed-out tasks with a higher token so stale workers are rejected.
Hierarchical budgetsPer-worker token counters drift and let child agents bypass parent caps.Napalm swarm blackboardsallocateBudget() enforces strict parent-to-child attenuation (400 budget_attenuation_violation), and chargeBudget() deducts atomically up the ancestor chain (429 budget_limit_reached).

Coordinating specialists on one ticket#

Here, three specialists collaborate on one default::Ticket record. The triage lead allocates a 40-call, 160,000-token ceiling and carves smaller sub-budgets for the researcher and writer. Each specialist signs in with its own credential, shares structured entries on the ticket’s blackboard and passes the task forward through atomic handoffs.

agents/ticketSwarm.ts
// agents/ticketSwarm.tsimport { NapalmClient } from 'napalm-client' const leadClient = new NapalmClient('https://s4p8m2k9vr.napalmcloud.com', { token: process.env.LEAD_TOKEN })const researcherClient = new NapalmClient('https://s4p8m2k9vr.napalmcloud.com', { token: process.env.RESEARCHER_TOKEN })const writerClient = new NapalmClient('https://s4p8m2k9vr.napalmcloud.com', { token: process.env.WRITER_TOKEN }) // Bind the blackboard to one Ticket record under its compiled select/update policies.const leadBoard = leadClient.swarmBlackboard('default::Ticket', ticketId) // 1. Allocate a root budget for the lead orchestrator, then carve sub-budgets for specialists.//    A child can never allocate above its parent or charge another worker's budget.await leadBoard.allocateBudget({ childId: 'triage-lead', maxCalls: 40, maxTokens: 160_000 })await leadBoard.allocateBudget({ parentId: 'triage-lead', childId: 'researcher', maxCalls: 15, maxTokens: 60_000 })await leadBoard.allocateBudget({ parentId: 'triage-lead', childId: 'writer', maxCalls: 10, maxTokens: 40_000 }) // 2. Post versioned shared state and queue a prioritized research task.const brief = await leadBoard.putEntry({  key: 'triage/summary',  valueJson: { severity: 'high', account: 'acme', issue: 'Prorated invoice mismatch' },  tags: ['triage'],}) const task = await leadBoard.createTask({  title: 'Verify Acme billing history and draft response',  payloadJson: { summaryKey: brief.key },  priority: 10,  maxAttempts: 3,}) // 3. The researcher claims the task atomically with an exclusive time-bounded claim.const researchBoard = researcherClient.swarmBlackboard('default::Ticket', ticketId)const claimed = await researchBoard.claimTask({ taskId: task.taskId, leaseTtlSeconds: 120 }) // Each active claim carries a leaseId and a strictly increasing fencingToken.export async function runResearchTurn(leaseId: string, fencingToken: number) {  // Extend the active claim during long tool calls so no peer steals it early.  await researchBoard.heartbeatLease({    taskId: claimed.taskId,    leaseId,    fencingToken,    extendSeconds: 60,  })   // Charge model calls and tokens atomically across the researcher and its parent cap.  await researchBoard.chargeBudget({ callerId: 'researcher', calls: 1, tokens: 3_200 })   // Save findings using expectedVersion compare-and-swap so concurrent writers cannot clobber each other.  const notes = await researchBoard.putEntry({    key: 'research/findings',    valueJson: { invoiceId: 'inv_981', creditCents: 62_000 },    expectedVersion: 0,    tags: ['research'],  })   // Hand the task straight to the writer with a WakeupEvent and fresh claim token.  const { wakeup } = await researchBoard.handoffTask({    taskId: claimed.taskId,    leaseId,    fencingToken,    targetCallerId: 'writer',    reason: 'Billing findings verified; ready for customer reply',    contextJson: { findingsKey: notes.key },    leaseTtlSeconds: 120,  })  return wakeup} // 4. The writer reads shared findings, charges its own sub-budget and completes the task.export async function finishReply(  taskId: string,  leaseId: string,  fencingToken: number,  draftBody: string,) {  const writerBoard = writerClient.swarmBlackboard('default::Ticket', ticketId)  const findings = await writerBoard.listEntries({ prefix: 'research/' })  await writerBoard.chargeBudget({ callerId: 'writer', calls: 1, tokens: 1_900 })   await writerBoard.completeTask({    taskId,    leaseId,    fencingToken,    resultJson: { reply: draftBody, usedEntries: findings.map((e) => e.key) },  })} // 5. If a worker crashes mid-turn, reclaimExpired() reopens timed-out tasks with a higher claim token//    so the stalled worker cannot commit late writes.await leadBoard.reclaimExpired()

Swarm entries, tasks and budgets are stored in normalized system types (ext::napalm::SwarmEntry, ext::napalm::SwarmTask and ext::napalm::SwarmBudget), so supervision UIs and reporting jobs can query and live-subscribe to swarm state directly with EdgeQL:

dbschema/queries/swarmDashboard.edgeql
# Query or live-subscribe to swarm entries, tasks and budgets directly with EdgeQLselect (  entries := (select ext::napalm::SwarmEntry { key, version, value_json, tags }),  tasks := (select ext::napalm::SwarmTask { title, status, priority, attempts }),  budgets := (select ext::napalm::SwarmBudget { caller_id, max_calls, max_tokens, used_calls, used_tokens }),);
Claim lifecycle
Create prioritized work with createTask(), claim exclusively with claimTask(), extend long runs with heartbeatLease(), finish with completeTask(), record retryable errors with failTask(), transfer directly with handoffTask(), cancel with cancelTask() and recover crashed workers with reclaimExpired().
Full board snapshots and EdgeQL
Call board.getState() for one HTTP snapshot of entries, tasks, budgets and wakeup events, or query and live-subscribe to ext::napalm::SwarmEntry, ext::napalm::SwarmTask and ext::napalm::SwarmBudget directly with EdgeQL.
Multi-engine Object Homes
Agent Channels and Swarm Blackboards route across multi-engine clusters through Object Homes so concurrent requests on any engine serialize cleanly and stream to every connected client.
When to use stage rows
When you want separate stage-level schema rules and live UI updates on application types themselves, pair blackboards with the shared-row pattern in the multi-agent pipelines guide.

Check loops, claims and budgets#

Validate your durable loops and swarm guardrails on a development branch before shipping to production:

Terminal
# Verify running and paused loop sessions on the branchnapalm loops list support # Inspect exact checkpoint history and turn count for a completed sessionnapalm loops inspect support <session-id> # Confirm pending approvals linked to paused loopsnapalm approvals list support --status pending
Double-resume safety
Send two concurrent client.agentLoops.resume() calls with the same approvalId and confirm one succeeds while the second fails with 409 loop_version_conflict.
Budget attenuation
Attempt to allocate a child budget larger than its parent’s remaining cap and confirm Napalm rejects the call with 400 budget_attenuation_violation.
Policy enforcement
Open client.swarmBlackboard with a credential that cannot read or update that Ticket row and confirm Napalm answers 403 swarm_access_denied.

Next steps#

Memory and context packs
Give long-running loops and swarms bi-temporal facts, private scratchpads and cited live context packs.
Multi-agent pipelines
Coordinate stage-scoped workers over live queries, dedicated worker accounts and cross-project A2A calls.
Evals
Gate prompt and tool changes with continuous regression suites and parallel branch RL gyms.