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

ThreadLaunchService.ts

1,140 lines44.1 KB

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