/** * opencode-plugin-sync.js — BADA 텔레메트리의 opencode 플러그인 설치기 * * 배경: Langfuse 텔레메트리는 Claude Code 훅(Stop 훅, src/langfuse-hook.js)으로만 * 구현되어 있어 opencode 세션에는 적용되지 않는 락인이 있었다(TR-027 후속). * opencode는 훅 대신 플러그인 체계(~/.config/opencode/plugin/*.js, @opencode-ai/plugin)를 * 사용하므로, 동등한 텔레메트리를 수행하는 플러그인 파일을 생성·설치한다. * * 플러그인 규약 실물 검증(2026-07-11, 로컬 ~/.cache/opencode/node_modules 기준): * - export const X: Plugin = async (input) => Hooks * - Hooks.event: async ({ event }) — event.type 'session.idle', properties.sessionID * 전송 형식은 Claude 훅의 파이썬 구현과 동일: POST {host}/api/public/ingestion * (trace-create + generation-create 배치, Basic 인증), 실패 시 * ~/.claude/langfuse_hook_backup.jsonl 백업 (파일 경로·페이로드 형식 호환 유지). */ const fs = require('fs'); const path = require('path'); const cliPaths = require('./cli-paths'); /** 플러그인 파일 버전 — 템플릿을 바꾸면 반드시 올릴 것 (설치기가 이 마커로 갱신 판단) */ const PLUGIN_VERSION = 'v2'; const PLUGIN_FILENAME = 'bada-telemetry.js'; const VERSION_MARKER = `// BADA-TELEMETRY-PLUGIN ${PLUGIN_VERSION}`; /** * opencode 플러그인 소스 생성. * 주의: 이 문자열은 opencode(Bun) 런타임에서 ESM으로 실행된다 — Electron 쪽 모듈을 * 참조할 수 없으므로 필요한 로직(설정 로드/스토리지 파싱/전송)을 전부 내장한다. * 세션 데이터 파싱 규약은 src/session-syncer-opencode.js 와 동일 (검증 완료 형식). */ function buildPluginSource(cliName = 'opencode') { return `${VERSION_MARKER} // 이 파일은 BADA Terminal이 자동 생성/갱신합니다. 직접 수정하지 마세요. // 역할: ${cliName} 세션이 유휴(session.idle) 상태가 될 때 세션 사용량을 Langfuse로 전송. // 문서: docs/TROUBLESHOOTING_REGISTRY.md TR-027, 설치기: src/config/opencode-plugin-sync.js import fs from "node:fs"; import path from "node:path"; import os from "node:os"; const CONFIG_PATH = path.join(os.homedir(), ".claude", "langfuse-config.json"); const BACKUP_LOG = path.join(os.homedir(), ".claude", "langfuse_hook_backup.jsonl"); const MIN_SEND_INTERVAL_MS = 60000; // 세션별 최소 전송 간격 (idle 다발 시 과전송 방지) function loadLangfuseConfig() { try { const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8")); if (!cfg.host || !cfg.publicKey || !cfg.secretKey) return null; return cfg; } catch { return null; } } function storageDir() { const dataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share"); return path.join(dataHome, "${cliName}", "storage"); } /** 세션 메타(ses_*.json)를 프로젝트 해시 디렉토리들에서 찾아 읽는다. */ function findSessionInfo(sessionID) { const root = path.join(storageDir(), "session"); try { for (const hashDir of fs.readdirSync(root)) { const p = path.join(root, hashDir, sessionID + ".json"); if (fs.existsSync(p)) { try { return JSON.parse(fs.readFileSync(p, "utf-8")); } catch { return null; } } } } catch { /* 스토리지 부재 등 — 조용히 스킵 */ } return null; } /** 세션 메시지/파트를 집계한다 (session-syncer-opencode.js와 동일 규약). */ function summarizeSession(sessionID) { const msgDir = path.join(storageDir(), "message", sessionID); const summary = { userMessages: 0, assistantMessages: 0, inputTokens: 0, outputTokens: 0, cacheRead: 0, cacheWrite: 0, cost: 0, model: "${cliName}-unknown", toolsUsed: new Set(), firstUserText: "" }; let files = []; try { files = fs.readdirSync(msgDir).filter(f => f.endsWith(".json")).sort(); } catch { return summary; } for (const f of files) { let msg; try { msg = JSON.parse(fs.readFileSync(path.join(msgDir, f), "utf-8")); } catch { continue; } if (msg.role === "user") { summary.userMessages++; if (!summary.firstUserText) { // 첫 사용자 메시지 미리보기: 해당 메시지의 text 파트에서 추출 try { const partDir = path.join(storageDir(), "part", msg.id); for (const pf of fs.readdirSync(partDir)) { const part = JSON.parse(fs.readFileSync(path.join(partDir, pf), "utf-8")); if (part.type === "text" && part.text) { summary.firstUserText = String(part.text).slice(0, 200); break; } } } catch { /* 파트 없음 — 무시 */ } } } else if (msg.role === "assistant") { summary.assistantMessages++; if (msg.modelID) summary.model = (msg.providerID ? msg.providerID + "/" : "") + msg.modelID; if (msg.tokens) { summary.inputTokens += msg.tokens.input || 0; summary.outputTokens += msg.tokens.output || 0; if (msg.tokens.cache) { summary.cacheRead += msg.tokens.cache.read || 0; summary.cacheWrite += msg.tokens.cache.write || 0; } } if (typeof msg.cost === "number") summary.cost += msg.cost; // 툴 사용 목록 (tool 파트) try { const partDir = path.join(storageDir(), "part", msg.id); for (const pf of fs.readdirSync(partDir)) { const part = JSON.parse(fs.readFileSync(path.join(partDir, pf), "utf-8")); if (part.type === "tool" && part.tool) summary.toolsUsed.add(part.tool); } } catch { /* 파트 없음 — 무시 */ } } } return summary; } async function sendToLangfuse(cfg, sessionID, info, s) { const now = new Date().toISOString(); const traceId = crypto.randomUUID(); const totalTokens = s.inputTokens + s.outputTokens; const credentials = Buffer.from(cfg.publicKey + ":" + cfg.secretKey).toString("base64"); const payload = { batch: [ { id: crypto.randomUUID(), type: "trace-create", timestamp: now, body: { id: traceId, name: "${cliName}-session", sessionId: sessionID, userId: process.env.USER || process.env.USERNAME || "unknown", input: s.firstUserText, output: "Session idle (" + totalTokens + " tokens)", metadata: { source: "bada-${cliName}-plugin", title: (info && info.title) || "", directory: (info && info.directory) || "", total_turns: s.userMessages + s.assistantMessages, user_messages: s.userMessages, assistant_messages: s.assistantMessages, tools_used: [...s.toolsUsed], estimated_cost_usd: Math.round(s.cost * 1e6) / 1e6 }, tags: ["${cliName}", "bada"] } }, { id: crypto.randomUUID(), type: "generation-create", timestamp: now, body: { id: crypto.randomUUID(), traceId, name: "${cliName}-generation", model: s.model, usage: { input: s.inputTokens, output: s.outputTokens, total: totalTokens, unit: "TOKENS" }, metadata: { cache_read_input_tokens: s.cacheRead, cache_creation_input_tokens: s.cacheWrite, estimated_cost_usd: Math.round(s.cost * 1e6) / 1e6 } } } ] }; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 5000); try { const res = await fetch((cfg.host.endsWith("/") ? cfg.host.slice(0, -1) : cfg.host) + "/api/public/ingestion", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Basic " + credentials }, body: JSON.stringify(payload), signal: controller.signal }); const result = await res.json().catch(() => ({})); return Array.isArray(result.successes) && result.successes.length > 0; } catch { return false; } finally { clearTimeout(timer); } } function saveBackup(sessionID, s) { try { fs.mkdirSync(path.dirname(BACKUP_LOG), { recursive: true }); const entry = { timestamp: new Date().toISOString(), session_id: sessionID, usage: { input_tokens: s.inputTokens, output_tokens: s.outputTokens }, summary: { source: "bada-${cliName}-plugin", cost: s.cost, tools: [...s.toolsUsed] } }; fs.appendFileSync(BACKUP_LOG, JSON.stringify(entry) + "\\n", "utf-8"); } catch { /* 백업 실패는 무시 (opencode 동작에 영향 금지) */ } } export const BadaTelemetryPlugin = async () => { // 세션별 전송 상태 (idle은 턴마다 발생 → 간격/변경량 기준 과전송 방지) const lastSent = new Map(); // sessionID → { at, msgCount } return { event: async ({ event }) => { try { if (!event || event.type !== "session.idle") return; const sessionID = event.properties && event.properties.sessionID; if (!sessionID) return; const cfg = loadLangfuseConfig(); if (!cfg) return; // Langfuse 미설정 — 완전 무동작 // 변경 감지: 메시지 수가 늘었고 최소 간격이 지났을 때만 전송 let msgCount = 0; try { msgCount = fs.readdirSync(path.join(storageDir(), "message", sessionID)).length; } catch {} const prev = lastSent.get(sessionID); if (prev && (msgCount <= prev.msgCount || Date.now() - prev.at < MIN_SEND_INTERVAL_MS)) return; const info = findSessionInfo(sessionID); const summary = summarizeSession(sessionID); const ok = await sendToLangfuse(cfg, sessionID, info, summary); if (!ok) saveBackup(sessionID, summary); lastSent.set(sessionID, { at: Date.now(), msgCount }); } catch { /* 어떤 예외도 opencode로 전파 금지 */ } } }; }; `; } /** * 활성 CLI가 opencode일 때 텔레메트리 플러그인을 설치/갱신한다. * - 대상: /plugin/bada-telemetry.js * - 멱등: 버전 마커가 같으면 아무것도 하지 않음 * - opencode 미설치(설정 홈 부재) 환경이면 디렉토리를 만들지 않고 스킵 * @returns {{ installed: boolean, reason?: string, path?: string }} */ function syncTelemetryPlugin() { try { const ctx = require('../context'); const activeCli = ctx.getActiveCli(); if (activeCli !== 'opencode' && activeCli !== 'codeagent') { return { installed: false, reason: '활성 CLI가 opencode/codeagent 아님' }; } const ocHome = cliPaths.getCliPaths(activeCli).homeDir; if (!fs.existsSync(ocHome)) { return { installed: false, reason: `${activeCli} 설정 홈 부재: ${ocHome}` }; } const pluginDir = path.join(ocHome, 'plugin'); const pluginPath = path.join(pluginDir, PLUGIN_FILENAME); // 멱등성: 동일 버전이면 재기록 생략 if (fs.existsSync(pluginPath)) { try { const head = fs.readFileSync(pluginPath, 'utf-8').split('\n', 1)[0]; if (head.trim() === VERSION_MARKER) { return { installed: false, reason: '이미 최신 버전', path: pluginPath }; } } catch (e) { /* intentional: 읽기 실패 시 재설치 시도 */ } } fs.mkdirSync(pluginDir, { recursive: true }); const tmpPath = pluginPath + '.tmp-' + process.pid; fs.writeFileSync(tmpPath, buildPluginSource(activeCli), 'utf-8'); fs.renameSync(tmpPath, pluginPath); // 원자적 교체 (기동 중 opencode의 부분 읽기 방지) console.log(`[OpencodePluginSync] ${activeCli} 텔레메트리 플러그인 설치/갱신 완료 ✓ (${PLUGIN_VERSION}): ${pluginPath}`); return { installed: true, path: pluginPath }; } catch (e) { const ctx = require('../context'); const activeCli = ctx.getActiveCli(); console.error(`[OpencodePluginSync] ${activeCli} 플러그인 설치 실패(무시하고 계속):`, e.message); return { installed: false, reason: e.message }; } } module.exports = { syncTelemetryPlugin, buildPluginSource, PLUGIN_VERSION };