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

commands.ts

858 lines28.1 KB

1import {
2 type ThreadLinkedPullRequest,
3 CommandId,
4 ORCHESTRATION_V2_WS_METHODS,
5 OrchestrationV2CheckpointUnavailableError,
6 WS_METHODS,
7 type ChatAttachment,
8 type MessageId,
9 type ModelSelection,
10 type OrchestrationV2Command,
11 type OrchestrationV2CreationSource,
12 type PlanId,
13 type ProjectId,
14 type ProjectScript,
15 type ProviderApprovalDecision,
16 type ProviderInteractionMode,
17 type ProviderUserInputAnswers,
18 type RunId,
19 type RuntimeMode,
20 type RuntimeRequestId,
21 type ThreadId,
22 type UploadChatAttachment,
23} from "@t3tools/contracts";
24import * as Crypto from "effect/Crypto";
25import * as Effect from "effect/Effect";
26​
27import { request } from "../rpc/client.ts";
28​
29interface CommandMetadata {
30 readonly commandId?: CommandId;
31 readonly createdAt?: string;
32 readonly creationSource?: OrchestrationV2CreationSource;
34​
35export interface CreateProjectInput extends CommandMetadata {
36 readonly projectId: ProjectId;
37 readonly title: string;
38 readonly workspaceRoot: string;
39 readonly createWorkspaceRootIfMissing?: boolean;
40 readonly defaultModelSelection?: ModelSelection | null;
41 readonly scripts?: ReadonlyArray<ProjectScript>;
43​
44export interface UpdateProjectInput extends CommandMetadata {
45 readonly projectId: ProjectId;
46 readonly title?: string;
47 readonly workspaceRoot?: string;
48 readonly defaultModelSelection?: ModelSelection | null;
49 readonly scripts?: ReadonlyArray<ProjectScript>;
51​
52export interface DeleteProjectInput extends CommandMetadata {
53 readonly projectId: ProjectId;
54 readonly force?: boolean;
56​
57export interface CreateThreadInput extends CommandMetadata {
58 readonly threadId: ThreadId;
59 readonly projectId: ProjectId;
60 readonly title: string;
61 readonly modelSelection: ModelSelection;
62 readonly runtimeMode: RuntimeMode;
63 readonly interactionMode: ProviderInteractionMode;
64 readonly branch: string | null;
65 readonly worktreePath: string | null;
67​
68export interface ThreadCommandInput extends CommandMetadata {
69 readonly threadId: ThreadId;
71​
72export type DeleteThreadInput = ThreadCommandInput;
73export type ArchiveThreadInput = ThreadCommandInput;
74export type UnarchiveThreadInput = ThreadCommandInput;
75export type SettleThreadInput = ThreadCommandInput;
76​
77export interface UnsettleThreadInput extends ThreadCommandInput {
78 readonly reason: "user";
80​
81export interface PinThreadInput extends ThreadCommandInput {
82 /** Initial slot in the user-arranged pinned order; omit to pin keyless. */
83 readonly orderKey?: string;
85export type UnpinThreadInput = ThreadCommandInput;
86​
87export interface ReorderPinnedThreadInput extends ThreadCommandInput {
88 /** Fractional-index key that sorts between the drop position's neighbors. */
89 readonly orderKey: string;
91​
92export interface SnoozeThreadInput extends ThreadCommandInput {
93 readonly snoozedUntil: string;
95​
96export interface UnsnoozeThreadInput extends ThreadCommandInput {
97 readonly reason: "user";
99​
100export interface VisitThreadInput extends ThreadCommandInput {
101 /** Watermark of the thread state the viewer has seen (ISO timestamp). */
102 readonly visitedAt: string;
104​
105export type MarkThreadUnreadInput = ThreadCommandInput;
106​
107export interface UpdateThreadMetadataInput extends ThreadCommandInput {
108 readonly title?: string;
109 readonly modelSelection?: ModelSelection;
110 readonly branch?: string | null;
111 readonly worktreePath?: string | null;
112 /** Kick off an async title regeneration for the thread. */
113 readonly regenerateTitle?: boolean;
114 /** Link (object) or unlink (null) a pull request (#8160). */
115 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
117​
118export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
119 readonly runtimeMode: RuntimeMode;
121​
122export interface SetThreadInteractionModeInput extends ThreadCommandInput {
123 readonly interactionMode: ProviderInteractionMode;
125​
126interface StartThreadBootstrap {
127 readonly createThread?: {
128 readonly projectId: ProjectId;
129 readonly title: string;
130 readonly modelSelection: ModelSelection;
131 readonly runtimeMode: RuntimeMode;
132 readonly interactionMode: ProviderInteractionMode;
133 readonly branch: string | null;
134 readonly worktreePath: string | null;
135 readonly createdAt: string;
136 };
137 readonly prepareWorktree?: {
138 readonly projectCwd: string;
139 readonly baseBranch: string;
140 readonly branch?: string;
141 readonly startFromOrigin?: boolean;
142 };
143 readonly runSetupScript?: boolean;
145​
146export interface StartThreadTurnInput extends ThreadCommandInput {
147 readonly message: {
148 readonly messageId: MessageId;
149 readonly role: "user";
150 readonly text: string;
151 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
152 };
153 readonly modelSelection?: ModelSelection;
154 readonly titleSeed?: string;
155 readonly runtimeMode: RuntimeMode;
156 readonly interactionMode: ProviderInteractionMode;
157 readonly bootstrap?: StartThreadBootstrap;
158 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
159 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
161​
162export interface InterruptThreadTurnInput extends ThreadCommandInput {
163 readonly runId?: RunId;
164 /** Temporary caller compatibility while UI naming moves from turns to runs. */
165 readonly turnId?: string;
167​
168export interface RespondToThreadApprovalInput extends ThreadCommandInput {
169 readonly requestId: RuntimeRequestId;
170 readonly decision: ProviderApprovalDecision;
172​
173export interface RespondToThreadUserInputInput extends ThreadCommandInput {
174 readonly requestId: RuntimeRequestId;
175 readonly answers: ProviderUserInputAnswers;
177​
178export interface RevertThreadCheckpointInput extends ThreadCommandInput {
179 readonly checkpointId?: string;
180 readonly scopeId?: string;
181 readonly turnCount?: number;
183​
184export type StopThreadSessionInput = ThreadCommandInput;
185​
186export interface ForkThreadFromRunInput extends CommandMetadata {
187 readonly sourceThreadId: ThreadId;
188 readonly targetThreadId: ThreadId;
189 readonly runId: RunId;
190 readonly title?: string;
192​
193export interface MergeThreadBackInput extends CommandMetadata {
194 readonly sourceThreadId: ThreadId;
195 readonly targetThreadId: ThreadId;
196 readonly runId: RunId;
198​
199export interface ReorderQueuedRunInput extends ThreadCommandInput {
200 readonly runId: RunId;
201 readonly beforeRunId: RunId | null;
203​
204export interface PromoteQueuedRunInput extends ThreadCommandInput {
205 readonly queuedRunId: RunId;
206 readonly targetRunId: RunId;
208​
209export interface CancelQueuedRunInput extends ThreadCommandInput {
210 readonly runId: RunId;
212​
213export interface EditQueuedRunInput extends ThreadCommandInput {
214 readonly runId: RunId;
215 readonly text: string;
216 /**
217 * Full replacement attachment list for the queued message. Omitted =
218 * text-only edit that leaves attachments untouched. `dataUrl` entries are
219 * persisted against `messageId` (the queued run's user message) before
220 * dispatch, so `messageId` is required whenever attachments are present.
221 */
222 readonly edit?: {
223 readonly messageId: MessageId;
224 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
225 };
227​
228const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
229 input: CommandMetadata,
230) {
231 if (input.commandId !== undefined) return input.commandId;
232 const crypto = yield* Crypto.Crypto;
233 return CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie));
234});
235​
236const dispatch = (command: OrchestrationV2Command) =>
237 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
238​
239const getProjection = (threadId: ThreadId) =>
240 request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
241​
242const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* (
243 threadId: ThreadId,
244 messageId: MessageId,
245 attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>,
246) {
247 const stored = attachments.filter(
248 (attachment): attachment is ChatAttachment => "id" in attachment,
249 );
250 const uploads = attachments.filter(
251 (attachment): attachment is UploadChatAttachment => "dataUrl" in attachment,
252 );
253 if (uploads.length === 0) return stored;
254 const result = yield* request(WS_METHODS.assetsPersistChatAttachments, {
255 threadId,
256 messageId,
257 attachments: uploads,
258 });
259 if (stored.length === 0) return result.attachments;
260 const byUpload = new Map(
261 uploads.map((attachment, index) => [attachment, result.attachments[index]]),
262 );
263 return attachments.flatMap((attachment) => {
264 if ("id" in attachment) return [attachment];
265 const persisted = byUpload.get(attachment);
266 return persisted === undefined ? [] : [persisted];
267 });
268});
269​
270const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* (
271 mutation:
272 | {
273 readonly type: "project.create";
274 readonly commandId: CommandId;
275 readonly projectId: ProjectId;
276 readonly title: string;
277 readonly workspaceRoot: string;
278 readonly createWorkspaceRootIfMissing?: boolean;
279 readonly defaultModelSelection?: ModelSelection | null;
280 readonly scripts?: ReadonlyArray<ProjectScript>;
281 }
282 | {
283 readonly type: "project.update";
284 readonly commandId: CommandId;
285 readonly projectId: ProjectId;
286 readonly title?: string;
287 readonly workspaceRoot?: string;
288 readonly defaultModelSelection?: ModelSelection | null;
289 readonly scripts?: ReadonlyArray<ProjectScript>;
290 }
291 | {
292 readonly type: "project.delete";
293 readonly commandId: CommandId;
294 readonly projectId: ProjectId;
295 readonly force?: boolean;
296 },
297) {
298 return yield* request(WS_METHODS.projectsMutate, mutation);
299});
300​
301export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
302 input: CreateProjectInput,
303) {
304 return yield* mutateProject({
305 type: "project.create",
306 commandId: yield* allocateCommandId(input),
307 projectId: input.projectId,
308 title: input.title,
309 workspaceRoot: input.workspaceRoot,
310 ...(input.createWorkspaceRootIfMissing === undefined
311 ? {}
312 : { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
313 ...(input.defaultModelSelection === undefined
314 ? {}
315 : { defaultModelSelection: input.defaultModelSelection }),
316 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
317 });
318});
319​
320export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
321 input: UpdateProjectInput,
322) {
323 return yield* mutateProject({
324 type: "project.update",
325 commandId: yield* allocateCommandId(input),
326 projectId: input.projectId,
327 ...(input.title === undefined ? {} : { title: input.title }),
328 ...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
329 ...(input.defaultModelSelection === undefined
330 ? {}
331 : { defaultModelSelection: input.defaultModelSelection }),
332 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
333 });
334});
335​
336export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
337 input: DeleteProjectInput,
338) {
339 return yield* mutateProject({
340 type: "project.delete",
341 commandId: yield* allocateCommandId(input),
342 projectId: input.projectId,
343 ...(input.force === undefined ? {} : { force: input.force }),
344 });
345});
346​
347export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
348 input: CreateThreadInput,
349) {
350 return yield* dispatch({
351 type: "thread.create",
352 commandId: yield* allocateCommandId(input),
353 createdBy: "user",
354 creationSource: input.creationSource ?? "web",
355 threadId: input.threadId,
356 projectId: input.projectId,
357 title: input.title,
358 modelSelection: input.modelSelection,
359 runtimeMode: input.runtimeMode,
360 interactionMode: input.interactionMode,
361 branch: input.branch,
362 worktreePath: input.worktreePath,
363 });
364});
365​
366function simpleThreadCommand(
367 type:
368 | "thread.delete"
369 | "thread.archive"
370 | "thread.unarchive"
371 | "thread.settle"
372 | "thread.pin"
373 | "thread.unpin",
374 input: ThreadCommandInput,
375) {
376 return allocateCommandId(input).pipe(
377 Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
378 );
380​
381export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
382 input: DeleteThreadInput,
383) {
384 return yield* simpleThreadCommand("thread.delete", input);
385});
386​
387export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
388 input: ArchiveThreadInput,
389) {
390 return yield* simpleThreadCommand("thread.archive", input);
391});
392​
393export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
394 input: UnarchiveThreadInput,
395) {
396 return yield* simpleThreadCommand("thread.unarchive", input);
397});
398​
399export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
400 input: SettleThreadInput,
401) {
402 return yield* simpleThreadCommand("thread.settle", input);
403});
404​
405export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* (
406 input: PinThreadInput,
407) {
408 const commandId = yield* allocateCommandId(input);
409 return yield* dispatch({
410 type: "thread.pin",
411 commandId,
412 threadId: input.threadId,
413 ...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }),
414 });
415});
416​
417export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* (
418 input: ReorderPinnedThreadInput,
419) {
420 const commandId = yield* allocateCommandId(input);
421 return yield* dispatch({
422 type: "thread.pin.reorder",
423 commandId,
424 threadId: input.threadId,
425 orderKey: input.orderKey,
426 });
427});
428​
429export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* (
430 input: UnpinThreadInput,
431) {
432 return yield* simpleThreadCommand("thread.unpin", input);
433});
434​
435export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
436 input: UnsettleThreadInput,
437) {
438 return yield* dispatch({
439 type: "thread.unsettle",
440 commandId: yield* allocateCommandId(input),
441 threadId: input.threadId,
442 reason: input.reason,
443 });
444});
445​
446export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
447 input: SnoozeThreadInput,
448) {
449 return yield* dispatch({
450 type: "thread.snooze",
451 commandId: yield* allocateCommandId(input),
452 threadId: input.threadId,
453 snoozedUntil: input.snoozedUntil,
454 });
455});
456​
457export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
458 input: UnsnoozeThreadInput,
459) {
460 return yield* dispatch({
461 type: "thread.unsnooze",
462 commandId: yield* allocateCommandId(input),
463 threadId: input.threadId,
464 reason: input.reason,
465 });
466});
467​
468export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
469 input: VisitThreadInput,
470) {
471 return yield* dispatch({
472 type: "thread.visit",
473 commandId: yield* allocateCommandId(input),
474 threadId: input.threadId,
475 visitedAt: input.visitedAt,
476 });
477});
478​
479export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
480 input: MarkThreadUnreadInput,
481) {
482 return yield* dispatch({
483 type: "thread.mark-unread",
484 commandId: yield* allocateCommandId(input),
485 threadId: input.threadId,
486 });
487});
488​
489export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
490 function* (input: UpdateThreadMetadataInput) {
491 const commandId = yield* allocateCommandId(input);
492 let result = null;
493 if (
494 input.title !== undefined ||
495 input.branch !== undefined ||
496 input.worktreePath !== undefined ||
497 input.regenerateTitle !== undefined ||
498 input.linkedPullRequest !== undefined
499 ) {
500 result = yield* dispatch({
501 type: "thread.metadata.update",
502 commandId,
503 threadId: input.threadId,
504 ...(input.title === undefined ? {} : { title: input.title }),
505 ...(input.branch === undefined ? {} : { branch: input.branch }),
506 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
507 ...(input.regenerateTitle === undefined ? {} : { regenerateTitle: input.regenerateTitle }),
508 ...(input.linkedPullRequest === undefined
509 ? {}
510 : { linkedPullRequest: input.linkedPullRequest }),
511 });
512 }
513 if (input.modelSelection !== undefined) {
514 const projection = yield* getProjection(input.threadId);
515 const type =
516 projection.thread.providerInstanceId === input.modelSelection.instanceId
517 ? ("thread.model-selection.set" as const)
518 : ("provider.switch" as const);
519 result = yield* dispatch({
520 type,
521 commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
522 threadId: input.threadId,
523 modelSelection: input.modelSelection,
524 });
525 }
526 return result ?? { sequence: 0 };
527 },
528);
529​
530export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
531 function* (input: SetThreadRuntimeModeInput) {
532 return yield* dispatch({
533 type: "thread.runtime-mode.set",
534 commandId: yield* allocateCommandId(input),
535 threadId: input.threadId,
536 runtimeMode: input.runtimeMode,
537 });
538 },
539);
540​
541export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
542 function* (input: SetThreadInteractionModeInput) {
543 return yield* dispatch({
544 type: "thread.interaction-mode.set",
545 commandId: yield* allocateCommandId(input),
546 threadId: input.threadId,
547 interactionMode: input.interactionMode,
548 });
549 },
550);
551​
552export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
553 input: StartThreadTurnInput,
554) {
555 const commandId = yield* allocateCommandId(input);
556 const attachments = yield* persistAttachments(
557 input.threadId,
558 input.message.messageId,
559 input.message.attachments,
560 );
561 const bootstrap = input.bootstrap?.createThread;
562 const prepareWorktree = input.bootstrap?.prepareWorktree;
563 if (bootstrap !== undefined || prepareWorktree !== undefined) {
564 const existingProjection =
565 bootstrap === undefined ? yield* getProjection(input.threadId) : null;
566 const thread = bootstrap ?? existingProjection!.thread;
567 const workspaceStrategy =
568 prepareWorktree !== undefined
569 ? {
570 type: "worktree" as const,
571 baseRef: prepareWorktree.baseBranch,
572 ...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
573 ...(prepareWorktree.startFromOrigin === undefined
574 ? {}
575 : { startFromOrigin: prepareWorktree.startFromOrigin }),
576 }
577 : bootstrap?.worktreePath
578 ? {
579 type: "existing_worktree" as const,
580 worktreePath: bootstrap.worktreePath,
581 ...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
582 }
583 : {
584 type: "root" as const,
585 ...(bootstrap?.branch === null || bootstrap?.branch === undefined
586 ? {}
587 : { branch: bootstrap.branch }),
588 };
589 return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
590 commandId,
591 creationSource: input.creationSource ?? "web",
592 threadId: input.threadId,
593 ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
594 projectId: thread.projectId,
595 title: input.titleSeed ?? thread.title,
596 generateTitle: input.titleSeed !== undefined,
597 modelSelection: input.modelSelection ?? thread.modelSelection,
598 runtimeMode: input.runtimeMode,
599 interactionMode: input.interactionMode,
600 workspaceStrategy,
601 initialMessage: {
602 messageId: input.message.messageId,
603 text: input.message.text,
604 attachments,
605 },
606 });
607 }
608​
609 const requestedMode = input.dispatchMode ?? "auto";
610 if (requestedMode === "start") {
611 return yield* dispatch({
612 type: "message.dispatch",
613 commandId,
614 createdBy: "user",
615 creationSource: input.creationSource ?? "web",
616 threadId: input.threadId,
617 messageId: input.message.messageId,
618 text: input.message.text,
619 attachments,
620 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
621 ...(input.sourceProposedPlan === undefined
622 ? {}
623 : { sourcePlanRef: input.sourceProposedPlan }),
624 dispatchMode: { type: "start_immediately" },
625 });
626 }
627​
628 const projection = yield* getProjection(input.threadId);
629 const activeRun = projection.runs.findLast(
630 (run) =>
631 run.status === "preparing" ||
632 run.status === "starting" ||
633 run.status === "running" ||
634 run.status === "waiting",
635 );
636 const activeProviderThread =
637 activeRun === undefined
638 ? undefined
639 : projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
640 const activeProviderSession =
641 activeProviderThread?.providerSessionId === null ||
642 activeProviderThread?.providerSessionId === undefined
643 ? undefined
644 : projection.providerSessions.find(
645 (session) => session.id === activeProviderThread.providerSessionId,
646 );
647 const turnCapabilities = activeProviderSession?.capabilities.turns;
648 const dispatchMode =
649 activeRun === undefined
650 ? ({ type: "start_immediately" } as const)
651 : requestedMode === "steer"
652 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
653 : requestedMode === "restart"
654 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
655 : requestedMode === "queue"
656 ? ({ type: "queue_after_active" } as const)
657 : turnCapabilities?.supportsActiveSteering === true
658 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
659 : turnCapabilities?.supportsQueuedMessages === true
660 ? ({ type: "queue_after_active" } as const)
661 : turnCapabilities?.supportsSteeringByInterruptRestart === true
662 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
663 : ({ type: "queue_after_active" } as const);
664 return yield* dispatch({
665 type: "message.dispatch",
666 commandId,
667 createdBy: "user",
668 creationSource: input.creationSource ?? "web",
669 threadId: input.threadId,
670 messageId: input.message.messageId,
671 text: input.message.text,
672 attachments,
673 ...(input.titleSeed === undefined || projection.messages.length > 0
674 ? {}
675 : { titleSeed: input.titleSeed }),
676 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
677 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
678 dispatchMode,
679 });
680});
681​
682export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
683 input: InterruptThreadTurnInput,
684) {
685 let runId = input.runId ?? (input.turnId as RunId | undefined);
686 if (runId === undefined) {
687 const projection = yield* getProjection(input.threadId);
688 runId = projection.runs.findLast(
689 (run) =>
690 run.status === "preparing" ||
691 run.status === "starting" ||
692 run.status === "running" ||
693 run.status === "waiting",
694 )?.id;
695 }
696 if (runId === undefined) return { sequence: 0 };
697 return yield* dispatch({
698 type: "run.interrupt",
699 commandId: yield* allocateCommandId(input),
700 threadId: input.threadId,
701 runId,
702 });
703});
704​
705export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
706 function* (input: RespondToThreadApprovalInput) {
707 return yield* dispatch({
708 type: "runtime-request.respond",
709 commandId: yield* allocateCommandId(input),
710 threadId: input.threadId,
711 requestId: input.requestId,
712 decision: input.decision,
713 });
714 },
715);
716​
717export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
718 function* (input: RespondToThreadUserInputInput) {
719 return yield* dispatch({
720 type: "runtime-request.respond",
721 commandId: yield* allocateCommandId(input),
722 threadId: input.threadId,
723 requestId: input.requestId,
724 answers: input.answers,
725 });
726 },
727);
728​
729export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
730 function* (input: RevertThreadCheckpointInput) {
731 const projection = yield* getProjection(input.threadId);
732 const checkpoint =
733 projection.checkpoints.find(
734 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
735 ) ??
736 projection.checkpoints.findLast((candidate) =>
737 input.turnCount === 0
738 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
739 : candidate.appRunOrdinal === input.turnCount,
740 );
741 if (checkpoint === undefined || checkpoint.status !== "ready") {
742 const target =
743 input.checkpointId === undefined
744 ? `run ordinal ${input.turnCount ?? "unknown"}`
745 : `checkpoint ${input.checkpointId}`;
746 return yield* new OrchestrationV2CheckpointUnavailableError({
747 threadId: input.threadId,
748 target,
749 });
750 }
751 return yield* dispatch({
752 type: "checkpoint.rollback",
753 commandId: yield* allocateCommandId(input),
754 threadId: input.threadId,
755 scopeId: checkpoint.scopeId,
756 checkpointId: checkpoint.id,
757 });
758 },
759);
760​
761export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
762 input: StopThreadSessionInput,
763) {
764 const projection = yield* getProjection(input.threadId);
765 const commandId = yield* allocateCommandId(input);
766 let result = { sequence: 0 };
767 for (const session of projection.providerSessions) {
768 result = yield* dispatch({
769 type: "provider-session.detach",
770 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
771 threadId: input.threadId,
772 providerSessionId: session.id,
773 reason: "client-requested",
774 });
775 }
776 return result;
777});
778​
779export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
780 input: ForkThreadFromRunInput,
781) {
782 return yield* dispatch({
783 type: "thread.fork",
784 commandId: yield* allocateCommandId(input),
785 createdBy: "user",
786 creationSource: input.creationSource ?? "web",
787 sourceThreadId: input.sourceThreadId,
788 targetThreadId: input.targetThreadId,
789 sourcePoint: { type: "run", runId: input.runId },
790 ...(input.title === undefined ? {} : { title: input.title }),
791 });
792});
793​
794export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
795 input: MergeThreadBackInput,
796) {
797 return yield* dispatch({
798 type: "thread.merge_back",
799 commandId: yield* allocateCommandId(input),
800 createdBy: "user",
801 creationSource: input.creationSource ?? "web",
802 sourceThreadId: input.sourceThreadId,
803 targetThreadId: input.targetThreadId,
804 sourcePoint: { type: "run", runId: input.runId },
805 });
806});
807​
808export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
809 input: ReorderQueuedRunInput,
810) {
811 return yield* dispatch({
812 type: "queued-run.reorder",
813 commandId: yield* allocateCommandId(input),
814 threadId: input.threadId,
815 runId: input.runId,
816 beforeRunId: input.beforeRunId,
817 });
818});
819​
820export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
821 input: PromoteQueuedRunInput,
822) {
823 return yield* dispatch({
824 type: "queued-message.promote-to-steer",
825 commandId: yield* allocateCommandId(input),
826 threadId: input.threadId,
827 queuedRunId: input.queuedRunId,
828 targetRunId: input.targetRunId,
829 });
830});
831​
832export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
833 input: CancelQueuedRunInput,
834) {
835 return yield* dispatch({
836 type: "queued-run.cancel",
837 commandId: yield* allocateCommandId(input),
838 threadId: input.threadId,
839 runId: input.runId,
840 });
841});
842​
843export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
844 input: EditQueuedRunInput,
845) {
846 const attachments =
847 input.edit === undefined
848 ? undefined
849 : yield* persistAttachments(input.threadId, input.edit.messageId, input.edit.attachments);
850 return yield* dispatch({
851 type: "queued-run.edit",
852 commandId: yield* allocateCommandId(input),
853 threadId: input.threadId,
854 runId: input.runId,
855 text: input.text,
856 ...(attachments === undefined ? {} : { attachments }),
857 });
858});