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

commands.ts

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