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