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