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