AI agents

Offline AI agents

Read agent data locally during a network outage and reconnect its database through device sync.

A local Sirannon database accepts reads and writes while the device has no network connection. An agent that has to generate answers offline as well needs a model that operates on the device, because a hosted model is out of reach while the network is down.

Give each signed-in account a separate local database. When the device reconnects, a SyncController can push the queued changes and apply the changes from the server to that database.

Answer with no connection at all

The complete offline-notes.ts program below shows the local read that an agent performs, without a call to any model. After the program records a note in a temporary database, it reads that note back from the cached state of a live query. Your agent can offer the same read through a tool that checks the caller's authorisation.

offline-notes.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon, type LiveQuery } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
interface Note { id: string; author: string; body: string }
 
const readNotes = (view: LiveQuery<Note>): Note[] => {
  const state = view.getState()
  if (state.status === 'error') throw state.error
  if (state.status !== 'ready') throw new Error('The local notes are not ready')
  return [...state.rows]
}
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-offline-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
let view: LiveQuery<Note> | undefined
 
try {
  const db = await sirannon.open('notes', join(directory, 'notes.db'))
  await db.execute('CREATE TABLE notes (id TEXT PRIMARY KEY, author TEXT NOT NULL, body TEXT NOT NULL)')
  await db.watch('notes')
  await db.execute('INSERT INTO notes VALUES (?, ?, ?)',
    ['maintenance-1', 'crew-a', 'Inspect the points motor before returning it to service.'])
  view = await db.live<Note>('SELECT id, author, body FROM notes ORDER BY id')
  console.log(JSON.stringify(readNotes(view), (key: string, value: unknown): unknown =>
    typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
  await view?.close()
  await sirannon.shutdown()
  await rm(directory, { recursive: true, force: true })
}

getState() returns the state that the live query caches. The live query updates that cache from the change feed, so the cache can lag behind a write until the feed delivers it. When a tool has to confirm a particular write at once, send a fresh query to the database.

The example uses the better-sqlite3 driver for Node.js. In a browser, use the wa-sqlite driver, while a React Native application can use the Expo driver. Drivers lists what each runtime requires.

Reconcile once the connection returns

Start from a database that the application bootstraps for the current account, using snapshot recovery. The server in the device sync example serves the same notes schema.

The complete connect-notes.ts file below exports a connection helper. The caller passes in the database that it selected for the account, together with the server URL, the credential, and a handler for recovery notices. The helper sets autoResync to false so that the application can protect unsent local work before it downloads a new snapshot.

connect-notes.ts
import type { Database } from '@delali/sirannon-db'
import { SyncController } from '@delali/sirannon-db/client'
 
interface ConnectionOptions {
  url: string
  token: string
  onResyncRequired: () => void
}
 
export const connectNotes = async (database: Database, options: ConnectionOptions): Promise<SyncController> => {
  const url = new URL(options.url)
  const isLocal = url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '[::1]'
  if (url.protocol !== 'https:' && !(isLocal && url.protocol === 'http:')) {
    throw new Error('Use HTTPS for a remote sync server')
  }
  if (!/^[a-f0-9]{64}$/.test(options.token)) throw new Error('The example server needs a hexadecimal session token')
  const sync = new SyncController(database, {
    url: options.url,
    databaseId: 'notes',
    tables: ['notes'],
    headers: { Authorization: `Bearer ${options.token}` },
    webSocketProtocols: [options.token],
    autoResync: false,
    onResyncRequired: options.onResyncRequired,
  })
  try {
    await sync.start()
    return sync
  } catch (error) {
    await sync.stop()
    throw error
  }
}

The helper works in a Node.js process that provides a WebSocket implementation. In a browser, the server's CORS configuration has to list the origin of your application. A browser has no API for WebSocket handshake headers, so the controller sends the WebSocket credential as an offered subprotocol. Use short-lived credentials in a deployed application.

When the server is unreachable, start() resolves with the failure in status().lastError, after which the controller tries the connection again and waits longer before each new try. When the server refuses with a code such as UNAUTHORIZED, FORBIDDEN, or DEVICE_SYNC_NOT_ACCEPTED, start() rejects with that error, so the helper stops the controller and throws the error again.

pendingPushCount is the number of local changes that wait for the controller to push them. A count of zero means that the push queue is empty, although the device can lack later changes from the server at the same moment. Before the agent tells someone that an answer matches the server, check the pull state and the recovery status as well.

The controller writes pulled changes into the local database, so the same live query returns both the local rows and the synchronised rows. Call sync.stop() before you close the database, and close the live query once the application finishes with it.

Where to go next

Choose a conflict policy for concurrent edits to one row. When your application can store both versions of a fact, give each version a separate identifier; for a row that several devices share, use conflict resolution.

A device can need a fresh snapshot after the server drops its cursor, after the device loses its local database, or after a schema update fails. While the snapshot replaces the local data, disable the tools that need complete data, and follow device sync recovery before you enable them again. Memory and forgetting shows how to record where each local fact came from and how to query its history.