Open History to see the last commit
1import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
2import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
3import * as TerminalManager from "../terminal/Manager.ts";
4import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
5import {
6 CommandId,
7 type ChatAttachment,
8 type MessageId,
9 type ModelSelection,
10 type OrchestrationV2Actor,
11 type OrchestrationV2CreationSource,
12 type OrchestrationV2DelegatedFrom,
13 type OrchestrationV2LinkOrigin,
14 type OrchestrationV2ProviderThreadNativeMetadata,
15 type OrchestrationV2ThreadProjection,
16 type ProviderDriverKind,
17 type ProviderInteractionMode,
18 ProjectId,
19 type RunId,
20 type RuntimeMode,
21 type ScheduledTaskId,
22 ThreadId,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Context from "effect/Context";
26import * as Effect from "effect/Effect";
27import * as Exit from "effect/Exit";
28import * as Fiber from "effect/Fiber";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Ref from "effect/Ref";
32import * as Schema from "effect/Schema";
33import * as Scope from "effect/Scope";
34import * as Stream from "effect/Stream";
35import {
36 buildTemporaryWorktreeBranchName,
37 flattenTemporaryWorktreeBranchName,
38 isTemporaryWorktreeBranch,
39 WORKTREE_BRANCH_PREFIX,
40} from "@t3tools/shared/git";
41
42import * as GitWorkflow from "../git/GitWorkflowService.ts";
43import * as ProjectService from "../project/ProjectService.ts";
44import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
45import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
46import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
47import * as ServerSettings from "../serverSettings.ts";
48import * as TextGeneration from "../textGeneration/TextGeneration.ts";
49import * as CommandReceiptStore from "./CommandReceiptStore.ts";
50import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
51import type * as Orchestrator from "./Orchestrator.ts";
52import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
53import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
54import { DispatchModeLimit } from "./DispatchModeLimit.ts";
55import * as ThreadManagement from "./ThreadManagementService.ts";
56
57export type ThreadLaunchWorkspaceStrategy =
58 | { readonly type: "root"; readonly branch?: string | undefined }
59 | {
60 readonly type: "existing_worktree";
61 readonly worktreePath: string;
62 readonly branch?: string | undefined;
63 }
64 | {
65 readonly type: "worktree";
66 readonly baseRef: string;
67 readonly branch?: string | undefined;
68 readonly startFromOrigin?: boolean | undefined;
69 };
70
71export interface ThreadLaunchInitialMessage {
72 readonly messageId?: MessageId;
73 readonly scheduledTaskId?: ScheduledTaskId;
74 readonly senderThreadId?: ThreadId;
75 readonly text: string;
76 readonly attachments: ReadonlyArray<ChatAttachment>;
77 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
78}
79
80export interface ThreadLaunchInput {
81 readonly commandId: CommandId;
82 readonly threadId?: ThreadId;
83 readonly reuseExistingThread?: boolean;
84 readonly projectId: ProjectId;
85 readonly title: string;
86 readonly generateTitle?: boolean;
87 readonly modelSelection: ModelSelection;
88 readonly runtimeMode: RuntimeMode;
89 readonly interactionMode: ProviderInteractionMode;
90 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
91 readonly initialMessage?: ThreadLaunchInitialMessage;
92 readonly importedNativeThread?: {
93 readonly ref: {
94 readonly driver: ProviderDriverKind;
95 readonly nativeId: string;
96 readonly strength: "strong";
97 };
98 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
99 };
100 readonly createdBy: OrchestrationV2Actor;
101 readonly creationSource: OrchestrationV2CreationSource;
102 /** The linked environment this launch is for, if one asked for it. */
103 readonly linkOrigin?: OrchestrationV2LinkOrigin;
104 /** The parent there, when that environment's agent delegated this as a task. */
105 readonly delegatedFrom?: OrchestrationV2DelegatedFrom;
106}
107
108type PreparationInput = Pick<
109 ThreadLaunchInput,
110 "commandId" | "projectId" | "workspaceStrategy" | "initialMessage"
111> & {
112 readonly reusedWorktree?: { readonly baseRef: string };
113};
114
115export interface ThreadLaunchPreparationInput {
116 readonly commandId: CommandId;
117 readonly threadId: ThreadId;
118 readonly runId: RunId;
119}
120
121export interface ThreadLaunchResult {
122 readonly threadId: ThreadId;
123 readonly projection: OrchestrationV2ThreadProjection;
124 /** The launch's last write (the initial message, else the thread claim) was accepted before this call. */
125 readonly resumed: boolean;
126 readonly sequence?: number;
127}
128
129export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
130 "ThreadLaunchError",
131 {
132 operation: Schema.Literals([
133 "resolve-project",
134 "read-receipt",
135 "generate-metadata",
136 "provision-worktree",
137 "run-setup-script",
138 "create-thread",
139 "update-thread",
140 "dispatch-message",
141 "release-run",
142 "fail-run",
143 ]),
144 commandId: CommandId,
145 projectId: ProjectId,
146 threadId: Schema.optional(ThreadId),
147 cause: Schema.Defect(),
148 },
149) {
150 override get message(): string {
151 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
152 }
153}
154
155export class ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBaseRefError>()(
156 "ThreadLaunchBaseRefError",
157 {
158 projectId: ProjectId,
159 projectTitle: Schema.String,
160 workspaceRoot: Schema.String,
161 baseRef: Schema.String,
162 },
163) {
164 override get message(): string {
165 return `Base ref "${this.baseRef}" does not resolve to a commit in project "${this.projectTitle}" (${this.workspaceRoot}).`;
166 }
167}
168
169export class ThreadLaunchService extends Context.Service<
170 ThreadLaunchService,
171 {
172 readonly launch: (
173 input: ThreadLaunchInput,
174 ) => Effect.Effect<
175 ThreadLaunchResult,
176 ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
177 >;
178 /** Check before creation for early errors; launch otherwise accepts and reports base failures inside the thread. */
179 readonly checkWorktreeBase: (
180 input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy">,
181 ) => Effect.Effect<void, ThreadLaunchBaseRefError>;
182 readonly retryPreparation: (
183 input: ThreadLaunchPreparationInput,
184 ) => Effect.Effect<
185 Orchestrator.OrchestratorV2DispatchResult,
186 | Orchestrator.OrchestratorV2Error
187 | ThreadManagement.ThreadManagementProviderInstanceDisabledError
188 >;
189 readonly prepareRun: (input: ThreadLaunchPreparationInput) => Effect.Effect<void>;
190 }
191>()("t3/orchestration-v2/ThreadLaunchService") {}
192
193const isThreadLaunchError = Schema.is(ThreadLaunchError);
194
195function failureDetail(error: unknown): string {
196 if (isThreadLaunchError(error)) {
197 const cause = error.cause;
198 const detail = cause instanceof Error ? cause.message : String(cause);
199 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
200 }
201 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
202}
203
204const make = Effect.gen(function* () {
205 const projects = yield* ProjectService.ProjectService;
206 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
207 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
208 const terminals = yield* TerminalManager.TerminalManager;
209 const git = yield* GitWorkflow.GitWorkflowService;
210 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
211 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
212 const serverSettings = yield* ServerSettings.ServerSettingsService;
213 const textGeneration = yield* TextGeneration.TextGeneration;
214 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
215 const ids = yield* IdAllocator.IdAllocatorV2;
216 const threads = yield* ThreadManagement.ThreadManagementService;
217 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
218 const preparationScope = yield* Scope.make("sequential");
219 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
220 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
221
222 const mapError =
223 (input: PreparationInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
224 (cause: unknown) =>
225 new ThreadLaunchError({
226 operation,
227 commandId: input.commandId,
228 projectId: input.projectId,
229 ...(threadId === undefined ? {} : { threadId }),
230 cause,
231 });
232
233 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
234 receipts
235 .getByCommandId(commandId)
236 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
237
238 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
239 input: ThreadLaunchInput,
240 threadId: ThreadId,
241 ) {
242 const projection = yield* threads
243 .getThreadRecords(threadId, ["runs"])
244 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
245 if (
246 projection.thread.projectId !== input.projectId ||
247 projection.thread.archivedAt !== null ||
248 projection.thread.deletedAt !== null ||
249 (yield* threads
250 .getMessageCount(threadId)
251 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
252 projection.runs.length > 0
253 ) {
254 return yield* mapError(
255 input,
256 "update-thread",
257 threadId,
258 )("Only an empty active thread in the target project can change workspace during launch.");
259 }
260 });
261
262 const checkWorktreeBase: ThreadLaunchService["Service"]["checkWorktreeBase"] = Effect.fn(
263 "ThreadLaunchService.checkWorktreeBase",
264 )(function* (input) {
265 const strategy = input.workspaceStrategy;
266 // `:/text` is a commit search, which cannot be asked for a commit type.
267 if (strategy.type !== "worktree" || strategy.baseRef.startsWith(":")) return;
268 const { baseRef } = strategy;
269 const unresolved = yield* Effect.gen(function* () {
270 const project = Option.getOrUndefined(yield* projects.getById(input.projectId));
271 if (project === undefined) return undefined;
272 const cwd = project.workspaceRoot;
273 // `git worktree add` reads `-` as the previous checkout.
274 if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
275 return undefined;
276 if (
277 strategy.startFromOrigin === true &&
278 (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null
279 )
280 return undefined;
281 // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists.
282 if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return undefined;
283 return (yield* git.hasCommit({ cwd, refName: "HEAD" })) ? project : undefined;
284 }).pipe(Effect.orElseSucceed(() => undefined));
285 if (unresolved !== undefined)
286 return yield* new ThreadLaunchBaseRefError({
287 projectId: unresolved.id,
288 projectTitle: unresolved.title,
289 workspaceRoot: unresolved.workspaceRoot,
290 baseRef,
291 });
292 });
293
294 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
295 input: PreparationInput,
296 threadId: ThreadId,
297 runId: RunId | null,
298 ) {
299 const project = yield* projects.getById(input.projectId).pipe(
300 Effect.mapError(mapError(input, "resolve-project", threadId)),
301 Effect.flatMap(
302 Option.match({
303 onNone: () =>
304 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
305 onSome: Effect.succeed,
306 }),
307 ),
308 );
309
310 const reused = input.reusedWorktree;
311 const tracked = input.workspaceStrategy.type === "worktree" || reused !== undefined;
312 let createdWorktreePath: string | null = null;
313 let createdBranch: string | null = null;
314 let setupTerminalId: string | null = null;
315 let workspaceRecorded = false;
316 let runReleased = false;
317 // Stop background renames before forgetting worktrees; completed renames record them again.
318 let branchRename: Fiber.Fiber<unknown> | null = null;
319 if (input.workspaceStrategy.type === "worktree") {
320 yield* setupTracker.begin({
321 threadId,
322 branch: input.workspaceStrategy.branch ?? null,
323 baseRef: input.workspaceStrategy.baseRef,
324 stages: ["fetch", "checkout", "setup-script", "agent"],
325 fiber: yield* Effect.fiber,
326 });
327 } else if (reused !== undefined) {
328 yield* setupTracker.begin({
329 threadId,
330 branch: input.workspaceStrategy.branch ?? null,
331 baseRef: reused.baseRef,
332 stages: ["setup-script", "agent"],
333 fiber: yield* Effect.fiber,
334 });
335 }
336 yield* Effect.gen(function* () {
337 const initialMessage = input.initialMessage;
338 const generateBranchNameFor = Effect.fn("ThreadLaunchService.generateBranchNameFor")(
339 function* (cwd: string, message: ThreadLaunchInitialMessage) {
340 const settings = resolveProjectSettings(
341 yield* serverSettings.getSettings,
342 input.projectId,
343 ).settings;
344 const modelSelection =
345 settings.sourceControlWriterModelSelection === null
346 ? settings.textGenerationModelSelection
347 : ServerSettings.resolveSourceControlWriterModelSelection(
348 settings,
349 yield* providerRegistry.getProviders,
350 input.projectId,
351 );
352 return yield* textGeneration
353 .generateBranchName({
354 naming: {
355 mode: settings.branchNamingMode,
356 prefix: settings.branchNamePrefix,
357 instructions: settings.branchNameInstructions,
358 },
359 cwd,
360 message: message.text,
361 attachments: message.attachments,
362 ...(message.context ? { context: message.context } : {}),
363 modelSelection,
364 })
365 .pipe(
366 Effect.map((result) => ({
367 branch: result.branch,
368 exactName: settings.branchNamingMode === "custom",
369 })),
370 );
371 },
372 );
373
374 const requestedBranch = input.workspaceStrategy.branch;
375 let branch: string | null;
376 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
377 const uuid = yield* randomUuidV4;
378 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
379 } else {
380 branch = requestedBranch ?? null;
381 }
382 let worktreePath =
383 input.workspaceStrategy.type === "existing_worktree"
384 ? input.workspaceStrategy.worktreePath
385 : null;
386 if (input.workspaceStrategy.type === "worktree") {
387 if (runId !== null) {
388 yield* threads
389 .dispatch({
390 type: "prepared-run.progress",
391 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
392 threadId,
393 runId,
394 phase: "worktree",
395 })
396 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
397 }
398 let startRef = input.workspaceStrategy.baseRef;
399 let baseRefName = input.workspaceStrategy.baseRef;
400 const remote =
401 input.workspaceStrategy.startFromOrigin === true
402 ? yield* git
403 .resolveWorktreeBaseRemote({
404 cwd: project.workspaceRoot,
405 refName: input.workspaceStrategy.baseRef,
406 })
407 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
408 : null;
409 const shouldFetch = remote !== null;
410 yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
411 if (remote !== null) {
412 const remoteBase = yield* git
413 .fetchWorktreeBaseCommit({
414 cwd: project.workspaceRoot,
415 refName: input.workspaceStrategy.baseRef,
416 remote,
417 })
418 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
419 if (remoteBase !== null) {
420 startRef = remoteBase.commitSha;
421 baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
422 }
423 }
424 if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
425 if (
426 branch !== null &&
427 isTemporaryWorktreeBranch(branch) &&
428 (yield* git
429 .hasCommit({
430 cwd: project.workspaceRoot,
431 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
432 })
433 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
434 ) {
435 branch = flattenTemporaryWorktreeBranchName(branch);
436 }
437 yield* setupTracker.stageStatus(threadId, "checkout", "running");
438 const worktree = yield* git
439 .createWorktree(
440 {
441 cwd: project.workspaceRoot,
442 refName: startRef,
443 newRefName: branch!,
444 baseRefName,
445 path: null,
446 },
447 {
448 progress: {
449 onWorktreeClaimed: (path) =>
450 Effect.sync(() => {
451 createdWorktreePath = path;
452 createdBranch = branch;
453 }),
454 onCheckoutProgress: (progress) =>
455 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
456 },
457 },
458 )
459 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
460 worktreePath = worktree.worktree.path;
461 branch = worktree.worktree.refName;
462 createdWorktreePath = worktreePath;
463 createdBranch = branch;
464 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
465 yield* setupTracker.stageStatus(threadId, "checkout", "done");
466 }
467
468 // Do not rewrite reused worktrees; that could undo the original branch rename.
469 if (reused === undefined) {
470 yield* threads
471 .dispatch({
472 type: "thread.metadata.update",
473 commandId: CommandId.make(`${input.commandId}:workspace`),
474 threadId,
475 branch,
476 worktreePath,
477 })
478 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
479 }
480 workspaceRecorded = true;
481
482 if (
483 reused === undefined &&
484 worktreePath !== null &&
485 branch !== null &&
486 initialMessage !== undefined &&
487 isTemporaryWorktreeBranch(branch)
488 ) {
489 const oldBranch = branch;
490 const worktreeCwd = worktreePath;
491 branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
492 Effect.flatMap(({ branch: newBranch, exactName }) =>
493 git
494 .renameBranch({
495 cwd: worktreeCwd,
496 oldBranch,
497 newBranch,
498 ...(exactName ? { exactName: true } : {}),
499 })
500 .pipe(
501 // A cancel must see the renamed branch, or its cleanup deletes the old name.
502 Effect.tap((renamed) =>
503 Effect.sync(() => {
504 createdBranch = renamed.branch;
505 }),
506 ),
507 Effect.uninterruptible,
508 ),
509 ),
510 Effect.flatMap((renamed) =>
511 Effect.gen(function* () {
512 yield* threads
513 .dispatch({
514 type: "thread.metadata.update",
515 commandId: CommandId.make(`${input.commandId}:branch-rename`),
516 threadId,
517 branch: renamed.branch,
518 worktreePath: worktreeCwd,
519 expectedBranch: oldBranch,
520 expectedWorktreePath: worktreeCwd,
521 })
522 .pipe(
523 Effect.catchCause((cause) =>
524 Effect.logWarning("Parent thread worktree branch update failed", {
525 threadId,
526 cause,
527 }),
528 ),
529 );
530 // Update parents first so children inherit names; reread each pass for newly updated descendants.
531 const visited = new Set([threadId]);
532 while (true) {
533 const snapshot = yield* threads.getShellSnapshot({ worktreePath: worktreeCwd });
534 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
535 (thread) => !visited.has(thread.id) && thread.branch === oldBranch,
536 );
537 if (sharing.length === 0) break;
538 for (const thread of sharing) {
539 visited.add(thread.id);
540 yield* threads
541 .dispatch({
542 type: "thread.metadata.update",
543 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
544 threadId: thread.id,
545 branch: renamed.branch,
546 expectedBranch: oldBranch,
547 expectedWorktreePath: worktreeCwd,
548 })
549 .pipe(
550 Effect.catchCause((cause) =>
551 Effect.logWarning("Shared thread worktree branch update failed", {
552 threadId: thread.id,
553 cause,
554 }),
555 ),
556 );
557 }
558 }
559 }),
560 ),
561 Effect.catchCause((cause) =>
562 Effect.logWarning("Thread worktree branch rename failed", {
563 commandId: input.commandId,
564 threadId,
565 oldBranch,
566 cause,
567 }),
568 ),
569 Effect.forkIn(preparationScope),
570 );
571 }
572
573 if (runId !== null && worktreePath !== null) {
574 yield* threads
575 .dispatch({
576 type: "prepared-run.progress",
577 commandId: CommandId.make(`${input.commandId}:progress:setup`),
578 threadId,
579 runId,
580 phase: "setup",
581 })
582 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
583 }
584 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
585 const setup =
586 worktreePath === null
587 ? ({ status: "no-script" } as const)
588 : yield* setupScripts
589 .runForThread({
590 threadId,
591 projectId: input.projectId,
592 projectCwd: project.workspaceRoot,
593 worktreePath,
594 ...(tracked
595 ? {
596 observeCompletion: {
597 onOutputLine: (line: string) =>
598 setupTracker.appendTail(threadId, "setup-script", line),
599 },
600 }
601 : {}),
602 project: {
603 id: project.id,
604 workspaceRoot: project.workspaceRoot,
605 scripts: project.scripts,
606 },
607 })
608 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
609
610 let awaitAsyncSetup = Effect.void;
611 if (setup.status === "started") {
612 setupTerminalId = setup.terminalId;
613 yield* setupTracker.update(threadId, (snapshot) => ({
614 ...snapshot,
615 setupScript: {
616 name: setup.scriptName,
617 command: setup.scriptCommand,
618 terminalId: setup.terminalId,
619 },
620 }));
621 if (setup.completion) {
622 const awaitCompletion = Effect.gen(function* () {
623 const completion = yield* setup.completion!;
624 yield* setupTracker.stage(threadId, "setup-script", {
625 status: completion.exitCode === 0 ? "done" : "failed",
626 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
627 });
628 if (completion.exitCode !== 0 && !setup.async)
629 return yield* mapError(
630 input,
631 "run-setup-script",
632 threadId,
633 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
634 });
635 if (setup.async) {
636 awaitAsyncSetup = awaitCompletion.pipe(
637 Effect.catchCause((cause) =>
638 setupTracker.stage(threadId, "setup-script", {
639 status: "failed",
640 detail: failureDetail(Cause.squash(cause)),
641 }),
642 ),
643 );
644 } else {
645 yield* awaitCompletion;
646 }
647 } else {
648 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
649 }
650 } else {
651 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
652 }
653 yield* setupTracker.markUncancellable(threadId);
654 yield* setupTracker.stageStatus(threadId, "agent", "running");
655 if (runId !== null) {
656 yield* threads
657 .dispatch({
658 type: "prepared-run.release",
659 commandId: CommandId.make(`${input.commandId}:release`),
660 threadId,
661 runId,
662 })
663 .pipe(
664 Effect.mapError(mapError(input, "release-run", threadId)),
665 Effect.tap(() =>
666 Effect.sync(() => {
667 runReleased = true;
668 }),
669 ),
670 Effect.uninterruptible,
671 );
672 }
673 yield* setupTracker.stageStatus(threadId, "agent", "done");
674 yield* awaitAsyncSetup;
675 yield* setupTracker.finish(threadId, "done");
676 }).pipe(
677 Effect.onError((cause) =>
678 Effect.gen(function* () {
679 const cancelled = Cause.hasInterruptsOnly(cause);
680 yield* setupTracker.finish(
681 threadId,
682 cancelled ? "cancelled" : "failed",
683 cancelled ? null : failureDetail(Cause.squash(cause)),
684 );
685 if (cancelled && setupTerminalId)
686 yield* terminals
687 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
688 .pipe(Effect.ignore);
689 if (
690 tracked &&
691 createdWorktreePath &&
692 ((cancelled && !runReleased) || !workspaceRecorded)
693 ) {
694 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
695 const removedPath = createdWorktreePath;
696 const removedBranch = createdBranch;
697 // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts.
698 yield* git
699 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
700 .pipe(
701 Effect.andThen(
702 removedBranch === null
703 ? Effect.void
704 : git
705 .deleteLocalBranch({
706 cwd: project.workspaceRoot,
707 refName: removedBranch,
708 force: true,
709 })
710 .pipe(Effect.ignoreCause({ log: true })),
711 ),
712 Effect.andThen(
713 threads
714 .dispatch({
715 type: "thread.metadata.update",
716 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
717 threadId,
718 worktreePath: null,
719 branch: null,
720 })
721 .pipe(Effect.ignore),
722 ),
723 Effect.catchCause((removeCause) =>
724 Effect.logWarning("Failed to remove an abandoned thread worktree", {
725 commandId: input.commandId,
726 threadId,
727 path: removedPath,
728 cause: removeCause,
729 }),
730 ),
731 );
732 }
733 }),
734 ),
735 );
736 });
737
738 const failPreparedRun = (
739 input: Pick<PreparationInput, "commandId">,
740 threadId: ThreadId,
741 runId: RunId | null,
742 cause: unknown,
743 ) =>
744 runId === null
745 ? Effect.logWarning("Thread workspace preparation failed", {
746 commandId: input.commandId,
747 threadId,
748 cause,
749 })
750 : threads
751 .dispatch({
752 type: "prepared-run.fail",
753 commandId: CommandId.make(`${input.commandId}:fail`),
754 threadId,
755 runId,
756 failure: makeProviderFailure({
757 cause,
758 message: failureDetail(cause),
759 class: "validation_error",
760 retryable: false,
761 }),
762 })
763 .pipe(
764 Effect.catchCause((persistCause) =>
765 Effect.logWarning("Failed to persist thread workspace preparation failure", {
766 commandId: input.commandId,
767 threadId,
768 cause,
769 persistCause,
770 }),
771 ),
772 );
773
774 const reservePreparation = (commandId: CommandId) =>
775 Ref.modify(scheduledLaunches, (scheduled) => {
776 if (scheduled.has(commandId)) return [false, scheduled] as const;
777 const next = new Set(scheduled);
778 next.add(commandId);
779 return [true, next] as const;
780 });
781
782 const releasePreparation = (commandId: CommandId) =>
783 Ref.update(scheduledLaunches, (scheduled) => {
784 const next = new Set(scheduled);
785 next.delete(commandId);
786 return next;
787 });
788
789 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
790 input: PreparationInput,
791 threadId: ThreadId,
792 runId: RunId | null,
793 ) {
794 const preparation = Effect.gen(function* () {
795 const prepare = prepareInBackground(input, threadId, runId);
796 if (
797 runId === null ||
798 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
799 ) {
800 return yield* prepare;
801 }
802 const afterSequence = yield* threads.getThreadEventSequence(threadId);
803 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
804 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
805 const interruption = threads
806 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
807 .pipe(
808 Stream.filter(
809 (stored) =>
810 stored.event.type === "run.updated" &&
811 stored.event.payload.id === runId &&
812 (stored.event.payload.status === "interrupted" ||
813 stored.event.payload.status === "cancelled"),
814 ),
815 Stream.runHead,
816 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
817 );
818 yield* Effect.raceFirst(prepare, interruption);
819 });
820 yield* preparation.pipe(
821 Effect.onError((cause) =>
822 failPreparedRun(
823 input,
824 threadId,
825 runId,
826 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
827 ),
828 ),
829 Effect.ignoreCause,
830 Effect.ensuring(releasePreparation(input.commandId)),
831 Effect.forkIn(preparationScope),
832 );
833 });
834
835 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
836 function* (request) {
837 // Scratch has no Git repository. Normalize before folder allocation so
838 // durable preparation and retries use the thread's own Scratch folder.
839 const input: ThreadLaunchInput =
840 request.workspaceStrategy.type === "worktree" &&
841 (yield* managedFolders.isScratchProject(request.projectId))
842 ? { ...request, workspaceStrategy: { type: "root" } }
843 : request;
844 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
845 type: "thread.create",
846 projectId: input.projectId,
847 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
848 const project = yield* projects.getById(input.projectId).pipe(
849 Effect.mapError(mapError(input, "resolve-project")),
850 Effect.flatMap(
851 Option.match({
852 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
853 onSome: Effect.succeed,
854 }),
855 ),
856 );
857 if (input.reuseExistingThread === true && input.threadId === undefined) {
858 return yield* mapError(
859 input,
860 "update-thread",
861 )("Reusing an existing thread requires a thread id.");
862 }
863
864 const launchReceipt = yield* readReceipt(input, input.commandId);
865 yield* threads.assertProviderInstanceEnabled({
866 projectId: input.projectId,
867 commandId: input.commandId,
868 instanceId: input.modelSelection.instanceId,
869 });
870 return yield* Effect.gen(function* () {
871 // Recover ids from accepted launch receipts before allocating; retries have no client id and new ids collide with receipts.
872 const reusableLaunchReceipt =
873 input.threadId === undefined &&
874 Option.isSome(launchReceipt) &&
875 launchReceipt.value.status === "accepted" &&
876 launchReceipt.value.commandType === "thread.create"
877 ? launchReceipt.value
878 : undefined;
879 const candidateThreadId =
880 input.threadId ??
881 reusableLaunchReceipt?.threadId ??
882 (yield* ids.allocate
883 .thread({ projectId: input.projectId })
884 .pipe(Effect.mapError(mapError(input, "create-thread"))));
885
886 if (reusableLaunchReceipt !== undefined) {
887 const shell = yield* threads
888 .getThreadShell(candidateThreadId)
889 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
890 if (shell === null) {
891 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
892 }
893 if (shell.projectId !== input.projectId) {
894 return yield* mapError(
895 input,
896 "resolve-project",
897 candidateThreadId,
898 )("Project identity changed.");
899 }
900 }
901
902 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
903 yield* validateReusableThread(input, candidateThreadId);
904 }
905
906 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
907 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
908 ? Option.match(
909 yield* managedFolders
910 .folderForThread({
911 projectId: input.projectId,
912 threadId: candidateThreadId,
913 text: input.initialMessage?.text ?? input.title,
914 })
915 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
916 {
917 onNone: () => input.workspaceStrategy,
918 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
919 },
920 )
921 : input.workspaceStrategy;
922 const initialBranch = workspaceStrategy.branch ?? null;
923 const initialWorktreePath =
924 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
925 const claimDispatch =
926 input.reuseExistingThread === true
927 ? threads.dispatch({
928 type: "thread.metadata.update",
929 commandId: input.commandId,
930 threadId: candidateThreadId,
931 expectedEmpty: true,
932 })
933 : threads.dispatch({
934 type: "thread.create",
935 commandId: input.commandId,
936 threadId: candidateThreadId,
937 projectId: input.projectId,
938 title: input.title,
939 modelSelection: input.modelSelection,
940 runtimeMode: input.runtimeMode,
941 interactionMode: input.interactionMode,
942 branch: initialBranch,
943 worktreePath: initialWorktreePath,
944 ...(input.importedNativeThread === undefined
945 ? {}
946 : { importedNativeThread: input.importedNativeThread }),
947 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
948 ...(input.delegatedFrom === undefined
949 ? {}
950 : { delegatedFrom: input.delegatedFrom }),
951 createdBy: input.createdBy,
952 creationSource: input.creationSource,
953 });
954 const claimed = yield* claimDispatch.pipe(
955 Effect.mapError(
956 mapError(
957 input,
958 input.reuseExistingThread === true ? "update-thread" : "create-thread",
959 candidateThreadId,
960 ),
961 ),
962 );
963 const threadId =
964 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
965 .threadId ?? candidateThreadId;
966 if (project.id !== input.projectId) {
967 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
968 }
969 let runId: RunId | null = null;
970 let messageSequence: number | undefined;
971 let messageWasAlreadyAccepted = false;
972 if (input.initialMessage !== undefined) {
973 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
974 const messageReceipt = yield* readReceipt(input, messageCommandId);
975 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
976 const messageId =
977 input.initialMessage.messageId ??
978 (yield* ids.allocate
979 .message({ threadId, ordinal: 1 })
980 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
981 const dispatched = yield* threads
982 .dispatch({
983 type: "message.dispatch",
984 commandId: messageCommandId,
985 threadId,
986 messageId,
987 text: input.initialMessage.text,
988 ...(input.initialMessage.scheduledTaskId === undefined
989 ? {}
990 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
991 ...(input.initialMessage.senderThreadId === undefined
992 ? {}
993 : { senderThreadId: input.initialMessage.senderThreadId }),
994 attachments: input.initialMessage.attachments,
995 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
996 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
997 modelSelection: input.modelSelection,
998 dispatchMode: { type: "defer_start", workspaceStrategy },
999 createdBy: input.createdBy,
1000 creationSource: input.creationSource,
1001 })
1002 .pipe(
1003 // An agent's launch can land on a thread that a replay, or a concurrent
1004 // launch with the same key, created with broader modes. The orchestrator
1005 // refuses the message under the thread's lock; the user's own clients
1006 // launch into their own drafts, whatever modes those hold.
1007 input.createdBy === "agent"
1008 ? Effect.provideService(DispatchModeLimit, {
1009 runtimeMode: input.runtimeMode,
1010 interactionMode: input.interactionMode,
1011 })
1012 : (effect) => effect,
1013 Effect.mapError(mapError(input, "dispatch-message", threadId)),
1014 );
1015 // A concurrent retry can read no receipt and still replay the dispatch.
1016 messageWasAlreadyAccepted ||= dispatched.replayed === true;
1017 messageSequence = dispatched.sequence;
1018 const runCreated = dispatched.storedEvents.find(
1019 (stored) => stored.event.type === "run.created",
1020 );
1021 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
1022 if (runId === null) {
1023 return yield* mapError(
1024 input,
1025 "dispatch-message",
1026 threadId,
1027 )("Initial message was accepted without a durable run.");
1028 }
1029 }
1030
1031 const projection = yield* threads
1032 .getThreadProjection(threadId)
1033 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1034 const runIsPreparing =
1035 runId !== null &&
1036 projection.runs.some((run) => run.id === runId && run.status === "preparing");
1037 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
1038 const boundWorktreePath = projection.thread.worktreePath;
1039 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1040 Option.isSome(launchReceipt) &&
1041 workspaceStrategy.type === "root" &&
1042 boundWorktreePath !== null
1043 ? {
1044 type: "existing_worktree",
1045 worktreePath: boundWorktreePath,
1046 branch: workspaceStrategy.branch,
1047 }
1048 : workspaceStrategy;
1049 if (shouldSchedule) {
1050 const ownsPreparation = yield* reservePreparation(input.commandId);
1051 if (ownsPreparation) {
1052 yield* Effect.gen(function* () {
1053 const preparationStillRequired =
1054 runId === null
1055 ? true
1056 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1057 Effect.map((current) =>
1058 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1059 ),
1060 Effect.mapError(mapError(input, "update-thread", threadId)),
1061 );
1062 if (preparationStillRequired) {
1063 yield* schedulePreparation(
1064 { ...input, workspaceStrategy: preparationStrategy },
1065 threadId,
1066 runId,
1067 );
1068 } else {
1069 yield* releasePreparation(input.commandId);
1070 }
1071 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1072 }
1073 }
1074
1075 return {
1076 threadId,
1077 projection,
1078 // An attempt that failed after claiming the thread recorded nothing, so
1079 // only a repeat of the final write counts as resumed.
1080 resumed:
1081 input.initialMessage === undefined
1082 ? Option.isSome(launchReceipt) || claimed.replayed === true
1083 : messageWasAlreadyAccepted,
1084 ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1085 };
1086 });
1087 },
1088 );
1089
1090 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1091 "ThreadLaunchService.prepareRun",
1092 )(function* (input) {
1093 const scheduled = yield* Effect.gen(function* () {
1094 const { thread, runs } = yield* threads.getThreadRecords(input.threadId, ["runs"], {
1095 runIds: [input.runId],
1096 });
1097 const run = runs.find((candidate) => candidate.id === input.runId);
1098 const workspacePreparation = run?.workspacePreparation;
1099 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1100 if (!(yield* reservePreparation(input.commandId))) return;
1101 yield* scheduleRunPreparation(input, thread, run, workspacePreparation).pipe(
1102 Effect.onError(() => releasePreparation(input.commandId)),
1103 );
1104 }).pipe(Effect.exit);
1105 if (Exit.isFailure(scheduled)) {
1106 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1107 }
1108 });
1109
1110 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1111 "ThreadLaunchService.retryPreparation",
1112 )(function* (input) {
1113 const dispatched = yield* threads.dispatch({
1114 type: "prepared-run.retry",
1115 commandId: input.commandId,
1116 threadId: input.threadId,
1117 runId: input.runId,
1118 });
1119 yield* prepareRun(input);
1120 return dispatched;
1121 });
1122
1123 const scheduleRunPreparation = Effect.fn("ThreadLaunchService.scheduleRunPreparation")(function* (
1124 input: ThreadLaunchPreparationInput,
1125 thread: OrchestrationV2ThreadProjection["thread"],
1126 run: OrchestrationV2ThreadProjection["runs"][number],
1127 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1128 ) {
1129 const { messages } = yield* threads.getThreadRecords(input.threadId, ["messages"], {
1130 messageIds: [run.userMessageId],
1131 });
1132 const message = messages.find((candidate) => candidate.id === run.userMessageId);
1133 const reuse =
1134 workspacePreparation.type === "worktree" &&
1135 thread.worktreePath !== null &&
1136 thread.branch !== null
1137 ? {
1138 strategy: {
1139 type: "existing_worktree" as const,
1140 worktreePath: thread.worktreePath,
1141 branch: thread.branch,
1142 },
1143 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1144 }
1145 : null;
1146 return yield* schedulePreparation(
1147 {
1148 commandId: input.commandId,
1149 projectId: thread.projectId,
1150 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1151 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1152 ...(message === undefined
1153 ? {}
1154 : {
1155 initialMessage: {
1156 text: message.text,
1157 attachments: message.attachments,
1158 ...(message.context ? { context: message.context } : {}),
1159 },
1160 }),
1161 },
1162 input.threadId,
1163 run.id,
1164 );
1165 });
1166
1167 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1168});
1169
1170export const layer = Layer.effect(ThreadLaunchService, make);