@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
114 lines • 5.24 kB
JavaScript
import { validateSchema } from './db-schema.js';
import { agentTables, ensureAgentTables, hasPricingTimestampColumns, } from './lucid-schema.js';
import { toDate } from './timestamps.js';
function toNum(value) {
if (typeof value === 'number')
return value;
if (typeof value === 'bigint')
return Number(value);
if (typeof value === 'string')
return Number.parseFloat(value) || 0;
return 0;
}
/**
* A production {@link AgentPricingStore} backed by AdonisJS **Lucid** (Knex) over the
* `agent_model_pricing` table — the write side the loop's cost fold prices token usage against. Like
* {@link import('./lucid.js').LucidAgentStore} it touches only the structural {@link LucidDatabaseLike}
* slice, so `@adonisjs/lucid` stays an optional peer (the factory casts the real `db` in).
*
* Atomic supersede (mirrors the reference Drizzle/MikroORM stores): `upsertModelPrice` retires the
* model's prior `is_current` row and inserts a fresh current one, so exactly one live price exists
* per model. `effective_from` is stored as epoch-ms (matching the rest of the schema) and read back
* as an ISO string. Booleans are `INTEGER` 0/1 for cross-dialect portability.
*/
export class LucidPricingStore {
db;
autoCreateTables;
schema;
/** The agent tables as the query builder names them (`schema.table` under a schema). */
tables;
/**
* Whether `agent_model_pricing` has `created_at` / `updated_at`. Always so when the store provisions
* the schema; probed once under `autoCreateTables: false`, where the app's migration may lag.
*/
timestampColumns = null;
constructor(db, options = {}) {
this.db = db;
this.autoCreateTables = options.autoCreateTables ?? true;
this.schema = validateSchema(db, options.schema, 'pricingStores.lucid()');
this.tables = agentTables(this.schema);
}
/** Provision the shared schema on first use (no-op when disabled), memoized across the stores. */
ready() {
return this.autoCreateTables
? ensureAgentTables(this.db, { schema: this.schema })
: Promise.resolve();
}
/** Whether the timestamp columns can be written (see {@link timestampColumns}). */
hasTimestamps() {
if (this.autoCreateTables)
return Promise.resolve(true);
if (this.timestampColumns === null) {
const probe = hasPricingTimestampColumns(this.db, this.schema);
probe.catch(() => {
if (this.timestampColumns === probe)
this.timestampColumns = null;
});
this.timestampColumns = probe;
}
return this.timestampColumns;
}
/** Provision the shared schema now (what the agent provider calls at app start). Idempotent. */
ensureSchema() {
return this.ready();
}
async upsertModelPrice(input) {
await this.ready();
const timestamps = await this.hasTimestamps();
const now = Date.now();
// Atomic supersede in a transaction: retire the model's current row, then insert the new one.
await this.db.transaction(async (trx) => {
await trx
.from(this.tables.modelPricing)
.where('model_id', input.modelId)
.where('is_current', 1)
.update(timestamps ? { is_current: 0, updated_at: now } : { is_current: 0 });
await trx.table(this.tables.modelPricing).insert({
id: crypto.randomUUID(),
model_id: input.modelId,
input_price_per_1m: input.inputPricePer1m,
output_price_per_1m: input.outputPricePer1m,
cache_write_price_per_1m: input.cacheWritePricePer1m ?? null,
cache_read_price_per_1m: input.cacheReadPricePer1m ?? null,
effective_from: now,
is_current: 1,
...(timestamps ? { created_at: now, updated_at: now } : {}),
});
});
}
async listCurrentPrices() {
await this.ready();
const rows = await this.db.from(this.tables.modelPricing).where('is_current', 1).select('*');
return rows.map((row) => {
const cacheWrite = row.cache_write_price_per_1m;
const cacheRead = row.cache_read_price_per_1m;
const createdAt = toDate(row.created_at);
const updatedAt = toDate(row.updated_at);
return {
modelId: String(row.model_id),
inputPricePer1m: toNum(row.input_price_per_1m),
outputPricePer1m: toNum(row.output_price_per_1m),
effectiveFrom: new Date(toNum(row.effective_from)).toISOString(),
...(cacheWrite !== null && cacheWrite !== undefined
? { cacheWritePricePer1m: toNum(cacheWrite) }
: {}),
...(cacheRead !== null && cacheRead !== undefined
? { cacheReadPricePer1m: toNum(cacheRead) }
: {}),
...(createdAt ? { createdAt } : {}),
...(updatedAt ? { updatedAt } : {}),
};
});
}
}
//# sourceMappingURL=lucid-pricing.js.map