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