diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs index 0c911baa91..4f6cc1bd1c 100644 --- a/bin/muse-proxy.mjs +++ b/bin/muse-proxy.mjs @@ -10,6 +10,13 @@ // possible — see the warm-sessions section below. The exec path remains as // the fallback for any warm failure and when MUSE_PROXY_WARM=0. // +// Direct mode (#2753): a third, first-tried path. The CLI's OAuth login +// token is an account token, not an inference credential; the proxy +// exchanges it at POST /muse-code/key for the plan's minted inference +// key and calls the Meta Responses API directly (see the direct section +// below). Warm/exec remain the fallback when direct never got an +// upstream response. MUSE_PROXY_DIRECT=0 disables direct mode. +// // Auth is the CLI's own OAuth login (~/.config/muse/auth.json). META_API_KEY // must NOT be set for the child: the CLI binary states it takes priority over // the account login, and the Model API key is a separate pay-as-you-go wallet @@ -843,6 +850,465 @@ const tryWarmChat = async ({ messages, baseModel, effort, fullName, stream, res, return true; }; + +// --------------------------------------------------------------------------- +// Direct mode (#2753): account-token exchange + Meta Responses API +// --------------------------------------------------------------------------- +// The Muse CLI's OAuth login (~/.config/muse/auth.json, +// providers.meta.access_token, a `dca:...` account token) is NOT an +// inference credential: /v1 calls with it return 401. The CLI exchanges it +// at POST {META_API_BASE}/muse-code/key (x-api-version: 1.0.0, body +// {"onboard": false}) for a MintedKey whose api_key field is the plan's +// inference key (`LLM|...` form), and that key is what inference presents. +// This section mirrors the exchange (the key value is never logged). +// +// Attestation is per-route, verified live 2026-10-30: with the minted key, +// /v1/chat/completions answers 403 client_attestation_denied no matter what +// headers are sent, while /v1/responses answers 200 with bare Authorization +// only. Direct mode therefore speaks the Responses API upstream and +// translates chat completions to/from it; /v1/responses is passed through. +// No tbh/muse-build headers are sent — they are proven unnecessary. +// +// Fallback discipline: ANY upstream HTTP response on the direct path +// (200/400/402/403/429/...) is returned to the client — a quota wall or an +// attestation denial must not cause a second burn through the CLI door. +// The warm/exec paths take over only when direct never got an upstream +// response: no credential, an exchange transport failure, or an upstream +// fetch that throws. One exception: is_subs_active === false or +// require_payment === true from the exchange is a hard 502 naming the +// subscription state, never a silent CLI fallback. + +const DIRECT_ENABLED = process.env.MUSE_PROXY_DIRECT !== '0'; +const META_API_BASE = (process.env.MUSE_PROXY_META_API_BASE || 'https://api.meta.ai').replace(/\/+$/, ''); +const MUSE_AUTH_PATH = process.env.MUSE_AUTH_PATH || path.join(os.homedir(), '.config', 'muse', 'auth.json'); +const DIRECT_KEY_TTL_MS = 10 * 60 * 1000; + +const directState = { + credentialFound: false, + cachedKey: null, + cachedAt: 0, + subsTier: null, + subsActive: null, + exchangePromise: null +}; + +const loadDirectCredential = () => { + try { + const parsed = JSON.parse(fs.readFileSync(MUSE_AUTH_PATH, 'utf-8')); + const meta = (parsed && parsed.providers && parsed.providers.meta) || {}; + const accessToken = typeof meta.access_token === 'string' && meta.access_token ? meta.access_token : null; + const apiKey = typeof meta.api_key === 'string' && meta.api_key ? meta.api_key : null; + directState.credentialFound = Boolean(accessToken || apiKey); + return directState.credentialFound ? { accessToken, apiKey } : null; + } catch { + directState.credentialFound = false; + return null; + } +}; + +// One exchange against /muse-code/key. Throws only on transport failure; +// every HTTP outcome is reported as a result object. +const exchangeMintedKey = async (accessToken) => { + const response = await fetch(`${META_API_BASE}/muse-code/key`, { + method: 'POST', + headers: { + Authorization: `Bearer ${accessToken}`, + 'x-api-version': '1.0.0', + 'Content-Type': 'application/json', + Accept: 'application/json' + }, + body: JSON.stringify({ onboard: false }) + }); + let body = null; + try { body = await response.json(); } catch { body = null; } + if (!response.ok) { + return { ok: false, message: `Direct Meta route unavailable: key exchange failed with HTTP ${response.status}` }; + } + if (body && body.is_subs_active === false) { + return { ok: false, message: 'Direct Meta route unavailable: Muse Code subscription is not active (is_subs_active=false)' }; + } + if (body && body.require_payment === true) { + return { ok: false, message: 'Direct Meta route unavailable: Muse Code subscription requires payment (require_payment=true)' }; + } + if (!body || typeof body.api_key !== 'string' || !body.api_key) { + return { ok: false, message: 'Direct Meta route unavailable: key exchange returned no api_key' }; + } + directState.cachedKey = body.api_key; + directState.cachedAt = Date.now(); + if (typeof body.subs_tier_name === 'string') directState.subsTier = body.subs_tier_name; + if (typeof body.is_subs_active === 'boolean') directState.subsActive = body.is_subs_active; + return { ok: true, key: body.api_key }; +}; + +// Resolve the inference key to present. Result statuses: 'disabled' and +// 'none' (no credential) and 'transport' (exchange fetch threw) all mean +// the caller may fall back; 'hard' means Meta answered and the caller must +// surface the error instead. When the auth store holds only a stored +// api_key (no account token), that key is used without exchanging. +const getDirectKey = async ({ forceExchange = false } = {}) => { + if (!DIRECT_ENABLED) return { status: 'disabled' }; + const cred = loadDirectCredential(); + if (!cred) return { status: 'none' }; + if (!cred.accessToken) { + directState.cachedKey = cred.apiKey; + directState.cachedAt = Date.now(); + return { status: 'ok', key: cred.apiKey, stored: true }; + } + if (!forceExchange && directState.cachedKey && + Date.now() - directState.cachedAt < DIRECT_KEY_TTL_MS) { + return { status: 'ok', key: directState.cachedKey }; + } + if (!directState.exchangePromise) { + directState.exchangePromise = exchangeMintedKey(cred.accessToken) + .then(result => (result.ok + ? { status: 'ok', key: result.key } + : { status: 'hard', message: result.message })) + .catch(err => ({ status: 'transport', message: err.message })) + .finally(() => { directState.exchangePromise = null; }); + } + return directState.exchangePromise; +}; + +// POST /v1/responses upstream with the resolved key. On 401: invalidate the +// cached key, re-exchange once, retry once (the second response is final). +// Throws only when a fetch itself throws (no upstream response received). +const directResponsesFetch = async (keyResult, requestBodyText, accept) => { + const doFetch = (key) => fetch(`${META_API_BASE}/v1/responses`, { + method: 'POST', + headers: { + Authorization: `Bearer ${key}`, + 'Content-Type': 'application/json', + Accept: accept + }, + body: requestBodyText + }); + let response = await doFetch(keyResult.key); + if (response.status === 401 && !keyResult.stored) { + directState.cachedKey = null; + directState.cachedAt = 0; + const fresh = await getDirectKey({ forceExchange: true }); + if (fresh.status === 'ok') { + response = await doFetch(fresh.key); + } else if (fresh.status === 'hard') { + return { hard: fresh }; + } + // Any other re-exchange outcome leaves the original 401 as the answer: + // Meta already responded, so the 401 passes through rather than falling + // back to a second burn through the CLI door. + } + return { response }; +}; + +const writeJsonBody = (res, status, obj) => { + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(obj, null, 2)); +}; + +// --- chat <-> responses translation ----------------------------------------- + +const mapResponsesEffort = (effort) => { + switch ((effort || '').toLowerCase()) { + case 'none': return null; // none means: send no reasoning block at all + case 'minimal': + case 'low': + case 'medium': + case 'high': + case 'xhigh': return (effort || '').toLowerCase(); + // The Responses API tops out at xhigh; the CLI's max/ultra efforts have + // no direct equivalent, so they clamp to the strongest available. + case 'max': + case 'ultra': return 'xhigh'; + default: return null; + } +}; + +const contentPartsForInput = (content) => { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content.map(part => (part && typeof part.text === 'string') + ? { type: 'input_text', text: part.text } + : part); + } + return content ? JSON.stringify(content) : ''; +}; + +const buildResponsesRequest = (body, baseModel, effort) => { + const messages = Array.isArray(body.messages) ? body.messages : []; + const instructions = messages + .filter(m => m.role === 'system') + .map(messageText) + .filter(Boolean) + .join('\n\n'); + const input = []; + for (const m of messages) { + if (m.role === 'system') continue; + if (m.role === 'user') { + input.push({ role: 'user', content: contentPartsForInput(m.content) }); + } else if (m.role === 'assistant') { + const text = messageText(m); + if (text) input.push({ role: 'assistant', content: text }); + for (const tc of m.tool_calls || []) { + input.push({ + type: 'function_call', + call_id: tc.id, + name: tc.function ? tc.function.name : undefined, + arguments: (tc.function && tc.function.arguments) || '' + }); + } + } else if (m.role === 'tool' || m.role === 'function') { + input.push({ + type: 'function_call_output', + call_id: m.tool_call_id || m.name, + output: messageText(m) + }); + } else { + input.push({ role: m.role, content: contentPartsForInput(m.content) }); + } + } + const out = { model: baseModel, input, store: false, stream: Boolean(body.stream) }; + if (instructions) out.instructions = instructions; + if (Array.isArray(body.tools) && body.tools.length > 0) { + out.tools = body.tools.map(t => (t && t.type === 'function' && t.function) + ? { type: 'function', name: t.function.name, description: t.function.description, parameters: t.function.parameters } + : t); + } + if (body.tool_choice !== undefined) { + const tc = body.tool_choice; + if (typeof tc === 'string') out.tool_choice = tc; + else if (tc && tc.type === 'function' && tc.function && tc.function.name) out.tool_choice = { type: 'function', name: tc.function.name }; + else out.tool_choice = tc; + } + const maxOut = body.max_completion_tokens !== undefined && body.max_completion_tokens !== null + ? body.max_completion_tokens + : body.max_tokens; + if (typeof maxOut === 'number') out.max_output_tokens = maxOut; + if (typeof body.temperature === 'number') out.temperature = body.temperature; + if (typeof body.top_p === 'number') out.top_p = body.top_p; + const mappedEffort = mapResponsesEffort(effort); + if (mappedEffort) out.reasoning = { effort: mappedEffort }; + return out; +}; + +const extractResponsesOutput = (respBody) => { + let content = ''; + const toolCalls = []; + for (const item of (respBody && respBody.output) || []) { + if (!item || typeof item !== 'object') continue; + if (item.type === 'message') { + for (const part of item.content || []) { + if (part && part.type === 'output_text' && typeof part.text === 'string') content += part.text; + } + } else if (item.type === 'function_call') { + toolCalls.push({ + id: item.call_id || item.id, + type: 'function', + function: { name: item.name, arguments: item.arguments || '' } + }); + } + } + return { content, toolCalls }; +}; + +const finishReasonFromResponses = (respBody, hasToolCalls) => { + if (hasToolCalls) return 'tool_calls'; + if (respBody && respBody.status === 'incomplete' && + respBody.incomplete_details && respBody.incomplete_details.reason === 'max_output_tokens') { + return 'length'; + } + return 'stop'; +}; + +const chatUsageFromResponses = (usage) => { + const promptTokens = usage && typeof usage.input_tokens === 'number' ? usage.input_tokens : 0; + const completionTokens = usage && typeof usage.output_tokens === 'number' ? usage.output_tokens : 0; + const totalTokens = usage && typeof usage.total_tokens === 'number' + ? usage.total_tokens + : promptTokens + completionTokens; + const cached = usage && usage.input_tokens_details && + typeof usage.input_tokens_details.cached_tokens === 'number' + ? usage.input_tokens_details.cached_tokens + : 0; + return { + prompt_tokens: promptTokens, + completion_tokens: completionTokens, + total_tokens: totalTokens, + ...(cached > 0 ? { prompt_tokens_details: { cached_tokens: cached } } : {}) + }; +}; + +const responsesToChatCompletion = (respBody, { chatId, created, fullName }) => { + const { content, toolCalls } = extractResponsesOutput(respBody); + const message = { role: 'assistant', content }; + if (toolCalls.length > 0) message.tool_calls = toolCalls; + return { + id: chatId, + object: 'chat.completion', + created, + model: fullName, + choices: [{ + index: 0, + message, + finish_reason: finishReasonFromResponses(respBody, toolCalls.length > 0) + }], + usage: chatUsageFromResponses(respBody && respBody.usage) + }; +}; + +// Translate an upstream Responses SSE stream into chat-completion chunks. +const streamResponsesAsChat = async (response, { res, chatId, created, fullName }) => { + const sendChunk = (delta, finishReason = null, usage) => { + if (res.writableEnded) return; + const chunk = { + id: chatId, + object: 'chat.completion.chunk', + created, + model: fullName, + choices: [{ index: 0, delta, finish_reason: finishReason }], + ...(usage ? { usage } : {}) + }; + res.write(`data: ${JSON.stringify(chunk)}\n\n`); + }; + const sendErrorAndEnd = (message) => { + if (!res.writableEnded) { + // SSE-framed error + [DONE], the #670 pattern: the 200 + event-stream + // headers are already on the wire, so a bare JSON body would be + // invisible to an SSE client. + res.write(`data: ${JSON.stringify({ error: { message } })}\n\n`); + res.write('data: [DONE]\n\n'); + } + res.end(); + }; + const toolIndexByItem = new Map(); + let nextToolIndex = 0; + let ended = false; + const handleEvent = (evt) => { + if (ended || !evt || typeof evt !== 'object') return; + const type = evt.type || ''; + if (type === 'response.output_text.delta' && typeof evt.delta === 'string') { + sendChunk({ content: evt.delta }); + } else if (type === 'response.output_item.added' && evt.item && evt.item.type === 'function_call') { + const index = nextToolIndex; + nextToolIndex += 1; + const itemKey = evt.item.id || evt.item.call_id; + if (itemKey) toolIndexByItem.set(itemKey, index); + sendChunk({ + tool_calls: [{ + index, + id: evt.item.call_id || evt.item.id, + type: 'function', + function: { name: evt.item.name || '', arguments: '' } + }] + }); + } else if (type === 'response.function_call_arguments.delta') { + const index = toolIndexByItem.get(evt.item_id) ?? toolIndexByItem.get(evt.call_id) ?? 0; + sendChunk({ + tool_calls: [{ + index, + function: { arguments: typeof evt.delta === 'string' ? evt.delta : '' } + }] + }); + } else if (type === 'response.completed') { + const respBody = evt.response || {}; + const { toolCalls } = extractResponsesOutput(respBody); + sendChunk({}, finishReasonFromResponses(respBody, toolCalls.length > 0), chatUsageFromResponses(respBody.usage)); + if (!res.writableEnded) res.write('data: [DONE]\n\n'); + res.end(); + ended = true; + } else if (type === 'response.failed') { + sendErrorAndEnd((evt.response && evt.response.error && evt.response.error.message) || 'Meta Responses request failed'); + ended = true; + } else if (type === 'error') { + sendErrorAndEnd(evt.message || (evt.error && evt.error.message) || 'Meta Responses stream error'); + ended = true; + } + }; + try { + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let idx; + while ((idx = buffer.indexOf('\n\n')) >= 0) { + const rawEvent = buffer.slice(0, idx); + buffer = buffer.slice(idx + 2); + for (const line of rawEvent.split('\n')) { + const trimmed = line.trim(); + if (!trimmed.startsWith('data:')) continue; + const data = trimmed.slice('data:'.length).trim(); + if (!data || data === '[DONE]') continue; + try { handleEvent(JSON.parse(data)); } catch { /* non-JSON data line */ } + } + if (ended) return; + } + } + } catch (err) { + sendErrorAndEnd(`Direct Meta stream failed: ${err.message}`); + return; + } + if (!ended && !res.writableEnded) { + res.write('data: [DONE]\n\n'); + res.end(); + } +}; + +// Attempt one chat completion on the direct path. Returns true when the +// response has been fully handled (including any upstream error response, +// passed through as-is); false when nothing was written and the caller +// should fall back to warm/exec. +const tryDirectChat = async ({ body, baseModel, effort, fullName, stream, res, chatId, created }) => { + const keyResult = await getDirectKey(); + if (keyResult.status === 'disabled' || keyResult.status === 'none' || keyResult.status === 'transport') { + return false; + } + if (keyResult.status === 'hard') { + writeJsonBody(res, 502, { error: { message: keyResult.message } }); + return true; + } + const upstreamBody = JSON.stringify(buildResponsesRequest(body, baseModel, effort)); + let outcome; + try { + outcome = await directResponsesFetch(keyResult, upstreamBody, stream ? 'text/event-stream' : 'application/json'); + } catch { + return false; // upstream fetch threw: no upstream response, fall back + } + if (outcome.hard) { + writeJsonBody(res, 502, { error: { message: outcome.hard.message } }); + return true; + } + const response = outcome.response; + if (!response.ok) { + // Meta answered: pass the response through as-is, whatever the status. + const text = await response.text().catch(() => ''); + res.writeHead(response.status, { + 'Content-Type': response.headers.get('content-type') || 'application/json' + }); + res.end(text); + return true; + } + if (!stream) { + let respBody; + try { + respBody = await response.json(); + } catch { + writeJsonBody(res, 502, { error: { message: 'Direct Meta route returned an unreadable response body' } }); + return true; + } + writeJsonBody(res, 200, responsesToChatCompletion(respBody, { chatId, created, fullName })); + return true; + } + res.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + 'Connection': 'keep-alive', + 'X-Accel-Buffering': 'no' + }); + await streamResponsesAsChat(response, { res, chatId, created, fullName }); + return true; +}; + const server = http.createServer((req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); @@ -872,6 +1338,13 @@ const server = http.createServer((req, res) => { hostUp: Boolean(warmHost.child), sessions: warmStore.map.size }, + direct: { + enabled: DIRECT_ENABLED, + credentialFound: Boolean(loadDirectCredential()), + mintedKeyCached: Boolean(directState.cachedKey && Date.now() - directState.cachedAt < DIRECT_KEY_TTL_MS), + subsTier: directState.subsTier, + subsActive: directState.subsActive + }, cliFlags: { serveProbed: cliCaps.serve !== null, execProbed: cliCaps.exec !== null, @@ -908,6 +1381,67 @@ const server = http.createServer((req, res) => { return; } + + // 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). + if (req.method === 'POST' && (pathname === '/v1/responses' || pathname === '/responses')) { + let bodyText = ''; + req.on('data', chunk => { + bodyText += chunk; + if (bodyText.length > 50 * 1024 * 1024) { + res.writeHead(413, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); + req.destroy(); + } + }); + req.on('end', async () => { + const keyResult = await getDirectKey(); + if (keyResult.status === 'disabled' || keyResult.status === 'none') { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); + return; + } + if (keyResult.status === 'hard' || keyResult.status === 'transport') { + writeJsonBody(res, 502, { + error: { message: keyResult.message || 'Direct Meta route unavailable: key exchange failed' } + }); + return; + } + let outcome; + try { + outcome = await directResponsesFetch(keyResult, bodyText, req.headers.accept || 'application/json'); + } catch (err) { + writeJsonBody(res, 502, { error: { message: `Direct Meta route request failed: ${err.message}` } }); + return; + } + if (outcome.hard) { + writeJsonBody(res, 502, { error: { message: outcome.hard.message } }); + 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') { + 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; + } + // Chat completions if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { let bodyText = ''; @@ -944,6 +1478,24 @@ const server = http.createServer((req, res) => { const chatId = `chatcmpl-muse-${crypto.randomUUID()}`; const created = Math.floor(Date.now() / 1000); + // Direct mode first (#2753): the minted-key Responses path + // answers when it can; any upstream response is final. Only a + // no-response outcome returns false and the warm/exec paths + // below take over unchanged. + if (DIRECT_ENABLED) { + let directHandled = false; + try { + directHandled = await tryDirectChat({ + body, baseModel, effort, fullName, stream, res, chatId, created + }); + } catch (err) { + console.warn(`[muse-proxy direct] unexpected direct error (${err.message}); falling back to warm/exec`); + directHandled = false; + } + if (directHandled) return; + if (res.writableEnded) return; + } + // Warm path first (#480): a persistent serve host + MSP session // answers when it can; any failure before the response is committed // returns false and the exec path below takes over unchanged. diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs index ded50732ca..f4e240499a 100644 --- a/bin/muse-proxy.test.mjs +++ b/bin/muse-proxy.test.mjs @@ -13,6 +13,7 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; +import http from 'node:http'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; @@ -138,6 +139,12 @@ const startProxy = async (extraEnv = {}) => { fs.mkdirSync(stubDir); fs.mkdirSync(path.join(tmp, 'home')); fs.writeFileSync(path.join(stubDir, 'muse'), STUB, { mode: 0o755 }); + // The proxy prefers $HOME/.local/bin/muse over PATH, and on NixOS hosts + // /run/current-system/sw/bin/muse exists and would shadow the stub with + // the real CLI. Plant the stub at the preferred path too so the harness + // is hermetic on those hosts. + fs.mkdirSync(path.join(tmp, 'home', '.local', 'bin'), { recursive: true }); + fs.writeFileSync(path.join(tmp, 'home', '.local', 'bin', 'muse'), STUB, { mode: 0o755 }); const port = await freePort(); const logFile = path.join(tmp, 'stub.log'); const child = spawn(process.execPath, [path.join(binDir, 'muse-proxy.mjs')], { @@ -165,7 +172,7 @@ const startProxy = async (extraEnv = {}) => { if (Date.now() > deadline) throw new Error(`proxy did not start:\n${log}`); await new Promise(r => setTimeout(r, 50)); } - return { port, stop: () => child.kill('SIGKILL'), logFile }; + return { port, stop: () => child.kill('SIGKILL'), logFile, home: path.join(tmp, 'home') }; }; const chat = async (port, body) => { @@ -448,3 +455,304 @@ test('flag probe: 1.4.13-shaped help — warm serve spawn passes --disable-reque assert.equal(serveArgv.length, 1); assert.ok(serveArgv[0].includes('--disable-request-user-input'), 'advertised flag must be passed'); }); + +// --- Direct mode (#2753) ---------------------------------------------------- +// The proxy exchanges the Muse CLI account token (`dca:...` in the temp +// HOME's .config/muse/auth.json) at a stub Meta API's /muse-code/key for a +// minted key, then speaks the Responses API upstream. The stub records +// every request so the tests can assert the exchange shape, the minted-key +// Authorization, the translation, and that Meta answering (even with 429) +// never falls back to a `muse exec` burn. + +const RESPONSES_FIXTURE = { + id: 'resp_stub', + object: 'response', + status: 'completed', + model: 'muse-spark-1.3', + output: [ + { type: 'message', id: 'msg_1', role: 'assistant', content: [{ type: 'output_text', text: 'Hello direct' }] }, + { type: 'function_call', id: 'fc_1', call_id: 'call_123', name: 'get_weather', arguments: '{"city":"Osseo"}', status: 'completed' } + ], + usage: { input_tokens: 13, output_tokens: 9, total_tokens: 22, input_tokens_details: { cached_tokens: 4 } } +}; + +const RESPONSES_SSE_FIXTURE = [ + ['response.output_text.delta', { type: 'response.output_text.delta', delta: 'Hello ' }], + ['response.output_text.delta', { type: 'response.output_text.delta', delta: 'stream' }], + ['response.output_item.added', { type: 'response.output_item.added', item: { type: 'function_call', id: 'fc_1', call_id: 'call_9', name: 'get_weather', arguments: '' } }], + ['response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', item_id: 'fc_1', delta: '{"city":' }], + ['response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', item_id: 'fc_1', delta: '"Osseo"}' }], + ['response.completed', { + type: 'response.completed', + response: { + id: 'resp_stream', + status: 'completed', + output: [ + { type: 'message', content: [{ type: 'output_text', text: 'Hello stream' }] }, + { type: 'function_call', call_id: 'call_9', name: 'get_weather', arguments: '{"city":"Osseo"}' } + ], + usage: { input_tokens: 11, output_tokens: 6, total_tokens: 17 } + } + }] +].map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`).join(''); + +const startMetaStub = async (mode) => { + const requests = []; + const server = http.createServer((req, res) => { + let body = ''; + req.on('data', c => { body += c; }); + req.on('end', () => { + requests.push({ method: req.method, url: req.url, headers: req.headers, body }); + if (req.url === '/muse-code/key') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + api_key: 'LLM|stub-minted', + is_subs_active: true, + require_payment: false, + subs_tier_name: 'Muse Code High Usage' + })); + return; + } + if (req.url === '/v1/responses') { + if (mode === '429') { + res.writeHead(429, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { message: 'Subscription quota exhausted', type: 'rate_limit_error' } })); + return; + } + if (mode === 'echo') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ received: JSON.parse(body || '{}'), authorization: req.headers.authorization })); + return; + } + let parsed = {}; + try { parsed = JSON.parse(body || '{}'); } catch { /* keep empty */ } + if (parsed.stream) { + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.end(RESPONSES_SSE_FIXTURE); + return; + } + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(RESPONSES_FIXTURE)); + return; + } + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { message: 'stub: unknown route' } })); + }); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address(); + return { url: `http://127.0.0.1:${port}`, requests, close: () => server.close() }; +}; + +const writeStubAuth = (home) => { + const dir = path.join(home, '.config', 'muse'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'auth.json'), JSON.stringify({ + schema_version: 1, + providers: { + meta: { + access_token: 'dca:stub-account-token', + mechanism: 'oauth', + obtained_via: 'device_code' + } + } + })); +}; + +const parseChatSse = (sse) => { + const chunks = []; + let done = false; + for (const line of sse.split('\n')) { + if (line === 'data: [DONE]') { done = true; continue; } + if (line.startsWith('data: ')) chunks.push(JSON.parse(line.slice('data: '.length))); + } + return { chunks, done }; +}; + +test('direct mode: one exchange mints the key, chat is translated to Responses and back (#2753)', async (t) => { + const meta = await startMetaStub('chat'); + t.after(() => meta.close()); + const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); + t.after(stop); + writeStubAuth(home); + + const body = { + model: 'muse-spark-1.3', + reasoning_effort: 'max', + max_tokens: 64, + messages: [ + { role: 'system', content: 'Be terse.' }, + { role: 'user', content: 'weather in Osseo?' }, + { role: 'assistant', content: '', tool_calls: [{ id: 'call_0', type: 'function', function: { name: 'get_weather', arguments: '{"city":"Osseo"}' } }] }, + { role: 'tool', tool_call_id: 'call_0', content: 'sunny' }, + { role: 'user', content: 'thanks, and tomorrow?' } + ], + tools: [{ type: 'function', function: { name: 'get_weather', description: 'Get weather', parameters: { type: 'object', properties: { city: { type: 'string' } } } } }], + tool_choice: { type: 'function', function: { name: 'get_weather' } } + }; + const plain = JSON.parse(await chat(port, body)); + assert.equal(plain.model, 'muse-spark-1.3-max', 'model is the fullName the exec/warm handlers compute'); + assert.equal(plain.choices[0].message.content, 'Hello direct'); + assert.deepEqual(plain.choices[0].message.tool_calls, [{ + id: 'call_123', + type: 'function', + function: { name: 'get_weather', arguments: '{"city":"Osseo"}' } + }]); + assert.equal(plain.choices[0].finish_reason, 'tool_calls'); + assert.equal(plain.usage.prompt_tokens, 13); + assert.equal(plain.usage.completion_tokens, 9); + assert.equal(plain.usage.total_tokens, 22); + assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 4); + + // A second call must reuse the cached minted key: still one exchange. + const again = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi again' }] })); + assert.equal(again.choices[0].message.content, 'Hello direct'); + + const exchanges = meta.requests.filter(r => r.url === '/muse-code/key'); + assert.equal(exchanges.length, 1, 'two chat calls must share one cached exchange'); + assert.equal(exchanges[0].method, 'POST'); + assert.equal(exchanges[0].headers.authorization, 'Bearer dca:stub-account-token'); + assert.equal(exchanges[0].headers['x-api-version'], '1.0.0'); + assert.deepEqual(JSON.parse(exchanges[0].body), { onboard: false }); + + const upstream = meta.requests.filter(r => r.url === '/v1/responses'); + assert.equal(upstream.length, 2); + for (const r of upstream) { + assert.equal(r.headers.authorization, 'Bearer LLM|stub-minted', 'upstream sees the minted key, never the account token'); + } + const sent = JSON.parse(upstream[0].body); + assert.equal(sent.model, 'muse-spark-1.3'); + assert.equal(sent.instructions, 'Be terse.'); + assert.equal(sent.store, false); + assert.deepEqual(sent.reasoning, { effort: 'xhigh' }, 'max clamps to the Responses ceiling xhigh'); + assert.equal(sent.max_output_tokens, 64); + const fnCall = sent.input.find(i => i.type === 'function_call'); + assert.equal(fnCall.call_id, 'call_0'); + assert.equal(fnCall.name, 'get_weather'); + const fnOut = sent.input.find(i => i.type === 'function_call_output'); + assert.equal(fnOut.call_id, 'call_0'); + assert.equal(fnOut.output, 'sunny'); + assert.deepEqual(sent.tools, [{ + type: 'function', + name: 'get_weather', + description: 'Get weather', + parameters: { type: 'object', properties: { city: { type: 'string' } } } + }]); + assert.deepEqual(sent.tool_choice, { type: 'function', name: 'get_weather' }); + + const healthRes = await fetch(`http://127.0.0.1:${port}/health`); + const health = await healthRes.json(); + assert.equal(health.direct.enabled, true); + assert.equal(health.direct.credentialFound, true); + assert.equal(health.direct.mintedKeyCached, true); + assert.equal(health.direct.subsTier, 'Muse Code High Usage'); + assert.equal(health.direct.subsActive, true); +}); + +test('direct mode: Responses SSE is translated into chat chunks with tool calls (#2753)', async (t) => { + const meta = await startMetaStub('chat'); + t.after(() => meta.close()); + const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); + t.after(stop); + writeStubAuth(home); + + const { chunks, done } = parseChatSse(await chat(port, { + messages: [{ role: 'user', content: 'weather?' }], + stream: true + })); + assert.ok(done, 'stream terminates with [DONE]'); + const content = chunks.map(c => c.choices[0].delta.content || '').join(''); + assert.equal(content, 'Hello stream'); + const toolHeads = chunks.flatMap(c => c.choices[0].delta.tool_calls || []).filter(tc => tc.id); + assert.equal(toolHeads.length, 1); + assert.equal(toolHeads[0].id, 'call_9'); + assert.equal(toolHeads[0].function.name, 'get_weather'); + const toolArgs = chunks.flatMap(c => c.choices[0].delta.tool_calls || []) + .map(tc => (tc.function && tc.function.arguments) || '') + .join(''); + assert.equal(toolArgs, '{"city":"Osseo"}'); + const final = chunks.find(c => c.choices[0].finish_reason); + assert.equal(final.choices[0].finish_reason, 'tool_calls'); + assert.equal(final.usage.prompt_tokens, 11); + assert.equal(final.usage.completion_tokens, 6); + assert.equal(final.usage.total_tokens, 17); +}); + +test('direct mode: upstream 429 passes through and never falls back to exec (#2753)', async (t) => { + const meta = await startMetaStub('429'); + t.after(() => meta.close()); + const { port, stop, home, logFile } = 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/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ messages: [{ role: 'user', content: 'hi' }] }) + }); + assert.equal(res.status, 429, 'the upstream status is returned as-is'); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /Subscription quota exhausted/); + assert.equal(meta.requests.filter(r => r.url === '/v1/responses').length, 1, 'a quota wall is never retried'); + const stubLog = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8') : ''; + assert.ok(!stubLog.includes('--prompt-file'), 'no muse exec invocation after Meta answered'); +}); + +test('direct mode: /v1/responses passes the body through verbatim, swapping only Authorization (#2753)', 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 clientBody = { + model: 'muse-wonder-1.0', + input: [{ role: 'user', content: 'hi' }], + stream: false, + custom_field: { a: 1 } + }; + const res = await fetch(`http://127.0.0.1:${port}/v1/responses`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: 'Bearer client-token-must-be-dropped' }, + body: JSON.stringify(clientBody) + }); + assert.equal(res.status, 200); + const echoed = JSON.parse(await res.text()); + assert.deepEqual(echoed.received, clientBody, 'the upstream body is the client body verbatim'); + assert.equal(echoed.authorization, 'Bearer LLM|stub-minted'); + const upstream = meta.requests.filter(r => r.url === '/v1/responses'); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].body, JSON.stringify(clientBody), 'byte-for-byte passthrough on the wire'); +}); + +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()); + const { port, stop, home } = await startProxy({ + MUSE_PROXY_META_API_BASE: meta.url, + MUSE_PROXY_DIRECT: '0' + }); + t.after(stop); + writeStubAuth(home); + + const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); + assert.equal(plain.choices[0].message.content, 'Hello world', 'exec stub answer proves the CLI path ran'); + assert.equal(meta.requests.length, 0, 'the Meta API stub is never contacted'); +}); + +test('direct mode: missing auth.json leaves the exec path in charge (#2753)', async (t) => { + const meta = await startMetaStub('chat'); + t.after(() => meta.close()); + const { port, stop } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); + t.after(stop); + + const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); + assert.equal(plain.choices[0].message.content, 'Hello world', 'exec stub answer proves the CLI path ran'); + assert.equal(meta.requests.length, 0, 'no credential means no exchange attempt'); + + const healthRes = await fetch(`http://127.0.0.1:${port}/health`); + const health = await healthRes.json(); + assert.equal(health.direct.enabled, true); + assert.equal(health.direct.credentialFound, false); + assert.equal(health.direct.mintedKeyCached, false); +});