/** * opencode-agent-sync.js — Claude Code 서브에이전트를 opencode 에이전트로 미러링 * * 배경: ~/.claude/agents/*.md 의 서브에이전트(analyst, architect, code-reviewer 등)는 * Claude Code 전용 발견 메커니즘이라 opencode에서는 전혀 인식되지 않는 락인이 있었다. * opencode는 ~/.config/opencode/agent/*.md (frontmatter=AgentConfig, 본문=프롬프트)를 * 읽으므로, 형식을 변환해 미러링한다. (규약 실측 검증: 2026-07-11, `opencode agent list`가 * 글로벌 agent/ 디렉토리의 .md를 subagent로 인식함 — TR-027 연장) * * 형식 대응: * - 파일명 → opencode 에이전트 이름 (동일 유지) * - description → description (없으면 미러링 제외 — opencode 스키마 필수값) * - (mode) → 'subagent' 고정 * - model 별칭(opus 등) → 생략 (opencode는 provider/model 형식 — 세션 모델 상속이 안전) * - tools/disallowedTools → opencode tools 맵(boolean)으로 변환 (알려진 툴명만) * - 본문 → 프롬프트 그대로 * * 안전 원칙: * 1) 생성 파일에는 BADA 미러 마커를 심고, 마커 있는 파일만 갱신/삭제한다 * (사용자가 직접 만든 opencode 에이전트는 절대 건드리지 않음). * 2) 원본이 사라진 미러 파일(고아)은 제거해 목록 오염을 막는다. * 3) 원본 해시가 같으면 재기록하지 않는다 (멱등). */ const fs = require('fs'); const path = require('path'); const os = require('os'); const crypto = require('crypto'); const cliPaths = require('./cli-paths'); /** 생성 파일 식별용 마커 (본문 최상단 HTML 주석) */ const MIRROR_MARKER = '\n\n${body.trim()}\n`; } /** * ~/.claude/agents/*.md 전체를 opencode 글로벌 agent 디렉토리로 미러링한다. * 활성 CLI가 opencode가 아니거나 opencode 미설치면 아무것도 하지 않는다. * @returns {{ synced: number, removed: number, skipped: number, reason?: string }} */ function syncClaudeAgentsToOpencode() { const result = { synced: 0, removed: 0, skipped: 0 }; const ctx = require('../context'); let activeCli; try { activeCli = ctx.getActiveCli(); } catch (e) { return { ...result, reason: '활성 CLI 확인 실패: ' + e.message }; } if (activeCli !== 'opencode' && activeCli !== 'codeagent') { return { ...result, reason: '활성 CLI가 opencode/codeagent 아님' }; } try { const ocHome = cliPaths.getCliPaths(activeCli).homeDir; if (!fs.existsSync(ocHome)) { return { ...result, reason: `${activeCli} 설정 홈 부재: ${ocHome}` }; } const srcDir = path.join(os.homedir(), '.claude', 'agents'); const dstDir = path.join(ocHome, 'agent'); const srcFiles = fs.existsSync(srcDir) ? fs.readdirSync(srcDir).filter(f => f.endsWith('.md')) : []; fs.mkdirSync(dstDir, { recursive: true }); // 1) 생성/갱신 — 원본 해시가 같으면 스킵 (멱등) const validTargets = new Set(); for (const file of srcFiles) { try { const content = fs.readFileSync(path.join(srcDir, file), 'utf-8'); const converted = convertAgentMd(path.basename(file, '.md'), content); if (!converted) { result.skipped++; continue; } const dstPath = path.join(dstDir, file); validTargets.add(file); if (fs.existsSync(dstPath)) { const existing = fs.readFileSync(dstPath, 'utf-8'); if (!existing.includes(MIRROR_MARKER)) { // 동명의 사용자 정의 에이전트 존재 — 덮어쓰지 않는다 (안전 원칙 1) result.skipped++; continue; } if (existing === converted) continue; // 변경 없음 } fs.writeFileSync(dstPath, converted, 'utf-8'); result.synced++; } catch (fileErr) { console.error(`[OpencodeAgentSync] 변환 실패(건너뜀): ${file} — ${fileErr.message}`); result.skipped++; } } // 2) 고아 미러 제거 — 마커 있는 파일 중 원본이 사라진 것만 for (const file of fs.readdirSync(dstDir).filter(f => f.endsWith('.md'))) { try { if (validTargets.has(file)) continue; const content = fs.readFileSync(path.join(dstDir, file), 'utf-8'); if (content.includes(MIRROR_MARKER) && !fs.existsSync(path.join(srcDir, file))) { fs.unlinkSync(path.join(dstDir, file)); result.removed++; } } catch (orphanErr) { console.error(`[OpencodeAgentSync] 고아 정리 실패(무시): ${file} — ${orphanErr.message}`); } } if (result.synced > 0 || result.removed > 0) { console.log(`[OpencodeAgentSync] ${activeCli} 서브에이전트 미러링 완료 ✓ (갱신 ${result.synced}, 제거 ${result.removed}, 스킵 ${result.skipped})`); } return result; } catch (e) { console.error(`[OpencodeAgentSync] ${activeCli} 미러링 실패(무시하고 계속):`, e.message); return { ...result, reason: e.message }; } } module.exports = { syncClaudeAgentsToOpencode, convertAgentMd, parseFrontmatter };