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