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
69 changes: 57 additions & 12 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1139,35 +1139,60 @@ const DIRECT_TOOL_NAMES = Object.fromEntries(
);
const directToolAlias = (name, taken) => {
const alias = DIRECT_TOOL_ALIASES[name];
if (!alias || (taken && taken.has(alias))) return name;
if (!alias) return name;
if (taken && taken.has(alias)) {
const error = new Error(`Cannot safely alias tool "${name}": "${alias}" is already defined`);
error.code = 'DIRECT_TOOL_ALIAS_COLLISION';
throw error;
}
return alias;
};
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.
// malformed JSON is rejected locally instead of silently bypassing aliasing.
const aliasResponsesRequestBody = (bodyText) => {
let parsed;
try { parsed = JSON.parse(bodyText); } catch { return { text: bodyText, aliased: false }; }
try { parsed = JSON.parse(bodyText); } catch {
return { error: 'Request body is not valid JSON; refusing to forward it unaliased' };
}
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);
let next;
try {
next = directToolAlias(holder.name, taken);
} catch (error) {
if (error.code === 'DIRECT_TOOL_ALIAS_COLLISION') return error.message;
throw error;
}
if (next !== holder.name) { holder.name = next; aliased = true; }
}
return null;
};
if (Array.isArray(parsed.tools)) for (const t of parsed.tools) rename(t);
if (Array.isArray(parsed.tools)) {
for (const t of parsed.tools) {
const error = rename(t);
if (error) return { error };
}
}
if (Array.isArray(parsed.input)) {
for (const item of parsed.input) {
if (item && item.type === 'function_call') rename(item);
if (item && item.type === 'function_call') {
const error = rename(item);
if (error) return { error };
}
}
}
if (parsed.tool_choice && parsed.tool_choice.type === 'function') rename(parsed.tool_choice);
if (parsed.tool_choice && parsed.tool_choice.type === 'function') {
const error = rename(parsed.tool_choice);
if (error) return { error };
}
return aliased ? { text: JSON.stringify(parsed), aliased } : { text: bodyText, aliased };
};

Expand All @@ -1186,10 +1211,17 @@ 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);
const unaliasFunctionCalls = (value) => {
if (Array.isArray(value)) {
for (const item of value) unaliasFunctionCalls(item);
} else if (value && typeof value === 'object') {
if (value.type === 'function_call' && typeof value.name === 'string') {
value.name = clientToolName(value.name);
}
for (const child of Object.values(value)) unaliasFunctionCalls(child);
}
};
unaliasFunctionCalls(evt);
return JSON.stringify(evt);
};

Expand Down Expand Up @@ -1430,7 +1462,16 @@ const tryDirectChat = async ({ body, baseModel, effort, fullName, stream, res, c
writeJsonBody(res, 502, { error: { message: keyResult.message } });
return true;
}
const upstreamBody = JSON.stringify(buildResponsesRequest(body, baseModel, effort));
let upstreamBody;
try {
upstreamBody = JSON.stringify(buildResponsesRequest(body, baseModel, effort));
} catch (error) {
if (error.code === 'DIRECT_TOOL_ALIAS_COLLISION') {
writeJsonBody(res, 400, { error: { message: error.message } });
return true;
}
throw error;
}
let outcome;
try {
outcome = await directResponsesFetch(keyResult, upstreamBody, stream ? 'text/event-stream' : 'application/json');
Expand Down Expand Up @@ -1605,6 +1646,10 @@ const server = http.createServer((req, res) => {
let aliasedBody = { text: bodyText, aliased: false };
try {
aliasedBody = aliasResponsesRequestBody(bodyText);
if (aliasedBody.error) {
writeJsonBody(res, 400, { error: { message: aliasedBody.error } });
return;
}
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}` } });
Expand Down
74 changes: 74 additions & 0 deletions bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,14 @@ const startMetaStub = async (mode) => {
res.end(JSON.stringify({ received: JSON.parse(body || '{}'), authorization: req.headers.authorization }));
return;
}
if (mode === 'shell-generic-sse') {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
res.end(`event: response.custom\ndata: ${JSON.stringify({
type: 'response.custom',
payload: { calls: [{ type: 'function_call', name: 'run_command' }] }
})}\n\n`);
return;
}
if (mode === 'failed-empty' || mode === 'failed-partial') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
Expand Down Expand Up @@ -957,6 +965,72 @@ test('direct mode: /v1/responses streaming translates aliased tool calls back',
assert.ok(!sse.includes('run_command'), 'the alias never leaks to the client');
});

test('direct mode: /v1/responses aliases are rejected when the alias is already taken', async (t) => {
const meta = await startMetaStub('echo');
t.after(() => meta.close());
const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url });
t.after(stop);
writeStubAuth(home);

for (const [existingName, blockedName] of [['run_command', 'shell'], ['terminal', 'bash']]) {
const res = await fetch(`http://127.0.0.1:${port}/v1/responses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'muse-spark-1.3',
input: [],
tools: [
{ type: 'function', name: existingName, parameters: { type: 'object' } },
{ type: 'function', name: blockedName, parameters: { type: 'object' } }
]
})
});
assert.equal(res.status, 400);
assert.match((await res.json()).error.message, new RegExp(`Cannot safely alias tool "${blockedName}"`));
}
assert.equal(meta.requests.filter(r => r.url === '/v1/responses').length, 0, 'the blocked tool name never goes upstream');
});

test('direct mode: /v1/responses rejects unparseable JSON instead of forwarding it', async (t) => {
const meta = await startMetaStub('echo');
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' },
body: '{'
});
assert.equal(res.status, 400);
assert.match((await res.json()).error.message, /not valid JSON/);
assert.equal(meta.requests.filter(r => r.url === '/v1/responses').length, 0, 'unparseable bytes are not forwarded');
});

test('direct mode: /v1/responses streaming unaliases nested function_call items', async (t) => {
const meta = await startMetaStub('shell-generic-sse');
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' },
body: JSON.stringify({
model: 'muse-spark-1.3',
stream: true,
input: [],
tools: [{ type: 'function', name: 'shell', parameters: { type: 'object' } }]
})
});
assert.equal(res.status, 200);
const sse = await res.text();
assert.match(sse, /"name":"shell"/);
assert.ok(!sse.includes('run_command'), 'the alias never leaks from an arbitrary nested event shape');
});

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