Skip to content

Commit e6ec74c

Browse files
authored
fix(compaction): preserve Anthropic context usage (#99864)
1 parent 5f2df24 commit e6ec74c

47 files changed

Lines changed: 2384 additions & 127 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
8928bb6ffc8ab7149502410bea3634ad737a574a490e43accced6ce5fe586c0c plugin-sdk-api-baseline.json
2-
5573bf9f5f3d6802a673c2406e2298de06f14128efb2dcdb779fa430b3abe602 plugin-sdk-api-baseline.jsonl
1+
6648558dcec4765bcb21a0837b3c19331129636b55741280ccc2837df9c03579 plugin-sdk-api-baseline.json
2+
c86d4ddbfc2e5842d87796dc06454fbf3ccf61f851417c38553f98dbf6f49279 plugin-sdk-api-baseline.jsonl

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,6 +1357,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
13571357
- H2: Operations and approval
13581358
- H2: Setup bootstrap
13591359
- H2: Model-assisted planner
1360+
- H3: CLI harness trust model
13601361
- H2: Switching to an agent
13611362
- H2: Message rescue mode
13621363
- H2: Related

‎packages/agent-core/src/harness/compaction/compaction.test.ts‎

Lines changed: 120 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,128 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { createAssistantMessageEventStream } from "../../llm.js";
33
import type { AssistantMessage, Model, StreamFn } from "../../llm.js";
4-
import { compact, generateSummary } from "./compaction.js";
4+
import {
5+
calculateContextTokens,
6+
compact,
7+
estimateContextTokens,
8+
generateSummary,
9+
} from "./compaction.js";
510
import { createFileOps } from "./utils.js";
611

12+
describe("calculateContextTokens", () => {
13+
it("prefers the final-iteration context snapshot over aggregate billing usage", () => {
14+
expect(
15+
calculateContextTokens({
16+
input: 12,
17+
output: 15_104,
18+
cacheRead: 819_661,
19+
cacheWrite: 93_130,
20+
contextUsage: {
21+
state: "available",
22+
promptTokens: 148_874,
23+
totalTokens: 163_978,
24+
},
25+
totalTokens: 927_907,
26+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
27+
}),
28+
).toBe(163_978);
29+
});
30+
31+
it("preserves the numeric compatibility fallback when the snapshot is unavailable", () => {
32+
expect(
33+
calculateContextTokens({
34+
input: 12,
35+
output: 15_104,
36+
cacheRead: 819_661,
37+
cacheWrite: 93_130,
38+
contextUsage: { state: "unavailable" },
39+
totalTokens: 927_907,
40+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
41+
}),
42+
).toBe(927_907);
43+
});
44+
45+
it("estimates the transcript instead of using aggregate billing when context is unavailable", () => {
46+
const estimate = estimateContextTokens([
47+
{ role: "user", content: "hello", timestamp: 0 },
48+
{
49+
role: "assistant",
50+
content: [{ type: "text", text: "done" }],
51+
api: "anthropic-messages",
52+
provider: "anthropic",
53+
model: "claude-fable-5",
54+
usage: {
55+
input: 12,
56+
output: 15_104,
57+
cacheRead: 819_661,
58+
cacheWrite: 93_130,
59+
contextUsage: { state: "unavailable" },
60+
totalTokens: 927_907,
61+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
62+
},
63+
stopReason: "stop",
64+
timestamp: 1,
65+
},
66+
]);
67+
68+
expect(estimate.tokens).toBeLessThan(927_907);
69+
expect(estimate.tokens).toBeGreaterThan(0);
70+
expect(estimate.usageTokens).toBe(0);
71+
expect(estimate.lastUsageIndex).toBeNull();
72+
});
73+
74+
it("uses the previous exact snapshot and estimates only the unavailable tail", () => {
75+
const estimate = estimateContextTokens([
76+
{
77+
role: "assistant",
78+
content: [{ type: "text", text: "previous" }],
79+
api: "anthropic-messages",
80+
provider: "anthropic",
81+
model: "claude-fable-5",
82+
usage: {
83+
input: 12,
84+
output: 1_000,
85+
cacheRead: 148_862,
86+
cacheWrite: 0,
87+
contextUsage: {
88+
state: "available",
89+
promptTokens: 148_874,
90+
totalTokens: 149_874,
91+
},
92+
totalTokens: 149_874,
93+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
94+
},
95+
stopReason: "stop",
96+
timestamp: 0,
97+
},
98+
{ role: "user", content: "next", timestamp: 1 },
99+
{
100+
role: "assistant",
101+
content: [{ type: "text", text: "done" }],
102+
api: "anthropic-messages",
103+
provider: "anthropic",
104+
model: "claude-fable-5",
105+
usage: {
106+
input: 12,
107+
output: 15_104,
108+
cacheRead: 819_661,
109+
cacheWrite: 93_130,
110+
contextUsage: { state: "unavailable" },
111+
totalTokens: 927_907,
112+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
113+
},
114+
stopReason: "stop",
115+
timestamp: 2,
116+
},
117+
]);
118+
119+
expect(estimate.usageTokens).toBe(149_874);
120+
expect(estimate.tokens).toBeGreaterThan(149_874);
121+
expect(estimate.tokens).toBeLessThan(927_907);
122+
expect(estimate.lastUsageIndex).toBe(0);
123+
});
124+
});
125+
7126
describe("generateSummary thinking options", () => {
8127
it("maps explicit Fable off to low effort for compaction", async () => {
9128
const model: Model = {

‎packages/agent-core/src/harness/compaction/compaction.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,9 @@ export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {
148148

149149
/** Calculate total context tokens from provider usage. */
150150
export function calculateContextTokens(usage: Usage): number {
151+
if (usage.contextUsage?.state === "available") {
152+
return usage.contextUsage.totalTokens;
153+
}
151154
return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
152155
}
153156
function getAssistantUsage(msg: AgentMessage): Usage | undefined {
@@ -184,7 +187,7 @@ export interface ContextUsageEstimate {
184187
tokens: number;
185188
/** Tokens reported by the most recent assistant usage block. */
186189
usageTokens: number;
187-
/** Estimated tokens after the most recent assistant usage block. */
190+
/** Estimated tokens not covered by usable provider usage. */
188191
trailingTokens: number;
189192
/** Index of the message that provided usage, or null when none exists. */
190193
lastUsageIndex: number | null;
@@ -195,7 +198,7 @@ function getLastAssistantUsageInfo(
195198
): { usage: Usage; index: number } | undefined {
196199
for (let i = messages.length - 1; i >= 0; i--) {
197200
const usage = getAssistantUsage(messages[i]);
198-
if (usage) {
201+
if (usage && usage.contextUsage?.state !== "unavailable") {
199202
return { usage, index: i };
200203
}
201204
}

‎packages/ai/src/internal/anthropic.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ export * from "../providers/anthropic-refusal.js";
55
export * from "../providers/anthropic-server-fallback.js";
66
export * from "../providers/anthropic-thinking-replay.js";
77
export * from "../providers/anthropic-tool-projection.js";
8+
export * from "../providers/anthropic-usage.js";
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { describe, expect, it } from "vitest";
2+
import { readLastAnthropicIterationUsage } from "./anthropic-usage.js";
3+
4+
describe("readLastAnthropicIterationUsage", () => {
5+
it.each(["message", "compaction", "advisor_message"])(
6+
"reads the final %s iteration as the context snapshot",
7+
(type) => {
8+
expect(
9+
readLastAnthropicIterationUsage({
10+
iterations: [
11+
{
12+
type: "message",
13+
input_tokens: 1,
14+
output_tokens: 2,
15+
cache_read_input_tokens: 3,
16+
cache_creation_input_tokens: 4,
17+
},
18+
{
19+
type,
20+
input_tokens: 12,
21+
output_tokens: 15_104,
22+
cache_read_input_tokens: 148_862,
23+
cache_creation_input_tokens: 0,
24+
},
25+
],
26+
}),
27+
).toEqual({
28+
state: "valid",
29+
usage: {
30+
contextPromptTokens: 148_874,
31+
totalTokens: 163_978,
32+
},
33+
});
34+
},
35+
);
36+
37+
it("reports absent iterations separately from malformed iterations", () => {
38+
expect(readLastAnthropicIterationUsage({ input_tokens: 1 })).toEqual({ state: "absent" });
39+
});
40+
41+
it("does not reuse an earlier iteration when the final iteration is malformed", () => {
42+
expect(
43+
readLastAnthropicIterationUsage({
44+
iterations: [
45+
{
46+
type: "message",
47+
input_tokens: 12,
48+
output_tokens: 15_104,
49+
cache_read_input_tokens: 148_862,
50+
cache_creation_input_tokens: 0,
51+
},
52+
{
53+
type: "message",
54+
input_tokens: "malformed",
55+
output_tokens: 1,
56+
cache_read_input_tokens: 0,
57+
cache_creation_input_tokens: 0,
58+
},
59+
],
60+
}),
61+
).toEqual({ state: "invalid" });
62+
});
63+
64+
it("rejects a final iteration with incomplete cache usage", () => {
65+
expect(
66+
readLastAnthropicIterationUsage({
67+
iterations: [
68+
{
69+
type: "message",
70+
input_tokens: 12,
71+
output_tokens: 15_104,
72+
},
73+
],
74+
}),
75+
).toEqual({ state: "invalid" });
76+
});
77+
});
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
type AnthropicUsagePayload = {
2+
input_tokens?: unknown;
3+
output_tokens?: unknown;
4+
cache_read_input_tokens?: unknown;
5+
cache_creation_input_tokens?: unknown;
6+
iterations?: unknown;
7+
};
8+
9+
export type AnthropicPromptUsageSnapshot = {
10+
input: number;
11+
cacheRead: number;
12+
cacheWrite: number;
13+
};
14+
15+
export type AnthropicIterationUsageSnapshot = {
16+
contextPromptTokens: number;
17+
totalTokens: number;
18+
};
19+
20+
export type AnthropicIterationUsageResult =
21+
| { state: "absent" }
22+
| { state: "invalid" }
23+
| { state: "valid"; usage: AnthropicIterationUsageSnapshot };
24+
25+
export function readAnthropicUsageTokenCount(value: unknown): number | undefined {
26+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
27+
}
28+
29+
export function readAnthropicPromptUsageSnapshot(
30+
usage: AnthropicUsagePayload,
31+
): AnthropicPromptUsageSnapshot | undefined {
32+
const input = readAnthropicUsageTokenCount(usage.input_tokens);
33+
const cacheRead =
34+
usage.cache_read_input_tokens == null
35+
? 0
36+
: readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
37+
const cacheWrite =
38+
usage.cache_creation_input_tokens == null
39+
? 0
40+
: readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
41+
if (input === undefined || cacheRead === undefined || cacheWrite === undefined) {
42+
return undefined;
43+
}
44+
return { input, cacheRead, cacheWrite };
45+
}
46+
47+
export function readLastAnthropicIterationUsage(
48+
usage: AnthropicUsagePayload,
49+
): AnthropicIterationUsageResult {
50+
if (usage.iterations == null) {
51+
return { state: "absent" };
52+
}
53+
if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) {
54+
return { state: "invalid" };
55+
}
56+
// Anthropic documents the final iteration as the true context window.
57+
// Top-level cache fields remain cumulative billing totals across iterations.
58+
const iteration = usage.iterations.at(-1);
59+
if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) {
60+
return { state: "invalid" };
61+
}
62+
const record = iteration as AnthropicUsagePayload;
63+
const input = readAnthropicUsageTokenCount(record.input_tokens);
64+
const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
65+
const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
66+
const outputTokens = readAnthropicUsageTokenCount(record.output_tokens);
67+
if (
68+
input === undefined ||
69+
cacheRead === undefined ||
70+
cacheWrite === undefined ||
71+
outputTokens === undefined
72+
) {
73+
return { state: "invalid" };
74+
}
75+
const contextPromptTokens = input + cacheRead + cacheWrite;
76+
return {
77+
state: "valid",
78+
usage: {
79+
contextPromptTokens,
80+
totalTokens: contextPromptTokens + outputTokens,
81+
},
82+
};
83+
}

0 commit comments

Comments
 (0)