Open History to see the last commit
1/**
2 * `@tanstack/ai-compaction` — context-window compaction as a `chat()`
3 * middleware. `withCompaction({ maxTokens, strategy })` runs before each model
4 * call: when the working message set grows past `maxTokens`, the chosen
5 * `CompactionStrategy` rewrites the messages. Because it runs every call,
6 * compaction is incremental and rolling.
7 *
8 * Strategies are pluggable, mirroring `AgentLoopStrategy`. Three are built in:
9 * {@link evictOldest}, {@link summarizeOldest}, and {@link clearToolResults}.
10 * Write your own by passing any {@link CompactionStrategy}.
11 *
12 * The system prompt is never touched — `chat()` keeps it separate from
13 * `messages`.
14 */
15import {
16 CONTEXT_OVERFLOW_CODE,
17 LogRecordsCapability,
18 MetadataCapability,
19 getLogRecords,
20 getMetadata,
21} from '@tanstack/ai'
22import {
23 COMPACTION_RECORD_TYPE,
24 compactionRecord,
25 projectCompaction,
26} from './record'
27import {
28 readSummary,
29 splitDetails,
30 summaryBody,
31 summaryContent,
32} from './summarizer'
33import {
34 USAGE_NAMESPACE,
35 countFromUsage,
36 hashMessages,
37 memoryMetadata,
38 sumUsage,
39 toUsageCount,
40} from './usage-count'
41import type {
42 AnyTextAdapter,
43 ChatMiddleware,
44 ChatMiddlewareConfig,
45 ChatMiddlewareContext,
46 ModelMessage,
47 TokenUsage,
48} from '@tanstack/ai'
49import type { CompactionRecord } from './record'
50import type { SummarizeInput, Summarizer } from './summarizer'
51
52export { COMPACTION_RECORD_TYPE, projectCompaction } from './record'
53export type { CompactionRecord } from './record'
54export { conversationSummarizer } from './summarizer'
55export type { SummarizeInput, Summarizer } from './summarizer'
56
57/** CUSTOM stream event: compaction is about to run. */
58export const COMPACTION_STARTED_EVENT = 'compaction:started'
59/** CUSTOM stream event: compaction result (counts and previews). */
60export const COMPACTION_STATE_EVENT = 'compaction:state'
61/** CUSTOM stream event: compaction finished. */
62export const COMPACTION_ENDED_EVENT = 'compaction:ended'
63
64export type CompactionStreamEventName =
65 | typeof COMPACTION_STARTED_EVENT
66 | typeof COMPACTION_STATE_EVENT
67 | typeof COMPACTION_ENDED_EVENT
68
69const PREVIEW_CHARS = 4000
70const MAX_PREVIEWS = 24
71
72/** One message in a `compaction:state` preview list. */
73export interface CompactionMessagePreview {
74 role: string
75 tokens: number
76 text: string
77}
78
79/** Why a compaction ran. */
80export type CompactionReason =
81 | 'threshold'
82 | 'forced'
83 | 'after-turn'
84 | 'background'
85
86/** Payload of {@link COMPACTION_STARTED_EVENT}. */
87export interface CompactionStartedEventValue {
88 before: number
89 messagesBefore: number
90 reusedCheckpoint: boolean
91 maxTokens: number
92 strategyKey?: string
93 reason: CompactionReason
94}
95
96/** Payload of {@link COMPACTION_STATE_EVENT}. */
97export interface CompactionStateEventValue {
98 before: number
99 after: number
100 messagesBefore: number
101 messagesAfter: number
102 reusedCheckpoint: boolean
103 maxTokens: number
104 strategyKey?: string
105 /** Messages removed or rewritten. */
106 dropped?: Array<CompactionMessagePreview>
107 /** Messages the model will see after compaction. */
108 result?: Array<CompactionMessagePreview>
109}
110
111/** Payload of {@link COMPACTION_ENDED_EVENT}. */
112export interface CompactionEndedEventValue {
113 after: number
114 messagesAfter: number
115 reusedCheckpoint: boolean
116 maxTokens: number
117 durationMs: number
118 strategyKey?: string
119 reason: CompactionReason
120 /** The sum of the strategy's `addUsage` calls, for example its summary call. */
121 usage?: TokenUsage
122 /**
123 * Set when the strategy threw, or when the adapter's `compact` failed and
124 * the strategy ran in its place.
125 */
126 error?: { message: string }
127 /** `true`: a ready background summary no longer fit the messages, and was dropped. */
128 stale?: boolean
129}
130
131/**
132 * The models whose native compaction failed for good, by adapter. They use
133 * the strategy for the rest of the process.
134 */
135const failedNative = new WeakMap<object, Set<string>>()
136
137/**
138 * True when the provider has no compaction endpoint: a 404, 405, or 501.
139 * Other failures can belong to one request, thread, or key (a 400 for a
140 * too-long history, a 401, a 429, a network error), so the next compaction
141 * tries again.
142 */
143function isPermanentFailure(error: unknown): boolean {
144 const status =
145 typeof error === 'object' && error !== null && 'status' in error
146 ? error.status
147 : undefined
148 return typeof status === 'number' && [404, 405, 501].includes(status)
149}
150
151function emitCompactionStarted(
152 ctx: ChatMiddlewareContext,
153 value: CompactionStartedEventValue,
154) {
155 ctx.emitCustomEvent(COMPACTION_STARTED_EVENT, value)
156}
157
158function emitCompactionState(
159 ctx: ChatMiddlewareContext,
160 value: CompactionStateEventValue,
161) {
162 ctx.emitCustomEvent(COMPACTION_STATE_EVENT, value)
163}
164
165function emitCompactionEnded(
166 ctx: ChatMiddlewareContext,
167 value: CompactionEndedEventValue,
168) {
169 ctx.emitCustomEvent(COMPACTION_ENDED_EVENT, value)
170}
171
172const strategyKeys = new WeakMap<CompactionStrategy, string>()
173const CHECKPOINT_NAMESPACE = '@tanstack/ai-compaction'
174
175interface CompactionCheckpoint {
176 schemaVersion: 1
177 sourceMessageCount: number
178 sourceHash: string
179 strategyKey: string
180 compactedMessages: Array<ModelMessage>
181}
182
183function identifyStrategy(
184 strategy: CompactionStrategy,
185 key: string | undefined,
186): CompactionStrategy {
187 if (key) strategyKeys.set(strategy, key)
188 return strategy
189}
190
191function isModelMessage(value: unknown): value is ModelMessage {
192 return (
193 typeof value === 'object' &&
194 value !== null &&
195 'role' in value &&
196 (value.role === 'user' ||
197 value.role === 'assistant' ||
198 value.role === 'tool') &&
199 'content' in value
200 )
201}
202
203function isCompactionCheckpoint(value: unknown): value is CompactionCheckpoint {
204 return (
205 typeof value === 'object' &&
206 value !== null &&
207 'schemaVersion' in value &&
208 value.schemaVersion === 1 &&
209 'sourceMessageCount' in value &&
210 typeof value.sourceMessageCount === 'number' &&
211 Number.isInteger(value.sourceMessageCount) &&
212 value.sourceMessageCount >= 0 &&
213 'sourceHash' in value &&
214 typeof value.sourceHash === 'string' &&
215 'strategyKey' in value &&
216 typeof value.strategyKey === 'string' &&
217 'compactedMessages' in value &&
218 Array.isArray(value.compactedMessages) &&
219 value.compactedMessages.every(isModelMessage)
220 )
221}
222
223/** The metadata namespace of a ready background summary. The key is the thread. */
224const BACKGROUND_NAMESPACE = '@tanstack/ai-compaction:background'
225
226/** The memory namespace of the run of the last call of each thread. */
227const RUN_NAMESPACE = '@tanstack/ai-compaction:run'
228
229/** A ready background summary: the record of its result, built on its snapshot. */
230interface BackgroundReady {
231 record: CompactionRecord
232 /** The hash of the snapshot before `record.from`, for a record with no `firstKeptId`. */
233 prefixHash: string
234}
235
236function isBackgroundReady(value: unknown): value is BackgroundReady {
237 return (
238 typeof value === 'object' &&
239 value !== null &&
240 'prefixHash' in value &&
241 typeof value.prefixHash === 'string' &&
242 'record' in value &&
243 typeof value.record === 'object' &&
244 value.record !== null &&
245 'type' in value.record &&
246 value.record.type === COMPACTION_RECORD_TYPE &&
247 'from' in value.record &&
248 typeof value.record.from === 'number'
249 )
250}
251
252/** Wait for `job`. Throw the signal's reason when it aborts first. */
253function abortable(job: Promise<void>, signal: AbortSignal | undefined) {
254 if (!signal) return job
255 return new Promise<void>((resolve, reject) => {
256 const stop = () => reject(signal.reason)
257 if (signal.aborted) {
258 stop()
259 return
260 }
261 signal.addEventListener('abort', stop, { once: true })
262 // A job never rejects: it reports its own failure.
263 void job.then(() => {
264 signal.removeEventListener('abort', stop)
265 resolve()
266 })
267 })
268}
269
270function messagePreviewText(message: ModelMessage): string {
271 if (typeof message.content === 'string') return message.content
272 return JSON.stringify(message.content ?? '')
273}
274
275function toMessagePreview(
276 message: ModelMessage,
277 estimate: (message: ModelMessage) => number,
278): CompactionMessagePreview {
279 const text = messagePreviewText(message)
280 return {
281 role: message.role,
282 tokens: estimate(message),
283 text:
284 text.length > PREVIEW_CHARS ? `${text.slice(0, PREVIEW_CHARS)}…` : text,
285 }
286}
287
288function previewList(
289 messages: ReadonlyArray<ModelMessage>,
290 estimate: (message: ModelMessage) => number,
291): Array<CompactionMessagePreview> {
292 const mapped = messages.map((message) => toMessagePreview(message, estimate))
293 if (mapped.length <= MAX_PREVIEWS) return mapped
294 return mapped.slice(0, MAX_PREVIEWS)
295}
296
297function droppedMessages(
298 before: ReadonlyArray<ModelMessage>,
299 after: ReadonlyArray<ModelMessage>,
300): Array<ModelMessage> {
301 const afterKeys = new Set(after.map((message) => JSON.stringify(message)))
302 return before.filter((message) => !afterKeys.has(JSON.stringify(message)))
303}
304
305function compactionStateValue(args: {
306 before: number
307 after: number
308 messagesBefore: number
309 messagesAfter: number
310 reusedCheckpoint: boolean
311 maxTokens: number
312 strategyKey?: string
313 beforeMessages?: ReadonlyArray<ModelMessage>
314 afterMessages?: ReadonlyArray<ModelMessage>
315 estimate: (message: ModelMessage) => number
316}): CompactionStateEventValue {
317 const value: CompactionStateEventValue = {
318 before: args.before,
319 after: args.after,
320 messagesBefore: args.messagesBefore,
321 messagesAfter: args.messagesAfter,
322 reusedCheckpoint: args.reusedCheckpoint,
323 maxTokens: args.maxTokens,
324 ...(args.strategyKey ? { strategyKey: args.strategyKey } : {}),
325 }
326 if (args.afterMessages) {
327 value.result = previewList(args.afterMessages, args.estimate)
328 }
329 if (args.beforeMessages && args.afterMessages) {
330 value.dropped = previewList(
331 droppedMessages(args.beforeMessages, args.afterMessages),
332 args.estimate,
333 )
334 }
335 return value
336}
337
338/** Rough token estimate for one message. Default: characters / 4. */
339export function estimateMessageTokens(message: ModelMessage): number {
340 let text = messagePreviewText(message)
341 if (message.toolCalls?.length) text += JSON.stringify(message.toolCalls)
342 return Math.ceil(text.length / 4)
343}
344
345/** What a {@link CompactionStrategy} receives alongside the messages. */
346export interface CompactionContext {
347 /** The `maxTokens` budget from `withCompaction`. */
348 maxTokens: number
349 /** The shared token estimator (default {@link estimateMessageTokens}). */
350 estimate: (message: ModelMessage) => number
351 /** Report the usage of a model call the strategy made, for example a summary. */
352 addUsage: (usage: TokenUsage) => void
353 /** Aborted when the run is cancelled. Pass it to a model call. */
354 signal?: AbortSignal
355 /**
356 * The thread id of the conversation. A model call of the strategy uses a
357 * thread id of its own, for example `${threadId}:compaction`.
358 */
359 threadId: string
360}
361
362/**
363 * Shrinks a message list. Called when the count is over `maxTokens`, or when
364 * `compactNext` forces it.
365 * Return the rewritten messages, or `null` to leave them unchanged.
366 */
367export type CompactionStrategy = (
368 messages: ReadonlyArray<ModelMessage>,
369 ctx: CompactionContext,
370) => Array<ModelMessage> | null | Promise<Array<ModelMessage> | null>
371
372/** Reported to `onCompact` after each compaction event. */
373export interface CompactionInfo {
374 /** Estimated tokens before compaction. */
375 before: number
376 /** Estimated tokens after compaction. */
377 after: number
378 /** Message count before compaction. */
379 messagesBefore: number
380 /** Message count after compaction (unchanged for {@link clearToolResults}). */
381 messagesAfter: number
382 /** Why the compaction ran. */
383 reason: CompactionReason
384 /** The usage the strategy reported with `addUsage`. */
385 usage?: TokenUsage
386 /**
387 * Set when the after-turn check failed (the strategy, the store, or
388 * `onCompact` threw), or when a background summary failed. The run goes
389 * on. When the strategy failed, a later check tries again. Also set when
390 * the adapter's `compact` failed and the strategy ran in its place.
391 */
392 error?: { message: string }
393 /** `true`: a ready background summary no longer fit the messages, and was dropped. */
394 stale?: boolean
395}
396
397export interface CompactionOptions {
398 /** Compact when the token count of `messages` passes this (see `countTokens` and `auto`). */
399 maxTokens: number
400 /** How to shrink the messages. Default: {@link evictOldest}. */
401 strategy?: CompactionStrategy
402 /** Per-message token estimator. Default: {@link estimateMessageTokens}. */
403 estimateTokens?: (message: ModelMessage) => number
404 /**
405 * Stable identity for persisted checkpoints. Set this for custom strategies
406 * or estimators, and change it when their output can change.
407 */
408 strategyKey?: string
409 /** Observe each compaction (logging, metrics). */
410 onCompact?: (info: CompactionInfo) => void
411 /**
412 * Compact with the provider's own endpoint. Pass the adapter of the
413 * `chat()` call. When the adapter has `compact`, it runs in place of
414 * `strategy`. Else, or when `compact` fails, `strategy` runs. A failure
415 * sets `error` in `onCompact` and `compaction:ended`. After a 404, 405,
416 * or 501 (no compaction endpoint), that adapter and model use `strategy`
417 * for the rest of the process. Default: off.
418 */
419 native?: Pick<AnyTextAdapter, 'compact'>
420 /**
421 * How to count the tokens of the list. `'usage'`: the usage the provider
422 * reported for the last model call, plus the estimate of each message after
423 * its reply. The estimate counts when no saved usage fits the list. The
424 * strategies still use the estimate to choose the cut. Default
425 * `'estimate'`.
426 */
427 countTokens?: 'estimate' | 'usage'
428 /**
429 * `false`: do not compact when the count passes `maxTokens`.
430 * `compactNext`, the after-turn overflow check, and the retry after a
431 * context overflow still compact. Default
432 * `true`.
433 */
434 auto?: boolean
435 /**
436 * The model's context window in tokens. With `countTokens: 'usage'` and
437 * `durable: true` on a host with a log, the check after the last model call
438 * of a run compacts when the usage is over it, even with `auto: false`. A
439 * failed after-turn compaction never fails the run: `onCompact` gets
440 * `error`. Only a failed log append fails it.
441 */
442 contextWindow?: number
443 /**
444 * Write each compaction as a log record when the host provides
445 * `LogRecordsCapability` (a host with a durable session log). The host
446 * folds each record with {@link projectCompaction} into the messages of
447 * the later model calls, and when it rebuilds the session. Without the
448 * capability, the checkpoint is used, and there is no after-turn check.
449 * When an earlier middleware set `providerMessages`, the result stays
450 * provider-only. Default `false`.
451 */
452 durable?: boolean
453 /**
454 * `true`: when the strategy throws in the check before a model call, report
455 * the error in `compaction:ended` and send the list without compaction.
456 * Default `false`: the run fails. The after-turn check never fails the run.
457 */
458 continueOnError?: boolean
459 /**
460 * Prepare the summary before the list is over `maxTokens`. When the count
461 * at a model call is over `atTokens` and not over `maxTokens`, the strategy
462 * runs on a copy of the messages, and the call does not wait for it. The
463 * result applies at the first model call of the next run. A call over
464 * `maxTokens` while it runs waits for it. A ready result waits in the
465 * metadata store, or in memory without one. `atTokens` must be below
466 * `maxTokens`. Default: off.
467 */
468 background?: { atTokens: number }
469}
470
471/** What {@link withCompaction} returns: a chat middleware with `compactNext`. */
472export interface CompactionMiddleware extends ChatMiddleware {
473 /**
474 * Compact at the next model call on `threadId`, even when the count is
475 * under `maxTokens` or `auto` is `false`. That call clears the flag.
476 */
477 compactNext: (threadId: string) => void
478}
479
480const sum = (
481 messages: ReadonlyArray<ModelMessage>,
482 estimate: (m: ModelMessage) => number,
483) => messages.reduce((total, m) => total + estimate(m), 0)
484
485/**
486 * Find the split point that keeps the most recent messages up to
487 * `keepRecentTokens`, then moves the cut forward past any leading tool result
488 * so the kept tail never starts with an orphan (its tool call would be dropped).
489 * Returns the index where the tail begins (head is `messages[0..cut)`).
490 */
491function splitAtRecent(
492 messages: ReadonlyArray<ModelMessage>,
493 estimate: (m: ModelMessage) => number,
494 keepRecentTokens: number,
495): number {
496 let kept = 0
497 let cut = messages.length
498 while (cut > 0) {
499 const prev = messages[cut - 1]
500 if (!prev) break
501 const size = estimate(prev)
502 if (kept + size > keepRecentTokens) break
503 kept += size
504 cut--
505 }
506 // Always keep at least the last message.
507 if (cut >= messages.length) cut = messages.length - 1
508 while (cut < messages.length && messages[cut]?.role === 'tool') cut++
509 // Trailing tool results: skipping orphans would drop the whole tail (the
510 // normal agent-loop state). Keep those results and the message that owns them.
511 if (cut >= messages.length) {
512 cut = messages.length
513 while (cut > 0 && messages[cut - 1]?.role === 'tool') cut--
514 if (cut > 0) cut--
515 }
516 return cut
517}
518
519/**
520 * Drop the oldest messages and replace them with a short marker. Cheapest
521 * strategy — no extra model call. This is the default.
522 */
523export function evictOldest(
524 options: {
525 /** Tokens of recent messages to keep verbatim. Default `floor(maxTokens/2)`. */
526 keepRecentTokens?: number
527 /** Build the marker that replaces the dropped head. */
528 marker?: (droppedCount: number) => string
529 } = {},
530): CompactionStrategy {
531 const strategy: CompactionStrategy = (messages, ctx) => {
532 const keep = options.keepRecentTokens ?? Math.floor(ctx.maxTokens / 2)
533 const cut = splitAtRecent(messages, ctx.estimate, keep)
534 // Can't shrink past the recent window; raise keepRecentTokens or lower
535 // maxTokens if compaction never fires.
536 if (cut <= 0) return null
537 const marker =
538 options.marker?.(cut) ??
539 `[${cut} earlier message(s) omitted to save context.]`
540 return [{ role: 'user', content: marker }, ...messages.slice(cut)]
541 }
542 return identifyStrategy(
543 strategy,
544 options.marker
545 ? undefined
546 : `evict-oldest:${options.keepRecentTokens ?? 'half'}`,
547 )
548}
549
550/**
551 * The start of the turn that holds index `cut`: its user message. When no
552 * user message comes after an earlier summary at index 0, the turn started
553 * before the summary. Then the cut is not a split turn: it returns `cut`, and
554 * one update call merges the messages into the summary.
555 */
556function turnStart(messages: ReadonlyArray<ModelMessage>, cut: number) {
557 let start = cut
558 // The walk stops at index 0 also when the summary has the role 'user'.
559 while (start > 0 && messages[start]?.role !== 'user') start -= 1
560 return start === 0 && readSummary(messages[0]) ? cut : start
561}
562
563/**
564 * Drop the oldest messages and replace them with an LLM summary. Keeps the gist
565 * of old turns at the cost of one summarization call. Wire `summarize` to
566 * {@link conversationSummarizer}, `summarize()`, or any model call.
567 *
568 * When the messages start with an earlier summary, `summarize` gets its text
569 * as `previousSummary`, so it can merge the new messages into it.
570 */
571export function summarizeOldest(options: {
572 /** Returns the summary text, or the text and the usage of its model call. */
573 summarize: Summarizer
574 /** Tokens of recent messages to keep verbatim. Default `floor(maxTokens/2)`. */
575 keepRecentTokens?: number
576 /** Role of the injected summary message. Default `'assistant'`. */
577 summaryRole?: 'user' | 'assistant'
578 /**
579 * `'turn'`: when the kept tail starts inside a turn, summarize the history
580 * before the turn and the first part of the turn, in two parallel calls.
581 * When the user message of the turn comes right after an earlier summary,
582 * only the second call runs. When no user message comes after an earlier
583 * summary, the turn started before it: one update call runs, as with
584 * `'message'`. Default `'message'`.
585 */
586 cut?: 'message' | 'turn'
587}): CompactionStrategy {
588 const strategy: CompactionStrategy = async (messages, ctx) => {
589 const keep = options.keepRecentTokens ?? Math.floor(ctx.maxTokens / 2)
590 const cut = splitAtRecent(messages, ctx.estimate, keep)
591 if (cut <= 0) return null
592 // Follows the signal of the run. When one call fails, it aborts the other
593 // call, so that call stops and adds no usage after the end event.
594 const controller = new AbortController()
595 const stop = () => controller.abort(ctx.signal?.reason)
596 if (ctx.signal?.aborted) stop()
597 ctx.signal?.addEventListener('abort', stop, { once: true })
598 const summarize = async (
599 part: Array<ModelMessage>,
600 input: Omit<SummarizeInput, 'threadId'>,
601 ) => {
602 try {
603 const result = await options.summarize(part, {
604 ...input,
605 threadId: ctx.threadId,
606 signal: controller.signal,
607 })
608 const summary = typeof result === 'string' ? result : result.summary
609 if (typeof result !== 'string' && result.usage) {
610 ctx.addUsage(result.usage)
611 }
612 // An empty summary would replace the history with nothing. Fail the
613 // compaction instead, so the history stays as it is.
614 if (summary.trim() === '') {
615 throw new Error('The summarizer returned an empty summary.')
616 }
617 return summary
618 } catch (error) {
619 controller.abort(error)
620 throw error
621 }
622 }
623 const earlier = readSummary(messages[0])
624 const start =
625 options.cut === 'turn' && messages[cut]?.role !== 'user'
626 ? turnStart(messages, cut)
627 : cut
628 const prefix = messages.slice(start, cut)
629 // With a turn prefix, an earlier summary right before the turn is the
630 // whole history. Keep its text, and make no history call.
631 const historyCall =
632 start > 0 && !(earlier && start === 1 && prefix.length > 0)
633 const previousDetails =
634 earlier?.details !== undefined ? { previousDetails: earlier.details } : {}
635 const [history, turn] = await Promise.all([
636 historyCall
637 ? summarize(messages.slice(0, start), {
638 ...(earlier ? { previousSummary: earlier.summary } : {}),
639 ...previousDetails,
640 ...(prefix.length > 0 ? { turnPrefixMessages: prefix } : {}),
641 })
642 : undefined,
643 prefix.length > 0
644 ? summarize(prefix, {
645 turnPrefix: true,
646 // With no history call, this call writes the details.
647 ...(historyCall
648 ? {}
649 : { turnPrefixMessages: prefix, ...previousDetails }),
650 })
651 : undefined,
652 ]).finally(() => ctx.signal?.removeEventListener('abort', stop))
653 let historyText = history
654 let turnText = turn
655 if (!historyCall && turn !== undefined) {
656 // The details of the turn-prefix call go with the history, before the
657 // turn context. When the call gives details, they replace the details
658 // of the earlier summary. Otherwise the earlier details stay.
659 const split = splitDetails(turn)
660 historyText = summaryBody(
661 earlier?.summary ?? '',
662 split.details ?? earlier?.details,
663 )
664 turnText = split.summary
665 }
666 const body = [
667 historyText,
668 turnText === undefined ? undefined : `## Turn context\n\n${turnText}`,
669 ]
670 .filter((part) => part !== undefined && part !== '')
671 .join('\n\n')
672 return [
673 {
674 role: options.summaryRole ?? 'assistant',
675 content: summaryContent(body),
676 },
677 ...messages.slice(cut),
678 ]
679 }
680 return identifyStrategy(
681 strategy,
682 `summarize-oldest:${options.keepRecentTokens ?? 'half'}:${options.summaryRole ?? 'assistant'}${options.cut === 'turn' ? ':turn' : ''}`,
683 )
684}
685
686/**
687 * Replace the content of old tool-result messages with a stub, keeping every
688 * message and its tool-call pairing in place. Best for agent loops where tool
689 * output (file reads, command output) dominates the token count — it clears the
690 * bulk without disturbing the conversation shape. No extra model call.
691 */
692export function clearToolResults(
693 options: {
694 /** Number of most-recent tool results to keep verbatim. Default `3`. */
695 keepRecentToolResults?: number
696 /** Text that replaces a cleared tool result. */
697 stub?: string
698 } = {},
699): CompactionStrategy {
700 const keepN = options.keepRecentToolResults ?? 3
701 const stub = options.stub ?? '[tool output cleared to save context]'
702 const strategy: CompactionStrategy = (messages) => {
703 const toolIndexes: Array<number> = []
704 messages.forEach((m, i) => {
705 if (m.role === 'tool') toolIndexes.push(i)
706 })
707 if (toolIndexes.length <= keepN) return null
708 const clearBefore = toolIndexes[toolIndexes.length - keepN] ?? 0
709 let changed = false
710 const next = messages.map((m, i) => {
711 if (m.role === 'tool' && i < clearBefore && m.content !== stub) {
712 changed = true
713 return { ...m, content: stub }
714 }
715 return m
716 })
717 return changed ? next : null
718 }
719 return identifyStrategy(strategy, `clear-tool-results:${keepN}:${stub}`)
720}
721
722/**
723 * Run several strategies in order, escalating: stop as soon as the running
724 * estimate is back under `maxTokens`. Put the cheap, targeted strategy first
725 * (for example {@link clearToolResults}) and a broad fallback last (for example
726 * {@link evictOldest}) — the fallback only runs when clearing was not enough.
727 * A strategy that returns `null` (no change) is skipped and the next one runs.
728 *
729 * @example
730 * ```ts
731 * withCompaction({
732 * maxTokens: 100_000,
733 * strategy: composeStrategies(clearToolResults(), evictOldest()),
734 * })
735 * ```
736 */
737export function composeStrategies(
738 ...strategies: Array<CompactionStrategy>
739): CompactionStrategy {
740 const strategy: CompactionStrategy = async (messages, ctx) => {
741 let current: ReadonlyArray<ModelMessage> = messages
742 let result: Array<ModelMessage> | null = null
743 for (const itemStrategy of strategies) {
744 if (sum(current, ctx.estimate) <= ctx.maxTokens) break
745 const out = await itemStrategy(current, ctx)
746 if (out) {
747 current = out
748 result = out
749 }
750 }
751 return result
752 }
753 const keys = strategies.map((item) => strategyKeys.get(item))
754 return identifyStrategy(
755 strategy,
756 keys.every((key) => key !== undefined) ? keys.join('|') : undefined,
757 )
758}
759
760/**
761 * Context-compaction middleware. Add to `chat({ middleware: [...] })`.
762 *
763 * When the provider rejects a model call as too long for its context window
764 * (`CONTEXT_OVERFLOW_CODE`), it compacts and calls the model again, once per
765 * model call. This also works with `auto: false`.
766 *
767 * @example
768 * ```ts
769 * chat({
770 * adapter,
771 * messages,
772 * middleware: [withCompaction({ maxTokens: 100_000 })], // evictOldest by default
773 * })
774 * ```
775 */
776export function withCompaction(
777 options: CompactionOptions,
778): CompactionMiddleware {
779 const background = options.background
780 if (background && background.atTokens >= options.maxTokens) {
781 throw new Error(
782 'withCompaction: background.atTokens must be below maxTokens.',
783 )
784 }
785 const estimate = options.estimateTokens ?? estimateMessageTokens
786 const configured = options.strategy ?? evictOldest()
787 const native = options.native
788 const nativeCompact = native?.compact?.bind(native)
789 /**
790 * The strategy of a call: the adapter's `compact` when `native` has it.
791 * When `compact` fails, the configured strategy runs, and `spent.error`
792 * gets the failure. An adapter can get `compact` from a shared base and
793 * point at a provider with no such endpoint.
794 */
795 const strategyOf = (
796 ctx: ChatMiddlewareContext,
797 spent: { error?: { message: string } },
798 config?: ChatMiddlewareConfig,
799 ): CompactionStrategy =>
800 native && nativeCompact
801 ? async (messages, compaction) => {
802 if (failedNative.get(native)?.has(ctx.model)) {
803 return configured(messages, compaction)
804 }
805 try {
806 return await nativeCompact({
807 messages: [...messages],
808 model: ctx.model,
809 // A background summary has no signal, so the run does not stop it.
810 ...(compaction.signal ? { signal: compaction.signal } : {}),
811 ...(config?.wrapFetch ? { wrapFetch: config.wrapFetch } : {}),
812 ...(config ? { systemPrompts: config.systemPrompts } : {}),
813 })
814 } catch (error) {
815 if (compaction.signal?.aborted) throw error
816 if (isPermanentFailure(error)) {
817 const models = failedNative.get(native) ?? new Set<string>()
818 failedNative.set(native, models.add(ctx.model))
819 }
820 spent.error = {
821 message: error instanceof Error ? error.message : String(error),
822 }
823 return configured(messages, compaction)
824 }
825 }
826 : configured
827 const strategyKey =
828 options.strategyKey ??
829 (nativeCompact
830 ? 'native'
831 : options.estimateTokens
832 ? undefined
833 : strategyKeys.get(configured))
834 // A native checkpoint holds an item that only its model reads, so the
835 // model is part of its key, also with a custom `strategyKey`.
836 const checkpointKeyOf = (model: string) =>
837 strategyKey
838 ? `${strategyKey}${nativeCompact ? `:${model}` : ''}:maxTokens=${options.maxTokens}`
839 : undefined
840 const countUsage = options.countTokens === 'usage'
841 const auto = options.auto !== false
842 const memory = memoryMetadata()
843 // The store of the checkpoint and of the usage. With countTokens: 'usage',
844 // a run with no store, or a strategy with no key, uses the memory of this
845 // middleware. Then the next call reuses the compacted list, and the saved
846 // usage fits that list.
847 const storeOf = (ctx: ChatMiddlewareContext) => {
848 const shared = getMetadata(ctx, { optional: true })
849 if (shared && checkpointKeyOf(ctx.model)) return shared
850 return countUsage ? memory : undefined
851 }
852 // True when the last model call of a run got a compacted view. The usage of
853 // that view fits a later call only when that call reuses the checkpoint.
854 const compactedViews = new WeakMap<ChatMiddlewareContext, boolean>()
855 // True when an earlier middleware made the list of the last model call
856 // provider-only. Then no record is written, also not after the turn.
857 const providerOnly = new WeakMap<ChatMiddlewareContext, boolean>()
858 /** The threads whose next model call compacts. */
859 const forced = new Set<string>()
860 /** The iteration whose model call already retried after an overflow. */
861 const overflowRetried = new WeakMap<ChatMiddlewareContext, number>()
862 /** The running background summary of each thread. */
863 const jobs = new Map<string, Promise<void>>()
864 /** Where a ready background summary waits: the metadata store, else memory. */
865 const backgroundStore = (ctx: ChatMiddlewareContext) =>
866 getMetadata(ctx, { optional: true }) ?? memory
867
868 /**
869 * Run the strategy on `snapshot`, apart from the run: the run's signal does
870 * not stop it, and the model call does not wait for it. The result waits in
871 * the store until the first model call of a later run applies it.
872 */
873 function startBackground(
874 ctx: ChatMiddlewareContext,
875 config: ChatMiddlewareConfig,
876 snapshot: Array<ModelMessage>,
877 before: number,
878 reusedCheckpoint: boolean,
879 ) {
880 const startedAt = Date.now()
881 const store = backgroundStore(ctx)
882 const checkpointStrategyKey = checkpointKeyOf(ctx.model)
883 const strategyField = checkpointStrategyKey
884 ? { strategyKey: checkpointStrategyKey }
885 : {}
886 emitCompactionStarted(ctx, {
887 before,
888 messagesBefore: snapshot.length,
889 reusedCheckpoint,
890 maxTokens: options.maxTokens,
891 ...strategyField,
892 reason: 'background',
893 })
894 const spent: { usage?: TokenUsage; error?: { message: string } } = {}
895 // This event reaches the stream only while the run that started the job
896 // still runs. onCompact always gets a failure.
897 const end = (error?: { message: string }) =>
898 emitCompactionEnded(ctx, {
899 after: before,
900 messagesAfter: snapshot.length,
901 reusedCheckpoint,
902 maxTokens: options.maxTokens,
903 durationMs: Date.now() - startedAt,
904 ...strategyField,
905 reason: 'background',
906 ...(spent.usage ? { usage: spent.usage } : {}),
907 ...(error ? { error } : {}),
908 })
909 // The job starts after `jobs.set`, so a strategy that throws at once
910 // still removes its entry.
911 const done = Promise.resolve().then(async () => {
912 try {
913 const next = await strategyOf(
914 ctx,
915 spent,
916 config,
917 )(snapshot, {
918 maxTokens: options.maxTokens,
919 estimate,
920 threadId: ctx.threadId,
921 addUsage: (usage) => {
922 spent.usage = sumUsage(spent.usage, usage)
923 },
924 })
925 if (!next || next === snapshot) {
926 end()
927 return
928 }
929 const record = compactionRecord({
930 reason: 'background',
931 before: snapshot,
932 after: next,
933 tokensBefore: before,
934 tokensAfter: sum(next, estimate),
935 ...(spent.usage ? { usage: spent.usage } : {}),
936 })
937 const ready: BackgroundReady = {
938 record,
939 prefixHash: await hashMessages(snapshot.slice(0, record.from)),
940 }
941 await store.set(BACKGROUND_NAMESPACE, ctx.threadId, ready)
942 } catch (failure) {
943 const error = {
944 message: failure instanceof Error ? failure.message : String(failure),
945 }
946 end(error)
947 try {
948 options.onCompact?.({
949 before,
950 after: before,
951 messagesBefore: snapshot.length,
952 messagesAfter: snapshot.length,
953 reason: 'background',
954 ...(spent.usage ? { usage: spent.usage } : {}),
955 error,
956 })
957 } catch {
958 // An onCompact that throws must not reject the job.
959 }
960 } finally {
961 jobs.delete(ctx.threadId)
962 }
963 })
964 jobs.set(ctx.threadId, done)
965 }
966
967 /**
968 * After the last model call of a run on a durable host: compact when the
969 * usage is over the context window, or over `maxTokens` with `auto` on, and
970 * write the record. Custom events from `onFinish` do not reach the stream,
971 * so only `onCompact` reports it.
972 */
973 async function afterTurn(ctx: ChatMiddlewareContext) {
974 // Without a log the result could go only to a checkpoint, and that can
975 // miss on the next run. The next call's own check covers it.
976 const logRecords = getLogRecords(ctx, { optional: true })
977 const store = storeOf(ctx)
978 if (!logRecords || !store || providerOnly.get(ctx) === true) return
979 const messages = [...ctx.messages]
980 const spent: { usage?: TokenUsage; error?: { message: string } } = {}
981 let tokens = 0
982 const info = (after: number, messagesAfter: number): CompactionInfo => ({
983 before: tokens,
984 after,
985 messagesBefore: messages.length,
986 messagesAfter,
987 reason: 'after-turn',
988 ...(spent.usage ? { usage: spent.usage } : {}),
989 })
990 // The answer already streamed, so only a failed log append fails the run.
991 // Other errors go to onCompact.
992 const fail = (error: unknown, done = info(tokens, messages.length)) => {
993 try {
994 options.onCompact?.({
995 ...done,
996 error: {
997 message: error instanceof Error ? error.message : String(error),
998 },
999 })
1000 } catch {
1001 // An onCompact that throws here must not fail the run either.
1002 }
1003 }
1004
1005 let next: Array<ModelMessage> | null
1006 let tokensAfter: number
1007 try {
1008 // A durable run never reuses a checkpoint. So this is true only when
1009 // the last call of this run compacted, and the list here is the folded
1010 // view that the saved usage counted.
1011 const counted = await countFromUsage(
1012 await store.get(USAGE_NAMESPACE, ctx.threadId),
1013 messages,
1014 estimate,
1015 compactedViews.get(ctx) === true,
1016 )
1017 if (counted === undefined) return
1018 tokens = counted
1019 const isOverflow =
1020 options.contextWindow !== undefined && tokens > options.contextWindow
1021 if (!isOverflow && !(auto && tokens > options.maxTokens)) return
1022 next = await strategyOf(ctx, spent)(messages, {
1023 maxTokens: options.maxTokens,
1024 estimate,
1025 signal: ctx.signal,
1026 threadId: ctx.threadId,
1027 addUsage: (usage) => {
1028 spent.usage = sumUsage(spent.usage, usage)
1029 },
1030 })
1031 if (!next || next === messages || ctx.signal?.aborted) return
1032 tokensAfter = sum(next, estimate)
1033 } catch (error) {
1034 // The saved usage stays, and the next call's own check tries again.
1035 fail(error)
1036 return
1037 }
1038 const record = compactionRecord({
1039 reason: 'after-turn',
1040 before: messages,
1041 after: next,
1042 tokensBefore: tokens,
1043 tokensAfter,
1044 ...(spent.usage ? { usage: spent.usage } : {}),
1045 })
1046 // Append first, so a failed append is never reported as a success.
1047 // withPersistence saved the reply before this hook: it is earlier in the
1048 // middleware list. If it was not, firstKeptId finds the kept tail, or the
1049 // fold skips the record.
1050 await logRecords.append([record])
1051 const done = info(tokensAfter, next.length)
1052 try {
1053 // The saved usage counted the list before this compaction.
1054 await store.delete(USAGE_NAMESPACE, ctx.threadId)
1055 options.onCompact?.(done)
1056 } catch (error) {
1057 fail(error, done)
1058 }
1059 }
1060
1061 return {
1062 name: 'compaction',
1063 optionalRequires: options.durable
1064 ? [MetadataCapability, LogRecordsCapability]
1065 : [MetadataCapability],
1066 compactNext: (threadId) => {
1067 forced.add(threadId)
1068 },
1069 onModelError(ctx, error) {
1070 // Compact and retry once per model call. A second overflow goes to the
1071 // caller.
1072 if (
1073 error.code !== CONTEXT_OVERFLOW_CODE ||
1074 overflowRetried.get(ctx) === ctx.iteration
1075 ) {
1076 return
1077 }
1078 overflowRetried.set(ctx, ctx.iteration)
1079 forced.add(ctx.threadId)
1080 ctx.retry()
1081 },
1082 async onConfig(ctx, config) {
1083 // init is discarded by the engine rebuild and can run before persistence
1084 // hydrates the thread. Compact only on model-bound phases.
1085 if (ctx.phase === 'init') return
1086 const force = forced.delete(ctx.threadId)
1087 const reason: CompactionReason = force ? 'forced' : 'threshold'
1088
1089 const checkpointStrategyKey = checkpointKeyOf(ctx.model)
1090 const startedAt = Date.now()
1091 const { messages } = config
1092 const inputMessages = config.providerMessages ?? messages
1093 providerOnly.set(ctx, inputMessages !== messages)
1094 const store = storeOf(ctx)
1095 // A durable compaction goes to the log, and the fold gives the next
1096 // call the compacted list, so it needs no checkpoint. A list that an
1097 // earlier middleware made provider-only cannot be recorded.
1098 const logRecords =
1099 options.durable && inputMessages === messages
1100 ? getLogRecords(ctx, { optional: true })
1101 : undefined
1102 const metadata = logRecords ? undefined : store
1103 const checkpointKey = checkpointStrategyKey ?? 'memory'
1104 let workingMessages = inputMessages
1105 let reusedCheckpoint = false
1106
1107 if (metadata && inputMessages === messages) {
1108 const stored = await metadata.get(CHECKPOINT_NAMESPACE, ctx.threadId)
1109 if (
1110 isCompactionCheckpoint(stored) &&
1111 stored.strategyKey === checkpointKey &&
1112 stored.sourceMessageCount <= messages.length &&
1113 stored.sourceHash ===
1114 (await hashMessages(messages.slice(0, stored.sourceMessageCount)))
1115 ) {
1116 workingMessages = [
1117 ...stored.compactedMessages,
1118 ...messages.slice(stored.sourceMessageCount),
1119 ]
1120 reusedCheckpoint = true
1121 }
1122 }
1123 // A reused checkpoint is always given to the model. A new compaction
1124 // sets this again below.
1125 compactedViews.set(ctx, reusedCheckpoint)
1126
1127 const fromUsage =
1128 countUsage && store
1129 ? await countFromUsage(
1130 await store.get(USAGE_NAMESPACE, ctx.threadId),
1131 messages,
1132 estimate,
1133 reusedCheckpoint,
1134 )
1135 : undefined
1136 let before = fromUsage ?? sum(workingMessages, estimate)
1137
1138 /**
1139 * Give the model `next` in place of `from`, and keep it: the record on
1140 * a durable host, else the checkpoint. Returns the count of `next`.
1141 */
1142 const commit = async (
1143 from: Array<ModelMessage>,
1144 next: Array<ModelMessage>,
1145 tokensBefore: number,
1146 why: CompactionReason,
1147 usage: TokenUsage | undefined,
1148 error?: { message: string },
1149 ) => {
1150 const info: CompactionInfo = {
1151 before: tokensBefore,
1152 after: sum(next, estimate),
1153 messagesBefore: from.length,
1154 messagesAfter: next.length,
1155 reason: why,
1156 ...(usage ? { usage } : {}),
1157 ...(error ? { error } : {}),
1158 }
1159 if (countUsage) {
1160 // The saved usage counted the list before this compaction.
1161 await store?.delete(USAGE_NAMESPACE, ctx.threadId)
1162 }
1163
1164 // A failed compact must not be stored. This call still uses the
1165 // fallback. The next process tries compact again.
1166 if (!error && logRecords) {
1167 // The model gets `next` now. The record makes the log fold the same.
1168 if (!ctx.signal?.aborted) {
1169 await logRecords.append([
1170 compactionRecord({
1171 reason: why,
1172 before: from,
1173 after: next,
1174 tokensBefore,
1175 tokensAfter: info.after,
1176 ...(usage ? { usage } : {}),
1177 }),
1178 ])
1179 }
1180 } else if (!error && metadata && inputMessages === messages) {
1181 const checkpoint: CompactionCheckpoint = {
1182 schemaVersion: 1,
1183 sourceMessageCount: messages.length,
1184 sourceHash: await hashMessages(messages),
1185 strategyKey: checkpointKey,
1186 compactedMessages: next,
1187 }
1188 if (!ctx.signal?.aborted) {
1189 await metadata.set(CHECKPOINT_NAMESPACE, ctx.threadId, checkpoint)
1190 }
1191 }
1192
1193 // Report after the writes, so a failed append is never reported as a
1194 // success.
1195 options.onCompact?.(info)
1196 emitCompactionState(
1197 ctx,
1198 compactionStateValue({
1199 before: info.before,
1200 after: info.after,
1201 messagesBefore: info.messagesBefore,
1202 messagesAfter: info.messagesAfter,
1203 reusedCheckpoint,
1204 maxTokens: options.maxTokens,
1205 strategyKey: checkpointStrategyKey,
1206 beforeMessages: from,
1207 afterMessages: next,
1208 estimate,
1209 }),
1210 )
1211 emitCompactionEnded(ctx, {
1212 after: info.after,
1213 messagesAfter: info.messagesAfter,
1214 reusedCheckpoint,
1215 maxTokens: options.maxTokens,
1216 durationMs: Date.now() - startedAt,
1217 ...(checkpointStrategyKey
1218 ? { strategyKey: checkpointStrategyKey }
1219 : {}),
1220 reason: why,
1221 ...(usage ? { usage } : {}),
1222 ...(error ? { error } : {}),
1223 })
1224
1225 compactedViews.set(ctx, true)
1226 return info.after
1227 }
1228
1229 /**
1230 * Apply the ready background summary of the thread, or drop it when it
1231 * no longer fits: a newer compaction cut past its kept message, or,
1232 * without a kept id, the messages before the cut changed. Returns the
1233 * new list, or `undefined`.
1234 */
1235 const applyReady = async () => {
1236 const readyStore = backgroundStore(ctx)
1237 const ready = await readyStore.get(BACKGROUND_NAMESPACE, ctx.threadId)
1238 if (!isBackgroundReady(ready)) return undefined
1239 await readyStore.delete(BACKGROUND_NAMESPACE, ctx.threadId)
1240 const { record, prefixHash } = ready
1241 // Without a kept id, the messages before the cut must be the ones
1242 // that the summary read.
1243 const fits =
1244 record.firstKeptId !== undefined ||
1245 (record.from <= workingMessages.length &&
1246 (await hashMessages(workingMessages.slice(0, record.from))) ===
1247 prefixHash)
1248 const next = fits
1249 ? projectCompaction({ messages: workingMessages, record })
1250 : undefined
1251 if (next) {
1252 await commit(
1253 workingMessages,
1254 next,
1255 before,
1256 'background',
1257 record.usage,
1258 )
1259 return next
1260 }
1261 const usageField = record.usage ? { usage: record.usage } : {}
1262 options.onCompact?.({
1263 before,
1264 after: before,
1265 messagesBefore: workingMessages.length,
1266 messagesAfter: workingMessages.length,
1267 reason: 'background',
1268 stale: true,
1269 ...usageField,
1270 })
1271 emitCompactionEnded(ctx, {
1272 after: before,
1273 messagesAfter: workingMessages.length,
1274 reusedCheckpoint,
1275 maxTokens: options.maxTokens,
1276 durationMs: Date.now() - startedAt,
1277 ...(checkpointStrategyKey
1278 ? { strategyKey: checkpointStrategyKey }
1279 : {}),
1280 reason: 'background',
1281 stale: true,
1282 ...usageField,
1283 })
1284 return undefined
1285 }
1286
1287 // Set when a background summary was applied at this call.
1288 let applied = false
1289 if (background) {
1290 // ponytail: the run of the last call of each thread, in the memory
1291 // store (its newest 1000 threads). A forgotten thread counts as a
1292 // first call.
1293 const firstCall =
1294 (await memory.get(RUN_NAMESPACE, ctx.threadId)) !== ctx.runId
1295 if (firstCall) await memory.set(RUN_NAMESPACE, ctx.threadId, ctx.runId)
1296 // Over maxTokens while a summary runs: wait for it and apply it, so
1297 // the summary runs once, not twice. The run's signal stops the wait.
1298 const running =
1299 !force && auto && before > options.maxTokens
1300 ? jobs.get(ctx.threadId)
1301 : undefined
1302 if (running) await abortable(running, ctx.signal)
1303 // A ready summary applies at the first model call of a run, and
1304 // after the wait. Never in the middle of a run otherwise.
1305 const checked = firstCall || running !== undefined
1306 if (checked) {
1307 const next = await applyReady()
1308 if (next) {
1309 workingMessages = next
1310 before = sum(next, estimate)
1311 applied = true
1312 }
1313 }
1314 if (
1315 !force &&
1316 auto &&
1317 before > background.atTokens &&
1318 before <= options.maxTokens &&
1319 !jobs.has(ctx.threadId) &&
1320 // A checked call took the ready summary already.
1321 (checked ||
1322 !isBackgroundReady(
1323 await backgroundStore(ctx).get(
1324 BACKGROUND_NAMESPACE,
1325 ctx.threadId,
1326 ),
1327 ))
1328 ) {
1329 // The model call goes on at once, with the messages as they are.
1330 startBackground(
1331 ctx,
1332 config,
1333 [...workingMessages],
1334 before,
1335 reusedCheckpoint,
1336 )
1337 }
1338 }
1339 const startedValue: CompactionStartedEventValue = {
1340 before,
1341 messagesBefore: workingMessages.length,
1342 reusedCheckpoint,
1343 maxTokens: options.maxTokens,
1344 ...(checkpointStrategyKey
1345 ? { strategyKey: checkpointStrategyKey }
1346 : {}),
1347 reason,
1348 }
1349
1350 if (!force && (!auto || before <= options.maxTokens)) {
1351 // A background summary was applied above, and its events went out.
1352 if (applied) return { providerMessages: workingMessages }
1353 if (reusedCheckpoint) {
1354 emitCompactionStarted(ctx, startedValue)
1355 const stateValue = compactionStateValue({
1356 before,
1357 after: before,
1358 messagesBefore: workingMessages.length,
1359 messagesAfter: workingMessages.length,
1360 reusedCheckpoint: true,
1361 maxTokens: options.maxTokens,
1362 strategyKey: checkpointStrategyKey,
1363 afterMessages: workingMessages,
1364 estimate,
1365 })
1366 emitCompactionState(ctx, stateValue)
1367 emitCompactionEnded(ctx, {
1368 after: before,
1369 messagesAfter: workingMessages.length,
1370 reusedCheckpoint: true,
1371 maxTokens: options.maxTokens,
1372 durationMs: Date.now() - startedAt,
1373 ...(checkpointStrategyKey
1374 ? { strategyKey: checkpointStrategyKey }
1375 : {}),
1376 reason,
1377 })
1378 return { providerMessages: workingMessages }
1379 }
1380 return
1381 }
1382
1383 emitCompactionStarted(ctx, startedValue)
1384 // An object, so the closure below can write it and TypeScript reads it.
1385 const spent: { usage?: TokenUsage; error?: { message: string } } = {}
1386 let next: Array<ModelMessage> | null
1387 try {
1388 next = await strategyOf(
1389 ctx,
1390 spent,
1391 config,
1392 )(workingMessages, {
1393 maxTokens: options.maxTokens,
1394 estimate,
1395 signal: ctx.signal,
1396 threadId: ctx.threadId,
1397 addUsage: (usage) => {
1398 spent.usage = sumUsage(spent.usage, usage)
1399 },
1400 })
1401 } catch (error) {
1402 emitCompactionEnded(ctx, {
1403 after: before,
1404 messagesAfter: workingMessages.length,
1405 reusedCheckpoint,
1406 maxTokens: options.maxTokens,
1407 durationMs: Date.now() - startedAt,
1408 ...(checkpointStrategyKey
1409 ? { strategyKey: checkpointStrategyKey }
1410 : {}),
1411 reason,
1412 ...(spent.usage ? { usage: spent.usage } : {}),
1413 error: {
1414 message: error instanceof Error ? error.message : String(error),
1415 },
1416 })
1417 // An aborted run must stop. Do not call the adapter with its signal.
1418 if (!options.continueOnError || ctx.signal?.aborted) throw error
1419 // A reused checkpoint or an applied summary still goes to the model.
1420 return reusedCheckpoint || applied
1421 ? { providerMessages: workingMessages }
1422 : undefined
1423 }
1424 if (!next || next === workingMessages) {
1425 emitCompactionEnded(ctx, {
1426 after: before,
1427 messagesAfter: workingMessages.length,
1428 reusedCheckpoint,
1429 maxTokens: options.maxTokens,
1430 durationMs: Date.now() - startedAt,
1431 ...(checkpointStrategyKey
1432 ? { strategyKey: checkpointStrategyKey }
1433 : {}),
1434 reason,
1435 ...(spent.usage ? { usage: spent.usage } : {}),
1436 ...(spent.error ? { error: spent.error } : {}),
1437 })
1438 if (reusedCheckpoint || applied) {
1439 return { providerMessages: workingMessages }
1440 }
1441 return
1442 }
1443
1444 await commit(
1445 workingMessages,
1446 next,
1447 before,
1448 reason,
1449 spent.usage,
1450 spent.error,
1451 )
1452 return { providerMessages: next }
1453 },
1454 onUsage: countUsage
1455 ? async (ctx, usage) => {
1456 const saved = await toUsageCount(
1457 ctx.messages,
1458 usage,
1459 compactedViews.get(ctx) ?? false,
1460 )
1461 // A cancelled call keeps the last good usage.
1462 if (!saved || ctx.signal?.aborted) return
1463 await storeOf(ctx)?.set(USAGE_NAMESPACE, ctx.threadId, saved)
1464 }
1465 : undefined,
1466 // Only a durable run checks after the turn (orchestrator decision).
1467 onFinish:
1468 countUsage && options.durable ? (ctx) => afterTurn(ctx) : undefined,
1469 }
1470}