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
155 changes: 138 additions & 17 deletions bin/muse-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ import { parseProxyPort } from './proxy-port.mjs';
const PORT = parseProxyPort('MUSE_PROXY_PORT', 18747);
const HOST = process.env.MUSE_PROXY_HOST || '127.0.0.1';

const EGRESS_PROXY = 'http://hatch-egress-proxy:3128';
// Egress pinning is a sandbox requirement (the CLI reaches Meta only via
// the unauthenticated egress proxy + CA bundle there). Fleet machines that
// reach Meta directly set MUSE_PROXY_EGRESS to the empty string in their
// start wrapper, which disables the pinning in childEnv() entirely.
const EGRESS_PROXY = process.env.MUSE_PROXY_EGRESS ?? 'http://hatch-egress-proxy:3128';
const EGRESS_CA = '/run/hatch/egress-tls/ca-bundle.pem';

const PROXY_DIR = path.dirname(fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -147,16 +151,119 @@ const formatPrompt = (messages) => {
const childEnv = () => {
const env = { ...process.env };
delete env.META_API_KEY;
env.HTTPS_PROXY = EGRESS_PROXY;
env.HTTP_PROXY = EGRESS_PROXY;
env.https_proxy = EGRESS_PROXY;
env.http_proxy = EGRESS_PROXY;
env.SSL_CERT_FILE = EGRESS_CA;
if (EGRESS_PROXY) {
env.HTTPS_PROXY = EGRESS_PROXY;
env.HTTP_PROXY = EGRESS_PROXY;
env.https_proxy = EGRESS_PROXY;
env.http_proxy = EGRESS_PROXY;
}
if (EGRESS_PROXY && fs.existsSync(EGRESS_CA)) env.SSL_CERT_FILE = EGRESS_CA;
env.NO_PROXY = [env.NO_PROXY, '127.0.0.1', 'localhost', '::1'].filter(Boolean).join(',');
env.no_proxy = env.NO_PROXY;
return env;
};

// ---------------------------------------------------------------------------
// CLI flag capability probe
// ---------------------------------------------------------------------------
// The muse CLI's flag surface differs between releases the fleet runs side
// by side (verified 2026-10-24: 1.4.2 advertises neither serve
// --disable-request-user-input nor exec --disable-reminders; 1.4.13
// advertises both), and an unknown option kills the child before it can
// serve anything. Rather than keying off version strings, probe the
// resolved binary's own `serve --help` / `exec --help` once at startup and
// pass only the flags it advertises. If a probe fails (or its output names
// no flags at all), optional flags are omitted — they are behavioural
// niceties — while core flags are still passed: a degraded proxy beats a
// dead one.
const CLI_FLAG_PLAN = {
serve: [
{ flag: '--provider' },
{ flag: '--disable-request-user-input', optional: true }
],
exec: [
{ flag: '--json' },
{ flag: '--prompt-file' },
{ flag: '--model' },
{ flag: '--reasoning-effort' },
{ flag: '--disable-reminders', optional: true },
{ flag: '--user-input-auto-resolve' },
{ flag: '--approval-mode' }
]
};
const cliCaps = { serve: null, exec: null };
const cliDropped = { serve: [], exec: [] };
let cliCapsPromise = null;

const flagSupported = (subcommand, flag, optional) => {
const caps = cliCaps[subcommand];
if (caps) return caps.has(flag);
return !optional; // probe unavailable: keep core flags, omit optional ones
};

const probeCliFlags = (subcommand) => new Promise((resolve) => {
let out = '';
let child;
try {
child = spawn(MUSE_BIN, [subcommand, '--help'], {
env: childEnv(),
stdio: ['ignore', 'pipe', 'pipe']
});
} catch {
resolve(null);
return;
}
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'); });
child.on('error', () => { clearTimeout(timer); resolve(null); });
child.on('close', () => {
clearTimeout(timer);
const flags = new Set(out.match(/--[a-z][a-z0-9-]*/g) || []);
resolve(flags.size > 0 ? flags : null);
});
});

// Probe once, lazily; every caller awaits the same promise. Never rejects.
const ensureCliCaps = () => {
if (!cliCapsPromise) {
cliCapsPromise = (async () => {
const [serve, exec] = await Promise.all([probeCliFlags('serve'), probeCliFlags('exec')]);
cliCaps.serve = serve;
cliCaps.exec = exec;
for (const sub of ['serve', 'exec']) {
cliDropped[sub] = CLI_FLAG_PLAN[sub]
.filter(p => !flagSupported(sub, p.flag, p.optional))
.map(p => p.flag);
if (cliCaps[sub]) {
console.log(`[muse-proxy] CLI probe: ${sub} advertises ${cliCaps[sub].size} flags` +
(cliDropped[sub].length ? `; omitting unsupported: ${cliDropped[sub].join(', ')}` : '; all planned flags supported'));
} else {
console.warn(`[muse-proxy] CLI probe: ${sub} --help unusable; omitting optional flags: ${cliDropped[sub].join(', ') || '(none)'}`);
}
}
return cliCaps;
})();
}
return cliCapsPromise;
};

// Build an argv from parts: plain strings pass through untouched;
// {flag, value?, optional?} entries are included only when the resolved
// CLI advertises the flag (see the probe above).
const buildCliArgs = (subcommand, parts) => {
const args = [];
for (const part of parts) {
if (typeof part === 'string') { args.push(part); continue; }
if (!flagSupported(subcommand, part.flag, part.optional)) continue;
args.push(part.flag);
if (part.value !== undefined) args.push(String(part.value));
}
return args;
};

// ---------------------------------------------------------------------------
// Warm sessions (#480): one persistent `muse serve` (MSP over stdio) host
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -314,7 +421,12 @@ const warmHost = {
},

async _start() {
const args = ['serve', '--provider', 'meta', '--disable-request-user-input'];
await ensureCliCaps();
const args = buildCliArgs('serve', [
'serve',
{ flag: '--provider', value: 'meta' },
{ flag: '--disable-request-user-input', optional: true }
]);
console.log(`[muse-proxy warm] Spawning serve host: ${MUSE_BIN} ${args.join(' ')}`);
const child = spawn(MUSE_BIN, args, {
cwd: WORKDIR,
Expand Down Expand Up @@ -752,6 +864,11 @@ const server = http.createServer((req, res) => {
hostGen: warmHost.gen,
hostUp: Boolean(warmHost.child),
sessions: warmStore.map.size
},
cliFlags: {
serveProbed: cliCaps.serve !== null,
execProbed: cliCaps.exec !== null,
dropped: { serve: cliDropped.serve, exec: cliDropped.exec }
}
}, null, 2));
return;
Expand Down Expand Up @@ -841,17 +958,19 @@ const server = http.createServer((req, res) => {
const promptFile = path.join(WORKDIR, `prompt-${crypto.randomUUID()}.txt`);
fs.writeFileSync(promptFile, prompt, 'utf-8');

// Spawn arguments for muse exec
const args = [
// Spawn arguments for muse exec (only the flags the resolved CLI
// advertises — see the capability probe)
await ensureCliCaps();
const args = buildCliArgs('exec', [
'exec',
'--json',
'--prompt-file', promptFile,
'--model', baseModel,
'--reasoning-effort', effort,
'--disable-reminders',
'--user-input-auto-resolve',
'--approval-mode', 'never'
];
{ flag: '--json' },
{ flag: '--prompt-file', value: promptFile },
{ flag: '--model', value: baseModel },
{ flag: '--reasoning-effort', value: effort },
{ flag: '--disable-reminders', optional: true },
{ flag: '--user-input-auto-resolve' },
{ flag: '--approval-mode', value: 'never' }
]);

console.log(`[muse-proxy] Spawning: ${MUSE_BIN} ${args.join(' ')}`);

Expand Down Expand Up @@ -1135,6 +1254,8 @@ const publishEndpoint = () => {

server.listen(PORT, HOST, () => {
publishEndpoint();
// Warm the CLI capability probe so the first request does not pay for it.
ensureCliCaps().catch(() => {});
console.log(`[muse-proxy] OpenAI-compatible bridge listening on http://${HOST}:${PORT}`);
console.log(`[muse-proxy] Resolved muse binary: ${MUSE_BIN}`);
console.log(`[muse-proxy] Workdir: ${WORKDIR}`);
Expand Down
106 changes: 106 additions & 0 deletions bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Tests for muse-proxy's streaming/terminal-text reconciliation (#484)
// and its warm serve/MSP session path (#480). The exec-path tests pin
// MUSE_PROXY_WARM=0; the warm tests drive a stub `muse serve` host.
// The flag-probe tests drive the stub's canned --help surfaces
// (1.4.2-shaped by default, 1.4.13-shaped with STUB_HELP_ALL_FLAGS=1).
// Run: node --test bin/muse-proxy.test.mjs
//
// The proxy spawns one `muse exec --json` child per request. These tests
Expand All @@ -25,6 +27,31 @@ const STUB = `#!/usr/bin/env node
// the warm-path tests, logging session/turn traffic to $STUB_LOG.
const fs = require('fs');
const args = process.argv.slice(2);
if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, 'ARGV ' + args.join(' ') + '\\n');
if (args.includes('--help')) {
// Canned --help for the proxy's flag-capability probe. By default the
// stub advertises the 1.4.2-shaped surface (no serve
// --disable-request-user-input, no exec --disable-reminders);
// STUB_HELP_ALL_FLAGS=1 advertises the 1.4.13-shaped surface instead.
const all = process.env.STUB_HELP_ALL_FLAGS === '1';
if (args[0] === 'serve') {
console.log('Usage: muse serve [--provider <PROVIDER>] [--model <MODEL>] [OPTIONS]');
console.log(' --provider <PROVIDER>');
console.log(' --model <MODEL>');
console.log(' --no-session-log');
if (all) console.log(' --disable-request-user-input');
} else {
console.log('Usage: muse exec [OPTIONS] [PROMPT]');
console.log(' --json');
console.log(' --prompt-file <PATH>');
console.log(' --model <ID>');
console.log(' --reasoning-effort <EFFORT>');
if (all) console.log(' --disable-reminders');
console.log(' --user-input-auto-resolve');
console.log(' --approval-mode <MODE>');
}
process.exit(0);
}
if (args[0] === 'serve') {
if (process.env.STUB_SERVE_FAIL === '1') process.exit(3);
const log = (line) => { if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, line + '\\n'); };
Expand Down Expand Up @@ -341,3 +368,82 @@ test('warm serve failure falls back to the exec path (#480)', async (t) => {
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 fallback ran');
});

// --- CLI flag capability probe -------------------------------------------
// The fleet runs muse CLIs with different flag surfaces side by side
// (1.4.2 advertises neither serve --disable-request-user-input nor exec
// --disable-reminders; 1.4.13 advertises both). The proxy probes the
// resolved binary's --help once at startup and must pass only the flags
// it advertises — an unknown option kills the child outright.

const argvLines = (logFile, sub) => fs.readFileSync(logFile, 'utf-8')
.split('\n')
.filter(l => l.startsWith(`ARGV ${sub} `) && !l.includes('--help'));

const waitForProbe = async (port) => {
const deadline = Date.now() + 5000;
for (;;) {
const res = await fetch(`http://127.0.0.1:${port}/health`);
const health = await res.json();
if (health.cliFlags && health.cliFlags.serveProbed && health.cliFlags.execProbed) return health;
if (Date.now() > deadline) throw new Error('CLI flag probe did not complete');
await new Promise(r => setTimeout(r, 25));
}
};

test('flag probe: 1.4.2-shaped help — exec omits --disable-reminders, health reports the drops', async (t) => {
const { port, stop, logFile } = await startProxy();
t.after(stop);
const health = await waitForProbe(port);
assert.deepEqual(health.cliFlags.dropped.exec, ['--disable-reminders']);
assert.deepEqual(health.cliFlags.dropped.serve, ['--disable-request-user-input']);

const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] }));
assert.equal(plain.choices[0].message.content, 'Hello world');
const execArgv = argvLines(logFile, 'exec');
assert.equal(execArgv.length, 1);
assert.ok(execArgv[0].includes('--json'), 'core flags are still passed');
assert.ok(execArgv[0].includes('--approval-mode never'), 'core flags are still passed');
assert.ok(!execArgv[0].includes('--disable-reminders'), 'unadvertised flag must be omitted');
});

test('flag probe: 1.4.13-shaped help — exec passes --disable-reminders', async (t) => {
const { port, stop, logFile } = await startProxy({ STUB_HELP_ALL_FLAGS: '1' });
t.after(stop);
const health = await waitForProbe(port);
assert.deepEqual(health.cliFlags.dropped.exec, []);
assert.deepEqual(health.cliFlags.dropped.serve, []);

const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] }));
assert.equal(plain.choices[0].message.content, 'Hello world');
const execArgv = argvLines(logFile, 'exec');
assert.equal(execArgv.length, 1);
assert.ok(execArgv[0].includes('--disable-reminders'), 'advertised flag must be passed');
});

