Open History to see the last commit
1import type {
2 ApplicationStoredEvent,
3 OrchestrationProjectShell,
4 OrchestrationV2ArchivedShellStreamItem,
5 OrchestrationV2ShellSnapshot,
6 OrchestrationV2ThreadShell,
7 OrchestrationV2ThreadShellSnapshot,
8 OrchestrationV2ShellStreamItem,
9 OrchestrationV2StoredEvent,
10} from "@t3tools/contracts";
11import {
12 OrchestrationProjectShell as ProjectShellSchema,
13 OrchestrationV2ThreadShell as ThreadShellSchema,
14} from "@t3tools/contracts";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16import type * as Arr from "effect/Array";
17import type * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import type * as SqlClient from "effect/sql/SqlClient";
25import * as Stream from "effect/Stream";
26
27import { bufferLatestLiveStream } from "./LiveStreamBudget.ts";
28
29type ShellDelta = Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;
30
31/** Snapshots, synchronization, and enrichment markers must bypass full-state coalescing. */
32export const bufferShellLiveStream = <E, R>(
33 source: Stream.Stream<ShellDelta, E, R>,
34 limits?: { readonly maxItems?: number; readonly maxSerializedBytes?: number },
35) =>
36 bufferLatestLiveStream(
37 source,
38 (item) => {
39 switch (item.kind) {
40 case "project.updated":
41 return `project:${item.project.id}`;
42 case "project.removed":
43 return `project:${item.projectId}`;
44 case "thread.updated":
45 return `thread:${item.location}:${item.thread.id}`;
46 case "thread.removed":
47 return `thread:${item.location}:${item.threadId}`;
48 }
49 },
50 limits,
51 );
52
53export function buildActiveShellSnapshot(input: {
54 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
55 readonly threads: OrchestrationV2ThreadShellSnapshot;
56 readonly snapshotSequence: number;
57}): OrchestrationV2ShellSnapshot {
58 return {
59 schemaVersion: input.threads.schemaVersion,
60 snapshotSequence: input.snapshotSequence,
61 projects: input.projects,
62 threads: input.threads.threads,
63 archivedThreads: [],
64 };
65}
66
67/**
68 * One transaction covers the reads so they agree; the threads are decoded after it commits,
69 * because the server shares one SQLite connection and decoding a large shell takes longer than
70 * reading it.
71 */
72export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <
73 E1,
74 E2,
75 E3,
76 E4,
77>(input: {
78 readonly sql: SqlClient.SqlClient;
79 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
80 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
81 readonly latestSequence: Effect.Effect<number, E4>;
82}) {
83 const read = yield* input.sql
84 .withTransaction(
85 Effect.all({
86 decodeThreads: input.readThreads,
87 projects: input.listProjects,
88 snapshotSequence: input.latestSequence,
89 }),
90 )
91 .pipe(NodeSqliteClient.readOnly);
92 return {
93 projects: read.projects,
94 threads: yield* read.decodeThreads,
95 snapshotSequence: read.snapshotSequence,
96 };
97});
98
99export type ShellApplicationEvent =
100 | Pick<
101 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
102 "aggregateKind" | "aggregateId" | "type" | "sequence"
103 >
104 | {
105 readonly sequence: number;
106 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
107 };
108
109/** Focused subagents receive these updates through their thread subscription. */
110export function shouldPublishShellApplicationEvent(
111 stored: ApplicationStoredEvent,
112 subagentThreadIds: Set<string>,
113): boolean {
114 if ("aggregateKind" in stored) return true;
115 const { event } = stored;
116 if (event.type === "thread.created") {
117 if (event.payload.lineage.relationshipToParent === "subagent") {
118 subagentThreadIds.add(event.threadId);
119 }
120 return true;
121 }
122 if (event.type === "thread.deleted") {
123 // Replay and the live tail overlap; keep known IDs so late events stay filtered.
124 return true;
125 }
126 return !(
127 subagentThreadIds.has(event.threadId) &&
128 (event.type === "node.updated" ||
129 event.type === "turn-item.updated" ||
130 event.type === "provider-turn.updated" ||
131 event.type === "message.updated")
132 );
133}
134
135/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
136export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
137 return "aggregateKind" in stored
138 ? {
139 aggregateKind: stored.aggregateKind,
140 aggregateId: stored.aggregateId,
141 type: stored.type,
142 sequence: stored.sequence,
143 }
144 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
145}
146
147export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
148 events: ReadonlyArray<A>,
149): ReadonlyArray<A> {
150 const latestByAggregate = new Map<string, A>();
151 for (const stored of events) {
152 const key =
153 "aggregateKind" in stored
154 ? `project:${stored.aggregateId}`
155 : `thread:${stored.event.threadId}`;
156 latestByAggregate.set(key, stored);
157 }
158 return Array.from(latestByAggregate.values()).sort(
159 (left, right) => left.sequence - right.sequence,
160 );
161}
162
163/**
164 * Prevents a newer marked enrichment from landing before the unmarked authoritative initial
165 * snapshot.
166 */
167export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
168 readonly initial: Stream.Stream<A, E, R>;
169 readonly tail: Stream.Stream<A2, E2, R2>;
170 readonly enrichment: Stream.Stream<A3, E3, R3>;
171}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
172 const merged = Stream.fromPull(
173 Effect.gen(function* () {
174 const output = yield* Queue.bounded<
175 {
176 readonly items: Arr.NonEmptyReadonlyArray<A2 | A3>;
177 readonly acknowledged?: Deferred.Deferred<void>;
178 },
179 E2 | E3 | Cause.Done
180 >(0);
181 yield* Effect.addFinalizer(() => Queue.shutdown(output));
182 let remaining = 2;
183 const drain = (effect: Effect.Effect<void, E2 | E3, R2 | R3>) =>
184 effect.pipe(
185 Effect.exit,
186 Effect.flatMap((exit) =>
187 Exit.isFailure(exit)
188 ? Queue.failCause(output, exit.cause)
189 : --remaining === 0
190 ? Queue.end(output)
191 : Effect.void,
192 ),
193 Effect.forkScoped,
194 );
195 yield* drain(
196 input.tail.pipe(
197 Stream.runForEachArray((items) =>
198 Effect.gen(function* () {
199 const acknowledged = yield* Deferred.make<void>();
200 yield* Queue.offer(output, { items, acknowledged });
201 yield* Deferred.await(acknowledged);
202 }),
203 ),
204 ),
205 );
206 // Keep draining the sliding enrichment subscription after each handoff,
207 // as Stream.merge does, while only the budgeted tail waits for an ACK.
208 yield* drain(
209 input.enrichment.pipe(Stream.runForEachArray((items) => Queue.offer(output, { items }))),
210 );
211 let previous: Deferred.Deferred<void> | undefined;
212 // Stream.merge pulls ahead after handing off each batch. Wait for the next
213 // downstream pull so shell delivery keeps that batch charged until its RPC ACK.
214 // @effect-diagnostics-next-line returnEffectInGen:off - Stream.fromPull needs the pull effect as its result.
215 return Effect.gen(function* () {
216 if (previous) yield* Deferred.succeed(previous, undefined);
217 const next = yield* Queue.take(output);
218 previous = next.acknowledged;
219 return next.items;
220 });
221 }),
222 ).pipe(Stream.scoped);
223 return Stream.concat(input.initial, merged);
224}
225
226const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
227
228export function dedupeShellEnrichment<E, R>(
229 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
230): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
231 return Stream.suspend(() => {
232 let previous:
233 | {
234 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
235 readonly roots: ReadonlySet<string>;
236 }
237 | undefined;
238 return stream.pipe(
239 Stream.filter((item) => {
240 if (item.kind !== "snapshot") {
241 if (item.kind === "project.updated" || item.kind === "project.removed")
242 previous = undefined;
243 return true;
244 }
245 if (
246 item.resolvedRepositoryIdentityRoots === undefined ||
247 item.snapshot.threads.length > 0 ||
248 item.snapshot.archivedThreads.length > 0
249 ) {
250 previous = undefined;
251 return true;
252 }
253 const roots = new Set(item.resolvedRepositoryIdentityRoots);
254 const prior = previous;
255 if (
256 prior !== undefined &&
257 roots.size === prior.roots.size &&
258 [...roots].every((root) => prior.roots.has(root)) &&
259 sameProjects(prior.projects, item.snapshot.projects)
260 )
261 return false;
262 previous = { projects: item.snapshot.projects, roots };
263 return true;
264 }),
265 );
266 });
267}
268
269export function shellStreamItemFromEnrichmentRefresh(input: {
270 readonly snapshot: OrchestrationV2ShellSnapshot;
271 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
272}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
273 const resolvedRepositoryIdentityRoots = [
274 ...new Set(input.changes.map((change) => change.workspaceRoot)),
275 ];
276 return {
277 kind: "snapshot",
278 snapshot: {
279 ...input.snapshot,
280 projects: input.snapshot.projects.filter((project) =>
281 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
282 ),
283 threads: [],
284 archivedThreads: [],
285 },
286 resolvedRepositoryIdentityRoots,
287 };
288}
289
290export function shellStreamItemsFromInitialSnapshot(input: {
291 readonly snapshot: OrchestrationV2ShellSnapshot;
292 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
293}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
294 const authoritative = {
295 kind: "snapshot" as const,
296 snapshot: input.snapshot,
297 };
298 if (input.resolvedRepositoryIdentityRoots.length === 0) {
299 return [authoritative];
300 }
301 return [
302 authoritative,
303 {
304 kind: "snapshot" as const,
305 snapshot: {
306 ...input.snapshot,
307 projects: input.snapshot.projects.filter((project) =>
308 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
309 ),
310 threads: [],
311 archivedThreads: [],
312 },
313 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
314 },
315 ];
316}
317
318export function shellStreamItemsFromResumeSnapshot(input: {
319 readonly snapshot: OrchestrationV2ShellSnapshot;
320 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
321}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
322 return shellStreamItemsFromInitialSnapshot(input).filter(
323 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
324 );
325}
326
327const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
328
329const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
330
331/**
332 * A skipped delta leaves the client cursor behind, and a resume replays the events after that
333 * cursor. So an unchanged shell is still sent once its last send is
334 * `UNCHANGED_THREAD_SHELL_RESEND_MS` old.
335 */
336export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
337 stream: Stream.Stream<A, E, R>,
338): Stream.Stream<A, E, R> {
339 return Stream.suspend(() => {
340 const lastSent = new Map<
341 OrchestrationV2ThreadShell["id"],
342 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
343 >();
344 return stream.pipe(
345 Stream.filterEffect((item) =>
346 Effect.map(Clock.currentTimeMillis, (now) => {
347 if (item.kind === "thread.removed") {
348 lastSent.delete(item.threadId);
349 return true;
350 }
351 if (item.kind !== "thread.updated") return true;
352 const previous = lastSent.get(item.thread.id);
353 if (
354 previous !== undefined &&
355 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
356 sameThreadShell(
357 { ...item.thread, updatedAt: previous.thread.updatedAt },
358 previous.thread,
359 )
360 ) {
361 return false;
362 }
363 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
364 return true;
365 }),
366 ),
367 );
368 });
369}
370
371export function coalesceStoredThreadEvents(
372 events: ReadonlyArray<OrchestrationV2StoredEvent>,
373): ReadonlyArray<OrchestrationV2StoredEvent> {
374 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
375 for (const stored of events) {
376 latestByThreadId.set(stored.event.threadId, stored);
377 }
378 return Array.from(latestByThreadId.values()).sort(
379 (left, right) => left.sequence - right.sequence,
380 );
381}
382
383export function shellStreamItemFromThreadShell(input: {
384 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
385 readonly shell: OrchestrationV2ThreadShell | null;
386}): Extract<
387 OrchestrationV2ShellStreamItem,
388 { readonly kind: "thread.updated" | "thread.removed" }
389> {
390 if (input.shell !== null) {
391 if (input.shell.archivedAt !== null) {
392 return {
393 kind: "thread.removed",
394 sequence: input.stored.sequence,
395 location: "active",
396 threadId: input.shell.id,
397 };
398 }
399 return {
400 kind: "thread.updated",
401 sequence: input.stored.sequence,
402 location: "active",
403 thread: input.shell,
404 };
405 }
406
407 return {
408 kind: "thread.removed",
409 sequence: input.stored.sequence,
410 location: "active",
411 threadId: input.stored.event.threadId,
412 };
413}
414
415export function archivedShellStreamItemFromThreadShell(input: {
416 readonly stored: OrchestrationV2StoredEvent;
417 readonly shell: OrchestrationV2ThreadShell | null;
418}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
419 if (input.shell !== null && input.shell.archivedAt !== null) {
420 return {
421 kind: "thread.updated",
422 sequence: input.stored.sequence,
423 thread: input.shell,
424 };
425 }
426 if (
427 input.stored.event.type === "thread.unarchived" ||
428 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
429 ) {
430 return {
431 kind: "thread.removed",
432 sequence: input.stored.sequence,
433 threadId: input.stored.event.threadId,
434 };
435 }
436 return null;
437}