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