Aviary
Guides

Cost & Governance

The usage ledger and read-model — spend per model and actor, a gateway's reported cost preferred over a cache-aware estimate, daily quota, and the console that surfaces it all.

Every turn writes a row to a usage ledger. A read-model rolls those rows up into spend per model, spend per actor, a usage trend over time, and recent tool-call / thread activity — the numbers behind the governance console. Cost is resolved per row, and the model is honest about what it knows: a gateway's real reported cost wins; otherwise it estimates, and the estimate accounts for prompt caching.


The ledger

Each model turn appends an agent_token_usage row: the actor, thread, run, model id, purpose, the token counts, the feature it was for (agent:<agent name>), and — when a gateway reported it — the real dollar cost. AI spend outside agent turns goes on the same ledger through AgentService.recordUsage, so one cost, one quota and one dashboard cover all of it. Aggregation happens in the read-model, in-process, so the day-bucketing stays engine-portable across MikroORM and Drizzle.

Every row is also published as aviary:agent:usage.recorded (amounts and attribution, never content) — see Diagnostics events.

Recording usage outside agent turns

An app pays for AI that never goes through an agent turn: transcription (billed by audio seconds), text-to-speech (by characters), embeddings in a batch job, a spellcheck that calls an SDK directly. AgentService.recordUsage writes those rows:

constructor(private readonly agent: AgentService) {}

await this.agent.recordUsage({
  actorRef: user.id,          // who pays — null for platform cost
  feature: 'transcription',   // free-form: what it was for
  modelId: 'whisper-1',
  provider: 'openai',
  audioSeconds: 312.4,
  costUsd: 0.0312,
  costSource: 'estimate',     // 'provider' (the default) when the provider reported it
  metadata: { meetingId },
});

