UNPKG

@adonis-agora/agent

Version:

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

73 lines • 3.23 kB
import { exhaustedWindow, quotaPeriodRange, quotaWarning, } from '../spi/quota-provider.js'; /** * A {@link QuotaProvider} over the usage ledger: a day window (tokens from `quotaToday`, spend from * `usageBetween` when the store has it), and a month window when the store implements * `usageBetween`. Ceilings come from `limits`; a {@link QuotaStore} passed alongside lends the day * window its own token ceiling when `limits.day.tokens` does not set one. * * Spend is what the usage rows recorded: the provider-reported cost of a gateway, plus the loop's * estimate for a provider that reports none (unless `countEstimatedCost: false`). */ export class LedgerQuotaProvider { store; quota; limits; options; constructor(store, quota, limits = {}, options = {}) { this.store = store; this.quota = quota; this.limits = limits; this.options = options; } async report(query) { const now = query.now ?? new Date(); const actorRef = query.actor.id; const windows = [await this.dayWindow(actorRef, now)]; if (this.store.usageBetween !== undefined) { const range = quotaPeriodRange('month', now); const used = await this.store.usageBetween(actorRef, range.fromDay, range.toDay); windows.push(this.window('month', used.usedTokens, this.usd(used), range.resetsAt)); } const blocked = exhaustedWindow(windows); const warning = quotaWarning(windows); return { windows, ...(blocked !== undefined ? { blocked } : {}), ...(warning !== undefined ? { warning } : {}), }; } async dayWindow(actorRef, now) { const range = quotaPeriodRange('day', now); const used = this.store.usageBetween !== undefined ? await this.store.usageBetween(actorRef, range.fromDay, range.toDay) : { ...(await this.store.quotaToday(actorRef, range.fromDay)), costUsd: 0 }; const window = this.window('day', used.usedTokens, this.usd(used), range.resetsAt); if (this.quota !== undefined && window.limitTokens === undefined) { window.limitTokens = (await this.quota.check(actorRef, range.fromDay)).limitTokens; } return window; } /** The window's USD: every priced row, or (with `countEstimatedCost: false`) reported cost only. */ usd(used) { if (this.options.countEstimatedCost === false) { return Math.max(0, used.costUsd - (used.estimatedCostUsd ?? 0)); } return used.costUsd; } window(period, usedTokens, usedUsd, resetsAt) { const limits = this.limits[period] ?? {}; return { period, usedTokens, ...(limits.tokens !== undefined ? { limitTokens: limits.tokens } : {}), usedUsd, ...(limits.usd !== undefined ? { limitUsd: limits.usd } : {}), resetsAt, ...(this.options.warnAt !== undefined && (limits.tokens !== undefined || limits.usd !== undefined) ? { warnAt: this.options.warnAt } : {}), }; } } //# sourceMappingURL=ledger-quota-provider.js.map