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

ProjectSetupScriptRunner.ts

643 lines24.1 KB

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