Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationThread,
5 type OrchestrationThreadDetailSnapshot,
6 type OrchestrationThreadStreamItem,
7 type ThreadId as ThreadIdType,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import { Atom } from "effect/unstable/reactivity";
17
18import { EnvironmentRegistry } from "../connection/registry.ts";
19import { connectionProjectionPhase } from "../connection/model.ts";
20import { EnvironmentSupervisor } from "../connection/supervisor.ts";
21import * as ConnectionWakeups from "../connection/wakeups.ts";
22import { EnvironmentCacheStore } from "../platform/persistence.ts";
23import { subscribeDynamic } from "../rpc/client.ts";
24import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
25import { parseThreadKey, threadKey } from "./entities.ts";
26import { applyThreadDetailEvent } from "./threadReducer.ts";
27import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
28import { followStreamInEnvironment } from "./runtime.ts";
29import {
30 EMPTY_ENVIRONMENT_THREAD_STATE,
31 type EnvironmentThreadState,
32 type EnvironmentThreadStatus,
33} from "./threadState.ts";
34
35function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
36 return Option.isSome(data) ? "cached" : "empty";
37}
38
39function formatThreadError(cause: Cause.Cause<unknown>): string {
40 const error = Cause.squash(cause);
41 return error instanceof Error && error.message.trim().length > 0
42 ? error.message
43 : "Could not synchronize the thread.";
44}
45
46function shouldPersistThread(thread: OrchestrationThread): boolean {
47 const status = thread.session?.status;
48 return status !== "starting" && status !== "running";
49}
50
51export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
52 threadId: ThreadIdType,
53) {
54 const supervisor = yield* EnvironmentSupervisor;
55 const cache = yield* EnvironmentCacheStore;
56 const snapshotLoader = yield* ThreadSnapshotLoader;
57 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
58 const environmentId = supervisor.target.environmentId;
59 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
60 Effect.catch((error) =>
61 Effect.logWarning("Could not load cached thread.").pipe(
62 Effect.annotateLogs({
63 environmentId,
64 threadId,
65 error: error.message,
66 }),
67 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
68 ),
69 ),
70 );
71 const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
72 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
73 data: cachedThread,
74 status: statusWithoutLiveData(cachedThread),
75 error: Option.none(),
76 });
77 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
78 // via `afterSequence` instead of re-downloading the full thread body.
79 const lastSequence = yield* SubscriptionRef.make(
80 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
81 );
82 const awaitingCompletion = yield* Ref.make(false);
83 const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
84
85 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
86 snapshot: OrchestrationThreadDetailSnapshot,
87 ) {
88 yield* cache.saveThread(environmentId, snapshot).pipe(
89 Effect.catch((error) =>
90 Effect.logWarning("Could not persist the thread cache.").pipe(
91 Effect.annotateLogs({
92 environmentId,
93 threadId,
94 error: error.message,
95 }),
96 ),
97 ),
98 );
99 });
100
101 yield* Stream.fromQueue(persistence).pipe(
102 Stream.debounce("500 millis"),
103 Stream.runForEach(persist),
104 Effect.forkScoped,
105 );
106
107 const setSynchronizing = SubscriptionRef.update(state, (current) =>
108 current.status === "deleted"
109 ? current
110 : {
111 ...current,
112 status: "synchronizing" as const,
113 error: Option.none(),
114 },
115 );
116 const setReady = SubscriptionRef.update(state, (current) =>
117 current.status === "live" || current.status === "deleted"
118 ? current
119 : {
120 ...current,
121 status: "synchronizing" as const,
122 error: Option.none(),
123 },
124 );
125 const setDisconnected = Effect.gen(function* () {
126 yield* Ref.set(awaitingCompletion, false);
127 yield* SubscriptionRef.update(state, (current) => ({
128 ...current,
129 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
130 }));
131 });
132 const setStreamError = (cause: Cause.Cause<unknown>) =>
133 Ref.set(awaitingCompletion, false).pipe(
134 Effect.andThen(
135 SubscriptionRef.update(state, (current) => ({
136 ...current,
137 status:
138 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
139 error: Option.some(formatThreadError(cause)),
140 })),
141 ),
142 );
143
144 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
145 thread: OrchestrationThread,
146 ) {
147 const waiting = yield* Ref.get(awaitingCompletion);
148 yield* SubscriptionRef.set(state, {
149 data: Option.some(thread),
150 status: waiting ? "synchronizing" : "live",
151 error: Option.none(),
152 });
153 // Active threads can update many times per second and retain large tool
154 // payloads. The server remains the source of truth while a turn is active;
155 // persist once it settles so cache encoding stays off the streaming path.
156 if (shouldPersistThread(thread)) {
157 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
158 yield* Queue.offer(persistence, { snapshotSequence, thread });
159 }
160 });
161
162 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
163 yield* Ref.set(awaitingCompletion, false);
164 yield* SubscriptionRef.set(state, {
165 data: Option.none(),
166 status: "deleted",
167 error: Option.none(),
168 });
169 yield* cache.removeThread(environmentId, threadId).pipe(
170 Effect.catch((error) =>
171 Effect.logWarning("Could not remove the cached thread.").pipe(
172 Effect.annotateLogs({
173 environmentId,
174 threadId,
175 error: error.message,
176 }),
177 ),
178 ),
179 );
180 });
181
182 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
183 item: OrchestrationThreadStreamItem,
184 ) {
185 if (item.kind === "synchronized") {
186 yield* Ref.set(awaitingCompletion, false);
187 yield* SubscriptionRef.update(state, (current) =>
188 Option.isSome(current.data) && current.status !== "deleted"
189 ? { ...current, status: "live" as const, error: Option.none() }
190 : current,
191 );
192 return;
193 }
194
195 if (item.kind === "snapshot") {
196 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
197 yield* setThread(item.snapshot.thread);
198 return;
199 }
200
201 const sequence = yield* SubscriptionRef.get(lastSequence);
202 if (item.event.sequence <= sequence) {
203 return;
204 }
205 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
206
207 const current = yield* SubscriptionRef.get(state);
208 if (Option.isNone(current.data)) {
209 if (item.event.type === "thread.deleted") {
210 yield* setDeleted();
211 }
212 return;
213 }
214 const result = applyThreadDetailEvent(current.data.value, item.event);
215 if (result.kind === "updated") {
216 yield* setThread(result.thread);
217 } else if (result.kind === "deleted") {
218 yield* setDeleted();
219 }
220 });
221
222 yield* SubscriptionRef.changes(supervisor.state).pipe(
223 Stream.runForEach((connectionState) => {
224 switch (connectionProjectionPhase(connectionState)) {
225 case "synchronizing":
226 return setSynchronizing;
227 case "disconnected":
228 return setDisconnected;
229 case "ready":
230 return setReady;
231 }
232 }),
233 Effect.forkScoped,
234 );
235
236 const foregroundResubscriptions = Option.match(wakeups, {
237 onNone: () => Stream.never,
238 onSome: (service) =>
239 service.changes.pipe(Stream.filter((reason) => reason === "application-active")),
240 });
241
242 yield* setSynchronizing;
243 yield* Effect.forkScoped(
244 subscribeDynamic(
245 ORCHESTRATION_WS_METHODS.subscribeThread,
246 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
247 const supportsCompletionMarker = yield* session.initialConfig.pipe(
248 Effect.map((config) => config.threadResumeCompletionMarker === true),
249 Effect.orElseSucceed(() => false),
250 );
251 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
252 yield* setSynchronizing;
253
254 let current = yield* SubscriptionRef.get(state);
255 if (Option.isNone(current.data) && current.status !== "deleted") {
256 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
257 Effect.flatMap(
258 Option.match({
259 onSome: Effect.succeed,
260 onNone: () =>
261 SubscriptionRef.changes(supervisor.prepared).pipe(
262 Stream.filter(Option.isSome),
263 Stream.map((value) => value.value),
264 Stream.runHead,
265 Effect.map(Option.getOrThrow),
266 ),
267 }),
268 ),
269 );
270 const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
271 if (Option.isSome(httpSnapshot)) {
272 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
273 current = yield* SubscriptionRef.get(state);
274 }
275 }
276
277 const sequence = yield* SubscriptionRef.get(lastSequence);
278 const canResume = Option.isSome(current.data);
279 if (!supportsCompletionMarker && canResume) {
280 yield* SubscriptionRef.update(state, (value) => ({
281 ...value,
282 status: value.status === "deleted" ? value.status : ("live" as const),
283 error: Option.none(),
284 }));
285 }
286
287 return {
288 threadId,
289 ...(canResume ? { afterSequence: sequence } : {}),
290 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
291 };
292 }),
293 {
294 onExpectedFailure: setStreamError,
295 retryExpectedFailureAfter: "250 millis",
296 resubscribe: foregroundResubscriptions,
297 },
298 ).pipe(Stream.runForEach(applyItem)),
299 );
300
301 yield* Effect.addFinalizer(() =>
302 Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
303 Effect.flatMap(([current, snapshotSequence]) =>
304 Option.match(current.data, {
305 onNone: () => Effect.void,
306 onSome: (thread) =>
307 shouldPersistThread(thread) ? persist({ snapshotSequence, thread }) : Effect.void,
308 }),
309 ),
310 ),
311 );
312
313 return state;
314});
315
316export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
317 return followStreamInEnvironment(
318 environmentId,
319 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
320 );
321}
322
323export function createEnvironmentThreadStateAtoms<R, E>(
324 runtime: Atom.AtomRuntime<
325 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
326 E
327 >,
328) {
329 const family = Atom.family((key: string) => {
330 const { environmentId, threadId } = parseThreadKey(key);
331 return runtime
332 .atom(threadStateChanges(environmentId, threadId), {
333 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
334 })
335 .pipe(
336 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
337 Atom.withLabel(`environment-thread-state:${key}`),
338 );
339 });
340
341 return {
342 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
343 family(threadKey({ environmentId, threadId })),
344 };
345}
346
347export * from "./archivedThreads.ts";
348export * from "./checkpointDiff.ts";
349export * from "./threadSnapshotHttp.ts";
350export * from "./composerPathSearch.ts";
351export * from "./threadCommands.ts";
352export * from "./threadDetail.ts";
353export * from "./threadReducer.ts";
354export * from "./threadShell.ts";
355export * from "./threadState.ts";