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

commands.ts

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