pi-langfuse 1.7.0 → 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.
Files changed (66) hide show
  1. package/README.md +87 -5
  2. package/README_CN.md +63 -5
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.js +216 -0
  5. package/dist/src/capture-policy.d.ts +43 -0
  6. package/dist/src/capture-policy.js +125 -0
  7. package/dist/src/commands.d.ts +25 -0
  8. package/dist/src/commands.js +374 -0
  9. package/dist/src/config.d.ts +13 -0
  10. package/dist/src/config.js +157 -0
  11. package/dist/src/constants.d.ts +9 -0
  12. package/dist/src/constants.js +11 -0
  13. package/dist/src/handlers/agent.d.ts +18 -0
  14. package/dist/src/handlers/agent.js +310 -0
  15. package/dist/src/handlers/cache.d.ts +5 -0
  16. package/dist/src/handlers/cache.js +134 -0
  17. package/dist/src/handlers/generation.d.ts +9 -0
  18. package/dist/src/handlers/generation.js +249 -0
  19. package/dist/src/handlers/session.d.ts +4 -0
  20. package/dist/src/handlers/session.js +121 -0
  21. package/dist/src/handlers/system-state.d.ts +3 -0
  22. package/dist/src/handlers/system-state.js +185 -0
  23. package/dist/src/handlers/tool.d.ts +3 -0
  24. package/dist/src/handlers/tool.js +168 -0
  25. package/dist/src/handlers/turn.d.ts +2 -0
  26. package/dist/src/handlers/turn.js +48 -0
  27. package/dist/src/langfuse.d.ts +42 -0
  28. package/dist/src/langfuse.js +837 -0
  29. package/dist/src/limits.d.ts +43 -0
  30. package/dist/src/limits.js +63 -0
  31. package/dist/src/observation.d.ts +24 -0
  32. package/dist/src/observation.js +24 -0
  33. package/dist/src/redaction.d.ts +14 -0
  34. package/dist/src/redaction.js +254 -0
  35. package/dist/src/session-lineage.d.ts +15 -0
  36. package/dist/src/session-lineage.js +87 -0
  37. package/dist/src/source-metadata.d.ts +2 -0
  38. package/dist/src/source-metadata.js +55 -0
  39. package/dist/src/state.d.ts +52 -0
  40. package/dist/src/state.js +144 -0
  41. package/dist/src/types.d.ts +157 -0
  42. package/dist/src/types.js +1 -0
  43. package/dist/src/usage-options.d.ts +27 -0
  44. package/dist/src/usage-options.js +21 -0
  45. package/dist/src/utils.d.ts +61 -0
  46. package/dist/src/utils.js +600 -0
  47. package/dist/src/workflow.d.ts +24 -0
  48. package/dist/src/workflow.js +62 -0
  49. package/examples/workflow-sdk.mjs +56 -0
  50. package/index.ts +47 -13
  51. package/package.json +16 -2
  52. package/src/commands.ts +48 -5
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +63 -33
  55. package/src/handlers/cache.ts +14 -10
  56. package/src/handlers/generation.ts +21 -43
  57. package/src/handlers/session.ts +71 -13
  58. package/src/handlers/tool.ts +12 -8
  59. package/src/langfuse.ts +110 -80
  60. package/src/observation.ts +31 -0
  61. package/src/redaction.ts +145 -10
  62. package/src/session-lineage.ts +98 -0
  63. package/src/state.ts +19 -2
  64. package/src/types.ts +2 -1
  65. package/src/utils.ts +95 -19
  66. package/src/workflow.ts +78 -0
