pi-langfuse 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +20 -4
  2. package/README_CN.md +20 -4
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.js +216 -0
  5. package/dist/src/capture-policy.d.ts +43 -0
  6. package/dist/src/capture-policy.js +125 -0
  7. package/dist/src/commands.d.ts +25 -0
  8. package/dist/src/commands.js +374 -0
  9. package/dist/src/config.d.ts +13 -0
  10. package/dist/src/config.js +157 -0
  11. package/dist/src/constants.d.ts +9 -0
  12. package/dist/src/constants.js +11 -0
  13. package/dist/src/handlers/agent.d.ts +18 -0
  14. package/dist/src/handlers/agent.js +310 -0
  15. package/dist/src/handlers/cache.d.ts +5 -0
  16. package/dist/src/handlers/cache.js +134 -0
  17. package/dist/src/handlers/generation.d.ts +9 -0
  18. package/dist/src/handlers/generation.js +249 -0
  19. package/dist/src/handlers/session.d.ts +4 -0
  20. package/dist/src/handlers/session.js +121 -0
  21. package/dist/src/handlers/system-state.d.ts +3 -0
  22. package/dist/src/handlers/system-state.js +185 -0
  23. package/dist/src/handlers/tool.d.ts +3 -0
  24. package/dist/src/handlers/tool.js +168 -0
  25. package/dist/src/handlers/turn.d.ts +2 -0
  26. package/dist/src/handlers/turn.js +48 -0
  27. package/dist/src/langfuse.d.ts +42 -0
  28. package/dist/src/langfuse.js +837 -0
  29. package/dist/src/limits.d.ts +43 -0
  30. package/dist/src/limits.js +63 -0
  31. package/dist/src/observation.d.ts +24 -0
  32. package/dist/src/observation.js +24 -0
  33. package/dist/src/redaction.d.ts +14 -0
  34. package/dist/src/redaction.js +254 -0
  35. package/dist/src/session-lineage.d.ts +15 -0
  36. package/dist/src/session-lineage.js +87 -0
  37. package/dist/src/source-metadata.d.ts +2 -0
  38. package/dist/src/source-metadata.js +55 -0
  39. package/dist/src/state.d.ts +52 -0
  40. package/dist/src/state.js +144 -0
  41. package/dist/src/types.d.ts +157 -0
  42. package/dist/src/types.js +1 -0
  43. package/dist/src/usage-options.d.ts +27 -0
  44. package/dist/src/usage-options.js +21 -0
  45. package/dist/src/utils.d.ts +61 -0
  46. package/dist/src/utils.js +600 -0
  47. package/dist/src/workflow.d.ts +24 -0
  48. package/dist/src/workflow.js +62 -0
  49. package/examples/workflow-sdk.mjs +56 -0
  50. package/index.ts +40 -12
  51. package/package.json +12 -1
  52. package/src/commands.ts +14 -3
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +60 -32
  55. package/src/handlers/cache.ts +12 -10
  56. package/src/handlers/session.ts +2 -2
  57. package/src/handlers/tool.ts +6 -1
  58. package/src/langfuse.ts +35 -16
  59. package/src/observation.ts +4 -0
  60. package/src/state.ts +12 -2
  61. package/src/types.ts +1 -1
  62. package/src/workflow.ts +78 -0
package/README.md CHANGED
@@ -9,7 +9,7 @@ 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
14
  - Foreground child sessions keep their SDK exporters isolated, so parent telemetry continues after a child exits.
15
15
  - Final assistant output capture, generation/tool error visibility, and trace-level scores.
