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
@@ -15,6 +15,8 @@ import {
15
15
  extractCacheMetrics,
16
16
  inferToolUpdateTransport,
17
17
  extractModelIdentity,
18
+ extractGenerationStatus,
19
+ toStatusMessage,
18
20
  } from "../utils.js";
19
21
  import type { GenerationState, ObservationUpdate } from "../types.js";
20
22
  import { applyCapturePolicy } from "../capture-policy.js";
@@ -114,50 +116,19 @@ export function updateGenerationMetadata(event: Record<string, unknown>) {
114
116
 
115
117
  const key = getRequestKey(event, "");
116
118
  const metadata = applyCapturePolicy({ metadata: extractResponseMetadata(event) }, getCapturePolicy()).metadata ?? {};
117
- if (!key) {
118
- const generation = getOpenGeneration();
119
- if (generation) {
120
- generation.metadata = { ...generation.metadata, ...metadata };
121
-
122
- const isError =
123
- (typeof metadata.status === "number" && metadata.status >= 400) ||
124
- event.error ||
125
- event.isError;
126
-
127
- if (isError) {
128
- generation.observation.update({
129
- metadata: generation.metadata,
130
- level: "ERROR",
131
- statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
132
- }).end();
133
- generation.ended = true;
134
- } else {
135
- generation.observation.update({ metadata: generation.metadata });
136
- }
137
- }
138
- return;
139
- }
119
+ const generation = (key ? state.agentState.activeGenerations.get(key) : undefined) ?? getOpenGeneration();
120
+ if (!generation || generation.ended) return;
140
121
 
141
- const generation = state.agentState.activeGenerations.get(key) ?? getOpenGeneration();
142
- if (generation) {
143
- generation.metadata = { ...generation.metadata, ...metadata };
144
-
145
- const isError =
146
- (typeof metadata.status === "number" && metadata.status >= 400) ||
147
- event.error ||
148
- event.isError;
149
-
150
- if (isError) {
151
- generation.observation.update({
152
- metadata: generation.metadata,
153
- level: "ERROR",
154
- statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
155
- }).end();
156
- generation.ended = true;
157
- } else {
158
- generation.observation.update({ metadata: generation.metadata });
159
- }
122
+ generation.metadata = { ...generation.metadata, ...metadata };
123
+ const isError = (typeof metadata.status === "number" && metadata.status >= 400) || event.error || event.isError;
124
+ if (isError) {
125
+ generation.errorStatus = {
126
+ level: "ERROR",
127
+ statusMessage: toStatusMessage(event.error ?? metadata.statusMessage ?? "Provider request failed"),
128
+ };
160
129
  }
130
+ // The assistant message supplies final error details and usage; close there.
131
+ generation.observation.update({ metadata: generation.metadata, ...generation.errorStatus });
161
132
  }
162
133
 
163
134
  export function recordTTFT(event: Record<string, unknown>) {
@@ -218,7 +189,12 @@ export async function finishGenerationFromMessage(event: Record<string, unknown>
218
189
  const cacheMetrics = extractCacheMetrics({ ...event, message });
219
190
  const modelParameters = extractModelParameters(getProviderPayload(event)) ?? generation.modelParameters;
220
191
  const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
192
+ const finishReason = message.finishReason ?? message.stopReason;
221
193
  const update: ObservationUpdate = {
194
+ ...(generation.errorStatus && ["stop", "toolUse", "length"].includes(String(finishReason))
195
+ ? { level: "DEFAULT" as const, statusMessage: "" }
196
+ : {}),
197
+ ...extractGenerationStatus(message),
222
198
  output,
223
199
  model: actual.model ?? (generation.metadata.actualModel as string | undefined) ?? (state.currentModel || undefined),
224
200
  modelParameters,
@@ -228,7 +204,7 @@ export async function finishGenerationFromMessage(event: Record<string, unknown>
228
204
  ...generation.metadata,
229
205
  ...(actual.model ? { actualModel: actual.model } : {}),
230
206
  ...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
231
- finishReason: message.finishReason ?? message.stopReason ?? event.finishReason,
207
+ finishReason: finishReason ?? event.finishReason,
232
208
  ...cacheMetrics,
233
209
  },
234
210
  };
@@ -270,6 +246,7 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
270
246
  actualModel: actual.model,
271
247
  actualProvider: actual.provider,
272
248
  sourceEvent: "turn_end",
249
+ finishReason: message.finishReason ?? message.stopReason ?? event.finishReason,
273
250
  promptStateHash: state.agentState.promptStateHash,
274
251
  toolStateHash: state.agentState.toolStateHash,
275
252
  systemStateSequence: state.agentState.systemStateSequence,
@@ -285,6 +262,7 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
285
262
  runtime: getRuntime,
286
263
  name: "llm-generation",
287
264
  body: {
265
+ ...extractGenerationStatus(message),
288
266
  input: captured.input,
289
267
  output: captured.output,
290
268
  model: actual.model ?? (state.currentModel || undefined),
@@ -1,16 +1,77 @@
1
1
  import { applyCapturePolicy } from "../capture-policy.js";
2
2
  import { getRuntime } from "../langfuse.js";
3
- import { startChildObservation } from "../observation.js";
3
+ import { startChildObservation, startSessionObservation } from "../observation.js";
4
4
  import { state } from "../state.js";
5
+ import { sessionGroupId } from "../workflow.js";
6
+ import { sessionLineageMetadata } from "../session-lineage.js";
5
7
  import {
6
8
  extractCostDetails,
9
+ extractGenerationStatus,
7
10
  extractUsage,
8
11
  getCapturePolicy,
9
12
  shapePayload,
10
13
  } from "../utils.js";
14
+ import type { LangfuseObservation, ObservationUpdate } from "../types.js";
11
15
 
12
16
  type RecordLike = Record<string, unknown>;
13
17
 
18
+ // Compaction can fire after the run already settled, so the event has no agent
19
+ // root to nest under. A rootless observation still belongs to the session, hence
20
+ // its own trace name instead of being dropped.
21
+ const SESSION_TRACE_NAME = "pi-session";
22
+
23
+ function startCompactionObservation(
24
+ name: string,
25
+ body: ObservationUpdate,
26
+ asType: "event" | "span",
27
+ ): Promise<LangfuseObservation> {
28
+ const agent = state.agentState;
29
+ const parent = agent?.activeTurn ?? agent?.activeAttempt ?? agent?.root;
30
+ if (parent) {
31
+ return startChildObservation({ parent, runtime: getRuntime, name, body, asType });
32
+ }
33
+
34
+ return startSessionObservation({
35
+ runtime: getRuntime,
36
+ name,
37
+ body,
38
+ asType,
39
+ attributes: {
40
+ sessionId: sessionGroupId(),
41
+ userId: state.config?.userId,
42
+ traceName: SESSION_TRACE_NAME,
43
+ metadata: { piScope: "session", ...sessionLineageMetadata() },
44
+ },
45
+ });
46
+ }
47
+
48
+ export async function recordSessionCompactionFailure(event: RecordLike): Promise<void> {
49
+ if (state.isTracingDisabled) return;
50
+
51
+ try {
52
+ const observation = await startCompactionObservation(
53
+ "session-compaction-failed",
54
+ {
55
+ ...extractGenerationStatus({
56
+ stopReason: event.aborted ? "aborted" : "error",
57
+ errorMessage: event.errorMessage
58
+ || (event.aborted ? "Compaction cancelled" : "Compaction failed"),
59
+ }),
60
+ metadata: shapePayload({
61
+ reason: event.reason,
62
+ aborted: event.aborted,
63
+ willRetry: event.willRetry,
64
+ fromExtension: event.fromExtension,
65
+ }) as RecordLike,
66
+ },
67
+ "event",
68
+ );
69
+ observation.end();
70
+ } catch (error) {
71
+ console.warn("📊 Langfuse: Failed to record compaction failure", error);
72
+ }
73
+ }
74
+
14
75
  function namesFromTools(value: unknown): string[] {
15
76
  if (!Array.isArray(value)) return [];
16
77
  return value.flatMap((tool) => {
@@ -22,9 +83,9 @@ function namesFromTools(value: unknown): string[] {
22
83
  }
23
84
 
24
85
  export async function recordSessionCompaction(event: RecordLike): Promise<void> {
25
- const agent = state.agentState;
26
- if (state.isTracingDisabled || !agent?.root) return;
86
+ if (state.isTracingDisabled) return;
27
87
 
88
+ const agent = state.agentState;
28
89
  const entry = event.compactionEntry && typeof event.compactionEntry === "object"
29
90
  ? event.compactionEntry as RecordLike
30
91
  : {};
@@ -48,22 +109,19 @@ export async function recordSessionCompaction(event: RecordLike): Promise<void>
48
109
  checkpointSectionNames: checkpointSections,
49
110
  checkpointToolNames: checkpointTools,
50
111
  checkpointToolCount: checkpointTools.length,
51
- promptStateHash: agent.promptStateHash,
52
- toolStateHash: agent.toolStateHash,
112
+ promptStateHash: agent?.promptStateHash,
113
+ toolStateHash: agent?.toolStateHash,
53
114
  },
54
115
  },
55
116
  getCapturePolicy(),
56
117
  );
57
118
 
58
119
  try {
59
- const parent = agent.activeTurn ?? agent.activeAttempt ?? agent.root;
60
- const compaction = await startChildObservation({
61
- parent,
62
- runtime: getRuntime,
63
- name: "session-compaction",
64
- body: { input: captured.input, metadata: captured.metadata },
65
- asType: "span",
66
- });
120
+ const compaction = await startCompactionObservation(
121
+ "session-compaction",
122
+ { input: captured.input, metadata: captured.metadata },
123
+ "span",
124
+ );
67
125
 
68
126
  if (entry.usage && typeof entry.usage === "object") {
69
127
  const summary = applyCapturePolicy({ output: entry.summary }, getCapturePolicy());
@@ -1,4 +1,5 @@
1
- import { state } from "../state.js";
1
+ import { getSessionRunState, state } from "../state.js";
2
+ import { warnWorkflow } from "../workflow.js";
2
3
  import { getRuntime, sendScore } from "../langfuse.js";
3
4
  import { startChildObservation } from "../observation.js";
4
5
  import {
@@ -7,14 +8,13 @@ import {
7
8
  getToolInput,
8
9
  shapePayload,
9
10
  extractTextContent,
10
- truncate,
11
+ toStatusMessage,
11
12
  estimatePayloadBytes,
12
13
  getCapturePolicy,
13
14
  getLimits,
14
15
  extractToolUsage,
15
16
  } from "../utils.js";
16
- import { applyCapturePolicy, redactOptionsFor } from "../capture-policy.js";
17
- import { redactString } from "../redaction.js";
17
+ import { applyCapturePolicy } from "../capture-policy.js";
18
18
 
19
19
  export async function startToolObservation(event: Record<string, unknown>) {
20
20
  if (state.isTracingDisabled || !state.agentState?.root) {
@@ -85,7 +85,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
85
85
 
86
86
  const isError = Boolean(event.isError ?? event.error ?? event.status === "error");
87
87
  const output =
88
- extractTextContent(event.content, getLimits().maxToolPayload) ??
88
+ extractTextContent(event.content) ??
89
89
  event.output ??
90
90
  event.result ??
91
91
  event.error ??
@@ -94,7 +94,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
94
94
 
95
95
  try {
96
96
  const policy = getCapturePolicy();
97
- const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload });
97
+ const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload, parseJsonPrefix: isError });
98
98
  const captured = applyCapturePolicy(
99
99
  {
100
100
  toolOutput: shapedOutput,
@@ -144,7 +144,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
144
144
  output: captured.toolOutput,
145
145
  level: isError ? "ERROR" : "DEFAULT",
146
146
  statusMessage: isError
147
- ? redactString(truncate(String(event.error ?? output), 1_000), redactOptionsFor(policy))
147
+ ? toStatusMessage(event.error ?? output, 1_000)
148
148
  : undefined,
149
149
  metadata: {
150
150
  ...(captured.metadata ?? {}),
@@ -156,6 +156,10 @@ export async function finishToolObservation(event: Record<string, unknown>) {
156
156
  .end();
157
157
  if (isError) {
158
158
  state.errorCount++;
159
+ if (getSessionRunState().runBinding?.parent && (!activeTool.observation.id || !state.agentState.traceId)) {
160
+ warnWorkflow("Skipping workflow tool score without an observation identity.");
161
+ return;
162
+ }
159
163
  await sendScore("tool_is_error", 1, {
160
164
  traceId: state.agentState.traceId,
161
165
  observationId: activeTool.observation.id,
@@ -184,7 +188,7 @@ export function closeDanglingObservations(statusMessage: string) {
184
188
 
185
189
  for (const generation of state.agentState.activeGenerations.values()) {
186
190
  if (!generation.ended) {
187
- generation.observation.update({ level: "WARNING", statusMessage, metadata: { ...generation.metadata, cancelled: true } }).end();
191
+ generation.observation.update({ level: "WARNING", statusMessage, ...generation.errorStatus, metadata: { ...generation.metadata, cancelled: true } }).end();
188
192
  generation.ended = true;
189
193
  }
190
194
  }
package/src/langfuse.ts CHANGED
@@ -54,7 +54,8 @@ interface RestFallbackObservation {
54
54
  }
55
55
 
56
56
  interface RestFallbackStore {
57
- trace?: RestFallbackTrace;
57
+ withTracerProvider?: <T>(fn: () => T) => T;
58
+ traces: Map<string, RestFallbackTrace>;
58
59
  observations: RestFallbackObservation[];
59
60
  observationById: Map<string, RestFallbackObservation>;
60
61
  attempted: boolean;
@@ -132,7 +133,7 @@ function delay(ms: number, signal?: AbortSignal) {
132
133
 
133
134
  function debugLog(message: string) {
134
135
  if (process.env.PI_LANGFUSE_DEBUG === "1" || process.env.PI_LANGFUSE_DEBUG === "true") {
135
- console.log(message);
136
+ console.error(message);
136
137
  }
137
138
  }
138
139
 
@@ -274,7 +275,8 @@ function serializedBytes(value: unknown): number {
274
275
 
275
276
  /**
276
277
  * Split an ingestion event list into chunks whose serialized request bodies each
277
- * stay under `maxBytes`. Each chunk, when wrapped as `{ batch: chunk }`, matches
278
+ * stay under `maxBytes`, skipping individually oversized events with a warning.
279
+ * Each chunk, when wrapped as `{ batch: chunk }`, matches
278
280
  * the measurement exactly because entries are serialized individually and joined
279
281
  * with single commas inside the `{"batch":[...]}` envelope.
280
282
  */
@@ -287,6 +289,12 @@ export function splitIngestionBatch(entries: unknown[], maxBytes: number): unkno
287
289
 
288
290
  for (let index = 0; index < serialized.length; index++) {
289
291
  const entryBytes = Buffer.byteLength(serialized[index], "utf8");
292
+ if (envelopeBytes + entryBytes > maxBytes) {
293
+ const message = `Skipping oversized REST fallback event (${envelopeBytes + entryBytes} bytes exceeds ${maxBytes}-byte request budget)`;
294
+ rememberRuntimeError("REST fallback ingestion", new Error(message));
295
+ console.warn(`📊 Langfuse: ${message}`);
296
+ continue;
297
+ }
290
298
  const separators = chunk.length > 0 ? 1 : 0;
291
299
  const projectedBytes = chunkBytes + entryBytes + separators;
292
300
  if (chunk.length > 0 && projectedBytes > maxBytes) {
@@ -443,15 +451,16 @@ function applyObservationUpdate(record: RestFallbackObservation, body: Record<st
443
451
  if (completionStartTime) record.completionStartTime = completionStartTime;
444
452
  }
445
453
 
446
- function applyTraceUpdate(store: RestFallbackStore, body: Record<string, unknown> | undefined) {
447
- if (!store.trace || !body) {
454
+ function applyTraceUpdate(store: RestFallbackStore, traceId: string, body: Record<string, unknown> | undefined) {
455
+ const trace = store.traces.get(traceId);
456
+ if (!trace || !body) {
448
457
  return;
449
458
  }
450
459
 
451
- if ("input" in body) store.trace.input = body.input;
452
- if ("output" in body) store.trace.output = body.output;
460
+ if ("input" in body) trace.input = body.input;
461
+ if ("output" in body) trace.output = body.output;
453
462
  if ("metadata" in body && body.metadata && typeof body.metadata === "object") {
454
- store.trace.metadata = mergeMetadata(store.trace.metadata, body.metadata as Record<string, unknown>);
463
+ trace.metadata = mergeMetadata(trace.metadata, body.metadata as Record<string, unknown>);
455
464
  }
456
465
  }
457
466
 
@@ -533,16 +542,16 @@ function readPropagatedAttributes(observation: any): PropagatedAttributes {
533
542
  return propagated;
534
543
  }
535
544
 
536
- function wrapObservation(
537
- observation: any,
545
+ function recordFallbackObservation(
538
546
  store: RestFallbackStore,
547
+ observation: any,
548
+ id: string,
549
+ traceId: string,
539
550
  name: string,
540
- body: Record<string, unknown> | undefined,
551
+ body?: Record<string, unknown>,
541
552
  asType?: string,
542
553
  parentObservationId?: string,
543
- ): any {
544
- const id = observation.id || randomUUID();
545
- const traceId = observation.traceId || store.trace?.id || randomUUID();
554
+ ) {
546
555
  const metadata = body?.metadata && typeof body.metadata === "object" ? body.metadata as Record<string, unknown> : undefined;
547
556
  const record: RestFallbackObservation = {
548
557
  id,
@@ -558,60 +567,79 @@ function wrapObservation(
558
567
  store.observations.push(record);
559
568
  store.observationById.set(id, record);
560
569
 
561
- if (!parentObservationId && !store.trace) {
570
+ if (!parentObservationId && !store.traces.has(traceId)) {
562
571
  const propagated = readPropagatedAttributes(observation);
563
- store.trace = {
572
+ store.traces.set(traceId, {
564
573
  id: traceId,
565
574
  timestamp: record.startTime,
566
- name,
575
+ name: propagated.traceName ?? name,
567
576
  input: body?.input,
568
577
  sessionId: propagated.sessionId
569
578
  ?? (typeof metadata?.sessionId === "string" ? metadata.sessionId : state.currentSessionId || undefined),
570
579
  userId: propagated.userId ?? state.config?.userId,
571
- metadata,
572
- };
580
+ metadata: mergeMetadata(propagated.metadata, metadata),
581
+ });
573
582
  }
574
583
 
584
+ return record;
585
+ }
586
+
587
+ function wrapObservation(
588
+ observation: any,
589
+ store: RestFallbackStore,
590
+ name: string,
591
+ body: Record<string, unknown> | undefined,
592
+ asType?: string,
593
+ parentObservationId?: string,
594
+ externalTrace = false,
595
+ ): any {
596
+ const id = observation.id ?? (externalTrace ? undefined : randomUUID());
597
+ const traceId = observation.traceId ?? (externalTrace ? undefined : randomUUID());
598
+ const record = externalTrace ? undefined
599
+ : recordFallbackObservation(store, observation, id, traceId, name, body, asType, parentObservationId);
600
+
575
601
  return {
576
602
  ...observation,
577
603
  id,
578
604
  traceId,
579
605
  update(updateBody?: Record<string, unknown>) {
580
- applyObservationUpdate(record, updateBody);
581
- if (!parentObservationId) {
582
- applyTraceUpdate(store, updateBody);
606
+ if (record) applyObservationUpdate(record, updateBody);
607
+ if (record && !parentObservationId) {
608
+ applyTraceUpdate(store, traceId, updateBody);
583
609
  }
584
610
  const updated = observation.update(updateBody);
585
611
  return updated === observation ? this : updated;
586
612
  },
587
613
  end(endBody?: Record<string, unknown>) {
588
- if (endBody && typeof endBody === "object") {
614
+ if (record && endBody && typeof endBody === "object") {
589
615
  applyObservationUpdate(record, endBody);
590
616
  if (!parentObservationId) {
591
- applyTraceUpdate(store, endBody);
617
+ applyTraceUpdate(store, traceId, endBody);
592
618
  }
593
619
  }
594
- record.endTime = nowIso();
620
+ if (record) record.endTime = nowIso();
595
621
  return observation.end();
596
622
  },
597
623
  startObservation(childName: string, childBody?: Record<string, unknown>, options?: { asType?: string }) {
598
624
  const inherited = readPropagatedAttributes(observation);
599
625
  const fallbackSessionId = state.currentSessionId?.slice(0, 200);
600
- if (!inherited.sessionId && fallbackSessionId) {
626
+ if (!externalTrace && !inherited.sessionId && fallbackSessionId) {
601
627
  inherited.sessionId = fallbackSessionId;
602
628
  }
603
629
  const propagate = runtime?.propagateAttributes;
604
630
  const createChild = () => observation.startObservation(childName, childBody, options);
631
+ const createOwnedChild = () => store.withTracerProvider ? store.withTracerProvider(createChild) : createChild();
605
632
  const createInheritingChild = propagate && Object.keys(inherited).length > 0
606
- ? () => propagate(inherited, createChild)
607
- : createChild;
633
+ ? () => propagate(inherited, createOwnedChild)
634
+ : createOwnedChild;
608
635
  const child = runtime?.withRootContext
609
636
  ? runtime.withRootContext(createInheritingChild)
610
637
  : createInheritingChild();
611
- return wrapObservation(child, store, childName, childBody, options?.asType, id);
638
+ return wrapObservation(child, store, childName, childBody, options?.asType, id, externalTrace);
612
639
  },
613
640
  setTraceIO(traceBody?: { input?: unknown; output?: unknown }) {
614
- applyTraceUpdate(store, traceBody);
641
+ if (externalTrace) return;
642
+ applyTraceUpdate(store, traceId, traceBody);
615
643
  return observation.setTraceIO?.(traceBody);
616
644
  },
617
645
  };
@@ -694,22 +722,32 @@ async function getTraceVisibility(
694
722
  async function waitForTraceVisibility(
695
723
  rt: LangfuseRuntime,
696
724
  store: RestFallbackStore,
697
- traceId: string,
698
725
  signal: AbortSignal,
699
- ): Promise<TraceVisibility> {
700
- const deadline = Date.now() + OTEL_VISIBILITY_TIMEOUT_MS;
726
+ shutdownDeadline: number,
727
+ ): Promise<RestFallbackTrace[]> {
728
+ const now = Date.now();
729
+ // Leave a quarter of the remaining shutdown time for REST ingestion.
730
+ const deadline = now + Math.min(OTEL_VISIBILITY_TIMEOUT_MS, Math.max(0, shutdownDeadline - now) * 0.75);
731
+ const pending = new Map(store.traces);
732
+ const missing = new Set<string>();
701
733
 
702
734
  while (true) {
703
- const visibility = await getTraceVisibility(rt, store, traceId, signal);
704
- if (visibility !== "missing") {
705
- return visibility;
735
+ const ids = [...pending.keys()];
736
+ // Bound read concurrency and stop polling in time to send the REST batch.
737
+ for (let index = 0; index < ids.length && Date.now() < deadline; index += 4) {
738
+ const readSignal = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, Math.floor(deadline - Date.now())))]);
739
+ await Promise.all(ids.slice(index, index + 4).map(async traceId => {
740
+ try {
741
+ const visibility = await getTraceVisibility(rt, store, traceId, readSignal);
742
+ if (visibility === "missing") missing.add(traceId);
743
+ else { pending.delete(traceId); missing.delete(traceId); }
744
+ } catch (error) {
745
+ if (signal.aborted || !readSignal.aborted) throw error;
746
+ }
747
+ }));
706
748
  }
707
-
708
749
  const remainingMs = deadline - Date.now();
709
- if (remainingMs <= 0) {
710
- return "missing";
711
- }
712
-
750
+ if (pending.size === 0 || remainingMs <= 0) return [...pending.values()].filter(trace => missing.has(trace.id));
713
751
  await delay(Math.min(OTEL_VISIBILITY_POLL_INTERVAL_MS, remainingMs), signal);
714
752
  }
715
753
  }
@@ -718,42 +756,23 @@ function eventTimestamp(record: { endTime?: string; startTime?: string; timestam
718
756
  return record.endTime ?? record.startTime ?? record.timestamp ?? nowIso();
719
757
  }
720
758
 
721
- async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal) {
759
+ async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal, shutdownDeadline: number) {
722
760
  const store = rt.restFallback as RestFallbackStore | undefined;
723
- if (!store?.trace || store.attempted) {
724
- return;
725
- }
761
+ if (!store?.traces.size || store.attempted) return;
726
762
  store.attempted = true;
727
763
 
728
- const visibility = await waitForTraceVisibility(rt, store, store.trace.id, signal);
729
- if (visibility === "visible") {
730
- return;
731
- }
732
- if (visibility !== "missing") {
733
- debugLog(`📊 Langfuse: Skipped REST fallback; trace visibility is ${visibility}`);
734
- return;
735
- }
736
-
737
- const trace = store.trace;
738
- const entries: any[] = [
739
- {
740
- type: "trace-create",
741
- id: randomUUID(),
742
- timestamp: eventTimestamp(trace),
743
- body: {
744
- id: trace.id,
745
- timestamp: trace.timestamp,
746
- name: trace.name,
747
- input: trace.input,
748
- output: trace.output,
749
- sessionId: trace.sessionId,
750
- userId: trace.userId,
751
- metadata: trace.metadata,
752
- },
753
- },
754
- ];
764
+ const traces = await waitForTraceVisibility(rt, store, signal, shutdownDeadline);
765
+ if (traces.length === 0) return;
766
+ const missingIds = new Set(traces.map(trace => trace.id));
767
+ const entries: any[] = traces.map(trace => ({
768
+ type: "trace-create",
769
+ id: randomUUID(),
770
+ timestamp: eventTimestamp(trace),
771
+ body: { ...trace },
772
+ }));
755
773
 
756
774
  for (const observation of store.observations) {
775
+ if (!missingIds.has(observation.traceId)) continue;
757
776
  const body = {
758
777
  id: observation.id,
759
778
  traceId: observation.traceId,
@@ -815,7 +834,7 @@ async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal)
815
834
  console.warn("📊 Langfuse: REST fallback ingestion reported errors", errors);
816
835
  } else {
817
836
  debugLog(
818
- `📊 Langfuse: OTel trace ${trace.id} was not visible; wrote fallback trace via REST ingestion (${chunks.length} chunk(s))`,
837
+ `📊 Langfuse: Processed ${traces.length} missing trace(s) via REST ingestion (${chunks.length} chunk(s))`,
819
838
  );
820
839
  }
821
840
  }
@@ -852,7 +871,11 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
852
871
  import("@langfuse/client"),
853
872
  ]);
854
873
 
874
+ // Another caller may have initialized it while the shared imports loaded.
875
+ if (runtime) return runtime;
876
+
855
877
  const restFallback: RestFallbackStore = {
878
+ traces: new Map(),
856
879
  observations: [],
857
880
  observationById: new Map(),
858
881
  attempted: false,
@@ -874,13 +897,13 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
874
897
  resources.detectResources({ detectors: [resources.envDetector] }),
875
898
  );
876
899
  const tracerProvider = new BasicTracerProvider({ resource, spanProcessors: [spanProcessor] });
877
- tracing.setLangfuseTracerProvider(tracerProvider);
878
900
 
879
901
  runtime = {
880
- startObservation: ((name: string, body?: Record<string, unknown>, options?: { asType?: string }) => {
881
- const observation = (tracing as any).startObservation(name, body, options);
882
- return wrapObservation(observation, restFallback, name, body, options?.asType);
883
- }) as unknown as LangfuseRuntime["startObservation"],
902
+ startObservation: (name, body, options) => {
903
+ const observation = restFallback.withTracerProvider!(() => (tracing as any).startObservation(name, body, options));
904
+ return wrapObservation(observation, restFallback, name, body as Record<string, unknown>, options?.asType,
905
+ options?.parentSpanContext?.spanId, !!options?.parentSpanContext);
906
+ },
884
907
  propagateAttributes: tracing.propagateAttributes as unknown as LangfuseRuntime["propagateAttributes"],
885
908
  withRootContext: (fn) => context.with(ROOT_CONTEXT, fn),
886
909
  scoreClient: new LangfuseClient({
@@ -890,7 +913,6 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
890
913
  }) as LangfuseScoreClient,
891
914
  spanProcessor,
892
915
  tracerProvider,
893
- clearTracerProvider: () => tracing.setLangfuseTracerProvider(null),
894
916
  restFallback,
895
917
  pendingScores: [],
896
918
  scoreFlushAt,
@@ -903,6 +925,14 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
903
925
  host: state.config.host,
904
926
  },
905
927
  };
928
+ const ownedRuntime = runtime;
929
+ // Pi reloads extension modules per session, but the SDK provider is process-global.
930
+ restFallback.withTracerProvider = fn => {
931
+ const previous = tracing.getLangfuseTracerProvider();
932
+ tracing.setLangfuseTracerProvider(ownedRuntime.tracerProvider);
933
+ try { return fn(); }
934
+ finally { tracing.setLangfuseTracerProvider(previous); }
935
+ };
906
936
  lastRuntimeError = null;
907
937
  } catch (e) {
908
938
  rememberRuntimeError("runtime init", e);
@@ -952,7 +982,7 @@ function doShutdownRuntime(): Promise<void> {
952
982
  await runShutdownStep("OTel tracer shutdown", () => rt.tracerProvider?.shutdown?.(), deadline);
953
983
  await runShutdownStep(
954
984
  "REST fallback ingestion",
955
- () => fallbackToRestIngestion(rt, controller.signal),
985
+ () => fallbackToRestIngestion(rt, controller.signal, deadline),
956
986
  deadline,
957
987
  controller.signal,
958
988
  );