Open History to see the last commit
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";
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
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";
56}
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 };
77}
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 }
93}
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 }
107}
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 }
116}
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}:`;
142}
143
144function completionSentinelPattern(token: string): RegExp {
145 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
146}
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, "");
155}
156
157// Line editors (zsh, fish, nu, 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;
167}
168
169type CompletionShell = "posix" | "fish" | "nushell" | "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 === "nu") return "nushell";
176 if (name === "pwsh" || name === "powershell") return "powershell";
177 return "posix";
178}
179
180const utf8 = new TextEncoder();
181// Canonical TTY input (before a line editor starts reading) caps a line below 1 KiB on Linux.
182const POSIX_MAX_LINE_BYTES = 1_023;
183const POSIX_APPEND = '__t3_command="$__t3_command"';
184
185function encodePosixScript(text: string): string {
186 let encoded = "";
187 for (const character of text) {
188 const code = character.charCodeAt(0);
189 if (character === "'") {
190 encoded += "'\\''";
191 } else if (character === "\\" || code <= 0x1f || code === 0x7f) {
192 encoded += `\\0${code.toString(8).padStart(3, "0")}`;
193 } else {
194 encoded += character;
195 }
196 }
197 return encoded;
198}
199
200// Line editors run each submitted line on its own, so every line must be a complete command.
201function wrapPosixCommand(command: string, sentinel: string): string {
202 const normalized = command.replace(/\r\n/g, "\n");
203 // The `_` suffix keeps trailing newlines; the subshell contains exits and syntax errors.
204 const evaluate = (payload: string) =>
205 `( __t3_command=$(printf '%b_' ${payload}); eval "\${__t3_command%_}" ); printf '\\n${sentinel}%s\\n' "$?"`;
206 const inline = evaluate(`'${encodePosixScript(normalized)}'`);
207 if (utf8.encode(` ${inline}\r`).byteLength <= POSIX_MAX_LINE_BYTES) return inline;
208
209 const maxChunkBytes = POSIX_MAX_LINE_BYTES - utf8.encode(` ${POSIX_APPEND}''\r`).byteLength;
210 const lines: string[] = [];
211 let prefix = "__t3_command=";
212 let chunk = "";
213 let chunkBytes = 0;
214 for (const character of normalized) {
215 const encoded = encodePosixScript(character);
216 const bytes = utf8.encode(encoded).byteLength;
217 if (chunkBytes + bytes > maxChunkBytes) {
218 lines.push(`${prefix}'${chunk}'`);
219 prefix = POSIX_APPEND;
220 chunk = "";
221 chunkBytes = 0;
222 }
223 chunk += encoded;
224 chunkBytes += bytes;
225 }
226 lines.push(`${prefix}'${chunk}'`, `${evaluate('"$__t3_command"')}; unset __t3_command`);
227 // The leading space gives every line the history suppression a short command gets.
228 return lines.join("\r ");
229}
230
231function wrapCommandForCompletion(
232 command: string,
233 shell: CompletionShell,
234 sentinel: string,
235): string {
236 const body = command.replace(/\r?\n/g, "\r");
237 switch (shell) {
238 case "powershell":
239 return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`;
240 case "fish":
241 return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`;
242 case "nushell": {
243 const escaped = command.replace(/["\\\x00-\x1f]/g, (char) =>
244 char === '"' || char === "\\" ? `\\${char}` : `\\u{${char.charCodeAt(0).toString(16)}}`,
245 );
246 // Nu resolves imports before running cd; source a file rooted in the worktree.
247 return [
248 "$env.LAST_EXIT_CODE = 0",
249 "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }",
250 `if $__t3f == null { $env.LAST_EXIT_CODE = 1 } else { try { [$"rm --permanent ($__t3f | to nuon)" "${escaped}"] | str join (char newline) | save --force --raw $__t3f; ^$nu.current-exe --login --commands $"cd $env.T3CODE_WORKTREE_PATH; source ($__t3f | to nuon)" } catch {|e| if $e != null and $e.exit_code? == null { print -e $e.msg }; if $env.LAST_EXIT_CODE == 0 { $env.LAST_EXIT_CODE = 1 } } }`,
251 "let __t3c = $env.LAST_EXIT_CODE",
252 "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }",
253 `print $"\\n${sentinel}($__t3c)"`,
254 ].join("; ");
255 }
256 case "posix":
257 return wrapPosixCommand(command, sentinel);
258 }
259}
260
261/** @public */
262export const make = Effect.gen(function* () {
263 const projects = yield* ProjectService.ProjectService;
264 const threads = yield* ProjectionStore.ProjectionStoreV2;
265 const terminalManager = yield* TerminalManager.TerminalManager;
266 const serverSettings = yield* ServerSettings.ServerSettingsService;
267 const random = yield* SecureRandom.SecureRandom;
268 const serviceScope = yield* Effect.scope;
269
270 const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
271 function* (input: {
272 readonly threadId: string;
273 readonly terminalId: string;
274 readonly sentinel: string;
275 readonly sentinelPattern: RegExp;
276 /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
277 readonly echoedWrapperLines: ReadonlyArray<string>;
278 readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
279 }) {
280 const startedAtMs = yield* Clock.currentTimeMillis;
281 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
282 // Wait for the prompt redraw; closing earlier mistakes it for activity and preserves an idle shell.
283 const promptReturned = yield* Deferred.make<void>();
284 let lineBuffer = "";
285 let settled = false;
286
287 const settle = (exitCode: number | null) =>
288 Effect.suspend(() => {
289 if (settled) return Effect.void;
290 settled = true;
291 return Clock.currentTimeMillis.pipe(
292 Effect.flatMap((nowMs) =>
293 Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
294 ),
295 Effect.asVoid,
296 );
297 });
298
299 const handleLine = (rawLine: string) =>
300 Effect.suspend(() => {
301 const sentinel = input.sentinelPattern.exec(rawLine);
302 if (sentinel) {
303 const parsed = Number(sentinel[1]);
304 return settle(Number.isFinite(parsed) ? parsed : null);
305 }
306 const cleaned = stripTerminalControl(rawLine).trimEnd();
307 if (
308 cleaned.length === 0 ||
309 cleaned.includes(input.sentinel) ||
310 input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
311 input.onOutputLine === undefined
312 ) {
313 return Effect.void;
314 }
315 return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
316 });
317
318 const unsubscribe = yield* terminalManager.subscribe((event) => {
319 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
320 return Effect.void;
321 }
322 if (event.type === "output") {
323 lineBuffer += event.data;
324 // Bare CR redraws progress in place; split redraws instead of growing one line.
325 const lines = lineBuffer.split(/\r\n|\r|\n/);
326 lineBuffer = lines.pop() ?? "";
327 // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe.
328 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
329 lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);
330 }
331 return Effect.forEach(lines, handleLine, { discard: true }).pipe(
332 Effect.andThen(
333 Effect.suspend(() =>
334 settled && lineBuffer.length > 0
335 ? Deferred.succeed(promptReturned, undefined).pipe(Effect.asVoid)
336 : Effect.void,
337 ),
338 ),
339 );
340 }
341 if (event.type === "exited" || event.type === "closed") {
342 return settle(null).pipe(Effect.andThen(Deferred.succeed(promptReturned, undefined)));
343 }
344 return Effect.void;
345 });
346
347 const completion = Deferred.await(done).pipe(
348 // A shell with an empty prompt never prints one; do not wait forever.
349 Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
350 Effect.ensuring(Effect.sync(() => unsubscribe())),
351 );
352 // A startup prompt waits for input on a line that has no newline yet.
353 const flushPartialLine = Effect.suspend(() => {
354 const partial = lineBuffer;
355 lineBuffer = "";
356 return handleLine(partial);
357 });
358 const abandon = settle(null).pipe(
359 Effect.andThen(Deferred.succeed(promptReturned, undefined)),
360 );
361 return { completion, unsubscribe, flushPartialLine, abandon };
362 },
363 );
364
365 // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
366 // shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
367 const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
368 function* (input: {
369 readonly threadId: string;
370 readonly terminalId: string;
371 readonly onStartupPrompt: Effect.Effect<void>;
372 }) {
373 const outcome = yield* Deferred.make<"ready" | "exited">();
374 let reading = false;
375 let carry = "";
376 let busy = false;
377 let activity = 0;
378 const unsubscribe = yield* terminalManager.subscribe((event) => {
379 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
380 return Effect.void;
381 }
382 activity += 1;
383 // A new shell process starts idle; the manager resets its subprocess state without an event.
384 if (event.type === "started" || event.type === "restarted") {
385 busy = false;
386 reading = false;
387 carry = "";
388 }
389 if (event.type === "activity") busy = event.hasRunningSubprocess;
390 if (event.type === "output") {
391 const text = carry + event.data;
392 carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
393 reading = lineEditorReading(text, reading);
394 }
395 if (event.type === "exited" || event.type === "closed") {
396 return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
397 }
398 return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
399 });
400 // A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
401 const quiet = Effect.gen(function* () {
402 while (true) {
403 const seen = activity;
404 yield* Effect.sleep(SHELL_QUIET_FALLBACK);
405 if (activity !== seen) continue;
406 if (!busy) return "ready" as const;
407 yield* input.onStartupPrompt;
408 }
409 });
410 // Restored history can hold a previous shell's line editor state, so only live output counts.
411 const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet));
412 return { wait, unsubscribe };
413 },
414 );
415
416 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
417 "ProjectSetupScriptRunner.runForThread",
418 )(function* (input) {
419 const errorContext = {
420 threadId: input.threadId,
421 worktreePath: input.worktreePath,
422 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
423 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
424 };
425 // A thread whose origin cannot be read might be a link's: run nothing.
426 const thread = yield* threads.getThreadShell(ThreadId.make(input.threadId)).pipe(
427 Effect.mapError(
428 (cause) =>
429 new ProjectSetupScriptOperationError({
430 ...errorContext,
431 operation: "readThread",
432 cause,
433 }),
434 ),
435 );
436 if (thread?.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin))
437 return { status: "skipped-for-link" } as const;
438 const suppliedProject = input.project;
439 const projectById =
440 suppliedProject ??
441 (input.projectId
442 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
443 Effect.map(Option.getOrUndefined),
444 Effect.mapError(
445 (cause) =>
446 new ProjectSetupScriptOperationError({
447 ...errorContext,
448 operation: "resolveProject",
449 cause,
450 }),
451 ),
452 )
453 : null);
454 const project =
455 suppliedProject ??
456 projectById ??
457 (input.projectCwd
458 ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
459 Effect.map(Option.getOrUndefined),
460 Effect.mapError(
461 (cause) =>
462 new ProjectSetupScriptOperationError({
463 ...errorContext,
464 operation: "resolveProject",
465 cause,
466 }),
467 ),
468 )
469 : null);
470
471 if (!project) {
472 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
473 }
474
475 const settings = yield* serverSettings.getSettings.pipe(
476 Effect.mapError(
477 (cause) =>
478 new ProjectSetupScriptOperationError({
479 ...errorContext,
480 operation: "readSettings",
481 cause,
482 }),
483 ),
484 );
485 const trigger = input.trigger ?? "setup";
486 const scripts = resolveProjectScripts(settings, project);
487 const script =
488 trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts);
489 if (!script) {
490 return {
491 status: "no-script",
492 } as const;
493 }
494
495 // Earlier settle shells may still run foreground programs; do not type resumed settles into them.
496 const terminalId =
497 trigger === "settle"
498 ? `settle-${script.id}-${(yield* random.uuidV4()).slice(0, 8)}`
499 : `setup-${script.id}`;
500 const cwd = input.worktreePath;
501 const env = {
502 ...projectScriptRuntimeEnv({
503 project: { cwd: project.workspaceRoot },
504 worktreePath: input.worktreePath,
505 }),
506 // Before client attachment, truecolor probes wait for terminal replies nobody can send.
507 COLORTERM: "",
508 };
509 const observe = input.observeCompletion;
510 const completionToken = observe ? (yield* random.uuidV4()).replaceAll("-", "") : null;
511 const echoedWrapperLines: string[] = [];
512 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
513 const observed =
514 observe && completionToken
515 ? yield* observeTerminalCompletion({
516 threadId: input.threadId,
517 terminalId,
518 sentinel: completionSentinel(completionToken),
519 sentinelPattern: completionSentinelPattern(completionToken),
520 echoedWrapperLines,
521 onOutputLine: observe.onOutputLine,
522 })
523 : undefined;
524 const readiness = yield* watchShellReadiness({
525 threadId: input.threadId,
526 terminalId,
527 onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
528 });
529 const { completionShell, commandLine } = yield* Effect.gen(function* () {
530 const shell = yield* terminalManager
531 .open({
532 threadId: input.threadId,
533 terminalId,
534 stopOnSettle: script.stopOnSettle ?? false,
535 cwd,
536 worktreePath: input.worktreePath,
537 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
538 })
539 .pipe(
540 Effect.andThen(() =>
541 terminalManager
542 .getShell({ threadId: input.threadId, terminalId })
543 .pipe(Effect.catchTags({ TerminalNotRunningError: () => Effect.succeed(null) })),
544 ),
545 Effect.mapError(
546 (cause) =>
547 new ProjectSetupScriptOperationError({
548 ...errorContext,
549 operation: "openTerminal",
550 cause,
551 }),
552 ),
553 );
554 if (shell === null) {
555 yield* observed?.abandon ?? Effect.void;
556 return { completionShell: null, commandLine: null };
557 }
558 const completionShell = resolveCompletionShell(shell);
559 let commandLine = script.command;
560 if (observe && completionToken) {
561 if (completionShell === null) {
562 yield* terminalManager.closeIdle({ threadId: input.threadId, terminalId });
563 return yield* new ProjectSetupScriptUnsupportedShellError({ shell });
564 }
565 commandLine = wrapCommandForCompletion(
566 script.command,
567 completionShell,
568 completionSentinel(completionToken),
569 );
570 }
571 echoedWrapperLines.push(...commandLine.split("\r").filter((line) => line.length > 0));
572 return { completionShell, commandLine };
573 }).pipe(
574 Effect.onError(() =>
575 Effect.sync(() => {
576 observed?.unsubscribe();
577 readiness.unsubscribe();
578 }),
579 ),
580 );
581
582 // Return once the terminal exists so callers can show it while a startup prompt waits.
583 // PowerShell and cmd have no line-editor signal.
584 yield* (
585 completionShell === "powershell" || completionShell === null
586 ? Effect.succeed("ready" as const)
587 : readiness.wait
588 ).pipe(
589 Effect.flatMap((shell) =>
590 shell === "exited" || commandLine === null
591 ? Effect.void
592 : terminalManager.write({
593 threadId: input.threadId,
594 terminalId,
595 data: projectScriptTerminalInput(commandLine),
596 }),
597 ),
598 Effect.catchCause((cause) =>
599 Effect.logWarning("project script command was not written", {
600 ...errorContext,
601 terminalId,
602 cause,
603 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
604 ),
605 Effect.ensuring(Effect.sync(() => readiness.unsubscribe())),
606 Effect.forkIn(serviceScope),
607 );
608
609 const completion = observed?.completion.pipe(
610 Effect.tap(({ exitCode }) =>
611 exitCode === 0
612 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
613 : Effect.void,
614 ),
615 );
616
617 return {
618 status: "started",
619 scriptId: script.id,
620 scriptName: script.name,
621 scriptCommand: script.command,
622 terminalId,
623 cwd,
624 async: script.async !== false,
625 ...(completion ? { completion } : {}),
626 } as const;
627 });
628
629 return ProjectSetupScriptRunner.of({ runForThread });
630});
631
632export const layer = Layer.effect(ProjectSetupScriptRunner, make);