File size: 12,079 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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | /**
* 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์ผ ๋ ํ
๋ ๋ฉํธ๋ฆฌ ํ๋ฌ๊ทธ์ธ์ ์ค์น/๊ฐฑ์ ํ๋ค.
* - ๋์: <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 };
|