pi-langfuse 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +87 -5
  2. package/README_CN.md +63 -5
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.js +216 -0
  5. package/dist/src/capture-policy.d.ts +43 -0
  6. package/dist/src/capture-policy.js +125 -0
  7. package/dist/src/commands.d.ts +25 -0
  8. package/dist/src/commands.js +374 -0
  9. package/dist/src/config.d.ts +13 -0
  10. package/dist/src/config.js +157 -0
  11. package/dist/src/constants.d.ts +9 -0
  12. package/dist/src/constants.js +11 -0
  13. package/dist/src/handlers/agent.d.ts +18 -0
  14. package/dist/src/handlers/agent.js +310 -0
  15. package/dist/src/handlers/cache.d.ts +5 -0
  16. package/dist/src/handlers/cache.js +134 -0
  17. package/dist/src/handlers/generation.d.ts +9 -0
  18. package/dist/src/handlers/generation.js +249 -0
  19. package/dist/src/handlers/session.d.ts +4 -0
  20. package/dist/src/handlers/session.js +121 -0
  21. package/dist/src/handlers/system-state.d.ts +3 -0
  22. package/dist/src/handlers/system-state.js +185 -0
  23. package/dist/src/handlers/tool.d.ts +3 -0
  24. package/dist/src/handlers/tool.js +168 -0
  25. package/dist/src/handlers/turn.d.ts +2 -0
  26. package/dist/src/handlers/turn.js +48 -0
  27. package/dist/src/langfuse.d.ts +42 -0
  28. package/dist/src/langfuse.js +837 -0
  29. package/dist/src/limits.d.ts +43 -0
  30. package/dist/src/limits.js +63 -0
  31. package/dist/src/observation.d.ts +24 -0
  32. package/dist/src/observation.js +24 -0
  33. package/dist/src/redaction.d.ts +14 -0
  34. package/dist/src/redaction.js +254 -0
  35. package/dist/src/session-lineage.d.ts +15 -0
  36. package/dist/src/session-lineage.js +87 -0
  37. package/dist/src/source-metadata.d.ts +2 -0
  38. package/dist/src/source-metadata.js +55 -0
  39. package/dist/src/state.d.ts +52 -0
  40. package/dist/src/state.js +144 -0
  41. package/dist/src/types.d.ts +157 -0
  42. package/dist/src/types.js +1 -0
  43. package/dist/src/usage-options.d.ts +27 -0
  44. package/dist/src/usage-options.js +21 -0
  45. package/dist/src/utils.d.ts +61 -0
  46. package/dist/src/utils.js +600 -0
  47. package/dist/src/workflow.d.ts +24 -0
  48. package/dist/src/workflow.js +62 -0
  49. package/examples/workflow-sdk.mjs +56 -0
  50. package/index.ts +47 -13
  51. package/package.json +16 -2
  52. package/src/commands.ts +48 -5
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +63 -33
  55. package/src/handlers/cache.ts +14 -10
  56. package/src/handlers/generation.ts +21 -43
  57. package/src/handlers/session.ts +71 -13
  58. package/src/handlers/tool.ts +12 -8
  59. package/src/langfuse.ts +110 -80
  60. package/src/observation.ts +31 -0
  61. package/src/redaction.ts +145 -10
  62. package/src/session-lineage.ts +98 -0
  63. package/src/state.ts +19 -2
  64. package/src/types.ts +2 -1
  65. package/src/utils.ts +95 -19
  66. package/src/workflow.ts +78 -0
