Skip to content

Commit da7e26c

Browse files
authored
fix(mcp,ai,agent,coding-agent,tui): read large streamed lines and events in linear time (#12451)
Closes #12224. ## Problem Stream readers kept an incomplete line or SSE event in one growing string and searched all of it again on every chunk. Searching only from a saved offset is not enough: searching a string built by `+=` makes V8 flatten (copy) the whole string first, so every chunk still costs the full pending length. Example: a 16 MiB MCP tool result arriving as one SSE `data:` line in 64 KiB chunks is about 256 chunks, each rescanning up to 16 MiB. `consumeSseStream` took 9.8 s, blocking the event loop. ## Fix Search only the new text, append the leftover to the pending string without reading it, and read the pending string once when its line or event ends. This is the approach #11791 used for the stdio line reader. - **mcp**: `consumeSseStream`. The size limit now uses a running byte count instead of measuring the buffer on every chunk. 16 MiB: 9.8 s -> 89 ms. - **ai**: Anthropic, OpenAI Codex, Mistral and pi-messages each had their own SSE parser with this bug. Anthropic's spec-conformant parser moves to `src/utils/sse.ts` as `SseDecoder` (now linear) and all four use it. Each keeps its own abort and error handling. - **agent**: `streamProxy` line splitting. - **coding-agent**: RPC JSONL reader, session file loading, llama.cpp model events (now `SseDecoder`), and the `subagent` and `rpc-extension-ui` examples. - **env, durable**: text line readers searched the whole pending line after every 64 KiB read. 16 MiB line: 1.35 s -> 72 ms. - **chord**: sync batch lines and `importStore` JSONL. - **tui**: `StdinBuffer` searched the whole bracketed paste for its end marker on every chunk. It now searches the new text plus the last 5 characters, in case the marker is split across chunks. - **p2**: terminal frames copied the whole incomplete frame on every chunk (backlog replays reach 8 MiB). They now keep the chunks and join them once per frame. Discord attachment downloads copied the growing 1 MiB upload chunk on every network read (about 800 MiB copied for a 25 MiB file); they now collect the parts and join them once per upload chunk. ## Behavior changes in the shared SSE parser - Codex also accepts CRLF line endings (it only split on LF before); Codex and pi-messages also accept lone CR. - llama.cpp model events also accept lone CR and CRLF split across chunks. - Anthropic no longer ends an event at a CRLF split across chunks. - pi-messages joins multiple `data:` lines instead of taking the first. - Mistral strips only the one space after `data:`. The payload is still trimmed, so JSON is unaffected. - Anthropic's `raw` diagnostic lines no longer carry comment lines from earlier blocks that had no event or data. ## Not changed - `readBodyText` in MCP: append-only, never rescanned. 16 MiB takes 100 ms. - `p2-sandbox.mjs` exec frames: each frame is at most one chunk of child output. - Bounded buffers (1 MiB or less) that are re-measured or rescanned per chunk: `apps/p2/src/runtime/logs.ts`, the `env/connection.ts` startup marker scan, the `p2-sandbox.mjs` request header, terminal-reply parsing in `StdinBuffer`. - Editor and input paste buffers: they receive the whole paste in one call from `StdinBuffer`. ## Tests - mcp: a 1 MiB event in 4 KiB chunks measures at most 2x its size (the old code measured 135M characters). - ai: `test/sse.test.ts`, same events for every chunk size and line ending, CRLF split across chunks. - tui: paste end marker split at every position. - p2: terminal frames at every chunk size; a 1 MiB frame calls `Buffer.concat` once (the old code called it 256 times); a frame whose handler threw is not delivered again. - mcp: a line that never ends is rejected at the limit. - ai: pi-messages skips `data: null`; an empty `event:` does not carry into the next event. - coding-agent: a throwing RPC line handler does not get its line joined with the next. - Existing tests pass for the Anthropic, Mistral, Codex and pi-messages providers, proxy, RPC JSONL, session manager, llama, durable env-node, env differential, and chord sync/store. `npm run check` and `apps/p2` check pass.
1 parent c7a5f2e commit da7e26c

33 files changed

Lines changed: 469 additions & 313 deletions

‎apps/p2/plugins/discord/worker.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -298,20 +298,27 @@ async function download(
298298
const response = await fetch(file.url, { signal: ctx.abortSignal });
299299
if (!response.ok || !response.body) throw new Error(`Download failed: ${response.status}`);
300300
let offset = 0;
301-
let pending = Buffer.alloc(0);
301+
// The parts of the next upload chunk, joined once it is full, so each byte is copied once.
302+
let pending: Uint8Array[] = [];
303+
let size = 0;
302304
const reader = response.body.getReader();
303305
for (;;) {
304306
const { done, value: chunk } = await reader.read();
305307
if (done) break;
306-
pending = Buffer.concat([pending, chunk]);
307-
while (pending.length >= FILE_CHUNK) {
308-
await files.append({ upload: begun.upload, offset, bytes: pending.subarray(0, FILE_CHUNK) }, ctx);
308+
for (let at = 0; at < chunk.length; ) {
309+
const take = Math.min(chunk.length - at, FILE_CHUNK - size);
310+
pending.push(chunk.subarray(at, at + take));
311+
size += take;
312+
at += take;
313+
if (size < FILE_CHUNK) continue;
314+
await files.append({ upload: begun.upload, offset, bytes: Buffer.concat(pending, size) }, ctx);
309315
offset += FILE_CHUNK;
310-
pending = pending.subarray(FILE_CHUNK);
316+
pending = [];
317+
size = 0;
311318
if (offset > MAX_UPLOAD_BYTES) throw new Error("Attachment too large");
312319
}
313320
}
314-
if (pending.length) await files.append({ upload: begun.upload, offset, bytes: pending }, ctx);
321+
if (size > 0) await files.append({ upload: begun.upload, offset, bytes: Buffer.concat(pending, size) }, ctx);
315322
await files.finish(begun.upload, ctx);
316323
return file.key;
317324
} catch (error) {

‎apps/p2/plugins/terminals/protocol.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,16 +136,32 @@ export function encodeFrame(message: object | Uint8Array): Buffer {
136136
}
137137

138138
export function readFrames(socket: Socket, onFrame: (frame: unknown | Uint8Array) => void): void {
139-
let pending: Buffer = Buffer.alloc(0);
139+
// The bytes of an incomplete frame stay chunks and are joined once its last byte arrives, so a large frame (a
140+
// backlog replay) arriving in many chunks is not copied again per chunk.
141+
let pending: Buffer[] = [];
142+
let pendingBytes = 0;
143+
// Bytes the next frame, or its length header, needs before it can be read.
144+
let needed = 4;
140145
socket.on("data", (chunk: Buffer) => {
141-
let buffer = pending.length ? Buffer.concat([pending, chunk]) : chunk;
146+
if (chunk.length === 0) return;
147+
pending.push(chunk);
148+
pendingBytes += chunk.length;
149+
if (pendingBytes < needed) return;
150+
let buffer = pending.length === 1 ? chunk : Buffer.concat(pending, pendingBytes);
151+
// Taken out before any frame is delivered, so a throwing `onFrame` cannot have its frames delivered again.
152+
pending = [];
153+
pendingBytes = 0;
154+
needed = 4;
142155
while (buffer.length >= 4) {
143156
const length = buffer.readUInt32BE(0);
144157
if (length < 1 || length > MAX_FRAME) {
145158
socket.destroy(new Error("Corrupt terminal frame"));
146159
return;
147160
}
148-
if (buffer.length < 4 + length) break;
161+
if (buffer.length < 4 + length) {
162+
needed = 4 + length;
163+
break;
164+
}
149165
const kind = buffer.readUInt8(4);
150166
const body = buffer.subarray(5, 4 + length);
151167
buffer = buffer.subarray(4 + length);
@@ -166,6 +182,7 @@ export function readFrames(socket: Socket, onFrame: (frame: unknown | Uint8Array
166182
}
167183
onFrame(parsed);
168184
}
169-
pending = Buffer.from(buffer);
185+
pending = buffer.length > 0 ? [Buffer.from(buffer)] : [];
186+
pendingBytes = buffer.length;
170187
});
171188
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import assert from "node:assert/strict";
2+
import { Socket } from "node:net";
3+
import { test } from "node:test";
4+
import { encodeFrame, readFrames } from "../../plugins/terminals/protocol.ts";
5+
6+
function feed(bytes: Buffer, chunkSize: number): unknown[] {
7+
const socket = new Socket();
8+
const frames: unknown[] = [];
9+
readFrames(socket, (frame) => frames.push(frame));
10+
for (let i = 0; i < bytes.length; i += chunkSize) socket.emit("data", bytes.subarray(i, i + chunkSize));
11+
return frames;
12+
}
13+
14+
test("terminal frames read the same at every chunk size", () => {
15+
const binary = new Uint8Array([1, 2, 3, 4, 5]);
16+
const bytes = Buffer.concat([encodeFrame({ type: "list" }), encodeFrame(binary), encodeFrame({ type: "exit" })]);
17+
for (let chunkSize = 1; chunkSize <= bytes.length; chunkSize++) {
18+
assert.deepEqual(feed(bytes, chunkSize), [{ type: "list" }, binary, { type: "exit" }], `chunk size ${chunkSize}`);
19+
}
20+
});
21+
22+
test("a frame whose handler threw is not delivered again", () => {
23+
const socket = new Socket();
24+
const frames: unknown[] = [];
25+
let thrown = false;
26+
readFrames(socket, (frame) => {
27+
frames.push(frame);
28+
if (!thrown) {
29+
thrown = true;
30+
throw new Error("handler failed");
31+
}
32+
});
33+
const first = Buffer.concat([encodeFrame({ n: 1 }), encodeFrame({ n: 2 })]);
34+
assert.throws(() => socket.emit("data", first), /handler failed/);
35+
socket.emit("data", encodeFrame({ n: 3 }));
36+
assert.deepEqual(frames, [{ n: 1 }, { n: 3 }]);
37+
});
38+
39+
test("a large terminal frame split across many chunks is joined once", (t) => {
40+
const payload = new Uint8Array(1024 * 1024).fill(7);
41+
const bytes = encodeFrame(payload);
42+
const concat = t.mock.method(Buffer, "concat");
43+
const frames = feed(bytes, 4096);
44+
assert.equal(concat.mock.callCount(), 1);
45+
assert.deepEqual(frames, [payload]);
46+
});

‎packages/agent/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## [Unreleased]
44

5+
### Fixed
6+
7+
- Fixed `streamProxy()` rescanning an incomplete line on every chunk, which made large proxy events take time quadratic in their size ([#12224](https://github.com/earendil-works/pi/issues/12224))
8+
59
## [1.6.0] - 2026-11-20
610

711
### Fixed

‎packages/agent/src/proxy.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,9 @@ export function streamProxy(
199199
throw new Error("Request aborted by user");
200200
}
201201

202-
buffer += decoder.decode(value, { stream: true });
203-
const lines = buffer.split("\n");
202+
// Split only the new text, so a long line arriving in many chunks is not rescanned per chunk.
203+
const lines = decoder.decode(value, { stream: true }).split("\n");
204+
lines[0] = buffer + lines[0];
204205
buffer = lines.pop() || "";
205206

206207
for (const line of lines) {

‎packages/ai/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
- Fixed `openai-completions` dropping OpenRouter's `native_finish_reason`, the upstream provider's own finish reason. `rawStopReason` now records it next to `finish_reason`, e.g. `stop.MALFORMED_RESPONSE`, and error messages include it, e.g. `Provider finish_reason: error (native_finish_reason: MALFORMED_FUNCTION_CALL)`. Stop reasons are unchanged ([#11931](https://github.com/earendil-works/pi/issues/11931))
4040
- Fixed GitHub Copilot listing classifier models the account cannot use, such as `microsoft-decision-1` on accounts whose plan does not include it, where every call failed with HTTP 400. After OAuth login or the next token refresh, only the decision models in the account's Copilot model catalog are listed ([#12395](https://github.com/earendil-works/pi/issues/12395))
4141
- Fixed HTTP 400 with thinking `off` on Claude Sonnet 5.5 through GitHub Copilot, and on Claude Opus 5.5 and Sonnet 5.5 through Cloudflare AI Gateway and Vercel AI Gateway, which reject `thinking: {type: "disabled"}`. The catalog now takes whether a Claude model can turn thinking off from the thinking toggle on Anthropic's own models.dev entry, for every host that serves it, and selecting `off` on those models uses the lowest supported level ([#12429](https://github.com/earendil-works/pi/issues/12429))
42+
- Fixed Anthropic, OpenAI Codex, Mistral, and pi-messages SSE streams rescanning an incomplete event on every chunk, which made large events take time quadratic in their size. All four now share one SSE parser, so OpenAI Codex also accepts CRLF line endings, OpenAI Codex and pi-messages accept lone CR line endings, pi-messages joins events with several `data:` lines, and Anthropic no longer ends an event at a CRLF split across chunks ([#12224](https://github.com/earendil-works/pi/issues/12224))
4243

4344
## [1.6.0] - 2026-11-20
4445

‎packages/ai/src/api/anthropic-messages.ts‎

Lines changed: 4 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import {
5151
import { getProviderEnvValue } from "../utils/provider-env.ts";
5252
import { retryProviderRequest } from "../utils/provider-retry.ts";
5353
import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";
54+
import { type ServerSentEvent, SseDecoder } from "../utils/sse.ts";
5455
import { ToolCallArgumentsStream } from "../utils/streaming-json.ts";
5556
import { getSystemMessageText, renderSystemMessageUpdate } from "../utils/text.ts";
5657
import {
@@ -613,18 +614,6 @@ function getAnthropicFederation(
613614
*/
614615
let federationClient: { key: string; fetch: typeof globalThis.fetch | undefined; client: Anthropic } | undefined;
615616

616-
interface ServerSentEvent {
617-
event: string | null;
618-
data: string;
619-
raw: string[];
620-
}
621-
622-
interface SseDecoderState {
623-
event: string | null;
624-
data: string[];
625-
raw: string[];
626-
}
627-
628617
const ANTHROPIC_MESSAGE_EVENTS: ReadonlySet<string> = new Set([
629618
"message_start",
630619
"message_delta",
@@ -634,85 +623,12 @@ const ANTHROPIC_MESSAGE_EVENTS: ReadonlySet<string> = new Set([
634623
"content_block_stop",
635624
]);
636625

637-
function flushSseEvent(state: SseDecoderState): ServerSentEvent | null {
638-
if (!state.event && state.data.length === 0) {
639-
return null;
640-
}
641-
642-
const event: ServerSentEvent = {
643-
event: state.event,
644-
data: state.data.join("\n"),
645-
raw: [...state.raw],
646-
};
647-
state.event = null;
648-
state.data = [];
649-
state.raw = [];
650-
return event;
651-
}
652-
653-
function decodeSseLine(line: string, state: SseDecoderState): ServerSentEvent | null {
654-
if (line === "") {
655-
return flushSseEvent(state);
656-
}
657-
658-
state.raw.push(line);
659-
if (line.startsWith(":")) {
660-
return null;
661-
}
662-
663-
const delimiterIndex = line.indexOf(":");
664-
const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);
665-
let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);
666-
if (value.startsWith(" ")) {
667-
value = value.slice(1);
668-
}
669-
670-
if (fieldName === "event") {
671-
state.event = value;
672-
} else if (fieldName === "data") {
673-
state.data.push(value);
674-
}
675-
676-
return null;
677-
}
678-
679-
function nextLineBreakIndex(text: string): number {
680-
const carriageReturnIndex = text.indexOf("\r");
681-
const newlineIndex = text.indexOf("\n");
682-
if (carriageReturnIndex === -1) {
683-
return newlineIndex;
684-
}
685-
if (newlineIndex === -1) {
686-
return carriageReturnIndex;
687-
}
688-
return Math.min(carriageReturnIndex, newlineIndex);
689-
}
690-
691-
function consumeLine(text: string): { line: string; rest: string } | null {
692-
const lineBreakIndex = nextLineBreakIndex(text);
693-
if (lineBreakIndex === -1) {
694-
return null;
695-
}
696-
697-
let nextIndex = lineBreakIndex + 1;
698-
if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") {
699-
nextIndex += 1;
700-
}
701-
702-
return {
703-
line: text.slice(0, lineBreakIndex),
704-
rest: text.slice(nextIndex),
705-
};
706-
}
707-
708626
async function* iterateSseMessages(
709627
body: ReadableStream<Uint8Array>,
710628
signal?: AbortSignal,
711629
): AsyncGenerator<ServerSentEvent> {
712630
const reader = body.getReader();
713-
const decoder = new TextDecoder();
714-
const state: SseDecoderState = { event: null, data: [], raw: [] };
715-
let buffer = "";
631+
const sse = new SseDecoder();
716632

717633
try {
718634
while (true) {
@@ -725,40 +641,10 @@ async function* iterateSseMessages(
725641
break;
726642
}
727643

728-
buffer += decoder.decode(value, { stream: true });
729-
let consumed = consumeLine(buffer);
730-
while (consumed) {
731-
buffer = consumed.rest;
732-
const event = decodeSseLine(consumed.line, state);
733-
if (event) {
734-
yield event;
735-
}
736-
consumed = consumeLine(buffer);
737-
}
738-
}
739-
740-
buffer += decoder.decode();
741-
let consumed = consumeLine(buffer);
742-
while (consumed) {
743-
buffer = consumed.rest;
744-
const event = decodeSseLine(consumed.line, state);
745-
if (event) {
746-
yield event;
747-
}
748-
consumed = consumeLine(buffer);
749-
}
750-
751-
if (buffer.length > 0) {
752-
const event = decodeSseLine(buffer, state);
753-
if (event) {
754-
yield event;
755-
}
644+
yield* sse.push(value);
756645
}
757646

758-
const trailingEvent = flushSseEvent(state);
759-
if (trailingEvent) {
760-
yield trailingEvent;
761-
}
647+
yield* sse.end();
762648
} finally {
763649
reader.releaseLock();
764650
}

‎packages/ai/src/api/mistral-conversations.ts‎

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { shortHash } from "../utils/hash.ts";
2020
import { headersToRecord } from "../utils/headers.ts";
2121
import { getIdentityHeaders } from "../utils/identity.ts";
2222
import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";
23+
import { SseDecoder } from "../utils/sse.ts";
2324
import { ToolCallArgumentsStream } from "../utils/streaming-json.ts";
2425
import { getSystemMessageText, renderSystemMessageUpdate } from "../utils/text.ts";
2526
import { getCurrentTools, resolveTranscript } from "../utils/transcript.ts";
@@ -453,8 +454,7 @@ async function* readMistralEvents(
453454
signal: AbortSignal | undefined,
454455
): AsyncGenerator<MistralCompletionEvent> {
455456
const reader = body.getReader();
456-
const decoder = new TextDecoder();
457-
let buffer = "";
457+
const sse = new SseDecoder();
458458
const onAbort = () => {
459459
void reader.cancel().catch(() => {});
460460
};
@@ -465,24 +465,16 @@ async function* readMistralEvents(
465465
if (signal?.aborted) throw signal.reason;
466466
const { done, value } = await reader.read();
467467
if (signal?.aborted) throw signal.reason;
468-
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
468+
const events = done ? sse.end() : sse.push(value);
469469

470-
let boundary = findMistralEventBoundary(buffer);
471-
while (boundary) {
472-
const event = parseMistralEvent(buffer.slice(0, boundary.index));
473-
buffer = buffer.slice(boundary.index + boundary.length);
470+
for (const { data } of events) {
471+
const event = parseMistralEvent(data.trim());
474472
if (event === MISTRAL_STREAM_DONE) return;
475473
if (event) yield event;
476-
boundary = findMistralEventBoundary(buffer);
477474
}
478475

479476
if (done) break;
480477
}
481-
482-
if (buffer.trim()) {
483-
const event = parseMistralEvent(buffer);
484-
if (event !== MISTRAL_STREAM_DONE && event) yield event;
485-
}
486478
} finally {
487479
signal?.removeEventListener("abort", onAbort);
488480
try {
@@ -494,18 +486,7 @@ async function* readMistralEvents(
494486
}
495487
}
496488

497-
function findMistralEventBoundary(buffer: string): { index: number; length: number } | undefined {
498-
const match = /\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);
499-
return match?.index === undefined ? undefined : { index: match.index, length: match[0].length };
500-
}
501-
502-
function parseMistralEvent(raw: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {
503-
const data = raw
504-
.split(/\r\n|\r|\n/u)
505-
.filter((line) => line.startsWith("data:"))
506-
.map((line) => line.slice(5).trimStart())
507-
.join("\n")
508-
.trim();
489+
function parseMistralEvent(data: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {
509490
if (!data) return undefined;
510491
if (data === "[DONE]") return MISTRAL_STREAM_DONE;
511492

0 commit comments

Comments
 (0)