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

ProjectSetupScriptRunner.ts

567 lines20.6 KB

1import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts";
2import {
3 projectScriptRuntimeEnv,
4 projectScriptTerminalInput,
5 resolveProjectScripts,
6 settleProjectScript,
7 setupProjectScript,
8} from "@t3tools/shared/projectScripts";
9​
10import * as Clock from "effect/Clock";
11import * as Context from "effect/Context";
12import * as SecureRandom from "effect/crypto/SecureRandom";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18​
19import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
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";
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>;
39​
40export interface ProjectSetupScriptCompletion {
41 readonly exitCode: number | null;
42 readonly durationMs: number;
44​
45export interface ProjectSetupScriptOutputLine {
46 readonly line: string;
48​
49/**
50 * A thread a link below full access started does not run this project's setup
51 * script: the script is the user's own code, and such a link only grants T3's
52 * tools (see `mcp/linkOrigin.ts`).
53 */
54export interface ProjectSetupScriptRunnerResultSkippedForLink {
55 readonly status: "skipped-for-link";
57​
58export type ProjectSetupScriptRunnerResult =
59 | ProjectSetupScriptRunnerResultNoScript
60 | ProjectSetupScriptRunnerResultSkippedForLink
61 | ProjectSetupScriptRunnerResultStarted;
62​
63export interface ProjectSetupScriptRunnerInput {
64 readonly threadId: string;
65 readonly projectId?: string;
66 readonly projectCwd?: string;
67 readonly worktreePath: string;
68 readonly trigger?: "setup" | "settle";
69 readonly project?: {
70 readonly id: ProjectId;
71 readonly workspaceRoot: string;
72 readonly scripts: ReadonlyArray<ProjectScript>;
73 };
74 readonly observeCompletion?: {
75 readonly onOutputLine?: (line: string) => Effect.Effect<void>;
76 };
78​
79export class ProjectSetupScriptOperationError extends Schema.TaggedError<ProjectSetupScriptOperationError>()(
80 "ProjectSetupScriptOperationError",
81 {
82 threadId: Schema.String,
83 projectId: Schema.optional(Schema.String),
84 projectCwd: Schema.optional(Schema.String),
85 worktreePath: Schema.String,
86 operation: Schema.Literals(["readThread", "resolveProject", "readSettings", "openTerminal"]),
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 return `Project setup script operation '${this.operation}' failed for thread '${this.threadId}' in '${this.worktreePath}'.`;
92 }
94​
95export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<ProjectSetupScriptProjectNotFoundError>()(
96 "ProjectSetupScriptProjectNotFoundError",
97 {
98 threadId: Schema.String,
99 projectId: Schema.optional(Schema.String),
100 projectCwd: Schema.optional(Schema.String),
101 worktreePath: Schema.String,
102 },
103) {
104 override get message(): string {
105 return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;
106 }
108​
109export class ProjectSetupScriptUnsupportedShellError extends Schema.TaggedError<ProjectSetupScriptUnsupportedShellError>()(
110 "ProjectSetupScriptUnsupportedShellError",
111 { shell: Schema.String },
112) {
113 override get message(): string {
114 return "Project script completion is not supported in cmd.exe. Install PowerShell and retry.";
115 }
117​
118export const ProjectSetupScriptRunnerError = Schema.Union([
119 ProjectSetupScriptOperationError,
120 ProjectSetupScriptProjectNotFoundError,
121 ProjectSetupScriptUnsupportedShellError,
122]);
123export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
124​
125export class ProjectSetupScriptRunner extends Context.Service<
126 ProjectSetupScriptRunner,
127 {
128 readonly runForThread: (
129 input: ProjectSetupScriptRunnerInput,
130 ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;
131 }
132>()("t3/project/ProjectSetupScriptRunner") {}
133​
134/** @public */
135// Random per-run tokens prevent script output from spoofing completion.
136const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__";
137const OUTPUT_LINE_MAX_LENGTH = 400;
138const PARTIAL_LINE_MAX_LENGTH = 4_096;
139​
140function completionSentinel(token: string): string {
141 return `${COMPLETION_SENTINEL_PREFIX}_${token}:`;
143​
144function completionSentinelPattern(token: string): RegExp {
145 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
147​
148function stripTerminalControl(text: string): string {
149 return text
150 .replace(
151 /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
152 "",
153 )
154 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
156​
157// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command.
158const BRACKETED_PASTE_ON = "\x1b[?2004h";
159const BRACKETED_PASTE_OFF = "\x1b[?2004l";
160// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first.
161const SHELL_QUIET_FALLBACK = "3 seconds";
162​
163function lineEditorReading(text: string, previous: boolean): boolean {
164 const on = text.lastIndexOf(BRACKETED_PASTE_ON);
165 const off = text.lastIndexOf(BRACKETED_PASTE_OFF);
166 return on === off ? previous : on > off;
168​
169type CompletionShell = "posix" | "fish" | "powershell";
170​
171function resolveCompletionShell(shell: string): CompletionShell | null {
172 const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, "");
173 if (name === "cmd") return null;
174 if (name === "fish") return "fish";
175 if (name === "pwsh" || name === "powershell") return "powershell";
176 return "posix";
178​
179// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
180function wrapCommandForCompletion(
181 command: string,
182 shell: CompletionShell,
183 sentinel: string,
184): string {
185 const body = command.replace(/\r?\n/g, "\r");
186 switch (shell) {
187 case "powershell":
188 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
189 case "fish":
190 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
191 case "posix":
192 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
193 }
195​
196/** @public */
197export const make = Effect.gen(function* () {
198 const projects = yield* ProjectService.ProjectService;
199 const threads = yield* ProjectionStore.ProjectionStoreV2;
200 const terminalManager = yield* TerminalManager.TerminalManager;
201 const serverSettings = yield* ServerSettings.ServerSettingsService;
202 const random = yield* SecureRandom.SecureRandom;
203 const serviceScope = yield* Effect.scope;
204​
205 const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
206 function* (input: {
207 readonly threadId: string;
208 readonly terminalId: string;
209 readonly sentinel: string;
210 readonly sentinelPattern: RegExp;
211 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
212 readonly echoedWrapperLines: ReadonlyArray<string>;
213 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
214 }) {
215 const startedAtMs = yield* Clock.currentTimeMillis;
216 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
217 // Wait for the prompt redraw; closing earlier mistakes it for activity and preserves an idle shell.
218 const promptReturned = yield* Deferred.make<void>();
219 let lineBuffer = "";
220 let settled = false;
221​
222 const settle = (exitCode: number | null) =>
223 Effect.suspend(() => {
224 if (settled) return Effect.void;
225 settled = true;
226 return Clock.currentTimeMillis.pipe(
227 Effect.flatMap((nowMs) =>
228 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
229 ),
230 Effect.asVoid,
231 );
232 });
233​
234 const handleLine = (rawLine: string) =>
235 Effect.suspend(() => {
236 const sentinel = input.sentinelPattern.exec(rawLine);
237 if (sentinel) {
238 const parsed = Number(sentinel[1]);
239 return settle(Number.isFinite(parsed) ? parsed : null);
240 }
241 const cleaned = stripTerminalControl(rawLine).trimEnd();
242 if (
243 cleaned.length === 0 ||
244 cleaned.includes(input.sentinel) ||
245 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
246 input.onOutputLine === undefined
247 ) {
248 return Effect.void;
249 }
250 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
251 });
252​
253 const unsubscribe = yield* terminalManager.subscribe((event) => {
254 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
255 return Effect.void;
256 }
257 if (event.type === "output") {
258 lineBuffer += event.data;
259 // Bare CR redraws progress in place; split redraws instead of growing one line.
260 const lines = lineBuffer.split(/\r\n|\r|\n/);
261 lineBuffer = lines.pop() ?? "";
262 // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe.
263 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
264 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
265 }
266 return Effect.forEach(lines, handleLine, { discard: true }).pipe(
267 Effect.andThen(
268 Effect.suspend(() =>
269 settled && lineBuffer.length > 0
270 ? Deferred.succeed(promptReturned, undefined).pipe(Effect.asVoid)
271 : Effect.void,
272 ),
273 ),
274 );
275 }
276 if (event.type === "exited" || event.type === "closed") {
277 return settle(null).pipe(Effect.andThen(Deferred.succeed(promptReturned, undefined)));
278 }
279 return Effect.void;
280 });
281​
282 const completion = Deferred.await(done).pipe(
283 // A shell with an empty prompt never prints one; do not wait forever.
284 Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
285 Effect.ensuring(Effect.sync(() => unsubscribe())),
286 );
287 // A startup prompt waits for input on a line that has no newline yet.
288 const flushPartialLine = Effect.suspend(() => {
289 const partial = lineBuffer;
290 lineBuffer = "";
291 return handleLine(partial);
292 });
293 const abandon = settle(null).pipe(
294 Effect.andThen(Deferred.succeed(promptReturned, undefined)),
295 );
296 return { completion, unsubscribe, flushPartialLine, abandon };
297 },
298 );
299​
300 // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
301 // shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
302 const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
303 function* (input: {
304 readonly threadId: string;
305 readonly terminalId: string;
306 readonly onStartupPrompt: Effect.Effect<void>;
307 }) {
308 const outcome = yield* Deferred.make<"ready" | "exited">();
309 let reading = false;
310 let carry = "";
311 let busy = false;
312 let activity = 0;
313 const unsubscribe = yield* terminalManager.subscribe((event) => {
314 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
315 return Effect.void;
316 }
317 activity += 1;
318 // A new shell process starts idle; the manager resets its subprocess state without an event.
319 if (event.type === "started" || event.type === "restarted") {
320 busy = false;
321 reading = false;
322 carry = "";
323 }
324 if (event.type === "activity") busy = event.hasRunningSubprocess;
325 if (event.type === "output") {
326 const text = carry + event.data;
327 carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
328 reading = lineEditorReading(text, reading);
329 }
330 if (event.type === "exited" || event.type === "closed") {
331 return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
332 }
333 return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
334 });
335 // A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
336 const quiet = Effect.gen(function* () {
337 while (true) {
338 const seen = activity;
339 yield* Effect.sleep(SHELL_QUIET_FALLBACK);
340 if (activity !== seen) continue;
341 if (!busy) return "ready" as const;
342 yield* input.onStartupPrompt;
343 }
344 });
345 // Restored history can hold a previous shell's line editor state, so only live output counts.
346 const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet));
347 return { wait, unsubscribe };
348 },
349 );
350​
351 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
352 "ProjectSetupScriptRunner.runForThread",
353 )(function* (input) {
354 const errorContext = {
355 threadId: input.threadId,
356 worktreePath: input.worktreePath,
357 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
358 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
359 };
360 // A thread whose origin cannot be read might be a link's: run nothing.
361 const thread = yield* threads.getThreadShell(ThreadId.make(input.threadId)).pipe(
362 Effect.mapError(
363 (cause) =>
364 new ProjectSetupScriptOperationError({
365 ...errorContext,
366 operation: "readThread",
367 cause,
368 }),
369 ),
370 );
371 if (thread?.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin))
372 return { status: "skipped-for-link" } as const;
373 const suppliedProject = input.project;
374 const projectById =
375 suppliedProject ??
376 (input.projectId
377 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
378 Effect.map(Option.getOrUndefined),
379 Effect.mapError(
380 (cause) =>
381 new ProjectSetupScriptOperationError({
382 ...errorContext,
383 operation: "resolveProject",
384 cause,
385 }),
386 ),
387 )
388 : null);
389 const project =
390 suppliedProject ??
391 projectById ??
392 (input.projectCwd
393 ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
394 Effect.map(Option.getOrUndefined),
395 Effect.mapError(
396 (cause) =>
397 new ProjectSetupScriptOperationError({
398 ...errorContext,
399 operation: "resolveProject",
400 cause,
401 }),
402 ),
403 )
404 : null);
405​
406 if (!project) {
407 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
408 }
409​
410 const settings = yield* serverSettings.getSettings.pipe(
411 Effect.mapError(
412 (cause) =>
413 new ProjectSetupScriptOperationError({
414 ...errorContext,
415 operation: "readSettings",
416 cause,
417 }),
418 ),
419 );
420 const trigger = input.trigger ?? "setup";
421 const scripts = resolveProjectScripts(settings, project);
422 const script =
423 trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts);
424 if (!script) {
425 return {
426 status: "no-script",
427 } as const;
428 }
429​
430 // Earlier settle shells may still run foreground programs; do not type resumed settles into them.
431 const terminalId =
432 trigger === "settle"
433 ? `settle-${script.id}-${(yield* random.uuidV4()).slice(0, 8)}`
434 : `setup-${script.id}`;
435 const cwd = input.worktreePath;
436 const env = {
437 ...projectScriptRuntimeEnv({
438 project: { cwd: project.workspaceRoot },
439 worktreePath: input.worktreePath,
440 }),
441 // Before client attachment, truecolor probes wait for terminal replies nobody can send.
442 COLORTERM: "",
443 };
444 const observe = input.observeCompletion;
445 const completionToken = observe ? (yield* random.uuidV4()).replaceAll("-", "") : null;
446 const echoedWrapperLines: string[] = [];
447 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
448 const observed =
449 observe && completionToken
450 ? yield* observeTerminalCompletion({
451 threadId: input.threadId,
452 terminalId,
453 sentinel: completionSentinel(completionToken),
454 sentinelPattern: completionSentinelPattern(completionToken),
455 echoedWrapperLines,
456 onOutputLine: observe.onOutputLine,
457 })
458 : undefined;
459 const readiness = yield* watchShellReadiness({
460 threadId: input.threadId,
461 terminalId,
462 onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
463 });
464 const { completionShell, commandLine } = yield* Effect.gen(function* () {
465 const shell = yield* terminalManager
466 .open({
467 threadId: input.threadId,
468 terminalId,
469 stopOnSettle: script.stopOnSettle ?? false,
470 cwd,
471 worktreePath: input.worktreePath,
472 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
473 })
474 .pipe(
475 Effect.andThen(() =>
476 terminalManager
477 .getShell({ threadId: input.threadId, terminalId })
478 .pipe(Effect.catchTags({ TerminalNotRunningError: () => Effect.succeed(null) })),
479 ),
480 Effect.mapError(
481 (cause) =>
482 new ProjectSetupScriptOperationError({
483 ...errorContext,
484 operation: "openTerminal",
485 cause,
486 }),
487 ),
488 );
489 if (shell === null) {
490 yield* observed?.abandon ?? Effect.void;
491 return { completionShell: null, commandLine: null };
492 }
493 const completionShell = resolveCompletionShell(shell);
494 let commandLine = script.command;
495 if (observe && completionToken) {
496 if (completionShell === null) {
497 yield* terminalManager.closeIdle({ threadId: input.threadId, terminalId });
498 return yield* new ProjectSetupScriptUnsupportedShellError({ shell });
499 }
500 commandLine = wrapCommandForCompletion(
501 script.command,
502 completionShell,
503 completionSentinel(completionToken),
504 );
505 }
506 echoedWrapperLines.push(...commandLine.split("\r").filter((line) => line.length > 0));
507 return { completionShell, commandLine };
508 }).pipe(
509 Effect.onError(() =>
510 Effect.sync(() => {
511 observed?.unsubscribe();
512 readiness.unsubscribe();
513 }),
514 ),
515 );
516​
517 // Return once the terminal exists so callers can show it while a startup prompt waits.
518 // PowerShell and cmd have no line-editor signal.
519 yield* (
520 completionShell === "posix" || completionShell === "fish"
521 ? readiness.wait
522 : Effect.succeed("ready" as const)
523 ).pipe(
524 Effect.flatMap((shell) =>
525 shell === "exited" || commandLine === null
526 ? Effect.void
527 : terminalManager.write({
528 threadId: input.threadId,
529 terminalId,
530 data: projectScriptTerminalInput(commandLine),
531 }),
532 ),
533 Effect.catchCause((cause) =>
534 Effect.logWarning("project script command was not written", {
535 ...errorContext,
536 terminalId,
537 cause,
538 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
539 ),
540 Effect.ensuring(Effect.sync(() => readiness.unsubscribe())),
541 Effect.forkIn(serviceScope),
542 );
543​
544 const completion = observed?.completion.pipe(
545 Effect.tap(({ exitCode }) =>
546 exitCode === 0
547 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
548 : Effect.void,
549 ),
550 );
551​
552 return {
553 status: "started",
554 scriptId: script.id,
555 scriptName: script.name,
556 scriptCommand: script.command,
557 terminalId,
558 cwd,
559 async: script.async !== false,
560 ...(completion ? { completion } : {}),
561 } as const;
562 });
563​
564 return ProjectSetupScriptRunner.of({ runForThread });
565});
566​
567export const layer = Layer.effect(ProjectSetupScriptRunner, make);