@narumitw/pi-langfuse 0.50.1 → 0.50.2

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/dist/index.ts ADDED
@@ -0,0 +1,1478 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+
4
+ // src/config.ts
5
+ import { randomUUID } from "node:crypto";
6
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
7
+ import { dirname, join } from "node:path";
8
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
9
+ var CONFIG_FILE_NAME = "pi-langfuse.json";
10
+ var DEFAULT_BASE_URL = "https://us.cloud.langfuse.com";
11
+ function langfuseConfigPath() {
12
+ return join(getAgentDir(), CONFIG_FILE_NAME);
13
+ }
14
+ var configSaveQueues = /* @__PURE__ */ new Map();
15
+ function writeLangfuseConfig(patch, path = langfuseConfigPath()) {
16
+ const previous = configSaveQueues.get(path) ?? Promise.resolve();
17
+ const operation = previous.then(() => writeLangfuseConfigNow(patch, path));
18
+ const tail = operation.then(
19
+ () => void 0,
20
+ () => void 0
21
+ );
22
+ configSaveQueues.set(path, tail);
23
+ void tail.then(() => {
24
+ if (configSaveQueues.get(path) === tail) configSaveQueues.delete(path);
25
+ });
26
+ return operation;
27
+ }
28
+ async function writeLangfuseConfigNow(patch, path) {
29
+ const currentDocument = await readLangfuseDocumentForUpdate(path);
30
+ const normalized = normalizeLangfuseConfig({ ...currentDocument, ...patch });
31
+ if (!normalized.ok) throw new Error(normalized.reason);
32
+ const {
33
+ publicKey: _publicKey,
34
+ secretKey: _secretKey,
35
+ baseUrl: _baseUrl,
36
+ environment: _environment,
37
+ release: _release,
38
+ userId: _userId,
39
+ captureContent: _captureContent,
40
+ ...unknownFields
41
+ } = currentDocument;
42
+ const nextDocument = { ...unknownFields, ...normalized.config };
43
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
44
+ const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
45
+ try {
46
+ await writeFile(tempPath, `${JSON.stringify(nextDocument, null, 2)}
47
+ `, {
48
+ encoding: "utf8",
49
+ mode: 384
50
+ });
51
+ await chmod(tempPath, 384);
52
+ await rename(tempPath, path);
53
+ return normalized.config;
54
+ } catch (error) {
55
+ await rm(tempPath, { force: true }).catch(() => void 0);
56
+ throw error;
57
+ }
58
+ }
59
+ async function readLangfuseDocumentForUpdate(path) {
60
+ let parsed;
61
+ try {
62
+ parsed = JSON.parse(await readFile(path, "utf8"));
63
+ } catch (error) {
64
+ if (isNodeError(error) && error.code === "ENOENT") return {};
65
+ throw new Error(
66
+ `Cannot update ${CONFIG_FILE_NAME} because the existing file is malformed or unreadable; repair it first.`
67
+ );
68
+ }
69
+ const normalized = normalizeLangfuseConfig(parsed);
70
+ if (!normalized.ok) {
71
+ throw new Error(
72
+ `Cannot update ${CONFIG_FILE_NAME} because the existing file has invalid recognized fields; repair it first.`
73
+ );
74
+ }
75
+ return { ...parsed };
76
+ }
77
+ async function loadLangfuseConfig(path = langfuseConfigPath()) {
78
+ await configSaveQueues.get(path);
79
+ const warnings = [];
80
+ const permissionFailure = await ensurePrivatePermissions(path, warnings);
81
+ if (permissionFailure) {
82
+ return {
83
+ ok: false,
84
+ path,
85
+ warnings,
86
+ reason: `Refusing to load credentials: ${permissionFailure}`
87
+ };
88
+ }
89
+ let text;
90
+ try {
91
+ text = await readFile(path, "utf8");
92
+ } catch (error) {
93
+ if (isNodeError(error) && error.code === "ENOENT") {
94
+ return { ok: false, path, warnings, reason: `Configuration file not found: ${path}` };
95
+ }
96
+ return {
97
+ ok: false,
98
+ path,
99
+ warnings,
100
+ reason: `Failed to read ${path}: ${formatError(error)}`
101
+ };
102
+ }
103
+ let parsed;
104
+ try {
105
+ parsed = JSON.parse(text);
106
+ } catch {
107
+ return {
108
+ ok: false,
109
+ path,
110
+ warnings,
111
+ reason: `Failed to parse ${path} as JSON; repair the file before retrying.`
112
+ };
113
+ }
114
+ const normalized = normalizeLangfuseConfig(parsed);
115
+ if (!normalized.ok) return { ok: false, path, warnings, reason: normalized.reason };
116
+ return { ok: true, config: normalized.config, path, warnings };
117
+ }
118
+ function normalizeLangfuseConfig(value) {
119
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
120
+ return { ok: false, reason: "pi-langfuse.json must contain a JSON object." };
121
+ }
122
+ const input = value;
123
+ const publicKey = normalizeString(input.publicKey);
124
+ const secretKey = normalizeString(input.secretKey);
125
+ if (!publicKey) {
126
+ return { ok: false, reason: "pi-langfuse.json requires a literal publicKey string." };
127
+ }
128
+ if (!secretKey) {
129
+ return { ok: false, reason: "pi-langfuse.json requires a literal secretKey string." };
130
+ }
131
+ if (isInterpolation(publicKey)) {
132
+ return {
133
+ ok: false,
134
+ reason: "pi-langfuse.json publicKey must be literal; environment and command interpolation are not supported."
135
+ };
136
+ }
137
+ if (isInterpolation(secretKey)) {
138
+ return {
139
+ ok: false,
140
+ reason: "pi-langfuse.json secretKey must be literal; environment and command interpolation are not supported."
141
+ };
142
+ }
143
+ const rawBaseUrl = input.baseUrl === void 0 ? DEFAULT_BASE_URL : normalizeString(input.baseUrl);
144
+ if (!rawBaseUrl) {
145
+ return { ok: false, reason: "pi-langfuse.json baseUrl must be a non-empty string." };
146
+ }
147
+ const baseUrl = normalizeBaseUrl(rawBaseUrl);
148
+ if (!baseUrl) {
149
+ return {
150
+ ok: false,
151
+ reason: "pi-langfuse.json baseUrl must use HTTP or HTTPS without credentials, a query, or a fragment."
152
+ };
153
+ }
154
+ if (input.captureContent !== void 0 && typeof input.captureContent !== "boolean") {
155
+ return { ok: false, reason: "pi-langfuse.json captureContent must be a boolean." };
156
+ }
157
+ const environment = optionalString(input.environment, "environment");
158
+ if (!environment.ok) return environment;
159
+ if (environment.value && (environment.value.length > 40 || !/^(?!langfuse)[a-z0-9_-]+$/u.test(environment.value))) {
160
+ return {
161
+ ok: false,
162
+ reason: "pi-langfuse.json environment must be at most 40 lowercase letters, numbers, hyphens, or underscores and must not start with langfuse."
163
+ };
164
+ }
165
+ const release = optionalString(input.release, "release");
166
+ if (!release.ok) return release;
167
+ const userId = optionalString(input.userId, "userId");
168
+ if (!userId.ok) return userId;
169
+ if (userId.value && userId.value.length > 200) {
170
+ return { ok: false, reason: "pi-langfuse.json userId must be at most 200 characters." };
171
+ }
172
+ return {
173
+ ok: true,
174
+ config: {
175
+ publicKey,
176
+ secretKey,
177
+ baseUrl,
178
+ ...environment.value ? { environment: environment.value } : {},
179
+ ...release.value ? { release: release.value } : {},
180
+ ...userId.value ? { userId: userId.value } : {},
181
+ captureContent: input.captureContent ?? true
182
+ }
183
+ };
184
+ }
185
+ async function ensurePrivatePermissions(path, warnings) {
186
+ try {
187
+ const file = await stat(path);
188
+ if ((file.mode & 511) !== 384) {
189
+ await chmod(path, 384);
190
+ const repaired = await stat(path);
191
+ if ((repaired.mode & 511) !== 384) {
192
+ throw new Error(`permissions remained ${(repaired.mode & 511).toString(8)}`);
193
+ }
194
+ warnings.push(`Restricted ${path} permissions to 0600.`);
195
+ }
196
+ } catch (error) {
197
+ if (isNodeError(error) && error.code === "ENOENT") return void 0;
198
+ const failure = `Failed to enforce 0600 permissions for ${path}: ${formatError(error)}`;
199
+ warnings.push(failure);
200
+ return failure;
201
+ }
202
+ return void 0;
203
+ }
204
+ function normalizeBaseUrl(value) {
205
+ try {
206
+ const url = new URL(value);
207
+ if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
208
+ if (url.username || url.password || url.search || url.hash) return void 0;
209
+ return url.toString().replace(/\/+$/, "");
210
+ } catch {
211
+ return void 0;
212
+ }
213
+ }
214
+ function optionalString(value, name) {
215
+ if (value === void 0) return { ok: true };
216
+ const normalized = normalizeString(value);
217
+ return normalized ? { ok: true, value: normalized } : { ok: false, reason: `pi-langfuse.json ${name} must be a non-empty string.` };
218
+ }
219
+ function normalizeString(value) {
220
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
221
+ }
222
+ function isInterpolation(value) {
223
+ return value.startsWith("$") || value.startsWith("!");
224
+ }
225
+ function isNodeError(error) {
226
+ return error instanceof Error && "code" in error;
227
+ }
228
+ function formatError(error) {
229
+ return error instanceof Error ? error.message : String(error);
230
+ }
231
+
232
+ // src/sanitizer.ts
233
+ var MAX_CAPTURE_BYTES = 64 * 1024;
234
+ var MAX_STRING_LENGTH = 5e4;
235
+ var MAX_COLLECTION_LENGTH = 200;
236
+ var MAX_DEPTH = 12;
237
+ var TRUNCATED = "[truncated: content budget exceeded]";
238
+ var BASE64_DATA_URI = /data:[^,\s"'`]*;base64,[^\s"'`]*/gi;
239
+ var BASE64_DATA_URI_OMITTED = "[base64 data URI omitted]";
240
+ var OPAQUE_SIGNATURE_KEYS = /* @__PURE__ */ new Set(["thinkingSignature", "textSignature", "thoughtSignature"]);
241
+ function sanitizeTraceValue(value) {
242
+ const budget = { remaining: MAX_CAPTURE_BYTES };
243
+ const sanitized = sanitize(value, /* @__PURE__ */ new WeakSet(), 0, budget);
244
+ return serializedBytes(sanitized) <= MAX_CAPTURE_BYTES ? sanitized : TRUNCATED;
245
+ }
246
+ function sanitize(value, active, depth, budget) {
247
+ if (budget.remaining <= byteLength(TRUNCATED)) return TRUNCATED;
248
+ if (value === null || typeof value === "number" || typeof value === "boolean") {
249
+ return consume(value, budget);
250
+ }
251
+ if (typeof value === "string") {
252
+ const bounded = truncateString(value, Math.min(MAX_STRING_LENGTH, budget.remaining));
253
+ const redacted = bounded.replace(BASE64_DATA_URI, BASE64_DATA_URI_OMITTED);
254
+ return consume(redacted, budget);
255
+ }
256
+ if (typeof value === "bigint") return consume(value.toString(), budget);
257
+ if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol") {
258
+ return void 0;
259
+ }
260
+ if (value instanceof Date) {
261
+ return consume(Number.isNaN(value.getTime()) ? "[invalid date]" : value.toISOString(), budget);
262
+ }
263
+ if (value instanceof Error) {
264
+ return sanitize({ name: value.name, message: value.message }, active, depth, budget);
265
+ }
266
+ if (depth >= MAX_DEPTH) return consume("[maximum depth reached]", budget);
267
+ if (active.has(value)) return consume("[circular]", budget);
268
+ active.add(value);
269
+ let result;
270
+ if (Array.isArray(value)) {
271
+ const items = [];
272
+ for (const item of value.slice(0, MAX_COLLECTION_LENGTH)) {
273
+ if (budget.remaining <= byteLength(TRUNCATED)) break;
274
+ items.push(sanitize(item, active, depth + 1, budget));
275
+ }
276
+ if (items.length < value.length) items.push(`[${value.length - items.length} items omitted]`);
277
+ result = items;
278
+ } else {
279
+ const record = value;
280
+ const output = {};
281
+ const objectType = readProperty(record, "type").value;
282
+ const redactData = objectType === "image" || objectType === "base64";
283
+ let visited = 0;
284
+ let processed = 0;
285
+ let omitted = false;
286
+ try {
287
+ for (const key in record) {
288
+ if (visited >= MAX_COLLECTION_LENGTH || budget.remaining <= byteLength(TRUNCATED)) {
289
+ omitted = true;
290
+ break;
291
+ }
292
+ visited += 1;
293
+ if (!Object.hasOwn(record, key) || OPAQUE_SIGNATURE_KEYS.has(key)) continue;
294
+ const keyBudget = Math.min(MAX_STRING_LENGTH, Math.max(0, budget.remaining - 4));
295
+ if (key.length > keyBudget) {
296
+ omitted = true;
297
+ break;
298
+ }
299
+ const keyBytes = byteLength(key);
300
+ if (keyBytes > keyBudget) {
301
+ omitted = true;
302
+ break;
303
+ }
304
+ budget.remaining -= keyBytes + 4;
305
+ const property = readProperty(record, key);
306
+ if (redactData && key === "data") {
307
+ output[key] = consume("[base64 omitted]", budget);
308
+ } else if (!property.ok) output[key] = consume("[unreadable property]", budget);
309
+ else output[key] = sanitize(property.value, active, depth + 1, budget);
310
+ processed += 1;
311
+ }
312
+ } catch {
313
+ if (processed === 0) {
314
+ active.delete(value);
315
+ return consume("[unreadable object]", budget);
316
+ }
317
+ omitted = true;
318
+ }
319
+ if (omitted) output.$truncated = "additional object entries omitted";
320
+ result = output;
321
+ }
322
+ active.delete(value);
323
+ return result;
324
+ }
325
+ function readProperty(record, key) {
326
+ try {
327
+ return { ok: true, value: record[key] };
328
+ } catch {
329
+ return { ok: false };
330
+ }
331
+ }
332
+ function consume(value, budget) {
333
+ const size = serializedBytes(value);
334
+ if (size > budget.remaining) {
335
+ budget.remaining -= byteLength(TRUNCATED);
336
+ return TRUNCATED;
337
+ }
338
+ budget.remaining -= size;
339
+ return value;
340
+ }
341
+ function truncateString(value, maxBytes) {
342
+ const boundedPrefix = value.slice(0, maxBytes);
343
+ if (boundedPrefix.length === value.length && byteLength(boundedPrefix) <= maxBytes) {
344
+ return boundedPrefix;
345
+ }
346
+ const suffix = "\u2026 [truncated]";
347
+ const target = Math.max(0, maxBytes - byteLength(suffix) - 2);
348
+ let bytes = 0;
349
+ let output = "";
350
+ for (const character of boundedPrefix) {
351
+ const size = byteLength(character);
352
+ if (bytes + size > target) break;
353
+ output += character;
354
+ bytes += size;
355
+ }
356
+ return `${output}${suffix}`;
357
+ }
358
+ function serializedBytes(value) {
359
+ return byteLength(JSON.stringify(value) ?? "null");
360
+ }
361
+ function byteLength(value) {
362
+ return Buffer.byteLength(value, "utf8");
363
+ }
364
+
365
+ // src/tracing.ts
366
+ var TRACE_SCHEMA_VERSION = "2";
367
+ var MAX_HEADER_VALUE_LENGTH = 1024;
368
+ var CONTENT_DISABLED = "[content capture disabled]";
369
+ var ALLOWED_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
370
+ "anthropic-ratelimit-requests-limit",
371
+ "anthropic-ratelimit-requests-remaining",
372
+ "anthropic-ratelimit-requests-reset",
373
+ "anthropic-ratelimit-tokens-limit",
374
+ "anthropic-ratelimit-tokens-remaining",
375
+ "anthropic-ratelimit-tokens-reset",
376
+ "cf-ray",
377
+ "openai-request-id",
378
+ "request-id",
379
+ "retry-after",
380
+ "x-amzn-requestid",
381
+ "x-request-id",
382
+ "x-ratelimit-limit-requests",
383
+ "x-ratelimit-limit-tokens",
384
+ "x-ratelimit-remaining-requests",
385
+ "x-ratelimit-remaining-tokens",
386
+ "x-ratelimit-reset-requests",
387
+ "x-ratelimit-reset-tokens"
388
+ ]);
389
+ var TraceRecorder = class {
390
+ constructor(backend, context) {
391
+ this.backend = backend;
392
+ this.context = context;
393
+ }
394
+ backend;
395
+ context;
396
+ root;
397
+ attempt;
398
+ attemptIndex;
399
+ turn;
400
+ turnIndex;
401
+ generation;
402
+ tools = /* @__PURE__ */ new Map();
403
+ duplicateToolIds = /* @__PURE__ */ new Set();
404
+ compaction;
405
+ lastOutput;
406
+ lastAssistant;
407
+ lastAttemptOutcome;
408
+ unresolvedToolErrors = 0;
409
+ startSnapshot;
410
+ counters = emptyCounters();
411
+ startObservation(name, attributes, options) {
412
+ const { sessionId, userId } = this.context;
413
+ return this.backend.start(
414
+ name,
415
+ { ...attributes, sessionId, ...userId ? { userId } : {} },
416
+ options
417
+ );
418
+ }
419
+ hasActiveTrace() {
420
+ return this.root !== void 0;
421
+ }
422
+ hasActiveAttempt() {
423
+ return this.attempt !== void 0;
424
+ }
425
+ beginAgent(input) {
426
+ if (this.root) this.closeActiveTrace("Interrupted by a new Pi run.", void 0, "interrupted");
427
+ this.lastOutput = void 0;
428
+ this.lastAssistant = void 0;
429
+ this.lastAttemptOutcome = void 0;
430
+ this.unresolvedToolErrors = 0;
431
+ this.duplicateToolIds.clear();
432
+ this.startSnapshot = input.snapshot;
433
+ this.counters = emptyCounters();
434
+ const traceInput = this.capture({
435
+ prompt: input.prompt,
436
+ ...hasItems(input.images) ? { images: input.images } : {}
437
+ });
438
+ const metadata = {
439
+ "pi.cwd": this.context.cwd,
440
+ ...input.git?.branch ? { "pi.git.branch": input.git.branch } : {},
441
+ ...input.git?.commit ? { "pi.git.commit": input.git.commit } : {},
442
+ ...input.git ? { "pi.git.detached": input.git.detached } : {},
443
+ "pi.mode": this.context.mode,
444
+ ...input.model?.id ? { "pi.model": input.model.id } : {},
445
+ ...input.model?.provider ? { "pi.provider": input.model.provider } : {},
446
+ "pi.session.id": this.context.sessionId,
447
+ "pi.trace.schema_version": Number(TRACE_SCHEMA_VERSION),
448
+ ...snapshotMetadata("start", input.snapshot)
449
+ };
450
+ const attributes = { input: traceInput, metadata, version: TRACE_SCHEMA_VERSION };
451
+ const gitTag = input.git?.branch ? `branch:${input.git.branch}` : input.git?.detached ? "git:detached" : void 0;
452
+ this.root = this.startObservation("pi.agent", attributes, { asType: "agent" });
453
+ this.root.updateTrace?.({
454
+ name: "pi.trace",
455
+ sessionId: this.context.sessionId,
456
+ ...this.context.userId ? { userId: this.context.userId } : {},
457
+ version: TRACE_SCHEMA_VERSION,
458
+ input: traceInput,
459
+ metadata,
460
+ tags: ["pi", ...gitTag ? [gitTag] : []]
461
+ });
462
+ }
463
+ beginAttempt(input = {}) {
464
+ if (!this.root) return;
465
+ if (this.attempt) {
466
+ this.closeAttempt(void 0, "Interrupted by the next Pi attempt.", "interrupted");
467
+ }
468
+ const index = this.counters.attempts;
469
+ this.counters.attempts += 1;
470
+ this.lastAssistant = void 0;
471
+ this.unresolvedToolErrors = 0;
472
+ this.attemptIndex = index;
473
+ this.attempt = this.startObservation(
474
+ "pi.attempt",
475
+ {
476
+ metadata: {
477
+ "pi.attempt.index": index,
478
+ ...input.reason ? { "pi.attempt.reason": input.reason } : {}
479
+ },
480
+ version: TRACE_SCHEMA_VERSION
481
+ },
482
+ { asType: "span", parent: this.root }
483
+ );
484
+ }
485
+ finishAttempt(message) {
486
+ if (message?.role === "assistant") this.finishAssistant(message);
487
+ if (!this.attempt) return;
488
+ const outcome = this.unresolvedToolErrors > 0 ? "error" : classifyOutcome(message);
489
+ this.closeAttempt(
490
+ message,
491
+ this.unresolvedToolErrors > 0 ? "Pi attempt ended after a tool failure." : void 0,
492
+ outcome
493
+ );
494
+ }
495
+ beginTurn(turnIndex) {
496
+ if (!this.root) return;
497
+ if (this.turn) this.closeTurn("Interrupted by the next Pi turn.", "ERROR");
498
+ this.counters.turns += 1;
499
+ this.turnIndex = turnIndex;
500
+ this.turn = this.startObservation(
501
+ "pi.turn",
502
+ { metadata: { "pi.turn.index": turnIndex }, version: TRACE_SCHEMA_VERSION },
503
+ { asType: "span", parent: this.attempt ?? this.root }
504
+ );
505
+ }
506
+ finishTurn(turnIndex, result) {
507
+ if (!this.turn) return;
508
+ this.closeGeneration("Turn ended without a finalized assistant message.");
509
+ this.closeTools("Tool span ended when the Pi turn finished.");
510
+ const mismatched = this.turnIndex !== turnIndex;
511
+ const outcome = classifyOutcome(result.message);
512
+ this.turn.update({
513
+ metadata: {
514
+ "pi.turn.index": this.turnIndex ?? turnIndex,
515
+ "pi.turn.tool_result_count": result.toolResultCount,
516
+ ...result.message.stopReason ? { "pi.turn.stop_reason": result.message.stopReason } : {}
517
+ },
518
+ ...mismatched && outcome === "success" ? {
519
+ level: "WARNING",
520
+ statusMessage: `Turn ${turnIndex} ended while turn ${this.turnIndex} was active.`
521
+ } : severityForOutcome(outcome, result.message.errorMessage)
522
+ });
523
+ this.turn.end();
524
+ this.turn = void 0;
525
+ this.turnIndex = void 0;
526
+ }
527
+ beginGeneration(input = {}) {
528
+ if (!this.root) return;
529
+ this.closeGeneration("Interrupted by the next provider request.");
530
+ if (this.unresolvedToolErrors > 0) {
531
+ this.counters.recoveredErrors += this.unresolvedToolErrors;
532
+ this.unresolvedToolErrors = 0;
533
+ }
534
+ this.counters.generations += 1;
535
+ const requestMetadata = {
536
+ ...input.payloadStage ? { "pi.request.payload_stage": input.payloadStage } : {},
537
+ ...input.model?.provider ? { "pi.request.provider": input.model.provider } : {},
538
+ ...input.model?.id ? { "pi.request.model": input.model.id } : {},
539
+ ...input.model?.api ? { "pi.request.api": input.model.api } : {},
540
+ ...input.thinkingLevel ? { "pi.request.thinking_level": input.thinkingLevel } : {}
541
+ };
542
+ const observation = this.startObservation(
543
+ "pi.llm",
544
+ {
545
+ ...input.payload !== void 0 ? { input: this.capture(input.payload) } : {},
546
+ ...input.model?.id ? { model: input.model.id } : {},
547
+ ...input.thinkingLevel ? { modelParameters: { thinking_level: input.thinkingLevel } } : {},
548
+ ...Object.keys(requestMetadata).length > 0 ? { metadata: requestMetadata } : {},
549
+ version: TRACE_SCHEMA_VERSION
550
+ },
551
+ { asType: "generation", parent: this.turn ?? this.attempt ?? this.root }
552
+ );
553
+ this.generation = {
554
+ observation,
555
+ requestMetadata,
556
+ statuses: [],
557
+ headers: {}
558
+ };
559
+ }
560
+ recordProviderResponse(status, headers = {}) {
561
+ if (!this.generation) return;
562
+ this.generation.statuses.push(status);
563
+ Object.assign(this.generation.headers, allowlistedResponseHeaders(headers));
564
+ }
565
+ markGenerationFirstOutput(timestamp = Date.now()) {
566
+ if (this.generation && this.generation.completionStartTime === void 0) {
567
+ this.generation.completionStartTime = timestamp;
568
+ }
569
+ }
570
+ markGenerationEnd(endTime = Date.now()) {
571
+ if (this.generation && this.generation.endTime === void 0) {
572
+ this.generation.endTime = endTime;
573
+ }
574
+ }
575
+ finishAssistant(message) {
576
+ if (message.role !== "assistant") return;
577
+ this.lastAssistant = message;
578
+ this.lastOutput = this.capture(message.content);
579
+ if (!this.generation) return;
580
+ const state = this.generation;
581
+ const usageDetails = numericRecord({
582
+ input: message.usage?.input,
583
+ output: message.usage?.output,
584
+ cache_read_input_tokens: message.usage?.cacheRead,
585
+ cache_creation_input_tokens: message.usage?.cacheWrite,
586
+ total: message.usage?.totalTokens
587
+ });
588
+ const costDetails = positiveNumericRecord({
589
+ input: message.usage?.cost?.input,
590
+ output: message.usage?.cost?.output,
591
+ cache_read: message.usage?.cost?.cacheRead,
592
+ cache_write: message.usage?.cost?.cacheWrite,
593
+ total: message.usage?.cost?.total
594
+ });
595
+ const outcome = classifyOutcome(message);
596
+ const responseModel = message.responseModel ?? message.model;
597
+ const httpMetadata = generationHttpMetadata(state);
598
+ const recoveredStatuses = state.statuses.filter((status) => status >= 400).length;
599
+ if (outcome === "success" && recoveredStatuses > 0) {
600
+ this.counters.recoveredErrors += recoveredStatuses;
601
+ }
602
+ state.observation.update({
603
+ output: this.lastOutput,
604
+ ...state.completionStartTime !== void 0 ? { completionStartTime: new Date(state.completionStartTime) } : {},
605
+ ...responseModel ? { model: responseModel } : {},
606
+ ...Object.keys(usageDetails).length > 0 ? { usageDetails } : {},
607
+ ...Object.keys(costDetails).length > 0 ? { costDetails } : {},
608
+ metadata: {
609
+ ...state.requestMetadata,
610
+ ...httpMetadata,
611
+ ...message.provider ? { "pi.provider": message.provider, "pi.response.provider": message.provider } : {},
612
+ ...message.api ? { "pi.response.api": message.api } : {},
613
+ ...responseModel ? { "pi.response.model": responseModel } : {},
614
+ ...message.responseId ? { "pi.response.id": message.responseId } : {},
615
+ ...message.responseModel && message.model && message.responseModel !== message.model ? { "pi.requested_model": message.model } : {},
616
+ ...message.stopReason ? { "pi.stop_reason": message.stopReason } : {},
617
+ ...finiteNumber(message.usage?.reasoning) ? { "pi.usage.reasoning_tokens": message.usage.reasoning } : {},
618
+ ...finiteNumber(message.usage?.cacheWrite1h) ? { "pi.usage.cache_write_1h_tokens": message.usage.cacheWrite1h } : {}
619
+ },
620
+ ...severityForOutcome(outcome, message.errorMessage)
621
+ });
622
+ state.observation.end(state.endTime);
623
+ this.generation = void 0;
624
+ }
625
+ beginTool(toolCallId, toolName, args, startedAt = Date.now()) {
626
+ if (!this.root) return;
627
+ this.counters.tools += 1;
628
+ if (this.duplicateToolIds.has(toolCallId)) {
629
+ this.counters.toolErrors += 1;
630
+ const duplicate = this.startToolObservation(toolCallId, toolName, args);
631
+ duplicate.update({
632
+ level: "ERROR",
633
+ statusMessage: "Duplicate tool call ID cannot be correlated safely."
634
+ });
635
+ duplicate.end();
636
+ return;
637
+ }
638
+ const existing = this.tools.get(toolCallId);
639
+ if (existing) {
640
+ existing.observation.update({
641
+ level: "ERROR",
642
+ statusMessage: "Duplicate tool execution started."
643
+ });
644
+ existing.observation.end();
645
+ this.tools.delete(toolCallId);
646
+ this.counters.toolErrors += 2;
647
+ const duplicate = this.startToolObservation(toolCallId, toolName, args);
648
+ duplicate.update({
649
+ level: "ERROR",
650
+ statusMessage: "Duplicate tool call ID cannot be correlated safely."
651
+ });
652
+ duplicate.end();
653
+ this.duplicateToolIds.add(toolCallId);
654
+ return;
655
+ }
656
+ this.tools.set(toolCallId, {
657
+ observation: this.startToolObservation(toolCallId, toolName, args),
658
+ startedAt,
659
+ progressUpdates: 0
660
+ });
661
+ }
662
+ recordToolInput(toolCallId, input) {
663
+ if (input === void 0 || this.duplicateToolIds.has(toolCallId)) return;
664
+ this.tools.get(toolCallId)?.observation.update({ input: this.capture(input) });
665
+ }
666
+ recordToolProgress(toolCallId, timestamp = Date.now()) {
667
+ const tool = this.tools.get(toolCallId);
668
+ if (!tool) return;
669
+ tool.progressUpdates += 1;
670
+ tool.firstProgressAt ??= timestamp;
671
+ }
672
+ finishTool(toolCallId, result) {
673
+ if (this.duplicateToolIds.has(toolCallId)) return;
674
+ const tool = this.tools.get(toolCallId);
675
+ if (!tool) return;
676
+ if (result.isError) {
677
+ this.counters.toolErrors += 1;
678
+ this.unresolvedToolErrors += 1;
679
+ }
680
+ tool.observation.update({
681
+ output: this.capture({ content: result.content, details: result.details }),
682
+ metadata: {
683
+ "pi.tool.progress_update_count": tool.progressUpdates,
684
+ ...tool.firstProgressAt !== void 0 ? {
685
+ "pi.tool.time_to_first_progress_ms": Math.max(
686
+ 0,
687
+ tool.firstProgressAt - tool.startedAt
688
+ )
689
+ } : {}
690
+ },
691
+ ...result.isError ? { level: "ERROR", statusMessage: "Pi tool execution failed." } : {}
692
+ });
693
+ tool.observation.end();
694
+ this.tools.delete(toolCallId);
695
+ }
696
+ beginCompaction(input) {
697
+ if (!this.root) return;
698
+ this.closeCompaction("Interrupted by another Pi compaction.");
699
+ this.counters.compactions += 1;
700
+ this.compaction = {
701
+ observation: this.startObservation(
702
+ "pi.compaction",
703
+ {
704
+ metadata: {
705
+ "pi.compaction.reason": input.reason,
706
+ "pi.compaction.will_retry": input.willRetry,
707
+ ...finiteNumber(input.tokensBefore) ? { "pi.compaction.tokens_before": input.tokensBefore } : {},
708
+ "pi.compaction.messages_to_summarize": input.messagesToSummarize,
709
+ "pi.compaction.turn_prefix_messages": input.turnPrefixMessages,
710
+ "pi.compaction.branch_entries": input.branchEntries,
711
+ "pi.compaction.is_split_turn": input.isSplitTurn
712
+ },
713
+ version: TRACE_SCHEMA_VERSION
714
+ },
715
+ { asType: "span", parent: this.root }
716
+ )
717
+ };
718
+ }
719
+ finishCompaction(input) {
720
+ if (!this.compaction) return;
721
+ const details = structuralCompactionDetails(input.details);
722
+ const usage = numericRecord({
723
+ input: input.usage?.input,
724
+ output: input.usage?.output,
725
+ cache_read: input.usage?.cacheRead,
726
+ cache_write: input.usage?.cacheWrite,
727
+ total: input.usage?.totalTokens
728
+ });
729
+ const cost = positiveNumericRecord({
730
+ input: input.usage?.cost?.input,
731
+ output: input.usage?.cost?.output,
732
+ cache_read: input.usage?.cost?.cacheRead,
733
+ cache_write: input.usage?.cost?.cacheWrite,
734
+ total: input.usage?.cost?.total
735
+ });
736
+ this.compaction.observation.update({
737
+ metadata: {
738
+ "pi.compaction.reason": input.reason,
739
+ "pi.compaction.will_retry": input.willRetry,
740
+ "pi.compaction.from_extension": input.fromExtension,
741
+ ...finiteNumber(input.tokensBefore) ? { "pi.compaction.tokens_before": input.tokensBefore } : {},
742
+ ...details,
743
+ ...prefixRecord("pi.compaction.usage", usage),
744
+ ...prefixRecord("pi.compaction.cost", cost)
745
+ }
746
+ });
747
+ this.compaction.observation.end();
748
+ this.compaction = void 0;
749
+ }
750
+ settle(snapshot) {
751
+ this.closeActiveTrace(void 0, snapshot);
752
+ }
753
+ interrupt(statusMessage, snapshot) {
754
+ this.closeActiveTrace(statusMessage, snapshot, "interrupted");
755
+ }
756
+ async flush() {
757
+ await this.backend.forceFlush();
758
+ }
759
+ async shutdown(snapshot) {
760
+ this.closeActiveTrace("Pi shut down before the active trace settled.", snapshot, "interrupted");
761
+ await this.backend.shutdown();
762
+ }
763
+ closeActiveTrace(statusMessage, snapshot, forcedOutcome) {
764
+ this.closeTurn(statusMessage ?? "Pi turn ended when the agent run settled.");
765
+ this.closeAttempt(void 0, statusMessage, forcedOutcome ?? "interrupted");
766
+ this.closeCompaction(statusMessage ?? "Pi compaction ended when the agent run settled.");
767
+ if (!this.root) return;
768
+ const baseOutcome = forcedOutcome ?? this.lastAttemptOutcome ?? classifyOutcome(this.lastAssistant);
769
+ const recoveredErrorCount = this.counters.recoveredErrors + (baseOutcome === "success" ? this.counters.failedAttempts : 0);
770
+ const traceOutcome = baseOutcome === "success" && recoveredErrorCount > 0 ? "recovered_success" : baseOutcome;
771
+ const finalMetadata = {
772
+ "pi.trace.schema_version": Number(TRACE_SCHEMA_VERSION),
773
+ "pi.trace.outcome": traceOutcome,
774
+ ...this.lastAssistant?.stopReason ? { "pi.trace.stop_reason": this.lastAssistant.stopReason } : {},
775
+ "pi.trace.attempt_count": this.counters.attempts,
776
+ "pi.trace.turn_count": this.counters.turns,
777
+ "pi.trace.generation_count": this.counters.generations,
778
+ "pi.trace.tool_count": this.counters.tools,
779
+ "pi.trace.tool_error_count": this.counters.toolErrors,
780
+ "pi.trace.compaction_count": this.counters.compactions,
781
+ "pi.trace.recovered_error_count": recoveredErrorCount,
782
+ ...snapshotMetadata("start", this.startSnapshot),
783
+ ...snapshotMetadata("end", snapshot)
784
+ };
785
+ const finalAttributes = {
786
+ ...this.lastOutput !== void 0 ? { output: this.lastOutput } : {},
787
+ metadata: finalMetadata,
788
+ ...severityForOutcome(baseOutcome, statusMessage ?? this.lastAssistant?.errorMessage)
789
+ };
790
+ this.root.update(finalAttributes);
791
+ this.root.updateTrace?.({
792
+ ...this.lastOutput !== void 0 ? { output: this.lastOutput } : {},
793
+ metadata: finalMetadata,
794
+ version: TRACE_SCHEMA_VERSION
795
+ });
796
+ this.root.end();
797
+ this.root = void 0;
798
+ this.lastOutput = void 0;
799
+ this.lastAssistant = void 0;
800
+ this.lastAttemptOutcome = void 0;
801
+ this.unresolvedToolErrors = 0;
802
+ this.duplicateToolIds.clear();
803
+ this.startSnapshot = void 0;
804
+ }
805
+ closeAttempt(message, statusMessage, forcedOutcome) {
806
+ if (!this.attempt) return;
807
+ this.closeTurn(statusMessage ?? "Pi turn ended when the attempt finished.");
808
+ const outcome = forcedOutcome ?? classifyOutcome(message);
809
+ if (outcome === "error") this.counters.failedAttempts += 1;
810
+ this.lastAttemptOutcome = outcome;
811
+ this.attempt.update({
812
+ ...message?.content !== void 0 ? { output: this.capture(message.content) } : {},
813
+ metadata: {
814
+ "pi.attempt.index": this.attemptIndex ?? Math.max(0, this.counters.attempts - 1),
815
+ "pi.attempt.outcome": outcome,
816
+ ...message?.stopReason ? { "pi.attempt.stop_reason": message.stopReason } : {}
817
+ },
818
+ ...severityForOutcome(outcome, statusMessage ?? message?.errorMessage)
819
+ });
820
+ this.attempt.end();
821
+ this.attempt = void 0;
822
+ this.attemptIndex = void 0;
823
+ this.unresolvedToolErrors = 0;
824
+ }
825
+ startToolObservation(toolCallId, toolName, args) {
826
+ return this.startObservation(
827
+ `pi.tool.${toolName}`,
828
+ {
829
+ ...args !== void 0 ? { input: this.capture(args) } : {},
830
+ metadata: { "pi.tool.call_id": toolCallId, "pi.tool.name": toolName },
831
+ version: TRACE_SCHEMA_VERSION
832
+ },
833
+ { asType: "tool", parent: this.turn ?? this.attempt ?? this.root }
834
+ );
835
+ }
836
+ closeTurn(statusMessage, generationLevel = "WARNING") {
837
+ this.closeGeneration(statusMessage, generationLevel);
838
+ this.closeTools(statusMessage);
839
+ if (!this.turn) return;
840
+ this.turn.update({ level: "WARNING", statusMessage });
841
+ this.turn.end();
842
+ this.turn = void 0;
843
+ this.turnIndex = void 0;
844
+ }
845
+ closeTools(statusMessage) {
846
+ for (const tool of this.tools.values()) {
847
+ tool.observation.update({
848
+ level: "WARNING",
849
+ statusMessage,
850
+ metadata: {
851
+ "pi.tool.progress_update_count": tool.progressUpdates,
852
+ ...tool.firstProgressAt !== void 0 ? {
853
+ "pi.tool.time_to_first_progress_ms": Math.max(
854
+ 0,
855
+ tool.firstProgressAt - tool.startedAt
856
+ )
857
+ } : {}
858
+ }
859
+ });
860
+ tool.observation.end();
861
+ }
862
+ this.tools.clear();
863
+ }
864
+ closeGeneration(statusMessage, level = "ERROR") {
865
+ if (!this.generation) return;
866
+ this.generation.observation.update({
867
+ level,
868
+ statusMessage,
869
+ metadata: {
870
+ ...this.generation.requestMetadata,
871
+ ...generationHttpMetadata(this.generation)
872
+ }
873
+ });
874
+ this.generation.observation.end(this.generation.endTime);
875
+ this.generation = void 0;
876
+ }
877
+ closeCompaction(statusMessage) {
878
+ if (!this.compaction) return;
879
+ this.compaction.observation.update({ level: "WARNING", statusMessage });
880
+ this.compaction.observation.end();
881
+ this.compaction = void 0;
882
+ }
883
+ capture(value) {
884
+ return this.context.captureContent ? sanitizeTraceValue(value) : CONTENT_DISABLED;
885
+ }
886
+ };
887
+ function generationHttpMetadata(state) {
888
+ const finalStatus = state.statuses.at(-1);
889
+ return {
890
+ ...state.statuses.length > 0 ? {
891
+ "http.response.status_codes": [...state.statuses],
892
+ "http.response.status_code": finalStatus,
893
+ "http.response.attempt_count": state.statuses.length,
894
+ "http.response.retry_count": Math.max(0, state.statuses.length - 1)
895
+ } : {},
896
+ ...Object.keys(state.headers).length > 0 ? { "http.response.headers": { ...state.headers } } : {}
897
+ };
898
+ }
899
+ function allowlistedResponseHeaders(headers) {
900
+ const output = {};
901
+ for (const [rawName, rawValue] of Object.entries(headers)) {
902
+ const name = rawName.toLowerCase();
903
+ if (!ALLOWED_RESPONSE_HEADERS.has(name) || typeof rawValue !== "string") continue;
904
+ output[name] = truncateString2(rawValue, MAX_HEADER_VALUE_LENGTH);
905
+ }
906
+ return output;
907
+ }
908
+ function structuralCompactionDetails(details) {
909
+ if (!details || typeof details !== "object" || Array.isArray(details)) return {};
910
+ const record = details;
911
+ return {
912
+ ...Array.isArray(record.readFiles) ? { "pi.compaction.read_file_count": record.readFiles.length } : {},
913
+ ...Array.isArray(record.modifiedFiles) ? { "pi.compaction.modified_file_count": record.modifiedFiles.length } : {}
914
+ };
915
+ }
916
+ function snapshotMetadata(prefix, snapshot) {
917
+ if (!snapshot) return {};
918
+ return {
919
+ ...snapshot.leafId ? { [`pi.trace.${prefix}_leaf_id`]: snapshot.leafId } : {},
920
+ ...snapshot.contextUsage ? {
921
+ ...finiteNumber(snapshot.contextUsage.tokens) ? { [`pi.trace.${prefix}_context_tokens`]: snapshot.contextUsage.tokens } : {},
922
+ [`pi.trace.${prefix}_context_window`]: snapshot.contextUsage.contextWindow,
923
+ ...finiteNumber(snapshot.contextUsage.percent) ? { [`pi.trace.${prefix}_context_percent`]: snapshot.contextUsage.percent } : {}
924
+ } : {}
925
+ };
926
+ }
927
+ function classifyOutcome(message) {
928
+ if (message?.role !== "assistant") return "interrupted";
929
+ if (message.stopReason === "error" || message.errorMessage) return "error";
930
+ if (message.stopReason === "aborted") return "aborted";
931
+ if (message.stopReason === "length") return "length";
932
+ return "success";
933
+ }
934
+ function severityForOutcome(outcome, statusMessage) {
935
+ if (outcome === "success") return {};
936
+ if (outcome === "error") {
937
+ return {
938
+ level: "ERROR",
939
+ statusMessage: statusMessage ?? "The Pi operation failed."
940
+ };
941
+ }
942
+ return {
943
+ level: "WARNING",
944
+ statusMessage: statusMessage ?? (outcome === "aborted" ? "The Pi operation was aborted." : outcome === "length" ? "The model reached its output limit." : "The Pi operation was interrupted.")
945
+ };
946
+ }
947
+ function prefixRecord(prefix, values) {
948
+ return Object.fromEntries(
949
+ Object.entries(values).map(([key, value]) => [`${prefix}.${key}`, value])
950
+ );
951
+ }
952
+ function truncateString2(value, maxBytes) {
953
+ const boundedPrefix = value.slice(0, maxBytes);
954
+ if (boundedPrefix.length === value.length && byteLength2(boundedPrefix) <= maxBytes) {
955
+ return boundedPrefix;
956
+ }
957
+ const suffix = "\u2026 [truncated]";
958
+ const target = Math.max(0, maxBytes - byteLength2(suffix) - 2);
959
+ let bytes = 0;
960
+ let output = "";
961
+ for (const character of boundedPrefix) {
962
+ const size = byteLength2(character);
963
+ if (bytes + size > target) break;
964
+ output += character;
965
+ bytes += size;
966
+ }
967
+ return `${output}${suffix}`;
968
+ }
969
+ function byteLength2(value) {
970
+ return Buffer.byteLength(value, "utf8");
971
+ }
972
+ function numericRecord(values) {
973
+ return Object.fromEntries(
974
+ Object.entries(values).filter((entry) => finiteNumber(entry[1]))
975
+ );
976
+ }
977
+ function positiveNumericRecord(values) {
978
+ return Object.fromEntries(
979
+ Object.entries(values).filter(
980
+ (entry) => finiteNumber(entry[1]) && entry[1] > 0
981
+ )
982
+ );
983
+ }
984
+ function finiteNumber(value) {
985
+ return typeof value === "number" && Number.isFinite(value);
986
+ }
987
+ function hasItems(value) {
988
+ return Array.isArray(value) ? value.length > 0 : value !== void 0;
989
+ }
990
+ function emptyCounters() {
991
+ return {
992
+ attempts: 0,
993
+ turns: 0,
994
+ generations: 0,
995
+ tools: 0,
996
+ toolErrors: 0,
997
+ compactions: 0,
998
+ recoveredErrors: 0,
999
+ failedAttempts: 0
1000
+ };
1001
+ }
1002
+
1003
+ // src/langfuse.ts
1004
+ var FLUSH_ACTION = "Flush completed traces for this session";
1005
+ var SET_UP_ACTION = "Set up Langfuse for this Pi agent directory (restart required)";
1006
+ var UPDATE_ACTION = "Update Langfuse for this Pi agent directory (restart required)";
1007
+ var HELP_ACTION = "Show setup and privacy help";
1008
+ function createLangfuseExtension(dependencies = {}) {
1009
+ const loadConfig = dependencies.loadConfig ?? loadLangfuseConfig;
1010
+ const writeConfig = dependencies.writeConfig ?? writeLangfuseConfig;
1011
+ const createBackend = dependencies.createBackend ?? (async (config) => {
1012
+ const { createProductionBackend } = await import("./chunks/runtime-NX5HM7IU.js");
1013
+ return createProductionBackend(config);
1014
+ });
1015
+ return function langfuse(pi) {
1016
+ const resolveGit = dependencies.resolveGitMetadata ?? ((cwd) => resolveGitMetadata((command, args, options) => pi.exec(command, args, options), cwd));
1017
+ let recorder;
1018
+ let activeConfig;
1019
+ let configPath;
1020
+ let initializationError;
1021
+ let hasStoredConfig = false;
1022
+ let configurationNotice;
1023
+ let sessionGeneration = 0;
1024
+ let menuController = new AbortController();
1025
+ let configWriteQueue = Promise.resolve();
1026
+ let nextAttemptReason;
1027
+ async function showLangfuseMenu(ctx) {
1028
+ if (!ctx.hasUI) {
1029
+ ctx.ui.notify(
1030
+ formatNonInteractiveStatus(activeConfig, configPath, initializationError),
1031
+ "warning"
1032
+ );
1033
+ return;
1034
+ }
1035
+ const menuGeneration = sessionGeneration;
1036
+ const menuSignal = menuController.signal;
1037
+ const isCurrent = () => menuGeneration === sessionGeneration && !menuSignal.aborted;
1038
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
1039
+ if (!isCurrent()) return;
1040
+ const menu = defineMenu({
1041
+ start: "main",
1042
+ screens: {
1043
+ main: () => ({
1044
+ kind: "actions",
1045
+ title: "Langfuse",
1046
+ lines: formatMenuTitle(
1047
+ activeConfig,
1048
+ configPath,
1049
+ initializationError,
1050
+ configurationNotice
1051
+ ).split("\n").slice(1),
1052
+ items: [
1053
+ ...recorder ? [{ id: "flush", label: FLUSH_ACTION, action: "flush" }] : [],
1054
+ {
1055
+ id: "configure",
1056
+ label: hasStoredConfig ? UPDATE_ACTION : SET_UP_ACTION,
1057
+ action: "configure"
1058
+ },
1059
+ { id: "help", label: HELP_ACTION, action: "help" }
1060
+ ],
1061
+ hint: "close"
1062
+ })
1063
+ },
1064
+ actions: {
1065
+ flush: async () => {
1066
+ const menuRecorder = recorder;
1067
+ const menuConfig = activeConfig;
1068
+ if (!menuRecorder) {
1069
+ ctx.ui.notify("Langfuse tracing is not enabled for this session.", "warning");
1070
+ return { kind: "close" };
1071
+ }
1072
+ try {
1073
+ await menuRecorder.flush();
1074
+ if (menuGeneration !== sessionGeneration) return { kind: "close" };
1075
+ ctx.ui.notify("Langfuse traces flushed for this session.", "info");
1076
+ } catch (error) {
1077
+ if (menuGeneration !== sessionGeneration) return { kind: "close" };
1078
+ ctx.ui.notify(`Langfuse flush failed: ${formatError2(error, menuConfig)}`, "error");
1079
+ }
1080
+ return { kind: "close" };
1081
+ },
1082
+ configure: async () => {
1083
+ const loaded = await loadConfig(configPath);
1084
+ if (menuGeneration !== sessionGeneration) return { kind: "close" };
1085
+ configPath = loaded.path;
1086
+ const next = await promptForConfig(
1087
+ ctx,
1088
+ loaded.ok ? loaded.config : void 0,
1089
+ () => menuGeneration === sessionGeneration
1090
+ );
1091
+ if (!next || menuGeneration !== sessionGeneration) return { kind: "close" };
1092
+ try {
1093
+ const write = configWriteQueue.then(() => writeConfig(next, loaded.path));
1094
+ configWriteQueue = write.then(
1095
+ () => void 0,
1096
+ () => void 0
1097
+ );
1098
+ await write;
1099
+ if (menuGeneration !== sessionGeneration) return { kind: "close" };
1100
+ hasStoredConfig = true;
1101
+ configurationNotice = "Saved; restart each Pi process to use it in subsequent sessions.";
1102
+ ctx.ui.notify(
1103
+ `Saved Langfuse config to ${loaded.path} for this Pi agent directory. Restart each Pi process to apply it to subsequent sessions.`,
1104
+ "info"
1105
+ );
1106
+ } catch (error) {
1107
+ if (menuGeneration !== sessionGeneration) return { kind: "close" };
1108
+ ctx.ui.notify(`Failed to save Langfuse config: ${formatError2(error, next)}`, "error");
1109
+ }
1110
+ return { kind: "close" };
1111
+ },
1112
+ help: async () => {
1113
+ ctx.ui.notify(formatHelp(configPath), "info");
1114
+ return { kind: "close" };
1115
+ }
1116
+ }
1117
+ });
1118
+ await runMenu(ctx, menu, {
1119
+ getState: () => void 0,
1120
+ signal: menuSignal,
1121
+ isCurrent
1122
+ });
1123
+ }
1124
+ pi.registerCommand("langfuse", {
1125
+ description: "Open interactive Langfuse tracing controls",
1126
+ handler: async (_args, ctx) => showLangfuseMenu(ctx)
1127
+ });
1128
+ pi.on("session_start", async (_event, ctx) => {
1129
+ const generation = ++sessionGeneration;
1130
+ menuController.abort(new DOMException("Langfuse session replaced", "AbortError"));
1131
+ menuController = new AbortController();
1132
+ recorder = void 0;
1133
+ activeConfig = void 0;
1134
+ configPath = void 0;
1135
+ initializationError = void 0;
1136
+ hasStoredConfig = false;
1137
+ configurationNotice = void 0;
1138
+ nextAttemptReason = void 0;
1139
+ await configWriteQueue;
1140
+ if (generation !== sessionGeneration) return;
1141
+ const result = await loadConfig();
1142
+ if (generation !== sessionGeneration) return;
1143
+ configPath = result.path;
1144
+ for (const warning of result.warnings) ctx.ui.notify(warning, "warning");
1145
+ if (!result.ok) {
1146
+ initializationError = formatConfigError(result);
1147
+ ctx.ui.notify(initializationError, "warning");
1148
+ return;
1149
+ }
1150
+ hasStoredConfig = true;
1151
+ try {
1152
+ const backend = await createBackend(result.config);
1153
+ if (generation !== sessionGeneration) {
1154
+ await backend.shutdown().catch(() => void 0);
1155
+ return;
1156
+ }
1157
+ activeConfig = result.config;
1158
+ recorder = new TraceRecorder(backend, {
1159
+ sessionId: ctx.sessionManager.getSessionId(),
1160
+ ...result.config.userId ? { userId: result.config.userId } : {},
1161
+ cwd: ctx.cwd,
1162
+ mode: ctx.mode,
1163
+ captureContent: result.config.captureContent
1164
+ });
1165
+ } catch (error) {
1166
+ if (generation !== sessionGeneration) return;
1167
+ initializationError = `Langfuse tracing could not start: ${formatError2(error, result.config)}`;
1168
+ ctx.ui.notify(initializationError, "warning");
1169
+ }
1170
+ });
1171
+ pi.on("before_agent_start", async (event, ctx) => {
1172
+ nextAttemptReason = void 0;
1173
+ const activeRecorder = recorder;
1174
+ if (!activeRecorder) return;
1175
+ const git = await resolveGit(ctx.cwd).catch(() => void 0);
1176
+ if (recorder !== activeRecorder) return;
1177
+ activeRecorder.beginAgent({
1178
+ prompt: event.prompt,
1179
+ images: event.images,
1180
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
1181
+ git,
1182
+ snapshot: contextSnapshot(ctx)
1183
+ });
1184
+ });
1185
+ pi.on("agent_start", () => {
1186
+ if (!recorder) return;
1187
+ recorder.beginAttempt(nextAttemptReason ? { reason: nextAttemptReason } : void 0);
1188
+ nextAttemptReason = void 0;
1189
+ });
1190
+ pi.on("turn_start", (event, ctx) => {
1191
+ if (!recorder) return;
1192
+ ensureActiveRun(recorder, ctx);
1193
+ recorder.beginTurn(event.turnIndex);
1194
+ });
1195
+ pi.on("before_provider_request", (event, ctx) => {
1196
+ if (!recorder) return;
1197
+ ensureActiveRun(recorder, ctx);
1198
+ recorder.beginGeneration({
1199
+ payload: event.payload,
1200
+ payloadStage: "before_provider_request",
1201
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
1202
+ thinkingLevel: pi.getThinkingLevel()
1203
+ });
1204
+ });
1205
+ pi.on("after_provider_response", (event) => {
1206
+ recorder?.recordProviderResponse(event.status, event.headers);
1207
+ });
1208
+ pi.on("message_update", (event) => {
1209
+ if (isRealOutputDelta(event.assistantMessageEvent)) recorder?.markGenerationFirstOutput();
1210
+ });
1211
+ pi.on("message_end", (event) => {
1212
+ if (event.message.role === "assistant") recorder?.markGenerationEnd();
1213
+ });
1214
+ pi.on("turn_end", (event) => {
1215
+ if (event.message.role === "assistant") recorder?.finishAssistant(event.message);
1216
+ recorder?.finishTurn(event.turnIndex, {
1217
+ message: event.message,
1218
+ toolResultCount: event.toolResults.length
1219
+ });
1220
+ });
1221
+ pi.on("tool_execution_start", (event) => {
1222
+ recorder?.beginTool(event.toolCallId, event.toolName, event.args);
1223
+ });
1224
+ pi.on("tool_execution_update", (event) => {
1225
+ recorder?.recordToolProgress(event.toolCallId);
1226
+ });
1227
+ pi.on("tool_result", (event) => {
1228
+ recorder?.recordToolInput(event.toolCallId, event.input);
1229
+ });
1230
+ pi.on("tool_execution_end", (event) => {
1231
+ recorder?.finishTool(event.toolCallId, {
1232
+ content: event.result.content,
1233
+ details: event.result.details,
1234
+ isError: event.isError
1235
+ });
1236
+ });
1237
+ pi.on("agent_end", (event) => {
1238
+ const message = findLastAssistant(event.messages);
1239
+ recorder?.finishAttempt(message);
1240
+ });
1241
+ pi.on("session_before_compact", (event) => {
1242
+ recorder?.beginCompaction({
1243
+ reason: event.reason,
1244
+ willRetry: event.willRetry,
1245
+ tokensBefore: event.preparation.tokensBefore,
1246
+ messagesToSummarize: event.preparation.messagesToSummarize.length,
1247
+ turnPrefixMessages: event.preparation.turnPrefixMessages.length,
1248
+ branchEntries: event.branchEntries.length,
1249
+ isSplitTurn: event.preparation.isSplitTurn
1250
+ });
1251
+ });
1252
+ pi.on("session_compact", (event) => {
1253
+ const entry = event.compactionEntry;
1254
+ recorder?.finishCompaction({
1255
+ reason: event.reason,
1256
+ willRetry: event.willRetry,
1257
+ fromExtension: event.fromExtension,
1258
+ tokensBefore: entry.tokensBefore,
1259
+ details: entry.details,
1260
+ usage: entry.usage
1261
+ });
1262
+ if (event.willRetry && recorder?.hasActiveTrace()) nextAttemptReason = "post_compaction";
1263
+ });
1264
+ pi.on("agent_settled", (_event, ctx) => {
1265
+ recorder?.settle(contextSnapshot(ctx));
1266
+ nextAttemptReason = void 0;
1267
+ });
1268
+ pi.on("session_shutdown", async (event, ctx) => {
1269
+ const generation = ++sessionGeneration;
1270
+ menuController.abort(new DOMException("Langfuse session shut down", "AbortError"));
1271
+ const activeRecorder = recorder;
1272
+ const shutdownConfig = activeConfig;
1273
+ const pendingConfigWrite = configWriteQueue;
1274
+ const shutdownSnapshot = activeRecorder ? contextSnapshot(ctx) : void 0;
1275
+ recorder = void 0;
1276
+ activeConfig = void 0;
1277
+ await pendingConfigWrite;
1278
+ if (!activeRecorder) return;
1279
+ try {
1280
+ if (event.reason === "quit") await activeRecorder.shutdown(shutdownSnapshot);
1281
+ else {
1282
+ activeRecorder.interrupt(
1283
+ `Pi session ended before settlement (${event.reason}).`,
1284
+ shutdownSnapshot
1285
+ );
1286
+ await activeRecorder.flush();
1287
+ }
1288
+ } catch (error) {
1289
+ if (generation !== sessionGeneration) return;
1290
+ ctx.ui.notify(
1291
+ `Langfuse shutdown export failed: ${formatError2(error, shutdownConfig)}`,
1292
+ "error"
1293
+ );
1294
+ }
1295
+ });
1296
+ };
1297
+ }
1298
+ function ensureActiveRun(recorder, ctx) {
1299
+ if (!recorder.hasActiveTrace()) {
1300
+ recorder.beginAgent({
1301
+ prompt: "[automatic continuation]",
1302
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
1303
+ snapshot: contextSnapshot(ctx)
1304
+ });
1305
+ }
1306
+ if (!recorder.hasActiveAttempt()) recorder.beginAttempt();
1307
+ }
1308
+ function contextSnapshot(ctx) {
1309
+ return {
1310
+ leafId: typeof ctx.sessionManager.getLeafId === "function" ? ctx.sessionManager.getLeafId() : void 0,
1311
+ contextUsage: ctx.getContextUsage()
1312
+ };
1313
+ }
1314
+ function findLastAssistant(messages) {
1315
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1316
+ const message = messages[index];
1317
+ if (message?.role === "assistant") return message;
1318
+ }
1319
+ return void 0;
1320
+ }
1321
+ function isRealOutputDelta(event) {
1322
+ return (event.type === "text_delta" || event.type === "thinking_delta" || event.type === "toolcall_delta") && typeof event.delta === "string" && event.delta.length > 0;
1323
+ }
1324
+ var GIT_LOOKUP_TIMEOUT_MS = 1e3;
1325
+ var MAX_GIT_BRANCH_LENGTH = 256;
1326
+ async function resolveGitMetadata(exec, cwd) {
1327
+ const [branchResult, commit] = await Promise.all([
1328
+ resolveGitBranch(exec, cwd),
1329
+ resolveGitCommit(exec, cwd)
1330
+ ]);
1331
+ if (!branchResult.resolved) return void 0;
1332
+ if (branchResult.branch) {
1333
+ return {
1334
+ branch: branchResult.branch,
1335
+ ...commit ? { commit } : {},
1336
+ detached: false
1337
+ };
1338
+ }
1339
+ return commit ? { commit, detached: true } : void 0;
1340
+ }
1341
+ async function resolveGitBranch(exec, cwd) {
1342
+ try {
1343
+ const result = await exec("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
1344
+ cwd,
1345
+ timeout: GIT_LOOKUP_TIMEOUT_MS
1346
+ });
1347
+ if (result.killed) return { resolved: false };
1348
+ if (result.code === 1) return { resolved: true };
1349
+ if (result.code !== 0) return { resolved: false };
1350
+ const branch = normalizeGitBranch(result.stdout);
1351
+ return branch ? { resolved: true, branch } : { resolved: false };
1352
+ } catch {
1353
+ return { resolved: false };
1354
+ }
1355
+ }
1356
+ async function resolveGitCommit(exec, cwd) {
1357
+ try {
1358
+ const result = await exec("git", ["rev-parse", "--verify", "--short=12", "HEAD"], {
1359
+ cwd,
1360
+ timeout: GIT_LOOKUP_TIMEOUT_MS
1361
+ });
1362
+ if (result.code !== 0 || result.killed) return void 0;
1363
+ const commit = result.stdout.trim();
1364
+ return /^[0-9a-f]{4,64}$/iu.test(commit) ? commit.toLowerCase() : void 0;
1365
+ } catch {
1366
+ return void 0;
1367
+ }
1368
+ }
1369
+ function normalizeGitBranch(value) {
1370
+ const branch = value.trim();
1371
+ if (!branch || branch.length > MAX_GIT_BRANCH_LENGTH) return void 0;
1372
+ for (const character of branch) {
1373
+ const code = character.codePointAt(0) ?? 0;
1374
+ if (code <= 31 || code === 127) return void 0;
1375
+ }
1376
+ return branch;
1377
+ }
1378
+ async function promptForConfig(ctx, current, isCurrent) {
1379
+ const secretKey = await ctx.ui.input("Langfuse secret key (leave blank to keep existing):");
1380
+ if (!isCurrent()) return void 0;
1381
+ if (secretKey === void 0) {
1382
+ ctx.ui.notify("Cancelled", "info");
1383
+ return void 0;
1384
+ }
1385
+ const publicKey = await ctx.ui.input("Langfuse public key (leave blank to keep existing):");
1386
+ if (!isCurrent()) return void 0;
1387
+ if (publicKey === void 0) {
1388
+ ctx.ui.notify("Cancelled", "info");
1389
+ return void 0;
1390
+ }
1391
+ const baseUrl = await ctx.ui.input(
1392
+ `Langfuse base URL (leave blank for default ${DEFAULT_BASE_URL}):`,
1393
+ DEFAULT_BASE_URL
1394
+ );
1395
+ if (!isCurrent()) return void 0;
1396
+ if (baseUrl === void 0) {
1397
+ ctx.ui.notify("Cancelled", "info");
1398
+ return void 0;
1399
+ }
1400
+ const patch = {
1401
+ ...publicKey.trim() ? { publicKey: publicKey.trim() } : {},
1402
+ ...secretKey.trim() ? { secretKey: secretKey.trim() } : {},
1403
+ baseUrl: baseUrl.trim() || DEFAULT_BASE_URL
1404
+ };
1405
+ const normalized = normalizeLangfuseConfig({ ...current, ...patch });
1406
+ if (!normalized.ok) {
1407
+ ctx.ui.notify(`Invalid Langfuse config: ${normalized.reason}`, "error");
1408
+ return void 0;
1409
+ }
1410
+ return patch;
1411
+ }
1412
+ function formatMenuTitle(activeConfig, configPath, initializationError, configurationNotice) {
1413
+ const lines = [
1414
+ "Langfuse",
1415
+ "",
1416
+ "Current session:",
1417
+ ` Tracing: ${activeConfig ? "enabled" : "disabled"}`
1418
+ ];
1419
+ if (activeConfig) {
1420
+ lines.push(
1421
+ ` Endpoint: ${activeConfig.baseUrl}`,
1422
+ ` Content capture: ${activeConfig.captureContent ? "enabled" : "disabled"}`
1423
+ );
1424
+ } else if (configurationNotice) {
1425
+ lines.push(" State: tracing remains disabled until Pi restarts.");
1426
+ } else if (initializationError) {
1427
+ lines.push(` Reason: ${initializationError}`);
1428
+ }
1429
+ lines.push(
1430
+ "",
1431
+ "Agent-directory configuration:",
1432
+ ` Configuration: ${configPath ?? "unknown"}`,
1433
+ " Scope: this Pi agent directory; restart each Pi process to apply changes."
1434
+ );
1435
+ if (configurationNotice) lines.push(` Pending: ${configurationNotice}`);
1436
+ lines.push("", "What do you want to do?");
1437
+ return lines.join("\n");
1438
+ }
1439
+ function formatNonInteractiveStatus(activeConfig, configPath, initializationError) {
1440
+ return [
1441
+ "/langfuse requires interactive UI.",
1442
+ `Current session tracing: ${activeConfig ? "enabled" : "disabled"}`,
1443
+ ...activeConfig ? [
1444
+ `Endpoint: ${activeConfig.baseUrl}`,
1445
+ `Content capture: ${activeConfig.captureContent ? "enabled" : "disabled"}`
1446
+ ] : initializationError ? [`Reason: ${initializationError}`] : [],
1447
+ `Configuration: ${configPath ?? "unknown"}`,
1448
+ "Edit the private config manually, then restart each Pi process to apply it to subsequent sessions."
1449
+ ].join("\n");
1450
+ }
1451
+ function formatHelp(configPath) {
1452
+ return [
1453
+ "Langfuse setup and privacy:",
1454
+ "Run /langfuse in interactive Pi to manage tracing for the current session.",
1455
+ `Configuration: ${configPath ?? "pi-langfuse.json"}`,
1456
+ "The file belongs to this Pi agent directory; restart each Pi process after changing it.",
1457
+ "Trace content may contain prompts, responses, tool arguments, tool results, and source code.",
1458
+ "Git branch, commit, cwd, model, and usage remain in metadata when content capture is disabled.",
1459
+ 'Use "captureContent": false in the private config to export metadata only.'
1460
+ ].join("\n");
1461
+ }
1462
+ function formatConfigError(result) {
1463
+ const setupHint = result.reason.startsWith("Configuration file not found:") ? " Run /langfuse and choose Set up Langfuse." : "";
1464
+ return `Langfuse tracing is disabled: ${result.reason}${setupHint}`;
1465
+ }
1466
+ function formatError2(error, config) {
1467
+ let message = error instanceof Error ? error.message : String(error);
1468
+ const secrets = [config?.publicKey, config?.secretKey].filter((secret) => Boolean(secret)).sort((left, right) => right.length - left.length);
1469
+ for (const secret of secrets) {
1470
+ message = message.split(secret).join("[LANGFUSE_KEY_REDACTED]");
1471
+ }
1472
+ return message;
1473
+ }
1474
+ var langfuse_default = createLangfuseExtension();
1475
+ export {
1476
+ langfuse_default as default
1477
+ };
1478
+ //# sourceMappingURL=index.ts.map