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

commands.ts

1,139 lines38.1 KB

1import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2import {
3 type ThreadLinkedPullRequest,
4 CommandId,
5 CheckpointId,
6 CheckpointScopeId,
7 ORCHESTRATION_V2_WS_METHODS,
8 OrchestrationV2CheckpointUnavailableError,
9 WS_METHODS,
10 type ChatAttachment,
11 type MessageId,
12 type ModelSelection,
13 type NodeId,
14 type OrchestrationV2Command,
15 type OrchestrationV2CreationSource,
16 type PlanId,
17 type ProjectId,
18 type ProjectIconOverride,
19 type ProjectScript,
20 type ProviderApprovalDecision,
21 type ProviderInteractionMode,
22 type ProviderUserInputAnswers,
23 type RunId,
24 type RuntimeMode,
25 type RuntimeRequestId,
26 type ThreadId,
27 type ThreadEnvMode,
28 type UploadChatAttachment,
29} from "@t3tools/contracts";
30import { modelSelectionCommandType } from "@t3tools/shared/model";
31import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
32import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
33import * as Crypto from "effect/Crypto";
34import * as Effect from "effect/Effect";
35​
36import { getInitialServerConfig, request } from "../rpc/client.ts";
37​
38interface CommandMetadata {
39 readonly commandId?: CommandId;
40 readonly createdAt?: string;
41 readonly creationSource?: OrchestrationV2CreationSource;
43​
44export interface CreateProjectInput extends CommandMetadata {
45 readonly projectId: ProjectId;
46 readonly title: string;
47 readonly workspaceRoot: string;
48 readonly createWorkspaceRootIfMissing?: boolean;
49 readonly defaultModelSelection?: ModelSelection | null;
50 readonly scripts?: ReadonlyArray<ProjectScript>;
52​
53export interface UpdateProjectInput extends CommandMetadata {
54 readonly projectId: ProjectId;
55 readonly title?: string;
56 readonly workspaceRoot?: string;
57 readonly defaultModelSelection?: ModelSelection | null;
58 readonly autoPull?: boolean;
59 readonly projectIcon?: ProjectIconOverride | null;
60 readonly faviconPath?: string | null;
61 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
62 readonly scripts?: ReadonlyArray<ProjectScript>;
64​
65export interface DeleteProjectInput extends CommandMetadata {
66 readonly projectId: ProjectId;
67 readonly force?: boolean;
69​
70export interface CreateThreadInput extends CommandMetadata {
71 readonly threadId: ThreadId;
72 readonly projectId: ProjectId;
73 readonly title: string;
74 readonly modelSelection: ModelSelection;
75 readonly runtimeMode: RuntimeMode;
76 readonly interactionMode: ProviderInteractionMode;
77 readonly branch: string | null;
78 readonly worktreePath: string | null;
80​
81export interface ThreadCommandInput extends CommandMetadata {
82 readonly threadId: ThreadId;
84​
85export type DeleteThreadInput = ThreadCommandInput;
86export type ArchiveThreadInput = ThreadCommandInput;
87export type UnarchiveThreadInput = ThreadCommandInput;
88export type SettleThreadInput = ThreadCommandInput;
89​
90export interface UnsettleThreadInput extends ThreadCommandInput {
91 readonly reason: "user";
93​
94export interface PinThreadInput extends ThreadCommandInput {
95 readonly orderKey?: string;
97export type UnpinThreadInput = ThreadCommandInput;
98​
99export interface ReorderPinnedThreadInput extends ThreadCommandInput {
100 readonly orderKey: string;
102​
103export interface ReorderActiveThreadInput extends ThreadCommandInput {
104 readonly orderKey: string;
106​
107export interface SnoozeThreadInput extends ThreadCommandInput {
108 readonly snoozedUntil: string;
110​
111export interface UnsnoozeThreadInput extends ThreadCommandInput {
112 readonly reason: "user";
114​
115export interface VisitThreadInput extends ThreadCommandInput {
116 readonly visitedAt: string;
117 /** Counts toward search frecency; `searchQuery` is the palette query that picked it. */
118 readonly opened?: boolean;
119 readonly searchQuery?: string;
121​
122export type MarkThreadUnreadInput = ThreadCommandInput;
123​
124export interface UpdateThreadMetadataInput extends ThreadCommandInput {
125 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecoveryUpdate | null;
126 readonly title?: string;
127 readonly modelSelection?: ModelSelection;
128 readonly branch?: string | null;
129 readonly worktreePath?: string | null;
130 readonly regenerateTitle?: boolean;
131 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
132 readonly expectedEmpty?: boolean;
134​
135export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
136 readonly runtimeMode: RuntimeMode;
138​
139export interface SetThreadInteractionModeInput extends ThreadCommandInput {
140 readonly interactionMode: ProviderInteractionMode;
142​
143interface StartThreadBootstrap {
144 readonly createThread?: {
145 readonly projectId: ProjectId;
146 readonly title: string;
147 readonly modelSelection: ModelSelection;
148 readonly runtimeMode: RuntimeMode;
149 readonly interactionMode: ProviderInteractionMode;
150 readonly branch: string | null;
151 readonly worktreePath: string | null;
152 readonly createdAt: string;
153 };
154 readonly prepareWorktree?: {
155 readonly requireWorktree?: boolean;
156 readonly projectCwd: string;
157 readonly baseBranch: string;
158 readonly branch?: string;
159 readonly startFromOrigin?: boolean;
160 };
161 readonly runSetupScript?: boolean;
163​
164export interface StartThreadTurnInput extends ThreadCommandInput {
165 readonly manualContinuationOfRunId?: RunId;
166 readonly message: {
167 readonly messageId: MessageId;
168 readonly role: "user";
169 readonly text: string;
170 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
171 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
172 readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
173 };
174 readonly modelSelection?: ModelSelection;
175 readonly titleSeed?: string;
176 readonly runtimeMode: RuntimeMode;
177 readonly interactionMode: ProviderInteractionMode;
178 readonly bootstrap?: StartThreadBootstrap;
179 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
180 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
182​
183export interface InterruptThreadTurnInput extends ThreadCommandInput {
184 readonly runId?: RunId;
185 readonly subagentId?: NodeId;
186 readonly turnId?: string;
188​
189export interface RespondToThreadApprovalInput extends ThreadCommandInput {
190 readonly requestId: RuntimeRequestId;
191 readonly decision: ProviderApprovalDecision;
192 readonly feedback?: string;
194​
195export interface RespondToThreadUserInputInput extends ThreadCommandInput {
196 readonly requestId: RuntimeRequestId;
197 readonly answers: ProviderUserInputAnswers;
198 readonly attachmentsByQuestionId?: import("@t3tools/contracts").UserInputAttachments;
200​
201export interface DismissThreadUserInputInput extends ThreadCommandInput {
202 readonly requestId: RuntimeRequestId;
204​
205export interface RevertThreadCheckpointInput extends ThreadCommandInput {
206 readonly restoreFiles?: boolean;
207 readonly checkpointId?: string;
208 readonly scopeId?: string;
209 readonly turnCount?: number;
211​
212export type StopThreadSessionInput = ThreadCommandInput;
213​
214export interface ForkThreadFromRunInput extends CommandMetadata {
215 readonly sourceThreadId: ThreadId;
216 readonly targetThreadId: ThreadId;
217 readonly runId: RunId;
218 readonly title?: string;
220​
221export interface MergeThreadBackInput extends CommandMetadata {
222 readonly sourceThreadId: ThreadId;
223 readonly targetThreadId: ThreadId;
224 readonly runId: RunId;
226​
227export interface ResumeThreadQueueInput extends ThreadCommandInput {
228 readonly runId?: RunId;
230​
231export interface ReorderQueuedRunInput extends ThreadCommandInput {
232 readonly runId: RunId;
233 readonly beforeRunId: RunId | null;
235​
236export interface PromoteQueuedRunInput extends ThreadCommandInput {
237 readonly queuedRunId: RunId;
238 readonly targetRunId: RunId;
240​
241export interface CancelQueuedRunInput extends ThreadCommandInput {
242 readonly runId: RunId;
244​
245export interface RetryWorkspacePreparationInput extends ThreadCommandInput {
246 readonly runId: RunId;
248​
249export interface EditQueuedRunInput extends ThreadCommandInput {
250 readonly runId: RunId;
251 readonly text: string;
252 /**
253 * Full replacement attachment list for the queued message. Omitted =
254 * text-only edit that leaves attachments untouched.
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 ...(input.opened ? { opened: true } : {}),
550 ...(input.searchQuery ? { searchQuery: input.searchQuery } : {}),
551 });
552});
553​
554export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
555 input: MarkThreadUnreadInput,
556) {
557 return yield* dispatch({
558 type: "thread.mark-unread",
559 commandId: yield* allocateCommandId(input),
560 threadId: input.threadId,
561 });
562});
563​
564export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
565 function* (input: UpdateThreadMetadataInput) {
566 const commandId = yield* allocateCommandId(input);
567 let result = null;
568 if (
569 input.title !== undefined ||
570 input.branch !== undefined ||
571 input.worktreePath !== undefined ||
572 input.regenerateTitle !== undefined ||
573 input.linkedPullRequest !== undefined ||
574 input.limitRecovery !== undefined
575 ) {
576 result = yield* dispatch({
577 type: "thread.metadata.update",
578 ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }),
579 commandId,
580 threadId: input.threadId,
581 ...(input.title === undefined ? {} : { title: input.title }),
582 ...(input.branch === undefined ? {} : { branch: input.branch }),
583 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
584 ...(input.expectedEmpty === true ? { expectedEmpty: true } : {}),
585 ...(input.regenerateTitle === undefined ? {} : { regenerateTitle: input.regenerateTitle }),
586 ...(input.linkedPullRequest === undefined
587 ? {}
588 : { linkedPullRequest: input.linkedPullRequest }),
589 });
590 }
591 if (input.modelSelection !== undefined) {
592 const type = (yield* supportsServerResolvedCommandContext())
593 ? ("thread.model-selection.set" as const)
594 : modelSelectionCommandType(
595 (yield* getProjection(input.threadId)).thread.providerInstanceId,
596 input.modelSelection,
597 );
598 result = yield* dispatch({
599 type,
600 commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
601 threadId: input.threadId,
602 modelSelection: input.modelSelection,
603 });
604 }
605 return result ?? { sequence: 0 };
606 },
607);
608​
609export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
610 function* (input: SetThreadRuntimeModeInput) {
611 return yield* dispatch({
612 type: "thread.runtime-mode.set",
613 commandId: yield* allocateCommandId(input),
614 threadId: input.threadId,
615 runtimeMode: input.runtimeMode,
616 });
617 },
618);
619​
620export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
621 function* (input: SetThreadInteractionModeInput) {
622 return yield* dispatch({
623 type: "thread.interaction-mode.set",
624 commandId: yield* allocateCommandId(input),
625 threadId: input.threadId,
626 interactionMode: input.interactionMode,
627 });
628 },
629);
630​
631export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
632 input: StartThreadTurnInput,
633) {
634 const commandId = yield* allocateCommandId(input);
635 const attachments = yield* persistAttachments(
636 input.threadId,
637 input.message.messageId,
638 input.message.attachments,
639 );
640 const context = remapComposerContextAttachments(
641 input.message.context,
642 input.message.attachments,
643 attachments,
644 );
645 const bootstrap = input.bootstrap?.createThread;
646 const prepareWorktree = input.bootstrap?.prepareWorktree;
647 if (bootstrap !== undefined || prepareWorktree !== undefined) {
648 const existingProjection =
649 bootstrap === undefined ? yield* getProjection(input.threadId) : null;
650 const thread = bootstrap ?? existingProjection!.thread;
651 const workspaceStrategy =
652 prepareWorktree !== undefined
653 ? {
654 type: "worktree" as const,
655 baseRef: prepareWorktree.baseBranch,
656 ...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
657 ...(prepareWorktree.startFromOrigin === undefined
658 ? {}
659 : { startFromOrigin: prepareWorktree.startFromOrigin }),
660 }
661 : bootstrap?.worktreePath
662 ? {
663 type: "existing_worktree" as const,
664 worktreePath: bootstrap.worktreePath,
665 ...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
666 }
667 : {
668 type: "root" as const,
669 ...(bootstrap?.branch === null || bootstrap?.branch === undefined
670 ? {}
671 : { branch: bootstrap.branch }),
672 };
673 return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
674 commandId,
675 creationSource: input.creationSource ?? "web",
676 threadId: input.threadId,
677 ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
678 projectId: thread.projectId,
679 title: input.titleSeed ?? thread.title,
680 generateTitle: input.titleSeed !== undefined,
681 modelSelection: input.modelSelection ?? thread.modelSelection,
682 runtimeMode: input.runtimeMode,
683 interactionMode: input.interactionMode,
684 workspaceStrategy,
685 initialMessage: {
686 messageId: input.message.messageId,
687 text: input.message.text,
688 ...(context ? { context } : {}),
689 attachments,
690 },
691 });
692 }
693​
694 const requestedMode = input.dispatchMode ?? "auto";
695 if (requestedMode === "start") {
696 return yield* dispatch({
697 type: "message.dispatch",
698 commandId,
699 createdBy: "user",
700 creationSource: input.creationSource ?? "web",
701 threadId: input.threadId,
702 messageId: input.message.messageId,
703 ...(input.manualContinuationOfRunId === undefined
704 ? {}
705 : { manualContinuationOfRunId: input.manualContinuationOfRunId }),
706 text: input.message.text,
707 ...(context ? { context } : {}),
708 ...(input.message.idleCompaction === undefined
709 ? {}
710 : { idleCompaction: input.message.idleCompaction }),
711 attachments,
712 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
713 ...(input.sourceProposedPlan === undefined
714 ? {}
715 : { sourcePlanRef: input.sourceProposedPlan }),
716 dispatchMode: { type: "start_immediately" },
717 });
718 }
719​
720 const serverResolvesCommandContext = yield* supportsServerResolvedCommandContext();
721 const projection = serverResolvesCommandContext ? null : yield* getProjection(input.threadId);
722 const activeRun = projection?.runs.findLast(
723 (run) =>
724 run.status === "preparing" ||
725 run.status === "starting" ||
726 run.status === "running" ||
727 run.status === "waiting",
728 );
729 const activeProviderThread =
730 activeRun === undefined
731 ? undefined
732 : projection?.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
733 const activeProviderSession =
734 activeProviderThread?.providerSessionId === null ||
735 activeProviderThread?.providerSessionId === undefined
736 ? undefined
737 : projection?.providerSessions.find(
738 (session) => session.id === activeProviderThread.providerSessionId,
739 );
740 const turnCapabilities = activeProviderSession?.capabilities.turns;
741 const dispatchMode = serverResolvesCommandContext
742 ? requestedMode === "queue"
743 ? ({ type: "queue_after_active" } as const)
744 : ({ type: "start_immediately" } as const)
745 : activeRun === undefined
746 ? ({ type: "start_immediately" } as const)
747 : requestedMode === "steer"
748 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
749 : requestedMode === "restart"
750 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
751 : requestedMode === "queue"
752 ? ({ type: "queue_after_active" } as const)
753 : turnCapabilities?.supportsActiveSteering === true
754 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
755 : turnCapabilities?.supportsQueuedMessages === true
756 ? ({ type: "queue_after_active" } as const)
757 : turnCapabilities?.supportsSteeringByInterruptRestart === true
758 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
759 : ({ type: "queue_after_active" } as const);
760 const shouldSendTitleSeed =
761 input.titleSeed !== undefined &&
762 (serverResolvesCommandContext || projection?.messages.length === 0);
763 return yield* dispatch({
764 type: "message.dispatch",
765 commandId,
766 createdBy: "user",
767 creationSource: input.creationSource ?? "web",
768 threadId: input.threadId,
769 messageId: input.message.messageId,
770 text: input.message.text,
771 ...(context ? { context } : {}),
772 ...(input.message.idleCompaction === undefined
773 ? {}
774 : { idleCompaction: input.message.idleCompaction }),
775 attachments,
776 ...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
777 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
778 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
779 ...(serverResolvesCommandContext && requestedMode !== "queue"
780 ? { deliveryIntent: requestedMode }
781 : {}),
782 dispatchMode,
783 });
784});
785​
786export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
787 input: InterruptThreadTurnInput,
788) {
789 let threadId = input.threadId;
790 if (input.subagentId !== undefined) {
791 const projection = yield* getProjection(input.threadId);
792 const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);
793 if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {
794 // The parent ends the task even when its child lost track of it (#19002). Older
795 // servers reject this for app-owned tasks, so the child stop below still runs.
796 if (subagent.runId !== null) {
797 yield* dispatch({
798 type: "subagent.stop",
799 commandId: yield* allocateCommandId({}),
800 threadId: input.threadId,
801 runId: subagent.runId,
802 subagentId: subagent.id,
803 }).pipe(Effect.ignore);
804 }
805 threadId = subagent.childThreadId;
806 } else {
807 if (subagent?.runId == null) return { sequence: 0 };
808 return yield* dispatch({
809 type: "subagent.stop",
810 commandId: yield* allocateCommandId(input),
811 threadId: input.threadId,
812 runId: subagent.runId,
813 subagentId: subagent.id,
814 });
815 }
816 }
817 // A run named by the caller belongs to the parent, not the rerouted child.
818 let runId =
819 threadId === input.threadId ? (input.runId ?? (input.turnId as RunId | undefined)) : undefined;
820 if (runId === undefined) {
821 const config = yield* getInitialServerConfig();
822 if (config.environment.capabilities.threadStop === true) {
823 // A paginated projection can omit commands still running from earlier turns.
824 return yield* dispatch({
825 type: "thread.stop",
826 commandId: yield* allocateCommandId(input),
827 threadId,
828 });
829 }
830 }
831 if (runId === undefined) {
832 const projection = yield* getProjection(threadId);
833 runId = projection.runs.findLast(
834 (run) =>
835 run.status === "preparing" ||
836 run.status === "starting" ||
837 run.status === "running" ||
838 run.status === "waiting",
839 )?.id;
840 if (runId === undefined) {
841 const latestRun = projection.runs.at(-1);
842 if (
843 derivePendingBackgroundWork({
844 latestRun,
845 providerThreads: projection.providerThreads,
846 turnItems: projection.turnItems,
847 activeProviderThreadId: projection.thread.activeProviderThreadId,
848 runs: projection.runs,
849 }).length > 0
850 ) {
851 runId = latestRun?.id;
852 }
853 }
854 if (runId === undefined) {
855 let result = { sequence: 0 };
856 for (const link of visibleThreadPullRequests(projection.thread.pullRequests ?? [])) {
857 if (link.watch === undefined) continue;
858 result = yield* dispatch({
859 type: "thread.pull-request.watch",
860 commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),
861 threadId,
862 host: link.host,
863 repository: link.repository,
864 number: link.number,
865 watching: false,
866 });
867 }
868 return result;
869 }
870 }
871 if (runId === undefined) return { sequence: 0 };
872 return yield* dispatch({
873 type: "run.interrupt",
874 commandId: yield* allocateCommandId(input),
875 threadId,
876 runId,
877 holdQueue: true,
878 });
879});
880​
881export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
882 function* (input: RespondToThreadApprovalInput) {
883 return yield* dispatch({
884 type: "runtime-request.respond",
885 commandId: yield* allocateCommandId(input),
886 threadId: input.threadId,
887 requestId: input.requestId,
888 decision: input.decision,
889 ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
890 });
891 },
892);
893​
894export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
895 function* (input: RespondToThreadUserInputInput) {
896 return yield* dispatch({
897 type: "runtime-request.respond",
898 commandId: yield* allocateCommandId(input),
899 threadId: input.threadId,
900 requestId: input.requestId,
901 answers: input.answers,
902 ...(input.attachmentsByQuestionId === undefined
903 ? {}
904 : { attachmentsByQuestionId: input.attachmentsByQuestionId }),
905 });
906 },
907);
908​
909export const dismissThreadUserInput = Effect.fn("EnvironmentCommands.dismissThreadUserInput")(
910 function* (input: DismissThreadUserInputInput) {
911 return yield* dispatch({
912 type: "thread.user-input.dismiss",
913 commandId: yield* allocateCommandId(input),
914 threadId: input.threadId,
915 requestId: input.requestId,
916 });
917 },
918);
919​
920export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
921 function* (input: RevertThreadCheckpointInput) {
922 if (
923 input.checkpointId !== undefined &&
924 input.scopeId !== undefined &&
925 (yield* supportsServerResolvedCommandContext())
926 ) {
927 return yield* dispatch({
928 type: "checkpoint.rollback",
929 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
930 commandId: yield* allocateCommandId(input),
931 threadId: input.threadId,
932 scopeId: CheckpointScopeId.make(input.scopeId),
933 checkpointId: CheckpointId.make(input.checkpointId),
934 });
935 }
936 const projection = yield* getProjection(input.threadId);
937 const checkpoint =
938 projection.checkpoints.find(
939 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
940 ) ??
941 projection.checkpoints.findLast((candidate) =>
942 input.turnCount === 0
943 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
944 : candidate.appRunOrdinal === input.turnCount,
945 );
946 if (checkpoint === undefined || checkpoint.status !== "ready") {
947 const target =
948 input.checkpointId === undefined
949 ? `run ordinal ${input.turnCount ?? "unknown"}`
950 : `checkpoint ${input.checkpointId}`;
951 return yield* new OrchestrationV2CheckpointUnavailableError({
952 threadId: input.threadId,
953 target,
954 });
955 }
956 return yield* dispatch({
957 type: "checkpoint.rollback",
958 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
959 commandId: yield* allocateCommandId(input),
960 threadId: input.threadId,
961 scopeId: checkpoint.scopeId,
962 checkpointId: checkpoint.id,
963 });
964 },
965);
966​
967export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
968 input: StopThreadSessionInput,
969) {
970 const projection = yield* getProjection(input.threadId);
971 const commandId = yield* allocateCommandId(input);
972 let result = { sequence: 0 };
973 for (const session of projection.providerSessions) {
974 result = yield* dispatch({
975 type: "provider-session.detach",
976 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
977 threadId: input.threadId,
978 providerSessionId: session.id,
979 reason: "client-requested",
980 });
981 }
982 return result;
983});
984​
985export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
986 input: ForkThreadFromRunInput,
987) {
988 return yield* dispatch({
989 type: "thread.fork",
990 commandId: yield* allocateCommandId(input),
991 createdBy: "user",
992 creationSource: input.creationSource ?? "web",
993 sourceThreadId: input.sourceThreadId,
994 targetThreadId: input.targetThreadId,
995 sourcePoint: { type: "run", runId: input.runId },
996 ...(input.title === undefined ? {} : { title: input.title }),
997 });
998});
999​
1000export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
1001 input: MergeThreadBackInput,
1002) {
1003 return yield* dispatch({
1004 type: "thread.merge_back",
1005 commandId: yield* allocateCommandId(input),
1006 createdBy: "user",
1007 creationSource: input.creationSource ?? "web",
1008 sourceThreadId: input.sourceThreadId,
1009 targetThreadId: input.targetThreadId,
1010 sourcePoint: { type: "run", runId: input.runId },
1011 });
1012});
1013​
1014export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
1015 input: ResumeThreadQueueInput,
1016) {
1017 return yield* dispatch({
1018 ...(input.runId === undefined
1019 ? { type: "queue.resume" as const }
1020 : { type: "queued-run.start" as const, runId: input.runId }),
1021 commandId: yield* allocateCommandId(input),
1022 threadId: input.threadId,
1023 });
1024});
1025​
1026export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
1027 input: ReorderQueuedRunInput,
1028) {
1029 return yield* dispatch({
1030 type: "queued-run.reorder",
1031 commandId: yield* allocateCommandId(input),
1032 threadId: input.threadId,
1033 runId: input.runId,
1034 beforeRunId: input.beforeRunId,
1035 });
1036});
1037​
1038export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
1039 input: PromoteQueuedRunInput,
1040) {
1041 return yield* dispatch({
1042 type: "queued-message.promote-to-steer",
1043 commandId: yield* allocateCommandId(input),
1044 threadId: input.threadId,
1045 queuedRunId: input.queuedRunId,
1046 targetRunId: input.targetRunId,
1047 });
1048});
1049​
1050export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
1051 input: CancelQueuedRunInput,
1052) {
1053 return yield* dispatch({
1054 type: "queued-run.cancel",
1055 commandId: yield* allocateCommandId(input),
1056 threadId: input.threadId,
1057 runId: input.runId,
1058 });
1059});
1060​
1061export const retryWorkspacePreparation = Effect.fn("EnvironmentCommands.retryWorkspacePreparation")(
1062 function* (input: RetryWorkspacePreparationInput) {
1063 return yield* dispatch({
1064 type: "prepared-run.retry",
1065 commandId: yield* allocateCommandId(input),
1066 threadId: input.threadId,
1067 runId: input.runId,
1068 });
1069 },
1071​
1072export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
1073 input: EditQueuedRunInput,
1074) {
1075 const attachments =
1076 input.edit === undefined
1077 ? undefined
1078 : yield* persistAttachments(input.threadId, input.edit.messageId, input.edit.attachments);
1079 return yield* dispatch({
1080 type: "queued-run.edit",
1081 commandId: yield* allocateCommandId(input),
1082 threadId: input.threadId,
1083 runId: input.runId,
1084 text: input.text,
1085 ...(attachments === undefined ? {} : { attachments }),
1086 ...(input.edit?.context && attachments
1087 ? {
1088 context: remapComposerContextAttachments(
1089 input.edit.context,
1090 input.edit.attachments,
1091 attachments,
1092 ),
1094 : {}),
1095 });
1096});
1097​
1098export type LinkThreadPullRequestInput = Omit<
1099 Extract<OrchestrationV2Command, { type: "thread.pull-request.link" }>,
1100 "type" | "commandId"
1101> &
1102 CommandMetadata;
1103export type UnlinkThreadPullRequestInput = Omit<
1104 Extract<OrchestrationV2Command, { type: "thread.pull-request.unlink" }>,
1105 "type" | "commandId"
1106> &
1107 CommandMetadata;
1108export const linkThreadPullRequest = Effect.fn("EnvironmentCommands.linkThreadPullRequest")(
1109 function* (input: LinkThreadPullRequestInput) {
1110 return yield* dispatch({
1111 ...input,
1112 type: "thread.pull-request.link",
1113 commandId: yield* allocateCommandId(input),
1114 });
1115 },
1117export type WatchThreadPullRequestInput = Omit<
1118 Extract<OrchestrationV2Command, { type: "thread.pull-request.watch" }>,
1119 "type" | "commandId"
1120> &
1121 CommandMetadata;
1122export const watchThreadPullRequest = Effect.fn("EnvironmentCommands.watchThreadPullRequest")(
1123 function* (input: WatchThreadPullRequestInput) {
1124 return yield* dispatch({
1125 ...input,
1126 type: "thread.pull-request.watch",
1127 commandId: yield* allocateCommandId(input),
1128 });
1129 },
1131export const unlinkThreadPullRequest = Effect.fn("EnvironmentCommands.unlinkThreadPullRequest")(
1132 function* (input: UnlinkThreadPullRequestInput) {
1133 return yield* dispatch({
1134 ...input,
1135 type: "thread.pull-request.unlink",
1136 commandId: yield* allocateCommandId(input),
1137 });
1138 },