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