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

threads.ts

354 lines12.2 KB

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";
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.";
45​
46function shouldPersistThread(thread: OrchestrationThread): boolean {
47 const status = thread.session?.status;
48 return status !== "starting" && status !== "running";
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) => service.changes.pipe(Stream.filter(ConnectionWakeups.wakeupResubscribes)),
239 });
240​
241 yield* setSynchronizing;
242 yield* Effect.forkScoped(
243 subscribeDynamic(
244 ORCHESTRATION_WS_METHODS.subscribeThread,
245 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
246 const supportsCompletionMarker = yield* session.initialConfig.pipe(
247 Effect.map((config) => config.threadResumeCompletionMarker === true),
248 Effect.orElseSucceed(() => false),
249 );
250 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
251 yield* setSynchronizing;
252​
253 let current = yield* SubscriptionRef.get(state);
254 if (Option.isNone(current.data) && current.status !== "deleted") {
255 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
256 Effect.flatMap(
257 Option.match({
258 onSome: Effect.succeed,
259 onNone: () =>
260 SubscriptionRef.changes(supervisor.prepared).pipe(
261 Stream.filter(Option.isSome),
262 Stream.map((value) => value.value),
263 Stream.runHead,
264 Effect.map(Option.getOrThrow),
265 ),
266 }),
267 ),
268 );
269 const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
270 if (Option.isSome(httpSnapshot)) {
271 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
272 current = yield* SubscriptionRef.get(state);
273 }
274 }
275​
276 const sequence = yield* SubscriptionRef.get(lastSequence);
277 const canResume = Option.isSome(current.data);
278 if (!supportsCompletionMarker && canResume) {
279 yield* SubscriptionRef.update(state, (value) => ({
280 ...value,
281 status: value.status === "deleted" ? value.status : ("live" as const),
282 error: Option.none(),
283 }));
284 }
285​
286 return {
287 threadId,
288 ...(canResume ? { afterSequence: sequence } : {}),
289 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
290 };
291 }),
292 {
293 onExpectedFailure: setStreamError,
294 retryExpectedFailureAfter: "250 millis",
295 resubscribe: foregroundResubscriptions,
296 },
297 ).pipe(Stream.runForEach(applyItem)),
298 );
299​
300 yield* Effect.addFinalizer(() =>
301 Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
302 Effect.flatMap(([current, snapshotSequence]) =>
303 Option.match(current.data, {
304 onNone: () => Effect.void,
305 onSome: (thread) =>
306 shouldPersistThread(thread) ? persist({ snapshotSequence, thread }) : Effect.void,
307 }),
308 ),
309 ),
310 );
311​
312 return state;
313});
314​
315export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
316 return followStreamInEnvironment(
317 environmentId,
318 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
319 );
321​
322export function createEnvironmentThreadStateAtoms<R, E>(
323 runtime: Atom.AtomRuntime<
324 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
325 E
326 >,
327) {
328 const family = Atom.family((key: string) => {
329 const { environmentId, threadId } = parseThreadKey(key);
330 return runtime
331 .atom(threadStateChanges(environmentId, threadId), {
332 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
333 })
334 .pipe(
335 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
336 Atom.withLabel(`environment-thread-state:${key}`),
337 );
338 });
339​
340 return {
341 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
342 family(threadKey({ environmentId, threadId })),
343 };
345​
346export * from "./archivedThreads.ts";
347export * from "./checkpointDiff.ts";
348export * from "./threadSnapshotHttp.ts";
349export * from "./composerPathSearch.ts";
350export * from "./threadCommands.ts";
351export * from "./threadDetail.ts";
352export * from "./threadReducer.ts";
353export * from "./threadShell.ts";
354export * from "./threadState.ts";