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,168 @@
1
+ import { getSessionRunState, state } from "../state.js";
2
+ import { warnWorkflow } from "../workflow.js";
3
+ import { getRuntime, sendScore } from "../langfuse.js";
4
+ import { startChildObservation } from "../observation.js";
5
+ import { getToolCallId, getToolName, getToolInput, shapePayload, extractTextContent, toStatusMessage, estimatePayloadBytes, getCapturePolicy, getLimits, extractToolUsage, } from "../utils.js";
6
+ import { applyCapturePolicy } from "../capture-policy.js";
7
+ export async function startToolObservation(event) {
8
+ if (state.isTracingDisabled || !state.agentState?.root) {
9
+ return;
10
+ }
11
+ const toolCallId = getToolCallId(event);
12
+ if (!toolCallId || state.agentState.activeTools.has(toolCallId)) {
13
+ return;
14
+ }
15
+ try {
16
+ const toolName = getToolName(event);
17
+ const parentToolCallId = typeof event.parentToolCallId === "string" ? event.parentToolCallId : undefined;
18
+ const toolInput = getToolInput(event);
19
+ const shapedInput = shapePayload(toolInput, { maxString: getLimits().maxToolPayload });
20
+ const captured = applyCapturePolicy({
21
+ toolInput: shapedInput,
22
+ metadata: shapePayload({ toolName, toolCallId, parentToolCallId }),
23
+ }, getCapturePolicy());
24
+ const inputBytes = estimatePayloadBytes(captured.toolInput, getLimits().maxToolPayload);
25
+ const parentTool = parentToolCallId ? state.agentState.activeTools.get(parentToolCallId) : undefined;
26
+ const parent = parentTool?.observation ?? state.agentState.activeTurn ?? state.agentState.activeAttempt ?? state.agentState.root;
27
+ const tool = await startChildObservation({
28
+ parent,
29
+ runtime: getRuntime,
30
+ name: toolName,
31
+ body: {
32
+ input: captured.toolInput,
33
+ metadata: { ...(captured.metadata ?? {}), inputBytes },
34
+ },
35
+ asType: "tool",
36
+ });
37
+ state.toolCallCount++;
38
+ state.agentState.activeTools.set(toolCallId, {
39
+ observation: tool,
40
+ toolName,
41
+ ended: false,
42
+ startedAt: Date.now(),
43
+ inputBytes,
44
+ parentToolCallId,
45
+ });
46
+ }
47
+ catch (e) {
48
+ console.warn("📊 Langfuse: Failed to start tool observation", e);
49
+ }
50
+ }
51
+ export async function finishToolObservation(event) {
52
+ if (state.isTracingDisabled || !state.agentState) {
53
+ return;
54
+ }
55
+ const toolCallId = getToolCallId(event);
56
+ if (!toolCallId) {
57
+ return;
58
+ }
59
+ const activeTool = state.agentState.activeTools.get(toolCallId);
60
+ if (!activeTool || activeTool.ended) {
61
+ return;
62
+ }
63
+ // Claim completion before creating the usage child (which awaits the runtime).
64
+ activeTool.ended = true;
65
+ const isError = Boolean(event.isError ?? event.error ?? event.status === "error");
66
+ const output = extractTextContent(event.content) ??
67
+ event.output ??
68
+ event.result ??
69
+ event.error ??
70
+ event.content ??
71
+ event;
72
+ try {
73
+ const policy = getCapturePolicy();
74
+ const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload, parseJsonPrefix: isError });
75
+ const captured = applyCapturePolicy({
76
+ toolOutput: shapedOutput,
77
+ metadata: shapePayload({
78
+ toolName: activeTool.toolName,
79
+ toolCallId,
80
+ parentToolCallId: activeTool.parentToolCallId,
81
+ isError,
82
+ }),
83
+ }, policy);
84
+ const outputBytes = estimatePayloadBytes(captured.toolOutput, getLimits().maxToolPayload);
85
+ const durationMs = Math.max(0, Date.now() - activeTool.startedAt);
86
+ // Pi's tool_result and tool_execution_end carry only this tool's own usage.
87
+ // Do not consume transcript toolResult usage, which includes all descendants.
88
+ // A separate generation makes this cost visible on Langfuse versions that
89
+ // only account for usage/cost on generation observations.
90
+ const { usageDetails, costDetails } = extractToolUsage(event);
91
+ if (usageDetails || costDetails) {
92
+ try {
93
+ const usage = await startChildObservation({
94
+ parent: activeTool.observation,
95
+ runtime: getRuntime,
96
+ name: "tool-usage",
97
+ body: {
98
+ usageDetails,
99
+ costDetails,
100
+ metadata: applyCapturePolicy({ metadata: shapePayload({
101
+ toolName: activeTool.toolName,
102
+ toolCallId,
103
+ parentToolCallId: activeTool.parentToolCallId,
104
+ usageSource: "tool-result",
105
+ }) }, policy).metadata,
106
+ },
107
+ asType: "generation",
108
+ });
109
+ usage.end();
110
+ }
111
+ catch (error) {
112
+ console.warn("📊 Langfuse: Failed to record tool usage", error);
113
+ }
114
+ }
115
+ activeTool.observation
116
+ .update({
117
+ output: captured.toolOutput,
118
+ level: isError ? "ERROR" : "DEFAULT",
119
+ statusMessage: isError
120
+ ? toStatusMessage(event.error ?? output, 1_000)
121
+ : undefined,
122
+ metadata: {
123
+ ...(captured.metadata ?? {}),
124
+ durationMs,
125
+ inputBytes: activeTool.inputBytes,
126
+ outputBytes,
127
+ },
128
+ })
129
+ .end();
130
+ if (isError) {
131
+ state.errorCount++;
132
+ if (getSessionRunState().runBinding?.parent && (!activeTool.observation.id || !state.agentState.traceId)) {
133
+ warnWorkflow("Skipping workflow tool score without an observation identity.");
134
+ return;
135
+ }
136
+ await sendScore("tool_is_error", 1, {
137
+ traceId: state.agentState.traceId,
138
+ observationId: activeTool.observation.id,
139
+ });
140
+ }
141
+ }
142
+ catch (e) {
143
+ console.warn("📊 Langfuse: Failed to finish tool observation", e);
144
+ }
145
+ finally {
146
+ state.agentState.activeTools.delete(toolCallId);
147
+ }
148
+ }
149
+ export function closeDanglingObservations(statusMessage) {
150
+ if (state.isTracingDisabled || !state.agentState) {
151
+ return;
152
+ }
153
+ for (const activeTool of state.agentState.activeTools.values()) {
154
+ if (!activeTool.ended) {
155
+ activeTool.observation
156
+ .update({ level: "WARNING", statusMessage, metadata: { toolName: activeTool.toolName, cancelled: true } })
157
+ .end();
158
+ activeTool.ended = true;
159
+ }
160
+ }
161
+ for (const generation of state.agentState.activeGenerations.values()) {
162
+ if (!generation.ended) {
163
+ generation.observation.update({ level: "WARNING", statusMessage, ...generation.errorStatus, metadata: { ...generation.metadata, cancelled: true } }).end();
164
+ generation.ended = true;
165
+ }
166
+ }
167
+ state.agentState.activeTools.clear();
168
+ }
@@ -0,0 +1,2 @@
1
+ export declare function startTurnObservation(event: Record<string, unknown>): Promise<void>;
2
+ export declare function finishTurnObservation(_event?: Record<string, unknown>): void;
@@ -0,0 +1,48 @@
1
+ import { state } from "../state.js";
2
+ import { getRuntime } from "../langfuse.js";
3
+ import { startChildObservation } from "../observation.js";
4
+ import { shapePayload, getCapturePolicy } from "../utils.js";
5
+ import { applyCapturePolicy } from "../capture-policy.js";
6
+ export async function startTurnObservation(event) {
7
+ if (state.isTracingDisabled || !state.agentState?.root) {
8
+ return;
9
+ }
10
+ // If a turn is already active, close it (fallback safety)
11
+ if (state.agentState.activeTurn) {
12
+ state.agentState.activeTurn.end();
13
+ state.agentState.activeTurn = undefined;
14
+ }
15
+ try {
16
+ const turnIndex = event.turnIndex ?? state.turnCount;
17
+ const captured = applyCapturePolicy({
18
+ input: shapePayload(event.context ?? event),
19
+ metadata: { turnIndex },
20
+ }, getCapturePolicy());
21
+ const observation = await startChildObservation({
22
+ parent: state.agentState.activeAttempt ?? state.agentState.root,
23
+ runtime: getRuntime,
24
+ name: "turn",
25
+ body: {
26
+ input: captured.input,
27
+ metadata: captured.metadata,
28
+ },
29
+ asType: "span",
30
+ });
31
+ state.agentState.activeTurn = observation;
32
+ }
33
+ catch (e) {
34
+ console.warn("📊 Langfuse: Failed to start turn observation", e);
35
+ }
36
+ }
37
+ export function finishTurnObservation(_event) {
38
+ if (state.isTracingDisabled || !state.agentState?.activeTurn) {
39
+ return;
40
+ }
41
+ try {
42
+ state.agentState.activeTurn.end();
43
+ state.agentState.activeTurn = undefined;
44
+ }
45
+ catch (e) {
46
+ console.warn("📊 Langfuse: Failed to finish turn observation", e);
47
+ }
48
+ }
@@ -0,0 +1,42 @@
1
+ import type { LangfuseRuntime } from "./types.js";
2
+ interface OtelContextManager {
3
+ enable(): OtelContextManager;
4
+ disable(): void;
5
+ }
6
+ interface OtelContextApi {
7
+ setGlobalContextManager(contextManager: OtelContextManager): boolean;
8
+ }
9
+ type AsyncHooksContextManagerCtor = new () => OtelContextManager;
10
+ export declare function ensureOtelContextManager(contextApi: OtelContextApi, AsyncHooksContextManager: AsyncHooksContextManagerCtor): boolean;
11
+ export declare function getLastRuntimeError(): {
12
+ scope: string;
13
+ message: string;
14
+ timestamp: Date;
15
+ } | null;
16
+ /**
17
+ * Split an ingestion event list into chunks whose serialized request bodies each
18
+ * stay under `maxBytes`, skipping individually oversized events with a warning.
19
+ * Each chunk, when wrapped as `{ batch: chunk }`, matches
20
+ * the measurement exactly because entries are serialized individually and joined
21
+ * with single commas inside the `{"batch":[...]}` envelope.
22
+ */
23
+ export declare function splitIngestionBatch(entries: unknown[], maxBytes: number): unknown[][];
24
+ export declare function getRuntime(): Promise<LangfuseRuntime>;
25
+ /**
26
+ * Release the current session's reference to the Langfuse runtime.
27
+ * Only actually shuts down the runtime when the last session releases it.
28
+ * Accepts an optional sessionId for use outside of withSession (e.g. deferred callbacks).
29
+ */
30
+ export declare function shutdownRuntime(sessionId?: string): Promise<void>;
31
+ /**
32
+ * Force-shutdown the Langfuse runtime regardless of active session references.
33
+ * Used when the user manually reconfigures (e.g. /langfuse-setup) and needs
34
+ * a fresh runtime with new credentials.
35
+ */
36
+ export declare function forceShutdownRuntime(): Promise<void>;
37
+ export declare function __setRuntimeForTest(rt: LangfuseRuntime | null, timeoutMs?: number): void;
38
+ export declare function sendScore(name: string, value: number, options?: {
39
+ traceId?: string;
40
+ observationId?: string;
41
+ }): Promise<void>;
42
+ export {};