Open History to see the last commit
1import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2import {
3 type ThreadLinkedPullRequest,
4 CommandId,
5 CheckpointId,
6 CheckpointScopeId,
7 ORCHESTRATION_V2_WS_METHODS,
8 OrchestrationV2CheckpointUnavailableError,
9 WS_METHODS,
10 type ChatAttachment,
11 type MessageId,
12 type ModelSelection,
13 type NodeId,
14 type OrchestrationV2Command,
15 type OrchestrationV2CreationSource,
16 type PlanId,
17 type ProjectId,
18 type ProjectIconOverride,
19 type ProjectScript,
20 type ProviderApprovalDecision,
21 type ProviderInteractionMode,
22 type ProviderUserInputAnswers,
23 type RunId,
24 type RuntimeMode,
25 type RuntimeRequestId,
26 type ThreadId,
27 type ThreadEnvMode,
28 type UploadChatAttachment,
29} from "@t3tools/contracts";
30import { modelSelectionCommandType } from "@t3tools/shared/model";
31import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
32import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
33import * as Crypto from "effect/Crypto";
34import * as Effect from "effect/Effect";
35
36import { getInitialServerConfig, request } from "../rpc/client.ts";
37
38interface CommandMetadata {
39 readonly commandId?: CommandId;
40 readonly createdAt?: string;
41 readonly creationSource?: OrchestrationV2CreationSource;
42}
43
44export interface CreateProjectInput extends CommandMetadata {
45 readonly projectId: ProjectId;
46 readonly title: string;
47 readonly workspaceRoot: string;
48 readonly createWorkspaceRootIfMissing?: boolean;
49 readonly defaultModelSelection?: ModelSelection | null;
50 readonly scripts?: ReadonlyArray<ProjectScript>;
51}
52
53export interface UpdateProjectInput extends CommandMetadata {
54 readonly projectId: ProjectId;
55 readonly title?: string;
56 readonly workspaceRoot?: string;
57 readonly defaultModelSelection?: ModelSelection | null;
58 readonly autoPull?: boolean;
59 readonly projectIcon?: ProjectIconOverride | null;
60 readonly faviconPath?: string | null;
61 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
62 readonly scripts?: ReadonlyArray<ProjectScript>;
63}
64
65export interface DeleteProjectInput extends CommandMetadata {
66 readonly projectId: ProjectId;
67 readonly force?: boolean;
68}
69
70export interface CreateThreadInput extends CommandMetadata {
71 readonly threadId: ThreadId;
72 readonly projectId: ProjectId;
73 readonly title: string;
74 readonly modelSelection: ModelSelection;
75 readonly runtimeMode: RuntimeMode;
76 readonly interactionMode: ProviderInteractionMode;
77 readonly branch: string | null;
78 readonly worktreePath: string | null;
79}
80
81export interface ThreadCommandInput extends CommandMetadata {
82 readonly threadId: ThreadId;
83}
84
85export type DeleteThreadInput = ThreadCommandInput;
86export type ArchiveThreadInput = ThreadCommandInput;
87export type UnarchiveThreadInput = ThreadCommandInput;
88export type SettleThreadInput = ThreadCommandInput;
89
90export interface UnsettleThreadInput extends ThreadCommandInput {
91 readonly reason: "user";
92}
93
94export interface PinThreadInput extends ThreadCommandInput {
95 readonly orderKey?: string;
96}
97export type UnpinThreadInput = ThreadCommandInput;
98
99export interface ReorderPinnedThreadInput extends ThreadCommandInput {
100 readonly orderKey: string;
101}
102
103export interface ReorderActiveThreadInput extends ThreadCommandInput {
104 readonly orderKey: string;
105}
106
107export interface SnoozeThreadInput extends ThreadCommandInput {
108 readonly snoozedUntil: string;
109}
110
111export interface UnsnoozeThreadInput extends ThreadCommandInput {
112 readonly reason: "user";
113}
114
115export interface VisitThreadInput extends ThreadCommandInput {
116 readonly visitedAt: string;
117}
118
119export type MarkThreadUnreadInput = ThreadCommandInput;
120
121export interface UpdateThreadMetadataInput extends ThreadCommandInput {
122 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecoveryUpdate | null;
123 readonly title?: string;
124 readonly modelSelection?: ModelSelection;
125 readonly branch?: string | null;
126 readonly worktreePath?: string | null;
127 readonly regenerateTitle?: boolean;
128 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
129 readonly expectedEmpty?: boolean;
130}
131
132export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
133 readonly runtimeMode: RuntimeMode;
134}
135
136export interface SetThreadInteractionModeInput extends ThreadCommandInput {
137 readonly interactionMode: ProviderInteractionMode;
138}
139
140interface StartThreadBootstrap {
141 readonly createThread?: {
142 readonly projectId: ProjectId;
143 readonly title: string;
144 readonly modelSelection: ModelSelection;
145 readonly runtimeMode: RuntimeMode;
146 readonly interactionMode: ProviderInteractionMode;
147 readonly branch: string | null;
148 readonly worktreePath: string | null;
149 readonly createdAt: string;
150 };
151 readonly prepareWorktree?: {
152 readonly requireWorktree?: boolean;
153 readonly projectCwd: string;
154 readonly baseBranch: string;
155 readonly branch?: string;
156 readonly startFromOrigin?: boolean;
157 };
158 readonly runSetupScript?: boolean;
159}
160
161export interface StartThreadTurnInput extends ThreadCommandInput {
162 readonly manualContinuationOfRunId?: RunId;
163 readonly message: {
164 readonly messageId: MessageId;
165 readonly role: "user";
166 readonly text: string;
167 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
168 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
169 };
170 readonly modelSelection?: ModelSelection;
171 readonly titleSeed?: string;
172 readonly runtimeMode: RuntimeMode;
173 readonly interactionMode: ProviderInteractionMode;
174 readonly bootstrap?: StartThreadBootstrap;
175 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
176 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
177}
178
179export interface InterruptThreadTurnInput extends ThreadCommandInput {
180 readonly runId?: RunId;
181 readonly subagentId?: NodeId;
182 readonly turnId?: string;
183}
184
185export interface RespondToThreadApprovalInput extends ThreadCommandInput {
186 readonly requestId: RuntimeRequestId;
187 readonly decision: ProviderApprovalDecision;
188}
189
190export interface RespondToThreadUserInputInput extends ThreadCommandInput {
191 readonly requestId: RuntimeRequestId;
192 readonly answers: ProviderUserInputAnswers;
193 readonly attachmentsByQuestionId?: import("@t3tools/contracts").UserInputAttachments;
194}
195
196export interface DismissThreadUserInputInput extends ThreadCommandInput {
197 readonly requestId: RuntimeRequestId;
198}
199
200export interface RevertThreadCheckpointInput extends ThreadCommandInput {
201 readonly restoreFiles?: boolean;
202 readonly checkpointId?: string;
203 readonly scopeId?: string;
204 readonly turnCount?: number;
205}
206
207export type StopThreadSessionInput = ThreadCommandInput;
208
209export interface ForkThreadFromRunInput extends CommandMetadata {
210 readonly sourceThreadId: ThreadId;
211 readonly targetThreadId: ThreadId;
212 readonly runId: RunId;
213 readonly title?: string;
214}
215
216export interface MergeThreadBackInput extends CommandMetadata {
217 readonly sourceThreadId: ThreadId;
218 readonly targetThreadId: ThreadId;
219 readonly runId: RunId;
220}
221
222export interface ReorderQueuedRunInput extends ThreadCommandInput {
223 readonly runId: RunId;
224 readonly beforeRunId: RunId | null;
225}
226
227export interface PromoteQueuedRunInput extends ThreadCommandInput {
228 readonly queuedRunId: RunId;
229 readonly targetRunId: RunId;
230}
231
232export interface CancelQueuedRunInput extends ThreadCommandInput {
233 readonly runId: RunId;
234}
235
236export interface RetryWorkspacePreparationInput extends ThreadCommandInput {
237 readonly runId: RunId;
238}
239
240export interface EditQueuedRunInput extends ThreadCommandInput {
241 readonly runId: RunId;
242 readonly text: string;
243 /**
244 * Full replacement attachment list for the queued message. Omitted =
245 * text-only edit that leaves attachments untouched.
246 */
247 readonly edit?: {
248 readonly messageId: MessageId;
249 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
250 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
251 };
252}
253
254const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
255 input: CommandMetadata,
256) {
257 if (input.commandId !== undefined) return input.commandId;
258 const crypto = yield* Crypto.Crypto;
259 return CommandId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie));
260});
261
262const dispatch = (command: OrchestrationV2Command) =>
263 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
264
265const getProjection = (threadId: ThreadId) =>
266 request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
267
268const supportsServerResolvedCommandContext = Effect.fn(
269 "EnvironmentCommands.supportsServerResolvedCommandContext",
270)(function* () {
271 const config = yield* getInitialServerConfig();
272 return config.environment.capabilities.serverResolvedCommandContext === true;
273});
274
275const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* (
276 threadId: ThreadId,
277 messageId: MessageId,
278 attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>,
279) {
280 const stored = attachments.filter(
281 (attachment): attachment is ChatAttachment => !("dataUrl" in attachment),
282 );
283 const uploads = attachments.filter(
284 (attachment): attachment is UploadChatAttachment => "dataUrl" in attachment,
285 );
286 if (uploads.length === 0) return stored;
287 const result = yield* request(WS_METHODS.assetsPersistChatAttachments, {
288 threadId,
289 messageId,
290 attachments: uploads,
291 });
292 if (stored.length === 0) return result.attachments;
293 const byUpload = new Map(
294 uploads.map((attachment, index) => [attachment, result.attachments[index]]),
295 );
296 return attachments.flatMap((attachment) => {
297 if (!("dataUrl" in attachment)) return [attachment];
298 const persisted = byUpload.get(attachment);
299 return persisted === undefined ? [] : [persisted];
300 });
301});
302
303const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* (
304 mutation:
305 | {
306 readonly type: "project.create";
307 readonly commandId: CommandId;
308 readonly projectId: ProjectId;
309 readonly title: string;
310 readonly workspaceRoot: string;
311 readonly createWorkspaceRootIfMissing?: boolean;
312 readonly defaultModelSelection?: ModelSelection | null;
313 readonly scripts?: ReadonlyArray<ProjectScript>;
314 }
315 | {
316 readonly type: "project.update";
317 readonly commandId: CommandId;
318 readonly projectId: ProjectId;
319 readonly title?: string;
320 readonly workspaceRoot?: string;
321 readonly defaultModelSelection?: ModelSelection | null;
322 readonly scripts?: ReadonlyArray<ProjectScript>;
323 }
324 | {
325 readonly type: "project.delete";
326 readonly commandId: CommandId;
327 readonly projectId: ProjectId;
328 readonly force?: boolean;
329 },
330) {
331 return yield* request(WS_METHODS.projectsMutate, mutation);
332});
333
334export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
335 input: CreateProjectInput,
336) {
337 return yield* mutateProject({
338 type: "project.create",
339 commandId: yield* allocateCommandId(input),
340 projectId: input.projectId,
341 title: input.title,
342 workspaceRoot: input.workspaceRoot,
343 ...(input.createWorkspaceRootIfMissing === undefined
344 ? {}
345 : { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
346 ...(input.defaultModelSelection === undefined
347 ? {}
348 : { defaultModelSelection: input.defaultModelSelection }),
349 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
350 });
351});
352
353export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
354 input: UpdateProjectInput,
355) {
356 return yield* mutateProject({
357 type: "project.update",
358 commandId: yield* allocateCommandId(input),
359 projectId: input.projectId,
360 ...(input.title === undefined ? {} : { title: input.title }),
361 ...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
362 ...(input.defaultModelSelection === undefined
363 ? {}
364 : { defaultModelSelection: input.defaultModelSelection }),
365 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
366 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
367 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
368 ...(input.defaultThreadEnvMode === undefined
369 ? {}
370 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
371 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
372 });
373});
374
375export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
376 input: DeleteProjectInput,
377) {
378 return yield* mutateProject({
379 type: "project.delete",
380 commandId: yield* allocateCommandId(input),
381 projectId: input.projectId,
382 ...(input.force === undefined ? {} : { force: input.force }),
383 });
384});
385
386export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
387 input: CreateThreadInput,
388) {
389 return yield* dispatch({
390 type: "thread.create",
391 commandId: yield* allocateCommandId(input),
392 createdBy: "user",
393 creationSource: input.creationSource ?? "web",
394 threadId: input.threadId,
395 projectId: input.projectId,
396 title: input.title,
397 modelSelection: input.modelSelection,
398 runtimeMode: input.runtimeMode,
399 interactionMode: input.interactionMode,
400 branch: input.branch,
401 worktreePath: input.worktreePath,
402 });
403});
404
405function simpleThreadCommand(
406 type:
407 | "thread.delete"
408 | "thread.archive"
409 | "thread.unarchive"
410 | "thread.settle"
411 | "thread.pin"
412 | "thread.unpin",
413 input: ThreadCommandInput,
414) {
415 return allocateCommandId(input).pipe(
416 Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
417 );
418}
419
420export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
421 input: DeleteThreadInput,
422) {
423 return yield* simpleThreadCommand("thread.delete", input);
424});
425
426export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
427 input: ArchiveThreadInput,
428) {
429 return yield* simpleThreadCommand("thread.archive", input);
430});
431
432export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
433 input: UnarchiveThreadInput,
434) {
435 return yield* simpleThreadCommand("thread.unarchive", input);
436});
437
438export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
439 input: SettleThreadInput,
440) {
441 return yield* simpleThreadCommand("thread.settle", input);
442});
443
444export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* (
445 input: PinThreadInput,
446) {
447 const commandId = yield* allocateCommandId(input);
448 return yield* dispatch({
449 type: "thread.pin",
450 commandId,
451 threadId: input.threadId,
452 ...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }),
453 });
454});
455
456export interface SetThreadAutoSettleInput extends ThreadCommandInput {
457 readonly enabled: boolean;
458}
459export const setThreadAutoSettle = Effect.fn("EnvironmentCommands.setThreadAutoSettle")(function* (
460 input: SetThreadAutoSettleInput,
461) {
462 return yield* dispatch({
463 type: "thread.auto-settle.set",
464 commandId: yield* allocateCommandId(input),
465 threadId: input.threadId,
466 enabled: input.enabled,
467 });
468});
469
470export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* (
471 input: ReorderPinnedThreadInput,
472) {
473 const commandId = yield* allocateCommandId(input);
474 return yield* dispatch({
475 type: "thread.pin.reorder",
476 commandId,
477 threadId: input.threadId,
478 orderKey: input.orderKey,
479 });
480});
481
482export const reorderActiveThread = Effect.fn("EnvironmentCommands.reorderActiveThread")(function* (
483 input: ReorderActiveThreadInput,
484) {
485 return yield* dispatch({
486 type: "thread.active.reorder",
487 commandId: yield* allocateCommandId(input),
488 threadId: input.threadId,
489 orderKey: input.orderKey,
490 });
491});
492
493export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* (
494 input: UnpinThreadInput,
495) {
496 return yield* simpleThreadCommand("thread.unpin", input);
497});
498
499export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
500 input: UnsettleThreadInput,
501) {
502 return yield* dispatch({
503 type: "thread.unsettle",
504 commandId: yield* allocateCommandId(input),
505 threadId: input.threadId,
506 reason: input.reason,
507 });
508});
509
510export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
511 input: SnoozeThreadInput,
512) {
513 return yield* dispatch({
514 type: "thread.snooze",
515 commandId: yield* allocateCommandId(input),
516 threadId: input.threadId,
517 snoozedUntil: input.snoozedUntil,
518 });
519});
520
521export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
522 input: UnsnoozeThreadInput,
523) {
524 return yield* dispatch({
525 type: "thread.unsnooze",
526 commandId: yield* allocateCommandId(input),
527 threadId: input.threadId,
528 reason: input.reason,
529 });
530});
531
532export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
533 input: VisitThreadInput,
534) {
535 return yield* dispatch({
536 type: "thread.visit",
537 commandId: yield* allocateCommandId(input),
538 threadId: input.threadId,
539 visitedAt: input.visitedAt,
540 });
541});
542
543export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
544 input: MarkThreadUnreadInput,
545) {
546 return yield* dispatch({
547 type: "thread.mark-unread",
548 commandId: yield* allocateCommandId(input),
549 threadId: input.threadId,
550 });
551});
552
553export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
554 function* (input: UpdateThreadMetadataInput) {
555 const commandId = yield* allocateCommandId(input);
556 let result = null;
557 if (
558 input.title !== undefined ||
559 input.branch !== undefined ||
560 input.worktreePath !== undefined ||
561 input.regenerateTitle !== undefined ||
562 input.linkedPullRequest !== undefined ||
563 input.limitRecovery !== undefined
564 ) {
565 result = yield* dispatch({
566 type: "thread.metadata.update",
567 ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }),
568 commandId,
569 threadId: input.threadId,
570 ...(input.title === undefined ? {} : { title: input.title }),
571 ...(input.branch === undefined ? {} : { branch: input.branch }),
572 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
573 ...(input.expectedEmpty === true ? { expectedEmpty: true } : {}),
574 ...(input.regenerateTitle === undefined ? {} : { regenerateTitle: input.regenerateTitle }),
575 ...(input.linkedPullRequest === undefined
576 ? {}
577 : { linkedPullRequest: input.linkedPullRequest }),
578 });
579 }
580 if (input.modelSelection !== undefined) {
581 const type = (yield* supportsServerResolvedCommandContext())
582 ? ("thread.model-selection.set" as const)
583 : modelSelectionCommandType(
584 (yield* getProjection(input.threadId)).thread.providerInstanceId,
585 input.modelSelection,
586 );
587 result = yield* dispatch({
588 type,
589 commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
590 threadId: input.threadId,
591 modelSelection: input.modelSelection,
592 });
593 }
594 return result ?? { sequence: 0 };
595 },
596);
597
598export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
599 function* (input: SetThreadRuntimeModeInput) {
600 return yield* dispatch({
601 type: "thread.runtime-mode.set",
602 commandId: yield* allocateCommandId(input),
603 threadId: input.threadId,
604 runtimeMode: input.runtimeMode,
605 });
606 },
607);
608
609export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
610 function* (input: SetThreadInteractionModeInput) {
611 return yield* dispatch({
612 type: "thread.interaction-mode.set",
613 commandId: yield* allocateCommandId(input),
614 threadId: input.threadId,
615 interactionMode: input.interactionMode,
616 });
617 },
618);
619
620export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
621 input: StartThreadTurnInput,
622) {
623 const commandId = yield* allocateCommandId(input);
624 const attachments = yield* persistAttachments(
625 input.threadId,
626 input.message.messageId,
627 input.message.attachments,
628 );
629 const context = remapComposerContextAttachments(
630 input.message.context,
631 input.message.attachments,
632 attachments,
633 );
634 const bootstrap = input.bootstrap?.createThread;
635 const prepareWorktree = input.bootstrap?.prepareWorktree;
636 if (bootstrap !== undefined || prepareWorktree !== undefined) {
637 const existingProjection =
638 bootstrap === undefined ? yield* getProjection(input.threadId) : null;
639 const thread = bootstrap ?? existingProjection!.thread;
640 const workspaceStrategy =
641 prepareWorktree !== undefined
642 ? {
643 type: "worktree" as const,
644 baseRef: prepareWorktree.baseBranch,
645 ...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
646 ...(prepareWorktree.startFromOrigin === undefined
647 ? {}
648 : { startFromOrigin: prepareWorktree.startFromOrigin }),
649 }
650 : bootstrap?.worktreePath
651 ? {
652 type: "existing_worktree" as const,
653 worktreePath: bootstrap.worktreePath,
654 ...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
655 }
656 : {
657 type: "root" as const,
658 ...(bootstrap?.branch === null || bootstrap?.branch === undefined
659 ? {}
660 : { branch: bootstrap.branch }),
661 };
662 return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
663 commandId,
664 creationSource: input.creationSource ?? "web",
665 threadId: input.threadId,
666 ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
667 projectId: thread.projectId,
668 title: input.titleSeed ?? thread.title,
669 generateTitle: input.titleSeed !== undefined,
670 modelSelection: input.modelSelection ?? thread.modelSelection,
671 runtimeMode: input.runtimeMode,
672 interactionMode: input.interactionMode,
673 workspaceStrategy,
674 initialMessage: {
675 messageId: input.message.messageId,
676 text: input.message.text,
677 ...(context ? { context } : {}),
678 attachments,
679 },
680 });
681 }
682
683 const requestedMode = input.dispatchMode ?? "auto";
684 if (requestedMode === "start") {
685 return yield* dispatch({
686 type: "message.dispatch",
687 commandId,
688 createdBy: "user",
689 creationSource: input.creationSource ?? "web",
690 threadId: input.threadId,
691 messageId: input.message.messageId,
692 ...(input.manualContinuationOfRunId === undefined
693 ? {}
694 : { manualContinuationOfRunId: input.manualContinuationOfRunId }),
695 text: input.message.text,
696 ...(context ? { context } : {}),
697 attachments,
698 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
699 ...(input.sourceProposedPlan === undefined
700 ? {}
701 : { sourcePlanRef: input.sourceProposedPlan }),
702 dispatchMode: { type: "start_immediately" },
703 });
704 }
705
706 const serverResolvesCommandContext = yield* supportsServerResolvedCommandContext();
707 const projection = serverResolvesCommandContext ? null : yield* getProjection(input.threadId);
708 const activeRun = projection?.runs.findLast(
709 (run) =>
710 run.status === "preparing" ||
711 run.status === "starting" ||
712 run.status === "running" ||
713 run.status === "waiting",
714 );
715 const activeProviderThread =
716 activeRun === undefined
717 ? undefined
718 : projection?.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
719 const activeProviderSession =
720 activeProviderThread?.providerSessionId === null ||
721 activeProviderThread?.providerSessionId === undefined
722 ? undefined
723 : projection?.providerSessions.find(
724 (session) => session.id === activeProviderThread.providerSessionId,
725 );
726 const turnCapabilities = activeProviderSession?.capabilities.turns;
727 const dispatchMode = serverResolvesCommandContext
728 ? requestedMode === "queue"
729 ? ({ type: "queue_after_active" } as const)
730 : ({ type: "start_immediately" } as const)
731 : activeRun === undefined
732 ? ({ type: "start_immediately" } as const)
733 : requestedMode === "steer"
734 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
735 : requestedMode === "restart"
736 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
737 : requestedMode === "queue"
738 ? ({ type: "queue_after_active" } as const)
739 : turnCapabilities?.supportsActiveSteering === true
740 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
741 : turnCapabilities?.supportsQueuedMessages === true
742 ? ({ type: "queue_after_active" } as const)
743 : turnCapabilities?.supportsSteeringByInterruptRestart === true
744 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
745 : ({ type: "queue_after_active" } as const);
746 const shouldSendTitleSeed =
747 input.titleSeed !== undefined &&
748 (serverResolvesCommandContext || projection?.messages.length === 0);
749 return yield* dispatch({
750 type: "message.dispatch",
751 commandId,
752 createdBy: "user",
753 creationSource: input.creationSource ?? "web",
754 threadId: input.threadId,
755 messageId: input.message.messageId,
756 text: input.message.text,
757 ...(context ? { context } : {}),
758 attachments,
759 ...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
760 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
761 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
762 ...(serverResolvesCommandContext && requestedMode !== "queue"
763 ? { deliveryIntent: requestedMode }
764 : {}),
765 dispatchMode,
766 });
767});
768
769export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
770 input: InterruptThreadTurnInput,
771) {
772 if (input.subagentId !== undefined) {
773 const projection = yield* getProjection(input.threadId);
774 const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);
775 if (subagent?.runId == null) return { sequence: 0 };
776 return yield* dispatch({
777 type: "subagent.stop",
778 commandId: yield* allocateCommandId(input),
779 threadId: input.threadId,
780 runId: subagent.runId,
781 subagentId: subagent.id,
782 });
783 }
784 let runId = input.runId ?? (input.turnId as RunId | undefined);
785 if (runId === undefined) {
786 const config = yield* getInitialServerConfig();
787 if (config.environment.capabilities.threadStop === true) {
788 // A paginated projection can omit commands still running from earlier turns.
789 return yield* dispatch({
790 type: "thread.stop",
791 commandId: yield* allocateCommandId(input),
792 threadId: input.threadId,
793 });
794 }
795 }
796 if (runId === undefined) {
797 const projection = yield* getProjection(input.threadId);
798 runId = projection.runs.findLast(
799 (run) =>
800 run.status === "preparing" ||
801 run.status === "starting" ||
802 run.status === "running" ||
803 run.status === "waiting",
804 )?.id;
805 if (runId === undefined) {
806 const latestRun = projection.runs.at(-1);
807 if (
808 derivePendingBackgroundWork({
809 latestRun,
810 providerThreads: projection.providerThreads,
811 turnItems: projection.turnItems,
812 activeProviderThreadId: projection.thread.activeProviderThreadId,
813 runs: projection.runs,
814 }).length > 0
815 ) {
816 runId = latestRun?.id;
817 }
818 }
819 if (runId === undefined) {
820 let result = { sequence: 0 };
821 for (const link of visibleThreadPullRequests(projection.thread.pullRequests ?? [])) {
822 if (link.watch === undefined) continue;
823 result = yield* dispatch({
824 type: "thread.pull-request.watch",
825 commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),
826 threadId: input.threadId,
827 host: link.host,
828 repository: link.repository,
829 number: link.number,
830 watching: false,
831 });
832 }
833 return result;
834 }
835 }
836 if (runId === undefined) return { sequence: 0 };
837 return yield* dispatch({
838 type: "run.interrupt",
839 commandId: yield* allocateCommandId(input),
840 threadId: input.threadId,
841 runId,
842 holdQueue: true,
843 });
844});
845
846export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
847 function* (input: RespondToThreadApprovalInput) {
848 return yield* dispatch({
849 type: "runtime-request.respond",
850 commandId: yield* allocateCommandId(input),
851 threadId: input.threadId,
852 requestId: input.requestId,
853 decision: input.decision,
854 });
855 },
856);
857
858export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
859 function* (input: RespondToThreadUserInputInput) {
860 return yield* dispatch({
861 type: "runtime-request.respond",
862 commandId: yield* allocateCommandId(input),
863 threadId: input.threadId,
864 requestId: input.requestId,
865 answers: input.answers,
866 ...(input.attachmentsByQuestionId === undefined
867 ? {}
868 : { attachmentsByQuestionId: input.attachmentsByQuestionId }),
869 });
870 },
871);
872
873export const dismissThreadUserInput = Effect.fn("EnvironmentCommands.dismissThreadUserInput")(
874 function* (input: DismissThreadUserInputInput) {
875 return yield* dispatch({
876 type: "thread.user-input.dismiss",
877 commandId: yield* allocateCommandId(input),
878 threadId: input.threadId,
879 requestId: input.requestId,
880 });
881 },
882);
883
884export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
885 function* (input: RevertThreadCheckpointInput) {
886 if (
887 input.checkpointId !== undefined &&
888 input.scopeId !== undefined &&
889 (yield* supportsServerResolvedCommandContext())
890 ) {
891 return yield* dispatch({
892 type: "checkpoint.rollback",
893 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
894 commandId: yield* allocateCommandId(input),
895 threadId: input.threadId,
896 scopeId: CheckpointScopeId.make(input.scopeId),
897 checkpointId: CheckpointId.make(input.checkpointId),
898 });
899 }
900 const projection = yield* getProjection(input.threadId);
901 const checkpoint =
902 projection.checkpoints.find(
903 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
904 ) ??
905 projection.checkpoints.findLast((candidate) =>
906 input.turnCount === 0
907 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
908 : candidate.appRunOrdinal === input.turnCount,
909 );
910 if (checkpoint === undefined || checkpoint.status !== "ready") {
911 const target =
912 input.checkpointId === undefined
913 ? `run ordinal ${input.turnCount ?? "unknown"}`
914 : `checkpoint ${input.checkpointId}`;
915 return yield* new OrchestrationV2CheckpointUnavailableError({
916 threadId: input.threadId,
917 target,
918 });
919 }
920 return yield* dispatch({
921 type: "checkpoint.rollback",
922 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
923 commandId: yield* allocateCommandId(input),
924 threadId: input.threadId,
925 scopeId: checkpoint.scopeId,
926 checkpointId: checkpoint.id,
927 });
928 },
929);
930
931export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
932 input: StopThreadSessionInput,
933) {
934 const projection = yield* getProjection(input.threadId);
935 const commandId = yield* allocateCommandId(input);
936 let result = { sequence: 0 };
937 for (const session of projection.providerSessions) {
938 result = yield* dispatch({
939 type: "provider-session.detach",
940 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
941 threadId: input.threadId,
942 providerSessionId: session.id,
943 reason: "client-requested",
944 });
945 }
946 return result;
947});
948
949export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
950 input: ForkThreadFromRunInput,
951) {
952 return yield* dispatch({
953 type: "thread.fork",
954 commandId: yield* allocateCommandId(input),
955 createdBy: "user",
956 creationSource: input.creationSource ?? "web",
957 sourceThreadId: input.sourceThreadId,
958 targetThreadId: input.targetThreadId,
959 sourcePoint: { type: "run", runId: input.runId },
960 ...(input.title === undefined ? {} : { title: input.title }),
961 });
962});
963
964export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
965 input: MergeThreadBackInput,
966) {
967 return yield* dispatch({
968 type: "thread.merge_back",
969 commandId: yield* allocateCommandId(input),
970 createdBy: "user",
971 creationSource: input.creationSource ?? "web",
972 sourceThreadId: input.sourceThreadId,
973 targetThreadId: input.targetThreadId,
974 sourcePoint: { type: "run", runId: input.runId },
975 });
976});
977
978export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
979 input: ThreadCommandInput,
980) {
981 return yield* dispatch({
982 type: "queue.resume",
983 commandId: yield* allocateCommandId(input),
984 threadId: input.threadId,
985 });
986});
987
988export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
989 input: ReorderQueuedRunInput,
990) {
991 return yield* dispatch({
992 type: "queued-run.reorder",
993 commandId: yield* allocateCommandId(input),
994 threadId: input.threadId,
995 runId: input.runId,
996 beforeRunId: input.beforeRunId,
997 });
998});
999
1000export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
1001 input: PromoteQueuedRunInput,
1002) {
1003 return yield* dispatch({
1004 type: "queued-message.promote-to-steer",
1005 commandId: yield* allocateCommandId(input),
1006 threadId: input.threadId,
1007 queuedRunId: input.queuedRunId,
1008 targetRunId: input.targetRunId,
1009 });
1010});
1011
1012export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
1013 input: CancelQueuedRunInput,
1014) {
1015 return yield* dispatch({
1016 type: "queued-run.cancel",
1017 commandId: yield* allocateCommandId(input),
1018 threadId: input.threadId,
1019 runId: input.runId,
1020 });
1021});
1022
1023export const retryWorkspacePreparation = Effect.fn("EnvironmentCommands.retryWorkspacePreparation")(
1024 function* (input: RetryWorkspacePreparationInput) {
1025 return yield* dispatch({
1026 type: "prepared-run.retry",
1027 commandId: yield* allocateCommandId(input),
1028 threadId: input.threadId,
1029 runId: input.runId,
1030 });
1031 },
1032);
1033
1034export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
1035 input: EditQueuedRunInput,
1036) {
1037 const attachments =
1038 input.edit === undefined
1039 ? undefined
1040 : yield* persistAttachments(input.threadId, input.edit.messageId, input.edit.attachments);
1041 return yield* dispatch({
1042 type: "queued-run.edit",
1043 commandId: yield* allocateCommandId(input),
1044 threadId: input.threadId,
1045 runId: input.runId,
1046 text: input.text,
1047 ...(attachments === undefined ? {} : { attachments }),
1048 ...(input.edit?.context && attachments
1049 ? {
1050 context: remapComposerContextAttachments(
1051 input.edit.context,
1052 input.edit.attachments,
1053 attachments,
1054 ),
1055 }
1056 : {}),
1057 });
1058});
1059
1060export type LinkThreadPullRequestInput = Omit<
1061 Extract<OrchestrationV2Command, { type: "thread.pull-request.link" }>,
1062 "type" | "commandId"
1063> &
1064 CommandMetadata;
1065export type UnlinkThreadPullRequestInput = Omit<
1066 Extract<OrchestrationV2Command, { type: "thread.pull-request.unlink" }>,
1067 "type" | "commandId"
1068> &
1069 CommandMetadata;
1070export const linkThreadPullRequest = Effect.fn("EnvironmentCommands.linkThreadPullRequest")(
1071 function* (input: LinkThreadPullRequestInput) {
1072 return yield* dispatch({
1073 ...input,
1074 type: "thread.pull-request.link",
1075 commandId: yield* allocateCommandId(input),
1076 });
1077 },
1078);
1079export type WatchThreadPullRequestInput = Omit<
1080 Extract<OrchestrationV2Command, { type: "thread.pull-request.watch" }>,
1081 "type" | "commandId"
1082> &
1083 CommandMetadata;
1084export const watchThreadPullRequest = Effect.fn("EnvironmentCommands.watchThreadPullRequest")(
1085 function* (input: WatchThreadPullRequestInput) {
1086 return yield* dispatch({
1087 ...input,
1088 type: "thread.pull-request.watch",
1089 commandId: yield* allocateCommandId(input),
1090 });
1091 },
1092);
1093export const unlinkThreadPullRequest = Effect.fn("EnvironmentCommands.unlinkThreadPullRequest")(
1094 function* (input: UnlinkThreadPullRequestInput) {
1095 return yield* dispatch({
1096 ...input,
1097 type: "thread.pull-request.unlink",
1098 commandId: yield* allocateCommandId(input),
1099 });
1100 },
1101);