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

ShellStream.ts

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