pi-langfuse 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +20 -4
  2. package/README_CN.md +20 -4
  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 +40 -12
  51. package/package.json +12 -1
  52. package/src/commands.ts +14 -3
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +60 -32
  55. package/src/handlers/cache.ts +12 -10
  56. package/src/handlers/session.ts +2 -2
  57. package/src/handlers/tool.ts +6 -1
  58. package/src/langfuse.ts +35 -16
  59. package/src/observation.ts +4 -0
  60. package/src/state.ts +12 -2
  61. package/src/types.ts +1 -1
  62. package/src/workflow.ts +78 -0
@@ -0,0 +1,56 @@
1
+ // Configure Pi's model and Langfuse credentials as usual before creating the host.
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import {
4
+ createAgentSessionFromServices,
5
+ createAgentSessionRuntime,
6
+ createAgentSessionServices,
7
+ getAgentDir,
8
+ SessionManager,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { createLangfuseExtension } from "pi-langfuse/sdk";
11
+
12
+ export async function createWorkflowSession(cwd = process.cwd()) {
13
+ const calls = new AsyncLocalStorage();
14
+ const extension = createLangfuseExtension({
15
+ getRunContext({ piSessionId, messageType }) {
16
+ const call = calls.getStore();
17
+ if (!call?.available || call.piSessionId !== piSessionId || messageType !== "user") return;
18
+ call.available = false;
19
+ return call.context;
20
+ },
21
+ });
22
+ const runtime = await createAgentSessionRuntime(async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
23
+ const services = await createAgentSessionServices({
24
+ cwd, agentDir,
25
+ // This example loads just the inline extension, including when also installed on disk.
26
+ resourceLoaderOptions: { noExtensions: true, extensionFactories: [extension] },
27
+ });
28
+ const result = await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent });
29
+ return { ...result, services, diagnostics: services.diagnostics };
30
+ }, { cwd, agentDir: getAgentDir(), sessionManager: SessionManager.inMemory(cwd) });
31
+
32
+ try {
33
+ await runtime.session.bindExtensions({});
34
+ } catch (error) {
35
+ await runtime.dispose();
36
+ throw error;
37
+ }
38
+
39
+ let submitting = false;
40
+ return {
41
+ async prompt(text, context) {
42
+ const session = runtime.session;
43
+ if (submitting || !session.isIdle) throw new Error("Wait for the current Pi run to settle");
44
+ const call = { piSessionId: session.sessionId, context, available: true };
45
+ submitting = true;
46
+ try {
47
+ await calls.run(call, () => session.prompt(text));
48
+ } finally {
49
+ call.available = false;
50
+ submitting = false;
51
+ }
52
+ },
53
+ // Pi awaits session_shutdown here, including the extension's bounded flush.
54
+ dispose: () => runtime.dispose(),
55
+ };
56
+ }
package/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Langfuse Observability Extension for Pi Coding Agent
3
3
  *
4
- * Sends one complete Langfuse trace per Pi agent run:
4
+ * Records each Pi run in its own trace or under an explicit workflow parent:
5
5
  * - root agent observation for the user prompt and final assistant response
6
6
  * - one generation observation per provider request
7
7
  * - one tool observation per tool call, keyed by toolCallId
@@ -10,7 +10,9 @@
10
10
  import { basename } from "node:path";
11
11
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
 
13
- import { state, resetRunState, runWithSession, setCurrentSession } from "./src/state.js";
13
+ import { parseWorkflowContext, isUnsampled, warnWorkflow, type LangfuseExtensionOptions } from "./src/workflow.js";
14
+ export type { LangfuseExtensionOptions, WorkflowContext } from "./src/workflow.js";
15
+ import { state, getSessionRunState, resetRunState, runWithSession, setCurrentSession } from "./src/state.js";
14
16
  import { bindSessionLineage } from "./src/session-lineage.js";
15
17
  import { ensureConfig, promptForConfig, loadConfig } from "./src/config.js";
16
18
  import { shutdownRuntime } from "./src/langfuse.js";
