AI agents

Shared state

Claim work through an atomic condition and keep an agent task board current with a live query.

Two agents can select the same available job before either claims it. Put the availability condition inside the write so that SQLite accepts one claimant and returns zero changed rows to the other.

The database claim determines who may start the work. An external action, such as placing a purchase order, also needs an idempotency key or another recovery mechanism at the receiving service.

Watch two agents take the same job

A read followed by an unconditional update leaves a gap between checking and claiming. Another agent can claim the job during that gap, including while a model generates its next tool call.

The complete board.ts below makes both agents read the available jobs before either writes. Its conditional update then prevents the second claimant from overwriting the first.

board.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { Sirannon, type LiveQuery } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
interface Job {
  id: number
  depot: string
  claimed_by: string | null
}
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-board-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
let board: LiveQuery<Job> | undefined
 
try {
  const db = await sirannon.open('restock', join(directory, 'restock.db'))
  await db.execute(`CREATE TABLE restock_job (
    id INTEGER PRIMARY KEY, depot TEXT NOT NULL, item TEXT NOT NULL, claimed_by TEXT
  )`)
  await db.executeBatch('INSERT INTO restock_job VALUES (?, ?, ?, NULL)', [
    [1, 'Rotterdam', 'oat milk'],
    [2, 'Valparaíso', 'tinned tomatoes'],
  ])
  board = await db.live<Job>('SELECT id, depot, claimed_by FROM restock_job ORDER BY id')
 
  const openJobs = (): Promise<Job[]> =>
    db.query<Job>('SELECT id, depot, claimed_by FROM restock_job WHERE claimed_by IS NULL ORDER BY id')
  const claimJob = async (agent: string, jobId: number): Promise<boolean> => {
    if (!Number.isSafeInteger(jobId) || jobId < 1) throw new Error('Invalid job identifier')
    const claimed = await db.execute(
      'UPDATE restock_job SET claimed_by = ? WHERE id = ? AND claimed_by IS NULL', [agent, jobId])
    return claimed.changes === 1
  }
 
  const [firstChoices, secondChoices] = await Promise.all([openJobs(), openJobs()])
  const first = firstChoices[0]
  const second = secondChoices[0]
  if (!first || !second) throw new Error('The example needs an available job')
  const claims = await Promise.all([
    claimJob('restock-agent-1', first.id),
    claimJob('restock-agent-2', second.id),
  ])
  const losingAgent = claims[0] ? 'restock-agent-2' : 'restock-agent-1'
  const remaining = (await openJobs())[0]
  if (remaining) await claimJob(losingAgent, remaining.id)
 
  const deadline = Date.now() + 5000
  while (true) {
    const state = board.getState()
    if (state.status === 'error') throw state.error
    if (state.status === 'ready' && state.rows.every((job: Job): boolean => job.claimed_by !== null)) {
      console.log(JSON.stringify({ firstJobClaims: claims, board: state.rows },
        (key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
      break
    }
    if (Date.now() >= deadline) throw new Error('The live query did not receive the claims')
    await setTimeout(10)
  }
} finally {
  await board?.close()
  await sirannon.shutdown()
  await rm(directory, { recursive: true, force: true })
}

The retry uses the remaining available job after the first conditional claim fails. A model can make the same choice through a tool, but the SQL condition must protect every call independently of the model.

Let one statement settle the claim

UPDATE ... WHERE claimed_by IS NULL checks and changes the row in one SQLite statement. The first successful claimant receives changes: 1; another claimant receives zero while that claim remains in place. Return that distinction to the caller before starting work.

Derive the agent identifier from authenticated application context when exposing this function remotely. Use registered operations so that a model can select a permitted job without choosing another actor's identity or sending SQL.

A permanent claim remains after an agent crashes. For work that can be reassigned, add a lease expiry and a claim token. Renew and complete the job only when the token matches the current claim, so that an older worker cannot complete work after reassignment. The receiving system must also reject stale or duplicate external actions; a lease alone cannot undo a purchase that a worker already placed.

Give a person the board

db.live() reads the board once and then maintains its rows from change events. The loop in the example waits for delivery before printing the final state; a dashboard can call subscribe() and render each update as it arrives.

A live update can contain a replacement row set or an array of edits. Apply those edits in order, or read getState() when the listener fires. Avoid assuming that every committed claim produces exactly one callback, because delivery and query maintenance can group changes.

Live queries support a restricted single-table SELECT. Joins, aggregates, grouping, distinct rows, compound selects, window functions, and subqueries require another approach. A limited query needs deterministic ordering. The live-query guide describes the restrictions and remote registered reads.

Where to go next

Auditing a fleet saves committed actions alongside their audit events. Distributed replication copies the database to other nodes, while coordinator failover manages the authority that admits writes.