In short.
This OpenRouter tutorial helps developers shorten the history of long-running AI agents, but its paid summaries can omit details. It supplies TypeScript code for chunked summarization, retaining recent messages, combining earlier summaries and preserving the original history when summarization fails. The page reports synthetic examples retaining 9 or 10 of 10 planted facts after initial compaction and 8 to 10 after repeated compaction. These results do not establish real-agent task performance. The implementation uses character estimates and does not guarantee that every resulting history fits a model's context window. Execution and live API compatibility are not assessed.
Researched and written by an AI model and checked by a second AI model. How it works
Coverage is the complete page at [https://openrouter.ai/docs/cookbook/building-agents/compact-agent-sessions-with-scaledown.md], including its code, prerequisite and paid-request notices, synthetic example, captured output, checks, variations and follow-up links. The documentation index, model pricing page, Responses API reference and linked tutorials are excluded. No separate software package or licensed library files are supplied. Code execution, live requests, current prices, real-agent performance and behavior outside the documented examples are not assessed.
The overview
identity
Compact Long Agent Sessions with ScaleDown Summarize is an OpenRouter cookbook tutorial at [https://openrouter.ai/docs/cookbook/building-agents/compact-agent-sessions-with-scaledown.md]. It teaches developers to add history compaction to an existing coding or research agent.
The resource is instructional code rather than a standalone application or packaged library. Its central function, maybeCompact, replaces older conversation messages with summaries produced by the scaledown/summarize model through OpenRouter.
assessment
The tutorial is useful for developers who control their agent's message history and need a concrete starting point for reducing accumulated tool output. It explains message serialization, repeated compaction, tool-result boundaries and failure handling, rather than presenting only a summarization prompt.
Treat the implementation as a recipe to adapt. The page's broad claim that history stays under budget is stronger than the code guarantees: thresholds count characters, retained messages can be large, and summaries are folded only once per compaction. Its synthetic recall examples support a limited demonstration, not production reliability or successful completion of real tasks.
users
The main audience is developers building TypeScript agents that accumulate many messages and tool results. Coding agents and research agents are the stated use cases.
Beginners can learn why an agent needs both concise historical memory and unchanged recent messages, but implementation requires familiarity with asynchronous TypeScript, HTTP requests, environment variables and tool-call message formats. It is not directly usable inside an assistant whose history cannot be rewritten.
capabilities
The example serializes older messages, including tool arguments and results, into text; summarizes chunks concurrently; and inserts their combined summary before recent messages. Later compactions carry the earlier summary forward and summarize it again when it grows past a threshold.
It preserves the first system message, adjusts the retained-message boundary to avoid starting with an orphaned tool result, validates API responses with Zod, and logs returned usage on successful compaction. Errors inside the summarization block return the original history unchanged. These are documented code behaviors, not independently verified results.
Using it
requirements
The stated prerequisites are an existing TypeScript agent loop using Node.js 20+ or Bun as an ES module, the corresponding Node or Bun types, Zod 4, and an OPENROUTER_API_KEY configured for paid requests. The agent must keep its history in an array that can be replaced between steps.
The sample assumes an OpenAI-style chat message structure and a system message at the beginning of the history. Other message schemas require adaptation. Histories are sent to OpenRouter for summarization; applicable provider data-handling terms and compatibility with a particular downstream agent model are not established here.
mechanism
The code estimates history size using serialized character counts. At 50,000 characters, subject to a message-count guard, it separates older messages from roughly the last eight messages. KEEP_RECENT counts array entries, including tool results, rather than eight complete conversational exchanges; the boundary adjustment can change how many entries remain.
Older messages are grouped into approximately 16,000-character chunks and submitted to [https://openrouter.ai/api/v1/responses] using scaledown/summarize. Instructions request goals, decisions, failures, confirmed facts and exact identifiers. Each request has a 60-second timeout.
An existing summary is combined with the new one. Above 12,000 characters, the combined text is summarized again in approximately 4,000-character windows. The result becomes a user message after the original system prompt. Large individual messages or paragraphs can exceed the nominal chunk sizes because the splitting functions preserve those units.
setup
Configure the API key, install the stated dependencies, and adapt the tutorial's message types to the agent's actual history. Call maybeCompact before each agent step and replace the working history with its returned array.
For the synthetic demonstration, the page instructs readers to combine steps 1 through 4 with the two example blocks in compact.ts and run bun run compact.ts. The agentStep loop is an integration sketch requiring the developer's own implementation. The page advises keeping indispensable task constraints outside summarized messages, including in the preserved system prompt.
example
The worked example constructs a fictional 100-step coding session with 202 messages and about 86,000 characters. Ten planted facts include a configuration path, a failed approach, a table name, a ticket identifier and a test command. The displayed test results belong to this fabricated history; they are not evidence of an actual billing project or executed test suite.
One captured compaction reports 193 older messages, totaling 82,444 characters, becoming a 3,256-character summary through six calls. Across seven source-reported initial runs, 9 or 10 planted facts survived. After two further compactions, the page reports 8 to 10 surviving facts. The check searches the summary for fact strings, so it does not establish whether an agent can apply those facts correctly during a real task.
Assessment & evidence
limitations
Summarization is lossy, especially when an earlier summary is summarized again. Exact identifiers can disappear despite instructions to preserve them. The page explicitly recommends keeping facts that must never be lost in separate state.
Character counts are an approximation of token usage. Oversized messages, long retained tool outputs or unexpectedly long summaries can leave the history above its intended budget. The implementation performs no final token-limit check or repeated reduction until a hard limit is met.
On summarization failure, retaining the full history preserves information but may leave the next model request too large. There are no explicit retries or concurrency controls. Real-world task accuracy, sensitive-data handling and compatibility beyond the demonstrated message structure are not assessed.
reasoning
The design keeps recent messages unchanged because immediate tool interactions need their original structure and detail. Chunking asks the summarizer to handle smaller portions of history, while carrying earlier summaries forward postpones another potentially lossy compression.
These choices trade additional API calls and waiting time for reduced history size. The reported variation in retained facts supports treating summaries as working memory with possible omissions. The evidence does not establish an optimal chunk size, folding threshold or balance between cost and recall for other workloads.
alternatives
The page discusses keeping the complete history, dropping old messages and summarizing the whole history in one call. Keeping everything preserves the original content but allows context to grow. Dropping messages removes information entirely. A single summary call is simpler, but the page reports that it loses facts on long inputs.
Separate durable state is the page's recommendation for indispensable facts. It provides no comparative evidence for other summarization providers, retrieval-based memory, larger-context models or native agent compaction features. Linked follow-up guides are outside the material assessed here.
evidence
The evidence consists of the complete documentation page preserved as selected-page.txt, acquired from [https://openrouter.ai/docs/cookbook/building-agents/compact-agent-sessions-with-scaledown.md]. The artifact is 22,406 bytes, with source revision sha256:9ca36599a8324a6e1b3cfe3d788b4bf00052f6128bacba20529ad575a43834ff.
The page includes implementation code, a synthetic history generator, captured output and author-reported observations. Its examples are useful evidence of the documented approach, but independent execution, live service behavior and real-agent outcomes remain unassessed. The fact-retention check measures string presence rather than semantic correctness or task completion.
Access & freshness
costs
Every summarization request is paid through the reader's OpenRouter account. The page reports approximately $0.00065 to $0.00073 for example compactions without a fold and $0.00099 for an example with a fold. Its introductory example separately quotes $0.00087. These are historical example costs, not established current rates or a quote for another workload.
The source reports 5 to 6 calls without folding and 11 with one fold, with compaction latency of 2 to 33 seconds in its examples. A fold requires another round of requests. Current pricing, future availability and total operating costs are unknown.
The code does not impose a spending cap or concurrency limit. Parallel calls are not explicitly cancelled when another call fails, and usage is logged only after successful compaction, so that log is not a complete accounting mechanism for failed attempts.
rights
The captured page contains documentation and TypeScript snippets but supplies no explicit licence or reuse and redistribution grant. Permissions for copying, adapting or redistributing that material are unknown from this evidence.
The page also does not establish service terms, ownership provisions for generated summaries, data retention or provider training practices. No separately licensed library files are included in the supplied material.
freshness
The supplied snapshot was captured at 2026-11-14T20:04:50.738Z. The page's publication date and last modification date are not stated.
The code names scaledown/summarize without a pinned model revision. Current model availability, pricing, response-schema compatibility and dependency compatibility are unknown beyond the captured documentation. The capture timestamp does not establish when the reported example runs occurred.
actions
Before adopting the recipe, confirm current model access, pricing, service terms and permissions to reuse the code. Check whether the histories being sent to the service may contain sensitive information. Adapt message serialization and context accounting to the actual agent and downstream model.
Evaluate repeated compaction with representative histories, exact identifiers, oversized tool outputs, API failures and downstream task completion. Measure actual token counts and all request costs. Preserve indispensable facts in durable state, and define what the agent should do when failed compaction leaves its history too large.
