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 projectId: input.projectId,
365 })
366 .pipe(
367 Effect.map((result) => ({
368 branch: result.branch,
369 exactName: settings.branchNamingMode === "custom",
370 })),
371 );
372 },
373 );
374
375 const requestedBranch = input.workspaceStrategy.branch;
376 let branch: string | null;
377 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
378 const uuid = yield* randomUuidV4;
379 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
380 } else {
381 branch = requestedBranch ?? null;
382 }
383 let worktreePath =
384 input.workspaceStrategy.type === "existing_worktree"
385 ? input.workspaceStrategy.worktreePath
386 : null;
387 if (input.workspaceStrategy.type === "worktree") {
388 if (runId !== null) {
389 yield* threads
390 .dispatch({
391 type: "prepared-run.progress",
392 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
393 threadId,
394 runId,
395 phase: "worktree",
396 })
397 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
398 }
399 let startRef = input.workspaceStrategy.baseRef;
400 let baseRefName = input.workspaceStrategy.baseRef;
401 const remote =
402 input.workspaceStrategy.startFromOrigin === true
403 ? yield* git
404 .resolveWorktreeBaseRemote({
405 cwd: project.workspaceRoot,
406 refName: input.workspaceStrategy.baseRef,
407 })
408 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))
409 : null;
410 const shouldFetch = remote !== null;
411 yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
412 if (remote !== null) {
413 const remoteBase = yield* git
414 .fetchWorktreeBaseCommit({
415 cwd: project.workspaceRoot,
416 refName: input.workspaceStrategy.baseRef,
417 remote,
418 })
419 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
420 if (remoteBase !== null) {
421 startRef = remoteBase.commitSha;
422 baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
423 }
424 }
425 if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
426 if (
427 branch !== null &&
428 isTemporaryWorktreeBranch(branch) &&
429 (yield* git
430 .hasCommit({
431 cwd: project.workspaceRoot,
432 refName: `refs/heads/${WORKTREE_BRANCH_PREFIX}`,
433 })
434 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))))
435 ) {
436 branch = flattenTemporaryWorktreeBranchName(branch);
437 }
438 yield* setupTracker.stageStatus(threadId, "checkout", "running");
439 const worktree = yield* git
440 .createWorktree(
441 {
442 cwd: project.workspaceRoot,
443 refName: startRef,
444 newRefName: branch!,
445 baseRefName,
446 path: null,
447 },
448 {
449 progress: {
450 onWorktreeClaimed: (path) =>
451 Effect.sync(() => {
452 createdWorktreePath = path;
453 createdBranch = branch;
454 }),
455 onCheckoutProgress: (progress) =>
456 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
457 },
458 },
459 )
460 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
461 worktreePath = worktree.worktree.path;
462 branch = worktree.worktree.refName;
463 createdWorktreePath = worktreePath;
464 createdBranch = branch;
465 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
466 yield* setupTracker.stageStatus(threadId, "checkout", "done");
467 }
468
469 // Do not rewrite reused worktrees; that could undo the original branch rename.
470 if (reused === undefined) {
471 yield* threads
472 .dispatch({
473 type: "thread.metadata.update",
474 commandId: CommandId.make(`${input.commandId}:workspace`),
475 threadId,
476 branch,
477 worktreePath,
478 })
479 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
480 }
481 workspaceRecorded = true;
482
483 if (
484 reused === undefined &&
485 worktreePath !== null &&
486 branch !== null &&
487 initialMessage !== undefined &&
488 isTemporaryWorktreeBranch(branch)
489 ) {
490 const oldBranch = branch;
491 const worktreeCwd = worktreePath;
492 branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
493 Effect.flatMap(({ branch: newBranch, exactName }) =>
494 git
495 .renameBranch({
496 cwd: worktreeCwd,
497 oldBranch,
498 newBranch,
499 ...(exactName ? { exactName: true } : {}),
500 })
501 .pipe(
502 // A cancel must see the renamed branch, or its cleanup deletes the old name.
503 Effect.tap((renamed) =>
504 Effect.sync(() => {
505 createdBranch = renamed.branch;
506 }),
507 ),
508 Effect.uninterruptible,
509 ),
510 ),
511 Effect.flatMap((renamed) =>
512 Effect.gen(function* () {
513 yield* threads
514 .dispatch({
515 type: "thread.metadata.update",
516 commandId: CommandId.make(`${input.commandId}:branch-rename`),
517 threadId,
518 branch: renamed.branch,
519 worktreePath: worktreeCwd,
520 expectedBranch: oldBranch,
521 expectedWorktreePath: worktreeCwd,
522 })
523 .pipe(
524 Effect.catchCause((cause) =>
525 Effect.logWarning("Parent thread worktree branch update failed", {
526 threadId,
527 cause,
528 }),
529 ),
530 );
531 // Update parents first so children inherit names; reread each pass for newly updated descendants.
532 const visited = new Set([threadId]);
533 while (true) {
534 const snapshot = yield* threads.getShellSnapshot({ worktreePath: worktreeCwd });
535 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
536 (thread) => !visited.has(thread.id) && thread.branch === oldBranch,
537 );
538 if (sharing.length === 0) break;
539 for (const thread of sharing) {
540 visited.add(thread.id);
541 yield* threads
542 .dispatch({
543 type: "thread.metadata.update",
544 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
545 threadId: thread.id,
546 branch: renamed.branch,
547 expectedBranch: oldBranch,
548 expectedWorktreePath: worktreeCwd,
549 })
550 .pipe(
551 Effect.catchCause((cause) =>
552 Effect.logWarning("Shared thread worktree branch update failed", {
553 threadId: thread.id,
554 cause,
555 }),
556 ),
557 );
558 }
559 }
560 }),
561 ),
562 Effect.catchCause((cause) =>
563 Effect.logWarning("Thread worktree branch rename failed", {
564 commandId: input.commandId,
565 threadId,
566 oldBranch,
567 cause,
568 }),
569 ),
570 Effect.forkIn(preparationScope),
571 );
572 }
573
574 if (runId !== null && worktreePath !== null) {
575 yield* threads
576 .dispatch({
577 type: "prepared-run.progress",
578 commandId: CommandId.make(`${input.commandId}:progress:setup`),
579 threadId,
580 runId,
581 phase: "setup",
582 })
583 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
584 }
585 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
586 const setup =
587 worktreePath === null
588 ? ({ status: "no-script" } as const)
589 : yield* setupScripts
590 .runForThread({
591 threadId,
592 projectId: input.projectId,
593 projectCwd: project.workspaceRoot,
594 worktreePath,
595 ...(tracked
596 ? {
597 observeCompletion: {
598 onOutputLine: (line: string) =>
599 setupTracker.appendTail(threadId, "setup-script", line),
600 },
601 }
602 : {}),
603 project: {
604 id: project.id,
605 workspaceRoot: project.workspaceRoot,
606 scripts: project.scripts,
607 },
608 })
609 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
610
611 let awaitAsyncSetup = Effect.void;
612 if (setup.status === "started") {
613 setupTerminalId = setup.terminalId;
614 yield* setupTracker.update(threadId, (snapshot) => ({
615 ...snapshot,
616 setupScript: {
617 name: setup.scriptName,
618 command: setup.scriptCommand,
619 terminalId: setup.terminalId,
620 },
621 }));
622 if (setup.completion) {
623 const awaitCompletion = Effect.gen(function* () {
624 const completion = yield* setup.completion!;
625 yield* setupTracker.stage(threadId, "setup-script", {
626 status: completion.exitCode === 0 ? "done" : "failed",
627 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
628 });
629 if (completion.exitCode !== 0 && !setup.async)
630 return yield* mapError(
631 input,
632 "run-setup-script",
633 threadId,
634 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
635 });
636 if (setup.async) {
637 awaitAsyncSetup = awaitCompletion.pipe(
638 Effect.catchCause((cause) =>
639 setupTracker.stage(threadId, "setup-script", {
640 status: "failed",
641 detail: failureDetail(Cause.squash(cause)),
642 }),
643 ),
644 );
645 } else {
646 yield* awaitCompletion;
647 }
648 } else {
649 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
650 }
651 } else {
652 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
653 }
654 yield* setupTracker.markUncancellable(threadId);
655 yield* setupTracker.stageStatus(threadId, "agent", "running");
656 if (runId !== null) {
657 yield* threads
658 .dispatch({
659 type: "prepared-run.release",
660 commandId: CommandId.make(`${input.commandId}:release`),
661 threadId,
662 runId,
663 })
664 .pipe(
665 Effect.mapError(mapError(input, "release-run", threadId)),
666 Effect.tap(() =>
667 Effect.sync(() => {
668 runReleased = true;
669 }),
670 ),
671 Effect.uninterruptible,
672 );
673 }
674 yield* setupTracker.stageStatus(threadId, "agent", "done");
675 yield* awaitAsyncSetup;
676 yield* setupTracker.finish(threadId, "done");
677 }).pipe(
678 Effect.onError((cause) =>
679 Effect.gen(function* () {
680 const cancelled = Cause.hasInterruptsOnly(cause);
681 yield* setupTracker.finish(
682 threadId,
683 cancelled ? "cancelled" : "failed",
684 cancelled ? null : failureDetail(Cause.squash(cause)),
685 );
686 if (cancelled && setupTerminalId)
687 yield* terminals
688 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
689 .pipe(Effect.ignore);
690 if (
691 tracked &&
692 createdWorktreePath &&
693 ((cancelled && !runReleased) || !workspaceRecorded)
694 ) {
695 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
696 const removedPath = createdWorktreePath;
697 const removedBranch = createdBranch;
698 // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts.
699 yield* git
700 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
701 .pipe(
702 Effect.andThen(
703 removedBranch === null
704 ? Effect.void
705 : git
706 .deleteLocalBranch({
707 cwd: project.workspaceRoot,
708 refName: removedBranch,
709 force: true,
710 })
711 .pipe(Effect.ignoreCause({ log: true })),
712 ),
713 Effect.andThen(
714 threads
715 .dispatch({
716 type: "thread.metadata.update",
717 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
718 threadId,
719 worktreePath: null,
720 branch: null,
721 })
722 .pipe(Effect.ignore),
723 ),
724 Effect.catchCause((removeCause) =>
725 Effect.logWarning("Failed to remove an abandoned thread worktree", {
726 commandId: input.commandId,
727 threadId,
728 path: removedPath,
729 cause: removeCause,
730 }),
731 ),
732 );
733 }
734 }),
735 ),
736 );
737 });
738
739 const failPreparedRun = (
740 input: Pick<PreparationInput, "commandId">,
741 threadId: ThreadId,
742 runId: RunId | null,
743 cause: unknown,
744 ) =>
745 runId === null
746 ? Effect.logWarning("Thread workspace preparation failed", {
747 commandId: input.commandId,
748 threadId,
749 cause,
750 })
751 : threads
752 .dispatch({
753 type: "prepared-run.fail",
754 commandId: CommandId.make(`${input.commandId}:fail`),
755 threadId,
756 runId,
757 failure: makeProviderFailure({
758 cause,
759 message: failureDetail(cause),
760 class: "validation_error",
761 retryable: false,
762 }),
763 })
764 .pipe(
765 Effect.catchCause((persistCause) =>
766 Effect.logWarning("Failed to persist thread workspace preparation failure", {
767 commandId: input.commandId,
768 threadId,
769 cause,
770 persistCause,
771 }),
772 ),
773 );
774
775 const reservePreparation = (commandId: CommandId) =>
776 Ref.modify(scheduledLaunches, (scheduled) => {
777 if (scheduled.has(commandId)) return [false, scheduled] as const;
778 const next = new Set(scheduled);
779 next.add(commandId);
780 return [true, next] as const;
781 });
782
783 const releasePreparation = (commandId: CommandId) =>
784 Ref.update(scheduledLaunches, (scheduled) => {
785 const next = new Set(scheduled);
786 next.delete(commandId);
787 return next;
788 });
789
790 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
791 input: PreparationInput,
792 threadId: ThreadId,
793 runId: RunId | null,
794 ) {
795 const preparation = Effect.gen(function* () {
796 const prepare = prepareInBackground(input, threadId, runId);
797 if (
798 runId === null ||
799 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
800 ) {
801 return yield* prepare;
802 }
803 const afterSequence = yield* threads.getThreadEventSequence(threadId);
804 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
805 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
806 const interruption = threads
807 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
808 .pipe(
809 Stream.filter(
810 (stored) =>
811 stored.event.type === "run.updated" &&
812 stored.event.payload.id === runId &&
813 (stored.event.payload.status === "interrupted" ||
814 stored.event.payload.status === "cancelled"),
815 ),
816 Stream.runHead,
817 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
818 );
819 yield* Effect.raceFirst(prepare, interruption);
820 });
821 yield* preparation.pipe(
822 Effect.onError((cause) =>
823 failPreparedRun(
824 input,
825 threadId,
826 runId,
827 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
828 ),
829 ),
830 Effect.ignoreCause,
831 Effect.ensuring(releasePreparation(input.commandId)),
832 Effect.forkIn(preparationScope),
833 );
834 });
835
836 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
837 function* (request) {
838 // Scratch has no Git repository. Normalize before folder allocation so
839 // durable preparation and retries use the thread's own Scratch folder.
840 const input: ThreadLaunchInput =
841 request.workspaceStrategy.type === "worktree" &&
842 (yield* managedFolders.isScratchProject(request.projectId))
843 ? { ...request, workspaceStrategy: { type: "root" } }
844 : request;
845 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
846 type: "thread.create",
847 projectId: input.projectId,
848 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
849 const project = yield* projects.getById(input.projectId).pipe(
850 Effect.mapError(mapError(input, "resolve-project")),
851 Effect.flatMap(
852 Option.match({
853 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
854 onSome: Effect.succeed,
855 }),
856 ),
857 );
858 if (input.reuseExistingThread === true && input.threadId === undefined) {
859 return yield* mapError(
860 input,
861 "update-thread",
862 )("Reusing an existing thread requires a thread id.");
863 }
864
865 const launchReceipt = yield* readReceipt(input, input.commandId);
866 yield* threads.assertProviderInstanceEnabled({
867 projectId: input.projectId,
868 commandId: input.commandId,
869 instanceId: input.modelSelection.instanceId,
870 });
871 return yield* Effect.gen(function* () {
872 // Recover ids from accepted launch receipts before allocating; retries have no client id and new ids collide with receipts.
873 const reusableLaunchReceipt =
874 input.threadId === undefined &&
875 Option.isSome(launchReceipt) &&
876 launchReceipt.value.status === "accepted" &&
877 launchReceipt.value.commandType === "thread.create"
878 ? launchReceipt.value
879 : undefined;
880 const candidateThreadId =
881 input.threadId ??
882 reusableLaunchReceipt?.threadId ??
883 (yield* ids.allocate
884 .thread({ projectId: input.projectId })
885 .pipe(Effect.mapError(mapError(input, "create-thread"))));
886
887 if (reusableLaunchReceipt !== undefined) {
888 const shell = yield* threads
889 .getThreadShell(candidateThreadId)
890 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
891 if (shell === null) {
892 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
893 }
894 if (shell.projectId !== input.projectId) {
895 return yield* mapError(
896 input,
897 "resolve-project",
898 candidateThreadId,
899 )("Project identity changed.");
900 }
901 }
902
903 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
904 yield* validateReusableThread(input, candidateThreadId);
905 }
906
907 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
908 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
909 ? Option.match(
910 yield* managedFolders
911 .folderForThread({
912 projectId: input.projectId,
913 threadId: candidateThreadId,
914 text: input.initialMessage?.text ?? input.title,
915 })
916 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
917 {
918 onNone: () => input.workspaceStrategy,
919 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
920 },
921 )
922 : input.workspaceStrategy;
923 const initialBranch = workspaceStrategy.branch ?? null;
924 const initialWorktreePath =
925 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
926 const claimDispatch =
927 input.reuseExistingThread === true
928 ? threads.dispatch({
929 type: "thread.metadata.update",
930 commandId: input.commandId,
931 threadId: candidateThreadId,
932 expectedEmpty: true,
933 })
934 : threads.dispatch({
935 type: "thread.create",
936 commandId: input.commandId,
937 threadId: candidateThreadId,
938 projectId: input.projectId,
939 title: input.title,
940 modelSelection: input.modelSelection,
941 runtimeMode: input.runtimeMode,
942 interactionMode: input.interactionMode,
943 branch: initialBranch,
944 worktreePath: initialWorktreePath,
945 ...(input.importedNativeThread === undefined
946 ? {}
947 : { importedNativeThread: input.importedNativeThread }),
948 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
949 ...(input.delegatedFrom === undefined
950 ? {}
951 : { delegatedFrom: input.delegatedFrom }),
952 createdBy: input.createdBy,
953 creationSource: input.creationSource,
954 });
955 const claimed = yield* claimDispatch.pipe(
956 Effect.mapError(
957 mapError(
958 input,
959 input.reuseExistingThread === true ? "update-thread" : "create-thread",
960 candidateThreadId,
961 ),
962 ),
963 );
964 const threadId =
965 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
966 .threadId ?? candidateThreadId;
967 if (project.id !== input.projectId) {
968 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
969 }
970 let runId: RunId | null = null;
971 let messageSequence: number | undefined;
972 let messageWasAlreadyAccepted = false;
973 if (input.initialMessage !== undefined) {
974 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
975 const messageReceipt = yield* readReceipt(input, messageCommandId);
976 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
977 const messageId =
978 input.initialMessage.messageId ??
979 (yield* ids.allocate
980 .message({ threadId, ordinal: 1 })
981 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
982 const dispatched = yield* threads
983 .dispatch({
984 type: "message.dispatch",
985 commandId: messageCommandId,
986 threadId,
987 messageId,
988 text: input.initialMessage.text,
989 ...(input.initialMessage.scheduledTaskId === undefined
990 ? {}
991 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
992 ...(input.initialMessage.senderThreadId === undefined
993 ? {}
994 : { senderThreadId: input.initialMessage.senderThreadId }),
995 attachments: input.initialMessage.attachments,
996 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
997 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
998 modelSelection: input.modelSelection,
999 dispatchMode: { type: "defer_start", workspaceStrategy },
1000 createdBy: input.createdBy,
1001 creationSource: input.creationSource,
1002 })
1003 .pipe(
1004 // An agent's launch can land on a thread that a replay, or a concurrent
1005 // launch with the same key, created with broader modes. The orchestrator
1006 // refuses the message under the thread's lock; the user's own clients
1007 // launch into their own drafts, whatever modes those hold.
1008 input.createdBy === "agent"
1009 ? Effect.provideService(DispatchModeLimit, {
1010 runtimeMode: input.runtimeMode,
1011 interactionMode: input.interactionMode,
1012 })
1013 : (effect) => effect,
1014 Effect.mapError(mapError(input, "dispatch-message", threadId)),
1015 );
1016 // A concurrent retry can read no receipt and still replay the dispatch.
1017 messageWasAlreadyAccepted ||= dispatched.replayed === true;
1018 messageSequence = dispatched.sequence;
1019 const runCreated = dispatched.storedEvents.find(
1020 (stored) => stored.event.type === "run.created",
1021 );
1022 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
1023 if (runId === null) {
1024 return yield* mapError(
1025 input,
1026 "dispatch-message",
1027 threadId,
1028 )("Initial message was accepted without a durable run.");
1029 }
1030 }
1031
1032 const projection = yield* threads
1033 .getThreadProjection(threadId)
1034 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1035 const runIsPreparing =
1036 runId !== null &&
1037 projection.runs.some((run) => run.id === runId && run.status === "preparing");
1038 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
1039 const boundWorktreePath = projection.thread.worktreePath;
1040 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1041 Option.isSome(launchReceipt) &&
1042 workspaceStrategy.type === "root" &&
1043 boundWorktreePath !== null
1044 ? {
1045 type: "existing_worktree",
1046 worktreePath: boundWorktreePath,
1047 branch: workspaceStrategy.branch,
1048 }
1049 : workspaceStrategy;
1050 if (shouldSchedule) {
1051 const ownsPreparation = yield* reservePreparation(input.commandId);
1052 if (ownsPreparation) {
1053 yield* Effect.gen(function* () {
1054 const preparationStillRequired =
1055 runId === null
1056 ? true
1057 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1058 Effect.map((current) =>
1059 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1060 ),
1061 Effect.mapError(mapError(input, "update-thread", threadId)),
1062 );
1063 if (preparationStillRequired) {
1064 yield* schedulePreparation(
1065 { ...input, workspaceStrategy: preparationStrategy },
1066 threadId,
1067 runId,
1068 );
1069 } else {
1070 yield* releasePreparation(input.commandId);
1071 }
1072 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1073 }
1074 }
1075
1076 return {
1077 threadId,
1078 projection,
1079 // An attempt that failed after claiming the thread recorded nothing, so
1080 // only a repeat of the final write counts as resumed.
1081 resumed:
1082 input.initialMessage === undefined
1083 ? Option.isSome(launchReceipt) || claimed.replayed === true
1084 : messageWasAlreadyAccepted,
1085 ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1086 };
1087 });
1088 },
1089 );
1090
1091 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1092 "ThreadLaunchService.prepareRun",
1093 )(function* (input) {
1094 const scheduled = yield* Effect.gen(function* () {
1095 const { thread, runs } = yield* threads.getThreadRecords(input.threadId, ["runs"], {
1096 runIds: [input.runId],
1097 });
1098 const run = runs.find((candidate) => candidate.id === input.runId);
1099 const workspacePreparation = run?.workspacePreparation;
1100 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1101 if (!(yield* reservePreparation(input.commandId))) return;
1102 yield* scheduleRunPreparation(input, thread, run, workspacePreparation).pipe(
1103 Effect.onError(() => releasePreparation(input.commandId)),
1104 );
1105 }).pipe(Effect.exit);
1106 if (Exit.isFailure(scheduled)) {
1107 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1108 }
1109 });
1110
1111 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1112 "ThreadLaunchService.retryPreparation",
1113 )(function* (input) {
1114 const dispatched = yield* threads.dispatch({
1115 type: "prepared-run.retry",
1116 commandId: input.commandId,
1117 threadId: input.threadId,
1118 runId: input.runId,
1119 });
1120 yield* prepareRun(input);
1121 return dispatched;
1122 });
1123
1124 const scheduleRunPreparation = Effect.fn("ThreadLaunchService.scheduleRunPreparation")(function* (
1125 input: ThreadLaunchPreparationInput,
1126 thread: OrchestrationV2ThreadProjection["thread"],
1127 run: OrchestrationV2ThreadProjection["runs"][number],
1128 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1129 ) {
1130 const { messages } = yield* threads.getThreadRecords(input.threadId, ["messages"], {
1131 messageIds: [run.userMessageId],
1132 });
1133 const message = messages.find((candidate) => candidate.id === run.userMessageId);
1134 const reuse =
1135 workspacePreparation.type === "worktree" &&
1136 thread.worktreePath !== null &&
1137 thread.branch !== null
1138 ? {
1139 strategy: {
1140 type: "existing_worktree" as const,
1141 worktreePath: thread.worktreePath,
1142 branch: thread.branch,
1143 },
1144 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1145 }
1146 : null;
1147 return yield* schedulePreparation(
1148 {
1149 commandId: input.commandId,
1150 projectId: thread.projectId,
1151 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1152 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1153 ...(message === undefined
1154 ? {}
1155 : {
1156 initialMessage: {
1157 text: message.text,
1158 attachments: message.attachments,
1159 ...(message.context ? { context: message.context } : {}),
1160 },
1161 }),
1162 },
1163 input.threadId,
1164 run.id,
1165 );
1166 });
1167
1168 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1169});
1170
1171export const layer = Layer.effect(ThreadLaunchService, make);