@narumitw/pi-otel 0.0.0-stage → 0.55.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.
- package/CHANGELOG.md +170 -0
- package/LICENSE +21 -0
- package/README.md +371 -2
- package/dist/chunks/chunk-IXR5MVGN.ts +156 -0
- package/dist/chunks/chunk-IXR5MVGN.ts.map +7 -0
- package/dist/chunks/runtime-KWIFBNQ2.ts +404 -0
- package/dist/chunks/runtime-KWIFBNQ2.ts.map +7 -0
- package/dist/config.d.ts +36 -0
- package/dist/durable-projection.d.ts +9 -0
- package/dist/durable-recorder.d.ts +57 -0
- package/dist/durable-state.d.ts +43 -0
- package/dist/durable.d.ts +25 -0
- package/dist/durable.js +897 -0
- package/dist/durable.js.map +7 -0
- package/dist/git.d.ts +5 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1736 -0
- package/dist/index.js.map +7 -0
- package/dist/index.ts +1878 -0
- package/dist/index.ts.map +7 -0
- package/dist/library-chunks/chunk-BBL32ZV5.js +84 -0
- package/dist/library-chunks/chunk-BBL32ZV5.js.map +7 -0
- package/dist/library-chunks/chunk-ROM6FIM7.js +78 -0
- package/dist/library-chunks/chunk-ROM6FIM7.js.map +7 -0
- package/dist/library-chunks/chunk-ZCEZBO2T.js +158 -0
- package/dist/library-chunks/chunk-ZCEZBO2T.js.map +7 -0
- package/dist/library-chunks/runtime-7TSAKORH.js +406 -0
- package/dist/library-chunks/runtime-7TSAKORH.js.map +7 -0
- package/dist/otel.d.ts +13 -0
- package/dist/otlp-settings.d.ts +9 -0
- package/dist/pi-session.d.ts +43 -0
- package/dist/public-api.d.ts +2 -0
- package/dist/runtime-api.d.ts +6 -0
- package/dist/runtime-core.d.ts +26 -0
- package/dist/runtime-defaults.d.ts +1 -0
- package/dist/runtime.d.ts +26 -0
- package/dist/sanitizer.d.ts +2 -0
- package/dist/tracing.d.ts +199 -0
- package/docs/durable.md +128 -0
- package/package.json +87 -4
- package/src/config.ts +330 -0
- package/src/durable-projection.ts +112 -0
- package/src/durable-recorder.ts +539 -0
- package/src/durable-state.ts +135 -0
- package/src/durable.ts +364 -0
- package/src/git.ts +64 -0
- package/src/index.ts +12 -0
- package/src/otel.ts +397 -0
- package/src/otlp-settings.ts +80 -0
- package/src/pi-session.ts +570 -0
- package/src/public-api.ts +13 -0
- package/src/runtime-api.ts +16 -0
- package/src/runtime-core.ts +114 -0
- package/src/runtime-defaults.ts +1 -0
- package/src/runtime.ts +509 -0
- package/src/sanitizer.ts +157 -0
- package/src/tracing.ts +946 -0
package/src/otel.ts
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
DEFAULT_BASE_URL,
|
|
5
|
+
type LangfuseConfig,
|
|
6
|
+
type LangfuseConfigPatch,
|
|
7
|
+
loadSettings,
|
|
8
|
+
normalizeLangfuseConfig,
|
|
9
|
+
otelSettingsPath,
|
|
10
|
+
type SettingsResult,
|
|
11
|
+
type TracingSettings,
|
|
12
|
+
writeLangfuseConfig,
|
|
13
|
+
} from "./config.js";
|
|
14
|
+
import { otlpSecrets } from "./otlp-settings.js";
|
|
15
|
+
import { createPiLangfuseSessionController, type PiLangfuseSessionController } from "./pi-session.js";
|
|
16
|
+
import { createLangfuseRuntimeFromBackend, type LangfuseRuntime } from "./runtime-core.js";
|
|
17
|
+
import type { GitMetadata, TraceBackend } from "./tracing.js";
|
|
18
|
+
|
|
19
|
+
export { resolveGitMetadata } from "./git.js";
|
|
20
|
+
|
|
21
|
+
interface ExtensionDependencies {
|
|
22
|
+
loadConfig(path?: string): Promise<SettingsResult>;
|
|
23
|
+
writeConfig(config: LangfuseConfigPatch, path?: string): Promise<unknown>;
|
|
24
|
+
createBackend(config: TracingSettings): Promise<TraceBackend>;
|
|
25
|
+
resolveGitMetadata(cwd: string): Promise<GitMetadata | undefined>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const FLUSH_ACTION = "Flush completed traces for this session";
|
|
29
|
+
const SET_UP_ACTION = "Set up Langfuse for this Pi agent directory (restart required)";
|
|
30
|
+
const UPDATE_ACTION = "Update Langfuse for this Pi agent directory (restart required)";
|
|
31
|
+
const HELP_ACTION = "Show setup and privacy help";
|
|
32
|
+
|
|
33
|
+
export function createOtelExtension(dependencies: Partial<ExtensionDependencies> = {}): (pi: ExtensionAPI) => void {
|
|
34
|
+
const loadConfig = dependencies.loadConfig ?? loadSettings;
|
|
35
|
+
const writeConfig = dependencies.writeConfig ?? writeLangfuseConfig;
|
|
36
|
+
const resolveInjectedGitMetadata = dependencies.resolveGitMetadata;
|
|
37
|
+
|
|
38
|
+
return function otel(pi: ExtensionAPI) {
|
|
39
|
+
let activeConfig: TracingSettings | undefined;
|
|
40
|
+
let loadingConfig: TracingSettings | undefined;
|
|
41
|
+
let runtimeConfigForShutdown: TracingSettings | undefined;
|
|
42
|
+
let shutdownConfig: TracingSettings | undefined;
|
|
43
|
+
let configPath: string | undefined;
|
|
44
|
+
let initializationError: string | undefined;
|
|
45
|
+
let storedBackend: "otlp" | "langfuse" | undefined;
|
|
46
|
+
let configurationNotice: string | undefined;
|
|
47
|
+
let sessionGeneration = 0;
|
|
48
|
+
let menuController = new AbortController();
|
|
49
|
+
let configWriteQueue = Promise.resolve();
|
|
50
|
+
|
|
51
|
+
const tracing: PiLangfuseSessionController = createPiLangfuseSessionController({
|
|
52
|
+
onSessionStart() {
|
|
53
|
+
sessionGeneration += 1;
|
|
54
|
+
menuController.abort(new DOMException("Pi OTel session replaced", "AbortError"));
|
|
55
|
+
menuController = new AbortController();
|
|
56
|
+
activeConfig = undefined;
|
|
57
|
+
loadingConfig = undefined;
|
|
58
|
+
shutdownConfig = undefined;
|
|
59
|
+
configPath = undefined;
|
|
60
|
+
initializationError = undefined;
|
|
61
|
+
storedBackend = undefined;
|
|
62
|
+
configurationNotice = undefined;
|
|
63
|
+
},
|
|
64
|
+
onSessionShutdown() {
|
|
65
|
+
sessionGeneration += 1;
|
|
66
|
+
menuController.abort(new DOMException("Pi OTel session shut down", "AbortError"));
|
|
67
|
+
shutdownConfig = activeConfig ?? runtimeConfigForShutdown ?? loadingConfig;
|
|
68
|
+
activeConfig = undefined;
|
|
69
|
+
},
|
|
70
|
+
async resolveSession(ctx, isCurrent) {
|
|
71
|
+
await configWriteQueue;
|
|
72
|
+
if (!isCurrent()) return undefined;
|
|
73
|
+
const result = await loadConfig();
|
|
74
|
+
if (!isCurrent()) return undefined;
|
|
75
|
+
configPath = result.path;
|
|
76
|
+
for (const warning of result.warnings) ctx.ui.notify(stripVTControlCharacters(warning), "warning");
|
|
77
|
+
if (!result.ok) {
|
|
78
|
+
initializationError = formatConfigError(result);
|
|
79
|
+
if (!result.missing) ctx.ui.notify(initializationError, "warning");
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
storedBackend = result.config.backend ?? "langfuse";
|
|
84
|
+
loadingConfig = result.config;
|
|
85
|
+
const createBackend = dependencies.createBackend;
|
|
86
|
+
const ownsRuntime = createBackend !== undefined;
|
|
87
|
+
const config = result.config;
|
|
88
|
+
let runtime: LangfuseRuntime;
|
|
89
|
+
if (createBackend) {
|
|
90
|
+
runtime = createLangfuseRuntimeFromBackend(await createBackend(config));
|
|
91
|
+
} else {
|
|
92
|
+
const { createLangfuseRuntime, createOtelRuntime } = await import("./runtime.js");
|
|
93
|
+
if (!isCurrent()) return undefined;
|
|
94
|
+
runtime = await (config.backend === "otlp"
|
|
95
|
+
? createOtelRuntime(config)
|
|
96
|
+
: createLangfuseRuntime({ config, env: false }));
|
|
97
|
+
}
|
|
98
|
+
if (isCurrent() || !runtimeConfigForShutdown) runtimeConfigForShutdown = result.config;
|
|
99
|
+
if (isCurrent()) {
|
|
100
|
+
activeConfig = result.config;
|
|
101
|
+
loadingConfig = undefined;
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
runtime,
|
|
105
|
+
releaseIfStale: async (reason) => {
|
|
106
|
+
if (ownsRuntime || reason === "quit") await runtime.shutdown();
|
|
107
|
+
},
|
|
108
|
+
options: {
|
|
109
|
+
...(result.config.userId ? { userId: result.config.userId } : {}),
|
|
110
|
+
captureContent: result.config.captureContent,
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
},
|
|
114
|
+
...(resolveInjectedGitMetadata
|
|
115
|
+
? { resolveGitMetadata: (_pi: ExtensionAPI, cwd: string) => resolveInjectedGitMetadata(cwd) }
|
|
116
|
+
: {}),
|
|
117
|
+
onInitializationError(error, ctx) {
|
|
118
|
+
const config = loadingConfig;
|
|
119
|
+
loadingConfig = undefined;
|
|
120
|
+
initializationError = `${backendLabel(config)} tracing could not start: ${formatError(error, config)}`;
|
|
121
|
+
ctx.ui.notify(initializationError, "warning");
|
|
122
|
+
},
|
|
123
|
+
beforeSessionDispose: async () => {
|
|
124
|
+
await configWriteQueue;
|
|
125
|
+
},
|
|
126
|
+
onShutdownError(error, ctx) {
|
|
127
|
+
ctx.ui.notify(
|
|
128
|
+
`${backendLabel(shutdownConfig)} shutdown export failed: ${formatError(error, shutdownConfig)}`,
|
|
129
|
+
"error",
|
|
130
|
+
);
|
|
131
|
+
},
|
|
132
|
+
flushOnReplacement: true,
|
|
133
|
+
shutdownRuntimeOnQuit: true,
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
async function showMenu(ctx: ExtensionCommandContext) {
|
|
137
|
+
if (!ctx.hasUI) {
|
|
138
|
+
throw new Error(formatNonInteractiveStatus(activeConfig, configPath, initializationError));
|
|
139
|
+
}
|
|
140
|
+
const menuGeneration = sessionGeneration;
|
|
141
|
+
const menuSignal = menuController.signal;
|
|
142
|
+
const isCurrent = () => menuGeneration === sessionGeneration && !menuSignal.aborted;
|
|
143
|
+
const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
|
|
144
|
+
if (!isCurrent()) return;
|
|
145
|
+
type Screen = "main";
|
|
146
|
+
type Action = "flush" | "configure" | "settings" | "help";
|
|
147
|
+
const menu = defineMenu<undefined, Screen, Action>({
|
|
148
|
+
start: "main",
|
|
149
|
+
screens: {
|
|
150
|
+
main: () => ({
|
|
151
|
+
kind: "actions",
|
|
152
|
+
title: "Pi OTel",
|
|
153
|
+
lines: formatMenuDetails(activeConfig, configPath, initializationError, configurationNotice),
|
|
154
|
+
items: [
|
|
155
|
+
...(tracing.active ? [{ id: "flush", label: FLUSH_ACTION, action: "flush" as const }] : []),
|
|
156
|
+
...(storedBackend !== "otlp"
|
|
157
|
+
? [
|
|
158
|
+
{
|
|
159
|
+
id: "configure",
|
|
160
|
+
label: storedBackend ? UPDATE_ACTION : SET_UP_ACTION,
|
|
161
|
+
action: "configure" as const,
|
|
162
|
+
},
|
|
163
|
+
]
|
|
164
|
+
: []),
|
|
165
|
+
{ id: "settings", label: "Settings (edit private file)", action: "settings" },
|
|
166
|
+
{ id: "help", label: HELP_ACTION, action: "help" },
|
|
167
|
+
],
|
|
168
|
+
hint: "close",
|
|
169
|
+
}),
|
|
170
|
+
},
|
|
171
|
+
actions: {
|
|
172
|
+
flush: async () => {
|
|
173
|
+
const menuConfig = activeConfig;
|
|
174
|
+
const label = backendLabel(menuConfig);
|
|
175
|
+
if (!tracing.active) {
|
|
176
|
+
ctx.ui.notify(`${label} tracing is not enabled for this session.`, "warning");
|
|
177
|
+
return { kind: "close" };
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
await tracing.flush();
|
|
181
|
+
if (!isCurrent()) return { kind: "close" };
|
|
182
|
+
ctx.ui.notify(`${label} traces flushed for this session.`, "info");
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (!isCurrent()) return { kind: "close" };
|
|
185
|
+
ctx.ui.notify(`${label} flush failed: ${formatError(error, menuConfig)}`, "error");
|
|
186
|
+
}
|
|
187
|
+
return { kind: "close" };
|
|
188
|
+
},
|
|
189
|
+
configure: async () => {
|
|
190
|
+
const loaded = await loadConfig();
|
|
191
|
+
if (!isCurrent()) return { kind: "close" };
|
|
192
|
+
configPath = loaded.path;
|
|
193
|
+
const current = loaded.ok ? loaded.config : undefined;
|
|
194
|
+
storedBackend = current ? (current.backend ?? "langfuse") : undefined;
|
|
195
|
+
if (loaded.legacy || current?.backend === "otlp") {
|
|
196
|
+
ctx.ui.notify(formatSettingsNotice(configPath, loaded.legacy), "info");
|
|
197
|
+
return { kind: "close" };
|
|
198
|
+
}
|
|
199
|
+
const next = await promptForConfig(ctx, current, menuSignal);
|
|
200
|
+
if (!next || !isCurrent()) return { kind: "close" };
|
|
201
|
+
try {
|
|
202
|
+
const write = configWriteQueue.then(() => writeConfig(next, loaded.path));
|
|
203
|
+
configWriteQueue = write.then(
|
|
204
|
+
() => undefined,
|
|
205
|
+
() => undefined,
|
|
206
|
+
);
|
|
207
|
+
await write;
|
|
208
|
+
if (!isCurrent()) return { kind: "close" };
|
|
209
|
+
storedBackend = "langfuse";
|
|
210
|
+
configurationNotice = "Saved; restart each Pi process to use it in subsequent sessions.";
|
|
211
|
+
ctx.ui.notify(
|
|
212
|
+
`Saved Langfuse config to ${stripVTControlCharacters(loaded.path)} for this Pi agent directory. Restart each Pi process to apply it to subsequent sessions.`,
|
|
213
|
+
"info",
|
|
214
|
+
);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (!isCurrent()) return { kind: "close" };
|
|
217
|
+
ctx.ui.notify(`Failed to save Langfuse config: ${formatError(error, { ...current, ...next })}`, "error");
|
|
218
|
+
}
|
|
219
|
+
return { kind: "close" };
|
|
220
|
+
},
|
|
221
|
+
settings: async () => {
|
|
222
|
+
ctx.ui.notify(formatSettingsNotice(configPath), "info");
|
|
223
|
+
return { kind: "close" };
|
|
224
|
+
},
|
|
225
|
+
help: async () => {
|
|
226
|
+
ctx.ui.notify(formatHelp(configPath), "info");
|
|
227
|
+
return { kind: "close" };
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
await runMenu(ctx, menu, {
|
|
232
|
+
getState: () => undefined,
|
|
233
|
+
signal: menuSignal,
|
|
234
|
+
isCurrent,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
pi.registerCommand("otel", {
|
|
239
|
+
description: "Show OpenTelemetry tracing status, settings, and export controls",
|
|
240
|
+
handler: async (args, ctx) => {
|
|
241
|
+
if (args.trim()) throw new Error("/otel takes no arguments.");
|
|
242
|
+
await showMenu(ctx);
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
pi.registerCommand("langfuse", {
|
|
246
|
+
description: "Deprecated: use /otel instead",
|
|
247
|
+
handler: async (_args, ctx) => {
|
|
248
|
+
if (ctx.hasUI) ctx.ui.notify("/langfuse is deprecated. Use /otel instead.", "warning");
|
|
249
|
+
await showMenu(ctx);
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
tracing.extension(pi);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function promptForConfig(
|
|
258
|
+
ctx: ExtensionCommandContext,
|
|
259
|
+
current: LangfuseConfig | undefined,
|
|
260
|
+
signal: AbortSignal,
|
|
261
|
+
): Promise<LangfuseConfigPatch | undefined> {
|
|
262
|
+
const secretKey = await ctx.ui.input("Langfuse secret key (leave blank to keep existing):", undefined, { signal });
|
|
263
|
+
if (signal.aborted) return undefined;
|
|
264
|
+
if (secretKey === undefined) {
|
|
265
|
+
ctx.ui.notify("Cancelled", "info");
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
const publicKey = await ctx.ui.input("Langfuse public key (leave blank to keep existing):", undefined, { signal });
|
|
269
|
+
if (signal.aborted) return undefined;
|
|
270
|
+
if (publicKey === undefined) {
|
|
271
|
+
ctx.ui.notify("Cancelled", "info");
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
const baseUrl = await ctx.ui.input(
|
|
275
|
+
`Langfuse base URL (leave blank for default ${DEFAULT_BASE_URL}):`,
|
|
276
|
+
DEFAULT_BASE_URL,
|
|
277
|
+
{ signal },
|
|
278
|
+
);
|
|
279
|
+
if (signal.aborted) return undefined;
|
|
280
|
+
if (baseUrl === undefined) {
|
|
281
|
+
ctx.ui.notify("Cancelled", "info");
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const patch: LangfuseConfigPatch = {
|
|
286
|
+
...(publicKey.trim() ? { publicKey: publicKey.trim() } : {}),
|
|
287
|
+
...(secretKey.trim() ? { secretKey: secretKey.trim() } : {}),
|
|
288
|
+
baseUrl: baseUrl.trim() || DEFAULT_BASE_URL,
|
|
289
|
+
};
|
|
290
|
+
const normalized = normalizeLangfuseConfig({ ...current, ...patch });
|
|
291
|
+
if (!normalized.ok) {
|
|
292
|
+
ctx.ui.notify(`Invalid Langfuse config: ${normalized.reason}`, "error");
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
return patch;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function formatMenuDetails(
|
|
299
|
+
activeConfig: TracingSettings | undefined,
|
|
300
|
+
configPath: string | undefined,
|
|
301
|
+
initializationError: string | undefined,
|
|
302
|
+
configurationNotice: string | undefined,
|
|
303
|
+
): string[] {
|
|
304
|
+
const lines = ["Current session:", ` Tracing: ${activeConfig ? "enabled" : "disabled"}`];
|
|
305
|
+
if (activeConfig) {
|
|
306
|
+
lines.push(...connectionDetails(activeConfig));
|
|
307
|
+
} else if (configurationNotice) {
|
|
308
|
+
lines.push(" State: tracing remains disabled until Pi restarts.");
|
|
309
|
+
} else if (initializationError) {
|
|
310
|
+
lines.push(` Reason: ${initializationError}`);
|
|
311
|
+
}
|
|
312
|
+
lines.push(
|
|
313
|
+
"",
|
|
314
|
+
"Agent-directory configuration:",
|
|
315
|
+
` Configuration: ${displaySettingsPath(configPath)}`,
|
|
316
|
+
" Scope: this Pi agent directory; restart each Pi process to apply changes.",
|
|
317
|
+
);
|
|
318
|
+
if (configurationNotice) lines.push(` Pending: ${configurationNotice}`);
|
|
319
|
+
lines.push("", "What do you want to do?");
|
|
320
|
+
return lines;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function formatNonInteractiveStatus(
|
|
324
|
+
activeConfig: TracingSettings | undefined,
|
|
325
|
+
configPath: string | undefined,
|
|
326
|
+
initializationError: string | undefined,
|
|
327
|
+
): string {
|
|
328
|
+
return [
|
|
329
|
+
"/otel requires interactive UI.",
|
|
330
|
+
`Current session tracing: ${activeConfig ? "enabled" : "disabled"}`,
|
|
331
|
+
...(activeConfig ? connectionDetails(activeConfig) : initializationError ? [`Reason: ${initializationError}`] : []),
|
|
332
|
+
`Configuration: ${displaySettingsPath(configPath)}`,
|
|
333
|
+
"Edit the private config manually, then restart each Pi process to apply it to subsequent sessions.",
|
|
334
|
+
].join("\n");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function backendLabel(config: TracingSettings | undefined): string {
|
|
338
|
+
return config?.backend === "otlp" ? "OTLP" : "Langfuse";
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function connectionDetails(settings: TracingSettings): string[] {
|
|
342
|
+
const otlp = settings.backend === "otlp";
|
|
343
|
+
return [
|
|
344
|
+
`Backend: ${backendLabel(settings)}`,
|
|
345
|
+
otlp ? `Endpoint origin: ${new URL(settings.endpoint).origin}` : `Endpoint: ${settings.baseUrl}`,
|
|
346
|
+
...(otlp && Object.keys(settings.headers).length ? ["Export headers: settings file"] : []),
|
|
347
|
+
`Content capture: ${settings.captureContent ? "enabled" : "disabled"}`,
|
|
348
|
+
];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function displaySettingsPath(path = otelSettingsPath()): string {
|
|
352
|
+
return stripVTControlCharacters(path);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function formatSettingsNotice(path: string | undefined, legacy = false): string {
|
|
356
|
+
const canonical = displaySettingsPath();
|
|
357
|
+
return legacy
|
|
358
|
+
? `Read-only legacy settings: ${displaySettingsPath(path)}. Move the file to ${canonical} before editing it.`
|
|
359
|
+
: `Edit the private settings file: ${canonical}. Restart each Pi process to change its export connection.`;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function formatHelp(configPath: string | undefined): string {
|
|
363
|
+
return [
|
|
364
|
+
"Pi OTel setup and privacy:",
|
|
365
|
+
'For an OTLP collector, set backend to "otlp" and enter the full traces endpoint in the settings file.',
|
|
366
|
+
"For Langfuse, use the setup action in /otel or edit the settings file manually.",
|
|
367
|
+
`Configuration: ${displaySettingsPath(configPath)}`,
|
|
368
|
+
"The file belongs to this Pi agent directory; restart each Pi process after changing it.",
|
|
369
|
+
"Trace content may contain prompts, responses, tool arguments, tool results, and source code.",
|
|
370
|
+
"Git branch, commit, cwd, model, and usage remain in metadata when content capture is disabled.",
|
|
371
|
+
'Use "captureContent": false in the private config to export metadata only.',
|
|
372
|
+
].join("\n");
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function formatConfigError(result: Extract<SettingsResult, { ok: false }>): string {
|
|
376
|
+
const setupHint =
|
|
377
|
+
result.missing || result.reason.startsWith("Configuration file not found:")
|
|
378
|
+
? " Run /otel and choose Set up Langfuse, or configure an OTLP endpoint in pi-otel.json."
|
|
379
|
+
: "";
|
|
380
|
+
return `Tracing is disabled: ${stripVTControlCharacters(result.reason)}${setupHint}`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function formatError(error: unknown, config?: TracingSettings | LangfuseConfigPatch): string {
|
|
384
|
+
let message = error instanceof Error ? error.message : String(error);
|
|
385
|
+
const otlp = config?.backend === "otlp";
|
|
386
|
+
const secrets = otlp
|
|
387
|
+
? [config.endpoint, ...otlpSecrets(config.headers)].sort((left, right) => right.length - left.length)
|
|
388
|
+
: [config?.publicKey, config?.secretKey]
|
|
389
|
+
.filter((secret): secret is string => Boolean(secret))
|
|
390
|
+
.sort((left, right) => right.length - left.length);
|
|
391
|
+
for (const secret of secrets) {
|
|
392
|
+
message = message.replaceAll(secret, otlp ? "[OTLP_SECRET_REDACTED]" : "[LANGFUSE_KEY_REDACTED]");
|
|
393
|
+
}
|
|
394
|
+
return stripVTControlCharacters(message);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export default createOtelExtension();
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { validateHeaderName, validateHeaderValue } from "node:http";
|
|
2
|
+
import { isIP } from "node:net";
|
|
3
|
+
|
|
4
|
+
export interface OtlpRuntimeConfig {
|
|
5
|
+
endpoint: string;
|
|
6
|
+
/** Requires HTTPS unless the endpoint uses a loopback IP. */
|
|
7
|
+
headers?: Readonly<Record<string, string>>;
|
|
8
|
+
serviceName?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type OtlpConnection = Required<OtlpRuntimeConfig>;
|
|
12
|
+
|
|
13
|
+
const RESERVED_HEADERS = new Set([
|
|
14
|
+
"__proto__",
|
|
15
|
+
"connection",
|
|
16
|
+
"content-encoding",
|
|
17
|
+
"content-length",
|
|
18
|
+
"content-type",
|
|
19
|
+
"host",
|
|
20
|
+
"transfer-encoding",
|
|
21
|
+
"user-agent",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export function normalizeOtlpConnection(input: Readonly<Record<string, unknown>>): OtlpConnection {
|
|
25
|
+
const url = parseHttpUrl(input.endpoint);
|
|
26
|
+
if (!url) {
|
|
27
|
+
throw new Error("OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.");
|
|
28
|
+
}
|
|
29
|
+
const serviceName = input.serviceName === undefined ? "pi" : input.serviceName;
|
|
30
|
+
if (typeof serviceName !== "string" || !serviceName.trim()) {
|
|
31
|
+
throw new Error("OTLP serviceName must be a non-empty string.");
|
|
32
|
+
}
|
|
33
|
+
const headers = normalizeHeaders(input.headers);
|
|
34
|
+
// URL canonicalizes numeric IPs. Do not trust DNS or hosts-file aliases with cleartext credentials.
|
|
35
|
+
const loopback = (url.hostname.startsWith("127.") && isIP(url.hostname) === 4) || url.hostname === "[::1]";
|
|
36
|
+
if (Object.keys(headers).length > 0 && url.protocol === "http:" && !loopback) {
|
|
37
|
+
throw new Error("OTLP headers require HTTPS unless the endpoint uses a loopback IP (127.0.0.0/8 or [::1]).");
|
|
38
|
+
}
|
|
39
|
+
return { endpoint: url.href, headers, serviceName: serviceName.trim() };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseHttpUrl(value: unknown): URL | undefined {
|
|
43
|
+
if (typeof value !== "string" || !/^https?:\/\//iu.test(value.trim()) || /[?#]/u.test(value)) return undefined;
|
|
44
|
+
try {
|
|
45
|
+
const url = new URL(value.trim());
|
|
46
|
+
if (url.username || url.password) return undefined;
|
|
47
|
+
return url;
|
|
48
|
+
} catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function normalizeHeaders(input: unknown): Record<string, string> {
|
|
54
|
+
if (input === undefined) return {};
|
|
55
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) {
|
|
56
|
+
throw new Error("OTLP headers must be an object of literal HTTP header names and values.");
|
|
57
|
+
}
|
|
58
|
+
const entries = new Map<string, string>();
|
|
59
|
+
for (const [name, value] of Object.entries(input)) {
|
|
60
|
+
const key = name.toLowerCase();
|
|
61
|
+
try {
|
|
62
|
+
validateHeaderName(name);
|
|
63
|
+
if (typeof value !== "string" || !value.trim() || RESERVED_HEADERS.has(key) || entries.has(key)) {
|
|
64
|
+
throw new Error("Invalid header");
|
|
65
|
+
}
|
|
66
|
+
validateHeaderValue(name, value);
|
|
67
|
+
entries.set(key, value.trim());
|
|
68
|
+
} catch {
|
|
69
|
+
// Neither the header name nor its value is safe to include in a diagnostic.
|
|
70
|
+
throw new Error("OTLP headers contain an invalid, reserved, empty, or duplicate HTTP header.");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right)));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function otlpSecrets(headers: Readonly<Record<string, string>>): string[] {
|
|
77
|
+
const auth = headers.authorization;
|
|
78
|
+
const token = auth?.match(/^\S+\s+(.+)$/u)?.[1];
|
|
79
|
+
return [...new Set([...Object.values(headers), ...(token ? [token] : [])])].sort((a, b) => b.length - a.length);
|
|
80
|
+
}
|