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

ShellStream.ts

568 lines19.3 KB

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