pi-langfuse 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +87 -5
  2. package/README_CN.md +63 -5
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.js +216 -0
  5. package/dist/src/capture-policy.d.ts +43 -0
  6. package/dist/src/capture-policy.js +125 -0
  7. package/dist/src/commands.d.ts +25 -0
  8. package/dist/src/commands.js +374 -0
  9. package/dist/src/config.d.ts +13 -0
  10. package/dist/src/config.js +157 -0
  11. package/dist/src/constants.d.ts +9 -0
  12. package/dist/src/constants.js +11 -0
  13. package/dist/src/handlers/agent.d.ts +18 -0
  14. package/dist/src/handlers/agent.js +310 -0
  15. package/dist/src/handlers/cache.d.ts +5 -0
  16. package/dist/src/handlers/cache.js +134 -0
  17. package/dist/src/handlers/generation.d.ts +9 -0
  18. package/dist/src/handlers/generation.js +249 -0
  19. package/dist/src/handlers/session.d.ts +4 -0
  20. package/dist/src/handlers/session.js +121 -0
  21. package/dist/src/handlers/system-state.d.ts +3 -0
  22. package/dist/src/handlers/system-state.js +185 -0
  23. package/dist/src/handlers/tool.d.ts +3 -0
  24. package/dist/src/handlers/tool.js +168 -0
  25. package/dist/src/handlers/turn.d.ts +2 -0
  26. package/dist/src/handlers/turn.js +48 -0
  27. package/dist/src/langfuse.d.ts +42 -0
  28. package/dist/src/langfuse.js +837 -0
  29. package/dist/src/limits.d.ts +43 -0
  30. package/dist/src/limits.js +63 -0
  31. package/dist/src/observation.d.ts +24 -0
  32. package/dist/src/observation.js +24 -0
  33. package/dist/src/redaction.d.ts +14 -0
  34. package/dist/src/redaction.js +254 -0
  35. package/dist/src/session-lineage.d.ts +15 -0
  36. package/dist/src/session-lineage.js +87 -0
  37. package/dist/src/source-metadata.d.ts +2 -0
  38. package/dist/src/source-metadata.js +55 -0
  39. package/dist/src/state.d.ts +52 -0
  40. package/dist/src/state.js +144 -0
  41. package/dist/src/types.d.ts +157 -0
  42. package/dist/src/types.js +1 -0
  43. package/dist/src/usage-options.d.ts +27 -0
  44. package/dist/src/usage-options.js +21 -0
  45. package/dist/src/utils.d.ts +61 -0
  46. package/dist/src/utils.js +600 -0
  47. package/dist/src/workflow.d.ts +24 -0
  48. package/dist/src/workflow.js +62 -0
  49. package/examples/workflow-sdk.mjs +56 -0
  50. package/index.ts +47 -13
  51. package/package.json +16 -2
  52. package/src/commands.ts +48 -5
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +63 -33
  55. package/src/handlers/cache.ts +14 -10
  56. package/src/handlers/generation.ts +21 -43
  57. package/src/handlers/session.ts +71 -13
  58. package/src/handlers/tool.ts +12 -8
  59. package/src/langfuse.ts +110 -80
  60. package/src/observation.ts +31 -0
  61. package/src/redaction.ts +145 -10
  62. package/src/session-lineage.ts +98 -0
  63. package/src/state.ts +19 -2
  64. package/src/types.ts +2 -1
  65. package/src/utils.ts +95 -19
  66. package/src/workflow.ts +78 -0
@@ -0,0 +1,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,10 @@
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";
16
+ import { bindSessionLineage } from "./src/session-lineage.js";
14
17
  import { ensureConfig, promptForConfig, loadConfig } from "./src/config.js";
15
18
  import { shutdownRuntime } from "./src/langfuse.js";
16
19
  import { handleLangfusePrivacyCommand, handleLangfuseStatusCommand, handleLangfuseTestCommand } from "./src/commands.js";
