Skip to content

Commit af907a0

Browse files
fix(diagnostics): preserve CLI turn usage totals
1 parent c245cfc commit af907a0

11 files changed

Lines changed: 181 additions & 76 deletions

‎src/agents/agent-command.ingress-diagnostics.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,47 @@ describe("emitIngressModelUsageDiagnostic", () => {
235235
});
236236
});
237237

238+
it("uses terminal cumulative usage only for the diagnostic event and cost", () => {
239+
const result = makeResult({
240+
agentMeta: {
241+
diagnosticUsage: {
242+
input: 900,
243+
output: 300,
244+
cacheRead: 70,
245+
cacheWrite: 30,
246+
total: 1300,
247+
},
248+
},
249+
});
250+
251+
testing.emitIngressModelUsageDiagnostic(result, makeOpts());
252+
253+
expect(mocks.estimateUsageCost).toHaveBeenCalledWith({
254+
usage: {
255+
input: 900,
256+
output: 300,
257+
cacheRead: 70,
258+
cacheWrite: 30,
259+
total: 1300,
260+
},
261+
cost: {},
262+
});
263+
expect(mocks.emitTrustedDiagnosticEvent).toHaveBeenCalledWith(
264+
expect.objectContaining({
265+
usage: {
266+
input: 900,
267+
output: 300,
268+
cacheRead: 70,
269+
cacheWrite: 30,
270+
promptTokens: 1000,
271+
total: 1300,
272+
},
273+
lastCallUsage: { input: 500, output: 200 },
274+
context: { limit: 128000, used: 1200 },
275+
}),
276+
);
277+
});
278+
238279
it("does not emit when diagnostics are disabled", () => {
239280
mocks.isDiagnosticsEnabled.mockReturnValue(false);
240281
const result = makeResult();

‎src/agents/cli-output.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2683,6 +2683,34 @@ describe("createCliJsonlStreamingParser", () => {
26832683
]);
26842684
});
26852685

