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"]),
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
142// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command.
143const BRACKETED_PASTE_ON = "\x1b[?2004h";
144const BRACKETED_PASTE_OFF = "\x1b[?2004l";
145// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first.
146const SHELL_QUIET_FALLBACK = "3 seconds";
147
148function lineEditorReading(text: string, previous: boolean): boolean {
149 const on = text.lastIndexOf(BRACKETED_PASTE_ON);
150 const off = text.lastIndexOf(BRACKETED_PASTE_OFF);
151 return on === off ? previous : on > off;
152}
153
154type CompletionShell = "posix" | "fish" | "powershell";
155
156function resolveCompletionShell(
157 platform: NodeJS.Platform,
158 env: NodeJS.ProcessEnv,
159): CompletionShell {
160 if (platform === "win32") return "powershell";
161 const shell = env.SHELL ?? "";
162 const name = shell.split("/").at(-1) ?? shell;
163 if (name === "fish") return "fish";
164 if (name === "pwsh" || name === "powershell") return "powershell";
165 return "posix";
166}
167
168// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
169function wrapCommandForCompletion(
170 command: string,
171 shell: CompletionShell,
172 sentinel: string,
173): string {
174 const body = command.replace(/\r?\n/g, "\r");
175 switch (shell) {
176 case "powershell":
177 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
178 case "fish":
179 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
180 case "posix":
181 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
182 }
183}
184
185/** @public */
186export const make = Effect.gen(function* () {
187 const projects = yield* ProjectService.ProjectService;
188 const terminalManager = yield* TerminalManager.TerminalManager;
189 const serverSettings = yield* ServerSettings.ServerSettingsService;
190 const crypto = yield* Crypto.Crypto;
191 const serviceScope = yield* Effect.scope;
192 const completionShell = resolveCompletionShell(
193 yield* HostProcess.Platform,
194 yield* HostProcess.Environment,
195 );
196
197 const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
198 function* (input: {
199 readonly threadId: string;
200 readonly terminalId: string;
201 readonly sentinel: string;
202 readonly sentinelPattern: RegExp;
203 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
204 readonly echoedWrapperLines: ReadonlyArray<string>;
205 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
206 }) {
207 const startedAtMs = yield* Clock.currentTimeMillis;
208 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
209 // Wait for the prompt redraw; closing earlier mistakes it for activity and preserves an idle shell.
210 const promptReturned = yield* Deferred.make<void>();
211 let lineBuffer = "";
212 let settled = false;
213
214 const settle = (exitCode: number | null) =>
215 Effect.suspend(() => {
216 if (settled) return Effect.void;
217 settled = true;
218 return Clock.currentTimeMillis.pipe(
219 Effect.flatMap((nowMs) =>
220 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
221 ),
222 Effect.asVoid,
223 );
224 });
225
226 const handleLine = (rawLine: string) =>
227 Effect.suspend(() => {
228 const sentinel = input.sentinelPattern.exec(rawLine);
229 if (sentinel) {
230 const parsed = Number(sentinel[1]);
231 return settle(Number.isFinite(parsed) ? parsed : null);
232 }
233 const cleaned = stripTerminalControl(rawLine).trimEnd();
234 if (
235 cleaned.length === 0 ||
236 cleaned.includes(input.sentinel) ||
237 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
238 input.onOutputLine === undefined
239 ) {
240 return Effect.void;
241 }
242 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
243 });
244
245 const unsubscribe = yield* terminalManager.subscribe((event) => {
246 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
247 return Effect.void;
248 }
249 if (event.type === "output") {
250 lineBuffer += event.data;
251 // Bare CR redraws progress in place; split redraws instead of growing one line.
252 const lines = lineBuffer.split(/\r\n|\r|\n/);
253 lineBuffer = lines.pop() ?? "";
254 // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe.
255 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
256 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
257 }
258 return Effect.forEach(lines, handleLine, { discard: true }).pipe(
259 Effect.andThen(
260 Effect.suspend(() =>
261 settled && lineBuffer.length > 0
262 ? Deferred.succeed(promptReturned, undefined).pipe(Effect.asVoid)
263 : Effect.void,
264 ),
265 ),
266 );
267 }
268 if (event.type === "exited" || event.type === "closed") {
269 return settle(null).pipe(Effect.andThen(Deferred.succeed(promptReturned, undefined)));
270 }
271 return Effect.void;
272 });
273
274 const completion = Deferred.await(done).pipe(
275 // A shell with an empty prompt never prints one; do not wait forever.
276 Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
277 Effect.ensuring(Effect.sync(() => unsubscribe())),
278 );
279 // A startup prompt waits for input on a line that has no newline yet.
280 const flushPartialLine = Effect.suspend(() => {
281 const partial = lineBuffer;
282 lineBuffer = "";
283 return handleLine(partial);
284 });
285 const abandon = settle(null).pipe(
286 Effect.andThen(Deferred.succeed(promptReturned, undefined)),
287 );
288 return { completion, unsubscribe, flushPartialLine, abandon };
289 },
290 );
291
292 // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
293 // shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
294 const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
295 function* (input: {
296 readonly threadId: string;
297 readonly terminalId: string;
298 readonly onStartupPrompt: Effect.Effect<void>;
299 }) {
300 const outcome = yield* Deferred.make<"ready" | "exited">();
301 let reading = false;
302 let carry = "";
303 let busy = false;
304 let activity = 0;
305 const unsubscribe = yield* terminalManager.subscribe((event) => {
306 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
307 return Effect.void;
308 }
309 activity += 1;
310 // A new shell process starts idle; the manager resets its subprocess state without an event.
311 if (event.type === "started" || event.type === "restarted") {
312 busy = false;
313 reading = false;
314 carry = "";
315 }
316 if (event.type === "activity") busy = event.hasRunningSubprocess;
317 if (event.type === "output") {
318 const text = carry + event.data;
319 carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
320 reading = lineEditorReading(text, reading);
321 }
322 if (event.type === "exited" || event.type === "closed") {
323 return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
324 }
325 return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
326 });
327 // A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
328 const quiet = Effect.gen(function* () {
329 while (true) {
330 const seen = activity;
331 yield* Effect.sleep(SHELL_QUIET_FALLBACK);
332 if (activity !== seen) continue;
333 if (!busy) return "ready" as const;
334 yield* input.onStartupPrompt;
335 }
336 });
337 // Restored history can hold a previous shell's line editor state, so only live output counts.
338 const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet));
339 return { wait, unsubscribe };
340 },
341 );
342
343 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
344 "ProjectSetupScriptRunner.runForThread",
345 )(function* (input) {
346 const errorContext = {
347 threadId: input.threadId,
348 worktreePath: input.worktreePath,
349 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
350 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
351 };
352 const suppliedProject = input.project;
353 const projectById =
354 suppliedProject ??
355 (input.projectId
356 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
357 Effect.map(Option.getOrUndefined),
358 Effect.mapError(
359 (cause) =>
360 new ProjectSetupScriptOperationError({
361 ...errorContext,
362 operation: "resolveProject",
363 cause,
364 }),
365 ),
366 )
367 : null);
368 const project =
369 suppliedProject ??
370 projectById ??
371 (input.projectCwd
372 ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
373 Effect.map(Option.getOrUndefined),
374 Effect.mapError(
375 (cause) =>
376 new ProjectSetupScriptOperationError({
377 ...errorContext,
378 operation: "resolveProject",
379 cause,
380 }),
381 ),
382 )
383 : null);
384
385 if (!project) {
386 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
387 }
388
389 const settings = yield* serverSettings.getSettings.pipe(
390 Effect.mapError(
391 (cause) =>
392 new ProjectSetupScriptOperationError({
393 ...errorContext,
394 operation: "readSettings",
395 cause,
396 }),
397 ),
398 );
399 const trigger = input.trigger ?? "setup";
400 const scripts = resolveProjectScripts(settings, project);
401 const script =
402 trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts);
403 if (!script) {
404 return {
405 status: "no-script",
406 } as const;
407 }
408
409 // Earlier settle shells may still run foreground programs; do not type resumed settles into them.
410 const terminalId =
411 input.preferredTerminalId ??
412 (trigger === "settle"
413 ? `settle-${script.id}-${(yield* crypto.randomUUIDv4().pipe(Effect.orDie)).slice(0, 8)}`
414 : `setup-${script.id}`);
415 const cwd = input.worktreePath;
416 const env = {
417 ...projectScriptRuntimeEnv({
418 project: { cwd: project.workspaceRoot },
419 worktreePath: input.worktreePath,
420 }),
421 // Before client attachment, truecolor probes wait for terminal replies nobody can send.
422 COLORTERM: "",
423 };
424 const observe = input.observeCompletion;
425 const completionToken = observe
426 ? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "")
427 : null;
428 const commandLine =
429 observe && completionToken
430 ? wrapCommandForCompletion(
431 script.command,
432 completionShell,
433 completionSentinel(completionToken),
434 )
435 : script.command;
436
437 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
438 const observed =
439 observe && completionToken
440 ? yield* observeTerminalCompletion({
441 threadId: input.threadId,
442 terminalId,
443 sentinel: completionSentinel(completionToken),
444 sentinelPattern: completionSentinelPattern(completionToken),
445 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
446 onOutputLine: observe.onOutputLine,
447 })
448 : undefined;
449 // PowerShell has no line-editor signal; keep its immediate write.
450 const readiness =
451 completionShell === "powershell"
452 ? undefined
453 : yield* watchShellReadiness({
454 threadId: input.threadId,
455 terminalId,
456 onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
457 });
458
459 yield* terminalManager
460 .open({
461 threadId: input.threadId,
462 terminalId,
463 cwd,
464 worktreePath: input.worktreePath,
465 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
466 })
467 .pipe(
468 Effect.mapError(
469 (cause) =>
470 new ProjectSetupScriptOperationError({
471 ...errorContext,
472 operation: "openTerminal",
473 cause,
474 }),
475 ),
476 Effect.onError(() =>
477 Effect.sync(() => {
478 observed?.unsubscribe();
479 readiness?.unsubscribe();
480 }),
481 ),
482 );
483
484 // Return once the terminal exists so callers can show it while a startup prompt waits.
485 yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe(
486 Effect.flatMap((shell) =>
487 shell === "exited"
488 ? Effect.void
489 : terminalManager.write({
490 threadId: input.threadId,
491 terminalId,
492 data: projectScriptTerminalInput(commandLine),
493 }),
494 ),
495 Effect.catchCause((cause) =>
496 Effect.logWarning("project script command was not written", {
497 ...errorContext,
498 terminalId,
499 cause,
500 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
501 ),
502 Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())),
503 Effect.forkIn(serviceScope),
504 );
505
506 const completion = observed?.completion.pipe(
507 Effect.tap(({ exitCode }) =>
508 exitCode === 0
509 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
510 : Effect.void,
511 ),
512 );
513
514 return {
515 status: "started",
516 scriptId: script.id,
517 scriptName: script.name,
518 scriptCommand: script.command,
519 terminalId,
520 cwd,
521 async: script.async !== false,
522 ...(completion ? { completion } : {}),
523 } as const;
524 });
525
526 return ProjectSetupScriptRunner.of({ runForThread });
527});
528
529export const layer = Layer.effect(ProjectSetupScriptRunner, make);