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