@@ -30,7 +33,7 @@ import {
30
33
  recordCacheWarmingDecision,
31
34
  recordNewUsageEntries,
32
35
  } from "./src/handlers/cache.js";
33
- import { recordSessionCompaction } from "./src/handlers/session.js";
36
+ import { recordSessionCompaction, recordSessionCompactionFailure } from "./src/handlers/session.js";
34
37
  import {
35
38
  startGeneration,
36
39
  updateGenerationMetadata,
@@ -48,18 +51,27 @@ import {
48
51
  // Extension
49
52
  // ============================================
50
53
 
51
- 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) {
52
61
  const asRecord = (value: object): Record<string, unknown> => value as unknown as Record<string, unknown>;
53
62
  if (!state.config) {
54
63
  state.config = loadConfig();
55
64
  }
56
65
 
57
66
  if (state.config) {
58
- console.log("📊 Langfuse: Tracing enabled →", state.config.host);
67
+ console.error("📊 Langfuse: Tracing enabled →", state.config.host);
59
68
  } else {
60
- console.log("📊 Langfuse: Waiting for first-run setup");
69
+ console.error("📊 Langfuse: Waiting for first-run setup");
61
70
  }
62
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
+
63
75
  pi.registerCommand("langfuse-setup", {
64
76
  description: "Configure Langfuse API keys for this extension",
65
77
  handler: async (_args, ctx) => {
@@ -77,7 +89,7 @@ export default async function (pi: ExtensionAPI) {
77
89
  pi.registerCommand("langfuse-status", {
78
90
  description: "Show Langfuse configuration and runtime status",
79
91
  handler: async (args, ctx) => {
80
- await handleLangfuseStatusCommand(String(args ?? ""), ctx);
92
+ await withSession(ctx, () => handleLangfuseStatusCommand(String(args ?? ""), ctx));
81
93
  },
82
94
  });
83
95
 
@@ -105,12 +117,24 @@ export default async function (pi: ExtensionAPI) {
105
117
  }
106
118
  };
107
119
 
108
- 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);
109
121
 
110
- 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
+ }
111
134
  state.setupAttemptedThisSession = false;
112
135
  await ensureConfig(ctx);
113
- resetRunState();
136
+ if (getSessionRunState() !== session) return;
137
+ bindSessionLineage(ctx?.sessionManager);
114
138
  initializeSystemStateTracking(ctx);
115
139
  initializeUsageTracking(ctx);
116
140
  }));
@@ -121,14 +145,16 @@ export default async function (pi: ExtensionAPI) {
121
145
  }));
122
146
 
123
147
  pi.on("before_agent_start", async (event, ctx) => withSession(ctx, async () => {
124
- await recordNewUsageEntries(ctx);
125
- await startAgentRun(asRecord(event), ctx);
148
+ await startAgentRun(asRecord(event), ctx, options.getRunContext);
126
149
  }));
127
150
 
128
151
  pi.on("agent_start", async (event, ctx) => withSession(ctx, async () => {
129
- if (!state.agentState?.root) {
152
+ const session = getSessionRunState();
153
+ if (!session.agentState?.root) {
130
154
  await startAgentRun(asRecord(event), ctx);
155
+ if (getSessionRunState() !== session) return;
131
156
  }
157
+ if (session.tracingDisabled) return;
132
158
  await startAgentAttempt();
133
159
  // The system prompt is only final here: before_agent_start handlers that
134
160
  // run after this extension may still rewrite it.
@@ -202,6 +228,7 @@ export default async function (pi: ExtensionAPI) {
202
228
  }));
203
229
 
204
230
  pi.on("agent_settled", async (_event, ctx) => withSession(ctx, async () => {
231
+ if (isUnsampled(getSessionRunState().runBinding)) initializeUsageTracking(ctx);
205
232
  await finishAgentRun();
206
233
  }));
207
234
 
@@ -227,9 +254,16 @@ export default async function (pi: ExtensionAPI) {
227
254
  await recordSessionCompaction(asRecord(event));
228
255
  }));
229
256
 