actorRef: null is platform cost, recorded under PLATFORM_ACTOR_REF ('@platform') — actor_ref stays non-null, so every per-actor read keeps working and the platform is one more row in spend by actor. Every unit is optional: tokens (inputTokens, outputTokens, the cache split), audioSeconds, characters, requests (absent → one; at least 1 — every rollup's requests counts a row as that many). threadId, runId, tenantRef and metadata (your JSON, never read by the library) attribute the row; nothing requires a thread — thread_id is nullable, and the foreign key still cascades a deleted thread's rows.

It never throws into your flow: a failed write or an invalid input (an empty feature, a negative amount) is logged and answered with { recorded: false, error }, a good one with { recorded: true }. Pass { throwOnError: true } where losing the row must fail the caller.

What counts toward the quota: the token windows sum inputTokens + outputTokens, so a row billed in audio seconds or characters adds nothing there — seconds are not tokens; the USD windows sum costUsd, so every priced row counts whatever its unit. Platform cost counts against nobody. A token-only budget does not limit audio; a USD budget limits everything that was priced.

Spend you budget yourself. The agent's quota is the assistant's budget. If the app meters some AI on its own (indexing a library into embeddings, a spellcheck with its own allowance), counting it here too would lock a person out of the assistant for the day. Pass countsTowardsQuota: false:

await this.agent.recordUsage({
  actorRef: user.id,
  feature: 'embeddings',
  modelId: 'text-embedding-3-small',
  inputTokens: 480_000,
  countsTowardsQuota: false,
});

The row stays in the ledger, every report and usage.recorded (which then carries countsTowardsQuota: false); quotaToday / usageBetween / usageWindows — the token and USD windows — skip it, and no QuotaStore counter is bumped. It is stored in agent_token_usage.counts_towards_quota (boolean, NOT NULL DEFAULT true, so every older row counts), added by both adapters' heal; the quota reads add counts_towards_quota = true to the rows the (actor_ref, created_at) index already narrows to one actor's window, so they stay one index range scan.

A call whose provider named no model leaves modelId out (or passes null): it is recorded as 'unknown' (UNKNOWN_MODEL), the loop's own convention.


Cost per row: reported wins, else estimate

costUsd = COALESCE(reportedCostUsd, cache-aware token estimate)

Cost is computed per usage row and then summed — never once on an aggregate — so a gateway-priced turn and a token-estimated turn can sit side by side in the same rollup and each be correct.

A gateway's reported cost wins

A gateway knows the real spend of a turn. When it reports one, the model provider surfaces it on the turn result and it is stored verbatim:

ProviderWhere the real cost comes from
Vercel AI GatewayproviderMetadata.gateway.cost
OpenRoutertotal_cost
Direct (Anthropic / OpenAI / Bedrock)only tokens reported → falls through to the estimate

Your ModelProvider sets costUsd on the ModelTurnResult when it has it; the loop persists it to the nullable cost_usd column, and the read-model uses it verbatim. Preferring the report per row is why prompt-cache pricing skew never reaches numbers a gateway already priced.

// inside your ModelProvider.runTurn — pass the gateway's number straight through
return {
  text,
  toolCalls,
  usage: { inputTokens, outputTokens },
  costUsd: providerMetadata?.gateway?.cost, // undefined for direct providers — that's fine
};

The fallback estimate is cache-aware

When no gateway priced the turn, the estimate runs against the current pricing row for the model (AgentModelPricing where isCurrent). Prompt caching makes a naive inputTokens × inputPrice wrong — cache writes cost a premium, cache reads a fraction — so the estimate splits the input side:

estimate =
    uncachedInput × inputPricePer1m
  + cacheWrite    × cacheWritePricePer1m   (falls back to inputPricePer1m)
  + cacheRead     × cacheReadPricePer1m    (falls back to inputPricePer1m)
  + output        × outputPricePer1m

MessageUsage carries the split, and the counts are subsets of inputTokens (uncachedInput = inputTokens − cacheWrite − cacheRead):

interface MessageUsage {
  inputTokens: number;  // the whole input side, cached and uncached alike
  outputTokens: number;
  cacheWriteTokens?: number; // subset of inputTokens — billed at a premium
  cacheReadTokens?: number;  // subset of inputTokens — billed at a discount
  reasoningTokens?: number;  // subset of outputTokens — observability only (output-rate)
}

Backward compatible by construction

Because the cache counts are subsets of inputTokens, token totals and quota never change when a breakdown is present. And because the cache rates are nullable, a pricing table with no cache data reduces exactly to the old input×inputPrice + output×outputPrice. Reasoning tokens ride along for observability but are billed at the output rate, so they don't move the estimate.


The pricing table

Prices are versioned rows keyed by model, with the live one flagged isCurrent. Add the nullable cache rates to make the fallback precise for prompt-cached models:

// one current row per model
{
  modelId: 'claude-sonnet-4-6',
  inputPricePer1m: 3,
  outputPricePer1m: 15,
  cacheWritePricePer1m: 3.75, // ~1.25× input
  cacheReadPricePer1m: 0.3,   // ~0.1× input
  effectiveFrom: new Date('2026-06-01T00:00:00Z'),
  isCurrent: true,
}

Supersede a price by inserting a new isCurrent: true row and clearing the flag on the old one; the read-model always joins to the current row, and historical rows are ignored.

Seeding prices

Unpriced models cost $0

The pricing table starts empty. Until something writes a row for a model, that model's estimate has no current price to join against, and every turn against it is costed at $0 — tokens still accumulate correctly, only the dollar figure is missing. Seeding prices isn't optional for accurate cost reporting; it's a required setup step, same as wiring a store.

The write side is a separate SPI, AgentPricingStore (from @dudousxd/nestjs-agent-core), bound to the AGENT_PRICING_STORE token by the same store module that binds AGENT_STORE:

interface AgentPricingStore {
  upsertModelPrice(input: ModelPriceInput): Promise<void>; // atomic supersede — retires the old
                                                             // current row, inserts a new one now
  listCurrentPrices(): Promise<CurrentModelPrice[]>;
}

Inject it and seed prices at boot, either one at a time with upsertModelPrice or in bulk with the seedModelPrices(store, prices[]) helper:

import { Inject, Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { AGENT_PRICING_STORE, seedModelPrices, type AgentPricingStore } from '@dudousxd/nestjs-agent';

@Injectable()
export class SeedAgentPricing implements OnApplicationBootstrap {
  constructor(@Inject(AGENT_PRICING_STORE) private readonly pricing: AgentPricingStore) {}

  async onApplicationBootstrap() {
    await seedModelPrices(this.pricing, [
      { modelId: 'claude-sonnet-4-6', inputPricePer1m: 3, outputPricePer1m: 15, cacheWritePricePer1m: 3.75, cacheReadPricePer1m: 0.3 },
    ]);
  }
}

upsertModelPrice is the same atomic supersede described above, just exposed as a real write path instead of a manual insert — it retires the model's current row and inserts the new one as current, effective now. -store-mikro-orm and -store-drizzle both ship an implementation (MikroOrmPricingStore / DrizzlePricingStore); -testing ships InMemoryPricingStore for tests.


The read-model

AgentGovernanceQueries is the read/analytics half of the store SPI (the write half is AgentStore). The store adapters bind it to the AGENT_GOVERNANCE_QUERIES token, so the surfaces just inject it:

MethodReturns
spendByModel(range)requests / input+output tokens / cost, per model
spendByActor(range)requests / total tokens / cost, per actor
usageTrend(range)total tokens + cost bucketed by day
spendByFeature?(range)requests / tokens / audio seconds / characters / cost per feature, agent turns (source: 'agent') and recorded usage ('external') side by side
usageBreakdown?(range, { actor?, feature?, reprice? })the same per actor × feature — cost by actor and by feature, with the estimated share and unpricedRows. range is UTC days or { from, to } instants (to exclusive). reprice: false reports recorded cost only, leaving unpriced rows at 0 instead of pricing their tokens
recentToolCalls(limit)latest tool calls with status + thread
recentThreads(limit)latest threads with message count + tokens
runMetrics(range)success/error rate, retries, p95 run duration
runsByAgent(range)run counts broken down by agent name
runErrors(range)failure counts broken down by error code
runTrend(range)run + failure counts bucketed by day
recentRuns(limit)latest runs with promptHash, duration, outcome
pendingApprovals(limit)oldest-first pending action-tool calls, joined to thread/actor
toolStats(range)per-tool calls / failed / rejected counts + p95 execution time
toolCallsPage(query) / threadsPage(query) / runsPage(query)the same tool-call/thread/run activity, paginated and filterable

The run-reliability and tool-governance methods (runMetrics through toolStats, and runsPage) are required members of the interface — an external adapter must implement them, but one whose backing store never records runs (no recordRunStart, see Persistence) is free to return zeros/empty rather than throw, and the dashboard renders an empty state instead of erroring.

For unit tests and the offline demo, @dudousxd/nestjs-agent-testing ships an InMemoryGovernanceQueries with an optional pricing map (default empty → zero cost, tokens still counted) and in-memory implementations of every read above.


Run reliability

Every run's start and end are durably recorded (see Persistence), so the read-model can answer "is the agent healthy" as a real signal instead of a diagnostics-tailing guess: success/error rate, retry counts, run duration as a distribution (p50/p95), a run/failure trend over time, a failure breakdown by error code, and a recent-runs table that carries each run's promptHash — a stable fingerprint of the resolved system prompt (pre-RAG) that lets you correlate an error-rate spike with a specific prompt change rather than guessing from timing alone.

Where a run's time goes

A completed run also persists where its time went: queue_ms (enqueue → the body starting), model_ms and tools_ms (totals), model_calls, tool_calls, and the per-step breakdown in timings (each step's model time and its tool calls' name and ms). recentRuns / runsPage carry the totals, runDetail the steps, and run.finished all of it. None of it is a new clock:

  • Queue — the durable runtime's own run row: createdAt, written when the run was started, read once on the body's first execution. The enqueuing process's clock against the worker's. Inline, about 0. Written at start, so a failed run has it too.
  • Model — each llm.turn span's duration, journaled with the model result (inline llm:<i> or the dispatched llm step's result).
  • Tools — each executed call's tool.execution time (the same figure as agent_tool_call.execution_ms), journaled by the call's persist checkpoint. A step's tool time is the union of its calls' windows, so parallel calls count once. Approval waits and a delegation's time are not tool time.

Because each figure rides the journal entry of the step that measured it, a durable replay reads it back instead of measuring again: a resumed run counts every step once, whichever slice ran it, and the time it spent parked is in none of the totals — it is what separates durationMs from queue

  • model + tools.

Tool governance

toolStats(range) rolls the tool-call ledger up per tool: how many times it was called, how many failed, how many were rejected at the approval gate, and the p95 execution time. It's the per-tool complement to the per-model/per-actor cost views above — the number to reach for when one tool is timing out or getting rejected disproportionately, not just costing the most.


The approvals inbox

Pending action tool calls (see Human-in-the-loop & Durability) are a governance surface in their own right: pendingApprovals(limit) lists them oldest-first, joined to their thread and actor, and both shipped surfaces render an Approvals section with approve/reject affordances (and a nav badge for the pending count).

Deciding from the console — rather than from the chat UI watching the run — goes through the AGENT_APPROVAL_PORT SPI, described in full in Human-in-the-loop & Durability: it routes through the same durable-signal / inline-resolution decision path as chat approvals, without re-running chat's ownership check, and records who decided via executedByRef. Under actionApprovalMode: 'independent' the port's approveActionProposal / rejectActionProposal decide a proposal instead, by thread and proposal id (Action proposals). When no AGENT_APPROVAL_PORT is bound, the dashboard's approval endpoints answer 501 and the SPA renders the inbox read-only rather than pretending decisions are being applied.


Paginated, filterable lists

toolCallsPage, threadsPage, and runsPage back the console's list views with real pagination instead of a latest-N cap: a neutral GovernancePageQuery<TWhere> (page, pageSize, a typed where) returns a GovernancePage with a real COUNT, offset paging, deterministic id tiebreaks, and case-insensitive title search where relevant. The dashboard's HTTP surface speaks the Aviary list wire the rest of the ecosystem uses — page, size, filter[field]=value, answering { data, meta }, with an unknown filter field 400ing — so the SPA's tables get prev/next paging with per-table filters. The latest-N reads (recentToolCalls, recentThreads, recentRuns) remain for the Telescope bridge, which doesn't need pagination.


Quota

GET /agent/quota reports the actor's budget across windows — each { period, usedTokens?, limitTokens?, usedUsd, limitUsd?, resetsAt?, warnAt? } — blocked when one is used up, and warning ({ period, ratio, reason? }) when one is past its soft limit. It comes from a QuotaProvider; the default LedgerQuotaProvider reads this ledger (a day window, plus month when the store has usageBetween or usageWindows) and, unconfigured, only reports. Both SQL stores sum the ledger in the database and answer both windows in one statement (usageWindows), so a quota check costs the same whatever the number of usage rows. Tokens count inputTokens + outputTokens, unaffected by the cache split.

One option configures it:

AgentModule.forRoot({
  // ceilings on the default provider — tokens and/or USD, per window
  quota: { limits: { day: { tokens: 200_000 }, month: { usd: 20 } }, warnAt: 0.8 },
  // …or the host's own budget, e.g. what an AI gateway says is left
  // quota: { report: async ({ actor }) => gatewayBudget(actor.id) },
});

Either form turns on the send gate: while the report is blocked, POST /agent/chat answers 429 with { code: 'quota_exceeded', period, message } before any work — no model call, no usage row. The limits apply per actor — per browser in anonymous mode, where a public deployment without them has unbounded spend. To count a whole organization's spend instead, set per: 'tenant' (or 'actor-in-tenant'); see Tenancy. On the client, useAgentChat reads the report and refuses to send while it is blocked (chat.blocked, composer.blockedBy === 'quota'), and chat.quota.warning names the window past warnAt — see Frontend. A message waiting in a thread's queue is checked as it starts; a spent budget pauses the queue (quota_exceeded).


Follow-up suggestions cost an extra call

AgentModule.forRoot({ followUps: true | { count } }) proposes short follow-up questions after the final turn — but it does so with one additional model call, over and above the turn's own steps. That call writes its own usage row (purpose: 'follow_ups'), so it shows up in spendByModel / spendByActor like any other, and it counts against quota the same as a normal step. It's off by default for exactly this reason — turn it on only where the extra spend is worth the UX. See Configuration for the option.


So does a structured answer

@Agent({ outputSchema }) restates the turn's final answer as a schema with one additional, non-streamed model call — plus up to outputRepairAttempts more when a reply fails validation. Each attempt writes its own row with purpose: 'structured_output' and counts against quota like any other step. It is a separate pass rather than a constraint on the turn's own calls for reasons covered in Structured output; the cost is the price of it.


Surfacing it

Both surfaces read the same AGENT_GOVERNANCE_QUERIES read-model and tail live tool-call / quota signals off the aviary:agent:* diagnostics channel — pick either or both.

A bundled React SPA served by a NestJS module, mounted at its own route, no Telescope required:

import { AgentDashboardModule } from '@dudousxd/nestjs-agent-dashboard';

@Module({ imports: [AgentDashboardModule.forRoot({ basePath: '/ai-gateway' })] })
export class AppModule {}

The in-process analog of a hosted AI-gateway dashboard — spend per model/actor, spend by feature (agent turns and recorded usage side by side, in the units each billed), usage trend, and live activity — at /ai-gateway. A run's drill-down shows where its time went: queue / model / tools / other, then each step's model time and tool calls.

Any consumer can subscribe

The read-model and the diagnostics channel are public. Beyond the shipped surfaces, your app can query AGENT_GOVERNANCE_QUERIES for its own billing export, or subscribe to aviary:agent:* for alerts and metrics — the library instruments nothing in your code.


On this page