test('flag probe: 1.4.2-shaped help — warm serve spawn omits --disable-request-user-input', async (t) => {
const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' });
t.after(stop);
const plain = JSON.parse(await chat(port, {
model: 'muse-spark-1.3',
messages: [{ role: 'user', content: 'alpha one' }]
}));
assert.equal(plain.choices[0].message.content, 'RE:alpha one', 'warm path still answers');
const serveArgv = argvLines(logFile, 'serve');
assert.equal(serveArgv.length, 1);
assert.ok(serveArgv[0].includes('--provider meta'), 'core flags are still passed');
assert.ok(!serveArgv[0].includes('--disable-request-user-input'), 'unadvertised flag must be omitted');
});

test('flag probe: 1.4.13-shaped help — warm serve spawn passes --disable-request-user-input', async (t) => {
const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1', STUB_HELP_ALL_FLAGS: '1' });
t.after(stop);
const plain = JSON.parse(await chat(port, {
model: 'muse-spark-1.3',
messages: [{ role: 'user', content: 'alpha one' }]
}));
assert.equal(plain.choices[0].message.content, 'RE:alpha one');
const serveArgv = argvLines(logFile, 'serve');
assert.equal(serveArgv.length, 1);
assert.ok(serveArgv[0].includes('--disable-request-user-input'), 'advertised flag must be passed');
});
Loading