@@ -49,18 +51,27 @@ import {
49
51
  // Extension
50
52
  // ============================================
51
53
 
52
- export default async function (pi: ExtensionAPI) {
54
+ export function createLangfuseExtension(options: LangfuseExtensionOptions = {}) {
55
+ return (pi: ExtensionAPI) => registerExtension(pi, options);
56
+ }
57
+
58
+ export default createLangfuseExtension();
59
+
60
+ async function registerExtension(pi: ExtensionAPI, options: LangfuseExtensionOptions) {
53
61
  const asRecord = (value: object): Record<string, unknown> => value as unknown as Record<string, unknown>;
54
62
  if (!state.config) {
55
63
  state.config = loadConfig();
56
64
  }
57
65
 
58
66
  if (state.config) {
59
- console.log("📊 Langfuse: Tracing enabled →", state.config.host);
67
+ console.error("📊 Langfuse: Tracing enabled →", state.config.host);
60
68
  } else {
61
- console.log("📊 Langfuse: Waiting for first-run setup");
69
+ console.error("📊 Langfuse: Waiting for first-run setup");
62
70
  }
63
71
 
72
+ pi.registerFlag("langfuse-session-id", { type: "string", description: "Group observations under this Langfuse workflow session" });
73
+ pi.registerFlag("langfuse-traceparent", { type: "string", description: "Attach runs to this W3C traceparent for the initial Pi session" });
74
+
64
75
  pi.registerCommand("langfuse-setup", {
65
76
  description: "Configure Langfuse API keys for this extension",
66
77
  handler: async (_args, ctx) => {
@@ -78,7 +89,7 @@ export default async function (pi: ExtensionAPI) {
78
89
  pi.registerCommand("langfuse-status", {
79
90
  description: "Show Langfuse configuration and runtime status",
80
91
  handler: async (args, ctx) => {
81
- await handleLangfuseStatusCommand(String(args ?? ""), ctx);
92
+ await withSession(ctx, () => handleLangfuseStatusCommand(String(args ?? ""), ctx));
82
93
  },
83
94
  });
84
95
 
@@ -106,12 +117,23 @@ export default async function (pi: ExtensionAPI) {
106
117
  }
107
118
  };
108
119
 
109
- const withSession = <T>(ctx: any, fn: () => T): T => runWithSession(getSessionId(ctx) ?? state.currentSessionId, fn);
120
+ const withSession = <T>(ctx: any, fn: () => T): T => runWithSession(getSessionId(ctx), fn);
110
121
 
111
- pi.on("session_start", async (_event, ctx) => withSession(ctx, async () => {
122
+ pi.on("session_start", async (event, ctx) => withSession(ctx, async () => {
123
+ resetRunState();
124
+ const session = getSessionRunState();
125
+ session.instance = Symbol("Pi session");
126
+ session.startupBinding = undefined;
127
+ session.workflowWarnings = undefined;
128
+ if (event.reason === "startup") {
129
+ const sessionId = pi.getFlag("langfuse-session-id");
130
+ const traceparent = pi.getFlag("langfuse-traceparent");
131
+ if (state.currentSessionId) session.startupBinding = parseWorkflowContext({ sessionId, traceparent });
132
+ else if (sessionId !== undefined || traceparent !== undefined) warnWorkflow("Ignoring workflow flags without a Pi session identity.");
133
+ }
112
134
  state.setupAttemptedThisSession = false;
113
135
  await ensureConfig(ctx);
114
- resetRunState();
136
+ if (getSessionRunState() !== session) return;
115
137
  bindSessionLineage(ctx?.sessionManager);
116
138
  initializeSystemStateTracking(ctx);
117
139
  initializeUsageTracking(ctx);
@@ -123,14 +145,16 @@ export default async function (pi: ExtensionAPI) {
123
145
  }));
124
146
 
125
147
  pi.on("before_agent_start", async (event, ctx) => withSession(ctx, async () => {
126
- await recordNewUsageEntries(ctx);
127
- await startAgentRun(asRecord(event), ctx);
148
+ await startAgentRun(asRecord(event), ctx, options.getRunContext);
128
149
  }));
129
150
 
130
151
  pi.on("agent_start", async (event, ctx) => withSession(ctx, async () => {
131
- if (!state.agentState?.root) {
152
+ const session = getSessionRunState();
153
+ if (!session.agentState?.root) {
132
154
  await startAgentRun(asRecord(event), ctx);
155
+ if (getSessionRunState() !== session) return;
133
156
  }
157
+ if (session.tracingDisabled) return;
134
158
  await startAgentAttempt();
135
159
  // The system prompt is only final here: before_agent_start handlers that
136
160
  // run after this extension may still rewrite it.
@@ -204,6 +228,7 @@ export default async function (pi: ExtensionAPI) {
204
228
  }));
205
229
 
206
230
  pi.on("agent_settled", async (_event, ctx) => withSession(ctx, async () => {
231
+ if (isUnsampled(getSessionRunState().runBinding)) initializeUsageTracking(ctx);
207
232
  await finishAgentRun();
208
233
  }));
209
234
 
@@ -234,8 +259,11 @@ export default async function (pi: ExtensionAPI) {
234
259
  }));
235
260
 
236
261
  pi.on("session_shutdown", async (_event, ctx) => withSession(ctx, async () => {
262
+ const instance = getSessionRunState().instance;
237
263
  await recordNewUsageEntries(ctx);
264
+ if (getSessionRunState().instance !== instance) return;
238
265
  handleSessionInterruption("Session shutdown before agent completed");
266
+ getSessionRunState().startupBinding = undefined;
239
267
  await shutdownRuntime();
240
268
  }));
241
269
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-langfuse",
3
- "version": "1.7.1",
3
+ "version": "1.8.0",
4
4
  "description": "Langfuse extension for Pi coding agent",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,9 +13,19 @@
13
13
  "type": "module",
14
14
  "packageManager": "npm@11.12.1",
15
15
  "main": "index.ts",
16
+ "exports": {
17
+ ".": "./index.ts",
18
+ "./sdk": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./*": "./*"
23
+ },
16
24
  "files": [
17
25
  "index.ts",
18
26
  "src/",
27
+ "dist/",
28
+ "examples/workflow-sdk.mjs",
19
29
  "README.md",
20
30
  "README_CN.md",
21
31
  "image.png",
@@ -24,6 +34,7 @@
24
34
  ],
25
35
  "scripts": {
26
36
  "typecheck": "tsc --noEmit",
37
+ "prepack": "tsc --noEmit false --declaration --outDir dist --rootDir .",
27
38
  "test": "tsx --import=./test/reset-ambient-env.ts --test test/*.test.ts"
28
39
  },
29
40
  "keywords": [
package/src/commands.ts CHANGED
@@ -11,12 +11,14 @@ import {
11
11
  } from "./config.js";
12
12
  import { createCapturePolicy, type PrivacyPreset, type CapturePolicy } from "./capture-policy.js";
13
13
  import { getRuntime, getLastRuntimeError, forceShutdownRuntime as shutdownLangfuseRuntime } from "./langfuse.js";
14
- import { state } from "./state.js";
14
+ import { getSessionRunState, state } from "./state.js";
15
+ import { isUnsampled } from "./workflow.js";
15
16
  import type { Config, LangfuseRuntime } from "./types.js";
16
17
 
17
18
  const PRIVACY_PRESETS = ["metadata-only", "prompts-only", "conversations", "full-debug"] as const;
18
19
 
19
20
  export interface CommandContextLike {
21
+ mode?: string;
20
22
  hasUI?: boolean;
21
23
  ui?: {
22
24
  notify?: (message: string, level?: "info" | "warning" | "error") => void;
@@ -44,7 +46,8 @@ function notify(ctx: CommandContextLike, message: string, level: "info" | "warni
44
46
  return;
45
47
  }
46
48
  const prefix = level === "error" ? "❌" : level === "warning" ? "⚠️" : "📊";
47
- console.log(`${prefix} Langfuse: ${message}`);
49
+ const log = ctx.mode === "rpc" || ctx.mode === "json" ? console.error : console.log;
50
+ log(`${prefix} Langfuse: ${message}`);
48
51
  }
49
52
 
50
53
  function parseCommandArgs(args: string): { values: Record<string, string>; positional: string[]; malformed: string[] } {
@@ -204,6 +207,11 @@ function formatStatus(configPath: string, env: Record<string, string | undefined
204
207
  ].join("\n");
205
208
  }
206
209
 
210
+ const session = getSessionRunState();
211
+ const binding = session.runBinding ?? session.startupBinding;
212
+ const workflow = isUnsampled(binding) ? "upstream sampling disabled"
213
+ : binding?.parent ? "external parent (OTel only)"
214
+ : binding?.sessionId ? "external session group" : "independent";
207
215
  const safeConfig = sanitizeConfigForLog(config);
208
216
  const policy = config.capturePolicy ?? createCapturePolicy(env);
209
217
  return [
@@ -222,6 +230,7 @@ function formatStatus(configPath: string, env: Record<string, string | undefined
222
230
  ` system prompt: ${flag(policy.captureSystemPrompt)}`,
223
231
  ` cwd: ${flag(policy.captureCwd)}`,
224
232
  ` absolute paths: ${flag(policy.capturePaths)}`,
233
+ `Workflow tracing: ${workflow}`,
225
234
  `Active run: ${hasActiveAgentObservation() ? "yes" : "no"}`,
226
235
  `Last error: ${lastErrorSummary()}`,
227
236
  ].join("\n");
@@ -419,7 +428,7 @@ export async function handleLangfuseTestCommand(
419
428
  try {
420
429
  const rt = await (deps.getRuntime ?? getRuntime)();
421
430
  runtimeInitialized = true;
422
- rt.propagateAttributes(
431
+ const create = () => rt.propagateAttributes(
423
432
  {
424
433
  traceName: "pi-langfuse-test",
425
434
  metadata: {
@@ -444,6 +453,8 @@ export async function handleLangfuseTestCommand(
444
453
  return observation;
445
454
  },
446
455
  );
456
+ if (rt.withRootContext) rt.withRootContext(create);
457
+ else create();
447
458
  const result = connectivity.warning ? "completed with a read warning" : "succeeded";
448
459
  notify(ctx, `Langfuse test ${result}. ${connectivity.message}; test trace sent to ${config.host}.`, connectivity.warning ? "warning" : "info");
449
460
  return true;
package/src/config.ts CHANGED
@@ -101,7 +101,7 @@ export function sanitizeConfigForLog(config: Pick<Config, "publicKey" | "secretK
101
101
 
102
102
  async function collectConfigFromUI(ctx: any, reason: string): Promise<Config | null> {
103
103
  if (!ctx.hasUI) {
104
- console.log(`📊 Langfuse: ${reason}. Run this extension in Pi UI to complete setup, or set LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_BASE_URL.`);
104
+ console.error(`📊 Langfuse: ${reason}. Run this extension in Pi UI to complete setup, or set LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_BASE_URL.`);
105
105
  return null;
106
106
  }
107
107
 
@@ -1,11 +1,13 @@
1
- import { state, resetRunState, computeEvaluationScores } from "../state.js";
1
+ import { state, resetRunState, getSessionRunState, computeEvaluationScores, type SessionRunState } from "../state.js";
2
2
  import { getRuntime, sendScore } from "../langfuse.js";
3
3
  import { ensureConfig } from "../config.js";
4
- import { shapePayload, truncate, extractFinalAssistant, extractAssistantOutput, getCapturePolicy } from "../utils.js";
4
+ import { shapePayload, extractFinalAssistant, extractAssistantOutput, getCapturePolicy } from "../utils.js";
5
5
  import { closeDanglingObservations } from "./tool.js";
6
6
  import { applyCapturePolicy } from "../capture-policy.js";
7
7
  import { collectSourceMetadata } from "../source-metadata.js";
8
8
  import { sessionLineageMetadata } from "../session-lineage.js";
9
+ import { isUnsampled, localSessionGroupId, resolveRunBinding, warnWorkflow, type LangfuseExtensionOptions, type WorkflowBinding } from "../workflow.js";
10
+ import { recordNewUsageEntries } from "./cache.js";
9
11
  import { startChildObservation } from "../observation.js";
10
12
 
11
13
  function stringMetadata(metadata: Record<string, unknown> | undefined): Record<string, string> | undefined {
@@ -26,7 +28,7 @@ function stringMetadata(metadata: Record<string, unknown> | undefined): Record<s
26
28
 
27
29
  export function updateTraceIO(input?: unknown, output?: unknown) {
28
30
  const root = state.agentState?.root;
29
- if (!root?.setTraceIO) {
31
+ if (!root?.setTraceIO || getSessionRunState().runBinding?.parent) {
30
32
  return;
31
33
  }
32
34
 
@@ -37,14 +39,36 @@ export function updateTraceIO(input?: unknown, output?: unknown) {
37
39
  }
38
40
  }
39
41
 
40
- export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
41
- if (!(await ensureConfig(ctx))) {
42
- state.isTracingDisabled = true;
43
- return;
44
- }
42
+ export function startAgentRun(event: Record<string, unknown>, ctx: any, getRunContext?: LangfuseExtensionOptions["getRunContext"]) {
43
+ const session = getSessionRunState();
44
+ if (session.startingRun) return session.startingRun;
45
+ if (session.agentState?.root || isUnsampled(session.runBinding)) return Promise.resolve();
46
+
47
+ const binding = session.runBinding ?? resolveRunBinding(event, getRunContext);
48
+ session.runBinding = binding;
49
+ session.startingRun = initializeRun(session, binding, event, ctx).finally(() => {
50
+ session.startingRun = undefined;
51
+ });
52
+ return session.startingRun;
53
+ }
45
54
 
55
+ async function initializeRun(session: SessionRunState, binding: WorkflowBinding, event: Record<string, unknown>, ctx: any) {
46
56
  try {
57
+ // Entries already present before this prompt belong to the session, even
58
+ // when the caller chose not to sample the upcoming run.
59
+ const previousUsage = recordNewUsageEntries(ctx);
60
+ const unsampled = isUnsampled(binding);
61
+ if (unsampled) session.tracingDisabled = true;
62
+ await previousUsage;
63
+ if (unsampled || getSessionRunState() !== session) return;
64
+ if (!(await ensureConfig(ctx))) {
65
+ session.tracingDisabled = true;
66
+ return;
67
+ }
68
+ if (getSessionRunState() !== session) return;
69
+ session.tracingDisabled = false;
47
70
  const rt = await getRuntime();
71
+ if (getSessionRunState() !== session) return;
48
72
  const cwd = String(
49
73
  (event.systemPromptOptions && typeof event.systemPromptOptions === "object"
50
74
  ? (event.systemPromptOptions as Record<string, unknown>).cwd
@@ -95,30 +119,27 @@ export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
95
119
  uncachedInputTokens: 0,
96
120
  };
97
121
 
98
- const root = rt.propagateAttributes(
99
- {
100
- sessionId: state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined,
101
- userId: state.config?.userId,
102
- traceName: "pi-agent",
103
- metadata: stringMetadata(captured.metadata),
104
- },
105
- () =>
106
- rt.startObservation(
107
- "pi-agent",
108
- {
109
- input: captured.input,
110
- metadata: captured.metadata ?? {},
111
- },
112
- { asType: "agent" },
113
- ),
114
- );
122
+ const attributes = binding.parent
123
+ ? { sessionId: binding.sessionId }
124
+ : {
125
+ sessionId: binding.sessionId ?? localSessionGroupId(),
126
+ userId: state.config?.userId,
127
+ traceName: "pi-agent",
128
+ metadata: stringMetadata(captured.metadata),
129
+ };
130
+ const create = () => rt.propagateAttributes(attributes, () => rt.startObservation(
131
+ "pi-agent",
132
+ { input: captured.input, metadata: captured.metadata ?? {} },
133
+ { asType: "agent", parentSpanContext: binding.parent },
134
+ ));
135
+ const root = rt.withRootContext ? rt.withRootContext(create) : create();
115
136
 
116
137
  state.agentState.root = root;
117
138
  state.agentState.traceId = root.traceId;
118
139
  updateTraceIO(captured.input, undefined);
119
140
  } catch (e) {
120
141
  console.warn("📊 Langfuse: Failed to create agent observation", e);
121
- state.isTracingDisabled = true;
142
+ session.tracingDisabled = true;
122
143
  }
123
144
  }
124
145
 
@@ -247,6 +268,9 @@ export async function finishAgentRun(event: Record<string, unknown> = {}) {
247
268
  return;
248
269
  }
249
270
 
271
+ const session = getSessionRunState();
272
+ if (session.finishingRun) return;
273
+ session.finishingRun = true;
250
274
  const finalEvent = Object.keys(event).length > 0 ? event : state.agentState.lastAgentEndEvent ?? {};
251
275
  const lastAssistant = extractFinalAssistant(finalEvent.messages);
252
276
  const rawOutput = lastAssistant ? extractAssistantOutput(lastAssistant) : state.agentState.latestAssistantOutput;
@@ -295,14 +319,18 @@ export async function finishAgentRun(event: Record<string, unknown> = {}) {
295
319
  .end();
296
320
  updateTraceIO(state.agentState.promptInput, captured.output);
297
321
 
298
- await sendScore("tool_call_count", scores.tool_call_count, { traceId: state.agentState.traceId });
299
- await sendScore("turn_count", scores.turn_count, { traceId: state.agentState.traceId });
300
- await sendScore("total_tool_errors", scores.total_tool_errors, { traceId: state.agentState.traceId });
301
- await sendScore("tool_success_rate", scores.tool_success_rate, { traceId: state.agentState.traceId });
302
- await sendScore("session_had_errors", scores.session_had_errors, { traceId: state.agentState.traceId });
322
+ const target = {
323
+ traceId: state.agentState.traceId,
324
+ observationId: session.runBinding?.parent ? state.agentState.root.id : undefined,
325
+ };
326
+ if (session.runBinding?.parent && (!target.observationId || !target.traceId)) {
327
+ warnWorkflow("Skipping workflow run scores without an observation identity.");
328
+ return;
329
+ }
330
+ for (const [name, value] of Object.entries(scores)) await sendScore(name, value, target);
303
331
  } catch (e) {
304
332
  console.warn("📊 Langfuse: Failed to finish agent observation", e);
305
333
  } finally {
306
- resetRunState();
334
+ if (getSessionRunState() === session) resetRunState();
307
335
  }
308
336
  }
@@ -3,14 +3,11 @@ import { getRuntime } from "../langfuse.js";
3
3
  import { startChildObservation } from "../observation.js";
4
4
  import { getSessionRunState, state } from "../state.js";
5
5
  import { sessionLineageMetadata } from "../session-lineage.js";
6
- import { extractCostDetails, extractUsage, getCapturePolicy, truncate } from "../utils.js";
6
+ import { extractCostDetails, extractUsage, getCapturePolicy } from "../utils.js";
7
+ import { isUnsampled, sessionGroupId } from "../workflow.js";
7
8
 
8
9
  type RecordLike = Record<string, unknown>;
9
10
 
10
- function sessionIdForTrace(): string | undefined {
11
- return state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined;
12
- }
13
-
14
11
  export function initializeUsageTracking(ctx: any): void {
15
12
  const session = getSessionRunState();
16
13
  try {
@@ -65,7 +62,7 @@ export async function recordCacheWarmingDecision(event: RecordLike, ctx: any): P
65
62
  const runtime = await getRuntime();
66
63
  const create = () => runtime.propagateAttributes(
67
64
  {
68
- sessionId: sessionIdForTrace(),
65
+ sessionId: sessionGroupId(),
69
66
  traceName: "pi-cache-warming",
70
67
  metadata: {
71
68
  ...sessionLineageMetadata(ctx?.sessionManager),
@@ -87,7 +84,10 @@ export async function recordCacheWarmingDecision(event: RecordLike, ctx: any): P
87
84
  }
88
85
 
89
86
  export async function recordNewUsageEntries(ctx: any): Promise<void> {
90
- if (state.isTracingDisabled || !state.config) return;
87
+ if (state.isTracingDisabled || !state.config) {
88
+ if (isUnsampled(getSessionRunState().runBinding)) initializeUsageTracking(ctx);
89
+ return;
90
+ }
91
91
  const session = getSessionRunState();
92
92
  let entries: unknown;
93
93
  try {
@@ -97,6 +97,8 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
97
97
  }
98
98
  if (!Array.isArray(entries)) return;
99
99
 
100
+ const parent = session.agentState?.activeTurn ?? session.agentState?.activeAttempt ?? session.agentState?.root;
101
+ const sessionId = sessionGroupId();
100
102
  for (const rawEntry of entries) {
101
103
  if (!rawEntry || typeof rawEntry !== "object") continue;
102
104
  const entry = rawEntry as RecordLike;
@@ -122,7 +124,7 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
122
124
 
123
125
  try {
124
126
  const runtime = await getRuntime();
125
- const parent = state.agentState?.activeTurn ?? state.agentState?.activeAttempt ?? state.agentState?.root;
127
+ if (getSessionRunState() !== session) return;
126
128
  const body = {
127
129
  model: typeof entry.model === "string" ? entry.model : undefined,
128
130
  usageDetails,
@@ -133,11 +135,11 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
133
135
  ? await startChildObservation({ parent, runtime: getRuntime, name: "cache-warm", body, asType: "generation" })
134
136
  : (runtime.withRootContext
135
137
  ? runtime.withRootContext(() => runtime.propagateAttributes(
136
- { sessionId: sessionIdForTrace(), traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
138
+ { sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
137
139
  () => runtime.startObservation("cache-warm", body, { asType: "generation" }),
138
140
  ))
139
141
  : runtime.propagateAttributes(
140
- { sessionId: sessionIdForTrace(), traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
142
+ { sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
141
143
  () => runtime.startObservation("cache-warm", body, { asType: "generation" }),
142
144
  ));
143
145
  observation.end();
@@ -2,6 +2,7 @@ import { applyCapturePolicy } from "../capture-policy.js";
2
2
  import { getRuntime } from "../langfuse.js";
3
3
  import { startChildObservation, startSessionObservation } from "../observation.js";
4
4
  import { state } from "../state.js";
5
+ import { sessionGroupId } from "../workflow.js";
5
6
  import { sessionLineageMetadata } from "../session-lineage.js";
6
7
  import {
7
8
  extractCostDetails,
@@ -9,7 +10,6 @@ import {
9
10
  extractUsage,
10
11
  getCapturePolicy,
11
12
  shapePayload,
12
- truncate,
13
13
  } from "../utils.js";
14
14
  import type { LangfuseObservation, ObservationUpdate } from "../types.js";
15
15
 
@@ -37,7 +37,7 @@ function startCompactionObservation(
37
37
  body,
38
38
  asType,
39
39
  attributes: {
40
- sessionId: state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined,
40
+ sessionId: sessionGroupId(),
41
41
  userId: state.config?.userId,
42
42
  traceName: SESSION_TRACE_NAME,
43
43
  metadata: { piScope: "session", ...sessionLineageMetadata() },
@@ -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 {
@@ -155,6 +156,10 @@ export async function finishToolObservation(event: Record<string, unknown>) {
155
156
  .end();
156
157
  if (isError) {
157
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
+ }
158
163
  await sendScore("tool_is_error", 1, {
159
164
  traceId: state.agentState.traceId,
160
165
  observationId: activeTool.observation.id,
package/src/langfuse.ts CHANGED
@@ -133,7 +133,7 @@ function delay(ms: number, signal?: AbortSignal) {
133
133
 
134
134
  function debugLog(message: string) {
135
135
  if (process.env.PI_LANGFUSE_DEBUG === "1" || process.env.PI_LANGFUSE_DEBUG === "true") {
136
- console.log(message);
136
+ console.error(message);
137
137
  }
138
138
  }
139
139
 
@@ -542,16 +542,16 @@ function readPropagatedAttributes(observation: any): PropagatedAttributes {
542
542
  return propagated;
543
543
  }
544
544
 
545
- function wrapObservation(
546
- observation: any,
545
+ function recordFallbackObservation(
547
546
  store: RestFallbackStore,
547
+ observation: any,
548
+ id: string,
549
+ traceId: string,
548
550
  name: string,
549
- body: Record<string, unknown> | undefined,
551
+ body?: Record<string, unknown>,
550
552
  asType?: string,
551
553
  parentObservationId?: string,
552
- ): any {
553
- const id = observation.id || randomUUID();
554
- const traceId = observation.traceId || randomUUID();
554
+ ) {
555
555
  const metadata = body?.metadata && typeof body.metadata === "object" ? body.metadata as Record<string, unknown> : undefined;
556
556
  const record: RestFallbackObservation = {
557
557
  id,
@@ -581,32 +581,49 @@ function wrapObservation(
581
581
  });
582
582
  }
583
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
+
584
601
  return {
585
602
  ...observation,
586
603
  id,
587
604
  traceId,
588
605
  update(updateBody?: Record<string, unknown>) {
589
- applyObservationUpdate(record, updateBody);
590
- if (!parentObservationId) {
606
+ if (record) applyObservationUpdate(record, updateBody);
607
+ if (record && !parentObservationId) {
591
608
  applyTraceUpdate(store, traceId, updateBody);
592
609
  }
593
610
  const updated = observation.update(updateBody);
594
611
  return updated === observation ? this : updated;
595
612
  },
596
613
  end(endBody?: Record<string, unknown>) {
597
- if (endBody && typeof endBody === "object") {
614
+ if (record && endBody && typeof endBody === "object") {
598
615
  applyObservationUpdate(record, endBody);
599
616
  if (!parentObservationId) {
600
617
  applyTraceUpdate(store, traceId, endBody);
601
618
  }
602
619
  }
603
- record.endTime = nowIso();
620
+ if (record) record.endTime = nowIso();
604
621
  return observation.end();
605
622
  },
606
623
  startObservation(childName: string, childBody?: Record<string, unknown>, options?: { asType?: string }) {
607
624
  const inherited = readPropagatedAttributes(observation);
608
625
  const fallbackSessionId = state.currentSessionId?.slice(0, 200);
609
- if (!inherited.sessionId && fallbackSessionId) {
626
+ if (!externalTrace && !inherited.sessionId && fallbackSessionId) {
610
627
  inherited.sessionId = fallbackSessionId;
611
628
  }
612
629
  const propagate = runtime?.propagateAttributes;
@@ -618,9 +635,10 @@ function wrapObservation(
618
635
  const child = runtime?.withRootContext
619
636
  ? runtime.withRootContext(createInheritingChild)
620
637
  : createInheritingChild();
621
- return wrapObservation(child, store, childName, childBody, options?.asType, id);
638
+ return wrapObservation(child, store, childName, childBody, options?.asType, id, externalTrace);
622
639
  },
623
640
  setTraceIO(traceBody?: { input?: unknown; output?: unknown }) {
641
+ if (externalTrace) return;
624
642
  applyTraceUpdate(store, traceId, traceBody);
625
643
  return observation.setTraceIO?.(traceBody);
626
644
  },
@@ -881,10 +899,11 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
881
899
  const tracerProvider = new BasicTracerProvider({ resource, spanProcessors: [spanProcessor] });
882
900
 
883
901
  runtime = {
884
- startObservation: ((name: string, body?: Record<string, unknown>, options?: { asType?: string }) => {
902
+ startObservation: (name, body, options) => {
885
903
  const observation = restFallback.withTracerProvider!(() => (tracing as any).startObservation(name, body, options));
886
- return wrapObservation(observation, restFallback, name, body, options?.asType);
887
- }) as unknown as LangfuseRuntime["startObservation"],
904
+ return wrapObservation(observation, restFallback, name, body as Record<string, unknown>, options?.asType,
905
+ options?.parentSpanContext?.spanId, !!options?.parentSpanContext);
906
+ },
888
907
  propagateAttributes: tracing.propagateAttributes as unknown as LangfuseRuntime["propagateAttributes"],
889
908
  withRootContext: (fn) => context.with(ROOT_CONTEXT, fn),
890
909
  scoreClient: new LangfuseClient({