From 4bc307dcc27db6df19526d1b48229efd53a542d8 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 13 Nov 2026 02:22:21 -0400 Subject: [PATCH] fix: decode UTF-8 incrementally in proxy body, bash output and MCP stderr Multi-byte characters split across stream chunks were turned into U+FFFD by per-chunk toString()/string concatenation. Use stream setEncoding or a StringDecoder per stream so partial sequences carry over. --- src/mcp/client.ts | 6 ++-- src/proxy/server.ts | 5 ++- src/tools/bash.ts | 19 ++++++++--- test/local.mjs | 83 ++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 105 insertions(+), 8 deletions(-) diff --git a/src/mcp/client.ts b/src/mcp/client.ts index 039ea469..2f0beb59 100644 --- a/src/mcp/client.ts +++ b/src/mcp/client.ts @@ -271,8 +271,10 @@ async function connectStdio(name: string, config: McpServerConfig): Promise { - buf += chunk.toString('utf8'); + // Decode incrementally so multi-byte characters split across chunks survive. + (stderr as NodeJS.ReadableStream).setEncoding('utf8'); + stderr.on('data', (chunk: string | Buffer) => { + buf += chunk.toString(); const lines = buf.split('\n'); buf = lines.pop() || ''; for (const line of lines) { diff --git a/src/proxy/server.ts b/src/proxy/server.ts index 6923099d..99518e9a 100644 --- a/src/proxy/server.ts +++ b/src/proxy/server.ts @@ -352,7 +352,10 @@ export function createProxy(options: ProxyOptions): http.Server { let body = ''; const requestStartTime = Date.now(); - req.on('data', (chunk: Buffer) => { + // Decode incrementally: a multi-byte UTF-8 character can be split across + // 'data' chunks, and `body += chunk` would decode each Buffer on its own. + req.setEncoding('utf8'); + req.on('data', (chunk: string) => { body += chunk; }); diff --git a/src/tools/bash.ts b/src/tools/bash.ts index 5246b968..d3d9a620 100644 --- a/src/tools/bash.ts +++ b/src/tools/bash.ts @@ -3,6 +3,7 @@ */ import { spawn } from 'node:child_process'; +import { StringDecoder } from 'node:string_decoder'; import fs from 'node:fs'; import type { CapabilityHandler, CapabilityResult, ExecutionScope } from '../agent/types.js'; import { sanitizeSubprocessEnv } from './subprocess-env.js'; @@ -411,6 +412,9 @@ function executeCommand(command: string, timeoutMs: number, ctx: ExecutionScope) if (lastLine) ctx.onProgress(lastLine.slice(0, 120)); }; + // Decode per stream so a multi-byte UTF-8 character split across two + // chunks is not replaced by U+FFFD. + const stdoutDecoder = new StringDecoder('utf8'); child.stdout?.on('data', (chunk: Buffer) => { if (truncated) return; const remaining = MAX_OUTPUT_BYTES - outputBytes; @@ -418,18 +422,23 @@ function executeCommand(command: string, timeoutMs: number, ctx: ExecutionScope) truncated = true; return; } - const text = chunk.toString('utf-8'); + let text: string; if (chunk.length <= remaining) { + text = stdoutDecoder.write(chunk); stdout += text; outputBytes += chunk.length; } else { - stdout += text.slice(0, remaining); + text = stdoutDecoder.write(chunk.subarray(0, remaining)) + stdoutDecoder.end(); + stdout += text; outputBytes = MAX_OUTPUT_BYTES; truncated = true; } emitProgress(text); }); + // Decode per stream so a multi-byte UTF-8 character split across two + // chunks is not replaced by U+FFFD. + const stderrDecoder = new StringDecoder('utf8'); child.stderr?.on('data', (chunk: Buffer) => { if (truncated) return; const remaining = MAX_OUTPUT_BYTES - outputBytes; @@ -437,12 +446,14 @@ function executeCommand(command: string, timeoutMs: number, ctx: ExecutionScope) truncated = true; return; } - const text = chunk.toString('utf-8'); + let text: string; if (chunk.length <= remaining) { + text = stderrDecoder.write(chunk); stderr += text; outputBytes += chunk.length; } else { - stderr += text.slice(0, remaining); + text = stderrDecoder.write(chunk.subarray(0, remaining)) + stderrDecoder.end(); + stderr += text; outputBytes = MAX_OUTPUT_BYTES; truncated = true; } diff --git a/test/local.mjs b/test/local.mjs index 17422c60..e55bfd53 100644 --- a/test/local.mjs +++ b/test/local.mjs @@ -30,7 +30,7 @@ process.env.FRANKLIN_ALLOW_PRIVATE_FETCH = '1'; import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { createServer } from 'node:http'; +import { createServer, request } from 'node:http'; import { execFileSync, spawn } from 'node:child_process'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unwatchFile, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -607,6 +607,74 @@ test('proxy Auto routes through the shared portfolio before forwarding', async ( } }); +test('proxy preserves multi-byte UTF-8 characters split across request body chunks', async () => { + const originalHome = process.env.HOME; + const fakeHome = mkdtempSync(join(tmpdir(), 'rc-proxy-utf8-home-')); + const proxyUrl = new URL('../dist/proxy/server.js', import.meta.url); + const forwarded = []; + const backend = createServer(async (req, res) => { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + forwarded.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ + id: 'msg_utf8', + type: 'message', + role: 'assistant', + model: 'zai/glm-5.1', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + usage: { input_tokens: 4, output_tokens: 2 }, + })); + }); + + let proxy; + try { + process.env.HOME = fakeHome; + const backendPort = await listenOnRandomPort(backend); + const { createProxy } = await import(`${proxyUrl.href}?t=${Date.now()}`); + proxy = createProxy({ + authToken: TEST_PROXY_TOKEN, + port: 0, + apiUrl: `http://127.0.0.1:${backendPort}`, + chain: 'base', + modelOverride: 'zai/glm-5.1', + fallbackEnabled: false, + }); + const proxyPort = await listenOnRandomPort(proxy); + const prompt = 'Price is \u20ac20'; + const bytes = Buffer.from(JSON.stringify({ + model: 'zai/glm-5.1', + messages: [{ role: 'user', content: prompt }], + max_tokens: 64, + })); + // Cut inside the 3-byte euro sign so the proxy sees it split across two 'data' events. + const cut = bytes.indexOf(Buffer.from('\u20ac')) + 1; + + await new Promise((resolve, reject) => { + const clientReq = request({ + host: '127.0.0.1', + port: proxyPort, + path: '/api/v1/messages', + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Content-Length': bytes.length, Authorization: `Bearer ${TEST_PROXY_TOKEN}` }, + }, (res) => { res.resume(); res.on('end', resolve); }); + clientReq.on('error', reject); + clientReq.write(bytes.subarray(0, cut)); + setTimeout(() => clientReq.end(bytes.subarray(cut)), 100); + }); + + assert.equal(forwarded.length, 1); + assert.equal(forwarded[0].messages[0].content, prompt); + } finally { + if (proxy) await new Promise((resolve) => proxy.close(() => resolve())); + await new Promise((resolve) => backend.close(() => resolve())); + if (originalHome === undefined) delete process.env.HOME; + else process.env.HOME = originalHome; + rmSync(fakeHome, { recursive: true, force: true }); + } +}); + test('proxy Auto honors tool_choice none as a hard no-tool constraint', async () => { const originalHome = process.env.HOME; const fakeHome = mkdtempSync(join(tmpdir(), 'rc-proxy-auto-none-home-')); @@ -1409,6 +1477,19 @@ test('bash capability reports user abort distinctly from timeout', async () => { assert.ok(!result.output.includes('timeout after'), `Abort should not be mislabeled as timeout.\n${result.output}`); }); +test('bash capability keeps multi-byte characters split across output chunks', async () => { + const { bashCapability } = await import('../dist/tools/bash.js'); + // printf emits the three bytes of the euro sign (E2 82 AC) in separate writes. + const command = "printf '\\342\\202'; sleep 0.3; printf '\\254 20'; printf '\\342\\202' >&2; sleep 0.3; printf '\\254 30' >&2"; + const result = await bashCapability.execute( + { command }, + { workingDir: process.cwd(), abortSignal: new AbortController().signal } + ); + assert.ok(result.output.includes('€ 20'), `stdout corrupted: ${JSON.stringify(result.output)}`); + assert.ok(result.output.includes('€ 30'), `stderr corrupted: ${JSON.stringify(result.output)}`); + assert.ok(!result.output.includes('\uFFFD'), `Unexpected replacement character: ${JSON.stringify(result.output)}`); +}); + test('webfetch cache key includes max_length to avoid stale truncated responses', async () => { let hits = 0; const server = createServer((_req, res) => {