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

threads.ts

365 lines12.4 KB

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