/** * 실행별 OpenCode provider 전송 설정. 원본 설정 파일은 수정하지 않는다. * 설명 문서: docs/WRAPPER_REFACTOR_PROGRESS_2026-09-09.md (4차 수정) * JSON/JSONC의 provider 설정을 우선순위대로 읽고 최종 인라인 설정에 proxy URL을 넣는다. * 관리자가 강제한 provider 설정은 인라인으로 덮을 수 없으므로 조용히 우회하지 않는다. */ const fs = require('fs'); const path = require('path'); const os = require('os'); const jsonc = require('jsonc-parser'); const forbidden = new Set(['__proto__', 'constructor', 'prototype']); function object(value) { return value && typeof value === 'object' && !Array.isArray(value); } function merge(left, right) { const result = { ...left }; for (const [key, value] of Object.entries(right || {})) { if (forbidden.has(key)) throw new Error('Unsafe OpenCode configuration key'); result[key] = object(value) ? merge(object(result[key]) ? result[key] : {}, value) : value; } return result; } function parse(text, filename) { jsonc.visit(text, { onObjectProperty: key => { if (forbidden.has(key)) throw new Error('Unsafe OpenCode configuration key'); } }); const errors = []; const value = jsonc.parse(text.replace(/^\uFEFF/, ''), errors, { allowTrailingComma: true }); if (errors.length || !object(value)) throw new Error('Invalid OpenCode JSON/JSONC configuration: ' + filename); return value; } function expand(value, directory, env) { if (typeof value === 'string') return value.replace(/\{(env|file):([^}]+)\}/g, (_, type, name) => { if (type === 'env') return env[name] || ''; const home = env.HOME || env.USERPROFILE || os.homedir(); const file = name.startsWith('~/') ? path.join(home, name.slice(2)) : path.resolve(directory, name); return fs.readFileSync(file, 'utf8').trim(); }); if (Array.isArray(value)) return value.map(item => expand(item, directory, env)); if (object(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, expand(item, directory, env)])); return value; } function resolveManagedConfigDir(env = process.env) { return process.platform === 'darwin' ? '/Library/Application Support/opencode' : process.platform === 'win32' ? path.join(env.ProgramData || 'C:\\ProgramData', 'opencode') : '/etc/opencode'; } function hasManagedConfigFile(env = process.env, cli = 'opencode') { const managed = resolveManagedConfigDir(env); const names = cli === 'codeagent' ? ['codeagent.json', 'codeagent.jsonc', 'opencode.json', 'opencode.jsonc'] : ['opencode.json', 'opencode.jsonc']; return names.some(name => fs.existsSync(path.join(managed, name))); } function ensureEmptyManagedDir() { const emptyDir = path.join(os.tmpdir(), 'bada-opencode-managed-empty'); try { fs.mkdirSync(emptyDir, { recursive: true }); } catch { // 임시 디렉토리 생성 실패 시 기존 경로 유지 } return emptyDir; } function readConfiguration(env, cwd, cli = 'opencode', _options = {}) { const home = env.HOME || env.USERPROFILE || os.homedir(); const configHome = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), cli); const files = [path.join(configHome, 'config.json')]; const addDirectory = directory => { if (cli === 'codeagent') files.push(path.join(directory, 'codeagent.json'), path.join(directory, 'codeagent.jsonc')); files.push(path.join(directory, 'opencode.json'), path.join(directory, 'opencode.jsonc')); }; addDirectory(configHome); if (env.OPENCODE_CONFIG) files.push(path.resolve(cwd, env.OPENCODE_CONFIG)); const ancestors = []; let current = path.resolve(cwd); while (true) { ancestors.push(current); if (fs.existsSync(path.join(current, '.git')) || path.dirname(current) === current) break; current = path.dirname(current); } if (env.OPENCODE_DISABLE_PROJECT_CONFIG !== 'true') for (const directory of ancestors.reverse()) addDirectory(directory); for (const directory of ancestors) addDirectory(path.join(directory, '.opencode')); addDirectory(path.join(home, '.opencode')); if (env.OPENCODE_CONFIG_DIR) addDirectory(path.resolve(cwd, env.OPENCODE_CONFIG_DIR)); // Windows(C:\ProgramData\opencode) 등 시스템 관리 설정을 에러로 차단하지 않고 병합하여 Headroom 라우팅 및 프로필 MCP 제어를 일관되게 적용한다. const managed = resolveManagedConfigDir(env); addDirectory(managed); let config = {}; for (const filename of [...new Set(files)]) { if (!fs.existsSync(filename)) continue; config = merge(config, expand(parse(fs.readFileSync(filename, 'utf8'), filename), path.dirname(filename), env)); } if (env.OPENCODE_CONFIG_CONTENT) config = merge(config, expand(parse(env.OPENCODE_CONFIG_CONTENT, 'OPENCODE_CONFIG_CONTENT'), cwd, env)); if (process.platform === 'darwin') { for (const directory of ['/Library/Managed Preferences', path.join('/Library/Managed Preferences', env.USER || os.userInfo().username)]) { if (fs.existsSync(path.join(directory, 'ai.opencode.managed.plist'))) throw new Error('Managed OpenCode preferences require administrator-configured Headroom routing'); } } return config; } function applyOpenCodeEnvironment(env, { cwd = process.cwd(), cli = 'opencode', proxyUrl }) { const config = readConfiguration(env, cwd, cli); const anthropicBase = env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_URL; const defaults = { anthropic: anthropicBase ? anthropicBase.replace(/\/$/, '').replace(/(?:\/v1)?$/, '/v1') : 'https://api.anthropic.com/v1', openai: env.OPENAI_BASE_URL || env.OPENAI_API_BASE || 'https://api.openai.com/v1', google: env.GOOGLE_GENERATIVE_AI_BASE_URL || 'https://generativelanguage.googleapis.com/v1beta' }; const knownEndpoints = { 'bada-conductor': env.BADA_CONDUCTOR_URL || 'http://127.0.0.1:55060/v1', 'openai-compatible': env.OPENAI_BASE_URL || env.OPENAI_API_BASE || 'http://127.0.0.1:11434/v1', opencode: 'https://opencode.ai/zen/v1', ollama: env.OLLAMA_BASE_URL || 'http://127.0.0.1:11434/v1', lmstudio: 'http://127.0.0.1:1234/v1', openrouter: 'https://openrouter.ai/api/v1', deepseek: 'https://api.deepseek.com/v1', xai: 'https://api.x.ai/v1', groq: 'https://api.groq.com/openai/v1', mistral: 'https://api.mistral.ai/v1', togetherai: 'https://api.together.xyz/v1', together: 'https://api.together.xyz/v1', fireworks: 'https://api.fireworks.ai/inference/v1', perplexity: 'https://api.perplexity.ai', cerebras: 'https://api.cerebras.ai/v1', cohere: 'https://api.cohere.com/compatibility/v1', deepinfra: 'https://api.deepinfra.com/v1/openai', moonshotai: 'https://api.moonshot.ai/v1', alibaba: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', zai: 'https://api.z.ai/api/paas/v4', minimax: 'https://api.minimax.io/v1', xiaomi: 'https://api.xiaomimimo.com/v1', mimo: 'https://api.xiaomimimo.com/v1', 'github-copilot': 'https://api.githubcopilot.com', copilot: 'https://api.githubcopilot.com', 'github-models': 'https://models.inference.ai.azure.com' }; if (config.provider !== undefined && !object(config.provider)) throw new Error('Invalid OpenCode provider configuration'); const providers = merge({}, config.provider || {}); const allowed = config.enabled_providers || [...new Set([...Object.keys(defaults), ...Object.keys(providers)])]; if (!Array.isArray(allowed) || !allowed.every(id => typeof id === 'string')) throw new Error('Invalid OpenCode enabled_providers'); const disabled = new Set(config.disabled_providers || []); function rewrite(value) { if (Array.isArray(value)) return value.map(rewrite); if (!object(value)) return value; return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, key === 'baseURL' && typeof item === 'string' ? proxyUrl(item) : rewrite(item)])); } for (const id of allowed) { if (disabled.has(id)) continue; const provider = providers[id] || {}; const endpoint = provider.options?.baseURL || provider.api || provider.baseURL || defaults[id] || knownEndpoints[id]; if (!endpoint) throw new Error('Headroom requires an explicit baseURL for OpenCode provider: ' + id); providers[id] = rewrite(merge(provider, { options: { baseURL: endpoint } })); } // 사용자 인라인의 agent/MCP/permission 설정은 보존하고 provider 및 허용 목록만 덮는다. const inline = env.OPENCODE_CONFIG_CONTENT ? parse(env.OPENCODE_CONFIG_CONTENT, 'OPENCODE_CONFIG_CONTENT') : {}; const fingerprint = require('crypto').createHash('sha256').update(JSON.stringify(config)).digest('hex'); // 시스템 관리 경로(C:\ProgramData\opencode 등)에 원본 파일이 존재할 때 OpenCode 바이너리가 OPENCODE_CONFIG_CONTENT 위에서 // 프록시 미적용 원본을 다시 덮어쓰지 않도록 이미 병합·라우팅된 후에는 빈 관리 디렉토리로 리다이렉트한다. const managedRedirect = hasManagedConfigFile(env, cli) && !env.OPENCODE_TEST_MANAGED_CONFIG_DIR ? { OPENCODE_TEST_MANAGED_CONFIG_DIR: ensureEmptyManagedDir() } : {}; return { ...env, ...managedRedirect, BADA_CLI_CONFIG_HASH: fingerprint, OPENCODE_CONFIG_CONTENT: JSON.stringify({ ...inline, provider: providers, enabled_providers: allowed.filter(id => !disabled.has(id)) }) }; } module.exports = { readConfiguration, applyOpenCodeEnvironment };