Skip to main content

Why cost attribution matters

When agents make LLM calls, every token has a price. In multi-agent systems where one agent can spawn or delegate to others, costs accumulate across multiple providers and chains. Without proper attribution you cannot answer basic questions: which agent is responsible for a $200 spike? Which tool is burning the most budget? Did the delegation chain for last night’s job exceed its allocation? Cost attribution gives you per-agent, per-tool, and per-delegation-chain cost records. Alert callbacks and a budget check read the same cost records, so you can react to spend as it is recorded. The module reports and alerts; it does not block anything by itself.

Setup

Configuration options

string
default:"'USD'"
Currency code stored on each cost record. It is a label only, no conversion happens, and the input field is still named costUsd.
{ warn: number; critical: number }
default:"undefined (no threshold alerts)"
Amounts for 24-hour rolling spend that trigger alerts. Only used when onAlert is also set.
(alert: CostAlert) => void | Promise<void>
default:"undefined"
Called from recordCost() when 24-hour spend is at or above a threshold, or when monthly spend has reached a budget policy limit.
number
default:"90"
How many days of cost events to keep. Older rows are deleted on cleanup().

Recording costs

Call recordCost() after each LLM response or API call. Pass the raw token counts and the exact dollar amount from the provider’s response.

RecordCostInput

string
The agent that incurred this cost.
string
Provider and model identifier, e.g. ‘openai:gpt-4o’, ‘anthropic:claude-3-5-sonnet’, ‘mcp:github’.
number
default:"undefined"
Prompt tokens consumed.
number
default:"undefined"
Completion tokens generated.
number
Exact cost in the configured currency.
Record<string, unknown>
default:"undefined"
Any additional data to store alongside this event (request IDs, model version, etc.).
string
default:"undefined"
When set, this event is also attributed to the given delegation chain.
Costs are stored internally as integer microdollars (value × 1,000,000) to avoid floating-point drift across aggregations.

Provider helpers

Generating cost reports

Per-agent report

Pass a custom period to narrow the query:

CostReport

string
Agent (or owner/chain) this report covers.
{ start: Date; end: Date }
The time window the report covers.
number
Total cost across all events in the period.
Array<{ tool: string; costUsd: number; callCount: number }>
Cost breakdown per tool, sorted by cost descending.
Array<{ date: string; costUsd: number }>
Daily spend as YYYY-MM-DD strings, sorted ascending.

Owner report

Aggregate cost across all agents owned by a user:

Top agents by cost

Find the most expensive agents in any period:

Delegation chain report

getDelegationChainCost(chainId) returns all events recorded with that delegationChainId, regardless of date. The returned report uses the chain ID in its agentId field and a default 30-day period value that does not filter the events. When agents delegate to sub-agents, you can attribute all costs back to the originating chain by passing delegationChainId in recordCost():

Setting up alerts

Alerts are evaluated inside recordCost() and only when onAlert is set. There are three alert types: Alerts are level-triggered, not edge-triggered: every recordCost() call made while spend is above a threshold fires the alert again, so deduplicate in onAlert if you notify humans. Budget alerts need onAlert but not alertThresholds. A failed recordCost() returns an error result; an onAlert that throws is caught and also returns RECORD_COST_FAILED (the cost row is already written).

CostAlert

'warn' | 'critical' | 'budget_exceeded'
Severity of the alert.
string
The agent that triggered the alert.
number
The actual spend that triggered the alert.
number
The limit that was crossed.
string
Time window for this alert, e.g. ‘24h’ or ‘monthly’.

Integration with budget policies

checkBudget() reads budget policies created via theauth.policies and compares them against calendar-month spend from the cost events table. It only considers policies whose agentId equals the agent (user-wide or tenant-wide policies are ignored), and only the maxTokensCostPerMonth limit; the daily and call-count limits and the policy action are not used. It reports; enforcing the result is up to your code. theauth.authorize() does not call it.
To set a budget limit, create a policy with maxTokensCostPerMonth:
The budget_exceeded alert fires from recordCost() once spend has reached this limit (withinBudget is false when spend is equal to or above the limit). The action: 'block' value is stored on the policy but nothing in the cost module acts on it, so revoke or block the agent yourself in onAlert.

Maintenance

Cost events accumulate. Run cleanup() periodically to remove events older than the retention window:
If you configured retentionDays on the module, you can call cleanup() with no arguments and it uses that value.

Return types

All methods return a Result<T> union:
Check result.success before accessing result.data. Error codes:

Budget policies

Create the policies that checkBudget() reads. Policies are not enforced by authorize().

Audit trail

The authorization log. Cost events are stored separately, in their own table.

Trust scoring

Trust levels you can combine with spend data in your own logic.

Rate limiting

Hard call-count caps per agent, per resource, per hour.
Last modified on October 18, 2026