From 1ad7042c3e5bb3a327633200ef2d1c93f7256c69 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:05:09 -0600 Subject: [PATCH] chore(proxy): decommission the retired CLI proxy lineage (Drew, 2026-11-06) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the dead provider-proxy infrastructure whose providers now live in the opencode fork as native wire-emulation providers: - claude-code (:18749) and commandcode (:18748): repointed to native providers 2026-11-05 (code#6117, opencode#1749); remove bin programs, tests, systemd units, port lets, session variables and guard rows (the proxy-port guard had been failing on their stale rows since the repoint). node-net-defaults.mjs goes too — its only consumer was commandcode-proxy-start.sh. - antigravity-ls (:18745) and agy (:18743): units retired 2026-10-30; remove the bin programs and tests that remained as history. - design-code (:18746): unit retired 2026-11-03; remove bin program and test. - antigravity-direct (:18751): bin and unit were already removed 2026-11-04; remaining references are the live native provider id. Also: provider-catalog-sync drops the four dead proxy enumeration entries (its tests re-vehicle onto the surviving chatgpt/codex door), proxy-port.test drops the retired doors from its parse-site inventory, cli-proxy-workroots.test is removed (its three-proxy premise is gone), and stale live-presenting references are date-corrected in opencode.jsonc, the OpenClaw docs and PORTS.md (18748/18749 now retired — free). Untouched, verified live: muse-proxy (:18747, unit running, muse-direct seated in routes), codex-proxy (:18744, socket-activated), proxy-port/proxy-relay/proxy-supervise shared helpers, the sanctioned runtime CONNECT proxy (:3130), mcpx and fleet proxies. Verified: check-proxy-port-fallbacks.sh passes (2 proxies); node --test bin/*.test.mjs 237/237; both edited Nix files parse. --- .github/scripts/check-proxy-port-fallbacks.sh | 18 +- .github/workflows/bin-tests.yml | 4 +- .opencode/opencode.jsonc | 27 +- bin/agy-proxy.mjs | 1164 -------------- bin/agy-proxy.test.mjs | 552 ------- bin/antigravity-ls-proxy.mjs | 1139 -------------- bin/antigravity-ls-proxy.test.mjs | 461 ------ bin/claude-code-proxy.mjs | 812 ---------- bin/claude-code-proxy.test.mjs | 253 ---- bin/cli-proxy-workroots.test.mjs | 70 - bin/commandcode-proxy-start.sh | 17 - bin/commandcode-proxy.mjs | 1349 ----------------- bin/commandcode-proxy.test.mjs | 338 ----- bin/design-code-proxy.mjs | 525 ------- bin/design-code-proxy.test.mjs | 505 ------ bin/muse-proxy.mjs | 9 +- bin/openchamber-start.sh | 2 +- bin/provider-catalog-sync.mjs | 10 +- bin/provider-catalog-sync.test.mjs | 20 +- bin/proxy-port.test.mjs | 33 +- home/common/default.nix | 161 +- home/openclaw/README.md | 15 +- home/openclaw/default.nix | 19 +- home/openclaw/workspace/QUOTAS.md | 2 +- home/openclaw/workspace/TOOLS.md | 6 - node-net-defaults.mjs | 21 - pm-stack/PORTS.md | 4 +- 27 files changed, 136 insertions(+), 7400 deletions(-) delete mode 100755 bin/agy-proxy.mjs delete mode 100644 bin/agy-proxy.test.mjs delete mode 100755 bin/antigravity-ls-proxy.mjs delete mode 100644 bin/antigravity-ls-proxy.test.mjs delete mode 100644 bin/claude-code-proxy.mjs delete mode 100644 bin/claude-code-proxy.test.mjs delete mode 100644 bin/cli-proxy-workroots.test.mjs delete mode 100755 bin/commandcode-proxy-start.sh delete mode 100644 bin/commandcode-proxy.mjs delete mode 100644 bin/commandcode-proxy.test.mjs delete mode 100755 bin/design-code-proxy.mjs delete mode 100644 bin/design-code-proxy.test.mjs delete mode 100644 node-net-defaults.mjs diff --git a/.github/scripts/check-proxy-port-fallbacks.sh b/.github/scripts/check-proxy-port-fallbacks.sh index a81509dc64..7b0d6a1b1e 100755 --- a/.github/scripts/check-proxy-port-fallbacks.sh +++ b/.github/scripts/check-proxy-port-fallbacks.sh @@ -25,8 +25,9 @@ # Retired 2026-11-04 (opencode#1414): the antigravity-direct door itself # is gone — let, unit, session var, bin program and this row removed in # one change; the provider id lives on over the in-fork native provider. -# Their bin/ scripts remain in the repo as history, uninvoked, and -# their disabled opencode.jsonc providers keep the old fallbacks; see +# Their bin/ scripts remained in the repo as history until the +# 2026-11-06 proxy-infra decommission removed them; their disabled +# opencode.jsonc providers keep the old fallbacks; see # the retirement note in home/common/default.nix. They are deliberately # NOT rows here — restoring one means restoring its let from git # history and re-adding its row in the same change (#2961). @@ -47,11 +48,20 @@ # outright (7b51087cc removed its let and unit; a0755459e removed its # opencode.jsonc door shell), so its row is gone from the table below, # same pattern as the 2026-10-30 retirements; bin/design-code-proxy.mjs -# remains as history. The codex door program (:18744) is NOT retired — +# remained as history until the 2026-11-06 proxy-infra decommission +# removed it. The codex door program (:18744) is NOT retired — # only its opencode.jsonc provider was (1dad07b4a re-seated the # openai-codex routes onto openai-plan) — so the CODEX row keeps its # let and bin/ fallback checks with has_config "no": there is no # baseURL left in opencode.jsonc for it to match. +# +# Retired 2026-11-06 (Drew, proxy-infra decommission): the +# commandcode door (:18748) and the claude-code door (:18749) are +# gone the same way — let, unit, session var, bin program and their +# rows below removed in one change. Both providers were repointed +# to the fork's native wire-emulation providers on 2026-11-05 +# (code#6117, opencode#1749); this guard had been failing on their +# stale rows since that repoint removed the jsonc baseURLs. set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -62,8 +72,6 @@ config_file="$repo_root/.opencode/opencode.jsonc" proxies=( "CODEX_PROXY_PORT|codexProxyPort|bin/codex-proxy.mjs|no" "MUSE_PROXY_PORT|museProxyPort|bin/muse-proxy.mjs|yes" - "COMMANDCODE_PROXY_PORT|commandcodeProxyPort|bin/commandcode-proxy.mjs|yes" - "CLAUDE_CODE_PROXY_PORT|claudeCodeProxyPort|bin/claude-code-proxy.mjs|yes" ) failed=0 diff --git a/.github/workflows/bin-tests.yml b/.github/workflows/bin-tests.yml index a4bf482ead..ade54b18f3 100644 --- a/.github/workflows/bin-tests.yml +++ b/.github/workflows/bin-tests.yml @@ -4,9 +4,9 @@ name: bin tests # # Test verification for the bin/ provider proxies (#6081). # -# 19 of the 20 bin/*.test.mjs suites — the regression tests for the +# 13 of the 14 bin/*.test.mjs suites — the regression tests for the # live provider proxies in bin/ (muse-proxy, codex-proxy, -# claude-code-proxy, agy-proxy, proxy-supervise, ...) — were run by +# proxy-supervise, ...) — were run by # no workflow; only bin/check-opencode-metered-providers.test.mjs # had wiring (opencode-config-guard). The rest executed only when a # human remembered to run node --test by hand, so pins regressed diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index 4f4dcea5b7..d5c434d0a0 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -35,10 +35,14 @@ // shows a zero-traffic window. // - "claude-code" was TEMPORARILY disabled (2026-10-27, Drew; RE-ENABLED 2026-11-06, Drew - see the dated note above disabled_providers): the Claude // plan is on the FREE tier for now and the API may be down. The setup - // itself is confirmed working — the proxy (:18749) is live and serves - // claude-haiku-5-5 (verified 2026-10-27) — this is a config-level pause - // only: the proxy, its catalog entries, and every route that references - // it stay in place. Claude MODELS via other plans (antigravity-ls, + // itself was confirmed working at pause time — the proxy (:18749) + // was live and served claude-haiku-5-5 (verified 2026-10-27) — and + // the pause began as config-level only. That changed on 2026-11-05: + // the provider block below was repointed from the proxy to the + // fork's native claude-code provider (code#6117, opencode#1749), + // and on 2026-11-06 the proxy itself (bin/claude-code-proxy.mjs, + // its systemd unit and :18749) was removed in the proxy-infra + // decommission. Claude MODELS via other plans (antigravity-ls, // cline-pass, opendesign leaves in haiku/sonnet/opus-plan) are NOT the // Claude plan and are unaffected. To re-enable: delete "claude-code" // from disabled_providers and restore the "default" below. @@ -70,8 +74,9 @@ // (the pools below already ship that way — haiku-plan seats claude-code // while it is off). // - // WORKED EXAMPLE — Claude: "claude-code" sits in the list today because - // the Claude plan is on the free tier (see the header note). The day it + // WORKED EXAMPLE — Claude (resolved 2026-11-06, when claude-code + // left the list): "claude-code" sat in the list because the Claude + // plan was on the free tier (see the header note). The day it // comes back, delete the "claude-code" line from the list and Claude is // live: its definition, model catalog, and haiku-plan seat are already in // place, and every tier that consumes haiku-plan (scout, workhorse, @@ -2208,7 +2213,7 @@ // every other leaf in this pool. Same last position. // NEW 2026-10-28 (Job 2): round-robin over every verified Spark // contributor door — meta direct, ClinePass (live completion - // probed 2026-10-28), Command Code (live :18748 list), and + // probed 2026-10-28), Command Code (live :18748 proxy list, 2026-10-28; the proxy retired 2026-11-06 — the provider is native since 2026-11-05), and // OpenCode Go x3 (the live serve catalog lists // muse-spark-1.3-contributor on all three workspaces). The // tier seats that used to address the meta leaf directly @@ -2251,9 +2256,11 @@ // catalog lists a Sol-class model. // 2026-10-28 (Job 2): two plan doors join — OpenDesign (serves // gpt-6.1-sol; its block entry is added in this PR) and Command - // Code (gpt-6.1-sol verified in the LIVE :18748 /v1/models - // list, 85 ids, 2026-10-28 — the running bridge trails the - // source catalog but does serve Sol). + // Code (gpt-6.1-sol verified in the then-live :18748 + // /v1/models list, 85 ids, 2026-10-28 — the running bridge + // trailed the source catalog but did serve Sol; the bridge + // retired 2026-11-06 and the provider is native since + // 2026-11-05). // 2026-10-31 (Drew): the ChatGPT pair seats through // openai-plan/gpt-6.1-sol (ordered: alternate first, // main the reserve) at the pair's previous combined weight diff --git a/bin/agy-proxy.mjs b/bin/agy-proxy.mjs deleted file mode 100755 index 1051d5afcd..0000000000 --- a/bin/agy-proxy.mjs +++ /dev/null @@ -1,1164 +0,0 @@ -#!/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. -// Cached-token accounting (#480, settled 2026-11-01): the agy CLI's -// stream-json `result.usage` DOES carry a cached-input figure — -// `cache_read_tokens`, cumulative over the session like its sibling -// counters (verified against the real CLI's result shape on the -// laptop: usage keys are input_tokens, output_tokens, -// thinking_tokens, cache_read_tokens, total_tokens). The per-turn -// delta is emitted as `prompt_tokens_details.cached_tokens` in both -// response shapes when > 0, matching the sibling proxies' -// opencode#394 contract; when the CLI reports none, the field is -// omitted entirely rather than reporting a fabricated zero split. -// 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'; -import fs from 'node:fs'; -import path from 'node:path'; -import os from 'node:os'; -import { parseProxyPort } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -const PORT = parseProxyPort('AGY_PROXY_PORT', 18743); -const HOST = process.env.AGY_PROXY_HOST || '127.0.0.1'; - -// Publish the bound endpoint so other tools can find this proxy without -// knowing its port in advance: $XDG_STATE_HOME//endpoint.json -// (default ~/.local/state//endpoint.json), written on listen, -// removed on exit. -const publishEndpoint = () => { - try { - const stateHome = - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'agy-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync( - `${file}.tmp`, - JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n', - ); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { - try { - fs.unlinkSync(file); - } catch {} - }; - process.on('exit', cleanup); - process.on('SIGTERM', () => { - cleanup(); - process.exit(0); - }); - process.on('SIGINT', () => { - cleanup(); - process.exit(0); - }); - } catch {} -}; - -// 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' }, - { 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' } -]; - -const findAgyBinary = () => { - // Explicit override first: the test suite points this at its stub so - // a host-installed agy can never shadow it (#3355, mirroring - // CODEX_PROXY_CODEX_BIN in codex-proxy.mjs, #694). - if (process.env.AGY_PROXY_AGY_BIN) return process.env.AGY_PROXY_AGY_BIN; - const candidates = [ - '/run/current-system/sw/bin/agy', - `${process.env.HOME}/.gemini/bin/agy`, - `${process.env.HOME}/.local/bin/agy`, - 'agy' - ]; - for (const c of candidates) { - if (c === 'agy' || fs.existsSync(c)) { - return c; - } - } - return 'agy'; -}; - -const AGY_BIN = findAgyBinary(); - -const REAL_HOME = process.env.HOME || '/home/user'; -const AGY_HOME = process.env.AGY_ISOLATED_HOME || `${REAL_HOME}/.gemini/agy-proxy-env`; - -const ensureAgyEnvironment = () => { - const geminiDir = `${AGY_HOME}/.gemini`; - const configDir = `${geminiDir}/config`; - try { - fs.mkdirSync(configDir, { recursive: true }); - - const authFiles = [ - 'oauth_creds.json', - 'gemini-credentials.json', - 'google_accounts.json', - 'installation_id', - 'projects.json', - 'settings.json', - 'state.json', - 'trustedFolders.json' - ]; - - for (const file of authFiles) { - const src = `${REAL_HOME}/.gemini/${file}`; - const dst = `${geminiDir}/${file}`; - if (fs.existsSync(src)) { - try { - if (fs.existsSync(dst)) fs.unlinkSync(dst); - fs.symlinkSync(src, dst); - } catch {} - } - } - - const mcpConfigPath = `${configDir}/mcp_config.json`; - fs.writeFileSync(mcpConfigPath, JSON.stringify({ mcpServers: {} }, null, 2)); - - const userConfigPath = `${configDir}/config.json`; - fs.writeFileSync(userConfigPath, JSON.stringify({ - plugins: {}, - userSettings: { - browserJsExecutionPolicy: 'BROWSER_JS_EXECUTION_POLICY_DISABLED', - enableTerminalSandbox: false - } - }, null, 2)); - } catch (err) { - console.error('Warning: failed to initialize isolated agy environment:', err); - } - return AGY_HOME; -}; - -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 = ''; - const stdoutDecoder = createStreamDecoder(); - 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 += stdoutDecoder.push(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; - - // Check if model string ends with -low, -medium, or -high - for (const suffix of ['-low', '-medium', '-high']) { - if (modelStr.endsWith(suffix)) { - effort = suffix.slice(1); - modelStr = modelStr.slice(0, -suffix.length); - break; - } - } - - // 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 - if (!effort || !modelConfig.efforts.includes(effort)) { - effort = modelConfig.defaultEffort; - } - - return { - baseModel: modelConfig.id, - effort, - fullName: `${modelConfig.id}-${effort}` - }; -}; - -// In-memory session store mapping sessionKey -> { conversationId, updatedAt } -const sessionStore = new Map(); -const MAX_SESSIONS = 1000; - -const pruneSessionStore = () => { - if (sessionStore.size <= MAX_SESSIONS) return; - const entries = Array.from(sessionStore.entries()) - .sort((a, b) => a[1].updatedAt - b[1].updatedAt); - const toDelete = entries.slice(0, entries.length - MAX_SESSIONS); - for (const [key] of toDelete) { - sessionStore.delete(key); - } -}; - -const extractLatestUserPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - const lastUserMsg = [...messages].reverse().find(m => m.role === 'user'); - if (lastUserMsg) { - if (typeof lastUserMsg.content === 'string') return lastUserMsg.content; - if (Array.isArray(lastUserMsg.content)) { - return lastUserMsg.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } - return JSON.stringify(lastUserMsg.content); - } - return formatPrompt(messages); -}; - -const getSessionKey = (req, body) => { - const explicitId = - req.headers['x-conversation-id'] || - req.headers['x-session-id'] || - req.headers['conversation-id'] || - req.headers['session-id'] || - body.conversation_id || - body.conversationId || - body.session_id || - body.sessionId || - body.chat_id; - - if (explicitId && typeof explicitId === 'string' && explicitId.trim()) { - return { key: explicitId.trim(), explicit: true, conversationId: explicitId.trim() }; - } - - if (body.user && typeof body.user === 'string' && body.user.trim()) { - const userKey = `user:${body.user.trim()}`; - const cached = sessionStore.get(userKey); - return { key: userKey, explicit: false, conversationId: cached?.conversationId }; - } - - // Multi-turn automatic session tracking - if (Array.isArray(body.messages) && body.messages.length > 1) { - const firstMsg = body.messages[0]; - const firstContent = typeof firstMsg?.content === 'string' - ? firstMsg.content - : JSON.stringify(firstMsg?.content || ''); - if (firstContent.length > 0) { - const hash = crypto.createHash('sha256').update(firstContent).digest('hex').slice(0, 16); - const sessionKey = `turn0:${hash}`; - const cached = sessionStore.get(sessionKey); - return { key: sessionKey, explicit: false, conversationId: cached?.conversationId }; - } - } - - return { key: null, explicit: false, conversationId: null }; -}; - -const formatPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - if (messages.length === 1 && messages[0].role === 'user') { - return typeof messages[0].content === 'string' - ? messages[0].content - : JSON.stringify(messages[0].content); - } - - const parts = []; - const systemMessages = messages.filter(m => m.role === 'system'); - const convoMessages = messages.filter(m => m.role !== 'system'); - - if (systemMessages.length > 0) { - const sysText = systemMessages.map(m => - typeof m.content === 'string' ? m.content : JSON.stringify(m.content) - ).join('\n\n'); - parts.push(`[System Instructions]\n${sysText}`); - } - - if (convoMessages.length > 0) { - const convoText = convoMessages.map(m => { - const role = m.role === 'assistant' ? 'Assistant' : (m.role === 'user' ? 'User' : m.role); - let text = ''; - if (typeof m.content === 'string') { - text = m.content; - } else if (Array.isArray(m.content)) { - text = m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } else { - text = JSON.stringify(m.content); - } - return `${role}: ${text}`; - }).join('\n\n'); - parts.push(convoText); - } - - 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.stdoutDecoder = createStreamDecoder(); - this.stderrDecoder = createStreamDecoder(); - this.turnWaiter = null; - this.ready = false; // set when the init event arrives - this.prevUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0, cache_read_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 + this.stderrDecoder.push(chunk)).slice(-4000); - }); - child.on('error', err => { - this._fail(turnError(err.message, { isSpawnError: true })); - }); - child.on('close', (code, signal) => { - // Flush any unterminated final line before judging the exit - // (#683): a partial delta that never got its newline is real - // output, and the resume-retry gate reads hasOutput from the - // deltas this flush delivers. - this._flushLineBuffer(); - // 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 += this.stdoutDecoder.push(chunk); - const lines = this.lineBuffer.split('\n'); - this.lineBuffer = lines.pop() || ''; - for (const line of lines) this._processLine(line); - } - - _processLine(line) { - if (!line.trim()) return; - let obj; - try { obj = JSON.parse(line); } catch { return; } - this._onEvent(obj); - } - - // The child can exit mid-line: whatever tail is still buffered is a - // complete final line for judging purposes (#683) -- run it through - // the same path a terminated line takes before any close judgment. - _flushLineBuffer() { - const tail = this.lineBuffer; - this.lineBuffer = ''; - if (tail.trim()) this._processLine(tail); - } - - _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), - cache_read_tokens: Math.max(0, (cum.cache_read_tokens || 0) - this.prevUsage.cache_read_tokens) - }; - this.prevUsage = { - input_tokens: cum.input_tokens || 0, - output_tokens: cum.output_tokens || 0, - total_tokens: cum.total_tokens || 0, - cache_read_tokens: cum.cache_read_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) { - w.kill(); - liveWorkers.delete(lk); - continue; - } - // lastUsedAt is refreshed when a turn finishes, so an over-TTL worker - // can still be actively serving a long turn. Keep it until that turn - // settles; the next sweep can then apply the refreshed idle timestamp. - if (w.turnWaiter !== null) continue; - if (now - w.lastUsedAt > SESSION_IDLE_TTL_MS) { - w.kill(); - liveWorkers.delete(lk); - } - } - const idle = [...liveWorkers.entries()] - .filter(([, w]) => w.turnWaiter === null) - .sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt); - while (liveWorkers.size >= MAX_LIVE_WORKERS && idle.length > 0) { - const [lk, w] = idle.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(/\/+$/, '') || '/'; - - // Health & Root - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'antigravity-agy-proxy', - port: PORT, - binary: AGY_BIN, - engine: 'agy-stream-json-resident', - defaultModel: 'gemini-3.8-flash-medium', - activeSessions: sessionStore.size, - models: modelsStatus(), - warm: warmStatus() - }, null, 2)); - return; - } - - // Models catalog (live-pulled from `agy models`, see above) - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - (async () => { - await ensureInitialModels(); - maybeRefreshModels(); - const now = Math.floor(Date.now() / 1000); - const data = []; - - for (const m of modelCatalog) { - data.push({ - 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)); - })(); - return; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(20 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Request payload exceeds 20MB limit' })); - req.destroy(); - } - }); - - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON request body' })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON request body: expected an object' })); - return; - } - - 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; - } - const { fullName } = resolved; - - const sessionInfo = getSessionKey(req, body); - const isResuming = Boolean(sessionInfo.conversationId); - const prompt = isResuming - ? extractLatestUserPrompt(body.messages) - : formatPrompt(body.messages); - - if (!prompt.trim()) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Messages list produced empty prompt' })); - return; - } - - const reqId = `chatcmpl-${crypto.randomUUID()}`; - const created = Math.floor(Date.now() / 1000); - - let currentWorker = null; - let activeConversationId = sessionInfo.conversationId || null; - - res.on('close', () => { - if (!res.writableEnded && currentWorker) { - const lk = sessionInfo.key ? `${fullName}|${sessionInfo.key}` : null; - retireWorker({ worker: currentWorker, lk }); - } - }); - - const recordConversationId = (id) => { - if (!id) return; - activeConversationId = id; - if (sessionInfo.key) { - sessionStore.set(sessionInfo.key, { conversationId: id, updatedAt: Date.now() }); - pruneSessionStore(); - } - }; - - // 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 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 - } - ] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } : 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 - // 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; - } - - // 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; - - 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: { content: suffix }, finish_reason: null }] - }; - 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' - } - ], - usage: { - prompt_tokens: result.usage?.input_tokens || 0, - completion_tokens: result.usage?.output_tokens || 0, - total_tokens: result.usage?.total_tokens || 0, - ...(result.usage?.cache_read_tokens > 0 ? { prompt_tokens_details: { cached_tokens: result.usage.cache_read_tokens } } : {}) - } - }; - 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 - } : {}) - }); - 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, - ...(result.usage?.cache_read_tokens > 0 ? { prompt_tokens_details: { cached_tokens: result.usage.cache_read_tokens } } : {}) - } - }, null, 2)); - } - }; - - 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; - } - - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Endpoint not found', path: pathname })); -}); - -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`); - console.log(` - POST http://${HOST}:${PORT}/v1/chat/completions`); -}); diff --git a/bin/agy-proxy.test.mjs b/bin/agy-proxy.test.mjs deleted file mode 100644 index 552f884eda..0000000000 --- a/bin/agy-proxy.test.mjs +++ /dev/null @@ -1,552 +0,0 @@ -// 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. 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 AND answers -// `agy models` with a TSV list including a test-only model no static -// array could contain (startProxy also pins the stub via -// AGY_PROXY_AGY_BIN so a host-installed agy can never shadow it, -// #3355): 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'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const STUB = `#!/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 - if [ "$prev" = "--conversation" ]; then conv="$a"; fi - prev="$a" -done -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"}}' - echo "stub agy: run failed midway" >&2 - exit 3 ;; - *FAILTAIL*) - if [ -n "$conv" ]; then - printf '%s' '{"event":"step_update","step_update":{"text_delta":"partial tail"}}' - echo "stub agy: tail run failed" >&2 - exit 3 - fi ;; - *SLOWME*) - sleep "\${AGY_STUB_SLOW_SECONDS:-0.75}" ;; - *SIGKILLME*) - kill -9 $$ ;; - esac - printf '%s\\n' '{"event":"step_update","step_update":{"text_delta":"Hello world"}}' - 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,"cache_read_tokens":77}}}' -done -`; - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -const startProxy = async (extraEnv = {}) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'agy-proxy-test-')); - const home = path.join(tmp, 'home'); - fs.mkdirSync(path.join(home, '.local', 'bin'), { recursive: true }); - fs.writeFileSync(path.join(home, '.local', 'bin', 'agy'), STUB, { mode: 0o755 }); - const port = await freePort(); - const child = spawn(process.execPath, [path.join(binDir, 'agy-proxy.mjs')], { - env: { - ...process.env, - HOME: home, - XDG_STATE_HOME: path.join(tmp, 'state'), - AGY_PROXY_PORT: String(port), - AGY_PROXY_AGY_BIN: path.join(home, ".local", "bin", "agy"), - ...extraEnv - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', d => { log += d; }); - child.stderr.on('data', d => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch { /* not up yet */ } - if (Date.now() > deadline) throw new Error(`proxy did not start:\n${log}`); - await new Promise(r => setTimeout(r, 50)); - } - return { port, stop: () => child.kill('SIGKILL') }; -}; - -const post = (port, body, headers = {}) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', ...headers }, - body: JSON.stringify(body) -}); - -const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - -const waitForSessionPids = async (port, minCount) => { - const deadline = Date.now() + 5000; - for (;;) { - const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); - const pids = health.warm?.sessionPids ?? []; - if (pids.length >= minCount) return pids; - if (Date.now() > deadline) throw new Error(`expected ${minCount} live session workers, saw ${pids.length}`); - await delay(20); - } -}; - -const parseSse = (sse) => { - const dataLines = sse.split('\n').filter(l => l.startsWith('data: ')); - assert.equal(dataLines[dataLines.length - 1], 'data: [DONE]', 'stream must end with [DONE]'); - return dataLines.slice(0, -1).map(l => JSON.parse(l.slice('data: '.length))); -}; - -const assertStreamFailure = async (port, marker, detail) => { - const messages = [{ role: 'user', content: `please ${marker} now` }]; - const streamRes = await post(port, { messages, stream: true }); - assert.equal(streamRes.status, 200); - assert.match(streamRes.headers.get('content-type'), /text\/event-stream/); - const events = parseSse(await streamRes.text()); - const errorEvent = events.find(e => e.error); - assert.ok(errorEvent, `${marker}: stream must carry an error event`); - assert.match(errorEvent.error.message, detail, `${marker}: stream detail must name the cause, got: ${errorEvent.error.message}`); - const stopChunk = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); - assert.equal(stopChunk, undefined, `${marker}: no chunk may claim finish_reason 'stop'`); -}; - -test('successful run is unchanged in both modes', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'hi' }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 200); - const plain = JSON.parse(await plainRes.text()); - assert.equal(plain.choices[0].message.content, 'Hello world'); - assert.equal(plain.choices[0].finish_reason, 'stop'); - - const streamRes = await post(port, { messages, stream: true }); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - assert.match(sse, /Hello world/); - assert.match(sse, /"finish_reason":"stop"/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]')); -}); - -test('agy cache_read_tokens surfaces as prompt_tokens_details.cached_tokens in both shapes (#480)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'hi' }]; - const plain = JSON.parse(await (await post(port, { messages })).text()); - assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 77, 'non-streaming usage must surface the agy cache_read_tokens delta (opencode #394)'); - const streamRes = await post(port, { messages, stream: true }); - const events = parseSse(await streamRes.text()); - const finish = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); - assert.ok(finish, 'stream must carry a finish chunk'); - assert.equal(finish.usage.prompt_tokens_details.cached_tokens, 77, 'streaming finish chunk must surface cached_tokens'); -}); - -test('execution failure with no output: 502 non-stream, SSE error + [DONE] stream (#678)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please FAILME now' }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 502, 'non-stream failure must not be a 200 stop'); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.stderr, /stub agy: auth expired/); - - await assertStreamFailure(port, 'FAILME', /agy execution failed: stub agy: auth expired/); -}); - -test('partial output then failure: masked success becomes an error in both modes (#678)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please FAILPARTIAL now' }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 502, 'non-stream partial failure must not be a 200 stop'); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.stderr, /stub agy: run failed midway/); - - await assertStreamFailure(port, 'FAILPARTIAL', /agy execution failed: stub agy: run failed midway/); -}); - -test('signal-killed run: stream fallback names the signal, non-stream is a 502 (#678)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please SIGKILLME now' }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 502); - const plainBody = JSON.parse(await plainRes.text()); - assert.equal(plainBody.signal, 'SIGKILL'); - - await assertStreamFailure(port, 'SIGKILLME', /agy execution failed: agy process terminated by signal SIGKILL/); -}); - -test('failed resume still retries once as a fresh conversation (#678)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please RETRYME now' }]; - const headers = { 'x-conversation-id': 'conv-123' }; - - const plainRes = await post(port, { messages }, headers); - assert.equal(plainRes.status, 200); - const plain = JSON.parse(await plainRes.text()); - assert.equal(plain.choices[0].message.content, 'Hello world'); - assert.equal(plain.choices[0].finish_reason, 'stop'); - - const streamRes = await post(port, { messages, stream: true }, headers); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - assert.match(sse, /Hello world/); - assert.match(sse, /"finish_reason":"stop"/); -}); - -test('unterminated final delta counts as output: failed resume is NOT retried fresh (#683)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'please FAILTAIL now' }]; - const headers = { 'x-conversation-id': 'conv-456' }; - - const plainRes = await post(port, { messages }, headers); - assert.equal(plainRes.status, 502, 'a resumed turn whose only output is an unterminated tail delta must fail, not silently retry as a fresh conversation'); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.stderr, /stub agy: tail run failed/); - - const streamRes = await post(port, { messages, stream: true }, headers); - assert.equal(streamRes.status, 200); - const events = parseSse(await streamRes.text()); - const deltaChunk = events.find(e => e.choices && e.choices[0].delta && e.choices[0].delta.content === 'partial tail'); - assert.ok(deltaChunk, 'the unterminated tail delta must be delivered exactly like a terminated line'); - const errorEvent = events.find(e => e.error); - assert.ok(errorEvent, 'stream must carry an error event'); - assert.match(errorEvent.error.message, /tail run failed/); - const stopChunk = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); - assert.equal(stopChunk, undefined, "no chunk may claim finish_reason 'stop'"); -}); - -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'); - 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'); - assert.ok(health.warm.sessionPids.includes(Number(pid1)), 'health must list the live session worker pid'); -}); - -test('TTL eviction skips a worker with a turn in flight, then evicts it after the turn settles', async (t) => { - const { port, stop } = await startProxy({ - AGY_PROXY_WARM_SPARES: '0', - AGY_PROXY_SESSION_TTL_MS: '75', - AGY_STUB_SLOW_SECONDS: '0.5' - }); - t.after(stop); - - const busyPromise = post(port, { messages: [{ role: 'user', content: 'SLOWME ttl' }] }, { - 'x-conversation-id': 'ttl-busy' - }); - const [busyPid] = await waitForSessionPids(port, 1); - await delay(125); // worker is turn-busy and its spawn timestamp is TTL-expired - - const trigger = await post(port, { messages: [{ role: 'user', content: 'trigger ttl sweep' }] }, { - 'x-conversation-id': 'ttl-trigger' - }); - assert.equal(trigger.status, 200); - await trigger.text(); - - const busy = await busyPromise; - assert.equal(busy.status, 200, 'the TTL sweep must not kill an in-flight turn'); - assert.equal(Number(busy.headers.get('x-agy-worker-pid')), busyPid); - await busy.text(); - - await delay(100); // after turn completion lastUsedAt is refreshed; let that idle TTL expire - const after = await post(port, { messages: [{ role: 'user', content: 'trigger post-turn sweep' }] }, { - 'x-conversation-id': 'ttl-after' - }); - assert.equal(after.status, 200); - await after.text(); - const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); - assert.ok(!health.warm.sessionPids.includes(busyPid), 'the now-idle worker is eligible on the next TTL sweep'); -}); - -test('cap eviction chooses an idle LRU candidate instead of a busy older worker', async (t) => { - const { port, stop } = await startProxy({ - AGY_PROXY_WARM_SPARES: '0', - AGY_PROXY_MAX_LIVE_WORKERS: '2', - AGY_PROXY_SESSION_TTL_MS: '60000', - AGY_STUB_SLOW_SECONDS: '0.8' - }); - t.after(stop); - - const busyPromise = post(port, { messages: [{ role: 'user', content: 'SLOWME cap-busy' }] }, { - 'x-conversation-id': 'cap-busy' - }); - const [busyPid] = await waitForSessionPids(port, 1); - await delay(75); - - const idle = await post(port, { messages: [{ role: 'user', content: 'idle worker' }] }, { - 'x-conversation-id': 'cap-idle' - }); - assert.equal(idle.status, 200); - const idlePid = Number(idle.headers.get('x-agy-worker-pid')); - await idle.text(); - assert.notEqual(idlePid, busyPid); - - const trigger = await post(port, { messages: [{ role: 'user', content: 'trigger cap sweep' }] }, { - 'x-conversation-id': 'cap-trigger' - }); - assert.equal(trigger.status, 200); - await trigger.text(); - - const busy = await busyPromise; - assert.equal(busy.status, 200, 'cap pressure must not kill the busy LRU worker'); - assert.equal(Number(busy.headers.get('x-agy-worker-pid')), busyPid); - await busy.text(); - const health = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); - assert.ok(health.warm.sessionPids.includes(busyPid), 'busy worker remains live'); - assert.ok(!health.warm.sessionPids.includes(idlePid), 'idle worker is selected for eviction'); -}); - -test('cap eviction does nothing when every live worker has a turn in flight', async (t) => { - const { port, stop } = await startProxy({ - AGY_PROXY_WARM_SPARES: '0', - AGY_PROXY_MAX_LIVE_WORKERS: '2', - AGY_PROXY_SESSION_TTL_MS: '60000', - AGY_STUB_SLOW_SECONDS: '0.8' - }); - t.after(stop); - - const firstPromise = post(port, { messages: [{ role: 'user', content: 'SLOWME all-busy-1' }] }, { - 'x-conversation-id': 'all-busy-1' - }); - const [firstPid] = await waitForSessionPids(port, 1); - await delay(75); - const secondPromise = post(port, { messages: [{ role: 'user', content: 'SLOWME all-busy-2' }] }, { - 'x-conversation-id': 'all-busy-2' - }); - const pids = await waitForSessionPids(port, 2); - const secondPid = pids.find(pid => pid !== firstPid); - assert.ok(secondPid); - await delay(75); - - const trigger = await post(port, { messages: [{ role: 'user', content: 'trigger all-busy sweep' }] }, { - 'x-conversation-id': 'all-busy-trigger' - }); - assert.equal(trigger.status, 200); - await trigger.text(); - - const [first, second] = await Promise.all([firstPromise, secondPromise]); - assert.equal(first.status, 200, 'no busy worker is evicted when every candidate is busy'); - assert.equal(second.status, 200, 'all busy turns survive cap pressure'); - assert.equal(Number(first.headers.get('x-agy-worker-pid')), firstPid); - assert.equal(Number(second.headers.get('x-agy-worker-pid')), secondPid); -}); - -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 live `agy models` list", async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: "user", content: "hi" }]; - - const badRes = await post(port, { model: "gemini-9-nonexistent", messages }); - assert.equal(badRes.status, 400, "unknown model must fail loudly, not fall back to the first model"); - const badBody = JSON.parse(await badRes.text()); - assert.match(badBody.error, /gemini-9-nonexistent/); - - 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); - // 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", - "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"); -}); - -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(); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); diff --git a/bin/antigravity-ls-proxy.mjs b/bin/antigravity-ls-proxy.mjs deleted file mode 100755 index 79c41f7434..0000000000 --- a/bin/antigravity-ls-proxy.mjs +++ /dev/null @@ -1,1139 +0,0 @@ -#!/usr/bin/env node -import http from 'node:http'; -import { spawn, execSync } from 'node:child_process'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; -import os from 'node:os'; -import { parseProxyPort, parseAddressPortValue } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; - -const PORT = parseProxyPort('ANTIGRAVITY_LS_PROXY_PORT', 18745); -const HOST = process.env.ANTIGRAVITY_LS_PROXY_HOST || '127.0.0.1'; - -// Publish the bound endpoint so other tools can find this proxy without -// knowing its port in advance: $XDG_STATE_HOME//endpoint.json -// (default ~/.local/state//endpoint.json), written on listen, -// removed on exit. This file already registers SIGTERM/SIGINT handlers -// (see below, calling lsManager.cleanup() then process.exit(0)), so this -// helper does not register duplicate signal handlers; the 'exit' cleanup -// it registers runs on that existing exit path. -const publishEndpoint = () => { - try { - const stateHome = - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'antigravity-ls-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync( - `${file}.tmp`, - JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n', - ); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { - try { - fs.unlinkSync(file); - } catch {} - }; - process.on('exit', cleanup); - } catch {} -}; - -const DEFAULT_MANAGED_HTTP_PORT = 48999; -const DEFAULT_MANAGED_HTTPS_PORT = 48998; -const MANAGED_CSRF_TOKEN = 'antigravity-ls-local-token-' + crypto.randomUUID().slice(0, 8); - -const MODEL_MAP = { - // Gemini 3.8 Flash - 'gemini-3.8-flash': { low: 'MODEL_PLACEHOLDER_M320', medium: 'MODEL_PLACEHOLDER_M319', high: 'MODEL_PLACEHOLDER_M318', default: 'medium', name: 'Gemini 3.8 Flash' }, - 'gemini-3.8-flash-low': { enum: 'MODEL_PLACEHOLDER_M320', name: 'Gemini 3.8 Flash (Low)' }, - 'gemini-3.8-flash-medium': { enum: 'MODEL_PLACEHOLDER_M319', name: 'Gemini 3.8 Flash (Medium)' }, - 'gemini-3.8-flash-high': { enum: 'MODEL_PLACEHOLDER_M318', name: 'Gemini 3.8 Flash (High)' }, - - // Gemini 3.7 Flash - 'gemini-3.7-flash': { low: 'MODEL_PLACEHOLDER_M300', medium: 'MODEL_PLACEHOLDER_M299', high: 'MODEL_PLACEHOLDER_M298', default: 'medium', name: 'Gemini 3.7 Flash' }, - 'gemini-3.7-flash-low': { enum: 'MODEL_PLACEHOLDER_M300', name: 'Gemini 3.7 Flash (Low)' }, - 'gemini-3.7-flash-medium': { enum: 'MODEL_PLACEHOLDER_M299', name: 'Gemini 3.7 Flash (Medium)' }, - 'gemini-3.7-flash-high': { enum: 'MODEL_PLACEHOLDER_M298', name: 'Gemini 3.7 Flash (High)' }, - - // Gemini 3.6 Flash - 'gemini-3.6-flash': { low: 'MODEL_PLACEHOLDER_M73', medium: 'MODEL_PLACEHOLDER_M72', high: 'MODEL_PLACEHOLDER_M71', default: 'medium', name: 'Gemini 3.6 Flash' }, - 'gemini-3.6-flash-low': { enum: 'MODEL_PLACEHOLDER_M73', name: 'Gemini 3.6 Flash (Low)' }, - 'gemini-3.6-flash-medium': { enum: 'MODEL_PLACEHOLDER_M72', name: 'Gemini 3.6 Flash (Medium)' }, - 'gemini-3.6-flash-high': { enum: 'MODEL_PLACEHOLDER_M71', name: 'Gemini 3.6 Flash (High)' }, - - // Gemini 3.1 Pro - 'gemini-3.1-pro': { low: 'MODEL_PLACEHOLDER_M36', high: 'MODEL_PLACEHOLDER_M37', default: 'high', name: 'Gemini 3.1 Pro' }, - 'gemini-3.1-pro-low': { enum: 'MODEL_PLACEHOLDER_M36', name: 'Gemini 3.1 Pro (Low)' }, - 'gemini-3.1-pro-high': { enum: 'MODEL_PLACEHOLDER_M37', name: 'Gemini 3.1 Pro (High)' }, - - // Claude Sonnet 5.5 - 'claude-sonnet-5-5': { low: 'MODEL_PLACEHOLDER_M403', medium: 'MODEL_PLACEHOLDER_M404', high: 'MODEL_PLACEHOLDER_M405', default: 'medium', name: 'Claude Sonnet 5.5' }, - 'claude-sonnet-5-5-low': { enum: 'MODEL_PLACEHOLDER_M403', name: 'Claude Sonnet 5.5 (Low)' }, - 'claude-sonnet-5-5-medium': { enum: 'MODEL_PLACEHOLDER_M404', name: 'Claude Sonnet 5.5 (Medium)' }, - 'claude-sonnet-5-5-high': { enum: 'MODEL_PLACEHOLDER_M405', name: 'Claude Sonnet 5.5 (High)' }, - - // Claude Opus 5.5 - 'claude-opus-5-5': { low: 'MODEL_PLACEHOLDER_M400', medium: 'MODEL_PLACEHOLDER_M401', high: 'MODEL_PLACEHOLDER_M402', default: 'medium', name: 'Claude Opus 5.5' }, - 'claude-opus-5-5-low': { enum: 'MODEL_PLACEHOLDER_M400', name: 'Claude Opus 5.5 (Low)' }, - 'claude-opus-5-5-medium': { enum: 'MODEL_PLACEHOLDER_M401', name: 'Claude Opus 5.5 (Medium)' }, - 'claude-opus-5-5-high': { enum: 'MODEL_PLACEHOLDER_M402', name: 'Claude Opus 5.5 (High)' }, - - // GPT-OSS 120B - 'gpt-oss-120b': { enum: 'MODEL_OPENAI_GPT_OSS_120B_MEDIUM', name: 'GPT-OSS 120B' }, - 'gpt-oss-120b-medium': { enum: 'MODEL_OPENAI_GPT_OSS_120B_MEDIUM', name: 'GPT-OSS 120B (Medium)' }, - - // Direct Google Gemini fallback - 'gemini-2.5-flash': { enum: 'MODEL_GOOGLE_GEMINI_2_5_FLASH', name: 'Gemini 2.5 Flash' }, - 'gemini-2.5-pro': { enum: 'MODEL_GOOGLE_GEMINI_2_5_PRO', name: 'Gemini 2.5 Pro' } -}; - -const resolveModelEnum = (requestedModel, requestedEffort, liveModels = {}) => { - let modelStr = (requestedModel || 'gemini-3.8-flash').toLowerCase().trim(); - let isCascade = false; - - if (modelStr.endsWith('-cascade')) { - isCascade = true; - modelStr = modelStr.slice(0, -'-cascade'.length); - } - - // Strip prefixes like 'antigravity-ls/', 'antigravity-agy/', 'antigravity/', 'google/' - for (const prefix of ['antigravity-ls/', 'antigravity-agy/', 'antigravity/', 'google/']) { - if (modelStr.startsWith(prefix)) { - modelStr = modelStr.slice(prefix.length); - break; - } - } - - // Candidates to test: original and dot-normalized (e.g. claude-sonnet-5.5 -> claude-sonnet-5-5) - const candIds = [modelStr]; - const dotNormalized = modelStr.replace(/\./g, '-'); - if (dotNormalized !== modelStr) candIds.push(dotNormalized); - - // 1. Exact match in liveModels - for (const cand of candIds) { - if (liveModels[cand]?.model) { - return { - modelEnum: liveModels[cand].model, - displayName: liveModels[cand].displayName || cand, - isCascade - }; - } - } - - // 2. Exact match in MODEL_MAP - for (const cand of candIds) { - if (MODEL_MAP[cand]?.enum) { - return { - modelEnum: MODEL_MAP[cand].enum, - displayName: MODEL_MAP[cand].name, - isCascade - }; - } - } - - // 3. Model family with effort in MODEL_MAP - for (const cand of candIds) { - const family = MODEL_MAP[cand]; - if (family) { - // A family entry also carries metadata keys — `default` (an effort - // name) and `name` (a display name) — whose values are not model - // enums. Accept an effort only when it maps to an actual enum, - // otherwise fall back to the family's default effort (#686). - const isModelEnum = (v) => typeof v === 'string' && v.startsWith('MODEL_'); - let effort = (requestedEffort || family.default || 'medium').toLowerCase().trim(); - if (!isModelEnum(family[effort])) effort = family.default; - if (!isModelEnum(family[effort])) { - effort = Object.keys(family).find((k) => isModelEnum(family[k])); - } - const enumVal = family[effort]; - return { - modelEnum: enumVal, - displayName: `${family.name} (${effort.charAt(0).toUpperCase() + effort.slice(1)})`, - isCascade - }; - } - } - - // 4. Try matching with effort suffix in liveModels (e.g. claude-sonnet-5-5-medium, gemini-3.8-flash-high) - const effortOrder = requestedEffort ? [requestedEffort.toLowerCase().trim(), 'medium', 'high', 'low', 'extra-low'] : ['medium', 'high', 'low', 'extra-low']; - for (const cand of candIds) { - for (const eff of effortOrder) { - const variant = liveModels[`${cand}-${eff}`]; - if (variant?.model) { - return { - modelEnum: variant.model, - displayName: variant.displayName || `${cand} (${eff})`, - isCascade - }; - } - } - } - - // 5. Direct pass-through if enum name - if (modelStr.startsWith('model_')) { - return { modelEnum: modelStr.toUpperCase(), displayName: modelStr, isCascade }; - } - - // Refuse rather than quietly run a different model than the one asked for. - const err = new Error(`Unknown model "${requestedModel}": not in the language server catalog or the proxy's model map`); - err.status = 400; - throw err; -}; - -const findLanguageServerBinary = () => { - // Set by the Nix unit to the exact hub build, so nothing here goes stale - // when the flake bumps antigravity-hub. - if (process.env.ANTIGRAVITY_LS_BIN) return process.env.ANTIGRAVITY_LS_BIN; - - const candidates = [ - '/nix/store/rpgwxqadiscnsm9zmb4j4brb3yp2ayqg-antigravity-hub-2.12.2/share/antigravity/resources/bin/language_server', - '/nix/store/4lcvb3j5418q7nlfx156b3rmf0vhv8qk-antigravity-ide-2.5.5/lib/antigravity-ide/resources/app/extensions/antigravity/bin/language_server_linux_x64' - ]; - for (const c of candidates) { - if (fs.existsSync(c)) return c; - } - // Scan store entry names rather than `find /nix/store`, which walks the whole - // store synchronously and would freeze the proxy while it runs. - try { - for (const entry of fs.readdirSync('/nix/store')) { - if (!entry.includes('-antigravity-hub-')) continue; - const c = `/nix/store/${entry}/share/antigravity/resources/bin/language_server`; - if (fs.existsSync(c)) return c; - } - } catch {} - return candidates[0]; -}; - -// --- RPC timeout policy (#2102) ------------------------------------------- -// callRpc used to fetch the language server with no timeout, so a server -// that passes heartbeat but never answers an RPC hung /v1/models and every -// chat request forever. Every RPC is now bounded, including the -// response-body read (the AbortSignal stays attached until the body is -// consumed). Budgets are method-specific: the model catalog and trajectory -// polls are cheap, cascade start/send queue work server-side, and -// GetModelResponse carries long model generations, so it gets minutes. -// Tests inject short budgets via ANTIGRAVITY_LS_RPC_TIMEOUTS (a JSON object -// mapping method name -> milliseconds) and the cascade deadline via -// ANTIGRAVITY_LS_CASCADE_DEADLINE_MS. -const RPC_TIMEOUTS_MS = { - GetAvailableModels: 3_000, - StartCascade: 30_000, - SendUserCascadeMessage: 30_000, - GetCascadeTrajectorySteps: 5_000, - GetModelResponse: 300_000 -}; -const DEFAULT_RPC_TIMEOUT_MS = 30_000; - -const parseRpcTimeoutOverrides = () => { - try { - const parsed = JSON.parse(process.env.ANTIGRAVITY_LS_RPC_TIMEOUTS || '{}'); - const out = {}; - for (const [k, v] of Object.entries(parsed || {})) { - if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[k] = v; - } - return out; - } catch { - return {}; - } -}; -const RPC_TIMEOUT_OVERRIDES = parseRpcTimeoutOverrides(); -const rpcTimeoutMs = (method) => - RPC_TIMEOUT_OVERRIDES[method] ?? RPC_TIMEOUTS_MS[method] ?? DEFAULT_RPC_TIMEOUT_MS; - -const parsePositiveMs = (raw, fallback) => { - const n = Number(raw); - return Number.isFinite(n) && n > 0 ? n : fallback; -}; -// Cascade polling obeys a strict elapsed-time deadline, not an iteration -// count: slow polls stretched the old 120-attempt loop far past 30s. -const CASCADE_DEADLINE_MS = parsePositiveMs(process.env.ANTIGRAVITY_LS_CASCADE_DEADLINE_MS, 30_000); - -class LanguageServerManager { - constructor() { - this.managedChild = null; - this.activeHttpPort = null; - this.activeCsrfToken = null; - this.isManaged = false; - } - - async checkHeartbeat(port, token) { - try { - const res = await fetch(`http://127.0.0.1:${port}/exa.language_server_pb.LanguageServerService/Heartbeat`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-codeium-csrf-token': token - }, - body: '{}', - signal: AbortSignal.timeout(1500) - }); - return res.status === 200; - } catch { - return false; - } - } - - // Every running language server that might be ours to attach to, newest - // first. Its HTTP port is logged rather than passed as a flag, and an HTTPS - // listener is logged the same way, so ensureActive heartbeats each candidate - // and keeps the one that answers. - detectRunningInstances() { - if (process.env.ANTIGRAVITY_LS_ADDRESS && process.env.ANTIGRAVITY_CSRF_TOKEN) { - const port = parseAddressPortValue('ANTIGRAVITY_LS_ADDRESS', process.env.ANTIGRAVITY_LS_ADDRESS); - return [{ port, token: process.env.ANTIGRAVITY_CSRF_TOKEN }]; - } - - const candidates = []; - const seen = new Set(); - const add = (port, token) => { - const p = parseInt(port, 10); - const key = `${p}:${token}`; - if (p >= 1 && p <= 65535 && !seen.has(key)) { - seen.add(key); - candidates.push({ port: p, token }); - } - }; - - // 1. Detect from active running processes and their listening sockets - try { - const psOutput = execSync('ps -ef | grep language_server | grep -v grep', { encoding: 'utf-8' }); - for (const line of psOutput.split('\n')) { - if (!line.includes('language_server')) continue; - const csrfMatch = line.match(/--csrf_token\s+([a-zA-Z0-9_-]+)/); - if (!csrfMatch) continue; - const token = csrfMatch[1]; - - const tokens = line.trim().split(/\s+/); - const pid = tokens[1]; - - const portMatch = line.match(/--http_server_port\s+(\d+)/); - if (portMatch) add(parseInt(portMatch[1], 10), token); - - if (pid) { - try { - const ssOut = execSync(`ss -tlnp 2>/dev/null | grep "pid=${pid},"`, { encoding: 'utf-8' }); - for (const ssLine of ssOut.split('\n')) { - const m = ssLine.match(/(?:127\.0\.0\.1|0\.0\.0\.0|\[::\]|localhost):(\d+)/); - if (m) add(m[1], token); - } - } catch {} - try { - const lsofOut = execSync(`lsof -a -p ${pid} -iTCP -sTCP:LISTEN -P -n 2>/dev/null`, { encoding: 'utf-8' }); - for (const lsofLine of lsofOut.split('\n')) { - const m = lsofLine.match(/:(\d+)\s+\(LISTEN\)/); - if (m) add(m[1], token); - } - } catch {} - } - } - } catch {} - - // 2. Fallback: Parse log files for logged HTTP ports - try { - const logContent = fs.readFileSync(`${process.env.HOME}/.config/Antigravity/logs/language_server.log`, 'utf-8'); - const loggedPorts = logContent.split('\n').reverse() - .map(l => l.match(/listening on random port at (\d+) for HTTP\b/)) - .filter(Boolean) - .map(m => parseInt(m[1], 10)); - for (const cand of [...candidates]) { - for (const port of loggedPorts) add(port, cand.token); - } - } catch {} - - return candidates; - } - - async ensureActive() { - if (this.activeHttpPort && this.activeCsrfToken) { - const healthy = await this.checkHeartbeat(this.activeHttpPort, this.activeCsrfToken); - if (healthy) return { port: this.activeHttpPort, token: this.activeCsrfToken }; - } - - for (const candidate of this.detectRunningInstances()) { - if (await this.checkHeartbeat(candidate.port, candidate.token)) { - console.log(`Connected to active Antigravity Language Server on port ${candidate.port}`); - this.activeHttpPort = candidate.port; - this.activeCsrfToken = candidate.token; - this.isManaged = false; - return candidate; - } - } - - return this.startManagedDaemon(); - } - - async startManagedDaemon() { - const bin = findLanguageServerBinary(); - if (!fs.existsSync(bin)) { - throw new Error(`Antigravity language_server binary not found at ${bin}`); - } - - console.log(`Standing up dedicated Antigravity Language Server daemon (${bin})...`); - - const args = [ - '--standalone', - '--override_ide_name', 'antigravity', - '--subclient_type', 'hub', - '--override_ide_version', '2.12.2', - '--override_user_agent_name', 'antigravity', - '--csrf_token', MANAGED_CSRF_TOKEN, - '--http_server_port', String(DEFAULT_MANAGED_HTTP_PORT), - '--https_server_port', String(DEFAULT_MANAGED_HTTPS_PORT), - '--app_data_dir', 'antigravity', - '--api_server_url', 'https://generativelanguage.googleapis.com', - '--cloud_code_endpoint', 'https://daily-cloudcode-pa.googleapis.com' - ]; - - const child = spawn(bin, args, { - cwd: '/tmp', - detached: true, - stdio: ['ignore', 'pipe', 'pipe'] - }); - - this.managedChild = child; - this.activeHttpPort = DEFAULT_MANAGED_HTTP_PORT; - this.activeCsrfToken = MANAGED_CSRF_TOKEN; - this.isManaged = true; - - child.on('exit', (code, sig) => { - console.log(`Managed language_server exited with code ${code}, signal ${sig}`); - this.managedChild = null; - this.activeHttpPort = null; - }); - - for (let i = 0; i < 30; i++) { - await new Promise(r => setTimeout(r, 200)); - const ok = await this.checkHeartbeat(DEFAULT_MANAGED_HTTP_PORT, MANAGED_CSRF_TOKEN); - if (ok) { - console.log(`Dedicated Language Server ready on port ${DEFAULT_MANAGED_HTTP_PORT}`); - return { port: this.activeHttpPort, token: this.activeCsrfToken }; - } - } - - throw new Error('Timed out waiting for managed Antigravity Language Server to initialize'); - } - - async callRpc(method, payload, timeoutCapMs) { - const { port, token } = await this.ensureActive(); - const url = `http://127.0.0.1:${port}/exa.language_server_pb.LanguageServerService/${method}`; - // A caller with its own deadline (the cascade poll loop) may cap the - // per-method budget at the time it has left; the cap can only shrink it. - const timeoutMs = timeoutCapMs === undefined - ? rpcTimeoutMs(method) - : Math.min(rpcTimeoutMs(method), Math.max(1, timeoutCapMs)); - // One signal for the whole RPC: it bounds the fetch AND the body read. - const signal = AbortSignal.timeout(timeoutMs); - const isTimeout = (err) => err?.name === 'TimeoutError' || err?.name === 'AbortError'; - const timeoutError = () => new Error(`RPC ${method} timed out after ${timeoutMs}ms`); - - let res; - try { - res = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-codeium-csrf-token': token - }, - body: JSON.stringify(payload), - signal - }); - } catch (err) { - if (isTimeout(err)) throw timeoutError(); - throw err; - } - - try { - if (!res.ok) { - const errText = await res.text(); - throw new Error(`RPC ${method} returned HTTP ${res.status}: ${errText}`); - } - return await res.json(); - } catch (err) { - if (isTimeout(err)) throw timeoutError(); - throw err; - } - } - - cleanup() { - if (this.managedChild) { - try { - if (this.managedChild.pid) process.kill(-this.managedChild.pid, 'SIGTERM'); - } catch { - try { this.managedChild.kill('SIGTERM'); } catch {} - } - } - } -} - -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 }), -// 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; - try { - const live = await lsManager.callRpc('GetAvailableModels', {}); - liveCatalogCache = { at: Date.now(), models: live?.response?.models || {} }; - } catch { - // Keep { at } unchanged so the next request retries the live pull. - return liveCatalogCache.models; - } - return liveCatalogCache.models; -}; - -// Session store for multi-turn conversations -const sessionStore = new Map(); -const MAX_SESSIONS = 1000; - -const pruneSessionStore = () => { - if (sessionStore.size <= MAX_SESSIONS) return; - const entries = Array.from(sessionStore.entries()) - .sort((a, b) => a[1].updatedAt - b[1].updatedAt); - const toDelete = entries.slice(0, entries.length - MAX_SESSIONS); - for (const [key] of toDelete) sessionStore.delete(key); -}; - -const extractLatestUserPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - const lastUserMsg = [...messages].reverse().find(m => m.role === 'user'); - if (lastUserMsg) { - if (typeof lastUserMsg.content === 'string') return lastUserMsg.content; - if (Array.isArray(lastUserMsg.content)) { - return lastUserMsg.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } - return JSON.stringify(lastUserMsg.content); - } - return formatPrompt(messages); -}; - -const formatPrompt = (messages, tools = []) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - if (messages.length === 1 && messages[0].role === 'user' && (!tools || tools.length === 0)) { - return typeof messages[0].content === 'string' - ? messages[0].content - : JSON.stringify(messages[0].content); - } - - const parts = []; - const systemMessages = messages.filter(m => m.role === 'system'); - const convoMessages = messages.filter(m => m.role !== 'system'); - - if (systemMessages.length > 0) { - const sysText = systemMessages.map(m => - typeof m.content === 'string' ? m.content : JSON.stringify(m.content) - ).join('\n\n'); - parts.push(`[System Instructions]\n${sysText}`); - } - - if (Array.isArray(tools) && tools.length > 0) { - const toolsDesc = tools.map(t => { - const fn = t.function || t; - return `- ${fn.name}: ${fn.description || ''} (parameters: ${JSON.stringify(fn.parameters || {})})`; - }).join('\n'); - parts.push(`[Available Tools]\n${toolsDesc}\n\n[Tool Calling]\nWhen you need to use a tool, emit each call as a fenced block in exactly this format, with nothing else inside the block:\n\`\`\`tool_call\n{"name": "", "arguments": {}}\n\`\`\`\nEmit one block per call. Never describe a call in prose instead of emitting its block. Any text outside the blocks is treated as your reply text.`); - } - - if (convoMessages.length > 0) { - const convoText = convoMessages.map(m => { - let role = 'User'; - if (m.role === 'assistant') role = 'Assistant'; - else if (m.role === 'tool') role = `Tool Result (${m.name || m.tool_call_id || 'tool'})`; - else if (m.role === 'user') role = 'User'; - else role = m.role; - - let text = ''; - if (typeof m.content === 'string') { - text = m.content; - } else if (Array.isArray(m.content)) { - text = m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } else if (m.content) { - text = JSON.stringify(m.content); - } - - if (Array.isArray(m.tool_calls) && m.tool_calls.length > 0) { - const calls = m.tool_calls.map(tc => { - const fn = tc.function || tc; - return `[Calls Tool: ${fn.name} with args ${fn.arguments || '{}'}]`; - }).join('\n'); - text = text ? `${text}\n${calls}` : calls; - } - - return `${role}: ${text}`; - }).join('\n\n'); - parts.push(convoText); - } - - return parts.join('\n\n'); -}; - -// --- Tool-call extraction --------------------------------------------------- -// The language server returns plain text, so models spell tool calls in -// text: the canonical ```tool_call fenced JSON formatPrompt asks for, -// Claude's XML, or a fenced/bare JSON object. When a request -// carries tools, lift every recognized call whose name matches an offered -// tool into structured OpenAI tool_calls and strip the syntax from the -// reply text. Without this, clients that require structured tool_calls -// (e.g. OpenCode) receive the calls as inert prose and execute nothing. -const coerceArgValue = (value) => { - if (typeof value !== 'string') return value; - const trimmed = value.trim(); - if (!trimmed) return value; - try { - return JSON.parse(trimmed); - } catch { - return value; - } -}; - -const extractToolCalls = (text, tools) => { - if (!text || !Array.isArray(tools) || tools.length === 0) { - return { content: text, toolCalls: [] }; - } - const validNames = new Set(tools.map(t => (t.function || t).name).filter(Boolean)); - if (validNames.size === 0) return { content: text, toolCalls: [] }; - - const calls = []; - const spans = []; - const addCall = (name, args, start, end) => { - if (!validNames.has(name) || start < 0) return; - calls.push({ name, arguments: args && typeof args === 'object' ? args : {} }); - spans.push([start, end]); - }; - - // Fenced blocks: ```tool_call {json} ``` — a plain ```json fence whose - // object names an offered tool counts too. - const fenceRe = /```(?:tool_call|json)?[ \t]*\n?([\s\S]*?)```/g; - for (const m of text.matchAll(fenceRe)) { - const inner = m[1].trim(); - if (!inner.startsWith('{')) continue; - try { - const obj = JSON.parse(inner); - if (obj && typeof obj.name === 'string') { - addCall(obj.name, obj.arguments ?? obj.args ?? {}, m.index, m.index + m[0].length); - } - } catch {} - } - - // Claude-style XML: v - const invokeRe = /([\s\S]*?)<\/invoke>/g; - for (const m of text.matchAll(invokeRe)) { - const args = {}; - for (const p of m[2].matchAll(/([\s\S]*?)<\/parameter>/g)) { - args[p[1]] = coerceArgValue(p[2].trim()); - } - addCall(m[1], args, m.index, m.index + m[0].length); - } - - // A reply that is one bare JSON object naming an offered tool. - if (calls.length === 0) { - const trimmed = text.trim(); - if (trimmed.startsWith('{') && trimmed.endsWith('}')) { - try { - const obj = JSON.parse(trimmed); - if (obj && typeof obj.name === 'string' && validNames.has(obj.name)) { - addCall(obj.name, obj.arguments ?? obj.args ?? {}, text.indexOf('{'), text.lastIndexOf('}') + 1); - } - } catch {} - } - } - - if (calls.length === 0) return { content: text, toolCalls: [] }; - - spans.sort((a, b) => a[0] - b[0]); - let content = ''; - let cursor = 0; - for (const [start, end] of spans) { - if (start < cursor) continue; - content += text.slice(cursor, start); - cursor = end; - } - content += text.slice(cursor); - content = content.replace(/|<\/function_calls>/g, '').replace(/\n{3,}/g, '\n\n').trim(); - - return { - content, - toolCalls: calls.map(c => ({ - id: `call_${crypto.randomUUID().replace(/-/g, '').slice(0, 24)}`, - type: 'function', - function: { name: c.name, arguments: JSON.stringify(c.arguments) } - })) - }; -}; - -// Emit one streaming chunk per tool call (OpenAI delta.tool_calls shape). -const writeToolCallChunks = (res, base, toolCalls) => { - toolCalls.forEach((tc, i) => { - const chunk = { - ...base, - choices: [{ - index: 0, - delta: { - tool_calls: [{ - index: i, - id: tc.id, - type: 'function', - function: { name: tc.function.name, arguments: tc.function.arguments } - }] - }, - finish_reason: null - }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - }); -}; - -const getSessionKey = (req, body) => { - const explicitId = - req.headers['x-conversation-id'] || - req.headers['x-session-id'] || - req.headers['conversation-id'] || - req.headers['session-id'] || - body.conversation_id || - body.conversationId || - body.session_id || - body.sessionId || - body.chat_id; - - if (explicitId && typeof explicitId === 'string' && explicitId.trim()) { - const trimmed = explicitId.trim(); - const cached = sessionStore.get(trimmed); - return { key: trimmed, explicit: true, cascadeId: cached?.cascadeId || (trimmed.includes('-') && trimmed.length === 36 ? trimmed : null) }; - } - - if (body.user && typeof body.user === 'string' && body.user.trim()) { - const userKey = `user:${body.user.trim()}`; - const cached = sessionStore.get(userKey); - return { key: userKey, explicit: false, cascadeId: cached?.cascadeId || null }; - } - - if (Array.isArray(body.messages) && body.messages.length > 1) { - const firstMsg = body.messages[0]; - const firstContent = typeof firstMsg?.content === 'string' - ? firstMsg.content - : JSON.stringify(firstMsg?.content || ''); - if (firstContent.length > 0) { - const hash = crypto.createHash('sha256').update(firstContent).digest('hex').slice(0, 16); - const sessionKey = `turn0:${hash}`; - const cached = sessionStore.get(sessionKey); - return { key: sessionKey, explicit: false, cascadeId: cached?.cascadeId || null }; - } - } - - return { key: null, explicit: false, cascadeId: null }; -}; - -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', '*'); - - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - // Health - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - try { - const active = await lsManager.ensureActive(); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'antigravity-ls-proxy', - port: PORT, - languageServer: { - port: active.port, - managed: lsManager.isManaged, - activeSessions: sessionStore.size - } - }, null, 2)); - } catch (err) { - res.writeHead(503, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ status: 'error', error: err.message })); - } - return; - } - - // Models catalog - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - const data = []; - - const registered = new Set(); - for (const [key, val] of Object.entries(MODEL_MAP)) { - if (val.name && !registered.has(key)) { - registered.add(key); - data.push({ - id: key, - object: 'model', - created: now, - owned_by: 'antigravity-ls', - display_name: val.name - }); - } - } - - try { - const liveModels = await getLiveCatalog(); - for (const [k, v] of Object.entries(liveModels)) { - if (!registered.has(k)) { - registered.add(k); - data.push({ - id: k, - object: 'model', - created: now, - owned_by: 'antigravity-ls', - display_name: v.displayName || k, - max_tokens: v.maxTokens || 65536, - supports_thinking: Boolean(v.supportsThinking) - }); - } - } - } catch {} - - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); - return; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(20 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Request payload exceeds 20MB limit' })); - req.destroy(); - } - }); - - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON request body' })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON request body: expected an object' })); - return; - } - - const stream = Boolean(body.stream); - const requestedEffort = body.reasoning_effort || body.effort || (body.options && (body.options.reasoning_effort || body.options.effort)); - let resolved; - try { - resolved = resolveModelEnum(body.model, requestedEffort, await getLiveCatalog()); - } catch (err) { - res.writeHead(err.status || 500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: err.message })); - return; - } - const { modelEnum, displayName, isCascade } = resolved; - - const sessionInfo = getSessionKey(req, body); - const useCascade = isCascade || Boolean(sessionInfo.cascadeId) || body.mode === 'cascade'; - - const reqId = `chatcmpl-${crypto.randomUUID()}`; - const created = Math.floor(Date.now() / 1000); - - try { - if (useCascade) { - // CASCADE TRAJECTORY MODE - let cascadeId = sessionInfo.cascadeId; - if (!cascadeId) { - const startResp = await lsManager.callRpc('StartCascade', { - workspaceUris: ['file:///home/user/code'], - source: 'CORTEX_TRAJECTORY_SOURCE_CLI' - }); - cascadeId = startResp.cascadeId; - } - - if (sessionInfo.key) { - sessionStore.set(sessionInfo.key, { cascadeId, updatedAt: Date.now() }); - pruneSessionStore(); - } - - const userPrompt = extractLatestUserPrompt(body.messages); - await lsManager.callRpc('SendUserCascadeMessage', { - cascadeId, - items: [{ text: userPrompt }], - cascadeConfig: { - plannerConfig: { - requestedModel: { - model: modelEnum - } - } - } - }); - - // Poll for completion, bounded by a strict elapsed-time - // deadline (#2102) instead of an iteration count. - let completedResponse = null; - let usageInfo = null; - const cascadeDeadline = Date.now() + CASCADE_DEADLINE_MS; - - while (completedResponse === null && Date.now() < cascadeDeadline) { - // Every step of the poll is bounded by the time left to the - // deadline (Codex review on PR #4080): the sleep is capped, - // the poll RPC is capped, and a response that lands after - // the deadline is not accepted. - await new Promise(r => setTimeout(r, Math.min(250, cascadeDeadline - Date.now()))); - const pollBudgetMs = cascadeDeadline - Date.now(); - if (pollBudgetMs <= 0) break; - let trajectory; - try { - trajectory = await lsManager.callRpc('GetCascadeTrajectorySteps', { cascadeId }, pollBudgetMs); - } catch (err) { - // The poll hit the remaining-budget cap: that is the - // cascade deadline expiring, not an RPC failure. - if (Date.now() >= cascadeDeadline) break; - throw err; - } - if (Date.now() >= cascadeDeadline) break; - const steps = trajectory?.steps || []; - const lastStep = steps[steps.length - 1]; - - if (lastStep?.errorMessage) { - throw new Error(lastStep.errorMessage?.error?.shortError || 'Cascade step error'); - } - - if (lastStep?.type === 'CORTEX_STEP_TYPE_PLANNER_RESPONSE' && lastStep?.status === 'CORTEX_STEP_STATUS_DONE') { - completedResponse = lastStep.plannerResponse?.response || lastStep.plannerResponse?.modifiedResponse || ''; - usageInfo = lastStep.metadata?.modelUsage || null; - break; - } - } - - if (completedResponse === null) { - throw new Error(`Cascade execution timed out after ${CASCADE_DEADLINE_MS}ms`); - } - - const inputTokens = parseInt(usageInfo?.inputTokens || '0', 10); - const outputTokens = parseInt(usageInfo?.outputTokens || '0', 10); - - const cascadeExtract = extractToolCalls(completedResponse, body.tools); - const cascadeContent = cascadeExtract.content; - const cascadeToolCalls = cascadeExtract.toolCalls; - const cascadeFinish = cascadeToolCalls.length > 0 ? 'tool_calls' : 'stop'; - const cascadeBase = { - id: reqId, - object: 'chat.completion.chunk', - created, - model: body.model || 'gemini-3.8-flash', - conversation_id: cascadeId - }; - - if (stream) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - 'Connection': 'keep-alive', - 'X-Conversation-Id': cascadeId, - 'X-Session-Id': cascadeId - }); - - if (cascadeContent) { - const chunk = { - ...cascadeBase, - choices: [{ index: 0, delta: { content: cascadeContent }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - - if (cascadeToolCalls.length > 0) writeToolCallChunks(res, cascadeBase, cascadeToolCalls); - - const finishChunk = { - ...cascadeBase, - choices: [{ index: 0, delta: {}, finish_reason: cascadeFinish }], - usage: { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens } - }; - res.write(`data: ${JSON.stringify(finishChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { - 'Content-Type': 'application/json', - 'X-Conversation-Id': cascadeId, - 'X-Session-Id': cascadeId - }); - res.end(JSON.stringify({ - id: reqId, - object: 'chat.completion', - created, - model: body.model || 'gemini-3.8-flash', - conversation_id: cascadeId, - choices: [{ - index: 0, - message: { - role: 'assistant', - content: cascadeToolCalls.length > 0 ? (cascadeContent || null) : cascadeContent, - ...(cascadeToolCalls.length > 0 ? { tool_calls: cascadeToolCalls } : {}) - }, - finish_reason: cascadeFinish - }], - usage: { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens } - }, null, 2)); - } - - } else { - // FAST DIRECT RPC MODE (GetModelResponse) - const prompt = formatPrompt(body.messages, body.tools); - const resp = await lsManager.callRpc('GetModelResponse', { - model: modelEnum, - prompt - }); - - const responseText = resp.response || ''; - const outTokens = Math.max(1, Math.round(responseText.length / 4)); - const inTokens = Math.max(1, Math.round(prompt.length / 4)); - - const extracted = extractToolCalls(responseText, body.tools); - const finalContent = extracted.content; - const toolCalls = extracted.toolCalls; - const finishReason = toolCalls.length > 0 ? 'tool_calls' : 'stop'; - - const activeId = sessionInfo.key || reqId; - const directBase = { - id: reqId, - object: 'chat.completion.chunk', - created, - model: body.model || 'gemini-3.8-flash', - conversation_id: activeId - }; - - if (stream) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - 'Connection': 'keep-alive', - 'X-Conversation-Id': activeId, - 'X-Session-Id': activeId - }); - - // Stream chunks - const words = finalContent ? finalContent.split(/(?<=\s+)/) : []; - for (const word of words) { - const chunk = { - ...directBase, - choices: [{ index: 0, delta: { content: word }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - - if (toolCalls.length > 0) writeToolCallChunks(res, directBase, toolCalls); - - const finishChunk = { - ...directBase, - choices: [{ index: 0, delta: {}, finish_reason: finishReason }], - usage: { prompt_tokens: inTokens, completion_tokens: outTokens, total_tokens: inTokens + outTokens } - }; - res.write(`data: ${JSON.stringify(finishChunk)}\n\n`); - - if (body.stream_options?.include_usage) { - const usageChunk = { - id: reqId, - object: 'chat.completion.chunk', - created, - model: body.model || 'gemini-3.8-flash', - conversation_id: activeId, - choices: [], - usage: { prompt_tokens: inTokens, completion_tokens: outTokens, total_tokens: inTokens + outTokens } - }; - res.write(`data: ${JSON.stringify(usageChunk)}\n\n`); - } - - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { - 'Content-Type': 'application/json', - 'X-Conversation-Id': activeId, - 'X-Session-Id': activeId - }); - res.end(JSON.stringify({ - id: reqId, - object: 'chat.completion', - created, - model: body.model || 'gemini-3.8-flash', - conversation_id: activeId, - choices: [{ - index: 0, - message: { - role: 'assistant', - content: toolCalls.length > 0 ? (finalContent || null) : finalContent, - ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}) - }, - finish_reason: finishReason - }], - usage: { prompt_tokens: inTokens, completion_tokens: outTokens, total_tokens: inTokens + outTokens } - }, null, 2)); - } - } - } catch (err) { - let status = err.status || 500; - let errType = 'api_error'; - const msg = err.message || 'Internal server error'; - - if (msg.includes('429') || msg.includes('RESOURCE_EXHAUSTED') || msg.includes('quota reached')) { - status = 429; - errType = 'insufficient_quota'; - } else if (msg.includes('Unknown model') || msg.includes('Invalid JSON') || status === 400) { - status = 400; - errType = 'invalid_request_error'; - } - - const errPayload = { - error: { - message: msg, - type: errType, - code: status - } - }; - - if (!res.headersSent) { - res.writeHead(status, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify(errPayload, null, 2)); - } else { - res.write(`data: ${JSON.stringify(errPayload)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } - } - }); - return; - } - - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Endpoint not found', path: pathname })); -}); - -server.listen(PORT, HOST, () => { - publishEndpoint(); - console.log(`Antigravity Language Server Proxy listening on http://${HOST}:${PORT}`); - console.log(`Endpoints:`); - console.log(` - GET http://${HOST}:${PORT}/health`); - console.log(` - GET http://${HOST}:${PORT}/v1/models`); - console.log(` - POST http://${HOST}:${PORT}/v1/chat/completions`); -}); diff --git a/bin/antigravity-ls-proxy.test.mjs b/bin/antigravity-ls-proxy.test.mjs deleted file mode 100644 index 30e7bf2375..0000000000 --- a/bin/antigravity-ls-proxy.test.mjs +++ /dev/null @@ -1,461 +0,0 @@ -// Tests for antigravity-ls-proxy's model resolution (#686). -// Run: node --test bin/antigravity-ls-proxy.test.mjs -// -// The proxy talks to an Antigravity language server over HTTP RPC. These -// tests run a stub language server, point the proxy at it via -// ANTIGRAVITY_LS_ADDRESS / ANTIGRAVITY_CSRF_TOKEN (the env attach path in -// detectRunningInstances), and capture the `model` value the proxy sends -// in GetModelResponse. A MODEL_MAP family entry carries metadata keys -// (`default`, `name`) besides effort -> enum, and an effort string that -// collides with one of those keys used to "resolve" to the metadata -// value — an effort name or a display name — instead of a model enum. -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import fs from 'node:fs'; -import http from 'node:http'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; -import test, { after, before } from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -let lsServer; -let proxyChild; -let proxyPort; -let capturedModel; -let capturedPrompt; -let stubResponse = 'stub answer'; - -const startStubLs = async () => { - lsServer = http.createServer((req, res) => { - let body = ''; - req.on('data', (c) => { body += c; }); - req.on('end', () => { - res.writeHead(200, { 'Content-Type': 'application/json' }); - if (req.url.endsWith('/GetAvailableModels')) { - res.end(JSON.stringify({ response: { models: {} } })); - } else if (req.url.endsWith('/GetModelResponse')) { - try { - const parsed = JSON.parse(body); - capturedModel = parsed.model; - capturedPrompt = parsed.prompt; - } catch { capturedModel = null; capturedPrompt = null; } - res.end(JSON.stringify({ response: stubResponse })); - } else { - // Heartbeat and anything else: a bare 200 is all the proxy checks. - res.end('{}'); - } - }); - }); - const port = await freePort(); - await new Promise((resolve) => lsServer.listen(port, '127.0.0.1', resolve)); - return port; -}; - -before(async () => { - const lsPort = await startStubLs(); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-proxy-test-')); - proxyPort = await freePort(); - proxyChild = spawn(process.execPath, [path.join(binDir, 'antigravity-ls-proxy.mjs')], { - env: { - ...process.env, - ANTIGRAVITY_LS_PROXY_PORT: String(proxyPort), - ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${lsPort}`, - ANTIGRAVITY_CSRF_TOKEN: 'test-token', - XDG_STATE_HOME: path.join(tmp, 'state') - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - proxyChild.stdout.on('data', (d) => { log += d; }); - proxyChild.stderr.on('data', (d) => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${proxyPort}/health`); - if (res.ok) break; - } catch {} - if (Date.now() > deadline) throw new Error(`proxy did not start: ${log}`); - await new Promise((r) => setTimeout(r, 100)); - } -}); - -after(() => { - if (proxyChild) proxyChild.kill('SIGKILL'); - if (lsServer) lsServer.close(); -}); - -const chat = async (payload) => { - capturedModel = undefined; - capturedPrompt = undefined; - const res = await fetch(`http://127.0.0.1:${proxyPort}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - messages: [{ role: 'user', content: 'hello' }], - ...payload - }) - }); - return res; -}; - -const echoTools = [{ - type: 'function', - function: { - name: 'run_echo', - description: 'echo a word', - parameters: { - type: 'object', - properties: { word: { type: 'string' }, count: { type: 'number' } }, - required: ['word'] - } - } -}]; - -test("effort 'default' falls back to the family default enum, not the string 'medium'", async () => { - const res = await chat({ model: 'gemini-3.8-flash', reasoning_effort: 'default' }); - assert.equal(res.status, 200); - assert.equal(capturedModel, 'MODEL_PLACEHOLDER_M319'); -}); - -test("effort 'name' falls back to the family default enum, not the display name", async () => { - const res = await chat({ model: 'gemini-3.8-flash', reasoning_effort: 'name' }); - assert.equal(res.status, 200); - assert.equal(capturedModel, 'MODEL_PLACEHOLDER_M319'); -}); - -test('a valid effort still resolves to its own enum', async () => { - const res = await chat({ model: 'gemini-3.8-flash', reasoning_effort: 'high' }); - assert.equal(res.status, 200); - assert.equal(capturedModel, 'MODEL_PLACEHOLDER_M318'); -}); - -test('an unoffered effort still falls back to the family default', async () => { - const res = await chat({ model: 'gemini-3.1-pro', reasoning_effort: 'medium' }); - assert.equal(res.status, 200); - assert.equal(capturedModel, 'MODEL_PLACEHOLDER_M37'); -}); - -test('an unknown model is still refused with 400', async () => { - const res = await chat({ model: 'no-such-model-xyz' }); - assert.equal(res.status, 400); - assert.equal(capturedModel, undefined); -}); - -// --- Tool-call translation (#865) ------------------------------------------- -// The language server returns plain text; the proxy must lift the tool -// calls models spell in that text into structured OpenAI tool_calls, or -// tool-driven clients (OpenCode) execute nothing. - -test('the formatted prompt carries the tool-calling contract', async () => { - stubResponse = 'ok'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools }); - assert.equal(res.status, 200); - assert.match(capturedPrompt, /\[Tool Calling\]/); - assert.match(capturedPrompt, /```tool_call/); -}); - -test('a canonical tool_call fence becomes structured tool_calls', async () => { - stubResponse = '```tool_call\n{"name": "run_echo", "arguments": {"word": "banana", "count": 2}}\n```'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools }); - assert.equal(res.status, 200); - const body = await res.json(); - const choice = body.choices[0]; - assert.equal(choice.finish_reason, 'tool_calls'); - assert.equal(choice.message.content, null); - assert.equal(choice.message.tool_calls.length, 1); - const call = choice.message.tool_calls[0]; - assert.equal(call.type, 'function'); - assert.equal(call.function.name, 'run_echo'); - assert.deepEqual(JSON.parse(call.function.arguments), { word: 'banana', count: 2 }); - assert.ok(call.id.startsWith('call_')); -}); - -test('a Claude-style invoke block becomes tool_calls and prose survives', async () => { - stubResponse = 'Let me run that.\n\n\n\nbanana\n3\n\n'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools }); - assert.equal(res.status, 200); - const body = await res.json(); - const choice = body.choices[0]; - assert.equal(choice.finish_reason, 'tool_calls'); - assert.equal(choice.message.content, 'Let me run that.'); - assert.equal(choice.message.tool_calls.length, 1); - assert.deepEqual(JSON.parse(choice.message.tool_calls[0].function.arguments), { word: 'banana', count: 3 }); -}); - -test('a Gemini-style json fence becomes tool_calls', async () => { - stubResponse = '```json\n{ "name": "run_echo", "arguments": { "word": "banana" } }\n```'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools }); - assert.equal(res.status, 200); - const body = await res.json(); - assert.equal(body.choices[0].finish_reason, 'tool_calls'); - assert.equal(body.choices[0].message.tool_calls[0].function.name, 'run_echo'); -}); - -test('a block naming an unoffered tool is left as text', async () => { - stubResponse = '```tool_call\n{"name": "rm_rf", "arguments": {}}\n```'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools }); - assert.equal(res.status, 200); - const body = await res.json(); - assert.equal(body.choices[0].finish_reason, 'stop'); - assert.equal(body.choices[0].message.tool_calls, undefined); - assert.match(body.choices[0].message.content, /rm_rf/); -}); - -test('no tools in the request means no extraction', async () => { - stubResponse = '```tool_call\n{"name": "run_echo", "arguments": {"word": "banana"}}\n```'; - const res = await chat({ model: 'gemini-3.8-flash' }); - assert.equal(res.status, 200); - const body = await res.json(); - assert.equal(body.choices[0].finish_reason, 'stop'); - assert.equal(body.choices[0].message.tool_calls, undefined); -}); - -test('streaming emits a tool_calls delta and a tool_calls finish', async () => { - stubResponse = '```tool_call\n{"name": "run_echo", "arguments": {"word": "banana"}}\n```'; - const res = await chat({ model: 'gemini-3.8-flash', tools: echoTools, stream: true }); - assert.equal(res.status, 200); - const text = await res.text(); - const chunks = text.split('\n') - .filter(l => l.startsWith('data: ') && !l.includes('[DONE]')) - .map(l => JSON.parse(l.slice('data: '.length))); - const toolChunks = chunks.filter(c => c.choices[0]?.delta?.tool_calls); - assert.equal(toolChunks.length, 1); - assert.equal(toolChunks[0].choices[0].delta.tool_calls[0].function.name, 'run_echo'); - const finish = chunks[chunks.length - 1]; - assert.equal(finish.choices[0].finish_reason, 'tool_calls'); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async () => { - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${proxyPort}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${proxyPort}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); - -// --- RPC timeouts (#2102) --------------------------------------------------- -// A language server that passes heartbeat but never answers an RPC used to -// hang /v1/models and every chat request forever: callRpc fetched with no -// timeout. These tests run their own stub + proxy pairs with short injected -// budgets (ANTIGRAVITY_LS_RPC_TIMEOUTS / ANTIGRAVITY_LS_CASCADE_DEADLINE_MS) -// so nothing waits for the production budgets. - -const startTimeoutRig = async ({ hang = [], delayMs = {}, cascadeSteps = [], timeouts = {}, cascadeDeadlineMs = 30_000 } = {}) => { - const hangSet = new Set(hang); - const stub = http.createServer((req, res) => { - let body = ''; - req.on('data', (c) => { body += c; }); - req.on('end', () => { - const method = req.url.split('/').pop(); - if (hangSet.has(method)) return; // heartbeat-ok, RPC never answers - const respond = () => { - if (res.destroyed) return; - res.writeHead(200, { 'Content-Type': 'application/json' }); - if (method === 'GetAvailableModels') res.end(JSON.stringify({ response: { models: {} } })); - else if (method === 'GetModelResponse') res.end(JSON.stringify({ response: 'slow but alive' })); - else if (method === 'StartCascade') res.end(JSON.stringify({ cascadeId: 'cascade-timeout-test' })); - else if (method === 'GetCascadeTrajectorySteps') res.end(JSON.stringify({ steps: cascadeSteps })); - else res.end('{}'); - }; - const d = delayMs[method] || 0; - if (d) setTimeout(respond, d); else respond(); - }); - }); - const lsPort = await freePort(); - await new Promise((resolve) => stub.listen(lsPort, '127.0.0.1', resolve)); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-proxy-timeout-test-')); - const port = await freePort(); - const child = spawn(process.execPath, [path.join(binDir, 'antigravity-ls-proxy.mjs')], { - env: { - ...process.env, - ANTIGRAVITY_LS_PROXY_PORT: String(port), - ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${stub.address().port}`, - ANTIGRAVITY_CSRF_TOKEN: 'test-token', - ANTIGRAVITY_LS_RPC_TIMEOUTS: JSON.stringify(timeouts), - ANTIGRAVITY_LS_CASCADE_DEADLINE_MS: String(cascadeDeadlineMs), - XDG_STATE_HOME: path.join(tmp, 'state') - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', (d) => { log += d; }); - child.stderr.on('data', (d) => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch {} - if (Date.now() > deadline) throw new Error(`timeout-rig proxy did not start: ${log}`); - await new Promise((r) => setTimeout(r, 100)); - } - return { - port, - close: () => { child.kill('SIGKILL'); stub.close(); } - }; -}; - -test('a hung GetAvailableModels still serves the static catalog, bounded (#2102)', async () => { - const rig = await startTimeoutRig({ hang: ['GetAvailableModels'], timeouts: { GetAvailableModels: 200 } }); - try { - const t0 = Date.now(); - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/models`); - const elapsed = Date.now() - t0; - assert.equal(res.status, 200); - const body = await res.json(); - assert.ok(body.data.some((m) => m.id === 'gemini-3.8-flash'), 'static MODEL_MAP catalog must be served'); - assert.ok(elapsed < 5000, `models took ${elapsed}ms; the catalog RPC must be bounded`); - } finally { rig.close(); } -}); - -test('a hung GetModelResponse returns a clean bounded API error (#2102)', async () => { - const rig = await startTimeoutRig({ hang: ['GetModelResponse'], timeouts: { GetModelResponse: 200 } }); - try { - const t0 = Date.now(); - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'gemini-3.8-flash', messages: [{ role: 'user', content: 'hello' }] }) - }); - const elapsed = Date.now() - t0; - assert.notEqual(res.status, 200); - const body = await res.json(); - assert.match(JSON.stringify(body), /GetModelResponse timed out after 200ms/); - assert.ok(elapsed < 5000, `chat took ${elapsed}ms; the RPC must be bounded`); - } finally { rig.close(); } -}); - -test('a slow-but-alive RPC below its budget still succeeds (#2102)', async () => { - const rig = await startTimeoutRig({ delayMs: { GetModelResponse: 100 }, timeouts: { GetModelResponse: 2000 } }); - try { - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'gemini-3.8-flash', messages: [{ role: 'user', content: 'hello' }] }) - }); - assert.equal(res.status, 200); - const body = await res.json(); - assert.equal(body.choices[0].message.content, 'slow but alive'); - } finally { rig.close(); } -}); - -test('cascade polling stops at the elapsed deadline, not an iteration count (#2102)', async () => { - const rig = await startTimeoutRig({ - timeouts: { GetCascadeTrajectorySteps: 1000 }, - cascadeDeadlineMs: 600, - cascadeSteps: [] - }); - try { - const t0 = Date.now(); - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) - }); - const elapsed = Date.now() - t0; - assert.notEqual(res.status, 200); - const body = await res.json(); - assert.match(JSON.stringify(body), /Cascade execution timed out after 600ms/); - assert.ok(elapsed < 5000, `cascade took ${elapsed}ms; the deadline must bound it`); - } finally { rig.close(); } -}); - -test('a cascade poll that lands after the deadline is not accepted (#2102)', async () => { - // Codex repro on PR #4080: with a 100ms cascade deadline and a 1000ms - // trajectory delay, the old loop accepted the late completion and - // answered 200 after ~1.3s. The poll must be bounded by the remaining - // deadline budget and the late response discarded. - const rig = await startTimeoutRig({ - cascadeDeadlineMs: 100, - delayMs: { GetCascadeTrajectorySteps: 1000 }, - cascadeSteps: [{ - type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', - status: 'CORTEX_STEP_STATUS_DONE', - plannerResponse: { response: 'late answer' }, - metadata: {} - }] - }); - try { - const t0 = Date.now(); - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) - }); - const elapsed = Date.now() - t0; - assert.notEqual(res.status, 200); - const body = await res.json(); - assert.match(JSON.stringify(body), /Cascade execution timed out after 100ms/); - assert.ok(elapsed < 800, `cascade took ${elapsed}ms; a late poll must not stretch past the deadline`); - } finally { rig.close(); } -}); - -test('a healthy cascade still completes (#2102)', async () => { - const rig = await startTimeoutRig({ - cascadeSteps: [{ - type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', - status: 'CORTEX_STEP_STATUS_DONE', - plannerResponse: { response: 'cascade answer' }, - metadata: {} - }] - }); - try { - const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) - }); - assert.equal(res.status, 200); - const body = await res.json(); - assert.equal(body.choices[0].message.content, 'cascade answer'); - } finally { rig.close(); } -}); -test('preserves UTF-8 split across HTTP request-body chunks (#3186)', async () => { - const content = 'before-😀-after'; - const body = Buffer.from(JSON.stringify({ - model: 'gemini-3.8-flash', - messages: [{ role: 'user', content }] - }), 'utf8'); - const emojiStart = body.indexOf(Buffer.from('😀', 'utf8')); - const chunks = [body.subarray(0, emojiStart + 2), body.subarray(emojiStart + 2)]; - capturedPrompt = undefined; - - const response = await new Promise((resolve, reject) => { - const request = http.request({ - hostname: '127.0.0.1', - port: proxyPort, - path: '/v1/chat/completions', - method: 'POST', - headers: { 'Content-Type': 'application/json' } - }, (res) => { - res.resume(); - res.on('end', () => resolve(res.statusCode)); - }); - request.on('error', reject); - request.write(chunks[0]); - request.write(chunks[1]); - request.end(); - }); - - assert.equal(response, 200); - assert.match(capturedPrompt, /before-😀-after/); -}); diff --git a/bin/claude-code-proxy.mjs b/bin/claude-code-proxy.mjs deleted file mode 100644 index 2e7b3d74f1..0000000000 --- a/bin/claude-code-proxy.mjs +++ /dev/null @@ -1,812 +0,0 @@ -#!/usr/bin/env node -// claude-code-proxy — OpenAI-compatible bridge to the Claude Code CLI. -// -// Same shape as the fleet's other warm bridges (bin/muse-proxy.mjs's serve -// pool, bin/commandcode-proxy.mjs's resident ACP process): one PERSISTENT -// `claude` process per conversation, never a spawn per request. Each -// conversation runs the CLI in bidirectional stream-json mode -// (`claude -p --input-format stream-json --output-format stream-json`), so -// a conversation's first turn pays the process start + full context once -// and later turns send only the newest user message — the CLI session -// itself holds the history, and Anthropic's prompt cache serves the -// replayed prefix. -// -// Conversations are keyed like commandcode-proxy keys them (explicit -// session headers / body ids, else a hash of the first user message), and -// the key -> CLI session map persists to sessions.json in the shared -// CLI-proxy state root (~/.local/state/cli-proxies, #3067), -// so a proxy restart re-attaches with `--resume ` instead of -// re-bootstrapping. A request whose history no longer matches the mapped -// session (diverged prefix, extra mid-history user turns, lost session) -// is re-bootstrapped as a fresh session whose first turn is the full -// flattened transcript — the same text the cold path would send. A turn -// that fails before any content is committed is retried once that way. -// -// Auth is the CLI's own claude.ai OAuth login (~/.claude, under $HOME). -// ANTHROPIC_API_KEY is explicitly deleted from the child env: when set it -// outranks the account login and bills the pay-as-you-go API instead of -// the subscription. Children also get the sandbox's unauthenticated -// egress proxy + CA bundle pinned (fleet machines with direct egress set -// CLAUDE_CODE_PROXY_EGRESS="" in their start wrapper to disable that). -import http from 'node:http'; -import { spawn } from 'node:child_process'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { parseProxyPort } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -// Default port 18749: the next free port in the fleet family (clef 18742, -// agy 18743, codex 18744, antigravity-ls 18745, design-code 18746, -// muse 18747, commandcode 18748). -const PORT = parseProxyPort('CLAUDE_CODE_PROXY_PORT', 18749); -const HOST = process.env.CLAUDE_CODE_PROXY_HOST || '127.0.0.1'; - -const EGRESS_PROXY = process.env.CLAUDE_CODE_PROXY_EGRESS ?? 'http://hatch-egress-proxy:3128'; -const EGRESS_CA = '/run/hatch/egress-tls/ca-bundle.pem'; - -const PROXY_DIR = path.dirname(fileURLToPath(import.meta.url)); -const WORKROOT = process.env.CLAUDE_CODE_PROXY_WORKDIR || path.join(PROXY_DIR, 'work'); -fs.mkdirSync(WORKROOT, { recursive: true }); - -// Session map: SHARED with commandcode-proxy (mirrored key space), so -// both proxies must resolve to the SAME path -- the shared CLI-proxy -// state root, not the script's directory: bin/ is the tracked checkout, -// and every write there dirtied the primary clone and blocked -// pm-git-sync (#3067; missed by the #2782 workdir move). -const SESSION_FILE = - process.env.CLAUDE_CODE_PROXY_SESSION_FILE || - path.join( - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), - 'cli-proxies', - 'sessions.json' - ); -fs.mkdirSync(path.dirname(SESSION_FILE), { recursive: true }); -const MAX_LIVE_SESSIONS = 32; -const IDLE_TTL_MS = 2 * 60 * 60 * 1000; -const TURN_TIMEOUT_MS = 300 * 1000; - -// The models the sandbox opencode.jsonc advertises for this provider. -// Any other requested id is passed through to the CLI untouched. -// Sonnet/Opus ids verified against the CLI's own session records on the -// laptop (~/.claude/projects: claude-sonnet-5-5 and claude-opus-5-5 are -// models this CLI has served under the fleet account). Issue #1132. -const MODELS = [ - { id: 'claude-haiku-5-5', name: 'Haiku 5.5 (Claude Code)' }, - { id: 'claude-sonnet-5-5', name: 'Sonnet 5.5 (Claude Code)' }, - { id: 'claude-opus-5-5', name: 'Opus 5.5 (Claude Code)' } -]; -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, - `${process.env.HOME}/tools/claude-code/package/claude`, - `${process.env.HOME}/.local/bin/claude`, - 'claude' - ]; - for (const c of candidates) { - if (c && (c === 'claude' || fs.existsSync(c))) return c; - } - return 'claude'; -}; -const CLAUDE_BIN = findClaudeBinary(); - -const resolveModel = (requested) => { - let raw = (requested || DEFAULT_MODEL).trim(); - raw = raw.replace(/^.*\//, '').trim(); // strip any provider prefix - return raw || DEFAULT_MODEL; -}; - -// Child env: inherit, but strip ANTHROPIC_API_KEY (it outranks the OAuth -// login) and pin the egress proxy + CA bundle the CLI needs here. -const childEnv = () => { - const env = { ...process.env }; - delete env.ANTHROPIC_API_KEY; - if (EGRESS_PROXY) { - env.HTTPS_PROXY = EGRESS_PROXY; - env.HTTP_PROXY = EGRESS_PROXY; - env.https_proxy = EGRESS_PROXY; - env.http_proxy = EGRESS_PROXY; - env.NODE_USE_ENV_PROXY = '1'; - } - if (EGRESS_PROXY && fs.existsSync(EGRESS_CA)) env.SSL_CERT_FILE = EGRESS_CA; - env.NO_PROXY = [env.NO_PROXY, '127.0.0.1', 'localhost', '::1'].filter(Boolean).join(','); - env.no_proxy = env.NO_PROXY; - return env; -}; - -// --------------------------------------------------------------------------- -// Message helpers (mirror muse-proxy / commandcode-proxy) -// --------------------------------------------------------------------------- -const messageText = (m) => { - if (!m || typeof m !== 'object') return ''; - if (typeof m.content === 'string') return m.content; - if (Array.isArray(m.content)) { - return m.content.map(c => (c && typeof c.text === 'string') ? c.text : '').join('\n'); - } - return m.content ? JSON.stringify(m.content) : ''; -}; - -const messageHash = (m) => - crypto.createHash('sha256').update(`${m.role}\x00${messageText(m)}`).digest('hex'); - -const formatTranscript = (messages) => { - const convo = messages.filter(m => m.role !== 'system'); - return convo.map(m => { - let role = m.role === 'assistant' ? 'Assistant' : (m.role === 'user' ? 'User' : m.role); - let text = messageText(m); - if (m.tool_calls && Array.isArray(m.tool_calls)) { - const tcStr = m.tool_calls.map(tc => `[Tool Call: ${tc.function?.name || 'function'}(${tc.function?.arguments || ''})]`).join('\n'); - text = text ? `${text}\n${tcStr}` : tcStr; - } - if (m.role === 'tool') role = `Tool Result (${m.tool_call_id || 'result'})`; - return `${role}: ${text}`; - }).join('\n\n'); -}; - -const systemText = (messages) => - messages.filter(m => m.role === 'system').map(messageText).join('\n\n'); - -// Conversation key derivation mirrors commandcode-proxy's getSessionKey: -// explicit ids first, then `user:`, then a hash of the first USER message -// (messages[0] is OpenCode's identical system prompt for every session -// and would collide all conversations). -const getSessionKey = (req, body) => { - const explicitId = - req.headers['x-conversation-id'] || - req.headers['x-session-id'] || - req.headers['conversation-id'] || - req.headers['session-id'] || - body.conversation_id || - body.conversationId || - body.session_id || - body.sessionId || - body.chat_id; - if (explicitId && typeof explicitId === 'string' && explicitId.trim()) { - return explicitId.trim(); - } - if (body.user && typeof body.user === 'string' && body.user.trim()) { - return `user:${body.user.trim()}`; - } - if (Array.isArray(body.messages) && body.messages.length > 0) { - const firstUser = body.messages.find(m => m.role === 'user'); - const firstContent = firstUser ? messageText(firstUser) : ''; - if (firstContent.length > 0) { - const hash = crypto.createHash('sha256').update(firstContent).digest('hex').slice(0, 16); - return `turn0:${hash}`; - } - } - return null; -}; - -// One stable workdir per conversation key: the CLI keys its on-disk -// project state by cwd slug, so a stable cwd keeps a conversation's -// transcript in a single ~/.claude/projects// directory. -const sessionWorkdirFor = (key) => { - const hash = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16); - const dir = path.join(WORKROOT, 'sessions', hash); - fs.mkdirSync(dir, { recursive: true }); - return dir; -}; - -// --------------------------------------------------------------------------- -// Persisted key -> CLI session map (survives proxy restarts; re-attached -// with --resume) -// --------------------------------------------------------------------------- -const sessionStore = new Map(); -const saveSessions = () => { - try { - const obj = {}; - for (const [k, v] of sessionStore) obj[k] = v; - fs.writeFileSync(`${SESSION_FILE}.tmp`, JSON.stringify(obj, null, 2) + '\n'); - fs.renameSync(`${SESSION_FILE}.tmp`, SESSION_FILE); - } catch (err) { - console.warn(`[claude-code-proxy] Failed to persist session store: ${err.message}`); - } -}; -const loadSessions = () => { - try { - const obj = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - const now = Date.now(); - for (const [k, v] of Object.entries(obj)) { - if (v && typeof v.sessionId === 'string' && now - (v.lastUsedAt || 0) <= IDLE_TTL_MS) { - sessionStore.set(k, v); - } - } - if (sessionStore.size > 0) { - console.log(`[claude-code-proxy] Loaded ${sessionStore.size} warm-session mapping(s) from ${SESSION_FILE}`); - } - } catch { /* no state yet */ } -}; -loadSessions(); - -// --------------------------------------------------------------------------- -// One resident `claude` stream-json process per conversation -// --------------------------------------------------------------------------- -class ClaudeSession { - constructor({ key, model, sessionId, resume, system }) { - this.key = key; - this.model = model; - this.sessionId = sessionId; - this.child = null; - this.ready = false; - this.dead = null; // Error once the child is gone - this.lineBuffer = ''; - this.stderrTail = ''; - this.stdoutDecoder = createStreamDecoder(); - this.stderrDecoder = createStreamDecoder(); - this.turnWaiter = null; // { resolve, reject, onDelta, deltasText, lastAssistantText } - this.workdir = sessionWorkdirFor(key); - - const args = [ - '-p', - '--input-format', 'stream-json', - '--output-format', 'stream-json', - '--verbose', - '--include-partial-messages', - '--model', model - // No --permission-mode: bypassPermissions is refused outright when - // the CLI runs as root (the sandbox unit does), and default mode - // routes tool approvals through can_use_tool control requests, - // which _onMessage answers — see below. - ]; - if (resume) args.push('--resume', sessionId); - else args.push('--session-id', sessionId); - if (!resume && system) args.push('--append-system-prompt', system); - - console.log(`[claude-code-proxy] Spawning session ${sessionId} (key ${key.slice(0, 24)}, ${resume ? 'resume' : 'fresh'}): ${CLAUDE_BIN} ${args.slice(0, 12).join(' ')}...`); - const child = spawn(CLAUDE_BIN, args, { - cwd: this.workdir, - env: childEnv(), - stdio: ['pipe', 'pipe', 'pipe'] - }); - this.child = child; - - this.initPromise = new Promise((resolve, reject) => { - this._initResolve = resolve; - this._initReject = reject; - setTimeout(() => { - if (!this.ready) { - const err = new Error(`claude session ${sessionId} did not init within 30s`); - this._initReject(err); - } - }, 30000).unref(); - }); - this.initPromise.catch(() => {}); // rejection is surfaced via runTurn - - // The stream-json protocol starts with an initialize control - // request: the CLI emits nothing (not even system/init) until it - // receives one (verified live against CLI 2.1.293). - this.initRequestId = crypto.randomUUID(); - child.stdout.on('data', chunk => this._onStdout(chunk)); - child.stderr.on('data', chunk => { - const msg = this.stderrDecoder.push(chunk); - this.stderrTail = (this.stderrTail + msg).slice(-2000); - if (msg.trim()) console.warn(`[claude-code-proxy stderr ${sessionId.slice(0, 8)}] ${msg.trim().slice(0, 300)}`); - }); - child.on('error', err => this._onExit(`spawn error: ${err.message}`)); - child.on('close', (code, signal) => this._onExit(`claude exited (code ${code}, signal ${signal})`)); - try { - this._write({ - type: 'control_request', - request_id: this.initRequestId, - request: { subtype: 'initialize' } - }); - } catch (err) { - this._onExit(`initialize write failed: ${err.message}`); - } - } - - _onExit(reason) { - if (this.dead) return; - this.dead = new Error(`${reason}${this.stderrTail ? `: ${this.stderrTail.trim().split('\n').pop()}` : ''}`); - this.ready = false; - if (this._initReject) this._initReject(this.dead); - if (this.turnWaiter) { - const w = this.turnWaiter; - this.turnWaiter = null; - w.reject(this.dead); - } - } - - _onStdout(chunk) { - this.lineBuffer += this.stdoutDecoder.push(chunk); - const lines = this.lineBuffer.split('\n'); - this.lineBuffer = lines.pop(); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) continue; - let msg; - try { msg = JSON.parse(trimmed); } catch { continue; } - this._onMessage(msg); - } - } - - _onMessage(msg) { - if (msg.type === 'system' && msg.subtype === 'init') { - if (typeof msg.session_id === 'string') this.sessionId = msg.session_id; - this.ready = true; - if (this._initResolve) this._initResolve(this.sessionId); - return; - } - if (msg.type === 'control_response' && - msg.response?.request_id === this.initRequestId && - msg.response?.subtype === 'success') { - // system/init follows immediately; treat the handshake answer as - // readiness too so a turn is never gated on event ordering. - this.ready = true; - if (this._initResolve) this._initResolve(this.sessionId); - return; - } - // Tool approvals arrive as can_use_tool control requests and a - // request left unanswered would stall the turn. Answer allow, the - // same posture as muse-proxy's serve sessions (approvalMode - // allowAll): the CLI works in a per-conversation workdir under the - // proxy's own workroot. - if (msg.type === 'control_request' && msg.request?.subtype === 'can_use_tool') { - this._write({ - type: 'control_response', - response: { - subtype: 'success', - request_id: msg.request_id, - response: { behavior: 'allow', updatedInput: msg.request.input || {} } - } - }); - return; - } - const w = this.turnWaiter; - if (!w) return; - if (msg.type === 'stream_event' && msg.event) { - const ev = msg.event; - if (ev.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && typeof ev.delta.text === 'string') { - w.deltasText += ev.delta.text; - if (w.onDelta) { try { w.onDelta(ev.delta.text); } catch { /* response gone */ } } - } - return; - } - if (msg.type === 'assistant' && msg.message && Array.isArray(msg.message.content)) { - const text = msg.message.content - .filter(c => c && c.type === 'text' && typeof c.text === 'string') - .map(c => c.text).join(''); - if (text) w.lastAssistantText = text; - return; - } - if (msg.type === 'result') { - this.turnWaiter = null; - if (msg.subtype && msg.subtype !== 'success') { - const detail = (typeof msg.result === 'string' && msg.result) || - (Array.isArray(msg.errors) && msg.errors.join('; ')) || - `result subtype ${msg.subtype}`; - w.reject(new Error(`claude turn failed: ${String(detail).slice(0, 300)}`)); - return; - } - const usage = msg.usage || {}; - w.resolve({ - deltasText: w.deltasText, - fullText: (typeof msg.result === 'string' && msg.result) || w.lastAssistantText || w.deltasText, - promptTokens: typeof usage.input_tokens === 'number' - ? usage.input_tokens + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0) - : undefined, - completionTokens: typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined - }); - } - } - - _write(obj) { - if (!this.child || !this.child.stdin.writable) throw new Error('claude session stdin is not writable'); - this.child.stdin.write(JSON.stringify(obj) + '\n'); - } - - async runTurn(text, onDelta) { - if (this.dead) throw this.dead; - await this.initPromise; - if (this.dead) throw this.dead; - if (this.turnWaiter) throw new Error('claude session already has a turn in flight'); - return new Promise((resolve, reject) => { - const waiter = { - deltasText: '', - lastAssistantText: null, - 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(); // a wedged session must not poison later turns - reject(new Error(`claude turn timed out after ${TURN_TIMEOUT_MS}ms`)); - } - }, TURN_TIMEOUT_MS); - this.turnWaiter = waiter; - try { - this._write({ - type: 'user', - message: { role: 'user', content: [{ type: 'text', text }] }, - session_id: this.sessionId - }); - } catch (err) { - this.turnWaiter = null; - waiter.reject(err); - } - }); - } - - kill() { - if (this.child && !this.child.killed) { - try { this.child.kill('SIGTERM'); } catch { /* already gone */ } - const child = this.child; - setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } }, 3000).unref(); - } - } -} - -// Live sessions + per-key serialization (turns on one CLI session must -// not interleave, and the delta decision needs the latest committed -// state). -const liveSessions = new Map(); -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 evictIfNeeded = () => { - const live = [...liveSessions.entries()] - .filter(([, s]) => !s.dead) - .sort((a, b) => (a[1].lastUsedAt || 0) - (b[1].lastUsedAt || 0)); - while (live.length >= MAX_LIVE_SESSIONS) { - const [key, sess] = live.shift(); - console.log(`[claude-code-proxy] Evicting idle session for key ${key.slice(0, 24)}`); - sess.kill(); - liveSessions.delete(key); - } - // Idle TTL sweep - const now = Date.now(); - for (const [key, sess] of liveSessions) { - if (now - (sess.lastUsedAt || 0) > IDLE_TTL_MS) { - sess.kill(); - liveSessions.delete(key); - } - } -}; -setInterval(evictIfNeeded, 60000).unref(); - -// Attempt the chat completion on the resident-session path. Mirrors -// muse-proxy's tryWarmChat contract: true when the response has been -// fully handled, false when nothing was written and the caller should -// retry once with a fresh full-transcript session. -const trySessionChat = async ({ key, messages, model, stream, res, chatId, created, forceFresh }) => { - const hashes = messages.map(messageHash); - let entry = forceFresh ? null : sessionStore.get(key); - let sess = forceFresh ? null : liveSessions.get(key); - if (sess && (sess.dead || sess.model !== model)) { - sess.kill(); - liveSessions.delete(key); - sess = null; - } - - // Delta decision (against the stored mapping, whether or not a live - // process exists): the stored prefix must match exactly and the only - // new content allowed is one trailing user message. - let turnText = null; - if (entry && entry.model === model) { - const last = messages[messages.length - 1]; - const suffix = messages.slice(entry.sentCount); - const prefixOk = entry.sentCount > 0 && - entry.hashes.length >= entry.sentCount && - entry.hashes.slice(0, entry.sentCount).every((h, i) => h === hashes[i]); - const midUsers = suffix.slice(0, -1).filter(m => m.role === 'user').length; - if (prefixOk && suffix.length > 0 && last.role === 'user' && midUsers === 0) { - turnText = messageText(last); - } - } - - if (sess && turnText === null) { - console.log(`[claude-code-proxy] history diverged for key ${key.slice(0, 24)}; re-bootstrapping`); - sess.kill(); - liveSessions.delete(key); - sess = null; - entry = null; - } - - if (!sess) { - evictIfNeeded(); - // A stored session may be re-attached with --resume only when the - // delta decision passed; anything else starts fresh. - const canResume = Boolean(entry && entry.sessionId && turnText !== null); - const sessionId = canResume ? entry.sessionId : crypto.randomUUID(); - sess = new ClaudeSession({ - key, - model, - sessionId, - resume: canResume, - system: systemText(messages) - }); - liveSessions.set(key, sess); - if (!canResume) { - // Fresh session: a lone user turn is sent as-is; anything longer - // (re-bootstrap) goes as the full flattened transcript. The system - // prompt rides --append-system-prompt at spawn instead. - const nonSystem = messages.filter(m => m.role !== 'system'); - turnText = (nonSystem.length === 1 && nonSystem[0].role === 'user') - ? messageText(nonSystem[0]) - : formatTranscript(messages); - } - } - sess.lastUsedAt = Date.now(); - - let headed = false; - const writeChunk = (content) => { - if (!stream || res.writableEnded) return; - if (!headed) { - headed = true; - res.writeHead(200, { - 'Content-Type': 'text/event-stream; charset=utf-8', - 'Cache-Control': 'no-cache, no-transform', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no' - }); - } - res.write(`data: ${JSON.stringify({ - id: chatId, object: 'chat.completion.chunk', created, model, - choices: [{ index: 0, delta: { content }, finish_reason: null }] - })}\n\n`); - }; - - let result; - try { - result = await sess.runTurn(turnText, stream ? writeChunk : null); - } catch (err) { - // Dead/lost session: drop the mapping so the retry starts clean. - liveSessions.delete(key); - sessionStore.delete(key); - saveSessions(); - if (!headed) return false; - if (!res.writableEnded) { - res.write(`data: ${JSON.stringify({ error: { message: `Claude Code execution failed: ${err.message}` } })}\n\n`); - res.write('data: [DONE]\n\n'); - } - res.end(); - return true; - } - - // Commit the mapping only after a successful turn. - const committed = { - sessionId: sess.sessionId, model, - hashes, sentCount: messages.length, lastUsedAt: Date.now() - }; - sessionStore.set(key, committed); - saveSessions(); - - let fullContent = result.deltasText; - let unstreamedSuffix = ''; - if (typeof result.fullText === 'string' && result.fullText.length >= fullContent.length) { - if (result.fullText.startsWith(fullContent)) unstreamedSuffix = result.fullText.slice(fullContent.length); - fullContent = result.fullText; - } - const promptTokens = (typeof result.promptTokens === 'number' && result.promptTokens > 0) - ? result.promptTokens - : Math.max(1, Math.ceil(turnText.length / 4)); - let completionTokens = (typeof result.completionTokens === 'number' && result.completionTokens > 0) - ? result.completionTokens - : 0; - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - - if (stream) { - if (unstreamedSuffix.length > 0) writeChunk(unstreamedSuffix); - if (!headed) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream; charset=utf-8', - 'Cache-Control': 'no-cache, no-transform', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no' - }); - } - res.write(`data: ${JSON.stringify({ - id: chatId, object: 'chat.completion.chunk', created, model, - choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], - usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens } - })}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: chatId, object: 'chat.completion', created, model, - choices: [{ index: 0, message: { role: 'assistant', content: fullContent }, finish_reason: 'stop' }], - usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens } - }, null, 2)); - } - return true; -}; - -const server = http.createServer((req, res) => { - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', '*'); - if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'claude-code-proxy', - port: PORT, - binary: CLAUDE_BIN, - engine: 'claude-stream-json-resident', - defaultModel: DEFAULT_MODEL, - endpoint: '/v1/chat/completions', - sessions: { - live: [...liveSessions.values()].filter(s => !s.dead).length, - stored: sessionStore.size, - chains: chains.size - } - }, null, 2)); - return; - } - - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - object: 'list', - data: getServedModels().map(m => ({ id: m.id, object: 'model', created: now, owned_by: 'anthropic-claude-code' })) - }, null, 2)); - return; - } - - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); - req.destroy(); - } - }); - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { body = JSON.parse(bodyText); } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Invalid JSON body: ${err.message}` } })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Invalid JSON body: expected an object' } })); - return; - } - const messages = Array.isArray(body.messages) ? body.messages : []; - if (messages.length === 0) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Messages cannot be empty' } })); - return; - } - const model = resolveModel(body.model); - const stream = Boolean(body.stream); - const chatId = `chatcmpl-claude-code-${crypto.randomUUID()}`; - const created = Math.floor(Date.now() / 1000); - const key = getSessionKey(req, body) || `anon:${crypto.randomUUID()}`; - - const job = async () => { - let handled = await trySessionChat({ key, messages, model, stream, res, chatId, created, forceFresh: false }); - if (!handled && !res.writableEnded) { - console.warn(`[claude-code-proxy] session path failed for key ${key.slice(0, 24)}; retrying once with a fresh session`); - handled = await trySessionChat({ key, messages, model, stream, res, chatId, created, forceFresh: true }); - } - if (!handled && !res.writableEnded) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Claude Code execution failed' } })); - } - }; - try { - await enqueue(key, job); - } catch (err) { - if (!res.writableEnded && !res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Claude Code execution failed: ${err.message}` } })); - } - } - }); - return; - } - - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); -}); - -// Publish the bound endpoint ($XDG_STATE_HOME/claude-code-proxy/ -// endpoint.json) like the other fleet proxies, removed on exit. -const publishEndpoint = () => { - try { - const stateHome = process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'claude-code-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync(`${file}.tmp`, JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n'); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { try { fs.unlinkSync(file); } catch {} }; - process.on('exit', cleanup); - process.on('SIGTERM', () => { cleanup(); process.exit(0); }); - process.on('SIGINT', () => { cleanup(); process.exit(0); }); - } catch {} -}; - -server.listen(PORT, HOST, () => { - publishEndpoint(); - console.log(`[claude-code-proxy] OpenAI-compatible bridge listening on http://${HOST}:${PORT}`); - console.log(`[claude-code-proxy] Resolved claude binary: ${CLAUDE_BIN}`); - console.log(`[claude-code-proxy] Workroot: ${WORKROOT}`); -}); diff --git a/bin/claude-code-proxy.test.mjs b/bin/claude-code-proxy.test.mjs deleted file mode 100644 index 447adde357..0000000000 --- a/bin/claude-code-proxy.test.mjs +++ /dev/null @@ -1,253 +0,0 @@ -// Tests for claude-code-proxy's resident stream-json sessions. -// Run: node --test bin/claude-code-proxy.test.mjs -// -// A stub `claude` stands in for the real CLI: it answers spawn args with -// an init event naming the --session-id/--resume id, then for every user -// line on stdin it emits two text deltas, an assistant message, and a -// result whose text echoes what it received. Every user line it receives -// is appended to $STUB_LOG so the tests can prove the second turn sent -// ONLY the newest user message (the delta-only warm behavior) rather -// than a re-flattened history. -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import fs from 'node:fs'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const STUB = `#!/bin/sh -sid="stub-session" -prev="" -for a in "$@"; do - if [ "$prev" = "--session-id" ] || [ "$prev" = "--resume" ]; then sid="$a"; fi - prev="$a" -done -while IFS= read -r line; do - case "$line" in - *'"subtype":"initialize"'*) - rid=$(printf '%s' "$line" | sed 's/.*"request_id":"\\([^"]*\\)".*/\\1/') - printf '%s\\n' "{\\"type\\":\\"control_response\\",\\"response\\":{\\"subtype\\":\\"success\\",\\"request_id\\":\\"$rid\\",\\"response\\":{}}}" - printf '%s\\n' "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$sid\\"}" - continue - ;; - esac - printf '%s\\n' "$line" >> "$STUB_LOG" - txt=$(printf '%s' "$line" | sed 's/.*"text":"\\([^"]*\\)".*/\\1/') - if [ "$txt" = "FAILME" ]; then - printf '%s\\n' '{"type":"result","subtype":"error_during_execution","result":"stub failure"}' - continue - fi - half=$(printf '%s' "$txt" | cut -c1-4) - printf '%s\\n' "{\\"type\\":\\"stream_event\\",\\"event\\":{\\"type\\":\\"content_block_delta\\",\\"index\\":0,\\"delta\\":{\\"type\\":\\"text_delta\\",\\"text\\":\\"ECHO:$half\\"}}}" - printf '%s\\n' "{\\"type\\":\\"stream_event\\",\\"event\\":{\\"type\\":\\"content_block_delta\\",\\"index\\":0,\\"delta\\":{\\"type\\":\\"text_delta\\",\\"text\\":\\" rest\\"}}}" - printf '%s\\n' "{\\"type\\":\\"assistant\\",\\"message\\":{\\"content\\":[{\\"type\\":\\"text\\",\\"text\\":\\"ECHO:$txt rest\\"}]}}" - printf '%s\\n' "{\\"type\\":\\"result\\",\\"subtype\\":\\"success\\",\\"result\\":\\"ECHO:$txt rest\\",\\"usage\\":{\\"input_tokens\\":100,\\"output_tokens\\":5,\\"cache_read_input_tokens\\":80}}" -done -`; - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -const startProxy = async () => { - const port = await freePort(); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-code-proxy-test-')); - const stubPath = path.join(tmp, 'claude-stub'); - fs.writeFileSync(stubPath, STUB, { mode: 0o755 }); - const logPath = path.join(tmp, 'stub.log'); - const child = spawn(process.execPath, [path.join(binDir, 'claude-code-proxy.mjs')], { - env: { - ...process.env, - CLAUDE_CODE_PROXY_PORT: String(port), - CLAUDE_CODE_PROXY_HOST: '127.0.0.1', - 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') - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let stderr = ''; - child.stderr.on('data', c => { stderr += c; }); - const base = `http://127.0.0.1:${port}`; - const deadline = Date.now() + 15000; - for (;;) { - try { - const r = await fetch(`${base}/health`); - if (r.ok) break; - } catch { /* not up yet */ } - if (Date.now() > deadline) { - child.kill('SIGKILL'); - throw new Error(`proxy did not become healthy; stderr: ${stderr}`); - } - await new Promise(r => setTimeout(r, 100)); - } - return { base, child, logPath, tmp }; -}; - -const chat = (base, body, headers = {}) => fetch(`${base}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', ...headers }, - body: JSON.stringify(body) -}); - -test('health + models catalog', async (t) => { - const { base, child } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - const health = await (await fetch(`${base}/health`)).json(); - assert.equal(health.status, 'ok'); - assert.equal(health.service, 'claude-code-proxy'); - assert.equal(health.engine, 'claude-stream-json-resident'); - const models = await (await fetch(`${base}/v1/models`)).json(); - // 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) => { - const { base, child, logPath } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - const headers = { 'x-session-id': 'test-convo-1' }; - const sys = { role: 'system', content: 'You are terse.' }; - const u1 = { role: 'user', content: 'remember BANANA' }; - - const r1 = await chat(base, { model: 'claude-haiku-5-5', messages: [sys, u1] }, headers); - assert.equal(r1.status, 200); - const j1 = await r1.json(); - const a1 = j1.choices[0].message.content; - assert.ok(a1.includes('ECHO:remember BANANA rest'), `unexpected turn-1 content: ${a1}`); - assert.equal(j1.usage.prompt_tokens, 180); // 100 input + 80 cache read - - const u2 = { role: 'user', content: 'what was it?' }; - const r2 = await chat(base, { - model: 'claude-haiku-5-5', - messages: [sys, u1, { role: 'assistant', content: a1 }, u2] - }, headers); - assert.equal(r2.status, 200); - const j2 = await r2.json(); - assert.ok(j2.choices[0].message.content.includes('ECHO:what was it? rest')); - - const received = fs.readFileSync(logPath, 'utf-8').trim().split('\n'); - assert.equal(received.length, 2, `stub should have received exactly 2 user lines, got: ${received.join(' | ')}`); - assert.ok(received[0].includes('remember BANANA')); - assert.ok(received[1].includes('what was it?')); - assert.ok(!received[1].includes('BANANA'), `turn 2 must be delta-only, got: ${received[1]}`); -}); - -test('diverged history re-bootstraps with the full transcript', async (t) => { - const { base, child, logPath } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - const headers = { 'x-session-id': 'test-convo-2' }; - const u1 = { role: 'user', content: 'first version' }; - const r1 = await chat(base, { model: 'claude-haiku-5-5', messages: [u1] }, headers); - assert.equal(r1.status, 200); - await r1.json(); - - // Same key, but the first user message changed -> prefix mismatch -> - // fresh session whose first turn is the flattened transcript. - const r2 = await chat(base, { - model: 'claude-haiku-5-5', - messages: [{ role: 'user', content: 'EDITED first' }, { role: 'user', content: 'second' }] - }, headers); - assert.equal(r2.status, 200); - await r2.json(); - const received = fs.readFileSync(logPath, 'utf-8').trim().split('\n'); - assert.equal(received.length, 2); - assert.ok(received[1].includes('EDITED first'), `re-bootstrap should carry the transcript, got: ${received[1]}`); - assert.ok(received[1].includes('second')); -}); - -test('streaming emits SSE deltas and a finish chunk', async (t) => { - const { base, child } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - const r = await chat(base, { - model: 'claude-haiku-5-5', stream: true, - messages: [{ role: 'user', content: 'stream please' }] - }, { 'x-session-id': 'test-convo-3' }); - assert.equal(r.status, 200); - const text = await r.text(); - assert.ok(text.includes('ECHO:stre')); - assert.ok(text.includes('finish_reason":"stop"') || text.includes('"finish_reason": "stop"') || text.includes('stop')); - assert.ok(text.trimEnd().endsWith('data: [DONE]')); -}); - -test('failed turn surfaces an error and the session is retryable', async (t) => { - const { base, child } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - // FAILME makes the stub answer with an error result on both the primary - // session and the one fresh retry, so the proxy must surface a 500. - const r = await chat(base, { - model: 'claude-haiku-5-5', - messages: [{ role: 'user', content: 'FAILME' }] - }, { 'x-session-id': 'test-convo-4' }); - assert.equal(r.status, 500); - const j = await r.json(); - assert.ok(j.error.message.includes('stub failure') || j.error.message.length > 0); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const { base, child } = await startProxy(); - t.after(() => { child.kill('SIGKILL'); }); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`${base}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`${base}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); - -test('chain map self-deletes settled entries; same-key turns stay ordered (#2407)', async (t) => { - const { base, child, logPath } = await startProxy(); - t.after(() => child.kill('SIGKILL')); - const chainsNow = async () => (await (await fetch(base + '/health')).json()).sessions.chains; - const waitChainsEmpty = async () => { - const deadline = Date.now() + 5000; - for (;;) { - const n = await chainsNow(); - if (n === 0) return; - if (Date.now() > deadline) assert.fail('chains map must be empty after settle, got ' + n); - await new Promise(r => setTimeout(r, 50)); - } - }; - - // Two distinct keys through enqueue: both settle, map must empty. - for (const id of ['leak-a', 'leak-b']) { - const r = await chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'hello ' + id }] }, { 'x-session-id': id }); - assert.equal(r.status, 200); - await r.json(); - } - await waitChainsEmpty(); - - // Same key: second turn enqueued while the first is in flight must run - // after it, in order, and the map must empty afterwards. - const headers = { 'x-session-id': 'order-key' }; - const p1 = chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'order first' }] }, headers); - await new Promise(r => setTimeout(r, 100)); - const p2 = chat(base, { model: 'claude-haiku-5-5', messages: [{ role: 'user', content: 'order second' }] }, headers); - const [r1, r2] = await Promise.all([p1, p2]); - assert.equal(r1.status, 200); await r1.json(); - assert.equal(r2.status, 200); await r2.json(); - const received = fs.readFileSync(logPath, 'utf-8'); - const i1 = received.indexOf('order first'); - const i2 = received.indexOf('order second'); - assert.ok(i1 !== -1 && i2 !== -1 && i1 < i2, 'same-key turns must reach the engine in enqueue order'); - await waitChainsEmpty(); -}); diff --git a/bin/cli-proxy-workroots.test.mjs b/bin/cli-proxy-workroots.test.mjs deleted file mode 100644 index 8f560fabfb..0000000000 --- a/bin/cli-proxy-workroots.test.mjs +++ /dev/null @@ -1,70 +0,0 @@ -// Tests for the per-proxy CLI workroot isolation (#2785). -// Run: node --test bin/cli-proxy-workroots.test.mjs -// -// home/common/default.nix points all three CLI proxies at one shared -// WORKDIR before this fix: commandcode and claude-code derive identical -// sessions/ workdirs for overlapping keys, and the -// muse proxy uses the shared root itself as its session cwd and -// workspaceRoot. The units must give each proxy its own subtree while -// the commandcode/claude-code session map stays intentionally shared -// (#3067) — it is anchored to the state root, not to either workroot. -import assert from 'node:assert/strict'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); -const nix = fs.readFileSync(path.join(binDir, '..', 'home', 'common', 'default.nix'), 'utf8'); - -const envValue = (name) => { - const m = nix.match(new RegExp(`"${name}=([^"]+)"`)); - assert.ok(m, `default.nix should set ${name}`); - return m[1]; -}; - -const WORKDIRS = { - commandcode: envValue('COMMANDCODE_PROXY_WORKDIR'), - claudeCode: envValue('CLAUDE_CODE_PROXY_WORKDIR'), - muse: envValue('MUSE_PROXY_WORKDIR'), -}; - -test('each CLI proxy unit gets a distinct workroot subtree', () => { - const values = Object.values(WORKDIRS); - assert.equal(new Set(values).size, 3, `workroots must be pairwise distinct: ${values}`); - for (const [proxy, dir] of Object.entries(WORKDIRS)) { - assert.ok( - dir.startsWith('%h/.local/state/cli-proxies/'), - `${proxy} workroot stays under the cli-proxies state root: ${dir}`, - ); - assert.notEqual( - dir, - '%h/.local/state/cli-proxies', - `${proxy} workroot must not be the shared root itself`, - ); - } -}); - -test('an overlapping conversation key derives disjoint session workdirs', () => { - // Both proxies derive sessions/ under - // their WORKROOT (commandcode-proxy.mjs / claude-code-proxy.mjs - // sessionWorkdirFor). Distinct workroots make the derived paths - // disjoint even when the key — and therefore the hash — is identical. - const key = 'an overlapping conversation key'; - const hash = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16); - const ccDir = path.join(WORKDIRS.commandcode, 'sessions', hash); - const claudeDir = path.join(WORKDIRS.claudeCode, 'sessions', hash); - assert.notEqual(ccDir, claudeDir); -}); - -test('the shared commandcode/claude session map is unchanged (#3067)', () => { - const cc = envValue('COMMANDCODE_PROXY_SESSION_FILE'); - const claude = envValue('CLAUDE_CODE_PROXY_SESSION_FILE'); - assert.equal(cc, claude, 'both units must name the same session file'); - assert.equal(cc, '%h/.local/state/cli-proxies/sessions.json'); - // The shared map lives at the state root, outside every workroot. - for (const dir of Object.values(WORKDIRS)) { - assert.ok(!cc.startsWith(dir), 'session file must not sit inside a per-proxy workroot'); - } -}); diff --git a/bin/commandcode-proxy-start.sh b/bin/commandcode-proxy-start.sh deleted file mode 100755 index a9fd152c3b..0000000000 --- a/bin/commandcode-proxy-start.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -# Laptop start wrapper for commandcode-proxy (fleet pattern, mirrors the -# sandbox wrapper minus the sandbox-only egress pins). -export HOME=/home/user -export COMMANDCODE_PROXY_PORT=${COMMANDCODE_PROXY_PORT:-18748} -export COMMANDCODE_PROXY_MAX_TURNS=1 -export COMMANDCODE_PROXY_HOST=127.0.0.1 -# Empty egress override: on the laptop the CLI reaches CommandCode -# directly; the proxy must NOT pin the sandbox egress proxy for children. -export COMMANDCODE_PROXY_EGRESS= -# IPv6 fix (2026-10-25): LAN v6 is ULA-only/no-upstream and Node 24 -# fetch (undici autoSelectFamily) times out on it. Load per-process net -# defaults (autoSelectFamily OFF) for the whole proxy tree; CLI children -# inherit env via the proxy's childEnv(). -export NODE_OPTIONS="--import $HOME/code/node-net-defaults.mjs${NODE_OPTIONS:+ $NODE_OPTIONS}" -export PATH="/run/current-system/sw/bin:$HOME/.local/bin:/run/current-system/sw/bin:/usr/local/bin:$PATH" -exec /run/current-system/sw/bin/node "$HOME/code/bin/commandcode-proxy.mjs" diff --git a/bin/commandcode-proxy.mjs b/bin/commandcode-proxy.mjs deleted file mode 100644 index 3aeb919f91..0000000000 --- a/bin/commandcode-proxy.mjs +++ /dev/null @@ -1,1349 +0,0 @@ -#!/usr/bin/env node -// commandcode-proxy — OpenAI-compatible bridge to the CommandCode CLI. -// -// Why this exists: CommandCode's hosted API (api.commandcode.ai/provider/v1) -// rejects Drew's Go plan ("Your Go plan doesn't include API access. Upgrade -// to Provider or higher"), so the only working route is the CLI itself, -// exactly like bin/codex-proxy.mjs (Muse) and -// ~/tools/muse-proxy/muse-proxy.mjs (Muse CLI): one headless CLI -// subprocess per chat-completions request. -// -// CLI contract (v1.88.0, verified live 2026-10-24): -// commandcode -p --output-format json -m --max-turns 1 -// --no-session --skip-onboarding --no-auto-update -t -// --permission-mode dont-ask -// with the flattened conversation written to the child's STDIN -// (`-p` with no query argument reads the prompt from stdin — no argv -// length/escaping concerns). Stdout is NDJSON: -// {"type":"event","event":{"type":"text_delta","delta":"..."}} -// {"type":"event","event":{"type":"thinking_delta",...}} (ignored) -// {"type":"event","event":{"type":"run_end","result": -// {"finalText":"...","usage":{"inputTokens":N,"outputTokens":N}}}} -// Exit 0 on success, 8 on max-turns cap. -// -// Session mode shipped: RESIDENT ACP (phase 2) — see the "Resident ACP -// engine" section below. One `cmd acp` process is held by this service; -// conversations map to persistent ACP threads and per call only the -// newest user turn is sent. The warm-session spawn chain (resume-by- -// transcript, then fresh full-history) remains as the automatic -// fallback if the ACP path fails. -// -// Agency (2026-10-25): when the incoming OpenAI request carries `tools` -// (i.e. OpenCode runs an agentic turn — its agent loop only sends tools -// when it wants tool calls), the CLI runs tool-enabled and does the task -// with ITS OWN tools; the bridge returns its final text. Chat turns (no -// tools) keep the no-tools steer. Verified live: the CLI's ACP tools are -// internal (write_file/edit/shell against the session cwd), so no ACP -// client fs/terminal handlers are needed; session mode 'dont-ask' fails -// tools CLOSED with "Permission denied by the user" (no client prompt is -// sent), so agency threads stay on the default mode while chat threads -// are set to 'dont-ask'. 'yolo' is not a valid ACP modeId (Unknown mode) -// — only a CLI flag, used on the agency spawn fallback with --tools-all. -// The agency prompt confines file work to the per-conversation session -// workdir; the CLI process itself is unconfined (fleet parity with -// codex-proxy's danger-full-access). -// -// Auth is the CLI's own login (~/.commandcode/auth.json). No API key is -// 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, execFile } from 'node:child_process'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { parseProxyPort } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -const PORT = parseProxyPort('COMMANDCODE_PROXY_PORT', 18748); -const HOST = process.env.COMMANDCODE_PROXY_HOST || '127.0.0.1'; -const TIMEOUT_MS = Number(process.env.COMMANDCODE_PROXY_TIMEOUT_MS || 240000); -const MAX_TURNS = process.env.COMMANDCODE_PROXY_MAX_TURNS || '1'; -// Spawn-fallback turn budget for agency turns only (chat stays at -// MAX_TURNS). The ACP path has no turn cap (bounded by TIMEOUT_MS). -const AGENCY_MAX_TURNS = process.env.COMMANDCODE_PROXY_AGENCY_MAX_TURNS || '8'; - -const EGRESS_PROXY = process.env.COMMANDCODE_PROXY_EGRESS ?? 'http://hatch-egress-proxy:3128'; -const EGRESS_CA = '/run/hatch/egress-tls/ca-bundle.pem'; - -const PROXY_DIR = path.dirname(fileURLToPath(import.meta.url)); -const WORKROOT = process.env.COMMANDCODE_PROXY_WORKDIR || path.join(PROXY_DIR, 'work'); -fs.mkdirSync(WORKROOT, { recursive: true }); - -// 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. This is the documented-impossibility exception to -// the live-model rule, re-verified with evidence 2026-10-28: -// - Upstream `commandcode --list-models` (CLI v1.88.0) segregates it -// itself: the banner reads "Available models · 94 models" and jev -// appears only afterwards, under a separate "Decision models -// (headless only)" heading: "typed questions in, probabilities -// out". Vendor docs (Available Models / Provider API / Headless) -// agree: "not a chat model", "not available in /model and can't -// drive a session", served on the Provider API only via a separate -// `v1/systemone` endpoint because "its request is not a chat -// message, and it never streams". -// - Demonstrated live through this proxy (2026-10-28, while the CLI -// login was expired): a chat-completions request for typesafe/jev -// ("Reply with exactly: PROBE-OK") failed 502 with a jev-specific -// error BEFORE any auth check — "a decision model takes a JSON -// request, not a prompt. Expected: {\"state\": , -// \"questions\": {...}}" — while the identical request for -// gpt-6.1-sol reached the upstream and failed only on auth -// ("POST /alpha/generate → 401 error: Invalid 'Authorization' -// header or token."). A direct CLI run with a well-formed JSON -// state/questions payload reached the auth boundary instead -// ("Authentication failed. Please run \"cmd login\" first."), so -// the request SHAPE, not auth, is the discriminator. -// Serving jev in /v1/models would advertise it as a chat model this -// bridge cannot serve chat traffic for; callers that need jev must -// use the CLI headless JSON form or the Provider API systemone -// endpoint directly. -const STATIC_MODELS = [ - 'deepseek/deepseek-v4-pro', - 'deepseek/deepseek-v4-flash', - 'deepseek/deepseek-v4-flash-vision-exp', - 'deepseek/deepseek-v4-flash-fast', - 'deepseek/deepseek-v4.1-flash', - 'deepseek/deepseek-v4.1-flash-fast', - 'moonshotai/kimi-k3', - 'moonshotai/kimi-k2.7-code', - 'moonshotai/kimi-k2.7-code-highspeed', - 'moonshotai/kimi-k2.6', - 'moonshotai/kimi-k2.5', - 'z-ai/glm-5.3-flash', - 'z-ai/glm-5.3-flashx', - 'zai-org/glm-5.3', - 'zai-org/glm-5.2', - 'zai-org/glm-5.2-fast', - 'zai-org/glm-5.1', - 'zai-org/glm-5', - 'minimaxai/minimax-m3', - 'minimaxai/minimax-m2.7', - 'minimaxai/minimax-m2.5', - 'xiaomi/mimo-v2.6-pro', - 'xiaomi/mimo-v2.6-pro-ultraspeed', - 'xiaomi/mimo-v2.6-flash', - 'xiaomi/mimo-v2.5-pro', - 'xiaomi/mimo-v2.5', - 'meituan/longcat-2.0', - 'qwen/qwen3.8-omni-flash', - 'qwen/qwen3.8-max-0902', - 'qwen/qwen3.8-max', - 'qwen/qwen3.8-27b', - 'qwen/qwen3.8-flash', - 'qwen/qwen3.7-max', - 'qwen/qwen3.7-plus', - 'qwen/qwen3.7-flash', - 'qwen/qwen3.6-max-preview', - 'qwen/qwen3.6-plus', - 'stepfun/step-5-preview', - 'stepfun/step-3.7-flash', - 'stepfun/step-3.5-flash', - 'tencent/hy3-paid', - 'tencent/hy4-preview', - 'nvidia/nemotron-3-ultra-550b-a55b', - 'thinkingmachines/inkling', - 'thinkingmachines/inkling-small', - 'poolside/laguna-s-2.1-free', - 'inclusionai/ling-3.1-flash:free', - 'inclusionai/ling-3.0-flash-sante:free', - 'stealth/space-bunny-alpha', - 'claude-sonnet-5-5', - 'claude-sonnet-5', - 'claude-sonnet-4-6', - 'claude-fable-5-1', - 'claude-fable-5', - 'claude-opus-5-5', - 'claude-opus-5', - 'claude-opus-4-8', - 'claude-opus-4-7', - 'claude-haiku-4-5', - 'gpt-6-astra', - 'gpt-6.1-sol', - 'gpt-6-sol', - 'gpt-6-luna', - 'gpt-5.6-sol', - 'gpt-5.6-terra', - 'gpt-5.6-luna', - 'gpt-5.5', - 'gpt-5.4', - 'gpt-5.3-codex', - 'gpt-5.4-mini', - 'google/gemini-3.8-flash', - 'google/gemini-3.7-flash', - 'google/gemini-3.6-flash', - 'google/gemini-3.5-flash', - 'google/gemini-3.5-flash-lite', - 'google/gemini-3.1-flash-lite', - 'sakana/fugu-ultra', - 'meta/muse-spark-1.1', - 'meta/muse-spark-1.2', - 'meta/muse-spark-1.2-contributor', - 'meta/muse-spark-1.3', - 'meta/muse-spark-1.3-contributor', - 'xai/grok-4.5', - 'xai/grok-4.6', - 'xai/grok-4.7' -]; -const DEFAULT_MODEL = 'deepseek/deepseek-v4-flash'; - -// Publish the bound endpoint so other tools can find this proxy without -// knowing its port in advance: $XDG_STATE_HOME//endpoint.json -// (default ~/.local/state//endpoint.json), written on listen, -// removed on exit. (Copied from agy-proxy.) -const publishEndpoint = () => { - try { - const stateHome = - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'commandcode-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync( - `${file}.tmp`, - JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n', - ); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { - try { - fs.unlinkSync(file); - } catch {} - }; - process.on('exit', cleanup); - process.on('SIGTERM', () => { - cleanup(); - process.exit(0); - }); - process.on('SIGINT', () => { - cleanup(); - process.exit(0); - }); - } catch {} -}; - -const findCommandCodeBinary = () => { - const candidates = [ - `${process.env.HOME}/tools/command-code/bin/commandcode`, - `${process.env.HOME}/.local/bin/commandcode`, - 'commandcode' - ]; - for (const c of candidates) { - if (c === 'commandcode' || fs.existsSync(c)) { - return c; - } - } - return 'commandcode'; -}; - -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; - // OpenCode may send the id bare; a stray leading "commandcode/" is the - // 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); - const served = getServedModels(); - if (served.includes(raw)) return raw; - // CLI also accepts the short name after the last '/'. - 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; -}; - -const formatPrompt = (messages, agency, workdir, toolManifest) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - if (!agency && messages.length === 1 && messages[0].role === 'user' && typeof messages[0].content === 'string') { - return messages[0].content; - } - - const parts = []; - if (agency) { - // Agency turn (the OpenAI request carried tools, i.e. OpenCode wants - // an agentic turn): the CLI does the task with ITS OWN tools and this - // bridge returns its final text. Verified live 2026-10-25: the CLI's - // ACP tools are internal (write_file/edit/shell against the session - // cwd) — no ACP client fs/terminal handlers are needed. Permission - // posture is the session mode: 'dont-ask' FAILS tools closed - // ("Permission denied by the user", no client prompt is sent), so - // agency threads stay on the default mode and this proxy auto-allows - // any session/request_permission the CLI does send (see handleLine). - // Keep all file work inside the assigned workdir (absolute paths). - parts.push(`[Bridge instruction: act as the tool-using agent for the conversation below. Use your own file/shell tools to complete the task. Do ALL file work inside ${workdir} (absolute paths under it); do not touch anything outside it. When done, reply with a brief text summary of what you did. OpenCode asked for these tools — implement each with your closest equivalent: ${toolManifest}]`); - } else { - // The CLI is an agentic coding tool with its own system prompt; without - // this steer it treats the flattened conversation as a workspace task - // and burns multiple turns on tool calls (observed: a trivial - // "Reply with exactly: PROBE-OK" from OpenCode took ~208s at - // max-turns 5). This bridge is a chat completion: one direct text - // answer, no tools, no workspace exploration. - parts.push('[Bridge instruction: answer the conversation below directly with a single text reply. Do not invoke tools, do not explore or modify any workspace, do not run commands.]'); - } - const systemMessages = messages.filter(m => m.role === 'system'); - const convoMessages = messages.filter(m => m.role !== 'system'); - - if (systemMessages.length > 0) { - const sysText = systemMessages.map(m => - typeof m.content === 'string' ? m.content : JSON.stringify(m.content) - ).join('\n\n'); - parts.push(`[System Instructions]\n${sysText}`); - } - - if (convoMessages.length > 0) { - const convoText = convoMessages.map(m => { - let role = m.role === 'assistant' ? 'Assistant' : (m.role === 'user' ? 'User' : m.role); - let text = ''; - if (typeof m.content === 'string') { - text = m.content; - } else if (Array.isArray(m.content)) { - text = m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } else if (m.content) { - text = JSON.stringify(m.content); - } - - if (m.tool_calls && Array.isArray(m.tool_calls)) { - const tcStr = m.tool_calls.map(tc => `[Tool Call: ${tc.function?.name || 'function'}(${tc.function?.arguments || ''})]`).join('\n'); - text = text ? `${text}\n${tcStr}` : tcStr; - } - if (m.role === 'tool') { - role = `Tool Result (${m.tool_call_id || 'result'})`; - } - - return `${role}: ${text}`; - }).join('\n\n'); - parts.push(convoText); - } - - return parts.join('\n\n'); -}; - -// Child env: inherit, and pin the egress proxy + CA bundle the CLI needs -// to reach CommandCode from the sandbox (same treatment as muse-proxy). -// NODE_USE_ENV_PROXY=1 is REQUIRED (verified 2026-10-24): the CLI is a -// Node app whose fetch() ignores *_PROXY env vars without it, tries a -// direct connection, and dies with run_error TransportError -// "POST /alpha/generate → network error: fetch failed" / stderr -// "Error: Unable to connect to the API". With it set, the -// unauthenticated egress proxy works. -const childEnv = () => { - const env = { ...process.env }; - env.NODE_USE_ENV_PROXY = '1'; - if (EGRESS_PROXY) { - env.HTTPS_PROXY = EGRESS_PROXY; - env.HTTP_PROXY = EGRESS_PROXY; - env.https_proxy = EGRESS_PROXY; - env.http_proxy = EGRESS_PROXY; - env.ALL_PROXY = EGRESS_PROXY; - env.all_proxy = EGRESS_PROXY; - } - if (EGRESS_PROXY && fs.existsSync(EGRESS_CA)) env.SSL_CERT_FILE = EGRESS_CA; - env.NO_PROXY = '127.0.0.1,localhost'; - env.no_proxy = '127.0.0.1,localhost'; - return env; -}; - - -// --------------------------------------------------------------------------- -// Warm-session support (fleet design: developing-today/code issue #480). -// -// The CommandCode CLI persists sessions under -// ~/.commandcode/projects//.jsonl (transcript), -// .checkpoints.jsonl and .meta.json, and -// `commandcode -p --session ` resumes one from any cwd -// (verified live 2026-10-24: a codeword stored in turn 1 was recalled in -// turn 2 from only the new turn's prompt, with usage cacheReadTokens -// 19840 of 19934 input — ~99% of the replayed context served from the -// provider prompt cache). So when a conversation key is known, the proxy -// resumes the mapped CLI session and sends ONLY the newest user turn -// instead of re-flattening the whole history; any resume failure falls -// back to a full-history fresh run (which re-creates the mapping). -// -// Conversation key derivation mirrors agy-proxy's getSessionKey, with one -// change: the automatic multi-turn key hashes the first USER message, -// not messages[0] — OpenCode's messages[0] is its identical system -// prompt for every session, which would collide all conversations. -// Session map: SHARED with claude-code-proxy (mirrored key space), so -// both proxies must resolve to the SAME path. It lives in the shared -// CLI-proxy state root, not beside the script: bin/ is the tracked -// checkout, and every write there dirtied the primary clone and blocked -// pm-git-sync. #3067 completes the state-dir move of #2782, which -// covered the WORKDIR state (bin/work) but missed this PROXY_DIR anchor. -const SESSION_FILE = - process.env.COMMANDCODE_PROXY_SESSION_FILE || - path.join( - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), - 'cli-proxies', - 'sessions.json' - ); -fs.mkdirSync(path.dirname(SESSION_FILE), { recursive: true }); -const MAX_SESSIONS = 200; -const sessionStore = new Map(); - -const saveSessions = () => { - try { - const obj = {}; - for (const [k, v] of sessionStore) obj[k] = v; - fs.writeFileSync(`${SESSION_FILE}.tmp`, JSON.stringify(obj, null, 2) + '\n'); - fs.renameSync(`${SESSION_FILE}.tmp`, SESSION_FILE); - } catch (err) { - console.warn(`[commandcode-proxy] Failed to persist session store: ${err.message}`); - } -}; - -const loadSessions = () => { - try { - const obj = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - for (const [k, v] of Object.entries(obj)) { - if (v && typeof v.sessionId === 'string') sessionStore.set(k, v); - } - if (sessionStore.size > 0) { - console.log(`[commandcode-proxy] Loaded ${sessionStore.size} warm-session mapping(s) from ${SESSION_FILE}`); - } - } catch {} -}; -loadSessions(); - -const pruneSessionStore = () => { - if (sessionStore.size <= MAX_SESSIONS) return; - const entries = Array.from(sessionStore.entries()) - .sort((a, b) => (a[1].updatedAt || 0) - (b[1].updatedAt || 0)); - for (const [key] of entries.slice(0, entries.length - MAX_SESSIONS)) { - sessionStore.delete(key); - } -}; - -const messageText = (m) => { - if (!m) return ''; - if (typeof m.content === 'string') return m.content; - if (Array.isArray(m.content)) return m.content.map(c => c.text || '').join('\n'); - return ''; -}; - -const getSessionKey = (req, body) => { - const explicitId = - req.headers['x-conversation-id'] || - req.headers['x-session-id'] || - req.headers['conversation-id'] || - req.headers['session-id'] || - body.conversation_id || - body.conversationId || - body.session_id || - body.sessionId || - body.chat_id; - - if (explicitId && typeof explicitId === 'string' && explicitId.trim()) { - return explicitId.trim(); - } - - if (body.user && typeof body.user === 'string' && body.user.trim()) { - return `user:${body.user.trim()}`; - } - - if (Array.isArray(body.messages) && body.messages.length > 1) { - const firstUser = body.messages.find(m => m.role === 'user'); - const firstContent = firstUser ? messageText(firstUser) : ''; - if (firstContent.length > 0) { - const hash = crypto.createHash('sha256').update(firstContent).digest('hex').slice(0, 16); - return `turn0:${hash}`; - } - } - - return null; -}; - -const extractLatestUserPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - const lastUserMsg = [...messages].reverse().find(m => m.role === 'user'); - return lastUserMsg ? messageText(lastUserMsg) : ''; -}; - -// One stable workdir per conversation key: the CLI keys its on-disk -// project state by cwd slug, so a stable cwd keeps a conversation's -// transcript in a single ~/.commandcode/projects// directory -// instead of scattering one project dir per request. -const sessionWorkdirFor = (key) => { - const hash = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16); - const dir = path.join(WORKROOT, 'sessions', hash); - fs.mkdirSync(dir, { recursive: true }); - return dir; -}; - - - -// --------------------------------------------------------------------------- -// Resident ACP engine (phase 2, Drew's requirement: "whatever saves -// tokens and reduces per call binary load/boot time"). -// -// ONE resident `commandcode acp` process is held by this proxy and driven -// over stdio JSON-RPC (Agent Client Protocol — initialize, session/new, -// session/load, session/set_model, session/set_mode, session/prompt, -// session/close, session/cancel; streamed replies arrive as -// session/update agent_message_chunk notifications). Verified live -// 2026-10-24 against cmd v1.88.0: initialize ~7.4s once, session/new -// ~1.1s, turn 1 prompt 4.0s, turn 2 prompt 1.8s with per-turn usage -// cacheReadTokens 21632/21778 (~99% of input cache-read), codeword -// recalled from the resident session after sending only the new turn. -// -// Design notes: -// - One `cmd acp` process serves ONE project directory (upstream rule), -// so every thread lives in ACP_HOME below; a conversation's transcript -// persists at ~/.commandcode/projects//.jsonl. -// - Per conversation key (same derivation as the warm-session layer) the -// proxy keeps key -> { sessionId, model, updatedAt } in sessions.json. -// A live thread is reused directly; after a proxy/agent restart a -// mapped thread is re-attached with session/load (history replay -// updates are dropped — no prompt handler is registered during load). -// - Per call only the newest user turn is sent for an existing thread; -// a brand-new thread gets the full flattened history once. -// - Threads are serialized per key (one prompt at a time per thread); -// different threads may prompt concurrently. -// - ANY ACP failure returns { failed: true } and the caller falls back -// to the spawn-per-request attempt chain (resume-by-transcript, then -// fresh) — the v2 behavior remains the safety net. -const ACP_HOME = path.join(WORKROOT, 'acp-project'); -fs.mkdirSync(ACP_HOME, { recursive: true }); - -const acp = { - proc: null, - ready: null, - nextId: 1, - pending: new Map(), // rpc id -> { resolve, reject } - updateHandlers: new Map(),// sessionId -> fn(update) - liveSessions: new Map(), // sessionId -> { model, mode, lastUsed } - locks: new Map(), // conversation key -> promise chain - starts: 0, - - spawnProc() { - const child = spawn(CC_BIN, ['acp'], { - cwd: ACP_HOME, - env: childEnv(), - stdio: ['pipe', 'pipe', 'pipe'] - }); - this.proc = child; - this.starts += 1; - console.log(`[commandcode-proxy] ACP resident process started (pid ${child.pid}, start #${this.starts})`); - - let lineBuffer = ''; - const stdoutDecoder = createStreamDecoder(); - const stderrDecoder = createStreamDecoder(); - child.stdout.on('data', chunk => { - lineBuffer += stdoutDecoder.push(chunk); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); - for (const line of lines) this.handleLine(line); - }); - child.stderr.on('data', chunk => { - const msg = stderrDecoder.push(chunk); - if (msg.trim().length > 0) console.warn(`[acp stderr] ${msg.trim().slice(0, 500)}`); - }); - child.on('error', err => console.error(`[commandcode-proxy] ACP process error: ${err.message}`)); - child.on('close', (code, signal) => { - console.error(`[commandcode-proxy] ACP resident process exited (code ${code}, signal ${signal}) — in-flight prompts failed, next request restarts it`); - if (this.proc === child) { - this.proc = null; - this.ready = null; - this.liveSessions.clear(); - const err = new Error(`ACP process exited (code ${code})`); - for (const [, p] of this.pending) p.reject(err); - this.pending.clear(); - this.updateHandlers.clear(); - } - }); - }, - - write(obj) { - if (!this.proc || !this.proc.stdin.writable) throw new Error('ACP process not running'); - this.proc.stdin.write(JSON.stringify(obj) + '\n'); - }, - - handleLine(line) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - let msg; - try { msg = JSON.parse(trimmed); } catch { return; } - - // Response to one of our requests - if (msg.id !== undefined && !msg.method && this.pending.has(msg.id)) { - const p = this.pending.get(msg.id); - this.pending.delete(msg.id); - if (msg.error) p.reject(new Error(`ACP ${msg.error.code || ''} ${msg.error.message || JSON.stringify(msg.error)}`.trim())); - else p.resolve(msg.result); - return; - } - - // Agent -> client request (e.g. session/request_permission) - if (msg.method && msg.id !== undefined) { - if (msg.method === 'session/request_permission') { - const opts = (msg.params && msg.params.options) || []; - const pick = opts.find(o => o.kind === 'allow_once' || o.kind === 'allow_always') - || opts.find(o => /allow/i.test(o.optionId || '')) - || opts[0]; - try { - this.write({ jsonrpc: '2.0', id: msg.id, result: { outcome: { outcome: 'selected', optionId: pick ? pick.optionId : 'allow_once' } } }); - } catch {} - } else { - // We declared fs/terminal capabilities false at initialize, so - // other client services should never be called. Refuse politely. - try { - this.write({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: `client service not supported: ${msg.method}` } }); - } catch {} - } - return; - } - - // Notification: session/update streams prompt output - if (msg.method === 'session/update' && msg.params) { - const handler = this.updateHandlers.get(msg.params.sessionId); - if (handler && msg.params.update) { - try { handler(msg.params.update); } catch {} - } - } - }, - - request(method, params, timeoutMs = 60000) { - const id = this.nextId++; - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`ACP ${method} timed out after ${timeoutMs}ms`)); - }, timeoutMs); - timer.unref(); - this.pending.set(id, { - resolve: (v) => { clearTimeout(timer); resolve(v); }, - reject: (e) => { clearTimeout(timer); reject(e); } - }); - try { - this.write({ jsonrpc: '2.0', id, method, params }); - } catch (err) { - clearTimeout(timer); - this.pending.delete(id); - reject(err); - } - }); - }, - - notify(method, params) { - try { this.write({ jsonrpc: '2.0', method, params }); } catch {} - }, - - async ensureReady() { - if (this.ready) return this.ready; - this.ready = (async () => { - this.spawnProc(); - const init = await this.request('initialize', { - protocolVersion: 1, - clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, - clientInfo: { name: 'commandcode-proxy', version: '3.0.0' } - }, 90000); - console.log(`[commandcode-proxy] ACP initialized: ${(init.agentInfo && init.agentInfo.name) || 'agent'} ${(init.agentInfo && init.agentInfo.version) || ''}, loadSession=${Boolean(init.agentCapabilities && init.agentCapabilities.loadSession)}`); - return init; - })(); - this.ready.catch(() => { this.ready = null; }); - return this.ready; - }, - - async getOrCreateThread(mappingKey, model, ephemeral, mode) { - await this.ensureReady(); - const stored = ephemeral ? null : sessionStore.get(mappingKey); - let sessionId = null; - let resumed = false; - - if (stored && stored.sessionId) { - if (this.liveSessions.has(stored.sessionId)) { - sessionId = stored.sessionId; - resumed = true; - } else { - try { - await this.request('session/load', { sessionId: stored.sessionId, cwd: ACP_HOME, mcpServers: [] }, 60000); - sessionId = stored.sessionId; - resumed = true; - this.liveSessions.set(sessionId, { model: stored.model || null, mode: null, lastUsed: Date.now() }); - console.log(`[commandcode-proxy] ACP thread re-attached via session/load: ${sessionId} (key ${mappingKey})`); - } catch (err) { - console.warn(`[commandcode-proxy] ACP session/load failed for ${stored.sessionId} (${err.message}) — opening a new thread`); - } - } - } - - if (!sessionId) { - const created = await this.request('session/new', { cwd: ACP_HOME, mcpServers: [] }, 60000); - sessionId = created.sessionId; - this.liveSessions.set(sessionId, { model: null, mode: mode === 'dont-ask' ? null : 'default', lastUsed: Date.now() }); - if (!ephemeral) { - sessionStore.set(mappingKey, { sessionId, model: null, updatedAt: Date.now() }); - pruneSessionStore(); - saveSessions(); - } - console.log(`[commandcode-proxy] ACP thread created: ${sessionId} (key ${mappingKey}${ephemeral ? ', ephemeral' : ''})`); - } - - const live = this.liveSessions.get(sessionId); - if (live) { - live.lastUsed = Date.now(); - // Permission posture is per-request, not per-thread: chat turns run - // 'dont-ask' (fail-closed, text answers only); agency turns run the - // session default mode (tools allowed; any permission prompt the CLI - // sends is auto-allowed by handleLine). 'yolo' is NOT a valid ACP - // modeId (verified: Unknown mode) — only the CLI flag. - if (live.mode !== mode) { - try { await this.request('session/set_mode', { sessionId, modeId: mode }, 30000); live.mode = mode; } - catch (err) { console.warn(`[commandcode-proxy] ACP set_mode ${mode} failed (${err.message}) — continuing`); } - } - if (model && live.model !== model) { - await this.request('session/set_model', { sessionId, modelId: model }, 30000); - live.model = model; - if (!ephemeral) { - const cur = sessionStore.get(mappingKey); - if (cur && cur.sessionId === sessionId) { cur.model = model; cur.updatedAt = Date.now(); saveSessions(); } - } - } - } - return { sessionId, resumed }; - }, - - promptThread(sessionId, text, onDelta, timeoutMs) { - return new Promise((resolve, reject) => { - let fullContent = ''; - const handler = (update) => { - if (update.sessionUpdate === 'agent_message_chunk' && update.content && update.content.type === 'text' && typeof update.content.text === 'string') { - fullContent += update.content.text; - if (onDelta) { try { onDelta(update.content.text); } catch {} } - } - }; - this.updateHandlers.set(sessionId, handler); - const timer = setTimeout(() => { - this.updateHandlers.delete(sessionId); - this.notify('session/cancel', { sessionId }); - reject(new Error(`ACP prompt timed out after ${timeoutMs}ms`)); - }, timeoutMs); - timer.unref(); - - this.request('session/prompt', { sessionId, prompt: [{ type: 'text', text }] }, timeoutMs + 30000) - .then(result => { - clearTimeout(timer); - this.updateHandlers.delete(sessionId); - const usage = (result && result._meta && result._meta.usage) || (result && result.usage) || {}; - resolve({ - fullContent, - promptTokens: typeof usage.inputTokens === 'number' ? usage.inputTokens : 0, - completionTokens: typeof usage.outputTokens === 'number' ? usage.outputTokens : 0, - cacheReadTokens: typeof usage.cacheReadTokens === 'number' ? usage.cacheReadTokens : 0, - stopReason: result ? result.stopReason : null - }); - }) - .catch(err => { - clearTimeout(timer); - this.updateHandlers.delete(sessionId); - reject(err); - }); - }); - }, - - // Run one chat turn on the resident engine. Returns the same result - // shape as the spawn-per-request attempts: { failed, detail, ... }. - // agency: the OpenAI request carried tools — run the CLI in tool-using - // mode (default session mode) with the agency prompt; otherwise chat - // mode ('dont-ask', text answer only). - async runChat({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency }) { - const lockKey = ephemeral ? `ephemeral:${crypto.randomUUID()}` : sessionKey; - const prev = this.locks.get(lockKey) || Promise.resolve(); - const run = prev.then( - () => this.runChatLocked({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency, lockKey }), - () => this.runChatLocked({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency, lockKey }) - ); - const stored = run.catch(() => {}); - this.locks.set(lockKey, stored); - stored.then(() => { if (this.locks.get(lockKey) === stored) this.locks.delete(lockKey); }); - return run; - }, - - async runChatLocked({ sessionKey, model, firstPrompt, deltaPrompt, ephemeral, onDelta, agency }) { - let thread = null; - try { - thread = await this.getOrCreateThread(ephemeral ? null : sessionKey, model, ephemeral, agency ? 'default' : 'dont-ask'); - const text = thread.resumed && deltaPrompt && deltaPrompt.trim().length > 0 ? deltaPrompt : firstPrompt; - console.log(`[commandcode-proxy] ACP prompt (${agency ? 'agency' : 'chat'}, ${thread.resumed ? 'delta' : 'full'}, ${text.length} chars) on thread ${thread.sessionId}`); - const r = await this.promptThread(thread.sessionId, text, onDelta, TIMEOUT_MS); - if (!r.fullContent || r.fullContent.trim().length === 0) { - return { failed: true, detail: 'ACP prompt returned no text', fullContent: '', promptTokens: 0, completionTokens: 0, capturedSessionId: thread.sessionId }; - } - const promptTokens = r.promptTokens > 0 ? r.promptTokens : Math.max(1, Math.ceil(text.length / 4)); - const completionTokens = r.completionTokens > 0 ? r.completionTokens : Math.max(1, Math.ceil(r.fullContent.length / 4)); - return { failed: false, detail: null, fullContent: r.fullContent, promptTokens, completionTokens, cacheReadTokens: r.cacheReadTokens || 0, capturedSessionId: thread.sessionId }; - } catch (err) { - return { failed: true, detail: `ACP failed: ${err.message}`, fullContent: '', promptTokens: 0, completionTokens: 0, capturedSessionId: thread ? thread.sessionId : null }; - } finally { - if (ephemeral && thread && thread.sessionId) { - this.liveSessions.delete(thread.sessionId); - try { await this.request('session/close', { sessionId: thread.sessionId }, 10000); } catch {} - } - } - } -}; - - -const server = http.createServer((req, res) => { - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', '*'); - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - // Health & Root - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'commandcode-proxy', - port: PORT, - binary: CC_BIN, - defaultModel: DEFAULT_MODEL, - endpoint: '/v1/chat/completions', - engine: 'acp-resident', - acp: { - running: Boolean(acp.proc), - pid: acp.proc ? acp.proc.pid : null, - starts: acp.starts, - liveThreads: acp.liveSessions.size, - locks: acp.locks.size, - storedMappings: sessionStore.size - } - }, null, 2)); - return; - } - - // Models catalog - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - const data = getServedModels().map(id => ({ - id, - object: 'model', - created: now, - owned_by: 'commandcode' - })); - - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); - return; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); - req.destroy(); - } - }); - - req.on('end', () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Invalid JSON body: ${err.message}` } })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Invalid JSON body: expected an object' } })); - return; - } - - const stream = Boolean(body.stream); - const model = resolveModel(body.model); - const chatId = `chatcmpl-commandcode-${crypto.randomUUID()}`; - const created = Math.floor(Date.now() / 1000); - const sessionKey = getSessionKey(req, body); - const known = sessionKey ? sessionStore.get(sessionKey) : null; - // Agency: the request carries tools, i.e. OpenCode wants an agentic - // turn (its agent loop only sends tools when it wants tool calls). - // The CLI then does the task with its own tools; chat turns stay - // tool-free. Every `opencode run` (build agent) sends tools, so - // opencode agent runs are agency turns by design. - const agency = Array.isArray(body.tools) && body.tools.length > 0; - const agencyWorkdir = sessionKey - ? sessionWorkdirFor(sessionKey) - : path.join(WORKROOT, `req-${crypto.randomUUID()}`); - // Keyed workdirs are mkdir'd by sessionWorkdirFor; ephemeral chat - // turns need no directory at all (the spawn fallback creates and - // cleans its own). Only agency turns need the dir to exist, because - // the agency prompt names it as the file-work root. - if (agency) fs.mkdirSync(agencyWorkdir, { recursive: true }); - const toolManifest = agency - ? body.tools.map(t => { - const fn = t.function || t; - const name = fn.name || t.type || 'tool'; - const desc = (fn.description || '').slice(0, 200); - return `${name}${desc ? ` (${desc})` : ''}`; - }).join('; ').slice(0, 2000) - : ''; - const fullPrompt = formatPrompt(body.messages, agency, agencyWorkdir, toolManifest); - - if (!fullPrompt || fullPrompt.trim().length === 0) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Messages cannot be empty' } })); - return; - } - - // Attempt chain (warm-session pattern, issue #480): resume the - // mapped CLI session with only the newest user turn when we have - // one; a full-history fresh run is always the final fallback. - const attempts = []; - if (known && known.sessionId) { - const latest = extractLatestUserPrompt(body.messages); - if (latest.trim().length > 0) { - const workdir = sessionWorkdirFor(sessionKey); - attempts.push({ - mode: 'resume', - // Agency resume: the raw latest turn lacks the agency - // instruction — re-wrap it so the CLI runs tool-enabled with - // the workdir steer even on the delta path. - prompt: agency - ? formatPrompt([{ role: 'user', content: latest }], true, workdir, toolManifest) - : latest, - sessionId: known.sessionId, - workdir, - persist: true - }); - } - } - attempts.push({ - mode: 'fresh', - prompt: fullPrompt, - sessionId: null, - workdir: sessionKey ? sessionWorkdirFor(sessionKey) : agencyWorkdir, - persist: Boolean(sessionKey) - }); - - if (stream) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream; charset=utf-8', - 'Cache-Control': 'no-cache, no-transform', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no' - }); - } - - let currentChild = null; - let emittedDelta = false; - res.on('close', () => { - if (!res.writableEnded && currentChild) { - try { currentChild.kill('SIGTERM'); } catch (_) {} - } - }); - - const runAttempt = (attempt) => new Promise((resolve) => { - fs.mkdirSync(attempt.workdir, { recursive: true }); - - // Agency spawn: default permission mode (tools allowed — 'dont-ask' - // fails them closed), --tools-all (headless -p withholds tools - // otherwise), and a multi-turn budget. Chat spawn stays - // single-turn dont-ask. cwd is the per-conversation workdir either - // way; the CLI's own tools are unconfined there (fleet parity with - // codex-proxy's danger-full-access), while the agency prompt - // instructs it to stay inside the workdir. - const args = [ - '-p', - '--output-format', 'json', - '-m', model, - '--max-turns', agency ? AGENCY_MAX_TURNS : MAX_TURNS, - '--skip-onboarding', - '--no-auto-update', - '-t' - ]; - if (agency) args.push('--tools-all'); - else args.push('--permission-mode', 'dont-ask'); - if (attempt.sessionId) args.push('--session', attempt.sessionId); - if (!attempt.persist) args.push('--no-session'); - - console.log(`[commandcode-proxy] Spawning (${attempt.mode}${attempt.sessionId ? ` session=${attempt.sessionId}` : ''}): ${CC_BIN} ${args.join(' ')} (prompt ${attempt.prompt.length} chars)`); - - let child; - try { - child = spawn(CC_BIN, args, { - cwd: attempt.workdir, - env: childEnv(), - stdio: ['pipe', 'pipe', 'pipe'] - }); - } catch (err) { - resolve({ failed: true, detail: `Failed to spawn commandcode: ${err.message}`, fullContent: '', promptTokens: 0, completionTokens: 0, capturedSessionId: null }); - return; - } - currentChild = child; - - // Prompt goes in via stdin (`-p` with no query reads stdin). - child.stdin.on('error', () => {}); - child.stdin.write(attempt.prompt); - child.stdin.end(); - - // Never hang forever: hard timeout per attempt. - let timedOut = false; - const timer = setTimeout(() => { - timedOut = true; - try { child.kill('SIGTERM'); } catch (_) {} - setTimeout(() => { try { child.kill('SIGKILL'); } catch (_) {} }, 5000).unref(); - }, TIMEOUT_MS); - timer.unref(); - - let lineBuffer = ''; - const stdoutDecoder = createStreamDecoder(); - const stderrDecoder = createStreamDecoder(); - let fullContent = ''; - let finalText = null; - let promptTokens = Math.max(1, Math.ceil(attempt.prompt.length / 4)); - let completionTokens = 0; - let stderrTail = ''; - let eventError = null; - let capturedSessionId = null; - - const processJsonLine = (line) => { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - - try { - const obj = JSON.parse(trimmed); - const ev = obj.event || obj; - if (!ev || typeof ev.type !== 'string') return; - - if (ev.type === 'run_start' && typeof ev.sessionId === 'string') { - capturedSessionId = ev.sessionId; - } - - // Assistant text delta (thinking_delta deliberately ignored) - if (ev.type === 'text_delta' && typeof ev.delta === 'string') { - const text = ev.delta; - fullContent += text; - - if (stream && !res.writableEnded) { - emittedDelta = true; - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model, - choices: [{ - index: 0, - delta: { content: text }, - finish_reason: null - }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - } - - // Final result line: authoritative text + real token usage. - // (result.nextState carries the full transcript/workspace - // dump — never forwarded; its sessionId is captured.) - if (ev.type === 'run_end' && ev.result) { - if (typeof ev.result.finalText === 'string') finalText = ev.result.finalText; - const usage = ev.result.usage || {}; - if (typeof usage.inputTokens === 'number' && usage.inputTokens > 0) promptTokens = usage.inputTokens; - if (typeof usage.outputTokens === 'number' && usage.outputTokens > 0) completionTokens = usage.outputTokens; - const nsId = ev.result.nextState && ev.result.nextState.sessionId; - if (typeof nsId === 'string') capturedSessionId = nsId; - } - - // Top-level final line: {"type":"result","finalText":...} - if (ev.type === 'result' && typeof ev.finalText === 'string' && ev.finalText) { - finalText = ev.finalText; - const usage = ev.usage || {}; - if (typeof usage.inputTokens === 'number' && usage.inputTokens > 0) promptTokens = usage.inputTokens; - if (typeof usage.outputTokens === 'number' && usage.outputTokens > 0) completionTokens = usage.outputTokens; - if (typeof ev.sessionId === 'string') capturedSessionId = ev.sessionId; - } - - if (ev.type === 'error' || ev.type === 'run_error') { - // Shape: {"type":"run_error","error":{"name":"TransportError", - // "message":"POST /alpha/generate → network error: fetch failed"}} - const e = ev.error; - eventError = (typeof ev.message === 'string' && ev.message) - || (e && typeof e.message === 'string' && e.message) - || (e && typeof e === 'string' && e) - || (e ? JSON.stringify(e) : null) - || 'commandcode reported an error event'; - } - } catch (err) { - // Non-JSON line or parser error ignored - } - }; - - child.stdout.on('data', chunk => { - lineBuffer += stdoutDecoder.push(chunk); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); // remainder - for (const line of lines) { - processJsonLine(line); - } - }); - - child.stderr.on('data', chunk => { - const msg = stderrDecoder.push(chunk); - stderrTail = (stderrTail + msg).slice(-2000); - if (msg.trim().length > 0) { - console.warn(`[commandcode-proxy stderr] ${msg.trim()}`); - } - }); - - child.on('close', (code, signal) => { - clearTimeout(timer); - if (lineBuffer.trim().length > 0) { - processJsonLine(lineBuffer); - lineBuffer = ''; - } - if (!attempt.persist) { - try { fs.rmSync(attempt.workdir, { recursive: true, force: true }); } catch (_) {} - } - - // Prefer the run_end finalText if deltas missed any of it. - if (finalText !== null && finalText.length >= fullContent.length) { - fullContent = finalText; - } - - const failed = timedOut || eventError !== null || (code !== 0 && fullContent.length === 0); - if (failed) { - let detail; - if (timedOut) detail = `commandcode timed out after ${TIMEOUT_MS}ms`; - else if (eventError) detail = String(eventError); - else detail = (stderrTail.trim().split('\n').pop() || `commandcode exited with code ${code}${signal ? ` (signal ${signal})` : ''}`).trim(); - resolve({ failed: true, detail, fullContent, promptTokens, completionTokens, capturedSessionId }); - return; - } - - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - resolve({ failed: false, detail: null, fullContent, promptTokens, completionTokens, capturedSessionId }); - }); - - child.on('error', err => { - clearTimeout(timer); - if (!attempt.persist) { - try { fs.rmSync(attempt.workdir, { recursive: true, force: true }); } catch (_) {} - } - resolve({ failed: true, detail: `CommandCode execution error: ${err.message}`, fullContent: '', promptTokens: 0, completionTokens: 0, capturedSessionId: null }); - }); - }); - - (async () => { - let result = null; - - // Phase 2 primary path: resident ACP engine (one binary boot - // per service, delta-only turns on a persistent thread). Any - // failure falls through to the spawn-per-request attempt chain. - try { - const latestTurn = extractLatestUserPrompt(body.messages); - result = await acp.runChat({ - sessionKey, - model, - firstPrompt: fullPrompt, - // Agency resume: re-wrap the delta turn so the workdir steer - // is present even when only the newest turn is sent. - deltaPrompt: agency && latestTurn.trim().length > 0 - ? formatPrompt([{ role: 'user', content: latestTurn }], true, agencyWorkdir, toolManifest) - : latestTurn, - ephemeral: !sessionKey, - agency, - onDelta: stream ? (text) => { - if (!res.writableEnded) { - emittedDelta = true; - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model, - choices: [{ index: 0, delta: { content: text }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - } : null - }); - if (result && !result.failed) { - console.log(`[commandcode-proxy] ACP turn ok (${result.promptTokens}+${result.completionTokens} tokens)`); - } else if (result) { - console.error(`[commandcode-proxy] ACP path failed, falling back to spawn-per-request: ${result.detail}`); - result = null; - } - } catch (err) { - console.error(`[commandcode-proxy] ACP path threw, falling back: ${err.message}`); - result = null; - } - - if (!result && !emittedDelta) { - for (const attempt of attempts) { - result = await runAttempt(attempt); - if (!result.failed) { - if (attempt.persist && sessionKey && result.capturedSessionId) { - sessionStore.set(sessionKey, { sessionId: result.capturedSessionId, updatedAt: Date.now() }); - pruneSessionStore(); - saveSessions(); - } - break; - } - console.error(`[commandcode-proxy] ${attempt.mode} attempt failed: ${result.detail}`); - if (emittedDelta) break; // cannot retry mid-stream - if (attempt.mode === 'resume' && sessionKey) { - // Stale mapping: drop it so the fresh fallback re-creates it. - sessionStore.delete(sessionKey); - saveSessions(); - } - } - } - - if (res.writableEnded) return; - - if (!result || result.failed) { - const detail = result ? result.detail : 'no attempt ran'; - if (stream) { - // 200 + SSE headers are already on the wire: frame the error - // as an SSE event and close with [DONE] (mirrors agy-proxy). - res.write(`data: ${JSON.stringify({ error: { message: `CommandCode execution failed: ${detail}` } })}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(502, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `CommandCode execution failed: ${detail}` } })); - } - return; - } - - if (stream) { - const endChunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model, - choices: [{ - index: 0, - delta: {}, - finish_reason: 'stop' - }], - usage: { - prompt_tokens: result.promptTokens, - completion_tokens: result.completionTokens, - total_tokens: result.promptTokens + result.completionTokens, - ...(result.cacheReadTokens > 0 ? { prompt_tokens_details: { cached_tokens: result.cacheReadTokens } } : {}) - } - }; - res.write(`data: ${JSON.stringify(endChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: chatId, - object: 'chat.completion', - created, - model, - choices: [{ - index: 0, - message: { - role: 'assistant', - content: result.fullContent - }, - finish_reason: 'stop' - }], - usage: { - prompt_tokens: result.promptTokens, - completion_tokens: result.completionTokens, - total_tokens: result.promptTokens + result.completionTokens, - ...(result.cacheReadTokens > 0 ? { prompt_tokens_details: { cached_tokens: result.cacheReadTokens } } : {}) - } - }, null, 2)); - } - })(); - }); - return; - } - - - // Fallthrough 404 - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); -}); - -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}`); - console.log(`[commandcode-proxy] Workroot: ${WORKROOT}`); -}); diff --git a/bin/commandcode-proxy.test.mjs b/bin/commandcode-proxy.test.mjs deleted file mode 100644 index 7979345658..0000000000 --- a/bin/commandcode-proxy.test.mjs +++ /dev/null @@ -1,338 +0,0 @@ -#!/usr/bin/env node -// Tests for commandcode-proxy's chat/agency split. -// Run: node --test bin/commandcode-proxy.test.mjs -// -// A stub `commandcode` (preferred binary path under a temp HOME) fails the -// ACP handshake fast (so the proxy falls through to the spawn path) and -// answers -p runs with canned NDJSON while recording argv+stdin. The tests -// assert: -// - chat requests (no tools) spawn single-turn `--permission-mode dont-ask` -// with the no-tools steer and never `--tools-all`; -// - agency requests (tools present) spawn `--tools-all`, a multi-turn -// budget, no `dont-ask`, with the workdir steer. -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const STUB = `#!/usr/bin/env node -const fs = require('node:fs'); -const path = require('node:path'); -const rec = process.env.STUB_RECORD_DIR; -const args = process.argv.slice(2); -if (args[0] === 'acp') { - // Fail the ACP handshake fast: answer initialize with an error so the - // proxy falls back to the spawn path without waiting out its timeout. - let buf = ''; - process.stdin.on('data', (c) => { - buf += c.toString('utf8'); - const lines = buf.split('\\n'); - buf = lines.pop(); - for (const line of lines) { - const t = line.trim(); - if (!t || !t.startsWith('{')) continue; - let m; - try { m = JSON.parse(t); } catch { continue; } - if (m.method === 'initialize') { - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: m.id, error: { code: -32000, message: 'stub: no acp' } }) + '\\n'); - process.exit(0); - } - } - }); - return; -} -let stdin = ''; -process.stdin.on('data', (c) => { stdin += c; }); -process.stdin.on('end', () => { - fs.mkdirSync(rec, { recursive: true }); - fs.writeFileSync(path.join(rec, 'argv.json'), JSON.stringify(args)); - fs.writeFileSync(path.join(rec, 'stdin.txt'), stdin); - process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'text_delta', delta: 'STUB-OK' } }) + '\\n'); - process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'run_end', result: { finalText: 'STUB-OK', usage: { inputTokens: 10, outputTokens: 2 } } } }) + '\\n'); - process.exit(0); -}); -`; - -const waitFor = async (url, timeoutMs = 15000) => { - const start = Date.now(); - for (;;) { - try { - const res = await fetch(url); - if (res.ok) return; - } catch {} - if (Date.now() - start > timeoutMs) throw new Error(`timed out waiting for ${url}`); - await new Promise((r) => setTimeout(r, 200)); - } -}; - -test('chat vs agency spawn contract', async (t) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-test-')); - const stubHome = path.join(tmp, 'home'); - const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin'); - fs.mkdirSync(stubBin, { recursive: true }); - fs.writeFileSync(path.join(stubBin, 'commandcode'), STUB, { mode: 0o755 }); - const recDir = path.join(tmp, 'rec'); - fs.mkdirSync(recDir, { recursive: true }); - - const port = 18948; - const env = { - ...process.env, - HOME: stubHome, - COMMANDCODE_PROXY_PORT: String(port), - COMMANDCODE_PROXY_HOST: '127.0.0.1', - COMMANDCODE_PROXY_EGRESS: '', - COMMANDCODE_PROXY_TIMEOUT_MS: '30000', - STUB_RECORD_DIR: recDir, - }; - const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); - let logged = ''; - child.stdout.on('data', (c) => { logged += c; }); - child.stderr.on('data', (c) => { logged += c; }); - child.on('exit', (code, signal) => { logged += `\n[PROXY EXIT code=${code} signal=${signal}]`; }); - t.after(() => { try { child.kill('SIGKILL'); } catch {} }); - t.after(() => { if (process.env.CC_TEST_DEBUG) console.log(logged); }); - - await waitFor(`http://127.0.0.1:${port}/health`); - - const chat = async (body) => { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const text = await res.text(); - assert.equal(res.status, 200, `expected 200, got ${res.status}: ${text.slice(0, 500)}`); - return JSON.parse(text); - }; - - // Chat: no tools (system + user, as OpenCode sends). - const chatRes = await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'system', content: 'sys' }, { role: 'user', content: 'hi' }], stream: false }); - assert.equal(chatRes.choices[0].message.content, 'STUB-OK'); - let argv = JSON.parse(fs.readFileSync(path.join(recDir, 'argv.json'), 'utf8')); - let stdin = fs.readFileSync(path.join(recDir, 'stdin.txt'), 'utf8'); - assert.ok(argv.includes('dont-ask'), `chat must pass dont-ask: ${argv.join(' ')}`); - assert.ok(!argv.includes('--tools-all'), `chat must not pass --tools-all: ${argv.join(' ')}`); - const mt = argv[argv.indexOf('--max-turns') + 1]; - assert.equal(mt, '1', `chat must be single-turn, got max-turns=${mt}`); - assert.ok(stdin.includes('Do not invoke tools'), 'chat prompt must carry the no-tools steer'); - - // Agency: tools present. - const agencyRes = await chat({ - model: 'deepseek/deepseek-v4-flash', - messages: [{ role: 'user', content: 'write it' }], - tools: [{ type: 'function', function: { name: 'write_file', description: 'write a file' } }], - stream: false, - }); - assert.equal(agencyRes.choices[0].message.content, 'STUB-OK'); - argv = JSON.parse(fs.readFileSync(path.join(recDir, 'argv.json'), 'utf8')); - stdin = fs.readFileSync(path.join(recDir, 'stdin.txt'), 'utf8'); - assert.ok(argv.includes('--tools-all'), `agency must pass --tools-all: ${argv.join(' ')}`); - assert.ok(!argv.includes('dont-ask'), `agency must not pass dont-ask: ${argv.join(' ')}`); - const amt = argv[argv.indexOf('--max-turns') + 1]; - assert.ok(Number(amt) > 1, `agency must allow multiple turns, got max-turns=${amt}`); - assert.ok(stdin.includes('Do ALL file work inside'), 'agency prompt must carry the workdir steer'); - assert.ok(stdin.includes('write_file'), 'agency prompt must name the requested tool'); -}); - -// --------------------------------------------------------------------------- -// ACP-speaking stub (#3114): answers the ACP handshake for real so the proxy -// stays on the ACP path, and returns prompt usage carrying cacheReadTokens -// (omitted when the prompt contains NOCACHE). Spawn (-p) invocations keep -// the canned NDJSON behaviour. -// --------------------------------------------------------------------------- -const ACP_STUB = `#!/usr/bin/env node -const args = process.argv.slice(2); -if (args[0] !== 'acp') { - let stdin = ''; - process.stdin.on('data', (c) => { stdin += c; }); - process.stdin.on('end', () => { - process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'text_delta', delta: 'STUB-OK' } }) + '\\n'); - process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'run_end', result: { finalText: 'STUB-OK', usage: { inputTokens: 10, outputTokens: 2 } } } }) + '\\n'); - process.exit(0); - }); - return; -} -let buf = ''; -process.stdin.on('data', (c) => { - buf += c.toString('utf8'); - const lines = buf.split('\\n'); - buf = lines.pop(); - for (const line of lines) { - const t = line.trim(); - if (!t || !t.startsWith('{')) continue; - let m; - try { m = JSON.parse(t); } catch { continue; } - if (m.id === undefined || !m.method) continue; - const reply = (result) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: m.id, result }) + '\\n'); - if (m.method === 'initialize') { - reply({ protocolVersion: 1, agentInfo: { name: 'stub-acp', version: '0' }, agentCapabilities: { loadSession: false } }); - } else if (m.method === 'session/new') { - reply({ sessionId: 'stub-acp-session-1' }); - } else if (m.method === 'session/prompt') { - const sessionId = m.params.sessionId; - const text = (m.params.prompt && m.params.prompt[0] && m.params.prompt[0].text) || ''; - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'ACP-OK' } } } }) + '\\n'); - const usage = text.includes('NOCACHE') - ? { inputTokens: 50, outputTokens: 4 } - : { inputTokens: 50, outputTokens: 4, cacheReadTokens: 77 }; - reply({ stopReason: 'end_turn', usage }); - } else { - reply({}); - } - } -}); -`; - -test('ACP prompt usage cacheReadTokens surfaces as prompt_tokens_details.cached_tokens (#3114)', async (t) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-acp-test-')); - const stubHome = path.join(tmp, 'home'); - const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin'); - fs.mkdirSync(stubBin, { recursive: true }); - fs.writeFileSync(path.join(stubBin, 'commandcode'), ACP_STUB, { mode: 0o755 }); - - const port = 18949; - const env = { - ...process.env, - HOME: stubHome, - COMMANDCODE_PROXY_PORT: String(port), - COMMANDCODE_PROXY_HOST: '127.0.0.1', - COMMANDCODE_PROXY_EGRESS: '', - COMMANDCODE_PROXY_TIMEOUT_MS: '30000', - COMMANDCODE_PROXY_WORKDIR: path.join(tmp, 'work'), - }; - const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); - let logged = ''; - child.stdout.on('data', (c) => { logged += c; }); - child.stderr.on('data', (c) => { logged += c; }); - t.after(() => { try { child.kill('SIGKILL'); } catch {} }); - t.after(() => { if (process.env.CC_TEST_DEBUG) console.log(logged); }); - - await waitFor(`http://127.0.0.1:${port}/health`); - - const chat = async (body) => { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const text = await res.text(); - assert.equal(res.status, 200, `expected 200, got ${res.status}: ${text.slice(0, 500)}`); - return text; - }; - - // Non-streaming: ACP usage cacheReadTokens 77 must surface as cached_tokens. - const plain = JSON.parse(await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi cached' }], stream: false })); - assert.equal(plain.choices[0].message.content, 'ACP-OK'); - assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 77, 'ACP cacheReadTokens must surface as prompt_tokens_details.cached_tokens (opencode #394)'); - - // Streaming: the end chunk carries the same cached_tokens. - const sse = await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi cached stream' }], stream: true }); - const events = sse.split('\n').filter(l => l.startsWith('data: ') && !l.includes('[DONE]')).map(l => JSON.parse(l.slice('data: '.length))); - const endChunk = events.find(e => e.usage); - assert.ok(endChunk, 'stream end chunk must carry usage'); - assert.equal(endChunk.usage.prompt_tokens_details.cached_tokens, 77, 'streaming ACP path must surface cached_tokens'); - - // Zero/absent cache value: prompt_tokens_details omitted entirely. - const noCache = JSON.parse(await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'NOCACHE please' }], stream: false })); - assert.equal(noCache.choices[0].message.content, 'ACP-OK'); - assert.equal(noCache.usage.prompt_tokens_details, undefined, 'absent cacheReadTokens must omit prompt_tokens_details entirely'); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-nullbody-')); - const stubHome = path.join(tmp, 'home'); - const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin'); - fs.mkdirSync(stubBin, { recursive: true }); - fs.writeFileSync(path.join(stubBin, 'commandcode'), STUB, { mode: 0o755 }); - const port = 18953; - const env = { - ...process.env, - HOME: stubHome, - COMMANDCODE_PROXY_PORT: String(port), - COMMANDCODE_PROXY_HOST: '127.0.0.1', - COMMANDCODE_PROXY_EGRESS: '', - COMMANDCODE_PROXY_TIMEOUT_MS: '30000', - STUB_RECORD_DIR: path.join(tmp, 'rec'), - }; - fs.mkdirSync(path.join(tmp, 'rec'), { recursive: true }); - const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); - t.after(() => { try { child.kill('SIGKILL'); } catch {} }); - await waitFor(`http://127.0.0.1:${port}/health`); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); - -test('ACP lock map self-deletes settled entries (#2407)', async (t) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-locks-test-')); - const stubHome = path.join(tmp, 'home'); - const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin'); - fs.mkdirSync(stubBin, { recursive: true }); - fs.writeFileSync(path.join(stubBin, 'commandcode'), ACP_STUB, { mode: 0o755 }); - - const port = 18950; - const env = { - ...process.env, - HOME: stubHome, - COMMANDCODE_PROXY_PORT: String(port), - COMMANDCODE_PROXY_HOST: '127.0.0.1', - COMMANDCODE_PROXY_EGRESS: '', - COMMANDCODE_PROXY_TIMEOUT_MS: '30000', - COMMANDCODE_PROXY_WORKDIR: path.join(tmp, 'work'), - }; - const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); - t.after(() => { try { child.kill('SIGKILL'); } catch {} }); - await waitFor('http://127.0.0.1:' + port + '/health'); - - const chatH = async (body, headers = {}) => { - const res = await fetch('http://127.0.0.1:' + port + '/v1/chat/completions', { - method: 'POST', - headers: { 'Content-Type': 'application/json', ...headers }, - body: JSON.stringify(body), - }); - const text = await res.text(); - assert.equal(res.status, 200, 'expected 200, got ' + res.status + ': ' + text.slice(0, 300)); - return JSON.parse(text); - }; - const locksNow = async () => (await (await fetch('http://127.0.0.1:' + port + '/health')).json()).acp.locks; - const waitLocksEmpty = async () => { - const deadline = Date.now() + 5000; - for (;;) { - const n = await locksNow(); - if (n === 0) return; - if (Date.now() > deadline) assert.fail('locks map must be empty after settle, got ' + n); - await new Promise(r => setTimeout(r, 50)); - } - }; - - // Two distinct session keys through runChat's lock chain. - for (const id of ['cc-leak-a', 'cc-leak-b']) { - const res = await chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi ' + id }], stream: false }, { 'x-session-id': id }); - assert.equal(res.choices[0].message.content, 'ACP-OK'); - } - await waitLocksEmpty(); - - // Same key back-to-back: both complete and the map empties afterwards. - const h = { 'x-session-id': 'cc-order-key' }; - const [r1, r2] = await Promise.all([ - chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'first' }], stream: false }, h), - chatH({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'second' }], stream: false }, h), - ]); - assert.equal(r1.choices[0].message.content, 'ACP-OK'); - assert.equal(r2.choices[0].message.content, 'ACP-OK'); - await waitLocksEmpty(); -}); diff --git a/bin/design-code-proxy.mjs b/bin/design-code-proxy.mjs deleted file mode 100755 index 05e6ddf0e7..0000000000 --- a/bin/design-code-proxy.mjs +++ /dev/null @@ -1,525 +0,0 @@ -#!/usr/bin/env node -import http from 'node:http'; -import https from 'node:https'; -import { parseProxyMillis, parseProxyPort } from './proxy-port.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -const PORT = parseProxyPort('DESIGN_CODE_PROXY_PORT', 18746); -const HOST = process.env.DESIGN_CODE_PROXY_HOST || '127.0.0.1'; - -// Repointed 2026-11-02 (#1413, unblocks #1409): the antigravity-ls door -// (:18745) is retired; every recipe leg that used it now targets -// antigravity-direct (:18751), which serves the same backend model ids -// (gemini-3.8-flash, claude-sonnet-5-5) — verified live against its -// /v1/models before this change. -const ANTIGRAVITY_DIRECT_PORT = parseProxyPort('ANTIGRAVITY_DIRECT_PORT', 18751); -const CODEX_PROXY_PORT = parseProxyPort('CODEX_PROXY_PORT', 18744); -const AMR_UPSTREAM_URL = process.env.AMR_UPSTREAM_URL || 'https://amr-link.open-design.ai/v1'; - -// Warm connections (#480): one keep-alive pool per scheme, shared by every -// backend/upstream call, so repeat requests reuse an open socket instead of -// paying a fresh TCP (and, for the AMR upstream, TLS) handshake per request. -const httpAgent = new http.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); -const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); - -// Backend inactivity timeout (#2097): a backend (or the AMR upstream) that -// accepts the request and then goes silent must fail like any other backend -// error so the fallback fires, instead of hanging the client request and -// holding a pooled socket forever. The timeout is socket inactivity, not a -// total deadline: an actively streaming response keeps resetting it, so -// slow-but-alive streams are never killed. Pinned at 60s — generous for a -// slow first byte from a local language-server backend — and overridable -// via DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS (tests pin it short). -// Strict parse via the house helper (#4225): the previous hand-rolled -// Number() guard admitted values above 2^31-1, which Node's timer layer -// silently truncates to 2147483647 ms (~24.8 days) — defeating this -// timeout entirely — and non-decimal spellings like 0x10 (16 ms). -// parseProxyMillis refuses anything outside integer 1..2147483647 at -// startup, naming the variable; unset/empty keeps the 60s default. -const BACKEND_TIMEOUT_MS = parseProxyMillis('DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS', 60_000); - -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_DIRECT_PORT, model: 'claude-sonnet-5-5' }, fallback: { port: ANTIGRAVITY_DIRECT_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_DIRECT_PORT, model: 'gemini-3.8-flash' } }, - { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol (Design Code)', primary: { port: CODEX_PROXY_PORT, model: 'gpt-6.1-sol' }, fallback: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' } }, - { id: 'deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash (Design Code)', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } }, - { id: 'glm-5.3-flash', name: 'GLM 5.3 Flash (Design Code)', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } }, - { id: 'glm-5.3-flashx', name: 'GLM 5.3 FlashX (Design Code)', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } }, - { id: 'mimo-v2.6-flash', name: 'MIMO v2.6 Flash (Design Code)', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } }, - { id: 'mimo-v2.6-pro', name: 'MIMO v2.6 Pro (Design Code)', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-6.1-sol' } }, - { id: 'design-code-pro', name: 'Design Code Pro', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-6.1-sol' } }, - { id: 'design-code-flash', name: 'Design Code Flash', primary: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' }, fallback: { port: CODEX_PROXY_PORT, model: 'gpt-5.6-luna' } }, - { id: 'open-design-pro', name: 'Open Design Pro', primary: { port: CODEX_PROXY_PORT, model: 'gpt-6.1-sol' }, fallback: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' } } -]; - -const resolveModelConfig = (requestedModel) => { - const clean = (requestedModel || 'design-code-pro').replace(/^.*\//, '').toLowerCase().trim(); - const found = MODELS.find(m => m.id === clean || m.id.replace(/[-_.]/g, '') === clean.replace(/[-_.]/g, '')); - if (found) { - return { modelId: found.id, config: found }; - } - - // 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, - config: { - primary: { port: CODEX_PROXY_PORT, model: clean }, - fallback: { port: ANTIGRAVITY_DIRECT_PORT, model: 'gemini-3.8-flash' } - } - }; - } - - // 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, 18751, 19751]); -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) => { - const envKey = process.env.OPEN_DESIGN_API_KEY || process.env.AMR_API_KEY; - if (envKey && envKey.trim().length > 8) return envKey.trim(); - - if (authHeader && authHeader.startsWith('Bearer ')) { - const token = authHeader.slice(7).trim(); - if (token && !['design-local', 'local', 'none', 'dummy', 'test', 'opencode'].includes(token.toLowerCase())) { - return token; - } - } - return null; -}; - -const server = http.createServer((req, res) => { - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', '*'); - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - // Health - 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), - modelListSource: 'virtual routing recipes (documented exception); backend targets validated live', - backendTargetsCheckedAt: backendCatalogCache.at ? new Date(backendCatalogCache.at).toISOString() : null, - backendTargets: targetState - }, null, 2)); - return; - } - - // Models catalog - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - const data = MODELS.map(m => ({ - id: m.id, - object: 'model', - created: now, - owned_by: 'design-code' - })); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); - return; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Payload too large' } })); - req.destroy(); - } - }); - - req.on('end', () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Invalid JSON: ${err.message}` } })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Invalid JSON body: expected an object' } })); - return; - } - - const upstreamKey = hasUpstreamKey(req.headers.authorization); - - if (upstreamKey) { - // Forward to AMR Link Upstream - console.log(`[design-code-proxy] Forwarding request upstream to ${AMR_UPSTREAM_URL}`); - const upstreamUrl = new URL(`${AMR_UPSTREAM_URL}/chat/completions`); - const clientReq = https.request({ - hostname: upstreamUrl.hostname, - port: upstreamUrl.port || 443, - path: upstreamUrl.pathname + upstreamUrl.search, - method: 'POST', - agent: httpsAgent, - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${upstreamKey}` - } - }, upstreamRes => { - res.writeHead(upstreamRes.statusCode || 200, upstreamRes.headers); - // A mid-stream upstream error must not leave the client (or the - // pooled socket) hanging: tear the response down so the socket - // is released instead of stalling half-open. - upstreamRes.on('error', err => { - console.error(`[design-code-proxy] Upstream response error: ${err.message}`); - res.destroy(); - }); - upstreamRes.pipe(res); - }); - - // Socket inactivity bound (#2097): a silent upstream times out into - // the same error path as a refused connection, so the local - // fallback fires instead of the request hanging forever. - clientReq.setTimeout(BACKEND_TIMEOUT_MS, () => { - clientReq.destroy(new Error(`AMR upstream silent for ${BACKEND_TIMEOUT_MS}ms (backend timeout)`)); - }); - - let upstreamSettled = false; - clientReq.on('error', err => { - if (upstreamSettled) return; - upstreamSettled = true; - if (res.headersSent) { - console.error(`[design-code-proxy] Upstream error after response started: ${err.message}`); - res.destroy(); - return; - } - console.error(`[design-code-proxy] Upstream error: ${err.message}. Falling back to local dispatch.`); - dispatchWithFallback(body, res); - }); - - clientReq.write(bodyText); - clientReq.end(); - } else { - // Local smart dispatch - dispatchWithFallback(body, res); - } - }); - return; - } - - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); -}); - -const dispatchWithFallback = (body, clientRes) => { - const reqModel = body.model; - 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] : []; - const sysIdx = messages.findIndex(m => m.role === 'system'); - if (sysIdx >= 0) { - const existing = typeof messages[sysIdx].content === 'string' - ? messages[sysIdx].content - : JSON.stringify(messages[sysIdx].content); - messages[sysIdx] = { - role: 'system', - content: `${DESIGN_SYSTEM_PROMPT}\n\n${existing}` - }; - } else { - messages.unshift({ - role: 'system', - content: DESIGN_SYSTEM_PROMPT - }); - } - - const tryTarget = (target, onFailRaw) => { - // onFail must fire at most once per target: a timeout destroy surfaces - // as both a request error and (sometimes) a response error, and a - // second onFail would re-enter the fallback chain (#2097). - let failSettled = false; - const onFail = (err) => { - if (failSettled) return; - failSettled = true; - onFailRaw(err); - }; - // A target that has failed is retired: the fallback (or the final 502) - // owns the client response from that moment, and nothing the retired - // target does afterwards — a late response error, a timeout firing on - // a body still being drained — may touch the client response (Codex - // P2 on PR #4204). - const targetRetired = () => failSettled; - // Set when THIS target writes the client head (streaming path). A - // retired target whose head the client is carrying is still the owner - // of that stream: its late errors must tear the stream down, not be - // ignored (PR #4204 Codex P2, second round). Only a retired target - // that never wrote the head has handed the client to the fallback. - let headWrittenByMe = false; - const stream = Boolean(body.stream); - const payload = JSON.stringify({ - ...body, - model: target.model, - messages - }); - - console.log(`[design-code-proxy] Trying '${reqModel}' -> 127.0.0.1:${target.port} (${target.model})`); - - const localReq = http.request({ - hostname: '127.0.0.1', - port: target.port, - path: '/v1/chat/completions', - method: 'POST', - agent: httpAgent, - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(payload) - } - }, localRes => { - // A backend response error must not hang the client: fall back when - // nothing was sent yet, otherwise tear the response down so the - // pooled socket is released instead of stalling half-open. - localRes.on('error', err => { - console.warn(`[design-code-proxy] Error reading response from 127.0.0.1:${target.port}: ${err.message}`); - if (targetRetired() && !headWrittenByMe) return; // fallback owns the client response now - if (!clientRes.headersSent) onFail(err); - else clientRes.destroy(); - }); - - // Check for quota exhaustion / error codes - if (localRes.statusCode === 429 || localRes.statusCode >= 500) { - console.warn(`[design-code-proxy] Target 127.0.0.1:${target.port} returned ${localRes.statusCode}`); - localRes.resume(); // discard response - onFail(new Error(`HTTP ${localRes.statusCode}`)); - // Retire the failed target immediately instead of draining a body - // that may never end: its socket is freed now, and the retired - // guard above keeps any resulting error away from the fallback's - // client response. - localReq.destroy(); - return; - } - - // The head is written up front only for streaming. For a buffered - // (non-stream) response it must wait until the body has been read: - // the in-body quota check below can still call onFail, and onFail is - // a no-op once headers are sent — writing the head first made that - // check hang the request forever instead of falling back (#681). - // The backend's framing headers describe the backend's body, not - // the one this proxy sends: the non-stream success path - // re-serializes the JSON (model rewritten, pretty-printed) and the - // stream path rewrites each chunk's model, so a forwarded - // Content-Length truncates the client at the backend's byte count - // (#684). When the exact body being sent is known, advertise its - // real length; for streaming, drop the stale framing and let Node - // chunk the response. - const writeHead = (sentBody) => { - if (!clientRes.headersSent) { - const headers = { - ...localRes.headers, - 'Access-Control-Allow-Origin': '*' - }; - delete headers['transfer-encoding']; - if (sentBody !== undefined) { - headers['content-length'] = Buffer.byteLength(sentBody); - } else { - delete headers['content-length']; - } - clientRes.writeHead(localRes.statusCode || 200, headers); - headWrittenByMe = true; - } - }; - - if (stream) { - writeHead(); - let buffer = ''; - const streamDecoder = createStreamDecoder(); - localRes.on('data', chunk => { - buffer += streamDecoder.push(chunk); - const lines = buffer.split('\n'); - buffer = lines.pop(); - for (const line of lines) { - if (line.startsWith('data: ') && line.trim() !== 'data: [DONE]') { - try { - const data = JSON.parse(line.slice(6)); - data.model = modelId; - clientRes.write(`data: ${JSON.stringify(data)}\n\n`); - } catch (_) { - clientRes.write(`${line}\n`); - } - } else { - clientRes.write(`${line}\n`); - } - } - }); - - localRes.on('end', () => { - if (buffer) clientRes.write(buffer); - clientRes.end(); - }); - } else { - const fullBodyChunks = []; - localRes.on('data', chunk => { - fullBodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - localRes.on('end', () => { - const fullBody = Buffer.concat(fullBodyChunks).toString('utf-8'); - try { - const json = JSON.parse(fullBody); - if (json.error && (json.error.code === 429 || json.error.type === 'insufficient_quota')) { - return onFail(new Error('Quota exceeded in JSON body')); - } - json.model = modelId; - const sentBody = JSON.stringify(json, null, 2); - writeHead(sentBody); - clientRes.end(sentBody); - } catch (_) { - writeHead(fullBody); - clientRes.end(fullBody); - } - }); - } - }); - - localReq.on('error', err => { - console.warn(`[design-code-proxy] Error connecting to 127.0.0.1:${target.port}: ${err.message}`); - onFail(err); - }); - - // Socket inactivity bound (#2097): a backend that accepts and never - // answers (or stalls mid-response with no bytes flowing) is destroyed - // into the error path above, so onFail fires and the fallback runs. - // Actively streaming responses keep the socket busy and are untouched. - localReq.setTimeout(BACKEND_TIMEOUT_MS, () => { - localReq.destroy(new Error(`backend 127.0.0.1:${target.port} silent for ${BACKEND_TIMEOUT_MS}ms (backend timeout)`)); - }); - - localReq.write(payload); - localReq.end(); - }; - - // 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 (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({ - error: { message: `All design code backends failed: ${fallbackErr.message}` } - })); - } - }); - } else { - clientRes.writeHead(502, { 'Content-Type': 'application/json' }); - clientRes.end(JSON.stringify({ - error: { message: `Design code backend failed: ${err.message}` } - })); - } - }); -}; - -server.listen(PORT, HOST, () => { - console.log(`[design-code-proxy] Listening on http://${HOST}:${PORT}`); - console.log(`[design-code-proxy] Backends: Antigravity Direct (${ANTIGRAVITY_DIRECT_PORT}), Codex (${CODEX_PROXY_PORT}), AMR Upstream (${AMR_UPSTREAM_URL})`); -}); diff --git a/bin/design-code-proxy.test.mjs b/bin/design-code-proxy.test.mjs deleted file mode 100644 index e792884ea0..0000000000 --- a/bin/design-code-proxy.test.mjs +++ /dev/null @@ -1,505 +0,0 @@ -// Tests for design-code-proxy's local-dispatch fallback (#681). -// Run: node --test bin/design-code-proxy.test.mjs -// -// The proxy dispatches a chat request to a primary local backend and -// falls back to a second one on quota/5xx/connection failures. These -// tests run the real proxy against two in-process stub backends whose -// behaviour each test sets per stub (primary.mode / fallback.mode): -// -// 'quota-body' -> HTTP 200 with {"error":{"code":429,...}} in the body -// 'quota-status' -> HTTP 429 status -// 'ok-length' -> a successful chat completion with an explicit -// Content-Length on the compact JSON body (#684) -// 'ok-length-stream' -> the SSE stream, with a Content-Length set to -// the backend's own (pre-model-rewrite) byte count, -// which is stale the moment the proxy rewrites the -// model in each chunk (#688) -// 'ok' (default) -> a successful chat completion naming the backend -// -// A quota error reported in a 200 JSON body used to hang the client -// request forever: tryTarget wrote the response head before reading -// the body, so the in-body quota check's onFail hit the headersSent -// guard and silently returned — no fallback, no response end. -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import http from 'node:http'; -import net from 'node:net'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -const startStub = (name) => new Promise((resolve) => { - const stub = { name, mode: 'ok', calls: 0, port: 0, remotePorts: [], stop: () => {} }; - const server = http.createServer((req, res) => { - let bodyText = ''; - req.on('data', c => { bodyText += c; }); - req.on('end', () => { - stub.calls += 1; - stub.remotePorts.push(req.socket.remotePort); - if (stub.mode === 'stall-mid-stream') { - // Send one SSE chunk, then go silent forever (PR #4204 Codex P2, - // second round): the backend timeout must tear the client stream - // down, not leave it open. - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - const chunk = { - id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', - choices: [{ index: 0, delta: { content: `partial from ${name}` }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - return; - } - if (stub.mode === 'stall-status') { - // Flush a 429 head and then leave the body open forever (#2097 / - // PR #4204 Codex P2): the proxy falls back at the head, and the - // stalled body must not be able to hurt the fallback afterwards. - res.writeHead(429, { 'Content-Type': 'application/json' }); - res.flushHeaders(); - return; - } - if (stub.mode === 'hang') { - // Accept the request and never respond (#2097): the wedged-backend - // case. The socket is left open; the proxy's backend timeout is - // the only thing that can unstick the client request. - return; - } - if (stub.mode === 'slow-stream') { - // Actively streaming with gaps well under any sane inactivity - // timeout: must NOT be killed by the backend timeout (#2097). - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - const chunk = { - id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', - choices: [{ index: 0, delta: { content: `hello from ${name}` }, finish_reason: null }] - }; - let sent = 0; - const timer = setInterval(() => { - sent += 1; - if (sent <= 3) { - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } else { - clearInterval(timer); - res.end('data: [DONE]\n\n'); - } - }, 150); - return; - } - if (stub.mode === 'error-mid-stream') { - // Send a head and a partial body, then destroy the socket: - // the proxy's backend response errors mid-stream (#782). - if (bodyText.includes('"stream":true')) { - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - const chunk = { - id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', - choices: [{ index: 0, delta: { content: `partial from ${name}` }, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.write('{"id":"chatcmpl-stub","partial":'); - } - setTimeout(() => { res.socket.destroy(); }, 25); - return; - } - if (stub.mode === 'quota-body') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { code: 429, message: `${name} quota`, type: 'insufficient_quota' } })); - } else if (stub.mode === 'quota-status') { - res.writeHead(429, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { code: 429, message: `${name} quota` } })); - } else if (stub.mode === 'ok-length' && !bodyText.includes('"stream":true')) { - const compact = JSON.stringify({ - id: 'chatcmpl-stub', object: 'chat.completion', created: 0, model: 'stub-model', - choices: [{ index: 0, message: { role: 'assistant', content: `hello from ${name}` }, finish_reason: 'stop' }] - }); - res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(compact) }); - res.end(compact); - } else if (bodyText.includes('"stream":true')) { - const chunk = { - id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', - choices: [{ index: 0, delta: { content: `hello from ${name}` }, finish_reason: null }] - }; - const payload = `data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`; - const headers = { 'Content-Type': 'text/event-stream' }; - if (stub.mode === 'ok-length-stream') { - // #688: the length of the backend's own body. The proxy's - // per-chunk model rewrite makes the body it sends longer, so - // forwarding this length would truncate the stream. - headers['Content-Length'] = Buffer.byteLength(payload); - } - res.writeHead(200, headers); - res.end(payload); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: 'chatcmpl-stub', object: 'chat.completion', created: 0, model: 'stub-model', - choices: [{ index: 0, message: { role: 'assistant', content: `hello from ${name}` }, finish_reason: 'stop' }] - })); - } - }); - }); - server.listen(0, '127.0.0.1', () => { - stub.port = server.address().port; - stub.stop = () => server.close(); - resolve(stub); - }); -}); - -const startProxy = async ({ backendTimeoutMs } = {}) => { - const primary = await startStub('primary'); - const fallback = await startStub('fallback'); - const port = await freePort(); - const env = { ...process.env }; - delete env.OPEN_DESIGN_API_KEY; - delete env.AMR_API_KEY; - const child = spawn(process.execPath, [path.join(binDir, 'design-code-proxy.mjs')], { - env: { - ...env, - DESIGN_CODE_PROXY_PORT: String(port), - ANTIGRAVITY_DIRECT_PORT: String(primary.port), - CODEX_PROXY_PORT: String(fallback.port), - ...(backendTimeoutMs ? { DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS: String(backendTimeoutMs) } : {}) - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', d => { log += d; }); - child.stderr.on('data', d => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch { /* not up yet */ } - if (Date.now() > deadline) throw new Error(`proxy did not start:\n${log}`); - await new Promise(r => setTimeout(r, 50)); - } - return { - port, primary, fallback, - stop: () => { child.kill('SIGKILL'); primary.stop(); fallback.stop(); } - }; -}; - -// design-code-flash: primary = Antigravity stub, fallback = Codex stub. -// The 5s abort makes the pre-fix hang fail fast instead of wedging the suite. -const post = (port, extra = {}) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: 'design-code-flash', messages: [{ role: 'user', content: 'hi' }], ...extra }), - signal: AbortSignal.timeout(5000) -}); - -test('successful primary response is unchanged (model rewritten, no fallback call)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - const res = await post(port); - assert.equal(res.status, 200); - const body = JSON.parse(await res.text()); - assert.equal(body.choices[0].message.content, 'hello from primary'); - assert.equal(body.model, 'design-code-flash'); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 0); -}); - -test('quota error in a 200 JSON body falls back instead of hanging (#681)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'quota-body'; - const res = await post(port); - assert.equal(res.status, 200); - const body = JSON.parse(await res.text()); - assert.equal(body.choices[0].message.content, 'hello from fallback'); - assert.equal(body.model, 'design-code-flash'); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 1); -}); - -test('quota error in a 200 JSON body on the fallback target answers 502 promptly (#681)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'quota-body'; - fallback.mode = 'quota-body'; - const res = await post(port); - assert.equal(res.status, 502); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /All design code backends failed/); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 1); -}); - -test('HTTP-status 429 still falls back (control)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'quota-status'; - const res = await post(port); - assert.equal(res.status, 200); - const body = JSON.parse(await res.text()); - assert.equal(body.choices[0].message.content, 'hello from fallback'); - assert.equal(fallback.calls, 1); -}); - -test('backend Content-Length does not truncate the re-serialized success body (#684)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'ok-length'; - const res = await post(port); - assert.equal(res.status, 200); - const text = await res.text(); - // The forwarded head must describe the body actually sent: either no - // Content-Length (chunked) or exactly the received byte count — never - // the backend's shorter compact-body length. - const advertised = res.headers.get('content-length'); - if (advertised !== null) { - assert.equal(Number(advertised), Buffer.byteLength(text)); - } - const body = JSON.parse(text); - assert.equal(body.choices[0].message.content, 'hello from primary'); - assert.equal(body.model, 'design-code-flash'); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 0); -}); - -test('backend Content-Length does not truncate the model-rewritten SSE stream (#688)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'ok-length-stream'; - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - const sse = await res.text(); - // The proxy rewrites the model in every chunk, so the stream it sends - // is longer than the backend body the stub's Content-Length describes. - // Forwarding that stale length truncates the tail — [DONE] is lost. - assert.match(sse, /hello from primary/); - assert.match(sse, /design-code-flash/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]'), `stream truncated: ${JSON.stringify(sse)}`); - // The forwarded head must describe the stream actually sent: either no - // Content-Length (chunked) or exactly the received byte count. - const advertised = res.headers.get('content-length'); - if (advertised !== null) { - assert.equal(Number(advertised), Buffer.byteLength(sse)); - } - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 0); -}); - -test('streaming success is unchanged', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - const sse = await res.text(); - assert.match(sse, /hello from primary/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]')); -}); - -// Keep-alive pool + response-error contracts (#768, per #782). The -// stub records the source port of each backend connection: a reused -// pooled socket arrives from the same port, a fresh handshake from a -// new one. -test('sequential requests reuse the keep-alive pool (#782)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - const first = await post(port); - assert.equal(first.status, 200); - await first.text(); - const second = await post(port); - assert.equal(second.status, 200); - await second.text(); - assert.equal(primary.calls, 2); - assert.equal(fallback.calls, 0); - assert.equal(primary.remotePorts.length, 2); - assert.equal(primary.remotePorts[0], primary.remotePorts[1], - `expected one pooled socket, saw source ports ${primary.remotePorts}`); -}); - -test('backend response error before headers falls back (#782)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'error-mid-stream'; - // Non-stream: the proxy sends no head until the backend body is - // complete, so a mid-stream backend error is still "before headers" - // for the client and must fall back, not hang or tear down. - const res = await post(port); - assert.equal(res.status, 200); - const body = JSON.parse(await res.text()); - assert.equal(body.choices[0].message.content, 'hello from fallback'); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 1); -}); - -test('backend response error after headers tears the client response down (#782)', async (t) => { - const { port, primary, fallback, stop } = await startProxy(); - t.after(stop); - primary.mode = 'error-mid-stream'; - // Stream: the head is written up front, so a mid-stream backend - // error is "after headers" — the client response must be destroyed - // promptly (its body read fails), never left hanging and never - // completed as if the stream had ended cleanly. - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - const startedAt = Date.now(); - await assert.rejects(res.text()); - // The rejection must come from the proxy tearing the response down, - // not from the client's own 5s abort: a proxy that simply hangs - // would also reject, but only at the abort deadline. - assert.ok(Date.now() - startedAt < 3000, - `client response was not torn down promptly (${Date.now() - startedAt}ms)`); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 0); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); - -test('silent primary times out and falls back instead of hanging forever (#2097)', async (t) => { - const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); - t.after(stop); - primary.mode = 'hang'; - const started = Date.now(); - const res = await post(port); - assert.ok(Date.now() - started < 5000, 'fallback must answer within the client abort window'); - assert.equal(res.status, 200); - const body = JSON.parse(await res.text()); - assert.equal(body.choices[0].message.content, 'hello from fallback'); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 1); -}); - -test('both backends silent answer a bounded 502, never an indefinite hang (#2097)', async (t) => { - const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); - t.after(stop); - primary.mode = 'hang'; - fallback.mode = 'hang'; - const started = Date.now(); - const res = await post(port); - const elapsed = Date.now() - started; - assert.ok(elapsed < 5000, `both-hang must 502 within the client abort window, took ${elapsed}ms`); - assert.equal(res.status, 502); - const body = JSON.parse(await res.text()); - assert.match(body.error.message, /All design code backends failed/); - assert.match(body.error.message, /backend timeout/); -}); - -test('slow but actively streaming primary is not killed by the backend timeout (#2097)', async (t) => { - const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); - t.after(stop); - primary.mode = 'slow-stream'; - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - const text = await res.text(); - assert.match(text, /hello from primary/); - assert.match(text, /\[DONE\]/); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 0); -}); - -test('a retired primary with a stalled 429 body cannot truncate the fallback stream (#2097, PR #4204 Codex P2)', async (t) => { - const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 400 }); - t.after(stop); - primary.mode = 'stall-status'; - fallback.mode = 'slow-stream'; - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - const text = await res.text(); - assert.match(text, /hello from fallback/); - assert.match(text, /\[DONE\]/); - assert.equal(primary.calls, 1); - assert.equal(fallback.calls, 1); -}); - -test('a primary that stalls mid-stream has its client stream torn down by the timeout (#2097, PR #4204 Codex P2 round 2)', async (t) => { - const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 400 }); - t.after(stop); - primary.mode = 'stall-mid-stream'; - const res = await post(port, { stream: true }); - assert.equal(res.status, 200); - // The body read must fail (stream torn down) rather than hang: the 5s - // client abort in post() only covers the fetch head, so race the read - // against a 3s bound explicitly. - const read = res.text().then(() => 'completed', () => 'torn-down'); - const bounded = new Promise(r => setTimeout(() => r('hung'), 3000)); - assert.equal(await Promise.race([read, bounded]), 'torn-down'); - assert.equal(fallback.calls, 0); -}); - -// #4225: DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS goes through the strict -// parseProxyMillis helper. Overflow and non-decimal spellings must -// refuse to start (naming the variable) instead of silently truncating -// to ~24.8 days or 16 ms; a valid value is honoured (the #2097 tests -// above already pin short values through startProxy). -const spawnProxyRaw = async (extraEnv) => { - const port = await freePort(); - const env = { ...process.env }; - delete env.OPEN_DESIGN_API_KEY; - delete env.AMR_API_KEY; - const child = spawn(process.execPath, [path.join(binDir, 'design-code-proxy.mjs')], { - env: { ...env, DESIGN_CODE_PROXY_PORT: String(port), ...extraEnv }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', d => { log += d; }); - child.stderr.on('data', d => { log += d; }); - return { child, port, log: () => log }; -}; - -const waitForExit = (child, ms = 5000) => new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error('proxy did not exit in time')), ms); - child.on('exit', code => { clearTimeout(timer); resolve(code); }); -}); - -test('a backend timeout above 2^31-1 refuses to start, naming the variable (#4225)', async () => { - const { child, log } = await spawnProxyRaw({ DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS: '2147483648' }); - const code = await waitForExit(child); - assert.notEqual(code, 0); - assert.match(log(), /DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS/); - assert.match(log(), /2147483648/); -}); - -test('non-decimal backend timeout spellings refuse to start (#4225)', async () => { - for (const bad of ['0x10', '1e5']) { - const { child, log } = await spawnProxyRaw({ DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS: bad }); - const code = await waitForExit(child); - assert.notEqual(code, 0, `${bad} should refuse to start`); - assert.match(log(), /DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS/); - } -}); - -test('a valid backend timeout value is honoured (#4225)', async () => { - const { child, port } = await spawnProxyRaw({ DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS: '5000' }); - try { - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch { /* not up yet */ } - if (Date.now() > deadline) throw new Error('proxy with a valid timeout did not start'); - await new Promise(r => setTimeout(r, 50)); - } - } finally { - child.kill('SIGKILL'); - } -}); diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs index 05da7c29e7..f865f7a9a9 100644 --- a/bin/muse-proxy.mjs +++ b/bin/muse-proxy.mjs @@ -47,10 +47,11 @@ import { parseProxyPort } from './proxy-port.mjs'; import { createRequestBodyCollector } from './request-body.mjs'; import { createStreamDecoder } from './stream-decode.mjs'; -// Default port 18747: 18746 is claimed by design-code-proxy -// (DESIGN_CODE_PROXY_PORT) in this repo's config, so muse-proxy takes the -// next port in the family range (cf. clef 18742, agy 18743, codex 18744, -// antigravity-ls 18745, design-code 18746). +// Default port 18747: muse-proxy takes the next port in the family +// range after design-code's old 18746 (cf. clef 18742, agy 18743, +// codex 18744, antigravity-ls 18745, design-code 18746 — all since +// retired; design-code's bin program was removed in the 2026-11-06 +// proxy-infra decommission). const PORT = parseProxyPort('MUSE_PROXY_PORT', 18747); const HOST = process.env.MUSE_PROXY_HOST || '127.0.0.1'; diff --git a/bin/openchamber-start.sh b/bin/openchamber-start.sh index dee8594d17..7a1fdee5f9 100755 --- a/bin/openchamber-start.sh +++ b/bin/openchamber-start.sh @@ -1,6 +1,6 @@ #!/bin/bash # Laptop start wrapper for OpenChamber (fleet pattern, mirrors -# bin/commandcode-proxy-start.sh). The home-manager unit does not exec +# bin/muse-proxy-start.sh). The home-manager unit does not exec # the serve script directly; it execs this wrapper with the serve # script's store path as $1 (openchamberUnitStart in # home/common/default.nix). diff --git a/bin/provider-catalog-sync.mjs b/bin/provider-catalog-sync.mjs index 7c5fff0fd0..0bb21585d3 100644 --- a/bin/provider-catalog-sync.mjs +++ b/bin/provider-catalog-sync.mjs @@ -75,12 +75,14 @@ const defineValue = (obj, key, value) => { // api.json used as cross-check (null = no meaningful cross-check). // --------------------------------------------------------------------------- const PROVIDER_SOURCES = { - 'claude-code': { kind: 'proxy', port: 18749, modelsDev: null }, - commandcode: { kind: 'proxy', port: 18748, modelsDev: 'commandcode' }, + // No claude-code / commandcode / antigravity-agy / antigravity-ls + // entries: their CLI proxies were removed in the 2026-11-06 + // proxy-infra decommission (claude-code and commandcode were + // repointed to native fork providers on 2026-11-05; the + // antigravity doors retired 2026-10-30). Their catalogs are + // native-owned now, so they report 'no-source-configured'. 'openai-codex': { kind: 'proxy', port: 18744, modelsDev: 'openai' }, chatgpt: { kind: 'proxy', port: 18744, modelsDev: 'openai' }, - 'antigravity-agy': { kind: 'proxy', port: 18743, modelsDev: null }, - 'antigravity-ls': { kind: 'proxy', port: 18745, modelsDev: null }, deepseek: { kind: 'crosscheck', modelsDev: 'deepseek' }, groq: { kind: 'crosscheck', modelsDev: 'groq' }, meta: { kind: 'crosscheck', modelsDev: 'meta' }, diff --git a/bin/provider-catalog-sync.test.mjs b/bin/provider-catalog-sync.test.mjs index cadcb6c64b..489163d06d 100644 --- a/bin/provider-catalog-sync.test.mjs +++ b/bin/provider-catalog-sync.test.mjs @@ -60,10 +60,10 @@ const runSnapshot = async (snapshot) => { const configPath = path.join(dir, 'config.jsonc'); fs.writeFileSync(configPath, JSON.stringify({ provider: { - 'claude-code': { models: { 'model-a': {}, 'model-b': {} } }, + chatgpt: { models: { 'model-a': {}, 'model-b': {} } }, }, })); - fs.writeFileSync(path.join(sourceDir, '18749.json'), JSON.stringify(snapshot)); + fs.writeFileSync(path.join(sourceDir, '18744.json'), JSON.stringify(snapshot)); try { return await runSync({ configPath, modelsDevSpec: null, sourceDir }); } finally { @@ -79,9 +79,9 @@ for (const [name, snapshot] of [ ]) { test(`runSync marks proxy snapshot with ${name} as not-enumerable`, async () => { const { report } = await runSnapshot(snapshot); - const entry = report.providers['claude-code']; + const entry = report.providers.chatgpt; assert.equal(entry.status, 'not-enumerable'); - assert.match(entry.note, /proxy :18749 enumeration failed:/); + assert.match(entry.note, /proxy :18744 enumeration failed:/); assert.equal(entry.live_count, undefined); assert.equal(entry.vanishings_basis, undefined); }); @@ -89,7 +89,7 @@ for (const [name, snapshot] of [ test('runSync preserves the valid proxy snapshot report', async () => { const { report } = await runSnapshot({ data: [{ id: 'model-a' }, { id: 'model-b' }] }); - const entry = report.providers['claude-code']; + const entry = report.providers.chatgpt; assert.equal(entry.live_count, 2); assert.deepEqual(entry.additions_validated, []); assert.deepEqual(entry.vanishings, []); @@ -356,10 +356,10 @@ function controlFixture() { const configPath = path.join(dir, 'opencode.jsonc'); const configText = `{ "provider": { - "commandcode": { + "chatgpt": { "npm": "@ai-sdk/openai-compatible", "models": { - "acme-1": { "name": "Acme 1 (commandcode)" } + "acme-1": { "name": "Acme 1 (chatgpt)" } } } } @@ -368,7 +368,7 @@ function controlFixture() { fs.writeFileSync(configPath, configText); const sourceDir = path.join(dir, 'src'); fs.mkdirSync(sourceDir); - fs.writeFileSync(path.join(sourceDir, '18748.json'), JSON.stringify({ data: [{ id: 'acme-1' }, { id: 'acme-2' }] })); + fs.writeFileSync(path.join(sourceDir, '18744.json'), JSON.stringify({ data: [{ id: 'acme-1' }, { id: 'acme-2' }] })); const modelsDev = path.join(dir, 'models-dev.json'); fs.writeFileSync(modelsDev, '{}'); return { configPath, configText, sourceDir, modelsDev }; @@ -418,14 +418,14 @@ test('CLI: OPENCODE_CONFIG_PATH pointing at the overlay does not redirect the ta ['--config', configPath, '--runtime-config', overlayPath, '--models-dev', modelsDev, '--source-dir', sourceDir, '--json'], { OPENCODE_CONFIG_PATH: overlayPath }, ); - // The tracked file carries commandcode/acme-1 and the snapshot adds acme-2: + // The tracked file carries chatgpt/acme-1 and the snapshot adds acme-2: // a run against the tracked default reports the validated addition (exit 3). // Against the overlay (the bug) it would report config=overlay and exit 0. assert.equal(r.status, 3, `stdout: ${r.stdout} stderr: ${r.stderr}`); const report = JSON.parse(r.stdout); assert.equal(report.config, configPath); assert.equal(report.runtime_overlay, overlayPath); - assert.ok(report.providers.commandcode, `providers: ${Object.keys(report.providers)}`); + assert.ok(report.providers.chatgpt, `providers: ${Object.keys(report.providers)}`); }); // --------------------------------------------------------------------------- diff --git a/bin/proxy-port.test.mjs b/bin/proxy-port.test.mjs index 0a71a4a78b..2ed947d1f7 100644 --- a/bin/proxy-port.test.mjs +++ b/bin/proxy-port.test.mjs @@ -140,21 +140,6 @@ test('host:port addresses are parsed strictly (#494)', () => { } }); -test('antigravity-ls-proxy validates ANTIGRAVITY_LS_ADDRESS via the shared helper (#494)', () => { - const source = fs.readFileSync(path.join(binDir, 'antigravity-ls-proxy.mjs'), 'utf8'); - assert.match( - source, - /parseAddressPortValue\('ANTIGRAVITY_LS_ADDRESS', process\.env\.ANTIGRAVITY_LS_ADDRESS\)/, - 'antigravity-ls-proxy should validate ANTIGRAVITY_LS_ADDRESS with parseAddressPortValue' - ); - assert.doesNotMatch( - source, - /parseInt\(parts/, - 'antigravity-ls-proxy still parses ANTIGRAVITY_LS_ADDRESS with bare parseInt' - ); - assert.match(source, /p >= 1 && p <= 65535/, 'candidate add() should bound ports to 1-65535'); -}); - const runCodex = (value) => spawnSync(process.execPath, [path.join(binDir, 'codex-proxy.mjs')], { env: { @@ -318,19 +303,16 @@ test('codex-proxy binds exactly the requested valid port', async (t) => { assert.equal((await res.json()).port, port); }); -test('every proxy port parse site in the five proxies uses the shared helper', () => { +test('every proxy port parse site in the surviving proxies uses the shared helper', () => { // Per-file inventory, named, so a rework that moves a port from one proxy // to another has to update this list on purpose instead of drifting a bare - // total. design-code-proxy owns the antigravity-direct port parses. + // total. The retired doors (agy-proxy, antigravity-ls-proxy and + // design-code-proxy — retired 2026-10-30/2026-11-03, their bins kept + // as history until then — plus claude-code-proxy and + // commandcode-proxy) left this list with their bin programs in the + // 2026-11-06 proxy-infra decommission. const expected = { 'codex-proxy.mjs': ['CODEX_PROXY_PORT'], - 'agy-proxy.mjs': ['AGY_PROXY_PORT'], - 'antigravity-ls-proxy.mjs': ['ANTIGRAVITY_LS_PROXY_PORT'], - 'design-code-proxy.mjs': [ - 'DESIGN_CODE_PROXY_PORT', - 'ANTIGRAVITY_DIRECT_PORT', - 'CODEX_PROXY_PORT' - ], 'muse-proxy.mjs': ['MUSE_PROXY_PORT'] }; for (const [file, names] of Object.entries(expected)) { @@ -366,7 +348,8 @@ test('home-manager launches codex-proxy from the bin directory', () => { // entries this test once listed were removed with their launchers: // agy-proxy + antigravity-ls-proxy (retired 2026-10-30), // design-code-proxy (2026-11-03), clef-proxy (2026-11-04, - // opencode#1410). + // opencode#1410); the retired doors' bin programs were removed in + // the 2026-11-06 proxy-infra decommission. const nix = fs.readFileSync( path.join(binDir, '..', 'home', 'common', 'default.nix'), 'utf8' diff --git a/home/common/default.nix b/home/common/default.nix index 4420a79891..a936b675b6 100644 --- a/home/common/default.nix +++ b/home/common/default.nix @@ -19,11 +19,16 @@ let # /v1/systemone (127.0.0.1:13420); the port is free. codexProxyPort = 18744; museProxyPort = 18747; - commandcodeProxyPort = 18748; + # commandcodeProxyPort (18748) and claudeCodeProxyPort (18749) + # retired 2026-11-06 (Drew, proxy-infra decommission): both + # providers were repointed to the fork's native wire-emulation + # providers on 2026-11-05 (code#6117, opencode#1749), so the CLI + # proxies had no consumers left; their lets, units, session + # variables, bin programs and guard rows were removed in one + # change. Both ports are free. # opencodeRouteProxyPort (18750) retired 2026-11-04 # (opencode#1153): OpenClaw repointed to the server facade # (127.0.0.1:13420/v1); the port is free. - claudeCodeProxyPort = 18749; # antigravityDirectProxyPort (18751) retired 2026-11-04 (opencode#1414): # the in-fork native provider replaced the door; the port is free. # Atlas search service port (code#5350 step 5, #5355): the fleet @@ -76,7 +81,8 @@ let # Vendored from nixpkgs master; see the header in that file for why. Provides # `agy_acp_server`, which t3code's AcpRegistryDriver can drive. antigravity-acp = pkgs.callPackage ../../pkgs/antigravity-acp { }; - # The hub build ships the language_server binary the LS proxy drives. Same + # The hub build ships the language_server binary the retired + # (2026-10-30) antigravity-ls proxy drove. Same # derivation as the system one, so the store path is shared, not rebuilt. antigravity-hub = pkgs.callPackage ../../pkgs/antigravity-hub { }; # 2.1.293; nixpkgs is on 2.1.234. Must match the system `claude` so t3's @@ -740,12 +746,14 @@ in # both replaced by antigravity-direct (above codex-proxy), which speaks # the CLI's wire protocol with no spawned processes. The definitions # are removed, not commented out, so the switch stops the services and - # they stay off; bin/antigravity-ls-proxy.mjs and bin/agy-proxy.mjs - # remain in the repo as history, uninvoked, and the matching opencode - # providers sit in disabled_providers. To undo: restore the two unit - # blocks and the agyProxyPort/antigravityLsProxyPort lets from git - # history, drop the session-variable removals below, and re-point the - # plan seats in opencode.jsonc back from antigravity-direct. + # they stay off. bin/antigravity-ls-proxy.mjs and bin/agy-proxy.mjs + # remained in the repo as history until the 2026-11-06 proxy-infra + # decommission removed them; the matching opencode providers sit in + # disabled_providers. To undo: restore the two unit blocks, the two + # bin programs and the agyProxyPort/antigravityLsProxyPort lets from + # git history, drop the session-variable removals below, and + # re-point the plan seats in opencode.jsonc back from + # antigravity-direct. # Design Code proxy removed (2026-11-03, Drew): its unit definition # stood here. Drew removed the design persona routes and the whole @@ -754,9 +762,10 @@ in # removed from opencode.jsonc in the same pass, and the opendesign # provider/pool (a different thing, kept) never used this door. The # definition is removed, not commented out, so the switch stops the - # service and it stays off; bin/design-code-proxy.mjs remains in the - # repo as history, uninvoked, and its port let and session variable - # are removed with it. To undo: restore this unit block, the + # service and it stays off. bin/design-code-proxy.mjs remained in + # the repo as history until the 2026-11-06 proxy-infra decommission + # removed it; its port let and session variable were removed with + # the unit. To undo: restore this unit block, the bin program, the # designCodeProxyPort let, and the DESIGN_CODE_PROXY_PORT session # variable from git history, and re-add the config-side machinery. @@ -774,97 +783,29 @@ in # reproduced: a switch that changes a unit's ExecStart restarts that # proxy, per the normal flake service pattern (cf. mcpx/openchamber). - # CLI proxy workroots (muse / commandcode / claude-code): the three - # units below point their *_PROXY_WORKDIR overrides at per-proxy - # subtrees of the state dir ~/.local/state/cli-proxies - # (cli-proxies/commandcode, cli-proxies/claude-code, - # cli-proxies/muse), so runtime session state (warm-session maps, - # per-conversation workdirs) lives outside the checkout. The - # scripts' default (bin/work inside ~/code) dirtied the primary - # checkout with every session and blocked pm-git-sync. The subtrees - # are per-proxy (#2785): commandcode and claude-code derive identical - # sessions/ workdirs for overlapping keys, and - # muse uses its workroot as the session cwd/workspaceRoot, so one - # shared root let the proxies mutate each other's session state. - # Only the workroots moved: pre-#2785 state under the shared root is - # left in place (unattributable between the proxies by construction) - # and each proxy re-warms fresh state in its own subtree. + # CLI proxy workroot (muse): the muse unit below points its + # MUSE_PROXY_WORKDIR override at ~/.local/state/cli-proxies/muse, + # so runtime session state lives outside the checkout (the script's + # default, bin/work inside ~/code, dirtied the primary checkout + # with every session and blocked pm-git-sync). The commandcode and + # claude-code units that shared the cli-proxies root (#2785, #3067) + # are retired below; their state subtrees are left in place. # - # The commandcode + claude-code units additionally pin their shared - # key->session map via *_PROXY_SESSION_FILE to - # ~/.local/state/cli-proxies/sessions.json (#3067): that map was - # anchored to the scripts' own directory (bin/sessions.json) rather - # than the workroot, so the #2782 move missed it and the primary - # checkout kept dirtying. Both units MUST name the same file -- the - # two proxies share one map (mirrored key space). - - # Command Code CLI Local Proxy Bridge for OpenCode (Go plan: the hosted - # Provider API rejects the Go plan, so OpenCode talks to the CLI via - # this OpenAI-compatible bridge on 18748, same pattern as codex-proxy). - # Runs the repo checkout's start script -- the same invocation the - # proxy-supervisor used for its transient fps-commandcode-proxy unit -- - # so laptop/sandbox env handling and the MAX_TURNS pins live in exactly - # one place: bin/commandcode-proxy-start.sh. (The checkout path also - # avoids the stale-store ExecStart failure of #883.) + # Command Code proxy retired 2026-11-06 (Drew, proxy-infra + # decommission): its unit definition stood here. The provider was + # repointed to the fork's native wire-emulation provider on + # 2026-11-05 (code#6117, opencode#1749), so the :18748 CLI bridge + # had no consumers left; its let, unit, session variable, + # bin/commandcode-proxy.mjs, its start script and its test were + # removed in the same change. The port is free. # - # History: this unit originally landed (169d594e) WITH an - # Install.WantedBy while the supervisor owned the port, and the first - # activation including it (2026-10-26) crash-looped it against the - # supervisor's instance (44 restarts). That fight was a two-owners - # problem; #2104 removes the supervisor, so WantedBy is now correct. - systemd.user.services.commandcode-proxy = { - Unit = { - Description = "Command Code CLI Local Proxy Bridge for OpenCode"; - After = [ "network-online.target" ]; - Wants = [ "network-online.target" ]; - }; - Service = { - ExecStart = toString ( - pkgs.writeShellScript "commandcode-proxy-start-unit" '' - exec /run/current-system/sw/bin/bash "$HOME/code/bin/commandcode-proxy-start.sh" - '' - ); - Restart = "always"; - RestartSec = 3; - Environment = [ - "COMMANDCODE_PROXY_PORT=${toString commandcodeProxyPort}" - "COMMANDCODE_PROXY_HOST=127.0.0.1" - "COMMANDCODE_PROXY_WORKDIR=%h/.local/state/cli-proxies/commandcode" - "COMMANDCODE_PROXY_SESSION_FILE=%h/.local/state/cli-proxies/sessions.json" - "COMMANDCODE_PROXY_MAX_TURNS=1" - "COMMANDCODE_PROXY_AGENCY_MAX_TURNS=8" - ]; - }; - Install.WantedBy = [ "default.target" ]; - }; - - # Muse proxy (#2104): previously supervisor-config only, with no - # declarative unit at all. Entry point mirrors the supervisor's - # invocation of bin/claude-code-proxy.mjs (the codex-proxy shape). - systemd.user.services.claude-code-proxy = { - Unit = { - Description = "Claude Code CLI Local Proxy Bridge for OpenCode"; - After = [ "network-online.target" ]; - Wants = [ "network-online.target" ]; - }; - Service = { - ExecStart = toString ( - pkgs.writeShellScript "claude-code-proxy-start" '' - export PATH="/run/current-system/sw/bin:$HOME/.local/bin:$PATH" - exec /run/current-system/sw/bin/node "$HOME/code/bin/claude-code-proxy.mjs" - '' - ); - Restart = "always"; - RestartSec = 3; - Environment = [ - "CLAUDE_CODE_PROXY_PORT=${toString claudeCodeProxyPort}" - "CLAUDE_CODE_PROXY_HOST=127.0.0.1" - "CLAUDE_CODE_PROXY_WORKDIR=%h/.local/state/cli-proxies/claude-code" - "CLAUDE_CODE_PROXY_SESSION_FILE=%h/.local/state/cli-proxies/sessions.json" - ]; - }; - Install.WantedBy = [ "default.target" ]; - }; + # Claude Code proxy retired 2026-11-06 (Drew, proxy-infra + # decommission): its unit definition stood here. Same story: the + # provider was repointed to the fork's native wire-emulation + # provider on 2026-11-05 (code#6117, opencode#1749) and re-enabled + # as a native provider on 2026-11-06; the :18749 CLI bridge's let, + # unit, session variable, bin/claude-code-proxy.mjs and its test + # were removed in the same change. The port is free. # Muse (Meta) proxy (#2104): also previously supervisor-config only. # Runs the checkout start script, the supervisor's exact invocation; @@ -1708,13 +1649,14 @@ in # Single source for the local proxy ports (see the let block): # opencode.jsonc reads them via {env:...} substitution. CODEX_PROXY_PORT = toString codexProxyPort; - # The three below were missing: their {env:...} templates in - # opencode.jsonc resolved to an empty port in the OpenChamber serve + # MUSE_PROXY_PORT below was one of three missing session + # variables whose {env:...} templates in opencode.jsonc + # resolved to an empty port in the OpenChamber serve # (2026-10-25 audit) because the variables never reached its - # environment. The session list must cover every let-block port. + # environment; the other two (commandcode, claude-code) were + # removed with their retired proxies on 2026-11-06. The session + # list must cover every let-block port. MUSE_PROXY_PORT = toString museProxyPort; - COMMANDCODE_PROXY_PORT = toString commandcodeProxyPort; - CLAUDE_CODE_PROXY_PORT = toString claudeCodeProxyPort; OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT = "1"; # File watcher off by default (Drew, 2026-10-20): the working trees # are giant, and watching costs more than the live-external-edit @@ -1762,9 +1704,10 @@ in # `atlas-search` (the Python CLI is kept as atlas-search-py). atlasSearch # No "agy-proxy" / "antigravity-ls-proxy" launchers here: both - # doors were retired 2026-10-30 and their units removed above. - # The .mjs files remain in bin/ as history, uninvoked — a PATH - # launcher would resurrect a retired door on its canonical port. + # doors were retired 2026-10-30, their units removed above, and + # their .mjs files removed in the 2026-11-06 proxy-infra + # decommission — a PATH launcher would resurrect a retired door + # on its canonical port. (pkgs.writeShellScriptBin "codex-proxy" '' export PATH="/run/current-system/sw/bin:$HOME/.local/bin:$PATH" exec ${pkgs.nodejs}/bin/node ${../../bin}/codex-proxy.mjs "$@" diff --git a/home/openclaw/README.md b/home/openclaw/README.md index 1a5e09c320..fd854f3d86 100644 --- a/home/openclaw/README.md +++ b/home/openclaw/README.md @@ -17,11 +17,16 @@ source in the fleet next to Muse (Archer) and Aster (Dot). It is installed - **Workspace/knowledge pack:** `workspace/*.md` here, materialized into `~/.openclaw/workspace/` (AGENTS/SOUL/TOOLS/IDENTITY/USER/HEARTBEAT are the bootstrap files; FLEET/QUOTAS/CHANNELS are reference files). -- **Models:** local plan proxies only — primary DeepSeek V4 Flash via the - CommandCode proxy (:18748), fallbacks on the Design (:18746) and - Antigravity (:18743) plans. The Codex/OpenAI proxy (:18744) is the final - reserve and is deliberately not an automatic fallback. See - `workspace/QUOTAS.md`. +- **Models:** the OpenCode server facade (127.0.0.1:13420) is this + gateway's only model route: the default is the opencode-route + workhorse pool, with the specialist and speed pools as fallbacks. + The local plan proxies this gateway once fronted directly are + retired — CommandCode (:18748) and Claude Code (:18749) in the + 2026-11-06 proxy-infra decommission (both providers are native in + the fork since 2026-11-05), Design (:18746) on 2026-11-03 and + Antigravity (:18743) on 2026-10-30. The Codex/OpenAI proxy + (:18744) is the final reserve and is deliberately not an automatic + fallback. See `workspace/QUOTAS.md`. - **Coding:** ACP via the acpx plugin. The default ACP agent is `opencode` (spawn with cwd `~/code`) — the same OpenCode build/config/auth OpenChamber drives; `~/.acpx/config.json` (managed in diff --git a/home/openclaw/default.nix b/home/openclaw/default.nix index e049ed971a..021858e3ff 100644 --- a/home/openclaw/default.nix +++ b/home/openclaw/default.nix @@ -24,7 +24,7 @@ let homeDir = "/home/user"; # Local provider-proxy ports. The canonical definitions live in - # home/common/default.nix (clefProxyPort..claudeCodeProxyPort); these are + # home/common/default.nix (codexProxyPort..museProxyPort); these are # the same numbers, repeated here because OpenClaw's config is rendered # as data, not shell env. Keep in sync with home/common. # The opencode-route provider talks to the OpenCode server facade @@ -71,12 +71,13 @@ in # since the route proxy retired (opencode#1153, 2026-11-04); it is # ordered After it but does not Want it (the server has its own # enablement; the ExecStartPre below waits for its service record). - # The per-CLI proxies are owned by the proxy-supervisor (transient - # fps-* units on the canonical ports), so the gateway must not Want - # the manual per-proxy units: a gateway restart would re-pull them, - # and the manual commandcode-proxy unit crash-loops on its - # already-taken port (#883). Only mcpx and the embedding server are - # Wanted. + # The gateway must not Want the per-proxy units: a gateway restart + # would re-pull them (the manual commandcode-proxy unit once + # crash-looped on its already-taken port, #883, in the retired + # proxy-supervisor era). The commandcode-proxy and agy-proxy units + # themselves are gone — commandcode in the 2026-11-06 proxy-infra + # decommission, agy on 2026-10-30 — so their After entries below + # are gone too. Only mcpx and the embedding server are Wanted. # Stable local embedding endpoint for memory-lancedb (#1300 phase 1): # a dedicated llama-server on a FIXED loopback port, reusing the # llama.cpp build and the Qwen3-Embedding-0.6B GGUF that OpenCode's @@ -102,8 +103,6 @@ in Unit = { After = [ "openclaw-embedding.service" - "commandcode-proxy.service" - "agy-proxy.service" "codex-proxy.service" "mcpx.service" "opencode.service" @@ -332,7 +331,7 @@ in # Laptop operations - Everything is a systemd **user** service (linger on): `systemctl --user status|restart `, logs via `journalctl --user -u `. - - Provider proxies on loopback: clef 18742, agy 18743, codex 18744, antigravity-ls 18745, muse 18747, commandcode 18748, claude-code 18749; the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). + - Provider proxies on loopback: codex 18744, muse 18747 (the clef, agy, antigravity-ls, design-code, commandcode and claude-code doors are all retired — the last two in the 2026-11-06 proxy-infra decommission); the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). - OpenChamber's managed OpenCode port is dynamic — read `~/.config/openchamber/managed-opencode/state.json`, never hardcode it. - Secrets are referenced by name only (Bitwarden Secrets Manager; sops files under /run/secrets/agent-auth/). Never print or commit a secret value. diff --git a/home/openclaw/workspace/QUOTAS.md b/home/openclaw/workspace/QUOTAS.md index c57ac8a415..39e08adc58 100644 --- a/home/openclaw/workspace/QUOTAS.md +++ b/home/openclaw/workspace/QUOTAS.md @@ -3,7 +3,7 @@ Drew's rule, verbatim in spirit: **"Use the plans. Measure the quotas."** 1. **Plans only, never funds.** Every model call must ride a subscription plan. PAYG balances (e.g. a raw DeepSeek API balance, OpenAI API billing, Zen funds) are emergency reserves Drew controls — an agent never falls back to them. A 402/quota error is a wall: at most ONE retry on the same pool, then rotate pools or stop and report. -2. **Burn by expiry.** Prefer the pool whose window expires soonest. **OpenAI is the final reserve** — do not drain it while other pools have capacity. (This is why this gateway's default is DeepSeek Flash on the CommandCode plan, with the Design-plan DeepSeek as fallback, and the Codex/OpenAI proxy is registered but _not_ in the fallback chain.) +2. **Burn by expiry.** Prefer the pool whose window expires soonest. **OpenAI is the final reserve** — do not drain it while other pools have capacity. (This gateway's default is the opencode-route workhorse pool via the OpenCode server facade; the CommandCode-plan and Design-plan proxies it once fronted directly are retired — Design on 2026-11-03, CommandCode in the 2026-11-06 proxy-infra decommission — and the Codex/OpenAI proxy is registered but _not_ in the fallback chain.) 3. **Measure before and during.** Before starting heavy work on a pool, check its quota if a checker exists (OpenChamber's quota view / the provider registry in the keep-the-four-repos-healthy goal files). Pools are used all the way to 100% (the old ~85% caution zone is retired, Drew 2026-10-27). At a known 100% the pool is closed — no new work, no continued calls — until its reset time, or until a fresh check shows it has dropped below 100% (some providers reset early). 4. **Model + effort is one decision, per task.** Defaults: DeepSeek Flash (high effort) for routine work; Haiku/Sonnet-class for standard Claude work; Luna-class at max effort for cheap OpenAI-side work; flagship models (Sol/Opus-class) right-sized at medium, only for genuinely hard problems. Never leave model or effort at "default" by accident. 5. **One Meta pool, one door.** The Meta High Usage plan is reached through the fleet's `meta` provider route (muse-proxy, :18747). It is a plan pool like the others — not "Muse's subscription" (that's Drew's separate assistant product and not a pool at all). This gateway does not use it by default; OpenCode sessions route to it under their own discipline. diff --git a/home/openclaw/workspace/TOOLS.md b/home/openclaw/workspace/TOOLS.md index bf951f0c32..ecaa39c5b7 100644 --- a/home/openclaw/workspace/TOOLS.md +++ b/home/openclaw/workspace/TOOLS.md @@ -9,14 +9,8 @@ This file is managed by Nix (source: `home/openclaw/` in the developing-today/co | `openclaw-gateway` | This gateway | tailnet, port 18789 (Control UI + WebChat) | | `openchamber` | OpenChamber server (GUI over OpenCode) | 127.0.0.1:3000, socket-activated | | `mcpx` | Standing MCP gateway daemon | config `~/.config/mcpx/config.json` | -| `clef-proxy` | Provider proxy | 127.0.0.1:18742 | -| `agy-proxy` | Antigravity proxy (Gemini/Claude models) | 127.0.0.1:18743 | | `codex-proxy` | ChatGPT/Codex plan proxy (OpenAI — final reserve) | 127.0.0.1:18744 | -| `antigravity-ls-proxy` | Antigravity language-server proxy | 127.0.0.1:18745 | -| `design-code-proxy` | Open Design AMR plan proxy (DeepSeek/Haiku/Luna/GLM) | 127.0.0.1:18746 | | `muse-proxy` | Meta High Usage plan proxy | 127.0.0.1:18747 | -| `commandcode-proxy` | CommandCode plan proxy (DeepSeek/Kimi/GLM/Qwen) | 127.0.0.1:18748 | -| `claude-code-proxy` | Claude Code proxy | 127.0.0.1:18749 | - Check one: `systemctl --user status ` · logs: `journalctl --user -u -f` - OpenCode (the engine under OpenChamber) keeps its live managed-server port in `~/.config/openchamber/managed-opencode/state.json` — it changes on restart; never hardcode it. diff --git a/node-net-defaults.mjs b/node-net-defaults.mjs deleted file mode 100644 index 5be67d47ba..0000000000 --- a/node-net-defaults.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// node-net-defaults.mjs - per-process Node network defaults, loaded via -// NODE_OPTIONS=--import by commandcode-proxy-start.sh (laptop only). -// -// Why: this LAN's IPv6 is ULA-only with no upstream - the router advertises -// fd2e:2810:acf5::/48 plus a default route but answers -// Destination-unreachable for global IPv6 (tracepath !N at hop 1, router -// NDP entry FAILED). Node 24's global fetch (undici) with the default -// autoSelectFamily=true times out against it (ETIMEDOUT, all hosts), while -// plain net.connect / https.get succeed. Turning autoSelectFamily OFF makes -// undici use plain sequential connects in getaddrinfo order (IPv4 first on -// this host), which work. -// Scope: only Node processes whose env carries this NODE_OPTIONS - i.e. the -// commandcode-proxy tree (proxy + ACP CLI children, which inherit env). -// Undo: remove the NODE_OPTIONS export from commandcode-proxy-start.sh. -import net from 'node:net'; - -try { - net.setDefaultAutoSelectFamily(false); -} catch { - // Node without this API: leave defaults untouched. -} diff --git a/pm-stack/PORTS.md b/pm-stack/PORTS.md index 541436018a..3e5bdd72d6 100644 --- a/pm-stack/PORTS.md +++ b/pm-stack/PORTS.md @@ -90,8 +90,8 @@ pattern at its atlas-search block). | 18745 | antigravity-ls-proxy | loopback | retired 2026-10-30 | retired — **stale `tailscale serve` forward still present** | | 18746 | design-code-proxy | loopback | retired 2026-11-03 (`home/common/default.nix` comment block) | retired — **stale `tailscale serve` forward still present** | | 18747 | muse-proxy | loopback | `home/common/default.nix:21` (`museProxyPort`) | live | -| 18748 | commandcode-proxy | loopback | `home/common/default.nix:22` (`commandcodeProxyPort`) | live | -| 18749 | claude-code-proxy | loopback | `home/common/default.nix:26` (`claudeCodeProxyPort`) | live | +| 18748 | commandcode-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free | +| 18749 | claude-code-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free | | 18750 | opencode-route-proxy | loopback | retired 2026-11-04 | retired — free | | 18751 | antigravity-direct proxy | loopback | retired 2026-11-04 | retired — free | | 18760 | atlas-search service | loopback + tailnet via serve | `home/common/default.nix:39` (`atlasSearchPort`); `pkgs/atlas-search/crates/atlas-search/src/server.rs:285` | live |