netra-sdk 1.4.0 → 1.5.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.
package/dist/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { __toESM, require_decamelize, require_camelcase, init_esm_node, __publicField, v7_default, __require } from './chunk-WMQRYJGR.js';
2
- import { createContextKey, propagation, context, trace, SpanKind, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
2
+ import { createContextKey, propagation, trace, context, SpanKind, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
3
3
  import { createRequire } from 'module';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
5
  import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';
6
6
  import { initialize } from '@traceloop/node-server-sdk';
7
7
  import shimmer from 'shimmer';
8
- import * as dotenv from 'dotenv';
9
8
  import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator, ExportResultCode } from '@opentelemetry/core';
10
9
  import * as http from 'http';
11
10
  import * as https from 'https';
@@ -76,9 +75,9 @@ function netraExpressMiddleware() {
76
75
 
77
76
  // src/api/http-client.ts
78
77
  var NetraHttpClient = class {
79
- constructor(config2, timeoutEnvVar, defaultTimeout) {
78
+ constructor(config, timeoutEnvVar, defaultTimeout) {
80
79
  this.initialized = false;
81
- const endpoint = config2.otlpEndpoint?.trim() || "";
80
+ const endpoint = config.otlpEndpoint?.trim() || "";
82
81
  if (!endpoint) {
83
82
  Logger.error(
84
83
  "netra: NETRA_OTLP_ENDPOINT is required for API calls"
@@ -89,7 +88,7 @@ var NetraHttpClient = class {
89
88
  return;
90
89
  }
91
90
  this.baseUrl = this.resolveBaseUrl(endpoint);
92
- this.headers = this.buildHeaders(config2);
91
+ this.headers = this.buildHeaders(config);
93
92
  this.timeout = this.getTimeout(timeoutEnvVar, defaultTimeout);
94
93
  this.initialized = true;
95
94
  }
@@ -100,10 +99,10 @@ var NetraHttpClient = class {
100
99
  }
101
100
  return baseUrl;
102
101
  }
103
- buildHeaders(config2) {
104
- const headers = { ...config2.headers };
105
- if (config2.apiKey) {
106
- headers["x-api-key"] = config2.apiKey;
102
+ buildHeaders(config) {
103
+ const headers = { ...config.headers };
104
+ if (config.apiKey) {
105
+ headers["x-api-key"] = config.apiKey;
107
106
  }
108
107
  headers["Content-Type"] = "application/json";
109
108
  return headers;
@@ -209,8 +208,8 @@ var NetraHttpClient = class {
209
208
 
210
209
  // src/api/usage/client.ts
211
210
  var UsageHttpClient = class extends NetraHttpClient {
212
- constructor(config2) {
213
- super(config2, "NETRA_USAGE_TIMEOUT", 10);
211
+ constructor(config) {
212
+ super(config, "NETRA_USAGE_TIMEOUT", 10);
214
213
  }
215
214
  async getSessionUsage(sessionId, startTime, endTime) {
216
215
  if (!this.isInitialized()) {
@@ -298,9 +297,9 @@ var UsageHttpClient = class extends NetraHttpClient {
298
297
 
299
298
  // src/api/usage/api.ts
300
299
  var Usage = class {
301
- constructor(config2) {
302
- this.config = config2;
303
- this.client = new UsageHttpClient(config2);
300
+ constructor(config) {
301
+ this.config = config;
302
+ this.client = new UsageHttpClient(config);
304
303
  }
305
304
  /**
306
305
  * Get session usage data
@@ -465,8 +464,8 @@ var Usage = class {
465
464
  if (!page) {
466
465
  break;
467
466
  }
468
- for (const trace24 of page.traces) {
469
- yield trace24;
467
+ for (const trace25 of page.traces) {
468
+ yield trace25;
470
469
  }
471
470
  if (!page.hasNextPage || !page.nextCursor) {
472
471
  break;
@@ -579,13 +578,14 @@ var Usage = class {
579
578
  };
580
579
 
581
580
  // src/version.ts
582
- var SDK_VERSION = "1.4.0";
581
+ var SDK_VERSION = "1.5.0";
583
582
 
584
583
  // src/config.ts
585
584
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
586
585
  NetraInstruments2["ALL"] = "__all__";
587
586
  NetraInstruments2["OPENAI"] = "openai";
588
- NetraInstruments2["GOOGLE_GENERATIVE_AI"] = "google_genai";
587
+ NetraInstruments2["GOOGLE_GENAI"] = "google_genai";
588
+ NetraInstruments2["GOOGLE_GENERATIVE_AI"] = "google_generative_ai";
589
589
  NetraInstruments2["MISTRAL"] = "mistral_ai";
590
590
  NetraInstruments2["GROQ"] = "groq";
591
591
  NetraInstruments2["VERTEX_AI"] = "vertexai";
@@ -610,7 +610,8 @@ var DEFAULT_INSTRUMENTS_FOR_ROOT = /* @__PURE__ */ new Set([
610
610
  "anthropic" /* ANTHROPIC */,
611
611
  "groq" /* GROQ */,
612
612
  "mistral_ai" /* MISTRAL */,
613
- "google_genai" /* GOOGLE_GENERATIVE_AI */,
613
+ "google_genai" /* GOOGLE_GENAI */,
614
+ "google_generative_ai" /* GOOGLE_GENERATIVE_AI */,
614
615
  "vertexai" /* VERTEX_AI */,
615
616
  "together" /* TOGETHER */,
616
617
  // AI frameworks
@@ -634,41 +635,41 @@ var DEFAULT_INSTRUMENTS = /* @__PURE__ */ new Set([
634
635
  "express" /* EXPRESS */
635
636
  ]);
636
637
  var Config = class {
637
- constructor(config2 = {}) {
638
- this.appName = this._getAppName(config2.appName);
638
+ constructor(config = {}) {
639
+ this.appName = this._getAppName(config.appName);
639
640
  this.otlpEndpoint = this._getOtlpEndpoint();
640
641
  this.apiKey = process.env.NETRA_API_KEY;
641
- this.headers = this._parseHeaders(config2.headers);
642
+ this.headers = this._parseHeaders(config.headers);
642
643
  this.disableBatch = this._getBoolConfig(
643
- config2.disableBatch,
644
+ config.disableBatch,
644
645
  "NETRA_DISABLE_BATCH",
645
646
  false
646
647
  );
647
648
  this.traceContent = this._getBoolConfig(
648
- config2.traceContent,
649
+ config.traceContent,
649
650
  "NETRA_TRACE_CONTENT",
650
651
  true
651
652
  );
652
653
  this.debugMode = this._getBoolConfig(
653
- config2.debugMode,
654
+ config.debugMode,
654
655
  "NETRA_DEBUG",
655
656
  false
656
657
  );
657
658
  this.enableRootSpan = this._getBoolConfig(
658
- config2.enableRootSpan,
659
+ config.enableRootSpan,
659
660
  "NETRA_ENABLE_ROOT_SPAN",
660
661
  false
661
662
  );
662
663
  this.enableScrubbing = this._getBoolConfig(
663
- config2.enableScrubbing,
664
+ config.enableScrubbing,
664
665
  "NETRA_ENABLE_SCRUBBING",
665
666
  false
666
667
  );
667
- this.environment = config2.environment || process.env.NETRA_ENV || "local";
668
+ this.environment = config.environment || process.env.NETRA_ENV || "local";
668
669
  this.resourceAttributes = this._getResourceAttributes(
669
- config2.resourceAttributes
670
+ config.resourceAttributes
670
671
  );
671
- this.blockedSpans = config2.blockedSpans;
672
+ this.blockedSpans = config.blockedSpans;
672
673
  this._validateApiKey();
673
674
  this._setupAuthentication();
674
675
  this._setTraceContentEnv();
@@ -1097,6 +1098,9 @@ function safeStringify(value, maxLength) {
1097
1098
  let result;
1098
1099
  try {
1099
1100
  result = JSON.stringify(value, (_key, val) => {
1101
+ if (typeof val === "string" && maxLength && val.length > maxLength) {
1102
+ return truncate(val, maxLength);
1103
+ }
1100
1104
  if (typeof val === "function")
1101
1105
  return `[Function: ${val.name || "anonymous"}]`;
1102
1106
  if (typeof val === "symbol") return val.toString();
@@ -1252,8 +1256,8 @@ var SessionManager = class _SessionManager {
1252
1256
  }
1253
1257
  /**
1254
1258
  * Set input on the currently active span.
1255
- * Writes to `netra.user.input` so that SpanIOProcessor can promote it
1256
- * to `input` at span end, giving user-supplied values the highest priority.
1259
+ * Writes to `netra.user.input` which SpanIOProcessor intercepts inline
1260
+ * and writes directly to `input`, taking priority over decorator/instrumentation.
1257
1261
  */
1258
1262
  static setInput(value) {
1259
1263
  try {
@@ -1267,8 +1271,8 @@ var SessionManager = class _SessionManager {
1267
1271
  }
1268
1272
  /**
1269
1273
  * Set output on the currently active span.
1270
- * Writes to `netra.user.output` so that SpanIOProcessor can promote it
1271
- * to `output` at span end, giving user-supplied values the highest priority.
1274
+ * Writes to `netra.user.output` which SpanIOProcessor intercepts inline
1275
+ * and writes directly to `output`, taking priority over decorator/instrumentation.
1272
1276
  */
1273
1277
  static setOutput(value) {
1274
1278
  try {
@@ -1283,12 +1287,12 @@ var SessionManager = class _SessionManager {
1283
1287
  /**
1284
1288
  * Set input on the root span of the current trace.
1285
1289
  * Delegates to RootSpanProcessor which owns root span bookkeeping.
1286
- * Writes to `netra.user.input` so SpanIOProcessor promotes it at span end.
1290
+ * Uses `netra.root.input` for highest priority (overrides even setInput).
1287
1291
  */
1288
1292
  static setRootInput(value) {
1289
1293
  try {
1290
1294
  RootSpanProcessor.setAttributeOnRootSpan(
1291
- "netra.user.input",
1295
+ "netra.root.input",
1292
1296
  serializeValue(value, Config.ATTRIBUTE_MAX_LEN)
1293
1297
  );
1294
1298
  } catch (e) {
@@ -1298,12 +1302,12 @@ var SessionManager = class _SessionManager {
1298
1302
  /**
1299
1303
  * Set output on the root span of the current trace.
1300
1304
  * Delegates to RootSpanProcessor which owns root span bookkeeping.
1301
- * Writes to `netra.user.output` so SpanIOProcessor promotes it at span end.
1305
+ * Uses `netra.root.output` for highest priority (overrides even setOutput).
1302
1306
  */
1303
1307
  static setRootOutput(value) {
1304
1308
  try {
1305
1309
  RootSpanProcessor.setAttributeOnRootSpan(
1306
- "netra.user.output",
1310
+ "netra.root.output",
1307
1311
  serializeValue(value, Config.ATTRIBUTE_MAX_LEN)
1308
1312
  );
1309
1313
  } catch (e) {
@@ -1545,8 +1549,8 @@ var SpanWrapper = class {
1545
1549
 
1546
1550
  // src/api/evaluation/client.ts
1547
1551
  var EvaluationHttpClient = class extends NetraHttpClient {
1548
- constructor(config2) {
1549
- super(config2, "NETRA_EVALUATION_TIMEOUT", 10);
1552
+ constructor(config) {
1553
+ super(config, "NETRA_EVALUATION_TIMEOUT", 10);
1550
1554
  }
1551
1555
  /**
1552
1556
  * Fetch dataset items for a dataset id
@@ -1791,11 +1795,11 @@ function extractEvaluatorConfig(evaluator) {
1791
1795
  if (!evaluator || typeof evaluator !== "object" || !("config" in evaluator)) {
1792
1796
  return null;
1793
1797
  }
1794
- const config2 = evaluator.config;
1795
- if (!config2 || typeof config2 !== "object") {
1798
+ const config = evaluator.config;
1799
+ if (!config || typeof config !== "object") {
1796
1800
  return null;
1797
1801
  }
1798
- return config2;
1802
+ return config;
1799
1803
  }
1800
1804
  async function executeTask(task2, itemInput) {
1801
1805
  try {
@@ -1811,17 +1815,17 @@ async function runSingleEvaluator(params) {
1811
1815
  return null;
1812
1816
  }
1813
1817
  let expectedName = null;
1814
- const config2 = extractEvaluatorConfig(evaluator);
1815
- if (config2) {
1816
- expectedName = config2.name;
1818
+ const config = extractEvaluatorConfig(evaluator);
1819
+ if (config) {
1820
+ expectedName = config.name;
1817
1821
  }
1818
- const context16 = {
1822
+ const context17 = {
1819
1823
  input: itemInput,
1820
1824
  taskOutput,
1821
1825
  expectedOutput,
1822
1826
  metadata
1823
1827
  };
1824
- let result = evaluator.evaluate(context16);
1828
+ let result = evaluator.evaluate(context17);
1825
1829
  if (result instanceof Promise) {
1826
1830
  result = await result;
1827
1831
  }
@@ -1889,12 +1893,12 @@ function buildEvaluatorsConfig(evaluators) {
1889
1893
  return configs;
1890
1894
  }
1891
1895
  for (const evaluator of evaluators) {
1892
- const config2 = extractEvaluatorConfig(evaluator);
1893
- if (!config2) {
1896
+ const config = extractEvaluatorConfig(evaluator);
1897
+ if (!config) {
1894
1898
  continue;
1895
1899
  }
1896
1900
  try {
1897
- configs.push(config2);
1901
+ configs.push(config);
1898
1902
  } catch {
1899
1903
  continue;
1900
1904
  }
@@ -1904,8 +1908,8 @@ function buildEvaluatorsConfig(evaluators) {
1904
1908
 
1905
1909
  // src/api/evaluation/api.ts
1906
1910
  var Evaluation = class {
1907
- constructor(config2) {
1908
- this.config = config2;
1911
+ constructor(config) {
1912
+ this.config = config;
1909
1913
  this.client = new EvaluationHttpClient(this.config);
1910
1914
  }
1911
1915
  /**
@@ -2306,9 +2310,9 @@ var RunStatus = /* @__PURE__ */ ((RunStatus2) => {
2306
2310
 
2307
2311
  // src/api/evaluation/context.ts
2308
2312
  var RunEntryContext = class {
2309
- constructor(client, config2, run, entry) {
2313
+ constructor(client, config, run, entry) {
2310
2314
  this.client = client;
2311
- this.config = config2;
2315
+ this.config = config;
2312
2316
  this.evaluationRun = run;
2313
2317
  this.entry = entry;
2314
2318
  }
@@ -2391,8 +2395,8 @@ var RunEntryContext = class {
2391
2395
 
2392
2396
  // src/api/dashboard/client.ts
2393
2397
  var DashboardHttpClient = class extends NetraHttpClient {
2394
- constructor(config2) {
2395
- super(config2, "NETRA_DASHBOARD_TIMEOUT", 30);
2398
+ constructor(config) {
2399
+ super(config, "NETRA_DASHBOARD_TIMEOUT", 30);
2396
2400
  }
2397
2401
  /**
2398
2402
  * Execute a dynamic query for dashboards
@@ -2662,9 +2666,9 @@ function metadataField(key) {
2662
2666
 
2663
2667
  // src/api/dashboard/api.ts
2664
2668
  var Dashboard = class {
2665
- constructor(config2) {
2666
- this.config = config2;
2667
- this.client = new DashboardHttpClient(config2);
2669
+ constructor(config) {
2670
+ this.config = config;
2671
+ this.client = new DashboardHttpClient(config);
2668
2672
  }
2669
2673
  /**
2670
2674
  * Execute a dynamic query for dashboards to retrieve metrics and time-series data
@@ -2813,8 +2817,8 @@ var Dashboard = class {
2813
2817
 
2814
2818
  // src/api/prompts/client.ts
2815
2819
  var PromptsHttpClient = class extends NetraHttpClient {
2816
- constructor(config2) {
2817
- super(config2, "NETRA_PROMPTS_TIMEOUT", 30);
2820
+ constructor(config) {
2821
+ super(config, "NETRA_PROMPTS_TIMEOUT", 30);
2818
2822
  }
2819
2823
  /**
2820
2824
  * Fetch prompt version from backend
@@ -2848,9 +2852,9 @@ var PromptsHttpClient = class extends NetraHttpClient {
2848
2852
 
2849
2853
  // src/api/prompts/api.ts
2850
2854
  var Prompts = class {
2851
- constructor(config2) {
2852
- this.config = config2;
2853
- this.client = new PromptsHttpClient(config2);
2855
+ constructor(config) {
2856
+ this.config = config;
2857
+ this.client = new PromptsHttpClient(config);
2854
2858
  }
2855
2859
  /**
2856
2860
  * Fetch prompt version by name and label.
@@ -2932,6 +2936,7 @@ var ALLOWED_INSTRUMENTATION_NAMES = /* @__PURE__ */ new Set([
2932
2936
  "mistral_ai",
2933
2937
  "mistralai",
2934
2938
  "google_genai",
2939
+ "google_generative_ai",
2935
2940
  "langchain",
2936
2941
  "llama_index",
2937
2942
  "pinecone",
@@ -3340,7 +3345,6 @@ var SessionSpanProcessor = class {
3340
3345
  span2.setAttribute("library.name", Config.LIBRARY_NAME);
3341
3346
  span2.setAttribute("library.version", Config.LIBRARY_VERSION);
3342
3347
  span2.setAttribute("sdk.name", Config.SDK_NAME);
3343
- span2.setAttribute("deployment.environment", this.environment);
3344
3348
  const ctxToUse = parentContext || context.active();
3345
3349
  const baggage = propagation.getBaggage(ctxToUse);
3346
3350
  const sessionId = baggage?.getEntry("session_id")?.value ?? sessionValues.get("session_id");
@@ -3556,6 +3560,8 @@ var _USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens";
3556
3560
  var _USAGE_COMPLETION_TOKENS = "gen_ai.usage.completion_tokens";
3557
3561
  var NETRA_USER_INPUT = "netra.user.input";
3558
3562
  var NETRA_USER_OUTPUT = "netra.user.output";
3563
+ var NETRA_ROOT_INPUT = "netra.root.input";
3564
+ var NETRA_ROOT_OUTPUT = "netra.root.output";
3559
3565
  var NETRA_ENTITY_INPUT = "netra.entity.input";
3560
3566
  var NETRA_ENTITY_OUTPUT = "netra.entity.output";
3561
3567
  var MAX_PARSE_LEN = 1e6;
@@ -3598,54 +3604,15 @@ var SpanIOProcessor = class {
3598
3604
  if (!("output" in attrs)) {
3599
3605
  span2.setAttribute("output", "");
3600
3606
  }
3607
+ if (!("conversation" in attrs)) {
3608
+ span2.setAttribute("conversation", JSON.stringify([]));
3609
+ }
3601
3610
  this._wrapSetAttribute(span2);
3602
3611
  } catch (e) {
3603
3612
  Logger.error("SpanIOProcessor.onStart failed:", e);
3604
3613
  }
3605
3614
  }
3606
- onEnd(span2) {
3607
- try {
3608
- const attrs = span2._attributes ?? span2.attributes;
3609
- if (!attrs || typeof attrs !== "object") {
3610
- Logger.debug(
3611
- "SpanIOProcessor.onEnd: could not access span attributes \u2014 OTel SDK internal API may have changed"
3612
- );
3613
- return;
3614
- }
3615
- try {
3616
- if (NETRA_USER_INPUT in attrs) {
3617
- const userInput = attrs[NETRA_USER_INPUT];
3618
- if (!isEmpty(userInput)) {
3619
- attrs["input"] = userInput;
3620
- }
3621
- delete attrs[NETRA_USER_INPUT];
3622
- }
3623
- } catch (e) {
3624
- Logger.warn(
3625
- "SpanIOProcessor.onEnd: could not promote netra.user.input \u2192 input",
3626
- e
3627
- );
3628
- }
3629
- try {
3630
- if (NETRA_USER_OUTPUT in attrs) {
3631
- const userOutput = attrs[NETRA_USER_OUTPUT];
3632
- if (!isEmpty(userOutput)) {
3633
- attrs["output"] = userOutput;
3634
- }
3635
- delete attrs[NETRA_USER_OUTPUT];
3636
- }
3637
- } catch (e) {
3638
- Logger.warn(
3639
- "SpanIOProcessor.onEnd: could not promote netra.user.output \u2192 output",
3640
- e
3641
- );
3642
- }
3643
- } catch (e) {
3644
- Logger.error(
3645
- "SpanIOProcessor.onEnd: unexpected error during netra.user promotion",
3646
- e
3647
- );
3648
- }
3615
+ onEnd(_span) {
3649
3616
  }
3650
3617
  shutdown() {
3651
3618
  return Promise.resolve();
@@ -3659,10 +3626,50 @@ var SpanIOProcessor = class {
3659
3626
  let completions;
3660
3627
  let genAiOwnsInput = false;
3661
3628
  let genAiOwnsOutput = false;
3629
+ let userOwnsInput = false;
3630
+ let userOwnsOutput = false;
3631
+ let rootOwnsInput = false;
3632
+ let rootOwnsOutput = false;
3633
+ const inputLocked = () => rootOwnsInput || userOwnsInput;
3634
+ const outputLocked = () => rootOwnsOutput || userOwnsOutput;
3662
3635
  const inputIsEmpty = () => isEmpty((span2.attributes ?? {})["input"]);
3663
3636
  const outputIsEmpty = () => isEmpty((span2.attributes ?? {})["output"]);
3664
3637
  const patched = (key, value) => {
3665
3638
  try {
3639
+ if (key === NETRA_ROOT_INPUT) {
3640
+ rootOwnsInput = true;
3641
+ return original("input", value);
3642
+ }
3643
+ if (key === NETRA_ROOT_OUTPUT) {
3644
+ rootOwnsOutput = true;
3645
+ return original("output", value);
3646
+ }
3647
+ if (key === NETRA_USER_INPUT) {
3648
+ if (!rootOwnsInput) {
3649
+ userOwnsInput = true;
3650
+ return original("input", value);
3651
+ }
3652
+ return span2;
3653
+ }
3654
+ if (key === NETRA_USER_OUTPUT) {
3655
+ if (!rootOwnsOutput) {
3656
+ userOwnsOutput = true;
3657
+ return original("output", value);
3658
+ }
3659
+ return span2;
3660
+ }
3661
+ if (key === "input") {
3662
+ if (!inputLocked()) {
3663
+ return original("input", value);
3664
+ }
3665
+ return span2;
3666
+ }
3667
+ if (key === "output") {
3668
+ if (!outputLocked()) {
3669
+ return original("output", value);
3670
+ }
3671
+ return span2;
3672
+ }
3666
3673
  const promptMatch = _PROMPT_RE.exec(key);
3667
3674
  if (promptMatch) {
3668
3675
  original(key, value);
@@ -3675,7 +3682,7 @@ var SpanIOProcessor = class {
3675
3682
  prompts.set(idx, entry);
3676
3683
  }
3677
3684
  entry[field] = String(value);
3678
- if (inputIsEmpty() || genAiOwnsInput) {
3685
+ if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) {
3679
3686
  original("input", buildMessages(prompts));
3680
3687
  genAiOwnsInput = true;
3681
3688
  }
@@ -3693,32 +3700,32 @@ var SpanIOProcessor = class {
3693
3700
  completions.set(idx, entry);
3694
3701
  }
3695
3702
  entry[field] = String(value);
3696
- if (outputIsEmpty() || genAiOwnsOutput) {
3703
+ if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) {
3697
3704
  original("output", buildMessages(completions));
3698
3705
  genAiOwnsOutput = true;
3699
3706
  }
3700
3707
  return span2;
3701
3708
  }
3702
3709
  if (key === "traceloop.entity.input") {
3703
- if (inputIsEmpty()) {
3710
+ if (!inputLocked() && inputIsEmpty()) {
3704
3711
  original("input", extractTraceloopInput(value));
3705
3712
  }
3706
3713
  return span2;
3707
3714
  }
3708
3715
  if (key === "traceloop.entity.output") {
3709
- if (outputIsEmpty()) {
3716
+ if (!outputLocked() && outputIsEmpty()) {
3710
3717
  original("output", extractTraceloopOutput(value));
3711
3718
  }
3712
3719
  return span2;
3713
3720
  }
3714
3721
  if (key === NETRA_ENTITY_INPUT) {
3715
- if (inputIsEmpty()) {
3722
+ if (!inputLocked() && inputIsEmpty()) {
3716
3723
  original("input", extractTraceloopInput(value));
3717
3724
  }
3718
3725
  return span2;
3719
3726
  }
3720
3727
  if (key === NETRA_ENTITY_OUTPUT) {
3721
- if (outputIsEmpty()) {
3728
+ if (!outputLocked() && outputIsEmpty()) {
3722
3729
  original("output", extractTraceloopOutput(value));
3723
3730
  }
3724
3731
  return span2;
@@ -3933,12 +3940,14 @@ var SpanAttributes2 = {
3933
3940
  LLM_REQUEST_MAX_TOKENS: "gen_ai.request.max_tokens",
3934
3941
  LLM_REQUEST_TEMPERATURE: "gen_ai.request.temperature",
3935
3942
  LLM_REQUEST_TOP_P: "gen_ai.request.top_p",
3943
+ LLM_REQUEST_TOP_K: "gen_ai.request.top_k",
3936
3944
  LLM_REQUEST_REASONING: "gen_ai.request.reasoning",
3937
3945
  LLM_REQUEST_REASONING_EFFORT: "gen_ai.request.reasoning_effort",
3938
3946
  LLM_REQUEST_TOOL_NAME: "gen_ai.request.tool.name",
3939
3947
  LLM_REQUEST_TOOL_ID: "gen_ai.request.tool.id",
3940
3948
  LLM_RESPONSE_MODEL: "gen_ai.response.model",
3941
3949
  LLM_RESPONSE_FINISH_REASON: "llm.response.finish_reason",
3950
+ LLM_RESPONSE_DURATION: "llm.response.duration",
3942
3951
  LLM_USAGE_PROMPT_TOKENS: "gen_ai.usage.prompt_tokens",
3943
3952
  LLM_USAGE_COMPLETION_TOKENS: "gen_ai.usage.completion_tokens",
3944
3953
  LLM_USAGE_CACHE_READ_INPUT_TOKENS: "gen_ai.usage.cache_read_input_tokens",
@@ -3964,6 +3973,9 @@ function shouldSuppressInstrumentation() {
3964
3973
  const ctx = context.active();
3965
3974
  return ctx.getValue(SUPPRESS_INSTRUMENTATION_KEY) === true;
3966
3975
  }
3976
+ function createSuppressedContext(ctx) {
3977
+ return (ctx ?? context.active()).setValue(SUPPRESS_INSTRUMENTATION_KEY, true);
3978
+ }
3967
3979
  function defineHidden(target, key, value) {
3968
3980
  Object.defineProperty(target, key, {
3969
3981
  value,
@@ -5324,35 +5336,803 @@ var NetraAnthropicInstrumentor = class {
5324
5336
  }
5325
5337
  };
5326
5338
  var anthropicInstrumentor = new NetraAnthropicInstrumentor();
5339
+ var BaseInstrumentor = class {
5340
+ constructor() {
5341
+ this._isInstrumented = false;
5342
+ this._instrumentPromise = null;
5343
+ this._resolvedClasses = [];
5344
+ this._generation = 0;
5345
+ this._tracer = null;
5346
+ }
5347
+ /**
5348
+ * Check whether two resolved class sets refer to the same module load.
5349
+ * Default: reference equality. Override for composite class objects.
5350
+ */
5351
+ isSameClasses(a, b) {
5352
+ return a === b;
5353
+ }
5354
+ /**
5355
+ * Optional hook called during uninstrument() after prototype unwrapping.
5356
+ * Use for extra cleanup (e.g. restoring patched instance methods).
5357
+ */
5358
+ onUninstrument() {
5359
+ }
5360
+ get tracer() {
5361
+ return this._tracer;
5362
+ }
5363
+ isInstrumented() {
5364
+ return this._isInstrumented;
5365
+ }
5366
+ get resolvedClasses() {
5367
+ return this._resolvedClasses;
5368
+ }
5369
+ async instrument(options = {}) {
5370
+ if (this._isInstrumented) {
5371
+ Logger.warn(`${this.displayName} is already instrumented`);
5372
+ return this;
5373
+ }
5374
+ if (this._instrumentPromise) {
5375
+ return this._instrumentPromise;
5376
+ }
5377
+ this._instrumentPromise = this._doInstrument(options);
5378
+ try {
5379
+ return await this._instrumentPromise;
5380
+ } finally {
5381
+ this._instrumentPromise = null;
5382
+ }
5383
+ }
5384
+ uninstrument() {
5385
+ this._generation++;
5386
+ this._instrumentPromise = null;
5387
+ if (!this._isInstrumented) {
5388
+ Logger.warn(`${this.displayName} is not instrumented`);
5389
+ return;
5390
+ }
5391
+ for (const classes of this._resolvedClasses) {
5392
+ try {
5393
+ this.removePatches(classes);
5394
+ } catch (error) {
5395
+ Logger.error(`${this.displayName}: failed to remove patches: ${error}`);
5396
+ }
5397
+ }
5398
+ try {
5399
+ this.onUninstrument();
5400
+ } catch (error) {
5401
+ Logger.error(`${this.displayName}: onUninstrument failed: ${error}`);
5402
+ } finally {
5403
+ this._resolvedClasses = [];
5404
+ this._isInstrumented = false;
5405
+ }
5406
+ }
5407
+ async _doInstrument(options) {
5408
+ const gen = this._generation;
5409
+ const classSets = await this.resolveClasses();
5410
+ if (classSets.length === 0) {
5411
+ return this;
5412
+ }
5413
+ if (this._isInstrumented || this._generation !== gen) {
5414
+ return this;
5415
+ }
5416
+ try {
5417
+ this._tracerProvider = options.tracerProvider;
5418
+ this._tracer = this._tracerProvider ? this._tracerProvider.getTracer(
5419
+ this.instrumentationName,
5420
+ this.instrumentationVersion
5421
+ ) : trace.getTracer(
5422
+ this.instrumentationName,
5423
+ this.instrumentationVersion
5424
+ );
5425
+ } catch (error) {
5426
+ Logger.error(`${this.displayName}: failed to initialize tracer: ${error}`);
5427
+ return this;
5428
+ }
5429
+ let anyWrapped = false;
5430
+ for (const classes of classSets) {
5431
+ try {
5432
+ if (this.applyPatches(classes, this._tracer)) {
5433
+ anyWrapped = true;
5434
+ }
5435
+ } catch (error) {
5436
+ Logger.error(`${this.displayName}: patch failed: ${error}`);
5437
+ try {
5438
+ this.removePatches(classes);
5439
+ } catch {
5440
+ Logger.error(`${this.displayName}: failed to remove patches: ${error}`);
5441
+ }
5442
+ }
5443
+ }
5444
+ if (anyWrapped) {
5445
+ this._isInstrumented = true;
5446
+ }
5447
+ return this;
5448
+ }
5449
+ /**
5450
+ * Resolve the target package via ESM import() and CJS createRequire().
5451
+ * Override this for non-standard resolution strategies.
5452
+ */
5453
+ async resolveClasses() {
5454
+ if (this._resolvedClasses.length > 0) return this._resolvedClasses;
5455
+ try {
5456
+ const mod = await import(this.packageName);
5457
+ const classes = this.extractClasses(mod);
5458
+ if (classes) {
5459
+ this._resolvedClasses.push(classes);
5460
+ }
5461
+ } catch {
5462
+ Logger.debug(`${this.displayName}: ESM import not available`);
5463
+ }
5464
+ try {
5465
+ const req = createRequire(import.meta.url);
5466
+ const mod = req(this.packageName);
5467
+ const classes = this.extractClasses(mod);
5468
+ if (classes) {
5469
+ const isDuplicate = this._resolvedClasses.some(
5470
+ (existing) => this.isSameClasses(existing, classes)
5471
+ );
5472
+ if (!isDuplicate) {
5473
+ this._resolvedClasses.push(classes);
5474
+ }
5475
+ }
5476
+ } catch {
5477
+ Logger.debug(`${this.displayName}: CJS require not available`);
5478
+ }
5479
+ return this._resolvedClasses;
5480
+ }
5481
+ };
5327
5482
 
5328
5483
  // src/instrumentation/google-genai/version.ts
5329
5484
  var __version__2 = "1.0.0";
5330
- dotenv.config();
5331
- function safeStringify2(value) {
5485
+
5486
+ // src/instrumentation/google-genai/types.ts
5487
+ var SPAN_NAMES2 = {
5488
+ CHAT: "google_genai.chat",
5489
+ EMBEDDING: "google_genai.embedding"
5490
+ };
5491
+
5492
+ // src/instrumentation/google-genai/utils.ts
5493
+ var LOG_PREFIX = "netra.instrumentation.google_genai";
5494
+ function setRequestAttributes3(span2, params, requestType) {
5332
5495
  try {
5333
- if (typeof value === "string") return value;
5334
- return JSON.stringify(value);
5335
- } catch {
5336
- return String(value);
5496
+ if (!span2.isRecording()) return;
5497
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, requestType);
5498
+ span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
5499
+ if (params.model) {
5500
+ span2.setAttribute(
5501
+ SpanAttributes2.LLM_REQUEST_MODEL,
5502
+ extractModelName(String(params.model))
5503
+ );
5504
+ }
5505
+ const cfg = params.config ?? {};
5506
+ if (cfg.temperature !== void 0) {
5507
+ span2.setAttribute(
5508
+ SpanAttributes2.LLM_REQUEST_TEMPERATURE,
5509
+ Number(cfg.temperature)
5510
+ );
5511
+ }
5512
+ if (cfg.topP !== void 0) {
5513
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(cfg.topP));
5514
+ }
5515
+ if (cfg.topK !== void 0) {
5516
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_K, Number(cfg.topK));
5517
+ }
5518
+ if (cfg.maxOutputTokens !== void 0) {
5519
+ span2.setAttribute(
5520
+ SpanAttributes2.LLM_REQUEST_MAX_TOKENS,
5521
+ Number(cfg.maxOutputTokens)
5522
+ );
5523
+ }
5524
+ if (cfg.frequencyPenalty !== void 0) {
5525
+ span2.setAttribute(
5526
+ SpanAttributes2.LLM_FREQUENCY_PENALTY,
5527
+ Number(cfg.frequencyPenalty)
5528
+ );
5529
+ }
5530
+ if (cfg.presencePenalty !== void 0) {
5531
+ span2.setAttribute(
5532
+ SpanAttributes2.LLM_PRESENCE_PENALTY,
5533
+ Number(cfg.presencePenalty)
5534
+ );
5535
+ }
5536
+ if (cfg.stopSequences !== void 0) {
5537
+ span2.setAttribute(
5538
+ SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
5539
+ safeStringify(cfg.stopSequences)
5540
+ );
5541
+ }
5542
+ if (isTraceContentEnabled()) {
5543
+ const messages = buildGoogleInputMessages(params, cfg);
5544
+ writePromptAttributes(span2, messages);
5545
+ }
5546
+ } catch (e) {
5547
+ Logger.error(`${LOG_PREFIX}: setRequestAttributes error`, e);
5337
5548
  }
5338
5549
  }
5339
5550
  function extractModelName(model) {
5551
+ const MODEL_PREFIX = "models/";
5552
+ const TUNED_MODELS_PREFIX = "tunedModels/";
5553
+ const PUBLISHERS_PREFIX = "publishers/";
5554
+ const PROJECTS_PREFIX = "projects/";
5555
+ const MODELS_SEGMENT = "/models/";
5556
+ if (model.startsWith(MODEL_PREFIX)) return model.slice(MODEL_PREFIX.length);
5557
+ if (model.startsWith(TUNED_MODELS_PREFIX)) return model;
5558
+ const publisherIdx = model.indexOf(PUBLISHERS_PREFIX);
5559
+ if (publisherIdx !== -1) {
5560
+ const modelsIdx = model.indexOf(MODELS_SEGMENT, publisherIdx);
5561
+ if (modelsIdx !== -1) return model.slice(modelsIdx + MODELS_SEGMENT.length);
5562
+ }
5563
+ const slashIdx = model.indexOf("/");
5564
+ if (slashIdx !== -1 && !model.startsWith(PROJECTS_PREFIX)) {
5565
+ return model.slice(slashIdx + 1);
5566
+ }
5567
+ return model;
5568
+ }
5569
+ function buildGoogleInputMessages(params, cfg) {
5570
+ const messages = [];
5571
+ if (hasContent(cfg.systemInstruction)) {
5572
+ const sysContent = typeof cfg.systemInstruction === "string" ? cfg.systemInstruction : safeStringify(cfg.systemInstruction, Config.CONVERSATION_MAX_LEN);
5573
+ messages.push({ role: "system", content: sysContent });
5574
+ }
5575
+ const history = params._history;
5576
+ if (Array.isArray(history)) {
5577
+ for (const turn of history) {
5578
+ const role = normalizeRole(String(turn.role ?? "user"));
5579
+ const parts = turn.parts;
5580
+ if (Array.isArray(parts)) {
5581
+ const text = extractTextFromParts(parts);
5582
+ if (text) messages.push({ role, content: text });
5583
+ }
5584
+ }
5585
+ }
5586
+ const contents = params.contents ?? params.message;
5587
+ if (!hasContent(contents)) return messages;
5588
+ if (typeof contents === "string") {
5589
+ messages.push({ role: "user", content: contents });
5590
+ return messages;
5591
+ }
5592
+ if (Array.isArray(contents)) {
5593
+ for (const item of contents) {
5594
+ if (typeof item === "string") {
5595
+ messages.push({ role: "user", content: item });
5596
+ } else if (isDict(item) && item.role && Array.isArray(item.parts)) {
5597
+ const role = normalizeRole(String(item.role));
5598
+ const text = extractTextFromParts(item.parts);
5599
+ if (text) messages.push({ role, content: text });
5600
+ } else if (isDict(item) && item.text !== void 0) {
5601
+ messages.push({ role: "user", content: String(item.text) });
5602
+ } else {
5603
+ messages.push({
5604
+ role: "user",
5605
+ content: safeStringify(item, Config.CONVERSATION_MAX_LEN)
5606
+ });
5607
+ }
5608
+ }
5609
+ } else if (isDict(contents) && Array.isArray(contents.parts)) {
5610
+ const role = normalizeRole(String(contents.role ?? "user"));
5611
+ const text = extractTextFromParts(contents.parts);
5612
+ if (text) messages.push({ role, content: text });
5613
+ } else if (isDict(contents) && contents.text !== void 0) {
5614
+ messages.push({ role: "user", content: String(contents.text) });
5615
+ } else {
5616
+ messages.push({
5617
+ role: "user",
5618
+ content: safeStringify(contents, Config.CONVERSATION_MAX_LEN)
5619
+ });
5620
+ }
5621
+ return messages;
5622
+ }
5623
+ function normalizeRole(role) {
5624
+ if (role === "model") return "assistant";
5625
+ return role;
5626
+ }
5627
+ function extractTextFromParts(parts) {
5628
+ const texts = [];
5629
+ for (const part of parts) {
5630
+ if (!isDict(part)) continue;
5631
+ if (typeof part.text === "string") {
5632
+ texts.push(part.text);
5633
+ } else if (part.functionCall) {
5634
+ texts.push(safeStringify(part.functionCall, Config.CONVERSATION_MAX_LEN));
5635
+ } else if (part.functionResponse) {
5636
+ texts.push(
5637
+ safeStringify(part.functionResponse, Config.CONVERSATION_MAX_LEN)
5638
+ );
5639
+ }
5640
+ }
5641
+ return texts.join("");
5642
+ }
5643
+ function setResponseAttributes3(span2, response) {
5644
+ try {
5645
+ if (!span2.isRecording()) return;
5646
+ if (response.responseId) {
5647
+ span2.setAttribute("llm.response.id", String(response.responseId));
5648
+ }
5649
+ if (response.modelVersion) {
5650
+ span2.setAttribute(
5651
+ SpanAttributes2.LLM_RESPONSE_MODEL,
5652
+ String(response.modelVersion)
5653
+ );
5654
+ }
5655
+ setUsageAttributes2(span2, response);
5656
+ setFinishReason2(span2, response);
5657
+ setEmbeddingMeta(span2, response);
5658
+ if (isTraceContentEnabled()) {
5659
+ const messages = buildGoogleOutputMessages(response);
5660
+ writeCompletionAttributes(span2, messages);
5661
+ }
5662
+ } catch (e) {
5663
+ Logger.error(`${LOG_PREFIX}: setResponseAttributes error`, e);
5664
+ }
5665
+ }
5666
+ function setUsageAttributes2(span2, response) {
5667
+ const usage = response.usageMetadata;
5668
+ if (!usage) return;
5669
+ if (usage.promptTokenCount !== void 0) {
5670
+ span2.setAttribute(
5671
+ SpanAttributes2.LLM_USAGE_PROMPT_TOKENS,
5672
+ Number(usage.promptTokenCount)
5673
+ );
5674
+ }
5675
+ if (usage.candidatesTokenCount !== void 0) {
5676
+ span2.setAttribute(
5677
+ SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS,
5678
+ Number(usage.candidatesTokenCount)
5679
+ );
5680
+ }
5681
+ if (usage.totalTokenCount !== void 0) {
5682
+ span2.setAttribute(
5683
+ SpanAttributes2.LLM_USAGE_TOTAL_TOKENS,
5684
+ Number(usage.totalTokenCount)
5685
+ );
5686
+ }
5687
+ if (usage.cachedContentTokenCount !== void 0) {
5688
+ span2.setAttribute(
5689
+ SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS,
5690
+ Number(usage.cachedContentTokenCount)
5691
+ );
5692
+ }
5693
+ if (usage.thoughtsTokenCount !== void 0) {
5694
+ span2.setAttribute(
5695
+ SpanAttributes2.LLM_USAGE_REASONING_TOKENS,
5696
+ Number(usage.thoughtsTokenCount)
5697
+ );
5698
+ }
5699
+ }
5700
+ function setFinishReason2(span2, response) {
5701
+ const candidates = response.candidates;
5702
+ if (!Array.isArray(candidates) || candidates.length === 0) return;
5703
+ const reason = candidates[0].finishReason;
5704
+ if (reason) {
5705
+ span2.setAttribute(
5706
+ SpanAttributes2.LLM_RESPONSE_FINISH_REASON,
5707
+ String(reason)
5708
+ );
5709
+ span2.setAttribute("gen_ai.response.finish_reason", String(reason));
5710
+ }
5711
+ }
5712
+ function setEmbeddingMeta(span2, response) {
5713
+ const singleEmbed = response.embedding;
5714
+ if (singleEmbed?.values !== void 0) {
5715
+ const values2 = singleEmbed.values;
5716
+ span2.setAttribute("gen_ai.response.embedding_dimensions", values2.length);
5717
+ const stats = singleEmbed.statistics;
5718
+ if (stats?.tokenCount !== void 0) {
5719
+ const tokenCount = Number(stats.tokenCount);
5720
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, tokenCount);
5721
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, tokenCount);
5722
+ }
5723
+ return;
5724
+ }
5725
+ const embeddings = response.embeddings;
5726
+ if (!Array.isArray(embeddings) || embeddings.length === 0) return;
5727
+ span2.setAttribute("gen_ai.response.embedding_count", embeddings.length);
5728
+ const first = embeddings[0];
5729
+ const values = first?.values;
5730
+ if (Array.isArray(values)) {
5731
+ span2.setAttribute("gen_ai.response.embedding_dimensions", values.length);
5732
+ }
5733
+ let totalTokens = 0;
5734
+ let hasTokenCount = false;
5735
+ for (const emb of embeddings) {
5736
+ const stats = emb.statistics;
5737
+ if (stats?.tokenCount !== void 0) {
5738
+ totalTokens += Number(stats.tokenCount);
5739
+ hasTokenCount = true;
5740
+ }
5741
+ }
5742
+ if (hasTokenCount) {
5743
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, totalTokens);
5744
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, totalTokens);
5745
+ }
5746
+ }
5747
+ function buildGoogleOutputMessages(response) {
5748
+ const messages = [];
5749
+ const text = response.text;
5750
+ if (typeof text === "string" && text.length > 0) {
5751
+ messages.push({ role: "assistant", content: text });
5752
+ }
5753
+ const functionCalls = response.functionCalls;
5754
+ if (Array.isArray(functionCalls)) {
5755
+ for (const fc of functionCalls) {
5756
+ messages.push({
5757
+ role: "tool",
5758
+ content: safeStringify(
5759
+ { name: fc.name, arguments: fc.args },
5760
+ Config.CONVERSATION_MAX_LEN
5761
+ )
5762
+ });
5763
+ }
5764
+ }
5765
+ if (messages.length === 0) {
5766
+ const candidates = response.candidates;
5767
+ if (Array.isArray(candidates)) {
5768
+ for (const candidate of candidates) {
5769
+ const content = candidate.content;
5770
+ if (!content || !Array.isArray(content.parts)) continue;
5771
+ for (const part of content.parts) {
5772
+ if (typeof part.text === "string" && part.text.length > 0) {
5773
+ messages.push({ role: "assistant", content: part.text });
5774
+ }
5775
+ if (part.functionCall && isDict(part.functionCall)) {
5776
+ const fc = part.functionCall;
5777
+ messages.push({
5778
+ role: "tool",
5779
+ content: safeStringify(
5780
+ { name: fc.name, arguments: fc.args },
5781
+ Config.CONVERSATION_MAX_LEN
5782
+ )
5783
+ });
5784
+ }
5785
+ }
5786
+ }
5787
+ }
5788
+ }
5789
+ if (messages.length === 0) {
5790
+ const singleEmbed = response.embedding;
5791
+ if (singleEmbed?.values !== void 0) {
5792
+ const values = singleEmbed.values;
5793
+ messages.push({
5794
+ role: "assistant",
5795
+ content: safeStringify({
5796
+ dimensions: values.length,
5797
+ preview: values.slice(0, 5)
5798
+ })
5799
+ });
5800
+ }
5801
+ const embeddings = response.embeddings;
5802
+ if (Array.isArray(embeddings) && embeddings.length > 0) {
5803
+ for (let i = 0; i < embeddings.length; i++) {
5804
+ const values = embeddings[i]?.values ?? [];
5805
+ messages.push({
5806
+ role: "assistant",
5807
+ content: safeStringify({
5808
+ index: i,
5809
+ dimensions: values.length,
5810
+ preview: values.slice(0, 5)
5811
+ })
5812
+ });
5813
+ }
5814
+ }
5815
+ }
5816
+ return messages;
5817
+ }
5818
+ function processStreamChunk2(accumulated, chunk, span2, startTime) {
5819
+ try {
5820
+ if (chunk.modelVersion) {
5821
+ accumulated.modelVersion = chunk.modelVersion;
5822
+ }
5823
+ if (chunk.responseId) {
5824
+ accumulated.responseId = chunk.responseId;
5825
+ }
5826
+ const chunkText = typeof chunk.text === "string" ? chunk.text : void 0;
5827
+ if (chunkText && chunkText.length > 0) {
5828
+ if (!accumulated._text) {
5829
+ accumulated._text = chunkText;
5830
+ span2.setAttribute(
5831
+ "gen_ai.performance.time_to_first_token",
5832
+ (Date.now() - startTime) / 1e3
5833
+ );
5834
+ } else {
5835
+ accumulated._text += chunkText;
5836
+ }
5837
+ }
5838
+ const fcs = chunk.functionCalls;
5839
+ if (Array.isArray(fcs) && fcs.length > 0) {
5840
+ if (!accumulated._functionCalls) accumulated._functionCalls = [];
5841
+ accumulated._functionCalls.push(...fcs);
5842
+ }
5843
+ if (chunk.usageMetadata) {
5844
+ accumulated.usageMetadata = chunk.usageMetadata;
5845
+ }
5846
+ if (Array.isArray(chunk.candidates) && chunk.candidates.length > 0) {
5847
+ const reason = chunk.candidates[0]?.finishReason;
5848
+ if (reason) {
5849
+ if (!accumulated.candidates) accumulated.candidates = [{}];
5850
+ accumulated.candidates[0].finishReason = reason;
5851
+ }
5852
+ }
5853
+ if (Logger.isDebugMode()) {
5854
+ span2.addEvent("llm.content.completion.chunk");
5855
+ }
5856
+ } catch (e) {
5857
+ Logger.error(`${LOG_PREFIX}: processStreamChunk error`, e);
5858
+ }
5859
+ }
5860
+ function buildAccumulatedResponse(accumulated) {
5861
+ const response = {
5862
+ responseId: accumulated.responseId,
5863
+ modelVersion: accumulated.modelVersion,
5864
+ usageMetadata: accumulated.usageMetadata,
5865
+ candidates: accumulated.candidates
5866
+ };
5867
+ if (accumulated._text) {
5868
+ response.text = accumulated._text;
5869
+ }
5870
+ if (accumulated._functionCalls) {
5871
+ response.functionCalls = accumulated._functionCalls;
5872
+ }
5873
+ return response;
5874
+ }
5875
+
5876
+ // src/instrumentation/google-genai/wrappers.ts
5877
+ var LOG_PREFIX2 = "netra.instrumentation.google_genai";
5878
+ function buildParams(args, self) {
5879
+ const raw = args[0];
5880
+ const params = typeof raw === "object" && raw !== null ? { ...raw } : { message: raw };
5881
+ if (!params.model && self.model) {
5882
+ params.model = self.model;
5883
+ }
5884
+ if (!params.config && self.config) {
5885
+ params.config = self.config;
5886
+ }
5887
+ try {
5888
+ const history = typeof self.getHistory === "function" ? self.getHistory(true) : self.history;
5889
+ if (Array.isArray(history)) {
5890
+ params._history = history;
5891
+ }
5892
+ } catch {
5893
+ }
5894
+ return params;
5895
+ }
5896
+ function genericWrapperFactory(tracer, spanName, requestType) {
5897
+ return function wrapper(original) {
5898
+ return function(...args) {
5899
+ if (shouldSuppressInstrumentation()) {
5900
+ return original.apply(this, args);
5901
+ }
5902
+ const self = this;
5903
+ const params = buildParams(args, self);
5904
+ const currentContext = context.active();
5905
+ return tracer.startActiveSpan(
5906
+ spanName,
5907
+ { kind: SpanKind.CLIENT },
5908
+ (span2) => {
5909
+ try {
5910
+ setRequestAttributes3(span2, params, requestType);
5911
+ const startTime = Date.now();
5912
+ const spanContext = trace.setSpan(currentContext, span2);
5913
+ const suppressedCtx = createSuppressedContext(spanContext);
5914
+ const response = context.with(
5915
+ suppressedCtx,
5916
+ () => original.apply(this, args)
5917
+ );
5918
+ return wrapResponse(
5919
+ response,
5920
+ {
5921
+ withContext: (fn) => context.with(spanContext, fn),
5922
+ onSuccess: (value) => {
5923
+ const endTime = Date.now();
5924
+ const responseDict = modelAsDict(value);
5925
+ if (typeof value?.text === "string") {
5926
+ responseDict.text = value.text;
5927
+ }
5928
+ if (Array.isArray(value?.functionCalls)) {
5929
+ responseDict.functionCalls = value.functionCalls;
5930
+ }
5931
+ setResponseAttributes3(span2, responseDict);
5932
+ span2.setAttribute(
5933
+ SpanAttributes2.LLM_RESPONSE_DURATION,
5934
+ (endTime - startTime) / 1e3
5935
+ );
5936
+ },
5937
+ onError: (error) => {
5938
+ span2.setStatus({
5939
+ code: SpanStatusCode.ERROR,
5940
+ message: error instanceof Error ? error.message : String(error)
5941
+ });
5942
+ span2.recordException(error);
5943
+ },
5944
+ finalize: (status) => {
5945
+ if (status === "ok") {
5946
+ span2.setStatus({ code: SpanStatusCode.OK });
5947
+ }
5948
+ span2.end();
5949
+ }
5950
+ },
5951
+ { preserveOriginal: response }
5952
+ );
5953
+ } catch (error) {
5954
+ span2.setStatus({
5955
+ code: SpanStatusCode.ERROR,
5956
+ message: error instanceof Error ? error.message : String(error)
5957
+ });
5958
+ span2.recordException(error);
5959
+ span2.end();
5960
+ throw error;
5961
+ }
5962
+ }
5963
+ );
5964
+ };
5965
+ };
5966
+ }
5967
+ function streamWrapperFactory(tracer, spanName, requestType) {
5968
+ return function wrapper(original) {
5969
+ return function(...args) {
5970
+ if (shouldSuppressInstrumentation()) {
5971
+ return original.apply(this, args);
5972
+ }
5973
+ const self = this;
5974
+ const params = buildParams(args, self);
5975
+ const currentContext = context.active();
5976
+ return tracer.startActiveSpan(
5977
+ spanName,
5978
+ {
5979
+ kind: SpanKind.CLIENT,
5980
+ attributes: { [SpanAttributes2.LLM_IS_STREAMING]: true }
5981
+ },
5982
+ (span2) => {
5983
+ const startTime = Date.now();
5984
+ const accumulated = {};
5985
+ try {
5986
+ setRequestAttributes3(span2, params, requestType);
5987
+ const spanContext = trace.setSpan(currentContext, span2);
5988
+ const suppressedCtx = createSuppressedContext(spanContext);
5989
+ const response = context.with(
5990
+ suppressedCtx,
5991
+ () => original.apply(this, args)
5992
+ );
5993
+ return wrapResponse(
5994
+ response,
5995
+ {
5996
+ withContext: (fn) => context.with(spanContext, fn),
5997
+ onChunk: (chunk) => {
5998
+ processStreamChunk2(accumulated, chunk, span2, startTime);
5999
+ },
6000
+ onError: (error) => {
6001
+ span2.setStatus({
6002
+ code: SpanStatusCode.ERROR,
6003
+ message: error instanceof Error ? error.message : String(error)
6004
+ });
6005
+ span2.recordException(error);
6006
+ },
6007
+ finalize: (status) => {
6008
+ try {
6009
+ const endTime = Date.now();
6010
+ const syntheticResponse = buildAccumulatedResponse(accumulated);
6011
+ setResponseAttributes3(span2, syntheticResponse);
6012
+ span2.setAttribute(
6013
+ SpanAttributes2.LLM_RESPONSE_DURATION,
6014
+ (endTime - startTime) / 1e3
6015
+ );
6016
+ } catch (e) {
6017
+ Logger.error(`${LOG_PREFIX2}: stream finalize error`, e);
6018
+ }
6019
+ if (status === "ok") {
6020
+ span2.setStatus({ code: SpanStatusCode.OK });
6021
+ }
6022
+ span2.end();
6023
+ }
6024
+ },
6025
+ { preserveOriginal: response }
6026
+ );
6027
+ } catch (error) {
6028
+ span2.setStatus({
6029
+ code: SpanStatusCode.ERROR,
6030
+ message: error instanceof Error ? error.message : String(error)
6031
+ });
6032
+ span2.recordException(error);
6033
+ span2.end();
6034
+ throw error;
6035
+ }
6036
+ }
6037
+ );
6038
+ };
6039
+ };
6040
+ }
6041
+ var chatWrapper2 = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
6042
+ var chatStreamWrapper2 = (tracer) => streamWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
6043
+ var embeddingsWrapper = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.EMBEDDING, "embedding");
6044
+
6045
+ // src/instrumentation/google-genai/index.ts
6046
+ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
6047
+ constructor() {
6048
+ super(...arguments);
6049
+ this.instrumentationName = "netra.instrumentation.google_genai";
6050
+ this.instrumentationVersion = __version__2;
6051
+ this.packageName = "@google/genai";
6052
+ this.displayName = "Google GenAI";
6053
+ }
6054
+ extractClasses(mod) {
6055
+ const root = mod.default ?? mod;
6056
+ if (!root.Models) return null;
6057
+ return { Models: root.Models, Chat: root.Chat };
6058
+ }
6059
+ isSameClasses(a, b) {
6060
+ return a.Models === b.Models;
6061
+ }
6062
+ applyPatches(classes, tracer) {
6063
+ const modelsProto = classes.Models?.prototype;
6064
+ if (!modelsProto) {
6065
+ Logger.error("Google GenAI: Models.prototype not found");
6066
+ return false;
6067
+ }
6068
+ let wrapped = false;
6069
+ if (typeof modelsProto.generateContentInternal === "function") {
6070
+ shimmer.wrap(modelsProto, "generateContentInternal", chatWrapper2(tracer));
6071
+ wrapped = true;
6072
+ }
6073
+ if (typeof modelsProto.generateContentStreamInternal === "function") {
6074
+ shimmer.wrap(modelsProto, "generateContentStreamInternal", chatStreamWrapper2(tracer));
6075
+ wrapped = true;
6076
+ }
6077
+ if (typeof modelsProto.embedContentInternal === "function") {
6078
+ shimmer.wrap(modelsProto, "embedContentInternal", embeddingsWrapper(tracer));
6079
+ wrapped = true;
6080
+ }
6081
+ const chatProto = classes.Chat?.prototype;
6082
+ if (chatProto) {
6083
+ if (typeof chatProto.sendMessage === "function") {
6084
+ shimmer.wrap(chatProto, "sendMessage", chatWrapper2(tracer));
6085
+ wrapped = true;
6086
+ }
6087
+ if (typeof chatProto.sendMessageStream === "function") {
6088
+ shimmer.wrap(chatProto, "sendMessageStream", chatStreamWrapper2(tracer));
6089
+ wrapped = true;
6090
+ }
6091
+ }
6092
+ return wrapped;
6093
+ }
6094
+ removePatches(classes) {
6095
+ const modelsProto = classes.Models?.prototype;
6096
+ if (modelsProto) {
6097
+ if (typeof modelsProto.generateContentInternal === "function")
6098
+ shimmer.unwrap(modelsProto, "generateContentInternal");
6099
+ if (typeof modelsProto.generateContentStreamInternal === "function")
6100
+ shimmer.unwrap(modelsProto, "generateContentStreamInternal");
6101
+ if (typeof modelsProto.embedContentInternal === "function")
6102
+ shimmer.unwrap(modelsProto, "embedContentInternal");
6103
+ }
6104
+ const chatProto = classes.Chat?.prototype;
6105
+ if (chatProto) {
6106
+ if (typeof chatProto.sendMessage === "function")
6107
+ shimmer.unwrap(chatProto, "sendMessage");
6108
+ if (typeof chatProto.sendMessageStream === "function")
6109
+ shimmer.unwrap(chatProto, "sendMessageStream");
6110
+ }
6111
+ }
6112
+ };
6113
+ var googleGenAIInstrumentor = new NetraGoogleGenAIInstrumentor();
6114
+
6115
+ // src/instrumentation/google-generative-ai/version.ts
6116
+ var __version__3 = "1.0.0";
6117
+
6118
+ // src/instrumentation/google-generative-ai/utils.ts
6119
+ function extractModelName2(model) {
5340
6120
  if (model && model.startsWith("models/")) {
5341
6121
  return model.replace(/^models\//, "");
5342
6122
  }
5343
6123
  return model;
5344
6124
  }
5345
- function normalizeGenAIRole(raw) {
6125
+ function normalizeGenerativeAIRole(raw) {
5346
6126
  const rawLower = raw.toLowerCase();
5347
6127
  return rawLower === "model" ? "assistant" : rawLower;
5348
6128
  }
5349
- function setRequestAttributes3(span2, kwargs, requestType, args) {
6129
+ function setRequestAttributes4(span2, kwargs, requestType, args) {
5350
6130
  span2._netra_kwargs = kwargs;
5351
6131
  if (!span2.isRecording()) {
5352
6132
  return;
5353
6133
  }
5354
6134
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, requestType);
5355
- span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
6135
+ span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_generative_ai");
5356
6136
  if (kwargs.model !== void 0) {
5357
6137
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_MODEL, String(kwargs.model));
5358
6138
  }
@@ -5381,7 +6161,7 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
5381
6161
  if (generationConfig.stopSequences !== void 0) {
5382
6162
  span2.setAttribute(
5383
6163
  SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
5384
- safeStringify2(generationConfig.stopSequences)
6164
+ safeStringify(generationConfig.stopSequences)
5385
6165
  );
5386
6166
  }
5387
6167
  if (generationConfig.candidateCount !== void 0) {
@@ -5411,7 +6191,7 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
5411
6191
  if (kwargs.toolConfig !== void 0) {
5412
6192
  span2.setAttribute(
5413
6193
  "gen_ai.request.tool_config",
5414
- safeStringify2(kwargs.toolConfig)
6194
+ safeStringify(kwargs.toolConfig)
5415
6195
  );
5416
6196
  }
5417
6197
  if (Array.isArray(kwargs.safetySettings) && kwargs.safetySettings.length > 0) {
@@ -5421,22 +6201,18 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
5421
6201
  );
5422
6202
  }
5423
6203
  if (kwargs.systemInstruction !== void 0) {
5424
- if (isTraceContentEnabled2()) {
6204
+ if (isTraceContentEnabled()) {
5425
6205
  span2.setAttribute(
5426
6206
  "gen_ai.request.system_instruction",
5427
- safeStringify2(kwargs.systemInstruction)
6207
+ safeStringify(kwargs.systemInstruction)
5428
6208
  );
5429
6209
  }
5430
6210
  span2.setAttribute("gen_ai.request.has_system_instruction", true);
5431
6211
  }
5432
- if (isTraceContentEnabled2()) {
6212
+ if (isTraceContentEnabled()) {
5433
6213
  _setPromptAttributes(span2, kwargs, args);
5434
6214
  }
5435
6215
  }
5436
- function isTraceContentEnabled2() {
5437
- const raw = process.env.TRACELOOP_TRACE_CONTENT ?? process.env.NETRA_TRACE_CONTENT ?? "";
5438
- return ["1", "true"].includes(String(raw).toLowerCase());
5439
- }
5440
6216
  function _setPromptAttributes(span2, kwargs, args) {
5441
6217
  let promptIndex = 0;
5442
6218
  if (kwargs.systemInstruction !== void 0) {
@@ -5449,7 +6225,7 @@ function _setPromptAttributes(span2, kwargs, args) {
5449
6225
  } else if (systemInstruction.text) {
5450
6226
  systemContent = String(systemInstruction.text);
5451
6227
  } else {
5452
- systemContent = JSON.stringify(systemInstruction);
6228
+ systemContent = safeStringify(systemInstruction);
5453
6229
  }
5454
6230
  if (systemContent) {
5455
6231
  span2.setAttribute(
@@ -5465,7 +6241,7 @@ function _setPromptAttributes(span2, kwargs, args) {
5465
6241
  }
5466
6242
  if (kwargs.history && Array.isArray(kwargs.history)) {
5467
6243
  for (const turn of kwargs.history) {
5468
- const role = normalizeGenAIRole(String(turn.role ?? "user"));
6244
+ const role = normalizeGenerativeAIRole(String(turn.role ?? "user"));
5469
6245
  const parts = turn.parts;
5470
6246
  if (Array.isArray(parts)) {
5471
6247
  const textContent = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
@@ -5518,29 +6294,32 @@ function _setPromptAttributes(span2, kwargs, args) {
5518
6294
  const contents = args.contents;
5519
6295
  if (Array.isArray(contents)) {
5520
6296
  for (const content of contents) {
5521
- const role = String(content.role ?? "user");
6297
+ const role = normalizeGenerativeAIRole(String(content.role ?? "user"));
5522
6298
  const parts = content.parts;
5523
6299
  if (Array.isArray(parts)) {
5524
6300
  const textParts = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
5525
- if (textParts) {
6301
+ const inlineDataParts = parts.filter((p) => p.inlineData !== void 0);
6302
+ const slotIndex = promptIndex;
6303
+ if (textParts || inlineDataParts.length > 0) {
5526
6304
  span2.setAttribute(
5527
- `${SpanAttributes2.LLM_PROMPTS}.${promptIndex}.role`,
6305
+ `${SpanAttributes2.LLM_PROMPTS}.${slotIndex}.role`,
5528
6306
  role
5529
6307
  );
5530
- span2.setAttribute(
5531
- `${SpanAttributes2.LLM_PROMPTS}.${promptIndex}.content`,
5532
- textParts
5533
- );
6308
+ if (textParts) {
6309
+ span2.setAttribute(
6310
+ `${SpanAttributes2.LLM_PROMPTS}.${slotIndex}.content`,
6311
+ textParts
6312
+ );
6313
+ }
5534
6314
  promptIndex++;
5535
6315
  }
5536
- const inlineDataParts = parts.filter((p) => p.inlineData !== void 0);
5537
6316
  if (inlineDataParts.length > 0) {
5538
6317
  span2.setAttribute(
5539
- `gen_ai.prompt.${promptIndex - 1}.has_inline_data`,
6318
+ `gen_ai.prompt.${slotIndex}.has_inline_data`,
5540
6319
  true
5541
6320
  );
5542
6321
  span2.setAttribute(
5543
- `gen_ai.prompt.${promptIndex - 1}.inline_data_count`,
6322
+ `gen_ai.prompt.${slotIndex}.inline_data_count`,
5544
6323
  inlineDataParts.length
5545
6324
  );
5546
6325
  }
@@ -5568,15 +6347,18 @@ function _setPromptAttributes(span2, kwargs, args) {
5568
6347
  }
5569
6348
  }
5570
6349
  }
5571
- function setResponseAttributes3(span2, response) {
6350
+ function setResponseAttributes4(span2, response) {
5572
6351
  if (!span2.isRecording()) {
5573
6352
  return;
5574
6353
  }
5575
6354
  const actualResponse = response.response ?? response;
5576
6355
  _setUsageAttributes(span2, actualResponse);
6356
+ if (!actualResponse.usageMetadata && response.usageMetadata) {
6357
+ _setUsageAttributes(span2, response);
6358
+ }
5577
6359
  _setCandidateAttributes(span2, actualResponse);
5578
6360
  _setPromptFeedbackAttributes(span2, actualResponse);
5579
- if (isTraceContentEnabled2()) {
6361
+ if (isTraceContentEnabled()) {
5580
6362
  _setCompletionAttributes(span2, actualResponse);
5581
6363
  }
5582
6364
  _setEmbeddingResponseAttributes(span2, actualResponse);
@@ -5687,7 +6469,7 @@ function _setCompletionAttributes(span2, response) {
5687
6469
  const candidate = candidates[i];
5688
6470
  const content = candidate.content;
5689
6471
  if (!content) continue;
5690
- const role = normalizeGenAIRole(String(content.role ?? "model"));
6472
+ const role = normalizeGenerativeAIRole(String(content.role ?? "model"));
5691
6473
  const parts = content.parts;
5692
6474
  if (!Array.isArray(parts)) continue;
5693
6475
  const textContent = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
@@ -5732,29 +6514,39 @@ function _setEmbeddingResponseAttributes(span2, response) {
5732
6514
  }
5733
6515
  }
5734
6516
 
5735
- // src/instrumentation/google-genai/wrappers.ts
5736
- var CHAT_SPAN_NAME = "google_genai.chat";
5737
- var EMBEDDING_SPAN_NAME = "google_genai.embedding";
5738
- function googleGenAIWrapper(tracer, spanName, requestType) {
6517
+ // src/instrumentation/google-generative-ai/wrappers.ts
6518
+ var LOG_PREFIX3 = "netra.instrumentation.google_generative_ai";
6519
+ var CHAT_SPAN_NAME = "google_generative_ai.chat";
6520
+ var EMBEDDING_SPAN_NAME = "google_generative_ai.embedding";
6521
+ function buildKwargs(instance) {
6522
+ const kwargs = {};
6523
+ const params = instance.params;
6524
+ const modelName = instance.model;
6525
+ if (modelName) {
6526
+ kwargs.model = extractModelName2(modelName);
6527
+ }
6528
+ const systemInstruction = instance.systemInstruction ?? params?.systemInstruction;
6529
+ if (systemInstruction) kwargs.systemInstruction = systemInstruction;
6530
+ const history = instance._history ?? instance.history;
6531
+ if (history) kwargs.history = history;
6532
+ const generationConfig = instance.generationConfig ?? params?.generationConfig;
6533
+ if (generationConfig) kwargs.generationConfig = generationConfig;
6534
+ const safetySettings = instance.safetySettings ?? params?.safetySettings;
6535
+ if (safetySettings) kwargs.safetySettings = safetySettings;
6536
+ const tools = instance.tools ?? params?.tools;
6537
+ if (tools) kwargs.tools = tools;
6538
+ const toolConfig = instance.toolConfig ?? params?.toolConfig;
6539
+ if (toolConfig) kwargs.toolConfig = toolConfig;
6540
+ return kwargs;
6541
+ }
6542
+ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
5739
6543
  return function wrapper(original) {
5740
6544
  return function(...args) {
5741
6545
  if (shouldSuppressInstrumentation()) {
5742
6546
  return original.apply(this, args);
5743
6547
  }
5744
- let kwargs = {};
5745
6548
  const modelInstance = this;
5746
- const modelName = modelInstance.model;
5747
- const systemInstruction = modelInstance.systemInstruction;
5748
- const history = modelInstance.history;
5749
- if (modelName) {
5750
- kwargs.model = extractModelName(modelName);
5751
- }
5752
- if (systemInstruction) {
5753
- kwargs.systemInstruction = systemInstruction;
5754
- }
5755
- if (history) {
5756
- kwargs.history = history;
5757
- }
6549
+ const kwargs = buildKwargs(modelInstance);
5758
6550
  const currentContext = context.active();
5759
6551
  return tracer.startActiveSpan(
5760
6552
  spanName,
@@ -5765,27 +6557,36 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
5765
6557
  currentContext,
5766
6558
  (span2) => {
5767
6559
  try {
5768
- setRequestAttributes3(span2, kwargs, requestType, args[0]);
6560
+ try {
6561
+ setRequestAttributes4(span2, kwargs, requestType, args[0]);
6562
+ } catch (e) {
6563
+ Logger.error(`${LOG_PREFIX3}:`, e);
6564
+ }
5769
6565
  const startTime = Date.now();
5770
6566
  const response = original.apply(this, args);
5771
6567
  if (isPromise(response)) {
5772
6568
  return (async () => {
5773
6569
  try {
5774
6570
  const value = await response;
5775
- const endTime = Date.now();
5776
- const responseDict = modelAsDict(value);
5777
- setResponseAttributes3(span2, responseDict);
5778
- const duration = (endTime - startTime) / 1e3;
5779
- span2.setAttribute("llm.response.duration", duration);
5780
- span2.setAttribute(
5781
- "gen_ai.performance.time_to_first_token",
5782
- duration
5783
- );
6571
+ try {
6572
+ const endTime = Date.now();
6573
+ const responseDict = modelAsDict(value);
6574
+ setResponseAttributes4(span2, responseDict);
6575
+ const duration = (endTime - startTime) / 1e3;
6576
+ span2.setAttribute("llm.response.duration", duration);
6577
+ if (requestType !== "embedding") {
6578
+ span2.setAttribute(
6579
+ "gen_ai.performance.time_to_first_token",
6580
+ duration
6581
+ );
6582
+ }
6583
+ } catch (e) {
6584
+ Logger.error(`${LOG_PREFIX3}:`, e);
6585
+ }
5784
6586
  span2.setStatus({ code: SpanStatusCode.OK });
5785
6587
  span2.end();
5786
6588
  return value;
5787
6589
  } catch (error) {
5788
- Logger.error("netra.instrumentation.google-genai:", error);
5789
6590
  span2.setStatus({
5790
6591
  code: SpanStatusCode.ERROR,
5791
6592
  message: error instanceof Error ? error.message : String(error)
@@ -5796,19 +6597,22 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
5796
6597
  }
5797
6598
  })();
5798
6599
  } else {
5799
- const endTime = Date.now();
5800
- const responseDict = modelAsDict(response);
5801
- setResponseAttributes3(span2, responseDict);
5802
- span2.setAttribute(
5803
- "llm.response.duration",
5804
- (endTime - startTime) / 1e3
5805
- );
6600
+ try {
6601
+ const endTime = Date.now();
6602
+ const responseDict = modelAsDict(response);
6603
+ setResponseAttributes4(span2, responseDict);
6604
+ span2.setAttribute(
6605
+ "llm.response.duration",
6606
+ (endTime - startTime) / 1e3
6607
+ );
6608
+ } catch (e) {
6609
+ Logger.error(`${LOG_PREFIX3}:`, e);
6610
+ }
5806
6611
  span2.setStatus({ code: SpanStatusCode.OK });
5807
6612
  span2.end();
5808
6613
  return response;
5809
6614
  }
5810
6615
  } catch (error) {
5811
- Logger.error("netra.instrumentation.google-genai:", error);
5812
6616
  span2.setStatus({
5813
6617
  code: SpanStatusCode.ERROR,
5814
6618
  message: error instanceof Error ? error.message : String(error)
@@ -5822,20 +6626,14 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
5822
6626
  };
5823
6627
  };
5824
6628
  }
5825
- function googleGenAIStreamWrapper(tracer, spanName, requestType) {
6629
+ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
5826
6630
  return function wrapper(original) {
5827
6631
  return function(...args) {
5828
6632
  if (shouldSuppressInstrumentation()) {
5829
6633
  return original.apply(this, args);
5830
6634
  }
5831
- let kwargs = {};
5832
6635
  const modelInstance = this;
5833
- const modelName = modelInstance.model;
5834
- const systemInstruction = modelInstance.systemInstruction;
5835
- const history = modelInstance.history;
5836
- if (modelName) kwargs.model = extractModelName(modelName);
5837
- if (systemInstruction) kwargs.systemInstruction = systemInstruction;
5838
- if (history) kwargs.history = history;
6636
+ const kwargs = buildKwargs(modelInstance);
5839
6637
  const currentContext = context.active();
5840
6638
  return tracer.startActiveSpan(
5841
6639
  spanName,
@@ -5847,7 +6645,11 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5847
6645
  (span2) => {
5848
6646
  const startTime = Date.now();
5849
6647
  try {
5850
- setRequestAttributes3(span2, kwargs, requestType, args[0]);
6648
+ try {
6649
+ setRequestAttributes4(span2, kwargs, requestType, args[0]);
6650
+ } catch (e) {
6651
+ Logger.error(`${LOG_PREFIX3}:`, e);
6652
+ }
5851
6653
  const response = original.apply(this, args);
5852
6654
  if (!isPromise(response)) {
5853
6655
  span2.setStatus({ code: SpanStatusCode.OK });
@@ -5859,21 +6661,23 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5859
6661
  const streamResult = await response;
5860
6662
  const originalStream = streamResult.stream;
5861
6663
  if (!originalStream || typeof originalStream[Symbol.asyncIterator] !== "function") {
5862
- const endTime = Date.now();
5863
- const responseDict = modelAsDict(streamResult);
5864
- setResponseAttributes3(span2, responseDict);
5865
- const duration = (endTime - startTime) / 1e3;
5866
- span2.setAttribute("llm.response.duration", duration);
5867
- span2.setAttribute(
5868
- "gen_ai.performance.time_to_first_token",
5869
- duration
5870
- );
6664
+ try {
6665
+ const endTime = Date.now();
6666
+ const responseDict = modelAsDict(streamResult);
6667
+ setResponseAttributes4(span2, responseDict);
6668
+ const duration = (endTime - startTime) / 1e3;
6669
+ span2.setAttribute("llm.response.duration", duration);
6670
+ span2.setAttribute(
6671
+ "gen_ai.performance.time_to_first_token",
6672
+ duration
6673
+ );
6674
+ } catch (e) {
6675
+ Logger.error(`${LOG_PREFIX3}:`, e);
6676
+ }
5871
6677
  span2.setStatus({ code: SpanStatusCode.OK });
5872
6678
  span2.end();
5873
6679
  return streamResult;
5874
6680
  }
5875
- let chunkIndex = 0;
5876
- let finalText = "";
5877
6681
  let firstTokenRecorded = false;
5878
6682
  const wrappedStream = {
5879
6683
  [Symbol.asyncIterator]() {
@@ -5883,25 +6687,29 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5883
6687
  try {
5884
6688
  const res = await iterator.next();
5885
6689
  if (res?.done) {
5886
- const endTime = Date.now();
5887
- if (streamResult.response && isPromise(streamResult.response)) {
5888
- try {
5889
- const finalResponse = await streamResult.response;
5890
- const responseDict = modelAsDict(finalResponse);
5891
- setResponseAttributes3(span2, responseDict);
5892
- } catch {
6690
+ try {
6691
+ const endTime = Date.now();
6692
+ if (streamResult.response && isPromise(streamResult.response)) {
6693
+ try {
6694
+ const finalResponse = await streamResult.response;
6695
+ const responseDict = modelAsDict(finalResponse);
6696
+ setResponseAttributes4(span2, responseDict);
6697
+ } catch {
6698
+ const responseDict = modelAsDict(streamResult);
6699
+ setResponseAttributes4(span2, responseDict);
6700
+ }
6701
+ } else {
5893
6702
  const responseDict = modelAsDict(streamResult);
5894
- setResponseAttributes3(span2, responseDict);
6703
+ setResponseAttributes4(span2, responseDict);
5895
6704
  }
5896
- } else {
5897
- const responseDict = modelAsDict(streamResult);
5898
- setResponseAttributes3(span2, responseDict);
6705
+ const duration = (endTime - startTime) / 1e3;
6706
+ span2.setAttribute(
6707
+ "llm.response.duration",
6708
+ duration
6709
+ );
6710
+ } catch (e) {
6711
+ Logger.error(`${LOG_PREFIX3}:`, e);
5899
6712
  }
5900
- const duration = (endTime - startTime) / 1e3;
5901
- span2.setAttribute(
5902
- "llm.response.duration",
5903
- duration
5904
- );
5905
6713
  span2.setStatus({ code: SpanStatusCode.OK });
5906
6714
  span2.end();
5907
6715
  return res;
@@ -5917,11 +6725,9 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5917
6725
  );
5918
6726
  firstTokenRecorded = true;
5919
6727
  }
5920
- finalText += t;
5921
6728
  }
5922
6729
  } catch {
5923
6730
  }
5924
- chunkIndex += 1;
5925
6731
  return res;
5926
6732
  } catch (error) {
5927
6733
  span2.setStatus({
@@ -5933,13 +6739,23 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5933
6739
  throw error;
5934
6740
  }
5935
6741
  },
5936
- async return() {
6742
+ async return(value) {
5937
6743
  const endTime = Date.now();
5938
6744
  const duration = (endTime - startTime) / 1e3;
5939
6745
  span2.setAttribute("llm.response.duration", duration);
5940
6746
  span2.setStatus({ code: SpanStatusCode.OK });
5941
6747
  span2.end();
5942
- return { value: void 0, done: true };
6748
+ return iterator.return?.(value) ?? { value: void 0, done: true };
6749
+ },
6750
+ async throw(e) {
6751
+ span2.setStatus({
6752
+ code: SpanStatusCode.ERROR,
6753
+ message: e instanceof Error ? e.message : String(e)
6754
+ });
6755
+ span2.recordException(e instanceof Error ? e : new Error(String(e)));
6756
+ span2.end();
6757
+ if (iterator.throw) return iterator.throw(e);
6758
+ throw e;
5943
6759
  }
5944
6760
  };
5945
6761
  }
@@ -5949,7 +6765,6 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5949
6765
  stream: wrappedStream
5950
6766
  };
5951
6767
  } catch (error) {
5952
- Logger.error("netra.instrumentation.google-genai:", error);
5953
6768
  span2.setStatus({
5954
6769
  code: SpanStatusCode.ERROR,
5955
6770
  message: error instanceof Error ? error.message : String(error)
@@ -5960,7 +6775,6 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5960
6775
  }
5961
6776
  })();
5962
6777
  } catch (error) {
5963
- Logger.error("netra.instrumentation.google-genai:", error);
5964
6778
  span2.setStatus({
5965
6779
  code: SpanStatusCode.ERROR,
5966
6780
  message: error instanceof Error ? error.message : String(error)
@@ -5974,227 +6788,100 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
5974
6788
  };
5975
6789
  };
5976
6790
  }
5977
- function googleGenAIStartChatWrapper(tracer, spanName, requestType) {
5978
- const sendMessageWrapperFn = googleGenAIWrapper(tracer, spanName, requestType);
5979
- const sendMessageStreamWrapperFn = googleGenAIStreamWrapper(tracer, spanName, requestType);
5980
- return function wrapper(original) {
5981
- return function(...args) {
5982
- const chatSession = original.apply(this, args);
5983
- if (!chatSession) return chatSession;
5984
- const modelInstance = this;
5985
- const modelName = modelInstance.model;
5986
- const systemInstruction = modelInstance.systemInstruction;
5987
- const chatHistory = args[0]?.history;
5988
- if (typeof chatSession.sendMessage === "function" && !chatSession.__netra_patched) {
5989
- const originalSendMessage = chatSession.sendMessage.bind(chatSession);
5990
- const wrappedSendMessage = sendMessageWrapperFn(originalSendMessage);
5991
- chatSession.sendMessage = function(...sendArgs) {
5992
- const ctx = this;
5993
- if (modelName) ctx.model = modelName;
5994
- if (systemInstruction) ctx.systemInstruction = systemInstruction;
5995
- if (chatHistory) ctx.history = chatHistory;
5996
- return wrappedSendMessage.apply(this, sendArgs);
5997
- };
5998
- if (typeof chatSession.sendMessageStream === "function") {
5999
- const originalSendStream = chatSession.sendMessageStream.bind(chatSession);
6000
- const wrappedSendStream = sendMessageStreamWrapperFn(originalSendStream);
6001
- chatSession.sendMessageStream = function(...sendArgs) {
6002
- const ctx = this;
6003
- if (modelName) ctx.model = modelName;
6004
- if (systemInstruction) ctx.systemInstruction = systemInstruction;
6005
- if (chatHistory) ctx.history = chatHistory;
6006
- return wrappedSendStream.apply(this, sendArgs);
6007
- };
6008
- }
6009
- chatSession.__netra_patched = true;
6010
- }
6011
- return chatSession;
6012
- };
6013
- };
6014
- }
6015
- var chatWrapper2 = (tracer) => googleGenAIWrapper(tracer, CHAT_SPAN_NAME, "chat");
6016
- var embeddingsWrapper = (tracer) => googleGenAIWrapper(tracer, EMBEDDING_SPAN_NAME, "embedding");
6017
- var chatStreamWrapper2 = (tracer) => googleGenAIStreamWrapper(tracer, CHAT_SPAN_NAME, "chat");
6018
- var startChatWrapper = (tracer) => googleGenAIStartChatWrapper(tracer, CHAT_SPAN_NAME, "chat");
6019
- var INSTRUMENTATION_NAME2 = "netra.instrumentation.google_genai";
6020
- var INSTRUMENTS2 = ["@google/genai >= 0.24.1"];
6021
- var isInstrumented2 = false;
6022
- var generativeModelClasses = [];
6023
- async function resolveGoogleGenerativeAIAsync() {
6024
- if (generativeModelClasses.length > 0) return generativeModelClasses;
6025
- try {
6026
- const googleGenAIModule = await import('@google/generative-ai');
6027
- const esmClass = googleGenAIModule.GenerativeModel || googleGenAIModule.default?.GenerativeModel || googleGenAIModule.default || googleGenAIModule;
6028
- generativeModelClasses.push(esmClass);
6029
- } catch {
6030
- Logger.warn("Failed to resolve Google GenAI ESM module");
6031
- }
6032
- try {
6033
- const req = createRequire(import.meta.url);
6034
- const mod = req("@google/generative-ai");
6035
- const cjsClass = mod.GenerativeModel || mod.default?.GenerativeModel || mod.default || mod;
6036
- if (!generativeModelClasses.includes(cjsClass)) {
6037
- generativeModelClasses.push(cjsClass);
6038
- }
6039
- } catch {
6040
- Logger.warn("Failed to resolve Google GenAI CJS module");
6041
- }
6042
- return generativeModelClasses;
6043
- }
6044
- function resolveGoogleGenerativeAI() {
6045
- return generativeModelClasses;
6046
- }
6047
- var NetraGoogleGenerativeAIInstrumentor = class {
6791
+ var chatWrapper3 = (tracer) => googleGenerativeAIWrapper(tracer, CHAT_SPAN_NAME, "chat");
6792
+ var embeddingsWrapper2 = (tracer) => googleGenerativeAIWrapper(tracer, EMBEDDING_SPAN_NAME, "embedding");
6793
+ var chatStreamWrapper3 = (tracer) => googleGenerativeAIStreamWrapper(tracer, CHAT_SPAN_NAME, "chat");
6794
+
6795
+ // src/instrumentation/google-generative-ai/index.ts
6796
+ var NetraGoogleGenerativeAIInstrumentor = class extends BaseInstrumentor {
6048
6797
  constructor() {
6049
- this.tracer = null;
6050
- }
6051
- /**
6052
- * Returns the list of instrumentation dependencies
6053
- */
6054
- instrumentationDependencies() {
6055
- return [...INSTRUMENTS2];
6056
- }
6057
- /**
6058
- * Instrument Google GenAI client methods (async version)
6059
- * Tries both ESM and CJS resolution to cover dual-package setups.
6060
- */
6061
- async instrumentAsync(options = {}) {
6062
- if (isInstrumented2) {
6063
- Logger.warn("Google GenAI is already instrumented");
6064
- return this;
6065
- }
6066
- const classes = await resolveGoogleGenerativeAIAsync();
6067
- if (classes.length === 0) {
6068
- return this;
6798
+ super(...arguments);
6799
+ this.instrumentationName = "netra.instrumentation.google_generative_ai";
6800
+ this.instrumentationVersion = __version__3;
6801
+ this.packageName = "@google/generative-ai";
6802
+ this.displayName = "Google Generative AI";
6803
+ }
6804
+ extractClasses(mod) {
6805
+ const root = mod.default ?? mod;
6806
+ const GenerativeModel = root.GenerativeModel ?? root;
6807
+ if (!GenerativeModel?.prototype) return null;
6808
+ return { GenerativeModel, ChatSession: root.ChatSession };
6809
+ }
6810
+ isSameClasses(a, b) {
6811
+ return a.GenerativeModel === b.GenerativeModel;
6812
+ }
6813
+ applyPatches(classes, tracer) {
6814
+ const proto = classes.GenerativeModel?.prototype;
6815
+ if (!proto) {
6816
+ Logger.error("Google Generative AI: GenerativeModel.prototype not found");
6817
+ return false;
6069
6818
  }
6070
- try {
6071
- this.tracerProvider = options.tracerProvider;
6072
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME2, __version__2) : trace.getTracer(INSTRUMENTATION_NAME2, __version__2);
6073
- } catch (error) {
6074
- Logger.error(`Failed to initialize tracer: ${error}`);
6075
- return this;
6819
+ let wrapped = false;
6820
+ if (typeof proto.generateContent === "function") {
6821
+ shimmer.wrap(proto, "generateContent", chatWrapper3(tracer));
6822
+ wrapped = true;
6076
6823
  }
6077
- classes.forEach((model) => this._instrumentGenerativeModel(model));
6078
- isInstrumented2 = true;
6079
- return this;
6080
- }
6081
- /**
6082
- * Instrument Google GenAI client methods (sync version)
6083
- */
6084
- instrument(options = {}) {
6085
- if (isInstrumented2) {
6086
- Logger.warn("Google GenAI is already instrumented");
6087
- return this;
6824
+ if (typeof proto.generateContentStream === "function") {
6825
+ shimmer.wrap(proto, "generateContentStream", chatStreamWrapper3(tracer));
6826
+ wrapped = true;
6088
6827
  }
6089
- const classes = resolveGoogleGenerativeAI();
6090
- if (classes.length === 0) {
6091
- this.instrumentAsync(options).catch((e) => {
6092
- Logger.error("Failed to instrument Google GenAI:", e);
6093
- });
6094
- return this;
6828
+ if (typeof proto.embedContent === "function") {
6829
+ shimmer.wrap(proto, "embedContent", embeddingsWrapper2(tracer));
6830
+ wrapped = true;
6095
6831
  }
6096
- try {
6097
- this.tracerProvider = options.tracerProvider;
6098
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME2, __version__2) : trace.getTracer(INSTRUMENTATION_NAME2, __version__2);
6099
- } catch (error) {
6100
- Logger.error(`Failed to initialize tracer: ${error}`);
6101
- return this;
6832
+ const chatProto = classes.ChatSession?.prototype;
6833
+ if (chatProto) {
6834
+ if (typeof chatProto.sendMessage === "function") {
6835
+ shimmer.wrap(chatProto, "sendMessage", chatWrapper3(tracer));
6836
+ wrapped = true;
6837
+ }
6838
+ if (typeof chatProto.sendMessageStream === "function") {
6839
+ shimmer.wrap(chatProto, "sendMessageStream", chatStreamWrapper3(tracer));
6840
+ wrapped = true;
6841
+ }
6102
6842
  }
6103
- classes.forEach((model) => this._instrumentGenerativeModel(model));
6104
- isInstrumented2 = true;
6105
- return this;
6843
+ return wrapped;
6106
6844
  }
6107
- /**
6108
- * Uninstrument Google GenAI client methods
6109
- */
6110
- uninstrument() {
6111
- if (!isInstrumented2) {
6112
- Logger.warn("Google GenAI is not instrumented");
6113
- return;
6845
+ removePatches(classes) {
6846
+ const proto = classes.GenerativeModel?.prototype;
6847
+ if (proto) {
6848
+ if (typeof proto.generateContent === "function")
6849
+ shimmer.unwrap(proto, "generateContent");
6850
+ if (typeof proto.generateContentStream === "function")
6851
+ shimmer.unwrap(proto, "generateContentStream");
6852
+ if (typeof proto.embedContent === "function")
6853
+ shimmer.unwrap(proto, "embedContent");
6854
+ }
6855
+ const chatProto = classes.ChatSession?.prototype;
6856
+ if (chatProto) {
6857
+ if (typeof chatProto.sendMessage === "function")
6858
+ shimmer.unwrap(chatProto, "sendMessage");
6859
+ if (typeof chatProto.sendMessageStream === "function")
6860
+ shimmer.unwrap(chatProto, "sendMessageStream");
6114
6861
  }
6115
- const classes = resolveGoogleGenerativeAI();
6116
- classes.forEach((model) => this._uninstrumentGenerativeModel(model));
6117
- generativeModelClasses = [];
6118
- isInstrumented2 = false;
6119
6862
  }
6120
6863
  /**
6121
- * Check if Google GenAI is currently instrumented
6864
+ * @deprecated Use instrument() instead. Kept for backward compatibility
6865
+ * with orchestrator call sites that haven't been updated yet.
6122
6866
  */
6123
- isInstrumented() {
6124
- return isInstrumented2;
6125
- }
6126
- _instrumentGenerativeModel(GenerativeModel) {
6127
- if (!this.tracer) return;
6128
- try {
6129
- if (!GenerativeModel?.prototype) {
6130
- Logger.error(
6131
- "Failed to find Google GenAI GenerativeModel to instrument"
6132
- );
6133
- return;
6134
- }
6135
- const tracer = this.tracer;
6136
- shimmer.wrap(
6137
- GenerativeModel.prototype,
6138
- "generateContent",
6139
- chatWrapper2(tracer)
6140
- );
6141
- shimmer.wrap(
6142
- GenerativeModel.prototype,
6143
- "generateContentStream",
6144
- chatStreamWrapper2(tracer)
6145
- );
6146
- shimmer.wrap(
6147
- GenerativeModel.prototype,
6148
- "embedContent",
6149
- embeddingsWrapper(tracer)
6150
- );
6151
- if (typeof GenerativeModel.prototype.startChat === "function") {
6152
- shimmer.wrap(
6153
- GenerativeModel.prototype,
6154
- "startChat",
6155
- startChatWrapper(tracer)
6156
- );
6157
- }
6158
- } catch (error) {
6159
- Logger.debug(
6160
- `Google GenAI instrumentation: failed to instrument: ${error}`
6161
- );
6162
- }
6163
- }
6164
- _uninstrumentGenerativeModel(GenerativeModel) {
6165
- try {
6166
- if (!GenerativeModel?.prototype) return;
6167
- if (typeof GenerativeModel.prototype.generateContent === "function") {
6168
- shimmer.unwrap(GenerativeModel.prototype, "generateContent");
6169
- }
6170
- if (typeof GenerativeModel.prototype.generateContentStream === "function") {
6171
- shimmer.unwrap(GenerativeModel.prototype, "generateContentStream");
6172
- }
6173
- if (typeof GenerativeModel.prototype.embedContent === "function") {
6174
- shimmer.unwrap(GenerativeModel.prototype, "embedContent");
6175
- }
6176
- if (typeof GenerativeModel.prototype.startChat === "function") {
6177
- shimmer.unwrap(GenerativeModel.prototype, "startChat");
6178
- }
6179
- } catch (error) {
6180
- Logger.debug(`Failed to uninstrument Google GenAI: ${error}`);
6181
- }
6867
+ async instrumentAsync(options = {}) {
6868
+ return this.instrument(options);
6182
6869
  }
6183
6870
  };
6184
6871
  var googleGenerativeAIInstrumentor = new NetraGoogleGenerativeAIInstrumentor();
6185
6872
 
6186
6873
  // src/instrumentation/groq/version.ts
6187
- var __version__3 = "1.0.0";
6874
+ var __version__4 = "1.0.0";
6188
6875
 
6189
6876
  // src/instrumentation/groq/utils.ts
6190
- function setRequestAttributes4(span2, kwargs, requestType) {
6877
+ function setRequestAttributes5(span2, kwargs, requestType) {
6191
6878
  if (!span2.isRecording()) {
6192
6879
  Logger.log("Span is not recording");
6193
6880
  return;
6194
6881
  }
6195
6882
  setRequestAttributes(span2, kwargs, requestType, "groq");
6196
6883
  }
6197
- function setResponseAttributes4(span2, response) {
6884
+ function setResponseAttributes5(span2, response) {
6198
6885
  if (!span2.isRecording()) {
6199
6886
  Logger.log("Span is not recording");
6200
6887
  return;
@@ -6223,7 +6910,7 @@ function groqWrapper(tracer, spanName, requestType) {
6223
6910
  currentContext
6224
6911
  );
6225
6912
  try {
6226
- setRequestAttributes4(span2, kwargs, requestType);
6913
+ setRequestAttributes5(span2, kwargs, requestType);
6227
6914
  const startTime = Date.now();
6228
6915
  const response = wrapped.call(instance, ...args);
6229
6916
  if (isPromise(response)) {
@@ -6264,7 +6951,7 @@ function groqWrapper(tracer, spanName, requestType) {
6264
6951
  },
6265
6952
  (span2) => {
6266
6953
  try {
6267
- setRequestAttributes4(span2, kwargs, requestType);
6954
+ setRequestAttributes5(span2, kwargs, requestType);
6268
6955
  const startTime = Date.now();
6269
6956
  const response = wrapped.call(instance, ...args);
6270
6957
  if (isPromise(response)) {
@@ -6273,7 +6960,7 @@ function groqWrapper(tracer, spanName, requestType) {
6273
6960
  const value = await response;
6274
6961
  const endTime = Date.now();
6275
6962
  const responseDict = modelAsDict(value);
6276
- setResponseAttributes4(span2, responseDict);
6963
+ setResponseAttributes5(span2, responseDict);
6277
6964
  span2.setAttribute(
6278
6965
  "llm.response.duration",
6279
6966
  (endTime - startTime) / 1e3
@@ -6295,7 +6982,7 @@ function groqWrapper(tracer, spanName, requestType) {
6295
6982
  } else {
6296
6983
  const endTime = Date.now();
6297
6984
  const responseDict = modelAsDict(response);
6298
- setResponseAttributes4(span2, responseDict);
6985
+ setResponseAttributes5(span2, responseDict);
6299
6986
  span2.setAttribute(
6300
6987
  "llm.response.duration",
6301
6988
  (endTime - startTime) / 1e3
@@ -6319,7 +7006,7 @@ function groqWrapper(tracer, spanName, requestType) {
6319
7006
  }
6320
7007
  };
6321
7008
  }
6322
- var chatWrapper3 = (tracer) => groqWrapper(tracer, CHAT_SPAN_NAME2, "chat");
7009
+ var chatWrapper4 = (tracer) => groqWrapper(tracer, CHAT_SPAN_NAME2, "chat");
6323
7010
  var StreamingWrapper = class {
6324
7011
  constructor(span2, response, startTime, requestKwargs) {
6325
7012
  this.iterator = null;
@@ -6527,7 +7214,7 @@ var AsyncStreamingWrapper = class {
6527
7214
  finalizeSpan(code) {
6528
7215
  const endTime = Date.now();
6529
7216
  const duration = (endTime - this.startTime) / 1e3;
6530
- setResponseAttributes4(this.span, this.completeResponse);
7217
+ setResponseAttributes5(this.span, this.completeResponse);
6531
7218
  this.span.setAttribute("llm.response.duration", duration);
6532
7219
  this.span.setStatus({ code });
6533
7220
  this.span.end();
@@ -6535,10 +7222,10 @@ var AsyncStreamingWrapper = class {
6535
7222
  };
6536
7223
 
6537
7224
  // src/instrumentation/groq/index.ts
6538
- var INSTRUMENTATION_NAME3 = "netra.instrumentation.groq";
6539
- var INSTRUMENTS3 = ["groq-sdk >= 0.3.0"];
7225
+ var INSTRUMENTATION_NAME2 = "netra.instrumentation.groq";
7226
+ var INSTRUMENTS2 = ["groq-sdk >= 0.3.0"];
6540
7227
  var originalMethods = /* @__PURE__ */ new Map();
6541
- var isInstrumented3 = false;
7228
+ var isInstrumented2 = false;
6542
7229
  var groqClasses = [];
6543
7230
  async function resolveGroqAsync() {
6544
7231
  if (groqClasses.length > 0) return groqClasses;
@@ -6568,14 +7255,14 @@ var NetraGroqInstrumentor = class {
6568
7255
  this.tracer = null;
6569
7256
  }
6570
7257
  instrumentationDependencies() {
6571
- return INSTRUMENTS3;
7258
+ return INSTRUMENTS2;
6572
7259
  }
6573
7260
  /**
6574
7261
  * Instrument Groq client methods (async version)
6575
7262
  * Tries both ESM and CJS resolution to cover dual-package setups.
6576
7263
  */
6577
7264
  async instrumentAsync(options = {}) {
6578
- if (isInstrumented3) {
7265
+ if (isInstrumented2) {
6579
7266
  Logger.warn("Groq is already instrumented");
6580
7267
  return this;
6581
7268
  }
@@ -6587,11 +7274,11 @@ var NetraGroqInstrumentor = class {
6587
7274
  this.tracerProvider = options.tracerProvider;
6588
7275
  if (this.tracerProvider) {
6589
7276
  this.tracer = this.tracerProvider.getTracer(
6590
- INSTRUMENTATION_NAME3,
6591
- __version__3
7277
+ INSTRUMENTATION_NAME2,
7278
+ __version__4
6592
7279
  );
6593
7280
  } else {
6594
- this.tracer = trace.getTracer(INSTRUMENTATION_NAME3, __version__3);
7281
+ this.tracer = trace.getTracer(INSTRUMENTATION_NAME2, __version__4);
6595
7282
  }
6596
7283
  } catch (error) {
6597
7284
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -6600,7 +7287,7 @@ var NetraGroqInstrumentor = class {
6600
7287
  classes.forEach((Groq, index) => {
6601
7288
  this._instrumentChatCompletions(Groq, index);
6602
7289
  });
6603
- isInstrumented3 = true;
7290
+ isInstrumented2 = true;
6604
7291
  return this;
6605
7292
  }
6606
7293
  /**
@@ -6608,7 +7295,7 @@ var NetraGroqInstrumentor = class {
6608
7295
  * Note: This uses cached Groq classes. Call instrumentAsync() for proper initialization.
6609
7296
  */
6610
7297
  instrument(options = {}) {
6611
- if (isInstrumented3) {
7298
+ if (isInstrumented2) {
6612
7299
  Logger.warn("Groq is already instrumented");
6613
7300
  return this;
6614
7301
  }
@@ -6623,11 +7310,11 @@ var NetraGroqInstrumentor = class {
6623
7310
  this.tracerProvider = options.tracerProvider;
6624
7311
  if (this.tracerProvider) {
6625
7312
  this.tracer = this.tracerProvider.getTracer(
6626
- INSTRUMENTATION_NAME3,
6627
- __version__3
7313
+ INSTRUMENTATION_NAME2,
7314
+ __version__4
6628
7315
  );
6629
7316
  } else {
6630
- this.tracer = trace.getTracer(INSTRUMENTATION_NAME3, __version__3);
7317
+ this.tracer = trace.getTracer(INSTRUMENTATION_NAME2, __version__4);
6631
7318
  }
6632
7319
  } catch (error) {
6633
7320
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -6636,11 +7323,11 @@ var NetraGroqInstrumentor = class {
6636
7323
  classes.forEach((Groq, index) => {
6637
7324
  this._instrumentChatCompletions(Groq, index);
6638
7325
  });
6639
- isInstrumented3 = true;
7326
+ isInstrumented2 = true;
6640
7327
  return this;
6641
7328
  }
6642
7329
  uninstrument() {
6643
- if (!isInstrumented3) {
7330
+ if (!isInstrumented2) {
6644
7331
  Logger.warn("Groq is not instrumented");
6645
7332
  return;
6646
7333
  }
@@ -6650,10 +7337,10 @@ var NetraGroqInstrumentor = class {
6650
7337
  });
6651
7338
  originalMethods.clear();
6652
7339
  groqClasses = [];
6653
- isInstrumented3 = false;
7340
+ isInstrumented2 = false;
6654
7341
  }
6655
7342
  isInstrumented() {
6656
- return isInstrumented3;
7343
+ return isInstrumented2;
6657
7344
  }
6658
7345
  _instrumentChatCompletions(Groq, index) {
6659
7346
  if (!this.tracer) {
@@ -6671,7 +7358,7 @@ var NetraGroqInstrumentor = class {
6671
7358
  const originalCreate = CompletionsClass.prototype.create;
6672
7359
  originalMethods.set(`chat.completions.create-${index}`, originalCreate);
6673
7360
  const tracer = this.tracer;
6674
- const wrapper = chatWrapper3(tracer);
7361
+ const wrapper = chatWrapper4(tracer);
6675
7362
  CompletionsClass.prototype.create = function(...args) {
6676
7363
  const original = originalCreate.bind(this);
6677
7364
  const kwargs = args[0] || {};
@@ -6699,7 +7386,7 @@ var NetraGroqInstrumentor = class {
6699
7386
  var groqInstrumentor = new NetraGroqInstrumentor();
6700
7387
 
6701
7388
  // src/instrumentation/langgraph/version.ts
6702
- var __version__4 = "1.0.0";
7389
+ var __version__5 = "1.0.0";
6703
7390
 
6704
7391
  // node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js
6705
7392
  var __defProp = Object.defineProperty;
@@ -7397,8 +8084,8 @@ var LanggraphStreamingWrapper = class {
7397
8084
  return {};
7398
8085
  }
7399
8086
  }
7400
- async startStream(originalFunc, instance, input, config2, ...rest) {
7401
- this.iterable = await originalFunc.call(instance, input, config2, ...rest);
8087
+ async startStream(originalFunc, instance, input, config, ...rest) {
8088
+ this.iterable = await originalFunc.call(instance, input, config, ...rest);
7402
8089
  return this;
7403
8090
  }
7404
8091
  async *[Symbol.asyncIterator]() {
@@ -7432,23 +8119,23 @@ var LanggraphWrapper = class {
7432
8119
  this.tracer = tracer;
7433
8120
  this.spanName = "Langgraph.workflow";
7434
8121
  }
7435
- getUpdatedConfig(config2, rootSpan) {
7436
- if (!rootSpan) return config2 || {};
8122
+ getUpdatedConfig(config, rootSpan) {
8123
+ if (!rootSpan) return config || {};
7437
8124
  const callbackHandler = new NetraLanggraphCallbackHandler(
7438
8125
  this.tracer,
7439
8126
  rootSpan
7440
8127
  );
7441
- const callbacks = config2?.callbacks;
8128
+ const callbacks = config?.callbacks;
7442
8129
  const normalizedCallbacks = callbacks ? Array.isArray(callbacks) ? callbacks : [callbacks] : [];
7443
8130
  const updatedConfig = {
7444
- ...config2,
8131
+ ...config,
7445
8132
  callbacks: [...normalizedCallbacks, callbackHandler]
7446
8133
  };
7447
8134
  return updatedConfig;
7448
8135
  }
7449
- async invoke(originalFunc, instance, input, config2, ...rest) {
8136
+ async invoke(originalFunc, instance, input, config, ...rest) {
7450
8137
  if (shouldSuppressInstrumentation() || context.active().getValue(LANGGRAPH_INSTRUMENTATION_ACTIVE)) {
7451
- return await originalFunc.call(instance, input, config2, ...rest);
8138
+ return await originalFunc.call(instance, input, config, ...rest);
7452
8139
  }
7453
8140
  const activeSpan = trace.getSpan(context.active());
7454
8141
  Logger.debug(`LangGraph invoke start. Active TraceId: ${activeSpan?.spanContext().traceId}, SpanId: ${activeSpan?.spanContext().spanId}`);
@@ -7470,7 +8157,7 @@ var LanggraphWrapper = class {
7470
8157
  }
7471
8158
  try {
7472
8159
  setGraphInputAttributes(span2, input);
7473
- const updatedConfig = this.getUpdatedConfig(config2, span2);
8160
+ const updatedConfig = this.getUpdatedConfig(config, span2);
7474
8161
  const output = await originalFunc.call(
7475
8162
  instance,
7476
8163
  input,
@@ -7487,10 +8174,10 @@ var LanggraphWrapper = class {
7487
8174
  }
7488
8175
  });
7489
8176
  }
7490
- async stream(originalFunc, instance, input, config2, ...rest) {
8177
+ async stream(originalFunc, instance, input, config, ...rest) {
7491
8178
  if (shouldSuppressInstrumentation() || context.active().getValue(LANGGRAPH_INSTRUMENTATION_ACTIVE)) {
7492
8179
  Logger.debug("LangGraph stream skipped (inside instrumented call)");
7493
- return await originalFunc.call(instance, input, config2, ...rest);
8180
+ return await originalFunc.call(instance, input, config, ...rest);
7494
8181
  }
7495
8182
  Logger.debug("LangGraph stream starting instrumentation");
7496
8183
  const span2 = this.tracer.startSpan(
@@ -7501,7 +8188,7 @@ var LanggraphWrapper = class {
7501
8188
  context.active()
7502
8189
  );
7503
8190
  setGraphInputAttributes(span2, input);
7504
- const updatedConfig = this.getUpdatedConfig(config2, span2);
8191
+ const updatedConfig = this.getUpdatedConfig(config, span2);
7505
8192
  try {
7506
8193
  const ctxWithSpan = trace.setSpan(context.active(), span2);
7507
8194
  const ctxWithFlag = ctxWithSpan.setValue(LANGGRAPH_INSTRUMENTATION_ACTIVE, true);
@@ -7522,9 +8209,9 @@ var LanggraphWrapper = class {
7522
8209
  };
7523
8210
 
7524
8211
  // src/instrumentation/langgraph/index.ts
7525
- var INSTRUMENTATION_NAME4 = "netra.instrumentation.langgraph";
7526
- var INSTRUMENTS4 = ["langgraph >= 1.1.1"];
7527
- var isInstrumented4 = false;
8212
+ var INSTRUMENTATION_NAME3 = "netra.instrumentation.langgraph";
8213
+ var INSTRUMENTS3 = ["langgraph >= 1.1.1"];
8214
+ var isInstrumented3 = false;
7528
8215
  var LanggraphClass = null;
7529
8216
  var originalMethods2 = /* @__PURE__ */ new Map();
7530
8217
  function findModuleInCache(moduleName) {
@@ -7585,13 +8272,13 @@ var NetraLanggraphInstrumentor = class {
7585
8272
  this.tracer = null;
7586
8273
  }
7587
8274
  isInstrumented() {
7588
- return isInstrumented4;
8275
+ return isInstrumented3;
7589
8276
  }
7590
8277
  instrumentationDependencies() {
7591
- return [...INSTRUMENTS4];
8278
+ return [...INSTRUMENTS3];
7592
8279
  }
7593
8280
  async instrument(options = {}) {
7594
- if (isInstrumented4) {
8281
+ if (isInstrumented3) {
7595
8282
  Logger.warn("Langgraph is already instrumented");
7596
8283
  return this;
7597
8284
  }
@@ -7602,18 +8289,18 @@ var NetraLanggraphInstrumentor = class {
7602
8289
  }
7603
8290
  try {
7604
8291
  this.tracerProvider = options.tracerProvider;
7605
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME4, __version__4) : trace.getTracer(INSTRUMENTATION_NAME4, __version__4);
8292
+ this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME3, __version__5) : trace.getTracer(INSTRUMENTATION_NAME3, __version__5);
7606
8293
  } catch (error) {
7607
8294
  Logger.error(`Failed to initialize tracer: ${error}`);
7608
8295
  return this;
7609
8296
  }
7610
8297
  this._instrumentInvoke(Langgraph);
7611
8298
  this._instrumentStream(Langgraph);
7612
- isInstrumented4 = true;
8299
+ isInstrumented3 = true;
7613
8300
  return this;
7614
8301
  }
7615
8302
  async uninstrument() {
7616
- if (!isInstrumented4) {
8303
+ if (!isInstrumented3) {
7617
8304
  Logger.warn("LangGraph is not instrumented");
7618
8305
  return;
7619
8306
  }
@@ -7624,7 +8311,7 @@ var NetraLanggraphInstrumentor = class {
7624
8311
  }
7625
8312
  originalMethods2.clear();
7626
8313
  LanggraphClass = null;
7627
- isInstrumented4 = false;
8314
+ isInstrumented3 = false;
7628
8315
  }
7629
8316
  _instrumentInvoke(Langgraph) {
7630
8317
  if (!this.tracer) return;
@@ -7643,13 +8330,13 @@ var NetraLanggraphInstrumentor = class {
7643
8330
  originalMethods2.set("langgraph.graph.invoke.proto", targetProto);
7644
8331
  const tracer = this.tracer;
7645
8332
  const wrapper = new LanggraphWrapper(tracer);
7646
- const patchedInvoke = async function(input, config2, ...rest) {
8333
+ const patchedInvoke = async function(input, config, ...rest) {
7647
8334
  Logger.debug("LangGraph invoke intercepted!");
7648
8335
  return await wrapper.invoke(
7649
8336
  originalInvoke,
7650
8337
  this,
7651
8338
  input,
7652
- config2,
8339
+ config,
7653
8340
  ...rest
7654
8341
  );
7655
8342
  };
@@ -7678,13 +8365,13 @@ var NetraLanggraphInstrumentor = class {
7678
8365
  originalMethods2.set("langgraph.graph.stream.proto", targetProto);
7679
8366
  const tracer = this.tracer;
7680
8367
  const wrapper = new LanggraphWrapper(tracer);
7681
- targetProto.stream = async function(input, config2, ...rest) {
8368
+ targetProto.stream = async function(input, config, ...rest) {
7682
8369
  Logger.debug("LangGraph stream intercepted!");
7683
8370
  return await wrapper.stream(
7684
8371
  originalStream,
7685
8372
  this,
7686
8373
  input,
7687
- config2,
8374
+ config,
7688
8375
  ...rest
7689
8376
  );
7690
8377
  };
@@ -7721,10 +8408,10 @@ var NetraLanggraphInstrumentor = class {
7721
8408
  var langgraphInstrumentor = new NetraLanggraphInstrumentor();
7722
8409
 
7723
8410
  // src/instrumentation/mistralai/version.ts
7724
- var __version__5 = "1.0.0";
8411
+ var __version__6 = "1.0.0";
7725
8412
 
7726
8413
  // src/instrumentation/mistralai/utils.ts
7727
- function setRequestAttributes5(span2, kwargs, requestType) {
8414
+ function setRequestAttributes6(span2, kwargs, requestType) {
7728
8415
  setRequestAttributes(span2, kwargs, requestType, "mistralai");
7729
8416
  if (kwargs.agentId) {
7730
8417
  span2.setAttribute("gen_ai.agent.id", String(kwargs.agentId));
@@ -7743,7 +8430,7 @@ function setRequestAttributes5(span2, kwargs, requestType) {
7743
8430
  span2.setAttribute("llm.request.has_suffix", true);
7744
8431
  }
7745
8432
  }
7746
- function setResponseAttributes5(span2, response) {
8433
+ function setResponseAttributes6(span2, response) {
7747
8434
  setResponseAttributes(span2, response);
7748
8435
  }
7749
8436
 
@@ -7769,7 +8456,7 @@ function mistralWrapper(tracer, spanName, requestType) {
7769
8456
  },
7770
8457
  (span2) => {
7771
8458
  try {
7772
- setRequestAttributes5(span2, kwargs, requestType);
8459
+ setRequestAttributes6(span2, kwargs, requestType);
7773
8460
  const startTime = Date.now();
7774
8461
  const response = wrapped.call(instance, ...args);
7775
8462
  if (isPromise(response)) {
@@ -7777,7 +8464,7 @@ function mistralWrapper(tracer, spanName, requestType) {
7777
8464
  try {
7778
8465
  const value = await response;
7779
8466
  const endTime2 = Date.now();
7780
- setResponseAttributes5(span2, modelAsDict(value));
8467
+ setResponseAttributes6(span2, modelAsDict(value));
7781
8468
  span2.setAttribute(
7782
8469
  "llm.response.duration",
7783
8470
  (endTime2 - startTime) / 1e3
@@ -7798,7 +8485,7 @@ function mistralWrapper(tracer, spanName, requestType) {
7798
8485
  })();
7799
8486
  }
7800
8487
  const endTime = Date.now();
7801
- setResponseAttributes5(span2, modelAsDict(response));
8488
+ setResponseAttributes6(span2, modelAsDict(response));
7802
8489
  span2.setAttribute(
7803
8490
  "llm.response.duration",
7804
8491
  (endTime - startTime) / 1e3
@@ -7839,7 +8526,7 @@ function mistralStreamWrapper(tracer, spanName, requestType) {
7839
8526
  currentContext
7840
8527
  );
7841
8528
  try {
7842
- setRequestAttributes5(span2, { ...kwargs, stream: true }, requestType);
8529
+ setRequestAttributes6(span2, { ...kwargs, stream: true }, requestType);
7843
8530
  const startTime = Date.now();
7844
8531
  const response = wrapped.call(instance, ...args);
7845
8532
  if (isPromise(response)) {
@@ -7878,9 +8565,9 @@ function mistralStreamWrapper(tracer, spanName, requestType) {
7878
8565
  }
7879
8566
  };
7880
8567
  }
7881
- var chatWrapper4 = (tracer) => mistralWrapper(tracer, CHAT_SPAN_NAME3, "chat");
7882
- var chatStreamWrapper3 = (tracer) => mistralStreamWrapper(tracer, CHAT_STREAM_SPAN_NAME, "chat");
7883
- var embeddingsWrapper2 = (tracer) => mistralWrapper(tracer, EMBEDDING_SPAN_NAME2, "embedding");
8568
+ var chatWrapper5 = (tracer) => mistralWrapper(tracer, CHAT_SPAN_NAME3, "chat");
8569
+ var chatStreamWrapper4 = (tracer) => mistralStreamWrapper(tracer, CHAT_STREAM_SPAN_NAME, "chat");
8570
+ var embeddingsWrapper3 = (tracer) => mistralWrapper(tracer, EMBEDDING_SPAN_NAME2, "embedding");
7884
8571
  var fimWrapper = (tracer) => mistralWrapper(tracer, FIM_SPAN_NAME, "fim");
7885
8572
  var fimStreamWrapper = (tracer) => mistralStreamWrapper(tracer, FIM_STREAM_SPAN_NAME, "fim");
7886
8573
  var agentsWrapper = (tracer) => mistralWrapper(tracer, AGENTS_SPAN_NAME, "agent");
@@ -8013,7 +8700,7 @@ var StreamingWrapper2 = class {
8013
8700
  finalizeSpan(error) {
8014
8701
  const endTime = Date.now();
8015
8702
  const duration = (endTime - this.startTime) / 1e3;
8016
- setResponseAttributes5(this.span, this.completeResponse);
8703
+ setResponseAttributes6(this.span, this.completeResponse);
8017
8704
  this.span.setAttribute("llm.response.duration", duration);
8018
8705
  if (error) {
8019
8706
  this.span.setStatus({
@@ -8159,7 +8846,7 @@ var AsyncStreamingWrapper2 = class {
8159
8846
  finalizeSpan(error) {
8160
8847
  const endTime = Date.now();
8161
8848
  const duration = (endTime - this.startTime) / 1e3;
8162
- setResponseAttributes5(this.span, this.completeResponse);
8849
+ setResponseAttributes6(this.span, this.completeResponse);
8163
8850
  this.span.setAttribute("llm.response.duration", duration);
8164
8851
  if (error) {
8165
8852
  this.span.setStatus({
@@ -8178,10 +8865,10 @@ var AsyncStreamingWrapper2 = class {
8178
8865
  };
8179
8866
 
8180
8867
  // src/instrumentation/mistralai/index.ts
8181
- var INSTRUMENTATION_NAME5 = "netra.instrumentation.mistral_ai";
8182
- var INSTRUMENTS5 = ["@mistralai/mistralai >= 1.0.0"];
8868
+ var INSTRUMENTATION_NAME4 = "netra.instrumentation.mistral_ai";
8869
+ var INSTRUMENTS4 = ["@mistralai/mistralai >= 1.0.0"];
8183
8870
  var originalMethods3 = /* @__PURE__ */ new Map();
8184
- var isInstrumented5 = false;
8871
+ var isInstrumented4 = false;
8185
8872
  var mistralClasses = [];
8186
8873
  async function resolveMistralAsync() {
8187
8874
  if (mistralClasses.length > 0) return mistralClasses;
@@ -8217,14 +8904,14 @@ var NetraMistralAIInstrumentor = class {
8217
8904
  * Returns the list of instrumentation dependencies
8218
8905
  */
8219
8906
  instrumentationDependencies() {
8220
- return INSTRUMENTS5;
8907
+ return INSTRUMENTS4;
8221
8908
  }
8222
8909
  /**
8223
8910
  * Instrument MistralAI client methods (async version)
8224
8911
  * Tries both ESM and CJS resolution to cover dual-package setups.
8225
8912
  */
8226
8913
  async instrumentAsync(options = {}) {
8227
- if (isInstrumented5) {
8914
+ if (isInstrumented4) {
8228
8915
  Logger.warn("MistralAI is already instrumented");
8229
8916
  return this;
8230
8917
  }
@@ -8236,11 +8923,11 @@ var NetraMistralAIInstrumentor = class {
8236
8923
  this.tracerProvider = options.tracerProvider;
8237
8924
  if (this.tracerProvider) {
8238
8925
  this.tracer = this.tracerProvider.getTracer(
8239
- INSTRUMENTATION_NAME5,
8240
- __version__5
8926
+ INSTRUMENTATION_NAME4,
8927
+ __version__6
8241
8928
  );
8242
8929
  } else {
8243
- this.tracer = trace.getTracer(INSTRUMENTATION_NAME5, __version__5);
8930
+ this.tracer = trace.getTracer(INSTRUMENTATION_NAME4, __version__6);
8244
8931
  }
8245
8932
  } catch (error) {
8246
8933
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -8262,7 +8949,7 @@ var NetraMistralAIInstrumentor = class {
8262
8949
  );
8263
8950
  return this;
8264
8951
  }
8265
- isInstrumented5 = true;
8952
+ isInstrumented4 = true;
8266
8953
  return this;
8267
8954
  }
8268
8955
  /**
@@ -8270,7 +8957,7 @@ var NetraMistralAIInstrumentor = class {
8270
8957
  * Note: This uses cached Mistral classes. Call instrumentAsync() for proper initialization.
8271
8958
  */
8272
8959
  instrument(options = {}) {
8273
- if (isInstrumented5) {
8960
+ if (isInstrumented4) {
8274
8961
  Logger.warn("MistralAI is already instrumented");
8275
8962
  return this;
8276
8963
  }
@@ -8285,11 +8972,11 @@ var NetraMistralAIInstrumentor = class {
8285
8972
  this.tracerProvider = options.tracerProvider;
8286
8973
  if (this.tracerProvider) {
8287
8974
  this.tracer = this.tracerProvider.getTracer(
8288
- INSTRUMENTATION_NAME5,
8289
- __version__5
8975
+ INSTRUMENTATION_NAME4,
8976
+ __version__6
8290
8977
  );
8291
8978
  } else {
8292
- this.tracer = trace.getTracer(INSTRUMENTATION_NAME5, __version__5);
8979
+ this.tracer = trace.getTracer(INSTRUMENTATION_NAME4, __version__6);
8293
8980
  }
8294
8981
  } catch (error) {
8295
8982
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -8311,14 +8998,14 @@ var NetraMistralAIInstrumentor = class {
8311
8998
  );
8312
8999
  return this;
8313
9000
  }
8314
- isInstrumented5 = true;
9001
+ isInstrumented4 = true;
8315
9002
  return this;
8316
9003
  }
8317
9004
  /**
8318
9005
  * Uninstrument MistralAI client methods
8319
9006
  */
8320
9007
  uninstrument() {
8321
- if (!isInstrumented5) {
9008
+ if (!isInstrumented4) {
8322
9009
  Logger.warn("MistralAI is not instrumented");
8323
9010
  return;
8324
9011
  }
@@ -8331,13 +9018,13 @@ var NetraMistralAIInstrumentor = class {
8331
9018
  });
8332
9019
  originalMethods3.clear();
8333
9020
  mistralClasses = [];
8334
- isInstrumented5 = false;
9021
+ isInstrumented4 = false;
8335
9022
  }
8336
9023
  /**
8337
9024
  * Check if MistralAI is currently instrumented
8338
9025
  */
8339
9026
  isInstrumented() {
8340
- return isInstrumented5;
9027
+ return isInstrumented4;
8341
9028
  }
8342
9029
  /**
8343
9030
  * Resolve public resource constructors from the exported Mistral client.
@@ -8377,7 +9064,7 @@ var NetraMistralAIInstrumentor = class {
8377
9064
  const originalComplete = ChatClass.prototype.complete;
8378
9065
  originalMethods3.set(`chat.complete-${index}`, originalComplete);
8379
9066
  const tracer = this.tracer;
8380
- const wrapper = chatWrapper4(tracer);
9067
+ const wrapper = chatWrapper5(tracer);
8381
9068
  ChatClass.prototype.complete = function(...args) {
8382
9069
  const original = originalComplete.bind(this);
8383
9070
  const kwargs = args[0] || {};
@@ -8394,7 +9081,7 @@ var NetraMistralAIInstrumentor = class {
8394
9081
  const originalStream = ChatClass.prototype.stream;
8395
9082
  originalMethods3.set(`chat.stream-${index}`, originalStream);
8396
9083
  const tracer = this.tracer;
8397
- const wrapper = chatStreamWrapper3(tracer);
9084
+ const wrapper = chatStreamWrapper4(tracer);
8398
9085
  ChatClass.prototype.stream = function(...args) {
8399
9086
  const original = originalStream.bind(this);
8400
9087
  const kwargs = args[0] || {};
@@ -8422,7 +9109,7 @@ var NetraMistralAIInstrumentor = class {
8422
9109
  const originalCreate = EmbeddingsClass.prototype.create;
8423
9110
  originalMethods3.set(`embeddings.create-${index}`, originalCreate);
8424
9111
  const tracer = this.tracer;
8425
- const wrapper = embeddingsWrapper2(tracer);
9112
+ const wrapper = embeddingsWrapper3(tracer);
8426
9113
  EmbeddingsClass.prototype.create = function(...args) {
8427
9114
  const original = originalCreate.bind(this);
8428
9115
  const kwargs = args[0] || {};
@@ -8591,23 +9278,23 @@ var NetraMistralAIInstrumentor = class {
8591
9278
  var mistralAIInstrumentor = new NetraMistralAIInstrumentor();
8592
9279
 
8593
9280
  // src/instrumentation/openai/version.ts
8594
- var __version__6 = "1.0.0";
9281
+ var __version__7 = "1.0.0";
8595
9282
 
8596
9283
  // src/instrumentation/openai/utils.ts
8597
- function setRequestAttributes6(span2, kwargs, requestType) {
9284
+ function setRequestAttributes7(span2, kwargs, requestType) {
8598
9285
  if (!span2.isRecording()) return;
8599
9286
  setRequestAttributes(span2, kwargs, requestType, "openai");
8600
9287
  if (kwargs.dimensions !== void 0) {
8601
9288
  span2.setAttribute("gen_ai.request.dimensions", Number(kwargs.dimensions));
8602
9289
  }
8603
9290
  }
8604
- function setResponseAttributes6(span2, response) {
9291
+ function setResponseAttributes7(span2, response) {
8605
9292
  if (!span2.isRecording()) return;
8606
9293
  setResponseAttributes(span2, response);
8607
9294
  }
8608
9295
 
8609
9296
  // src/instrumentation/openai/wrappers.ts
8610
- var SPAN_NAMES2 = {
9297
+ var SPAN_NAMES3 = {
8611
9298
  chat: "openai.chat",
8612
9299
  embedding: "openai.embedding",
8613
9300
  response: "openai.response"
@@ -8622,10 +9309,10 @@ function handleSpanError(span2, error) {
8622
9309
  span2.end();
8623
9310
  }
8624
9311
  function setSpanRequestContext(span2, kwargs, requestType) {
8625
- setRequestAttributes6(span2, kwargs, requestType);
9312
+ setRequestAttributes7(span2, kwargs, requestType);
8626
9313
  }
8627
9314
  function finalizeSpanSuccess(span2, response, startTime) {
8628
- setResponseAttributes6(span2, response);
9315
+ setResponseAttributes7(span2, response);
8629
9316
  span2.setAttribute("llm.response.duration", (Date.now() - startTime) / 1e3);
8630
9317
  span2.setStatus({ code: SpanStatusCode.OK });
8631
9318
  span2.end();
@@ -8842,7 +9529,7 @@ function executeNonStreaming(span2, kwargs, requestType, call) {
8842
9529
  }
8843
9530
  }
8844
9531
  function openAIWrapper(tracer, requestType) {
8845
- const spanName = SPAN_NAMES2[requestType];
9532
+ const spanName = SPAN_NAMES3[requestType];
8846
9533
  const spanOpts = { kind: SpanKind.CLIENT, attributes: { "llm.request.type": requestType } };
8847
9534
  return (wrapped, instance, args, kwargs) => {
8848
9535
  if (shouldSuppressInstrumentation()) {
@@ -8863,12 +9550,12 @@ function openAIWrapper(tracer, requestType) {
8863
9550
  );
8864
9551
  };
8865
9552
  }
8866
- var chatWrapper5 = (tracer) => openAIWrapper(tracer, "chat");
8867
- var embeddingsWrapper3 = (tracer) => openAIWrapper(tracer, "embedding");
9553
+ var chatWrapper6 = (tracer) => openAIWrapper(tracer, "chat");
9554
+ var embeddingsWrapper4 = (tracer) => openAIWrapper(tracer, "embedding");
8868
9555
  var responsesWrapper = (tracer) => openAIWrapper(tracer, "response");
8869
9556
 
8870
9557
  // src/instrumentation/openai/index.ts
8871
- var INSTRUMENTATION_NAME6 = "netra.instrumentation.openai";
9558
+ var INSTRUMENTATION_NAME5 = "netra.instrumentation.openai";
8872
9559
  var SUPPORTED_VERSIONS = ["openai >= 4.0.0"];
8873
9560
  var openAIClasses = [];
8874
9561
  async function resolveOpenAI() {
@@ -8895,12 +9582,12 @@ var PATCH_TARGETS = [
8895
9582
  {
8896
9583
  key: "chat.completions.create",
8897
9584
  getPrototype: (O) => O.Chat?.Completions?.prototype,
8898
- wrapperFactory: chatWrapper5
9585
+ wrapperFactory: chatWrapper6
8899
9586
  },
8900
9587
  {
8901
9588
  key: "embeddings.create",
8902
9589
  getPrototype: (O) => O.Embeddings?.prototype,
8903
- wrapperFactory: embeddingsWrapper3
9590
+ wrapperFactory: embeddingsWrapper4
8904
9591
  },
8905
9592
  {
8906
9593
  key: "responses.create",
@@ -8927,7 +9614,7 @@ var _NetraOpenAIInstrumentor = class _NetraOpenAIInstrumentor {
8927
9614
  }
8928
9615
  try {
8929
9616
  const provider = options.tracerProvider;
8930
- this.tracer = provider ? provider.getTracer(INSTRUMENTATION_NAME6, __version__6) : trace.getTracer(INSTRUMENTATION_NAME6, __version__6);
9617
+ this.tracer = provider ? provider.getTracer(INSTRUMENTATION_NAME5, __version__7) : trace.getTracer(INSTRUMENTATION_NAME5, __version__7);
8931
9618
  } catch (error) {
8932
9619
  Logger.error(`Failed to initialize tracer: ${error}`);
8933
9620
  return this;
@@ -8999,7 +9686,7 @@ var NetraOpenAIInstrumentor = _NetraOpenAIInstrumentor;
8999
9686
  var openAIInstrumentor = new NetraOpenAIInstrumentor();
9000
9687
 
9001
9688
  // src/instrumentation/openai-agents/constants.ts
9002
- var INSTRUMENTATION_NAME7 = "netra.instrumentation.openai_agents";
9689
+ var INSTRUMENTATION_NAME6 = "netra.instrumentation.openai_agents";
9003
9690
  var DEFAULT_LLM_SYSTEM = "openai";
9004
9691
  var MAX_INDEXED_MESSAGES = 128;
9005
9692
  var MAX_STRINGIFY_LENGTH = 65536;
@@ -9098,7 +9785,7 @@ function setSpanDataAttributes(otelSpan, agentSpan, systemName = DEFAULT_LLM_SYS
9098
9785
  setGenerationAttributes(otelSpan, data, systemName);
9099
9786
  break;
9100
9787
  case "response":
9101
- setResponseAttributes7(otelSpan, agentSpan, systemName);
9788
+ setResponseAttributes8(otelSpan, agentSpan, systemName);
9102
9789
  break;
9103
9790
  case "function":
9104
9791
  setFunctionAttributes(otelSpan, data);
@@ -9132,6 +9819,10 @@ function setAgentAttributes(span2, data) {
9132
9819
  span2.setAttribute(NETRA_AGENT_OUTPUT_TYPE, data.output_type);
9133
9820
  }
9134
9821
  }
9822
+ function unwrapGenerationOutput(output) {
9823
+ const isSingleWrappedResponse = Array.isArray(output) && output.length === 1 && output[0] && typeof output[0] === "object" && ("choices" in output[0] || "usage" in output[0]);
9824
+ return isSingleWrappedResponse ? output[0] : output;
9825
+ }
9135
9826
  function setGenerationAttributes(span2, data, systemName) {
9136
9827
  span2.setAttribute(SpanAttributes2.LLM_SYSTEM, systemName);
9137
9828
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "chat");
@@ -9140,42 +9831,48 @@ function setGenerationAttributes(span2, data, systemName) {
9140
9831
  span2.setAttribute(SpanAttributes2.LLM_RESPONSE_MODEL, data.model);
9141
9832
  }
9142
9833
  if (data.model_config) {
9143
- const config2 = data.model_config;
9144
- if (config2.temperature !== void 0) {
9145
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TEMPERATURE, Number(config2.temperature));
9834
+ const config = data.model_config;
9835
+ if (config.temperature !== void 0) {
9836
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TEMPERATURE, Number(config.temperature));
9146
9837
  }
9147
- if (config2.max_tokens !== void 0) {
9148
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_MAX_TOKENS, Number(config2.max_tokens));
9838
+ if (config.max_tokens !== void 0) {
9839
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_MAX_TOKENS, Number(config.max_tokens));
9149
9840
  }
9150
- if (config2.top_p !== void 0) {
9151
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(config2.top_p));
9841
+ if (config.top_p !== void 0) {
9842
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(config.top_p));
9152
9843
  }
9153
- if (config2.frequency_penalty !== void 0) {
9154
- span2.setAttribute(SpanAttributes2.LLM_FREQUENCY_PENALTY, Number(config2.frequency_penalty));
9844
+ if (config.frequency_penalty !== void 0) {
9845
+ span2.setAttribute(SpanAttributes2.LLM_FREQUENCY_PENALTY, Number(config.frequency_penalty));
9155
9846
  }
9156
- if (config2.presence_penalty !== void 0) {
9157
- span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, Number(config2.presence_penalty));
9847
+ if (config.presence_penalty !== void 0) {
9848
+ span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, Number(config.presence_penalty));
9158
9849
  }
9159
- if (config2.stop !== void 0) {
9160
- span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES, safeJsonStringify(config2.stop));
9850
+ if (config.stop !== void 0) {
9851
+ span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES, safeJsonStringify(config.stop));
9161
9852
  }
9162
- if (config2.reasoning_effort !== void 0) {
9163
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, String(config2.reasoning_effort));
9164
- } else if (config2.reasoning !== void 0) {
9165
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeJsonStringify(config2.reasoning));
9853
+ if (config.reasoning_effort !== void 0) {
9854
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, String(config.reasoning_effort));
9855
+ } else if (config.reasoning !== void 0) {
9856
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeJsonStringify(config.reasoning));
9166
9857
  }
9167
9858
  }
9859
+ const effectiveOutput = unwrapGenerationOutput(data.output);
9168
9860
  if (data.usage) {
9169
- setUsageAttributes2(span2, data.usage);
9861
+ setUsageAttributes3(span2, data.usage);
9862
+ } else if (effectiveOutput && typeof effectiveOutput === "object" && !Array.isArray(effectiveOutput)) {
9863
+ const respUsage = effectiveOutput.usage;
9864
+ if (respUsage && typeof respUsage === "object") {
9865
+ setUsageAttributes3(span2, respUsage);
9866
+ }
9170
9867
  }
9171
9868
  if (data.input !== void 0) {
9172
9869
  setIndexedPromptAttributes(span2, data.input);
9173
9870
  }
9174
- if (data.output !== void 0) {
9175
- setIndexedCompletionAttributes(span2, data.output);
9871
+ if (effectiveOutput !== void 0) {
9872
+ setIndexedCompletionAttributes(span2, effectiveOutput);
9176
9873
  }
9177
9874
  }
9178
- function setResponseAttributes7(span2, agentSpan, systemName) {
9875
+ function setResponseAttributes8(span2, agentSpan, systemName) {
9179
9876
  const data = agentSpan.spanData;
9180
9877
  span2.setAttribute(SpanAttributes2.LLM_SYSTEM, systemName);
9181
9878
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "response");
@@ -9204,7 +9901,7 @@ function setResponseAttributes7(span2, agentSpan, systemName) {
9204
9901
  }
9205
9902
  const resp = data._response;
9206
9903
  if (data.usage && !(resp && typeof resp === "object" && resp.usage)) {
9207
- setUsageAttributes2(span2, data.usage);
9904
+ setUsageAttributes3(span2, data.usage);
9208
9905
  }
9209
9906
  }
9210
9907
  function setFunctionAttributes(span2, data) {
@@ -9253,17 +9950,22 @@ function setCustomAttributes(span2, data) {
9253
9950
  span2.setAttribute(NETRA_CUSTOM_DATA, safeJsonStringify(data.data));
9254
9951
  }
9255
9952
  }
9256
- function setUsageAttributes2(span2, usage) {
9257
- if (usage.input_tokens !== void 0) {
9258
- span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, usage.input_tokens);
9953
+ function setUsageAttributes3(span2, usage) {
9954
+ const promptTokens = usage.input_tokens ?? usage.prompt_tokens;
9955
+ const completionTokens = usage.output_tokens ?? usage.completion_tokens;
9956
+ const totalTokens = usage.total_tokens;
9957
+ if (promptTokens !== void 0) {
9958
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, promptTokens);
9259
9959
  }
9260
- if (usage.output_tokens !== void 0) {
9261
- span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, usage.output_tokens);
9960
+ if (completionTokens !== void 0) {
9961
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, completionTokens);
9262
9962
  }
9263
- if (usage.input_tokens !== void 0 && usage.output_tokens !== void 0) {
9963
+ if (totalTokens !== void 0) {
9964
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, totalTokens);
9965
+ } else if (promptTokens !== void 0 && completionTokens !== void 0) {
9264
9966
  span2.setAttribute(
9265
9967
  SpanAttributes2.LLM_USAGE_TOTAL_TOKENS,
9266
- usage.input_tokens + usage.output_tokens
9968
+ promptTokens + completionTokens
9267
9969
  );
9268
9970
  }
9269
9971
  if (usage.details) {
@@ -9275,6 +9977,21 @@ function setUsageAttributes2(span2, usage) {
9275
9977
  span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, Number(details.reasoning_tokens));
9276
9978
  }
9277
9979
  }
9980
+ const inputDetails = usage.input_tokens_details ?? usage.prompt_tokens_details;
9981
+ if (inputDetails) {
9982
+ if (inputDetails.cached_tokens !== void 0) {
9983
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS, Number(inputDetails.cached_tokens));
9984
+ }
9985
+ if (inputDetails.cache_write_tokens !== void 0) {
9986
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, Number(inputDetails.cache_write_tokens));
9987
+ }
9988
+ }
9989
+ const outputDetails = usage.output_tokens_details ?? usage.completion_tokens_details;
9990
+ if (outputDetails) {
9991
+ if (outputDetails.reasoning_tokens !== void 0) {
9992
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, Number(outputDetails.reasoning_tokens));
9993
+ }
9994
+ }
9278
9995
  }
9279
9996
  function setResponseObjectAttributes(span2, response) {
9280
9997
  if (!response || typeof response !== "object") return;
@@ -9317,6 +10034,9 @@ function setResponseObjectUsageAttributes(span2, usage) {
9317
10034
  if (usage.input_tokens_details?.cached_tokens !== void 0) {
9318
10035
  span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS, usage.input_tokens_details.cached_tokens);
9319
10036
  }
10037
+ if (usage.input_tokens_details?.cache_write_tokens !== void 0) {
10038
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, usage.input_tokens_details.cache_write_tokens);
10039
+ }
9320
10040
  if (usage.output_tokens_details?.reasoning_tokens !== void 0) {
9321
10041
  span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, usage.output_tokens_details.reasoning_tokens);
9322
10042
  }
@@ -9356,8 +10076,14 @@ function setIndexedPromptAttributes(span2, input, startIndex = 0) {
9356
10076
  }
9357
10077
  }
9358
10078
  function setIndexedCompletionAttributes(span2, responseData) {
9359
- if (!responseData || typeof responseData !== "object") return;
9360
- const resp = responseData;
10079
+ if (!responseData) return;
10080
+ if (typeof responseData === "string") {
10081
+ span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.role`, "assistant");
10082
+ span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.content`, responseData);
10083
+ return;
10084
+ }
10085
+ if (typeof responseData !== "object") return;
10086
+ const resp = Array.isArray(responseData) ? { output: responseData } : responseData;
9361
10087
  if (Array.isArray(resp.output)) {
9362
10088
  let index = 0;
9363
10089
  for (const item of resp.output) {
@@ -9664,11 +10390,11 @@ try {
9664
10390
  if (pkg?.version) _version = pkg.version;
9665
10391
  } catch {
9666
10392
  }
9667
- var __version__7 = _version;
10393
+ var __version__8 = _version;
9668
10394
 
9669
10395
  // src/instrumentation/openai-agents/index.ts
9670
10396
  var cachedAgentsModule = null;
9671
- var isInstrumented6 = false;
10397
+ var isInstrumented5 = false;
9672
10398
  var activeTracer = null;
9673
10399
  var activeProcessor = null;
9674
10400
  var originalProcessors = null;
@@ -9694,7 +10420,7 @@ async function resolveAgentsModule() {
9694
10420
  }
9695
10421
  var NetraOpenAIAgentsInstrumentor = class {
9696
10422
  isInstrumented() {
9697
- return isInstrumented6;
10423
+ return isInstrumented5;
9698
10424
  }
9699
10425
  /**
9700
10426
  * Register the Netra tracing processor with the OpenAI Agents SDK.
@@ -9704,13 +10430,13 @@ var NetraOpenAIAgentsInstrumentor = class {
9704
10430
  * was registered successfully.
9705
10431
  */
9706
10432
  async instrument(options = {}) {
9707
- if (isInstrumented6) {
10433
+ if (isInstrumented5) {
9708
10434
  Logger.warn("OpenAI Agents SDK is already instrumented");
9709
10435
  return this;
9710
10436
  }
9711
10437
  try {
9712
10438
  const provider = options.tracerProvider;
9713
- activeTracer = provider ? provider.getTracer(INSTRUMENTATION_NAME7, __version__7) : trace.getTracer(INSTRUMENTATION_NAME7, __version__7);
10439
+ activeTracer = provider ? provider.getTracer(INSTRUMENTATION_NAME6, __version__8) : trace.getTracer(INSTRUMENTATION_NAME6, __version__8);
9714
10440
  } catch (error) {
9715
10441
  Logger.error(`Failed to initialize tracer for OpenAI Agents: ${error}`);
9716
10442
  return this;
@@ -9777,11 +10503,11 @@ var NetraOpenAIAgentsInstrumentor = class {
9777
10503
  activeTracer = null;
9778
10504
  return this;
9779
10505
  }
9780
- isInstrumented6 = true;
10506
+ isInstrumented5 = true;
9781
10507
  return this;
9782
10508
  }
9783
10509
  uninstrument() {
9784
- if (!isInstrumented6) {
10510
+ if (!isInstrumented5) {
9785
10511
  Logger.warn("OpenAI Agents SDK is not instrumented");
9786
10512
  return;
9787
10513
  }
@@ -9806,7 +10532,7 @@ var NetraOpenAIAgentsInstrumentor = class {
9806
10532
  didReplaceProcessors = false;
9807
10533
  activeTracer = null;
9808
10534
  cachedAgentsModule = null;
9809
- isInstrumented6 = false;
10535
+ isInstrumented5 = false;
9810
10536
  }
9811
10537
  };
9812
10538
  var openaiAgentsInstrumentor = new NetraOpenAIAgentsInstrumentor();
@@ -10065,22 +10791,22 @@ function repositoryQueryWrapper(tracer) {
10065
10791
  }
10066
10792
 
10067
10793
  // src/instrumentation/typeorm/version.ts
10068
- var __version__8 = "1.0.0";
10794
+ var __version__9 = "1.0.0";
10069
10795
  var require2 = createRequire(import.meta.url);
10070
- var INSTRUMENTATION_NAME8 = "netra.instrumentation.typeorm";
10796
+ var INSTRUMENTATION_NAME7 = "netra.instrumentation.typeorm";
10071
10797
  var originalMethods4 = /* @__PURE__ */ new Map();
10072
- var isInstrumented7 = false;
10798
+ var isInstrumented6 = false;
10073
10799
  var NetraTypeORMInstrumentor = class {
10074
10800
  constructor() {
10075
10801
  }
10076
10802
  async instrument(options = {}) {
10077
- if (isInstrumented7) {
10803
+ if (isInstrumented6) {
10078
10804
  Logger.warn("TypeORM is already instrumented");
10079
10805
  return this;
10080
10806
  }
10081
10807
  try {
10082
10808
  this.tracerProvider = options.tracerProvider;
10083
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME8, __version__8) : trace.getTracer(INSTRUMENTATION_NAME8, __version__8);
10809
+ this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME7, __version__9) : trace.getTracer(INSTRUMENTATION_NAME7, __version__9);
10084
10810
  } catch (error) {
10085
10811
  Logger.error(`Failed to initialize tracer: ${error}`);
10086
10812
  return this;
@@ -10088,11 +10814,11 @@ var NetraTypeORMInstrumentor = class {
10088
10814
  await this._instrumentDataSource();
10089
10815
  await this._instrumentEntityManager();
10090
10816
  await this._instrumentRepository();
10091
- isInstrumented7 = true;
10817
+ isInstrumented6 = true;
10092
10818
  return this;
10093
10819
  }
10094
10820
  uninstrument() {
10095
- if (!isInstrumented7) {
10821
+ if (!isInstrumented6) {
10096
10822
  Logger.warn("TypeORM is not instrumented");
10097
10823
  return;
10098
10824
  }
@@ -10103,10 +10829,10 @@ var NetraTypeORMInstrumentor = class {
10103
10829
  this._uninstrumentRepository().catch(() => {
10104
10830
  });
10105
10831
  originalMethods4.clear();
10106
- isInstrumented7 = false;
10832
+ isInstrumented6 = false;
10107
10833
  }
10108
10834
  isInstrumented() {
10109
- return isInstrumented7;
10835
+ return isInstrumented6;
10110
10836
  }
10111
10837
  async _instrumentDataSource() {
10112
10838
  if (!this.tracer) return;
@@ -10452,10 +11178,10 @@ _FilteringSpanExporter.MAX_REMEMBERED_ENTRIES = 1e4;
10452
11178
  _FilteringSpanExporter.MAX_LOCAL_PATTERN_CACHE = 100;
10453
11179
  var FilteringSpanExporter = _FilteringSpanExporter;
10454
11180
  var TrialAwareOTLPExporter = class {
10455
- constructor(config2) {
11181
+ constructor(config) {
10456
11182
  this._isShutdown = false;
10457
- this._url = config2.url;
10458
- this._headers = config2.headers || {};
11183
+ this._url = config.url;
11184
+ this._headers = config.headers || {};
10459
11185
  }
10460
11186
  export(spans, resultCallback) {
10461
11187
  if (this._isShutdown || isTrialBlocked()) {
@@ -10673,7 +11399,7 @@ function resolveRootInstrumentNames(rootInstruments, blockInstruments) {
10673
11399
  }
10674
11400
  return resolved;
10675
11401
  }
10676
- function initInstrumentations(config2, instruments, blockInstruments, rootInstruments) {
11402
+ function initInstrumentations(config, instruments, blockInstruments, rootInstruments) {
10677
11403
  const enableAll = instruments != null && instruments.has("__all__" /* ALL */);
10678
11404
  const resolvedRootNames = resolveRootInstrumentNames(
10679
11405
  rootInstruments,
@@ -10686,6 +11412,7 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
10686
11412
  mistral: false,
10687
11413
  langgraph: false,
10688
11414
  googleGenAI: false,
11415
+ googleGenerativeAI: false,
10689
11416
  anthropic: false,
10690
11417
  openAiAgents: false
10691
11418
  };
@@ -10706,9 +11433,12 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
10706
11433
  if (resolved.has("groq" /* GROQ */)) {
10707
11434
  customInstrumentModules.groq = true;
10708
11435
  }
10709
- if (resolved.has("google_genai" /* GOOGLE_GENERATIVE_AI */)) {
11436
+ if (resolved.has("google_genai" /* GOOGLE_GENAI */)) {
10710
11437
  customInstrumentModules.googleGenAI = true;
10711
11438
  }
11439
+ if (resolved.has("google_generative_ai" /* GOOGLE_GENERATIVE_AI */)) {
11440
+ customInstrumentModules.googleGenerativeAI = true;
11441
+ }
10712
11442
  if (resolved.has("vertexai" /* VERTEX_AI */) && isPackageInstalled("@google-cloud/vertexai")) {
10713
11443
  instrumentModules.google_vertexai = require3("@google-cloud/vertexai");
10714
11444
  }
@@ -10745,7 +11475,8 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
10745
11475
  if (blockAll || blockInstruments.has("groq" /* GROQ */)) customInstrumentModules.groq = false;
10746
11476
  if (blockAll || blockInstruments.has("mistral_ai" /* MISTRAL */)) customInstrumentModules.mistral = false;
10747
11477
  if (blockAll || blockInstruments.has("langgraph" /* LANGGRAPH */)) customInstrumentModules.langgraph = false;
10748
- if (blockAll || blockInstruments.has("google_genai" /* GOOGLE_GENERATIVE_AI */)) customInstrumentModules.googleGenAI = false;
11478
+ if (blockAll || blockInstruments.has("google_genai" /* GOOGLE_GENAI */)) customInstrumentModules.googleGenAI = false;
11479
+ if (blockAll || blockInstruments.has("google_generative_ai" /* GOOGLE_GENERATIVE_AI */)) customInstrumentModules.googleGenerativeAI = false;
10749
11480
  if (blockAll || blockInstruments.has("anthropic" /* ANTHROPIC */)) customInstrumentModules.anthropic = false;
10750
11481
  if (blockAll || blockInstruments.has("openai_agents" /* OPENAI_AGENTS */)) customInstrumentModules.openAiAgents = false;
10751
11482
  if (blockAll || blockInstruments.has("vertexai" /* VERTEX_AI */)) instrumentModules.google_vertexai = false;
@@ -10756,34 +11487,34 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
10756
11487
  if (blockAll || blockInstruments.has("chromadb" /* CHROMADB */)) instrumentModules.chromadb = false;
10757
11488
  if (blockAll || blockInstruments.has("together" /* TOGETHER */)) instrumentModules.together = false;
10758
11489
  }
10759
- config2.setTraceloopEnv();
11490
+ config.setTraceloopEnv();
10760
11491
  Logger.debug("Netra SDK Configuration:");
10761
- Logger.debug(` App Name: ${config2.appName}`);
10762
- Logger.debug(` OTLP Endpoint: ${config2.otlpEndpoint || "(default - localhost:3002)"}`);
10763
- Logger.debug(` API Key: ${config2.apiKey ? "***" + config2.apiKey.slice(-4) : "(not set)"}`);
10764
- Logger.debug(` Trace Content: ${config2.traceContent}`);
10765
- Logger.debug(` Enable Scrubbing: ${config2.enableScrubbing}`);
11492
+ Logger.debug(` App Name: ${config.appName}`);
11493
+ Logger.debug(` OTLP Endpoint: ${config.otlpEndpoint || "(default - localhost:3002)"}`);
11494
+ Logger.debug(` API Key: ${config.apiKey ? "***" + config.apiKey.slice(-4) : "(not set)"}`);
11495
+ Logger.debug(` Trace Content: ${config.traceContent}`);
11496
+ Logger.debug(` Enable Scrubbing: ${config.enableScrubbing}`);
10766
11497
  const traceloopOptions = {
10767
- appName: config2.appName,
10768
- apiKey: config2.apiKey,
10769
- baseUrl: config2.otlpEndpoint,
10770
- disableBatch: config2.disableBatch,
10771
- traceContent: config2.traceContent,
10772
- headers: config2.headers,
11498
+ appName: config.appName,
11499
+ apiKey: config.apiKey,
11500
+ baseUrl: config.otlpEndpoint,
11501
+ disableBatch: config.disableBatch,
11502
+ traceContent: config.traceContent,
11503
+ headers: config.headers,
10773
11504
  instrumentModules,
10774
- silenceInitializationMessage: !config2.debugMode
11505
+ silenceInitializationMessage: !config.debugMode
10775
11506
  };
10776
11507
  let exporter;
10777
11508
  if (!traceloopOptions.baseUrl || traceloopOptions.baseUrl == void 0) {
10778
11509
  exporter = new ConsoleSpanExporter();
10779
11510
  } else {
10780
- const formattedEndpoint = config2.formatOtlpEndpoint();
11511
+ const formattedEndpoint = config.formatOtlpEndpoint();
10781
11512
  exporter = new TrialAwareOTLPExporter({
10782
11513
  url: formattedEndpoint,
10783
- headers: config2.headers
11514
+ headers: config.headers
10784
11515
  });
10785
11516
  }
10786
- const globalBlockedPatterns = config2.blockedSpans ?? [];
11517
+ const globalBlockedPatterns = config.blockedSpans ?? [];
10787
11518
  const localFilteringSpanProcessor = new LocalFilteringSpanProcessor(globalBlockedPatterns);
10788
11519
  const originalExporter = exporter;
10789
11520
  try {
@@ -10805,23 +11536,23 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
10805
11536
  const tracerProvider = trace.getTracerProvider();
10806
11537
  const effectiveProvider = addCustomSpanProcessors(
10807
11538
  tracerProvider,
10808
- config2,
11539
+ config,
10809
11540
  resolvedRootNames
10810
11541
  );
10811
11542
  instrumentationsReady = initCustomInstrumentationsAsync(
10812
- config2,
11543
+ config,
10813
11544
  tracerProvider,
10814
11545
  customInstrumentModules,
10815
11546
  blockInstruments
10816
11547
  );
10817
- initOpenTelemetryInstrumentations(config2, resolved, blockInstruments);
11548
+ initOpenTelemetryInstrumentations(config, resolved, blockInstruments);
10818
11549
  return effectiveProvider;
10819
11550
  }
10820
11551
  function isBlocked(instrument, blockInstruments) {
10821
11552
  if (!blockInstruments || blockInstruments.size === 0) return false;
10822
11553
  return blockInstruments.has("__all__" /* ALL */) || blockInstruments.has(instrument);
10823
11554
  }
10824
- async function initCustomInstrumentationsAsync(config2, tracerProvider, customInstrumentModules, blockInstruments) {
11555
+ async function initCustomInstrumentationsAsync(config, tracerProvider, customInstrumentModules, blockInstruments) {
10825
11556
  if (customInstrumentModules.mistral) {
10826
11557
  try {
10827
11558
  await mistralAIInstrumentor.instrumentAsync({ tracerProvider });
@@ -10848,10 +11579,21 @@ async function initCustomInstrumentationsAsync(config2, tracerProvider, customIn
10848
11579
  }
10849
11580
  if (customInstrumentModules.googleGenAI) {
10850
11581
  try {
10851
- await googleGenerativeAIInstrumentor.instrumentAsync({ tracerProvider });
11582
+ await googleGenAIInstrumentor.instrument({ tracerProvider });
10852
11583
  Logger.debug("Custom Google GenAI instrumentation enabled");
10853
11584
  } catch (e) {
10854
- Logger.debug("Failed to initialize custom Google GenAI instrumentation:", e);
11585
+ Logger.debug(
11586
+ "Failed to initialize custom Google GenAI instrumentation:",
11587
+ e
11588
+ );
11589
+ }
11590
+ }
11591
+ if (customInstrumentModules.googleGenerativeAI) {
11592
+ try {
11593
+ await googleGenerativeAIInstrumentor.instrument({ tracerProvider });
11594
+ Logger.debug("Custom Google Generative AI instrumentation enabled");
11595
+ } catch (e) {
11596
+ Logger.debug("Failed to initialize custom Google Generative AI instrumentation:", e);
10855
11597
  }
10856
11598
  }
10857
11599
  if (customInstrumentModules.langgraph) {
@@ -10879,20 +11621,20 @@ async function initCustomInstrumentationsAsync(config2, tracerProvider, customIn
10879
11621
  }
10880
11622
  }
10881
11623
  }
10882
- function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments) {
11624
+ function initOpenTelemetryInstrumentations(config, resolved, blockInstruments) {
10883
11625
  let netraHost = "";
10884
11626
  try {
10885
- if (config2.otlpEndpoint) {
10886
- netraHost = new URL(config2.otlpEndpoint).host;
11627
+ if (config.otlpEndpoint) {
11628
+ netraHost = new URL(config.otlpEndpoint).host;
10887
11629
  }
10888
11630
  } catch {
10889
- Logger.debug(`OTEL_NODE_EXCLUDED_URLS: malformed otlpEndpoint '${config2.otlpEndpoint}', skipping host-based exclusion`);
11631
+ Logger.debug(`OTEL_NODE_EXCLUDED_URLS: malformed otlpEndpoint '${config.otlpEndpoint}', skipping host-based exclusion`);
10890
11632
  }
10891
11633
  const excludeRegexes = (process.env.OTEL_NODE_EXCLUDED_URLS || "").split(",").map((s) => s.trim()).filter(Boolean).map((pattern) => {
10892
11634
  try {
10893
11635
  return new RegExp(pattern);
10894
11636
  } catch {
10895
- if (config2.debugMode) {
11637
+ if (config.debugMode) {
10896
11638
  Logger.debug(
10897
11639
  `Invalid OTEL_NODE_EXCLUDED_URLS pattern skipped: ${pattern}`
10898
11640
  );
@@ -10915,7 +11657,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
10915
11657
  }
10916
11658
  });
10917
11659
  registerInstrumentations({ instrumentations: [_httpInstrumentation] });
10918
- if (config2.debugMode) {
11660
+ if (config.debugMode) {
10919
11661
  Logger.debug("HTTP instrumentation enabled");
10920
11662
  }
10921
11663
  } catch (e) {
@@ -10934,11 +11676,11 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
10934
11676
  }
10935
11677
  });
10936
11678
  registerInstrumentations({ instrumentations: [_undiciInstrumentation] });
10937
- if (config2.debugMode) {
11679
+ if (config.debugMode) {
10938
11680
  Logger.debug("Undici/fetch instrumentation enabled");
10939
11681
  }
10940
11682
  } catch (e) {
10941
- if (config2.debugMode) {
11683
+ if (config.debugMode) {
10942
11684
  Logger.debug("Undici/fetch instrumentation not available:", e);
10943
11685
  }
10944
11686
  }
@@ -10962,7 +11704,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
10962
11704
  const { ExpressInstrumentation } = require3("@opentelemetry/instrumentation-express");
10963
11705
  const { registerInstrumentations } = require3("@opentelemetry/instrumentation");
10964
11706
  registerInstrumentations({ instrumentations: [new ExpressInstrumentation()] });
10965
- if (config2.debugMode) {
11707
+ if (config.debugMode) {
10966
11708
  Logger.debug("Express instrumentation enabled");
10967
11709
  }
10968
11710
  } catch (e) {
@@ -10970,7 +11712,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
10970
11712
  }
10971
11713
  }
10972
11714
  }
10973
- function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
11715
+ function addCustomSpanProcessors(tracerProvider, config, rootInstrumentNames) {
10974
11716
  try {
10975
11717
  let provider = null;
10976
11718
  const providerAny = tracerProvider;
@@ -11016,7 +11758,7 @@ function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
11016
11758
  }
11017
11759
  const instrumentationProcessor = new InstrumentationSpanProcessor();
11018
11760
  provider.addSpanProcessor(instrumentationProcessor);
11019
- const sessionProcessor = new SessionSpanProcessor(config2.environment);
11761
+ const sessionProcessor = new SessionSpanProcessor(config.environment);
11020
11762
  provider.addSpanProcessor(sessionProcessor);
11021
11763
  const spanIOProcessor = new SpanIOProcessor();
11022
11764
  provider.addSpanProcessor(spanIOProcessor);
@@ -11024,7 +11766,7 @@ function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
11024
11766
  provider.addSpanProcessor(llmTraceProcessor);
11025
11767
  const rootSpanProcessor = new RootSpanProcessor();
11026
11768
  provider.addSpanProcessor(rootSpanProcessor);
11027
- if (config2.enableScrubbing) {
11769
+ if (config.enableScrubbing) {
11028
11770
  const scrubbingProcessor = new ScrubbingSpanProcessor();
11029
11771
  provider.addSpanProcessor(scrubbingProcessor);
11030
11772
  }
@@ -11073,13 +11815,21 @@ async function uninstrumentAll() {
11073
11815
  Logger.debug("Failed to uninstrument Anthropic:", e);
11074
11816
  }
11075
11817
  try {
11076
- if (googleGenerativeAIInstrumentor.isInstrumented()) {
11077
- googleGenerativeAIInstrumentor.uninstrument();
11818
+ if (googleGenAIInstrumentor.isInstrumented()) {
11819
+ googleGenAIInstrumentor.uninstrument();
11078
11820
  Logger.debug("Custom Google GenAI instrumentation disabled");
11079
11821
  }
11080
11822
  } catch (e) {
11081
11823
  Logger.debug("Failed to uninstrument Google GenAI:", e);
11082
11824
  }
11825
+ try {
11826
+ if (googleGenerativeAIInstrumentor.isInstrumented()) {
11827
+ googleGenerativeAIInstrumentor.uninstrument();
11828
+ Logger.debug("Custom Google Generative AI instrumentation disabled");
11829
+ }
11830
+ } catch (e) {
11831
+ Logger.debug("Failed to uninstrument Google Generative AI:", e);
11832
+ }
11083
11833
  try {
11084
11834
  if (langgraphInstrumentor.isInstrumented()) {
11085
11835
  await langgraphInstrumentor.uninstrument();
@@ -11129,17 +11879,17 @@ var BaseTask = class {
11129
11879
  };
11130
11880
 
11131
11881
  // src/simulation/utils.ts
11132
- var LOG_PREFIX = "netra.simulation";
11882
+ var LOG_PREFIX4 = "netra.simulation";
11133
11883
  var DEFAULT_FILE_DOWNLOAD_TIMEOUT_S = 30;
11134
11884
  var MAX_FILE_DOWNLOAD_WORKERS = 8;
11135
11885
  var _cachedFileDownloadTimeoutMs = null;
11136
11886
  function validateSimulationInputs(datasetId, task2) {
11137
11887
  if (!datasetId) {
11138
- Logger.error(`${LOG_PREFIX}: dataset_id is required`);
11888
+ Logger.error(`${LOG_PREFIX4}: dataset_id is required`);
11139
11889
  return false;
11140
11890
  }
11141
11891
  if (!(task2 instanceof BaseTask)) {
11142
- Logger.error(`${LOG_PREFIX}: task must be a BaseTask instance`);
11892
+ Logger.error(`${LOG_PREFIX4}: task must be a BaseTask instance`);
11143
11893
  return false;
11144
11894
  }
11145
11895
  return true;
@@ -11156,7 +11906,7 @@ function _getFileDownloadTimeout() {
11156
11906
  return _cachedFileDownloadTimeoutMs;
11157
11907
  }
11158
11908
  Logger.warn(
11159
- `${LOG_PREFIX}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
11909
+ `${LOG_PREFIX4}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
11160
11910
  );
11161
11911
  }
11162
11912
  _cachedFileDownloadTimeoutMs = DEFAULT_FILE_DOWNLOAD_TIMEOUT_S * 1e3;
@@ -11185,7 +11935,7 @@ async function _downloadSingleFile(fileData, timeoutMs, signal) {
11185
11935
  const status = axios.isAxiosError(error) ? error.response?.status : void 0;
11186
11936
  const reason = status ? `HTTP ${status}` : error instanceof Error ? error.message : String(error);
11187
11937
  Logger.error(
11188
- `${LOG_PREFIX}: Failed to download file '${fileData.fileName}': ${reason}`
11938
+ `${LOG_PREFIX4}: Failed to download file '${fileData.fileName}': ${reason}`
11189
11939
  );
11190
11940
  throw new Error(
11191
11941
  `Failed to download file '${fileData.fileName}': ${reason}`
@@ -11202,7 +11952,7 @@ function parseFiles(rawFiles) {
11202
11952
  const downloadUrl = entry.downloadUrl || "";
11203
11953
  if (!fileName || !downloadUrl) {
11204
11954
  Logger.warn(
11205
- `${LOG_PREFIX}: Skipping malformed file attachment (missing fileName or downloadUrl)`
11955
+ `${LOG_PREFIX4}: Skipping malformed file attachment (missing fileName or downloadUrl)`
11206
11956
  );
11207
11957
  continue;
11208
11958
  }
@@ -11246,24 +11996,24 @@ async function executeTask2(task2, message, sessionId, rawFiles) {
11246
11996
  }
11247
11997
 
11248
11998
  // src/simulation/client.ts
11249
- var LOG_PREFIX2 = "netra.simulation";
11999
+ var LOG_PREFIX5 = "netra.simulation";
11250
12000
  var DEFAULT_TIMEOUT = 1e4;
11251
12001
  var SimulationHttpClient = class {
11252
- constructor(config2) {
12002
+ constructor(config) {
11253
12003
  this.client = null;
11254
- this.client = this._createClient(config2);
12004
+ this.client = this._createClient(config);
11255
12005
  }
11256
12006
  /**
11257
12007
  * Create and configure the HTTP client.
11258
12008
  */
11259
- _createClient(config2) {
11260
- const endpoint = (config2.otlpEndpoint || "").trim();
12009
+ _createClient(config) {
12010
+ const endpoint = (config.otlpEndpoint || "").trim();
11261
12011
  if (!endpoint) {
11262
- Logger.error(`${LOG_PREFIX2}: NETRA_OTLP_ENDPOINT is required`);
12012
+ Logger.error(`${LOG_PREFIX5}: NETRA_OTLP_ENDPOINT is required`);
11263
12013
  return null;
11264
12014
  }
11265
12015
  const baseURL = this._resolveBaseUrl(endpoint);
11266
- const headers = this._buildHeaders(config2);
12016
+ const headers = this._buildHeaders(config);
11267
12017
  const timeout = this._getTimeout();
11268
12018
  try {
11269
12019
  const instance = axios.create({
@@ -11272,16 +12022,16 @@ var SimulationHttpClient = class {
11272
12022
  timeout
11273
12023
  });
11274
12024
  instance.interceptors.request.use(
11275
- (config3) => {
12025
+ (config2) => {
11276
12026
  const traceHeaders = injectTraceContextHeaders({});
11277
- Object.assign(config3.headers, traceHeaders);
11278
- return config3;
12027
+ Object.assign(config2.headers, traceHeaders);
12028
+ return config2;
11279
12029
  },
11280
12030
  (error) => Promise.reject(error)
11281
12031
  );
11282
12032
  return instance;
11283
12033
  } catch (error) {
11284
- Logger.error(`${LOG_PREFIX2}: Failed to create HTTP client:`, error);
12034
+ Logger.error(`${LOG_PREFIX5}: Failed to create HTTP client:`, error);
11285
12035
  return null;
11286
12036
  }
11287
12037
  }
@@ -11298,10 +12048,10 @@ var SimulationHttpClient = class {
11298
12048
  /**
11299
12049
  * Build request headers from configuration.
11300
12050
  */
11301
- _buildHeaders(config2) {
11302
- const headers = { ...config2.headers };
11303
- if (config2.apiKey) {
11304
- headers["x-api-key"] = config2.apiKey;
12051
+ _buildHeaders(config) {
12052
+ const headers = { ...config.headers };
12053
+ if (config.apiKey) {
12054
+ headers["x-api-key"] = config.apiKey;
11305
12055
  }
11306
12056
  return headers;
11307
12057
  }
@@ -11316,7 +12066,7 @@ var SimulationHttpClient = class {
11316
12066
  const timeout = parseFloat(timeoutStr);
11317
12067
  if (isNaN(timeout)) {
11318
12068
  Logger.warn(
11319
- `${LOG_PREFIX2}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
12069
+ `${LOG_PREFIX5}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
11320
12070
  );
11321
12071
  return DEFAULT_TIMEOUT;
11322
12072
  }
@@ -11325,9 +12075,9 @@ var SimulationHttpClient = class {
11325
12075
  /**
11326
12076
  * Create a new simulation run for the specified dataset.
11327
12077
  */
11328
- async createRun(name, datasetId, context16) {
12078
+ async createRun(name, datasetId, context17) {
11329
12079
  if (!this.client) {
11330
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
12080
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
11331
12081
  return null;
11332
12082
  }
11333
12083
  try {
@@ -11335,14 +12085,14 @@ var SimulationHttpClient = class {
11335
12085
  const payload = {
11336
12086
  name,
11337
12087
  datasetId,
11338
- context: context16 || {}
12088
+ context: context17 || {}
11339
12089
  };
11340
12090
  const response = await this.client.post(url, payload);
11341
12091
  const data = response.data;
11342
12092
  const responseData = data.data || {};
11343
12093
  const userMessages = responseData.userMessages || [];
11344
12094
  if (userMessages.length === 0) {
11345
- Logger.warn(`${LOG_PREFIX2}: No user messages returned from create_run`);
12095
+ Logger.warn(`${LOG_PREFIX5}: No user messages returned from create_run`);
11346
12096
  return null;
11347
12097
  }
11348
12098
  const runId = responseData.id || "";
@@ -11360,7 +12110,7 @@ var SimulationHttpClient = class {
11360
12110
  };
11361
12111
  } catch (error) {
11362
12112
  const errorMsg = this._extractErrorMessage(error);
11363
- Logger.error(`${LOG_PREFIX2}: Failed to create simulation run:`, errorMsg);
12113
+ Logger.error(`${LOG_PREFIX5}: Failed to create simulation run:`, errorMsg);
11364
12114
  return null;
11365
12115
  }
11366
12116
  }
@@ -11369,7 +12119,7 @@ var SimulationHttpClient = class {
11369
12119
  */
11370
12120
  async triggerConversation(message, turnId, sessionId, traceId) {
11371
12121
  if (!this.client) {
11372
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
12122
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
11373
12123
  return null;
11374
12124
  }
11375
12125
  try {
@@ -11392,7 +12142,7 @@ var SimulationHttpClient = class {
11392
12142
  }
11393
12143
  const userMessages = responseData.userMessages || [];
11394
12144
  if (userMessages.length === 0) {
11395
- Logger.warn(`${LOG_PREFIX2}: No user messages in continue response`);
12145
+ Logger.warn(`${LOG_PREFIX5}: No user messages in continue response`);
11396
12146
  return null;
11397
12147
  }
11398
12148
  const nextMsg = userMessages[0];
@@ -11405,7 +12155,7 @@ var SimulationHttpClient = class {
11405
12155
  };
11406
12156
  } catch (error) {
11407
12157
  const errorMsg = this._extractErrorMessage(error);
11408
- Logger.error(`${LOG_PREFIX2}: Failed to trigger conversation:`, errorMsg);
12158
+ Logger.error(`${LOG_PREFIX5}: Failed to trigger conversation:`, errorMsg);
11409
12159
  return null;
11410
12160
  }
11411
12161
  }
@@ -11414,17 +12164,17 @@ var SimulationHttpClient = class {
11414
12164
  */
11415
12165
  async reportFailure(runId, runItemId, error) {
11416
12166
  if (!this.client) {
11417
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
12167
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
11418
12168
  return;
11419
12169
  }
11420
12170
  try {
11421
12171
  const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
11422
12172
  const payload = { status: "failed", failureReason: error };
11423
12173
  await this.client.patch(url, payload);
11424
- Logger.info(`${LOG_PREFIX2}: Reported failure - ${error}`);
12174
+ Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
11425
12175
  } catch (err) {
11426
12176
  const errorMsg = this._extractErrorMessage(err);
11427
- Logger.error(`${LOG_PREFIX2}: Failed to report failure:`, errorMsg);
12177
+ Logger.error(`${LOG_PREFIX5}: Failed to report failure:`, errorMsg);
11428
12178
  }
11429
12179
  }
11430
12180
  /**
@@ -11433,7 +12183,7 @@ var SimulationHttpClient = class {
11433
12183
  async postRunStatus(runId, status) {
11434
12184
  if (!this.client) {
11435
12185
  Logger.error(
11436
- `${LOG_PREFIX2}: Client not initialized; cannot post run status`
12186
+ `${LOG_PREFIX5}: Client not initialized; cannot post run status`
11437
12187
  );
11438
12188
  return { success: false };
11439
12189
  }
@@ -11443,14 +12193,14 @@ var SimulationHttpClient = class {
11443
12193
  const response = await this.client.post(url, payload);
11444
12194
  const data = response.data;
11445
12195
  if (data && typeof data === "object" && "data" in data) {
11446
- Logger.info(`${LOG_PREFIX2}: Completed test run successfully`);
12196
+ Logger.info(`${LOG_PREFIX5}: Completed test run successfully`);
11447
12197
  return data.data || {};
11448
12198
  }
11449
12199
  return data;
11450
12200
  } catch (error) {
11451
12201
  const errorMsg = this._extractErrorMessage(error);
11452
12202
  Logger.error(
11453
- `${LOG_PREFIX2}: Failed to post run status for run '${runId}':`,
12203
+ `${LOG_PREFIX5}: Failed to post run status for run '${runId}':`,
11454
12204
  errorMsg
11455
12205
  );
11456
12206
  return { success: false };
@@ -11475,12 +12225,12 @@ var SimulationHttpClient = class {
11475
12225
  };
11476
12226
 
11477
12227
  // src/simulation/api.ts
11478
- var LOG_PREFIX3 = "netra.simulation";
12228
+ var LOG_PREFIX6 = "netra.simulation";
11479
12229
  var SPAN_NAME = "Netra.Simulation.TestRun";
11480
12230
  var Simulation = class {
11481
- constructor(config2) {
11482
- this._config = config2;
11483
- this._client = new SimulationHttpClient(config2);
12231
+ constructor(config) {
12232
+ this._config = config;
12233
+ this._client = new SimulationHttpClient(config);
11484
12234
  }
11485
12235
  /**
11486
12236
  * Run a multi-turn conversation simulation.
@@ -11493,20 +12243,20 @@ var Simulation = class {
11493
12243
  name,
11494
12244
  datasetId,
11495
12245
  task: task2,
11496
- context: context16,
12246
+ context: context17,
11497
12247
  maxConcurrency = 5
11498
12248
  } = options;
11499
12249
  if (!validateSimulationInputs(datasetId, task2)) {
11500
12250
  return null;
11501
12251
  }
11502
12252
  const startTime = Date.now();
11503
- const runResult = await this._client.createRun(name, datasetId, context16);
12253
+ const runResult = await this._client.createRun(name, datasetId, context17);
11504
12254
  if (!runResult) {
11505
12255
  return null;
11506
12256
  }
11507
12257
  const { runId, simulationItems } = runResult;
11508
12258
  if (!simulationItems || simulationItems.length === 0) {
11509
- Logger.error(`${LOG_PREFIX3}: No items returned from create_run`);
12259
+ Logger.error(`${LOG_PREFIX6}: No items returned from create_run`);
11510
12260
  return null;
11511
12261
  }
11512
12262
  let interrupted = false;
@@ -11542,7 +12292,7 @@ var Simulation = class {
11542
12292
  proc.once("unhandledRejection", handleRejection);
11543
12293
  }
11544
12294
  Logger.info(
11545
- `${LOG_PREFIX3}: Starting simulation with ${simulationItems.length} items`
12295
+ `${LOG_PREFIX6}: Starting simulation with ${simulationItems.length} items`
11546
12296
  );
11547
12297
  try {
11548
12298
  const result = await this._runSimulationAsync(
@@ -11553,11 +12303,11 @@ var Simulation = class {
11553
12303
  );
11554
12304
  const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
11555
12305
  Logger.info(
11556
- `${LOG_PREFIX3}: Simulation completed in ${elapsedTime} seconds`
12306
+ `${LOG_PREFIX6}: Simulation completed in ${elapsedTime} seconds`
11557
12307
  );
11558
12308
  return result;
11559
12309
  } catch (error) {
11560
- Logger.error(`${LOG_PREFIX3}: Run simulation failed`);
12310
+ Logger.error(`${LOG_PREFIX6}: Run simulation failed`);
11561
12311
  await this._client.postRunStatus(runId, "failed");
11562
12312
  throw error;
11563
12313
  } finally {
@@ -11591,14 +12341,14 @@ var Simulation = class {
11591
12341
  }
11592
12342
  processedCount++;
11593
12343
  Logger.info(
11594
- `${LOG_PREFIX3}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
12344
+ `${LOG_PREFIX6}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
11595
12345
  );
11596
12346
  return result;
11597
12347
  })
11598
12348
  );
11599
12349
  await Promise.all(promises);
11600
12350
  Logger.info(
11601
- `${LOG_PREFIX3}: Completed=${results.completed.length}, Failed=${results.failed.length}`
12351
+ `${LOG_PREFIX6}: Completed=${results.completed.length}, Failed=${results.failed.length}`
11602
12352
  );
11603
12353
  await this._client.postRunStatus(runId, "completed");
11604
12354
  return results;
@@ -11613,7 +12363,7 @@ var Simulation = class {
11613
12363
  let sessionId = null;
11614
12364
  let rawFiles = initialFiles ?? [];
11615
12365
  while (true) {
11616
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX3);
12366
+ const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX6);
11617
12367
  span2.start();
11618
12368
  try {
11619
12369
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -11642,7 +12392,7 @@ var Simulation = class {
11642
12392
  }
11643
12393
  if (response.decision === "stop") {
11644
12394
  Logger.info(
11645
- `${LOG_PREFIX3}: Completed run_item_id=${runItemId} reason=${response.reason}`
12395
+ `${LOG_PREFIX6}: Completed run_item_id=${runItemId} reason=${response.reason}`
11646
12396
  );
11647
12397
  return {
11648
12398
  runItemId,
@@ -11656,7 +12406,7 @@ var Simulation = class {
11656
12406
  } catch (error) {
11657
12407
  const errorMsg = error instanceof Error ? error.message : String(error);
11658
12408
  Logger.error(
11659
- `${LOG_PREFIX3}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
12409
+ `${LOG_PREFIX6}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
11660
12410
  );
11661
12411
  await this._client.reportFailure(runId, runItemId, errorMsg);
11662
12412
  return {
@@ -11671,7 +12421,7 @@ var Simulation = class {
11671
12421
  }
11672
12422
  }
11673
12423
  };
11674
- var Tracer17 = class {
12424
+ var Tracer18 = class {
11675
12425
  constructor(cfg, effectiveProvider) {
11676
12426
  if (effectiveProvider && typeof effectiveProvider.getTracer === "function") {
11677
12427
  this.tracer = effectiveProvider.getTracer(Config.LIBRARY_NAME, Config.LIBRARY_VERSION);
@@ -11698,7 +12448,7 @@ function addInputAttributes(span2, args, entityType) {
11698
12448
  }
11699
12449
  }
11700
12450
  function addOutputAttributes(span2, result) {
11701
- if (spanHasOutput(span2)) return;
12451
+ if (result === void 0 || spanHasOutput(span2)) return;
11702
12452
  try {
11703
12453
  span2.setAttribute("output", serializeValue(result, Config.ATTRIBUTE_MAX_LEN));
11704
12454
  } catch (e) {
@@ -11869,21 +12619,21 @@ var Netra = class {
11869
12619
  static isInitialized() {
11870
12620
  return this._initialized;
11871
12621
  }
11872
- static async init(config2 = {}) {
12622
+ static async init(config = {}) {
11873
12623
  if (this._initialized) {
11874
12624
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
11875
12625
  return;
11876
12626
  }
11877
- const cfg = new Config(config2);
12627
+ const cfg = new Config(config);
11878
12628
  this._config = cfg;
11879
12629
  Logger.setDebugMode(cfg.debugMode);
11880
12630
  const effectiveProvider = initInstrumentations(
11881
12631
  cfg,
11882
- config2.instruments,
11883
- config2.blockInstruments,
11884
- config2.rootInstruments
12632
+ config.instruments,
12633
+ config.blockInstruments,
12634
+ config.rootInstruments
11885
12635
  );
11886
- const tracer = new Tracer17(cfg, effectiveProvider);
12636
+ const tracer = new Tracer18(cfg, effectiveProvider);
11887
12637
  this._tracer = tracer.tracer;
11888
12638
  try {
11889
12639
  this.usage = new Usage(cfg);