257
+ pi.on("session_compact_failed", async (event, ctx) => withSession(ctx, async () => {
258
+ await recordSessionCompactionFailure(asRecord(event));
259
+ }));
260
+
230
261
  pi.on("session_shutdown", async (_event, ctx) => withSession(ctx, async () => {
262
+ const instance = getSessionRunState().instance;
231
263
  await recordNewUsageEntries(ctx);
264
+ if (getSessionRunState().instance !== instance) return;
232
265
  handleSessionInterruption("Session shutdown before agent completed");
266
+ getSessionRunState().startupBinding = undefined;
233
267
  await shutdownRuntime();
234
268
  }));
235
269
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-langfuse",
3
- "version": "1.7.0",
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,7 +34,8 @@
24
34
  ],
25
35
  "scripts": {
26
36
  "typecheck": "tsc --noEmit",
27
- "test": "tsx --test test/*.test.ts"
37
+ "prepack": "tsc --noEmit false --declaration --outDir dist --rootDir .",
38
+ "test": "tsx --import=./test/reset-ambient-env.ts --test test/*.test.ts"
28
39
  },
29
40
  "keywords": [
30
41
  "pi-package",
@@ -46,7 +57,10 @@
46
57
  "@langfuse/otel": "^5.3.0",
47
58
  "@langfuse/tracing": "^5.3.0",
48
59
  "@opentelemetry/api": "^1.9.0",
60
+ "@opentelemetry/core": "^2.0.1",
49
61
  "@opentelemetry/context-async-hooks": "^2.7.1",
62
+ "@opentelemetry/exporter-trace-otlp-http": "^0.218.0",
63
+ "@opentelemetry/otlp-exporter-base": "^0.218.0",
50
64
  "@opentelemetry/sdk-node": "^0.218.0",
51
65
  "@opentelemetry/sdk-trace-base": "^2.0.1"
52
66
  },
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;
@@ -35,6 +37,7 @@ interface CommandDeps {
35
37
  interface ConnectivityResult {
36
38
  ok: boolean;
37
39
  message: string;
40
+ warning?: boolean;
38
41
  }
39
42
 
40
43
  function notify(ctx: CommandContextLike, message: string, level: "info" | "warning" | "error" = "info") {
@@ -43,7 +46,8 @@ function notify(ctx: CommandContextLike, message: string, level: "info" | "warni
43
46
  return;
44
47
  }
45
48
  const prefix = level === "error" ? "❌" : level === "warning" ? "⚠️" : "📊";
46
- console.log(`${prefix} Langfuse: ${message}`);
49
+ const log = ctx.mode === "rpc" || ctx.mode === "json" ? console.error : console.log;
50
+ log(`${prefix} Langfuse: ${message}`);
47
51
  }
48
52
 
49
53
  function parseCommandArgs(args: string): { values: Record<string, string>; positional: string[]; malformed: string[] } {
@@ -203,6 +207,11 @@ function formatStatus(configPath: string, env: Record<string, string | undefined
203
207
  ].join("\n");
204
208
  }
205
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";
206
215
  const safeConfig = sanitizeConfigForLog(config);
207
216
  const policy = config.capturePolicy ?? createCapturePolicy(env);
208
217
  return [
@@ -221,11 +230,41 @@ function formatStatus(configPath: string, env: Record<string, string | undefined
221
230
  ` system prompt: ${flag(policy.captureSystemPrompt)}`,
222
231
  ` cwd: ${flag(policy.captureCwd)}`,
223
232
  ` absolute paths: ${flag(policy.capturePaths)}`,
233
+ `Workflow tracing: ${workflow}`,
224
234
  `Active run: ${hasActiveAgentObservation() ? "yes" : "no"}`,
225
235
  `Last error: ${lastErrorSummary()}`,
226
236
  ].join("\n");
227
237
  }
228
238
 
239
+ // v4 events_only removes legacy reads; older servers may not expose v2 reads.
240
+ const READ_PROBE_WINDOW_MS = 6 * 60 * 60 * 1_000;
241
+
242
+ async function probeReadSurface(host: string, auth: string): Promise<{ message: string; warning: boolean }> {
243
+ const to = new Date();
244
+ const from = new Date(to.getTime() - READ_PROBE_WINDOW_MS);
245
+ const url = `${host}/api/public/v2/observations?fromStartTime=${from.toISOString()}&toStartTime=${to.toISOString()}&limit=1`;
246
+
247
+ for (const [name, endpoint] of [
248
+ ["v2 observations", url],
249
+ ["legacy observations", `${host}/api/public/observations?limit=1`],
250
+ ]) {
251
+ try {
252
+ const response = await fetch(endpoint, {
253
+ headers: { Authorization: `Basic ${auth}` },
254
+ signal: AbortSignal.timeout(10_000),
255
+ });
256
+ if (name === "v2 observations" && (response.status === 404 || response.status === 405)) continue;
257
+ return {
258
+ message: `read: ${name} ${response.ok ? "ok" : `HTTP ${response.status}`}`,
259
+ warning: !response.ok,
260
+ };
261
+ } catch (error) {
262
+ return { message: `read: ${name} failed: ${error instanceof Error ? error.message : String(error)}`, warning: true };
263
+ }
264
+ }
265
+ return { message: "read: unavailable", warning: true };
266
+ }
267
+
229
268
  async function checkLangfuseConnectivity(config: Config): Promise<ConnectivityResult> {
230
269
  const host = config.host.replace(/\/+$/, "");
231
270
  const auth = Buffer.from(`${config.publicKey}:${config.secretKey}`).toString("base64");
@@ -239,7 +278,8 @@ async function checkLangfuseConnectivity(config: Config): Promise<ConnectivityRe
239
278
  });
