@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
67 lines • 2.58 kB
JavaScript
import { format } from "node:util";
/** The longest a print-then-exit command waits for its reader before exiting anyway. */
export const OUTPUT_DELIVERY_LIMIT_MS = 30_000;
const nativeLog = console.log;
const nativeStdoutWrite = process.stdout.write;
/**
* Runs `print` with stdout collected instead of written. Both runtimes can drop queued stdout at
* exit: Node writes to a pipe asynchronously, and Bun discards `console.log` output queued behind
* an earlier `process.stdout` write (senpi#2937). One write whose own callback is awaited is the
* shape both deliver in full. Output already redirected (json mode sends it to stderr) is left alone.
*/
export async function captureStdout(print) {
if (console.log !== nativeLog || process.stdout.write !== nativeStdoutWrite) {
return { result: await print(), output: "" };
}
const chunks = [];
console.log = (...args) => {
chunks.push(`${format(...args)}\n`);
};
process.stdout.write = ((chunk, encodingOrCallback, callback) => {
chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString());
const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
done?.();
return true;
});
let printed = false;
try {
const result = await print();
printed = true;
return { result, output: chunks.join("") };
}
finally {
console.log = nativeLog;
process.stdout.write = nativeStdoutWrite;
if (!printed && chunks.length > 0)
process.stdout.write(chunks.join(""));
}
}
function delivered(stream, text) {
if (stream.destroyed || stream.writableEnded)
return Promise.resolve();
return new Promise((resolve) => {
const timer = setTimeout(resolve, OUTPUT_DELIVERY_LIMIT_MS);
timer.unref();
const done = () => {
clearTimeout(timer);
resolve();
};
// A reader that went away (`| head -1`) surfaces as EPIPE: it ends the wait instead of crashing.
stream.once("error", done);
try {
stream.write(text, done);
}
catch {
done();
}
});
}
export async function exitAfterOutput(output = "", code) {
await Promise.all([delivered(process.stdout, output), delivered(process.stderr, "")]);
process.exit(code);
}
export async function printThenExit(print, code) {
const { output } = await captureStdout(print);
return exitAfterOutput(output, code);
}
//# sourceMappingURL=print-then-exit.js.map