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