pi-langfuse 1.6.1 → 1.7.1

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.
@@ -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 { sessionLineageMetadata } from "../session-lineage.js";
5
6
  import {
6
7
  extractCostDetails,
8
+ extractGenerationStatus,
7
9
  extractUsage,
8
10
  getCapturePolicy,
9
11
  shapePayload,
12
+ truncate,
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: state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined,
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());
@@ -73,7 +73,7 @@ export function initializeSystemStateTracking(ctx: any): void {
73
73
  }
74
74
  }
75
75
 
76
- export async function recordSystemState(ctx: any, activeTools: string[]): Promise<void> {
76
+ export async function recordSystemState(ctx: any, activeTools: string[], emitUnchanged = true): Promise<void> {
77
77
  const agent = state.agentState;
78
78
  if (state.isTracingDisabled || !agent?.root) return;
79
79
 
@@ -133,6 +133,9 @@ export async function recordSystemState(ctx: any, activeTools: string[]): Promis
133
133
  const changed = isInitial || promptChanged || toolsChanged || systemMessages.length > 0;
134
134
  if (changed) session.systemStateSequence++;
135
135
 
136
+ // agent_start emits a snapshot; unchanged request hooks keep the existing reference.
137
+ if (!changed && !emitUnchanged && agent.systemStateSequence !== undefined) return;
138
+
136
139
  const capturePolicy = getCapturePolicy();
137
140
  const rawSystemUpdate = systemMessages.length > 0
138
141
  ? systemMessages.map(({ entryId, message }) => ({ entryId, ...message }))
@@ -7,13 +7,13 @@ import {
7
7
  getToolInput,
8
8
  shapePayload,
9
9
  extractTextContent,
10
- truncate,
10
+ toStatusMessage,
11
11
  estimatePayloadBytes,
12
12
  getCapturePolicy,
13
13
  getLimits,
14
+ extractToolUsage,
14
15
  } from "../utils.js";
15
- import { applyCapturePolicy, redactOptionsFor } from "../capture-policy.js";
16
- import { redactString } from "../redaction.js";
16
+ import { applyCapturePolicy } from "../capture-policy.js";
17
17
 
18
18
  export async function startToolObservation(event: Record<string, unknown>) {
19
19
  if (state.isTracingDisabled || !state.agentState?.root) {
@@ -27,17 +27,19 @@ export async function startToolObservation(event: Record<string, unknown>) {
27
27
 
28
28
  try {
29
29
  const toolName = getToolName(event);
30
+ const parentToolCallId = typeof event.parentToolCallId === "string" ? event.parentToolCallId : undefined;
30
31
  const toolInput = getToolInput(event);
31
32
  const shapedInput = shapePayload(toolInput, { maxString: getLimits().maxToolPayload });
32
33
  const captured = applyCapturePolicy(
33
34
  {
34
35
  toolInput: shapedInput,
35
- metadata: { toolName, toolCallId },
36
+ metadata: shapePayload({ toolName, toolCallId, parentToolCallId }) as Record<string, unknown>,
36
37
  },
37
38
  getCapturePolicy(),
38
39
  );
39
40
  const inputBytes = estimatePayloadBytes(captured.toolInput, getLimits().maxToolPayload);
40
- const parent = state.agentState.activeTurn ?? state.agentState.activeAttempt ?? state.agentState.root;
41
+ const parentTool = parentToolCallId ? state.agentState.activeTools.get(parentToolCallId) : undefined;
42
+ const parent = parentTool?.observation ?? state.agentState.activeTurn ?? state.agentState.activeAttempt ?? state.agentState.root;
41
43
  const tool = await startChildObservation({
42
44
  parent,
43
45
  runtime: getRuntime,
@@ -56,6 +58,7 @@ export async function startToolObservation(event: Record<string, unknown>) {
56
58
  ended: false,
57
59
  startedAt: Date.now(),
58
60
  inputBytes,
61
+ parentToolCallId,
59
62
  });
60
63
  } catch (e) {
61
64
  console.warn("📊 Langfuse: Failed to start tool observation", e);
@@ -76,10 +79,12 @@ export async function finishToolObservation(event: Record<string, unknown>) {
76
79
  if (!activeTool || activeTool.ended) {
77
80
  return;
78
81
  }
82
+ // Claim completion before creating the usage child (which awaits the runtime).
83
+ activeTool.ended = true;
79
84
 
80
85
  const isError = Boolean(event.isError ?? event.error ?? event.status === "error");
81
86
  const output =
82
- extractTextContent(event.content, getLimits().maxToolPayload) ??
87
+ extractTextContent(event.content) ??
83
88
  event.output ??
84
89
  event.result ??
85
90
  event.error ??
@@ -88,27 +93,57 @@ export async function finishToolObservation(event: Record<string, unknown>) {
88
93
 
89
94
  try {
90
95
  const policy = getCapturePolicy();
91
- const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload });
96
+ const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload, parseJsonPrefix: isError });
92
97
  const captured = applyCapturePolicy(
93
98
  {
94
99
  toolOutput: shapedOutput,
95
- metadata: {
100
+ metadata: shapePayload({
96
101
  toolName: activeTool.toolName,
97
102
  toolCallId,
103
+ parentToolCallId: activeTool.parentToolCallId,
98
104
  isError,
99
- },
105
+ }) as Record<string, unknown>,
100
106
  },
101
107
  policy,
102
108
  );
103
109
  const outputBytes = estimatePayloadBytes(captured.toolOutput, getLimits().maxToolPayload);
104
110
  const durationMs = Math.max(0, Date.now() - activeTool.startedAt);
105
111
 
112
+ // Pi's tool_result and tool_execution_end carry only this tool's own usage.
113
+ // Do not consume transcript toolResult usage, which includes all descendants.
114
+ // A separate generation makes this cost visible on Langfuse versions that
115
+ // only account for usage/cost on generation observations.
116
+ const { usageDetails, costDetails } = extractToolUsage(event);
117
+ if (usageDetails || costDetails) {
118
+ try {
119
+ const usage = await startChildObservation({
120
+ parent: activeTool.observation,
121
+ runtime: getRuntime,
122
+ name: "tool-usage",
123
+ body: {
124
+ usageDetails,
125
+ costDetails,
126
+ metadata: applyCapturePolicy({ metadata: shapePayload({
127
+ toolName: activeTool.toolName,
128
+ toolCallId,
129
+ parentToolCallId: activeTool.parentToolCallId,
130
+ usageSource: "tool-result",
131
+ }) as Record<string, unknown> }, policy).metadata,
132
+ },
133
+ asType: "generation",
134
+ });
135
+ usage.end();
136
+ } catch (error) {
137
+ console.warn("📊 Langfuse: Failed to record tool usage", error);
138
+ }
139
+ }
140
+
106
141
  activeTool.observation
107
142
  .update({
108
143
  output: captured.toolOutput,
109
144
  level: isError ? "ERROR" : "DEFAULT",
110
145
  statusMessage: isError
111
- ? redactString(truncate(String(event.error ?? output), 1_000), redactOptionsFor(policy))
146
+ ? toStatusMessage(event.error ?? output, 1_000)
112
147
  : undefined,
113
148
  metadata: {
114
149
  ...(captured.metadata ?? {}),
@@ -118,8 +153,6 @@ export async function finishToolObservation(event: Record<string, unknown>) {
118
153
  },
119
154
  })
120
155
  .end();
121
- activeTool.ended = true;
122
-
123
156
  if (isError) {
124
157
  state.errorCount++;
125
158
  await sendScore("tool_is_error", 1, {
@@ -150,7 +183,7 @@ export function closeDanglingObservations(statusMessage: string) {
150
183
 
151
184
  for (const generation of state.agentState.activeGenerations.values()) {
152
185
  if (!generation.ended) {
153
- generation.observation.update({ level: "WARNING", statusMessage, metadata: { ...generation.metadata, cancelled: true } }).end();
186
+ generation.observation.update({ level: "WARNING", statusMessage, ...generation.errorStatus, metadata: { ...generation.metadata, cancelled: true } }).end();
154
187
  generation.ended = true;
155
188
  }
156
189
  }
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;
@@ -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
 
@@ -542,7 +551,7 @@ function wrapObservation(
542
551
  parentObservationId?: string,
543
552
  ): any {
544
553
  const id = observation.id || randomUUID();
545
- const traceId = observation.traceId || store.trace?.id || randomUUID();
554
+ const traceId = observation.traceId || randomUUID();
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,18 +567,18 @@ 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
 
575
584
  return {
@@ -579,7 +588,7 @@ function wrapObservation(
579
588
  update(updateBody?: Record<string, unknown>) {
580
589
  applyObservationUpdate(record, updateBody);
581
590
  if (!parentObservationId) {
582
- applyTraceUpdate(store, updateBody);
591
+ applyTraceUpdate(store, traceId, updateBody);
583
592
  }
584
593
  const updated = observation.update(updateBody);
585
594
  return updated === observation ? this : updated;
@@ -588,7 +597,7 @@ function wrapObservation(
588
597
  if (endBody && typeof endBody === "object") {
589
598
  applyObservationUpdate(record, endBody);
590
599
  if (!parentObservationId) {
591
- applyTraceUpdate(store, endBody);
600
+ applyTraceUpdate(store, traceId, endBody);
592
601
  }
593
602
  }
594
603
  record.endTime = nowIso();
@@ -602,16 +611,17 @@ function wrapObservation(
602
611
  }
603
612
  const propagate = runtime?.propagateAttributes;
604
613
  const createChild = () => observation.startObservation(childName, childBody, options);
614
+ const createOwnedChild = () => store.withTracerProvider ? store.withTracerProvider(createChild) : createChild();
605
615
  const createInheritingChild = propagate && Object.keys(inherited).length > 0
606
- ? () => propagate(inherited, createChild)
607
- : createChild;
616
+ ? () => propagate(inherited, createOwnedChild)
617
+ : createOwnedChild;
608
618
  const child = runtime?.withRootContext
609
619
  ? runtime.withRootContext(createInheritingChild)
610
620
  : createInheritingChild();
611
621
  return wrapObservation(child, store, childName, childBody, options?.asType, id);
612
622
  },
613
623
  setTraceIO(traceBody?: { input?: unknown; output?: unknown }) {
614
- applyTraceUpdate(store, traceBody);
624
+ applyTraceUpdate(store, traceId, traceBody);
615
625
  return observation.setTraceIO?.(traceBody);
616
626
  },
617
627
  };
@@ -694,22 +704,32 @@ async function getTraceVisibility(
694
704
  async function waitForTraceVisibility(
695
705
  rt: LangfuseRuntime,
696
706
  store: RestFallbackStore,
697
- traceId: string,
698
707
  signal: AbortSignal,
699
- ): Promise<TraceVisibility> {
700
- const deadline = Date.now() + OTEL_VISIBILITY_TIMEOUT_MS;
708
+ shutdownDeadline: number,
709
+ ): Promise<RestFallbackTrace[]> {
710
+ const now = Date.now();
711
+ // Leave a quarter of the remaining shutdown time for REST ingestion.
712
+ const deadline = now + Math.min(OTEL_VISIBILITY_TIMEOUT_MS, Math.max(0, shutdownDeadline - now) * 0.75);
713
+ const pending = new Map(store.traces);
714
+ const missing = new Set<string>();
701
715
 
702
716
  while (true) {
703
- const visibility = await getTraceVisibility(rt, store, traceId, signal);
704
- if (visibility !== "missing") {
705
- return visibility;
717
+ const ids = [...pending.keys()];
718
+ // Bound read concurrency and stop polling in time to send the REST batch.
719
+ for (let index = 0; index < ids.length && Date.now() < deadline; index += 4) {
720
+ const readSignal = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, Math.floor(deadline - Date.now())))]);
721
+ await Promise.all(ids.slice(index, index + 4).map(async traceId => {
722
+ try {
723
+ const visibility = await getTraceVisibility(rt, store, traceId, readSignal);
724
+ if (visibility === "missing") missing.add(traceId);
725
+ else { pending.delete(traceId); missing.delete(traceId); }
726
+ } catch (error) {
727
+ if (signal.aborted || !readSignal.aborted) throw error;
728
+ }
729
+ }));
706
730
  }
707
-
708
731
  const remainingMs = deadline - Date.now();
709
- if (remainingMs <= 0) {
710
- return "missing";
711
- }
712
-
732
+ if (pending.size === 0 || remainingMs <= 0) return [...pending.values()].filter(trace => missing.has(trace.id));
713
733
  await delay(Math.min(OTEL_VISIBILITY_POLL_INTERVAL_MS, remainingMs), signal);
714
734
  }
715
735
  }
@@ -718,42 +738,23 @@ function eventTimestamp(record: { endTime?: string; startTime?: string; timestam
718
738
  return record.endTime ?? record.startTime ?? record.timestamp ?? nowIso();
719
739
  }
720
740
 
721
- async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal) {
741
+ async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal, shutdownDeadline: number) {
722
742
  const store = rt.restFallback as RestFallbackStore | undefined;
723
- if (!store?.trace || store.attempted) {
724
- return;
725
- }
743
+ if (!store?.traces.size || store.attempted) return;
726
744
  store.attempted = true;
727
745
 
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
- ];
746
+ const traces = await waitForTraceVisibility(rt, store, signal, shutdownDeadline);
747
+ if (traces.length === 0) return;
748
+ const missingIds = new Set(traces.map(trace => trace.id));
749
+ const entries: any[] = traces.map(trace => ({
750
+ type: "trace-create",
751
+ id: randomUUID(),
752
+ timestamp: eventTimestamp(trace),
753
+ body: { ...trace },
754
+ }));
755
755
 
756
756
  for (const observation of store.observations) {
757
+ if (!missingIds.has(observation.traceId)) continue;
757
758
  const body = {
758
759
  id: observation.id,
759
760
  traceId: observation.traceId,
@@ -815,7 +816,7 @@ async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal)
815
816
  console.warn("📊 Langfuse: REST fallback ingestion reported errors", errors);
816
817
  } else {
817
818
  debugLog(
818
- `📊 Langfuse: OTel trace ${trace.id} was not visible; wrote fallback trace via REST ingestion (${chunks.length} chunk(s))`,
819
+ `📊 Langfuse: Processed ${traces.length} missing trace(s) via REST ingestion (${chunks.length} chunk(s))`,
819
820
  );
820
821
  }
821
822
  }
@@ -852,7 +853,11 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
852
853
  import("@langfuse/client"),
853
854
  ]);
854
855
 
856
+ // Another caller may have initialized it while the shared imports loaded.
857
+ if (runtime) return runtime;
858
+
855
859
  const restFallback: RestFallbackStore = {
860
+ traces: new Map(),
856
861
  observations: [],
857
862
  observationById: new Map(),
858
863
  attempted: false,
@@ -874,11 +879,10 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
874
879
  resources.detectResources({ detectors: [resources.envDetector] }),
875
880
  );
876
881
  const tracerProvider = new BasicTracerProvider({ resource, spanProcessors: [spanProcessor] });
877
- tracing.setLangfuseTracerProvider(tracerProvider);
878
882
 
879
883
  runtime = {
880
884
  startObservation: ((name: string, body?: Record<string, unknown>, options?: { asType?: string }) => {
881
- const observation = (tracing as any).startObservation(name, body, options);
885
+ const observation = restFallback.withTracerProvider!(() => (tracing as any).startObservation(name, body, options));
882
886
  return wrapObservation(observation, restFallback, name, body, options?.asType);
883
887
  }) as unknown as LangfuseRuntime["startObservation"],
884
888
  propagateAttributes: tracing.propagateAttributes as unknown as LangfuseRuntime["propagateAttributes"],
@@ -890,7 +894,6 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
890
894
  }) as LangfuseScoreClient,
891
895
  spanProcessor,
892
896
  tracerProvider,
893
- clearTracerProvider: () => tracing.setLangfuseTracerProvider(null),
894
897
  restFallback,
895
898
  pendingScores: [],
896
899
  scoreFlushAt,
@@ -903,6 +906,14 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
903
906
  host: state.config.host,
904
907
  },
905
908
  };
909
+ const ownedRuntime = runtime;
910
+ // Pi reloads extension modules per session, but the SDK provider is process-global.
911
+ restFallback.withTracerProvider = fn => {
912
+ const previous = tracing.getLangfuseTracerProvider();
913
+ tracing.setLangfuseTracerProvider(ownedRuntime.tracerProvider);
914
+ try { return fn(); }
915
+ finally { tracing.setLangfuseTracerProvider(previous); }
916
+ };
906
917
  lastRuntimeError = null;
907
918
  } catch (e) {
908
919
  rememberRuntimeError("runtime init", e);
@@ -952,7 +963,7 @@ function doShutdownRuntime(): Promise<void> {
952
963
  await runShutdownStep("OTel tracer shutdown", () => rt.tracerProvider?.shutdown?.(), deadline);
953
964
  await runShutdownStep(
954
965
  "REST fallback ingestion",
955
- () => fallbackToRestIngestion(rt, controller.signal),
966
+ () => fallbackToRestIngestion(rt, controller.signal, deadline),
956
967
  deadline,
957
968
  controller.signal,
958
969
  );
@@ -19,3 +19,30 @@ export async function startChildObservation({
19
19
 
20
20
  return (await runtime()).startObservation(name, body, { asType });
21
21
  }
22
+
23
+ /**
24
+ * Starts a top-level observation for a session-scoped event that arrives when no
25
+ * agent run is active (e.g. recovery compaction after a failed generation).
26
+ *
27
+ * Attributes must be passed explicitly: `propagateAttributes` only seeds the OTel
28
+ * context for the duration of its callback, so a root observation created outside
29
+ * a run would be written without `session.id` or `langfuse.trace.name` and would
30
+ * drop out of every session filter in Langfuse v4.
31
+ */
32
+ export async function startSessionObservation({
33
+ runtime,
34
+ name,
35
+ body,
36
+ asType,
37
+ attributes,
38
+ }: {
39
+ runtime: () => Promise<LangfuseRuntime>;
40
+ name: string;
41
+ body?: ObservationUpdate;
42
+ asType: "event" | "generation" | "tool" | "span";
43
+ attributes: Parameters<LangfuseRuntime["propagateAttributes"]>[0];
44
+ }): Promise<LangfuseObservation> {
45
+ const rt = await runtime();
46
+ const create = () => rt.propagateAttributes(attributes, () => rt.startObservation(name, body, { asType }));
47
+ return rt.withRootContext ? rt.withRootContext(create) : create();
48
+ }