pi-langfuse 1.7.1 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/README_CN.md +20 -4
- package/dist/index.d.ts +14 -0
- package/dist/index.js +216 -0
- package/dist/src/capture-policy.d.ts +43 -0
- package/dist/src/capture-policy.js +125 -0
- package/dist/src/commands.d.ts +25 -0
- package/dist/src/commands.js +374 -0
- package/dist/src/config.d.ts +13 -0
- package/dist/src/config.js +157 -0
- package/dist/src/constants.d.ts +9 -0
- package/dist/src/constants.js +11 -0
- package/dist/src/handlers/agent.d.ts +18 -0
- package/dist/src/handlers/agent.js +310 -0
- package/dist/src/handlers/cache.d.ts +5 -0
- package/dist/src/handlers/cache.js +134 -0
- package/dist/src/handlers/generation.d.ts +9 -0
- package/dist/src/handlers/generation.js +249 -0
- package/dist/src/handlers/session.d.ts +4 -0
- package/dist/src/handlers/session.js +121 -0
- package/dist/src/handlers/system-state.d.ts +3 -0
- package/dist/src/handlers/system-state.js +185 -0
- package/dist/src/handlers/tool.d.ts +3 -0
- package/dist/src/handlers/tool.js +168 -0
- package/dist/src/handlers/turn.d.ts +2 -0
- package/dist/src/handlers/turn.js +48 -0
- package/dist/src/langfuse.d.ts +42 -0
- package/dist/src/langfuse.js +837 -0
- package/dist/src/limits.d.ts +43 -0
- package/dist/src/limits.js +63 -0
- package/dist/src/observation.d.ts +24 -0
- package/dist/src/observation.js +24 -0
- package/dist/src/redaction.d.ts +14 -0
- package/dist/src/redaction.js +254 -0
- package/dist/src/session-lineage.d.ts +15 -0
- package/dist/src/session-lineage.js +87 -0
- package/dist/src/source-metadata.d.ts +2 -0
- package/dist/src/source-metadata.js +55 -0
- package/dist/src/state.d.ts +52 -0
- package/dist/src/state.js +144 -0
- package/dist/src/types.d.ts +157 -0
- package/dist/src/types.js +1 -0
- package/dist/src/usage-options.d.ts +27 -0
- package/dist/src/usage-options.js +21 -0
- package/dist/src/utils.d.ts +61 -0
- package/dist/src/utils.js +600 -0
- package/dist/src/workflow.d.ts +24 -0
- package/dist/src/workflow.js +62 -0
- package/examples/workflow-sdk.mjs +56 -0
- package/index.ts +40 -12
- package/package.json +12 -1
- package/src/commands.ts +14 -3
- package/src/config.ts +1 -1
- package/src/handlers/agent.ts +60 -32
- package/src/handlers/cache.ts +12 -10
- package/src/handlers/session.ts +2 -2
- package/src/handlers/tool.ts +6 -1
- package/src/langfuse.ts +35 -16
- package/src/observation.ts +4 -0
- package/src/state.ts +12 -2
- package/src/types.ts +1 -1
- package/src/workflow.ts +78 -0
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { CONFIG_PATH } from "./constants.js";
|
|
3
|
+
import { loadConfig, loadConfigFromEnv, loadConfigFromFile, sanitizeConfigForLog, saveConfig, ensureConfig, } from "./config.js";
|
|
4
|
+
import { createCapturePolicy } from "./capture-policy.js";
|
|
5
|
+
import { getRuntime, getLastRuntimeError, forceShutdownRuntime as shutdownLangfuseRuntime } from "./langfuse.js";
|
|
6
|
+
import { getSessionRunState, state } from "./state.js";
|
|
7
|
+
import { isUnsampled } from "./workflow.js";
|
|
8
|
+
const PRIVACY_PRESETS = ["metadata-only", "prompts-only", "conversations", "full-debug"];
|
|
9
|
+
function notify(ctx, message, level = "info") {
|
|
10
|
+
if (ctx.hasUI && ctx.ui?.notify) {
|
|
11
|
+
ctx.ui.notify(message, level);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const prefix = level === "error" ? "❌" : level === "warning" ? "⚠️" : "📊";
|
|
15
|
+
const log = ctx.mode === "rpc" || ctx.mode === "json" ? console.error : console.log;
|
|
16
|
+
log(`${prefix} Langfuse: ${message}`);
|
|
17
|
+
}
|
|
18
|
+
function parseCommandArgs(args) {
|
|
19
|
+
const values = {};
|
|
20
|
+
const positional = [];
|
|
21
|
+
const malformed = [];
|
|
22
|
+
for (const part of args.trim().split(/\s+/)) {
|
|
23
|
+
if (!part) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const eq = part.indexOf("=");
|
|
27
|
+
if (eq === -1) {
|
|
28
|
+
positional.push(part);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (eq === 0) {
|
|
32
|
+
malformed.push(part);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
values[part.slice(0, eq)] = part.slice(eq + 1);
|
|
36
|
+
}
|
|
37
|
+
return { values, positional, malformed };
|
|
38
|
+
}
|
|
39
|
+
function isPrivacyPreset(value) {
|
|
40
|
+
return PRIVACY_PRESETS.includes(value);
|
|
41
|
+
}
|
|
42
|
+
function inferPreset(policy) {
|
|
43
|
+
const entries = [
|
|
44
|
+
[
|
|
45
|
+
"metadata-only",
|
|
46
|
+
{
|
|
47
|
+
captureInputs: false,
|
|
48
|
+
captureOutputs: false,
|
|
49
|
+
captureToolIo: false,
|
|
50
|
+
captureSystemPrompt: false,
|
|
51
|
+
captureCwd: false,
|
|
52
|
+
},
|
|
53
|
+
],
|
|
54
|
+
[
|
|
55
|
+
"prompts-only",
|
|
56
|
+
{
|
|
57
|
+
captureInputs: true,
|
|
58
|
+
captureOutputs: false,
|
|
59
|
+
captureToolIo: false,
|
|
60
|
+
captureSystemPrompt: false,
|
|
61
|
+
captureCwd: false,
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
[
|
|
65
|
+
"conversations",
|
|
66
|
+
{
|
|
67
|
+
captureInputs: true,
|
|
68
|
+
captureOutputs: true,
|
|
69
|
+
captureToolIo: false,
|
|
70
|
+
captureSystemPrompt: false,
|
|
71
|
+
captureCwd: false,
|
|
72
|
+
},
|
|
73
|
+
],
|
|
74
|
+
[
|
|
75
|
+
"full-debug",
|
|
76
|
+
{
|
|
77
|
+
captureInputs: true,
|
|
78
|
+
captureOutputs: true,
|
|
79
|
+
captureToolIo: true,
|
|
80
|
+
captureSystemPrompt: true,
|
|
81
|
+
captureCwd: true,
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
];
|
|
85
|
+
for (const [preset, presetPolicy] of entries) {
|
|
86
|
+
if (policy.captureInputs === presetPolicy.captureInputs &&
|
|
87
|
+
policy.captureOutputs === presetPolicy.captureOutputs &&
|
|
88
|
+
policy.captureToolIo === presetPolicy.captureToolIo &&
|
|
89
|
+
policy.captureSystemPrompt === presetPolicy.captureSystemPrompt &&
|
|
90
|
+
policy.captureCwd === presetPolicy.captureCwd) {
|
|
91
|
+
return preset;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return "custom";
|
|
95
|
+
}
|
|
96
|
+
function describePolicy(policy) {
|
|
97
|
+
return [
|
|
98
|
+
`captureInputs: ${policy.captureInputs}`,
|
|
99
|
+
`captureOutputs: ${policy.captureOutputs}`,
|
|
100
|
+
`captureToolIo: ${policy.captureToolIo}`,
|
|
101
|
+
`captureSystemPrompt: ${policy.captureSystemPrompt}`,
|
|
102
|
+
`captureCwd: ${policy.captureCwd}`,
|
|
103
|
+
`captureSourceMetadata: ${policy.captureSourceMetadata}`,
|
|
104
|
+
`capturePaths: ${policy.capturePaths}`,
|
|
105
|
+
].join("\n");
|
|
106
|
+
}
|
|
107
|
+
function flag(value) {
|
|
108
|
+
return value ? "on" : "off";
|
|
109
|
+
}
|
|
110
|
+
function readPersistedConfig(path) {
|
|
111
|
+
if (!existsSync(path)) {
|
|
112
|
+
return {};
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return {};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function hasActiveAgentObservation() {
|
|
122
|
+
for (const sessionState of state.sessionStates.values()) {
|
|
123
|
+
if (sessionState.agentState?.root) {
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
function configSource(env, configPath) {
|
|
130
|
+
const fileConfig = loadConfigFromFile(configPath, env);
|
|
131
|
+
const envConfig = loadConfigFromEnv(env);
|
|
132
|
+
if (fileConfig && envConfig) {
|
|
133
|
+
return "config file (env capture flags may override saved privacy)";
|
|
134
|
+
}
|
|
135
|
+
if (fileConfig) {
|
|
136
|
+
return "config file";
|
|
137
|
+
}
|
|
138
|
+
if (envConfig) {
|
|
139
|
+
return "environment variables";
|
|
140
|
+
}
|
|
141
|
+
return "none";
|
|
142
|
+
}
|
|
143
|
+
function lastErrorSummary() {
|
|
144
|
+
const lastError = getLastRuntimeError();
|
|
145
|
+
if (!lastError) {
|
|
146
|
+
return "none";
|
|
147
|
+
}
|
|
148
|
+
return `${lastError.scope}: ${lastError.message} (${lastError.timestamp.toISOString()})`;
|
|
149
|
+
}
|
|
150
|
+
function formatStatus(configPath, env) {
|
|
151
|
+
const config = loadConfig(env, configPath);
|
|
152
|
+
if (!config) {
|
|
153
|
+
return [
|
|
154
|
+
"pi-langfuse status:",
|
|
155
|
+
"State: not configured",
|
|
156
|
+
`Config file: ${configPath}`,
|
|
157
|
+
"Action: run /langfuse-setup or set LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY",
|
|
158
|
+
`Last error: ${lastErrorSummary()}`,
|
|
159
|
+
].join("\n");
|
|
160
|
+
}
|
|
161
|
+
const session = getSessionRunState();
|
|
162
|
+
const binding = session.runBinding ?? session.startupBinding;
|
|
163
|
+
const workflow = isUnsampled(binding) ? "upstream sampling disabled"
|
|
164
|
+
: binding?.parent ? "external parent (OTel only)"
|
|
165
|
+
: binding?.sessionId ? "external session group" : "independent";
|
|
166
|
+
const safeConfig = sanitizeConfigForLog(config);
|
|
167
|
+
const policy = config.capturePolicy ?? createCapturePolicy(env);
|
|
168
|
+
return [
|
|
169
|
+
"pi-langfuse status:",
|
|
170
|
+
"State: configured",
|
|
171
|
+
`Source: ${configSource(env, configPath)}`,
|
|
172
|
+
`Host: ${safeConfig?.host ?? config.host}`,
|
|
173
|
+
`Public key: ${safeConfig?.publicKey ?? "[REDACTED_SECRET]"}`,
|
|
174
|
+
`User ID: ${config.userId ? "configured" : "not set"}`,
|
|
175
|
+
`Config file: ${configPath}`,
|
|
176
|
+
`Privacy preset: ${inferPreset(policy)}`,
|
|
177
|
+
"Capture:",
|
|
178
|
+
` inputs: ${flag(policy.captureInputs)}`,
|
|
179
|
+
` outputs: ${flag(policy.captureOutputs)}`,
|
|
180
|
+
` tool IO: ${flag(policy.captureToolIo)}`,
|
|
181
|
+
` system prompt: ${flag(policy.captureSystemPrompt)}`,
|
|
182
|
+
` cwd: ${flag(policy.captureCwd)}`,
|
|
183
|
+
` absolute paths: ${flag(policy.capturePaths)}`,
|
|
184
|
+
`Workflow tracing: ${workflow}`,
|
|
185
|
+
`Active run: ${hasActiveAgentObservation() ? "yes" : "no"}`,
|
|
186
|
+
`Last error: ${lastErrorSummary()}`,
|
|
187
|
+
].join("\n");
|
|
188
|
+
}
|
|
189
|
+
// v4 events_only removes legacy reads; older servers may not expose v2 reads.
|
|
190
|
+
const READ_PROBE_WINDOW_MS = 6 * 60 * 60 * 1_000;
|
|
191
|
+
async function probeReadSurface(host, auth) {
|
|
192
|
+
const to = new Date();
|
|
193
|
+
const from = new Date(to.getTime() - READ_PROBE_WINDOW_MS);
|
|
194
|
+
const url = `${host}/api/public/v2/observations?fromStartTime=${from.toISOString()}&toStartTime=${to.toISOString()}&limit=1`;
|
|
195
|
+
for (const [name, endpoint] of [
|
|
196
|
+
["v2 observations", url],
|
|
197
|
+
["legacy observations", `${host}/api/public/observations?limit=1`],
|
|
198
|
+
]) {
|
|
199
|
+
try {
|
|
200
|
+
const response = await fetch(endpoint, {
|
|
201
|
+
headers: { Authorization: `Basic ${auth}` },
|
|
202
|
+
signal: AbortSignal.timeout(10_000),
|
|
203
|
+
});
|
|
204
|
+
if (name === "v2 observations" && (response.status === 404 || response.status === 405))
|
|
205
|
+
continue;
|
|
206
|
+
return {
|
|
207
|
+
message: `read: ${name} ${response.ok ? "ok" : `HTTP ${response.status}`}`,
|
|
208
|
+
warning: !response.ok,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
return { message: `read: ${name} failed: ${error instanceof Error ? error.message : String(error)}`, warning: true };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { message: "read: unavailable", warning: true };
|
|
216
|
+
}
|
|
217
|
+
async function checkLangfuseConnectivity(config) {
|
|
218
|
+
const host = config.host.replace(/\/+$/, "");
|
|
219
|
+
const auth = Buffer.from(`${config.publicKey}:${config.secretKey}`).toString("base64");
|
|
220
|
+
try {
|
|
221
|
+
const response = await fetch(`${host}/api/public/projects`, {
|
|
222
|
+
headers: {
|
|
223
|
+
Authorization: `Basic ${auth}`,
|
|
224
|
+
},
|
|
225
|
+
signal: AbortSignal.timeout(10_000),
|
|
226
|
+
});
|
|
227
|
+
if (response.ok) {
|
|
228
|
+
const read = await probeReadSurface(host, auth);
|
|
229
|
+
return { ok: true, message: `Connected to ${config.host}; ${read.message}`, warning: read.warning };
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
ok: false,
|
|
233
|
+
message: `${config.host} returned ${response.status} ${response.statusText}`.trim(),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
return {
|
|
238
|
+
ok: false,
|
|
239
|
+
message: error instanceof Error ? error.message : String(error),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
export async function handleLangfuseStatusCommand(args, ctx, deps = {}) {
|
|
244
|
+
const parsed = parseCommandArgs(args);
|
|
245
|
+
const unexpected = parsed.malformed[0] ?? parsed.positional[0] ?? Object.keys(parsed.values)[0];
|
|
246
|
+
if (unexpected) {
|
|
247
|
+
notify(ctx, `Unexpected argument '${unexpected}'. Usage: /langfuse-status`, "warning");
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
const env = deps.env ?? process.env;
|
|
251
|
+
const configPath = deps.configPath ?? CONFIG_PATH;
|
|
252
|
+
notify(ctx, formatStatus(configPath, env));
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
function savePrivacyPreset(requestedPreset, ctx, configPath) {
|
|
256
|
+
const existing = readPersistedConfig(configPath);
|
|
257
|
+
const loaded = state.config ?? loadConfig(process.env, configPath);
|
|
258
|
+
const publicKey = existing.publicKey ?? loaded?.publicKey;
|
|
259
|
+
const secretKey = existing.secretKey ?? loaded?.secretKey;
|
|
260
|
+
const host = existing.host ?? loaded?.host;
|
|
261
|
+
if (!publicKey || !secretKey || !host) {
|
|
262
|
+
notify(ctx, "Langfuse is not configured yet. Run /langfuse-setup before changing privacy settings.", "warning");
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
const nextConfig = {
|
|
266
|
+
publicKey: String(publicKey),
|
|
267
|
+
secretKey: String(secretKey),
|
|
268
|
+
host: String(host),
|
|
269
|
+
privacyPreset: requestedPreset,
|
|
270
|
+
};
|
|
271
|
+
saveConfig(nextConfig, configPath);
|
|
272
|
+
state.config = loadConfig(process.env, configPath);
|
|
273
|
+
notify(ctx, `Langfuse privacy preset saved: ${requestedPreset}\n${describePolicy(state.config?.capturePolicy ?? createCapturePolicy())}`);
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
export async function handleLangfusePrivacyCommand(args, ctx, deps = {}) {
|
|
277
|
+
const configPath = deps.configPath ?? CONFIG_PATH;
|
|
278
|
+
const parsed = parseCommandArgs(args);
|
|
279
|
+
if (parsed.malformed.length > 0) {
|
|
280
|
+
notify(ctx, `Couldn't understand '${parsed.malformed[0]}'. Use /langfuse-privacy preset=metadata-only.`, "warning");
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
const requestedPreset = parsed.values.preset ?? parsed.positional[0];
|
|
284
|
+
if (!requestedPreset) {
|
|
285
|
+
state.config = state.config ?? loadConfig(process.env, configPath);
|
|
286
|
+
const policy = state.config?.capturePolicy ?? createCapturePolicy();
|
|
287
|
+
if (ctx.hasUI && ctx.ui?.select) {
|
|
288
|
+
const currentPreset = inferPreset(policy);
|
|
289
|
+
const selectedPreset = await ctx.ui.select(`Langfuse privacy preset (current: ${currentPreset})`, [...PRIVACY_PRESETS]);
|
|
290
|
+
if (!selectedPreset) {
|
|
291
|
+
notify(ctx, `Current Langfuse privacy preset: ${currentPreset}\n${describePolicy(policy)}`);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
if (!isPrivacyPreset(selectedPreset)) {
|
|
295
|
+
notify(ctx, `Unknown privacy preset '${selectedPreset}'. Use one of: ${PRIVACY_PRESETS.join(", ")}.`, "warning");
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
return savePrivacyPreset(selectedPreset, ctx, configPath);
|
|
299
|
+
}
|
|
300
|
+
notify(ctx, `Current Langfuse privacy preset: ${inferPreset(policy)}\n${describePolicy(policy)}`);
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
if (!isPrivacyPreset(requestedPreset)) {
|
|
304
|
+
notify(ctx, `Unknown privacy preset '${requestedPreset}'. Use one of: ${PRIVACY_PRESETS.join(", ")}.`, "warning");
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
return savePrivacyPreset(requestedPreset, ctx, configPath);
|
|
308
|
+
}
|
|
309
|
+
export async function handleLangfuseTestCommand(args, ctx, deps = {}) {
|
|
310
|
+
const parsed = parseCommandArgs(args);
|
|
311
|
+
const unexpected = parsed.malformed[0] ?? parsed.positional[0] ?? Object.keys(parsed.values)[0];
|
|
312
|
+
if (unexpected) {
|
|
313
|
+
notify(ctx, `Unexpected argument '${unexpected}'. Usage: /langfuse-test`, "warning");
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
if (!state.config && !(await ensureConfig(ctx))) {
|
|
317
|
+
notify(ctx, "Langfuse is not configured yet. Run /langfuse-setup first.", "warning");
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
if (hasActiveAgentObservation()) {
|
|
321
|
+
notify(ctx, "Langfuse test skipped because an agent run is active. Try again after the run finishes.", "warning");
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
const config = state.config;
|
|
325
|
+
if (!config) {
|
|
326
|
+
notify(ctx, "Langfuse is not configured yet. Run /langfuse-setup first.", "warning");
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
const connectivity = await (deps.checkConnectivity ?? checkLangfuseConnectivity)(config);
|
|
330
|
+
if (!connectivity.ok) {
|
|
331
|
+
notify(ctx, `Langfuse connectivity check failed: ${connectivity.message}`, "error");
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
let runtimeInitialized = false;
|
|
335
|
+
try {
|
|
336
|
+
const rt = await (deps.getRuntime ?? getRuntime)();
|
|
337
|
+
runtimeInitialized = true;
|
|
338
|
+
const create = () => rt.propagateAttributes({
|
|
339
|
+
traceName: "pi-langfuse-test",
|
|
340
|
+
metadata: {
|
|
341
|
+
source: "pi-langfuse",
|
|
342
|
+
command: "langfuse-test",
|
|
343
|
+
},
|
|
344
|
+
}, () => {
|
|
345
|
+
const observation = rt.startObservation("pi-langfuse-test", {
|
|
346
|
+
input: { command: "/langfuse-test" },
|
|
347
|
+
output: "ok",
|
|
348
|
+
metadata: {
|
|
349
|
+
source: "pi-langfuse",
|
|
350
|
+
command: "langfuse-test",
|
|
351
|
+
},
|
|
352
|
+
}, { asType: "span" });
|
|
353
|
+
observation.end();
|
|
354
|
+
return observation;
|
|
355
|
+
});
|
|
356
|
+
if (rt.withRootContext)
|
|
357
|
+
rt.withRootContext(create);
|
|
358
|
+
else
|
|
359
|
+
create();
|
|
360
|
+
const result = connectivity.warning ? "completed with a read warning" : "succeeded";
|
|
361
|
+
notify(ctx, `Langfuse test ${result}. ${connectivity.message}; test trace sent to ${config.host}.`, connectivity.warning ? "warning" : "info");
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
366
|
+
notify(ctx, `Langfuse test failed: ${message}`, "error");
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
finally {
|
|
370
|
+
if (runtimeInitialized) {
|
|
371
|
+
await (deps.forceShutdownRuntime ?? shutdownLangfuseRuntime)();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Config } from "./types.js";
|
|
2
|
+
import { type EnvLike } from "./capture-policy.js";
|
|
3
|
+
export declare function loadConfigFromFile(path?: string, env?: EnvLike): Config | null;
|
|
4
|
+
export declare function loadConfigFromEnv(env?: EnvLike): Config | null;
|
|
5
|
+
export declare function loadConfig(env?: EnvLike, path?: string): Config | null;
|
|
6
|
+
export declare function saveConfig(config: Config, path?: string): void;
|
|
7
|
+
export declare function sanitizeConfigForLog(config: Pick<Config, "publicKey" | "secretKey" | "host"> | null): {
|
|
8
|
+
publicKey: string;
|
|
9
|
+
secretKey: string;
|
|
10
|
+
host: string;
|
|
11
|
+
} | null;
|
|
12
|
+
export declare function ensureConfig(ctx: any): Promise<boolean>;
|
|
13
|
+
export declare function promptForConfig(ctx: any): Promise<boolean>;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, existsSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { CONFIG_PATH, DEFAULT_LANGFUSE_HOST } from "./constants.js";
|
|
4
|
+
import { state } from "./state.js";
|
|
5
|
+
import { forceShutdownRuntime } from "./langfuse.js";
|
|
6
|
+
import { createCapturePolicy } from "./capture-policy.js";
|
|
7
|
+
import { createPayloadLimits } from "./limits.js";
|
|
8
|
+
import { createUsageOptions } from "./usage-options.js";
|
|
9
|
+
const MAX_LANGFUSE_USER_ID_LENGTH = 200;
|
|
10
|
+
function normalizeUserId(value) {
|
|
11
|
+
if (typeof value !== "string") {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
const trimmed = value.trim();
|
|
15
|
+
return trimmed ? trimmed.slice(0, MAX_LANGFUSE_USER_ID_LENGTH) : undefined;
|
|
16
|
+
}
|
|
17
|
+
export function loadConfigFromFile(path = CONFIG_PATH, env = process.env) {
|
|
18
|
+
if (existsSync(path)) {
|
|
19
|
+
try {
|
|
20
|
+
const content = readFileSync(path, "utf-8");
|
|
21
|
+
const config = JSON.parse(content);
|
|
22
|
+
if (config.publicKey && config.secretKey) {
|
|
23
|
+
const captureSource = {
|
|
24
|
+
...(config.capture ?? {}),
|
|
25
|
+
...(config.privacyPreset ? { LANGFUSE_PRIVACY_PRESET: config.privacyPreset } : {}),
|
|
26
|
+
...env,
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
publicKey: config.publicKey,
|
|
30
|
+
secretKey: config.secretKey,
|
|
31
|
+
host: config.host || DEFAULT_LANGFUSE_HOST,
|
|
32
|
+
userId: normalizeUserId(config.userId) ?? normalizeUserId(env.LANGFUSE_USER_ID),
|
|
33
|
+
capturePolicy: createCapturePolicy(captureSource),
|
|
34
|
+
limits: createPayloadLimits(env),
|
|
35
|
+
usage: createUsageOptions(captureSource),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
catch (e) {
|
|
40
|
+
console.warn("📊 Langfuse: Failed to load config.json", e);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
export function loadConfigFromEnv(env = process.env) {
|
|
46
|
+
const publicKey = env.LANGFUSE_PUBLIC_KEY || "";
|
|
47
|
+
const secretKey = env.LANGFUSE_SECRET_KEY || "";
|
|
48
|
+
if (!publicKey || !secretKey) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
publicKey,
|
|
53
|
+
secretKey,
|
|
54
|
+
host: env.LANGFUSE_BASE_URL || env.LANGFUSE_HOST || DEFAULT_LANGFUSE_HOST,
|
|
55
|
+
userId: normalizeUserId(env.LANGFUSE_USER_ID),
|
|
56
|
+
capturePolicy: createCapturePolicy(env),
|
|
57
|
+
limits: createPayloadLimits(env),
|
|
58
|
+
usage: createUsageOptions(env),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export function loadConfig(env = process.env, path = CONFIG_PATH) {
|
|
62
|
+
return loadConfigFromFile(path, env) || loadConfigFromEnv(env);
|
|
63
|
+
}
|
|
64
|
+
export function saveConfig(config, path = CONFIG_PATH) {
|
|
65
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
66
|
+
chmodSync(dirname(path), 0o700);
|
|
67
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { encoding: "utf-8", mode: 0o600 });
|
|
68
|
+
chmodSync(path, 0o600);
|
|
69
|
+
}
|
|
70
|
+
function maskPublicKey(value) {
|
|
71
|
+
if (value.length <= 9) {
|
|
72
|
+
return "[REDACTED_SECRET]";
|
|
73
|
+
}
|
|
74
|
+
return `${value.slice(0, 6)}...${value.slice(-4)}`;
|
|
75
|
+
}
|
|
76
|
+
export function sanitizeConfigForLog(config) {
|
|
77
|
+
if (!config) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
publicKey: maskPublicKey(config.publicKey),
|
|
82
|
+
secretKey: "[REDACTED_SECRET]",
|
|
83
|
+
host: config.host || DEFAULT_LANGFUSE_HOST,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function collectConfigFromUI(ctx, reason) {
|
|
87
|
+
if (!ctx.hasUI) {
|
|
88
|
+
console.error(`📊 Langfuse: ${reason}. Run this extension in Pi UI to complete setup, or set LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_BASE_URL.`);
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
ctx.ui.notify("Langfuse setup required. Enter your API keys to enable tracing.", "info");
|
|
92
|
+
const publicKey = (await ctx.ui.input("Langfuse public key:", "pk-lf-..."))?.trim();
|
|
93
|
+
if (!publicKey) {
|
|
94
|
+
ctx.ui.notify("Langfuse setup cancelled.", "warning");
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
const secretKey = (await ctx.ui.input("Langfuse secret key:", "sk-lf-..."))?.trim();
|
|
98
|
+
if (!secretKey) {
|
|
99
|
+
ctx.ui.notify("Langfuse setup cancelled.", "warning");
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const hostInput = (await ctx.ui.input("Langfuse host:", DEFAULT_LANGFUSE_HOST))?.trim();
|
|
103
|
+
const userId = normalizeUserId(await ctx.ui.input("Langfuse user ID (optional):", ""));
|
|
104
|
+
return {
|
|
105
|
+
publicKey,
|
|
106
|
+
secretKey,
|
|
107
|
+
host: hostInput || DEFAULT_LANGFUSE_HOST,
|
|
108
|
+
...(userId ? { userId } : {}),
|
|
109
|
+
capturePolicy: createCapturePolicy(),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
async function saveConfigFromUI(ctx, config) {
|
|
113
|
+
state.config = config;
|
|
114
|
+
try {
|
|
115
|
+
saveConfig(state.config);
|
|
116
|
+
ctx.ui.notify(`Langfuse config saved to ${CONFIG_PATH}`, "info");
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
console.warn("📊 Langfuse: Failed to save config.json", error);
|
|
121
|
+
ctx.ui.notify(`Failed to save Langfuse config.json to ${CONFIG_PATH}. Check Pi config directory permissions.`, "error");
|
|
122
|
+
state.config = null;
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export async function ensureConfig(ctx) {
|
|
127
|
+
if (!state.config) {
|
|
128
|
+
state.config = loadConfig();
|
|
129
|
+
}
|
|
130
|
+
if (state.config) {
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
if (state.setupAttemptedThisSession) {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
state.setupAttemptedThisSession = true;
|
|
137
|
+
const config = await collectConfigFromUI(ctx, "Missing config");
|
|
138
|
+
if (!config) {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
return saveConfigFromUI(ctx, config);
|
|
142
|
+
}
|
|
143
|
+
export async function promptForConfig(ctx) {
|
|
144
|
+
state.setupAttemptedThisSession = false;
|
|
145
|
+
state.config = null;
|
|
146
|
+
await forceShutdownRuntime();
|
|
147
|
+
const config = await collectConfigFromUI(ctx, "Manual setup requested");
|
|
148
|
+
if (!config) {
|
|
149
|
+
state.config = loadConfig();
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
const saved = await saveConfigFromUI(ctx, config);
|
|
153
|
+
if (saved) {
|
|
154
|
+
ctx.ui.notify("Langfuse tracing enabled for future agent runs.", "info");
|
|
155
|
+
}
|
|
156
|
+
return saved;
|
|
157
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const CONFIG_DIR: string;
|
|
2
|
+
export declare const CONFIG_PATH: string;
|
|
3
|
+
export declare const DEFAULT_LANGFUSE_HOST = "https://cloud.langfuse.com";
|
|
4
|
+
export declare const MAX_STRING_LENGTH = 12000;
|
|
5
|
+
export declare const MAX_TOOL_PAYLOAD_LENGTH = 24000;
|
|
6
|
+
export declare const MAX_DEPTH = 6;
|
|
7
|
+
export declare const MAX_ARRAY_ITEMS = 50;
|
|
8
|
+
export declare const MAX_OBJECT_KEYS = 80;
|
|
9
|
+
export declare const MAX_PAYLOAD_NODES = 2000;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
export const CONFIG_DIR = resolve(homedir(), ".pi", "agent", "pi-langfuse");
|
|
4
|
+
export const CONFIG_PATH = resolve(CONFIG_DIR, "config.json");
|
|
5
|
+
export const DEFAULT_LANGFUSE_HOST = "https://cloud.langfuse.com";
|
|
6
|
+
export const MAX_STRING_LENGTH = 12_000;
|
|
7
|
+
export const MAX_TOOL_PAYLOAD_LENGTH = 24_000;
|
|
8
|
+
export const MAX_DEPTH = 6;
|
|
9
|
+
export const MAX_ARRAY_ITEMS = 50;
|
|
10
|
+
export const MAX_OBJECT_KEYS = 80;
|
|
11
|
+
export const MAX_PAYLOAD_NODES = 2_000;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type LangfuseExtensionOptions } from "../workflow.js";
|
|
2
|
+
export declare function updateTraceIO(input?: unknown, output?: unknown): void;
|
|
3
|
+
export declare function startAgentRun(event: Record<string, unknown>, ctx: any, getRunContext?: LangfuseExtensionOptions["getRunContext"]): Promise<void>;
|
|
4
|
+
export declare function startAgentAttempt(): Promise<void>;
|
|
5
|
+
export declare function finishAgentAttempt(event?: Record<string, unknown>): void;
|
|
6
|
+
export declare function cancelAgentRun(reason: string): void;
|
|
7
|
+
/**
|
|
8
|
+
* Records the effective system prompt on the root agent observation.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately called from `agent_start` rather than `before_agent_start`:
|
|
11
|
+
* during `before_agent_start` the extension runner hands each handler the
|
|
12
|
+
* prompt as it stands mid-chain, so extensions registered after this one
|
|
13
|
+
* (e.g. inline factories that rewrite the system prompt) are not reflected
|
|
14
|
+
* yet. By `agent_start` the session has applied the final override, and
|
|
15
|
+
* `ctx.getSystemPrompt()` returns the prompt actually sent to the model.
|
|
16
|
+
*/
|
|
17
|
+
export declare function recordSystemPrompt(ctx: any): Promise<void>;
|
|
18
|
+
export declare function finishAgentRun(event?: Record<string, unknown>): Promise<void>;
|