File size: 20,509 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | /** ๋ํํ CLI์ ์ค๋นยทํดยท์ทจ์ยท์ฌ์ฌ์ฉ ๊ณ์ฝ. docs/specs/interactive-execution.md v1.2.0 */
const { randomUUID } = require('crypto');
const pty = require('node-pty');
const { stripAnsi } = require('./log-cleaner');
const processHelper = require('./process-helper');
const { executionFingerprint } = require('./execution-fingerprint');
const { Terminal } = require('@xterm/headless');
const sessions = new WeakMap();
const initializations = new WeakMap();
function promptReady(text) {
// ๊ณผ๊ฑฐ ํ๋กฌํํธ/์ฝ๋์ >, ๋ณธ๋ฌธ ์ โฏ๋ฅผ ํ์ฌ ๋๊ธฐ ์ํ๋ก ์ค์ธํ์ง ์๋๋ค.
const lines = stripAnsi(text).split(/[\r\n]/);
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i].trim();
if (!line || /^[โโโ\-ยทโข\s]+$/.test(line)) continue;
if (/^(?:\? for shortcuts|shift\+tab|bypass permissions on|โตโต bypass permissions)/i.test(line)) continue;
return /^(?:โฏ(?:\s+Try\b.*)?|>)\s*$/.test(line);
}
return false;
}
function openCodePromptReady(screen) {
const lines = screen.split('\n');
// ๊ธด cwd๊ฐ footer ์ผ์ชฝ ์ด์ ์ฐจ์งํ ๋ ์ฐ์ธก ๋จ์ถํค์ ์ค๋ช
์ด ์๋ก ๋ค๋ฅธ ํ์ ๋์ธ๋ค.
const wrappedCommands = lines.some((line, i) => {
const column = line.indexOf('ctrl+p');
const nextColumn = (lines[i + 1] || '').search(/\bcommands\s*$/);
return column >= 0 && /ctrl\+p\s*$/.test(line) && nextColumn >= column;
});
return (/ctrl\+p[ \t]+commands/.test(screen) || wrappedCommands)
&& /Build\s*ยท|Ask anything/.test(screen) && !/esc interrupt/.test(screen);
}
function closeSession(owner) {
if (owner.pendingInteractiveClosePromise) return owner.pendingInteractiveClosePromise;
const initialization = initializations.get(owner);
initialization?.abort(new Error('Interactive CLI initialization closed'));
const session = sessions.get(owner);
if (!session) return initialization?.done || Promise.resolve();
sessions.delete(owner);
// ์ข
๋ฃ ์์ฒญ ์งํ ์๊ฒฉ/๋ฌธ๋งฅ์ ํด์ ํ์ง ์๋๋ค. ์ค์ PTY exit์ HTTP drain์ ๋ชจ๋ ๊ธฐ๋ค๋ฆฐ๋ค.
// ์ค๋ช
๋ฌธ์: docs/specs/interactive-headroom-ownership.md (v1.0.0)
const operation = Promise.allSettled([session.exitPromise, Promise.resolve().then(() => session.headroomScope?.close())]).then(results => {
for (const disposable of session.disposables) { try { disposable.dispose(); } catch { /* ์ข
๋ฃ๋ ์ด๋ฒคํธ ๊ตฌ๋
์ ๋ฐ๋ณต ์ ๋ฆฌํด๋ ์์ ํ๊ฒ ๋๊ธด๋ค. */ } }
try { session.terminal?.dispose(); } catch { /* ํ๋ฉด ํด์ ์คํจ์ ์์ ์์ ํ์๋ฅผ ๋ถ๋ฆฌํ๋ค. */ } // ํ๋ฉด ์ค๋ฅ๊ฐ ๋๋จธ์ง ์์ ์์ ํด์ ๋ฅผ ๋ง์ง ์๋๋ค.
let releaseError;
try { try { session.headroomScope?.release(); } finally { session.profileScope?.release(); } } catch (error) { releaseError = error; }
if (owner.workflowPty === session.child) {
owner.workflowPty = null; owner.workflowPtyReadyPromise = null; owner.workflowPtyFingerprint = null;
}
if (owner.currentProcess === session.child) owner.currentProcess = null;
const failed = results.find(result => result.status === 'rejected'); if (failed) throw failed.reason;
if (releaseError) throw releaseError;
});
owner.pendingInteractiveClosePromise = operation;
const clear = () => { if (owner.pendingInteractiveClosePromise === operation) delete owner.pendingInteractiveClosePromise; };
operation.then(clear, clear);
session.listener?.('error', new Error('Interactive CLI session closed'));
session.dead = true; session.listener = null;
if (!session.exited) {
try { if (session.child.pid) processHelper.killProcessTree(session.child.pid, true); else session.child.kill('SIGKILL'); }
catch { /* ์ข
๋ฃ๋ฅผ ์์ฒญํ์ง ๋ชปํด๋ ์ค์ exit๋ฅผ ์ถ์ธกํ์ง ์๊ณ ์๋ ๋๊ธฐ๋ฅผ ์ ์งํ๋ค. */ }
}
return operation;
}
async function runInteractive({ owner, command, runtimeCommand = command, args, cwd, env, cli, profile = {}, profilePreparation, prompt,
signal, isCancelled = () => false, timeoutMs = 120000, readyTimeoutMs = 30000,
maxBytes = 2 * 1024 * 1024, idleMs = 1500, allowBypass = false,
onOutput = () => {}, register, unregister, onResult }) {
signal?.throwIfAborted();
require('../security/host-launch').assertHostPathSupported('uncontained-task');
if (require('../services/runtime-usage-ledger').isBound(owner) && typeof onResult !== 'function') throw new Error('Bound interactive execution requires a usage callback');
if (owner.pendingInteractiveClosePromise) throw new Error('Interactive CLI session is closing');
if (isCancelled()) throw new Error('Interactive CLI cancelled');
for (const [name, value] of Object.entries({ timeoutMs, readyTimeoutMs, maxBytes, idleMs })) {
if (!Number.isFinite(value) || value <= 0 || value > 2147483647) throw new Error('Invalid interactive CLI ' + name);
}
if (typeof prompt === 'string') prompt = prompt.replace(/\r\n/g, '\n');
// eslint-disable-next-line no-control-regex -- ํฐ๋ฏธ๋ ์
๋ ฅ ์ ์ด๋ฌธ์๋ฅผ ์ ์ถ ์ ์ ๋ช
์์ ์ผ๋ก ๊ฑฐ๋ถํ๋ค.
if (typeof prompt !== 'string' || !prompt.trim() || /[\x00-\x08\x0b-\x1f\x7f]/.test(prompt)) throw new Error('Invalid interactive CLI prompt');
let session = sessions.get(owner);
if (session?.busy || initializations.has(owner)) throw new Error('Interactive CLI session is already running a turn');
let pendingScope, pendingHeadroom, initializationDone;
try {
const profileStarted = Date.now();
pendingScope = profilePreparation?.acquire();
if (pendingScope?.contextId) ({ args, env } = profilePreparation.prepare(pendingScope.contextId));
const profileElapsed = Date.now() - profileStarted;
timeoutMs -= profileElapsed; readyTimeoutMs -= profileElapsed;
if (timeoutMs <= 0 || readyTimeoutMs <= 0) throw new Error('Interactive CLI timed out during profile preparation');
const environment = require('../security/agent-environment');
env = environment.scrubAgentEnvironment(env, { trustedKeys: [...environment.MODEL_KEYS, ...environment.RUNTIME_KEYS] });
const fingerprint = executionFingerprint({ command, args, cwd, env, profile });
if (session && (session.dead || session.fingerprint !== fingerprint || owner.workflowPty !== session.child)) {
await closeSession(owner); session = null;
}
if (!session) {
if (require('../services/runtime-usage-ledger').isBound(owner)) {
pendingHeadroom = require('../services/interactive-headroom-usage-scope').create({ contextId: pendingScope?.contextId, cwd });
if (profilePreparation?.prepare) ({ args, env } = profilePreparation.prepare(pendingScope?.contextId, pendingHeadroom.token));
else if (require('./headroom-manager').shouldUseProxy()) throw new Error('Managed interactive policy requires a prepared execution environment');
}
// ์ธ์ฆ๊ฐ์ ์ ํ๋ก์ธ์ค์๋ง ์ ๋ฌํ๋ค. ์ผํ์ฑ ๊ฐ์ผ๋ก ๊ธฐ์กด PTY์ ์ฌ์ฌ์ฉ ํด์๋ฅผ ๋ฐ๊พธ์ง ์๋๋ค.
env = require('../services/mcp-session-credentials').environment(env, pendingScope);
// ์ด์ ๊ตฌํ์ ์ธ์
์ ์ ์๋ช
๊ด๋ฆฌ ๊ณ์ฝ์ผ๋ก ์์ ์ฌ์ฌ์ฉํ์ง ์๋๋ค.
if (owner.workflowPty) throw new Error('Unmanaged interactive CLI session');
if (pendingScope?.contextId || require('../config/cli-paths').normalizeExecutableName(runtimeCommand) === 'opencode') {
const preparationStarted = Date.now();
const controller = new AbortController(), abort = () => controller.abort(signal.reason);
controller.done = new Promise(resolve => { initializationDone = resolve; });
initializations.set(owner, controller);
signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
try {
if (pendingScope?.contextId) await profilePreparation.ready(controller.signal, Math.min(readyTimeoutMs, timeoutMs, 15000), isCancelled);
const remaining = Math.min(readyTimeoutMs, timeoutMs, 15000) - (Date.now() - preparationStarted);
if (remaining <= 0) throw new Error('Interactive CLI timed out before runtime preparation');
await require('./cli-runtime-ready').ensureCliRuntimeReady({ command: runtimeCommand, env, cwd, signal: controller.signal, isCancelled, timeoutMs: remaining });
controller.signal.throwIfAborted();
if (isCancelled()) throw new Error('Interactive CLI cancelled');
} finally { signal?.removeEventListener('abort', abort); }
const elapsed = Date.now() - preparationStarted;
readyTimeoutMs -= elapsed; timeoutMs -= elapsed;
if (readyTimeoutMs <= 0 || timeoutMs <= 0) throw new Error('Interactive CLI timed out before task submission');
}
let child;
try {
require('../security/host-launch').assertHostPathSupported('uncontained-task');
env = environment.scrubAgentEnvironment(env, { trustedKeys: [...environment.MODEL_KEYS, ...environment.RUNTIME_KEYS] });
child = pty.spawn(command, args, { name: 'xterm-256color', cols: 100, rows: 40, cwd, env });
let exit; const exitPromise = new Promise(resolve => { exit = resolve; });
session = { child, fingerprint, terminal: null, ready: false, busy: false, dead: false, exited: false, exitPromise, disposables: [], listener: null, profileScope: pendingScope, headroomScope: pendingHeadroom };
pendingScope = null; pendingHeadroom = null;
sessions.set(owner, session); owner.workflowPty = child; owner.workflowPtyFingerprint = fingerprint;
try {
session.disposables.push(child.onExit(event => { session.exited = true; session.dead = true; exit(); session.listener?.('exit', event); if (!session.busy) closeSession(owner); }));
} catch (error) {
// ์ด๋ฒคํธ ๋ฑ๋ก ์์ฒด๊ฐ ์คํจํ ๋ถ๋ถ ์์ฑ์์๋ ์์ PID์ ์ค์ ๋ถ์ฌ๋ฅผ ํ์ธํ๋ค.
session.exitPromise = new Promise((resolve, reject) => {
if (!Number.isSafeInteger(child.pid) || child.pid <= 0) { reject(error); return; }
const check = () => { if (!processHelper.isProcessAlive(child.pid)) { session.exited = true; resolve(); } else setTimeout(check, 10); };
check();
});
throw error;
}
session.terminal = new Terminal({ cols: 100, rows: 40, scrollback: 1000, allowProposedApi: true });
session.disposables.push(child.onData(data => {
if (session.listener) session.listener('data', data);
else if (!session.dead) session.terminal.write(data);
}));
session.disposables.push(session.terminal.onData(data => { if (!session.dead) { try { child.write(data); } catch (error) { session.listener?.('error', error); } } }));
} catch (error) {
if (session && sessions.get(owner) === session) await closeSession(owner);
else if (child) { try { if (child.pid) processHelper.killProcessTree(child.pid, true); else child.kill('SIGKILL'); } catch { /* ๋ถ๋ถ ์์ฑ ์์์ ์ค๋ณต ์ข
๋ฃ ์ค๋ฅ๋ ์๋ ์์ฑ ์ค๋ฅ๋ฅผ ๋ณด์กดํ๋ค. */ } }
throw error;
}
}
require('../security/host-launch').assertHostPathSupported('uncontained-task');
session.busy = true;
let output = '', submitted = false, complete = false, requestId, turnError;
try {
register?.(session.child);
const id = 'BADA_TURN_' + randomUUID().replaceAll('-', '');
const marker = 'BADA_RESULT:' + id;
// ์์ฑ๋ marker๋ ์
๋ ฅ ๋ฌธ์์ด์ ์๋ค. ์ค๋ฐ๊ฟ/ํ๋ฉด ์๋ ์ค๋ฐ๊ฟ์ผ๋ก ์์ฝ๊ฐ ๋
๋ฆฝ๋ ์ค์ด ๋์ด๋ ์ผ์นํ์ง ์๋๋ค.
const input = prompt + '\n\n๋ชจ๋ ์์
์ ๋ง์น ์ต์ข
์๋ต์ ๋ง์ง๋ง ๋
๋ฆฝ๋ ์ค์ BADA_RESULT: ์ ๋์ฌ ๋ฐ๋ก ๋ค์ ๊ณต๋ฐฑ ์์ด ๋ค์ ์๋ณ์๋ฅผ ๋ถ์ฌ ์ถ๋ ฅํ์ธ์. ์๋ณ์: ' + id;
if (session.profileScope?.contextId) require('../config/profile-request-context').protectPrompt(session.profileScope.contextId, input);
await new Promise((resolve, reject) => {
let settled = false, phase = session.ready ? 'input' : 'ready', bytes = 0, inputEnded = false, submissionScheduled = false;
let idle, startup, trustSent = false, bypassSent = false, dataRevision = 0;
const timers = new Set();
const later = (callback, ms) => {
const timer = setTimeout(() => { timers.delete(timer); if (!settled) callback(); }, ms);
timers.add(timer); return timer;
};
const finish = error => {
if (settled) return; settled = true;
// PTY ์ข
๋ฃ ์ด๋ฒคํธ๊ฐ ์์ง ๋ฐฐ๋ฌ๋์ง ์์์ด๋ ์ด๋ฏธ ์ฌ๋ผ์ง ์์ ํ๋ก์ธ์ค๋ฅผ ์ฑ๊ณต ์ฒ๋ฆฌํ์ง ์๋๋ค.
if (!error && (session.dead || !processHelper.isProcessAlive(session.child.pid))) error = new Error('Interactive CLI exited before turn completion');
for (const timer of timers) clearTimeout(timer);
clearInterval(cancellation); clearTimeout(startup); clearTimeout(deadline); clearTimeout(idle);
signal?.removeEventListener('abort', abort); session.listener = null;
if (error) reject(error); else resolve();
};
const abort = () => finish(signal?.reason || new Error('Interactive CLI cancelled'));
const write = text => {
if (!settled) {
// ์ฌ์ฌ์ฉ PTY์๋ ์ ์
๋ ฅ๋ง๋ค ์ต์ ์ ์ฑ
์ ์ ์ฉํ๋ค. ์ข
๋ฃ/ํ์ ๊ฒฝ๋ก์๋ ์ ์ฉํ์ง ์๋๋ค.
require('../security/host-launch').assertHostPathSupported('uncontained-task');
session.child.write(text);
}
};
const submit = delay => {
if (submissionScheduled) return;
submissionScheduled = true;
later(() => {
try { requestId = require('../services/usage-request').begin(owner, 'interactive'); session.headroomScope?.beginTurn({ run: owner, requestId, signal, marker: id }); output = ''; phase = 'response'; submitted = true; write('\r'); }
catch (error) { finish(error); }
}, delay);
};
const send = () => {
if (settled) return;
phase = 'input'; session.ready = true; clearTimeout(startup);
// ๋ถ์ฌ๋ฃ๊ธฐ ๊ตฌ๊ฐ์ ๊ฐํ์ด ๋ณ๋ ๋ช
๋ น ์ ์ถ๋ก ํด์๋์ง ์๊ฒ ํ๋ค. ์
๋ ฅ ์ค ์์ฝ๋ ์๋ฃ ํ์ ์์ ์ ์ธํ๋ค.
const chars = Array.from(input); let offset = 0;
const next = () => {
try {
if (offset === 0) write('\x1b[200~');
if (offset < chars.length) {
write(chars.slice(offset, offset + 256).join('')); offset += 256; later(next, 10);
} else {
write('\x1b[201~');
inputEnded = true;
// Claude์ paste ์ํ ๋ฐ์ ์ ์ Enter๋ฅผ ๋ณด๋ด๋ฉด ์
๋ ฅ์ฐฝ์ ๋ถ์ฌ๋ฃ๊ธฐ๋ง ๋จ๋๋ค.
// ๊ณ ์ ์๊ฐ๋ง์ผ๋ก ์ ์ถํ์ง ์๊ณ ์ค์ ์
๋ ฅ์ฐฝ์ paste ํ์๋ฅผ ์๋์์ ๊ด์ฐฐํ๋ค.
if (cli !== 'claude') submit(100);
}
} catch (error) { finish(error); }
};
next();
};
session.listener = (kind, data) => {
if (settled) return;
if (kind === 'exit') return finish(new Error('Interactive CLI exited before turn completion: ' + data.exitCode));
if (kind === 'error') return finish(data);
try {
bytes += Buffer.byteLength(data);
if (bytes > maxBytes) return finish(new Error('Interactive CLI output limit exceeded'));
onOutput(data);
clearTimeout(idle);
const revision = ++dataRevision;
const receivedPhase = phase;
if (phase === 'response') output += data;
// ์ปค์ ์ด๋ยท์ง์ฐ๊ธฐยท๋ถํ ANSI๋ฅผ ๋ฐ์ํ ํ์ฌ ํ๋ฉด์ ์ฌ์ฉํ๋ค. ๋น๋๊ธฐ ํ์ฑ ์๋ฃ ํ์๋ง ํ์ ํ๋ค.
session.terminal.write(data, () => {
// ๋ค์ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ๋์ฐฉํ๋ค๋ฉด ์ด์ ํ์ฑ callback์ด ์ ์๋ฃ ํ์ด๋จธ๋ฅผ ๋ง๋ค ์ ์๋ค.
if (settled || receivedPhase !== phase || revision !== dataRevision) return;
try {
const buffer = session.terminal.buffer.active;
const screen = Array.from({ length: buffer.length }, (_, i) => buffer.getLine(i)?.translateToString(true) || '').join('\n');
const ready = cli === 'opencode' || cli === 'codeagent'
? openCodePromptReady(screen)
: promptReady(screen);
if (phase === 'ready') {
const clean = screen;
if (!trustSent && /Yes,\s*I\s*trust|trust\s*this\s*folder/i.test(clean)) {
trustSent = true; write('\r'); return;
}
if (!bypassSent && /accept responsibility|Yes, I accept/i.test(clean)) {
if (!allowBypass) return finish(new Error('Interactive CLI permission bypass was not requested'));
bypassSent = true; write('\x1b[B');
later(() => { try { write('\r'); } catch (error) { finish(error); } }, 200); return;
}
if (ready) send();
} else if (phase === 'input' && inputEnded && cli === 'claude') {
const lastPrompt = screen.split('\n').filter(line => /^\s*โฏ/.test(line)).at(-1) || '';
if (/\[Pasted text #/.test(lastPrompt) || screen.includes(id)) submit(200);
} else if (phase === 'response') {
const clean = screen;
// ์์ฑ ๋ฌธ๊ตฌ์ ๋ถ๋ถ ์ผ์น๋ ์ฌ์ฉ์ ์
๋ ฅ ์์ฝ๋ง์ผ๋ก ๋ค์ ๋จ๊ณ/๋ณํฉ์ ์งํํ์ง ์๋๋ค.
const hasMarker = clean.split(/[\r\n]/).some(line => line.trim().replace(/^[โโโบโ]\s*/, '') === marker);
if (hasMarker && ready) idle = setTimeout(() => { if (revision === dataRevision) finish(); }, idleMs);
}
} catch (error) { finish(error); }
});
} catch (error) { finish(error); }
};
signal?.addEventListener('abort', abort, { once: true });
const cancellation = setInterval(() => { if (isCancelled()) abort(); }, 50);
const deadline = setTimeout(() => finish(new Error('Interactive CLI execution timed out')), timeoutMs);
if (session.dead) finish(new Error('Interactive CLI session exited'));
else if (signal?.aborted || isCancelled()) abort();
else if (session.ready) send();
else startup = setTimeout(() => finish(new Error('Interactive CLI initialization timed out')), readyTimeoutMs);
});
signal?.throwIfAborted();
if (isCancelled()) throw new Error('Interactive CLI cancelled');
complete = true;
} catch (error) { turnError = error; }
// ์ค์ ๋ณด๊ณ ๋ฅผ ๋จผ์ ์ ์ฅํ๊ณ ๋น์ฉ ๊ฒํ ๋ฅผ ์๋ ์ฑ๊ณต/์ทจ์๋ณด๋ค ์ฐ์ ํ๋ค.
// finally์ ๋ฐํ ๋ฎ์ด์ฐ๊ธฐ์ ์์กดํ์ง ์๊ณ ์คํจ ์ฐ์ ์์๋ฅผ ๋ช
์ํ๋ค.
let drainError;
try {
if (!complete) await closeSession(owner);
else await session.headroomScope?.endTurn();
} catch (error) { drainError = error; }
let cleanupError;
try { unregister?.(session.child); } catch (error) { cleanupError = error; }
try {
await onResult?.({ output: stripAnsi(output), submitted, complete: complete && !drainError && !cleanupError && !session.headroomScope?.code, requestId });
require('../services/runtime-request-reservation').assertReady(owner);
if (drainError) throw drainError;
if (cleanupError) throw cleanupError;
if (session.headroomScope?.code) throw Object.assign(new Error('Interactive policy request could not complete'), { code: session.headroomScope.code });
signal?.throwIfAborted();
if (isCancelled()) throw new Error('Interactive CLI cancelled');
} catch (error) { await closeSession(owner); throw error; }
finally { session.busy = false; }
if (turnError) throw turnError;
return stripAnsi(output).trim();
} finally { try { await pendingHeadroom?.close(); } finally { pendingHeadroom?.release(); pendingScope?.release(); if (initializationDone) initializations.delete(owner); initializationDone?.(); } }
}
module.exports = { runInteractive, closeSession, promptReady,
hasSession: owner => sessions.has(owner) || initializations.has(owner) || !!owner.pendingInteractiveClosePromise,
isSessionBusy: owner => initializations.has(owner) || !!owner.pendingInteractiveClosePromise || sessions.get(owner)?.busy === true };
|