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

ThreadLaunchService.ts

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