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

ProjectSetupScriptRunner.ts

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