Open History to see the last commit
1import * as NodeUtil from "node:util";
2
3import * as Cause from "effect/Cause";
4import * as Fiber from "effect/Fiber";
5import * as Effect from "effect/Effect";
6import * as Queue from "effect/Queue";
7import * as Ref from "effect/Ref";
8import * as Sink from "effect/Sink";
9import * as Stdio from "effect/Stdio";
10import * as Stream from "effect/Stream";
11import { ChildProcessSpawner } from "effect/process";
12
13import * as CodexError from "../errors.ts";
14
15const encoder = new TextEncoder();
16
17export const makeChildStdio = (
18 handle: Pick<ChildProcessSpawner.ChildProcessHandle, "stdin" | "stdout">,
19 stderrDrained: Effect.Effect<void>,
20) =>
21 Stdio.make({
22 args: Effect.succeed([]),
23 // Finish stderr separately from the protocol's exit-status deadline.
24 stdin: handle.stdout.pipe(Stream.onEnd(stderrDrained)),
25 stdout: () =>
26 Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
27 typeof chunk === "string" ? encoder.encode(chunk) : chunk,
28 ),
29 stderr: () => Sink.drain,
30 });
31
32export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
33 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
34 const output = yield* Queue.unbounded<string>();
35 const decoder = new TextDecoder();
36
37 return {
38 stdio: Stdio.make({
39 args: Effect.succeed([]),
40 stdin: Stream.fromQueue(input),
41 stdout: () =>
42 Sink.forEach((chunk: string | Uint8Array) =>
43 Queue.offer(
44 output,
45 typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
46 ),
47 ),
48 stderr: () => Sink.drain,
49 }),
50 input,
51 output,
52 };
53});
54
55const STDERR_TAIL_MAX_CHARS = 8_192;
56const STDERR_EXCERPT_MAX_CHARS = 512;
57// `Error: …`, `TypeError: …`, `Error [ERR_MODULE_NOT_FOUND]: …`, `error: …`, `ERROR: …`, `fatal: …`
58const ERROR_LINE_PATTERN = /^(?:[a-z]*error|fatal)(?: ?\[[^\]]+\])?:\s*\S/i;
59const EXIT_SUMMARY_PATTERN = /\b(?:exit status|exit code|exited with code)\s+\d+\.?$/i;
60// Rust panics and aborts end with `note: run with \`RUST_BACKTRACE=1\` …` after the cause.
61const TRAILING_NOTE_PATTERN = /^note:\s/i;
62
63export const appendStderrTail = (current: string, chunk: string): string => {
64 const next = `${current}${chunk}`;
65 return next.length <= STDERR_TAIL_MAX_CHARS
66 ? next
67 : next.slice(-STDERR_TAIL_MAX_CHARS).replace(/^[\uDC00-\uDFFF]/, "");
68};
69
70// Node launchers print the actionable error between a source excerpt and stack frames.
71export const stderrExcerpt = (tail: string): string | undefined => {
72 const lines = NodeUtil.stripVTControlCharacters(tail)
73 .split(/\r?\n/)
74 .map((line) => line.trim().replace(/\s+/g, " "))
75 .filter((line) => line.length > 0);
76 const errorIndex = lines.findLastIndex((candidate) => ERROR_LINE_PATTERN.test(candidate));
77 const causeIndex = lines.findLastIndex((candidate) => !TRAILING_NOTE_PATTERN.test(candidate));
78 const endsWithNote = causeIndex !== -1 && causeIndex < lines.length - 1;
79 const lineIndex =
80 errorIndex === -1 || EXIT_SUMMARY_PATTERN.test(lines.at(-1) ?? "")
81 ? endsWithNote
82 ? causeIndex
83 : lines.length - 1
84 : errorIndex;
85 const line = lines[lineIndex];
86 if (line === undefined) {
87 return undefined;
88 }
89 // Wrappers can print the actual failure before their generic exit-status summary,
90 // and a Rust panic prints its location on the line before its message.
91 const contextLines = EXIT_SUMMARY_PATTERN.test(line)
92 ? 2
93 : lineIndex === causeIndex && endsWithNote
94 ? 1
95 : 0;
96 const excerpt = lines.slice(Math.max(0, lineIndex - contextLines), lineIndex + 1).join(" | ");
97 if (excerpt.length <= STDERR_EXCERPT_MAX_CHARS) {
98 return excerpt;
99 }
100 return excerpt !== line
101 ? `…${excerpt.slice(-(STDERR_EXCERPT_MAX_CHARS - 1)).replace(/^[\uDC00-\uDFFF]/, "")}`
102 : `${excerpt.slice(0, STDERR_EXCERPT_MAX_CHARS - 1).replace(/[\uD800-\uDBFF]$/, "")}…`;
103};
104
105export const makeStderrTail = Effect.fn("makeStderrTail")(function* (
106 stderr: ChildProcessSpawner.ChildProcessHandle["stderr"],
107) {
108 const tail = yield* Ref.make("");
109 const drain = yield* stderr.pipe(
110 Stream.decodeText(),
111 Stream.runForEach((chunk) => Ref.update(tail, (current) => appendStderrTail(current, chunk))),
112 Effect.ignore,
113 Effect.forkScoped,
114 );
115 return {
116 read: Ref.get(tail),
117 awaitDrained: Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore),
118 };
119});
120
121type ChildProcessTerminationHandle = Pick<
122 ChildProcessSpawner.ChildProcessHandle,
123 "exitCode" | "pid"
124>;
125
126export const makeTerminationError = (
127 handle: ChildProcessTerminationHandle,
128 stderrTail: Effect.Effect<string>,
129): Effect.Effect<CodexError.CodexAppServerError> =>
130 Effect.matchEffect(handle.exitCode, {
131 onFailure: (cause) =>
132 Effect.succeed(
133 new CodexError.CodexAppServerTransportError({
134 operation: "read-process-exit-status",
135 pid: handle.pid,
136 cause,
137 }),
138 ),
139 onSuccess: (code) =>
140 Effect.map(stderrTail, (tail) => {
141 const stderr = stderrExcerpt(tail);
142 return new CodexError.CodexAppServerProcessExitedError({
143 code,
144 pid: handle.pid,
145 ...(stderr ? { stderr } : {}),
146 });
147 }),
148 });