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

ProjectSetupScriptRunner.ts

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