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 };