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

feed.ts

336 lines10.3 KB

1import { EventType } from '@tanstack/ai'
2import { isMediaRecord } from './media-ref'
3import { HARNESS_EVENTS } from './types'
4import { isRecord } from './utils'
5import type { StreamChunk } from '@tanstack/ai'
6import type {
7 AuthRequest,
8 Cursor,
9 EventGap,
10 LiveEvent,
11 MediaRecord,
12 OnEvent,
13 PendingQuestion,
14 SessionEvent,
15 StreamChunkType,
16 UsageUpdate,
17} from './types'
18​
19/**
20 * The ordered event stream of one session. Every operation publishes here.
21 * A session uses a feed that keeps the events in the session log. Before its
22 * log opens, it has a {@link SessionFeed} in memory.
23 */
24export interface EventFeed {
25 publish: (operationId: string, event: StreamChunk) => void
26 /** The cursor of the newest event, or `'0'` for an empty feed. */
27 head: () => Cursor
28 /**
29 * Events after `from` (exclusive), then live events until `signal` aborts
30 * or the feed closes. Pass a `filter` to read one operation's events.
31 */
32 read: (options: {
33 from?: Cursor
34 signal?: AbortSignal
35 filter?: (entry: SessionEvent) => boolean
36 /** Stop after `until()` returns true and no buffered event is left. */
37 until?: () => boolean
38 }) => AsyncIterable<SessionEvent>
39 close: () => void
40 /** Let every waiting reader check `until` again, when nothing was published. */
41 wake: () => void
43​
44/** A listener of the events a session publishes. */
45export type EventListener = (entry: LiveEvent) => void
46​
47/** An {@link EventFeed} that also calls listeners after each publish. */
48export interface ListenedFeed extends EventFeed {
49 /** Add `listener`. Returns a function that removes it. */
50 listen: (listener: EventListener) => () => void
52​
53/**
54 * The `onEvent` of a session, or of one operation when `operationId` is set.
55 * `listen` adds a listener to the feed.
56 */
57export function onEventOf(
58 listen: (listener: EventListener) => () => void,
59 operationId?: string,
60): OnEvent {
61 function onEvent(listener: EventListener): () => void
62 function onEvent(
63 type: StreamChunkType,
64 listener: (entry: LiveEvent<never>) => void,
65 ): () => void
66 function onEvent(
67 typeOrListener: StreamChunkType | EventListener,
68 typed?: (entry: LiveEvent<never>) => void,
69 ): () => void {
70 const type = typeof typeOrListener === 'string' ? typeOrListener : null
71 const listener = typeof typeOrListener === 'string' ? typed : typeOrListener
72 if (typeof listener !== 'function') {
73 throw new TypeError('onEvent needs a listener function.')
74 }
75 return listen((entry) => {
76 if (operationId !== undefined && entry.operationId !== operationId) {
77 return
78 }
79 // A typed listener gets only events of its type. The result goes back,
80 // so the feed can catch a promise that rejects.
81 if (type === null || entry.event.type === type) {
82 return (listener as EventListener)(entry)
83 }
84 })
85 }
86 return onEvent
88​
89/** A listener of one kind of harness event. Returns a function that stops it. */
90export type OnHarnessEvent<TEntry> = (
91 listener: (entry: TEntry & { operationId: string }) => void,
92) => () => void
93​
94/**
95 * Listen to the `CUSTOM` events named `name`. `read` turns the event value
96 * into the listener entry, or returns `undefined` to skip a bad value.
97 */
98function onCustomOf<TEntry>(
99 onEvent: OnEvent,
100 name: string,
101 read: (value: unknown) => TEntry | undefined,
102): OnHarnessEvent<TEntry> {
103 return (listener) =>
104 onEvent(EventType.CUSTOM, ({ operationId, event }) => {
105 if (event.name !== name) return
106 const entry = read(event.value)
107 // The result goes back, so the feed can catch a promise that rejects.
108 if (entry !== undefined) return listener({ ...entry, operationId })
109 })
111​
112/** The `onMedia` of a session or an operation: its `harness.media` events. */
113export function onMediaOf(
114 onEvent: OnEvent,
115): OnHarnessEvent<{ media: MediaRecord }> {
116 return onCustomOf(onEvent, HARNESS_EVENTS.media, (value) =>
117 isMediaRecord(value) ? { media: value } : undefined,
118 )
120​
121/** The `onQuestion` of a session: its `harness.question` events. */
122export function onQuestionOf(
123 onEvent: OnEvent,
124): OnHarnessEvent<{ question: PendingQuestion }> {
125 return onCustomOf(onEvent, HARNESS_EVENTS.question, (value) =>
126 isPendingQuestion(value) ? { question: value } : undefined,
127 )
129​
130/** The `onAuthRequired` of a session: its `harness.auth_required` events. */
131export function onAuthRequiredOf(
132 onEvent: OnEvent,
133): OnHarnessEvent<AuthRequest> {
134 return onCustomOf(onEvent, HARNESS_EVENTS.authRequired, (value) =>
135 isAuthRequest(value) ? value : undefined,
136 )
138​
139/** The `onUsage` of a session: its `harness.usage` events. */
140export function onUsageOf(onEvent: OnEvent): OnHarnessEvent<UsageUpdate> {
141 return onCustomOf(onEvent, HARNESS_EVENTS.usage, (value) =>
142 isUsageUpdate(value) ? value : undefined,
143 )
145​
146function isPendingQuestion(value: unknown): value is PendingQuestion {
147 return (
148 isRecord(value) &&
149 typeof value.questionId === 'string' &&
150 typeof value.message === 'string'
151 )
153​
154function isAuthRequest(value: unknown): value is AuthRequest {
155 return isRecord(value) && typeof value.connector === 'string'
157​
158function isUsageUpdate(value: unknown): value is UsageUpdate {
159 return (
160 isRecord(value) &&
161 typeof value.model === 'string' &&
162 isRecord(value.usage) &&
163 isRecord(value.total)
164 )
166​
167/**
168 * The in-memory {@link EventFeed}. Cursors are opaque to callers and increase
169 * with each event.
170 */
171// ponytail: it keeps the newest `eventBytes` of events (the JSON length of
172// each). A reader whose cursor fell out of them gets a `harness.gap` event,
173// then resumes from the oldest kept event. Durable cross-process delivery
174// goes through StreamDurability in the protocol layer.
175export class SessionFeed implements EventFeed {
176 /** The kept events. Their cursors are consecutive numbers. */
177 private readonly entries: Array<SessionEvent> = []
178 /** The JSON length of each event in `entries`, in the same order. */
179 private readonly sizes: Array<number> = []
180 /** The sum of `sizes`. */
181 private bytes = 0
182 private readonly eventBytes: number
183 private readonly threadId: string
184 private sequence = 0
185 private readonly waiters = new Set<() => void>()
186 private closed = false
187​
188 /**
189 * `threadId`: the thread of the session. `eventBytes`: how many bytes of
190 * events to keep.
191 */
192 constructor(options: { threadId: string; eventBytes: number }) {
193 this.threadId = options.threadId
194 this.eventBytes = options.eventBytes
195 }
196​
197 publish(operationId: string, event: StreamChunk): void {
198 this.sequence += 1
199 const size = jsonLength(event)
200 this.entries.push({
201 cursor: String(this.sequence),
202 threadId: this.threadId,
203 operationId,
204 event,
205 })
206 this.sizes.push(size)
207 this.bytes += size
208 // The newest event stays, so a live reader still gets it.
209 while (this.bytes > this.eventBytes && this.entries.length > 1) {
210 this.entries.shift()
211 this.bytes -= this.sizes.shift() ?? 0
212 }
213 this.wake()
214 }
215​
216 head(): Cursor {
217 return String(this.sequence)
218 }
219​
220 /** The kept events after the cursor `after` that `filter` accepts. */
221 private after(
222 after: number,
223 filter: ((entry: SessionEvent) => boolean) | undefined,
224 ) {
225 const first = this.sequence - this.entries.length + 1
226 return this.entries
227 .slice(Math.max(0, after + 1 - first))
228 .filter((entry) => (filter ? filter(entry) : true))
229 }
230​
231 async *read(options: {
232 from?: Cursor
233 signal?: AbortSignal
234 filter?: (entry: SessionEvent) => boolean
235 /** Stop after `until()` returns true and no buffered event is left. */
236 until?: () => boolean
237 }): AsyncIterable<SessionEvent> {
238 let after = Number(options.from ?? '0')
239 if (!Number.isFinite(after)) after = 0
240 while (true) {
241 if (options.signal?.aborted) return
242 // The feed dropped events after `after`: say so once, then go on from
243 // the oldest kept event.
244 const oldest = this.sequence - this.entries.length + 1
245 if (this.entries.length > 0 && after < oldest - 1) {
246 yield gapEvent(
247 this.threadId,
248 String(after),
249 String(oldest - 1),
250 'evicted',
251 )
252 after = oldest - 1
253 }
254 const next = this.after(after, options.filter)
255 for (const entry of next) {
256 if (options.signal?.aborted) return
257 after = Number(entry.cursor)
258 yield entry
259 }
260 if (next.length === 0) {
261 // Skip past events the filter rejected, so they are not scanned again.
262 after = Math.max(after, this.sequence)
263 }
264 if (this.closed || options.until?.()) {
265 for (const entry of this.after(after, options.filter)) yield entry
266 return
267 }
268 // Events published while the reader handled `next` woke nobody, so
269 // scan again before waiting. An empty scan moves `after` to the head.
270 if (next.length > 0) continue
271 await this.waitForNext(options.signal)
272 }
273 }
274​
275 close(): void {
276 this.closed = true
277 this.wake()
278 }
279​
280 wake(): void {
281 const waiters = [...this.waiters]
282 this.waiters.clear()
283 for (const wake of waiters) wake()
284 }
285​
286 private waitForNext(signal?: AbortSignal): Promise<void> {
287 return new Promise((resolve) => {
288 if (signal?.aborted) return resolve()
289 const done = () => {
290 signal?.removeEventListener('abort', done)
291 this.waiters.delete(done)
292 resolve()
293 }
294 this.waiters.add(done)
295 signal?.addEventListener('abort', done, { once: true })
296 })
297 }
299​
300/**
301 * The `harness.gap` event of thread `threadId` for a reader at `from`: the
302 * events after `from` are gone, and the stream goes on after `resumeAt`, the
303 * cursor of this event.
304 */
305export function gapEvent(
306 threadId: string,
307 from: Cursor,
308 resumeAt: Cursor,
309 reason: EventGap['reason'],
310): SessionEvent {
311 const value: EventGap = { from, resumeAt, reason }
312 return {
313 cursor: resumeAt,
314 threadId,
315 // No operation made it. Like a session input, it belongs to the session.
316 operationId: 'session',
317 event: {
318 type: EventType.CUSTOM,
319 name: HARNESS_EVENTS.gap,
320 value,
321 timestamp: Date.now(),
322 },
323 }
325​
326/**
327 * The JSON length of `event`. A value that JSON cannot encode (a `BigInt`
328 * from a plugin) counts as 0, so the publish does not throw.
329 */
330function jsonLength(event: StreamChunk) {
331 try {
332 return JSON.stringify(event).length
333 } catch {
334 return 0
335 }