Open History to see the last commit
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";
28}
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>;
40}
41
42export interface ProjectSetupScriptCompletion {
43 readonly exitCode: number | null;
44 readonly durationMs: number;
45}
46
47export interface ProjectSetupScriptOutputLine {
48 readonly line: string;
49}
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";
58}
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 };
79}
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 }
95}
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 }
109}
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 }
118}
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}:`;
144}
145
146function completionSentinelPattern(token: string): RegExp {
147 return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`);
148}
149
150// ECMA-48: CSI, OSC, then any other escape as intermediates (0x20-0x2F) and one final byte.
151function stripTerminalControl(text: string): string {
152 return text
153 .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[ -/]*[0-~]/g, "")
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(
316 cleaned.slice(
317 0,
318 splitsSurrogatePair(cleaned, OUTPUT_LINE_MAX_LENGTH)
319 ? OUTPUT_LINE_MAX_LENGTH - 1
320 : OUTPUT_LINE_MAX_LENGTH,
321 ),
322 );
323 });
324
325 const unsubscribe = yield* terminalManager.subscribe((event) => {
326 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
327 return Effect.void;
328 }
329 if (event.type === "output") {
330 lineBuffer += event.data;
331 // Bare CR redraws progress in place; split redraws instead of growing one line.
332 const lines = lineBuffer.split(/\r\n|\r|\n/);
333 lineBuffer = lines.pop() ?? "";
334 // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe.
335 if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {
336 const start = lineBuffer.length - PARTIAL_LINE_MAX_LENGTH;
337 lineBuffer = lineBuffer.slice(
338 splitsSurrogatePair(lineBuffer, start) ? start + 1 : start,
339 );
340 }
341 return Effect.forEach(lines, handleLine, { discard: true }).pipe(
342 Effect.andThen(
343 Effect.suspend(() =>
344 settled && lineBuffer.length > 0
345 ? Deferred.succeed(promptReturned, undefined).pipe(Effect.asVoid)
346 : Effect.void,
347 ),
348 ),
349 );
350 }
351 if (event.type === "exited" || event.type === "closed") {
352 return settle(null).pipe(Effect.andThen(Deferred.succeed(promptReturned, undefined)));
353 }
354 return Effect.void;
355 });
356
357 const completion = Deferred.await(done).pipe(
358 // A shell with an empty prompt never prints one; do not wait forever.
359 Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
360 Effect.ensuring(Effect.sync(() => unsubscribe())),
361 );
362 // A startup prompt waits for input on a line that has no newline yet.
363 const flushPartialLine = Effect.suspend(() => {
364 const partial = lineBuffer;
365 lineBuffer = "";
366 return handleLine(partial);
367 });
368 const abandon = settle(null).pipe(
369 Effect.andThen(Deferred.succeed(promptReturned, undefined)),
370 );
371 return { completion, unsubscribe, flushPartialLine, abandon };
372 },
373 );
374
375 // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
376 // shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
377 const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
378 function* (input: {
379 readonly threadId: string;
380 readonly terminalId: string;
381 readonly onStartupPrompt: Effect.Effect<void>;
382 }) {
383 const outcome = yield* Deferred.make<"ready" | "exited">();
384 let reading = false;
385 let carry = "";
386 let busy = false;
387 let activity = 0;
388 const unsubscribe = yield* terminalManager.subscribe((event) => {
389 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
390 return Effect.void;
391 }
392 activity += 1;
393 // A new shell process starts idle; the manager resets its subprocess state without an event.
394 if (event.type === "started" || event.type === "restarted") {
395 busy = false;
396 reading = false;
397 carry = "";
398 }
399 if (event.type === "activity") busy = event.hasRunningSubprocess;
400 if (event.type === "output") {
401 const text = carry + event.data;
402 carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
403 reading = lineEditorReading(text, reading);
404 }
405 if (event.type === "exited" || event.type === "closed") {
406 return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
407 }
408 return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
409 });
410 // A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
411 const quiet = Effect.gen(function* () {
412 while (true) {
413 const seen = activity;
414 yield* Effect.sleep(SHELL_QUIET_FALLBACK);
415 if (activity !== seen) continue;
416 if (!busy) return "quiet" as const;
417 yield* input.onStartupPrompt;
418 }
419 });
420 // Restored history can hold a previous shell's line editor state, so only live output counts.
421 const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet));
422 return { wait, unsubscribe };
423 },
424 );
425
426 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
427 "ProjectSetupScriptRunner.runForThread",
428 )(function* (input) {
429 const errorContext = {
430 threadId: input.threadId,
431 worktreePath: input.worktreePath,
432 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
433 ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
434 };
435 // A thread whose origin cannot be read might be a link's: run nothing.
436 const thread = yield* threads.getThreadShell(ThreadId.make(input.threadId)).pipe(
437 Effect.mapError(
438 (cause) =>
439 new ProjectSetupScriptOperationError({
440 ...errorContext,
441 operation: "readThread",
442 cause,
443 }),
444 ),
445 );
446 if (thread?.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin))
447 return { status: "skipped-for-link" } as const;
448 const suppliedProject = input.project;
449 const projectById =
450 suppliedProject ??
451 (input.projectId
452 ? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
453 Effect.map(Option.getOrUndefined),
454 Effect.mapError(
455 (cause) =>
456 new ProjectSetupScriptOperationError({
457 ...errorContext,
458 operation: "resolveProject",
459 cause,
460 }),
461 ),
462 )
463 : null);
464 const project =
465 suppliedProject ??
466 projectById ??
467 (input.projectCwd
468 ? yield* projects.getByWorkspaceRoot(input.projectCwd).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
481 if (!project) {
482 return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
483 }
484
485 const settings = yield* serverSettings.getSettings.pipe(
486 Effect.mapError(
487 (cause) =>
488 new ProjectSetupScriptOperationError({
489 ...errorContext,
490 operation: "readSettings",
491 cause,
492 }),
493 ),
494 );
495 const trigger = input.trigger ?? "setup";
496 const scripts = resolveProjectScripts(settings, project);
497 const script =
498 trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts);
499 if (!script) {
500 return {
501 status: "no-script",
502 } as const;
503 }
504
505 // Earlier settle shells may still run foreground programs; do not type resumed settles into them.
506 const terminalId =
507 trigger === "settle"
508 ? `settle-${script.id}-${(yield* random.uuidV4()).slice(0, 8)}`
509 : `setup-${script.id}`;
510 // A surviving setup shell may still hold a deleted worktree directory.
511 if (trigger === "setup") {
512 yield* terminalManager.close({ threadId: input.threadId, terminalId }).pipe(
513 Effect.mapError(
514 (cause) =>
515 new ProjectSetupScriptOperationError({
516 ...errorContext,
517 operation: "openTerminal",
518 cause,
519 }),
520 ),
521 );
522 }
523 const cwd = input.worktreePath;
524 const env = {
525 ...projectScriptRuntimeEnv({
526 project: { cwd: project.workspaceRoot },
527 worktreePath: input.worktreePath,
528 }),
529 // Before client attachment, truecolor probes wait for terminal replies nobody can send.
530 COLORTERM: "",
531 // Project scripts keep the default shell; the preference is for interactive terminals only.
532 T3CODE_TERMINAL_SHELL: "",
533 };
534 const observe = input.observeCompletion;
535 const completionToken = observe ? (yield* random.uuidV4()).replaceAll("-", "") : null;
536 const echoedWrapperLines: string[] = [];
537 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
538 const observed =
539 observe && completionToken
540 ? yield* observeTerminalCompletion({
541 threadId: input.threadId,
542 terminalId,
543 sentinel: completionSentinel(completionToken),
544 sentinelPattern: completionSentinelPattern(completionToken),
545 echoedWrapperLines,
546 onOutputLine: observe.onOutputLine,
547 })
548 : undefined;
549 const readiness = yield* watchShellReadiness({
550 threadId: input.threadId,
551 terminalId,
552 onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
553 });
554 const { completionShell, commandLine } = yield* Effect.gen(function* () {
555 const shell = yield* terminalManager
556 .open({
557 threadId: input.threadId,
558 terminalId,
559 stopOnSettle: script.stopOnSettle ?? false,
560 cwd,
561 worktreePath: input.worktreePath,
562 env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
563 })
564 .pipe(
565 Effect.andThen(() =>
566 terminalManager
567 .getShell({ threadId: input.threadId, terminalId })
568 .pipe(Effect.catchTags({ TerminalNotRunningError: () => Effect.succeed(null) })),
569 ),
570 Effect.mapError(
571 (cause) =>
572 new ProjectSetupScriptOperationError({
573 ...errorContext,
574 operation: "openTerminal",
575 cause,
576 }),
577 ),
578 );
579 if (shell === null) {
580 yield* observed?.abandon ?? Effect.void;
581 return { completionShell: null, commandLine: null };
582 }
583 const completionShell = resolveCompletionShell(shell);
584 let commandLine = script.command;
585 if (observe && completionToken) {
586 if (completionShell === null) {
587 yield* terminalManager.closeIdle({ threadId: input.threadId, terminalId });
588 return yield* new ProjectSetupScriptUnsupportedShellError({ shell });
589 }
590 commandLine = wrapCommandForCompletion(
591 script.command,
592 completionShell,
593 completionSentinel(completionToken),
594 );
595 }
596 echoedWrapperLines.push(...commandLine.split("\r").filter((line) => line.length > 0));
597 return { completionShell, commandLine };
598 }).pipe(
599 Effect.onError(() =>
600 Effect.sync(() => {
601 observed?.unsubscribe();
602 readiness.unsubscribe();
603 }),
604 ),
605 );
606
607 // Return once the terminal exists so callers can show it while a startup prompt waits.
608 // PowerShell and cmd have no line-editor signal.
609 const commandWriter = yield* (
610 completionShell === "powershell" || completionShell === null
611 ? Effect.succeed("ready" as const)
612 : readiness.wait
613 ).pipe(
614 Effect.flatMap((shell) =>
615 shell === "exited" || commandLine === null
616 ? Effect.void
617 : terminalManager.write({
618 threadId: input.threadId,
619 terminalId,
620 // macOS zsh garbles long typed-ahead multiline input; a live line editor takes it as one paste.
621 data: projectScriptTerminalInput(
622 shell === "ready" && completionShell === "posix" && commandLine.includes("\r")
623 ? `\x1b[200~${commandLine.replaceAll("\r", "\n")}\x1b[201~`
624 : commandLine,
625 ),
626 }),
627 ),
628 Effect.catchCause((cause) =>
629 Effect.logWarning("project script command was not written", {
630 ...errorContext,
631 terminalId,
632 cause,
633 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
634 ),
635 Effect.ensuring(Effect.sync(() => readiness.unsubscribe())),
636 Effect.forkIn(serviceScope),
637 );
638
639 const completion = observed?.completion.pipe(
640 Effect.onInterrupt(() =>
641 Fiber.interrupt(commandWriter).pipe(
642 Effect.andThen(Effect.sync(() => readiness.unsubscribe())),
643 Effect.andThen(terminalManager.close({ threadId: input.threadId, terminalId })),
644 Effect.ignore,
645 ),
646 ),
647 Effect.tap(({ exitCode }) => {
648 if (exitCode !== 0) return Effect.void;
649 // Nothing closes a settle shell later, so a prompt hook still running (a git prompt)
650 // must not fail an idle check and leave it holding the settled worktree.
651 if (trigger === "settle") {
652 return terminalManager.close({ threadId: input.threadId, terminalId }).pipe(
653 Effect.catch((error) =>
654 Effect.logWarning("failed to close settle script terminal", {
655 ...errorContext,
656 terminalId,
657 error: error.message,
658 }),
659 ),
660 );
661 }
662 return terminalManager.closeIdle({ threadId: input.threadId, terminalId });
663 }),
664 );
665
666 return {
667 status: "started",
668 scriptId: script.id,
669 scriptName: script.name,
670 scriptCommand: script.command,
671 terminalId,
672 cwd,
673 async: script.async !== false,
674 ...(completion ? { completion } : {}),
675 } as const;
676 });
677
678 return ProjectSetupScriptRunner.of({ runForThread });
679});
680
681export const layer = Layer.effect(ProjectSetupScriptRunner, make);