| 1 | #!/usr/bin/env node |
| 2 | // ── Agent Host Relay ───────────────────────────────────────────────────────── |
| 3 | // Runs on the Mac HOST (outside Docker) so claude can authenticate via |
| 4 | // the macOS Keychain / OAuth subscription. |
| 5 | // |
| 6 | // The console container hits http://host.docker.internal:3201/run to launch |
| 7 | // a claude agent with full Mac auth, and events are POSTed back to the |
| 8 | // console's activity API. |
| 9 | // |
| 10 | // Usage (from the work2026/agent-manager directory): |
| 11 | // node scripts/host-relay.js |
| 12 | // |
| 13 | // Or start automatically via the start.sh wrapper. |
| 14 | // ───────────────────────────────────────────────────────────────────────────── |
| 15 | |
| 16 | const http = require('http'); |
| 17 | const https = require('https'); |
| 18 | const { spawn } = require('child_process'); |
| 19 | const path = require('path'); |
| 20 | const url = require('url'); |
| 21 | |
| 22 | const PORT = parseInt(process.env.RELAY_PORT || '3201', 10); |
| 23 | const CLAUDE_BIN = process.env.CLAUDE_BIN || '/Users/kikocisneros/.local/bin/claude'; |
| 24 | const CONSOLE_URL = process.env.CONSOLE_URL || 'http://localhost:3100'; |
| 25 | const AUTH_TOKEN = process.env.RELAY_TOKEN || ''; // optional bearer token for relay itself |
| 26 | const INTERNAL_API_KEY = process.env.INTERNAL_API_KEY || 'relay-internal-2026'; // must match console |
| 27 | const LOCAL_MLX_URL = process.env.LOCAL_MLX_URL || 'http://localhost:8000'; |
| 28 | const LOCAL_MLX_URL_B = process.env.LOCAL_MLX_URL_B || 'http://localhost:8001'; |
| 29 | const LITELLM_URL = process.env.LITELLM_URL || 'http://localhost:4000'; |
| 30 | |
| 31 | // ── Auto-recovery config ────────────────────────────────────────────────────── |
| 32 | const SESSION_TIMEOUT_MS = parseInt(process.env.SESSION_TIMEOUT_MS || '600000', 10); // 10 min |
| 33 | const CIRCUIT_BREAKER_THRESHOLD = parseInt(process.env.CIRCUIT_BREAKER_THRESHOLD || '5', 10); // 5 consecutive failures |
| 34 | const CIRCUIT_BREAKER_RESET_MS = parseInt(process.env.CIRCUIT_BREAKER_RESET_MS || '300000', 10); // 5 min |
| 35 | const WATCHDOG_INTERVAL_MS = parseInt(process.env.WATCHDOG_INTERVAL_MS || '60000', 10); // 1 min |
| 36 | const BINARY_CHECK_INTERVAL_MS = parseInt(process.env.BINARY_CHECK_INTERVAL_MS || '120000', 10); // 2 min |
| 37 | |
| 38 | // ── Relay state ─────────────────────────────────────────────────────────────── |
| 39 | let claudeAvailable = true; // false when binary check fails |
| 40 | let circuitOpen = false; // true after N consecutive spawn failures |
| 41 | let circuitOpenAt = 0; // timestamp when circuit opened |
| 42 | let consecutiveFailures = 0; // circuit breaker counter |
| 43 | |
| 44 | const active = new Map(); // sessionId → { proc, stdin, startedAt, lastActivity } |
| 45 | |
| 46 | // ── MLX health check (GET /v1/models) ──────────────────────────────────────── |
| 47 | async function checkMlx(baseUrl) { |
| 48 | const modelsUrl = baseUrl.replace(/\/v1\/?$/, '') + '/v1/models'; |
| 49 | try { |
| 50 | const r = await fetch(modelsUrl, { signal: AbortSignal.timeout(5000) }); |
| 51 | if (!r.ok) return { ok: false, url: modelsUrl, status: r.status }; |
| 52 | const data = await r.json(); |
| 53 | const models = (data.data || []).map(m => m.id || m.model_name).filter(Boolean); |
| 54 | return { ok: true, url: modelsUrl, models }; |
| 55 | } catch (e) { |
| 56 | return { ok: false, url: modelsUrl, error: e.message }; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // ── DNS check for .kikocis.test ─────────────────────────────────────────────── |
| 61 | function checkDns(hostname) { |
| 62 | const dns = require('dns'); |
| 63 | return new Promise(resolve => { |
| 64 | dns.lookup(hostname, (err, addr) => |
| 65 | err ? resolve({ ok: false, error: err.message }) : resolve({ ok: true, addr }) |
| 66 | ); |
| 67 | }); |
| 68 | } |
| 69 | |
| 70 | // ── Claude binary check ─────────────────────────────────────────────────────── |
| 71 | function checkClaudeBinary() { |
| 72 | const { execFile } = require('child_process'); |
| 73 | execFile(CLAUDE_BIN, ['--version'], { timeout: 8000 }, (err, stdout) => { |
| 74 | if (err) { |
| 75 | if (claudeAvailable) { |
| 76 | console.error(`[relay] ⚠ claude binary unavailable: ${err.message}`); |
| 77 | claudeAvailable = false; |
| 78 | } |
| 79 | } else { |
| 80 | if (!claudeAvailable) { |
| 81 | console.log(`[relay] ✓ claude binary restored: ${stdout.trim()}`); |
| 82 | claudeAvailable = true; |
| 83 | } |
| 84 | } |
| 85 | }); |
| 86 | } |
| 87 | |
| 88 | // ── Circuit breaker helpers ─────────────────────────────────────────────────── |
| 89 | function recordSpawnFailure() { |
| 90 | consecutiveFailures++; |
| 91 | if (!circuitOpen && consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) { |
| 92 | circuitOpen = true; |
| 93 | circuitOpenAt = Date.now(); |
| 94 | console.error(`[relay] ⚡ Circuit breaker OPEN after ${consecutiveFailures} consecutive failures — pausing spawns for ${CIRCUIT_BREAKER_RESET_MS / 60000}min`); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | function recordSpawnSuccess() { |
| 99 | if (consecutiveFailures > 0) { |
| 100 | console.log(`[relay] ✓ Spawn success — resetting failure counter (was ${consecutiveFailures})`); |
| 101 | } |
| 102 | consecutiveFailures = 0; |
| 103 | circuitOpen = false; |
| 104 | } |
| 105 | |
| 106 | function isCircuitOpen() { |
| 107 | if (!circuitOpen) return false; |
| 108 | if (Date.now() - circuitOpenAt >= CIRCUIT_BREAKER_RESET_MS) { |
| 109 | console.log(`[relay] ⚡ Circuit breaker HALF-OPEN — allowing test spawn`); |
| 110 | circuitOpen = false; // half-open: allow one attempt |
| 111 | return false; |
| 112 | } |
| 113 | return true; |
| 114 | } |
| 115 | |
| 116 | // ── Session watchdog ────────────────────────────────────────────────────────── |
| 117 | // Runs every WATCHDOG_INTERVAL_MS — kills stale sessions and cleans up zombies |
| 118 | function runWatchdog() { |
| 119 | const now = Date.now(); |
| 120 | for (const [sid, entry] of active.entries()) { |
| 121 | const { proc, startedAt, lastActivity } = entry; |
| 122 | |
| 123 | // Zombie check: process already exited but wasn't cleaned up |
| 124 | if (proc.exitCode !== null || proc.killed) { |
| 125 | console.warn(`[relay] watchdog: cleaning up zombie session ${sid} (exitCode=${proc.exitCode})`); |
| 126 | active.delete(sid); |
| 127 | post(`${CONSOLE_URL}/api/activity/sessions/${sid}/events`, { |
| 128 | type: 'session_error', code: proc.exitCode || 1, error: 'Session zombie — cleaned up by watchdog', |
| 129 | }).catch(() => {}); |
| 130 | continue; |
| 131 | } |
| 132 | |
| 133 | // Timeout check: session has been running too long with no recent activity |
| 134 | const idleMs = now - (lastActivity || startedAt); |
| 135 | const totalMs = now - startedAt; |
| 136 | if (totalMs > SESSION_TIMEOUT_MS) { |
| 137 | console.warn(`[relay] watchdog: session ${sid} timed out after ${Math.round(totalMs / 60000)}min — killing`); |
| 138 | try { proc.kill('SIGTERM'); } catch {} |
| 139 | setTimeout(() => { try { if (!proc.killed) proc.kill('SIGKILL'); } catch {} }, 5000); |
| 140 | active.delete(sid); |
| 141 | post(`${CONSOLE_URL}/api/activity/sessions/${sid}/events`, { |
| 142 | type: 'session_error', code: 1, error: `Session timed out after ${Math.round(totalMs / 60000)}min`, |
| 143 | }).catch(() => {}); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // ── helpers ────────────────────────────────────────────────────────────────── |
| 149 | function post(targetUrl, body) { |
| 150 | return new Promise((resolve, reject) => { |
| 151 | const parsed = url.parse(targetUrl); |
| 152 | const mod = parsed.protocol === 'https:' ? https : http; |
| 153 | const data = JSON.stringify(body); |
| 154 | const req = mod.request({ |
| 155 | hostname: parsed.hostname, |
| 156 | port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80), |
| 157 | path: parsed.path, |
| 158 | method: 'POST', |
| 159 | headers: { |
| 160 | 'Content-Type': 'application/json', |
| 161 | 'Content-Length': Buffer.byteLength(data), |
| 162 | 'x-internal-key': INTERNAL_API_KEY, |
| 163 | }, |
| 164 | }, res => { res.resume(); resolve(res.statusCode); }); |
| 165 | req.on('error', reject); |
| 166 | req.write(data); |
| 167 | req.end(); |
| 168 | }); |
| 169 | } |
| 170 | |
| 171 | function readBody(req) { |
| 172 | return new Promise((resolve, reject) => { |
| 173 | let buf = ''; |
| 174 | req.on('data', c => buf += c); |
| 175 | req.on('end', () => { |
| 176 | try { resolve(JSON.parse(buf)); } |
| 177 | catch (e) { reject(e); } |
| 178 | }); |
| 179 | req.on('error', reject); |
| 180 | }); |
| 181 | } |
| 182 | |
| 183 | // ── routes ─────────────────────────────────────────────────────────────────── |
| 184 | const server = http.createServer(async (req, res) => { |
| 185 | const { pathname } = url.parse(req.url); |
| 186 | |
| 187 | // Auth check |
| 188 | if (AUTH_TOKEN) { |
| 189 | const tok = (req.headers.authorization || '').replace('Bearer ', ''); |
| 190 | if (tok !== AUTH_TOKEN) { |
| 191 | res.writeHead(401); return res.end(JSON.stringify({ error: 'unauthorized' })); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | res.setHeader('Content-Type', 'application/json'); |
| 196 | |
| 197 | // ── GET /health ────────────────────────────────────────────────────────── |
| 198 | if (req.method === 'GET' && pathname === '/health') { |
| 199 | // Run all checks in parallel |
| 200 | const [mlxA, mlxB, dnsConsole, dnsLitellm] = await Promise.all([ |
| 201 | checkMlx(LOCAL_MLX_URL), |
| 202 | checkMlx(LOCAL_MLX_URL_B), |
| 203 | checkDns('console.kikocis.test'), |
| 204 | checkDns('litellm.kikocis.test'), |
| 205 | ]); |
| 206 | const degraded = !claudeAvailable || circuitOpen; |
| 207 | return res.end(JSON.stringify({ |
| 208 | ok: !degraded, |
| 209 | degraded, |
| 210 | relay: '1.1', |
| 211 | claude: CLAUDE_BIN, |
| 212 | claudeOk: claudeAvailable, |
| 213 | active: active.size, |
| 214 | circuit: { |
| 215 | open: circuitOpen, |
| 216 | consecutiveFailures, |
| 217 | openSince: circuitOpen ? new Date(circuitOpenAt).toISOString() : null, |
| 218 | resetInMs: circuitOpen ? Math.max(0, CIRCUIT_BREAKER_RESET_MS - (Date.now() - circuitOpenAt)) : 0, |
| 219 | }, |
| 220 | mlx: { |
| 221 | a: mlxA, |
| 222 | b: mlxB, |
| 223 | }, |
| 224 | dns: { |
| 225 | 'console.kikocis.test': dnsConsole, |
| 226 | 'litellm.kikocis.test': dnsLitellm, |
| 227 | }, |
| 228 | })); |
| 229 | } |
| 230 | |
| 231 | // ── POST /v1/chat/completions — OpenAI-compatible endpoint via Claude subscription ── |
| 232 | // LiteLLM calls this as the "claude-subscription" backend. It spawns the claude CLI |
| 233 | // WITHOUT ANTHROPIC_BASE_URL so it authenticates via macOS Keychain (OAuth subscription). |
| 234 | if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { |
| 235 | // Auth: accept INTERNAL_API_KEY or LITELLM_MASTER_KEY as bearer token |
| 236 | const authHdr = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, ''); |
| 237 | const xKey = req.headers['x-internal-key'] || ''; |
| 238 | const masterKey = process.env.LITELLM_MASTER_KEY || ''; |
| 239 | if (authHdr !== INTERNAL_API_KEY && xKey !== INTERNAL_API_KEY && |
| 240 | (masterKey && authHdr !== masterKey)) { |
| 241 | res.writeHead(401, { 'Content-Type': 'application/json' }); |
| 242 | return res.end(JSON.stringify({ error: { message: 'Unauthorized', type: 'auth_error', code: '401' } })); |
| 243 | } |
| 244 | |
| 245 | let body; |
| 246 | try { body = await readBody(req); } |
| 247 | catch { res.writeHead(400, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ error: { message: 'Invalid JSON' } })); } |
| 248 | |
| 249 | const messages = body.messages || []; |
| 250 | const doStream = body.stream || false; |
| 251 | const maxTokens = body.max_tokens || 8192; |
| 252 | |
| 253 | // Map LiteLLM model names → Claude model identifiers |
| 254 | const MODEL_MAP = { |
| 255 | 'claude-haiku-4-5': 'claude-haiku-4-5', |
| 256 | 'claude-sonnet-4-6': 'claude-sonnet-4-6', |
| 257 | 'claude-opus-4-5': 'claude-opus-4-5', |
| 258 | 'claude-primary': 'claude-sonnet-4-6', |
| 259 | 'council-security': 'claude-sonnet-4-6', |
| 260 | 'council-quality': 'claude-sonnet-4-6', |
| 261 | 'council-fixes': 'claude-sonnet-4-6', |
| 262 | 'chat-assistant': 'claude-haiku-4-5', |
| 263 | }; |
| 264 | const requestedModel = (body.model || 'claude-sonnet-4-6').replace(/^openai\//, ''); |
| 265 | const claudeModel = MODEL_MAP[requestedModel] || requestedModel; |
| 266 | |
| 267 | // Extract system prompt and build user prompt |
| 268 | const sysParts = messages.filter(m => m.role === 'system').map(m => |
| 269 | typeof m.content === 'string' ? m.content : (m.content || []).map(c => c.text || '').join('') |
| 270 | ); |
| 271 | const systemPrompt = sysParts.join('\n'); |
| 272 | |
| 273 | const nonSys = messages.filter(m => m.role !== 'system'); |
| 274 | if (nonSys.length === 0) { |
| 275 | res.writeHead(400, { 'Content-Type': 'application/json' }); |
| 276 | return res.end(JSON.stringify({ error: { message: 'No user messages provided' } })); |
| 277 | } |
| 278 | |
| 279 | let userPrompt; |
| 280 | if (nonSys.length === 1 && nonSys[0].role === 'user') { |
| 281 | const c = nonSys[0].content; |
| 282 | userPrompt = typeof c === 'string' ? c : (c || []).map(b => b.text || '').join(''); |
| 283 | } else { |
| 284 | // Multi-turn: format as dialogue, handling tool-call exchanges |
| 285 | userPrompt = nonSys.map(m => { |
| 286 | if (m.role === 'user') { |
| 287 | const c = m.content; |
| 288 | const text = typeof c === 'string' ? c : (c || []).map(b => b.text || '').join(''); |
| 289 | return `Human: ${text}`; |
| 290 | } |
| 291 | if (m.role === 'assistant') { |
| 292 | // May have tool_calls (no content) or content (plain response) |
| 293 | if (m.tool_calls?.length) { |
| 294 | const calls = m.tool_calls.map(tc => `${tc.function.name}(${tc.function.arguments})`).join(', '); |
| 295 | return `Assistant (called): ${calls}`; |
| 296 | } |
| 297 | const c = m.content; |
| 298 | const text = typeof c === 'string' ? c : (c || []).map(b => b.text || '').join(''); |
| 299 | return `Assistant: ${text}`; |
| 300 | } |
| 301 | if (m.role === 'tool') { |
| 302 | return `Tool result [${m.tool_call_id || 'call'}]: ${m.content}`; |
| 303 | } |
| 304 | return ''; |
| 305 | }).filter(Boolean).join('\n\n'); |
| 306 | // When tool-calling mode and the last message is a tool result, |
| 307 | // append a reminder so claude doesn't drift into plain text |
| 308 | if ((body.tools || []).length > 0 && nonSys.length > 1 && nonSys[nonSys.length - 1]?.role === 'tool') { |
| 309 | userPrompt += '\n\n[REMINDER: Respond ONLY with a JSON object {"function_calls": [...]}. No text outside the JSON.]'; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | const reqId = `relay-cmpl-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; |
| 314 | const created = Math.floor(Date.now() / 1000); |
| 315 | const startMs = Date.now(); |
| 316 | |
| 317 | // ── Prompt-based tool calling ───────────────────────────────────────────── |
| 318 | // The claude CLI doesn't support OpenAI tool_calls format. When tools are |
| 319 | // provided in the request (e.g. from the orchestrator), we inject them as |
| 320 | // text into the system prompt and ask claude to respond with JSON. |
| 321 | // The relay then parses the JSON and returns it as proper OpenAI tool_calls. |
| 322 | const requestedTools = body.tools || []; |
| 323 | const hasTools = requestedTools.length > 0; |
| 324 | |
| 325 | let effectiveSystemPrompt; |
| 326 | if (hasTools) { |
| 327 | const toolDescriptions = requestedTools.map(t => { |
| 328 | const fn = t.function; |
| 329 | return `- ${fn.name}: ${fn.description}`; |
| 330 | }).join('\n'); |
| 331 | |
| 332 | // Put the JSON constraint FIRST so it overrides the orchestrator's system prompt. |
| 333 | // Explicitly state that WebSearch/Bash do NOT exist to prevent claude from trying them. |
| 334 | effectiveSystemPrompt = |
| 335 | `CRITICAL: You are a JSON function-calling endpoint. You CANNOT use WebSearch, Bash, Task, or any built-in tools — they do not exist here. Attempting to use them will fail.\n\n` + |
| 336 | `To take actions, output ONLY a JSON object with the functions you want to call. The system executes them and calls you again with results.\n\n` + |
| 337 | `AVAILABLE FUNCTIONS (the ONLY ones you can use):\n${toolDescriptions}\n\n` + |
| 338 | `REQUIRED OUTPUT FORMAT — respond with ONLY this JSON, nothing else:\n` + |
| 339 | `{"function_calls": [{"name": "function_name", "arguments": {"key": "value"}}]}\n` + |
| 340 | `Multiple calls: {"function_calls": [{"name": "fn1", "arguments": {}}, {"name": "fn2", "arguments": {}}]}\n` + |
| 341 | `No calls needed: {"function_calls": []}\n\n` + |
| 342 | (systemPrompt || ''); |
| 343 | } else { |
| 344 | // Non-tool-calling: ask for plain text, prevent built-in tool use that wastes turns |
| 345 | const noToolsNote = '\n\nIMPORTANT: Respond with plain text only. Do NOT call WebSearch, Bash, or any other tools. Base your response on the information already provided.'; |
| 346 | effectiveSystemPrompt = systemPrompt ? systemPrompt + noToolsNote : noToolsNote.trim(); |
| 347 | } |
| 348 | |
| 349 | const cliArgs = [ |
| 350 | '--print', '--verbose', |
| 351 | '--output-format', doStream ? 'stream-json' : 'json', |
| 352 | '--model', claudeModel, |
| 353 | '--no-session-persistence', |
| 354 | '--dangerously-skip-permissions', // allow built-in tools to run within the 1 turn |
| 355 | '--max-turns', '1', // 1 turn: use tools if needed, then output JSON |
| 356 | ]; |
| 357 | cliArgs.push('--system-prompt', effectiveSystemPrompt); |
| 358 | cliArgs.push(userPrompt); |
| 359 | |
| 360 | // Run WITHOUT ANTHROPIC_BASE_URL → Claude uses real Anthropic (subscription) |
| 361 | // If no Anthropic API key is available, fall back to direct MLX call |
| 362 | const homeDir = process.env.HOME || '/Users/kikocisneros'; |
| 363 | const userName = homeDir.split('/').pop() || 'kikocisneros'; |
| 364 | |
| 365 | // ── Spawn Claude CLI — uses OAuth subscription if no API key, or API key if set ── |
| 366 | // Detect a REAL Anthropic API key (not the fake relay proxy key) |
| 367 | const rawKey = process.env.ANTHROPIC_API_KEY || ''; |
| 368 | const isFakeKey = !rawKey || rawKey === 'sk-ant-local-proxy' || rawKey.length < 20; |
| 369 | const anthropicKey = isFakeKey ? '' : rawKey; |
| 370 | // No API key → claude uses stored OAuth credentials (subscription) automatically |
| 371 | |
| 372 | // ── Spawn Claude CLI ────────────────────────────────────────────────────── |
| 373 | const claudeEnv = { |
| 374 | HOME: homeDir, USER: userName, LOGNAME: userName, |
| 375 | TMPDIR: process.env.TMPDIR || '/tmp', |
| 376 | TERM: process.env.TERM || 'xterm-256color', |
| 377 | LANG: process.env.LANG || 'en_US.UTF-8', |
| 378 | PATH: process.env.PATH || `/Users/${userName}/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin`, |
| 379 | XDG_CONFIG_HOME: `${homeDir}/.config`, |
| 380 | XDG_DATA_HOME: `${homeDir}/.local/share`, |
| 381 | ...process.env, |
| 382 | HOME: homeDir, |
| 383 | ...(anthropicKey ? { ANTHROPIC_API_KEY: anthropicKey } : {}), |
| 384 | }; |
| 385 | // Remove LiteLLM proxy override — use real Anthropic endpoint for subscription |
| 386 | delete claudeEnv.ANTHROPIC_BASE_URL; |
| 387 | delete claudeEnv.ANTHROPIC_AUTH_TOKEN; |
| 388 | |
| 389 | const promptSize = (systemPrompt.length + userPrompt.length); |
| 390 | console.log(`[relay] /v1/chat/completions model=${claudeModel} stream=${doStream} id=${reqId} prompt=${promptSize}chars`); |
| 391 | |
| 392 | let proc; |
| 393 | try { |
| 394 | proc = spawn(CLAUDE_BIN, cliArgs, { env: claudeEnv, stdio: ['pipe', 'pipe', 'pipe'] }); |
| 395 | } catch (err) { |
| 396 | res.writeHead(500, { 'Content-Type': 'application/json' }); |
| 397 | return res.end(JSON.stringify({ error: { message: `spawn failed: ${err.message}` } })); |
| 398 | } |
| 399 | proc.stdin.end(); // no stdin needed |
| 400 | |
| 401 | if (!doStream) { |
| 402 | // ── Non-streaming ──────────────────────────────────────────────────── |
| 403 | let stdout = '', stderr = ''; |
| 404 | // Declare BEFORE the close handler to avoid TDZ ReferenceError |
| 405 | let resultText = '', inputTok = 0, outputTok = 0; |
| 406 | // --output-format json emits a JSON array on stdout; stream-json emits NDJSON. |
| 407 | // Try JSON array first, then fall back to NDJSON line-by-line parsing. |
| 408 | const findResult = ev => { |
| 409 | // Capture last assistant text message (fallback if result.result is null) |
| 410 | if (ev.type === 'assistant' && ev.message?.content) { |
| 411 | const textBlocks = (ev.message.content || []).filter(b => b.type === 'text'); |
| 412 | if (textBlocks.length) resultText = textBlocks.map(b => b.text).join(''); |
| 413 | } |
| 414 | if (ev.type === 'result') { |
| 415 | if (ev.result) resultText = ev.result; // prefer result.result if present |
| 416 | inputTok = ev.usage?.input_tokens || inputTok; |
| 417 | outputTok = ev.usage?.output_tokens || outputTok; |
| 418 | } |
| 419 | }; |
| 420 | proc.stdout.on('data', d => stdout += d.toString()); |
| 421 | proc.stderr.on('data', d => stderr += d.toString()); |
| 422 | proc.on('close', code => { |
| 423 | const elapsed = ((Date.now() - startMs) / 1000).toFixed(2); |
| 424 | // Parse stdout — handles both JSON array (--output-format json) and NDJSON (stream-json) |
| 425 | try { |
| 426 | const parsed = JSON.parse(stdout.trim()); |
| 427 | if (Array.isArray(parsed)) parsed.forEach(findResult); |
| 428 | else findResult(parsed); |
| 429 | } catch { |
| 430 | for (const line of stdout.split('\n')) { |
| 431 | const t = line.trim(); if (!t) continue; |
| 432 | try { findResult(JSON.parse(t)); } catch {} |
| 433 | } |
| 434 | } |
| 435 | if (code !== 0 && !resultText) { |
| 436 | console.error(`[relay] completions failed code=${code} stderr="${stderr.slice(0, 300)}" stdout_tail="${stdout.slice(-500)}"`); |
| 437 | res.writeHead(500, { 'Content-Type': 'application/json' }); |
| 438 | return res.end(JSON.stringify({ error: { message: `Claude exited ${code}: ${stderr.slice(0, 200)}`, type: 'server_error', code: '500' } })); |
| 439 | } |
| 440 | if (code !== 0) { |
| 441 | console.log(`[relay] completions code=${code} but has result text — recovering id=${reqId}`); |
| 442 | } |
| 443 | if (!resultText) resultText = stdout.trim(); |
| 444 | // ── Tool-calling response: parse JSON function_calls → OpenAI tool_calls ── |
| 445 | if (hasTools && resultText) { |
| 446 | console.log(`[relay] tool-mode result preview: ${resultText.slice(0, 300).replace(/\n/g, '↵')}`); |
| 447 | try { |
| 448 | // Strip markdown code fences if present |
| 449 | const cleaned = resultText.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, ''); |
| 450 | const parsed = JSON.parse(cleaned); |
| 451 | if (parsed.function_calls !== undefined) { |
| 452 | const fcs = parsed.function_calls || []; |
| 453 | if (fcs.length > 0) { |
| 454 | const tool_calls = fcs.map((fc, i) => ({ |
| 455 | id: `call_${reqId}_${i}`, |
| 456 | type: 'function', |
| 457 | function: { name: fc.name, arguments: JSON.stringify(fc.arguments || {}) }, |
| 458 | })); |
| 459 | console.log(`[relay] completions tool_calls=[${fcs.map(f => f.name).join(',')}] id=${reqId} tokens=${inputTok}+${outputTok} elapsed=${elapsed}s`); |
| 460 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 461 | return res.end(JSON.stringify({ |
| 462 | id: reqId, object: 'chat.completion', created, model: claudeModel, |
| 463 | choices: [{ index: 0, message: { role: 'assistant', content: null, tool_calls }, finish_reason: 'tool_calls' }], |
| 464 | usage: { prompt_tokens: inputTok, completion_tokens: outputTok, total_tokens: inputTok + outputTok }, |
| 465 | })); |
| 466 | } else { |
| 467 | // Empty function_calls → model is done |
| 468 | console.log(`[relay] completions tool_calls=[] (done) id=${reqId} elapsed=${elapsed}s`); |
| 469 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 470 | return res.end(JSON.stringify({ |
| 471 | id: reqId, object: 'chat.completion', created, model: claudeModel, |
| 472 | choices: [{ index: 0, message: { role: 'assistant', content: null, tool_calls: [] }, finish_reason: 'stop' }], |
| 473 | usage: { prompt_tokens: inputTok, completion_tokens: outputTok, total_tokens: inputTok + outputTok }, |
| 474 | })); |
| 475 | } |
| 476 | } |
| 477 | } catch { /* not JSON — fall through to plain text response */ } |
| 478 | } |
| 479 | console.log(`[relay] completions done id=${reqId} tokens=${inputTok}+${outputTok} elapsed=${elapsed}s`); |
| 480 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 481 | res.end(JSON.stringify({ |
| 482 | id: reqId, object: 'chat.completion', created, model: claudeModel, |
| 483 | choices: [{ index: 0, message: { role: 'assistant', content: resultText }, finish_reason: 'stop' }], |
| 484 | usage: { prompt_tokens: inputTok, completion_tokens: outputTok, total_tokens: inputTok + outputTok }, |
| 485 | })); |
| 486 | }); |
| 487 | |
| 488 | } else { |
| 489 | // ── Streaming (SSE) ────────────────────────────────────────────────── |
| 490 | res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); |
| 491 | // Send role delta first |
| 492 | res.write(`data: ${JSON.stringify({ id: reqId, object: 'chat.completion.chunk', created, model: claudeModel, |
| 493 | choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }] })}\n\n`); |
| 494 | |
| 495 | let buf = '', lastLen = 0; |
| 496 | proc.stdout.on('data', chunk => { |
| 497 | buf += chunk.toString(); |
| 498 | const lines = buf.split('\n'); buf = lines.pop(); |
| 499 | for (const line of lines) { |
| 500 | const t = line.trim(); if (!t) continue; |
| 501 | try { |
| 502 | const ev = JSON.parse(t); |
| 503 | if (ev.type === 'assistant' && ev.message?.content) { |
| 504 | for (const blk of ev.message.content) { |
| 505 | if (blk.type === 'text') { |
| 506 | const delta = blk.text.slice(lastLen); |
| 507 | lastLen = blk.text.length; |
| 508 | if (delta) res.write(`data: ${JSON.stringify({ id: reqId, object: 'chat.completion.chunk', created, model: claudeModel, |
| 509 | choices: [{ index: 0, delta: { content: delta }, finish_reason: null }] })}\n\n`); |
| 510 | } |
| 511 | } |
| 512 | } |
| 513 | if (ev.type === 'result') { |
| 514 | res.write(`data: ${JSON.stringify({ id: reqId, object: 'chat.completion.chunk', created, model: claudeModel, |
| 515 | choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`); |
| 516 | res.write('data: [DONE]\n\n'); |
| 517 | } |
| 518 | } catch {} |
| 519 | } |
| 520 | }); |
| 521 | proc.on('close', code => { |
| 522 | const elapsed = ((Date.now() - startMs) / 1000).toFixed(2); |
| 523 | console.log(`[relay] completions stream done id=${reqId} code=${code} elapsed=${elapsed}s`); |
| 524 | if (!res.writableEnded) { res.write('data: [DONE]\n\n'); res.end(); } |
| 525 | }); |
| 526 | req.on('close', () => { if (!proc.killed) proc.kill('SIGTERM'); }); |
| 527 | } |
| 528 | return; |
| 529 | } |
| 530 | |
| 531 | // ── GET /pid/:pid — check if a process is still alive ──────────────────── |
| 532 | if (req.method === 'GET' && pathname.startsWith('/pid/')) { |
| 533 | const pid = parseInt(pathname.split('/pid/')[1], 10); |
| 534 | let alive = false; |
| 535 | try { process.kill(pid, 0); alive = true; } catch { alive = false; } |
| 536 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 537 | return res.end(JSON.stringify({ pid, alive })); |
| 538 | } |
| 539 | |
| 540 | // ── POST /run — launch a claude agent ──────────────────────────────────── |
| 541 | if (req.method === 'POST' && pathname === '/run') { |
| 542 | let job; |
| 543 | try { job = await readBody(req); } |
| 544 | catch { res.writeHead(400); return res.end(JSON.stringify({ error: 'bad json' })); } |
| 545 | |
| 546 | const { sessionId, task, workdir, model, args: prebuiltArgs } = job; |
| 547 | if (!sessionId || !task) { |
| 548 | res.writeHead(400); return res.end(JSON.stringify({ error: 'sessionId and task required' })); |
| 549 | } |
| 550 | |
| 551 | // ── Circuit breaker check ────────────────────────────────────────────── |
| 552 | if (isCircuitOpen()) { |
| 553 | const resetIn = Math.ceil((CIRCUIT_BREAKER_RESET_MS - (Date.now() - circuitOpenAt)) / 1000); |
| 554 | res.writeHead(503); |
| 555 | return res.end(JSON.stringify({ ok: false, error: `Circuit breaker open — relay paused. Resets in ${resetIn}s` })); |
| 556 | } |
| 557 | if (!claudeAvailable) { |
| 558 | res.writeHead(503); |
| 559 | return res.end(JSON.stringify({ ok: false, error: `Claude binary unavailable at ${CLAUDE_BIN}` })); |
| 560 | } |
| 561 | |
| 562 | const resolvedModel = model || 'claude-sonnet-4-6'; |
| 563 | const resolvedDir = workdir || process.cwd(); |
| 564 | // Always use the relay's own CONSOLE_URL — the callbackUrl from the container |
| 565 | // is an internal Docker DNS name (http://console:3100) not reachable from the host. |
| 566 | const callback = CONSOLE_URL; |
| 567 | |
| 568 | // Use pre-built args from agent-runner if provided (includes --dangerously-skip-permissions etc.) |
| 569 | // Otherwise fall back to minimal args |
| 570 | const args = (prebuiltArgs && prebuiltArgs.length > 0) ? prebuiltArgs : [ |
| 571 | '--output-format', 'stream-json', |
| 572 | '--verbose', |
| 573 | '--model', resolvedModel, |
| 574 | '-p', task, |
| 575 | ]; |
| 576 | |
| 577 | // Ensure workspace dir exists before spawning (cwd must exist or Node throws ENOENT) |
| 578 | require('fs').mkdirSync(resolvedDir, { recursive: true }); |
| 579 | |
| 580 | console.log(`[relay] Launching ${sessionId} model=${resolvedModel} dir=${resolvedDir} args=${args.slice(0,6).join(' ')}...`); |
| 581 | |
| 582 | let proc; |
| 583 | try { |
| 584 | // When running under launchd the environment is very sparse (only what's in the plist). |
| 585 | // Claude needs USER, LOGNAME, TMPDIR, etc. to authenticate and run properly. |
| 586 | // Build a complete env by combining launchd env with essential user vars. |
| 587 | const homeDir = process.env.HOME || `/Users/${process.env.USER || 'kikocisneros'}`; |
| 588 | const userName = homeDir.split('/').pop() || 'kikocisneros'; |
| 589 | const claudeEnv = { |
| 590 | // Essential user environment |
| 591 | HOME: homeDir, |
| 592 | USER: process.env.USER || userName, |
| 593 | LOGNAME: process.env.LOGNAME || userName, |
| 594 | TMPDIR: process.env.TMPDIR || '/tmp', |
| 595 | TERM: process.env.TERM || 'xterm-256color', |
| 596 | LANG: process.env.LANG || 'en_US.UTF-8', |
| 597 | // PATH that includes homebrew, local bin, standard bins |
| 598 | PATH: process.env.PATH || [ |
| 599 | `${homeDir}/.local/bin`, |
| 600 | '/opt/homebrew/bin', |
| 601 | '/opt/homebrew/sbin', |
| 602 | '/usr/local/bin', |
| 603 | '/usr/bin', |
| 604 | '/bin', |
| 605 | '/usr/sbin', |
| 606 | '/sbin', |
| 607 | ].join(':'), |
| 608 | // XDG dirs (some CLIs need these) |
| 609 | XDG_CONFIG_HOME: `${homeDir}/.config`, |
| 610 | XDG_DATA_HOME: `${homeDir}/.local/share`, |
| 611 | // Merge any extra vars from launchd (ANTHROPIC_API_KEY etc.) |
| 612 | ...process.env, |
| 613 | // Always override HOME to the correct value |
| 614 | HOME: homeDir, |
| 615 | }; |
| 616 | // Agents must use native Claude OAuth (macOS Keychain), NOT LiteLLM proxy. |
| 617 | // The LiteLLM port in the plist (4000) is the internal Docker port — not |
| 618 | // reachable from the host. Removing these vars lets Claude Code authenticate |
| 619 | // directly via the user's subscription stored in the Keychain. |
| 620 | delete claudeEnv.ANTHROPIC_BASE_URL; |
| 621 | delete claudeEnv.ANTHROPIC_AUTH_TOKEN; |
| 622 | delete claudeEnv.ANTHROPIC_API_KEY; |
| 623 | proc = spawn(CLAUDE_BIN, args, { |
| 624 | cwd: resolvedDir, |
| 625 | env: claudeEnv, |
| 626 | stdio: ['pipe', 'pipe', 'pipe'], // stdin piped so we can inject comments |
| 627 | }); |
| 628 | } catch (err) { |
| 629 | console.error(`[relay] spawn failed: ${err.message}`); |
| 630 | recordSpawnFailure(); |
| 631 | res.writeHead(500); |
| 632 | return res.end(JSON.stringify({ ok: false, error: err.message })); |
| 633 | } |
| 634 | |
| 635 | recordSpawnSuccess(); |
| 636 | const sessionEntry = { proc, stdin: proc.stdin, startedAt: Date.now(), lastActivity: Date.now() }; |
| 637 | active.set(sessionId, sessionEntry); |
| 638 | res.end(JSON.stringify({ ok: true, sessionId, pid: proc.pid })); |
| 639 | |
| 640 | // Stream stdout events back to the console |
| 641 | let buf = ''; |
| 642 | proc.stdout.on('data', async chunk => { |
| 643 | sessionEntry.lastActivity = Date.now(); // update for watchdog |
| 644 | buf += chunk.toString(); |
| 645 | const lines = buf.split('\n'); |
| 646 | buf = lines.pop(); // keep incomplete line |
| 647 | for (const line of lines) { |
| 648 | if (!line.trim()) continue; |
| 649 | try { |
| 650 | const event = JSON.parse(line); |
| 651 | await post(`${callback}/api/activity/sessions/${sessionId}/events`, event) |
| 652 | .catch(e => console.warn(`[relay] callback failed: ${e.message}`)); |
| 653 | } catch { /* non-JSON line, ignore */ } |
| 654 | } |
| 655 | }); |
| 656 | |
| 657 | proc.stderr.on('data', d => { |
| 658 | const msg = d.toString().trim(); |
| 659 | if (msg) console.warn(`[relay] stderr [${sessionId}]: ${msg}`); |
| 660 | }); |
| 661 | |
| 662 | // Prevent uncaught 'error' events from crashing the relay process |
| 663 | proc.on('error', async err => { |
| 664 | active.delete(sessionId); |
| 665 | recordSpawnFailure(); |
| 666 | console.error(`[relay] spawn error [${sessionId}]: ${err.message}`); |
| 667 | await post(`${callback}/api/activity/sessions/${sessionId}/events`, { |
| 668 | type: 'session_error', |
| 669 | code: 1, |
| 670 | error: `Spawn failed: ${err.message}`, |
| 671 | }).catch(() => {}); |
| 672 | }); |
| 673 | |
| 674 | proc.on('close', async code => { |
| 675 | active.delete(sessionId); |
| 676 | console.log(`[relay] ${sessionId} exited code=${code}`); |
| 677 | await post(`${callback}/api/activity/sessions/${sessionId}/events`, { |
| 678 | type: code === 0 ? 'session_end' : 'session_error', |
| 679 | code, |
| 680 | error: code !== 0 ? `Process exited with code ${code}` : undefined, |
| 681 | }).catch(() => {}); |
| 682 | }); |
| 683 | |
| 684 | return; |
| 685 | } |
| 686 | |
| 687 | // ── POST /inject/:sessionId — write a comment to running agent's stdin ──── |
| 688 | if (req.method === 'POST' && pathname.startsWith('/inject/')) { |
| 689 | const sid = pathname.slice('/inject/'.length); |
| 690 | const entry = active.get(sid); |
| 691 | if (!entry) { |
| 692 | res.writeHead(404); |
| 693 | return res.end(JSON.stringify({ ok: false, error: 'session not running' })); |
| 694 | } |
| 695 | let body; |
| 696 | try { body = await readBody(req); } catch { body = {}; } |
| 697 | const text = (body.text || '').trim(); |
| 698 | if (!text) { |
| 699 | return res.end(JSON.stringify({ ok: false, error: 'text required' })); |
| 700 | } |
| 701 | try { |
| 702 | // Write as a human message — Claude Code reads from stdin during interactive turns |
| 703 | entry.proc.stdin.write(`\n${text}\n`); |
| 704 | console.log(`[relay] Injected comment into ${sid}: ${text.slice(0, 60)}`); |
| 705 | return res.end(JSON.stringify({ ok: true, sid })); |
| 706 | } catch (e) { |
| 707 | return res.end(JSON.stringify({ ok: false, error: e.message })); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | // ── POST /stop/:sessionId — kill a running agent ────────────────────────── |
| 712 | if (req.method === 'POST' && pathname.startsWith('/stop/')) { |
| 713 | const sid = pathname.slice('/stop/'.length); |
| 714 | const entry = active.get(sid); |
| 715 | const proc = entry?.proc || entry; // support both old and new format |
| 716 | if (proc) { try { proc.kill(); } catch {} active.delete(sid); } |
| 717 | return res.end(JSON.stringify({ ok: true, killed: !!proc })); |
| 718 | } |
| 719 | |
| 720 | // ── GET /active — list running agents ───────────────────────────────────── |
| 721 | if (req.method === 'GET' && pathname === '/active') { |
| 722 | return res.end(JSON.stringify({ |
| 723 | active: [...active.keys()], |
| 724 | count: active.size, |
| 725 | })); |
| 726 | } |
| 727 | |
| 728 | // ── GET /rtk-status — check RTK installation on the host ────────────────── |
| 729 | if (req.method === 'GET' && pathname === '/rtk-status') { |
| 730 | const { execFile } = require('child_process'); |
| 731 | execFile('rtk', ['--version'], { timeout: 5000 }, (err, stdout) => { |
| 732 | if (err) { |
| 733 | return res.end(JSON.stringify({ |
| 734 | installed: false, |
| 735 | error: 'RTK no instalado — ejecuta: brew install rtk-ai/tap/rtk', |
| 736 | hint: 'https://github.com/rtk-ai/rtk', |
| 737 | })); |
| 738 | } |
| 739 | // Check if hook is initialised |
| 740 | execFile('rtk', ['init', '--show'], { timeout: 5000 }, (err2, hookOut) => { |
| 741 | const hookActive = !err2 && hookOut.includes('hook'); |
| 742 | res.end(JSON.stringify({ |
| 743 | installed: true, |
| 744 | version: stdout.trim(), |
| 745 | hookActive, |
| 746 | note: hookActive |
| 747 | ? 'RTK instalado y hook activo — los agentes ahorran tokens automáticamente' |
| 748 | : 'RTK instalado pero hook no activo — ejecuta: rtk init -g', |
| 749 | })); |
| 750 | }); |
| 751 | }); |
| 752 | return; // async — don't fall through to 404 |
| 753 | } |
| 754 | |
| 755 | // ── POST /admin/circuit-reset — manually reset circuit breaker ─────────── |
| 756 | if (req.method === 'POST' && pathname === '/admin/circuit-reset') { |
| 757 | consecutiveFailures = 0; |
| 758 | circuitOpen = false; |
| 759 | circuitOpenAt = 0; |
| 760 | console.log('[relay] Circuit breaker manually reset'); |
| 761 | return res.end(JSON.stringify({ ok: true, message: 'Circuit breaker reset' })); |
| 762 | } |
| 763 | |
| 764 | // ── POST /admin/restart — drain active sessions then exit (systemd restarts) ─ |
| 765 | if (req.method === 'POST' && pathname === '/admin/restart') { |
| 766 | console.log(`[relay] Graceful restart requested — draining ${active.size} active sessions`); |
| 767 | res.end(JSON.stringify({ ok: true, message: `Draining ${active.size} sessions then restarting` })); |
| 768 | |
| 769 | // Give active sessions 10s to finish, then SIGTERM them and exit |
| 770 | setTimeout(() => { |
| 771 | for (const [sid, entry] of active.entries()) { |
| 772 | console.log(`[relay] restart: killing session ${sid}`); |
| 773 | try { entry.proc.kill('SIGTERM'); } catch {} |
| 774 | } |
| 775 | setTimeout(() => { |
| 776 | console.log('[relay] Restarting now (systemd will restart)'); |
| 777 | process.exit(0); |
| 778 | }, 3000); |
| 779 | }, active.size > 0 ? 10000 : 0); |
| 780 | return; |
| 781 | } |
| 782 | |
| 783 | // ── POST /rtk-install — install + init RTK hook on the host ─────────────── |
| 784 | if (req.method === 'POST' && pathname === '/rtk-install') { |
| 785 | const { exec } = require('child_process'); |
| 786 | // Try brew first, then cargo |
| 787 | const installCmd = 'brew install rtk-ai/tap/rtk 2>&1 || cargo install rtk 2>&1'; |
| 788 | exec(installCmd, { timeout: 120000 }, (err, stdout, stderr) => { |
| 789 | if (err && !stdout.includes('already installed')) { |
| 790 | return res.end(JSON.stringify({ ok: false, error: stderr || err.message, stdout })); |
| 791 | } |
| 792 | // Init hook |
| 793 | exec('rtk init -g --auto-patch 2>&1', { timeout: 30000 }, (err2, hookOut) => { |
| 794 | res.end(JSON.stringify({ |
| 795 | ok: true, |
| 796 | install: stdout, |
| 797 | hook: hookOut, |
| 798 | note: 'RTK instalado. Reinicia el relay para activar el hook.', |
| 799 | })); |
| 800 | }); |
| 801 | }); |
| 802 | return; |
| 803 | } |
| 804 | |
| 805 | res.writeHead(404); |
| 806 | res.end(JSON.stringify({ error: 'not found' })); |
| 807 | }); |
| 808 | |
| 809 | server.listen(PORT, '0.0.0.0', () => { |
| 810 | console.log(`\n🤖 Agent Host Relay v1.1`); |
| 811 | console.log(` Listening on :${PORT}`); |
| 812 | console.log(` Claude bin: ${CLAUDE_BIN}`); |
| 813 | console.log(` Console URL: ${CONSOLE_URL}`); |
| 814 | console.log(` Auth: ${AUTH_TOKEN ? 'token set' : 'none (localhost only)'}`); |
| 815 | console.log(` Session timeout: ${SESSION_TIMEOUT_MS / 60000}min`); |
| 816 | console.log(` Circuit breaker: ${CIRCUIT_BREAKER_THRESHOLD} failures → ${CIRCUIT_BREAKER_RESET_MS / 60000}min pause`); |
| 817 | console.log(` Watchdog: every ${WATCHDOG_INTERVAL_MS / 1000}s\n`); |
| 818 | |
| 819 | // Verify claude is accessible on startup |
| 820 | checkClaudeBinary(); |
| 821 | }); |
| 822 | |
| 823 | // ── Periodic auto-recovery tasks ────────────────────────────────────────────── |
| 824 | setInterval(runWatchdog, WATCHDOG_INTERVAL_MS); |
| 825 | setInterval(checkClaudeBinary, BINARY_CHECK_INTERVAL_MS); |
| 826 | |
| 827 | // ── Uncaught exception guard — log but don't crash ──────────────────────────── |
| 828 | process.on('uncaughtException', err => { |
| 829 | console.error(`[relay] uncaughtException: ${err.message}\n${err.stack}`); |
| 830 | }); |
| 831 | process.on('unhandledRejection', (reason) => { |
| 832 | console.error(`[relay] unhandledRejection: ${reason}`); |
| 833 | }); |