Open History to see the last commit
1import { encodeWsFrame } from '@tanstack/ai'
2import type { SessionEvent } from './types'
3
4// The encoded frame of each log entry. Readers of one log get the same entry
5// objects, so N readers encode an event once.
6const encoded = new WeakMap<SessionEvent, string>()
7
8/**
9 * The `harness.event` frame of `entry` as JSON text. The event is an AG-UI
10 * wire chunk (`toWireChunk`): keys that are not in the AG-UI spec are gone.
11 * The log keeps the full chunk. Only the wire drops keys.
12 *
13 * @example
14 * ```ts
15 * for await (const entry of session.events({ from })) socket.send(wireFrame(entry))
16 * ```
17 */
18export function wireFrame(entry: SessionEvent): string {
19 const cached = encoded.get(entry)
20 if (cached !== undefined) return cached
21 const { event, ...tags } = entry
22 // `encodeWsFrame` with no id is the JSON of `toWireChunk(event)`. The slice
23 // drops the closing `}` of the tags, so the event goes in after them.
24 const text = `${JSON.stringify({ type: 'harness.event', ...tags }).slice(0, -1)},"event":${encodeWsFrame(event, undefined)}}`
25 encoded.set(entry, text)
26 return text
27}