@amaster.ai/pi-telemetry 0.1.2-beta.61 → 0.1.2-beta.63

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 (48) hide show
  1. package/README.md +12 -14
  2. package/dist/config.d.ts +0 -1
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js.map +1 -1
  5. package/dist/extension.d.ts.map +1 -1
  6. package/dist/extension.js +84 -28
  7. package/dist/extension.js.map +1 -1
  8. package/dist/index.d.ts +6 -11
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/langfuse/config.d.ts +8 -0
  13. package/dist/langfuse/config.d.ts.map +1 -0
  14. package/dist/langfuse/config.js +79 -0
  15. package/dist/langfuse/config.js.map +1 -0
  16. package/dist/langfuse/exporters.d.ts +34 -0
  17. package/dist/langfuse/exporters.d.ts.map +1 -0
  18. package/dist/langfuse/exporters.js +466 -0
  19. package/dist/langfuse/exporters.js.map +1 -0
  20. package/dist/langfuse/mapping.d.ts +24 -0
  21. package/dist/langfuse/mapping.d.ts.map +1 -0
  22. package/dist/langfuse/mapping.js +130 -0
  23. package/dist/langfuse/mapping.js.map +1 -0
  24. package/dist/langfuse/metadata.d.ts +17 -0
  25. package/dist/langfuse/metadata.d.ts.map +1 -0
  26. package/dist/langfuse/metadata.js +89 -0
  27. package/dist/langfuse/metadata.js.map +1 -0
  28. package/dist/langfuse/types.d.ts +31 -0
  29. package/dist/langfuse/types.d.ts.map +1 -0
  30. package/dist/langfuse/types.js +36 -0
  31. package/dist/langfuse/types.js.map +1 -0
  32. package/dist/langfuse/utils.d.ts +17 -0
  33. package/dist/langfuse/utils.d.ts.map +1 -0
  34. package/dist/langfuse/utils.js +113 -0
  35. package/dist/langfuse/utils.js.map +1 -0
  36. package/dist/langfuse.d.ts +3 -80
  37. package/dist/langfuse.d.ts.map +1 -1
  38. package/dist/langfuse.js +4 -1139
  39. package/dist/langfuse.js.map +1 -1
  40. package/dist/otel.d.ts +5 -4
  41. package/dist/otel.d.ts.map +1 -1
  42. package/dist/otel.js +42 -30
  43. package/dist/otel.js.map +1 -1
  44. package/dist/parse.d.ts +4 -0
  45. package/dist/parse.d.ts.map +1 -0
  46. package/dist/parse.js +14 -0
  47. package/dist/parse.js.map +1 -0
  48. package/package.json +8 -3
