@agent-inspect/openai-agents 6.31.34 → 6.31.36

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.mjs DELETED
@@ -1,666 +0,0 @@
1
- import { createAdapterPreviewCapture } from 'agent-inspect/advanced';
2
- import { fileWriter } from 'agent-inspect/writers';
3
-
4
- // packages/openai-agents/src/index.ts
5
- var OPENAI_AGENTS_SOURCE = {
6
- type: "adapter",
7
- name: "@agent-inspect/openai-agents",
8
- version: "experimental"
9
- };
10
- function nowIso() {
11
- return (/* @__PURE__ */ new Date()).toISOString();
12
- }
13
- function normalizeError(error) {
14
- if (error instanceof Error && error.message.trim() !== "") {
15
- return error.message;
16
- }
17
- if (typeof error === "string" && error.trim() !== "") {
18
- return error;
19
- }
20
- return "Unknown OpenAI Agents processor error";
21
- }
22
- function durationMs(startedAt, endedAt) {
23
- const started = Date.parse(startedAt);
24
- const ended = Date.parse(endedAt);
25
- if (!Number.isFinite(started) || !Number.isFinite(ended)) return void 0;
26
- return Math.max(0, ended - started);
27
- }
28
- function countRecordKeys(value) {
29
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
30
- return void 0;
31
- }
32
- return Object.keys(value).length;
33
- }
34
- function normalizeMaxPreviewChars(value) {
35
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
36
- return void 0;
37
- }
38
- return Math.floor(value);
39
- }
40
- function summarizeUnknown(value) {
41
- if (value === null) return { type: "null" };
42
- if (Array.isArray(value)) return { type: "array", itemCount: value.length };
43
- if (typeof value === "object") {
44
- return { type: "object", keyCount: countRecordKeys(value) ?? 0 };
45
- }
46
- if (typeof value === "string") {
47
- return { type: "string", length: value.length };
48
- }
49
- const valueType = typeof value;
50
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
51
- return { type: valueType };
52
- }
53
- if (valueType === "undefined") return { type: "undefined" };
54
- return { type: "unknown" };
55
- }
56
- function summarizeOptionalUnknown(value) {
57
- return value === void 0 ? void 0 : summarizeUnknown(value);
58
- }
59
- function summarizeError(error) {
60
- if (!error?.message) return void 0;
61
- return { message: error.message };
62
- }
63
- function readFiniteNonNegative(value) {
64
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
65
- }
66
- function applyCachedAndReasoningFromDetails(tokenUsage, detailRecord) {
67
- if (tokenUsage.cached === void 0) {
68
- const cached = readFiniteNonNegative(
69
- detailRecord.cached_tokens ?? detailRecord.cached_input_tokens
70
- );
71
- if (cached !== void 0) {
72
- tokenUsage.cached = cached;
73
- }
74
- }
75
- if (tokenUsage.cacheWrite === void 0) {
76
- const cacheWrite = readFiniteNonNegative(
77
- detailRecord.cache_creation_tokens ?? detailRecord.cached_creation_tokens ?? detailRecord.cache_write_tokens
78
- );
79
- if (cacheWrite !== void 0) {
80
- tokenUsage.cacheWrite = cacheWrite;
81
- }
82
- }
83
- if (tokenUsage.reasoning !== void 0) {
84
- return;
85
- }
86
- const reasoning = detailRecord.reasoning_tokens ?? detailRecord.output_tokens_details;
87
- const asNumber = readFiniteNonNegative(reasoning);
88
- if (asNumber !== void 0) {
89
- tokenUsage.reasoning = asNumber;
90
- return;
91
- }
92
- if (typeof reasoning === "object" && reasoning !== null && !Array.isArray(reasoning)) {
93
- const nested = readFiniteNonNegative(
94
- reasoning.reasoning_tokens
95
- );
96
- if (nested !== void 0) {
97
- tokenUsage.reasoning = nested;
98
- }
99
- }
100
- }
101
- function summarizeUsage(usage) {
102
- if (typeof usage !== "object" || usage === null || Array.isArray(usage)) {
103
- return void 0;
104
- }
105
- const record = usage;
106
- const tokenUsage = {};
107
- if (typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)) {
108
- tokenUsage.input = record.input_tokens;
109
- }
110
- if (typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)) {
111
- tokenUsage.output = record.output_tokens;
112
- }
113
- if (tokenUsage.input !== void 0 || tokenUsage.output !== void 0) {
114
- tokenUsage.total = (tokenUsage.input ?? 0) + (tokenUsage.output ?? 0);
115
- }
116
- const inputDetails = record.input_tokens_details;
117
- if (typeof inputDetails === "object" && inputDetails !== null && !Array.isArray(inputDetails)) {
118
- applyCachedAndReasoningFromDetails(
119
- tokenUsage,
120
- inputDetails
121
- );
122
- }
123
- const details = record.details;
124
- if (typeof details === "object" && details !== null && !Array.isArray(details)) {
125
- applyCachedAndReasoningFromDetails(tokenUsage, details);
126
- }
127
- const outputDetails = record.output_tokens_details;
128
- if (typeof outputDetails === "object" && outputDetails !== null && !Array.isArray(outputDetails)) {
129
- const nested = readFiniteNonNegative(
130
- outputDetails.reasoning_tokens
131
- );
132
- if (nested !== void 0 && tokenUsage.reasoning === void 0) {
133
- tokenUsage.reasoning = nested;
134
- }
135
- }
136
- return Object.keys(tokenUsage).length > 0 ? tokenUsage : void 0;
137
- }
138
- function spanKind(type) {
139
- switch (type) {
140
- case "agent":
141
- return "AGENT";
142
- case "generation":
143
- case "response":
144
- case "transcription":
145
- case "speech":
146
- return "LLM";
147
- case "function":
148
- case "mcp_tools":
149
- return "TOOL";
150
- case "handoff":
151
- case "guardrail":
152
- return "DECISION";
153
- case "custom":
154
- case "speech_group":
155
- return "LOGIC";
156
- default:
157
- return "LOGIC";
158
- }
159
- }
160
- function spanName(data) {
161
- switch (data.type) {
162
- case "agent":
163
- case "function":
164
- case "custom":
165
- case "guardrail":
166
- return data.name;
167
- case "generation":
168
- return data.model ? `generation:${data.model}` : "generation";
169
- case "response":
170
- return data.response_id ? `response:${data.response_id}` : "response";
171
- case "handoff":
172
- return data.to_agent ? `handoff:${data.to_agent}` : "handoff";
173
- case "mcp_tools":
174
- return data.server ? `mcp-tools:${data.server}` : "mcp-tools";
175
- case "transcription":
176
- return data.model ? `transcription:${data.model}` : "transcription";
177
- case "speech":
178
- return data.model ? `speech:${data.model}` : "speech";
179
- case "speech_group":
180
- return "speech-group";
181
- default:
182
- return "openai-agents-span";
183
- }
184
- }
185
- function commonSpanAttributes(span) {
186
- return {
187
- legacyEvent: "step_started",
188
- stepId: span.spanId,
189
- stepType: mapSpanTypeToStepType(span.spanData.type),
190
- spanType: span.spanData.type,
191
- traceId: span.traceId,
192
- spanId: span.spanId,
193
- parentSpanId: span.parentId ?? void 0,
194
- traceMetadataKeyCount: countRecordKeys(span.traceMetadata)
195
- };
196
- }
197
- function specificSpanAttributes(data) {
198
- switch (data.type) {
199
- case "agent":
200
- return {
201
- agentName: data.name,
202
- handoffCount: data.handoffs?.length ?? 0,
203
- handoffNames: data.handoffs,
204
- toolCount: data.tools?.length ?? 0,
205
- toolNames: data.tools,
206
- outputType: data.output_type
207
- };
208
- case "function":
209
- return {
210
- toolName: data.name,
211
- hasInput: data.input !== void 0,
212
- hasOutput: data.output !== void 0,
213
- inputSummary: summarizeUnknown(data.input),
214
- outputSummary: summarizeUnknown(data.output),
215
- mcpDataSummary: summarizeOptionalUnknown(data.mcp_data)
216
- };
217
- case "generation":
218
- return {
219
- model: data.model,
220
- modelConfigKeyCount: countRecordKeys(data.model_config),
221
- inputSummary: summarizeOptionalUnknown(data.input),
222
- outputSummary: summarizeOptionalUnknown(data.output),
223
- usageDetailsKeyCount: countRecordKeys(data.usage?.details)
224
- };
225
- case "response":
226
- return {
227
- responseId: data.response_id,
228
- inputSummary: summarizeOptionalUnknown(data._input),
229
- responseSummary: summarizeOptionalUnknown(data._response)
230
- };
231
- case "handoff":
232
- return {
233
- fromAgent: data.from_agent,
234
- toAgent: data.to_agent
235
- };
236
- case "custom":
237
- return {
238
- customName: data.name,
239
- dataSummary: summarizeUnknown(data.data)
240
- };
241
- case "guardrail":
242
- return {
243
- guardrailName: data.name,
244
- triggered: data.triggered
245
- };
246
- case "mcp_tools":
247
- return {
248
- server: data.server,
249
- toolCount: data.result?.length ?? 0,
250
- toolNames: data.result
251
- };
252
- case "transcription":
253
- return {
254
- model: data.model,
255
- inputFormat: data.input.format,
256
- inputSummary: summarizeUnknown(data.input.data),
257
- outputSummary: summarizeOptionalUnknown(data.output),
258
- modelConfigKeyCount: countRecordKeys(data.model_config)
259
- };
260
- case "speech":
261
- return {
262
- model: data.model,
263
- inputSummary: summarizeOptionalUnknown(data.input),
264
- outputFormat: data.output.format,
265
- outputSummary: summarizeUnknown(data.output.data),
266
- modelConfigKeyCount: countRecordKeys(data.model_config)
267
- };
268
- case "speech_group":
269
- return {
270
- inputSummary: summarizeOptionalUnknown(data.input)
271
- };
272
- default:
273
- return {};
274
- }
275
- }
276
- function mapSpanTypeToStepType(type) {
277
- switch (type) {
278
- case "generation":
279
- case "response":
280
- case "transcription":
281
- case "speech":
282
- return "llm";
283
- case "function":
284
- case "mcp_tools":
285
- return "tool";
286
- case "handoff":
287
- case "guardrail":
288
- return "decision";
289
- case "agent":
290
- return "logic";
291
- case "custom":
292
- case "speech_group":
293
- return "custom";
294
- default:
295
- return "logic";
296
- }
297
- }
298
- function spanInputSummary(data) {
299
- switch (data.type) {
300
- case "generation":
301
- return summarizeOptionalUnknown(data.input);
302
- case "function":
303
- return summarizeUnknown(data.input);
304
- case "response":
305
- return summarizeOptionalUnknown(data._input);
306
- case "custom":
307
- return summarizeUnknown(data.data);
308
- case "transcription":
309
- return { format: data.input.format, ...summarizeUnknown(data.input.data) };
310
- case "speech":
311
- case "speech_group":
312
- return summarizeOptionalUnknown(data.input);
313
- default:
314
- return void 0;
315
- }
316
- }
317
- function spanOutputSummary(data) {
318
- switch (data.type) {
319
- case "generation":
320
- return summarizeOptionalUnknown(data.output);
321
- case "function":
322
- return summarizeUnknown(data.output);
323
- case "response":
324
- return summarizeOptionalUnknown(data._response);
325
- case "guardrail":
326
- return { triggered: data.triggered };
327
- case "mcp_tools":
328
- return { toolCount: data.result?.length ?? 0 };
329
- case "transcription":
330
- return summarizeOptionalUnknown(data.output);
331
- case "speech":
332
- return { format: data.output.format, ...summarizeUnknown(data.output.data) };
333
- default:
334
- return void 0;
335
- }
336
- }
337
- function spanPreviewSources(data, phase) {
338
- const withPhase = (input, output) => phase === "start" ? { input } : { input, output };
339
- switch (data.type) {
340
- case "generation":
341
- return withPhase(data.input, data.output);
342
- case "function":
343
- return withPhase(data.input, data.output);
344
- case "response":
345
- return withPhase(data._input, data._response);
346
- case "transcription":
347
- return withPhase(data.input.data, data.output);
348
- case "speech":
349
- return withPhase(data.input, data.output.data);
350
- case "custom":
351
- return { input: data.data };
352
- case "speech_group":
353
- return { input: data.input };
354
- default:
355
- return {};
356
- }
357
- }
358
- function traceEventId(traceId) {
359
- return `openai_agents_trace:${traceId}`;
360
- }
361
- function spanEventId(spanId) {
362
- return `openai_agents_span:${spanId}`;
363
- }
364
- var AgentInspectOpenAiAgentsTracingProcessor = class {
365
- constructor(options) {
366
- this.options = options;
367
- this.requestedCapture = options.capture ?? "metadata-only";
368
- this.preview = createAdapterPreviewCapture({
369
- capture: this.requestedCapture,
370
- redactionProfile: options.redactionProfile,
371
- maxPreviewChars: options.maxPreviewChars,
372
- onDiagnostic: options.onDiagnostic
373
- });
374
- this.effectiveCapture = this.preview.capture;
375
- this.writer = options.writer ?? (options.traceDir ? fileWriter({ dir: options.traceDir }) : void 0);
376
- for (const key of [
377
- "options",
378
- "writer",
379
- "requestedCapture",
380
- "preview",
381
- "effectiveCapture",
382
- "diagnostics",
383
- "activeTraces",
384
- "activeSpans",
385
- "closed"
386
- ]) {
387
- Object.defineProperty(this, key, { enumerable: false });
388
- }
389
- this.recordCaptureOptionWarnings();
390
- }
391
- options;
392
- installMode = "setTraceProcessors";
393
- localOnly = true;
394
- writer;
395
- requestedCapture;
396
- preview;
397
- effectiveCapture;
398
- diagnostics = {
399
- writeFailures: 0,
400
- lifecycleWarnings: 0,
401
- flushFailures: 0,
402
- shutdownFailures: 0,
403
- runtimeMappingImplemented: true
404
- };
405
- activeTraces = /* @__PURE__ */ new Map();
406
- activeSpans = /* @__PURE__ */ new Map();
407
- closed = false;
408
- start() {
409
- }
410
- async onTraceStart(trace) {
411
- await this.handleLifecycle("onTraceStart", async () => {
412
- if (this.closed) {
413
- this.recordLifecycleWarning("onTraceStart ignored because processor is shut down.");
414
- return;
415
- }
416
- const startedAt = nowIso();
417
- const name = this.options.workflowName ?? trace.name ?? "openai-agents-run";
418
- const eventId = traceEventId(trace.traceId);
419
- this.activeTraces.set(trace.traceId, { eventId, startedAt, name });
420
- await this.write({
421
- schemaVersion: "0.2",
422
- eventId,
423
- runId: trace.traceId,
424
- kind: "RUN",
425
- name,
426
- status: "running",
427
- timestamp: startedAt,
428
- startedAt,
429
- confidence: "explicit",
430
- source: OPENAI_AGENTS_SOURCE,
431
- attributes: {
432
- legacyEvent: "run_started",
433
- installMode: this.installMode,
434
- capture: this.effectiveCapture,
435
- requestedCapture: this.requestedCapture === this.effectiveCapture ? void 0 : this.requestedCapture,
436
- previewCaptureSupported: true,
437
- // Preview rows report the effective bound/profile, which the
438
- // `share` and `strict` profiles can lower below the request.
439
- redactionProfile: this.preview.previewEnabled ? this.preview.redactionProfile : this.options.redactionProfile,
440
- maxPreviewChars: this.preview.previewEnabled ? this.preview.maxPreviewChars : normalizeMaxPreviewChars(this.options.maxPreviewChars),
441
- groupId: trace.groupId ?? void 0,
442
- metadataKeyCount: countRecordKeys(trace.metadata)
443
- },
444
- trace: {
445
- traceId: trace.traceId
446
- }
447
- });
448
- });
449
- }
450
- async onTraceEnd(trace) {
451
- await this.handleLifecycle("onTraceEnd", async () => {
452
- if (this.closed) {
453
- this.recordLifecycleWarning("onTraceEnd ignored because processor is shut down.");
454
- return;
455
- }
456
- const active = this.activeTraces.get(trace.traceId);
457
- if (!active) {
458
- this.recordLifecycleWarning(
459
- `onTraceEnd ignored because trace ${trace.traceId} has no matching start callback.`
460
- );
461
- return;
462
- }
463
- const endedAt = nowIso();
464
- await this.write({
465
- schemaVersion: "0.2",
466
- eventId: active.eventId,
467
- runId: trace.traceId,
468
- kind: "RUN",
469
- name: active.name,
470
- status: "ok",
471
- timestamp: endedAt,
472
- startedAt: active.startedAt,
473
- endedAt,
474
- durationMs: durationMs(active.startedAt, endedAt),
475
- confidence: "explicit",
476
- source: OPENAI_AGENTS_SOURCE,
477
- attributes: {
478
- legacyEvent: "run_completed",
479
- installMode: this.installMode,
480
- groupId: trace.groupId ?? void 0,
481
- metadataKeyCount: countRecordKeys(trace.metadata)
482
- },
483
- trace: {
484
- traceId: trace.traceId
485
- }
486
- });
487
- this.activeTraces.delete(trace.traceId);
488
- });
489
- }
490
- async onSpanStart(span) {
491
- await this.handleLifecycle("onSpanStart", async () => {
492
- if (this.closed) {
493
- this.recordLifecycleWarning("onSpanStart ignored because processor is shut down.");
494
- return;
495
- }
496
- const startedAt = span.startedAt ?? nowIso();
497
- const eventId = spanEventId(span.spanId);
498
- const parentId = this.resolveParentEventId(span);
499
- const kind = spanKind(span.spanData.type);
500
- const name = spanName(span.spanData);
501
- this.activeSpans.set(span.spanId, {
502
- eventId,
503
- runId: span.traceId,
504
- parentId,
505
- startedAt,
506
- name,
507
- kind
508
- });
509
- await this.write({
510
- schemaVersion: "0.2",
511
- eventId,
512
- runId: span.traceId,
513
- parentId,
514
- kind,
515
- name,
516
- status: "running",
517
- timestamp: startedAt,
518
- startedAt,
519
- confidence: "explicit",
520
- source: OPENAI_AGENTS_SOURCE,
521
- attributes: {
522
- ...commonSpanAttributes(span),
523
- ...specificSpanAttributes(span.spanData),
524
- ...this.previewAttributes(span, "start")
525
- },
526
- inputSummary: spanInputSummary(span.spanData),
527
- tokenUsage: summarizeUsage(
528
- span.spanData.type === "generation" ? span.spanData.usage : void 0
529
- ),
530
- trace: {
531
- traceId: span.traceId,
532
- spanId: span.spanId,
533
- parentSpanId: span.parentId ?? void 0
534
- }
535
- });
536
- });
537
- }
538
- async onSpanEnd(span) {
539
- await this.handleLifecycle("onSpanEnd", async () => {
540
- if (this.closed) {
541
- this.recordLifecycleWarning("onSpanEnd ignored because processor is shut down.");
542
- return;
543
- }
544
- const active = this.activeSpans.get(span.spanId);
545
- if (!active) {
546
- this.recordLifecycleWarning(
547
- `onSpanEnd ignored because span ${span.spanId} has no matching start callback.`
548
- );
549
- return;
550
- }
551
- const endedAt = span.endedAt ?? nowIso();
552
- const error = summarizeError(span.error);
553
- await this.write({
554
- schemaVersion: "0.2",
555
- eventId: active.eventId,
556
- runId: active.runId,
557
- parentId: active.parentId,
558
- kind: active.kind,
559
- name: active.name,
560
- status: error ? "error" : "ok",
561
- timestamp: endedAt,
562
- startedAt: active.startedAt,
563
- endedAt,
564
- durationMs: durationMs(active.startedAt, endedAt),
565
- confidence: "explicit",
566
- source: OPENAI_AGENTS_SOURCE,
567
- attributes: {
568
- ...commonSpanAttributes(span),
569
- ...specificSpanAttributes(span.spanData),
570
- legacyEvent: "step_completed",
571
- errorDataSummary: summarizeOptionalUnknown(span.error?.data),
572
- ...this.previewAttributes(span, "end")
573
- },
574
- inputSummary: spanInputSummary(span.spanData),
575
- outputSummary: spanOutputSummary(span.spanData),
576
- error,
577
- tokenUsage: summarizeUsage(
578
- span.spanData.type === "generation" ? span.spanData.usage : void 0
579
- ),
580
- trace: {
581
- traceId: span.traceId,
582
- spanId: span.spanId,
583
- parentSpanId: span.parentId ?? void 0
584
- }
585
- });
586
- this.activeSpans.delete(span.spanId);
587
- });
588
- }
589
- async forceFlush() {
590
- try {
591
- await this.writer?.flush?.();
592
- } catch (error) {
593
- this.diagnostics.flushFailures += 1;
594
- this.diagnostics.lastError = normalizeError(error);
595
- }
596
- }
597
- async shutdown(_timeout) {
598
- if (this.closed) return;
599
- try {
600
- await this.writer?.close?.();
601
- } catch (error) {
602
- this.diagnostics.shutdownFailures += 1;
603
- this.diagnostics.lastError = normalizeError(error);
604
- } finally {
605
- this.closed = true;
606
- this.activeTraces.clear();
607
- this.activeSpans.clear();
608
- }
609
- }
610
- getDiagnostics() {
611
- return { ...this.diagnostics, capture: this.preview.getDiagnostics() };
612
- }
613
- /** Bounded preview attributes for one span phase (empty unless enabled). */
614
- previewAttributes(span, phase) {
615
- if (!this.preview.previewEnabled) return {};
616
- return this.preview.applyPreviewFields(
617
- {},
618
- spanPreviewSources(span.spanData, phase)
619
- );
620
- }
621
- getWriterStats() {
622
- return this.writer?.getStats?.();
623
- }
624
- resolveParentEventId(span) {
625
- if (span.parentId) return spanEventId(span.parentId);
626
- return this.activeTraces.get(span.traceId)?.eventId;
627
- }
628
- async handleLifecycle(callbackName, run) {
629
- try {
630
- await run();
631
- } catch (error) {
632
- this.recordLifecycleWarning(`${callbackName}: ${normalizeError(error)}`);
633
- }
634
- }
635
- recordLifecycleWarning(message) {
636
- this.diagnostics.lifecycleWarnings += 1;
637
- this.diagnostics.lastWarning = message;
638
- }
639
- recordCaptureOptionWarnings() {
640
- if (this.effectiveCapture === "preview") return;
641
- const previewOnlyOptions = [];
642
- if (this.options.redactionProfile !== void 0) previewOnlyOptions.push("redactionProfile");
643
- if (this.options.maxPreviewChars !== void 0) previewOnlyOptions.push("maxPreviewChars");
644
- if (previewOnlyOptions.length > 0) {
645
- this.recordLifecycleWarning(
646
- `OpenAI Agents preview-only options have no effect in metadata-only capture: ${previewOnlyOptions.join(", ")}.`
647
- );
648
- }
649
- }
650
- async write(event) {
651
- if (!this.writer) return;
652
- try {
653
- await this.writer.write(event);
654
- } catch (error) {
655
- this.diagnostics.writeFailures += 1;
656
- this.diagnostics.lastError = normalizeError(error);
657
- }
658
- }
659
- };
660
- function agentInspectProcessor(options = {}) {
661
- return new AgentInspectOpenAiAgentsTracingProcessor(options);
662
- }
663
-
664
- export { agentInspectProcessor };
665
- //# sourceMappingURL=index.mjs.map
666
- //# sourceMappingURL=index.mjs.map