Open History to see the last commit
1import type { StreamChunk } from '@tanstack/ai'
2import { onEventOf, onMediaOf } from './feed'
3import type { ListenedFeed } from './feed'
4import type {
5 Cursor,
6 MediaRecord,
7 OnEvent,
8 Operation,
9 OperationKind,
10 OperationStatus,
11 Receipt,
12 SessionEvent,
13} from './types'
14
15let counter = 0
16
17/** A new operation id. It is also the AG-UI `runId` of the operation. */
18export function createOperationId(kind: OperationKind): string {
19 counter += 1
20 return `op-${kind}-${Date.now().toString(36)}-${counter}`
21}
22
23/** The session-side implementation of {@link Operation}. */
24export class OperationImpl<TResult> implements Operation<TResult> {
25 readonly id: string
26 /**
27 * The feed head when the operation was made. Its events come after it. A
28 * rebuilt operation gets the start of its run in the log.
29 */
30 readonly startedCursor: Cursor
31 readonly abortController = new AbortController()
32 readonly receipt: Promise<Receipt>
33 private current: OperationStatus = 'accepted'
34 /**
35 * The result is set. An agent run that waits is `interrupted`, but it
36 * does not end until an answer resumes it.
37 */
38 private ended = false
39 private readonly settled: Promise<TResult>
40 private resolveResult!: (value: TResult) => void
41 private rejectResult!: (error: unknown) => void
42 private settleReceipt!: (receipt: Receipt) => void
43 readonly onEvent: OnEvent
44 readonly onMedia: (
45 listener: (entry: { media: MediaRecord }) => void,
46 ) => () => void
47
48 constructor(
49 readonly kind: OperationKind,
50 private readonly feed: ListenedFeed,
51 private readonly onCancel: (
52 operation: OperationImpl<TResult>,
53 ) => Promise<Receipt>,
54 readonly agent?: string,
55 /** A stored operation id, when a restart rebuilds this operation. */
56 id?: string,
57 /** The cursor before the first event of a rebuilt operation. */
58 startedCursor?: Cursor,
59 ) {
60 this.id = id ?? createOperationId(kind)
61 this.startedCursor = startedCursor ?? feed.head()
62 // A settled operation sends no more events, so a listener is not added,
63 // and its listeners go once it settled. After a tick, so the events it
64 // sends as it settles (the finished event) still reach them.
65 const stops = new Set<() => void>()
66 this.onEvent = onEventOf((listener) => {
67 if (this.isSettled()) return () => {}
68 const stop = feed.listen(listener)
69 stops.add(stop)
70 return () => {
71 stops.delete(stop)
72 stop()
73 }
74 }, this.id)
75 const dropListeners = () => {
76 const timer = setTimeout(() => {
77 for (const stop of stops) stop()
78 stops.clear()
79 }, 0)
80 // The timer must not keep a CLI or a test process alive.
81 if (typeof timer === 'object' && 'unref' in timer) timer.unref()
82 }
83 this.onMedia = onMediaOf(this.onEvent)
84 this.receipt = new Promise<Receipt>((resolve) => {
85 this.settleReceipt = resolve
86 })
87 this.settled = new Promise<TResult>((resolve, reject) => {
88 this.resolveResult = resolve
89 this.rejectResult = reject
90 })
91 // Nobody may await a failed background operation. Do not report that as an
92 // unhandled rejection. `then` still rejects for callers that await.
93 this.settled.then(dropListeners, dropListeners)
94 }
95
96 then<TResult1 = TResult, TResult2 = never>(
97 onfulfilled?: ((value: TResult) => TResult1 | PromiseLike<TResult1>) | null,
98 onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
99 ): PromiseLike<TResult1 | TResult2> {
100 return this.settled.then(onfulfilled, onrejected)
101 }
102
103 status(): OperationStatus {
104 return this.current
105 }
106
107 isSettled(): boolean {
108 return this.ended
109 }
110
111 /** Set the status. A settled operation keeps its final status. */
112 setStatus(status: OperationStatus): void {
113 if (this.isSettled()) return
114 this.current = status
115 }
116
117 publish(event: StreamChunk): void {
118 this.feed.publish(this.id, event)
119 }
120
121 /** Answer `receipt`. The first answer wins. */
122 resolveReceipt(receipt: Receipt): void {
123 this.settleReceipt(receipt)
124 }
125
126 /**
127 * Settle with `result`. The first settle wins: when the operation settled
128 * already, this call does nothing.
129 */
130 finish(status: 'completed' | 'interrupted', result: TResult): void {
131 if (this.isSettled()) return
132 this.current = status
133 this.ended = true
134 this.resolveResult(result)
135 // A reader of `events()` waits for the next event: it ends now instead.
136 this.feed.wake()
137 }
138
139 /**
140 * Settle with `error`. The first settle wins: when the operation settled
141 * already, this call does nothing.
142 */
143 fail(status: 'failed' | 'cancelled', error: unknown): void {
144 if (this.isSettled()) return
145 this.current = status
146 this.ended = true
147 this.rejectResult(error)
148 this.feed.wake()
149 }
150
151 events(options?: {
152 from?: Cursor
153 signal?: AbortSignal
154 }): AsyncIterable<SessionEvent> {
155 return this.feed.read({
156 ...options,
157 // Every event of this operation comes after its start, so the read
158 // does not walk the older events of the feed.
159 from: options?.from ?? this.startedCursor,
160 filter: (entry) => entry.operationId === this.id,
161 until: () => this.isSettled(),
162 })
163 }
164
165 async *stream(options?: {
166 signal?: AbortSignal
167 }): AsyncIterable<StreamChunk> {
168 for await (const entry of this.events(options)) {
169 yield entry.event
170 }
171 }
172
173 cancel(_reason?: string): Promise<Receipt> {
174 return this.onCancel(this)
175 }
176}