File size: 9,454 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
/**
 * ์‹คํ–‰๋ณ„ 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 };