2686+
it("preserves terminal cumulative usage when reparsing completed Claude JSONL", () => {
2687+
const output = parseCliJsonl(
2688+
readFileSync("test/fixtures/cli/claude-2.1-thinking-progress.jsonl", "utf8"),
2689+
{
2690+
command: "claude",
2691+
output: "jsonl",
2692+
jsonlDialect: "claude-stream-json",
2693+
sessionIdFields: ["session_id"],
2694+
},
2695+
"claude-cli",
2696+
);
2697+
2698+
expect(output.usage).toEqual({
2699+
input: 4418,
2700+
output: 5,
2701+
cacheRead: undefined,
2702+
cacheWrite: 36955,
2703+
total: undefined,
2704+
});
2705+
expect(output.diagnosticUsage).toEqual({
2706+
input: 4418,
2707+
output: 534,
2708+
cacheRead: undefined,
2709+
cacheWrite: 36955,
2710+
total: undefined,
2711+
});
2712+
});
2713+
26862714
it("resets per-index thinking state on a new message within the same turn (tool round-trip)", () => {
26872715
const thinking: Array<{ text: string; delta: string; isReasoningSnapshot?: boolean }> = [];
26882716
const parser = createCliJsonlStreamingParser({

‎src/agents/cli-output.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2063,6 +2063,7 @@ function parseCliJsonl(
20632063
let sessionId: string | undefined;
20642064
let resumeCheckpointId: string | undefined;
20652065
let usage: CliUsage | undefined;
2066+
let diagnosticUsage: CliUsage | undefined;
20662067
const texts: string[] = [];
20672068
let streamJsonText = "";
20682069
let pendingMessageSeparator = false;
@@ -2085,6 +2086,11 @@ function parseCliJsonl(
20852086
resumeCheckpointId =
20862087
pickCliResumeCheckpointId({ backend, providerId, parsed }) ?? resumeCheckpointId;
20872088
const nextUsage = readCliUsage(parsed);
2089+
const isClaudeTerminalResult =
2090+
isClaudeStreamJsonDialect({ backend, providerId }) && parsed.type === "result";
2091+
if (isClaudeTerminalResult && nextUsage && usage) {
2092+
diagnosticUsage = nextUsage;
2093+
}
20882094
const shouldUseUsage = !isClaudeStreamJsonResult({ backend, providerId, parsed }) || !usage;
20892095
if (shouldUseUsage) {
20902096
usage = nextUsage ?? usage;
@@ -2161,6 +2167,7 @@ function parseCliJsonl(
21612167
...claudeResult,
21622168
text,
21632169
...(resumeCheckpointId ? { resumeCheckpointId } : {}),
2170+
...(diagnosticUsage ? { diagnosticUsage } : {}),
21642171
};
21652172
segmentStart = streamJsonText.length;
21662173
currentMessageStart = segmentStart;

‎src/agents/cli-runner.context-engine.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ describe("runPreparedCliAgent context engine lifecycle", () => {
158158
rawText: " final answer ",
159159
sessionId: "external-cli-session-1",
160160
usage: { input: 11, output: 7, total: 18 },
161+
diagnosticUsage: { input: 21, output: 9, total: 30 },
161162
finalPromptText: "prompt sent to cli",
162163
});
163164
loadCliSessionContextEngineMessagesMock.mockReset();
@@ -236,6 +237,11 @@ describe("runPreparedCliAgent context engine lifecycle", () => {
236237
const result = await runPreparedCliAgent(context);
237238

238239
expect(result.meta.agentMeta?.sessionId).toBe("external-cli-session-1");
240+
expect(result.meta.agentMeta).toMatchObject({
241+
usage: { input: 11, output: 7, total: 18 },
242+
lastCallUsage: { input: 11, output: 7, total: 18 },
243+
diagnosticUsage: { input: 21, output: 9, total: 30 },
244+
});
239245
expect(loadCliSessionContextEngineMessagesMock).toHaveBeenCalledWith({
240246
sessionId: "openclaw-session-1",
241247
sessionFile: "session.jsonl",

‎src/agents/cli-runner.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,6 +1356,9 @@ export async function runPreparedCliAgent(
13561356
...preparedContextAgentMeta,
13571357
usage: resultParams.output.usage,
13581358
...(resultParams.output.usage ? { lastCallUsage: resultParams.output.usage } : {}),
1359+
...(resultParams.output.diagnosticUsage
1360+
? { diagnosticUsage: resultParams.output.diagnosticUsage }
1361+
: {}),
13591362
...(persistedCliSessionId
13601363
? {
13611364
cliSessionBinding: {

‎src/agents/command/ingress-diagnostics.ts‎

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,23 @@ import { estimateUsageCost, resolveModelCostConfig } from "../../utils/usage-for
44
import { hasNonzeroUsage } from "../usage.js";
55
import type { AgentCommandIngressOpts } from "./types.js";
66

7+
type AgentCommandUsage = {
8+
input?: number;
9+
output?: number;
10+
cacheRead?: number;
11+
cacheWrite?: number;
12+
total?: number;
13+
};
14+
715
type AgentCommandResult = {
816
meta?: {
917
agentMeta?: {
1018
provider?: string;
1119
model?: string;
1220
sessionId?: string;
13-
usage?: {
14-
input?: number;
15-
output?: number;
16-
cacheRead?: number;
17-
cacheWrite?: number;
18-
total?: number;
19-
};
20-
lastCallUsage?: {
21-
input?: number;
22-
output?: number;
23-
cacheRead?: number;
24-
cacheWrite?: number;
25-
total?: number;
26-
};
21+
usage?: AgentCommandUsage;
22+
diagnosticUsage?: AgentCommandUsage;
23+
lastCallUsage?: AgentCommandUsage;
2724
contextTokens?: number;
2825
promptTokens?: number;
2926
};
@@ -46,7 +43,7 @@ export function emitIngressModelUsageDiagnostic(
4643
return;
4744
}
4845
const agentMeta = result.meta?.agentMeta;
49-
const usage = agentMeta?.usage;
46+
const usage = agentMeta?.diagnosticUsage ?? agentMeta?.usage;
5047
if (!agentMeta || !hasNonzeroUsage(usage)) {
5148
return;
5249
}

‎src/agents/embedded-agent-runner/types.ts‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import type {
1717
import type { McpAppChannelView } from "../mcp-ui-resource.js";
1818
import type { FallbackAttempt } from "../model-fallback.types.js";
1919
import type { AgentRunTimeoutPhase } from "../run-timeout-attribution.js";
20-
import type { ContextUsage } from "../usage.js";
20+
import type { NormalizedUsage } from "../usage.js";
2121

2222
export type BlockReplyFlushContext =
2323
| {
@@ -35,6 +35,8 @@ export type BlockReplyFlushContext =
3535
attemptAccepted: boolean;
3636
};
3737

38+
type EmbeddedAgentUsage = Omit<NormalizedUsage, "contextUsage">;
39+
3840
export type EmbeddedAgentMeta = {
3941
sessionId: string;
4042
sessionFile?: string;
@@ -58,30 +60,17 @@ export type EmbeddedAgentMeta = {
5860
* and completion tokens that are useful for billing but noisy as live context.
5961
*/
6062
promptTokens?: number;
61-
usage?: {
62-
input?: number;
63-
output?: number;
64-
cacheRead?: number;
65-
cacheWrite?: number;
66-
reasoningTokens?: number;
67-
total?: number;
68-
};
63+
usage?: EmbeddedAgentUsage;
64+
/** Terminal cumulative usage reserved for turn-level diagnostics. */
65+
diagnosticUsage?: EmbeddedAgentUsage;
6966
/**
7067
* Usage from the last individual API call (not accumulated across tool-use
7168
* loops or compaction retries). Used for context-window utilization display
7269
* (`totalTokens` in sessions.json) because the accumulated `usage.input`
7370
* sums input tokens from every API call in the run, which overstates the
7471
* actual context size.
7572
*/
76-
lastCallUsage?: {
77-
input?: number;
78-
output?: number;
79-
cacheRead?: number;
80-
cacheWrite?: number;
81-
contextUsage?: ContextUsage;
82-
reasoningTokens?: number;
83-
total?: number;
84-
};
73+
lastCallUsage?: NormalizedUsage;
8574
contextBudgetStatus?: SessionContextBudgetStatus;
8675
/**
8776
* True when code mode owned the model tool surface for this run. Config

‎src/auto-reply/reply/agent-runner-result-payloads.ts‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ export async function prepareReplyAgentPayloads(state: {
8181
fallbackAttempts,
8282
fallbackExhausted,
8383
fallbackTransition,
84-
hasBillableUsageBuckets,
8584
modelUsed,
8685
payloadArray,
8786
preserveUserFacingSessionState,
@@ -483,13 +482,14 @@ export async function prepareReplyAgentPayloads(state: {
483482

484483
await signalTypingIfNeeded(guardedReplyPayloads, typingSignals);
485484

486-
if (isDiagnosticsEnabled(cfg) && hasNonzeroUsage(usage)) {
487-
const input = usage.input ?? 0;
488-
const output = usage.output ?? 0;
489-
const cacheRead = usage.cacheRead ?? 0;
490-
const cacheWrite = usage.cacheWrite ?? 0;
485+
const diagnosticUsage = runResult.meta?.agentMeta?.diagnosticUsage ?? usage;
486+
if (isDiagnosticsEnabled(cfg) && hasNonzeroUsage(diagnosticUsage)) {
487+
const input = diagnosticUsage.input ?? 0;
488+
const output = diagnosticUsage.output ?? 0;
489+
const cacheRead = diagnosticUsage.cacheRead ?? 0;
490+
const cacheWrite = diagnosticUsage.cacheWrite ?? 0;
491491
const usagePromptTokens = input + cacheRead + cacheWrite;
492-
const totalTokens = usage.total ?? usagePromptTokens + output;
492+
const totalTokens = diagnosticUsage.total ?? usagePromptTokens + output;
493493
const contextUsedTokens = deriveContextPromptTokens({
494494
lastCallUsage: runResult.meta?.agentMeta?.lastCallUsage,
495495
promptTokens,
@@ -500,8 +500,13 @@ export async function prepareReplyAgentPayloads(state: {
500500
model: modelUsed,
501501
config: cfg,
502502
});
503-
const costUsd = hasBillableUsageBuckets
504-
? estimateUsageCost({ usage, cost: costConfig })
503+
const hasDiagnosticBillableUsageBuckets =
504+
diagnosticUsage.input !== undefined ||
505+
diagnosticUsage.output !== undefined ||
506+
diagnosticUsage.cacheRead !== undefined ||
507+
diagnosticUsage.cacheWrite !== undefined;
508+
const costUsd = hasDiagnosticBillableUsageBuckets
509+
? estimateUsageCost({ usage: diagnosticUsage, cost: costConfig })
505510
: undefined;
506511
emitTrustedDiagnosticEvent({
507512
type: "model.usage",

‎src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -866,11 +866,18 @@ describe("runReplyAgent auto-compaction token update", () => {
866866
});
867867

868868
it("reports live diagnostic context from promptTokens, not provider usage totals", async () => {
869-
const { usageEvent } = await runBaseReplyWithAgentMeta({
869+
const { sessionKey, stored, usageEvent } = await runBaseReplyWithAgentMeta({
870870
tmpPrefix: "openclaw-usage-diagnostic-",
871871
collectDiagnostics: true,
872872
agentMeta: {
873873
usage: { input: 75_000, output: 5_000, cacheRead: 25_000, total: 105_000 },
874+
diagnosticUsage: {
875+
input: 90_000,
876+
output: 8_000,
877+
cacheRead: 30_000,
878+
cacheWrite: 2_000,
879+
total: 130_000,
880+
},
874881
lastCallUsage: { input: 55_000, output: 2_000, cacheRead: 25_000, total: 82_000 },
875882
promptTokens: 44_000,
876883
},
@@ -887,11 +894,12 @@ describe("runReplyAgent auto-compaction token update", () => {
887894
expectRecordFields(
888895
usagePayload.usage,
889896
{
890-
input: 75_000,
891-
output: 5_000,
892-
cacheRead: 25_000,
893-
promptTokens: 100_000,
894-
total: 105_000,
897+
input: 90_000,
898+
output: 8_000,
899+
cacheRead: 30_000,
900+
cacheWrite: 2_000,
901+
promptTokens: 122_000,
902+
total: 130_000,
895903
},
896904
"usage diagnostic usage",
897905
);
@@ -903,6 +911,7 @@ describe("runReplyAgent auto-compaction token update", () => {
903911
},
904912
"usage diagnostic context",
905913
);
914+
expect(stored[sessionKey as keyof typeof stored]?.totalTokens).toBe(44_000);
906915
});
907916

908917
it("falls back to last-call prompt usage for live diagnostic context", async () => {

0 commit comments

Comments
 (0)