UNPKG

@adonis-agora/agent

Version:

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

133 lines • 8.14 kB
import { type GenuiStats } from '../genui-telemetry.js'; import type { ActorSpendRow, AgentGovernanceQueries, FeatureSpendRow, GovernanceRange, GovernanceThreadDetail, ListRunsFilter, ListRunsResult, ModelSpendRow, PendingApprovalRow, PendingApprovalsFilter, PerToolStatRow, RunDetail, RunReliability, ThreadActivityRow, TimestampRange, ToolCallActivityRow, ToolStatsRange, UsageBreakdownFilter, UsageBreakdownRow, UsageTrendPoint } from '../spi/governance-queries.js'; import type { AgentPricingStore } from '../spi/pricing-store.js'; import { type LucidDatabaseLike } from './lucid.js'; /** Options for {@link LucidGovernanceQueries}. */ export interface LucidGovernanceQueriesOptions { /** * Provision the shared agent tables on first use. Default `true` (the ecosystem convention). The * read-model aggregates the six shared tables; auto-provisioning here is what lets the governance * routes / dashboard answer on a fresh deploy before the first agent run. Set `false` for the migration. */ autoCreateTables?: boolean; } /** * A production {@link AgentGovernanceQueries} — the read/analytics half of the store SPI — backed by * AdonisJS **Lucid** (Knex) over the same five agent tables {@link import('./lucid.js').LucidAgentStore} * writes. Like the store it touches only the structural {@link LucidDatabaseLike} slice, so * `@adonisjs/lucid` stays an *optional peer* (the factory casts the real `db` in). * * Cost is the token ledger priced against the current prices from the injected {@link AgentPricingStore} * (fetched once per query, exactly like the Drizzle/MikroORM references and the loop's cost fold), so a * host that binds its own pricing store controls the cost every governance surface reports. A * provider-reported `cost_usd` on a usage row always wins; an unpriced model contributes 0 cost (its * tokens still count). Omit the pricing store entirely for a zero-cost read-model. Usage is summed in * the database, per model, with UTC days bucketed by integer arithmetic on the epoch-ms `created_at` * (the same on SQLite/Postgres/MySQL), and priced here — the behavioral twin of * {@link import('../testing/in-memory-governance-queries.js').InMemoryGovernanceQueries}. */ export declare class LucidGovernanceQueries implements AgentGovernanceQueries { private readonly db; private readonly pricingStore?; private readonly autoCreateTables; constructor(db: LucidDatabaseLike, pricingStore?: AgentPricingStore | undefined, options?: LucidGovernanceQueriesOptions); /** Provision the shared schema on first use (no-op when disabled), memoized across the stores. */ private ready; private ledgerExpressions; /** * The SQL the rollups read the ledger columns through. With `autoCreateTables` on they always * exist; off, the app's migration may not have added them yet, and the reports then read every row * as an agent turn's rather than fail. Probed once. */ private ledger; /** Provision the shared schema now (what the agent provider calls at app start). Idempotent. */ ensureSchema(): Promise<void>; private loadPricing; /** * Provider-reported cost wins per row; the rest are priced by the cache-aware token estimate (0 * when the model is unpriced). */ private groupCost; /** * The usage ledger summed in the database — per model, and per `by` when given — over the * inclusive UTC-day `range` and/or one thread. A dashboard's ranges span every row of a month or * more; summing them is the database's job, not a page of rows shipped to the process per chart. */ private usageGroups; spendByModel(range: GovernanceRange): Promise<ModelSpendRow[]>; spendByActor(range: GovernanceRange): Promise<ActorSpendRow[]>; usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]>; /** * The ledger summed in the database per model and (feature, source), and per actor when `byActor` * — what {@link spendByFeature} and {@link usageBreakdown} price. Same unreported-token split as * {@link usageGroups}, plus the units non-token rows bill by. */ private featureGroups; /** An unpriced group's tokens at the current price (0 when the model is unpriced). */ private unreportedCost; spendByFeature(range: GovernanceRange): Promise<FeatureSpendRow[]>; usageBreakdown(range: GovernanceRange | TimestampRange, filter?: UsageBreakdownFilter): Promise<UsageBreakdownRow[]>; /** `thread_id → value` for one aggregate over `table`'s rows of `threadIds`. */ private perThread; /** How many of `table`'s rows belong to `threadId`. */ private countForThread; /** * Newest-first recent tool calls, capped at `limit`. Each call's `threadId` is its owning * message's, read for the whole page at once. */ recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>; /** * Newest-first recent threads (soft-deleted excluded, mirroring `listThreads`/the reference), each * with its message count and rolled-up token total, capped at `limit`. */ recentThreads(limit: number): Promise<ThreadActivityRow[]>; /** * Filterable, cursor-paginated run list, newest-first (`started_at` desc, then `id` desc for a * stable tiebreak). `after` is an opaque cursor (over the SAME filter set); a page fetches * `first + 1` rows to learn whether a next page exists. A store without recorded runs yields an * empty page. * * Forward-only, so the returned {@link CursorPage} always carries `prevCursor: null` / * `hasPrev: false` — see `src/pagination.ts`. */ listRuns(filter?: ListRunsFilter): Promise<ListRunsResult>; /** * The full trace of one run: the run row plus every message / tool call / usage row stamped with * its `run_id` (oldest first), and the subset of tool calls still `pending_approval`. `null` when * the run is unknown. */ runDetail(runId: string): Promise<RunDetail | null>; /** * `FROM … WHERE …` over the calls sitting `pending_approval`, each joined to the actor that owns * it: its run's (`run_id`, or its message's, `→ agent_run.actor_ref`), else its thread's * (`message → agent_thread.actor_ref`) for a call recorded before run tracking, else `''`. Joined * rather than looked up per call, so the `actor` filter runs in the database and an inbox costs * one statement however long the backlog. */ private pendingApprovalsFrom; /** Tool calls sitting `pending_approval`, oldest first; `actor` filters, `limit` caps the inbox. */ pendingApprovals(filter?: PendingApprovalsFilter): Promise<PendingApprovalRow[]>; countPendingApprovals(filter?: Pick<PendingApprovalsFilter, 'actor'>): Promise<number>; /** * Per-tool call/failure/rejection/latency rollup over the (optional) range, highest call count * first. `avgDurationMs` is the mean `execution_ms` across calls that recorded one; `null` when * none did. */ genuiStats(range: GovernanceRange): Promise<GenuiStats>; perToolStats(range?: ToolStatsRange): Promise<PerToolStatRow[]>; /** * Success / failure / cancel rates + mean settled-run duration over the (optional) range, bucketed * on `started_at`, plus a per-agent breakdown, a daily runs/failed trend, turn latency and failures * by code over the same rows. A store without recorded runs yields all zeros / `null` duration / * empty breakdown+trend+codes. */ runReliability(range?: ToolStatsRange): Promise<RunReliability>; /** * The thread governance drill-down: metadata + a LIFETIME usage rollup (every usage row ever * recorded for the thread, not range-scoped) + its most recent runs/messages. `null` when the * thread is unknown. Soft-deleted threads still resolve (with `deleted: true`), mirroring * `runDetail`'s "the record exists, render it" posture. */ threadDetail(threadId: string): Promise<GovernanceThreadDetail | null>; } //# sourceMappingURL=lucid-governance-queries.d.ts.map