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

threadCommands.ts

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