From 94dcd63fef2c9ecb279d9a54c9eccbc4d63db796 Mon Sep 17 00:00:00 2001 From: Archer Date: Fri, 6 Nov 2026 12:48:57 -0600 Subject: [PATCH] muse-direct goes native: retire muse-proxy, pin fork f4514086 (opencode#1825) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drew (2026-11-06): "what part of muse proxy sounds direct." - .opencode/opencode.jsonc: muse-direct now resolves to the fork's native provider (@opencode/ai/providers/muse-direct, fork PR #1872) speaking the Meta Responses wire in-process; the proxy baseURL template and placeholder apiKey are gone. Provider id, model ids and all six effort variants per model are unchanged; the provider normalizes the v1 reasoning_effort dialect onto the wire, so the seats keep their effort. - muse-proxy decommissioned in the #6494 pattern: bin/muse-proxy.mjs, bin/muse-proxy-start.sh and bin/muse-proxy.test.mjs deleted; the home-manager let (museProxyPort), user unit and MUSE_PROXY_PORT session variable removed from home/common/default.nix; guard row removed (.github/scripts/check-proxy-port-fallbacks.sh — its last row; the guard stays wired and passes vacuously) and the proxy-port test inventory emptied with the retirement narrated. - Residue swept: pm-stack/PORTS.md row retired, OpenClaw TOOLS.md row removed, QUOTAS.md + openclaw prompt/let comments corrected. - flake.lock: opencode pin 5e9b135f -> f4514086e5 (fork main with the native muse-direct provider merged). --- .github/scripts/check-proxy-port-fallbacks.sh | 8 +- .github/workflows/bin-tests.yml | 4 +- .opencode/opencode.jsonc | 40 +- bin/muse-proxy-start.sh | 12 - bin/muse-proxy.mjs | 2140 ----------------- bin/muse-proxy.test.mjs | 1348 ----------- bin/openchamber-start.sh | 2 +- bin/proxy-port.test.mjs | 10 +- flake.lock | 6 +- home/common/default.nix | 76 +- home/openclaw/default.nix | 10 +- home/openclaw/workspace/QUOTAS.md | 2 +- home/openclaw/workspace/TOOLS.md | 1 - pm-stack/PORTS.md | 2 +- 14 files changed, 66 insertions(+), 3595 deletions(-) delete mode 100755 bin/muse-proxy-start.sh delete mode 100644 bin/muse-proxy.mjs delete mode 100644 bin/muse-proxy.test.mjs diff --git a/.github/scripts/check-proxy-port-fallbacks.sh b/.github/scripts/check-proxy-port-fallbacks.sh index f76348da9b..99d2026564 100755 --- a/.github/scripts/check-proxy-port-fallbacks.sh +++ b/.github/scripts/check-proxy-port-fallbacks.sh @@ -66,6 +66,13 @@ # to the fork's native wire-emulation providers on 2026-11-05 # (code#6117, opencode#1749); this guard had been failing on their # stale rows since that repoint removed the jsonc baseURLs. +# +# Retired 2026-11-06 (Drew, muse-direct order): the muse door +# (:18747), this guard's last row, is gone the same way — the +# provider went native in the fork (@opencode/ai/providers/ +# muse-direct, opencode#1825). The row list is empty and the guard +# passes vacuously; it stays wired so a future proxy door re-adds +# its row here on purpose. set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -74,7 +81,6 @@ config_file="$repo_root/.opencode/opencode.jsonc" # var | let binding | proxy script | has an opencode.jsonc baseURL proxies=( - "MUSE_PROXY_PORT|museProxyPort|bin/muse-proxy.mjs|yes" ) failed=0 diff --git a/.github/workflows/bin-tests.yml b/.github/workflows/bin-tests.yml index 2fe0f43167..e2a8a40e20 100644 --- a/.github/workflows/bin-tests.yml +++ b/.github/workflows/bin-tests.yml @@ -5,8 +5,8 @@ name: bin tests # Test verification for the bin/ provider proxies (#6081). # # 12 of the 13 bin/*.test.mjs suites — the regression tests for the -# live provider proxies in bin/ (muse-proxy, -# proxy-supervise, ...) — were run by +# live provider proxies in bin/ (proxy-supervise, +# proxy-relay, ...) — were run by # no workflow; only bin/check-opencode-metered-providers.test.mjs # had wiring (opencode-config-guard). The rest executed only when a # human remembered to run node --test by hand, so pins regressed diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index c6ad7bb322..2e0877f023 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -830,30 +830,24 @@ // and deleted (disabled-only at the end; the routes seat muse-direct // leaves — the block below — not muse/*). -// muse-direct (2026-10-30, #2753): the Responses-native door into the -// SAME single Meta pool (the Muse API High Usage plan) — not a -// separate pool, and not the assistant Muse's subscription. It fronts -// muse-proxy's DIRECT mode: the proxy exchanges the Muse CLI's OAuth -// account token at /muse-code/key for the plan's minted key and speaks -// the Responses API, the route that answers that key with bare -// Authorization (the chat-completions route is the one returning -// client_attestation_denied to non-CLI clients). This provider uses -// @ai-sdk/openai so OpenCode speaks Responses to the proxy's -// /v1/responses passthrough, which swaps in the minted key; the "muse" -// provider above (chat route into the same proxy) is untouched. The -// apiKey below is the local placeholder the proxy ignores — the real -// key never leaves the proxy and no auth.json entry is needed. A call -// costs ~10 input tokens through this door vs ~26k through the CLI -// harness. The provider's models are the contributor variants — the -// ids the routes seat — with the effort variants the "meta" block -// defines for its contributor models. +// muse-direct (2026-11-06, Drew: "what part of muse proxy sounds +// direct"): the provider is NATIVE now. @opencode/ai/providers/ +// muse-direct (fork PR #1872, opencode#1825) speaks the Meta +// Responses wire in-process — endpoint https://api.meta.ai/v1 — +// exchanging the Muse account token from ~/.config/muse/auth.json +// at /muse-code/key for the plan's minted key, exactly the exchange +// the retired proxy's direct mode performed, with no proxy hop, no +// subprocess and no placeholder key: this block carries no baseURL +// and no apiKey, and muse-proxy (:18747) is decommissioned. Same +// single Meta pool as ever (the Muse API High Usage plan — not a +// separate pool, and not the assistant Muse's subscription); the +// "meta" provider remains the separate PAYG door under its own id — +// do not merge them. The models are the contributor variants the +// routes seat; the provider normalizes the v1 reasoning_effort +// variant dialect onto the wire. "muse-direct": { - "npm": "@ai-sdk/openai", - "name": "Meta Muse Direct (proxy)", - "options": { - "baseURL": "http://127.0.0.1:{env:MUSE_PROXY_PORT:-18747}/v1", - "apiKey": "muse-local" - }, + "npm": "@opencode/ai/providers/muse-direct", + "name": "Meta Muse Direct", "models": { "muse-spark-1.3-contributor": { "name": "Muse Spark 1.3 Contributor (muse-direct)", diff --git a/bin/muse-proxy-start.sh b/bin/muse-proxy-start.sh deleted file mode 100755 index 8085569a35..0000000000 --- a/bin/muse-proxy-start.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -# Laptop start wrapper for muse-proxy (fleet pattern, mirrors the sandbox -# wrapper minus the sandbox-only egress pins). -export HOME=/home/user -export MUSE_PROXY_PORT=${MUSE_PROXY_PORT:-18747} -# Empty egress override: on the laptop the muse CLI reaches Meta directly. -export MUSE_PROXY_EGRESS= -# META_API_KEY takes priority over the CLI's OAuth account login and bills -# a separate pay-as-you-go wallet — it must be absent. -unset META_API_KEY -export PATH="$HOME/.local/bin:/run/current-system/sw/bin:/usr/local/bin:$PATH" -exec /run/current-system/sw/bin/node "$HOME/code/bin/muse-proxy.mjs" diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs deleted file mode 100644 index f865f7a9a9..0000000000 --- a/bin/muse-proxy.mjs +++ /dev/null @@ -1,2140 +0,0 @@ -#!/usr/bin/env node -// muse-proxy — OpenAI-compatible bridge to the Meta Muse Code CLI. -// -// Mirrors bin/codex-proxy.mjs in developing-today/code: one `muse exec --json` -// subprocess per chat-completions request, prompt delivered via --prompt-file, -// streamed back out of the CLI's JSONL event stream. -// -// Warm path (#480): chat completions are served by one persistent -// `muse serve` (MSP) host with durable per-conversation sessions whenever -// 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. -// -// Tools doctrine (code#6117, opencode#1708): the warm/exec paths are -// vendor-CLI doors — the conversation is flattened to a prompt and the -// Muse CLI answers with its OWN tools, returning only final text -// (finish_reason "stop"). They cannot emit client tool calls, so a -// request that carries client tools is NEVER eligible for them: it is -// served by the direct (wire-emulation) path or fails loudly with a -// 502 naming the limitation. Conforming warm/exec is not possible — -// the CLI's serve/exec surfaces expose no wire tool-call emission for -// arbitrary client tools (their end state is the facade migration, -// opencode#1155) — so direct-or-error is the floor. Text-only requests -// keep the warm/exec reliability fallback, and every chat response -// records the serving path in the X-Muse-Proxy-Path header. -// -// 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 -// (inference there returns 402 until funded). The child is therefore spawned -// with META_API_KEY explicitly deleted and with the sandbox's unauthenticated -// egress proxy + CA bundle, the only network path the CLI can reach here. -import http from 'node:http'; -import { spawn } from 'node:child_process'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { parseProxyPort } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -// Default port 18747: muse-proxy takes the next port in the family -// range after design-code's old 18746 (cf. clef 18742, agy 18743, -// codex 18744, antigravity-ls 18745, design-code 18746 — all since -// retired; design-code's bin program was removed in the 2026-11-06 -// proxy-infra decommission). -const PORT = parseProxyPort('MUSE_PROXY_PORT', 18747); -const HOST = process.env.MUSE_PROXY_HOST || '127.0.0.1'; - -// 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)); -const WORKDIR = process.env.MUSE_PROXY_WORKDIR || path.join(PROXY_DIR, 'work'); -fs.mkdirSync(WORKDIR, { recursive: true }); - -const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']; -const MODELS = [ - { id: 'muse-spark-1.3', name: 'Muse Spark 1.3 (muse)', efforts: EFFORTS, defaultEffort: 'high' }, - { id: 'muse-wonder-1.0', name: 'Muse Wonder 1.0 (muse)', efforts: EFFORTS, defaultEffort: 'high' } -]; - -const findMuseBinary = () => { - const candidates = [ - `${process.env.HOME}/.local/bin/muse`, - '/run/current-system/sw/bin/muse', - 'muse' - ]; - for (const c of candidates) { - if (c === 'muse' || fs.existsSync(c)) { - return c; - } - } - return 'muse'; -}; - -const MUSE_BIN = findMuseBinary(); - -const resolveModelAndEffort = (requestedModel, requestedEffort) => { - let rawModel = (requestedModel || 'muse-spark-1.3').trim(); - // Strip any provider prefix before '/' (e.g. 'muse/', 'meta/', 'muse-code/') - let modelStr = rawModel.replace(/^.*\//, '').toLowerCase().trim(); - let effort = requestedEffort ? requestedEffort.toLowerCase().trim() : null; - - // Check if model string ends with effort suffix (longest first) - const possibleSuffixes = ['-minimal', '-medium', '-xhigh', '-ultra', '-high', '-none', '-low', '-max']; - for (const suffix of possibleSuffixes) { - if (modelStr.endsWith(suffix)) { - effort = suffix.slice(1); - modelStr = modelStr.slice(0, -suffix.length); - break; - } - } - - // Contributor variants (#2753 amendment): the Meta pool's contributor - // models are distinct upstream ids (muse-spark-1.3-contributor, - // muse-wonder-1.0-contributor), optionally carrying an effort suffix - // AFTER the contributor part (muse-wonder-1.0-contributor-high — the - // effort suffix was already stripped above). Peel the contributor part - // off for the base-model lookup and re-attach it to the resolved ids, - // so the direct path sends the contributor id upstream verbatim. A - // plain base-model request keeps the plain id — contributor is the - // caller's choice, never a proxy rewrite. - let contributor = false; - if (modelStr.endsWith('-contributor')) { - contributor = true; - modelStr = modelStr.slice(0, -'-contributor'.length); - } - - // Bare aliases - if (modelStr === 'spark' || modelStr === 'muse-spark') modelStr = 'muse-spark-1.3'; - if (modelStr === 'wonder' || modelStr === 'muse-wonder') modelStr = 'muse-wonder-1.0'; - - // Find base model config - const modelConfig = MODELS.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')) - || MODELS[0]; // default to muse-spark-1.3 - - // Resolve effort - if (!effort || !modelConfig.efforts.includes(effort)) { - effort = modelConfig.defaultEffort; - } - - const baseModel = contributor ? `${modelConfig.id}-contributor` : modelConfig.id; - return { - baseModel, - effort, - fullName: `${baseModel}-${effort}` - }; -}; - -const formatPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - if (messages.length === 1 && messages[0].role === 'user' && typeof messages[0].content === 'string') { - return messages[0].content; - } - - const parts = []; - const systemMessages = messages.filter(m => m.role === 'system'); - const convoMessages = messages.filter(m => m.role !== 'system'); - - if (systemMessages.length > 0) { - const sysText = systemMessages.map(m => - typeof m.content === 'string' ? m.content : JSON.stringify(m.content) - ).join('\n\n'); - parts.push(`[System Instructions]\n${sysText}`); - } - - if (convoMessages.length > 0) { - const convoText = convoMessages.map(m => { - let role = m.role === 'assistant' ? 'Assistant' : (m.role === 'user' ? 'User' : m.role); - let text = ''; - if (typeof m.content === 'string') { - text = m.content; - } else if (Array.isArray(m.content)) { - text = m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } else if (m.content) { - text = JSON.stringify(m.content); - } - - if (m.tool_calls && Array.isArray(m.tool_calls)) { - const tcStr = m.tool_calls.map(tc => `[Tool Call: ${tc.function?.name || 'function'}(${tc.function?.arguments || ''})]`).join('\n'); - text = text ? `${text}\n${tcStr}` : tcStr; - } - if (m.role === 'tool') { - role = `Tool Result (${m.tool_call_id || 'result'})`; - } - - return `${role}: ${text}`; - }).join('\n\n'); - parts.push(convoText); - } - - return parts.join('\n\n'); -}; - -// A request "carries tools" when the client offers tools, forces a tool -// choice, or its history already contains tool calls / tool results -// (a tool loop in progress). Any of those makes the vendor-CLI -// warm/exec fallback ineligible — see the tools-doctrine note at the -// top of this file. -const requestCarriesTools = (body) => { - if (Array.isArray(body.tools) && body.tools.length > 0) return true; - const tc = body.tool_choice; - if (tc === 'required') return true; - if (tc && typeof tc === 'object' && (tc.type === 'function' || tc.type === 'tool')) return true; - if (Array.isArray(body.messages)) { - for (const m of body.messages) { - if (!m || typeof m !== 'object') continue; - if (m.role === 'tool') return true; - if (Array.isArray(m.tool_calls) && m.tool_calls.length > 0) return true; - } - } - return false; -}; - -// Child env: inherit, but strip META_API_KEY (it outranks the OAuth login) -// and pin the egress proxy + CA bundle the CLI needs to reach Meta. -const childEnv = () => { - const env = { ...process.env }; - delete env.META_API_KEY; - 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); - const flagScanDecoder = createStreamDecoder(); - child.stdout.on('data', c => { out += flagScanDecoder.push(c); }); - const flagScanStderrDecoder = createStreamDecoder(); - child.stderr.on('data', c => { out += flagScanStderrDecoder.push(c); }); - 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 -// --------------------------------------------------------------------------- -// The exec path above pays a fresh CLI spawn (+ ~26k tokens of session -// scaffolding) for every request. `muse serve` instead hosts durable MSP -// sessions in one long-lived process: a conversation's first turn creates a -// session, later turns send only the new user message, and the provider -// serves the scaffolding from its prompt cache (verified on the sandbox: -// turn 2 of a served session reported 26,225 cacheReadTokens of 26,455 -// input tokens — ~230 uncached — vs 26,708 fully re-read input tokens for -// the same turn through the exec path). -// -// MSP is newline-delimited JSON-RPC 2.0 on the host's stdio (schema: -// `muse schema generate-json-schema`), so this is driven with the standard -// library only — no @muse-code/sdk runtime dependency. -// -// Conversations are keyed by sha256(model + system + first user message). -// The key -> session map persists to warm-sessions.json in the workdir -// (LRU 64 entries, 2h idle TTL), so sessions survive proxy restarts: the -// sessions themselves are durable in the CLI's own store and are re-attached -// with session/resume on the new host. A request whose history no longer -// matches the mapped session (diverged prefix, extra user turns, expired or -// lost session) is re-bootstrapped as a fresh session whose first turn is -// the full flattened transcript — exactly what the exec path sends on every -// request. Any warm-path failure before the response is committed falls -// back to the exec path; the warm path can be disabled with -// MUSE_PROXY_WARM=0. - -const WARM_ENABLED = process.env.MUSE_PROXY_WARM !== '0'; -const WARM_STATE_FILE = - process.env.MUSE_PROXY_WARM_STATE || path.join(WORKDIR, 'warm-sessions.json'); -const WARM_TTL_MS = 2 * 60 * 60 * 1000; -const WARM_MAX_SESSIONS = 64; -const WARM_TURN_TIMEOUT_MS = 300 * 1000; - -// Exec-fallback turn deadline (#2159): the exec path settles a request -// only when its child closes, so without a deadline a hung `muse exec` -// child wedges the request forever and leaks the process. The override -// is a strict positive integer of milliseconds within Node's timer -// range (<= 2^31 - 1; setTimeout clamps larger delays to ~1ms, which -// would time out every turn immediately); anything else warns once -// and falls back to the default — 0/disabled is not expressible. -const EXEC_TURN_TIMEOUT_MS = 300 * 1000; -const EXEC_KILL_GRACE_MS = 3000; -const parseExecTurnTimeoutMs = () => { - const raw = process.env.MUSE_PROXY_EXEC_TURN_TIMEOUT_MS; - if (raw === undefined) return EXEC_TURN_TIMEOUT_MS; - const n = Number(raw); - if (!Number.isInteger(n) || n <= 0 || n > 2147483647) { - console.warn(`[muse-proxy] ignoring invalid MUSE_PROXY_EXEC_TURN_TIMEOUT_MS=${JSON.stringify(raw)}; using ${EXEC_TURN_TIMEOUT_MS}ms`); - return EXEC_TURN_TIMEOUT_MS; - } - return n; -}; -const EXEC_TURN_TIMEOUT_MS_VALUE = parseExecTurnTimeoutMs(); - -// Shared kill escalation for the exec fallback (#2159): SIGTERM, then -// SIGKILL after a grace period. Used by both the turn deadline and the -// client-disconnect handler, and idempotent so the two can race safely. -const killChildWithEscalation = (child) => { - if (!child || child.__killEscalationStarted) return; - if (child.exitCode !== null || child.signalCode !== null) return; - child.__killEscalationStarted = true; - try { child.kill('SIGTERM'); } catch (_) {} - const grace = setTimeout(() => { - try { child.kill('SIGKILL'); } catch (_) {} - }, EXEC_KILL_GRACE_MS); - grace.unref?.(); - child.once('close', () => clearTimeout(grace)); -}; - -// MSP command ids must be UUIDv7 (the host rejects v4: "expected UUIDv7"). -let uuidV7LastMs = -1; -let uuidV7Seq = 0; -const uuidv7 = () => { - let now = Date.now(); - if (now <= uuidV7LastMs) { - now = uuidV7LastMs; - uuidV7Seq += 1; - if (uuidV7Seq > 0xfff) { now += 1; uuidV7Seq = 0; } - } else { - uuidV7Seq = 0; - } - uuidV7LastMs = now; - const bytes = crypto.randomBytes(16); - let t = now; - for (let i = 5; i >= 0; i -= 1) { bytes[i] = t & 0xff; t = Math.floor(t / 256); } - bytes[6] = 0x70 | ((uuidV7Seq >> 8) & 0x0f); - bytes[7] = uuidV7Seq & 0xff; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - const hex = bytes.toString('hex'); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -}; - -const messageText = (m) => { - if (!m || typeof m !== 'object') return ''; - if (typeof m.content === 'string') return m.content; - if (Array.isArray(m.content)) { - return m.content.map(c => (c && typeof c.text === 'string') ? c.text : '').join('\n'); - } - return m.content ? JSON.stringify(m.content) : ''; -}; - -const messageHash = (m) => - crypto.createHash('sha256').update(`${m.role}\x00${messageText(m)}`).digest('hex'); - -const conversationKey = (messages, baseModel) => { - const system = messages.filter(m => m.role === 'system').map(messageText).join('\n\n'); - const firstUser = messages.find(m => m.role === 'user'); - return crypto.createHash('sha256') - .update(`${baseModel}\x00${system}\x00${firstUser ? messageText(firstUser) : ''}`) - .digest('hex'); -}; - -// --- persistent key -> session map ----------------------------------------- -const warmStore = { - map: new Map(), - loaded: false, - load() { - if (this.loaded) return; - this.loaded = true; - try { - const raw = JSON.parse(fs.readFileSync(WARM_STATE_FILE, 'utf-8')); - const now = Date.now(); - for (const e of raw.entries || []) { - if (e && e.key && e.sessionId && now - (e.lastUsedAt || 0) <= WARM_TTL_MS) { - this.map.set(e.key, e); - } - } - } catch { /* no state yet */ } - }, - save() { - try { - const entries = [...this.map.values()].map(e => ({ - key: e.key, sessionId: e.sessionId, model: e.model, - hashes: e.hashes, sentCount: e.sentCount, lastUsedAt: e.lastUsedAt - })); - const tmp = `${WARM_STATE_FILE}.tmp`; - fs.writeFileSync(tmp, JSON.stringify({ entries }, null, 2)); - fs.renameSync(tmp, WARM_STATE_FILE); - } catch (err) { - console.warn(`[muse-proxy warm] state save failed: ${err.message}`); - } - }, - get(key) { - this.load(); - const entry = this.map.get(key); - if (!entry) return null; - if (Date.now() - (entry.lastUsedAt || 0) > WARM_TTL_MS) { - this.map.delete(key); - this.save(); - return null; - } - return entry; - }, - set(key, entry) { - this.load(); - this.map.set(key, entry); - if (this.map.size > WARM_MAX_SESSIONS) { - const byAge = [...this.map.values()].sort((a, b) => (a.lastUsedAt || 0) - (b.lastUsedAt || 0)); - for (const old of byAge.slice(0, this.map.size - WARM_MAX_SESSIONS)) { - this.map.delete(old.key); - warmHost.leave(old.sessionId); - } - } - this.save(); - }, - delete(key) { - this.map.delete(key); - this.save(); - } -}; - -// --- the one persistent serve host ------------------------------------------ -const warmHost = { - child: null, - readyPromise: null, - gen: 0, - seq: 0, - pending: new Map(), - listeners: new Set(), - stderrTail: '', - - ensure() { - if (this.readyPromise) return this.readyPromise; - this.readyPromise = this._start().catch(err => { - this.readyPromise = null; - throw err; - }); - return this.readyPromise; - }, - - async _start() { - 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, - env: childEnv(), - stdio: ['pipe', 'pipe', 'pipe'] - }); - this.child = child; - this.stderrTail = ''; - let lineBuffer = ''; - const stdoutDecoder = createStreamDecoder(); - const stderrDecoder = createStreamDecoder(); - child.stdout.on('data', chunk => { - lineBuffer += stdoutDecoder.push(chunk); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); - for (const line of lines) this._onLine(line); - }); - child.stderr.on('data', chunk => { - const msg = stderrDecoder.push(chunk); - this.stderrTail = (this.stderrTail + msg).slice(-2000); - if (msg.trim().length > 0) console.warn(`[muse-proxy warm stderr] ${msg.trim()}`); - }); - child.on('error', err => this._onExit(`spawn error: ${err.message}`)); - child.on('close', (code, signal) => this._onExit(`serve host exited (code ${code}, signal ${signal})`)); - let result; - try { - result = await this.rpc('initialize', { - clientInfo: { name: 'muse_proxy', version: '1.0.0' }, - capabilities: { userInputDialogs: false } - }, 20000); - this._write({ jsonrpc: '2.0', method: 'initialized' }); - } catch (err) { - try { child.kill('SIGKILL'); } catch { /* already gone */ } - if (this.child === child) this.child = null; - throw err; - } - this.gen += 1; - console.log(`[muse-proxy warm] serve host ready (gen ${this.gen}, server ${result?.serverInfo?.name} ${result?.serverInfo?.version})`); - }, - - _onExit(reason) { - if (!this.child && this.pending.size === 0) return; - this.child = null; - this.readyPromise = null; - const err = new Error(reason); - for (const p of this.pending.values()) p.reject(err); - this.pending.clear(); - for (const fn of [...this.listeners]) { - try { fn({ method: 'host/died', params: { reason } }); } catch { /* listener */ } - } - }, - - _write(obj) { - if (!this.child || !this.child.stdin.writable) throw new Error('serve host stdin is not writable'); - this.child.stdin.write(JSON.stringify(obj) + '\n'); - }, - - _onLine(line) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - let msg; - try { msg = JSON.parse(trimmed); } catch { return; } - if (msg.id !== undefined && msg.method === undefined && this.pending.has(msg.id)) { - const p = this.pending.get(msg.id); - this.pending.delete(msg.id); - if (msg.error) p.reject(new Error(`MSP ${msg.error.message || 'error'} (code ${msg.error.code})`)); - else p.resolve(msg.result); - return; - } - if (msg.id !== undefined && typeof msg.method === 'string') { - // Server-initiated request (approval/request, userInput/request): - // acknowledge presentation only, as the SDK's receipt does. Sessions - // run with approvalMode allowAll and request-user-input withheld, so - // no decision is expected to follow. - try { this._write({ jsonrpc: '2.0', id: msg.id, result: {} }); } catch { /* host gone */ } - console.warn(`[muse-proxy warm] server request ${msg.method} acknowledged`); - return; - } - if (typeof msg.method === 'string') { - for (const fn of [...this.listeners]) { - try { fn(msg); } catch { /* listener */ } - } - } - }, - - rpc(method, params, timeoutMs = 30000) { - return new Promise((resolve, reject) => { - const id = ++this.seq; - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`MSP ${method} timed out after ${timeoutMs}ms`)); - }, timeoutMs); - this.pending.set(id, { - resolve: v => { clearTimeout(timer); resolve(v); }, - reject: e => { clearTimeout(timer); reject(e); } - }); - try { - this._write({ jsonrpc: '2.0', id, method, params }); - } catch (err) { - this.pending.delete(id); - clearTimeout(timer); - reject(err); - } - }); - }, - - onNotification(fn) { - this.listeners.add(fn); - return () => this.listeners.delete(fn); - }, - - leave(sessionId) { - if (!sessionId || !this.readyPromise) return; - this.rpc('session/leave', { commandId: uuidv7(), sessionId }, 5000).catch(() => {}); - }, - - async startSession(baseModel) { - const result = await this.rpc('session/start', { - commandId: uuidv7(), - modelId: baseModel, - approvalMode: 'allowAll', - workspaceRoots: [WORKDIR] - }); - const sessionId = result?.session?.sessionId; - if (!sessionId) throw new Error('session/start returned no sessionId'); - return sessionId; - }, - - async resumeSession(sessionId) { - const result = await this.rpc('session/resume', { - commandId: uuidv7(), - sessionId, - excludeItems: true - }); - const resumed = result?.session?.sessionId; - if (!resumed) throw new Error('session/resume returned no session'); - return resumed; - }, - - // Run one turn on a loaded session. Streams agentMessage text deltas to - // onDelta (when given) and resolves with the turn's full text + usage. - runTurn({ sessionId, text, effort, onDelta }) { - return new Promise((resolve, reject) => { - let turnId = null; - let deltasText = ''; - let lastAgentText = null; - let lastFinalText = null; - let usage = null; - const itemKinds = new Map(); - let settled = false; - const settle = (fn, value) => { - if (settled) return; - settled = true; - clearTimeout(timer); - off(); - fn(value); - }; - const timer = setTimeout(() => { - settle(reject, new Error(`warm turn timed out after ${WARM_TURN_TIMEOUT_MS}ms`)); - }, WARM_TURN_TIMEOUT_MS); - const off = this.onNotification(msg => { - const params = msg.params || {}; - if (params.sessionId !== sessionId && msg.method !== 'host/died') return; - switch (msg.method) { - case 'host/died': - settle(reject, new Error(`serve host died mid-turn: ${params.reason}`)); - break; - case 'item/started': - if (params.item && params.item.itemId) itemKinds.set(params.item.itemId, params.item.kind); - break; - case 'item/delta': { - const kind = itemKinds.get(params.itemId); - if ((params.field === undefined || params.field === 'text') && - (kind === undefined || kind === 'agentMessage') && - typeof params.delta === 'string') { - deltasText += params.delta; - if (onDelta) { - try { onDelta(params.delta); } catch { /* response gone */ } - } - } - break; - } - case 'item/completed': - if (params.item && params.item.kind === 'agentMessage' && typeof params.item.text === 'string') { - lastAgentText = params.item.text; - if (params.item.messagePhase === 'finalAnswer') lastFinalText = params.item.text; - } - break; - case 'session/tokenUsage': - if (params.usage) { - usage = { - promptTokens: params.usage.inputTokens, - completionTokens: params.usage.outputTokens, - cacheReadTokens: typeof params.usage.cacheReadTokens === 'number' ? params.usage.cacheReadTokens : 0 - }; - } - break; - case 'turn/completed': - if (turnId && params.turnId !== turnId) break; - if (params.terminal !== 'completed') { - settle(reject, new Error(`warm turn terminated with state '${params.terminal}'${params.reason ? `: ${params.reason}` : ''}`)); - } else { - settle(resolve, { - deltasText, - fullText: lastFinalText ?? lastAgentText ?? deltasText, - promptTokens: usage?.promptTokens, - completionTokens: usage?.completionTokens, - cacheReadTokens: usage?.cacheReadTokens - }); - } - break; - default: - break; - } - }); - this.rpc('turn/start', { - commandId: uuidv7(), - sessionId, - input: [{ type: 'text', text }], - reasoningEffort: effort - }).then(ack => { - turnId = ack?.turnId || turnId; - }).catch(err => settle(reject, err)); - }); - } -}; - -// Per-conversation serialization: turns on one session must not interleave, -// and the delta decision must be made against the latest committed state. -const warmChains = new Map(); -const enqueueWarm = (key, job) => { - const prev = warmChains.get(key) || Promise.resolve(); - const run = prev.then(job, job); - const stored = run.catch(() => {}); - warmChains.set(key, stored); - stored.then(() => { if (warmChains.get(key) === stored) warmChains.delete(key); }); - return run; -}; - -// Attempt the chat completion on the warm serve path. Returns true when the -// response has been fully handled (success, or a stream already committed -// that had to be terminated in place); false when nothing was written and -// the caller should fall back to the exec path. -const tryWarmChat = async ({ messages, baseModel, effort, fullName, stream, res, chatId, created }) => { - const key = conversationKey(messages, baseModel); - let headed = false; - let streamedText = ''; - const writeChunk = (content) => { - if (!stream || res.writableEnded) return; - if (!headed) { - headed = 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' - }); - } - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ index: 0, delta: { content }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - streamedText += content; - }; - - const job = async () => { - await warmHost.ensure(); - let entry = warmStore.get(key); - let sessionId = null; - let turnText = null; - const hashes = messages.map(messageHash); - - if (entry && entry.sessionId && entry.model === baseModel) { - if (entry.hostGen === warmHost.gen) { - sessionId = entry.sessionId; - } else { - try { - sessionId = await warmHost.resumeSession(entry.sessionId); - entry.hostGen = warmHost.gen; - console.log(`[muse-proxy warm] resumed session ${sessionId} for key ${key.slice(0, 8)}`); - } catch (err) { - console.warn(`[muse-proxy warm] resume failed (${err.message}); re-bootstrapping`); - sessionId = null; - } - } - } - - if (sessionId) { - const last = messages[messages.length - 1]; - const suffix = messages.slice(entry.sentCount); - const prefixOk = entry.sentCount > 0 && - entry.hashes.length >= entry.sentCount && - entry.hashes.slice(0, entry.sentCount).every((h, i) => h === hashes[i]); - const midUsers = suffix.slice(0, -1).filter(m => m.role === 'user').length; - if (prefixOk && suffix.length > 0 && last.role === 'user' && midUsers === 0) { - turnText = messageText(last); - } else { - console.log(`[muse-proxy warm] history diverged for key ${key.slice(0, 8)}; re-bootstrapping`); - sessionId = null; - } - } - - if (!sessionId) { - const replacedSessionId = entry && entry.sessionId; - sessionId = await warmHost.startSession(baseModel); - if (replacedSessionId && replacedSessionId !== sessionId) warmHost.leave(replacedSessionId); - turnText = formatPrompt(messages); - entry = { - key, sessionId, model: baseModel, - hashes: [], sentCount: 0, lastUsedAt: Date.now(), hostGen: warmHost.gen - }; - warmStore.set(key, entry); - console.log(`[muse-proxy warm] new session ${sessionId} for key ${key.slice(0, 8)}`); - } - - const result = await warmHost.runTurn({ - sessionId, - text: turnText, - effort, - onDelta: stream ? writeChunk : null - }); - - entry.sessionId = sessionId; - entry.hashes = hashes; - entry.sentCount = messages.length; - entry.lastUsedAt = Date.now(); - entry.hostGen = warmHost.gen; - warmStore.set(key, entry); - return result; - }; - - let result; - try { - result = await enqueueWarm(key, job); - } catch (err) { - console.warn(`[muse-proxy warm] warm path failed (${err.message}); ${headed ? 'stream already committed, terminating in place' : 'falling back to exec'}`); - if (!headed) return false; - if (!res.writableEnded) { - res.write(`data: ${JSON.stringify({ error: { message: `Muse execution failed: ${err.message}` } })}\n\n`); - res.write('data: [DONE]\n\n'); - } - res.end(); - return true; - } - - // Reconcile deltas with the authoritative final text (same rule as the - // exec path, #484): only a missing tail can still be appended to a stream. - let fullContent = result.deltasText; - let unstreamedSuffix = ''; - if (typeof result.fullText === 'string' && result.fullText.length >= fullContent.length) { - if (result.fullText.startsWith(fullContent)) unstreamedSuffix = result.fullText.slice(fullContent.length); - fullContent = result.fullText; - } - const promptTokens = (typeof result.promptTokens === 'number' && result.promptTokens > 0) - ? result.promptTokens - : Math.max(1, Math.ceil(formatPrompt(messages).length / 4)); - let completionTokens = (typeof result.completionTokens === 'number' && result.completionTokens > 0) - ? result.completionTokens - : 0; - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - const cacheReadTokens = (typeof result.cacheReadTokens === 'number' && result.cacheReadTokens > 0) - ? result.cacheReadTokens - : 0; - - if (stream) { - if (unstreamedSuffix.length > 0) writeChunk(unstreamedSuffix); - if (!headed) { - headed = 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' - }); - } - const endChunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens, - ...(cacheReadTokens > 0 ? { prompt_tokens_details: { cached_tokens: cacheReadTokens } } : {}) - } - }; - res.write(`data: ${JSON.stringify(endChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: chatId, - object: 'chat.completion', - created, - model: fullName, - choices: [{ - index: 0, - message: { role: 'assistant', content: fullContent }, - finish_reason: 'stop' - }], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens, - ...(cacheReadTokens > 0 ? { prompt_tokens_details: { cached_tokens: cacheReadTokens } } : {}) - } - }, null, 2)); - } - 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) : ''; -}; - -// Meta's subscription-key gate rejects requests whose function tools carry -// the well-known agent-harness shell names (`shell`, `bash`) with 403 -// client_attestation_denied — verified live 2026-10-30 by bisecting a real -// opencode request body: every other tool, the instructions, and all client -// headers pass unchanged, while `run_command` / `terminal` pass. The direct -// path therefore presents those tools under alias names and translates the -// model's tool calls back on the way out. The CLI door never needed this — -// the CLI sends its own toolset. -const DIRECT_TOOL_ALIASES = { shell: 'run_command', bash: 'terminal' }; -const DIRECT_TOOL_NAMES = Object.fromEntries( - Object.entries(DIRECT_TOOL_ALIASES).map(([client, alias]) => [alias, client]) -); -const directToolAlias = (name, taken) => { - const alias = DIRECT_TOOL_ALIASES[name]; - if (!alias || (taken && taken.has(alias))) return name; - 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. -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; } - } - }; - 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); - } - } -}; - -// 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 - .filter(m => m.role === 'system') - .map(messageText) - .filter(Boolean) - .join('\n\n'); - const takenNames = new Set((Array.isArray(body.tools) ? body.tools : []) - .map(t => t && t.function && t.function.name).filter(Boolean)); - 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 ? directToolAlias(tc.function.name, takenNames) : 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: directToolAlias(t.function.name, takenNames), 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: directToolAlias(tc.function.name, takenNames) }; - 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: clientToolName(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: clientToolName(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) { - const text = await response.text().catch(() => ''); - if (response.status === 403 && text.includes('client_attestation_denied')) { - // The attestation fingerprint moved (a tool name newly blocked): - // degrade to the CLI door instead of failing the seat outright. - console.warn('[muse-proxy] direct path attestation denied; falling back to the CLI door'); - return false; - } - // Meta answered: pass the response through as-is, whatever the status. - 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; - } - const failedMessage = respBody && respBody.status === 'failed' - ? ((respBody.error && respBody.error.message) || 'Direct Meta Responses request failed') - : null; - if (failedMessage) { - // A failed upstream body must surface as an error even when output - // carries partial text (#2780): never report it as a 200 completion. - writeJsonBody(res, 500, { error: { message: failedMessage } }); - return true; - } - const incompleteReason = respBody && respBody.status === 'incomplete' && - (!respBody.incomplete_details || respBody.incomplete_details.reason !== 'max_output_tokens') - ? ((respBody.incomplete_details && respBody.incomplete_details.reason) || 'unknown') - : null; - if (incompleteReason) { - // An incomplete body that was not cut off by max_output_tokens is an - // upstream failure, not a finish_reason stop (#2780). - writeJsonBody(res, 500, { error: { message: `Direct Meta response incomplete: ${incompleteReason}` } }); - 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'); - res.setHeader('Access-Control-Allow-Headers', '*'); - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - // Health & Root - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'meta-muse-proxy', - port: PORT, - binary: MUSE_BIN, - defaultModel: 'muse-spark-1.3-high', - endpoint: '/v1/chat/completions', - warm: { - enabled: WARM_ENABLED, - hostGen: warmHost.gen, - hostUp: Boolean(warmHost.child), - sessions: warmStore.map.size, - chains: warmChains.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, - dropped: { serve: cliDropped.serve, exec: cliDropped.exec } - } - }, null, 2)); - return; - } - - // Models catalog - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - const data = []; - - for (const m of MODELS) { - data.push({ - id: m.id, - object: 'model', - created: now, - owned_by: 'meta-muse' - }); - for (const eff of m.efforts) { - data.push({ - id: `${m.id}-${eff}`, - object: 'model', - created: now, - owned_by: 'meta-muse' - }); - } - } - - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); - 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')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); - req.destroy(); - } - }); - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - 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; - let aliasedBody = { text: bodyText, aliased: false }; - try { - 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; - } - if (outcome.hard) { - writeJsonBody(res, 502, { error: { message: outcome.hard.message } }); - return; - } - const response = outcome.response; - 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; - 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(); - 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; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); - req.destroy(); - } - }); - - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Invalid JSON body: ${err.message}` } })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Invalid JSON body: expected an object' } })); - return; - } - - const stream = Boolean(body.stream); - const reqReasoningEffort = body.reasoning_effort || (body.options && body.options.reasoning_effort); - const { baseModel, effort, fullName } = resolveModelAndEffort(body.model, reqReasoningEffort); - const prompt = formatPrompt(body.messages); - - if (!prompt || prompt.trim().length === 0) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Messages cannot be empty' } })); - return; - } - - 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. - const carriesTools = requestCarriesTools(body); - res.setHeader('X-Muse-Proxy-Path', 'direct'); - 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; - } - - // Tools gate (code#6117): the warm/exec vendor-CLI fallback - // flattens the conversation to a prompt and can only return - // final text — it can never emit the client's tool calls. A - // tools-carrying request that direct mode could not serve - // (no credential, direct disabled, exchange/upstream transport - // failure, or an attestation denial) fails loudly here instead - // of silently degrading to CLI agency under the client's tools. - if (carriesTools) { - console.warn('[muse-proxy] tools-carrying request refused: direct path unavailable and the warm/exec vendor-CLI fallback cannot emit client tool calls'); - writeJsonBody(res, 502, { - error: { - message: 'muse-proxy: this request carries client tools, which only the direct (Meta Responses wire-emulation) path can serve with real tool calls. The direct path is unavailable for this request and the warm/exec vendor-CLI fallback is ineligible for tools-carrying requests (it would silently substitute the Muse CLI\'s own tools and return text only), so no fallback was attempted.', - type: 'tools_fallback_ineligible', - code: 'tools_fallback_ineligible' - } - }); - 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. - res.setHeader('X-Muse-Proxy-Path', 'warm'); - if (WARM_ENABLED) { - let warmHandled = false; - try { - warmHandled = await tryWarmChat({ - messages: body.messages, baseModel, effort, fullName, stream, res, chatId, created - }); - } catch (err) { - console.warn(`[muse-proxy warm] unexpected warm error (${err.message}); falling back to exec`); - warmHandled = false; - } - if (warmHandled) return; - if (res.writableEnded) return; - } - - res.setHeader('X-Muse-Proxy-Path', 'exec'); - // Prompt goes in via --prompt-file (no argv length/escaping concerns) - const promptFile = path.join(WORKDIR, `prompt-${crypto.randomUUID()}.txt`); - fs.writeFileSync(promptFile, prompt, 'utf-8'); - - // Spawn arguments for muse exec (only the flags the resolved CLI - // advertises — see the capability probe) - await ensureCliCaps(); - const args = buildCliArgs('exec', [ - 'exec', - { 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(' ')}`); - - let child; - try { - child = spawn(MUSE_BIN, args, { - cwd: WORKDIR, - env: childEnv(), - stdio: ['ignore', 'pipe', 'pipe'] - }); - } catch (err) { - console.error(`[muse-proxy] Failed to spawn muse: ${err.message}`); - try { fs.unlinkSync(promptFile); } catch (_) {} - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Failed to spawn muse: ${err.message}` } })); - return; - } - - // Turn deadline (#2159): from spawn, exec fallback only. The kill - // normally produces the child's close event, and the close handler - // below settles the request through the existing error shape. But - // 'close' waits for the child's stdio pipes to drain, and a - // descendant that inherited those pipes can hold them open - // indefinitely after the child itself is dead — so the deadline - // also arms an independent settle at deadline + kill grace that - // bounds settlement and prompt-file cleanup whether or not - // 'close' ever fires (Codex review on PR #4242). - let timedOut = false; - let settleTimer = null; - const deadlineTimer = setTimeout(() => { - timedOut = true; - killChildWithEscalation(child); - // The +1s past the grace lets the normal SIGKILL path settle - // through 'close' first; only a 'close' that never comes (the - // descendant-pipe case) actually reaches this timer. - settleTimer = setTimeout(() => { - try { child.stdout?.destroy(); } catch (_) {} - try { child.stderr?.destroy(); } catch (_) {} - settleRequest(null, null); - }, EXEC_KILL_GRACE_MS + 1000); - settleTimer.unref?.(); - }, EXEC_TURN_TIMEOUT_MS_VALUE); - deadlineTimer.unref?.(); - - res.on('close', () => { - if (!res.writableEnded) { - killChildWithEscalation(child); - } - }); - - if (stream) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream; charset=utf-8', - 'Cache-Control': 'no-cache, no-transform', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no' - }); - } - - let lineBuffer = ''; - const stdoutDecoder = createStreamDecoder(); - const stderrDecoder = createStreamDecoder(); - let fullContent = ''; - let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); - let completionTokens = 0; - let terminalState = null; - let terminalText = null; - let stderrTail = ''; - - const processJsonLine = (line) => { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - - try { - const event = JSON.parse(trimmed); - const payload = event.payload || {}; - - // Assistant text delta (streams token chunks) - if (event.payload_type === 'run.output.delta' && typeof payload.text === 'string') { - const text = payload.text; - fullContent += text; - - if (stream && !res.writableEnded) { - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ - index: 0, - delta: { content: text }, - finish_reason: null - }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - } - - // Real token usage from the run - if (event.payload_type === 'run.usage' && Array.isArray(payload.models)) { - let inTok = 0; - let outTok = 0; - for (const m of payload.models) { - if (typeof m.input_tokens === 'number') inTok += m.input_tokens; - if (typeof m.output_tokens === 'number') outTok += m.output_tokens; - } - if (inTok > 0) promptTokens = inTok; - if (outTok > 0) completionTokens = outTok; - } - - // Terminal event carries the authoritative final text - if (typeof event.payload_type === 'string' && event.payload_type.startsWith('run.terminal.')) { - terminalState = payload.terminal || event.payload_type.slice('run.terminal.'.length); - if (typeof payload.text === 'string') terminalText = payload.text; - } - } catch (err) { - // Non-JSON line or parser error ignored - } - }; - - child.stdout.on('data', chunk => { - lineBuffer += stdoutDecoder.push(chunk); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); // remainder - for (const line of lines) { - processJsonLine(line); - } - }); - - child.stderr.on('data', chunk => { - const msg = stderrDecoder.push(chunk); - stderrTail = (stderrTail + msg).slice(-2000); - if (msg.trim().length > 0) { - console.warn(`[muse-proxy stderr] ${msg.trim()}`); - } - }); - - const emitFailure = (detail) => { - const errorBody = { error: { message: `Muse execution failed: ${detail}` } }; - if (stream) { - // The 200 + text/event-stream headers are already on the wire, - // so a bare JSON body would be invisible to an SSE client - // parsing `data:` lines — it would see an empty, successful - // stream (#670). Frame the error as an SSE event and close - // the stream with [DONE] instead. - if (!res.writableEnded) { - res.write(`data: ${JSON.stringify(errorBody)}\n\n`); - res.write('data: [DONE]\n\n'); - } - res.end(); - return; - } - if (!res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - } - res.end(JSON.stringify(errorBody)); - }; - - let settled = false; - const settleRequest = (code, signal) => { - if (settled) return; - settled = true; - clearTimeout(deadlineTimer); - if (settleTimer) clearTimeout(settleTimer); - if (lineBuffer.trim().length > 0) { - processJsonLine(lineBuffer); - lineBuffer = ''; - } - try { fs.unlinkSync(promptFile); } catch (_) {} - - // Deadline check FIRST (#2159): a turn killed for exceeding the - // deadline is a timeout failure even if the child had already - // emitted a completed terminal event — never a silent - // successful stop — and the #484 reconciliation is skipped. - if (timedOut) { - if (!res.writableEnded) { - emitFailure(`muse exec turn timed out after ${EXEC_TURN_TIMEOUT_MS_VALUE}ms`); - } - return; - } - - if (res.writableEnded) return; - - // Reconcile the streamed deltas with the terminal event's - // authoritative final text (#484). In stream mode the deltas are - // already on the wire, so the only recoverable divergence is a - // missing tail: when the terminal text extends the streamed text, - // the suffix is emitted as one last content chunk before the - // finish chunk below, so streamed and non-streamed clients end up - // with identical content. Any other divergence (the terminal text - // is not an extension of what was streamed) cannot be retracted - // from a stream; it is logged explicitly instead of silently - // truncating, and the non-streamed response still uses the - // authoritative text when it is at least as long. - let unstreamedSuffix = ''; - if (terminalText !== null) { - if (terminalText.startsWith(fullContent)) { - unstreamedSuffix = terminalText.slice(fullContent.length); - } else if (terminalText.length >= fullContent.length) { - console.warn('[muse-proxy] terminal text diverges from streamed deltas; streamed response cannot be corrected retroactively'); - } - if (terminalText.length >= fullContent.length) { - fullContent = terminalText; - } - } - - // Failure is judged by the run's authoritative terminal state when - // one was emitted, otherwise by the exit code (#672). Partial - // content must not mask a failure: a run that failed midway used to - // be reported as a successful 'stop' carrying the truncated text, - // because both clauses of the old predicate required empty content. - const failed = terminalState ? terminalState !== 'completed' : code !== 0; - if (failed) { - const stderrLine = stderrTail.trim().split('\n').pop(); - const fallback = terminalState && terminalState !== 'completed' - ? `muse run terminated with state '${terminalState}'` - : signal - ? `muse exec terminated by signal ${signal}` - : `muse exec exited with code ${code}`; - const detail = (stderrLine || fallback).trim(); - emitFailure(detail); - return; - } - - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - - if (stream) { - if (unstreamedSuffix.length > 0) { - const tailChunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ - index: 0, - delta: { content: unstreamedSuffix }, - finish_reason: null - }] - }; - res.write(`data: ${JSON.stringify(tailChunk)}\n\n`); - } - const endChunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ - index: 0, - delta: {}, - finish_reason: 'stop' - }], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens - } - }; - res.write(`data: ${JSON.stringify(endChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: chatId, - object: 'chat.completion', - created, - model: fullName, - choices: [{ - index: 0, - message: { - role: 'assistant', - content: fullContent - }, - finish_reason: 'stop' - }], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens - } - }, null, 2)); - } - }; - - child.on('close', settleRequest); - - child.on('error', err => { - if (settled) return; - settled = true; - clearTimeout(deadlineTimer); - if (settleTimer) clearTimeout(settleTimer); - console.error(`[muse-proxy child error] ${err.message}`); - try { fs.unlinkSync(promptFile); } catch (_) {} - if (!res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Muse execution error: ${err.message}` } })); - } - }); - }); - return; - } - - // Fallthrough 404 - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); -}); - - -// Publish the bound endpoint so other tools can find this proxy without -// knowing its port in advance: $XDG_STATE_HOME//endpoint.json -// (default ~/.local/state//endpoint.json), written on listen, -// removed on exit. -const publishEndpoint = () => { - try { - const stateHome = - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'muse-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync( - `${file}.tmp`, - JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n', - ); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { - try { fs.unlinkSync(file); } catch {} - }; - process.on('exit', cleanup); - process.on('SIGTERM', () => { cleanup(); process.exit(0); }); - process.on('SIGINT', () => { cleanup(); process.exit(0); }); - } catch {} -}; - -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}`); -}); diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs deleted file mode 100644 index 2240300b38..0000000000 --- a/bin/muse-proxy.test.mjs +++ /dev/null @@ -1,1348 +0,0 @@ -// 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 -// put a stub `muse` first on PATH (and point HOME at an empty dir so the -// real ~/.local/bin/muse is not preferred) whose JSONL output is fixed: -// the deltas are a strict prefix of the terminal event's authoritative -// text — the case where streaming used to silently drop the tail. -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'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const STUB = `#!/usr/bin/env node -// Stub muse: 'exec' reproduces the fixed JSONL behaviours the exec-path -// tests assert on; 'serve' speaks just enough MSP (NDJSON JSON-RPC) for -// 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 ] [--model ] [OPTIONS]'); - console.log(' --provider '); - console.log(' --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 '); - console.log(' --model '); - console.log(' --reasoning-effort '); - if (all) console.log(' --disable-reminders'); - console.log(' --user-input-auto-resolve'); - console.log(' --approval-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'); }; - let buf = ''; - let stubSessN = 0; - process.stdin.on('data', (d) => { - buf += d.toString('utf-8'); - let i; - while ((i = buf.indexOf('\\n')) >= 0) { - const line = buf.slice(0, i); buf = buf.slice(i + 1); - if (!line.trim()) continue; - let msg; try { msg = JSON.parse(line); } catch { continue; } - if (msg.id === undefined || !msg.method) continue; - const reply = (result) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result }) + '\\n'); - const notify = (method, params) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\\n'); - if (msg.method === 'initialize') { - reply({ serverInfo: { name: 'stub-muse', version: '0' } }); - } else if (msg.method === 'session/start') { - log('START ' + msg.params.modelId); - reply({ session: { sessionId: 'stub-session-' + (++stubSessN) } }); - } else if (msg.method === 'session/resume') { - log('RESUME ' + msg.params.sessionId); - reply({ session: { sessionId: msg.params.sessionId } }); - } else if (msg.method === 'turn/start') { - const text = (msg.params.input || []).map(p => p.text || '').join(''); - if (text.includes('KILLHOST')) { log('KILLED ' + text); process.kill(process.pid, 'SIGKILL'); } - log('TURN ' + text); - const sid = msg.params.sessionId; - const turnId = msg.params.commandId; - reply({ commandId: msg.params.commandId, turnId, disposition: 'started', startedNewTurn: true, status: 'accepted' }); - notify('item/started', { sessionId: sid, item: { itemId: 'a1', kind: 'agentMessage' } }); - notify('item/delta', { sessionId: sid, itemId: 'a1', delta: 'RE:' + text }); - notify('item/completed', { sessionId: sid, item: { itemId: 'a1', kind: 'agentMessage', messagePhase: 'finalAnswer', text: 'RE:' + text } }); - notify('session/tokenUsage', { sessionId: sid, turnId, usage: { inputTokens: 42, outputTokens: 7, cacheReadTokens: 40 } }); - notify('turn/completed', { sessionId: sid, turnId, terminal: 'completed' }); - } else { - reply({}); - } - } - }); -} else { - let promptFile = null; - for (let i = 0; i < args.length; i++) if (args[i] === '--prompt-file') promptFile = args[i + 1]; - let prompt = ''; - try { prompt = fs.readFileSync(promptFile, 'utf-8'); } catch {} - const line = (o) => console.log(JSON.stringify(o)); - if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, 'EXECPID ' + process.pid + String.fromCharCode(10)); - if (prompt.includes('HANGAFTERDONE')) { - line({ payload_type: 'run.output.delta', payload: { text: 'Hel' } }); - line({ payload_type: 'run.terminal.completed', payload: { terminal: 'completed', text: 'Hello world' } }); - setInterval(() => {}, 1000); - return; - } - if (prompt.includes('HANGTERMI')) { process.on('SIGTERM', () => {}); setInterval(() => {}, 1000); return; } - if (prompt.includes('HANGME')) { setInterval(() => {}, 1000); return; } - if (prompt.includes('HANGDESCENDANT')) { - // A descendant that inherits our stdout/stderr and outlives us: the - // proxy's child 'close' event waits on those pipes, so killing this - // process alone never settles the request (Codex P2 on PR #4242). - const descendant = require('child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'inherit' }); - if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, 'DESCPID ' + descendant.pid + String.fromCharCode(10)); - setInterval(() => {}, 1000); - return; - } - if (prompt.includes('FAILME')) { console.error('stub muse: auth expired'); process.exit(3); } - if (prompt.includes('FAILPARTIAL')) { - line({ payload_type: 'run.output.delta', payload: { text: 'partial answer' } }); - line({ payload_type: 'run.terminal.failed', payload: { terminal: 'failed', text: 'partial answer' } }); - console.error('stub muse: run failed midway'); - process.exit(0); - } - if (prompt.includes('CRASHPARTIAL')) { - line({ payload_type: 'run.output.delta', payload: { text: 'partial answer' } }); - console.error('stub muse: crashed midway'); - process.exit(3); - } - if (prompt.includes('FAILSTATE')) { - line({ payload_type: 'run.terminal.failed', payload: { terminal: 'failed' } }); - process.exit(0); - } - if (prompt.includes('SIGKILLME')) { process.kill(process.pid, 'SIGKILL'); } - if (prompt.includes('DIVERGE')) { - line({ payload_type: 'run.output.delta', payload: { text: 'abc' } }); - line({ payload_type: 'run.terminal.completed', payload: { terminal: 'completed', text: 'xyz-longer' } }); - } else { - line({ payload_type: 'run.output.delta', payload: { text: 'Hel' } }); - line({ payload_type: 'run.usage', payload: { models: [{ input_tokens: 100, output_tokens: 3 }] } }); - line({ payload_type: 'run.terminal.completed', payload: { terminal: 'completed', text: 'Hello world' } }); - } -}`; - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -const startProxy = async (extraEnv = {}) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'muse-proxy-test-')); - const stubDir = path.join(tmp, 'stub'); - 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')], { - env: { - ...process.env, - HOME: path.join(tmp, 'home'), - PATH: `${stubDir}:${process.env.PATH}`, - MUSE_PROXY_PORT: String(port), - MUSE_PROXY_WORKDIR: path.join(tmp, 'work'), - MUSE_PROXY_WARM: '0', - STUB_LOG: logFile, - ...extraEnv - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', d => { log += d; }); - child.stderr.on('data', d => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch { /* not up yet */ } - 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, home: path.join(tmp, 'home') }; -}; - -const chat = async (port, body) => { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) - }); - assert.equal(res.status, 200); - return res.text(); -}; - -const streamedContent = (sse) => { - let content = ''; - let finish = null; - for (const line of sse.split('\n')) { - if (!line.startsWith('data: ') || line === 'data: [DONE]') continue; - const chunk = JSON.parse(line.slice('data: '.length)); - const choice = chunk.choices[0]; - if (choice.delta && typeof choice.delta.content === 'string') content += choice.delta.content; - if (choice.finish_reason) finish = choice.finish_reason; - } - return { content, finish }; -}; - -test('streaming emits the terminal text tail the deltas missed (#484)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'hi' }]; - - const plain = JSON.parse(await chat(port, { messages })); - assert.equal(plain.choices[0].message.content, 'Hello world'); - - const { content, finish } = streamedContent(await chat(port, { messages, stream: true })); - assert.equal(content, 'Hello world', 'streamed content must equal the non-streamed content'); - assert.equal(finish, 'stop'); -}); - -test('execution failure: stream gets an SSE-framed error + [DONE], non-stream gets 500 (#670)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please FAILME now' }]; - - const plainRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages }) - }); - assert.equal(plainRes.status, 500); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.error.message, /Muse execution failed: stub muse: auth expired/); - - const streamRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages, stream: true }) - }); - assert.equal(streamRes.status, 200); - assert.match(streamRes.headers.get('content-type'), /text\/event-stream/); - const sse = await streamRes.text(); - const dataLines = sse.split('\n').filter(l => l.startsWith('data: ')); - assert.ok(dataLines.length >= 2, `expected a framed error event and [DONE], got: ${JSON.stringify(sse)}`); - const errorEvent = JSON.parse(dataLines[0].slice('data: '.length)); - assert.match(errorEvent.error.message, /Muse execution failed: stub muse: auth expired/); - assert.equal(dataLines[dataLines.length - 1], 'data: [DONE]'); -}); - -test('partial output then failure: masked success becomes an error in both modes (#672)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - - for (const marker of ['FAILPARTIAL', 'CRASHPARTIAL']) { - const messages = [{ role: 'user', content: `please ${marker} now` }]; - - const plainRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages }) - }); - assert.equal(plainRes.status, 500, `${marker}: non-stream must be a 500, not a 200 'stop'`); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.error.message, /Muse execution failed: stub muse:/); - - const streamRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages, stream: true }) - }); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - const dataLines = sse.split('\n').filter(l => l.startsWith('data: ')); - assert.equal(dataLines[dataLines.length - 1], 'data: [DONE]', `${marker}: stream must end with [DONE]`); - const events = dataLines.slice(0, -1).map(l => JSON.parse(l.slice('data: '.length))); - const errorEvent = events.find(e => e.error); - assert.ok(errorEvent, `${marker}: stream must carry an error event, got: ${JSON.stringify(sse)}`); - assert.match(errorEvent.error.message, /Muse execution failed: stub muse:/); - const stopChunk = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); - assert.equal(stopChunk, undefined, `${marker}: no chunk may claim finish_reason 'stop'`); - } -}); - -const assertEmptyStderrFallback = async (t, marker, detail) => { - const { port, stop } = await startProxy(); - t.after(stop); - - { - const messages = [{ role: 'user', content: `please ${marker} now` }]; - - const plainRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages }) - }); - assert.equal(plainRes.status, 500, `${marker}: non-stream must be a 500`); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.error.message, detail, `${marker}: non-stream detail must name the cause, got: ${plainBody.error.message}`); - assert.doesNotMatch(plainBody.error.message, /code (null|0)\b/); - - const streamRes = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages, stream: true }) - }); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - const dataLines = sse.split('\n').filter(l => l.startsWith('data: ')); - assert.equal(dataLines[dataLines.length - 1], 'data: [DONE]', `${marker}: stream must end with [DONE]`); - const events = dataLines.slice(0, -1).map(l => JSON.parse(l.slice('data: '.length))); - const errorEvent = events.find(e => e.error); - assert.ok(errorEvent, `${marker}: stream must carry an error event, got: ${JSON.stringify(sse)}`); - assert.match(errorEvent.error.message, detail, `${marker}: stream detail must name the cause, got: ${errorEvent.error.message}`); - assert.doesNotMatch(errorEvent.error.message, /code (null|0)\b/); - } -}; - -test('empty-stderr fallback names the terminal state (#674)', async (t) => { - await assertEmptyStderrFallback(t, 'FAILSTATE', /Muse execution failed: muse run terminated with state 'failed'/); -}); - -test('empty-stderr fallback names the killing signal, not code null (#674)', async (t) => { - await assertEmptyStderrFallback(t, 'SIGKILLME', /Muse execution failed: muse exec terminated by signal SIGKILL/); -}); - -test('divergent terminal text: non-stream uses it, stream keeps the deltas already sent', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please DIVERGE now' }]; - - const plain = JSON.parse(await chat(port, { messages })); - assert.equal(plain.choices[0].message.content, 'xyz-longer'); - - const { content, finish } = streamedContent(await chat(port, { messages, stream: true })); - assert.equal(content, 'abc'); - assert.equal(finish, 'stop'); -}); - -test('warm serve path: second turn sends only the new user message (#480)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); - t.after(stop); - - const turn1 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [{ role: 'user', content: 'alpha one' }] - })); - assert.equal(turn1.choices[0].message.content, 'RE:alpha one'); - assert.equal(turn1.usage.prompt_tokens, 42, 'usage must come from the MSP tokenUsage notification'); - assert.equal(turn1.usage.prompt_tokens_details.cached_tokens, 40, 'MSP cacheReadTokens must surface as prompt_tokens_details.cached_tokens (opencode #394)'); - - const turn2 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [ - { role: 'user', content: 'alpha one' }, - { role: 'assistant', content: 'RE:alpha one' }, - { role: 'user', content: 'beta two' } - ] - })); - assert.equal(turn2.choices[0].message.content, 'RE:beta two'); - - const log = fs.readFileSync(logFile, 'utf-8').trim().split('\n'); - assert.equal(log.filter(l => l.startsWith('START')).length, 1, 'one MSP session for the whole conversation'); - const turns = log.filter(l => l.startsWith('TURN')); - assert.equal(turns.length, 2); - assert.equal(turns[0], 'TURN alpha one'); - assert.equal(turns[1], 'TURN beta two', 'turn 2 must send only the new message, not the re-flattened history'); -}); - -test('warm serve path: streaming turn streams the MSP deltas (#480)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_WARM: '1' }); - t.after(stop); - const { content, finish } = streamedContent(await chat(port, { - messages: [{ role: 'user', content: 'alpha one' }], - stream: true - })); - assert.equal(content, 'RE:alpha one'); - assert.equal(finish, 'stop'); -}); - -test('two concurrent conversations stay isolated: separate sessions, tail-only turns (#480)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); - t.after(stop); - const convA = [{ role: 'user', content: 'alpha one' }]; - const convB = [{ role: 'user', content: 'gamma one' }]; - const [a1, b1] = await Promise.all([ - chat(port, { model: 'muse-spark-1.3', messages: convA }).then(r => JSON.parse(r)), - chat(port, { model: 'muse-spark-1.3', messages: convB }).then(r => JSON.parse(r)) - ]); - assert.equal(a1.choices[0].message.content, 'RE:alpha one'); - assert.equal(b1.choices[0].message.content, 'RE:gamma one'); - const a2 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [...convA, { role: 'assistant', content: 'RE:alpha one' }, { role: 'user', content: 'alpha two' }] - })); - const b2 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [...convB, { role: 'assistant', content: 'RE:gamma one' }, { role: 'user', content: 'gamma two' }] - })); - assert.equal(a2.choices[0].message.content, 'RE:alpha two'); - assert.equal(b2.choices[0].message.content, 'RE:gamma two'); - const log = fs.readFileSync(logFile, 'utf-8').trim().split('\n'); - assert.equal(log.filter(l => l.startsWith('START')).length, 2, 'each conversation key must own a separate MSP session'); - const turns = log.filter(l => l.startsWith('TURN')).map(l => l.slice(5)).sort(); - assert.deepEqual(turns, ['alpha one', 'alpha two', 'gamma one', 'gamma two'], 'every turn after the first must send only its own conversation\'s new tail — no cross-conversation history'); -}); - -test('warm host killed mid-turn degrades to a successful cold exec request (#480)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); - t.after(stop); - const turn1 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [{ role: 'user', content: 'alpha one' }] - })); - assert.equal(turn1.choices[0].message.content, 'RE:alpha one', 'turn 1 must be served warm'); - // Turn 2's new message kills the warm serve host mid-turn (before any - // delta is committed); the request must degrade to the cold exec path - // and still answer, not surface a client-visible error (#480 spike - // criterion 4). - const turn2 = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [ - { role: 'user', content: 'alpha one' }, - { role: 'assistant', content: 'RE:alpha one' }, - { role: 'user', content: 'KILLHOST now' } - ] - })); - assert.equal(turn2.choices[0].message.content, 'Hello world', 'exec stub answer proves the cold fallback ran after the warm host died'); - const log = fs.readFileSync(logFile, 'utf-8'); - assert.match(log, /KILLED KILLHOST now/, 'the warm host must actually have been killed mid-turn'); -}); - -test('warm serve failure falls back to the exec path (#480)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_WARM: '1', STUB_SERVE_FAIL: '1' }); - 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 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'); -}); - -// --- 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 === 'attest') { - res.writeHead(403, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { code: 'client_attestation_denied', message: 'This API key is billed to a Muse Code subscription. Muse Code subscriptions cover requests from the Muse Code client only.', type: 'permission_error' } })); - return; - } - 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; - } - if (mode === 'failed-empty' || mode === 'failed-partial') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: 'resp_failed', - object: 'response', - status: 'failed', - error: { message: 'stub upstream boom', type: 'server_error' }, - output: mode === 'failed-partial' - ? [{ type: 'message', id: 'msg_p', role: 'assistant', content: [{ type: 'output_text', text: 'partial text that must not mask the failure' }] }] - : [] - })); - return; - } - if (mode === 'incomplete-filter' || mode === 'incomplete-max') { - const reason = mode === 'incomplete-max' ? 'max_output_tokens' : 'content_filter'; - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: 'resp_incomplete', - object: 'response', - status: 'incomplete', - incomplete_details: { reason }, - output: [{ type: 'message', id: 'msg_i', role: 'assistant', content: [{ type: 'output_text', text: 'cut off but usable' }] }] - })); - return; - } - let parsed = {}; - try { parsed = JSON.parse(body || '{}'); } catch { /* keep empty */ } - if (parsed.stream) { - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - res.end(mode === 'shell' ? RESPONSES_SSE_FIXTURE.replaceAll('get_weather', 'run_command') : RESPONSES_SSE_FIXTURE); - return; - } - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(mode === 'shell' - ? JSON.stringify(RESPONSES_FIXTURE).replaceAll('get_weather', 'run_command') - : 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: failed/incomplete upstream bodies are 500 errors, never a 200 stop (#2780)', async (t) => { - const postChat = (port) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'muse-spark-1.3', messages: [{ role: 'user', content: 'hi' }] }) - }); - for (const [mode, match] of [ - ['failed-empty', /stub upstream boom/], - ['failed-partial', /stub upstream boom/], - ['incomplete-filter', /incomplete: content_filter/], - ]) { - const meta = await startMetaStub(mode); - const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); - try { - writeStubAuth(home); - const plainRes = await postChat(port); - assert.equal(plainRes.status, 500, `${mode}: non-stream must be a 500, not a 200 'stop'`); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.error.message, match, `${mode}: error must carry the upstream cause`); - assert.ok(!('choices' in plainBody), `${mode}: no masked completion may be present`); - } finally { - stop(); - meta.close(); - } - } - - const meta = await startMetaStub('incomplete-max'); - t.after(() => meta.close()); - const { port, stop, home } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); - t.after(stop); - writeStubAuth(home); - const maxRes = await postChat(port); - assert.equal(maxRes.status, 200, 'incomplete/max_output_tokens stays a 200'); - const maxBody = JSON.parse(await maxRes.text()); - assert.equal(maxBody.choices[0].finish_reason, 'length'); - assert.equal(maxBody.choices[0].message.content, 'cut off but usable'); -}); - -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: the shell tool is aliased upstream and its calls translate 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 plain = JSON.parse(await chat(port, { - messages: [ - { role: 'user', content: 'run echo hi' }, - { role: 'assistant', content: null, tool_calls: [{ id: 'call_0', type: 'function', function: { name: 'shell', arguments: '{"command":"echo hi"}' } }] }, - { role: 'tool', tool_call_id: 'call_0', content: 'hi' }, - { role: 'user', content: 'what did it print?' } - ], - tools: [{ type: 'function', function: { name: 'shell', description: 'Run a shell command', parameters: { type: 'object', properties: { command: { type: 'string' } } } } }] - })); - const upstream = JSON.parse(meta.requests.filter(r => r.url === '/v1/responses')[0].body); - assert.deepEqual(upstream.tools.map(x => x.name), ['run_command'], 'the shell tool is presented upstream under its alias'); - const historyCall = upstream.input.find(i => i.type === 'function_call'); - assert.equal(historyCall.name, 'run_command', 'history tool calls are aliased too'); - assert.equal(plain.choices[0].message.tool_calls[0].function.name, 'shell', 'the model call is translated back to the client name'); -}); - -test('direct mode: an attestation denial falls back to the CLI door', async (t) => { - const meta = await startMetaStub('attest'); - t.after(() => meta.close()); - const { port, stop, home, logFile } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url }); - 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 fallback ran'); - const stubLog = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8') : ''; - assert.ok(stubLog.includes('--prompt-file'), 'the CLI door took over after the denial'); -}); - -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: /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 ' }, - 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 ' }, - 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()); - 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); -}); - -test('direct mode: contributor ids reach upstream verbatim, effort suffix parses after contributor (#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 wonder = JSON.parse(await chat(port, { - model: 'muse-wonder-1.0-contributor-high', - messages: [{ role: 'user', content: 'hi' }] - })); - assert.equal(wonder.model, 'muse-wonder-1.0-contributor-high'); - - const spark = JSON.parse(await chat(port, { - model: 'muse-spark-1.3-contributor', - messages: [{ role: 'user', content: 'hi' }] - })); - assert.equal(spark.model, 'muse-spark-1.3-contributor-high', 'no explicit effort means the default effort, contributor intact'); - - const plainBase = JSON.parse(await chat(port, { - model: 'muse-spark-1.3', - messages: [{ role: 'user', content: 'hi' }] - })); - assert.equal(plainBase.model, 'muse-spark-1.3-high', 'a plain request is NOT rewritten to contributor'); - - const sent = meta.requests.filter(r => r.url === '/v1/responses').map(r => JSON.parse(r.body)); - assert.equal(sent.length, 3); - assert.equal(sent[0].model, 'muse-wonder-1.0-contributor', 'contributor id goes upstream verbatim'); - assert.deepEqual(sent[0].reasoning, { effort: 'high' }, 'the effort suffix after -contributor is the effort'); - assert.equal(sent[1].model, 'muse-spark-1.3-contributor'); - assert.deepEqual(sent[1].reasoning, { effort: 'high' }); - assert.equal(sent[2].model, 'muse-spark-1.3', 'plain base model stays plain upstream'); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); - -test('warm chain map self-deletes settled entries; same-key turns stay ordered (#2407)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); - t.after(stop); - const chainsNow = async () => (await (await fetch('http://127.0.0.1:' + port + '/health')).json()).warm.chains; - const waitChainsEmpty = async () => { - const deadline = Date.now() + 5000; - for (;;) { - const n = await chainsNow(); - if (n === 0) return; - if (Date.now() > deadline) assert.fail('warmChains map must be empty after settle, got ' + n); - await new Promise(r => setTimeout(r, 50)); - } - }; - - // Two distinct conversation keys through enqueueWarm. - for (const first of ['leak alpha', 'leak gamma']) { - const res = JSON.parse(await chat(port, { model: 'muse-spark-1.3', messages: [{ role: 'user', content: first }] })); - assert.equal(res.choices[0].message.content, 'RE:' + first); - } - await waitChainsEmpty(); - - // Same key: turn 2 enqueued while turn 1 is in flight runs after it, on - // the same single MSP session, in order. - const p1 = chat(port, { model: 'muse-spark-1.3', messages: [{ role: 'user', content: 'order one' }] }); - await new Promise(r => setTimeout(r, 50)); - const p2 = chat(port, { - model: 'muse-spark-1.3', - messages: [ - { role: 'user', content: 'order one' }, - { role: 'assistant', content: 'RE:order one' }, - { role: 'user', content: 'order two' } - ] - }); - const [t1, t2] = await Promise.all([p1.then(r => JSON.parse(r)), p2.then(r => JSON.parse(r))]); - assert.equal(t1.choices[0].message.content, 'RE:order one'); - assert.equal(t2.choices[0].message.content, 'RE:order two'); - const log = fs.readFileSync(logFile, 'utf-8').trim().split('\n'); - const turns = log.filter(l => l.startsWith('TURN')).map(l => l.slice(5)); - assert.deepEqual(turns.slice(-2), ['order one', 'order two'], 'same-key turns must run in enqueue order'); - await waitChainsEmpty(); -}); - -// --------------------------------------------------------------------------- -// Exec-fallback turn deadline (#2159): a hung muse exec child must be -// killed (SIGTERM, then SIGKILL after the grace), the request must -// settle with the existing error shape, and the timeout must never be -// reported as a silent successful stop. -// --------------------------------------------------------------------------- - -const postChat = (port, body, signal) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - signal -}); - -const waitForCondition = async (fn, timeoutMs = 10000) => { - const deadline = Date.now() + timeoutMs; - for (;;) { - const v = fn(); - if (v) return v; - if (Date.now() > deadline) throw new Error('waitForCondition timed out'); - await new Promise(r => setTimeout(r, 50)); - } -}; - -const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }; - -const stubExecPid = (logFile) => { - try { - const m = fs.readFileSync(logFile, 'utf-8').match(/EXECPID (\d+)/); - return m ? Number(m[1]) : null; - } catch { return null; } -}; - -const stubPromptFile = (logFile) => { - const m = fs.readFileSync(logFile, 'utf-8').match(/--prompt-file (\S+)/); - return m ? m[1] : null; -}; - -test('exec deadline: never-exiting child is killed, request 500s with the timeout, prompt file removed (#2159)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); - t.after(stop); - const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }] }); - assert.equal(res.status, 500); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /muse exec turn timed out after 300ms/); - const pid = stubExecPid(logFile); - assert.ok(pid, 'stub exec pid recorded'); - await waitForCondition(() => !pidAlive(pid)); - const promptFile = stubPromptFile(logFile); - assert.ok(promptFile, 'prompt file path recorded in stub argv log'); - assert.equal(fs.existsSync(promptFile), false, 'prompt file must be unlinked on the deadline path'); -}); - -test('exec deadline: request settles at deadline+grace even when a descendant holds the stdio pipes (#2159)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); - t.after(stop); - const started = Date.now(); - let res = null; - try { - res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGDESCENDANT now' }] }, AbortSignal.timeout(20000)); - } catch { /* aborted: settlement was not bounded */ } - assert.ok(res, 'request must settle at deadline + kill grace, not when the descendant exits'); - assert.equal(res.status, 500); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /muse exec turn timed out after 300ms/); - assert.ok(Date.now() - started < 15000, 'settlement must be bounded independently of the descendant lifetime'); - const pid = stubExecPid(logFile); - assert.ok(pid, 'stub exec pid recorded'); - await waitForCondition(() => !pidAlive(pid)); - const promptFile = stubPromptFile(logFile); - assert.ok(promptFile, 'prompt file path recorded in stub argv log'); - assert.equal(fs.existsSync(promptFile), false, 'prompt file must be unlinked on the independent settle path'); - const dm = fs.readFileSync(logFile, 'utf-8').match(/DESCPID (\d+)/); - assert.ok(dm, 'descendant pid recorded'); - try { process.kill(Number(dm[1]), 'SIGKILL'); } catch { /* already gone */ } -}); - -test('exec deadline: streaming request gets an SSE-framed timeout error + [DONE] (#2159)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); - t.after(stop); - const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }], stream: true }); - assert.equal(res.status, 200); - const sse = await res.text(); - assert.match(sse, /muse exec turn timed out after 300ms/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]'), `stream must end with [DONE], got: ${JSON.stringify(sse)}`); -}); - -test('exec deadline: SIGTERM-ignoring child is SIGKILLed after the grace (#2159)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); - t.after(stop); - const started = Date.now(); - const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGTERMI now' }] }); - assert.equal(res.status, 500); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /muse exec turn timed out after 300ms/); - assert.ok(Date.now() - started >= 3000, 'SIGKILL escalation must wait the 3000ms grace'); - const pid = stubExecPid(logFile); - assert.ok(pid && !pidAlive(pid), 'SIGTERM-ignoring child must be dead after the grace'); -}); - -test('exec deadline: completed-then-hangs child is a timeout failure, not a stop (#2159)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); - t.after(stop); - const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGAFTERDONE now' }] }); - assert.equal(res.status, 500, 'a completed terminal event must not mask the deadline'); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /muse exec turn timed out after 300ms/); -}); - -test('exec deadline: a normal child inside the deadline is unaffected (#2159)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '5000' }); - t.after(stop); - const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); - assert.equal(plain.choices[0].message.content, 'Hello world'); -}); - -test('exec deadline: an override above Node timer limit falls back to the default, not a ~1ms timeout (#2159)', async (t) => { - const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '2147483648' }); - t.after(stop); - const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); - assert.equal(plain.choices[0].message.content, 'Hello world'); -}); - -test('exec disconnect: client disconnect kills the child via the shared helper (#2159)', async (t) => { - const { port, stop, logFile } = await startProxy(); - t.after(stop); - const ac = new AbortController(); - const pending = postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }] }, ac.signal) - .catch(() => null); - const pid = await waitForCondition(() => stubExecPid(logFile)); - assert.ok(pidAlive(pid), 'child runs while the request is open'); - ac.abort(); - await pending; - await waitForCondition(() => !pidAlive(pid)); -}); - -// --------------------------------------------------------------------------- -// Tools doctrine (code#6117, opencode#1708): a tools-carrying chat request -// must never silently degrade to the warm/exec vendor-CLI fallback — those -// paths flatten the conversation to a prompt, run the Muse CLI with its -// OWN tools, and return only final text. Such requests are direct-or-error. -// --------------------------------------------------------------------------- - -const TOOLS_BODY = { - messages: [{ role: 'user', content: 'weather in Osseo?' }], - tools: [{ type: 'function', function: { name: 'get_weather', description: 'Get weather', parameters: { type: 'object', properties: { city: { type: 'string' } } } } }] -}; - -const postChatRaw = async (port, body) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) -}); - -const stubLogText = (logFile) => (fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8') : ''); - -test('tools gate: tools-carrying request with no direct credential is a loud 502, never the CLI fallback (code#6117)', async (t) => { - const meta = await startMetaStub('chat'); - t.after(() => meta.close()); - // Warm deliberately enabled: the gate must skip warm AND exec. - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_META_API_BASE: meta.url, MUSE_PROXY_WARM: '1' }); - t.after(stop); - - const res = await postChatRaw(port, TOOLS_BODY); - assert.equal(res.status, 502, 'a tools-carrying request must not be answered by the vendor CLI'); - const body = JSON.parse(await res.text()); - assert.equal(body.error.code, 'tools_fallback_ineligible'); - assert.match(body.error.message, /client tools/); - assert.match(body.error.message, /fallback is ineligible/); - const stubLog = stubLogText(logFile); - assert.ok(!stubLog.includes('--prompt-file'), 'no muse exec invocation for a tools-carrying request'); - assert.ok(!stubLog.includes('START'), 'no muse serve session started for a tools-carrying request'); - assert.equal(meta.requests.length, 0, 'no credential means no exchange attempt'); -}); - -test('tools gate: tools-carrying request with direct disabled (MUSE_PROXY_DIRECT=0) is a loud 502 (code#6117)', async (t) => { - const { port, stop, logFile } = await startProxy({ MUSE_PROXY_DIRECT: '0' }); - t.after(stop); - - const res = await postChatRaw(port, TOOLS_BODY); - assert.equal(res.status, 502); - const body = JSON.parse(await res.text()); - assert.equal(body.error.code, 'tools_fallback_ineligible'); - assert.ok(!stubLogText(logFile).includes('--prompt-file'), 'exec never runs for a tools-carrying request'); -}); - -test('tools gate: an attestation denial on a tools-carrying request is a loud 502, not a CLI-door fallback (code#6117)', async (t) => { - const meta = await startMetaStub('attest'); - 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 postChatRaw(port, TOOLS_BODY); - assert.equal(res.status, 502, 'attestation denial must not reroute a tools-carrying request to the CLI door'); - const body = JSON.parse(await res.text()); - assert.equal(body.error.code, 'tools_fallback_ineligible'); - assert.ok(!stubLogText(logFile).includes('--prompt-file'), 'the CLI door never took over'); -}); - -test('tools gate: history-only tool loop (tool_calls + tool result, no tools array) is also gated (code#6117)', async (t) => { - const { port, stop, logFile } = await startProxy(); - t.after(stop); - - const res = await postChatRaw(port, { - messages: [ - { 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: 'and tomorrow?' } - ] - }); - assert.equal(res.status, 502); - const body = JSON.parse(await res.text()); - assert.equal(body.error.code, 'tools_fallback_ineligible'); - assert.ok(!stubLogText(logFile).includes('--prompt-file'), 'exec never runs mid-tool-loop'); -}); - -test('tools gate: direct mode still serves a tools-carrying request with real tool calls (code#6117)', 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 res = await postChatRaw(port, TOOLS_BODY); - assert.equal(res.status, 200); - assert.equal(res.headers.get('x-muse-proxy-path'), 'direct', 'the serving path is surfaced'); - const plain = JSON.parse(await res.text()); - assert.deepEqual(plain.choices[0].message.tool_calls, [{ - id: 'call_123', - type: 'function', - function: { name: 'get_weather', arguments: '{"city":"Osseo"}' } - }], 'the direct path returns real client tool calls'); - assert.equal(plain.choices[0].finish_reason, 'tool_calls'); -}); - -test('tools gate: text-only requests keep the exec fallback and surface the serving path (code#6117)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - - const res = await postChatRaw(port, { messages: [{ role: 'user', content: 'hi' }] }); - assert.equal(res.status, 200); - assert.equal(res.headers.get('x-muse-proxy-path'), 'exec'); - const plain = JSON.parse(await res.text()); - assert.equal(plain.choices[0].message.content, 'Hello world', 'exec stub answer proves the CLI fallback still serves text-only requests'); -}); - -test('tools gate: /v1/responses with tools and no direct credential is a loud 404 and never touches the CLI (code#6117)', async (t) => { - const { port, stop, logFile } = await startProxy(); - t.after(stop); - - 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: [{ role: 'user', content: 'hi' }], - tools: [{ type: 'function', name: 'get_weather', parameters: { type: 'object' } }] - }) - }); - assert.equal(res.status, 404, 'the Responses route is direct-only: no credential, no route, no fallback'); - assert.ok(!stubLogText(logFile).includes('--prompt-file'), 'exec never runs for a Responses tools request'); -}); diff --git a/bin/openchamber-start.sh b/bin/openchamber-start.sh index 7a1fdee5f9..97fe95b8c1 100755 --- a/bin/openchamber-start.sh +++ b/bin/openchamber-start.sh @@ -1,6 +1,6 @@ #!/bin/bash # Laptop start wrapper for OpenChamber (fleet pattern, mirrors -# bin/muse-proxy-start.sh). The home-manager unit does not exec +# the retired bin/muse-proxy-start.sh). The home-manager unit does not exec # the serve script directly; it execs this wrapper with the serve # script's store path as $1 (openchamberUnitStart in # home/common/default.nix). diff --git a/bin/proxy-port.test.mjs b/bin/proxy-port.test.mjs index 243fd4ffb6..4ce4a24451 100644 --- a/bin/proxy-port.test.mjs +++ b/bin/proxy-port.test.mjs @@ -243,10 +243,12 @@ test('every proxy port parse site in the surviving proxies uses the shared helpe // design-code-proxy — retired 2026-10-30/2026-11-03, their bins kept // as history until then — plus claude-code-proxy, // commandcode-proxy and codex-proxy) left this list with their bin programs in the - // 2026-11-06 proxy-infra decommission. - const expected = { - 'muse-proxy.mjs': ['MUSE_PROXY_PORT'] - }; + // 2026-11-06 proxy-infra decommission, and muse-proxy — the last + // provider proxy — left it the same day when muse-direct went + // native in the fork (opencode#1825). The list is empty: no + // provider proxy remains. proxy-supervise and proxy-relay still + // use the shared helper but take no per-proxy port variable. + const expected = {}; for (const [file, names] of Object.entries(expected)) { const source = fs.readFileSync(path.join(binDir, file), 'utf8'); assert.match( diff --git a/flake.lock b/flake.lock index 0417372883..3d02f912f4 100644 --- a/flake.lock +++ b/flake.lock @@ -2248,11 +2248,11 @@ ] }, "locked": { - "lastModified": 1793974935, - "narHash": "sha256-DVCWIAOxTgz2YuQNXZshoQnBA8ESR036ECv173J9Hk0=", + "lastModified": 1793990700, + "narHash": "sha256-VcsjUVmuVhgErWqfhtt6n4mMCpRSwTtagKRab1POEUg=", "owner": "developing-today-forks", "repo": "opencode", - "rev": "5e9b135ffc8c0d7ba35d2a2d42d351a49553bdfa", + "rev": "f4514086e5f602823d7aa6c583450f81b69594c7", "type": "github" }, "original": { diff --git a/home/common/default.nix b/home/common/default.nix index a75d134085..dd49c7577e 100644 --- a/home/common/default.nix +++ b/home/common/default.nix @@ -22,7 +22,11 @@ let # Codex CLI bridge, so the proxy had no consumers left; its let, # units, session variable, bin program, launcher and guard row # were removed in one change. The port is free. - museProxyPort = 18747; + # museProxyPort (18747) retired 2026-11-06 (Drew, muse-direct + # order): the fork's native muse-direct provider replaced the + # proxy, so it had no consumers left; its let, unit, session + # variable, bin program, launcher and guard row were removed in + # one change. The port is free. # commandcodeProxyPort (18748) and claudeCodeProxyPort (18749) # retired 2026-11-06 (Drew, proxy-infra decommission): both # providers were repointed to the fork's native wire-emulation @@ -762,13 +766,13 @@ in # reproduced: a switch that changes a unit's ExecStart restarts that # proxy, per the normal flake service pattern (cf. mcpx/openchamber). - # CLI proxy workroot (muse): the muse unit below points its - # MUSE_PROXY_WORKDIR override at ~/.local/state/cli-proxies/muse, - # so runtime session state lives outside the checkout (the script's + # CLI proxy workroot: the retired proxy units pointed their + # workdir overrides at ~/.local/state/cli-proxies/, so + # runtime session state lived outside the checkout (the scripts' # default, bin/work inside ~/code, dirtied the primary checkout - # with every session and blocked pm-git-sync). The commandcode and - # claude-code units that shared the cli-proxies root (#2785, #3067) - # are retired below; their state subtrees are left in place. + # with every session and blocked pm-git-sync). All three units + # that shared the cli-proxies root (#2785, #3067) are retired + # below; their state subtrees are left in place. # # Command Code proxy retired 2026-11-06 (Drew, proxy-infra # decommission): its unit definition stood here. The provider was @@ -786,42 +790,14 @@ in # unit, session variable, bin/claude-code-proxy.mjs and its test # were removed in the same change. The port is free. - # Muse (Meta) proxy (#2104): also previously supervisor-config only. - # Runs the checkout start script, the supervisor's exact invocation; - # the script owns its environment (including keeping META_API_KEY out). - # Enrolled here so retiring the supervisor does not strand :18747 -- - # the redesign leaves exactly one owner for every proxy port. - # - # Direct mode (#2753, 2026-10-30): bin/muse-proxy.mjs defaults to - # exchanging the Muse CLI account token for the plan's minted key - # and serving the OpenCode muse-direct provider (declared in - # .opencode/opencode.jsonc, the sole enabled Meta door) over the - # Responses API; the CLI harness remains only as a fallback. The - # credential is read at runtime from ~/.config/muse/auth.json -- - # it is never part of this config. Direct mode changes nothing - # about this unit: same port, same start script, same env contract. - systemd.user.services.muse-proxy = { - Unit = { - Description = "Muse (Meta) Local Proxy Bridge for OpenCode"; - After = [ "network-online.target" ]; - Wants = [ "network-online.target" ]; - }; - Service = { - ExecStart = toString ( - pkgs.writeShellScript "muse-proxy-start-unit" '' - exec /run/current-system/sw/bin/bash "$HOME/code/bin/muse-proxy-start.sh" - '' - ); - Restart = "always"; - RestartSec = 3; - Environment = [ - "MUSE_PROXY_PORT=${toString museProxyPort}" - "MUSE_PROXY_HOST=127.0.0.1" - "MUSE_PROXY_WORKDIR=%h/.local/state/cli-proxies/muse" - ]; - }; - Install.WantedBy = [ "default.target" ]; - }; + # Muse (Meta) proxy retired 2026-11-06 (Drew, muse-direct order): + # its unit definition stood here. The provider was rebuilt as a + # native fork provider (@opencode/ai/providers/muse-direct, + # opencode PR #1872) speaking the Meta Responses wire in-process — + # the same /muse-code/key minted-key exchange the proxy's direct + # mode performed, with no hop — and the proxy's let, unit, session + # variable, bin/muse-proxy.mjs, its start script and its test + # were removed in the same change. The port is free. # Route proxy retired 2026-11-04 (opencode#1153): the door's # only live consumer, OpenClaw's opencode-route provider, was @@ -1625,16 +1601,10 @@ in OPENCODE_EXPERIMENTAL_OXFMT = "1"; OPENCODE_EXPERIMENTAL_EXA = "1"; OPENCODE_EXPERIMENTAL_EVENT_SYSTEM = "1"; - # Single source for the local proxy ports (see the let block): - # opencode.jsonc reads them via {env:...} substitution. - # MUSE_PROXY_PORT below was one of three missing session - # variables whose {env:...} templates in opencode.jsonc - # resolved to an empty port in the OpenChamber serve - # (2026-10-25 audit) because the variables never reached its - # environment; the other two (commandcode, claude-code) were - # removed with their retired proxies on 2026-11-06. The session - # list must cover every let-block port. - MUSE_PROXY_PORT = toString museProxyPort; + # Proxy-port session variables stood here: the last of them + # (MUSE_PROXY_PORT) was removed with the muse proxy's + # retirement on 2026-11-06. Every provider proxy is gone, and + # no {env:...} templates remain in opencode.jsonc. OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT = "1"; # File watcher off by default (Drew, 2026-10-20): the working trees # are giant, and watching costs more than the live-external-edit diff --git a/home/openclaw/default.nix b/home/openclaw/default.nix index 0923a5da2e..8eba3e4d5d 100644 --- a/home/openclaw/default.nix +++ b/home/openclaw/default.nix @@ -23,10 +23,10 @@ # store) and is read at service start. let homeDir = "/home/user"; - # Local provider-proxy ports. The canonical definitions live in - # home/common/default.nix (museProxyPort); these are - # the same numbers, repeated here because OpenClaw's config is rendered - # as data, not shell env. Keep in sync with home/common. + # Local service ports, repeated here because OpenClaw's config is + # rendered as data, not shell env. (The provider-proxy ports that + # once had to stay in sync with home/common/default.nix are all + # retired — the last, museProxyPort 18747, on 2026-11-06.) # The opencode-route provider talks to the OpenCode server facade # directly (127.0.0.1:13420/v1) since the route proxy's retirement # (opencode#1153, 2026-11-04); the proxy's port (18750) is free. @@ -330,7 +330,7 @@ in # Laptop operations - Everything is a systemd **user** service (linger on): `systemctl --user status|restart `, logs via `journalctl --user -u `. - - Provider proxy on loopback: muse 18747 (the codex, clef, agy, antigravity-ls, design-code, commandcode and claude-code doors are all retired — codex, commandcode and claude-code in the 2026-11-06 proxy-infra decommission); the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). + - No provider proxies remain on loopback: the last one, muse 18747, retired 2026-11-06 when muse-direct went native in the fork (the codex, clef, agy, antigravity-ls, design-code, commandcode and claude-code doors retired earlier — codex, commandcode and claude-code in the 2026-11-06 proxy-infra decommission); the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). - OpenChamber's managed OpenCode port is dynamic — read `~/.config/openchamber/managed-opencode/state.json`, never hardcode it. - Secrets are referenced by name only (Bitwarden Secrets Manager; sops files under /run/secrets/agent-auth/). Never print or commit a secret value. diff --git a/home/openclaw/workspace/QUOTAS.md b/home/openclaw/workspace/QUOTAS.md index 39e08adc58..f862ad4419 100644 --- a/home/openclaw/workspace/QUOTAS.md +++ b/home/openclaw/workspace/QUOTAS.md @@ -6,5 +6,5 @@ Drew's rule, verbatim in spirit: **"Use the plans. Measure the quotas."** 2. **Burn by expiry.** Prefer the pool whose window expires soonest. **OpenAI is the final reserve** — do not drain it while other pools have capacity. (This gateway's default is the opencode-route workhorse pool via the OpenCode server facade; the CommandCode-plan and Design-plan proxies it once fronted directly are retired — Design on 2026-11-03, CommandCode in the 2026-11-06 proxy-infra decommission — and the Codex/OpenAI proxy is registered but _not_ in the fallback chain.) 3. **Measure before and during.** Before starting heavy work on a pool, check its quota if a checker exists (OpenChamber's quota view / the provider registry in the keep-the-four-repos-healthy goal files). Pools are used all the way to 100% (the old ~85% caution zone is retired, Drew 2026-10-27). At a known 100% the pool is closed — no new work, no continued calls — until its reset time, or until a fresh check shows it has dropped below 100% (some providers reset early). 4. **Model + effort is one decision, per task.** Defaults: DeepSeek Flash (high effort) for routine work; Haiku/Sonnet-class for standard Claude work; Luna-class at max effort for cheap OpenAI-side work; flagship models (Sol/Opus-class) right-sized at medium, only for genuinely hard problems. Never leave model or effort at "default" by accident. -5. **One Meta pool, one door.** The Meta High Usage plan is reached through the fleet's `meta` provider route (muse-proxy, :18747). It is a plan pool like the others — not "Muse's subscription" (that's Drew's separate assistant product and not a pool at all). This gateway does not use it by default; OpenCode sessions route to it under their own discipline. +5. **One Meta pool, one door.** The Meta High Usage plan is reached through OpenCode's native muse-direct provider (in-process Meta wire since 2026-11-06; muse-proxy is retired, and the `meta` provider id is the separate PAYG door). It is a plan pool like the others — not "Muse's subscription" (that's Drew's separate assistant product and not a pool at all). This gateway does not use it by default; OpenCode sessions route to it under their own discipline. 6. **Cloudflare gateway:** at most one unimportant session at a time. Not a routine route. diff --git a/home/openclaw/workspace/TOOLS.md b/home/openclaw/workspace/TOOLS.md index ee31a9228b..007a2bf1e2 100644 --- a/home/openclaw/workspace/TOOLS.md +++ b/home/openclaw/workspace/TOOLS.md @@ -9,7 +9,6 @@ This file is managed by Nix (source: `home/openclaw/` in the developing-today/co | `openclaw-gateway` | This gateway | tailnet, port 18789 (Control UI + WebChat) | | `openchamber` | OpenChamber server (GUI over OpenCode) | 127.0.0.1:3000, socket-activated | | `mcpx` | Standing MCP gateway daemon | config `~/.config/mcpx/config.json` | -| `muse-proxy` | Meta High Usage plan proxy | 127.0.0.1:18747 | - Check one: `systemctl --user status ` · logs: `journalctl --user -u -f` - OpenCode (the engine under OpenChamber) keeps its live managed-server port in `~/.config/openchamber/managed-opencode/state.json` — it changes on restart; never hardcode it. diff --git a/pm-stack/PORTS.md b/pm-stack/PORTS.md index 81181e26d9..b58d9664da 100644 --- a/pm-stack/PORTS.md +++ b/pm-stack/PORTS.md @@ -89,7 +89,7 @@ pattern at its atlas-search block). | 18744 | codex-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free (tailscale serve forward removed at kill) | | 18745 | antigravity-ls-proxy | loopback | retired 2026-10-30 | retired — **stale `tailscale serve` forward still present** | | 18746 | design-code-proxy | loopback | retired 2026-11-03 (`home/common/default.nix` comment block) | retired — **stale `tailscale serve` forward still present** | -| 18747 | muse-proxy | loopback | `home/common/default.nix:21` (`museProxyPort`) | live | +| 18747 | muse-proxy | loopback | retired 2026-11-06 (native muse-direct provider, opencode#1825) | retired — free | | 18748 | commandcode-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free | | 18749 | claude-code-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free | | 18750 | opencode-route-proxy | loopback | retired 2026-11-04 | retired — free |