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

ThreadLaunchService.ts

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