Skip to content
Closed
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
105 changes: 95 additions & 10 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,48 @@ const directToolAlias = (name, taken) => {
};
const clientToolName = (name) => DIRECT_TOOL_NAMES[name] || name;

// The /v1/responses passthrough applies the same aliasing as the chat
// translation (#2764 follow-up): its native client — OpenCode's
// muse-direct provider (@ai-sdk/openai) — sends the same tool set and
// hit the same attestation denial the chat path did, so "verbatim"
// forwarding 403s every tool-using session. Outbound: tool definitions,
// history function_call items, and a function tool_choice are aliased.
// Inbound: function_call names in the response (buffered JSON or SSE
// events) are translated back to the client's names.
const aliasResponsesRequest = (parsed) => {
if (!parsed || typeof parsed !== 'object') return false;
let changed = false;
const alias = (holder) => {
const next = directToolAlias(holder.name, taken);
if (next !== holder.name) { holder.name = next; changed = true; }
Comment on lines +1082 to +1083

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude inherited properties from outbound alias lookups

On native Responses requests containing a function named constructor, toString, or __proto__, this newly added aliasing step corrupts the tool definition even though none of those names is a configured alias. directToolAlias indexes a normal object without checking ownership, so it returns inherited functions or objects; assigning that result here makes serialization omit the tool name or emit name: {}. These requests previously passed through unchanged and now reach upstream with invalid definitions. Require an own-property match in the alias table before replacing a name.

Useful? React with 👍 / 👎.

};
const tools = Array.isArray(parsed.tools) ? parsed.tools : [];
const taken = new Set(tools.map(t => t && t.name).filter(Boolean));
for (const t of tools) {
if (t && t.type === 'function' && t.name) alias(t);
}
if (Array.isArray(parsed.input)) {
for (const item of parsed.input) {
if (item && item.type === 'function_call' && item.name) alias(item);
}
}
const tc = parsed.tool_choice;
if (tc && typeof tc === 'object' && tc.type === 'function' && tc.name) alias(tc);
return changed;
};

const restoreFnCallNames = (container) => {
if (!container || typeof container !== 'object') return;
if (container.type === 'function_call' && container.name) {
container.name = clientToolName(container.name);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore only aliases applied to the current request

When a client defines a tool named terminal or run_command, the outbound request preserves that name, but this unconditional reverse mapping changes its returned function calls to bash or shell. This also defeats the outbound collision guard when both original and alias names are defined, potentially dispatching the wrong tool. Track the aliases actually applied to each request and use only that request-local mapping when restoring buffered responses and SSE events.

Useful? React with 👍 / 👎.

}
if (Array.isArray(container.output)) {
for (const item of container.output) restoreFnCallNames(item);
}
if (container.item) restoreFnCallNames(container.item);
if (container.response) restoreFnCallNames(container.response);
};

