Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadLaunchService.ts

1,429 lines56.1 KB

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