@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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