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