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