240
279
 
241
280
  if (response.ok) {
242
- return { ok: true, message: `Connected to ${config.host}` };
281
+ const read = await probeReadSurface(host, auth);
282
+ return { ok: true, message: `Connected to ${config.host}; ${read.message}`, warning: read.warning };
243
283
  }
244
284
 
245
285
  return {
@@ -388,7 +428,7 @@ export async function handleLangfuseTestCommand(
388
428
  try {
389
429
  const rt = await (deps.getRuntime ?? getRuntime)();
390
430
  runtimeInitialized = true;
391
- rt.propagateAttributes(
431
+ const create = () => rt.propagateAttributes(
392
432
  {
393
433
  traceName: "pi-langfuse-test",
394
434
  metadata: {
@@ -413,7 +453,10 @@ export async function handleLangfuseTestCommand(
413
453
  return observation;
414
454
  },
415
455
  );
416
- notify(ctx, `Langfuse test succeeded. ${connectivity.message}; test trace sent to ${config.host}.`);
456
+ if (rt.withRootContext) rt.withRootContext(create);
457
+ else create();
458
+ const result = connectivity.warning ? "completed with a read warning" : "succeeded";
459
+ notify(ctx, `Langfuse test ${result}. ${connectivity.message}; test trace sent to ${config.host}.`, connectivity.warning ? "warning" : "info");
417
460
  return true;
418
461
  } catch (error) {
419
462
  const message = error instanceof Error ? error.message : String(error);
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,10 +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, getLimits } 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
+ 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";
8
11
  import { startChildObservation } from "../observation.js";
9
12
 
10
13
  function stringMetadata(metadata: Record<string, unknown> | undefined): Record<string, string> | undefined {
@@ -25,7 +28,7 @@ function stringMetadata(metadata: Record<string, unknown> | undefined): Record<s
25
28
 
26
29
  export function updateTraceIO(input?: unknown, output?: unknown) {
27
30
  const root = state.agentState?.root;
28
- if (!root?.setTraceIO) {
31
+ if (!root?.setTraceIO || getSessionRunState().runBinding?.parent) {
29
32
  return;
30
33
  }
31
34
 
@@ -36,14 +39,36 @@ export function updateTraceIO(input?: unknown, output?: unknown) {
36
39
  }
37
40
  }
38
41
 
39
- export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
40
- if (!(await ensureConfig(ctx))) {
41
- state.isTracingDisabled = true;
42
- return;
43
- }
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
+ }
44
54
 
55
+ async function initializeRun(session: SessionRunState, binding: WorkflowBinding, event: Record<string, unknown>, ctx: any) {
45
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;
46
70
  const rt = await getRuntime();
71
+ if (getSessionRunState() !== session) return;
47
72
  const cwd = String(
48
73
  (event.systemPromptOptions && typeof event.systemPromptOptions === "object"
49
74
  ? (event.systemPromptOptions as Record<string, unknown>).cwd
@@ -72,6 +97,7 @@ export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
72
97
  ...(state.currentProvider ? { provider: state.currentProvider } : {}),
73
98
  sessionId: state.currentSessionId || undefined,
74
99
  sessionLeafId: ctx?.sessionManager?.getLeafId?.() || undefined,
100
+ ...sessionLineageMetadata(ctx?.sessionManager),
75
101
  },
76
102
  },
77
103
  capturePolicy,
@@ -93,30 +119,27 @@ export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
93
119
  uncachedInputTokens: 0,
94
120
  };
95
121
 
96
- const root = rt.propagateAttributes(
97
- {
98
- sessionId: state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined,
99
- userId: state.config?.userId,
100
- traceName: "pi-agent",
101
- metadata: stringMetadata(captured.metadata),
102
- },
103
- () =>
104
- rt.startObservation(
105
- "pi-agent",
106
- {
107
- input: captured.input,
108
- metadata: captured.metadata ?? {},
109
- },
110
- { asType: "agent" },
111
- ),
112
- );
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();
113
136
 
114
137
  state.agentState.root = root;
115
138
  state.agentState.traceId = root.traceId;
116
139
  updateTraceIO(captured.input, undefined);
117
140
  } catch (e) {
118
141
  console.warn("📊 Langfuse: Failed to create agent observation", e);
119
- state.isTracingDisabled = true;
142
+ session.tracingDisabled = true;
120
143
  }
121
144
  }
122
145
 
@@ -225,7 +248,7 @@ export async function recordSystemPrompt(ctx: any) {
225
248
  }
226
249
 
227
250
  const captured = applyCapturePolicy(
228
- { systemPrompt: truncate(String(systemPrompt), getLimits().maxString) },
251
+ { systemPrompt: String(systemPrompt) },
229
252
  getCapturePolicy(),
230
253
  );
231
254
  if (!captured.systemPrompt) {
@@ -245,6 +268,9 @@ export async function finishAgentRun(event: Record<string, unknown> = {}) {
245
268
  return;
246
269
  }
247
270
 
271
+ const session = getSessionRunState();
272
+ if (session.finishingRun) return;
273
+ session.finishingRun = true;
248
274
  const finalEvent = Object.keys(event).length > 0 ? event : state.agentState.lastAgentEndEvent ?? {};
249
275
  const lastAssistant = extractFinalAssistant(finalEvent.messages);
250
276
  const rawOutput = lastAssistant ? extractAssistantOutput(lastAssistant) : state.agentState.latestAssistantOutput;
@@ -293,14 +319,18 @@ export async function finishAgentRun(event: Record<string, unknown> = {}) {
293
319
  .end();
294
320
  updateTraceIO(state.agentState.promptInput, captured.output);
295
321
 
296
- await sendScore("tool_call_count", scores.tool_call_count, { traceId: state.agentState.traceId });
297
- await sendScore("turn_count", scores.turn_count, { traceId: state.agentState.traceId });
298
- await sendScore("total_tool_errors", scores.total_tool_errors, { traceId: state.agentState.traceId });
299
- await sendScore("tool_success_rate", scores.tool_success_rate, { traceId: state.agentState.traceId });
300
- 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);
301
331
  } catch (e) {
302
332
  console.warn("📊 Langfuse: Failed to finish agent observation", e);
303
333
  } finally {
304
- resetRunState();
334
+ if (getSessionRunState() === session) resetRunState();
305
335
  }
306
336
  }
@@ -2,14 +2,12 @@ import { applyCapturePolicy } from "../capture-policy.js";
2
2
  import { getRuntime } from "../langfuse.js";
3
3
  import { startChildObservation } from "../observation.js";
4
4
  import { getSessionRunState, state } from "../state.js";
5
- import { extractCostDetails, extractUsage, getCapturePolicy, truncate } from "../utils.js";
5
+ import { sessionLineageMetadata } from "../session-lineage.js";
6
+ import { extractCostDetails, extractUsage, getCapturePolicy } from "../utils.js";
7
+ import { isUnsampled, sessionGroupId } from "../workflow.js";
6
8
 
7
9
  type RecordLike = Record<string, unknown>;
8
10
 
9
- function sessionIdForTrace(): string | undefined {
10
- return state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined;
11
- }
12
-
13
11
  export function initializeUsageTracking(ctx: any): void {
14
12
  const session = getSessionRunState();
15
13
  try {
@@ -64,9 +62,10 @@ export async function recordCacheWarmingDecision(event: RecordLike, ctx: any): P
64
62
  const runtime = await getRuntime();
65
63
  const create = () => runtime.propagateAttributes(
66
64
  {
67
- sessionId: sessionIdForTrace(),
65
+ sessionId: sessionGroupId(),
68
66
  traceName: "pi-cache-warming",
69
67
  metadata: {
68
+ ...sessionLineageMetadata(ctx?.sessionManager),
70
69
  ...(ctx?.model?.id ? { model: String(ctx.model.id) } : {}),
71
70
  ...(ctx?.model?.provider ? { provider: String(ctx.model.provider) } : {}),
72
71
  },
@@ -85,7 +84,10 @@ export async function recordCacheWarmingDecision(event: RecordLike, ctx: any): P
85
84
  }
86
85
 
87
86
  export async function recordNewUsageEntries(ctx: any): Promise<void> {
88
- if (state.isTracingDisabled || !state.config) return;
87
+ if (state.isTracingDisabled || !state.config) {
88
+ if (isUnsampled(getSessionRunState().runBinding)) initializeUsageTracking(ctx);
89
+ return;
90
+ }
89
91
  const session = getSessionRunState();
90
92
  let entries: unknown;
91
93
  try {
@@ -95,6 +97,8 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
95
97
  }
96
98
  if (!Array.isArray(entries)) return;
97
99
 
100
+ const parent = session.agentState?.activeTurn ?? session.agentState?.activeAttempt ?? session.agentState?.root;
101
+ const sessionId = sessionGroupId();
98
102
  for (const rawEntry of entries) {
99
103
  if (!rawEntry || typeof rawEntry !== "object") continue;
100
104
  const entry = rawEntry as RecordLike;
@@ -120,7 +124,7 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
120
124
 
121
125
  try {
122
126
  const runtime = await getRuntime();
123
- const parent = state.agentState?.activeTurn ?? state.agentState?.activeAttempt ?? state.agentState?.root;
127
+ if (getSessionRunState() !== session) return;
124
128
  const body = {
125
129
  model: typeof entry.model === "string" ? entry.model : undefined,
126
130
  usageDetails,
@@ -131,11 +135,11 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
131
135
  ? await startChildObservation({ parent, runtime: getRuntime, name: "cache-warm", body, asType: "generation" })
132
136
  : (runtime.withRootContext
133
137
  ? runtime.withRootContext(() => runtime.propagateAttributes(
134
- { sessionId: sessionIdForTrace(), traceName: "pi-cache-warm" },
138
+ { sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
135
139
  () => runtime.startObservation("cache-warm", body, { asType: "generation" }),
136
140
  ))
137
141
  : runtime.propagateAttributes(
138
- { sessionId: sessionIdForTrace(), traceName: "pi-cache-warm" },
142
+ { sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
139
143
  () => runtime.startObservation("cache-warm", body, { asType: "generation" }),
140
144
  ));
141
145
  observation.end();