UNPKG

@adonis-agora/agent

Version:

Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.

196 lines • 7.64 kB
import { ensureDatabaseSchema, qualifiedName, qualifiedSql, validateSchema, } from '../stores/db-schema.js'; import { addMissingColumns, forDialect } from '../stores/lucid-schema.js'; import { isMySql } from '../stores/sql-dialect.js'; import { toDate } from '../stores/timestamps.js'; /** Process-local {@link A2aStore} — tests and single-instance dev. */ export class InMemoryA2aStore { #contexts = new Map(); #messages = new Map(); async getContext(id) { const found = this.#contexts.get(id); if (!found) return null; return { ...found, ...(found.createdAt ? { createdAt: new Date(found.createdAt) } : {}), ...(found.updatedAt ? { updatedAt: new Date(found.updatedAt) } : {}), }; } async createContext(context) { const now = new Date(); this.#contexts.set(context.id, { ...context, createdAt: now, updatedAt: new Date(now) }); } async bindAccount(id, accountRef) { const context = this.#contexts.get(id); if (!context) return false; if (context.accountRef === null) { context.accountRef = accountRef; context.updatedAt = new Date(); } return context.accountRef === accountRef; } async claimMessage(contextId, messageId) { const key = `${contextId}\n${messageId}`; const found = this.#messages.get(key); if (!found) { this.#messages.set(key, { done: false }); return { status: 'claimed' }; } return found.done ? { status: 'done', reply: found.reply } : { status: 'pending' }; } async completeMessage(contextId, messageId, reply) { this.#messages.set(`${contextId}\n${messageId}`, { done: true, reply }); } async releaseMessage(contextId, messageId) { this.#messages.delete(`${contextId}\n${messageId}`); } } export const A2A_TABLES = { contexts: 'agent_a2a_context', messages: 'agent_a2a_message', }; /** * `CREATE TABLE IF NOT EXISTS` DDL for the two A2A tables — same portable dialect as the agent * tables (quoted identifiers, epoch-ms `BIGINT`, `TEXT` JSON). The message table's primary key IS the * idempotency lock: two deliveries of one `messageId` race on the insert and one loses. */ export function a2aTableStatements(schema) { const t = A2A_TABLES; return [ `CREATE TABLE IF NOT EXISTS ${qualifiedSql(t.contexts, schema)} ( "id" VARCHAR(255) PRIMARY KEY NOT NULL, "brand" VARCHAR(255) NOT NULL, "agent_issuer" VARCHAR(2048) NOT NULL, "agent_sub" VARCHAR(255) NOT NULL, "account_ref" VARCHAR(255) NULL, "created_at" BIGINT NOT NULL, "updated_at" BIGINT NULL )`, `CREATE TABLE IF NOT EXISTS ${qualifiedSql(t.messages, schema)} ( "context_id" VARCHAR(255) NOT NULL, "message_id" VARCHAR(255) NOT NULL, "reply" TEXT NULL, "created_at" BIGINT NOT NULL, PRIMARY KEY ("context_id", "message_id") )`, ]; } /** * Create the A2A tables if missing. Idempotent. `schema` puts them in that database schema (created * when missing); refused on SQLite. */ export async function ensureA2aTables(db, options = {}) { const schema = validateSchema(db, options.schema, 'config/a2a.ts'); const mysql = isMySql(db); if (schema !== undefined) await ensureDatabaseSchema(db, schema); for (const statement of a2aTableStatements(schema)) { // MySQL reads `"quoted"` names as strings: backticks there, like the other stores' DDL. await db.rawQuery(forDialect(statement, mysql)); } // Added after the table first shipped: `CREATE TABLE IF NOT EXISTS` cannot reach an existing one. // NULL-able with no default — instant, and a context from before simply has none. await addMissingColumns(db, A2A_ADDITIVE_COLUMNS, schema); } /** Columns added to the A2A tables after they first shipped. */ const A2A_ADDITIVE_COLUMNS = [ { table: A2A_TABLES.contexts, column: 'updated_at', type: 'BIGINT NULL' }, ]; /** {@link A2aStore} over Lucid (any of SQLite / Postgres / MySQL). */ export class LucidA2aStore { db; /** The tables as the query builder names them (`schema.table` under a `schema`). */ #tables; constructor(db, options = {}) { this.db = db; const schema = validateSchema(db, options.schema, 'config/a2a.ts'); this.#tables = { contexts: qualifiedName(A2A_TABLES.contexts, schema), messages: qualifiedName(A2A_TABLES.messages, schema), }; } async getContext(id) { const row = await this.db.from(this.#tables.contexts).where('id', id).first(); if (!row) return null; return { id: String(row.id), brand: String(row.brand), agentIssuer: String(row.agent_issuer), agentSub: String(row.agent_sub), accountRef: row.account_ref == null ? null : String(row.account_ref), ...withDate('createdAt', row.created_at), ...withDate('updatedAt', row.updated_at), }; } async createContext(context) { const now = Date.now(); await this.db.table(this.#tables.contexts).insert({ id: context.id, brand: context.brand, agent_issuer: context.agentIssuer, agent_sub: context.agentSub, account_ref: context.accountRef, created_at: now, updated_at: now, }); } async bindAccount(id, accountRef) { await this.db .from(this.#tables.contexts) .where('id', id) .whereNull('account_ref') .update({ account_ref: accountRef, updated_at: Date.now() }); // Re-read rather than trust the update count: a concurrent bind to the SAME account also wins. const context = await this.getContext(id); return context?.accountRef === accountRef; } async claimMessage(contextId, messageId) { try { await this.db.table(this.#tables.messages).insert({ context_id: contextId, message_id: messageId, reply: null, created_at: Date.now(), }); return { status: 'claimed' }; } catch (error) { const row = await this.#message(contextId, messageId); if (!row) throw error; return row.reply == null ? { status: 'pending' } : { status: 'done', reply: JSON.parse(String(row.reply)) }; } } async completeMessage(contextId, messageId, reply) { await this.db .from(this.#tables.messages) .where('context_id', contextId) .where('message_id', messageId) .update({ reply: JSON.stringify(reply) }); } async releaseMessage(contextId, messageId) { await this.db .from(this.#tables.messages) .where('context_id', contextId) .where('message_id', messageId) .whereNull('reply') .delete(); } #message(contextId, messageId) { return this.db .from(this.#tables.messages) .where('context_id', contextId) .where('message_id', messageId) .first(); } } /** `{ [key]: Date }` when `value` is a time, else nothing — so an unknown time stays absent. */ function withDate(key, value) { const date = toDate(value); return date ? { [key]: date } : {}; } //# sourceMappingURL=store.js.map