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

ThreadLaunchService.ts

625 lines22.7 KB

1import {
2 CommandId,
3 type ChatAttachment,
4 type MessageId,
5 type ModelSelection,
6 type OrchestrationV2Actor,
7 type OrchestrationV2CreationSource,
8 type OrchestrationV2ProviderThreadNativeMetadata,
9 type OrchestrationV2ThreadProjection,
10 type ProviderDriverKind,
11 type ProviderInteractionMode,
12 ProjectId,
13 type RunId,
14 type RuntimeMode,
15 type ScheduledTaskId,
16 ThreadId,
17} from "@t3tools/contracts";
18import * as Cause from "effect/Cause";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Scope from "effect/Scope";
27import { buildTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
28​
29import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
30import * as GitWorkflow from "../git/GitWorkflowService.ts";
31import * as ProjectService from "../project/ProjectService.ts";
32import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as TextGeneration from "../textGeneration/TextGeneration.ts";
36import * as CommandReceiptStore from "./CommandReceiptStore.ts";
37import * as IdAllocator from "./IdAllocator.ts";
38import { makeProviderFailure } from "./ProviderFailure.ts";
39import { randomUuidV4 } from "./RandomUuid.ts";
40import * as ThreadManagement from "./ThreadManagementService.ts";
41​
42export type ThreadLaunchWorkspaceStrategy =
43 | { readonly type: "root"; readonly branch?: string | undefined }
44 | {
45 readonly type: "existing_worktree";
46 readonly worktreePath: string;
47 readonly branch?: string | undefined;
48 }
49 | {
50 readonly type: "worktree";
51 readonly baseRef: string;
52 readonly branch?: string | undefined;
53 readonly startFromOrigin?: boolean | undefined;
54 };
55​
56export interface ThreadLaunchInitialMessage {
57 readonly messageId?: MessageId;
58 readonly scheduledTaskId?: ScheduledTaskId;
59 readonly text: string;
60 readonly attachments: ReadonlyArray<ChatAttachment>;
62​
63export interface ThreadLaunchInput {
64 readonly commandId: CommandId;
65 readonly threadId?: ThreadId;
66 readonly reuseExistingThread?: boolean;
67 readonly projectId: ProjectId;
68 readonly title: string;
69 readonly generateTitle?: boolean;
70 readonly modelSelection: ModelSelection;
71 readonly runtimeMode: RuntimeMode;
72 readonly interactionMode: ProviderInteractionMode;
73 readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
74 readonly initialMessage?: ThreadLaunchInitialMessage;
75 readonly importedNativeThread?: {
76 readonly ref: {
77 readonly driver: ProviderDriverKind;
78 readonly nativeId: string;
79 readonly strength: "strong";
80 };
81 readonly metadata?: OrchestrationV2ProviderThreadNativeMetadata;
82 };
83 readonly createdBy: OrchestrationV2Actor;
84 readonly creationSource: OrchestrationV2CreationSource;
86​
87export interface ThreadLaunchResult {
88 readonly threadId: ThreadId;
89 readonly projection: OrchestrationV2ThreadProjection;
90 readonly resumed: boolean;
92​
93export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
94 "ThreadLaunchError",
95 {
96 operation: Schema.Literals([
97 "resolve-project",
98 "read-receipt",
99 "generate-metadata",
100 "provision-worktree",
101 "run-setup-script",
102 "create-thread",
103 "update-thread",
104 "dispatch-message",
105 "release-run",
106 "fail-run",
107 ]),
108 commandId: CommandId,
109 projectId: ProjectId,
110 threadId: Schema.optional(ThreadId),
111 cause: Schema.Defect(),
112 },
113) {
114 override get message(): string {
115 return `Thread launch ${this.commandId} failed during ${this.operation}.`;
116 }
118​
119export class ThreadLaunchService extends Context.Service<
120 ThreadLaunchService,
121 {
122 readonly launch: (
123 input: ThreadLaunchInput,
124 ) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
125 }
126>()("t3/orchestration-v2/ThreadLaunchService") {}
127​
128const isThreadLaunchError = Schema.is(ThreadLaunchError);
129​
130function failureDetail(error: unknown): string {
131 if (isThreadLaunchError(error)) {
132 const cause = error.cause;
133 const detail = cause instanceof Error ? cause.message : String(cause);
134 return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`;
135 }
136 return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`;
138​
139const make = Effect.gen(function* () {
140 const projects = yield* ProjectService.ProjectService;
141 const git = yield* GitWorkflow.GitWorkflowService;
142 const checkpointStore = yield* CheckpointStore.CheckpointStore;
143 const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
144 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
145 const serverSettings = yield* ServerSettings.ServerSettingsService;
146 const textGeneration = yield* TextGeneration.TextGeneration;
147 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
148 const ids = yield* IdAllocator.IdAllocatorV2;
149 const threads = yield* ThreadManagement.ThreadManagementService;
150 const preparationScope = yield* Scope.make("sequential");
151 const scheduledLaunches = yield* Ref.make<ReadonlySet<CommandId>>(new Set());
152 yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void));
153​
154 const mapError =
155 (input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
156 (cause: unknown) =>
157 new ThreadLaunchError({
158 operation,
159 commandId: input.commandId,
160 projectId: input.projectId,
161 ...(threadId === undefined ? {} : { threadId }),
162 cause,
163 });
164​
165 const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) =>
166 receipts
167 .getByCommandId(commandId)
168 .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId)));
169​
170 const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* (
171 input: ThreadLaunchInput,
172 threadId: ThreadId,
173 ) {
174 const projection = yield* threads
175 .getThreadProjection(threadId)
176 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
177 if (
178 projection.thread.projectId !== input.projectId ||
179 projection.thread.archivedAt !== null ||
180 projection.thread.deletedAt !== null ||
181 projection.messages.length > 0 ||
182 projection.runs.length > 0
183 ) {
184 return yield* mapError(
185 input,
186 "update-thread",
187 threadId,
188 )("Only an empty active thread in the target project can change workspace during launch.");
189 }
190 });
191​
192 const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
193 input: ThreadLaunchInput,
194 threadId: ThreadId,
195 runId: RunId | null,
196 ) {
197 const project = yield* projects.getById(input.projectId).pipe(
198 Effect.mapError(mapError(input, "resolve-project", threadId)),
199 Effect.flatMap(
200 Option.match({
201 onNone: () =>
202 Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")),
203 onSome: Effect.succeed,
204 }),
205 ),
206 );
207​
208 const initialMessage = input.initialMessage;
209 const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
210 Effect.gen(function* () {
211 const settings = yield* serverSettings.getSettings;
212 const modelSelection =
213 settings.sourceControlWriterModelSelection === null
214 ? settings.textGenerationModelSelection
215 : ServerSettings.resolveSourceControlWriterModelSelection(
216 settings,
217 yield* providerRegistry.getProviders,
218 );
219 return yield* textGeneration
220 .generateBranchName({
221 cwd,
222 message: message.text,
223 attachments: message.attachments,
224 modelSelection,
225 })
226 .pipe(Effect.map((result) => result.branch));
227 });
228​
229 // The server owns worktree naming: without an explicit branch, provision
230 // under a temporary `t3code/<hash>` name so the worktree never waits on
231 // name generation, then rename in the background below.
232 const requestedBranch = input.workspaceStrategy.branch;
233 let branch: string | null;
234 if (input.workspaceStrategy.type === "worktree" && requestedBranch === undefined) {
235 const uuid = yield* randomUuidV4;
236 branch = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
237 } else {
238 branch = requestedBranch ?? null;
239 }
240 let worktreePath =
241 input.workspaceStrategy.type === "existing_worktree"
242 ? input.workspaceStrategy.worktreePath
243 : null;
244 if (input.workspaceStrategy.type === "worktree") {
245 if (runId !== null) {
246 yield* threads
247 .dispatch({
248 type: "prepared-run.progress",
249 commandId: CommandId.make(`${input.commandId}:progress:worktree`),
250 threadId,
251 runId,
252 phase: "worktree",
253 })
254 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
255 }
256 let startRef = input.workspaceStrategy.baseRef;
257 // "Start from origin" is a stored default; repos without the requested
258 // remote branch fall back to the local base branch.
259 const startFromOrigin =
260 input.workspaceStrategy.startFromOrigin === true &&
261 (yield* git
262 .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
263 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
264 if (startFromOrigin) {
265 yield* git
266 .fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
267 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
268 const remoteBaseExists = yield* git
269 .remoteBranchExists({
270 cwd: project.workspaceRoot,
271 refName: input.workspaceStrategy.baseRef,
272 remoteName: "origin",
273 })
274 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
275 if (remoteBaseExists) {
276 startRef = yield* git
277 .resolveRemoteTrackingCommit({
278 cwd: project.workspaceRoot,
279 refName: input.workspaceStrategy.baseRef,
280 fallbackRemoteName: "origin",
281 })
282 .pipe(
283 Effect.map((resolved) => resolved.commitSha),
284 Effect.mapError(mapError(input, "provision-worktree", threadId)),
285 );
286 }
287 }
288 const worktree = yield* git
289 .createWorktree({
290 cwd: project.workspaceRoot,
291 refName: startRef,
292 newRefName: branch!,
293 baseRefName: input.workspaceStrategy.baseRef,
294 path: null,
295 })
296 .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
297 worktreePath = worktree.worktree.path;
298 branch = worktree.worktree.refName;
299 }
300​
301 yield* threads
302 .dispatch({
303 type: "thread.metadata.update",
304 commandId: CommandId.make(`${input.commandId}:workspace`),
305 threadId,
306 branch,
307 worktreePath,
308 })
309 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
310​
311 // Rename temporary branches (server-invented above, or sent by clients
312 // that name worktrees themselves) in the background so generation latency
313 // never delays provisioning or the provider turn. The temporary name
314 // simply sticks if generation or the rename fails.
315 if (
316 worktreePath !== null &&
317 branch !== null &&
318 initialMessage !== undefined &&
319 isTemporaryWorktreeBranch(branch)
320 ) {
321 const oldBranch = branch;
322 const worktreeCwd = worktreePath;
323 yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe(
324 Effect.flatMap((newBranch) => git.renameBranch({ cwd: worktreeCwd, oldBranch, newBranch })),
325 Effect.flatMap((renamed) =>
326 threads.dispatch({
327 type: "thread.metadata.update",
328 commandId: CommandId.make(`${input.commandId}:branch-rename`),
329 threadId,
330 branch: renamed.branch,
331 worktreePath: worktreeCwd,
332 }),
333 ),
334 Effect.catchCause((cause) =>
335 Effect.logWarning("Thread worktree branch rename failed", {
336 commandId: input.commandId,
337 threadId,
338 oldBranch,
339 cause,
340 }),
341 ),
342 Effect.forkIn(preparationScope),
343 );
344 }
345​
346 const cwd = worktreePath ?? project.workspaceRoot;
347 // Warm the checkpoint object store while the provider session starts, so
348 // the first blocking baseline capture (measured ~10s cold on a large
349 // fresh worktree) reuses the hashed blobs instead of paying that on the
350 // prompt critical path. Best effort in the background.
351 yield* checkpointStore.warmCheckpoint({ cwd }).pipe(
352 Effect.catchCause((cause) =>
353 Effect.logDebug("Thread launch checkpoint warm-up failed", {
354 commandId: input.commandId,
355 threadId,
356 cause,
357 }),
358 ),
359 Effect.forkIn(preparationScope),
360 );
361 if (runId !== null) {
362 yield* threads
363 .dispatch({
364 type: "prepared-run.progress",
365 commandId: CommandId.make(`${input.commandId}:progress:setup`),
366 threadId,
367 runId,
368 phase: "setup",
369 })
370 .pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
371 }
372 yield* setupScripts
373 .runForThread({
374 threadId,
375 projectId: input.projectId,
376 projectCwd: project.workspaceRoot,
377 worktreePath: cwd,
378 project: {
379 id: project.id,
380 workspaceRoot: project.workspaceRoot,
381 scripts: project.scripts,
382 },
383 })
384 .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId)));
385​
386 if (runId !== null) {
387 yield* threads
388 .dispatch({
389 type: "prepared-run.release",
390 commandId: CommandId.make(`${input.commandId}:release`),
391 threadId,
392 runId,
393 })
394 .pipe(Effect.mapError(mapError(input, "release-run", threadId)));
395 }
396 });
397​
398 const failPreparedRun = (
399 input: ThreadLaunchInput,
400 threadId: ThreadId,
401 runId: RunId | null,
402 cause: unknown,
403 ) =>
404 runId === null
405 ? Effect.logWarning("Thread workspace preparation failed", {
406 commandId: input.commandId,
407 threadId,
408 cause,
409 })
410 : threads
411 .dispatch({
412 type: "prepared-run.fail",
413 commandId: CommandId.make(`${input.commandId}:fail`),
414 threadId,
415 runId,
416 failure: makeProviderFailure({
417 cause,
418 message: failureDetail(cause),
419 class: "validation_error",
420 retryable: false,
421 }),
422 })
423 .pipe(
424 Effect.mapError(mapError(input, "fail-run", threadId)),
425 Effect.catchCause((persistCause) =>
426 Effect.logWarning("Failed to persist thread workspace preparation failure", {
427 commandId: input.commandId,
428 threadId,
429 cause,
430 persistCause,
431 }),
432 ),
433 );
434​
435 const reservePreparation = (commandId: CommandId) =>
436 Ref.modify(scheduledLaunches, (scheduled) => {
437 if (scheduled.has(commandId)) return [false, scheduled] as const;
438 const next = new Set(scheduled);
439 next.add(commandId);
440 return [true, next] as const;
441 });
442​
443 const releasePreparation = (commandId: CommandId) =>
444 Ref.update(scheduledLaunches, (scheduled) => {
445 const next = new Set(scheduled);
446 next.delete(commandId);
447 return next;
448 });
449​
450 const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* (
451 input: ThreadLaunchInput,
452 threadId: ThreadId,
453 runId: RunId | null,
454 ) {
455 yield* prepareInBackground(input, threadId, runId).pipe(
456 Effect.catchCause((cause) =>
457 Cause.hasInterruptsOnly(cause)
458 ? Effect.void
459 : failPreparedRun(input, threadId, runId, Cause.squash(cause)),
460 ),
461 Effect.ensuring(releasePreparation(input.commandId)),
462 Effect.forkIn(preparationScope),
463 );
464 });
465​
466 const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")(
467 function* (input) {
468 const project = yield* projects.getById(input.projectId).pipe(
469 Effect.mapError(mapError(input, "resolve-project")),
470 Effect.flatMap(
471 Option.match({
472 onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
473 onSome: Effect.succeed,
474 }),
475 ),
476 );
477 if (input.reuseExistingThread === true && input.threadId === undefined) {
478 return yield* mapError(
479 input,
480 "update-thread",
481 )("Reusing an existing thread requires a thread id.");
482 }
483​
484 const launchReceipt = yield* readReceipt(input, input.commandId);
485 return yield* Effect.gen(function* () {
486 const candidateThreadId =
487 input.threadId ??
488 (yield* ids.allocate
489 .thread({ projectId: input.projectId })
490 .pipe(Effect.mapError(mapError(input, "create-thread"))));
491​
492 if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) {
493 yield* validateReusableThread(input, candidateThreadId);
494 }
495​
496 const initialBranch = input.workspaceStrategy.branch ?? null;
497 const initialWorktreePath =
498 input.workspaceStrategy.type === "existing_worktree"
499 ? input.workspaceStrategy.worktreePath
500 : null;
501 const claimDispatch =
502 input.reuseExistingThread === true
503 ? threads.dispatch({
504 type: "thread.metadata.update",
505 commandId: input.commandId,
506 threadId: candidateThreadId,
507 expectedEmpty: true,
508 })
509 : threads.dispatch({
510 type: "thread.create",
511 commandId: input.commandId,
512 threadId: candidateThreadId,
513 projectId: input.projectId,
514 title: input.title,
515 modelSelection: input.modelSelection,
516 runtimeMode: input.runtimeMode,
517 interactionMode: input.interactionMode,
518 branch: initialBranch,
519 worktreePath: initialWorktreePath,
520 ...(input.importedNativeThread === undefined
521 ? {}
522 : { importedNativeThread: input.importedNativeThread }),
523 createdBy: input.createdBy,
524 creationSource: input.creationSource,
525 });
526 const claimed = yield* claimDispatch.pipe(
527 Effect.mapError(
528 mapError(
529 input,
530 input.reuseExistingThread === true ? "update-thread" : "create-thread",
531 candidateThreadId,
532 ),
533 ),
534 );
535 const threadId =
536 claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event
537 .threadId ?? candidateThreadId;
538 if (project.id !== input.projectId) {
539 return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
540 }
541​
542 let runId: RunId | null = null;
543 let messageWasAlreadyAccepted = false;
544 if (input.initialMessage !== undefined) {
545 const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
546 const messageReceipt = yield* readReceipt(input, messageCommandId);
547 messageWasAlreadyAccepted = Option.isSome(messageReceipt);
548 const messageId =
549 input.initialMessage.messageId ??
550 (yield* ids.allocate
551 .message({ threadId, ordinal: 1 })
552 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
553 const dispatched = yield* threads
554 .dispatch({
555 type: "message.dispatch",
556 commandId: messageCommandId,
557 threadId,
558 messageId,
559 text: input.initialMessage.text,
560 ...(input.initialMessage.scheduledTaskId === undefined
561 ? {}
562 : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
563 attachments: input.initialMessage.attachments,
564 ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
565 modelSelection: input.modelSelection,
566 dispatchMode: { type: "defer_start" },
567 createdBy: input.createdBy,
568 creationSource: input.creationSource,
569 })
570 .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
571 const runCreated = dispatched.storedEvents.find(
572 (stored) => stored.event.type === "run.created",
573 );
574 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
575 if (runId === null) {
576 return yield* mapError(
577 input,
578 "dispatch-message",
579 threadId,
580 )("Initial message was accepted without a durable run.");
581 }
582 }
583​
584 const projection = yield* threads
585 .getThreadProjection(threadId)
586 .pipe(Effect.mapError(mapError(input, "create-thread", threadId)));
587 const runIsPreparing =
588 runId !== null &&
589 projection.runs.some((run) => run.id === runId && run.status === "preparing");
590 const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing;
591 if (shouldSchedule) {
592 const ownsPreparation = yield* reservePreparation(input.commandId);
593 if (ownsPreparation) {
594 yield* Effect.gen(function* () {
595 const preparationStillRequired =
596 runId === null
597 ? true
598 : yield* threads.getThreadProjection(threadId).pipe(
599 Effect.map((current) =>
600 current.runs.some((run) => run.id === runId && run.status === "preparing"),
601 ),
602 Effect.mapError(mapError(input, "update-thread", threadId)),
603 );
604 if (preparationStillRequired) {
605 yield* schedulePreparation(input, threadId, runId);
606 } else {
607 yield* releasePreparation(input.commandId);
608 }
609 }).pipe(Effect.onError(() => releasePreparation(input.commandId)));
610 }
611 }
612​
613 return {
614 threadId,
615 projection,
616 resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
617 };
618 });
619 },
620 );
621​
622 return ThreadLaunchService.of({ launch });
623});
624​
625export const layer = Layer.effect(ThreadLaunchService, make);