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

ThreadLaunchService.ts

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