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

threadCommands.ts

443 lines14.5 KB

1import type { ThreadId } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import { Atom } from "effect/reactivity";
6import {
7 WS_METHODS,
8 type EnvironmentId,
9 type OrchestrationV2ShellSnapshot,
10} from "@t3tools/contracts";
11​
12import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts";
13import * as DateTime from "effect/DateTime";
14​
15import {
16 createAtomCommandScheduler,
17 createEnvironmentCommand,
18 createEnvironmentRpcCommand,
19} from "./runtime.ts";
20import {
21 type InterruptThreadTurnInput,
22 archiveThread,
23 closeGuestShare,
24 resolveGuestMessage,
25 cancelQueuedRun,
26 createThread,
27 deleteThread,
28 editQueuedRun,
29 interruptThreadTurn,
30 forkThreadFromRun,
31 markThreadUnread,
32 mergeThreadBack,
33 promoteQueuedRun,
34 resumeThreadQueue,
35 retryWorkspacePreparation,
36 linkThreadPullRequest,
37 respondToThreadApproval,
38 respondToThreadUserInput,
39 dismissThreadUserInput,
40 revertThreadCheckpoint,
41 setThreadInteractionMode,
42 setThreadRuntimeMode,
43 pinThread,
44 reorderPinnedThread,
45 reorderActiveThread,
46 setThreadAutoSettle,
47 settleThread,
48 snoozeThread,
49 startThreadTurn,
50 stopThreadSession,
51 unarchiveThread,
52 unlinkThreadPullRequest,
53 unpinThread,
54 unsettleThread,
55 unsnoozeThread,
56 updateThreadMetadata,
57 visitThread,
58 watchThreadPullRequest,
59} from "../operations/commands.ts";
60import type { EnvironmentRegistry } from "../connection/registry.ts";
61import * as EnvironmentSupervisor from "../connection/supervisor.ts";
62import * as ThreadHistoryController from "./threadHistoryController.ts";
63​
64export type LoadEarlierThreadHistoryInput = {
65 readonly threadId: ThreadId;
66 readonly throughEntryId?: string;
67};
68​
69export function createThreadEnvironmentAtoms<R, E>(
70 runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,
71 snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom<OrchestrationV2ShellSnapshot | null>,
72) {
73 const scheduler = createAtomCommandScheduler();
74 const concurrency = {
75 mode: "serial" as const,
76 key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
77 JSON.stringify([environmentId, input.threadId]),
78 };
79 const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (
80 input: LoadEarlierThreadHistoryInput,
81 ) {
82 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
83 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
84 if (Option.isNone(controller)) {
85 return {
86 _tag: "noop",
87 } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
88 }
89 return yield* controller.value.loadEarlier(
90 supervisor.target.environmentId,
91 input.threadId,
92 input.throughEntryId,
93 );
94 });
95​
96 // Runs whether or not the server accepted the interrupt, so a stale cached item still
97 // settles when Stop had nothing to interrupt; the interrupt's own failure still surfaces.
98 // The repair is detached: its lookups must not hold the thread's serial command key, and
99 // closing the thread cancels the repair, not the Stop that triggered it.
100 const interruptTurn = Effect.fn("ThreadCommands.interruptTurn")(function* (
101 input: InterruptThreadTurnInput,
102 ) {
103 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
104 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
105 return yield* interruptThreadTurn(input).pipe(
106 Effect.ensuring(
107 Option.match(controller, {
108 onNone: () => Effect.void,
109 onSome: (value) =>
110 value
111 .reconcilePendingWork(supervisor.target.environmentId, input.threadId)
112 .pipe(Effect.forkDetach, Effect.asVoid),
113 }),
114 ),
115 );
116 });
117​
118 const commands = {
119 create: createEnvironmentCommand(runtime, {
120 label: "environment-data:commands:thread:create",
121 execute: createThread,
122 scheduler,
123 concurrency,
124 }),
125 delete: createEnvironmentCommand(runtime, {
126 label: "environment-data:commands:thread:delete",
127 execute: deleteThread,
128 scheduler,
129 concurrency,
130 }),
131 closeGuestShare: createEnvironmentCommand(runtime, {
132 label: "environment-data:commands:thread:close-guest-share",
133 execute: closeGuestShare,
134 scheduler,
135 concurrency,
136 }),
137 resolveGuestMessage: createEnvironmentCommand(runtime, {
138 label: "environment-data:commands:thread:resolve-guest-message",
139 execute: resolveGuestMessage,
140 scheduler,
141 concurrency,
142 }),
143 archive: createEnvironmentCommand(runtime, {
144 label: "environment-data:commands:thread:archive",
145 execute: archiveThread,
146 scheduler,
147 concurrency,
148 }),
149 unarchive: createEnvironmentCommand(runtime, {
150 label: "environment-data:commands:thread:unarchive",
151 execute: unarchiveThread,
152 scheduler,
153 concurrency,
154 }),
155 settle: createEnvironmentCommand(runtime, {
156 label: "environment-data:commands:thread:settle",
157 execute: settleThread,
158 scheduler,
159 concurrency,
160 }),
161 unsettle: createEnvironmentCommand(runtime, {
162 label: "environment-data:commands:thread:unsettle",
163 execute: unsettleThread,
164 scheduler,
165 concurrency,
166 }),
167 snooze: createEnvironmentCommand(runtime, {
168 label: "environment-data:commands:thread:snooze",
169 execute: snoozeThread,
170 scheduler,
171 concurrency,
172 }),
173 unsnooze: createEnvironmentCommand(runtime, {
174 label: "environment-data:commands:thread:unsnooze",
175 execute: unsnoozeThread,
176 scheduler,
177 concurrency,
178 }),
179 pin: createEnvironmentCommand(runtime, {
180 label: "environment-data:commands:thread:pin",
181 execute: pinThread,
182 scheduler,
183 concurrency,
184 }),
185 unpin: createEnvironmentCommand(runtime, {
186 label: "environment-data:commands:thread:unpin",
187 execute: unpinThread,
188 scheduler,
189 concurrency,
190 }),
191 reorderPin: createEnvironmentCommand(runtime, {
192 label: "environment-data:commands:thread:reorder-pin",
193 execute: reorderPinnedThread,
194 scheduler,
195 concurrency,
196 }),
197 setAutoSettle: createEnvironmentCommand(runtime, {
198 label: "environment-data:commands:thread:set-auto-settle",
199 execute: setThreadAutoSettle,
200 scheduler,
201 concurrency,
202 }),
203 reorderActive: createEnvironmentCommand(runtime, {
204 label: "environment-data:commands:thread:reorder-active",
205 execute: reorderActiveThread,
206 scheduler,
207 concurrency,
208 }),
209 visit: createEnvironmentCommand(runtime, {
210 label: "environment-data:commands:thread:visit",
211 execute: visitThread,
212 scheduler,
213 concurrency,
214 }),
215 markUnread: createEnvironmentCommand(runtime, {
216 label: "environment-data:commands:thread:mark-unread",
217 execute: markThreadUnread,
218 scheduler,
219 concurrency,
220 }),
221 updateMetadata: createEnvironmentCommand(runtime, {
222 label: "environment-data:commands:thread:update-metadata",
223 execute: updateThreadMetadata,
224 scheduler,
225 concurrency,
226 }),
227 linkPullRequest: createEnvironmentCommand(runtime, {
228 label: "environment-data:commands:thread:link-pull-request",
229 execute: linkThreadPullRequest,
230 scheduler,
231 concurrency,
232 }),
233 unlinkPullRequest: createEnvironmentCommand(runtime, {
234 label: "environment-data:commands:thread:unlink-pull-request",
235 execute: unlinkThreadPullRequest,
236 scheduler,
237 concurrency,
238 }),
239 watchPullRequest: createEnvironmentCommand(runtime, {
240 label: "environment-data:commands:thread:watch-pull-request",
241 execute: watchThreadPullRequest,
242 scheduler,
243 concurrency,
244 }),
245 setRuntimeMode: createEnvironmentCommand(runtime, {
246 label: "environment-data:commands:thread:set-runtime-mode",
247 execute: setThreadRuntimeMode,
248 scheduler,
249 concurrency,
250 }),
251 setInteractionMode: createEnvironmentCommand(runtime, {
252 label: "environment-data:commands:thread:set-interaction-mode",
253 execute: setThreadInteractionMode,
254 scheduler,
255 concurrency,
256 }),
257 startTurn: createEnvironmentCommand(runtime, {
258 label: "environment-data:commands:thread:start-turn",
259 execute: startThreadTurn,
260 scheduler,
261 concurrency,
262 }),
263 interruptTurn: createEnvironmentCommand(runtime, {
264 label: "environment-data:commands:thread:interrupt-turn",
265 execute: interruptTurn,
266 scheduler,
267 concurrency,
268 }),
269 respondToApproval: createEnvironmentCommand(runtime, {
270 label: "environment-data:commands:thread:respond-to-approval",
271 execute: respondToThreadApproval,
272 scheduler,
273 concurrency,
274 }),
275 respondToUserInput: createEnvironmentCommand(runtime, {
276 label: "environment-data:commands:thread:respond-to-user-input",
277 execute: respondToThreadUserInput,
278 scheduler,
279 concurrency,
280 }),
281 dismissUserInput: createEnvironmentCommand(runtime, {
282 label: "environment-data:commands:thread:dismiss-user-input",
283 execute: dismissThreadUserInput,
284 scheduler,
285 concurrency,
286 }),
287 revertCheckpoint: createEnvironmentCommand(runtime, {
288 label: "environment-data:commands:thread:revert-checkpoint",
289 execute: revertThreadCheckpoint,
290 scheduler,
291 concurrency,
292 }),
293 stopSession: createEnvironmentCommand(runtime, {
294 label: "environment-data:commands:thread:stop-session",
295 execute: stopThreadSession,
296 scheduler,
297 concurrency,
298 }),
299 forkFromRun: createEnvironmentCommand(runtime, {
300 label: "environment-data:commands:thread:fork-from-run",
301 execute: forkThreadFromRun,
302 scheduler,
303 concurrency: {
304 mode: "serial",
305 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
306 },
307 }),
308 mergeBack: createEnvironmentCommand(runtime, {
309 label: "environment-data:commands:thread:merge-back",
310 execute: mergeThreadBack,
311 scheduler,
312 concurrency: {
313 mode: "serial",
314 key: ({ environmentId, input }) =>
315 JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]),
316 },
317 }),
318 resumeThreadQueue: createEnvironmentCommand(runtime, {
319 label: "environment-data:commands:thread:resume-queue",
320 execute: resumeThreadQueue,
321 scheduler,
322 concurrency,
323 }),
324 promoteQueuedRun: createEnvironmentCommand(runtime, {
325 label: "environment-data:commands:thread:promote-queued-run",
326 execute: promoteQueuedRun,
327 scheduler,
328 concurrency,
329 }),
330 cancelQueuedRun: createEnvironmentCommand(runtime, {
331 label: "environment-data:commands:thread:cancel-queued-run",
332 execute: cancelQueuedRun,
333 scheduler,
334 concurrency,
335 }),
336 retryWorkspacePreparation: createEnvironmentCommand(runtime, {
337 label: "environment-data:commands:thread:retry-workspace-preparation",
338 execute: retryWorkspacePreparation,
339 scheduler,
340 concurrency,
341 }),
342 editQueuedRun: createEnvironmentCommand(runtime, {
343 label: "environment-data:commands:thread:edit-queued-run",
344 execute: editQueuedRun,
345 scheduler,
346 concurrency,
347 }),
348 loadEarlierHistory: createEnvironmentCommand(runtime, {
349 label: "environment-data:commands:thread:load-earlier-history",
350 execute: loadEarlierHistory,
351 scheduler,
352 concurrency: {
353 mode: "serial",
354 key: ({ environmentId, input }) =>
355 `history:${JSON.stringify([environmentId, input.threadId])}`,
356 },
357 }),
358 uploadFeedback: createEnvironmentRpcCommand(runtime, {
359 label: "environment-data:commands:thread:upload-feedback",
360 tag: WS_METHODS.providerUploadFeedback,
361 scheduler,
362 concurrency,
363 }),
364 };
365 const optimistic = createOptimisticThreadLifecycle(snapshotAtom);
366 return {
367 ...commands,
368 snapshotAtom: optimistic.snapshotAtom,
369 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
370 !accepted &&
371 (thread.pendingRuntimeRequest !== null ||
372 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status))
373 ? thread
374 : {
375 ...thread,
376 pendingRuntimeRequest: null,
377 settledOverride: "settled",
378 settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now,
379 unsettledAt: null,
380 activeOrderKey: null,
381 pinnedAt: null,
382 pinOrderKey: null,
383 snoozedAt: null,
384 snoozedUntil: null,
385 },
386 ),
387 unsettle: optimistic.wrap(commands.unsettle, (thread, input, now) => ({
388 ...thread,
389 settledOverride: input.reason === "user" ? "active" : null,
390 settledAt: null,
391 unsettledAt: thread.settledOverride === "active" ? (thread.unsettledAt ?? null) : now,
392 })),
393 snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
394 (!accepted &&
395 (thread.pendingRuntimeRequest !== null ||
396 ["preparing", "queued", "starting"].includes(thread.status))) ||
397 !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
398 ? thread
399 : {
400 ...thread,
401 pendingRuntimeRequest: null,
402 snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
403 snoozedAt: now,
404 },
405 ),
406 unsnooze: optimistic.wrap(commands.unsnooze, (thread) => ({
407 ...thread,
408 snoozedUntil: null,
409 snoozedAt: null,
410 })),
411 setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({
412 ...thread,
413 autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now),
414 })),
415 pin: optimistic.wrap(commands.pin, (thread, input, now) => ({
416 ...thread,
417 pinnedAt: thread.pinnedAt ?? now,
418 pinOrderKey: thread.pinnedAt == null ? (input.orderKey ?? null) : thread.pinOrderKey,
419 ...(thread.settledOverride === "settled"
420 ? {
421 settledOverride: "active" as const,
422 settledAt: null,
423 unsettledAt: now,
424 }
425 : {}),
426 snoozedUntil: null,
427 snoozedAt: null,
428 })),
429 unpin: optimistic.wrap(commands.unpin, (thread) => ({
430 ...thread,
431 pinnedAt: null,
432 pinOrderKey: null,
433 })),
434 reorderPin: optimistic.wrap(commands.reorderPin, (thread, input) => ({
435 ...thread,
436 pinOrderKey: input.orderKey,
437 })),
438 reorderActive: optimistic.wrap(commands.reorderActive, (thread, input) => ({
439 ...thread,
440 activeOrderKey: input.orderKey,
441 })),
442 };