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 /** 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>;
41}
42
43export interface ProjectSetupScriptCompletion {
44 readonly exitCode: number | null;
45 readonly durationMs: number;
46}
47
48export interface ProjectSetupScriptOutputLine {
49 readonly line: string;
50}
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 };
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 * 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}:`;
130}
131
132function completionSentinelPattern(token: string): RegExp {
133 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
134}
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 );
148}
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";
167}
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 }
191}
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 const lines = lineBuffer.split(/\r?\n/);
262 lineBuffer = lines.pop() ?? "";
263 // A script that never prints a newline must not grow this forever.
264 // The sentinel is always on its own line, so keeping the tail is safe.
265 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
266 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
267 }
268 return Effect.forEach(lines, handleLine, { discard: true });
269 }
270 if (event.type === "exited" || event.type === "closed") {
271 return settle(null);
272 }
273 return Effect.void;
274 });
275
276 const completion = Deferred.await(done).pipe(
277 Effect.ensuring(Effect.sync(() => unsubscribe())),
278 );
279 return { completion, unsubscribe };
280 });
281
282 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
283 "ProjectSetupScriptRunner.runForThread",
284 )(function* (input) {
285 const errorContext = {
286 threadId: input.threadId,
287 worktreePath: input.worktreePath,
288 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
289 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
290 };
291 const projectById = input.projectId
292 ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
293 Effect.map(Option.getOrUndefined),
294 Effect.mapError(
295 (cause) =>
296 new ProjectSetupScriptOperationError({
297 ...errorContext,
298 operation: "resolveProject",
299 cause,
300 }),
301 ),
302 )
303 : null;
304 const project =
305 projectById ??
306 (input.projectCwd
307 ? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
308 Effect.map(Option.getOrUndefined),
309 Effect.mapError(
310 (cause) =>
311 new ProjectSetupScriptOperationError({
312 ...errorContext,
313 operation: "resolveProject",
314 cause,
315 }),
316 ),
317 )
318 : null);
319
320 if (!project) {
321 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
322 }
323
324 const settings = yield* serverSettings.getSettings.pipe(
325 Effect.mapError(
326 (cause) =>
327 new ProjectSetupScriptOperationError({
328 ...errorContext,
329 operation: "readSettings",
330 cause,
331 }),
332 ),
333 );
334 const script = setupProjectScript(resolveProjectScripts(settings, project));
335 if (!script) {
336 return {
337 status: "no-script",
338 } as const;
339 }
340
341 const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
342 const cwd = input.worktreePath;
343 const env = projectScriptRuntimeEnv({
344 project: { cwd: project.workspaceRoot },
345 worktreePath: input.worktreePath,
346 });
347 const observe = input.observeCompletion;
348 const completionToken = observe ? NodeCrypto.randomUUID().replaceAll("-", "") : null;
349 const commandLine =
350 observe && completionToken
351 ? wrapCommandForCompletion(
352 script.command,
353 completionShell,
354 completionSentinel(completionToken),
355 )
356 : script.command;
357
358 yield* terminalManager
359 .open({
360 threadId: input.threadId,
361 terminalId,
362 cwd,
363 worktreePath: input.worktreePath,
364 env,
365 })
366 .pipe(
367 Effect.mapError(
368 (cause) =>
369 new ProjectSetupScriptOperationError({
370 ...errorContext,
371 operation: "openTerminal",
372 cause,
373 }),
374 ),
375 );
376 // Subscribe before writing so the sentinel cannot race past the listener.
377 const observed =
378 observe && completionToken
379 ? yield* observeTerminalCompletion({
380 threadId: input.threadId,
381 terminalId,
382 sentinel: completionSentinel(completionToken),
383 sentinelPattern: completionSentinelPattern(completionToken),
384 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
385 onOutputLine: observe.onOutputLine,
386 })
387 : undefined;
388
389 yield* terminalManager
390 .write({
391 threadId: input.threadId,
392 terminalId,
393 data: `${commandLine}\r`,
394 })
395 .pipe(
396 Effect.mapError(
397 (cause) =>
398 new ProjectSetupScriptOperationError({
399 ...errorContext,
400 operation: "writeCommand",
401 cause,
402 }),
403 ),
404 // Nothing will ever settle the completion if the command never ran.
405 Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
406 );
407
408 return {
409 status: "started",
410 scriptId: script.id,
411 scriptName: script.name,
412 scriptCommand: script.command,
413 terminalId,
414 cwd,
415 async: script.async !== false,
416 ...(observed ? { completion: observed.completion } : {}),
417 } as const;
418 });
419
420 return ProjectSetupScriptRunner.of({ runForThread });
421});
422
423export const layer = Layer.effect(ProjectSetupScriptRunner, make);