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

log-stores.ts

173 lines5.9 KB

1import type {
2 InterruptCommitEntry,
3 InterruptRecord,
4 InterruptStore,
5 RunRecord,
6 RunStore,
7} from '@tanstack/ai-persistence'
8import type { LogWriter } from './log'
9import type { ClearableRunField, RunPatch } from './log-records'
10​
11/** What the stores need of a session's view of its log. */
12type LogView = Pick<LogWriter, 'state' | 'append'>
13​
14// The fields that a `RunStore.update` can remove, with `undefined`. A record
15// keyed by the union: a new field of `update` is a compile error here.
16const CLEARABLE: Record<ClearableRunField, true> = {
17 finishedAt: true,
18 error: true,
19 usage: true,
20 sandboxKey: true,
21 detachedSince: true,
22 cancelRequested: true,
23 driverEpoch: true,
24 result: true,
25 artifacts: true,
26 leaseOwner: true,
27 leaseExpiresAt: true,
28 checkpoint: true,
30​
31const isClearable = (field: string): field is ClearableRunField =>
32 Object.hasOwn(CLEARABLE, field)
33​
34/** The fields that `patch` sets to `undefined`, so the change removes them. */
35function clearedFields(patch: RunPatch) {
36 return Object.keys(patch)
37 .filter(isClearable)
38 .filter((field) => patch[field] === undefined)
40​
41const byStartedAt = (a: RunRecord, b: RunRecord) => a.startedAt - b.startedAt
42const byRequestedAt = (a: InterruptRecord, b: InterruptRecord) =>
43 a.requestedAt - b.requestedAt
44​
45/**
46 * The newest run of `threadId` that is `'running'`, or `null`. "Newest" is
47 * the greatest `startedAt`, as `RunStore.findActiveRun` says.
48 */
49export function activeRunIn(
50 runs: ReadonlyMap<string, RunRecord>,
51 threadId: string,
52) {
53 let active: RunRecord | null = null
54 for (const run of runs.values()) {
55 if (run.threadId !== threadId || run.status !== 'running') continue
56 if (active === null || run.startedAt > active.startedAt) active = run
57 }
58 return active
60​
61/**
62 * The `RunStore` and the `InterruptStore` of a session, on its log. Core
63 * `withPersistence` and the checkpoints take them. Each write is a log
64 * record that the session's writer appends, with its ownership epoch. Each
65 * read comes from the fold of the session, so a new host that folds the log
66 * has every run and interrupt, with no other store.
67 *
68 * The records keep the thread id of the app. The log id has the tenant
69 * already, so one run id in two tenants is two runs.
70 *
71 * @example
72 * ```ts
73 * const { runs, interrupts } = logChatStores(writer)
74 * withPersistence({ stores: { messages, runs, interrupts } })
75 * ```
76 */
77export function logChatStores(writer: LogView) {
78 const runsOf = () => writer.state.thread.runs
79 const interruptsOf = () => writer.state.thread.interrupts
80 const listRuns = (keep: (run: RunRecord) => boolean) =>
81 Promise.resolve([...runsOf().values()].filter(keep).sort(byStartedAt))
82 const listInterrupts = (keep: (record: InterruptRecord) => boolean) =>
83 Promise.resolve(
84 [...interruptsOf().values()].filter(keep).sort(byRequestedAt),
85 )
86​
87 const runs: RunStore = {
88 createOrResume: async (input) => {
89 const known = runsOf().get(input.runId)
90 if (known) return known
91 const { status, ...fields } = input
92 const run: RunRecord = { ...fields, status: status ?? 'running' }
93 await writer.append([{ type: 'harness.run', run }])
94 // A closed view writes nothing, so the fold can be without it.
95 return runsOf().get(input.runId) ?? run
96 },
97 update: async (runId, patch) => {
98 if (!runsOf().has(runId)) return
99 const unset = clearedFields(patch)
100 await writer.append([
101 {
102 type: 'harness.run.update',
103 runId,
104 patch,
105 ...(unset.length > 0 ? { unset } : {}),
106 },
107 ])
108 },
109 get: (runId) => Promise.resolve(runsOf().get(runId) ?? null),
110 findActiveRun: (threadId) =>
111 Promise.resolve(activeRunIn(runsOf(), threadId)),
112 listByThread: (threadId) => listRuns((run) => run.threadId === threadId),
113 listByParentRun: (parentRunId) =>
114 listRuns((run) => run.parentRunId === parentRunId),
115 }
116​
117 /** Append the ends of known interrupts. An unknown id writes nothing. */
118 const end = async (entries: ReadonlyArray<InterruptCommitEntry>) => {
119 const at = Date.now()
120 const known = entries.filter((entry) =>
121 interruptsOf().has(entry.interruptId),
122 )
123 if (known.length === 0) return
124 await writer.append(
125 known.map((entry) => ({
126 type: 'harness.interrupt.end',
127 at,
128 ...entry,
129 })),
130 )
131 }
132​
133 const interrupts: InterruptStore = {
134 create: async (record) => {
135 if (interruptsOf().has(record.interruptId)) return
136 await writer.append([{ type: 'harness.interrupt', interrupt: record }])
137 },
138 resolve: (interruptId, response) =>
139 end([{ interruptId, status: 'resolved', response }]),
140 cancel: (interruptId) => end([{ interruptId, status: 'cancelled' }]),
141 // One append, so every entry lands or none does.
142 commitBatch: async (entries) => {
143 const seen = new Set<string>()
144 for (const { interruptId } of entries) {
145 if (seen.has(interruptId)) {
146 throw new Error(`Interrupt batch has the id ${interruptId} twice.`)
147 }
148 seen.add(interruptId)
149 const status = interruptsOf().get(interruptId)?.status
150 if (status !== 'pending') {
151 throw new Error(
152 `Interrupt batch names ${interruptId}, which is ${status ?? 'not known'}, not pending.`,
153 )
154 }
155 }
156 await end(entries)
157 },
158 get: (interruptId) =>
159 Promise.resolve(interruptsOf().get(interruptId) ?? null),
160 list: (threadId) =>
161 listInterrupts((record) => record.threadId === threadId),
162 listPending: (threadId) =>
163 listInterrupts(
164 (record) => record.threadId === threadId && record.status === 'pending',
165 ),
166 listByRun: (runId) => listInterrupts((record) => record.runId === runId),
167 listPendingByRun: (runId) =>
168 listInterrupts(
169 (record) => record.runId === runId && record.status === 'pending',
170 ),
171 }
172 return { runs, interrupts }