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

threadCommands.ts

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