Agent summaries: only near the model's window, room for 20,000 tokens, a cut-off summary says so, a fuller ask (#2)
jonas, 2026-11-28 09:32 UTC ยท d9dbaa821ee25a23936d514615a89804e5ae6759 ยท parent 320b3d7
10 files changed
- M agent-tests/processor.test.mjs
- M agent-tests/test-support.mjs
- M agent/contract.ts
- M agent/llm-api.ts
- M agent/llm-apis/anthropic-messages.ts
- M agent/llm-apis/chat-completions.ts
- M agent/llm-apis/google-generate-content.ts
- M agent/llm-apis/openai-responses.ts
- M agent/llm-request.ts
- M agent/processor.ts
M agent-tests/processor.test.mjs
@@ -18,12 +18,19 @@ import { ProcessorEngine } from "iterate/stream/processor"; import { RunEventCatalog } from "iterate/stream/run"; import { memoryStorage, memoryStream, reduceProcessor, settle } from "iterate/stream/test-support"; -import { AgentContract, ScheduleEventCatalog } from "../agent/contract.ts"; +import { + AgentConfig, + AgentContract, + DEFAULT_CONTEXT_WINDOWS, + ScheduleEventCatalog, + contextWindowOf, + summaryThresholdTokens, +} from "../agent/contract.ts"; import { LlmApiProcessor } from "../agent/llm-api.ts"; import { chatCompletions } from "../agent/llm-apis/chat-completions.ts"; import { openaiResponses } from "../agent/llm-apis/openai-responses.ts"; import { LlmRequestContract } from "../agent/llm-request.ts"; -import { Agent } from "../agent/processor.ts"; +import { Agent, SUMMARY_CUT_OFF, summaryAsk } from "../agent/processor.ts"; import { agentOnALog, anthropic, @@ -2421,17 +2428,38 @@ const isSummaryAsk = (call) => String(call.body.input.at(-1).content).startsWith("Write the summary"); -test("rent or purchase: when the rent paid reaches a summary's cost, a summary replaces the history", async () => { +/** The model that an agent asks when its config names none, and a window for it that puts the + * threshold at `tokens`: the window less the summary's room and 13,000 (contract.ts). */ +const DEFAULT_MODEL_NAME = AgentConfig.parse({}).llm.model; +const thresholdAt = (tokens) => ({ [DEFAULT_MODEL_NAME]: tokens + 33_000 }); + +test("the threshold is ONE rule: the model's window less the summary's room and 13,000 tokens", () => { + const config = AgentConfig.parse({}); + // Misha, 28 Nov 2026: "367k on Sol, 167k on a 200k window" + assert.equal(summaryThresholdTokens(config, "openai/gpt-6.2-sol"), 367_000); + assert.equal(summaryThresholdTokens(config, "anthropic/claude-opus-5.5"), 167_000); + assert.equal(summaryThresholdTokens(config, "basement/llama-5"), 167_000); + assert.equal(contextWindowOf({ "openai/gpt-6.2-sol": 272_000 }, "openai/gpt-6.2-sol"), 272_000); + // the summary's room is 20,000 tokens, and the threshold reserves that same number and 13,000 + assert.equal(config.summary.maxOutputTokens, 20_000); + assert.equal(config.summary.reservedOutputTokens, config.summary.maxOutputTokens + 13_000); + assert.equal(config.summary.atShareOfUsableWindow, 1); + // every model that has a price has a window + assert.deepEqual(Object.keys(DEFAULT_CONTEXT_WINDOWS).sort(), Object.keys(config.prices).sort()); + assert.equal(summaryThresholdTokens(config, DEFAULT_MODEL_NAME), contextWindowOf({}, DEFAULT_MODEL_NAME) - 33_000); +}); + +test("near the model's window: at the threshold a summary replaces the history", async () => { const agent = agentOnALog({ - config: { summary: { minInputTokens: 100, keepNewestItems: 0, rentFactor: 0.3 } }, + // the response reads 100,000 tokens and writes 10: the threshold, to the token + config: { contextWindows: thresholdAt(100_010), summary: { minInputTokens: 100, keepNewestItems: 0 } }, model: (call) => isSummaryAsk(call) ? openai({ raw: "The user greeted; nothing is open." }) - : openai({ say: "Hello.", usage: { input: 100_000, cached: 100_000, output: 10 } }), + : openai({ say: "Hello.", usage: { input: 100_000, cached: 0, output: 10 } }), }); await agent.say("hello"); - // reading 100,000 tokens again cost $0.01; a summary costs about $0.03, and at a rent factor of - // 0.3 it pays at $0.009: as soon as the response's script has its result + // as soon as the response's script has its result assert.equal(agent.calls.length, 2); const [answer, summary] = agent.durable("events.iterate.com/llm-request/requested"); assert.equal(answer.payload?.purpose, "answer"); @@ -2447,6 +2475,19 @@ ]); assert.deepEqual(agent.calls[1].body.tools, agent.calls[0].body.tools); assert.deepEqual(agent.calls[1].body.input[0], agent.calls[0].body.input[0]); + // its room is 20,000 output tokens, and the ask says that room in words and what to keep + assert.equal(agent.calls[1].body.max_output_tokens, 20_000); + const ask = String(agent.calls[1].body.input.at(-1).content); + assert.equal(ask, summaryAsk(20_000)); + for (const kept of [ + "THE PERSON'S OWN WORDS", + "WHAT YOU ALREADY TOLD EACH PERSON", + "A LABEL IN SQUARE BRACKETS", + "AN EARLIER SUMMARY ABOVE", + "ABOUT 10,000 WORDS", + ]) + assert.ok(ask.includes(kept), kept); + assert.ok(summaryAsk(4_000).includes("ABOUT 2,000 WORDS")); const state = await agent.state(); assert.deepEqual( @@ -2471,26 +2512,31 @@ assert.deepEqual(agent.invalidFacts(), []); }); -test("a cold read is not rent, and a long system prompt is not history: neither pays for a summary", async () => { - // tokens the provider had not read before are no rent: so the first read after a summary, which - // is cold, never pays for the next summary - const cold = agentOnALog({ - config: { summary: { minInputTokens: 100, keepNewestItems: 0, rentFactor: 0.3 } }, +test("below the threshold no summary, whatever the reads cost and when the cache ends; a long system prompt is not history", async () => { + // one token short of the threshold. Every token was read from the cache: until 28 Nov 2026 that + // rent paid for a summary, and a timer waited for the cache's end. Now neither does. + const below = agentOnALog({ + config: { contextWindows: thresholdAt(100_011), summary: { minInputTokens: 100, keepNewestItems: 0 } }, model: (call) => isSummaryAsk(call) ? openai({ raw: "A summary." }) - : openai({ say: "Hello.", usage: { input: 100_000, cached: 0, output: 10 } }), + : openai({ say: "Hello.", usage: { input: 100_000, cached: 100_000, output: 10 } }), }); - await cold.say("hello"); - assert.equal(cold.calls.length, 1); - assert.equal((await cold.state()).history.rentUsd, 0); + await below.say("hello"); + await below.say("again"); + assert.equal(below.calls.length, 2); + assert.equal(below.calls.some(isSummaryAsk), false); + const state = await below.state(); + assert.ok(state.history.rentUsd > 0, "the rent is still counted"); + assert.equal(state.timer.atMs === null || state.timer.atMs <= state.nowMs, true, "no timer waits for the cache's end"); // the instructions are read by every request whatever is summarised: 400,000 characters of them // are 100,000 tokens that no summary can replace, so the history is still too small const prompted = agentOnALog({ config: { instructions: "x".repeat(400_000), - summary: { minInputTokens: 100, keepNewestItems: 0, rentFactor: 0.3 }, + contextWindows: thresholdAt(100_010), + summary: { minInputTokens: 100, keepNewestItems: 0 }, }, model: (call) => isSummaryAsk(call) @@ -2501,24 +2547,30 @@ assert.equal(prompted.calls.length, 1); }); -test("before the cache is dropped: a timer two minutes before, and a summary if a cold read would cost more", async () => { +test("a summary that the provider cut off at its limit ends with a line that says its end is missing", async () => { const agent = agentOnALog({ - config: { summary: { minInputTokens: 100, keepNewestItems: 0, rentFactor: 1_000 } }, + config: { contextWindows: thresholdAt(100_010), summary: { minInputTokens: 100, keepNewestItems: 0 } }, model: (call) => isSummaryAsk(call) - ? openai({ raw: "A summary." }) - : openai({ say: "Hello.", usage: { input: 100_000, cached: 99_000, output: 10 } }), + ? // OpenAI ends it with `response.incomplete`, and it settles as succeeded + openai({ raw: "The user greeted, and the agent had", cutOff: true, usage: { input: 100_100, output: 20_000 } }) + : openai({ say: "Hello.", usage: { input: 100_000, cached: 0, output: 10 } }), }); await agent.say("hello"); - assert.equal(agent.calls.length, 1, "the rent is small: no summary yet"); - const state = await agent.state(); - assert.equal(state.timer.atMs, 28 * 60_000); - await agent.fire("agent/timer"); assert.equal(agent.calls.length, 2); - assert.ok(isSummaryAsk(agent.calls[1])); - const after = await agent.state(); - assert.equal(after.items[0].tag, "summary"); - assert.deepEqual(after.obligations, [], "summarised: no timer, no cache to lose"); + const [answered, summarised] = agent.durable("events.iterate.com/llm-request/settled").map((settled) => settled.payload?.result); + assert.equal(answered.cutOff, undefined, "a whole response has no mark"); + assert.deepEqual([summarised.status, summarised.cutOff], ["succeeded", true]); + const state = await agent.state(); + assert.equal( + state.items[0].text, + `Summary of the conversation before this point:\nThe user greeted, and the agent had\n\n${SUMMARY_CUT_OFF}`, + ); + assert.ok(SUMMARY_CUT_OFF.includes("its end is missing")); + // the agent reads the line in its next request + await agent.say("and now?"); + assert.ok(String(agent.calls[2].body.input[1].content).endsWith(SUMMARY_CUT_OFF)); + assert.deepEqual(agent.invalidFacts(), []); }); test("the conversation no longer fits the model: a summary of the older half first, then the answer", async () => {
M agent-tests/test-support.mjs
@@ -366,7 +366,8 @@ ] : []), { - type: "response.completed", + // `cutOff`: the model stopped at `max_output_tokens`, and OpenAI ends the response so + type: answer.cutOff ? "response.incomplete" : "response.completed", response: { usage: { input_tokens: usage.input ?? 100,
M agent/contract.ts
@@ -85,7 +85,7 @@ * and counted its versions "1", "2", โฆ. A facet keeps its checkpoint under the slug, and the engine * takes a checkpoint of its own version as its own state. An equal number here would make that * agent's state this one's. */ -const AGENT_VERSION = "config-5"; +const AGENT_VERSION = "config-6"; /** What an input does to the agent's requests. */ export const LlmRequestPolicy = z.object({ @@ -111,6 +111,75 @@ } } +/** THE CONTEXT WINDOW OF EACH MODEL THAT HAS A PRICE BELOW, in tokens: what one request may hold, + * the response with it. Where two sources differ, the smaller number is here. Sol: 400,000. + * Astra and Luna: 272,000 is the window that Codex works them at (openai/codex 372947d of 27 Nov + * 2026, codex-rs/models-manager/models.json, `context_window`). Opus 5.5, Grok 4.3 and Gemini 3.8 + * Flash were checked against no provider's page. + * A number that is too large costs one refused request: the provider's refusal for size starts a + * summary of the older half (`contextWindowExceeded`). */ +export const DEFAULT_CONTEXT_WINDOWS: Record<string, number> = { + "openai/gpt-6.2-sol": 400_000, + "openai/gpt-6.2-astra": 272_000, + "openai/gpt-6-luna": 272_000, + "xai/grok-4.3": 256_000, + "anthropic/claude-opus-5.5": 200_000, + "google/gemini-3.8-flash": 1_000_000, +}; +/** A model that no table names: the smallest window of the models above. */ +export const UNKNOWN_MODEL_CONTEXT_WINDOW = 200_000; + +/** A MODEL'S CONTEXT WINDOW: the agent's own config first, then `DEFAULT_CONTEXT_WINDOWS`, then + * `UNKNOWN_MODEL_CONTEXT_WINDOW`. An agent keeps the table of its start. */ +export function contextWindowOf(windows: Record<string, number>, model: string): number { + return windows[model] ?? DEFAULT_CONTEXT_WINDOWS[model] ?? UNKNOWN_MODEL_CONTEXT_WINDOW; +} + +/** WHERE AN AUTOMATIC SUMMARY STARTS: at the model's window less the summary's own room + * (`SUMMARY_MAX_OUTPUT_TOKENS`) and less 13,000 tokens. So 167,000 of a 200,000 window (83.5%), + * 367,000 of 400,000 (91.75%), 967,000 of a million (96.7%). It is ONE rule, Claude Code's + * (2.1.332, read from its bundle on 27 Nov 2026; code.claude.com/docs/en/model-config says "about + * 967K" of a million): the window less min(max output, 20,000), less 13,000. + * Until 28 Nov 2026 two rules were stacked here: that reserve AND Codex's share, 90% of what the + * reserve left (342,000 on Sol). Misha, 28 Nov 2026, in Slack, after a night of it on + * misherate.com: "Two rules stacked. [โฆ] Pick one. I took Claude Code's". Codex's 90% alone + * (openai/codex 372947d, codex-rs/protocol/src/openai_models.rs) leaves a 200,000 window 20,000, + * which a summary of 20,000 tokens fills whole. opencode v1.19.6 takes the window less up to + * 20,000; Gemini CLI alone is far lower, at 50%. + * THE RESERVE HOLDS THE SUMMARY: the summary request reads the history that reached the + * threshold and writes up to `summary.maxOutputTokens`, so both fit the window with 13,000 over. + * This agent counts the newest response alone (`history.inputTokens`), and not the items added + * since: what one turn adds (a script result of up to `scriptResultHistoryLimit` characters, a + * person's words) fits in the 13,000 and in the room that a summary does not use. What does not + * fit costs one refused request, and then a summary of the older half (`contextWindowExceeded`). */ + +/** THE ROOM OF A SUMMARY, in output tokens: what the summary request may write, reasoning and + * all. Claude Code keeps 20,000 for its summary; Codex sets no limit. Until 28 Nov 2026 it was + * 2,000: in one conversation of four hours on misherate.com, 13 of 18 summaries reached it and + * stopped in the middle of a sentence (Misha, 28 Nov 2026). A model that reasons spends this + * room on its reasoning first. */ +export const SUMMARY_MAX_OUTPUT_TOKENS = 20_000; +/** What the threshold leaves free beside the summary's room: Claude Code's 13,000. */ +const SUMMARY_MARGIN_TOKENS = 13_000; +/** The reserve is the whole rule: no share is taken of what it leaves. The field stays, at 1, + * because a page that marks the threshold reads both numbers from the agent's state. */ +const SUMMARY_AT_SHARE = 1; +const SUMMARY_RESERVED_TOKENS = SUMMARY_MAX_OUTPUT_TOKENS + SUMMARY_MARGIN_TOKENS; + +/** THE SIZE OF HISTORY AT WHICH THE AGENT SUMMARISES BY ITSELF, in tokens of `model`: the model's + * window less `reservedOutputTokens`, times `atShareOfUsableWindow` (1: the reserve alone). The + * Dash's context bar repeats this line (/repos/chat, `automaticSummaryTokens`): it reads the two + * numbers from the agent's state, so a change of the defaults moves its mark, and a change of + * the formula does not. */ +export function summaryThresholdTokens( + config: Pick<AgentConfig, "summary" | "contextWindows">, + model: string, +): number { + const { atShareOfUsableWindow, reservedOutputTokens } = config.summary; + const usable = Math.max(0, contextWindowOf(config.contextWindows, model) - reservedOutputTokens); + return Math.floor(usable * atShareOfUsableWindow); +} + export const AgentConfig = z.object({ /** What the model is told before the conversation. A change starts a new prompt cache. The * default names no channel: the mind's `worker.ts` adds the fragments of the channels the agent @@ -245,27 +314,38 @@ /** A script result up to this many characters is shown to the model whole. A longer one is shown * as its shape, and a later script reads it whole from the log with `await result(n)`. */ scriptResultHistoryLimit: z.number().int().positive().default(30_000), - /** WHEN A SUMMARY REPLACES THE HISTORY. Every request reads the whole history again, and a cached - * token still costs a tenth: that is rent. A summary is a purchase. The agent summarises when the - * rent paid since the last summary reaches `rentFactor` summaries' cost, or in the last minutes - * before the provider drops its cache, when reading the history cold would cost more than a - * summary. `rentFactor` is what detail is worth: 1 is cheapest, a larger one keeps detail longer. */ + /** WHEN A SUMMARY REPLACES THE HISTORY: when the history nears the model's context window, as in + * Claude Code, and not before (`summaryThresholdTokens` above has the numbers and where they + * are from). Until 28 Nov 2026 the agent summarised by cost: when the cached reads since the + * last summary had cost as much as a summary (`rentFactor`), or just before the provider + * dropped its cache (`cacheLifetimeMs`). On Sol that was a summary every five or six requests + * from 20,000 tokens of conversation up: an agent of iterate.com summarised at 56,224 of + * 400,000 tokens, 14% (27 Nov 2026). Cost and the cache now start no summary; `history.rentUsd` + * is still counted, for a page that shows it. A provider's refusal for size starts a summary + * at any size. */ summary: z .object({ - rentFactor: z.number().positive().default(1), - /** A history smaller than this is never summarised. */ + /** The share of the usable window at which the agent summarises by itself. 1: the reserve + * below is the whole rule. */ + atShareOfUsableWindow: z.number().positive().max(1).default(SUMMARY_AT_SHARE), + /** What the usable window leaves free of the model's window: the summary's own room + * (`maxOutputTokens` below) and 13,000 tokens. An agent that names a larger + * `maxOutputTokens` names a larger reserve with it. */ + reservedOutputTokens: z.number().int().nonnegative().default(SUMMARY_RESERVED_TOKENS), + /** A conversation smaller than this, counted without the instructions, is never summarised + * by itself: a summary cannot make the instructions smaller. */ minInputTokens: z.number().int().positive().default(20_000), - maxOutputTokens: z.number().int().positive().default(2_000), - /** How long a provider keeps a prompt cached after its last use. */ - cacheLifetimeMs: z - .number() - .int() - .positive() - .default(30 * 60_000), + /** The summary's room, reasoning and all (`SUMMARY_MAX_OUTPUT_TOKENS`). The summary is told + * its room in words, and one that the provider stops at it says that its end is missing + * (processor.ts `summaryAsk`, `SUMMARY_CUT_OFF`). */ + maxOutputTokens: z.number().int().positive().default(SUMMARY_MAX_OUTPUT_TOKENS), /** The newest items stay as they are. */ keepNewestItems: z.number().int().nonnegative().default(6), }) .prefault({}), + /** Tokens of each model's context window, by model: `DEFAULT_CONTEXT_WINDOWS` above. Read one + * with `contextWindowOf`, never from this record alone. */ + contextWindows: z.record(z.string(), z.number().int().positive()).default(DEFAULT_CONTEXT_WINDOWS), /** US dollars for a million tokens, by model. OpenAI's are from OpenAI's price page on * 18 November 2026. Anthropic's and * Google's are this repository's lab values of 20 November 2026, not checked against a price page.
M agent/llm-api.ts
@@ -194,6 +194,8 @@ providerItems: Record<string, unknown>[]; usage: LlmUsage | null; done: boolean; + /** The provider stopped the response at its output limit: `text` has no end. */ + cutOff?: boolean; }; /** What the processor uses of its context's `itx` (iterate/sdk): whatever the providers' @@ -690,6 +692,7 @@ text: response.text, providerItems: response.providerItems, ...(response.usage && { usage: priced(config.prices, request.model, response.usage) }), + ...(response.cutOff && { cutOff: true as const }), }; } catch (error) { transport?.failed?.();
M agent/llm-apis/anthropic-messages.ts
@@ -79,9 +79,11 @@ if (signature) block.signature = signature; response.text += text || ""; response.thinking += thinking || ""; - } else if (e.type === "message_delta" && response.usage && e.usage?.output_tokens != null) - response.usage.outputTokens = e.usage.output_tokens; - else if (e.type === "message_stop") { + } else if (e.type === "message_delta") { + if (response.usage && e.usage?.output_tokens != null) + response.usage.outputTokens = e.usage.output_tokens; + if (e.delta?.stop_reason === "max_tokens") response.cutOff = true; + } else if (e.type === "message_stop") { response.isThinking = false; response.done = true; } else if (e.type === "error") throw streamFailure(e.error?.message); @@ -111,6 +113,7 @@ text: z.string(), thinking: z.string(), signature: z.string(), + stop_reason: z.string().nullable(), }) .partial() .optional(),
M agent/llm-apis/chat-completions.ts
@@ -66,6 +66,7 @@ if (content || choice?.finish_reason) response.isThinking = false; message.content = response.text; if (choice?.finish_reason) response.done = true; + if (choice?.finish_reason === "length") response.cutOff = true; // the last chunk carries the counts; reasoning is counted beside `completion_tokens` const usage = chunk.usage; if (usage) {
M agent/llm-apis/google-generate-content.ts
@@ -70,6 +70,7 @@ }; } if (candidate?.finishReason) { + if (candidate.finishReason === "MAX_TOKENS") response.cutOff = true; response.isThinking = false; response.done = true; }
M agent/llm-apis/openai-responses.ts
@@ -147,6 +147,8 @@ cachedInputTokens: usage.input_tokens_details?.cached_tokens ?? 0, reasoningOutputTokens: usage.output_tokens_details?.reasoning_tokens ?? 0, }; + // `response.incomplete`: the model stopped at `max_output_tokens`, or a filter stopped it + if (e.type === "response.incomplete") response.cutOff = true; response.done = true; } else if (e.type === "response.failed" || e.type === "error") throw streamFailure(e.response?.error?.message || e.error?.message || e.message);
M agent/llm-request.ts
@@ -145,6 +145,11 @@ text: z.string(), providerItems: z.array(z.unknown()), usage: LlmUsage.optional(), + /** The provider stopped the response at its output limit: the text's end is missing. A + * provider settles such a response like a whole one (OpenAI's `response.incomplete`, + * Anthropic's stop reason `max_tokens`), so the request maker says it here. Absent: the + * response is whole, or the fact is older than 28 Nov 2026. */ + cutOff: z.literal(true).optional(), }), z.object({ status: z.literal("failed"),
M agent/processor.ts
Not shown: the change is larger than this page shows. A clone has it.