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