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

commands.ts

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