// 관측 설명 문서: /docs/specs/bada-bong-agent-telemetry.md (v0.3.0) /** 비대화형 CLI 실행: stdin EOF, 종료 코드, 취소·timeout·출력 제한을 하나의 계약으로 처리한다. */ const { spawn } = require('child_process'); const paths = require('../config/cli-paths'); const claude = require('../config/claude-execution-config'); const processHelper = require('./process-helper'); const { jsonOutputArgs, parseCliOutput } = require('./cli-output'); const { isStorageBusy, storageBusyError, isUncertainCliFailure, terminalStorageBusy } = require('./cli-storage-error'); async function runCliText({ cliCommand, cliArguments = [], argsTemplate, permissionBypass = false, transport = 'pipe', model, profile, prompt, cwd, env = process.env, signal, timeoutMs = 60000, maxBytes = 2 * 1024 * 1024, register, unregister, beforeSpawn, onUsage, onDelta, onActivity, usageOwner, requireRuntimePolicy = false }) { signal?.throwIfAborted(); if (usageOwner && require('../services/runtime-usage-ledger').isBound(usageOwner) && typeof onUsage !== 'function') throw new Error('Bound CLI execution requires a usage callback'); if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error('Invalid CLI timeout'); if (!Number.isFinite(maxBytes) || maxBytes <= 0) throw new Error('Invalid CLI output limit'); if (!['pipe', 'pty'].includes(transport)) throw new Error('Invalid CLI transport'); const tokens = claude.shellTokens(cliCommand).map(token => token.value); if (!tokens.length) throw new Error('CLI command is required'); let cli = paths.normalizeExecutableName(tokens[0]); let resolvedCommand = tokens[0]; // 베어(bare) 명령어(`antigravity` -> `/opt/homebrew/bin/agy`, `hermes` -> `~/.hermes/hermes-agent/venv/bin/hermes`, `cursor` -> `cursor-agent`)를 // 실제 설치된 터미널 CLI 바이너리로 해석하여 ENOENT 또는 Electron IDE 런처 오실행을 원천 차단한다. const catalogClis = ['antigravity', 'agy', 'hermes', 'hermes-agent', 'cursor', 'cursor-agent', 'aider', 'goose', 'qwen', 'codex', 'gemini', 'opencode', 'codeagent', 'pi', 'mimo', 'mimocode', 'gjc', 'ollama']; if (!/[\\/]/.test(resolvedCommand) && catalogClis.includes(cli)) { const resolvedBin = require('../herd/herd-cli-catalog').resolveCliBinaryPath(cli, env); if (resolvedBin) { resolvedCommand = resolvedBin; } else if (cli === 'antigravity') { resolvedCommand = 'agy'; } else if (cli === 'cursor') { resolvedCommand = 'cursor-agent'; } cli = cli === 'agy' ? 'antigravity' : cli === 'hermes-agent' ? 'hermes' : cli === 'cursor-agent' ? 'cursor' : cli; } if (onDelta !== undefined && typeof onDelta !== 'function') throw new Error('Invalid CLI stream callback'); if(beforeSpawn!==undefined&&typeof beforeSpawn!=='function')throw new Error('Invalid CLI submission callback'); // 관측을 요청한 Claude pipe만 스트림으로 실행한다. 일반 호출/PTY의 기존 JSON 계약은 유지한다. const streamJson = cli === 'claude' && transport === 'pipe' && typeof onActivity === 'function'; const nativeStreaming = Boolean(onDelta) && ['opencode', 'codeagent'].includes(cli); const streams = require('./cli-native-stream'); let stream, headroomScope, hostLaunch; let args; if (argsTemplate !== undefined) { if (!Array.isArray(argsTemplate) || !argsTemplate.every(arg => typeof arg === 'string') || !argsTemplate.some(arg => ['@prompt', '@brief_content'].includes(arg))) throw new Error('CLI args_template requires a prompt placeholder'); args = jsonOutputArgs(cli, [...tokens.slice(1), ...argsTemplate], { streamJson }).map(arg => ['@prompt', '@brief_content'].includes(arg) ? prompt : arg); } else { const extraArgs = jsonOutputArgs(cli, [...tokens.slice(1), ...cliArguments], { streamJson }); args = paths.buildHeadlessArgs(cli, { prompt, extraArgs, model, permissionBypass }); } const preparationStarted = Date.now(); const environmentGuard = require('../security/agent-environment'); env = environmentGuard.scrubAgentEnvironment(env, { trustedKeys: environmentGuard.MODEL_KEYS }); const profileScope = require('./cli-profile-scope').acquire({ command: resolvedCommand, profile, cwd, prompt }); try { if (require('../services/runtime-usage-ledger').isBound(usageOwner)) headroomScope = require('../services/cli-headroom-usage-scope').create({ contextId: profileScope.contextId, cwd }); let executionEnv = require('../services/mcp-session-credentials').environment( require('./execution-environment').getExecutionEnvironment(streams.applyNativeStream(env), { cliCommand: claude.quoteShellArgument(resolvedCommand), directArgs: args, cwd, profile: profileScope.profile, profileContextId: profileScope.contextId, headroomOwnerToken: headroomScope?.token, requireRuntimePolicy: requireRuntimePolicy || nativeStreaming }), profileScope); if (profileScope.contextId) { await require('./cli-profile-scope').ready(signal, Math.min(timeoutMs - (Date.now() - preparationStarted), 15000)); } signal?.throwIfAborted(); if (Date.now() - preparationStarted >= timeoutMs) throw new Error('CLI execution timed out before runtime preparation'); await require('./cli-runtime-ready').ensureCliRuntimeReady({ command: resolvedCommand, env: executionEnv, cwd, signal, timeoutMs: Math.min(timeoutMs - (Date.now() - preparationStarted), 15000) }); signal?.throwIfAborted(); if (nativeStreaming) { stream = await streams.createNativeStream({ onDelta, maxBytes }); executionEnv = streams.applyNativeStream(executionEnv, stream); signal?.throwIfAborted(); } timeoutMs -= Date.now() - preparationStarted; if (timeoutMs <= 0) throw new Error('CLI execution timed out before task submission'); let executable = resolvedCommand, spawnArgs = args; if (process.platform === 'win32' && !/\.exe$/i.test(executable)) { spawnArgs = ['-NoLogo', '-NoProfile', '-Command', '& ' + [executable, ...args].map(arg => claude.quoteShellArgument(arg, true)).join(' ')]; executable = 'powershell.exe'; } hostLaunch = await require('../security/host-launch').prepareHostLaunch({ command: executable, args: spawnArgs, cwd, env: executionEnv, kind: transport === 'pty' ? 'pty' : 'cli' }); executable = hostLaunch.command; spawnArgs = hostLaunch.args; executionEnv = hostLaunch.env; hostLaunch.assertCurrent(); signal?.throwIfAborted(); const requestId = require('../services/usage-request').begin(usageOwner, 'cli'); // 실행권의 제출 가능 단계를 실제 spawn 전에 저장한다. 여기서 실패하면 자식은 만들지 않는다. // docs/specs/bong-feedback-recovery.md v1.0.0 // 제출 표시의 비동기 저장 중 취소되면 자식을 만들지 않고 기존 미제출 정산을 사용한다. // docs/specs/workflow-triage-admission.md v1.1.0 try{headroomScope?.arm({run:usageOwner,requestId,signal});await beforeSpawn?.();signal?.throwIfAborted();}catch(error){await headroomScope?.close();if(requestId)await onUsage?.({id:requestId,notSubmitted:true,costUsd:0,costSource:'not_submitted',totalTokens:0,tokenSource:'not_submitted',complete:false});throw error;} const output = await new Promise(resolve => { let child, timer, settled = false, ending = false, didClose = false, terminalError, bytes = 0, stdout = '', stderr = ''; const disposables = []; let activity, activityReady = false, activityFailed = false; const activityFailure = () => { if (activityFailed) return; activityFailed = true; try { activity?.stop(); } catch { /* 관측 정리 실패도 실행에는 전파하지 않는다. */ } try { require('../utils/logger').makeLogger('cli-activity').warn('CLI_ACTIVITY_OBSERVER_FAILED'); } catch { /* 관측 로거 실패는 실제 CLI 결과를 바꾸지 않는다. */ } }; const observe = (method, value) => { if (activityFailed) return; try { activity?.[method](value); } catch { activityFailure(); } }; // 출력/정산 파서와 분리한다. 원문은 기존 실행 경로에만 남고 관측 callback에는 정규화된 메타데이터만 전달한다. if (typeof onActivity === 'function' && transport === 'pipe' && ['claude', 'opencode', 'codeagent'].includes(cli)) { try { activity = require('./cli-activity-stream').createCliActivityStream({ cli, transport, maxBytes, onActivity: event => { if (!activityReady || ending || activityFailed) return; try { const pending = onActivity(event); if (pending?.then) Promise.resolve(pending).catch(activityFailure); } catch { activityFailure(); } } }); } catch { activityFailure(); } } const terminate = (kill = false) => { // pipe 프로세스는 아래 spawn의 detached:true로 우리 소유의 별도 Unix 그룹이다. // 일반 PTY/공유 프로세스에 음수 PID를 적용하지 않는다. 정상 종료 후 남은 자식도 정리한다. if (child?.pid && transport === 'pipe' && process.platform !== 'win32') { try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (kill && error.code !== 'ESRCH') { try { processHelper.killProcessTree(child.pid, true); } catch { /* 이미 끝난 소유 프로세스는 원래 종료 오류를 유지한다. */ } } } } else if (kill && child) { try { if (child.pid) processHelper.killProcessTree(child.pid, true); else child.kill(); } catch { /* 중복 종료의 실패가 원래 오류를 가리지 않게 한다. */ } } }; const finish = (error, kill = false) => { if (settled) return; if (!ending) { ending = true; observe('stop'); terminalError = error; clearTimeout(timer); signal?.removeEventListener('abort', abort); stream?.stop(); terminate(kill); } // kill 요청을 종료 근거로 삼지 않는다. 실제 close/onExit 뒤 정산과 자격 해제를 허용한다. // 설명 문서: docs/specs/cli-headroom-ownership.md (v1.0.0) if (child && !didClose) return; settled = true; error = terminalError || error; for (const disposable of disposables) { try { disposable.dispose(); } catch { /* 종료된 PTY의 후속 정리는 반복해도 안전하게 끝낸다. */ } } try { unregister?.(child); } catch (cleanupError) { error ||= cleanupError; } resolve({ stdout, stderr, error, submitted: Boolean(child?.pid) }); }; const abort = () => finish(signal.reason || new Error('CLI execution cancelled'), true); try { stream?.onFailure(error => finish(error, true)); if (ending) return; const data = (chunk, errorStream) => { if (ending) return; bytes += Buffer.byteLength(chunk); if (bytes > maxBytes) return finish(new Error('CLI output limit exceeded'), true); if (errorStream) stderr += chunk; else { stdout += chunk; observe('feed', chunk); } }; const closed = (code, exitSignal) => { if (!ending) observe('end'); didClose = true; let error = code === 0 ? null : new Error('CLI exited with ' + (exitSignal || code)); if (error) error.code = 'CLI_EXIT_FAILED'; // 종료 이벤트에서만 분류해 취소·시간/출력 제한 오류를 덮어쓰지 않는다. if (error && ['opencode', 'codeagent'].includes(cli) && (isStorageBusy(stderr) || (transport === 'pty' && terminalStorageBusy(stdout)))) error = storageBusyError(); finish(error); }; hostLaunch.assertCurrent(); if (transport === 'pty') { // 명시적 TTY 요청만 PTY로 실행한다. 종료·취소·제한·집계는 pipe와 같은 경로다. child = require('node-pty').spawn(executable, spawnArgs, { cwd, env: executionEnv, name: 'dumb', cols: 2000, rows: 30 }); disposables.push(child.onData(chunk => data(chunk, false))); disposables.push(child.onExit(({ exitCode, signal: exitSignal }) => closed(exitCode, exitSignal))); } else { child = spawn(executable, spawnArgs, { cwd, env: executionEnv, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', windowsHide: true }); // EMFILE/ENFILE 등 spawn 실패는 stdio 없이 error/close만 올 수 있다. // stdio 준비보다 먼저 수명을 소유하여 준비 실패도 실제 close까지 회수한다. child.on('error', error => finish(error, true)); child.on('close', closed); // 부모가 끝나도 상속 stdio를 가진 자손 때문에 close가 지연될 수 있다. child.once('exit', () => { if (process.platform !== 'win32') terminate(true); }); child.stdout?.setEncoding('utf8'); child.stderr?.setEncoding('utf8'); child.stdout?.on('data', chunk => data(chunk, false)); child.stderr?.on('data', chunk => data(chunk, true)); } register?.(child); activityReady = Boolean(child?.pid); if (!ending) { timer = setTimeout(() => finish(new Error('CLI execution timed out'), true), timeoutMs); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort(); } } catch (error) { finish(error, true); } }); // 원 CLI 보고보다 먼저 모든 소유 HTTP의 정책 정산과 응답 종료를 기다린다. let headroomError; try { await headroomScope?.close(); } catch (error) { headroomError = error; } if (!headroomError && headroomScope?.code) headroomError = Object.assign(new Error('CLI policy request could not complete'), { code: headroomScope.code }); const parsed = parseCliOutput(cli, output.stdout, { streamJson }); const error = output.error?.code === 'CLI_EXIT_FAILED' && isUncertainCliFailure(parsed.error) ? parsed.error : output.error || parsed.error || headroomError; parsed.usage.complete = !error; if (requestId) parsed.usage.id = requestId; parsed.usage.notSubmitted = !output.submitted; if (!output.submitted) Object.assign(parsed.usage, { costUsd: 0, reportedCostUsd: 0, totalTokens: 0, costSource: 'not_submitted', tokenSource: 'not_submitted' }); // 콜백은 한 실행당 한 번 호출하며, 실패한 실행의 수신 완료 사용량도 전달한다. await onUsage?.(parsed.usage, parsed.text); // 보고 비용 저장을 먼저 끝낸 뒤 명시 예약의 초과/미상으로 성공 반환을 막는다. require('../services/runtime-request-reservation').assertReady(usageOwner); if (error) throw error; return parsed.text; } finally { try { await headroomScope?.close(); } finally { try { await stream?.close(); } finally { try { await hostLaunch?.dispose(); } finally { headroomScope?.release(); profileScope.release(); } } } } } module.exports = { runCliText };