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 the data of each agent in a separate SQLite file. Your application chooses the customer and the agent before it calls the database, so the model supplies only the arguments of the task that it is allowed to perform.

Separate files keep the queries of each agent apart; however, the application process can open every file that its filesystem permissions allow. Authenticate the caller and authorise the database identifier before the resolver turns it into a path. 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 inside a configured directory. It accepts 1 to 255 lowercase letters, digits, hyphens, and underscores, with a lowercase letter or a digit first. For any other identifier, such as one that tries to climb out of the directory with .., the resolver returns no path, so the registry opens no file through that resolver.

The complete agents.ts example below takes a stricter customer identifier and a fixed set of agent roles, so that the separator between the customer and the role can never appear inside either part. A deployed application has to take 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 firstSupport = await databaseFor('customer-a', 'support-agent')
  await firstSupport.execute('INSERT INTO facts VALUES (?, ?)', ['refund window', '30 days'])
  const secondSupport = await databaseFor('customer-b', 'support-agent')
  await secondSupport.execute('INSERT INTO facts VALUES (?, ?)', ['refund window', '14 days'])
  const firstBilling = await databaseFor('customer-a', 'billing-agent')
  await firstBilling.execute('INSERT INTO facts VALUES (?, ?)', ['invoice currency', 'USD'])
 
  const reopened = await databaseFor('customer-a', 'support-agent')
  const supportCurrency = await reopened.query('SELECT value FROM facts WHERE subject = ?', ['invoice currency'])
  const refundWindow = 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({
    refundWindow,
    supportCurrency,
    files,
    openDatabases: sirannon.databases().size,
    traversalPath: resolver('customer-a/../customer-b') ?? 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 of the first customer contains its refund window but no invoice currency, because the billing agent of that customer stores the currency in a separate file. When the registry closes a database, it leaves the file in place, so a later resolve of the same identifier opens the earlier data again.

Decide where the boundary falls

Choose the identifier by who may share data. An identifier made of the customer and the role gives each role of each customer a separate file. An identifier made of the customer alone lets the agents of that customer share one file, while an identifier that includes a conversation gives each conversation a separate database.

Fix that identifier when you construct a tool. When a model can choose the database identifier, it can request the database of another customer, so the server has to check each such request against the authenticated identity of the caller.

The resolver checks the syntax of the path, while your authorisation service decides who may use each identifier. Give only your application control of the database directory, so that an untrusted process has no way to replace a path with a symbolic link.

Hold only a few of those files open at once

lifecycle.maxOpen limits the number of open databases. At that limit, the registry closes the least recently used database before it opens another. When it can close none and no other open is under way, it throws MAX_DATABASES.

lifecycle.idleTimeout closes a database once it receives no request for that many milliseconds. The example sets a limit of two databases so that it reopens a file across three files, while its timeout of 60,000 milliseconds is a sample setting. Choose the limits of a deployment from the available file descriptors, the size of the connection pool, and the expected number of concurrent requests.

Watch for each closure through onDatabaseClose, and resolve the database again for later work. Finish each database call within the lifetime of its request, so that no other task uses a handle after the registry closes it. The lifecycle guide describes the hooks and the idle closure in more detail.

Delete the customer's agent data

Disable the access of the customer and let its work finish before you delete its data. Every process that can resolve those identifiers has to refuse them once you disable the customer, because a later request can otherwise create the file again after you delete it.

After every connection closes, remove each database file together with its -wal and -shm files. Use the same validated identifier and resolver that created the file. Match the exact identifier of each customer and role, because a check on a prefix alone can select the identifiers of another customer.

A continuous backup also creates a staging directory at {databasePath}-backup. Include that directory, the uploaded backups, search indexes, audit records, and retained encryption keys in the deletion policy of your application, because a deletion of the SQLite file alone leaves those copies in place.

For encrypted agent files, enable a driver that supports encryption and supply the key loader when each database opens. Store the references to each key in trusted application configuration, and check access to the keys separately from the arguments of the tools that the model calls.

Where to go next

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