const buildResponsesRequest = (body, baseModel, effort) => {
const messages = Array.isArray(body.messages) ? body.messages : [];
const instructions = messages
Expand Down Expand Up @@ -1426,10 +1468,13 @@ const server = http.createServer((req, res) => {


// Responses passthrough (direct mode, #2753): the client's body is
// forwarded verbatim to the upstream Responses API with only the
// Authorization header swapped for the minted plan key. Any upstream
// HTTP response is piped through as-is. Without direct credentials the
// route is not offered (404, as before direct mode existed).
// forwarded to the upstream Responses API with the Authorization
// header swapped for the minted plan key and the shell-tool names
// aliased (see aliasResponsesRequest — the attestation gate applies
// to this route's clients too); function_call names in the response
// are translated back. Any upstream HTTP response is otherwise
// returned as-is. Without direct credentials the route is not
// offered (404, as before direct mode existed).
if (req.method === 'POST' && (pathname === '/v1/responses' || pathname === '/responses')) {
let bodyText = '';
req.on('data', chunk => {
Expand All @@ -1453,9 +1498,14 @@ const server = http.createServer((req, res) => {
});
return;
}
let parsedBody = null;
try { parsedBody = JSON.parse(bodyText); } catch { /* not JSON: forward raw */ }
// Bodies with nothing to alias keep travelling byte-for-byte.
const outboundText = (parsedBody && aliasResponsesRequest(parsedBody))
? JSON.stringify(parsedBody) : bodyText;
let outcome;
try {
outcome = await directResponsesFetch(keyResult, bodyText, req.headers.accept || 'application/json');
outcome = await directResponsesFetch(keyResult, outboundText, req.headers.accept || 'application/json');
} catch (err) {
writeJsonBody(res, 502, { error: { message: `Direct Meta route request failed: ${err.message}` } });
return;
Expand All @@ -1465,19 +1515,54 @@ const server = http.createServer((req, res) => {
return;
}
const response = outcome.response;
res.writeHead(response.status, {
'Content-Type': response.headers.get('content-type') || 'application/json'
});
if (response.body && typeof response.body.getReader === 'function') {
const contentType = response.headers.get('content-type') || 'application/json';
res.writeHead(response.status, { 'Content-Type': contentType });
if (contentType.includes('text/event-stream') && response.body && typeof response.body.getReader === 'function') {
// SSE: restore tool names per event. Events are `data:` blocks
// separated by blank lines; non-JSON payloads pass untouched.
const restoreEventBlock = (block) => block.split('\n').map(line => {
if (!line.startsWith('data:')) return line;
const payload = line.slice(5).trim();
if (!payload || payload === '[DONE]') return line;
try {
const evt = JSON.parse(payload);
restoreFnCallNames(evt);
return `data: ${JSON.stringify(evt)}`;
} catch { return line; }
}).join('\n');
try {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
res.write(Buffer.from(value));
buf += decoder.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf('\n\n')) >= 0) {
res.write(restoreEventBlock(buf.slice(0, idx)) + '\n\n');
buf = buf.slice(idx + 2);
Comment on lines +1542 to +1544

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recognize CRLF-delimited SSE events before buffering further

If upstream sends SSE events with CRLF line endings, the event separator is \r\n\r\n, so this search never finds a boundary. Unlike the previous streaming passthrough, the proxy buffers the entire response until upstream closes, withholding all incremental output and potentially triggering client idle timeouts during long generations. Recognize CRLF boundaries as well as LF boundaries, including separators split across reads.

Useful? React with 👍 / 👎.

}
}
if (buf) res.write(restoreEventBlock(buf));
} catch { /* upstream stream cut: end with what was sent */ }
res.end();
} else if (response.body && typeof response.body.getReader === 'function') {
try {
const reader = response.body.getReader();
const chunks = [];
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(Buffer.from(value));
}
const text = Buffer.concat(chunks).toString('utf8');
try {
const parsed = JSON.parse(text);
restoreFnCallNames(parsed);
res.end(JSON.stringify(parsed));
} catch { res.end(text); }
} catch { res.end(); }
} else {
res.end(await response.text().catch(() => ''));
}
Expand Down
57 changes: 57 additions & 0 deletions bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,21 @@ const startMetaStub = async (mode) => {
res.end(JSON.stringify({ error: { message: 'Subscription quota exhausted', type: 'rate_limit_error' } }));
return;
}
if (mode === 'passthrough-tools') {
let reqBody = {};
try { reqBody = JSON.parse(body || '{}'); } catch { /* keep empty */ }
const callItem = { type: 'function_call', call_id: 'call_pt1', name: 'terminal', arguments: '{"command":"echo hi"}' };
if (reqBody.stream) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
res.end(
`data: ${JSON.stringify({ type: 'response.output_item.added', item: { ...callItem, status: 'in_progress' } })}\n\n` +
`data: ${JSON.stringify({ type: 'response.completed', response: { id: 'resp_pt', status: 'completed', output: [callItem] } })}\n\n`);
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 'resp_pt', object: 'response', status: 'completed', output: [callItem] }));
}
return;
}
if (mode === 'echo') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: JSON.parse(body || '{}'), authorization: req.headers.authorization }));
Expand Down Expand Up @@ -833,3 +848,45 @@ test('direct mode: contributor ids reach upstream verbatim, effort suffix parses
assert.deepEqual(sent[1].reasoning, { effort: 'high' });
assert.equal(sent[2].model, 'muse-spark-1.3', 'plain base model stays plain upstream');
});

test('direct mode: /v1/responses passthrough aliases shell tools out and restores call names back (#2764)', async (t) => {
const meta = await startMetaStub('passthrough-tools');
t.after(() => meta.close());
const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url });
t.after(stop);
writeStubAuth(home);

const clientBody = {
model: 'muse-spark-1.3-contributor',
input: [
{ role: 'user', content: 'run echo hi' },
{ type: 'function_call', call_id: 'call_prev', name: 'bash', arguments: '{"command":"ls"}' }
],
tools: [{ type: 'function', name: 'bash', description: 'Run a bash command', parameters: { type: 'object', properties: { command: { type: 'string' } } } }],
tool_choice: { type: 'function', name: 'bash' },
stream: false
};
const res = await fetch(`http://127.0.0.1:${port}/v1/responses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer client-side' },
body: JSON.stringify(clientBody)
});
assert.equal(res.status, 200);
const upstream = JSON.parse(meta.requests.filter(r => r.url === '/v1/responses')[0].body);
assert.equal(upstream.tools[0].name, 'terminal', 'tool definitions are aliased upstream');
assert.equal(upstream.input[1].name, 'terminal', 'history function_call items are aliased upstream');
assert.equal(upstream.tool_choice.name, 'terminal', 'tool_choice is aliased upstream');
assert.equal(upstream.authorization, undefined, 'no credential material in the body');
const out = JSON.parse(await res.text());
assert.equal(out.output[0].name, 'bash', 'the model call name is restored for the client');

const sres = await fetch(`http://127.0.0.1:${port}/v1/responses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer client-side' },
body: JSON.stringify({ ...clientBody, stream: true })
});
assert.equal(sres.status, 200);
const streamText = await sres.text();
assert.match(streamText, /"name":"bash"/, 'SSE events carry the restored client name');
assert.ok(!streamText.includes('"name":"terminal"'), 'the alias never leaks to the client');
});