@@ -45,6 +45,23 @@ Langfuse observability extension for [Pi Coding Agent](https://github.com/earend
45
45
 
46
46
  4. Open Langfuse and inspect the new trace.
47
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
+
48
65
  ## Configuration
49
66
 
50
67
  Langfuse API keys are available in **Langfuse Cloud** -> **Settings** -> **API Keys**.
@@ -303,8 +320,7 @@ Langfuse v4 in `events_only` mode removes legacy reads; the compaction and error
303
320
 
304
321
  ## What Appears in Langfuse
305
322
 
306
- - Each Pi session gets its own Langfuse session ID.
307
- - 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.
308
324
  - The trace contains the final assistant output shown in Pi.
309
325
  - Tool runs appear as tool observations with arguments, results, and error state.
310
326
  Pi 1.0 nested calls (including codemode tools) are parented by `parentToolCallId`.
@@ -331,7 +347,7 @@ Langfuse v4 in `events_only` mode removes legacy reads; the compaction and error
331
347
  - On Pi versions that emit `session_compact_failed`, failed compactions appear as
332
348
  `session-compaction-failed` events: `ERROR` for failures and `WARNING` for cancellations.
333
349
  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.
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.
335
351
 
336
352
  The package also includes a Langfuse CLI skill, so Langfuse data can be queried directly from Pi:
337
353
 
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** 中获取。
@@ -267,8 +284,7 @@ Langfuse v4 的 `events_only` 模式移除了旧版读取接口;compaction 和
267
284
 
268
285
  ## 在 Langfuse 中会看到什么
269
286
 
270
- - 每个 Pi 会话对应一个独立的 Langfuse session ID。
271
- - 该会话中的每个用户提示词都会生成一个独立 trace。
287
+ - 默认使用 Pi 会话 ID 分组,每个提示词生成一条独立 trace。
272
288
  - trace 中会包含 Pi 实际显示的最终助手回复。
273
289
  - 工具执行会以工具观察节点展示参数、结果和错误状态。
274
290
  Pi 1.0 的嵌套调用(含 codemode 内部工具)按 `parentToolCallId` 建立父子关系。
@@ -288,7 +304,7 @@ Langfuse v4 的 `events_only` 模式移除了旧版读取接口;compaction 和
288
304
  即使没有活动的 agent run(恢复性 compaction 常发生在 run 结束之后)也会记录 compaction 事件;
289
305
  此时它们会在同一 session 下形成名为 `pi-session` 的独立 trace。发出 `session_compact_failed` 的 Pi 版本
290
306
  会将失败的 compaction 记为 `session-compaction-failed`:失败为 `ERROR`,取消为 `WARNING`。
291
- - trace 级别会记录工具调用次数、工具成功率和是否出现错误。
307
+ - 运行评分包括工具调用次数、工具成功率和错误情况。独立运行把分数挂在 trace 上,接入外层时挂在本次 Pi agent 节点上。
292
308
 
293
309
  此包还包含一个内置 Langfuse 技能,可直接在 Pi 中查询 Langfuse 数据:
294
310
 
@@ -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;
@@ -0,0 +1,125 @@
1
+ import { hashPath, redactValue } from "./redaction.js";
2
+ /** Redaction options implied by a policy, so path rendering follows the same switch everywhere. */
3
+ export function redactOptionsFor(policy) {
4
+ return { redactPaths: !policy.capturePaths };
5
+ }
6
+ const PRESETS = {
7
+ "metadata-only": {
8
+ captureInputs: false,
9
+ captureOutputs: false,
10
+ captureToolIo: false,
11
+ captureSystemPrompt: false,
12
+ captureCwd: false,
13
+ captureSourceMetadata: false,
14
+ capturePaths: false,
15
+ },
16
+ "prompts-only": {
17
+ captureInputs: true,
18
+ captureOutputs: false,
19
+ captureToolIo: false,
20
+ captureSystemPrompt: false,
21
+ captureCwd: false,
22
+ captureSourceMetadata: false,
23
+ capturePaths: false,
24
+ },
25
+ conversations: {
26
+ captureInputs: true,
27
+ captureOutputs: true,
28
+ captureToolIo: false,
29
+ captureSystemPrompt: false,
30
+ captureCwd: false,
31
+ captureSourceMetadata: false,
32
+ capturePaths: false,
33
+ },
34
+ "full-debug": {
35
+ captureInputs: true,
36
+ captureOutputs: true,
37
+ captureToolIo: true,
38
+ captureSystemPrompt: true,
39
+ captureCwd: true,
40
+ captureSourceMetadata: false,
41
+ capturePaths: false,
42
+ },
43
+ };
44
+ const FLAG_TO_FIELD = {
45
+ LANGFUSE_CAPTURE_INPUTS: "captureInputs",
46
+ LANGFUSE_CAPTURE_OUTPUTS: "captureOutputs",
47
+ LANGFUSE_CAPTURE_TOOL_IO: "captureToolIo",
48
+ LANGFUSE_CAPTURE_SYSTEM_PROMPT: "captureSystemPrompt",
49
+ LANGFUSE_CAPTURE_CWD: "captureCwd",
50
+ LANGFUSE_CAPTURE_SOURCE_METADATA: "captureSourceMetadata",
51
+ LANGFUSE_CAPTURE_PATHS: "capturePaths",
52
+ };
53
+ /**
54
+ * Parse a boolean env flag. `1/true/yes/on` and `0/false/no/off` are
55
+ * case-insensitive; anything else (including unset) is `undefined` so the
56
+ * caller keeps its default.
57
+ */
58
+ export function parseFlag(value) {
59
+ if (value === undefined) {
60
+ return undefined;
61
+ }
62
+ if (/^(1|true|yes|on)$/i.test(value)) {
63
+ return true;
64
+ }
65
+ if (/^(0|false|no|off)$/i.test(value)) {
66
+ return false;
67
+ }
68
+ return undefined;
69
+ }
70
+ function normalizePreset(value) {
71
+ return value && value in PRESETS ? value : "full-debug";
72
+ }
73
+ export function createCapturePolicy(env = process.env) {
74
+ const policy = { ...PRESETS[normalizePreset(env.LANGFUSE_PRIVACY_PRESET)] };
75
+ for (const [envName, field] of Object.entries(FLAG_TO_FIELD)) {
76
+ const override = parseFlag(env[envName]);
77
+ if (override !== undefined) {
78
+ policy[field] = override;
79
+ }
80
+ }
81
+ return policy;
82
+ }
83
+ function redactMetadata(metadata, policy) {
84
+ if (!metadata) {
85
+ return undefined;
86
+ }
87
+ const redactOptions = redactOptionsFor(policy);
88
+ const output = {};
89
+ for (const [key, value] of Object.entries(metadata)) {
90
+ if (key === "cwd") {
91
+ if (!policy.captureCwd) {
92
+ continue;
93
+ }
94
+ output[key] =
95
+ !policy.capturePaths && typeof value === "string" && /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value)
96
+ ? hashPath(value)
97
+ : redactValue(value, redactOptions);
98
+ continue;
99
+ }
100
+ output[key] = redactValue(value, redactOptions);
101
+ }
102
+ return Object.keys(output).length > 0 ? output : undefined;
103
+ }
104
+ export function applyCapturePolicy(payload, policy = createCapturePolicy()) {
105
+ const redactOptions = redactOptionsFor(policy);
106
+ const captured = {
107
+ metadata: redactMetadata(payload.metadata, policy),
108
+ };
109
+ if (policy.captureInputs && "input" in payload) {
110
+ captured.input = redactValue(payload.input, redactOptions);
111
+ }
112
+ if (policy.captureOutputs && "output" in payload) {
113
+ captured.output = redactValue(payload.output, redactOptions);
114
+ }
115
+ if (policy.captureToolIo && "toolInput" in payload) {
116
+ captured.toolInput = redactValue(payload.toolInput, redactOptions);
117
+ }
118
+ if (policy.captureToolIo && "toolOutput" in payload) {
119
+ captured.toolOutput = redactValue(payload.toolOutput, redactOptions);
120
+ }
121
+ if (policy.captureSystemPrompt && "systemPrompt" in payload) {
122
+ captured.systemPrompt = redactValue(payload.systemPrompt, redactOptions);
123
+ }
124
+ return captured;
125
+ }
@@ -0,0 +1,25 @@
1
+ import type { Config, LangfuseRuntime } from "./types.js";
2
+ export interface CommandContextLike {
3
+ mode?: string;
4
+ hasUI?: boolean;
5
+ ui?: {
6
+ notify?: (message: string, level?: "info" | "warning" | "error") => void;
7
+ select?: (title: string, options: string[]) => Promise<string | undefined>;
8
+ };
9
+ }
10
+ interface CommandDeps {
11
+ configPath?: string;
12
+ getRuntime?: () => Promise<LangfuseRuntime>;
13
+ forceShutdownRuntime?: () => Promise<void>;
14
+ env?: Record<string, string | undefined>;
15
+ checkConnectivity?: (config: Config) => Promise<ConnectivityResult>;
16
+ }
17
+ interface ConnectivityResult {
18
+ ok: boolean;
19
+ message: string;
20
+ warning?: boolean;
21
+ }
22
+ export declare function handleLangfuseStatusCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
23
+ export declare function handleLangfusePrivacyCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
24
+ export declare function handleLangfuseTestCommand(args: string, ctx: CommandContextLike, deps?: CommandDeps): Promise<boolean>;
25
+ export {};