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

ShellStream.ts

605 lines20.5 KB

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