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

ThreadLaunchService.ts

807 lines30.2 KB

1import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
2import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
3import * as TerminalManager from "../terminal/Manager.ts";
4import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
5import {
6 CommandId,
7 type ChatAttachment,
8 type MessageId,
9 type ModelSelection,
10 type OrchestrationV2Actor,
11 type OrchestrationV2CreationSource,
12 type OrchestrationV2ProviderThreadNativeMetadata,
13 type OrchestrationV2ThreadProjection,
14 type ProviderDriverKind,
15 type ProviderInteractionMode,
16 ProjectId,
17 type RunId,
18 type RuntimeMode,
19 type ScheduledTaskId,
20 ThreadId,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Exit from "effect/Exit";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Scope from "effect/Scope";
31import { buildTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
32​
33import * as GitWorkflow from "../git/GitWorkflowService.ts";
34import * as ProjectService from "../project/ProjectService.ts";
35import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
36import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import * as TextGeneration from "../textGeneration/TextGeneration.ts";
39import * as CommandReceiptStore from "./CommandReceiptStore.ts";
40import * as IdAllocator from "./IdAllocator.ts";
41import { makeProviderFailure } from "./ProviderFailure.ts";
42import { randomUuidV4 } from "./RandomUuid.ts";
43import * as ThreadManagement from "./ThreadManagementService.ts";
44​
45export type ThreadLaunchWorkspaceStrategy =
46 | { readonly type: "root"; readonly branch?: string | undefined }
47 | {
48 readonly type: "existing_worktree";
49 readonly worktreePath: string;
50 readonly branch?: string | undefined;
51 }
52 | {
53 readonly type: "worktree";
54 readonly baseRef: string;
55 readonly branch?: string | undefined;
56 readonly startFromOrigin?: boolean | undefined;
57 };
58​
59export interface ThreadLaunchInitialMessage {
60 readonly messageId?: MessageId;
61 readonly scheduledTaskId?: ScheduledTaskId;
62 readonly senderThreadId?: ThreadId;
63 readonly text: string;
64 readonly attachments: ReadonlyArray<ChatAttachment>;
65 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
67​
68export interface ThreadLaunchInput {
69 readonly commandId: CommandId;
70 readonly threadId?: ThreadId;
71 readonly reuseExistingThread?: boolean;
72 readonly projectId: ProjectId;
73 readonly title: string;
74 readonly generateTitle?: boolean;
75 readonly modelSelection: ModelSelection;
76 readonly runtimeMode: RuntimeMode;
77 readonly interactionMode: ProviderInteractionMode;
78 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
79 readonly initialMessage?: ThreadLaunchInitialMessage;
80 readonly importedNativeThread?: {
81 readonly ref: {
82 readonly driver: ProviderDriverKind;
83 readonly nativeId: string;
84 readonly strength: "strong";
85 };
86 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
87 };
88 readonly createdBy: OrchestrationV2Actor;
89 readonly creationSource: OrchestrationV2CreationSource;
91​
92export interface ThreadLaunchResult {
93 readonly threadId: ThreadId;
94 readonly projection: OrchestrationV2ThreadProjection;
95 readonly resumed: boolean;
97​
98export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
99 "ThreadLaunchError",
100 {
101 operation: Schema.Literals([
102 "resolve-project",
103 "read-receipt",
104 "generate-metadata",
105 "provision-worktree",
106 "run-setup-script",
107 "create-thread",
108 "update-thread",
109 "dispatch-message",
110 "release-run",
111 "fail-run",
112 ]),
113 commandId: CommandId,
114 projectId: ProjectId,
115 threadId: Schema.optional(ThreadId),
116 cause: Schema.Defect(),
117 },
118) {
119 override get message(): string {
120 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
121 }
123​
124export class ThreadLaunchService extends Context.Service<
125 ThreadLaunchService,
126 {
127 readonly launch: (
128 input: ThreadLaunchInput,
129 ) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
130 }
131>()("t3/orchestration-v2/ThreadLaunchService") {}
132​
133const isThreadLaunchError = Schema.is(ThreadLaunchError);
134​
135function failureDetail(error: unknown): string {
136 if (isThreadLaunchError(error)) {
137 const cause = error.cause;
138 const detail = cause instanceof Error ? cause.message : String(cause);
139 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
140 }
141 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
143​
144const make = Effect.gen(function* () {
145 const projects = yield* ProjectService.ProjectService;
146 const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
147 const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
148 const terminals = yield* TerminalManager.TerminalManager;
149 const git = yield* GitWorkflow.GitWorkflowService;
150 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
151 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
152 const serverSettings = yield* ServerSettings.ServerSettingsService;
153 const textGeneration = yield* TextGeneration.TextGeneration;
154 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
155 const ids = yield* IdAllocator.IdAllocatorV2;
156 const threads = yield* ThreadManagement.ThreadManagementService;
157 const preparationScope = yield* Scope.make("sequential");
158 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
159 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
160​
161 const mapError =
162 (input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
163 (cause: unknown) =>
164 new ThreadLaunchError({
165 operation,
166 commandId: input.commandId,
167 projectId: input.projectId,
168 ...(threadId === undefined ? {} : { threadId }),
169 cause,
170 });
171​
172 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
173 receipts
174 .getByCommandId(commandId)
175 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
176​
177 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
178 input: ThreadLaunchInput,
179 threadId: ThreadId,
180 ) {
181 const projection = yield* threads
182 .getThreadRecords(threadId, ["runs"])
183 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
184 if (
185 projection.thread.projectId !== input.projectId ||
186 projection.thread.archivedAt !== null ||
187 projection.thread.deletedAt !== null ||
188 (yield* threads
189 .getMessageCount(threadId)
190 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)))) > 0 ||
191 projection.runs.length > 0
192 ) {
193 return yield* mapError(
194 input,
195 "update-thread",
196 threadId,
197 )("Only an empty active thread in the target project can change workspace during launch.");
198 }
199 });
200​
201 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
202 input: ThreadLaunchInput,
203 threadId: ThreadId,
204 runId: RunId | null,
205 ) {
206 const project = yield* projects.getById(input.projectId).pipe(
207 Effect.mapError(mapError(input, "resolve-project", threadId)),
208 Effect.flatMap(
209 Option.match({
210 onNone: () =>
211 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
212 onSome: Effect.succeed,
213 }),
214 ),
215 );
216​
217 const tracked = input.workspaceStrategy.type === "worktree";
218 let createdWorktreePath: string | null = null;
219 let setupTerminalId: string | null = null;
220 if (tracked) {
221 yield* setupTracker.begin({
222 threadId,
223 branch: input.workspaceStrategy.branch ?? null,
224 baseRef: input.workspaceStrategy.baseRef,
225 stages: ["fetch", "checkout", "setup-script", "agent"],
226 fiber: yield* Effect.fiber,
227 });
228 }
229 yield* Effect.gen(function* () {
230 const initialMessage = input.initialMessage;
231 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
232 Effect.gen(function* () {
233 const settings = resolveProjectSettings(
234 yield* serverSettings.getSettings,
235 input.projectId,
236 ).settings;
237 const modelSelection =
238 settings.sourceControlWriterModelSelection === null
239 ? settings.textGenerationModelSelection
240 : ServerSettings.resolveSourceControlWriterModelSelection(
241 settings,
242 yield* providerRegistry.getProviders,
243 );
244 return yield* textGeneration
245 .generateBranchName({
246 naming: {
247 mode: settings.branchNamingMode,
248 prefix: settings.branchNamePrefix,
249 instructions: settings.branchNameInstructions,
250 },
251 cwd,
252 message: message.text,
253 attachments: message.attachments,
254 ...(message.context ? { context: message.context } : {}),
255 modelSelection,
256 })
257 .pipe(
258 Effect.map((result) => ({
259 branch: result.branch,
260 exactName: settings.branchNamingMode === "custom",
261 })),
262 );
263 });
264​
265 // The server owns worktree naming: without an explicit branch, provision
266 // under a temporary `t3code/<hash>` name so the worktree never waits on
267 // name generation, then rename in the background below.
268 const requestedBranch = input.workspaceStrategy.branch;
269 let branch: string | null;
270 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
271 const uuid = yield* randomUuidV4;
272 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
273 } else {
274 branch = requestedBranch ?? null;
275 }
276 let worktreePath =
277 input.workspaceStrategy.type === "existing_worktree"
278 ? input.workspaceStrategy.worktreePath
279 : null;
280 if (input.workspaceStrategy.type === "worktree") {
281 if (runId !== null) {
282 yield* threads
283 .dispatch({
284 type: "prepared-run.progress",
285 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
286 threadId,
287 runId,
288 phase: "worktree",
289 })
290 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
291 }
292 let startRef = input.workspaceStrategy.baseRef;
293 // "Start from origin" is a stored default; repos without the requested
294 // remote branch fall back to the local base branch.
295 const startFromOrigin =
296 input.workspaceStrategy.startFromOrigin === true &&
297 (yield* git
298 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
299 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
300 yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped");
301 if (startFromOrigin) {
302 yield* git
303 .fetchRemote({
304 cwd: project.workspaceRoot,
305 remoteName: "origin",
306 refName: input.workspaceStrategy.baseRef,
307 })
308 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
309 const remoteBaseExists = yield* git
310 .remoteBranchExists({
311 cwd: project.workspaceRoot,
312 refName: input.workspaceStrategy.baseRef,
313 remoteName: "origin",
314 })
315 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
316 if (remoteBaseExists) {
317 startRef = yield* git
318 .resolveRemoteTrackingCommit({
319 cwd: project.workspaceRoot,
320 refName: input.workspaceStrategy.baseRef,
321 fallbackRemoteName: "origin",
322 })
323 .pipe(
324 Effect.map((resolved) => resolved.commitSha),
325 Effect.mapError(mapError(input, "provision-worktree", threadId)),
326 );
327 }
328 }
329 if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done");
330 yield* setupTracker.stageStatus(threadId, "checkout", "running");
331 const worktree = yield* git
332 .createWorktree(
333 {
334 cwd: project.workspaceRoot,
335 refName: startRef,
336 newRefName: branch!,
337 baseRefName: input.workspaceStrategy.baseRef,
338 path: null,
339 },
340 {
341 progress: {
342 onWorktreeClaimed: (path) =>
343 Effect.sync(() => {
344 createdWorktreePath = path;
345 }),
346 onCheckoutProgress: (progress) =>
347 setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
348 },
349 },
350 )
351 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
352 worktreePath = worktree.worktree.path;
353 branch = worktree.worktree.refName;
354 createdWorktreePath = worktreePath;
355 yield* setupTracker.update(threadId, (snapshot) => ({ ...snapshot, worktreePath, branch }));
356 yield* setupTracker.stageStatus(threadId, "checkout", "done");
357 }
358​
359 yield* threads
360 .dispatch({
361 type: "thread.metadata.update",
362 commandId: CommandId.make(`${input.commandId}:workspace`),
363 threadId,
364 branch,
365 worktreePath,
366 })
367 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
368​
369 // Rename temporary branches (server-invented above, or sent by clients
370 // that name worktrees themselves) in the background so generation latency
371 // never delays provisioning or the provider turn. The temporary name
372 // simply sticks if generation or the rename fails.
373 if (
374 worktreePath !== null &&
375 branch !== null &&
376 initialMessage !== undefined &&
377 isTemporaryWorktreeBranch(branch)
378 ) {
379 const oldBranch = branch;
380 const worktreeCwd = worktreePath;
381 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
382 Effect.flatMap(({ branch: newBranch, exactName }) =>
383 git.renameBranch({
384 cwd: worktreeCwd,
385 oldBranch,
386 newBranch,
387 ...(exactName ? { exactName: true } : {}),
388 }),
389 ),
390 Effect.flatMap((renamed) =>
391 threads.dispatch({
392 type: "thread.metadata.update",
393 commandId: CommandId.make(`${input.commandId}:branch-rename`),
394 threadId,
395 branch: renamed.branch,
396 worktreePath: worktreeCwd,
397 }),
398 ),
399 Effect.catchCause((cause) =>
400 Effect.logWarning("Thread worktree branch rename failed", {
401 commandId: input.commandId,
402 threadId,
403 oldBranch,
404 cause,
405 }),
406 ),
407 Effect.forkIn(preparationScope),
408 );
409 }
410​
411 const cwd = worktreePath ?? project.workspaceRoot;
412 if (runId !== null) {
413 yield* threads
414 .dispatch({
415 type: "prepared-run.progress",
416 commandId: CommandId.make(`${input.commandId}:progress:setup`),
417 threadId,
418 runId,
419 phase: "setup",
420 })
421 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
422 }
423 yield* setupTracker.stageStatus(threadId, "setup-script", "running");
424 const setup = yield* setupScripts
425 .runForThread({
426 threadId,
427 projectId: input.projectId,
428 projectCwd: project.workspaceRoot,
429 worktreePath: cwd,
430 ...(tracked
431 ? {
432 observeCompletion: {
433 onOutputLine: (line: string) =>
434 setupTracker.appendTail(threadId, "setup-script", line),
435 },
436 }
437 : {}),
438 project: {
439 id: project.id,
440 workspaceRoot: project.workspaceRoot,
441 scripts: project.scripts,
442 },
443 })
444 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
445​
446 let awaitAsyncSetup = Effect.void;
447 if (setup.status === "started") {
448 setupTerminalId = setup.terminalId;
449 yield* setupTracker.update(threadId, (snapshot) => ({
450 ...snapshot,
451 setupScript: {
452 name: setup.scriptName,
453 command: setup.scriptCommand,
454 terminalId: setup.terminalId,
455 },
456 }));
457 if (setup.completion) {
458 const awaitCompletion = Effect.gen(function* () {
459 const completion = yield* setup.completion!;
460 yield* setupTracker.stage(threadId, "setup-script", {
461 status: completion.exitCode === 0 ? "done" : "failed",
462 detail: `exited with ${completion.exitCode ?? "no exit code"}`,
463 });
464 if (completion.exitCode !== 0 && !setup.async)
465 return yield* mapError(
466 input,
467 "run-setup-script",
468 threadId,
469 )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`);
470 });
471 if (setup.async) {
472 awaitAsyncSetup = awaitCompletion.pipe(
473 Effect.catchCause((cause) =>
474 setupTracker.stage(threadId, "setup-script", {
475 status: "failed",
476 detail: failureDetail(Cause.squash(cause)),
477 }),
478 ),
479 );
480 } else {
481 yield* awaitCompletion;
482 }
483 } else {
484 yield* setupTracker.stageStatus(threadId, "setup-script", "done");
485 }
486 } else {
487 yield* setupTracker.stageStatus(threadId, "setup-script", "skipped");
488 }
489 yield* setupTracker.markUncancellable(threadId);
490 yield* setupTracker.stageStatus(threadId, "agent", "running");
491 if (runId !== null) {
492 yield* threads
493 .dispatch({
494 type: "prepared-run.release",
495 commandId: CommandId.make(`${input.commandId}:release`),
496 threadId,
497 runId,
498 })
499 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
500 }
501 yield* setupTracker.stageStatus(threadId, "agent", "done");
502 yield* awaitAsyncSetup;
503 yield* setupTracker.finish(threadId, "done");
504 }).pipe(
505 Effect.onError((cause) =>
506 Effect.gen(function* () {
507 const cancelled = Cause.hasInterruptsOnly(cause);
508 yield* setupTracker.finish(
509 threadId,
510 cancelled ? "cancelled" : "failed",
511 cancelled ? null : failureDetail(Cause.squash(cause)),
512 );
513 if (cancelled && tracked && createdWorktreePath) {
514 if (setupTerminalId)
515 yield* terminals
516 .close({ threadId, terminalId: setupTerminalId, deleteHistory: true })
517 .pipe(Effect.ignore);
518 yield* git
519 .removeWorktree({
520 cwd: project.workspaceRoot,
521 path: createdWorktreePath,
522 force: true,
523 })
524 .pipe(Effect.ignore);
525 yield* threads
526 .dispatch({
527 type: "thread.metadata.update",
528 commandId: CommandId.make(`${input.commandId}:cancel-workspace`),
529 threadId,
530 worktreePath: null,
531 branch: null,
532 })
533 .pipe(Effect.ignore);
534 }
535 }),
536 ),
537 );
538 });
539​
540 const failPreparedRun = (
541 input: ThreadLaunchInput,
542 threadId: ThreadId,
543 runId: RunId | null,
544 cause: unknown,
545 ) =>
546 runId === null
547 ? Effect.logWarning("Thread workspace preparation failed", {
548 commandId: input.commandId,
549 threadId,
550 cause,
551 })
552 : threads
553 .dispatch({
554 type: "prepared-run.fail",
555 commandId: CommandId.make(`${input.commandId}:fail`),
556 threadId,
557 runId,
558 failure: makeProviderFailure({
559 cause,
560 message: failureDetail(cause),
561 class: "validation_error",
562 retryable: false,
563 }),
564 })
565 .pipe(
566 Effect.mapError(mapError(input, "fail-run", threadId)),
567 Effect.catchCause((persistCause) =>
568 Effect.logWarning("Failed to persist thread workspace preparation failure", {
569 commandId: input.commandId,
570 threadId,
571 cause,
572 persistCause,
573 }),
574 ),
575 );
576​
577 const reservePreparation = (commandId: CommandId) =>
578 Ref.modify(scheduledLaunches, (scheduled) => {
579 if (scheduled.has(commandId)) return [false, scheduled] as const;
580 const next = new Set(scheduled);
581 next.add(commandId);
582 return [true, next] as const;
583 });
584​
585 const releasePreparation = (commandId: CommandId) =>
586 Ref.update(scheduledLaunches, (scheduled) => {
587 const next = new Set(scheduled);
588 next.delete(commandId);
589 return next;
590 });
591​
592 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
593 input: ThreadLaunchInput,
594 threadId: ThreadId,
595 runId: RunId | null,
596 ) {
597 yield* prepareInBackground(input, threadId, runId).pipe(
598 Effect.onError((cause) =>
599 failPreparedRun(
600 input,
601 threadId,
602 runId,
603 Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause),
604 ),
605 ),
606 Effect.ignoreCause,
607 Effect.ensuring(releasePreparation(input.commandId)),
608 Effect.forkIn(preparationScope),
609 );
610 });
611​
612 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
613 function* (input) {
614 yield* ProjectCloneTracker.rejectCommandsDuringClone(cloneTracker, {
615 type: "thread.create",
616 projectId: input.projectId,
617 }).pipe(Effect.mapError(mapError(input, "resolve-project")));
618 const project = yield* projects.getById(input.projectId).pipe(
619 Effect.mapError(mapError(input, "resolve-project")),
620 Effect.flatMap(
621 Option.match({
622 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
623 onSome: Effect.succeed,
624 }),
625 ),
626 );
627 if (input.reuseExistingThread === true && input.threadId === undefined) {
628 return yield* mapError(
629 input,
630 "update-thread",
631 )("Reusing an existing thread requires a thread id.");
632 }
633​
634 const launchReceipt = yield* readReceipt(input, input.commandId);
635 return yield* Effect.gen(function* () {
636 // A retried launch has no client-supplied id to replay against, so
637 // recover the thread id its accepted create was recorded under before
638 // allocating another one; a fresh id would only collide with the
639 // recorded receipt.
640 const reusableLaunchReceipt =
641 input.threadId === undefined &&
642 Option.isSome(launchReceipt) &&
643 launchReceipt.value.status === "accepted" &&
644 launchReceipt.value.commandType === "thread.create"
645 ? launchReceipt.value
646 : undefined;
647 const candidateThreadId =
648 input.threadId ??
649 reusableLaunchReceipt?.threadId ??
650 (yield* ids.allocate
651 .thread({ projectId: input.projectId })
652 .pipe(Effect.mapError(mapError(input, "create-thread"))));
653​
654 if (reusableLaunchReceipt !== undefined) {
655 const shell = yield* threads
656 .getThreadShell(candidateThreadId)
657 .pipe(Effect.mapError(mapError(input, "create-thread", candidateThreadId)));
658 if (shell === null) {
659 return yield* mapError(input, "create-thread", candidateThreadId)("Thread not found.");
660 }
661 if (shell.projectId !== input.projectId) {
662 return yield* mapError(
663 input,
664 "resolve-project",
665 candidateThreadId,
666 )("Project identity changed.");
667 }
668 }
669​
670 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
671 yield* validateReusableThread(input, candidateThreadId);
672 }
673​
674 const initialBranch = input.workspaceStrategy.branch ?? null;
675 const initialWorktreePath =
676 input.workspaceStrategy.type === "existing_worktree"
677 ? input.workspaceStrategy.worktreePath
678 : null;
679 const claimDispatch =
680 input.reuseExistingThread === true
681 ? threads.dispatch({
682 type: "thread.metadata.update",
683 commandId: input.commandId,
684 threadId: candidateThreadId,
685 expectedEmpty: true,
686 })
687 : threads.dispatch({
688 type: "thread.create",
689 commandId: input.commandId,
690 threadId: candidateThreadId,
691 projectId: input.projectId,
692 title: input.title,
693 modelSelection: input.modelSelection,
694 runtimeMode: input.runtimeMode,
695 interactionMode: input.interactionMode,
696 branch: initialBranch,
697 worktreePath: initialWorktreePath,
698 ...(input.importedNativeThread === undefined
699 ? {}
700 : { importedNativeThread: input.importedNativeThread }),
701 createdBy: input.createdBy,
702 creationSource: input.creationSource,
703 });
704 const claimed = yield* claimDispatch.pipe(
705 Effect.mapError(
706 mapError(
707 input,
708 input.reuseExistingThread === true ? "update-thread" : "create-thread",
709 candidateThreadId,
710 ),
711 ),
712 );
713 const threadId =
714 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
715 .threadId ?? candidateThreadId;
716 if (project.id !== input.projectId) {
717 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
718 }
719​
720 let runId: RunId | null = null;
721 let messageWasAlreadyAccepted = false;
722 if (input.initialMessage !== undefined) {
723 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
724 const messageReceipt = yield* readReceipt(input, messageCommandId);
725 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
726 const messageId =
727 input.initialMessage.messageId ??
728 (yield* ids.allocate
729 .message({ threadId, ordinal: 1 })
730 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
731 const dispatched = yield* threads
732 .dispatch({
733 type: "message.dispatch",
734 commandId: messageCommandId,
735 threadId,
736 messageId,
737 text: input.initialMessage.text,
738 ...(input.initialMessage.scheduledTaskId === undefined
739 ? {}
740 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
741 ...(input.initialMessage.senderThreadId === undefined
742 ? {}
743 : { senderThreadId: input.initialMessage.senderThreadId }),
744 attachments: input.initialMessage.attachments,
745 ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
746 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
747 modelSelection: input.modelSelection,
748 dispatchMode: { type: "defer_start" },
749 createdBy: input.createdBy,
750 creationSource: input.creationSource,
751 })
752 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
753 const runCreated = dispatched.storedEvents.find(
754 (stored) => stored.event.type === "run.created",
755 );
756 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
757 if (runId === null) {
758 return yield* mapError(
759 input,
760 "dispatch-message",
761 threadId,
762 )("Initial message was accepted without a durable run.");
763 }
764 }
765​
766 const projection = yield* threads
767 .getThreadProjection(threadId)
768 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
769 const runIsPreparing =
770 runId !== null &&
771 projection.runs.some((run) => run.id === runId && run.status === "preparing");
772 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
773 if (shouldSchedule) {
774 const ownsPreparation = yield* reservePreparation(input.commandId);
775 if (ownsPreparation) {
776 yield* Effect.gen(function* () {
777 const preparationStillRequired =
778 runId === null
779 ? true
780 : yield* threads.getThreadRecords(threadId, ["runs"], { runIds: [runId] }).pipe(
781 Effect.map((current) =>
782 current.runs.some((run) => run.id === runId && run.status === "preparing"),
783 ),
784 Effect.mapError(mapError(input, "update-thread", threadId)),
785 );
786 if (preparationStillRequired) {
787 yield* schedulePreparation(input, threadId, runId);
788 } else {
789 yield* releasePreparation(input.commandId);
790 }
791 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
792 }
793 }
794​
795 return {
796 threadId,
797 projection,
798 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
799 };
800 });
801 },
802 );
803​
804 return ThreadLaunchService.of({ launch });
805});
806​
807export const layer = Layer.effect(ThreadLaunchService, make);