File size: 12,014 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
/** ๋ณธ ์ž‘์—…์„ ์ œ์ถœํ•˜๊ธฐ ์ „์— CLI ์ž์ฒด ์ €์žฅ์†Œ ์ดˆ๊ธฐํ™”๋งŒ ์ง๋ ฌํ™”ํ•œ๋‹ค.
 * ์„ค๋ช… ๋ฌธ์„œ: /docs/specs/cli-runtime-initialization.md (v1.1.0)
 */
const fs = require('fs');
const path = require('path');
const os = require('os');
const { spawn } = require('child_process');
const { createHash } = require('crypto');
const files = require('./protected-file-write');
const { acquireStoreWriteLock } = require('../db/store-write-lock');
const { normalizeExecutableName } = require('../config/cli-paths');
const { quoteShellArgument } = require('../config/claude-execution-config');
const processHelper = require('./process-helper');
const { environmentValue, selectedDatabase } = require('./opencode-database-path');
const defaultDatabaseName = name => /^opencode(?:-[a-zA-Z0-9._-]+)?\.db$/.test(name);
function error(code, message) { return Object.assign(new Error(message), { code }); }
function check(signal, deadline, isCancelled = () => false) {
  signal?.throwIfAborted();
  if (isCancelled()) throw new Error('CLI initialization cancelled');
  if (Date.now() >= deadline) throw error('CLI_INITIALIZATION_TIMEOUT', 'CLI database initialization timed out before submitting the task');
}
function wait(signal, ms) {
  return new Promise((resolve, reject) => {
    const done = () => { signal?.removeEventListener('abort', abort); resolve(); };
    const timer = setTimeout(done, ms);
    const abort = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); reject(signal.reason || new Error('CLI initialization cancelled')); };
    signal?.addEventListener('abort', abort, { once: true });
    if (signal?.aborted) abort();
  });
}
function initialize(command, env, cwd, signal, timeoutMs, isCancelled) {
  // debug config๋Š” ์‚ฌ์šฉ์ž ์„ค์ •/ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ๋กœ๋“œํ•  ์ˆ˜ ์žˆ๋‹ค. DB ์งˆ์˜๋งŒ ์‹คํ–‰ํ•˜๋ฉฐ ํ”„๋กฌํ”„ํŠธ์™€
  // ์‚ฌ์šฉ์ž CLI ์ธ์ž๋Š” ์ „๋‹ฌํ•˜์ง€ ์•Š๋Š”๋‹ค. stdout์€ ๊ณ ์ • ์‘๋‹ต ๊ฒ€์ฆ์—๋งŒ ์“ฐ๊ณ  ์˜ค๋ฅ˜ ์›๋ฌธ์€ ๋…ธ์ถœํ•˜์ง€ ์•Š๋Š”๋‹ค.
  let args = ['db', "SELECT 1 AS bada_ready, file AS bada_database FROM pragma_database_list WHERE name = 'main'", '--format', 'json'];
  if (process.platform === 'win32' && !/\.exe$/i.test(command)) {
    args = ['-NoLogo', '-NoProfile', '-Command', '& ' + [command, ...args].map(arg => quoteShellArgument(arg, true)).join(' ')];
    command = 'powershell.exe';
  }
  return new Promise((resolve, reject) => {
    let child, timer, cancellation, failure, stdout = '', bytes = 0, settled = false;
    const kill = () => {
      if (!child?.pid) return;
      try {
        if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL');
        else processHelper.killProcessTree(child.pid, true);
      } catch (e) { if (e.code !== 'ESRCH') { try { child.kill('SIGKILL'); } catch {} } }
    };
    const finish = () => {
      if (settled) return; settled = true;
      clearTimeout(timer); clearInterval(cancellation); signal?.removeEventListener('abort', abort); process.removeListener('exit', kill);
      let database;
      if (!failure) {
        try {
          const result = JSON.parse(stdout);
          if (!Array.isArray(result) || result.length !== 1 || result[0]?.bada_ready !== 1) throw new Error('Invalid readiness result');
          database = result[0].bada_database;
          if (typeof database !== 'string' || !path.isAbsolute(database)) throw new Error('Invalid readiness database');
        } catch { failure = error('CLI_INITIALIZATION_FAILED', 'CLI database readiness response was invalid; task was not submitted'); }
      }
      if (failure) reject(failure); else resolve(database);
    };
    const stop = reason => { failure ||= reason; kill(); };
    const abort = () => stop(signal.reason || new Error('CLI initialization cancelled'));
    try {
      child = spawn(command, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', windowsHide: true });
      process.once('exit', kill);
      // ํ•œ๊ธ€ ๊ฒฝ๋กœ์˜ UTF-8 ๋ฌธ์ž๊ฐ€ ์—ฌ๋Ÿฌ ์ˆ˜์‹  chunk๋กœ ๊ฐˆ๋ผ์ ธ๋„ ๊ฐ™์€ ๋ฌธ์ž์—ด๋กœ ๋ณต์›ํ•œ๋‹ค.
      child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
      const consume = (data, output) => {
        bytes += Buffer.byteLength(data);
        if (bytes > 64 * 1024) stop(error('CLI_INITIALIZATION_OUTPUT_LIMIT', 'CLI initialization output exceeded the limit; task was not submitted'));
        else if (output) stdout += data;
      };
      child.stdout.on('data', data => consume(data, true)); child.stderr.on('data', data => consume(data, false));
      child.once('error', () => { failure ||= error('CLI_INITIALIZATION_SPAWN_FAILED', 'Unable to start CLI database initialization; task was not submitted'); });
      // ์ข…๋ฃŒ๋œ ๋ถ€๋ชจ๊ฐ€ ๋‚จ๊ธด ์†Œ์œ  ์ž์‹์˜ pipe๊นŒ์ง€ ์ •๋ฆฌํ•œ ๋’ค close์—์„œ ์ž ๊ธˆ์„ ํ•ด์ œํ•œ๋‹ค.
      child.once('exit', (code, exitSignal) => {
        if (code !== 0 || exitSignal) failure ||= error('CLI_INITIALIZATION_FAILED', 'CLI database initialization failed; task was not submitted');
        kill();
      });
      child.once('close', finish);
      timer = setTimeout(() => stop(error('CLI_INITIALIZATION_TIMEOUT', 'CLI database initialization timed out; task was not submitted')), timeoutMs);
      cancellation = setInterval(() => { if (isCancelled()) stop(new Error('CLI initialization cancelled')); }, 50);
      signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
    } catch { failure = error('CLI_INITIALIZATION_SPAWN_FAILED', 'Unable to start CLI database initialization; task was not submitted'); kill(); finish(); }
  });
}
function runtimeHash(command, cwd, env, selectedFile) {
  const envValue = name => environmentValue(env, name);
  const names = process.platform === 'win32' && !path.extname(command) ? (envValue('PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').map(ext => command + ext.toLowerCase()) : [command];
  const directories = /[\\/]/.test(command) ? [cwd] : (envValue('PATH') || '').split(path.delimiter);
  for (const directory of directories) for (const name of names) {
    const candidate = path.resolve(cwd, directory, name);
    try {
      const actual = fs.realpathSync(candidate), stat = fs.statSync(actual);
      if (!stat.isFile()) continue;
      const identity = [actual, stat.dev, stat.ino, stat.size, stat.mtimeMs, envValue('OPENCODE_DISABLE_CHANNEL_DB') || ''];
      // ๊ธฐ๋ณธ DB์˜ ๊ธฐ์กด ์ค€๋น„ ๊ธฐ๋ก์€ ๋ณด์กดํ•œ๋‹ค. ๋ช…์‹œ์  DB๋Š” ์ •๊ทœ ๊ฒฝ๋กœ๊นŒ์ง€ ์‹๋ณ„ํ•œ๋‹ค.
      if (selectedFile) identity.push(selectedFile);
      return createHash('sha256').update(JSON.stringify(identity)).digest('hex');
    } catch (e) { if (!['ENOENT', 'ENOTDIR'].includes(e.code)) throw e; }
  }
  throw error('CLI_INITIALIZATION_SPAWN_FAILED', 'OpenCode executable was not found; task was not submitted');
}
function databaseIdentity(file) {
  const stat = fs.lstatSync(file);
  if (!stat.isFile() || stat.isSymbolicLink()) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI database must be a regular file');
  return [stat.dev, stat.ino, stat.birthtimeMs];
}
async function ensureCliRuntimeReady({ command, env = process.env, cwd = process.cwd(), signal, timeoutMs = 15000, isCancelled = () => false }) {
  signal?.throwIfAborted();
  // CodeAgent ๋ฐ ๋‹ค๋ฅธ CLI์— OpenCode์˜ DB ๋ช…๋ น์„ ์ถ”์ • ์ ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
  if (normalizeExecutableName(command) !== 'opencode') return;
  // DB ์ค€๋น„๋„ ์™ธ๋ถ€ ์‹คํ–‰์ด๋‹ค. ์—„๊ฒฉ ๋ชจ๋“œ์—์„œ ์ค€๋น„ ๋ช…๋ น๋งŒ ๋ฌด๊ฒฉ๋ฆฌ๋กœ ๋จผ์ € ์‹คํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค.
  require('../security/host-launch').assertHostPathSupported('uncontained-task');
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error('Invalid CLI initialization timeout');
  const deadline = Date.now() + timeoutMs;
  const home = environmentValue(env, 'HOME') || environmentValue(env, 'USERPROFILE') || os.homedir();
  const dataDirectory = path.resolve(cwd, environmentValue(env, 'XDG_DATA_HOME') || path.join(home, '.local', 'share'), 'opencode');
  const selected = selectedDatabase(dataDirectory, environmentValue(env, 'OPENCODE_DB'));
  // :memory:๋Š” CLI ํ”„๋กœ์„ธ์Šค๋งˆ๋‹ค ๋ณ„๊ฐœ๋‹ค. ํ๊ธฐ๋  ์ค€๋น„ ํ”„๋กœ์„ธ์Šค์˜ DB๋ฅผ ์ค€๋น„ ์™„๋ฃŒ๋กœ ๊ธฐ๋กํ•˜์ง€ ์•Š๋Š”๋‹ค.
  if (selected.kind === 'memory') { check(signal, deadline, isCancelled); return; }
  const selectedName = selected.kind === 'custom' ? path.basename(selected.file) : null;
  if (selectedName?.toLowerCase().startsWith('.bada-')) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI database conflicts with wrapper metadata; task was not submitted');
  check(signal, deadline, isCancelled);
  const directory = files.directory(selectedName ? path.dirname(selected.file) : dataDirectory);
  const selectedFile = selectedName ? path.join(directory, selectedName) : null;
  const markerName = selectedName ? '.bada-runtime-ready-' + createHash('sha256').update(selectedName).digest('hex') + '.json' : '.bada-runtime-ready.json';
  const validDatabaseName = name => selectedName ? name === selectedName : defaultDatabaseName(name);
  // HOME/XDG๊ฐ€ ๋‹ฌ๋ผ๋„ ๊ฐ™์€ DB ๋ถ€๋ชจ์—์„œ๋Š” ๊ฐ™์€ ์ž ๊ธˆ์œผ๋กœ ์ค€๋น„ํ•œ๋‹ค. ๊ธฐ์กด ๊ธฐ๋ณธ DB ์ž ๊ธˆ๊ณผ๋„ ํ˜‘๋ ฅํ•œ๋‹ค.
  const lockTarget = path.join(directory, '.bada-runtime-initialization');
  const hash = runtimeHash(command, cwd, env, selectedFile);
  let release;
  while (!release) {
    check(signal, deadline, isCancelled);
    try { release = acquireStoreWriteLock(lockTarget); }
    catch (e) {
      if (e.code !== 'KNOWLEDGE_STORE_BUSY') throw e;
      // ์ž ๊ธˆ ์†Œ์œ ์ž ์ข…๋ฃŒ๋ฅผ ์ž„์˜ ์ถ”์ •ํ•ด ์‚ญ์ œํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ทจ์†Œ/๊ธฐํ•œ์€ ๋Œ€๊ธฐ ์ค‘์—๋„ ์ ์šฉํ•œ๋‹ค.
      await wait(signal, Math.min(50, Math.max(1, deadline - Date.now())));
    }
  }
  try {
    check(signal, deadline, isCancelled);
    const markerFile = path.join(directory, markerName);
    let marker, markerExists = false;
    try {
      if (fs.lstatSync(markerFile).size > 4096) throw new Error('Oversized readiness metadata');
      marker = JSON.parse(files.readRegular(markerFile).toString('utf8')); markerExists = true;
    }
    catch (e) { if (e.code !== 'ENOENT') throw error('CLI_INITIALIZATION_METADATA_INVALID', 'CLI readiness metadata is unreadable; task was not submitted'); }
    if (markerExists) {
      if (!marker || marker.version !== 1 || typeof marker.database !== 'string' || !validDatabaseName(marker.database)
        || typeof marker.runtimeHash !== 'string' || !/^[a-f0-9]{64}$/.test(marker.runtimeHash)
        || !Array.isArray(marker.identity) || marker.identity.length !== 3 || !marker.identity.every(Number.isFinite)) throw error('CLI_INITIALIZATION_METADATA_INVALID', 'CLI readiness metadata is invalid; task was not submitted');
      try { if (marker.runtimeHash === hash && JSON.stringify(databaseIdentity(path.join(directory, marker.database))) === JSON.stringify(marker.identity)) return; }
      catch (e) { if (e.code !== 'ENOENT') throw e; }
    }
    // ์ด๋ฏธ ์ค€๋น„ํ•œ DB์— ๋งค๋ฒˆ ๋ณ„๋„ CLI๋ฅผ ๋„์šฐ๋ฉด ๋ณธ ์ž‘์—…์˜ DB ์‚ฌ์šฉ๊ณผ ์ดˆ๊ธฐํ™” ์งˆ์˜๊ฐ€ ๋‹ค์‹œ
    // ๊ฒน์น  ์ˆ˜ ์žˆ๋‹ค. ์‹คํ–‰ ํŒŒ์ผ๊ณผ ์‹ค์ œ DB ํŒŒ์ผ์˜ ์‹ ์›์ด ๊ฐ™์„ ๋•Œ๋งŒ ์ค€๋น„ ๊ฒฐ๊ณผ๋ฅผ ์žฌ์‚ฌ์šฉํ•œ๋‹ค.
    for (const name of fs.readdirSync(directory)) if (validDatabaseName(name)) databaseIdentity(path.join(directory, name));
    const database = await initialize(command, env, cwd, signal, Math.max(1, deadline - Date.now()), isCancelled);
    check(signal, deadline, isCancelled);
    if (fs.realpathSync(path.dirname(database)) !== fs.realpathSync(directory) || !validDatabaseName(path.basename(database))) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI initialized an unexpected database; task was not submitted');
    const identity = databaseIdentity(database);
    files.writeProtected(directory, [markerName], JSON.stringify({ version: 1, runtimeHash: hash, database: path.basename(database), identity }), { replace: true, allowHidden: true });
  } finally { release(); }
}
module.exports = { ensureCliRuntimeReady };