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