HAL 0.3.1: 서버에 설치된 CLI 자동 탐색·연결 가능화 — HAL 서비스 PATH 밖(~/.local/bin 등)의 Claude Code·Codex CLI 를 찾아 버전·로그인 상태·기본 모델을 AI 연동 화면에 보이고(GET /ops/api/ai/cli, "이 CLI 로 연결 추가"), Codex exec --json 지원, 로그인 안 됨은 cli_not_logged_in → reauth_required + 서버 로그인 안내, 확인 실패 응답 424(원인 표시), 점검 결과·개발 지시 v0.3.1(Oz)·docs/HAL-AI.md·VERSION_HISTORY 0.3.1 — test/hal-ai.test.mjs RED → GREEN 12/12, 전체 26파일 183건 통과

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Claude Fable 5.1
2026-10-29 01:11:32 +00:00
parent 0d3a0b80e9
commit 3775b7bee4
14 changed files with 252 additions and 52 deletions
+10 -7
View File
@@ -14,7 +14,7 @@ import { nowIso, toJson, parseJson } from '../../lib/db.mjs';
import { newId, randomToken, sha256 } from '../../lib/crypto.mjs';
import { hint, safeError } from '../../lib/redact.mjs';
import { createHash } from 'node:crypto';
import { PROVIDERS, listModels as providerModels, ProviderError } from './providers.mjs';
import { PROVIDERS, listModels as providerModels, ProviderError, CLI_TOOLS, cliDefaultModel } from './providers.mjs';
import { ensureDirectRoom, removeRoomsOf } from './rooms.mjs';
const VK = { key: (id) => `ai:conn:${id}:api_key`, oauth: (id) => `ai:conn:${id}:oauth`, client: (id) => `ai:conn:${id}:client_secret`, state: (h) => `ai:oauth:${h}` };
@@ -42,7 +42,7 @@ function checkOauth(x) {
if (!isUrl(x.authorizeUrl) || !isUrl(x.tokenUrl)) throw bad('bad_oauth', 'authorizeUrl·tokenUrl 은 https 주소여야 합니다'); if (!clip(x.clientId, 200)) throw bad('bad_oauth', 'clientId 가 필요합니다');
return { authorizeUrl: x.authorizeUrl, tokenUrl: x.tokenUrl, clientId: clip(x.clientId, 200), scopes: Array.isArray(x.scopes) ? x.scopes.map((s) => clip(s, 100)).filter(Boolean).slice(0, 30) : [] };
}
function checkCli(x) { if (x == null) return null; if (typeof x !== 'object') throw bad('bad_cli', 'CLI 설정은 객체여야 합니다'); const out = {}; if (x.bin != null) { const b = clip(x.bin, 400); if (b && !b.startsWith('/')) throw bad('bad_cli', 'CLI 실행 파일은 절대 경로여야 합니다'); out.bin = b || undefined; } if (Array.isArray(x.args)) out.args = x.args.map((a) => clip(a, 200)).filter(Boolean).slice(0, 20); if (x.timeoutMs != null) out.timeoutMs = Math.min(3600000, Math.max(10000, Number(x.timeoutMs) || 600000)); return out; }
function checkCli(x) { if (x == null) return null; if (typeof x !== 'object') throw bad('bad_cli', 'CLI 설정은 객체여야 합니다'); const out = {}; if (x.tool != null && x.tool !== '') { if (!CLI_TOOLS[x.tool]) throw bad('bad_cli', `지원하지 않는 CLI 종류: ${x.tool} (${Object.keys(CLI_TOOLS).join('·')})`); out.tool = x.tool; } if (x.bin != null) { const b = clip(x.bin, 400); if (b && !b.startsWith('/')) throw bad('bad_cli', 'CLI 실행 파일은 절대 경로여야 합니다'); out.bin = b || undefined; } if (Array.isArray(x.args)) out.args = x.args.map((a) => clip(a, 200)).filter(Boolean).slice(0, 20); if (x.timeoutMs != null) out.timeoutMs = Math.min(3600000, Math.max(10000, Number(x.timeoutMs) || 600000)); return out; }
function nameFree(d, name, exceptId = null) { const r = d.store.get('SELECT id FROM ai_connections WHERE lower(name)=lower(?)', name); return !r || r.id === exceptId; }
/** 연결 만들기. 비밀값(apiKey·oauth.clientSecret)은 Vault 로만 가고 행·감사에는 들어가지 않는다. */
@@ -50,8 +50,9 @@ export function create(d, b, by) {
const name = clip(b.name, 60); if (!name) throw bad('bad_name', '이름이 필요합니다(1~60자)'); if (!nameFree(d, name)) throw new HttpError(409, 'name_taken', '같은 이름의 연결이 있습니다');
const prov = PROVIDERS[b.provider]; if (!prov) throw bad('bad_provider', `알 수 없는 공급자: ${b.provider}`); const authKind = String(b.authKind || ''); if (!prov.authKinds.includes(authKind)) throw bad('bad_auth_kind', `${prov.label} 는 ${prov.authKinds.join('·')} 방식만 지원합니다`);
if (b.baseUrl != null && b.baseUrl !== '' && !isUrl(b.baseUrl, true)) throw bad('bad_base_url', 'baseUrl 은 http(s) 주소여야 합니다');
const model = clip(b.model, 120) || (b.provider === 'local-cli' ? 'claude-opus-5-5' : ''); if (!model) throw bad('bad_model', '기본 모델이 필요합니다');
const identity = checkIdentity(b.identity); const oauth = authKind === 'oauth' ? checkOauth(b.oauth) : null; const cli = b.provider === 'local-cli' ? checkCli(b.cli) || {} : null;
if (cli && !cli.tool) cli.tool = cli.bin && CLI_TOOLS[cli.bin.split('/').pop()] ? cli.bin.split('/').pop() : 'claude'; // [0.3.1] CLI 종류: 지정 → 실행 파일 이름 → claude
const model = clip(b.model, 120) || (cli ? cliDefaultModel(cli.tool) : ''); if (!model) throw bad('bad_model', '기본 모델이 필요합니다');
if (authKind === 'api_key' && (typeof b.apiKey !== 'string' || b.apiKey.trim().length < 8)) throw bad('bad_api_key', 'API 키가 필요합니다');
const id = newId('aic_'); const pos = (d.store.get('SELECT COALESCE(MAX(position),0) AS p FROM ai_connections').p || 0) + 1; const status = authKind === 'oauth' ? 'reauth_required' : 'active';
d.store.run('INSERT INTO ai_connections(id, name, tab_label, provider, auth_kind, base_url, model, models_json, identity_json, oauth_json, cli_json, status, position, created_by, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', id, name, null, b.provider, authKind, b.baseUrl || null, model, '[]', toJson(identity), oauth ? toJson(oauth) : null, cli ? toJson(cli) : null, status, pos, by || null, nowIso(), nowIso());
@@ -116,12 +117,14 @@ export async function testConnection(d, id, by) {
try {
const secret = await secretFor(d, conn); const r = await providerModels(d, conn, secret);
d.store.run('UPDATE ai_connections SET models_json=?, updated_at=? WHERE id=?', toJson(r.models || []), nowIso(), id); setStatus(d, id, 'active', null, true);
audit(d.store, { actorType: 'operator', actorId: by, action: 'ai.connection.test', subjectType: 'ai_connection', subjectId: id, outcome: 'ok', detail: { models: (r.models || []).length, cliVersion: r.cliVersion || null } });
return { models: r.models || [], cliVersion: r.cliVersion || null, connection: get(d, id) };
// [0.3.1] 로컬 CLI: 탐색한 실행 파일·버전·로그인 상태를 연결에 남긴다(화면 표시, 다음 실행은 같은 파일). 운영자가 bin 을 직접 적었으면 그대로 둔다.
if (r.cli) { const prev = parseJson(row(d, id).cli_json, {}) || {}; d.store.run('UPDATE ai_connections SET cli_json=? WHERE id=?', toJson({ ...prev, tool: r.cli.tool, bin: prev.bin || r.cli.bin, version: r.cli.version, loggedIn: r.cli.loggedIn, loginMethod: r.cli.loginMethod, checkedAt: nowIso() }), id); }
audit(d.store, { actorType: 'operator', actorId: by, action: 'ai.connection.test', subjectType: 'ai_connection', subjectId: id, outcome: 'ok', detail: { models: (r.models || []).length, cliVersion: r.cliVersion || null, loggedIn: r.loggedIn ?? null } });
return { models: r.models || [], cliVersion: r.cliVersion || null, loggedIn: r.loggedIn ?? null, connection: get(d, id) };
} catch (e) {
const msg = safeError(e); const code = e.code || 'provider_error'; setStatus(d, id, code === 'oauth_required' || code === 'oauth_expired' || code === 'provider_401' ? 'reauth_required' : 'error', msg);
const msg = safeError(e); const code = e.code || 'provider_error'; setStatus(d, id, ['oauth_required', 'oauth_expired', 'provider_401', 'cli_not_logged_in'].includes(code) ? 'reauth_required' : 'error', msg);
audit(d.store, { actorType: 'operator', actorId: by, action: 'ai.connection.test', subjectType: 'ai_connection', subjectId: id, outcome: 'failed', detail: { code, message: msg } });
throw new HttpError(e.status && e.status < 500 && e.status !== 409 ? e.status : 502, code, msg);
throw new HttpError(e.status && e.status < 500 && e.status !== 409 ? e.status : 424, code, msg); // 424(의존성 실패): 5xx 로 내면 화면에 메시지가 숨겨지므로(일시적 오류 문구) 원인을 그대로 보여 준다
}
}
// ---------------------------------------------------------------- OAuth(PKCE)
+1 -1
View File
@@ -105,7 +105,7 @@ export function createEngine(d) {
function fail(room, conn, relayDepth, e) {
const msg = safeError(e); const code = e && e.code ? e.code : 'provider_error';
R.appendMessage(d, { roomId: room.id, role: 'assistant', connectionId: conn.id, author: conn.name, content: [{ type: 'text', text: '' }], relayDepth, status: 'failed', error: `${code}: ${msg}` });
if (code === 'oauth_required' || code === 'oauth_expired' || code === 'provider_401') d.store.run('UPDATE ai_connections SET status=CASE WHEN status=\'disabled\' THEN status ELSE \'reauth_required\' END, last_error=?, updated_at=? WHERE id=?', msg, nowIso(), conn.id);
if (['oauth_required', 'oauth_expired', 'provider_401', 'cli_not_logged_in'].includes(code)) d.store.run('UPDATE ai_connections SET status=CASE WHEN status=\'disabled\' THEN status ELSE \'reauth_required\' END, last_error=?, updated_at=? WHERE id=?', msg, nowIso(), conn.id);
else d.store.run('UPDATE ai_connections SET last_error=?, updated_at=? WHERE id=?', msg, nowIso(), conn.id);
audit(d.store, { actorType: 'system', actorId: `ai:${conn.id}`, action: 'ai.turn.failed', subjectType: 'ai_room', subjectId: room.id, outcome: 'failed', automatic: true, detail: { connection: conn.id, code, message: msg } });
}
+88 -25
View File
@@ -4,7 +4,7 @@
* 공급자
* - anthropic : Messages API(POST {base}/messages, GET {base}/models). API 키는 `x-api-key`, OAuth 는 `Authorization: Bearer`.
* - openai : OpenAI 호환 Chat Completions(POST {base}/chat/completions, GET {base}/models). base_url 을 바꾸면 호환 공급자도 쓴다. 키·토큰은 Bearer.
* - local-cli : 서버에 설치된 Claude Code CLI 의 **로그인 세션**으로 `claude -p … --output-format json` 을 실행한다(Webmaker 의 lib/claude.js 와 같은 계열).
* - local-cli : 서버에 설치된 CLI 의 **로그인 세션** — Claude Code(`claude -p … --output-format json`) 또는 OpenAI Codex(`codex exec --json -s read-only …`). [0.3.1] 설치 위치를 자동 탐색한다(아래).
* CLI 에는 HAL 도구를 넘기지 않는다(대화·분석 전용). 세션 파일·자격은 HAL 이 읽지도 전달하지도 않는다. 환경 변수는 PATH·HOME 등 최소만 넘긴다(Vault 키 등 HAL 환경 비노출).
*
* 공통 블록 형식
@@ -14,13 +14,15 @@
* 비밀값은 인자(secret)로만 받아 요청 헤더에만 넣는다. 오류 메시지에 헤더·키를 넣지 않는다.
*/
import { spawn, execFile } from 'node:child_process';
import { accessSync, constants } from 'node:fs';
import { accessSync, constants, statSync, realpathSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
import { join, basename } from 'node:path';
import { homedir, tmpdir } from 'node:os';
export class ProviderError extends Error { constructor(code, message, { status = 502, detail } = {}) { super(message); this.code = code; this.status = status; this.detail = detail; } }
export const PROVIDERS = {
anthropic: { label: 'Anthropic(Claude)', authKinds: ['api_key', 'oauth'], defaultBase: 'https://api.anthropic.com/v1', tools: true },
openai: { label: 'OpenAI 호환', authKinds: ['api_key', 'oauth'], defaultBase: 'https://api.openai.com/v1', tools: true },
'local-cli': { label: '로컬 CLI 로그인 세션(Claude Code)', authKinds: ['login'], defaultBase: null, tools: false },
'local-cli': { label: '로컬 CLI 로그인 세션(Claude Code·Codex)', authKinds: ['login'], defaultBase: null, tools: false },
};
const base = (conn) => String(conn.baseUrl || PROVIDERS[conn.provider].defaultBase || '').replace(/\/+$/, '');
const fetchOf = (d) => d.fetch || fetch;
@@ -34,7 +36,7 @@ function providerFail(status, j) { const e = j && j.error ? (typeof j.error ===
/** 사용 가능한 모델 목록(실제 공급자 응답). local-cli 는 실행 파일 확인으로 대신한다. */
export async function listModels(d, conn, secret) {
if (conn.provider === 'local-cli') { const info = await cliInfo(conn); return { models: [conn.model].filter(Boolean), cliVersion: info.version }; }
if (conn.provider === 'local-cli') { const info = await cliInfo(conn); if (info.loggedIn === false) throw new ProviderError('cli_not_logged_in', `${info.label}(${info.bin})에 로그인되어 있지 않습니다 — 서버(HAL 실행 계정)에서 '${info.loginCommand}' 을 실행하세요. HAL 이 대신 로그인할 수 없습니다`, { status: 502 }); return { models: info.models.length ? info.models : [conn.model].filter(Boolean), cliVersion: info.version, loggedIn: info.loggedIn, cli: info }; }
const r = await fetchOf(d)(`${base(conn)}/models`, { method: 'GET', headers: { ...authHeaders(conn, secret), 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(20000) });
const j = await readJson(r); if (!r.ok) throw providerFail(r.status, j);
const models = ((j && j.data) || []).map((m) => m.id).filter(Boolean);
@@ -87,34 +89,95 @@ async function chatOpenai(d, conn, secret, { system, messages, tools, maxTokens
for (const c of msg.tool_calls || []) { let input = {}; try { input = c.function?.arguments ? JSON.parse(c.function.arguments) : {}; } catch (_) { input = { __parse_error: String(c.function?.arguments || '').slice(0, 200) }; } blocks.push({ type: 'tool_use', id: c.id, name: c.function?.name, input }); }
return { blocks, usage: { inputTokens: j.usage?.prompt_tokens ?? null, outputTokens: j.usage?.completion_tokens ?? null }, stopReason: j.choices[0].finish_reason || null, model: j.model || conn.model };
}
// ---------------------------------------------------------------- 로컬 CLI(로그인 세션)
/** HAL 프로세스 환경을 CLI 에 넘기지 않는다(ARIWEB_VAULT_KEY 등). 로그인 세션은 CLI 가 HOME 아래 자기 설정에서 스스로 읽는다. */
const cliEnv = () => { const e = {}; for (const k of ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TERM', 'TMPDIR']) if (process.env[k]) e[k] = process.env[k]; return e; };
const cliBin = (conn) => (conn.cli && conn.cli.bin) || process.env.CLAUDE_BIN || 'claude';
export function cliInfo(conn) {
const bin = cliBin(conn);
return new Promise((resolve, reject) => {
try { accessSync(bin, constants.X_OK); } catch (_) { if (bin.includes('/')) return reject(new ProviderError('cli_unavailable', `CLI 실행 파일을 찾지 못했거나 실행할 수 없습니다: ${bin}`)); }
execFile(bin, ['--version'], { env: cliEnv(), timeout: 15000 }, (err, stdout) => { if (err) return reject(new ProviderError('cli_unavailable', `CLI 실행 파일을 실행할 수 없습니다(${bin}): ${err.code || err.message}`)); resolve({ bin, version: String(stdout || '').trim().split('\n')[0] }); });
});
// ---------------------------------------------------------------- 로컬 CLI(로그인 세션): claude(Claude Code) · codex(OpenAI Codex CLI)
/**
* [0.3.1] 자동 탐색. HAL 서비스(systemd)의 PATH 에는 사용자 설치 위치(~/.local/bin 등)가 없어 0.3.0 은 bear 에 설치된 CLI 를 찾지 못했다.
* 탐색 순서: 환경 변수(CLAUDE_BIN·CODEX_BIN) → HAL_CLI_DIRS(있으면 이것만) → HOME 의 알려진 설치 위치(~/.local/bin, ~/.npm-global/bin, ~/.claude/local, ~/.codex/packages/standalone/current/bin, ~/node_modules/.bin)
* → /usr/local/bin·/usr/bin → PATH. HOME 은 HAL 실행 계정(HAL_CLI_HOME 으로 바꿀 수 있다 — 테스트용). 심볼릭 링크(~/.local/bin/claude → ~/.local/share/claude/versions/…)도 실행 가능하면 인정.
* 로그인 상태: claude 는 `claude auth status`(JSON loggedIn), codex 는 `codex login status`("Logged in …"). 로그인 안 됨은 HAL 이 대신할 수 없다 — 서버에서 그 계정으로 `claude login` / `codex login`.
*/
export const CLI_TOOLS = {
claude: { label: 'Claude Code CLI', defaultModel: 'claude-opus-5-5', loginCommand: 'claude login', envBin: 'CLAUDE_BIN' },
codex: { label: 'OpenAI Codex CLI', defaultModel: 'gpt-5.5', loginCommand: 'codex login', envBin: 'CODEX_BIN' },
};
const cliHome = () => process.env.HAL_CLI_HOME || homedir();
/** HAL 프로세스 환경을 CLI 에 넘기지 않는다(ARIWEB_VAULT_KEY 등). 로그인 세션은 CLI 가 HOME 아래 자기 설정에서 스스로 읽는다. PATH 에는 탐색 위치를 더해 CLI 가 자기 보조 실행 파일(node 등)을 찾게 한다. */
const cliEnv = () => { const e = {}; for (const k of ['LANG', 'LC_ALL', 'TERM', 'TMPDIR']) if (process.env[k]) e[k] = process.env[k]; e.HOME = cliHome(); e.PATH = [...new Set([...(process.env.PATH || '').split(':'), ...cliSearchDirs()])].filter(Boolean).join(':'); return e; };
const isExec = (p) => { try { accessSync(p, constants.X_OK); return statSync(p).isFile(); } catch (_) { return false; } };
export function cliSearchDirs() {
const h = cliHome(); const forced = (process.env.HAL_CLI_DIRS || '').split(':').filter(Boolean); if (forced.length) return forced;
return [...new Set([join(h, '.local', 'bin'), join(h, '.npm-global', 'bin'), join(h, '.claude', 'local'), join(h, '.codex', 'packages', 'standalone', 'current', 'bin'), join(h, 'node_modules', '.bin'), '/usr/local/bin', '/usr/bin', ...(process.env.PATH || '').split(':').filter(Boolean)])];
}
export function findCliBin(tool) {
const t = CLI_TOOLS[tool]; if (!t) return null; const env = process.env[t.envBin]; if (env && isExec(env)) return env;
for (const d of cliSearchDirs()) { const p = join(d, tool); if (isExec(p)) return p; } return null;
}
const runCli = (bin, args, timeout = 20000) => new Promise((resolve) => execFile(bin, args, { env: cliEnv(), timeout, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => resolve({ err, stdout: String(stdout || ''), stderr: String(stderr || '') })));
/** 로그인 상태. loggedIn: true/false/null(알 수 없음 — 막지 않는다) */
export async function cliLoginStatus(tool, bin) {
if (tool === 'claude') { const r = await runCli(bin, ['auth', 'status']); try { const j = JSON.parse(r.stdout.trim()); return { loggedIn: 'loggedIn' in j ? !!j.loggedIn : null, method: j.authMethod || null }; } catch (_) { return { loggedIn: null, method: null }; } }
if (tool === 'codex') { const r = await runCli(bin, ['login', 'status']); const t = r.stdout + '\n' + r.stderr; if (/not logged in/i.test(t)) return { loggedIn: false, method: null }; if (/logged in/i.test(t)) return { loggedIn: true, method: /chatgpt/i.test(t) ? 'chatgpt' : /api key/i.test(t) ? 'api_key' : null }; return { loggedIn: null, method: null }; }
return { loggedIn: null, method: null };
}
/** codex 가 로그인 상태로 실행될 때 백엔드 모델 목록을 ~/.codex/models_cache.json 에 둔다(Webmaker engine-codex 와 같은 해석). 숨김(visibility=hide)은 뺀다. */
export function codexModels() { try { const j = JSON.parse(readFileSync(join(cliHome(), '.codex', 'models_cache.json'), 'utf8')); const ms = Array.isArray(j) ? j : (j.models || []); return ms.filter((m) => m && m.slug && m.visibility !== 'hide').map((m) => m.slug); } catch (_) { return []; } }
export function codexDefaultModel() { try { const m = readFileSync(join(cliHome(), '.codex', 'config.toml'), 'utf8').match(/^model\s*=\s*"([^"]+)"/m); return m ? m[1] : null; } catch (_) { return null; } }
export function cliDefaultModel(tool) { if (tool === 'codex') return codexDefaultModel() || codexModels()[0] || CLI_TOOLS.codex.defaultModel; return CLI_TOOLS.claude.defaultModel; }
/** 연결 설정의 CLI 종류: cli.tool → 실행 파일 이름 → claude */
export function cliToolOf(conn) { const c = conn.cli || {}; if (c.tool && CLI_TOOLS[c.tool]) return c.tool; if (c.bin) { const b = basename(c.bin); if (CLI_TOOLS[b]) return b; } return 'claude'; }
export const cliBin = (conn) => (conn.cli && conn.cli.bin) || findCliBin(cliToolOf(conn)) || null;
/** 서버에서 찾은 CLI 전부(버전·로그인·기본 모델·모델 목록). AI 연동 화면과 /ops/api/ai/cli 가 쓴다. */
export async function discoverClis() {
const clis = [];
for (const tool of Object.keys(CLI_TOOLS)) {
const bin = findCliBin(tool); if (!bin) continue; const t = CLI_TOOLS[tool];
const v = await runCli(bin, ['--version'], 15000); const login = await cliLoginStatus(tool, bin); let realpath = bin; try { realpath = realpathSync(bin); } catch (_) {}
clis.push({ tool, label: t.label, bin, realpath, version: v.err ? null : v.stdout.trim().split('\n')[0], versionError: v.err ? (v.err.code || v.err.message) : null, loggedIn: login.loggedIn, loginMethod: login.method, defaultModel: cliDefaultModel(tool), models: tool === 'codex' ? codexModels() : [], loginHint: login.loggedIn === false ? `서버(HAL 실행 계정)에서 '${t.loginCommand}' 을 실행해 로그인하세요 — HAL 이 대신 로그인할 수 없습니다` : null });
}
return { clis, searched: cliSearchDirs(), home: cliHome() };
}
export async function cliInfo(conn) {
const tool = cliToolOf(conn); const t = CLI_TOOLS[tool]; const bin = cliBin(conn);
if (!bin || !isExec(bin)) throw new ProviderError('cli_unavailable', `${t.label} 실행 파일을 찾지 못했습니다(탐색 위치: ${cliSearchDirs().slice(0, 7).join(', ')}). 서버에 설치하거나 연결 설정에 절대 경로를 적으세요.`);
const v = await runCli(bin, ['--version'], 15000); if (v.err) throw new ProviderError('cli_unavailable', `CLI 실행 파일을 실행할 수 없습니다(${bin}): ${v.err.code || v.err.message}`);
const login = await cliLoginStatus(tool, bin);
return { tool, label: t.label, bin, version: v.stdout.trim().split('\n')[0], loggedIn: login.loggedIn, loginMethod: login.method, models: tool === 'codex' ? codexModels() : [], defaultModel: cliDefaultModel(tool), loginCommand: t.loginCommand };
}
/** 대화 기록을 CLI 프롬프트 글로 편다(도구 없음). */
function transcriptText(messages) {
return messages.map((m) => m.content.filter((b) => b.type === 'text').map((b) => `${m.role === 'assistant' ? '[나]' : '[운영자/참여자]'} ${b.text}`).join('\n')).filter(Boolean).join('\n\n');
}
function chatCli(conn, { system, messages }) {
const bin = cliBin(conn); const prompt = transcriptText(messages) + '\n\n위 대화의 마지막 발언에 답하라.';
const args = ['-p', prompt, '--output-format', 'json', '--model', conn.model || 'claude-opus-5-5', '--append-system-prompt', system, '--no-session-persistence', ...((conn.cli && Array.isArray(conn.cli.args)) ? conn.cli.args.filter((a) => typeof a === 'string' && a.length < 200) : [])];
/** 자식 프로세스 실행 공통: 프로세스 그룹으로 띄워 시간 초과 때 통째로 끝낸다. */
function spawnCollect(bin, args, { cwd, timeoutMs }) {
return new Promise((resolve, reject) => {
let child; try { child = spawn(bin, args, { env: cliEnv(), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); } catch (e) { return reject(new ProviderError('cli_unavailable', `CLI 실행 실패: ${e.message}`)); }
let out = ''; let err = ''; const timer = setTimeout(() => { try { process.kill(-child.pid, 'SIGTERM'); } catch (_) {} }, (conn.cli && conn.cli.timeoutMs) || 10 * 60 * 1000);
let child; try { child = spawn(bin, args, { cwd, env: cliEnv(), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); } catch (e) { return reject(new ProviderError('cli_unavailable', `CLI 실행 실패: ${e.message}`)); }
let out = ''; let err = ''; const timer = setTimeout(() => { try { process.kill(-child.pid, 'SIGTERM'); } catch (_) {} }, timeoutMs);
child.stdout.on('data', (c) => { out += c.toString(); if (out.length > 4 * 1024 * 1024) out = out.slice(-4 * 1024 * 1024); }); child.stderr.on('data', (c) => { err += c.toString(); if (err.length > 20000) err = err.slice(-20000); });
child.on('error', (e) => { clearTimeout(timer); reject(new ProviderError('cli_unavailable', `CLI 실행 파일을 실행할 수 없습니다(${bin}): ${e.code || e.message}`)); });
child.on('close', (code) => {
clearTimeout(timer); let j = null; const lines = out.trim().split('\n'); for (let i = lines.length - 1; i >= 0 && !j; i--) { try { const x = JSON.parse(lines[i]); if (x && (x.type === 'result' || x.result !== undefined)) j = x; } catch (_) {} }
if (code !== 0 && !j) return reject(new ProviderError('cli_failed', `CLI 종료 코드 ${code}: ${err.trim().split('\n').pop() || '출력 없음'}`));
if (!j) return reject(new ProviderError('bad_response', 'CLI 가 JSON 결과를 내지 않았습니다'));
resolve({ blocks: [{ type: 'text', text: String(j.result ?? j.text ?? '') }], usage: { inputTokens: j.usage?.input_tokens ?? null, outputTokens: j.usage?.output_tokens ?? null }, stopReason: j.is_error ? 'error' : 'end_turn', model: conn.model, sessionId: j.session_id || null });
});
child.on('close', (code) => { clearTimeout(timer); resolve({ code, out, err }); });
});
}
function chatCli(conn, { system, messages }) {
const tool = cliToolOf(conn); const bin = cliBin(conn); if (!bin) return Promise.reject(new ProviderError('cli_unavailable', `${CLI_TOOLS[tool].label} 실행 파일을 찾지 못했습니다 — AI 연동 화면에서 "확인"으로 탐색 결과를 보세요`));
return tool === 'codex' ? chatCodex(conn, bin, { system, messages }) : chatClaude(conn, bin, { system, messages });
}
async function chatClaude(conn, bin, { system, messages }) {
const prompt = transcriptText(messages) + '\n\n위 대화의 마지막 발언에 답하라.';
const args = ['-p', prompt, '--output-format', 'json', '--model', conn.model || CLI_TOOLS.claude.defaultModel, '--append-system-prompt', system, '--no-session-persistence', ...((conn.cli && Array.isArray(conn.cli.args)) ? conn.cli.args.filter((a) => typeof a === 'string' && a.length < 200) : [])];
const { code, out, err } = await spawnCollect(bin, args, { cwd: undefined, timeoutMs: (conn.cli && conn.cli.timeoutMs) || 10 * 60 * 1000 });
let j = null; const lines = out.trim().split('\n'); for (let i = lines.length - 1; i >= 0 && !j; i--) { try { const x = JSON.parse(lines[i]); if (x && (x.type === 'result' || x.result !== undefined)) j = x; } catch (_) {} }
if (code !== 0 && !j) throw new ProviderError('cli_failed', `CLI 종료 코드 ${code}: ${err.trim().split('\n').pop() || '출력 없음'}`);
if (!j) throw new ProviderError('bad_response', 'CLI 가 JSON 결과를 내지 않았습니다');
if (j.is_error) { const msg = String(j.result || '오류'); throw new ProviderError(/authenticate|login|OAuth/i.test(msg) ? 'cli_not_logged_in' : 'cli_failed', `Claude Code CLI 오류: ${msg}${/authenticate|login|OAuth/i.test(msg) ? ` — 서버에서 '${CLI_TOOLS.claude.loginCommand}' 로 다시 로그인하세요` : ''}`); }
return { blocks: [{ type: 'text', text: String(j.result ?? j.text ?? '') }], usage: { inputTokens: j.usage?.input_tokens ?? null, outputTokens: j.usage?.output_tokens ?? null }, stopReason: 'end_turn', model: conn.model, sessionId: j.session_id || null };
}
/** codex exec --json: 읽기 전용 샌드박스·임시 작업 폴더·세션 비보존. JSONL 의 item.completed(agent_message) 가 답, turn.completed.usage 가 사용량. */
async function chatCodex(conn, bin, { system, messages }) {
const prompt = `${system}\n\n---\n${transcriptText(messages)}\n\n위 대화의 마지막 발언에 답하라.`; const dir = mkdtempSync(join(tmpdir(), 'hal-codex-'));
const args = ['exec', '--json', '-s', 'read-only', '--skip-git-repo-check', '--ephemeral', '-C', dir, '-m', conn.model || cliDefaultModel('codex'), prompt, ...((conn.cli && Array.isArray(conn.cli.args)) ? conn.cli.args.filter((a) => typeof a === 'string' && a.length < 200) : [])];
let res; try { res = await spawnCollect(bin, args, { cwd: dir, timeoutMs: (conn.cli && conn.cli.timeoutMs) || 10 * 60 * 1000 }); } finally { try { rmSync(dir, { recursive: true, force: true }); } catch (_) {} }
let text = ''; let usage = { inputTokens: null, outputTokens: null }; let errText = '';
for (const line of res.out.split('\n')) { let ev; try { ev = JSON.parse(line); } catch (_) { continue; } if (!ev || typeof ev !== 'object') continue; if (ev.type === 'item.completed' && ev.item && ev.item.type === 'agent_message' && ev.item.text) text = String(ev.item.text).trim(); else if (ev.type === 'turn.completed' && ev.usage) usage = { inputTokens: ev.usage.input_tokens ?? null, outputTokens: ev.usage.output_tokens ?? null }; else if (ev.type === 'error') errText = String(ev.message || ev.error || JSON.stringify(ev)).slice(0, 300); }
if (!text) { const tail = errText || res.err.trim().split('\n').pop() || `종료 코드 ${res.code}`; throw new ProviderError(/login|auth|unauthorized|401/i.test(tail) ? 'cli_not_logged_in' : 'cli_failed', `Codex CLI 오류: ${tail}${/login|auth|unauthorized|401/i.test(tail) ? ` — 서버에서 '${CLI_TOOLS.codex.loginCommand}' 을 실행하세요` : ''}`); }
return { blocks: [{ type: 'text', text }], usage, stopReason: 'end_turn', model: conn.model };
}
+3 -2
View File
@@ -4,7 +4,7 @@
* 연결 GET/POST /ops/api/ai/connections · PATCH/DELETE /ops/api/ai/connections/:id · POST …/:id/secret · POST …/:id/test · POST …/:id/oauth/start · GET /ops/ai/oauth/callback
* 방 GET /ops/api/ai/rooms · PATCH /ops/api/ai/rooms/:id · GET/POST /ops/api/ai/rooms/:id/messages · POST /ops/api/ai/rooms/:id/reset
* 제안 GET /ops/api/ai/actions · POST /ops/api/ai/actions/:id/approve · POST /ops/api/ai/actions/:id/reject
* 도구 GET /ops/api/ai/tools · GET /ops/api/ai/skill
* 도구 GET /ops/api/ai/tools · GET /ops/api/ai/skill · GET /ops/api/ai/cli(0.3.1, 서버에 설치된 CLI 탐색)
*
* 보안 경계(기존 규칙을 그대로 적용, 약화 없음)
* - 인증 키 변경(API 키 등록·교체, OAuth client secret, 연결 삭제) → requireRecent(최근 10분 재인증).
@@ -25,6 +25,7 @@ export function registerAiRoutes(app, d, { requireRecent, threeStep, wrap }) {
app.delete('/ops/api/ai/connections/:id', wrap((ctx) => { requireRecent(ctx); return { ok: true, ...C.remove(d, ctx.params.id, ctx.operator.id) }; }));
app.post('/ops/api/ai/connections/:id/secret', wrap(async (ctx) => { requireRecent(ctx); const b = await ctx.body(); return { ok: true, connection: C.setSecret(d, ctx.params.id, b.apiKey, ctx.operator.id) }; }));
app.post('/ops/api/ai/connections/:id/test', wrap(async (ctx) => ({ ok: true, ...(await C.testConnection(d, ctx.params.id, ctx.operator.id)) })));
app.get('/ops/api/ai/cli', wrap(async () => ({ ok: true, ...(await discoverClis()), tools: Object.entries(CLI_TOOLS).map(([k, v]) => ({ tool: k, label: v.label, loginCommand: v.loginCommand })) }))); // [0.3.1] 서버에 설치된 CLI 자동 탐색(버전·로그인·기본 모델)
app.post('/ops/api/ai/connections/:id/oauth/start', wrap((ctx) => ({ ok: true, ...C.oauthStart(d, ctx.params.id, { operatorId: ctx.operator.id }) })));
app.get('/ops/ai/oauth/callback', wrap(async (ctx) => { if (!ctx.operator) throw new HttpError(401, 'unauthenticated', '운영자 로그인이 필요합니다'); if (ctx.query.error) throw new HttpError(400, 'oauth_denied', `공급자가 로그인을 거부했습니다: ${String(ctx.query.error).slice(0, 100)}`); const c = await C.oauthCallback(d, { code: ctx.query.code, state: ctx.query.state, operatorId: ctx.operator.id }); return ctx.redirect(`/ops/ai?oauth=ok&connection=${encodeURIComponent(c.id)}`); }));
// ---------------- 방·메시지
@@ -46,5 +47,5 @@ export function registerAiRoutes(app, d, { requireRecent, threeStep, wrap }) {
app.get('/ops/api/ai/skill', () => ({ ok: true, skill: SKILL_DOC }));
}
// providers 모듈을 여기서 직접 import 하지 않고 connections 를 통해 노출(순환 없음)
import { PROVIDERS } from './providers.mjs';
import { PROVIDERS, discoverClis, CLI_TOOLS } from './providers.mjs';
const C_PROVIDERS = () => PROVIDERS;