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

ThreadLaunchService.ts

553 lines19.2 KB

1import {
2 CommandId,
3 type ChatAttachment,
4 type MessageId,
5 type ModelSelection,
6 type OrchestrationV2Actor,
7 type OrchestrationV2CreationSource,
8 type OrchestrationV2ThreadProjection,
9 type ProviderInteractionMode,
10 ProjectId,
11 type RunId,
12 type RuntimeMode,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Scope from "effect/Scope";
24​
25import * as GitWorkflow from "../git/GitWorkflowService.ts";
26import * as ProjectService from "../project/ProjectService.ts";
27import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
28import * as TextGeneration from "../textGeneration/TextGeneration.ts";
29import * as CommandReceiptStore from "./CommandReceiptStore.ts";
30import * as IdAllocator from "./IdAllocator.ts";
31import { makeProviderFailure } from "./ProviderFailure.ts";
32import * as ThreadManagement from "./ThreadManagementService.ts";
33​
34export type ThreadLaunchWorkspaceStrategy =
35 | { readonly type: "root"; readonly branch?: string | undefined }
36 | {
37 readonly type: "existing_worktree";
38 readonly worktreePath: string;
39 readonly branch?: string | undefined;
40 }
41 | {
42 readonly type: "worktree";
43 readonly baseRef: string;
44 readonly branch?: string | undefined;
45 readonly startFromOrigin?: boolean | undefined;
46 };
47​
48export interface ThreadLaunchInitialMessage {
49 readonly messageId?: MessageId;
50 readonly text: string;
51 readonly attachments: ReadonlyArray<ChatAttachment>;
53​
54export interface ThreadLaunchInput {
55 readonly commandId: CommandId;
56 readonly threadId?: ThreadId;
57 readonly reuseExistingThread?: boolean;
58 readonly projectId: ProjectId;
59 readonly title: string;
60 readonly modelSelection: ModelSelection;
61 readonly runtimeMode: RuntimeMode;
62 readonly interactionMode: ProviderInteractionMode;
63 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
64 readonly initialMessage?: ThreadLaunchInitialMessage;
65 readonly createdBy: OrchestrationV2Actor;
66 readonly creationSource: OrchestrationV2CreationSource;
68​
69export interface ThreadLaunchResult {
70 readonly threadId: ThreadId;
71 readonly projection: OrchestrationV2ThreadProjection;
72 readonly resumed: boolean;
74​
75export class ThreadLaunchError extends Schema.TaggedErrorClass<ThreadLaunchError>()(
76 "ThreadLaunchError",
77 {
78 operation: Schema.Literals([
79 "resolve-project",
80 "read-receipt",
81 "generate-metadata",
82 "provision-worktree",
83 "run-setup-script",
84 "create-thread",
85 "update-thread",
86 "dispatch-message",
87 "release-run",
88 "fail-run",
89 ]),
90 commandId: CommandId,
91 projectId: ProjectId,
92 threadId: Schema.optional(ThreadId),
93 cause: Schema.Defect(),
94 },
95) {
96 override get message(): string {
97 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
98 }
100​
101export class ThreadLaunchService extends Context.Service<
102 ThreadLaunchService,
103 {
104 readonly launch: (
105 input: ThreadLaunchInput,
106 ) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
107 }
108>()("t3/orchestration-v2/ThreadLaunchService") {}
109​
110const isThreadLaunchError = Schema.is(ThreadLaunchError);
111​
112function fallbackBranchName(threadId: ThreadId): string {
113 const suffix = String(threadId)
114 .split(":")
115 .at(-1)
116 ?.replace(/[^a-zA-Z0-9-]+/gu, "-")
117 .replace(/^-+|-+$/gu, "")
118 .slice(0, 16);
119 return `thread-${suffix || "new"}`;
121​
122function failureDetail(error: unknown): string {
123 if (isThreadLaunchError(error)) {
124 const cause = error.cause;
125 const detail = cause instanceof Error ? cause.message : String(cause);
126 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
127 }
128 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
130​
131export const make = Effect.gen(function* () {
132 const projects = yield* ProjectService.ProjectService;
133 const git = yield* GitWorkflow.GitWorkflowService;
134 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
135 const textGeneration = yield* TextGeneration.TextGeneration;
136 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
137 const ids = yield* IdAllocator.IdAllocatorV2;
138 const threads = yield* ThreadManagement.ThreadManagementService;
139 const preparationScope = yield* Scope.make("sequential");
140 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
141 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
142​
143 const mapError =
144 (input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
145 (cause: unknown) =>
146 new ThreadLaunchError({
147 operation,
148 commandId: input.commandId,
149 projectId: input.projectId,
150 ...(threadId === undefined ? {} : { threadId }),
151 cause,
152 });
153​
154 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
155 receipts
156 .getByCommandId(commandId)
157 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
158​
159 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
160 input: ThreadLaunchInput,
161 threadId: ThreadId,
162 ) {
163 const projection = yield* threads
164 .getThreadProjection(threadId)
165 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
166 if (
167 projection.thread.projectId !== input.projectId ||
168 projection.thread.archivedAt !== null ||
169 projection.thread.deletedAt !== null ||
170 projection.messages.length > 0 ||
171 projection.runs.length > 0
172 ) {
173 return yield* mapError(
174 input,
175 "update-thread",
176 threadId,
177 )("Only an empty active thread in the target project can change workspace during launch.");
178 }
179 });
180​
181 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
182 input: ThreadLaunchInput,
183 threadId: ThreadId,
184 runId: RunId | null,
185 ) {
186 const project = yield* projects.getById(input.projectId).pipe(
187 Effect.mapError(mapError(input, "resolve-project", threadId)),
188 Effect.flatMap(
189 Option.match({
190 onNone: () =>
191 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
192 onSome: Effect.succeed,
193 }),
194 ),
195 );
196​
197 if (input.title === "New thread" && input.initialMessage !== undefined) {
198 yield* textGeneration
199 .generateThreadTitle({
200 cwd: project.workspaceRoot,
201 message: input.initialMessage.text,
202 attachments: input.initialMessage.attachments,
203 modelSelection: input.modelSelection,
204 })
205 .pipe(
206 Effect.flatMap((result) =>
207 threads.dispatch({
208 type: "thread.metadata.update",
209 commandId: CommandId.make(`${input.commandId}:title`),
210 threadId,
211 title: result.title,
212 }),
213 ),
214 Effect.catchCause((cause) =>
215 Effect.logWarning("Thread title generation failed", {
216 commandId: input.commandId,
217 threadId,
218 cause,
219 }),
220 ),
221 Effect.forkIn(preparationScope),
222 );
223 }
224​
225 let branch =
226 input.workspaceStrategy.type === "worktree" &&
227 input.workspaceStrategy.branch === undefined &&
228 input.initialMessage !== undefined
229 ? yield* textGeneration
230 .generateBranchName({
231 cwd: project.workspaceRoot,
232 message: input.initialMessage.text,
233 attachments: input.initialMessage.attachments,
234 modelSelection: input.modelSelection,
235 })
236 .pipe(
237 Effect.map((result) => result.branch),
238 Effect.mapError(mapError(input, "generate-metadata", threadId)),
239 )
240 : (input.workspaceStrategy.branch ??
241 (input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null));
242 let worktreePath =
243 input.workspaceStrategy.type === "existing_worktree"
244 ? input.workspaceStrategy.worktreePath
245 : null;
246 if (input.workspaceStrategy.type === "worktree") {
247 if (runId !== null) {
248 yield* threads
249 .dispatch({
250 type: "prepared-run.progress",
251 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
252 threadId,
253 runId,
254 phase: "worktree",
255 })
256 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
257 }
258 let startRef = input.workspaceStrategy.baseRef;
259 if (input.workspaceStrategy.startFromOrigin === true) {
260 yield* git
261 .fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
262 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
263 startRef = yield* git
264 .resolveRemoteTrackingCommit({
265 cwd: project.workspaceRoot,
266 refName: input.workspaceStrategy.baseRef,
267 fallbackRemoteName: "origin",
268 })
269 .pipe(
270 Effect.map((resolved) => resolved.commitSha),
271 Effect.mapError(mapError(input, "provision-worktree", threadId)),
272 );
273 }
274 const worktree = yield* git
275 .createWorktree({
276 cwd: project.workspaceRoot,
277 refName: startRef,
278 newRefName: branch!,
279 baseRefName: input.workspaceStrategy.baseRef,
280 path: null,
281 })
282 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
283 worktreePath = worktree.worktree.path;
284 branch = worktree.worktree.refName;
285 }
286​
287 yield* threads
288 .dispatch({
289 type: "thread.metadata.update",
290 commandId: CommandId.make(`${input.commandId}:workspace`),
291 threadId,
292 branch,
293 worktreePath,
294 })
295 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
296​
297 const cwd = worktreePath ?? project.workspaceRoot;
298 if (runId !== null) {
299 yield* threads
300 .dispatch({
301 type: "prepared-run.progress",
302 commandId: CommandId.make(`${input.commandId}:progress:setup`),
303 threadId,
304 runId,
305 phase: "setup",
306 })
307 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
308 }
309 yield* setupScripts
310 .runForThread({
311 threadId,
312 projectId: input.projectId,
313 projectCwd: project.workspaceRoot,
314 worktreePath: cwd,
315 project: {
316 workspaceRoot: project.workspaceRoot,
317 scripts: project.scripts,
318 },
319 })
320 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
321​
322 if (runId !== null) {
323 yield* threads
324 .dispatch({
325 type: "prepared-run.release",
326 commandId: CommandId.make(`${input.commandId}:release`),
327 threadId,
328 runId,
329 })
330 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
331 }
332 });
333​
334 const failPreparedRun = (
335 input: ThreadLaunchInput,
336 threadId: ThreadId,
337 runId: RunId | null,
338 cause: unknown,
339 ) =>
340 runId === null
341 ? Effect.logWarning("Thread workspace preparation failed", {
342 commandId: input.commandId,
343 threadId,
344 cause,
345 })
346 : threads
347 .dispatch({
348 type: "prepared-run.fail",
349 commandId: CommandId.make(`${input.commandId}:fail`),
350 threadId,
351 runId,
352 failure: makeProviderFailure({
353 cause,
354 message: failureDetail(cause),
355 class: "validation_error",
356 retryable: false,
357 }),
358 })
359 .pipe(
360 Effect.mapError(mapError(input, "fail-run", threadId)),
361 Effect.catchCause((persistCause) =>
362 Effect.logWarning("Failed to persist thread workspace preparation failure", {
363 commandId: input.commandId,
364 threadId,
365 cause,
366 persistCause,
367 }),
368 ),
369 );
370​
371 const reservePreparation = (commandId: CommandId) =>
372 Ref.modify(scheduledLaunches, (scheduled) => {
373 if (scheduled.has(commandId)) return [false, scheduled] as const;
374 const next = new Set(scheduled);
375 next.add(commandId);
376 return [true, next] as const;
377 });
378​
379 const releasePreparation = (commandId: CommandId) =>
380 Ref.update(scheduledLaunches, (scheduled) => {
381 const next = new Set(scheduled);
382 next.delete(commandId);
383 return next;
384 });
385​
386 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
387 input: ThreadLaunchInput,
388 threadId: ThreadId,
389 runId: RunId | null,
390 ) {
391 yield* prepareInBackground(input, threadId, runId).pipe(
392 Effect.catchCause((cause) =>
393 Cause.hasInterruptsOnly(cause)
394 ? Effect.void
395 : failPreparedRun(input, threadId, runId, Cause.squash(cause)),
396 ),
397 Effect.ensuring(releasePreparation(input.commandId)),
398 Effect.forkIn(preparationScope),
399 );
400 });
401​
402 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
403 function* (input) {
404 const project = yield* projects.getById(input.projectId).pipe(
405 Effect.mapError(mapError(input, "resolve-project")),
406 Effect.flatMap(
407 Option.match({
408 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
409 onSome: Effect.succeed,
410 }),
411 ),
412 );
413 if (input.reuseExistingThread === true && input.threadId === undefined) {
414 return yield* mapError(
415 input,
416 "update-thread",
417 )("Reusing an existing thread requires a thread id.");
418 }
419​
420 const launchReceipt = yield* readReceipt(input, input.commandId);
421 return yield* Effect.gen(function* () {
422 const candidateThreadId =
423 input.threadId ??
424 (yield* ids.allocate
425 .thread({ projectId: input.projectId })
426 .pipe(Effect.mapError(mapError(input, "create-thread"))));
427​
428 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
429 yield* validateReusableThread(input, candidateThreadId);
430 }
431​
432 const initialBranch = input.workspaceStrategy.branch ?? null;
433 const initialWorktreePath =
434 input.workspaceStrategy.type === "existing_worktree"
435 ? input.workspaceStrategy.worktreePath
436 : null;
437 const claimDispatch =
438 input.reuseExistingThread === true
439 ? threads.dispatch({
440 type: "thread.metadata.update",
441 commandId: input.commandId,
442 threadId: candidateThreadId,
443 })
444 : threads.dispatch({
445 type: "thread.create",
446 commandId: input.commandId,
447 threadId: candidateThreadId,
448 projectId: input.projectId,
449 title: input.title,
450 modelSelection: input.modelSelection,
451 runtimeMode: input.runtimeMode,
452 interactionMode: input.interactionMode,
453 branch: initialBranch,
454 worktreePath: initialWorktreePath,
455 createdBy: input.createdBy,
456 creationSource: input.creationSource,
457 });
458 const claimed = yield* claimDispatch.pipe(
459 Effect.mapError(
460 mapError(
461 input,
462 input.reuseExistingThread === true ? "update-thread" : "create-thread",
463 candidateThreadId,
464 ),
465 ),
466 );
467 const threadId =
468 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
469 .threadId ?? candidateThreadId;
470 if (project.id !== input.projectId) {
471 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
472 }
473​
474 let runId: RunId | null = null;
475 let messageWasAlreadyAccepted = false;
476 if (input.initialMessage !== undefined) {
477 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
478 const messageReceipt = yield* readReceipt(input, messageCommandId);
479 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
480 const messageId =
481 input.initialMessage.messageId ??
482 (yield* ids.allocate
483 .message({ threadId, ordinal: 1 })
484 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
485 const dispatched = yield* threads
486 .dispatch({
487 type: "message.dispatch",
488 commandId: messageCommandId,
489 threadId,
490 messageId,
491 text: input.initialMessage.text,
492 attachments: input.initialMessage.attachments,
493 modelSelection: input.modelSelection,
494 dispatchMode: { type: "defer_start" },
495 createdBy: input.createdBy,
496 creationSource: input.creationSource,
497 })
498 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
499 const runCreated = dispatched.storedEvents.find(
500 (stored) => stored.event.type === "run.created",
501 );
502 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
503 if (runId === null) {
504 return yield* mapError(
505 input,
506 "dispatch-message",
507 threadId,
508 )("Initial message was accepted without a durable run.");
509 }
510 }
511​
512 const projection = yield* threads
513 .getThreadProjection(threadId)
514 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
515 const runIsPreparing =
516 runId !== null &&
517 projection.runs.some((run) => run.id === runId && run.status === "preparing");
518 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
519 if (shouldSchedule) {
520 const ownsPreparation = yield* reservePreparation(input.commandId);
521 if (ownsPreparation) {
522 yield* Effect.gen(function* () {
523 const preparationStillRequired =
524 runId === null
525 ? true
526 : yield* threads.getThreadProjection(threadId).pipe(
527 Effect.map((current) =>
528 current.runs.some((run) => run.id === runId && run.status === "preparing"),
529 ),
530 Effect.mapError(mapError(input, "update-thread", threadId)),
531 );
532 if (preparationStillRequired) {
533 yield* schedulePreparation(input, threadId, runId);
534 } else {
535 yield* releasePreparation(input.commandId);
536 }
537 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
538 }
539 }
540​
541 return {
542 threadId,
543 projection,
544 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
545 };
546 });
547 },
548 );
549​
550 return ThreadLaunchService.of({ launch });
551});
552​
553export const layer = Layer.effect(ThreadLaunchService, make);