File size: 8,185 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | /** ํ๋ค์ค ๋ช
๋ น์ ์ถ๋ ฅยท์ทจ์ยท์์ ํ๋ก์ธ์ค ์๋ช
. 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 };
|