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
10 changes: 7 additions & 3 deletions bin/agy-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -261,14 +262,15 @@ const pullModelsLive = () => new Promise((resolve) => {
stdio: ['ignore', 'pipe', 'pipe']
});
let stdout = '';
const stdoutDecoder = createStreamDecoder();
let settled = false;
const done = (ok, fullIds) => {
if (settled) return;
settled = true;
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) => {
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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 }));
Expand Down Expand Up @@ -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);
Expand Down
7 changes: 5 additions & 2 deletions bin/claude-code-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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)}`);
});
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 5 additions & 2 deletions bin/codex-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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()}`);
Expand Down
13 changes: 9 additions & 4 deletions bin/commandcode-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}`));
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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) {
Expand All @@ -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()}`);
Expand Down
9 changes: 6 additions & 3 deletions bin/design-code-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand All @@ -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')) {
Expand Down
19 changes: 13 additions & 6 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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()}`);
});
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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()}`);
Expand Down
19 changes: 19 additions & 0 deletions bin/stream-decode.mjs
Original file line number Diff line number Diff line change
@@ -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();
},
};
}
35 changes: 35 additions & 0 deletions bin/stream-decode.test.mjs
Original file line number Diff line number Diff line change
@@ -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');
});