Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 isOrchestrationV2WorkActive,
5 ORCHESTRATION_V2_WS_METHODS,
6 type EnvironmentId as EnvironmentIdType,
7 type OrchestrationV2ThreadDetailSnapshot,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ThreadStreamItem,
10 type OrchestrationV2TurnItem,
11 type ThreadId as ThreadIdType,
12} from "@t3tools/contracts";
13import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
14import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
15import * as Cause from "effect/Cause";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Scope from "effect/Scope";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Result from "effect/Result";
23import * as Semaphore from "effect/Semaphore";
24import * as Stream from "effect/Stream";
25import * as SubscriptionRef from "effect/SubscriptionRef";
26import { HttpClient } from "effect/http";
27import { Atom } from "effect/reactivity";
28
29import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
30import * as EnvironmentRegistry from "../connection/registry.ts";
31import { connectionProjectionPhase } from "../connection/model.ts";
32import * as EnvironmentSupervisor from "../connection/supervisor.ts";
33import * as ConnectionWakeups from "../connection/wakeups.ts";
34import * as Persistence from "../platform/persistence.ts";
35import { runCachePersistence } from "./cachePersistence.ts";
36import * as ManagedRelay from "../relay/managedRelay.ts";
37import {
38 isAuthorizationFailure,
39 request,
40 subscribeDynamic,
41 subscriptionRetryDelay,
42} from "../rpc/client.ts";
43import { parseThreadKey, threadKey } from "./entities.ts";
44import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
45import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
46import { followStreamInEnvironment } from "./runtime.ts";
47import * as ThreadHistoryController from "./threadHistoryController.ts";
48import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
49import {
50 applyHistoryPageMeta,
51 clearActiveHistoryLoading,
52 EMPTY_THREAD_HISTORY_META,
53 isActiveHistoryRequestCursor,
54 mergeOlderHistoryIntoProjection,
55 mergeOlderSubagentsIntoProjection,
56 type ThreadHistoryMeta,
57} from "./threadHistoryMerge.ts";
58import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
59import { makeThreadRequestsResolvedAnnouncer } from "./threadRequests.ts";
60import {
61 EMPTY_ENVIRONMENT_THREAD_STATE,
62 type EnvironmentThreadState,
63 type EnvironmentThreadStatus,
64} from "./threadState.ts";
65
66const THREAD_SUBSCRIPTION_RETRY_DELAY = "250 millis";
67
68function statusWithoutLiveData(
69 data: Option.Option<OrchestrationV2ThreadProjection>,
70): EnvironmentThreadStatus {
71 return Option.isSome(data) ? "cached" : "empty";
72}
73
74const THREAD_SYNC_ERROR = msg("Could not synchronize the thread.");
75const HISTORY_LOAD_ERROR = msg("Could not load earlier activity.");
76const WORK_HISTORY_CHANGED_ERROR = msg("Work history changed. Retry loading it.");
77const THREAD_ERRORS: ReadonlySet<string> = new Set([
78 THREAD_SYNC_ERROR,
79 HISTORY_LOAD_ERROR,
80 WORK_HISTORY_CHANGED_ERROR,
81]);
82
83/**
84 * A thread or history error in the active language. Errors this module wrote translate;
85 * messages from the server or another error stay as they are.
86 * @public
87 */
88export function threadErrorText(error: string, resolve: MFunctionType = mFallback): string {
89 return THREAD_ERRORS.has(error) ? resolve(error) : error;
90}
91
92function formatThreadError(cause: Cause.Cause<unknown>): string {
93 const error = Cause.squash(cause);
94 return error instanceof Error && error.message.trim().length > 0
95 ? error.message
96 : THREAD_SYNC_ERROR;
97}
98
99function formatHistoryError(error: unknown): string {
100 if (error instanceof Error && error.message.trim().length > 0) {
101 return error.message;
102 }
103 return HISTORY_LOAD_ERROR;
104}
105
106// Steers join a running turn; every other user message opens one. The timeline shows every
107// notification as a response boundary, whether it opened its run or arrived mid-run.
108function startsTurn(item: OrchestrationV2TurnItem): boolean {
109 return (
110 item.type === "notification" ||
111 (item.type === "user_message" &&
112 item.inputIntent !== "steer" &&
113 item.inputIntent !== "promoted_queued_to_steer")
114 );
115}
116
117function historyMetaFromCachedSnapshot(
118 snapshot: OrchestrationV2ThreadDetailSnapshot,
119): ThreadHistoryMeta {
120 const historyCursor = snapshot.historyCursor ?? null;
121 const hasMoreHistory = snapshot.hasMoreHistory ?? false;
122 return {
123 historyCursor,
124 hasMoreHistory,
125 loading: false,
126 error: null,
127 expanded: false,
128 latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null,
129 };
130}
131
132function snapshotToPersist(
133 snapshotSequence: number,
134 projection: OrchestrationV2ThreadProjection,
135 history: ThreadHistoryMeta,
136 acceptsBoundedSnapshots: boolean,
137): OrchestrationV2ThreadDetailSnapshot {
138 // A complete bounded snapshot still proves paging support. Retain that evidence
139 // so a thread that grows while closed can resume with a bounded fallback.
140 if (acceptsBoundedSnapshots || history.hasMoreHistory || history.historyCursor !== null) {
141 return {
142 snapshotSequence,
143 projection,
144 historyCursor: history.historyCursor,
145 hasMoreHistory: history.hasMoreHistory,
146 latestLocalTurnOrdinal: history.latestLocalTurnOrdinal,
147 };
148 }
149 return { snapshotSequence, projection };
150}
151
152function shouldPersistThread(
153 thread: OrchestrationV2ThreadProjection,
154 history: ThreadHistoryMeta,
155): boolean {
156 // After the user loads older pages the in-memory timeline can grow large.
157 // Keep those expanded projections out of the monolithic cache.
158 if (history.expanded) {
159 return false;
160 }
161 return !thread.runs.some(
162 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
163 );
164}
165
166// Only still-active local copies take the server's item: events applied meanwhile win,
167// and inherited rows belong to another thread.
168function settleTurnItems(
169 threadId: ThreadIdType,
170 projection: OrchestrationV2ThreadProjection,
171 settled: ReadonlyMap<string, OrchestrationV2TurnItem>,
172): OrchestrationV2ThreadProjection {
173 let changed = false;
174 const settle = (item: OrchestrationV2TurnItem, id: string) => {
175 const server = settled.get(id);
176 if (server === undefined || !isOrchestrationV2WorkActive(item.status)) return item;
177 changed = true;
178 return server;
179 };
180 const turnItems = projection.turnItems.map((item) => settle(item, item.id));
181 const visibleTurnItems = projection.visibleTurnItems.map((row) => {
182 if (row.sourceThreadId !== threadId) return row;
183 const item = settle(row.item, row.sourceItemId);
184 return item === row.item ? row : { ...row, item };
185 });
186 return changed ? { ...projection, turnItems, visibleTurnItems } : projection;
187}
188
189interface ThreadResumeSnapshot {
190 readonly state: EnvironmentThreadState;
191 readonly sequence: number;
192 readonly persisted: boolean;
193 readonly acceptsBoundedSnapshots?: boolean;
194}
195
196interface ThreadResumeCache {
197 snapshot: ThreadResumeSnapshot | undefined;
198 owner: object | undefined;
199}
200
201function matchesThreadSnapshot(
202 current: ThreadResumeSnapshot,
203 projection: OrchestrationV2ThreadProjection | null,
204 sequence: number,
205 history: Pick<ThreadHistoryMeta, "historyCursor" | "hasMoreHistory" | "latestLocalTurnOrdinal">,
206): boolean {
207 if (current.sequence !== sequence || Option.getOrNull(current.state.data) !== projection)
208 return false;
209 const currentHistory = current.state.history;
210 return (
211 currentHistory.historyCursor === history.historyCursor &&
212 currentHistory.hasMoreHistory === history.hasMoreHistory &&
213 (!(history.hasMoreHistory || history.historyCursor !== null) ||
214 currentHistory.latestLocalTurnOrdinal === history.latestLocalTurnOrdinal)
215 );
216}
217
218function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState {
219 return {
220 ...value,
221 status:
222 value.status === "deleted" || (value.status === "live" && Option.isSome(value.data))
223 ? value.status
224 : statusWithoutLiveData(value.data),
225 error: Option.none(),
226 history: { ...value.history, loading: false, error: null },
227 };
228}
229
230function hasMissingPendingQuestionCard(projection: OrchestrationV2ThreadProjection): boolean {
231 const pending = new Set(
232 projection.runtimeRequests
233 .filter((request) => request.kind === "user_input" && request.status === "pending")
234 .map((request) => request.id),
235 );
236 if (pending.size === 0) return false;
237 for (const item of projection.turnItems) {
238 if (item.type === "user_input_request") pending.delete(item.requestId);
239 if (pending.size === 0) return false;
240 }
241 return true;
242}
243
244export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
245 threadId: ThreadIdType,
246 resumeCache?: ThreadResumeCache,
247) {
248 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
249 const cache = yield* Persistence.EnvironmentCacheStore;
250 const snapshotLoader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
251 const historyController = yield* Effect.serviceOption(
252 ThreadHistoryController.ThreadHistoryController,
253 );
254 const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient);
255 const dpopSigner = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
256 const remoteAuthorization = yield* Effect.serviceOption(
257 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
258 );
259 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
260 const environmentId = supervisor.target.environmentId;
261 const candidate = resumeCache?.snapshot;
262 const retained =
263 candidate &&
264 Option.isSome(candidate.state.data) &&
265 hasMissingPendingQuestionCard(candidate.state.data.value)
266 ? undefined
267 : candidate;
268 const owner = {};
269 if (resumeCache) resumeCache.owner = owner;
270 const loaded =
271 retained === undefined
272 ? yield* cache.loadThread(environmentId, threadId).pipe(
273 Effect.catch((error) =>
274 Effect.logWarning("Could not load cached thread.").pipe(
275 Effect.annotateLogs({
276 environmentId,
277 threadId,
278 error: error.message,
279 }),
280 Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
281 ),
282 ),
283 )
284 : Option.none<OrchestrationV2ThreadDetailSnapshot>();
285 // Old bounded caches can omit a pending question's card; replay alone cannot restore it.
286 const cached = Option.filter(
287 loaded,
288 (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection),
289 );
290 const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);
291 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
292 // via `afterSequence` instead of re-downloading the full thread body.
293 const initialSequence =
294 retained?.sequence ??
295 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
296 const initialState: EnvironmentThreadState = retained
297 ? cachedThreadState(retained.state)
298 : {
299 data: cachedThread,
300 status: statusWithoutLiveData(cachedThread),
301 error: Option.none(),
302 history: Option.match(cached, {
303 onNone: () => EMPTY_THREAD_HISTORY_META,
304 onSome: historyMetaFromCachedSnapshot,
305 }),
306 sequence: initialSequence,
307 };
308 const state = yield* SubscriptionRef.make(initialState);
309 const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController);
310 const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory);
311 const lastSequence = yield* SubscriptionRef.make(initialSequence);
312 let committed: ThreadResumeSnapshot = {
313 state: initialState,
314 sequence: initialSequence,
315 persisted: retained?.persisted ?? Option.isSome(cached),
316 acceptsBoundedSnapshots: canLoadHistory,
317 };
318 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
319 const awaitingCompletion = yield* Ref.make(false);
320 const applyLock = yield* Semaphore.make(1);
321 // Save only completed data/cursor updates. A canceled scope must not cache
322 // a cursor whose event has not reached the data yet.
323 const announceRequests = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
324 const remember = Effect.gen(function* () {
325 const current = yield* SubscriptionRef.get(state);
326 const sequence = yield* SubscriptionRef.get(lastSequence);
327 // Only a synchronized projection from the scope that owns the thread is
328 // authoritative: a cached one can predate a request the user already has
329 // drafts for, and a superseded scope can lag its successor.
330 const owns = resumeCache === undefined || resumeCache.owner === owner;
331 if (owns && current.status === "deleted") announceRequests([]);
332 else if (owns && current.status === "live" && Option.isSome(current.data))
333 announceRequests(current.data.value.runtimeRequests);
334 committed = {
335 state: current,
336 sequence,
337 acceptsBoundedSnapshots: yield* Ref.get(acceptsBoundedSocketSnapshots),
338 persisted:
339 committed.persisted &&
340 matchesThreadSnapshot(committed, Option.getOrNull(current.data), sequence, current.history),
341 };
342 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
343 });
344 const persistence = yield* Queue.sliding<OrchestrationV2ThreadDetailSnapshot>(1);
345 let queuedSnapshot = Option.getOrUndefined(cached);
346 let savedSnapshot = queuedSnapshot;
347 const queuePersist = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
348 Effect.suspend(() => {
349 queuedSnapshot = snapshot;
350 return Queue.offer(persistence, snapshot);
351 });
352
353 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
354 snapshot: OrchestrationV2ThreadDetailSnapshot,
355 ) {
356 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
357 if (committed.state.status === "deleted") return;
358 if (
359 committed.persisted &&
360 matchesThreadSnapshot(
361 committed,
362 snapshot.projection,
363 snapshot.snapshotSequence,
364 historyMetaFromCachedSnapshot(snapshot),
365 )
366 )
367 return;
368 yield* cache.saveThread(environmentId, snapshot).pipe(
369 Effect.tap(() =>
370 Effect.sync(() => {
371 savedSnapshot = snapshot;
372 if (
373 !matchesThreadSnapshot(
374 committed,
375 snapshot.projection,
376 snapshot.snapshotSequence,
377 historyMetaFromCachedSnapshot(snapshot),
378 )
379 )
380 return;
381 committed = { ...committed, persisted: true };
382 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
383 }),
384 ),
385 Effect.catch((error) =>
386 Effect.logWarning("Could not persist the thread cache.").pipe(
387 Effect.annotateLogs({
388 environmentId,
389 threadId,
390 error: error.message,
391 }),
392 ),
393 ),
394 );
395 });
396
397 yield* Effect.addFinalizer(() =>
398 Effect.suspend(() => {
399 const { state: current, sequence: snapshotSequence } = committed;
400 return Option.match(current.data, {
401 onNone: () => Effect.void,
402 onSome: (projection) =>
403 !current.history.expanded
404 ? persist(
405 snapshotToPersist(
406 snapshotSequence,
407 projection,
408 current.history,
409 committed.acceptsBoundedSnapshots === true,
410 ),
411 )
412 : // The consumer may still be waiting out its delay; an expanded thread queues
413 // only cache repairs, which must survive leaving the thread.
414 queuedSnapshot !== undefined && queuedSnapshot !== savedSnapshot
415 ? persist(queuedSnapshot)
416 : Effect.void,
417 });
418 }),
419 );
420
421 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
422
423 const setConnecting = SubscriptionRef.update(state, (current) =>
424 current.status === "deleted" || Option.isSome(current.error)
425 ? current
426 : {
427 ...current,
428 status: "synchronizing" as const,
429 error: Option.none(),
430 },
431 );
432 const setReady = SubscriptionRef.update(state, (current) =>
433 current.status === "live" || current.status === "deleted" || Option.isSome(current.error)
434 ? current
435 : {
436 ...current,
437 status: "synchronizing" as const,
438 error: Option.none(),
439 },
440 );
441 const setDisconnected = Effect.gen(function* () {
442 yield* Ref.set(awaitingCompletion, false);
443 yield* SubscriptionRef.update(state, (current) => ({
444 ...current,
445 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
446 }));
447 });
448 const setStreamError = (message: string) =>
449 Ref.set(awaitingCompletion, false).pipe(
450 Effect.andThen(
451 SubscriptionRef.update(state, (current) => ({
452 ...current,
453 status:
454 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
455 error: Option.some(message),
456 })),
457 ),
458 );
459
460 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
461 thread: OrchestrationV2ThreadProjection,
462 options?: {
463 readonly resetHistory?: boolean;
464 readonly history?: ThreadHistoryMeta;
465 },
466 ) {
467 const waiting = yield* Ref.get(awaitingCompletion);
468 const sequence = yield* SubscriptionRef.get(lastSequence);
469 // Atomic with concurrent history meta updates: never get-then-set the whole
470 // state when only the projection changes. Bounded installs pass history so
471 // projection + cursor persist together in one enqueue.
472 const next = yield* SubscriptionRef.updateAndGet(state, (previous) => {
473 const history =
474 options?.history !== undefined
475 ? options.history
476 : options?.resetHistory === true
477 ? EMPTY_THREAD_HISTORY_META
478 : previous.history;
479 return {
480 ...previous,
481 data: Option.some(thread),
482 status: Option.isSome(previous.error)
483 ? ("cached" as const)
484 : waiting
485 ? ("synchronizing" as const)
486 : ("live" as const),
487 error: previous.error,
488 history,
489 sequence,
490 };
491 });
492 // Active projections can update many times per second and retain large tool
493 // payloads. Persist once the run settles so cache encoding stays off the
494 // streaming path. Progressive meta rides along when the window is incomplete.
495 if (shouldPersistThread(thread, next.history)) {
496 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
497 yield* queuePersist(
498 snapshotToPersist(
499 snapshotSequence,
500 thread,
501 next.history,
502 yield* Ref.get(acceptsBoundedSocketSnapshots),
503 ),
504 );
505 }
506 });
507
508 const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) =>
509 SubscriptionRef.update(state, (current) => ({
510 ...current,
511 history: patch(current.history),
512 }));
513
514 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
515 yield* Ref.set(awaitingCompletion, false);
516 yield* SubscriptionRef.set(state, {
517 data: Option.none(),
518 status: "deleted",
519 error: Option.none(),
520 history: EMPTY_THREAD_HISTORY_META,
521 sequence: yield* SubscriptionRef.get(lastSequence),
522 });
523 yield* remember;
524 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
525 yield* cache.removeThread(environmentId, threadId).pipe(
526 Effect.catch((error) =>
527 Effect.logWarning("Could not remove the cached thread.").pipe(
528 Effect.annotateLogs({
529 environmentId,
530 threadId,
531 error: error.message,
532 }),
533 ),
534 ),
535 );
536 });
537
538 type EventItem = Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }>;
539 type SequencedItem = Extract<
540 OrchestrationV2ThreadStreamItem,
541 { kind: "event" | "unknown-event" }
542 >;
543 // Per-batch streaming spans add trace volume without a useful timing boundary.
544 const applyEventsLocked = Effect.fnUntraced(function* (items: ReadonlyArray<SequencedItem>) {
545 const appliedSequence = yield* SubscriptionRef.get(lastSequence);
546 let sequence = appliedSequence;
547 const fresh: EventItem[] = [];
548 for (const item of items) {
549 if (item.sequence <= sequence) continue;
550 sequence = item.sequence;
551 if (item.kind === "event") {
552 fresh.push(item);
553 continue;
554 }
555 yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe(
556 Effect.annotateLogs({
557 environmentId,
558 threadId,
559 eventType: item.eventType.slice(0, 64),
560 sequence: item.sequence,
561 }),
562 );
563 }
564 if (sequence === appliedSequence) return;
565 yield* SubscriptionRef.set(lastSequence, sequence);
566 if (fresh.length === 0) return;
567
568 const waiting = yield* Ref.get(awaitingCompletion);
569 // Apply against the latest projection/history in one update so a concurrent
570 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
571 // get-then-set rebuild.
572 type EventApplyResult =
573 | { readonly _tag: "noop" }
574 | { readonly _tag: "delete" }
575 | {
576 readonly _tag: "applied";
577 readonly projection: OrchestrationV2ThreadProjection;
578 readonly history: ThreadHistoryMeta;
579 };
580
581 const applyEvent = (
582 current: EnvironmentThreadState,
583 item: EventItem,
584 ): readonly [EventApplyResult, EnvironmentThreadState] => {
585 if (current.status === "deleted") {
586 return [{ _tag: "noop" }, current];
587 }
588 if (Option.isNone(current.data)) {
589 return [
590 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
591 current,
592 ];
593 }
594 if (item.event.type === "thread.deleted") {
595 return [{ _tag: "delete" }, current];
596 }
597
598 // Incomplete progressive windows only (hasMore or open cursor). Do not
599 // use expanded: it remains true after the last page as a cache marker.
600 const partial =
601 current.history.hasMoreHistory || current.history.historyCursor !== null
602 ? {
603 partialTimeline: true as const,
604 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
605 }
606 : undefined;
607 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
608 if (next === null || next === current.data.value) {
609 return [{ _tag: "noop" }, current];
610 }
611
612 let history = current.history;
613 if (partial !== undefined && item.event.type === "turn-item.updated") {
614 const ordinal = item.event.payload.ordinal;
615 const watermark = history.latestLocalTurnOrdinal;
616 if (watermark === null || ordinal > watermark) {
617 history = { ...history, latestLocalTurnOrdinal: ordinal };
618 }
619 }
620
621 const updated: EnvironmentThreadState = {
622 ...current,
623 data: Option.some(next),
624 status: waiting ? "synchronizing" : "live",
625 error: Option.none(),
626 history,
627 };
628 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
629 };
630
631 const result = yield* SubscriptionRef.modify(
632 state,
633 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
634 let result: EventApplyResult = { _tag: "noop" };
635 for (const item of fresh) {
636 const [applied, next] = applyEvent(current, item);
637 current = next;
638 if (applied._tag !== "noop") result = applied;
639 if (applied._tag === "delete") break;
640 }
641 // A batch that changed nothing keeps its state object, so readers do not re-render.
642 return [result, result._tag === "noop" ? current : { ...current, sequence }];
643 },
644 );
645
646 if (result._tag === "delete") {
647 yield* setDeleted();
648 return;
649 }
650 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
651 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
652 yield* queuePersist(
653 snapshotToPersist(
654 snapshotSequence,
655 result.projection,
656 result.history,
657 yield* Ref.get(acceptsBoundedSocketSnapshots),
658 ),
659 );
660 }
661 });
662
663 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
664 item: OrchestrationV2ThreadStreamItem,
665 ) {
666 if (item.kind === "synchronized") {
667 yield* Ref.set(awaitingCompletion, false);
668 yield* SubscriptionRef.update(state, (current) =>
669 Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error)
670 ? { ...current, status: "live" as const, error: Option.none() }
671 : current,
672 );
673 return;
674 }
675
676 if (item.kind === "snapshot") {
677 yield* Ref.set(forceSnapshot, false);
678 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
679 const hasProgressiveHistory =
680 item.historyCursor !== undefined ||
681 item.hasMoreHistory !== undefined ||
682 item.latestLocalTurnOrdinal !== undefined;
683 yield* setThread(
684 boundedSnapshotProjection(item),
685 hasProgressiveHistory
686 ? {
687 history: {
688 historyCursor: item.historyCursor ?? null,
689 hasMoreHistory: item.hasMoreHistory ?? false,
690 loading: false,
691 error: null,
692 expanded: false,
693 latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null,
694 },
695 }
696 : { resetHistory: true },
697 );
698 return;
699 }
700
701 yield* applyEventsLocked([item]);
702 });
703
704 // Keep this per-batch streaming path untraced for the same reason as applyEventsLocked.
705 const applyItems = Effect.fnUntraced(function* (
706 items: ReadonlyArray<OrchestrationV2ThreadStreamItem>,
707 ) {
708 yield* applyLock.withPermits(1)(
709 Effect.gen(function* () {
710 let events: SequencedItem[] = [];
711 for (const item of items) {
712 if (
713 item.kind === "unknown-event" ||
714 (item.kind === "event" && item.event.type !== "thread.deleted")
715 ) {
716 events.push(item);
717 continue;
718 }
719 yield* applyEventsLocked(events);
720 events = [];
721 yield* applyItemLocked(item);
722 }
723 yield* applyEventsLocked(events);
724 yield* remember;
725 }),
726 );
727 });
728
729 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* (
730 throughEntryId?: string,
731 workAnchorId?: string,
732 ): Effect.fn.Return<ThreadHistoryController.ThreadHistoryLoadEarlierResult> {
733 const workCursor = (latest: EnvironmentThreadState) =>
734 Option.getOrNull(latest.data)?.visibleTurnItems.find(
735 (row) => row.sourceItemId === workAnchorId,
736 )?.item.deferredWork?.cursor ?? null;
737 const current = yield* SubscriptionRef.get(state);
738 const initialCursor =
739 workAnchorId === undefined ? current.history.historyCursor : workCursor(current);
740 if (
741 current.status === "deleted" ||
742 Option.isNone(current.data) ||
743 initialCursor === null ||
744 (workAnchorId === undefined && !current.history.hasMoreHistory)
745 )
746 return { _tag: "noop" };
747 if (workAnchorId === undefined && current.history.loading) return { _tag: "busy" };
748 let requestCursor = initialCursor;
749 const isCurrent = (latest: EnvironmentThreadState) =>
750 workAnchorId === undefined
751 ? isActiveHistoryRequestCursor(requestCursor, latest.history)
752 : workCursor(latest) === requestCursor;
753 const staleResult = (
754 latest: EnvironmentThreadState,
755 ): ThreadHistoryController.ThreadHistoryLoadEarlierResult =>
756 workAnchorId !== undefined && workCursor(latest) !== null
757 ? { _tag: "error", message: WORK_HISTORY_CHANGED_ERROR }
758 : { _tag: "noop" };
759 if (workAnchorId === undefined)
760 yield* patchHistoryMeta((history) =>
761 isActiveHistoryRequestCursor(requestCursor, history)
762 ? { ...history, loading: true, error: null }
763 : history,
764 );
765 const failLoad = (message: string) =>
766 SubscriptionRef.modify(
767 state,
768 (
769 latest,
770 ): readonly [
771 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
772 EnvironmentThreadState,
773 ] =>
774 isCurrent(latest)
775 ? [
776 { _tag: "error", message },
777 {
778 ...latest,
779 history:
780 workAnchorId === undefined
781 ? { ...latest.history, loading: false, error: message }
782 : latest.history,
783 },
784 ]
785 : [staleResult(latest), latest],
786 );
787
788 const runLoad = Effect.gen(function* () {
789 while (true) {
790 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
791 if (Option.isNone(preparedOption) || Option.isNone(httpClient))
792 return yield* failLoad("Environment is not connected.");
793 const views =
794 workAnchorId !== undefined
795 ? ["work" as const]
796 : throughEntryId === undefined
797 ? [undefined]
798 : ["conversation" as const, undefined];
799 let nextCursor: string | null = null;
800 for (const view of views) {
801 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
802 prepared: preparedOption.value,
803 threadId,
804 cursor: requestCursor,
805 throughEntryId: workAnchorId ?? throughEntryId,
806 view,
807 signer: dpopSigner,
808 remoteAuthorization,
809 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
810 if (Result.isFailure(pageResult))
811 return yield* failLoad(formatHistoryError(pageResult.failure));
812 const page = pageResult.success;
813 const complete = view !== "conversation";
814 const keepPaging =
815 complete &&
816 (workAnchorId !== undefined
817 ? page.nextCursor !== null
818 : throughEntryId === undefined &&
819 page.hasMoreHistory &&
820 !page.items.some(({ item }) => startsTurn(item)));
821 if (keepPaging && (page.nextCursor === null || page.nextCursor === requestCursor))
822 return yield* failLoad(
823 workAnchorId === undefined
824 ? "History did not advance."
825 : "Work history did not advance.",
826 );
827 const waiting = yield* Ref.get(awaitingCompletion);
828 const result = yield* applyLock.withPermits(1)(
829 SubscriptionRef.modify(
830 state,
831 (
832 latest,
833 ): readonly [
834 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
835 EnvironmentThreadState,
836 ] => {
837 if (!isCurrent(latest)) return [staleResult(latest), latest];
838 if (Option.isNone(latest.data) || latest.status === "deleted")
839 return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }];
840 return [
841 { _tag: "loaded" },
842 {
843 ...latest,
844 data: Option.some(
845 mergeOlderSubagentsIntoProjection(
846 mergeOlderHistoryIntoProjection(
847 latest.data.value,
848 page.items,
849 workAnchorId === undefined
850 ? undefined
851 : { anchorId: workAnchorId, nextCursor: page.nextCursor },
852 ),
853 page.subagents,
854 ),
855 ),
856 status:
857 workAnchorId === undefined && complete && waiting
858 ? "synchronizing"
859 : latest.status,
860 history:
861 workAnchorId === undefined && complete
862 ? { ...applyHistoryPageMeta(latest.history, page), loading: keepPaging }
863 : { ...latest.history, expanded: true },
864 },
865 ];
866 },
867 ),
868 );
869 if (result._tag !== "loaded") return result;
870 if (complete) yield* applyLock.withPermits(1)(remember);
871 nextCursor = keepPaging ? page.nextCursor : null;
872 }
873 if (nextCursor === null) return { _tag: "loaded" } as const;
874 requestCursor = nextCursor;
875 }
876 });
877 return yield* runLoad.pipe(
878 Effect.onInterrupt(() =>
879 SubscriptionRef.update(state, (latest) => ({
880 ...latest,
881 history: clearActiveHistoryLoading(requestCursor, latest.history),
882 })),
883 ),
884 );
885 });
886
887 // A cached item can stay running after the server finished it, and no event will ever
888 // name it again: it can sit outside every bounded window, and a repeated Stop records
889 // nothing new. Stop asks the server about each pending item instead of
890 // inferring status from what a snapshot omits, and settles only those items.
891 const reconcilePendingWork = Effect.fn("EnvironmentThreadState.reconcilePendingWork")(
892 function* () {
893 const current = yield* SubscriptionRef.get(state);
894 if (current.status === "deleted" || Option.isNone(current.data)) return;
895 const pending = pendingBackgroundTurnItems(current.data.value);
896 if (pending.length === 0) return;
897 const queried = new Set<string>(pending.map((item) => item.id));
898 const fetched = yield* Effect.forEach(
899 pending,
900 (item) =>
901 request(ORCHESTRATION_V2_WS_METHODS.getTurnItem, { threadId, itemId: item.id }).pipe(
902 Effect.timeout("10 seconds"),
903 Effect.map((result) => result.item),
904 Effect.orElseSucceed(() => null),
905 ),
906 { concurrency: 4 },
907 );
908 const settled = new Map(
909 fetched.flatMap((item) =>
910 item === null || isOrchestrationV2WorkActive(item.status) ? [] : [[item.id, item]],
911 ),
912 );
913 yield* applyLock.withPermits(1)(
914 Effect.gen(function* () {
915 const latest = yield* SubscriptionRef.get(state);
916 if (latest.status === "deleted" || Option.isNone(latest.data)) return;
917 const thread = settleTurnItems(threadId, latest.data.value, settled);
918 if (thread !== latest.data.value) {
919 yield* setThread(thread);
920 yield* remember;
921 }
922 // An expanded timeline is never saved, so reload would bring the stale row back.
923 // Repair the snapshot last handed to the cache instead, keeping its window and cursor.
924 // A resumed state skipped the cache load, so read the saved snapshot then.
925 if (shouldPersistThread(thread, latest.history)) return;
926 // A terminal event that landed during the lookup is newer than any reply, and the
927 // expanded live state never saves it, whatever the lookup returned.
928 const latestItems = new Map(settled);
929 for (const item of thread.turnItems) {
930 if (queried.has(item.id) && !isOrchestrationV2WorkActive(item.status)) {
931 latestItems.set(item.id, item);
932 }
933 }
934 if (latestItems.size === 0) return;
935 const saved =
936 queuedSnapshot ??
937 Option.getOrUndefined(
938 yield* cache
939 .loadThread(environmentId, threadId)
940 .pipe(Effect.orElseSucceed(() => Option.none())),
941 );
942 if (saved === undefined) return;
943 const projection = settleTurnItems(threadId, saved.projection, latestItems);
944 if (projection !== saved.projection) yield* queuePersist({ ...saved, projection });
945 }),
946 );
947 },
948 );
949
950 if (Option.isSome(historyController)) {
951 const scope = yield* Scope.Scope;
952 const registration = yield* historyController.value.register(environmentId, threadId, {
953 loadEarlier: (throughEntryId, workAnchorId) =>
954 loadEarlier(throughEntryId, workAnchorId).pipe(
955 Effect.forkIn(scope),
956 Effect.flatMap(Fiber.join),
957 ),
958 reconcilePendingWork: () =>
959 reconcilePendingWork().pipe(
960 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
961 Effect.forkIn(scope),
962 Effect.flatMap(Fiber.join),
963 ),
964 });
965 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
966 }
967
968 yield* SubscriptionRef.changes(supervisor.state).pipe(
969 Stream.runForEach((connectionState) => {
970 switch (connectionProjectionPhase(connectionState)) {
971 case "synchronizing":
972 return setConnecting;
973 case "disconnected":
974 return setDisconnected;
975 case "ready":
976 return setReady;
977 }
978 }),
979 Effect.forkScoped,
980 );
981
982 const foregroundResubscriptions = Option.match(wakeups, {
983 onNone: () => Stream.never,
984 onSome: (service) =>
985 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
986 });
987
988 // Only the first subscription after a warm live resume keeps the retained
989 // status. A replacement session or foreground resubscribe on the same scope
990 // may have missed events, so those show sync progress until confirmed.
991 const resumingLive = yield* Ref.make(initialState.status === "live");
992 // A cold open tries the socket snapshot once. Any later cold attempt, after a
993 // failure or a dropped session, asks HTTP, which also tells a missing thread
994 // apart from a failed load.
995 const socketOpenTried = yield* Ref.make(false);
996 const socketOnlyOpen = yield* Ref.make(false);
997 const failedSocketOnlyOpen = Effect.gen(function* () {
998 return (
999 (yield* Ref.get(socketOnlyOpen)) && Option.isNone((yield* SubscriptionRef.get(state)).data)
1000 );
1001 });
1002 // A stream defect parks the subscription until something resubscribes it.
1003 const resubscribes = yield* Queue.unbounded<void>();
1004 // A resumed replay that dies (an event this client cannot decode) dies the same
1005 // way from the same cursor, so later attempts reload the full snapshot until one applies.
1006 const resuming = yield* Ref.make(false);
1007 const forceSnapshot = yield* Ref.make(false);
1008 const markSynchronizing = Effect.gen(function* () {
1009 if (yield* Ref.get(resumingLive)) return;
1010 yield* SubscriptionRef.update(state, (current) =>
1011 current.status === "deleted"
1012 ? current
1013 : { ...current, status: "synchronizing" as const, error: Option.none() },
1014 );
1015 });
1016
1017 yield* markSynchronizing;
1018 // A 404 can arrive before the thread exists, so a miss asks HTTP again while mounted.
1019 let httpMisses = 0;
1020 let defectRetries = 0;
1021 const backOffAfterDefect = Effect.suspend(() => {
1022 const retryDelay = subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, defectRetries);
1023 defectRetries += 1;
1024 return setStreamError(THREAD_SYNC_ERROR).pipe(Effect.andThen(Effect.sleep(retryDelay)));
1025 });
1026 const followThread = (): Effect.Effect<
1027 void,
1028 never,
1029 EnvironmentSupervisor.EnvironmentSupervisor
1030 > =>
1031 subscribeDynamic(
1032 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
1033 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
1034 let current = yield* SubscriptionRef.get(state);
1035 // A delete event already cleared this thread. Park without opening the socket.
1036 if (current.status === "deleted" && httpMisses === 0) {
1037 return yield* Effect.never;
1038 }
1039
1040 const config = yield* Effect.option(session.initialConfig);
1041 yield* Ref.set(awaitingCompletion, true);
1042 yield* markSynchronizing;
1043 yield* Ref.set(resumingLive, false);
1044
1045 // A server that pages snapshots sends the same bounded window over the
1046 // socket, so a cold open can skip the HTTP round trip.
1047 const socketOnly =
1048 Option.isNone(current.data) &&
1049 canLoadHistory &&
1050 Option.exists(config, (value) => value.threadSnapshotPagination === true) &&
1051 !(yield* Ref.getAndSet(socketOpenTried, true));
1052 yield* Ref.set(socketOnlyOpen, socketOnly);
1053
1054 if (Option.isNone(current.data) && !socketOnly) {
1055 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
1056 Effect.flatMap(
1057 Option.match({
1058 onSome: Effect.succeed,
1059 onNone: () =>
1060 SubscriptionRef.changes(supervisor.prepared).pipe(
1061 Stream.filter(Option.isSome),
1062 Stream.map((value) => value.value),
1063 Stream.runHead,
1064 Effect.map(Option.getOrThrow),
1065 ),
1066 }),
1067 ),
1068 );
1069 const httpResult: ThreadSnapshotLoader.ThreadSnapshotLoadResult =
1070 yield* snapshotLoader.load(prepared, threadId);
1071 switch (httpResult._tag) {
1072 case "present": {
1073 httpMisses = 0;
1074 if (canLoadHistory && httpResult.history !== undefined) {
1075 yield* Ref.set(acceptsBoundedSocketSnapshots, true);
1076 }
1077 // Atomic projection + progressive meta so a settled bounded window
1078 // never persists as a complete full-timeline cache entry. Socket
1079 // snapshots still go through applyItem (resetHistory).
1080 yield* applyLock.withPermits(1)(
1081 Effect.gen(function* () {
1082 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
1083 const history: ThreadHistoryMeta =
1084 httpResult.history !== undefined
1085 ? {
1086 historyCursor: httpResult.history.historyCursor,
1087 hasMoreHistory: httpResult.history.hasMoreHistory,
1088 loading: false,
1089 error: null,
1090 expanded: false,
1091 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
1092 }
1093 : EMPTY_THREAD_HISTORY_META;
1094 yield* setThread(httpResult.snapshot.projection, { history });
1095 yield* remember;
1096 }),
1097 );
1098 current = yield* SubscriptionRef.get(state);
1099 break;
1100 }
1101 case "missing": {
1102 if (current.status !== "deleted") yield* setDeleted();
1103 // A 404 also means "not created yet". Only a delete event may outlive this mount.
1104 if (resumeCache?.owner === owner) resumeCache.snapshot = undefined;
1105 yield* Effect.sleep(
1106 subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, httpMisses++),
1107 );
1108 yield* Queue.offer(resubscribes, undefined);
1109 return yield* Effect.never;
1110 }
1111 case "unavailable": {
1112 break;
1113 }
1114 }
1115 }
1116
1117 const sequence = yield* SubscriptionRef.get(lastSequence);
1118 const canResume = Option.isSome(current.data) && !(yield* Ref.get(forceSnapshot));
1119 yield* Ref.set(resuming, canResume);
1120 const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots);
1121
1122 return {
1123 threadId,
1124 ...(canResume ? { afterSequence: sequence } : {}),
1125 requestCompletionMarker: true as const,
1126 ...(acceptBoundedSnapshot
1127 ? {
1128 acceptBoundedSnapshot: true as const,
1129 acceptDeferredWork: true as const,
1130 acceptCompactTurnItems: true as const,
1131 acceptCompactIds: true as const,
1132 }
1133 : {}),
1134 acceptDedupedBodies: true as const,
1135 };
1136 }),
1137 {
1138 // A socket-only open that fails retries over HTTP, which tells a
1139 // missing thread apart from a failure, before showing an error.
1140 onDefect: Effect.fn("EnvironmentThreadState.onDefect")(function* (cause) {
1141 if (yield* failedSocketOnlyOpen) {
1142 yield* Ref.set(socketOnlyOpen, false);
1143 return yield* Queue.offer(resubscribes, undefined);
1144 }
1145 if (!Cause.hasDies(cause)) {
1146 return yield* setStreamError(THREAD_SYNC_ERROR);
1147 }
1148 yield* Ref.set(forceSnapshot, true);
1149 if (yield* Ref.getAndSet(resuming, false)) {
1150 return yield* Queue.offer(resubscribes, undefined);
1151 }
1152 yield* backOffAfterDefect;
1153 yield* Queue.offer(resubscribes, undefined);
1154 }),
1155 onExpectedFailure: Effect.fn("EnvironmentThreadState.onExpectedFailure")(function* (cause) {
1156 const retryOverHttp = !isAuthorizationFailure(cause) && (yield* failedSocketOnlyOpen);
1157 if (!retryOverHttp) yield* setStreamError(formatThreadError(cause));
1158 }),
1159 retryExpectedFailureAfter: THREAD_SUBSCRIPTION_RETRY_DELAY,
1160 resubscribe: Stream.merge(foregroundResubscriptions, Stream.fromQueue(resubscribes)),
1161 },
1162 ).pipe(
1163 Stream.runForEachArray((items) =>
1164 applyItems(items).pipe(
1165 Effect.andThen(
1166 Effect.sync(() => {
1167 defectRetries = 0;
1168 }),
1169 ),
1170 ),
1171 ),
1172 // A defect while applying items ends the stream; resubscribe for a fresh snapshot.
1173 Effect.catchCause((cause) =>
1174 Cause.hasInterrupts(cause)
1175 ? Effect.interrupt
1176 : Effect.logWarning("Thread subscription failed; resubscribing.", {
1177 cause: Cause.pretty(cause),
1178 environmentId,
1179 threadId,
1180 }).pipe(
1181 Effect.andThen(Ref.set(forceSnapshot, true)),
1182 Effect.andThen(backOffAfterDefect),
1183 Effect.andThen(Effect.suspend(followThread)),
1184 ),
1185 ),
1186 );
1187 yield* Effect.forkScoped(followThread());
1188
1189 return state;
1190});
1191
1192function threadStateChanges(
1193 environmentId: EnvironmentIdType,
1194 threadId: ThreadIdType,
1195 resumeCache?: ThreadResumeCache,
1196) {
1197 return followStreamInEnvironment(
1198 environmentId,
1199 Stream.unwrap(
1200 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
1201 ),
1202 );
1203}
1204
1205export function createEnvironmentThreadStateAtoms<R, E>(
1206 runtime: Atom.AtomRuntime<
1207 | EnvironmentRegistry.EnvironmentRegistry
1208 | Persistence.EnvironmentCacheStore
1209 | ThreadSnapshotLoader.ThreadSnapshotLoader
1210 | R,
1211 E
1212 >,
1213) {
1214 // Cache definitions must outlive collectible live-atom definitions. The
1215 // registry retains these nodes without retaining environment or RPC scopes.
1216 const resumeFamily = Atom.family((key: string) =>
1217 Atom.make((): ThreadResumeCache => ({
1218 snapshot: undefined,
1219 owner: undefined,
1220 })).pipe(
1221 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
1222 Atom.withLabel(`environment-thread-resume:${key}`),
1223 ),
1224 );
1225 const family = Atom.family((key: string) => {
1226 const { environmentId, threadId } = parseThreadKey(key);
1227 const resumeAtom = resumeFamily(key);
1228 return runtime
1229 .atom(
1230 (get) => {
1231 get.mount(resumeAtom);
1232 const resume = get.once(resumeAtom);
1233 const live = threadStateChanges(environmentId, threadId, resume);
1234 return resume.snapshot === undefined
1235 ? live
1236 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
1237 },
1238 {
1239 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
1240 },
1241 )
1242 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
1243 });
1244
1245 return {
1246 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
1247 family(threadKey({ environmentId, threadId })),
1248 };
1249}
1250
1251export * from "./archivedThreads.ts";
1252export * from "./checkpointDiff.ts";
1253export * as BoundedThreadSnapshotLoader from "./boundedThreadSnapshotHttp.ts";
1254export * as ThreadHistoryController from "./threadHistoryController.ts";
1255export type { ThreadHistoryLoadEarlierResult } from "./threadHistoryController.ts";
1256export * from "./threadHistoryMerge.ts";
1257export * from "./threadSnapshotHttp.ts";
1258export * from "./composerPathSearch.ts";
1259export * from "./threadCommands.ts";
1260export * from "./threadFeedback.ts";
1261export * from "./threadDetail.ts";
1262export * from "./threadFamilies.ts";
1263export * from "./olderSettledThreads.ts";
1264export * from "./threadShell.ts";
1265export * from "./threadState.ts";
1266export * from "./threadTagFilter.ts";