pi-langfuse 1.7.0 → 1.7.1
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.
- package/README.md +68 -2
- package/README_CN.md +43 -1
- package/index.ts +7 -1
- package/package.json +5 -2
- package/src/commands.ts +34 -2
- package/src/handlers/agent.ts +4 -2
- package/src/handlers/cache.ts +4 -2
- package/src/handlers/generation.ts +21 -43
- package/src/handlers/session.ts +71 -13
- package/src/handlers/tool.ts +6 -7
- package/src/langfuse.ts +76 -65
- package/src/observation.ts +27 -0
- package/src/redaction.ts +145 -10
- package/src/session-lineage.ts +98 -0
- package/src/state.ts +7 -0
- package/src/types.ts +1 -0
- package/src/utils.ts +95 -19
package/README.md
CHANGED
|
@@ -11,7 +11,8 @@ Langfuse observability extension for [Pi Coding Agent](https://github.com/earend
|
|
|
11
11
|
|
|
12
12
|
- One Langfuse trace per user prompt, grouped by Pi session.
|
|
13
13
|
- Root `agent`, per-request `generation`, and per-tool `tool` observations.
|
|
14
|
-
-
|
|
14
|
+
- Foreground child sessions keep their SDK exporters isolated, so parent telemetry continues after a child exits.
|
|
15
|
+
- Final assistant output capture, generation/tool error visibility, and trace-level scores.
|
|
15
16
|
- Privacy controls for inputs, outputs, tool I/O, system prompt, and cwd.
|
|
16
17
|
- Secret redaction and local path hashing before upload.
|
|
17
18
|
- Capability-gated REST fallback for self-hosted Langfuse setups that expose the legacy trace API when OTel spans arrive but traces do not materialize. Langfuse v4 `events_only` deployments use OTel without legacy fallback ingestion.
|
|
@@ -165,6 +166,28 @@ defaults shown above. To capture a very large system prompt or big tool
|
|
|
165
166
|
payloads in full, raise or disable the relevant limit (e.g.
|
|
166
167
|
`PI_LANGFUSE_MAX_STRING_LENGTH=off`).
|
|
167
168
|
|
|
169
|
+
JSON strings above the string limit are replaced with `[payload too large]` rather
|
|
170
|
+
than cut into invalid JSON that could bypass sensitive-field redaction. Error
|
|
171
|
+
status text uses the same shaping and redaction limits, even when IO capture is disabled.
|
|
172
|
+
Status formatting also masks JSON credentials after Pi/provider error prefixes.
|
|
173
|
+
If surrounding diagnostics make structured error text unparseable, status and
|
|
174
|
+
captured tool-error output use `[unparseable error payload]` instead of the raw text.
|
|
175
|
+
The same protection applies to unparseable JSON fragments with sensitive field
|
|
176
|
+
names replayed inside later provider requests; ordinary surrounding text is retained
|
|
177
|
+
when it contains no sensitive JSON fields.
|
|
178
|
+
String-only capture paths (including assistant replies, compaction summaries, and
|
|
179
|
+
custom IDs) replace text containing unmasked sensitive JSON fields with
|
|
180
|
+
`[REDACTED_SECRET]`. Already-masked fields and ordinary text stay intact; captured
|
|
181
|
+
output remains a string.
|
|
182
|
+
This check also decodes nested JSON strings within the existing depth/node limits.
|
|
183
|
+
Ambiguous escaped text or exhausted inspection limits hide the string rather than expose unchecked content.
|
|
184
|
+
Credential assignments are masked with or without quotes, including escaped or
|
|
185
|
+
unterminated values. Escaped quotes in serialized text protect the entire value,
|
|
186
|
+
including spaces.
|
|
187
|
+
Ambiguous single-quote escaping can also mask the remaining diagnostic text.
|
|
188
|
+
Known tokens are masked before string truncation so a token
|
|
189
|
+
crossing a capture limit cannot escape detection as a shorter fragment.
|
|
190
|
+
|
|
168
191
|
The REST fallback ingestion is chunked so each request body stays well below
|
|
169
192
|
the Langfuse gateway's payload limit (~4.5MB). These knobs control the chunk
|
|
170
193
|
budget and a hard ceiling for the whole fallback payload:
|
|
@@ -177,6 +200,13 @@ export PI_LANGFUSE_MAX_FALLBACK_TOTAL_BYTES=33554432 # whole-payload ceiling, d
|
|
|
177
200
|
|
|
178
201
|
When the accumulated fallback payload exceeds the 32MB ceiling, ingestion is
|
|
179
202
|
skipped with a warning instead of attempting an unrecoverably large upload.
|
|
203
|
+
An individual event above the per-request budget is skipped with a size-only
|
|
204
|
+
warning; the remaining events are still sent. Raise capture limits with this
|
|
205
|
+
per-event ceiling in mind.
|
|
206
|
+
Fallback checks each trace separately within one visibility window and restores
|
|
207
|
+
only missing traces, preserving each trace's session, user, name, and metadata.
|
|
208
|
+
Visibility polling uses at most three quarters of the remaining shutdown time,
|
|
209
|
+
leaving the rest for ingestion even when SDK cleanup was slow.
|
|
180
210
|
|
|
181
211
|
### Reasoning tokens
|
|
182
212
|
|
|
@@ -266,6 +296,10 @@ To verify the Langfuse host and API keys from inside Pi, run:
|
|
|
266
296
|
```
|
|
267
297
|
|
|
268
298
|
This command makes a timeout-bounded authenticated request to Langfuse and, if it succeeds, sends a small test trace.
|
|
299
|
+
The result also probes the observations read API. It tries `v2/observations` first and falls back to the legacy
|
|
300
|
+
observations API only when v2 returns 404 or 405, so older servers remain supported. Read failures produce a
|
|
301
|
+
warning and do not block the test trace. This checks endpoint availability, not whether the new trace is queryable.
|
|
302
|
+
Langfuse v4 in `events_only` mode removes legacy reads; the compaction and error-text fixes do not require v4.
|
|
269
303
|
|
|
270
304
|
## What Appears in Langfuse
|
|
271
305
|
|
|
@@ -278,6 +312,9 @@ This command makes a timeout-bounded authenticated request to Langfuse and, if i
|
|
|
278
312
|
include descendants are not ingested again. Pi's tool usage does not identify each nested model,
|
|
279
313
|
so these aggregate generations have no inferred model name or price.
|
|
280
314
|
- LLM requests appear as generation observations, including usage and cost when the provider exposes them.
|
|
315
|
+
Failed assistant messages are marked `ERROR` with a redacted `statusMessage`, including streaming
|
|
316
|
+
failures after HTTP 200 and failures without provider hooks. User-aborted generations are `WARNING`.
|
|
317
|
+
A successful final assistant response clears an earlier transient HTTP error from an internal retry.
|
|
281
318
|
Reasoning tokens are reported as their own usage bucket when `PI_LANGFUSE_SPLIT_REASONING_TOKENS` is enabled.
|
|
282
319
|
Virtual routing preserves `selectedModel`/`selectedProvider` alongside `actualModel`/`actualProvider`;
|
|
283
320
|
the generation model and `provider` metadata use the actual identity when available.
|
|
@@ -289,7 +326,12 @@ This command makes a timeout-bounded authenticated request to Langfuse and, if i
|
|
|
289
326
|
- Cache-warming decisions and persisted `cache_warm` usage are reported, including standalone session-grouped
|
|
290
327
|
traces when warming happens while no user-request trace is active.
|
|
291
328
|
- Compaction is recorded as `session-compaction`, with a nested `compaction-summary` generation when usage is available.
|
|
292
|
-
|
|
329
|
+
Both compaction events are recorded even when no agent run is active — recovery compaction often lands after the
|
|
330
|
+
run settled — and then form their own trace named `pi-session` inside the same session.
|
|
331
|
+
- On Pi versions that emit `session_compact_failed`, failed compactions appear as
|
|
332
|
+
`session-compaction-failed` events: `ERROR` for failures and `WARNING` for cancellations.
|
|
333
|
+
Pi reports a cancelling extension as an abort and may omit its original error text.
|
|
334
|
+
- Trace-level scores include tool counts, tool success rate, and whether the run had tool errors.
|
|
293
335
|
|
|
294
336
|
The package also includes a Langfuse CLI skill, so Langfuse data can be queried directly from Pi:
|
|
295
337
|
|
|
@@ -338,6 +380,30 @@ Earlier versions emitted `git_commit`, branch, remote, owner, repository, and re
|
|
|
338
380
|
|
|
339
381
|
Unset `LANGFUSE_CAPTURE_SOURCE_METADATA` to stop collection immediately. Pin `pi-langfuse@1.5.12` only if the old schema is required during migration; doing so also restores its broader default source disclosure.
|
|
340
382
|
|
|
383
|
+
## Session Lineage
|
|
384
|
+
|
|
385
|
+
Pi writes the session file a session was forked or spawned from into its header, and the extension reads it through `sessionManager.getHeader()`. Every observation of such a derived session then carries:
|
|
386
|
+
|
|
387
|
+
```json
|
|
388
|
+
{
|
|
389
|
+
"parentSessionId": "01a1639b-58c5-729a-8315-f17b045ccd28",
|
|
390
|
+
"sessionKind": "fork"
|
|
391
|
+
}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
`sessionKind` is `subagent` when `pi-subagents` sets `PI_SUBAGENT_CHILD=1` and `fork` otherwise. That environment flag is a `pi-subagents` implementation detail, not a contract this package owns. Foreground children may omit it and receive the `fork` label; the parent link still comes from the session header. Normal parent UUIDs remain exact, while custom IDs pass through secret and path redaction before upload, including standalone traces.
|
|
395
|
+
|
|
396
|
+
Sessions remain separate in Langfuse, because Langfuse has no session-to-session relation. Correlate through metadata instead, for example after resolving a child session id:
|
|
397
|
+
|
|
398
|
+
```bash
|
|
399
|
+
curl -s -u "$LANGFUSE_PUBLIC_KEY:$LANGFUSE_SECRET_KEY" \
|
|
400
|
+
"$LANGFUSE_HOST/api/public/v2/observations?sessionId=<child-session-id>&fields=core,metadata"
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Root sessions carry neither key. Only the parent session id is read; the parent transcript is never opened beyond the header line that names it.
|
|
404
|
+
Standalone compaction and idle cache-warming traces retain these links, including
|
|
405
|
+
cache-warming usage and costs, through both OTel export and REST fallback.
|
|
406
|
+
|
|
341
407
|
## Troubleshooting
|
|
342
408
|
|
|
343
409
|
### No traces appearing?
|
package/README_CN.md
CHANGED
|
@@ -159,6 +159,18 @@ export PI_LANGFUSE_MAX_PAYLOAD_NODES=2000 # 单个负载的最大总节
|
|
|
159
159
|
任意上限设置为 `0`、`off`、`none` 或 `unlimited` 即表示关闭该限制(采集完整值);未设置或非法值回退到上方默认值。
|
|
160
160
|
若想完整采集很大的 system prompt 或工具负载,可以调高或关闭相关限制(例如 `PI_LANGFUSE_MAX_STRING_LENGTH=off`)。
|
|
161
161
|
|
|
162
|
+
若错误文本中的 JSON 因前后附加的诊断信息而无法解析,状态和采集的工具错误输出会使用
|
|
163
|
+
`[unparseable error payload]`,避免原始敏感字段泄露。
|
|
164
|
+
后续模型请求中重放的错误文本也会检查敏感 JSON 字段;不含这些字段的普通文本保持不变。
|
|
165
|
+
纯字符串采集路径(包括助手回复、压缩摘要和自定义 ID)会将含有未脱敏 JSON 敏感字段的文本
|
|
166
|
+
替换为 `[REDACTED_SECRET]`。已脱敏字段和普通文本保持不变,输出仍为字符串。
|
|
167
|
+
该检查还会在现有深度和节点数量限制内解码嵌套 JSON 字符串。转义内容无法安全解析或检查预算耗尽时,
|
|
168
|
+
会隐藏整个字符串,避免暴露未经检查的内容。
|
|
169
|
+
凭据赋值无论是否带引号都会脱敏,包括转义或未闭合的引号。序列化文本中的转义引号会保护整个值,包括空格。
|
|
170
|
+
如果单引号的转义层级不明确,后续诊断文本也可能被隐藏。
|
|
171
|
+
已知格式的令牌会在字符串截断前
|
|
172
|
+
脱敏,避免跨越采集长度上限的令牌因变成短片段而绕过检测。
|
|
173
|
+
|
|
162
174
|
REST 回退摄取会按字节切分,保证每个请求体都远低于 Langfuse 网关的负载限制(约 4.5MB)。以下变量控制切分预算
|
|
163
175
|
与整个回退负载的硬上限:
|
|
164
176
|
|
|
@@ -169,6 +181,8 @@ export PI_LANGFUSE_MAX_FALLBACK_TOTAL_BYTES=33554432 # 整体负载上限,默
|
|
|
169
181
|
```
|
|
170
182
|
|
|
171
183
|
当累积的回退负载超过 32MB 上限时,会跳过摄取并给出告警,而不是尝试一次注定失败的超大上传。
|
|
184
|
+
单个事件超过单次请求体预算时,会跳过该事件并输出仅包含大小信息的告警;其余事件仍会发送。
|
|
185
|
+
调高采集上限时,也需要注意这个单事件限制。
|
|
172
186
|
|
|
173
187
|
### 推理(reasoning)token
|
|
174
188
|
|
|
@@ -246,7 +260,10 @@ pi list
|
|
|
246
260
|
/langfuse-test
|
|
247
261
|
```
|
|
248
262
|
|
|
249
|
-
该命令会先发起一次带超时的认证请求;认证通过后,再发送一条小的测试 trace
|
|
263
|
+
该命令会先发起一次带超时的认证请求;认证通过后,再发送一条小的测试 trace。返回结果还会说明
|
|
264
|
+
读取接口是否可用:先检查 `v2/observations`,仅当它返回 404 或 405 时回退到旧版 observations API,以兼容旧服务器。
|
|
265
|
+
读取失败会显示警告,但不会阻止发送测试 trace。该检查只验证接口可用性,不保证新 trace 已可查询。
|
|
266
|
+
Langfuse v4 的 `events_only` 模式移除了旧版读取接口;compaction 和错误文本修复本身不要求 v4。
|
|
250
267
|
|
|
251
268
|
## 在 Langfuse 中会看到什么
|
|
252
269
|
|
|
@@ -268,6 +285,9 @@ pi list
|
|
|
268
285
|
- cache warming 决策及持久化的 `cache_warm` 用量会被记录;若 warming 发生时没有活动的用户请求 trace,
|
|
269
286
|
会创建按相同 session 分组的独立 trace。
|
|
270
287
|
- compaction 会记录为 `session-compaction`;若存在摘要用量,则包含 `compaction-summary` generation。
|
|
288
|
+
即使没有活动的 agent run(恢复性 compaction 常发生在 run 结束之后)也会记录 compaction 事件;
|
|
289
|
+
此时它们会在同一 session 下形成名为 `pi-session` 的独立 trace。发出 `session_compact_failed` 的 Pi 版本
|
|
290
|
+
会将失败的 compaction 记为 `session-compaction-failed`:失败为 `ERROR`,取消为 `WARNING`。
|
|
271
291
|
- trace 级别会记录工具调用次数、工具成功率和是否出现错误。
|
|
272
292
|
|
|
273
293
|
此包还包含一个内置 Langfuse 技能,可直接在 Pi 中查询 Langfuse 数据:
|
|
@@ -317,6 +337,28 @@ export OTEL_RESOURCE_ATTRIBUTES="service.version=1.2.3,vcs.repository.name=publi
|
|
|
317
337
|
|
|
318
338
|
取消设置 `LANGFUSE_CAPTURE_SOURCE_METADATA` 可立即停止采集。迁移期间只有在必须保留旧 schema 时才固定到 `pi-langfuse@1.5.12`;这样也会恢复旧版本更宽泛的默认源码披露。
|
|
319
339
|
|
|
340
|
+
## 会话血缘
|
|
341
|
+
|
|
342
|
+
Pi 会把派生会话的来源文件写入会话头,扩展通过 `sessionManager.getHeader()` 读取它。这类派生会话的所有 observation 都会携带:
|
|
343
|
+
|
|
344
|
+
```json
|
|
345
|
+
{
|
|
346
|
+
"parentSessionId": "01a1639b-58c5-729a-8315-f17b045ccd28",
|
|
347
|
+
"sessionKind": "fork"
|
|
348
|
+
}
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
当进程在 `pi-subagents` 下运行时(`PI_SUBAGENT_CHILD=1`)`sessionKind` 为 `subagent`,否则为 `fork`。该环境变量是 `pi-subagents` 的实现细节,不是本包持有的契约:子进程丢失该变量时只会标成 `fork`,即只有标签会降级——父链接本身取自会话头,始终是精确的。
|
|
352
|
+
|
|
353
|
+
Langfuse 中没有会话与会话的关联关系,因此会话仍然彼此独立,只能通过 metadata 关联。解析出子会话 id 后例如:
|
|
354
|
+
|
|
355
|
+
```bash
|
|
356
|
+
curl -s -u "$LANGFUSE_PUBLIC_KEY:$LANGFUSE_SECRET_KEY" \
|
|
357
|
+
"$LANGFUSE_HOST/api/public/v2/observations?sessionId=<child-session-id>&fields=core,metadata"
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
根会话不携带这两个键。扩展只读取父会话 id,除指明该 id 的首行外不会打开父会话转录。
|
|
361
|
+
|
|
320
362
|
## 故障排除
|
|
321
363
|
|
|
322
364
|
### 没有看到 trace
|
package/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { basename } from "node:path";
|
|
|
11
11
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
|
|
13
13
|
import { state, resetRunState, runWithSession, setCurrentSession } from "./src/state.js";
|
|
14
|
+
import { bindSessionLineage } from "./src/session-lineage.js";
|
|
14
15
|
import { ensureConfig, promptForConfig, loadConfig } from "./src/config.js";
|
|
15
16
|
import { shutdownRuntime } from "./src/langfuse.js";
|
|
16
17
|
import { handleLangfusePrivacyCommand, handleLangfuseStatusCommand, handleLangfuseTestCommand } from "./src/commands.js";
|
|
@@ -30,7 +31,7 @@ import {
|
|
|
30
31
|
recordCacheWarmingDecision,
|
|
31
32
|
recordNewUsageEntries,
|
|
32
33
|
} from "./src/handlers/cache.js";
|
|
33
|
-
import { recordSessionCompaction } from "./src/handlers/session.js";
|
|
34
|
+
import { recordSessionCompaction, recordSessionCompactionFailure } from "./src/handlers/session.js";
|
|
34
35
|
import {
|
|
35
36
|
startGeneration,
|
|
36
37
|
updateGenerationMetadata,
|
|
@@ -111,6 +112,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
111
112
|
state.setupAttemptedThisSession = false;
|
|
112
113
|
await ensureConfig(ctx);
|
|
113
114
|
resetRunState();
|
|
115
|
+
bindSessionLineage(ctx?.sessionManager);
|
|
114
116
|
initializeSystemStateTracking(ctx);
|
|
115
117
|
initializeUsageTracking(ctx);
|
|
116
118
|
}));
|
|
@@ -227,6 +229,10 @@ export default async function (pi: ExtensionAPI) {
|
|
|
227
229
|
await recordSessionCompaction(asRecord(event));
|
|
228
230
|
}));
|
|
229
231
|
|
|
232
|
+
pi.on("session_compact_failed", async (event, ctx) => withSession(ctx, async () => {
|
|
233
|
+
await recordSessionCompactionFailure(asRecord(event));
|
|
234
|
+
}));
|
|
235
|
+
|
|
230
236
|
pi.on("session_shutdown", async (_event, ctx) => withSession(ctx, async () => {
|
|
231
237
|
await recordNewUsageEntries(ctx);
|
|
232
238
|
handleSessionInterruption("Session shutdown before agent completed");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-langfuse",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Langfuse extension for Pi coding agent",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
],
|
|
25
25
|
"scripts": {
|
|
26
26
|
"typecheck": "tsc --noEmit",
|
|
27
|
-
"test": "tsx --test test/*.test.ts"
|
|
27
|
+
"test": "tsx --import=./test/reset-ambient-env.ts --test test/*.test.ts"
|
|
28
28
|
},
|
|
29
29
|
"keywords": [
|
|
30
30
|
"pi-package",
|
|
@@ -46,7 +46,10 @@
|
|
|
46
46
|
"@langfuse/otel": "^5.3.0",
|
|
47
47
|
"@langfuse/tracing": "^5.3.0",
|
|
48
48
|
"@opentelemetry/api": "^1.9.0",
|
|
49
|
+
"@opentelemetry/core": "^2.0.1",
|
|
49
50
|
"@opentelemetry/context-async-hooks": "^2.7.1",
|
|
51
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.218.0",
|
|
52
|
+
"@opentelemetry/otlp-exporter-base": "^0.218.0",
|
|
50
53
|
"@opentelemetry/sdk-node": "^0.218.0",
|
|
51
54
|
"@opentelemetry/sdk-trace-base": "^2.0.1"
|
|
52
55
|
},
|
package/src/commands.ts
CHANGED
|
@@ -35,6 +35,7 @@ interface CommandDeps {
|
|
|
35
35
|
interface ConnectivityResult {
|
|
36
36
|
ok: boolean;
|
|
37
37
|
message: string;
|
|
38
|
+
warning?: boolean;
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
function notify(ctx: CommandContextLike, message: string, level: "info" | "warning" | "error" = "info") {
|
|
@@ -226,6 +227,35 @@ function formatStatus(configPath: string, env: Record<string, string | undefined
|
|
|
226
227
|
].join("\n");
|
|
227
228
|
}
|
|
228
229
|
|
|
230
|
+
// v4 events_only removes legacy reads; older servers may not expose v2 reads.
|
|
231
|
+
const READ_PROBE_WINDOW_MS = 6 * 60 * 60 * 1_000;
|
|
232
|
+
|
|
233
|
+
async function probeReadSurface(host: string, auth: string): Promise<{ message: string; warning: boolean }> {
|
|
234
|
+
const to = new Date();
|
|
235
|
+
const from = new Date(to.getTime() - READ_PROBE_WINDOW_MS);
|
|
236
|
+
const url = `${host}/api/public/v2/observations?fromStartTime=${from.toISOString()}&toStartTime=${to.toISOString()}&limit=1`;
|
|
237
|
+
|
|
238
|
+
for (const [name, endpoint] of [
|
|
239
|
+
["v2 observations", url],
|
|
240
|
+
["legacy observations", `${host}/api/public/observations?limit=1`],
|
|
241
|
+
]) {
|
|
242
|
+
try {
|
|
243
|
+
const response = await fetch(endpoint, {
|
|
244
|
+
headers: { Authorization: `Basic ${auth}` },
|
|
245
|
+
signal: AbortSignal.timeout(10_000),
|
|
246
|
+
});
|
|
247
|
+
if (name === "v2 observations" && (response.status === 404 || response.status === 405)) continue;
|
|
248
|
+
return {
|
|
249
|
+
message: `read: ${name} ${response.ok ? "ok" : `HTTP ${response.status}`}`,
|
|
250
|
+
warning: !response.ok,
|
|
251
|
+
};
|
|
252
|
+
} catch (error) {
|
|
253
|
+
return { message: `read: ${name} failed: ${error instanceof Error ? error.message : String(error)}`, warning: true };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { message: "read: unavailable", warning: true };
|
|
257
|
+
}
|
|
258
|
+
|
|
229
259
|
async function checkLangfuseConnectivity(config: Config): Promise<ConnectivityResult> {
|
|
230
260
|
const host = config.host.replace(/\/+$/, "");
|
|
231
261
|
const auth = Buffer.from(`${config.publicKey}:${config.secretKey}`).toString("base64");
|
|
@@ -239,7 +269,8 @@ async function checkLangfuseConnectivity(config: Config): Promise<ConnectivityRe
|
|
|
239
269
|
});
|
|
240
270
|
|
|
241
271
|
if (response.ok) {
|
|
242
|
-
|
|
272
|
+
const read = await probeReadSurface(host, auth);
|
|
273
|
+
return { ok: true, message: `Connected to ${config.host}; ${read.message}`, warning: read.warning };
|
|
243
274
|
}
|
|
244
275
|
|
|
245
276
|
return {
|
|
@@ -413,7 +444,8 @@ export async function handleLangfuseTestCommand(
|
|
|
413
444
|
return observation;
|
|
414
445
|
},
|
|
415
446
|
);
|
|
416
|
-
|
|
447
|
+
const result = connectivity.warning ? "completed with a read warning" : "succeeded";
|
|
448
|
+
notify(ctx, `Langfuse test ${result}. ${connectivity.message}; test trace sent to ${config.host}.`, connectivity.warning ? "warning" : "info");
|
|
417
449
|
return true;
|
|
418
450
|
} catch (error) {
|
|
419
451
|
const message = error instanceof Error ? error.message : String(error);
|
package/src/handlers/agent.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { state, resetRunState, computeEvaluationScores } from "../state.js";
|
|
2
2
|
import { getRuntime, sendScore } from "../langfuse.js";
|
|
3
3
|
import { ensureConfig } from "../config.js";
|
|
4
|
-
import { shapePayload, truncate, extractFinalAssistant, extractAssistantOutput, getCapturePolicy
|
|
4
|
+
import { shapePayload, truncate, extractFinalAssistant, extractAssistantOutput, getCapturePolicy } from "../utils.js";
|
|
5
5
|
import { closeDanglingObservations } from "./tool.js";
|
|
6
6
|
import { applyCapturePolicy } from "../capture-policy.js";
|
|
7
7
|
import { collectSourceMetadata } from "../source-metadata.js";
|
|
8
|
+
import { sessionLineageMetadata } from "../session-lineage.js";
|
|
8
9
|
import { startChildObservation } from "../observation.js";
|
|
9
10
|
|
|
10
11
|
function stringMetadata(metadata: Record<string, unknown> | undefined): Record<string, string> | undefined {
|
|
@@ -72,6 +73,7 @@ export async function startAgentRun(event: Record<string, unknown>, ctx: any) {
|
|
|
72
73
|
...(state.currentProvider ? { provider: state.currentProvider } : {}),
|
|
73
74
|
sessionId: state.currentSessionId || undefined,
|
|
74
75
|
sessionLeafId: ctx?.sessionManager?.getLeafId?.() || undefined,
|
|
76
|
+
...sessionLineageMetadata(ctx?.sessionManager),
|
|
75
77
|
},
|
|
76
78
|
},
|
|
77
79
|
capturePolicy,
|
|
@@ -225,7 +227,7 @@ export async function recordSystemPrompt(ctx: any) {
|
|
|
225
227
|
}
|
|
226
228
|
|
|
227
229
|
const captured = applyCapturePolicy(
|
|
228
|
-
{ systemPrompt:
|
|
230
|
+
{ systemPrompt: String(systemPrompt) },
|
|
229
231
|
getCapturePolicy(),
|
|
230
232
|
);
|
|
231
233
|
if (!captured.systemPrompt) {
|
package/src/handlers/cache.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { applyCapturePolicy } from "../capture-policy.js";
|
|
|
2
2
|
import { getRuntime } from "../langfuse.js";
|
|
3
3
|
import { startChildObservation } from "../observation.js";
|
|
4
4
|
import { getSessionRunState, state } from "../state.js";
|
|
5
|
+
import { sessionLineageMetadata } from "../session-lineage.js";
|
|
5
6
|
import { extractCostDetails, extractUsage, getCapturePolicy, truncate } from "../utils.js";
|
|
6
7
|
|
|
7
8
|
type RecordLike = Record<string, unknown>;
|
|
@@ -67,6 +68,7 @@ export async function recordCacheWarmingDecision(event: RecordLike, ctx: any): P
|
|
|
67
68
|
sessionId: sessionIdForTrace(),
|
|
68
69
|
traceName: "pi-cache-warming",
|
|
69
70
|
metadata: {
|
|
71
|
+
...sessionLineageMetadata(ctx?.sessionManager),
|
|
70
72
|
...(ctx?.model?.id ? { model: String(ctx.model.id) } : {}),
|
|
71
73
|
...(ctx?.model?.provider ? { provider: String(ctx.model.provider) } : {}),
|
|
72
74
|
},
|
|
@@ -131,11 +133,11 @@ export async function recordNewUsageEntries(ctx: any): Promise<void> {
|
|
|
131
133
|
? await startChildObservation({ parent, runtime: getRuntime, name: "cache-warm", body, asType: "generation" })
|
|
132
134
|
: (runtime.withRootContext
|
|
133
135
|
? runtime.withRootContext(() => runtime.propagateAttributes(
|
|
134
|
-
{ sessionId: sessionIdForTrace(), traceName: "pi-cache-warm" },
|
|
136
|
+
{ sessionId: sessionIdForTrace(), traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
|
|
135
137
|
() => runtime.startObservation("cache-warm", body, { asType: "generation" }),
|
|
136
138
|
))
|
|
137
139
|
: runtime.propagateAttributes(
|
|
138
|
-
{ sessionId: sessionIdForTrace(), traceName: "pi-cache-warm" },
|
|
140
|
+
{ sessionId: sessionIdForTrace(), traceName: "pi-cache-warm", metadata: sessionLineageMetadata(ctx?.sessionManager) },
|
|
139
141
|
() => runtime.startObservation("cache-warm", body, { asType: "generation" }),
|
|
140
142
|
));
|
|
141
143
|
observation.end();
|
|
@@ -15,6 +15,8 @@ import {
|
|
|
15
15
|
extractCacheMetrics,
|
|
16
16
|
inferToolUpdateTransport,
|
|
17
17
|
extractModelIdentity,
|
|
18
|
+
extractGenerationStatus,
|
|
19
|
+
toStatusMessage,
|
|
18
20
|
} from "../utils.js";
|
|
19
21
|
import type { GenerationState, ObservationUpdate } from "../types.js";
|
|
20
22
|
import { applyCapturePolicy } from "../capture-policy.js";
|
|
@@ -114,50 +116,19 @@ export function updateGenerationMetadata(event: Record<string, unknown>) {
|
|
|
114
116
|
|
|
115
117
|
const key = getRequestKey(event, "");
|
|
116
118
|
const metadata = applyCapturePolicy({ metadata: extractResponseMetadata(event) }, getCapturePolicy()).metadata ?? {};
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if (generation) {
|
|
120
|
-
generation.metadata = { ...generation.metadata, ...metadata };
|
|
121
|
-
|
|
122
|
-
const isError =
|
|
123
|
-
(typeof metadata.status === "number" && metadata.status >= 400) ||
|
|
124
|
-
event.error ||
|
|
125
|
-
event.isError;
|
|
126
|
-
|
|
127
|
-
if (isError) {
|
|
128
|
-
generation.observation.update({
|
|
129
|
-
metadata: generation.metadata,
|
|
130
|
-
level: "ERROR",
|
|
131
|
-
statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
|
|
132
|
-
}).end();
|
|
133
|
-
generation.ended = true;
|
|
134
|
-
} else {
|
|
135
|
-
generation.observation.update({ metadata: generation.metadata });
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
119
|
+
const generation = (key ? state.agentState.activeGenerations.get(key) : undefined) ?? getOpenGeneration();
|
|
120
|
+
if (!generation || generation.ended) return;
|
|
140
121
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
(
|
|
147
|
-
|
|
148
|
-
event.isError;
|
|
149
|
-
|
|
150
|
-
if (isError) {
|
|
151
|
-
generation.observation.update({
|
|
152
|
-
metadata: generation.metadata,
|
|
153
|
-
level: "ERROR",
|
|
154
|
-
statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
|
|
155
|
-
}).end();
|
|
156
|
-
generation.ended = true;
|
|
157
|
-
} else {
|
|
158
|
-
generation.observation.update({ metadata: generation.metadata });
|
|
159
|
-
}
|
|
122
|
+
generation.metadata = { ...generation.metadata, ...metadata };
|
|
123
|
+
const isError = (typeof metadata.status === "number" && metadata.status >= 400) || event.error || event.isError;
|
|
124
|
+
if (isError) {
|
|
125
|
+
generation.errorStatus = {
|
|
126
|
+
level: "ERROR",
|
|
127
|
+
statusMessage: toStatusMessage(event.error ?? metadata.statusMessage ?? "Provider request failed"),
|
|
128
|
+
};
|
|
160
129
|
}
|
|
130
|
+
// The assistant message supplies final error details and usage; close there.
|
|
131
|
+
generation.observation.update({ metadata: generation.metadata, ...generation.errorStatus });
|
|
161
132
|
}
|
|
162
133
|
|
|
163
134
|
export function recordTTFT(event: Record<string, unknown>) {
|
|
@@ -218,7 +189,12 @@ export async function finishGenerationFromMessage(event: Record<string, unknown>
|
|
|
218
189
|
const cacheMetrics = extractCacheMetrics({ ...event, message });
|
|
219
190
|
const modelParameters = extractModelParameters(getProviderPayload(event)) ?? generation.modelParameters;
|
|
220
191
|
const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
|
|
192
|
+
const finishReason = message.finishReason ?? message.stopReason;
|
|
221
193
|
const update: ObservationUpdate = {
|
|
194
|
+
...(generation.errorStatus && ["stop", "toolUse", "length"].includes(String(finishReason))
|
|
195
|
+
? { level: "DEFAULT" as const, statusMessage: "" }
|
|
196
|
+
: {}),
|
|
197
|
+
...extractGenerationStatus(message),
|
|
222
198
|
output,
|
|
223
199
|
model: actual.model ?? (generation.metadata.actualModel as string | undefined) ?? (state.currentModel || undefined),
|
|
224
200
|
modelParameters,
|
|
@@ -228,7 +204,7 @@ export async function finishGenerationFromMessage(event: Record<string, unknown>
|
|
|
228
204
|
...generation.metadata,
|
|
229
205
|
...(actual.model ? { actualModel: actual.model } : {}),
|
|
230
206
|
...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
|
|
231
|
-
finishReason:
|
|
207
|
+
finishReason: finishReason ?? event.finishReason,
|
|
232
208
|
...cacheMetrics,
|
|
233
209
|
},
|
|
234
210
|
};
|
|
@@ -270,6 +246,7 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
|
|
|
270
246
|
actualModel: actual.model,
|
|
271
247
|
actualProvider: actual.provider,
|
|
272
248
|
sourceEvent: "turn_end",
|
|
249
|
+
finishReason: message.finishReason ?? message.stopReason ?? event.finishReason,
|
|
273
250
|
promptStateHash: state.agentState.promptStateHash,
|
|
274
251
|
toolStateHash: state.agentState.toolStateHash,
|
|
275
252
|
systemStateSequence: state.agentState.systemStateSequence,
|
|
@@ -285,6 +262,7 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
|
|
|
285
262
|
runtime: getRuntime,
|
|
286
263
|
name: "llm-generation",
|
|
287
264
|
body: {
|
|
265
|
+
...extractGenerationStatus(message),
|
|
288
266
|
input: captured.input,
|
|
289
267
|
output: captured.output,
|
|
290
268
|
model: actual.model ?? (state.currentModel || undefined),
|
package/src/handlers/session.ts
CHANGED
|
@@ -1,16 +1,77 @@
|
|
|
1
1
|
import { applyCapturePolicy } from "../capture-policy.js";
|
|
2
2
|
import { getRuntime } from "../langfuse.js";
|
|
3
|
-
import { startChildObservation } from "../observation.js";
|
|
3
|
+
import { startChildObservation, startSessionObservation } from "../observation.js";
|
|
4
4
|
import { state } from "../state.js";
|
|
5
|
+
import { sessionLineageMetadata } from "../session-lineage.js";
|
|
5
6
|
import {
|
|
6
7
|
extractCostDetails,
|
|
8
|
+
extractGenerationStatus,
|
|
7
9
|
extractUsage,
|
|
8
10
|
getCapturePolicy,
|
|
9
11
|
shapePayload,
|
|
12
|
+
truncate,
|
|
10
13
|
} from "../utils.js";
|
|
14
|
+
import type { LangfuseObservation, ObservationUpdate } from "../types.js";
|
|
11
15
|
|
|
12
16
|
type RecordLike = Record<string, unknown>;
|
|
13
17
|
|
|
18
|
+
// Compaction can fire after the run already settled, so the event has no agent
|
|
19
|
+
// root to nest under. A rootless observation still belongs to the session, hence
|
|
20
|
+
// its own trace name instead of being dropped.
|
|
21
|
+
const SESSION_TRACE_NAME = "pi-session";
|
|
22
|
+
|
|
23
|
+
function startCompactionObservation(
|
|
24
|
+
name: string,
|
|
25
|
+
body: ObservationUpdate,
|
|
26
|
+
asType: "event" | "span",
|
|
27
|
+
): Promise<LangfuseObservation> {
|
|
28
|
+
const agent = state.agentState;
|
|
29
|
+
const parent = agent?.activeTurn ?? agent?.activeAttempt ?? agent?.root;
|
|
30
|
+
if (parent) {
|
|
31
|
+
return startChildObservation({ parent, runtime: getRuntime, name, body, asType });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return startSessionObservation({
|
|
35
|
+
runtime: getRuntime,
|
|
36
|
+
name,
|
|
37
|
+
body,
|
|
38
|
+
asType,
|
|
39
|
+
attributes: {
|
|
40
|
+
sessionId: state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined,
|
|
41
|
+
userId: state.config?.userId,
|
|
42
|
+
traceName: SESSION_TRACE_NAME,
|
|
43
|
+
metadata: { piScope: "session", ...sessionLineageMetadata() },
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function recordSessionCompactionFailure(event: RecordLike): Promise<void> {
|
|
49
|
+
if (state.isTracingDisabled) return;
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
const observation = await startCompactionObservation(
|
|
53
|
+
"session-compaction-failed",
|
|
54
|
+
{
|
|
55
|
+
...extractGenerationStatus({
|
|
56
|
+
stopReason: event.aborted ? "aborted" : "error",
|
|
57
|
+
errorMessage: event.errorMessage
|
|
58
|
+
|| (event.aborted ? "Compaction cancelled" : "Compaction failed"),
|
|
59
|
+
}),
|
|
60
|
+
metadata: shapePayload({
|
|
61
|
+
reason: event.reason,
|
|
62
|
+
aborted: event.aborted,
|
|
63
|
+
willRetry: event.willRetry,
|
|
64
|
+
fromExtension: event.fromExtension,
|
|
65
|
+
}) as RecordLike,
|
|
66
|
+
},
|
|
67
|
+
"event",
|
|
68
|
+
);
|
|
69
|
+
observation.end();
|
|
70
|
+
} catch (error) {
|
|
71
|
+
console.warn("📊 Langfuse: Failed to record compaction failure", error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
14
75
|
function namesFromTools(value: unknown): string[] {
|
|
15
76
|
if (!Array.isArray(value)) return [];
|
|
16
77
|
return value.flatMap((tool) => {
|
|
@@ -22,9 +83,9 @@ function namesFromTools(value: unknown): string[] {
|
|
|
22
83
|
}
|
|
23
84
|
|
|
24
85
|
export async function recordSessionCompaction(event: RecordLike): Promise<void> {
|
|
25
|
-
|
|
26
|
-
if (state.isTracingDisabled || !agent?.root) return;
|
|
86
|
+
if (state.isTracingDisabled) return;
|
|
27
87
|
|
|
88
|
+
const agent = state.agentState;
|
|
28
89
|
const entry = event.compactionEntry && typeof event.compactionEntry === "object"
|
|
29
90
|
? event.compactionEntry as RecordLike
|
|
30
91
|
: {};
|
|
@@ -48,22 +109,19 @@ export async function recordSessionCompaction(event: RecordLike): Promise<void>
|
|
|
48
109
|
checkpointSectionNames: checkpointSections,
|
|
49
110
|
checkpointToolNames: checkpointTools,
|
|
50
111
|
checkpointToolCount: checkpointTools.length,
|
|
51
|
-
promptStateHash: agent
|
|
52
|
-
toolStateHash: agent
|
|
112
|
+
promptStateHash: agent?.promptStateHash,
|
|
113
|
+
toolStateHash: agent?.toolStateHash,
|
|
53
114
|
},
|
|
54
115
|
},
|
|
55
116
|
getCapturePolicy(),
|
|
56
117
|
);
|
|
57
118
|
|
|
58
119
|
try {
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
body: { input: captured.input, metadata: captured.metadata },
|
|
65
|
-
asType: "span",
|
|
66
|
-
});
|
|
120
|
+
const compaction = await startCompactionObservation(
|
|
121
|
+
"session-compaction",
|
|
122
|
+
{ input: captured.input, metadata: captured.metadata },
|
|
123
|
+
"span",
|
|
124
|
+
);
|
|
67
125
|
|
|
68
126
|
if (entry.usage && typeof entry.usage === "object") {
|
|
69
127
|
const summary = applyCapturePolicy({ output: entry.summary }, getCapturePolicy());
|