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

ThreadLaunchService.ts

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