Open History to see the last commit
1/**
2 * Resumable run event-log — the primitive that lets a trigger (e.g. a
3 * Cloudflare Worker) start an agent run and return immediately while a durable
4 * orchestrator (e.g. a Durable Object) drives the run and persists every
5 * emitted {@link StreamChunk} under a monotonic `seq`.
6 *
7 * Clients tail the log from a cursor (`fromSeq`), so a dropped connection, a new
8 * browser tab, or an orchestrator that hibernated between chunks all reconnect
9 * cleanly: replay everything after the client's last-seen `seq`, then live-tail
10 * until the run reaches a terminal status. The *run* never depends on any single
11 * connection staying open — that is what makes the serverless/edge model work.
12 *
13 * This module is transport- and storage-agnostic. {@link InMemoryRunEventLog} is
14 * the default (single-process / tests); a durable backend (DO storage, KV, SQL)
15 * implements the same {@link RunEventLog} interface — see
16 * {@link DurableObjectRunEventLog} in `./run-log-do`.
17 *
18 * Run statuses, `RunError`, and the record's lifecycle fields come from
19 * `@tanstack/ai`. {@link RunLogRecord} is core's {@link RunRecord} plus the two
20 * fields only an event log needs: the `lastSeq` cursor and the `updatedAt`
21 * activity clock.
22 */
23import { isTerminalRunStatus } from '@tanstack/ai'
24import type {
25 RunError,
26 RunRecord,
27 RunStore,
28 StreamChunk,
29 TerminalRunStatus,
30} from '@tanstack/ai'
31
32/**
33 * The mutable-field patch a {@link RunStore.update} accepts, reused verbatim so
34 * the log can back a `RunStore` without restating (and drifting from) the pick.
35 */
36export type RunRecordPatch = Parameters<RunStore['update']>[1]
37
38/**
39 * Durable bookkeeping for one run in the event log: core's {@link RunRecord}
40 * plus the two fields only an event log needs.
41 */
42export interface RunLogRecord extends RunRecord {
43 /** Seq of the last appended event, or `-1` when no events yet. */
44 lastSeq: number
45 /**
46 * Epoch ms of the last append or status change — the activity clock a stall
47 * watchdog reads. Distinct from `finishedAt`, which is set once, at terminal.
48 */
49 updatedAt: number
50}
51
52/** One persisted event: a chunk plus its monotonic, gap-free sequence number. */
53export interface RunEvent {
54 seq: number
55 chunk: StreamChunk
56}
57
58export interface RunEventLogReadOptions {
59 /**
60 * Exclusive cursor: only events with `seq > fromSeq` are yielded. Pass the
61 * client's last-seen `seq` to resume; omit (or `-1`) to replay from the start.
62 */
63 fromSeq?: number
64 /** Stop tailing when this fires (e.g. the client disconnected). */
65 signal?: AbortSignal
66}
67
68/**
69 * Append-only, `seq`-indexed log of a run's stream, with resumable reads.
70 *
71 * Contract:
72 * - `append` assigns the next `seq` (0, 1, 2, …) and returns it.
73 * - `read` yields the backlog after `fromSeq` in order, then live-tails new
74 * events, and RETURNS once the run is terminal and the cursor has caught up.
75 * - Unknown-run behavior is method-specific: `append`/`finish`/`read` reject,
76 * `get` resolves null, and `update` is a no-op.
77 */
78export interface RunEventLog {
79 /**
80 * Idempotently create (or return) the run record. An existing record is
81 * returned unchanged; `startedAt` (default `Date.now()`) applies only on
82 * first creation — matching core's `RunStore.createOrResume` invariant, which
83 * `runLogStore` maps directly onto this method.
84 */
85 open: (input: {
86 runId: string
87 threadId: string
88 startedAt?: number
89 }) => Promise<RunLogRecord>
90 /** Append one chunk; resolves with its assigned `seq`. */
91 append: (runId: string, chunk: StreamChunk) => Promise<number>
92 /** Move the run to a terminal status. Idempotent for the same status. */
93 finish: (
94 runId: string,
95 status: TerminalRunStatus,
96 error?: RunError,
97 ) => Promise<void>
98 /**
99 * Patch the record's mutable fields ({@link RunRecordPatch}). Unknown and
100 * already-terminal runs are NO-OPs (never a throw, never a create), preserving
101 * the first terminal status against late driver updates.
102 *
103 * MUST wake blocked readers, exactly like `append`/`finish`: the record and
104 * the event log share one status field here, so a driver that terminalizes
105 * through its `RunStore` — core's `pipeToRunLog` writes its terminal status
106 * via `runs.update`, not `finish` — is ending the log with this call.
107 */
108 update: (runId: string, patch: RunRecordPatch) => Promise<void>
109 /** Current record, or null if the run is unknown. */
110 get: (runId: string) => Promise<RunLogRecord | null>
111 /** Every run record this log holds. Backs `RunStore.findActiveRun`. */
112 list: () => Promise<Array<RunLogRecord>>
113 /** Replay-then-tail events with `seq > fromSeq` until the run is terminal. */
114 read: (
115 runId: string,
116 options?: RunEventLogReadOptions,
117 ) => AsyncIterable<RunEvent>
118}
119
120/** Per-run state for the in-memory log. */
121interface RunState {
122 record: RunLogRecord
123 chunks: Array<StreamChunk>
124 /** Resolved (and cleared) whenever an event is appended or status changes. */
125 waiters: Set<() => void>
126}
127
128/**
129 * Single-process {@link RunEventLog}. Backs `read`'s live-tail with an internal
130 * waiter set: `append`/`finish` wake every blocked reader. Suitable for a
131 * long-running Node host, tests, and as the reference implementation a durable
132 * backend mirrors.
133 */
134export class InMemoryRunEventLog implements RunEventLog {
135 private readonly runs = new Map<string, RunState>()
136
137 private now(): number {
138 return Date.now()
139 }
140
141 private require(runId: string): RunState {
142 const state = this.runs.get(runId)
143 if (!state) throw new Error(`run-log: unknown runId "${runId}"`)
144 return state
145 }
146
147 private wake(state: RunState): void {
148 const waiters = [...state.waiters]
149 state.waiters.clear()
150 for (const resolve of waiters) resolve()
151 }
152
153 // Mutators return a Promise without `async` so contract violations REJECT
154 // (rather than throwing synchronously from a Promise-typed method — a
155 // `.catch()` footgun) without an `await`-less async body.
156 open(input: {
157 runId: string
158 threadId: string
159 startedAt?: number
160 }): Promise<RunLogRecord> {
161 const existing = this.runs.get(input.runId)
162 if (existing) return Promise.resolve({ ...existing.record })
163 const now = this.now()
164 const record: RunLogRecord = {
165 runId: input.runId,
166 threadId: input.threadId,
167 status: 'running',
168 lastSeq: -1,
169 startedAt: input.startedAt ?? now,
170 updatedAt: now,
171 }
172 this.runs.set(input.runId, { record, chunks: [], waiters: new Set() })
173 return Promise.resolve({ ...record })
174 }
175
176 append(runId: string, chunk: StreamChunk): Promise<number> {
177 const state = this.runs.get(runId)
178 if (!state) {
179 return Promise.reject(new Error(`run-log: unknown runId "${runId}"`))
180 }
181 if (isTerminalRunStatus(state.record.status)) {
182 return Promise.reject(
183 new Error(
184 `run-log: cannot append to terminal run "${runId}" (status=${state.record.status})`,
185 ),
186 )
187 }
188 // Derive seq from the record's cursor (not `chunks.length`) so the gap-free
189 // invariant holds the same way the durable backend computes it, even if the
190 // backlog is ever trimmed/compacted.
191 const seq = state.record.lastSeq + 1
192 state.chunks.push(chunk)
193 state.record.lastSeq = seq
194 state.record.updatedAt = this.now()
195 this.wake(state)
196 return Promise.resolve(seq)
197 }
198
199 finish(
200 runId: string,
201 status: TerminalRunStatus,
202 error?: RunError,
203 ): Promise<void> {
204 const state = this.runs.get(runId)
205 if (!state) {
206 return Promise.reject(new Error(`run-log: unknown runId "${runId}"`))
207 }
208 if (isTerminalRunStatus(state.record.status)) return Promise.resolve()
209 const now = this.now()
210 state.record.status = status
211 if (error !== undefined) state.record.error = error
212 state.record.finishedAt = now
213 state.record.updatedAt = now
214 this.wake(state)
215 return Promise.resolve()
216 }
217
218 touch(runId: string): Promise<void> {
219 const state = this.runs.get(runId)
220 if (!state || isTerminalRunStatus(state.record.status)) {
221 return Promise.resolve()
222 }
223 state.record.updatedAt = this.now()
224 return Promise.resolve()
225 }
226
227 finishIfStale(
228 runId: string,
229 cutoff: number,
230 chunk: Extract<StreamChunk, { type: 'RUN_ERROR' }>,
231 ): Promise<boolean> {
232 const state = this.runs.get(runId)
233 if (
234 !state ||
235 isTerminalRunStatus(state.record.status) ||
236 state.record.updatedAt >= cutoff
237 ) {
238 return Promise.resolve(false)
239 }
240
241 const now = this.now()
242 const seq = state.record.lastSeq + 1
243 state.chunks.push(chunk)
244 state.record.lastSeq = seq
245 state.record.status = 'failed'
246 state.record.error = {
247 message: chunk.message,
248 ...(chunk.code !== undefined ? { code: chunk.code } : {}),
249 }
250 state.record.finishedAt = now
251 state.record.updatedAt = now
252 this.wake(state)
253 return Promise.resolve(true)
254 }
255
256 update(runId: string, patch: RunRecordPatch): Promise<void> {
257 const state = this.runs.get(runId)
258 if (!state || isTerminalRunStatus(state.record.status)) {
259 return Promise.resolve()
260 }
261 state.record = { ...state.record, ...patch, updatedAt: this.now() }
262 // A patch may terminalize the shared status field (core's driver writes its
263 // terminal status through `RunStore.update`) — parked readers must see it.
264 this.wake(state)
265 return Promise.resolve()
266 }
267
268 get(runId: string): Promise<RunLogRecord | null> {
269 const state = this.runs.get(runId)
270 return Promise.resolve(state ? { ...state.record } : null)
271 }
272
273 list(): Promise<Array<RunLogRecord>> {
274 return Promise.resolve(
275 [...this.runs.values()].map((state) => ({ ...state.record })),
276 )
277 }
278
279 async *read(
280 runId: string,
281 options?: RunEventLogReadOptions,
282 ): AsyncIterable<RunEvent> {
283 const state = this.require(runId)
284 const signal = options?.signal
285 let cursor = options?.fromSeq ?? -1
286 while (!signal?.aborted) {
287 while (cursor < state.record.lastSeq) {
288 cursor += 1
289 const chunk = state.chunks[cursor]
290 if (chunk !== undefined) yield { seq: cursor, chunk }
291 }
292 if (isTerminalRunStatus(state.record.status)) return
293 await this.waitForChange(state, signal)
294 }
295 }
296
297 private waitForChange(state: RunState, signal?: AbortSignal): Promise<void> {
298 return new Promise<void>((resolve) => {
299 const wake = (): void => {
300 state.waiters.delete(wake)
301 if (signal) signal.removeEventListener('abort', wake)
302 resolve()
303 }
304 state.waiters.add(wake)
305 if (signal) signal.addEventListener('abort', wake, { once: true })
306 })
307 }
308}