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

stdio.ts

123 lines4.0 KB

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;
59​
60export const appendStderrTail = (current: string, chunk: string): string => {
61 const next = `${current}${chunk}`;
62 return next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);
63};
64​
65// Node launchers print the actionable error between a source excerpt and stack frames.
66export const stderrExcerpt = (tail: string): string | undefined => {
67 const lines = NodeUtil.stripVTControlCharacters(tail)
68 .split(/\r?\n/)
69 .map((line) => line.trim().replace(/\s+/g, " "))
70 .filter((line) => line.length > 0);
71 const line = lines.findLast((candidate) => ERROR_LINE_PATTERN.test(candidate)) ?? lines.at(-1);
72 if (line === undefined) {
73 return undefined;
74 }
75 return line.length <= STDERR_EXCERPT_MAX_CHARS
76 ? line
77 : `${line.slice(0, STDERR_EXCERPT_MAX_CHARS - 1)}…`;
78};
79​
80export const makeStderrTail = Effect.fn("makeStderrTail")(function* (
81 stderr: ChildProcessSpawner.ChildProcessHandle["stderr"],
82) {
83 const tail = yield* Ref.make("");
84 const drain = yield* stderr.pipe(
85 Stream.decodeText(),
86 Stream.runForEach((chunk) => Ref.update(tail, (current) => appendStderrTail(current, chunk))),
87 Effect.ignore,
88 Effect.forkScoped,
89 );
90 return {
91 read: Ref.get(tail),
92 awaitDrained: Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore),
93 };
94});
95​
96type ChildProcessTerminationHandle = Pick<
97 ChildProcessSpawner.ChildProcessHandle,
98 "exitCode" | "pid"
99>;
100​
101export const makeTerminationError = (
102 handle: ChildProcessTerminationHandle,
103 stderrTail: Effect.Effect<string>,
104): Effect.Effect<CodexError.CodexAppServerError> =>
105 Effect.matchEffect(handle.exitCode, {
106 onFailure: (cause) =>
107 Effect.succeed(
108 new CodexError.CodexAppServerTransportError({
109 operation: "read-process-exit-status",
110 pid: handle.pid,
111 cause,
112 }),
113 ),
114 onSuccess: (code) =>
115 Effect.map(stderrTail, (tail) => {
116 const stderr = stderrExcerpt(tail);
117 return new CodexError.CodexAppServerProcessExitedError({
118 code,
119 pid: handle.pid,
120 ...(stderr ? { stderr } : {}),
121 });
122 }),
123 });