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,600 @@
1
+ import { getLimits } from "./limits.js";
2
+ import { getUsageOptions } from "./usage-options.js";
3
+ import { createCapturePolicy, redactOptionsFor } from "./capture-policy.js";
4
+ import { hasUnredactedSensitiveJsonField, redactString, redactValue } from "./redaction.js";
5
+ import { state } from "./state.js";
6
+ export function getCapturePolicy() {
7
+ return state.config?.capturePolicy ?? createCapturePolicy();
8
+ }
9
+ export { getLimits };
10
+ export function truncate(value, maxLength = getLimits().maxString) {
11
+ return value.length > maxLength ? `${value.slice(0, maxLength)}... [truncated]` : value;
12
+ }
13
+ export function tryParseJson(value) {
14
+ const trimmed = value.trim();
15
+ if (!trimmed || !["{", "["].includes(trimmed[0])) {
16
+ return value;
17
+ }
18
+ try {
19
+ return JSON.parse(trimmed);
20
+ }
21
+ catch {
22
+ return value;
23
+ }
24
+ }
25
+ const PAYLOAD_TOO_LARGE = "[payload too large]";
26
+ export function shapePayload(value, options = {}) {
27
+ const limits = getLimits();
28
+ const maxString = options.maxString ?? limits.maxString;
29
+ const depth = options.depth ?? limits.maxDepth;
30
+ const maxNodes = options.maxNodes ?? limits.maxNodes;
31
+ const maxArrayItems = options.maxArrayItems ?? limits.maxArrayItems;
32
+ const maxObjectKeys = options.maxObjectKeys ?? limits.maxObjectKeys;
33
+ const budget = { exhausted: false, nodeCount: 0 };
34
+ const redactionOptions = {
35
+ ...redactOptionsFor(getCapturePolicy()),
36
+ maxDepth: depth,
37
+ maxStringLength: maxString,
38
+ maxArrayItems,
39
+ maxObjectKeys,
40
+ };
41
+ function visit(item, remainingDepth, seen) {
42
+ if (budget.exhausted) {
43
+ return PAYLOAD_TOO_LARGE;
44
+ }
45
+ budget.nodeCount++;
46
+ if (budget.nodeCount > maxNodes) {
47
+ budget.exhausted = true;
48
+ return PAYLOAD_TOO_LARGE;
49
+ }
50
+ if (typeof item === "string") {
51
+ const jsonStart = options.parseJsonPrefix ? item.search(/[\[{]/) : item.search(/^[\s]*[\[{]/);
52
+ // Truncated JSON loses field names needed for secret redaction.
53
+ if (options.parseJson !== false && jsonStart >= 0 && item.length > maxString) {
54
+ return PAYLOAD_TOO_LARGE;
55
+ }
56
+ const truncated = truncate(item, maxString);
57
+ if (options.parseJson === false) {
58
+ return options.redact === false ? truncated : redactString(item, redactionOptions);
59
+ }
60
+ const candidate = jsonStart > 0 ? truncated.slice(jsonStart) : truncated;
61
+ const parsed = tryParseJson(candidate);
62
+ if (parsed === candidate) {
63
+ // Native tool suffixes and bracketed prefixes can make JSON unparseable.
64
+ if (options.redact !== false && ((options.parseJsonPrefix && /[\[{]\s*"/.test(truncated)) || hasUnredactedSensitiveJsonField(truncated)))
65
+ return "[unparseable error payload]";
66
+ return options.redact === false ? truncated : redactString(item, redactionOptions);
67
+ }
68
+ const shaped = visit(parsed, remainingDepth - 1, seen);
69
+ if (jsonStart > 0 && truncated.slice(0, jsonStart).trim()) {
70
+ // Pi/provider prefixes must not hide structured fields from redaction.
71
+ const safe = options.redact === false ? shaped : redactValue(shaped, redactionOptions);
72
+ return truncated.slice(0, jsonStart) + JSON.stringify(safe);
73
+ }
74
+ return shaped;
75
+ }
76
+ if (item === null ||
77
+ typeof item === "undefined" ||
78
+ typeof item === "number" ||
79
+ typeof item === "boolean") {
80
+ return item;
81
+ }
82
+ if (typeof item === "bigint") {
83
+ return item.toString();
84
+ }
85
+ if (typeof item === "function" || typeof item === "symbol") {
86
+ return `[${typeof item}]`;
87
+ }
88
+ if (remainingDepth <= 0) {
89
+ return `[max depth ${depth} reached]`;
90
+ }
91
+ if (Array.isArray(item)) {
92
+ const output = [];
93
+ const limit = Math.min(item.length, maxArrayItems);
94
+ for (let index = 0; index < limit; index++) {
95
+ output.push(visit(item[index], remainingDepth - 1, seen));
96
+ if (budget.exhausted) {
97
+ break;
98
+ }
99
+ }
100
+ return output;
101
+ }
102
+ if (item instanceof Error) {
103
+ // The stack repeats the raw message; retain frames without that copy.
104
+ return visit({
105
+ name: item.name,
106
+ message: item.message,
107
+ stack: item.message ? item.stack?.replaceAll(item.message, "[error message]") : item.stack,
108
+ }, remainingDepth, seen);
109
+ }
110
+ if (typeof item === "object") {
111
+ if (seen.has(item)) {
112
+ return "[circular]";
113
+ }
114
+ seen.add(item);
115
+ const output = {};
116
+ let keyCount = 0;
117
+ for (const key in item) {
118
+ if (!Object.hasOwn(item, key)) {
119
+ continue;
120
+ }
121
+ output[key] = visit(item[key], remainingDepth - 1, seen);
122
+ keyCount++;
123
+ if (budget.exhausted || keyCount >= maxObjectKeys) {
124
+ break;
125
+ }
126
+ }
127
+ return output;
128
+ }
129
+ return String(item);
130
+ }
131
+ const shaped = visit(value, depth, new WeakSet());
132
+ return options.redact === false
133
+ ? shaped
134
+ : redactValue(shaped, redactionOptions);
135
+ }
136
+ export function safeSerialize(value, maxLength = getLimits().maxToolPayload) {
137
+ try {
138
+ return truncate(JSON.stringify(shapePayload(value, { maxString: maxLength }), null, 2), maxLength);
139
+ }
140
+ catch {
141
+ return `[unserializable ${typeof value}]`;
142
+ }
143
+ }
144
+ export function estimatePayloadBytes(value, maxLength = getLimits().maxToolPayload) {
145
+ return new TextEncoder().encode(safeSerialize(value, maxLength)).length;
146
+ }
147
+ export function extractTextContent(content, maxLength, depth = 0) {
148
+ if (typeof content === "string") {
149
+ return maxLength ? truncate(content, maxLength) : content;
150
+ }
151
+ if (!Array.isArray(content)) {
152
+ // Tool results arrive wrapped ({ content: [{ type: "text", text }] }, or with
153
+ // the payload under result/output/text). The wrapper alone stringifies to
154
+ // "[object Object]", so dig out the text the reader actually wants; the depth
155
+ // cap keeps a reference cycle from recursing forever.
156
+ if (content && typeof content === "object" && depth < 2) {
157
+ const wrapper = content;
158
+ for (const nested of [wrapper.content, wrapper.result, wrapper.output, wrapper.text]) {
159
+ if (!nested || nested === content) {
160
+ continue;
161
+ }
162
+ const unwrapped = extractTextContent(nested, maxLength, depth + 1);
163
+ if (unwrapped) {
164
+ return unwrapped;
165
+ }
166
+ }
167
+ }
168
+ return undefined;
169
+ }
170
+ const text = content
171
+ .map((item) => {
172
+ if (!item || typeof item !== "object")
173
+ return "";
174
+ const block = item;
175
+ return block.type === "text" && block.text
176
+ ? typeof block.text === "string" ? block.text : safeSerialize(block.text, maxLength)
177
+ : "";
178
+ })
179
+ .filter(Boolean)
180
+ .join("\n");
181
+ if (!text) {
182
+ return undefined;
183
+ }
184
+ return maxLength ? truncate(text, maxLength) : text;
185
+ }
186
+ /**
187
+ * Human-readable text for an observation `statusMessage`: text blocks first, then
188
+ * the string, then JSON, so a structured error never lands as "[object Object]"
189
+ * or as a wall of escaped JSON. Shape and redact before extracting any text.
190
+ */
191
+ export function toStatusMessage(value, maxLength = 1_000) {
192
+ maxLength = Math.min(maxLength, getLimits().maxString);
193
+ const shaped = shapePayload(value instanceof Error ? value.message || String(value) : value, {
194
+ maxString: maxLength, parseJsonPrefix: true,
195
+ });
196
+ const text = extractTextContent(shaped, maxLength);
197
+ if (text) {
198
+ return text;
199
+ }
200
+ const message = shaped?.message;
201
+ if (typeof message === "string" && message) {
202
+ return truncate(message, maxLength);
203
+ }
204
+ try {
205
+ return truncate(JSON.stringify(shaped) ?? String(shaped), maxLength);
206
+ }
207
+ catch {
208
+ return "[unserializable error]";
209
+ }
210
+ }
211
+ export function normalizeContentForLangfuse(content, api) {
212
+ if (!Array.isArray(content)) {
213
+ return content;
214
+ }
215
+ const toolCallItems = content.filter((item) => {
216
+ return item && typeof item === "object" && item.type === "toolCall";
217
+ });
218
+ if (toolCallItems.length === 0) {
219
+ return content;
220
+ }
221
+ const text = content
222
+ .map((item) => {
223
+ if (!item || typeof item !== "object")
224
+ return "";
225
+ const block = item;
226
+ return block.type === "text" && typeof block.text === "string" ? block.text : "";
227
+ })
228
+ .filter(Boolean)
229
+ .join("");
230
+ if (api === "anthropic-messages") {
231
+ const blocks = [];
232
+ if (text) {
233
+ blocks.push({ type: "text", text });
234
+ }
235
+ for (const item of toolCallItems) {
236
+ const toolCall = item;
237
+ const toolInput = shapePayload(toolCall.arguments, { parseJson: false });
238
+ blocks.push({
239
+ type: "tool_use",
240
+ id: String(toolCall.id ?? ""),
241
+ name: String(toolCall.name ?? "tool"),
242
+ input: toolInput,
243
+ });
244
+ }
245
+ return blocks;
246
+ }
247
+ return {
248
+ role: "assistant",
249
+ content: text || null,
250
+ tool_calls: toolCallItems.map((item) => {
251
+ const toolCall = item;
252
+ const toolArguments = shapePayload(toolCall.arguments ?? {}, { parseJson: false });
253
+ return {
254
+ id: String(toolCall.id ?? ""),
255
+ type: "function",
256
+ function: {
257
+ name: String(toolCall.name ?? "tool"),
258
+ arguments: typeof toolArguments === "string" ? toolArguments : JSON.stringify(toolArguments),
259
+ },
260
+ };
261
+ }),
262
+ };
263
+ }
264
+ export function extractToolCalls(message) {
265
+ return (message.toolCalls ??
266
+ message.tool_calls ??
267
+ message.function_calls ??
268
+ (message.content && Array.isArray(message.content)
269
+ ? message.content.filter((block) => {
270
+ return block && typeof block === "object" && ["tool_use", "tool_call", "toolCall"].includes(String(block.type));
271
+ })
272
+ : undefined));
273
+ }
274
+ export function extractAssistantOutput(message) {
275
+ if (!message || typeof message !== "object") {
276
+ return undefined;
277
+ }
278
+ const msg = message;
279
+ const normalizedContent = normalizeContentForLangfuse(msg.content, typeof msg.api === "string" ? msg.api : undefined);
280
+ if (normalizedContent !== msg.content) {
281
+ return shapePayload(normalizedContent, { parseJson: false });
282
+ }
283
+ const text = extractTextContent(msg.content);
284
+ if (text) {
285
+ return text;
286
+ }
287
+ const toolCalls = extractToolCalls(msg);
288
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
289
+ return { toolCalls: shapePayload(toolCalls) };
290
+ }
291
+ if (toolCalls) {
292
+ return { toolCalls: shapePayload(toolCalls) };
293
+ }
294
+ return shapePayload(msg);
295
+ }
296
+ export function extractFinalAssistant(messages) {
297
+ if (!Array.isArray(messages)) {
298
+ return undefined;
299
+ }
300
+ return messages.filter((message) => message?.role === "assistant").pop();
301
+ }
302
+ export function getRequestKey(event, fallback) {
303
+ return String(event.requestId ??
304
+ event.providerRequestId ??
305
+ event.messageId ??
306
+ event.turnId ??
307
+ event.turnIndex ??
308
+ event.id ??
309
+ fallback);
310
+ }
311
+ export function getToolCallId(event) {
312
+ const id = event.toolCallId ?? event.id ?? event.callId ?? event.tool_use_id ?? event.toolUseId;
313
+ return id === undefined || id === null ? undefined : String(id);
314
+ }
315
+ export function getToolName(event) {
316
+ return String(event.toolName ??
317
+ event.name ??
318
+ event.tool ??
319
+ event.functionName ??
320
+ (event.call && typeof event.call === "object" ? event.call.name : undefined) ??
321
+ "tool");
322
+ }
323
+ export function getToolInput(event) {
324
+ return (event.input ??
325
+ event.args ??
326
+ event.arguments ??
327
+ event.params ??
328
+ (event.call && typeof event.call === "object" ? event.call.input : undefined) ??
329
+ event);
330
+ }
331
+ export function getProviderPayload(event) {
332
+ return event.request ?? event.payload ?? event.body ?? event.providerPayload ?? event.messages ?? event;
333
+ }
334
+ /** Classify the provider payload observed by this hook rather than guessing from the model name alone. */
335
+ export function inferToolUpdateTransport(payload, hasPriorSystemState) {
336
+ let sawToolChangeBlock = false;
337
+ let sawAdditionalTools = false;
338
+ let sawToolSearch = false;
339
+ let sawTopLevelTools = false;
340
+ let sawMidConversationSystem = false;
341
+ let visited = 0;
342
+ const walk = (value, key) => {
343
+ if (++visited > 2_000 || value === null || value === undefined)
344
+ return;
345
+ if (key === "additional_tools")
346
+ sawAdditionalTools = true;
347
+ if (key === "tools")
348
+ sawTopLevelTools = true;
349
+ if (key === "tool_search" || key === "tool_search_output")
350
+ sawToolSearch = true;
351
+ if (typeof value !== "object")
352
+ return;
353
+ if (Array.isArray(value)) {
354
+ let sawNonSystem = false;
355
+ for (const item of value) {
356
+ if (item && typeof item === "object" && !Array.isArray(item)) {
357
+ const role = item.role;
358
+ if (role === "system" && sawNonSystem)
359
+ sawMidConversationSystem = true;
360
+ if (role && role !== "system")
361
+ sawNonSystem = true;
362
+ }
363
+ walk(item);
364
+ }
365
+ return;
366
+ }
367
+ const record = value;
368
+ const type = record.type;
369
+ if (type === "tool_addition" || type === "tool_removal")
370
+ sawToolChangeBlock = true;
371
+ for (const [childKey, child] of Object.entries(record))
372
+ walk(child, childKey);
373
+ };
374
+ walk(payload);
375
+ if (sawToolChangeBlock)
376
+ return "anthropic-native";
377
+ if (sawAdditionalTools)
378
+ return "openai-additional-tools";
379
+ if (sawToolSearch)
380
+ return "openai-tool-search";
381
+ if (sawMidConversationSystem)
382
+ return "mid-conversation-system";
383
+ if (hasPriorSystemState && sawTopLevelTools)
384
+ return "collapsed-leading-system";
385
+ return undefined;
386
+ }
387
+ export function extractModelParameters(payload) {
388
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
389
+ return undefined;
390
+ }
391
+ const params = {};
392
+ const record = payload;
393
+ for (const key of [
394
+ "temperature",
395
+ "top_p",
396
+ "topP",
397
+ "max_tokens",
398
+ "maxTokens",
399
+ "max_completion_tokens",
400
+ "presence_penalty",
401
+ "frequency_penalty",
402
+ "reasoning_effort",
403
+ ]) {
404
+ const value = record[key];
405
+ if (typeof value === "string" || typeof value === "number") {
406
+ params[key] = value;
407
+ }
408
+ }
409
+ return Object.keys(params).length > 0 ? params : undefined;
410
+ }
411
+ export function extractGenerationStatus(message) {
412
+ const reason = message.finishReason ?? message.stopReason;
413
+ if (reason !== "error" && reason !== "aborted")
414
+ return {};
415
+ return {
416
+ level: reason === "error" ? "ERROR" : "WARNING",
417
+ statusMessage: toStatusMessage(message.errorMessage || (reason === "error" ? "Generation failed" : "Generation aborted"), getLimits().maxString),
418
+ };
419
+ }
420
+ export function getMessageFromEvent(event) {
421
+ if (event.message && typeof event.message === "object") {
422
+ return event.message;
423
+ }
424
+ if (event.role || event.content) {
425
+ return event;
426
+ }
427
+ return undefined;
428
+ }
429
+ /**
430
+ * Langfuse buckets usage and cost details by substring match on the key name:
431
+ * `input` rolls up into the Input row of the breakdown, `output` into Output,
432
+ * and anything matching neither falls into the catch-all Other row. Camel-cased
433
+ * `cacheWrite` lands in Other, so cache is reported outside the Input bucket it
434
+ * belongs to and never reaches Langfuse's own price table, which resolves
435
+ * usage types by exact key match (`price.usageType === key`) and therefore
436
+ * cannot price cache for providers that do not report cost themselves.
437
+ *
438
+ * These are the key names Langfuse documents for Anthropic-style caching.
439
+ * Pi reports `input` exclusive of cached tokens, so the buckets stay
440
+ * non-overlapping and nothing is double counted. Emitting both spellings would
441
+ * be worse than either: the canonical key would be counted in Input and the
442
+ * camel-cased duplicate again in Other.
443
+ */
444
+ const CACHE_READ_KEY = "cache_read_input_tokens";
445
+ const CACHE_WRITE_KEY = "cache_creation_input_tokens";
446
+ /**
447
+ * Anthropic prices one-hour cache writes at a different rate from the default
448
+ * five-minute ones, and Langfuse mirrors that with two TTL-specific usage keys.
449
+ * Pi reports the total under `cacheWrite` and the hour-TTL share of it under
450
+ * `cacheWrite1h`, so the two Langfuse buckets are `cacheWrite - cacheWrite1h`
451
+ * and `cacheWrite1h`. Both keys contain `input`, so the Input row of the
452
+ * breakdown is unchanged; only the price lookup differs.
453
+ */
454
+ const CACHE_WRITE_5M_KEY = "input_cache_creation_5m";
455
+ const CACHE_WRITE_1H_KEY = "input_cache_creation_1h";
456
+ /**
457
+ * Pi emits `cacheWrite1h: 0` on every Anthropic-family response, so a zero
458
+ * carries no TTL information. Only a non-zero hour-TTL figure is a real
459
+ * breakdown; everything else stays on the TTL-agnostic key so dashboards and
460
+ * custom model prices keyed on it keep working.
461
+ */
462
+ function splitCacheWrite(cacheWrite, cacheWrite1h) {
463
+ if (!cacheWrite) {
464
+ return {};
465
+ }
466
+ const longWrite = Math.min(Math.max(cacheWrite1h, 0), cacheWrite);
467
+ if (!longWrite) {
468
+ return { [CACHE_WRITE_KEY]: cacheWrite };
469
+ }
470
+ const shortWrite = cacheWrite - longWrite;
471
+ return {
472
+ ...(shortWrite ? { [CACHE_WRITE_5M_KEY]: shortWrite } : {}),
473
+ [CACHE_WRITE_1H_KEY]: longWrite,
474
+ };
475
+ }
476
+ /**
477
+ * Reasoning tokens are a subset of the completion, not a sibling of it: every
478
+ * provider Pi reports them for counts them inside `output`. Emitting them as an
479
+ * extra bucket alone would therefore inflate Output usage, so `output` is
480
+ * narrowed to the non-reasoning remainder first — the same conversion Langfuse
481
+ * applies to Gemini thought tokens in `OtelIngestionProcessor`. Both keys
482
+ * contain `output`, so Langfuse re-aggregates them into an unchanged Output row.
483
+ *
484
+ * Reasoning is clamped to the reported `output` so an inconsistent provider
485
+ * count cannot drive `output` negative or make the buckets stop summing to
486
+ * `total`.
487
+ *
488
+ * The split is opt-in (`PI_LANGFUSE_SPLIT_REASONING_TOKENS`). Langfuse prices
489
+ * usage by exact key and user-defined model prices shadow the maintained
490
+ * defaults, so a custom model priced on `output` alone would silently cost the
491
+ * reasoning share at zero the moment it moved to its own key. Off by default,
492
+ * `output` stays whole and reasoning is not reported, exactly as before.
493
+ */
494
+ const REASONING_KEY = "output_reasoning_tokens";
495
+ function splitReasoning(output, reasoning, enabled) {
496
+ if (!enabled) {
497
+ return { output };
498
+ }
499
+ const bounded = Math.min(Math.max(reasoning, 0), output);
500
+ if (!bounded) {
501
+ return { output };
502
+ }
503
+ return { output: output - bounded, [REASONING_KEY]: bounded };
504
+ }
505
+ export function extractUsage(messageOrEvent, options = getUsageOptions()) {
506
+ const usage = (messageOrEvent.usage ??
507
+ (messageOrEvent.message && typeof messageOrEvent.message === "object"
508
+ ? messageOrEvent.message.usage
509
+ : undefined));
510
+ if (!usage || typeof usage !== "object") {
511
+ return undefined;
512
+ }
513
+ const input = Number(usage.input ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens ?? 0);
514
+ const output = Number(usage.output ?? usage.outputTokens ?? usage.completion_tokens ?? usage.completionTokens ?? 0);
515
+ const total = Number(usage.total ?? usage.totalTokens ?? usage.total_tokens ?? input + output);
516
+ const cacheRead = Number(usage.cacheRead ?? usage.cache_read ?? usage.cachedTokens ?? 0);
517
+ const cacheWrite = Number(usage.cacheWrite ?? usage.cache_write ?? 0);
518
+ const cacheWrite1h = Number(usage.cacheWrite1h ?? usage.cache_write_1h ?? 0);
519
+ const reasoning = Number(usage.reasoning ?? usage.reasoningTokens ?? usage.reasoning_tokens ?? usage.thoughtsTokenCount ?? 0);
520
+ return {
521
+ input,
522
+ ...splitReasoning(output, reasoning, options.splitReasoningTokens),
523
+ total,
524
+ ...(cacheRead ? { [CACHE_READ_KEY]: cacheRead } : {}),
525
+ ...splitCacheWrite(cacheWrite, cacheWrite1h),
526
+ };
527
+ }
528
+ export function extractCacheMetrics(messageOrEvent) {
529
+ const usage = (messageOrEvent.usage ??
530
+ (messageOrEvent.message && typeof messageOrEvent.message === "object"
531
+ ? messageOrEvent.message.usage
532
+ : undefined));
533
+ if (!usage || typeof usage !== "object")
534
+ return undefined;
535
+ const uncachedInputTokens = Number(usage.input ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens ?? 0);
536
+ const cacheReadTokens = Number(usage.cacheRead ?? usage.cache_read ?? usage.cachedTokens ?? 0);
537
+ const cacheWriteTokens = Number(usage.cacheWrite ?? usage.cache_write ?? 0);
538
+ const denominator = uncachedInputTokens + cacheReadTokens;
539
+ return {
540
+ cacheReadTokens,
541
+ cacheWriteTokens,
542
+ uncachedInputTokens,
543
+ ...(denominator > 0 ? { cacheHitRatio: cacheReadTokens / denominator } : {}),
544
+ };
545
+ }
546
+ export function extractCostDetails(messageOrEvent) {
547
+ const usage = (messageOrEvent.usage ??
548
+ (messageOrEvent.message && typeof messageOrEvent.message === "object"
549
+ ? messageOrEvent.message.usage
550
+ : undefined));
551
+ const cost = (messageOrEvent.cost ?? usage?.cost ?? messageOrEvent.costDetails);
552
+ if (!cost || typeof cost !== "object") {
553
+ return undefined;
554
+ }
555
+ const input = Number(cost.input ?? cost.inputCost ?? 0);
556
+ const output = Number(cost.output ?? cost.outputCost ?? 0);
557
+ const cacheRead = Number(cost.cacheRead ?? cost.cache_read ?? 0);
558
+ // Pi has no per-TTL cost figure: `cost.cacheWrite` already prices the
559
+ // five-minute and one-hour shares at their own rates and sums them, so the
560
+ // cost side stays on the aggregate key even when usage is split by TTL.
561
+ const cacheWrite = Number(cost.cacheWrite ?? cost.cache_write ?? 0);
562
+ const total = Number(cost.total ?? cost.totalCost ?? input + output + cacheRead + cacheWrite);
563
+ if (input === 0 && output === 0 && cacheRead === 0 && cacheWrite === 0 && total === 0) {
564
+ return undefined;
565
+ }
566
+ return {
567
+ input,
568
+ output,
569
+ total,
570
+ ...(cacheRead ? { [CACHE_READ_KEY]: cacheRead } : {}),
571
+ ...(cacheWrite ? { [CACHE_WRITE_KEY]: cacheWrite } : {}),
572
+ };
573
+ }
574
+ /** Accept both provider model ids and Pi Model objects without serializing the whole model. */
575
+ export function extractModelIdentity(value, provider) {
576
+ const record = value && typeof value === "object" ? value : undefined;
577
+ const model = record?.id ?? record?.model ?? value;
578
+ const actualProvider = provider ?? record?.provider;
579
+ return {
580
+ ...(typeof model === "string" && model ? { model } : {}),
581
+ ...(typeof actualProvider === "string" && actualProvider ? { provider: actualProvider } : {}),
582
+ };
583
+ }
584
+ /** Tool hooks report own usage; transcript toolResult messages also include descendants' usage. */
585
+ export function extractToolUsage(event) {
586
+ const result = event.result && typeof event.result === "object"
587
+ ? event.result
588
+ : {};
589
+ const source = { usage: event.usage ?? result.usage, cost: event.cost ?? result.cost };
590
+ return { usageDetails: extractUsage(source), costDetails: extractCostDetails(source) };
591
+ }
592
+ export function extractResponseMetadata(event) {
593
+ return shapePayload({
594
+ status: event.status ?? event.statusCode ?? event.httpStatus,
595
+ headers: event.headers,
596
+ responseHeaders: event.responseHeaders,
597
+ providerMetadata: event.providerMetadata ?? event.metadata,
598
+ requestId: event.requestId ?? event.providerRequestId,
599
+ }, { depth: 4, maxString: 4_000 });
600
+ }
@@ -0,0 +1,24 @@
1
+ import { type SpanContext } from "@opentelemetry/api";
2
+ export interface WorkflowContext {
3
+ sessionId?: string;
4
+ traceparent?: string;
5
+ }
6
+ export interface LangfuseExtensionOptions {
7
+ getRunContext?(run: {
8
+ piSessionId: string;
9
+ messageType: "user" | "custom" | "unknown";
10
+ }): WorkflowContext | undefined;
11
+ }
12
+ export interface WorkflowBinding {
13
+ sessionId?: string;
14
+ parent?: SpanContext;
15
+ }
16
+ export declare function warnWorkflow(reason: string): void;
17
+ export declare function parseWorkflowContext(input: {
18
+ sessionId?: unknown;
19
+ traceparent?: unknown;
20
+ }): WorkflowBinding;
21
+ export declare function resolveRunBinding(event: Record<string, unknown>, getRunContext?: LangfuseExtensionOptions["getRunContext"]): WorkflowBinding;
22
+ export declare function sessionGroupId(): string | undefined;
23
+ export declare function localSessionGroupId(): string | undefined;
24
+ export declare function isUnsampled(binding?: WorkflowBinding): boolean;
@@ -0,0 +1,62 @@
1
+ import { defaultTextMapGetter, ROOT_CONTEXT, trace, TraceFlags } from "@opentelemetry/api";
2
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
3
+ import { redactString } from "./redaction.js";
4
+ import { getSessionRunState, state } from "./state.js";
5
+ import { truncate } from "./utils.js";
6
+ const propagator = new W3CTraceContextPropagator();
7
+ export function warnWorkflow(reason) {
8
+ const session = getSessionRunState();
9
+ const warnings = session.workflowWarnings ??= new Set();
10
+ if (warnings.has(reason))
11
+ return;
12
+ warnings.add(reason);
13
+ console.warn(`📊 Langfuse: ${reason}`);
14
+ }
15
+ export function parseWorkflowContext(input) {
16
+ const binding = {};
17
+ const { sessionId, traceparent } = input;
18
+ if (sessionId !== undefined) {
19
+ if (typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= 200
20
+ && !/[^\x20-\x7e]/.test(sessionId) && sessionId.trim() === sessionId && redactString(sessionId) === sessionId) {
21
+ binding.sessionId = sessionId;
22
+ }
23
+ else {
24
+ warnWorkflow("Ignoring invalid workflow session ID; using the default grouping for this trace.");
25
+ }
26
+ }
27
+ if (traceparent !== undefined) {
28
+ if (typeof traceparent === "string" && traceparent.length <= 512 && !/[^\x21-\x7e]/.test(traceparent)) {
29
+ const context = propagator.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
30
+ binding.parent = trace.getSpanContext(context);
31
+ }
32
+ if (!binding.parent)
33
+ warnWorkflow("Ignoring invalid traceparent; creating an independent trace.");
34
+ }
35
+ return binding;
36
+ }
37
+ export function resolveRunBinding(event, getRunContext) {
38
+ const session = getSessionRunState();
39
+ if (getRunContext && state.currentSessionId) {
40
+ try {
41
+ const messageType = event.messageType === "custom" ? "custom"
42
+ : typeof event.prompt === "string" || event.messageType === "user" ? "user" : "unknown";
43
+ const input = getRunContext({ piSessionId: state.currentSessionId, messageType });
44
+ if (input !== undefined)
45
+ return parseWorkflowContext(input);
46
+ }
47
+ catch {
48
+ warnWorkflow("Workflow context callback failed; using an independent trace.");
49
+ return {};
50
+ }
51
+ }
52
+ return session.startupBinding ?? {};
53
+ }
54
+ export function sessionGroupId() {
55
+ return getSessionRunState().startupBinding?.sessionId ?? localSessionGroupId();
56
+ }
57
+ export function localSessionGroupId() {
58
+ return state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined;
59
+ }
60
+ export function isUnsampled(binding) {
61
+ return !!binding?.parent && (binding.parent.traceFlags & TraceFlags.SAMPLED) === 0;
62
+ }