Open History to see the last commit
1import { ProjectId } 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 ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
19import * as ServerSettings from "../serverSettings.ts";
20import * as TerminalManager from "../terminal/Manager.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 /**
34 * Resolves when the script's shell prints the completion sentinel. The
35 * exit code is null when the terminal exited or was closed before the
36 * sentinel arrived. Only present when `observeCompletion` was requested.
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 /**
61 * Wrap the command so the shell reports its exit code back through the
62 * terminal stream, and forward cleaned output lines while it runs. The
63 * bootstrap flow uses this to drive the worktree setup card.
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 Service construction is part of the canonical Effect module API. */
116/**
117 * Marker the wrapped setup command echoes so the exit code can be read from
118 * the PTY stream. Each run gets its own random token so script output cannot
119 * spoof completion, and the sentinel pattern is built per run from it.
120 */
121const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__";
122const OUTPUT_LINE_MAX_LENGTH = 400;
123/** A partial line longer than this is a byte stream, not a line. Keep only the tail. */
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
134/** Removes ANSI escape sequences and cursor controls so lines can be shown as plain text. */
135function stripTerminalControl(text: string): string {
136 return (
137 text
138 .replace(
139 // eslint-disable-next-line no-control-regex
140 /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
141 "",
142 )
143 // eslint-disable-next-line no-control-regex
144 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
145 );
146}
147
148type CompletionShell = "posix" | "fish" | "powershell";
149
150/**
151 * Predicts the shell TerminalManager will spawn for the setup terminal. The
152 * manager takes `$SHELL` on POSIX and PowerShell on Windows, falling back to
153 * other shells only when that one fails to spawn.
154 */
155function resolveCompletionShell(
156 platform: NodeJS.Platform,
157 env: NodeJS.ProcessEnv,
158): CompletionShell {
159 if (platform === "win32") return "powershell";
160 const shell = env.SHELL ?? "";
161 const name = shell.split("/").at(-1) ?? shell;
162 if (name === "fish") return "fish";
163 if (name === "pwsh" || name === "powershell") return "powershell";
164 return "posix";
165}
166
167/**
168 * Builds the shell input for the setup script. The command runs inside a
169 * block and the block closes on its own line, so a trailing `# comment` or a
170 * heredoc terminator in the command cannot swallow the sentinel. The shell
171 * reads the whole block before running any of it, so a script that reads
172 * stdin cannot consume the sentinel line either. Lines are separated by `\r`
173 * because that is the Enter key for every shell's line editor.
174 */
175function wrapCommandForCompletion(
176 command: string,
177 shell: CompletionShell,
178 sentinel: string,
179): string {
180 const body = command.replace(/\r?\n/g, "\r");
181 switch (shell) {
182 case "powershell":
183 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
184 case "fish":
185 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
186 case "posix":
187 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
188 }
189}
190
191/** @public Service construction is part of the canonical Effect module API. */
192export const make = Effect.gen(function* () {
193 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
194 const terminalManager = yield* TerminalManager.TerminalManager;
195 const serverSettings = yield* ServerSettings.ServerSettingsService;
196 const completionShell = resolveCompletionShell(
197 yield* HostProcessPlatform,
198 yield* HostProcessEnvironment,
199 );
200
201 /**
202 * Watches the setup terminal for the completion sentinel. Terminal output is
203 * a byte stream, so partial lines are buffered until a newline. The
204 * subscription is torn down once the sentinel, an exit, or a close arrives.
205 */
206 const observeTerminalCompletion = (input: {
207 readonly threadId: string;
208 readonly terminalId: string;
209 /** Per-run sentinel, so only this run's wrapper can settle completion. */
210 readonly sentinel: string;
211 readonly sentinelPattern: RegExp;
212 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
213 readonly echoedWrapperLines: ReadonlyArray<string>;
214 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
215 }) =>
216 Effect.gen(function* () {
217 const startedAtMs = yield* Clock.currentTimeMillis;
218 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
219 let lineBuffer = "";
220 let settled = false;
221
222 const settle = (exitCode: number | null) =>
223 Effect.suspend(() => {
224 if (settled) return Effect.void;
225 settled = true;
226 return Clock.currentTimeMillis.pipe(
227 Effect.flatMap((nowMs) =>
228 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
229 ),
230 Effect.asVoid,
231 );
232 });
233
234 const handleLine = (rawLine: string) =>
235 Effect.suspend(() => {
236 const sentinel = input.sentinelPattern.exec(rawLine);
237 if (sentinel) {
238 const parsed = Number(sentinel[1]);
239 return settle(Number.isFinite(parsed) ? parsed : null);
240 }
241 const cleaned = stripTerminalControl(rawLine).trimEnd();
242 if (
243 cleaned.length === 0 ||
244 cleaned.includes(input.sentinel) ||
245 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
246 input.onOutputLine === undefined
247 ) {
248 return Effect.void;
249 }
250 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
251 });
252
253 const unsubscribe = yield* terminalManager.subscribe((event) => {
254 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
255 return Effect.void;
256 }
257 if (event.type === "output") {
258 lineBuffer += event.data;
259 const lines = lineBuffer.split(/\r?\n/);
260 lineBuffer = lines.pop() ?? "";
261 // A script that never prints a newline must not grow this forever.
262 // The sentinel is always on its own line, so keeping the tail is safe.
263 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
264 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
265 }
266 return Effect.forEach(lines, handleLine, { discard: true });
267 }
268 if (event.type === "exited" || event.type === "closed") {
269 return settle(null);
270 }
271 return Effect.void;
272 });
273
274 const completion = Deferred.await(done).pipe(
275 Effect.ensuring(Effect.sync(() => unsubscribe())),
276 );
277 return { completion, unsubscribe };
278 });
279
280 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
281 "ProjectSetupScriptRunner.runForThread",
282 )(function* (input) {
283 const errorContext = {
284 threadId: input.threadId,
285 worktreePath: input.worktreePath,
286 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
287 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
288 };
289 const projectById = input.projectId
290 ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
291 Effect.map(Option.getOrUndefined),
292 Effect.mapError(
293 (cause) =>
294 new ProjectSetupScriptOperationError({
295 ...errorContext,
296 operation: "resolveProject",
297 cause,
298 }),
299 ),
300 )
301 : null;
302 const project =
303 projectById ??
304 (input.projectCwd
305 ? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
306 Effect.map(Option.getOrUndefined),
307 Effect.mapError(
308 (cause) =>
309 new ProjectSetupScriptOperationError({
310 ...errorContext,
311 operation: "resolveProject",
312 cause,
313 }),
314 ),
315 )
316 : null);
317
318 if (!project) {
319 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
320 }
321
322 const settings = yield* serverSettings.getSettings.pipe(
323 Effect.mapError(
324 (cause) =>
325 new ProjectSetupScriptOperationError({
326 ...errorContext,
327 operation: "readSettings",
328 cause,
329 }),
330 ),
331 );
332 const script = setupProjectScript(resolveProjectScripts(settings, project));
333 if (!script) {
334 return {
335 status: "no-script",
336 } as const;
337 }
338
339 const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
340 const cwd = input.worktreePath;
341 const env = projectScriptRuntimeEnv({
342 project: { cwd: project.workspaceRoot },
343 worktreePath: input.worktreePath,
344 });
345 const observe = input.observeCompletion;
346 const completionToken = observe ? NodeCrypto.randomUUID().replaceAll("-", "") : null;
347 const commandLine =
348 observe && completionToken
349 ? wrapCommandForCompletion(
350 script.command,
351 completionShell,
352 completionSentinel(completionToken),
353 )
354 : script.command;
355
356 yield* terminalManager
357 .open({
358 threadId: input.threadId,
359 terminalId,
360 cwd,
361 worktreePath: input.worktreePath,
362 env,
363 })
364 .pipe(
365 Effect.mapError(
366 (cause) =>
367 new ProjectSetupScriptOperationError({
368 ...errorContext,
369 operation: "openTerminal",
370 cause,
371 }),
372 ),
373 );
374 // Subscribe before writing so the sentinel cannot race past the listener.
375 const observed =
376 observe && completionToken
377 ? yield* observeTerminalCompletion({
378 threadId: input.threadId,
379 terminalId,
380 sentinel: completionSentinel(completionToken),
381 sentinelPattern: completionSentinelPattern(completionToken),
382 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
383 onOutputLine: observe.onOutputLine,
384 })
385 : undefined;
386
387 yield* terminalManager
388 .write({
389 threadId: input.threadId,
390 terminalId,
391 data: `${commandLine}\r`,
392 })
393 .pipe(
394 Effect.mapError(
395 (cause) =>
396 new ProjectSetupScriptOperationError({
397 ...errorContext,
398 operation: "writeCommand",
399 cause,
400 }),
401 ),
402 // Nothing will ever settle the completion if the command never ran.
403 Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
404 );
405
406 return {
407 status: "started",
408 scriptId: script.id,
409 scriptName: script.name,
410 scriptCommand: script.command,
411 terminalId,
412 cwd,
413 ...(observed ? { completion: observed.completion } : {}),
414 } as const;
415 });
416
417 return ProjectSetupScriptRunner.of({ runForThread });
418});
419
420export const layer = Layer.effect(ProjectSetupScriptRunner, make);