From 50ba5cf2bf912849e42993dc3458f68119f75af6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 05:42:52 -0600 Subject: [PATCH] fix(bin): decode proxy response streams with StringDecoder (#4336) --- bin/agy-proxy.mjs | 10 +++++++--- bin/claude-code-proxy.mjs | 7 +++++-- bin/codex-proxy.mjs | 7 +++++-- bin/commandcode-proxy.mjs | 13 +++++++++---- bin/design-code-proxy.mjs | 9 ++++++--- bin/muse-proxy.mjs | 19 +++++++++++++------ bin/stream-decode.mjs | 19 +++++++++++++++++++ bin/stream-decode.test.mjs | 35 +++++++++++++++++++++++++++++++++++ 8 files changed, 99 insertions(+), 20 deletions(-) create mode 100644 bin/stream-decode.mjs create mode 100644 bin/stream-decode.test.mjs diff --git a/bin/agy-proxy.mjs b/bin/agy-proxy.mjs index 24779b8247..6a392650ca 100755 --- a/bin/agy-proxy.mjs +++ b/bin/agy-proxy.mjs @@ -46,6 +46,7 @@ import path from 'node:path'; import os from 'node:os'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; const PORT = parseProxyPort('AGY_PROXY_PORT', 18743); const HOST = process.env.AGY_PROXY_HOST || '127.0.0.1'; @@ -261,6 +262,7 @@ const pullModelsLive = () => new Promise((resolve) => { stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; + const stdoutDecoder = createStreamDecoder(); let settled = false; const done = (ok, fullIds) => { if (settled) return; @@ -268,7 +270,7 @@ const pullModelsLive = () => new Promise((resolve) => { resolve(ok ? fullIds : null); }; const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} done(false); }, MODELS_PULL_TIMEOUT_MS); - child.stdout.on('data', d => { stdout += d; }); + child.stdout.on('data', d => { stdout += stdoutDecoder.push(d); }); child.stderr.on('data', () => {}); child.on('error', () => { clearTimeout(timer); done(false); }); child.on('close', (code) => { @@ -493,6 +495,8 @@ class AgyWorker { this.dead = null; // Error once the process is gone this.lineBuffer = ''; this.stderrTail = ''; + this.stdoutDecoder = createStreamDecoder(); + this.stderrDecoder = createStreamDecoder(); this.turnWaiter = null; this.ready = false; // set when the init event arrives this.prevUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0, cache_read_tokens: 0 }; @@ -537,7 +541,7 @@ class AgyWorker { child.stdout.on('data', chunk => this._onStdout(chunk)); child.stderr.on('data', chunk => { - this.stderrTail = (this.stderrTail + chunk.toString()).slice(-4000); + this.stderrTail = (this.stderrTail + this.stderrDecoder.push(chunk)).slice(-4000); }); child.on('error', err => { this._fail(turnError(err.message, { isSpawnError: true })); @@ -571,7 +575,7 @@ class AgyWorker { } _onStdout(chunk) { - this.lineBuffer += chunk.toString(); + this.lineBuffer += this.stdoutDecoder.push(chunk); const lines = this.lineBuffer.split('\n'); this.lineBuffer = lines.pop() || ''; for (const line of lines) this._processLine(line); diff --git a/bin/claude-code-proxy.mjs b/bin/claude-code-proxy.mjs index 880596f3f9..2e7b3d74f1 100644 --- a/bin/claude-code-proxy.mjs +++ b/bin/claude-code-proxy.mjs @@ -37,6 +37,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; // Default port 18749: the next free port in the fleet family (clef 18742, // agy 18743, codex 18744, antigravity-ls 18745, design-code 18746, @@ -291,6 +292,8 @@ class ClaudeSession { this.dead = null; // Error once the child is gone this.lineBuffer = ''; this.stderrTail = ''; + this.stdoutDecoder = createStreamDecoder(); + this.stderrDecoder = createStreamDecoder(); this.turnWaiter = null; // { resolve, reject, onDelta, deltasText, lastAssistantText } this.workdir = sessionWorkdirFor(key); @@ -336,7 +339,7 @@ class ClaudeSession { this.initRequestId = crypto.randomUUID(); child.stdout.on('data', chunk => this._onStdout(chunk)); child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); + const msg = this.stderrDecoder.push(chunk); this.stderrTail = (this.stderrTail + msg).slice(-2000); if (msg.trim()) console.warn(`[claude-code-proxy stderr ${sessionId.slice(0, 8)}] ${msg.trim().slice(0, 300)}`); }); @@ -366,7 +369,7 @@ class ClaudeSession { } _onStdout(chunk) { - this.lineBuffer += chunk.toString('utf-8'); + this.lineBuffer += this.stdoutDecoder.push(chunk); const lines = this.lineBuffer.split('\n'); this.lineBuffer = lines.pop(); for (const line of lines) { diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index 54c35297fe..b260f77316 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -9,6 +9,7 @@ import path from 'node:path'; import os from 'node:os'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; const PORT = parseProxyPort('CODEX_PROXY_PORT', 18744); const HOST = process.env.CODEX_PROXY_HOST || '127.0.0.1'; @@ -871,6 +872,8 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => child.stdin.end(); let lineBuffer = ''; + const stdoutDecoder = createStreamDecoder(); + const stderrDecoder = createStreamDecoder(); let fullContent = ''; let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); let completionTokens = 0; @@ -944,7 +947,7 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => }; child.stdout.on('data', (chunk) => { - lineBuffer += chunk.toString('utf-8'); + lineBuffer += stdoutDecoder.push(chunk); const lines = lineBuffer.split('\n'); lineBuffer = lines.pop(); // remainder for (const line of lines) { @@ -953,7 +956,7 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => }); child.stderr.on('data', (chunk) => { - const msg = chunk.toString('utf-8'); + const msg = stderrDecoder.push(chunk); stderrTail = (stderrTail + msg).slice(-2000); if (msg.trim().length > 0) { console.warn(`[codex-proxy stderr] ${msg.trim()}`); diff --git a/bin/commandcode-proxy.mjs b/bin/commandcode-proxy.mjs index 481b2e7d94..3aeb919f91 100644 --- a/bin/commandcode-proxy.mjs +++ b/bin/commandcode-proxy.mjs @@ -55,6 +55,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; const PORT = parseProxyPort('COMMANDCODE_PROXY_PORT', 18748); const HOST = process.env.COMMANDCODE_PROXY_HOST || '127.0.0.1'; @@ -588,14 +589,16 @@ const acp = { console.log(`[commandcode-proxy] ACP resident process started (pid ${child.pid}, start #${this.starts})`); let lineBuffer = ''; + const stdoutDecoder = createStreamDecoder(); + const stderrDecoder = createStreamDecoder(); child.stdout.on('data', chunk => { - lineBuffer += chunk.toString('utf-8'); + lineBuffer += stdoutDecoder.push(chunk); const lines = lineBuffer.split('\n'); lineBuffer = lines.pop(); for (const line of lines) this.handleLine(line); }); child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); + const msg = stderrDecoder.push(chunk); if (msg.trim().length > 0) console.warn(`[acp stderr] ${msg.trim().slice(0, 500)}`); }); child.on('error', err => console.error(`[commandcode-proxy] ACP process error: ${err.message}`)); @@ -1062,6 +1065,8 @@ const server = http.createServer((req, res) => { timer.unref(); let lineBuffer = ''; + const stdoutDecoder = createStreamDecoder(); + const stderrDecoder = createStreamDecoder(); let fullContent = ''; let finalText = null; let promptTokens = Math.max(1, Math.ceil(attempt.prompt.length / 4)); @@ -1142,7 +1147,7 @@ const server = http.createServer((req, res) => { }; child.stdout.on('data', chunk => { - lineBuffer += chunk.toString('utf-8'); + lineBuffer += stdoutDecoder.push(chunk); const lines = lineBuffer.split('\n'); lineBuffer = lines.pop(); // remainder for (const line of lines) { @@ -1151,7 +1156,7 @@ const server = http.createServer((req, res) => { }); child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); + const msg = stderrDecoder.push(chunk); stderrTail = (stderrTail + msg).slice(-2000); if (msg.trim().length > 0) { console.warn(`[commandcode-proxy stderr] ${msg.trim()}`); diff --git a/bin/design-code-proxy.mjs b/bin/design-code-proxy.mjs index 4756f5e499..27620d3b6e 100755 --- a/bin/design-code-proxy.mjs +++ b/bin/design-code-proxy.mjs @@ -3,6 +3,7 @@ import http from 'node:http'; import https from 'node:https'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; const PORT = parseProxyPort('DESIGN_CODE_PROXY_PORT', 18746); const HOST = process.env.DESIGN_CODE_PROXY_HOST || '127.0.0.1'; @@ -408,8 +409,9 @@ const dispatchWithFallback = (body, clientRes) => { if (stream) { writeHead(); let buffer = ''; + const streamDecoder = createStreamDecoder(); localRes.on('data', chunk => { - buffer += chunk.toString('utf-8'); + buffer += streamDecoder.push(chunk); const lines = buffer.split('\n'); buffer = lines.pop(); for (const line of lines) { @@ -432,11 +434,12 @@ const dispatchWithFallback = (body, clientRes) => { clientRes.end(); }); } else { - let fullBody = ''; + const fullBodyChunks = []; localRes.on('data', chunk => { - fullBody += chunk.toString('utf-8'); + fullBodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); }); localRes.on('end', () => { + const fullBody = Buffer.concat(fullBodyChunks).toString('utf-8'); try { const json = JSON.parse(fullBody); if (json.error && (json.error.code === 429 || json.error.type === 'insufficient_quota')) { diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs index ba5405f647..0f955c8ad5 100644 --- a/bin/muse-proxy.mjs +++ b/bin/muse-proxy.mjs @@ -32,6 +32,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; +import { createStreamDecoder } from './stream-decode.mjs'; // Default port 18747: 18746 is claimed by design-code-proxy // (DESIGN_CODE_PROXY_PORT) in this repo's config, so muse-proxy takes the @@ -240,8 +241,10 @@ const probeCliFlags = (subcommand) => new Promise((resolve) => { const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* already gone */ } }, 10000); - child.stdout.on('data', c => { out += c.toString('utf-8'); }); - child.stderr.on('data', c => { out += c.toString('utf-8'); }); + const flagScanDecoder = createStreamDecoder(); + child.stdout.on('data', c => { out += flagScanDecoder.push(c); }); + const flagScanStderrDecoder = createStreamDecoder(); + child.stderr.on('data', c => { out += flagScanStderrDecoder.push(c); }); child.on('error', () => { clearTimeout(timer); resolve(null); }); child.on('close', () => { clearTimeout(timer); @@ -460,14 +463,16 @@ const warmHost = { this.child = child; this.stderrTail = ''; let lineBuffer = ''; + const stdoutDecoder = createStreamDecoder(); + const stderrDecoder = createStreamDecoder(); child.stdout.on('data', chunk => { - lineBuffer += chunk.toString('utf-8'); + lineBuffer += stdoutDecoder.push(chunk); const lines = lineBuffer.split('\n'); lineBuffer = lines.pop(); for (const line of lines) this._onLine(line); }); child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); + const msg = stderrDecoder.push(chunk); this.stderrTail = (this.stderrTail + msg).slice(-2000); if (msg.trim().length > 0) console.warn(`[muse-proxy warm stderr] ${msg.trim()}`); }); @@ -1712,6 +1717,8 @@ const server = http.createServer((req, res) => { } let lineBuffer = ''; + const stdoutDecoder = createStreamDecoder(); + const stderrDecoder = createStreamDecoder(); let fullContent = ''; let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); let completionTokens = 0; @@ -1771,7 +1778,7 @@ const server = http.createServer((req, res) => { }; child.stdout.on('data', chunk => { - lineBuffer += chunk.toString('utf-8'); + lineBuffer += stdoutDecoder.push(chunk); const lines = lineBuffer.split('\n'); lineBuffer = lines.pop(); // remainder for (const line of lines) { @@ -1780,7 +1787,7 @@ const server = http.createServer((req, res) => { }); child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); + const msg = stderrDecoder.push(chunk); stderrTail = (stderrTail + msg).slice(-2000); if (msg.trim().length > 0) { console.warn(`[muse-proxy stderr] ${msg.trim()}`); diff --git a/bin/stream-decode.mjs b/bin/stream-decode.mjs new file mode 100644 index 0000000000..697e638ba7 --- /dev/null +++ b/bin/stream-decode.mjs @@ -0,0 +1,19 @@ +/** Decode a byte stream chunk by chunk without corrupting multibyte UTF-8 + * sequences split across chunk boundaries (#4336). Per-chunk + * `chunk.toString('utf-8')` turns a split sequence into U+FFFD on both + * sides; StringDecoder holds the partial bytes until the rest arrives. + * This is the streaming counterpart of request-body.mjs (#3186), which + * covers whole-body collection. */ +import { StringDecoder } from 'node:string_decoder'; + +export function createStreamDecoder(encoding = 'utf-8') { + const decoder = new StringDecoder(encoding); + return { + push(chunk) { + return decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }, + end() { + return decoder.end(); + }, + }; +} diff --git a/bin/stream-decode.test.mjs b/bin/stream-decode.test.mjs new file mode 100644 index 0000000000..9eba32ac2a --- /dev/null +++ b/bin/stream-decode.test.mjs @@ -0,0 +1,35 @@ +// Tests for stream-decode's chunk-boundary-safe UTF-8 decoding (#4336). +// Run: node --test bin/stream-decode.test.mjs +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createStreamDecoder } from './stream-decode.mjs'; + +const TEXT = '{"type":"assistant","text":"before-☃é😀-after"}\n'; + +test('preserves multibyte UTF-8 split at every byte offset (#4336)', () => { + const bytes = Buffer.from(TEXT, 'utf-8'); + for (let split = 1; split < bytes.length; split++) { + const decoder = createStreamDecoder(); + const out = decoder.push(bytes.subarray(0, split)) + decoder.push(bytes.subarray(split)) + decoder.end(); + assert.equal(out, TEXT, `split at byte ${split}`); + assert.ok(!out.includes('�'), `split at byte ${split} produced U+FFFD`); + } +}); + +test('preserves multibyte UTF-8 fed one byte at a time (#4336)', () => { + const bytes = Buffer.from(TEXT, 'utf-8'); + const decoder = createStreamDecoder(); + let out = ''; + for (const byte of bytes) out += decoder.push(Buffer.from([byte])); + out += decoder.end(); + assert.equal(out, TEXT); +}); + +test('JSON line survives a split inside a 3-byte sequence (#4336)', () => { + const bytes = Buffer.from(TEXT, 'utf-8'); + const snowmanStart = Buffer.from('{"type":"assistant","text":"before-', 'utf-8').length; + const decoder = createStreamDecoder(); + const out = decoder.push(bytes.subarray(0, snowmanStart + 1)) + decoder.push(bytes.subarray(snowmanStart + 1)) + decoder.end(); + const parsed = JSON.parse(out.trim()); + assert.equal(parsed.text, 'before-☃é😀-after'); +});