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