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

threadCommands.ts

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