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