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

ThreadLaunchService.ts

1,142 lines44.3 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({ worktreePath: worktreeCwd });
518 const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
519 (thread) => !visited.has(thread.id) && thread.branch === oldBranch,
520 );
521 if (sharing.length === 0) break;
522 for (const thread of sharing) {
523 visited.add(thread.id);
524 yield* threads
525 .dispatch({
526 type: "thread.metadata.update",
527 commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
528 threadId: thread.id,
529 branch: renamed.branch,
530 expectedBranch: oldBranch,
531 expectedWorktreePath: worktreeCwd,
532 })
533 .pipe(
534 Effect.catchCause((cause) =>
535 Effect.logWarning("Shared thread worktree branch update failed", {
536 threadId: thread.id,
537 cause,
538 }),
539 ),
540 );
541 }
542 }
543 }),
544 ),
545 Effect.catchCause((cause) =>
546 Effect.logWarning("Thread worktree branch rename failed", {
547 commandId: input.commandId,
548 threadId,
549 oldBranch,
550 cause,
551 }),
552 ),
553 Effect.forkIn(preparationScope),
554 );
555 }
556​
557 if (runId !== null && worktreePath !== null) {
558 yield* threads
559 .dispatch({
560 type: "prepared-run.progress",
561 commandId: CommandId.make(`${input.commandId}:progress:setup`),
562 threadId,
563 runId,
564 phase: "setup",
565 })
566 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
567 }
568 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
569 const setup =
570 worktreePath === null
571 ? ({ status: "no-script" } as const)
572 : yield* setupScripts
573 .runForThread({
574 threadId,
575 projectId: input.projectId,
576 projectCwd: project.workspaceRoot,
577 worktreePath,
578 ...(tracked
579 ? {
580 observeCompletion: {
581 onOutputLine: (line: string) =>
582 setupTracker.appendTail(threadId, "setup-script", line),
583 },
584 }
585 : {}),
586 project: {
587 id: project.id,
588 workspaceRoot: project.workspaceRoot,
589 scripts: project.scripts,
590 },
591 })
592 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
593​
594 let awaitAsyncSetup = Effect.void;
595 if (setup.status === "started") {
596 setupTerminalId = setup.terminalId;
597 yield* setupTracker.update(threadId, (snapshot) => ({
598 ...snapshot,
599 setupScript: {
600 name: setup.scriptName,
601 command: setup.scriptCommand,
602 terminalId: setup.terminalId,
603 },
604 }));
605 if (setup.completion) {
606 const awaitCompletion = Effect.gen(function* () {
607 const completion = yield* setup.completion!;
608 yield* setupTracker.stage(threadId, "setup-script", {
609 status: completion.exitCode === 0 ? "done" : "failed",
610 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
611 });
612 if (completion.exitCode !== 0 && !setup.async)
613 return yield* mapError(
614 input,
615 "run-setup-script",
616 threadId,
617 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
618 });
619 if (setup.async) {
620 awaitAsyncSetup = awaitCompletion.pipe(
621 Effect.catchCause((cause) =>
622 setupTracker.stage(threadId, "setup-script", {
623 status: "failed",
624 detail: failureDetail(Cause.squash(cause)),
625 }),
626 ),
627 );
628 } else {
629 yield* awaitCompletion;
630 }
631 } else {
632 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
633 }
634 } else {
635 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
636 }
637 yield* setupTracker.markUncancellable(threadId);
638 yield* setupTracker.stageStatus(threadId, "agent", "running");
639 if (runId !== null) {
640 yield* threads
641 .dispatch({
642 type: "prepared-run.release",
643 commandId: CommandId.make(`${input.commandId}:release`),
644 threadId,
645 runId,
646 })
647 .pipe(
648 Effect.mapError(mapError(input, "release-run", threadId)),
649 Effect.tap(() =>
650 Effect.sync(() => {
651 runReleased = true;
652 }),
653 ),
654 Effect.uninterruptible,
655 );
656 }
657 yield* setupTracker.stageStatus(threadId, "agent", "done");
658 yield* awaitAsyncSetup;
659 yield* setupTracker.finish(threadId, "done");
660 }).pipe(
661 Effect.onError((cause) =>
662 Effect.gen(function* () {
663 const cancelled = Cause.hasInterruptsOnly(cause);
664 yield* setupTracker.finish(
665 threadId,
666 cancelled ? "cancelled" : "failed",
667 cancelled ? null : failureDetail(Cause.squash(cause)),
668 );
669 if (cancelled && setupTerminalId)
670 yield* terminals
671 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
672 .pipe(Effect.ignore);
673 if (
674 tracked &&
675 createdWorktreePath &&
676 ((cancelled && !runReleased) || !workspaceRecorded)
677 ) {
678 if (branchRename !== null) yield* Fiber.interrupt(branchRename);
679 const removedPath = createdWorktreePath;
680 // Forget worktrees only after removal succeeds; failed removals must not reuse partially written checkouts.
681 yield* git
682 .removeWorktree({ cwd: project.workspaceRoot, path: removedPath, force: true })
683 .pipe(
684 Effect.andThen(
685 threads
686 .dispatch({
687 type: "thread.metadata.update",
688 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
689 threadId,
690 worktreePath: null,
691 branch: null,
692 })
693 .pipe(Effect.ignore),
694 ),
695 Effect.catchCause((removeCause) =>
696 Effect.logWarning("Failed to remove an abandoned thread worktree", {
697 commandId: input.commandId,
698 threadId,
699 path: removedPath,
700 cause: removeCause,
701 }),
702 ),
703 );
704 }
705 }),
706 ),
707 );
708 });
709​
710 const failPreparedRun = (
711 input: Pick<PreparationInput, "commandId">,
712 threadId: ThreadId,
713 runId: RunId | null,
714 cause: unknown,
715 ) =>
716 runId === null
717 ? Effect.logWarning("Thread workspace preparation failed", {
718 commandId: input.commandId,
719 threadId,
720 cause,
721 })
722 : threads
723 .dispatch({
724 type: "prepared-run.fail",
725 commandId: CommandId.make(`${input.commandId}:fail`),
726 threadId,
727 runId,
728 failure: makeProviderFailure({
729 cause,
730 message: failureDetail(cause),
731 class: "validation_error",
732 retryable: false,
733 }),
734 })
735 .pipe(
736 Effect.catchCause((persistCause) =>
737 Effect.logWarning("Failed to persist thread workspace preparation failure", {
738 commandId: input.commandId,
739 threadId,
740 cause,
741 persistCause,
742 }),
743 ),
744 );
745​
746 const reservePreparation = (commandId: CommandId) =>
747 Ref.modify(scheduledLaunches, (scheduled) => {
748 if (scheduled.has(commandId)) return [false, scheduled] as const;
749 const next = new Set(scheduled);
750 next.add(commandId);
751 return [true, next] as const;
752 });
753​
754 const releasePreparation = (commandId: CommandId) =>
755 Ref.update(scheduledLaunches, (scheduled) => {
756 const next = new Set(scheduled);
757 next.delete(commandId);
758 return next;
759 });
760​
761 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
762 input: PreparationInput,
763 threadId: ThreadId,
764 runId: RunId | null,
765 ) {
766 const preparation = Effect.gen(function* () {
767 const prepare = prepareInBackground(input, threadId, runId);
768 if (
769 runId === null ||
770 (input.workspaceStrategy.type !== "worktree" && input.reusedWorktree === undefined)
771 ) {
772 return yield* prepare;
773 }
774 const afterSequence = yield* threads.getThreadEventSequence(threadId);
775 const projection = yield* threads.getThreadRecords(threadId, ["runs"]);
776 if (projection.runs.find((run) => run.id === runId)?.status !== "preparing") return;
777 const interruption = threads
778 .streamStoredEventsFrom({ threadId, afterSequence, eventType: "run.updated" })
779 .pipe(
780 Stream.filter(
781 (stored) =>
782 stored.event.type === "run.updated" &&
783 stored.event.payload.id === runId &&
784 (stored.event.payload.status === "interrupted" ||
785 stored.event.payload.status === "cancelled"),
786 ),
787 Stream.runHead,
788 Effect.flatMap((event) => (Option.isSome(event) ? Effect.interrupt : Effect.never)),
789 );
790 yield* Effect.raceFirst(prepare, interruption);
791 });
792 yield* preparation.pipe(
793 Effect.onError((cause) =>
794 failPreparedRun(
795 input,
796 threadId,
797 runId,
798 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
799 ),
800 ),
801 Effect.ignoreCause,
802 Effect.ensuring(releasePreparation(input.commandId)),
803 Effect.forkIn(preparationScope),
804 );
805 });
806​
807 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
808 function* (request) {
809 // Scratch has no Git repository. Normalize before folder allocation so
810 // durable preparation and retries use the thread's own Scratch folder.
811 const input: ThreadLaunchInput =
812 request.workspaceStrategy.type === "worktree" &&
813 (yield* managedFolders.isScratchProject(request.projectId))
814 ? { ...request, workspaceStrategy: { type: "root" } }
815 : request;
816 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
817 type: "thread.create",
818 projectId: input.projectId,
819 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
820 const project = yield* projects.getById(input.projectId).pipe(
821 Effect.mapError(mapError(input, "resolve-project")),
822 Effect.flatMap(
823 Option.match({
824 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
825 onSome: Effect.succeed,
826 }),
827 ),
828 );
829 if (input.reuseExistingThread === true && input.threadId === undefined) {
830 return yield* mapError(
831 input,
832 "update-thread",
833 )("Reusing an existing thread requires a thread id.");
834 }
835​
836 const launchReceipt = yield* readReceipt(input, input.commandId);
837 yield* threads.assertProviderInstanceEnabled({
838 projectId: input.projectId,
839 commandId: input.commandId,
840 instanceId: input.modelSelection.instanceId,
841 });
842 return yield* Effect.gen(function* () {
843 // Recover ids from accepted launch receipts before allocating; retries have no client id and new ids collide with receipts.
844 const reusableLaunchReceipt =
845 input.threadId === undefined &&
846 Option.isSome(launchReceipt) &&
847 launchReceipt.value.status === "accepted" &&
848 launchReceipt.value.commandType === "thread.create"
849 ? launchReceipt.value
850 : undefined;
851 const candidateThreadId =
852 input.threadId ??
853 reusableLaunchReceipt?.threadId ??
854 (yield* ids.allocate
855 .thread({ projectId: input.projectId })
856 .pipe(Effect.mapError(mapError(input, "create-thread"))));
857​
858 if (reusableLaunchReceipt !== undefined) {
859 const shell = yield* threads
860 .getThreadShell(candidateThreadId)
861 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
862 if (shell === null) {
863 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
864 }
865 if (shell.projectId !== input.projectId) {
866 return yield* mapError(
867 input,
868 "resolve-project",
869 candidateThreadId,
870 )("Project identity changed.");
871 }
872 }
873​
874 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
875 yield* validateReusableThread(input, candidateThreadId);
876 }
877​
878 const workspaceStrategy: ThreadLaunchWorkspaceStrategy =
879 input.workspaceStrategy.type === "root" && Option.isNone(launchReceipt)
880 ? Option.match(
881 yield* managedFolders
882 .folderForThread({
883 projectId: input.projectId,
884 threadId: candidateThreadId,
885 text: input.initialMessage?.text ?? input.title,
886 })
887 .pipe(Effect.mapError(mapError(input, "provision-worktree", candidateThreadId))),
888 {
889 onNone: () => input.workspaceStrategy,
890 onSome: (worktreePath) => ({ type: "existing_worktree", worktreePath }),
891 },
892 )
893 : input.workspaceStrategy;
894 const initialBranch = workspaceStrategy.branch ?? null;
895 const initialWorktreePath =
896 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
897 const claimDispatch =
898 input.reuseExistingThread === true
899 ? threads.dispatch({
900 type: "thread.metadata.update",
901 commandId: input.commandId,
902 threadId: candidateThreadId,
903 expectedEmpty: true,
904 })
905 : threads.dispatch({
906 type: "thread.create",
907 commandId: input.commandId,
908 threadId: candidateThreadId,
909 projectId: input.projectId,
910 title: input.title,
911 modelSelection: input.modelSelection,
912 runtimeMode: input.runtimeMode,
913 interactionMode: input.interactionMode,
914 branch: initialBranch,
915 worktreePath: initialWorktreePath,
916 ...(input.importedNativeThread === undefined
917 ? {}
918 : { importedNativeThread: input.importedNativeThread }),
919 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
920 ...(input.delegatedFrom === undefined
921 ? {}
922 : { delegatedFrom: input.delegatedFrom }),
923 createdBy: input.createdBy,
924 creationSource: input.creationSource,
925 });
926 const claimed = yield* claimDispatch.pipe(
927 Effect.mapError(
928 mapError(
929 input,
930 input.reuseExistingThread === true ? "update-thread" : "create-thread",
931 candidateThreadId,
932 ),
933 ),
934 );
935 const threadId =
936 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
937 .threadId ?? candidateThreadId;
938 if (project.id !== input.projectId) {
939 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
940 }
941 let runId: RunId | null = null;
942 let messageSequence: number | undefined;
943 let messageWasAlreadyAccepted = false;
944 if (input.initialMessage !== undefined) {
945 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
946 const messageReceipt = yield* readReceipt(input, messageCommandId);
947 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
948 const messageId =
949 input.initialMessage.messageId ??
950 (yield* ids.allocate
951 .message({ threadId, ordinal: 1 })
952 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
953 const dispatched = yield* threads
954 .dispatch({
955 type: "message.dispatch",
956 commandId: messageCommandId,
957 threadId,
958 messageId,
959 text: input.initialMessage.text,
960 ...(input.initialMessage.scheduledTaskId === undefined
961 ? {}
962 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
963 ...(input.initialMessage.senderThreadId === undefined
964 ? {}
965 : { senderThreadId: input.initialMessage.senderThreadId }),
966 attachments: input.initialMessage.attachments,
967 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
968 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
969 modelSelection: input.modelSelection,
970 dispatchMode: { type: "defer_start", workspaceStrategy },
971 createdBy: input.createdBy,
972 creationSource: input.creationSource,
973 })
974 .pipe(
975 // An agent's launch can land on a thread that a replay, or a concurrent
976 // launch with the same key, created with broader modes. The orchestrator
977 // refuses the message under the thread's lock; the user's own clients
978 // launch into their own drafts, whatever modes those hold.
979 input.createdBy === "agent"
980 ? Effect.provideService(DispatchModeLimit, {
981 runtimeMode: input.runtimeMode,
982 interactionMode: input.interactionMode,
983 })
984 : (effect) => effect,
985 Effect.mapError(mapError(input, "dispatch-message", threadId)),
986 );
987 // A concurrent retry can read no receipt and still replay the dispatch.
988 messageWasAlreadyAccepted ||= dispatched.replayed === true;
989 messageSequence = dispatched.sequence;
990 const runCreated = dispatched.storedEvents.find(
991 (stored) => stored.event.type === "run.created",
992 );
993 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
994 if (runId === null) {
995 return yield* mapError(
996 input,
997 "dispatch-message",
998 threadId,
999 )("Initial message was accepted without a durable run.");
1002​
1003 const projection = yield* threads
1004 .getThreadProjection(threadId)
1005 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
1006 const runIsPreparing =
1007 runId !== null &&
1008 projection.runs.some((run) => run.id === runId && run.status === "preparing");
1009 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
1010 const boundWorktreePath = projection.thread.worktreePath;
1011 const preparationStrategy: ThreadLaunchWorkspaceStrategy =
1012 Option.isSome(launchReceipt) &&
1013 workspaceStrategy.type === "root" &&
1014 boundWorktreePath !== null
1015 ? {
1016 type: "existing_worktree",
1017 worktreePath: boundWorktreePath,
1018 branch: workspaceStrategy.branch,
1020 : workspaceStrategy;
1021 if (shouldSchedule) {
1022 const ownsPreparation = yield* reservePreparation(input.commandId);
1023 if (ownsPreparation) {
1024 yield* Effect.gen(function* () {
1025 const preparationStillRequired =
1026 runId === null
1027 ? true
1028 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
1029 Effect.map((current) =>
1030 current.runs.some((run) => run.id === runId && run.status === "preparing"),
1031 ),
1032 Effect.mapError(mapError(input, "update-thread", threadId)),
1033 );
1034 if (preparationStillRequired) {
1035 yield* schedulePreparation(
1036 { ...input, workspaceStrategy: preparationStrategy },
1037 threadId,
1038 runId,
1039 );
1040 } else {
1041 yield* releasePreparation(input.commandId);
1043 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
1046​
1047 return {
1048 threadId,
1049 projection,
1050 // An attempt that failed after claiming the thread recorded nothing, so
1051 // only a repeat of the final write counts as resumed.
1052 resumed:
1053 input.initialMessage === undefined
1054 ? Option.isSome(launchReceipt) || claimed.replayed === true
1055 : messageWasAlreadyAccepted,
1056 ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1057 };
1058 });
1059 },
1060 );
1061​
1062 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(
1063 "ThreadLaunchService.prepareRun",
1064 )(function* (input) {
1065 const scheduled = yield* Effect.gen(function* () {
1066 const { thread, runs } = yield* threads.getThreadRecords(input.threadId, ["runs"], {
1067 runIds: [input.runId],
1068 });
1069 const run = runs.find((candidate) => candidate.id === input.runId);
1070 const workspacePreparation = run?.workspacePreparation;
1071 if (run?.status !== "preparing" || workspacePreparation === undefined) return;
1072 if (!(yield* reservePreparation(input.commandId))) return;
1073 yield* scheduleRunPreparation(input, thread, run, workspacePreparation).pipe(
1074 Effect.onError(() => releasePreparation(input.commandId)),
1075 );
1076 }).pipe(Effect.exit);
1077 if (Exit.isFailure(scheduled)) {
1078 yield* failPreparedRun(input, input.threadId, input.runId, Cause.squash(scheduled.cause));
1080 });
1081​
1082 const retryPreparation: ThreadLaunchService["Service"]["retryPreparation"] = Effect.fn(
1083 "ThreadLaunchService.retryPreparation",
1084 )(function* (input) {
1085 const dispatched = yield* threads.dispatch({
1086 type: "prepared-run.retry",
1087 commandId: input.commandId,
1088 threadId: input.threadId,
1089 runId: input.runId,
1090 });
1091 yield* prepareRun(input);
1092 return dispatched;
1093 });
1094​
1095 const scheduleRunPreparation = Effect.fn("ThreadLaunchService.scheduleRunPreparation")(function* (
1096 input: ThreadLaunchPreparationInput,
1097 thread: OrchestrationV2ThreadProjection["thread"],
1098 run: OrchestrationV2ThreadProjection["runs"][number],
1099 workspacePreparation: ThreadLaunchWorkspaceStrategy,
1100 ) {
1101 const { messages } = yield* threads.getThreadRecords(input.threadId, ["messages"], {
1102 messageIds: [run.userMessageId],
1103 });
1104 const message = messages.find((candidate) => candidate.id === run.userMessageId);
1105 const reuse =
1106 workspacePreparation.type === "worktree" &&
1107 thread.worktreePath !== null &&
1108 thread.branch !== null
1109 ? {
1110 strategy: {
1111 type: "existing_worktree" as const,
1112 worktreePath: thread.worktreePath,
1113 branch: thread.branch,
1114 },
1115 reusedWorktree: { baseRef: workspacePreparation.baseRef },
1117 : null;
1118 return yield* schedulePreparation(
1120 commandId: input.commandId,
1121 projectId: thread.projectId,
1122 workspaceStrategy: reuse?.strategy ?? workspacePreparation,
1123 ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }),
1124 ...(message === undefined
1125 ? {}
1126 : {
1127 initialMessage: {
1128 text: message.text,
1129 attachments: message.attachments,
1130 ...(message.context ? { context: message.context } : {}),
1131 },
1132 }),
1133 },
1134 input.threadId,
1135 run.id,
1136 );
1137 });
1138​
1139 return ThreadLaunchService.of({ launch, checkWorktreeBase, retryPreparation, prepareRun });
1140});
1141​
1142export const layer = Layer.effect(ThreadLaunchService, make);