Public: anyone can read this; the crew can change it.

A Talk turn is charged what it cost, not the session's running total #16110

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16100-a-talk-turn-is-charged-what-it-cost-not → main 0 commits fork

  • Merged. torque/16100-a-talk-turn-is-charged-what-it-cost-not was merged into main as a39cd59.

Review

Sign in to review this change.
7 files changed +259 −8
src/core/migration-pins/20261123130000-conversation-run-reported.pin added +1
@@ -0,0 +1,1 @@
1 b4f2233c66d2a9106a791a3d7f1679f9b649bea3062f78ab7173d545bfc2cdba
src/core/migrations/20261123130000-conversation-run-reported.ts added +6
@@ -0,0 +1,6 @@
1 // What the runner's result named in all for a resumed session (#16100): Claude Code's
2 // total_cost_usd is the session's running total, so a resumed turn is charged the difference
3 // from this figure on the turn before it. 0 when no result named one.
4 export default `
5 ALTER TABLE conversation_run ADD COLUMN reported_usd REAL NOT NULL DEFAULT 0;
6 `;
src/crew/agent_runner.ts +52 −2
@@ -32,6 +32,12 @@ export interface AgentRun {
3232 readonly account?: RunAccount | undefined;
3333 /** A session id to continue. */
3434 readonly resume?: string | undefined;
35 /**
36 * What the resumed session had reported in all before this run (`AgentOutcome.reportedUsd` of
37 * the run before it). A runner whose cost is the session's running total (`cumulativeCost`)
38 * is charged only the difference; absent, or without `resume`, the session starts from zero.
39 */
40 readonly priorUsd?: number | undefined;
3541 readonly env: Record<string, string>;
3642 readonly sandbox: SandboxPolicy;
3743 /** The run's machine's memory and CPU ceilings (`crew/run-cell.ts`); none is today's cell. */
@@ -118,6 +124,12 @@ export interface AgentOutcome {
118124 /** The agent's final message. */
119125 readonly result: string;
120126 readonly costUsd: number;
127 /**
128 * The total the runner reported, when its result named one and it is the session's running
129 * total (`cumulativeCost`): what the next resume is handed as `priorUsd`. `costUsd` is then
130 * this run's own share of it.
131 */
132 readonly reportedUsd?: number | undefined;
121133 readonly turns: number;
122134 /**
123135 * Tokens the model read (fresh input, cache writes and cache reads) and
@@ -160,6 +172,12 @@ export interface AgentRunner {
160172 * says these names; absent, it says the neutral ones (`DEFAULT_TOOLS`).
161173 */
162174 readonly tools?: Partial<ToolNames> | undefined;
175 /**
176 * The cost this runner reports for a resumed session is the session's running total, not the
177 * resumed run's own (Claude Code's `total_cost_usd`). A runner that reports each run's own
178 * leaves it unset and is never adjusted. `reportedUsd` carries the total it named.
179 */
180 readonly cumulativeCost?: boolean | undefined;
163181 /**
164182 * The run log's opening line for a run on `model` with `env`, where this
165183 * runner is not held by a dollar budget: it names the runner and the model
@@ -189,6 +207,7 @@ export interface UsageAsk {
189207 // Wrapped, not bound, so the two modules may load in either order.
190208 const claude: AgentRunner = {
191209 run: (input) => runClaude(input),
210 cumulativeCost: true,
192211 detect: (binary) => detectClaude(binary),
193212 readUsage: (input) => readClaudeUsage(input),
194213 };
@@ -210,8 +229,39 @@ export function briefTools(runner: AgentRunner = currentRunner()): Partial<ToolN
210229 return runner.tools;
211230 }
212231
213 export function runAgent(input: AgentRun): Promise<AgentOutcome> {
214 return currentRunner().run(input);
232 /**
233 * What a resumed run cost by its own account: the total its result named, less what the session
234 * had reported before it, never below zero. A fresh session starts from zero.
235 */
236 export const ownCost = (reported: number, priorUsd: number | undefined): number => {
237 const prior = priorUsd !== undefined && Number.isFinite(priorUsd) ? priorUsd : 0;
238 return Math.max(0, reported - prior);
239 };
240
241 /**
242 * Runs `input` on the current runner. Behind this seam a cumulative runner's cost is made the
243 * run's own (`ownCost`), in the outcome and in the live `onUsage` reports; a runner that reports
244 * per-run cost, a fresh session and a run cut before its result (priced from what streamed) pass
245 * through unchanged.
246 */
247 export async function runAgent(input: AgentRun): Promise<AgentOutcome> {
248 const runner = currentRunner();
249 if (runner.cumulativeCost !== true) return runner.run(input);
250 const prior = input.resume !== undefined && input.resume !== "" ? input.priorUsd : undefined;
251 const out = await runner.run({
252 ...input,
253 onUsage:
254 input.onUsage === undefined
255 ? undefined
256 : (spent) =>
257 input.onUsage?.(
258 spent.costUsd === undefined
259 ? spent
260 : { ...spent, costUsd: ownCost(spent.costUsd, prior) },
261 ),
262 });
263 if (out.reportedUsd === undefined) return out;
264 return { ...out, costUsd: ownCost(out.reportedUsd, prior) };
215265 }
216266
217267 /** The current runner's free read of an account's windows; null when it offers none. */
src/crew/claude.ts +13 −1
@@ -517,7 +517,19 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
517517 reason: `exit ${code}`,
518518 };
519519 }
520 return { ok, sessionId, result, costUsd, turns, tokensIn, tokensOut, contextTokens, contextWindow, reason };
520 return {
521 ok,
522 sessionId,
523 result,
524 costUsd,
525 reportedUsd: costUsd,
526 turns,
527 tokensIn,
528 tokensOut,
529 contextTokens,
530 contextWindow,
531 reason,
532 };
521533 }
522534
523535 /**
src/crew/conversation.ts +42 −5
@@ -137,6 +137,27 @@ export function stopTurn(app: App, userId: string): boolean {
137137 return stopped;
138138 }
139139
140 /**
141 * What session `session` had reported in all before run `runId`: the last total a finished turn
142 * of this conversation stored for that very session (`conversation_run.reported_usd`); 0 when
143 * none did. A lost or renewed session has a new id, so its first turn is charged from zero.
144 */
145 export function reportedBefore(
146 db: App["db"],
147 conversationId: string,
148 runId: string,
149 session: string,
150 ): number {
151 const row = db
152 .query<{ r: number }, [string, string, string]>(
153 `SELECT reported_usd AS r FROM conversation_run
154 WHERE conversation_id = ?1 AND id <> ?2 AND session_id = ?3 AND reported_usd > 0
155 ORDER BY rowid DESC LIMIT 1`,
156 )
157 .get(conversationId, runId, session);
158 return row?.r ?? 0;
159 }
160
140161 /** Turns with a session listening, by conversation id: the run id a message is steered to. */
141162 const live = new Map<string, string>();
142163
@@ -590,6 +611,12 @@ function begin(
590611 budgetUsd: budget,
591612 account: runAccount(picked, modelEnv),
592613 resume: session,
614 // The session's running total before this turn, so the turn is charged its own cost
615 // (#16100).
616 priorUsd:
617 session === undefined
618 ? undefined
619 : reportedBefore(app.db, conversation.id, runId, session),
593620 env: {
594621 ...modelEnv,
595622 CLAUDE_CONFIG_DIR: configDir,
@@ -637,6 +664,8 @@ function begin(
637664 // The turn is over for /talk only once its answer and its figures are stored.
638665 try {
639666 const cost = outcome?.costUsd ?? 0;
667 // The session's running total as its result named it; the next resume is charged from it.
668 const reported = outcome?.reportedUsd ?? 0;
640669 // Stopped for a restart: the row stays `running` for the next boot to
641670 // find, keeping what the session had reported (Claude Code names the
642671 // cost only in its result, so a cut turn keeps its tokens and the cost
@@ -645,7 +674,15 @@ function begin(
645674 // charging it, and the resumed turn is a run of its own charged only its
646675 // own cost (test/talk-stop.test.ts).
647676 if (options.signal.aborted) {
648 app.db.query("UPDATE conversation_run SET tokens_in = ?2, tokens_out = ?3, cost_usd = ?4, context_tokens = ?5, context_window = ?6 WHERE id = ?1").run(runId, outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0);
677 app.db.query("UPDATE conversation_run SET tokens_in = ?2, tokens_out = ?3, cost_usd = ?4, context_tokens = ?5, context_window = ?6, reported_usd = ?7 WHERE id = ?1").run(
678 runId,
679 outcome?.tokensIn ?? 0,
680 outcome?.tokensOut ?? 0,
681 cost,
682 outcome?.contextTokens ?? 0,
683 outcome?.contextWindow ?? 0,
684 reported,
685 );
649686 app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost);
650687 return;
651688 }
@@ -657,8 +694,8 @@ function begin(
657694 // A tell that finished before the stop still filed its issue: say so (#13942).
658695 for (const text of filedTurns(app.db, via, prompt, false)) put("tool", text);
659696 app.db
660 .query("UPDATE conversation_run SET state = 'stopped', stopped = 1, tokens_in = ?2, tokens_out = ?3, cost_usd = ?4, finished_at = ?5, context_tokens = ?6, context_window = ?7 WHERE id = ?1")
661 .run(runId, outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0);
697 .query("UPDATE conversation_run SET state = 'stopped', stopped = 1, tokens_in = ?2, tokens_out = ?3, cost_usd = ?4, finished_at = ?5, context_tokens = ?6, context_window = ?7, reported_usd = ?8 WHERE id = ?1")
698 .run(runId, outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported);
662699 app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost);
663700 return;
664701 }
@@ -681,9 +718,9 @@ function begin(
681718 for (const text of filedTurns(app.db, via, prompt, outcome?.ok === true)) put("tool", text);
682719 app.db
683720 .query(
684 "UPDATE conversation_run SET state = ?2, tokens_in = ?3, tokens_out = ?4, cost_usd = ?5, finished_at = ?6, context_tokens = ?7, context_window = ?8 WHERE id = ?1",
721 "UPDATE conversation_run SET state = ?2, tokens_in = ?3, tokens_out = ?4, cost_usd = ?5, finished_at = ?6, context_tokens = ?7, context_window = ?8, reported_usd = ?9 WHERE id = ?1",
685722 )
686 .run(runId, outcome?.ok ? "ok" : "failed", outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0);
723 .run(runId, outcome?.ok ? "ok" : "failed", outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported);
687724 // Against the account's lifetime budget, like a run's cost (`subscription.spent_usd`).
688725 app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost);
689726 } finally {
test/runner-own-cost.test.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * A resumed run is charged its own cost (#16100): behind the runner seam, a runner whose result
3 * is the session's running total reports the difference from what the session had reported
4 * before; a runner that reports per-run cost, a fresh session and a run cut before its result are
5 * not adjusted. Hand calculation: totals 0.094, 0.184, 0.234 give 0.094, 0.090, 0.050.
6 */
7 import { afterEach, expect, test } from "bun:test";
8 import { ownCost, runAgent, useRunner, type AgentOutcome, type AgentRun, type AgentRunner } from "../src/crew/agent_runner.ts";
9 import { sandboxPolicy } from "../src/crew/sandbox.ts";
10
11 afterEach(() => useRunner(undefined));
12
13 const base: AgentRun = { binary: "x", cwd: ".", prompt: "p", appendSystemPrompt: "", budgetUsd: 1, env: {}, sandbox: sandboxPolicy({ dataDir: ".", agentName: "bot", urls: [] }), label: "t", timeoutMs: 1000, log: () => {}, signal: new AbortController().signal };
14 const outcome = (costUsd: number, reportedUsd?: number): AgentOutcome => ({ ok: true, sessionId: "s", result: "", costUsd, reportedUsd, turns: 1, tokensIn: 0, tokensOut: 0, contextTokens: 0, contextWindow: 0, reason: "completed" });
15 const runner = (total: number, extra: Partial<AgentRunner> = {}, cut = false): AgentRunner => ({
16 run: async (input) => {
17 input.onUsage?.({ tokensIn: 0, tokensOut: 0, costUsd: total });
18 return outcome(total, cut ? undefined : total);
19 },
20 detect: async () => ({ ok: true, version: "x" }),
21 ...extra,
22 });
23
24 test("ownCost is the reported total less the prior one, never below zero", () => {
25 expect(ownCost(0.184, 0.094)).toBeCloseTo(0.09, 9);
26 expect(ownCost(0.094, undefined)).toBe(0.094);
27 expect(ownCost(0.05, 0.2)).toBe(0);
28 });
29
30 test("a cumulative runner resumed three times reports 0.094, 0.090, 0.050", async () => {
31 const costs: number[] = [];
32 let prior = 0;
33 for (const total of [0.094, 0.184, 0.234]) {
34 useRunner(runner(total, { cumulativeCost: true }));
35 const live: number[] = [];
36 const out = await runAgent({ ...base, resume: prior === 0 ? undefined : "s", priorUsd: prior, onUsage: (s) => live.push(s.costUsd ?? 0) });
37 costs.push(out.costUsd);
38 expect(live[0]).toBeCloseTo(out.costUsd, 9);
39 prior = out.reportedUsd ?? 0;
40 }
41 expect(costs[0]).toBeCloseTo(0.094, 9);
42 expect(costs[1]).toBeCloseTo(0.09, 9);
43 expect(costs[2]).toBeCloseTo(0.05, 9);
44 expect(costs.reduce((a, b) => a + b, 0)).toBeCloseTo(0.234, 9);
45 });
46
47 test("a fresh session, a per-run runner and a cut run are not adjusted", async () => {
48 useRunner(runner(0.3, { cumulativeCost: true }));
49 expect((await runAgent({ ...base, priorUsd: 0.2 })).costUsd).toBe(0.3);
50 useRunner(runner(0.3));
51 expect((await runAgent({ ...base, resume: "s", priorUsd: 0.2 })).costUsd).toBe(0.3);
52 useRunner(runner(0.3, { cumulativeCost: true }, true));
53 expect((await runAgent({ ...base, resume: "s", priorUsd: 0.2 })).costUsd).toBe(0.3);
54 });
test/talk-cost.test.ts +91
@@ -4,12 +4,15 @@
44 * to; an unknown cost shows nothing, never $0.
55 */
66 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { chmodSync, writeFileSync } from "node:fs";
78 import { mkdtemp, rm } from "node:fs/promises";
89 import { tmpdir } from "node:os";
910 import { join } from "node:path";
1011 import { createApp, type App } from "../src/app.ts";
1112 import { appendTurn, newConversation } from "../src/core/conversations.ts";
1213 import { conversationTotal, totalText } from "../src/core/conversation_cost.ts";
14 import { PLATFORM } from "../src/core/subscriptions.ts";
15 import { reportedBefore, say } from "../src/crew/conversation.ts";
1316 import { createSession } from "../src/core/sessions.ts";
1417 import { createUser, type User } from "../src/core/users.ts";
1518 import { serve, type Servers } from "../src/http/server.ts";
@@ -96,3 +99,91 @@ describe("talk cost, mixed runs", () => {
9699 expect(page).not.toContain("Spent $0 ");
97100 });
98101 });
102
103 describe("talk cost, a resumed session", () => {
104 test("three resumed turns are each charged their own cost, not the session's running total (#16100)", async () => {
105 // A stand-in `claude` whose result names the session's running total, growing as a resumed
106 // session's does: 0.094, 0.184, 0.234 (the first ten turns of a real conversation, #16100).
107 const counter = join(dir, "count");
108 writeFileSync(counter, "0");
109 const path = join(dir, "claude-growing");
110 writeFileSync(
111 path,
112 `#!/bin/sh
113 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
114 IFS= read -r first
115 n=$(cat ${counter}); n=$((n+1)); echo $n > ${counter}
116 case $n in 1) t=0.094;; 2) t=0.184;; *) t=0.234;; esac
117 echo '{"type":"system","subtype":"init","session_id":"s-grow","model":"fake"}'
118 echo '{"type":"assistant","session_id":"s-grow","message":{"id":"m'$n'","content":[{"type":"text","text":"Answer '$n'."}],"usage":{"input_tokens":10,"output_tokens":5}}}'
119 echo '{"type":"result","subtype":"success","is_error":false,"result":"Answer '$n'.","total_cost_usd":'$t',"num_turns":1,"session_id":"s-grow","terminal_reason":"completed","usage":{"input_tokens":10,"output_tokens":5}}'
120 `,
121 );
122 chmodSync(path, 0o755);
123 const conv = newConversation(app.db, alice.id);
124 const spent = (): number => app.db.query<{ n: number }, [string]>("SELECT spent_usd AS n FROM subscription WHERE id = ?1").get(PLATFORM)!.n;
125 const before = spent();
126 for (const text of ["one", "two", "three"]) {
127 const said = say(app, { binary: path, localUrl: "http://127.0.0.1:9", budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal }, alice.id, text, [], "inject", conv.id);
128 if (!said.ok || said.value.done === undefined) throw new Error("not started");
129 await said.value.done;
130 }
131 const costs = app.db.query<{ cost_usd: number }, [string]>("SELECT cost_usd FROM conversation_run WHERE conversation_id = ?1 ORDER BY rowid").all(conv.id).map((r) => r.cost_usd);
132 // Hand calculation: 0.094, 0.184 - 0.094 = 0.090, 0.234 - 0.184 = 0.050; they add up to 0.234.
133 expect(costs).toHaveLength(3);
134 expect(costs[0]).toBeCloseTo(0.094, 9);
135 expect(costs[1]).toBeCloseTo(0.09, 9);
136 expect(costs[2]).toBeCloseTo(0.05, 9);
137 expect(conversationTotal(app.db, conv.id)).toBeCloseTo(0.234, 9);
138 expect(spent() - before).toBeCloseTo(0.234, 9);
139 });
140 });
141
142 describe("talk cost, a session lost or renewed", () => {
143 test("a turn whose session was lost starts from zero, not from the lost session's total (#16100)", async () => {
144 // First turn: a fresh session whose total is 0.5. Second: its resume is refused as lost, so
145 // the turn runs again in a new session whose total is 0.1; it is charged 0.1, not 0.
146 const path = join(dir, "claude-lost-total");
147 writeFileSync(
148 path,
149 `#!/bin/sh
150 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
151 IFS= read -r first
152 case " $* " in *" --resume "*)
153 echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"","errors":["No conversation found with session ID: s-old"],"total_cost_usd":0,"num_turns":0,"session_id":"s-old"}'
154 exit 1 ;; esac
155 if [ -e ${dir}/lost-total.seen ]; then s=s-new; t=0.1; else s=s-old; t=0.5; touch ${dir}/lost-total.seen; fi
156 echo '{"type":"system","subtype":"init","session_id":"'$s'","model":"fake"}'
157 echo '{"type":"assistant","session_id":"'$s'","message":{"id":"m","content":[{"type":"text","text":"Ok."}],"usage":{"input_tokens":1,"output_tokens":1}}}'
158 echo '{"type":"result","subtype":"success","is_error":false,"result":"Ok.","total_cost_usd":'$t',"num_turns":1,"session_id":"'$s'","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
159 `,
160 );
161 chmodSync(path, 0o755);
162 const conv = newConversation(app.db, alice.id);
163 for (const text of ["one", "two"]) {
164 const said = say(app, { binary: path, localUrl: "http://127.0.0.1:9", budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal }, alice.id, text, [], "inject", conv.id);
165 if (!said.ok || said.value.done === undefined) throw new Error("not started");
166 await said.value.done;
167 }
168 const costs = app.db.query<{ cost_usd: number }, [string]>("SELECT cost_usd FROM conversation_run WHERE conversation_id = ?1 ORDER BY rowid").all(conv.id).map((r) => r.cost_usd);
169 expect(costs).toHaveLength(2);
170 expect(costs[0]).toBeCloseTo(0.5, 9);
171 expect(costs[1]).toBeCloseTo(0.1, 9);
172 });
173
174 test("reportedBefore names the total of the very session asked for, so a renewed session starts at zero", () => {
175 const conv = newConversation(app.db, alice.id);
176 const put = (id: string, session: string, reported: number): void => {
177 app.db
178 .query("INSERT INTO conversation_run (id, conversation_id, user_id, subscription_id, prompt, session_id, started_at, reported_usd) VALUES (?1,?2,?3,?4,'p',?5,?6,?7)")
179 .run(id, conv.id, alice.id, PLATFORM, session, new Date().toISOString(), reported);
180 };
181 put("r1", "s1", 0.2);
182 put("r2", "s1", 0.5);
183 expect(reportedBefore(app.db, conv.id, "r3", "s1")).toBeCloseTo(0.5, 9);
184 // Context renewal: s2 is a new session; its first turn stored 0, and the one after resumes s2.
185 put("r3", "s2", 0.3);
186 expect(reportedBefore(app.db, conv.id, "r4", "s2")).toBeCloseTo(0.3, 9);
187 expect(reportedBefore(app.db, conv.id, "r3", "s2")).toBe(0);
188 });
189 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs