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";
8
9import * as Clock from "effect/Clock";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
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 -- ANSI escape sequences start with ESC.
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 -- removing control characters is the point.
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 crypto = yield* Crypto.Crypto;
205 const completionShell = resolveCompletionShell(
206 yield* HostProcessPlatform,
207 yield* HostProcessEnvironment,
208 );
209
210 /**
211 * Watches the setup terminal for the completion sentinel. Terminal output is
212 * a byte stream, so partial lines are buffered until a newline. The
213 * subscription is torn down once the sentinel, an exit, or a close arrives.
214 */
215 const observeTerminalCompletion = (input: {
216 readonly threadId: string;
217 readonly terminalId: string;
218 /** Per-run sentinel, so only this run's wrapper can settle completion. */
219 readonly sentinel: string;
220 readonly sentinelPattern: RegExp;
221 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
222 readonly echoedWrapperLines: ReadonlyArray<string>;
223 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
224 }) =>
225 Effect.gen(function* () {
226 const startedAtMs = yield* Clock.currentTimeMillis;
227 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
228 let lineBuffer = "";
229 let settled = false;
230
231 const settle = (exitCode: number | null) =>
232 Effect.suspend(() => {
233 if (settled) return Effect.void;
234 settled = true;
235 return Clock.currentTimeMillis.pipe(
236 Effect.flatMap((nowMs) =>
237 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
238 ),
239 Effect.asVoid,
240 );
241 });
242
243 const handleLine = (rawLine: string) =>
244 Effect.suspend(() => {
245 const sentinel = input.sentinelPattern.exec(rawLine);
246 if (sentinel) {
247 const parsed = Number(sentinel[1]);
248 return settle(Number.isFinite(parsed) ? parsed : null);
249 }
250 const cleaned = stripTerminalControl(rawLine).trimEnd();
251 if (
252 cleaned.length === 0 ||
253 cleaned.includes(input.sentinel) ||
254 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
255 input.onOutputLine === undefined
256 ) {
257 return Effect.void;
258 }
259 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
260 });
261
262 const unsubscribe = yield* terminalManager.subscribe((event) => {
263 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
264 return Effect.void;
265 }
266 if (event.type === "output") {
267 lineBuffer += event.data;
268 // A bare carriage return is how installers redraw a progress line in
269 // place; each redraw becomes a short line of its own instead of
270 // being glued into one long one. The wrapper echo is filtered per
271 // segment too, which is why `echoedWrapperLines` is split on the
272 // same `\r`: a line editor repainting the typed command yields the
273 // same segments.
274 const lines = lineBuffer.split(/\r\n|\r|\n/);
275 lineBuffer = lines.pop() ?? "";
276 // A script that never prints a newline must not grow this forever.
277 // The sentinel is always on its own line, so keeping the tail is safe.
278 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
279 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
280 }
281 return Effect.forEach(lines, handleLine, { discard: true });
282 }
283 if (event.type === "exited" || event.type === "closed") {
284 return settle(null);
285 }
286 return Effect.void;
287 });
288
289 const completion = Deferred.await(done).pipe(
290 Effect.ensuring(Effect.sync(() => unsubscribe())),
291 );
292 return { completion, unsubscribe };
293 });
294
295 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
296 "ProjectSetupScriptRunner.runForThread",
297 )(function* (input) {
298 const errorContext = {
299 threadId: input.threadId,
300 worktreePath: input.worktreePath,
301 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
302 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
303 };
304 const suppliedProject = input.project;
305 const projectById =
306 suppliedProject ??
307 (input.projectId
308 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
309 Effect.map(Option.getOrUndefined),
310 Effect.mapError(
311 (cause) =>
312 new ProjectSetupScriptOperationError({
313 ...errorContext,
314 operation: "resolveProject",
315 cause,
316 }),
317 ),
318 )
319 : null);
320 const project =
321 suppliedProject ??
322 projectById ??
323 (input.projectCwd
324 ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
325 Effect.map(Option.getOrUndefined),
326 Effect.mapError(
327 (cause) =>
328 new ProjectSetupScriptOperationError({
329 ...errorContext,
330 operation: "resolveProject",
331 cause,
332 }),
333 ),
334 )
335 : null);
336
337 if (!project) {
338 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
339 }
340
341 const settings = yield* serverSettings.getSettings.pipe(
342 Effect.mapError(
343 (cause) =>
344 new ProjectSetupScriptOperationError({
345 ...errorContext,
346 operation: "readSettings",
347 cause,
348 }),
349 ),
350 );
351 const script = setupProjectScript(resolveProjectScripts(settings, project));
352 if (!script) {
353 return {
354 status: "no-script",
355 } as const;
356 }
357
358 const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
359 const cwd = input.worktreePath;
360 const env = {
361 ...projectScriptRuntimeEnv({
362 project: { cwd: project.workspaceRoot },
363 worktreePath: input.worktreePath,
364 }),
365 // Setup can run before a client attaches. Truecolor probes in tools such
366 // as Vite+ wait for terminal replies that nobody can send at that point.
367 // Keep TERM's 256-color support without advertising truecolor here.
368 COLORTERM: "",
369 };
370 const observe = input.observeCompletion;
371 const completionToken = observe
372 ? (yield* crypto.randomUUIDv4.pipe(Effect.orDie)).replaceAll("-", "")
373 : null;
374 const commandLine =
375 observe && completionToken
376 ? wrapCommandForCompletion(
377 script.command,
378 completionShell,
379 completionSentinel(completionToken),
380 )
381 : script.command;
382
383 yield* terminalManager
384 .open({
385 threadId: input.threadId,
386 terminalId,
387 cwd,
388 worktreePath: input.worktreePath,
389 // Setup may run before a terminal client attaches to answer color probes.
390 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
391 })
392 .pipe(
393 Effect.mapError(
394 (cause) =>
395 new ProjectSetupScriptOperationError({
396 ...errorContext,
397 operation: "openTerminal",
398 cause,
399 }),
400 ),
401 );
402 // Subscribe before writing so the sentinel cannot race past the listener.
403 const observed =
404 observe && completionToken
405 ? yield* observeTerminalCompletion({
406 threadId: input.threadId,
407 terminalId,
408 sentinel: completionSentinel(completionToken),
409 sentinelPattern: completionSentinelPattern(completionToken),
410 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
411 onOutputLine: observe.onOutputLine,
412 })
413 : undefined;
414
415 yield* terminalManager
416 .write({
417 threadId: input.threadId,
418 terminalId,
419 data: `${commandLine}\r`,
420 })
421 .pipe(
422 Effect.mapError(
423 (cause) =>
424 new ProjectSetupScriptOperationError({
425 ...errorContext,
426 operation: "writeCommand",
427 cause,
428 }),
429 ),
430 // Nothing will ever settle the completion if the command never ran.
431 Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
432 );
433
434 // A clean run leaves only an idle prompt behind; its output stays in the
435 // terminal history. A failed run keeps its shell open for a look.
436 const completion = observed?.completion.pipe(
437 Effect.tap(({ exitCode }) =>
438 exitCode === 0
439 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
440 : Effect.void,
441 ),
442 );
443
444 return {
445 status: "started",
446 scriptId: script.id,
447 scriptName: script.name,
448 scriptCommand: script.command,
449 terminalId,
450 cwd,
451 async: script.async !== false,
452 ...(completion ? { completion } : {}),
453 } as const;
454 });
455
456 return ProjectSetupScriptRunner.of({ runForThread });
457});
458
459export const layer = Layer.effect(ProjectSetupScriptRunner, make);