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

ProjectSetupScriptRunner.ts

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