Download src/utils/cli-text-runner.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/utils/cli-text-runner.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/utils/cli-text-runner.js
-
curl -L -o cli-text-runner.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/utils/cli-text-runner.js
15 kB
| // ๊ด์ธก ์ค๋ช ๋ฌธ์: /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 }; | |