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