Open History to see the last commit
1import type { OrchestrationV2ThreadStreamItem } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as Queue from "effect/Queue";
9import * as Semaphore from "effect/Semaphore";
10import * as Stream from "effect/Stream";
11
12import {
13 LiveStreamBufferError,
14 makeLiveStreamBudget,
15 type RetainedLiveItem,
16} from "./LiveStreamBudget.ts";
17
18const COALESCE_WINDOW = Duration.millis(50);
19const MAX_PENDING_UPDATES = 512;
20
21type ThreadLiveEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>;
22export type ThreadLiveInput = ThreadLiveEvent | { readonly kind: "synchronized" };
23
24function coalescibleUpdateKey(input: ThreadLiveEvent): string | null {
25 const { event } = input;
26 const prefix = `${event.threadId}\u0000${event.runId ?? ""}\u0000${event.type}`;
27 if (event.type === "message.updated") {
28 return event.payload.role === "assistant" && event.payload.streaming
29 ? `${prefix}\u0000${event.payload.id}`
30 : null;
31 }
32 if (event.type !== "turn-item.updated" || event.payload.status !== "running") return null;
33 switch (event.payload.type) {
34 case "assistant_message":
35 case "reasoning":
36 if (!event.payload.streaming) return null;
37 break;
38 case "command_execution":
39 case "file_change":
40 case "file_search":
41 case "web_search":
42 case "dynamic_tool":
43 break;
44 default:
45 return null;
46 }
47 return `${prefix}\u0000${event.payload.type}\u0000${event.payload.id}`;
48}
49
50// These events replace whole entities. Keep each survivor at its original
51// position/sequence so a resume cursor cannot skip an unrelated earlier update.
52export function coalesceLiveUpdatedEvents(
53 events: ReadonlyArray<ThreadLiveEvent>,
54): ReadonlyArray<ThreadLiveEvent> {
55 const latestUpdates = new Map<string, number>();
56 const superseded = new Set<number>();
57 const pendingKeys = new Map<ThreadLiveEvent["event"]["type"], string>();
58
59 for (const [index, event] of events.entries()) {
60 const key = coalescibleUpdateKey(event);
61 if (key === null) {
62 latestUpdates.clear();
63 pendingKeys.clear();
64 continue;
65 }
66 // Both entity families use insertion order; partial timelines also reject
67 // unseen items below their watermark. Keep identity switches within each
68 // family, while allowing paired message/item updates to coalesce.
69 const pendingKey = pendingKeys.get(event.event.type);
70 if (pendingKey !== undefined && pendingKey !== key) latestUpdates.clear();
71 pendingKeys.set(event.event.type, key);
72 const previous = latestUpdates.get(key);
73 if (previous !== undefined) superseded.add(previous);
74 latestUpdates.set(key, index);
75 }
76 return events.filter((_, index) => !superseded.has(index));
77}
78
79export const makeThreadLiveEventCoalescer = Effect.fn(
80 "ThreadLiveEventCoalescer.makeThreadLiveEventCoalescer",
81)(function* <E = never>(options?: {
82 readonly maxItems?: number;
83 readonly maxSerializedBytes?: number;
84}) {
85 const coalescerScope = yield* Effect.scope;
86 const budget = yield* makeLiveStreamBudget(options);
87 const cleanupComplete = yield* Deferred.make<void>();
88 const output = yield* Queue.unbounded<
89 RetainedLiveItem<ThreadLiveInput>,
90 E | LiveStreamBufferError | Cause.Done
91 >();
92 const mutex = yield* Semaphore.make(1);
93 let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
94 let windowGeneration = 0;
95 let windowFiber: Fiber.Fiber<void, never> | null = null;
96 let closed = false;
97
98 // cancelWindow/flushPending/offerAll run per live event or batch; sub-ms spans here would flood the rotating trace.
99 const cancelWindow = Effect.fnUntraced(function* () {
100 const fiber = windowFiber;
101 if (!fiber) {
102 return;
103 }
104 windowFiber = null;
105 yield* Fiber.interrupt(fiber);
106 });
107
108 const flushPending = Effect.fnUntraced(function* () {
109 if (pendingUpdates.length === 0) {
110 return;
111 }
112 const items = yield* budget.replace(
113 pendingUpdates,
114 coalesceLiveUpdatedEvents(pendingUpdates.map((item) => item.value)),
115 );
116 pendingUpdates = [];
117 yield* Queue.offerAll(output, items);
118 }, Effect.uninterruptible);
119
120 const flushWindow = (generation: number) =>
121 Effect.sleep(COALESCE_WINDOW).pipe(
122 Effect.andThen(
123 mutex.withPermits(1)(
124 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
125 ),
126 ),
127 Effect.ensuring(
128 Effect.sync(() => {
129 if (generation === windowGeneration) {
130 windowFiber = null;
131 }
132 }),
133 ),
134 Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
135 );
136
137 // Keep each source batch together so a synchronization marker cannot pass
138 // events already pulled from PubSub but still being coalesced.
139 const offerAll = Effect.fnUntraced(function* (inputs: ReadonlyArray<ThreadLiveInput>) {
140 yield* mutex.withPermits(1)(
141 Effect.forEach(
142 inputs,
143 (input) =>
144 Effect.gen(function* () {
145 yield* budget.check;
146 if (input.kind === "event") {
147 yield* budget.retain(input).pipe(
148 Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
149 Effect.uninterruptible,
150 );
151 }
152 if (input.kind === "event" && coalescibleUpdateKey(input) !== null) {
153 if (pendingUpdates.length === 1) {
154 const generation = ++windowGeneration;
155 windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
156 }
157 if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
158 yield* cancelWindow();
159 windowGeneration += 1;
160 yield* flushPending();
161 }
162 return;
163 }
164
165 yield* cancelWindow();
166 windowGeneration += 1;
167 yield* flushPending();
168 if (input.kind === "synchronized") {
169 yield* budget.retain({ kind: "synchronized" as const }).pipe(
170 Effect.flatMap((marker) => Queue.offer(output, marker)),
171 Effect.uninterruptible,
172 );
173 }
174 }),
175 { discard: true },
176 ),
177 );
178 });
179
180 const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
181 mutex.withPermits(1)(
182 Effect.gen(function* () {
183 if (closed) {
184 return;
185 }
186 closed = true;
187 windowGeneration += 1;
188 yield* cancelWindow();
189 budget.release(pendingUpdates);
190 pendingUpdates = [];
191 budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
192 if (cause) {
193 yield* Queue.failCause(output, cause);
194 }
195 yield* Queue.shutdown(output);
196 yield* Deferred.succeed(cleanupComplete, undefined);
197 }),
198 );
199
200 yield* Effect.addFinalizer(() => close());
201 yield* budget.failed.pipe(
202 Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
203 Effect.forkScoped,
204 );
205
206 return {
207 offer: (input: ThreadLiveInput) => offerAll([input]),
208 close,
209 end: mutex.withPermits(1)(
210 Effect.gen(function* () {
211 yield* cancelWindow();
212 windowGeneration += 1;
213 yield* flushPending();
214 yield* Queue.end(output);
215 }),
216 ),
217 offerAll,
218 stream: budget.deliver(Stream.fromQueue(output)),
219 failed: budget.failed,
220 closed: Deferred.await(cleanupComplete),
221 usage: budget.usage,
222 } as const;
223});
224
225export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>
226 Stream.unwrap(
227 Effect.gen(function* () {
228 const coalescer = yield* makeThreadLiveEventCoalescer<E>();
229 yield* source.pipe(
230 Stream.runForEachArray(coalescer.offerAll),
231 Effect.andThen(coalescer.end),
232 Effect.raceFirst(coalescer.failed),
233 Effect.exit,
234 Effect.flatMap((exit) =>
235 Exit.isFailure(exit) ? coalescer.close(exit.cause) : Effect.void,
236 ),
237 Effect.forkScoped({ startImmediately: true }),
238 );
239 return coalescer.stream;
240 }),
241 );