Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectSetupScriptRunner.ts

441 lines15.7 KB

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";
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>;
43​
44export interface ProjectSetupScriptCompletion {
45 readonly exitCode: number | null;
46 readonly durationMs: number;
48​
49export interface ProjectSetupScriptOutputLine {
50 readonly line: string;
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 /**
64 * Wrap the command so the shell reports its exit code back through the
65 * terminal stream, and forward cleaned output lines while it runs. The
66 * bootstrap flow uses this to drive the worktree setup card.
67 */
68 readonly observeCompletion?: {
69 readonly onOutputLine?: (line: string) => Effect.Effect<void>;
70 };
72​
73export class ProjectSetupScriptOperationError extends Schema.TaggedError<ProjectSetupScriptOperationError>()(
74 "ProjectSetupScriptOperationError",
75 {
76 threadId: Schema.String,
77 projectId: Schema.optional(Schema.String),
78 projectCwd: Schema.optional(Schema.String),
79 worktreePath: Schema.String,
80 operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal", "writeCommand"]),
81 cause: Schema.Defect(),
82 },
83) {
84 override get message(): string {
85 return `Project setup script operation '${this.operation}' failed for thread '${this.threadId}' in '${this.worktreePath}'.`;
86 }
88​
89export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<ProjectSetupScriptProjectNotFoundError>()(
90 "ProjectSetupScriptProjectNotFoundError",
91 {
92 threadId: Schema.String,
93 projectId: Schema.optional(Schema.String),
94 projectCwd: Schema.optional(Schema.String),
95 worktreePath: Schema.String,
96 },
97) {
98 override get message(): string {
99 return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;
100 }
102​
103export const ProjectSetupScriptRunnerError = Schema.Union([
104 ProjectSetupScriptOperationError,
105 ProjectSetupScriptProjectNotFoundError,
106]);
107export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
108​
109export class ProjectSetupScriptRunner extends Context.Service<
110 ProjectSetupScriptRunner,
111 {
112 readonly runForThread: (
113 input: ProjectSetupScriptRunnerInput,
114 ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;
115 }
116>()("t3/project/ProjectSetupScriptRunner") {}
117​
118/** @public Service construction is part of the canonical Effect module API. */
119/**
120 * Marker the wrapped setup command echoes so the exit code can be read from
121 * the PTY stream. Each run gets its own random token so script output cannot
122 * spoof completion, and the sentinel pattern is built per run from it.
123 */
124const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__";
125const OUTPUT_LINE_MAX_LENGTH = 400;
126/** A partial line longer than this is a byte stream, not a line. Keep only the tail. */
127const PARTIAL_LINE_MAX_LENGTH = 4_096;
128​
129function completionSentinel(token: string): string {
130 return `${COMPLETION_SENTINEL_PREFIX}_${token}:`;
132​
133function completionSentinelPattern(token: string): RegExp {
134 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
136​
137/** Removes ANSI escape sequences and cursor controls so lines can be shown as plain text. */
138function stripTerminalControl(text: string): string {
139 return (
140 text
141 .replace(
142 // eslint-disable-next-line no-control-regex
143 /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
144 "",
145 )
146 // eslint-disable-next-line no-control-regex
147 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
148 );
150​
151type CompletionShell = "posix" | "fish" | "powershell";
152​
153/**
154 * Predicts the shell TerminalManager will spawn for the setup terminal. The
155 * manager takes `$SHELL` on POSIX and PowerShell on Windows, falling back to
156 * other shells only when that one fails to spawn.
157 */
158function resolveCompletionShell(
159 platform: NodeJS.Platform,
160 env: NodeJS.ProcessEnv,
161): CompletionShell {
162 if (platform === "win32") return "powershell";
163 const shell = env.SHELL ?? "";
164 const name = shell.split("/").at(-1) ?? shell;
165 if (name === "fish") return "fish";
166 if (name === "pwsh" || name === "powershell") return "powershell";
167 return "posix";
169​
170/**
171 * Builds the shell input for the setup script. The command runs inside a
172 * block and the block closes on its own line, so a trailing `# comment` or a
173 * heredoc terminator in the command cannot swallow the sentinel. The shell
174 * reads the whole block before running any of it, so a script that reads
175 * stdin cannot consume the sentinel line either. Lines are separated by `\r`
176 * because that is the Enter key for every shell's line editor.
177 */
178function wrapCommandForCompletion(
179 command: string,
180 shell: CompletionShell,
181 sentinel: string,
182): string {
183 const body = command.replace(/\r?\n/g, "\r");
184 switch (shell) {
185 case "powershell":
186 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
187 case "fish":
188 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
189 case "posix":
190 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
191 }
193​
194/** @public Service construction is part of the canonical Effect module API. */
195export const make = Effect.gen(function* () {
196 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
197 const terminalManager = yield* TerminalManager.TerminalManager;
198 const serverSettings = yield* ServerSettings.ServerSettingsService;
199 const completionShell = resolveCompletionShell(
200 yield* HostProcessPlatform,
201 yield* HostProcessEnvironment,
202 );
203​
204 /**
205 * Watches the setup terminal for the completion sentinel. Terminal output is
206 * a byte stream, so partial lines are buffered until a newline. The
207 * subscription is torn down once the sentinel, an exit, or a close arrives.
208 */
209 const observeTerminalCompletion = (input: {
210 readonly threadId: string;
211 readonly terminalId: string;
212 /** Per-run sentinel, so only this run's wrapper can settle completion. */
213 readonly sentinel: string;
214 readonly sentinelPattern: RegExp;
215 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
216 readonly echoedWrapperLines: ReadonlyArray<string>;
217 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
218 }) =>
219 Effect.gen(function* () {
220 const startedAtMs = yield* Clock.currentTimeMillis;
221 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
222 let lineBuffer = "";
223 let settled = false;
224​
225 const settle = (exitCode: number | null) =>
226 Effect.suspend(() => {
227 if (settled) return Effect.void;
228 settled = true;
229 return Clock.currentTimeMillis.pipe(
230 Effect.flatMap((nowMs) =>
231 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
232 ),
233 Effect.asVoid,
234 );
235 });
236​
237 const handleLine = (rawLine: string) =>
238 Effect.suspend(() => {
239 const sentinel = input.sentinelPattern.exec(rawLine);
240 if (sentinel) {
241 const parsed = Number(sentinel[1]);
242 return settle(Number.isFinite(parsed) ? parsed : null);
243 }
244 const cleaned = stripTerminalControl(rawLine).trimEnd();
245 if (
246 cleaned.length === 0 ||
247 cleaned.includes(input.sentinel) ||
248 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
249 input.onOutputLine === undefined
250 ) {
251 return Effect.void;
252 }
253 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
254 });
255​
256 const unsubscribe = yield* terminalManager.subscribe((event) => {
257 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
258 return Effect.void;
259 }
260 if (event.type === "output") {
261 lineBuffer += event.data;
262 // A bare carriage return is how installers redraw a progress line in
263 // place; each redraw becomes a short line of its own instead of
264 // being glued into one long one. The wrapper echo is filtered per
265 // segment too, which is why `echoedWrapperLines` is split on the
266 // same `\r`: a line editor repainting the typed command yields the
267 // same segments.
268 const lines = lineBuffer.split(/\r\n|\r|\n/);
269 lineBuffer = lines.pop() ?? "";
270 // A script that never prints a newline must not grow this forever.
271 // The sentinel is always on its own line, so keeping the tail is safe.
272 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
273 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
274 }
275 return Effect.forEach(lines, handleLine, { discard: true });
276 }
277 if (event.type === "exited" || event.type === "closed") {
278 return settle(null);
279 }
280 return Effect.void;
281 });
282​
283 const completion = Deferred.await(done).pipe(
284 Effect.ensuring(Effect.sync(() => unsubscribe())),
285 );
286 return { completion, unsubscribe };
287 });
288​
289 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
290 "ProjectSetupScriptRunner.runForThread",
291 )(function* (input) {
292 const errorContext = {
293 threadId: input.threadId,
294 worktreePath: input.worktreePath,
295 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
296 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
297 };
298 const projectById = input.projectId
299 ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).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 const project =
312 projectById ??
313 (input.projectCwd
314 ? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
315 Effect.map(Option.getOrUndefined),
316 Effect.mapError(
317 (cause) =>
318 new ProjectSetupScriptOperationError({
319 ...errorContext,
320 operation: "resolveProject",
321 cause,
322 }),
323 ),
324 )
325 : null);
326​
327 if (!project) {
328 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
329 }
330​
331 const settings = yield* serverSettings.getSettings.pipe(
332 Effect.mapError(
333 (cause) =>
334 new ProjectSetupScriptOperationError({
335 ...errorContext,
336 operation: "readSettings",
337 cause,
338 }),
339 ),
340 );
341 const script = setupProjectScript(resolveProjectScripts(settings, project));
342 if (!script) {
343 return {
344 status: "no-script",
345 } as const;
346 }
347​
348 const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
349 const cwd = input.worktreePath;
350 const env = projectScriptRuntimeEnv({
351 project: { cwd: project.workspaceRoot },
352 worktreePath: input.worktreePath,
353 });
354 const observe = input.observeCompletion;
355 const completionToken = observe ? NodeCrypto.randomUUID().replaceAll("-", "") : null;
356 const commandLine =
357 observe && completionToken
358 ? wrapCommandForCompletion(
359 script.command,
360 completionShell,
361 completionSentinel(completionToken),
362 )
363 : script.command;
364​
365 yield* terminalManager
366 .open({
367 threadId: input.threadId,
368 terminalId,
369 cwd,
370 worktreePath: input.worktreePath,
371 // Setup may run before a terminal client attaches to answer color probes.
372 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
373 })
374 .pipe(
375 Effect.mapError(
376 (cause) =>
377 new ProjectSetupScriptOperationError({
378 ...errorContext,
379 operation: "openTerminal",
380 cause,
381 }),
382 ),
383 );
384 // Subscribe before writing so the sentinel cannot race past the listener.
385 const observed =
386 observe && completionToken
387 ? yield* observeTerminalCompletion({
388 threadId: input.threadId,
389 terminalId,
390 sentinel: completionSentinel(completionToken),
391 sentinelPattern: completionSentinelPattern(completionToken),
392 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
393 onOutputLine: observe.onOutputLine,
394 })
395 : undefined;
396​
397 yield* terminalManager
398 .write({
399 threadId: input.threadId,
400 terminalId,
401 data: `${commandLine}\r`,
402 })
403 .pipe(
404 Effect.mapError(
405 (cause) =>
406 new ProjectSetupScriptOperationError({
407 ...errorContext,
408 operation: "writeCommand",
409 cause,
410 }),
411 ),
412 // Nothing will ever settle the completion if the command never ran.
413 Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
414 );
415​
416 // A clean run leaves only an idle prompt behind; its output stays in the
417 // terminal history. A failed run keeps its shell open for a look.
418 const completion = observed?.completion.pipe(
419 Effect.tap(({ exitCode }) =>
420 exitCode === 0
421 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
422 : Effect.void,
423 ),
424 );
425​
426 return {
427 status: "started",
428 scriptId: script.id,
429 scriptName: script.name,
430 scriptCommand: script.command,
431 terminalId,
432 cwd,
433 async: script.async !== false,
434 ...(completion ? { completion } : {}),
435 } as const;
436 });
437​
438 return ProjectSetupScriptRunner.of({ runForThread });
439});
440​
441export const layer = Layer.effect(ProjectSetupScriptRunner, make);