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,249 @@
1
+ import { state } from "../state.js";
2
+ import { getRuntime } from "../langfuse.js";
3
+ import { startChildObservation } from "../observation.js";
4
+ import { getRequestKey, getProviderPayload, shapePayload, extractResponseMetadata, getMessageFromEvent, extractAssistantOutput, extractUsage, extractCostDetails, getCapturePolicy, extractModelParameters, extractCacheMetrics, inferToolUpdateTransport, extractModelIdentity, extractGenerationStatus, toStatusMessage, } from "../utils.js";
5
+ import { applyCapturePolicy } from "../capture-policy.js";
6
+ export function getOpenGeneration() {
7
+ if (state.isTracingDisabled || !state.agentState) {
8
+ return undefined;
9
+ }
10
+ for (let i = state.agentState.generationOrder.length - 1; i >= 0; i--) {
11
+ const key = state.agentState.generationOrder[i];
12
+ const genState = state.agentState.activeGenerations.get(key);
13
+ if (genState && !genState.ended) {
14
+ return genState;
15
+ }
16
+ }
17
+ return undefined;
18
+ }
19
+ export async function startGeneration(event, selectedModel) {
20
+ if (state.isTracingDisabled || !state.agentState?.root) {
21
+ return;
22
+ }
23
+ try {
24
+ const key = getRequestKey(event, `generation-${++state.agentState.generationSeq}`);
25
+ const payload = getProviderPayload(event);
26
+ const modelParameters = extractModelParameters(payload);
27
+ const selected = extractModelIdentity(selectedModel ?? state.currentModel, selectedModel ? undefined : state.currentProvider);
28
+ const payloadModel = payload && typeof payload === "object" ? payload.model : undefined;
29
+ const actual = extractModelIdentity(event.model ?? event.modelId ?? payloadModel, event.provider);
30
+ const toolUpdateTransport = inferToolUpdateTransport(payload, (state.agentState.systemStateSequence ?? 0) > 1);
31
+ const metadata = shapePayload({
32
+ provider: actual.provider ?? selected.provider,
33
+ selectedModel: selected.model,
34
+ selectedProvider: selected.provider,
35
+ actualModel: actual.model,
36
+ actualProvider: actual.provider,
37
+ requestId: key,
38
+ url: event.url,
39
+ method: event.method,
40
+ promptStateHash: state.agentState.promptStateHash,
41
+ toolStateHash: state.agentState.toolStateHash,
42
+ systemStateSequence: state.agentState.systemStateSequence,
43
+ activeToolCount: state.agentState.activeToolCount,
44
+ toolUpdateTransport,
45
+ cachePreservationExpected: toolUpdateTransport === "anthropic-native" ||
46
+ toolUpdateTransport === "openai-additional-tools" ||
47
+ toolUpdateTransport === "openai-tool-search" ||
48
+ toolUpdateTransport === "mid-conversation-system"
49
+ ? true
50
+ : toolUpdateTransport === "collapsed-leading-system"
51
+ ? false
52
+ : undefined,
53
+ });
54
+ const captured = applyCapturePolicy({
55
+ input: shapePayload(payload),
56
+ metadata,
57
+ }, getCapturePolicy());
58
+ const parent = state.agentState.activeTurn ?? state.agentState.activeAttempt ?? state.agentState.root;
59
+ const generation = await startChildObservation({
60
+ parent,
61
+ runtime: getRuntime,
62
+ name: "llm-generation",
63
+ body: {
64
+ input: captured.input,
65
+ model: actual.model ?? selected.model,
66
+ modelParameters,
67
+ metadata: captured.metadata,
68
+ },
69
+ asType: "generation",
70
+ });
71
+ state.agentState.activeGenerations.set(key, {
72
+ observation: generation,
73
+ requestKey: key,
74
+ ended: false,
75
+ metadata: captured.metadata ?? {},
76
+ modelParameters,
77
+ });
78
+ state.agentState.generationOrder.push(key);
79
+ }
80
+ catch (e) {
81
+ console.warn("📊 Langfuse: Failed to start generation", e);
82
+ }
83
+ }
84
+ export function updateGenerationMetadata(event) {
85
+ if (state.isTracingDisabled || !state.agentState) {
86
+ return;
87
+ }
88
+ const key = getRequestKey(event, "");
89
+ const metadata = applyCapturePolicy({ metadata: extractResponseMetadata(event) }, getCapturePolicy()).metadata ?? {};
90
+ const generation = (key ? state.agentState.activeGenerations.get(key) : undefined) ?? getOpenGeneration();
91
+ if (!generation || generation.ended)
92
+ return;
93
+ generation.metadata = { ...generation.metadata, ...metadata };
94
+ const isError = (typeof metadata.status === "number" && metadata.status >= 400) || event.error || event.isError;
95
+ if (isError) {
96
+ generation.errorStatus = {
97
+ level: "ERROR",
98
+ statusMessage: toStatusMessage(event.error ?? metadata.statusMessage ?? "Provider request failed"),
99
+ };
100
+ }
101
+ // The assistant message supplies final error details and usage; close there.
102
+ generation.observation.update({ metadata: generation.metadata, ...generation.errorStatus });
103
+ }
104
+ export function recordTTFT(event) {
105
+ if (state.isTracingDisabled || !state.agentState) {
106
+ return;
107
+ }
108
+ const key = getRequestKey(event, "");
109
+ const generation = key ? state.agentState.activeGenerations.get(key) : getOpenGeneration();
110
+ if (generation && !generation.ttftRecorded && !generation.ended) {
111
+ generation.ttftRecorded = true;
112
+ try {
113
+ generation.observation.update({ completionStartTime: new Date() });
114
+ }
115
+ catch (e) {
116
+ // Ignore
117
+ }
118
+ }
119
+ }
120
+ /** Routing identity is available before the assistant message, including failed streams. */
121
+ export function recordGenerationIdentity(event) {
122
+ const generation = getOpenGeneration();
123
+ if (!generation)
124
+ return;
125
+ const actual = extractModelIdentity(event.model, event.provider);
126
+ if (!actual.model && !actual.provider)
127
+ return;
128
+ if (generation.metadata.actualModel === actual.model && generation.metadata.actualProvider === actual.provider)
129
+ return;
130
+ generation.metadata = applyCapturePolicy({ metadata: shapePayload({
131
+ ...generation.metadata,
132
+ ...(actual.model ? { actualModel: actual.model } : {}),
133
+ ...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
134
+ }) }, getCapturePolicy()).metadata ?? {};
135
+ generation.observation.update({ model: actual.model, metadata: generation.metadata });
136
+ }
137
+ export async function finishGenerationFromMessage(event) {
138
+ if (state.isTracingDisabled || !state.agentState) {
139
+ return;
140
+ }
141
+ const message = getMessageFromEvent(event);
142
+ if (!message || message.role !== "assistant") {
143
+ return;
144
+ }
145
+ const generation = getOpenGeneration();
146
+ const rawOutput = extractAssistantOutput(message);
147
+ const captured = applyCapturePolicy({ output: rawOutput }, getCapturePolicy());
148
+ const output = captured.output;
149
+ state.agentState.latestAssistantOutput = output;
150
+ if (!generation) {
151
+ return;
152
+ }
153
+ const usageDetails = extractUsage({ ...event, message });
154
+ const costDetails = extractCostDetails({ ...event, message });
155
+ const cacheMetrics = extractCacheMetrics({ ...event, message });
156
+ const modelParameters = extractModelParameters(getProviderPayload(event)) ?? generation.modelParameters;
157
+ const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
158
+ const finishReason = message.finishReason ?? message.stopReason;
159
+ const update = {
160
+ ...(generation.errorStatus && ["stop", "toolUse", "length"].includes(String(finishReason))
161
+ ? { level: "DEFAULT", statusMessage: "" }
162
+ : {}),
163
+ ...extractGenerationStatus(message),
164
+ output,
165
+ model: actual.model ?? generation.metadata.actualModel ?? (state.currentModel || undefined),
166
+ modelParameters,
167
+ usageDetails,
168
+ ...(costDetails ? { costDetails } : {}),
169
+ metadata: {
170
+ ...generation.metadata,
171
+ ...(actual.model ? { actualModel: actual.model } : {}),
172
+ ...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
173
+ finishReason: finishReason ?? event.finishReason,
174
+ ...cacheMetrics,
175
+ },
176
+ };
177
+ update.metadata = applyCapturePolicy({ metadata: update.metadata }, getCapturePolicy()).metadata;
178
+ try {
179
+ generation.observation.update(update).end();
180
+ generation.ended = true;
181
+ if (cacheMetrics) {
182
+ state.agentState.cacheReadTokens = (state.agentState.cacheReadTokens ?? 0) + cacheMetrics.cacheReadTokens;
183
+ state.agentState.cacheWriteTokens = (state.agentState.cacheWriteTokens ?? 0) + cacheMetrics.cacheWriteTokens;
184
+ state.agentState.uncachedInputTokens =
185
+ (state.agentState.uncachedInputTokens ?? 0) + cacheMetrics.uncachedInputTokens;
186
+ }
187
+ }
188
+ catch (e) {
189
+ console.warn("📊 Langfuse: Failed to finish generation", e);
190
+ }
191
+ }
192
+ export async function createFallbackGenerationFromTurn(event, message) {
193
+ if (state.isTracingDisabled || !state.agentState?.root || state.agentState.generationOrder.length > 0) {
194
+ return;
195
+ }
196
+ try {
197
+ const usageDetails = extractUsage({ ...event, message });
198
+ const costDetails = extractCostDetails({ ...event, message });
199
+ const cacheMetrics = extractCacheMetrics({ ...event, message });
200
+ const modelParameters = extractModelParameters(getProviderPayload(event));
201
+ const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
202
+ const captured = applyCapturePolicy({
203
+ input: state.agentState.promptInput,
204
+ output: extractAssistantOutput(message),
205
+ metadata: {
206
+ provider: actual.provider ?? (state.currentProvider || undefined),
207
+ selectedModel: state.currentModel || undefined,
208
+ selectedProvider: state.currentProvider || undefined,
209
+ actualModel: actual.model,
210
+ actualProvider: actual.provider,
211
+ sourceEvent: "turn_end",
212
+ finishReason: message.finishReason ?? message.stopReason ?? event.finishReason,
213
+ promptStateHash: state.agentState.promptStateHash,
214
+ toolStateHash: state.agentState.toolStateHash,
215
+ systemStateSequence: state.agentState.systemStateSequence,
216
+ activeToolCount: state.agentState.activeToolCount,
217
+ ...cacheMetrics,
218
+ },
219
+ }, getCapturePolicy());
220
+ const parent = state.agentState.activeTurn ?? state.agentState.activeAttempt ?? state.agentState.root;
221
+ const generation = await startChildObservation({
222
+ parent,
223
+ runtime: getRuntime,
224
+ name: "llm-generation",
225
+ body: {
226
+ ...extractGenerationStatus(message),
227
+ input: captured.input,
228
+ output: captured.output,
229
+ model: actual.model ?? (state.currentModel || undefined),
230
+ modelParameters,
231
+ usageDetails,
232
+ ...(costDetails ? { costDetails } : {}),
233
+ metadata: captured.metadata,
234
+ },
235
+ asType: "generation",
236
+ });
237
+ generation.end();
238
+ state.agentState.generationOrder.push("turn-end-fallback");
239
+ if (cacheMetrics) {
240
+ state.agentState.cacheReadTokens = (state.agentState.cacheReadTokens ?? 0) + cacheMetrics.cacheReadTokens;
241
+ state.agentState.cacheWriteTokens = (state.agentState.cacheWriteTokens ?? 0) + cacheMetrics.cacheWriteTokens;
242
+ state.agentState.uncachedInputTokens =
243
+ (state.agentState.uncachedInputTokens ?? 0) + cacheMetrics.uncachedInputTokens;
244
+ }
245
+ }
246
+ catch (e) {
247
+ console.warn("📊 Langfuse: Failed to create fallback generation", e);
248
+ }
249
+ }
@@ -0,0 +1,4 @@
1
+ type RecordLike = Record<string, unknown>;
2
+ export declare function recordSessionCompactionFailure(event: RecordLike): Promise<void>;
3
+ export declare function recordSessionCompaction(event: RecordLike): Promise<void>;
4
+ export {};
@@ -0,0 +1,121 @@
1
+ import { applyCapturePolicy } from "../capture-policy.js";
2
+ import { getRuntime } from "../langfuse.js";
3
+ import { startChildObservation, startSessionObservation } from "../observation.js";
4
+ import { state } from "../state.js";
5
+ import { sessionGroupId } from "../workflow.js";
6
+ import { sessionLineageMetadata } from "../session-lineage.js";
7
+ import { extractCostDetails, extractGenerationStatus, extractUsage, getCapturePolicy, shapePayload, } from "../utils.js";
8
+ // Compaction can fire after the run already settled, so the event has no agent
9
+ // root to nest under. A rootless observation still belongs to the session, hence
10
+ // its own trace name instead of being dropped.
11
+ const SESSION_TRACE_NAME = "pi-session";
12
+ function startCompactionObservation(name, body, asType) {
13
+ const agent = state.agentState;
14
+ const parent = agent?.activeTurn ?? agent?.activeAttempt ?? agent?.root;
15
+ if (parent) {
16
+ return startChildObservation({ parent, runtime: getRuntime, name, body, asType });
17
+ }
18
+ return startSessionObservation({
19
+ runtime: getRuntime,
20
+ name,
21
+ body,
22
+ asType,
23
+ attributes: {
24
+ sessionId: sessionGroupId(),
25
+ userId: state.config?.userId,
26
+ traceName: SESSION_TRACE_NAME,
27
+ metadata: { piScope: "session", ...sessionLineageMetadata() },
28
+ },
29
+ });
30
+ }
31
+ export async function recordSessionCompactionFailure(event) {
32
+ if (state.isTracingDisabled)
33
+ return;
34
+ try {
35
+ const observation = await startCompactionObservation("session-compaction-failed", {
36
+ ...extractGenerationStatus({
37
+ stopReason: event.aborted ? "aborted" : "error",
38
+ errorMessage: event.errorMessage
39
+ || (event.aborted ? "Compaction cancelled" : "Compaction failed"),
40
+ }),
41
+ metadata: shapePayload({
42
+ reason: event.reason,
43
+ aborted: event.aborted,
44
+ willRetry: event.willRetry,
45
+ fromExtension: event.fromExtension,
46
+ }),
47
+ }, "event");
48
+ observation.end();
49
+ }
50
+ catch (error) {
51
+ console.warn("📊 Langfuse: Failed to record compaction failure", error);
52
+ }
53
+ }
54
+ function namesFromTools(value) {
55
+ if (!Array.isArray(value))
56
+ return [];
57
+ return value.flatMap((tool) => {
58
+ if (typeof tool === "string")
59
+ return [tool];
60
+ if (!tool || typeof tool !== "object")
61
+ return [];
62
+ const name = tool.name;
63
+ return typeof name === "string" ? [name] : [];
64
+ });
65
+ }
66
+ export async function recordSessionCompaction(event) {
67
+ if (state.isTracingDisabled)
68
+ return;
69
+ const agent = state.agentState;
70
+ const entry = event.compactionEntry && typeof event.compactionEntry === "object"
71
+ ? event.compactionEntry
72
+ : {};
73
+ const checkpoint = entry.systemMessage && typeof entry.systemMessage === "object"
74
+ ? entry.systemMessage
75
+ : undefined;
76
+ const checkpointTools = namesFromTools(checkpoint?.toolsAdded);
77
+ const checkpointSections = checkpoint?.sections && typeof checkpoint.sections === "object"
78
+ ? Object.keys(checkpoint.sections)
79
+ : [];
80
+ const captured = applyCapturePolicy({
81
+ input: shapePayload({ summary: entry.summary }),
82
+ metadata: {
83
+ reason: event.reason,
84
+ willRetry: event.willRetry,
85
+ fromExtension: event.fromExtension,
86
+ compactionEntryId: entry.id,
87
+ firstKeptEntryId: entry.firstKeptEntryId,
88
+ tokensBefore: entry.tokensBefore,
89
+ checkpointSectionNames: checkpointSections,
90
+ checkpointToolNames: checkpointTools,
91
+ checkpointToolCount: checkpointTools.length,
92
+ promptStateHash: agent?.promptStateHash,
93
+ toolStateHash: agent?.toolStateHash,
94
+ },
95
+ }, getCapturePolicy());
96
+ try {
97
+ const compaction = await startCompactionObservation("session-compaction", { input: captured.input, metadata: captured.metadata }, "span");
98
+ if (entry.usage && typeof entry.usage === "object") {
99
+ const summary = applyCapturePolicy({ output: entry.summary }, getCapturePolicy());
100
+ const costDetails = extractCostDetails({ usage: entry.usage });
101
+ const generation = await startChildObservation({
102
+ parent: compaction,
103
+ runtime: getRuntime,
104
+ name: "compaction-summary",
105
+ body: {
106
+ output: summary.output,
107
+ model: state.currentModel || undefined,
108
+ usageDetails: extractUsage({ usage: entry.usage }),
109
+ ...(costDetails ? { costDetails } : {}),
110
+ metadata: { provider: state.currentProvider || undefined },
111
+ },
112
+ asType: "generation",
113
+ });
114
+ generation.end();
115
+ }
116
+ compaction.end();
117
+ }
118
+ catch (error) {
119
+ console.warn("📊 Langfuse: Failed to record session compaction", error);
120
+ }
121
+ }
@@ -0,0 +1,3 @@
1
+ /** Mark restored transcript state as already seen so the first trace emits one snapshot, not the full history. */
2
+ export declare function initializeSystemStateTracking(ctx: any): void;
3
+ export declare function recordSystemState(ctx: any, activeTools: string[], emitUnchanged?: boolean): Promise<void>;
@@ -0,0 +1,185 @@
1
+ import { createHash } from "node:crypto";
2
+ import { applyCapturePolicy } from "../capture-policy.js";
3
+ import { getRuntime } from "../langfuse.js";
4
+ import { startChildObservation } from "../observation.js";
5
+ import { getSessionRunState, state } from "../state.js";
6
+ import { getCapturePolicy, shapePayload } from "../utils.js";
7
+ function fingerprint(value) {
8
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
9
+ }
10
+ function toolName(tool) {
11
+ if (typeof tool === "string")
12
+ return tool;
13
+ if (!tool || typeof tool !== "object")
14
+ return undefined;
15
+ const name = tool.name;
16
+ return typeof name === "string" && name ? name : undefined;
17
+ }
18
+ function sortedUnique(values) {
19
+ return [...new Set(values)].sort();
20
+ }
21
+ function readNewSystemMessages(ctx) {
22
+ const session = getSessionRunState();
23
+ let branch;
24
+ try {
25
+ branch = ctx?.sessionManager?.getBranch?.();
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ if (!Array.isArray(branch))
31
+ return [];
32
+ const messages = [];
33
+ for (const rawEntry of branch) {
34
+ if (!rawEntry || typeof rawEntry !== "object")
35
+ continue;
36
+ const entry = rawEntry;
37
+ const message = entry.message;
38
+ if (entry.type !== "message" || !message || typeof message !== "object")
39
+ continue;
40
+ if (message.role !== "system")
41
+ continue;
42
+ const entryId = typeof entry.id === "string" ? entry.id : "";
43
+ if (!entryId || session.seenSystemEntryIds.has(entryId))
44
+ continue;
45
+ session.seenSystemEntryIds.add(entryId);
46
+ messages.push({ entryId, message: message });
47
+ }
48
+ return messages;
49
+ }
50
+ /** Mark restored transcript state as already seen so the first trace emits one snapshot, not the full history. */
51
+ export function initializeSystemStateTracking(ctx) {
52
+ const session = getSessionRunState();
53
+ try {
54
+ const branch = ctx?.sessionManager?.getBranch?.();
55
+ if (!Array.isArray(branch))
56
+ return;
57
+ for (const rawEntry of branch) {
58
+ if (!rawEntry || typeof rawEntry !== "object")
59
+ continue;
60
+ const entry = rawEntry;
61
+ const message = entry.message;
62
+ if (entry.type === "message" &&
63
+ typeof entry.id === "string" &&
64
+ message &&
65
+ typeof message === "object" &&
66
+ message.role === "system") {
67
+ session.seenSystemEntryIds.add(entry.id);
68
+ }
69
+ }
70
+ }
71
+ catch {
72
+ // Session history is optional in SDK/headless hosts.
73
+ }
74
+ }
75
+ export async function recordSystemState(ctx, activeTools, emitUnchanged = true) {
76
+ const agent = state.agentState;
77
+ if (state.isTracingDisabled || !agent?.root)
78
+ return;
79
+ let prompt = "";
80
+ try {
81
+ prompt = String((await ctx?.getSystemPrompt?.()) ?? "");
82
+ }
83
+ catch {
84
+ // The tool state is still useful when a host cannot expose the rendered prompt.
85
+ }
86
+ const tools = sortedUnique(activeTools);
87
+ const promptStateHash = prompt ? fingerprint(prompt) : undefined;
88
+ const toolStateHash = fingerprint(JSON.stringify(tools));
89
+ const session = getSessionRunState();
90
+ const systemMessages = readNewSystemMessages(ctx);
91
+ const transcriptToolsAdded = [];
92
+ const transcriptToolsRemoved = [];
93
+ const sectionsChanged = new Set();
94
+ const sectionsRemoved = new Set();
95
+ const entryIds = [];
96
+ for (const { entryId, message } of systemMessages) {
97
+ entryIds.push(entryId);
98
+ const sections = message.sections;
99
+ if (sections && typeof sections === "object" && !Array.isArray(sections)) {
100
+ for (const [name, value] of Object.entries(sections)) {
101
+ (value === null ? sectionsRemoved : sectionsChanged).add(name);
102
+ }
103
+ }
104
+ if (Array.isArray(message.toolsAdded)) {
105
+ for (const tool of message.toolsAdded) {
106
+ const name = toolName(tool);
107
+ if (name)
108
+ transcriptToolsAdded.push(name);
109
+ }
110
+ }
111
+ if (Array.isArray(message.toolsRemoved)) {
112
+ for (const tool of message.toolsRemoved) {
113
+ const name = toolName(tool);
114
+ if (name)
115
+ transcriptToolsRemoved.push(name);
116
+ }
117
+ }
118
+ }
119
+ const previousTools = new Set(session.lastActiveTools);
120
+ const currentTools = new Set(tools);
121
+ const toolsAdded = sortedUnique([
122
+ ...tools.filter((name) => !previousTools.has(name)),
123
+ ...transcriptToolsAdded,
124
+ ]);
125
+ const toolsRemoved = sortedUnique([
126
+ ...session.lastActiveTools.filter((name) => !currentTools.has(name)),
127
+ ...transcriptToolsRemoved,
128
+ ]);
129
+ const promptChanged = session.lastPromptStateHash !== promptStateHash;
130
+ const toolsChanged = session.lastToolStateHash !== toolStateHash;
131
+ const isInitial = session.lastPromptStateHash === undefined && session.lastToolStateHash === undefined;
132
+ const changed = isInitial || promptChanged || toolsChanged || systemMessages.length > 0;
133
+ if (changed)
134
+ session.systemStateSequence++;
135
+ // agent_start emits a snapshot; unchanged request hooks keep the existing reference.
136
+ if (!changed && !emitUnchanged && agent.systemStateSequence !== undefined)
137
+ return;
138
+ const capturePolicy = getCapturePolicy();
139
+ const rawSystemUpdate = systemMessages.length > 0
140
+ ? systemMessages.map(({ entryId, message }) => ({ entryId, ...message }))
141
+ : { role: "system", content: prompt };
142
+ const captured = applyCapturePolicy({
143
+ systemPrompt: shapePayload(rawSystemUpdate),
144
+ metadata: {
145
+ stateSequence: session.systemStateSequence,
146
+ changeKind: isInitial ? "initial" : changed ? "updated" : "unchanged",
147
+ source: systemMessages.length > 0 ? "transcript" : "effective-snapshot",
148
+ transcriptEntryIds: entryIds,
149
+ promptStateHash,
150
+ toolStateHash,
151
+ promptChars: prompt.length,
152
+ activeToolCount: tools.length,
153
+ activeTools: tools,
154
+ toolsAdded,
155
+ toolsRemoved,
156
+ sectionsChanged: sortedUnique(sectionsChanged),
157
+ sectionsRemoved: sortedUnique(sectionsRemoved),
158
+ },
159
+ }, capturePolicy);
160
+ try {
161
+ const observation = await startChildObservation({
162
+ parent: agent.activeAttempt ?? agent.root,
163
+ runtime: getRuntime,
164
+ name: "system-state",
165
+ body: {
166
+ input: captured.systemPrompt,
167
+ metadata: captured.metadata,
168
+ },
169
+ asType: "event",
170
+ });
171
+ observation.end();
172
+ }
173
+ catch (error) {
174
+ console.warn("📊 Langfuse: Failed to record system state", error);
175
+ }
176
+ if (changed)
177
+ agent.systemStateChangeCount = (agent.systemStateChangeCount ?? 0) + 1;
178
+ agent.promptStateHash = promptStateHash;
179
+ agent.toolStateHash = toolStateHash;
180
+ agent.systemStateSequence = session.systemStateSequence;
181
+ agent.activeToolCount = tools.length;
182
+ session.lastPromptStateHash = promptStateHash;
183
+ session.lastToolStateHash = toolStateHash;
184
+ session.lastActiveTools = tools;
185
+ }
@@ -0,0 +1,3 @@
1
+ export declare function startToolObservation(event: Record<string, unknown>): Promise<void>;
2
+ export declare function finishToolObservation(event: Record<string, unknown>): Promise<void>;
3
+ export declare function closeDanglingObservations(statusMessage: string): void;