"type": "module" and the tsx runner.
Compaction replaces older model context with a summary when a conversation grows. It helps fit later turns into the model’s context window, but summaries are lossy. Keep authoritative records in application storage and include them again when exact wording matters.
Compact a session explicitly
Use the quickstart setup withOPENAI_API_KEY. Save this as compaction.ts and run node --env-file=.env --import tsx compaction.ts. Both the initial turn and the summary make provider requests.
compact() waits for a committed compaction boundary. It returns the boundary ID, pre-compaction token count, preserved message IDs and optional summary text. It occupies the session’s active operation slot; do not run another query in that session simultaneously.
The method has no signal option in v2. Use the owning session/client lifecycle to cancel and clean up abandoned work; do not assume a Promise.race timeout stops the underlying operation. A failed compaction can reject rather than return a normal ResultMessage.
Automatic compaction
compaction: { auto: true } allows runtime compaction near the model’s context limit. auto: false disables that automatic behavior; explicit session.compact() remains available.
includeFiles: false avoids the coding-oriented file/directory section. Neutral sessions use a general-purpose summary template. File-context inclusion changes the summary’s content, not the permissions of tools or the process.
Customize a summary
PasscustomInstructions to a manual call for that summary. PreCompact can add instructions for automatic and manual compactions; multiple hook instructions are joined in order. PostCompact reports outcome and preserved-message metadata after the work.
A call can select a different summary model with session.compact({ model: "openai/gpt-4.1-mini" }). That model must be configured and accessible to the runtime. A session-scoped agents.compaction definition can customize helper instructions. For manual session.compact(), choose the summary model through the call’s model option: the facade supplies that model, or the session’s main model when omitted, ahead of the helper’s model setting. Changing the summary model for a call does not change the main model.
Compaction consumes tokens and can incur cost. Manual compaction contributes to usage observed by the session handle. When checkpointing.beforeCompaction is enabled, the boundary can reference a file checkpoint; that checkpoint and the conversational summary remain separate mechanisms.