Context Management
Automatically manage conversation length with truncation, summarization, sliding window, and smart hybrid compression strategies.
Overview
Long-running agents accumulate conversation history that can exceed a model's context window. The ContextManager automatically detects when messages are approaching the limit and compresses them using one of four strategies -- keeping agents running indefinitely without losing critical context.
import { Cogitator } from '@cogitator-ai/core';
const cog = new Cogitator({
llm: { providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } } },
context: {
enabled: true,
strategy: 'hybrid',
compressionThreshold: 0.8,
outputReserve: 0.15,
windowSize: 10,
},
});Context management is built into the runtime: whenever context is set (and enabled is not false), the run checks the conversation before each model call and compresses it when needed. Compression changes only what is sent, memory keeps the full history. After compression, tool results whose call was dropped (and calls without their results) are removed too, so the provider never sees a broken tool exchange. What the agent must not lose comes back as system messages after the system prompt when compression dropped it: the instructions of the skills it activated (the newest, up to 40 000 characters) and the tools a tool search loaded. Its newest todo list comes back as a write_todos call and its result after the newest message. Compression keeps room for them, so the conversation and what comes back fit the window together. The check is the beforeModel hook of the built-in run middleware cogitator:compaction, the last one before the model, and compactionMiddleware(contextManager) gives compaction to one agent.
Configuration
interface ContextManagerConfig {
enabled?: boolean; // default: true
strategy?: 'truncate' | 'sliding-window' | 'summarize' | 'hybrid';
compressionThreshold?: number; // 0-1, triggers at this % of max tokens (default: 0.8)
outputReserve?: number; // fraction of context reserved for output (default: 0.15)
summaryModel?: string; // provider/model id for LLM summaries (see below)
windowSize?: number; // messages to keep in sliding window (default: 10)
clearToolOutputs?: boolean | ClearToolOutputsConfig; // see below, off by default
}The compressionThreshold controls when compression kicks in. At 0.8, compression triggers when token usage exceeds 80% of the available context (the model's context window minus outputReserve). Compression then brings the conversation back under the available context.
Which strategies call a model depends on summaryModel: with it, sliding-window, summarize and hybrid compression summarize older messages with that model. Without it, only strategy: 'summarize' calls a model (the running agent's); sliding-window and hybrid fall back to an extractive summary without an LLM call.
Clearing Old Tool Outputs
An agent that reads files, pages or query results fills its context with tool outputs it rarely needs again. context.clearToolOutputs replaces the outputs of old tool calls with a short note once the conversation grows past a threshold, the way Anthropic's clear_tool_uses_20250919 context edit does, but for every provider:
const cog = new Cogitator({
context: {
enabled: false, // clear tool outputs, but do not compress
clearToolOutputs: {
trigger: 100_000, // tokens of the conversation at which clearing starts
keep: 3, // the most recent tool results stay as they are
exclude: ['read_plan'], // tools whose outputs are never cleared
clearInputs: false, // also clear the arguments of the cleared calls
clearAtLeast: 0, // fewest tokens a clearing must free, else it waits
onBeforeClear: async ({ calls }) => {
for (const call of calls) await notes.save(call.toolCallId, call.output);
},
},
},
});clearToolOutputs: true takes the defaults above. Clearing is off unless set, and it works on its own: with enabled: false the runtime clears tool outputs without compressing, and with compression on it runs first, so outputs go before anything is summarized.
Before a turn whose conversation has trigger tokens or more (counted with the token counter below, tool schemas aside), every tool result but the keep most recent ones and those of excluded tools is cleared. The run's own use_skill, tool_search and write_todos results are left alone: the instructions of active skills (the newest, up to 40 000 characters), the tools a search loaded and the todo list stay in the conversation. A tool of yours with one of these names is cleared like any other. A cleared result keeps its message, so each tool call still has its result for every provider, and its output becomes a note that names the call:
[Output cleared to save context. Call recall_tool_output with {"toolCallId":"call_7"} to get it back.]While clearing is on, every agent gets the built-in tool recall_tool_output({ toolCallId }). It returns the output the run cleared, or, after a paused run resumed or for a call of an earlier run, reads it from memory: only the branch of the thread the run is on, and only for a run that uses memory and was let on its thread. With clearInputs: true the arguments of the cleared calls become { cleared: 'Arguments cleared to save context' } too, and those cannot be recalled.
The run goes on with the cleared conversation, so a later turn does not clear or count an output twice, and memory keeps every output as it was. What outlives the run gets the outputs and arguments back: RunResult.messages and the checkpoint of a paused run hold them as the tools returned them, and a resumed run clears again from there. A middleware stack of your own that uses clearToolOutputsMiddleware gives them back the same way with restoreClearedOutputs(messages, state), state being the run's middleware state. A result whose output is shorter than the note is left alone. onBeforeClear is awaited before each clearing with the calls about to be cleared that the run made itself (toolCallId, toolName, arguments, output, tokens), the conversation's tokens, the tokensFreed and the model, plus the run's middleware context: keep what matters there first. Outputs of earlier runs, loaded from memory, are cleared without it, since memory holds them already, and a clearing of those alone does not call it. An error it throws fails the run.
Each clearing changes the prompt from the first output it clears on, so the provider's prompt cache of the rest is lost. clearAtLeast makes clearing wait until it frees that many tokens, which batches clearings when prompt caching matters. It defaults to 0, as in Anthropic's edit, since after the first clearing each one only rewrites the tail behind the kept results.
The run's agent.run span reports what clearing did: context.cleared_tool_outputs (outputs cleared), context.cleared_tool_output_tokens (tokens freed) and context.clearings (how many times it cleared). The clearing is the built-in run middleware cogitator:clear-tool-outputs. To give it to one agent only, add clearToolOutputsMiddleware(options) to the agent's middleware and recallToolOutputTool() to its tools: the middleware answers the tool with the outputs it cleared. To read outputs of earlier runs from memory too, the tool needs to know where each run writes, recallToolOutputTool(() => memory, (runId) => ({ threadId, leafId })), which the Cogitator does for the tool it adds.
Long Tool Results
A tool result longer than the tool's maxResultLength, or limits.maxToolResultLength (100,000 characters by default), reaches the model cut: its start and end, with a note on how much was left out. When the agent has the read_file of workspaceTools() and it reaches a workspace (its bound one, else the run's), nothing is lost: the full text is saved to .cogitator/tool-results/<runId>/<toolCallId>.txt in that workspace, and the model gets the cut preview plus a note with that path, so it can page through the rest with read_file (offset and limit for lines, column to continue a line too long for one page).
import { Agent, LocalWorkspace, toolResultPath, workspaceTools } from '@cogitator-ai/core';
const workspace = new LocalWorkspace({ root: './project' });
const agent = new Agent({
name: 'investigator',
model: 'openai/gpt-6.1-sol',
instructions: 'Find the failing step in the build log.',
tools: [buildLog, ...workspaceTools()], // buildLog: your tool that returns a long log
workspace,
});
const result = await cog.run(agent, { input: 'Why did the build fail?' });
const saved = toolResultPath(result.runId, result.toolCalls[0].id);The application still gets the whole result in onToolResult and RunResult.toolCalls. Saved results can hold secrets a tool returned: .cogitator/ gets a .gitignore that keeps it out of git, and saving a result removes the results of runs older than limits.toolResultRetention (milliseconds, 7 days by default, Infinity keeps them all). Without such a workspace, or with a read_file of another origin, the result is only cut, as before, and when saving fails (the disk is full, the file is over the workspace's size limit) the result is only cut and the failure is logged as a warning. Errors are never saved, they are short.
Context Budget with Memory
With memory.contextBuilder and no maxTokens of its own, a run builds its context for the model it runs on: the model's context window minus room for the answer and the tool schemas, and below compressionThreshold when compression is on. The runtime passes that budget to the builder once, with reserveTokens: 0, and the builder counts the input in it (the final partition), so the window is not cut by a second reserve. The builder shares the budget among its partitions and lists what did not fit in dropped.
The context is ordered for the prompt cache: the system message and the history come first and stay the same from turn to turn, the history carries cache breakpoints at its end and at the end of the turn before, and what memory recalls for the turn, the run's context and the insights of reflection go with the input in the last user message (see Memory Context and Prompt Caching). Clearing tool outputs and compression change the conversation inside a run, so each one costs the cache of what comes after the first message it changes, and clearAtLeast and compressionThreshold decide how often that happens.
The builder's hybrid strategy (memory.contextBuilder.strategy, not the compression strategy of the same name below) keeps the newest turns as history and recalls older turns and memory items a search of memory finds for the turn into the recall partition, under Earlier in this conversation: and From memory:. So a turn long out of the window can still reach the model, while the history prefix keeps coming from the prompt cache. The search reads the turn at RunOptions.asOf (now by default) in the thread's time zone (its metadata.timeZone, else memory.contextBuilder.timeZone, else memory.extraction.timeZone, else UTC).
The agent.run span reports the tokens each partition of the context took as context.tokens.<partition> (context.tokens.system, context.tokens.recent, context.tokens.final and so on).
Clearing, Compression and Memory Compaction
Three features keep a conversation inside the model's window. They act at different times and last for different spans:
| Feature | When | What it changes | What stays |
|---|---|---|---|
context.clearToolOutputs | Before a model turn, past trigger tokens | Old tool outputs in the run's conversation become notes | Memory keeps every output, recall_tool_output reads one back |
context (compression) | Before a model turn, past compressionThreshold of the window | What this run sends, cut or summarized | Memory keeps the whole history, and the next run reads all of it again |
memory.compaction | After a run, past at of the window | The thread: a compaction entry that later runs read in place of older conversation | The entries stay on the branch, runs read the handoff and the newest turns |
Clearing comes first, so outputs go before anything is summarized. Compression lasts one run: the next run loads the history again and compresses it again. Memory compaction lasts: it writes a hierarchical summary of grounded atoms to the thread once, and every later run starts from it. Used together, compression keeps a single run that grows past the window going, and memory compaction keeps the thread small across runs.
A thread that outgrows its window again within two turns of its last compaction is not compacted again. Such a conversation is filled by a few large tool outputs, not by turns, so memory compaction logs a warning to turn on context.clearToolOutputs instead, which is what frees that room.
Token Counting
Cogitator uses a fast heuristic token counter (4 characters per token plus 4 per message) for real-time decisions. Context windows come from the model registry, with built-in fallbacks for well-known model families; an unknown model counts as 8,192 tokens:
import { ContextManager } from '@cogitator-ai/core';
const manager = new ContextManager({
enabled: true,
strategy: 'hybrid',
compressionThreshold: 0.8,
});
manager.getModelContextLimit('anthropic/claude-sonnet-5-5'); // 1000000
manager.getModelContextLimit('ollama/my-finetune'); // 8192Checking Context State
Before compressing, you can inspect the current state:
const state = manager.checkState(messages, 'openai/gpt-6.1-sol');
console.log(state.currentTokens); // estimated tokens used
console.log(state.maxTokens); // effective limit (minus output reserve)
console.log(state.availableTokens); // remaining space
console.log(state.utilizationPercent); // e.g. 85.3
console.log(state.needsCompression); // true if above thresholdStrategies
Truncate
Drops the oldest non-system messages to fit within the token budget. Fast and stateless -- no LLM call required.
const cog = new Cogitator({
context: { strategy: 'truncate', compressionThreshold: 0.8 },
// ...
});System messages are always preserved. History is trimmed from the beginning, keeping the most recent exchanges intact. Best for scenarios where older context is rarely needed.
Sliding Window
Keeps a fixed window of recent messages and optionally summarizes older ones. Provides a good balance between context preservation and token efficiency.
const cog = new Cogitator({
context: {
strategy: 'sliding-window',
windowSize: 15,
summaryModel: 'openai/gpt-6-luna',
},
// ...
});Messages outside the last windowSize are summarized into a single system message ([Previous conversation summary]): by summaryModel when it is set, else as a basic extractive summary of the last few user and assistant messages. If even the window does not leave room for a summary, the older messages are dropped.
Summarize
Uses an LLM to generate a comprehensive summary of older conversation history, preserving key facts, decisions, and pending tasks.
const cog = new Cogitator({
context: {
strategy: 'summarize',
summaryModel: 'openai/gpt-6-luna',
windowSize: 5,
},
// ...
});The summarizer keeps the most recent 20% of messages as is (at least 2, at most windowSize) and replaces everything older with one summary message. It uses summaryModel, or the running agent's model when that is not set. The summary prompt instructs the LLM to preserve user preferences, key decisions, and critical context. Falls back to an extractive summary if the LLM call fails.
Hybrid (Default)
Automatically selects the best strategy based on how far over the limit the conversation is:
| Size vs. available context | Strategy | Reasoning |
|---|---|---|
| Up to 1.5x | Sliding Window | Mild overflow, window is sufficient |
Over 1.5x, summaryModel set | Summarize | Heavy overflow, need intelligent compression |
1.5x–2x, no summaryModel | Sliding Window | Best effort without LLM |
Over 2x, no summaryModel | Truncate | Extreme overflow, aggressive trimming needed |
const cog = new Cogitator({
context: { strategy: 'hybrid', summaryModel: 'openai/gpt-6-luna' },
// ...
});This is the recommended default -- it adapts to the situation without manual tuning.
Compression Results
Every compression call returns detailed metrics:
const result = await manager.compress(messages, 'openai/gpt-6.1-sol');
console.log(result.messages); // compressed message array
console.log(result.originalTokens); // tokens before compression
console.log(result.compressedTokens); // tokens after compression
console.log(result.strategy); // which strategy was used
console.log(result.truncated); // messages dropped (truncate)
console.log(result.summarized); // messages summarized (summarize/sliding-window)Standalone Usage
You can use ContextManager outside of the Cogitator runtime for custom pipelines:
import { ContextManager } from '@cogitator-ai/core';
const manager = new ContextManager(
{
enabled: true,
strategy: 'sliding-window',
windowSize: 10,
summaryModel: 'openai/gpt-6-luna',
},
{ route: (model) => cog.route(model) }
);
if (manager.shouldCompress(messages, 'openai/gpt-6.1-sol')) {
const { messages: compressed } = await manager.compress(messages, 'openai/gpt-6.1-sol');
messages = compressed;
}The second constructor argument tells the manager how to reach a model for summaries: route returns the backend and the model name for a provider/model id (cog.route() does exactly that), and getBackend is the older form that returns only the backend. Without either, summaries are extractive. The strategy classes (TruncateStrategy, SlidingWindowStrategy, SummarizeStrategy, HybridStrategy) are exported too, for custom pipelines that call compress() on a strategy directly.