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,144 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const DEFAULT_SESSION_ID = "__pi_langfuse_default_session__";
3
+ let activeSessionId = DEFAULT_SESSION_ID;
4
+ const sessionScope = new AsyncLocalStorage();
5
+ function createSessionRunState(instance = Symbol("Pi session")) {
6
+ return {
7
+ instance,
8
+ currentModel: "",
9
+ currentProvider: "",
10
+ agentState: null,
11
+ toolCallCount: 0,
12
+ errorCount: 0,
13
+ turnCount: 0,
14
+ tracingDisabled: false,
15
+ setupAttemptedThisSession: false,
16
+ lastActiveTools: [],
17
+ lineageResolved: false,
18
+ systemStateSequence: 0,
19
+ seenSystemEntryIds: new Set(),
20
+ seenUsageEntryIds: new Set(),
21
+ };
22
+ }
23
+ function normalizeSessionId(sessionId) {
24
+ return sessionId || DEFAULT_SESSION_ID;
25
+ }
26
+ function getActiveSessionId() {
27
+ return sessionScope.getStore() ?? activeSessionId;
28
+ }
29
+ export function getSessionRunState(sessionId = getActiveSessionId()) {
30
+ const normalizedSessionId = normalizeSessionId(sessionId);
31
+ let sessionState = state.sessionStates.get(normalizedSessionId);
32
+ if (!sessionState) {
33
+ sessionState = createSessionRunState();
34
+ state.sessionStates.set(normalizedSessionId, sessionState);
35
+ }
36
+ return sessionState;
37
+ }
38
+ export function setCurrentSession(sessionId) {
39
+ activeSessionId = normalizeSessionId(sessionId);
40
+ getSessionRunState(activeSessionId);
41
+ }
42
+ export function runWithSession(sessionId, fn) {
43
+ const normalizedSessionId = normalizeSessionId(sessionId);
44
+ setCurrentSession(normalizedSessionId);
45
+ return sessionScope.run(normalizedSessionId, fn);
46
+ }
47
+ export const state = {
48
+ config: null,
49
+ sessionStates: new Map(),
50
+ get currentSessionId() {
51
+ const sessionId = getActiveSessionId();
52
+ return sessionId === DEFAULT_SESSION_ID ? "" : sessionId;
53
+ },
54
+ set currentSessionId(sessionId) {
55
+ setCurrentSession(sessionId);
56
+ },
57
+ get currentModel() {
58
+ return getSessionRunState().currentModel;
59
+ },
60
+ set currentModel(model) {
61
+ getSessionRunState().currentModel = model;
62
+ },
63
+ get currentProvider() {
64
+ return getSessionRunState().currentProvider;
65
+ },
66
+ set currentProvider(provider) {
67
+ getSessionRunState().currentProvider = provider;
68
+ },
69
+ get agentState() {
70
+ return getSessionRunState().agentState;
71
+ },
72
+ set agentState(agentState) {
73
+ getSessionRunState().agentState = agentState;
74
+ },
75
+ get toolCallCount() {
76
+ return getSessionRunState().toolCallCount;
77
+ },
78
+ set toolCallCount(toolCallCount) {
79
+ getSessionRunState().toolCallCount = toolCallCount;
80
+ },
81
+ get errorCount() {
82
+ return getSessionRunState().errorCount;
83
+ },
84
+ set errorCount(errorCount) {
85
+ getSessionRunState().errorCount = errorCount;
86
+ },
87
+ get turnCount() {
88
+ return getSessionRunState().turnCount;
89
+ },
90
+ set turnCount(turnCount) {
91
+ getSessionRunState().turnCount = turnCount;
92
+ },
93
+ get isTracingDisabled() {
94
+ return getSessionRunState().tracingDisabled;
95
+ },
96
+ set isTracingDisabled(disabled) {
97
+ getSessionRunState().tracingDisabled = disabled;
98
+ },
99
+ get setupAttemptedThisSession() {
100
+ return getSessionRunState().setupAttemptedThisSession;
101
+ },
102
+ set setupAttemptedThisSession(attempted) {
103
+ getSessionRunState().setupAttemptedThisSession = attempted;
104
+ },
105
+ };
106
+ export function resetRunState(sessionId = getActiveSessionId()) {
107
+ const normalizedSessionId = normalizeSessionId(sessionId);
108
+ const previous = state.sessionStates.get(normalizedSessionId);
109
+ state.sessionStates.set(normalizedSessionId, {
110
+ ...createSessionRunState(previous?.instance),
111
+ startupBinding: previous?.startupBinding,
112
+ workflowWarnings: previous?.workflowWarnings,
113
+ setupAttemptedThisSession: previous?.setupAttemptedThisSession ?? false,
114
+ lastPromptStateHash: previous?.lastPromptStateHash,
115
+ lastToolStateHash: previous?.lastToolStateHash,
116
+ lastActiveTools: previous?.lastActiveTools ?? [],
117
+ parentSessionId: previous?.parentSessionId,
118
+ sessionKind: previous?.sessionKind,
119
+ lineageResolved: previous?.lineageResolved ?? false,
120
+ systemStateSequence: previous?.systemStateSequence ?? 0,
121
+ seenSystemEntryIds: previous?.seenSystemEntryIds ?? new Set(),
122
+ seenUsageEntryIds: previous?.seenUsageEntryIds ?? new Set(),
123
+ });
124
+ }
125
+ export function clearAllSessionStates() {
126
+ state.sessionStates.clear();
127
+ activeSessionId = DEFAULT_SESSION_ID;
128
+ getSessionRunState();
129
+ }
130
+ export function computeEvaluationScores(sessionId = getActiveSessionId()) {
131
+ const sessionState = getSessionRunState(sessionId);
132
+ const toolSuccessRate = sessionState.toolCallCount > 0
133
+ ? (sessionState.toolCallCount - sessionState.errorCount) / sessionState.toolCallCount
134
+ : 1;
135
+ const sessionHadErrors = sessionState.errorCount > 0;
136
+ return {
137
+ tool_call_count: sessionState.toolCallCount,
138
+ turn_count: sessionState.turnCount,
139
+ total_tool_errors: sessionState.errorCount,
140
+ tool_success_rate: toolSuccessRate,
141
+ session_had_errors: sessionHadErrors ? 1 : 0,
142
+ };
143
+ }
144
+ getSessionRunState();
@@ -0,0 +1,157 @@
1
+ import type { CapturePolicy } from "./capture-policy.js";
2
+ import type { PayloadLimits } from "./limits.js";
3
+ import type { UsageOptions } from "./usage-options.js";
4
+ export interface Config {
5
+ publicKey: string;
6
+ secretKey: string;
7
+ host: string;
8
+ userId?: string;
9
+ capturePolicy?: CapturePolicy;
10
+ limits?: PayloadLimits;
11
+ usage?: UsageOptions;
12
+ }
13
+ export interface LangfuseObservation {
14
+ id?: string;
15
+ traceId?: string;
16
+ update(body?: ObservationUpdate): LangfuseObservation;
17
+ end(body?: ObservationUpdate): void;
18
+ startObservation?(name: string, body?: ObservationUpdate, options?: {
19
+ asType?: "agent" | "event" | "generation" | "tool" | "span";
20
+ }): LangfuseObservation;
21
+ setTraceIO?(body?: {
22
+ input?: unknown;
23
+ output?: unknown;
24
+ }): void;
25
+ }
26
+ export interface ObservationUpdate {
27
+ input?: unknown;
28
+ output?: unknown;
29
+ metadata?: Record<string, unknown>;
30
+ model?: string;
31
+ modelParameters?: Record<string, string | number>;
32
+ usageDetails?: Record<string, number>;
33
+ usage?: Record<string, number>;
34
+ costDetails?: Record<string, number>;
35
+ level?: "DEBUG" | "DEFAULT" | "WARNING" | "ERROR";
36
+ statusMessage?: string;
37
+ completionStartTime?: Date;
38
+ }
39
+ export interface LangfuseScoreClient {
40
+ api?: {
41
+ trace?: {
42
+ get?: (traceId: string) => Promise<unknown>;
43
+ };
44
+ ingestion?: {
45
+ batch?: (request: unknown) => Promise<unknown>;
46
+ };
47
+ };
48
+ score?: {
49
+ create(body: {
50
+ traceId?: string;
51
+ sessionId?: string;
52
+ observationId?: string;
53
+ name: string;
54
+ value: number;
55
+ dataType?: "NUMERIC" | "BOOLEAN";
56
+ }): unknown;
57
+ };
58
+ flush?: () => Promise<void>;
59
+ shutdown?: () => Promise<void>;
60
+ }
61
+ export interface PendingScore {
62
+ id?: string;
63
+ traceId?: string;
64
+ sessionId?: string;
65
+ observationId?: string;
66
+ name: string;
67
+ value: number;
68
+ dataType?: "NUMERIC" | "BOOLEAN";
69
+ environment?: string;
70
+ }
71
+ export interface LangfuseRuntimeConfig {
72
+ publicKey: string;
73
+ secretKey: string;
74
+ host: string;
75
+ }
76
+ export interface LangfuseRuntime {
77
+ startObservation: (name: string, body?: ObservationUpdate, options?: {
78
+ asType?: "agent" | "event" | "generation" | "tool" | "span";
79
+ parentSpanContext?: import("@opentelemetry/api").SpanContext;
80
+ }) => LangfuseObservation;
81
+ propagateAttributes: (params: {
82
+ sessionId?: string;
83
+ userId?: string;
84
+ traceName?: string;
85
+ version?: string;
86
+ metadata?: Record<string, string>;
87
+ tags?: string[];
88
+ }, fn: () => LangfuseObservation) => LangfuseObservation;
89
+ /**
90
+ * Runs `fn` on the OTel root context, so the observations it creates take
91
+ * their propagated attributes only from what is passed explicitly and not
92
+ * from whatever the caller's ambient context happens to carry.
93
+ */
94
+ withRootContext?: <T>(fn: () => T) => T;
95
+ scoreClient: LangfuseScoreClient;
96
+ spanProcessor?: {
97
+ forceFlush?: () => Promise<void>;
98
+ shutdown?: () => Promise<void>;
99
+ };
100
+ tracerProvider?: {
101
+ forceFlush?: () => Promise<void>;
102
+ shutdown?: () => Promise<void>;
103
+ };
104
+ clearTracerProvider?: () => void;
105
+ restFallback?: unknown;
106
+ pendingScores?: PendingScore[];
107
+ scoreFlushAt?: number;
108
+ scoreFlushIntervalMs?: number;
109
+ scoreRequestTimeoutMs?: number;
110
+ scoreFlushTimer?: NodeJS.Timeout;
111
+ scoreFlushPromise?: Promise<void>;
112
+ scoreFlushController?: AbortController;
113
+ scoreFlushStopped?: boolean;
114
+ runtimeConfig?: LangfuseRuntimeConfig;
115
+ }
116
+ export interface GenerationState {
117
+ observation: LangfuseObservation;
118
+ requestKey: string;
119
+ ended: boolean;
120
+ errorStatus?: Pick<ObservationUpdate, "level" | "statusMessage">;
121
+ metadata: Record<string, unknown>;
122
+ modelParameters?: Record<string, string | number>;
123
+ ttftRecorded?: boolean;
124
+ }
125
+ export interface ToolState {
126
+ observation: LangfuseObservation;
127
+ toolName: string;
128
+ ended: boolean;
129
+ startedAt: number;
130
+ inputBytes: number;
131
+ parentToolCallId?: string;
132
+ }
133
+ export interface AgentState {
134
+ root?: LangfuseObservation;
135
+ activeAttempt?: LangfuseObservation;
136
+ activeTurn?: LangfuseObservation;
137
+ traceId?: string;
138
+ promptInput?: unknown;
139
+ cwd?: string;
140
+ generationSeq: number;
141
+ activeGenerations: Map<string, GenerationState>;
142
+ generationOrder: string[];
143
+ activeTools: Map<string, ToolState>;
144
+ latestAssistantOutput?: unknown;
145
+ sourceMetadata?: Record<string, unknown>;
146
+ providerMetadataByRequest: Map<string, Record<string, unknown>>;
147
+ attemptCount: number;
148
+ lastAgentEndEvent?: Record<string, unknown>;
149
+ promptStateHash?: string;
150
+ toolStateHash?: string;
151
+ systemStateSequence?: number;
152
+ activeToolCount?: number;
153
+ systemStateChangeCount: number;
154
+ cacheReadTokens: number;
155
+ cacheWriteTokens: number;
156
+ uncachedInputTokens: number;
157
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ import { type EnvLike } from "./capture-policy.js";
2
+ /**
3
+ * Switches that change how token usage is reported to Langfuse. Resolved once
4
+ * from the environment (and the persisted `capture` block, which is merged
5
+ * into it) when config loads; consumers read the resolved values through
6
+ * `getUsageOptions()`.
7
+ */
8
+ export interface UsageOptions {
9
+ /**
10
+ * Report reasoning tokens as `output_reasoning_tokens` and narrow `output`
11
+ * to the non-reasoning remainder. Off by default because Langfuse prices
12
+ * usage by exact key and a custom model definition priced on `output`
13
+ * alone would cost the reasoning share at zero once it moved to its own key.
14
+ */
15
+ readonly splitReasoningTokens: boolean;
16
+ }
17
+ export declare const DEFAULT_USAGE_OPTIONS: UsageOptions;
18
+ /**
19
+ * Resolve usage options from the environment. Namespaced `PI_LANGFUSE_*` like
20
+ * the payload limits: this is extension behaviour, not a Langfuse server knob.
21
+ */
22
+ export declare function createUsageOptions(env?: EnvLike): UsageOptions;
23
+ /**
24
+ * Resolved usage options for the current session: the config-loaded values
25
+ * when a config is active, otherwise a fresh resolve from the environment.
26
+ */
27
+ export declare function getUsageOptions(): UsageOptions;
@@ -0,0 +1,21 @@
1
+ import { parseFlag } from "./capture-policy.js";
2
+ import { state } from "./state.js";
3
+ export const DEFAULT_USAGE_OPTIONS = {
4
+ splitReasoningTokens: false,
5
+ };
6
+ /**
7
+ * Resolve usage options from the environment. Namespaced `PI_LANGFUSE_*` like
8
+ * the payload limits: this is extension behaviour, not a Langfuse server knob.
9
+ */
10
+ export function createUsageOptions(env = process.env) {
11
+ return {
12
+ splitReasoningTokens: parseFlag(env.PI_LANGFUSE_SPLIT_REASONING_TOKENS) ?? DEFAULT_USAGE_OPTIONS.splitReasoningTokens,
13
+ };
14
+ }
15
+ /**
16
+ * Resolved usage options for the current session: the config-loaded values
17
+ * when a config is active, otherwise a fresh resolve from the environment.
18
+ */
19
+ export function getUsageOptions() {
20
+ return state.config?.usage ?? createUsageOptions();
21
+ }
@@ -0,0 +1,61 @@
1
+ import { getLimits } from "./limits.js";
2
+ import { type UsageOptions } from "./usage-options.js";
3
+ import { type CapturePolicy } from "./capture-policy.js";
4
+ import type { ObservationUpdate } from "./types.js";
5
+ export declare function getCapturePolicy(): CapturePolicy;
6
+ export { getLimits };
7
+ export declare function truncate(value: string, maxLength?: number): string;
8
+ export declare function tryParseJson(value: string): unknown;
9
+ export declare function shapePayload(value: unknown, options?: {
10
+ maxString?: number;
11
+ depth?: number;
12
+ maxNodes?: number;
13
+ maxArrayItems?: number;
14
+ maxObjectKeys?: number;
15
+ redact?: boolean;
16
+ parseJson?: boolean;
17
+ parseJsonPrefix?: boolean;
18
+ }): unknown;
19
+ export declare function safeSerialize(value: unknown, maxLength?: number): string;
20
+ export declare function estimatePayloadBytes(value: unknown, maxLength?: number): number;
21
+ export declare function extractTextContent(content: unknown, maxLength?: number, depth?: number): string | undefined;
22
+ /**
23
+ * Human-readable text for an observation `statusMessage`: text blocks first, then
24
+ * the string, then JSON, so a structured error never lands as "[object Object]"
25
+ * or as a wall of escaped JSON. Shape and redact before extracting any text.
26
+ */
27
+ export declare function toStatusMessage(value: unknown, maxLength?: number): string;
28
+ export declare function normalizeContentForLangfuse(content: unknown, api?: string): unknown;
29
+ export declare function extractToolCalls(message: Record<string, unknown>): unknown | undefined;
30
+ export declare function extractAssistantOutput(message: unknown): unknown | undefined;
31
+ export declare function extractFinalAssistant(messages: unknown): Record<string, unknown> | undefined;
32
+ export declare function getRequestKey(event: Record<string, unknown>, fallback: string): string;
33
+ export declare function getToolCallId(event: Record<string, unknown>): string | undefined;
34
+ export declare function getToolName(event: Record<string, unknown>): string;
35
+ export declare function getToolInput(event: Record<string, unknown>): unknown;
36
+ export declare function getProviderPayload(event: Record<string, unknown>): unknown;
37
+ export type ToolUpdateTransport = "anthropic-native" | "openai-additional-tools" | "openai-tool-search" | "mid-conversation-system" | "collapsed-leading-system";
38
+ /** Classify the provider payload observed by this hook rather than guessing from the model name alone. */
39
+ export declare function inferToolUpdateTransport(payload: unknown, hasPriorSystemState: boolean): ToolUpdateTransport | undefined;
40
+ export declare function extractModelParameters(payload: unknown): Record<string, string | number> | undefined;
41
+ export declare function extractGenerationStatus(message: Record<string, unknown>): ObservationUpdate;
42
+ export declare function getMessageFromEvent(event: Record<string, unknown>): Record<string, unknown> | undefined;
43
+ export declare function extractUsage(messageOrEvent: Record<string, unknown>, options?: UsageOptions): Record<string, number> | undefined;
44
+ export declare function extractCacheMetrics(messageOrEvent: Record<string, unknown>): {
45
+ cacheReadTokens: number;
46
+ cacheWriteTokens: number;
47
+ uncachedInputTokens: number;
48
+ cacheHitRatio?: number;
49
+ } | undefined;
50
+ export declare function extractCostDetails(messageOrEvent: Record<string, unknown>): Record<string, number> | undefined;
51
+ /** Accept both provider model ids and Pi Model objects without serializing the whole model. */
52
+ export declare function extractModelIdentity(value: unknown, provider?: unknown): {
53
+ model?: string;
54
+ provider?: string;
55
+ };
56
+ /** Tool hooks report own usage; transcript toolResult messages also include descendants' usage. */
57
+ export declare function extractToolUsage(event: Record<string, unknown>): {
58
+ usageDetails?: Record<string, number>;
59
+ costDetails?: Record<string, number>;
60
+ };
61
+ export declare function extractResponseMetadata(event: Record<string, unknown>): Record<string, unknown>;