Open History to see the last commit
1import { ProjectId, type ProjectScript } from "@t3tools/contracts";
2import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import {
4 projectScriptRuntimeEnv,
5 resolveProjectScripts,
6 setupProjectScript,
7} from "@t3tools/shared/projectScripts";
8import * as NodeCrypto from "node:crypto";
9
10import * as Clock from "effect/Clock";
11import * as Context from "effect/Context";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17
18import * as ServerSettings from "../serverSettings.ts";
19import * as TerminalManager from "../terminal/Manager.ts";
20import * as ProjectService from "./ProjectService.ts";
21
22export interface ProjectSetupScriptRunnerResultNoScript {
23 readonly status: "no-script";
24}
25
26export interface ProjectSetupScriptRunnerResultStarted {
27 readonly status: "started";
28 readonly scriptId: string;
29 readonly scriptName: string;
30 readonly scriptCommand: string;
31 readonly terminalId: string;
32 readonly cwd: string;
33 /** False when the script's `async` flag asks the agent to wait for it. */
34 readonly async: boolean;
35 /**
36 * Resolves when the script's shell prints the completion sentinel. The
37 * exit code is null when the terminal exited or was closed before the
38 * sentinel arrived. Only present when `observeCompletion` was requested.
39 * An exit code of 0 closes the setup shell if it has nothing left running.
40 */
41 readonly completion?: Effect.Effect<ProjectSetupScriptCompletion>;
42}
43
44export interface ProjectSetupScriptCompletion {
45 readonly exitCode: number | null;
46 readonly durationMs: number;
47}
48
49export interface ProjectSetupScriptOutputLine {
50 readonly line: string;
51}
52
53export type ProjectSetupScriptRunnerResult =
54 | ProjectSetupScriptRunnerResultNoScript
55 | ProjectSetupScriptRunnerResultStarted;
56
57export interface ProjectSetupScriptRunnerInput {
58 readonly threadId: string;
59 readonly projectId?: string;
60 readonly projectCwd?: string;
61 readonly worktreePath: string;
62 readonly preferredTerminalId?: string;
63 readonly project?: {
64 readonly id: ProjectId;
65 readonly workspaceRoot: string;
66 readonly scripts: ReadonlyArray<ProjectScript>;
67 };
68 /**
69 * Wrap the command so the shell reports its exit code back through the
70 * terminal stream, and forward cleaned output lines while it runs. The
71 * bootstrap flow uses this to drive the worktree setup card.
72 */
73 readonly observeCompletion?: {
74 readonly onOutputLine?: (line: string) => Effect.Effect<void>;
75 };
76}
77
78export class ProjectSetupScriptOperationError extends Schema.TaggedError<ProjectSetupScriptOperationError>()(
79 "ProjectSetupScriptOperationError",
80 {
81 threadId: Schema.String,
82 projectId: Schema.optional(Schema.String),
83 projectCwd: Schema.optional(Schema.String),
84 worktreePath: Schema.String,
85 operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal", "writeCommand"]),
86 cause: Schema.Defect(),
87 },
88) {
89 override get message(): string {
90 return `Project setup script operation '${this.operation}' failed for thread '${this.threadId}' in '${this.worktreePath}'.`;
91 }
92}
93
94export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<ProjectSetupScriptProjectNotFoundError>()(
95 "ProjectSetupScriptProjectNotFoundError",
96 {
97 threadId: Schema.String,
98 projectId: Schema.optional(Schema.String),
99 projectCwd: Schema.optional(Schema.String),
100 worktreePath: Schema.String,
101 },
102) {
103 override get message(): string {
104 return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;
105 }
106}
107
108export const ProjectSetupScriptRunnerError = Schema.Union([
109 ProjectSetupScriptOperationError,
110 ProjectSetupScriptProjectNotFoundError,
111]);
112export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
113
114export class ProjectSetupScriptRunner extends Context.Service<
115 ProjectSetupScriptRunner,
116 {
117 readonly runForThread: (
118 input: ProjectSetupScriptRunnerInput,
119 ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;
120 }
121>()("t3/project/ProjectSetupScriptRunner") {}
122
123/** @public Service construction is part of the canonical Effect module API. */
124/**
125 * Marker the wrapped setup command echoes so the exit code can be read from
126 * the PTY stream. Each run gets its own random token so script output cannot
127 * spoof completion, and the sentinel pattern is built per run from it.
128 */
129const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__";
130const OUTPUT_LINE_MAX_LENGTH = 400;
131/** A partial line longer than this is a byte stream, not a line. Keep only the tail. */
132const PARTIAL_LINE_MAX_LENGTH = 4_096;
133
134function completionSentinel(token: string): string {
135 return `${COMPLETION_SENTINEL_PREFIX}_${token}:`;
136}
137
138function completionSentinelPattern(token: string): RegExp {
139 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
140}
141
142/** Removes ANSI escape sequences and cursor controls so lines can be shown as plain text. */
143function stripTerminalControl(text: string): string {
144 return (
145 text
146 .replace(
147 // eslint-disable-next-line no-control-regex
148 /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
149 "",
150 )
151 // eslint-disable-next-line no-control-regex
152 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
153 );
154}
155
156type CompletionShell = "posix" | "fish" | "powershell";
157
158/**
159 * Predicts the shell TerminalManager will spawn for the setup terminal. The
160 * manager takes `$SHELL` on POSIX and PowerShell on Windows, falling back to
161 * other shells only when that one fails to spawn.
162 */
163function resolveCompletionShell(
164 platform: NodeJS.Platform,
165 env: NodeJS.ProcessEnv,
166): CompletionShell {
167 if (platform === "win32") return "powershell";
168 const shell = env.SHELL ?? "";
169 const name = shell.split("/").at(-1) ?? shell;
170 if (name === "fish") return "fish";
171 if (name === "pwsh" || name === "powershell") return "powershell";
172 return "posix";
173}
174
175/**
176 * Builds the shell input for the setup script. The command runs inside a
177 * block and the block closes on its own line, so a trailing `# comment` or a
178 * heredoc terminator in the command cannot swallow the sentinel. The shell
179 * reads the whole block before running any of it, so a script that reads
180 * stdin cannot consume the sentinel line either. Lines are separated by `\r`
181 * because that is the Enter key for every shell's line editor.
182 */
183function wrapCommandForCompletion(
184 command: string,
185 shell: CompletionShell,
186 sentinel: string,
187): string {
188 const body = command.replace(/\r?\n/g, "\r");
189 switch (shell) {
190 case "powershell":
191 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
192 case "fish":
193 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
194 case "posix":
195 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
196 }
197}
198
199/** @public Service construction is part of the canonical Effect module API. */
200export const make = Effect.gen(function* () {
201 const projects = yield* ProjectService.ProjectService;
202 const terminalManager = yield* TerminalManager.TerminalManager;
203 const serverSettings = yield* ServerSettings.ServerSettingsService;
204 const completionShell = resolveCompletionShell(
205 yield* HostProcessPlatform,
206 yield* HostProcessEnvironment,
207 );
208
209 /**
210 * Watches the setup terminal for the completion sentinel. Terminal output is
211 * a byte stream, so partial lines are buffered until a newline. The
212 * subscription is torn down once the sentinel, an exit, or a close arrives.
213 */
214 const observeTerminalCompletion = (input: {
215 readonly threadId: string;
216 readonly terminalId: string;
217 /** Per-run sentinel, so only this run's wrapper can settle completion. */
218 readonly sentinel: string;
219 readonly sentinelPattern: RegExp;
220 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
221 readonly echoedWrapperLines: ReadonlyArray<string>;
222 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
223 }) =>
224 Effect.gen(function* () {
225 const startedAtMs = yield* Clock.currentTimeMillis;
226 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
227 let lineBuffer = "";
228 let settled = false;
229
230 const settle = (exitCode: number | null) =>
231 Effect.suspend(() => {
232 if (settled) return Effect.void;
233 settled = true;
234 return Clock.currentTimeMillis.pipe(
235 Effect.flatMap((nowMs) =>
236 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
237 ),
238 Effect.asVoid,
239 );
240 });
241
242 const handleLine = (rawLine: string) =>
243 Effect.suspend(() => {
244 const sentinel = input.sentinelPattern.exec(rawLine);
245 if (sentinel) {
246 const parsed = Number(sentinel[1]);
247 return settle(Number.isFinite(parsed) ? parsed : null);
248 }
249 const cleaned = stripTerminalControl(rawLine).trimEnd();
250 if (
251 cleaned.length === 0 ||
252 cleaned.includes(input.sentinel) ||
253 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
254 input.onOutputLine === undefined
255 ) {
256 return Effect.void;
257 }
258 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
259 });
260
261 const unsubscribe = yield* terminalManager.subscribe((event) => {
262 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
263 return Effect.void;
264 }
265 if (event.type === "output") {
266 lineBuffer += event.data;
267 // A bare carriage return is how installers redraw a progress line in
268 // place; each redraw becomes a short line of its own instead of
269 // being glued into one long one. The wrapper echo is filtered per
270 // segment too, which is why `echoedWrapperLines` is split on the
271 // same `\r`: a line editor repainting the typed command yields the
272 // same segments.
273 const lines = lineBuffer.split(/\r\n|\r|\n/);
274 lineBuffer = lines.pop() ?? "";
275 // A script that never prints a newline must not grow this forever.
276 // The sentinel is always on its own line, so keeping the tail is safe.
277 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
278 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
279 }
280 return Effect.forEach(lines, handleLine, { discard: true });
281 }
282 if (event.type === "exited" || event.type === "closed") {
283 return settle(null);
284 }
285 return Effect.void;
286 });
287
288 const completion = Deferred.await(done).pipe(
289 Effect.ensuring(Effect.sync(() => unsubscribe())),
290 );
291 return { completion, unsubscribe };
292 });
293
294 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
295 "ProjectSetupScriptRunner.runForThread",
296 )(function* (input) {
297 const errorContext = {
298 threadId: input.threadId,
299 worktreePath: input.worktreePath,
300 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
301 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
302 };
303 const suppliedProject = input.project;
304 const projectById =
305 suppliedProject ??
306 (input.projectId
307 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
308 Effect.map(Option.getOrUndefined),
309 Effect.mapError(
310 (cause) =>
311 new ProjectSetupScriptOperationError({
312 ...errorContext,
313 operation: "resolveProject",
314 cause,
315 }),
316 ),
317 )
318 : null);
319 const project =
320 suppliedProject ??
321 projectById ??
322 (input.projectCwd
323 ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
324 Effect.map(Option.getOrUndefined),
325 Effect.mapError(
326 (cause) =>
327 new ProjectSetupScriptOperationError({
328 ...errorContext,
329 operation: "resolveProject",
330 cause,
331 }),
332 ),
333 )
334 : null);
335
336 if (!project) {
337 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
338 }
339
340 const settings = yield* serverSettings.getSettings.pipe(
341 Effect.mapError(
342 (cause) =>
343 new ProjectSetupScriptOperationError({
344 ...errorContext,
345 operation: "readSettings",
346 cause,
347 }),
348 ),
349 );
350 const script = setupProjectScript(resolveProjectScripts(settings, project));
351 if (!script) {
352 return {
353 status: "no-script",
354 } as const;
355 }
356
357 const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
358 const cwd = input.worktreePath;
359 const env = {
360 ...projectScriptRuntimeEnv({
361 project: { cwd: project.workspaceRoot },
362 worktreePath: input.worktreePath,
363 }),
364 // Setup can run before a client attaches. Truecolor probes in tools such
365 // as Vite+ wait for terminal replies that nobody can send at that point.
366 // Keep TERM's 256-color support without advertising truecolor here.
367 COLORTERM: "",
368 };
369 const observe = input.observeCompletion;
370 const completionToken = observe ? NodeCrypto.randomUUID().replaceAll("-", "") : null;
371 const commandLine =
372 observe && completionToken
373 ? wrapCommandForCompletion(
374 script.command,
375 completionShell,
376 completionSentinel(completionToken),
377 )
378 : script.command;
379
380 yield* terminalManager
381 .open({
382 threadId: input.threadId,
383 terminalId,
384 cwd,
385 worktreePath: input.worktreePath,
386 // Setup may run before a terminal client attaches to answer color probes.
387 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
388 })
389 .pipe(
390 Effect.mapError(
391 (cause) =>
392 new ProjectSetupScriptOperationError({
393 ...errorContext,
394 operation: "openTerminal",
395 cause,
396 }),
397 ),
398 );
399 // Subscribe before writing so the sentinel cannot race past the listener.
400 const observed =
401 observe && completionToken
402 ? yield* observeTerminalCompletion({
403 threadId: input.threadId,
404 terminalId,
405 sentinel: completionSentinel(completionToken),
406 sentinelPattern: completionSentinelPattern(completionToken),
407 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
408 onOutputLine: observe.onOutputLine,
409 })
410 : undefined;
411
412 yield* terminalManager
413 .write({
414 threadId: input.threadId,
415 terminalId,
416 data: `${commandLine}\r`,
417 })
418 .pipe(
419 Effect.mapError(
420 (cause) =>
421 new ProjectSetupScriptOperationError({
422 ...errorContext,
423 operation: "writeCommand",
424 cause,
425 }),
426 ),
427 // Nothing will ever settle the completion if the command never ran.
428 Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
429 );
430
431 // A clean run leaves only an idle prompt behind; its output stays in the
432 // terminal history. A failed run keeps its shell open for a look.
433 const completion = observed?.completion.pipe(
434 Effect.tap(({ exitCode }) =>
435 exitCode === 0
436 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
437 : Effect.void,
438 ),
439 );
440
441 return {
442 status: "started",
443 scriptId: script.id,
444 scriptName: script.name,
445 scriptCommand: script.command,
446 terminalId,
447 cwd,
448 async: script.async !== false,
449 ...(completion ? { completion } : {}),
450 } as const;
451 });
452
453 return ProjectSetupScriptRunner.of({ runForThread });
454});
455
456export const layer = Layer.effect(ProjectSetupScriptRunner, make);