Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commands.ts

989 lines33.0 KB

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