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

commands.ts

1,033 lines34.5 KB

1import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2import {
3 type ThreadLinkedPullRequest,
4 CommandId,
5 CheckpointId,
6 CheckpointScopeId,
7 ORCHESTRATION_V2_WS_METHODS,
8 OrchestrationV2CheckpointUnavailableError,
9 WS_METHODS,
10 type ChatAttachment,
11 type MessageId,
12 type ModelSelection,
13 type OrchestrationV2Command,
14 type OrchestrationV2CreationSource,
15 type PlanId,
16 type ProjectId,
17 type ProjectIconOverride,
18 type ProjectScript,
19 type ProviderApprovalDecision,
20 type ProviderInteractionMode,
21 type ProviderUserInputAnswers,
22 type RunId,
23 type RuntimeMode,
24 type RuntimeRequestId,
25 type ThreadId,
26 type ThreadEnvMode,
27 type UploadChatAttachment,
28} from "@t3tools/contracts";
29import { modelSelectionCommandType } from "@t3tools/shared/model";
30import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
31import * as Crypto from "effect/Crypto";
32import * as Effect from "effect/Effect";
33​
34import { getInitialServerConfig, request } from "../rpc/client.ts";
35​
36interface CommandMetadata {
37 readonly commandId?: CommandId;
38 readonly createdAt?: string;
39 readonly creationSource?: OrchestrationV2CreationSource;
41​
42export interface CreateProjectInput extends CommandMetadata {
43 readonly projectId: ProjectId;
44 readonly title: string;
45 readonly workspaceRoot: string;
46 readonly createWorkspaceRootIfMissing?: boolean;
47 readonly defaultModelSelection?: ModelSelection | null;
48 readonly scripts?: ReadonlyArray<ProjectScript>;
50​
51export interface UpdateProjectInput extends CommandMetadata {
52 readonly projectId: ProjectId;
53 readonly title?: string;
54 readonly workspaceRoot?: string;
55 readonly defaultModelSelection?: ModelSelection | null;
56 readonly autoPull?: boolean;
57 readonly projectIcon?: ProjectIconOverride | null;
58 readonly faviconPath?: string | null;
59 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
60 readonly scripts?: ReadonlyArray<ProjectScript>;
62​
63export interface DeleteProjectInput extends CommandMetadata {
64 readonly projectId: ProjectId;
65 readonly force?: boolean;
67​
68export interface CreateThreadInput extends CommandMetadata {
69 readonly threadId: ThreadId;
70 readonly projectId: ProjectId;
71 readonly title: string;
72 readonly modelSelection: ModelSelection;
73 readonly runtimeMode: RuntimeMode;
74 readonly interactionMode: ProviderInteractionMode;
75 readonly branch: string | null;
76 readonly worktreePath: string | null;
78​
79export interface ThreadCommandInput extends CommandMetadata {
80 readonly threadId: ThreadId;
82​
83export type DeleteThreadInput = ThreadCommandInput;
84export type ArchiveThreadInput = ThreadCommandInput;
85export type UnarchiveThreadInput = ThreadCommandInput;
86export type SettleThreadInput = ThreadCommandInput;
87​
88export interface UnsettleThreadInput extends ThreadCommandInput {
89 readonly reason: "user";
91​
92export interface PinThreadInput extends ThreadCommandInput {
93 /** Initial slot in the user-arranged pinned order; omit to pin keyless. */
94 readonly orderKey?: string;
96export type UnpinThreadInput = ThreadCommandInput;
97​
98export interface ReorderPinnedThreadInput extends ThreadCommandInput {
99 /** Fractional-index key that sorts between the drop position's neighbors. */
100 readonly orderKey: string;
102​
103export interface ReorderActiveThreadInput extends ThreadCommandInput {
104 /** Fractional-index key that sorts between the drop position's neighbors. */
105 readonly orderKey: string;
107​
108export interface SnoozeThreadInput extends ThreadCommandInput {
109 readonly snoozedUntil: string;
111​
112export interface UnsnoozeThreadInput extends ThreadCommandInput {
113 readonly reason: "user";
115​
116export interface VisitThreadInput extends ThreadCommandInput {
117 /** Watermark of the thread state the viewer has seen (ISO timestamp). */
118 readonly visitedAt: string;
120​
121export type MarkThreadUnreadInput = ThreadCommandInput;
122​
123export interface UpdateThreadMetadataInput extends ThreadCommandInput {
124 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecoveryUpdate | null;
125 readonly title?: string;
126 readonly modelSelection?: ModelSelection;
127 readonly branch?: string | null;
128 readonly worktreePath?: string | null;
129 /** Kick off an async title regeneration for the thread. */
130 readonly regenerateTitle?: boolean;
131 /** Link (object) or unlink (null) a pull request (#8160). */
132 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
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 /** V2 worktree launches always fail rather than falling back to the project checkout. */
156 readonly requireWorktree?: boolean;
157 readonly projectCwd: string;
158 readonly baseBranch: string;
159 readonly branch?: string;
160 readonly startFromOrigin?: boolean;
161 };
162 readonly runSetupScript?: boolean;
164​
165export interface StartThreadTurnInput extends ThreadCommandInput {
166 readonly 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 };
173 readonly modelSelection?: ModelSelection;
174 readonly titleSeed?: string;
175 readonly runtimeMode: RuntimeMode;
176 readonly interactionMode: ProviderInteractionMode;
177 readonly bootstrap?: StartThreadBootstrap;
178 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
179 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
181​
182export interface InterruptThreadTurnInput extends ThreadCommandInput {
183 readonly runId?: RunId;
184 /** Temporary caller compatibility while UI naming moves from turns to runs. */
185 readonly turnId?: string;
187​
188export interface RespondToThreadApprovalInput extends ThreadCommandInput {
189 readonly requestId: RuntimeRequestId;
190 readonly decision: ProviderApprovalDecision;
192​
193export interface RespondToThreadUserInputInput extends ThreadCommandInput {
194 readonly requestId: RuntimeRequestId;
195 readonly answers: ProviderUserInputAnswers;
196 readonly attachmentsByQuestionId?: import("@t3tools/contracts").UserInputAttachments;
198​
199export interface DismissThreadUserInputInput extends ThreadCommandInput {
200 readonly requestId: RuntimeRequestId;
202​
203export interface RevertThreadCheckpointInput extends ThreadCommandInput {
204 readonly restoreFiles?: boolean;
205 readonly checkpointId?: string;
206 readonly scopeId?: string;
207 readonly turnCount?: number;
209​
210export type StopThreadSessionInput = ThreadCommandInput;
211​
212export interface ForkThreadFromRunInput extends CommandMetadata {
213 readonly sourceThreadId: ThreadId;
214 readonly targetThreadId: ThreadId;
215 readonly runId: RunId;
216 readonly title?: string;
218​
219export interface MergeThreadBackInput extends CommandMetadata {
220 readonly sourceThreadId: ThreadId;
221 readonly targetThreadId: ThreadId;
222 readonly runId: RunId;
224​
225export interface ReorderQueuedRunInput extends ThreadCommandInput {
226 readonly runId: RunId;
227 readonly beforeRunId: RunId | null;
229​
230export interface PromoteQueuedRunInput extends ThreadCommandInput {
231 readonly queuedRunId: RunId;
232 readonly targetRunId: RunId;
234​
235export interface CancelQueuedRunInput extends ThreadCommandInput {
236 readonly runId: RunId;
238​
239export interface EditQueuedRunInput extends ThreadCommandInput {
240 readonly runId: RunId;
241 readonly text: string;
242 /**
243 * Full replacement attachment list for the queued message. Omitted =
244 * text-only edit that leaves attachments untouched. `dataUrl` entries are
245 * persisted against `messageId` (the queued run's user message) before
246 * dispatch, so `messageId` is required whenever attachments are present.
247 */
248 readonly edit?: {
249 readonly messageId: MessageId;
250 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
251 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
252 };
254​
255const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
256 input: CommandMetadata,
257) {
258 if (input.commandId !== undefined) return input.commandId;
259 const crypto = yield* Crypto.Crypto;
260 return CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie));
261});
262​
263const dispatch = (command: OrchestrationV2Command) =>
264 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
265​
266const getProjection = (threadId: ThreadId) =>
267 request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
268​
269const supportsServerResolvedCommandContext = Effect.fn(
270 "EnvironmentCommands.supportsServerResolvedCommandContext",
271)(function* () {
272 const config = yield* getInitialServerConfig();
273 return config.environment.capabilities.serverResolvedCommandContext === true;
274});
275​
276const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* (
277 threadId: ThreadId,
278 messageId: MessageId,
279 attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>,
280) {
281 const stored = attachments.filter(
282 (attachment): attachment is ChatAttachment => !("dataUrl" in attachment),
283 );
284 const uploads = attachments.filter(
285 (attachment): attachment is UploadChatAttachment => "dataUrl" in attachment,
286 );
287 if (uploads.length === 0) return stored;
288 const result = yield* request(WS_METHODS.assetsPersistChatAttachments, {
289 threadId,
290 messageId,
291 attachments: uploads,
292 });
293 if (stored.length === 0) return result.attachments;
294 const byUpload = new Map(
295 uploads.map((attachment, index) => [attachment, result.attachments[index]]),
296 );
297 return attachments.flatMap((attachment) => {
298 if (!("dataUrl" in attachment)) return [attachment];
299 const persisted = byUpload.get(attachment);
300 return persisted === undefined ? [] : [persisted];
301 });
302});
303​
304const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* (
305 mutation:
306 | {
307 readonly type: "project.create";
308 readonly commandId: CommandId;
309 readonly projectId: ProjectId;
310 readonly title: string;
311 readonly workspaceRoot: string;
312 readonly createWorkspaceRootIfMissing?: boolean;
313 readonly defaultModelSelection?: ModelSelection | null;
314 readonly scripts?: ReadonlyArray<ProjectScript>;
315 }
316 | {
317 readonly type: "project.update";
318 readonly commandId: CommandId;
319 readonly projectId: ProjectId;
320 readonly title?: string;
321 readonly workspaceRoot?: string;
322 readonly defaultModelSelection?: ModelSelection | null;
323 readonly scripts?: ReadonlyArray<ProjectScript>;
324 }
325 | {
326 readonly type: "project.delete";
327 readonly commandId: CommandId;
328 readonly projectId: ProjectId;
329 readonly force?: boolean;
330 },
331) {
332 return yield* request(WS_METHODS.projectsMutate, mutation);
333});
334​
335export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
336 input: CreateProjectInput,
337) {
338 return yield* mutateProject({
339 type: "project.create",
340 commandId: yield* allocateCommandId(input),
341 projectId: input.projectId,
342 title: input.title,
343 workspaceRoot: input.workspaceRoot,
344 ...(input.createWorkspaceRootIfMissing === undefined
345 ? {}
346 : { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
347 ...(input.defaultModelSelection === undefined
348 ? {}
349 : { defaultModelSelection: input.defaultModelSelection }),
350 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
351 });
352});
353​
354export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
355 input: UpdateProjectInput,
356) {
357 return yield* mutateProject({
358 type: "project.update",
359 commandId: yield* allocateCommandId(input),
360 projectId: input.projectId,
361 ...(input.title === undefined ? {} : { title: input.title }),
362 ...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
363 ...(input.defaultModelSelection === undefined
364 ? {}
365 : { defaultModelSelection: input.defaultModelSelection }),
366 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
367 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
368 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
369 ...(input.defaultThreadEnvMode === undefined
370 ? {}
371 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
372 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
373 });
374});
375​
376export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
377 input: DeleteProjectInput,
378) {
379 return yield* mutateProject({
380 type: "project.delete",
381 commandId: yield* allocateCommandId(input),
382 projectId: input.projectId,
383 ...(input.force === undefined ? {} : { force: input.force }),
384 });
385});
386​
387export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
388 input: CreateThreadInput,
389) {
390 return yield* dispatch({
391 type: "thread.create",
392 commandId: yield* allocateCommandId(input),
393 createdBy: "user",
394 creationSource: input.creationSource ?? "web",
395 threadId: input.threadId,
396 projectId: input.projectId,
397 title: input.title,
398 modelSelection: input.modelSelection,
399 runtimeMode: input.runtimeMode,
400 interactionMode: input.interactionMode,
401 branch: input.branch,
402 worktreePath: input.worktreePath,
403 });
404});
405​
406function simpleThreadCommand(
407 type:
408 | "thread.delete"
409 | "thread.archive"
410 | "thread.unarchive"
411 | "thread.settle"
412 | "thread.pin"
413 | "thread.unpin",
414 input: ThreadCommandInput,
415) {
416 return allocateCommandId(input).pipe(
417 Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
418 );
420​
421export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
422 input: DeleteThreadInput,
423) {
424 return yield* simpleThreadCommand("thread.delete", input);
425});
426​
427export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
428 input: ArchiveThreadInput,
429) {
430 return yield* simpleThreadCommand("thread.archive", input);
431});
432​
433export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
434 input: UnarchiveThreadInput,
435) {
436 return yield* simpleThreadCommand("thread.unarchive", input);
437});
438​
439export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
440 input: SettleThreadInput,
441) {
442 return yield* simpleThreadCommand("thread.settle", input);
443});
444​
445export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* (
446 input: PinThreadInput,
447) {
448 const commandId = yield* allocateCommandId(input);
449 return yield* dispatch({
450 type: "thread.pin",
451 commandId,
452 threadId: input.threadId,
453 ...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }),
454 });
455});
456​
457export interface SetThreadAutoSettleInput extends ThreadCommandInput {
458 readonly enabled: boolean;
460export const setThreadAutoSettle = Effect.fn("EnvironmentCommands.setThreadAutoSettle")(function* (
461 input: SetThreadAutoSettleInput,
462) {
463 return yield* dispatch({
464 type: "thread.auto-settle.set",
465 commandId: yield* allocateCommandId(input),
466 threadId: input.threadId,
467 enabled: input.enabled,
468 });
469});
470​
471export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* (
472 input: ReorderPinnedThreadInput,
473) {
474 const commandId = yield* allocateCommandId(input);
475 return yield* dispatch({
476 type: "thread.pin.reorder",
477 commandId,
478 threadId: input.threadId,
479 orderKey: input.orderKey,
480 });
481});
482​
483export const reorderActiveThread = Effect.fn("EnvironmentCommands.reorderActiveThread")(function* (
484 input: ReorderActiveThreadInput,
485) {
486 return yield* dispatch({
487 type: "thread.active.reorder",
488 commandId: yield* allocateCommandId(input),
489 threadId: input.threadId,
490 orderKey: input.orderKey,
491 });
492});
493​
494export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* (
495 input: UnpinThreadInput,
496) {
497 return yield* simpleThreadCommand("thread.unpin", input);
498});
499​
500export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
501 input: UnsettleThreadInput,
502) {
503 return yield* dispatch({
504 type: "thread.unsettle",
505 commandId: yield* allocateCommandId(input),
506 threadId: input.threadId,
507 reason: input.reason,
508 });
509});
510​
511export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
512 input: SnoozeThreadInput,
513) {
514 return yield* dispatch({
515 type: "thread.snooze",
516 commandId: yield* allocateCommandId(input),
517 threadId: input.threadId,
518 snoozedUntil: input.snoozedUntil,
519 });
520});
521​
522export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
523 input: UnsnoozeThreadInput,
524) {
525 return yield* dispatch({
526 type: "thread.unsnooze",
527 commandId: yield* allocateCommandId(input),
528 threadId: input.threadId,
529 reason: input.reason,
530 });
531});
532​
533export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
534 input: VisitThreadInput,
535) {
536 return yield* dispatch({
537 type: "thread.visit",
538 commandId: yield* allocateCommandId(input),
539 threadId: input.threadId,
540 visitedAt: input.visitedAt,
541 });
542});
543​
544export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
545 input: MarkThreadUnreadInput,
546) {
547 return yield* dispatch({
548 type: "thread.mark-unread",
549 commandId: yield* allocateCommandId(input),
550 threadId: input.threadId,
551 });
552});
553​
554export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
555 function* (input: UpdateThreadMetadataInput) {
556 const commandId = yield* allocateCommandId(input);
557 let result = null;
558 if (
559 input.title !== undefined ||
560 input.branch !== undefined ||
561 input.worktreePath !== undefined ||
562 input.regenerateTitle !== undefined ||
563 input.linkedPullRequest !== undefined ||
564 input.limitRecovery !== undefined
565 ) {
566 result = yield* dispatch({
567 type: "thread.metadata.update",
568 ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }),
569 commandId,
570 threadId: input.threadId,
571 ...(input.title === undefined ? {} : { title: input.title }),
572 ...(input.branch === undefined ? {} : { branch: input.branch }),
573 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
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 text: input.message.text,
693 ...(context ? { context } : {}),
694 attachments,
695 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
696 ...(input.sourceProposedPlan === undefined
697 ? {}
698 : { sourcePlanRef: input.sourceProposedPlan }),
699 dispatchMode: { type: "start_immediately" },
700 });
701 }
702​
703 const serverResolvesCommandContext = yield* supportsServerResolvedCommandContext();
704 const projection = serverResolvesCommandContext ? null : yield* getProjection(input.threadId);
705 const activeRun = projection?.runs.findLast(
706 (run) =>
707 run.status === "preparing" ||
708 run.status === "starting" ||
709 run.status === "running" ||
710 run.status === "waiting",
711 );
712 const activeProviderThread =
713 activeRun === undefined
714 ? undefined
715 : projection?.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
716 const activeProviderSession =
717 activeProviderThread?.providerSessionId === null ||
718 activeProviderThread?.providerSessionId === undefined
719 ? undefined
720 : projection?.providerSessions.find(
721 (session) => session.id === activeProviderThread.providerSessionId,
722 );
723 const turnCapabilities = activeProviderSession?.capabilities.turns;
724 const dispatchMode = serverResolvesCommandContext
725 ? requestedMode === "queue"
726 ? ({ type: "queue_after_active" } as const)
727 : ({ type: "start_immediately" } as const)
728 : activeRun === undefined
729 ? ({ type: "start_immediately" } as const)
730 : requestedMode === "steer"
731 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
732 : requestedMode === "restart"
733 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
734 : requestedMode === "queue"
735 ? ({ type: "queue_after_active" } as const)
736 : turnCapabilities?.supportsActiveSteering === true
737 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
738 : turnCapabilities?.supportsQueuedMessages === true
739 ? ({ type: "queue_after_active" } as const)
740 : turnCapabilities?.supportsSteeringByInterruptRestart === true
741 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
742 : ({ type: "queue_after_active" } as const);
743 const shouldSendTitleSeed =
744 input.titleSeed !== undefined &&
745 (serverResolvesCommandContext || projection?.messages.length === 0);
746 return yield* dispatch({
747 type: "message.dispatch",
748 commandId,
749 createdBy: "user",
750 creationSource: input.creationSource ?? "web",
751 threadId: input.threadId,
752 messageId: input.message.messageId,
753 text: input.message.text,
754 ...(context ? { context } : {}),
755 attachments,
756 ...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
757 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
758 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
759 ...(serverResolvesCommandContext && requestedMode !== "queue"
760 ? { deliveryIntent: requestedMode }
761 : {}),
762 dispatchMode,
763 });
764});
765​
766export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
767 input: InterruptThreadTurnInput,
768) {
769 let runId = input.runId ?? (input.turnId as RunId | undefined);
770 if (runId === undefined) {
771 const projection = yield* getProjection(input.threadId);
772 runId = projection.runs.findLast(
773 (run) =>
774 run.status === "preparing" ||
775 run.status === "starting" ||
776 run.status === "running" ||
777 run.status === "waiting",
778 )?.id;
779 if (runId === undefined) {
780 const latestRun = projection.runs.at(-1);
781 if (
782 derivePendingBackgroundWork({
783 latestRun,
784 providerThreads: projection.providerThreads,
785 turnItems: projection.turnItems,
786 activeProviderThreadId: projection.thread.activeProviderThreadId,
787 runs: projection.runs,
788 }).length > 0
789 ) {
790 runId = latestRun?.id;
791 }
792 }
793 }
794 if (runId === undefined) return { sequence: 0 };
795 return yield* dispatch({
796 type: "run.interrupt",
797 commandId: yield* allocateCommandId(input),
798 threadId: input.threadId,
799 runId,
800 });
801});
802​
803export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
804 function* (input: RespondToThreadApprovalInput) {
805 return yield* dispatch({
806 type: "runtime-request.respond",
807 commandId: yield* allocateCommandId(input),
808 threadId: input.threadId,
809 requestId: input.requestId,
810 decision: input.decision,
811 });
812 },
813);
814​
815export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
816 function* (input: RespondToThreadUserInputInput) {
817 return yield* dispatch({
818 type: "runtime-request.respond",
819 commandId: yield* allocateCommandId(input),
820 threadId: input.threadId,
821 requestId: input.requestId,
822 answers: input.answers,
823 ...(input.attachmentsByQuestionId === undefined
824 ? {}
825 : { attachmentsByQuestionId: input.attachmentsByQuestionId }),
826 });
827 },
828);
829​
830export const dismissThreadUserInput = Effect.fn("EnvironmentCommands.dismissThreadUserInput")(
831 function* (input: DismissThreadUserInputInput) {
832 return yield* dispatch({
833 type: "thread.user-input.dismiss",
834 commandId: yield* allocateCommandId(input),
835 threadId: input.threadId,
836 requestId: input.requestId,
837 });
838 },
839);
840​
841export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
842 function* (input: RevertThreadCheckpointInput) {
843 if (
844 input.checkpointId !== undefined &&
845 input.scopeId !== undefined &&
846 (yield* supportsServerResolvedCommandContext())
847 ) {
848 return yield* dispatch({
849 type: "checkpoint.rollback",
850 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
851 commandId: yield* allocateCommandId(input),
852 threadId: input.threadId,
853 scopeId: CheckpointScopeId.make(input.scopeId),
854 checkpointId: CheckpointId.make(input.checkpointId),
855 });
856 }
857 const projection = yield* getProjection(input.threadId);
858 const checkpoint =
859 projection.checkpoints.find(
860 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
861 ) ??
862 projection.checkpoints.findLast((candidate) =>
863 input.turnCount === 0
864 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
865 : candidate.appRunOrdinal === input.turnCount,
866 );
867 if (checkpoint === undefined || checkpoint.status !== "ready") {
868 const target =
869 input.checkpointId === undefined
870 ? `run ordinal ${input.turnCount ?? "unknown"}`
871 : `checkpoint ${input.checkpointId}`;
872 return yield* new OrchestrationV2CheckpointUnavailableError({
873 threadId: input.threadId,
874 target,
875 });
876 }
877 return yield* dispatch({
878 type: "checkpoint.rollback",
879 ...(input.restoreFiles === undefined ? {} : { restoreFiles: input.restoreFiles }),
880 commandId: yield* allocateCommandId(input),
881 threadId: input.threadId,
882 scopeId: checkpoint.scopeId,
883 checkpointId: checkpoint.id,
884 });
885 },
886);
887​
888export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
889 input: StopThreadSessionInput,
890) {
891 const projection = yield* getProjection(input.threadId);
892 const commandId = yield* allocateCommandId(input);
893 let result = { sequence: 0 };
894 for (const session of projection.providerSessions) {
895 result = yield* dispatch({
896 type: "provider-session.detach",
897 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
898 threadId: input.threadId,
899 providerSessionId: session.id,
900 reason: "client-requested",
901 });
902 }
903 return result;
904});
905​
906export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
907 input: ForkThreadFromRunInput,
908) {
909 return yield* dispatch({
910 type: "thread.fork",
911 commandId: yield* allocateCommandId(input),
912 createdBy: "user",
913 creationSource: input.creationSource ?? "web",
914 sourceThreadId: input.sourceThreadId,
915 targetThreadId: input.targetThreadId,
916 sourcePoint: { type: "run", runId: input.runId },
917 ...(input.title === undefined ? {} : { title: input.title }),
918 });
919});
920​
921export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
922 input: MergeThreadBackInput,
923) {
924 return yield* dispatch({
925 type: "thread.merge_back",
926 commandId: yield* allocateCommandId(input),
927 createdBy: "user",
928 creationSource: input.creationSource ?? "web",
929 sourceThreadId: input.sourceThreadId,
930 targetThreadId: input.targetThreadId,
931 sourcePoint: { type: "run", runId: input.runId },
932 });
933});
934​
935export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
936 input: ThreadCommandInput,
937) {
938 return yield* dispatch({
939 type: "queue.resume",
940 commandId: yield* allocateCommandId(input),
941 threadId: input.threadId,
942 });
943});
944​
945export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
946 input: ReorderQueuedRunInput,
947) {
948 return yield* dispatch({
949 type: "queued-run.reorder",
950 commandId: yield* allocateCommandId(input),
951 threadId: input.threadId,
952 runId: input.runId,
953 beforeRunId: input.beforeRunId,
954 });
955});
956​
957export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
958 input: PromoteQueuedRunInput,
959) {
960 return yield* dispatch({
961 type: "queued-message.promote-to-steer",
962 commandId: yield* allocateCommandId(input),
963 threadId: input.threadId,
964 queuedRunId: input.queuedRunId,
965 targetRunId: input.targetRunId,
966 });
967});
968​
969export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
970 input: CancelQueuedRunInput,
971) {
972 return yield* dispatch({
973 type: "queued-run.cancel",
974 commandId: yield* allocateCommandId(input),
975 threadId: input.threadId,
976 runId: input.runId,
977 });
978});
979​
980export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
981 input: EditQueuedRunInput,
982) {
983 const attachments =
984 input.edit === undefined
985 ? undefined
986 : yield* persistAttachments(input.threadId, input.edit.messageId, input.edit.attachments);
987 return yield* dispatch({
988 type: "queued-run.edit",
989 commandId: yield* allocateCommandId(input),
990 threadId: input.threadId,
991 runId: input.runId,
992 text: input.text,
993 ...(attachments === undefined ? {} : { attachments }),
994 ...(input.edit?.context && attachments
995 ? {
996 context: remapComposerContextAttachments(
997 input.edit.context,
998 input.edit.attachments,
999 attachments,
1000 ),
1002 : {}),
1003 });
1004});
1005​
1006export type LinkThreadPullRequestInput = Omit<
1007 Extract<OrchestrationV2Command, { type: "thread.pull-request.link" }>,
1008 "type" | "commandId"
1009> &
1010 CommandMetadata;
1011export type UnlinkThreadPullRequestInput = Omit<
1012 Extract<OrchestrationV2Command, { type: "thread.pull-request.unlink" }>,
1013 "type" | "commandId"
1014> &
1015 CommandMetadata;
1016export const linkThreadPullRequest = Effect.fn("EnvironmentCommands.linkThreadPullRequest")(
1017 function* (input: LinkThreadPullRequestInput) {
1018 return yield* dispatch({
1019 ...input,
1020 type: "thread.pull-request.link",
1021 commandId: yield* allocateCommandId(input),
1022 });
1023 },
1025export const unlinkThreadPullRequest = Effect.fn("EnvironmentCommands.unlinkThreadPullRequest")(
1026 function* (input: UnlinkThreadPullRequestInput) {
1027 return yield* dispatch({
1028 ...input,
1029 type: "thread.pull-request.unlink",
1030 commandId: yield* allocateCommandId(input),
1031 });
1032 },