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

ProjectSetupScriptRunner.ts

548 lines19.5 KB

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