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

ProjectSetupScriptRunner.ts

550 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 preferredTerminalId?: string;
70 readonly trigger?: "setup" | "settle";
71 readonly project?: {
72 readonly id: ProjectId;
73 readonly workspaceRoot: string;
74 readonly scripts: ReadonlyArray<ProjectScript>;
75 };
76 readonly observeCompletion?: {
77 readonly onOutputLine?: (line: string) => Effect.Effect<void>;
78 };
80​
81export class ProjectSetupScriptOperationError extends Schema.TaggedError<ProjectSetupScriptOperationError>()(
82 "ProjectSetupScriptOperationError",
83 {
84 threadId: Schema.String,
85 projectId: Schema.optional(Schema.String),
86 projectCwd: Schema.optional(Schema.String),
87 worktreePath: Schema.String,
88 operation: Schema.Literals(["readThread", "resolveProject", "readSettings", "openTerminal"]),
89 cause: Schema.Defect(),
90 },
91) {
92 override get message(): string {
93 return `Project setup script operation '${this.operation}' failed for thread '${this.threadId}' in '${this.worktreePath}'.`;
94 }
96​
97export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<ProjectSetupScriptProjectNotFoundError>()(
98 "ProjectSetupScriptProjectNotFoundError",
99 {
100 threadId: Schema.String,
101 projectId: Schema.optional(Schema.String),
102 projectCwd: Schema.optional(Schema.String),
103 worktreePath: Schema.String,
104 },
105) {
106 override get message(): string {
107 return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;
108 }
110​
111export const ProjectSetupScriptRunnerError = Schema.Union([
112 ProjectSetupScriptOperationError,
113 ProjectSetupScriptProjectNotFoundError,
114]);
115export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
116​
117export class ProjectSetupScriptRunner extends Context.Service<
118 ProjectSetupScriptRunner,
119 {
120 readonly runForThread: (
121 input: ProjectSetupScriptRunnerInput,
122 ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;
123 }
124>()("t3/project/ProjectSetupScriptRunner") {}
125​
126/** @public */
127// Random per-run tokens prevent script output from spoofing completion.
128const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__";
129const OUTPUT_LINE_MAX_LENGTH = 400;
130const PARTIAL_LINE_MAX_LENGTH = 4_096;
131​
132function completionSentinel(token: string): string {
133 return `${COMPLETION_SENTINEL_PREFIX}_${token}:`;
135​
136function completionSentinelPattern(token: string): RegExp {
137 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
139​
140function stripTerminalControl(text: string): string {
141 return text
142 .replace(
143 /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
144 "",
145 )
146 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
148​
149// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command.
150const BRACKETED_PASTE_ON = "\x1b[?2004h";
151const BRACKETED_PASTE_OFF = "\x1b[?2004l";
152// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first.
153const SHELL_QUIET_FALLBACK = "3 seconds";
154​
155function lineEditorReading(text: string, previous: boolean): boolean {
156 const on = text.lastIndexOf(BRACKETED_PASTE_ON);
157 const off = text.lastIndexOf(BRACKETED_PASTE_OFF);
158 return on === off ? previous : on > off;
160​
161type CompletionShell = "posix" | "fish" | "powershell";
162​
163function resolveCompletionShell(
164 platform: NodeJS.Platform,
165 env: NodeJS.ProcessEnv,
166): CompletionShell {
167 if (platform === "win32") return "powershell";
168 const shell = env.SHELL ?? "";
169 const name = shell.split("/").at(-1) ?? shell;
170 if (name === "fish") return "fish";
171 if (name === "pwsh" || name === "powershell") return "powershell";
172 return "posix";
174​
175// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin.
176function wrapCommandForCompletion(
177 command: string,
178 shell: CompletionShell,
179 sentinel: string,
180): string {
181 const body = command.replace(/\r?\n/g, "\r");
182 switch (shell) {
183 case "powershell":
184 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
185 case "fish":
186 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
187 case "posix":
188 return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`;
189 }
191​
192/** @public */
193export const make = Effect.gen(function* () {
194 const projects = yield* ProjectService.ProjectService;
195 const threads = yield* ProjectionStore.ProjectionStoreV2;
196 const terminalManager = yield* TerminalManager.TerminalManager;
197 const serverSettings = yield* ServerSettings.ServerSettingsService;
198 const crypto = yield* Crypto.Crypto;
199 const serviceScope = yield* Effect.scope;
200 const completionShell = resolveCompletionShell(
201 yield* HostProcess.Platform,
202 yield* HostProcess.Environment,
203 );
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 input.preferredTerminalId ??
433 (trigger === "settle"
434 ? `settle-${script.id}-${(yield* crypto.randomUUIDv4().pipe(Effect.orDie)).slice(0, 8)}`
435 : `setup-${script.id}`);
436 const cwd = input.worktreePath;
437 const env = {
438 ...projectScriptRuntimeEnv({
439 project: { cwd: project.workspaceRoot },
440 worktreePath: input.worktreePath,
441 }),
442 // Before client attachment, truecolor probes wait for terminal replies nobody can send.
443 COLORTERM: "",
444 };
445 const observe = input.observeCompletion;
446 const completionToken = observe
447 ? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "")
448 : null;
449 const commandLine =
450 observe && completionToken
451 ? wrapCommandForCompletion(
452 script.command,
453 completionShell,
454 completionSentinel(completionToken),
455 )
456 : script.command;
457​
458 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
459 const observed =
460 observe && completionToken
461 ? yield* observeTerminalCompletion({
462 threadId: input.threadId,
463 terminalId,
464 sentinel: completionSentinel(completionToken),
465 sentinelPattern: completionSentinelPattern(completionToken),
466 echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
467 onOutputLine: observe.onOutputLine,
468 })
469 : undefined;
470 // PowerShell has no line-editor signal; keep its immediate write.
471 const readiness =
472 completionShell === "powershell"
473 ? undefined
474 : yield* watchShellReadiness({
475 threadId: input.threadId,
476 terminalId,
477 onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
478 });
479​
480 yield* terminalManager
481 .open({
482 threadId: input.threadId,
483 terminalId,
484 cwd,
485 worktreePath: input.worktreePath,
486 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
487 })
488 .pipe(
489 Effect.mapError(
490 (cause) =>
491 new ProjectSetupScriptOperationError({
492 ...errorContext,
493 operation: "openTerminal",
494 cause,
495 }),
496 ),
497 Effect.onError(() =>
498 Effect.sync(() => {
499 observed?.unsubscribe();
500 readiness?.unsubscribe();
501 }),
502 ),
503 );
504​
505 // Return once the terminal exists so callers can show it while a startup prompt waits.
506 yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe(
507 Effect.flatMap((shell) =>
508 shell === "exited"
509 ? Effect.void
510 : terminalManager.write({
511 threadId: input.threadId,
512 terminalId,
513 data: projectScriptTerminalInput(commandLine),
514 }),
515 ),
516 Effect.catchCause((cause) =>
517 Effect.logWarning("project script command was not written", {
518 ...errorContext,
519 terminalId,
520 cause,
521 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
522 ),
523 Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())),
524 Effect.forkIn(serviceScope),
525 );
526​
527 const completion = observed?.completion.pipe(
528 Effect.tap(({ exitCode }) =>
529 exitCode === 0
530 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
531 : Effect.void,
532 ),
533 );
534​
535 return {
536 status: "started",
537 scriptId: script.id,
538 scriptName: script.name,
539 scriptCommand: script.command,
540 terminalId,
541 cwd,
542 async: script.async !== false,
543 ...(completion ? { completion } : {}),
544 } as const;
545 });
546​
547 return ProjectSetupScriptRunner.of({ runForThread });
548});
549​
550export const layer = Layer.effect(ProjectSetupScriptRunner, make);