@@ -0,0 +1,125 @@
1
+ import { hashPath, redactValue } from "./redaction.js";
2
+ /** Redaction options implied by a policy, so path rendering follows the same switch everywhere. */
3
+ export function redactOptionsFor(policy) {
4
+ return { redactPaths: !policy.capturePaths };
5
+ }
6
+ const PRESETS = {
7
+ "metadata-only": {
8
+ captureInputs: false,
9
+ captureOutputs: false,
10
+ captureToolIo: false,
11
+ captureSystemPrompt: false,
12
+ captureCwd: false,
13
+ captureSourceMetadata: false,
14
+ capturePaths: false,
15
+ },
16
+ "prompts-only": {
17
+ captureInputs: true,
18
+ captureOutputs: false,
19
+ captureToolIo: false,
20
+ captureSystemPrompt: false,
21
+ captureCwd: false,
22
+ captureSourceMetadata: false,
23
+ capturePaths: false,
24
+ },
25
+ conversations: {
26
+ captureInputs: true,
27
+ captureOutputs: true,
28
+ captureToolIo: false,
29
+ captureSystemPrompt: false,
30
+ captureCwd: false,
31
+ captureSourceMetadata: false,
32
+ capturePaths: false,
33
+ },
34
+ "full-debug": {
35
+ captureInputs: true,
36
+ captureOutputs: true,
37
+ captureToolIo: true,
38
+ captureSystemPrompt: true,
39
+ captureCwd: true,
40
+ captureSourceMetadata: false,
41
+ capturePaths: false,
42
+ },
43
+ };
44
+ const FLAG_TO_FIELD = {
45
+ LANGFUSE_CAPTURE_INPUTS: "captureInputs",
46
+ LANGFUSE_CAPTURE_OUTPUTS: "captureOutputs",
47
+ LANGFUSE_CAPTURE_TOOL_IO: "captureToolIo",
48
+ LANGFUSE_CAPTURE_SYSTEM_PROMPT: "captureSystemPrompt",
49
+ LANGFUSE_CAPTURE_CWD: "captureCwd",
50
+ LANGFUSE_CAPTURE_SOURCE_METADATA: "captureSourceMetadata",
51
+ LANGFUSE_CAPTURE_PATHS: "capturePaths",
52
+ };
53
+ /**
54
+ * Parse a boolean env flag. `1/true/yes/on` and `0/false/no/off` are
55
+ * case-insensitive; anything else (including unset) is `undefined` so the
56
+ * caller keeps its default.
57
+ */
58
+ export function parseFlag(value) {
59
+ if (value === undefined) {
60
+ return undefined;
61
+ }
62
+ if (/^(1|true|yes|on)$/i.test(value)) {
63
+ return true;
64
+ }
65
+ if (/^(0|false|no|off)$/i.test(value)) {
66
+ return false;
67
+ }
68
+ return undefined;
69
+ }
70
+ function normalizePreset(value) {
71
+ return value && value in PRESETS ? value : "full-debug";
72
+ }
73
+ export function createCapturePolicy(env = process.env) {
74
+ const policy = { ...PRESETS[normalizePreset(env.LANGFUSE_PRIVACY_PRESET)] };
75
+ for (const [envName, field] of Object.entries(FLAG_TO_FIELD)) {
76
+ const override = parseFlag(env[envName]);
77
+ if (override !== undefined) {
78
+ policy[field] = override;
79
+ }
80
+ }
81
+ return policy;
82
+ }
83
+ function redactMetadata(metadata, policy) {
84
+ if (!metadata) {
85
+ return undefined;
86
+ }
87
+ const redactOptions = redactOptionsFor(policy);
88
+ const output = {};
89
+ for (const [key, value] of Object.entries(metadata)) {
90
+ if (key === "cwd") {
91
+ if (!policy.captureCwd) {
92
+ continue;
93
+ }
94
+ output[key] =
95
+ !policy.capturePaths && typeof value === "string" && /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value)
96
+ ? hashPath(value)
97
+ : redactValue(value, redactOptions);
98
+ continue;
99
+ }
100
+ output[key] = redactValue(value, redactOptions);
101
+ }
102
+ return Object.keys(output).length > 0 ? output : undefined;
103
+ }
104
+ export function applyCapturePolicy(payload, policy = createCapturePolicy()) {
105
+ const redactOptions = redactOptionsFor(policy);
106
+ const captured = {
107
+ metadata: redactMetadata(payload.metadata, policy),
108
+ };
109
+ if (policy.captureInputs && "input" in payload) {
110
+ captured.input = redactValue(payload.input, redactOptions);
111
+ }
112
+ if (policy.captureOutputs && "output" in payload) {
113
+ captured.output = redactValue(payload.output, redactOptions);
114
+ }
115
+ if (policy.captureToolIo && "toolInput" in payload) {
116
+ captured.toolInput = redactValue(payload.toolInput, redactOptions);
117
+ }
118
+ if (policy.captureToolIo && "toolOutput" in payload) {
119
+ captured.toolOutput = redactValue(payload.toolOutput, redactOptions);
120
+ }
121
+ if (policy.captureSystemPrompt && "systemPrompt" in payload) {
122
+ captured.systemPrompt = redactValue(payload.systemPrompt, redactOptions);
123
+ }
124
+ return captured;
125
+ }
@@ -0,0 +1,25 @@
1
+ import type { Config, LangfuseRuntime } from "./types.js";
2
+ export interface CommandContextLike {
3
+ mode?: string;
4
+ hasUI?: boolean;
5
+ ui?: {
6
+ notify?: (message: string, level?: "info" | "warning" | "error") => void;
7
+ select?: (title: string, options: string[]) => Promise<string | undefined>;
8
+ };
9
+ }
10
+ interface CommandDeps {
11
+ configPath?: string;
12
+ getRuntime?: () => Promise<LangfuseRuntime>;
13
+ forceShutdownRuntime?: () => Promise<void>;
14
+ env?: Record<string, string | undefined>;
15
+ checkConnectivity?: (config: Config) => Promise<ConnectivityResult>;
16
+ }
17
+ interface ConnectivityResult {
18
+ ok: boolean;
19
+ message: string;
20
+ warning?: boolean;
21
+ }
22
+ export declare function handleLangfuseStatusCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
23
+ export declare function handleLangfusePrivacyCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
24
+ export declare function handleLangfuseTestCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
25
+ export {};
@@ -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
+ }