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

threadCommands.ts

469 lines16.1 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 { EnvironmentSupervisor } from "../connection/supervisor.ts";
92import {
93 ThreadHistoryController,
94 type ThreadHistoryLoadEarlierResult,
95} from "./threadHistoryController.ts";
96​
97export type LoadEarlierThreadHistoryInput = {
98 readonly threadId: ThreadId;
99};
100​
101export type {
102 ArchiveThreadInput,
103 CancelQueuedRunInput,
104 CreateThreadInput,
105 DeleteThreadInput,
106 EditQueuedRunInput,
107 InterruptThreadTurnInput,
108 MarkThreadUnreadInput,
109 ForkThreadFromRunInput,
110 MergeThreadBackInput,
111 PromoteQueuedRunInput,
112 ReorderQueuedRunInput,
113 LinkThreadPullRequestInput,
114 RespondToThreadApprovalInput,
115 RespondToThreadUserInputInput,
116 DismissThreadUserInputInput,
117 RevertThreadCheckpointInput,
118 SetThreadInteractionModeInput,
119 SetThreadRuntimeModeInput,
120 PinThreadInput,
121 ReorderPinnedThreadInput,
122 ReorderActiveThreadInput,
123 SetThreadAutoSettleInput,
124 SettleThreadInput,
125 SnoozeThreadInput,
126 StartThreadTurnInput,
127 StopThreadSessionInput,
128 ThreadCommandInput,
129 UnarchiveThreadInput,
130 UnlinkThreadPullRequestInput,
131 UnpinThreadInput,
132 UnsettleThreadInput,
133 UnsnoozeThreadInput,
134 UpdateThreadMetadataInput,
135 VisitThreadInput,
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 setRuntimeMode: createEnvironmentCommand(runtime, {
258 label: "environment-data:commands:thread:set-runtime-mode",
259 execute: (input: SetThreadRuntimeModeInput) => setThreadRuntimeMode(input),
260 scheduler,
261 concurrency,
262 }),
263 setInteractionMode: createEnvironmentCommand(runtime, {
264 label: "environment-data:commands:thread:set-interaction-mode",
265 execute: (input: SetThreadInteractionModeInput) => setThreadInteractionMode(input),
266 scheduler,
267 concurrency,
268 }),
269 startTurn: createEnvironmentCommand(runtime, {
270 label: "environment-data:commands:thread:start-turn",
271 execute: (input: StartThreadTurnInput) => startThreadTurn(input),
272 scheduler,
273 concurrency,
274 }),
275 interruptTurn: createEnvironmentCommand(runtime, {
276 label: "environment-data:commands:thread:interrupt-turn",
277 execute: (input: InterruptThreadTurnInput) => interruptThreadTurn(input),
278 scheduler,
279 concurrency,
280 }),
281 respondToApproval: createEnvironmentCommand(runtime, {
282 label: "environment-data:commands:thread:respond-to-approval",
283 execute: (input: RespondToThreadApprovalInput) => respondToThreadApproval(input),
284 scheduler,
285 concurrency,
286 }),
287 respondToUserInput: createEnvironmentCommand(runtime, {
288 label: "environment-data:commands:thread:respond-to-user-input",
289 execute: (input: RespondToThreadUserInputInput) => respondToThreadUserInput(input),
290 scheduler,
291 concurrency,
292 }),
293 dismissUserInput: createEnvironmentCommand(runtime, {
294 label: "environment-data:commands:thread:dismiss-user-input",
295 execute: (input: DismissThreadUserInputInput) => dismissThreadUserInput(input),
296 scheduler,
297 concurrency,
298 }),
299 revertCheckpoint: createEnvironmentCommand(runtime, {
300 label: "environment-data:commands:thread:revert-checkpoint",
301 execute: (input: RevertThreadCheckpointInput) => revertThreadCheckpoint(input),
302 scheduler,
303 concurrency,
304 }),
305 stopSession: createEnvironmentCommand(runtime, {
306 label: "environment-data:commands:thread:stop-session",
307 execute: (input: StopThreadSessionInput) => stopThreadSession(input),
308 scheduler,
309 concurrency,
310 }),
311 forkFromRun: createEnvironmentCommand(runtime, {
312 label: "environment-data:commands:thread:fork-from-run",
313 execute: (input: ForkThreadFromRunInput) => forkThreadFromRun(input),
314 scheduler,
315 concurrency: {
316 mode: "serial",
317 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
318 },
319 }),
320 mergeBack: createEnvironmentCommand(runtime, {
321 label: "environment-data:commands:thread:merge-back",
322 execute: (input: MergeThreadBackInput) => mergeThreadBack(input),
323 scheduler,
324 concurrency: {
325 mode: "serial",
326 key: ({ environmentId, input }) =>
327 JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]),
328 },
329 }),
330 resumeThreadQueue: createEnvironmentCommand(runtime, {
331 label: "environment-data:commands:thread:resume-queue",
332 execute: (input: ThreadCommandInput) => resumeThreadQueue(input),
333 scheduler,
334 concurrency,
335 }),
336 reorderQueuedRun: createEnvironmentCommand(runtime, {
337 label: "environment-data:commands:thread:reorder-queued-run",
338 execute: (input: ReorderQueuedRunInput) => reorderQueuedRun(input),
339 scheduler,
340 concurrency,
341 }),
342 promoteQueuedRun: createEnvironmentCommand(runtime, {
343 label: "environment-data:commands:thread:promote-queued-run",
344 execute: (input: PromoteQueuedRunInput) => promoteQueuedRun(input),
345 scheduler,
346 concurrency,
347 }),
348 cancelQueuedRun: createEnvironmentCommand(runtime, {
349 label: "environment-data:commands:thread:cancel-queued-run",
350 execute: (input: CancelQueuedRunInput) => cancelQueuedRun(input),
351 scheduler,
352 concurrency,
353 }),
354 editQueuedRun: createEnvironmentCommand(runtime, {
355 label: "environment-data:commands:thread:edit-queued-run",
356 execute: (input: EditQueuedRunInput) => editQueuedRun(input),
357 scheduler,
358 concurrency,
359 }),
360 loadEarlierHistory: createEnvironmentCommand(runtime, {
361 label: "environment-data:commands:thread:load-earlier-history",
362 execute: (input: LoadEarlierThreadHistoryInput) =>
363 Effect.gen(function* () {
364 const supervisor = yield* EnvironmentSupervisor;
365 const controller = yield* Effect.serviceOption(ThreadHistoryController);
366 if (Option.isNone(controller)) {
367 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
368 }
369 return yield* controller.value.loadEarlier(
370 supervisor.target.environmentId,
371 input.threadId,
372 );
373 }),
374 scheduler,
375 concurrency: {
376 mode: "serial",
377 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]),
378 },
379 }),
380 uploadFeedback: createEnvironmentRpcCommand(runtime, {
381 label: "environment-data:commands:thread:upload-feedback",
382 tag: WS_METHODS.providerUploadFeedback,
383 scheduler,
384 concurrency,
385 }),
386 };
387 const optimistic = createOptimisticThreadLifecycle(snapshotAtom);
388 return {
389 ...commands,
390 snapshotAtom: optimistic.snapshotAtom,
391 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
392 !accepted &&
393 (thread.pendingRuntimeRequest !== null ||
394 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status))
395 ? thread
396 : {
397 ...thread,
398 pendingRuntimeRequest: null,
399 settledOverride: "settled",
400 settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now,
401 unsettledAt: null,
402 activeOrderKey: null,
403 pinnedAt: null,
404 pinOrderKey: null,
405 snoozedAt: null,
406 snoozedUntil: null,
407 },
408 ),
409 unsettle: optimistic.wrap(commands.unsettle, (thread, input, now) => ({
410 ...thread,
411 settledOverride: input.reason === "user" ? "active" : null,
412 settledAt: null,
413 unsettledAt: thread.settledOverride === "active" ? (thread.unsettledAt ?? null) : now,
414 })),
415 snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
416 (!accepted &&
417 (thread.pendingRuntimeRequest !== null ||
418 ["preparing", "queued", "starting"].includes(thread.status))) ||
419 !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
420 ? thread
421 : {
422 ...thread,
423 pendingRuntimeRequest: null,
424 snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
425 snoozedAt:
426 thread.snoozedUntil != null &&
427 DateTime.formatIso(thread.snoozedUntil) === input.snoozedUntil
428 ? (thread.snoozedAt ?? now)
429 : now,
430 },
431 ),
432 unsnooze: optimistic.wrap(commands.unsnooze, (thread) => ({
433 ...thread,
434 snoozedUntil: null,
435 snoozedAt: null,
436 })),
437 setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({
438 ...thread,
439 autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now),
440 })),
441 pin: optimistic.wrap(commands.pin, (thread, input, now) => ({
442 ...thread,
443 pinnedAt: thread.pinnedAt ?? now,
444 pinOrderKey: thread.pinnedAt == null ? (input.orderKey ?? null) : thread.pinOrderKey,
445 ...(thread.settledOverride === "settled"
446 ? {
447 settledOverride: "active" as const,
448 settledAt: null,
449 unsettledAt: now,
450 }
451 : {}),
452 snoozedUntil: null,
453 snoozedAt: null,
454 })),
455 unpin: optimistic.wrap(commands.unpin, (thread) => ({
456 ...thread,
457 pinnedAt: null,
458 pinOrderKey: null,
459 })),
460 reorderPin: optimistic.wrap(commands.reorderPin, (thread, input) => ({
461 ...thread,
462 pinOrderKey: input.orderKey,
463 })),
464 reorderActive: optimistic.wrap(commands.reorderActive, (thread, input) => ({
465 ...thread,
466 activeOrderKey: input.orderKey,
467 })),
468 };