@@ -30,37 +30,52 @@ function getMcCommand(): string[] {
3030 // without an in-process depth parameter. Generous enough for real use-cases.
3131 const MAX_SUBAGENT_DEPTH = 10;
3232
33-function tailBytesFromChunks(
34- chunks: readonly Uint8Array[],
35- maxBytes: number,
36-): Uint8Array {
37- if (maxBytes <= 0) return new Uint8Array(0);
33+class TailByteBuffer {
34+ private readonly ring: Uint8Array;
35+ private writePos = 0;
36+ private totalSeen = 0;
3837
39- const ring = new Uint8Array(maxBytes);
40- let writePos = 0;
41- let totalSeen = 0;
38+ constructor(private readonly maxBytes: number) {
39+ this.ring = new Uint8Array(Math.max(0, maxBytes));
40+ }
41+
42+ push(chunk: Uint8Array): void {
43+ if (this.maxBytes <= 0 || chunk.length === 0) return;
4244
43- for (const chunk of chunks) {
4445 let offset = 0;
4546 while (offset < chunk.length) {
4647 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;
48+ const writable = Math.min(this.maxBytes - this.writePos, remaining);
49+ this.ring.set(chunk.subarray(offset, offset + writable), this.writePos);
50+ this.writePos = (this.writePos + writable) % this.maxBytes;
5051 offset += writable;
51- totalSeen += writable;
52+ this.totalSeen += writable;
5253 }
5354 }
5455
55- const kept = Math.min(totalSeen, maxBytes);
56- if (kept === 0) return new Uint8Array(0);
57- if (totalSeen <= maxBytes) return ring.subarray(0, kept);
56+ toUint8Array(): Uint8Array {
57+ if (this.maxBytes <= 0) return new Uint8Array(0);
58+ const kept = Math.min(this.totalSeen, this.maxBytes);
59+ if (kept === 0) return new Uint8Array(0);
60+ if (this.totalSeen <= this.maxBytes) return this.ring.subarray(0, kept);
5861
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;
62+ const out = new Uint8Array(kept);
63+ const tailBytes = this.ring.subarray(this.writePos);
64+ out.set(tailBytes, 0);
65+ out.set(this.ring.subarray(0, this.writePos), tailBytes.length);
66+ return out;
67+ }
68+}
69+
70+function tailBytesFromChunks(
71+ chunks: readonly Uint8Array[],
72+ maxBytes: number,
73+): Uint8Array {
74+ const buffer = new TailByteBuffer(maxBytes);
75+ for (const chunk of chunks) {
76+ buffer.push(chunk);
77+ }
78+ return buffer.toUint8Array();
6479 }
6580
6681 export function tailTextFromChunks(
@@ -70,23 +85,27 @@ export function tailTextFromChunks(
7085 return new TextDecoder().decode(tailBytesFromChunks(chunks, maxBytes));
7186 }
7287
73-async function consumeTail(
88+async function drainTail(
7489 stream: ReadableStream | null,
7590 maxBytes = 8192,
7691 ): Promise<string> {
7792 if (!stream) return "";
7893 const reader = stream.getReader();
79- const chunks: Uint8Array[] = [];
94+ const buffer = new TailByteBuffer(maxBytes);
95+
8096 try {
8197 while (true) {
8298 const { done, value } = await reader.read();
8399 if (done) break;
84- if (value) chunks.push(value as Uint8Array);
100+ if (value) {
101+ buffer.push(value as Uint8Array);
102+ }
85103 }
86104 } finally {
87105 reader.releaseLock();
88106 }
89- return tailTextFromChunks(chunks, maxBytes);
107+
108+ return new TextDecoder().decode(buffer.toUint8Array());
90109 }
91110
92111 function formatSubagentDiagnostics(stdout: string, stderr: string): string {
@@ -98,6 +117,17 @@ function formatSubagentDiagnostics(stdout: string, stderr: string): string {
98117 return ` (diagnostics: ${tail.slice(0, 300)})`;
99118 }
100119
120+async function resolveDiagnostics(opts: {
121+ stdoutTail: Promise<string>;
122+ stderrTail: Promise<string>;
123+}): Promise<string> {
124+ const [stdout, stderr] = await Promise.all([
125+ opts.stdoutTail,
126+ opts.stderrTail,
127+ ]);
128+ return formatSubagentDiagnostics(stdout, stderr);
129+}
130+
101131 export function createSubagentRunner(
102132 cwd: string,
103133 getCurrentModel: () => string,
@@ -172,11 +202,12 @@ export function createSubagentRunner(
172202 abortSignal.addEventListener("abort", onAbort);
173203 }
174204
205+ const stdoutTail = drainTail(proc.stdout).catch(() => "");
206+ const stderrTail = drainTail(proc.stderr).catch(() => "");
207+
175208 try {
176- const [text, stdout, stderr] = await Promise.all([
209+ const [text] = await Promise.all([
177210 Bun.file(proc.stdio[3] as number).text(),
178- consumeTail(proc.stdout),
179- consumeTail(proc.stderr),
180211 proc.exited,
181212 ]);
182213
@@ -187,10 +218,12 @@ export function createSubagentRunner(
187218 );
188219 }
189220
190- const diagnostics = formatSubagentDiagnostics(stdout, stderr);
191-
192221 const trimmed = text.trim();
193222 if (!trimmed) {
223+ const diagnostics = await resolveDiagnostics({
224+ stdoutTail,
225+ stderrTail,
226+ });
194227 throw new Error(
195228 `Subagent subprocess produced no output (exit code ${String(proc.exitCode)})${diagnostics}`,
196229 );
@@ -200,15 +233,27 @@ export function createSubagentRunner(
200233 try {
201234 parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
202235 } catch {
236+ const diagnostics = await resolveDiagnostics({
237+ stdoutTail,
238+ stderrTail,
239+ });
203240 throw new Error(
204241 `Subagent subprocess wrote non-JSON output (exit code ${String(proc.exitCode)}): ${trimmed.slice(0, 200)}${diagnostics}`,
205242 );
206243 }
207244
208245 if (parsed.error) {
246+ const diagnostics = await resolveDiagnostics({
247+ stdoutTail,
248+ stderrTail,
249+ });
209250 throw new Error(`Subagent failed: ${parsed.error}${diagnostics}`);
210251 }
211252 if (proc.exitCode !== 0) {
253+ const diagnostics = await resolveDiagnostics({
254+ stdoutTail,
255+ stderrTail,
256+ });
212257 throw new Error(
213258 `Subagent process exited with code ${String(proc.exitCode)}${diagnostics}`,
214259 );