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