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

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

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

Synced Nov 21, 03:37 UTC

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