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
107 changes: 99 additions & 8 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,55 @@ const directToolAlias = (name, taken) => {
};
const clientToolName = (name) => DIRECT_TOOL_NAMES[name] || name;

// The /v1/responses passthrough forwards client bodies in Responses shape;
// apply the same tool-name aliasing there, in both directions, so a native
// client (the muse-direct provider) passes the attestation gate too. An
// unparseable body forwards verbatim, exactly as before.
const aliasResponsesRequestBody = (bodyText) => {
let parsed;
try { parsed = JSON.parse(bodyText); } catch { return { text: bodyText, aliased: false }; }
if (!parsed || typeof parsed !== 'object') return { text: bodyText, aliased: false };
const taken = new Set((Array.isArray(parsed.tools) ? parsed.tools : [])
.map(t => t && t.name).filter(Boolean));
let aliased = false;
const rename = (holder) => {
if (holder && typeof holder.name === 'string') {
const next = directToolAlias(holder.name, taken);
if (next !== holder.name) { holder.name = next; aliased = true; }
Comment on lines +1083 to +1084

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 tool alias lookup

For valid native Responses tool names such as toString or constructor, calling directToolAlias here resolves inherited properties of DIRECT_TOOL_ALIASES rather than an explicit alias. Consequently, holder.name becomes a function and JSON.stringify(parsed) removes the name entirely: a request containing {type: 'function', name: 'toString'} is forwarded with an unnamed tool. These requests previously passed through unchanged. Restrict alias lookup to own properties or use a null-prototype map.

Useful? React with 👍 / 👎.

}
};
if (Array.isArray(parsed.tools)) for (const t of parsed.tools) rename(t);
if (Array.isArray(parsed.input)) {
for (const item of parsed.input) {
if (item && item.type === 'function_call') rename(item);
}
}
if (parsed.tool_choice && parsed.tool_choice.type === 'function') rename(parsed.tool_choice);
return aliased ? { text: JSON.stringify(parsed), aliased } : { text: bodyText, aliased };
};

