/** 하네스 명령의 출력·취소·소유 프로세스 수명. docs/specs/harness-validation.md v1.3.0 */ const { spawn } = require('child_process'); const { StringDecoder } = require('string_decoder'); const { validateCommand, configurationError } = require('../config/harness-configuration'); function controlError(error) { return Object.assign(new Error(error?.message || String(error), { cause: error }), { code: 'HARNESS_CONTROL' }); } function cancellationError(signal, prefix = '') { return Object.assign(new Error(prefix + (signal?.reason?.message || 'Workflow run was cancelled or failed.'), { cause: signal?.reason }), { code: 'HARNESS_CANCELLED' }); } function checkCancellation(signal, shouldCancel, prefix) { if (signal?.aborted) throw cancellationError(signal, prefix); let cancelled; try { cancelled = shouldCancel?.(); } catch (error) { throw controlError(error); } if (cancelled) throw cancellationError(null, prefix); } async function runHarnessCommand({ command, cwd, env, signal, shouldCancel, registerProcess, unregisterProcess, onData, timeoutMs = 60000, maxBufferBytes = 2 * 1024 * 1024, windowsShell = 'powershell', errorPrefix = '' }) { require('../security/host-launch').assertHostPathSupported('uncontained-task'); validateCommand(command); if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw configurationError('invalid command timeout'); if (!Number.isSafeInteger(maxBufferBytes) || maxBufferBytes <= 0) throw configurationError('invalid command output limit'); checkCancellation(signal, shouldCancel, errorPrefix); // 모든 BADA 하네스 셸 실행은 프로세스 생성 전에 공통 정책/단발 승인을 통과한다. await require('../orchestration/runtime-policy-guard').check({ commands: [command], workspacePath: cwd }, { signal }); checkCancellation(signal, shouldCancel, errorPrefix); const isWin = process.platform === 'win32'; let shell = '/bin/sh'; let args = ['-c', command]; const options = {}; if (isWin && windowsShell === 'cmd') { shell = process.env.ComSpec || 'cmd.exe'; args = ['/d', '/s', '/c', '"' + command + '"']; options.windowsVerbatimArgs = true; } else if (isWin) { shell = 'powershell.exe'; args = ['-NoLogo', '-NoProfile', '-Command', command]; } const credentials = require('../services/mcp-session-credentials'); const cli = require('../config/cli-paths').normalizeCliName(command); const credential = require('../context').runtimePolicyEnabled && ['claude', 'mimo', 'mimocode', 'opencode', 'codeagent'].includes(cli) ? credentials.issue({ cwd }) : null; let executionEnv; try { const base = credential ? credentials.environment(env || process.env, { mcpCredential: credential.token }) : env || { ...process.env }; const environment = require('../security/agent-environment'); executionEnv = environment.scrubAgentEnvironment(require('./execution-environment').getExecutionEnvironment(base, { cliCommand: command, shellArgs: args, cwd }), { trustedKeys: [...environment.MODEL_KEYS, ...environment.RUNTIME_KEYS] }); checkCancellation(signal, shouldCancel, errorPrefix); } catch (error) { credential?.release(); throw error; } return new Promise((resolve, reject) => { let child, timer, poll, failure, settled = false, terminated = false, bytes = 0, stdout = '', stderr = ''; const outDecoder = new StringDecoder('utf8'), errDecoder = new StringDecoder('utf8'); const terminate = () => { if (terminated || !child) return; terminated = true; // 이 spawn이 만든 독립 Unix 그룹에만 음수 PID를 사용한다. 일반 PTY/공유 // 프로세스에는 적용하지 않는다. 부모가 끝나도 같은 그룹의 자손을 정리한다. if (child.pid && !isWin) { try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') require('./process-helper').killProcessTree(child.pid, true); } } else if (child.pid) require('./process-helper').killProcessTree(child.pid, true); else { try { child.kill('SIGKILL'); } catch { /* 선택 환경 조회 실패 시 기본 명령을 유지한다. */ } } }; const clearControls = () => { clearTimeout(timer); clearInterval(poll); signal?.removeEventListener('abort', abort); }; // 종료 요청은 실제 close와 다르다. 실패 때도 pipe가 닫히기 전에는 // 등록·MCP 자격·상위 단계의 실행 소유권을 돌려주지 않는다. const stop = error => { if (settled) return; failure ||= error; clearControls(); try { terminate(); } catch (cleanupError) { failure ||= controlError(cleanupError); } }; const finish = (error, exitCode = null) => { if (settled) return; settled = true; error = failure || error; clearControls(); try { terminate(); } catch (cleanupError) { error ||= controlError(cleanupError); } // 등록 실패가 부분 등록을 남겼을 수도 있으므로 spawn 뒤에는 해제를 한 번 시도한다. try { if (child) unregisterProcess?.(child); } catch (cleanupError) { error ||= controlError(cleanupError); } if (error) { error.stdout = stdout; error.stderr = stderr; reject(error); } else resolve({ exitCode, stdout, stderr }); }; const abort = () => stop(cancellationError(signal, errorPrefix)); const pollCancellation = () => { if (!settled && !failure) { try { checkCancellation(signal, shouldCancel, errorPrefix); } catch (error) { stop(error); } } }; const data = (chunk, isError) => { if (settled || failure) return; const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); const remaining = Math.max(0, maxBufferBytes - bytes), accepted = buffer.subarray(0, remaining); bytes += accepted.length; const text = (isError ? errDecoder : outDecoder).write(accepted); if (isError) stderr += text; else stdout += text; try { if (text) onData?.(text); } catch (error) { stop(controlError(error)); return; } if (buffer.length > remaining) stop(Object.assign(new Error(errorPrefix + 'stdout maxBuffer length exceeded'), { code: 'HARNESS_OUTPUT_LIMIT' })); }; try { require('../security/host-launch').assertHostPathSupported('uncontained-task'); child = spawn(shell, args, { ...options, cwd, env: executionEnv, stdio: ['ignore', 'pipe', 'pipe'], detached: !isWin }); // EMFILE/ENFILE에서는 stdio가 없는 ChildProcess도 반환된다. // 스트림보다 error/close를 먼저 구독해 부분 생성도 소유 종료를 기다린다. child.on('error', stop); // exit 후 자손이 pipe를 붙잡으면 close가 오지 않을 수 있어 먼저 정리한다. // 정상 출력은 close까지 수집하여 마지막 stdout/stderr를 잃지 않는다. child.on('exit', () => { if (!settled) { try { terminate(); } catch (error) { stop(controlError(error)); } } }); child.on('close', code => { if (settled) return; // 실패 시 잘린 UTF-8 꼬리를 대체문자로 늘리지 않고 기존 부분 출력을 보존한다. if (!failure) { stdout += outDecoder.end(); stderr += errDecoder.end(); } try { checkCancellation(signal, shouldCancel, errorPrefix); finish(null, code); } catch (error) { finish(error); } }); child.stdout?.on('data', chunk => data(chunk, false)); child.stderr?.on('data', chunk => data(chunk, true)); child.stdout?.on('error', stop); child.stderr?.on('error', stop); timer = setTimeout(() => stop(Object.assign(new Error(errorPrefix + 'Validation command execution timed out after ' + Math.round(timeoutMs / 1000) + ' seconds.'), { code: 'HARNESS_TIMEOUT' })), timeoutMs); if (shouldCancel) poll = setInterval(pollCancellation, 50); signal?.addEventListener('abort', abort, { once: true }); try { registerProcess?.(child); } catch (error) { stop(controlError(error)); } pollCancellation(); } catch (error) { if (child) stop(error); else finish(error); } }).finally(() => credential?.release()); } module.exports = { runHarnessCommand, checkCancellation };