@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
396 lines • 20.7 kB
JavaScript
import { createHash } from 'node:crypto';
import { CoalescedWrites } from './coalesced-writes.js';
import { interruptible, sleepUnlessAborted } from './interruptible.js';
import { qualifiedName, qualifiedSql, validateSchema } from './stores/db-schema.js';
import { affectedRows } from './stores/lucid.js';
import { AGENT_TABLES, ensureStreamFrameTable, rowsOf } from './stores/lucid-schema.js';
import { dialectOf, isMySql, portableSql } from './stores/sql-dialect.js';
/** Default TTL (seconds) for a run's rows: 1h past its last write, the same window the Redis sink keeps. */
const DEFAULT_TTL_SECONDS = 3600;
/** Default gap (ms) between two reads of a run a subscriber is following. */
const DEFAULT_POLL_INTERVAL_MS = 250;
/** Default gap (ms) between two reads once a run has been quiet for {@link IDLE_AFTER_MS}. */
const DEFAULT_IDLE_POLL_INTERVAL_MS = 1000;
/** How long a run has to write nothing before its subscribers slow down to the idle interval. */
const IDLE_AFTER_MS = 5000;
/** Default window (ms) consecutive deltas are gathered over before they are written as one row. */
const DEFAULT_FLUSH_MS = 50;
/** Rows read per query, so a long run's replay is paged rather than loaded whole. */
const READ_PAGE = 500;
/** Run ids deleted per statement by {@link LucidTokenStreamSink.purgeExpired}. */
const PURGE_CHUNK = 200;
/** The least time between two purges an instance starts on its own (see `autoPurge`). */
const AUTO_PURGE_EVERY_MS = 60_000;
/** Attempts at one append before a sequence-number collision is reported instead of retried. */
const APPEND_ATTEMPTS = 8;
/** The longest (seconds) a MySQL writer waits for its turn at a contended run before giving up. */
const TURN_WAIT_SECONDS = 30;
function toInt(value) {
if (typeof value === 'number')
return value;
if (typeof value === 'bigint')
return Number(value);
if (typeof value === 'string')
return Number.parseInt(value, 10) || 0;
return 0;
}
/**
* Did this insert lose the race for a `(run_id, seq)`? Read off the driver's own code — Postgres
* `23505`, SQLite `SQLITE_CONSTRAINT_*`, MySQL `ER_DUP_ENTRY`/1062 (or its deadlock victim, 1213),
* SQL Server 2627 — so nothing
* else (a missing table, a lost connection) is ever retried as though it were one.
*/
function isUniqueViolation(error) {
const e = error;
if (e === null || typeof e !== 'object')
return false;
if (e.code === '23505' || e.code === 'ER_DUP_ENTRY')
return true;
// InnoDB settles two `INSERT … SELECT MAX(seq) + 1` into one run (both taking gap locks on the
// same range) by rolling one back as a deadlock victim, not with a duplicate key: the same lost
// race, just as safe to retry.
if (e.code === 'ER_LOCK_DEADLOCK' || e.errno === 1213)
return true;
if (typeof e.code === 'string' && e.code.startsWith('SQLITE_CONSTRAINT'))
return true;
return e.errno === 1062 || e.number === 2627;
}
/**
* A multi-replica {@link TokenStreamSink} over the app's SQL database (through `@adonisjs/lucid`) —
* for a deployment with several replicas and NO Redis. The replica running the model turn appends
* each frame as a row of `agent_stream_frame`; any replica serves the run's SSE by reading the rows
* past its cursor, in order, until it meets the end marker. A subscriber that attaches late, or
* after the run ended, replays from the first row — the same guarantee the in-process and Redis
* sinks give.
*
* Two things differ from the Redis sink, and both are the price of having no broker:
*
* - **Delivery is polled.** There is no publish to wake a subscriber, so a frame waits up to
* `pollIntervalMs` (250 ms) before a browser sees it.
* - **Deltas are coalesced on the way in.** Consecutive `text` frames written within `flushMs`
* (50 ms) are stored as ONE `text` frame holding their concatenation, and so are consecutive
* reasoning deltas, and consecutive argument deltas of one tool call. The stored rows are the
* run's stream: every subscriber, on every replica, reads the same rows in the same order, so
* the SSE event ids `AgentSseEncoder` counts from them — and an `after` cursor — stay exact. They
* are NOT the ids the in-process sink would have produced for the same run (it numbers every
* token), which only matters to a cursor carried across a change of sink.
*
* Sequence numbers are per run, start at 1 and have no gaps: each append takes `MAX(seq) + 1` for
* its run in the same statement that inserts it, and the `(run_id, seq)` primary key refuses a
* second row under a number already taken. A run normally has ONE writer, and then no append ever
* collides and each costs one statement. Several writers at once — a parent whose delegated
* children forward into its stream, possibly from other replicas — are taken in turn under a
* per-run lock once they collide (Postgres advisory lock, MySQL named lock), so every append lands
* however many writers contend. Nothing depends on ordering across runs.
*
* A subscriber notices when the rows it has read are gone: it ends when the run has none left
* (purged past its TTL, or `close()`d), and starts over from the first row when the run's numbering
* restarted under it (a run parked past its TTL that then wrote again).
*
* Text a writer is still gathering lives in the process for at most `flushMs`; a process that dies
* in that window loses it from the LIVE stream (the persisted message is unaffected).
*
* Wire it with `defineConfig({ sink: tokenSinks.lucid() })`.
*/
export class LucidTokenStreamSink {
db;
table;
/** The database schema the frame table lives in (`undefined`: the connection's current one). */
schema;
/** The frame table as the query builder names it (`schema.table` under a schema). */
tableRef;
/** The frame table as raw SQL names it (`"schema"."table"` under a schema). */
tableSql;
pollIntervalMs;
idlePollIntervalMs;
flushMs;
ttlSeconds;
autoPurge;
autoCreateTables;
writes;
provisioned;
lastAutoPurge = 0;
constructor(db, options = {}) {
this.db = db;
const table = options.tableName ?? AGENT_TABLES.streamFrames;
// The name is spliced into SQL (DDL takes no bindings), so it has to be a plain identifier.
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
throw new Error(`LucidTokenStreamSink: "${table}" is not a valid table name`);
}
this.table = table;
this.schema = validateSchema(db, options.schema, 'tokenSinks.lucid()');
this.tableRef = qualifiedName(table, this.schema);
this.tableSql = qualifiedSql(table, this.schema);
this.pollIntervalMs = Math.max(1, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
this.idlePollIntervalMs = Math.max(this.pollIntervalMs, options.idlePollIntervalMs ?? DEFAULT_IDLE_POLL_INTERVAL_MS);
this.flushMs = Math.max(0, options.flushMs ?? DEFAULT_FLUSH_MS);
this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
this.autoPurge = options.autoPurge ?? true;
this.autoCreateTables = options.autoCreateTables ?? true;
this.writes = new CoalescedWrites(this.flushMs, (runId, frame) => this.append(runId, frame === null ? null : JSON.stringify(frame)));
}
/**
* Create the frame table if it is missing. The agent provider calls this once as the app starts;
* a sink built by hand falls back to it on first use. A no-op under `autoCreateTables: false`.
*/
ensureSchema() {
if (!this.autoCreateTables)
return Promise.resolve();
if (this.provisioned === undefined) {
this.provisioned = ensureStreamFrameTable(this.db, this.table, {
schema: this.schema,
}).catch((error) => {
this.provisioned = undefined;
throw error;
});
}
return this.provisioned;
}
/** The per-run lock this database takes contended appends under, or `undefined` for none. */
turnLock() {
if (isMySql(this.db))
return 'mysql';
return /postgres|^pg$/i.test(dialectOf(this.db)) ? 'postgres' : undefined;
}
/** The lock's name for a run: an advisory-lock key text on Postgres, a named lock on MySQL. */
turnKey(runId, lock) {
const key = `${this.tableRef}:${runId}`;
// MySQL caps a lock name at 64 characters, so the run is named by its digest.
return lock === 'mysql' ? `agent_seq:${createHash('sha1').update(key).digest('hex')}` : key;
}
/** The append statement: the run's next number and the row, in one `INSERT … SELECT`. */
insertSql(guard = '') {
return portableSql(this.db, `INSERT INTO ${this.tableSql} ("run_id", "seq", "frame", "created_at") ` +
`SELECT ?, COALESCE(MAX("seq"), 0) + 1, ?, ? FROM ${this.tableSql} WHERE "run_id" = ?${guard}`);
}
/**
* Append one row to the run — a frame, or the end marker (`null`).
*
* The next number and the insert are one statement, and that is what keeps the numbering safe to
* follow: a row's number is computed only once every lower number is committed, so a subscriber
* reading `seq > cursor` never sees a number before the ones under it. Two writers that compute
* the same number lose nothing either — the `(run_id, seq)` primary key refuses the second row.
*
* What a collision must not do is send the loser straight back into the same race: against a
* writer that keeps appending, it can lose every round (a bounded retry then fails a perfectly
* good write with a duplicate-key error, and an unbounded one may spin). So on Postgres and MySQL
* an append is tried ONCE as a bare statement — the uncontended path, one round trip, as before —
* and a writer that collides, or that finds another writer taking its turn, appends inside a
* transaction holding the run's lock ({@link appendInTurn}). The bare statement yields to that
* lock (it only inserts while nobody holds it), so once writers contend they append one at a
* time and each gets through on its turn, however many there are.
*/
async append(runId, frame) {
await this.ensureSchema();
const lock = this.turnLock();
if (lock !== undefined) {
const key = this.turnKey(runId, lock);
// Postgres: take the run's lock for this statement if it is free, else insert nothing.
// MySQL: insert only while no writer is taking its turn (a named lock outlives the statement).
const guard = lock === 'postgres'
? ' HAVING pg_try_advisory_xact_lock(hashtextextended(?, 0))'
: ' HAVING IS_FREE_LOCK(?) = 1';
try {
const result = await this.db.rawQuery(this.insertSql(guard), [
runId,
frame,
Date.now(),
runId,
key,
]);
if (affectedRows(result) > 0)
return;
}
catch (error) {
if (!isUniqueViolation(error))
throw error;
}
if (await this.appendInTurn(runId, frame, lock, key))
return;
}
for (let attempt = 1;; attempt += 1) {
try {
await this.db.rawQuery(this.insertSql(), [runId, frame, Date.now(), runId]);
return;
}
catch (error) {
if (attempt >= APPEND_ATTEMPTS || !isUniqueViolation(error))
throw error;
}
}
}
/**
* Append under the run's lock, in a transaction of its own: the contended path. Writers in their
* turn never collide with each other; the retry covers a bare append that passed its guard just
* before this writer took the lock. Returns `false` (nothing written) when the database's
* transaction client cannot run raw SQL, leaving the caller to its plain retry.
*/
async appendInTurn(runId, frame, lock, key) {
for (let attempt = 1;; attempt += 1) {
try {
const appended = await this.db.transaction(async (trx) => {
const client = trx;
if (typeof client.rawQuery !== 'function')
return false;
const run = (sql, bindings) => client.rawQuery.call(trx, sql, bindings);
const insert = () => run(this.insertSql(), [runId, frame, Date.now(), runId]);
if (lock === 'postgres') {
// Read the run as it is once the lock is ours, whatever isolation the app defaults to.
await run('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
await run('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', [key]);
await insert();
return true; // the lock goes with the commit
}
const granted = rowsOf(await run('SELECT GET_LOCK(?, ?) AS granted', [key, TURN_WAIT_SECONDS]))[0]?.granted;
if (Number(granted) !== 1) {
throw new Error(`LucidTokenStreamSink: waited ${TURN_WAIT_SECONDS}s for a turn to append to run "${runId}"`);
}
try {
// Under the default REPEATABLE READ the insert's read of the run is a locking read, so
// it waits for — and counts — a row the previous turn has not committed yet.
await insert();
}
finally {
// A named lock belongs to the session, not the transaction, and the connection goes back
// to the pool at commit, so it is released here, just BEFORE the commit. The next turn
// can then start while this row is still uncommitted. That is safe: under REPEATABLE
// READ its locking read waits for this commit, and under READ COMMITTED it collides on
// the primary key and the retry below sends it again, after this row is visible.
await run('SELECT RELEASE_LOCK(?)', [key]);
}
return true;
});
return appended;
}
catch (error) {
if (attempt >= APPEND_ATTEMPTS || !isUniqueViolation(error))
throw error;
}
}
}
/**
* The run's writer. Writers opened for the same run in one process share what they are gathering,
* so a delegated run's text (forwarded through a {@link childSinkWriter}) and its parent's next
* frame keep the order they were written in.
*/
open(runId) {
return {
write: (frame) => this.writes.write(runId, frame),
flush: () => this.writes.flush(runId),
end: async () => {
await this.writes.end(runId);
this.purgeInBackground();
},
};
}
subscribe(runId) {
return interruptible((signal) => this.follow(runId, signal));
}
async *follow(runId, signal) {
await this.ensureSchema();
// The last row read, by number and by write time. It is read again with every page, so its
// absence is seen: a run whose rows went has nothing left to follow, and a number held by a
// row written at another time belongs to a run that started numbering over.
let cursor = 0;
let cursorAt = 0;
let quietSince = Date.now();
while (!signal.aborted) {
const rows = await this.db
.from(this.tableRef)
.where('run_id', runId)
.where('seq', '>=', cursor)
.orderBy('seq', 'asc')
.limit(cursor > 0 ? READ_PAGE + 1 : READ_PAGE)
.select('seq', 'frame', 'created_at');
let fresh = rows;
if (cursor > 0) {
const head = rows[0];
if (head === undefined ||
toInt(head.seq) !== cursor ||
toInt(head.created_at) !== cursorAt) {
if (!(await this.has(runId)))
return;
cursor = 0;
cursorAt = 0;
continue;
}
fresh = rows.slice(1);
}
let ended = false;
for (const row of fresh) {
cursor = toInt(row.seq);
cursorAt = toInt(row.created_at);
if (row.frame === null || row.frame === undefined) {
ended = true;
continue;
}
yield JSON.parse(String(row.frame));
}
if (ended) {
return;
}
if (fresh.length > 0) {
quietSince = Date.now();
// A full page means there may be more already written: read on without waiting.
if (fresh.length >= READ_PAGE)
continue;
}
await sleepUnlessAborted(Date.now() - quietSince >= IDLE_AFTER_MS ? this.idlePollIntervalMs : this.pollIntervalMs, signal);
}
}
async has(runId) {
await this.ensureSchema();
return (await this.db.from(this.tableRef).where('run_id', runId).first()) !== null;
}
async close(runId) {
await this.writes.discard(runId);
await this.ensureSchema();
await this.db.from(this.tableRef).where('run_id', runId).delete();
}
/**
* Delete every run whose last write is older than `ttlSeconds` at `now` (epoch ms) — ended runs
* past their replay window and runs that crashed without ending alike. Returns how many runs went.
* Safe to call from any replica, and from several at once. A no-op under `ttlSeconds: 0`.
*
* An instance already calls it after a run ends (at most once a minute; `autoPurge`), which keeps
* the table bounded on a replica that streams. Call it from a schedule as well if a quiet
* deployment must not keep the last hour's streams around indefinitely.
*/
async purgeExpired(now = Date.now()) {
if (this.ttlSeconds <= 0)
return 0;
await this.ensureSchema();
const cutoff = now - this.ttlSeconds * 1000;
// A run has lapsed when it has a row older than the cutoff and none newer. Both halves read an
// index — `created_at` for the old rows, the primary key for a candidate's newer ones — so a
// purge costs what has aged out rather than a scan of the table. Separate statements rather
// than one `DELETE … WHERE run_id IN (SELECT … FROM the same table)`, which MySQL refuses; a
// run that writes in between was idle for the whole TTL a moment ago.
const candidates = rowsOf(await this.db.rawQuery(portableSql(this.db, `SELECT DISTINCT "run_id" AS run_id FROM ${this.tableSql} WHERE "created_at" < ?`), [cutoff])).map((row) => String(row.run_id));
const lapsed = [];
for (let index = 0; index < candidates.length; index += PURGE_CHUNK) {
const chunk = candidates.slice(index, index + PURGE_CHUNK);
const live = new Set(rowsOf(await this.db.rawQuery(portableSql(this.db, `SELECT DISTINCT "run_id" AS run_id FROM ${this.tableSql} ` +
`WHERE "run_id" IN (${chunk.map(() => '?').join(', ')}) AND "created_at" >= ?`), [...chunk, cutoff])).map((row) => String(row.run_id)));
const gone = chunk.filter((run) => !live.has(run));
if (gone.length === 0)
continue;
await this.db.from(this.tableRef).whereIn('run_id', gone).delete();
lapsed.push(...gone);
}
return lapsed.length;
}
/** {@link purgeExpired}, unawaited and at most once a minute. Its failure is not the run's. */
purgeInBackground() {
if (!this.autoPurge || this.ttlSeconds <= 0)
return;
const now = Date.now();
if (now - this.lastAutoPurge < AUTO_PURGE_EVERY_MS)
return;
this.lastAutoPurge = now;
this.purgeExpired(now).catch(() => {
// Retried after the next run to end; a purge that cannot run must not fail a finished turn.
});
}
}
//# sourceMappingURL=lucid-token-stream-sink.js.map