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

commands.ts

1,103 lines37.0 KB

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