Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

index.ts

1,461 lines50.9 KB

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