AI agents

A database per AI agent

Separate agent data by database file, bound open connections, and remove a customer's files after disabling access.

Sirannon can store each agent's data in a separate SQLite file. Your application selects the customer and agent before calling the database, so a model needs only the arguments for its permitted task.

Separate files keep queries independent, but the application process can access every file that its filesystem permissions allow. Authenticate the caller and authorise the database identifier before resolving it. The security guide explains that check for a network service.

Give each customer's agent a separate file

createTenantResolver() maps a valid database identifier to a file beneath a configured directory. It accepts lowercase letters, digits, hyphens, and underscores, with a lowercase letter or digit first. A traversal string produces no path, which prevents automatic opening through that resolver.

The complete agents.ts example uses a stricter customer identifier and a fixed set of agent roles. This makes the separator between customer and role unambiguous. A deployed application must obtain the customer from its authenticated session.

agents.ts
import { mkdtemp, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createTenantResolver, type Database, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
type AgentRole = 'support-agent' | 'billing-agent'
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-agents-'))
const resolver = createTenantResolver({ basePath: directory })
const agentId = (customer: string, role: AgentRole): string => {
  if (!/^[a-z0-9][a-z0-9-]*$/.test(customer)) throw new Error('Invalid customer identifier')
  return `${customer}__${role}`
}
 
const sirannon = new Sirannon({
  driver: betterSqlite3(),
  migrations: [{
    version: 1,
    name: 'agent_facts',
    up: 'CREATE TABLE facts (subject TEXT PRIMARY KEY, value TEXT NOT NULL)',
  }],
  lifecycle: {
    autoOpen: { resolver },
    maxOpen: 2,
    idleTimeout: 60_000,
  },
})
 
const databaseFor = async (customer: string, role: AgentRole): Promise<Database> => {
  const database = await sirannon.resolve(agentId(customer, role))
  if (!database) throw new Error('The database identifier has no path')
  return database
}
 
try {
  const harbour = await databaseFor('harbour', 'support-agent')
  await harbour.execute('INSERT INTO facts VALUES (?, ?)', ['refund window', '30 days'])
  const lumen = await databaseFor('lumen', 'support-agent')
  await lumen.execute('INSERT INTO facts VALUES (?, ?)', ['refund window', '14 days'])
  const billing = await databaseFor('harbour', 'billing-agent')
  await billing.execute('INSERT INTO facts VALUES (?, ?)', ['invoice currency', 'USD'])
 
  const reopened = await databaseFor('harbour', 'support-agent')
  const supportCurrency = await reopened.query('SELECT value FROM facts WHERE subject = ?', ['invoice currency'])
  const harbourWindow = await reopened.query('SELECT value FROM facts WHERE subject = ?', ['refund window'])
  const files = (await readdir(directory)).filter((file: string): boolean => file.endsWith('.db')).sort()
  console.log(JSON.stringify({
    harbourWindow,
    supportCurrency,
    files,
    openDatabases: sirannon.databases().size,
    traversalPath: resolver('harbour/../lumen') ?? null,
  }, (key: string, value: unknown): unknown =>
    typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
  await sirannon.shutdown()
  await rm(directory, { recursive: true, force: true })
}

The support database contains Harbour's refund window but no invoice currency. The billing database stores that currency separately. Closing a database through the registry preserves its file, so resolving the same identifier can reopen its earlier data.

Decide where the boundary falls

Choose the identifier according to who may share data. A customer-and-role identifier creates a file for each role within each customer. A customer-only identifier lets that customer's agents share one file. Including a conversation identifier creates a separate conversation database.

Bind that identifier when constructing a tool. A model that can choose a database identifier can request another customer's database unless the server checks that request against its authenticated identity.

The resolver validates path syntax, while your authorisation service determines who may use each identifier. Keep the database directory application-controlled so that an untrusted process cannot replace paths with symbolic links.

Hold only a few of those files open at once

lifecycle.maxOpen bounds the number of open databases. At the cap, the registry tries to close the least recently used database before opening another. It raises MAX_DATABASES if it cannot make room.

lifecycle.idleTimeout closes a database after the configured milliseconds without activity. The example's limit of two databases demonstrates reopening across three files; its 60000-millisecond timeout is an example setting. Choose deployment limits from available file descriptors, connection-pool size, and expected concurrent use.

Observe closure through onDatabaseClose and resolve the database again for later work. Keep database operations within their request's lifetime so that another task does not use a stale handle after eviction. The lifecycle guide describes hooks and idle closure in more detail.

Delete the customer's agent data

Disable the customer's access and drain its work before deleting data. Every process that can resolve those identifiers must enforce the disabled state, or a later request can recreate a file after deletion.

After all connections close, remove the database and its -wal and -shm files. Use the same validated identifier and resolver that created the file. Match an exact customer-and-role mapping, because an unchecked prefix can select another customer's identifiers.

Continuous backups also create a {databasePath}-backup staging directory. Include that state, uploaded backups, search indexes, audit records, and retained encryption keys in the deletion policy that your application enforces. Deleting the active SQLite file alone does not erase those copies.

For encrypted agent files, enable a supported encryption driver and supply the key provider when each database opens. Keep key references in trusted application configuration, with access checks separate from the model's tool arguments.

Where to go next

Memory and forgetting adds sources, expiry, and historical queries to stored facts. Rewinding memory restores a database after an unwanted write, while auditing a fleet records which agent requested each change.