Open History to see the last commit
1import type { ModelMessage, TokenUsage } from '@tanstack/ai'
2import type { CompactionReason } from './index'
3
4/** The log record type of a durable compaction. */
5export const COMPACTION_RECORD_TYPE = 'tanstack.compaction'
6
7/**
8 * One durable compaction, as a host log record. Fold it into the model
9 * context with {@link projectCompaction}. It is a type, not an interface, so
10 * it fits the record shape of `LogRecordsWriter.append`.
11 */
12export type CompactionRecord = {
13 type: typeof COMPACTION_RECORD_TYPE
14 reason: CompactionReason
15 tokensBefore: number
16 tokensAfter: number
17 usage?: TokenUsage
18 /** The messages before `from` were replaced by `head`. */
19 head: Array<ModelMessage>
20 from: number
21 /** The id of the first kept message, when it has one. Checked before `from`. */
22 firstKeptId?: string
23}
24
25const sameMessage = (a: ModelMessage, b: ModelMessage) =>
26 a === b || JSON.stringify(a) === JSON.stringify(b)
27
28/**
29 * The record of a compaction from `before` to `after`: the new head, and the
30 * index in `before` where the kept tail starts. When `after` does not end with
31 * the tail of `before`, the head is all of `after`, and `from` is the end of
32 * `before`.
33 */
34export function compactionRecord(input: {
35 reason: CompactionReason
36 before: ReadonlyArray<ModelMessage>
37 after: Array<ModelMessage>
38 tokensBefore: number
39 tokensAfter: number
40 usage?: TokenUsage
41}): CompactionRecord {
42 const { before, after } = input
43 let kept = 0
44 for (;;) {
45 const old = before[before.length - 1 - kept]
46 const next = after[after.length - 1 - kept]
47 if (!old || !next || !sameMessage(old, next)) break
48 kept += 1
49 }
50 // A full rewrite keeps no tail: the head is all of `after`, and `from` is
51 // the end of `before`. A fold that does not have all of `before` yet (the
52 // results of a tool phase that are not saved) then skips the record.
53 const from = before.length - kept
54 const firstKeptId = before[from]?.id
55 return {
56 type: COMPACTION_RECORD_TYPE,
57 reason: input.reason,
58 tokensBefore: input.tokensBefore,
59 tokensAfter: input.tokensAfter,
60 ...(input.usage ? { usage: input.usage } : {}),
61 head: after.slice(0, after.length - kept),
62 from,
63 ...(firstKeptId ? { firstKeptId } : {}),
64 }
65}
66
67// The log is folded again on each open, so a bad record must not throw.
68const isMessageList = (value: unknown): value is Array<ModelMessage> =>
69 Array.isArray(value) &&
70 value.every(
71 (item: unknown) =>
72 typeof item === 'object' &&
73 item !== null &&
74 'role' in item &&
75 typeof item.role === 'string',
76 )
77
78/**
79 * Fold a compaction record into the model context. A host that rebuilds the
80 * context from its session log calls it for each record. Returns `undefined`
81 * for a record of another type, and for a record that this fold cannot use.
82 * Pure: the same log always folds to the same context.
83 */
84export function projectCompaction(input: {
85 messages: ReadonlyArray<ModelMessage>
86 record: { type: string; [key: string]: unknown }
87}): Array<ModelMessage> | undefined {
88 const { messages, record } = input
89 if (record.type !== COMPACTION_RECORD_TYPE) return undefined
90 const head = record.head
91 if (!isMessageList(head)) return undefined
92 const start =
93 typeof record.firstKeptId === 'string'
94 ? messages.findIndex((message) => message.id === record.firstKeptId)
95 : record.from
96 // The record counted messages that this fold does not have yet (a kept id
97 // that is not here, or a `from` past the end), or it is malformed. Skip it:
98 // the next check compacts again. A slice here would repeat those messages.
99 if (
100 typeof start !== 'number' ||
101 !Number.isInteger(start) ||
102 start < 0 ||
103 start > messages.length
104 ) {
105 return undefined
106 }
107 return [...head, ...messages.slice(start)]
108}