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

ShellStream.ts

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