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,310 @@
1
+ import { state, resetRunState, getSessionRunState, computeEvaluationScores } from "../state.js";
2
+ import { getRuntime, sendScore } from "../langfuse.js";
3
+ import { ensureConfig } from "../config.js";
4
+ import { shapePayload, extractFinalAssistant, extractAssistantOutput, getCapturePolicy } from "../utils.js";
5
+ import { closeDanglingObservations } from "./tool.js";
6
+ import { applyCapturePolicy } from "../capture-policy.js";
7
+ import { collectSourceMetadata } from "../source-metadata.js";
8
+ import { sessionLineageMetadata } from "../session-lineage.js";
9
+ import { isUnsampled, localSessionGroupId, resolveRunBinding, warnWorkflow } from "../workflow.js";
10
+ import { recordNewUsageEntries } from "./cache.js";
11
+ import { startChildObservation } from "../observation.js";
12
+ function stringMetadata(metadata) {
13
+ if (!metadata) {
14
+ return undefined;
15
+ }
16
+ const output = {};
17
+ for (const [key, value] of Object.entries(metadata)) {
18
+ if (typeof value === "string") {
19
+ output[key] = value;
20
+ }
21
+ else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
22
+ output[key] = String(value);
23
+ }
24
+ }
25
+ return Object.keys(output).length > 0 ? output : undefined;
26
+ }
27
+ export function updateTraceIO(input, output) {
28
+ const root = state.agentState?.root;
29
+ if (!root?.setTraceIO || getSessionRunState().runBinding?.parent) {
30
+ return;
31
+ }
32
+ try {
33
+ root.setTraceIO({ input, output });
34
+ }
35
+ catch {
36
+ // Older SDKs may omit setTraceIO; root IO still mirrors trace IO in current Langfuse.
37
+ }
38
+ }
39
+ export function startAgentRun(event, ctx, getRunContext) {
40
+ const session = getSessionRunState();
41
+ if (session.startingRun)
42
+ return session.startingRun;
43
+ if (session.agentState?.root || isUnsampled(session.runBinding))
44
+ return Promise.resolve();
45
+ const binding = session.runBinding ?? resolveRunBinding(event, getRunContext);
46
+ session.runBinding = binding;
47
+ session.startingRun = initializeRun(session, binding, event, ctx).finally(() => {
48
+ session.startingRun = undefined;
49
+ });
50
+ return session.startingRun;
51
+ }
52
+ async function initializeRun(session, binding, event, ctx) {
53
+ try {
54
+ // Entries already present before this prompt belong to the session, even
55
+ // when the caller chose not to sample the upcoming run.
56
+ const previousUsage = recordNewUsageEntries(ctx);
57
+ const unsampled = isUnsampled(binding);
58
+ if (unsampled)
59
+ session.tracingDisabled = true;
60
+ await previousUsage;
61
+ if (unsampled || getSessionRunState() !== session)
62
+ return;
63
+ if (!(await ensureConfig(ctx))) {
64
+ session.tracingDisabled = true;
65
+ return;
66
+ }
67
+ if (getSessionRunState() !== session)
68
+ return;
69
+ session.tracingDisabled = false;
70
+ const rt = await getRuntime();
71
+ if (getSessionRunState() !== session)
72
+ return;
73
+ const cwd = String((event.systemPromptOptions && typeof event.systemPromptOptions === "object"
74
+ ? event.systemPromptOptions.cwd
75
+ : undefined) ?? process.cwd());
76
+ if (!state.currentModel && ctx.model) {
77
+ state.currentModel = ctx.model.id || "";
78
+ state.currentProvider = ctx.model.provider || "";
79
+ }
80
+ const rawPromptInput = shapePayload({
81
+ prompt: event.prompt,
82
+ images: event.images,
83
+ context: event.context ?? event.attachments,
84
+ });
85
+ const capturePolicy = getCapturePolicy();
86
+ const sourceMetadata = collectSourceMetadata(cwd, capturePolicy.captureSourceMetadata);
87
+ const captured = applyCapturePolicy({
88
+ input: rawPromptInput,
89
+ metadata: {
90
+ cwd,
91
+ ...sourceMetadata,
92
+ ...(state.currentModel ? { model: state.currentModel } : {}),
93
+ ...(state.currentProvider ? { provider: state.currentProvider } : {}),
94
+ sessionId: state.currentSessionId || undefined,
95
+ sessionLeafId: ctx?.sessionManager?.getLeafId?.() || undefined,
96
+ ...sessionLineageMetadata(ctx?.sessionManager),
97
+ },
98
+ }, capturePolicy);
99
+ state.agentState = {
100
+ cwd,
101
+ promptInput: captured.input,
102
+ generationSeq: 0,
103
+ activeGenerations: new Map(),
104
+ generationOrder: [],
105
+ activeTools: new Map(),
106
+ sourceMetadata,
107
+ providerMetadataByRequest: new Map(),
108
+ attemptCount: 0,
109
+ systemStateChangeCount: 0,
110
+ cacheReadTokens: 0,
111
+ cacheWriteTokens: 0,
112
+ uncachedInputTokens: 0,
113
+ };
114
+ const attributes = binding.parent
115
+ ? { sessionId: binding.sessionId }
116
+ : {
117
+ sessionId: binding.sessionId ?? localSessionGroupId(),
118
+ userId: state.config?.userId,
119
+ traceName: "pi-agent",
120
+ metadata: stringMetadata(captured.metadata),
121
+ };
122
+ const create = () => rt.propagateAttributes(attributes, () => rt.startObservation("pi-agent", { input: captured.input, metadata: captured.metadata ?? {} }, { asType: "agent", parentSpanContext: binding.parent }));
123
+ const root = rt.withRootContext ? rt.withRootContext(create) : create();
124
+ state.agentState.root = root;
125
+ state.agentState.traceId = root.traceId;
126
+ updateTraceIO(captured.input, undefined);
127
+ }
128
+ catch (e) {
129
+ console.warn("📊 Langfuse: Failed to create agent observation", e);
130
+ session.tracingDisabled = true;
131
+ }
132
+ }
133
+ export async function startAgentAttempt() {
134
+ const agent = state.agentState;
135
+ if (state.isTracingDisabled || !agent?.root)
136
+ return;
137
+ if (agent.activeAttempt) {
138
+ agent.activeAttempt
139
+ .update({ level: "WARNING", statusMessage: "A new agent attempt started before the previous attempt ended" })
140
+ .end();
141
+ }
142
+ try {
143
+ agent.attemptCount++;
144
+ agent.activeAttempt = await startChildObservation({
145
+ parent: agent.root,
146
+ runtime: getRuntime,
147
+ name: "agent-attempt",
148
+ body: { metadata: { attemptIndex: agent.attemptCount } },
149
+ asType: "span",
150
+ });
151
+ }
152
+ catch (error) {
153
+ console.warn("📊 Langfuse: Failed to start agent attempt", error);
154
+ }
155
+ }
156
+ export function finishAgentAttempt(event = {}) {
157
+ const agent = state.agentState;
158
+ if (!agent)
159
+ return;
160
+ agent.lastAgentEndEvent = event;
161
+ closeDanglingObservations("Agent attempt ended before observation finalized");
162
+ if (agent.activeTurn) {
163
+ agent.activeTurn
164
+ .update({ level: "WARNING", statusMessage: "Agent attempt ended before turn finalized" })
165
+ .end();
166
+ agent.activeTurn = undefined;
167
+ }
168
+ if (!agent.activeAttempt)
169
+ return;
170
+ try {
171
+ const lastAssistant = extractFinalAssistant(event.messages);
172
+ const captured = applyCapturePolicy({ output: lastAssistant ? extractAssistantOutput(lastAssistant) : undefined }, getCapturePolicy());
173
+ agent.activeAttempt.update({ output: captured.output }).end();
174
+ }
175
+ catch (error) {
176
+ console.warn("📊 Langfuse: Failed to finish agent attempt", error);
177
+ }
178
+ finally {
179
+ agent.activeAttempt = undefined;
180
+ }
181
+ }
182
+ export function cancelAgentRun(reason) {
183
+ const agent = state.agentState;
184
+ if (!agent?.root) {
185
+ resetRunState();
186
+ return;
187
+ }
188
+ closeDanglingObservations(reason);
189
+ if (agent.activeTurn) {
190
+ agent.activeTurn.update({ level: "WARNING", statusMessage: reason, metadata: { cancelled: true } }).end();
191
+ agent.activeTurn = undefined;
192
+ }
193
+ if (agent.activeAttempt) {
194
+ agent.activeAttempt.update({ level: "WARNING", statusMessage: reason, metadata: { cancelled: true } }).end();
195
+ agent.activeAttempt = undefined;
196
+ }
197
+ agent.root.update({
198
+ level: "WARNING",
199
+ statusMessage: reason,
200
+ metadata: { completed: false, cancelled: true },
201
+ }).end();
202
+ resetRunState();
203
+ }
204
+ /**
205
+ * Records the effective system prompt on the root agent observation.
206
+ *
207
+ * Deliberately called from `agent_start` rather than `before_agent_start`:
208
+ * during `before_agent_start` the extension runner hands each handler the
209
+ * prompt as it stands mid-chain, so extensions registered after this one
210
+ * (e.g. inline factories that rewrite the system prompt) are not reflected
211
+ * yet. By `agent_start` the session has applied the final override, and
212
+ * `ctx.getSystemPrompt()` returns the prompt actually sent to the model.
213
+ */
214
+ export async function recordSystemPrompt(ctx) {
215
+ const root = state.agentState?.root;
216
+ if (state.isTracingDisabled || !root) {
217
+ return;
218
+ }
219
+ let systemPrompt = undefined;
220
+ try {
221
+ if (ctx.getSystemPrompt) {
222
+ systemPrompt = await ctx.getSystemPrompt();
223
+ }
224
+ }
225
+ catch {
226
+ // Ignore if getSystemPrompt is not available or fails
227
+ }
228
+ if (!systemPrompt) {
229
+ return;
230
+ }
231
+ const captured = applyCapturePolicy({ systemPrompt: String(systemPrompt) }, getCapturePolicy());
232
+ if (!captured.systemPrompt) {
233
+ return;
234
+ }
235
+ try {
236
+ root.update({ metadata: { systemPrompt: captured.systemPrompt } });
237
+ }
238
+ catch (e) {
239
+ console.warn("\u{1F4CA} Langfuse: Failed to record system prompt", e);
240
+ }
241
+ }
242
+ export async function finishAgentRun(event = {}) {
243
+ if (!state.agentState?.root) {
244
+ resetRunState();
245
+ return;
246
+ }
247
+ const session = getSessionRunState();
248
+ if (session.finishingRun)
249
+ return;
250
+ session.finishingRun = true;
251
+ const finalEvent = Object.keys(event).length > 0 ? event : state.agentState.lastAgentEndEvent ?? {};
252
+ const lastAssistant = extractFinalAssistant(finalEvent.messages);
253
+ const rawOutput = lastAssistant ? extractAssistantOutput(lastAssistant) : state.agentState.latestAssistantOutput;
254
+ const captured = applyCapturePolicy({
255
+ output: rawOutput,
256
+ metadata: {
257
+ cwd: state.agentState.cwd,
258
+ ...(state.agentState.sourceMetadata ?? {}),
259
+ completed: true,
260
+ model: state.currentModel || undefined,
261
+ provider: state.currentProvider || undefined,
262
+ totalTools: state.toolCallCount,
263
+ agentAttemptCount: state.agentState.attemptCount,
264
+ systemStateChangeCount: state.agentState.systemStateChangeCount,
265
+ promptStateHash: state.agentState.promptStateHash,
266
+ toolStateHash: state.agentState.toolStateHash,
267
+ activeToolCount: state.agentState.activeToolCount,
268
+ cacheReadTokens: state.agentState.cacheReadTokens,
269
+ cacheWriteTokens: state.agentState.cacheWriteTokens,
270
+ uncachedInputTokens: state.agentState.uncachedInputTokens,
271
+ cacheHitRatio: state.agentState.cacheReadTokens + state.agentState.uncachedInputTokens > 0
272
+ ? state.agentState.cacheReadTokens /
273
+ (state.agentState.cacheReadTokens + state.agentState.uncachedInputTokens)
274
+ : undefined,
275
+ ...computeEvaluationScores(),
276
+ },
277
+ }, getCapturePolicy());
278
+ const scores = computeEvaluationScores();
279
+ closeDanglingObservations("Agent run ended before observation finalized");
280
+ if (state.agentState.activeAttempt) {
281
+ state.agentState.activeAttempt.end();
282
+ state.agentState.activeAttempt = undefined;
283
+ }
284
+ try {
285
+ state.agentState.root
286
+ .update({
287
+ output: captured.output,
288
+ metadata: captured.metadata,
289
+ })
290
+ .end();
291
+ updateTraceIO(state.agentState.promptInput, captured.output);
292
+ const target = {
293
+ traceId: state.agentState.traceId,
294
+ observationId: session.runBinding?.parent ? state.agentState.root.id : undefined,
295
+ };
296
+ if (session.runBinding?.parent && (!target.observationId || !target.traceId)) {
297
+ warnWorkflow("Skipping workflow run scores without an observation identity.");
298
+ return;
299
+ }
300
+ for (const [name, value] of Object.entries(scores))
301
+ await sendScore(name, value, target);
302
+ }
303
+ catch (e) {
304
+ console.warn("📊 Langfuse: Failed to finish agent observation", e);
305
+ }
306
+ finally {
307
+ if (getSessionRunState() === session)
308
+ resetRunState();
309
+ }
310
+ }
@@ -0,0 +1,5 @@
1
+ type RecordLike = Record<string, unknown>;
2
+ export declare function initializeUsageTracking(ctx: any): void;
3
+ export declare function recordCacheWarmingDecision(event: RecordLike, ctx: any): Promise<void>;
4
+ export declare function recordNewUsageEntries(ctx: any): Promise<void>;
5
+ export {};
@@ -0,0 +1,134 @@
1
+ import { applyCapturePolicy } from "../capture-policy.js";
2
+ import { getRuntime } from "../langfuse.js";
3
+ import { startChildObservation } from "../observation.js";
4
+ import { getSessionRunState, state } from "../state.js";
5
+ import { sessionLineageMetadata } from "../session-lineage.js";
6
+ import { extractCostDetails, extractUsage, getCapturePolicy } from "../utils.js";
7
+ import { isUnsampled, sessionGroupId } from "../workflow.js";
8
+ export function initializeUsageTracking(ctx) {
9
+ const session = getSessionRunState();
10
+ try {
11
+ const entries = ctx?.sessionManager?.getEntries?.();
12
+ if (!Array.isArray(entries))
13
+ return;
14
+ for (const entry of entries) {
15
+ if (entry && typeof entry === "object" && entry.type === "usage") {
16
+ const id = entry.id;
17
+ if (typeof id === "string")
18
+ session.seenUsageEntryIds.add(id);
19
+ }
20
+ }
21
+ }
22
+ catch {
23
+ // Optional for SDK hosts without persisted sessions.
24
+ }
25
+ }
26
+ export async function recordCacheWarmingDecision(event, ctx) {
27
+ if (state.isTracingDisabled || !state.config)
28
+ return;
29
+ const contextUsage = ctx?.getContextUsage?.();
30
+ const captured = applyCapturePolicy({
31
+ metadata: {
32
+ action: event.action,
33
+ warmCostEstimate: event.warmCost,
34
+ missCostEstimate: event.missCost,
35
+ continuationProbability: event.continuationProbability,
36
+ contextTokens: contextUsage?.tokens,
37
+ contextWindow: contextUsage?.contextWindow,
38
+ contextPercent: contextUsage?.percent,
39
+ idle: ctx?.isIdle?.(),
40
+ model: ctx?.model?.id,
41
+ provider: ctx?.model?.provider,
42
+ },
43
+ }, getCapturePolicy());
44
+ try {
45
+ const parent = state.agentState?.activeTurn ?? state.agentState?.activeAttempt ?? state.agentState?.root;
46
+ if (parent) {
47
+ const observation = await startChildObservation({
48
+ parent,
49
+ runtime: getRuntime,
50
+ name: "cache-warming-decision",
51
+ body: { metadata: captured.metadata },
52
+ asType: "event",
53
+ });
54
+ observation.end();
55
+ return;
56
+ }
57
+ const runtime = await getRuntime();
58
+ const create = () => runtime.propagateAttributes({
59
+ sessionId: sessionGroupId(),
60
+ traceName: "pi-cache-warming",
61
+ metadata: {
62
+ ...sessionLineageMetadata(ctx?.sessionManager),
63
+ ...(ctx?.model?.id ? { model: String(ctx.model.id) } : {}),
64
+ ...(ctx?.model?.provider ? { provider: String(ctx.model.provider) } : {}),
65
+ },
66
+ }, () => runtime.startObservation("cache-warming-decision", { metadata: captured.metadata }, { asType: "event" }));
67
+ const observation = runtime.withRootContext ? runtime.withRootContext(create) : create();
68
+ observation.end();
69
+ }
70
+ catch (error) {
71
+ console.warn("📊 Langfuse: Failed to record cache warming decision", error);
72
+ }
73
+ }
74
+ export async function recordNewUsageEntries(ctx) {
75
+ if (state.isTracingDisabled || !state.config) {
76
+ if (isUnsampled(getSessionRunState().runBinding))
77
+ initializeUsageTracking(ctx);
78
+ return;
79
+ }
80
+ const session = getSessionRunState();
81
+ let entries;
82
+ try {
83
+ entries = ctx?.sessionManager?.getEntries?.();
84
+ }
85
+ catch {
86
+ return;
87
+ }
88
+ if (!Array.isArray(entries))
89
+ return;
90
+ const parent = session.agentState?.activeTurn ?? session.agentState?.activeAttempt ?? session.agentState?.root;
91
+ const sessionId = sessionGroupId();
92
+ for (const rawEntry of entries) {
93
+ if (!rawEntry || typeof rawEntry !== "object")
94
+ continue;
95
+ const entry = rawEntry;
96
+ if (entry.type !== "usage" || typeof entry.id !== "string" || session.seenUsageEntryIds.has(entry.id))
97
+ continue;
98
+ if (entry.kind !== "cache_warm") {
99
+ session.seenUsageEntryIds.add(entry.id);
100
+ continue;
101
+ }
102
+ const usageDetails = extractUsage(entry);
103
+ const costDetails = extractCostDetails(entry);
104
+ const captured = applyCapturePolicy({
105
+ metadata: {
106
+ usageEntryId: entry.id,
107
+ kind: entry.kind,
108
+ note: entry.note,
109
+ provider: entry.provider,
110
+ },
111
+ }, getCapturePolicy());
112
+ try {
113
+ const runtime = await getRuntime();
114
+ if (getSessionRunState() !== session)
115
+ return;
116
+ const body = {
117
+ model: typeof entry.model === "string" ? entry.model : undefined,
118
+ usageDetails,
119
+ ...(costDetails ? { costDetails } : {}),
120
+ metadata: captured.metadata,
121
+ };
122
+ const observation = parent
123
+ ? await startChildObservation({ parent, runtime: getRuntime, name: "cache-warm", body, asType: "generation" })
124
+ : (runtime.withRootContext
125
+ ? runtime.withRootContext(() => runtime.propagateAttributes({ sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) }, () => runtime.startObservation("cache-warm", body, { asType: "generation" })))
126
+ : runtime.propagateAttributes({ sessionId, traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) }, () => runtime.startObservation("cache-warm", body, { asType: "generation" })));
127
+ observation.end();
128
+ session.seenUsageEntryIds.add(entry.id);
129
+ }
130
+ catch (error) {
131
+ console.warn("📊 Langfuse: Failed to record cache warming usage", error);
132
+ }
133
+ }
134
+ }
@@ -0,0 +1,9 @@
1
+ import type { GenerationState } from "../types.js";
2
+ export declare function getOpenGeneration(): GenerationState | undefined;
3
+ export declare function startGeneration(event: Record<string, unknown>, selectedModel?: unknown): Promise<void>;
4
+ export declare function updateGenerationMetadata(event: Record<string, unknown>): void;
5
+ export declare function recordTTFT(event: Record<string, unknown>): void;
6
+ /** Routing identity is available before the assistant message, including failed streams. */
7
+ export declare function recordGenerationIdentity(event: Record<string, unknown>): void;
8
+ export declare function finishGenerationFromMessage(event: Record<string, unknown>): Promise<void>;
9
+ export declare function createFallbackGenerationFromTurn(event: Record<string, unknown>, message: Record<string, unknown>): Promise<void>;