@@ -0,0 +1,466 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { LangfuseSpanProcessor } from '@langfuse/otel';
4
+ import { LangfuseSpan } from '@langfuse/tracing';
5
+ import { ROOT_CONTEXT, SpanStatusCode, trace, } from '@opentelemetry/api';
6
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
7
+ import { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';
8
+ import { BasicTracerProvider, BatchSpanProcessor, } from '@opentelemetry/sdk-trace-base';
9
+ import { parsePositiveInteger } from '../parse.js';
10
+ import { chatInputLifecycleOutput, chatInputObservationName, chatSpanKey, langfuseObservationAttributes, llmGenerationKey, llmGenerationObservationName, subagentObservationName, subagentSpanKey, subagentSpawnToolSpanKey, telemetryEventSubagentSpanKey, toolObservationName, toolSpanKey, } from './mapping.js';
11
+ import { langfuseTraceId, langfuseUsageAttributes, lifecycleMetadata, lineageMetadata, llmGenerationMetadata, toolMetadata, } from './metadata.js';
12
+ import { DEFAULT_FLUSH_AT, DEFAULT_FLUSH_INTERVAL_MS, FILTERABLE_METADATA_KEYS, MAX_CLOSE_MS, MAX_STATUS_MESSAGE_CHARS, } from './types.js';
13
+ import { applyTelemetryRedaction, assertNever, isLlmGenerationEvent, isLlmStreamEvent, isToolEvent, normalizeOtelTracesEndpoint, requireTraceId, shortCorrelationId, truncateAttributePayload, } from './utils.js';
14
+ const MAX_FUTURE_CLOCK_SKEW_MS = 5 * 60 * 1000;
15
+ const EXPORT_TIMEOUT_MS = 15_000;
16
+ // Open spans retain their start attributes until the terminal event arrives;
17
+ // cap the map so a leaky producer cannot grow memory without bound.
18
+ const MAX_OPEN_SPANS = 512;
19
+ // Env var carrying the W3C traceparent of the nearest ancestor span, so a
20
+ // nested pi process (spawned via the bash tool) can parent its spans to it.
21
+ const TRACEPARENT_ENV = 'PI_TELEMETRY_TRACEPARENT';
22
+ // Lets a root span reuse the trace id the runtime already assigned to the
23
+ // event (hashed to 32 hex), so the whole tree shares one trace id. Set
24
+ // `nextTraceId` immediately before creating a parentless span; it is consumed
25
+ // once. Spans with a parent derive their trace id from the parent context and
26
+ // never consult the generator.
27
+ export class TelemetryIdGenerator {
28
+ nextTraceId;
29
+ generateTraceId() {
30
+ const next = this.nextTraceId;
31
+ this.nextTraceId = undefined;
32
+ return next && /^[0-9a-f]{32}$/i.test(next) ? next : randomBytes(16).toString('hex');
33
+ }
34
+ generateSpanId() {
35
+ return randomBytes(8).toString('hex');
36
+ }
37
+ }
38
+ // Transport is the official OpenTelemetry SDK: a BasicTracerProvider with one
39
+ // span processor per destination. The Langfuse processor wraps a
40
+ // BatchSpanProcessor + OTLPTraceExporter with Langfuse auth; the generic OTEL
41
+ // path is a plain BatchSpanProcessor + OTLPTraceExporter. Queueing, batching,
42
+ // retry with backoff, and bounded request timeouts belong to the SDK — this
43
+ // class only translates runtime events into span start/end calls.
44
+ export class OtelRuntimeEventExporter {
45
+ config;
46
+ provider;
47
+ tracer;
48
+ idGenerator = new TelemetryIdGenerator();
49
+ openSpans = new Map();
50
+ openSpanCapWarned = false;
51
+ constructor(config, opts) {
52
+ this.config = normalizeExporterConfig(config);
53
+ this.provider = opts?.provider ?? buildTracerProvider(this.config, this.idGenerator);
54
+ this.tracer = this.provider.getTracer('@amaster.ai/pi-telemetry', '0.1.0');
55
+ }
56
+ async publish(event) {
57
+ const redactedEvent = applyTelemetryRedaction(this.config, event);
58
+ if (!redactedEvent?.traceId) {
59
+ return;
60
+ }
61
+ const createdAtMs = Date.parse(redactedEvent.createdAt);
62
+ // ponytail: five minutes covers ordinary clock skew; future-dated replay
63
+ // can add an explicit normalization policy if it ever becomes a real use.
64
+ if (!Number.isFinite(createdAtMs) || createdAtMs > Date.now() + MAX_FUTURE_CLOCK_SKEW_MS) {
65
+ console.error('[pi-telemetry] dropping event with invalid or future createdAt timestamp');
66
+ return;
67
+ }
68
+ if (isLlmStreamEvent(redactedEvent)) {
69
+ this.publishLlmStreamEvent(redactedEvent, createdAtMs);
70
+ }
71
+ else if (isLlmGenerationEvent(redactedEvent)) {
72
+ this.publishLlmGenerationEvent(redactedEvent, createdAtMs);
73
+ }
74
+ else if (isToolEvent(redactedEvent)) {
75
+ this.publishToolEvent(redactedEvent, createdAtMs);
76
+ }
77
+ else {
78
+ this.publishLifecycleEvent(redactedEvent, createdAtMs);
79
+ }
80
+ }
81
+ async flush() {
82
+ await waitForExport(this.provider.forceFlush().catch((error) => {
83
+ console.error(`[pi-telemetry] export flush failed: ${error instanceof Error ? error.message : String(error)}`);
84
+ }));
85
+ }
86
+ async close() {
87
+ await waitForExport(this.provider.shutdown().catch((error) => {
88
+ console.error(`[pi-telemetry] exporter shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
89
+ }));
90
+ }
91
+ publishLifecycleEvent(event, createdAtMs) {
92
+ switch (event.type) {
93
+ case 'chat_turn_started': {
94
+ const span = this.startSpan('chat-turn', event, createdAtMs, this.enrichSpanAttributes({
95
+ ...lifecycleMetadata(event),
96
+ ...langfuseObservationAttributes({ input: event.details?.input, level: 'DEFAULT' }),
97
+ }, event));
98
+ this.trackOpenSpan(chatSpanKey(event), span);
99
+ // A nested pi process parents its subagent span to this root.
100
+ process.env[TRACEPARENT_ENV] = traceparent(span);
101
+ return;
102
+ }
103
+ case 'chat_turn_completed':
104
+ case 'chat_turn_failed': {
105
+ const output = event.details?.output ?? (event.error ? { error: event.error } : undefined);
106
+ const attributes = this.enrichSpanAttributes({
107
+ ...lifecycleMetadata(event),
108
+ ...langfuseObservationAttributes({
109
+ output,
110
+ level: event.error ? 'ERROR' : 'DEFAULT',
111
+ }),
112
+ }, event);
113
+ if (!this.endOpenSpan(chatSpanKey(event), attributes, event.error, createdAtMs)) {
114
+ this.emitTerminalSpan('chat-turn', event, createdAtMs, attributes);
115
+ }
116
+ return;
117
+ }
118
+ case 'chat_turn_steered':
119
+ case 'chat_turn_steer_delivered':
120
+ case 'chat_turn_followup_queued':
121
+ case 'chat_turn_followup_delivered': {
122
+ const span = this.startSpan(chatInputObservationName(event), event, createdAtMs, this.enrichSpanAttributes({
123
+ ...lifecycleMetadata(event),
124
+ ...langfuseObservationAttributes({
125
+ input: event.details?.input,
126
+ output: event.details?.output ?? chatInputLifecycleOutput(event),
127
+ level: 'DEFAULT',
128
+ }),
129
+ }, event), parentContextOf(this.openSpans.get(chatSpanKey(event))));
130
+ span.end(createdAtMs);
131
+ return;
132
+ }
133
+ case 'subagent_spawned':
134
+ case 'subagent_started': {
135
+ const key = subagentSpanKey(event);
136
+ const existing = this.openSpans.get(key);
137
+ if (existing) {
138
+ // spawned → started is the same lifecycle: update the open span
139
+ // instead of ending it and exporting a duplicate observation.
140
+ existing.otelSpan.setAttributes(this.enrichSpanAttributes({
141
+ ...lifecycleMetadata(event),
142
+ ...langfuseObservationAttributes({ input: event.details?.input, level: 'DEFAULT' }),
143
+ }, event));
144
+ return;
145
+ }
146
+ const span = this.startSpan(subagentObservationName(event), event, createdAtMs, this.enrichSpanAttributes({
147
+ ...lifecycleMetadata(event),
148
+ ...langfuseObservationAttributes({ input: event.details?.input, level: 'DEFAULT' }),
149
+ }, event), this.subagentParentContext(event));
150
+ this.trackOpenSpan(key, span);
151
+ // Grandchildren (pi processes spawned by this subagent) parent here.
152
+ process.env[TRACEPARENT_ENV] = traceparent(span);
153
+ return;
154
+ }
155
+ case 'subagent_completed':
156
+ case 'subagent_failed':
157
+ case 'subagent_cancelled': {
158
+ const output = event.details?.output ?? (event.error ? { error: event.error } : undefined);
159
+ const attributes = this.enrichSpanAttributes({
160
+ ...lifecycleMetadata(event),
161
+ ...langfuseObservationAttributes({
162
+ output,
163
+ level: event.error ? 'ERROR' : 'DEFAULT',
164
+ }),
165
+ }, event);
166
+ if (!this.endOpenSpan(subagentSpanKey(event), attributes, event.error, createdAtMs)) {
167
+ this.emitTerminalSpan(subagentObservationName(event), event, createdAtMs, attributes, this.subagentParentContext(event));
168
+ }
169
+ return;
170
+ }
171
+ default:
172
+ assertNever(event.type);
173
+ }
174
+ }
175
+ publishToolEvent(event, createdAtMs) {
176
+ const key = toolSpanKey(event);
177
+ if (event.status === 'started') {
178
+ const span = this.startSpan(toolObservationName(event), event, createdAtMs, this.enrichSpanAttributes({
179
+ ...toolMetadata(event),
180
+ ...(event.args ? { args: event.args } : {}),
181
+ ...langfuseObservationAttributes({ input: event.args, level: 'DEFAULT' }),
182
+ }, event), this.telemetryParentContext(event));
183
+ this.trackOpenSpan(key, span);
184
+ return;
185
+ }
186
+ const attributes = this.enrichSpanAttributes({
187
+ ...toolMetadata(event),
188
+ ...langfuseObservationAttributes({
189
+ output: event.error ? { error: event.error } : event.details,
190
+ level: event.error ? 'ERROR' : 'DEFAULT',
191
+ }),
192
+ }, event);
193
+ if (!this.endOpenSpan(key, attributes, event.error, createdAtMs)) {
194
+ this.emitTerminalSpan(toolObservationName(event), event, createdAtMs, attributes, this.telemetryParentContext(event));
195
+ }
196
+ }
197
+ publishLlmGenerationEvent(event, createdAtMs) {
198
+ const key = llmGenerationKey(event);
199
+ const terminalAttributes = {
200
+ ...llmGenerationMetadata(event),
201
+ // The langfuse-namespaced key is the first-priority mapping source for a
202
+ // generation's model on the OTEL path; a bare `model` key risks sinking
203
+ // into the unfilterable catch-all.
204
+ 'langfuse.observation.model.name': event.model.model,
205
+ 'langfuse.observation.model.parameters': JSON.stringify({
206
+ provider: event.model.provider,
207
+ ...(event.model.thinkingLevel ? { thinkingLevel: event.model.thinkingLevel } : {}),
208
+ }),
209
+ ...langfuseObservationAttributes({
210
+ type: 'generation',
211
+ output: event.output ?? (event.error ? { error: event.error } : undefined),
212
+ level: event.error ? 'ERROR' : 'DEFAULT',
213
+ }),
214
+ ...(event.usage ? langfuseUsageAttributes(event.usage) : {}),
215
+ };
216
+ if (event.status === 'started') {
217
+ const span = this.startSpan(llmGenerationObservationName(event), event, createdAtMs, this.enrichSpanAttributes({
218
+ ...terminalAttributes,
219
+ ...langfuseObservationAttributes({
220
+ type: 'generation',
221
+ input: event.input,
222
+ level: 'DEFAULT',
223
+ }),
224
+ }, event), this.telemetryParentContext(event));
225
+ this.trackOpenSpan(key, span);
226
+ return;
227
+ }
228
+ const attributes = this.enrichSpanAttributes(terminalAttributes, event);
229
+ if (!this.endOpenSpan(key, attributes, event.error, createdAtMs)) {
230
+ this.emitTerminalSpan(llmGenerationObservationName(event), event, createdAtMs, attributes, this.telemetryParentContext(event));
231
+ }
232
+ }
233
+ publishLlmStreamEvent(event, createdAtMs) {
234
+ const span = this.startSpan('llm-stream', event, createdAtMs, this.enrichSpanAttributes({
235
+ ...lineageMetadata(event),
236
+ llmGenerationId: event.llmGenerationId,
237
+ ...langfuseObservationAttributes({
238
+ output: event.streamEvents,
239
+ level: 'DEFAULT',
240
+ }),
241
+ }, event), parentContextOf(this.openSpans.get(llmGenerationKey(event))));
242
+ span.end(createdAtMs + (event.durationMs ?? 0));
243
+ }
244
+ startSpan(name, event, startMs, attributes, parentContext) {
245
+ // Consumed only when the new span has no parent — see TelemetryIdGenerator.
246
+ this.idGenerator.nextTraceId = langfuseTraceId(requireTraceId(event.traceId));
247
+ const otelSpan = this.tracer.startSpan(name, { startTime: startMs, attributes }, parentContext ?? ROOT_CONTEXT);
248
+ const observation = new LangfuseSpan({ otelSpan });
249
+ // The generic wrapper marks its span type as "span"; restore explicit
250
+ // generation attributes produced by the runtime mapping.
251
+ otelSpan.setAttributes(attributes);
252
+ return observation;
253
+ }
254
+ // Terminal event whose start was never seen (or was evicted from the open
255
+ // map): emit a zero-length span carrying only the terminal attributes.
256
+ emitTerminalSpan(name, event, atMs, attributes, parentContext) {
257
+ const span = this.startSpan(name, event, atMs, attributes, parentContext);
258
+ span.otelSpan.setStatus(statusFor(event.error));
259
+ span.end(atMs);
260
+ }
261
+ // Ends the span registered under `key`. Returns false when no start is
262
+ // open, so the caller can fall back to an output-only span.
263
+ endOpenSpan(key, attributes, error, endMs) {
264
+ const span = this.openSpans.get(key);
265
+ if (!span) {
266
+ return false;
267
+ }
268
+ this.openSpans.delete(key);
269
+ if (this.openSpans.size === 0) {
270
+ this.openSpanCapWarned = false;
271
+ }
272
+ span.otelSpan.setAttributes(attributes);
273
+ span.otelSpan.setStatus(statusFor(error));
274
+ span.end(endMs);
275
+ return true;
276
+ }
277
+ trackOpenSpan(key, span) {
278
+ // Same key tracked twice (e.g. a run ended without agent_end, then the
279
+ // next input reuses the chat key): end the orphaned span so its trace
280
+ // isn't silently incomplete.
281
+ const existing = this.openSpans.get(key);
282
+ if (existing) {
283
+ console.error(`[pi-telemetry] open span "${key}" was never ended — ending it before reuse`);
284
+ existing.end();
285
+ }
286
+ if (!this.openSpans.has(key) && this.openSpans.size >= MAX_OPEN_SPANS) {
287
+ const oldest = this.openSpans.keys().next().value;
288
+ if (oldest !== undefined) {
289
+ this.openSpans.delete(oldest);
290
+ }
291
+ // Log once per overflow streak; the flag resets when the map empties.
292
+ if (!this.openSpanCapWarned) {
293
+ this.openSpanCapWarned = true;
294
+ console.error('[pi-telemetry] too many open spans — dropping the oldest; its terminal event will produce an output-only span');
295
+ }
296
+ }
297
+ this.openSpans.set(key, span);
298
+ }
299
+ subagentParentContext(event) {
300
+ const spawnToolKey = subagentSpawnToolSpanKey(event);
301
+ const local = (spawnToolKey ? this.openSpans.get(spawnToolKey) : undefined) ??
302
+ this.openSpans.get(chatSpanKey(event));
303
+ // In a subagent (child) process there is no local root span — parent to
304
+ // the main process's span advertised through the environment instead.
305
+ return parentContextOf(local) ?? remoteParentContext();
306
+ }
307
+ telemetryParentContext(event) {
308
+ const subagentKey = telemetryEventSubagentSpanKey(event);
309
+ const local = (subagentKey ? this.openSpans.get(subagentKey) : undefined) ??
310
+ this.openSpans.get(chatSpanKey(event));
311
+ return parentContextOf(local) ?? remoteParentContext();
312
+ }
313
+ // langfuse.trace.metadata.* lands in the trace's top-level metadata and is
314
+ // filterable; plain span attributes sink into the metadata.attributes
315
+ // catch-all and are not. Set them on every span because Langfuse reads
316
+ // trace-level attributes from any span in the trace.
317
+ enrichSpanAttributes(base, event) {
318
+ const enriched = { ...base, 'langfuse.trace.name': 'chat-turn' };
319
+ if (this.config.serviceName) {
320
+ enriched['langfuse.trace.metadata.serviceName'] = this.config.serviceName;
321
+ enriched['langfuse.observation.metadata.serviceName'] = this.config.serviceName;
322
+ enriched['langfuse.trace.tags'] = [this.config.serviceName];
323
+ }
324
+ const taskRunId = event.taskRunId ?? shortCorrelationId(event.runId);
325
+ if (taskRunId) {
326
+ enriched['langfuse.trace.metadata.taskRunId'] = taskRunId;
327
+ }
328
+ // Promote the SDK-path metadata keys out of the catch-all
329
+ // metadata.attributes bucket into Langfuse's top-level observation
330
+ // metadata, so the filters that worked on the SDK transport still work.
331
+ for (const key of FILTERABLE_METADATA_KEYS) {
332
+ const value = enriched[key];
333
+ if (value !== undefined) {
334
+ enriched[`langfuse.observation.metadata.${key}`] =
335
+ typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
336
+ ? String(value)
337
+ : JSON.stringify(value);
338
+ }
339
+ }
340
+ return toOtelAttributes(enriched);
341
+ }
342
+ }
343
+ // One span processor per destination inside a single provider; both are
344
+ // present when a config carries Langfuse credentials and a generic endpoint.
345
+ function buildTracerProvider(config, idGenerator) {
346
+ const spanProcessors = [];
347
+ if (config.langfuse) {
348
+ spanProcessors.push(new LangfuseSpanProcessor({
349
+ publicKey: config.langfuse.publicKey,
350
+ secretKey: config.langfuse.secretKey,
351
+ baseUrl: config.langfuse.baseUrl,
352
+ flushAt: config.langfuse.flushAt,
353
+ // LangfuseSpanProcessor takes the flush interval in seconds.
354
+ flushInterval: config.langfuse.flushIntervalMs / 1000,
355
+ timeout: EXPORT_TIMEOUT_MS / 1000,
356
+ shouldExportSpan: () => true,
357
+ mediaUploadEnabled: false,
358
+ // Opt into real-time v4 ingestion — @langfuse/otel does not set this
359
+ // itself, and without it data can lag the v2 read APIs.
360
+ additionalHeaders: { 'x-langfuse-ingestion-version': '4' },
361
+ }));
362
+ }
363
+ if (config.endpoint) {
364
+ spanProcessors.push(new BatchSpanProcessor(new OTLPTraceExporter({
365
+ url: normalizeOtelTracesEndpoint(config.endpoint),
366
+ ...(config.headers ? { headers: config.headers } : {}),
367
+ timeoutMillis: EXPORT_TIMEOUT_MS,
368
+ }), {
369
+ maxExportBatchSize: config.flushAt,
370
+ scheduledDelayMillis: config.flushIntervalMs,
371
+ exportTimeoutMillis: EXPORT_TIMEOUT_MS,
372
+ }));
373
+ }
374
+ // Without a resource the collector sees service.name=unknown_service:node —
375
+ // set it from config so the traces identify their runtime.
376
+ const resource = defaultResource().merge(resourceFromAttributes({
377
+ 'service.name': config.serviceName ?? 'pi',
378
+ ...(config.serviceVersion ? { 'service.version': config.serviceVersion } : {}),
379
+ }));
380
+ return new BasicTracerProvider({ spanProcessors, idGenerator, resource });
381
+ }
382
+ function normalizeExporterConfig(config) {
383
+ return {
384
+ ...config,
385
+ flushAt: parsePositiveInteger(config.flushAt, DEFAULT_FLUSH_AT),
386
+ flushIntervalMs: parsePositiveInteger(config.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS),
387
+ ...(config.langfuse
388
+ ? {
389
+ langfuse: {
390
+ ...config.langfuse,
391
+ flushAt: parsePositiveInteger(config.langfuse.flushAt, DEFAULT_FLUSH_AT),
392
+ flushIntervalMs: parsePositiveInteger(config.langfuse.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS),
393
+ },
394
+ }
395
+ : {}),
396
+ };
397
+ }
398
+ function parentContextOf(span) {
399
+ return span ? trace.setSpanContext(ROOT_CONTEXT, span.otelSpan.spanContext()) : undefined;
400
+ }
401
+ // Parses the W3C traceparent a parent pi process published for us.
402
+ function remoteParentContext() {
403
+ const value = process.env[TRACEPARENT_ENV];
404
+ const match = value
405
+ ? /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i.exec(value)
406
+ : null;
407
+ if (!match) {
408
+ return undefined;
409
+ }
410
+ return trace.setSpanContext(ROOT_CONTEXT, {
411
+ traceId: match[1],
412
+ spanId: match[2],
413
+ traceFlags: Number(match[3]),
414
+ isRemote: true,
415
+ });
416
+ }
417
+ function traceparent(span) {
418
+ const { traceId, spanId } = span.otelSpan.spanContext();
419
+ return `00-${traceId}-${spanId}-01`;
420
+ }
421
+ function statusFor(error) {
422
+ if (!error) {
423
+ return { code: SpanStatusCode.OK };
424
+ }
425
+ const message = error.length > MAX_STATUS_MESSAGE_CHARS
426
+ ? `${error.slice(0, MAX_STATUS_MESSAGE_CHARS)}... [truncated]`
427
+ : error;
428
+ return { code: SpanStatusCode.ERROR, message };
429
+ }
430
+ async function waitForExport(operation) {
431
+ await Promise.race([operation, delay(MAX_CLOSE_MS, undefined, { ref: false })]);
432
+ }
433
+ // OTEL attribute values are scalar (or homogeneous string arrays); objects
434
+ // flatten to JSON strings, exactly like the previous hand-rolled serializer.
435
+ // Strings are truncated at set time, so no byte accounting happens later.
436
+ function toOtelAttributes(json) {
437
+ const attributes = {};
438
+ for (const [key, value] of Object.entries(json)) {
439
+ const converted = toOtelAttributeValue(value);
440
+ if (converted !== undefined) {
441
+ attributes[key] = converted;
442
+ }
443
+ }
444
+ return attributes;
445
+ }
446
+ function toOtelAttributeValue(value) {
447
+ if (value === undefined) {
448
+ return undefined;
449
+ }
450
+ if (value === null) {
451
+ return 'null';
452
+ }
453
+ if (typeof value === 'boolean' || typeof value === 'number') {
454
+ return value;
455
+ }
456
+ if (typeof value === 'string') {
457
+ return truncateAttributePayload(value);
458
+ }
459
+ // Real string arrays (e.g. langfuse.trace.tags) instead of a
460
+ // JSON-stringified blob Langfuse cannot map.
461
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) {
462
+ return value;
463
+ }
464
+ return truncateAttributePayload(JSON.stringify(value));
465
+ }
466
+ //# sourceMappingURL=exporters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exporters.js","sourceRoot":"","sources":["../../src/langfuse/exporters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAQ3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAIL,YAAY,EACZ,cAAc,EAEd,KAAK,GACN,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EACL,mBAAmB,EACnB,kBAAkB,GAGnB,MAAM,+BAA+B,CAAC;AAMvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,WAAW,EACX,6BAA6B,EAC7B,gBAAgB,EAChB,4BAA4B,EAC5B,uBAAuB,EACvB,eAAe,EACf,wBAAwB,EACxB,6BAA6B,EAC7B,mBAAmB,EACnB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,qBAAqB,EACrB,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,YAAY,EACZ,wBAAwB,GAEzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,uBAAuB,EACvB,WAAW,EACX,oBAAoB,EACpB,gBAAgB,EAChB,WAAW,EACX,2BAA2B,EAC3B,cA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B,OAAO,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,6DAA6D;IAC7D,6CAA6C;IAC7C,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,EAAE,CAAC;QAC5E,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,wBAAwB,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACzD,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { JsonObject, JsonValue, RuntimeLifecycleEvent, RuntimeLlmGenerationEvent, RuntimeToolEvent } from '@amaster.ai/pi-shared';
2
+ export declare function langfuseObservationAttributes(input: {
3
+ input?: JsonValue | undefined;
4
+ output?: JsonValue | undefined;
5
+ level?: 'DEFAULT' | 'WARNING' | 'ERROR';
6
+ type?: 'span' | 'generation';
7
+ }): JsonObject;
8
+ export declare function chatSpanKey(event: Pick<RuntimeLifecycleEvent, 'sessionId' | 'conversationId' | 'parentSessionId'>): string;
9
+ export declare function subagentSpanKey(event: Pick<RuntimeLifecycleEvent, 'runId' | 'childSessionId' | 'id'>): string;
10
+ export declare function telemetryEventSubagentSpanKey(event: Pick<RuntimeToolEvent | RuntimeLlmGenerationEvent, 'runId' | 'childSessionId'>): string | undefined;
11
+ export declare function toolSpanKey(event: Pick<RuntimeToolEvent, 'sessionId' | 'toolCallId' | 'toolName'>): string;
12
+ export declare function subagentSpawnToolSpanKey(event: Pick<RuntimeLifecycleEvent, 'parentSessionId' | 'parentToolCallId'>): string | undefined;
13
+ export declare function llmGenerationKey(event: Pick<RuntimeLlmGenerationEvent, 'sessionId' | 'llmGenerationId'>): string;
14
+ export declare function toolObservationName(event: Pick<RuntimeToolEvent, 'toolName' | 'args'>): string;
15
+ export declare function chatInputObservationName(event: RuntimeLifecycleEvent): string;
16
+ export declare function chatInputObservationPrefix(type: RuntimeLifecycleEvent['type']): string;
17
+ export declare function chatInputLifecycleOutput(event: RuntimeLifecycleEvent): JsonObject;
18
+ export declare function subagentObservationName(event: RuntimeLifecycleEvent): string;
19
+ export declare function summarizeToolArgsForName(toolName: string, args: JsonObject | undefined): string | undefined;
20
+ export declare function llmGenerationObservationName(event: Pick<RuntimeLlmGenerationEvent, 'input' | 'runId' | 'childSessionId'>): string;
21
+ export declare function summarizeLlmGenerationInputForName(input: JsonValue | undefined): string;
22
+ export declare function stringArg(args: JsonObject | undefined, key: string): string | undefined;
23
+ export declare function truncateObservationSummary(value: string, maxLength?: number): string;
24
+ //# sourceMappingURL=mapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapping.d.ts","sourceRoot":"","sources":["../../src/langfuse/mapping.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,qBAAqB,EACrB,yBAAyB,EACzB,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAE/B,wBAAgB,6BAA6B,CAAC,KAAK,EAAE;IACnD,KAAK,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAC9B,MAAM,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAC/B,KAAK,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC;IACxC,IAAI,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC9B,GAAG,UAAU,CAiBb;AAED,wBAAgB,WAAW,CACzB,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,WAAW,GAAG,gBAAgB,GAAG,iBAAiB,CAAC,GACrF,MAAM,CAIR;AAED,wBAAgB,eAAe,CAC7B,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,OAAO,GAAG,gBAAgB,GAAG,IAAI,CAAC,GACpE,MAAM,CAER;AAED,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,IAAI,CAAC,gBAAgB,GAAG,yBAAyB,EAAE,OAAO,GAAG,gBAAg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,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,SAAK,GAAG,MAAM,CAGhF"}
@@ -0,0 +1,130 @@
1
+ export function langfuseObservationAttributes(input) {
2
+ return {
3
+ 'langfuse.observation.type': input.type ?? 'span',
4
+ ...(input.input !== undefined
5
+ ? {
6
+ 'langfuse.observation.input': JSON.stringify(input.input),
7
+ 'input.value': JSON.stringify(input.input),
8
+ }
9
+ : {}),
10
+ ...(input.output !== undefined
11
+ ? {
12
+ 'langfuse.observation.output': JSON.stringify(input.output),
13
+ 'output.value': JSON.stringify(input.output),
14
+ }
15
+ : {}),
16
+ ...(input.level ? { 'langfuse.observation.level': input.level } : {}),
17
+ };
18
+ }
19
+ export function chatSpanKey(event) {
20
+ const sessionId = event.parentSessionId ?? event.sessionId;
21
+ const conversationId = event.parentSessionId ?? event.conversationId ?? sessionId;
22
+ return `chat:${sessionId}:${conversationId}`;
23
+ }
24
+ export function subagentSpanKey(event) {
25
+ return `subagent:${event.runId ?? event.childSessionId ?? event.id}`;
26
+ }
27
+ export function telemetryEventSubagentSpanKey(event) {
28
+ return event.runId || event.childSessionId
29
+ ? `subagent:${event.runId ?? event.childSessionId}`
30
+ : undefined;
31
+ }
32
+ export function toolSpanKey(event) {
33
+ return `tool:${event.sessionId}:${event.toolCallId}:${event.toolName}`;
34
+ }
35
+ export function subagentSpawnToolSpanKey(event) {
36
+ return event.parentSessionId && event.parentToolCallId
37
+ ? `tool:${event.parentSessionId}:${event.parentToolCallId}:sessions_spawn`
38
+ : undefined;
39
+ }
40
+ export function llmGenerationKey(event) {
41
+ return `llm-generation:${event.sessionId}:${event.llmGenerationId}`;
42
+ }
43
+ export function toolObservationName(event) {
44
+ const summary = summarizeToolArgsForName(event.toolName, event.args);
45
+ return summary ? `${event.toolName} [${summary}]` : event.toolName;
46
+ }
47
+ export function chatInputObservationName(event) {
48
+ const prefix = chatInputObservationPrefix(event.type);
49
+ const input = typeof event.details?.input === 'string'
50
+ ? truncateObservationSummary(event.details.input)
51
+ : undefined;
52
+ return input ? `${prefix} [${input}]` : prefix;
53
+ }
54
+ export function chatInputObservationPrefix(type) {
55
+ if (type === 'chat_turn_steered') {
56
+ return 'chat-steer';
57
+ }
58
+ if (type === 'chat_turn_steer_delivered') {
59
+ return 'chat-steer-delivered';
60
+ }
61
+ if (type === 'chat_turn_followup_delivered') {
62
+ return 'chat-followup-delivered';
63
+ }
64
+ return 'chat-followup';
65
+ }
66
+ export function chatInputLifecycleOutput(event) {
67
+ return event.type === 'chat_turn_steer_delivered' || event.type === 'chat_turn_followup_delivered'
68
+ ? { delivered: true, turnMode: event.details?.turnMode }
69
+ : { accepted: true, turnMode: event.details?.turnMode };
70
+ }
71
+ export function subagentObservationName(event) {
72
+ const agent = stringArg(event.details, 'agent');
73
+ return agent ? `subagent [${truncateObservationSummary(agent)}]` : 'subagent';
74
+ }
75
+ export function summarizeToolArgsForName(toolName, args) {
76
+ if (!args) {
77
+ return undefined;
78
+ }
79
+ const pathValue = stringArg(args, 'path') ?? stringArg(args, 'filePath') ?? stringArg(args, 'absolutePath');
80
+ if (pathValue) {
81
+ return truncateObservationSummary(pathValue);
82
+ }
83
+ const command = stringArg(args, 'command');
84
+ if (command) {
85
+ return truncateObservationSummary(command);
86
+ }
87
+ const query = stringArg(args, 'query');
88
+ if (query) {
89
+ return truncateObservationSummary(query);
90
+ }
91
+ const task = stringArg(args, 'task');
92
+ if (task && toolName === 'sessions_spawn') {
93
+ return truncateObservationSummary(task);
94
+ }
95
+ const code = stringArg(args, 'code');
96
+ if (code) {
97
+ return truncateObservationSummary(code);
98
+ }
99
+ const name = stringArg(args, 'name');
100
+ if (name && toolName.startsWith('mcp_')) {
101
+ return truncateObservationSummary(name);
102
+ }
103
+ return undefined;
104
+ }
105
+ export function llmGenerationObservationName(event) {
106
+ return `llm-generation [${event.runId || event.childSessionId ? 'subagent' : 'main'}] [${summarizeLlmGenerationInputForName(event.input)}]`;
107
+ }
108
+ export function summarizeLlmGenerationInputForName(input) {
109
+ if (typeof input === 'string') {
110
+ return truncateObservationSummary(input);
111
+ }
112
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
113
+ const continuation = input.continuation === true;
114
+ const index = typeof input.llmGenerationIndex === 'number' ? input.llmGenerationIndex : undefined;
115
+ const toolResults = typeof input.previousToolResultCount === 'number' ? input.previousToolResultCount : undefined;
116
+ if (continuation) {
117
+ return truncateObservationSummary(`continuation${index !== undefined ? ` #${index}` : ''}${toolResults !== undefined ? ` after ${toolResults} tool result(s)` : ''}`);
118
+ }
119
+ }
120
+ return 'request';
121
+ }
122
+ export function stringArg(args, key) {
123
+ const value = args?.[key];
124
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
125
+ }
126
+ export function truncateObservationSummary(value, maxLength = 90) {
127
+ const normalized = value.replace(/\s+/g, ' ').trim();
128
+ return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 1)}…` : normalized;
129
+ }
130
+ //# sourceMappingURL=mapping.js.map