outputCollector.ts•1.25 kB
const MAX_OUTPUT_BYTES = 10 * 1024 * 1024; // 10MB default limit
export interface OutputCollector {
getText(): string;
isTruncated(): boolean;
}
/**
* Creates a collector that captures stream output up to a max size.
* Additional data is drained but discarded to avoid blocking the child process.
*/
export function createOutputCollector(
stream: NodeJS.ReadableStream | null,
limit: number = MAX_OUTPUT_BYTES
): OutputCollector {
const chunks: Buffer[] = [];
let capturedBytes = 0;
let truncated = false;
stream?.on('data', (data: Buffer) => {
if (truncated) {
return;
}
const remaining = limit - capturedBytes;
if (remaining <= 0) {
truncated = true;
return;
}
if (data.length <= remaining) {
chunks.push(data);
capturedBytes += data.length;
} else {
chunks.push(data.subarray(0, remaining));
capturedBytes += remaining;
truncated = true;
}
});
return {
getText(): string {
return Buffer.concat(chunks, capturedBytes).toString();
},
isTruncated(): boolean {
return truncated;
},
};
}
export function formatTruncationSuffix(truncated: boolean): string {
return truncated ? ' (truncated at 10MB)' : '';
}