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