Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadLiveEventCoalescer.ts

207 lines6.7 KB

1import type { OrchestrationEvent, OrchestrationThreadStreamItem } from "@t3tools/contracts";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Predicate from "effect/Predicate";
7import * as Queue from "effect/Queue";
8import * as Semaphore from "effect/Semaphore";
9import * as Stream from "effect/Stream";
10​
11import { projectActivityEvent } from "./ActivityPayloadProjection.ts";
12​
13const COALESCE_WINDOW = Duration.millis(50);
14const MAX_PENDING_UPDATES = 512;
15​
16export type ThreadLiveInput =
17 | { readonly kind: "event"; readonly event: OrchestrationEvent }
18 | { readonly kind: "synchronized" };
19​
20function isToolUpdated(event: OrchestrationEvent): boolean {
21 return (
22 event.type === "thread.activity-appended" && event.payload.activity.kind === "tool.updated"
23 );
25​
26function asTrimmedString(value: unknown): string | null {
27 if (!Predicate.isString(value)) {
28 return null;
29 }
30 const trimmed = value.trim();
31 return trimmed.length > 0 ? trimmed : null;
33​
34function stableToolCallIdentity(event: OrchestrationEvent): string | null {
35 if (event.type !== "thread.activity-appended") {
36 return null;
37 }
38 const payload = event.payload.activity.payload;
39 if (!Predicate.isObject(payload)) {
40 return null;
41 }
42 const data = Predicate.isObject(payload.data) ? payload.data : null;
43 return asTrimmedString(payload.toolCallId) ?? asTrimmedString(data?.toolCallId);
45​
46/**
47 * Retain only the latest in-flight update for each stable tool-call id in a
48 * live run. Anonymous calls pass through because labels are not unique when
49 * tools execute in parallel. Survivors remain in sequence order.
50 */
51export function coalesceLiveToolUpdatedEvents(
52 events: ReadonlyArray<OrchestrationEvent>,
53): ReadonlyArray<OrchestrationEvent> {
54 const survivors: Array<OrchestrationEvent> = [];
55 let pendingUpdates: Array<OrchestrationEvent> = [];
56​
57 const flushUpdates = () => {
58 const seen = new Set<string>();
59 const latestUpdates: Array<OrchestrationEvent> = [];
60 for (let index = pendingUpdates.length - 1; index >= 0; index -= 1) {
61 const event = pendingUpdates[index]!;
62 const identity = stableToolCallIdentity(event);
63 const activity =
64 event.type === "thread.activity-appended" ? event.payload.activity : undefined;
65 const key = identity ? `${activity?.turnId ?? ""}\u0000${identity}` : null;
66 if (key && seen.has(key)) {
67 continue;
68 }
69 if (key) {
70 seen.add(key);
71 }
72 latestUpdates.push(event);
73 }
74 latestUpdates.reverse();
75 survivors.push(...latestUpdates);
76 pendingUpdates = [];
77 };
78​
79 for (const event of events) {
80 if (isToolUpdated(event)) {
81 pendingUpdates.push(event);
82 continue;
83 }
84 flushUpdates();
85 survivors.push(event);
86 }
87 flushUpdates();
88 return survivors;
90​
91export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoalescer")(
92 function* (options?: { readonly coalesceWindow?: Duration.Input }) {
93 const output = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
94 const input = yield* Queue.unbounded<{
95 readonly value: ThreadLiveInput;
96 readonly processed?: Deferred.Deferred<void>;
97 }>();
98 const mutex = yield* Semaphore.make(1);
99 const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
100 let pendingUpdates: Array<OrchestrationEvent> = [];
101 let windowGeneration = 0;
102 let windowFiber: Fiber.Fiber<void, never> | null = null;
103​
104 const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
105 const fiber = windowFiber;
106 if (!fiber) {
107 return;
108 }
109 windowFiber = null;
110 yield* Fiber.interrupt(fiber);
111 });
112​
113 const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* (
114 boundary?: OrchestrationEvent,
115 ) {
116 const events = boundary ? [...pendingUpdates, boundary] : pendingUpdates;
117 pendingUpdates = [];
118 if (events.length === 0) {
119 return;
120 }
121 yield* Queue.offerAll(
122 output,
123 coalesceLiveToolUpdatedEvents(events).map((event) => ({
124 kind: "event" as const,
125 event: projectActivityEvent(event),
126 })),
127 );
128 });
129​
130 const flushWindow = (generation: number) =>
131 Effect.sleep(coalesceWindow).pipe(
132 Effect.andThen(
133 mutex.withPermits(1)(
134 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
135 ),
136 ),
137 Effect.ensuring(
138 Effect.sync(() => {
139 if (generation === windowGeneration) {
140 windowFiber = null;
141 }
142 }),
143 ),
144 );
145​
146 const process = Effect.fn("ThreadLiveEventCoalescer.process")(function* (
147 input: ThreadLiveInput,
148 ) {
149 yield* mutex.withPermits(1)(
150 Effect.gen(function* () {
151 if (input.kind === "event" && isToolUpdated(input.event)) {
152 pendingUpdates.push(input.event);
153 if (pendingUpdates.length === 1) {
154 const generation = ++windowGeneration;
155 windowFiber = yield* Effect.forkScoped(flushWindow(generation));
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 // A non-update event closes the run immediately. The coalescer keeps
168 // that boundary after the final update from the run.
169 if (input.kind === "event") {
170 yield* flushPending(input.event);
171 } else {
172 yield* flushPending();
173 yield* Queue.offer(output, { kind: "synchronized" });
174 }
175 }),
176 );
177 });
178​
179 yield* Stream.fromQueue(input).pipe(
180 Stream.runForEach(({ value, processed }) =>
181 process(value).pipe(
182 Effect.andThen(processed ? Deferred.succeed(processed, undefined) : Effect.void),
183 ),
184 ),
185 Effect.forkScoped,
186 );
187​
188 const offer = (value: ThreadLiveInput) => Queue.offer(input, { value }).pipe(Effect.asVoid);
189​
190 // Synchronization callers wait for their marker to pass through the same
191 // ordered input queue before draining output produced ahead of it.
192 const offerAndWait = Effect.fn("ThreadLiveEventCoalescer.offerAndWait")(function* (
193 value: ThreadLiveInput,
194 ) {
195 const processed = yield* Deferred.make<void>();
196 yield* Queue.offer(input, { value, processed });
197 yield* Deferred.await(processed);
198 });
199​
200 return {
201 offer,
202 offerAndWait,
203 stream: Stream.fromQueue(output),
204 takeAll: Queue.takeAll(output),
205 } as const;
206 },
207);