File size: 14,961 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// ๊ด€์ธก ์„ค๋ช… ๋ฌธ์„œ: /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 };