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