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

commands.ts

1,119 lines37.2 KB

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