pi-langfuse 1.6.1 → 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 +76 -2
- package/README_CN.md +49 -1
- package/index.ts +14 -2
- package/package.json +6 -3
- 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 +58 -53
- package/src/handlers/session.ts +71 -13
- package/src/handlers/system-state.ts +4 -1
- package/src/handlers/tool.ts +46 -13
- 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 +2 -0
- package/src/utils.ts +118 -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
|
|
|
@@ -273,15 +307,31 @@ This command makes a timeout-bounded authenticated request to Langfuse and, if i
|
|
|
273
307
|
- Each user prompt within that session becomes a separate trace.
|
|
274
308
|
- The trace contains the final assistant output shown in Pi.
|
|
275
309
|
- Tool runs appear as tool observations with arguments, results, and error state.
|
|
310
|
+
Pi 1.0 nested calls (including codemode tools) are parented by `parentToolCallId`.
|
|
311
|
+
A tool's own model usage/cost appears in a child `tool-usage` generation; transcript totals that
|
|
312
|
+
include descendants are not ingested again. Pi's tool usage does not identify each nested model,
|
|
313
|
+
so these aggregate generations have no inferred model name or price.
|
|
276
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.
|
|
277
318
|
Reasoning tokens are reported as their own usage bucket when `PI_LANGFUSE_SPLIT_REASONING_TOKENS` is enabled.
|
|
319
|
+
Virtual routing preserves `selectedModel`/`selectedProvider` alongside `actualModel`/`actualProvider`;
|
|
320
|
+
the generation model and `provider` metadata use the actual identity when available.
|
|
278
321
|
- Pi 0.86 transcript-aware prompt/tool state appears as `system-state` events. Generations reference the
|
|
279
322
|
effective prompt/tool state hashes, active tool count, update transport, and cache hit ratio.
|
|
323
|
+
State is refreshed before every provider request, including after lazy tool loading, and unchanged
|
|
324
|
+
state is deduplicated within an attempt.
|
|
280
325
|
- Automatic retries are grouped under `agent-attempt` spans and the trace remains open until `agent_settled`.
|
|
281
326
|
- Cache-warming decisions and persisted `cache_warm` usage are reported, including standalone session-grouped
|
|
282
327
|
traces when warming happens while no user-request trace is active.
|
|
283
328
|
- Compaction is recorded as `session-compaction`, with a nested `compaction-summary` generation when usage is available.
|
|
284
|
-
|
|
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.
|
|
285
335
|
|
|
286
336
|
The package also includes a Langfuse CLI skill, so Langfuse data can be queried directly from Pi:
|
|
287
337
|
|
|
@@ -330,6 +380,30 @@ Earlier versions emitted `git_commit`, branch, remote, owner, repository, and re
|
|
|
330
380
|
|
|
331
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.
|
|
332
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
|
+
|
|
333
407
|
## Troubleshooting
|
|
334
408
|
|
|
335
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
|
|
|
@@ -254,14 +271,23 @@ pi list
|
|
|
254
271
|
- 该会话中的每个用户提示词都会生成一个独立 trace。
|
|
255
272
|
- trace 中会包含 Pi 实际显示的最终助手回复。
|
|
256
273
|
- 工具执行会以工具观察节点展示参数、结果和错误状态。
|
|
274
|
+
Pi 1.0 的嵌套调用(含 codemode 内部工具)按 `parentToolCallId` 建立父子关系。
|
|
275
|
+
工具自身的模型用量和费用记录在子级 `tool-usage` generation 中,不会重复上报 transcript 中包含
|
|
276
|
+
后代工具的合计用量。Pi 的工具 usage 未标识每个内部模型,因此这些聚合节点不推断模型名称或价格。
|
|
257
277
|
- 模型请求会以生成观察节点展示;如果提供商暴露相关信息,还会包含用量和成本。
|
|
258
278
|
开启 `PI_LANGFUSE_SPLIT_REASONING_TOKENS` 后,推理 token 会作为独立用量桶上报。
|
|
279
|
+
虚拟模型路由分别记录 `selectedModel`/`selectedProvider` 和 `actualModel`/`actualProvider`;
|
|
280
|
+
获得实际模型身份后,generation 的 model 和 `provider` 元数据使用实际值。
|
|
259
281
|
- Pi 0.86 的 transcript-aware system/tool 状态会作为 `system-state` 事件上报;generation 会引用有效的
|
|
260
282
|
prompt/tool 状态指纹、活动工具数、更新传输方式和缓存命中率。
|
|
283
|
+
每次 provider 请求前都会刷新状态,覆盖工具延迟加载;同一 attempt 内的未变化状态不会重复生成事件。
|
|
261
284
|
- 自动重试会归入 `agent-attempt` span,trace 会持续到 `agent_settled` 才结束。
|
|
262
285
|
- cache warming 决策及持久化的 `cache_warm` 用量会被记录;若 warming 发生时没有活动的用户请求 trace,
|
|
263
286
|
会创建按相同 session 分组的独立 trace。
|
|
264
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`。
|
|
265
291
|
- trace 级别会记录工具调用次数、工具成功率和是否出现错误。
|
|
266
292
|
|
|
267
293
|
此包还包含一个内置 Langfuse 技能,可直接在 Pi 中查询 Langfuse 数据:
|
|
@@ -311,6 +337,28 @@ export OTEL_RESOURCE_ATTRIBUTES="service.version=1.2.3,vcs.repository.name=publi
|
|
|
311
337
|
|
|
312
338
|
取消设置 `LANGFUSE_CAPTURE_SOURCE_METADATA` 可立即停止采集。迁移期间只有在必须保留旧 schema 时才固定到 `pi-langfuse@1.5.12`;这样也会恢复旧版本更宽泛的默认源码披露。
|
|
313
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
|
+
|
|
314
362
|
## 故障排除
|
|
315
363
|
|
|
316
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,13 +31,14 @@ 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,
|
|
37
38
|
finishGenerationFromMessage,
|
|
38
39
|
createFallbackGenerationFromTurn,
|
|
39
40
|
recordTTFT,
|
|
41
|
+
recordGenerationIdentity,
|
|
40
42
|
} from "./src/handlers/generation.js";
|
|
41
43
|
import {
|
|
42
44
|
startToolObservation,
|
|
@@ -110,6 +112,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
110
112
|
state.setupAttemptedThisSession = false;
|
|
111
113
|
await ensureConfig(ctx);
|
|
112
114
|
resetRunState();
|
|
115
|
+
bindSessionLineage(ctx?.sessionManager);
|
|
113
116
|
initializeSystemStateTracking(ctx);
|
|
114
117
|
initializeUsageTracking(ctx);
|
|
115
118
|
}));
|
|
@@ -145,13 +148,18 @@ export default async function (pi: ExtensionAPI) {
|
|
|
145
148
|
}));
|
|
146
149
|
|
|
147
150
|
pi.on("before_provider_request", async (event, ctx) => withSession(ctx, async () => {
|
|
148
|
-
await
|
|
151
|
+
await recordSystemState(ctx, pi.getActiveTools(), false);
|
|
152
|
+
await startGeneration(asRecord(event), ctx.model);
|
|
149
153
|
}));
|
|
150
154
|
|
|
151
155
|
pi.on("after_provider_response", async (event, ctx) => withSession(ctx, async () => {
|
|
152
156
|
updateGenerationMetadata(asRecord(event));
|
|
153
157
|
}));
|
|
154
158
|
|
|
159
|
+
pi.on("provider_stream_event", (event, ctx) => withSession(ctx, () => {
|
|
160
|
+
recordGenerationIdentity(asRecord(event));
|
|
161
|
+
}));
|
|
162
|
+
|
|
155
163
|
pi.on("message_update", async (event, ctx) => withSession(ctx, async () => {
|
|
156
164
|
recordTTFT(asRecord(event));
|
|
157
165
|
const message = getMessageFromEvent(asRecord(event));
|
|
@@ -221,6 +229,10 @@ export default async function (pi: ExtensionAPI) {
|
|
|
221
229
|
await recordSessionCompaction(asRecord(event));
|
|
222
230
|
}));
|
|
223
231
|
|
|
232
|
+
pi.on("session_compact_failed", async (event, ctx) => withSession(ctx, async () => {
|
|
233
|
+
await recordSessionCompactionFailure(asRecord(event));
|
|
234
|
+
}));
|
|
235
|
+
|
|
224
236
|
pi.on("session_shutdown", async (_event, ctx) => withSession(ctx, async () => {
|
|
225
237
|
await recordNewUsageEntries(ctx);
|
|
226
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.
|
|
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
|
},
|
|
@@ -62,7 +65,7 @@
|
|
|
62
65
|
"node": ">=22"
|
|
63
66
|
},
|
|
64
67
|
"devDependencies": {
|
|
65
|
-
"@earendil-works/pi-coding-agent": "^0.
|
|
68
|
+
"@earendil-works/pi-coding-agent": "^1.0.0",
|
|
66
69
|
"tsx": "^4.19.0",
|
|
67
70
|
"typescript": "^6.0.3"
|
|
68
71
|
}
|
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();
|
|
@@ -14,6 +14,9 @@ import {
|
|
|
14
14
|
extractModelParameters,
|
|
15
15
|
extractCacheMetrics,
|
|
16
16
|
inferToolUpdateTransport,
|
|
17
|
+
extractModelIdentity,
|
|
18
|
+
extractGenerationStatus,
|
|
19
|
+
toStatusMessage,
|
|
17
20
|
} from "../utils.js";
|
|
18
21
|
import type { GenerationState, ObservationUpdate } from "../types.js";
|
|
19
22
|
import { applyCapturePolicy } from "../capture-policy.js";
|
|
@@ -34,7 +37,7 @@ export function getOpenGeneration(): GenerationState | undefined {
|
|
|
34
37
|
return undefined;
|
|
35
38
|
}
|
|
36
39
|
|
|
37
|
-
export async function startGeneration(event: Record<string, unknown
|
|
40
|
+
export async function startGeneration(event: Record<string, unknown>, selectedModel?: unknown) {
|
|
38
41
|
if (state.isTracingDisabled || !state.agentState?.root) {
|
|
39
42
|
return;
|
|
40
43
|
}
|
|
@@ -43,11 +46,16 @@ export async function startGeneration(event: Record<string, unknown>) {
|
|
|
43
46
|
const key = getRequestKey(event, `generation-${++state.agentState.generationSeq}`);
|
|
44
47
|
const payload = getProviderPayload(event);
|
|
45
48
|
const modelParameters = extractModelParameters(payload);
|
|
46
|
-
const
|
|
47
|
-
const
|
|
49
|
+
const selected = extractModelIdentity(selectedModel ?? state.currentModel, selectedModel ? undefined : state.currentProvider);
|
|
50
|
+
const payloadModel = payload && typeof payload === "object" ? (payload as Record<string, unknown>).model : undefined;
|
|
51
|
+
const actual = extractModelIdentity(event.model ?? event.modelId ?? payloadModel, event.provider);
|
|
48
52
|
const toolUpdateTransport = inferToolUpdateTransport(payload, (state.agentState.systemStateSequence ?? 0) > 1);
|
|
49
53
|
const metadata = shapePayload({
|
|
50
|
-
provider,
|
|
54
|
+
provider: actual.provider ?? selected.provider,
|
|
55
|
+
selectedModel: selected.model,
|
|
56
|
+
selectedProvider: selected.provider,
|
|
57
|
+
actualModel: actual.model,
|
|
58
|
+
actualProvider: actual.provider,
|
|
51
59
|
requestId: key,
|
|
52
60
|
url: event.url,
|
|
53
61
|
method: event.method,
|
|
@@ -81,7 +89,7 @@ export async function startGeneration(event: Record<string, unknown>) {
|
|
|
81
89
|
name: "llm-generation",
|
|
82
90
|
body: {
|
|
83
91
|
input: captured.input,
|
|
84
|
-
model: model
|
|
92
|
+
model: actual.model ?? selected.model,
|
|
85
93
|
modelParameters,
|
|
86
94
|
metadata: captured.metadata,
|
|
87
95
|
},
|
|
@@ -108,50 +116,19 @@ export function updateGenerationMetadata(event: Record<string, unknown>) {
|
|
|
108
116
|
|
|
109
117
|
const key = getRequestKey(event, "");
|
|
110
118
|
const metadata = applyCapturePolicy({ metadata: extractResponseMetadata(event) }, getCapturePolicy()).metadata ?? {};
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (generation) {
|
|
114
|
-
generation.metadata = { ...generation.metadata, ...metadata };
|
|
115
|
-
|
|
116
|
-
const isError =
|
|
117
|
-
(typeof metadata.status === "number" && metadata.status >= 400) ||
|
|
118
|
-
event.error ||
|
|
119
|
-
event.isError;
|
|
120
|
-
|
|
121
|
-
if (isError) {
|
|
122
|
-
generation.observation.update({
|
|
123
|
-
metadata: generation.metadata,
|
|
124
|
-
level: "ERROR",
|
|
125
|
-
statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
|
|
126
|
-
}).end();
|
|
127
|
-
generation.ended = true;
|
|
128
|
-
} else {
|
|
129
|
-
generation.observation.update({ metadata: generation.metadata });
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
119
|
+
const generation = (key ? state.agentState.activeGenerations.get(key) : undefined) ?? getOpenGeneration();
|
|
120
|
+
if (!generation || generation.ended) return;
|
|
134
121
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
(
|
|
141
|
-
|
|
142
|
-
event.isError;
|
|
143
|
-
|
|
144
|
-
if (isError) {
|
|
145
|
-
generation.observation.update({
|
|
146
|
-
metadata: generation.metadata,
|
|
147
|
-
level: "ERROR",
|
|
148
|
-
statusMessage: String(event.error ?? metadata.statusMessage ?? "Provider request failed")
|
|
149
|
-
}).end();
|
|
150
|
-
generation.ended = true;
|
|
151
|
-
} else {
|
|
152
|
-
generation.observation.update({ metadata: generation.metadata });
|
|
153
|
-
}
|
|
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
|
+
};
|
|
154
129
|
}
|
|
130
|
+
// The assistant message supplies final error details and usage; close there.
|
|
131
|
+
generation.observation.update({ metadata: generation.metadata, ...generation.errorStatus });
|
|
155
132
|
}
|
|
156
133
|
|
|
157
134
|
export function recordTTFT(event: Record<string, unknown>) {
|
|
@@ -172,6 +149,21 @@ export function recordTTFT(event: Record<string, unknown>) {
|
|
|
172
149
|
}
|
|
173
150
|
}
|
|
174
151
|
|
|
152
|
+
/** Routing identity is available before the assistant message, including failed streams. */
|
|
153
|
+
export function recordGenerationIdentity(event: Record<string, unknown>) {
|
|
154
|
+
const generation = getOpenGeneration();
|
|
155
|
+
if (!generation) return;
|
|
156
|
+
const actual = extractModelIdentity(event.model, event.provider);
|
|
157
|
+
if (!actual.model && !actual.provider) return;
|
|
158
|
+
if (generation.metadata.actualModel === actual.model && generation.metadata.actualProvider === actual.provider) return;
|
|
159
|
+
generation.metadata = applyCapturePolicy({ metadata: shapePayload({
|
|
160
|
+
...generation.metadata,
|
|
161
|
+
...(actual.model ? { actualModel: actual.model } : {}),
|
|
162
|
+
...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
|
|
163
|
+
}) as Record<string, unknown> }, getCapturePolicy()).metadata ?? {};
|
|
164
|
+
generation.observation.update({ model: actual.model, metadata: generation.metadata });
|
|
165
|
+
}
|
|
166
|
+
|
|
175
167
|
export async function finishGenerationFromMessage(event: Record<string, unknown>) {
|
|
176
168
|
if (state.isTracingDisabled || !state.agentState) {
|
|
177
169
|
return;
|
|
@@ -196,16 +188,23 @@ export async function finishGenerationFromMessage(event: Record<string, unknown>
|
|
|
196
188
|
const costDetails = extractCostDetails({ ...event, message });
|
|
197
189
|
const cacheMetrics = extractCacheMetrics({ ...event, message });
|
|
198
190
|
const modelParameters = extractModelParameters(getProviderPayload(event)) ?? generation.modelParameters;
|
|
199
|
-
const
|
|
191
|
+
const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
|
|
192
|
+
const finishReason = message.finishReason ?? message.stopReason;
|
|
200
193
|
const update: ObservationUpdate = {
|
|
194
|
+
...(generation.errorStatus && ["stop", "toolUse", "length"].includes(String(finishReason))
|
|
195
|
+
? { level: "DEFAULT" as const, statusMessage: "" }
|
|
196
|
+
: {}),
|
|
197
|
+
...extractGenerationStatus(message),
|
|
201
198
|
output,
|
|
202
|
-
model: model || undefined,
|
|
199
|
+
model: actual.model ?? (generation.metadata.actualModel as string | undefined) ?? (state.currentModel || undefined),
|
|
203
200
|
modelParameters,
|
|
204
201
|
usageDetails,
|
|
205
202
|
...(costDetails ? { costDetails } : {}),
|
|
206
203
|
metadata: {
|
|
207
204
|
...generation.metadata,
|
|
208
|
-
|
|
205
|
+
...(actual.model ? { actualModel: actual.model } : {}),
|
|
206
|
+
...(actual.provider ? { provider: actual.provider, actualProvider: actual.provider } : {}),
|
|
207
|
+
finishReason: finishReason ?? event.finishReason,
|
|
209
208
|
...cacheMetrics,
|
|
210
209
|
},
|
|
211
210
|
};
|
|
@@ -235,14 +234,19 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
|
|
|
235
234
|
const costDetails = extractCostDetails({ ...event, message });
|
|
236
235
|
const cacheMetrics = extractCacheMetrics({ ...event, message });
|
|
237
236
|
const modelParameters = extractModelParameters(getProviderPayload(event));
|
|
238
|
-
const
|
|
237
|
+
const actual = extractModelIdentity(message.model ?? event.model, message.provider ?? event.provider);
|
|
239
238
|
const captured = applyCapturePolicy(
|
|
240
239
|
{
|
|
241
240
|
input: state.agentState.promptInput,
|
|
242
241
|
output: extractAssistantOutput(message),
|
|
243
242
|
metadata: {
|
|
244
|
-
provider: state.currentProvider || undefined,
|
|
243
|
+
provider: actual.provider ?? (state.currentProvider || undefined),
|
|
244
|
+
selectedModel: state.currentModel || undefined,
|
|
245
|
+
selectedProvider: state.currentProvider || undefined,
|
|
246
|
+
actualModel: actual.model,
|
|
247
|
+
actualProvider: actual.provider,
|
|
245
248
|
sourceEvent: "turn_end",
|
|
249
|
+
finishReason: message.finishReason ?? message.stopReason ?? event.finishReason,
|
|
246
250
|
promptStateHash: state.agentState.promptStateHash,
|
|
247
251
|
toolStateHash: state.agentState.toolStateHash,
|
|
248
252
|
systemStateSequence: state.agentState.systemStateSequence,
|
|
@@ -258,9 +262,10 @@ export async function createFallbackGenerationFromTurn(event: Record<string, unk
|
|
|
258
262
|
runtime: getRuntime,
|
|
259
263
|
name: "llm-generation",
|
|
260
264
|
body: {
|
|
265
|
+
...extractGenerationStatus(message),
|
|
261
266
|
input: captured.input,
|
|
262
267
|
output: captured.output,
|
|
263
|
-
model: model || undefined,
|
|
268
|
+
model: actual.model ?? (state.currentModel || undefined),
|
|
264
269
|
modelParameters,
|
|
265
270
|
usageDetails,
|
|
266
271
|
...(costDetails ? { costDetails } : {}),
|