@cloudbase/agent-observability 1.0.1-alpha.9

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.js ADDED
@@ -0,0 +1,732 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/core/constants.ts
24
+ var import_openinference_semantic_conventions, OtelSpanAttributes;
25
+ var init_constants = __esm({
26
+ "src/core/constants.ts"() {
27
+ "use strict";
28
+ import_openinference_semantic_conventions = require("@arizeai/openinference-semantic-conventions");
29
+ OtelSpanAttributes = {
30
+ // OpenInference - re-export all standard conventions
31
+ ...import_openinference_semantic_conventions.SemanticConventions,
32
+ // AG-Kit Trace attributes (non-standard)
33
+ TRACE_NAME: "trace.name",
34
+ TRACE_TAGS: "trace.tags",
35
+ TRACE_PUBLIC: "trace.public",
36
+ TRACE_METADATA: "trace.metadata",
37
+ TRACE_INPUT: "trace.input",
38
+ TRACE_OUTPUT: "trace.output",
39
+ // AG-Kit Observation attributes (non-standard)
40
+ OBSERVATION_TYPE: "observation.type",
41
+ OBSERVATION_LEVEL: "observation.level",
42
+ OBSERVATION_STATUS_MESSAGE: "observation.status_message",
43
+ OBSERVATION_INPUT: "observation.input",
44
+ OBSERVATION_OUTPUT: "observation.output",
45
+ OBSERVATION_METADATA: "observation.metadata",
46
+ // AG-Kit LLM-specific (non-standard)
47
+ LLM_COMPLETION_START_TIME: "llm.completion_start_time",
48
+ LLM_MODEL_PARAMETERS: "llm.model_parameters",
49
+ LLM_USAGE_DETAILS: "llm.usage_details",
50
+ LLM_COST_DETAILS: "llm.cost_details",
51
+ // AG-Kit Retriever-specific (non-standard)
52
+ RETRIEVER_NAME: "retriever.name",
53
+ RETRIEVER_QUERY: "retriever.query",
54
+ RETRIEVER_INDEX_ID: "retriever.index_id",
55
+ RETRIEVER_TOP_K: "retriever.top_k",
56
+ // AG-Kit General (non-standard)
57
+ ENVIRONMENT: "environment",
58
+ RELEASE: "release",
59
+ VERSION: "version"
60
+ };
61
+ }
62
+ });
63
+
64
+ // src/core/attributes.ts
65
+ function createTraceAttributes({
66
+ name,
67
+ userId,
68
+ sessionId,
69
+ version,
70
+ release,
71
+ input,
72
+ output,
73
+ metadata,
74
+ tags,
75
+ environment,
76
+ public: isPublic
77
+ } = {}) {
78
+ const attributes = {
79
+ [OtelSpanAttributes.TRACE_NAME]: name,
80
+ // Use OpenInference standard attributes for user and session
81
+ [OtelSpanAttributes.USER_ID]: userId,
82
+ [OtelSpanAttributes.SESSION_ID]: sessionId,
83
+ [OtelSpanAttributes.VERSION]: version,
84
+ [OtelSpanAttributes.RELEASE]: release,
85
+ [OtelSpanAttributes.TRACE_INPUT]: _serialize(input),
86
+ [OtelSpanAttributes.TRACE_OUTPUT]: _serialize(output),
87
+ [OtelSpanAttributes.TRACE_TAGS]: tags,
88
+ [OtelSpanAttributes.ENVIRONMENT]: environment,
89
+ [OtelSpanAttributes.TRACE_PUBLIC]: isPublic,
90
+ ..._flattenAndSerializeMetadata(metadata, OtelSpanAttributes.TRACE_METADATA)
91
+ };
92
+ return Object.fromEntries(
93
+ Object.entries(attributes).filter(([_, v]) => v != null)
94
+ );
95
+ }
96
+ function createObservationAttributes(type, attributes) {
97
+ const {
98
+ metadata,
99
+ input,
100
+ output,
101
+ level,
102
+ statusMessage,
103
+ version,
104
+ completionStartTime,
105
+ model,
106
+ modelParameters,
107
+ usageDetails
108
+ } = attributes;
109
+ const otelAttributes = {
110
+ [import_openinference_semantic_conventions2.SemanticConventions.OPENINFERENCE_SPAN_KIND]: type.toUpperCase(),
111
+ [OtelSpanAttributes.OBSERVATION_TYPE]: type,
112
+ [OtelSpanAttributes.OBSERVATION_LEVEL]: level,
113
+ [OtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
114
+ [OtelSpanAttributes.VERSION]: version,
115
+ // Use OpenInference input.value convention
116
+ [import_openinference_semantic_conventions2.SemanticConventions.INPUT_VALUE]: _serialize(input),
117
+ // Also set legacy agkit.observation.input for compatibility
118
+ [OtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
119
+ // Use OpenInference output.value convention
120
+ [import_openinference_semantic_conventions2.SemanticConventions.OUTPUT_VALUE]: _serialize(output),
121
+ // Also set legacy agkit.observation.output for compatibility
122
+ [OtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output)
123
+ };
124
+ if (type === "llm") {
125
+ if (model) {
126
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_MODEL_NAME] = model;
127
+ }
128
+ if (modelParameters) {
129
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_INVOCATION_PARAMETERS] = _serialize(modelParameters);
130
+ otelAttributes[OtelSpanAttributes.LLM_MODEL_PARAMETERS] = _serialize(modelParameters);
131
+ }
132
+ if (usageDetails) {
133
+ if (typeof usageDetails === "object") {
134
+ const usage = usageDetails;
135
+ if (usage.promptTokens !== void 0) {
136
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_TOKEN_COUNT_PROMPT] = usage.promptTokens;
137
+ }
138
+ if (usage.completionTokens !== void 0) {
139
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_TOKEN_COUNT_COMPLETION] = usage.completionTokens;
140
+ }
141
+ if (usage.totalTokens !== void 0) {
142
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_TOKEN_COUNT_TOTAL] = usage.totalTokens;
143
+ }
144
+ }
145
+ otelAttributes[OtelSpanAttributes.LLM_USAGE_DETAILS] = _serialize(usageDetails);
146
+ }
147
+ if (completionStartTime) {
148
+ otelAttributes[OtelSpanAttributes.LLM_COMPLETION_START_TIME] = _serialize(completionStartTime);
149
+ }
150
+ }
151
+ if (type === "embedding") {
152
+ if (model) {
153
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.EMBEDDING_MODEL_NAME] = model;
154
+ }
155
+ if (modelParameters) {
156
+ otelAttributes[import_openinference_semantic_conventions2.SemanticConventions.LLM_INVOCATION_PARAMETERS] = _serialize(modelParameters);
157
+ }
158
+ }
159
+ const metadataAttrs = _flattenAndSerializeMetadata(
160
+ metadata,
161
+ import_openinference_semantic_conventions2.SemanticConventions.METADATA
162
+ );
163
+ Object.assign(otelAttributes, metadataAttrs);
164
+ const obsetvabilityMetadataAttrs = _flattenAndSerializeMetadata(
165
+ metadata,
166
+ OtelSpanAttributes.OBSERVATION_METADATA
167
+ );
168
+ Object.assign(otelAttributes, obsetvabilityMetadataAttrs);
169
+ return Object.fromEntries(
170
+ Object.entries(otelAttributes).filter(([_, v]) => v != null)
171
+ );
172
+ }
173
+ function _serialize(obj) {
174
+ try {
175
+ if (typeof obj === "string") return obj;
176
+ if (obj instanceof Date) return obj.toISOString();
177
+ return obj != null ? JSON.stringify(obj) : void 0;
178
+ } catch {
179
+ return "<failed to serialize>";
180
+ }
181
+ }
182
+ function _flattenAndSerializeMetadata(metadata, prefix) {
183
+ const metadataAttributes = {};
184
+ if (metadata === void 0 || metadata === null) {
185
+ return metadataAttributes;
186
+ }
187
+ if (typeof metadata !== "object" || Array.isArray(metadata)) {
188
+ const serialized = _serialize(metadata);
189
+ if (serialized) {
190
+ metadataAttributes[prefix] = serialized;
191
+ }
192
+ } else {
193
+ for (const [key, value] of Object.entries(metadata)) {
194
+ const serialized = typeof value === "string" ? value : _serialize(value);
195
+ if (serialized) {
196
+ metadataAttributes[`${prefix}.${key}`] = serialized;
197
+ }
198
+ }
199
+ }
200
+ return metadataAttributes;
201
+ }
202
+ var import_openinference_semantic_conventions2;
203
+ var init_attributes = __esm({
204
+ "src/core/attributes.ts"() {
205
+ "use strict";
206
+ init_constants();
207
+ import_openinference_semantic_conventions2 = require("@arizeai/openinference-semantic-conventions");
208
+ }
209
+ });
210
+
211
+ // src/core/tracerProvider.ts
212
+ function createState() {
213
+ return {
214
+ isolatedTracerProvider: null
215
+ };
216
+ }
217
+ function getObservabilityGlobalState() {
218
+ const initialState = createState();
219
+ try {
220
+ const g = globalThis;
221
+ if (typeof g !== "object" || g === null) {
222
+ console.warn(
223
+ "[Observability] globalThis is not available, using fallback state"
224
+ );
225
+ return initialState;
226
+ }
227
+ if (!g[OBSERVABILITY_GLOBAL_SYMBOL]) {
228
+ Object.defineProperty(g, OBSERVABILITY_GLOBAL_SYMBOL, {
229
+ value: initialState,
230
+ writable: false,
231
+ configurable: false,
232
+ enumerable: false
233
+ });
234
+ }
235
+ return g[OBSERVABILITY_GLOBAL_SYMBOL];
236
+ } catch (err) {
237
+ console.error(
238
+ `[Observability] Failed to access global state: ${err instanceof Error ? err.message : String(err)}`
239
+ );
240
+ return initialState;
241
+ }
242
+ }
243
+ function setTracerProvider(provider) {
244
+ getObservabilityGlobalState().isolatedTracerProvider = provider;
245
+ }
246
+ function getTracerProvider() {
247
+ const { isolatedTracerProvider } = getObservabilityGlobalState();
248
+ if (isolatedTracerProvider) return isolatedTracerProvider;
249
+ return import_api.trace.getTracerProvider();
250
+ }
251
+ function getTracer() {
252
+ return getTracerProvider().getTracer(
253
+ OBSERVABILITY_SDK_NAME,
254
+ OBSERVABILITY_SDK_VERSION
255
+ );
256
+ }
257
+ var import_api, OBSERVABILITY_GLOBAL_SYMBOL, OBSERVABILITY_SDK_NAME, OBSERVABILITY_SDK_VERSION;
258
+ var init_tracerProvider = __esm({
259
+ "src/core/tracerProvider.ts"() {
260
+ "use strict";
261
+ import_api = require("@opentelemetry/api");
262
+ OBSERVABILITY_GLOBAL_SYMBOL = /* @__PURE__ */ Symbol.for("observability");
263
+ OBSERVABILITY_SDK_NAME = "ag-kit-observability";
264
+ OBSERVABILITY_SDK_VERSION = "0.1.0";
265
+ }
266
+ });
267
+
268
+ // src/core/spanWrapper.ts
269
+ var BaseObservation, ObservationSpan, ObservationLLM, ObservationEmbedding, ObservationAgent, ObservationTool, ObservationChain, ObservationRetriever, ObservationReranker, ObservationEvaluator, ObservationGuardrail;
270
+ var init_spanWrapper = __esm({
271
+ "src/core/spanWrapper.ts"() {
272
+ "use strict";
273
+ init_attributes();
274
+ init_tracerProvider();
275
+ BaseObservation = class {
276
+ /** The underlying OpenTelemetry span */
277
+ otelSpan;
278
+ /** The observation type */
279
+ type;
280
+ /** The span ID from the OpenTelemetry span context */
281
+ id;
282
+ /** The trace ID from the OpenTelemetry span context */
283
+ traceId;
284
+ constructor(params) {
285
+ this.otelSpan = params.otelSpan;
286
+ this.id = params.otelSpan.spanContext().spanId;
287
+ this.traceId = params.otelSpan.spanContext().traceId;
288
+ this.type = params.type;
289
+ if (params.attributes) {
290
+ this.otelSpan.setAttributes(
291
+ createObservationAttributes(params.type, params.attributes)
292
+ );
293
+ }
294
+ }
295
+ /** Gets the AG-Kit OpenTelemetry tracer instance */
296
+ get tracer() {
297
+ return getTracer();
298
+ }
299
+ /**
300
+ * Ends the observation, marking it as complete.
301
+ *
302
+ * @param endTime - Optional end time, defaults to current time
303
+ */
304
+ end(endTime) {
305
+ this.otelSpan.end(endTime);
306
+ }
307
+ /**
308
+ * Updates the OTEL span attributes.
309
+ *
310
+ * @param attributes - Attributes to update
311
+ * @internal
312
+ */
313
+ updateOtelSpanAttributes(attributes) {
314
+ this.otelSpan.setAttributes(
315
+ createObservationAttributes(this.type, attributes)
316
+ );
317
+ }
318
+ /**
319
+ * Updates the parent trace with new attributes.
320
+ *
321
+ * @param attributes - Trace attributes to set
322
+ * @returns This observation for method chaining
323
+ */
324
+ updateTrace(attributes) {
325
+ this.otelSpan.setAttributes(createTraceAttributes(attributes));
326
+ return this;
327
+ }
328
+ startObservation(name, attributes, options) {
329
+ const { startObservation: startObs } = (init_src(), __toCommonJS(src_exports));
330
+ const { asType = "span" } = options || {};
331
+ return startObs(name, attributes, {
332
+ asType,
333
+ parentSpanContext: this.otelSpan.spanContext()
334
+ });
335
+ }
336
+ };
337
+ ObservationSpan = class extends BaseObservation {
338
+ constructor(params) {
339
+ super({ ...params, type: "span" });
340
+ }
341
+ update(attributes) {
342
+ super.updateOtelSpanAttributes(attributes);
343
+ return this;
344
+ }
345
+ };
346
+ ObservationLLM = class extends BaseObservation {
347
+ constructor(params) {
348
+ super({ ...params, type: "llm" });
349
+ }
350
+ update(attributes) {
351
+ super.updateOtelSpanAttributes(attributes);
352
+ return this;
353
+ }
354
+ };
355
+ ObservationEmbedding = class extends BaseObservation {
356
+ constructor(params) {
357
+ super({ ...params, type: "embedding" });
358
+ }
359
+ update(attributes) {
360
+ super.updateOtelSpanAttributes(attributes);
361
+ return this;
362
+ }
363
+ };
364
+ ObservationAgent = class extends BaseObservation {
365
+ constructor(params) {
366
+ super({ ...params, type: "agent" });
367
+ }
368
+ update(attributes) {
369
+ super.updateOtelSpanAttributes(attributes);
370
+ return this;
371
+ }
372
+ };
373
+ ObservationTool = class extends BaseObservation {
374
+ constructor(params) {
375
+ super({ ...params, type: "tool" });
376
+ }
377
+ update(attributes) {
378
+ super.updateOtelSpanAttributes(attributes);
379
+ return this;
380
+ }
381
+ };
382
+ ObservationChain = class extends BaseObservation {
383
+ constructor(params) {
384
+ super({ ...params, type: "chain" });
385
+ }
386
+ update(attributes) {
387
+ super.updateOtelSpanAttributes(attributes);
388
+ return this;
389
+ }
390
+ };
391
+ ObservationRetriever = class extends BaseObservation {
392
+ constructor(params) {
393
+ super({ ...params, type: "retriever" });
394
+ }
395
+ update(attributes) {
396
+ super.updateOtelSpanAttributes(attributes);
397
+ return this;
398
+ }
399
+ };
400
+ ObservationReranker = class extends BaseObservation {
401
+ constructor(params) {
402
+ super({ ...params, type: "reranker" });
403
+ }
404
+ update(attributes) {
405
+ super.updateOtelSpanAttributes(attributes);
406
+ return this;
407
+ }
408
+ };
409
+ ObservationEvaluator = class extends BaseObservation {
410
+ constructor(params) {
411
+ super({ ...params, type: "evaluator" });
412
+ }
413
+ update(attributes) {
414
+ super.updateOtelSpanAttributes(attributes);
415
+ return this;
416
+ }
417
+ };
418
+ ObservationGuardrail = class extends BaseObservation {
419
+ constructor(params) {
420
+ super({ ...params, type: "guardrail" });
421
+ }
422
+ update(attributes) {
423
+ super.updateOtelSpanAttributes(attributes);
424
+ return this;
425
+ }
426
+ };
427
+ }
428
+ });
429
+
430
+ // src/index.ts
431
+ var src_exports = {};
432
+ __export(src_exports, {
433
+ ObservationAgent: () => ObservationAgent,
434
+ ObservationChain: () => ObservationChain,
435
+ ObservationEmbedding: () => ObservationEmbedding,
436
+ ObservationEvaluator: () => ObservationEvaluator,
437
+ ObservationGuardrail: () => ObservationGuardrail,
438
+ ObservationLLM: () => ObservationLLM,
439
+ ObservationReranker: () => ObservationReranker,
440
+ ObservationRetriever: () => ObservationRetriever,
441
+ ObservationSpan: () => ObservationSpan,
442
+ ObservationTool: () => ObservationTool,
443
+ createObservationAttributes: () => createObservationAttributes,
444
+ createTraceAttributes: () => createTraceAttributes,
445
+ getActiveSpanId: () => getActiveSpanId,
446
+ getActiveTraceId: () => getActiveTraceId,
447
+ getTracer: () => getTracer,
448
+ getTracerProvider: () => getTracerProvider,
449
+ observe: () => observe,
450
+ setTracerProvider: () => setTracerProvider,
451
+ startActiveObservation: () => startActiveObservation,
452
+ startObservation: () => startObservation,
453
+ updateActiveObservation: () => updateActiveObservation,
454
+ updateActiveTrace: () => updateActiveTrace
455
+ });
456
+ module.exports = __toCommonJS(src_exports);
457
+ function createOtelSpan(params) {
458
+ return getTracer().startSpan(
459
+ params.name,
460
+ { startTime: params.startTime },
461
+ createParentContext(params.parentSpanContext)
462
+ );
463
+ }
464
+ function createParentContext(parentSpanContext) {
465
+ if (!parentSpanContext) return;
466
+ return import_api2.trace.setSpanContext(import_api2.context.active(), parentSpanContext);
467
+ }
468
+ function startObservation(name, attributes, options) {
469
+ const { asType = "span", ...observationOptions } = options || {};
470
+ const otelSpan = createOtelSpan({
471
+ name,
472
+ ...observationOptions
473
+ });
474
+ switch (asType) {
475
+ case "llm":
476
+ return new ObservationLLM({
477
+ otelSpan,
478
+ attributes
479
+ });
480
+ case "embedding":
481
+ return new ObservationEmbedding({
482
+ otelSpan,
483
+ attributes
484
+ });
485
+ case "agent":
486
+ return new ObservationAgent({
487
+ otelSpan,
488
+ attributes
489
+ });
490
+ case "tool":
491
+ return new ObservationTool({
492
+ otelSpan,
493
+ attributes
494
+ });
495
+ case "chain":
496
+ return new ObservationChain({
497
+ otelSpan,
498
+ attributes
499
+ });
500
+ case "retriever":
501
+ return new ObservationRetriever({
502
+ otelSpan,
503
+ attributes
504
+ });
505
+ case "reranker":
506
+ return new ObservationReranker({
507
+ otelSpan,
508
+ attributes
509
+ });
510
+ case "evaluator":
511
+ return new ObservationEvaluator({
512
+ otelSpan,
513
+ attributes
514
+ });
515
+ case "guardrail":
516
+ return new ObservationGuardrail({
517
+ otelSpan,
518
+ attributes
519
+ });
520
+ case "span":
521
+ default:
522
+ return new ObservationSpan({
523
+ otelSpan,
524
+ attributes
525
+ });
526
+ }
527
+ }
528
+ function updateActiveTrace(attributes) {
529
+ const span = import_api2.trace.getActiveSpan();
530
+ if (!span) {
531
+ console.warn(
532
+ "[Observability] No active OTEL span in context. Skipping trace update."
533
+ );
534
+ return;
535
+ }
536
+ span.setAttributes(createTraceAttributes(attributes));
537
+ }
538
+ function getActiveTraceId() {
539
+ return import_api2.trace.getActiveSpan()?.spanContext().traceId;
540
+ }
541
+ function getActiveSpanId() {
542
+ return import_api2.trace.getActiveSpan()?.spanContext().spanId;
543
+ }
544
+ function wrapPromise(promise, span, endOnExit) {
545
+ return promise.then(
546
+ (value) => {
547
+ if (endOnExit !== false) {
548
+ span.end();
549
+ }
550
+ return value;
551
+ },
552
+ (err) => {
553
+ span.setStatus({
554
+ code: import_api2.SpanStatusCode.ERROR,
555
+ message: err instanceof Error ? err.message : "Unknown error"
556
+ });
557
+ if (endOnExit !== false) {
558
+ span.end();
559
+ }
560
+ throw err;
561
+ }
562
+ );
563
+ }
564
+ function startActiveObservation(name, fn, options) {
565
+ const { asType = "span", endOnExit, ...observationOptions } = options || {};
566
+ return getTracer().startActiveSpan(
567
+ name,
568
+ { startTime: observationOptions?.startTime },
569
+ createParentContext(observationOptions?.parentSpanContext) ?? import_api2.context.active(),
570
+ (span) => {
571
+ try {
572
+ let observation;
573
+ switch (asType) {
574
+ case "llm":
575
+ observation = new ObservationLLM({ otelSpan: span });
576
+ break;
577
+ case "embedding":
578
+ observation = new ObservationEmbedding({ otelSpan: span });
579
+ break;
580
+ case "agent":
581
+ observation = new ObservationAgent({ otelSpan: span });
582
+ break;
583
+ case "tool":
584
+ observation = new ObservationTool({ otelSpan: span });
585
+ break;
586
+ case "chain":
587
+ observation = new ObservationChain({ otelSpan: span });
588
+ break;
589
+ case "retriever":
590
+ observation = new ObservationRetriever({ otelSpan: span });
591
+ break;
592
+ case "reranker":
593
+ observation = new ObservationReranker({ otelSpan: span });
594
+ break;
595
+ case "evaluator":
596
+ observation = new ObservationEvaluator({ otelSpan: span });
597
+ break;
598
+ case "guardrail":
599
+ observation = new ObservationGuardrail({ otelSpan: span });
600
+ break;
601
+ case "span":
602
+ default:
603
+ observation = new ObservationSpan({ otelSpan: span });
604
+ }
605
+ const result = fn(observation);
606
+ if (result instanceof Promise) {
607
+ return wrapPromise(
608
+ result,
609
+ span,
610
+ endOnExit
611
+ );
612
+ } else {
613
+ if (endOnExit !== false) {
614
+ span.end();
615
+ }
616
+ return result;
617
+ }
618
+ } catch (err) {
619
+ span.setStatus({
620
+ code: import_api2.SpanStatusCode.ERROR,
621
+ message: err instanceof Error ? err.message : "Unknown error"
622
+ });
623
+ if (endOnExit !== false) {
624
+ span.end();
625
+ }
626
+ throw err;
627
+ }
628
+ }
629
+ );
630
+ }
631
+ function updateActiveObservation(attributes) {
632
+ const span = import_api2.trace.getActiveSpan();
633
+ if (!span) {
634
+ console.warn(
635
+ "[Observability] No active OTEL span in context. Skipping observation update."
636
+ );
637
+ return;
638
+ }
639
+ span.setAttributes(createObservationAttributes("span", attributes));
640
+ }
641
+ function _captureArguments(args) {
642
+ if (args.length === 0) return {};
643
+ if (args.length === 1) return { arg: args[0] };
644
+ return { args };
645
+ }
646
+ function observe(fn, options = {}) {
647
+ const {
648
+ asType = "span",
649
+ captureInput = true,
650
+ captureOutput = true,
651
+ ...observationOptions
652
+ } = options;
653
+ const wrappedFunction = function(...args) {
654
+ const name = fn.name || "anonymous-function";
655
+ const inputData = captureInput ? _captureArguments(args) : void 0;
656
+ const observation = startObservation(
657
+ name,
658
+ inputData ? { input: inputData } : {},
659
+ {
660
+ ...observationOptions,
661
+ asType
662
+ }
663
+ );
664
+ const activeContext = import_api2.trace.setSpan(import_api2.context.active(), observation.otelSpan);
665
+ const result = import_api2.context.with(activeContext, () => fn.apply(this, args));
666
+ if (result instanceof Promise) {
667
+ return result.then(
668
+ (value) => {
669
+ if (captureOutput) {
670
+ observation.update({ output: value });
671
+ }
672
+ observation.end();
673
+ return value;
674
+ },
675
+ (err) => {
676
+ observation.update({
677
+ level: "ERROR",
678
+ statusMessage: err instanceof Error ? err.message : "Unknown error"
679
+ });
680
+ observation.end();
681
+ throw err;
682
+ }
683
+ );
684
+ }
685
+ if (captureOutput) {
686
+ observation.update({ output: result });
687
+ }
688
+ observation.end();
689
+ return result;
690
+ };
691
+ Object.defineProperty(wrappedFunction, "name", { value: fn.name });
692
+ Object.defineProperty(wrappedFunction, "length", { value: fn.length });
693
+ return wrappedFunction;
694
+ }
695
+ var import_api2;
696
+ var init_src = __esm({
697
+ "src/index.ts"() {
698
+ import_api2 = require("@opentelemetry/api");
699
+ init_attributes();
700
+ init_spanWrapper();
701
+ init_tracerProvider();
702
+ init_attributes();
703
+ init_tracerProvider();
704
+ }
705
+ });
706
+ init_src();
707
+ // Annotate the CommonJS export names for ESM import in node:
708
+ 0 && (module.exports = {
709
+ ObservationAgent,
710
+ ObservationChain,
711
+ ObservationEmbedding,
712
+ ObservationEvaluator,
713
+ ObservationGuardrail,
714
+ ObservationLLM,
715
+ ObservationReranker,
716
+ ObservationRetriever,
717
+ ObservationSpan,
718
+ ObservationTool,
719
+ createObservationAttributes,
720
+ createTraceAttributes,
721
+ getActiveSpanId,
722
+ getActiveTraceId,
723
+ getTracer,
724
+ getTracerProvider,
725
+ observe,
726
+ setTracerProvider,
727
+ startActiveObservation,
728
+ startObservation,
729
+ updateActiveObservation,
730
+ updateActiveTrace
731
+ });
732
+ //# sourceMappingURL=index.js.map