@posthog/ai 7.14.0 → 7.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,655 @@
1
+ 'use strict';
2
+
3
+ require('uuid');
4
+ require('@posthog/core');
5
+
6
+ var version = "7.15.0";
7
+
8
+ // limit large outputs by truncating to 200kb (approx 200k bytes)
9
+ const MAX_OUTPUT_SIZE = 200000;
10
+ const STRING_FORMAT = 'utf8';
11
+ const withPrivacyMode = (client, privacyMode, input) => {
12
+ return client.privacy_mode || privacyMode ? null : input;
13
+ };
14
+ function toSafeString(input) {
15
+ if (input === undefined || input === null) {
16
+ return '';
17
+ }
18
+ if (typeof input === 'string') {
19
+ return input;
20
+ }
21
+ try {
22
+ return JSON.stringify(input);
23
+ } catch {
24
+ console.warn('Failed to stringify input', input);
25
+ return '';
26
+ }
27
+ }
28
+ const truncate = input => {
29
+ const str = toSafeString(input);
30
+ if (str === '') {
31
+ return '';
32
+ }
33
+
34
+ // Check if we need to truncate and ensure STRING_FORMAT is respected
35
+ const encoder = new TextEncoder();
36
+ const buffer = encoder.encode(str);
37
+ if (buffer.length <= MAX_OUTPUT_SIZE) {
38
+ // Ensure STRING_FORMAT is respected
39
+ return new TextDecoder(STRING_FORMAT).decode(buffer);
40
+ }
41
+
42
+ // Truncate the buffer and ensure a valid string is returned
43
+ const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
44
+ // fatal: false means we get U+FFFD at the end if truncation broke the encoding
45
+ const decoder = new TextDecoder(STRING_FORMAT, {
46
+ fatal: false
47
+ });
48
+ let truncatedStr = decoder.decode(truncatedBuffer);
49
+ if (truncatedStr.endsWith('\uFFFD')) {
50
+ truncatedStr = truncatedStr.slice(0, -1);
51
+ }
52
+ return `${truncatedStr}... [truncated]`;
53
+ };
54
+
55
+ /**
56
+ * Normalize OpenAI Responses API input items to include a `role` field.
57
+ * Items like `function_call` and `function_call_result` don't have a role,
58
+ * causing PostHog's trace viewer to default them to "user".
59
+ */
60
+ function normalizeInputRoles(input) {
61
+ if (!Array.isArray(input)) {
62
+ return input;
63
+ }
64
+ return input.map(item => {
65
+ if (item && typeof item === 'object' && !('role' in item) && 'type' in item) {
66
+ if (item.type === 'function_call') {
67
+ return {
68
+ ...item,
69
+ role: 'assistant'
70
+ };
71
+ }
72
+ if (item.type === 'function_call_result') {
73
+ return {
74
+ ...item,
75
+ role: 'tool'
76
+ };
77
+ }
78
+ }
79
+ return item;
80
+ });
81
+ }
82
+ function ensureSerializable(obj) {
83
+ if (obj === null || obj === undefined) {
84
+ return obj;
85
+ }
86
+ try {
87
+ JSON.stringify(obj);
88
+ return obj;
89
+ } catch {
90
+ return String(obj);
91
+ }
92
+ }
93
+ function exceedsMaxOutputSize(value) {
94
+ if (value === null || value === undefined) {
95
+ return false;
96
+ }
97
+ try {
98
+ const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);
99
+ return new TextEncoder().encode(serializedValue).length > MAX_OUTPUT_SIZE;
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+ function parseIsoTimestamp(isoStr) {
105
+ if (!isoStr) {
106
+ return null;
107
+ }
108
+ try {
109
+ const ts = new Date(isoStr).getTime();
110
+ return isNaN(ts) ? null : ts / 1000;
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+ /**
116
+ * A tracing processor that sends OpenAI Agents SDK traces to PostHog.
117
+ *
118
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK
119
+ * and maps agent traces, spans, and generations to PostHog's LLM analytics events.
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * import { PostHogTracingProcessor } from '@posthog/ai/openai-agents'
124
+ * import { addTraceProcessor } from '@openai/agents'
125
+ *
126
+ * const processor = new PostHogTracingProcessor({
127
+ * client: posthog,
128
+ * distinctId: 'user@example.com',
129
+ * })
130
+ * addTraceProcessor(processor)
131
+ * ```
132
+ */
133
+ class PostHogTracingProcessor {
134
+ _spanStartTimes = new Map();
135
+ _traceMetadata = new Map();
136
+ _maxTrackedEntries = 10000;
137
+ constructor(options) {
138
+ this._client = options.client;
139
+ this._distinctId = options.distinctId;
140
+ this._privacyMode = options.privacyMode ?? false;
141
+ this._groups = options.groups ?? {};
142
+ this._properties = options.properties ?? {};
143
+ }
144
+ _getDistinctId(trace) {
145
+ if (typeof this._distinctId === 'function') {
146
+ if (trace) {
147
+ const result = this._distinctId(trace);
148
+ if (result) {
149
+ return String(result);
150
+ }
151
+ }
152
+ return undefined;
153
+ } else if (this._distinctId) {
154
+ return String(this._distinctId);
155
+ }
156
+ return undefined;
157
+ }
158
+ _withPrivacyMode(value) {
159
+ return withPrivacyMode(this._client, this._privacyMode, value);
160
+ }
161
+ _prepareCapturedValue(value) {
162
+ const serializableValue = ensureSerializable(value);
163
+ const boundedValue = exceedsMaxOutputSize(serializableValue) ? truncate(serializableValue) : serializableValue;
164
+ return this._withPrivacyMode(boundedValue);
165
+ }
166
+ _evictStaleEntries() {
167
+ if (this._spanStartTimes.size > this._maxTrackedEntries) {
168
+ const entries = [...this._spanStartTimes.entries()].sort((a, b) => a[1] - b[1]);
169
+ const toRemove = entries.slice(0, Math.floor(entries.length / 2));
170
+ for (const [key] of toRemove) {
171
+ this._spanStartTimes.delete(key);
172
+ }
173
+ }
174
+ if (this._traceMetadata.size > this._maxTrackedEntries) {
175
+ const keys = [...this._traceMetadata.keys()];
176
+ const toRemove = keys.slice(0, Math.floor(keys.length / 2));
177
+ for (const key of toRemove) {
178
+ this._traceMetadata.delete(key);
179
+ }
180
+ }
181
+ }
182
+ _captureEvent(event, properties, distinctId) {
183
+ try {
184
+ if (!this._client?.capture) {
185
+ return;
186
+ }
187
+ const finalProperties = {
188
+ ...this._properties,
189
+ ...properties
190
+ };
191
+ const eventMessage = {
192
+ distinctId: distinctId || 'unknown',
193
+ event,
194
+ properties: finalProperties,
195
+ groups: Object.keys(this._groups).length > 0 ? this._groups : undefined
196
+ };
197
+ this._client.capture(eventMessage);
198
+ } catch {
199
+ // Silently ignore capture errors
200
+ }
201
+ }
202
+ _baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties) {
203
+ const properties = {
204
+ $ai_lib: 'posthog-ai',
205
+ $ai_lib_version: version,
206
+ $ai_trace_id: traceId,
207
+ $ai_span_id: spanId,
208
+ $ai_parent_id: parentId,
209
+ $ai_provider: 'openai',
210
+ $ai_framework: 'openai-agents',
211
+ $ai_latency: latency,
212
+ ...errorProperties
213
+ };
214
+ if (groupId) {
215
+ properties.$ai_group_id = groupId;
216
+ }
217
+ return properties;
218
+ }
219
+ _getErrorProperties(error) {
220
+ if (!error) {
221
+ return {};
222
+ }
223
+ const errorMessage = error.message || String(error);
224
+ let errorType = 'unknown';
225
+ if (errorMessage.includes('ModelBehaviorError')) {
226
+ errorType = 'model_behavior_error';
227
+ } else if (errorMessage.includes('UserError')) {
228
+ errorType = 'user_error';
229
+ } else if (errorMessage.includes('InputGuardrailTripwireTriggered')) {
230
+ errorType = 'input_guardrail_triggered';
231
+ } else if (errorMessage.includes('OutputGuardrailTripwireTriggered')) {
232
+ errorType = 'output_guardrail_triggered';
233
+ } else if (errorMessage.includes('MaxTurnsExceeded')) {
234
+ errorType = 'max_turns_exceeded';
235
+ }
236
+ return {
237
+ $ai_is_error: true,
238
+ $ai_error: errorMessage,
239
+ $ai_error_type: errorType
240
+ };
241
+ }
242
+
243
+ // --- TracingProcessor interface ---
244
+
245
+ async onTraceStart(trace) {
246
+ try {
247
+ this._evictStaleEntries();
248
+ const traceId = trace.traceId;
249
+ const traceName = trace.name;
250
+ const groupId = trace.groupId ?? null;
251
+ const metadata = trace.metadata;
252
+ const distinctId = this._getDistinctId(trace);
253
+ this._traceMetadata.set(traceId, {
254
+ name: traceName,
255
+ groupId,
256
+ metadata,
257
+ distinctId,
258
+ startTime: Date.now() / 1000
259
+ });
260
+ } catch {
261
+ // Silently ignore errors
262
+ }
263
+ }
264
+ async onTraceEnd(trace) {
265
+ try {
266
+ const traceId = trace.traceId;
267
+ const traceInfo = this._traceMetadata.get(traceId);
268
+ this._traceMetadata.delete(traceId);
269
+ const traceName = traceInfo?.name ?? trace.name;
270
+ const groupId = traceInfo?.groupId ?? trace.groupId ?? null;
271
+ const metadata = traceInfo?.metadata ?? trace.metadata;
272
+ const distinctId = traceInfo?.distinctId ?? this._getDistinctId(trace);
273
+ const startTime = traceInfo?.startTime;
274
+ const latency = startTime != null ? Date.now() / 1000 - startTime : undefined;
275
+ const properties = {
276
+ $ai_lib: 'posthog-ai',
277
+ $ai_lib_version: version,
278
+ $ai_trace_id: traceId,
279
+ $ai_trace_name: traceName,
280
+ $ai_provider: 'openai',
281
+ $ai_framework: 'openai-agents'
282
+ };
283
+ if (latency != null) {
284
+ properties.$ai_latency = latency;
285
+ }
286
+ if (groupId) {
287
+ properties.$ai_group_id = groupId;
288
+ }
289
+ if (metadata && Object.keys(metadata).length > 0) {
290
+ properties.$ai_trace_metadata = this._prepareCapturedValue(metadata);
291
+ }
292
+ if (distinctId == null) {
293
+ properties.$process_person_profile = false;
294
+ }
295
+ this._captureEvent('$ai_trace', properties, distinctId ?? traceId);
296
+ } catch {
297
+ // Silently ignore errors
298
+ }
299
+ }
300
+ async onSpanStart(span) {
301
+ try {
302
+ this._evictStaleEntries();
303
+ this._spanStartTimes.set(span.spanId, Date.now() / 1000);
304
+ } catch {
305
+ // Silently ignore errors
306
+ }
307
+ }
308
+ async onSpanEnd(span) {
309
+ try {
310
+ const spanId = span.spanId;
311
+ const traceId = span.traceId;
312
+ const parentId = span.parentId;
313
+ const spanData = span.spanData;
314
+
315
+ // Calculate latency
316
+ const startTime = this._spanStartTimes.get(spanId);
317
+ this._spanStartTimes.delete(spanId);
318
+ let latency;
319
+ if (startTime != null) {
320
+ latency = Date.now() / 1000 - startTime;
321
+ } else {
322
+ const started = parseIsoTimestamp(span.startedAt);
323
+ const ended = parseIsoTimestamp(span.endedAt);
324
+ latency = started != null && ended != null ? ended - started : 0;
325
+ }
326
+
327
+ // Get distinct ID from trace metadata
328
+ const traceInfo = this._traceMetadata.get(traceId);
329
+ const userDistinctId = traceInfo?.distinctId ?? this._getDistinctId(null);
330
+
331
+ // Get group_id from trace metadata
332
+ const groupId = traceInfo?.groupId ?? null;
333
+
334
+ // Get error properties
335
+ const errorProperties = this._getErrorProperties(span.error);
336
+
337
+ // Personless mode: no user-provided distinct_id, fallback to trace_id
338
+ if (userDistinctId == null) {
339
+ errorProperties.$process_person_profile = false;
340
+ }
341
+ const distinctId = userDistinctId ?? traceId;
342
+
343
+ // Dispatch based on span data type
344
+ switch (spanData.type) {
345
+ case 'generation':
346
+ this._handleGenerationSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
347
+ break;
348
+ case 'response':
349
+ this._handleResponseSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
350
+ break;
351
+ case 'function':
352
+ this._handleFunctionSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
353
+ break;
354
+ case 'agent':
355
+ this._handleAgentSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
356
+ break;
357
+ case 'handoff':
358
+ this._handleHandoffSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
359
+ break;
360
+ case 'guardrail':
361
+ this._handleGuardrailSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
362
+ break;
363
+ case 'custom':
364
+ this._handleCustomSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
365
+ break;
366
+ case 'transcription':
367
+ case 'speech':
368
+ case 'speech_group':
369
+ this._handleAudioSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
370
+ break;
371
+ case 'mcp_tools':
372
+ this._handleMcpSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
373
+ break;
374
+ default:
375
+ this._handleGenericSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties);
376
+ break;
377
+ }
378
+ } catch {
379
+ // Silently ignore errors
380
+ }
381
+ }
382
+ async shutdown() {
383
+ try {
384
+ this._spanStartTimes.clear();
385
+ this._traceMetadata.clear();
386
+ if (typeof this._client?.flush === 'function') {
387
+ await this._client.flush();
388
+ }
389
+ } catch {
390
+ // Silently ignore errors
391
+ }
392
+ }
393
+ async forceFlush() {
394
+ try {
395
+ if (typeof this._client?.flush === 'function') {
396
+ await this._client.flush();
397
+ }
398
+ } catch {
399
+ // Silently ignore errors
400
+ }
401
+ }
402
+
403
+ // --- Span handlers ---
404
+
405
+ _handleGenerationSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
406
+ const usage = spanData.usage ?? {};
407
+ const inputTokens = usage.input_tokens || usage.prompt_tokens || 0;
408
+ const outputTokens = usage.output_tokens || usage.completion_tokens || 0;
409
+ const modelConfig = spanData.model_config ?? {};
410
+ const modelParams = {};
411
+ for (const param of ['temperature', 'max_tokens', 'top_p', 'frequency_penalty', 'presence_penalty']) {
412
+ if (param in modelConfig) {
413
+ modelParams[param] = modelConfig[param];
414
+ }
415
+ }
416
+ const properties = {
417
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
418
+ $ai_model: spanData.model,
419
+ $ai_model_parameters: Object.keys(modelParams).length > 0 ? modelParams : null,
420
+ $ai_input: this._prepareCapturedValue(normalizeInputRoles(spanData.input)),
421
+ $ai_output_choices: this._prepareCapturedValue(spanData.output),
422
+ $ai_input_tokens: inputTokens,
423
+ $ai_output_tokens: outputTokens,
424
+ $ai_total_tokens: inputTokens + outputTokens
425
+ };
426
+ if (usage.details) {
427
+ const details = usage.details;
428
+ if (details.reasoning_tokens) {
429
+ properties.$ai_reasoning_tokens = details.reasoning_tokens;
430
+ }
431
+ if (details.cache_read_input_tokens) {
432
+ properties.$ai_cache_read_input_tokens = details.cache_read_input_tokens;
433
+ }
434
+ if (details.cache_creation_input_tokens) {
435
+ properties.$ai_cache_creation_input_tokens = details.cache_creation_input_tokens;
436
+ }
437
+ }
438
+
439
+ // Also check top-level usage for reasoning/cache tokens (flexible schema)
440
+ if (usage.reasoning_tokens) {
441
+ properties.$ai_reasoning_tokens = usage.reasoning_tokens;
442
+ }
443
+ if (usage.cache_read_input_tokens) {
444
+ properties.$ai_cache_read_input_tokens = usage.cache_read_input_tokens;
445
+ }
446
+ if (usage.cache_creation_input_tokens) {
447
+ properties.$ai_cache_creation_input_tokens = usage.cache_creation_input_tokens;
448
+ }
449
+ this._captureEvent('$ai_generation', properties, distinctId);
450
+ }
451
+ _handleResponseSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
452
+ // The OpenAI Agents SDK exposes these underscored fields for non-OpenAI tracing providers.
453
+ // Treat them as best-effort and avoid assuming they are always present.
454
+ const responseSpanData = spanData;
455
+ const response = responseSpanData._response;
456
+ const responseId = spanData.response_id ?? response?.id;
457
+
458
+ // Extract usage from response
459
+ const usage = response?.usage ?? {};
460
+ const inputTokens = usage?.input_tokens ?? 0;
461
+ const outputTokens = usage?.output_tokens ?? 0;
462
+
463
+ // Extract model from response
464
+ const model = response?.model;
465
+ const properties = {
466
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
467
+ $ai_model: model,
468
+ $ai_response_id: responseId,
469
+ $ai_input: this._prepareCapturedValue(normalizeInputRoles(responseSpanData._input)),
470
+ $ai_input_tokens: inputTokens,
471
+ $ai_output_tokens: outputTokens,
472
+ $ai_total_tokens: inputTokens + outputTokens
473
+ };
474
+
475
+ // Extract output from response
476
+ if (response?.output) {
477
+ properties.$ai_output_choices = this._prepareCapturedValue(response.output);
478
+ }
479
+ this._captureEvent('$ai_generation', properties, distinctId);
480
+ }
481
+ _handleFunctionSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
482
+ const properties = {
483
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
484
+ $ai_span_name: spanData.name,
485
+ $ai_span_type: 'tool',
486
+ $ai_input_state: this._prepareCapturedValue(spanData.input),
487
+ $ai_output_state: this._prepareCapturedValue(spanData.output)
488
+ };
489
+ if (spanData.mcp_data) {
490
+ properties.$ai_mcp_data = this._prepareCapturedValue(spanData.mcp_data);
491
+ }
492
+ this._captureEvent('$ai_span', properties, distinctId);
493
+ }
494
+ _handleAgentSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
495
+ const properties = {
496
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
497
+ $ai_span_name: spanData.name,
498
+ $ai_span_type: 'agent'
499
+ };
500
+ if (spanData.handoffs) {
501
+ properties.$ai_agent_handoffs = spanData.handoffs;
502
+ }
503
+ if (spanData.tools) {
504
+ properties.$ai_agent_tools = spanData.tools;
505
+ }
506
+ if (spanData.output_type) {
507
+ properties.$ai_agent_output_type = spanData.output_type;
508
+ }
509
+ this._captureEvent('$ai_span', properties, distinctId);
510
+ }
511
+ _handleHandoffSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
512
+ const properties = {
513
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
514
+ $ai_span_name: `${spanData.from_agent} -> ${spanData.to_agent}`,
515
+ $ai_span_type: 'handoff',
516
+ $ai_handoff_from_agent: spanData.from_agent,
517
+ $ai_handoff_to_agent: spanData.to_agent
518
+ };
519
+ this._captureEvent('$ai_span', properties, distinctId);
520
+ }
521
+ _handleGuardrailSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
522
+ const properties = {
523
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
524
+ $ai_span_name: spanData.name,
525
+ $ai_span_type: 'guardrail',
526
+ $ai_guardrail_triggered: spanData.triggered
527
+ };
528
+ this._captureEvent('$ai_span', properties, distinctId);
529
+ }
530
+ _handleCustomSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
531
+ const properties = {
532
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
533
+ $ai_span_name: spanData.name,
534
+ $ai_span_type: 'custom',
535
+ $ai_custom_data: this._prepareCapturedValue(spanData.data)
536
+ };
537
+ this._captureEvent('$ai_span', properties, distinctId);
538
+ }
539
+ _handleAudioSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
540
+ const spanType = spanData.type;
541
+ const properties = {
542
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
543
+ $ai_span_name: spanType,
544
+ $ai_span_type: spanType
545
+ };
546
+
547
+ // Add model info if available
548
+ if ('model' in spanData && spanData.model) {
549
+ properties.$ai_model = spanData.model;
550
+ }
551
+
552
+ // Add model config if available
553
+ if ('model_config' in spanData && spanData.model_config) {
554
+ properties.$ai_model_config = this._prepareCapturedValue(spanData.model_config);
555
+ }
556
+
557
+ // Add audio format info
558
+ if (spanData.type === 'transcription') {
559
+ const transcription = spanData;
560
+ if (transcription.input?.format) {
561
+ properties.$ai_audio_input_format = transcription.input.format;
562
+ }
563
+ // Transcription output is text
564
+ if (transcription.output) {
565
+ properties.$ai_output_state = this._prepareCapturedValue(transcription.output);
566
+ }
567
+ } else if (spanData.type === 'speech') {
568
+ const speech = spanData;
569
+ if (speech.output?.format) {
570
+ properties.$ai_audio_output_format = speech.output.format;
571
+ }
572
+ // Text input for TTS
573
+ if (speech.input) {
574
+ properties.$ai_input = this._prepareCapturedValue(speech.input);
575
+ }
576
+ } else if (spanData.type === 'speech_group') {
577
+ const speechGroup = spanData;
578
+ if (speechGroup.input) {
579
+ properties.$ai_input = this._prepareCapturedValue(speechGroup.input);
580
+ }
581
+ }
582
+ this._captureEvent('$ai_span', properties, distinctId);
583
+ }
584
+ _handleMcpSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
585
+ const properties = {
586
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
587
+ $ai_span_name: `mcp:${spanData.server}`,
588
+ $ai_span_type: 'mcp_tools',
589
+ $ai_mcp_server: spanData.server,
590
+ $ai_mcp_tools: this._prepareCapturedValue(spanData.result)
591
+ };
592
+ this._captureEvent('$ai_span', properties, distinctId);
593
+ }
594
+ _handleGenericSpan(spanData, traceId, spanId, parentId, latency, distinctId, groupId, errorProperties) {
595
+ const spanType = spanData.type || 'unknown';
596
+ const properties = {
597
+ ...this._baseProperties(traceId, spanId, parentId, latency, groupId, errorProperties),
598
+ $ai_span_name: spanType,
599
+ $ai_span_type: spanType
600
+ };
601
+ this._captureEvent('$ai_span', properties, distinctId);
602
+ }
603
+ }
604
+
605
+ /**
606
+ * One-liner to instrument OpenAI Agents SDK with PostHog tracing.
607
+ *
608
+ * This registers a PostHogTracingProcessor with the OpenAI Agents SDK,
609
+ * automatically capturing traces, spans, and LLM generations.
610
+ *
611
+ * @param options - Configuration options
612
+ * @returns The registered processor instance
613
+ *
614
+ * @example
615
+ * ```typescript
616
+ * import { instrument } from '@posthog/ai/openai-agents'
617
+ * import PostHog from 'posthog-node'
618
+ *
619
+ * const phClient = new PostHog('<API_KEY>')
620
+ *
621
+ * // Simple setup — await before running agents
622
+ * await instrument({ client: phClient, distinctId: 'user@example.com' })
623
+ *
624
+ * // With dynamic distinct ID
625
+ * await instrument({
626
+ * client: phClient,
627
+ * distinctId: (trace) => trace.metadata?.userId,
628
+ * privacyMode: true,
629
+ * properties: { environment: 'production' },
630
+ * })
631
+ *
632
+ * // Now run agents as normal - traces automatically sent to PostHog
633
+ * import { Agent, run } from '@openai/agents'
634
+ * const agent = new Agent({ name: 'Assistant', instructions: 'You are helpful.' })
635
+ * const result = await run(agent, 'Hello!')
636
+ * ```
637
+ */
638
+ async function instrument(options) {
639
+ const {
640
+ addTraceProcessor
641
+ } = await import('@openai/agents-core');
642
+ const processor = new PostHogTracingProcessor({
643
+ client: options.client,
644
+ distinctId: options.distinctId,
645
+ privacyMode: options.privacyMode,
646
+ groups: options.groups,
647
+ properties: options.properties
648
+ });
649
+ addTraceProcessor(processor);
650
+ return processor;
651
+ }
652
+
653
+ exports.PostHogTracingProcessor = PostHogTracingProcessor;
654
+ exports.instrument = instrument;
655
+ //# sourceMappingURL=index.cjs.map