// 설명 문서: docs/specs/cli-claude-inference.md (v1.0.0) // JSON 결과만 수용한다. stderr/오류 원문은 자격증명을 포함할 수 있어 노출하지 않는다. const { spawn } = require('child_process'); const failure = code => Object.assign(new Error('Claude inference failed'), { code, retryable: false }); async function runProcess({ command, args, cwd, env, prompt, signal, timeoutMs, maxBytes }) { let child, closed, timer, error, submitted = false, bytes = 0; const chunks = []; const terminate = () => { if (!child?.pid) return; try { if (process.platform === 'win32') require('../utils/process-helper').killProcessTree(child.pid, true); else process.kill(-child.pid, 'SIGKILL'); } catch (cause) { if (cause.code !== 'ESRCH') { try { child.kill('SIGKILL'); } catch { /* 이미 종료됨 */ } } } }; const fail = cause => { error ||= cause; terminate(); }; const abort = () => fail(failure('CLAUDE_INFERENCE_CANCELLED')); try { signal?.throwIfAborted(); const launch = require('../services/bong-antigravity-transport').launchCommand(command, args); child = spawn(launch.command, launch.args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' }); closed = new Promise(resolve => { child.once('error', () => fail(failure('CLAUDE_INFERENCE_SPAWN'))); child.once('exit', terminate); child.once('close', code => { if (code !== 0) error ||= failure('CLAUDE_INFERENCE_EXIT'); resolve(); }); }); child.once('spawn', () => { submitted = true; }); child.stdin.on('error', () => fail(failure('CLAUDE_INFERENCE_INPUT'))); for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => { bytes += chunk.length; if (bytes > maxBytes) fail(failure('CLAUDE_INFERENCE_OUTPUT_LIMIT')); else if (stream === child.stdout) chunks.push(chunk); }); timer = setTimeout(() => fail(failure('CLAUDE_INFERENCE_TIMEOUT')), timeoutMs); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort(); else child.stdin.end(prompt); await closed; if (error) return { error, submitted }; let result; try { result = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return { error: failure('CLAUDE_INFERENCE_JSON'), submitted }; } if (result?.type !== 'result' || result.subtype !== 'success' || result.is_error || typeof result.result !== 'string' || !result.result.trim()) { return { error: failure('CLAUDE_INFERENCE_RESULT'), submitted, usage: result?.usage, cost: result?.total_cost_usd }; } return { text: result.result, submitted, usage: result.usage, cost: result.total_cost_usd }; } catch { return { error: error || failure('CLAUDE_INFERENCE_SPAWN'), submitted }; } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); terminate(); if (closed) await closed; } } module.exports = { runProcess, failure };