Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(tokens): bill each step to the provider that ran it

parz1valc9c6a0e11a83
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 5848236e..68b10528 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -134,7 +134,7 @@ const NOTE_COOLDOWN_MS = 3 * 60 * 1000;
import { runReflection } from '../learning/reflection.js';
import { createOwnerSectionsMemo } from '../learning/owner-brief.js';
import type { ApplyResult } from '../memory/beliefs.js';
-import { TurnUsage, type StepUsageLike } from './turn-usage.js';
+import { TurnUsage, billingEntries, type StepUsageLike } from './turn-usage.js';
/**
* Step-aware text stream for the TUI. The SDK's textStream concatenates
@@ -3256,8 +3256,10 @@ export class Agent {
const turnUsage = new TurnUsage();
let usedProvider: { name: string; model: string } | null = null;
// The provider most recently called, even if that attempt never
- // completed (/stop, abort, error). Usage accounting falls back to it so
- // a stopped turn's billed steps aren't filed under "unknown".
+ // completed (/stop, abort, error). Set before every model call (main
+ // loop, guard, resume, verification): each step's usage is billed to
+ // it, so steps from a provider that failed before a fallback stay
+ // billed to that provider, and a stopped turn isn't filed as "unknown".
let attemptedProvider: { name: string; model: string } | null = null;
let lastError: any = null;
let hasCompletedTool = false;
@@ -3456,7 +3458,7 @@ export class Agent {
// continuation rounds (resume / verification) share a lighter handler.
const stepHandler = (path: 'stream' | 'gen') => async ({ toolCalls, toolResults, usage }: { toolCalls?: any[]; toolResults?: any[]; usage?: StepUsageLike }): Promise<void> => {
this.completedStepCount++;
- turnUsage.add(usage);
+ turnUsage.add(usage, attemptedProvider);
// Completion-contract tracking: per-round step usage and how
// the step ended (tool calls pending = work in progress).
lastRoundSteps++;
@@ -3758,7 +3760,7 @@ export class Agent {
};
const continuationStepHandler = async (toolCalls: any[] | undefined, toolResults: any[] | undefined, usage?: StepUsageLike): Promise<void> => {
this.completedStepCount++;
- turnUsage.add(usage);
+ turnUsage.add(usage, attemptedProvider);
lastRoundSteps++;
lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
const cliChResume = this.channels.get('cli');
@@ -3971,7 +3973,7 @@ export class Agent {
abortSignal: loopAbortController.signal,
experimental_include: { requestBody: false },
// Billed like any other step: count it in the turn total.
- onStepFinish: ({ usage }) => { turnUsage.add(usage); },
+ onStepFinish: ({ usage }) => { turnUsage.add(usage, attemptedProvider); },
})),
loopAbortController,
providerDeadlineAt,
@@ -4354,6 +4356,7 @@ export class Agent {
const guardProvider = providersForAttempt[guardProviderCursor % providersForAttempt.length];
guardProviderCursor++;
if (!guardProvider) break;
+ attemptedProvider = { name: guardProvider.name, model: guardProvider.getModel() };
try {
this.markProgress(`Resuming with ${guardProvider.name}...`);
const guardDeadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;
@@ -4389,7 +4392,7 @@ export class Agent {
experimental_include: { requestBody: false },
onStepFinish: async ({ toolCalls, toolResults, usage }) => {
this.completedStepCount++;
- turnUsage.add(usage);
+ turnUsage.add(usage, attemptedProvider);
// Completion-contract tracking for the guard round.
lastRoundSteps++;
lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
@@ -4516,6 +4519,7 @@ export class Agent {
? (providersForAttempt.find((p) => p.name === usedProvider!.name && p.getModel() === usedProvider!.model) ?? providersForAttempt[0])
: providersForAttempt[0];
if (!resumeProvider) break;
+ attemptedProvider = { name: resumeProvider.name, model: resumeProvider.getModel() };
lastRoundSteps = 0;
try {
const round = await this.runInlineContinuationRound({
@@ -4578,6 +4582,7 @@ export class Agent {
? (providersForAttempt.find((p) => p.name === usedProvider!.name && p.getModel() === usedProvider!.model) ?? providersForAttempt[0])
: providersForAttempt[0];
if (verifyProvider) {
+ attemptedProvider = { name: verifyProvider.name, model: verifyProvider.getModel() };
lastRoundSteps = 0;
try {
const round = await this.runInlineContinuationRound({
@@ -4721,18 +4726,27 @@ export class Agent {
fallback.add(result.usage);
return fallback.totals();
})();
- this.tokenBudget.recordUsage({
- provider: billedProvider?.name ?? 'unknown',
- model: billedProvider?.model ?? 'unknown',
- inputTokens: turnTotals.inputTokens,
- outputTokens: turnTotals.outputTokens,
- totalTokens: turnTotals.totalTokens,
- // The split lets tokens.cachedWeight discount cache hits in the budget.
- cachedInputTokens: turnTotals.cachedInputTokens,
- noCacheInputTokens: turnTotals.noCacheInputTokens,
- channelType: msg.channelType,
- agentId: this.config.cloud.agentId || undefined,
- });
+ // One budget entry per provider+model: a turn that fell back bills the
+ // failed provider for its finished steps and the fallback for the rest.
+ const usageEntries = billingEntries(
+ turnTotals,
+ turnUsage.totals().steps > 0 ? turnUsage.bySource() : [],
+ billedProvider,
+ );
+ for (const entry of usageEntries) {
+ this.tokenBudget.recordUsage({
+ provider: entry.provider,
+ model: entry.model,
+ inputTokens: entry.inputTokens,
+ outputTokens: entry.outputTokens,
+ totalTokens: entry.totalTokens,
+ // The split lets tokens.cachedWeight discount cache hits in the budget.
+ cachedInputTokens: entry.cachedInputTokens,
+ noCacheInputTokens: entry.noCacheInputTokens,
+ channelType: msg.channelType,
+ agentId: this.config.cloud.agentId || undefined,
+ });
+ }
logger.info({
provider: billedProvider?.name,
model: billedProvider?.model,
@@ -4743,6 +4757,7 @@ export class Agent {
reasoningTokens: turnTotals.reasoningTokens,
steps: this.completedStepCount,
usageSteps: turnTotals.steps,
+ ...(usageEntries.length > 1 ? { usageByProvider: usageEntries.map((e) => ({ provider: e.provider, model: e.model, inputTokens: e.inputTokens, outputTokens: e.outputTokens })) } : {}),
toolCalls: turnToolTrace.length,
historyEntries: recentMemory.length,
activeTools: activeTools?.length ?? 'all',
diff --git a/src/core/turn-usage.test.ts b/src/core/turn-usage.test.ts
index 73162fef..2a187d04 100644
--- a/src/core/turn-usage.test.ts
+++ b/src/core/turn-usage.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { TurnUsage } from './turn-usage.js';
+import { TurnUsage, billingEntries } from './turn-usage.js';
// The per-step input figures from the 4-step gateway probe in the bug report:
// the SDK's result.usage returned only the last (574); the turn spent 1,902.
@@ -66,3 +66,60 @@ describe('TurnUsage', () => {
expect(t.steps).toBe(2);
});
});
+
+describe('per-provider billing', () => {
+ const primary = { name: 'anthropic', model: 'claude-sonnet' };
+ const fallback = { name: 'openai', model: 'gpt-5' };
+
+ it('bills steps from a provider that failed before a fallback to that provider', () => {
+ // The primary finishes two tool steps, then errors; the fallback
+ // provider runs the turn to completion in three steps.
+ const u = new TurnUsage();
+ u.add({ inputTokens: 1000, outputTokens: 20, inputTokenDetails: { cacheReadTokens: 800, noCacheTokens: 200 } }, primary);
+ u.add({ inputTokens: 1100, outputTokens: 30, inputTokenDetails: { cacheReadTokens: 900, noCacheTokens: 200 } }, primary);
+ u.add({ inputTokens: 1500, outputTokens: 40 }, fallback);
+ u.add({ inputTokens: 1600, outputTokens: 50 }, fallback);
+ u.add({ inputTokens: 1700, outputTokens: 60 }, fallback);
+
+ const entries = billingEntries(u.totals(), u.bySource(), fallback);
+ expect(entries).toEqual([
+ expect.objectContaining({ provider: 'anthropic', model: 'claude-sonnet', inputTokens: 2100, cachedInputTokens: 1700, noCacheInputTokens: 400, outputTokens: 50, steps: 2 }),
+ expect.objectContaining({ provider: 'openai', model: 'gpt-5', inputTokens: 4800, cachedInputTokens: 0, outputTokens: 150, steps: 3 }),
+ ]);
+ });
+
+ it('keeps one entry for a turn served by a single provider', () => {
+ const u = new TurnUsage();
+ for (const step of probeSteps) u.add(step, primary);
+ const entries = billingEntries(u.totals(), u.bySource(), primary);
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({ provider: 'anthropic', inputTokens: 1902, outputTokens: 165, steps: 4 });
+ });
+
+ it('separates two models of the same provider', () => {
+ const u = new TurnUsage();
+ u.add({ inputTokens: 100, outputTokens: 1 }, { name: 'openai', model: 'a' });
+ u.add({ inputTokens: 200, outputTokens: 2 }, { name: 'openai', model: 'b' });
+ expect(u.bySource().map((s) => [s.model, s.inputTokens])).toEqual([['a', 100], ['b', 200]]);
+ });
+
+ it('bills untagged usage to the fallback, and entries always sum to the turn', () => {
+ const u = new TurnUsage();
+ u.add({ inputTokens: 300, outputTokens: 3 }, primary);
+ u.add({ inputTokens: 400, outputTokens: 4 });
+ const entries = billingEntries(u.totals(), u.bySource(), fallback);
+ expect(entries.map((e) => [e.provider, e.inputTokens, e.outputTokens])).toEqual([['anthropic', 300, 3], ['openai', 400, 4]]);
+ const sum = entries.reduce((n, e) => n + e.totalTokens, 0);
+ expect(sum).toBe(u.totals().totalTokens);
+ });
+
+ it('falls back to a single entry when no step reported usage', () => {
+ // The no-step-callback path: totals come from result.usage instead.
+ const fromResult = new TurnUsage();
+ fromResult.add({ inputTokens: 500, outputTokens: 5 });
+ expect(billingEntries(fromResult.totals(), [], primary)).toEqual([
+ expect.objectContaining({ provider: 'anthropic', inputTokens: 500, outputTokens: 5 }),
+ ]);
+ expect(billingEntries(fromResult.totals(), [], null)[0]).toMatchObject({ provider: 'unknown', model: 'unknown' });
+ });
+});
diff --git a/src/core/turn-usage.ts b/src/core/turn-usage.ts
index 521e03b3..a2e04fa8 100644
--- a/src/core/turn-usage.ts
+++ b/src/core/turn-usage.ts
@@ -43,6 +43,17 @@ export interface TurnUsageTotals {
steps: number;
}
+/** The provider and model a step was sent to. */
+export interface UsageSource {
+ name: string;
+ model: string;
+}
+
+export interface SourceUsageTotals extends TurnUsageTotals {
+ provider: string;
+ model: string;
+}
+
const count = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
export class TurnUsage {
@@ -52,10 +63,25 @@ export class TurnUsage {
private output = 0;
private reasoning = 0;
private stepCount = 0;
+ /** Per provider+model, so a fallback turn bills each provider its own steps. */
+ private readonly sources = new Map<string, { source: UsageSource; usage: TurnUsage }>();
- /** Add one step's usage. Missing or malformed fields count as 0. */
- add(usage: StepUsageLike | null | undefined): void {
+ /**
+ * Add one step's usage. Missing or malformed fields count as 0. `source`
+ * is the provider the step was sent to; steps without one count toward
+ * the turn total only.
+ */
+ add(usage: StepUsageLike | null | undefined, source?: UsageSource | null): void {
if (!usage || typeof usage !== 'object') return;
+ if (source) {
+ const key = `${source.name}\u0000${source.model}`;
+ let bucket = this.sources.get(key);
+ if (!bucket) {
+ bucket = { source: { name: source.name, model: source.model }, usage: new TurnUsage() };
+ this.sources.set(key, bucket);
+ }
+ bucket.usage.add(usage);
+ }
const input = count(usage.inputTokens);
const cached = count(usage.inputTokenDetails?.cacheReadTokens ?? usage.cachedInputTokens);
const noCacheReported = usage.inputTokenDetails?.noCacheTokens;
@@ -81,4 +107,43 @@ export class TurnUsage {
steps: this.stepCount,
};
}
+
+ /** Totals per provider+model, in the order each was first used. */
+ bySource(): SourceUsageTotals[] {
+ return [...this.sources.values()].map(({ source, usage }) => ({
+ provider: source.name,
+ model: source.model,
+ ...usage.totals(),
+ }));
+ }
+}
+
+/**
+ * The budget entries for one turn: one per provider+model that ran steps,
+ * so a turn that fell back bills the failed provider for its finished steps
+ * and the fallback for the rest. Usage not tagged with a provider (or a
+ * turn whose totals came from somewhere other than step callbacks) goes to
+ * `fallback`. The entries always add up to `totals`.
+ */
+export function billingEntries(
+ totals: TurnUsageTotals,
+ sources: SourceUsageTotals[],
+ fallback: UsageSource | null,
+): SourceUsageTotals[] {
+ const rest: SourceUsageTotals = {
+ provider: fallback?.name ?? 'unknown',
+ model: fallback?.model ?? 'unknown',
+ ...totals,
+ };
+ for (const s of sources) {
+ rest.inputTokens -= s.inputTokens;
+ rest.cachedInputTokens -= s.cachedInputTokens;
+ rest.noCacheInputTokens -= s.noCacheInputTokens;
+ rest.outputTokens -= s.outputTokens;
+ rest.reasoningTokens -= s.reasoningTokens;
+ rest.totalTokens -= s.totalTokens;
+ rest.steps -= s.steps;
+ }
+ if (sources.length > 0 && rest.totalTokens <= 0) return sources;
+ return [...sources, rest];
}