const unaliasResponsesOutput = (holder) => {
if (!holder || typeof holder !== 'object') return;
for (const item of holder.output || []) {
if (item && item.type === 'function_call' && typeof item.name === 'string') {
item.name = clientToolName(item.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 Reverse only aliases actually applied to this request

When a native Responses request declares both shell and a genuine terminal tool, the request becomes run_command plus terminal, but this unconditional reverse mapping changes an upstream terminal call into bash, which the client never declared. The streaming path has the same problem through unaliasSseData. Track the aliases applied per request and use that map for both JSON and SSE responses so unrelated tools retain their names.

Useful? React with 👍 / 👎.

}
}
};

// Rewrite one SSE data payload if it carries an aliased tool name in a
// function_call item; anything else passes through untouched.
const unaliasSseData = (data) => {
if (!data.includes('run_command') && !data.includes('terminal')) return data;
let evt;
try { evt = JSON.parse(data); } catch { return data; }
if (evt && evt.item && evt.item.type === 'function_call' && typeof evt.item.name === 'string') {
evt.item.name = clientToolName(evt.item.name);
}
if (evt && evt.response) unaliasResponsesOutput(evt.response);
return JSON.stringify(evt);
};

const buildResponsesRequest = (body, baseModel, effort) => {
const messages = Array.isArray(body.messages) ? body.messages : [];
const instructions = messages
Expand Down Expand Up @@ -1454,8 +1503,10 @@ const server = http.createServer((req, res) => {
return;
}
let outcome;
let aliasedBody = { text: bodyText, aliased: false };
try {
outcome = await directResponsesFetch(keyResult, bodyText, req.headers.accept || 'application/json');
aliasedBody = aliasResponsesRequestBody(bodyText);
outcome = await directResponsesFetch(keyResult, aliasedBody.text, req.headers.accept || 'application/json');
} catch (err) {
writeJsonBody(res, 502, { error: { message: `Direct Meta route request failed: ${err.message}` } });
return;
Expand All @@ -1465,22 +1516,62 @@ 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';
if (!aliasedBody.aliased) {
res.writeHead(response.status, { 'Content-Type': contentType });
if (response.body && typeof response.body.getReader === 'function') {
try {
const reader = response.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
res.write(Buffer.from(value));
}
} catch { /* upstream stream cut: end with what was sent */ }
res.end();
} else {
res.end(await response.text().catch(() => ''));
}
return;
}
// Aliased request: the model's tool calls come back under the alias
// names and must be translated before the client sees them.
if (contentType.includes('text/event-stream') && response.body && typeof response.body.getReader === 'function') {
res.writeHead(response.status, { 'Content-Type': contentType });
try {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const flushLine = (line) => {
if (line.startsWith('data: ') && line.length > 6 && !line.startsWith('data: [DONE]')) {
res.write(`data: ${unaliasSseData(line.slice(6))}\n`);
} else {
res.write(line + '\n');
}
};
for (;;) {
const { done, value } = await reader.read();
if (done) break;
res.write(Buffer.from(value));
buffer += decoder.decode(value, { stream: true });
let nl;
while ((nl = buffer.indexOf('\n')) >= 0) {
flushLine(buffer.slice(0, nl));
buffer = buffer.slice(nl + 1);
}
}
if (buffer) flushLine(buffer);
} catch { /* upstream stream cut: end with what was sent */ }
res.end();
} else {
res.end(await response.text().catch(() => ''));
return;
}
let text = await response.text().catch(() => '');
try {
const parsedJson = JSON.parse(text);
unaliasResponsesOutput(parsedJson);
text = JSON.stringify(parsedJson);
} catch { /* not JSON: pass through as-is */ }
res.writeHead(response.status, { 'Content-Type': contentType });
res.end(text);
});
return;
}
Expand Down
54 changes: 54 additions & 0 deletions bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,60 @@ test('direct mode: /v1/responses passes the body through verbatim, swapping only
assert.equal(upstream[0].body, JSON.stringify(clientBody), 'byte-for-byte passthrough on the wire');
});

test('direct mode: /v1/responses aliases the shell tool and translates calls back', async (t) => {
const meta = await startMetaStub('shell');
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',
stream: false,
input: [
{ type: 'function_call', call_id: 'call_0', name: 'shell', arguments: '{"command":"echo hi"}' },
{ type: 'function_call_output', call_id: 'call_0', output: 'hi' },
{ role: 'user', content: 'what did it print?' }
],
tools: [{ type: 'function', name: 'shell', description: 'Run a shell command', parameters: { type: 'object', properties: { command: { type: 'string' } } } }]
};
const res = await fetch(`http://127.0.0.1:${port}/v1/responses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer <redacted>' },
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, 'run_command', 'the tool definition is aliased upstream');
assert.equal(upstream.input[0].name, 'run_command', 'history function calls are aliased upstream');
const respBody = JSON.parse(await res.text());
const call = respBody.output.find(i => i.type === 'function_call');
assert.equal(call.name, 'shell', 'the returned call is translated back to the client name');
});

test('direct mode: /v1/responses streaming translates aliased tool calls back', async (t) => {
const meta = await startMetaStub('shell');
t.after(() => meta.close());
const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url });
t.after(stop);
writeStubAuth(home);

const res = await fetch(`http://127.0.0.1:${port}/v1/responses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer <redacted>' },
body: JSON.stringify({
model: 'muse-spark-1.3',
stream: true,
input: [{ role: 'user', content: 'hi' }],
tools: [{ type: 'function', name: 'shell', description: 'Run', parameters: { type: 'object' } }]
})
});
assert.equal(res.status, 200);
const sse = await res.text();
assert.ok(sse.includes('"name":"shell"'), 'the streamed function_call carries the client name');
assert.ok(!sse.includes('run_command'), 'the alias never leaks to the client');
});

test('direct mode: MUSE_PROXY_DIRECT=0 leaves the exec path in charge (#2753)', async (t) => {
const meta = await startMetaStub('chat');
t.after(() => meta.close());
Expand Down