@@ -29,13 +29,53 @@ function getMcCommand(): string[] {
2929 // Loose recursion cap passed via environment so subprocess chains are bounded
3030 // without an in-process depth parameter. Generous enough for real use-cases.
3131 const MAX_SUBAGENT_DEPTH = 10;
32+
33+function tailBytesFromChunks(
34+ chunks: readonly Uint8Array[],
35+ maxBytes: number,
36+): Uint8Array {
37+ if (maxBytes <= 0) return new Uint8Array(0);
38+
39+ const ring = new Uint8Array(maxBytes);
40+ let writePos = 0;
41+ let totalSeen = 0;
42+
43+ for (const chunk of chunks) {
44+ let offset = 0;
45+ while (offset < chunk.length) {
46+ const remaining = chunk.length - offset;
47+ const writable = Math.min(maxBytes - writePos, remaining);
48+ ring.set(chunk.subarray(offset, offset + writable), writePos);
49+ writePos = (writePos + writable) % maxBytes;
50+ offset += writable;
51+ totalSeen += writable;
52+ }
53+ }
54+
55+ const kept = Math.min(totalSeen, maxBytes);
56+ if (kept === 0) return new Uint8Array(0);
57+ if (totalSeen <= maxBytes) return ring.subarray(0, kept);
58+
59+ const out = new Uint8Array(kept);
60+ const tailBytes = ring.subarray(writePos);
61+ out.set(tailBytes, 0);
62+ out.set(ring.subarray(0, writePos), tailBytes.length);
63+ return out;
64+}
65+
66+export function tailTextFromChunks(
67+ chunks: readonly Uint8Array[],
68+ maxBytes: number,
69+): string {
70+ return new TextDecoder().decode(tailBytesFromChunks(chunks, maxBytes));
71+}
72+
3273 async function consumeTail(
3374 stream: ReadableStream | null,
3475 maxBytes = 8192,
3576 ): Promise<string> {
3677 if (!stream) return "";
3778 const reader = stream.getReader();
38- // Accumulate Uint8Array chunks and decode once at the end to avoid O(n²) string concatenation.
3979 const chunks: Uint8Array[] = [];
4080 try {
4181 while (true) {
@@ -46,8 +86,7 @@ async function consumeTail(
4686 } finally {
4787 reader.releaseLock();
4888 }
49- const text = new TextDecoder().decode(Buffer.concat(chunks));
50- return text.length > maxBytes ? text.slice(-maxBytes) : text;
89+ return tailTextFromChunks(chunks, maxBytes);
5190 }
5291
5392 function formatSubagentDiagnostics(stdout: string, stderr: string): string {