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,837 @@
1
+ import { state } from "./state.js";
2
+ import { randomUUID } from "node:crypto";
3
+ let runtime = null;
4
+ let registeredContextManager = null;
5
+ const activeSessions = new Set();
6
+ let lastRuntimeError = null;
7
+ const OTEL_VISIBILITY_TIMEOUT_MS = 1_500;
8
+ const OTEL_VISIBILITY_POLL_INTERVAL_MS = 200;
9
+ const DEFAULT_SHUTDOWN_STEP_TIMEOUT_MS = 2_000;
10
+ const DEFAULT_SCORE_SHUTDOWN_TIMEOUT_MS = 2_000;
11
+ const DEFAULT_LANGFUSE_REQUEST_TIMEOUT_SECONDS = 5;
12
+ const DEFAULT_SCORE_FLUSH_AT = 10;
13
+ const DEFAULT_SCORE_FLUSH_INTERVAL_MS = 1_000;
14
+ const MAX_SCORE_QUEUE_SIZE = 100_000;
15
+ const MAX_SCORE_BATCH_SIZE = 100;
16
+ // Langfuse gateways (incl. langfuse-dx.wair.ac.cn) reject ingestion bodies above
17
+ // ~4.5MB with HTTP 413. Keep the default chunk budget safely below that limit.
18
+ const DEFAULT_MAX_INGESTION_BATCH_BYTES = 4 * 1024 * 1024;
19
+ // Hard ceiling for the whole REST fallback payload. Above this the fallback is
20
+ // pointless (it would need dozens of requests during a bounded shutdown) and is
21
+ // skipped with a warning.
22
+ const DEFAULT_MAX_FALLBACK_TOTAL_BYTES = 32 * 1024 * 1024;
23
+ let shutdownStepTimeoutMs = DEFAULT_SHUTDOWN_STEP_TIMEOUT_MS;
24
+ function nowIso() {
25
+ return new Date().toISOString();
26
+ }
27
+ function resolvePositiveEnvNumber(name, fallback, integer = false) {
28
+ const parsed = Number(process.env[name]);
29
+ if (!Number.isFinite(parsed) || parsed <= 0) {
30
+ return fallback;
31
+ }
32
+ return integer ? Math.floor(parsed) : parsed;
33
+ }
34
+ function getScoreShutdownTimeoutMs() {
35
+ return resolvePositiveEnvNumber("PI_LANGFUSE_SCORE_SHUTDOWN_TIMEOUT", DEFAULT_SCORE_SHUTDOWN_TIMEOUT_MS / 1_000) * 1_000;
36
+ }
37
+ function getMaxIngestionBatchBytes() {
38
+ return resolvePositiveEnvNumber("PI_LANGFUSE_MAX_INGESTION_BATCH_BYTES", DEFAULT_MAX_INGESTION_BATCH_BYTES, true);
39
+ }
40
+ function getMaxFallbackTotalBytes() {
41
+ return resolvePositiveEnvNumber("PI_LANGFUSE_MAX_FALLBACK_TOTAL_BYTES", DEFAULT_MAX_FALLBACK_TOTAL_BYTES, true);
42
+ }
43
+ function delay(ms, signal) {
44
+ return new Promise((resolve, reject) => {
45
+ if (signal?.aborted) {
46
+ reject(signal.reason);
47
+ return;
48
+ }
49
+ const timeout = setTimeout(resolve, ms);
50
+ signal?.addEventListener("abort", () => {
51
+ clearTimeout(timeout);
52
+ reject(signal.reason);
53
+ }, { once: true });
54
+ });
55
+ }
56
+ function debugLog(message) {
57
+ if (process.env.PI_LANGFUSE_DEBUG === "1" || process.env.PI_LANGFUSE_DEBUG === "true") {
58
+ console.error(message);
59
+ }
60
+ }
61
+ export function ensureOtelContextManager(contextApi, AsyncHooksContextManager) {
62
+ if (registeredContextManager) {
63
+ return true;
64
+ }
65
+ const contextManager = new AsyncHooksContextManager().enable();
66
+ if (contextApi.setGlobalContextManager(contextManager)) {
67
+ registeredContextManager = contextManager;
68
+ return true;
69
+ }
70
+ contextManager.disable();
71
+ return false;
72
+ }
73
+ function rememberRuntimeError(scope, error) {
74
+ lastRuntimeError = {
75
+ scope,
76
+ message: error instanceof Error ? error.message : String(error),
77
+ timestamp: new Date(),
78
+ };
79
+ }
80
+ export function getLastRuntimeError() {
81
+ return lastRuntimeError;
82
+ }
83
+ function isAbortError(error) {
84
+ return error instanceof Error && error.name === "AbortError";
85
+ }
86
+ async function withShutdownDeadline(label, startOperation, deadline, signal) {
87
+ const remainingMs = deadline - Date.now();
88
+ if (remainingMs <= 0) {
89
+ debugLog(`📊 Langfuse: Skipped ${label}; shutdown deadline elapsed`);
90
+ return undefined;
91
+ }
92
+ const operation = startOperation();
93
+ if (!operation) {
94
+ return undefined;
95
+ }
96
+ let timeout;
97
+ try {
98
+ return await Promise.race([
99
+ operation,
100
+ new Promise((resolve) => {
101
+ timeout = setTimeout(() => {
102
+ debugLog(`📊 Langfuse: ${label} timed out; shutdown deadline elapsed`);
103
+ resolve(undefined);
104
+ }, remainingMs);
105
+ }),
106
+ ]);
107
+ }
108
+ catch (error) {
109
+ if (signal?.aborted && isAbortError(error)) {
110
+ debugLog(`📊 Langfuse: ${label} aborted; shutdown deadline elapsed`);
111
+ return undefined;
112
+ }
113
+ throw error;
114
+ }
115
+ finally {
116
+ if (timeout) {
117
+ clearTimeout(timeout);
118
+ }
119
+ }
120
+ }
121
+ async function runShutdownStep(label, startOperation, deadline, signal) {
122
+ try {
123
+ return await withShutdownDeadline(label, startOperation, deadline, signal);
124
+ }
125
+ catch (error) {
126
+ rememberRuntimeError(`runtime shutdown: ${label}`, error);
127
+ console.warn(`📊 Langfuse: Failed ${label} during shutdown`, error);
128
+ return undefined;
129
+ }
130
+ }
131
+ function getRuntimeConfig(rt) {
132
+ return rt.runtimeConfig ?? state.config;
133
+ }
134
+ function ingestionHeaders(rt) {
135
+ const config = getRuntimeConfig(rt);
136
+ if (!config) {
137
+ throw new Error("Langfuse runtime config is unavailable");
138
+ }
139
+ const auth = Buffer.from(`${config.publicKey}:${config.secretKey}`).toString("base64");
140
+ return {
141
+ Authorization: `Basic ${auth}`,
142
+ "Content-Type": "application/json",
143
+ };
144
+ }
145
+ async function ingestBatch(rt, batch, signal) {
146
+ const config = getRuntimeConfig(rt);
147
+ if (!config) {
148
+ throw new Error("Langfuse runtime config is unavailable");
149
+ }
150
+ const response = await fetch(`${config.host.replace(/\/$/, "")}/api/public/ingestion`, {
151
+ method: "POST",
152
+ headers: ingestionHeaders(rt),
153
+ body: JSON.stringify({ batch }),
154
+ signal,
155
+ });
156
+ if (!response.ok) {
157
+ throw new Error(`Langfuse ingestion failed with HTTP ${response.status}`);
158
+ }
159
+ const text = await response.text();
160
+ if (!text) {
161
+ return [];
162
+ }
163
+ const responseBody = JSON.parse(text);
164
+ return Array.isArray(responseBody.errors) ? responseBody.errors : [];
165
+ }
166
+ function serializedBytes(value) {
167
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
168
+ }
169
+ /**
170
+ * Split an ingestion event list into chunks whose serialized request bodies each
171
+ * stay under `maxBytes`, skipping individually oversized events with a warning.
172
+ * Each chunk, when wrapped as `{ batch: chunk }`, matches
173
+ * the measurement exactly because entries are serialized individually and joined
174
+ * with single commas inside the `{"batch":[...]}` envelope.
175
+ */
176
+ export function splitIngestionBatch(entries, maxBytes) {
177
+ const serialized = entries.map((entry) => JSON.stringify(entry));
178
+ const envelopeBytes = Buffer.byteLength('{"batch":[]}');
179
+ const chunks = [];
180
+ let chunk = [];
181
+ let chunkBytes = envelopeBytes;
182
+ for (let index = 0; index < serialized.length; index++) {
183
+ const entryBytes = Buffer.byteLength(serialized[index], "utf8");
184
+ if (envelopeBytes + entryBytes > maxBytes) {
185
+ const message = `Skipping oversized REST fallback event (${envelopeBytes + entryBytes} bytes exceeds ${maxBytes}-byte request budget)`;
186
+ rememberRuntimeError("REST fallback ingestion", new Error(message));
187
+ console.warn(`📊 Langfuse: ${message}`);
188
+ continue;
189
+ }
190
+ const separators = chunk.length > 0 ? 1 : 0;
191
+ const projectedBytes = chunkBytes + entryBytes + separators;
192
+ if (chunk.length > 0 && projectedBytes > maxBytes) {
193
+ chunks.push(chunk);
194
+ chunk = [];
195
+ chunkBytes = envelopeBytes;
196
+ }
197
+ chunk.push(entries[index]);
198
+ chunkBytes += entryBytes + (chunk.length > 1 ? 1 : 0);
199
+ }
200
+ if (chunk.length > 0) {
201
+ chunks.push(chunk);
202
+ }
203
+ return chunks;
204
+ }
205
+ async function flushPendingScores(rt, signal) {
206
+ const pendingScores = rt.pendingScores;
207
+ if (!pendingScores || pendingScores.length === 0) {
208
+ return;
209
+ }
210
+ while (pendingScores.length > 0) {
211
+ const scores = pendingScores.slice(0, MAX_SCORE_BATCH_SIZE);
212
+ for (const score of scores) {
213
+ score.id ??= randomUUID();
214
+ }
215
+ try {
216
+ const errors = await ingestBatch(rt, scores.map((score) => ({
217
+ type: "score-create",
218
+ id: randomUUID(),
219
+ timestamp: nowIso(),
220
+ body: score,
221
+ })), signal);
222
+ pendingScores.splice(0, scores.length);
223
+ if (errors.length > 0) {
224
+ rememberRuntimeError("score ingestion", new Error(JSON.stringify(errors)));
225
+ console.warn("📊 Langfuse: Score ingestion reported errors", errors);
226
+ }
227
+ }
228
+ catch (error) {
229
+ if (error.name !== "AbortError") {
230
+ rememberRuntimeError("score ingestion", error);
231
+ console.warn("📊 Langfuse: Failed to flush scores", error);
232
+ }
233
+ return;
234
+ }
235
+ }
236
+ }
237
+ function clearScoreFlushTimer(rt) {
238
+ if (rt.scoreFlushTimer) {
239
+ clearTimeout(rt.scoreFlushTimer);
240
+ rt.scoreFlushTimer = undefined;
241
+ }
242
+ }
243
+ function scheduleScoreFlush(rt) {
244
+ if (rt.scoreFlushStopped
245
+ || rt.scoreFlushTimer
246
+ || rt.scoreFlushPromise
247
+ || !rt.pendingScores?.length) {
248
+ return;
249
+ }
250
+ rt.scoreFlushTimer = setTimeout(() => {
251
+ rt.scoreFlushTimer = undefined;
252
+ void startScoreFlush(rt);
253
+ }, rt.scoreFlushIntervalMs ?? DEFAULT_SCORE_FLUSH_INTERVAL_MS);
254
+ rt.scoreFlushTimer.unref?.();
255
+ }
256
+ function startScoreFlush(rt) {
257
+ if (rt.scoreFlushPromise) {
258
+ return rt.scoreFlushPromise;
259
+ }
260
+ clearScoreFlushTimer(rt);
261
+ const controller = new AbortController();
262
+ const timeout = setTimeout(() => controller.abort(new DOMException("Langfuse score request timed out", "AbortError")), rt.scoreRequestTimeoutMs ?? DEFAULT_LANGFUSE_REQUEST_TIMEOUT_SECONDS * 1_000);
263
+ timeout.unref?.();
264
+ rt.scoreFlushController = controller;
265
+ const promise = flushPendingScores(rt, controller.signal).finally(() => {
266
+ clearTimeout(timeout);
267
+ if (rt.scoreFlushPromise === promise) {
268
+ rt.scoreFlushPromise = undefined;
269
+ }
270
+ if (rt.scoreFlushController === controller) {
271
+ rt.scoreFlushController = undefined;
272
+ }
273
+ scheduleScoreFlush(rt);
274
+ });
275
+ rt.scoreFlushPromise = promise;
276
+ return promise;
277
+ }
278
+ function stopScoreFlush(rt) {
279
+ rt.scoreFlushStopped = true;
280
+ clearScoreFlushTimer(rt);
281
+ rt.scoreFlushController?.abort(new DOMException("Langfuse score flushing stopped", "AbortError"));
282
+ }
283
+ function toIso(value) {
284
+ if (!value) {
285
+ return undefined;
286
+ }
287
+ if (value instanceof Date) {
288
+ return value.toISOString();
289
+ }
290
+ if (typeof value === "string") {
291
+ return value;
292
+ }
293
+ return undefined;
294
+ }
295
+ function mergeMetadata(current, next) {
296
+ return next ? { ...(current ?? {}), ...next } : current;
297
+ }
298
+ function applyObservationUpdate(record, body) {
299
+ if (!body) {
300
+ return;
301
+ }
302
+ if ("input" in body)
303
+ record.input = body.input;
304
+ if ("output" in body)
305
+ record.output = body.output;
306
+ if ("metadata" in body && body.metadata && typeof body.metadata === "object") {
307
+ record.metadata = mergeMetadata(record.metadata, body.metadata);
308
+ }
309
+ if (typeof body.model === "string")
310
+ record.model = body.model;
311
+ if (body.modelParameters && typeof body.modelParameters === "object") {
312
+ record.modelParameters = body.modelParameters;
313
+ }
314
+ if (body.usageDetails && typeof body.usageDetails === "object") {
315
+ record.usageDetails = body.usageDetails;
316
+ }
317
+ if (body.costDetails && typeof body.costDetails === "object") {
318
+ record.costDetails = body.costDetails;
319
+ }
320
+ if (typeof body.level === "string")
321
+ record.level = body.level;
322
+ if (typeof body.statusMessage === "string")
323
+ record.statusMessage = body.statusMessage;
324
+ const completionStartTime = toIso(body.completionStartTime);
325
+ if (completionStartTime)
326
+ record.completionStartTime = completionStartTime;
327
+ }
328
+ function applyTraceUpdate(store, traceId, body) {
329
+ const trace = store.traces.get(traceId);
330
+ if (!trace || !body) {
331
+ return;
332
+ }
333
+ if ("input" in body)
334
+ trace.input = body.input;
335
+ if ("output" in body)
336
+ trace.output = body.output;
337
+ if ("metadata" in body && body.metadata && typeof body.metadata === "object") {
338
+ trace.metadata = mergeMetadata(trace.metadata, body.metadata);
339
+ }
340
+ }
341
+ function observationType(asType) {
342
+ return asType === "generation" ? "GENERATION" : "SPAN";
343
+ }
344
+ const PROPAGATED_STRING_ATTRIBUTES = {
345
+ sessionId: "session.id",
346
+ userId: "user.id",
347
+ traceName: "langfuse.trace.name",
348
+ version: "langfuse.version",
349
+ };
350
+ const OTEL_TRACE_TAGS_ATTRIBUTE = "langfuse.trace.tags";
351
+ const OTEL_TRACE_METADATA_PREFIX = "langfuse.trace.metadata.";
352
+ function readPropagatedAttributes(observation) {
353
+ const attributes = observation?.otelSpan?.attributes ?? {};
354
+ const propagated = {};
355
+ for (const [key, attribute] of Object.entries(PROPAGATED_STRING_ATTRIBUTES)) {
356
+ const value = attributes[attribute];
357
+ if (typeof value === "string" && value) {
358
+ propagated[key] = value;
359
+ }
360
+ }
361
+ const tags = attributes[OTEL_TRACE_TAGS_ATTRIBUTE];
362
+ if (Array.isArray(tags)) {
363
+ const validTags = tags.filter((tag) => typeof tag === "string" && tag.length > 0);
364
+ if (validTags.length > 0) {
365
+ propagated.tags = validTags;
366
+ }
367
+ }
368
+ const metadata = {};
369
+ for (const [key, value] of Object.entries(attributes)) {
370
+ if (key.startsWith(OTEL_TRACE_METADATA_PREFIX) && typeof value === "string") {
371
+ metadata[key.slice(OTEL_TRACE_METADATA_PREFIX.length)] = value;
372
+ }
373
+ }
374
+ if (Object.keys(metadata).length > 0) {
375
+ propagated.metadata = metadata;
376
+ }
377
+ return propagated;
378
+ }
379
+ function recordFallbackObservation(store, observation, id, traceId, name, body, asType, parentObservationId) {
380
+ const metadata = body?.metadata && typeof body.metadata === "object" ? body.metadata : undefined;
381
+ const record = {
382
+ id,
383
+ traceId,
384
+ name,
385
+ type: observationType(asType),
386
+ startTime: nowIso(),
387
+ parentObservationId,
388
+ metadata: mergeMetadata(metadata, asType && asType !== "generation" && asType !== "span" ? { langfuseObservationType: asType } : undefined),
389
+ };
390
+ applyObservationUpdate(record, body);
391
+ store.observations.push(record);
392
+ store.observationById.set(id, record);
393
+ if (!parentObservationId && !store.traces.has(traceId)) {
394
+ const propagated = readPropagatedAttributes(observation);
395
+ store.traces.set(traceId, {
396
+ id: traceId,
397
+ timestamp: record.startTime,
398
+ name: propagated.traceName ?? name,
399
+ input: body?.input,
400
+ sessionId: propagated.sessionId
401
+ ?? (typeof metadata?.sessionId === "string" ? metadata.sessionId : state.currentSessionId || undefined),
402
+ userId: propagated.userId ?? state.config?.userId,
403
+ metadata: mergeMetadata(propagated.metadata, metadata),
404
+ });
405
+ }
406
+ return record;
407
+ }
408
+ function wrapObservation(observation, store, name, body, asType, parentObservationId, externalTrace = false) {
409
+ const id = observation.id ?? (externalTrace ? undefined : randomUUID());
410
+ const traceId = observation.traceId ?? (externalTrace ? undefined : randomUUID());
411
+ const record = externalTrace ? undefined
412
+ : recordFallbackObservation(store, observation, id, traceId, name, body, asType, parentObservationId);
413
+ return {
414
+ ...observation,
415
+ id,
416
+ traceId,
417
+ update(updateBody) {
418
+ if (record)
419
+ applyObservationUpdate(record, updateBody);
420
+ if (record && !parentObservationId) {
421
+ applyTraceUpdate(store, traceId, updateBody);
422
+ }
423
+ const updated = observation.update(updateBody);
424
+ return updated === observation ? this : updated;
425
+ },
426
+ end(endBody) {
427
+ if (record && endBody && typeof endBody === "object") {
428
+ applyObservationUpdate(record, endBody);
429
+ if (!parentObservationId) {
430
+ applyTraceUpdate(store, traceId, endBody);
431
+ }
432
+ }
433
+ if (record)
434
+ record.endTime = nowIso();
435
+ return observation.end();
436
+ },
437
+ startObservation(childName, childBody, options) {
438
+ const inherited = readPropagatedAttributes(observation);
439
+ const fallbackSessionId = state.currentSessionId?.slice(0, 200);
440
+ if (!externalTrace && !inherited.sessionId && fallbackSessionId) {
441
+ inherited.sessionId = fallbackSessionId;
442
+ }
443
+ const propagate = runtime?.propagateAttributes;
444
+ const createChild = () => observation.startObservation(childName, childBody, options);
445
+ const createOwnedChild = () => store.withTracerProvider ? store.withTracerProvider(createChild) : createChild();
446
+ const createInheritingChild = propagate && Object.keys(inherited).length > 0
447
+ ? () => propagate(inherited, createOwnedChild)
448
+ : createOwnedChild;
449
+ const child = runtime?.withRootContext
450
+ ? runtime.withRootContext(createInheritingChild)
451
+ : createInheritingChild();
452
+ return wrapObservation(child, store, childName, childBody, options?.asType, id, externalTrace);
453
+ },
454
+ setTraceIO(traceBody) {
455
+ if (externalTrace)
456
+ return;
457
+ applyTraceUpdate(store, traceId, traceBody);
458
+ return observation.setTraceIO?.(traceBody);
459
+ },
460
+ };
461
+ }
462
+ async function getLegacyTraceApiCapability(rt, store, signal) {
463
+ if (store.legacyTraceApi) {
464
+ return store.legacyTraceApi;
465
+ }
466
+ const config = getRuntimeConfig(rt);
467
+ if (!config) {
468
+ return undefined;
469
+ }
470
+ try {
471
+ const response = await fetch(`${config.host.replace(/\/$/, "")}/api/public/traces?limit=1`, {
472
+ headers: ingestionHeaders(rt),
473
+ signal,
474
+ });
475
+ if (response.status === 404) {
476
+ store.legacyTraceApi = "unsupported";
477
+ return store.legacyTraceApi;
478
+ }
479
+ if (!response.ok) {
480
+ return undefined;
481
+ }
482
+ store.legacyTraceApi = "supported";
483
+ return store.legacyTraceApi;
484
+ }
485
+ catch (error) {
486
+ if (signal.aborted) {
487
+ throw error;
488
+ }
489
+ return undefined;
490
+ }
491
+ }
492
+ async function getTraceVisibility(rt, store, traceId, signal) {
493
+ const config = getRuntimeConfig(rt);
494
+ if (!config) {
495
+ return "unknown";
496
+ }
497
+ try {
498
+ const response = await fetch(`${config.host.replace(/\/$/, "")}/api/public/traces/${encodeURIComponent(traceId)}`, {
499
+ headers: ingestionHeaders(rt),
500
+ signal,
501
+ });
502
+ if (response.status === 404) {
503
+ const capability = await getLegacyTraceApiCapability(rt, store, signal);
504
+ if (capability === "supported") {
505
+ return "missing";
506
+ }
507
+ return capability === "unsupported" ? "legacy-api-unsupported" : "unknown";
508
+ }
509
+ if (!response.ok) {
510
+ return "unknown";
511
+ }
512
+ return "visible";
513
+ }
514
+ catch (error) {
515
+ if (signal.aborted) {
516
+ throw error;
517
+ }
518
+ return "unknown";
519
+ }
520
+ }
521
+ async function waitForTraceVisibility(rt, store, signal, shutdownDeadline) {
522
+ const now = Date.now();
523
+ // Leave a quarter of the remaining shutdown time for REST ingestion.
524
+ const deadline = now + Math.min(OTEL_VISIBILITY_TIMEOUT_MS, Math.max(0, shutdownDeadline - now) * 0.75);
525
+ const pending = new Map(store.traces);
526
+ const missing = new Set();
527
+ while (true) {
528
+ const ids = [...pending.keys()];
529
+ // Bound read concurrency and stop polling in time to send the REST batch.
530
+ for (let index = 0; index < ids.length && Date.now() < deadline; index += 4) {
531
+ const readSignal = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, Math.floor(deadline - Date.now())))]);
532
+ await Promise.all(ids.slice(index, index + 4).map(async (traceId) => {
533
+ try {
534
+ const visibility = await getTraceVisibility(rt, store, traceId, readSignal);
535
+ if (visibility === "missing")
536
+ missing.add(traceId);
537
+ else {
538
+ pending.delete(traceId);
539
+ missing.delete(traceId);
540
+ }
541
+ }
542
+ catch (error) {
543
+ if (signal.aborted || !readSignal.aborted)
544
+ throw error;
545
+ }
546
+ }));
547
+ }
548
+ const remainingMs = deadline - Date.now();
549
+ if (pending.size === 0 || remainingMs <= 0)
550
+ return [...pending.values()].filter(trace => missing.has(trace.id));
551
+ await delay(Math.min(OTEL_VISIBILITY_POLL_INTERVAL_MS, remainingMs), signal);
552
+ }
553
+ }
554
+ function eventTimestamp(record) {
555
+ return record.endTime ?? record.startTime ?? record.timestamp ?? nowIso();
556
+ }
557
+ async function fallbackToRestIngestion(rt, signal, shutdownDeadline) {
558
+ const store = rt.restFallback;
559
+ if (!store?.traces.size || store.attempted)
560
+ return;
561
+ store.attempted = true;
562
+ const traces = await waitForTraceVisibility(rt, store, signal, shutdownDeadline);
563
+ if (traces.length === 0)
564
+ return;
565
+ const missingIds = new Set(traces.map(trace => trace.id));
566
+ const entries = traces.map(trace => ({
567
+ type: "trace-create",
568
+ id: randomUUID(),
569
+ timestamp: eventTimestamp(trace),
570
+ body: { ...trace },
571
+ }));
572
+ for (const observation of store.observations) {
573
+ if (!missingIds.has(observation.traceId))
574
+ continue;
575
+ const body = {
576
+ id: observation.id,
577
+ traceId: observation.traceId,
578
+ name: observation.name,
579
+ startTime: observation.startTime,
580
+ endTime: observation.endTime,
581
+ input: observation.input,
582
+ output: observation.output,
583
+ metadata: observation.metadata,
584
+ level: observation.level,
585
+ statusMessage: observation.statusMessage,
586
+ parentObservationId: observation.parentObservationId,
587
+ ...(observation.type === "GENERATION"
588
+ ? {
589
+ completionStartTime: observation.completionStartTime,
590
+ model: observation.model,
591
+ modelParameters: observation.modelParameters,
592
+ usageDetails: observation.usageDetails,
593
+ costDetails: observation.costDetails,
594
+ }
595
+ : {}),
596
+ };
597
+ entries.push({
598
+ type: observation.type === "GENERATION" ? "generation-create" : "span-create",
599
+ id: randomUUID(),
600
+ timestamp: eventTimestamp(observation),
601
+ body,
602
+ });
603
+ }
604
+ const maxTotalBytes = getMaxFallbackTotalBytes();
605
+ const totalBytes = serializedBytes({ batch: entries });
606
+ if (totalBytes > maxTotalBytes) {
607
+ const message = `REST fallback payload is ${(totalBytes / 1024 / 1024).toFixed(1)}MB, above the ${(maxTotalBytes / 1024 / 1024).toFixed(1)}MB ceiling; skipping fallback ingestion`;
608
+ rememberRuntimeError("REST fallback ingestion", new Error(message));
609
+ console.warn(`📊 Langfuse: ${message}`);
610
+ return;
611
+ }
612
+ const chunks = splitIngestionBatch(entries, getMaxIngestionBatchBytes());
613
+ const errors = [];
614
+ for (const chunk of chunks) {
615
+ if (signal.aborted) {
616
+ break;
617
+ }
618
+ try {
619
+ errors.push(...(await ingestBatch(rt, chunk, signal)));
620
+ }
621
+ catch (error) {
622
+ if (signal.aborted && isAbortError(error)) {
623
+ break;
624
+ }
625
+ rememberRuntimeError("REST fallback ingestion", error);
626
+ console.warn("📊 Langfuse: REST fallback ingestion chunk failed", error);
627
+ errors.push(error instanceof Error ? error.message : String(error));
628
+ }
629
+ }
630
+ if (errors.length > 0) {
631
+ rememberRuntimeError("REST fallback ingestion", new Error(JSON.stringify(errors)));
632
+ console.warn("📊 Langfuse: REST fallback ingestion reported errors", errors);
633
+ }
634
+ else {
635
+ debugLog(`📊 Langfuse: Processed ${traces.length} missing trace(s) via REST ingestion (${chunks.length} chunk(s))`);
636
+ }
637
+ }
638
+ export async function getRuntime() {
639
+ if (!state.config) {
640
+ throw new Error("Langfuse config is not set");
641
+ }
642
+ // Track the current session as a runtime consumer.
643
+ // Multiple sessions can share the same runtime; shutdown is deferred
644
+ // until the last session releases it.
645
+ const sessionId = state.currentSessionId;
646
+ if (sessionId) {
647
+ activeSessions.add(sessionId);
648
+ }
649
+ if (!runtime) {
650
+ const [{ BasicTracerProvider }, { resources }, { context, ROOT_CONTEXT }, { AsyncHooksContextManager }, { LangfuseSpanProcessor }, tracing, { LangfuseClient },] = await Promise.all([
651
+ import("@opentelemetry/sdk-trace-base"),
652
+ import("@opentelemetry/sdk-node"),
653
+ import("@opentelemetry/api"),
654
+ import("@opentelemetry/context-async-hooks"),
655
+ import("@langfuse/otel"),
656
+ import("@langfuse/tracing"),
657
+ import("@langfuse/client"),
658
+ ]);
659
+ // Another caller may have initialized it while the shared imports loaded.
660
+ if (runtime)
661
+ return runtime;
662
+ const restFallback = {
663
+ traces: new Map(),
664
+ observations: [],
665
+ observationById: new Map(),
666
+ attempted: false,
667
+ };
668
+ try {
669
+ ensureOtelContextManager(context, AsyncHooksContextManager);
670
+ const scoreFlushAt = resolvePositiveEnvNumber("LANGFUSE_FLUSH_AT", DEFAULT_SCORE_FLUSH_AT, true);
671
+ const scoreFlushIntervalMs = resolvePositiveEnvNumber("LANGFUSE_FLUSH_INTERVAL", DEFAULT_SCORE_FLUSH_INTERVAL_MS / 1_000) * 1_000;
672
+ const scoreRequestTimeoutMs = resolvePositiveEnvNumber("LANGFUSE_TIMEOUT", DEFAULT_LANGFUSE_REQUEST_TIMEOUT_SECONDS) * 1_000;
673
+ const spanProcessor = new LangfuseSpanProcessor({
674
+ publicKey: state.config.publicKey,
675
+ secretKey: state.config.secretKey,
676
+ baseUrl: state.config.host,
677
+ });
678
+ const resource = resources.defaultResource().merge(resources.detectResources({ detectors: [resources.envDetector] }));
679
+ const tracerProvider = new BasicTracerProvider({ resource, spanProcessors: [spanProcessor] });
680
+ runtime = {
681
+ startObservation: (name, body, options) => {
682
+ const observation = restFallback.withTracerProvider(() => tracing.startObservation(name, body, options));
683
+ return wrapObservation(observation, restFallback, name, body, options?.asType, options?.parentSpanContext?.spanId, !!options?.parentSpanContext);
684
+ },
685
+ propagateAttributes: tracing.propagateAttributes,
686
+ withRootContext: (fn) => context.with(ROOT_CONTEXT, fn),
687
+ scoreClient: new LangfuseClient({
688
+ publicKey: state.config.publicKey,
689
+ secretKey: state.config.secretKey,
690
+ baseUrl: state.config.host,
691
+ }),
692
+ spanProcessor,
693
+ tracerProvider,
694
+ restFallback,
695
+ pendingScores: [],
696
+ scoreFlushAt,
697
+ scoreFlushIntervalMs,
698
+ scoreRequestTimeoutMs,
699
+ scoreFlushStopped: false,
700
+ runtimeConfig: {
701
+ publicKey: state.config.publicKey,
702
+ secretKey: state.config.secretKey,
703
+ host: state.config.host,
704
+ },
705
+ };
706
+ const ownedRuntime = runtime;
707
+ // Pi reloads extension modules per session, but the SDK provider is process-global.
708
+ restFallback.withTracerProvider = fn => {
709
+ const previous = tracing.getLangfuseTracerProvider();
710
+ tracing.setLangfuseTracerProvider(ownedRuntime.tracerProvider);
711
+ try {
712
+ return fn();
713
+ }
714
+ finally {
715
+ tracing.setLangfuseTracerProvider(previous);
716
+ }
717
+ };
718
+ lastRuntimeError = null;
719
+ }
720
+ catch (e) {
721
+ rememberRuntimeError("runtime init", e);
722
+ throw e;
723
+ }
724
+ }
725
+ return runtime;
726
+ }
727
+ function doShutdownRuntime() {
728
+ return (async () => {
729
+ if (!runtime) {
730
+ return;
731
+ }
732
+ const rt = runtime;
733
+ runtime = null;
734
+ const deadline = Date.now() + shutdownStepTimeoutMs;
735
+ const controller = new AbortController();
736
+ const abortTimeout = setTimeout(() => controller.abort(), shutdownStepTimeoutMs);
737
+ const scoreController = new AbortController();
738
+ const scoreShutdownTimeoutMs = Math.min(getScoreShutdownTimeoutMs(), shutdownStepTimeoutMs);
739
+ const scoreDeadline = Math.min(deadline, Date.now() + scoreShutdownTimeoutMs);
740
+ const scoreAbortTimeout = setTimeout(() => scoreController.abort(), scoreShutdownTimeoutMs);
741
+ scoreAbortTimeout.unref?.();
742
+ stopScoreFlush(rt);
743
+ try {
744
+ await runShutdownStep("Active score flush", () => rt.scoreFlushPromise, deadline);
745
+ await runShutdownStep("Pending score flush", () => flushPendingScores(rt, scoreController.signal), scoreDeadline, scoreController.signal);
746
+ await runShutdownStep("OTel force flush", () => rt.tracerProvider?.forceFlush?.(), deadline);
747
+ await runShutdownStep("Langfuse score flush", () => rt.scoreClient.flush?.(), deadline);
748
+ await runShutdownStep("Langfuse client shutdown", () => rt.scoreClient.shutdown?.(), deadline);
749
+ await runShutdownStep("OTel tracer shutdown", () => rt.tracerProvider?.shutdown?.(), deadline);
750
+ await runShutdownStep("REST fallback ingestion", () => fallbackToRestIngestion(rt, controller.signal, deadline), deadline, controller.signal);
751
+ }
752
+ finally {
753
+ clearTimeout(abortTimeout);
754
+ clearTimeout(scoreAbortTimeout);
755
+ scoreController.abort();
756
+ clearScoreFlushTimer(rt);
757
+ rt.scoreFlushController?.abort();
758
+ rt.scoreFlushController = undefined;
759
+ rt.scoreFlushPromise = undefined;
760
+ if (!runtime) {
761
+ rt.clearTracerProvider?.();
762
+ }
763
+ }
764
+ })();
765
+ }
766
+ /**
767
+ * Release the current session's reference to the Langfuse runtime.
768
+ * Only actually shuts down the runtime when the last session releases it.
769
+ * Accepts an optional sessionId for use outside of withSession (e.g. deferred callbacks).
770
+ */
771
+ export async function shutdownRuntime(sessionId) {
772
+ const sid = sessionId ?? state.currentSessionId;
773
+ if (sid) {
774
+ activeSessions.delete(sid);
775
+ }
776
+ // Still have active sessions — keep the runtime alive.
777
+ if (activeSessions.size > 0) {
778
+ return;
779
+ }
780
+ await doShutdownRuntime();
781
+ }
782
+ /**
783
+ * Force-shutdown the Langfuse runtime regardless of active session references.
784
+ * Used when the user manually reconfigures (e.g. /langfuse-setup) and needs
785
+ * a fresh runtime with new credentials.
786
+ */
787
+ export async function forceShutdownRuntime() {
788
+ activeSessions.clear();
789
+ await doShutdownRuntime();
790
+ }
791
+ export function __setRuntimeForTest(rt, timeoutMs = DEFAULT_SHUTDOWN_STEP_TIMEOUT_MS) {
792
+ if (runtime && runtime !== rt) {
793
+ stopScoreFlush(runtime);
794
+ }
795
+ runtime = rt;
796
+ if (rt) {
797
+ rt.scoreFlushStopped = false;
798
+ }
799
+ shutdownStepTimeoutMs = timeoutMs;
800
+ activeSessions.clear();
801
+ }
802
+ export async function sendScore(name, value, options = {}) {
803
+ try {
804
+ const rt = await getRuntime();
805
+ const score = {
806
+ name,
807
+ value,
808
+ dataType: name === "session_had_errors" || name === "tool_is_error" ? "BOOLEAN" : "NUMERIC",
809
+ traceId: options.traceId,
810
+ observationId: options.observationId,
811
+ sessionId: options.traceId ? undefined : state.currentSessionId || undefined,
812
+ ...(process.env.LANGFUSE_TRACING_ENVIRONMENT
813
+ ? { environment: process.env.LANGFUSE_TRACING_ENVIRONMENT }
814
+ : {}),
815
+ };
816
+ if (!rt.pendingScores) {
817
+ return;
818
+ }
819
+ if (rt.pendingScores.length >= MAX_SCORE_QUEUE_SIZE) {
820
+ const error = new Error(`Langfuse score queue is full (${MAX_SCORE_QUEUE_SIZE}); dropping score`);
821
+ rememberRuntimeError("score queue", error);
822
+ console.warn(`📊 Langfuse: ${error.message}`);
823
+ return;
824
+ }
825
+ rt.pendingScores.push(score);
826
+ if (rt.pendingScores.length >= (rt.scoreFlushAt ?? DEFAULT_SCORE_FLUSH_AT)) {
827
+ void startScoreFlush(rt);
828
+ }
829
+ else {
830
+ scheduleScoreFlush(rt);
831
+ }
832
+ }
833
+ catch (e) {
834
+ rememberRuntimeError(`score ${name}`, e);
835
+ console.warn(`📊 Langfuse: Failed to send score ${name}`, e);
836
+ }
837
+ }