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

commands.ts

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