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