-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlangfuse_plugin.js
More file actions
75 lines (69 loc) · 1.94 KB
/
Copy pathlangfuse_plugin.js
File metadata and controls
75 lines (69 loc) · 1.94 KB
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
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
const ALLOWED_EVENTS = new Set([
'session.created',
'session.idle',
'session.error',
'session.compacted',
'message.updated',
'message.part.updated',
]);
function resolveHookPath() {
if (process.env.OPENCODE_LANGFUSE_HOOK_PATH) {
return process.env.OPENCODE_LANGFUSE_HOOK_PATH;
}
return path.join(process.env.HOME || '~', '.config', 'opencode', 'hooks', 'langfuse_hook.py');
}
function debugDump(payload) {
try {
const enabled = String(process.env.OPENCODE_LANGFUSE_PLUGIN_DEBUG || '').toLowerCase();
if (!['1', 'true', 'yes', 'on'].includes(enabled)) return;
const stateDir = path.join(process.env.HOME || '~', '.config', 'opencode', 'state', 'langfuse');
fs.mkdirSync(stateDir, { recursive: true });
fs.appendFileSync(
path.join(stateDir, 'plugin_events.ndjson'),
JSON.stringify({ ts: new Date().toISOString(), payload }) + '\n',
'utf8',
);
} catch {
// fail-open
}
}
function findPython() {
for (const cmd of ['python3', 'python']) {
try {
const result = spawnSync(cmd, ['--version'], { timeout: 5000 });
if (result.status === 0) return cmd;
} catch {}
}
return 'python3'; // fallback
}
function forwardToHook(payload) {
try {
debugDump(payload);
spawnSync(findPython(), [resolveHookPath()], {
input: JSON.stringify(payload || {}),
stdio: ['pipe', 'ignore', 'ignore'],
env: process.env,
timeout: 5000,
});
} catch {
// fail-open: never block OpenCode
}
}
export const LangfuseOpenCodePlugin = async () => {
return {
event: async ({ event }) => {
const eventType = String(event?.type || '').toLowerCase();
if (!ALLOWED_EVENTS.has(eventType)) {
return;
}
forwardToHook({
source: 'opencode-plugin',
captured_at: new Date().toISOString(),
event,
});
},
};
};