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

commands.ts

966 lines32.0 KB

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