UNPKG

@adonis-agora/agent

Version:

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

172 lines • 10.5 kB
import { type GenuiStats } from '../genui-telemetry.js'; import type { CursorPage, CursorParams } from '../pagination.js'; import type { StoreTenantScope } from '../spi/agent-store.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; /** * The database schema (a Postgres schema, a MySQL database) the agent tables live in — the same * one the agent store writes to. Default: none (the connection's current schema). */ schema?: string; } /** * 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; private readonly schema; /** The agent tables as the query builder names them (`schema.table` under a schema). */ private readonly tables; /** The agent tables as raw SQL names them (`"schema"."table"` under a schema). */ private readonly tablesSql; constructor(db: LucidDatabaseLike, pricingStore?: AgentPricingStore | undefined, options?: LucidGovernanceQueriesOptions); /** The tenant set this view is scoped to; `undefined` → every tenant (the unscoped read-model). */ private tenantScope; /** * A view of this read-model scoped to `scope`: every rollup, list and detail only reads rows whose * `tenant_ref` is in it (rows from a run or thread of another tenant read as unknown). */ forTenants(scope: StoreTenantScope): LucidGovernanceQueries; /** Tenant ids that own threads or runs, sorted, at most `limit` (default 500). */ listTenants(limit?: number): Promise<string[]>; /** The tenant predicate over `column`, or `null` when the view is unscoped. */ private tenantSql; /** `run_id IN (runs of the scope)` for tables keyed by run, or `null` when unscoped. */ private runInScopeSql; /** `message_id IN (messages of the scope's threads)` for tool calls, or `null` when unscoped. */ private messageInScopeSql; /** Whether a row stamped `tenantRef` is inside this view. */ private visible; /** 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` (`table` as raw SQL names it). */ private perThread; /** How many of `table`'s rows belong to `threadId` (`table` as raw SQL names it). */ 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[]>; /** * The tool-call feed one keyset page at a time: `(created_at, id) < cursor`, `first + 1` rows, no * offset. An index on `(created_at, id)` (the opt-in governance list indexes) serves it. */ toolCallsPage(page?: CursorParams): Promise<CursorPage<ToolCallActivityRow>>; private toolCallRows; /** * 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[]>; /** The thread feed one keyset page at a time on `(updated_at, id)`, as {@link toolCallsPage}. */ threadsPage(page?: CursorParams): Promise<CursorPage<ThreadActivityRow>>; private threadRows; /** * Filterable, cursor-paginated run list, newest-first (`started_at` desc, then `id` desc for a * stable tiebreak). `after` is an opaque keyset cursor (over the SAME filter set): the page seeks * past `(started_at, id)` and fetches `first + 1` rows to learn whether a next page exists, so no * page reads the rows above it. A plain offset (`"50"`, what older versions handed out) still * works. 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