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

ThreadLaunchService.ts

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