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