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