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 };