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

ThreadBootstrap.ts

387 lines14.4 KB

1import {
2 CommandId,
3 EventId,
4 type OrchestrationClientOrigin,
5 type OrchestrationCommand,
6 OrchestrationDispatchCommandError,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Crypto from "effect/Crypto";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Schema from "effect/Schema";
15​
16import * as GitWorkflowService from "../../git/GitWorkflowService.ts";
17import * as ProjectSetupScriptRunner from "../../project/ProjectSetupScriptRunner.ts";
18import * as VcsStatusBroadcaster from "../../vcs/VcsStatusBroadcaster.ts";
19import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
20import {
21 ThreadBootstrap,
22 type ThreadBootstrapShape,
23 type ThreadTurnStartCommand,
24} from "../Services/ThreadBootstrap.ts";
25import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
26​
27const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
28​
29const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
30​
31function unexpectedCompatibilityError(error: never): never {
32 throw new Error(`Unhandled compatibility error: ${String(error)}`);
34​
35/** Preserve the setup runner's broader pre-refactor message normalization. */
36function legacySetupFailureDescription(cause: unknown): string {
37 if (
38 typeof cause === "object" &&
39 cause !== null &&
40 "message" in cause &&
41 typeof cause.message === "string"
42 ) {
43 return cause.message;
44 }
45 return String(cause);
47​
48function projectSetupScriptCompatibilityDetail(
49 error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError,
50): string {
51 switch (error._tag) {
52 case "ProjectSetupScriptOperationError":
53 return legacySetupFailureDescription(error.cause);
54 case "ProjectSetupScriptProjectNotFoundError":
55 return "Project was not found for setup script execution.";
56 default:
57 return unexpectedCompatibilityError(error);
58 }
60​
61const make = Effect.gen(function* () {
62 const crypto = yield* Crypto.Crypto;
63 const orchestrationEngine = yield* OrchestrationEngineService;
64 const threadDeletionReactor = yield* ThreadDeletionReactor;
65 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
66 const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
67 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
68​
69 const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
70 isOrchestrationDispatchCommandError(cause)
71 ? cause
72 : new OrchestrationDispatchCommandError({
73 message: cause instanceof Error ? cause.message : fallbackMessage,
74 cause,
75 });
76 const randomUUID = crypto.randomUUIDv4.pipe(
77 Effect.mapError((cause) =>
78 toDispatchCommandError(cause, "Failed to generate orchestration command identifier."),
79 ),
80 );
81 const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
82 const serverCommandId = (tag: string) =>
83 randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
84​
85 const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
86 const error = Cause.squash(cause);
87 return isOrchestrationDispatchCommandError(error)
88 ? error
89 : new OrchestrationDispatchCommandError({
90 message:
91 error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
92 cause,
93 });
94 };
95​
96 const refreshGitStatus = (cwd: string) =>
97 vcsStatusBroadcaster
98 .refreshStatus(cwd)
99 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
100​
101 const dispatchTurnStart: ThreadBootstrapShape["dispatchTurnStart"] = (
102 command: ThreadTurnStartCommand,
103 options?: { readonly origin?: OrchestrationClientOrigin },
104 ) =>
105 Effect.gen(function* () {
106 const origin = options?.origin;
107 const dispatch: OrchestrationEngineService["Service"]["dispatch"] = (
108 subcommand: OrchestrationCommand,
109 ) => orchestrationEngine.dispatch(subcommand, origin ? { origin } : undefined);
110​
111 const appendSetupScriptActivity = (input: {
112 readonly threadId: ThreadId;
113 readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
114 readonly summary: string;
115 readonly createdAt: string;
116 readonly payload: Record<string, unknown>;
117 readonly tone: "info" | "error";
118 }) =>
119 Effect.all({
120 commandId: serverCommandId("setup-script-activity"),
121 activityId: serverEventId,
122 }).pipe(
123 Effect.flatMap(({ commandId, activityId }) =>
124 dispatch({
125 type: "thread.activity.append",
126 commandId,
127 threadId: input.threadId,
128 activity: {
129 id: activityId,
130 tone: input.tone,
131 kind: input.kind,
132 summary: input.summary,
133 payload: input.payload,
134 turnId: null,
135 createdAt: input.createdAt,
136 },
137 createdAt: input.createdAt,
138 }),
139 ),
140 );
141​
142 const bootstrap = command.bootstrap;
143 const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
144 let createdThread = false;
145 let targetProjectId = bootstrap?.createThread?.projectId;
146 let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
147 let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
148​
149 const cleanupCreatedThread = () =>
150 createdThread
151 ? serverCommandId("bootstrap-thread-delete").pipe(
152 Effect.flatMap((commandId) =>
153 dispatch({
154 type: "thread.delete",
155 commandId,
156 threadId: command.threadId,
157 }),
158 ),
159 Effect.as(true),
160 )
161 : Effect.succeed(false);
162​
163 const recordSetupScriptLaunchFailure = (input: {
164 readonly error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError;
165 readonly requestedAt: string;
166 readonly worktreePath: string;
167 }) => {
168 const detail = projectSetupScriptCompatibilityDetail(input.error);
169 return appendSetupScriptActivity({
170 threadId: command.threadId,
171 kind: "setup-script.failed",
172 summary: "Setup script failed to start",
173 createdAt: input.requestedAt,
174 payload: {
175 detail,
176 worktreePath: input.worktreePath,
177 },
178 tone: "error",
179 }).pipe(
180 Effect.ignoreCause({ log: false }),
181 Effect.flatMap(() =>
182 Effect.logWarning("bootstrap turn start failed to launch setup script", {
183 threadId: command.threadId,
184 worktreePath: input.worktreePath,
185 detail,
186 }),
187 ),
188 );
189 };
190​
191 const recordSetupScriptStarted = (input: {
192 readonly requestedAt: string;
193 readonly worktreePath: string;
194 readonly scriptId: string;
195 readonly scriptName: string;
196 readonly terminalId: string;
197 }) =>
198 Effect.gen(function* () {
199 const startedAt = yield* nowIso;
200 const payload = {
201 scriptId: input.scriptId,
202 scriptName: input.scriptName,
203 terminalId: input.terminalId,
204 worktreePath: input.worktreePath,
205 };
206 yield* Effect.all([
207 appendSetupScriptActivity({
208 threadId: command.threadId,
209 kind: "setup-script.requested",
210 summary: "Starting setup script",
211 createdAt: input.requestedAt,
212 payload,
213 tone: "info",
214 }),
215 appendSetupScriptActivity({
216 threadId: command.threadId,
217 kind: "setup-script.started",
218 summary: "Setup script started",
219 createdAt: startedAt,
220 payload,
221 tone: "info",
222 }),
223 ]).pipe(
224 Effect.asVoid,
225 Effect.catch((error) =>
226 Effect.logWarning(
227 "bootstrap turn start launched setup script but failed to record setup activity",
228 {
229 threadId: command.threadId,
230 worktreePath: input.worktreePath,
231 scriptId: input.scriptId,
232 terminalId: input.terminalId,
233 detail: error.message,
234 },
235 ),
236 ),
237 );
238 });
239​
240 const runSetupProgram = () =>
241 Effect.gen(function* () {
242 if (!bootstrap?.runSetupScript || !targetWorktreePath) {
243 return;
244 }
245 const worktreePath = targetWorktreePath;
246 const requestedAt = yield* nowIso;
247 yield* projectSetupScriptRunner
248 .runForThread({
249 threadId: command.threadId,
250 ...(targetProjectId ? { projectId: targetProjectId } : {}),
251 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
252 worktreePath,
253 })
254 .pipe(
255 Effect.matchEffect({
256 onFailure: (error) =>
257 recordSetupScriptLaunchFailure({
258 error,
259 requestedAt,
260 worktreePath,
261 }),
262 onSuccess: (setupResult) => {
263 if (setupResult.status !== "started") {
264 return Effect.void;
265 }
266 return recordSetupScriptStarted({
267 requestedAt,
268 worktreePath,
269 scriptId: setupResult.scriptId,
270 scriptName: setupResult.scriptName,
271 terminalId: setupResult.terminalId,
272 });
273 },
274 }),
275 );
276 });
277​
278 const bootstrapProgram = Effect.gen(function* () {
279 if (bootstrap?.createThread) {
280 const created = yield* dispatch({
281 type: "thread.create",
282 commandId: yield* serverCommandId("bootstrap-thread-create"),
283 threadId: command.threadId,
284 projectId: bootstrap.createThread.projectId,
285 title: bootstrap.createThread.title,
286 modelSelection: bootstrap.createThread.modelSelection,
287 runtimeMode: bootstrap.createThread.runtimeMode,
288 interactionMode: bootstrap.createThread.interactionMode,
289 branch: bootstrap.createThread.branch,
290 worktreePath: bootstrap.createThread.worktreePath,
291 createdAt: bootstrap.createThread.createdAt,
292 });
293 // The successful create is a fence in the engine command queue:
294 // every delete for the prior incarnation committed before it.
295 // Drain through that event before setup or turn start can own
296 // terminals and provider sessions under the reused thread id.
297 yield* threadDeletionReactor.drainThrough(created.sequence);
298 createdThread = true;
299 }
300​
301 if (bootstrap?.prepareWorktree) {
302 let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;
303 // "Start from origin" is a stored default; repos without the
304 // requested remote branch fall back to the local base branch.
305 const startFromOrigin =
306 bootstrap.prepareWorktree.startFromOrigin === true &&
307 (yield* gitWorkflow.remoteExists({
308 cwd: bootstrap.prepareWorktree.projectCwd,
309 remoteName: "origin",
310 }));
311 if (startFromOrigin) {
312 yield* gitWorkflow.fetchRemote({
313 cwd: bootstrap.prepareWorktree.projectCwd,
314 remoteName: "origin",
315 });
316 const remoteBaseExists = yield* gitWorkflow.remoteBranchExists({
317 cwd: bootstrap.prepareWorktree.projectCwd,
318 refName: bootstrap.prepareWorktree.baseBranch,
319 remoteName: "origin",
320 });
321 if (remoteBaseExists) {
322 const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({
323 cwd: bootstrap.prepareWorktree.projectCwd,
324 refName: bootstrap.prepareWorktree.baseBranch,
325 fallbackRemoteName: "origin",
326 });
327 worktreeBaseRef = resolvedRemoteBase.commitSha;
328 }
329 }
330 const worktree = yield* gitWorkflow.createWorktree({
331 cwd: bootstrap.prepareWorktree.projectCwd,
332 refName: worktreeBaseRef,
333 newRefName: bootstrap.prepareWorktree.branch,
334 baseRefName: bootstrap.prepareWorktree.baseBranch,
335 path: null,
336 });
337 targetWorktreePath = worktree.worktree.path;
338 yield* dispatch({
339 type: "thread.meta.update",
340 commandId: yield* serverCommandId("bootstrap-thread-meta-update"),
341 threadId: command.threadId,
342 branch: worktree.worktree.refName,
343 worktreePath: targetWorktreePath,
344 });
345 yield* refreshGitStatus(targetWorktreePath);
346 }
347​
348 yield* runSetupProgram();
349​
350 return yield* dispatch(finalTurnStartCommand);
351 });
352​
353 return yield* bootstrapProgram.pipe(
354 Effect.catchCause((cause) => {
355 const dispatchError = toBootstrapDispatchCommandCauseError(cause);
356 if (Cause.hasInterruptsOnly(cause)) {
357 return Effect.fail(dispatchError);
358 }
359 return Effect.uninterruptible(cleanupCreatedThread()).pipe(
360 Effect.matchCauseEffect({
361 onFailure: (cleanupCause) =>
362 Effect.logWarning("bootstrap thread cleanup failed", {
363 threadId: command.threadId,
364 detail: Cause.pretty(cleanupCause),
365 }).pipe(Effect.flatMap(() => Effect.fail(dispatchError))),
366 onSuccess: (threadDeleted) =>
367 Effect.fail(
368 threadDeleted
369 ? new OrchestrationDispatchCommandError({
370 message: dispatchError.message,
371 ...(dispatchError.cause !== undefined
372 ? { cause: dispatchError.cause }
373 : {}),
374 bootstrapThreadDisposition: "deleted",
375 })
376 : dispatchError,
377 ),
378 }),
379 );
380 }),
381 );
382 });
383​
384 return ThreadBootstrap.of({ dispatchTurnStart });
385});
386​
387export const ThreadBootstrapLive = Layer.effect(ThreadBootstrap, make);