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

commands.ts

1,180 lines39.5 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 { modelSelectionCommandType } from "@t3tools/shared/model";
32import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
33import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
34import * as Crypto from "effect/Crypto";
35import * as Effect from "effect/Effect";
36​
37import { getInitialServerConfig, request } from "../rpc/client.ts";
38​
39interface CommandMetadata {
40 readonly commandId?: CommandId;
41 readonly createdAt?: string;
42 readonly creationSource?: OrchestrationV2CreationSource;
44​
45export interface CreateProjectInput extends CommandMetadata {
46 readonly projectId: ProjectId;
47 readonly title: string;
48 readonly workspaceRoot: string;
49 readonly createWorkspaceRootIfMissing?: boolean;
50 readonly defaultModelSelection?: ModelSelection | null;
51 readonly scripts?: ReadonlyArray<ProjectScript>;
53​
54export interface UpdateProjectInput extends CommandMetadata {
55 readonly projectId: ProjectId;
56 readonly title?: string;
57 readonly workspaceRoot?: string;
58 readonly defaultModelSelection?: ModelSelection | null;
59 readonly autoPull?: boolean;
60 readonly projectIcon?: ProjectIconOverride | null;
61 readonly faviconPath?: string | null;
62 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
63 readonly scripts?: ReadonlyArray<ProjectScript>;
65​
66export interface DeleteProjectInput extends CommandMetadata {
67 readonly projectId: ProjectId;
68 readonly force?: boolean;
70​
71export interface CreateThreadInput extends CommandMetadata {
72 readonly threadId: ThreadId;
73 readonly projectId: ProjectId;
74 readonly title: string;
75 readonly modelSelection: ModelSelection;
76 readonly runtimeMode: RuntimeMode;
77 readonly interactionMode: ProviderInteractionMode;
78 readonly branch: string | null;
79 readonly worktreePath: string | null;
81​
82export interface ThreadCommandInput extends CommandMetadata {
83 readonly threadId: ThreadId;
85​
86export type DeleteThreadInput = ThreadCommandInput;
87export type ArchiveThreadInput = ThreadCommandInput;
88export type UnarchiveThreadInput = ThreadCommandInput;
89export type SettleThreadInput = ThreadCommandInput;
90​
91export interface UnsettleThreadInput extends ThreadCommandInput {
92 readonly reason: "user";
94​
95export interface PinThreadInput extends ThreadCommandInput {
96 readonly orderKey?: string;
98export type UnpinThreadInput = ThreadCommandInput;
99​
100export interface ReorderPinnedThreadInput extends ThreadCommandInput {
101 readonly orderKey: string;
103​
104export interface ReorderActiveThreadInput extends ThreadCommandInput {
105 readonly orderKey: string;
107​
108export interface SnoozeThreadInput extends ThreadCommandInput {
109 readonly snoozedUntil: string;
111​
112export interface UnsnoozeThreadInput extends ThreadCommandInput {
113 readonly reason: "user";
115​
116export interface VisitThreadInput extends ThreadCommandInput {
117 readonly visitedAt: string;
118 /** Counts toward search frecency; `searchQuery` is the palette query that picked it. */
119 readonly opened?: boolean;
120 readonly searchQuery?: string;
122​
123export type MarkThreadUnreadInput = ThreadCommandInput;
124​
125export interface UpdateThreadMetadataInput extends ThreadCommandInput {
126 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecoveryUpdate | null;
127 readonly title?: string;
128 readonly modelSelection?: ModelSelection;
129 readonly branch?: string | null;
130 readonly worktreePath?: string | null;
131 readonly regenerateTitle?: boolean;
132 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
133 readonly expectedEmpty?: boolean;
135​
136export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
137 readonly runtimeMode: RuntimeMode;
139​
140export interface SetThreadInteractionModeInput extends ThreadCommandInput {
141 readonly interactionMode: ProviderInteractionMode;
143​
144interface StartThreadBootstrap {
145 readonly createThread?: {
146 readonly projectId: ProjectId;
147 readonly title: string;
148 readonly modelSelection: ModelSelection;
149 readonly runtimeMode: RuntimeMode;
150 readonly interactionMode: ProviderInteractionMode;
151 readonly branch: string | null;
152 readonly worktreePath: string | null;
153 readonly createdAt: string;
154 };
155 readonly prepareWorktree?: {
156 readonly requireWorktree?: boolean;
157 readonly projectCwd: string;
158 readonly baseBranch: string;
159 readonly branch?: string;
160 readonly startFromOrigin?: boolean;
161 };
162 readonly runSetupScript?: boolean;
164​
165export interface StartThreadTurnInput extends ThreadCommandInput {
166 readonly manualContinuationOfRunId?: RunId;
167 readonly message: {
168 readonly messageId: MessageId;
169 readonly role: "user";
170 readonly text: string;
171 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
172 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
173 readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
174 };
175 readonly modelSelection?: ModelSelection;
176 readonly titleSeed?: string;
177 readonly runtimeMode: RuntimeMode;
178 readonly interactionMode: ProviderInteractionMode;
179 readonly bootstrap?: StartThreadBootstrap;
180 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
181 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
183​
184export interface InterruptThreadTurnInput extends ThreadCommandInput {
185 readonly runId?: RunId;
186 readonly subagentId?: NodeId;
187 readonly turnId?: string;
189​
190export interface RespondToThreadApprovalInput extends ThreadCommandInput {
191 readonly requestId: RuntimeRequestId;
192 readonly decision: ProviderApprovalDecision;
193 readonly feedback?: string;
195​
196export interface RespondToThreadUserInputInput extends ThreadCommandInput {
197 readonly requestId: RuntimeRequestId;
198 readonly answers: ProviderUserInputAnswers;
199 readonly attachmentsByQuestionId?: import("@t3tools/contracts").UserInputAttachments;
201​
202export interface DismissThreadUserInputInput extends ThreadCommandInput {
203 readonly requestId: RuntimeRequestId;
205​
206export interface RevertThreadCheckpointInput extends ThreadCommandInput {
207 readonly restoreFiles?: boolean;
208 readonly checkpointId?: string;
209 readonly scopeId?: string;
210 readonly turnCount?: number;
212​
213export type StopThreadSessionInput = ThreadCommandInput;
214​
215export interface ForkThreadFromRunInput extends CommandMetadata {
216 readonly sourceThreadId: ThreadId;
217 readonly targetThreadId: ThreadId;
218 readonly runId: RunId;
219 readonly title?: string;
221​
222export interface MergeThreadBackInput extends CommandMetadata {
223 readonly sourceThreadId: ThreadId;
224 readonly targetThreadId: ThreadId;
225 readonly runId: RunId;
227​
228export interface ResumeThreadQueueInput extends ThreadCommandInput {
229 readonly runId?: RunId;
231​
232export interface ReorderQueuedRunInput extends ThreadCommandInput {
233 readonly runId: RunId;
234 readonly beforeRunId: RunId | null;
236​
237export interface PromoteQueuedRunInput extends ThreadCommandInput {
238 readonly queuedRunId: RunId;
239 readonly targetRunId: RunId;
241​
242export interface CancelQueuedRunInput extends ThreadCommandInput {
243 readonly runId: RunId;
245​
246export interface RetryWorkspacePreparationInput extends ThreadCommandInput {
247 readonly runId: RunId;
249​
250export interface EditQueuedRunInput extends ThreadCommandInput {
251 readonly runId: RunId;
252 readonly text: string;
253 /**
254 * Full replacement attachment list for the queued message. Omitted =
255 * text-only edit that leaves attachments untouched.
256 */
257 readonly edit?: {
258 readonly messageId: MessageId;
259 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
260 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
261 };
263​
264const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
265 input: CommandMetadata,
266) {
267 if (input.commandId !== undefined) return input.commandId;
268 const crypto = yield* Crypto.Crypto;
269 return CommandId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie));
270});
271​
272const dispatch = (command: OrchestrationV2Command) =>
273 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
274​
275const getProjection = (threadId: ThreadId) =>
276 request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
277​
278const supportsServerResolvedCommandContext = Effect.fn(
279 "EnvironmentCommands.supportsServerResolvedCommandContext",
280)(function* () {
281 const config = yield* getInitialServerConfig();
282 return config.environment.capabilities.serverResolvedCommandContext === true;
283});
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 });
383});
384​
385export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
386 input: DeleteProjectInput,
387) {
388 return yield* mutateProject({
389 type: "project.delete",
390 commandId: yield* allocateCommandId(input),
391 projectId: input.projectId,
392 ...(input.force === undefined ? {} : { force: input.force }),
393 });
394});
395​
396export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
397 input: CreateThreadInput,
398) {
399 return yield* dispatch({
400 type: "thread.create",
401 commandId: yield* allocateCommandId(input),
402 createdBy: "user",
403 creationSource: input.creationSource ?? "web",
404 threadId: input.threadId,
405 projectId: input.projectId,
406 title: input.title,
407 modelSelection: input.modelSelection,
408 runtimeMode: input.runtimeMode,
409 interactionMode: input.interactionMode,
410 branch: input.branch,
411 worktreePath: input.worktreePath,
412 });
413});
414​
415function simpleThreadCommand(
416 type:
417 | "thread.delete"
418 | "thread.archive"
419 | "thread.unarchive"
420 | "thread.settle"
421 | "thread.pin"
422 | "thread.unpin"
423 | "thread.guest-share.close",
424 input: ThreadCommandInput,
425) {
426 return allocateCommandId(input).pipe(
427 Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
428 );
430​
431export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
432 input: DeleteThreadInput,
433) {
434 return yield* simpleThreadCommand("thread.delete", input);
435});
436​
437export type CloseGuestShareInput = ThreadCommandInput;
438export const closeGuestShare = Effect.fn("EnvironmentCommands.closeGuestShare")(function* (
439 input: CloseGuestShareInput,
440) {
441 return yield* simpleThreadCommand("thread.guest-share.close", input);
442});
443​
444export interface ResolveGuestMessageInput extends ThreadCommandInput {
445 readonly guestMessageId: GuestMessageId;
446 readonly decision: "send" | "dismiss";
447 readonly creationSource?: "web" | "mobile";
449/** Send runs the guest's text as a normal turn; the server supplies the text, not the client. */
450export const resolveGuestMessage = Effect.fn("EnvironmentCommands.resolveGuestMessage")(function* (
451 input: ResolveGuestMessageInput,
452) {
453 const commandId = yield* allocateCommandId(input);
454 if (input.decision === "dismiss") {
455 return yield* dispatch({
456 type: "thread.guest-message.dismiss",
457 commandId,
458 threadId: input.threadId,
459 guestMessageId: input.guestMessageId,
460 });
461 }
462 return yield* dispatch({
463 type: "message.dispatch",
464 commandId,
465 threadId: input.threadId,
466 messageId: MessageId.make(commandId),
467 guestMessageId: input.guestMessageId,
468 text: "",
469 attachments: [],
470 dispatchMode: { type: "queue_after_active" },
471 createdBy: "user",
472 creationSource: input.creationSource ?? "web",
473 });
474});
475​
476export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
477 input: ArchiveThreadInput,
478) {
479 return yield* simpleThreadCommand("thread.archive", input);
480});
481​
482export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
483 input: UnarchiveThreadInput,
484) {
485 return yield* simpleThreadCommand("thread.unarchive", input);
486});
487​
488export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
489 input: SettleThreadInput,
490) {
491 return yield* simpleThreadCommand("thread.settle", input);
492});
493​
494export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* (
495 input: PinThreadInput,
496) {
497 const commandId = yield* allocateCommandId(input);
498 return yield* dispatch({
499 type: "thread.pin",
500 commandId,
501 threadId: input.threadId,
502 ...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }),
503 });
504});
505​
506export interface SetThreadAutoSettleInput extends ThreadCommandInput {
507 readonly enabled: boolean;
509export const setThreadAutoSettle = Effect.fn("EnvironmentCommands.setThreadAutoSettle")(function* (
510 input: SetThreadAutoSettleInput,
511) {
512 return yield* dispatch({
513 type: "thread.auto-settle.set",
514 commandId: yield* allocateCommandId(input),
515 threadId: input.threadId,
516 enabled: input.enabled,
517 });
518});
519​
520export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* (
521 input: ReorderPinnedThreadInput,
522) {
523 const commandId = yield* allocateCommandId(input);
524 return yield* dispatch({
525 type: "thread.pin.reorder",
526 commandId,
527 threadId: input.threadId,
528 orderKey: input.orderKey,
529 });
530});
531​
532export const reorderActiveThread = Effect.fn("EnvironmentCommands.reorderActiveThread")(function* (
533 input: ReorderActiveThreadInput,
534) {
535 return yield* dispatch({
536 type: "thread.active.reorder",
537 commandId: yield* allocateCommandId(input),
538 threadId: input.threadId,
539 orderKey: input.orderKey,
540 });
541});
542​
543export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* (
544 input: UnpinThreadInput,
545) {
546 return yield* simpleThreadCommand("thread.unpin", input);
547});
548​
549export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
550 input: UnsettleThreadInput,
551) {
552 return yield* dispatch({
553 type: "thread.unsettle",
554 commandId: yield* allocateCommandId(input),
555 threadId: input.threadId,
556 reason: input.reason,
557 });
558});
559​
560export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
561 input: SnoozeThreadInput,
562) {
563 return yield* dispatch({
564 type: "thread.snooze",
565 commandId: yield* allocateCommandId(input),
566 threadId: input.threadId,
567 snoozedUntil: input.snoozedUntil,
568 });
569});
570​
571export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
572 input: UnsnoozeThreadInput,
573) {
574 return yield* dispatch({
575 type: "thread.unsnooze",
576 commandId: yield* allocateCommandId(input),
577 threadId: input.threadId,
578 reason: input.reason,
579 });
580});
581​
582export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
583 input: VisitThreadInput,
584) {
585 return yield* dispatch({
586 type: "thread.visit",
587 commandId: yield* allocateCommandId(input),
588 threadId: input.threadId,
589 visitedAt: input.visitedAt,
590 ...(input.opened ? { opened: true } : {}),
591 ...(input.searchQuery ? { searchQuery: input.searchQuery } : {}),
592 });
593});
594​
595export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
596 input: MarkThreadUnreadInput,
597) {
598 return yield* dispatch({
599 type: "thread.mark-unread",
600 commandId: yield* allocateCommandId(input),
601 threadId: input.threadId,
602 });
603});
604​
605export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
606 function* (input: UpdateThreadMetadataInput) {
607 const commandId = yield* allocateCommandId(input);
608 let result = null;
609 if (
610 input.title !== undefined ||
611 input.branch !== undefined ||
612 input.worktreePath !== undefined ||
613 input.regenerateTitle !== undefined ||
614 input.linkedPullRequest !== undefined ||
615 input.limitRecovery !== undefined
616 ) {
617 result = yield* dispatch({
618 type: "thread.metadata.update",
619 ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }),
620 commandId,
621 threadId: input.threadId,
622 ...(input.title === undefined ? {} : { title: input.title }),
623 ...(input.branch === undefined ? {} : { branch: input.branch }),
624 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
625 ...(input.expectedEmpty === true ? { expectedEmpty: true } : {}),
626 ...(input.regenerateTitle === undefined ? {} : { regenerateTitle: input.regenerateTitle }),
627 ...(input.linkedPullRequest === undefined
628 ? {}
629 : { linkedPullRequest: input.linkedPullRequest }),
630 });
631 }
632 if (input.modelSelection !== undefined) {
633 const type = (yield* supportsServerResolvedCommandContext())
634 ? ("thread.model-selection.set" as const)
635 : modelSelectionCommandType(
636 (yield* getProjection(input.threadId)).thread.providerInstanceId,
637 input.modelSelection,
638 );
639 result = yield* dispatch({
640 type,
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 dispatchMode: { type: "start_immediately" },
758 });
759 }
760​
761 const serverResolvesCommandContext = yield* supportsServerResolvedCommandContext();
762 const projection = serverResolvesCommandContext ? null : yield* getProjection(input.threadId);
763 const activeRun = projection?.runs.findLast(
764 (run) =>
765 run.status === "preparing" ||
766 run.status === "starting" ||
767 run.status === "running" ||
768 run.status === "waiting",
769 );
770 const activeProviderThread =
771 activeRun === undefined
772 ? undefined
773 : projection?.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
774 const activeProviderSession =
775 activeProviderThread?.providerSessionId === null ||
776 activeProviderThread?.providerSessionId === undefined
777 ? undefined
778 : projection?.providerSessions.find(
779 (session) => session.id === activeProviderThread.providerSessionId,
780 );
781 const turnCapabilities = activeProviderSession?.capabilities.turns;
782 const dispatchMode = serverResolvesCommandContext
783 ? requestedMode === "queue"
784 ? ({ type: "queue_after_active" } as const)
785 : ({ type: "start_immediately" } as const)
786 : activeRun === undefined
787 ? ({ type: "start_immediately" } as const)
788 : requestedMode === "steer"
789 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
790 : requestedMode === "restart"
791 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
792 : requestedMode === "queue"
793 ? ({ type: "queue_after_active" } as const)
794 : turnCapabilities?.supportsActiveSteering === true
795 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
796 : turnCapabilities?.supportsQueuedMessages === true
797 ? ({ type: "queue_after_active" } as const)
798 : turnCapabilities?.supportsSteeringByInterruptRestart === true
799 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
800 : ({ type: "queue_after_active" } as const);
801 const shouldSendTitleSeed =
802 input.titleSeed !== undefined &&
803 (serverResolvesCommandContext || projection?.messages.length === 0);
804 return yield* dispatch({
805 type: "message.dispatch",
806 commandId,
807 createdBy: "user",
808 creationSource: input.creationSource ?? "web",
809 threadId: input.threadId,
810 messageId: input.message.messageId,
811 text: input.message.text,
812 ...(context ? { context } : {}),
813 ...(input.message.idleCompaction === undefined
814 ? {}
815 : { idleCompaction: input.message.idleCompaction }),
816 attachments,
817 ...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
818 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
819 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
820 ...(serverResolvesCommandContext && requestedMode !== "queue"
821 ? { deliveryIntent: requestedMode }
822 : {}),
823 dispatchMode,
824 });
825});
826​
827export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
828 input: InterruptThreadTurnInput,
829) {
830 let threadId = input.threadId;
831 if (input.subagentId !== undefined) {
832 const projection = yield* getProjection(input.threadId);
833 const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);
834 if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {
835 // The parent ends the task even when its child lost track of it. Older
836 // servers reject this for app-owned tasks, so the child stop below still runs.
837 if (subagent.runId !== null) {
838 yield* dispatch({
839 type: "subagent.stop",
840 commandId: yield* allocateCommandId({}),
841 threadId: input.threadId,
842 runId: subagent.runId,
843 subagentId: subagent.id,
844 }).pipe(Effect.ignore);
845 }
846 threadId = subagent.childThreadId;
847 } else {
848 if (subagent?.runId == null) return { sequence: 0 };
849 return yield* dispatch({
850 type: "subagent.stop",
851 commandId: yield* allocateCommandId(input),
852 threadId: input.threadId,
853 runId: subagent.runId,
854 subagentId: subagent.id,
855 });
856 }
857 }
858 // A run named by the caller belongs to the parent, not the rerouted child.
859 let runId =
860 threadId === input.threadId ? (input.runId ?? (input.turnId as RunId | undefined)) : undefined;
861 if (runId === undefined) {
862 const config = yield* getInitialServerConfig();
863 if (config.environment.capabilities.threadStop === true) {
864 // A paginated projection can omit commands still running from earlier turns.
865 return yield* dispatch({
866 type: "thread.stop",
867 commandId: yield* allocateCommandId(input),
868 threadId,
869 });
870 }
871 }
872 if (runId === undefined) {
873 const projection = yield* getProjection(threadId);
874 runId = projection.runs.findLast(
875 (run) =>
876 run.status === "preparing" ||
877 run.status === "starting" ||
878 run.status === "running" ||
879 run.status === "waiting",
880 )?.id;
881 if (runId === undefined) {
882 const latestRun = projection.runs.at(-1);
883 if (
884 derivePendingBackgroundWork({
885 latestRun,
886 providerThreads: projection.providerThreads,
887 turnItems: projection.turnItems,
888 activeProviderThreadId: projection.thread.activeProviderThreadId,
889 runs: projection.runs,
890 }).length > 0
891 ) {
892 runId = latestRun?.id;
893 }
894 }
895 if (runId === undefined) {
896 let result = { sequence: 0 };
897 for (const link of visibleThreadPullRequests(projection.thread.pullRequests ?? [])) {
898 if (link.watch === undefined) continue;
899 result = yield* dispatch({
900 type: "thread.pull-request.watch",
901 commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),
902 threadId,
903 host: link.host,
904 repository: link.repository,
905 number: link.number,
906 watching: false,
907 });
908 }
909 return result;
910 }
911 }
912 if (runId === undefined) return { sequence: 0 };
913 return yield* dispatch({
914 type: "run.interrupt",
915 commandId: yield* allocateCommandId(input),
916 threadId,
917 runId,
918 holdQueue: true,
919 });
920});
921​
922export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
923 function* (input: RespondToThreadApprovalInput) {
924 return yield* dispatch({
925 type: "runtime-request.respond",
926 commandId: yield* allocateCommandId(input),
927 threadId: input.threadId,
928 requestId: input.requestId,
929 decision: input.decision,
930 ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
931 });
932 },
933);
934​
935export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
936 function* (input: RespondToThreadUserInputInput) {
937 return yield* dispatch({
938 type: "runtime-request.respond",
939 commandId: yield* allocateCommandId(input),
940 threadId: input.threadId,
941 requestId: input.requestId,
942 answers: input.answers,
943 ...(input.attachmentsByQuestionId === undefined
944 ? {}
945 : { attachmentsByQuestionId: input.attachmentsByQuestionId }),
946 });
947 },
948);
949​
950export const dismissThreadUserInput = Effect.fn("EnvironmentCommands.dismissThreadUserInput")(
951 function* (input: DismissThreadUserInputInput) {
952 return yield* dispatch({
953 type: "thread.user-input.dismiss",
954 commandId: yield* allocateCommandId(input),
955 threadId: input.threadId,
956 requestId: input.requestId,
957 });
958 },
959);
960​
961export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
962 function* (input: RevertThreadCheckpointInput) {
963 if (
964 input.checkpointId !== undefined &&
965 input.scopeId !== undefined &&
966 (yield* supportsServerResolvedCommandContext())
967 ) {
968 return yield* dispatch({
969 type: "checkpoint.rollback",
970 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
971 commandId: yield* allocateCommandId(input),
972 threadId: input.threadId,
973 scopeId: CheckpointScopeId.make(input.scopeId),
974 checkpointId: CheckpointId.make(input.checkpointId),
975 });
976 }
977 const projection = yield* getProjection(input.threadId);
978 const checkpoint =
979 projection.checkpoints.find(
980 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
981 ) ??
982 projection.checkpoints.findLast((candidate) =>
983 input.turnCount === 0
984 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
985 : candidate.appRunOrdinal === input.turnCount,
986 );
987 if (checkpoint === undefined || checkpoint.status !== "ready") {
988 const target =
989 input.checkpointId === undefined
990 ? `run ordinal ${input.turnCount ?? "unknown"}`
991 : `checkpoint ${input.checkpointId}`;
992 return yield* new OrchestrationV2CheckpointUnavailableError({
993 threadId: input.threadId,
994 target,
995 });
996 }
997 return yield* dispatch({
998 type: "checkpoint.rollback",
999 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
1000 commandId: yield* allocateCommandId(input),
1001 threadId: input.threadId,
1002 scopeId: checkpoint.scopeId,
1003 checkpointId: checkpoint.id,
1004 });
1005 },
1007​
1008export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
1009 input: StopThreadSessionInput,
1010) {
1011 const projection = yield* getProjection(input.threadId);
1012 const commandId = yield* allocateCommandId(input);
1013 let result = { sequence: 0 };
1014 for (const session of projection.providerSessions) {
1015 result = yield* dispatch({
1016 type: "provider-session.detach",
1017 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
1018 threadId: input.threadId,
1019 providerSessionId: session.id,
1020 reason: "client-requested",
1021 });
1023 return result;
1024});
1025​
1026export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
1027 input: ForkThreadFromRunInput,
1028) {
1029 return yield* dispatch({
1030 type: "thread.fork",
1031 commandId: yield* allocateCommandId(input),
1032 createdBy: "user",
1033 creationSource: input.creationSource ?? "web",
1034 sourceThreadId: input.sourceThreadId,
1035 targetThreadId: input.targetThreadId,
1036 sourcePoint: { type: "run", runId: input.runId },
1037 ...(input.title === undefined ? {} : { title: input.title }),
1038 });
1039});
1040​
1041export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
1042 input: MergeThreadBackInput,
1043) {
1044 return yield* dispatch({
1045 type: "thread.merge_back",
1046 commandId: yield* allocateCommandId(input),
1047 createdBy: "user",
1048 creationSource: input.creationSource ?? "web",
1049 sourceThreadId: input.sourceThreadId,
1050 targetThreadId: input.targetThreadId,
1051 sourcePoint: { type: "run", runId: input.runId },
1052 });
1053});
1054​
1055export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
1056 input: ResumeThreadQueueInput,
1057) {
1058 return yield* dispatch({
1059 ...(input.runId === undefined
1060 ? { type: "queue.resume" as const }
1061 : { type: "queued-run.start" as const, runId: input.runId }),
1062 commandId: yield* allocateCommandId(input),
1063 threadId: input.threadId,
1064 });
1065});
1066​
1067export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
1068 input: ReorderQueuedRunInput,
1069) {
1070 return yield* dispatch({
1071 type: "queued-run.reorder",
1072 commandId: yield* allocateCommandId(input),
1073 threadId: input.threadId,
1074 runId: input.runId,
1075 beforeRunId: input.beforeRunId,
1076 });
1077});
1078​
1079export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
1080 input: PromoteQueuedRunInput,
1081) {
1082 return yield* dispatch({
1083 type: "queued-message.promote-to-steer",
1084 commandId: yield* allocateCommandId(input),
1085 threadId: input.threadId,
1086 queuedRunId: input.queuedRunId,
1087 targetRunId: input.targetRunId,
1088 });
1089});
1090​
1091export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
1092 input: CancelQueuedRunInput,
1093) {
1094 return yield* dispatch({
1095 type: "queued-run.cancel",
1096 commandId: yield* allocateCommandId(input),
1097 threadId: input.threadId,
1098 runId: input.runId,
1099 });
1100});
1101​
1102export const retryWorkspacePreparation = Effect.fn("EnvironmentCommands.retryWorkspacePreparation")(
1103 function* (input: RetryWorkspacePreparationInput) {
1104 return yield* dispatch({
1105 type: "prepared-run.retry",
1106 commandId: yield* allocateCommandId(input),
1107 threadId: input.threadId,
1108 runId: input.runId,
1109 });
1110 },
1112​
1113export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
1114 input: EditQueuedRunInput,
1115) {
1116 const attachments =
1117 input.edit === undefined
1118 ? undefined
1119 : yield* persistAttachments(input.threadId, input.edit.messageId, input.edit.attachments);
1120 return yield* dispatch({
1121 type: "queued-run.edit",
1122 commandId: yield* allocateCommandId(input),
1123 threadId: input.threadId,
1124 runId: input.runId,
1125 text: input.text,
1126 ...(attachments === undefined ? {} : { attachments }),
1127 ...(input.edit?.context && attachments
1128 ? {
1129 context: remapComposerContextAttachments(
1130 input.edit.context,
1131 input.edit.attachments,
1132 attachments,
1133 ),
1135 : {}),
1136 });
1137});
1138​
1139export type LinkThreadPullRequestInput = Omit<
1140 Extract<OrchestrationV2Command, { type: "thread.pull-request.link" }>,
1141 "type" | "commandId"
1142> &
1143 CommandMetadata;
1144export type UnlinkThreadPullRequestInput = Omit<
1145 Extract<OrchestrationV2Command, { type: "thread.pull-request.unlink" }>,
1146 "type" | "commandId"
1147> &
1148 CommandMetadata;
1149export const linkThreadPullRequest = Effect.fn("EnvironmentCommands.linkThreadPullRequest")(
1150 function* (input: LinkThreadPullRequestInput) {
1151 return yield* dispatch({
1152 ...input,
1153 type: "thread.pull-request.link",
1154 commandId: yield* allocateCommandId(input),
1155 });
1156 },
1158export type WatchThreadPullRequestInput = Omit<
1159 Extract<OrchestrationV2Command, { type: "thread.pull-request.watch" }>,
1160 "type" | "commandId"
1161> &
1162 CommandMetadata;
1163export const watchThreadPullRequest = Effect.fn("EnvironmentCommands.watchThreadPullRequest")(
1164 function* (input: WatchThreadPullRequestInput) {
1165 return yield* dispatch({
1166 ...input,
1167 type: "thread.pull-request.watch",
1168 commandId: yield* allocateCommandId(input),
1169 });
1170 },
1172export const unlinkThreadPullRequest = Effect.fn("EnvironmentCommands.unlinkThreadPullRequest")(
1173 function* (input: UnlinkThreadPullRequestInput) {
1174 return yield* dispatch({
1175 ...input,
1176 type: "thread.pull-request.unlink",
1177 commandId: yield* allocateCommandId(input),
1178 });
1179 },