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