A local Sirannon database can accept reads and writes while the device has no network connection. An agent that must also generate answers offline needs a model that operates locally; a local database does not make a hosted model available offline.
Keep each signed-in account's local database separate. When the connection returns, a SyncController can push queued changes and apply server changes to that database.
Answer with no connection at all
The complete offline-notes.ts demonstrates the local retrieval operation without calling a model. It opens a temporary database, records a note, and reads the live query's cached state. Your agent can expose the same read through an authorised tool.
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() reads cached live-query state. Changes reach that cache through the change feed, so it can lag a write until delivery completes. Use a fresh database query when a tool must confirm a particular write immediately.
The example uses Node's better-sqlite3 driver. A browser uses wa-sqlite, while a React Native application can use Expo SQLite. The driver guide explains those runtime requirements.
Reconcile once the connection returns
Start from a database that the application has bootstrapped for the current account, using snapshot recovery. The device-sync server example serves the same notes schema.
This complete connect-notes.ts exports a connection helper. Its caller supplies the already selected database, server URL, credential, and recovery notification handler. The helper disables automatic replacement so that the application can protect unsent local work before downloading a new snapshot.
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 process with the necessary WebSocket runtime. A browser also requires its origin in the server's CORS configuration, and it sends the WebSocket credential through the offered subprotocol. Use short-lived credentials in a deployed application.
start() resolves when the server is unreachable, with the failure available through status().lastError. The controller retries with backoff. A server refusal such as UNAUTHORIZED, FORBIDDEN, or DEVICE_SYNC_NOT_ACCEPTED rejects startup.
pendingPushCount reports queued local changes. A zero count means the push queue has caught up; it does not establish that the device has received every later server change. Inspect pull state and recovery status separately before claiming that an answer is current with the server.
Pulled changes update the local database, so the same live query can display local and synchronised rows. Call sync.stop() before closing the database, and close the live query when the application no longer uses it.
Where to go next
Choose a conflict policy for concurrent edits to one row. Give separately authored facts separate identifiers when your application can preserve both, and use device-sync conflict resolution for shared rows.
An expired cursor, lost database, or failed schema update can require a fresh snapshot. Disable tools that depend on complete data during replacement and follow device-sync recovery before enabling them again. Memory and forgetting adds provenance and historical queries to local facts.