/** * On-demand compaction (beta compact-2026-09-04) with the Node SDK on claude-sonnet-5: send the conversation with * top-level compaction {type:"summarize"} → a single signed `compaction` block, stop_reason "compaction", * usage.iterations [{type:"compaction"}]. Then continue by sending the block FIRST in messages. * STATUS: LIVE_VERIFIED 2026-09-18: summary block + signature returned; continuation answered "Ada … teal" (~$0.002). * Run: node --env-file=.env --experimental-strip-types examples/anthropic/context-management/compaction_on_demand.ts */ import Anthropic from "@anthropic-ai/sdk"; import { appendFileSync } from "node:fs"; const MODEL = process.env.ANTHROPIC_MODEL ?? "claude-sonnet-5"; const client = new Anthropic({ maxRetries: 1 }); const log = (status: number, note: string, cost: number) => appendFileSync("reports/live-requests.jsonl", JSON.stringify({ ts: new Date().toISOString(), provider: "anthropic", method: "POST", path: "/v1/messages", status, est_cost_usd: cost, note }) + "\n"); const history = [ { role: "user", content: "My name is Ada and I like teal." }, { role: "assistant", content: "Nice to meet you, Ada." }, ]; // 1) Summarize (no reply is generated; max_tokens caps the summary incl. thinking) const summary = await client.beta.messages.create({ model: MODEL, max_tokens: 400, betas: ["compact-2026-09-04"], compaction: { type: "summarize" }, messages: history, } as any); const block = summary.content[0] as any; console.log("stop_reason:", summary.stop_reason, "| block:", block.type, "| signature:", String(block.signature).slice(0, 24) + "…"); console.log("summary:", block.content, "| iterations:", (summary.usage as any).iterations); log(200, `example context-management/compaction_on_demand.ts summarize ${MODEL} beta=compact-2026-09-04`, 0.0015); // 2) Continue: the block goes FIRST, in place of the summarized messages (leaving them in front → 400 compaction_block_misplaced) const next = await client.beta.messages.create({ model: MODEL, max_tokens: 30, betas: ["compact-2026-09-04"], messages: [{ role: "assistant", content: [block] }, { role: "user", content: "What is my name and favourite color? Five words." }], } as any); console.log("continuation:", next.content[0].type === "text" ? next.content[0].text : next.content[0].type); log(200, `example context-management/compaction_on_demand.ts continue ${MODEL}`, 0.0005);