File size: 2,997 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // ์ค๋ช
๋ฌธ์: 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 };
|