package/README.md CHANGED
@@ -9,9 +9,10 @@ Langfuse observability extension for [Pi Coding Agent](https://github.com/earend
9
9
 
10
10
  ## What This Adds to Pi
11
11
 
12
- - One Langfuse trace per user prompt, grouped by Pi session.
12
+ - By default, one Langfuse trace per user prompt, grouped by Pi session. External workflows can supply their own session and parent span.
13
13
  - Root `agent`, per-request `generation`, and per-tool `tool` observations.
14
- - Final assistant output capture, tool error visibility, and trace-level scores.
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.
@@ -44,6 +45,23 @@ Langfuse observability extension for [Pi Coding Agent](https://github.com/earend
44
45
 
45
46
  4. Open Langfuse and inspect the new trace.
46
47
 
48
+ ## Calling Pi from a workflow
49
+
50
+ Pass the caller’s W3C `traceparent` and Langfuse session ID when launching Pi. The caller and Pi must export to the same Langfuse project. The flag values below are examples; generate the actual carrier from the span that launches Pi.
51
+
52
+ ```sh
53
+ pi -p --langfuse-session-id ticket-482 \
54
+ --langfuse-traceparent 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 \
55
+ "Review this change"
56
+ ```
57
+
58
+ - Supply just `--langfuse-session-id` to group independent traces while keeping separate Pi transcripts. Pi’s own `--session-id` selects a conversation and its history.
59
+ - Supply `--langfuse-traceparent` to attach each `pi-agent` to the caller’s span. Pi writes its IO and five run scores to that observation. Tool failures still score the tool. For session-level usage and cost, pass the caller’s session ID too. An unsampled upstream decision suppresses the entire Pi run, including scores.
60
+ - The flags apply to the initially opened Pi session. New sessions, switches, forks, reloads and shutdown discard them. Idle cache and compaction events have their own traces and use the session-level group. The flags work for a dedicated RPC worker with a fixed parent. Pi RPC has no per-prompt carrier.
61
+ - Session IDs accept 1–200 printable ASCII characters without surrounding whitespace. Invalid IDs or parents produce a warning on stderr; Pi validates each independently. An attached subtree uses OTel export only. Self-hosted deployments that rely on legacy REST recovery can still use session grouping with independent traces. Check the mode with `/langfuse-status`.
62
+
63
+ **Node SDK.** Import `createLangfuseExtension` from `pi-langfuse/sdk` and load the factory once through Pi’s `extensionFactories`. Its synchronous `getRunContext({ piSessionId, messageType })` can return `{ sessionId, traceparent }` for one top-level prompt. The returned object replaces both startup defaults; returning `undefined` uses the startup binding. A thrown callback starts an independent trace. Use a call-scoped binding for idle prompts; retries, steering and queued continuations share the active run. The example shows two essential details: claiming the binding once and awaiting runtime disposal to flush telemetry. [Complete SDK host](./examples/workflow-sdk.mjs)
64
+
47
65
  ## Configuration
48
66
 
49
67
  Langfuse API keys are available in **Langfuse Cloud** -> **Settings** -> **API Keys**.
@@ -165,6 +183,28 @@ defaults shown above. To capture a very large system prompt or big tool
165
183
  payloads in full, raise or disable the relevant limit (e.g.
166
184
  `PI_LANGFUSE_MAX_STRING_LENGTH=off`).
167
185
 
186
+ JSON strings above the string limit are replaced with `[payload too large]` rather
187
+ than cut into invalid JSON that could bypass sensitive-field redaction. Error
188
+ status text uses the same shaping and redaction limits, even when IO capture is disabled.
189
+ Status formatting also masks JSON credentials after Pi/provider error prefixes.
190
+ If surrounding diagnostics make structured error text unparseable, status and
191
+ captured tool-error output use `[unparseable error payload]` instead of the raw text.
192
+ The same protection applies to unparseable JSON fragments with sensitive field
193
+ names replayed inside later provider requests; ordinary surrounding text is retained
194
+ when it contains no sensitive JSON fields.
195
+ String-only capture paths (including assistant replies, compaction summaries, and
196
+ custom IDs) replace text containing unmasked sensitive JSON fields with
197
+ `[REDACTED_SECRET]`. Already-masked fields and ordinary text stay intact; captured
198
+ output remains a string.
199
+ This check also decodes nested JSON strings within the existing depth/node limits.
200
+ Ambiguous escaped text or exhausted inspection limits hide the string rather than expose unchecked content.
201
+ Credential assignments are masked with or without quotes, including escaped or
202
+ unterminated values. Escaped quotes in serialized text protect the entire value,
203
+ including spaces.
204
+ Ambiguous single-quote escaping can also mask the remaining diagnostic text.
205
+ Known tokens are masked before string truncation so a token
206
+ crossing a capture limit cannot escape detection as a shorter fragment.
207
+
168
208
  The REST fallback ingestion is chunked so each request body stays well below
169
209
  the Langfuse gateway's payload limit (~4.5MB). These knobs control the chunk
170
210
  budget and a hard ceiling for the whole fallback payload:
@@ -177,6 +217,13 @@ export PI_LANGFUSE_MAX_FALLBACK_TOTAL_BYTES=33554432 # whole-payload ceiling, d
177
217
 
178
218
  When the accumulated fallback payload exceeds the 32MB ceiling, ingestion is
179
219
  skipped with a warning instead of attempting an unrecoverably large upload.
220
+ An individual event above the per-request budget is skipped with a size-only
221
+ warning; the remaining events are still sent. Raise capture limits with this
222
+ per-event ceiling in mind.
223
+ Fallback checks each trace separately within one visibility window and restores
224
+ only missing traces, preserving each trace's session, user, name, and metadata.
225
+ Visibility polling uses at most three quarters of the remaining shutdown time,
226
+ leaving the rest for ingestion even when SDK cleanup was slow.
180
227
 
181
228
  ### Reasoning tokens
182
229
 
@@ -266,11 +313,14 @@ To verify the Langfuse host and API keys from inside Pi, run:
266
313
  ```
267
314
 
268
315
  This command makes a timeout-bounded authenticated request to Langfuse and, if it succeeds, sends a small test trace.
316
+ The result also probes the observations read API. It tries `v2/observations` first and falls back to the legacy
317
+ observations API only when v2 returns 404 or 405, so older servers remain supported. Read failures produce a
318
+ warning and do not block the test trace. This checks endpoint availability, not whether the new trace is queryable.
319
+ Langfuse v4 in `events_only` mode removes legacy reads; the compaction and error-text fixes do not require v4.
269
320
 
270
321
  ## What Appears in Langfuse
271
322
 
272
- - Each Pi session gets its own Langfuse session ID.
273
- - Each user prompt within that session becomes a separate trace.
323
+ - By default, each Pi session supplies its Langfuse session ID and each prompt creates a separate trace.
274
324
  - The trace contains the final assistant output shown in Pi.
275
325
  - Tool runs appear as tool observations with arguments, results, and error state.
276
326
  Pi 1.0 nested calls (including codemode tools) are parented by `parentToolCallId`.
@@ -278,6 +328,9 @@ This command makes a timeout-bounded authenticated request to Langfuse and, if i
278
328
  include descendants are not ingested again. Pi's tool usage does not identify each nested model,
279
329
  so these aggregate generations have no inferred model name or price.
280
330
  - LLM requests appear as generation observations, including usage and cost when the provider exposes them.
331
+ Failed assistant messages are marked `ERROR` with a redacted `statusMessage`, including streaming
332
+ failures after HTTP 200 and failures without provider hooks. User-aborted generations are `WARNING`.
333
+ A successful final assistant response clears an earlier transient HTTP error from an internal retry.
281
334
  Reasoning tokens are reported as their own usage bucket when `PI_LANGFUSE_SPLIT_REASONING_TOKENS` is enabled.
282
335
  Virtual routing preserves `selectedModel`/`selectedProvider` alongside `actualModel`/`actualProvider`;
283
336
  the generation model and `provider` metadata use the actual identity when available.
@@ -289,7 +342,12 @@ This command makes a timeout-bounded authenticated request to Langfuse and, if i
289
342
  - Cache-warming decisions and persisted `cache_warm` usage are reported, including standalone session-grouped
290
343
  traces when warming happens while no user-request trace is active.
291
344
  - Compaction is recorded as `session-compaction`, with a nested `compaction-summary` generation when usage is available.
292
- - Trace-level scores include tool counts, tool success rate, and whether the run had errors.
345
+ Both compaction events are recorded even when no agent run is active — recovery compaction often lands after the
346
+ run settled — and then form their own trace named `pi-session` inside the same session.
347
+ - On Pi versions that emit `session_compact_failed`, failed compactions appear as
348
+ `session-compaction-failed` events: `ERROR` for failures and `WARNING` for cancellations.
349
+ Pi reports a cancelling extension as an abort and may omit its original error text.
350
+ - Run scores include tool counts, tool success rate, and whether the run had tool errors. They target the trace for independent runs and the Pi agent observation for attached runs.
293
351
 
294
352
  The package also includes a Langfuse CLI skill, so Langfuse data can be queried directly from Pi:
295
353
 
@@ -338,6 +396,30 @@ Earlier versions emitted `git_commit`, branch, remote, owner, repository, and re
338
396
 
339
397
  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
398
 
399
+ ## Session Lineage
400
+
401
+ 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:
402
+
403
+ ```json
404
+ {
405
+ "parentSessionId": "01a1639b-58c5-729a-8315-f17b045ccd28",
406
+ "sessionKind": "fork"
407
+ }
408
+ ```
409
+
410
+ `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.
411
+
412
+ 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:
413
+
414
+ ```bash
415
+ curl -s -u "$LANGFUSE_PUBLIC_KEY:$LANGFUSE_SECRET_KEY" \
416
+ "$LANGFUSE_HOST/api/public/v2/observations?sessionId=<child-session-id>&fields=core,metadata"
417
+ ```
418
+
419
+ 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.
420
+ Standalone compaction and idle cache-warming traces retain these links, including
421
+ cache-warming usage and costs, through both OTel export and REST fallback.
422
+
341
423
  ## Troubleshooting
342
424
 
343
425
  ### No traces appearing?
package/README_CN.md CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  ## 这个插件提供什么
11
11
 
12
- - 每个用户提示词对应一个 Langfuse trace,并按 Pi 会话分组。
12
+ - 默认每个用户提示词对应一个 Langfuse trace,按 Pi 会话分组。外层工作流也可以指定 session 和父 span。
13
13
  - 为根代理创建 `agent` 观察节点,为每次模型请求创建 `generation`,为每次工具调用创建 `tool`。
14
14
  - 记录最终助手输出、工具错误状态和追踪级别分数。
15
15
  - 提供输入、输出、工具 I/O、system prompt 和 cwd 的隐私采集开关。
@@ -44,6 +44,23 @@
44
44
 
45
45
  4. 打开 Langfuse,查看新生成的 trace。
46
46
 
47
+ ## 从外层工作流调用 Pi
48
+
49
+ 启动 Pi 时可传入外层调用的 W3C `traceparent` 和 Langfuse session ID。调用方与 Pi 需导出到同一个 Langfuse 项目。下面使用示例 ID,实际接入时请从启动 Pi 的那个 span 生成 carrier。
50
+
51
+ ```sh
52
+ pi -p --langfuse-session-id ticket-482 \
53
+ --langfuse-traceparent 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 \
54
+ "评审这次改动"
55
+ ```
56
+
57
+ - 只传 `--langfuse-session-id` 时,多个独立 trace 归入同一业务会话,各自保留 Pi 对话历史。Pi 自身的 `--session-id` 用于选择或恢复对话。
58
+ - 传入 `--langfuse-traceparent` 时,每个 `pi-agent` 成为指定 span 的直接子节点。Pi 的输入输出和五项运行评分归属本次节点,工具错误评分归属具体工具。需要按外层 session 统计用量时,同时传入一致的 session ID。上游未采样时,整次 Pi 运行及其分数均跳过。
59
+ - 参数绑定到启动时打开的 Pi 会话,新建、切换、fork、重载和退出都会解除绑定。运行外的 cache 与 compaction 使用独立 trace,沿用会话级分组。专属 RPC 进程可以固定一个父节点;Pi RPC 目前没有逐 prompt 的 carrier 字段。
60
+ - Session ID 接受 1–200 个可打印 ASCII 字符,首尾不能有空白。两个字段独立校验,非法输入会在 stderr 给出原因。挂入外层的子树通过 OTel 导出。依赖旧 REST 补传的自托管环境可使用独立 trace 加 session 分组。使用 `/langfuse-status` 查看当前模式。
61
+
62
+ **Node SDK** 可从 `pi-langfuse/sdk` 导入 `createLangfuseExtension`,通过 Pi 的 `extensionFactories` 加载一次。同步回调 `getRunContext({ piSessionId, messageType })` 返回的 `{ sessionId, traceparent }` 整体覆盖启动绑定;返回 `undefined` 时沿用启动绑定,抛错时建立独立 trace。在空闲会话提交顶层 prompt 时提供逐次上下文,重试、steer 和队列续跑沿用当前运行。示例包含一次性认领、清理调用上下文,以及等待关闭时导出遥测的写法。[完整 SDK 宿主示例](./examples/workflow-sdk.mjs)
63
+
47
64
  ## 配置
48
65
 
49
66
  Langfuse API 密钥可在 **Langfuse Cloud** -> **Settings** -> **API Keys** 中获取。
@@ -159,6 +176,18 @@ export PI_LANGFUSE_MAX_PAYLOAD_NODES=2000 # 单个负载的最大总节
159
176
  任意上限设置为 `0`、`off`、`none` 或 `unlimited` 即表示关闭该限制(采集完整值);未设置或非法值回退到上方默认值。
160
177
  若想完整采集很大的 system prompt 或工具负载,可以调高或关闭相关限制(例如 `PI_LANGFUSE_MAX_STRING_LENGTH=off`)。
161
178
 
179
+ 若错误文本中的 JSON 因前后附加的诊断信息而无法解析,状态和采集的工具错误输出会使用
180
+ `[unparseable error payload]`,避免原始敏感字段泄露。
181
+ 后续模型请求中重放的错误文本也会检查敏感 JSON 字段;不含这些字段的普通文本保持不变。
182
+ 纯字符串采集路径(包括助手回复、压缩摘要和自定义 ID)会将含有未脱敏 JSON 敏感字段的文本
183
+ 替换为 `[REDACTED_SECRET]`。已脱敏字段和普通文本保持不变,输出仍为字符串。
184
+ 该检查还会在现有深度和节点数量限制内解码嵌套 JSON 字符串。转义内容无法安全解析或检查预算耗尽时,
185
+ 会隐藏整个字符串,避免暴露未经检查的内容。
186
+ 凭据赋值无论是否带引号都会脱敏,包括转义或未闭合的引号。序列化文本中的转义引号会保护整个值,包括空格。
187
+ 如果单引号的转义层级不明确,后续诊断文本也可能被隐藏。
188
+ 已知格式的令牌会在字符串截断前
189
+ 脱敏,避免跨越采集长度上限的令牌因变成短片段而绕过检测。
190
+
162
191
  REST 回退摄取会按字节切分,保证每个请求体都远低于 Langfuse 网关的负载限制(约 4.5MB)。以下变量控制切分预算
163
192
  与整个回退负载的硬上限:
164
193
 
@@ -169,6 +198,8 @@ export PI_LANGFUSE_MAX_FALLBACK_TOTAL_BYTES=33554432 # 整体负载上限,默
169
198
  ```
170
199
 
171
200
  当累积的回退负载超过 32MB 上限时,会跳过摄取并给出告警,而不是尝试一次注定失败的超大上传。
201
+ 单个事件超过单次请求体预算时,会跳过该事件并输出仅包含大小信息的告警;其余事件仍会发送。
202
+ 调高采集上限时,也需要注意这个单事件限制。
172
203
 
173
204
  ### 推理(reasoning)token
174
205
 
@@ -246,12 +277,14 @@ pi list
246
277
  /langfuse-test
247
278
  ```
248
279
 
249
- 该命令会先发起一次带超时的认证请求;认证通过后,再发送一条小的测试 trace。
280
+ 该命令会先发起一次带超时的认证请求;认证通过后,再发送一条小的测试 trace。返回结果还会说明
281
+ 读取接口是否可用:先检查 `v2/observations`,仅当它返回 404 或 405 时回退到旧版 observations API,以兼容旧服务器。
282
+ 读取失败会显示警告,但不会阻止发送测试 trace。该检查只验证接口可用性,不保证新 trace 已可查询。
283
+ Langfuse v4 的 `events_only` 模式移除了旧版读取接口;compaction 和错误文本修复本身不要求 v4。
250
284
 
251
285
  ## 在 Langfuse 中会看到什么
252
286
 
253
- - 每个 Pi 会话对应一个独立的 Langfuse session ID。
254
- - 该会话中的每个用户提示词都会生成一个独立 trace。
287
+ - 默认使用 Pi 会话 ID 分组,每个提示词生成一条独立 trace。
255
288
  - trace 中会包含 Pi 实际显示的最终助手回复。
256
289
  - 工具执行会以工具观察节点展示参数、结果和错误状态。
257
290
  Pi 1.0 的嵌套调用(含 codemode 内部工具)按 `parentToolCallId` 建立父子关系。
@@ -268,7 +301,10 @@ pi list
268
301
  - cache warming 决策及持久化的 `cache_warm` 用量会被记录;若 warming 发生时没有活动的用户请求 trace,
269
302
  会创建按相同 session 分组的独立 trace。
270
303
  - compaction 会记录为 `session-compaction`;若存在摘要用量,则包含 `compaction-summary` generation。
271
- - trace 级别会记录工具调用次数、工具成功率和是否出现错误。
304
+ 即使没有活动的 agent run(恢复性 compaction 常发生在 run 结束之后)也会记录 compaction 事件;
305
+ 此时它们会在同一 session 下形成名为 `pi-session` 的独立 trace。发出 `session_compact_failed` 的 Pi 版本
306
+ 会将失败的 compaction 记为 `session-compaction-failed`:失败为 `ERROR`,取消为 `WARNING`。
307
+ - 运行评分包括工具调用次数、工具成功率和错误情况。独立运行把分数挂在 trace 上,接入外层时挂在本次 Pi agent 节点上。
272
308
 
273
309
  此包还包含一个内置 Langfuse 技能,可直接在 Pi 中查询 Langfuse 数据:
274
310
 
@@ -317,6 +353,28 @@ export OTEL_RESOURCE_ATTRIBUTES="service.version=1.2.3,vcs.repository.name=publi
317
353
 
318
354
  取消设置 `LANGFUSE_CAPTURE_SOURCE_METADATA` 可立即停止采集。迁移期间只有在必须保留旧 schema 时才固定到 `pi-langfuse@1.5.12`;这样也会恢复旧版本更宽泛的默认源码披露。
319
355
 
356
+ ## 会话血缘
357
+
358
+ Pi 会把派生会话的来源文件写入会话头,扩展通过 `sessionManager.getHeader()` 读取它。这类派生会话的所有 observation 都会携带:
359
+
360
+ ```json
361
+ {
362
+ "parentSessionId": "01a1639b-58c5-729a-8315-f17b045ccd28",
363
+ "sessionKind": "fork"
364
+ }
365
+ ```
366
+
367
+ 当进程在 `pi-subagents` 下运行时(`PI_SUBAGENT_CHILD=1`)`sessionKind` 为 `subagent`,否则为 `fork`。该环境变量是 `pi-subagents` 的实现细节,不是本包持有的契约:子进程丢失该变量时只会标成 `fork`,即只有标签会降级——父链接本身取自会话头,始终是精确的。
368
+
369
+ Langfuse 中没有会话与会话的关联关系,因此会话仍然彼此独立,只能通过 metadata 关联。解析出子会话 id 后例如:
370
+
371
+ ```bash
372
+ curl -s -u "$LANGFUSE_PUBLIC_KEY:$LANGFUSE_SECRET_KEY" \
373
+ "$LANGFUSE_HOST/api/public/v2/observations?sessionId=<child-session-id>&fields=core,metadata"
374
+ ```
375
+
376
+ 根会话不携带这两个键。扩展只读取父会话 id,除指明该 id 的首行外不会打开父会话转录。
377
+
320
378
  ## 故障排除
321
379
 
322
380
  ### 没有看到 trace
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Langfuse Observability Extension for Pi Coding Agent
3
+ *
4
+ * Records each Pi run in its own trace or under an explicit workflow parent:
5
+ * - root agent observation for the user prompt and final assistant response
6
+ * - one generation observation per provider request
7
+ * - one tool observation per tool call, keyed by toolCallId
8
+ */
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import { type LangfuseExtensionOptions } from "./src/workflow.js";
11
+ export type { LangfuseExtensionOptions, WorkflowContext } from "./src/workflow.js";
12
+ export declare function createLangfuseExtension(options?: LangfuseExtensionOptions): (pi: ExtensionAPI) => Promise<void>;
13
+ declare const _default: (pi: ExtensionAPI) => Promise<void>;
14
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Langfuse Observability Extension for Pi Coding Agent
3
+ *
4
+ * Records each Pi run in its own trace or under an explicit workflow parent:
5
+ * - root agent observation for the user prompt and final assistant response
6
+ * - one generation observation per provider request
7
+ * - one tool observation per tool call, keyed by toolCallId
8
+ */
9
+ import { basename } from "node:path";
10
+ import { parseWorkflowContext, isUnsampled, warnWorkflow } from "./src/workflow.js";
11
+ import { state, getSessionRunState, resetRunState, runWithSession, setCurrentSession } from "./src/state.js";
12
+ import { bindSessionLineage } from "./src/session-lineage.js";
13
+ import { ensureConfig, promptForConfig, loadConfig } from "./src/config.js";
14
+ import { shutdownRuntime } from "./src/langfuse.js";
15
+ import { handleLangfusePrivacyCommand, handleLangfuseStatusCommand, handleLangfuseTestCommand } from "./src/commands.js";
16
+ import { getMessageFromEvent, extractAssistantOutput } from "./src/utils.js";
17
+ import { startAgentRun, finishAgentRun, finishAgentAttempt, cancelAgentRun, recordSystemPrompt, startAgentAttempt, } from "./src/handlers/agent.js";
18
+ import { startTurnObservation, finishTurnObservation } from "./src/handlers/turn.js";
19
+ import { initializeSystemStateTracking, recordSystemState } from "./src/handlers/system-state.js";
20
+ import { initializeUsageTracking, recordCacheWarmingDecision, recordNewUsageEntries, } from "./src/handlers/cache.js";
21
+ import { recordSessionCompaction, recordSessionCompactionFailure } from "./src/handlers/session.js";
22
+ import { startGeneration, updateGenerationMetadata, finishGenerationFromMessage, createFallbackGenerationFromTurn, recordTTFT, recordGenerationIdentity, } from "./src/handlers/generation.js";
23
+ import { startToolObservation, finishToolObservation, } from "./src/handlers/tool.js";
24
+ // ============================================
25
+ // Extension
26
+ // ============================================
27
+ export function createLangfuseExtension(options = {}) {
28
+ return (pi) => registerExtension(pi, options);
29
+ }
30
+ export default createLangfuseExtension();
31
+ async function registerExtension(pi, options) {
32
+ const asRecord = (value) => value;
33
+ if (!state.config) {
34
+ state.config = loadConfig();
35
+ }
36
+ if (state.config) {
37
+ console.error("📊 Langfuse: Tracing enabled →", state.config.host);
38
+ }
39
+ else {
40
+ console.error("📊 Langfuse: Waiting for first-run setup");
41
+ }
42
+ pi.registerFlag("langfuse-session-id", { type: "string", description: "Group observations under this Langfuse workflow session" });
43
+ pi.registerFlag("langfuse-traceparent", { type: "string", description: "Attach runs to this W3C traceparent for the initial Pi session" });
44
+ pi.registerCommand("langfuse-setup", {
45
+ description: "Configure Langfuse API keys for this extension",
46
+ handler: async (_args, ctx) => {
47
+ await promptForConfig(ctx);
48
+ },
49
+ });
50
+ pi.registerCommand("langfuse-test", {
51
+ description: "Send a test trace to Langfuse to verify configuration",
52
+ handler: async (args, ctx) => {
53
+ await handleLangfuseTestCommand(String(args ?? ""), ctx);
54
+ },
55
+ });
56
+ pi.registerCommand("langfuse-status", {
57
+ description: "Show Langfuse configuration and runtime status",
58
+ handler: async (args, ctx) => {
59
+ await withSession(ctx, () => handleLangfuseStatusCommand(String(args ?? ""), ctx));
60
+ },
61
+ });
62
+ pi.registerCommand("langfuse-privacy", {
63
+ description: "View or set Langfuse telemetry privacy preset",
64
+ handler: async (args, ctx) => {
65
+ await handleLangfusePrivacyCommand(String(args ?? ""), ctx);
66
+ },
67
+ });
68
+ const getSessionId = (ctx) => {
69
+ try {
70
+ const sessionManager = ctx?.sessionManager;
71
+ const sessionId = sessionManager?.getSessionId?.();
72
+ if (typeof sessionId === "string" && sessionId) {
73
+ return sessionId;
74
+ }
75
+ const sessionFile = sessionManager?.getSessionFile?.();
76
+ return typeof sessionFile === "string" && sessionFile
77
+ ? basename(sessionFile, ".jsonl")
78
+ : undefined;
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ };
84
+ const withSession = (ctx, fn) => runWithSession(getSessionId(ctx), fn);
85
+ pi.on("session_start", async (event, ctx) => withSession(ctx, async () => {
86
+ resetRunState();
87
+ const session = getSessionRunState();
88
+ session.instance = Symbol("Pi session");
89
+ session.startupBinding = undefined;
90
+ session.workflowWarnings = undefined;
91
+ if (event.reason === "startup") {
92
+ const sessionId = pi.getFlag("langfuse-session-id");
93
+ const traceparent = pi.getFlag("langfuse-traceparent");
94
+ if (state.currentSessionId)
95
+ session.startupBinding = parseWorkflowContext({ sessionId, traceparent });
96
+ else if (sessionId !== undefined || traceparent !== undefined)
97
+ warnWorkflow("Ignoring workflow flags without a Pi session identity.");
98
+ }
99
+ state.setupAttemptedThisSession = false;
100
+ await ensureConfig(ctx);
101
+ if (getSessionRunState() !== session)
102
+ return;
103
+ bindSessionLineage(ctx?.sessionManager);
104
+ initializeSystemStateTracking(ctx);
105
+ initializeUsageTracking(ctx);
106
+ }));
107
+ pi.on("model_select", async (event, ctx) => withSession(ctx, async () => {
108
+ state.currentModel = event.model?.id || "";
109
+ state.currentProvider = event.model?.provider || "";
110
+ }));
111
+ pi.on("before_agent_start", async (event, ctx) => withSession(ctx, async () => {
112
+ await startAgentRun(asRecord(event), ctx, options.getRunContext);
113
+ }));
114
+ pi.on("agent_start", async (event, ctx) => withSession(ctx, async () => {
115
+ const session = getSessionRunState();
116
+ if (!session.agentState?.root) {
117
+ await startAgentRun(asRecord(event), ctx);
118
+ if (getSessionRunState() !== session)
119
+ return;
120
+ }
121
+ if (session.tracingDisabled)
122
+ return;
123
+ await startAgentAttempt();
124
+ // The system prompt is only final here: before_agent_start handlers that
125
+ // run after this extension may still rewrite it.
126
+ await recordSystemPrompt(ctx);
127
+ await recordSystemState(ctx, pi.getActiveTools());
128
+ }));
129
+ pi.on("cache_warming_decision", async (event, ctx) => withSession(ctx, async () => {
130
+ await recordNewUsageEntries(ctx);
131
+ await recordCacheWarmingDecision(asRecord(event), ctx);
132
+ }));
133
+ pi.on("turn_start", async (event, ctx) => withSession(ctx, async () => {
134
+ await startTurnObservation(asRecord(event));
135
+ }));
136
+ pi.on("before_provider_request", async (event, ctx) => withSession(ctx, async () => {
137
+ await recordSystemState(ctx, pi.getActiveTools(), false);
138
+ await startGeneration(asRecord(event), ctx.model);
139
+ }));
140
+ pi.on("after_provider_response", async (event, ctx) => withSession(ctx, async () => {
141
+ updateGenerationMetadata(asRecord(event));
142
+ }));
143
+ pi.on("provider_stream_event", (event, ctx) => withSession(ctx, () => {
144
+ recordGenerationIdentity(asRecord(event));
145
+ }));
146
+ pi.on("message_update", async (event, ctx) => withSession(ctx, async () => {
147
+ recordTTFT(asRecord(event));
148
+ const message = getMessageFromEvent(asRecord(event));
149
+ if (message?.role === "assistant" && state.agentState) {
150
+ state.agentState.latestAssistantOutput = extractAssistantOutput(message);
151
+ }
152
+ }));
153
+ pi.on("message_end", async (event, ctx) => withSession(ctx, async () => {
154
+ await finishGenerationFromMessage(asRecord(event));
155
+ }));
156
+ pi.on("tool_execution_start", async (event, ctx) => withSession(ctx, async () => {
157
+ await startToolObservation(asRecord(event));
158
+ }));
159
+ pi.on("tool_call", async (event, ctx) => withSession(ctx, async () => {
160
+ await startToolObservation(asRecord(event));
161
+ }));
162
+ pi.on("tool_result", async (event, ctx) => withSession(ctx, async () => {
163
+ await finishToolObservation(asRecord(event));
164
+ }));
165
+ pi.on("tool_execution_end", async (event, ctx) => withSession(ctx, async () => {
166
+ await finishToolObservation(asRecord(event));
167
+ }));
168
+ pi.on("turn_end", async (event, ctx) => withSession(ctx, async () => {
169
+ state.turnCount++;
170
+ const record = asRecord(event);
171
+ const message = getMessageFromEvent(record);
172
+ if (message?.role === "assistant") {
173
+ await createFallbackGenerationFromTurn(record, message);
174
+ await finishGenerationFromMessage(record);
175
+ }
176
+ finishTurnObservation(record);
177
+ }));
178
+ pi.on("agent_end", async (event, ctx) => withSession(ctx, async () => {
179
+ finishAgentAttempt(asRecord(event));
180
+ }));
181
+ pi.on("agent_settled", async (_event, ctx) => withSession(ctx, async () => {
182
+ if (isUnsampled(getSessionRunState().runBinding))
183
+ initializeUsageTracking(ctx);
184
+ await finishAgentRun();
185
+ }));
186
+ const handleSessionInterruption = (reason) => {
187
+ cancelAgentRun(reason);
188
+ };
189
+ pi.on("session_before_switch", async (_event, ctx) => {
190
+ const sessionId = getSessionId(ctx);
191
+ if (sessionId) {
192
+ setCurrentSession(sessionId);
193
+ }
194
+ });
195
+ pi.on("session_before_fork", async (_event, ctx) => {
196
+ const sessionId = getSessionId(ctx);
197
+ if (sessionId) {
198
+ setCurrentSession(sessionId);
199
+ }
200
+ });
201
+ pi.on("session_compact", async (event, ctx) => withSession(ctx, async () => {
202
+ await recordSessionCompaction(asRecord(event));
203
+ }));
204
+ pi.on("session_compact_failed", async (event, ctx) => withSession(ctx, async () => {
205
+ await recordSessionCompactionFailure(asRecord(event));
206
+ }));
207
+ pi.on("session_shutdown", async (_event, ctx) => withSession(ctx, async () => {
208
+ const instance = getSessionRunState().instance;
209
+ await recordNewUsageEntries(ctx);
210
+ if (getSessionRunState().instance !== instance)
211
+ return;
212
+ handleSessionInterruption("Session shutdown before agent completed");
213
+ getSessionRunState().startupBinding = undefined;
214
+ await shutdownRuntime();
215
+ }));
216
+ }
@@ -0,0 +1,43 @@
1
+ import { type RedactOptions } from "./redaction.js";
2
+ export interface CapturePolicy {
3
+ readonly captureInputs: boolean;
4
+ readonly captureOutputs: boolean;
5
+ readonly captureToolIo: boolean;
6
+ readonly captureSystemPrompt: boolean;
7
+ readonly captureCwd: boolean;
8
+ readonly captureSourceMetadata: boolean;
9
+ /**
10
+ * Capture local absolute paths verbatim. Off in every preset, like
11
+ * `captureSourceMetadata`: paths are replaced with `[PATH_HASH:...]` unless
12
+ * `LANGFUSE_CAPTURE_PATHS` opts in explicitly.
13
+ */
14
+ readonly capturePaths: boolean;
15
+ }
16
+ /** Redaction options implied by a policy, so path rendering follows the same switch everywhere. */
17
+ export declare function redactOptionsFor(policy: CapturePolicy): Partial<RedactOptions>;
18
+ export type PrivacyPreset = "metadata-only" | "prompts-only" | "conversations" | "full-debug";
19
+ export type EnvLike = Readonly<Record<string, string | undefined>>;
20
+ export interface RawTelemetryPayload {
21
+ input?: unknown;
22
+ output?: unknown;
23
+ toolInput?: unknown;
24
+ toolOutput?: unknown;
25
+ systemPrompt?: unknown;
26
+ metadata?: Record<string, unknown>;
27
+ }
28
+ export interface CapturedTelemetryPayload {
29
+ input?: unknown;
30
+ output?: unknown;
31
+ toolInput?: unknown;
32
+ toolOutput?: unknown;
33
+ systemPrompt?: unknown;
34
+ metadata?: Record<string, unknown>;
35
+ }
36
+ /**
37
+ * Parse a boolean env flag. `1/true/yes/on` and `0/false/no/off` are
38
+ * case-insensitive; anything else (including unset) is `undefined` so the
39
+ * caller keeps its default.
40
+ */
41
+ export declare function parseFlag(value: string | undefined): boolean | undefined;
42
+ export declare function createCapturePolicy(env?: EnvLike): CapturePolicy;
43
+ export declare function applyCapturePolicy(payload: RawTelemetryPayload, policy?: CapturePolicy): CapturedTelemetryPayload;