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

threadCommands.ts

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