Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/mcp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,10 @@ async function connectStdio(name: string, config: McpServerConfig): Promise<Conn
const stderr = transport.stderr;
if (stderr) {
let buf = '';
stderr.on('data', (chunk: Buffer) => {
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) {
Expand Down
5 changes: 4 additions & 1 deletion src/proxy/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});

Expand Down
19 changes: 15 additions & 4 deletions src/tools/bash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -411,38 +412,48 @@ 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;
if (remaining <= 0) {
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;
if (remaining <= 0) {
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;
}
Expand Down
83 changes: 82 additions & 1 deletion test/local.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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-'));
Expand Down Expand Up @@ -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) => {
Expand Down
Loading