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

threadCommands.ts

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