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