Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Merge pull request #296 from parz1val-t/fix/turn-token-usage
Salman Qureshibfbed387beb5
diff --cc CHANGELOG.mdindex 4cce1c9a,98052963..1df2bcc6--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -2,20 -2,6 +2,24 @@@## Unreleased++### Token usage++- **Token usage is now counted correctly** (#296, thanks @parz1val-t). Mercury used to record only the last model call of each turn, under-reporting usage by about 6–12×. Every call is now counted, including the steps of a turn that ended early (a failed provider, a pause), so `dailyBudget` fills up and Token Saver kicks in much sooner than before. If you hit the budget earlier than expected, raise `tokens.dailyBudget`, or set `tokens.cachedWeight` (0–1, e.g. `0.1`) to count prompt-cache hits at a discount. `/budget` now shows today's cached, uncached and output split. Usage from past days is not recalculated.++- **Each provider is billed for its own steps** when a turn moves from one provider to another.+++### Faster, cheaper requests+- **Repeat turns hit the prompt cache.** The parts of Mercury's instructions that change between turns (what it knows about you, bot status, the clock, the folder) now come after the cached part. A new message reuses most of the previous request on Anthropic, OpenAI, DeepSeek, Gemini and others, instead of about 900 tokens.+- **Long screen tasks cost far less.** Only the two newest screenshots are sent on each step. On Anthropic, each step reads the conversation so far from cache instead of paying for it again.+- **No more "Starting" for minutes.** If a provider accepts a request and then sends nothing for 150 seconds, Mercury moves to the next provider. Set `MERCURY_FIRST_RESPONSE_TIMEOUT_MS` to change the wait.+- **No more invented skill picks.** Mercury no longer stops to ask which skill you meant, or tells the model you chose a skill (often `web-search`) when you didn't. Matching skills are suggested and the model decides; `#skill-name` still picks one directly.+- **Smaller requests.** The draw.io tools are only sent when you're working on a diagram.++### Chats at the same time+- **Mercury answers several chats at once.** A long research run or coding task in one chat no longer makes the terminal, Telegram, the desktop app or a scheduled task wait. Each chat still handles its own messages in order.+- **Sized to your machine.** Up to 4 chats run at once, 3 under 8 GB of RAM, and 2 on Termux or under 4 GB. When memory runs short, new chats wait for a free slot, and if memory keeps growing the most recently started task stops while the rest carry on. Set `concurrency.maxTurns` in `mercury.yaml` (or `MERCURY_MAX_CONCURRENT_TURNS`) to choose the limit; `1` restores one chat at a time.+- **Stop really stops.** A stopped task no longer comes back a few seconds later. Before, it could resume through an automatic retry after a tool had run, through a stall retry, or through the next message waiting in that chat. Stop also ends everything a running command started (`npm run build` and the like keep going no more) and drops the messages that chat had waiting. A stopped sub-agent stays stopped.+- **No more "(no text response)".** When Mercury Code (or a sub-agent or bot) finishes by writing files or running commands without a closing message, you now get what it did: the files it wrote or edited, and each command with whether it succeeded.+- **`/stop` stops the chat you're in.** Esc in the terminal, the Stop button in Mercury Desktop and `/stop` in Telegram stop that chat's task and the sub-agents it started. `/halt` still stops everything.+### Providers- **Remote Ollama behind a username and password.** Set `username` and `password` on Ollama Local, OpenAI-compatible, LM Studio, LiteLLM or Atomic Chat in `mercury.yaml`. Mercury sends them as HTTP Basic auth for chat and for model lists, instead of a Bearer key.diff --cc src/core/agent.tsindex 79fe984e,68b10528..ff77a35e--- a/src/core/agent.ts+++ b/src/core/agent.ts@@@ -138,6 -134,7 +138,7 @@@ const NOTE_COOLDOWN_MS = 3 * 60 * 1000import { runReflection } from '../learning/reflection.js';import { createOwnerSectionsMemo } from '../learning/owner-brief.js';import type { ApplyResult } from '../memory/beliefs.js';-import { TurnUsage, billingEntries, type StepUsageLike } from './turn-usage.js';++import { TurnUsage, billingEntries, type SourceUsageTotals, type StepUsageLike, type TurnUsageTotals } from './turn-usage.js';/*** Step-aware text stream for the TUI. The SDK's textStream concatenates@@@ -3475,7 -2980,6 +3476,12 @@@ export class Agent});stallWatchdog.start();let canonicalSessionId: string | undefined;+ let releaseSession: (() => void) | null = null;++ // Bills the turn's model steps to the token budget, once. Set when the++ // turn starts calling models; the finally runs it for turns that end++ // early (all providers failed, an honest pause, a memory stop, a retry++ // scheduled) — their steps were spent too.++ let flushTurnUsage: (() => void) | null = null;if (this.supervisor && msg.channelType !== 'internal') {const activeAgents = this.supervisor.getActiveAgents();@@@ -3756,7 -3250,17 +3762,57 @@@[Symbol.iterator](): this.providers.getFallbackIterator();let result: any = null;+ // Every model step this turn adds its own usage here (main loop,+ // continuations, guard, verification). Report THIS, never result.usage:+ // that is the SDK's last step only, and later rounds replace result.+ 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). 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 usageRecorded: { turnTotals: TurnUsageTotals; usageEntries: SourceUsageTotals[]; billedProvider: { name: string; model: string } | null } | null = null;++ const recordTurnUsage = (lastResultUsage?: StepUsageLike) => {++ if (usageRecorded) return usageRecorded;++ // Who billed this turn: the provider that completed, else the last one++ // called (a stopped or failed attempt still billed its finished steps).++ const billedProvider = usedProvider ?? attemptedProvider;++ // Whole-turn usage: every step of every round. Fall back to the last++ // result only if no step reported (a path without step callbacks).++ const turnTotals = turnUsage.totals().steps > 0++ ? turnUsage.totals()++ : (() => {++ const fallback = new TurnUsage();++ fallback.add(lastResultUsage);++ return fallback.totals();++ })();++ // 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,++ });++ }++ usageRecorded = { turnTotals, usageEntries, billedProvider };++ return usageRecorded;++ };++ flushTurnUsage = () => { if (turnUsage.totals().steps > 0) recordTurnUsage(); };let lastError: any = null;let hasCompletedTool = false;let hasStreamedOutput = false;@@@ -4259,11 -3758,13 +4316,12 @@@}}};- const continuationStepHandler = async (toolCalls: any[] | undefined, toolResults: any[] | undefined): Promise<void> => {+ const continuationStepHandler = async (toolCalls: any[] | undefined, toolResults: any[] | undefined, usage?: StepUsageLike): Promise<void> => {this.completedStepCount++;+ turnUsage.add(usage, attemptedProvider);lastRoundSteps++;lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);- const cliChResume = this.channels.get('cli');- if (cliChResume instanceof CLIChannel) cliChResume.bumpLiveActivitySteps();+ this.cliFeed()?.bumpLiveActivitySteps();if (toolCalls && toolResults && toolCalls.length > 0) {hasCompletedTool = true;noteToolSteps(toolCalls, toolResults);@@@ -4296,7 -3797,7 +4354,8 @@@// Per-attempt latency accounting: the only way to answer "why is// coding slow" with data instead of guesses.const attemptStartedAt = Date.now();+ let firstResponse: { received(): void; clear(): void } | null = null;+ attemptedProvider = { name: provider.name, model: provider.getModel() };try {const providerDeadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;this.markProgress(`Calling ${provider.name}...`);@@@ -5235,22 -4714,50 +5300,20 @@@logger.info({ planLength: preGuardText.length }, 'Plan captured from plan-mode response');}- this.tokenBudget.recordUsage({- provider: usedProvider?.name ?? 'unknown',- model: usedProvider?.model ?? 'unknown',- inputTokens: result.usage?.inputTokens ?? 0,- outputTokens: result.usage?.outputTokens ?? 0,- totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),- channelType: msg.channelType,- agentId: this.config.cloud.agentId || undefined,- });+ // Who billed this turn: the provider that completed, else the last one+ // called (a stopped or failed attempt still billed its finished steps).- const billedProvider = usedProvider ?? attemptedProvider;- // Whole-turn usage: every step of every round. Fall back to the last- // result only if no step reported (a path without step callbacks).- const turnTotals = turnUsage.totals().steps > 0- ? turnUsage.totals()- : (() => {- const fallback = new TurnUsage();- fallback.add(result.usage);- return fallback.totals();- })();- // 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,- });- }++ const { turnTotals, usageEntries, billedProvider } = recordTurnUsage(result.usage);logger.info({- provider: usedProvider?.name,- model: usedProvider?.model,- inputTokens: result.usage?.inputTokens ?? 0,- cachedInputTokens: result.usage?.cachedInputTokens ?? 0,- outputTokens: result.usage?.outputTokens ?? 0,+ provider: billedProvider?.name,+ model: billedProvider?.model,+ inputTokens: turnTotals.inputTokens,+ cachedInputTokens: turnTotals.cachedInputTokens,+ noCacheInputTokens: turnTotals.noCacheInputTokens,+ outputTokens: turnTotals.outputTokens,+ 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',@@@ -5444,7 -4950,6 +5508,8 @@@} catch { /* best effort */ }this.lifecycle.transition('idle');} finally {+ releaseSession?.();++ try { flushTurnUsage?.(); } catch (err) { logger.warn({ err }, 'Recording turn token usage failed'); }if (chatFolder) {if (cwdBeforeChatFolder && this.capabilities.getCwd() === chatFolder) this.capabilities.setCwd(cwdBeforeChatFolder);this.chatFolders().close(chatFolder);diff --cc src/eval/scenarios/token-usage.test.tsindex 00000000,00000000..7c036462new file mode 100644--- /dev/null+++ b/src/eval/scenarios/token-usage.test.ts@@@ -1,0 -1,0 +1,51 @@@++import { afterAll, describe, expect, it } from 'vitest';++import { EvalHarness, runScenario } from '../runner.js';++import { call, textStep, toolStep } from '../fixture.js';++++/**++ * #296 on the real agent: a turn bills every model step it made (ai@6's++ * result.usage is the last step only), and a turn that ends early — here++ * a provider failing after a tool ran — still bills the steps it spent.++ */++describe('eval · token usage counts every step (#296)', () => {++ afterAll(async () => {++ const { removeEvalRoot } = await import('../env.js');++ removeEvalRoot();++ });++++ it('a two-step turn reports and bills both steps', async () => {++ const result = await runScenario({++ name: 'usage-two-steps',++ turns: [{++ message: 'write my notes to notes.md',++ steps: [++ toolStep([call('create_file', { path: 'notes.md', content: '- milk\n' })], undefined, { inputTokens: 1000, outputTokens: 50 }),++ textStep('Saved to notes.md.', { inputTokens: 2000, outputTokens: 80 }),++ ],++ }],++ });++ expect(result.failures).toEqual([]);++ // The old code reported the last step only: 2000 / 80.++ expect(result.turns[0].tokens).toMatchObject({ input: 3000, output: 130 });++ });++++ it('a turn that ends early still bills the steps it ran', async () => {++ const harness = await EvalHarness.create({++ name: 'usage-early-exit',++ providers: [{ name: 'scripted', failOnCalls: [2] }],++ turns: [],++ });++ try {++ const before = harness.agent.tokenBudget.getDailyUsed();++ await harness.runTurn({++ message: 'write my notes to notes.md',++ steps: [toolStep([call('create_file', { path: 'notes.md', content: '- milk\n' })], undefined, { inputTokens: 1000, outputTokens: 50 })],++ });++ // Step 1 ran (and its tool), step 2's call failed: the turn ended on the++ // failure path, which used to record nothing.++ expect(harness.agent.tokenBudget.getDailyUsed() - before).toBe(1050);++ } finally {++ await harness.dispose();++ }++ });++});diff --cc website/docs/reference/token-saver.mdxindex 9e256a1d,9e256a1d..c9957c7c--- a/website/docs/reference/token-saver.mdx+++ b/website/docs/reference/token-saver.mdx@@@ -101,8 -101,8 +101,11 @@@ tokenssaverAutoEnabled: true # master switch for auto-engagementsaverAutoThreshold: 75 # percentage at which auto-engage triggerssaverTokensSavedLifetime: 0 # lifetime savings counter++ cachedWeight: 1 # how much a prompt-cache hit counts toward dailyBudget (0–1)```++Every model call in a turn counts toward `dailyBudget`, including the tool steps and any extra rounds. Prompt-cache hits cost far less than fresh input at most providers. Set `cachedWeight` to `0.1` to count them at roughly their price instead of in full. `/budget` shows today's split: cached, uncached and output tokens.++All fields are optional. Existing installs without saver fields work unchanged — defaults are applied silently on read, and no file is rewritten until you first toggle saver on or it auto-engages.## Zero-Impact Guarantee When Off