From c55b2bcddd5af527a1d53027225a3138a363dd0a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 12:48:10 -0500 Subject: [PATCH 1/3] feat(antigravity): agy-proxy serves through resident warm stream-json workers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the spawn-per-request -p path with resident agy processes speaking --input-format stream-json / --output-format stream-json: session requests own a dedicated worker (delta turns, --conversation resume, same pid across turns); stateless requests claim a pre-warmed spare for one fresh turn and retire it while a replacement warms. Dead/errored/timed-out workers are killed and never reused. #678 failure semantics (502 / SSE error, never a stop carrying partial output; failed resume retries once fresh) and the #1692 unknown-model 400 are preserved. Model list reconciled against `agy models` (agy 1.2.16, proxy service context, 2026-10-28): exactly 13 ids over 5 bases (gemini-4-argon, gemini-3.8-flash, claude-sonnet-5-5, claude-opus-5-5, gpt-oss-120b). Drops gemini-3.7-flash, gemini-3.6-flash and gemini-3.1-pro, which the proxy advertised but agy does not list and rejects. Tests: node --test bin/agy-proxy.test.mjs — 8/8 (stub agy rewritten to the stream-json stdin protocol; adds resident-worker pid-reuse, pre-warmed spare, and reconciled model list coverage). --- bin/agy-proxy.mjs | 799 +++++++++++++++++++++++++++-------------- bin/agy-proxy.test.mjs | 144 ++++++-- 2 files changed, 640 insertions(+), 303 deletions(-) diff --git a/bin/agy-proxy.mjs b/bin/agy-proxy.mjs index f026282e7e..b59e2ac4f4 100755 --- a/bin/agy-proxy.mjs +++ b/bin/agy-proxy.mjs @@ -1,4 +1,33 @@ #!/usr/bin/env node +// agy-proxy — OpenAI-compatible bridge to the Antigravity CLI (`agy`). +// +// Serving path (2026-10-28): RESIDENT warm `agy` processes speaking +// `--input-format stream-json` / `--output-format stream-json` (agy's +// documented warm shape: one process holds one continuous conversation, +// one NDJSON `{"event":"user",...}` line per turn, one `result` event +// per turn). This replaces the previous spawn-per-request `-p` path, +// where every request paid full CLI + language-server startup. +// +// Worker lifecycle: +// - Session requests (explicit id / `user:` / first-message hash, see +// getSessionKey) own a dedicated resident worker keyed by +// (model, session key). Later turns on that worker send only the +// newest user message; the worker's conversation holds the history. +// If no live worker exists but a conversation id is known, a worker +// is spawned with `--conversation ` to resume it. +// - Stateless requests claim a PRE-WARMED spare worker (spawned ahead +// of time, init already received) for exactly one fresh-conversation +// turn, then retire it — a used worker's context is never handed to +// an unrelated request — and a replacement spare is spawned in the +// background. With no spare ready, a worker is spawned on demand. +// - A worker that dies, errors its turn (result status != SUCCESS), +// or times out is killed and never reused; the next request respawns +// (spares replenish automatically). Live session workers are evicted +// after an idle TTL / past a live-worker cap. +// Failure semantics are unchanged from #678: a failed turn is an error +// (502 non-stream, SSE error event + [DONE] stream), never a 'stop' +// carrying partial output; a failed resume retries once as a fresh +// conversation with the full prompt when nothing was output yet. import http from 'node:http'; import { spawn } from 'node:child_process'; import crypto from 'node:crypto'; @@ -43,12 +72,20 @@ const publishEndpoint = () => { } catch {} }; +// The served model set, reconciled against `agy models` (agy 1.2.16, +// run in this proxy's service context on 2026-10-28): the CLI listed +// exactly 13 ids — the 5 bases below × their efforts. This stays a +// static array because `agy models` is a CLI call whose auth lives in +// the spawned child's environment, not something the proxy can poll; +// re-run `agy models` and update this array whenever the CLI version +// or the account's model entitlements change. Requests for ids not in +// this list are a 400, never a silent fallback (#1692). +// Removed 2026-10-28: gemini-3.7-flash, gemini-3.6-flash, +// gemini-3.1-pro — the proxy advertised them but `agy models` does not +// list them and agy itself rejects them. const MODELS = [ { id: 'gemini-4-argon', name: 'Gemini 4 Argon (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, { id: 'gemini-3.8-flash', name: 'Gemini 3.8 Flash (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, - { id: 'gemini-3.7-flash', name: 'Gemini 3.7 Flash (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, - { id: 'gemini-3.6-flash', name: 'Gemini 3.6 Flash (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, - { id: 'gemini-3.1-pro', name: 'Gemini 3.1 Pro (agy)', efforts: ['low', 'high'], defaultEffort: 'high' }, { id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5 (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, { id: 'claude-opus-5-5', name: 'Claude Opus 5.5 (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, { id: 'gpt-oss-120b', name: 'GPT-OSS 120B (agy)', efforts: ['medium'], defaultEffort: 'medium' } @@ -254,6 +291,329 @@ const formatPrompt = (messages) => { return parts.join('\n\n'); }; +// --------------------------------------------------------------------------- +// Resident warm `agy` stream-json workers +// --------------------------------------------------------------------------- +const TURN_TIMEOUT_MS = Number(process.env.AGY_PROXY_TURN_TIMEOUT_MS || 300000); +const INIT_TIMEOUT_MS = 60000; +const SPARES_ENABLED = process.env.AGY_PROXY_WARM_SPARES !== '0'; +const MAX_LIVE_WORKERS = Number(process.env.AGY_PROXY_MAX_LIVE_WORKERS || 32); +const SESSION_IDLE_TTL_MS = Number(process.env.AGY_PROXY_SESSION_TTL_MS || 30 * 60 * 1000); +// Models pre-warmed at startup (one spare each, default effort). Every +// other model warms its first spare after its first completed turn. +const PREWARM_MODELS = (process.env.AGY_PROXY_PREWARM_MODELS || 'gemini-4-argon-medium,gemini-3.8-flash-medium') + .split(',').map(s => s.trim()).filter(Boolean); + +const turnError = (detail, props = {}) => { + const err = new Error(detail); + err.detail = detail; + err.hasOutput = false; + Object.assign(err, props); + return err; +}; + +class AgyWorker { + constructor({ fullName, conversationId = null }) { + this.fullName = fullName; + this.conversationId = conversationId || null; + this.spawnedAt = Date.now(); + this.lastUsedAt = Date.now(); + this.turns = 0; + this.dead = null; // Error once the process is gone + this.lineBuffer = ''; + this.stderrTail = ''; + this.turnWaiter = null; + this.ready = false; // set when the init event arrives + this.prevUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 }; + + const args = [ + '--dangerously-skip-permissions', + '--disable-slash-commands' + ]; + if (conversationId) { + args.push('--conversation', conversationId); + } + // No `-p`: in stream-json input mode prompts arrive on stdin, one + // NDJSON user event per turn (a `-p` prompt would be dropped). + args.push( + '--model', fullName, + '--input-format', 'stream-json', + '--output-format', 'stream-json' + ); + + const child = spawn(AGY_BIN, args, { + cwd: '/tmp', + env: { + ...process.env, + HOME: AGY_HOME + }, + stdio: ['pipe', 'pipe', 'pipe'] + }); + this.child = child; + this.pid = child.pid; + + this.initPromise = new Promise((resolve, reject) => { + this._initResolve = resolve; + this._initReject = reject; + setTimeout(() => { + if (!this.dead && !this.ready) { + this._fail(turnError(`agy session did not init within ${INIT_TIMEOUT_MS}ms`)); + this.kill(); + } + }, INIT_TIMEOUT_MS).unref(); + }); + this.initPromise.catch(() => {}); // surfaced via runTurn + + child.stdout.on('data', chunk => this._onStdout(chunk)); + child.stderr.on('data', chunk => { + this.stderrTail = (this.stderrTail + chunk.toString()).slice(-4000); + }); + child.on('error', err => { + this._fail(turnError(err.message, { isSpawnError: true })); + }); + child.on('close', (code, signal) => { + // Failure is judged by the child's exit (#678): the last stderr + // line names the cause when there is one, then the signal, then + // the exit code — the same detail ladder the cold path used. + const stderrLine = this.stderrTail.trim().split('\n').filter(Boolean).pop(); + const detail = stderrLine + || (signal ? `agy process terminated by signal ${signal}` : `agy process exited with code ${code}`); + this._fail(turnError(detail, { isExitError: true, code, signal, stderr: this.stderrTail })); + }); + } + + _fail(err) { + if (this.dead) return; + this.dead = err; + if (this._initReject) this._initReject(err); + if (this.turnWaiter) { + const w = this.turnWaiter; + this.turnWaiter = null; + err.hasOutput = w.deltas.length > 0; + w.reject(err); + } + } + + _onStdout(chunk) { + this.lineBuffer += chunk.toString(); + const lines = this.lineBuffer.split('\n'); + this.lineBuffer = lines.pop() || ''; + for (const line of lines) { + if (!line.trim()) continue; + let obj; + try { obj = JSON.parse(line); } catch { continue; } + this._onEvent(obj); + } + } + + _onEvent(obj) { + if (obj.conversation_id) this.conversationId = obj.conversation_id; + if (obj.event === 'init') { + this.ready = true; + if (obj.conversation_id) this.conversationId = obj.conversation_id; + if (this._initResolve) this._initResolve(this.conversationId); + return; + } + const w = this.turnWaiter; + if (!w) return; + if (obj.event === 'step_update' && obj.step_update?.text_delta) { + const delta = obj.step_update.text_delta; + w.deltas += delta; + if (w.onDelta) { try { w.onDelta(delta); } catch {} } + return; + } + if (obj.event === 'result') { + this.turnWaiter = null; + const result = obj.result || {}; + if (result.conversation_id) this.conversationId = result.conversation_id; + if (result.status && result.status !== 'SUCCESS') { + // A turn-level error (agy docs: the result carries `error`). + // The session's state is unknown afterwards — the caller kills + // this worker rather than reusing it. + const detail = (typeof result.error === 'string' && result.error.trim()) + || `agy turn ended with status ${result.status}`; + const err = turnError(detail, { isResultError: true, stderr: this.stderrTail }); + err.hasOutput = w.deltas.length > 0; + w.reject(err); + return; + } + // `usage` on a stream-json result is CUMULATIVE over the session + // (agy docs); the per-turn usage is the delta from the previous + // turn's cumulative counters. + const cum = result.usage || {}; + const deltaUsage = { + input_tokens: Math.max(0, (cum.input_tokens || 0) - this.prevUsage.input_tokens), + output_tokens: Math.max(0, (cum.output_tokens || 0) - this.prevUsage.output_tokens), + total_tokens: Math.max(0, (cum.total_tokens || 0) - this.prevUsage.total_tokens) + }; + this.prevUsage = { + input_tokens: cum.input_tokens || 0, + output_tokens: cum.output_tokens || 0, + total_tokens: cum.total_tokens || 0 + }; + this.turns += 1; + this.lastUsedAt = Date.now(); + w.resolve({ + text: typeof result.response === 'string' ? result.response : w.deltas, + deltas: w.deltas, + usage: deltaUsage, + conversationId: this.conversationId + }); + } + } + + async runTurn(promptText, onDelta) { + if (this.dead) { const e = this.dead; e.hasOutput = false; throw e; } + await this.initPromise; + if (this.dead) { const e = this.dead; e.hasOutput = false; throw e; } + if (this.turnWaiter) throw turnError('agy worker already has a turn in flight'); + return new Promise((resolve, reject) => { + const waiter = { + deltas: '', + onDelta, + resolve: (v) => { clearTimeout(timer); resolve(v); }, + reject: (e) => { clearTimeout(timer); reject(e); } + }; + const timer = setTimeout(() => { + if (this.turnWaiter === waiter) { + this.turnWaiter = null; + this.kill(); + const err = turnError(`agy turn timed out after ${TURN_TIMEOUT_MS}ms`, { isTimeout: true }); + err.hasOutput = waiter.deltas.length > 0; + waiter.reject(err); + } + }, TURN_TIMEOUT_MS); + this.turnWaiter = waiter; + try { + this.child.stdin.write(JSON.stringify({ event: 'user', message: { content: promptText } }) + '\n'); + } catch (err) { + this.turnWaiter = null; + waiter.reject(turnError(err.message, { isSpawnError: true })); + } + }); + } + + kill() { + // Settle any in-flight turn / pending init first, so a killed + // worker never leaves a request hanging until the turn timeout. + this._fail(turnError('agy worker killed')); + if (this.child && !this.child.killed) { + try { this.child.kill('SIGTERM'); } catch {} + const child = this.child; + setTimeout(() => { try { child.kill('SIGKILL'); } catch {} }, 3000).unref(); + } + } +} + +// Live session workers, keyed `${fullName}|${sessionKey}`. +const liveWorkers = new Map(); +// One pre-warmed spare per model fullName: spawned ahead of a request, +// init already received, zero turns taken — its conversation is fresh. +const spares = new Map(); + +const ensureSpare = (fullName) => { + if (!SPARES_ENABLED) return; + const existing = spares.get(fullName); + if (existing && !existing.dead) return; + if (existing) spares.delete(fullName); + const w = new AgyWorker({ fullName }); + spares.set(fullName, w); + w.initPromise.catch(() => { + if (spares.get(fullName) === w) spares.delete(fullName); + }); +}; + +const takeSpare = (fullName) => { + const w = spares.get(fullName); + if (w) spares.delete(fullName); + if (w && !w.dead) { + ensureSpare(fullName); // replenish in the background + return w; + } + return null; +}; + +const evictLiveWorkersIfNeeded = () => { + const now = Date.now(); + for (const [lk, w] of liveWorkers) { + if (w.dead || now - w.lastUsedAt > SESSION_IDLE_TTL_MS) { + w.kill(); + liveWorkers.delete(lk); + } + } + const live = [...liveWorkers.entries()].sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt); + while (live.length >= MAX_LIVE_WORKERS) { + const [lk, w] = live.shift(); + w.kill(); + liveWorkers.delete(lk); + } +}; +setInterval(evictLiveWorkersIfNeeded, 60000).unref(); + +// Acquire a worker for one request. Synchronous: spawning is cheap to +// start; runTurn awaits the worker's init. `resumed` is true when the +// worker was spawned to resume `conversationId` or already holds the +// session's conversation (so the caller sends the delta prompt and may +// apply the fresh-conversation retry on a no-output failure). +const acquireWorker = ({ fullName, key, conversationId }) => { + if (key) { + const lk = `${fullName}|${key}`; + const live = liveWorkers.get(lk); + if (live && !live.dead) return { worker: live, resumed: true, lk }; + if (live) liveWorkers.delete(lk); + evictLiveWorkersIfNeeded(); + if (conversationId) { + const w = new AgyWorker({ fullName, conversationId }); + liveWorkers.set(lk, w); + return { worker: w, resumed: true, lk }; + } + const w = takeSpare(fullName) || new AgyWorker({ fullName }); + liveWorkers.set(lk, w); + return { worker: w, resumed: false, lk }; + } + const w = takeSpare(fullName) || new AgyWorker({ fullName }); + return { worker: w, resumed: false, lk: null }; +}; + +// Drop a worker after a failed turn / a finished stateless turn: it is +// killed, unbound, and (for stateless use) a fresh spare is warmed. +const retireWorker = ({ worker, lk }) => { + if (lk && liveWorkers.get(lk) === worker) liveWorkers.delete(lk); + worker.kill(); + if (!lk) ensureSpare(worker.fullName); +}; + +const killAllWorkers = () => { + for (const w of liveWorkers.values()) w.kill(); + for (const w of spares.values()) w.kill(); + liveWorkers.clear(); + spares.clear(); +}; +// Registered before publishEndpoint's handlers (added at listen time) +// so workers die before the process exits on SIGTERM/SIGINT. +process.on('SIGTERM', killAllWorkers); +process.on('SIGINT', killAllWorkers); +process.on('exit', killAllWorkers); + +// Per-session-key serialization: turns on one conversation must not +// interleave (stateless requests use distinct workers and skip this). +const chains = new Map(); +const enqueue = (key, job) => { + const prev = chains.get(key) || Promise.resolve(); + const run = prev.then(job, job); + const stored = run.catch(() => {}); + chains.set(key, stored); + stored.then(() => { if (chains.get(key) === stored) chains.delete(key); }); + return run; +}; + +const warmStatus = () => ({ + spares: Object.fromEntries([...spares.entries()].map(([m, w]) => [m, w.pid])), + sparePids: [...spares.values()].filter(w => !w.dead).map(w => w.pid), + sessionPids: [...liveWorkers.values()].filter(w => !w.dead).map(w => w.pid), + liveSessions: liveWorkers.size +}); + const server = http.createServer((req, res) => { const url = new URL(req.url, `http://${req.headers.host || HOST}`); const pathname = url.pathname.replace(/\/+$/, '') || '/'; @@ -266,8 +626,10 @@ const server = http.createServer((req, res) => { service: 'antigravity-agy-proxy', port: PORT, binary: AGY_BIN, + engine: 'agy-stream-json-resident', defaultModel: 'gemini-3.8-flash-medium', - activeSessions: sessionStore.size + activeSessions: sessionStore.size, + warm: warmStatus() }, null, 2)); return; } @@ -311,7 +673,7 @@ const server = http.createServer((req, res) => { } }); - req.on('end', () => { + req.on('end', async () => { let body; try { body = JSON.parse(bodyText); @@ -329,7 +691,7 @@ const server = http.createServer((req, res) => { res.end(JSON.stringify({ error: `Unknown model: ${body.model}` })); return; } - const { baseModel, effort, fullName } = resolved; + const { fullName } = resolved; const sessionInfo = getSessionKey(req, body); const isResuming = Boolean(sessionInfo.conversationId); @@ -346,45 +708,13 @@ const server = http.createServer((req, res) => { const reqId = `chatcmpl-${crypto.randomUUID()}`; const created = Math.floor(Date.now() / 1000); - const runAgy = (targetConversationId, promptText, onComplete) => { - const agyArgs = [ - '--dangerously-skip-permissions', - '--disable-slash-commands' - ]; - - if (targetConversationId) { - agyArgs.push('--conversation', targetConversationId); - } - - agyArgs.push( - '-p', promptText, - '--model', fullName, - '--output-format', stream ? 'stream-json' : 'json' - ); - - const child = spawn(AGY_BIN, agyArgs, { - cwd: '/tmp', - detached: true, - env: { - ...process.env, - HOME: AGY_HOME - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - - onComplete(child); - }; - - let currentChild = null; + let currentWorker = null; let activeConversationId = sessionInfo.conversationId || null; res.on('close', () => { - if (!res.writableEnded && currentChild) { - try { - if (currentChild.pid) process.kill(-currentChild.pid, 'SIGTERM'); - } catch { - try { currentChild.kill('SIGTERM'); } catch {} - } + if (!res.writableEnded && currentWorker) { + const lk = sessionInfo.key ? `${fullName}|${sessionInfo.key}` : null; + retireWorker({ worker: currentWorker, lk }); } }); @@ -395,253 +725,192 @@ const server = http.createServer((req, res) => { sessionStore.set(sessionInfo.key, { conversationId: id, updatedAt: Date.now() }); pruneSessionStore(); } - if (!res.headersSent) { - try { - res.setHeader('X-Conversation-Id', id); - res.setHeader('X-Session-Id', id); - } catch {} - } }; - if (stream) { + // Streaming head is written lazily (on the first delta, or when + // the turn settles) so a no-output resume failure can still be + // retried transparently before anything reaches the client. + let headed = false; + const ensureStreamHead = () => { + if (!stream || headed) return; + headed = true; res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' }); + }; - const executeStream = (targetConvId, promptToUse, allowRetry) => { - let lineBuffer = ''; - let finalUsage = null; - let responseEnded = false; - let hasOutput = false; - let stderrBuffer = ''; - - runAgy(targetConvId, promptToUse, (child) => { - currentChild = child; - - const processJsonLine = (line) => { - if (!line.trim()) return; - try { - const obj = JSON.parse(line); - if (obj.conversation_id) { - recordConversationId(obj.conversation_id); - } - if (obj.event === 'init' && obj.conversation_id) { - recordConversationId(obj.conversation_id); - } - if (obj.event === 'step_update' && obj.step_update?.text_delta) { - hasOutput = true; - const delta = obj.step_update.text_delta; - const chunk = { - id: reqId, - object: 'chat.completion.chunk', - created, - model: fullName, - conversation_id: activeConversationId, - choices: [ - { - index: 0, - delta: { content: delta }, - finish_reason: null - } - ] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } else if (obj.event === 'result') { - finalUsage = obj.result?.usage || null; - if (obj.result?.conversation_id) { - recordConversationId(obj.result.conversation_id); - } + const runJob = async () => { + const attempt = async (targetConvId, promptText, allowRetry) => { + const { worker, resumed, lk } = acquireWorker({ + fullName, key: sessionInfo.key, conversationId: targetConvId + }); + currentWorker = worker; + try { res.setHeader('X-Agy-Worker-Pid', String(worker.pid)); } catch {} + if (worker.conversationId) activeConversationId = worker.conversationId; + + let streamedText = ''; + const onDelta = stream ? (delta) => { + streamedText += delta; + ensureStreamHead(); + const chunk = { + id: reqId, + object: 'chat.completion.chunk', + created, + model: fullName, + conversation_id: activeConversationId, + choices: [ + { + index: 0, + delta: { content: delta }, + finish_reason: null } - } catch {} + ] }; + res.write(`data: ${JSON.stringify(chunk)}\n\n`); + } : null; - child.stdout.on('data', chunk => { - lineBuffer += chunk.toString(); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop() || ''; - for (const line of lines) { - processJsonLine(line); - } - }); - - child.stderr.on('data', chunk => { - stderrBuffer += chunk.toString(); - }); - - child.on('close', (code, signal) => { - if (responseEnded) return; - - // Fallback retry if resuming failed without output - if (code !== 0 && !hasOutput && allowRetry && targetConvId) { - console.log(`Resuming conversation ${targetConvId} failed (code ${code}), retrying as fresh conversation...`); - executeStream(null, formatPrompt(body.messages), false); - return; - } - - responseEnded = true; - - if (lineBuffer.trim()) { - processJsonLine(lineBuffer.trim()); - } - - // Failure is judged by the child's exit: a non-zero code or - // a killing signal means the run failed, however much content - // was already produced (#678). Partial output must not mask - // a failure — it used to be reported as a successful 'stop' - // carrying the truncated text (or an empty 200 when nothing - // was produced at all), and stderrBuffer was never read. - if (code !== 0) { - const stderrLine = stderrBuffer.trim().split('\n').pop(); - const fallback = signal - ? `agy process terminated by signal ${signal}` - : `agy process exited with code ${code}`; - const detail = (stderrLine || fallback).trim(); - const errorBody = { error: { message: `agy execution failed: ${detail}` } }; - // The 200 + text/event-stream headers are already on the - // wire, so frame the error as an SSE event and close the - // stream with [DONE] (mirrors muse-proxy #670). - res.write(`data: ${JSON.stringify(errorBody)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - return; - } + let result; + try { + result = await worker.runTurn(promptText, onDelta); + } catch (err) { + retireWorker({ worker, lk }); + if (currentWorker === worker) currentWorker = null; + // Fallback retry if resuming failed without output (#678's + // retry, preserved): start over as a fresh conversation + // carrying the full flattened prompt. + if (allowRetry && resumed && !err.hasOutput) { + console.log(`Resuming conversation ${targetConvId} failed (${err.detail}), retrying as fresh conversation...`); + return attempt(null, formatPrompt(body.messages), false); + } + // Failure is judged by the turn's outcome, never by whether + // partial output was produced (#678): partial output must + // not mask a failure as a successful 'stop'. + if (stream) { + ensureStreamHead(); + const errorBody = { error: { message: `agy execution failed: ${err.detail}` } }; + // The 200 + text/event-stream headers may already be on + // the wire, so frame the error as an SSE event and close + // the stream with [DONE] (mirrors muse-proxy #670). + res.write(`data: ${JSON.stringify(errorBody)}\n\n`); + res.write('data: [DONE]\n\n'); + res.end(); + } else if (err.isExitError) { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + error: 'agy process exited with non-zero code', + code: err.code, + ...(err.signal ? { signal: err.signal } : {}), + stderr: (err.stderr || '').trim() + })); + } else { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + error: `agy execution failed: ${err.detail}`, + stderr: (err.stderr || '').trim() + })); + } + return; + } - const finishChunk = { + // Success: commit the session mapping, keep session workers + // resident for their next turn, retire stateless workers (a + // replacement spare is already warming). + recordConversationId(result.conversationId); + if (!lk) retireWorker({ worker, lk }); + if (currentWorker === worker) currentWorker = null; + + if (stream) { + // Emit any response tail the result carried beyond the + // deltas already streamed (short replies can arrive whole + // in the result with no ACTIVE delta for the tail). + if (typeof result.text === 'string' && result.text.startsWith(streamedText) && result.text.length > streamedText.length) { + const suffix = result.text.slice(streamedText.length); + ensureStreamHead(); + const chunk = { id: reqId, object: 'chat.completion.chunk', created, model: fullName, conversation_id: activeConversationId, - choices: [ - { - index: 0, - delta: {}, - finish_reason: 'stop' - } - ], - usage: { - prompt_tokens: finalUsage?.input_tokens || 0, - completion_tokens: finalUsage?.output_tokens || 0, - total_tokens: finalUsage?.total_tokens || 0 - } + choices: [{ index: 0, delta: { content: suffix }, finish_reason: null }] }; - - res.write(`data: ${JSON.stringify(finishChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - }); - - child.on('error', err => { - if (!responseEnded) { - responseEnded = true; - res.write(`data: {"error": ${JSON.stringify(err.message)}}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } - }); - }); - }; - - executeStream(sessionInfo.conversationId, prompt, Boolean(sessionInfo.conversationId)); - - } else { - // Non-streaming JSON mode - const executeJson = (targetConvId, promptToUse, allowRetry) => { - let stdoutBuffer = ''; - let stderrBuffer = ''; - - runAgy(targetConvId, promptToUse, (child) => { - currentChild = child; - - child.stdout.on('data', chunk => { stdoutBuffer += chunk.toString(); }); - child.stderr.on('data', chunk => { stderrBuffer += chunk.toString(); }); - - child.on('close', (code, signal) => { - if (res.writableEnded) return; - - let responseText = ''; - let usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 }; - let detectedConvId = null; - - try { - const parsed = JSON.parse(stdoutBuffer.trim()); - responseText = parsed.response || ''; - if (parsed.usage) usage = parsed.usage; - if (parsed.conversation_id) detectedConvId = parsed.conversation_id; - } catch { - responseText = stdoutBuffer.trim(); - } - - if (detectedConvId) { - recordConversationId(detectedConvId); - } - - // Failure is judged by the child's exit, not by whether it - // produced output (#678): a run that fails after a partial - // response must not be reported as a successful 'stop' - // carrying the truncated text. The resume retry stays - // gated on empty output, as before. - if (code !== 0) { - if (!responseText && allowRetry && targetConvId) { - console.log(`Resuming conversation ${targetConvId} failed (code ${code}), retrying as fresh conversation...`); - executeJson(null, formatPrompt(body.messages), false); - return; + res.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + ensureStreamHead(); + const finishChunk = { + id: reqId, + object: 'chat.completion.chunk', + created, + model: fullName, + conversation_id: activeConversationId, + choices: [ + { + index: 0, + delta: {}, + finish_reason: 'stop' } - - res.writeHead(502, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - error: 'agy process exited with non-zero code', - code, - ...(signal ? { signal } : {}), - stderr: stderrBuffer.trim() - })); - return; + ], + usage: { + prompt_tokens: result.usage?.input_tokens || 0, + completion_tokens: result.usage?.output_tokens || 0, + total_tokens: result.usage?.total_tokens || 0 } - - res.writeHead(200, { - 'Content-Type': 'application/json', - ...(activeConversationId ? { - 'X-Conversation-Id': activeConversationId, - 'X-Session-Id': activeConversationId - } : {}) - }); - res.end(JSON.stringify({ - id: reqId, - object: 'chat.completion', - created, - model: fullName, - conversation_id: activeConversationId, - choices: [ - { - index: 0, - message: { - role: 'assistant', - content: responseText - }, - finish_reason: 'stop' - } - ], - usage: { - prompt_tokens: usage.input_tokens || 0, - completion_tokens: usage.output_tokens || 0, - total_tokens: usage.total_tokens || 0 - } - }, null, 2)); + }; + res.write(`data: ${JSON.stringify(finishChunk)}\n\n`); + res.write('data: [DONE]\n\n'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Type': 'application/json', + ...(activeConversationId ? { + 'X-Conversation-Id': activeConversationId, + 'X-Session-Id': activeConversationId + } : {}) }); - - child.on('error', err => { - if (!res.writableEnded) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: err.message })); + res.end(JSON.stringify({ + id: reqId, + object: 'chat.completion', + created, + model: fullName, + conversation_id: activeConversationId, + choices: [ + { + index: 0, + message: { + role: 'assistant', + content: result.text + }, + finish_reason: 'stop' + } + ], + usage: { + prompt_tokens: result.usage?.input_tokens || 0, + completion_tokens: result.usage?.output_tokens || 0, + total_tokens: result.usage?.total_tokens || 0 } - }); - }); + }, null, 2)); + } }; - executeJson(sessionInfo.conversationId, prompt, Boolean(sessionInfo.conversationId)); + await attempt(sessionInfo.conversationId, prompt, Boolean(sessionInfo.conversationId)); + }; + + try { + if (sessionInfo.key) { + await enqueue(`${fullName}|${sessionInfo.key}`, runJob); + } else { + await runJob(); + } + } catch (err) { + if (!res.writableEnded && !res.headersSent) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: err.message })); + } else if (!res.writableEnded) { + res.end(); + } } }); return; @@ -653,7 +922,9 @@ const server = http.createServer((req, res) => { server.listen(PORT, HOST, () => { publishEndpoint(); + for (const m of PREWARM_MODELS) ensureSpare(m); console.log(`Antigravity agy Proxy listening on http://${HOST}:${PORT}`); + console.log(`Engine: resident agy stream-json workers (spares ${SPARES_ENABLED ? 'on' : 'off'}, prewarm: ${PREWARM_MODELS.join(', ') || 'none'})`); console.log(`Endpoints:`); console.log(` - GET http://${HOST}:${PORT}/health`); console.log(` - GET http://${HOST}:${PORT}/v1/models`); diff --git a/bin/agy-proxy.test.mjs b/bin/agy-proxy.test.mjs index c17d373697..4407a12232 100644 --- a/bin/agy-proxy.test.mjs +++ b/bin/agy-proxy.test.mjs @@ -1,13 +1,18 @@ -// Tests for agy-proxy's failure detection (#678). +// Tests for agy-proxy: failure detection (#678), the reconciled model +// list (#1692 + the 2026-10-28 `agy models` reconciliation), and the +// resident warm stream-json serving path. // Run: node --test bin/agy-proxy.test.mjs // -// The proxy spawns one `agy` child per request, with the prompt delivered -// as the `-p` argument. These tests put a stub `agy` at -// $HOME/.local/bin/agy (the proxy's binary resolution prefers it) whose -// behaviour is keyed on markers in the prompt: a run that exited non-zero -// used to be reported as a successful 'stop' — in stream mode always -// (the close handler never checked the code), and in non-stream mode -// whenever the run had produced partial output. +// The proxy now holds resident `agy` processes speaking +// `--input-format stream-json`: prompts arrive on the child's stdin as +// NDJSON `{"event":"user","message":{"content":...}}` lines and each +// turn ends with a `result` event. These tests put a stub `agy` at +// $HOME/.local/bin/agy (the proxy's binary resolution reaches it when +// no system agy exists) that speaks that protocol: it emits an `init` +// event at spawn, then one reply per stdin line, keyed on markers in +// the prompt — a run that dies non-zero must be reported as an error, +// never as a successful 'stop' (in stream mode always, in non-stream +// mode also when the run produced partial output first). import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; @@ -20,43 +25,33 @@ import { fileURLToPath } from 'node:url'; const binDir = path.dirname(fileURLToPath(import.meta.url)); const STUB = `#!/bin/sh -prompt="" -fmt="json" conv="" prev="" for a in "$@"; do - if [ "$prev" = "-p" ]; then prompt="$a"; fi if [ "$prev" = "--conversation" ]; then conv="$a"; fi - if [ "$a" = "stream-json" ]; then fmt="stream"; fi prev="$a" done -case "$prompt" in - *RETRYME*) - if [ -n "$conv" ]; then - echo "stub agy: resume failed" >&2 - exit 3 - fi ;; - *FAILME*) - echo "stub agy: auth expired" >&2 - exit 3 ;; - *FAILPARTIAL*) - if [ "$fmt" = "stream" ]; then +printf '%s\\n' '{"event":"init","conversation_id":"stub-conv-1","init":{}}' +while IFS= read -r line; do + case "$line" in + *RETRYME*) + if [ -n "$conv" ]; then + echo "stub agy: resume failed" >&2 + exit 3 + fi ;; + *FAILME*) + echo "stub agy: auth expired" >&2 + exit 3 ;; + *FAILPARTIAL*) printf '%s\\n' '{"event":"step_update","step_update":{"text_delta":"partial answer"}}' - else - printf '%s\\n' '{"response":"partial answer"}' - fi - echo "stub agy: run failed midway" >&2 - exit 3 ;; - *SIGKILLME*) - kill -9 $$ ;; -esac -if [ "$fmt" = "stream" ]; then + echo "stub agy: run failed midway" >&2 + exit 3 ;; + *SIGKILLME*) + kill -9 $$ ;; + esac printf '%s\\n' '{"event":"step_update","step_update":{"text_delta":"Hello world"}}' - printf '%s\\n' '{"event":"result","result":{"usage":{"input_tokens":100,"output_tokens":3,"total_tokens":103}}}' -else - printf '%s\\n' '{"response":"Hello world","usage":{"input_tokens":100,"output_tokens":3,"total_tokens":103}}' -fi -exit 0 + printf '%s\\n' '{"event":"result","result":{"conversation_id":"stub-conv-1","status":"SUCCESS","response":"Hello world","usage":{"input_tokens":100,"output_tokens":3,"total_tokens":103}}}' +done `; const freePort = () => new Promise((resolve, reject) => { @@ -200,7 +195,51 @@ test('failed resume still retries once as a fresh conversation (#678)', async (t assert.match(sse, /"finish_reason":"stop"/); }); -test("unknown model is a 400, never a silent fallback; Argon is listed and served", async (t) => { +test('session requests reuse one resident worker (same pid across turns)', async (t) => { + const { port, stop } = await startProxy(); + t.after(stop); + const headers = { 'x-conversation-id': 'conv-warm-1' }; + + const first = await post(port, { messages: [{ role: 'user', content: 'hi' }] }, headers); + assert.equal(first.status, 200); + await first.text(); + const pid1 = first.headers.get('x-agy-worker-pid'); + assert.ok(pid1 && Number(pid1) > 0, 'first response must name its worker pid'); + + const second = await post(port, { + messages: [ + { role: 'user', content: 'hi' }, + { role: 'assistant', content: 'Hello world' }, + { role: 'user', content: 'again' } + ] + }, headers); + assert.equal(second.status, 200); + const secondBody = JSON.parse(await second.text()); + assert.equal(secondBody.choices[0].message.content, 'Hello world'); + const pid2 = second.headers.get('x-agy-worker-pid'); + assert.equal(pid2, pid1, 'second turn of a session must run on the same resident worker'); + + const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); + assert.equal(health.engine, 'agy-stream-json-resident'); + assert.ok(health.warm.sessionPids.includes(Number(pid1)), 'health must list the live session worker pid'); +}); + +test('a pre-warmed spare is ready before the first stateless request', async (t) => { + const { port, stop } = await startProxy(); + t.after(stop); + const deadline = Date.now() + 5000; + for (;;) { + const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); + if (Array.isArray(health.warm?.sparePids) && health.warm.sparePids.length > 0) { + assert.ok(health.warm.spares['gemini-4-argon-medium'] > 0, 'argon spare must be pre-warmed'); + return; + } + if (Date.now() > deadline) throw new Error('no pre-warmed spare appeared in /health'); + await new Promise(r => setTimeout(r, 50)); + } +}); + +test("unknown model is a 400, never a silent fallback; the served list is the `agy models` list", async (t) => { const { port, stop } = await startProxy(); t.after(stop); const messages = [{ role: "user", content: "hi" }]; @@ -213,12 +252,39 @@ test("unknown model is a 400, never a silent fallback; Argon is listed and serve const listRes = await fetch(`http://127.0.0.1:${port}/v1/models`); const list = JSON.parse(await listRes.text()); const ids = list.data.map((m) => m.id); - for (const id of ["gemini-4-argon", "gemini-4-argon-low", "gemini-4-argon-medium", "gemini-4-argon-high"]) { + // `agy models` (1.2.16, 2026-10-28) lists exactly these 13 ids; the + // proxy serves each base plus its per-effort variants. + for (const id of [ + "gemini-4-argon", "gemini-4-argon-low", "gemini-4-argon-medium", "gemini-4-argon-high", + "gemini-3.8-flash", "gemini-3.8-flash-low", "gemini-3.8-flash-medium", "gemini-3.8-flash-high", + "claude-sonnet-5-5", "claude-sonnet-5-5-low", "claude-sonnet-5-5-medium", "claude-sonnet-5-5-high", + "claude-opus-5-5", "claude-opus-5-5-low", "claude-opus-5-5-medium", "claude-opus-5-5-high", + "gpt-oss-120b", "gpt-oss-120b-medium" + ]) { assert.ok(ids.includes(id), `models list must include ${id}`); } + // Advertised before 2026-10-28 but absent from `agy models` (agy + // itself rejects them): they must not be served or silently remapped. + for (const id of ["gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.1-pro"]) { + assert.ok(!ids.includes(id), `models list must not include ${id}`); + const res = await post(port, { model: id, messages }); + assert.equal(res.status, 400, `${id} must be a 400, not a silent remap`); + await res.text(); + } const argonRes = await post(port, { model: "gemini-4-argon", messages }); assert.equal(argonRes.status, 200); const argon = JSON.parse(await argonRes.text()); assert.equal(argon.model, "gemini-4-argon-medium"); + + const sonnetRes = await post(port, { model: "claude-sonnet-5-5", messages }); + assert.equal(sonnetRes.status, 200); + const sonnet = JSON.parse(await sonnetRes.text()); + assert.equal(sonnet.model, "claude-sonnet-5-5-medium"); + assert.equal(sonnet.choices[0].message.content, "Hello world"); + + const opusRes = await post(port, { model: "claude-opus-5-5-high", messages }); + assert.equal(opusRes.status, 200); + const opus = JSON.parse(await opusRes.text()); + assert.equal(opus.model, "claude-opus-5-5-high"); }); From bfcfc15ac2c6fbd1d0d0728b9832c89c0e798ab0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 13:02:15 -0500 Subject: [PATCH 2/3] feat(antigravity): agy-proxy pulls its model list live from agy models MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fleet live-pull rule (2026-10-28): the served catalog is no longer a static array. The proxy spawns `agy models` in the same service context its workers use, groups the ids into bases/efforts, caches in memory for AGY_PROXY_MODELS_TTL_MS (default 5m, stale-while-revalidate), persists the last successful pull to $XDG_STATE_HOME/agy-proxy/models-cache.json, and falls back cache-then-baked-list when a pull fails. A 400-triggering unknown-model miss also fires an async re-pull. Unknown ids are judged against the current live / last-known-good list (#1692 preserved). /health reports models {source, bases, ids, fetchedAt, ttlMs}. Also adds per-request timing observability for benchmarking: X-Agy-Turn-Ms response header and a journal turn line (reqId, model, workerPid, durationMs, status). Tests: 10/10 — stub agy now answers `agy models` (incl. a stub-only model, proving live sourcing) and can be made to fail it (proving last-known-good fallback with unknowns still 400). --- bin/agy-proxy.mjs | 234 +++++++++++++++++++++++++++++++++++------ bin/agy-proxy.test.mjs | 105 +++++++++++++++--- 2 files changed, 295 insertions(+), 44 deletions(-) diff --git a/bin/agy-proxy.mjs b/bin/agy-proxy.mjs index b59e2ac4f4..97264331a2 100755 --- a/bin/agy-proxy.mjs +++ b/bin/agy-proxy.mjs @@ -72,18 +72,22 @@ const publishEndpoint = () => { } catch {} }; -// The served model set, reconciled against `agy models` (agy 1.2.16, -// run in this proxy's service context on 2026-10-28): the CLI listed -// exactly 13 ids — the 5 bases below × their efforts. This stays a -// static array because `agy models` is a CLI call whose auth lives in -// the spawned child's environment, not something the proxy can poll; -// re-run `agy models` and update this array whenever the CLI version -// or the account's model entitlements change. Requests for ids not in -// this list are a 400, never a silent fallback (#1692). -// Removed 2026-10-28: gemini-3.7-flash, gemini-3.6-flash, -// gemini-3.1-pro — the proxy advertised them but `agy models` does not -// list them and agy itself rejects them. -const MODELS = [ +// The served model set is pulled LIVE from `agy models` (Drew's +// fleet-wide rule, 2026-10-28: providers pull their model list live +// unless not possible), in this proxy's own service context — the +// pull spawns `agy models` with the same child environment the +// workers get (HOME=AGY_HOME), which is the context whose auth works. +// The list is cached in memory for MODELS_TTL_MS (stale-while- +// revalidate: requests never block on a refresh after the first +// load), refreshed in the background when stale and immediately +// (async) when a request names an unknown model. Last-known-good +// fallback chain when a pull fails: the on-disk cache of the last +// successful pull ($XDG_STATE_HOME/agy-proxy/models-cache.json), +// then FALLBACK_MODELS — the list as pulled on 2026-10-28 (agy +// 1.2.16: 13 ids over 5 bases), kept only as a cold-start floor. +// Unknown ids (against the current live / last-known-good list) +// return HTTP 400, never a silent fallback (#1692). +const FALLBACK_MODELS = [ { id: 'gemini-4-argon', name: 'Gemini 4 Argon (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, { id: 'gemini-3.8-flash', name: 'Gemini 3.8 Flash (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, { id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5 (agy)', efforts: ['low', 'medium', 'high'], defaultEffort: 'medium' }, @@ -158,6 +162,158 @@ const ensureAgyEnvironment = () => { ensureAgyEnvironment(); +// --------------------------------------------------------------------------- +// Live model catalog (see the FALLBACK_MODELS comment above) +// --------------------------------------------------------------------------- +const MODELS_TTL_MS = Number(process.env.AGY_PROXY_MODELS_TTL_MS || 300000); +const MODELS_PULL_TIMEOUT_MS = 30000; +const modelsCacheFile = () => path.join( + process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), + 'agy-proxy', 'models-cache.json' +); + +let modelCatalog = FALLBACK_MODELS; +let modelsSource = 'fallback'; // 'live' | 'cache' | 'fallback' +let modelsFetchedAt = 0; +let modelsPullInFlight = null; + +// Group `agy models` full ids (`-` TSV lines) into the +// base-model catalog shape resolveModelAndEffort / /v1/models use. +const catalogFromFullIds = (fullIds) => { + const bases = new Map(); + for (const { id, name } of fullIds) { + let base = id; + let effort = null; + for (const suffix of ['-low', '-medium', '-high']) { + if (id.endsWith(suffix)) { + effort = suffix.slice(1); + base = id.slice(0, -suffix.length); + break; + } + } + if (!bases.has(base)) { + const baseName = (name || base).replace(/\s*\((Low|Medium|High)\)\s*$/, ''); + bases.set(base, { id: base, name: `${baseName} (agy)`, efforts: [], defaultEffort: null }); + } + const entry = bases.get(base); + if (effort && !entry.efforts.includes(effort)) entry.efforts.push(effort); + } + const catalog = [...bases.values()].filter(m => m.efforts.length > 0); + for (const m of catalog) { + m.defaultEffort = m.efforts.includes('medium') ? 'medium' : m.efforts[0]; + } + return catalog; +}; + +const parseAgyModelsOutput = (stdout) => { + const fullIds = []; + for (const line of stdout.split('\n')) { + const [id, name] = line.split('\t'); + if (!id || !/^[a-z0-9][a-z0-9._-]*$/i.test(id.trim())) continue; + fullIds.push({ id: id.trim(), name: (name || '').trim() }); + } + return fullIds; +}; + +const persistModelsCache = (fullIds) => { + try { + const file = modelsCacheFile(); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(`${file}.tmp`, JSON.stringify({ fetchedAt: Date.now(), models: fullIds }, null, 2) + '\n'); + fs.renameSync(`${file}.tmp`, file); + } catch {} +}; + +const loadModelsCache = () => { + try { + const cached = JSON.parse(fs.readFileSync(modelsCacheFile(), 'utf8')); + if (Array.isArray(cached.models) && cached.models.length > 0) { + const catalog = catalogFromFullIds(cached.models); + if (catalog.length > 0) { + modelCatalog = catalog; + modelsSource = 'cache'; + modelsFetchedAt = cached.fetchedAt || 0; + console.log(`[agy-proxy] Model catalog from last-known-good cache (${catalog.length} bases, pulled ${new Date(modelsFetchedAt).toISOString()})`); + } + } + } catch { /* no cache yet */ } +}; + +const pullModelsLive = () => new Promise((resolve) => { + const child = spawn(AGY_BIN, ['models'], { + cwd: '/tmp', + env: { ...process.env, HOME: AGY_HOME }, + stdio: ['ignore', 'pipe', 'pipe'] + }); + let stdout = ''; + let settled = false; + const done = (ok, fullIds) => { + if (settled) return; + settled = true; + resolve(ok ? fullIds : null); + }; + const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} done(false); }, MODELS_PULL_TIMEOUT_MS); + child.stdout.on('data', d => { stdout += d; }); + child.stderr.on('data', () => {}); + child.on('error', () => { clearTimeout(timer); done(false); }); + child.on('close', (code) => { + clearTimeout(timer); + if (code !== 0) return done(false); + const fullIds = parseAgyModelsOutput(stdout); + done(fullIds.length > 0, fullIds); + }); +}); + +const refreshModels = () => { + if (modelsPullInFlight) return modelsPullInFlight; + modelsPullInFlight = (async () => { + const fullIds = await pullModelsLive(); + if (fullIds) { + const catalog = catalogFromFullIds(fullIds); + if (catalog.length > 0) { + modelCatalog = catalog; + modelsSource = 'live'; + modelsFetchedAt = Date.now(); + persistModelsCache(fullIds); + console.log(`[agy-proxy] Model catalog pulled live from \`agy models\` (${catalog.length} bases, ${fullIds.length} ids)`); + } + } else { + console.warn('[agy-proxy] Live `agy models` pull failed; serving last-known-good catalog'); + } + modelsPullInFlight = null; + })(); + return modelsPullInFlight; +}; + +// Serve-stale refresh check, run on catalog reads. +const maybeRefreshModels = () => { + if (Date.now() - modelsFetchedAt > MODELS_TTL_MS) refreshModels(); +}; + +// Requests block only on the very first load (no cache, no pull yet), +// and only up to the pull timeout; afterwards the catalog is always +// served from memory while refreshes happen in the background. +let initialModelsPull = null; +const ensureInitialModels = async () => { + if (modelsFetchedAt > 0) return; + if (!initialModelsPull) initialModelsPull = refreshModels(); + await Promise.race([ + initialModelsPull, + new Promise(r => setTimeout(r, MODELS_PULL_TIMEOUT_MS + 5000)) + ]); +}; + +loadModelsCache(); +refreshModels(); + +const modelsStatus = () => ({ + source: modelsSource, + bases: modelCatalog.length, + ids: modelCatalog.reduce((n, m) => n + 1 + m.efforts.length, 0), + fetchedAt: modelsFetchedAt ? new Date(modelsFetchedAt).toISOString() : null, + ttlMs: MODELS_TTL_MS +}); + const resolveModelAndEffort = (requestedModel, requestedEffort) => { let modelStr = (requestedModel || 'gemini-3.8-flash').toLowerCase().trim(); let effort = requestedEffort ? requestedEffort.toLowerCase().trim() : null; @@ -171,8 +327,8 @@ const resolveModelAndEffort = (requestedModel, requestedEffort) => { } } - // Find base model config - const modelConfig = MODELS.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')); + // Find base model config (in the live / last-known-good catalog) + const modelConfig = modelCatalog.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')); if (!modelConfig) return null; // Resolve effort @@ -629,35 +785,40 @@ const server = http.createServer((req, res) => { engine: 'agy-stream-json-resident', defaultModel: 'gemini-3.8-flash-medium', activeSessions: sessionStore.size, + models: modelsStatus(), warm: warmStatus() }, null, 2)); return; } - // Models catalog + // Models catalog (live-pulled from `agy models`, see above) 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: 'antigravity-agy' - }); - for (const eff of m.efforts) { + (async () => { + await ensureInitialModels(); + maybeRefreshModels(); + const now = Math.floor(Date.now() / 1000); + const data = []; + + for (const m of modelCatalog) { data.push({ - id: `${m.id}-${eff}`, + id: m.id, object: 'model', created: now, owned_by: 'antigravity-agy' }); + for (const eff of m.efforts) { + data.push({ + id: `${m.id}-${eff}`, + object: 'model', + created: now, + owned_by: 'antigravity-agy' + }); + } } - } - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ object: 'list', data }, null, 2)); + })(); return; } @@ -685,8 +846,14 @@ const server = http.createServer((req, res) => { const stream = Boolean(body.stream); const requestedEffort = body.reasoning_effort || body.effort || (body.options && (body.options.reasoning_effort || body.options.effort)); + await ensureInitialModels(); + maybeRefreshModels(); const resolved = resolveModelAndEffort(body.model, requestedEffort); if (!resolved) { + // Judged against the current live / last-known-good list; a + // miss also triggers an async re-pull so a model agy gained + // since the last pull is picked up without waiting for TTL. + refreshModels(); res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: `Unknown model: ${body.model}` })); return; @@ -773,9 +940,13 @@ const server = http.createServer((req, res) => { } : null; let result; + const turnStart = Date.now(); try { result = await worker.runTurn(promptText, onDelta); } catch (err) { + const durationMs = Date.now() - turnStart; + console.log(`[agy-proxy] turn reqId=${reqId} model=${fullName} workerPid=${worker.pid} durationMs=${durationMs} status=error`); + try { if (!res.headersSent) res.setHeader('X-Agy-Turn-Ms', String(durationMs)); } catch {} retireWorker({ worker, lk }); if (currentWorker === worker) currentWorker = null; // Fallback retry if resuming failed without output (#678's @@ -818,6 +989,9 @@ const server = http.createServer((req, res) => { // Success: commit the session mapping, keep session workers // resident for their next turn, retire stateless workers (a // replacement spare is already warming). + const durationMs = Date.now() - turnStart; + console.log(`[agy-proxy] turn reqId=${reqId} model=${fullName} workerPid=${worker.pid} durationMs=${durationMs} status=ok`); + try { if (!res.headersSent) res.setHeader('X-Agy-Turn-Ms', String(durationMs)); } catch {} recordConversationId(result.conversationId); if (!lk) retireWorker({ worker, lk }); if (currentWorker === worker) currentWorker = null; diff --git a/bin/agy-proxy.test.mjs b/bin/agy-proxy.test.mjs index 4407a12232..0544e85dd6 100644 --- a/bin/agy-proxy.test.mjs +++ b/bin/agy-proxy.test.mjs @@ -1,18 +1,21 @@ -// Tests for agy-proxy: failure detection (#678), the reconciled model -// list (#1692 + the 2026-10-28 `agy models` reconciliation), and the -// resident warm stream-json serving path. +// Tests for agy-proxy: failure detection (#678), the live-pulled model +// list (fleet live-pull rule, 2026-10-28; #1692's unknown-model 400 is +// judged against it), and the resident warm stream-json serving path. // Run: node --test bin/agy-proxy.test.mjs // // The proxy now holds resident `agy` processes speaking // `--input-format stream-json`: prompts arrive on the child's stdin as // NDJSON `{"event":"user","message":{"content":...}}` lines and each -// turn ends with a `result` event. These tests put a stub `agy` at +// turn ends with a `result` event. The served model list is pulled +// live from `agy models`. These tests put a stub `agy` at // $HOME/.local/bin/agy (the proxy's binary resolution reaches it when -// no system agy exists) that speaks that protocol: it emits an `init` -// event at spawn, then one reply per stdin line, keyed on markers in -// the prompt — a run that dies non-zero must be reported as an error, -// never as a successful 'stop' (in stream mode always, in non-stream -// mode also when the run produced partial output first). +// no system agy exists) that speaks that protocol AND answers +// `agy models` with a TSV list including a test-only model no static +// array could contain: it emits an `init` event at spawn, then one +// reply per stdin line, keyed on markers in the prompt — a run that +// dies non-zero must be reported as an error, never as a successful +// 'stop' (in stream mode always, in non-stream mode also when the run +// produced partial output first). import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; @@ -25,6 +28,27 @@ import { fileURLToPath } from 'node:url'; const binDir = path.dirname(fileURLToPath(import.meta.url)); const STUB = `#!/bin/sh +if [ "$1" = "models" ]; then + if [ -n "$AGY_STUB_FAIL_MODELS" ]; then + echo "stub agy: models unavailable" >&2 + exit 1 + fi + printf '%s\\t%s\\n' 'gemini-4-argon-medium' 'Gemini 4 Argon (Medium)' + printf '%s\\t%s\\n' 'gemini-4-argon-high' 'Gemini 4 Argon (High)' + printf '%s\\t%s\\n' 'gemini-4-argon-low' 'Gemini 4 Argon (Low)' + printf '%s\\t%s\\n' 'gemini-3.8-flash-high' 'Gemini 3.8 Flash (High)' + printf '%s\\t%s\\n' 'gemini-3.8-flash-medium' 'Gemini 3.8 Flash (Medium)' + printf '%s\\t%s\\n' 'gemini-3.8-flash-low' 'Gemini 3.8 Flash (Low)' + printf '%s\\t%s\\n' 'claude-opus-5-5-low' 'Claude Opus 5.5 (Low)' + printf '%s\\t%s\\n' 'claude-opus-5-5-medium' 'Claude Opus 5.5 (Medium)' + printf '%s\\t%s\\n' 'claude-opus-5-5-high' 'Claude Opus 5.5 (High)' + printf '%s\\t%s\\n' 'claude-sonnet-5-5-low' 'Claude Sonnet 5.5 (Low)' + printf '%s\\t%s\\n' 'claude-sonnet-5-5-medium' 'Claude Sonnet 5.5 (Medium)' + printf '%s\\t%s\\n' 'claude-sonnet-5-5-high' 'Claude Sonnet 5.5 (High)' + printf '%s\\t%s\\n' 'gpt-oss-120b-medium' 'GPT-OSS 120B (Medium)' + printf '%s\\t%s\\n' 'gemini-9-testonly-medium' 'Gemini 9 Testonly (Medium)' + exit 0 +fi conv="" prev="" for a in "$@"; do @@ -63,7 +87,7 @@ const freePort = () => new Promise((resolve, reject) => { }); }); -const startProxy = async () => { +const startProxy = async (extraEnv = {}) => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'agy-proxy-test-')); const home = path.join(tmp, 'home'); fs.mkdirSync(path.join(home, '.local', 'bin'), { recursive: true }); @@ -74,7 +98,8 @@ const startProxy = async () => { ...process.env, HOME: home, XDG_STATE_HOME: path.join(tmp, 'state'), - AGY_PROXY_PORT: String(port) + AGY_PROXY_PORT: String(port), + ...extraEnv }, stdio: ['ignore', 'pipe', 'pipe'] }); @@ -218,6 +243,7 @@ test('session requests reuse one resident worker (same pid across turns)', async assert.equal(secondBody.choices[0].message.content, 'Hello world'); const pid2 = second.headers.get('x-agy-worker-pid'); assert.equal(pid2, pid1, 'second turn of a session must run on the same resident worker'); + assert.ok(Number(second.headers.get('x-agy-turn-ms')) >= 0, 'responses must carry per-turn timing (x-agy-turn-ms)'); const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); assert.equal(health.engine, 'agy-stream-json-resident'); @@ -239,7 +265,7 @@ test('a pre-warmed spare is ready before the first stateless request', async (t) } }); -test("unknown model is a 400, never a silent fallback; the served list is the `agy models` list", async (t) => { +test("unknown model is a 400, never a silent fallback; the served list is the live `agy models` list", async (t) => { const { port, stop } = await startProxy(); t.after(stop); const messages = [{ role: "user", content: "hi" }]; @@ -252,8 +278,9 @@ test("unknown model is a 400, never a silent fallback; the served list is the `a const listRes = await fetch(`http://127.0.0.1:${port}/v1/models`); const list = JSON.parse(await listRes.text()); const ids = list.data.map((m) => m.id); - // `agy models` (1.2.16, 2026-10-28) lists exactly these 13 ids; the - // proxy serves each base plus its per-effort variants. + // The stub's `agy models` answer lists these 13 real ids (matching + // agy 1.2.16 on 2026-10-28); the proxy serves each base plus its + // per-effort variants, sourced live from that answer. for (const id of [ "gemini-4-argon", "gemini-4-argon-low", "gemini-4-argon-medium", "gemini-4-argon-high", "gemini-3.8-flash", "gemini-3.8-flash-low", "gemini-3.8-flash-medium", "gemini-3.8-flash-high", @@ -288,3 +315,53 @@ test("unknown model is a 400, never a silent fallback; the served list is the `a const opus = JSON.parse(await opusRes.text()); assert.equal(opus.model, "claude-opus-5-5-high"); }); + +test('model list is sourced live: a model only the stub`s `agy models` reports is served', async (t) => { + const { port, stop } = await startProxy(); + t.after(stop); + const messages = [{ role: 'user', content: 'hi' }]; + + const deadline = Date.now() + 5000; + let health; + for (;;) { + health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); + if (health.models.source === 'live') break; + if (Date.now() > deadline) break; + await new Promise(r => setTimeout(r, 50)); + } + assert.equal(health.models.source, 'live', 'catalog must come from the live pull'); + + const listRes = await fetch(`http://127.0.0.1:${port}/v1/models`); + const list = JSON.parse(await listRes.text()); + const ids = list.data.map((m) => m.id); + assert.ok(ids.includes('gemini-9-testonly'), 'live list must include the stub-only base'); + assert.ok(ids.includes('gemini-9-testonly-medium'), 'live list must include the stub-only variant'); + + const res = await post(port, { model: 'gemini-9-testonly', messages }); + assert.equal(res.status, 200, 'a model from the live list must be served, not 400ed'); + const body = JSON.parse(await res.text()); + assert.equal(body.model, 'gemini-9-testonly-medium'); + assert.equal(body.choices[0].message.content, 'Hello world'); +}); + +test('live pull failure falls back to the last-known-good catalog; unknowns still 400', async (t) => { + const { port, stop } = await startProxy({ AGY_STUB_FAIL_MODELS: '1' }); + t.after(stop); + const messages = [{ role: 'user', content: 'hi' }]; + + const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); + assert.ok(['cache', 'fallback'].includes(health.models.source), `expected a last-known-good source, got ${health.models.source}`); + + const listRes = await fetch(`http://127.0.0.1:${port}/v1/models`); + const list = JSON.parse(await listRes.text()); + const ids = list.data.map((m) => m.id); + assert.ok(ids.includes('gemini-4-argon-medium'), 'fallback catalog must still serve Argon'); + + const okRes = await post(port, { model: 'gemini-4-argon', messages }); + assert.equal(okRes.status, 200); + await okRes.text(); + + const badRes = await post(port, { model: 'gemini-9-nonexistent', messages }); + assert.equal(badRes.status, 400, 'unknown ids are 400 against the fallback list too'); + await badRes.text(); +}); From fe5dc6923882f3ee7a1fffb6852df7a3c59581b4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 15:40:02 -0500 Subject: [PATCH 3/3] =?UTF-8?q?wip:=20proxy=20+=20flake.lock=20changes=20r?= =?UTF-8?q?escued=20from=20the=20parked=20primary=20(Muse,=202026-10-28)?= =?UTF-8?q?=20=E2=80=94=20work=20continues=20in=20the=20branch=20worktree;?= =?UTF-8?q?=20PR=20#1759?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/antigravity-ls-proxy.mjs | 16 +++-- bin/claude-code-proxy.mjs | 57 ++++++++++++++++- bin/claude-code-proxy.test.mjs | 5 +- bin/clef-proxy.mjs | 67 +++++++++++++++++++ bin/codex-proxy.mjs | 113 +++++++++++++++++++++++++++++---- bin/commandcode-proxy.mjs | 80 ++++++++++++++++++++--- bin/design-code-proxy.mjs | 113 +++++++++++++++++++++++++++++---- flake.lock | 8 +-- 8 files changed, 412 insertions(+), 47 deletions(-) diff --git a/bin/antigravity-ls-proxy.mjs b/bin/antigravity-ls-proxy.mjs index f098156419..d5890ca7bb 100755 --- a/bin/antigravity-ls-proxy.mjs +++ b/bin/antigravity-ls-proxy.mjs @@ -406,9 +406,13 @@ const lsManager = new LanguageServerManager(); process.on('SIGINT', () => { lsManager.cleanup(); process.exit(0); }); process.on('SIGTERM', () => { lsManager.cleanup(); process.exit(0); }); -// The language server's model catalog (id -> { model enum, displayName }), cached -// briefly so each chat request doesn't re-fetch it. Empty when the server is -// unreachable, in which case only the static MODEL_MAP can resolve. +// The language server's model catalog (id -> { model enum, displayName }), +// pulled LIVE from the server's GetAvailableModels RPC (live-model rule, +// 2026-10-28) and cached for 60s so each chat request doesn't re-fetch +// it. Last-known-good: a failed refresh returns the previous successful +// catalog (not an empty one), so a transient server outage never shrinks +// the resolvable set; only a proxy that has never reached the server +// resolves from the static MODEL_MAP floor alone. let liveCatalogCache = { at: 0, models: {} }; const getLiveCatalog = async () => { if (Date.now() - liveCatalogCache.at < 60_000) return liveCatalogCache.models; @@ -416,7 +420,8 @@ const getLiveCatalog = async () => { const live = await lsManager.callRpc('GetAvailableModels', {}); liveCatalogCache = { at: Date.now(), models: live?.response?.models || {} }; } catch { - return {}; + // Keep { at } unchanged so the next request retries the live pull. + return liveCatalogCache.models; } return liveCatalogCache.models; }; @@ -718,8 +723,7 @@ const server = http.createServer(async (req, res) => { } try { - const live = await lsManager.callRpc('GetAvailableModels', {}); - const liveModels = live?.response?.models || {}; + const liveModels = await getLiveCatalog(); for (const [k, v] of Object.entries(liveModels)) { if (!registered.has(k)) { registered.add(k); diff --git a/bin/claude-code-proxy.mjs b/bin/claude-code-proxy.mjs index 5889b3f1d8..221148ea15 100644 --- a/bin/claude-code-proxy.mjs +++ b/bin/claude-code-proxy.mjs @@ -66,6 +66,61 @@ const MODELS = [ ]; const DEFAULT_MODEL = 'claude-haiku-5-5'; +// --- Model list sourcing (live-model rule, 2026-10-28 — DOCUMENTED +// EXCEPTION) --------------------------------------------------------------- +// This provider has NO live catalog to pull: +// * the Claude Code CLI exposes no list command (its subcommands are +// agents/auth/doctor/mcp/plugin/...; --model takes an alias or a full +// name but nothing enumerates the account's models), and +// * Anthropic's GET /v1/models rejects this account's Claude Code OAuth +// token with 403 oauth_not_allowed_for_organization (verified live +// 2026-10-28, with and without the oauth beta header). The API-key +// route would be pay-as-you-go billing, which this proxy deliberately +// never uses (it strips ANTHROPIC_API_KEY from child env — plan only). +// Closest truthful refresh: the served list is the verified floor above +// UNION every model id found in the CLI's own recent session records +// (~/.claude/projects/**/*.jsonl message.model fields) — ids the CLI has +// provably served under this account. Rescanned on a 60s TTL; a model +// appears after its first real use and never from an unverified catalog. +const PROJECTS_DIR = process.env.CLAUDE_CODE_PROXY_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects'); +const OBSERVED_TTL_MS = 60 * 1000; +let observedCache = { at: 0, ids: [] }; +const getObservedModelIds = () => { + if (Date.now() - observedCache.at < OBSERVED_TTL_MS) return observedCache.ids; + const found = new Set(); + try { + const files = []; + for (const entry of fs.readdirSync(PROJECTS_DIR, { recursive: true, withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue; + const full = path.join(entry.parentPath || entry.path, entry.name); + try { files.push({ full, mtime: fs.statSync(full).mtimeMs }); } catch {} + } + files.sort((a, b) => b.mtime - a.mtime); + for (const { full } of files.slice(0, 60)) { + try { + const fd = fs.openSync(full, 'r'); + const buf = Buffer.alloc(1024 * 1024); + const n = fs.readSync(fd, buf, 0, buf.length, 0); + fs.closeSync(fd); + for (const m of buf.toString('utf8', 0, n).matchAll(/"model"\s*:\s*"(claude-[a-z0-9][a-z0-9.-]*)"/g)) { + found.add(m[1]); + } + } catch {} + } + } catch {} + observedCache = { at: Date.now(), ids: [...found].sort() }; + return observedCache.ids; +}; + +const getServedModels = () => { + const data = MODELS.map(m => ({ id: m.id, name: m.name })); + const known = new Set(data.map(m => m.id)); + for (const id of getObservedModelIds()) { + if (!known.has(id)) data.push({ id, name: `${id} (Claude Code, observed)` }); + } + return data; +}; + const findClaudeBinary = () => { const candidates = [ process.env.CLAUDE_CODE_BIN, @@ -643,7 +698,7 @@ const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ object: 'list', - data: MODELS.map(m => ({ id: m.id, object: 'model', created: now, owned_by: 'anthropic-claude-code' })) + data: getServedModels().map(m => ({ id: m.id, object: 'model', created: now, owned_by: 'anthropic-claude-code' })) }, null, 2)); return; } diff --git a/bin/claude-code-proxy.test.mjs b/bin/claude-code-proxy.test.mjs index 618647a00a..938f6902a0 100644 --- a/bin/claude-code-proxy.test.mjs +++ b/bin/claude-code-proxy.test.mjs @@ -72,6 +72,7 @@ const startProxy = async () => { CLAUDE_CODE_BIN: stubPath, CLAUDE_CODE_PROXY_WORKDIR: path.join(tmp, 'work'), CLAUDE_CODE_PROXY_SESSION_FILE: path.join(tmp, 'sessions.json'), + CLAUDE_CODE_PROXY_PROJECTS_DIR: path.join(tmp, 'no-projects'), CLAUDE_CODE_PROXY_EGRESS: '', STUB_LOG: logPath, XDG_STATE_HOME: path.join(tmp, 'state') @@ -110,7 +111,9 @@ test('health + models catalog', async (t) => { assert.equal(health.service, 'claude-code-proxy'); assert.equal(health.engine, 'claude-stream-json-resident'); const models = await (await fetch(`${base}/v1/models`)).json(); - assert.deepEqual(models.data.map(m => m.id), ['claude-haiku-5-5']); + // The verified static floor; the observed-models union is empty here + // because CLAUDE_CODE_PROXY_PROJECTS_DIR points at an empty test dir. + assert.deepEqual(models.data.map(m => m.id), ['claude-haiku-5-5', 'claude-sonnet-5-5', 'claude-opus-5-5']); }); test('two turns: second turn sends only the newest user message', async (t) => { diff --git a/bin/clef-proxy.mjs b/bin/clef-proxy.mjs index ea250a6925..a1783da593 100755 --- a/bin/clef-proxy.mjs +++ b/bin/clef-proxy.mjs @@ -102,6 +102,61 @@ const resolveModel = (model) => { return '@cf/cloudflare/clef-flash'; }; +// --- Live model list (2026-10-28 standing rule) --------------------------- +// This proxy is a single-purpose SystemOne endpoint, not a chat router: +// its model universe is the Clef family inside Cloudflare's Workers AI +// catalog. That catalog IS queryable live — GET +// /client/v4/accounts//ai/models/search with the same inference token +// the data path uses — so GET /v1/models serves the live Clef subset +// (which gained @cf/cloudflare/clef-omni upstream without any code change +// here) with a 5-minute TTL cache and last-known-good fallback to the +// static floor below. +const STATIC_MODELS = ['@cf/cloudflare/clef', '@cf/cloudflare/clef-flash']; +const MODEL_LIST_TTL_MS = 5 * 60 * 1000; +let liveModelCache = { at: 0, models: null }; +let liveModelRefresh = null; + +const refreshLiveModels = (authHeader) => { + if (liveModelRefresh) return liveModelRefresh; + liveModelRefresh = (async () => { + try { + const { accountId, token } = getCredentials(authHeader); + if (!token) throw new Error('no Cloudflare token available'); + const names = []; + for (let page = 1; page <= 10; page++) { + const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/models/search?per_page=100&page=${page}`; + const res = await fetch(url, { + headers: { 'Authorization': `Bearer ${token}` }, + signal: AbortSignal.timeout(10000) + }); + if (!res.ok) throw new Error(`models search HTTP ${res.status}`); + const data = await res.json(); + const result = Array.isArray(data?.result) ? data.result : []; + if (result.length === 0) break; + for (const m of result) { + if (typeof m?.name === 'string' && m.name.toLowerCase().includes('clef')) names.push(m.name); + } + if (result.length < 100) break; + } + if (names.length === 0) throw new Error('models search returned no Clef models'); + liveModelCache = { at: Date.now(), models: [...new Set(names)].sort() }; + } catch (err) { + console.warn(`[clef-proxy] live model refresh failed (${err.message}); serving last-known-good`); + } finally { + liveModelRefresh = null; + } + return liveModelCache.models || STATIC_MODELS; + })(); + return liveModelRefresh; +}; + +const getServedModels = async (authHeader) => { + if (liveModelCache.models && Date.now() - liveModelCache.at <= MODEL_LIST_TTL_MS) { + return liveModelCache.models; + } + return refreshLiveModels(authHeader); +}; + const server = http.createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host || HOST}`); const pathname = url.pathname.replace(/\/+$/, '') || '/'; @@ -118,6 +173,18 @@ const server = http.createServer(async (req, res) => { return; } + if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { + getServedModels(req.headers['authorization']).then((models) => { + const now = Math.floor(Date.now() / 1000); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + object: 'list', + data: models.map(id => ({ id, object: 'model', created: now, owned_by: 'cloudflare-workers-ai' })) + }, null, 2)); + }); + return; + } + if (req.method === 'POST' && (pathname === '/v1/systemone' || pathname === '/systemone' || pathname === '/')) { let bodyText = ''; req.on('data', chunk => { diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index d9a21e38b2..9452451757 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import http from 'node:http'; import net from 'node:net'; -import { spawn, execSync } from 'node:child_process'; +import { spawn, execSync, execFile } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; @@ -78,7 +78,14 @@ conn.commit() } }; -const MODELS = [ +// Static floor for the served model list (live-model rule, 2026-10-28): +// only the last-resort fallback. The served list is pulled LIVE from +// `codex debug models` (the CLI's own rendering of the upstream catalog; +// see refreshLiveModels below) with a 60s TTL cache and last-known-good +// fallback. All slugs the CLI reports are served, including +// visibility:"hide" ones (gpt-reserve, codex-auto-review) — this floor +// deliberately served them too. +const STATIC_MODELS = [ { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, { id: 'gpt-6-astra', name: 'GPT-6 Astra (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, { id: 'gpt-6-sol', name: 'GPT-6 Sol (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, @@ -107,6 +114,75 @@ const findCodexBinary = () => { const CODEX_BIN = findCodexBinary(); +// --- Live model list ------------------------------------------------------- +// `codex debug models` prints the CLI's current upstream catalog as JSON +// ({models:[{slug, display_name, supported_reasoning_levels:[{effort}], +// default_reasoning_level, visibility}]}). It answers in ~1s from the +// CLI's own fetch/cache, so the TTL is short (60s) and a stale read is +// refreshed inline; any failure serves the last-known-good (or floor). +const MODEL_LIST_TTL_MS = 60 * 1000; +let liveModelCache = { at: 0, models: null }; +let liveModelRefresh = null; + +const parseDebugModels = (text) => { + const parsed = JSON.parse(text); + const arr = Array.isArray(parsed) ? parsed : parsed.models; + if (!Array.isArray(arr)) throw new Error('debug models: no models array'); + const models = []; + for (const m of arr) { + if (!m || typeof m.slug !== 'string' || !m.slug) continue; + const efforts = (m.supported_reasoning_levels || []).map(r => r && r.effort).filter(Boolean); + if (efforts.length === 0) continue; + models.push({ + id: m.slug, + name: `${m.display_name || m.slug} (codex)`, + efforts, + defaultEffort: efforts.includes(m.default_reasoning_level) ? m.default_reasoning_level : efforts[0] + }); + } + if (models.length < 3) throw new Error(`debug models: only ${models.length} usable models`); + return models; +}; + +const refreshLiveModels = () => { + if (liveModelRefresh) return liveModelRefresh; + liveModelRefresh = new Promise((resolve) => { + execFile(CODEX_BIN, ['debug', 'models'], { + timeout: 30000, maxBuffer: 16 * 1024 * 1024, input: '' + }, (err, stdout) => { + liveModelRefresh = null; + if (!err) { + try { + liveModelCache = { at: Date.now(), models: parseDebugModels(stdout) }; + } catch (parseErr) { + console.warn(`[codex-proxy] live model parse failed (${parseErr.message}); serving last-known-good`); + } + } else { + console.warn(`[codex-proxy] \`codex debug models\` failed (${err.message}); serving last-known-good`); + } + resolve(liveModelCache.models); + }); + }); + return liveModelRefresh; +}; + +const getModelCatalog = async () => { + if (liveModelCache.models && Date.now() - liveModelCache.at <= MODEL_LIST_TTL_MS) { + return liveModelCache.models; + } + await refreshLiveModels(); + return liveModelCache.models || STATIC_MODELS; +}; + +// Synchronous view for code paths that cannot await: last-known-good or +// the static floor, with a background refresh triggered when stale. +const getModelCatalogSync = () => { + if (!liveModelCache.models || Date.now() - liveModelCache.at > MODEL_LIST_TTL_MS) { + refreshLiveModels(); + } + return liveModelCache.models || STATIC_MODELS; +}; + // Transport selection (#480): 'app-server' (default) talks JSON-RPC to the // long-running codex app-server daemon over its WebSocket-over-Unix control // socket — no per-request CLI boot. 'exec-resume' is the previous warm @@ -122,8 +198,8 @@ const appServerSocketPath = () => process.env.CODEX_APP_SERVER_SOCKET || path.join(os.homedir(), '.codex', 'app-server-control', 'app-server-control.sock'); -const resolveModelAndEffort = (requestedModel, requestedEffort) => { - let rawModel = (requestedModel || 'gpt-6.1-sol').trim(); +const resolveModelAndEffort = (requestedModel, requestedEffort, catalog = getModelCatalogSync()) => { + let rawModel = (requestedModel || '').trim(); // Strip any provider prefix before '/' (e.g. 'openai-codex/', 'codex/', 'openai/', 'chatgpt/') let modelStr = rawModel.replace(/^.*\//, '').toLowerCase().trim(); let effort = requestedEffort ? requestedEffort.toLowerCase().trim() : null; @@ -138,9 +214,15 @@ const resolveModelAndEffort = (requestedModel, requestedEffort) => { } } - // Find base model config - const modelConfig = MODELS.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')) - || MODELS[0]; // default to gpt-6.1-sol + // Find base model config in the live (or last-known-good/floor) catalog. + // No requested model at all -> the catalog's first entry is the default. + // An explicitly requested but unknown id returns null: the caller answers + // a clean 400. It must NEVER silently fall back to a default model (a + // fleet proxy once served a different model than requested with HTTP 200). + const modelConfig = !modelStr + ? catalog[0] + : catalog.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')); + if (!modelConfig) return null; // Resolve effort if (!effort || !modelConfig.efforts.includes(effort)) { @@ -886,7 +968,7 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => }); }); -const server = http.createServer((req, res) => { +const server = http.createServer(async (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', '*'); @@ -913,12 +995,13 @@ const server = http.createServer((req, res) => { return; } - // Models catalog + // Models catalog (live: `codex debug models`, TTL-cached with + // last-known-good/static-floor fallback — see refreshLiveModels) if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { const now = Math.floor(Date.now() / 1000); const data = []; - for (const m of MODELS) { + for (const m of await getModelCatalog()) { data.push({ id: m.id, object: 'model', @@ -952,7 +1035,7 @@ const server = http.createServer((req, res) => { } }); - req.on('end', () => { + req.on('end', async () => { let body; try { body = JSON.parse(bodyText); @@ -964,7 +1047,13 @@ const server = http.createServer((req, res) => { 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 resolvedModel = resolveModelAndEffort(body.model, reqReasoningEffort, await getModelCatalog()); + if (!resolvedModel) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { message: `Unknown model "${body.model}": not in the live Codex catalog (see GET /v1/models)` } })); + return; + } + const { baseModel, effort, fullName } = resolvedModel; const prompt = formatPrompt(body.messages); if (!prompt || prompt.trim().length === 0) { diff --git a/bin/commandcode-proxy.mjs b/bin/commandcode-proxy.mjs index 567f195721..dc3c8add9e 100644 --- a/bin/commandcode-proxy.mjs +++ b/bin/commandcode-proxy.mjs @@ -47,7 +47,7 @@ // needed or read; clients may send the placeholder "commandcode-local" // (accepted and ignored, like the other fleet proxies' *-local keys). import http from 'node:http'; -import { spawn } from 'node:child_process'; +import { spawn, execFile } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; @@ -70,11 +70,16 @@ const PROXY_DIR = path.dirname(fileURLToPath(import.meta.url)); const WORKROOT = process.env.COMMANDCODE_PROXY_WORKDIR || path.join(PROXY_DIR, 'work'); fs.mkdirSync(WORKROOT, { recursive: true }); -// Model ids exactly as `commandcode --list-models` prints them (v1.88.0, -// re-synced live 2026-10-25: 85 models). typesafe/jev is deliberately -// omitted: it is a headless-only decision model taking a JSON -// state/questions payload, not a chat model. -const MODELS = [ +// Static floor for the served model list (live-model rule, 2026-10-28): +// the ids below are only the last-resort fallback. The served list is +// pulled LIVE from `commandcode --list-models` (see refreshLiveModels +// below) with a TTL cache and last-known-good fallback, so a model the +// CLI gains or drops shows up here without a code change. This floor is +// the 2026-10-25 snapshot (85 models, CLI v1.88.0). typesafe/jev is +// deliberately omitted everywhere (including the live parse): it is a +// headless-only decision model taking a JSON state/questions payload, +// not a chat model. +const STATIC_MODELS = [ 'deepseek/deepseek-v4-pro', 'deepseek/deepseek-v4-flash', 'deepseek/deepseek-v4-flash-vision-exp', @@ -212,6 +217,61 @@ const findCommandCodeBinary = () => { const CC_BIN = findCommandCodeBinary(); +// --- Live model list (2026-10-28 standing rule: pull live, never ship a +// static list as the source of truth) ------------------------------------- +// `commandcode --list-models` is authoritative but slow (~28s cold), so +// the pull is asynchronous: requests serve the last-known-good list (or +// the static floor before the first successful pull) and a stale entry +// triggers a background refresh (stale-while-revalidate). TTL 5 min. +const MODEL_LIST_TTL_MS = 5 * 60 * 1000; +let liveModelCache = { at: 0, models: null }; +let liveModelRefresh = null; + +const parseListModelsOutput = (text) => { + const ids = []; + for (const line of String(text).split('\n')) { + const token = line.trim().split(/\s+/)[0] || ''; + // Model ids are vendor/name, claude-* or gpt-*; section headers and + // the "Available models" banner never match this shape. + if (!token.includes('/') && !token.startsWith('claude-') && !token.startsWith('gpt-')) continue; + if (token === 'typesafe/jev') continue; // headless-only, see floor note + if (!ids.includes(token)) ids.push(token); + } + return ids; +}; + +const refreshLiveModels = () => { + if (liveModelRefresh) return liveModelRefresh; + liveModelRefresh = new Promise((resolve) => { + execFile(CC_BIN, ['--list-models'], { + timeout: 120000, maxBuffer: 8 * 1024 * 1024, input: '', env: childEnv() + }, (err, stdout) => { + liveModelRefresh = null; + if (!err) { + const ids = parseListModelsOutput(stdout); + // Sanity floor: a garbled/truncated pull must not shrink the + // served list to near-empty; keep the last-known-good instead. + if (ids.length >= 20) { + liveModelCache = { at: Date.now(), models: ids }; + } else { + console.warn(`[commandcode-proxy] --list-models returned only ${ids.length} ids; keeping last-known-good`); + } + } else { + console.warn(`[commandcode-proxy] --list-models refresh failed (${err.message}); serving last-known-good`); + } + resolve(liveModelCache.models); + }); + }); + return liveModelRefresh; +}; + +const getServedModels = () => { + if (!liveModelCache.models || Date.now() - liveModelCache.at > MODEL_LIST_TTL_MS) { + refreshLiveModels(); // fire-and-forget; serve cache/floor meanwhile + } + return liveModelCache.models || STATIC_MODELS; +}; + const resolveModel = (requestedModel) => { let raw = (requestedModel || '').trim(); if (!raw) return DEFAULT_MODEL; @@ -219,9 +279,10 @@ const resolveModel = (requestedModel) => { // provider name, not part of the model id — but model ids themselves // contain slashes (deepseek/...), so only strip that exact prefix. if (raw.startsWith('commandcode/')) raw = raw.slice('commandcode/'.length); - if (MODELS.includes(raw)) return raw; + const served = getServedModels(); + if (served.includes(raw)) return raw; // CLI also accepts the short name after the last '/'. - const byShort = MODELS.find(m => m.slice(m.lastIndexOf('/') + 1) === raw); + const byShort = served.find(m => m.slice(m.lastIndexOf('/') + 1) === raw); if (byShort) return byShort; // Unknown id: pass through — the CLI may know a newer model than this list. return raw; @@ -779,7 +840,7 @@ const server = http.createServer((req, res) => { // Models catalog if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { const now = Math.floor(Date.now() / 1000); - const data = MODELS.map(id => ({ + const data = getServedModels().map(id => ({ id, object: 'model', created: now, @@ -1222,6 +1283,7 @@ const server = http.createServer((req, res) => { }); server.listen(PORT, HOST, () => { + refreshLiveModels(); // warm the live model list in the background publishEndpoint(); console.log(`[commandcode-proxy] OpenAI-compatible bridge listening on http://${HOST}:${PORT}`); console.log(`[commandcode-proxy] Resolved commandcode binary: ${CC_BIN}`); diff --git a/bin/design-code-proxy.mjs b/bin/design-code-proxy.mjs index 89e6a92752..e857f21392 100755 --- a/bin/design-code-proxy.mjs +++ b/bin/design-code-proxy.mjs @@ -19,6 +19,16 @@ const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxS const DESIGN_SYSTEM_PROMPT = `You are an elite Code & Systems Design Architect. Your core expertise is in software architecture, clean code design, UI/UX design engineering, design tokens, component abstractions, domain-driven design, and maintainable systems patterns. Provide elegant, production-grade architectures and idiomatic design implementations.`; +// Model list sourcing (live-model rule, 2026-10-28 — DOCUMENTED +// EXCEPTION): this proxy's ids are VIRTUAL design personas, not upstream +// model ids — each entry is a curated routing recipe (primary/fallback +// backend + backend model) invented here, so no upstream catalog can be +// pulled for the list itself. The AMR upstream's /v1/models is API-key +// gated and no key is configured for the local-dispatch path. What CAN +// stay live does: the backend model each recipe points at is validated +// against that backend proxy's own live /v1/models (see +// refreshBackendCatalogs below), and an unknown requested id now gets a +// clean 400 instead of the old silent remap onto gemini-3.8-flash. const MODELS = [ { id: 'claude-haiku-5.5', name: 'Claude Haiku 5.5 (Design Code)', primary: { port: ANTIGRAVITY_LS_PORT, model: 'claude-sonnet-5-5' }, fallback: { port: ANTIGRAVITY_LS_PORT, model: 'gemini-3.8-flash' } }, { id: 'gpt-6-luna', name: 'GPT-6 Luna (Design Code)', primary: { port: CODEX_PROXY_PORT, model: 'gpt-6-luna' }, fallback: { port: ANTIGRAVITY_LS_PORT, model: 'gemini-3.8-flash' } }, @@ -40,7 +50,9 @@ const resolveModelConfig = (requestedModel) => { return { modelId: found.id, config: found }; } - // Fallbacks by keyword + // Fallbacks by keyword: a gpt/codex-shaped id is passed to the Codex + // backend under its own name — and the Codex proxy now validates it + // against its live catalog and answers a clean 400 for unknown ids. if (clean.includes('gpt') || clean.includes('codex') || clean.includes('luna') || clean.includes('sol')) { return { modelId: clean, @@ -51,13 +63,52 @@ const resolveModelConfig = (requestedModel) => { }; } - return { - modelId: clean, - config: { - primary: { port: ANTIGRAVITY_LS_PORT, model: 'gemini-3.8-flash' }, - fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } + // Unknown id: refuse (the caller answers 400) rather than silently + // serving a different model than the one requested. + return null; +}; + +// --- Live backend-catalog validation --------------------------------------- +// Background-only (never on the request path): pull each fleet backend's +// live /v1/models on a 60s TTL and record which recipe targets still +// exist upstream. Restricted to the canonical/alt fleet backend ports so +// non-fleet backend overrides are never probed. Dispatch uses the +// last-known-good result: a target proven absent upstream is skipped, and +// if every target is proven absent the request gets a clean 400. +const FLEET_BACKEND_PORTS = new Set([18744, 19744, 18745, 19745]); +const BACKEND_CATALOG_TTL_MS = 60 * 1000; +let backendCatalogCache = { at: 0, byPort: new Map() }; +let backendCatalogRefresh = null; + +const refreshBackendCatalogs = () => { + if (backendCatalogRefresh) return backendCatalogRefresh; + if (Date.now() - backendCatalogCache.at < BACKEND_CATALOG_TTL_MS && backendCatalogCache.at > 0) { + return Promise.resolve(backendCatalogCache); + } + backendCatalogRefresh = (async () => { + const ports = new Set(); + for (const m of MODELS) { ports.add(m.primary.port); if (m.fallback) ports.add(m.fallback.port); } + const byPort = new Map(backendCatalogCache.byPort); + for (const port of ports) { + if (!FLEET_BACKEND_PORTS.has(port)) continue; + try { + const res = await fetch(`http://127.0.0.1:${port}/v1/models`, { signal: AbortSignal.timeout(2500) }); + if (!res.ok) continue; + const data = await res.json(); + if (Array.isArray(data?.data)) byPort.set(port, new Set(data.data.map(d => d.id))); + } catch { /* keep last-known-good for this port */ } } - }; + backendCatalogCache = { at: Date.now(), byPort }; + backendCatalogRefresh = null; + return backendCatalogCache; + })(); + return backendCatalogRefresh; +}; + +const backendTargetKnown = (target) => { + const catalog = backendCatalogCache.byPort.get(target.port); + if (!catalog) return null; // never pulled / not a fleet port: unvalidated + return catalog.has(target.model); }; const hasUpstreamKey = (authHeader) => { @@ -88,12 +139,23 @@ const server = http.createServer((req, res) => { // Health if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { + refreshBackendCatalogs(); // background live validation of recipe targets + const targetState = {}; + for (const m of MODELS) { + targetState[m.id] = { + primary: backendTargetKnown(m.primary), + fallback: m.fallback ? backendTargetKnown(m.fallback) : null + }; + } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', service: 'design-code-proxy', port: PORT, - availableModels: MODELS.map(m => m.id) + availableModels: MODELS.map(m => m.id), + modelListSource: 'virtual routing recipes (documented exception); backend targets validated live', + backendTargetsCheckedAt: backendCatalogCache.at ? new Date(backendCatalogCache.at).toISOString() : null, + backendTargets: targetState }, null, 2)); return; } @@ -183,7 +245,15 @@ const server = http.createServer((req, res) => { const dispatchWithFallback = (body, clientRes) => { const reqModel = body.model; - const { modelId, config } = resolveModelConfig(reqModel); + const resolved = resolveModelConfig(reqModel); + if (!resolved) { + clientRes.writeHead(400, { 'Content-Type': 'application/json' }); + clientRes.end(JSON.stringify({ + error: { message: `Unknown model "${reqModel}": not a design-code model (see GET /v1/models)` } + })); + return; + } + const { modelId, config } = resolved; // Prepare messages with design prompt const messages = Array.isArray(body.messages) ? [...body.messages] : []; @@ -327,12 +397,27 @@ const dispatchWithFallback = (body, clientRes) => { localReq.end(); }; - // Try primary target, then fallback if needed - tryTarget(config.primary, err => { + // Try primary target, then fallback if needed — skipping any target + // the live backend catalogs have proven absent (last-known-good view; + // unvalidated targets are always tried). If every target is proven + // absent upstream, refuse with 400 rather than silently remapping. + const allTargets = [config.primary, config.fallback] + .filter(Boolean) + .filter((t, i, arr) => i === 0 || t.port !== arr[0].port || t.model !== arr[0].model); + const liveTargets = allTargets.filter(t => backendTargetKnown(t) !== false); + if (liveTargets.length === 0) { + clientRes.writeHead(400, { 'Content-Type': 'application/json' }); + clientRes.end(JSON.stringify({ + error: { message: `Model "${reqModel}" routes only to backend models absent from the live backend catalogs` } + })); + return; + } + const [firstTarget, secondTarget] = liveTargets; + tryTarget(firstTarget, err => { if (clientRes.headersSent) return; - if (config.fallback && (config.fallback.port !== config.primary.port || config.fallback.model !== config.primary.model)) { - console.log(`[design-code-proxy] Falling back for '${reqModel}' to 127.0.0.1:${config.fallback.port} (${config.fallback.model})`); - tryTarget(config.fallback, fallbackErr => { + if (secondTarget) { + console.log(`[design-code-proxy] Falling back for '${reqModel}' to 127.0.0.1:${secondTarget.port} (${secondTarget.model})`); + tryTarget(secondTarget, fallbackErr => { if (!clientRes.headersSent) { clientRes.writeHead(502, { 'Content-Type': 'application/json' }); clientRes.end(JSON.stringify({ diff --git a/flake.lock b/flake.lock index 398353f602..41eacd685f 100644 --- a/flake.lock +++ b/flake.lock @@ -3192,11 +3192,11 @@ "nixpkgs": "nixpkgs_20" }, "locked": { - "lastModified": 1792954829, - "narHash": "sha256-5KgtGYCuLMT+D/tqzSIzycL96rOTRedrBrQl764llgo=", + "lastModified": 1793209014, + "narHash": "sha256-GhbjS5R0CNuVXbTckZrxxzcO/5E+t+z+Qmtt9vulHjc=", "owner": "developing-today", "repo": "opencode", - "rev": "56590c57d084b600f915a9d77a5636b9786d7a56", + "rev": "ad881d2b2634bae38bd07c4c858c8cc4a1f0f71c", "type": "github" }, "original": { @@ -4119,4 +4119,4 @@ }, "root": "root", "version": 7 -} \ No newline at end of file +}